IVDescriptors.h 18 KB

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