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