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