IVDescriptors.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. //===- llvm/Analysis/IVDescriptors.h - IndVar Descriptors -------*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file "describes" induction and recurrence variables.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #ifndef LLVM_ANALYSIS_IVDESCRIPTORS_H
  13. #define LLVM_ANALYSIS_IVDESCRIPTORS_H
  14. #include "llvm/ADT/DenseMap.h"
  15. #include "llvm/ADT/SmallPtrSet.h"
  16. #include "llvm/ADT/SmallVector.h"
  17. #include "llvm/ADT/StringRef.h"
  18. #include "llvm/IR/InstrTypes.h"
  19. #include "llvm/IR/Instruction.h"
  20. #include "llvm/IR/Operator.h"
  21. #include "llvm/IR/ValueHandle.h"
  22. #include "llvm/Support/Casting.h"
  23. namespace llvm {
  24. class DemandedBits;
  25. class AssumptionCache;
  26. class Loop;
  27. class PredicatedScalarEvolution;
  28. class ScalarEvolution;
  29. class SCEV;
  30. class DominatorTree;
  31. /// These are the kinds of recurrences that we support.
  32. enum class RecurKind {
  33. None, ///< Not a recurrence.
  34. Add, ///< Sum of integers.
  35. Mul, ///< Product of integers.
  36. Or, ///< Bitwise or logical OR of integers.
  37. And, ///< Bitwise or logical AND of integers.
  38. Xor, ///< Bitwise or logical XOR of integers.
  39. SMin, ///< Signed integer min implemented in terms of select(cmp()).
  40. SMax, ///< Signed integer max implemented in terms of select(cmp()).
  41. UMin, ///< Unisgned integer min implemented in terms of select(cmp()).
  42. UMax, ///< Unsigned integer max implemented in terms of select(cmp()).
  43. FAdd, ///< Sum of floats.
  44. FMul, ///< Product of floats.
  45. FMin, ///< FP min implemented in terms of select(cmp()).
  46. FMax ///< FP max implemented in terms of select(cmp()).
  47. };
  48. /// The RecurrenceDescriptor is used to identify recurrences variables in a
  49. /// loop. Reduction is a special case of recurrence that has uses of the
  50. /// recurrence variable outside the loop. The method isReductionPHI identifies
  51. /// reductions that are basic recurrences.
  52. ///
  53. /// Basic recurrences are defined as the summation, product, OR, AND, XOR, min,
  54. /// or max of a set of terms. For example: for(i=0; i<n; i++) { total +=
  55. /// array[i]; } is a summation of array elements. Basic recurrences are a
  56. /// special case of chains of recurrences (CR). See ScalarEvolution for CR
  57. /// references.
  58. /// This struct holds information about recurrence variables.
  59. class RecurrenceDescriptor {
  60. public:
  61. RecurrenceDescriptor() = default;
  62. RecurrenceDescriptor(Value *Start, Instruction *Exit, RecurKind K,
  63. FastMathFlags FMF, Instruction *ExactFP, Type *RT,
  64. bool Signed, bool Ordered,
  65. SmallPtrSetImpl<Instruction *> &CI)
  66. : StartValue(Start), LoopExitInstr(Exit), Kind(K), FMF(FMF),
  67. ExactFPMathInst(ExactFP), RecurrenceType(RT), IsSigned(Signed),
  68. IsOrdered(Ordered) {
  69. CastInsts.insert(CI.begin(), CI.end());
  70. }
  71. /// This POD struct holds information about a potential recurrence operation.
  72. class InstDesc {
  73. public:
  74. InstDesc(bool IsRecur, Instruction *I, Instruction *ExactFP = nullptr)
  75. : IsRecurrence(IsRecur), PatternLastInst(I),
  76. RecKind(RecurKind::None), ExactFPMathInst(ExactFP) {}
  77. InstDesc(Instruction *I, RecurKind K, Instruction *ExactFP = nullptr)
  78. : IsRecurrence(true), PatternLastInst(I), RecKind(K),
  79. ExactFPMathInst(ExactFP) {}
  80. bool isRecurrence() const { return IsRecurrence; }
  81. bool needsExactFPMath() const { return ExactFPMathInst != nullptr; }
  82. Instruction *getExactFPMathInst() const { return ExactFPMathInst; }
  83. RecurKind getRecKind() const { return RecKind; }
  84. Instruction *getPatternInst() const { return PatternLastInst; }
  85. private:
  86. // Is this instruction a recurrence candidate.
  87. bool IsRecurrence;
  88. // The last instruction in a min/max pattern (select of the select(icmp())
  89. // pattern), or the current recurrence instruction otherwise.
  90. Instruction *PatternLastInst;
  91. // If this is a min/max pattern.
  92. RecurKind RecKind;
  93. // Recurrence does not allow floating-point reassociation.
  94. Instruction *ExactFPMathInst;
  95. };
  96. /// Returns a struct describing if the instruction 'I' can be a recurrence
  97. /// variable of type 'Kind'. If the recurrence is a min/max pattern of
  98. /// select(icmp()) this function advances the instruction pointer 'I' from the
  99. /// compare instruction to the select instruction and stores this pointer in
  100. /// 'PatternLastInst' member of the returned struct.
  101. static InstDesc isRecurrenceInstr(Instruction *I, RecurKind Kind,
  102. InstDesc &Prev, FastMathFlags FMF);
  103. /// Returns true if instruction I has multiple uses in Insts
  104. static bool hasMultipleUsesOf(Instruction *I,
  105. SmallPtrSetImpl<Instruction *> &Insts,
  106. unsigned MaxNumUses);
  107. /// Returns true if all uses of the instruction I is within the Set.
  108. static bool areAllUsesIn(Instruction *I, SmallPtrSetImpl<Instruction *> &Set);
  109. /// Returns a struct describing if the instruction is a
  110. /// Select(ICmp(X, Y), X, Y) instruction pattern corresponding to a min(X, Y)
  111. /// or max(X, Y). \p Prev specifies the description of an already processed
  112. /// select instruction, so its corresponding cmp can be matched to it.
  113. static InstDesc isMinMaxSelectCmpPattern(Instruction *I,
  114. const InstDesc &Prev);
  115. /// Returns a struct describing if the instruction is a
  116. /// Select(FCmp(X, Y), (Z = X op PHINode), PHINode) instruction pattern.
  117. static InstDesc isConditionalRdxPattern(RecurKind Kind, Instruction *I);
  118. /// Returns identity corresponding to the RecurrenceKind.
  119. static Constant *getRecurrenceIdentity(RecurKind K, Type *Tp,
  120. FastMathFlags FMF);
  121. /// Returns the opcode corresponding to the RecurrenceKind.
  122. static unsigned getOpcode(RecurKind Kind);
  123. /// Returns true if Phi is a reduction of type Kind and adds it to the
  124. /// RecurrenceDescriptor. If either \p DB is non-null or \p AC and \p DT are
  125. /// non-null, the minimal bit width needed to compute the reduction will be
  126. /// computed.
  127. static bool AddReductionVar(PHINode *Phi, RecurKind Kind, Loop *TheLoop,
  128. FastMathFlags FMF,
  129. RecurrenceDescriptor &RedDes,
  130. DemandedBits *DB = nullptr,
  131. AssumptionCache *AC = nullptr,
  132. DominatorTree *DT = nullptr);
  133. /// Returns true if Phi is a reduction in TheLoop. The RecurrenceDescriptor
  134. /// is returned in RedDes. If either \p DB is non-null or \p AC and \p DT are
  135. /// non-null, the minimal bit width needed to compute the reduction will be
  136. /// computed.
  137. static bool isReductionPHI(PHINode *Phi, Loop *TheLoop,
  138. RecurrenceDescriptor &RedDes,
  139. DemandedBits *DB = nullptr,
  140. AssumptionCache *AC = nullptr,
  141. DominatorTree *DT = nullptr);
  142. /// Returns true if Phi is a first-order recurrence. A first-order recurrence
  143. /// is a non-reduction recurrence relation in which the value of the
  144. /// recurrence in the current loop iteration equals a value defined in the
  145. /// previous iteration. \p SinkAfter includes pairs of instructions where the
  146. /// first will be rescheduled to appear after the second if/when the loop is
  147. /// vectorized. It may be augmented with additional pairs if needed in order
  148. /// to handle Phi as a first-order recurrence.
  149. static bool
  150. isFirstOrderRecurrence(PHINode *Phi, Loop *TheLoop,
  151. DenseMap<Instruction *, Instruction *> &SinkAfter,
  152. DominatorTree *DT);
  153. RecurKind getRecurrenceKind() const { return Kind; }
  154. unsigned getOpcode() const { return getOpcode(getRecurrenceKind()); }
  155. FastMathFlags getFastMathFlags() const { return FMF; }
  156. TrackingVH<Value> getRecurrenceStartValue() const { return StartValue; }
  157. Instruction *getLoopExitInstr() const { return LoopExitInstr; }
  158. /// Returns true if the recurrence has floating-point math that requires
  159. /// precise (ordered) operations.
  160. bool hasExactFPMath() const { return ExactFPMathInst != nullptr; }
  161. /// Returns 1st non-reassociative FP instruction in the PHI node's use-chain.
  162. Instruction *getExactFPMathInst() const { return ExactFPMathInst; }
  163. /// Returns true if the recurrence kind is an integer kind.
  164. static bool isIntegerRecurrenceKind(RecurKind Kind);
  165. /// Returns true if the recurrence kind is a floating point kind.
  166. static bool isFloatingPointRecurrenceKind(RecurKind Kind);
  167. /// Returns true if the recurrence kind is an arithmetic kind.
  168. static bool isArithmeticRecurrenceKind(RecurKind Kind);
  169. /// Returns true if the recurrence kind is an integer min/max kind.
  170. static bool isIntMinMaxRecurrenceKind(RecurKind Kind) {
  171. return Kind == RecurKind::UMin || Kind == RecurKind::UMax ||
  172. Kind == RecurKind::SMin || Kind == RecurKind::SMax;
  173. }
  174. /// Returns true if the recurrence kind is a floating-point min/max kind.
  175. static bool isFPMinMaxRecurrenceKind(RecurKind Kind) {
  176. return Kind == RecurKind::FMin || Kind == RecurKind::FMax;
  177. }
  178. /// Returns true if the recurrence kind is any min/max kind.
  179. static bool isMinMaxRecurrenceKind(RecurKind Kind) {
  180. return isIntMinMaxRecurrenceKind(Kind) || isFPMinMaxRecurrenceKind(Kind);
  181. }
  182. /// Returns the type of the recurrence. This type can be narrower than the
  183. /// actual type of the Phi if the recurrence has been type-promoted.
  184. Type *getRecurrenceType() const { return RecurrenceType; }
  185. /// Returns a reference to the instructions used for type-promoting the
  186. /// recurrence.
  187. const SmallPtrSet<Instruction *, 8> &getCastInsts() const { return CastInsts; }
  188. /// Returns true if all source operands of the recurrence are SExtInsts.
  189. bool isSigned() const { return IsSigned; }
  190. /// Expose an ordered FP reduction to the instance users.
  191. bool isOrdered() const { return IsOrdered; }
  192. /// Attempts to find a chain of operations from Phi to LoopExitInst that can
  193. /// be treated as a set of reductions instructions for in-loop reductions.
  194. SmallVector<Instruction *, 4> getReductionOpChain(PHINode *Phi,
  195. Loop *L) const;
  196. private:
  197. // The starting value of the recurrence.
  198. // It does not have to be zero!
  199. TrackingVH<Value> StartValue;
  200. // The instruction who's value is used outside the loop.
  201. Instruction *LoopExitInstr = nullptr;
  202. // The kind of the recurrence.
  203. RecurKind Kind = RecurKind::None;
  204. // The fast-math flags on the recurrent instructions. We propagate these
  205. // fast-math flags into the vectorized FP instructions we generate.
  206. FastMathFlags FMF;
  207. // First instance of non-reassociative floating-point in the PHI's use-chain.
  208. Instruction *ExactFPMathInst = nullptr;
  209. // The type of the recurrence.
  210. Type *RecurrenceType = nullptr;
  211. // True if all source operands of the recurrence are SExtInsts.
  212. bool IsSigned = false;
  213. // True if this recurrence can be treated as an in-order reduction.
  214. // Currently only a non-reassociative FAdd can be considered in-order,
  215. // if it is also the only FAdd in the PHI's use chain.
  216. bool IsOrdered = false;
  217. // Instructions used for type-promoting the recurrence.
  218. SmallPtrSet<Instruction *, 8> CastInsts;
  219. };
  220. /// A struct for saving information about induction variables.
  221. class InductionDescriptor {
  222. public:
  223. /// This enum represents the kinds of inductions that we support.
  224. enum InductionKind {
  225. IK_NoInduction, ///< Not an induction variable.
  226. IK_IntInduction, ///< Integer induction variable. Step = C.
  227. IK_PtrInduction, ///< Pointer induction var. Step = C / sizeof(elem).
  228. IK_FpInduction ///< Floating point induction variable.
  229. };
  230. public:
  231. /// Default constructor - creates an invalid induction.
  232. InductionDescriptor() = default;
  233. Value *getStartValue() const { return StartValue; }
  234. InductionKind getKind() const { return IK; }
  235. const SCEV *getStep() const { return Step; }
  236. BinaryOperator *getInductionBinOp() const { return InductionBinOp; }
  237. ConstantInt *getConstIntStepValue() const;
  238. /// Returns true if \p Phi is an induction in the loop \p L. If \p Phi is an
  239. /// induction, the induction descriptor \p D will contain the data describing
  240. /// this induction. If by some other means the caller has a better SCEV
  241. /// expression for \p Phi than the one returned by the ScalarEvolution
  242. /// analysis, it can be passed through \p Expr. If the def-use chain
  243. /// associated with the phi includes casts (that we know we can ignore
  244. /// under proper runtime checks), they are passed through \p CastsToIgnore.
  245. static bool
  246. isInductionPHI(PHINode *Phi, const Loop *L, ScalarEvolution *SE,
  247. InductionDescriptor &D, const SCEV *Expr = nullptr,
  248. SmallVectorImpl<Instruction *> *CastsToIgnore = nullptr);
  249. /// Returns true if \p Phi is a floating point induction in the loop \p L.
  250. /// If \p Phi is an induction, the induction descriptor \p D will contain
  251. /// the data describing this induction.
  252. static bool isFPInductionPHI(PHINode *Phi, const Loop *L, ScalarEvolution *SE,
  253. InductionDescriptor &D);
  254. /// Returns true if \p Phi is a loop \p L induction, in the context associated
  255. /// with the run-time predicate of PSE. If \p Assume is true, this can add
  256. /// further SCEV predicates to \p PSE in order to prove that \p Phi is an
  257. /// induction.
  258. /// If \p Phi is an induction, \p D will contain the data describing this
  259. /// induction.
  260. static bool isInductionPHI(PHINode *Phi, const Loop *L,
  261. PredicatedScalarEvolution &PSE,
  262. InductionDescriptor &D, bool Assume = false);
  263. /// Returns floating-point induction operator that does not allow
  264. /// reassociation (transforming the induction requires an override of normal
  265. /// floating-point rules).
  266. Instruction *getExactFPMathInst() {
  267. if (IK == IK_FpInduction && InductionBinOp &&
  268. !InductionBinOp->hasAllowReassoc())
  269. return InductionBinOp;
  270. return nullptr;
  271. }
  272. /// Returns binary opcode of the induction operator.
  273. Instruction::BinaryOps getInductionOpcode() const {
  274. return InductionBinOp ? InductionBinOp->getOpcode()
  275. : Instruction::BinaryOpsEnd;
  276. }
  277. /// Returns a reference to the type cast instructions in the induction
  278. /// update chain, that are redundant when guarded with a runtime
  279. /// SCEV overflow check.
  280. const SmallVectorImpl<Instruction *> &getCastInsts() const {
  281. return RedundantCasts;
  282. }
  283. private:
  284. /// Private constructor - used by \c isInductionPHI.
  285. InductionDescriptor(Value *Start, InductionKind K, const SCEV *Step,
  286. BinaryOperator *InductionBinOp = nullptr,
  287. SmallVectorImpl<Instruction *> *Casts = nullptr);
  288. /// Start value.
  289. TrackingVH<Value> StartValue;
  290. /// Induction kind.
  291. InductionKind IK = IK_NoInduction;
  292. /// Step value.
  293. const SCEV *Step = nullptr;
  294. // Instruction that advances induction variable.
  295. BinaryOperator *InductionBinOp = nullptr;
  296. // Instructions used for type-casts of the induction variable,
  297. // that are redundant when guarded with a runtime SCEV overflow check.
  298. SmallVector<Instruction *, 2> RedundantCasts;
  299. };
  300. } // end namespace llvm
  301. #endif // LLVM_ANALYSIS_IVDESCRIPTORS_H