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 13 #ifndef LLVM_ANALYSIS_IVDESCRIPTORS_H 14 #define LLVM_ANALYSIS_IVDESCRIPTORS_H 15 16 #include "llvm/ADT/SmallPtrSet.h" 17 #include "llvm/ADT/SmallVector.h" 18 #include "llvm/IR/IntrinsicInst.h" 19 #include "llvm/IR/ValueHandle.h" 20 #include "llvm/Support/Compiler.h" 21 22 namespace llvm { 23 24 class AssumptionCache; 25 class DemandedBits; 26 class DominatorTree; 27 class Loop; 28 class PredicatedScalarEvolution; 29 class ScalarEvolution; 30 class SCEV; 31 class StoreInst; 32 33 /// These are the kinds of recurrences that we support. 34 enum class RecurKind { 35 // clang-format off 36 None, ///< Not a recurrence. 37 Add, ///< Sum of integers. 38 Mul, ///< Product of integers. 39 Or, ///< Bitwise or logical OR of integers. 40 And, ///< Bitwise or logical AND of integers. 41 Xor, ///< Bitwise or logical XOR of integers. 42 SMin, ///< Signed integer min implemented in terms of select(cmp()). 43 SMax, ///< Signed integer max implemented in terms of select(cmp()). 44 UMin, ///< Unsigned integer min implemented in terms of select(cmp()). 45 UMax, ///< Unsigned integer max implemented in terms of select(cmp()). 46 FAdd, ///< Sum of floats. 47 FMul, ///< Product of floats. 48 FMin, ///< FP min implemented in terms of select(cmp()). 49 FMax, ///< FP max implemented in terms of select(cmp()). 50 FMinNum, ///< FP min with llvm.minnum semantics including NaNs. 51 FMaxNum, ///< FP max with llvm.maxnum semantics including NaNs. 52 FMinimum, ///< FP min with llvm.minimum semantics 53 FMaximum, ///< FP max with llvm.maximum semantics 54 FMinimumNum, ///< FP min with llvm.minimumnum semantics 55 FMaximumNum, ///< FP max with llvm.maximumnum semantics 56 FMulAdd, ///< Sum of float products with llvm.fmuladd(a * b + sum). 57 AnyOf, ///< AnyOf reduction with select(cmp(),x,y) where one of (x,y) is 58 ///< loop invariant, and both x and y are integer type. 59 FindFirstIVSMin, /// FindFirst reduction with select(icmp(),x,y) where one of 60 ///< (x,y) is a decreasing loop induction, and both x and y 61 ///< are integer type, producing a SMin reduction. 62 FindFirstIVUMin, /// FindFirst reduction with select(icmp(),x,y) where one of 63 ///< (x,y) is a decreasing loop induction, and both x and y 64 ///< are integer type, producing a UMin reduction. 65 FindLastIVSMax, ///< FindLast reduction with select(cmp(),x,y) where one of 66 ///< (x,y) is increasing loop induction, and both x and y 67 ///< are integer type, producing a SMax reduction. 68 FindLastIVUMax, ///< FindLast reduction with select(cmp(),x,y) where one of 69 ///< (x,y) is increasing loop induction, and both x and y 70 ///< are integer type, producing a UMax reduction. 71 // clang-format on 72 // TODO: Any_of and FindLast reduction need not be restricted to integer type 73 // only. 74 }; 75 76 /// The RecurrenceDescriptor is used to identify recurrences variables in a 77 /// loop. Reduction is a special case of recurrence that has uses of the 78 /// recurrence variable outside the loop. The method isReductionPHI identifies 79 /// reductions that are basic recurrences. 80 /// 81 /// Basic recurrences are defined as the summation, product, OR, AND, XOR, min, 82 /// or max of a set of terms. For example: for(i=0; i<n; i++) { total += 83 /// array[i]; } is a summation of array elements. Basic recurrences are a 84 /// special case of chains of recurrences (CR). See ScalarEvolution for CR 85 /// references. 86 87 /// This struct holds information about recurrence variables. 88 class RecurrenceDescriptor { 89 public: 90 RecurrenceDescriptor() = default; 91 RecurrenceDescriptor(Value * Start,Instruction * Exit,StoreInst * Store,RecurKind K,FastMathFlags FMF,Instruction * ExactFP,Type * RT,bool Signed,bool Ordered,SmallPtrSetImpl<Instruction * > & CI,unsigned MinWidthCastToRecurTy)92 RecurrenceDescriptor(Value *Start, Instruction *Exit, StoreInst *Store, 93 RecurKind K, FastMathFlags FMF, Instruction *ExactFP, 94 Type *RT, bool Signed, bool Ordered, 95 SmallPtrSetImpl<Instruction *> &CI, 96 unsigned MinWidthCastToRecurTy) 97 : IntermediateStore(Store), StartValue(Start), LoopExitInstr(Exit), 98 Kind(K), FMF(FMF), ExactFPMathInst(ExactFP), RecurrenceType(RT), 99 IsSigned(Signed), IsOrdered(Ordered), 100 MinWidthCastToRecurrenceType(MinWidthCastToRecurTy) { 101 CastInsts.insert_range(CI); 102 } 103 104 /// This POD struct holds information about a potential recurrence operation. 105 class InstDesc { 106 public: 107 InstDesc(bool IsRecur, Instruction *I, Instruction *ExactFP = nullptr) IsRecurrence(IsRecur)108 : IsRecurrence(IsRecur), PatternLastInst(I), 109 RecKind(RecurKind::None), ExactFPMathInst(ExactFP) {} 110 111 InstDesc(Instruction *I, RecurKind K, Instruction *ExactFP = nullptr) IsRecurrence(true)112 : IsRecurrence(true), PatternLastInst(I), RecKind(K), 113 ExactFPMathInst(ExactFP) {} 114 isRecurrence()115 bool isRecurrence() const { return IsRecurrence; } 116 needsExactFPMath()117 bool needsExactFPMath() const { return ExactFPMathInst != nullptr; } 118 getExactFPMathInst()119 Instruction *getExactFPMathInst() const { return ExactFPMathInst; } 120 getRecKind()121 RecurKind getRecKind() const { return RecKind; } 122 getPatternInst()123 Instruction *getPatternInst() const { return PatternLastInst; } 124 125 private: 126 // Is this instruction a recurrence candidate. 127 bool IsRecurrence; 128 // The last instruction in a min/max pattern (select of the select(icmp()) 129 // pattern), or the current recurrence instruction otherwise. 130 Instruction *PatternLastInst; 131 // If this is a min/max pattern. 132 RecurKind RecKind; 133 // Recurrence does not allow floating-point reassociation. 134 Instruction *ExactFPMathInst; 135 }; 136 137 /// Returns a struct describing if the instruction 'I' can be a recurrence 138 /// variable of type 'Kind' for a Loop \p L and reduction PHI \p Phi. 139 /// If the recurrence is a min/max pattern of select(icmp()) this function 140 /// advances the instruction pointer 'I' from the compare instruction to the 141 /// select instruction and stores this pointer in 'PatternLastInst' member of 142 /// the returned struct. 143 LLVM_ABI static InstDesc 144 isRecurrenceInstr(Loop *L, PHINode *Phi, Instruction *I, RecurKind Kind, 145 InstDesc &Prev, FastMathFlags FuncFMF, ScalarEvolution *SE); 146 147 /// Returns true if instruction I has multiple uses in Insts 148 LLVM_ABI static bool hasMultipleUsesOf(Instruction *I, 149 SmallPtrSetImpl<Instruction *> &Insts, 150 unsigned MaxNumUses); 151 152 /// Returns true if all uses of the instruction I is within the Set. 153 LLVM_ABI static bool areAllUsesIn(Instruction *I, 154 SmallPtrSetImpl<Instruction *> &Set); 155 156 /// Returns a struct describing if the instruction is a llvm.(s/u)(min/max), 157 /// llvm.minnum/maxnum or a Select(ICmp(X, Y), X, Y) pair of instructions 158 /// corresponding to a min(X, Y) or max(X, Y), matching the recurrence kind \p 159 /// Kind. \p Prev specifies the description of an already processed select 160 /// instruction, so its corresponding cmp can be matched to it. 161 LLVM_ABI static InstDesc isMinMaxPattern(Instruction *I, RecurKind Kind, 162 const InstDesc &Prev); 163 164 /// Returns a struct describing whether the instruction is either a 165 /// Select(ICmp(A, B), X, Y), or 166 /// Select(FCmp(A, B), X, Y) 167 /// where one of (X, Y) is a loop invariant integer and the other is a PHI 168 /// value. \p Prev specifies the description of an already processed select 169 /// instruction, so its corresponding cmp can be matched to it. 170 LLVM_ABI static InstDesc isAnyOfPattern(Loop *Loop, PHINode *OrigPhi, 171 Instruction *I, InstDesc &Prev); 172 173 /// Returns a struct describing whether the instruction is either a 174 /// Select(ICmp(A, B), X, Y), or 175 /// Select(FCmp(A, B), X, Y) 176 /// where one of (X, Y) is an increasing (FindLast) or decreasing (FindFirst) 177 /// loop induction variable, and the other is a PHI value. 178 // TODO: Support non-monotonic variable. FindLast does not need be restricted 179 // to increasing loop induction variables. 180 LLVM_ABI static InstDesc isFindIVPattern(RecurKind Kind, Loop *TheLoop, 181 PHINode *OrigPhi, Instruction *I, 182 ScalarEvolution &SE); 183 184 /// Returns a struct describing if the instruction is a 185 /// Select(FCmp(X, Y), (Z = X op PHINode), PHINode) instruction pattern. 186 LLVM_ABI static InstDesc isConditionalRdxPattern(Instruction *I); 187 188 /// Returns the opcode corresponding to the RecurrenceKind. 189 LLVM_ABI static unsigned getOpcode(RecurKind Kind); 190 191 /// Returns true if Phi is a reduction of type Kind and adds it to the 192 /// RecurrenceDescriptor. If either \p DB is non-null or \p AC and \p DT are 193 /// non-null, the minimal bit width needed to compute the reduction will be 194 /// computed. 195 LLVM_ABI static bool 196 AddReductionVar(PHINode *Phi, RecurKind Kind, Loop *TheLoop, 197 FastMathFlags FuncFMF, RecurrenceDescriptor &RedDes, 198 DemandedBits *DB = nullptr, AssumptionCache *AC = nullptr, 199 DominatorTree *DT = nullptr, ScalarEvolution *SE = nullptr); 200 201 /// Returns true if Phi is a reduction in TheLoop. The RecurrenceDescriptor 202 /// is returned in RedDes. If either \p DB is non-null or \p AC and \p DT are 203 /// non-null, the minimal bit width needed to compute the reduction will be 204 /// computed. If \p SE is non-null, store instructions to loop invariant 205 /// addresses are processed. 206 LLVM_ABI static bool 207 isReductionPHI(PHINode *Phi, Loop *TheLoop, RecurrenceDescriptor &RedDes, 208 DemandedBits *DB = nullptr, AssumptionCache *AC = nullptr, 209 DominatorTree *DT = nullptr, ScalarEvolution *SE = nullptr); 210 211 /// Returns true if Phi is a fixed-order recurrence. A fixed-order recurrence 212 /// is a non-reduction recurrence relation in which the value of the 213 /// recurrence in the current loop iteration equals a value defined in a 214 /// previous iteration (e.g. if the value is defined in the previous 215 /// iteration, we refer to it as first-order recurrence, if it is defined in 216 /// the iteration before the previous, we refer to it as second-order 217 /// recurrence and so on). Note that this function optimistically assumes that 218 /// uses of the recurrence can be re-ordered if necessary and users need to 219 /// check and perform the re-ordering. 220 LLVM_ABI static bool isFixedOrderRecurrence(PHINode *Phi, Loop *TheLoop, 221 DominatorTree *DT); 222 getRecurrenceKind()223 RecurKind getRecurrenceKind() const { return Kind; } 224 getOpcode()225 unsigned getOpcode() const { return getOpcode(getRecurrenceKind()); } 226 getFastMathFlags()227 FastMathFlags getFastMathFlags() const { return FMF; } 228 getRecurrenceStartValue()229 TrackingVH<Value> getRecurrenceStartValue() const { return StartValue; } 230 getLoopExitInstr()231 Instruction *getLoopExitInstr() const { return LoopExitInstr; } 232 233 /// Returns true if the recurrence has floating-point math that requires 234 /// precise (ordered) operations. hasExactFPMath()235 bool hasExactFPMath() const { return ExactFPMathInst != nullptr; } 236 237 /// Returns 1st non-reassociative FP instruction in the PHI node's use-chain. getExactFPMathInst()238 Instruction *getExactFPMathInst() const { return ExactFPMathInst; } 239 240 /// Returns true if the recurrence kind is an integer kind. 241 LLVM_ABI static bool isIntegerRecurrenceKind(RecurKind Kind); 242 243 /// Returns true if the recurrence kind is a floating point kind. 244 LLVM_ABI static bool isFloatingPointRecurrenceKind(RecurKind Kind); 245 246 /// Returns true if the recurrence kind is an integer min/max kind. isIntMinMaxRecurrenceKind(RecurKind Kind)247 static bool isIntMinMaxRecurrenceKind(RecurKind Kind) { 248 return Kind == RecurKind::UMin || Kind == RecurKind::UMax || 249 Kind == RecurKind::SMin || Kind == RecurKind::SMax; 250 } 251 252 /// Returns true if the recurrence kind is a floating-point min/max kind. isFPMinMaxRecurrenceKind(RecurKind Kind)253 static bool isFPMinMaxRecurrenceKind(RecurKind Kind) { 254 return Kind == RecurKind::FMin || Kind == RecurKind::FMax || 255 Kind == RecurKind::FMinNum || Kind == RecurKind::FMaxNum || 256 Kind == RecurKind::FMinimum || Kind == RecurKind::FMaximum || 257 Kind == RecurKind::FMinimumNum || Kind == RecurKind::FMaximumNum; 258 } 259 260 /// Returns true if the recurrence kind is any min/max kind. isMinMaxRecurrenceKind(RecurKind Kind)261 static bool isMinMaxRecurrenceKind(RecurKind Kind) { 262 return isIntMinMaxRecurrenceKind(Kind) || isFPMinMaxRecurrenceKind(Kind); 263 } 264 265 /// Returns true if the recurrence kind is of the form 266 /// select(cmp(),x,y) where one of (x,y) is loop invariant. isAnyOfRecurrenceKind(RecurKind Kind)267 static bool isAnyOfRecurrenceKind(RecurKind Kind) { 268 return Kind == RecurKind::AnyOf; 269 } 270 271 /// Returns true if the recurrence kind is of the form 272 /// select(cmp(),x,y) where one of (x,y) is decreasing loop induction. isFindFirstIVRecurrenceKind(RecurKind Kind)273 static bool isFindFirstIVRecurrenceKind(RecurKind Kind) { 274 return Kind == RecurKind::FindFirstIVSMin || 275 Kind == RecurKind::FindFirstIVUMin; 276 } 277 278 /// Returns true if the recurrence kind is of the form 279 /// select(cmp(),x,y) where one of (x,y) is increasing loop induction. isFindLastIVRecurrenceKind(RecurKind Kind)280 static bool isFindLastIVRecurrenceKind(RecurKind Kind) { 281 return Kind == RecurKind::FindLastIVSMax || 282 Kind == RecurKind::FindLastIVUMax; 283 } 284 285 /// Returns true if recurrece kind is a signed redux kind. isSignedRecurrenceKind(RecurKind Kind)286 static bool isSignedRecurrenceKind(RecurKind Kind) { 287 return Kind == RecurKind::SMax || Kind == RecurKind::SMin || 288 Kind == RecurKind::FindFirstIVSMin || 289 Kind == RecurKind::FindLastIVSMax; 290 } 291 292 /// Returns true if the recurrence kind is of the form 293 /// select(cmp(),x,y) where one of (x,y) is an increasing or decreasing loop 294 /// induction. isFindIVRecurrenceKind(RecurKind Kind)295 static bool isFindIVRecurrenceKind(RecurKind Kind) { 296 return isFindFirstIVRecurrenceKind(Kind) || 297 isFindLastIVRecurrenceKind(Kind); 298 } 299 300 /// Returns the type of the recurrence. This type can be narrower than the 301 /// actual type of the Phi if the recurrence has been type-promoted. getRecurrenceType()302 Type *getRecurrenceType() const { return RecurrenceType; } 303 304 /// Returns the sentinel value for FindFirstIV & FindLastIV recurrences to 305 /// replace the start value. getSentinelValue()306 Value *getSentinelValue() const { 307 Type *Ty = StartValue->getType(); 308 unsigned BW = Ty->getIntegerBitWidth(); 309 if (isFindLastIVRecurrenceKind(Kind)) { 310 return ConstantInt::get(Ty, isSignedRecurrenceKind(Kind) 311 ? APInt::getSignedMinValue(BW) 312 : APInt::getMinValue(BW)); 313 } 314 return ConstantInt::get(Ty, isSignedRecurrenceKind(Kind) 315 ? APInt::getSignedMaxValue(BW) 316 : APInt::getMaxValue(BW)); 317 } 318 319 /// Returns a reference to the instructions used for type-promoting the 320 /// recurrence. getCastInsts()321 const SmallPtrSet<Instruction *, 8> &getCastInsts() const { return CastInsts; } 322 323 /// Returns the minimum width used by the recurrence in bits. getMinWidthCastToRecurrenceTypeInBits()324 unsigned getMinWidthCastToRecurrenceTypeInBits() const { 325 return MinWidthCastToRecurrenceType; 326 } 327 328 /// Returns true if all source operands of the recurrence are SExtInsts. isSigned()329 bool isSigned() const { return IsSigned; } 330 331 /// Expose an ordered FP reduction to the instance users. isOrdered()332 bool isOrdered() const { return IsOrdered; } 333 334 /// Attempts to find a chain of operations from Phi to LoopExitInst that can 335 /// be treated as a set of reductions instructions for in-loop reductions. 336 LLVM_ABI SmallVector<Instruction *, 4> getReductionOpChain(PHINode *Phi, 337 Loop *L) const; 338 339 /// Returns true if the instruction is a call to the llvm.fmuladd intrinsic. isFMulAddIntrinsic(Instruction * I)340 static bool isFMulAddIntrinsic(Instruction *I) { 341 return isa<IntrinsicInst>(I) && 342 cast<IntrinsicInst>(I)->getIntrinsicID() == Intrinsic::fmuladd; 343 } 344 345 /// Reductions may store temporary or final result to an invariant address. 346 /// If there is such a store in the loop then, after successfull run of 347 /// AddReductionVar method, this field will be assigned the last met store. 348 StoreInst *IntermediateStore = nullptr; 349 350 private: 351 // The starting value of the recurrence. 352 // It does not have to be zero! 353 TrackingVH<Value> StartValue; 354 // The instruction who's value is used outside the loop. 355 Instruction *LoopExitInstr = nullptr; 356 // The kind of the recurrence. 357 RecurKind Kind = RecurKind::None; 358 // The fast-math flags on the recurrent instructions. We propagate these 359 // fast-math flags into the vectorized FP instructions we generate. 360 FastMathFlags FMF; 361 // First instance of non-reassociative floating-point in the PHI's use-chain. 362 Instruction *ExactFPMathInst = nullptr; 363 // The type of the recurrence. 364 Type *RecurrenceType = nullptr; 365 // True if all source operands of the recurrence are SExtInsts. 366 bool IsSigned = false; 367 // True if this recurrence can be treated as an in-order reduction. 368 // Currently only a non-reassociative FAdd can be considered in-order, 369 // if it is also the only FAdd in the PHI's use chain. 370 bool IsOrdered = false; 371 // Instructions used for type-promoting the recurrence. 372 SmallPtrSet<Instruction *, 8> CastInsts; 373 // The minimum width used by the recurrence. 374 unsigned MinWidthCastToRecurrenceType; 375 }; 376 377 /// A struct for saving information about induction variables. 378 class InductionDescriptor { 379 public: 380 /// This enum represents the kinds of inductions that we support. 381 enum InductionKind { 382 IK_NoInduction, ///< Not an induction variable. 383 IK_IntInduction, ///< Integer induction variable. Step = C. 384 IK_PtrInduction, ///< Pointer induction var. Step = C. 385 IK_FpInduction ///< Floating point induction variable. 386 }; 387 388 public: 389 /// Default constructor - creates an invalid induction. 390 InductionDescriptor() = default; 391 getStartValue()392 Value *getStartValue() const { return StartValue; } getKind()393 InductionKind getKind() const { return IK; } getStep()394 const SCEV *getStep() const { return Step; } getInductionBinOp()395 BinaryOperator *getInductionBinOp() const { return InductionBinOp; } 396 LLVM_ABI ConstantInt *getConstIntStepValue() const; 397 398 /// Returns true if \p Phi is an induction in the loop \p L. If \p Phi is an 399 /// induction, the induction descriptor \p D will contain the data describing 400 /// this induction. Since Induction Phis can only be present inside loop 401 /// headers, the function will assert if it is passed a Phi whose parent is 402 /// not the loop header. If by some other means the caller has a better SCEV 403 /// expression for \p Phi than the one returned by the ScalarEvolution 404 /// analysis, it can be passed through \p Expr. If the def-use chain 405 /// associated with the phi includes casts (that we know we can ignore 406 /// under proper runtime checks), they are passed through \p CastsToIgnore. 407 LLVM_ABI static bool 408 isInductionPHI(PHINode *Phi, const Loop *L, ScalarEvolution *SE, 409 InductionDescriptor &D, const SCEV *Expr = nullptr, 410 SmallVectorImpl<Instruction *> *CastsToIgnore = nullptr); 411 412 /// Returns true if \p Phi is a floating point induction in the loop \p L. 413 /// If \p Phi is an induction, the induction descriptor \p D will contain 414 /// the data describing this induction. 415 LLVM_ABI static bool isFPInductionPHI(PHINode *Phi, const Loop *L, 416 ScalarEvolution *SE, 417 InductionDescriptor &D); 418 419 /// Returns true if \p Phi is a loop \p L induction, in the context associated 420 /// with the run-time predicate of PSE. If \p Assume is true, this can add 421 /// further SCEV predicates to \p PSE in order to prove that \p Phi is an 422 /// induction. 423 /// If \p Phi is an induction, \p D will contain the data describing this 424 /// induction. 425 LLVM_ABI static bool isInductionPHI(PHINode *Phi, const Loop *L, 426 PredicatedScalarEvolution &PSE, 427 InductionDescriptor &D, 428 bool Assume = false); 429 430 /// Returns floating-point induction operator that does not allow 431 /// reassociation (transforming the induction requires an override of normal 432 /// floating-point rules). getExactFPMathInst()433 Instruction *getExactFPMathInst() { 434 if (IK == IK_FpInduction && InductionBinOp && 435 !InductionBinOp->hasAllowReassoc()) 436 return InductionBinOp; 437 return nullptr; 438 } 439 440 /// Returns binary opcode of the induction operator. getInductionOpcode()441 Instruction::BinaryOps getInductionOpcode() const { 442 return InductionBinOp ? InductionBinOp->getOpcode() 443 : Instruction::BinaryOpsEnd; 444 } 445 446 /// Returns a reference to the type cast instructions in the induction 447 /// update chain, that are redundant when guarded with a runtime 448 /// SCEV overflow check. getCastInsts()449 const SmallVectorImpl<Instruction *> &getCastInsts() const { 450 return RedundantCasts; 451 } 452 453 private: 454 /// Private constructor - used by \c isInductionPHI. 455 InductionDescriptor(Value *Start, InductionKind K, const SCEV *Step, 456 BinaryOperator *InductionBinOp = nullptr, 457 SmallVectorImpl<Instruction *> *Casts = nullptr); 458 459 /// Start value. 460 TrackingVH<Value> StartValue; 461 /// Induction kind. 462 InductionKind IK = IK_NoInduction; 463 /// Step value. 464 const SCEV *Step = nullptr; 465 // Instruction that advances induction variable. 466 BinaryOperator *InductionBinOp = nullptr; 467 // Instructions used for type-casts of the induction variable, 468 // that are redundant when guarded with a runtime SCEV overflow check. 469 SmallVector<Instruction *, 2> RedundantCasts; 470 }; 471 472 } // end namespace llvm 473 474 #endif // LLVM_ANALYSIS_IVDESCRIPTORS_H 475