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