1 //===- LoopVectorize.cpp - A Loop Vectorizer ------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This is the LLVM loop vectorizer. This pass modifies 'vectorizable' loops 11 // and generates target-independent LLVM-IR. 12 // The vectorizer uses the TargetTransformInfo analysis to estimate the costs 13 // of instructions in order to estimate the profitability of vectorization. 14 // 15 // The loop vectorizer combines consecutive loop iterations into a single 16 // 'wide' iteration. After this transformation the index is incremented 17 // by the SIMD vector width, and not by one. 18 // 19 // This pass has three parts: 20 // 1. The main loop pass that drives the different parts. 21 // 2. LoopVectorizationLegality - A unit that checks for the legality 22 // of the vectorization. 23 // 3. InnerLoopVectorizer - A unit that performs the actual 24 // widening of instructions. 25 // 4. LoopVectorizationCostModel - A unit that checks for the profitability 26 // of vectorization. It decides on the optimal vector width, which 27 // can be one, if vectorization is not profitable. 28 // 29 //===----------------------------------------------------------------------===// 30 // 31 // The reduction-variable vectorization is based on the paper: 32 // D. Nuzman and R. Henderson. Multi-platform Auto-vectorization. 33 // 34 // Variable uniformity checks are inspired by: 35 // Karrenberg, R. and Hack, S. Whole Function Vectorization. 36 // 37 // Other ideas/concepts are from: 38 // A. Zaks and D. Nuzman. Autovectorization in GCC-two years later. 39 // 40 // S. Maleki, Y. Gao, M. Garzaran, T. Wong and D. Padua. An Evaluation of 41 // Vectorizing Compilers. 42 // 43 //===----------------------------------------------------------------------===// 44 45 #include "llvm/Transforms/Vectorize.h" 46 #include "llvm/ADT/DenseMap.h" 47 #include "llvm/ADT/EquivalenceClasses.h" 48 #include "llvm/ADT/Hashing.h" 49 #include "llvm/ADT/MapVector.h" 50 #include "llvm/ADT/SetVector.h" 51 #include "llvm/ADT/SmallPtrSet.h" 52 #include "llvm/ADT/SmallSet.h" 53 #include "llvm/ADT/SmallVector.h" 54 #include "llvm/ADT/Statistic.h" 55 #include "llvm/ADT/StringExtras.h" 56 #include "llvm/Analysis/AliasAnalysis.h" 57 #include "llvm/Analysis/AliasSetTracker.h" 58 #include "llvm/Analysis/AssumptionCache.h" 59 #include "llvm/Analysis/BlockFrequencyInfo.h" 60 #include "llvm/Analysis/CodeMetrics.h" 61 #include "llvm/Analysis/LoopAccessAnalysis.h" 62 #include "llvm/Analysis/LoopInfo.h" 63 #include "llvm/Analysis/LoopIterator.h" 64 #include "llvm/Analysis/LoopPass.h" 65 #include "llvm/Analysis/ScalarEvolution.h" 66 #include "llvm/Analysis/ScalarEvolutionExpander.h" 67 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 68 #include "llvm/Analysis/TargetTransformInfo.h" 69 #include "llvm/Analysis/ValueTracking.h" 70 #include "llvm/IR/Constants.h" 71 #include "llvm/IR/DataLayout.h" 72 #include "llvm/IR/DebugInfo.h" 73 #include "llvm/IR/DerivedTypes.h" 74 #include "llvm/IR/DiagnosticInfo.h" 75 #include "llvm/IR/Dominators.h" 76 #include "llvm/IR/Function.h" 77 #include "llvm/IR/IRBuilder.h" 78 #include "llvm/IR/Instructions.h" 79 #include "llvm/IR/IntrinsicInst.h" 80 #include "llvm/IR/LLVMContext.h" 81 #include "llvm/IR/Module.h" 82 #include "llvm/IR/PatternMatch.h" 83 #include "llvm/IR/Type.h" 84 #include "llvm/IR/Value.h" 85 #include "llvm/IR/ValueHandle.h" 86 #include "llvm/IR/Verifier.h" 87 #include "llvm/Pass.h" 88 #include "llvm/Support/BranchProbability.h" 89 #include "llvm/Support/CommandLine.h" 90 #include "llvm/Support/Debug.h" 91 #include "llvm/Support/raw_ostream.h" 92 #include "llvm/Transforms/Scalar.h" 93 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 94 #include "llvm/Transforms/Utils/Local.h" 95 #include "llvm/Transforms/Utils/VectorUtils.h" 96 #include <algorithm> 97 #include <map> 98 #include <tuple> 99 100 using namespace llvm; 101 using namespace llvm::PatternMatch; 102 103 #define LV_NAME "loop-vectorize" 104 #define DEBUG_TYPE LV_NAME 105 106 STATISTIC(LoopsVectorized, "Number of loops vectorized"); 107 STATISTIC(LoopsAnalyzed, "Number of loops analyzed for vectorization"); 108 109 static cl::opt<unsigned> 110 VectorizationFactor("force-vector-width", cl::init(0), cl::Hidden, 111 cl::desc("Sets the SIMD width. Zero is autoselect.")); 112 113 static cl::opt<unsigned> 114 VectorizationInterleave("force-vector-interleave", cl::init(0), cl::Hidden, 115 cl::desc("Sets the vectorization interleave count. " 116 "Zero is autoselect.")); 117 118 static cl::opt<bool> 119 EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden, 120 cl::desc("Enable if-conversion during vectorization.")); 121 122 /// We don't vectorize loops with a known constant trip count below this number. 123 static cl::opt<unsigned> 124 TinyTripCountVectorThreshold("vectorizer-min-trip-count", cl::init(16), 125 cl::Hidden, 126 cl::desc("Don't vectorize loops with a constant " 127 "trip count that is smaller than this " 128 "value.")); 129 130 /// This enables versioning on the strides of symbolically striding memory 131 /// accesses in code like the following. 132 /// for (i = 0; i < N; ++i) 133 /// A[i * Stride1] += B[i * Stride2] ... 134 /// 135 /// Will be roughly translated to 136 /// if (Stride1 == 1 && Stride2 == 1) { 137 /// for (i = 0; i < N; i+=4) 138 /// A[i:i+3] += ... 139 /// } else 140 /// ... 141 static cl::opt<bool> EnableMemAccessVersioning( 142 "enable-mem-access-versioning", cl::init(true), cl::Hidden, 143 cl::desc("Enable symblic stride memory access versioning")); 144 145 /// We don't unroll loops with a known constant trip count below this number. 146 static const unsigned TinyTripCountUnrollThreshold = 128; 147 148 /// When performing memory disambiguation checks at runtime do not make more 149 /// than this number of comparisons. 150 static const unsigned RuntimeMemoryCheckThreshold = 8; 151 152 /// Maximum simd width. 153 static const unsigned MaxVectorWidth = 64; 154 155 static cl::opt<unsigned> ForceTargetNumScalarRegs( 156 "force-target-num-scalar-regs", cl::init(0), cl::Hidden, 157 cl::desc("A flag that overrides the target's number of scalar registers.")); 158 159 static cl::opt<unsigned> ForceTargetNumVectorRegs( 160 "force-target-num-vector-regs", cl::init(0), cl::Hidden, 161 cl::desc("A flag that overrides the target's number of vector registers.")); 162 163 /// Maximum vectorization interleave count. 164 static const unsigned MaxInterleaveFactor = 16; 165 166 static cl::opt<unsigned> ForceTargetMaxScalarInterleaveFactor( 167 "force-target-max-scalar-interleave", cl::init(0), cl::Hidden, 168 cl::desc("A flag that overrides the target's max interleave factor for " 169 "scalar loops.")); 170 171 static cl::opt<unsigned> ForceTargetMaxVectorInterleaveFactor( 172 "force-target-max-vector-interleave", cl::init(0), cl::Hidden, 173 cl::desc("A flag that overrides the target's max interleave factor for " 174 "vectorized loops.")); 175 176 static cl::opt<unsigned> ForceTargetInstructionCost( 177 "force-target-instruction-cost", cl::init(0), cl::Hidden, 178 cl::desc("A flag that overrides the target's expected cost for " 179 "an instruction to a single constant value. Mostly " 180 "useful for getting consistent testing.")); 181 182 static cl::opt<unsigned> SmallLoopCost( 183 "small-loop-cost", cl::init(20), cl::Hidden, 184 cl::desc("The cost of a loop that is considered 'small' by the unroller.")); 185 186 static cl::opt<bool> LoopVectorizeWithBlockFrequency( 187 "loop-vectorize-with-block-frequency", cl::init(false), cl::Hidden, 188 cl::desc("Enable the use of the block frequency analysis to access PGO " 189 "heuristics minimizing code growth in cold regions and being more " 190 "aggressive in hot regions.")); 191 192 // Runtime unroll loops for load/store throughput. 193 static cl::opt<bool> EnableLoadStoreRuntimeUnroll( 194 "enable-loadstore-runtime-unroll", cl::init(true), cl::Hidden, 195 cl::desc("Enable runtime unrolling until load/store ports are saturated")); 196 197 /// The number of stores in a loop that are allowed to need predication. 198 static cl::opt<unsigned> NumberOfStoresToPredicate( 199 "vectorize-num-stores-pred", cl::init(1), cl::Hidden, 200 cl::desc("Max number of stores to be predicated behind an if.")); 201 202 static cl::opt<bool> EnableIndVarRegisterHeur( 203 "enable-ind-var-reg-heur", cl::init(true), cl::Hidden, 204 cl::desc("Count the induction variable only once when unrolling")); 205 206 static cl::opt<bool> EnableCondStoresVectorization( 207 "enable-cond-stores-vec", cl::init(false), cl::Hidden, 208 cl::desc("Enable if predication of stores during vectorization.")); 209 210 static cl::opt<unsigned> MaxNestedScalarReductionUF( 211 "max-nested-scalar-reduction-unroll", cl::init(2), cl::Hidden, 212 cl::desc("The maximum unroll factor to use when unrolling a scalar " 213 "reduction in a nested loop.")); 214 215 namespace { 216 217 // Forward declarations. 218 class LoopVectorizationLegality; 219 class LoopVectorizationCostModel; 220 class LoopVectorizeHints; 221 222 /// InnerLoopVectorizer vectorizes loops which contain only one basic 223 /// block to a specified vectorization factor (VF). 224 /// This class performs the widening of scalars into vectors, or multiple 225 /// scalars. This class also implements the following features: 226 /// * It inserts an epilogue loop for handling loops that don't have iteration 227 /// counts that are known to be a multiple of the vectorization factor. 228 /// * It handles the code generation for reduction variables. 229 /// * Scalarization (implementation using scalars) of un-vectorizable 230 /// instructions. 231 /// InnerLoopVectorizer does not perform any vectorization-legality 232 /// checks, and relies on the caller to check for the different legality 233 /// aspects. The InnerLoopVectorizer relies on the 234 /// LoopVectorizationLegality class to provide information about the induction 235 /// and reduction variables that were found to a given vectorization factor. 236 class InnerLoopVectorizer { 237 public: 238 InnerLoopVectorizer(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI, 239 DominatorTree *DT, const DataLayout *DL, 240 const TargetLibraryInfo *TLI, unsigned VecWidth, 241 unsigned UnrollFactor) 242 : OrigLoop(OrigLoop), SE(SE), LI(LI), DT(DT), DL(DL), TLI(TLI), 243 VF(VecWidth), UF(UnrollFactor), Builder(SE->getContext()), 244 Induction(nullptr), OldInduction(nullptr), WidenMap(UnrollFactor), 245 Legal(nullptr) {} 246 247 // Perform the actual loop widening (vectorization). 248 void vectorize(LoopVectorizationLegality *L) { 249 Legal = L; 250 // Create a new empty loop. Unlink the old loop and connect the new one. 251 createEmptyLoop(); 252 // Widen each instruction in the old loop to a new one in the new loop. 253 // Use the Legality module to find the induction and reduction variables. 254 vectorizeLoop(); 255 // Register the new loop and update the analysis passes. 256 updateAnalysis(); 257 } 258 259 virtual ~InnerLoopVectorizer() {} 260 261 protected: 262 /// A small list of PHINodes. 263 typedef SmallVector<PHINode*, 4> PhiVector; 264 /// When we unroll loops we have multiple vector values for each scalar. 265 /// This data structure holds the unrolled and vectorized values that 266 /// originated from one scalar instruction. 267 typedef SmallVector<Value*, 2> VectorParts; 268 269 // When we if-convert we need create edge masks. We have to cache values so 270 // that we don't end up with exponential recursion/IR. 271 typedef DenseMap<std::pair<BasicBlock*, BasicBlock*>, 272 VectorParts> EdgeMaskCache; 273 274 /// \brief Add checks for strides that where assumed to be 1. 275 /// 276 /// Returns the last check instruction and the first check instruction in the 277 /// pair as (first, last). 278 std::pair<Instruction *, Instruction *> addStrideCheck(Instruction *Loc); 279 280 /// Create an empty loop, based on the loop ranges of the old loop. 281 void createEmptyLoop(); 282 /// Copy and widen the instructions from the old loop. 283 virtual void vectorizeLoop(); 284 285 /// \brief The Loop exit block may have single value PHI nodes where the 286 /// incoming value is 'Undef'. While vectorizing we only handled real values 287 /// that were defined inside the loop. Here we fix the 'undef case'. 288 /// See PR14725. 289 void fixLCSSAPHIs(); 290 291 /// A helper function that computes the predicate of the block BB, assuming 292 /// that the header block of the loop is set to True. It returns the *entry* 293 /// mask for the block BB. 294 VectorParts createBlockInMask(BasicBlock *BB); 295 /// A helper function that computes the predicate of the edge between SRC 296 /// and DST. 297 VectorParts createEdgeMask(BasicBlock *Src, BasicBlock *Dst); 298 299 /// A helper function to vectorize a single BB within the innermost loop. 300 void vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV); 301 302 /// Vectorize a single PHINode in a block. This method handles the induction 303 /// variable canonicalization. It supports both VF = 1 for unrolled loops and 304 /// arbitrary length vectors. 305 void widenPHIInstruction(Instruction *PN, VectorParts &Entry, 306 unsigned UF, unsigned VF, PhiVector *PV); 307 308 /// Insert the new loop to the loop hierarchy and pass manager 309 /// and update the analysis passes. 310 void updateAnalysis(); 311 312 /// This instruction is un-vectorizable. Implement it as a sequence 313 /// of scalars. If \p IfPredicateStore is true we need to 'hide' each 314 /// scalarized instruction behind an if block predicated on the control 315 /// dependence of the instruction. 316 virtual void scalarizeInstruction(Instruction *Instr, 317 bool IfPredicateStore=false); 318 319 /// Vectorize Load and Store instructions, 320 virtual void vectorizeMemoryInstruction(Instruction *Instr); 321 322 /// Create a broadcast instruction. This method generates a broadcast 323 /// instruction (shuffle) for loop invariant values and for the induction 324 /// value. If this is the induction variable then we extend it to N, N+1, ... 325 /// this is needed because each iteration in the loop corresponds to a SIMD 326 /// element. 327 virtual Value *getBroadcastInstrs(Value *V); 328 329 /// This function adds (StartIdx, StartIdx + Step, StartIdx + 2*Step, ...) 330 /// to each vector element of Val. The sequence starts at StartIndex. 331 virtual Value *getStepVector(Value *Val, int StartIdx, Value *Step); 332 333 /// When we go over instructions in the basic block we rely on previous 334 /// values within the current basic block or on loop invariant values. 335 /// When we widen (vectorize) values we place them in the map. If the values 336 /// are not within the map, they have to be loop invariant, so we simply 337 /// broadcast them into a vector. 338 VectorParts &getVectorValue(Value *V); 339 340 /// Generate a shuffle sequence that will reverse the vector Vec. 341 virtual Value *reverseVector(Value *Vec); 342 343 /// This is a helper class that holds the vectorizer state. It maps scalar 344 /// instructions to vector instructions. When the code is 'unrolled' then 345 /// then a single scalar value is mapped to multiple vector parts. The parts 346 /// are stored in the VectorPart type. 347 struct ValueMap { 348 /// C'tor. UnrollFactor controls the number of vectors ('parts') that 349 /// are mapped. 350 ValueMap(unsigned UnrollFactor) : UF(UnrollFactor) {} 351 352 /// \return True if 'Key' is saved in the Value Map. 353 bool has(Value *Key) const { return MapStorage.count(Key); } 354 355 /// Initializes a new entry in the map. Sets all of the vector parts to the 356 /// save value in 'Val'. 357 /// \return A reference to a vector with splat values. 358 VectorParts &splat(Value *Key, Value *Val) { 359 VectorParts &Entry = MapStorage[Key]; 360 Entry.assign(UF, Val); 361 return Entry; 362 } 363 364 ///\return A reference to the value that is stored at 'Key'. 365 VectorParts &get(Value *Key) { 366 VectorParts &Entry = MapStorage[Key]; 367 if (Entry.empty()) 368 Entry.resize(UF); 369 assert(Entry.size() == UF); 370 return Entry; 371 } 372 373 private: 374 /// The unroll factor. Each entry in the map stores this number of vector 375 /// elements. 376 unsigned UF; 377 378 /// Map storage. We use std::map and not DenseMap because insertions to a 379 /// dense map invalidates its iterators. 380 std::map<Value *, VectorParts> MapStorage; 381 }; 382 383 /// The original loop. 384 Loop *OrigLoop; 385 /// Scev analysis to use. 386 ScalarEvolution *SE; 387 /// Loop Info. 388 LoopInfo *LI; 389 /// Dominator Tree. 390 DominatorTree *DT; 391 /// Alias Analysis. 392 AliasAnalysis *AA; 393 /// Data Layout. 394 const DataLayout *DL; 395 /// Target Library Info. 396 const TargetLibraryInfo *TLI; 397 398 /// The vectorization SIMD factor to use. Each vector will have this many 399 /// vector elements. 400 unsigned VF; 401 402 protected: 403 /// The vectorization unroll factor to use. Each scalar is vectorized to this 404 /// many different vector instructions. 405 unsigned UF; 406 407 /// The builder that we use 408 IRBuilder<> Builder; 409 410 // --- Vectorization state --- 411 412 /// The vector-loop preheader. 413 BasicBlock *LoopVectorPreHeader; 414 /// The scalar-loop preheader. 415 BasicBlock *LoopScalarPreHeader; 416 /// Middle Block between the vector and the scalar. 417 BasicBlock *LoopMiddleBlock; 418 ///The ExitBlock of the scalar loop. 419 BasicBlock *LoopExitBlock; 420 ///The vector loop body. 421 SmallVector<BasicBlock *, 4> LoopVectorBody; 422 ///The scalar loop body. 423 BasicBlock *LoopScalarBody; 424 /// A list of all bypass blocks. The first block is the entry of the loop. 425 SmallVector<BasicBlock *, 4> LoopBypassBlocks; 426 427 /// The new Induction variable which was added to the new block. 428 PHINode *Induction; 429 /// The induction variable of the old basic block. 430 PHINode *OldInduction; 431 /// Holds the extended (to the widest induction type) start index. 432 Value *ExtendedIdx; 433 /// Maps scalars to widened vectors. 434 ValueMap WidenMap; 435 EdgeMaskCache MaskCache; 436 437 LoopVectorizationLegality *Legal; 438 }; 439 440 class InnerLoopUnroller : public InnerLoopVectorizer { 441 public: 442 InnerLoopUnroller(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI, 443 DominatorTree *DT, const DataLayout *DL, 444 const TargetLibraryInfo *TLI, unsigned UnrollFactor) : 445 InnerLoopVectorizer(OrigLoop, SE, LI, DT, DL, TLI, 1, UnrollFactor) { } 446 447 private: 448 void scalarizeInstruction(Instruction *Instr, 449 bool IfPredicateStore = false) override; 450 void vectorizeMemoryInstruction(Instruction *Instr) override; 451 Value *getBroadcastInstrs(Value *V) override; 452 Value *getStepVector(Value *Val, int StartIdx, Value *Step) override; 453 Value *reverseVector(Value *Vec) override; 454 }; 455 456 /// \brief Look for a meaningful debug location on the instruction or it's 457 /// operands. 458 static Instruction *getDebugLocFromInstOrOperands(Instruction *I) { 459 if (!I) 460 return I; 461 462 DebugLoc Empty; 463 if (I->getDebugLoc() != Empty) 464 return I; 465 466 for (User::op_iterator OI = I->op_begin(), OE = I->op_end(); OI != OE; ++OI) { 467 if (Instruction *OpInst = dyn_cast<Instruction>(*OI)) 468 if (OpInst->getDebugLoc() != Empty) 469 return OpInst; 470 } 471 472 return I; 473 } 474 475 /// \brief Set the debug location in the builder using the debug location in the 476 /// instruction. 477 static void setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr) { 478 if (const Instruction *Inst = dyn_cast_or_null<Instruction>(Ptr)) 479 B.SetCurrentDebugLocation(Inst->getDebugLoc()); 480 else 481 B.SetCurrentDebugLocation(DebugLoc()); 482 } 483 484 #ifndef NDEBUG 485 /// \return string containing a file name and a line # for the given loop. 486 static std::string getDebugLocString(const Loop *L) { 487 std::string Result; 488 if (L) { 489 raw_string_ostream OS(Result); 490 const DebugLoc LoopDbgLoc = L->getStartLoc(); 491 if (!LoopDbgLoc.isUnknown()) 492 LoopDbgLoc.print(L->getHeader()->getContext(), OS); 493 else 494 // Just print the module name. 495 OS << L->getHeader()->getParent()->getParent()->getModuleIdentifier(); 496 OS.flush(); 497 } 498 return Result; 499 } 500 #endif 501 502 /// \brief Propagate known metadata from one instruction to another. 503 static void propagateMetadata(Instruction *To, const Instruction *From) { 504 SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata; 505 From->getAllMetadataOtherThanDebugLoc(Metadata); 506 507 for (auto M : Metadata) { 508 unsigned Kind = M.first; 509 510 // These are safe to transfer (this is safe for TBAA, even when we 511 // if-convert, because should that metadata have had a control dependency 512 // on the condition, and thus actually aliased with some other 513 // non-speculated memory access when the condition was false, this would be 514 // caught by the runtime overlap checks). 515 if (Kind != LLVMContext::MD_tbaa && 516 Kind != LLVMContext::MD_alias_scope && 517 Kind != LLVMContext::MD_noalias && 518 Kind != LLVMContext::MD_fpmath) 519 continue; 520 521 To->setMetadata(Kind, M.second); 522 } 523 } 524 525 /// \brief Propagate known metadata from one instruction to a vector of others. 526 static void propagateMetadata(SmallVectorImpl<Value *> &To, const Instruction *From) { 527 for (Value *V : To) 528 if (Instruction *I = dyn_cast<Instruction>(V)) 529 propagateMetadata(I, From); 530 } 531 532 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and 533 /// to what vectorization factor. 534 /// This class does not look at the profitability of vectorization, only the 535 /// legality. This class has two main kinds of checks: 536 /// * Memory checks - The code in canVectorizeMemory checks if vectorization 537 /// will change the order of memory accesses in a way that will change the 538 /// correctness of the program. 539 /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory 540 /// checks for a number of different conditions, such as the availability of a 541 /// single induction variable, that all types are supported and vectorize-able, 542 /// etc. This code reflects the capabilities of InnerLoopVectorizer. 543 /// This class is also used by InnerLoopVectorizer for identifying 544 /// induction variable and the different reduction variables. 545 class LoopVectorizationLegality { 546 public: 547 LoopVectorizationLegality(Loop *L, ScalarEvolution *SE, const DataLayout *DL, 548 DominatorTree *DT, TargetLibraryInfo *TLI, 549 AliasAnalysis *AA, Function *F, 550 const TargetTransformInfo *TTI) 551 : NumPredStores(0), TheLoop(L), SE(SE), DL(DL), 552 TLI(TLI), TheFunction(F), TTI(TTI), Induction(nullptr), 553 WidestIndTy(nullptr), 554 LAA(F, L, SE, DL, TLI, AA, DT, 555 LoopAccessAnalysis::VectorizerParams( 556 MaxVectorWidth, VectorizationFactor, VectorizationInterleave, 557 RuntimeMemoryCheckThreshold)), 558 HasFunNoNaNAttr(false) {} 559 560 /// This enum represents the kinds of reductions that we support. 561 enum ReductionKind { 562 RK_NoReduction, ///< Not a reduction. 563 RK_IntegerAdd, ///< Sum of integers. 564 RK_IntegerMult, ///< Product of integers. 565 RK_IntegerOr, ///< Bitwise or logical OR of numbers. 566 RK_IntegerAnd, ///< Bitwise or logical AND of numbers. 567 RK_IntegerXor, ///< Bitwise or logical XOR of numbers. 568 RK_IntegerMinMax, ///< Min/max implemented in terms of select(cmp()). 569 RK_FloatAdd, ///< Sum of floats. 570 RK_FloatMult, ///< Product of floats. 571 RK_FloatMinMax ///< Min/max implemented in terms of select(cmp()). 572 }; 573 574 /// This enum represents the kinds of inductions that we support. 575 enum InductionKind { 576 IK_NoInduction, ///< Not an induction variable. 577 IK_IntInduction, ///< Integer induction variable. Step = C. 578 IK_PtrInduction ///< Pointer induction var. Step = C / sizeof(elem). 579 }; 580 581 // This enum represents the kind of minmax reduction. 582 enum MinMaxReductionKind { 583 MRK_Invalid, 584 MRK_UIntMin, 585 MRK_UIntMax, 586 MRK_SIntMin, 587 MRK_SIntMax, 588 MRK_FloatMin, 589 MRK_FloatMax 590 }; 591 592 /// This struct holds information about reduction variables. 593 struct ReductionDescriptor { 594 ReductionDescriptor() : StartValue(nullptr), LoopExitInstr(nullptr), 595 Kind(RK_NoReduction), MinMaxKind(MRK_Invalid) {} 596 597 ReductionDescriptor(Value *Start, Instruction *Exit, ReductionKind K, 598 MinMaxReductionKind MK) 599 : StartValue(Start), LoopExitInstr(Exit), Kind(K), MinMaxKind(MK) {} 600 601 // The starting value of the reduction. 602 // It does not have to be zero! 603 TrackingVH<Value> StartValue; 604 // The instruction who's value is used outside the loop. 605 Instruction *LoopExitInstr; 606 // The kind of the reduction. 607 ReductionKind Kind; 608 // If this a min/max reduction the kind of reduction. 609 MinMaxReductionKind MinMaxKind; 610 }; 611 612 /// This POD struct holds information about a potential reduction operation. 613 struct ReductionInstDesc { 614 ReductionInstDesc(bool IsRedux, Instruction *I) : 615 IsReduction(IsRedux), PatternLastInst(I), MinMaxKind(MRK_Invalid) {} 616 617 ReductionInstDesc(Instruction *I, MinMaxReductionKind K) : 618 IsReduction(true), PatternLastInst(I), MinMaxKind(K) {} 619 620 // Is this instruction a reduction candidate. 621 bool IsReduction; 622 // The last instruction in a min/max pattern (select of the select(icmp()) 623 // pattern), or the current reduction instruction otherwise. 624 Instruction *PatternLastInst; 625 // If this is a min/max pattern the comparison predicate. 626 MinMaxReductionKind MinMaxKind; 627 }; 628 629 /// A struct for saving information about induction variables. 630 struct InductionInfo { 631 InductionInfo(Value *Start, InductionKind K, ConstantInt *Step) 632 : StartValue(Start), IK(K), StepValue(Step) { 633 assert(IK != IK_NoInduction && "Not an induction"); 634 assert(StartValue && "StartValue is null"); 635 assert(StepValue && !StepValue->isZero() && "StepValue is zero"); 636 assert((IK != IK_PtrInduction || StartValue->getType()->isPointerTy()) && 637 "StartValue is not a pointer for pointer induction"); 638 assert((IK != IK_IntInduction || StartValue->getType()->isIntegerTy()) && 639 "StartValue is not an integer for integer induction"); 640 assert(StepValue->getType()->isIntegerTy() && 641 "StepValue is not an integer"); 642 } 643 InductionInfo() 644 : StartValue(nullptr), IK(IK_NoInduction), StepValue(nullptr) {} 645 646 /// Get the consecutive direction. Returns: 647 /// 0 - unknown or non-consecutive. 648 /// 1 - consecutive and increasing. 649 /// -1 - consecutive and decreasing. 650 int getConsecutiveDirection() const { 651 if (StepValue && (StepValue->isOne() || StepValue->isMinusOne())) 652 return StepValue->getSExtValue(); 653 return 0; 654 } 655 656 /// Compute the transformed value of Index at offset StartValue using step 657 /// StepValue. 658 /// For integer induction, returns StartValue + Index * StepValue. 659 /// For pointer induction, returns StartValue[Index * StepValue]. 660 /// FIXME: The newly created binary instructions should contain nsw/nuw 661 /// flags, which can be found from the original scalar operations. 662 Value *transform(IRBuilder<> &B, Value *Index) const { 663 switch (IK) { 664 case IK_IntInduction: 665 assert(Index->getType() == StartValue->getType() && 666 "Index type does not match StartValue type"); 667 if (StepValue->isMinusOne()) 668 return B.CreateSub(StartValue, Index); 669 if (!StepValue->isOne()) 670 Index = B.CreateMul(Index, StepValue); 671 return B.CreateAdd(StartValue, Index); 672 673 case IK_PtrInduction: 674 if (StepValue->isMinusOne()) 675 Index = B.CreateNeg(Index); 676 else if (!StepValue->isOne()) 677 Index = B.CreateMul(Index, StepValue); 678 return B.CreateGEP(StartValue, Index); 679 680 case IK_NoInduction: 681 return nullptr; 682 } 683 llvm_unreachable("invalid enum"); 684 } 685 686 /// Start value. 687 TrackingVH<Value> StartValue; 688 /// Induction kind. 689 InductionKind IK; 690 /// Step value. 691 ConstantInt *StepValue; 692 }; 693 694 /// ReductionList contains the reduction descriptors for all 695 /// of the reductions that were found in the loop. 696 typedef DenseMap<PHINode*, ReductionDescriptor> ReductionList; 697 698 /// InductionList saves induction variables and maps them to the 699 /// induction descriptor. 700 typedef MapVector<PHINode*, InductionInfo> InductionList; 701 702 /// Returns true if it is legal to vectorize this loop. 703 /// This does not mean that it is profitable to vectorize this 704 /// loop, only that it is legal to do so. 705 bool canVectorize(); 706 707 /// Returns the Induction variable. 708 PHINode *getInduction() { return Induction; } 709 710 /// Returns the reduction variables found in the loop. 711 ReductionList *getReductionVars() { return &Reductions; } 712 713 /// Returns the induction variables found in the loop. 714 InductionList *getInductionVars() { return &Inductions; } 715 716 /// Returns the widest induction type. 717 Type *getWidestInductionType() { return WidestIndTy; } 718 719 /// Returns True if V is an induction variable in this loop. 720 bool isInductionVariable(const Value *V); 721 722 /// Return true if the block BB needs to be predicated in order for the loop 723 /// to be vectorized. 724 bool blockNeedsPredication(BasicBlock *BB); 725 726 /// Check if this pointer is consecutive when vectorizing. This happens 727 /// when the last index of the GEP is the induction variable, or that the 728 /// pointer itself is an induction variable. 729 /// This check allows us to vectorize A[idx] into a wide load/store. 730 /// Returns: 731 /// 0 - Stride is unknown or non-consecutive. 732 /// 1 - Address is consecutive. 733 /// -1 - Address is consecutive, and decreasing. 734 int isConsecutivePtr(Value *Ptr); 735 736 /// Returns true if the value V is uniform within the loop. 737 bool isUniform(Value *V); 738 739 /// Returns true if this instruction will remain scalar after vectorization. 740 bool isUniformAfterVectorization(Instruction* I) { return Uniforms.count(I); } 741 742 /// Returns the information that we collected about runtime memory check. 743 LoopAccessAnalysis::RuntimePointerCheck *getRuntimePointerCheck() { 744 return LAA.getRuntimePointerCheck(); 745 } 746 747 LoopAccessAnalysis *getLAA() { 748 return &LAA; 749 } 750 751 /// This function returns the identity element (or neutral element) for 752 /// the operation K. 753 static Constant *getReductionIdentity(ReductionKind K, Type *Tp); 754 755 unsigned getMaxSafeDepDistBytes() { return LAA.getMaxSafeDepDistBytes(); } 756 757 bool hasStride(Value *V) { return StrideSet.count(V); } 758 bool mustCheckStrides() { return !StrideSet.empty(); } 759 SmallPtrSet<Value *, 8>::iterator strides_begin() { 760 return StrideSet.begin(); 761 } 762 SmallPtrSet<Value *, 8>::iterator strides_end() { return StrideSet.end(); } 763 764 /// Returns true if the target machine supports masked store operation 765 /// for the given \p DataType and kind of access to \p Ptr. 766 bool isLegalMaskedStore(Type *DataType, Value *Ptr) { 767 return TTI->isLegalMaskedStore(DataType, isConsecutivePtr(Ptr)); 768 } 769 /// Returns true if the target machine supports masked load operation 770 /// for the given \p DataType and kind of access to \p Ptr. 771 bool isLegalMaskedLoad(Type *DataType, Value *Ptr) { 772 return TTI->isLegalMaskedLoad(DataType, isConsecutivePtr(Ptr)); 773 } 774 /// Returns true if vector representation of the instruction \p I 775 /// requires mask. 776 bool isMaskRequired(const Instruction* I) { 777 return (MaskedOp.count(I) != 0); 778 } 779 unsigned getNumStores() const { 780 return LAA.getNumStores(); 781 } 782 unsigned getNumLoads() const { 783 return LAA.getNumLoads(); 784 } 785 unsigned getNumPredStores() const { 786 return NumPredStores; 787 } 788 private: 789 /// Check if a single basic block loop is vectorizable. 790 /// At this point we know that this is a loop with a constant trip count 791 /// and we only need to check individual instructions. 792 bool canVectorizeInstrs(); 793 794 /// When we vectorize loops we may change the order in which 795 /// we read and write from memory. This method checks if it is 796 /// legal to vectorize the code, considering only memory constrains. 797 /// Returns true if the loop is vectorizable 798 bool canVectorizeMemory(); 799 800 /// Return true if we can vectorize this loop using the IF-conversion 801 /// transformation. 802 bool canVectorizeWithIfConvert(); 803 804 /// Collect the variables that need to stay uniform after vectorization. 805 void collectLoopUniforms(); 806 807 /// Return true if all of the instructions in the block can be speculatively 808 /// executed. \p SafePtrs is a list of addresses that are known to be legal 809 /// and we know that we can read from them without segfault. 810 bool blockCanBePredicated(BasicBlock *BB, SmallPtrSetImpl<Value *> &SafePtrs); 811 812 /// Returns True, if 'Phi' is the kind of reduction variable for type 813 /// 'Kind'. If this is a reduction variable, it adds it to ReductionList. 814 bool AddReductionVar(PHINode *Phi, ReductionKind Kind); 815 /// Returns a struct describing if the instruction 'I' can be a reduction 816 /// variable of type 'Kind'. If the reduction is a min/max pattern of 817 /// select(icmp()) this function advances the instruction pointer 'I' from the 818 /// compare instruction to the select instruction and stores this pointer in 819 /// 'PatternLastInst' member of the returned struct. 820 ReductionInstDesc isReductionInstr(Instruction *I, ReductionKind Kind, 821 ReductionInstDesc &Desc); 822 /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction 823 /// pattern corresponding to a min(X, Y) or max(X, Y). 824 static ReductionInstDesc isMinMaxSelectCmpPattern(Instruction *I, 825 ReductionInstDesc &Prev); 826 /// Returns the induction kind of Phi and record the step. This function may 827 /// return NoInduction if the PHI is not an induction variable. 828 InductionKind isInductionVariable(PHINode *Phi, ConstantInt *&StepValue); 829 830 /// \brief Collect memory access with loop invariant strides. 831 /// 832 /// Looks for accesses like "a[i * StrideA]" where "StrideA" is loop 833 /// invariant. 834 void collectStridedAccess(Value *LoadOrStoreInst); 835 836 /// Report an analysis message to assist the user in diagnosing loops that are 837 /// not vectorized. 838 void emitAnalysis(VectorizationReport &Message) { 839 VectorizationReport::emitAnalysis(Message, TheFunction, TheLoop); 840 } 841 842 unsigned NumPredStores; 843 844 /// The loop that we evaluate. 845 Loop *TheLoop; 846 /// Scev analysis. 847 ScalarEvolution *SE; 848 /// DataLayout analysis. 849 const DataLayout *DL; 850 /// Target Library Info. 851 TargetLibraryInfo *TLI; 852 /// Parent function 853 Function *TheFunction; 854 /// Target Transform Info 855 const TargetTransformInfo *TTI; 856 857 // --- vectorization state --- // 858 859 /// Holds the integer induction variable. This is the counter of the 860 /// loop. 861 PHINode *Induction; 862 /// Holds the reduction variables. 863 ReductionList Reductions; 864 /// Holds all of the induction variables that we found in the loop. 865 /// Notice that inductions don't need to start at zero and that induction 866 /// variables can be pointers. 867 InductionList Inductions; 868 /// Holds the widest induction type encountered. 869 Type *WidestIndTy; 870 871 /// Allowed outside users. This holds the reduction 872 /// vars which can be accessed from outside the loop. 873 SmallPtrSet<Value*, 4> AllowedExit; 874 /// This set holds the variables which are known to be uniform after 875 /// vectorization. 876 SmallPtrSet<Instruction*, 4> Uniforms; 877 LoopAccessAnalysis LAA; 878 /// Can we assume the absence of NaNs. 879 bool HasFunNoNaNAttr; 880 881 ValueToValueMap Strides; 882 SmallPtrSet<Value *, 8> StrideSet; 883 884 /// While vectorizing these instructions we have to generate a 885 /// call to the appropriate masked intrinsic 886 SmallPtrSet<const Instruction*, 8> MaskedOp; 887 }; 888 889 /// LoopVectorizationCostModel - estimates the expected speedups due to 890 /// vectorization. 891 /// In many cases vectorization is not profitable. This can happen because of 892 /// a number of reasons. In this class we mainly attempt to predict the 893 /// expected speedup/slowdowns due to the supported instruction set. We use the 894 /// TargetTransformInfo to query the different backends for the cost of 895 /// different operations. 896 class LoopVectorizationCostModel { 897 public: 898 LoopVectorizationCostModel(Loop *L, ScalarEvolution *SE, LoopInfo *LI, 899 LoopVectorizationLegality *Legal, 900 const TargetTransformInfo &TTI, 901 const DataLayout *DL, const TargetLibraryInfo *TLI, 902 AssumptionCache *AC, const Function *F, 903 const LoopVectorizeHints *Hints) 904 : TheLoop(L), SE(SE), LI(LI), Legal(Legal), TTI(TTI), DL(DL), TLI(TLI), 905 TheFunction(F), Hints(Hints) { 906 CodeMetrics::collectEphemeralValues(L, AC, EphValues); 907 } 908 909 /// Information about vectorization costs 910 struct VectorizationFactor { 911 unsigned Width; // Vector width with best cost 912 unsigned Cost; // Cost of the loop with that width 913 }; 914 /// \return The most profitable vectorization factor and the cost of that VF. 915 /// This method checks every power of two up to VF. If UserVF is not ZERO 916 /// then this vectorization factor will be selected if vectorization is 917 /// possible. 918 VectorizationFactor selectVectorizationFactor(bool OptForSize); 919 920 /// \return The size (in bits) of the widest type in the code that 921 /// needs to be vectorized. We ignore values that remain scalar such as 922 /// 64 bit loop indices. 923 unsigned getWidestType(); 924 925 /// \return The most profitable unroll factor. 926 /// If UserUF is non-zero then this method finds the best unroll-factor 927 /// based on register pressure and other parameters. 928 /// VF and LoopCost are the selected vectorization factor and the cost of the 929 /// selected VF. 930 unsigned selectUnrollFactor(bool OptForSize, unsigned VF, unsigned LoopCost); 931 932 /// \brief A struct that represents some properties of the register usage 933 /// of a loop. 934 struct RegisterUsage { 935 /// Holds the number of loop invariant values that are used in the loop. 936 unsigned LoopInvariantRegs; 937 /// Holds the maximum number of concurrent live intervals in the loop. 938 unsigned MaxLocalUsers; 939 /// Holds the number of instructions in the loop. 940 unsigned NumInstructions; 941 }; 942 943 /// \return information about the register usage of the loop. 944 RegisterUsage calculateRegisterUsage(); 945 946 private: 947 /// Returns the expected execution cost. The unit of the cost does 948 /// not matter because we use the 'cost' units to compare different 949 /// vector widths. The cost that is returned is *not* normalized by 950 /// the factor width. 951 unsigned expectedCost(unsigned VF); 952 953 /// Returns the execution time cost of an instruction for a given vector 954 /// width. Vector width of one means scalar. 955 unsigned getInstructionCost(Instruction *I, unsigned VF); 956 957 /// A helper function for converting Scalar types to vector types. 958 /// If the incoming type is void, we return void. If the VF is 1, we return 959 /// the scalar type. 960 static Type* ToVectorTy(Type *Scalar, unsigned VF); 961 962 /// Returns whether the instruction is a load or store and will be a emitted 963 /// as a vector operation. 964 bool isConsecutiveLoadOrStore(Instruction *I); 965 966 /// Report an analysis message to assist the user in diagnosing loops that are 967 /// not vectorized. 968 void emitAnalysis(VectorizationReport &Message) { 969 VectorizationReport::emitAnalysis(Message, TheFunction, TheLoop); 970 } 971 972 /// Values used only by @llvm.assume calls. 973 SmallPtrSet<const Value *, 32> EphValues; 974 975 /// The loop that we evaluate. 976 Loop *TheLoop; 977 /// Scev analysis. 978 ScalarEvolution *SE; 979 /// Loop Info analysis. 980 LoopInfo *LI; 981 /// Vectorization legality. 982 LoopVectorizationLegality *Legal; 983 /// Vector target information. 984 const TargetTransformInfo &TTI; 985 /// Target data layout information. 986 const DataLayout *DL; 987 /// Target Library Info. 988 const TargetLibraryInfo *TLI; 989 const Function *TheFunction; 990 // Loop Vectorize Hint. 991 const LoopVectorizeHints *Hints; 992 }; 993 994 /// Utility class for getting and setting loop vectorizer hints in the form 995 /// of loop metadata. 996 /// This class keeps a number of loop annotations locally (as member variables) 997 /// and can, upon request, write them back as metadata on the loop. It will 998 /// initially scan the loop for existing metadata, and will update the local 999 /// values based on information in the loop. 1000 /// We cannot write all values to metadata, as the mere presence of some info, 1001 /// for example 'force', means a decision has been made. So, we need to be 1002 /// careful NOT to add them if the user hasn't specifically asked so. 1003 class LoopVectorizeHints { 1004 enum HintKind { 1005 HK_WIDTH, 1006 HK_UNROLL, 1007 HK_FORCE 1008 }; 1009 1010 /// Hint - associates name and validation with the hint value. 1011 struct Hint { 1012 const char * Name; 1013 unsigned Value; // This may have to change for non-numeric values. 1014 HintKind Kind; 1015 1016 Hint(const char * Name, unsigned Value, HintKind Kind) 1017 : Name(Name), Value(Value), Kind(Kind) { } 1018 1019 bool validate(unsigned Val) { 1020 switch (Kind) { 1021 case HK_WIDTH: 1022 return isPowerOf2_32(Val) && Val <= MaxVectorWidth; 1023 case HK_UNROLL: 1024 return isPowerOf2_32(Val) && Val <= MaxInterleaveFactor; 1025 case HK_FORCE: 1026 return (Val <= 1); 1027 } 1028 return false; 1029 } 1030 }; 1031 1032 /// Vectorization width. 1033 Hint Width; 1034 /// Vectorization interleave factor. 1035 Hint Interleave; 1036 /// Vectorization forced 1037 Hint Force; 1038 1039 /// Return the loop metadata prefix. 1040 static StringRef Prefix() { return "llvm.loop."; } 1041 1042 public: 1043 enum ForceKind { 1044 FK_Undefined = -1, ///< Not selected. 1045 FK_Disabled = 0, ///< Forcing disabled. 1046 FK_Enabled = 1, ///< Forcing enabled. 1047 }; 1048 1049 LoopVectorizeHints(const Loop *L, bool DisableInterleaving) 1050 : Width("vectorize.width", VectorizationFactor, HK_WIDTH), 1051 Interleave("interleave.count", DisableInterleaving, HK_UNROLL), 1052 Force("vectorize.enable", FK_Undefined, HK_FORCE), 1053 TheLoop(L) { 1054 // Populate values with existing loop metadata. 1055 getHintsFromMetadata(); 1056 1057 // force-vector-interleave overrides DisableInterleaving. 1058 if (VectorizationInterleave.getNumOccurrences() > 0) 1059 Interleave.Value = VectorizationInterleave; 1060 1061 DEBUG(if (DisableInterleaving && Interleave.Value == 1) dbgs() 1062 << "LV: Interleaving disabled by the pass manager\n"); 1063 } 1064 1065 /// Mark the loop L as already vectorized by setting the width to 1. 1066 void setAlreadyVectorized() { 1067 Width.Value = Interleave.Value = 1; 1068 Hint Hints[] = {Width, Interleave}; 1069 writeHintsToMetadata(Hints); 1070 } 1071 1072 /// Dumps all the hint information. 1073 std::string emitRemark() const { 1074 VectorizationReport R; 1075 if (Force.Value == LoopVectorizeHints::FK_Disabled) 1076 R << "vectorization is explicitly disabled"; 1077 else { 1078 R << "use -Rpass-analysis=loop-vectorize for more info"; 1079 if (Force.Value == LoopVectorizeHints::FK_Enabled) { 1080 R << " (Force=true"; 1081 if (Width.Value != 0) 1082 R << ", Vector Width=" << Width.Value; 1083 if (Interleave.Value != 0) 1084 R << ", Interleave Count=" << Interleave.Value; 1085 R << ")"; 1086 } 1087 } 1088 1089 return R.str(); 1090 } 1091 1092 unsigned getWidth() const { return Width.Value; } 1093 unsigned getInterleave() const { return Interleave.Value; } 1094 enum ForceKind getForce() const { return (ForceKind)Force.Value; } 1095 1096 private: 1097 /// Find hints specified in the loop metadata and update local values. 1098 void getHintsFromMetadata() { 1099 MDNode *LoopID = TheLoop->getLoopID(); 1100 if (!LoopID) 1101 return; 1102 1103 // First operand should refer to the loop id itself. 1104 assert(LoopID->getNumOperands() > 0 && "requires at least one operand"); 1105 assert(LoopID->getOperand(0) == LoopID && "invalid loop id"); 1106 1107 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) { 1108 const MDString *S = nullptr; 1109 SmallVector<Metadata *, 4> Args; 1110 1111 // The expected hint is either a MDString or a MDNode with the first 1112 // operand a MDString. 1113 if (const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i))) { 1114 if (!MD || MD->getNumOperands() == 0) 1115 continue; 1116 S = dyn_cast<MDString>(MD->getOperand(0)); 1117 for (unsigned i = 1, ie = MD->getNumOperands(); i < ie; ++i) 1118 Args.push_back(MD->getOperand(i)); 1119 } else { 1120 S = dyn_cast<MDString>(LoopID->getOperand(i)); 1121 assert(Args.size() == 0 && "too many arguments for MDString"); 1122 } 1123 1124 if (!S) 1125 continue; 1126 1127 // Check if the hint starts with the loop metadata prefix. 1128 StringRef Name = S->getString(); 1129 if (Args.size() == 1) 1130 setHint(Name, Args[0]); 1131 } 1132 } 1133 1134 /// Checks string hint with one operand and set value if valid. 1135 void setHint(StringRef Name, Metadata *Arg) { 1136 if (!Name.startswith(Prefix())) 1137 return; 1138 Name = Name.substr(Prefix().size(), StringRef::npos); 1139 1140 const ConstantInt *C = mdconst::dyn_extract<ConstantInt>(Arg); 1141 if (!C) return; 1142 unsigned Val = C->getZExtValue(); 1143 1144 Hint *Hints[] = {&Width, &Interleave, &Force}; 1145 for (auto H : Hints) { 1146 if (Name == H->Name) { 1147 if (H->validate(Val)) 1148 H->Value = Val; 1149 else 1150 DEBUG(dbgs() << "LV: ignoring invalid hint '" << Name << "'\n"); 1151 break; 1152 } 1153 } 1154 } 1155 1156 /// Create a new hint from name / value pair. 1157 MDNode *createHintMetadata(StringRef Name, unsigned V) const { 1158 LLVMContext &Context = TheLoop->getHeader()->getContext(); 1159 Metadata *MDs[] = {MDString::get(Context, Name), 1160 ConstantAsMetadata::get( 1161 ConstantInt::get(Type::getInt32Ty(Context), V))}; 1162 return MDNode::get(Context, MDs); 1163 } 1164 1165 /// Matches metadata with hint name. 1166 bool matchesHintMetadataName(MDNode *Node, ArrayRef<Hint> HintTypes) { 1167 MDString* Name = dyn_cast<MDString>(Node->getOperand(0)); 1168 if (!Name) 1169 return false; 1170 1171 for (auto H : HintTypes) 1172 if (Name->getString().endswith(H.Name)) 1173 return true; 1174 return false; 1175 } 1176 1177 /// Sets current hints into loop metadata, keeping other values intact. 1178 void writeHintsToMetadata(ArrayRef<Hint> HintTypes) { 1179 if (HintTypes.size() == 0) 1180 return; 1181 1182 // Reserve the first element to LoopID (see below). 1183 SmallVector<Metadata *, 4> MDs(1); 1184 // If the loop already has metadata, then ignore the existing operands. 1185 MDNode *LoopID = TheLoop->getLoopID(); 1186 if (LoopID) { 1187 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) { 1188 MDNode *Node = cast<MDNode>(LoopID->getOperand(i)); 1189 // If node in update list, ignore old value. 1190 if (!matchesHintMetadataName(Node, HintTypes)) 1191 MDs.push_back(Node); 1192 } 1193 } 1194 1195 // Now, add the missing hints. 1196 for (auto H : HintTypes) 1197 MDs.push_back(createHintMetadata(Twine(Prefix(), H.Name).str(), H.Value)); 1198 1199 // Replace current metadata node with new one. 1200 LLVMContext &Context = TheLoop->getHeader()->getContext(); 1201 MDNode *NewLoopID = MDNode::get(Context, MDs); 1202 // Set operand 0 to refer to the loop id itself. 1203 NewLoopID->replaceOperandWith(0, NewLoopID); 1204 1205 TheLoop->setLoopID(NewLoopID); 1206 } 1207 1208 /// The loop these hints belong to. 1209 const Loop *TheLoop; 1210 }; 1211 1212 static void emitMissedWarning(Function *F, Loop *L, 1213 const LoopVectorizeHints &LH) { 1214 emitOptimizationRemarkMissed(F->getContext(), DEBUG_TYPE, *F, 1215 L->getStartLoc(), LH.emitRemark()); 1216 1217 if (LH.getForce() == LoopVectorizeHints::FK_Enabled) { 1218 if (LH.getWidth() != 1) 1219 emitLoopVectorizeWarning( 1220 F->getContext(), *F, L->getStartLoc(), 1221 "failed explicitly specified loop vectorization"); 1222 else if (LH.getInterleave() != 1) 1223 emitLoopInterleaveWarning( 1224 F->getContext(), *F, L->getStartLoc(), 1225 "failed explicitly specified loop interleaving"); 1226 } 1227 } 1228 1229 static void addInnerLoop(Loop &L, SmallVectorImpl<Loop *> &V) { 1230 if (L.empty()) 1231 return V.push_back(&L); 1232 1233 for (Loop *InnerL : L) 1234 addInnerLoop(*InnerL, V); 1235 } 1236 1237 /// The LoopVectorize Pass. 1238 struct LoopVectorize : public FunctionPass { 1239 /// Pass identification, replacement for typeid 1240 static char ID; 1241 1242 explicit LoopVectorize(bool NoUnrolling = false, bool AlwaysVectorize = true) 1243 : FunctionPass(ID), 1244 DisableUnrolling(NoUnrolling), 1245 AlwaysVectorize(AlwaysVectorize) { 1246 initializeLoopVectorizePass(*PassRegistry::getPassRegistry()); 1247 } 1248 1249 ScalarEvolution *SE; 1250 const DataLayout *DL; 1251 LoopInfo *LI; 1252 TargetTransformInfo *TTI; 1253 DominatorTree *DT; 1254 BlockFrequencyInfo *BFI; 1255 TargetLibraryInfo *TLI; 1256 AliasAnalysis *AA; 1257 AssumptionCache *AC; 1258 bool DisableUnrolling; 1259 bool AlwaysVectorize; 1260 1261 BlockFrequency ColdEntryFreq; 1262 1263 bool runOnFunction(Function &F) override { 1264 SE = &getAnalysis<ScalarEvolution>(); 1265 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>(); 1266 DL = DLP ? &DLP->getDataLayout() : nullptr; 1267 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 1268 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 1269 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 1270 BFI = &getAnalysis<BlockFrequencyInfo>(); 1271 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>(); 1272 TLI = TLIP ? &TLIP->getTLI() : nullptr; 1273 AA = &getAnalysis<AliasAnalysis>(); 1274 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); 1275 1276 // Compute some weights outside of the loop over the loops. Compute this 1277 // using a BranchProbability to re-use its scaling math. 1278 const BranchProbability ColdProb(1, 5); // 20% 1279 ColdEntryFreq = BlockFrequency(BFI->getEntryFreq()) * ColdProb; 1280 1281 // If the target claims to have no vector registers don't attempt 1282 // vectorization. 1283 if (!TTI->getNumberOfRegisters(true)) 1284 return false; 1285 1286 if (!DL) { 1287 DEBUG(dbgs() << "\nLV: Not vectorizing " << F.getName() 1288 << ": Missing data layout\n"); 1289 return false; 1290 } 1291 1292 // Build up a worklist of inner-loops to vectorize. This is necessary as 1293 // the act of vectorizing or partially unrolling a loop creates new loops 1294 // and can invalidate iterators across the loops. 1295 SmallVector<Loop *, 8> Worklist; 1296 1297 for (Loop *L : *LI) 1298 addInnerLoop(*L, Worklist); 1299 1300 LoopsAnalyzed += Worklist.size(); 1301 1302 // Now walk the identified inner loops. 1303 bool Changed = false; 1304 while (!Worklist.empty()) 1305 Changed |= processLoop(Worklist.pop_back_val()); 1306 1307 // Process each loop nest in the function. 1308 return Changed; 1309 } 1310 1311 bool processLoop(Loop *L) { 1312 assert(L->empty() && "Only process inner loops."); 1313 1314 #ifndef NDEBUG 1315 const std::string DebugLocStr = getDebugLocString(L); 1316 #endif /* NDEBUG */ 1317 1318 DEBUG(dbgs() << "\nLV: Checking a loop in \"" 1319 << L->getHeader()->getParent()->getName() << "\" from " 1320 << DebugLocStr << "\n"); 1321 1322 LoopVectorizeHints Hints(L, DisableUnrolling); 1323 1324 DEBUG(dbgs() << "LV: Loop hints:" 1325 << " force=" 1326 << (Hints.getForce() == LoopVectorizeHints::FK_Disabled 1327 ? "disabled" 1328 : (Hints.getForce() == LoopVectorizeHints::FK_Enabled 1329 ? "enabled" 1330 : "?")) << " width=" << Hints.getWidth() 1331 << " unroll=" << Hints.getInterleave() << "\n"); 1332 1333 // Function containing loop 1334 Function *F = L->getHeader()->getParent(); 1335 1336 // Looking at the diagnostic output is the only way to determine if a loop 1337 // was vectorized (other than looking at the IR or machine code), so it 1338 // is important to generate an optimization remark for each loop. Most of 1339 // these messages are generated by emitOptimizationRemarkAnalysis. Remarks 1340 // generated by emitOptimizationRemark and emitOptimizationRemarkMissed are 1341 // less verbose reporting vectorized loops and unvectorized loops that may 1342 // benefit from vectorization, respectively. 1343 1344 if (Hints.getForce() == LoopVectorizeHints::FK_Disabled) { 1345 DEBUG(dbgs() << "LV: Not vectorizing: #pragma vectorize disable.\n"); 1346 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F, 1347 L->getStartLoc(), Hints.emitRemark()); 1348 return false; 1349 } 1350 1351 if (!AlwaysVectorize && Hints.getForce() != LoopVectorizeHints::FK_Enabled) { 1352 DEBUG(dbgs() << "LV: Not vectorizing: No #pragma vectorize enable.\n"); 1353 emitOptimizationRemarkAnalysis(F->getContext(), DEBUG_TYPE, *F, 1354 L->getStartLoc(), Hints.emitRemark()); 1355 return false; 1356 } 1357 1358 if (Hints.getWidth() == 1 && Hints.getInterleave() == 1) { 1359 DEBUG(dbgs() << "LV: Not vectorizing: Disabled/already vectorized.\n"); 1360 emitOptimizationRemarkAnalysis( 1361 F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(), 1362 "loop not vectorized: vector width and interleave count are " 1363 "explicitly set to 1"); 1364 return false; 1365 } 1366 1367 // Check the loop for a trip count threshold: 1368 // do not vectorize loops with a tiny trip count. 1369 const unsigned TC = SE->getSmallConstantTripCount(L); 1370 if (TC > 0u && TC < TinyTripCountVectorThreshold) { 1371 DEBUG(dbgs() << "LV: Found a loop with a very small trip count. " 1372 << "This loop is not worth vectorizing."); 1373 if (Hints.getForce() == LoopVectorizeHints::FK_Enabled) 1374 DEBUG(dbgs() << " But vectorizing was explicitly forced.\n"); 1375 else { 1376 DEBUG(dbgs() << "\n"); 1377 emitOptimizationRemarkAnalysis( 1378 F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(), 1379 "vectorization is not beneficial and is not explicitly forced"); 1380 return false; 1381 } 1382 } 1383 1384 // Check if it is legal to vectorize the loop. 1385 LoopVectorizationLegality LVL(L, SE, DL, DT, TLI, AA, F, TTI); 1386 if (!LVL.canVectorize()) { 1387 DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n"); 1388 emitMissedWarning(F, L, Hints); 1389 return false; 1390 } 1391 1392 // Use the cost model. 1393 LoopVectorizationCostModel CM(L, SE, LI, &LVL, *TTI, DL, TLI, AC, F, 1394 &Hints); 1395 1396 // Check the function attributes to find out if this function should be 1397 // optimized for size. 1398 bool OptForSize = Hints.getForce() != LoopVectorizeHints::FK_Enabled && 1399 F->hasFnAttribute(Attribute::OptimizeForSize); 1400 1401 // Compute the weighted frequency of this loop being executed and see if it 1402 // is less than 20% of the function entry baseline frequency. Note that we 1403 // always have a canonical loop here because we think we *can* vectoriez. 1404 // FIXME: This is hidden behind a flag due to pervasive problems with 1405 // exactly what block frequency models. 1406 if (LoopVectorizeWithBlockFrequency) { 1407 BlockFrequency LoopEntryFreq = BFI->getBlockFreq(L->getLoopPreheader()); 1408 if (Hints.getForce() != LoopVectorizeHints::FK_Enabled && 1409 LoopEntryFreq < ColdEntryFreq) 1410 OptForSize = true; 1411 } 1412 1413 // Check the function attributes to see if implicit floats are allowed.a 1414 // FIXME: This check doesn't seem possibly correct -- what if the loop is 1415 // an integer loop and the vector instructions selected are purely integer 1416 // vector instructions? 1417 if (F->hasFnAttribute(Attribute::NoImplicitFloat)) { 1418 DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat" 1419 "attribute is used.\n"); 1420 emitOptimizationRemarkAnalysis( 1421 F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(), 1422 "loop not vectorized due to NoImplicitFloat attribute"); 1423 emitMissedWarning(F, L, Hints); 1424 return false; 1425 } 1426 1427 // Select the optimal vectorization factor. 1428 const LoopVectorizationCostModel::VectorizationFactor VF = 1429 CM.selectVectorizationFactor(OptForSize); 1430 1431 // Select the unroll factor. 1432 const unsigned UF = 1433 CM.selectUnrollFactor(OptForSize, VF.Width, VF.Cost); 1434 1435 DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width << ") in " 1436 << DebugLocStr << '\n'); 1437 DEBUG(dbgs() << "LV: Unroll Factor is " << UF << '\n'); 1438 1439 if (VF.Width == 1) { 1440 DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial\n"); 1441 1442 if (UF == 1) { 1443 emitOptimizationRemarkAnalysis( 1444 F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(), 1445 "not beneficial to vectorize and user disabled interleaving"); 1446 return false; 1447 } 1448 DEBUG(dbgs() << "LV: Trying to at least unroll the loops.\n"); 1449 1450 // Report the unrolling decision. 1451 emitOptimizationRemark(F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(), 1452 Twine("unrolled with interleaving factor " + 1453 Twine(UF) + 1454 " (vectorization not beneficial)")); 1455 1456 // We decided not to vectorize, but we may want to unroll. 1457 1458 InnerLoopUnroller Unroller(L, SE, LI, DT, DL, TLI, UF); 1459 Unroller.vectorize(&LVL); 1460 } else { 1461 // If we decided that it is *legal* to vectorize the loop then do it. 1462 InnerLoopVectorizer LB(L, SE, LI, DT, DL, TLI, VF.Width, UF); 1463 LB.vectorize(&LVL); 1464 ++LoopsVectorized; 1465 1466 // Report the vectorization decision. 1467 emitOptimizationRemark( 1468 F->getContext(), DEBUG_TYPE, *F, L->getStartLoc(), 1469 Twine("vectorized loop (vectorization factor: ") + Twine(VF.Width) + 1470 ", unrolling interleave factor: " + Twine(UF) + ")"); 1471 } 1472 1473 // Mark the loop as already vectorized to avoid vectorizing again. 1474 Hints.setAlreadyVectorized(); 1475 1476 DEBUG(verifyFunction(*L->getHeader()->getParent())); 1477 return true; 1478 } 1479 1480 void getAnalysisUsage(AnalysisUsage &AU) const override { 1481 AU.addRequired<AssumptionCacheTracker>(); 1482 AU.addRequiredID(LoopSimplifyID); 1483 AU.addRequiredID(LCSSAID); 1484 AU.addRequired<BlockFrequencyInfo>(); 1485 AU.addRequired<DominatorTreeWrapperPass>(); 1486 AU.addRequired<LoopInfoWrapperPass>(); 1487 AU.addRequired<ScalarEvolution>(); 1488 AU.addRequired<TargetTransformInfoWrapperPass>(); 1489 AU.addRequired<AliasAnalysis>(); 1490 AU.addPreserved<LoopInfoWrapperPass>(); 1491 AU.addPreserved<DominatorTreeWrapperPass>(); 1492 AU.addPreserved<AliasAnalysis>(); 1493 } 1494 1495 }; 1496 1497 } // end anonymous namespace 1498 1499 //===----------------------------------------------------------------------===// 1500 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and 1501 // LoopVectorizationCostModel. 1502 //===----------------------------------------------------------------------===// 1503 1504 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) { 1505 // We need to place the broadcast of invariant variables outside the loop. 1506 Instruction *Instr = dyn_cast<Instruction>(V); 1507 bool NewInstr = 1508 (Instr && std::find(LoopVectorBody.begin(), LoopVectorBody.end(), 1509 Instr->getParent()) != LoopVectorBody.end()); 1510 bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr; 1511 1512 // Place the code for broadcasting invariant variables in the new preheader. 1513 IRBuilder<>::InsertPointGuard Guard(Builder); 1514 if (Invariant) 1515 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator()); 1516 1517 // Broadcast the scalar into all locations in the vector. 1518 Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast"); 1519 1520 return Shuf; 1521 } 1522 1523 Value *InnerLoopVectorizer::getStepVector(Value *Val, int StartIdx, 1524 Value *Step) { 1525 assert(Val->getType()->isVectorTy() && "Must be a vector"); 1526 assert(Val->getType()->getScalarType()->isIntegerTy() && 1527 "Elem must be an integer"); 1528 assert(Step->getType() == Val->getType()->getScalarType() && 1529 "Step has wrong type"); 1530 // Create the types. 1531 Type *ITy = Val->getType()->getScalarType(); 1532 VectorType *Ty = cast<VectorType>(Val->getType()); 1533 int VLen = Ty->getNumElements(); 1534 SmallVector<Constant*, 8> Indices; 1535 1536 // Create a vector of consecutive numbers from zero to VF. 1537 for (int i = 0; i < VLen; ++i) 1538 Indices.push_back(ConstantInt::get(ITy, StartIdx + i)); 1539 1540 // Add the consecutive indices to the vector value. 1541 Constant *Cv = ConstantVector::get(Indices); 1542 assert(Cv->getType() == Val->getType() && "Invalid consecutive vec"); 1543 Step = Builder.CreateVectorSplat(VLen, Step); 1544 assert(Step->getType() == Val->getType() && "Invalid step vec"); 1545 // FIXME: The newly created binary instructions should contain nsw/nuw flags, 1546 // which can be found from the original scalar operations. 1547 Step = Builder.CreateMul(Cv, Step); 1548 return Builder.CreateAdd(Val, Step, "induction"); 1549 } 1550 1551 /// \brief Find the operand of the GEP that should be checked for consecutive 1552 /// stores. This ignores trailing indices that have no effect on the final 1553 /// pointer. 1554 static unsigned getGEPInductionOperand(const DataLayout *DL, 1555 const GetElementPtrInst *Gep) { 1556 unsigned LastOperand = Gep->getNumOperands() - 1; 1557 unsigned GEPAllocSize = DL->getTypeAllocSize( 1558 cast<PointerType>(Gep->getType()->getScalarType())->getElementType()); 1559 1560 // Walk backwards and try to peel off zeros. 1561 while (LastOperand > 1 && match(Gep->getOperand(LastOperand), m_Zero())) { 1562 // Find the type we're currently indexing into. 1563 gep_type_iterator GEPTI = gep_type_begin(Gep); 1564 std::advance(GEPTI, LastOperand - 1); 1565 1566 // If it's a type with the same allocation size as the result of the GEP we 1567 // can peel off the zero index. 1568 if (DL->getTypeAllocSize(*GEPTI) != GEPAllocSize) 1569 break; 1570 --LastOperand; 1571 } 1572 1573 return LastOperand; 1574 } 1575 1576 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) { 1577 assert(Ptr->getType()->isPointerTy() && "Unexpected non-ptr"); 1578 // Make sure that the pointer does not point to structs. 1579 if (Ptr->getType()->getPointerElementType()->isAggregateType()) 1580 return 0; 1581 1582 // If this value is a pointer induction variable we know it is consecutive. 1583 PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr); 1584 if (Phi && Inductions.count(Phi)) { 1585 InductionInfo II = Inductions[Phi]; 1586 return II.getConsecutiveDirection(); 1587 } 1588 1589 GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr); 1590 if (!Gep) 1591 return 0; 1592 1593 unsigned NumOperands = Gep->getNumOperands(); 1594 Value *GpPtr = Gep->getPointerOperand(); 1595 // If this GEP value is a consecutive pointer induction variable and all of 1596 // the indices are constant then we know it is consecutive. We can 1597 Phi = dyn_cast<PHINode>(GpPtr); 1598 if (Phi && Inductions.count(Phi)) { 1599 1600 // Make sure that the pointer does not point to structs. 1601 PointerType *GepPtrType = cast<PointerType>(GpPtr->getType()); 1602 if (GepPtrType->getElementType()->isAggregateType()) 1603 return 0; 1604 1605 // Make sure that all of the index operands are loop invariant. 1606 for (unsigned i = 1; i < NumOperands; ++i) 1607 if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop)) 1608 return 0; 1609 1610 InductionInfo II = Inductions[Phi]; 1611 return II.getConsecutiveDirection(); 1612 } 1613 1614 unsigned InductionOperand = getGEPInductionOperand(DL, Gep); 1615 1616 // Check that all of the gep indices are uniform except for our induction 1617 // operand. 1618 for (unsigned i = 0; i != NumOperands; ++i) 1619 if (i != InductionOperand && 1620 !SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop)) 1621 return 0; 1622 1623 // We can emit wide load/stores only if the last non-zero index is the 1624 // induction variable. 1625 const SCEV *Last = nullptr; 1626 if (!Strides.count(Gep)) 1627 Last = SE->getSCEV(Gep->getOperand(InductionOperand)); 1628 else { 1629 // Because of the multiplication by a stride we can have a s/zext cast. 1630 // We are going to replace this stride by 1 so the cast is safe to ignore. 1631 // 1632 // %indvars.iv = phi i64 [ 0, %entry ], [ %indvars.iv.next, %for.body ] 1633 // %0 = trunc i64 %indvars.iv to i32 1634 // %mul = mul i32 %0, %Stride1 1635 // %idxprom = zext i32 %mul to i64 << Safe cast. 1636 // %arrayidx = getelementptr inbounds i32* %B, i64 %idxprom 1637 // 1638 Last = replaceSymbolicStrideSCEV(SE, Strides, 1639 Gep->getOperand(InductionOperand), Gep); 1640 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(Last)) 1641 Last = 1642 (C->getSCEVType() == scSignExtend || C->getSCEVType() == scZeroExtend) 1643 ? C->getOperand() 1644 : Last; 1645 } 1646 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) { 1647 const SCEV *Step = AR->getStepRecurrence(*SE); 1648 1649 // The memory is consecutive because the last index is consecutive 1650 // and all other indices are loop invariant. 1651 if (Step->isOne()) 1652 return 1; 1653 if (Step->isAllOnesValue()) 1654 return -1; 1655 } 1656 1657 return 0; 1658 } 1659 1660 bool LoopVectorizationLegality::isUniform(Value *V) { 1661 return LAA.isUniform(V); 1662 } 1663 1664 InnerLoopVectorizer::VectorParts& 1665 InnerLoopVectorizer::getVectorValue(Value *V) { 1666 assert(V != Induction && "The new induction variable should not be used."); 1667 assert(!V->getType()->isVectorTy() && "Can't widen a vector"); 1668 1669 // If we have a stride that is replaced by one, do it here. 1670 if (Legal->hasStride(V)) 1671 V = ConstantInt::get(V->getType(), 1); 1672 1673 // If we have this scalar in the map, return it. 1674 if (WidenMap.has(V)) 1675 return WidenMap.get(V); 1676 1677 // If this scalar is unknown, assume that it is a constant or that it is 1678 // loop invariant. Broadcast V and save the value for future uses. 1679 Value *B = getBroadcastInstrs(V); 1680 return WidenMap.splat(V, B); 1681 } 1682 1683 Value *InnerLoopVectorizer::reverseVector(Value *Vec) { 1684 assert(Vec->getType()->isVectorTy() && "Invalid type"); 1685 SmallVector<Constant*, 8> ShuffleMask; 1686 for (unsigned i = 0; i < VF; ++i) 1687 ShuffleMask.push_back(Builder.getInt32(VF - i - 1)); 1688 1689 return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()), 1690 ConstantVector::get(ShuffleMask), 1691 "reverse"); 1692 } 1693 1694 void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr) { 1695 // Attempt to issue a wide load. 1696 LoadInst *LI = dyn_cast<LoadInst>(Instr); 1697 StoreInst *SI = dyn_cast<StoreInst>(Instr); 1698 1699 assert((LI || SI) && "Invalid Load/Store instruction"); 1700 1701 Type *ScalarDataTy = LI ? LI->getType() : SI->getValueOperand()->getType(); 1702 Type *DataTy = VectorType::get(ScalarDataTy, VF); 1703 Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand(); 1704 unsigned Alignment = LI ? LI->getAlignment() : SI->getAlignment(); 1705 // An alignment of 0 means target abi alignment. We need to use the scalar's 1706 // target abi alignment in such a case. 1707 if (!Alignment) 1708 Alignment = DL->getABITypeAlignment(ScalarDataTy); 1709 unsigned AddressSpace = Ptr->getType()->getPointerAddressSpace(); 1710 unsigned ScalarAllocatedSize = DL->getTypeAllocSize(ScalarDataTy); 1711 unsigned VectorElementSize = DL->getTypeStoreSize(DataTy)/VF; 1712 1713 if (SI && Legal->blockNeedsPredication(SI->getParent()) && 1714 !Legal->isMaskRequired(SI)) 1715 return scalarizeInstruction(Instr, true); 1716 1717 if (ScalarAllocatedSize != VectorElementSize) 1718 return scalarizeInstruction(Instr); 1719 1720 // If the pointer is loop invariant or if it is non-consecutive, 1721 // scalarize the load. 1722 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr); 1723 bool Reverse = ConsecutiveStride < 0; 1724 bool UniformLoad = LI && Legal->isUniform(Ptr); 1725 if (!ConsecutiveStride || UniformLoad) 1726 return scalarizeInstruction(Instr); 1727 1728 Constant *Zero = Builder.getInt32(0); 1729 VectorParts &Entry = WidenMap.get(Instr); 1730 1731 // Handle consecutive loads/stores. 1732 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr); 1733 if (Gep && Legal->isInductionVariable(Gep->getPointerOperand())) { 1734 setDebugLocFromInst(Builder, Gep); 1735 Value *PtrOperand = Gep->getPointerOperand(); 1736 Value *FirstBasePtr = getVectorValue(PtrOperand)[0]; 1737 FirstBasePtr = Builder.CreateExtractElement(FirstBasePtr, Zero); 1738 1739 // Create the new GEP with the new induction variable. 1740 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone()); 1741 Gep2->setOperand(0, FirstBasePtr); 1742 Gep2->setName("gep.indvar.base"); 1743 Ptr = Builder.Insert(Gep2); 1744 } else if (Gep) { 1745 setDebugLocFromInst(Builder, Gep); 1746 assert(SE->isLoopInvariant(SE->getSCEV(Gep->getPointerOperand()), 1747 OrigLoop) && "Base ptr must be invariant"); 1748 1749 // The last index does not have to be the induction. It can be 1750 // consecutive and be a function of the index. For example A[I+1]; 1751 unsigned NumOperands = Gep->getNumOperands(); 1752 unsigned InductionOperand = getGEPInductionOperand(DL, Gep); 1753 // Create the new GEP with the new induction variable. 1754 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone()); 1755 1756 for (unsigned i = 0; i < NumOperands; ++i) { 1757 Value *GepOperand = Gep->getOperand(i); 1758 Instruction *GepOperandInst = dyn_cast<Instruction>(GepOperand); 1759 1760 // Update last index or loop invariant instruction anchored in loop. 1761 if (i == InductionOperand || 1762 (GepOperandInst && OrigLoop->contains(GepOperandInst))) { 1763 assert((i == InductionOperand || 1764 SE->isLoopInvariant(SE->getSCEV(GepOperandInst), OrigLoop)) && 1765 "Must be last index or loop invariant"); 1766 1767 VectorParts &GEPParts = getVectorValue(GepOperand); 1768 Value *Index = GEPParts[0]; 1769 Index = Builder.CreateExtractElement(Index, Zero); 1770 Gep2->setOperand(i, Index); 1771 Gep2->setName("gep.indvar.idx"); 1772 } 1773 } 1774 Ptr = Builder.Insert(Gep2); 1775 } else { 1776 // Use the induction element ptr. 1777 assert(isa<PHINode>(Ptr) && "Invalid induction ptr"); 1778 setDebugLocFromInst(Builder, Ptr); 1779 VectorParts &PtrVal = getVectorValue(Ptr); 1780 Ptr = Builder.CreateExtractElement(PtrVal[0], Zero); 1781 } 1782 1783 VectorParts Mask = createBlockInMask(Instr->getParent()); 1784 // Handle Stores: 1785 if (SI) { 1786 assert(!Legal->isUniform(SI->getPointerOperand()) && 1787 "We do not allow storing to uniform addresses"); 1788 setDebugLocFromInst(Builder, SI); 1789 // We don't want to update the value in the map as it might be used in 1790 // another expression. So don't use a reference type for "StoredVal". 1791 VectorParts StoredVal = getVectorValue(SI->getValueOperand()); 1792 1793 for (unsigned Part = 0; Part < UF; ++Part) { 1794 // Calculate the pointer for the specific unroll-part. 1795 Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF)); 1796 1797 if (Reverse) { 1798 // If we store to reverse consecutive memory locations then we need 1799 // to reverse the order of elements in the stored value. 1800 StoredVal[Part] = reverseVector(StoredVal[Part]); 1801 // If the address is consecutive but reversed, then the 1802 // wide store needs to start at the last vector element. 1803 PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF)); 1804 PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF)); 1805 Mask[Part] = reverseVector(Mask[Part]); 1806 } 1807 1808 Value *VecPtr = Builder.CreateBitCast(PartPtr, 1809 DataTy->getPointerTo(AddressSpace)); 1810 1811 Instruction *NewSI; 1812 if (Legal->isMaskRequired(SI)) 1813 NewSI = Builder.CreateMaskedStore(StoredVal[Part], VecPtr, Alignment, 1814 Mask[Part]); 1815 else 1816 NewSI = Builder.CreateAlignedStore(StoredVal[Part], VecPtr, Alignment); 1817 propagateMetadata(NewSI, SI); 1818 } 1819 return; 1820 } 1821 1822 // Handle loads. 1823 assert(LI && "Must have a load instruction"); 1824 setDebugLocFromInst(Builder, LI); 1825 for (unsigned Part = 0; Part < UF; ++Part) { 1826 // Calculate the pointer for the specific unroll-part. 1827 Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF)); 1828 1829 if (Reverse) { 1830 // If the address is consecutive but reversed, then the 1831 // wide load needs to start at the last vector element. 1832 PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF)); 1833 PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF)); 1834 Mask[Part] = reverseVector(Mask[Part]); 1835 } 1836 1837 Instruction* NewLI; 1838 Value *VecPtr = Builder.CreateBitCast(PartPtr, 1839 DataTy->getPointerTo(AddressSpace)); 1840 if (Legal->isMaskRequired(LI)) 1841 NewLI = Builder.CreateMaskedLoad(VecPtr, Alignment, Mask[Part], 1842 UndefValue::get(DataTy), 1843 "wide.masked.load"); 1844 else 1845 NewLI = Builder.CreateAlignedLoad(VecPtr, Alignment, "wide.load"); 1846 propagateMetadata(NewLI, LI); 1847 Entry[Part] = Reverse ? reverseVector(NewLI) : NewLI; 1848 } 1849 } 1850 1851 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr, bool IfPredicateStore) { 1852 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors"); 1853 // Holds vector parameters or scalars, in case of uniform vals. 1854 SmallVector<VectorParts, 4> Params; 1855 1856 setDebugLocFromInst(Builder, Instr); 1857 1858 // Find all of the vectorized parameters. 1859 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) { 1860 Value *SrcOp = Instr->getOperand(op); 1861 1862 // If we are accessing the old induction variable, use the new one. 1863 if (SrcOp == OldInduction) { 1864 Params.push_back(getVectorValue(SrcOp)); 1865 continue; 1866 } 1867 1868 // Try using previously calculated values. 1869 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp); 1870 1871 // If the src is an instruction that appeared earlier in the basic block 1872 // then it should already be vectorized. 1873 if (SrcInst && OrigLoop->contains(SrcInst)) { 1874 assert(WidenMap.has(SrcInst) && "Source operand is unavailable"); 1875 // The parameter is a vector value from earlier. 1876 Params.push_back(WidenMap.get(SrcInst)); 1877 } else { 1878 // The parameter is a scalar from outside the loop. Maybe even a constant. 1879 VectorParts Scalars; 1880 Scalars.append(UF, SrcOp); 1881 Params.push_back(Scalars); 1882 } 1883 } 1884 1885 assert(Params.size() == Instr->getNumOperands() && 1886 "Invalid number of operands"); 1887 1888 // Does this instruction return a value ? 1889 bool IsVoidRetTy = Instr->getType()->isVoidTy(); 1890 1891 Value *UndefVec = IsVoidRetTy ? nullptr : 1892 UndefValue::get(VectorType::get(Instr->getType(), VF)); 1893 // Create a new entry in the WidenMap and initialize it to Undef or Null. 1894 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec); 1895 1896 Instruction *InsertPt = Builder.GetInsertPoint(); 1897 BasicBlock *IfBlock = Builder.GetInsertBlock(); 1898 BasicBlock *CondBlock = nullptr; 1899 1900 VectorParts Cond; 1901 Loop *VectorLp = nullptr; 1902 if (IfPredicateStore) { 1903 assert(Instr->getParent()->getSinglePredecessor() && 1904 "Only support single predecessor blocks"); 1905 Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(), 1906 Instr->getParent()); 1907 VectorLp = LI->getLoopFor(IfBlock); 1908 assert(VectorLp && "Must have a loop for this block"); 1909 } 1910 1911 // For each vector unroll 'part': 1912 for (unsigned Part = 0; Part < UF; ++Part) { 1913 // For each scalar that we create: 1914 for (unsigned Width = 0; Width < VF; ++Width) { 1915 1916 // Start if-block. 1917 Value *Cmp = nullptr; 1918 if (IfPredicateStore) { 1919 Cmp = Builder.CreateExtractElement(Cond[Part], Builder.getInt32(Width)); 1920 Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cmp, ConstantInt::get(Cmp->getType(), 1)); 1921 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store"); 1922 LoopVectorBody.push_back(CondBlock); 1923 VectorLp->addBasicBlockToLoop(CondBlock, *LI); 1924 // Update Builder with newly created basic block. 1925 Builder.SetInsertPoint(InsertPt); 1926 } 1927 1928 Instruction *Cloned = Instr->clone(); 1929 if (!IsVoidRetTy) 1930 Cloned->setName(Instr->getName() + ".cloned"); 1931 // Replace the operands of the cloned instructions with extracted scalars. 1932 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) { 1933 Value *Op = Params[op][Part]; 1934 // Param is a vector. Need to extract the right lane. 1935 if (Op->getType()->isVectorTy()) 1936 Op = Builder.CreateExtractElement(Op, Builder.getInt32(Width)); 1937 Cloned->setOperand(op, Op); 1938 } 1939 1940 // Place the cloned scalar in the new loop. 1941 Builder.Insert(Cloned); 1942 1943 // If the original scalar returns a value we need to place it in a vector 1944 // so that future users will be able to use it. 1945 if (!IsVoidRetTy) 1946 VecResults[Part] = Builder.CreateInsertElement(VecResults[Part], Cloned, 1947 Builder.getInt32(Width)); 1948 // End if-block. 1949 if (IfPredicateStore) { 1950 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else"); 1951 LoopVectorBody.push_back(NewIfBlock); 1952 VectorLp->addBasicBlockToLoop(NewIfBlock, *LI); 1953 Builder.SetInsertPoint(InsertPt); 1954 Instruction *OldBr = IfBlock->getTerminator(); 1955 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr); 1956 OldBr->eraseFromParent(); 1957 IfBlock = NewIfBlock; 1958 } 1959 } 1960 } 1961 } 1962 1963 static Instruction *getFirstInst(Instruction *FirstInst, Value *V, 1964 Instruction *Loc) { 1965 if (FirstInst) 1966 return FirstInst; 1967 if (Instruction *I = dyn_cast<Instruction>(V)) 1968 return I->getParent() == Loc->getParent() ? I : nullptr; 1969 return nullptr; 1970 } 1971 1972 std::pair<Instruction *, Instruction *> 1973 InnerLoopVectorizer::addStrideCheck(Instruction *Loc) { 1974 Instruction *tnullptr = nullptr; 1975 if (!Legal->mustCheckStrides()) 1976 return std::pair<Instruction *, Instruction *>(tnullptr, tnullptr); 1977 1978 IRBuilder<> ChkBuilder(Loc); 1979 1980 // Emit checks. 1981 Value *Check = nullptr; 1982 Instruction *FirstInst = nullptr; 1983 for (SmallPtrSet<Value *, 8>::iterator SI = Legal->strides_begin(), 1984 SE = Legal->strides_end(); 1985 SI != SE; ++SI) { 1986 Value *Ptr = stripIntegerCast(*SI); 1987 Value *C = ChkBuilder.CreateICmpNE(Ptr, ConstantInt::get(Ptr->getType(), 1), 1988 "stride.chk"); 1989 // Store the first instruction we create. 1990 FirstInst = getFirstInst(FirstInst, C, Loc); 1991 if (Check) 1992 Check = ChkBuilder.CreateOr(Check, C); 1993 else 1994 Check = C; 1995 } 1996 1997 // We have to do this trickery because the IRBuilder might fold the check to a 1998 // constant expression in which case there is no Instruction anchored in a 1999 // the block. 2000 LLVMContext &Ctx = Loc->getContext(); 2001 Instruction *TheCheck = 2002 BinaryOperator::CreateAnd(Check, ConstantInt::getTrue(Ctx)); 2003 ChkBuilder.Insert(TheCheck, "stride.not.one"); 2004 FirstInst = getFirstInst(FirstInst, TheCheck, Loc); 2005 2006 return std::make_pair(FirstInst, TheCheck); 2007 } 2008 2009 void InnerLoopVectorizer::createEmptyLoop() { 2010 /* 2011 In this function we generate a new loop. The new loop will contain 2012 the vectorized instructions while the old loop will continue to run the 2013 scalar remainder. 2014 2015 [ ] <-- Back-edge taken count overflow check. 2016 / | 2017 / v 2018 | [ ] <-- vector loop bypass (may consist of multiple blocks). 2019 | / | 2020 | / v 2021 || [ ] <-- vector pre header. 2022 || | 2023 || v 2024 || [ ] \ 2025 || [ ]_| <-- vector loop. 2026 || | 2027 | \ v 2028 | >[ ] <--- middle-block. 2029 | / | 2030 | / v 2031 -|- >[ ] <--- new preheader. 2032 | | 2033 | v 2034 | [ ] \ 2035 | [ ]_| <-- old scalar loop to handle remainder. 2036 \ | 2037 \ v 2038 >[ ] <-- exit block. 2039 ... 2040 */ 2041 2042 BasicBlock *OldBasicBlock = OrigLoop->getHeader(); 2043 BasicBlock *BypassBlock = OrigLoop->getLoopPreheader(); 2044 BasicBlock *ExitBlock = OrigLoop->getExitBlock(); 2045 assert(BypassBlock && "Invalid loop structure"); 2046 assert(ExitBlock && "Must have an exit block"); 2047 2048 // Some loops have a single integer induction variable, while other loops 2049 // don't. One example is c++ iterators that often have multiple pointer 2050 // induction variables. In the code below we also support a case where we 2051 // don't have a single induction variable. 2052 OldInduction = Legal->getInduction(); 2053 Type *IdxTy = Legal->getWidestInductionType(); 2054 2055 // Find the loop boundaries. 2056 const SCEV *ExitCount = SE->getBackedgeTakenCount(OrigLoop); 2057 assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count"); 2058 2059 // The exit count might have the type of i64 while the phi is i32. This can 2060 // happen if we have an induction variable that is sign extended before the 2061 // compare. The only way that we get a backedge taken count is that the 2062 // induction variable was signed and as such will not overflow. In such a case 2063 // truncation is legal. 2064 if (ExitCount->getType()->getPrimitiveSizeInBits() > 2065 IdxTy->getPrimitiveSizeInBits()) 2066 ExitCount = SE->getTruncateOrNoop(ExitCount, IdxTy); 2067 2068 const SCEV *BackedgeTakeCount = SE->getNoopOrZeroExtend(ExitCount, IdxTy); 2069 // Get the total trip count from the count by adding 1. 2070 ExitCount = SE->getAddExpr(BackedgeTakeCount, 2071 SE->getConstant(BackedgeTakeCount->getType(), 1)); 2072 2073 // Expand the trip count and place the new instructions in the preheader. 2074 // Notice that the pre-header does not change, only the loop body. 2075 SCEVExpander Exp(*SE, "induction"); 2076 2077 // We need to test whether the backedge-taken count is uint##_max. Adding one 2078 // to it will cause overflow and an incorrect loop trip count in the vector 2079 // body. In case of overflow we want to directly jump to the scalar remainder 2080 // loop. 2081 Value *BackedgeCount = 2082 Exp.expandCodeFor(BackedgeTakeCount, BackedgeTakeCount->getType(), 2083 BypassBlock->getTerminator()); 2084 if (BackedgeCount->getType()->isPointerTy()) 2085 BackedgeCount = CastInst::CreatePointerCast(BackedgeCount, IdxTy, 2086 "backedge.ptrcnt.to.int", 2087 BypassBlock->getTerminator()); 2088 Instruction *CheckBCOverflow = 2089 CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, BackedgeCount, 2090 Constant::getAllOnesValue(BackedgeCount->getType()), 2091 "backedge.overflow", BypassBlock->getTerminator()); 2092 2093 // The loop index does not have to start at Zero. Find the original start 2094 // value from the induction PHI node. If we don't have an induction variable 2095 // then we know that it starts at zero. 2096 Builder.SetInsertPoint(BypassBlock->getTerminator()); 2097 Value *StartIdx = ExtendedIdx = OldInduction ? 2098 Builder.CreateZExt(OldInduction->getIncomingValueForBlock(BypassBlock), 2099 IdxTy): 2100 ConstantInt::get(IdxTy, 0); 2101 2102 // We need an instruction to anchor the overflow check on. StartIdx needs to 2103 // be defined before the overflow check branch. Because the scalar preheader 2104 // is going to merge the start index and so the overflow branch block needs to 2105 // contain a definition of the start index. 2106 Instruction *OverflowCheckAnchor = BinaryOperator::CreateAdd( 2107 StartIdx, ConstantInt::get(IdxTy, 0), "overflow.check.anchor", 2108 BypassBlock->getTerminator()); 2109 2110 // Count holds the overall loop count (N). 2111 Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(), 2112 BypassBlock->getTerminator()); 2113 2114 LoopBypassBlocks.push_back(BypassBlock); 2115 2116 // Split the single block loop into the two loop structure described above. 2117 BasicBlock *VectorPH = 2118 BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph"); 2119 BasicBlock *VecBody = 2120 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body"); 2121 BasicBlock *MiddleBlock = 2122 VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block"); 2123 BasicBlock *ScalarPH = 2124 MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph"); 2125 2126 // Create and register the new vector loop. 2127 Loop* Lp = new Loop(); 2128 Loop *ParentLoop = OrigLoop->getParentLoop(); 2129 2130 // Insert the new loop into the loop nest and register the new basic blocks 2131 // before calling any utilities such as SCEV that require valid LoopInfo. 2132 if (ParentLoop) { 2133 ParentLoop->addChildLoop(Lp); 2134 ParentLoop->addBasicBlockToLoop(ScalarPH, *LI); 2135 ParentLoop->addBasicBlockToLoop(VectorPH, *LI); 2136 ParentLoop->addBasicBlockToLoop(MiddleBlock, *LI); 2137 } else { 2138 LI->addTopLevelLoop(Lp); 2139 } 2140 Lp->addBasicBlockToLoop(VecBody, *LI); 2141 2142 // Use this IR builder to create the loop instructions (Phi, Br, Cmp) 2143 // inside the loop. 2144 Builder.SetInsertPoint(VecBody->getFirstNonPHI()); 2145 2146 // Generate the induction variable. 2147 setDebugLocFromInst(Builder, getDebugLocFromInstOrOperands(OldInduction)); 2148 Induction = Builder.CreatePHI(IdxTy, 2, "index"); 2149 // The loop step is equal to the vectorization factor (num of SIMD elements) 2150 // times the unroll factor (num of SIMD instructions). 2151 Constant *Step = ConstantInt::get(IdxTy, VF * UF); 2152 2153 // This is the IR builder that we use to add all of the logic for bypassing 2154 // the new vector loop. 2155 IRBuilder<> BypassBuilder(BypassBlock->getTerminator()); 2156 setDebugLocFromInst(BypassBuilder, 2157 getDebugLocFromInstOrOperands(OldInduction)); 2158 2159 // We may need to extend the index in case there is a type mismatch. 2160 // We know that the count starts at zero and does not overflow. 2161 if (Count->getType() != IdxTy) { 2162 // The exit count can be of pointer type. Convert it to the correct 2163 // integer type. 2164 if (ExitCount->getType()->isPointerTy()) 2165 Count = BypassBuilder.CreatePointerCast(Count, IdxTy, "ptrcnt.to.int"); 2166 else 2167 Count = BypassBuilder.CreateZExtOrTrunc(Count, IdxTy, "cnt.cast"); 2168 } 2169 2170 // Add the start index to the loop count to get the new end index. 2171 Value *IdxEnd = BypassBuilder.CreateAdd(Count, StartIdx, "end.idx"); 2172 2173 // Now we need to generate the expression for N - (N % VF), which is 2174 // the part that the vectorized body will execute. 2175 Value *R = BypassBuilder.CreateURem(Count, Step, "n.mod.vf"); 2176 Value *CountRoundDown = BypassBuilder.CreateSub(Count, R, "n.vec"); 2177 Value *IdxEndRoundDown = BypassBuilder.CreateAdd(CountRoundDown, StartIdx, 2178 "end.idx.rnd.down"); 2179 2180 // Now, compare the new count to zero. If it is zero skip the vector loop and 2181 // jump to the scalar loop. 2182 Value *Cmp = 2183 BypassBuilder.CreateICmpEQ(IdxEndRoundDown, StartIdx, "cmp.zero"); 2184 2185 BasicBlock *LastBypassBlock = BypassBlock; 2186 2187 // Generate code to check that the loops trip count that we computed by adding 2188 // one to the backedge-taken count will not overflow. 2189 { 2190 auto PastOverflowCheck = 2191 std::next(BasicBlock::iterator(OverflowCheckAnchor)); 2192 BasicBlock *CheckBlock = 2193 LastBypassBlock->splitBasicBlock(PastOverflowCheck, "overflow.checked"); 2194 if (ParentLoop) 2195 ParentLoop->addBasicBlockToLoop(CheckBlock, *LI); 2196 LoopBypassBlocks.push_back(CheckBlock); 2197 Instruction *OldTerm = LastBypassBlock->getTerminator(); 2198 BranchInst::Create(ScalarPH, CheckBlock, CheckBCOverflow, OldTerm); 2199 OldTerm->eraseFromParent(); 2200 LastBypassBlock = CheckBlock; 2201 } 2202 2203 // Generate the code to check that the strides we assumed to be one are really 2204 // one. We want the new basic block to start at the first instruction in a 2205 // sequence of instructions that form a check. 2206 Instruction *StrideCheck; 2207 Instruction *FirstCheckInst; 2208 std::tie(FirstCheckInst, StrideCheck) = 2209 addStrideCheck(LastBypassBlock->getTerminator()); 2210 if (StrideCheck) { 2211 // Create a new block containing the stride check. 2212 BasicBlock *CheckBlock = 2213 LastBypassBlock->splitBasicBlock(FirstCheckInst, "vector.stridecheck"); 2214 if (ParentLoop) 2215 ParentLoop->addBasicBlockToLoop(CheckBlock, *LI); 2216 LoopBypassBlocks.push_back(CheckBlock); 2217 2218 // Replace the branch into the memory check block with a conditional branch 2219 // for the "few elements case". 2220 Instruction *OldTerm = LastBypassBlock->getTerminator(); 2221 BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm); 2222 OldTerm->eraseFromParent(); 2223 2224 Cmp = StrideCheck; 2225 LastBypassBlock = CheckBlock; 2226 } 2227 2228 // Generate the code that checks in runtime if arrays overlap. We put the 2229 // checks into a separate block to make the more common case of few elements 2230 // faster. 2231 Instruction *MemRuntimeCheck; 2232 std::tie(FirstCheckInst, MemRuntimeCheck) = 2233 Legal->getLAA()->addRuntimeCheck(LastBypassBlock->getTerminator()); 2234 if (MemRuntimeCheck) { 2235 // Create a new block containing the memory check. 2236 BasicBlock *CheckBlock = 2237 LastBypassBlock->splitBasicBlock(FirstCheckInst, "vector.memcheck"); 2238 if (ParentLoop) 2239 ParentLoop->addBasicBlockToLoop(CheckBlock, *LI); 2240 LoopBypassBlocks.push_back(CheckBlock); 2241 2242 // Replace the branch into the memory check block with a conditional branch 2243 // for the "few elements case". 2244 Instruction *OldTerm = LastBypassBlock->getTerminator(); 2245 BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm); 2246 OldTerm->eraseFromParent(); 2247 2248 Cmp = MemRuntimeCheck; 2249 LastBypassBlock = CheckBlock; 2250 } 2251 2252 LastBypassBlock->getTerminator()->eraseFromParent(); 2253 BranchInst::Create(MiddleBlock, VectorPH, Cmp, 2254 LastBypassBlock); 2255 2256 // We are going to resume the execution of the scalar loop. 2257 // Go over all of the induction variables that we found and fix the 2258 // PHIs that are left in the scalar version of the loop. 2259 // The starting values of PHI nodes depend on the counter of the last 2260 // iteration in the vectorized loop. 2261 // If we come from a bypass edge then we need to start from the original 2262 // start value. 2263 2264 // This variable saves the new starting index for the scalar loop. 2265 PHINode *ResumeIndex = nullptr; 2266 LoopVectorizationLegality::InductionList::iterator I, E; 2267 LoopVectorizationLegality::InductionList *List = Legal->getInductionVars(); 2268 // Set builder to point to last bypass block. 2269 BypassBuilder.SetInsertPoint(LoopBypassBlocks.back()->getTerminator()); 2270 for (I = List->begin(), E = List->end(); I != E; ++I) { 2271 PHINode *OrigPhi = I->first; 2272 LoopVectorizationLegality::InductionInfo II = I->second; 2273 2274 Type *ResumeValTy = (OrigPhi == OldInduction) ? IdxTy : OrigPhi->getType(); 2275 PHINode *ResumeVal = PHINode::Create(ResumeValTy, 2, "resume.val", 2276 MiddleBlock->getTerminator()); 2277 // We might have extended the type of the induction variable but we need a 2278 // truncated version for the scalar loop. 2279 PHINode *TruncResumeVal = (OrigPhi == OldInduction) ? 2280 PHINode::Create(OrigPhi->getType(), 2, "trunc.resume.val", 2281 MiddleBlock->getTerminator()) : nullptr; 2282 2283 // Create phi nodes to merge from the backedge-taken check block. 2284 PHINode *BCResumeVal = PHINode::Create(ResumeValTy, 3, "bc.resume.val", 2285 ScalarPH->getTerminator()); 2286 BCResumeVal->addIncoming(ResumeVal, MiddleBlock); 2287 2288 PHINode *BCTruncResumeVal = nullptr; 2289 if (OrigPhi == OldInduction) { 2290 BCTruncResumeVal = 2291 PHINode::Create(OrigPhi->getType(), 2, "bc.trunc.resume.val", 2292 ScalarPH->getTerminator()); 2293 BCTruncResumeVal->addIncoming(TruncResumeVal, MiddleBlock); 2294 } 2295 2296 Value *EndValue = nullptr; 2297 switch (II.IK) { 2298 case LoopVectorizationLegality::IK_NoInduction: 2299 llvm_unreachable("Unknown induction"); 2300 case LoopVectorizationLegality::IK_IntInduction: { 2301 // Handle the integer induction counter. 2302 assert(OrigPhi->getType()->isIntegerTy() && "Invalid type"); 2303 2304 // We have the canonical induction variable. 2305 if (OrigPhi == OldInduction) { 2306 // Create a truncated version of the resume value for the scalar loop, 2307 // we might have promoted the type to a larger width. 2308 EndValue = 2309 BypassBuilder.CreateTrunc(IdxEndRoundDown, OrigPhi->getType()); 2310 // The new PHI merges the original incoming value, in case of a bypass, 2311 // or the value at the end of the vectorized loop. 2312 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I) 2313 TruncResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]); 2314 TruncResumeVal->addIncoming(EndValue, VecBody); 2315 2316 BCTruncResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[0]); 2317 2318 // We know what the end value is. 2319 EndValue = IdxEndRoundDown; 2320 // We also know which PHI node holds it. 2321 ResumeIndex = ResumeVal; 2322 break; 2323 } 2324 2325 // Not the canonical induction variable - add the vector loop count to the 2326 // start value. 2327 Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown, 2328 II.StartValue->getType(), 2329 "cast.crd"); 2330 EndValue = II.transform(BypassBuilder, CRD); 2331 EndValue->setName("ind.end"); 2332 break; 2333 } 2334 case LoopVectorizationLegality::IK_PtrInduction: { 2335 EndValue = II.transform(BypassBuilder, CountRoundDown); 2336 EndValue->setName("ptr.ind.end"); 2337 break; 2338 } 2339 }// end of case 2340 2341 // The new PHI merges the original incoming value, in case of a bypass, 2342 // or the value at the end of the vectorized loop. 2343 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I) { 2344 if (OrigPhi == OldInduction) 2345 ResumeVal->addIncoming(StartIdx, LoopBypassBlocks[I]); 2346 else 2347 ResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]); 2348 } 2349 ResumeVal->addIncoming(EndValue, VecBody); 2350 2351 // Fix the scalar body counter (PHI node). 2352 unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH); 2353 2354 // The old induction's phi node in the scalar body needs the truncated 2355 // value. 2356 if (OrigPhi == OldInduction) { 2357 BCResumeVal->addIncoming(StartIdx, LoopBypassBlocks[0]); 2358 OrigPhi->setIncomingValue(BlockIdx, BCTruncResumeVal); 2359 } else { 2360 BCResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[0]); 2361 OrigPhi->setIncomingValue(BlockIdx, BCResumeVal); 2362 } 2363 } 2364 2365 // If we are generating a new induction variable then we also need to 2366 // generate the code that calculates the exit value. This value is not 2367 // simply the end of the counter because we may skip the vectorized body 2368 // in case of a runtime check. 2369 if (!OldInduction){ 2370 assert(!ResumeIndex && "Unexpected resume value found"); 2371 ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val", 2372 MiddleBlock->getTerminator()); 2373 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I) 2374 ResumeIndex->addIncoming(StartIdx, LoopBypassBlocks[I]); 2375 ResumeIndex->addIncoming(IdxEndRoundDown, VecBody); 2376 } 2377 2378 // Make sure that we found the index where scalar loop needs to continue. 2379 assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() && 2380 "Invalid resume Index"); 2381 2382 // Add a check in the middle block to see if we have completed 2383 // all of the iterations in the first vector loop. 2384 // If (N - N%VF) == N, then we *don't* need to run the remainder. 2385 Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd, 2386 ResumeIndex, "cmp.n", 2387 MiddleBlock->getTerminator()); 2388 2389 BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator()); 2390 // Remove the old terminator. 2391 MiddleBlock->getTerminator()->eraseFromParent(); 2392 2393 // Create i+1 and fill the PHINode. 2394 Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next"); 2395 Induction->addIncoming(StartIdx, VectorPH); 2396 Induction->addIncoming(NextIdx, VecBody); 2397 // Create the compare. 2398 Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown); 2399 Builder.CreateCondBr(ICmp, MiddleBlock, VecBody); 2400 2401 // Now we have two terminators. Remove the old one from the block. 2402 VecBody->getTerminator()->eraseFromParent(); 2403 2404 // Get ready to start creating new instructions into the vectorized body. 2405 Builder.SetInsertPoint(VecBody->getFirstInsertionPt()); 2406 2407 // Save the state. 2408 LoopVectorPreHeader = VectorPH; 2409 LoopScalarPreHeader = ScalarPH; 2410 LoopMiddleBlock = MiddleBlock; 2411 LoopExitBlock = ExitBlock; 2412 LoopVectorBody.push_back(VecBody); 2413 LoopScalarBody = OldBasicBlock; 2414 2415 LoopVectorizeHints Hints(Lp, true); 2416 Hints.setAlreadyVectorized(); 2417 } 2418 2419 /// This function returns the identity element (or neutral element) for 2420 /// the operation K. 2421 Constant* 2422 LoopVectorizationLegality::getReductionIdentity(ReductionKind K, Type *Tp) { 2423 switch (K) { 2424 case RK_IntegerXor: 2425 case RK_IntegerAdd: 2426 case RK_IntegerOr: 2427 // Adding, Xoring, Oring zero to a number does not change it. 2428 return ConstantInt::get(Tp, 0); 2429 case RK_IntegerMult: 2430 // Multiplying a number by 1 does not change it. 2431 return ConstantInt::get(Tp, 1); 2432 case RK_IntegerAnd: 2433 // AND-ing a number with an all-1 value does not change it. 2434 return ConstantInt::get(Tp, -1, true); 2435 case RK_FloatMult: 2436 // Multiplying a number by 1 does not change it. 2437 return ConstantFP::get(Tp, 1.0L); 2438 case RK_FloatAdd: 2439 // Adding zero to a number does not change it. 2440 return ConstantFP::get(Tp, 0.0L); 2441 default: 2442 llvm_unreachable("Unknown reduction kind"); 2443 } 2444 } 2445 2446 /// This function translates the reduction kind to an LLVM binary operator. 2447 static unsigned 2448 getReductionBinOp(LoopVectorizationLegality::ReductionKind Kind) { 2449 switch (Kind) { 2450 case LoopVectorizationLegality::RK_IntegerAdd: 2451 return Instruction::Add; 2452 case LoopVectorizationLegality::RK_IntegerMult: 2453 return Instruction::Mul; 2454 case LoopVectorizationLegality::RK_IntegerOr: 2455 return Instruction::Or; 2456 case LoopVectorizationLegality::RK_IntegerAnd: 2457 return Instruction::And; 2458 case LoopVectorizationLegality::RK_IntegerXor: 2459 return Instruction::Xor; 2460 case LoopVectorizationLegality::RK_FloatMult: 2461 return Instruction::FMul; 2462 case LoopVectorizationLegality::RK_FloatAdd: 2463 return Instruction::FAdd; 2464 case LoopVectorizationLegality::RK_IntegerMinMax: 2465 return Instruction::ICmp; 2466 case LoopVectorizationLegality::RK_FloatMinMax: 2467 return Instruction::FCmp; 2468 default: 2469 llvm_unreachable("Unknown reduction operation"); 2470 } 2471 } 2472 2473 Value *createMinMaxOp(IRBuilder<> &Builder, 2474 LoopVectorizationLegality::MinMaxReductionKind RK, 2475 Value *Left, 2476 Value *Right) { 2477 CmpInst::Predicate P = CmpInst::ICMP_NE; 2478 switch (RK) { 2479 default: 2480 llvm_unreachable("Unknown min/max reduction kind"); 2481 case LoopVectorizationLegality::MRK_UIntMin: 2482 P = CmpInst::ICMP_ULT; 2483 break; 2484 case LoopVectorizationLegality::MRK_UIntMax: 2485 P = CmpInst::ICMP_UGT; 2486 break; 2487 case LoopVectorizationLegality::MRK_SIntMin: 2488 P = CmpInst::ICMP_SLT; 2489 break; 2490 case LoopVectorizationLegality::MRK_SIntMax: 2491 P = CmpInst::ICMP_SGT; 2492 break; 2493 case LoopVectorizationLegality::MRK_FloatMin: 2494 P = CmpInst::FCMP_OLT; 2495 break; 2496 case LoopVectorizationLegality::MRK_FloatMax: 2497 P = CmpInst::FCMP_OGT; 2498 break; 2499 } 2500 2501 Value *Cmp; 2502 if (RK == LoopVectorizationLegality::MRK_FloatMin || 2503 RK == LoopVectorizationLegality::MRK_FloatMax) 2504 Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp"); 2505 else 2506 Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp"); 2507 2508 Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select"); 2509 return Select; 2510 } 2511 2512 namespace { 2513 struct CSEDenseMapInfo { 2514 static bool canHandle(Instruction *I) { 2515 return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) || 2516 isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I); 2517 } 2518 static inline Instruction *getEmptyKey() { 2519 return DenseMapInfo<Instruction *>::getEmptyKey(); 2520 } 2521 static inline Instruction *getTombstoneKey() { 2522 return DenseMapInfo<Instruction *>::getTombstoneKey(); 2523 } 2524 static unsigned getHashValue(Instruction *I) { 2525 assert(canHandle(I) && "Unknown instruction!"); 2526 return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(), 2527 I->value_op_end())); 2528 } 2529 static bool isEqual(Instruction *LHS, Instruction *RHS) { 2530 if (LHS == getEmptyKey() || RHS == getEmptyKey() || 2531 LHS == getTombstoneKey() || RHS == getTombstoneKey()) 2532 return LHS == RHS; 2533 return LHS->isIdenticalTo(RHS); 2534 } 2535 }; 2536 } 2537 2538 /// \brief Check whether this block is a predicated block. 2539 /// Due to if predication of stores we might create a sequence of "if(pred) a[i] 2540 /// = ...; " blocks. We start with one vectorized basic block. For every 2541 /// conditional block we split this vectorized block. Therefore, every second 2542 /// block will be a predicated one. 2543 static bool isPredicatedBlock(unsigned BlockNum) { 2544 return BlockNum % 2; 2545 } 2546 2547 ///\brief Perform cse of induction variable instructions. 2548 static void cse(SmallVector<BasicBlock *, 4> &BBs) { 2549 // Perform simple cse. 2550 SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap; 2551 for (unsigned i = 0, e = BBs.size(); i != e; ++i) { 2552 BasicBlock *BB = BBs[i]; 2553 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) { 2554 Instruction *In = I++; 2555 2556 if (!CSEDenseMapInfo::canHandle(In)) 2557 continue; 2558 2559 // Check if we can replace this instruction with any of the 2560 // visited instructions. 2561 if (Instruction *V = CSEMap.lookup(In)) { 2562 In->replaceAllUsesWith(V); 2563 In->eraseFromParent(); 2564 continue; 2565 } 2566 // Ignore instructions in conditional blocks. We create "if (pred) a[i] = 2567 // ...;" blocks for predicated stores. Every second block is a predicated 2568 // block. 2569 if (isPredicatedBlock(i)) 2570 continue; 2571 2572 CSEMap[In] = In; 2573 } 2574 } 2575 } 2576 2577 /// \brief Adds a 'fast' flag to floating point operations. 2578 static Value *addFastMathFlag(Value *V) { 2579 if (isa<FPMathOperator>(V)){ 2580 FastMathFlags Flags; 2581 Flags.setUnsafeAlgebra(); 2582 cast<Instruction>(V)->setFastMathFlags(Flags); 2583 } 2584 return V; 2585 } 2586 2587 void InnerLoopVectorizer::vectorizeLoop() { 2588 //===------------------------------------------------===// 2589 // 2590 // Notice: any optimization or new instruction that go 2591 // into the code below should be also be implemented in 2592 // the cost-model. 2593 // 2594 //===------------------------------------------------===// 2595 Constant *Zero = Builder.getInt32(0); 2596 2597 // In order to support reduction variables we need to be able to vectorize 2598 // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two 2599 // stages. First, we create a new vector PHI node with no incoming edges. 2600 // We use this value when we vectorize all of the instructions that use the 2601 // PHI. Next, after all of the instructions in the block are complete we 2602 // add the new incoming edges to the PHI. At this point all of the 2603 // instructions in the basic block are vectorized, so we can use them to 2604 // construct the PHI. 2605 PhiVector RdxPHIsToFix; 2606 2607 // Scan the loop in a topological order to ensure that defs are vectorized 2608 // before users. 2609 LoopBlocksDFS DFS(OrigLoop); 2610 DFS.perform(LI); 2611 2612 // Vectorize all of the blocks in the original loop. 2613 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(), 2614 be = DFS.endRPO(); bb != be; ++bb) 2615 vectorizeBlockInLoop(*bb, &RdxPHIsToFix); 2616 2617 // At this point every instruction in the original loop is widened to 2618 // a vector form. We are almost done. Now, we need to fix the PHI nodes 2619 // that we vectorized. The PHI nodes are currently empty because we did 2620 // not want to introduce cycles. Notice that the remaining PHI nodes 2621 // that we need to fix are reduction variables. 2622 2623 // Create the 'reduced' values for each of the induction vars. 2624 // The reduced values are the vector values that we scalarize and combine 2625 // after the loop is finished. 2626 for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end(); 2627 it != e; ++it) { 2628 PHINode *RdxPhi = *it; 2629 assert(RdxPhi && "Unable to recover vectorized PHI"); 2630 2631 // Find the reduction variable descriptor. 2632 assert(Legal->getReductionVars()->count(RdxPhi) && 2633 "Unable to find the reduction variable"); 2634 LoopVectorizationLegality::ReductionDescriptor RdxDesc = 2635 (*Legal->getReductionVars())[RdxPhi]; 2636 2637 setDebugLocFromInst(Builder, RdxDesc.StartValue); 2638 2639 // We need to generate a reduction vector from the incoming scalar. 2640 // To do so, we need to generate the 'identity' vector and override 2641 // one of the elements with the incoming scalar reduction. We need 2642 // to do it in the vector-loop preheader. 2643 Builder.SetInsertPoint(LoopBypassBlocks[1]->getTerminator()); 2644 2645 // This is the vector-clone of the value that leaves the loop. 2646 VectorParts &VectorExit = getVectorValue(RdxDesc.LoopExitInstr); 2647 Type *VecTy = VectorExit[0]->getType(); 2648 2649 // Find the reduction identity variable. Zero for addition, or, xor, 2650 // one for multiplication, -1 for And. 2651 Value *Identity; 2652 Value *VectorStart; 2653 if (RdxDesc.Kind == LoopVectorizationLegality::RK_IntegerMinMax || 2654 RdxDesc.Kind == LoopVectorizationLegality::RK_FloatMinMax) { 2655 // MinMax reduction have the start value as their identify. 2656 if (VF == 1) { 2657 VectorStart = Identity = RdxDesc.StartValue; 2658 } else { 2659 VectorStart = Identity = Builder.CreateVectorSplat(VF, 2660 RdxDesc.StartValue, 2661 "minmax.ident"); 2662 } 2663 } else { 2664 // Handle other reduction kinds: 2665 Constant *Iden = 2666 LoopVectorizationLegality::getReductionIdentity(RdxDesc.Kind, 2667 VecTy->getScalarType()); 2668 if (VF == 1) { 2669 Identity = Iden; 2670 // This vector is the Identity vector where the first element is the 2671 // incoming scalar reduction. 2672 VectorStart = RdxDesc.StartValue; 2673 } else { 2674 Identity = ConstantVector::getSplat(VF, Iden); 2675 2676 // This vector is the Identity vector where the first element is the 2677 // incoming scalar reduction. 2678 VectorStart = Builder.CreateInsertElement(Identity, 2679 RdxDesc.StartValue, Zero); 2680 } 2681 } 2682 2683 // Fix the vector-loop phi. 2684 2685 // Reductions do not have to start at zero. They can start with 2686 // any loop invariant values. 2687 VectorParts &VecRdxPhi = WidenMap.get(RdxPhi); 2688 BasicBlock *Latch = OrigLoop->getLoopLatch(); 2689 Value *LoopVal = RdxPhi->getIncomingValueForBlock(Latch); 2690 VectorParts &Val = getVectorValue(LoopVal); 2691 for (unsigned part = 0; part < UF; ++part) { 2692 // Make sure to add the reduction stat value only to the 2693 // first unroll part. 2694 Value *StartVal = (part == 0) ? VectorStart : Identity; 2695 cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal, 2696 LoopVectorPreHeader); 2697 cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part], 2698 LoopVectorBody.back()); 2699 } 2700 2701 // Before each round, move the insertion point right between 2702 // the PHIs and the values we are going to write. 2703 // This allows us to write both PHINodes and the extractelement 2704 // instructions. 2705 Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt()); 2706 2707 VectorParts RdxParts; 2708 setDebugLocFromInst(Builder, RdxDesc.LoopExitInstr); 2709 for (unsigned part = 0; part < UF; ++part) { 2710 // This PHINode contains the vectorized reduction variable, or 2711 // the initial value vector, if we bypass the vector loop. 2712 VectorParts &RdxExitVal = getVectorValue(RdxDesc.LoopExitInstr); 2713 PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi"); 2714 Value *StartVal = (part == 0) ? VectorStart : Identity; 2715 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I) 2716 NewPhi->addIncoming(StartVal, LoopBypassBlocks[I]); 2717 NewPhi->addIncoming(RdxExitVal[part], 2718 LoopVectorBody.back()); 2719 RdxParts.push_back(NewPhi); 2720 } 2721 2722 // Reduce all of the unrolled parts into a single vector. 2723 Value *ReducedPartRdx = RdxParts[0]; 2724 unsigned Op = getReductionBinOp(RdxDesc.Kind); 2725 setDebugLocFromInst(Builder, ReducedPartRdx); 2726 for (unsigned part = 1; part < UF; ++part) { 2727 if (Op != Instruction::ICmp && Op != Instruction::FCmp) 2728 // Floating point operations had to be 'fast' to enable the reduction. 2729 ReducedPartRdx = addFastMathFlag( 2730 Builder.CreateBinOp((Instruction::BinaryOps)Op, RdxParts[part], 2731 ReducedPartRdx, "bin.rdx")); 2732 else 2733 ReducedPartRdx = createMinMaxOp(Builder, RdxDesc.MinMaxKind, 2734 ReducedPartRdx, RdxParts[part]); 2735 } 2736 2737 if (VF > 1) { 2738 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles 2739 // and vector ops, reducing the set of values being computed by half each 2740 // round. 2741 assert(isPowerOf2_32(VF) && 2742 "Reduction emission only supported for pow2 vectors!"); 2743 Value *TmpVec = ReducedPartRdx; 2744 SmallVector<Constant*, 32> ShuffleMask(VF, nullptr); 2745 for (unsigned i = VF; i != 1; i >>= 1) { 2746 // Move the upper half of the vector to the lower half. 2747 for (unsigned j = 0; j != i/2; ++j) 2748 ShuffleMask[j] = Builder.getInt32(i/2 + j); 2749 2750 // Fill the rest of the mask with undef. 2751 std::fill(&ShuffleMask[i/2], ShuffleMask.end(), 2752 UndefValue::get(Builder.getInt32Ty())); 2753 2754 Value *Shuf = 2755 Builder.CreateShuffleVector(TmpVec, 2756 UndefValue::get(TmpVec->getType()), 2757 ConstantVector::get(ShuffleMask), 2758 "rdx.shuf"); 2759 2760 if (Op != Instruction::ICmp && Op != Instruction::FCmp) 2761 // Floating point operations had to be 'fast' to enable the reduction. 2762 TmpVec = addFastMathFlag(Builder.CreateBinOp( 2763 (Instruction::BinaryOps)Op, TmpVec, Shuf, "bin.rdx")); 2764 else 2765 TmpVec = createMinMaxOp(Builder, RdxDesc.MinMaxKind, TmpVec, Shuf); 2766 } 2767 2768 // The result is in the first element of the vector. 2769 ReducedPartRdx = Builder.CreateExtractElement(TmpVec, 2770 Builder.getInt32(0)); 2771 } 2772 2773 // Create a phi node that merges control-flow from the backedge-taken check 2774 // block and the middle block. 2775 PHINode *BCBlockPhi = PHINode::Create(RdxPhi->getType(), 2, "bc.merge.rdx", 2776 LoopScalarPreHeader->getTerminator()); 2777 BCBlockPhi->addIncoming(RdxDesc.StartValue, LoopBypassBlocks[0]); 2778 BCBlockPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock); 2779 2780 // Now, we need to fix the users of the reduction variable 2781 // inside and outside of the scalar remainder loop. 2782 // We know that the loop is in LCSSA form. We need to update the 2783 // PHI nodes in the exit blocks. 2784 for (BasicBlock::iterator LEI = LoopExitBlock->begin(), 2785 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) { 2786 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI); 2787 if (!LCSSAPhi) break; 2788 2789 // All PHINodes need to have a single entry edge, or two if 2790 // we already fixed them. 2791 assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI"); 2792 2793 // We found our reduction value exit-PHI. Update it with the 2794 // incoming bypass edge. 2795 if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) { 2796 // Add an edge coming from the bypass. 2797 LCSSAPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock); 2798 break; 2799 } 2800 }// end of the LCSSA phi scan. 2801 2802 // Fix the scalar loop reduction variable with the incoming reduction sum 2803 // from the vector body and from the backedge value. 2804 int IncomingEdgeBlockIdx = 2805 (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch()); 2806 assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index"); 2807 // Pick the other block. 2808 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1); 2809 (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi); 2810 (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr); 2811 }// end of for each redux variable. 2812 2813 fixLCSSAPHIs(); 2814 2815 // Remove redundant induction instructions. 2816 cse(LoopVectorBody); 2817 } 2818 2819 void InnerLoopVectorizer::fixLCSSAPHIs() { 2820 for (BasicBlock::iterator LEI = LoopExitBlock->begin(), 2821 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) { 2822 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI); 2823 if (!LCSSAPhi) break; 2824 if (LCSSAPhi->getNumIncomingValues() == 1) 2825 LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()), 2826 LoopMiddleBlock); 2827 } 2828 } 2829 2830 InnerLoopVectorizer::VectorParts 2831 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) { 2832 assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) && 2833 "Invalid edge"); 2834 2835 // Look for cached value. 2836 std::pair<BasicBlock*, BasicBlock*> Edge(Src, Dst); 2837 EdgeMaskCache::iterator ECEntryIt = MaskCache.find(Edge); 2838 if (ECEntryIt != MaskCache.end()) 2839 return ECEntryIt->second; 2840 2841 VectorParts SrcMask = createBlockInMask(Src); 2842 2843 // The terminator has to be a branch inst! 2844 BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator()); 2845 assert(BI && "Unexpected terminator found"); 2846 2847 if (BI->isConditional()) { 2848 VectorParts EdgeMask = getVectorValue(BI->getCondition()); 2849 2850 if (BI->getSuccessor(0) != Dst) 2851 for (unsigned part = 0; part < UF; ++part) 2852 EdgeMask[part] = Builder.CreateNot(EdgeMask[part]); 2853 2854 for (unsigned part = 0; part < UF; ++part) 2855 EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]); 2856 2857 MaskCache[Edge] = EdgeMask; 2858 return EdgeMask; 2859 } 2860 2861 MaskCache[Edge] = SrcMask; 2862 return SrcMask; 2863 } 2864 2865 InnerLoopVectorizer::VectorParts 2866 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) { 2867 assert(OrigLoop->contains(BB) && "Block is not a part of a loop"); 2868 2869 // Loop incoming mask is all-one. 2870 if (OrigLoop->getHeader() == BB) { 2871 Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1); 2872 return getVectorValue(C); 2873 } 2874 2875 // This is the block mask. We OR all incoming edges, and with zero. 2876 Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0); 2877 VectorParts BlockMask = getVectorValue(Zero); 2878 2879 // For each pred: 2880 for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) { 2881 VectorParts EM = createEdgeMask(*it, BB); 2882 for (unsigned part = 0; part < UF; ++part) 2883 BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]); 2884 } 2885 2886 return BlockMask; 2887 } 2888 2889 void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN, 2890 InnerLoopVectorizer::VectorParts &Entry, 2891 unsigned UF, unsigned VF, PhiVector *PV) { 2892 PHINode* P = cast<PHINode>(PN); 2893 // Handle reduction variables: 2894 if (Legal->getReductionVars()->count(P)) { 2895 for (unsigned part = 0; part < UF; ++part) { 2896 // This is phase one of vectorizing PHIs. 2897 Type *VecTy = (VF == 1) ? PN->getType() : 2898 VectorType::get(PN->getType(), VF); 2899 Entry[part] = PHINode::Create(VecTy, 2, "vec.phi", 2900 LoopVectorBody.back()-> getFirstInsertionPt()); 2901 } 2902 PV->push_back(P); 2903 return; 2904 } 2905 2906 setDebugLocFromInst(Builder, P); 2907 // Check for PHI nodes that are lowered to vector selects. 2908 if (P->getParent() != OrigLoop->getHeader()) { 2909 // We know that all PHIs in non-header blocks are converted into 2910 // selects, so we don't have to worry about the insertion order and we 2911 // can just use the builder. 2912 // At this point we generate the predication tree. There may be 2913 // duplications since this is a simple recursive scan, but future 2914 // optimizations will clean it up. 2915 2916 unsigned NumIncoming = P->getNumIncomingValues(); 2917 2918 // Generate a sequence of selects of the form: 2919 // SELECT(Mask3, In3, 2920 // SELECT(Mask2, In2, 2921 // ( ...))) 2922 for (unsigned In = 0; In < NumIncoming; In++) { 2923 VectorParts Cond = createEdgeMask(P->getIncomingBlock(In), 2924 P->getParent()); 2925 VectorParts &In0 = getVectorValue(P->getIncomingValue(In)); 2926 2927 for (unsigned part = 0; part < UF; ++part) { 2928 // We might have single edge PHIs (blocks) - use an identity 2929 // 'select' for the first PHI operand. 2930 if (In == 0) 2931 Entry[part] = Builder.CreateSelect(Cond[part], In0[part], 2932 In0[part]); 2933 else 2934 // Select between the current value and the previous incoming edge 2935 // based on the incoming mask. 2936 Entry[part] = Builder.CreateSelect(Cond[part], In0[part], 2937 Entry[part], "predphi"); 2938 } 2939 } 2940 return; 2941 } 2942 2943 // This PHINode must be an induction variable. 2944 // Make sure that we know about it. 2945 assert(Legal->getInductionVars()->count(P) && 2946 "Not an induction variable"); 2947 2948 LoopVectorizationLegality::InductionInfo II = 2949 Legal->getInductionVars()->lookup(P); 2950 2951 // FIXME: The newly created binary instructions should contain nsw/nuw flags, 2952 // which can be found from the original scalar operations. 2953 switch (II.IK) { 2954 case LoopVectorizationLegality::IK_NoInduction: 2955 llvm_unreachable("Unknown induction"); 2956 case LoopVectorizationLegality::IK_IntInduction: { 2957 assert(P->getType() == II.StartValue->getType() && "Types must match"); 2958 Type *PhiTy = P->getType(); 2959 Value *Broadcasted; 2960 if (P == OldInduction) { 2961 // Handle the canonical induction variable. We might have had to 2962 // extend the type. 2963 Broadcasted = Builder.CreateTrunc(Induction, PhiTy); 2964 } else { 2965 // Handle other induction variables that are now based on the 2966 // canonical one. 2967 Value *NormalizedIdx = Builder.CreateSub(Induction, ExtendedIdx, 2968 "normalized.idx"); 2969 NormalizedIdx = Builder.CreateSExtOrTrunc(NormalizedIdx, PhiTy); 2970 Broadcasted = II.transform(Builder, NormalizedIdx); 2971 Broadcasted->setName("offset.idx"); 2972 } 2973 Broadcasted = getBroadcastInstrs(Broadcasted); 2974 // After broadcasting the induction variable we need to make the vector 2975 // consecutive by adding 0, 1, 2, etc. 2976 for (unsigned part = 0; part < UF; ++part) 2977 Entry[part] = getStepVector(Broadcasted, VF * part, II.StepValue); 2978 return; 2979 } 2980 case LoopVectorizationLegality::IK_PtrInduction: 2981 // Handle the pointer induction variable case. 2982 assert(P->getType()->isPointerTy() && "Unexpected type."); 2983 // This is the normalized GEP that starts counting at zero. 2984 Value *NormalizedIdx = 2985 Builder.CreateSub(Induction, ExtendedIdx, "normalized.idx"); 2986 // This is the vector of results. Notice that we don't generate 2987 // vector geps because scalar geps result in better code. 2988 for (unsigned part = 0; part < UF; ++part) { 2989 if (VF == 1) { 2990 int EltIndex = part; 2991 Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex); 2992 Value *GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx); 2993 Value *SclrGep = II.transform(Builder, GlobalIdx); 2994 SclrGep->setName("next.gep"); 2995 Entry[part] = SclrGep; 2996 continue; 2997 } 2998 2999 Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF)); 3000 for (unsigned int i = 0; i < VF; ++i) { 3001 int EltIndex = i + part * VF; 3002 Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex); 3003 Value *GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx); 3004 Value *SclrGep = II.transform(Builder, GlobalIdx); 3005 SclrGep->setName("next.gep"); 3006 VecVal = Builder.CreateInsertElement(VecVal, SclrGep, 3007 Builder.getInt32(i), 3008 "insert.gep"); 3009 } 3010 Entry[part] = VecVal; 3011 } 3012 return; 3013 } 3014 } 3015 3016 void InnerLoopVectorizer::vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV) { 3017 // For each instruction in the old loop. 3018 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) { 3019 VectorParts &Entry = WidenMap.get(it); 3020 switch (it->getOpcode()) { 3021 case Instruction::Br: 3022 // Nothing to do for PHIs and BR, since we already took care of the 3023 // loop control flow instructions. 3024 continue; 3025 case Instruction::PHI: { 3026 // Vectorize PHINodes. 3027 widenPHIInstruction(it, Entry, UF, VF, PV); 3028 continue; 3029 }// End of PHI. 3030 3031 case Instruction::Add: 3032 case Instruction::FAdd: 3033 case Instruction::Sub: 3034 case Instruction::FSub: 3035 case Instruction::Mul: 3036 case Instruction::FMul: 3037 case Instruction::UDiv: 3038 case Instruction::SDiv: 3039 case Instruction::FDiv: 3040 case Instruction::URem: 3041 case Instruction::SRem: 3042 case Instruction::FRem: 3043 case Instruction::Shl: 3044 case Instruction::LShr: 3045 case Instruction::AShr: 3046 case Instruction::And: 3047 case Instruction::Or: 3048 case Instruction::Xor: { 3049 // Just widen binops. 3050 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it); 3051 setDebugLocFromInst(Builder, BinOp); 3052 VectorParts &A = getVectorValue(it->getOperand(0)); 3053 VectorParts &B = getVectorValue(it->getOperand(1)); 3054 3055 // Use this vector value for all users of the original instruction. 3056 for (unsigned Part = 0; Part < UF; ++Part) { 3057 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]); 3058 3059 if (BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V)) 3060 VecOp->copyIRFlags(BinOp); 3061 3062 Entry[Part] = V; 3063 } 3064 3065 propagateMetadata(Entry, it); 3066 break; 3067 } 3068 case Instruction::Select: { 3069 // Widen selects. 3070 // If the selector is loop invariant we can create a select 3071 // instruction with a scalar condition. Otherwise, use vector-select. 3072 bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)), 3073 OrigLoop); 3074 setDebugLocFromInst(Builder, it); 3075 3076 // The condition can be loop invariant but still defined inside the 3077 // loop. This means that we can't just use the original 'cond' value. 3078 // We have to take the 'vectorized' value and pick the first lane. 3079 // Instcombine will make this a no-op. 3080 VectorParts &Cond = getVectorValue(it->getOperand(0)); 3081 VectorParts &Op0 = getVectorValue(it->getOperand(1)); 3082 VectorParts &Op1 = getVectorValue(it->getOperand(2)); 3083 3084 Value *ScalarCond = (VF == 1) ? Cond[0] : 3085 Builder.CreateExtractElement(Cond[0], Builder.getInt32(0)); 3086 3087 for (unsigned Part = 0; Part < UF; ++Part) { 3088 Entry[Part] = Builder.CreateSelect( 3089 InvariantCond ? ScalarCond : Cond[Part], 3090 Op0[Part], 3091 Op1[Part]); 3092 } 3093 3094 propagateMetadata(Entry, it); 3095 break; 3096 } 3097 3098 case Instruction::ICmp: 3099 case Instruction::FCmp: { 3100 // Widen compares. Generate vector compares. 3101 bool FCmp = (it->getOpcode() == Instruction::FCmp); 3102 CmpInst *Cmp = dyn_cast<CmpInst>(it); 3103 setDebugLocFromInst(Builder, it); 3104 VectorParts &A = getVectorValue(it->getOperand(0)); 3105 VectorParts &B = getVectorValue(it->getOperand(1)); 3106 for (unsigned Part = 0; Part < UF; ++Part) { 3107 Value *C = nullptr; 3108 if (FCmp) 3109 C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]); 3110 else 3111 C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]); 3112 Entry[Part] = C; 3113 } 3114 3115 propagateMetadata(Entry, it); 3116 break; 3117 } 3118 3119 case Instruction::Store: 3120 case Instruction::Load: 3121 vectorizeMemoryInstruction(it); 3122 break; 3123 case Instruction::ZExt: 3124 case Instruction::SExt: 3125 case Instruction::FPToUI: 3126 case Instruction::FPToSI: 3127 case Instruction::FPExt: 3128 case Instruction::PtrToInt: 3129 case Instruction::IntToPtr: 3130 case Instruction::SIToFP: 3131 case Instruction::UIToFP: 3132 case Instruction::Trunc: 3133 case Instruction::FPTrunc: 3134 case Instruction::BitCast: { 3135 CastInst *CI = dyn_cast<CastInst>(it); 3136 setDebugLocFromInst(Builder, it); 3137 /// Optimize the special case where the source is the induction 3138 /// variable. Notice that we can only optimize the 'trunc' case 3139 /// because: a. FP conversions lose precision, b. sext/zext may wrap, 3140 /// c. other casts depend on pointer size. 3141 if (CI->getOperand(0) == OldInduction && 3142 it->getOpcode() == Instruction::Trunc) { 3143 Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction, 3144 CI->getType()); 3145 Value *Broadcasted = getBroadcastInstrs(ScalarCast); 3146 LoopVectorizationLegality::InductionInfo II = 3147 Legal->getInductionVars()->lookup(OldInduction); 3148 Constant *Step = 3149 ConstantInt::getSigned(CI->getType(), II.StepValue->getSExtValue()); 3150 for (unsigned Part = 0; Part < UF; ++Part) 3151 Entry[Part] = getStepVector(Broadcasted, VF * Part, Step); 3152 propagateMetadata(Entry, it); 3153 break; 3154 } 3155 /// Vectorize casts. 3156 Type *DestTy = (VF == 1) ? CI->getType() : 3157 VectorType::get(CI->getType(), VF); 3158 3159 VectorParts &A = getVectorValue(it->getOperand(0)); 3160 for (unsigned Part = 0; Part < UF; ++Part) 3161 Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy); 3162 propagateMetadata(Entry, it); 3163 break; 3164 } 3165 3166 case Instruction::Call: { 3167 // Ignore dbg intrinsics. 3168 if (isa<DbgInfoIntrinsic>(it)) 3169 break; 3170 setDebugLocFromInst(Builder, it); 3171 3172 Module *M = BB->getParent()->getParent(); 3173 CallInst *CI = cast<CallInst>(it); 3174 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI); 3175 assert(ID && "Not an intrinsic call!"); 3176 switch (ID) { 3177 case Intrinsic::assume: 3178 case Intrinsic::lifetime_end: 3179 case Intrinsic::lifetime_start: 3180 scalarizeInstruction(it); 3181 break; 3182 default: 3183 bool HasScalarOpd = hasVectorInstrinsicScalarOpd(ID, 1); 3184 for (unsigned Part = 0; Part < UF; ++Part) { 3185 SmallVector<Value *, 4> Args; 3186 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) { 3187 if (HasScalarOpd && i == 1) { 3188 Args.push_back(CI->getArgOperand(i)); 3189 continue; 3190 } 3191 VectorParts &Arg = getVectorValue(CI->getArgOperand(i)); 3192 Args.push_back(Arg[Part]); 3193 } 3194 Type *Tys[] = {CI->getType()}; 3195 if (VF > 1) 3196 Tys[0] = VectorType::get(CI->getType()->getScalarType(), VF); 3197 3198 Function *F = Intrinsic::getDeclaration(M, ID, Tys); 3199 Entry[Part] = Builder.CreateCall(F, Args); 3200 } 3201 3202 propagateMetadata(Entry, it); 3203 break; 3204 } 3205 break; 3206 } 3207 3208 default: 3209 // All other instructions are unsupported. Scalarize them. 3210 scalarizeInstruction(it); 3211 break; 3212 }// end of switch. 3213 }// end of for_each instr. 3214 } 3215 3216 void InnerLoopVectorizer::updateAnalysis() { 3217 // Forget the original basic block. 3218 SE->forgetLoop(OrigLoop); 3219 3220 // Update the dominator tree information. 3221 assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) && 3222 "Entry does not dominate exit."); 3223 3224 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I) 3225 DT->addNewBlock(LoopBypassBlocks[I], LoopBypassBlocks[I-1]); 3226 DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlocks.back()); 3227 3228 // Due to if predication of stores we might create a sequence of "if(pred) 3229 // a[i] = ...; " blocks. 3230 for (unsigned i = 0, e = LoopVectorBody.size(); i != e; ++i) { 3231 if (i == 0) 3232 DT->addNewBlock(LoopVectorBody[0], LoopVectorPreHeader); 3233 else if (isPredicatedBlock(i)) { 3234 DT->addNewBlock(LoopVectorBody[i], LoopVectorBody[i-1]); 3235 } else { 3236 DT->addNewBlock(LoopVectorBody[i], LoopVectorBody[i-2]); 3237 } 3238 } 3239 3240 DT->addNewBlock(LoopMiddleBlock, LoopBypassBlocks[1]); 3241 DT->addNewBlock(LoopScalarPreHeader, LoopBypassBlocks[0]); 3242 DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader); 3243 DT->changeImmediateDominator(LoopExitBlock, LoopBypassBlocks[0]); 3244 3245 DEBUG(DT->verifyDomTree()); 3246 } 3247 3248 /// \brief Check whether it is safe to if-convert this phi node. 3249 /// 3250 /// Phi nodes with constant expressions that can trap are not safe to if 3251 /// convert. 3252 static bool canIfConvertPHINodes(BasicBlock *BB) { 3253 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) { 3254 PHINode *Phi = dyn_cast<PHINode>(I); 3255 if (!Phi) 3256 return true; 3257 for (unsigned p = 0, e = Phi->getNumIncomingValues(); p != e; ++p) 3258 if (Constant *C = dyn_cast<Constant>(Phi->getIncomingValue(p))) 3259 if (C->canTrap()) 3260 return false; 3261 } 3262 return true; 3263 } 3264 3265 bool LoopVectorizationLegality::canVectorizeWithIfConvert() { 3266 if (!EnableIfConversion) { 3267 emitAnalysis(VectorizationReport() << "if-conversion is disabled"); 3268 return false; 3269 } 3270 3271 assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable"); 3272 3273 // A list of pointers that we can safely read and write to. 3274 SmallPtrSet<Value *, 8> SafePointes; 3275 3276 // Collect safe addresses. 3277 for (Loop::block_iterator BI = TheLoop->block_begin(), 3278 BE = TheLoop->block_end(); BI != BE; ++BI) { 3279 BasicBlock *BB = *BI; 3280 3281 if (blockNeedsPredication(BB)) 3282 continue; 3283 3284 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) { 3285 if (LoadInst *LI = dyn_cast<LoadInst>(I)) 3286 SafePointes.insert(LI->getPointerOperand()); 3287 else if (StoreInst *SI = dyn_cast<StoreInst>(I)) 3288 SafePointes.insert(SI->getPointerOperand()); 3289 } 3290 } 3291 3292 // Collect the blocks that need predication. 3293 BasicBlock *Header = TheLoop->getHeader(); 3294 for (Loop::block_iterator BI = TheLoop->block_begin(), 3295 BE = TheLoop->block_end(); BI != BE; ++BI) { 3296 BasicBlock *BB = *BI; 3297 3298 // We don't support switch statements inside loops. 3299 if (!isa<BranchInst>(BB->getTerminator())) { 3300 emitAnalysis(VectorizationReport(BB->getTerminator()) 3301 << "loop contains a switch statement"); 3302 return false; 3303 } 3304 3305 // We must be able to predicate all blocks that need to be predicated. 3306 if (blockNeedsPredication(BB)) { 3307 if (!blockCanBePredicated(BB, SafePointes)) { 3308 emitAnalysis(VectorizationReport(BB->getTerminator()) 3309 << "control flow cannot be substituted for a select"); 3310 return false; 3311 } 3312 } else if (BB != Header && !canIfConvertPHINodes(BB)) { 3313 emitAnalysis(VectorizationReport(BB->getTerminator()) 3314 << "control flow cannot be substituted for a select"); 3315 return false; 3316 } 3317 } 3318 3319 // We can if-convert this loop. 3320 return true; 3321 } 3322 3323 bool LoopVectorizationLegality::canVectorize() { 3324 // We must have a loop in canonical form. Loops with indirectbr in them cannot 3325 // be canonicalized. 3326 if (!TheLoop->getLoopPreheader()) { 3327 emitAnalysis( 3328 VectorizationReport() << 3329 "loop control flow is not understood by vectorizer"); 3330 return false; 3331 } 3332 3333 // We can only vectorize innermost loops. 3334 if (!TheLoop->getSubLoopsVector().empty()) { 3335 emitAnalysis(VectorizationReport() << "loop is not the innermost loop"); 3336 return false; 3337 } 3338 3339 // We must have a single backedge. 3340 if (TheLoop->getNumBackEdges() != 1) { 3341 emitAnalysis( 3342 VectorizationReport() << 3343 "loop control flow is not understood by vectorizer"); 3344 return false; 3345 } 3346 3347 // We must have a single exiting block. 3348 if (!TheLoop->getExitingBlock()) { 3349 emitAnalysis( 3350 VectorizationReport() << 3351 "loop control flow is not understood by vectorizer"); 3352 return false; 3353 } 3354 3355 // We only handle bottom-tested loops, i.e. loop in which the condition is 3356 // checked at the end of each iteration. With that we can assume that all 3357 // instructions in the loop are executed the same number of times. 3358 if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) { 3359 emitAnalysis( 3360 VectorizationReport() << 3361 "loop control flow is not understood by vectorizer"); 3362 return false; 3363 } 3364 3365 // We need to have a loop header. 3366 DEBUG(dbgs() << "LV: Found a loop: " << 3367 TheLoop->getHeader()->getName() << '\n'); 3368 3369 // Check if we can if-convert non-single-bb loops. 3370 unsigned NumBlocks = TheLoop->getNumBlocks(); 3371 if (NumBlocks != 1 && !canVectorizeWithIfConvert()) { 3372 DEBUG(dbgs() << "LV: Can't if-convert the loop.\n"); 3373 return false; 3374 } 3375 3376 // ScalarEvolution needs to be able to find the exit count. 3377 const SCEV *ExitCount = SE->getBackedgeTakenCount(TheLoop); 3378 if (ExitCount == SE->getCouldNotCompute()) { 3379 emitAnalysis(VectorizationReport() << 3380 "could not determine number of loop iterations"); 3381 DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n"); 3382 return false; 3383 } 3384 3385 // Check if we can vectorize the instructions and CFG in this loop. 3386 if (!canVectorizeInstrs()) { 3387 DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n"); 3388 return false; 3389 } 3390 3391 // Go over each instruction and look at memory deps. 3392 if (!canVectorizeMemory()) { 3393 DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n"); 3394 return false; 3395 } 3396 3397 // Collect all of the variables that remain uniform after vectorization. 3398 collectLoopUniforms(); 3399 3400 DEBUG(dbgs() << "LV: We can vectorize this loop" << 3401 (LAA.getRuntimePointerCheck()->Need ? " (with a runtime bound check)" : 3402 "") 3403 <<"!\n"); 3404 3405 // Okay! We can vectorize. At this point we don't have any other mem analysis 3406 // which may limit our maximum vectorization factor, so just return true with 3407 // no restrictions. 3408 return true; 3409 } 3410 3411 static Type *convertPointerToIntegerType(const DataLayout &DL, Type *Ty) { 3412 if (Ty->isPointerTy()) 3413 return DL.getIntPtrType(Ty); 3414 3415 // It is possible that char's or short's overflow when we ask for the loop's 3416 // trip count, work around this by changing the type size. 3417 if (Ty->getScalarSizeInBits() < 32) 3418 return Type::getInt32Ty(Ty->getContext()); 3419 3420 return Ty; 3421 } 3422 3423 static Type* getWiderType(const DataLayout &DL, Type *Ty0, Type *Ty1) { 3424 Ty0 = convertPointerToIntegerType(DL, Ty0); 3425 Ty1 = convertPointerToIntegerType(DL, Ty1); 3426 if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits()) 3427 return Ty0; 3428 return Ty1; 3429 } 3430 3431 /// \brief Check that the instruction has outside loop users and is not an 3432 /// identified reduction variable. 3433 static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst, 3434 SmallPtrSetImpl<Value *> &Reductions) { 3435 // Reduction instructions are allowed to have exit users. All other 3436 // instructions must not have external users. 3437 if (!Reductions.count(Inst)) 3438 //Check that all of the users of the loop are inside the BB. 3439 for (User *U : Inst->users()) { 3440 Instruction *UI = cast<Instruction>(U); 3441 // This user may be a reduction exit value. 3442 if (!TheLoop->contains(UI)) { 3443 DEBUG(dbgs() << "LV: Found an outside user for : " << *UI << '\n'); 3444 return true; 3445 } 3446 } 3447 return false; 3448 } 3449 3450 bool LoopVectorizationLegality::canVectorizeInstrs() { 3451 BasicBlock *PreHeader = TheLoop->getLoopPreheader(); 3452 BasicBlock *Header = TheLoop->getHeader(); 3453 3454 // Look for the attribute signaling the absence of NaNs. 3455 Function &F = *Header->getParent(); 3456 if (F.hasFnAttribute("no-nans-fp-math")) 3457 HasFunNoNaNAttr = F.getAttributes().getAttribute( 3458 AttributeSet::FunctionIndex, 3459 "no-nans-fp-math").getValueAsString() == "true"; 3460 3461 // For each block in the loop. 3462 for (Loop::block_iterator bb = TheLoop->block_begin(), 3463 be = TheLoop->block_end(); bb != be; ++bb) { 3464 3465 // Scan the instructions in the block and look for hazards. 3466 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e; 3467 ++it) { 3468 3469 if (PHINode *Phi = dyn_cast<PHINode>(it)) { 3470 Type *PhiTy = Phi->getType(); 3471 // Check that this PHI type is allowed. 3472 if (!PhiTy->isIntegerTy() && 3473 !PhiTy->isFloatingPointTy() && 3474 !PhiTy->isPointerTy()) { 3475 emitAnalysis(VectorizationReport(it) 3476 << "loop control flow is not understood by vectorizer"); 3477 DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n"); 3478 return false; 3479 } 3480 3481 // If this PHINode is not in the header block, then we know that we 3482 // can convert it to select during if-conversion. No need to check if 3483 // the PHIs in this block are induction or reduction variables. 3484 if (*bb != Header) { 3485 // Check that this instruction has no outside users or is an 3486 // identified reduction value with an outside user. 3487 if (!hasOutsideLoopUser(TheLoop, it, AllowedExit)) 3488 continue; 3489 emitAnalysis(VectorizationReport(it) << 3490 "value could not be identified as " 3491 "an induction or reduction variable"); 3492 return false; 3493 } 3494 3495 // We only allow if-converted PHIs with exactly two incoming values. 3496 if (Phi->getNumIncomingValues() != 2) { 3497 emitAnalysis(VectorizationReport(it) 3498 << "control flow not understood by vectorizer"); 3499 DEBUG(dbgs() << "LV: Found an invalid PHI.\n"); 3500 return false; 3501 } 3502 3503 // This is the value coming from the preheader. 3504 Value *StartValue = Phi->getIncomingValueForBlock(PreHeader); 3505 ConstantInt *StepValue = nullptr; 3506 // Check if this is an induction variable. 3507 InductionKind IK = isInductionVariable(Phi, StepValue); 3508 3509 if (IK_NoInduction != IK) { 3510 // Get the widest type. 3511 if (!WidestIndTy) 3512 WidestIndTy = convertPointerToIntegerType(*DL, PhiTy); 3513 else 3514 WidestIndTy = getWiderType(*DL, PhiTy, WidestIndTy); 3515 3516 // Int inductions are special because we only allow one IV. 3517 if (IK == IK_IntInduction && StepValue->isOne()) { 3518 // Use the phi node with the widest type as induction. Use the last 3519 // one if there are multiple (no good reason for doing this other 3520 // than it is expedient). 3521 if (!Induction || PhiTy == WidestIndTy) 3522 Induction = Phi; 3523 } 3524 3525 DEBUG(dbgs() << "LV: Found an induction variable.\n"); 3526 Inductions[Phi] = InductionInfo(StartValue, IK, StepValue); 3527 3528 // Until we explicitly handle the case of an induction variable with 3529 // an outside loop user we have to give up vectorizing this loop. 3530 if (hasOutsideLoopUser(TheLoop, it, AllowedExit)) { 3531 emitAnalysis(VectorizationReport(it) << 3532 "use of induction value outside of the " 3533 "loop is not handled by vectorizer"); 3534 return false; 3535 } 3536 3537 continue; 3538 } 3539 3540 if (AddReductionVar(Phi, RK_IntegerAdd)) { 3541 DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n"); 3542 continue; 3543 } 3544 if (AddReductionVar(Phi, RK_IntegerMult)) { 3545 DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n"); 3546 continue; 3547 } 3548 if (AddReductionVar(Phi, RK_IntegerOr)) { 3549 DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n"); 3550 continue; 3551 } 3552 if (AddReductionVar(Phi, RK_IntegerAnd)) { 3553 DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n"); 3554 continue; 3555 } 3556 if (AddReductionVar(Phi, RK_IntegerXor)) { 3557 DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n"); 3558 continue; 3559 } 3560 if (AddReductionVar(Phi, RK_IntegerMinMax)) { 3561 DEBUG(dbgs() << "LV: Found a MINMAX reduction PHI."<< *Phi <<"\n"); 3562 continue; 3563 } 3564 if (AddReductionVar(Phi, RK_FloatMult)) { 3565 DEBUG(dbgs() << "LV: Found an FMult reduction PHI."<< *Phi <<"\n"); 3566 continue; 3567 } 3568 if (AddReductionVar(Phi, RK_FloatAdd)) { 3569 DEBUG(dbgs() << "LV: Found an FAdd reduction PHI."<< *Phi <<"\n"); 3570 continue; 3571 } 3572 if (AddReductionVar(Phi, RK_FloatMinMax)) { 3573 DEBUG(dbgs() << "LV: Found an float MINMAX reduction PHI."<< *Phi << 3574 "\n"); 3575 continue; 3576 } 3577 3578 emitAnalysis(VectorizationReport(it) << 3579 "value that could not be identified as " 3580 "reduction is used outside the loop"); 3581 DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n"); 3582 return false; 3583 }// end of PHI handling 3584 3585 // We still don't handle functions. However, we can ignore dbg intrinsic 3586 // calls and we do handle certain intrinsic and libm functions. 3587 CallInst *CI = dyn_cast<CallInst>(it); 3588 if (CI && !getIntrinsicIDForCall(CI, TLI) && !isa<DbgInfoIntrinsic>(CI)) { 3589 emitAnalysis(VectorizationReport(it) << 3590 "call instruction cannot be vectorized"); 3591 DEBUG(dbgs() << "LV: Found a call site.\n"); 3592 return false; 3593 } 3594 3595 // Intrinsics such as powi,cttz and ctlz are legal to vectorize if the 3596 // second argument is the same (i.e. loop invariant) 3597 if (CI && 3598 hasVectorInstrinsicScalarOpd(getIntrinsicIDForCall(CI, TLI), 1)) { 3599 if (!SE->isLoopInvariant(SE->getSCEV(CI->getOperand(1)), TheLoop)) { 3600 emitAnalysis(VectorizationReport(it) 3601 << "intrinsic instruction cannot be vectorized"); 3602 DEBUG(dbgs() << "LV: Found unvectorizable intrinsic " << *CI << "\n"); 3603 return false; 3604 } 3605 } 3606 3607 // Check that the instruction return type is vectorizable. 3608 // Also, we can't vectorize extractelement instructions. 3609 if ((!VectorType::isValidElementType(it->getType()) && 3610 !it->getType()->isVoidTy()) || isa<ExtractElementInst>(it)) { 3611 emitAnalysis(VectorizationReport(it) 3612 << "instruction return type cannot be vectorized"); 3613 DEBUG(dbgs() << "LV: Found unvectorizable type.\n"); 3614 return false; 3615 } 3616 3617 // Check that the stored type is vectorizable. 3618 if (StoreInst *ST = dyn_cast<StoreInst>(it)) { 3619 Type *T = ST->getValueOperand()->getType(); 3620 if (!VectorType::isValidElementType(T)) { 3621 emitAnalysis(VectorizationReport(ST) << 3622 "store instruction cannot be vectorized"); 3623 return false; 3624 } 3625 if (EnableMemAccessVersioning) 3626 collectStridedAccess(ST); 3627 } 3628 3629 if (EnableMemAccessVersioning) 3630 if (LoadInst *LI = dyn_cast<LoadInst>(it)) 3631 collectStridedAccess(LI); 3632 3633 // Reduction instructions are allowed to have exit users. 3634 // All other instructions must not have external users. 3635 if (hasOutsideLoopUser(TheLoop, it, AllowedExit)) { 3636 emitAnalysis(VectorizationReport(it) << 3637 "value cannot be used outside the loop"); 3638 return false; 3639 } 3640 3641 } // next instr. 3642 3643 } 3644 3645 if (!Induction) { 3646 DEBUG(dbgs() << "LV: Did not find one integer induction var.\n"); 3647 if (Inductions.empty()) { 3648 emitAnalysis(VectorizationReport() 3649 << "loop induction variable could not be identified"); 3650 return false; 3651 } 3652 } 3653 3654 return true; 3655 } 3656 3657 ///\brief Remove GEPs whose indices but the last one are loop invariant and 3658 /// return the induction operand of the gep pointer. 3659 static Value *stripGetElementPtr(Value *Ptr, ScalarEvolution *SE, 3660 const DataLayout *DL, Loop *Lp) { 3661 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr); 3662 if (!GEP) 3663 return Ptr; 3664 3665 unsigned InductionOperand = getGEPInductionOperand(DL, GEP); 3666 3667 // Check that all of the gep indices are uniform except for our induction 3668 // operand. 3669 for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i) 3670 if (i != InductionOperand && 3671 !SE->isLoopInvariant(SE->getSCEV(GEP->getOperand(i)), Lp)) 3672 return Ptr; 3673 return GEP->getOperand(InductionOperand); 3674 } 3675 3676 ///\brief Look for a cast use of the passed value. 3677 static Value *getUniqueCastUse(Value *Ptr, Loop *Lp, Type *Ty) { 3678 Value *UniqueCast = nullptr; 3679 for (User *U : Ptr->users()) { 3680 CastInst *CI = dyn_cast<CastInst>(U); 3681 if (CI && CI->getType() == Ty) { 3682 if (!UniqueCast) 3683 UniqueCast = CI; 3684 else 3685 return nullptr; 3686 } 3687 } 3688 return UniqueCast; 3689 } 3690 3691 ///\brief Get the stride of a pointer access in a loop. 3692 /// Looks for symbolic strides "a[i*stride]". Returns the symbolic stride as a 3693 /// pointer to the Value, or null otherwise. 3694 static Value *getStrideFromPointer(Value *Ptr, ScalarEvolution *SE, 3695 const DataLayout *DL, Loop *Lp) { 3696 const PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType()); 3697 if (!PtrTy || PtrTy->isAggregateType()) 3698 return nullptr; 3699 3700 // Try to remove a gep instruction to make the pointer (actually index at this 3701 // point) easier analyzable. If OrigPtr is equal to Ptr we are analzying the 3702 // pointer, otherwise, we are analyzing the index. 3703 Value *OrigPtr = Ptr; 3704 3705 // The size of the pointer access. 3706 int64_t PtrAccessSize = 1; 3707 3708 Ptr = stripGetElementPtr(Ptr, SE, DL, Lp); 3709 const SCEV *V = SE->getSCEV(Ptr); 3710 3711 if (Ptr != OrigPtr) 3712 // Strip off casts. 3713 while (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V)) 3714 V = C->getOperand(); 3715 3716 const SCEVAddRecExpr *S = dyn_cast<SCEVAddRecExpr>(V); 3717 if (!S) 3718 return nullptr; 3719 3720 V = S->getStepRecurrence(*SE); 3721 if (!V) 3722 return nullptr; 3723 3724 // Strip off the size of access multiplication if we are still analyzing the 3725 // pointer. 3726 if (OrigPtr == Ptr) { 3727 DL->getTypeAllocSize(PtrTy->getElementType()); 3728 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(V)) { 3729 if (M->getOperand(0)->getSCEVType() != scConstant) 3730 return nullptr; 3731 3732 const APInt &APStepVal = 3733 cast<SCEVConstant>(M->getOperand(0))->getValue()->getValue(); 3734 3735 // Huge step value - give up. 3736 if (APStepVal.getBitWidth() > 64) 3737 return nullptr; 3738 3739 int64_t StepVal = APStepVal.getSExtValue(); 3740 if (PtrAccessSize != StepVal) 3741 return nullptr; 3742 V = M->getOperand(1); 3743 } 3744 } 3745 3746 // Strip off casts. 3747 Type *StripedOffRecurrenceCast = nullptr; 3748 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V)) { 3749 StripedOffRecurrenceCast = C->getType(); 3750 V = C->getOperand(); 3751 } 3752 3753 // Look for the loop invariant symbolic value. 3754 const SCEVUnknown *U = dyn_cast<SCEVUnknown>(V); 3755 if (!U) 3756 return nullptr; 3757 3758 Value *Stride = U->getValue(); 3759 if (!Lp->isLoopInvariant(Stride)) 3760 return nullptr; 3761 3762 // If we have stripped off the recurrence cast we have to make sure that we 3763 // return the value that is used in this loop so that we can replace it later. 3764 if (StripedOffRecurrenceCast) 3765 Stride = getUniqueCastUse(Stride, Lp, StripedOffRecurrenceCast); 3766 3767 return Stride; 3768 } 3769 3770 void LoopVectorizationLegality::collectStridedAccess(Value *MemAccess) { 3771 Value *Ptr = nullptr; 3772 if (LoadInst *LI = dyn_cast<LoadInst>(MemAccess)) 3773 Ptr = LI->getPointerOperand(); 3774 else if (StoreInst *SI = dyn_cast<StoreInst>(MemAccess)) 3775 Ptr = SI->getPointerOperand(); 3776 else 3777 return; 3778 3779 Value *Stride = getStrideFromPointer(Ptr, SE, DL, TheLoop); 3780 if (!Stride) 3781 return; 3782 3783 DEBUG(dbgs() << "LV: Found a strided access that we can version"); 3784 DEBUG(dbgs() << " Ptr: " << *Ptr << " Stride: " << *Stride << "\n"); 3785 Strides[Ptr] = Stride; 3786 StrideSet.insert(Stride); 3787 } 3788 3789 void LoopVectorizationLegality::collectLoopUniforms() { 3790 // We now know that the loop is vectorizable! 3791 // Collect variables that will remain uniform after vectorization. 3792 std::vector<Value*> Worklist; 3793 BasicBlock *Latch = TheLoop->getLoopLatch(); 3794 3795 // Start with the conditional branch and walk up the block. 3796 Worklist.push_back(Latch->getTerminator()->getOperand(0)); 3797 3798 // Also add all consecutive pointer values; these values will be uniform 3799 // after vectorization (and subsequent cleanup) and, until revectorization is 3800 // supported, all dependencies must also be uniform. 3801 for (Loop::block_iterator B = TheLoop->block_begin(), 3802 BE = TheLoop->block_end(); B != BE; ++B) 3803 for (BasicBlock::iterator I = (*B)->begin(), IE = (*B)->end(); 3804 I != IE; ++I) 3805 if (I->getType()->isPointerTy() && isConsecutivePtr(I)) 3806 Worklist.insert(Worklist.end(), I->op_begin(), I->op_end()); 3807 3808 while (!Worklist.empty()) { 3809 Instruction *I = dyn_cast<Instruction>(Worklist.back()); 3810 Worklist.pop_back(); 3811 3812 // Look at instructions inside this loop. 3813 // Stop when reaching PHI nodes. 3814 // TODO: we need to follow values all over the loop, not only in this block. 3815 if (!I || !TheLoop->contains(I) || isa<PHINode>(I)) 3816 continue; 3817 3818 // This is a known uniform. 3819 Uniforms.insert(I); 3820 3821 // Insert all operands. 3822 Worklist.insert(Worklist.end(), I->op_begin(), I->op_end()); 3823 } 3824 } 3825 3826 bool LoopVectorizationLegality::canVectorizeMemory() { 3827 return LAA.canVectorizeMemory(Strides); 3828 } 3829 3830 static bool hasMultipleUsesOf(Instruction *I, 3831 SmallPtrSetImpl<Instruction *> &Insts) { 3832 unsigned NumUses = 0; 3833 for(User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use) { 3834 if (Insts.count(dyn_cast<Instruction>(*Use))) 3835 ++NumUses; 3836 if (NumUses > 1) 3837 return true; 3838 } 3839 3840 return false; 3841 } 3842 3843 static bool areAllUsesIn(Instruction *I, SmallPtrSetImpl<Instruction *> &Set) { 3844 for(User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use) 3845 if (!Set.count(dyn_cast<Instruction>(*Use))) 3846 return false; 3847 return true; 3848 } 3849 3850 bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi, 3851 ReductionKind Kind) { 3852 if (Phi->getNumIncomingValues() != 2) 3853 return false; 3854 3855 // Reduction variables are only found in the loop header block. 3856 if (Phi->getParent() != TheLoop->getHeader()) 3857 return false; 3858 3859 // Obtain the reduction start value from the value that comes from the loop 3860 // preheader. 3861 Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader()); 3862 3863 // ExitInstruction is the single value which is used outside the loop. 3864 // We only allow for a single reduction value to be used outside the loop. 3865 // This includes users of the reduction, variables (which form a cycle 3866 // which ends in the phi node). 3867 Instruction *ExitInstruction = nullptr; 3868 // Indicates that we found a reduction operation in our scan. 3869 bool FoundReduxOp = false; 3870 3871 // We start with the PHI node and scan for all of the users of this 3872 // instruction. All users must be instructions that can be used as reduction 3873 // variables (such as ADD). We must have a single out-of-block user. The cycle 3874 // must include the original PHI. 3875 bool FoundStartPHI = false; 3876 3877 // To recognize min/max patterns formed by a icmp select sequence, we store 3878 // the number of instruction we saw from the recognized min/max pattern, 3879 // to make sure we only see exactly the two instructions. 3880 unsigned NumCmpSelectPatternInst = 0; 3881 ReductionInstDesc ReduxDesc(false, nullptr); 3882 3883 SmallPtrSet<Instruction *, 8> VisitedInsts; 3884 SmallVector<Instruction *, 8> Worklist; 3885 Worklist.push_back(Phi); 3886 VisitedInsts.insert(Phi); 3887 3888 // A value in the reduction can be used: 3889 // - By the reduction: 3890 // - Reduction operation: 3891 // - One use of reduction value (safe). 3892 // - Multiple use of reduction value (not safe). 3893 // - PHI: 3894 // - All uses of the PHI must be the reduction (safe). 3895 // - Otherwise, not safe. 3896 // - By one instruction outside of the loop (safe). 3897 // - By further instructions outside of the loop (not safe). 3898 // - By an instruction that is not part of the reduction (not safe). 3899 // This is either: 3900 // * An instruction type other than PHI or the reduction operation. 3901 // * A PHI in the header other than the initial PHI. 3902 while (!Worklist.empty()) { 3903 Instruction *Cur = Worklist.back(); 3904 Worklist.pop_back(); 3905 3906 // No Users. 3907 // If the instruction has no users then this is a broken chain and can't be 3908 // a reduction variable. 3909 if (Cur->use_empty()) 3910 return false; 3911 3912 bool IsAPhi = isa<PHINode>(Cur); 3913 3914 // A header PHI use other than the original PHI. 3915 if (Cur != Phi && IsAPhi && Cur->getParent() == Phi->getParent()) 3916 return false; 3917 3918 // Reductions of instructions such as Div, and Sub is only possible if the 3919 // LHS is the reduction variable. 3920 if (!Cur->isCommutative() && !IsAPhi && !isa<SelectInst>(Cur) && 3921 !isa<ICmpInst>(Cur) && !isa<FCmpInst>(Cur) && 3922 !VisitedInsts.count(dyn_cast<Instruction>(Cur->getOperand(0)))) 3923 return false; 3924 3925 // Any reduction instruction must be of one of the allowed kinds. 3926 ReduxDesc = isReductionInstr(Cur, Kind, ReduxDesc); 3927 if (!ReduxDesc.IsReduction) 3928 return false; 3929 3930 // A reduction operation must only have one use of the reduction value. 3931 if (!IsAPhi && Kind != RK_IntegerMinMax && Kind != RK_FloatMinMax && 3932 hasMultipleUsesOf(Cur, VisitedInsts)) 3933 return false; 3934 3935 // All inputs to a PHI node must be a reduction value. 3936 if(IsAPhi && Cur != Phi && !areAllUsesIn(Cur, VisitedInsts)) 3937 return false; 3938 3939 if (Kind == RK_IntegerMinMax && (isa<ICmpInst>(Cur) || 3940 isa<SelectInst>(Cur))) 3941 ++NumCmpSelectPatternInst; 3942 if (Kind == RK_FloatMinMax && (isa<FCmpInst>(Cur) || 3943 isa<SelectInst>(Cur))) 3944 ++NumCmpSelectPatternInst; 3945 3946 // Check whether we found a reduction operator. 3947 FoundReduxOp |= !IsAPhi; 3948 3949 // Process users of current instruction. Push non-PHI nodes after PHI nodes 3950 // onto the stack. This way we are going to have seen all inputs to PHI 3951 // nodes once we get to them. 3952 SmallVector<Instruction *, 8> NonPHIs; 3953 SmallVector<Instruction *, 8> PHIs; 3954 for (User *U : Cur->users()) { 3955 Instruction *UI = cast<Instruction>(U); 3956 3957 // Check if we found the exit user. 3958 BasicBlock *Parent = UI->getParent(); 3959 if (!TheLoop->contains(Parent)) { 3960 // Exit if you find multiple outside users or if the header phi node is 3961 // being used. In this case the user uses the value of the previous 3962 // iteration, in which case we would loose "VF-1" iterations of the 3963 // reduction operation if we vectorize. 3964 if (ExitInstruction != nullptr || Cur == Phi) 3965 return false; 3966 3967 // The instruction used by an outside user must be the last instruction 3968 // before we feed back to the reduction phi. Otherwise, we loose VF-1 3969 // operations on the value. 3970 if (std::find(Phi->op_begin(), Phi->op_end(), Cur) == Phi->op_end()) 3971 return false; 3972 3973 ExitInstruction = Cur; 3974 continue; 3975 } 3976 3977 // Process instructions only once (termination). Each reduction cycle 3978 // value must only be used once, except by phi nodes and min/max 3979 // reductions which are represented as a cmp followed by a select. 3980 ReductionInstDesc IgnoredVal(false, nullptr); 3981 if (VisitedInsts.insert(UI).second) { 3982 if (isa<PHINode>(UI)) 3983 PHIs.push_back(UI); 3984 else 3985 NonPHIs.push_back(UI); 3986 } else if (!isa<PHINode>(UI) && 3987 ((!isa<FCmpInst>(UI) && 3988 !isa<ICmpInst>(UI) && 3989 !isa<SelectInst>(UI)) || 3990 !isMinMaxSelectCmpPattern(UI, IgnoredVal).IsReduction)) 3991 return false; 3992 3993 // Remember that we completed the cycle. 3994 if (UI == Phi) 3995 FoundStartPHI = true; 3996 } 3997 Worklist.append(PHIs.begin(), PHIs.end()); 3998 Worklist.append(NonPHIs.begin(), NonPHIs.end()); 3999 } 4000 4001 // This means we have seen one but not the other instruction of the 4002 // pattern or more than just a select and cmp. 4003 if ((Kind == RK_IntegerMinMax || Kind == RK_FloatMinMax) && 4004 NumCmpSelectPatternInst != 2) 4005 return false; 4006 4007 if (!FoundStartPHI || !FoundReduxOp || !ExitInstruction) 4008 return false; 4009 4010 // We found a reduction var if we have reached the original phi node and we 4011 // only have a single instruction with out-of-loop users. 4012 4013 // This instruction is allowed to have out-of-loop users. 4014 AllowedExit.insert(ExitInstruction); 4015 4016 // Save the description of this reduction variable. 4017 ReductionDescriptor RD(RdxStart, ExitInstruction, Kind, 4018 ReduxDesc.MinMaxKind); 4019 Reductions[Phi] = RD; 4020 // We've ended the cycle. This is a reduction variable if we have an 4021 // outside user and it has a binary op. 4022 4023 return true; 4024 } 4025 4026 /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction 4027 /// pattern corresponding to a min(X, Y) or max(X, Y). 4028 LoopVectorizationLegality::ReductionInstDesc 4029 LoopVectorizationLegality::isMinMaxSelectCmpPattern(Instruction *I, 4030 ReductionInstDesc &Prev) { 4031 4032 assert((isa<ICmpInst>(I) || isa<FCmpInst>(I) || isa<SelectInst>(I)) && 4033 "Expect a select instruction"); 4034 Instruction *Cmp = nullptr; 4035 SelectInst *Select = nullptr; 4036 4037 // We must handle the select(cmp()) as a single instruction. Advance to the 4038 // select. 4039 if ((Cmp = dyn_cast<ICmpInst>(I)) || (Cmp = dyn_cast<FCmpInst>(I))) { 4040 if (!Cmp->hasOneUse() || !(Select = dyn_cast<SelectInst>(*I->user_begin()))) 4041 return ReductionInstDesc(false, I); 4042 return ReductionInstDesc(Select, Prev.MinMaxKind); 4043 } 4044 4045 // Only handle single use cases for now. 4046 if (!(Select = dyn_cast<SelectInst>(I))) 4047 return ReductionInstDesc(false, I); 4048 if (!(Cmp = dyn_cast<ICmpInst>(I->getOperand(0))) && 4049 !(Cmp = dyn_cast<FCmpInst>(I->getOperand(0)))) 4050 return ReductionInstDesc(false, I); 4051 if (!Cmp->hasOneUse()) 4052 return ReductionInstDesc(false, I); 4053 4054 Value *CmpLeft; 4055 Value *CmpRight; 4056 4057 // Look for a min/max pattern. 4058 if (m_UMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select)) 4059 return ReductionInstDesc(Select, MRK_UIntMin); 4060 else if (m_UMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select)) 4061 return ReductionInstDesc(Select, MRK_UIntMax); 4062 else if (m_SMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select)) 4063 return ReductionInstDesc(Select, MRK_SIntMax); 4064 else if (m_SMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select)) 4065 return ReductionInstDesc(Select, MRK_SIntMin); 4066 else if (m_OrdFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select)) 4067 return ReductionInstDesc(Select, MRK_FloatMin); 4068 else if (m_OrdFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select)) 4069 return ReductionInstDesc(Select, MRK_FloatMax); 4070 else if (m_UnordFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select)) 4071 return ReductionInstDesc(Select, MRK_FloatMin); 4072 else if (m_UnordFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select)) 4073 return ReductionInstDesc(Select, MRK_FloatMax); 4074 4075 return ReductionInstDesc(false, I); 4076 } 4077 4078 LoopVectorizationLegality::ReductionInstDesc 4079 LoopVectorizationLegality::isReductionInstr(Instruction *I, 4080 ReductionKind Kind, 4081 ReductionInstDesc &Prev) { 4082 bool FP = I->getType()->isFloatingPointTy(); 4083 bool FastMath = FP && I->hasUnsafeAlgebra(); 4084 switch (I->getOpcode()) { 4085 default: 4086 return ReductionInstDesc(false, I); 4087 case Instruction::PHI: 4088 if (FP && (Kind != RK_FloatMult && Kind != RK_FloatAdd && 4089 Kind != RK_FloatMinMax)) 4090 return ReductionInstDesc(false, I); 4091 return ReductionInstDesc(I, Prev.MinMaxKind); 4092 case Instruction::Sub: 4093 case Instruction::Add: 4094 return ReductionInstDesc(Kind == RK_IntegerAdd, I); 4095 case Instruction::Mul: 4096 return ReductionInstDesc(Kind == RK_IntegerMult, I); 4097 case Instruction::And: 4098 return ReductionInstDesc(Kind == RK_IntegerAnd, I); 4099 case Instruction::Or: 4100 return ReductionInstDesc(Kind == RK_IntegerOr, I); 4101 case Instruction::Xor: 4102 return ReductionInstDesc(Kind == RK_IntegerXor, I); 4103 case Instruction::FMul: 4104 return ReductionInstDesc(Kind == RK_FloatMult && FastMath, I); 4105 case Instruction::FSub: 4106 case Instruction::FAdd: 4107 return ReductionInstDesc(Kind == RK_FloatAdd && FastMath, I); 4108 case Instruction::FCmp: 4109 case Instruction::ICmp: 4110 case Instruction::Select: 4111 if (Kind != RK_IntegerMinMax && 4112 (!HasFunNoNaNAttr || Kind != RK_FloatMinMax)) 4113 return ReductionInstDesc(false, I); 4114 return isMinMaxSelectCmpPattern(I, Prev); 4115 } 4116 } 4117 4118 LoopVectorizationLegality::InductionKind 4119 LoopVectorizationLegality::isInductionVariable(PHINode *Phi, 4120 ConstantInt *&StepValue) { 4121 Type *PhiTy = Phi->getType(); 4122 // We only handle integer and pointer inductions variables. 4123 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy()) 4124 return IK_NoInduction; 4125 4126 // Check that the PHI is consecutive. 4127 const SCEV *PhiScev = SE->getSCEV(Phi); 4128 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev); 4129 if (!AR) { 4130 DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n"); 4131 return IK_NoInduction; 4132 } 4133 4134 const SCEV *Step = AR->getStepRecurrence(*SE); 4135 // Calculate the pointer stride and check if it is consecutive. 4136 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step); 4137 if (!C) 4138 return IK_NoInduction; 4139 4140 ConstantInt *CV = C->getValue(); 4141 if (PhiTy->isIntegerTy()) { 4142 StepValue = CV; 4143 return IK_IntInduction; 4144 } 4145 4146 assert(PhiTy->isPointerTy() && "The PHI must be a pointer"); 4147 Type *PointerElementType = PhiTy->getPointerElementType(); 4148 // The pointer stride cannot be determined if the pointer element type is not 4149 // sized. 4150 if (!PointerElementType->isSized()) 4151 return IK_NoInduction; 4152 4153 int64_t Size = static_cast<int64_t>(DL->getTypeAllocSize(PointerElementType)); 4154 int64_t CVSize = CV->getSExtValue(); 4155 if (CVSize % Size) 4156 return IK_NoInduction; 4157 StepValue = ConstantInt::getSigned(CV->getType(), CVSize / Size); 4158 return IK_PtrInduction; 4159 } 4160 4161 bool LoopVectorizationLegality::isInductionVariable(const Value *V) { 4162 Value *In0 = const_cast<Value*>(V); 4163 PHINode *PN = dyn_cast_or_null<PHINode>(In0); 4164 if (!PN) 4165 return false; 4166 4167 return Inductions.count(PN); 4168 } 4169 4170 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) { 4171 return LAA.blockNeedsPredication(BB); 4172 } 4173 4174 bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB, 4175 SmallPtrSetImpl<Value *> &SafePtrs) { 4176 4177 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) { 4178 // Check that we don't have a constant expression that can trap as operand. 4179 for (Instruction::op_iterator OI = it->op_begin(), OE = it->op_end(); 4180 OI != OE; ++OI) { 4181 if (Constant *C = dyn_cast<Constant>(*OI)) 4182 if (C->canTrap()) 4183 return false; 4184 } 4185 // We might be able to hoist the load. 4186 if (it->mayReadFromMemory()) { 4187 LoadInst *LI = dyn_cast<LoadInst>(it); 4188 if (!LI) 4189 return false; 4190 if (!SafePtrs.count(LI->getPointerOperand())) { 4191 if (isLegalMaskedLoad(LI->getType(), LI->getPointerOperand())) { 4192 MaskedOp.insert(LI); 4193 continue; 4194 } 4195 return false; 4196 } 4197 } 4198 4199 // We don't predicate stores at the moment. 4200 if (it->mayWriteToMemory()) { 4201 StoreInst *SI = dyn_cast<StoreInst>(it); 4202 // We only support predication of stores in basic blocks with one 4203 // predecessor. 4204 if (!SI) 4205 return false; 4206 4207 bool isSafePtr = (SafePtrs.count(SI->getPointerOperand()) != 0); 4208 bool isSinglePredecessor = SI->getParent()->getSinglePredecessor(); 4209 4210 if (++NumPredStores > NumberOfStoresToPredicate || !isSafePtr || 4211 !isSinglePredecessor) { 4212 // Build a masked store if it is legal for the target, otherwise scalarize 4213 // the block. 4214 bool isLegalMaskedOp = 4215 isLegalMaskedStore(SI->getValueOperand()->getType(), 4216 SI->getPointerOperand()); 4217 if (isLegalMaskedOp) { 4218 --NumPredStores; 4219 MaskedOp.insert(SI); 4220 continue; 4221 } 4222 return false; 4223 } 4224 } 4225 if (it->mayThrow()) 4226 return false; 4227 4228 // The instructions below can trap. 4229 switch (it->getOpcode()) { 4230 default: continue; 4231 case Instruction::UDiv: 4232 case Instruction::SDiv: 4233 case Instruction::URem: 4234 case Instruction::SRem: 4235 return false; 4236 } 4237 } 4238 4239 return true; 4240 } 4241 4242 LoopVectorizationCostModel::VectorizationFactor 4243 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize) { 4244 // Width 1 means no vectorize 4245 VectorizationFactor Factor = { 1U, 0U }; 4246 if (OptForSize && Legal->getRuntimePointerCheck()->Need) { 4247 emitAnalysis(VectorizationReport() << 4248 "runtime pointer checks needed. Enable vectorization of this " 4249 "loop with '#pragma clang loop vectorize(enable)' when " 4250 "compiling with -Os"); 4251 DEBUG(dbgs() << "LV: Aborting. Runtime ptr check is required in Os.\n"); 4252 return Factor; 4253 } 4254 4255 if (!EnableCondStoresVectorization && Legal->getNumPredStores()) { 4256 emitAnalysis(VectorizationReport() << 4257 "store that is conditionally executed prevents vectorization"); 4258 DEBUG(dbgs() << "LV: No vectorization. There are conditional stores.\n"); 4259 return Factor; 4260 } 4261 4262 // Find the trip count. 4263 unsigned TC = SE->getSmallConstantTripCount(TheLoop); 4264 DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n'); 4265 4266 unsigned WidestType = getWidestType(); 4267 unsigned WidestRegister = TTI.getRegisterBitWidth(true); 4268 unsigned MaxSafeDepDist = -1U; 4269 if (Legal->getMaxSafeDepDistBytes() != -1U) 4270 MaxSafeDepDist = Legal->getMaxSafeDepDistBytes() * 8; 4271 WidestRegister = ((WidestRegister < MaxSafeDepDist) ? 4272 WidestRegister : MaxSafeDepDist); 4273 unsigned MaxVectorSize = WidestRegister / WidestType; 4274 DEBUG(dbgs() << "LV: The Widest type: " << WidestType << " bits.\n"); 4275 DEBUG(dbgs() << "LV: The Widest register is: " 4276 << WidestRegister << " bits.\n"); 4277 4278 if (MaxVectorSize == 0) { 4279 DEBUG(dbgs() << "LV: The target has no vector registers.\n"); 4280 MaxVectorSize = 1; 4281 } 4282 4283 assert(MaxVectorSize <= 64 && "Did not expect to pack so many elements" 4284 " into one vector!"); 4285 4286 unsigned VF = MaxVectorSize; 4287 4288 // If we optimize the program for size, avoid creating the tail loop. 4289 if (OptForSize) { 4290 // If we are unable to calculate the trip count then don't try to vectorize. 4291 if (TC < 2) { 4292 emitAnalysis 4293 (VectorizationReport() << 4294 "unable to calculate the loop count due to complex control flow"); 4295 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n"); 4296 return Factor; 4297 } 4298 4299 // Find the maximum SIMD width that can fit within the trip count. 4300 VF = TC % MaxVectorSize; 4301 4302 if (VF == 0) 4303 VF = MaxVectorSize; 4304 4305 // If the trip count that we found modulo the vectorization factor is not 4306 // zero then we require a tail. 4307 if (VF < 2) { 4308 emitAnalysis(VectorizationReport() << 4309 "cannot optimize for size and vectorize at the " 4310 "same time. Enable vectorization of this loop " 4311 "with '#pragma clang loop vectorize(enable)' " 4312 "when compiling with -Os"); 4313 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n"); 4314 return Factor; 4315 } 4316 } 4317 4318 int UserVF = Hints->getWidth(); 4319 if (UserVF != 0) { 4320 assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two"); 4321 DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n"); 4322 4323 Factor.Width = UserVF; 4324 return Factor; 4325 } 4326 4327 float Cost = expectedCost(1); 4328 #ifndef NDEBUG 4329 const float ScalarCost = Cost; 4330 #endif /* NDEBUG */ 4331 unsigned Width = 1; 4332 DEBUG(dbgs() << "LV: Scalar loop costs: " << (int)ScalarCost << ".\n"); 4333 4334 bool ForceVectorization = Hints->getForce() == LoopVectorizeHints::FK_Enabled; 4335 // Ignore scalar width, because the user explicitly wants vectorization. 4336 if (ForceVectorization && VF > 1) { 4337 Width = 2; 4338 Cost = expectedCost(Width) / (float)Width; 4339 } 4340 4341 for (unsigned i=2; i <= VF; i*=2) { 4342 // Notice that the vector loop needs to be executed less times, so 4343 // we need to divide the cost of the vector loops by the width of 4344 // the vector elements. 4345 float VectorCost = expectedCost(i) / (float)i; 4346 DEBUG(dbgs() << "LV: Vector loop of width " << i << " costs: " << 4347 (int)VectorCost << ".\n"); 4348 if (VectorCost < Cost) { 4349 Cost = VectorCost; 4350 Width = i; 4351 } 4352 } 4353 4354 DEBUG(if (ForceVectorization && Width > 1 && Cost >= ScalarCost) dbgs() 4355 << "LV: Vectorization seems to be not beneficial, " 4356 << "but was forced by a user.\n"); 4357 DEBUG(dbgs() << "LV: Selecting VF: "<< Width << ".\n"); 4358 Factor.Width = Width; 4359 Factor.Cost = Width * Cost; 4360 return Factor; 4361 } 4362 4363 unsigned LoopVectorizationCostModel::getWidestType() { 4364 unsigned MaxWidth = 8; 4365 4366 // For each block. 4367 for (Loop::block_iterator bb = TheLoop->block_begin(), 4368 be = TheLoop->block_end(); bb != be; ++bb) { 4369 BasicBlock *BB = *bb; 4370 4371 // For each instruction in the loop. 4372 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) { 4373 Type *T = it->getType(); 4374 4375 // Ignore ephemeral values. 4376 if (EphValues.count(it)) 4377 continue; 4378 4379 // Only examine Loads, Stores and PHINodes. 4380 if (!isa<LoadInst>(it) && !isa<StoreInst>(it) && !isa<PHINode>(it)) 4381 continue; 4382 4383 // Examine PHI nodes that are reduction variables. 4384 if (PHINode *PN = dyn_cast<PHINode>(it)) 4385 if (!Legal->getReductionVars()->count(PN)) 4386 continue; 4387 4388 // Examine the stored values. 4389 if (StoreInst *ST = dyn_cast<StoreInst>(it)) 4390 T = ST->getValueOperand()->getType(); 4391 4392 // Ignore loaded pointer types and stored pointer types that are not 4393 // consecutive. However, we do want to take consecutive stores/loads of 4394 // pointer vectors into account. 4395 if (T->isPointerTy() && !isConsecutiveLoadOrStore(it)) 4396 continue; 4397 4398 MaxWidth = std::max(MaxWidth, 4399 (unsigned)DL->getTypeSizeInBits(T->getScalarType())); 4400 } 4401 } 4402 4403 return MaxWidth; 4404 } 4405 4406 unsigned 4407 LoopVectorizationCostModel::selectUnrollFactor(bool OptForSize, 4408 unsigned VF, 4409 unsigned LoopCost) { 4410 4411 // -- The unroll heuristics -- 4412 // We unroll the loop in order to expose ILP and reduce the loop overhead. 4413 // There are many micro-architectural considerations that we can't predict 4414 // at this level. For example, frontend pressure (on decode or fetch) due to 4415 // code size, or the number and capabilities of the execution ports. 4416 // 4417 // We use the following heuristics to select the unroll factor: 4418 // 1. If the code has reductions, then we unroll in order to break the cross 4419 // iteration dependency. 4420 // 2. If the loop is really small, then we unroll in order to reduce the loop 4421 // overhead. 4422 // 3. We don't unroll if we think that we will spill registers to memory due 4423 // to the increased register pressure. 4424 4425 // Use the user preference, unless 'auto' is selected. 4426 int UserUF = Hints->getInterleave(); 4427 if (UserUF != 0) 4428 return UserUF; 4429 4430 // When we optimize for size, we don't unroll. 4431 if (OptForSize) 4432 return 1; 4433 4434 // We used the distance for the unroll factor. 4435 if (Legal->getMaxSafeDepDistBytes() != -1U) 4436 return 1; 4437 4438 // Do not unroll loops with a relatively small trip count. 4439 unsigned TC = SE->getSmallConstantTripCount(TheLoop); 4440 if (TC > 1 && TC < TinyTripCountUnrollThreshold) 4441 return 1; 4442 4443 unsigned TargetNumRegisters = TTI.getNumberOfRegisters(VF > 1); 4444 DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters << 4445 " registers\n"); 4446 4447 if (VF == 1) { 4448 if (ForceTargetNumScalarRegs.getNumOccurrences() > 0) 4449 TargetNumRegisters = ForceTargetNumScalarRegs; 4450 } else { 4451 if (ForceTargetNumVectorRegs.getNumOccurrences() > 0) 4452 TargetNumRegisters = ForceTargetNumVectorRegs; 4453 } 4454 4455 LoopVectorizationCostModel::RegisterUsage R = calculateRegisterUsage(); 4456 // We divide by these constants so assume that we have at least one 4457 // instruction that uses at least one register. 4458 R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U); 4459 R.NumInstructions = std::max(R.NumInstructions, 1U); 4460 4461 // We calculate the unroll factor using the following formula. 4462 // Subtract the number of loop invariants from the number of available 4463 // registers. These registers are used by all of the unrolled instances. 4464 // Next, divide the remaining registers by the number of registers that is 4465 // required by the loop, in order to estimate how many parallel instances 4466 // fit without causing spills. All of this is rounded down if necessary to be 4467 // a power of two. We want power of two unroll factors to simplify any 4468 // addressing operations or alignment considerations. 4469 unsigned UF = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs) / 4470 R.MaxLocalUsers); 4471 4472 // Don't count the induction variable as unrolled. 4473 if (EnableIndVarRegisterHeur) 4474 UF = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs - 1) / 4475 std::max(1U, (R.MaxLocalUsers - 1))); 4476 4477 // Clamp the unroll factor ranges to reasonable factors. 4478 unsigned MaxInterleaveSize = TTI.getMaxInterleaveFactor(); 4479 4480 // Check if the user has overridden the unroll max. 4481 if (VF == 1) { 4482 if (ForceTargetMaxScalarInterleaveFactor.getNumOccurrences() > 0) 4483 MaxInterleaveSize = ForceTargetMaxScalarInterleaveFactor; 4484 } else { 4485 if (ForceTargetMaxVectorInterleaveFactor.getNumOccurrences() > 0) 4486 MaxInterleaveSize = ForceTargetMaxVectorInterleaveFactor; 4487 } 4488 4489 // If we did not calculate the cost for VF (because the user selected the VF) 4490 // then we calculate the cost of VF here. 4491 if (LoopCost == 0) 4492 LoopCost = expectedCost(VF); 4493 4494 // Clamp the calculated UF to be between the 1 and the max unroll factor 4495 // that the target allows. 4496 if (UF > MaxInterleaveSize) 4497 UF = MaxInterleaveSize; 4498 else if (UF < 1) 4499 UF = 1; 4500 4501 // Unroll if we vectorized this loop and there is a reduction that could 4502 // benefit from unrolling. 4503 if (VF > 1 && Legal->getReductionVars()->size()) { 4504 DEBUG(dbgs() << "LV: Unrolling because of reductions.\n"); 4505 return UF; 4506 } 4507 4508 // Note that if we've already vectorized the loop we will have done the 4509 // runtime check and so unrolling won't require further checks. 4510 bool UnrollingRequiresRuntimePointerCheck = 4511 (VF == 1 && Legal->getRuntimePointerCheck()->Need); 4512 4513 // We want to unroll small loops in order to reduce the loop overhead and 4514 // potentially expose ILP opportunities. 4515 DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n'); 4516 if (!UnrollingRequiresRuntimePointerCheck && 4517 LoopCost < SmallLoopCost) { 4518 // We assume that the cost overhead is 1 and we use the cost model 4519 // to estimate the cost of the loop and unroll until the cost of the 4520 // loop overhead is about 5% of the cost of the loop. 4521 unsigned SmallUF = std::min(UF, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost)); 4522 4523 // Unroll until store/load ports (estimated by max unroll factor) are 4524 // saturated. 4525 unsigned NumStores = Legal->getNumStores(); 4526 unsigned NumLoads = Legal->getNumLoads(); 4527 unsigned StoresUF = UF / (NumStores ? NumStores : 1); 4528 unsigned LoadsUF = UF / (NumLoads ? NumLoads : 1); 4529 4530 // If we have a scalar reduction (vector reductions are already dealt with 4531 // by this point), we can increase the critical path length if the loop 4532 // we're unrolling is inside another loop. Limit, by default to 2, so the 4533 // critical path only gets increased by one reduction operation. 4534 if (Legal->getReductionVars()->size() && 4535 TheLoop->getLoopDepth() > 1) { 4536 unsigned F = static_cast<unsigned>(MaxNestedScalarReductionUF); 4537 SmallUF = std::min(SmallUF, F); 4538 StoresUF = std::min(StoresUF, F); 4539 LoadsUF = std::min(LoadsUF, F); 4540 } 4541 4542 if (EnableLoadStoreRuntimeUnroll && std::max(StoresUF, LoadsUF) > SmallUF) { 4543 DEBUG(dbgs() << "LV: Unrolling to saturate store or load ports.\n"); 4544 return std::max(StoresUF, LoadsUF); 4545 } 4546 4547 DEBUG(dbgs() << "LV: Unrolling to reduce branch cost.\n"); 4548 return SmallUF; 4549 } 4550 4551 DEBUG(dbgs() << "LV: Not Unrolling.\n"); 4552 return 1; 4553 } 4554 4555 LoopVectorizationCostModel::RegisterUsage 4556 LoopVectorizationCostModel::calculateRegisterUsage() { 4557 // This function calculates the register usage by measuring the highest number 4558 // of values that are alive at a single location. Obviously, this is a very 4559 // rough estimation. We scan the loop in a topological order in order and 4560 // assign a number to each instruction. We use RPO to ensure that defs are 4561 // met before their users. We assume that each instruction that has in-loop 4562 // users starts an interval. We record every time that an in-loop value is 4563 // used, so we have a list of the first and last occurrences of each 4564 // instruction. Next, we transpose this data structure into a multi map that 4565 // holds the list of intervals that *end* at a specific location. This multi 4566 // map allows us to perform a linear search. We scan the instructions linearly 4567 // and record each time that a new interval starts, by placing it in a set. 4568 // If we find this value in the multi-map then we remove it from the set. 4569 // The max register usage is the maximum size of the set. 4570 // We also search for instructions that are defined outside the loop, but are 4571 // used inside the loop. We need this number separately from the max-interval 4572 // usage number because when we unroll, loop-invariant values do not take 4573 // more register. 4574 LoopBlocksDFS DFS(TheLoop); 4575 DFS.perform(LI); 4576 4577 RegisterUsage R; 4578 R.NumInstructions = 0; 4579 4580 // Each 'key' in the map opens a new interval. The values 4581 // of the map are the index of the 'last seen' usage of the 4582 // instruction that is the key. 4583 typedef DenseMap<Instruction*, unsigned> IntervalMap; 4584 // Maps instruction to its index. 4585 DenseMap<unsigned, Instruction*> IdxToInstr; 4586 // Marks the end of each interval. 4587 IntervalMap EndPoint; 4588 // Saves the list of instruction indices that are used in the loop. 4589 SmallSet<Instruction*, 8> Ends; 4590 // Saves the list of values that are used in the loop but are 4591 // defined outside the loop, such as arguments and constants. 4592 SmallPtrSet<Value*, 8> LoopInvariants; 4593 4594 unsigned Index = 0; 4595 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(), 4596 be = DFS.endRPO(); bb != be; ++bb) { 4597 R.NumInstructions += (*bb)->size(); 4598 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e; 4599 ++it) { 4600 Instruction *I = it; 4601 IdxToInstr[Index++] = I; 4602 4603 // Save the end location of each USE. 4604 for (unsigned i = 0; i < I->getNumOperands(); ++i) { 4605 Value *U = I->getOperand(i); 4606 Instruction *Instr = dyn_cast<Instruction>(U); 4607 4608 // Ignore non-instruction values such as arguments, constants, etc. 4609 if (!Instr) continue; 4610 4611 // If this instruction is outside the loop then record it and continue. 4612 if (!TheLoop->contains(Instr)) { 4613 LoopInvariants.insert(Instr); 4614 continue; 4615 } 4616 4617 // Overwrite previous end points. 4618 EndPoint[Instr] = Index; 4619 Ends.insert(Instr); 4620 } 4621 } 4622 } 4623 4624 // Saves the list of intervals that end with the index in 'key'. 4625 typedef SmallVector<Instruction*, 2> InstrList; 4626 DenseMap<unsigned, InstrList> TransposeEnds; 4627 4628 // Transpose the EndPoints to a list of values that end at each index. 4629 for (IntervalMap::iterator it = EndPoint.begin(), e = EndPoint.end(); 4630 it != e; ++it) 4631 TransposeEnds[it->second].push_back(it->first); 4632 4633 SmallSet<Instruction*, 8> OpenIntervals; 4634 unsigned MaxUsage = 0; 4635 4636 4637 DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n"); 4638 for (unsigned int i = 0; i < Index; ++i) { 4639 Instruction *I = IdxToInstr[i]; 4640 // Ignore instructions that are never used within the loop. 4641 if (!Ends.count(I)) continue; 4642 4643 // Ignore ephemeral values. 4644 if (EphValues.count(I)) 4645 continue; 4646 4647 // Remove all of the instructions that end at this location. 4648 InstrList &List = TransposeEnds[i]; 4649 for (unsigned int j=0, e = List.size(); j < e; ++j) 4650 OpenIntervals.erase(List[j]); 4651 4652 // Count the number of live interals. 4653 MaxUsage = std::max(MaxUsage, OpenIntervals.size()); 4654 4655 DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # " << 4656 OpenIntervals.size() << '\n'); 4657 4658 // Add the current instruction to the list of open intervals. 4659 OpenIntervals.insert(I); 4660 } 4661 4662 unsigned Invariant = LoopInvariants.size(); 4663 DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsage << '\n'); 4664 DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << '\n'); 4665 DEBUG(dbgs() << "LV(REG): LoopSize: " << R.NumInstructions << '\n'); 4666 4667 R.LoopInvariantRegs = Invariant; 4668 R.MaxLocalUsers = MaxUsage; 4669 return R; 4670 } 4671 4672 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) { 4673 unsigned Cost = 0; 4674 4675 // For each block. 4676 for (Loop::block_iterator bb = TheLoop->block_begin(), 4677 be = TheLoop->block_end(); bb != be; ++bb) { 4678 unsigned BlockCost = 0; 4679 BasicBlock *BB = *bb; 4680 4681 // For each instruction in the old loop. 4682 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) { 4683 // Skip dbg intrinsics. 4684 if (isa<DbgInfoIntrinsic>(it)) 4685 continue; 4686 4687 // Ignore ephemeral values. 4688 if (EphValues.count(it)) 4689 continue; 4690 4691 unsigned C = getInstructionCost(it, VF); 4692 4693 // Check if we should override the cost. 4694 if (ForceTargetInstructionCost.getNumOccurrences() > 0) 4695 C = ForceTargetInstructionCost; 4696 4697 BlockCost += C; 4698 DEBUG(dbgs() << "LV: Found an estimated cost of " << C << " for VF " << 4699 VF << " For instruction: " << *it << '\n'); 4700 } 4701 4702 // We assume that if-converted blocks have a 50% chance of being executed. 4703 // When the code is scalar then some of the blocks are avoided due to CF. 4704 // When the code is vectorized we execute all code paths. 4705 if (VF == 1 && Legal->blockNeedsPredication(*bb)) 4706 BlockCost /= 2; 4707 4708 Cost += BlockCost; 4709 } 4710 4711 return Cost; 4712 } 4713 4714 /// \brief Check whether the address computation for a non-consecutive memory 4715 /// access looks like an unlikely candidate for being merged into the indexing 4716 /// mode. 4717 /// 4718 /// We look for a GEP which has one index that is an induction variable and all 4719 /// other indices are loop invariant. If the stride of this access is also 4720 /// within a small bound we decide that this address computation can likely be 4721 /// merged into the addressing mode. 4722 /// In all other cases, we identify the address computation as complex. 4723 static bool isLikelyComplexAddressComputation(Value *Ptr, 4724 LoopVectorizationLegality *Legal, 4725 ScalarEvolution *SE, 4726 const Loop *TheLoop) { 4727 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr); 4728 if (!Gep) 4729 return true; 4730 4731 // We are looking for a gep with all loop invariant indices except for one 4732 // which should be an induction variable. 4733 unsigned NumOperands = Gep->getNumOperands(); 4734 for (unsigned i = 1; i < NumOperands; ++i) { 4735 Value *Opd = Gep->getOperand(i); 4736 if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) && 4737 !Legal->isInductionVariable(Opd)) 4738 return true; 4739 } 4740 4741 // Now we know we have a GEP ptr, %inv, %ind, %inv. Make sure that the step 4742 // can likely be merged into the address computation. 4743 unsigned MaxMergeDistance = 64; 4744 4745 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Ptr)); 4746 if (!AddRec) 4747 return true; 4748 4749 // Check the step is constant. 4750 const SCEV *Step = AddRec->getStepRecurrence(*SE); 4751 // Calculate the pointer stride and check if it is consecutive. 4752 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step); 4753 if (!C) 4754 return true; 4755 4756 const APInt &APStepVal = C->getValue()->getValue(); 4757 4758 // Huge step value - give up. 4759 if (APStepVal.getBitWidth() > 64) 4760 return true; 4761 4762 int64_t StepVal = APStepVal.getSExtValue(); 4763 4764 return StepVal > MaxMergeDistance; 4765 } 4766 4767 static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) { 4768 if (Legal->hasStride(I->getOperand(0)) || Legal->hasStride(I->getOperand(1))) 4769 return true; 4770 return false; 4771 } 4772 4773 unsigned 4774 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) { 4775 // If we know that this instruction will remain uniform, check the cost of 4776 // the scalar version. 4777 if (Legal->isUniformAfterVectorization(I)) 4778 VF = 1; 4779 4780 Type *RetTy = I->getType(); 4781 Type *VectorTy = ToVectorTy(RetTy, VF); 4782 4783 // TODO: We need to estimate the cost of intrinsic calls. 4784 switch (I->getOpcode()) { 4785 case Instruction::GetElementPtr: 4786 // We mark this instruction as zero-cost because the cost of GEPs in 4787 // vectorized code depends on whether the corresponding memory instruction 4788 // is scalarized or not. Therefore, we handle GEPs with the memory 4789 // instruction cost. 4790 return 0; 4791 case Instruction::Br: { 4792 return TTI.getCFInstrCost(I->getOpcode()); 4793 } 4794 case Instruction::PHI: 4795 //TODO: IF-converted IFs become selects. 4796 return 0; 4797 case Instruction::Add: 4798 case Instruction::FAdd: 4799 case Instruction::Sub: 4800 case Instruction::FSub: 4801 case Instruction::Mul: 4802 case Instruction::FMul: 4803 case Instruction::UDiv: 4804 case Instruction::SDiv: 4805 case Instruction::FDiv: 4806 case Instruction::URem: 4807 case Instruction::SRem: 4808 case Instruction::FRem: 4809 case Instruction::Shl: 4810 case Instruction::LShr: 4811 case Instruction::AShr: 4812 case Instruction::And: 4813 case Instruction::Or: 4814 case Instruction::Xor: { 4815 // Since we will replace the stride by 1 the multiplication should go away. 4816 if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal)) 4817 return 0; 4818 // Certain instructions can be cheaper to vectorize if they have a constant 4819 // second vector operand. One example of this are shifts on x86. 4820 TargetTransformInfo::OperandValueKind Op1VK = 4821 TargetTransformInfo::OK_AnyValue; 4822 TargetTransformInfo::OperandValueKind Op2VK = 4823 TargetTransformInfo::OK_AnyValue; 4824 TargetTransformInfo::OperandValueProperties Op1VP = 4825 TargetTransformInfo::OP_None; 4826 TargetTransformInfo::OperandValueProperties Op2VP = 4827 TargetTransformInfo::OP_None; 4828 Value *Op2 = I->getOperand(1); 4829 4830 // Check for a splat of a constant or for a non uniform vector of constants. 4831 if (isa<ConstantInt>(Op2)) { 4832 ConstantInt *CInt = cast<ConstantInt>(Op2); 4833 if (CInt && CInt->getValue().isPowerOf2()) 4834 Op2VP = TargetTransformInfo::OP_PowerOf2; 4835 Op2VK = TargetTransformInfo::OK_UniformConstantValue; 4836 } else if (isa<ConstantVector>(Op2) || isa<ConstantDataVector>(Op2)) { 4837 Op2VK = TargetTransformInfo::OK_NonUniformConstantValue; 4838 Constant *SplatValue = cast<Constant>(Op2)->getSplatValue(); 4839 if (SplatValue) { 4840 ConstantInt *CInt = dyn_cast<ConstantInt>(SplatValue); 4841 if (CInt && CInt->getValue().isPowerOf2()) 4842 Op2VP = TargetTransformInfo::OP_PowerOf2; 4843 Op2VK = TargetTransformInfo::OK_UniformConstantValue; 4844 } 4845 } 4846 4847 return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy, Op1VK, Op2VK, 4848 Op1VP, Op2VP); 4849 } 4850 case Instruction::Select: { 4851 SelectInst *SI = cast<SelectInst>(I); 4852 const SCEV *CondSCEV = SE->getSCEV(SI->getCondition()); 4853 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop)); 4854 Type *CondTy = SI->getCondition()->getType(); 4855 if (!ScalarCond) 4856 CondTy = VectorType::get(CondTy, VF); 4857 4858 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy); 4859 } 4860 case Instruction::ICmp: 4861 case Instruction::FCmp: { 4862 Type *ValTy = I->getOperand(0)->getType(); 4863 VectorTy = ToVectorTy(ValTy, VF); 4864 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy); 4865 } 4866 case Instruction::Store: 4867 case Instruction::Load: { 4868 StoreInst *SI = dyn_cast<StoreInst>(I); 4869 LoadInst *LI = dyn_cast<LoadInst>(I); 4870 Type *ValTy = (SI ? SI->getValueOperand()->getType() : 4871 LI->getType()); 4872 VectorTy = ToVectorTy(ValTy, VF); 4873 4874 unsigned Alignment = SI ? SI->getAlignment() : LI->getAlignment(); 4875 unsigned AS = SI ? SI->getPointerAddressSpace() : 4876 LI->getPointerAddressSpace(); 4877 Value *Ptr = SI ? SI->getPointerOperand() : LI->getPointerOperand(); 4878 // We add the cost of address computation here instead of with the gep 4879 // instruction because only here we know whether the operation is 4880 // scalarized. 4881 if (VF == 1) 4882 return TTI.getAddressComputationCost(VectorTy) + 4883 TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS); 4884 4885 // Scalarized loads/stores. 4886 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr); 4887 bool Reverse = ConsecutiveStride < 0; 4888 unsigned ScalarAllocatedSize = DL->getTypeAllocSize(ValTy); 4889 unsigned VectorElementSize = DL->getTypeStoreSize(VectorTy)/VF; 4890 if (!ConsecutiveStride || ScalarAllocatedSize != VectorElementSize) { 4891 bool IsComplexComputation = 4892 isLikelyComplexAddressComputation(Ptr, Legal, SE, TheLoop); 4893 unsigned Cost = 0; 4894 // The cost of extracting from the value vector and pointer vector. 4895 Type *PtrTy = ToVectorTy(Ptr->getType(), VF); 4896 for (unsigned i = 0; i < VF; ++i) { 4897 // The cost of extracting the pointer operand. 4898 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i); 4899 // In case of STORE, the cost of ExtractElement from the vector. 4900 // In case of LOAD, the cost of InsertElement into the returned 4901 // vector. 4902 Cost += TTI.getVectorInstrCost(SI ? Instruction::ExtractElement : 4903 Instruction::InsertElement, 4904 VectorTy, i); 4905 } 4906 4907 // The cost of the scalar loads/stores. 4908 Cost += VF * TTI.getAddressComputationCost(PtrTy, IsComplexComputation); 4909 Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(), 4910 Alignment, AS); 4911 return Cost; 4912 } 4913 4914 // Wide load/stores. 4915 unsigned Cost = TTI.getAddressComputationCost(VectorTy); 4916 Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS); 4917 4918 if (Reverse) 4919 Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, 4920 VectorTy, 0); 4921 return Cost; 4922 } 4923 case Instruction::ZExt: 4924 case Instruction::SExt: 4925 case Instruction::FPToUI: 4926 case Instruction::FPToSI: 4927 case Instruction::FPExt: 4928 case Instruction::PtrToInt: 4929 case Instruction::IntToPtr: 4930 case Instruction::SIToFP: 4931 case Instruction::UIToFP: 4932 case Instruction::Trunc: 4933 case Instruction::FPTrunc: 4934 case Instruction::BitCast: { 4935 // We optimize the truncation of induction variable. 4936 // The cost of these is the same as the scalar operation. 4937 if (I->getOpcode() == Instruction::Trunc && 4938 Legal->isInductionVariable(I->getOperand(0))) 4939 return TTI.getCastInstrCost(I->getOpcode(), I->getType(), 4940 I->getOperand(0)->getType()); 4941 4942 Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF); 4943 return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy); 4944 } 4945 case Instruction::Call: { 4946 CallInst *CI = cast<CallInst>(I); 4947 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI); 4948 assert(ID && "Not an intrinsic call!"); 4949 Type *RetTy = ToVectorTy(CI->getType(), VF); 4950 SmallVector<Type*, 4> Tys; 4951 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) 4952 Tys.push_back(ToVectorTy(CI->getArgOperand(i)->getType(), VF)); 4953 return TTI.getIntrinsicInstrCost(ID, RetTy, Tys); 4954 } 4955 default: { 4956 // We are scalarizing the instruction. Return the cost of the scalar 4957 // instruction, plus the cost of insert and extract into vector 4958 // elements, times the vector width. 4959 unsigned Cost = 0; 4960 4961 if (!RetTy->isVoidTy() && VF != 1) { 4962 unsigned InsCost = TTI.getVectorInstrCost(Instruction::InsertElement, 4963 VectorTy); 4964 unsigned ExtCost = TTI.getVectorInstrCost(Instruction::ExtractElement, 4965 VectorTy); 4966 4967 // The cost of inserting the results plus extracting each one of the 4968 // operands. 4969 Cost += VF * (InsCost + ExtCost * I->getNumOperands()); 4970 } 4971 4972 // The cost of executing VF copies of the scalar instruction. This opcode 4973 // is unknown. Assume that it is the same as 'mul'. 4974 Cost += VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy); 4975 return Cost; 4976 } 4977 }// end of switch. 4978 } 4979 4980 Type* LoopVectorizationCostModel::ToVectorTy(Type *Scalar, unsigned VF) { 4981 if (Scalar->isVoidTy() || VF == 1) 4982 return Scalar; 4983 return VectorType::get(Scalar, VF); 4984 } 4985 4986 char LoopVectorize::ID = 0; 4987 static const char lv_name[] = "Loop Vectorization"; 4988 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false) 4989 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 4990 INITIALIZE_AG_DEPENDENCY(AliasAnalysis) 4991 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 4992 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfo) 4993 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 4994 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution) 4995 INITIALIZE_PASS_DEPENDENCY(LCSSA) 4996 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 4997 INITIALIZE_PASS_DEPENDENCY(LoopSimplify) 4998 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false) 4999 5000 namespace llvm { 5001 Pass *createLoopVectorizePass(bool NoUnrolling, bool AlwaysVectorize) { 5002 return new LoopVectorize(NoUnrolling, AlwaysVectorize); 5003 } 5004 } 5005 5006 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) { 5007 // Check for a store. 5008 if (StoreInst *ST = dyn_cast<StoreInst>(Inst)) 5009 return Legal->isConsecutivePtr(ST->getPointerOperand()) != 0; 5010 5011 // Check for a load. 5012 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) 5013 return Legal->isConsecutivePtr(LI->getPointerOperand()) != 0; 5014 5015 return false; 5016 } 5017 5018 5019 void InnerLoopUnroller::scalarizeInstruction(Instruction *Instr, 5020 bool IfPredicateStore) { 5021 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors"); 5022 // Holds vector parameters or scalars, in case of uniform vals. 5023 SmallVector<VectorParts, 4> Params; 5024 5025 setDebugLocFromInst(Builder, Instr); 5026 5027 // Find all of the vectorized parameters. 5028 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) { 5029 Value *SrcOp = Instr->getOperand(op); 5030 5031 // If we are accessing the old induction variable, use the new one. 5032 if (SrcOp == OldInduction) { 5033 Params.push_back(getVectorValue(SrcOp)); 5034 continue; 5035 } 5036 5037 // Try using previously calculated values. 5038 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp); 5039 5040 // If the src is an instruction that appeared earlier in the basic block 5041 // then it should already be vectorized. 5042 if (SrcInst && OrigLoop->contains(SrcInst)) { 5043 assert(WidenMap.has(SrcInst) && "Source operand is unavailable"); 5044 // The parameter is a vector value from earlier. 5045 Params.push_back(WidenMap.get(SrcInst)); 5046 } else { 5047 // The parameter is a scalar from outside the loop. Maybe even a constant. 5048 VectorParts Scalars; 5049 Scalars.append(UF, SrcOp); 5050 Params.push_back(Scalars); 5051 } 5052 } 5053 5054 assert(Params.size() == Instr->getNumOperands() && 5055 "Invalid number of operands"); 5056 5057 // Does this instruction return a value ? 5058 bool IsVoidRetTy = Instr->getType()->isVoidTy(); 5059 5060 Value *UndefVec = IsVoidRetTy ? nullptr : 5061 UndefValue::get(Instr->getType()); 5062 // Create a new entry in the WidenMap and initialize it to Undef or Null. 5063 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec); 5064 5065 Instruction *InsertPt = Builder.GetInsertPoint(); 5066 BasicBlock *IfBlock = Builder.GetInsertBlock(); 5067 BasicBlock *CondBlock = nullptr; 5068 5069 VectorParts Cond; 5070 Loop *VectorLp = nullptr; 5071 if (IfPredicateStore) { 5072 assert(Instr->getParent()->getSinglePredecessor() && 5073 "Only support single predecessor blocks"); 5074 Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(), 5075 Instr->getParent()); 5076 VectorLp = LI->getLoopFor(IfBlock); 5077 assert(VectorLp && "Must have a loop for this block"); 5078 } 5079 5080 // For each vector unroll 'part': 5081 for (unsigned Part = 0; Part < UF; ++Part) { 5082 // For each scalar that we create: 5083 5084 // Start an "if (pred) a[i] = ..." block. 5085 Value *Cmp = nullptr; 5086 if (IfPredicateStore) { 5087 if (Cond[Part]->getType()->isVectorTy()) 5088 Cond[Part] = 5089 Builder.CreateExtractElement(Cond[Part], Builder.getInt32(0)); 5090 Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cond[Part], 5091 ConstantInt::get(Cond[Part]->getType(), 1)); 5092 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store"); 5093 LoopVectorBody.push_back(CondBlock); 5094 VectorLp->addBasicBlockToLoop(CondBlock, *LI); 5095 // Update Builder with newly created basic block. 5096 Builder.SetInsertPoint(InsertPt); 5097 } 5098 5099 Instruction *Cloned = Instr->clone(); 5100 if (!IsVoidRetTy) 5101 Cloned->setName(Instr->getName() + ".cloned"); 5102 // Replace the operands of the cloned instructions with extracted scalars. 5103 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) { 5104 Value *Op = Params[op][Part]; 5105 Cloned->setOperand(op, Op); 5106 } 5107 5108 // Place the cloned scalar in the new loop. 5109 Builder.Insert(Cloned); 5110 5111 // If the original scalar returns a value we need to place it in a vector 5112 // so that future users will be able to use it. 5113 if (!IsVoidRetTy) 5114 VecResults[Part] = Cloned; 5115 5116 // End if-block. 5117 if (IfPredicateStore) { 5118 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else"); 5119 LoopVectorBody.push_back(NewIfBlock); 5120 VectorLp->addBasicBlockToLoop(NewIfBlock, *LI); 5121 Builder.SetInsertPoint(InsertPt); 5122 Instruction *OldBr = IfBlock->getTerminator(); 5123 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr); 5124 OldBr->eraseFromParent(); 5125 IfBlock = NewIfBlock; 5126 } 5127 } 5128 } 5129 5130 void InnerLoopUnroller::vectorizeMemoryInstruction(Instruction *Instr) { 5131 StoreInst *SI = dyn_cast<StoreInst>(Instr); 5132 bool IfPredicateStore = (SI && Legal->blockNeedsPredication(SI->getParent())); 5133 5134 return scalarizeInstruction(Instr, IfPredicateStore); 5135 } 5136 5137 Value *InnerLoopUnroller::reverseVector(Value *Vec) { 5138 return Vec; 5139 } 5140 5141 Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) { 5142 return V; 5143 } 5144 5145 Value *InnerLoopUnroller::getStepVector(Value *Val, int StartIdx, Value *Step) { 5146 // When unrolling and the VF is 1, we only need to add a simple scalar. 5147 Type *ITy = Val->getType(); 5148 assert(!ITy->isVectorTy() && "Val must be a scalar"); 5149 Constant *C = ConstantInt::get(ITy, StartIdx); 5150 return Builder.CreateAdd(Val, Builder.CreateMul(C, Step), "induction"); 5151 } 5152