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, 1224 DataTy->getPointerTo(AddressSpace)); 1225 Builder.CreateStore(StoredVal[Part], VecPtr)->setAlignment(Alignment); 1226 } 1227 return; 1228 } 1229 1230 // Handle loads. 1231 assert(LI && "Must have a load instruction"); 1232 setDebugLocFromInst(Builder, LI); 1233 for (unsigned Part = 0; Part < UF; ++Part) { 1234 // Calculate the pointer for the specific unroll-part. 1235 Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF)); 1236 1237 if (Reverse) { 1238 // If the address is consecutive but reversed, then the 1239 // wide store needs to start at the last vector element. 1240 PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF)); 1241 PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF)); 1242 } 1243 1244 Value *VecPtr = Builder.CreateBitCast(PartPtr, 1245 DataTy->getPointerTo(AddressSpace)); 1246 Value *LI = Builder.CreateLoad(VecPtr, "wide.load"); 1247 cast<LoadInst>(LI)->setAlignment(Alignment); 1248 Entry[Part] = Reverse ? reverseVector(LI) : LI; 1249 } 1250 } 1251 1252 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr) { 1253 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors"); 1254 // Holds vector parameters or scalars, in case of uniform vals. 1255 SmallVector<VectorParts, 4> Params; 1256 1257 setDebugLocFromInst(Builder, Instr); 1258 1259 // Find all of the vectorized parameters. 1260 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) { 1261 Value *SrcOp = Instr->getOperand(op); 1262 1263 // If we are accessing the old induction variable, use the new one. 1264 if (SrcOp == OldInduction) { 1265 Params.push_back(getVectorValue(SrcOp)); 1266 continue; 1267 } 1268 1269 // Try using previously calculated values. 1270 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp); 1271 1272 // If the src is an instruction that appeared earlier in the basic block 1273 // then it should already be vectorized. 1274 if (SrcInst && OrigLoop->contains(SrcInst)) { 1275 assert(WidenMap.has(SrcInst) && "Source operand is unavailable"); 1276 // The parameter is a vector value from earlier. 1277 Params.push_back(WidenMap.get(SrcInst)); 1278 } else { 1279 // The parameter is a scalar from outside the loop. Maybe even a constant. 1280 VectorParts Scalars; 1281 Scalars.append(UF, SrcOp); 1282 Params.push_back(Scalars); 1283 } 1284 } 1285 1286 assert(Params.size() == Instr->getNumOperands() && 1287 "Invalid number of operands"); 1288 1289 // Does this instruction return a value ? 1290 bool IsVoidRetTy = Instr->getType()->isVoidTy(); 1291 1292 Value *UndefVec = IsVoidRetTy ? 0 : 1293 UndefValue::get(VectorType::get(Instr->getType(), VF)); 1294 // Create a new entry in the WidenMap and initialize it to Undef or Null. 1295 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec); 1296 1297 // For each vector unroll 'part': 1298 for (unsigned Part = 0; Part < UF; ++Part) { 1299 // For each scalar that we create: 1300 for (unsigned Width = 0; Width < VF; ++Width) { 1301 Instruction *Cloned = Instr->clone(); 1302 if (!IsVoidRetTy) 1303 Cloned->setName(Instr->getName() + ".cloned"); 1304 // Replace the operands of the cloned instrucions with extracted scalars. 1305 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) { 1306 Value *Op = Params[op][Part]; 1307 // Param is a vector. Need to extract the right lane. 1308 if (Op->getType()->isVectorTy()) 1309 Op = Builder.CreateExtractElement(Op, Builder.getInt32(Width)); 1310 Cloned->setOperand(op, Op); 1311 } 1312 1313 // Place the cloned scalar in the new loop. 1314 Builder.Insert(Cloned); 1315 1316 // If the original scalar returns a value we need to place it in a vector 1317 // so that future users will be able to use it. 1318 if (!IsVoidRetTy) 1319 VecResults[Part] = Builder.CreateInsertElement(VecResults[Part], Cloned, 1320 Builder.getInt32(Width)); 1321 } 1322 } 1323 } 1324 1325 Instruction * 1326 InnerLoopVectorizer::addRuntimeCheck(LoopVectorizationLegality *Legal, 1327 Instruction *Loc) { 1328 LoopVectorizationLegality::RuntimePointerCheck *PtrRtCheck = 1329 Legal->getRuntimePointerCheck(); 1330 1331 if (!PtrRtCheck->Need) 1332 return NULL; 1333 1334 unsigned NumPointers = PtrRtCheck->Pointers.size(); 1335 SmallVector<TrackingVH<Value> , 2> Starts; 1336 SmallVector<TrackingVH<Value> , 2> Ends; 1337 1338 SCEVExpander Exp(*SE, "induction"); 1339 1340 // Use this type for pointer arithmetic. 1341 Type* PtrArithTy = Type::getInt8PtrTy(Loc->getContext(), 0); 1342 1343 for (unsigned i = 0; i < NumPointers; ++i) { 1344 Value *Ptr = PtrRtCheck->Pointers[i]; 1345 const SCEV *Sc = SE->getSCEV(Ptr); 1346 1347 if (SE->isLoopInvariant(Sc, OrigLoop)) { 1348 DEBUG(dbgs() << "LV: Adding RT check for a loop invariant ptr:" << 1349 *Ptr <<"\n"); 1350 Starts.push_back(Ptr); 1351 Ends.push_back(Ptr); 1352 } else { 1353 DEBUG(dbgs() << "LV: Adding RT check for range:" << *Ptr <<"\n"); 1354 1355 Value *Start = Exp.expandCodeFor(PtrRtCheck->Starts[i], PtrArithTy, Loc); 1356 Value *End = Exp.expandCodeFor(PtrRtCheck->Ends[i], PtrArithTy, Loc); 1357 Starts.push_back(Start); 1358 Ends.push_back(End); 1359 } 1360 } 1361 1362 IRBuilder<> ChkBuilder(Loc); 1363 // Our instructions might fold to a constant. 1364 Value *MemoryRuntimeCheck = 0; 1365 for (unsigned i = 0; i < NumPointers; ++i) { 1366 for (unsigned j = i+1; j < NumPointers; ++j) { 1367 // No need to check if two readonly pointers intersect. 1368 if (!PtrRtCheck->IsWritePtr[i] && !PtrRtCheck->IsWritePtr[j]) 1369 continue; 1370 1371 // Only need to check pointers between two different dependency sets. 1372 if (PtrRtCheck->DependencySetId[i] == PtrRtCheck->DependencySetId[j]) 1373 continue; 1374 1375 Value *Start0 = ChkBuilder.CreateBitCast(Starts[i], PtrArithTy, "bc"); 1376 Value *Start1 = ChkBuilder.CreateBitCast(Starts[j], PtrArithTy, "bc"); 1377 Value *End0 = ChkBuilder.CreateBitCast(Ends[i], PtrArithTy, "bc"); 1378 Value *End1 = ChkBuilder.CreateBitCast(Ends[j], PtrArithTy, "bc"); 1379 1380 Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0"); 1381 Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1"); 1382 Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict"); 1383 if (MemoryRuntimeCheck) 1384 IsConflict = ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict, 1385 "conflict.rdx"); 1386 MemoryRuntimeCheck = IsConflict; 1387 } 1388 } 1389 1390 // We have to do this trickery because the IRBuilder might fold the check to a 1391 // constant expression in which case there is no Instruction anchored in a 1392 // the block. 1393 LLVMContext &Ctx = Loc->getContext(); 1394 Instruction * Check = BinaryOperator::CreateAnd(MemoryRuntimeCheck, 1395 ConstantInt::getTrue(Ctx)); 1396 ChkBuilder.Insert(Check, "memcheck.conflict"); 1397 return Check; 1398 } 1399 1400 void 1401 InnerLoopVectorizer::createEmptyLoop(LoopVectorizationLegality *Legal) { 1402 /* 1403 In this function we generate a new loop. The new loop will contain 1404 the vectorized instructions while the old loop will continue to run the 1405 scalar remainder. 1406 1407 [ ] <-- vector loop bypass (may consist of multiple blocks). 1408 / | 1409 / v 1410 | [ ] <-- vector pre header. 1411 | | 1412 | v 1413 | [ ] \ 1414 | [ ]_| <-- vector loop. 1415 | | 1416 \ v 1417 >[ ] <--- middle-block. 1418 / | 1419 / v 1420 | [ ] <--- new preheader. 1421 | | 1422 | v 1423 | [ ] \ 1424 | [ ]_| <-- old scalar loop to handle remainder. 1425 \ | 1426 \ v 1427 >[ ] <-- exit block. 1428 ... 1429 */ 1430 1431 BasicBlock *OldBasicBlock = OrigLoop->getHeader(); 1432 BasicBlock *BypassBlock = OrigLoop->getLoopPreheader(); 1433 BasicBlock *ExitBlock = OrigLoop->getExitBlock(); 1434 assert(ExitBlock && "Must have an exit block"); 1435 1436 // Some loops have a single integer induction variable, while other loops 1437 // don't. One example is c++ iterators that often have multiple pointer 1438 // induction variables. In the code below we also support a case where we 1439 // don't have a single induction variable. 1440 OldInduction = Legal->getInduction(); 1441 Type *IdxTy = Legal->getWidestInductionType(); 1442 1443 // Find the loop boundaries. 1444 const SCEV *ExitCount = SE->getBackedgeTakenCount(OrigLoop); 1445 assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count"); 1446 1447 // Get the total trip count from the count by adding 1. 1448 ExitCount = SE->getAddExpr(ExitCount, 1449 SE->getConstant(ExitCount->getType(), 1)); 1450 1451 // Expand the trip count and place the new instructions in the preheader. 1452 // Notice that the pre-header does not change, only the loop body. 1453 SCEVExpander Exp(*SE, "induction"); 1454 1455 // Count holds the overall loop count (N). 1456 Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(), 1457 BypassBlock->getTerminator()); 1458 1459 // The loop index does not have to start at Zero. Find the original start 1460 // value from the induction PHI node. If we don't have an induction variable 1461 // then we know that it starts at zero. 1462 Builder.SetInsertPoint(BypassBlock->getTerminator()); 1463 Value *StartIdx = ExtendedIdx = OldInduction ? 1464 Builder.CreateZExt(OldInduction->getIncomingValueForBlock(BypassBlock), 1465 IdxTy): 1466 ConstantInt::get(IdxTy, 0); 1467 1468 assert(BypassBlock && "Invalid loop structure"); 1469 LoopBypassBlocks.push_back(BypassBlock); 1470 1471 // Split the single block loop into the two loop structure described above. 1472 BasicBlock *VectorPH = 1473 BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph"); 1474 BasicBlock *VecBody = 1475 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body"); 1476 BasicBlock *MiddleBlock = 1477 VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block"); 1478 BasicBlock *ScalarPH = 1479 MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph"); 1480 1481 // Create and register the new vector loop. 1482 Loop* Lp = new Loop(); 1483 Loop *ParentLoop = OrigLoop->getParentLoop(); 1484 1485 // Insert the new loop into the loop nest and register the new basic blocks 1486 // before calling any utilities such as SCEV that require valid LoopInfo. 1487 if (ParentLoop) { 1488 ParentLoop->addChildLoop(Lp); 1489 ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase()); 1490 ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase()); 1491 ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase()); 1492 } else { 1493 LI->addTopLevelLoop(Lp); 1494 } 1495 Lp->addBasicBlockToLoop(VecBody, LI->getBase()); 1496 1497 // Use this IR builder to create the loop instructions (Phi, Br, Cmp) 1498 // inside the loop. 1499 Builder.SetInsertPoint(VecBody->getFirstInsertionPt()); 1500 1501 // Generate the induction variable. 1502 setDebugLocFromInst(Builder, getDebugLocFromInstOrOperands(OldInduction)); 1503 Induction = Builder.CreatePHI(IdxTy, 2, "index"); 1504 // The loop step is equal to the vectorization factor (num of SIMD elements) 1505 // times the unroll factor (num of SIMD instructions). 1506 Constant *Step = ConstantInt::get(IdxTy, VF * UF); 1507 1508 // This is the IR builder that we use to add all of the logic for bypassing 1509 // the new vector loop. 1510 IRBuilder<> BypassBuilder(BypassBlock->getTerminator()); 1511 setDebugLocFromInst(BypassBuilder, 1512 getDebugLocFromInstOrOperands(OldInduction)); 1513 1514 // We may need to extend the index in case there is a type mismatch. 1515 // We know that the count starts at zero and does not overflow. 1516 if (Count->getType() != IdxTy) { 1517 // The exit count can be of pointer type. Convert it to the correct 1518 // integer type. 1519 if (ExitCount->getType()->isPointerTy()) 1520 Count = BypassBuilder.CreatePointerCast(Count, IdxTy, "ptrcnt.to.int"); 1521 else 1522 Count = BypassBuilder.CreateZExtOrTrunc(Count, IdxTy, "cnt.cast"); 1523 } 1524 1525 // Add the start index to the loop count to get the new end index. 1526 Value *IdxEnd = BypassBuilder.CreateAdd(Count, StartIdx, "end.idx"); 1527 1528 // Now we need to generate the expression for N - (N % VF), which is 1529 // the part that the vectorized body will execute. 1530 Value *R = BypassBuilder.CreateURem(Count, Step, "n.mod.vf"); 1531 Value *CountRoundDown = BypassBuilder.CreateSub(Count, R, "n.vec"); 1532 Value *IdxEndRoundDown = BypassBuilder.CreateAdd(CountRoundDown, StartIdx, 1533 "end.idx.rnd.down"); 1534 1535 // Now, compare the new count to zero. If it is zero skip the vector loop and 1536 // jump to the scalar loop. 1537 Value *Cmp = BypassBuilder.CreateICmpEQ(IdxEndRoundDown, StartIdx, 1538 "cmp.zero"); 1539 1540 BasicBlock *LastBypassBlock = BypassBlock; 1541 1542 // Generate the code that checks in runtime if arrays overlap. We put the 1543 // checks into a separate block to make the more common case of few elements 1544 // faster. 1545 Instruction *MemRuntimeCheck = addRuntimeCheck(Legal, 1546 BypassBlock->getTerminator()); 1547 if (MemRuntimeCheck) { 1548 // Create a new block containing the memory check. 1549 BasicBlock *CheckBlock = BypassBlock->splitBasicBlock(MemRuntimeCheck, 1550 "vector.memcheck"); 1551 if (ParentLoop) 1552 ParentLoop->addBasicBlockToLoop(CheckBlock, LI->getBase()); 1553 LoopBypassBlocks.push_back(CheckBlock); 1554 1555 // Replace the branch into the memory check block with a conditional branch 1556 // for the "few elements case". 1557 Instruction *OldTerm = BypassBlock->getTerminator(); 1558 BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm); 1559 OldTerm->eraseFromParent(); 1560 1561 Cmp = MemRuntimeCheck; 1562 LastBypassBlock = CheckBlock; 1563 } 1564 1565 LastBypassBlock->getTerminator()->eraseFromParent(); 1566 BranchInst::Create(MiddleBlock, VectorPH, Cmp, 1567 LastBypassBlock); 1568 1569 // We are going to resume the execution of the scalar loop. 1570 // Go over all of the induction variables that we found and fix the 1571 // PHIs that are left in the scalar version of the loop. 1572 // The starting values of PHI nodes depend on the counter of the last 1573 // iteration in the vectorized loop. 1574 // If we come from a bypass edge then we need to start from the original 1575 // start value. 1576 1577 // This variable saves the new starting index for the scalar loop. 1578 PHINode *ResumeIndex = 0; 1579 LoopVectorizationLegality::InductionList::iterator I, E; 1580 LoopVectorizationLegality::InductionList *List = Legal->getInductionVars(); 1581 // Set builder to point to last bypass block. 1582 BypassBuilder.SetInsertPoint(LoopBypassBlocks.back()->getTerminator()); 1583 for (I = List->begin(), E = List->end(); I != E; ++I) { 1584 PHINode *OrigPhi = I->first; 1585 LoopVectorizationLegality::InductionInfo II = I->second; 1586 1587 Type *ResumeValTy = (OrigPhi == OldInduction) ? IdxTy : OrigPhi->getType(); 1588 PHINode *ResumeVal = PHINode::Create(ResumeValTy, 2, "resume.val", 1589 MiddleBlock->getTerminator()); 1590 // We might have extended the type of the induction variable but we need a 1591 // truncated version for the scalar loop. 1592 PHINode *TruncResumeVal = (OrigPhi == OldInduction) ? 1593 PHINode::Create(OrigPhi->getType(), 2, "trunc.resume.val", 1594 MiddleBlock->getTerminator()) : 0; 1595 1596 Value *EndValue = 0; 1597 switch (II.IK) { 1598 case LoopVectorizationLegality::IK_NoInduction: 1599 llvm_unreachable("Unknown induction"); 1600 case LoopVectorizationLegality::IK_IntInduction: { 1601 // Handle the integer induction counter. 1602 assert(OrigPhi->getType()->isIntegerTy() && "Invalid type"); 1603 1604 // We have the canonical induction variable. 1605 if (OrigPhi == OldInduction) { 1606 // Create a truncated version of the resume value for the scalar loop, 1607 // we might have promoted the type to a larger width. 1608 EndValue = 1609 BypassBuilder.CreateTrunc(IdxEndRoundDown, OrigPhi->getType()); 1610 // The new PHI merges the original incoming value, in case of a bypass, 1611 // or the value at the end of the vectorized loop. 1612 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I) 1613 TruncResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]); 1614 TruncResumeVal->addIncoming(EndValue, VecBody); 1615 1616 // We know what the end value is. 1617 EndValue = IdxEndRoundDown; 1618 // We also know which PHI node holds it. 1619 ResumeIndex = ResumeVal; 1620 break; 1621 } 1622 1623 // Not the canonical induction variable - add the vector loop count to the 1624 // start value. 1625 Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown, 1626 II.StartValue->getType(), 1627 "cast.crd"); 1628 EndValue = BypassBuilder.CreateAdd(CRD, II.StartValue , "ind.end"); 1629 break; 1630 } 1631 case LoopVectorizationLegality::IK_ReverseIntInduction: { 1632 // Convert the CountRoundDown variable to the PHI size. 1633 Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown, 1634 II.StartValue->getType(), 1635 "cast.crd"); 1636 // Handle reverse integer induction counter. 1637 EndValue = BypassBuilder.CreateSub(II.StartValue, CRD, "rev.ind.end"); 1638 break; 1639 } 1640 case LoopVectorizationLegality::IK_PtrInduction: { 1641 // For pointer induction variables, calculate the offset using 1642 // the end index. 1643 EndValue = BypassBuilder.CreateGEP(II.StartValue, CountRoundDown, 1644 "ptr.ind.end"); 1645 break; 1646 } 1647 case LoopVectorizationLegality::IK_ReversePtrInduction: { 1648 // The value at the end of the loop for the reverse pointer is calculated 1649 // by creating a GEP with a negative index starting from the start value. 1650 Value *Zero = ConstantInt::get(CountRoundDown->getType(), 0); 1651 Value *NegIdx = BypassBuilder.CreateSub(Zero, CountRoundDown, 1652 "rev.ind.end"); 1653 EndValue = BypassBuilder.CreateGEP(II.StartValue, NegIdx, 1654 "rev.ptr.ind.end"); 1655 break; 1656 } 1657 }// end of case 1658 1659 // The new PHI merges the original incoming value, in case of a bypass, 1660 // or the value at the end of the vectorized loop. 1661 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I) { 1662 if (OrigPhi == OldInduction) 1663 ResumeVal->addIncoming(StartIdx, LoopBypassBlocks[I]); 1664 else 1665 ResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]); 1666 } 1667 ResumeVal->addIncoming(EndValue, VecBody); 1668 1669 // Fix the scalar body counter (PHI node). 1670 unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH); 1671 // The old inductions phi node in the scalar body needs the truncated value. 1672 if (OrigPhi == OldInduction) 1673 OrigPhi->setIncomingValue(BlockIdx, TruncResumeVal); 1674 else 1675 OrigPhi->setIncomingValue(BlockIdx, ResumeVal); 1676 } 1677 1678 // If we are generating a new induction variable then we also need to 1679 // generate the code that calculates the exit value. This value is not 1680 // simply the end of the counter because we may skip the vectorized body 1681 // in case of a runtime check. 1682 if (!OldInduction){ 1683 assert(!ResumeIndex && "Unexpected resume value found"); 1684 ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val", 1685 MiddleBlock->getTerminator()); 1686 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I) 1687 ResumeIndex->addIncoming(StartIdx, LoopBypassBlocks[I]); 1688 ResumeIndex->addIncoming(IdxEndRoundDown, VecBody); 1689 } 1690 1691 // Make sure that we found the index where scalar loop needs to continue. 1692 assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() && 1693 "Invalid resume Index"); 1694 1695 // Add a check in the middle block to see if we have completed 1696 // all of the iterations in the first vector loop. 1697 // If (N - N%VF) == N, then we *don't* need to run the remainder. 1698 Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd, 1699 ResumeIndex, "cmp.n", 1700 MiddleBlock->getTerminator()); 1701 1702 BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator()); 1703 // Remove the old terminator. 1704 MiddleBlock->getTerminator()->eraseFromParent(); 1705 1706 // Create i+1 and fill the PHINode. 1707 Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next"); 1708 Induction->addIncoming(StartIdx, VectorPH); 1709 Induction->addIncoming(NextIdx, VecBody); 1710 // Create the compare. 1711 Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown); 1712 Builder.CreateCondBr(ICmp, MiddleBlock, VecBody); 1713 1714 // Now we have two terminators. Remove the old one from the block. 1715 VecBody->getTerminator()->eraseFromParent(); 1716 1717 // Get ready to start creating new instructions into the vectorized body. 1718 Builder.SetInsertPoint(VecBody->getFirstInsertionPt()); 1719 1720 // Save the state. 1721 LoopVectorPreHeader = VectorPH; 1722 LoopScalarPreHeader = ScalarPH; 1723 LoopMiddleBlock = MiddleBlock; 1724 LoopExitBlock = ExitBlock; 1725 LoopVectorBody = VecBody; 1726 LoopScalarBody = OldBasicBlock; 1727 } 1728 1729 /// This function returns the identity element (or neutral element) for 1730 /// the operation K. 1731 Constant* 1732 LoopVectorizationLegality::getReductionIdentity(ReductionKind K, Type *Tp) { 1733 switch (K) { 1734 case RK_IntegerXor: 1735 case RK_IntegerAdd: 1736 case RK_IntegerOr: 1737 // Adding, Xoring, Oring zero to a number does not change it. 1738 return ConstantInt::get(Tp, 0); 1739 case RK_IntegerMult: 1740 // Multiplying a number by 1 does not change it. 1741 return ConstantInt::get(Tp, 1); 1742 case RK_IntegerAnd: 1743 // AND-ing a number with an all-1 value does not change it. 1744 return ConstantInt::get(Tp, -1, true); 1745 case RK_FloatMult: 1746 // Multiplying a number by 1 does not change it. 1747 return ConstantFP::get(Tp, 1.0L); 1748 case RK_FloatAdd: 1749 // Adding zero to a number does not change it. 1750 return ConstantFP::get(Tp, 0.0L); 1751 default: 1752 llvm_unreachable("Unknown reduction kind"); 1753 } 1754 } 1755 1756 static Intrinsic::ID 1757 getIntrinsicIDForCall(CallInst *CI, const TargetLibraryInfo *TLI) { 1758 // If we have an intrinsic call, check if it is trivially vectorizable. 1759 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) { 1760 switch (II->getIntrinsicID()) { 1761 case Intrinsic::sqrt: 1762 case Intrinsic::sin: 1763 case Intrinsic::cos: 1764 case Intrinsic::exp: 1765 case Intrinsic::exp2: 1766 case Intrinsic::log: 1767 case Intrinsic::log10: 1768 case Intrinsic::log2: 1769 case Intrinsic::fabs: 1770 case Intrinsic::floor: 1771 case Intrinsic::ceil: 1772 case Intrinsic::trunc: 1773 case Intrinsic::rint: 1774 case Intrinsic::nearbyint: 1775 case Intrinsic::pow: 1776 case Intrinsic::fma: 1777 case Intrinsic::fmuladd: 1778 case Intrinsic::lifetime_start: 1779 case Intrinsic::lifetime_end: 1780 return II->getIntrinsicID(); 1781 default: 1782 return Intrinsic::not_intrinsic; 1783 } 1784 } 1785 1786 if (!TLI) 1787 return Intrinsic::not_intrinsic; 1788 1789 LibFunc::Func Func; 1790 Function *F = CI->getCalledFunction(); 1791 // We're going to make assumptions on the semantics of the functions, check 1792 // that the target knows that it's available in this environment. 1793 if (!F || !TLI->getLibFunc(F->getName(), Func)) 1794 return Intrinsic::not_intrinsic; 1795 1796 // Otherwise check if we have a call to a function that can be turned into a 1797 // vector intrinsic. 1798 switch (Func) { 1799 default: 1800 break; 1801 case LibFunc::sin: 1802 case LibFunc::sinf: 1803 case LibFunc::sinl: 1804 return Intrinsic::sin; 1805 case LibFunc::cos: 1806 case LibFunc::cosf: 1807 case LibFunc::cosl: 1808 return Intrinsic::cos; 1809 case LibFunc::exp: 1810 case LibFunc::expf: 1811 case LibFunc::expl: 1812 return Intrinsic::exp; 1813 case LibFunc::exp2: 1814 case LibFunc::exp2f: 1815 case LibFunc::exp2l: 1816 return Intrinsic::exp2; 1817 case LibFunc::log: 1818 case LibFunc::logf: 1819 case LibFunc::logl: 1820 return Intrinsic::log; 1821 case LibFunc::log10: 1822 case LibFunc::log10f: 1823 case LibFunc::log10l: 1824 return Intrinsic::log10; 1825 case LibFunc::log2: 1826 case LibFunc::log2f: 1827 case LibFunc::log2l: 1828 return Intrinsic::log2; 1829 case LibFunc::fabs: 1830 case LibFunc::fabsf: 1831 case LibFunc::fabsl: 1832 return Intrinsic::fabs; 1833 case LibFunc::floor: 1834 case LibFunc::floorf: 1835 case LibFunc::floorl: 1836 return Intrinsic::floor; 1837 case LibFunc::ceil: 1838 case LibFunc::ceilf: 1839 case LibFunc::ceill: 1840 return Intrinsic::ceil; 1841 case LibFunc::trunc: 1842 case LibFunc::truncf: 1843 case LibFunc::truncl: 1844 return Intrinsic::trunc; 1845 case LibFunc::rint: 1846 case LibFunc::rintf: 1847 case LibFunc::rintl: 1848 return Intrinsic::rint; 1849 case LibFunc::nearbyint: 1850 case LibFunc::nearbyintf: 1851 case LibFunc::nearbyintl: 1852 return Intrinsic::nearbyint; 1853 case LibFunc::pow: 1854 case LibFunc::powf: 1855 case LibFunc::powl: 1856 return Intrinsic::pow; 1857 } 1858 1859 return Intrinsic::not_intrinsic; 1860 } 1861 1862 /// This function translates the reduction kind to an LLVM binary operator. 1863 static unsigned 1864 getReductionBinOp(LoopVectorizationLegality::ReductionKind Kind) { 1865 switch (Kind) { 1866 case LoopVectorizationLegality::RK_IntegerAdd: 1867 return Instruction::Add; 1868 case LoopVectorizationLegality::RK_IntegerMult: 1869 return Instruction::Mul; 1870 case LoopVectorizationLegality::RK_IntegerOr: 1871 return Instruction::Or; 1872 case LoopVectorizationLegality::RK_IntegerAnd: 1873 return Instruction::And; 1874 case LoopVectorizationLegality::RK_IntegerXor: 1875 return Instruction::Xor; 1876 case LoopVectorizationLegality::RK_FloatMult: 1877 return Instruction::FMul; 1878 case LoopVectorizationLegality::RK_FloatAdd: 1879 return Instruction::FAdd; 1880 case LoopVectorizationLegality::RK_IntegerMinMax: 1881 return Instruction::ICmp; 1882 case LoopVectorizationLegality::RK_FloatMinMax: 1883 return Instruction::FCmp; 1884 default: 1885 llvm_unreachable("Unknown reduction operation"); 1886 } 1887 } 1888 1889 Value *createMinMaxOp(IRBuilder<> &Builder, 1890 LoopVectorizationLegality::MinMaxReductionKind RK, 1891 Value *Left, 1892 Value *Right) { 1893 CmpInst::Predicate P = CmpInst::ICMP_NE; 1894 switch (RK) { 1895 default: 1896 llvm_unreachable("Unknown min/max reduction kind"); 1897 case LoopVectorizationLegality::MRK_UIntMin: 1898 P = CmpInst::ICMP_ULT; 1899 break; 1900 case LoopVectorizationLegality::MRK_UIntMax: 1901 P = CmpInst::ICMP_UGT; 1902 break; 1903 case LoopVectorizationLegality::MRK_SIntMin: 1904 P = CmpInst::ICMP_SLT; 1905 break; 1906 case LoopVectorizationLegality::MRK_SIntMax: 1907 P = CmpInst::ICMP_SGT; 1908 break; 1909 case LoopVectorizationLegality::MRK_FloatMin: 1910 P = CmpInst::FCMP_OLT; 1911 break; 1912 case LoopVectorizationLegality::MRK_FloatMax: 1913 P = CmpInst::FCMP_OGT; 1914 break; 1915 } 1916 1917 Value *Cmp; 1918 if (RK == LoopVectorizationLegality::MRK_FloatMin || 1919 RK == LoopVectorizationLegality::MRK_FloatMax) 1920 Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp"); 1921 else 1922 Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp"); 1923 1924 Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select"); 1925 return Select; 1926 } 1927 1928 void 1929 InnerLoopVectorizer::vectorizeLoop(LoopVectorizationLegality *Legal) { 1930 //===------------------------------------------------===// 1931 // 1932 // Notice: any optimization or new instruction that go 1933 // into the code below should be also be implemented in 1934 // the cost-model. 1935 // 1936 //===------------------------------------------------===// 1937 Constant *Zero = Builder.getInt32(0); 1938 1939 // In order to support reduction variables we need to be able to vectorize 1940 // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two 1941 // stages. First, we create a new vector PHI node with no incoming edges. 1942 // We use this value when we vectorize all of the instructions that use the 1943 // PHI. Next, after all of the instructions in the block are complete we 1944 // add the new incoming edges to the PHI. At this point all of the 1945 // instructions in the basic block are vectorized, so we can use them to 1946 // construct the PHI. 1947 PhiVector RdxPHIsToFix; 1948 1949 // Scan the loop in a topological order to ensure that defs are vectorized 1950 // before users. 1951 LoopBlocksDFS DFS(OrigLoop); 1952 DFS.perform(LI); 1953 1954 // Vectorize all of the blocks in the original loop. 1955 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(), 1956 be = DFS.endRPO(); bb != be; ++bb) 1957 vectorizeBlockInLoop(Legal, *bb, &RdxPHIsToFix); 1958 1959 // At this point every instruction in the original loop is widened to 1960 // a vector form. We are almost done. Now, we need to fix the PHI nodes 1961 // that we vectorized. The PHI nodes are currently empty because we did 1962 // not want to introduce cycles. Notice that the remaining PHI nodes 1963 // that we need to fix are reduction variables. 1964 1965 // Create the 'reduced' values for each of the induction vars. 1966 // The reduced values are the vector values that we scalarize and combine 1967 // after the loop is finished. 1968 for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end(); 1969 it != e; ++it) { 1970 PHINode *RdxPhi = *it; 1971 assert(RdxPhi && "Unable to recover vectorized PHI"); 1972 1973 // Find the reduction variable descriptor. 1974 assert(Legal->getReductionVars()->count(RdxPhi) && 1975 "Unable to find the reduction variable"); 1976 LoopVectorizationLegality::ReductionDescriptor RdxDesc = 1977 (*Legal->getReductionVars())[RdxPhi]; 1978 1979 setDebugLocFromInst(Builder, RdxDesc.StartValue); 1980 1981 // We need to generate a reduction vector from the incoming scalar. 1982 // To do so, we need to generate the 'identity' vector and overide 1983 // one of the elements with the incoming scalar reduction. We need 1984 // to do it in the vector-loop preheader. 1985 Builder.SetInsertPoint(LoopBypassBlocks.front()->getTerminator()); 1986 1987 // This is the vector-clone of the value that leaves the loop. 1988 VectorParts &VectorExit = getVectorValue(RdxDesc.LoopExitInstr); 1989 Type *VecTy = VectorExit[0]->getType(); 1990 1991 // Find the reduction identity variable. Zero for addition, or, xor, 1992 // one for multiplication, -1 for And. 1993 Value *Identity; 1994 Value *VectorStart; 1995 if (RdxDesc.Kind == LoopVectorizationLegality::RK_IntegerMinMax || 1996 RdxDesc.Kind == LoopVectorizationLegality::RK_FloatMinMax) { 1997 // MinMax reduction have the start value as their identify. 1998 VectorStart = Identity = Builder.CreateVectorSplat(VF, RdxDesc.StartValue, 1999 "minmax.ident"); 2000 } else { 2001 Constant *Iden = 2002 LoopVectorizationLegality::getReductionIdentity(RdxDesc.Kind, 2003 VecTy->getScalarType()); 2004 Identity = ConstantVector::getSplat(VF, Iden); 2005 2006 // This vector is the Identity vector where the first element is the 2007 // incoming scalar reduction. 2008 VectorStart = Builder.CreateInsertElement(Identity, 2009 RdxDesc.StartValue, Zero); 2010 } 2011 2012 // Fix the vector-loop phi. 2013 // We created the induction variable so we know that the 2014 // preheader is the first entry. 2015 BasicBlock *VecPreheader = Induction->getIncomingBlock(0); 2016 2017 // Reductions do not have to start at zero. They can start with 2018 // any loop invariant values. 2019 VectorParts &VecRdxPhi = WidenMap.get(RdxPhi); 2020 BasicBlock *Latch = OrigLoop->getLoopLatch(); 2021 Value *LoopVal = RdxPhi->getIncomingValueForBlock(Latch); 2022 VectorParts &Val = getVectorValue(LoopVal); 2023 for (unsigned part = 0; part < UF; ++part) { 2024 // Make sure to add the reduction stat value only to the 2025 // first unroll part. 2026 Value *StartVal = (part == 0) ? VectorStart : Identity; 2027 cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal, VecPreheader); 2028 cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part], LoopVectorBody); 2029 } 2030 2031 // Before each round, move the insertion point right between 2032 // the PHIs and the values we are going to write. 2033 // This allows us to write both PHINodes and the extractelement 2034 // instructions. 2035 Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt()); 2036 2037 VectorParts RdxParts; 2038 setDebugLocFromInst(Builder, RdxDesc.LoopExitInstr); 2039 for (unsigned part = 0; part < UF; ++part) { 2040 // This PHINode contains the vectorized reduction variable, or 2041 // the initial value vector, if we bypass the vector loop. 2042 VectorParts &RdxExitVal = getVectorValue(RdxDesc.LoopExitInstr); 2043 PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi"); 2044 Value *StartVal = (part == 0) ? VectorStart : Identity; 2045 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I) 2046 NewPhi->addIncoming(StartVal, LoopBypassBlocks[I]); 2047 NewPhi->addIncoming(RdxExitVal[part], LoopVectorBody); 2048 RdxParts.push_back(NewPhi); 2049 } 2050 2051 // Reduce all of the unrolled parts into a single vector. 2052 Value *ReducedPartRdx = RdxParts[0]; 2053 unsigned Op = getReductionBinOp(RdxDesc.Kind); 2054 setDebugLocFromInst(Builder, ReducedPartRdx); 2055 for (unsigned part = 1; part < UF; ++part) { 2056 if (Op != Instruction::ICmp && Op != Instruction::FCmp) 2057 ReducedPartRdx = Builder.CreateBinOp((Instruction::BinaryOps)Op, 2058 RdxParts[part], ReducedPartRdx, 2059 "bin.rdx"); 2060 else 2061 ReducedPartRdx = createMinMaxOp(Builder, RdxDesc.MinMaxKind, 2062 ReducedPartRdx, RdxParts[part]); 2063 } 2064 2065 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles 2066 // and vector ops, reducing the set of values being computed by half each 2067 // round. 2068 assert(isPowerOf2_32(VF) && 2069 "Reduction emission only supported for pow2 vectors!"); 2070 Value *TmpVec = ReducedPartRdx; 2071 SmallVector<Constant*, 32> ShuffleMask(VF, 0); 2072 for (unsigned i = VF; i != 1; i >>= 1) { 2073 // Move the upper half of the vector to the lower half. 2074 for (unsigned j = 0; j != i/2; ++j) 2075 ShuffleMask[j] = Builder.getInt32(i/2 + j); 2076 2077 // Fill the rest of the mask with undef. 2078 std::fill(&ShuffleMask[i/2], ShuffleMask.end(), 2079 UndefValue::get(Builder.getInt32Ty())); 2080 2081 Value *Shuf = 2082 Builder.CreateShuffleVector(TmpVec, 2083 UndefValue::get(TmpVec->getType()), 2084 ConstantVector::get(ShuffleMask), 2085 "rdx.shuf"); 2086 2087 if (Op != Instruction::ICmp && Op != Instruction::FCmp) 2088 TmpVec = Builder.CreateBinOp((Instruction::BinaryOps)Op, TmpVec, Shuf, 2089 "bin.rdx"); 2090 else 2091 TmpVec = createMinMaxOp(Builder, RdxDesc.MinMaxKind, TmpVec, Shuf); 2092 } 2093 2094 // The result is in the first element of the vector. 2095 Value *Scalar0 = Builder.CreateExtractElement(TmpVec, Builder.getInt32(0)); 2096 2097 // Now, we need to fix the users of the reduction variable 2098 // inside and outside of the scalar remainder loop. 2099 // We know that the loop is in LCSSA form. We need to update the 2100 // PHI nodes in the exit blocks. 2101 for (BasicBlock::iterator LEI = LoopExitBlock->begin(), 2102 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) { 2103 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI); 2104 if (!LCSSAPhi) continue; 2105 2106 // All PHINodes need to have a single entry edge, or two if 2107 // we already fixed them. 2108 assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI"); 2109 2110 // We found our reduction value exit-PHI. Update it with the 2111 // incoming bypass edge. 2112 if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) { 2113 // Add an edge coming from the bypass. 2114 LCSSAPhi->addIncoming(Scalar0, LoopMiddleBlock); 2115 break; 2116 } 2117 }// end of the LCSSA phi scan. 2118 2119 // Fix the scalar loop reduction variable with the incoming reduction sum 2120 // from the vector body and from the backedge value. 2121 int IncomingEdgeBlockIdx = 2122 (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch()); 2123 assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index"); 2124 // Pick the other block. 2125 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1); 2126 (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, Scalar0); 2127 (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr); 2128 }// end of for each redux variable. 2129 2130 // The Loop exit block may have single value PHI nodes where the incoming 2131 // value is 'undef'. While vectorizing we only handled real values that 2132 // were defined inside the loop. Here we handle the 'undef case'. 2133 // See PR14725. 2134 for (BasicBlock::iterator LEI = LoopExitBlock->begin(), 2135 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) { 2136 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI); 2137 if (!LCSSAPhi) continue; 2138 if (LCSSAPhi->getNumIncomingValues() == 1) 2139 LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()), 2140 LoopMiddleBlock); 2141 } 2142 } 2143 2144 InnerLoopVectorizer::VectorParts 2145 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) { 2146 assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) && 2147 "Invalid edge"); 2148 2149 // Look for cached value. 2150 std::pair<BasicBlock*, BasicBlock*> Edge(Src, Dst); 2151 EdgeMaskCache::iterator ECEntryIt = MaskCache.find(Edge); 2152 if (ECEntryIt != MaskCache.end()) 2153 return ECEntryIt->second; 2154 2155 VectorParts SrcMask = createBlockInMask(Src); 2156 2157 // The terminator has to be a branch inst! 2158 BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator()); 2159 assert(BI && "Unexpected terminator found"); 2160 2161 if (BI->isConditional()) { 2162 VectorParts EdgeMask = getVectorValue(BI->getCondition()); 2163 2164 if (BI->getSuccessor(0) != Dst) 2165 for (unsigned part = 0; part < UF; ++part) 2166 EdgeMask[part] = Builder.CreateNot(EdgeMask[part]); 2167 2168 for (unsigned part = 0; part < UF; ++part) 2169 EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]); 2170 2171 MaskCache[Edge] = EdgeMask; 2172 return EdgeMask; 2173 } 2174 2175 MaskCache[Edge] = SrcMask; 2176 return SrcMask; 2177 } 2178 2179 InnerLoopVectorizer::VectorParts 2180 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) { 2181 assert(OrigLoop->contains(BB) && "Block is not a part of a loop"); 2182 2183 // Loop incoming mask is all-one. 2184 if (OrigLoop->getHeader() == BB) { 2185 Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1); 2186 return getVectorValue(C); 2187 } 2188 2189 // This is the block mask. We OR all incoming edges, and with zero. 2190 Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0); 2191 VectorParts BlockMask = getVectorValue(Zero); 2192 2193 // For each pred: 2194 for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) { 2195 VectorParts EM = createEdgeMask(*it, BB); 2196 for (unsigned part = 0; part < UF; ++part) 2197 BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]); 2198 } 2199 2200 return BlockMask; 2201 } 2202 2203 void 2204 InnerLoopVectorizer::vectorizeBlockInLoop(LoopVectorizationLegality *Legal, 2205 BasicBlock *BB, PhiVector *PV) { 2206 // For each instruction in the old loop. 2207 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) { 2208 VectorParts &Entry = WidenMap.get(it); 2209 switch (it->getOpcode()) { 2210 case Instruction::Br: 2211 // Nothing to do for PHIs and BR, since we already took care of the 2212 // loop control flow instructions. 2213 continue; 2214 case Instruction::PHI:{ 2215 PHINode* P = cast<PHINode>(it); 2216 // Handle reduction variables: 2217 if (Legal->getReductionVars()->count(P)) { 2218 for (unsigned part = 0; part < UF; ++part) { 2219 // This is phase one of vectorizing PHIs. 2220 Type *VecTy = VectorType::get(it->getType(), VF); 2221 Entry[part] = PHINode::Create(VecTy, 2, "vec.phi", 2222 LoopVectorBody-> getFirstInsertionPt()); 2223 } 2224 PV->push_back(P); 2225 continue; 2226 } 2227 2228 setDebugLocFromInst(Builder, P); 2229 // Check for PHI nodes that are lowered to vector selects. 2230 if (P->getParent() != OrigLoop->getHeader()) { 2231 // We know that all PHIs in non header blocks are converted into 2232 // selects, so we don't have to worry about the insertion order and we 2233 // can just use the builder. 2234 // At this point we generate the predication tree. There may be 2235 // duplications since this is a simple recursive scan, but future 2236 // optimizations will clean it up. 2237 2238 unsigned NumIncoming = P->getNumIncomingValues(); 2239 2240 // Generate a sequence of selects of the form: 2241 // SELECT(Mask3, In3, 2242 // SELECT(Mask2, In2, 2243 // ( ...))) 2244 for (unsigned In = 0; In < NumIncoming; In++) { 2245 VectorParts Cond = createEdgeMask(P->getIncomingBlock(In), 2246 P->getParent()); 2247 VectorParts &In0 = getVectorValue(P->getIncomingValue(In)); 2248 2249 for (unsigned part = 0; part < UF; ++part) { 2250 // We might have single edge PHIs (blocks) - use an identity 2251 // 'select' for the first PHI operand. 2252 if (In == 0) 2253 Entry[part] = Builder.CreateSelect(Cond[part], In0[part], 2254 In0[part]); 2255 else 2256 // Select between the current value and the previous incoming edge 2257 // based on the incoming mask. 2258 Entry[part] = Builder.CreateSelect(Cond[part], In0[part], 2259 Entry[part], "predphi"); 2260 } 2261 } 2262 continue; 2263 } 2264 2265 // This PHINode must be an induction variable. 2266 // Make sure that we know about it. 2267 assert(Legal->getInductionVars()->count(P) && 2268 "Not an induction variable"); 2269 2270 LoopVectorizationLegality::InductionInfo II = 2271 Legal->getInductionVars()->lookup(P); 2272 2273 switch (II.IK) { 2274 case LoopVectorizationLegality::IK_NoInduction: 2275 llvm_unreachable("Unknown induction"); 2276 case LoopVectorizationLegality::IK_IntInduction: { 2277 assert(P->getType() == II.StartValue->getType() && "Types must match"); 2278 Type *PhiTy = P->getType(); 2279 Value *Broadcasted; 2280 if (P == OldInduction) { 2281 // Handle the canonical induction variable. We might have had to 2282 // extend the type. 2283 Broadcasted = Builder.CreateTrunc(Induction, PhiTy); 2284 } else { 2285 // Handle other induction variables that are now based on the 2286 // canonical one. 2287 Value *NormalizedIdx = Builder.CreateSub(Induction, ExtendedIdx, 2288 "normalized.idx"); 2289 NormalizedIdx = Builder.CreateSExtOrTrunc(NormalizedIdx, PhiTy); 2290 Broadcasted = Builder.CreateAdd(II.StartValue, NormalizedIdx, 2291 "offset.idx"); 2292 } 2293 Broadcasted = getBroadcastInstrs(Broadcasted); 2294 // After broadcasting the induction variable we need to make the vector 2295 // consecutive by adding 0, 1, 2, etc. 2296 for (unsigned part = 0; part < UF; ++part) 2297 Entry[part] = getConsecutiveVector(Broadcasted, VF * part, false); 2298 continue; 2299 } 2300 case LoopVectorizationLegality::IK_ReverseIntInduction: 2301 case LoopVectorizationLegality::IK_PtrInduction: 2302 case LoopVectorizationLegality::IK_ReversePtrInduction: 2303 // Handle reverse integer and pointer inductions. 2304 Value *StartIdx = ExtendedIdx; 2305 // This is the normalized GEP that starts counting at zero. 2306 Value *NormalizedIdx = Builder.CreateSub(Induction, StartIdx, 2307 "normalized.idx"); 2308 2309 // Handle the reverse integer induction variable case. 2310 if (LoopVectorizationLegality::IK_ReverseIntInduction == II.IK) { 2311 IntegerType *DstTy = cast<IntegerType>(II.StartValue->getType()); 2312 Value *CNI = Builder.CreateSExtOrTrunc(NormalizedIdx, DstTy, 2313 "resize.norm.idx"); 2314 Value *ReverseInd = Builder.CreateSub(II.StartValue, CNI, 2315 "reverse.idx"); 2316 2317 // This is a new value so do not hoist it out. 2318 Value *Broadcasted = getBroadcastInstrs(ReverseInd); 2319 // After broadcasting the induction variable we need to make the 2320 // vector consecutive by adding ... -3, -2, -1, 0. 2321 for (unsigned part = 0; part < UF; ++part) 2322 Entry[part] = getConsecutiveVector(Broadcasted, -(int)VF * part, 2323 true); 2324 continue; 2325 } 2326 2327 // Handle the pointer induction variable case. 2328 assert(P->getType()->isPointerTy() && "Unexpected type."); 2329 2330 // Is this a reverse induction ptr or a consecutive induction ptr. 2331 bool Reverse = (LoopVectorizationLegality::IK_ReversePtrInduction == 2332 II.IK); 2333 2334 // This is the vector of results. Notice that we don't generate 2335 // vector geps because scalar geps result in better code. 2336 for (unsigned part = 0; part < UF; ++part) { 2337 Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF)); 2338 for (unsigned int i = 0; i < VF; ++i) { 2339 int EltIndex = (i + part * VF) * (Reverse ? -1 : 1); 2340 Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex); 2341 Value *GlobalIdx; 2342 if (!Reverse) 2343 GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx, "gep.idx"); 2344 else 2345 GlobalIdx = Builder.CreateSub(Idx, NormalizedIdx, "gep.ridx"); 2346 2347 Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx, 2348 "next.gep"); 2349 VecVal = Builder.CreateInsertElement(VecVal, SclrGep, 2350 Builder.getInt32(i), 2351 "insert.gep"); 2352 } 2353 Entry[part] = VecVal; 2354 } 2355 continue; 2356 } 2357 2358 }// End of PHI. 2359 2360 case Instruction::Add: 2361 case Instruction::FAdd: 2362 case Instruction::Sub: 2363 case Instruction::FSub: 2364 case Instruction::Mul: 2365 case Instruction::FMul: 2366 case Instruction::UDiv: 2367 case Instruction::SDiv: 2368 case Instruction::FDiv: 2369 case Instruction::URem: 2370 case Instruction::SRem: 2371 case Instruction::FRem: 2372 case Instruction::Shl: 2373 case Instruction::LShr: 2374 case Instruction::AShr: 2375 case Instruction::And: 2376 case Instruction::Or: 2377 case Instruction::Xor: { 2378 // Just widen binops. 2379 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it); 2380 setDebugLocFromInst(Builder, BinOp); 2381 VectorParts &A = getVectorValue(it->getOperand(0)); 2382 VectorParts &B = getVectorValue(it->getOperand(1)); 2383 2384 // Use this vector value for all users of the original instruction. 2385 for (unsigned Part = 0; Part < UF; ++Part) { 2386 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]); 2387 2388 // Update the NSW, NUW and Exact flags. Notice: V can be an Undef. 2389 BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V); 2390 if (VecOp && isa<OverflowingBinaryOperator>(BinOp)) { 2391 VecOp->setHasNoSignedWrap(BinOp->hasNoSignedWrap()); 2392 VecOp->setHasNoUnsignedWrap(BinOp->hasNoUnsignedWrap()); 2393 } 2394 if (VecOp && isa<PossiblyExactOperator>(VecOp)) 2395 VecOp->setIsExact(BinOp->isExact()); 2396 2397 Entry[Part] = V; 2398 } 2399 break; 2400 } 2401 case Instruction::Select: { 2402 // Widen selects. 2403 // If the selector is loop invariant we can create a select 2404 // instruction with a scalar condition. Otherwise, use vector-select. 2405 bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)), 2406 OrigLoop); 2407 setDebugLocFromInst(Builder, it); 2408 2409 // The condition can be loop invariant but still defined inside the 2410 // loop. This means that we can't just use the original 'cond' value. 2411 // We have to take the 'vectorized' value and pick the first lane. 2412 // Instcombine will make this a no-op. 2413 VectorParts &Cond = getVectorValue(it->getOperand(0)); 2414 VectorParts &Op0 = getVectorValue(it->getOperand(1)); 2415 VectorParts &Op1 = getVectorValue(it->getOperand(2)); 2416 Value *ScalarCond = Builder.CreateExtractElement(Cond[0], 2417 Builder.getInt32(0)); 2418 for (unsigned Part = 0; Part < UF; ++Part) { 2419 Entry[Part] = Builder.CreateSelect( 2420 InvariantCond ? ScalarCond : Cond[Part], 2421 Op0[Part], 2422 Op1[Part]); 2423 } 2424 break; 2425 } 2426 2427 case Instruction::ICmp: 2428 case Instruction::FCmp: { 2429 // Widen compares. Generate vector compares. 2430 bool FCmp = (it->getOpcode() == Instruction::FCmp); 2431 CmpInst *Cmp = dyn_cast<CmpInst>(it); 2432 setDebugLocFromInst(Builder, it); 2433 VectorParts &A = getVectorValue(it->getOperand(0)); 2434 VectorParts &B = getVectorValue(it->getOperand(1)); 2435 for (unsigned Part = 0; Part < UF; ++Part) { 2436 Value *C = 0; 2437 if (FCmp) 2438 C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]); 2439 else 2440 C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]); 2441 Entry[Part] = C; 2442 } 2443 break; 2444 } 2445 2446 case Instruction::Store: 2447 case Instruction::Load: 2448 vectorizeMemoryInstruction(it, Legal); 2449 break; 2450 case Instruction::ZExt: 2451 case Instruction::SExt: 2452 case Instruction::FPToUI: 2453 case Instruction::FPToSI: 2454 case Instruction::FPExt: 2455 case Instruction::PtrToInt: 2456 case Instruction::IntToPtr: 2457 case Instruction::SIToFP: 2458 case Instruction::UIToFP: 2459 case Instruction::Trunc: 2460 case Instruction::FPTrunc: 2461 case Instruction::BitCast: { 2462 CastInst *CI = dyn_cast<CastInst>(it); 2463 setDebugLocFromInst(Builder, it); 2464 /// Optimize the special case where the source is the induction 2465 /// variable. Notice that we can only optimize the 'trunc' case 2466 /// because: a. FP conversions lose precision, b. sext/zext may wrap, 2467 /// c. other casts depend on pointer size. 2468 if (CI->getOperand(0) == OldInduction && 2469 it->getOpcode() == Instruction::Trunc) { 2470 Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction, 2471 CI->getType()); 2472 Value *Broadcasted = getBroadcastInstrs(ScalarCast); 2473 for (unsigned Part = 0; Part < UF; ++Part) 2474 Entry[Part] = getConsecutiveVector(Broadcasted, VF * Part, false); 2475 break; 2476 } 2477 /// Vectorize casts. 2478 Type *DestTy = VectorType::get(CI->getType()->getScalarType(), VF); 2479 2480 VectorParts &A = getVectorValue(it->getOperand(0)); 2481 for (unsigned Part = 0; Part < UF; ++Part) 2482 Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy); 2483 break; 2484 } 2485 2486 case Instruction::Call: { 2487 // Ignore dbg intrinsics. 2488 if (isa<DbgInfoIntrinsic>(it)) 2489 break; 2490 setDebugLocFromInst(Builder, it); 2491 2492 Module *M = BB->getParent()->getParent(); 2493 CallInst *CI = cast<CallInst>(it); 2494 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI); 2495 assert(ID && "Not an intrinsic call!"); 2496 switch (ID) { 2497 case Intrinsic::lifetime_end: 2498 case Intrinsic::lifetime_start: 2499 scalarizeInstruction(it); 2500 break; 2501 default: 2502 for (unsigned Part = 0; Part < UF; ++Part) { 2503 SmallVector<Value *, 4> Args; 2504 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) { 2505 VectorParts &Arg = getVectorValue(CI->getArgOperand(i)); 2506 Args.push_back(Arg[Part]); 2507 } 2508 Type *Tys[] = { VectorType::get(CI->getType()->getScalarType(), VF) }; 2509 Function *F = Intrinsic::getDeclaration(M, ID, Tys); 2510 Entry[Part] = Builder.CreateCall(F, Args); 2511 } 2512 break; 2513 } 2514 break; 2515 } 2516 2517 default: 2518 // All other instructions are unsupported. Scalarize them. 2519 scalarizeInstruction(it); 2520 break; 2521 }// end of switch. 2522 }// end of for_each instr. 2523 } 2524 2525 void InnerLoopVectorizer::updateAnalysis() { 2526 // Forget the original basic block. 2527 SE->forgetLoop(OrigLoop); 2528 2529 // Update the dominator tree information. 2530 assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) && 2531 "Entry does not dominate exit."); 2532 2533 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I) 2534 DT->addNewBlock(LoopBypassBlocks[I], LoopBypassBlocks[I-1]); 2535 DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlocks.back()); 2536 DT->addNewBlock(LoopVectorBody, LoopVectorPreHeader); 2537 DT->addNewBlock(LoopMiddleBlock, LoopBypassBlocks.front()); 2538 DT->addNewBlock(LoopScalarPreHeader, LoopMiddleBlock); 2539 DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader); 2540 DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock); 2541 2542 DEBUG(DT->verifyAnalysis()); 2543 } 2544 2545 bool LoopVectorizationLegality::canVectorizeWithIfConvert() { 2546 if (!EnableIfConversion) 2547 return false; 2548 2549 assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable"); 2550 std::vector<BasicBlock*> &LoopBlocks = TheLoop->getBlocksVector(); 2551 2552 // A list of pointers that we can safely read and write to. 2553 SmallPtrSet<Value *, 8> SafePointes; 2554 2555 // Collect safe addresses. 2556 for (unsigned i = 0, e = LoopBlocks.size(); i < e; ++i) { 2557 BasicBlock *BB = LoopBlocks[i]; 2558 2559 if (blockNeedsPredication(BB)) 2560 continue; 2561 2562 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) { 2563 if (LoadInst *LI = dyn_cast<LoadInst>(I)) 2564 SafePointes.insert(LI->getPointerOperand()); 2565 else if (StoreInst *SI = dyn_cast<StoreInst>(I)) 2566 SafePointes.insert(SI->getPointerOperand()); 2567 } 2568 } 2569 2570 // Collect the blocks that need predication. 2571 for (unsigned i = 0, e = LoopBlocks.size(); i < e; ++i) { 2572 BasicBlock *BB = LoopBlocks[i]; 2573 2574 // We don't support switch statements inside loops. 2575 if (!isa<BranchInst>(BB->getTerminator())) 2576 return false; 2577 2578 // We must be able to predicate all blocks that need to be predicated. 2579 if (blockNeedsPredication(BB) && !blockCanBePredicated(BB, SafePointes)) 2580 return false; 2581 } 2582 2583 // We can if-convert this loop. 2584 return true; 2585 } 2586 2587 bool LoopVectorizationLegality::canVectorize() { 2588 // We must have a loop in canonical form. Loops with indirectbr in them cannot 2589 // be canonicalized. 2590 if (!TheLoop->getLoopPreheader()) 2591 return false; 2592 2593 // We can only vectorize innermost loops. 2594 if (TheLoop->getSubLoopsVector().size()) 2595 return false; 2596 2597 // We must have a single backedge. 2598 if (TheLoop->getNumBackEdges() != 1) 2599 return false; 2600 2601 // We must have a single exiting block. 2602 if (!TheLoop->getExitingBlock()) 2603 return false; 2604 2605 unsigned NumBlocks = TheLoop->getNumBlocks(); 2606 2607 // Check if we can if-convert non single-bb loops. 2608 if (NumBlocks != 1 && !canVectorizeWithIfConvert()) { 2609 DEBUG(dbgs() << "LV: Can't if-convert the loop.\n"); 2610 return false; 2611 } 2612 2613 // We need to have a loop header. 2614 BasicBlock *Latch = TheLoop->getLoopLatch(); 2615 DEBUG(dbgs() << "LV: Found a loop: " << 2616 TheLoop->getHeader()->getName() << "\n"); 2617 2618 // ScalarEvolution needs to be able to find the exit count. 2619 const SCEV *ExitCount = SE->getBackedgeTakenCount(TheLoop); 2620 if (ExitCount == SE->getCouldNotCompute()) { 2621 DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n"); 2622 return false; 2623 } 2624 2625 // Do not loop-vectorize loops with a tiny trip count. 2626 unsigned TC = SE->getSmallConstantTripCount(TheLoop, Latch); 2627 if (TC > 0u && TC < TinyTripCountVectorThreshold) { 2628 DEBUG(dbgs() << "LV: Found a loop with a very small trip count. " << 2629 "This loop is not worth vectorizing.\n"); 2630 return false; 2631 } 2632 2633 // Check if we can vectorize the instructions and CFG in this loop. 2634 if (!canVectorizeInstrs()) { 2635 DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n"); 2636 return false; 2637 } 2638 2639 // Go over each instruction and look at memory deps. 2640 if (!canVectorizeMemory()) { 2641 DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n"); 2642 return false; 2643 } 2644 2645 // Collect all of the variables that remain uniform after vectorization. 2646 collectLoopUniforms(); 2647 2648 DEBUG(dbgs() << "LV: We can vectorize this loop" << 2649 (PtrRtCheck.Need ? " (with a runtime bound check)" : "") 2650 <<"!\n"); 2651 2652 // Okay! We can vectorize. At this point we don't have any other mem analysis 2653 // which may limit our maximum vectorization factor, so just return true with 2654 // no restrictions. 2655 return true; 2656 } 2657 2658 static Type *convertPointerToIntegerType(DataLayout &DL, Type *Ty) { 2659 if (Ty->isPointerTy()) 2660 return DL.getIntPtrType(Ty->getContext()); 2661 return Ty; 2662 } 2663 2664 static Type* getWiderType(DataLayout &DL, Type *Ty0, Type *Ty1) { 2665 Ty0 = convertPointerToIntegerType(DL, Ty0); 2666 Ty1 = convertPointerToIntegerType(DL, Ty1); 2667 if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits()) 2668 return Ty0; 2669 return Ty1; 2670 } 2671 2672 /// \brief Check that the instruction has outside loop users and is not an 2673 /// identified reduction variable. 2674 static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst, 2675 SmallPtrSet<Value *, 4> &Reductions) { 2676 // Reduction instructions are allowed to have exit users. All other 2677 // instructions must not have external users. 2678 if (!Reductions.count(Inst)) 2679 //Check that all of the users of the loop are inside the BB. 2680 for (Value::use_iterator I = Inst->use_begin(), E = Inst->use_end(); 2681 I != E; ++I) { 2682 Instruction *U = cast<Instruction>(*I); 2683 // This user may be a reduction exit value. 2684 if (!TheLoop->contains(U)) { 2685 DEBUG(dbgs() << "LV: Found an outside user for : "<< *U << "\n"); 2686 return true; 2687 } 2688 } 2689 return false; 2690 } 2691 2692 bool LoopVectorizationLegality::canVectorizeInstrs() { 2693 BasicBlock *PreHeader = TheLoop->getLoopPreheader(); 2694 BasicBlock *Header = TheLoop->getHeader(); 2695 2696 // Look for the attribute signaling the absence of NaNs. 2697 Function &F = *Header->getParent(); 2698 if (F.hasFnAttribute("no-nans-fp-math")) 2699 HasFunNoNaNAttr = F.getAttributes().getAttribute( 2700 AttributeSet::FunctionIndex, 2701 "no-nans-fp-math").getValueAsString() == "true"; 2702 2703 // For each block in the loop. 2704 for (Loop::block_iterator bb = TheLoop->block_begin(), 2705 be = TheLoop->block_end(); bb != be; ++bb) { 2706 2707 // Scan the instructions in the block and look for hazards. 2708 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e; 2709 ++it) { 2710 2711 if (PHINode *Phi = dyn_cast<PHINode>(it)) { 2712 Type *PhiTy = Phi->getType(); 2713 // Check that this PHI type is allowed. 2714 if (!PhiTy->isIntegerTy() && 2715 !PhiTy->isFloatingPointTy() && 2716 !PhiTy->isPointerTy()) { 2717 DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n"); 2718 return false; 2719 } 2720 2721 // If this PHINode is not in the header block, then we know that we 2722 // can convert it to select during if-conversion. No need to check if 2723 // the PHIs in this block are induction or reduction variables. 2724 if (*bb != Header) { 2725 // Check that this instruction has no outside users or is an 2726 // identified reduction value with an outside user. 2727 if(!hasOutsideLoopUser(TheLoop, it, AllowedExit)) 2728 continue; 2729 return false; 2730 } 2731 2732 // We only allow if-converted PHIs with more than two incoming values. 2733 if (Phi->getNumIncomingValues() != 2) { 2734 DEBUG(dbgs() << "LV: Found an invalid PHI.\n"); 2735 return false; 2736 } 2737 2738 // This is the value coming from the preheader. 2739 Value *StartValue = Phi->getIncomingValueForBlock(PreHeader); 2740 // Check if this is an induction variable. 2741 InductionKind IK = isInductionVariable(Phi); 2742 2743 if (IK_NoInduction != IK) { 2744 // Get the widest type. 2745 if (!WidestIndTy) 2746 WidestIndTy = convertPointerToIntegerType(*DL, PhiTy); 2747 else 2748 WidestIndTy = getWiderType(*DL, PhiTy, WidestIndTy); 2749 2750 // Int inductions are special because we only allow one IV. 2751 if (IK == IK_IntInduction) { 2752 // Use the phi node with the widest type as induction. Use the last 2753 // one if there are multiple (no good reason for doing this other 2754 // than it is expedient). 2755 if (!Induction || PhiTy == WidestIndTy) 2756 Induction = Phi; 2757 } 2758 2759 DEBUG(dbgs() << "LV: Found an induction variable.\n"); 2760 Inductions[Phi] = InductionInfo(StartValue, IK); 2761 continue; 2762 } 2763 2764 if (AddReductionVar(Phi, RK_IntegerAdd)) { 2765 DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n"); 2766 continue; 2767 } 2768 if (AddReductionVar(Phi, RK_IntegerMult)) { 2769 DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n"); 2770 continue; 2771 } 2772 if (AddReductionVar(Phi, RK_IntegerOr)) { 2773 DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n"); 2774 continue; 2775 } 2776 if (AddReductionVar(Phi, RK_IntegerAnd)) { 2777 DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n"); 2778 continue; 2779 } 2780 if (AddReductionVar(Phi, RK_IntegerXor)) { 2781 DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n"); 2782 continue; 2783 } 2784 if (AddReductionVar(Phi, RK_IntegerMinMax)) { 2785 DEBUG(dbgs() << "LV: Found a MINMAX reduction PHI."<< *Phi <<"\n"); 2786 continue; 2787 } 2788 if (AddReductionVar(Phi, RK_FloatMult)) { 2789 DEBUG(dbgs() << "LV: Found an FMult reduction PHI."<< *Phi <<"\n"); 2790 continue; 2791 } 2792 if (AddReductionVar(Phi, RK_FloatAdd)) { 2793 DEBUG(dbgs() << "LV: Found an FAdd reduction PHI."<< *Phi <<"\n"); 2794 continue; 2795 } 2796 if (AddReductionVar(Phi, RK_FloatMinMax)) { 2797 DEBUG(dbgs() << "LV: Found an float MINMAX reduction PHI."<< *Phi << 2798 "\n"); 2799 continue; 2800 } 2801 2802 DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n"); 2803 return false; 2804 }// end of PHI handling 2805 2806 // We still don't handle functions. However, we can ignore dbg intrinsic 2807 // calls and we do handle certain intrinsic and libm functions. 2808 CallInst *CI = dyn_cast<CallInst>(it); 2809 if (CI && !getIntrinsicIDForCall(CI, TLI) && !isa<DbgInfoIntrinsic>(CI)) { 2810 DEBUG(dbgs() << "LV: Found a call site.\n"); 2811 return false; 2812 } 2813 2814 // Check that the instruction return type is vectorizable. 2815 if (!VectorType::isValidElementType(it->getType()) && 2816 !it->getType()->isVoidTy()) { 2817 DEBUG(dbgs() << "LV: Found unvectorizable type." << "\n"); 2818 return false; 2819 } 2820 2821 // Check that the stored type is vectorizable. 2822 if (StoreInst *ST = dyn_cast<StoreInst>(it)) { 2823 Type *T = ST->getValueOperand()->getType(); 2824 if (!VectorType::isValidElementType(T)) 2825 return false; 2826 } 2827 2828 // Reduction instructions are allowed to have exit users. 2829 // All other instructions must not have external users. 2830 if (hasOutsideLoopUser(TheLoop, it, AllowedExit)) 2831 return false; 2832 2833 } // next instr. 2834 2835 } 2836 2837 if (!Induction) { 2838 DEBUG(dbgs() << "LV: Did not find one integer induction var.\n"); 2839 if (Inductions.empty()) 2840 return false; 2841 } 2842 2843 return true; 2844 } 2845 2846 void LoopVectorizationLegality::collectLoopUniforms() { 2847 // We now know that the loop is vectorizable! 2848 // Collect variables that will remain uniform after vectorization. 2849 std::vector<Value*> Worklist; 2850 BasicBlock *Latch = TheLoop->getLoopLatch(); 2851 2852 // Start with the conditional branch and walk up the block. 2853 Worklist.push_back(Latch->getTerminator()->getOperand(0)); 2854 2855 while (Worklist.size()) { 2856 Instruction *I = dyn_cast<Instruction>(Worklist.back()); 2857 Worklist.pop_back(); 2858 2859 // Look at instructions inside this loop. 2860 // Stop when reaching PHI nodes. 2861 // TODO: we need to follow values all over the loop, not only in this block. 2862 if (!I || !TheLoop->contains(I) || isa<PHINode>(I)) 2863 continue; 2864 2865 // This is a known uniform. 2866 Uniforms.insert(I); 2867 2868 // Insert all operands. 2869 Worklist.insert(Worklist.end(), I->op_begin(), I->op_end()); 2870 } 2871 } 2872 2873 namespace { 2874 /// \brief Analyses memory accesses in a loop. 2875 /// 2876 /// Checks whether run time pointer checks are needed and builds sets for data 2877 /// dependence checking. 2878 class AccessAnalysis { 2879 public: 2880 /// \brief Read or write access location. 2881 typedef PointerIntPair<Value *, 1, bool> MemAccessInfo; 2882 typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet; 2883 2884 /// \brief Set of potential dependent memory accesses. 2885 typedef EquivalenceClasses<MemAccessInfo> DepCandidates; 2886 2887 AccessAnalysis(DataLayout *Dl, DepCandidates &DA) : 2888 DL(Dl), DepCands(DA), AreAllWritesIdentified(true), 2889 AreAllReadsIdentified(true), IsRTCheckNeeded(false) {} 2890 2891 /// \brief Register a load and whether it is only read from. 2892 void addLoad(Value *Ptr, bool IsReadOnly) { 2893 Accesses.insert(MemAccessInfo(Ptr, false)); 2894 if (IsReadOnly) 2895 ReadOnlyPtr.insert(Ptr); 2896 } 2897 2898 /// \brief Register a store. 2899 void addStore(Value *Ptr) { 2900 Accesses.insert(MemAccessInfo(Ptr, true)); 2901 } 2902 2903 /// \brief Check whether we can check the pointers at runtime for 2904 /// non-intersection. 2905 bool canCheckPtrAtRT(LoopVectorizationLegality::RuntimePointerCheck &RtCheck, 2906 unsigned &NumComparisons, ScalarEvolution *SE, 2907 Loop *TheLoop); 2908 2909 /// \brief Goes over all memory accesses, checks whether a RT check is needed 2910 /// and builds sets of dependent accesses. 2911 void buildDependenceSets() { 2912 // Process read-write pointers first. 2913 processMemAccesses(false); 2914 // Next, process read pointers. 2915 processMemAccesses(true); 2916 } 2917 2918 bool isRTCheckNeeded() { return IsRTCheckNeeded; } 2919 2920 bool isDependencyCheckNeeded() { return !CheckDeps.empty(); } 2921 2922 MemAccessInfoSet &getDependenciesToCheck() { return CheckDeps; } 2923 2924 private: 2925 typedef SetVector<MemAccessInfo> PtrAccessSet; 2926 typedef DenseMap<Value*, MemAccessInfo> UnderlyingObjToAccessMap; 2927 2928 /// \brief Go over all memory access or only the deferred ones if 2929 /// \p UseDeferred is true and check whether runtime pointer checks are needed 2930 /// and build sets of dependency check candidates. 2931 void processMemAccesses(bool UseDeferred); 2932 2933 /// Set of all accesses. 2934 PtrAccessSet Accesses; 2935 2936 /// Set of access to check after all writes have been processed. 2937 PtrAccessSet DeferredAccesses; 2938 2939 /// Map of pointers to last access encountered. 2940 UnderlyingObjToAccessMap ObjToLastAccess; 2941 2942 /// Set of accesses that need a further dependence check. 2943 MemAccessInfoSet CheckDeps; 2944 2945 /// Set of pointers that are read only. 2946 SmallPtrSet<Value*, 16> ReadOnlyPtr; 2947 2948 /// Set of underlying objects already written to. 2949 SmallPtrSet<Value*, 16> WriteObjects; 2950 2951 DataLayout *DL; 2952 2953 /// Sets of potentially dependent accesses - members of one set share an 2954 /// underlying pointer. The set "CheckDeps" identfies which sets really need a 2955 /// dependence check. 2956 DepCandidates &DepCands; 2957 2958 bool AreAllWritesIdentified; 2959 bool AreAllReadsIdentified; 2960 bool IsRTCheckNeeded; 2961 }; 2962 2963 } // end anonymous namespace 2964 2965 /// \brief Check whether a pointer can participate in a runtime bounds check. 2966 static bool hasComputableBounds(ScalarEvolution *SE, Value *Ptr) { 2967 const SCEV *PtrScev = SE->getSCEV(Ptr); 2968 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev); 2969 if (!AR) 2970 return false; 2971 2972 return AR->isAffine(); 2973 } 2974 2975 bool AccessAnalysis::canCheckPtrAtRT( 2976 LoopVectorizationLegality::RuntimePointerCheck &RtCheck, 2977 unsigned &NumComparisons, ScalarEvolution *SE, 2978 Loop *TheLoop) { 2979 // Find pointers with computable bounds. We are going to use this information 2980 // to place a runtime bound check. 2981 unsigned NumReadPtrChecks = 0; 2982 unsigned NumWritePtrChecks = 0; 2983 bool CanDoRT = true; 2984 2985 bool IsDepCheckNeeded = isDependencyCheckNeeded(); 2986 // We assign consecutive id to access from different dependence sets. 2987 // Accesses within the same set don't need a runtime check. 2988 unsigned RunningDepId = 1; 2989 DenseMap<Value *, unsigned> DepSetId; 2990 2991 for (PtrAccessSet::iterator AI = Accesses.begin(), AE = Accesses.end(); 2992 AI != AE; ++AI) { 2993 const MemAccessInfo &Access = *AI; 2994 Value *Ptr = Access.getPointer(); 2995 bool IsWrite = Access.getInt(); 2996 2997 // Just add write checks if we have both. 2998 if (!IsWrite && Accesses.count(MemAccessInfo(Ptr, true))) 2999 continue; 3000 3001 if (IsWrite) 3002 ++NumWritePtrChecks; 3003 else 3004 ++NumReadPtrChecks; 3005 3006 if (hasComputableBounds(SE, Ptr)) { 3007 // The id of the dependence set. 3008 unsigned DepId; 3009 3010 if (IsDepCheckNeeded) { 3011 Value *Leader = DepCands.getLeaderValue(Access).getPointer(); 3012 unsigned &LeaderId = DepSetId[Leader]; 3013 if (!LeaderId) 3014 LeaderId = RunningDepId++; 3015 DepId = LeaderId; 3016 } else 3017 // Each access has its own dependence set. 3018 DepId = RunningDepId++; 3019 3020 RtCheck.insert(SE, TheLoop, Ptr, IsWrite, DepId); 3021 3022 DEBUG(dbgs() << "LV: Found a runtime check ptr:" << *Ptr <<"\n"); 3023 } else { 3024 CanDoRT = false; 3025 } 3026 } 3027 3028 if (IsDepCheckNeeded && CanDoRT && RunningDepId == 2) 3029 NumComparisons = 0; // Only one dependence set. 3030 else 3031 NumComparisons = (NumWritePtrChecks * (NumReadPtrChecks + 3032 NumWritePtrChecks - 1)); 3033 return CanDoRT; 3034 } 3035 3036 static bool isFunctionScopeIdentifiedObject(Value *Ptr) { 3037 return isNoAliasArgument(Ptr) || isNoAliasCall(Ptr) || isa<AllocaInst>(Ptr); 3038 } 3039 3040 void AccessAnalysis::processMemAccesses(bool UseDeferred) { 3041 // We process the set twice: first we process read-write pointers, last we 3042 // process read-only pointers. This allows us to skip dependence tests for 3043 // read-only pointers. 3044 3045 PtrAccessSet &S = UseDeferred ? DeferredAccesses : Accesses; 3046 for (PtrAccessSet::iterator AI = S.begin(), AE = S.end(); AI != AE; ++AI) { 3047 const MemAccessInfo &Access = *AI; 3048 Value *Ptr = Access.getPointer(); 3049 bool IsWrite = Access.getInt(); 3050 3051 DepCands.insert(Access); 3052 3053 // Memorize read-only pointers for later processing and skip them in the 3054 // first round (they need to be checked after we have seen all write 3055 // pointers). Note: we also mark pointer that are not consecutive as 3056 // "read-only" pointers (so that we check "a[b[i]] +="). Hence, we need the 3057 // second check for "!IsWrite". 3058 bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite; 3059 if (!UseDeferred && IsReadOnlyPtr) { 3060 DeferredAccesses.insert(Access); 3061 continue; 3062 } 3063 3064 bool NeedDepCheck = false; 3065 // Check whether there is the possiblity of dependency because of underlying 3066 // objects being the same. 3067 typedef SmallVector<Value*, 16> ValueVector; 3068 ValueVector TempObjects; 3069 GetUnderlyingObjects(Ptr, TempObjects, DL); 3070 for (ValueVector::iterator UI = TempObjects.begin(), UE = TempObjects.end(); 3071 UI != UE; ++UI) { 3072 Value *UnderlyingObj = *UI; 3073 3074 // If this is a write then it needs to be an identified object. If this a 3075 // read and all writes (so far) are identified function scope objects we 3076 // don't need an identified underlying object but only an Argument (the 3077 // next write is going to invalidate this assumption if it is 3078 // unidentified). 3079 // This is a micro-optimization for the case where all writes are 3080 // identified and we have one argument pointer. 3081 // Otherwise, we do need a runtime check. 3082 if ((IsWrite && !isFunctionScopeIdentifiedObject(UnderlyingObj)) || 3083 (!IsWrite && (!AreAllWritesIdentified || 3084 !isa<Argument>(UnderlyingObj)) && 3085 !isIdentifiedObject(UnderlyingObj))) { 3086 DEBUG(dbgs() << "LV: Found an unidentified " << 3087 (IsWrite ? "write" : "read" ) << " ptr:" << *UnderlyingObj << 3088 "\n"); 3089 IsRTCheckNeeded = (IsRTCheckNeeded || 3090 !isIdentifiedObject(UnderlyingObj) || 3091 !AreAllReadsIdentified); 3092 3093 if (IsWrite) 3094 AreAllWritesIdentified = false; 3095 if (!IsWrite) 3096 AreAllReadsIdentified = false; 3097 } 3098 3099 // If this is a write - check other reads and writes for conflicts. If 3100 // this is a read only check other writes for conflicts (but only if there 3101 // is no other write to the ptr - this is an optimization to catch "a[i] = 3102 // a[i] + " without having to do a dependence check). 3103 if ((IsWrite || IsReadOnlyPtr) && WriteObjects.count(UnderlyingObj)) 3104 NeedDepCheck = true; 3105 3106 if (IsWrite) 3107 WriteObjects.insert(UnderlyingObj); 3108 3109 // Create sets of pointers connected by shared underlying objects. 3110 UnderlyingObjToAccessMap::iterator Prev = 3111 ObjToLastAccess.find(UnderlyingObj); 3112 if (Prev != ObjToLastAccess.end()) 3113 DepCands.unionSets(Access, Prev->second); 3114 3115 ObjToLastAccess[UnderlyingObj] = Access; 3116 } 3117 3118 if (NeedDepCheck) 3119 CheckDeps.insert(Access); 3120 } 3121 } 3122 3123 namespace { 3124 /// \brief Checks memory dependences among accesses to the same underlying 3125 /// object to determine whether there vectorization is legal or not (and at 3126 /// which vectorization factor). 3127 /// 3128 /// This class works under the assumption that we already checked that memory 3129 /// locations with different underlying pointers are "must-not alias". 3130 /// We use the ScalarEvolution framework to symbolically evalutate access 3131 /// functions pairs. Since we currently don't restructure the loop we can rely 3132 /// on the program order of memory accesses to determine their safety. 3133 /// At the moment we will only deem accesses as safe for: 3134 /// * A negative constant distance assuming program order. 3135 /// 3136 /// Safe: tmp = a[i + 1]; OR a[i + 1] = x; 3137 /// a[i] = tmp; y = a[i]; 3138 /// 3139 /// The latter case is safe because later checks guarantuee that there can't 3140 /// be a cycle through a phi node (that is, we check that "x" and "y" is not 3141 /// the same variable: a header phi can only be an induction or a reduction, a 3142 /// reduction can't have a memory sink, an induction can't have a memory 3143 /// source). This is important and must not be violated (or we have to 3144 /// resort to checking for cycles through memory). 3145 /// 3146 /// * A positive constant distance assuming program order that is bigger 3147 /// than the biggest memory access. 3148 /// 3149 /// tmp = a[i] OR b[i] = x 3150 /// a[i+2] = tmp y = b[i+2]; 3151 /// 3152 /// Safe distance: 2 x sizeof(a[0]), and 2 x sizeof(b[0]), respectively. 3153 /// 3154 /// * Zero distances and all accesses have the same size. 3155 /// 3156 class MemoryDepChecker { 3157 public: 3158 typedef PointerIntPair<Value *, 1, bool> MemAccessInfo; 3159 typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet