1 //===- LoopVectorize.cpp - A Loop Vectorizer ------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This is the LLVM loop vectorizer. This pass modifies 'vectorizable' loops 11 // and generates target-independent LLVM-IR. 12 // The vectorizer uses the TargetTransformInfo analysis to estimate the costs 13 // of instructions in order to estimate the profitability of vectorization. 14 // 15 // The loop vectorizer combines consecutive loop iterations into a single 16 // 'wide' iteration. After this transformation the index is incremented 17 // by the SIMD vector width, and not by one. 18 // 19 // This pass has three parts: 20 // 1. The main loop pass that drives the different parts. 21 // 2. LoopVectorizationLegality - A unit that checks for the legality 22 // of the vectorization. 23 // 3. InnerLoopVectorizer - A unit that performs the actual 24 // widening of instructions. 25 // 4. LoopVectorizationCostModel - A unit that checks for the profitability 26 // of vectorization. It decides on the optimal vector width, which 27 // can be one, if vectorization is not profitable. 28 // 29 //===----------------------------------------------------------------------===// 30 // 31 // The reduction-variable vectorization is based on the paper: 32 // D. Nuzman and R. Henderson. Multi-platform Auto-vectorization. 33 // 34 // Variable uniformity checks are inspired by: 35 // Karrenberg, R. and Hack, S. Whole Function Vectorization. 36 // 37 // The interleaved access vectorization is based on the paper: 38 // Dorit Nuzman, Ira Rosen and Ayal Zaks. Auto-Vectorization of Interleaved 39 // Data for SIMD 40 // 41 // Other ideas/concepts are from: 42 // A. Zaks and D. Nuzman. Autovectorization in GCC-two years later. 43 // 44 // S. Maleki, Y. Gao, M. Garzaran, T. Wong and D. Padua. An Evaluation of 45 // Vectorizing Compilers. 46 // 47 //===----------------------------------------------------------------------===// 48 49 #include "llvm/Transforms/Vectorize/LoopVectorize.h" 50 #include "llvm/ADT/DenseMap.h" 51 #include "llvm/ADT/Hashing.h" 52 #include "llvm/ADT/MapVector.h" 53 #include "llvm/ADT/SCCIterator.h" 54 #include "llvm/ADT/SetVector.h" 55 #include "llvm/ADT/SmallPtrSet.h" 56 #include "llvm/ADT/SmallSet.h" 57 #include "llvm/ADT/SmallVector.h" 58 #include "llvm/ADT/Statistic.h" 59 #include "llvm/ADT/StringExtras.h" 60 #include "llvm/Analysis/CodeMetrics.h" 61 #include "llvm/Analysis/GlobalsModRef.h" 62 #include "llvm/Analysis/LoopInfo.h" 63 #include "llvm/Analysis/LoopIterator.h" 64 #include "llvm/Analysis/LoopPass.h" 65 #include "llvm/Analysis/ScalarEvolutionExpander.h" 66 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 67 #include "llvm/Analysis/ValueTracking.h" 68 #include "llvm/Analysis/VectorUtils.h" 69 #include "llvm/IR/Constants.h" 70 #include "llvm/IR/DataLayout.h" 71 #include "llvm/IR/DebugInfo.h" 72 #include "llvm/IR/DerivedTypes.h" 73 #include "llvm/IR/DiagnosticInfo.h" 74 #include "llvm/IR/Dominators.h" 75 #include "llvm/IR/Function.h" 76 #include "llvm/IR/IRBuilder.h" 77 #include "llvm/IR/Instructions.h" 78 #include "llvm/IR/IntrinsicInst.h" 79 #include "llvm/IR/LLVMContext.h" 80 #include "llvm/IR/Module.h" 81 #include "llvm/IR/PatternMatch.h" 82 #include "llvm/IR/Type.h" 83 #include "llvm/IR/Value.h" 84 #include "llvm/IR/ValueHandle.h" 85 #include "llvm/IR/Verifier.h" 86 #include "llvm/Pass.h" 87 #include "llvm/Support/BranchProbability.h" 88 #include "llvm/Support/CommandLine.h" 89 #include "llvm/Support/Debug.h" 90 #include "llvm/Support/raw_ostream.h" 91 #include "llvm/Transforms/Scalar.h" 92 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 93 #include "llvm/Transforms/Utils/Local.h" 94 #include "llvm/Transforms/Utils/LoopUtils.h" 95 #include "llvm/Transforms/Utils/LoopVersioning.h" 96 #include "llvm/Transforms/Vectorize.h" 97 #include <algorithm> 98 #include <map> 99 #include <tuple> 100 101 using namespace llvm; 102 using namespace llvm::PatternMatch; 103 104 #define LV_NAME "loop-vectorize" 105 #define DEBUG_TYPE LV_NAME 106 107 STATISTIC(LoopsVectorized, "Number of loops vectorized"); 108 STATISTIC(LoopsAnalyzed, "Number of loops analyzed for vectorization"); 109 110 static cl::opt<bool> 111 EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden, 112 cl::desc("Enable if-conversion during vectorization.")); 113 114 /// We don't vectorize loops with a known constant trip count below this number. 115 static cl::opt<unsigned> TinyTripCountVectorThreshold( 116 "vectorizer-min-trip-count", cl::init(16), cl::Hidden, 117 cl::desc("Don't vectorize loops with a constant " 118 "trip count that is smaller than this " 119 "value.")); 120 121 static cl::opt<bool> MaximizeBandwidth( 122 "vectorizer-maximize-bandwidth", cl::init(false), cl::Hidden, 123 cl::desc("Maximize bandwidth when selecting vectorization factor which " 124 "will be determined by the smallest type in loop.")); 125 126 static cl::opt<bool> EnableInterleavedMemAccesses( 127 "enable-interleaved-mem-accesses", cl::init(false), cl::Hidden, 128 cl::desc("Enable vectorization on interleaved memory accesses in a loop")); 129 130 /// Maximum factor for an interleaved memory access. 131 static cl::opt<unsigned> MaxInterleaveGroupFactor( 132 "max-interleave-group-factor", cl::Hidden, 133 cl::desc("Maximum factor for an interleaved access group (default = 8)"), 134 cl::init(8)); 135 136 /// We don't interleave loops with a known constant trip count below this 137 /// number. 138 static const unsigned TinyTripCountInterleaveThreshold = 128; 139 140 static cl::opt<unsigned> ForceTargetNumScalarRegs( 141 "force-target-num-scalar-regs", cl::init(0), cl::Hidden, 142 cl::desc("A flag that overrides the target's number of scalar registers.")); 143 144 static cl::opt<unsigned> ForceTargetNumVectorRegs( 145 "force-target-num-vector-regs", cl::init(0), cl::Hidden, 146 cl::desc("A flag that overrides the target's number of vector registers.")); 147 148 /// Maximum vectorization interleave count. 149 static const unsigned MaxInterleaveFactor = 16; 150 151 static cl::opt<unsigned> ForceTargetMaxScalarInterleaveFactor( 152 "force-target-max-scalar-interleave", cl::init(0), cl::Hidden, 153 cl::desc("A flag that overrides the target's max interleave factor for " 154 "scalar loops.")); 155 156 static cl::opt<unsigned> ForceTargetMaxVectorInterleaveFactor( 157 "force-target-max-vector-interleave", cl::init(0), cl::Hidden, 158 cl::desc("A flag that overrides the target's max interleave factor for " 159 "vectorized loops.")); 160 161 static cl::opt<unsigned> ForceTargetInstructionCost( 162 "force-target-instruction-cost", cl::init(0), cl::Hidden, 163 cl::desc("A flag that overrides the target's expected cost for " 164 "an instruction to a single constant value. Mostly " 165 "useful for getting consistent testing.")); 166 167 static cl::opt<unsigned> SmallLoopCost( 168 "small-loop-cost", cl::init(20), cl::Hidden, 169 cl::desc( 170 "The cost of a loop that is considered 'small' by the interleaver.")); 171 172 static cl::opt<bool> LoopVectorizeWithBlockFrequency( 173 "loop-vectorize-with-block-frequency", cl::init(false), cl::Hidden, 174 cl::desc("Enable the use of the block frequency analysis to access PGO " 175 "heuristics minimizing code growth in cold regions and being more " 176 "aggressive in hot regions.")); 177 178 // Runtime interleave loops for load/store throughput. 179 static cl::opt<bool> EnableLoadStoreRuntimeInterleave( 180 "enable-loadstore-runtime-interleave", cl::init(true), cl::Hidden, 181 cl::desc( 182 "Enable runtime interleaving until load/store ports are saturated")); 183 184 /// The number of stores in a loop that are allowed to need predication. 185 static cl::opt<unsigned> NumberOfStoresToPredicate( 186 "vectorize-num-stores-pred", cl::init(1), cl::Hidden, 187 cl::desc("Max number of stores to be predicated behind an if.")); 188 189 static cl::opt<bool> EnableIndVarRegisterHeur( 190 "enable-ind-var-reg-heur", cl::init(true), cl::Hidden, 191 cl::desc("Count the induction variable only once when interleaving")); 192 193 static cl::opt<bool> EnableCondStoresVectorization( 194 "enable-cond-stores-vec", cl::init(false), cl::Hidden, 195 cl::desc("Enable if predication of stores during vectorization.")); 196 197 static cl::opt<unsigned> MaxNestedScalarReductionIC( 198 "max-nested-scalar-reduction-interleave", cl::init(2), cl::Hidden, 199 cl::desc("The maximum interleave count to use when interleaving a scalar " 200 "reduction in a nested loop.")); 201 202 static cl::opt<unsigned> PragmaVectorizeMemoryCheckThreshold( 203 "pragma-vectorize-memory-check-threshold", cl::init(128), cl::Hidden, 204 cl::desc("The maximum allowed number of runtime memory checks with a " 205 "vectorize(enable) pragma.")); 206 207 static cl::opt<unsigned> VectorizeSCEVCheckThreshold( 208 "vectorize-scev-check-threshold", cl::init(16), cl::Hidden, 209 cl::desc("The maximum number of SCEV checks allowed.")); 210 211 static cl::opt<unsigned> PragmaVectorizeSCEVCheckThreshold( 212 "pragma-vectorize-scev-check-threshold", cl::init(128), cl::Hidden, 213 cl::desc("The maximum number of SCEV checks allowed with a " 214 "vectorize(enable) pragma")); 215 216 /// Create an analysis remark that explains why vectorization failed 217 /// 218 /// \p PassName is the name of the pass (e.g. can be AlwaysPrint). \p 219 /// RemarkName is the identifier for the remark. If \p I is passed it is an 220 /// instruction that prevents vectorization. Otherwise \p TheLoop is used for 221 /// the location of the remark. \return the remark object that can be 222 /// streamed to. 223 static OptimizationRemarkAnalysis 224 createMissedAnalysis(const char *PassName, StringRef RemarkName, Loop *TheLoop, 225 Instruction *I = nullptr) { 226 Value *CodeRegion = TheLoop->getHeader(); 227 DebugLoc DL = TheLoop->getStartLoc(); 228 229 if (I) { 230 CodeRegion = I->getParent(); 231 // If there is no debug location attached to the instruction, revert back to 232 // using the loop's. 233 if (I->getDebugLoc()) 234 DL = I->getDebugLoc(); 235 } 236 237 OptimizationRemarkAnalysis R(PassName, RemarkName, DL, CodeRegion); 238 R << "loop not vectorized: "; 239 return R; 240 } 241 242 namespace { 243 244 // Forward declarations. 245 class LoopVectorizeHints; 246 class LoopVectorizationLegality; 247 class LoopVectorizationCostModel; 248 class LoopVectorizationRequirements; 249 250 /// Returns true if the given loop body has a cycle, excluding the loop 251 /// itself. 252 static bool hasCyclesInLoopBody(const Loop &L) { 253 if (!L.empty()) 254 return true; 255 256 for (const auto &SCC : 257 make_range(scc_iterator<Loop, LoopBodyTraits>::begin(L), 258 scc_iterator<Loop, LoopBodyTraits>::end(L))) { 259 if (SCC.size() > 1) { 260 DEBUG(dbgs() << "LVL: Detected a cycle in the loop body:\n"); 261 DEBUG(L.dump()); 262 return true; 263 } 264 } 265 return false; 266 } 267 268 /// \brief This modifies LoopAccessReport to initialize message with 269 /// loop-vectorizer-specific part. 270 class VectorizationReport : public LoopAccessReport { 271 public: 272 VectorizationReport(Instruction *I = nullptr) 273 : LoopAccessReport("loop not vectorized: ", I) {} 274 275 /// \brief This allows promotion of the loop-access analysis report into the 276 /// loop-vectorizer report. It modifies the message to add the 277 /// loop-vectorizer-specific part of the message. 278 explicit VectorizationReport(const LoopAccessReport &R) 279 : LoopAccessReport(Twine("loop not vectorized: ") + R.str(), 280 R.getInstr()) {} 281 }; 282 283 /// A helper function for converting Scalar types to vector types. 284 /// If the incoming type is void, we return void. If the VF is 1, we return 285 /// the scalar type. 286 static Type *ToVectorTy(Type *Scalar, unsigned VF) { 287 if (Scalar->isVoidTy() || VF == 1) 288 return Scalar; 289 return VectorType::get(Scalar, VF); 290 } 291 292 /// A helper function that returns GEP instruction and knows to skip a 293 /// 'bitcast'. The 'bitcast' may be skipped if the source and the destination 294 /// pointee types of the 'bitcast' have the same size. 295 /// For example: 296 /// bitcast double** %var to i64* - can be skipped 297 /// bitcast double** %var to i8* - can not 298 static GetElementPtrInst *getGEPInstruction(Value *Ptr) { 299 300 if (isa<GetElementPtrInst>(Ptr)) 301 return cast<GetElementPtrInst>(Ptr); 302 303 if (isa<BitCastInst>(Ptr) && 304 isa<GetElementPtrInst>(cast<BitCastInst>(Ptr)->getOperand(0))) { 305 Type *BitcastTy = Ptr->getType(); 306 Type *GEPTy = cast<BitCastInst>(Ptr)->getSrcTy(); 307 if (!isa<PointerType>(BitcastTy) || !isa<PointerType>(GEPTy)) 308 return nullptr; 309 Type *Pointee1Ty = cast<PointerType>(BitcastTy)->getPointerElementType(); 310 Type *Pointee2Ty = cast<PointerType>(GEPTy)->getPointerElementType(); 311 const DataLayout &DL = cast<BitCastInst>(Ptr)->getModule()->getDataLayout(); 312 if (DL.getTypeSizeInBits(Pointee1Ty) == DL.getTypeSizeInBits(Pointee2Ty)) 313 return cast<GetElementPtrInst>(cast<BitCastInst>(Ptr)->getOperand(0)); 314 } 315 return nullptr; 316 } 317 318 /// A helper function that returns the pointer operand of a load or store 319 /// instruction. 320 static Value *getPointerOperand(Value *I) { 321 if (auto *LI = dyn_cast<LoadInst>(I)) 322 return LI->getPointerOperand(); 323 if (auto *SI = dyn_cast<StoreInst>(I)) 324 return SI->getPointerOperand(); 325 return nullptr; 326 } 327 328 /// A helper function that returns true if the given type is irregular. The 329 /// type is irregular if its allocated size doesn't equal the store size of an 330 /// element of the corresponding vector type at the given vectorization factor. 331 static bool hasIrregularType(Type *Ty, const DataLayout &DL, unsigned VF) { 332 333 // Determine if an array of VF elements of type Ty is "bitcast compatible" 334 // with a <VF x Ty> vector. 335 if (VF > 1) { 336 auto *VectorTy = VectorType::get(Ty, VF); 337 return VF * DL.getTypeAllocSize(Ty) != DL.getTypeStoreSize(VectorTy); 338 } 339 340 // If the vectorization factor is one, we just check if an array of type Ty 341 // requires padding between elements. 342 return DL.getTypeAllocSizeInBits(Ty) != DL.getTypeSizeInBits(Ty); 343 } 344 345 /// A helper function that returns the reciprocal of the block probability of 346 /// predicated blocks. If we return X, we are assuming the predicated block 347 /// will execute once for for every X iterations of the loop header. 348 /// 349 /// TODO: We should use actual block probability here, if available. Currently, 350 /// we always assume predicated blocks have a 50% chance of executing. 351 static unsigned getReciprocalPredBlockProb() { return 2; } 352 353 /// InnerLoopVectorizer vectorizes loops which contain only one basic 354 /// block to a specified vectorization factor (VF). 355 /// This class performs the widening of scalars into vectors, or multiple 356 /// scalars. This class also implements the following features: 357 /// * It inserts an epilogue loop for handling loops that don't have iteration 358 /// counts that are known to be a multiple of the vectorization factor. 359 /// * It handles the code generation for reduction variables. 360 /// * Scalarization (implementation using scalars) of un-vectorizable 361 /// instructions. 362 /// InnerLoopVectorizer does not perform any vectorization-legality 363 /// checks, and relies on the caller to check for the different legality 364 /// aspects. The InnerLoopVectorizer relies on the 365 /// LoopVectorizationLegality class to provide information about the induction 366 /// and reduction variables that were found to a given vectorization factor. 367 class InnerLoopVectorizer { 368 public: 369 InnerLoopVectorizer(Loop *OrigLoop, PredicatedScalarEvolution &PSE, 370 LoopInfo *LI, DominatorTree *DT, 371 const TargetLibraryInfo *TLI, 372 const TargetTransformInfo *TTI, AssumptionCache *AC, 373 OptimizationRemarkEmitter *ORE, unsigned VecWidth, 374 unsigned UnrollFactor, LoopVectorizationLegality *LVL, 375 LoopVectorizationCostModel *CM) 376 : OrigLoop(OrigLoop), PSE(PSE), LI(LI), DT(DT), TLI(TLI), TTI(TTI), 377 AC(AC), ORE(ORE), VF(VecWidth), UF(UnrollFactor), 378 Builder(PSE.getSE()->getContext()), Induction(nullptr), 379 OldInduction(nullptr), VectorLoopValueMap(UnrollFactor, VecWidth), 380 TripCount(nullptr), VectorTripCount(nullptr), Legal(LVL), Cost(CM), 381 AddedSafetyChecks(false) {} 382 383 // Perform the actual loop widening (vectorization). 384 void vectorize() { 385 // Create a new empty loop. Unlink the old loop and connect the new one. 386 createEmptyLoop(); 387 // Widen each instruction in the old loop to a new one in the new loop. 388 vectorizeLoop(); 389 } 390 391 // Return true if any runtime check is added. 392 bool areSafetyChecksAdded() { return AddedSafetyChecks; } 393 394 virtual ~InnerLoopVectorizer() {} 395 396 protected: 397 /// A small list of PHINodes. 398 typedef SmallVector<PHINode *, 4> PhiVector; 399 400 /// A type for vectorized values in the new loop. Each value from the 401 /// original loop, when vectorized, is represented by UF vector values in the 402 /// new unrolled loop, where UF is the unroll factor. 403 typedef SmallVector<Value *, 2> VectorParts; 404 405 /// A type for scalarized values in the new loop. Each value from the 406 /// original loop, when scalarized, is represented by UF x VF scalar values 407 /// in the new unrolled loop, where UF is the unroll factor and VF is the 408 /// vectorization factor. 409 typedef SmallVector<SmallVector<Value *, 4>, 2> ScalarParts; 410 411 // When we if-convert we need to create edge masks. We have to cache values 412 // so that we don't end up with exponential recursion/IR. 413 typedef DenseMap<std::pair<BasicBlock *, BasicBlock *>, VectorParts> 414 EdgeMaskCache; 415 416 /// Create an empty loop, based on the loop ranges of the old loop. 417 void createEmptyLoop(); 418 419 /// Set up the values of the IVs correctly when exiting the vector loop. 420 void fixupIVUsers(PHINode *OrigPhi, const InductionDescriptor &II, 421 Value *CountRoundDown, Value *EndValue, 422 BasicBlock *MiddleBlock); 423 424 /// Create a new induction variable inside L. 425 PHINode *createInductionVariable(Loop *L, Value *Start, Value *End, 426 Value *Step, Instruction *DL); 427 /// Copy and widen the instructions from the old loop. 428 virtual void vectorizeLoop(); 429 430 /// Fix a first-order recurrence. This is the second phase of vectorizing 431 /// this phi node. 432 void fixFirstOrderRecurrence(PHINode *Phi); 433 434 /// \brief The Loop exit block may have single value PHI nodes where the 435 /// incoming value is 'Undef'. While vectorizing we only handled real values 436 /// that were defined inside the loop. Here we fix the 'undef case'. 437 /// See PR14725. 438 void fixLCSSAPHIs(); 439 440 /// Predicate conditional instructions that require predication on their 441 /// respective conditions. 442 void predicateInstructions(); 443 444 /// Shrinks vector element sizes to the smallest bitwidth they can be legally 445 /// represented as. 446 void truncateToMinimalBitwidths(); 447 448 /// A helper function that computes the predicate of the block BB, assuming 449 /// that the header block of the loop is set to True. It returns the *entry* 450 /// mask for the block BB. 451 VectorParts createBlockInMask(BasicBlock *BB); 452 /// A helper function that computes the predicate of the edge between SRC 453 /// and DST. 454 VectorParts createEdgeMask(BasicBlock *Src, BasicBlock *Dst); 455 456 /// A helper function to vectorize a single BB within the innermost loop. 457 void vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV); 458 459 /// Vectorize a single PHINode in a block. This method handles the induction 460 /// variable canonicalization. It supports both VF = 1 for unrolled loops and 461 /// arbitrary length vectors. 462 void widenPHIInstruction(Instruction *PN, unsigned UF, unsigned VF, 463 PhiVector *PV); 464 465 /// Insert the new loop to the loop hierarchy and pass manager 466 /// and update the analysis passes. 467 void updateAnalysis(); 468 469 /// This instruction is un-vectorizable. Implement it as a sequence 470 /// of scalars. If \p IfPredicateInstr is true we need to 'hide' each 471 /// scalarized instruction behind an if block predicated on the control 472 /// dependence of the instruction. 473 virtual void scalarizeInstruction(Instruction *Instr, 474 bool IfPredicateInstr = false); 475 476 /// Vectorize Load and Store instructions, 477 virtual void vectorizeMemoryInstruction(Instruction *Instr); 478 479 /// Create a broadcast instruction. This method generates a broadcast 480 /// instruction (shuffle) for loop invariant values and for the induction 481 /// value. If this is the induction variable then we extend it to N, N+1, ... 482 /// this is needed because each iteration in the loop corresponds to a SIMD 483 /// element. 484 virtual Value *getBroadcastInstrs(Value *V); 485 486 /// This function adds (StartIdx, StartIdx + Step, StartIdx + 2*Step, ...) 487 /// to each vector element of Val. The sequence starts at StartIndex. 488 /// \p Opcode is relevant for FP induction variable. 489 virtual Value *getStepVector(Value *Val, int StartIdx, Value *Step, 490 Instruction::BinaryOps Opcode = 491 Instruction::BinaryOpsEnd); 492 493 /// Compute scalar induction steps. \p ScalarIV is the scalar induction 494 /// variable on which to base the steps, \p Step is the size of the step, and 495 /// \p EntryVal is the value from the original loop that maps to the steps. 496 /// Note that \p EntryVal doesn't have to be an induction variable (e.g., it 497 /// can be a truncate instruction). 498 void buildScalarSteps(Value *ScalarIV, Value *Step, Value *EntryVal); 499 500 /// Create a vector induction phi node based on an existing scalar one. This 501 /// currently only works for integer induction variables with a constant 502 /// step. \p EntryVal is the value from the original loop that maps to the 503 /// vector phi node. If \p EntryVal is a truncate instruction, instead of 504 /// widening the original IV, we widen a version of the IV truncated to \p 505 /// EntryVal's type. 506 void createVectorIntInductionPHI(const InductionDescriptor &II, 507 Instruction *EntryVal); 508 509 /// Widen an integer induction variable \p IV. If \p Trunc is provided, the 510 /// induction variable will first be truncated to the corresponding type. 511 void widenIntInduction(PHINode *IV, TruncInst *Trunc = nullptr); 512 513 /// Returns true if we should generate a scalar version of \p IV. 514 bool needsScalarInduction(Instruction *IV) const; 515 516 /// Return a constant reference to the VectorParts corresponding to \p V from 517 /// the original loop. If the value has already been vectorized, the 518 /// corresponding vector entry in VectorLoopValueMap is returned. If, 519 /// however, the value has a scalar entry in VectorLoopValueMap, we construct 520 /// new vector values on-demand by inserting the scalar values into vectors 521 /// with an insertelement sequence. If the value has been neither vectorized 522 /// nor scalarized, it must be loop invariant, so we simply broadcast the 523 /// value into vectors. 524 const VectorParts &getVectorValue(Value *V); 525 526 /// Return a value in the new loop corresponding to \p V from the original 527 /// loop at unroll index \p Part and vector index \p Lane. If the value has 528 /// been vectorized but not scalarized, the necessary extractelement 529 /// instruction will be generated. 530 Value *getScalarValue(Value *V, unsigned Part, unsigned Lane); 531 532 /// Try to vectorize the interleaved access group that \p Instr belongs to. 533 void vectorizeInterleaveGroup(Instruction *Instr); 534 535 /// Generate a shuffle sequence that will reverse the vector Vec. 536 virtual Value *reverseVector(Value *Vec); 537 538 /// Returns (and creates if needed) the original loop trip count. 539 Value *getOrCreateTripCount(Loop *NewLoop); 540 541 /// Returns (and creates if needed) the trip count of the widened loop. 542 Value *getOrCreateVectorTripCount(Loop *NewLoop); 543 544 /// Emit a bypass check to see if the trip count would overflow, or we 545 /// wouldn't have enough iterations to execute one vector loop. 546 void emitMinimumIterationCountCheck(Loop *L, BasicBlock *Bypass); 547 /// Emit a bypass check to see if the vector trip count is nonzero. 548 void emitVectorLoopEnteredCheck(Loop *L, BasicBlock *Bypass); 549 /// Emit a bypass check to see if all of the SCEV assumptions we've 550 /// had to make are correct. 551 void emitSCEVChecks(Loop *L, BasicBlock *Bypass); 552 /// Emit bypass checks to check any memory assumptions we may have made. 553 void emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass); 554 555 /// Add additional metadata to \p To that was not present on \p Orig. 556 /// 557 /// Currently this is used to add the noalias annotations based on the 558 /// inserted memchecks. Use this for instructions that are *cloned* into the 559 /// vector loop. 560 void addNewMetadata(Instruction *To, const Instruction *Orig); 561 562 /// Add metadata from one instruction to another. 563 /// 564 /// This includes both the original MDs from \p From and additional ones (\see 565 /// addNewMetadata). Use this for *newly created* instructions in the vector 566 /// loop. 567 void addMetadata(Instruction *To, Instruction *From); 568 569 /// \brief Similar to the previous function but it adds the metadata to a 570 /// vector of instructions. 571 void addMetadata(ArrayRef<Value *> To, Instruction *From); 572 573 /// This is a helper class for maintaining vectorization state. It's used for 574 /// mapping values from the original loop to their corresponding values in 575 /// the new loop. Two mappings are maintained: one for vectorized values and 576 /// one for scalarized values. Vectorized values are represented with UF 577 /// vector values in the new loop, and scalarized values are represented with 578 /// UF x VF scalar values in the new loop. UF and VF are the unroll and 579 /// vectorization factors, respectively. 580 /// 581 /// Entries can be added to either map with initVector and initScalar, which 582 /// initialize and return a constant reference to the new entry. If a 583 /// non-constant reference to a vector entry is required, getVector can be 584 /// used to retrieve a mutable entry. We currently directly modify the mapped 585 /// values during "fix-up" operations that occur once the first phase of 586 /// widening is complete. These operations include type truncation and the 587 /// second phase of recurrence widening. 588 /// 589 /// Otherwise, entries from either map should be accessed using the 590 /// getVectorValue or getScalarValue functions from InnerLoopVectorizer. 591 /// getVectorValue and getScalarValue coordinate to generate a vector or 592 /// scalar value on-demand if one is not yet available. When vectorizing a 593 /// loop, we visit the definition of an instruction before its uses. When 594 /// visiting the definition, we either vectorize or scalarize the 595 /// instruction, creating an entry for it in the corresponding map. (In some 596 /// cases, such as induction variables, we will create both vector and scalar 597 /// entries.) Then, as we encounter uses of the definition, we derive values 598 /// for each scalar or vector use unless such a value is already available. 599 /// For example, if we scalarize a definition and one of its uses is vector, 600 /// we build the required vector on-demand with an insertelement sequence 601 /// when visiting the use. Otherwise, if the use is scalar, we can use the 602 /// existing scalar definition. 603 struct ValueMap { 604 605 /// Construct an empty map with the given unroll and vectorization factors. 606 ValueMap(unsigned UnrollFactor, unsigned VecWidth) 607 : UF(UnrollFactor), VF(VecWidth) { 608 // The unroll and vectorization factors are only used in asserts builds 609 // to verify map entries are sized appropriately. 610 (void)UF; 611 (void)VF; 612 } 613 614 /// \return True if the map has a vector entry for \p Key. 615 bool hasVector(Value *Key) const { return VectorMapStorage.count(Key); } 616 617 /// \return True if the map has a scalar entry for \p Key. 618 bool hasScalar(Value *Key) const { return ScalarMapStorage.count(Key); } 619 620 /// \brief Map \p Key to the given VectorParts \p Entry, and return a 621 /// constant reference to the new vector map entry. The given key should 622 /// not already be in the map, and the given VectorParts should be 623 /// correctly sized for the current unroll factor. 624 const VectorParts &initVector(Value *Key, const VectorParts &Entry) { 625 assert(!hasVector(Key) && "Vector entry already initialized"); 626 assert(Entry.size() == UF && "VectorParts has wrong dimensions"); 627 VectorMapStorage[Key] = Entry; 628 return VectorMapStorage[Key]; 629 } 630 631 /// \brief Map \p Key to the given ScalarParts \p Entry, and return a 632 /// constant reference to the new scalar map entry. The given key should 633 /// not already be in the map, and the given ScalarParts should be 634 /// correctly sized for the current unroll and vectorization factors. 635 const ScalarParts &initScalar(Value *Key, const ScalarParts &Entry) { 636 assert(!hasScalar(Key) && "Scalar entry already initialized"); 637 assert(Entry.size() == UF && 638 all_of(make_range(Entry.begin(), Entry.end()), 639 [&](const SmallVectorImpl<Value *> &Values) -> bool { 640 return Values.size() == VF; 641 }) && 642 "ScalarParts has wrong dimensions"); 643 ScalarMapStorage[Key] = Entry; 644 return ScalarMapStorage[Key]; 645 } 646 647 /// \return A reference to the vector map entry corresponding to \p Key. 648 /// The key should already be in the map. This function should only be used 649 /// when it's necessary to update values that have already been vectorized. 650 /// This is the case for "fix-up" operations including type truncation and 651 /// the second phase of recurrence vectorization. If a non-const reference 652 /// isn't required, getVectorValue should be used instead. 653 VectorParts &getVector(Value *Key) { 654 assert(hasVector(Key) && "Vector entry not initialized"); 655 return VectorMapStorage.find(Key)->second; 656 } 657 658 /// Retrieve an entry from the vector or scalar maps. The preferred way to 659 /// access an existing mapped entry is with getVectorValue or 660 /// getScalarValue from InnerLoopVectorizer. Until those functions can be 661 /// moved inside ValueMap, we have to declare them as friends. 662 friend const VectorParts &InnerLoopVectorizer::getVectorValue(Value *V); 663 friend Value *InnerLoopVectorizer::getScalarValue(Value *V, unsigned Part, 664 unsigned Lane); 665 666 private: 667 /// The unroll factor. Each entry in the vector map contains UF vector 668 /// values. 669 unsigned UF; 670 671 /// The vectorization factor. Each entry in the scalar map contains UF x VF 672 /// scalar values. 673 unsigned VF; 674 675 /// The vector and scalar map storage. We use std::map and not DenseMap 676 /// because insertions to DenseMap invalidate its iterators. 677 std::map<Value *, VectorParts> VectorMapStorage; 678 std::map<Value *, ScalarParts> ScalarMapStorage; 679 }; 680 681 /// The original loop. 682 Loop *OrigLoop; 683 /// A wrapper around ScalarEvolution used to add runtime SCEV checks. Applies 684 /// dynamic knowledge to simplify SCEV expressions and converts them to a 685 /// more usable form. 686 PredicatedScalarEvolution &PSE; 687 /// Loop Info. 688 LoopInfo *LI; 689 /// Dominator Tree. 690 DominatorTree *DT; 691 /// Alias Analysis. 692 AliasAnalysis *AA; 693 /// Target Library Info. 694 const TargetLibraryInfo *TLI; 695 /// Target Transform Info. 696 const TargetTransformInfo *TTI; 697 /// Assumption Cache. 698 AssumptionCache *AC; 699 /// Interface to emit optimization remarks. 700 OptimizationRemarkEmitter *ORE; 701 702 /// \brief LoopVersioning. It's only set up (non-null) if memchecks were 703 /// used. 704 /// 705 /// This is currently only used to add no-alias metadata based on the 706 /// memchecks. The actually versioning is performed manually. 707 std::unique_ptr<LoopVersioning> LVer; 708 709 /// The vectorization SIMD factor to use. Each vector will have this many 710 /// vector elements. 711 unsigned VF; 712 713 protected: 714 /// The vectorization unroll factor to use. Each scalar is vectorized to this 715 /// many different vector instructions. 716 unsigned UF; 717 718 /// The builder that we use 719 IRBuilder<> Builder; 720 721 // --- Vectorization state --- 722 723 /// The vector-loop preheader. 724 BasicBlock *LoopVectorPreHeader; 725 /// The scalar-loop preheader. 726 BasicBlock *LoopScalarPreHeader; 727 /// Middle Block between the vector and the scalar. 728 BasicBlock *LoopMiddleBlock; 729 /// The ExitBlock of the scalar loop. 730 BasicBlock *LoopExitBlock; 731 /// The vector loop body. 732 BasicBlock *LoopVectorBody; 733 /// The scalar loop body. 734 BasicBlock *LoopScalarBody; 735 /// A list of all bypass blocks. The first block is the entry of the loop. 736 SmallVector<BasicBlock *, 4> LoopBypassBlocks; 737 738 /// The new Induction variable which was added to the new block. 739 PHINode *Induction; 740 /// The induction variable of the old basic block. 741 PHINode *OldInduction; 742 743 /// Maps values from the original loop to their corresponding values in the 744 /// vectorized loop. A key value can map to either vector values, scalar 745 /// values or both kinds of values, depending on whether the key was 746 /// vectorized and scalarized. 747 ValueMap VectorLoopValueMap; 748 749 /// Store instructions that should be predicated, as a pair 750 /// <StoreInst, Predicate> 751 SmallVector<std::pair<Instruction *, Value *>, 4> PredicatedInstructions; 752 EdgeMaskCache MaskCache; 753 /// Trip count of the original loop. 754 Value *TripCount; 755 /// Trip count of the widened loop (TripCount - TripCount % (VF*UF)) 756 Value *VectorTripCount; 757 758 /// The legality analysis. 759 LoopVectorizationLegality *Legal; 760 761 /// The profitablity analysis. 762 LoopVectorizationCostModel *Cost; 763 764 // Record whether runtime checks are added. 765 bool AddedSafetyChecks; 766 }; 767 768 class InnerLoopUnroller : public InnerLoopVectorizer { 769 public: 770 InnerLoopUnroller(Loop *OrigLoop, PredicatedScalarEvolution &PSE, 771 LoopInfo *LI, DominatorTree *DT, 772 const TargetLibraryInfo *TLI, 773 const TargetTransformInfo *TTI, AssumptionCache *AC, 774 OptimizationRemarkEmitter *ORE, unsigned UnrollFactor, 775 LoopVectorizationLegality *LVL, 776 LoopVectorizationCostModel *CM) 777 : InnerLoopVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE, 1, 778 UnrollFactor, LVL, CM) {} 779 780 private: 781 void scalarizeInstruction(Instruction *Instr, 782 bool IfPredicateInstr = false) override; 783 void vectorizeMemoryInstruction(Instruction *Instr) override; 784 Value *getBroadcastInstrs(Value *V) override; 785 Value *getStepVector(Value *Val, int StartIdx, Value *Step, 786 Instruction::BinaryOps Opcode = 787 Instruction::BinaryOpsEnd) override; 788 Value *reverseVector(Value *Vec) override; 789 }; 790 791 /// \brief Look for a meaningful debug location on the instruction or it's 792 /// operands. 793 static Instruction *getDebugLocFromInstOrOperands(Instruction *I) { 794 if (!I) 795 return I; 796 797 DebugLoc Empty; 798 if (I->getDebugLoc() != Empty) 799 return I; 800 801 for (User::op_iterator OI = I->op_begin(), OE = I->op_end(); OI != OE; ++OI) { 802 if (Instruction *OpInst = dyn_cast<Instruction>(*OI)) 803 if (OpInst->getDebugLoc() != Empty) 804 return OpInst; 805 } 806 807 return I; 808 } 809 810 /// \brief Set the debug location in the builder using the debug location in the 811 /// instruction. 812 static void setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr) { 813 if (const Instruction *Inst = dyn_cast_or_null<Instruction>(Ptr)) 814 B.SetCurrentDebugLocation(Inst->getDebugLoc()); 815 else 816 B.SetCurrentDebugLocation(DebugLoc()); 817 } 818 819 #ifndef NDEBUG 820 /// \return string containing a file name and a line # for the given loop. 821 static std::string getDebugLocString(const Loop *L) { 822 std::string Result; 823 if (L) { 824 raw_string_ostream OS(Result); 825 if (const DebugLoc LoopDbgLoc = L->getStartLoc()) 826 LoopDbgLoc.print(OS); 827 else 828 // Just print the module name. 829 OS << L->getHeader()->getParent()->getParent()->getModuleIdentifier(); 830 OS.flush(); 831 } 832 return Result; 833 } 834 #endif 835 836 void InnerLoopVectorizer::addNewMetadata(Instruction *To, 837 const Instruction *Orig) { 838 // If the loop was versioned with memchecks, add the corresponding no-alias 839 // metadata. 840 if (LVer && (isa<LoadInst>(Orig) || isa<StoreInst>(Orig))) 841 LVer->annotateInstWithNoAlias(To, Orig); 842 } 843 844 void InnerLoopVectorizer::addMetadata(Instruction *To, 845 Instruction *From) { 846 propagateMetadata(To, From); 847 addNewMetadata(To, From); 848 } 849 850 void InnerLoopVectorizer::addMetadata(ArrayRef<Value *> To, 851 Instruction *From) { 852 for (Value *V : To) { 853 if (Instruction *I = dyn_cast<Instruction>(V)) 854 addMetadata(I, From); 855 } 856 } 857 858 /// \brief The group of interleaved loads/stores sharing the same stride and 859 /// close to each other. 860 /// 861 /// Each member in this group has an index starting from 0, and the largest 862 /// index should be less than interleaved factor, which is equal to the absolute 863 /// value of the access's stride. 864 /// 865 /// E.g. An interleaved load group of factor 4: 866 /// for (unsigned i = 0; i < 1024; i+=4) { 867 /// a = A[i]; // Member of index 0 868 /// b = A[i+1]; // Member of index 1 869 /// d = A[i+3]; // Member of index 3 870 /// ... 871 /// } 872 /// 873 /// An interleaved store group of factor 4: 874 /// for (unsigned i = 0; i < 1024; i+=4) { 875 /// ... 876 /// A[i] = a; // Member of index 0 877 /// A[i+1] = b; // Member of index 1 878 /// A[i+2] = c; // Member of index 2 879 /// A[i+3] = d; // Member of index 3 880 /// } 881 /// 882 /// Note: the interleaved load group could have gaps (missing members), but 883 /// the interleaved store group doesn't allow gaps. 884 class InterleaveGroup { 885 public: 886 InterleaveGroup(Instruction *Instr, int Stride, unsigned Align) 887 : Align(Align), SmallestKey(0), LargestKey(0), InsertPos(Instr) { 888 assert(Align && "The alignment should be non-zero"); 889 890 Factor = std::abs(Stride); 891 assert(Factor > 1 && "Invalid interleave factor"); 892 893 Reverse = Stride < 0; 894 Members[0] = Instr; 895 } 896 897 bool isReverse() const { return Reverse; } 898 unsigned getFactor() const { return Factor; } 899 unsigned getAlignment() const { return Align; } 900 unsigned getNumMembers() const { return Members.size(); } 901 902 /// \brief Try to insert a new member \p Instr with index \p Index and 903 /// alignment \p NewAlign. The index is related to the leader and it could be 904 /// negative if it is the new leader. 905 /// 906 /// \returns false if the instruction doesn't belong to the group. 907 bool insertMember(Instruction *Instr, int Index, unsigned NewAlign) { 908 assert(NewAlign && "The new member's alignment should be non-zero"); 909 910 int Key = Index + SmallestKey; 911 912 // Skip if there is already a member with the same index. 913 if (Members.count(Key)) 914 return false; 915 916 if (Key > LargestKey) { 917 // The largest index is always less than the interleave factor. 918 if (Index >= static_cast<int>(Factor)) 919 return false; 920 921 LargestKey = Key; 922 } else if (Key < SmallestKey) { 923 // The largest index is always less than the interleave factor. 924 if (LargestKey - Key >= static_cast<int>(Factor)) 925 return false; 926 927 SmallestKey = Key; 928 } 929 930 // It's always safe to select the minimum alignment. 931 Align = std::min(Align, NewAlign); 932 Members[Key] = Instr; 933 return true; 934 } 935 936 /// \brief Get the member with the given index \p Index 937 /// 938 /// \returns nullptr if contains no such member. 939 Instruction *getMember(unsigned Index) const { 940 int Key = SmallestKey + Index; 941 if (!Members.count(Key)) 942 return nullptr; 943 944 return Members.find(Key)->second; 945 } 946 947 /// \brief Get the index for the given member. Unlike the key in the member 948 /// map, the index starts from 0. 949 unsigned getIndex(Instruction *Instr) const { 950 for (auto I : Members) 951 if (I.second == Instr) 952 return I.first - SmallestKey; 953 954 llvm_unreachable("InterleaveGroup contains no such member"); 955 } 956 957 Instruction *getInsertPos() const { return InsertPos; } 958 void setInsertPos(Instruction *Inst) { InsertPos = Inst; } 959 960 private: 961 unsigned Factor; // Interleave Factor. 962 bool Reverse; 963 unsigned Align; 964 DenseMap<int, Instruction *> Members; 965 int SmallestKey; 966 int LargestKey; 967 968 // To avoid breaking dependences, vectorized instructions of an interleave 969 // group should be inserted at either the first load or the last store in 970 // program order. 971 // 972 // E.g. %even = load i32 // Insert Position 973 // %add = add i32 %even // Use of %even 974 // %odd = load i32 975 // 976 // store i32 %even 977 // %odd = add i32 // Def of %odd 978 // store i32 %odd // Insert Position 979 Instruction *InsertPos; 980 }; 981 982 /// \brief Drive the analysis of interleaved memory accesses in the loop. 983 /// 984 /// Use this class to analyze interleaved accesses only when we can vectorize 985 /// a loop. Otherwise it's meaningless to do analysis as the vectorization 986 /// on interleaved accesses is unsafe. 987 /// 988 /// The analysis collects interleave groups and records the relationships 989 /// between the member and the group in a map. 990 class InterleavedAccessInfo { 991 public: 992 InterleavedAccessInfo(PredicatedScalarEvolution &PSE, Loop *L, 993 DominatorTree *DT, LoopInfo *LI) 994 : PSE(PSE), TheLoop(L), DT(DT), LI(LI), LAI(nullptr), 995 RequiresScalarEpilogue(false) {} 996 997 ~InterleavedAccessInfo() { 998 SmallSet<InterleaveGroup *, 4> DelSet; 999 // Avoid releasing a pointer twice. 1000 for (auto &I : InterleaveGroupMap) 1001 DelSet.insert(I.second); 1002 for (auto *Ptr : DelSet) 1003 delete Ptr; 1004 } 1005 1006 /// \brief Analyze the interleaved accesses and collect them in interleave 1007 /// groups. Substitute symbolic strides using \p Strides. 1008 void analyzeInterleaving(const ValueToValueMap &Strides); 1009 1010 /// \brief Check if \p Instr belongs to any interleave group. 1011 bool isInterleaved(Instruction *Instr) const { 1012 return InterleaveGroupMap.count(Instr); 1013 } 1014 1015 /// \brief Return the maximum interleave factor of all interleaved groups. 1016 unsigned getMaxInterleaveFactor() const { 1017 unsigned MaxFactor = 1; 1018 for (auto &Entry : InterleaveGroupMap) 1019 MaxFactor = std::max(MaxFactor, Entry.second->getFactor()); 1020 return MaxFactor; 1021 } 1022 1023 /// \brief Get the interleave group that \p Instr belongs to. 1024 /// 1025 /// \returns nullptr if doesn't have such group. 1026 InterleaveGroup *getInterleaveGroup(Instruction *Instr) const { 1027 if (InterleaveGroupMap.count(Instr)) 1028 return InterleaveGroupMap.find(Instr)->second; 1029 return nullptr; 1030 } 1031 1032 /// \brief Returns true if an interleaved group that may access memory 1033 /// out-of-bounds requires a scalar epilogue iteration for correctness. 1034 bool requiresScalarEpilogue() const { return RequiresScalarEpilogue; } 1035 1036 /// \brief Initialize the LoopAccessInfo used for dependence checking. 1037 void setLAI(const LoopAccessInfo *Info) { LAI = Info; } 1038 1039 private: 1040 /// A wrapper around ScalarEvolution, used to add runtime SCEV checks. 1041 /// Simplifies SCEV expressions in the context of existing SCEV assumptions. 1042 /// The interleaved access analysis can also add new predicates (for example 1043 /// by versioning strides of pointers). 1044 PredicatedScalarEvolution &PSE; 1045 Loop *TheLoop; 1046 DominatorTree *DT; 1047 LoopInfo *LI; 1048 const LoopAccessInfo *LAI; 1049 1050 /// True if the loop may contain non-reversed interleaved groups with 1051 /// out-of-bounds accesses. We ensure we don't speculatively access memory 1052 /// out-of-bounds by executing at least one scalar epilogue iteration. 1053 bool RequiresScalarEpilogue; 1054 1055 /// Holds the relationships between the members and the interleave group. 1056 DenseMap<Instruction *, InterleaveGroup *> InterleaveGroupMap; 1057 1058 /// Holds dependences among the memory accesses in the loop. It maps a source 1059 /// access to a set of dependent sink accesses. 1060 DenseMap<Instruction *, SmallPtrSet<Instruction *, 2>> Dependences; 1061 1062 /// \brief The descriptor for a strided memory access. 1063 struct StrideDescriptor { 1064 StrideDescriptor(int64_t Stride, const SCEV *Scev, uint64_t Size, 1065 unsigned Align) 1066 : Stride(Stride), Scev(Scev), Size(Size), Align(Align) {} 1067 1068 StrideDescriptor() = default; 1069 1070 // The access's stride. It is negative for a reverse access. 1071 int64_t Stride = 0; 1072 const SCEV *Scev = nullptr; // The scalar expression of this access 1073 uint64_t Size = 0; // The size of the memory object. 1074 unsigned Align = 0; // The alignment of this access. 1075 }; 1076 1077 /// \brief A type for holding instructions and their stride descriptors. 1078 typedef std::pair<Instruction *, StrideDescriptor> StrideEntry; 1079 1080 /// \brief Create a new interleave group with the given instruction \p Instr, 1081 /// stride \p Stride and alignment \p Align. 1082 /// 1083 /// \returns the newly created interleave group. 1084 InterleaveGroup *createInterleaveGroup(Instruction *Instr, int Stride, 1085 unsigned Align) { 1086 assert(!InterleaveGroupMap.count(Instr) && 1087 "Already in an interleaved access group"); 1088 InterleaveGroupMap[Instr] = new InterleaveGroup(Instr, Stride, Align); 1089 return InterleaveGroupMap[Instr]; 1090 } 1091 1092 /// \brief Release the group and remove all the relationships. 1093 void releaseGroup(InterleaveGroup *Group) { 1094 for (unsigned i = 0; i < Group->getFactor(); i++) 1095 if (Instruction *Member = Group->getMember(i)) 1096 InterleaveGroupMap.erase(Member); 1097 1098 delete Group; 1099 } 1100 1101 /// \brief Collect all the accesses with a constant stride in program order. 1102 void collectConstStrideAccesses( 1103 MapVector<Instruction *, StrideDescriptor> &AccessStrideInfo, 1104 const ValueToValueMap &Strides); 1105 1106 /// \brief Returns true if \p Stride is allowed in an interleaved group. 1107 static bool isStrided(int Stride) { 1108 unsigned Factor = std::abs(Stride); 1109 return Factor >= 2 && Factor <= MaxInterleaveGroupFactor; 1110 } 1111 1112 /// \brief Returns true if \p BB is a predicated block. 1113 bool isPredicated(BasicBlock *BB) const { 1114 return LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT); 1115 } 1116 1117 /// \brief Returns true if LoopAccessInfo can be used for dependence queries. 1118 bool areDependencesValid() const { 1119 return LAI && LAI->getDepChecker().getDependences(); 1120 } 1121 1122 /// \brief Returns true if memory accesses \p A and \p B can be reordered, if 1123 /// necessary, when constructing interleaved groups. 1124 /// 1125 /// \p A must precede \p B in program order. We return false if reordering is 1126 /// not necessary or is prevented because \p A and \p B may be dependent. 1127 bool canReorderMemAccessesForInterleavedGroups(StrideEntry *A, 1128 StrideEntry *B) const { 1129 1130 // Code motion for interleaved accesses can potentially hoist strided loads 1131 // and sink strided stores. The code below checks the legality of the 1132 // following two conditions: 1133 // 1134 // 1. Potentially moving a strided load (B) before any store (A) that 1135 // precedes B, or 1136 // 1137 // 2. Potentially moving a strided store (A) after any load or store (B) 1138 // that A precedes. 1139 // 1140 // It's legal to reorder A and B if we know there isn't a dependence from A 1141 // to B. Note that this determination is conservative since some 1142 // dependences could potentially be reordered safely. 1143 1144 // A is potentially the source of a dependence. 1145 auto *Src = A->first; 1146 auto SrcDes = A->second; 1147 1148 // B is potentially the sink of a dependence. 1149 auto *Sink = B->first; 1150 auto SinkDes = B->second; 1151 1152 // Code motion for interleaved accesses can't violate WAR dependences. 1153 // Thus, reordering is legal if the source isn't a write. 1154 if (!Src->mayWriteToMemory()) 1155 return true; 1156 1157 // At least one of the accesses must be strided. 1158 if (!isStrided(SrcDes.Stride) && !isStrided(SinkDes.Stride)) 1159 return true; 1160 1161 // If dependence information is not available from LoopAccessInfo, 1162 // conservatively assume the instructions can't be reordered. 1163 if (!areDependencesValid()) 1164 return false; 1165 1166 // If we know there is a dependence from source to sink, assume the 1167 // instructions can't be reordered. Otherwise, reordering is legal. 1168 return !Dependences.count(Src) || !Dependences.lookup(Src).count(Sink); 1169 } 1170 1171 /// \brief Collect the dependences from LoopAccessInfo. 1172 /// 1173 /// We process the dependences once during the interleaved access analysis to 1174 /// enable constant-time dependence queries. 1175 void collectDependences() { 1176 if (!areDependencesValid()) 1177 return; 1178 auto *Deps = LAI->getDepChecker().getDependences(); 1179 for (auto Dep : *Deps) 1180 Dependences[Dep.getSource(*LAI)].insert(Dep.getDestination(*LAI)); 1181 } 1182 }; 1183 1184 /// Utility class for getting and setting loop vectorizer hints in the form 1185 /// of loop metadata. 1186 /// This class keeps a number of loop annotations locally (as member variables) 1187 /// and can, upon request, write them back as metadata on the loop. It will 1188 /// initially scan the loop for existing metadata, and will update the local 1189 /// values based on information in the loop. 1190 /// We cannot write all values to metadata, as the mere presence of some info, 1191 /// for example 'force', means a decision has been made. So, we need to be 1192 /// careful NOT to add them if the user hasn't specifically asked so. 1193 class LoopVectorizeHints { 1194 enum HintKind { HK_WIDTH, HK_UNROLL, HK_FORCE }; 1195 1196 /// Hint - associates name and validation with the hint value. 1197 struct Hint { 1198 const char *Name; 1199 unsigned Value; // This may have to change for non-numeric values. 1200 HintKind Kind; 1201 1202 Hint(const char *Name, unsigned Value, HintKind Kind) 1203 : Name(Name), Value(Value), Kind(Kind) {} 1204 1205 bool validate(unsigned Val) { 1206 switch (Kind) { 1207 case HK_WIDTH: 1208 return isPowerOf2_32(Val) && Val <= VectorizerParams::MaxVectorWidth; 1209 case HK_UNROLL: 1210 return isPowerOf2_32(Val) && Val <= MaxInterleaveFactor; 1211 case HK_FORCE: 1212 return (Val <= 1); 1213 } 1214 return false; 1215 } 1216 }; 1217 1218 /// Vectorization width. 1219 Hint Width; 1220 /// Vectorization interleave factor. 1221 Hint Interleave; 1222 /// Vectorization forced 1223 Hint Force; 1224 1225 /// Return the loop metadata prefix. 1226 static StringRef Prefix() { return "llvm.loop."; } 1227 1228 /// True if there is any unsafe math in the loop. 1229 bool PotentiallyUnsafe; 1230 1231 public: 1232 enum ForceKind { 1233 FK_Undefined = -1, ///< Not selected. 1234 FK_Disabled = 0, ///< Forcing disabled. 1235 FK_Enabled = 1, ///< Forcing enabled. 1236 }; 1237 1238 LoopVectorizeHints(const Loop *L, bool DisableInterleaving, 1239 OptimizationRemarkEmitter &ORE) 1240 : Width("vectorize.width", VectorizerParams::VectorizationFactor, 1241 HK_WIDTH), 1242 Interleave("interleave.count", DisableInterleaving, HK_UNROLL), 1243 Force("vectorize.enable", FK_Undefined, HK_FORCE), 1244 PotentiallyUnsafe(false), TheLoop(L), ORE(ORE) { 1245 // Populate values with existing loop metadata. 1246 getHintsFromMetadata(); 1247 1248 // force-vector-interleave overrides DisableInterleaving. 1249 if (VectorizerParams::isInterleaveForced()) 1250 Interleave.Value = VectorizerParams::VectorizationInterleave; 1251 1252 DEBUG(if (DisableInterleaving && Interleave.Value == 1) dbgs() 1253 << "LV: Interleaving disabled by the pass manager\n"); 1254 } 1255 1256 /// Mark the loop L as already vectorized by setting the width to 1. 1257 void setAlreadyVectorized() { 1258 Width.Value = Interleave.Value = 1; 1259 Hint Hints[] = {Width, Interleave}; 1260 writeHintsToMetadata(Hints); 1261 } 1262 1263 bool allowVectorization(Function *F, Loop *L, bool AlwaysVectorize) const { 1264 if (getForce() == LoopVectorizeHints::FK_Disabled) { 1265 DEBUG(dbgs() << "LV: Not vectorizing: #pragma vectorize disable.\n"); 1266 emitRemarkWithHints(); 1267 return false; 1268 } 1269 1270 if (!AlwaysVectorize && getForce() != LoopVectorizeHints::FK_Enabled) { 1271 DEBUG(dbgs() << "LV: Not vectorizing: No #pragma vectorize enable.\n"); 1272 emitRemarkWithHints(); 1273 return false; 1274 } 1275 1276 if (getWidth() == 1 && getInterleave() == 1) { 1277 // FIXME: Add a separate metadata to indicate when the loop has already 1278 // been vectorized instead of setting width and count to 1. 1279 DEBUG(dbgs() << "LV: Not vectorizing: Disabled/already vectorized.\n"); 1280 // FIXME: Add interleave.disable metadata. This will allow 1281 // vectorize.disable to be used without disabling the pass and errors 1282 // to differentiate between disabled vectorization and a width of 1. 1283 ORE.emit(OptimizationRemarkAnalysis(vectorizeAnalysisPassName(), 1284 "AllDisabled", L->getStartLoc(), 1285 L->getHeader()) 1286 << "loop not vectorized: vectorization and interleaving are " 1287 "explicitly disabled, or vectorize width and interleave " 1288 "count are both set to 1"); 1289 return false; 1290 } 1291 1292 return true; 1293 } 1294 1295 /// Dumps all the hint information. 1296 void emitRemarkWithHints() const { 1297 using namespace ore; 1298 if (Force.Value == LoopVectorizeHints::FK_Disabled) 1299 ORE.emit(OptimizationRemarkMissed(LV_NAME, "MissedExplicitlyDisabled", 1300 TheLoop->getStartLoc(), 1301 TheLoop->getHeader()) 1302 << "loop not vectorized: vectorization is explicitly disabled"); 1303 else { 1304 OptimizationRemarkMissed R(LV_NAME, "MissedDetails", 1305 TheLoop->getStartLoc(), TheLoop->getHeader()); 1306 R << "loop not vectorized: use -Rpass-analysis=loop-vectorize for more " 1307 "info"; 1308 if (Force.Value == LoopVectorizeHints::FK_Enabled) { 1309 R << " (Force=" << NV("Force", true); 1310 if (Width.Value != 0) 1311 R << ", Vector Width=" << NV("VectorWidth", Width.Value); 1312 if (Interleave.Value != 0) 1313 R << ", Interleave Count=" << NV("InterleaveCount", Interleave.Value); 1314 R << ")"; 1315 } 1316 ORE.emit(R); 1317 } 1318 } 1319 1320 unsigned getWidth() const { return Width.Value; } 1321 unsigned getInterleave() const { return Interleave.Value; } 1322 enum ForceKind getForce() const { return (ForceKind)Force.Value; } 1323 1324 /// \brief If hints are provided that force vectorization, use the AlwaysPrint 1325 /// pass name to force the frontend to print the diagnostic. 1326 const char *vectorizeAnalysisPassName() const { 1327 if (getWidth() == 1) 1328 return LV_NAME; 1329 if (getForce() == LoopVectorizeHints::FK_Disabled) 1330 return LV_NAME; 1331 if (getForce() == LoopVectorizeHints::FK_Undefined && getWidth() == 0) 1332 return LV_NAME; 1333 return OptimizationRemarkAnalysis::AlwaysPrint; 1334 } 1335 1336 bool allowReordering() const { 1337 // When enabling loop hints are provided we allow the vectorizer to change 1338 // the order of operations that is given by the scalar loop. This is not 1339 // enabled by default because can be unsafe or inefficient. For example, 1340 // reordering floating-point operations will change the way round-off 1341 // error accumulates in the loop. 1342 return getForce() == LoopVectorizeHints::FK_Enabled || getWidth() > 1; 1343 } 1344 1345 bool isPotentiallyUnsafe() const { 1346 // Avoid FP vectorization if the target is unsure about proper support. 1347 // This may be related to the SIMD unit in the target not handling 1348 // IEEE 754 FP ops properly, or bad single-to-double promotions. 1349 // Otherwise, a sequence of vectorized loops, even without reduction, 1350 // could lead to different end results on the destination vectors. 1351 return getForce() != LoopVectorizeHints::FK_Enabled && PotentiallyUnsafe; 1352 } 1353 1354 void setPotentiallyUnsafe() { PotentiallyUnsafe = true; } 1355 1356 private: 1357 /// Find hints specified in the loop metadata and update local values. 1358 void getHintsFromMetadata() { 1359 MDNode *LoopID = TheLoop->getLoopID(); 1360 if (!LoopID) 1361 return; 1362 1363 // First operand should refer to the loop id itself. 1364 assert(LoopID->getNumOperands() > 0 && "requires at least one operand"); 1365 assert(LoopID->getOperand(0) == LoopID && "invalid loop id"); 1366 1367 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) { 1368 const MDString *S = nullptr; 1369 SmallVector<Metadata *, 4> Args; 1370 1371 // The expected hint is either a MDString or a MDNode with the first 1372 // operand a MDString. 1373 if (const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i))) { 1374 if (!MD || MD->getNumOperands() == 0) 1375 continue; 1376 S = dyn_cast<MDString>(MD->getOperand(0)); 1377 for (unsigned i = 1, ie = MD->getNumOperands(); i < ie; ++i) 1378 Args.push_back(MD->getOperand(i)); 1379 } else { 1380 S = dyn_cast<MDString>(LoopID->getOperand(i)); 1381 assert(Args.size() == 0 && "too many arguments for MDString"); 1382 } 1383 1384 if (!S) 1385 continue; 1386 1387 // Check if the hint starts with the loop metadata prefix. 1388 StringRef Name = S->getString(); 1389 if (Args.size() == 1) 1390 setHint(Name, Args[0]); 1391 } 1392 } 1393 1394 /// Checks string hint with one operand and set value if valid. 1395 void setHint(StringRef Name, Metadata *Arg) { 1396 if (!Name.startswith(Prefix())) 1397 return; 1398 Name = Name.substr(Prefix().size(), StringRef::npos); 1399 1400 const ConstantInt *C = mdconst::dyn_extract<ConstantInt>(Arg); 1401 if (!C) 1402 return; 1403 unsigned Val = C->getZExtValue(); 1404 1405 Hint *Hints[] = {&Width, &Interleave, &Force}; 1406 for (auto H : Hints) { 1407 if (Name == H->Name) { 1408 if (H->validate(Val)) 1409 H->Value = Val; 1410 else 1411 DEBUG(dbgs() << "LV: ignoring invalid hint '" << Name << "'\n"); 1412 break; 1413 } 1414 } 1415 } 1416 1417 /// Create a new hint from name / value pair. 1418 MDNode *createHintMetadata(StringRef Name, unsigned V) const { 1419 LLVMContext &Context = TheLoop->getHeader()->getContext(); 1420 Metadata *MDs[] = {MDString::get(Context, Name), 1421 ConstantAsMetadata::get( 1422 ConstantInt::get(Type::getInt32Ty(Context), V))}; 1423 return MDNode::get(Context, MDs); 1424 } 1425 1426 /// Matches metadata with hint name. 1427 bool matchesHintMetadataName(MDNode *Node, ArrayRef<Hint> HintTypes) { 1428 MDString *Name = dyn_cast<MDString>(Node->getOperand(0)); 1429 if (!Name) 1430 return false; 1431 1432 for (auto H : HintTypes) 1433 if (Name->getString().endswith(H.Name)) 1434 return true; 1435 return false; 1436 } 1437 1438 /// Sets current hints into loop metadata, keeping other values intact. 1439 void writeHintsToMetadata(ArrayRef<Hint> HintTypes) { 1440 if (HintTypes.size() == 0) 1441 return; 1442 1443 // Reserve the first element to LoopID (see below). 1444 SmallVector<Metadata *, 4> MDs(1); 1445 // If the loop already has metadata, then ignore the existing operands. 1446 MDNode *LoopID = TheLoop->getLoopID(); 1447 if (LoopID) { 1448 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) { 1449 MDNode *Node = cast<MDNode>(LoopID->getOperand(i)); 1450 // If node in update list, ignore old value. 1451 if (!matchesHintMetadataName(Node, HintTypes)) 1452 MDs.push_back(Node); 1453 } 1454 } 1455 1456 // Now, add the missing hints. 1457 for (auto H : HintTypes) 1458 MDs.push_back(createHintMetadata(Twine(Prefix(), H.Name).str(), H.Value)); 1459 1460 // Replace current metadata node with new one. 1461 LLVMContext &Context = TheLoop->getHeader()->getContext(); 1462 MDNode *NewLoopID = MDNode::get(Context, MDs); 1463 // Set operand 0 to refer to the loop id itself. 1464 NewLoopID->replaceOperandWith(0, NewLoopID); 1465 1466 TheLoop->setLoopID(NewLoopID); 1467 } 1468 1469 /// The loop these hints belong to. 1470 const Loop *TheLoop; 1471 1472 /// Interface to emit optimization remarks. 1473 OptimizationRemarkEmitter &ORE; 1474 }; 1475 1476 static void emitAnalysisDiag(const Loop *TheLoop, 1477 const LoopVectorizeHints &Hints, 1478 OptimizationRemarkEmitter &ORE, 1479 const LoopAccessReport &Message) { 1480 const char *Name = Hints.vectorizeAnalysisPassName(); 1481 LoopAccessReport::emitAnalysis(Message, TheLoop, Name, ORE); 1482 } 1483 1484 static void emitMissedWarning(Function *F, Loop *L, 1485 const LoopVectorizeHints &LH, 1486 OptimizationRemarkEmitter *ORE) { 1487 LH.emitRemarkWithHints(); 1488 1489 if (LH.getForce() == LoopVectorizeHints::FK_Enabled) { 1490 if (LH.getWidth() != 1) 1491 emitLoopVectorizeWarning( 1492 F->getContext(), *F, L->getStartLoc(), 1493 "failed explicitly specified loop vectorization"); 1494 else if (LH.getInterleave() != 1) 1495 emitLoopInterleaveWarning( 1496 F->getContext(), *F, L->getStartLoc(), 1497 "failed explicitly specified loop interleaving"); 1498 } 1499 } 1500 1501 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and 1502 /// to what vectorization factor. 1503 /// This class does not look at the profitability of vectorization, only the 1504 /// legality. This class has two main kinds of checks: 1505 /// * Memory checks - The code in canVectorizeMemory checks if vectorization 1506 /// will change the order of memory accesses in a way that will change the 1507 /// correctness of the program. 1508 /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory 1509 /// checks for a number of different conditions, such as the availability of a 1510 /// single induction variable, that all types are supported and vectorize-able, 1511 /// etc. This code reflects the capabilities of InnerLoopVectorizer. 1512 /// This class is also used by InnerLoopVectorizer for identifying 1513 /// induction variable and the different reduction variables. 1514 class LoopVectorizationLegality { 1515 public: 1516 LoopVectorizationLegality( 1517 Loop *L, PredicatedScalarEvolution &PSE, DominatorTree *DT, 1518 TargetLibraryInfo *TLI, AliasAnalysis *AA, Function *F, 1519 const TargetTransformInfo *TTI, 1520 std::function<const LoopAccessInfo &(Loop &)> *GetLAA, LoopInfo *LI, 1521 OptimizationRemarkEmitter *ORE, LoopVectorizationRequirements *R, 1522 LoopVectorizeHints *H) 1523 : NumPredStores(0), TheLoop(L), PSE(PSE), TLI(TLI), TTI(TTI), DT(DT), 1524 GetLAA(GetLAA), LAI(nullptr), ORE(ORE), InterleaveInfo(PSE, L, DT, LI), 1525 Induction(nullptr), WidestIndTy(nullptr), HasFunNoNaNAttr(false), 1526 Requirements(R), Hints(H) {} 1527 1528 /// ReductionList contains the reduction descriptors for all 1529 /// of the reductions that were found in the loop. 1530 typedef DenseMap<PHINode *, RecurrenceDescriptor> ReductionList; 1531 1532 /// InductionList saves induction variables and maps them to the 1533 /// induction descriptor. 1534 typedef MapVector<PHINode *, InductionDescriptor> InductionList; 1535 1536 /// RecurrenceSet contains the phi nodes that are recurrences other than 1537 /// inductions and reductions. 1538 typedef SmallPtrSet<const PHINode *, 8> RecurrenceSet; 1539 1540 /// Returns true if it is legal to vectorize this loop. 1541 /// This does not mean that it is profitable to vectorize this 1542 /// loop, only that it is legal to do so. 1543 bool canVectorize(); 1544 1545 /// Returns the Induction variable. 1546 PHINode *getInduction() { return Induction; } 1547 1548 /// Returns the reduction variables found in the loop. 1549 ReductionList *getReductionVars() { return &Reductions; } 1550 1551 /// Returns the induction variables found in the loop. 1552 InductionList *getInductionVars() { return &Inductions; } 1553 1554 /// Return the first-order recurrences found in the loop. 1555 RecurrenceSet *getFirstOrderRecurrences() { return &FirstOrderRecurrences; } 1556 1557 /// Returns the widest induction type. 1558 Type *getWidestInductionType() { return WidestIndTy; } 1559 1560 /// Returns True if V is an induction variable in this loop. 1561 bool isInductionVariable(const Value *V); 1562 1563 /// Returns True if PN is a reduction variable in this loop. 1564 bool isReductionVariable(PHINode *PN) { return Reductions.count(PN); } 1565 1566 /// Returns True if Phi is a first-order recurrence in this loop. 1567 bool isFirstOrderRecurrence(const PHINode *Phi); 1568 1569 /// Return true if the block BB needs to be predicated in order for the loop 1570 /// to be vectorized. 1571 bool blockNeedsPredication(BasicBlock *BB); 1572 1573 /// Check if this pointer is consecutive when vectorizing. This happens 1574 /// when the last index of the GEP is the induction variable, or that the 1575 /// pointer itself is an induction variable. 1576 /// This check allows us to vectorize A[idx] into a wide load/store. 1577 /// Returns: 1578 /// 0 - Stride is unknown or non-consecutive. 1579 /// 1 - Address is consecutive. 1580 /// -1 - Address is consecutive, and decreasing. 1581 int isConsecutivePtr(Value *Ptr); 1582 1583 /// Returns true if the value V is uniform within the loop. 1584 bool isUniform(Value *V); 1585 1586 /// Returns true if \p I is known to be uniform after vectorization. 1587 bool isUniformAfterVectorization(Instruction *I) { return Uniforms.count(I); } 1588 1589 /// Returns true if \p I is known to be scalar after vectorization. 1590 bool isScalarAfterVectorization(Instruction *I) { return Scalars.count(I); } 1591 1592 /// Returns the information that we collected about runtime memory check. 1593 const RuntimePointerChecking *getRuntimePointerChecking() const { 1594 return LAI->getRuntimePointerChecking(); 1595 } 1596 1597 const LoopAccessInfo *getLAI() const { return LAI; } 1598 1599 /// \brief Check if \p Instr belongs to any interleaved access group. 1600 bool isAccessInterleaved(Instruction *Instr) { 1601 return InterleaveInfo.isInterleaved(Instr); 1602 } 1603 1604 /// \brief Return the maximum interleave factor of all interleaved groups. 1605 unsigned getMaxInterleaveFactor() const { 1606 return InterleaveInfo.getMaxInterleaveFactor(); 1607 } 1608 1609 /// \brief Get the interleaved access group that \p Instr belongs to. 1610 const InterleaveGroup *getInterleavedAccessGroup(Instruction *Instr) { 1611 return InterleaveInfo.getInterleaveGroup(Instr); 1612 } 1613 1614 /// \brief Returns true if an interleaved group requires a scalar iteration 1615 /// to handle accesses with gaps. 1616 bool requiresScalarEpilogue() const { 1617 return InterleaveInfo.requiresScalarEpilogue(); 1618 } 1619 1620 unsigned getMaxSafeDepDistBytes() { return LAI->getMaxSafeDepDistBytes(); } 1621 1622 bool hasStride(Value *V) { return LAI->hasStride(V); } 1623 1624 /// Returns true if the target machine supports masked store operation 1625 /// for the given \p DataType and kind of access to \p Ptr. 1626 bool isLegalMaskedStore(Type *DataType, Value *Ptr) { 1627 return isConsecutivePtr(Ptr) && TTI->isLegalMaskedStore(DataType); 1628 } 1629 /// Returns true if the target machine supports masked load operation 1630 /// for the given \p DataType and kind of access to \p Ptr. 1631 bool isLegalMaskedLoad(Type *DataType, Value *Ptr) { 1632 return isConsecutivePtr(Ptr) && TTI->isLegalMaskedLoad(DataType); 1633 } 1634 /// Returns true if the target machine supports masked scatter operation 1635 /// for the given \p DataType. 1636 bool isLegalMaskedScatter(Type *DataType) { 1637 return TTI->isLegalMaskedScatter(DataType); 1638 } 1639 /// Returns true if the target machine supports masked gather operation 1640 /// for the given \p DataType. 1641 bool isLegalMaskedGather(Type *DataType) { 1642 return TTI->isLegalMaskedGather(DataType); 1643 } 1644 /// Returns true if the target machine can represent \p V as a masked gather 1645 /// or scatter operation. 1646 bool isLegalGatherOrScatter(Value *V) { 1647 auto *LI = dyn_cast<LoadInst>(V); 1648 auto *SI = dyn_cast<StoreInst>(V); 1649 if (!LI && !SI) 1650 return false; 1651 auto *Ptr = getPointerOperand(V); 1652 auto *Ty = cast<PointerType>(Ptr->getType())->getElementType(); 1653 return (LI && isLegalMaskedGather(Ty)) || (SI && isLegalMaskedScatter(Ty)); 1654 } 1655 1656 /// Returns true if vector representation of the instruction \p I 1657 /// requires mask. 1658 bool isMaskRequired(const Instruction *I) { return (MaskedOp.count(I) != 0); } 1659 unsigned getNumStores() const { return LAI->getNumStores(); } 1660 unsigned getNumLoads() const { return LAI->getNumLoads(); } 1661 unsigned getNumPredStores() const { return NumPredStores; } 1662 1663 /// Returns true if \p I is an instruction that will be scalarized with 1664 /// predication. Such instructions include conditional stores and 1665 /// instructions that may divide by zero. 1666 bool isScalarWithPredication(Instruction *I); 1667 1668 /// Returns true if \p I is a memory instruction that has a consecutive or 1669 /// consecutive-like pointer operand. Consecutive-like pointers are pointers 1670 /// that are treated like consecutive pointers during vectorization. The 1671 /// pointer operands of interleaved accesses are an example. 1672 bool hasConsecutiveLikePtrOperand(Instruction *I); 1673 1674 /// Returns true if \p I is a memory instruction that must be scalarized 1675 /// during vectorization. 1676 bool memoryInstructionMustBeScalarized(Instruction *I, unsigned VF = 1); 1677 1678 private: 1679 /// Check if a single basic block loop is vectorizable. 1680 /// At this point we know that this is a loop with a constant trip count 1681 /// and we only need to check individual instructions. 1682 bool canVectorizeInstrs(); 1683 1684 /// When we vectorize loops we may change the order in which 1685 /// we read and write from memory. This method checks if it is 1686 /// legal to vectorize the code, considering only memory constrains. 1687 /// Returns true if the loop is vectorizable 1688 bool canVectorizeMemory(); 1689 1690 /// Return true if we can vectorize this loop using the IF-conversion 1691 /// transformation. 1692 bool canVectorizeWithIfConvert(); 1693 1694 /// Collect the instructions that are uniform after vectorization. An 1695 /// instruction is uniform if we represent it with a single scalar value in 1696 /// the vectorized loop corresponding to each vector iteration. Examples of 1697 /// uniform instructions include pointer operands of consecutive or 1698 /// interleaved memory accesses. Note that although uniformity implies an 1699 /// instruction will be scalar, the reverse is not true. In general, a 1700 /// scalarized instruction will be represented by VF scalar values in the 1701 /// vectorized loop, each corresponding to an iteration of the original 1702 /// scalar loop. 1703 void collectLoopUniforms(); 1704 1705 /// Collect the instructions that are scalar after vectorization. An 1706 /// instruction is scalar if it is known to be uniform or will be scalarized 1707 /// during vectorization. Non-uniform scalarized instructions will be 1708 /// represented by VF values in the vectorized loop, each corresponding to an 1709 /// iteration of the original scalar loop. 1710 void collectLoopScalars(); 1711 1712 /// Return true if all of the instructions in the block can be speculatively 1713 /// executed. \p SafePtrs is a list of addresses that are known to be legal 1714 /// and we know that we can read from them without segfault. 1715 bool blockCanBePredicated(BasicBlock *BB, SmallPtrSetImpl<Value *> &SafePtrs); 1716 1717 /// Updates the vectorization state by adding \p Phi to the inductions list. 1718 /// This can set \p Phi as the main induction of the loop if \p Phi is a 1719 /// better choice for the main induction than the existing one. 1720 void addInductionPhi(PHINode *Phi, const InductionDescriptor &ID, 1721 SmallPtrSetImpl<Value *> &AllowedExit); 1722 1723 /// Report an analysis message to assist the user in diagnosing loops that are 1724 /// not vectorized. These are handled as LoopAccessReport rather than 1725 /// VectorizationReport because the << operator of VectorizationReport returns 1726 /// LoopAccessReport. 1727 void emitAnalysis(const LoopAccessReport &Message) const { 1728 emitAnalysisDiag(TheLoop, *Hints, *ORE, Message); 1729 } 1730 1731 /// Create an analysis remark that explains why vectorization failed 1732 /// 1733 /// \p RemarkName is the identifier for the remark. If \p I is passed it is 1734 /// an instruction that prevents vectorization. Otherwise the loop is used 1735 /// for the location of the remark. \return the remark object that can be 1736 /// streamed to. 1737 OptimizationRemarkAnalysis 1738 createMissedAnalysis(StringRef RemarkName, Instruction *I = nullptr) const { 1739 return ::createMissedAnalysis(Hints->vectorizeAnalysisPassName(), 1740 RemarkName, TheLoop, I); 1741 } 1742 1743 /// \brief If an access has a symbolic strides, this maps the pointer value to 1744 /// the stride symbol. 1745 const ValueToValueMap *getSymbolicStrides() { 1746 // FIXME: Currently, the set of symbolic strides is sometimes queried before 1747 // it's collected. This happens from canVectorizeWithIfConvert, when the 1748 // pointer is checked to reference consecutive elements suitable for a 1749 // masked access. 1750 return LAI ? &LAI->getSymbolicStrides() : nullptr; 1751 } 1752 1753 unsigned NumPredStores; 1754 1755 /// The loop that we evaluate. 1756 Loop *TheLoop; 1757 /// A wrapper around ScalarEvolution used to add runtime SCEV checks. 1758 /// Applies dynamic knowledge to simplify SCEV expressions in the context 1759 /// of existing SCEV assumptions. The analysis will also add a minimal set 1760 /// of new predicates if this is required to enable vectorization and 1761 /// unrolling. 1762 PredicatedScalarEvolution &PSE; 1763 /// Target Library Info. 1764 TargetLibraryInfo *TLI; 1765 /// Target Transform Info 1766 const TargetTransformInfo *TTI; 1767 /// Dominator Tree. 1768 DominatorTree *DT; 1769 // LoopAccess analysis. 1770 std::function<const LoopAccessInfo &(Loop &)> *GetLAA; 1771 // And the loop-accesses info corresponding to this loop. This pointer is 1772 // null until canVectorizeMemory sets it up. 1773 const LoopAccessInfo *LAI; 1774 /// Interface to emit optimization remarks. 1775 OptimizationRemarkEmitter *ORE; 1776 1777 /// The interleave access information contains groups of interleaved accesses 1778 /// with the same stride and close to each other. 1779 InterleavedAccessInfo InterleaveInfo; 1780 1781 // --- vectorization state --- // 1782 1783 /// Holds the integer induction variable. This is the counter of the 1784 /// loop. 1785 PHINode *Induction; 1786 /// Holds the reduction variables. 1787 ReductionList Reductions; 1788 /// Holds all of the induction variables that we found in the loop. 1789 /// Notice that inductions don't need to start at zero and that induction 1790 /// variables can be pointers. 1791 InductionList Inductions; 1792 /// Holds the phi nodes that are first-order recurrences. 1793 RecurrenceSet FirstOrderRecurrences; 1794 /// Holds the widest induction type encountered. 1795 Type *WidestIndTy; 1796 1797 /// Allowed outside users. This holds the induction and reduction 1798 /// vars which can be accessed from outside the loop. 1799 SmallPtrSet<Value *, 4> AllowedExit; 1800 1801 /// Holds the instructions known to be uniform after vectorization. 1802 SmallPtrSet<Instruction *, 4> Uniforms; 1803 1804 /// Holds the instructions known to be scalar after vectorization. 1805 SmallPtrSet<Instruction *, 4> Scalars; 1806 1807 /// Can we assume the absence of NaNs. 1808 bool HasFunNoNaNAttr; 1809 1810 /// Vectorization requirements that will go through late-evaluation. 1811 LoopVectorizationRequirements *Requirements; 1812 1813 /// Used to emit an analysis of any legality issues. 1814 LoopVectorizeHints *Hints; 1815 1816 /// While vectorizing these instructions we have to generate a 1817 /// call to the appropriate masked intrinsic 1818 SmallPtrSet<const Instruction *, 8> MaskedOp; 1819 }; 1820 1821 /// LoopVectorizationCostModel - estimates the expected speedups due to 1822 /// vectorization. 1823 /// In many cases vectorization is not profitable. This can happen because of 1824 /// a number of reasons. In this class we mainly attempt to predict the 1825 /// expected speedup/slowdowns due to the supported instruction set. We use the 1826 /// TargetTransformInfo to query the different backends for the cost of 1827 /// different operations. 1828 class LoopVectorizationCostModel { 1829 public: 1830 LoopVectorizationCostModel(Loop *L, PredicatedScalarEvolution &PSE, 1831 LoopInfo *LI, LoopVectorizationLegality *Legal, 1832 const TargetTransformInfo &TTI, 1833 const TargetLibraryInfo *TLI, DemandedBits *DB, 1834 AssumptionCache *AC, 1835 OptimizationRemarkEmitter *ORE, const Function *F, 1836 const LoopVectorizeHints *Hints) 1837 : TheLoop(L), PSE(PSE), LI(LI), Legal(Legal), TTI(TTI), TLI(TLI), DB(DB), 1838 AC(AC), ORE(ORE), TheFunction(F), Hints(Hints) {} 1839 1840 /// Information about vectorization costs 1841 struct VectorizationFactor { 1842 unsigned Width; // Vector width with best cost 1843 unsigned Cost; // Cost of the loop with that width 1844 }; 1845 /// \return The most profitable vectorization factor and the cost of that VF. 1846 /// This method checks every power of two up to VF. If UserVF is not ZERO 1847 /// then this vectorization factor will be selected if vectorization is 1848 /// possible. 1849 VectorizationFactor selectVectorizationFactor(bool OptForSize); 1850 1851 /// \return The size (in bits) of the smallest and widest types in the code 1852 /// that needs to be vectorized. We ignore values that remain scalar such as 1853 /// 64 bit loop indices. 1854 std::pair<unsigned, unsigned> getSmallestAndWidestTypes(); 1855 1856 /// \return The desired interleave count. 1857 /// If interleave count has been specified by metadata it will be returned. 1858 /// Otherwise, the interleave count is computed and returned. VF and LoopCost 1859 /// are the selected vectorization factor and the cost of the selected VF. 1860 unsigned selectInterleaveCount(bool OptForSize, unsigned VF, 1861 unsigned LoopCost); 1862 1863 /// \return The most profitable unroll factor. 1864 /// This method finds the best unroll-factor based on register pressure and 1865 /// other parameters. VF and LoopCost are the selected vectorization factor 1866 /// and the cost of the selected VF. 1867 unsigned computeInterleaveCount(bool OptForSize, unsigned VF, 1868 unsigned LoopCost); 1869 1870 /// \brief A struct that represents some properties of the register usage 1871 /// of a loop. 1872 struct RegisterUsage { 1873 /// Holds the number of loop invariant values that are used in the loop. 1874 unsigned LoopInvariantRegs; 1875 /// Holds the maximum number of concurrent live intervals in the loop. 1876 unsigned MaxLocalUsers; 1877 /// Holds the number of instructions in the loop. 1878 unsigned NumInstructions; 1879 }; 1880 1881 /// \return Returns information about the register usages of the loop for the 1882 /// given vectorization factors. 1883 SmallVector<RegisterUsage, 8> calculateRegisterUsage(ArrayRef<unsigned> VFs); 1884 1885 /// Collect values we want to ignore in the cost model. 1886 void collectValuesToIgnore(); 1887 1888 /// \returns The smallest bitwidth each instruction can be represented with. 1889 /// The vector equivalents of these instructions should be truncated to this 1890 /// type. 1891 const MapVector<Instruction *, uint64_t> &getMinimalBitwidths() const { 1892 return MinBWs; 1893 } 1894 1895 private: 1896 /// The vectorization cost is a combination of the cost itself and a boolean 1897 /// indicating whether any of the contributing operations will actually 1898 /// operate on 1899 /// vector values after type legalization in the backend. If this latter value 1900 /// is 1901 /// false, then all operations will be scalarized (i.e. no vectorization has 1902 /// actually taken place). 1903 typedef std::pair<unsigned, bool> VectorizationCostTy; 1904 1905 /// Returns the expected execution cost. The unit of the cost does 1906 /// not matter because we use the 'cost' units to compare different 1907 /// vector widths. The cost that is returned is *not* normalized by 1908 /// the factor width. 1909 VectorizationCostTy expectedCost(unsigned VF); 1910 1911 /// Returns the execution time cost of an instruction for a given vector 1912 /// width. Vector width of one means scalar. 1913 VectorizationCostTy getInstructionCost(Instruction *I, unsigned VF); 1914 1915 /// The cost-computation logic from getInstructionCost which provides 1916 /// the vector type as an output parameter. 1917 unsigned getInstructionCost(Instruction *I, unsigned VF, Type *&VectorTy); 1918 1919 /// Returns whether the instruction is a load or store and will be a emitted 1920 /// as a vector operation. 1921 bool isConsecutiveLoadOrStore(Instruction *I); 1922 1923 /// Create an analysis remark that explains why vectorization failed 1924 /// 1925 /// \p RemarkName is the identifier for the remark. \return the remark object 1926 /// that can be streamed to. 1927 OptimizationRemarkAnalysis createMissedAnalysis(StringRef RemarkName) { 1928 return ::createMissedAnalysis(Hints->vectorizeAnalysisPassName(), 1929 RemarkName, TheLoop); 1930 } 1931 1932 /// Map of scalar integer values to the smallest bitwidth they can be legally 1933 /// represented as. The vector equivalents of these values should be truncated 1934 /// to this type. 1935 MapVector<Instruction *, uint64_t> MinBWs; 1936 1937 public: 1938 /// The loop that we evaluate. 1939 Loop *TheLoop; 1940 /// Predicated scalar evolution analysis. 1941 PredicatedScalarEvolution &PSE; 1942 /// Loop Info analysis. 1943 LoopInfo *LI; 1944 /// Vectorization legality. 1945 LoopVectorizationLegality *Legal; 1946 /// Vector target information. 1947 const TargetTransformInfo &TTI; 1948 /// Target Library Info. 1949 const TargetLibraryInfo *TLI; 1950 /// Demanded bits analysis. 1951 DemandedBits *DB; 1952 /// Assumption cache. 1953 AssumptionCache *AC; 1954 /// Interface to emit optimization remarks. 1955 OptimizationRemarkEmitter *ORE; 1956 1957 const Function *TheFunction; 1958 /// Loop Vectorize Hint. 1959 const LoopVectorizeHints *Hints; 1960 /// Values to ignore in the cost model. 1961 SmallPtrSet<const Value *, 16> ValuesToIgnore; 1962 /// Values to ignore in the cost model when VF > 1. 1963 SmallPtrSet<const Value *, 16> VecValuesToIgnore; 1964 }; 1965 1966 /// \brief This holds vectorization requirements that must be verified late in 1967 /// the process. The requirements are set by legalize and costmodel. Once 1968 /// vectorization has been determined to be possible and profitable the 1969 /// requirements can be verified by looking for metadata or compiler options. 1970 /// For example, some loops require FP commutativity which is only allowed if 1971 /// vectorization is explicitly specified or if the fast-math compiler option 1972 /// has been provided. 1973 /// Late evaluation of these requirements allows helpful diagnostics to be 1974 /// composed that tells the user what need to be done to vectorize the loop. For 1975 /// example, by specifying #pragma clang loop vectorize or -ffast-math. Late 1976 /// evaluation should be used only when diagnostics can generated that can be 1977 /// followed by a non-expert user. 1978 class LoopVectorizationRequirements { 1979 public: 1980 LoopVectorizationRequirements(OptimizationRemarkEmitter &ORE) 1981 : NumRuntimePointerChecks(0), UnsafeAlgebraInst(nullptr), ORE(ORE) {} 1982 1983 void addUnsafeAlgebraInst(Instruction *I) { 1984 // First unsafe algebra instruction. 1985 if (!UnsafeAlgebraInst) 1986 UnsafeAlgebraInst = I; 1987 } 1988 1989 void addRuntimePointerChecks(unsigned Num) { NumRuntimePointerChecks = Num; } 1990 1991 bool doesNotMeet(Function *F, Loop *L, const LoopVectorizeHints &Hints) { 1992 const char *PassName = Hints.vectorizeAnalysisPassName(); 1993 bool Failed = false; 1994 if (UnsafeAlgebraInst && !Hints.allowReordering()) { 1995 ORE.emit( 1996 OptimizationRemarkAnalysisFPCommute(PassName, "CantReorderFPOps", 1997 UnsafeAlgebraInst->getDebugLoc(), 1998 UnsafeAlgebraInst->getParent()) 1999 << "loop not vectorized: cannot prove it is safe to reorder " 2000 "floating-point operations"); 2001 Failed = true; 2002 } 2003 2004 // Test if runtime memcheck thresholds are exceeded. 2005 bool PragmaThresholdReached = 2006 NumRuntimePointerChecks > PragmaVectorizeMemoryCheckThreshold; 2007 bool ThresholdReached = 2008 NumRuntimePointerChecks > VectorizerParams::RuntimeMemoryCheckThreshold; 2009 if ((ThresholdReached && !Hints.allowReordering()) || 2010 PragmaThresholdReached) { 2011 ORE.emit(OptimizationRemarkAnalysisAliasing(PassName, "CantReorderMemOps", 2012 L->getStartLoc(), 2013 L->getHeader()) 2014 << "loop not vectorized: cannot prove it is safe to reorder " 2015 "memory operations"); 2016 DEBUG(dbgs() << "LV: Too many memory checks needed.\n"); 2017 Failed = true; 2018 } 2019 2020 return Failed; 2021 } 2022 2023 private: 2024 unsigned NumRuntimePointerChecks; 2025 Instruction *UnsafeAlgebraInst; 2026 2027 /// Interface to emit optimization remarks. 2028 OptimizationRemarkEmitter &ORE; 2029 }; 2030 2031 static void addAcyclicInnerLoop(Loop &L, SmallVectorImpl<Loop *> &V) { 2032 if (L.empty()) { 2033 if (!hasCyclesInLoopBody(L)) 2034 V.push_back(&L); 2035 return; 2036 } 2037 for (Loop *InnerL : L) 2038 addAcyclicInnerLoop(*InnerL, V); 2039 } 2040 2041 /// The LoopVectorize Pass. 2042 struct LoopVectorize : public FunctionPass { 2043 /// Pass identification, replacement for typeid 2044 static char ID; 2045 2046 explicit LoopVectorize(bool NoUnrolling = false, bool AlwaysVectorize = true) 2047 : FunctionPass(ID) { 2048 Impl.DisableUnrolling = NoUnrolling; 2049 Impl.AlwaysVectorize = AlwaysVectorize; 2050 initializeLoopVectorizePass(*PassRegistry::getPassRegistry()); 2051 } 2052 2053 LoopVectorizePass Impl; 2054 2055 bool runOnFunction(Function &F) override { 2056 if (skipFunction(F)) 2057 return false; 2058 2059 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 2060 auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 2061 auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 2062 auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 2063 auto *BFI = &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI(); 2064 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>(); 2065 auto *TLI = TLIP ? &TLIP->getTLI() : nullptr; 2066 auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); 2067 auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); 2068 auto *LAA = &getAnalysis<LoopAccessLegacyAnalysis>(); 2069 auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits(); 2070 auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE(); 2071 2072 std::function<const LoopAccessInfo &(Loop &)> GetLAA = 2073 [&](Loop &L) -> const LoopAccessInfo & { return LAA->getInfo(&L); }; 2074 2075 return Impl.runImpl(F, *SE, *LI, *TTI, *DT, *BFI, TLI, *DB, *AA, *AC, 2076 GetLAA, *ORE); 2077 } 2078 2079 void getAnalysisUsage(AnalysisUsage &AU) const override { 2080 AU.addRequired<AssumptionCacheTracker>(); 2081 AU.addRequiredID(LoopSimplifyID); 2082 AU.addRequiredID(LCSSAID); 2083 AU.addRequired<BlockFrequencyInfoWrapperPass>(); 2084 AU.addRequired<DominatorTreeWrapperPass>(); 2085 AU.addRequired<LoopInfoWrapperPass>(); 2086 AU.addRequired<ScalarEvolutionWrapperPass>(); 2087 AU.addRequired<TargetTransformInfoWrapperPass>(); 2088 AU.addRequired<AAResultsWrapperPass>(); 2089 AU.addRequired<LoopAccessLegacyAnalysis>(); 2090 AU.addRequired<DemandedBitsWrapperPass>(); 2091 AU.addRequired<OptimizationRemarkEmitterWrapperPass>(); 2092 AU.addPreserved<LoopInfoWrapperPass>(); 2093 AU.addPreserved<DominatorTreeWrapperPass>(); 2094 AU.addPreserved<BasicAAWrapperPass>(); 2095 AU.addPreserved<GlobalsAAWrapperPass>(); 2096 } 2097 }; 2098 2099 } // end anonymous namespace 2100 2101 //===----------------------------------------------------------------------===// 2102 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and 2103 // LoopVectorizationCostModel. 2104 //===----------------------------------------------------------------------===// 2105 2106 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) { 2107 // We need to place the broadcast of invariant variables outside the loop. 2108 Instruction *Instr = dyn_cast<Instruction>(V); 2109 bool NewInstr = (Instr && Instr->getParent() == LoopVectorBody); 2110 bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr; 2111 2112 // Place the code for broadcasting invariant variables in the new preheader. 2113 IRBuilder<>::InsertPointGuard Guard(Builder); 2114 if (Invariant) 2115 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator()); 2116 2117 // Broadcast the scalar into all locations in the vector. 2118 Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast"); 2119 2120 return Shuf; 2121 } 2122 2123 void InnerLoopVectorizer::createVectorIntInductionPHI( 2124 const InductionDescriptor &II, Instruction *EntryVal) { 2125 Value *Start = II.getStartValue(); 2126 ConstantInt *Step = II.getConstIntStepValue(); 2127 assert(Step && "Can not widen an IV with a non-constant step"); 2128 2129 // Construct the initial value of the vector IV in the vector loop preheader 2130 auto CurrIP = Builder.saveIP(); 2131 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator()); 2132 if (isa<TruncInst>(EntryVal)) { 2133 auto *TruncType = cast<IntegerType>(EntryVal->getType()); 2134 Step = ConstantInt::getSigned(TruncType, Step->getSExtValue()); 2135 Start = Builder.CreateCast(Instruction::Trunc, Start, TruncType); 2136 } 2137 Value *SplatStart = Builder.CreateVectorSplat(VF, Start); 2138 Value *SteppedStart = getStepVector(SplatStart, 0, Step); 2139 Builder.restoreIP(CurrIP); 2140 2141 Value *SplatVF = 2142 ConstantVector::getSplat(VF, ConstantInt::getSigned(Start->getType(), 2143 VF * Step->getSExtValue())); 2144 // We may need to add the step a number of times, depending on the unroll 2145 // factor. The last of those goes into the PHI. 2146 PHINode *VecInd = PHINode::Create(SteppedStart->getType(), 2, "vec.ind", 2147 &*LoopVectorBody->getFirstInsertionPt()); 2148 Instruction *LastInduction = VecInd; 2149 VectorParts Entry(UF); 2150 for (unsigned Part = 0; Part < UF; ++Part) { 2151 Entry[Part] = LastInduction; 2152 LastInduction = cast<Instruction>( 2153 Builder.CreateAdd(LastInduction, SplatVF, "step.add")); 2154 } 2155 VectorLoopValueMap.initVector(EntryVal, Entry); 2156 if (isa<TruncInst>(EntryVal)) 2157 addMetadata(Entry, EntryVal); 2158 2159 // Move the last step to the end of the latch block. This ensures consistent 2160 // placement of all induction updates. 2161 auto *LoopVectorLatch = LI->getLoopFor(LoopVectorBody)->getLoopLatch(); 2162 auto *Br = cast<BranchInst>(LoopVectorLatch->getTerminator()); 2163 auto *ICmp = cast<Instruction>(Br->getCondition()); 2164 LastInduction->moveBefore(ICmp); 2165 LastInduction->setName("vec.ind.next"); 2166 2167 VecInd->addIncoming(SteppedStart, LoopVectorPreHeader); 2168 VecInd->addIncoming(LastInduction, LoopVectorLatch); 2169 } 2170 2171 bool InnerLoopVectorizer::needsScalarInduction(Instruction *IV) const { 2172 if (Legal->isScalarAfterVectorization(IV)) 2173 return true; 2174 auto isScalarInst = [&](User *U) -> bool { 2175 auto *I = cast<Instruction>(U); 2176 return (OrigLoop->contains(I) && Legal->isScalarAfterVectorization(I)); 2177 }; 2178 return any_of(IV->users(), isScalarInst); 2179 } 2180 2181 void InnerLoopVectorizer::widenIntInduction(PHINode *IV, TruncInst *Trunc) { 2182 2183 auto II = Legal->getInductionVars()->find(IV); 2184 assert(II != Legal->getInductionVars()->end() && "IV is not an induction"); 2185 2186 auto ID = II->second; 2187 assert(IV->getType() == ID.getStartValue()->getType() && "Types must match"); 2188 2189 // The scalar value to broadcast. This will be derived from the canonical 2190 // induction variable. 2191 Value *ScalarIV = nullptr; 2192 2193 // The step of the induction. 2194 Value *Step = nullptr; 2195 2196 // The value from the original loop to which we are mapping the new induction 2197 // variable. 2198 Instruction *EntryVal = Trunc ? cast<Instruction>(Trunc) : IV; 2199 2200 // True if we have vectorized the induction variable. 2201 auto VectorizedIV = false; 2202 2203 // Determine if we want a scalar version of the induction variable. This is 2204 // true if the induction variable itself is not widened, or if it has at 2205 // least one user in the loop that is not widened. 2206 auto NeedsScalarIV = VF > 1 && needsScalarInduction(EntryVal); 2207 2208 // If the induction variable has a constant integer step value, go ahead and 2209 // get it now. 2210 if (ID.getConstIntStepValue()) 2211 Step = ID.getConstIntStepValue(); 2212 2213 // Try to create a new independent vector induction variable. If we can't 2214 // create the phi node, we will splat the scalar induction variable in each 2215 // loop iteration. 2216 if (VF > 1 && IV->getType() == Induction->getType() && Step && 2217 !Legal->isScalarAfterVectorization(EntryVal)) { 2218 createVectorIntInductionPHI(ID, EntryVal); 2219 VectorizedIV = true; 2220 } 2221 2222 // If we haven't yet vectorized the induction variable, or if we will create 2223 // a scalar one, we need to define the scalar induction variable and step 2224 // values. If we were given a truncation type, truncate the canonical 2225 // induction variable and constant step. Otherwise, derive these values from 2226 // the induction descriptor. 2227 if (!VectorizedIV || NeedsScalarIV) { 2228 if (Trunc) { 2229 auto *TruncType = cast<IntegerType>(Trunc->getType()); 2230 assert(Step && "Truncation requires constant integer step"); 2231 auto StepInt = cast<ConstantInt>(Step)->getSExtValue(); 2232 ScalarIV = Builder.CreateCast(Instruction::Trunc, Induction, TruncType); 2233 Step = ConstantInt::getSigned(TruncType, StepInt); 2234 } else { 2235 ScalarIV = Induction; 2236 auto &DL = OrigLoop->getHeader()->getModule()->getDataLayout(); 2237 if (IV != OldInduction) { 2238 ScalarIV = Builder.CreateSExtOrTrunc(ScalarIV, IV->getType()); 2239 ScalarIV = ID.transform(Builder, ScalarIV, PSE.getSE(), DL); 2240 ScalarIV->setName("offset.idx"); 2241 } 2242 if (!Step) { 2243 SCEVExpander Exp(*PSE.getSE(), DL, "induction"); 2244 Step = Exp.expandCodeFor(ID.getStep(), ID.getStep()->getType(), 2245 &*Builder.GetInsertPoint()); 2246 } 2247 } 2248 } 2249 2250 // If we haven't yet vectorized the induction variable, splat the scalar 2251 // induction variable, and build the necessary step vectors. 2252 if (!VectorizedIV) { 2253 Value *Broadcasted = getBroadcastInstrs(ScalarIV); 2254 VectorParts Entry(UF); 2255 for (unsigned Part = 0; Part < UF; ++Part) 2256 Entry[Part] = getStepVector(Broadcasted, VF * Part, Step); 2257 VectorLoopValueMap.initVector(EntryVal, Entry); 2258 if (Trunc) 2259 addMetadata(Entry, Trunc); 2260 } 2261 2262 // If an induction variable is only used for counting loop iterations or 2263 // calculating addresses, it doesn't need to be widened. Create scalar steps 2264 // that can be used by instructions we will later scalarize. Note that the 2265 // addition of the scalar steps will not increase the number of instructions 2266 // in the loop in the common case prior to InstCombine. We will be trading 2267 // one vector extract for each scalar step. 2268 if (NeedsScalarIV) 2269 buildScalarSteps(ScalarIV, Step, EntryVal); 2270 } 2271 2272 Value *InnerLoopVectorizer::getStepVector(Value *Val, int StartIdx, Value *Step, 2273 Instruction::BinaryOps BinOp) { 2274 // Create and check the types. 2275 assert(Val->getType()->isVectorTy() && "Must be a vector"); 2276 int VLen = Val->getType()->getVectorNumElements(); 2277 2278 Type *STy = Val->getType()->getScalarType(); 2279 assert((STy->isIntegerTy() || STy->isFloatingPointTy()) && 2280 "Induction Step must be an integer or FP"); 2281 assert(Step->getType() == STy && "Step has wrong type"); 2282 2283 SmallVector<Constant *, 8> Indices; 2284 2285 if (STy->isIntegerTy()) { 2286 // Create a vector of consecutive numbers from zero to VF. 2287 for (int i = 0; i < VLen; ++i) 2288 Indices.push_back(ConstantInt::get(STy, StartIdx + i)); 2289 2290 // Add the consecutive indices to the vector value. 2291 Constant *Cv = ConstantVector::get(Indices); 2292 assert(Cv->getType() == Val->getType() && "Invalid consecutive vec"); 2293 Step = Builder.CreateVectorSplat(VLen, Step); 2294 assert(Step->getType() == Val->getType() && "Invalid step vec"); 2295 // FIXME: The newly created binary instructions should contain nsw/nuw flags, 2296 // which can be found from the original scalar operations. 2297 Step = Builder.CreateMul(Cv, Step); 2298 return Builder.CreateAdd(Val, Step, "induction"); 2299 } 2300 2301 // Floating point induction. 2302 assert((BinOp == Instruction::FAdd || BinOp == Instruction::FSub) && 2303 "Binary Opcode should be specified for FP induction"); 2304 // Create a vector of consecutive numbers from zero to VF. 2305 for (int i = 0; i < VLen; ++i) 2306 Indices.push_back(ConstantFP::get(STy, (double)(StartIdx + i))); 2307 2308 // Add the consecutive indices to the vector value. 2309 Constant *Cv = ConstantVector::get(Indices); 2310 2311 Step = Builder.CreateVectorSplat(VLen, Step); 2312 2313 // Floating point operations had to be 'fast' to enable the induction. 2314 FastMathFlags Flags; 2315 Flags.setUnsafeAlgebra(); 2316 2317 Value *MulOp = Builder.CreateFMul(Cv, Step); 2318 if (isa<Instruction>(MulOp)) 2319 // Have to check, MulOp may be a constant 2320 cast<Instruction>(MulOp)->setFastMathFlags(Flags); 2321 2322 Value *BOp = Builder.CreateBinOp(BinOp, Val, MulOp, "induction"); 2323 if (isa<Instruction>(BOp)) 2324 cast<Instruction>(BOp)->setFastMathFlags(Flags); 2325 return BOp; 2326 } 2327 2328 void InnerLoopVectorizer::buildScalarSteps(Value *ScalarIV, Value *Step, 2329 Value *EntryVal) { 2330 2331 // We shouldn't have to build scalar steps if we aren't vectorizing. 2332 assert(VF > 1 && "VF should be greater than one"); 2333 2334 // Get the value type and ensure it and the step have the same integer type. 2335 Type *ScalarIVTy = ScalarIV->getType()->getScalarType(); 2336 assert(ScalarIVTy->isIntegerTy() && ScalarIVTy == Step->getType() && 2337 "Val and Step should have the same integer type"); 2338 2339 // Determine the number of scalars we need to generate for each unroll 2340 // iteration. If EntryVal is uniform, we only need to generate the first 2341 // lane. Otherwise, we generate all VF values. 2342 unsigned Lanes = 2343 Legal->isUniformAfterVectorization(cast<Instruction>(EntryVal)) ? 1 : VF; 2344 2345 // Compute the scalar steps and save the results in VectorLoopValueMap. 2346 ScalarParts Entry(UF); 2347 for (unsigned Part = 0; Part < UF; ++Part) { 2348 Entry[Part].resize(VF); 2349 for (unsigned Lane = 0; Lane < Lanes; ++Lane) { 2350 auto *StartIdx = ConstantInt::get(ScalarIVTy, VF * Part + Lane); 2351 auto *Mul = Builder.CreateMul(StartIdx, Step); 2352 auto *Add = Builder.CreateAdd(ScalarIV, Mul); 2353 Entry[Part][Lane] = Add; 2354 } 2355 } 2356 VectorLoopValueMap.initScalar(EntryVal, Entry); 2357 } 2358 2359 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) { 2360 2361 const ValueToValueMap &Strides = getSymbolicStrides() ? *getSymbolicStrides() : 2362 ValueToValueMap(); 2363 2364 int Stride = getPtrStride(PSE, Ptr, TheLoop, Strides, true, false); 2365 if (Stride == 1 || Stride == -1) 2366 return Stride; 2367 return 0; 2368 } 2369 2370 bool LoopVectorizationLegality::isUniform(Value *V) { 2371 return LAI->isUniform(V); 2372 } 2373 2374 const InnerLoopVectorizer::VectorParts & 2375 InnerLoopVectorizer::getVectorValue(Value *V) { 2376 assert(V != Induction && "The new induction variable should not be used."); 2377 assert(!V->getType()->isVectorTy() && "Can't widen a vector"); 2378 assert(!V->getType()->isVoidTy() && "Type does not produce a value"); 2379 2380 // If we have a stride that is replaced by one, do it here. 2381 if (Legal->hasStride(V)) 2382 V = ConstantInt::get(V->getType(), 1); 2383 2384 // If we have this scalar in the map, return it. 2385 if (VectorLoopValueMap.hasVector(V)) 2386 return VectorLoopValueMap.VectorMapStorage[V]; 2387 2388 // If the value has not been vectorized, check if it has been scalarized 2389 // instead. If it has been scalarized, and we actually need the value in 2390 // vector form, we will construct the vector values on demand. 2391 if (VectorLoopValueMap.hasScalar(V)) { 2392 2393 // Initialize a new vector map entry. 2394 VectorParts Entry(UF); 2395 2396 // If we've scalarized a value, that value should be an instruction. 2397 auto *I = cast<Instruction>(V); 2398 2399 // If we aren't vectorizing, we can just copy the scalar map values over to 2400 // the vector map. 2401 if (VF == 1) { 2402 for (unsigned Part = 0; Part < UF; ++Part) 2403 Entry[Part] = getScalarValue(V, Part, 0); 2404 return VectorLoopValueMap.initVector(V, Entry); 2405 } 2406 2407 // Get the last scalar instruction we generated for V. If the value is 2408 // known to be uniform after vectorization, this corresponds to lane zero 2409 // of the last unroll iteration. Otherwise, the last instruction is the one 2410 // we created for the last vector lane of the last unroll iteration. 2411 unsigned LastLane = Legal->isUniformAfterVectorization(I) ? 0 : VF - 1; 2412 auto *LastInst = cast<Instruction>(getScalarValue(V, UF - 1, LastLane)); 2413 2414 // Set the insert point after the last scalarized instruction. This ensures 2415 // the insertelement sequence will directly follow the scalar definitions. 2416 auto OldIP = Builder.saveIP(); 2417 auto NewIP = std::next(BasicBlock::iterator(LastInst)); 2418 Builder.SetInsertPoint(&*NewIP); 2419 2420 // However, if we are vectorizing, we need to construct the vector values. 2421 // If the value is known to be uniform after vectorization, we can just 2422 // broadcast the scalar value corresponding to lane zero for each unroll 2423 // iteration. Otherwise, we construct the vector values using insertelement 2424 // instructions. Since the resulting vectors are stored in 2425 // VectorLoopValueMap, we will only generate the insertelements once. 2426 for (unsigned Part = 0; Part < UF; ++Part) { 2427 Value *VectorValue = nullptr; 2428 if (Legal->isUniformAfterVectorization(I)) { 2429 VectorValue = getBroadcastInstrs(getScalarValue(V, Part, 0)); 2430 } else { 2431 VectorValue = UndefValue::get(VectorType::get(V->getType(), VF)); 2432 for (unsigned Lane = 0; Lane < VF; ++Lane) 2433 VectorValue = Builder.CreateInsertElement( 2434 VectorValue, getScalarValue(V, Part, Lane), 2435 Builder.getInt32(Lane)); 2436 } 2437 Entry[Part] = VectorValue; 2438 } 2439 Builder.restoreIP(OldIP); 2440 return VectorLoopValueMap.initVector(V, Entry); 2441 } 2442 2443 // If this scalar is unknown, assume that it is a constant or that it is 2444 // loop invariant. Broadcast V and save the value for future uses. 2445 Value *B = getBroadcastInstrs(V); 2446 return VectorLoopValueMap.initVector(V, VectorParts(UF, B)); 2447 } 2448 2449 Value *InnerLoopVectorizer::getScalarValue(Value *V, unsigned Part, 2450 unsigned Lane) { 2451 2452 // If the value is not an instruction contained in the loop, it should 2453 // already be scalar. 2454 if (OrigLoop->isLoopInvariant(V)) 2455 return V; 2456 2457 assert(Lane > 0 ? !Legal->isUniformAfterVectorization(cast<Instruction>(V)) 2458 : true && "Uniform values only have lane zero"); 2459 2460 // If the value from the original loop has not been vectorized, it is 2461 // represented by UF x VF scalar values in the new loop. Return the requested 2462 // scalar value. 2463 if (VectorLoopValueMap.hasScalar(V)) 2464 return VectorLoopValueMap.ScalarMapStorage[V][Part][Lane]; 2465 2466 // If the value has not been scalarized, get its entry in VectorLoopValueMap 2467 // for the given unroll part. If this entry is not a vector type (i.e., the 2468 // vectorization factor is one), there is no need to generate an 2469 // extractelement instruction. 2470 auto *U = getVectorValue(V)[Part]; 2471 if (!U->getType()->isVectorTy()) { 2472 assert(VF == 1 && "Value not scalarized has non-vector type"); 2473 return U; 2474 } 2475 2476 // Otherwise, the value from the original loop has been vectorized and is 2477 // represented by UF vector values. Extract and return the requested scalar 2478 // value from the appropriate vector lane. 2479 return Builder.CreateExtractElement(U, Builder.getInt32(Lane)); 2480 } 2481 2482 Value *InnerLoopVectorizer::reverseVector(Value *Vec) { 2483 assert(Vec->getType()->isVectorTy() && "Invalid type"); 2484 SmallVector<Constant *, 8> ShuffleMask; 2485 for (unsigned i = 0; i < VF; ++i) 2486 ShuffleMask.push_back(Builder.getInt32(VF - i - 1)); 2487 2488 return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()), 2489 ConstantVector::get(ShuffleMask), 2490 "reverse"); 2491 } 2492 2493 // Get a mask to interleave \p NumVec vectors into a wide vector. 2494 // I.e. <0, VF, VF*2, ..., VF*(NumVec-1), 1, VF+1, VF*2+1, ...> 2495 // E.g. For 2 interleaved vectors, if VF is 4, the mask is: 2496 // <0, 4, 1, 5, 2, 6, 3, 7> 2497 static Constant *getInterleavedMask(IRBuilder<> &Builder, unsigned VF, 2498 unsigned NumVec) { 2499 SmallVector<Constant *, 16> Mask; 2500 for (unsigned i = 0; i < VF; i++) 2501 for (unsigned j = 0; j < NumVec; j++) 2502 Mask.push_back(Builder.getInt32(j * VF + i)); 2503 2504 return ConstantVector::get(Mask); 2505 } 2506 2507 // Get the strided mask starting from index \p Start. 2508 // I.e. <Start, Start + Stride, ..., Start + Stride*(VF-1)> 2509 static Constant *getStridedMask(IRBuilder<> &Builder, unsigned Start, 2510 unsigned Stride, unsigned VF) { 2511 SmallVector<Constant *, 16> Mask; 2512 for (unsigned i = 0; i < VF; i++) 2513 Mask.push_back(Builder.getInt32(Start + i * Stride)); 2514 2515 return ConstantVector::get(Mask); 2516 } 2517 2518 // Get a mask of two parts: The first part consists of sequential integers 2519 // starting from 0, The second part consists of UNDEFs. 2520 // I.e. <0, 1, 2, ..., NumInt - 1, undef, ..., undef> 2521 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned NumInt, 2522 unsigned NumUndef) { 2523 SmallVector<Constant *, 16> Mask; 2524 for (unsigned i = 0; i < NumInt; i++) 2525 Mask.push_back(Builder.getInt32(i)); 2526 2527 Constant *Undef = UndefValue::get(Builder.getInt32Ty()); 2528 for (unsigned i = 0; i < NumUndef; i++) 2529 Mask.push_back(Undef); 2530 2531 return ConstantVector::get(Mask); 2532 } 2533 2534 // Concatenate two vectors with the same element type. The 2nd vector should 2535 // not have more elements than the 1st vector. If the 2nd vector has less 2536 // elements, extend it with UNDEFs. 2537 static Value *ConcatenateTwoVectors(IRBuilder<> &Builder, Value *V1, 2538 Value *V2) { 2539 VectorType *VecTy1 = dyn_cast<VectorType>(V1->getType()); 2540 VectorType *VecTy2 = dyn_cast<VectorType>(V2->getType()); 2541 assert(VecTy1 && VecTy2 && 2542 VecTy1->getScalarType() == VecTy2->getScalarType() && 2543 "Expect two vectors with the same element type"); 2544 2545 unsigned NumElts1 = VecTy1->getNumElements(); 2546 unsigned NumElts2 = VecTy2->getNumElements(); 2547 assert(NumElts1 >= NumElts2 && "Unexpect the first vector has less elements"); 2548 2549 if (NumElts1 > NumElts2) { 2550 // Extend with UNDEFs. 2551 Constant *ExtMask = 2552 getSequentialMask(Builder, NumElts2, NumElts1 - NumElts2); 2553 V2 = Builder.CreateShuffleVector(V2, UndefValue::get(VecTy2), ExtMask); 2554 } 2555 2556 Constant *Mask = getSequentialMask(Builder, NumElts1 + NumElts2, 0); 2557 return Builder.CreateShuffleVector(V1, V2, Mask); 2558 } 2559 2560 // Concatenate vectors in the given list. All vectors have the same type. 2561 static Value *ConcatenateVectors(IRBuilder<> &Builder, 2562 ArrayRef<Value *> InputList) { 2563 unsigned NumVec = InputList.size(); 2564 assert(NumVec > 1 && "Should be at least two vectors"); 2565 2566 SmallVector<Value *, 8> ResList; 2567 ResList.append(InputList.begin(), InputList.end()); 2568 do { 2569 SmallVector<Value *, 8> TmpList; 2570 for (unsigned i = 0; i < NumVec - 1; i += 2) { 2571 Value *V0 = ResList[i], *V1 = ResList[i + 1]; 2572 assert((V0->getType() == V1->getType() || i == NumVec - 2) && 2573 "Only the last vector may have a different type"); 2574 2575 TmpList.push_back(ConcatenateTwoVectors(Builder, V0, V1)); 2576 } 2577 2578 // Push the last vector if the total number of vectors is odd. 2579 if (NumVec % 2 != 0) 2580 TmpList.push_back(ResList[NumVec - 1]); 2581 2582 ResList = TmpList; 2583 NumVec = ResList.size(); 2584 } while (NumVec > 1); 2585 2586 return ResList[0]; 2587 } 2588 2589 // Try to vectorize the interleave group that \p Instr belongs to. 2590 // 2591 // E.g. Translate following interleaved load group (factor = 3): 2592 // for (i = 0; i < N; i+=3) { 2593 // R = Pic[i]; // Member of index 0 2594 // G = Pic[i+1]; // Member of index 1 2595 // B = Pic[i+2]; // Member of index 2 2596 // ... // do something to R, G, B 2597 // } 2598 // To: 2599 // %wide.vec = load <12 x i32> ; Read 4 tuples of R,G,B 2600 // %R.vec = shuffle %wide.vec, undef, <0, 3, 6, 9> ; R elements 2601 // %G.vec = shuffle %wide.vec, undef, <1, 4, 7, 10> ; G elements 2602 // %B.vec = shuffle %wide.vec, undef, <2, 5, 8, 11> ; B elements 2603 // 2604 // Or translate following interleaved store group (factor = 3): 2605 // for (i = 0; i < N; i+=3) { 2606 // ... do something to R, G, B 2607 // Pic[i] = R; // Member of index 0 2608 // Pic[i+1] = G; // Member of index 1 2609 // Pic[i+2] = B; // Member of index 2 2610 // } 2611 // To: 2612 // %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7> 2613 // %B_U.vec = shuffle %B.vec, undef, <0, 1, 2, 3, u, u, u, u> 2614 // %interleaved.vec = shuffle %R_G.vec, %B_U.vec, 2615 // <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> ; Interleave R,G,B elements 2616 // store <12 x i32> %interleaved.vec ; Write 4 tuples of R,G,B 2617 void InnerLoopVectorizer::vectorizeInterleaveGroup(Instruction *Instr) { 2618 const InterleaveGroup *Group = Legal->getInterleavedAccessGroup(Instr); 2619 assert(Group && "Fail to get an interleaved access group."); 2620 2621 // Skip if current instruction is not the insert position. 2622 if (Instr != Group->getInsertPos()) 2623 return; 2624 2625 LoadInst *LI = dyn_cast<LoadInst>(Instr); 2626 StoreInst *SI = dyn_cast<StoreInst>(Instr); 2627 Value *Ptr = getPointerOperand(Instr); 2628 2629 // Prepare for the vector type of the interleaved load/store. 2630 Type *ScalarTy = LI ? LI->getType() : SI->getValueOperand()->getType(); 2631 unsigned InterleaveFactor = Group->getFactor(); 2632 Type *VecTy = VectorType::get(ScalarTy, InterleaveFactor * VF); 2633 Type *PtrTy = VecTy->getPointerTo(Ptr->getType()->getPointerAddressSpace()); 2634 2635 // Prepare for the new pointers. 2636 setDebugLocFromInst(Builder, Ptr); 2637 SmallVector<Value *, 2> NewPtrs; 2638 unsigned Index = Group->getIndex(Instr); 2639 2640 // If the group is reverse, adjust the index to refer to the last vector lane 2641 // instead of the first. We adjust the index from the first vector lane, 2642 // rather than directly getting the pointer for lane VF - 1, because the 2643 // pointer operand of the interleaved access is supposed to be uniform. For 2644 // uniform instructions, we're only required to generate a value for the 2645 // first vector lane in each unroll iteration. 2646 if (Group->isReverse()) 2647 Index += (VF - 1) * Group->getFactor(); 2648 2649 for (unsigned Part = 0; Part < UF; Part++) { 2650 Value *NewPtr = getScalarValue(Ptr, Part, 0); 2651 2652 // Notice current instruction could be any index. Need to adjust the address 2653 // to the member of index 0. 2654 // 2655 // E.g. a = A[i+1]; // Member of index 1 (Current instruction) 2656 // b = A[i]; // Member of index 0 2657 // Current pointer is pointed to A[i+1], adjust it to A[i]. 2658 // 2659 // E.g. A[i+1] = a; // Member of index 1 2660 // A[i] = b; // Member of index 0 2661 // A[i+2] = c; // Member of index 2 (Current instruction) 2662 // Current pointer is pointed to A[i+2], adjust it to A[i]. 2663 NewPtr = Builder.CreateGEP(NewPtr, Builder.getInt32(-Index)); 2664 2665 // Cast to the vector pointer type. 2666 NewPtrs.push_back(Builder.CreateBitCast(NewPtr, PtrTy)); 2667 } 2668 2669 setDebugLocFromInst(Builder, Instr); 2670 Value *UndefVec = UndefValue::get(VecTy); 2671 2672 // Vectorize the interleaved load group. 2673 if (LI) { 2674 2675 // For each unroll part, create a wide load for the group. 2676 SmallVector<Value *, 2> NewLoads; 2677 for (unsigned Part = 0; Part < UF; Part++) { 2678 auto *NewLoad = Builder.CreateAlignedLoad( 2679 NewPtrs[Part], Group->getAlignment(), "wide.vec"); 2680 addMetadata(NewLoad, Instr); 2681 NewLoads.push_back(NewLoad); 2682 } 2683 2684 // For each member in the group, shuffle out the appropriate data from the 2685 // wide loads. 2686 for (unsigned I = 0; I < InterleaveFactor; ++I) { 2687 Instruction *Member = Group->getMember(I); 2688 2689 // Skip the gaps in the group. 2690 if (!Member) 2691 continue; 2692 2693 VectorParts Entry(UF); 2694 Constant *StrideMask = getStridedMask(Builder, I, InterleaveFactor, VF); 2695 for (unsigned Part = 0; Part < UF; Part++) { 2696 Value *StridedVec = Builder.CreateShuffleVector( 2697 NewLoads[Part], UndefVec, StrideMask, "strided.vec"); 2698 2699 // If this member has different type, cast the result type. 2700 if (Member->getType() != ScalarTy) { 2701 VectorType *OtherVTy = VectorType::get(Member->getType(), VF); 2702 StridedVec = Builder.CreateBitOrPointerCast(StridedVec, OtherVTy); 2703 } 2704 2705 Entry[Part] = 2706 Group->isReverse() ? reverseVector(StridedVec) : StridedVec; 2707 } 2708 VectorLoopValueMap.initVector(Member, Entry); 2709 } 2710 return; 2711 } 2712 2713 // The sub vector type for current instruction. 2714 VectorType *SubVT = VectorType::get(ScalarTy, VF); 2715 2716 // Vectorize the interleaved store group. 2717 for (unsigned Part = 0; Part < UF; Part++) { 2718 // Collect the stored vector from each member. 2719 SmallVector<Value *, 4> StoredVecs; 2720 for (unsigned i = 0; i < InterleaveFactor; i++) { 2721 // Interleaved store group doesn't allow a gap, so each index has a member 2722 Instruction *Member = Group->getMember(i); 2723 assert(Member && "Fail to get a member from an interleaved store group"); 2724 2725 Value *StoredVec = 2726 getVectorValue(cast<StoreInst>(Member)->getValueOperand())[Part]; 2727 if (Group->isReverse()) 2728 StoredVec = reverseVector(StoredVec); 2729 2730 // If this member has different type, cast it to an unified type. 2731 if (StoredVec->getType() != SubVT) 2732 StoredVec = Builder.CreateBitOrPointerCast(StoredVec, SubVT); 2733 2734 StoredVecs.push_back(StoredVec); 2735 } 2736 2737 // Concatenate all vectors into a wide vector. 2738 Value *WideVec = ConcatenateVectors(Builder, StoredVecs); 2739 2740 // Interleave the elements in the wide vector. 2741 Constant *IMask = getInterleavedMask(Builder, VF, InterleaveFactor); 2742 Value *IVec = Builder.CreateShuffleVector(WideVec, UndefVec, IMask, 2743 "interleaved.vec"); 2744 2745 Instruction *NewStoreInstr = 2746 Builder.CreateAlignedStore(IVec, NewPtrs[Part], Group->getAlignment()); 2747 addMetadata(NewStoreInstr, Instr); 2748 } 2749 } 2750 2751 void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr) { 2752 // Attempt to issue a wide load. 2753 LoadInst *LI = dyn_cast<LoadInst>(Instr); 2754 StoreInst *SI = dyn_cast<StoreInst>(Instr); 2755 2756 assert((LI || SI) && "Invalid Load/Store instruction"); 2757 2758 // Try to vectorize the interleave group if this access is interleaved. 2759 if (Legal->isAccessInterleaved(Instr)) 2760 return vectorizeInterleaveGroup(Instr); 2761 2762 Type *ScalarDataTy = LI ? LI->getType() : SI->getValueOperand()->getType(); 2763 Type *DataTy = VectorType::get(ScalarDataTy, VF); 2764 Value *Ptr = getPointerOperand(Instr); 2765 unsigned Alignment = LI ? LI->getAlignment() : SI->getAlignment(); 2766 // An alignment of 0 means target abi alignment. We need to use the scalar's 2767 // target abi alignment in such a case. 2768 const DataLayout &DL = Instr->getModule()->getDataLayout(); 2769 if (!Alignment) 2770 Alignment = DL.getABITypeAlignment(ScalarDataTy); 2771 unsigned AddressSpace = Ptr->getType()->getPointerAddressSpace(); 2772 2773 // Scalarize the memory instruction if necessary. 2774 if (Legal->memoryInstructionMustBeScalarized(Instr, VF)) 2775 return scalarizeInstruction(Instr, Legal->isScalarWithPredication(Instr)); 2776 2777 // Determine if the pointer operand of the access is either consecutive or 2778 // reverse consecutive. 2779 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr); 2780 bool Reverse = ConsecutiveStride < 0; 2781 2782 // Determine if either a gather or scatter operation is legal. 2783 bool CreateGatherScatter = 2784 !ConsecutiveStride && Legal->isLegalGatherOrScatter(Instr); 2785 2786 VectorParts VectorGep; 2787 2788 // Handle consecutive loads/stores. 2789 GetElementPtrInst *Gep = getGEPInstruction(Ptr); 2790 if (ConsecutiveStride) { 2791 if (Gep) { 2792 unsigned NumOperands = Gep->getNumOperands(); 2793 #ifndef NDEBUG 2794 // The original GEP that identified as a consecutive memory access 2795 // should have only one loop-variant operand. 2796 unsigned NumOfLoopVariantOps = 0; 2797 for (unsigned i = 0; i < NumOperands; ++i) 2798 if (!PSE.getSE()->isLoopInvariant(PSE.getSCEV(Gep->getOperand(i)), 2799 OrigLoop)) 2800 NumOfLoopVariantOps++; 2801 assert(NumOfLoopVariantOps == 1 && 2802 "Consecutive GEP should have only one loop-variant operand"); 2803 #endif 2804 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone()); 2805 Gep2->setName("gep.indvar"); 2806 2807 // A new GEP is created for a 0-lane value of the first unroll iteration. 2808 // The GEPs for the rest of the unroll iterations are computed below as an 2809 // offset from this GEP. 2810 for (unsigned i = 0; i < NumOperands; ++i) 2811 // We can apply getScalarValue() for all GEP indices. It returns an 2812 // original value for loop-invariant operand and 0-lane for consecutive 2813 // operand. 2814 Gep2->setOperand(i, getScalarValue(Gep->getOperand(i), 2815 0, /* First unroll iteration */ 2816 0 /* 0-lane of the vector */ )); 2817 setDebugLocFromInst(Builder, Gep); 2818 Ptr = Builder.Insert(Gep2); 2819 2820 } else { // No GEP 2821 setDebugLocFromInst(Builder, Ptr); 2822 Ptr = getScalarValue(Ptr, 0, 0); 2823 } 2824 } else { 2825 // At this point we should vector version of GEP for Gather or Scatter 2826 assert(CreateGatherScatter && "The instruction should be scalarized"); 2827 if (Gep) { 2828 // Vectorizing GEP, across UF parts. We want to get a vector value for base 2829 // and each index that's defined inside the loop, even if it is 2830 // loop-invariant but wasn't hoisted out. Otherwise we want to keep them 2831 // scalar. 2832 SmallVector<VectorParts, 4> OpsV; 2833 for (Value *Op : Gep->operands()) { 2834 Instruction *SrcInst = dyn_cast<Instruction>(Op); 2835 if (SrcInst && OrigLoop->contains(SrcInst)) 2836 OpsV.push_back(getVectorValue(Op)); 2837 else 2838 OpsV.push_back(VectorParts(UF, Op)); 2839 } 2840 for (unsigned Part = 0; Part < UF; ++Part) { 2841 SmallVector<Value *, 4> Ops; 2842 Value *GEPBasePtr = OpsV[0][Part]; 2843 for (unsigned i = 1; i < Gep->getNumOperands(); i++) 2844 Ops.push_back(OpsV[i][Part]); 2845 Value *NewGep = Builder.CreateGEP(GEPBasePtr, Ops, "VectorGep"); 2846 cast<GetElementPtrInst>(NewGep)->setIsInBounds(Gep->isInBounds()); 2847 assert(NewGep->getType()->isVectorTy() && "Expected vector GEP"); 2848 2849 NewGep = 2850 Builder.CreateBitCast(NewGep, VectorType::get(Ptr->getType(), VF)); 2851 VectorGep.push_back(NewGep); 2852 } 2853 } else 2854 VectorGep = getVectorValue(Ptr); 2855 } 2856 2857 VectorParts Mask = createBlockInMask(Instr->getParent()); 2858 // Handle Stores: 2859 if (SI) { 2860 assert(!Legal->isUniform(SI->getPointerOperand()) && 2861 "We do not allow storing to uniform addresses"); 2862 setDebugLocFromInst(Builder, SI); 2863 // We don't want to update the value in the map as it might be used in 2864 // another expression. So don't use a reference type for "StoredVal". 2865 VectorParts StoredVal = getVectorValue(SI->getValueOperand()); 2866 2867 for (unsigned Part = 0; Part < UF; ++Part) { 2868 Instruction *NewSI = nullptr; 2869 if (CreateGatherScatter) { 2870 Value *MaskPart = Legal->isMaskRequired(SI) ? Mask[Part] : nullptr; 2871 NewSI = Builder.CreateMaskedScatter(StoredVal[Part], VectorGep[Part], 2872 Alignment, MaskPart); 2873 } else { 2874 // Calculate the pointer for the specific unroll-part. 2875 Value *PartPtr = 2876 Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(Part * VF)); 2877 2878 if (Reverse) { 2879 // If we store to reverse consecutive memory locations, then we need 2880 // to reverse the order of elements in the stored value. 2881 StoredVal[Part] = reverseVector(StoredVal[Part]); 2882 // If the address is consecutive but reversed, then the 2883 // wide store needs to start at the last vector element. 2884 PartPtr = 2885 Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(-Part * VF)); 2886 PartPtr = 2887 Builder.CreateGEP(nullptr, PartPtr, Builder.getInt32(1 - VF)); 2888 Mask[Part] = reverseVector(Mask[Part]); 2889 } 2890 2891 Value *VecPtr = 2892 Builder.CreateBitCast(PartPtr, DataTy->getPointerTo(AddressSpace)); 2893 2894 if (Legal->isMaskRequired(SI)) 2895 NewSI = Builder.CreateMaskedStore(StoredVal[Part], VecPtr, Alignment, 2896 Mask[Part]); 2897 else 2898 NewSI = 2899 Builder.CreateAlignedStore(StoredVal[Part], VecPtr, Alignment); 2900 } 2901 addMetadata(NewSI, SI); 2902 } 2903 return; 2904 } 2905 2906 // Handle loads. 2907 assert(LI && "Must have a load instruction"); 2908 setDebugLocFromInst(Builder, LI); 2909 VectorParts Entry(UF); 2910 for (unsigned Part = 0; Part < UF; ++Part) { 2911 Instruction *NewLI; 2912 if (CreateGatherScatter) { 2913 Value *MaskPart = Legal->isMaskRequired(LI) ? Mask[Part] : nullptr; 2914 NewLI = Builder.CreateMaskedGather(VectorGep[Part], Alignment, MaskPart, 2915 0, "wide.masked.gather"); 2916 Entry[Part] = NewLI; 2917 } else { 2918 // Calculate the pointer for the specific unroll-part. 2919 Value *PartPtr = 2920 Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(Part * VF)); 2921 2922 if (Reverse) { 2923 // If the address is consecutive but reversed, then the 2924 // wide load needs to start at the last vector element. 2925 PartPtr = Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(-Part * VF)); 2926 PartPtr = Builder.CreateGEP(nullptr, PartPtr, Builder.getInt32(1 - VF)); 2927 Mask[Part] = reverseVector(Mask[Part]); 2928 } 2929 2930 Value *VecPtr = 2931 Builder.CreateBitCast(PartPtr, DataTy->getPointerTo(AddressSpace)); 2932 if (Legal->isMaskRequired(LI)) 2933 NewLI = Builder.CreateMaskedLoad(VecPtr, Alignment, Mask[Part], 2934 UndefValue::get(DataTy), 2935 "wide.masked.load"); 2936 else 2937 NewLI = Builder.CreateAlignedLoad(VecPtr, Alignment, "wide.load"); 2938 Entry[Part] = Reverse ? reverseVector(NewLI) : NewLI; 2939 } 2940 addMetadata(NewLI, LI); 2941 } 2942 VectorLoopValueMap.initVector(Instr, Entry); 2943 } 2944 2945 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr, 2946 bool IfPredicateInstr) { 2947 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors"); 2948 DEBUG(dbgs() << "LV: Scalarizing" 2949 << (IfPredicateInstr ? " and predicating:" : ":") << *Instr 2950 << '\n'); 2951 // Holds vector parameters or scalars, in case of uniform vals. 2952 SmallVector<VectorParts, 4> Params; 2953 2954 setDebugLocFromInst(Builder, Instr); 2955 2956 // Does this instruction return a value ? 2957 bool IsVoidRetTy = Instr->getType()->isVoidTy(); 2958 2959 // Initialize a new scalar map entry. 2960 ScalarParts Entry(UF); 2961 2962 VectorParts Cond; 2963 if (IfPredicateInstr) 2964 Cond = createBlockInMask(Instr->getParent()); 2965 2966 // Determine the number of scalars we need to generate for each unroll 2967 // iteration. If the instruction is uniform, we only need to generate the 2968 // first lane. Otherwise, we generate all VF values. 2969 unsigned Lanes = Legal->isUniformAfterVectorization(Instr) ? 1 : VF; 2970 2971 // For each vector unroll 'part': 2972 for (unsigned Part = 0; Part < UF; ++Part) { 2973 Entry[Part].resize(VF); 2974 // For each scalar that we create: 2975 for (unsigned Lane = 0; Lane < Lanes; ++Lane) { 2976 2977 // Start if-block. 2978 Value *Cmp = nullptr; 2979 if (IfPredicateInstr) { 2980 Cmp = Builder.CreateExtractElement(Cond[Part], Builder.getInt32(Lane)); 2981 Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cmp, 2982 ConstantInt::get(Cmp->getType(), 1)); 2983 } 2984 2985 Instruction *Cloned = Instr->clone(); 2986 if (!IsVoidRetTy) 2987 Cloned->setName(Instr->getName() + ".cloned"); 2988 2989 // Replace the operands of the cloned instructions with their scalar 2990 // equivalents in the new loop. 2991 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) { 2992 auto *NewOp = getScalarValue(Instr->getOperand(op), Part, Lane); 2993 Cloned->setOperand(op, NewOp); 2994 } 2995 addNewMetadata(Cloned, Instr); 2996 2997 // Place the cloned scalar in the new loop. 2998 Builder.Insert(Cloned); 2999 3000 // Add the cloned scalar to the scalar map entry. 3001 Entry[Part][Lane] = Cloned; 3002 3003 // If we just cloned a new assumption, add it the assumption cache. 3004 if (auto *II = dyn_cast<IntrinsicInst>(Cloned)) 3005 if (II->getIntrinsicID() == Intrinsic::assume) 3006 AC->registerAssumption(II); 3007 3008 // End if-block. 3009 if (IfPredicateInstr) 3010 PredicatedInstructions.push_back(std::make_pair(Cloned, Cmp)); 3011 } 3012 } 3013 VectorLoopValueMap.initScalar(Instr, Entry); 3014 } 3015 3016 PHINode *InnerLoopVectorizer::createInductionVariable(Loop *L, Value *Start, 3017 Value *End, Value *Step, 3018 Instruction *DL) { 3019 BasicBlock *Header = L->getHeader(); 3020 BasicBlock *Latch = L->getLoopLatch(); 3021 // As we're just creating this loop, it's possible no latch exists 3022 // yet. If so, use the header as this will be a single block loop. 3023 if (!Latch) 3024 Latch = Header; 3025 3026 IRBuilder<> Builder(&*Header->getFirstInsertionPt()); 3027 setDebugLocFromInst(Builder, getDebugLocFromInstOrOperands(OldInduction)); 3028 auto *Induction = Builder.CreatePHI(Start->getType(), 2, "index"); 3029 3030 Builder.SetInsertPoint(Latch->getTerminator()); 3031 3032 // Create i+1 and fill the PHINode. 3033 Value *Next = Builder.CreateAdd(Induction, Step, "index.next"); 3034 Induction->addIncoming(Start, L->getLoopPreheader()); 3035 Induction->addIncoming(Next, Latch); 3036 // Create the compare. 3037 Value *ICmp = Builder.CreateICmpEQ(Next, End); 3038 Builder.CreateCondBr(ICmp, L->getExitBlock(), Header); 3039 3040 // Now we have two terminators. Remove the old one from the block. 3041 Latch->getTerminator()->eraseFromParent(); 3042 3043 return Induction; 3044 } 3045 3046 Value *InnerLoopVectorizer::getOrCreateTripCount(Loop *L) { 3047 if (TripCount) 3048 return TripCount; 3049 3050 IRBuilder<> Builder(L->getLoopPreheader()->getTerminator()); 3051 // Find the loop boundaries. 3052 ScalarEvolution *SE = PSE.getSE(); 3053 const SCEV *BackedgeTakenCount = PSE.getBackedgeTakenCount(); 3054 assert(BackedgeTakenCount != SE->getCouldNotCompute() && 3055 "Invalid loop count"); 3056 3057 Type *IdxTy = Legal->getWidestInductionType(); 3058 3059 // The exit count might have the type of i64 while the phi is i32. This can 3060 // happen if we have an induction variable that is sign extended before the 3061 // compare. The only way that we get a backedge taken count is that the 3062 // induction variable was signed and as such will not overflow. In such a case 3063 // truncation is legal. 3064 if (BackedgeTakenCount->getType()->getPrimitiveSizeInBits() > 3065 IdxTy->getPrimitiveSizeInBits()) 3066 BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount, IdxTy); 3067 BackedgeTakenCount = SE->getNoopOrZeroExtend(BackedgeTakenCount, IdxTy); 3068 3069 // Get the total trip count from the count by adding 1. 3070 const SCEV *ExitCount = SE->getAddExpr( 3071 BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType())); 3072 3073 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout(); 3074 3075 // Expand the trip count and place the new instructions in the preheader. 3076 // Notice that the pre-header does not change, only the loop body. 3077 SCEVExpander Exp(*SE, DL, "induction"); 3078 3079 // Count holds the overall loop count (N). 3080 TripCount = Exp.expandCodeFor(ExitCount, ExitCount->getType(), 3081 L->getLoopPreheader()->getTerminator()); 3082 3083 if (TripCount->getType()->isPointerTy()) 3084 TripCount = 3085 CastInst::CreatePointerCast(TripCount, IdxTy, "exitcount.ptrcnt.to.int", 3086 L->getLoopPreheader()->getTerminator()); 3087 3088 return TripCount; 3089 } 3090 3091 Value *InnerLoopVectorizer::getOrCreateVectorTripCount(Loop *L) { 3092 if (VectorTripCount) 3093 return VectorTripCount; 3094 3095 Value *TC = getOrCreateTripCount(L); 3096 IRBuilder<> Builder(L->getLoopPreheader()->getTerminator()); 3097 3098 // Now we need to generate the expression for the part of the loop that the 3099 // vectorized body will execute. This is equal to N - (N % Step) if scalar 3100 // iterations are not required for correctness, or N - Step, otherwise. Step 3101 // is equal to the vectorization factor (number of SIMD elements) times the 3102 // unroll factor (number of SIMD instructions). 3103 Constant *Step = ConstantInt::get(TC->getType(), VF * UF); 3104 Value *R = Builder.CreateURem(TC, Step, "n.mod.vf"); 3105 3106 // If there is a non-reversed interleaved group that may speculatively access 3107 // memory out-of-bounds, we need to ensure that there will be at least one 3108 // iteration of the scalar epilogue loop. Thus, if the step evenly divides 3109 // the trip count, we set the remainder to be equal to the step. If the step 3110 // does not evenly divide the trip count, no adjustment is necessary since 3111 // there will already be scalar iterations. Note that the minimum iterations 3112 // check ensures that N >= Step. 3113 if (VF > 1 && Legal->requiresScalarEpilogue()) { 3114 auto *IsZero = Builder.CreateICmpEQ(R, ConstantInt::get(R->getType(), 0)); 3115 R = Builder.CreateSelect(IsZero, Step, R); 3116 } 3117 3118 VectorTripCount = Builder.CreateSub(TC, R, "n.vec"); 3119 3120 return VectorTripCount; 3121 } 3122 3123 void InnerLoopVectorizer::emitMinimumIterationCountCheck(Loop *L, 3124 BasicBlock *Bypass) { 3125 Value *Count = getOrCreateTripCount(L); 3126 BasicBlock *BB = L->getLoopPreheader(); 3127 IRBuilder<> Builder(BB->getTerminator()); 3128 3129 // Generate code to check that the loop's trip count that we computed by 3130 // adding one to the backedge-taken count will not overflow. 3131 Value *CheckMinIters = Builder.CreateICmpULT( 3132 Count, ConstantInt::get(Count->getType(), VF * UF), "min.iters.check"); 3133 3134 BasicBlock *NewBB = 3135 BB->splitBasicBlock(BB->getTerminator(), "min.iters.checked"); 3136 // Update dominator tree immediately if the generated block is a 3137 // LoopBypassBlock because SCEV expansions to generate loop bypass 3138 // checks may query it before the current function is finished. 3139 DT->addNewBlock(NewBB, BB); 3140 if (L->getParentLoop()) 3141 L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI); 3142 ReplaceInstWithInst(BB->getTerminator(), 3143 BranchInst::Create(Bypass, NewBB, CheckMinIters)); 3144 LoopBypassBlocks.push_back(BB); 3145 } 3146 3147 void InnerLoopVectorizer::emitVectorLoopEnteredCheck(Loop *L, 3148 BasicBlock *Bypass) { 3149 Value *TC = getOrCreateVectorTripCount(L); 3150 BasicBlock *BB = L->getLoopPreheader(); 3151 IRBuilder<> Builder(BB->getTerminator()); 3152 3153 // Now, compare the new count to zero. If it is zero skip the vector loop and 3154 // jump to the scalar loop. 3155 Value *Cmp = Builder.CreateICmpEQ(TC, Constant::getNullValue(TC->getType()), 3156 "cmp.zero"); 3157 3158 // Generate code to check that the loop's trip count that we computed by 3159 // adding one to the backedge-taken count will not overflow. 3160 BasicBlock *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph"); 3161 // Update dominator tree immediately if the generated block is a 3162 // LoopBypassBlock because SCEV expansions to generate loop bypass 3163 // checks may query it before the current function is finished. 3164 DT->addNewBlock(NewBB, BB); 3165 if (L->getParentLoop()) 3166 L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI); 3167 ReplaceInstWithInst(BB->getTerminator(), 3168 BranchInst::Create(Bypass, NewBB, Cmp)); 3169 LoopBypassBlocks.push_back(BB); 3170 } 3171 3172 void InnerLoopVectorizer::emitSCEVChecks(Loop *L, BasicBlock *Bypass) { 3173 BasicBlock *BB = L->getLoopPreheader(); 3174 3175 // Generate the code to check that the SCEV assumptions that we made. 3176 // We want the new basic block to start at the first instruction in a 3177 // sequence of instructions that form a check. 3178 SCEVExpander Exp(*PSE.getSE(), Bypass->getModule()->getDataLayout(), 3179 "scev.check"); 3180 Value *SCEVCheck = 3181 Exp.expandCodeForPredicate(&PSE.getUnionPredicate(), BB->getTerminator()); 3182 3183 if (auto *C = dyn_cast<ConstantInt>(SCEVCheck)) 3184 if (C->isZero()) 3185 return; 3186 3187 // Create a new block containing the stride check. 3188 BB->setName("vector.scevcheck"); 3189 auto *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph"); 3190 // Update dominator tree immediately if the generated block is a 3191 // LoopBypassBlock because SCEV expansions to generate loop bypass 3192 // checks may query it before the current function is finished. 3193 DT->addNewBlock(NewBB, BB); 3194 if (L->getParentLoop()) 3195 L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI); 3196 ReplaceInstWithInst(BB->getTerminator(), 3197 BranchInst::Create(Bypass, NewBB, SCEVCheck)); 3198 LoopBypassBlocks.push_back(BB); 3199 AddedSafetyChecks = true; 3200 } 3201 3202 void InnerLoopVectorizer::emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass) { 3203 BasicBlock *BB = L->getLoopPreheader(); 3204 3205 // Generate the code that checks in runtime if arrays overlap. We put the 3206 // checks into a separate block to make the more common case of few elements 3207 // faster. 3208 Instruction *FirstCheckInst; 3209 Instruction *MemRuntimeCheck; 3210 std::tie(FirstCheckInst, MemRuntimeCheck) = 3211 Legal->getLAI()->addRuntimeChecks(BB->getTerminator()); 3212 if (!MemRuntimeCheck) 3213 return; 3214 3215 // Create a new block containing the memory check. 3216 BB->setName("vector.memcheck"); 3217 auto *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph"); 3218 // Update dominator tree immediately if the generated block is a 3219 // LoopBypassBlock because SCEV expansions to generate loop bypass 3220 // checks may query it before the current function is finished. 3221 DT->addNewBlock(NewBB, BB); 3222 if (L->getParentLoop()) 3223 L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI); 3224 ReplaceInstWithInst(BB->getTerminator(), 3225 BranchInst::Create(Bypass, NewBB, MemRuntimeCheck)); 3226 LoopBypassBlocks.push_back(BB); 3227 AddedSafetyChecks = true; 3228 3229 // We currently don't use LoopVersioning for the actual loop cloning but we 3230 // still use it to add the noalias metadata. 3231 LVer = llvm::make_unique<LoopVersioning>(*Legal->getLAI(), OrigLoop, LI, DT, 3232 PSE.getSE()); 3233 LVer->prepareNoAliasMetadata(); 3234 } 3235 3236 void InnerLoopVectorizer::createEmptyLoop() { 3237 /* 3238 In this function we generate a new loop. The new loop will contain 3239 the vectorized instructions while the old loop will continue to run the 3240 scalar remainder. 3241 3242 [ ] <-- loop iteration number check. 3243 / | 3244 / v 3245 | [ ] <-- vector loop bypass (may consist of multiple blocks). 3246 | / | 3247 | / v 3248 || [ ] <-- vector pre header. 3249 |/ | 3250 | v 3251 | [ ] \ 3252 | [ ]_| <-- vector loop. 3253 | | 3254 | v 3255 | -[ ] <--- middle-block. 3256 | / | 3257 | / v 3258 -|- >[ ] <--- new preheader. 3259 | | 3260 | v 3261 | [ ] \ 3262 | [ ]_| <-- old scalar loop to handle remainder. 3263 \ | 3264 \ v 3265 >[ ] <-- exit block. 3266 ... 3267 */ 3268 3269 BasicBlock *OldBasicBlock = OrigLoop->getHeader(); 3270 BasicBlock *VectorPH = OrigLoop->getLoopPreheader(); 3271 BasicBlock *ExitBlock = OrigLoop->getExitBlock(); 3272 assert(VectorPH && "Invalid loop structure"); 3273 assert(ExitBlock && "Must have an exit block"); 3274 3275 // Some loops have a single integer induction variable, while other loops 3276 // don't. One example is c++ iterators that often have multiple pointer 3277 // induction variables. In the code below we also support a case where we 3278 // don't have a single induction variable. 3279 // 3280 // We try to obtain an induction variable from the original loop as hard 3281 // as possible. However if we don't find one that: 3282 // - is an integer 3283 // - counts from zero, stepping by one 3284 // - is the size of the widest induction variable type 3285 // then we create a new one. 3286 OldInduction = Legal->getInduction(); 3287 Type *IdxTy = Legal->getWidestInductionType(); 3288 3289 // Split the single block loop into the two loop structure described above. 3290 BasicBlock *VecBody = 3291 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body"); 3292 BasicBlock *MiddleBlock = 3293 VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block"); 3294 BasicBlock *ScalarPH = 3295 MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph"); 3296 3297 // Create and register the new vector loop. 3298 Loop *Lp = new Loop(); 3299 Loop *ParentLoop = OrigLoop->getParentLoop(); 3300 3301 // Insert the new loop into the loop nest and register the new basic blocks 3302 // before calling any utilities such as SCEV that require valid LoopInfo. 3303 if (ParentLoop) { 3304 ParentLoop->addChildLoop(Lp); 3305 ParentLoop->addBasicBlockToLoop(ScalarPH, *LI); 3306 ParentLoop->addBasicBlockToLoop(MiddleBlock, *LI); 3307 } else { 3308 LI->addTopLevelLoop(Lp); 3309 } 3310 Lp->addBasicBlockToLoop(VecBody, *LI); 3311 3312 // Find the loop boundaries. 3313 Value *Count = getOrCreateTripCount(Lp); 3314 3315 Value *StartIdx = ConstantInt::get(IdxTy, 0); 3316 3317 // We need to test whether the backedge-taken count is uint##_max. Adding one 3318 // to it will cause overflow and an incorrect loop trip count in the vector 3319 // body. In case of overflow we want to directly jump to the scalar remainder 3320 // loop. 3321 emitMinimumIterationCountCheck(Lp, ScalarPH); 3322 // Now, compare the new count to zero. If it is zero skip the vector loop and 3323 // jump to the scalar loop. 3324 emitVectorLoopEnteredCheck(Lp, ScalarPH); 3325 // Generate the code to check any assumptions that we've made for SCEV 3326 // expressions. 3327 emitSCEVChecks(Lp, ScalarPH); 3328 3329 // Generate the code that checks in runtime if arrays overlap. We put the 3330 // checks into a separate block to make the more common case of few elements 3331 // faster. 3332 emitMemRuntimeChecks(Lp, ScalarPH); 3333 3334 // Generate the induction variable. 3335 // The loop step is equal to the vectorization factor (num of SIMD elements) 3336 // times the unroll factor (num of SIMD instructions). 3337 Value *CountRoundDown = getOrCreateVectorTripCount(Lp); 3338 Constant *Step = ConstantInt::get(IdxTy, VF * UF); 3339 Induction = 3340 createInductionVariable(Lp, StartIdx, CountRoundDown, Step, 3341 getDebugLocFromInstOrOperands(OldInduction)); 3342 3343 // We are going to resume the execution of the scalar loop. 3344 // Go over all of the induction variables that we found and fix the 3345 // PHIs that are left in the scalar version of the loop. 3346 // The starting values of PHI nodes depend on the counter of the last 3347 // iteration in the vectorized loop. 3348 // If we come from a bypass edge then we need to start from the original 3349 // start value. 3350 3351 // This variable saves the new starting index for the scalar loop. It is used 3352 // to test if there are any tail iterations left once the vector loop has 3353 // completed. 3354 LoopVectorizationLegality::InductionList *List = Legal->getInductionVars(); 3355 for (auto &InductionEntry : *List) { 3356 PHINode *OrigPhi = InductionEntry.first; 3357 InductionDescriptor II = InductionEntry.second; 3358 3359 // Create phi nodes to merge from the backedge-taken check block. 3360 PHINode *BCResumeVal = PHINode::Create( 3361 OrigPhi->getType(), 3, "bc.resume.val", ScalarPH->getTerminator()); 3362 Value *EndValue; 3363 if (OrigPhi == OldInduction) { 3364 // We know what the end value is. 3365 EndValue = CountRoundDown; 3366 } else { 3367 IRBuilder<> B(LoopBypassBlocks.back()->getTerminator()); 3368 Type *StepType = II.getStep()->getType(); 3369 Instruction::CastOps CastOp = 3370 CastInst::getCastOpcode(CountRoundDown, true, StepType, true); 3371 Value *CRD = B.CreateCast(CastOp, CountRoundDown, StepType, "cast.crd"); 3372 const DataLayout &DL = OrigLoop->getHeader()->getModule()->getDataLayout(); 3373 EndValue = II.transform(B, CRD, PSE.getSE(), DL); 3374 EndValue->setName("ind.end"); 3375 } 3376 3377 // The new PHI merges the original incoming value, in case of a bypass, 3378 // or the value at the end of the vectorized loop. 3379 BCResumeVal->addIncoming(EndValue, MiddleBlock); 3380 3381 // Fix up external users of the induction variable. 3382 fixupIVUsers(OrigPhi, II, CountRoundDown, EndValue, MiddleBlock); 3383 3384 // Fix the scalar body counter (PHI node). 3385 unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH); 3386 3387 // The old induction's phi node in the scalar body needs the truncated 3388 // value. 3389 for (BasicBlock *BB : LoopBypassBlocks) 3390 BCResumeVal->addIncoming(II.getStartValue(), BB); 3391 OrigPhi->setIncomingValue(BlockIdx, BCResumeVal); 3392 } 3393 3394 // Add a check in the middle block to see if we have completed 3395 // all of the iterations in the first vector loop. 3396 // If (N - N%VF) == N, then we *don't* need to run the remainder. 3397 Value *CmpN = 3398 CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, Count, 3399 CountRoundDown, "cmp.n", MiddleBlock->getTerminator()); 3400 ReplaceInstWithInst(MiddleBlock->getTerminator(), 3401 BranchInst::Create(ExitBlock, ScalarPH, CmpN)); 3402 3403 // Get ready to start creating new instructions into the vectorized body. 3404 Builder.SetInsertPoint(&*VecBody->getFirstInsertionPt()); 3405 3406 // Save the state. 3407 LoopVectorPreHeader = Lp->getLoopPreheader(); 3408 LoopScalarPreHeader = ScalarPH; 3409 LoopMiddleBlock = MiddleBlock; 3410 LoopExitBlock = ExitBlock; 3411 LoopVectorBody = VecBody; 3412 LoopScalarBody = OldBasicBlock; 3413 3414 // Keep all loop hints from the original loop on the vector loop (we'll 3415 // replace the vectorizer-specific hints below). 3416 if (MDNode *LID = OrigLoop->getLoopID()) 3417 Lp->setLoopID(LID); 3418 3419 LoopVectorizeHints Hints(Lp, true, *ORE); 3420 Hints.setAlreadyVectorized(); 3421 } 3422 3423 // Fix up external users of the induction variable. At this point, we are 3424 // in LCSSA form, with all external PHIs that use the IV having one input value, 3425 // coming from the remainder loop. We need those PHIs to also have a correct 3426 // value for the IV when arriving directly from the middle block. 3427 void InnerLoopVectorizer::fixupIVUsers(PHINode *OrigPhi, 3428 const InductionDescriptor &II, 3429 Value *CountRoundDown, Value *EndValue, 3430 BasicBlock *MiddleBlock) { 3431 // There are two kinds of external IV usages - those that use the value 3432 // computed in the last iteration (the PHI) and those that use the penultimate 3433 // value (the value that feeds into the phi from the loop latch). 3434 // We allow both, but they, obviously, have different values. 3435 3436 assert(OrigLoop->getExitBlock() && "Expected a single exit block"); 3437 3438 DenseMap<Value *, Value *> MissingVals; 3439 3440 // An external user of the last iteration's value should see the value that 3441 // the remainder loop uses to initialize its own IV. 3442 Value *PostInc = OrigPhi->getIncomingValueForBlock(OrigLoop->getLoopLatch()); 3443 for (User *U : PostInc->users()) { 3444 Instruction *UI = cast<Instruction>(U); 3445 if (!OrigLoop->contains(UI)) { 3446 assert(isa<PHINode>(UI) && "Expected LCSSA form"); 3447 MissingVals[UI] = EndValue; 3448 } 3449 } 3450 3451 // An external user of the penultimate value need to see EndValue - Step. 3452 // The simplest way to get this is to recompute it from the constituent SCEVs, 3453 // that is Start + (Step * (CRD - 1)). 3454 for (User *U : OrigPhi->users()) { 3455 auto *UI = cast<Instruction>(U); 3456 if (!OrigLoop->contains(UI)) { 3457 const DataLayout &DL = 3458 OrigLoop->getHeader()->getModule()->getDataLayout(); 3459 assert(isa<PHINode>(UI) && "Expected LCSSA form"); 3460 3461 IRBuilder<> B(MiddleBlock->getTerminator()); 3462 Value *CountMinusOne = B.CreateSub( 3463 CountRoundDown, ConstantInt::get(CountRoundDown->getType(), 1)); 3464 Value *CMO = B.CreateSExtOrTrunc(CountMinusOne, II.getStep()->getType(), 3465 "cast.cmo"); 3466 Value *Escape = II.transform(B, CMO, PSE.getSE(), DL); 3467 Escape->setName("ind.escape"); 3468 MissingVals[UI] = Escape; 3469 } 3470 } 3471 3472 for (auto &I : MissingVals) { 3473 PHINode *PHI = cast<PHINode>(I.first); 3474 // One corner case we have to handle is two IVs "chasing" each-other, 3475 // that is %IV2 = phi [...], [ %IV1, %latch ] 3476 // In this case, if IV1 has an external use, we need to avoid adding both 3477 // "last value of IV1" and "penultimate value of IV2". So, verify that we 3478 // don't already have an incoming value for the middle block. 3479 if (PHI->getBasicBlockIndex(MiddleBlock) == -1) 3480 PHI->addIncoming(I.second, MiddleBlock); 3481 } 3482 } 3483 3484 namespace { 3485 struct CSEDenseMapInfo { 3486 static bool canHandle(Instruction *I) { 3487 return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) || 3488 isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I); 3489 } 3490 static inline Instruction *getEmptyKey() { 3491 return DenseMapInfo<Instruction *>::getEmptyKey(); 3492 } 3493 static inline Instruction *getTombstoneKey() { 3494 return DenseMapInfo<Instruction *>::getTombstoneKey(); 3495 } 3496 static unsigned getHashValue(Instruction *I) { 3497 assert(canHandle(I) && "Unknown instruction!"); 3498 return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(), 3499 I->value_op_end())); 3500 } 3501 static bool isEqual(Instruction *LHS, Instruction *RHS) { 3502 if (LHS == getEmptyKey() || RHS == getEmptyKey() || 3503 LHS == getTombstoneKey() || RHS == getTombstoneKey()) 3504 return LHS == RHS; 3505 return LHS->isIdenticalTo(RHS); 3506 } 3507 }; 3508 } 3509 3510 ///\brief Perform cse of induction variable instructions. 3511 static void cse(BasicBlock *BB) { 3512 // Perform simple cse. 3513 SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap; 3514 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) { 3515 Instruction *In = &*I++; 3516 3517 if (!CSEDenseMapInfo::canHandle(In)) 3518 continue; 3519 3520 // Check if we can replace this instruction with any of the 3521 // visited instructions. 3522 if (Instruction *V = CSEMap.lookup(In)) { 3523 In->replaceAllUsesWith(V); 3524 In->eraseFromParent(); 3525 continue; 3526 } 3527 3528 CSEMap[In] = In; 3529 } 3530 } 3531 3532 /// \brief Adds a 'fast' flag to floating point operations. 3533 static Value *addFastMathFlag(Value *V) { 3534 if (isa<FPMathOperator>(V)) { 3535 FastMathFlags Flags; 3536 Flags.setUnsafeAlgebra(); 3537 cast<Instruction>(V)->setFastMathFlags(Flags); 3538 } 3539 return V; 3540 } 3541 3542 /// \brief Estimate the overhead of scalarizing a value based on its type. 3543 /// Insert and Extract are set if the result needs to be inserted and/or 3544 /// extracted from vectors. 3545 /// If the instruction is also to be predicated, add the cost of a PHI 3546 /// node to the insertion cost. 3547 static unsigned getScalarizationOverhead(Type *Ty, bool Insert, bool Extract, 3548 bool Predicated, 3549 const TargetTransformInfo &TTI) { 3550 if (Ty->isVoidTy()) 3551 return 0; 3552 3553 assert(Ty->isVectorTy() && "Can only scalarize vectors"); 3554 unsigned Cost = 0; 3555 3556 for (unsigned I = 0, E = Ty->getVectorNumElements(); I < E; ++I) { 3557 if (Extract) 3558 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, Ty, I); 3559 if (Insert) { 3560 Cost += TTI.getVectorInstrCost(Instruction::InsertElement, Ty, I); 3561 if (Predicated) 3562 Cost += TTI.getCFInstrCost(Instruction::PHI); 3563 } 3564 } 3565 3566 // If we have a predicated instruction, it may not be executed for each 3567 // vector lane. Scale the cost by the probability of executing the 3568 // predicated block. 3569 if (Predicated) 3570 Cost /= getReciprocalPredBlockProb(); 3571 3572 return Cost; 3573 } 3574 3575 /// \brief Estimate the overhead of scalarizing an Instruction based on the 3576 /// types of its operands and return value. 3577 static unsigned getScalarizationOverhead(SmallVectorImpl<Type *> &OpTys, 3578 Type *RetTy, bool Predicated, 3579 const TargetTransformInfo &TTI) { 3580 unsigned ScalarizationCost = 3581 getScalarizationOverhead(RetTy, true, false, Predicated, TTI); 3582 3583 for (Type *Ty : OpTys) 3584 ScalarizationCost += 3585 getScalarizationOverhead(Ty, false, true, Predicated, TTI); 3586 3587 return ScalarizationCost; 3588 } 3589 3590 /// \brief Estimate the overhead of scalarizing an instruction. This is a 3591 /// convenience wrapper for the type-based getScalarizationOverhead API. 3592 static unsigned getScalarizationOverhead(Instruction *I, unsigned VF, 3593 bool Predicated, 3594 const TargetTransformInfo &TTI) { 3595 if (VF == 1) 3596 return 0; 3597 3598 Type *RetTy = ToVectorTy(I->getType(), VF); 3599 3600 SmallVector<Type *, 4> OpTys; 3601 unsigned OperandsNum = I->getNumOperands(); 3602 for (unsigned OpInd = 0; OpInd < OperandsNum; ++OpInd) 3603 OpTys.push_back(ToVectorTy(I->getOperand(OpInd)->getType(), VF)); 3604 3605 return getScalarizationOverhead(OpTys, RetTy, Predicated, TTI); 3606 } 3607 3608 // Estimate cost of a call instruction CI if it were vectorized with factor VF. 3609 // Return the cost of the instruction, including scalarization overhead if it's 3610 // needed. The flag NeedToScalarize shows if the call needs to be scalarized - 3611 // i.e. either vector version isn't available, or is too expensive. 3612 static unsigned getVectorCallCost(CallInst *CI, unsigned VF, 3613 const TargetTransformInfo &TTI, 3614 const TargetLibraryInfo *TLI, 3615 bool &NeedToScalarize) { 3616 Function *F = CI->getCalledFunction(); 3617 StringRef FnName = CI->getCalledFunction()->getName(); 3618 Type *ScalarRetTy = CI->getType(); 3619 SmallVector<Type *, 4> Tys, ScalarTys; 3620 for (auto &ArgOp : CI->arg_operands()) 3621 ScalarTys.push_back(ArgOp->getType()); 3622 3623 // Estimate cost of scalarized vector call. The source operands are assumed 3624 // to be vectors, so we need to extract individual elements from there, 3625 // execute VF scalar calls, and then gather the result into the vector return 3626 // value. 3627 unsigned ScalarCallCost = TTI.getCallInstrCost(F, ScalarRetTy, ScalarTys); 3628 if (VF == 1) 3629 return ScalarCallCost; 3630 3631 // Compute corresponding vector type for return value and arguments. 3632 Type *RetTy = ToVectorTy(ScalarRetTy, VF); 3633 for (Type *ScalarTy : ScalarTys) 3634 Tys.push_back(ToVectorTy(ScalarTy, VF)); 3635 3636 // Compute costs of unpacking argument values for the scalar calls and 3637 // packing the return values to a vector. 3638 unsigned ScalarizationCost = getScalarizationOverhead(Tys, RetTy, false, TTI); 3639 3640 unsigned Cost = ScalarCallCost * VF + ScalarizationCost; 3641 3642 // If we can't emit a vector call for this function, then the currently found 3643 // cost is the cost we need to return. 3644 NeedToScalarize = true; 3645 if (!TLI || !TLI->isFunctionVectorizable(FnName, VF) || CI->isNoBuiltin()) 3646 return Cost; 3647 3648 // If the corresponding vector cost is cheaper, return its cost. 3649 unsigned VectorCallCost = TTI.getCallInstrCost(nullptr, RetTy, Tys); 3650 if (VectorCallCost < Cost) { 3651 NeedToScalarize = false; 3652 return VectorCallCost; 3653 } 3654 return Cost; 3655 } 3656 3657 // Estimate cost of an intrinsic call instruction CI if it were vectorized with 3658 // factor VF. Return the cost of the instruction, including scalarization 3659 // overhead if it's needed. 3660 static unsigned getVectorIntrinsicCost(CallInst *CI, unsigned VF, 3661 const TargetTransformInfo &TTI, 3662 const TargetLibraryInfo *TLI) { 3663 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI); 3664 assert(ID && "Expected intrinsic call!"); 3665 3666 Type *RetTy = ToVectorTy(CI->getType(), VF); 3667 SmallVector<Type *, 4> Tys; 3668 for (Value *ArgOperand : CI->arg_operands()) 3669 Tys.push_back(ToVectorTy(ArgOperand->getType(), VF)); 3670 3671 FastMathFlags FMF; 3672 if (auto *FPMO = dyn_cast<FPMathOperator>(CI)) 3673 FMF = FPMO->getFastMathFlags(); 3674 3675 return TTI.getIntrinsicInstrCost(ID, RetTy, Tys, FMF); 3676 } 3677 3678 static Type *smallestIntegerVectorType(Type *T1, Type *T2) { 3679 auto *I1 = cast<IntegerType>(T1->getVectorElementType()); 3680 auto *I2 = cast<IntegerType>(T2->getVectorElementType()); 3681 return I1->getBitWidth() < I2->getBitWidth() ? T1 : T2; 3682 } 3683 static Type *largestIntegerVectorType(Type *T1, Type *T2) { 3684 auto *I1 = cast<IntegerType>(T1->getVectorElementType()); 3685 auto *I2 = cast<IntegerType>(T2->getVectorElementType()); 3686 return I1->getBitWidth() > I2->getBitWidth() ? T1 : T2; 3687 } 3688 3689 void InnerLoopVectorizer::truncateToMinimalBitwidths() { 3690 // For every instruction `I` in MinBWs, truncate the operands, create a 3691 // truncated version of `I` and reextend its result. InstCombine runs 3692 // later and will remove any ext/trunc pairs. 3693 // 3694 SmallPtrSet<Value *, 4> Erased; 3695 for (const auto &KV : Cost->getMinimalBitwidths()) { 3696 VectorParts &Parts = VectorLoopValueMap.getVector(KV.first); 3697 for (Value *&I : Parts) { 3698 if (Erased.count(I) || I->use_empty() || !isa<Instruction>(I)) 3699 continue; 3700 Type *OriginalTy = I->getType(); 3701 Type *ScalarTruncatedTy = 3702 IntegerType::get(OriginalTy->getContext(), KV.second); 3703 Type *TruncatedTy = VectorType::get(ScalarTruncatedTy, 3704 OriginalTy->getVectorNumElements()); 3705 if (TruncatedTy == OriginalTy) 3706 continue; 3707 3708 IRBuilder<> B(cast<Instruction>(I)); 3709 auto ShrinkOperand = [&](Value *V) -> Value * { 3710 if (auto *ZI = dyn_cast<ZExtInst>(V)) 3711 if (ZI->getSrcTy() == TruncatedTy) 3712 return ZI->getOperand(0); 3713 return B.CreateZExtOrTrunc(V, TruncatedTy); 3714 }; 3715 3716 // The actual instruction modification depends on the instruction type, 3717 // unfortunately. 3718 Value *NewI = nullptr; 3719 if (auto *BO = dyn_cast<BinaryOperator>(I)) { 3720 NewI = B.CreateBinOp(BO->getOpcode(), ShrinkOperand(BO->getOperand(0)), 3721 ShrinkOperand(BO->getOperand(1))); 3722 cast<BinaryOperator>(NewI)->copyIRFlags(I); 3723 } else if (auto *CI = dyn_cast<ICmpInst>(I)) { 3724 NewI = 3725 B.CreateICmp(CI->getPredicate(), ShrinkOperand(CI->getOperand(0)), 3726 ShrinkOperand(CI->getOperand(1))); 3727 } else if (auto *SI = dyn_cast<SelectInst>(I)) { 3728 NewI = B.CreateSelect(SI->getCondition(), 3729 ShrinkOperand(SI->getTrueValue()), 3730 ShrinkOperand(SI->getFalseValue())); 3731 } else if (auto *CI = dyn_cast<CastInst>(I)) { 3732 switch (CI->getOpcode()) { 3733 default: 3734 llvm_unreachable("Unhandled cast!"); 3735 case Instruction::Trunc: 3736 NewI = ShrinkOperand(CI->getOperand(0)); 3737 break; 3738 case Instruction::SExt: 3739 NewI = B.CreateSExtOrTrunc( 3740 CI->getOperand(0), 3741 smallestIntegerVectorType(OriginalTy, TruncatedTy)); 3742 break; 3743 case Instruction::ZExt: 3744 NewI = B.CreateZExtOrTrunc( 3745 CI->getOperand(0), 3746 smallestIntegerVectorType(OriginalTy, TruncatedTy)); 3747 break; 3748 } 3749 } else if (auto *SI = dyn_cast<ShuffleVectorInst>(I)) { 3750 auto Elements0 = SI->getOperand(0)->getType()->getVectorNumElements(); 3751 auto *O0 = B.CreateZExtOrTrunc( 3752 SI->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements0)); 3753 auto Elements1 = SI->getOperand(1)->getType()->getVectorNumElements(); 3754 auto *O1 = B.CreateZExtOrTrunc( 3755 SI->getOperand(1), VectorType::get(ScalarTruncatedTy, Elements1)); 3756 3757 NewI = B.CreateShuffleVector(O0, O1, SI->getMask()); 3758 } else if (isa<LoadInst>(I)) { 3759 // Don't do anything with the operands, just extend the result. 3760 continue; 3761 } else if (auto *IE = dyn_cast<InsertElementInst>(I)) { 3762 auto Elements = IE->getOperand(0)->getType()->getVectorNumElements(); 3763 auto *O0 = B.CreateZExtOrTrunc( 3764 IE->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements)); 3765 auto *O1 = B.CreateZExtOrTrunc(IE->getOperand(1), ScalarTruncatedTy); 3766 NewI = B.CreateInsertElement(O0, O1, IE->getOperand(2)); 3767 } else if (auto *EE = dyn_cast<ExtractElementInst>(I)) { 3768 auto Elements = EE->getOperand(0)->getType()->getVectorNumElements(); 3769 auto *O0 = B.CreateZExtOrTrunc( 3770 EE->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements)); 3771 NewI = B.CreateExtractElement(O0, EE->getOperand(2)); 3772 } else { 3773 llvm_unreachable("Unhandled instruction type!"); 3774 } 3775 3776 // Lastly, extend the result. 3777 NewI->takeName(cast<Instruction>(I)); 3778 Value *Res = B.CreateZExtOrTrunc(NewI, OriginalTy); 3779 I->replaceAllUsesWith(Res); 3780 cast<Instruction>(I)->eraseFromParent(); 3781 Erased.insert(I); 3782 I = Res; 3783 } 3784 } 3785 3786 // We'll have created a bunch of ZExts that are now parentless. Clean up. 3787 for (const auto &KV : Cost->getMinimalBitwidths()) { 3788 VectorParts &Parts = VectorLoopValueMap.getVector(KV.first); 3789 for (Value *&I : Parts) { 3790 ZExtInst *Inst = dyn_cast<ZExtInst>(I); 3791 if (Inst && Inst->use_empty()) { 3792 Value *NewI = Inst->getOperand(0); 3793 Inst->eraseFromParent(); 3794 I = NewI; 3795 } 3796 } 3797 } 3798 } 3799 3800 void InnerLoopVectorizer::vectorizeLoop() { 3801 //===------------------------------------------------===// 3802 // 3803 // Notice: any optimization or new instruction that go 3804 // into the code below should be also be implemented in 3805 // the cost-model. 3806 // 3807 //===------------------------------------------------===// 3808 Constant *Zero = Builder.getInt32(0); 3809 3810 // In order to support recurrences we need to be able to vectorize Phi nodes. 3811 // Phi nodes have cycles, so we need to vectorize them in two stages. First, 3812 // we create a new vector PHI node with no incoming edges. We use this value 3813 // when we vectorize all of the instructions that use the PHI. Next, after 3814 // all of the instructions in the block are complete we add the new incoming 3815 // edges to the PHI. At this point all of the instructions in the basic block 3816 // are vectorized, so we can use them to construct the PHI. 3817 PhiVector PHIsToFix; 3818 3819 // Scan the loop in a topological order to ensure that defs are vectorized 3820 // before users. 3821 LoopBlocksDFS DFS(OrigLoop); 3822 DFS.perform(LI); 3823 3824 // Vectorize all of the blocks in the original loop. 3825 for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) 3826 vectorizeBlockInLoop(BB, &PHIsToFix); 3827 3828 // Insert truncates and extends for any truncated instructions as hints to 3829 // InstCombine. 3830 if (VF > 1) 3831 truncateToMinimalBitwidths(); 3832 3833 // At this point every instruction in the original loop is widened to a 3834 // vector form. Now we need to fix the recurrences in PHIsToFix. These PHI 3835 // nodes are currently empty because we did not want to introduce cycles. 3836 // This is the second stage of vectorizing recurrences. 3837 for (PHINode *Phi : PHIsToFix) { 3838 assert(Phi && "Unable to recover vectorized PHI"); 3839 3840 // Handle first-order recurrences that need to be fixed. 3841 if (Legal->isFirstOrderRecurrence(Phi)) { 3842 fixFirstOrderRecurrence(Phi); 3843 continue; 3844 } 3845 3846 // If the phi node is not a first-order recurrence, it must be a reduction. 3847 // Get it's reduction variable descriptor. 3848 assert(Legal->isReductionVariable(Phi) && 3849 "Unable to find the reduction variable"); 3850 RecurrenceDescriptor RdxDesc = (*Legal->getReductionVars())[Phi]; 3851 3852 RecurrenceDescriptor::RecurrenceKind RK = RdxDesc.getRecurrenceKind(); 3853 TrackingVH<Value> ReductionStartValue = RdxDesc.getRecurrenceStartValue(); 3854 Instruction *LoopExitInst = RdxDesc.getLoopExitInstr(); 3855 RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind = 3856 RdxDesc.getMinMaxRecurrenceKind(); 3857 setDebugLocFromInst(Builder, ReductionStartValue); 3858 3859 // We need to generate a reduction vector from the incoming scalar. 3860 // To do so, we need to generate the 'identity' vector and override 3861 // one of the elements with the incoming scalar reduction. We need 3862 // to do it in the vector-loop preheader. 3863 Builder.SetInsertPoint(LoopBypassBlocks[1]->getTerminator()); 3864 3865 // This is the vector-clone of the value that leaves the loop. 3866 const VectorParts &VectorExit = getVectorValue(LoopExitInst); 3867 Type *VecTy = VectorExit[0]->getType(); 3868 3869 // Find the reduction identity variable. Zero for addition, or, xor, 3870 // one for multiplication, -1 for And. 3871 Value *Identity; 3872 Value *VectorStart; 3873 if (RK == RecurrenceDescriptor::RK_IntegerMinMax || 3874 RK == RecurrenceDescriptor::RK_FloatMinMax) { 3875 // MinMax reduction have the start value as their identify. 3876 if (VF == 1) { 3877 VectorStart = Identity = ReductionStartValue; 3878 } else { 3879 VectorStart = Identity = 3880 Builder.CreateVectorSplat(VF, ReductionStartValue, "minmax.ident"); 3881 } 3882 } else { 3883 // Handle other reduction kinds: 3884 Constant *Iden = RecurrenceDescriptor::getRecurrenceIdentity( 3885 RK, VecTy->getScalarType()); 3886 if (VF == 1) { 3887 Identity = Iden; 3888 // This vector is the Identity vector where the first element is the 3889 // incoming scalar reduction. 3890 VectorStart = ReductionStartValue; 3891 } else { 3892 Identity = ConstantVector::getSplat(VF, Iden); 3893 3894 // This vector is the Identity vector where the first element is the 3895 // incoming scalar reduction. 3896 VectorStart = 3897 Builder.CreateInsertElement(Identity, ReductionStartValue, Zero); 3898 } 3899 } 3900 3901 // Fix the vector-loop phi. 3902 3903 // Reductions do not have to start at zero. They can start with 3904 // any loop invariant values. 3905 const VectorParts &VecRdxPhi = getVectorValue(Phi); 3906 BasicBlock *Latch = OrigLoop->getLoopLatch(); 3907 Value *LoopVal = Phi->getIncomingValueForBlock(Latch); 3908 const VectorParts &Val = getVectorValue(LoopVal); 3909 for (unsigned part = 0; part < UF; ++part) { 3910 // Make sure to add the reduction stat value only to the 3911 // first unroll part. 3912 Value *StartVal = (part == 0) ? VectorStart : Identity; 3913 cast<PHINode>(VecRdxPhi[part]) 3914 ->addIncoming(StartVal, LoopVectorPreHeader); 3915 cast<PHINode>(VecRdxPhi[part]) 3916 ->addIncoming(Val[part], LoopVectorBody); 3917 } 3918 3919 // Before each round, move the insertion point right between 3920 // the PHIs and the values we are going to write. 3921 // This allows us to write both PHINodes and the extractelement 3922 // instructions. 3923 Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt()); 3924 3925 VectorParts &RdxParts = VectorLoopValueMap.getVector(LoopExitInst); 3926 setDebugLocFromInst(Builder, LoopExitInst); 3927 3928 // If the vector reduction can be performed in a smaller type, we truncate 3929 // then extend the loop exit value to enable InstCombine to evaluate the 3930 // entire expression in the smaller type. 3931 if (VF > 1 && Phi->getType() != RdxDesc.getRecurrenceType()) { 3932 Type *RdxVecTy = VectorType::get(RdxDesc.getRecurrenceType(), VF); 3933 Builder.SetInsertPoint(LoopVectorBody->getTerminator()); 3934 for (unsigned part = 0; part < UF; ++part) { 3935 Value *Trunc = Builder.CreateTrunc(RdxParts[part], RdxVecTy); 3936 Value *Extnd = RdxDesc.isSigned() ? Builder.CreateSExt(Trunc, VecTy) 3937 : Builder.CreateZExt(Trunc, VecTy); 3938 for (Value::user_iterator UI = RdxParts[part]->user_begin(); 3939 UI != RdxParts[part]->user_end();) 3940 if (*UI != Trunc) { 3941 (*UI++)->replaceUsesOfWith(RdxParts[part], Extnd); 3942 RdxParts[part] = Extnd; 3943 } else { 3944 ++UI; 3945 } 3946 } 3947 Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt()); 3948 for (unsigned part = 0; part < UF; ++part) 3949 RdxParts[part] = Builder.CreateTrunc(RdxParts[part], RdxVecTy); 3950 } 3951 3952 // Reduce all of the unrolled parts into a single vector. 3953 Value *ReducedPartRdx = RdxParts[0]; 3954 unsigned Op = RecurrenceDescriptor::getRecurrenceBinOp(RK); 3955 setDebugLocFromInst(Builder, ReducedPartRdx); 3956 for (unsigned part = 1; part < UF; ++part) { 3957 if (Op != Instruction::ICmp && Op != Instruction::FCmp) 3958 // Floating point operations had to be 'fast' to enable the reduction. 3959 ReducedPartRdx = addFastMathFlag( 3960 Builder.CreateBinOp((Instruction::BinaryOps)Op, RdxParts[part], 3961 ReducedPartRdx, "bin.rdx")); 3962 else 3963 ReducedPartRdx = RecurrenceDescriptor::createMinMaxOp( 3964 Builder, MinMaxKind, ReducedPartRdx, RdxParts[part]); 3965 } 3966 3967 if (VF > 1) { 3968 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles 3969 // and vector ops, reducing the set of values being computed by half each 3970 // round. 3971 assert(isPowerOf2_32(VF) && 3972 "Reduction emission only supported for pow2 vectors!"); 3973 Value *TmpVec = ReducedPartRdx; 3974 SmallVector<Constant *, 32> ShuffleMask(VF, nullptr); 3975 for (unsigned i = VF; i != 1; i >>= 1) { 3976 // Move the upper half of the vector to the lower half. 3977 for (unsigned j = 0; j != i / 2; ++j) 3978 ShuffleMask[j] = Builder.getInt32(i / 2 + j); 3979 3980 // Fill the rest of the mask with undef. 3981 std::fill(&ShuffleMask[i / 2], ShuffleMask.end(), 3982 UndefValue::get(Builder.getInt32Ty())); 3983 3984 Value *Shuf = Builder.CreateShuffleVector( 3985 TmpVec, UndefValue::get(TmpVec->getType()), 3986 ConstantVector::get(ShuffleMask), "rdx.shuf"); 3987 3988 if (Op != Instruction::ICmp && Op != Instruction::FCmp) 3989 // Floating point operations had to be 'fast' to enable the reduction. 3990 TmpVec = addFastMathFlag(Builder.CreateBinOp( 3991 (Instruction::BinaryOps)Op, TmpVec, Shuf, "bin.rdx")); 3992 else 3993 TmpVec = RecurrenceDescriptor::createMinMaxOp(Builder, MinMaxKind, 3994 TmpVec, Shuf); 3995 } 3996 3997 // The result is in the first element of the vector. 3998 ReducedPartRdx = 3999 Builder.CreateExtractElement(TmpVec, Builder.getInt32(0)); 4000 4001 // If the reduction can be performed in a smaller type, we need to extend 4002 // the reduction to the wider type before we branch to the original loop. 4003 if (Phi->getType() != RdxDesc.getRecurrenceType()) 4004 ReducedPartRdx = 4005 RdxDesc.isSigned() 4006 ? Builder.CreateSExt(ReducedPartRdx, Phi->getType()) 4007 : Builder.CreateZExt(ReducedPartRdx, Phi->getType()); 4008 } 4009 4010 // Create a phi node that merges control-flow from the backedge-taken check 4011 // block and the middle block. 4012 PHINode *BCBlockPhi = PHINode::Create(Phi->getType(), 2, "bc.merge.rdx", 4013 LoopScalarPreHeader->getTerminator()); 4014 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I) 4015 BCBlockPhi->addIncoming(ReductionStartValue, LoopBypassBlocks[I]); 4016 BCBlockPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock); 4017 4018 // Now, we need to fix the users of the reduction variable 4019 // inside and outside of the scalar remainder loop. 4020 // We know that the loop is in LCSSA form. We need to update the 4021 // PHI nodes in the exit blocks. 4022 for (BasicBlock::iterator LEI = LoopExitBlock->begin(), 4023 LEE = LoopExitBlock->end(); 4024 LEI != LEE; ++LEI) { 4025 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI); 4026 if (!LCSSAPhi) 4027 break; 4028 4029 // All PHINodes need to have a single entry edge, or two if 4030 // we already fixed them. 4031 assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI"); 4032 4033 // We found our reduction value exit-PHI. Update it with the 4034 // incoming bypass edge. 4035 if (LCSSAPhi->getIncomingValue(0) == LoopExitInst) { 4036 // Add an edge coming from the bypass. 4037 LCSSAPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock); 4038 break; 4039 } 4040 } // end of the LCSSA phi scan. 4041 4042 // Fix the scalar loop reduction variable with the incoming reduction sum 4043 // from the vector body and from the backedge value. 4044 int IncomingEdgeBlockIdx = 4045 Phi->getBasicBlockIndex(OrigLoop->getLoopLatch()); 4046 assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index"); 4047 // Pick the other block. 4048 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1); 4049 Phi->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi); 4050 Phi->setIncomingValue(IncomingEdgeBlockIdx, LoopExitInst); 4051 } // end of for each Phi in PHIsToFix. 4052 4053 fixLCSSAPHIs(); 4054 4055 // Make sure DomTree is updated. 4056 updateAnalysis(); 4057 4058 predicateInstructions(); 4059 4060 // Remove redundant induction instructions. 4061 cse(LoopVectorBody); 4062 } 4063 4064 void InnerLoopVectorizer::fixFirstOrderRecurrence(PHINode *Phi) { 4065 4066 // This is the second phase of vectorizing first-order recurrences. An 4067 // overview of the transformation is described below. Suppose we have the 4068 // following loop. 4069 // 4070 // for (int i = 0; i < n; ++i) 4071 // b[i] = a[i] - a[i - 1]; 4072 // 4073 // There is a first-order recurrence on "a". For this loop, the shorthand 4074 // scalar IR looks like: 4075 // 4076 // scalar.ph: 4077 // s_init = a[-1] 4078 // br scalar.body 4079 // 4080 // scalar.body: 4081 // i = phi [0, scalar.ph], [i+1, scalar.body] 4082 // s1 = phi [s_init, scalar.ph], [s2, scalar.body] 4083 // s2 = a[i] 4084 // b[i] = s2 - s1 4085 // br cond, scalar.body, ... 4086 // 4087 // In this example, s1 is a recurrence because it's value depends on the 4088 // previous iteration. In the first phase of vectorization, we created a 4089 // temporary value for s1. We now complete the vectorization and produce the 4090 // shorthand vector IR shown below (for VF = 4, UF = 1). 4091 // 4092 // vector.ph: 4093 // v_init = vector(..., ..., ..., a[-1]) 4094 // br vector.body 4095 // 4096 // vector.body 4097 // i = phi [0, vector.ph], [i+4, vector.body] 4098 // v1 = phi [v_init, vector.ph], [v2, vector.body] 4099 // v2 = a[i, i+1, i+2, i+3]; 4100 // v3 = vector(v1(3), v2(0, 1, 2)) 4101 // b[i, i+1, i+2, i+3] = v2 - v3 4102 // br cond, vector.body, middle.block 4103 // 4104 // middle.block: 4105 // x = v2(3) 4106 // br scalar.ph 4107 // 4108 // scalar.ph: 4109 // s_init = phi [x, middle.block], [a[-1], otherwise] 4110 // br scalar.body 4111 // 4112 // After execution completes the vector loop, we extract the next value of 4113 // the recurrence (x) to use as the initial value in the scalar loop. 4114 4115 // Get the original loop preheader and single loop latch. 4116 auto *Preheader = OrigLoop->getLoopPreheader(); 4117 auto *Latch = OrigLoop->getLoopLatch(); 4118 4119 // Get the initial and previous values of the scalar recurrence. 4120 auto *ScalarInit = Phi->getIncomingValueForBlock(Preheader); 4121 auto *Previous = Phi->getIncomingValueForBlock(Latch); 4122 4123 // Create a vector from the initial value. 4124 auto *VectorInit = ScalarInit; 4125 if (VF > 1) { 4126 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator()); 4127 VectorInit = Builder.CreateInsertElement( 4128 UndefValue::get(VectorType::get(VectorInit->getType(), VF)), VectorInit, 4129 Builder.getInt32(VF - 1), "vector.recur.init"); 4130 } 4131 4132 // We constructed a temporary phi node in the first phase of vectorization. 4133 // This phi node will eventually be deleted. 4134 VectorParts &PhiParts = VectorLoopValueMap.getVector(Phi); 4135 Builder.SetInsertPoint(cast<Instruction>(PhiParts[0])); 4136 4137 // Create a phi node for the new recurrence. The current value will either be 4138 // the initial value inserted into a vector or loop-varying vector value. 4139 auto *VecPhi = Builder.CreatePHI(VectorInit->getType(), 2, "vector.recur"); 4140 VecPhi->addIncoming(VectorInit, LoopVectorPreHeader); 4141 4142 // Get the vectorized previous value. We ensured the previous values was an 4143 // instruction when detecting the recurrence. 4144 auto &PreviousParts = getVectorValue(Previous); 4145 4146 // Set the insertion point to be after this instruction. We ensured the 4147 // previous value dominated all uses of the phi when detecting the 4148 // recurrence. 4149 Builder.SetInsertPoint( 4150 &*++BasicBlock::iterator(cast<Instruction>(PreviousParts[UF - 1]))); 4151 4152 // We will construct a vector for the recurrence by combining the values for 4153 // the current and previous iterations. This is the required shuffle mask. 4154 SmallVector<Constant *, 8> ShuffleMask(VF); 4155 ShuffleMask[0] = Builder.getInt32(VF - 1); 4156 for (unsigned I = 1; I < VF; ++I) 4157 ShuffleMask[I] = Builder.getInt32(I + VF - 1); 4158 4159 // The vector from which to take the initial value for the current iteration 4160 // (actual or unrolled). Initially, this is the vector phi node. 4161 Value *Incoming = VecPhi; 4162 4163 // Shuffle the current and previous vector and update the vector parts. 4164 for (unsigned Part = 0; Part < UF; ++Part) { 4165 auto *Shuffle = 4166 VF > 1 4167 ? Builder.CreateShuffleVector(Incoming, PreviousParts[Part], 4168 ConstantVector::get(ShuffleMask)) 4169 : Incoming; 4170 PhiParts[Part]->replaceAllUsesWith(Shuffle); 4171 cast<Instruction>(PhiParts[Part])->eraseFromParent(); 4172 PhiParts[Part] = Shuffle; 4173 Incoming = PreviousParts[Part]; 4174 } 4175 4176 // Fix the latch value of the new recurrence in the vector loop. 4177 VecPhi->addIncoming(Incoming, LI->getLoopFor(LoopVectorBody)->getLoopLatch()); 4178 4179 // Extract the last vector element in the middle block. This will be the 4180 // initial value for the recurrence when jumping to the scalar loop. 4181 auto *Extract = Incoming; 4182 if (VF > 1) { 4183 Builder.SetInsertPoint(LoopMiddleBlock->getTerminator()); 4184 Extract = Builder.CreateExtractElement(Extract, Builder.getInt32(VF - 1), 4185 "vector.recur.extract"); 4186 } 4187 4188 // Fix the initial value of the original recurrence in the scalar loop. 4189 Builder.SetInsertPoint(&*LoopScalarPreHeader->begin()); 4190 auto *Start = Builder.CreatePHI(Phi->getType(), 2, "scalar.recur.init"); 4191 for (auto *BB : predecessors(LoopScalarPreHeader)) { 4192 auto *Incoming = BB == LoopMiddleBlock ? Extract : ScalarInit; 4193 Start->addIncoming(Incoming, BB); 4194 } 4195 4196 Phi->setIncomingValue(Phi->getBasicBlockIndex(LoopScalarPreHeader), Start); 4197 Phi->setName("scalar.recur"); 4198 4199 // Finally, fix users of the recurrence outside the loop. The users will need 4200 // either the last value of the scalar recurrence or the last value of the 4201 // vector recurrence we extracted in the middle block. Since the loop is in 4202 // LCSSA form, we just need to find the phi node for the original scalar 4203 // recurrence in the exit block, and then add an edge for the middle block. 4204 for (auto &I : *LoopExitBlock) { 4205 auto *LCSSAPhi = dyn_cast<PHINode>(&I); 4206 if (!LCSSAPhi) 4207 break; 4208 if (LCSSAPhi->getIncomingValue(0) == Phi) { 4209 LCSSAPhi->addIncoming(Extract, LoopMiddleBlock); 4210 break; 4211 } 4212 } 4213 } 4214 4215 void InnerLoopVectorizer::fixLCSSAPHIs() { 4216 for (Instruction &LEI : *LoopExitBlock) { 4217 auto *LCSSAPhi = dyn_cast<PHINode>(&LEI); 4218 if (!LCSSAPhi) 4219 break; 4220 if (LCSSAPhi->getNumIncomingValues() == 1) 4221 LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()), 4222 LoopMiddleBlock); 4223 } 4224 } 4225 4226 void InnerLoopVectorizer::predicateInstructions() { 4227 4228 // For each instruction I marked for predication on value C, split I into its 4229 // own basic block to form an if-then construct over C. 4230 // Since I may be fed by extractelement and/or be feeding an insertelement 4231 // generated during scalarization we try to move such instructions into the 4232 // predicated basic block as well. For the insertelement this also means that 4233 // the PHI will be created for the resulting vector rather than for the 4234 // scalar instruction. 4235 // So for some predicated instruction, e.g. the conditional sdiv in: 4236 // 4237 // for.body: 4238 // ... 4239 // %add = add nsw i32 %mul, %0 4240 // %cmp5 = icmp sgt i32 %2, 7 4241 // br i1 %cmp5, label %if.then, label %if.end 4242 // 4243 // if.then: 4244 // %div = sdiv i32 %0, %1 4245 // br label %if.end 4246 // 4247 // if.end: 4248 // %x.0 = phi i32 [ %div, %if.then ], [ %add, %for.body ] 4249 // 4250 // the sdiv at this point is scalarized and if-converted using a select. 4251 // The inactive elements in the vector are not used, but the predicated 4252 // instruction is still executed for all vector elements, essentially: 4253 // 4254 // vector.body: 4255 // ... 4256 // %17 = add nsw <2 x i32> %16, %wide.load 4257 // %29 = extractelement <2 x i32> %wide.load, i32 0 4258 // %30 = extractelement <2 x i32> %wide.load51, i32 0 4259 // %31 = sdiv i32 %29, %30 4260 // %32 = insertelement <2 x i32> undef, i32 %31, i32 0 4261 // %35 = extractelement <2 x i32> %wide.load, i32 1 4262 // %36 = extractelement <2 x i32> %wide.load51, i32 1 4263 // %37 = sdiv i32 %35, %36 4264 // %38 = insertelement <2 x i32> %32, i32 %37, i32 1 4265 // %predphi = select <2 x i1> %26, <2 x i32> %38, <2 x i32> %17 4266 // 4267 // Predication will now re-introduce the original control flow to avoid false 4268 // side-effects by the sdiv instructions on the inactive elements, yielding 4269 // (after cleanup): 4270 // 4271 // vector.body: 4272 // ... 4273 // %5 = add nsw <2 x i32> %4, %wide.load 4274 // %8 = icmp sgt <2 x i32> %wide.load52, <i32 7, i32 7> 4275 // %9 = extractelement <2 x i1> %8, i32 0 4276 // br i1 %9, label %pred.sdiv.if, label %pred.sdiv.continue 4277 // 4278 // pred.sdiv.if: 4279 // %10 = extractelement <2 x i32> %wide.load, i32 0 4280 // %11 = extractelement <2 x i32> %wide.load51, i32 0 4281 // %12 = sdiv i32 %10, %11 4282 // %13 = insertelement <2 x i32> undef, i32 %12, i32 0 4283 // br label %pred.sdiv.continue 4284 // 4285 // pred.sdiv.continue: 4286 // %14 = phi <2 x i32> [ undef, %vector.body ], [ %13, %pred.sdiv.if ] 4287 // %15 = extractelement <2 x i1> %8, i32 1 4288 // br i1 %15, label %pred.sdiv.if54, label %pred.sdiv.continue55 4289 // 4290 // pred.sdiv.if54: 4291 // %16 = extractelement <2 x i32> %wide.load, i32 1 4292 // %17 = extractelement <2 x i32> %wide.load51, i32 1 4293 // %18 = sdiv i32 %16, %17 4294 // %19 = insertelement <2 x i32> %14, i32 %18, i32 1 4295 // br label %pred.sdiv.continue55 4296 // 4297 // pred.sdiv.continue55: 4298 // %20 = phi <2 x i32> [ %14, %pred.sdiv.continue ], [ %19, %pred.sdiv.if54 ] 4299 // %predphi = select <2 x i1> %8, <2 x i32> %20, <2 x i32> %5 4300 4301 for (auto KV : PredicatedInstructions) { 4302 BasicBlock::iterator I(KV.first); 4303 BasicBlock *Head = I->getParent(); 4304 auto *BB = SplitBlock(Head, &*std::next(I), DT, LI); 4305 auto *T = SplitBlockAndInsertIfThen(KV.second, &*I, /*Unreachable=*/false, 4306 /*BranchWeights=*/nullptr, DT, LI); 4307 I->moveBefore(T); 4308 // Try to move any extractelement we may have created for the predicated 4309 // instruction into the Then block. 4310 for (Use &Op : I->operands()) { 4311 auto *OpInst = dyn_cast<ExtractElementInst>(&*Op); 4312 if (OpInst && OpInst->hasOneUse()) // TODO: more accurately - hasOneUser() 4313 OpInst->moveBefore(&*I); 4314 } 4315 4316 I->getParent()->setName(Twine("pred.") + I->getOpcodeName() + ".if"); 4317 BB->setName(Twine("pred.") + I->getOpcodeName() + ".continue"); 4318 4319 // If the instruction is non-void create a Phi node at reconvergence point. 4320 if (!I->getType()->isVoidTy()) { 4321 Value *IncomingTrue = nullptr; 4322 Value *IncomingFalse = nullptr; 4323 4324 if (I->hasOneUse() && isa<InsertElementInst>(*I->user_begin())) { 4325 // If the predicated instruction is feeding an insert-element, move it 4326 // into the Then block; Phi node will be created for the vector. 4327 InsertElementInst *IEI = cast<InsertElementInst>(*I->user_begin()); 4328 IEI->moveBefore(T); 4329 IncomingTrue = IEI; // the new vector with the inserted element. 4330 IncomingFalse = IEI->getOperand(0); // the unmodified vector 4331 } else { 4332 // Phi node will be created for the scalar predicated instruction. 4333 IncomingTrue = &*I; 4334 IncomingFalse = UndefValue::get(I->getType()); 4335 } 4336 4337 BasicBlock *PostDom = I->getParent()->getSingleSuccessor(); 4338 assert(PostDom && "Then block has multiple successors"); 4339 PHINode *Phi = 4340 PHINode::Create(IncomingTrue->getType(), 2, "", &PostDom->front()); 4341 IncomingTrue->replaceAllUsesWith(Phi); 4342 Phi->addIncoming(IncomingFalse, Head); 4343 Phi->addIncoming(IncomingTrue, I->getParent()); 4344 } 4345 } 4346 4347 DEBUG(DT->verifyDomTree()); 4348 } 4349 4350 InnerLoopVectorizer::VectorParts 4351 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) { 4352 assert(is_contained(predecessors(Dst), Src) && "Invalid edge"); 4353 4354 // Look for cached value. 4355 std::pair<BasicBlock *, BasicBlock *> Edge(Src, Dst); 4356 EdgeMaskCache::iterator ECEntryIt = MaskCache.find(Edge); 4357 if (ECEntryIt != MaskCache.end()) 4358 return ECEntryIt->second; 4359 4360 VectorParts SrcMask = createBlockInMask(Src); 4361 4362 // The terminator has to be a branch inst! 4363 BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator()); 4364 assert(BI && "Unexpected terminator found"); 4365 4366 if (BI->isConditional()) { 4367 VectorParts EdgeMask = getVectorValue(BI->getCondition()); 4368 4369 if (BI->getSuccessor(0) != Dst) 4370 for (unsigned part = 0; part < UF; ++part) 4371 EdgeMask[part] = Builder.CreateNot(EdgeMask[part]); 4372 4373 for (unsigned part = 0; part < UF; ++part) 4374 EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]); 4375 4376 MaskCache[Edge] = EdgeMask; 4377 return EdgeMask; 4378 } 4379 4380 MaskCache[Edge] = SrcMask; 4381 return SrcMask; 4382 } 4383 4384 InnerLoopVectorizer::VectorParts 4385 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) { 4386 assert(OrigLoop->contains(BB) && "Block is not a part of a loop"); 4387 4388 // Loop incoming mask is all-one. 4389 if (OrigLoop->getHeader() == BB) { 4390 Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1); 4391 return getVectorValue(C); 4392 } 4393 4394 // This is the block mask. We OR all incoming edges, and with zero. 4395 Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0); 4396 VectorParts BlockMask = getVectorValue(Zero); 4397 4398 // For each pred: 4399 for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) { 4400 VectorParts EM = createEdgeMask(*it, BB); 4401 for (unsigned part = 0; part < UF; ++part) 4402 BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]); 4403 } 4404 4405 return BlockMask; 4406 } 4407 4408 void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN, unsigned UF, 4409 unsigned VF, PhiVector *PV) { 4410 PHINode *P = cast<PHINode>(PN); 4411 // Handle recurrences. 4412 if (Legal->isReductionVariable(P) || Legal->isFirstOrderRecurrence(P)) { 4413 VectorParts Entry(UF); 4414 for (unsigned part = 0; part < UF; ++part) { 4415 // This is phase one of vectorizing PHIs. 4416 Type *VecTy = 4417 (VF == 1) ? PN->getType() : VectorType::get(PN->getType(), VF); 4418 Entry[part] = PHINode::Create( 4419 VecTy, 2, "vec.phi", &*LoopVectorBody->getFirstInsertionPt()); 4420 } 4421 VectorLoopValueMap.initVector(P, Entry); 4422 PV->push_back(P); 4423 return; 4424 } 4425 4426 setDebugLocFromInst(Builder, P); 4427 // Check for PHI nodes that are lowered to vector selects. 4428 if (P->getParent() != OrigLoop->getHeader()) { 4429 // We know that all PHIs in non-header blocks are converted into 4430 // selects, so we don't have to worry about the insertion order and we 4431 // can just use the builder. 4432 // At this point we generate the predication tree. There may be 4433 // duplications since this is a simple recursive scan, but future 4434 // optimizations will clean it up. 4435 4436 unsigned NumIncoming = P->getNumIncomingValues(); 4437 4438 // Generate a sequence of selects of the form: 4439 // SELECT(Mask3, In3, 4440 // SELECT(Mask2, In2, 4441 // ( ...))) 4442 VectorParts Entry(UF); 4443 for (unsigned In = 0; In < NumIncoming; In++) { 4444 VectorParts Cond = 4445 createEdgeMask(P->getIncomingBlock(In), P->getParent()); 4446 const VectorParts &In0 = getVectorValue(P->getIncomingValue(In)); 4447 4448 for (unsigned part = 0; part < UF; ++part) { 4449 // We might have single edge PHIs (blocks) - use an identity 4450 // 'select' for the first PHI operand. 4451 if (In == 0) 4452 Entry[part] = Builder.CreateSelect(Cond[part], In0[part], In0[part]); 4453 else 4454 // Select between the current value and the previous incoming edge 4455 // based on the incoming mask. 4456 Entry[part] = Builder.CreateSelect(Cond[part], In0[part], Entry[part], 4457 "predphi"); 4458 } 4459 } 4460 VectorLoopValueMap.initVector(P, Entry); 4461 return; 4462 } 4463 4464 // This PHINode must be an induction variable. 4465 // Make sure that we know about it. 4466 assert(Legal->getInductionVars()->count(P) && "Not an induction variable"); 4467 4468 InductionDescriptor II = Legal->getInductionVars()->lookup(P); 4469 const DataLayout &DL = OrigLoop->getHeader()->getModule()->getDataLayout(); 4470 4471 // FIXME: The newly created binary instructions should contain nsw/nuw flags, 4472 // which can be found from the original scalar operations. 4473 switch (II.getKind()) { 4474 case InductionDescriptor::IK_NoInduction: 4475 llvm_unreachable("Unknown induction"); 4476 case InductionDescriptor::IK_IntInduction: 4477 return widenIntInduction(P); 4478 case InductionDescriptor::IK_PtrInduction: { 4479 // Handle the pointer induction variable case. 4480 assert(P->getType()->isPointerTy() && "Unexpected type."); 4481 // This is the normalized GEP that starts counting at zero. 4482 Value *PtrInd = Induction; 4483 PtrInd = Builder.CreateSExtOrTrunc(PtrInd, II.getStep()->getType()); 4484 // Determine the number of scalars we need to generate for each unroll 4485 // iteration. If the instruction is uniform, we only need to generate the 4486 // first lane. Otherwise, we generate all VF values. 4487 unsigned Lanes = Legal->isUniformAfterVectorization(P) ? 1 : VF; 4488 // These are the scalar results. Notice that we don't generate vector GEPs 4489 // because scalar GEPs result in better code. 4490 ScalarParts Entry(UF); 4491 for (unsigned Part = 0; Part < UF; ++Part) { 4492 Entry[Part].resize(VF); 4493 for (unsigned Lane = 0; Lane < Lanes; ++Lane) { 4494 Constant *Idx = ConstantInt::get(PtrInd->getType(), Lane + Part * VF); 4495 Value *GlobalIdx = Builder.CreateAdd(PtrInd, Idx); 4496 Value *SclrGep = II.transform(Builder, GlobalIdx, PSE.getSE(), DL); 4497 SclrGep->setName("next.gep"); 4498 Entry[Part][Lane] = SclrGep; 4499 } 4500 } 4501 VectorLoopValueMap.initScalar(P, Entry); 4502 return; 4503 } 4504 case InductionDescriptor::IK_FpInduction: { 4505 assert(P->getType() == II.getStartValue()->getType() && 4506 "Types must match"); 4507 // Handle other induction variables that are now based on the 4508 // canonical one. 4509 assert(P != OldInduction && "Primary induction can be integer only"); 4510 4511 Value *V = Builder.CreateCast(Instruction::SIToFP, Induction, P->getType()); 4512 V = II.transform(Builder, V, PSE.getSE(), DL); 4513 V->setName("fp.offset.idx"); 4514 4515 // Now we have scalar op: %fp.offset.idx = StartVal +/- Induction*StepVal 4516 4517 Value *Broadcasted = getBroadcastInstrs(V); 4518 // After broadcasting the induction variable we need to make the vector 4519 // consecutive by adding StepVal*0, StepVal*1, StepVal*2, etc. 4520 Value *StepVal = cast<SCEVUnknown>(II.getStep())->getValue(); 4521 VectorParts Entry(UF); 4522 for (unsigned part = 0; part < UF; ++part) 4523 Entry[part] = getStepVector(Broadcasted, VF * part, StepVal, 4524 II.getInductionOpcode()); 4525 VectorLoopValueMap.initVector(P, Entry); 4526 return; 4527 } 4528 } 4529 } 4530 4531 /// A helper function for checking whether an integer division-related 4532 /// instruction may divide by zero (in which case it must be predicated if 4533 /// executed conditionally in the scalar code). 4534 /// TODO: It may be worthwhile to generalize and check isKnownNonZero(). 4535 /// Non-zero divisors that are non compile-time constants will not be 4536 /// converted into multiplication, so we will still end up scalarizing 4537 /// the division, but can do so w/o predication. 4538 static bool mayDivideByZero(Instruction &I) { 4539 assert((I.getOpcode() == Instruction::UDiv || 4540 I.getOpcode() == Instruction::SDiv || 4541 I.getOpcode() == Instruction::URem || 4542 I.getOpcode() == Instruction::SRem) && 4543 "Unexpected instruction"); 4544 Value *Divisor = I.getOperand(1); 4545 auto *CInt = dyn_cast<ConstantInt>(Divisor); 4546 return !CInt || CInt->isZero(); 4547 } 4548 4549 void InnerLoopVectorizer::vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV) { 4550 // For each instruction in the old loop. 4551 for (Instruction &I : *BB) { 4552 4553 // Scalarize instructions that should remain scalar after vectorization. 4554 if (!(isa<BranchInst>(&I) || isa<PHINode>(&I) || 4555 isa<DbgInfoIntrinsic>(&I)) && 4556 Legal->isScalarAfterVectorization(&I)) { 4557 scalarizeInstruction(&I); 4558 continue; 4559 } 4560 4561 switch (I.getOpcode()) { 4562 case Instruction::Br: 4563 // Nothing to do for PHIs and BR, since we already took care of the 4564 // loop control flow instructions. 4565 continue; 4566 case Instruction::PHI: { 4567 // Vectorize PHINodes. 4568 widenPHIInstruction(&I, UF, VF, PV); 4569 continue; 4570 } // End of PHI. 4571 4572 case Instruction::UDiv: 4573 case Instruction::SDiv: 4574 case Instruction::SRem: 4575 case Instruction::URem: 4576 // Scalarize with predication if this instruction may divide by zero and 4577 // block execution is conditional, otherwise fallthrough. 4578 if (Legal->isScalarWithPredication(&I)) { 4579 scalarizeInstruction(&I, true); 4580 continue; 4581 } 4582 case Instruction::Add: 4583 case Instruction::FAdd: 4584 case Instruction::Sub: 4585 case Instruction::FSub: 4586 case Instruction::Mul: 4587 case Instruction::FMul: 4588 case Instruction::FDiv: 4589 case Instruction::FRem: 4590 case Instruction::Shl: 4591 case Instruction::LShr: 4592 case Instruction::AShr: 4593 case Instruction::And: 4594 case Instruction::Or: 4595 case Instruction::Xor: { 4596 // Just widen binops. 4597 auto *BinOp = cast<BinaryOperator>(&I); 4598 setDebugLocFromInst(Builder, BinOp); 4599 const VectorParts &A = getVectorValue(BinOp->getOperand(0)); 4600 const VectorParts &B = getVectorValue(BinOp->getOperand(1)); 4601 4602 // Use this vector value for all users of the original instruction. 4603 VectorParts Entry(UF); 4604 for (unsigned Part = 0; Part < UF; ++Part) { 4605 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]); 4606 4607 if (BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V)) 4608 VecOp->copyIRFlags(BinOp); 4609 4610 Entry[Part] = V; 4611 } 4612 4613 VectorLoopValueMap.initVector(&I, Entry); 4614 addMetadata(Entry, BinOp); 4615 break; 4616 } 4617 case Instruction::Select: { 4618 // Widen selects. 4619 // If the selector is loop invariant we can create a select 4620 // instruction with a scalar condition. Otherwise, use vector-select. 4621 auto *SE = PSE.getSE(); 4622 bool InvariantCond = 4623 SE->isLoopInvariant(PSE.getSCEV(I.getOperand(0)), OrigLoop); 4624 setDebugLocFromInst(Builder, &I); 4625 4626 // The condition can be loop invariant but still defined inside the 4627 // loop. This means that we can't just use the original 'cond' value. 4628 // We have to take the 'vectorized' value and pick the first lane. 4629 // Instcombine will make this a no-op. 4630 const VectorParts &Cond = getVectorValue(I.getOperand(0)); 4631 const VectorParts &Op0 = getVectorValue(I.getOperand(1)); 4632 const VectorParts &Op1 = getVectorValue(I.getOperand(2)); 4633 4634 auto *ScalarCond = getScalarValue(I.getOperand(0), 0, 0); 4635 4636 VectorParts Entry(UF); 4637 for (unsigned Part = 0; Part < UF; ++Part) { 4638 Entry[Part] = Builder.CreateSelect( 4639 InvariantCond ? ScalarCond : Cond[Part], Op0[Part], Op1[Part]); 4640 } 4641 4642 VectorLoopValueMap.initVector(&I, Entry); 4643 addMetadata(Entry, &I); 4644 break; 4645 } 4646 4647 case Instruction::ICmp: 4648 case Instruction::FCmp: { 4649 // Widen compares. Generate vector compares. 4650 bool FCmp = (I.getOpcode() == Instruction::FCmp); 4651 auto *Cmp = dyn_cast<CmpInst>(&I); 4652 setDebugLocFromInst(Builder, Cmp); 4653 const VectorParts &A = getVectorValue(Cmp->getOperand(0)); 4654 const VectorParts &B = getVectorValue(Cmp->getOperand(1)); 4655 VectorParts Entry(UF); 4656 for (unsigned Part = 0; Part < UF; ++Part) { 4657 Value *C = nullptr; 4658 if (FCmp) { 4659 C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]); 4660 cast<FCmpInst>(C)->copyFastMathFlags(Cmp); 4661 } else { 4662 C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]); 4663 } 4664 Entry[Part] = C; 4665 } 4666 4667 VectorLoopValueMap.initVector(&I, Entry); 4668 addMetadata(Entry, &I); 4669 break; 4670 } 4671 4672 case Instruction::Store: 4673 case Instruction::Load: 4674 vectorizeMemoryInstruction(&I); 4675 break; 4676 case Instruction::ZExt: 4677 case Instruction::SExt: 4678 case Instruction::FPToUI: 4679 case Instruction::FPToSI: 4680 case Instruction::FPExt: 4681 case Instruction::PtrToInt: 4682 case Instruction::IntToPtr: 4683 case Instruction::SIToFP: 4684 case Instruction::UIToFP: 4685 case Instruction::Trunc: 4686 case Instruction::FPTrunc: 4687 case Instruction::BitCast: { 4688 auto *CI = dyn_cast<CastInst>(&I); 4689 setDebugLocFromInst(Builder, CI); 4690 4691 // Optimize the special case where the source is a constant integer 4692 // induction variable. Notice that we can only optimize the 'trunc' case 4693 // because (a) FP conversions lose precision, (b) sext/zext may wrap, and 4694 // (c) other casts depend on pointer size. 4695 auto ID = Legal->getInductionVars()->lookup(OldInduction); 4696 if (isa<TruncInst>(CI) && CI->getOperand(0) == OldInduction && 4697 ID.getConstIntStepValue()) { 4698 widenIntInduction(OldInduction, cast<TruncInst>(CI)); 4699 break; 4700 } 4701 4702 /// Vectorize casts. 4703 Type *DestTy = 4704 (VF == 1) ? CI->getType() : VectorType::get(CI->getType(), VF); 4705 4706 const VectorParts &A = getVectorValue(CI->getOperand(0)); 4707 VectorParts Entry(UF); 4708 for (unsigned Part = 0; Part < UF; ++Part) 4709 Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy); 4710 VectorLoopValueMap.initVector(&I, Entry); 4711 addMetadata(Entry, &I); 4712 break; 4713 } 4714 4715 case Instruction::Call: { 4716 // Ignore dbg intrinsics. 4717 if (isa<DbgInfoIntrinsic>(I)) 4718 break; 4719 setDebugLocFromInst(Builder, &I); 4720 4721 Module *M = BB->getParent()->getParent(); 4722 auto *CI = cast<CallInst>(&I); 4723 4724 StringRef FnName = CI->getCalledFunction()->getName(); 4725 Function *F = CI->getCalledFunction(); 4726 Type *RetTy = ToVectorTy(CI->getType(), VF); 4727 SmallVector<Type *, 4> Tys; 4728 for (Value *ArgOperand : CI->arg_operands()) 4729 Tys.push_back(ToVectorTy(ArgOperand->getType(), VF)); 4730 4731 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI); 4732 if (ID && (ID == Intrinsic::assume || ID == Intrinsic::lifetime_end || 4733 ID == Intrinsic::lifetime_start)) { 4734 scalarizeInstruction(&I); 4735 break; 4736 } 4737 // The flag shows whether we use Intrinsic or a usual Call for vectorized 4738 // version of the instruction. 4739 // Is it beneficial to perform intrinsic call compared to lib call? 4740 bool NeedToScalarize; 4741 unsigned CallCost = getVectorCallCost(CI, VF, *TTI, TLI, NeedToScalarize); 4742 bool UseVectorIntrinsic = 4743 ID && getVectorIntrinsicCost(CI, VF, *TTI, TLI) <= CallCost; 4744 if (!UseVectorIntrinsic && NeedToScalarize) { 4745 scalarizeInstruction(&I); 4746 break; 4747 } 4748 4749 VectorParts Entry(UF); 4750 for (unsigned Part = 0; Part < UF; ++Part) { 4751 SmallVector<Value *, 4> Args; 4752 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) { 4753 Value *Arg = CI->getArgOperand(i); 4754 // Some intrinsics have a scalar argument - don't replace it with a 4755 // vector. 4756 if (!UseVectorIntrinsic || !hasVectorInstrinsicScalarOpd(ID, i)) { 4757 const VectorParts &VectorArg = getVectorValue(CI->getArgOperand(i)); 4758 Arg = VectorArg[Part]; 4759 } 4760 Args.push_back(Arg); 4761 } 4762 4763 Function *VectorF; 4764 if (UseVectorIntrinsic) { 4765 // Use vector version of the intrinsic. 4766 Type *TysForDecl[] = {CI->getType()}; 4767 if (VF > 1) 4768 TysForDecl[0] = VectorType::get(CI->getType()->getScalarType(), VF); 4769 VectorF = Intrinsic::getDeclaration(M, ID, TysForDecl); 4770 } else { 4771 // Use vector version of the library call. 4772 StringRef VFnName = TLI->getVectorizedFunction(FnName, VF); 4773 assert(!VFnName.empty() && "Vector function name is empty."); 4774 VectorF = M->getFunction(VFnName); 4775 if (!VectorF) { 4776 // Generate a declaration 4777 FunctionType *FTy = FunctionType::get(RetTy, Tys, false); 4778 VectorF = 4779 Function::Create(FTy, Function::ExternalLinkage, VFnName, M); 4780 VectorF->copyAttributesFrom(F); 4781 } 4782 } 4783 assert(VectorF && "Can't create vector function."); 4784 4785 SmallVector<OperandBundleDef, 1> OpBundles; 4786 CI->getOperandBundlesAsDefs(OpBundles); 4787 CallInst *V = Builder.CreateCall(VectorF, Args, OpBundles); 4788 4789 if (isa<FPMathOperator>(V)) 4790 V->copyFastMathFlags(CI); 4791 4792 Entry[Part] = V; 4793 } 4794 4795 VectorLoopValueMap.initVector(&I, Entry); 4796 addMetadata(Entry, &I); 4797 break; 4798 } 4799 4800 default: 4801 // All other instructions are unsupported. Scalarize them. 4802 scalarizeInstruction(&I); 4803 break; 4804 } // end of switch. 4805 } // end of for_each instr. 4806 } 4807 4808 void InnerLoopVectorizer::updateAnalysis() { 4809 // Forget the original basic block. 4810 PSE.getSE()->forgetLoop(OrigLoop); 4811 4812 // Update the dominator tree information. 4813 assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) && 4814 "Entry does not dominate exit."); 4815 4816 // We don't predicate stores by this point, so the vector body should be a 4817 // single loop. 4818 DT->addNewBlock(LoopVectorBody, LoopVectorPreHeader); 4819 4820 DT->addNewBlock(LoopMiddleBlock, LoopVectorBody); 4821 DT->addNewBlock(LoopScalarPreHeader, LoopBypassBlocks[0]); 4822 DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader); 4823 DT->changeImmediateDominator(LoopExitBlock, LoopBypassBlocks[0]); 4824 4825 DEBUG(DT->verifyDomTree()); 4826 } 4827 4828 /// \brief Check whether it is safe to if-convert this phi node. 4829 /// 4830 /// Phi nodes with constant expressions that can trap are not safe to if 4831 /// convert. 4832 static bool canIfConvertPHINodes(BasicBlock *BB) { 4833 for (Instruction &I : *BB) { 4834 auto *Phi = dyn_cast<PHINode>(&I); 4835 if (!Phi) 4836 return true; 4837 for (Value *V : Phi->incoming_values()) 4838 if (auto *C = dyn_cast<Constant>(V)) 4839 if (C->canTrap()) 4840 return false; 4841 } 4842 return true; 4843 } 4844 4845 bool LoopVectorizationLegality::canVectorizeWithIfConvert() { 4846 if (!EnableIfConversion) { 4847 ORE->emit(createMissedAnalysis("IfConversionDisabled") 4848 << "if-conversion is disabled"); 4849 return false; 4850 } 4851 4852 assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable"); 4853 4854 // A list of pointers that we can safely read and write to. 4855 SmallPtrSet<Value *, 8> SafePointes; 4856 4857 // Collect safe addresses. 4858 for (BasicBlock *BB : TheLoop->blocks()) { 4859 if (blockNeedsPredication(BB)) 4860 continue; 4861 4862 for (Instruction &I : *BB) 4863 if (auto *Ptr = getPointerOperand(&I)) 4864 SafePointes.insert(Ptr); 4865 } 4866 4867 // Collect the blocks that need predication. 4868 BasicBlock *Header = TheLoop->getHeader(); 4869 for (BasicBlock *BB : TheLoop->blocks()) { 4870 // We don't support switch statements inside loops. 4871 if (!isa<BranchInst>(BB->getTerminator())) { 4872 ORE->emit(createMissedAnalysis("LoopContainsSwitch", BB->getTerminator()) 4873 << "loop contains a switch statement"); 4874 return false; 4875 } 4876 4877 // We must be able to predicate all blocks that need to be predicated. 4878 if (blockNeedsPredication(BB)) { 4879 if (!blockCanBePredicated(BB, SafePointes)) { 4880 ORE->emit(createMissedAnalysis("NoCFGForSelect", BB->getTerminator()) 4881 << "control flow cannot be substituted for a select"); 4882 return false; 4883 } 4884 } else if (BB != Header && !canIfConvertPHINodes(BB)) { 4885 ORE->emit(createMissedAnalysis("NoCFGForSelect", BB->getTerminator()) 4886 << "control flow cannot be substituted for a select"); 4887 return false; 4888 } 4889 } 4890 4891 // We can if-convert this loop. 4892 return true; 4893 } 4894 4895 bool LoopVectorizationLegality::canVectorize() { 4896 // We must have a loop in canonical form. Loops with indirectbr in them cannot 4897 // be canonicalized. 4898 if (!TheLoop->getLoopPreheader()) { 4899 ORE->emit(createMissedAnalysis("CFGNotUnderstood") 4900 << "loop control flow is not understood by vectorizer"); 4901 return false; 4902 } 4903 4904 // FIXME: The code is currently dead, since the loop gets sent to 4905 // LoopVectorizationLegality is already an innermost loop. 4906 // 4907 // We can only vectorize innermost loops. 4908 if (!TheLoop->empty()) { 4909 ORE->emit(createMissedAnalysis("NotInnermostLoop") 4910 << "loop is not the innermost loop"); 4911 return false; 4912 } 4913 4914 // We must have a single backedge. 4915 if (TheLoop->getNumBackEdges() != 1) { 4916 ORE->emit(createMissedAnalysis("CFGNotUnderstood") 4917 << "loop control flow is not understood by vectorizer"); 4918 return false; 4919 } 4920 4921 // We must have a single exiting block. 4922 if (!TheLoop->getExitingBlock()) { 4923 ORE->emit(createMissedAnalysis("CFGNotUnderstood") 4924 << "loop control flow is not understood by vectorizer"); 4925 return false; 4926 } 4927 4928 // We only handle bottom-tested loops, i.e. loop in which the condition is 4929 // checked at the end of each iteration. With that we can assume that all 4930 // instructions in the loop are executed the same number of times. 4931 if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) { 4932 ORE->emit(createMissedAnalysis("CFGNotUnderstood") 4933 << "loop control flow is not understood by vectorizer"); 4934 return false; 4935 } 4936 4937 // We need to have a loop header. 4938 DEBUG(dbgs() << "LV: Found a loop: " << TheLoop->getHeader()->getName() 4939 << '\n'); 4940 4941 // Check if we can if-convert non-single-bb loops. 4942 unsigned NumBlocks = TheLoop->getNumBlocks(); 4943 if (NumBlocks != 1 && !canVectorizeWithIfConvert()) { 4944 DEBUG(dbgs() << "LV: Can't if-convert the loop.\n"); 4945 return false; 4946 } 4947 4948 // ScalarEvolution needs to be able to find the exit count. 4949 const SCEV *ExitCount = PSE.getBackedgeTakenCount(); 4950 if (ExitCount == PSE.getSE()->getCouldNotCompute()) { 4951 ORE->emit(createMissedAnalysis("CantComputeNumberOfIterations") 4952 << "could not determine number of loop iterations"); 4953 DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n"); 4954 return false; 4955 } 4956 4957 // Check if we can vectorize the instructions and CFG in this loop. 4958 if (!canVectorizeInstrs()) { 4959 DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n"); 4960 return false; 4961 } 4962 4963 // Go over each instruction and look at memory deps. 4964 if (!canVectorizeMemory()) { 4965 DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n"); 4966 return false; 4967 } 4968 4969 DEBUG(dbgs() << "LV: We can vectorize this loop" 4970 << (LAI->getRuntimePointerChecking()->Need 4971 ? " (with a runtime bound check)" 4972 : "") 4973 << "!\n"); 4974 4975 bool UseInterleaved = TTI->enableInterleavedAccessVectorization(); 4976 4977 // If an override option has been passed in for interleaved accesses, use it. 4978 if (EnableInterleavedMemAccesses.getNumOccurrences() > 0) 4979 UseInterleaved = EnableInterleavedMemAccesses; 4980 4981 // Analyze interleaved memory accesses. 4982 if (UseInterleaved) 4983 InterleaveInfo.analyzeInterleaving(*getSymbolicStrides()); 4984 4985 // Collect all instructions that are known to be uniform after vectorization. 4986 collectLoopUniforms(); 4987 4988 // Collect all instructions that are known to be scalar after vectorization. 4989 collectLoopScalars(); 4990 4991 unsigned SCEVThreshold = VectorizeSCEVCheckThreshold; 4992 if (Hints->getForce() == LoopVectorizeHints::FK_Enabled) 4993 SCEVThreshold = PragmaVectorizeSCEVCheckThreshold; 4994 4995 if (PSE.getUnionPredicate().getComplexity() > SCEVThreshold) { 4996 ORE->emit(createMissedAnalysis("TooManySCEVRunTimeChecks") 4997 << "Too many SCEV assumptions need to be made and checked " 4998 << "at runtime"); 4999 DEBUG(dbgs() << "LV: Too many SCEV checks needed.\n"); 5000 return false; 5001 } 5002 5003 // Okay! We can vectorize. At this point we don't have any other mem analysis 5004 // which may limit our maximum vectorization factor, so just return true with 5005 // no restrictions. 5006 return true; 5007 } 5008 5009 static Type *convertPointerToIntegerType(const DataLayout &DL, Type *Ty) { 5010 if (Ty->isPointerTy()) 5011 return DL.getIntPtrType(Ty); 5012 5013 // It is possible that char's or short's overflow when we ask for the loop's 5014 // trip count, work around this by changing the type size. 5015 if (Ty->getScalarSizeInBits() < 32) 5016 return Type::getInt32Ty(Ty->getContext()); 5017 5018 return Ty; 5019 } 5020 5021 static Type *getWiderType(const DataLayout &DL, Type *Ty0, Type *Ty1) { 5022 Ty0 = convertPointerToIntegerType(DL, Ty0); 5023 Ty1 = convertPointerToIntegerType(DL, Ty1); 5024 if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits()) 5025 return Ty0; 5026 return Ty1; 5027 } 5028 5029 /// \brief Check that the instruction has outside loop users and is not an 5030 /// identified reduction variable. 5031 static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst, 5032 SmallPtrSetImpl<Value *> &AllowedExit) { 5033 // Reduction and Induction instructions are allowed to have exit users. All 5034 // other instructions must not have external users. 5035 if (!AllowedExit.count(Inst)) 5036 // Check that all of the users of the loop are inside the BB. 5037 for (User *U : Inst->users()) { 5038 Instruction *UI = cast<Instruction>(U); 5039 // This user may be a reduction exit value. 5040 if (!TheLoop->contains(UI)) { 5041 DEBUG(dbgs() << "LV: Found an outside user for : " << *UI << '\n'); 5042 return true; 5043 } 5044 } 5045 return false; 5046 } 5047 5048 void LoopVectorizationLegality::addInductionPhi( 5049 PHINode *Phi, const InductionDescriptor &ID, 5050 SmallPtrSetImpl<Value *> &AllowedExit) { 5051 Inductions[Phi] = ID; 5052 Type *PhiTy = Phi->getType(); 5053 const DataLayout &DL = Phi->getModule()->getDataLayout(); 5054 5055 // Get the widest type. 5056 if (!PhiTy->isFloatingPointTy()) { 5057 if (!WidestIndTy) 5058 WidestIndTy = convertPointerToIntegerType(DL, PhiTy); 5059 else 5060 WidestIndTy = getWiderType(DL, PhiTy, WidestIndTy); 5061 } 5062 5063 // Int inductions are special because we only allow one IV. 5064 if (ID.getKind() == InductionDescriptor::IK_IntInduction && 5065 ID.getConstIntStepValue() && 5066 ID.getConstIntStepValue()->isOne() && 5067 isa<Constant>(ID.getStartValue()) && 5068 cast<Constant>(ID.getStartValue())->isNullValue()) { 5069 5070 // Use the phi node with the widest type as induction. Use the last 5071 // one if there are multiple (no good reason for doing this other 5072 // than it is expedient). We've checked that it begins at zero and 5073 // steps by one, so this is a canonical induction variable. 5074 if (!Induction || PhiTy == WidestIndTy) 5075 Induction = Phi; 5076 } 5077 5078 // Both the PHI node itself, and the "post-increment" value feeding 5079 // back into the PHI node may have external users. 5080 AllowedExit.insert(Phi); 5081 AllowedExit.insert(Phi->getIncomingValueForBlock(TheLoop->getLoopLatch())); 5082 5083 DEBUG(dbgs() << "LV: Found an induction variable.\n"); 5084 return; 5085 } 5086 5087 bool LoopVectorizationLegality::canVectorizeInstrs() { 5088 BasicBlock *Header = TheLoop->getHeader(); 5089 5090 // Look for the attribute signaling the absence of NaNs. 5091 Function &F = *Header->getParent(); 5092 HasFunNoNaNAttr = 5093 F.getFnAttribute("no-nans-fp-math").getValueAsString() == "true"; 5094 5095 // For each block in the loop. 5096 for (BasicBlock *BB : TheLoop->blocks()) { 5097 // Scan the instructions in the block and look for hazards. 5098 for (Instruction &I : *BB) { 5099 if (auto *Phi = dyn_cast<PHINode>(&I)) { 5100 Type *PhiTy = Phi->getType(); 5101 // Check that this PHI type is allowed. 5102 if (!PhiTy->isIntegerTy() && !PhiTy->isFloatingPointTy() && 5103 !PhiTy->isPointerTy()) { 5104 ORE->emit(createMissedAnalysis("CFGNotUnderstood", Phi) 5105 << "loop control flow is not understood by vectorizer"); 5106 DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n"); 5107 return false; 5108 } 5109 5110 // If this PHINode is not in the header block, then we know that we 5111 // can convert it to select during if-conversion. No need to check if 5112 // the PHIs in this block are induction or reduction variables. 5113 if (BB != Header) { 5114 // Check that this instruction has no outside users or is an 5115 // identified reduction value with an outside user. 5116 if (!hasOutsideLoopUser(TheLoop, Phi, AllowedExit)) 5117 continue; 5118 ORE->emit(createMissedAnalysis("NeitherInductionNorReduction", Phi) 5119 << "value could not be identified as " 5120 "an induction or reduction variable"); 5121 return false; 5122 } 5123 5124 // We only allow if-converted PHIs with exactly two incoming values. 5125 if (Phi->getNumIncomingValues() != 2) { 5126 ORE->emit(createMissedAnalysis("CFGNotUnderstood", Phi) 5127 << "control flow not understood by vectorizer"); 5128 DEBUG(dbgs() << "LV: Found an invalid PHI.\n"); 5129 return false; 5130 } 5131 5132 RecurrenceDescriptor RedDes; 5133 if (RecurrenceDescriptor::isReductionPHI(Phi, TheLoop, RedDes)) { 5134 if (RedDes.hasUnsafeAlgebra()) 5135 Requirements->addUnsafeAlgebraInst(RedDes.getUnsafeAlgebraInst()); 5136 AllowedExit.insert(RedDes.getLoopExitInstr()); 5137 Reductions[Phi] = RedDes; 5138 continue; 5139 } 5140 5141 InductionDescriptor ID; 5142 if (InductionDescriptor::isInductionPHI(Phi, TheLoop, PSE, ID)) { 5143 addInductionPhi(Phi, ID, AllowedExit); 5144 if (ID.hasUnsafeAlgebra() && !HasFunNoNaNAttr) 5145 Requirements->addUnsafeAlgebraInst(ID.getUnsafeAlgebraInst()); 5146 continue; 5147 } 5148 5149 if (RecurrenceDescriptor::isFirstOrderRecurrence(Phi, TheLoop, DT)) { 5150 FirstOrderRecurrences.insert(Phi); 5151 continue; 5152 } 5153 5154 // As a last resort, coerce the PHI to a AddRec expression 5155 // and re-try classifying it a an induction PHI. 5156 if (InductionDescriptor::isInductionPHI(Phi, TheLoop, PSE, ID, true)) { 5157 addInductionPhi(Phi, ID, AllowedExit); 5158 continue; 5159 } 5160 5161 ORE->emit(createMissedAnalysis("NonReductionValueUsedOutsideLoop", Phi) 5162 << "value that could not be identified as " 5163 "reduction is used outside the loop"); 5164 DEBUG(dbgs() << "LV: Found an unidentified PHI." << *Phi << "\n"); 5165 return false; 5166 } // end of PHI handling 5167 5168 // We handle calls that: 5169 // * Are debug info intrinsics. 5170 // * Have a mapping to an IR intrinsic. 5171 // * Have a vector version available. 5172 auto *CI = dyn_cast<CallInst>(&I); 5173 if (CI && !getVectorIntrinsicIDForCall(CI, TLI) && 5174 !isa<DbgInfoIntrinsic>(CI) && 5175 !(CI->getCalledFunction() && TLI && 5176 TLI->isFunctionVectorizable(CI->getCalledFunction()->getName()))) { 5177 ORE->emit(createMissedAnalysis("CantVectorizeCall", CI) 5178 << "call instruction cannot be vectorized"); 5179 DEBUG(dbgs() << "LV: Found a non-intrinsic, non-libfunc callsite.\n"); 5180 return false; 5181 } 5182 5183 // Intrinsics such as powi,cttz and ctlz are legal to vectorize if the 5184 // second argument is the same (i.e. loop invariant) 5185 if (CI && hasVectorInstrinsicScalarOpd( 5186 getVectorIntrinsicIDForCall(CI, TLI), 1)) { 5187 auto *SE = PSE.getSE(); 5188 if (!SE->isLoopInvariant(PSE.getSCEV(CI->getOperand(1)), TheLoop)) { 5189 ORE->emit(createMissedAnalysis("CantVectorizeIntrinsic", CI) 5190 << "intrinsic instruction cannot be vectorized"); 5191 DEBUG(dbgs() << "LV: Found unvectorizable intrinsic " << *CI << "\n"); 5192 return false; 5193 } 5194 } 5195 5196 // Check that the instruction return type is vectorizable. 5197 // Also, we can't vectorize extractelement instructions. 5198 if ((!VectorType::isValidElementType(I.getType()) && 5199 !I.getType()->isVoidTy()) || 5200 isa<ExtractElementInst>(I)) { 5201 ORE->emit(createMissedAnalysis("CantVectorizeInstructionReturnType", &I) 5202 << "instruction return type cannot be vectorized"); 5203 DEBUG(dbgs() << "LV: Found unvectorizable type.\n"); 5204 return false; 5205 } 5206 5207 // Check that the stored type is vectorizable. 5208 if (auto *ST = dyn_cast<StoreInst>(&I)) { 5209 Type *T = ST->getValueOperand()->getType(); 5210 if (!VectorType::isValidElementType(T)) { 5211 ORE->emit(createMissedAnalysis("CantVectorizeStore", ST) 5212 << "store instruction cannot be vectorized"); 5213 return false; 5214 } 5215 5216 // FP instructions can allow unsafe algebra, thus vectorizable by 5217 // non-IEEE-754 compliant SIMD units. 5218 // This applies to floating-point math operations and calls, not memory 5219 // operations, shuffles, or casts, as they don't change precision or 5220 // semantics. 5221 } else if (I.getType()->isFloatingPointTy() && (CI || I.isBinaryOp()) && 5222 !I.hasUnsafeAlgebra()) { 5223 DEBUG(dbgs() << "LV: Found FP op with unsafe algebra.\n"); 5224 Hints->setPotentiallyUnsafe(); 5225 } 5226 5227 // Reduction instructions are allowed to have exit users. 5228 // All other instructions must not have external users. 5229 if (hasOutsideLoopUser(TheLoop, &I, AllowedExit)) { 5230 ORE->emit(createMissedAnalysis("ValueUsedOutsideLoop", &I) 5231 << "value cannot be used outside the loop"); 5232 return false; 5233 } 5234 5235 } // next instr. 5236 } 5237 5238 if (!Induction) { 5239 DEBUG(dbgs() << "LV: Did not find one integer induction var.\n"); 5240 if (Inductions.empty()) { 5241 ORE->emit(createMissedAnalysis("NoInductionVariable") 5242 << "loop induction variable could not be identified"); 5243 return false; 5244 } 5245 } 5246 5247 // Now we know the widest induction type, check if our found induction 5248 // is the same size. If it's not, unset it here and InnerLoopVectorizer 5249 // will create another. 5250 if (Induction && WidestIndTy != Induction->getType()) 5251 Induction = nullptr; 5252 5253 return true; 5254 } 5255 5256 void LoopVectorizationLegality::collectLoopScalars() { 5257 5258 // If an instruction is uniform after vectorization, it will remain scalar. 5259 Scalars.insert(Uniforms.begin(), Uniforms.end()); 5260 5261 // Collect the getelementptr instructions that will not be vectorized. A 5262 // getelementptr instruction is only vectorized if it is used for a legal 5263 // gather or scatter operation. 5264 for (auto *BB : TheLoop->blocks()) 5265 for (auto &I : *BB) { 5266 if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) { 5267 Scalars.insert(GEP); 5268 continue; 5269 } 5270 auto *Ptr = getPointerOperand(&I); 5271 if (!Ptr) 5272 continue; 5273 auto *GEP = getGEPInstruction(Ptr); 5274 if (GEP && isLegalGatherOrScatter(&I)) 5275 Scalars.erase(GEP); 5276 } 5277 5278 // An induction variable will remain scalar if all users of the induction 5279 // variable and induction variable update remain scalar. 5280 auto *Latch = TheLoop->getLoopLatch(); 5281 for (auto &Induction : *getInductionVars()) { 5282 auto *Ind = Induction.first; 5283 auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch)); 5284 5285 // Determine if all users of the induction variable are scalar after 5286 // vectorization. 5287 auto ScalarInd = all_of(Ind->users(), [&](User *U) -> bool { 5288 auto *I = cast<Instruction>(U); 5289 return I == IndUpdate || !TheLoop->contains(I) || Scalars.count(I); 5290 }); 5291 if (!ScalarInd) 5292 continue; 5293 5294 // Determine if all users of the induction variable update instruction are 5295 // scalar after vectorization. 5296 auto ScalarIndUpdate = all_of(IndUpdate->users(), [&](User *U) -> bool { 5297 auto *I = cast<Instruction>(U); 5298 return I == Ind || !TheLoop->contains(I) || Scalars.count(I); 5299 }); 5300 if (!ScalarIndUpdate) 5301 continue; 5302 5303 // The induction variable and its update instruction will remain scalar. 5304 Scalars.insert(Ind); 5305 Scalars.insert(IndUpdate); 5306 } 5307 } 5308 5309 bool LoopVectorizationLegality::hasConsecutiveLikePtrOperand(Instruction *I) { 5310 if (isAccessInterleaved(I)) 5311 return true; 5312 if (auto *Ptr = getPointerOperand(I)) 5313 return isConsecutivePtr(Ptr); 5314 return false; 5315 } 5316 5317 bool LoopVectorizationLegality::isScalarWithPredication(Instruction *I) { 5318 if (!blockNeedsPredication(I->getParent())) 5319 return false; 5320 switch(I->getOpcode()) { 5321 default: 5322 break; 5323 case Instruction::Store: 5324 return !isMaskRequired(I); 5325 case Instruction::UDiv: 5326 case Instruction::SDiv: 5327 case Instruction::SRem: 5328 case Instruction::URem: 5329 return mayDivideByZero(*I); 5330 } 5331 return false; 5332 } 5333 5334 bool LoopVectorizationLegality::memoryInstructionMustBeScalarized( 5335 Instruction *I, unsigned VF) { 5336 5337 // If the memory instruction is in an interleaved group, it will be 5338 // vectorized and its pointer will remain uniform. 5339 if (isAccessInterleaved(I)) 5340 return false; 5341 5342 // Get and ensure we have a valid memory instruction. 5343 LoadInst *LI = dyn_cast<LoadInst>(I); 5344 StoreInst *SI = dyn_cast<StoreInst>(I); 5345 assert((LI || SI) && "Invalid memory instruction"); 5346 5347 // If the pointer operand is uniform (loop invariant), the memory instruction 5348 // will be scalarized. 5349 auto *Ptr = getPointerOperand(I); 5350 if (LI && isUniform(Ptr)) 5351 return true; 5352 5353 // If the pointer operand is non-consecutive and neither a gather nor a 5354 // scatter operation is legal, the memory instruction will be scalarized. 5355 if (!isConsecutivePtr(Ptr) && !isLegalGatherOrScatter(I)) 5356 return true; 5357 5358 // If the instruction is a store located in a predicated block, it will be 5359 // scalarized. 5360 if (isScalarWithPredication(I)) 5361 return true; 5362 5363 // If the instruction's allocated size doesn't equal it's type size, it 5364 // requires padding and will be scalarized. 5365 auto &DL = I->getModule()->getDataLayout(); 5366 auto *ScalarTy = LI ? LI->getType() : SI->getValueOperand()->getType(); 5367 if (hasIrregularType(ScalarTy, DL, VF)) 5368 return true; 5369 5370 // Otherwise, the memory instruction should be vectorized if the rest of the 5371 // loop is. 5372 return false; 5373 } 5374 5375 void LoopVectorizationLegality::collectLoopUniforms() { 5376 // We now know that the loop is vectorizable! 5377 // Collect instructions inside the loop that will remain uniform after 5378 // vectorization. 5379 5380 // Global values, params and instructions outside of current loop are out of 5381 // scope. 5382 auto isOutOfScope = [&](Value *V) -> bool { 5383 Instruction *I = dyn_cast<Instruction>(V); 5384 return (!I || !TheLoop->contains(I)); 5385 }; 5386 5387 SetVector<Instruction *> Worklist; 5388 BasicBlock *Latch = TheLoop->getLoopLatch(); 5389 5390 // Start with the conditional branch. If the branch condition is an 5391 // instruction contained in the loop that is only used by the branch, it is 5392 // uniform. 5393 auto *Cmp = dyn_cast<Instruction>(Latch->getTerminator()->getOperand(0)); 5394 if (Cmp && TheLoop->contains(Cmp) && Cmp->hasOneUse()) { 5395 Worklist.insert(Cmp); 5396 DEBUG(dbgs() << "LV: Found uniform instruction: " << *Cmp << "\n"); 5397 } 5398 5399 // Holds consecutive and consecutive-like pointers. Consecutive-like pointers 5400 // are pointers that are treated like consecutive pointers during 5401 // vectorization. The pointer operands of interleaved accesses are an 5402 // example. 5403 SmallPtrSet<Instruction *, 8> ConsecutiveLikePtrs; 5404 5405 // Holds pointer operands of instructions that are possibly non-uniform. 5406 SmallPtrSet<Instruction *, 8> PossibleNonUniformPtrs; 5407 5408 // Iterate over the instructions in the loop, and collect all 5409 // consecutive-like pointer operands in ConsecutiveLikePtrs. If it's possible 5410 // that a consecutive-like pointer operand will be scalarized, we collect it 5411 // in PossibleNonUniformPtrs instead. We use two sets here because a single 5412 // getelementptr instruction can be used by both vectorized and scalarized 5413 // memory instructions. For example, if a loop loads and stores from the same 5414 // location, but the store is conditional, the store will be scalarized, and 5415 // the getelementptr won't remain uniform. 5416 for (auto *BB : TheLoop->blocks()) 5417 for (auto &I : *BB) { 5418 5419 // If there's no pointer operand, there's nothing to do. 5420 auto *Ptr = dyn_cast_or_null<Instruction>(getPointerOperand(&I)); 5421 if (!Ptr) 5422 continue; 5423 5424 // True if all users of Ptr are memory accesses that have Ptr as their 5425 // pointer operand. 5426 auto UsersAreMemAccesses = all_of(Ptr->users(), [&](User *U) -> bool { 5427 return getPointerOperand(U) == Ptr; 5428 }); 5429 5430 // Ensure the memory instruction will not be scalarized, making its 5431 // pointer operand non-uniform. If the pointer operand is used by some 5432 // instruction other than a memory access, we're not going to check if 5433 // that other instruction may be scalarized here. Thus, conservatively 5434 // assume the pointer operand may be non-uniform. 5435 if (!UsersAreMemAccesses || memoryInstructionMustBeScalarized(&I)) 5436 PossibleNonUniformPtrs.insert(Ptr); 5437 5438 // If the memory instruction will be vectorized and its pointer operand 5439 // is consecutive-like, the pointer operand should remain uniform. 5440 else if (hasConsecutiveLikePtrOperand(&I)) 5441 ConsecutiveLikePtrs.insert(Ptr); 5442 } 5443 5444 // Add to the Worklist all consecutive and consecutive-like pointers that 5445 // aren't also identified as possibly non-uniform. 5446 for (auto *V : ConsecutiveLikePtrs) 5447 if (!PossibleNonUniformPtrs.count(V)) { 5448 DEBUG(dbgs() << "LV: Found uniform instruction: " << *V << "\n"); 5449 Worklist.insert(V); 5450 } 5451 5452 // Expand Worklist in topological order: whenever a new instruction 5453 // is added , its users should be either already inside Worklist, or 5454 // out of scope. It ensures a uniform instruction will only be used 5455 // by uniform instructions or out of scope instructions. 5456 unsigned idx = 0; 5457 while (idx != Worklist.size()) { 5458 Instruction *I = Worklist[idx++]; 5459 5460 for (auto OV : I->operand_values()) { 5461 if (isOutOfScope(OV)) 5462 continue; 5463 auto *OI = cast<Instruction>(OV); 5464 if (all_of(OI->users(), [&](User *U) -> bool { 5465 return isOutOfScope(U) || Worklist.count(cast<Instruction>(U)); 5466 })) { 5467 Worklist.insert(OI); 5468 DEBUG(dbgs() << "LV: Found uniform instruction: " << *OI << "\n"); 5469 } 5470 } 5471 } 5472 5473 // Returns true if Ptr is the pointer operand of a memory access instruction 5474 // I, and I is known to not require scalarization. 5475 auto isVectorizedMemAccessUse = [&](Instruction *I, Value *Ptr) -> bool { 5476 return getPointerOperand(I) == Ptr && !memoryInstructionMustBeScalarized(I); 5477 }; 5478 5479 // For an instruction to be added into Worklist above, all its users inside 5480 // the loop should also be in Worklist. However, this condition cannot be 5481 // true for phi nodes that form a cyclic dependence. We must process phi 5482 // nodes separately. An induction variable will remain uniform if all users 5483 // of the induction variable and induction variable update remain uniform. 5484 // The code below handles both pointer and non-pointer induction variables. 5485 for (auto &Induction : Inductions) { 5486 auto *Ind = Induction.first; 5487 auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch)); 5488 5489 // Determine if all users of the induction variable are uniform after 5490 // vectorization. 5491 auto UniformInd = all_of(Ind->users(), [&](User *U) -> bool { 5492 auto *I = cast<Instruction>(U); 5493 return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) || 5494 isVectorizedMemAccessUse(I, Ind); 5495 }); 5496 if (!UniformInd) 5497 continue; 5498 5499 // Determine if all users of the induction variable update instruction are 5500 // uniform after vectorization. 5501 auto UniformIndUpdate = all_of(IndUpdate->users(), [&](User *U) -> bool { 5502 auto *I = cast<Instruction>(U); 5503 return I == Ind || !TheLoop->contains(I) || Worklist.count(I) || 5504 isVectorizedMemAccessUse(I, IndUpdate); 5505 }); 5506 if (!UniformIndUpdate) 5507 continue; 5508 5509 // The induction variable and its update instruction will remain uniform. 5510 Worklist.insert(Ind); 5511 Worklist.insert(IndUpdate); 5512 DEBUG(dbgs() << "LV: Found uniform instruction: " << *Ind << "\n"); 5513 DEBUG(dbgs() << "LV: Found uniform instruction: " << *IndUpdate << "\n"); 5514 } 5515 5516 Uniforms.insert(Worklist.begin(), Worklist.end()); 5517 } 5518 5519 bool LoopVectorizationLegality::canVectorizeMemory() { 5520 LAI = &(*GetLAA)(*TheLoop); 5521 InterleaveInfo.setLAI(LAI); 5522 const OptimizationRemarkAnalysis *LAR = LAI->getReport(); 5523 if (LAR) { 5524 OptimizationRemarkAnalysis VR(Hints->vectorizeAnalysisPassName(), 5525 "loop not vectorized: ", *LAR); 5526 ORE->emit(VR); 5527 } 5528 if (!LAI->canVectorizeMemory()) 5529 return false; 5530 5531 if (LAI->hasStoreToLoopInvariantAddress()) { 5532 ORE->emit(createMissedAnalysis("CantVectorizeStoreToLoopInvariantAddress") 5533 << "write to a loop invariant address could not be vectorized"); 5534 DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n"); 5535 return false; 5536 } 5537 5538 Requirements->addRuntimePointerChecks(LAI->getNumRuntimePointerChecks()); 5539 PSE.addPredicate(LAI->getPSE().getUnionPredicate()); 5540 5541 return true; 5542 } 5543 5544 bool LoopVectorizationLegality::isInductionVariable(const Value *V) { 5545 Value *In0 = const_cast<Value *>(V); 5546 PHINode *PN = dyn_cast_or_null<PHINode>(In0); 5547 if (!PN) 5548 return false; 5549 5550 return Inductions.count(PN); 5551 } 5552 5553 bool LoopVectorizationLegality::isFirstOrderRecurrence(const PHINode *Phi) { 5554 return FirstOrderRecurrences.count(Phi); 5555 } 5556 5557 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) { 5558 return LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT); 5559 } 5560 5561 bool LoopVectorizationLegality::blockCanBePredicated( 5562 BasicBlock *BB, SmallPtrSetImpl<Value *> &SafePtrs) { 5563 const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel(); 5564 5565 for (Instruction &I : *BB) { 5566 // Check that we don't have a constant expression that can trap as operand. 5567 for (Value *Operand : I.operands()) { 5568 if (auto *C = dyn_cast<Constant>(Operand)) 5569 if (C->canTrap()) 5570 return false; 5571 } 5572 // We might be able to hoist the load. 5573 if (I.mayReadFromMemory()) { 5574 auto *LI = dyn_cast<LoadInst>(&I); 5575 if (!LI) 5576 return false; 5577 if (!SafePtrs.count(LI->getPointerOperand())) { 5578 if (isLegalMaskedLoad(LI->getType(), LI->getPointerOperand()) || 5579 isLegalMaskedGather(LI->getType())) { 5580 MaskedOp.insert(LI); 5581 continue; 5582 } 5583 // !llvm.mem.parallel_loop_access implies if-conversion safety. 5584 if (IsAnnotatedParallel) 5585 continue; 5586 return false; 5587 } 5588 } 5589 5590 if (I.mayWriteToMemory()) { 5591 auto *SI = dyn_cast<StoreInst>(&I); 5592 // We only support predication of stores in basic blocks with one 5593 // predecessor. 5594 if (!SI) 5595 return false; 5596 5597 // Build a masked store if it is legal for the target. 5598 if (isLegalMaskedStore(SI->getValueOperand()->getType(), 5599 SI->getPointerOperand()) || 5600 isLegalMaskedScatter(SI->getValueOperand()->getType())) { 5601 MaskedOp.insert(SI); 5602 continue; 5603 } 5604 5605 bool isSafePtr = (SafePtrs.count(SI->getPointerOperand()) != 0); 5606 bool isSinglePredecessor = SI->getParent()->getSinglePredecessor(); 5607 5608 if (++NumPredStores > NumberOfStoresToPredicate || !isSafePtr || 5609 !isSinglePredecessor) 5610 return false; 5611 } 5612 if (I.mayThrow()) 5613 return false; 5614 } 5615 5616 return true; 5617 } 5618 5619 void InterleavedAccessInfo::collectConstStrideAccesses( 5620 MapVector<Instruction *, StrideDescriptor> &AccessStrideInfo, 5621 const ValueToValueMap &Strides) { 5622 5623 auto &DL = TheLoop->getHeader()->getModule()->getDataLayout(); 5624 5625 // Since it's desired that the load/store instructions be maintained in 5626 // "program order" for the interleaved access analysis, we have to visit the 5627 // blocks in the loop in reverse postorder (i.e., in a topological order). 5628 // Such an ordering will ensure that any load/store that may be executed 5629 // before a second load/store will precede the second load/store in 5630 // AccessStrideInfo. 5631 LoopBlocksDFS DFS(TheLoop); 5632 DFS.perform(LI); 5633 for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) 5634 for (auto &I : *BB) { 5635 auto *LI = dyn_cast<LoadInst>(&I); 5636 auto *SI = dyn_cast<StoreInst>(&I); 5637 if (!LI && !SI) 5638 continue; 5639 5640 Value *Ptr = getPointerOperand(&I); 5641 int64_t Stride = getPtrStride(PSE, Ptr, TheLoop, Strides); 5642 5643 const SCEV *Scev = replaceSymbolicStrideSCEV(PSE, Strides, Ptr); 5644 PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType()); 5645 uint64_t Size = DL.getTypeAllocSize(PtrTy->getElementType()); 5646 5647 // An alignment of 0 means target ABI alignment. 5648 unsigned Align = LI ? LI->getAlignment() : SI->getAlignment(); 5649 if (!Align) 5650 Align = DL.getABITypeAlignment(PtrTy->getElementType()); 5651 5652 AccessStrideInfo[&I] = StrideDescriptor(Stride, Scev, Size, Align); 5653 } 5654 } 5655 5656 // Analyze interleaved accesses and collect them into interleaved load and 5657 // store groups. 5658 // 5659 // When generating code for an interleaved load group, we effectively hoist all 5660 // loads in the group to the location of the first load in program order. When 5661 // generating code for an interleaved store group, we sink all stores to the 5662 // location of the last store. This code motion can change the order of load 5663 // and store instructions and may break dependences. 5664 // 5665 // The code generation strategy mentioned above ensures that we won't violate 5666 // any write-after-read (WAR) dependences. 5667 // 5668 // E.g., for the WAR dependence: a = A[i]; // (1) 5669 // A[i] = b; // (2) 5670 // 5671 // The store group of (2) is always inserted at or below (2), and the load 5672 // group of (1) is always inserted at or above (1). Thus, the instructions will 5673 // never be reordered. All other dependences are checked to ensure the 5674 // correctness of the instruction reordering. 5675 // 5676 // The algorithm visits all memory accesses in the loop in bottom-up program 5677 // order. Program order is established by traversing the blocks in the loop in 5678 // reverse postorder when collecting the accesses. 5679 // 5680 // We visit the memory accesses in bottom-up order because it can simplify the 5681 // construction of store groups in the presence of write-after-write (WAW) 5682 // dependences. 5683 // 5684 // E.g., for the WAW dependence: A[i] = a; // (1) 5685 // A[i] = b; // (2) 5686 // A[i + 1] = c; // (3) 5687 // 5688 // We will first create a store group with (3) and (2). (1) can't be added to 5689 // this group because it and (2) are dependent. However, (1) can be grouped 5690 // with other accesses that may precede it in program order. Note that a 5691 // bottom-up order does not imply that WAW dependences should not be checked. 5692 void InterleavedAccessInfo::analyzeInterleaving( 5693 const ValueToValueMap &Strides) { 5694 DEBUG(dbgs() << "LV: Analyzing interleaved accesses...\n"); 5695 5696 // Holds all accesses with a constant stride. 5697 MapVector<Instruction *, StrideDescriptor> AccessStrideInfo; 5698 collectConstStrideAccesses(AccessStrideInfo, Strides); 5699 5700 if (AccessStrideInfo.empty()) 5701 return; 5702 5703 // Collect the dependences in the loop. 5704 collectDependences(); 5705 5706 // Holds all interleaved store groups temporarily. 5707 SmallSetVector<InterleaveGroup *, 4> StoreGroups; 5708 // Holds all interleaved load groups temporarily. 5709 SmallSetVector<InterleaveGroup *, 4> LoadGroups; 5710 5711 // Search in bottom-up program order for pairs of accesses (A and B) that can 5712 // form interleaved load or store groups. In the algorithm below, access A 5713 // precedes access B in program order. We initialize a group for B in the 5714 // outer loop of the algorithm, and then in the inner loop, we attempt to 5715 // insert each A into B's group if: 5716 // 5717 // 1. A and B have the same stride, 5718 // 2. A and B have the same memory object size, and 5719 // 3. A belongs in B's group according to its distance from B. 5720 // 5721 // Special care is taken to ensure group formation will not break any 5722 // dependences. 5723 for (auto BI = AccessStrideInfo.rbegin(), E = AccessStrideInfo.rend(); 5724 BI != E; ++BI) { 5725 Instruction *B = BI->first; 5726 StrideDescriptor DesB = BI->second; 5727 5728 // Initialize a group for B if it has an allowable stride. Even if we don't 5729 // create a group for B, we continue with the bottom-up algorithm to ensure 5730 // we don't break any of B's dependences. 5731 InterleaveGroup *Group = nullptr; 5732 if (isStrided(DesB.Stride)) { 5733 Group = getInterleaveGroup(B); 5734 if (!Group) { 5735 DEBUG(dbgs() << "LV: Creating an interleave group with:" << *B << '\n'); 5736 Group = createInterleaveGroup(B, DesB.Stride, DesB.Align); 5737 } 5738 if (B->mayWriteToMemory()) 5739 StoreGroups.insert(Group); 5740 else 5741 LoadGroups.insert(Group); 5742 } 5743 5744 for (auto AI = std::next(BI); AI != E; ++AI) { 5745 Instruction *A = AI->first; 5746 StrideDescriptor DesA = AI->second; 5747 5748 // Our code motion strategy implies that we can't have dependences 5749 // between accesses in an interleaved group and other accesses located 5750 // between the first and last member of the group. Note that this also 5751 // means that a group can't have more than one member at a given offset. 5752 // The accesses in a group can have dependences with other accesses, but 5753 // we must ensure we don't extend the boundaries of the group such that 5754 // we encompass those dependent accesses. 5755 // 5756 // For example, assume we have the sequence of accesses shown below in a 5757 // stride-2 loop: 5758 // 5759 // (1, 2) is a group | A[i] = a; // (1) 5760 // | A[i-1] = b; // (2) | 5761 // A[i-3] = c; // (3) 5762 // A[i] = d; // (4) | (2, 4) is not a group 5763 // 5764 // Because accesses (2) and (3) are dependent, we can group (2) with (1) 5765 // but not with (4). If we did, the dependent access (3) would be within 5766 // the boundaries of the (2, 4) group. 5767 if (!canReorderMemAccessesForInterleavedGroups(&*AI, &*BI)) { 5768 5769 // If a dependence exists and A is already in a group, we know that A 5770 // must be a store since A precedes B and WAR dependences are allowed. 5771 // Thus, A would be sunk below B. We release A's group to prevent this 5772 // illegal code motion. A will then be free to form another group with 5773 // instructions that precede it. 5774 if (isInterleaved(A)) { 5775 InterleaveGroup *StoreGroup = getInterleaveGroup(A); 5776 StoreGroups.remove(StoreGroup); 5777 releaseGroup(StoreGroup); 5778 } 5779 5780 // If a dependence exists and A is not already in a group (or it was 5781 // and we just released it), B might be hoisted above A (if B is a 5782 // load) or another store might be sunk below A (if B is a store). In 5783 // either case, we can't add additional instructions to B's group. B 5784 // will only form a group with instructions that it precedes. 5785 break; 5786 } 5787 5788 // At this point, we've checked for illegal code motion. If either A or B 5789 // isn't strided, there's nothing left to do. 5790 if (!isStrided(DesA.Stride) || !isStrided(DesB.Stride)) 5791 continue; 5792 5793 // Ignore A if it's already in a group or isn't the same kind of memory 5794 // operation as B. 5795 if (isInterleaved(A) || A->mayReadFromMemory() != B->mayReadFromMemory()) 5796 continue; 5797 5798 // Check rules 1 and 2. Ignore A if its stride or size is different from 5799 // that of B. 5800 if (DesA.Stride != DesB.Stride || DesA.Size != DesB.Size) 5801 continue; 5802 5803 // Calculate the distance from A to B. 5804 const SCEVConstant *DistToB = dyn_cast<SCEVConstant>( 5805 PSE.getSE()->getMinusSCEV(DesA.Scev, DesB.Scev)); 5806 if (!DistToB) 5807 continue; 5808 int64_t DistanceToB = DistToB->getAPInt().getSExtValue(); 5809 5810 // Check rule 3. Ignore A if its distance to B is not a multiple of the 5811 // size. 5812 if (DistanceToB % static_cast<int64_t>(DesB.Size)) 5813 continue; 5814 5815 // Ignore A if either A or B is in a predicated block. Although we 5816 // currently prevent group formation for predicated accesses, we may be 5817 // able to relax this limitation in the future once we handle more 5818 // complicated blocks. 5819 if (isPredicated(A->getParent()) || isPredicated(B->getParent())) 5820 continue; 5821 5822 // The index of A is the index of B plus A's distance to B in multiples 5823 // of the size. 5824 int IndexA = 5825 Group->getIndex(B) + DistanceToB / static_cast<int64_t>(DesB.Size); 5826 5827 // Try to insert A into B's group. 5828 if (Group->insertMember(A, IndexA, DesA.Align)) { 5829 DEBUG(dbgs() << "LV: Inserted:" << *A << '\n' 5830 << " into the interleave group with" << *B << '\n'); 5831 InterleaveGroupMap[A] = Group; 5832 5833 // Set the first load in program order as the insert position. 5834 if (A->mayReadFromMemory()) 5835 Group->setInsertPos(A); 5836 } 5837 } // Iteration over A accesses. 5838 } // Iteration over B accesses. 5839 5840 // Remove interleaved store groups with gaps. 5841 for (InterleaveGroup *Group : StoreGroups) 5842 if (Group->getNumMembers() != Group->getFactor()) 5843 releaseGroup(Group); 5844 5845 // If there is a non-reversed interleaved load group with gaps, we will need 5846 // to execute at least one scalar epilogue iteration. This will ensure that 5847 // we don't speculatively access memory out-of-bounds. Note that we only need 5848 // to look for a member at index factor - 1, since every group must have a 5849 // member at index zero. 5850 for (InterleaveGroup *Group : LoadGroups) 5851 if (!Group->getMember(Group->getFactor() - 1)) { 5852 if (Group->isReverse()) { 5853 releaseGroup(Group); 5854 } else { 5855 DEBUG(dbgs() << "LV: Interleaved group requires epilogue iteration.\n"); 5856 RequiresScalarEpilogue = true; 5857 } 5858 } 5859 } 5860 5861 LoopVectorizationCostModel::VectorizationFactor 5862 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize) { 5863 // Width 1 means no vectorize 5864 VectorizationFactor Factor = {1U, 0U}; 5865 if (OptForSize && Legal->getRuntimePointerChecking()->Need) { 5866 ORE->emit(createMissedAnalysis("CantVersionLoopWithOptForSize") 5867 << "runtime pointer checks needed. Enable vectorization of this " 5868 "loop with '#pragma clang loop vectorize(enable)' when " 5869 "compiling with -Os/-Oz"); 5870 DEBUG(dbgs() 5871 << "LV: Aborting. Runtime ptr check is required with -Os/-Oz.\n"); 5872 return Factor; 5873 } 5874 5875 if (!EnableCondStoresVectorization && Legal->getNumPredStores()) { 5876 ORE->emit(createMissedAnalysis("ConditionalStore") 5877 << "store that is conditionally executed prevents vectorization"); 5878 DEBUG(dbgs() << "LV: No vectorization. There are conditional stores.\n"); 5879 return Factor; 5880 } 5881 5882 // Find the trip count. 5883 unsigned TC = PSE.getSE()->getSmallConstantTripCount(TheLoop); 5884 DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n'); 5885 5886 MinBWs = computeMinimumValueSizes(TheLoop->getBlocks(), *DB, &TTI); 5887 unsigned SmallestType, WidestType; 5888 std::tie(SmallestType, WidestType) = getSmallestAndWidestTypes(); 5889 unsigned WidestRegister = TTI.getRegisterBitWidth(true); 5890 unsigned MaxSafeDepDist = -1U; 5891 5892 // Get the maximum safe dependence distance in bits computed by LAA. If the 5893 // loop contains any interleaved accesses, we divide the dependence distance 5894 // by the maximum interleave factor of all interleaved groups. Note that 5895 // although the division ensures correctness, this is a fairly conservative 5896 // computation because the maximum distance computed by LAA may not involve 5897 // any of the interleaved accesses. 5898 if (Legal->getMaxSafeDepDistBytes() != -1U) 5899 MaxSafeDepDist = 5900 Legal->getMaxSafeDepDistBytes() * 8 / Legal->getMaxInterleaveFactor(); 5901 5902 WidestRegister = 5903 ((WidestRegister < MaxSafeDepDist) ? WidestRegister : MaxSafeDepDist); 5904 unsigned MaxVectorSize = WidestRegister / WidestType; 5905 5906 DEBUG(dbgs() << "LV: The Smallest and Widest types: " << SmallestType << " / " 5907 << WidestType << " bits.\n"); 5908 DEBUG(dbgs() << "LV: The Widest register is: " << WidestRegister 5909 << " bits.\n"); 5910 5911 if (MaxVectorSize == 0) { 5912 DEBUG(dbgs() << "LV: The target has no vector registers.\n"); 5913 MaxVectorSize = 1; 5914 } 5915 5916 assert(MaxVectorSize <= 64 && "Did not expect to pack so many elements" 5917 " into one vector!"); 5918 5919 unsigned VF = MaxVectorSize; 5920 if (MaximizeBandwidth && !OptForSize) { 5921 // Collect all viable vectorization factors. 5922 SmallVector<unsigned, 8> VFs; 5923 unsigned NewMaxVectorSize = WidestRegister / SmallestType; 5924 for (unsigned VS = MaxVectorSize; VS <= NewMaxVectorSize; VS *= 2) 5925 VFs.push_back(VS); 5926 5927 // For each VF calculate its register usage. 5928 auto RUs = calculateRegisterUsage(VFs); 5929 5930 // Select the largest VF which doesn't require more registers than existing 5931 // ones. 5932 unsigned TargetNumRegisters = TTI.getNumberOfRegisters(true); 5933 for (int i = RUs.size() - 1; i >= 0; --i) { 5934 if (RUs[i].MaxLocalUsers <= TargetNumRegisters) { 5935 VF = VFs[i]; 5936 break; 5937 } 5938 } 5939 } 5940 5941 // If we optimize the program for size, avoid creating the tail loop. 5942 if (OptForSize) { 5943 // If we are unable to calculate the trip count then don't try to vectorize. 5944 if (TC < 2) { 5945 ORE->emit( 5946 createMissedAnalysis("UnknownLoopCountComplexCFG") 5947 << "unable to calculate the loop count due to complex control flow"); 5948 DEBUG(dbgs() << "LV: Aborting. A tail loop is required with -Os/-Oz.\n"); 5949 return Factor; 5950 } 5951 5952 // Find the maximum SIMD width that can fit within the trip count. 5953 VF = TC % MaxVectorSize; 5954 5955 if (VF == 0) 5956 VF = MaxVectorSize; 5957 else { 5958 // If the trip count that we found modulo the vectorization factor is not 5959 // zero then we require a tail. 5960 ORE->emit(createMissedAnalysis("NoTailLoopWithOptForSize") 5961 << "cannot optimize for size and vectorize at the " 5962 "same time. Enable vectorization of this loop " 5963 "with '#pragma clang loop vectorize(enable)' " 5964 "when compiling with -Os/-Oz"); 5965 DEBUG(dbgs() << "LV: Aborting. A tail loop is required with -Os/-Oz.\n"); 5966 return Factor; 5967 } 5968 } 5969 5970 int UserVF = Hints->getWidth(); 5971 if (UserVF != 0) { 5972 assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two"); 5973 DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n"); 5974 5975 Factor.Width = UserVF; 5976 return Factor; 5977 } 5978 5979 float Cost = expectedCost(1).first; 5980 #ifndef NDEBUG 5981 const float ScalarCost = Cost; 5982 #endif /* NDEBUG */ 5983 unsigned Width = 1; 5984 DEBUG(dbgs() << "LV: Scalar loop costs: " << (int)ScalarCost << ".\n"); 5985 5986 bool ForceVectorization = Hints->getForce() == LoopVectorizeHints::FK_Enabled; 5987 // Ignore scalar width, because the user explicitly wants vectorization. 5988 if (ForceVectorization && VF > 1) { 5989 Width = 2; 5990 Cost = expectedCost(Width).first / (float)Width; 5991 } 5992 5993 for (unsigned i = 2; i <= VF; i *= 2) { 5994 // Notice that the vector loop needs to be executed less times, so 5995 // we need to divide the cost of the vector loops by the width of 5996 // the vector elements. 5997 VectorizationCostTy C = expectedCost(i); 5998 float VectorCost = C.first / (float)i; 5999 DEBUG(dbgs() << "LV: Vector loop of width " << i 6000 << " costs: " << (int)VectorCost << ".\n"); 6001 if (!C.second && !ForceVectorization) { 6002 DEBUG( 6003 dbgs() << "LV: Not considering vector loop of width " << i 6004 << " because it will not generate any vector instructions.\n"); 6005 continue; 6006 } 6007 if (VectorCost < Cost) { 6008 Cost = VectorCost; 6009 Width = i; 6010 } 6011 } 6012 6013 DEBUG(if (ForceVectorization && Width > 1 && Cost >= ScalarCost) dbgs() 6014 << "LV: Vectorization seems to be not beneficial, " 6015 << "but was forced by a user.\n"); 6016 DEBUG(dbgs() << "LV: Selecting VF: " << Width << ".\n"); 6017 Factor.Width = Width; 6018 Factor.Cost = Width * Cost; 6019 return Factor; 6020 } 6021 6022 std::pair<unsigned, unsigned> 6023 LoopVectorizationCostModel::getSmallestAndWidestTypes() { 6024 unsigned MinWidth = -1U; 6025 unsigned MaxWidth = 8; 6026 const DataLayout &DL = TheFunction->getParent()->getDataLayout(); 6027 6028 // For each block. 6029 for (BasicBlock *BB : TheLoop->blocks()) { 6030 // For each instruction in the loop. 6031 for (Instruction &I : *BB) { 6032 Type *T = I.getType(); 6033 6034 // Skip ignored values. 6035 if (ValuesToIgnore.count(&I)) 6036 continue; 6037 6038 // Only examine Loads, Stores and PHINodes. 6039 if (!isa<LoadInst>(I) && !isa<StoreInst>(I) && !isa<PHINode>(I)) 6040 continue; 6041 6042 // Examine PHI nodes that are reduction variables. Update the type to 6043 // account for the recurrence type. 6044 if (auto *PN = dyn_cast<PHINode>(&I)) { 6045 if (!Legal->isReductionVariable(PN)) 6046 continue; 6047 RecurrenceDescriptor RdxDesc = (*Legal->getReductionVars())[PN]; 6048 T = RdxDesc.getRecurrenceType(); 6049 } 6050 6051 // Examine the stored values. 6052 if (auto *ST = dyn_cast<StoreInst>(&I)) 6053 T = ST->getValueOperand()->getType(); 6054 6055 // Ignore loaded pointer types and stored pointer types that are not 6056 // consecutive. However, we do want to take consecutive stores/loads of 6057 // pointer vectors into account. 6058 if (T->isPointerTy() && !isConsecutiveLoadOrStore(&I)) 6059 continue; 6060 6061 MinWidth = std::min(MinWidth, 6062 (unsigned)DL.getTypeSizeInBits(T->getScalarType())); 6063 MaxWidth = std::max(MaxWidth, 6064 (unsigned)DL.getTypeSizeInBits(T->getScalarType())); 6065 } 6066 } 6067 6068 return {MinWidth, MaxWidth}; 6069 } 6070 6071 unsigned LoopVectorizationCostModel::selectInterleaveCount(bool OptForSize, 6072 unsigned VF, 6073 unsigned LoopCost) { 6074 6075 // -- The interleave heuristics -- 6076 // We interleave the loop in order to expose ILP and reduce the loop overhead. 6077 // There are many micro-architectural considerations that we can't predict 6078 // at this level. For example, frontend pressure (on decode or fetch) due to 6079 // code size, or the number and capabilities of the execution ports. 6080 // 6081 // We use the following heuristics to select the interleave count: 6082 // 1. If the code has reductions, then we interleave to break the cross 6083 // iteration dependency. 6084 // 2. If the loop is really small, then we interleave to reduce the loop 6085 // overhead. 6086 // 3. We don't interleave if we think that we will spill registers to memory 6087 // due to the increased register pressure. 6088 6089 // When we optimize for size, we don't interleave. 6090 if (OptForSize) 6091 return 1; 6092 6093 // We used the distance for the interleave count. 6094 if (Legal->getMaxSafeDepDistBytes() != -1U) 6095 return 1; 6096 6097 // Do not interleave loops with a relatively small trip count. 6098 unsigned TC = PSE.getSE()->getSmallConstantTripCount(TheLoop); 6099 if (TC > 1 && TC < TinyTripCountInterleaveThreshold) 6100 return 1; 6101 6102 unsigned TargetNumRegisters = TTI.getNumberOfRegisters(VF > 1); 6103 DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters 6104 << " registers\n"); 6105 6106 if (VF == 1) { 6107 if (ForceTargetNumScalarRegs.getNumOccurrences() > 0) 6108 TargetNumRegisters = ForceTargetNumScalarRegs; 6109 } else { 6110 if (ForceTargetNumVectorRegs.getNumOccurrences() > 0) 6111 TargetNumRegisters = ForceTargetNumVectorRegs; 6112 } 6113 6114 RegisterUsage R = calculateRegisterUsage({VF})[0]; 6115 // We divide by these constants so assume that we have at least one 6116 // instruction that uses at least one register. 6117 R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U); 6118 R.NumInstructions = std::max(R.NumInstructions, 1U); 6119 6120 // We calculate the interleave count using the following formula. 6121 // Subtract the number of loop invariants from the number of available 6122 // registers. These registers are used by all of the interleaved instances. 6123 // Next, divide the remaining registers by the number of registers that is 6124 // required by the loop, in order to estimate how many parallel instances 6125 // fit without causing spills. All of this is rounded down if necessary to be 6126 // a power of two. We want power of two interleave count to simplify any 6127 // addressing operations or alignment considerations. 6128 unsigned IC = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs) / 6129 R.MaxLocalUsers); 6130 6131 // Don't count the induction variable as interleaved. 6132 if (EnableIndVarRegisterHeur) 6133 IC = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs - 1) / 6134 std::max(1U, (R.MaxLocalUsers - 1))); 6135 6136 // Clamp the interleave ranges to reasonable counts. 6137 unsigned MaxInterleaveCount = TTI.getMaxInterleaveFactor(VF); 6138 6139 // Check if the user has overridden the max. 6140 if (VF == 1) { 6141 if (ForceTargetMaxScalarInterleaveFactor.getNumOccurrences() > 0) 6142 MaxInterleaveCount = ForceTargetMaxScalarInterleaveFactor; 6143 } else { 6144 if (ForceTargetMaxVectorInterleaveFactor.getNumOccurrences() > 0) 6145 MaxInterleaveCount = ForceTargetMaxVectorInterleaveFactor; 6146 } 6147 6148 // If we did not calculate the cost for VF (because the user selected the VF) 6149 // then we calculate the cost of VF here. 6150 if (LoopCost == 0) 6151 LoopCost = expectedCost(VF).first; 6152 6153 // Clamp the calculated IC to be between the 1 and the max interleave count 6154 // that the target allows. 6155 if (IC > MaxInterleaveCount) 6156 IC = MaxInterleaveCount; 6157 else if (IC < 1) 6158 IC = 1; 6159 6160 // Interleave if we vectorized this loop and there is a reduction that could 6161 // benefit from interleaving. 6162 if (VF > 1 && Legal->getReductionVars()->size()) { 6163 DEBUG(dbgs() << "LV: Interleaving because of reductions.\n"); 6164 return IC; 6165 } 6166 6167 // Note that if we've already vectorized the loop we will have done the 6168 // runtime check and so interleaving won't require further checks. 6169 bool InterleavingRequiresRuntimePointerCheck = 6170 (VF == 1 && Legal->getRuntimePointerChecking()->Need); 6171 6172 // We want to interleave small loops in order to reduce the loop overhead and 6173 // potentially expose ILP opportunities. 6174 DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n'); 6175 if (!InterleavingRequiresRuntimePointerCheck && LoopCost < SmallLoopCost) { 6176 // We assume that the cost overhead is 1 and we use the cost model 6177 // to estimate the cost of the loop and interleave until the cost of the 6178 // loop overhead is about 5% of the cost of the loop. 6179 unsigned SmallIC = 6180 std::min(IC, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost)); 6181 6182 // Interleave until store/load ports (estimated by max interleave count) are 6183 // saturated. 6184 unsigned NumStores = Legal->getNumStores(); 6185 unsigned NumLoads = Legal->getNumLoads(); 6186 unsigned StoresIC = IC / (NumStores ? NumStores : 1); 6187 unsigned LoadsIC = IC / (NumLoads ? NumLoads : 1); 6188 6189 // If we have a scalar reduction (vector reductions are already dealt with 6190 // by this point), we can increase the critical path length if the loop 6191 // we're interleaving is inside another loop. Limit, by default to 2, so the 6192 // critical path only gets increased by one reduction operation. 6193 if (Legal->getReductionVars()->size() && TheLoop->getLoopDepth() > 1) { 6194 unsigned F = static_cast<unsigned>(MaxNestedScalarReductionIC); 6195 SmallIC = std::min(SmallIC, F); 6196 StoresIC = std::min(StoresIC, F); 6197 LoadsIC = std::min(LoadsIC, F); 6198 } 6199 6200 if (EnableLoadStoreRuntimeInterleave && 6201 std::max(StoresIC, LoadsIC) > SmallIC) { 6202 DEBUG(dbgs() << "LV: Interleaving to saturate store or load ports.\n"); 6203 return std::max(StoresIC, LoadsIC); 6204 } 6205 6206 DEBUG(dbgs() << "LV: Interleaving to reduce branch cost.\n"); 6207 return SmallIC; 6208 } 6209 6210 // Interleave if this is a large loop (small loops are already dealt with by 6211 // this point) that could benefit from interleaving. 6212 bool HasReductions = (Legal->getReductionVars()->size() > 0); 6213 if (TTI.enableAggressiveInterleaving(HasReductions)) { 6214 DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n"); 6215 return IC; 6216 } 6217 6218 DEBUG(dbgs() << "LV: Not Interleaving.\n"); 6219 return 1; 6220 } 6221 6222 SmallVector<LoopVectorizationCostModel::RegisterUsage, 8> 6223 LoopVectorizationCostModel::calculateRegisterUsage(ArrayRef<unsigned> VFs) { 6224 // This function calculates the register usage by measuring the highest number 6225 // of values that are alive at a single location. Obviously, this is a very 6226 // rough estimation. We scan the loop in a topological order in order and 6227 // assign a number to each instruction. We use RPO to ensure that defs are 6228 // met before their users. We assume that each instruction that has in-loop 6229 // users starts an interval. We record every time that an in-loop value is 6230 // used, so we have a list of the first and last occurrences of each 6231 // instruction. Next, we transpose this data structure into a multi map that 6232 // holds the list of intervals that *end* at a specific location. This multi 6233 // map allows us to perform a linear search. We scan the instructions linearly 6234 // and record each time that a new interval starts, by placing it in a set. 6235 // If we find this value in the multi-map then we remove it from the set. 6236 // The max register usage is the maximum size of the set. 6237 // We also search for instructions that are defined outside the loop, but are 6238 // used inside the loop. We need this number separately from the max-interval 6239 // usage number because when we unroll, loop-invariant values do not take 6240 // more register. 6241 LoopBlocksDFS DFS(TheLoop); 6242 DFS.perform(LI); 6243 6244 RegisterUsage RU; 6245 RU.NumInstructions = 0; 6246 6247 // Each 'key' in the map opens a new interval. The values 6248 // of the map are the index of the 'last seen' usage of the 6249 // instruction that is the key. 6250 typedef DenseMap<Instruction *, unsigned> IntervalMap; 6251 // Maps instruction to its index. 6252 DenseMap<unsigned, Instruction *> IdxToInstr; 6253 // Marks the end of each interval. 6254 IntervalMap EndPoint; 6255 // Saves the list of instruction indices that are used in the loop. 6256 SmallSet<Instruction *, 8> Ends; 6257 // Saves the list of values that are used in the loop but are 6258 // defined outside the loop, such as arguments and constants. 6259 SmallPtrSet<Value *, 8> LoopInvariants; 6260 6261 unsigned Index = 0; 6262 for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) { 6263 RU.NumInstructions += BB->size(); 6264 for (Instruction &I : *BB) { 6265 IdxToInstr[Index++] = &I; 6266 6267 // Save the end location of each USE. 6268 for (Value *U : I.operands()) { 6269 auto *Instr = dyn_cast<Instruction>(U); 6270 6271 // Ignore non-instruction values such as arguments, constants, etc. 6272 if (!Instr) 6273 continue; 6274 6275 // If this instruction is outside the loop then record it and continue. 6276 if (!TheLoop->contains(Instr)) { 6277 LoopInvariants.insert(Instr); 6278 continue; 6279 } 6280 6281 // Overwrite previous end points. 6282 EndPoint[Instr] = Index; 6283 Ends.insert(Instr); 6284 } 6285 } 6286 } 6287 6288 // Saves the list of intervals that end with the index in 'key'. 6289 typedef SmallVector<Instruction *, 2> InstrList; 6290 DenseMap<unsigned, InstrList> TransposeEnds; 6291 6292 // Transpose the EndPoints to a list of values that end at each index. 6293 for (auto &Interval : EndPoint) 6294 TransposeEnds[Interval.second].push_back(Interval.first); 6295 6296 SmallSet<Instruction *, 8> OpenIntervals; 6297 6298 // Get the size of the widest register. 6299 unsigned MaxSafeDepDist = -1U; 6300 if (Legal->getMaxSafeDepDistBytes() != -1U) 6301 MaxSafeDepDist = Legal->getMaxSafeDepDistBytes() * 8; 6302 unsigned WidestRegister = 6303 std::min(TTI.getRegisterBitWidth(true), MaxSafeDepDist); 6304 const DataLayout &DL = TheFunction->getParent()->getDataLayout(); 6305 6306 SmallVector<RegisterUsage, 8> RUs(VFs.size()); 6307 SmallVector<unsigned, 8> MaxUsages(VFs.size(), 0); 6308 6309 DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n"); 6310 6311 // A lambda that gets the register usage for the given type and VF. 6312 auto GetRegUsage = [&DL, WidestRegister](Type *Ty, unsigned VF) { 6313 if (Ty->isTokenTy()) 6314 return 0U; 6315 unsigned TypeSize = DL.getTypeSizeInBits(Ty->getScalarType()); 6316 return std::max<unsigned>(1, VF * TypeSize / WidestRegister); 6317 }; 6318 6319 for (unsigned int i = 0; i < Index; ++i) { 6320 Instruction *I = IdxToInstr[i]; 6321 // Ignore instructions that are never used within the loop. 6322 if (!Ends.count(I)) 6323 continue; 6324 6325 // Remove all of the instructions that end at this location. 6326 InstrList &List = TransposeEnds[i]; 6327 for (Instruction *ToRemove : List) 6328 OpenIntervals.erase(ToRemove); 6329 6330 // Skip ignored values. 6331 if (ValuesToIgnore.count(I)) 6332 continue; 6333 6334 // For each VF find the maximum usage of registers. 6335 for (unsigned j = 0, e = VFs.size(); j < e; ++j) { 6336 if (VFs[j] == 1) { 6337 MaxUsages[j] = std::max(MaxUsages[j], OpenIntervals.size()); 6338 continue; 6339 } 6340 6341 // Count the number of live intervals. 6342 unsigned RegUsage = 0; 6343 for (auto Inst : OpenIntervals) { 6344 // Skip ignored values for VF > 1. 6345 if (VecValuesToIgnore.count(Inst)) 6346 continue; 6347 RegUsage += GetRegUsage(Inst->getType(), VFs[j]); 6348 } 6349 MaxUsages[j] = std::max(MaxUsages[j], RegUsage); 6350 } 6351 6352 DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # " 6353 << OpenIntervals.size() << '\n'); 6354 6355 // Add the current instruction to the list of open intervals. 6356 OpenIntervals.insert(I); 6357 } 6358 6359 for (unsigned i = 0, e = VFs.size(); i < e; ++i) { 6360 unsigned Invariant = 0; 6361 if (VFs[i] == 1) 6362 Invariant = LoopInvariants.size(); 6363 else { 6364 for (auto Inst : LoopInvariants) 6365 Invariant += GetRegUsage(Inst->getType(), VFs[i]); 6366 } 6367 6368 DEBUG(dbgs() << "LV(REG): VF = " << VFs[i] << '\n'); 6369 DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsages[i] << '\n'); 6370 DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << '\n'); 6371 DEBUG(dbgs() << "LV(REG): LoopSize: " << RU.NumInstructions << '\n'); 6372 6373 RU.LoopInvariantRegs = Invariant; 6374 RU.MaxLocalUsers = MaxUsages[i]; 6375 RUs[i] = RU; 6376 } 6377 6378 return RUs; 6379 } 6380 6381 LoopVectorizationCostModel::VectorizationCostTy 6382 LoopVectorizationCostModel::expectedCost(unsigned VF) { 6383 VectorizationCostTy Cost; 6384 6385 // For each block. 6386 for (BasicBlock *BB : TheLoop->blocks()) { 6387 VectorizationCostTy BlockCost; 6388 6389 // For each instruction in the old loop. 6390 for (Instruction &I : *BB) { 6391 // Skip dbg intrinsics. 6392 if (isa<DbgInfoIntrinsic>(I)) 6393 continue; 6394 6395 // Skip ignored values. 6396 if (ValuesToIgnore.count(&I)) 6397 continue; 6398 6399 VectorizationCostTy C = getInstructionCost(&I, VF); 6400 6401 // Check if we should override the cost. 6402 if (ForceTargetInstructionCost.getNumOccurrences() > 0) 6403 C.first = ForceTargetInstructionCost; 6404 6405 BlockCost.first += C.first; 6406 BlockCost.second |= C.second; 6407 DEBUG(dbgs() << "LV: Found an estimated cost of " << C.first << " for VF " 6408 << VF << " For instruction: " << I << '\n'); 6409 } 6410 6411 // If we are vectorizing a predicated block, it will have been 6412 // if-converted. This means that the block's instructions (aside from 6413 // stores and instructions that may divide by zero) will now be 6414 // unconditionally executed. For the scalar case, we may not always execute 6415 // the predicated block. Thus, scale the block's cost by the probability of 6416 // executing it. 6417 if (VF == 1 && Legal->blockNeedsPredication(BB)) 6418 BlockCost.first /= getReciprocalPredBlockProb(); 6419 6420 Cost.first += BlockCost.first; 6421 Cost.second |= BlockCost.second; 6422 } 6423 6424 return Cost; 6425 } 6426 6427 /// \brief Check whether the address computation for a non-consecutive memory 6428 /// access looks like an unlikely candidate for being merged into the indexing 6429 /// mode. 6430 /// 6431 /// We look for a GEP which has one index that is an induction variable and all 6432 /// other indices are loop invariant. If the stride of this access is also 6433 /// within a small bound we decide that this address computation can likely be 6434 /// merged into the addressing mode. 6435 /// In all other cases, we identify the address computation as complex. 6436 static bool isLikelyComplexAddressComputation(Value *Ptr, 6437 LoopVectorizationLegality *Legal, 6438 ScalarEvolution *SE, 6439 const Loop *TheLoop) { 6440 auto *Gep = dyn_cast<GetElementPtrInst>(Ptr); 6441 if (!Gep) 6442 return true; 6443 6444 // We are looking for a gep with all loop invariant indices except for one 6445 // which should be an induction variable. 6446 unsigned NumOperands = Gep->getNumOperands(); 6447 for (unsigned i = 1; i < NumOperands; ++i) { 6448 Value *Opd = Gep->getOperand(i); 6449 if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) && 6450 !Legal->isInductionVariable(Opd)) 6451 return true; 6452 } 6453 6454 // Now we know we have a GEP ptr, %inv, %ind, %inv. Make sure that the step 6455 // can likely be merged into the address computation. 6456 unsigned MaxMergeDistance = 64; 6457 6458 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Ptr)); 6459 if (!AddRec) 6460 return true; 6461 6462 // Check the step is constant. 6463 const SCEV *Step = AddRec->getStepRecurrence(*SE); 6464 // Calculate the pointer stride and check if it is consecutive. 6465 const auto *C = dyn_cast<SCEVConstant>(Step); 6466 if (!C) 6467 return true; 6468 6469 const APInt &APStepVal = C->getAPInt(); 6470 6471 // Huge step value - give up. 6472 if (APStepVal.getBitWidth() > 64) 6473 return true; 6474 6475 int64_t StepVal = APStepVal.getSExtValue(); 6476 6477 return StepVal > MaxMergeDistance; 6478 } 6479 6480 static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) { 6481 return Legal->hasStride(I->getOperand(0)) || 6482 Legal->hasStride(I->getOperand(1)); 6483 } 6484 6485 LoopVectorizationCostModel::VectorizationCostTy 6486 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) { 6487 // If we know that this instruction will remain uniform, check the cost of 6488 // the scalar version. 6489 if (Legal->isUniformAfterVectorization(I)) 6490 VF = 1; 6491 6492 Type *VectorTy; 6493 unsigned C = getInstructionCost(I, VF, VectorTy); 6494 6495 bool TypeNotScalarized = 6496 VF > 1 && !VectorTy->isVoidTy() && TTI.getNumberOfParts(VectorTy) < VF; 6497 return VectorizationCostTy(C, TypeNotScalarized); 6498 } 6499 6500 unsigned LoopVectorizationCostModel::getInstructionCost(Instruction *I, 6501 unsigned VF, 6502 Type *&VectorTy) { 6503 Type *RetTy = I->getType(); 6504 if (VF > 1 && MinBWs.count(I)) 6505 RetTy = IntegerType::get(RetTy->getContext(), MinBWs[I]); 6506 VectorTy = ToVectorTy(RetTy, VF); 6507 auto SE = PSE.getSE(); 6508 6509 // TODO: We need to estimate the cost of intrinsic calls. 6510 switch (I->getOpcode()) { 6511 case Instruction::GetElementPtr: 6512 // We mark this instruction as zero-cost because the cost of GEPs in 6513 // vectorized code depends on whether the corresponding memory instruction 6514 // is scalarized or not. Therefore, we handle GEPs with the memory 6515 // instruction cost. 6516 return 0; 6517 case Instruction::Br: { 6518 return TTI.getCFInstrCost(I->getOpcode()); 6519 } 6520 case Instruction::PHI: { 6521 auto *Phi = cast<PHINode>(I); 6522 6523 // First-order recurrences are replaced by vector shuffles inside the loop. 6524 if (VF > 1 && Legal->isFirstOrderRecurrence(Phi)) 6525 return TTI.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector, 6526 VectorTy, VF - 1, VectorTy); 6527 6528 // TODO: IF-converted IFs become selects. 6529 return 0; 6530 } 6531 case Instruction::UDiv: 6532 case Instruction::SDiv: 6533 case Instruction::URem: 6534 case Instruction::SRem: 6535 // If we have a predicated instruction, it may not be executed for each 6536 // vector lane. Get the scalarization cost and scale this amount by the 6537 // probability of executing the predicated block. If the instruction is not 6538 // predicated, we fall through to the next case. 6539 if (VF > 1 && Legal->isScalarWithPredication(I)) 6540 return VF * TTI.getArithmeticInstrCost(I->getOpcode(), RetTy) / 6541 getReciprocalPredBlockProb() + 6542 getScalarizationOverhead(I, VF, true, TTI); 6543 case Instruction::Add: 6544 case Instruction::FAdd: 6545 case Instruction::Sub: 6546 case Instruction::FSub: 6547 case Instruction::Mul: 6548 case Instruction::FMul: 6549 case Instruction::FDiv: 6550 case Instruction::FRem: 6551 case Instruction::Shl: 6552 case Instruction::LShr: 6553 case Instruction::AShr: 6554 case Instruction::And: 6555 case Instruction::Or: 6556 case Instruction::Xor: { 6557 // Since we will replace the stride by 1 the multiplication should go away. 6558 if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal)) 6559 return 0; 6560 // Certain instructions can be cheaper to vectorize if they have a constant 6561 // second vector operand. One example of this are shifts on x86. 6562 TargetTransformInfo::OperandValueKind Op1VK = 6563 TargetTransformInfo::OK_AnyValue; 6564 TargetTransformInfo::OperandValueKind Op2VK = 6565 TargetTransformInfo::OK_AnyValue; 6566 TargetTransformInfo::OperandValueProperties Op1VP = 6567 TargetTransformInfo::OP_None; 6568 TargetTransformInfo::OperandValueProperties Op2VP = 6569 TargetTransformInfo::OP_None; 6570 Value *Op2 = I->getOperand(1); 6571 6572 // Check for a splat or for a non uniform vector of constants. 6573 if (isa<ConstantInt>(Op2)) { 6574 ConstantInt *CInt = cast<ConstantInt>(Op2); 6575 if (CInt && CInt->getValue().isPowerOf2()) 6576 Op2VP = TargetTransformInfo::OP_PowerOf2; 6577 Op2VK = TargetTransformInfo::OK_UniformConstantValue; 6578 } else if (isa<ConstantVector>(Op2) || isa<ConstantDataVector>(Op2)) { 6579 Op2VK = TargetTransformInfo::OK_NonUniformConstantValue; 6580 Constant *SplatValue = cast<Constant>(Op2)->getSplatValue(); 6581 if (SplatValue) { 6582 ConstantInt *CInt = dyn_cast<ConstantInt>(SplatValue); 6583 if (CInt && CInt->getValue().isPowerOf2()) 6584 Op2VP = TargetTransformInfo::OP_PowerOf2; 6585 Op2VK = TargetTransformInfo::OK_UniformConstantValue; 6586 } 6587 } else if (Legal->isUniform(Op2)) { 6588 Op2VK = TargetTransformInfo::OK_UniformValue; 6589 } 6590 6591 return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy, Op1VK, Op2VK, 6592 Op1VP, Op2VP); 6593 } 6594 case Instruction::Select: { 6595 SelectInst *SI = cast<SelectInst>(I); 6596 const SCEV *CondSCEV = SE->getSCEV(SI->getCondition()); 6597 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop)); 6598 Type *CondTy = SI->getCondition()->getType(); 6599 if (!ScalarCond) 6600 CondTy = VectorType::get(CondTy, VF); 6601 6602 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy); 6603 } 6604 case Instruction::ICmp: 6605 case Instruction::FCmp: { 6606 Type *ValTy = I->getOperand(0)->getType(); 6607 Instruction *Op0AsInstruction = dyn_cast<Instruction>(I->getOperand(0)); 6608 auto It = MinBWs.find(Op0AsInstruction); 6609 if (VF > 1 && It != MinBWs.end()) 6610 ValTy = IntegerType::get(ValTy->getContext(), It->second); 6611 VectorTy = ToVectorTy(ValTy, VF); 6612 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy); 6613 } 6614 case Instruction::Store: 6615 case Instruction::Load: { 6616 StoreInst *SI = dyn_cast<StoreInst>(I); 6617 LoadInst *LI = dyn_cast<LoadInst>(I); 6618 Type *ValTy = (SI ? SI->getValueOperand()->getType() : LI->getType()); 6619 VectorTy = ToVectorTy(ValTy, VF); 6620 6621 unsigned Alignment = SI ? SI->getAlignment() : LI->getAlignment(); 6622 unsigned AS = 6623 SI ? SI->getPointerAddressSpace() : LI->getPointerAddressSpace(); 6624 Value *Ptr = getPointerOperand(I); 6625 // We add the cost of address computation here instead of with the gep 6626 // instruction because only here we know whether the operation is 6627 // scalarized. 6628 if (VF == 1) 6629 return TTI.getAddressComputationCost(VectorTy) + 6630 TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS); 6631 6632 if (LI && Legal->isUniform(Ptr)) { 6633 // Scalar load + broadcast 6634 unsigned Cost = TTI.getAddressComputationCost(ValTy->getScalarType()); 6635 Cost += TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(), 6636 Alignment, AS); 6637 return Cost + 6638 TTI.getShuffleCost(TargetTransformInfo::SK_Broadcast, ValTy); 6639 } 6640 6641 // For an interleaved access, calculate the total cost of the whole 6642 // interleave group. 6643 if (Legal->isAccessInterleaved(I)) { 6644 auto Group = Legal->getInterleavedAccessGroup(I); 6645 assert(Group && "Fail to get an interleaved access group."); 6646 6647 // Only calculate the cost once at the insert position. 6648 if (Group->getInsertPos() != I) 6649 return 0; 6650 6651 unsigned InterleaveFactor = Group->getFactor(); 6652 Type *WideVecTy = 6653 VectorType::get(VectorTy->getVectorElementType(), 6654 VectorTy->getVectorNumElements() * InterleaveFactor); 6655 6656 // Holds the indices of existing members in an interleaved load group. 6657 // An interleaved store group doesn't need this as it doesn't allow gaps. 6658 SmallVector<unsigned, 4> Indices; 6659 if (LI) { 6660 for (unsigned i = 0; i < InterleaveFactor; i++) 6661 if (Group->getMember(i)) 6662 Indices.push_back(i); 6663 } 6664 6665 // Calculate the cost of the whole interleaved group. 6666 unsigned Cost = TTI.getInterleavedMemoryOpCost( 6667 I->getOpcode(), WideVecTy, Group->getFactor(), Indices, 6668 Group->getAlignment(), AS); 6669 6670 if (Group->isReverse()) 6671 Cost += 6672 Group->getNumMembers() * 6673 TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, 0); 6674 6675 // FIXME: The interleaved load group with a huge gap could be even more 6676 // expensive than scalar operations. Then we could ignore such group and 6677 // use scalar operations instead. 6678 return Cost; 6679 } 6680 6681 // Check if the memory instruction will be scalarized. 6682 if (Legal->memoryInstructionMustBeScalarized(I, VF)) { 6683 unsigned Cost = 0; 6684 Type *PtrTy = ToVectorTy(Ptr->getType(), VF); 6685 6686 // True if the memory instruction's address computation is complex. 6687 bool IsComplexComputation = 6688 isLikelyComplexAddressComputation(Ptr, Legal, SE, TheLoop); 6689 6690 // Get the cost of the scalar memory instruction and address computation. 6691 Cost += VF * TTI.getAddressComputationCost(PtrTy, IsComplexComputation); 6692 Cost += VF * 6693 TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(), 6694 Alignment, AS); 6695 6696 // Get the overhead of the extractelement and insertelement instructions 6697 // we might create due to scalarization. 6698 Cost += getScalarizationOverhead(I, VF, false, TTI); 6699 6700 return Cost; 6701 } 6702 6703 // Determine if the pointer operand of the access is either consecutive or 6704 // reverse consecutive. 6705 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr); 6706 bool Reverse = ConsecutiveStride < 0; 6707 6708 // Determine if either a gather or scatter operation is legal. 6709 bool UseGatherOrScatter = 6710 !ConsecutiveStride && Legal->isLegalGatherOrScatter(I); 6711 6712 unsigned Cost = TTI.getAddressComputationCost(VectorTy); 6713 if (UseGatherOrScatter) { 6714 assert(ConsecutiveStride == 0 && 6715 "Gather/Scatter are not used for consecutive stride"); 6716 return Cost + 6717 TTI.getGatherScatterOpCost(I->getOpcode(), VectorTy, Ptr, 6718 Legal->isMaskRequired(I), Alignment); 6719 } 6720 // Wide load/stores. 6721 if (Legal->isMaskRequired(I)) 6722 Cost += 6723 TTI.getMaskedMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS); 6724 else 6725 Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS); 6726 6727 if (Reverse) 6728 Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, 0); 6729 return Cost; 6730 } 6731 case Instruction::ZExt: 6732 case Instruction::SExt: 6733 case Instruction::FPToUI: 6734 case Instruction::FPToSI: 6735 case Instruction::FPExt: 6736 case Instruction::PtrToInt: 6737 case Instruction::IntToPtr: 6738 case Instruction::SIToFP: 6739 case Instruction::UIToFP: 6740 case Instruction::Trunc: 6741 case Instruction::FPTrunc: 6742 case Instruction::BitCast: { 6743 // We optimize the truncation of induction variable. 6744 // The cost of these is the same as the scalar operation. 6745 if (I->getOpcode() == Instruction::Trunc && 6746 Legal->isInductionVariable(I->getOperand(0))) 6747 return TTI.getCastInstrCost(I->getOpcode(), I->getType(), 6748 I->getOperand(0)->getType()); 6749 6750 Type *SrcScalarTy = I->getOperand(0)->getType(); 6751 Type *SrcVecTy = ToVectorTy(SrcScalarTy, VF); 6752 if (VF > 1 && MinBWs.count(I)) { 6753 // This cast is going to be shrunk. This may remove the cast or it might 6754 // turn it into slightly different cast. For example, if MinBW == 16, 6755 // "zext i8 %1 to i32" becomes "zext i8 %1 to i16". 6756 // 6757 // Calculate the modified src and dest types. 6758 Type *MinVecTy = VectorTy; 6759 if (I->getOpcode() == Instruction::Trunc) { 6760 SrcVecTy = smallestIntegerVectorType(SrcVecTy, MinVecTy); 6761 VectorTy = 6762 largestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy); 6763 } else if (I->getOpcode() == Instruction::ZExt || 6764 I->getOpcode() == Instruction::SExt) { 6765 SrcVecTy = largestIntegerVectorType(SrcVecTy, MinVecTy); 6766 VectorTy = 6767 smallestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy); 6768 } 6769 } 6770 6771 return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy); 6772 } 6773 case Instruction::Call: { 6774 bool NeedToScalarize; 6775 CallInst *CI = cast<CallInst>(I); 6776 unsigned CallCost = getVectorCallCost(CI, VF, TTI, TLI, NeedToScalarize); 6777 if (getVectorIntrinsicIDForCall(CI, TLI)) 6778 return std::min(CallCost, getVectorIntrinsicCost(CI, VF, TTI, TLI)); 6779 return CallCost; 6780 } 6781 default: 6782 // The cost of executing VF copies of the scalar instruction. This opcode 6783 // is unknown. Assume that it is the same as 'mul'. 6784 return VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy) + 6785 getScalarizationOverhead(I, VF, false, TTI); 6786 } // end of switch. 6787 } 6788 6789 char LoopVectorize::ID = 0; 6790 static const char lv_name[] = "Loop Vectorization"; 6791 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false) 6792 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 6793 INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass) 6794 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 6795 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass) 6796 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 6797 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass) 6798 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 6799 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass) 6800 INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass) 6801 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 6802 INITIALIZE_PASS_DEPENDENCY(LoopSimplify) 6803 INITIALIZE_PASS_DEPENDENCY(LoopAccessLegacyAnalysis) 6804 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass) 6805 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass) 6806 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false) 6807 6808 namespace llvm { 6809 Pass *createLoopVectorizePass(bool NoUnrolling, bool AlwaysVectorize) { 6810 return new LoopVectorize(NoUnrolling, AlwaysVectorize); 6811 } 6812 } 6813 6814 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) { 6815 6816 // Check if the pointer operand of a load or store instruction is 6817 // consecutive. 6818 if (auto *Ptr = getPointerOperand(Inst)) 6819 return Legal->isConsecutivePtr(Ptr); 6820 return false; 6821 } 6822 6823 void LoopVectorizationCostModel::collectValuesToIgnore() { 6824 // Ignore ephemeral values. 6825 CodeMetrics::collectEphemeralValues(TheLoop, AC, ValuesToIgnore); 6826 6827 // Ignore type-promoting instructions we identified during reduction 6828 // detection. 6829 for (auto &Reduction : *Legal->getReductionVars()) { 6830 RecurrenceDescriptor &RedDes = Reduction.second; 6831 SmallPtrSetImpl<Instruction *> &Casts = RedDes.getCastInsts(); 6832 VecValuesToIgnore.insert(Casts.begin(), Casts.end()); 6833 } 6834 6835 // Insert values known to be scalar into VecValuesToIgnore. 6836 for (auto *BB : TheLoop->getBlocks()) 6837 for (auto &I : *BB) 6838 if (Legal->isScalarAfterVectorization(&I)) 6839 VecValuesToIgnore.insert(&I); 6840 } 6841 6842 void InnerLoopUnroller::scalarizeInstruction(Instruction *Instr, 6843 bool IfPredicateInstr) { 6844 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors"); 6845 // Holds vector parameters or scalars, in case of uniform vals. 6846 SmallVector<VectorParts, 4> Params; 6847 6848 setDebugLocFromInst(Builder, Instr); 6849 6850 // Does this instruction return a value ? 6851 bool IsVoidRetTy = Instr->getType()->isVoidTy(); 6852 6853 // Initialize a new scalar map entry. 6854 ScalarParts Entry(UF); 6855 6856 VectorParts Cond; 6857 if (IfPredicateInstr) 6858 Cond = createBlockInMask(Instr->getParent()); 6859 6860 // For each vector unroll 'part': 6861 for (unsigned Part = 0; Part < UF; ++Part) { 6862 Entry[Part].resize(1); 6863 // For each scalar that we create: 6864 6865 // Start an "if (pred) a[i] = ..." block. 6866 Value *Cmp = nullptr; 6867 if (IfPredicateInstr) { 6868 if (Cond[Part]->getType()->isVectorTy()) 6869 Cond[Part] = 6870 Builder.CreateExtractElement(Cond[Part], Builder.getInt32(0)); 6871 Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cond[Part], 6872 ConstantInt::get(Cond[Part]->getType(), 1)); 6873 } 6874 6875 Instruction *Cloned = Instr->clone(); 6876 if (!IsVoidRetTy) 6877 Cloned->setName(Instr->getName() + ".cloned"); 6878 6879 // Replace the operands of the cloned instructions with their scalar 6880 // equivalents in the new loop. 6881 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) { 6882 auto *NewOp = getScalarValue(Instr->getOperand(op), Part, 0); 6883 Cloned->setOperand(op, NewOp); 6884 } 6885 6886 // Place the cloned scalar in the new loop. 6887 Builder.Insert(Cloned); 6888 6889 // Add the cloned scalar to the scalar map entry. 6890 Entry[Part][0] = Cloned; 6891 6892 // If we just cloned a new assumption, add it the assumption cache. 6893 if (auto *II = dyn_cast<IntrinsicInst>(Cloned)) 6894 if (II->getIntrinsicID() == Intrinsic::assume) 6895 AC->registerAssumption(II); 6896 6897 // End if-block. 6898 if (IfPredicateInstr) 6899 PredicatedInstructions.push_back(std::make_pair(Cloned, Cmp)); 6900 } 6901 VectorLoopValueMap.initScalar(Instr, Entry); 6902 } 6903 6904 void InnerLoopUnroller::vectorizeMemoryInstruction(Instruction *Instr) { 6905 auto *SI = dyn_cast<StoreInst>(Instr); 6906 bool IfPredicateInstr = (SI && Legal->blockNeedsPredication(SI->getParent())); 6907 6908 return scalarizeInstruction(Instr, IfPredicateInstr); 6909 } 6910 6911 Value *InnerLoopUnroller::reverseVector(Value *Vec) { return Vec; } 6912 6913 Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) { return V; } 6914 6915 Value *InnerLoopUnroller::getStepVector(Value *Val, int StartIdx, Value *Step, 6916 Instruction::BinaryOps BinOp) { 6917 // When unrolling and the VF is 1, we only need to add a simple scalar. 6918 Type *Ty = Val->getType(); 6919 assert(!Ty->isVectorTy() && "Val must be a scalar"); 6920 6921 if (Ty->isFloatingPointTy()) { 6922 Constant *C = ConstantFP::get(Ty, (double)StartIdx); 6923 6924 // Floating point operations had to be 'fast' to enable the unrolling. 6925 Value *MulOp = addFastMathFlag(Builder.CreateFMul(C, Step)); 6926 return addFastMathFlag(Builder.CreateBinOp(BinOp, Val, MulOp)); 6927 } 6928 Constant *C = ConstantInt::get(Ty, StartIdx); 6929 return Builder.CreateAdd(Val, Builder.CreateMul(C, Step), "induction"); 6930 } 6931 6932 static void AddRuntimeUnrollDisableMetaData(Loop *L) { 6933 SmallVector<Metadata *, 4> MDs; 6934 // Reserve first location for self reference to the LoopID metadata node. 6935 MDs.push_back(nullptr); 6936 bool IsUnrollMetadata = false; 6937 MDNode *LoopID = L->getLoopID(); 6938 if (LoopID) { 6939 // First find existing loop unrolling disable metadata. 6940 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) { 6941 auto *MD = dyn_cast<MDNode>(LoopID->getOperand(i)); 6942 if (MD) { 6943 const auto *S = dyn_cast<MDString>(MD->getOperand(0)); 6944 IsUnrollMetadata = 6945 S && S->getString().startswith("llvm.loop.unroll.disable"); 6946 } 6947 MDs.push_back(LoopID->getOperand(i)); 6948 } 6949 } 6950 6951 if (!IsUnrollMetadata) { 6952 // Add runtime unroll disable metadata. 6953 LLVMContext &Context = L->getHeader()->getContext(); 6954 SmallVector<Metadata *, 1> DisableOperands; 6955 DisableOperands.push_back( 6956 MDString::get(Context, "llvm.loop.unroll.runtime.disable")); 6957 MDNode *DisableNode = MDNode::get(Context, DisableOperands); 6958 MDs.push_back(DisableNode); 6959 MDNode *NewLoopID = MDNode::get(Context, MDs); 6960 // Set operand 0 to refer to the loop id itself. 6961 NewLoopID->replaceOperandWith(0, NewLoopID); 6962 L->setLoopID(NewLoopID); 6963 } 6964 } 6965 6966 bool LoopVectorizePass::processLoop(Loop *L) { 6967 assert(L->empty() && "Only process inner loops."); 6968 6969 #ifndef NDEBUG 6970 const std::string DebugLocStr = getDebugLocString(L); 6971 #endif /* NDEBUG */ 6972 6973 DEBUG(dbgs() << "\nLV: Checking a loop in \"" 6974 << L->getHeader()->getParent()->getName() << "\" from " 6975 << DebugLocStr << "\n"); 6976 6977 LoopVectorizeHints Hints(L, DisableUnrolling, *ORE); 6978 6979 DEBUG(dbgs() << "LV: Loop hints:" 6980 << " force=" 6981 << (Hints.getForce() == LoopVectorizeHints::FK_Disabled 6982 ? "disabled" 6983 : (Hints.getForce() == LoopVectorizeHints::FK_Enabled 6984 ? "enabled" 6985 : "?")) 6986 << " width=" << Hints.getWidth() 6987 << " unroll=" << Hints.getInterleave() << "\n"); 6988 6989 // Function containing loop 6990 Function *F = L->getHeader()->getParent(); 6991 6992 // Looking at the diagnostic output is the only way to determine if a loop 6993 // was vectorized (other than looking at the IR or machine code), so it 6994 // is important to generate an optimization remark for each loop. Most of 6995 // these messages are generated as OptimizationRemarkAnalysis. Remarks 6996 // generated as OptimizationRemark and OptimizationRemarkMissed are 6997 // less verbose reporting vectorized loops and unvectorized loops that may 6998 // benefit from vectorization, respectively. 6999 7000 if (!Hints.allowVectorization(F, L, AlwaysVectorize)) { 7001 DEBUG(dbgs() << "LV: Loop hints prevent vectorization.\n"); 7002 return false; 7003 } 7004 7005 // Check the loop for a trip count threshold: 7006 // do not vectorize loops with a tiny trip count. 7007 const unsigned TC = SE->getSmallConstantTripCount(L); 7008 if (TC > 0u && TC < TinyTripCountVectorThreshold) { 7009 DEBUG(dbgs() << "LV: Found a loop with a very small trip count. " 7010 << "This loop is not worth vectorizing."); 7011 if (Hints.getForce() == LoopVectorizeHints::FK_Enabled) 7012 DEBUG(dbgs() << " But vectorizing was explicitly forced.\n"); 7013 else { 7014 DEBUG(dbgs() << "\n"); 7015 ORE->emit(createMissedAnalysis(Hints.vectorizeAnalysisPassName(), 7016 "NotBeneficial", L) 7017 << "vectorization is not beneficial " 7018 "and is not explicitly forced"); 7019 return false; 7020 } 7021 } 7022 7023 PredicatedScalarEvolution PSE(*SE, *L); 7024 7025 // Check if it is legal to vectorize the loop. 7026 LoopVectorizationRequirements Requirements(*ORE); 7027 LoopVectorizationLegality LVL(L, PSE, DT, TLI, AA, F, TTI, GetLAA, LI, ORE, 7028 &Requirements, &Hints); 7029 if (!LVL.canVectorize()) { 7030 DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n"); 7031 emitMissedWarning(F, L, Hints, ORE); 7032 return false; 7033 } 7034 7035 // Use the cost model. 7036 LoopVectorizationCostModel CM(L, PSE, LI, &LVL, *TTI, TLI, DB, AC, ORE, F, 7037 &Hints); 7038 CM.collectValuesToIgnore(); 7039 7040 // Check the function attributes to find out if this function should be 7041 // optimized for size. 7042 bool OptForSize = 7043 Hints.getForce() != LoopVectorizeHints::FK_Enabled && F->optForSize(); 7044 7045 // Compute the weighted frequency of this loop being executed and see if it 7046 // is less than 20% of the function entry baseline frequency. Note that we 7047 // always have a canonical loop here because we think we *can* vectorize. 7048 // FIXME: This is hidden behind a flag due to pervasive problems with 7049 // exactly what block frequency models. 7050 if (LoopVectorizeWithBlockFrequency) { 7051 BlockFrequency LoopEntryFreq = BFI->getBlockFreq(L->getLoopPreheader()); 7052 if (Hints.getForce() != LoopVectorizeHints::FK_Enabled && 7053 LoopEntryFreq < ColdEntryFreq) 7054 OptForSize = true; 7055 } 7056 7057 // Check the function attributes to see if implicit floats are allowed. 7058 // FIXME: This check doesn't seem possibly correct -- what if the loop is 7059 // an integer loop and the vector instructions selected are purely integer 7060 // vector instructions? 7061 if (F->hasFnAttribute(Attribute::NoImplicitFloat)) { 7062 DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat" 7063 "attribute is used.\n"); 7064 ORE->emit(createMissedAnalysis(Hints.vectorizeAnalysisPassName(), 7065 "NoImplicitFloat", L) 7066 << "loop not vectorized due to NoImplicitFloat attribute"); 7067 emitMissedWarning(F, L, Hints, ORE); 7068 return false; 7069 } 7070 7071 // Check if the target supports potentially unsafe FP vectorization. 7072 // FIXME: Add a check for the type of safety issue (denormal, signaling) 7073 // for the target we're vectorizing for, to make sure none of the 7074 // additional fp-math flags can help. 7075 if (Hints.isPotentiallyUnsafe() && 7076 TTI->isFPVectorizationPotentiallyUnsafe()) { 7077 DEBUG(dbgs() << "LV: Potentially unsafe FP op prevents vectorization.\n"); 7078 ORE->emit( 7079 createMissedAnalysis(Hints.vectorizeAnalysisPassName(), "UnsafeFP", L) 7080 << "loop not vectorized due to unsafe FP support."); 7081 emitMissedWarning(F, L, Hints, ORE); 7082 return false; 7083 } 7084 7085 // Select the optimal vectorization factor. 7086 const LoopVectorizationCostModel::VectorizationFactor VF = 7087 CM.selectVectorizationFactor(OptForSize); 7088 7089 // Select the interleave count. 7090 unsigned IC = CM.selectInterleaveCount(OptForSize, VF.Width, VF.Cost); 7091 7092 // Get user interleave count. 7093 unsigned UserIC = Hints.getInterleave(); 7094 7095 // Identify the diagnostic messages that should be produced. 7096 std::pair<StringRef, std::string> VecDiagMsg, IntDiagMsg; 7097 bool VectorizeLoop = true, InterleaveLoop = true; 7098 if (Requirements.doesNotMeet(F, L, Hints)) { 7099 DEBUG(dbgs() << "LV: Not vectorizing: loop did not meet vectorization " 7100 "requirements.\n"); 7101 emitMissedWarning(F, L, Hints, ORE); 7102 return false; 7103 } 7104 7105 if (VF.Width == 1) { 7106 DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n"); 7107 VecDiagMsg = std::make_pair( 7108 "VectorizationNotBeneficial", 7109 "the cost-model indicates that vectorization is not beneficial"); 7110 VectorizeLoop = false; 7111 } 7112 7113 if (IC == 1 && UserIC <= 1) { 7114 // Tell the user interleaving is not beneficial. 7115 DEBUG(dbgs() << "LV: Interleaving is not beneficial.\n"); 7116 IntDiagMsg = std::make_pair( 7117 "InterleavingNotBeneficial", 7118 "the cost-model indicates that interleaving is not beneficial"); 7119 InterleaveLoop = false; 7120 if (UserIC == 1) { 7121 IntDiagMsg.first = "InterleavingNotBeneficialAndDisabled"; 7122 IntDiagMsg.second += 7123 " and is explicitly disabled or interleave count is set to 1"; 7124 } 7125 } else if (IC > 1 && UserIC == 1) { 7126 // Tell the user interleaving is beneficial, but it explicitly disabled. 7127 DEBUG(dbgs() 7128 << "LV: Interleaving is beneficial but is explicitly disabled."); 7129 IntDiagMsg = std::make_pair( 7130 "InterleavingBeneficialButDisabled", 7131 "the cost-model indicates that interleaving is beneficial " 7132 "but is explicitly disabled or interleave count is set to 1"); 7133 InterleaveLoop = false; 7134 } 7135 7136 // Override IC if user provided an interleave count. 7137 IC = UserIC > 0 ? UserIC : IC; 7138 7139 // Emit diagnostic messages, if any. 7140 const char *VAPassName = Hints.vectorizeAnalysisPassName(); 7141 if (!VectorizeLoop && !InterleaveLoop) { 7142 // Do not vectorize or interleaving the loop. 7143 ORE->emit(OptimizationRemarkAnalysis(VAPassName, VecDiagMsg.first, 7144 L->getStartLoc(), L->getHeader()) 7145 << VecDiagMsg.second); 7146 ORE->emit(OptimizationRemarkAnalysis(LV_NAME, IntDiagMsg.first, 7147 L->getStartLoc(), L->getHeader()) 7148 << IntDiagMsg.second); 7149 return false; 7150 } else if (!VectorizeLoop && InterleaveLoop) { 7151 DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n'); 7152 ORE->emit(OptimizationRemarkAnalysis(VAPassName, VecDiagMsg.first, 7153 L->getStartLoc(), L->getHeader()) 7154 << VecDiagMsg.second); 7155 } else if (VectorizeLoop && !InterleaveLoop) { 7156 DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width << ") in " 7157 << DebugLocStr << '\n'); 7158 ORE->emit(OptimizationRemarkAnalysis(LV_NAME, IntDiagMsg.first, 7159 L->getStartLoc(), L->getHeader()) 7160 << IntDiagMsg.second); 7161 } else if (VectorizeLoop && InterleaveLoop) { 7162 DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width << ") in " 7163 << DebugLocStr << '\n'); 7164 DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n'); 7165 } 7166 7167 using namespace ore; 7168 if (!VectorizeLoop) { 7169 assert(IC > 1 && "interleave count should not be 1 or 0"); 7170 // If we decided that it is not legal to vectorize the loop, then 7171 // interleave it. 7172 InnerLoopUnroller Unroller(L, PSE, LI, DT, TLI, TTI, AC, ORE, IC, &LVL, 7173 &CM); 7174 Unroller.vectorize(); 7175 7176 ORE->emit(OptimizationRemark(LV_NAME, "Interleaved", L->getStartLoc(), 7177 L->getHeader()) 7178 << "interleaved loop (interleaved count: " 7179 << NV("InterleaveCount", IC) << ")"); 7180 } else { 7181 // If we decided that it is *legal* to vectorize the loop, then do it. 7182 InnerLoopVectorizer LB(L, PSE, LI, DT, TLI, TTI, AC, ORE, VF.Width, IC, 7183 &LVL, &CM); 7184 LB.vectorize(); 7185 ++LoopsVectorized; 7186 7187 // Add metadata to disable runtime unrolling a scalar loop when there are 7188 // no runtime checks about strides and memory. A scalar loop that is 7189 // rarely used is not worth unrolling. 7190 if (!LB.areSafetyChecksAdded()) 7191 AddRuntimeUnrollDisableMetaData(L); 7192 7193 // Report the vectorization decision. 7194 ORE->emit(OptimizationRemark(LV_NAME, "Vectorized", L->getStartLoc(), 7195 L->getHeader()) 7196 << "vectorized loop (vectorization width: " 7197 << NV("VectorizationFactor", VF.Width) 7198 << ", interleaved count: " << NV("InterleaveCount", IC) << ")"); 7199 } 7200 7201 // Mark the loop as already vectorized to avoid vectorizing again. 7202 Hints.setAlreadyVectorized(); 7203 7204 DEBUG(verifyFunction(*L->getHeader()->getParent())); 7205 return true; 7206 } 7207 7208 bool LoopVectorizePass::runImpl( 7209 Function &F, ScalarEvolution &SE_, LoopInfo &LI_, TargetTransformInfo &TTI_, 7210 DominatorTree &DT_, BlockFrequencyInfo &BFI_, TargetLibraryInfo *TLI_, 7211 DemandedBits &DB_, AliasAnalysis &AA_, AssumptionCache &AC_, 7212 std::function<const LoopAccessInfo &(Loop &)> &GetLAA_, 7213 OptimizationRemarkEmitter &ORE_) { 7214 7215 SE = &SE_; 7216 LI = &LI_; 7217 TTI = &TTI_; 7218 DT = &DT_; 7219 BFI = &BFI_; 7220 TLI = TLI_; 7221 AA = &AA_; 7222 AC = &AC_; 7223 GetLAA = &GetLAA_; 7224 DB = &DB_; 7225 ORE = &ORE_; 7226 7227 // Compute some weights outside of the loop over the loops. Compute this 7228 // using a BranchProbability to re-use its scaling math. 7229 const BranchProbability ColdProb(1, 5); // 20% 7230 ColdEntryFreq = BlockFrequency(BFI->getEntryFreq()) * ColdProb; 7231 7232 // Don't attempt if 7233 // 1. the target claims to have no vector registers, and 7234 // 2. interleaving won't help ILP. 7235 // 7236 // The second condition is necessary because, even if the target has no 7237 // vector registers, loop vectorization may still enable scalar 7238 // interleaving. 7239 if (!TTI->getNumberOfRegisters(true) && TTI->getMaxInterleaveFactor(1) < 2) 7240 return false; 7241 7242 // Build up a worklist of inner-loops to vectorize. This is necessary as 7243 // the act of vectorizing or partially unrolling a loop creates new loops 7244 // and can invalidate iterators across the loops. 7245 SmallVector<Loop *, 8> Worklist; 7246 7247 for (Loop *L : *LI) 7248 addAcyclicInnerLoop(*L, Worklist); 7249 7250 LoopsAnalyzed += Worklist.size(); 7251 7252 // Now walk the identified inner loops. 7253 bool Changed = false; 7254 while (!Worklist.empty()) 7255 Changed |= processLoop(Worklist.pop_back_val()); 7256 7257 // Process each loop nest in the function. 7258 return Changed; 7259 7260 } 7261 7262 7263 PreservedAnalyses LoopVectorizePass::run(Function &F, 7264 FunctionAnalysisManager &AM) { 7265 auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F); 7266 auto &LI = AM.getResult<LoopAnalysis>(F); 7267 auto &TTI = AM.getResult<TargetIRAnalysis>(F); 7268 auto &DT = AM.getResult<DominatorTreeAnalysis>(F); 7269 auto &BFI = AM.getResult<BlockFrequencyAnalysis>(F); 7270 auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F); 7271 auto &AA = AM.getResult<AAManager>(F); 7272 auto &AC = AM.getResult<AssumptionAnalysis>(F); 7273 auto &DB = AM.getResult<DemandedBitsAnalysis>(F); 7274 auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F); 7275 7276 auto &LAM = AM.getResult<LoopAnalysisManagerFunctionProxy>(F).getManager(); 7277 std::function<const LoopAccessInfo &(Loop &)> GetLAA = 7278 [&](Loop &L) -> const LoopAccessInfo & { 7279 return LAM.getResult<LoopAccessAnalysis>(L); 7280 }; 7281 bool Changed = 7282 runImpl(F, SE, LI, TTI, DT, BFI, TLI, DB, AA, AC, GetLAA, ORE); 7283 if (!Changed) 7284 return PreservedAnalyses::all(); 7285 PreservedAnalyses PA; 7286 PA.preserve<LoopAnalysis>(); 7287 PA.preserve<DominatorTreeAnalysis>(); 7288 PA.preserve<BasicAA>(); 7289 PA.preserve<GlobalsAA>(); 7290 return PA; 7291 } 7292