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