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