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. Legalization of the IR is done 12 // in the codegen. However, the vectorizes uses (will use) the codegen 13 // interfaces to generate IR that is likely to result in an optimal binary. 14 // 15 // The loop vectorizer combines consecutive loop iteration 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/MapVector.h" 51 #include "llvm/ADT/SmallPtrSet.h" 52 #include "llvm/ADT/SmallSet.h" 53 #include "llvm/ADT/SmallVector.h" 54 #include "llvm/ADT/StringExtras.h" 55 #include "llvm/Analysis/AliasAnalysis.h" 56 #include "llvm/Analysis/AliasSetTracker.h" 57 #include "llvm/Analysis/Dominators.h" 58 #include "llvm/Analysis/LoopInfo.h" 59 #include "llvm/Analysis/LoopIterator.h" 60 #include "llvm/Analysis/LoopPass.h" 61 #include "llvm/Analysis/ScalarEvolution.h" 62 #include "llvm/Analysis/ScalarEvolutionExpander.h" 63 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 64 #include "llvm/Analysis/TargetTransformInfo.h" 65 #include "llvm/Analysis/ValueTracking.h" 66 #include "llvm/Analysis/Verifier.h" 67 #include "llvm/IR/Constants.h" 68 #include "llvm/IR/DataLayout.h" 69 #include "llvm/IR/DerivedTypes.h" 70 #include "llvm/IR/Function.h" 71 #include "llvm/IR/IRBuilder.h" 72 #include "llvm/IR/Instructions.h" 73 #include "llvm/IR/IntrinsicInst.h" 74 #include "llvm/IR/LLVMContext.h" 75 #include "llvm/IR/Module.h" 76 #include "llvm/IR/Type.h" 77 #include "llvm/IR/Value.h" 78 #include "llvm/Pass.h" 79 #include "llvm/Support/CommandLine.h" 80 #include "llvm/Support/Debug.h" 81 #include "llvm/Support/raw_ostream.h" 82 #include "llvm/Transforms/Scalar.h" 83 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 84 #include "llvm/Transforms/Utils/Local.h" 85 #include <algorithm> 86 #include <map> 87 88 using namespace llvm; 89 90 static cl::opt<unsigned> 91 VectorizationFactor("force-vector-width", cl::init(0), cl::Hidden, 92 cl::desc("Sets the SIMD width. Zero is autoselect.")); 93 94 static cl::opt<unsigned> 95 VectorizationUnroll("force-vector-unroll", cl::init(0), cl::Hidden, 96 cl::desc("Sets the vectorization unroll count. " 97 "Zero is autoselect.")); 98 99 static cl::opt<bool> 100 EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden, 101 cl::desc("Enable if-conversion during vectorization.")); 102 103 /// We don't vectorize loops with a known constant trip count below this number. 104 static cl::opt<unsigned> 105 TinyTripCountVectorThreshold("vectorizer-min-trip-count", cl::init(16), 106 cl::Hidden, 107 cl::desc("Don't vectorize loops with a constant " 108 "trip count that is smaller than this " 109 "value.")); 110 111 /// We don't unroll loops with a known constant trip count below this number. 112 static const unsigned TinyTripCountUnrollThreshold = 128; 113 114 /// When performing a runtime memory check, do not check more than this 115 /// number of pointers. Notice that the check is quadratic! 116 static const unsigned RuntimeMemoryCheckThreshold = 4; 117 118 namespace { 119 120 // Forward declarations. 121 class LoopVectorizationLegality; 122 class LoopVectorizationCostModel; 123 124 /// InnerLoopVectorizer vectorizes loops which contain only one basic 125 /// block to a specified vectorization factor (VF). 126 /// This class performs the widening of scalars into vectors, or multiple 127 /// scalars. This class also implements the following features: 128 /// * It inserts an epilogue loop for handling loops that don't have iteration 129 /// counts that are known to be a multiple of the vectorization factor. 130 /// * It handles the code generation for reduction variables. 131 /// * Scalarization (implementation using scalars) of un-vectorizable 132 /// instructions. 133 /// InnerLoopVectorizer does not perform any vectorization-legality 134 /// checks, and relies on the caller to check for the different legality 135 /// aspects. The InnerLoopVectorizer relies on the 136 /// LoopVectorizationLegality class to provide information about the induction 137 /// and reduction variables that were found to a given vectorization factor. 138 class InnerLoopVectorizer { 139 public: 140 InnerLoopVectorizer(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI, 141 DominatorTree *DT, DataLayout *DL, unsigned VecWidth, 142 unsigned UnrollFactor) 143 : OrigLoop(OrigLoop), SE(SE), LI(LI), DT(DT), DL(DL), VF(VecWidth), 144 UF(UnrollFactor), Builder(SE->getContext()), Induction(0), 145 OldInduction(0), WidenMap(UnrollFactor) {} 146 147 // Perform the actual loop widening (vectorization). 148 void vectorize(LoopVectorizationLegality *Legal) { 149 // Create a new empty loop. Unlink the old loop and connect the new one. 150 createEmptyLoop(Legal); 151 // Widen each instruction in the old loop to a new one in the new loop. 152 // Use the Legality module to find the induction and reduction variables. 153 vectorizeLoop(Legal); 154 // Register the new loop and update the analysis passes. 155 updateAnalysis(); 156 } 157 158 private: 159 /// A small list of PHINodes. 160 typedef SmallVector<PHINode*, 4> PhiVector; 161 /// When we unroll loops we have multiple vector values for each scalar. 162 /// This data structure holds the unrolled and vectorized values that 163 /// originated from one scalar instruction. 164 typedef SmallVector<Value*, 2> VectorParts; 165 166 /// Add code that checks at runtime if the accessed arrays overlap. 167 /// Returns the comparator value or NULL if no check is needed. 168 Instruction *addRuntimeCheck(LoopVectorizationLegality *Legal, 169 Instruction *Loc); 170 /// Create an empty loop, based on the loop ranges of the old loop. 171 void createEmptyLoop(LoopVectorizationLegality *Legal); 172 /// Copy and widen the instructions from the old loop. 173 void vectorizeLoop(LoopVectorizationLegality *Legal); 174 175 /// A helper function that computes the predicate of the block BB, assuming 176 /// that the header block of the loop is set to True. It returns the *entry* 177 /// mask for the block BB. 178 VectorParts createBlockInMask(BasicBlock *BB); 179 /// A helper function that computes the predicate of the edge between SRC 180 /// and DST. 181 VectorParts createEdgeMask(BasicBlock *Src, BasicBlock *Dst); 182 183 /// A helper function to vectorize a single BB within the innermost loop. 184 void vectorizeBlockInLoop(LoopVectorizationLegality *Legal, BasicBlock *BB, 185 PhiVector *PV); 186 187 /// Insert the new loop to the loop hierarchy and pass manager 188 /// and update the analysis passes. 189 void updateAnalysis(); 190 191 /// This instruction is un-vectorizable. Implement it as a sequence 192 /// of scalars. 193 void scalarizeInstruction(Instruction *Instr); 194 195 /// Vectorize Load and Store instructions, 196 void vectorizeMemoryInstruction(Instruction *Instr, 197 LoopVectorizationLegality *Legal); 198 199 /// Create a broadcast instruction. This method generates a broadcast 200 /// instruction (shuffle) for loop invariant values and for the induction 201 /// value. If this is the induction variable then we extend it to N, N+1, ... 202 /// this is needed because each iteration in the loop corresponds to a SIMD 203 /// element. 204 Value *getBroadcastInstrs(Value *V); 205 206 /// This function adds 0, 1, 2 ... to each vector element, starting at zero. 207 /// If Negate is set then negative numbers are added e.g. (0, -1, -2, ...). 208 /// The sequence starts at StartIndex. 209 Value *getConsecutiveVector(Value* Val, unsigned StartIdx, bool Negate); 210 211 /// When we go over instructions in the basic block we rely on previous 212 /// values within the current basic block or on loop invariant values. 213 /// When we widen (vectorize) values we place them in the map. If the values 214 /// are not within the map, they have to be loop invariant, so we simply 215 /// broadcast them into a vector. 216 VectorParts &getVectorValue(Value *V); 217 218 /// Generate a shuffle sequence that will reverse the vector Vec. 219 Value *reverseVector(Value *Vec); 220 221 /// This is a helper class that holds the vectorizer state. It maps scalar 222 /// instructions to vector instructions. When the code is 'unrolled' then 223 /// then a single scalar value is mapped to multiple vector parts. The parts 224 /// are stored in the VectorPart type. 225 struct ValueMap { 226 /// C'tor. UnrollFactor controls the number of vectors ('parts') that 227 /// are mapped. 228 ValueMap(unsigned UnrollFactor) : UF(UnrollFactor) {} 229 230 /// \return True if 'Key' is saved in the Value Map. 231 bool has(Value *Key) const { return MapStorage.count(Key); } 232 233 /// Initializes a new entry in the map. Sets all of the vector parts to the 234 /// save value in 'Val'. 235 /// \return A reference to a vector with splat values. 236 VectorParts &splat(Value *Key, Value *Val) { 237 VectorParts &Entry = MapStorage[Key]; 238 Entry.assign(UF, Val); 239 return Entry; 240 } 241 242 ///\return A reference to the value that is stored at 'Key'. 243 VectorParts &get(Value *Key) { 244 VectorParts &Entry = MapStorage[Key]; 245 if (Entry.empty()) 246 Entry.resize(UF); 247 assert(Entry.size() == UF); 248 return Entry; 249 } 250 251 private: 252 /// The unroll factor. Each entry in the map stores this number of vector 253 /// elements. 254 unsigned UF; 255 256 /// Map storage. We use std::map and not DenseMap because insertions to a 257 /// dense map invalidates its iterators. 258 std::map<Value *, VectorParts> MapStorage; 259 }; 260 261 /// The original loop. 262 Loop *OrigLoop; 263 /// Scev analysis to use. 264 ScalarEvolution *SE; 265 /// Loop Info. 266 LoopInfo *LI; 267 /// Dominator Tree. 268 DominatorTree *DT; 269 /// Data Layout. 270 DataLayout *DL; 271 /// The vectorization SIMD factor to use. Each vector will have this many 272 /// vector elements. 273 unsigned VF; 274 /// The vectorization unroll factor to use. Each scalar is vectorized to this 275 /// many different vector instructions. 276 unsigned UF; 277 278 /// The builder that we use 279 IRBuilder<> Builder; 280 281 // --- Vectorization state --- 282 283 /// The vector-loop preheader. 284 BasicBlock *LoopVectorPreHeader; 285 /// The scalar-loop preheader. 286 BasicBlock *LoopScalarPreHeader; 287 /// Middle Block between the vector and the scalar. 288 BasicBlock *LoopMiddleBlock; 289 ///The ExitBlock of the scalar loop. 290 BasicBlock *LoopExitBlock; 291 ///The vector loop body. 292 BasicBlock *LoopVectorBody; 293 ///The scalar loop body. 294 BasicBlock *LoopScalarBody; 295 /// A list of all bypass blocks. The first block is the entry of the loop. 296 SmallVector<BasicBlock *, 4> LoopBypassBlocks; 297 298 /// The new Induction variable which was added to the new block. 299 PHINode *Induction; 300 /// The induction variable of the old basic block. 301 PHINode *OldInduction; 302 /// Maps scalars to widened vectors. 303 ValueMap WidenMap; 304 }; 305 306 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and 307 /// to what vectorization factor. 308 /// This class does not look at the profitability of vectorization, only the 309 /// legality. This class has two main kinds of checks: 310 /// * Memory checks - The code in canVectorizeMemory checks if vectorization 311 /// will change the order of memory accesses in a way that will change the 312 /// correctness of the program. 313 /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory 314 /// checks for a number of different conditions, such as the availability of a 315 /// single induction variable, that all types are supported and vectorize-able, 316 /// etc. This code reflects the capabilities of InnerLoopVectorizer. 317 /// This class is also used by InnerLoopVectorizer for identifying 318 /// induction variable and the different reduction variables. 319 class LoopVectorizationLegality { 320 public: 321 LoopVectorizationLegality(Loop *L, ScalarEvolution *SE, DataLayout *DL, 322 DominatorTree *DT) 323 : TheLoop(L), SE(SE), DL(DL), DT(DT), Induction(0) {} 324 325 /// This enum represents the kinds of reductions that we support. 326 enum ReductionKind { 327 RK_NoReduction, ///< Not a reduction. 328 RK_IntegerAdd, ///< Sum of integers. 329 RK_IntegerMult, ///< Product of integers. 330 RK_IntegerOr, ///< Bitwise or logical OR of numbers. 331 RK_IntegerAnd, ///< Bitwise or logical AND of numbers. 332 RK_IntegerXor, ///< Bitwise or logical XOR of numbers. 333 RK_FloatAdd, ///< Sum of floats. 334 RK_FloatMult ///< Product of floats. 335 }; 336 337 /// This enum represents the kinds of inductions that we support. 338 enum InductionKind { 339 IK_NoInduction, ///< Not an induction variable. 340 IK_IntInduction, ///< Integer induction variable. Step = 1. 341 IK_ReverseIntInduction, ///< Reverse int induction variable. Step = -1. 342 IK_PtrInduction, ///< Pointer induction var. Step = sizeof(elem). 343 IK_ReversePtrInduction ///< Reverse ptr indvar. Step = - sizeof(elem). 344 }; 345 346 /// This POD struct holds information about reduction variables. 347 struct ReductionDescriptor { 348 ReductionDescriptor() : StartValue(0), LoopExitInstr(0), 349 Kind(RK_NoReduction) {} 350 351 ReductionDescriptor(Value *Start, Instruction *Exit, ReductionKind K) 352 : StartValue(Start), LoopExitInstr(Exit), Kind(K) {} 353 354 // The starting value of the reduction. 355 // It does not have to be zero! 356 Value *StartValue; 357 // The instruction who's value is used outside the loop. 358 Instruction *LoopExitInstr; 359 // The kind of the reduction. 360 ReductionKind Kind; 361 }; 362 363 // This POD struct holds information about the memory runtime legality 364 // check that a group of pointers do not overlap. 365 struct RuntimePointerCheck { 366 RuntimePointerCheck() : Need(false) {} 367 368 /// Reset the state of the pointer runtime information. 369 void reset() { 370 Need = false; 371 Pointers.clear(); 372 Starts.clear(); 373 Ends.clear(); 374 } 375 376 /// Insert a pointer and calculate the start and end SCEVs. 377 void insert(ScalarEvolution *SE, Loop *Lp, Value *Ptr); 378 379 /// This flag indicates if we need to add the runtime check. 380 bool Need; 381 /// Holds the pointers that we need to check. 382 SmallVector<Value*, 2> Pointers; 383 /// Holds the pointer value at the beginning of the loop. 384 SmallVector<const SCEV*, 2> Starts; 385 /// Holds the pointer value at the end of the loop. 386 SmallVector<const SCEV*, 2> Ends; 387 }; 388 389 /// A POD for saving information about induction variables. 390 struct InductionInfo { 391 InductionInfo(Value *Start, InductionKind K) : StartValue(Start), IK(K) {} 392 InductionInfo() : StartValue(0), IK(IK_NoInduction) {} 393 /// Start value. 394 Value *StartValue; 395 /// Induction kind. 396 InductionKind IK; 397 }; 398 399 /// ReductionList contains the reduction descriptors for all 400 /// of the reductions that were found in the loop. 401 typedef DenseMap<PHINode*, ReductionDescriptor> ReductionList; 402 403 /// InductionList saves induction variables and maps them to the 404 /// induction descriptor. 405 typedef MapVector<PHINode*, InductionInfo> InductionList; 406 407 /// Returns true if it is legal to vectorize this loop. 408 /// This does not mean that it is profitable to vectorize this 409 /// loop, only that it is legal to do so. 410 bool canVectorize(); 411 412 /// Returns the Induction variable. 413 PHINode *getInduction() { return Induction; } 414 415 /// Returns the reduction variables found in the loop. 416 ReductionList *getReductionVars() { return &Reductions; } 417 418 /// Returns the induction variables found in the loop. 419 InductionList *getInductionVars() { return &Inductions; } 420 421 /// Returns True if V is an induction variable in this loop. 422 bool isInductionVariable(const Value *V); 423 424 /// Return true if the block BB needs to be predicated in order for the loop 425 /// to be vectorized. 426 bool blockNeedsPredication(BasicBlock *BB); 427 428 /// Check if this pointer is consecutive when vectorizing. This happens 429 /// when the last index of the GEP is the induction variable, or that the 430 /// pointer itself is an induction variable. 431 /// This check allows us to vectorize A[idx] into a wide load/store. 432 /// Returns: 433 /// 0 - Stride is unknown or non consecutive. 434 /// 1 - Address is consecutive. 435 /// -1 - Address is consecutive, and decreasing. 436 int isConsecutivePtr(Value *Ptr); 437 438 /// Returns true if the value V is uniform within the loop. 439 bool isUniform(Value *V); 440 441 /// Returns true if this instruction will remain scalar after vectorization. 442 bool isUniformAfterVectorization(Instruction* I) { return Uniforms.count(I); } 443 444 /// Returns the information that we collected about runtime memory check. 445 RuntimePointerCheck *getRuntimePointerCheck() { return &PtrRtCheck; } 446 private: 447 /// Check if a single basic block loop is vectorizable. 448 /// At this point we know that this is a loop with a constant trip count 449 /// and we only need to check individual instructions. 450 bool canVectorizeInstrs(); 451 452 /// When we vectorize loops we may change the order in which 453 /// we read and write from memory. This method checks if it is 454 /// legal to vectorize the code, considering only memory constrains. 455 /// Returns true if the loop is vectorizable 456 bool canVectorizeMemory(); 457 458 /// Return true if we can vectorize this loop using the IF-conversion 459 /// transformation. 460 bool canVectorizeWithIfConvert(); 461 462 /// Collect the variables that need to stay uniform after vectorization. 463 void collectLoopUniforms(); 464 465 /// Return true if all of the instructions in the block can be speculatively 466 /// executed. 467 bool blockCanBePredicated(BasicBlock *BB); 468 469 /// Returns True, if 'Phi' is the kind of reduction variable for type 470 /// 'Kind'. If this is a reduction variable, it adds it to ReductionList. 471 bool AddReductionVar(PHINode *Phi, ReductionKind Kind); 472 /// Returns true if the instruction I can be a reduction variable of type 473 /// 'Kind'. 474 bool isReductionInstr(Instruction *I, ReductionKind Kind); 475 /// Returns the induction kind of Phi. This function may return NoInduction 476 /// if the PHI is not an induction variable. 477 InductionKind isInductionVariable(PHINode *Phi); 478 /// Return true if can compute the address bounds of Ptr within the loop. 479 bool hasComputableBounds(Value *Ptr); 480 481 /// The loop that we evaluate. 482 Loop *TheLoop; 483 /// Scev analysis. 484 ScalarEvolution *SE; 485 /// DataLayout analysis. 486 DataLayout *DL; 487 // Dominators. 488 DominatorTree *DT; 489 490 // --- vectorization state --- // 491 492 /// Holds the integer induction variable. This is the counter of the 493 /// loop. 494 PHINode *Induction; 495 /// Holds the reduction variables. 496 ReductionList Reductions; 497 /// Holds all of the induction variables that we found in the loop. 498 /// Notice that inductions don't need to start at zero and that induction 499 /// variables can be pointers. 500 InductionList Inductions; 501 502 /// Allowed outside users. This holds the reduction 503 /// vars which can be accessed from outside the loop. 504 SmallPtrSet<Value*, 4> AllowedExit; 505 /// This set holds the variables which are known to be uniform after 506 /// vectorization. 507 SmallPtrSet<Instruction*, 4> Uniforms; 508 /// We need to check that all of the pointers in this list are disjoint 509 /// at runtime. 510 RuntimePointerCheck PtrRtCheck; 511 }; 512 513 /// LoopVectorizationCostModel - estimates the expected speedups due to 514 /// vectorization. 515 /// In many cases vectorization is not profitable. This can happen because of 516 /// a number of reasons. In this class we mainly attempt to predict the 517 /// expected speedup/slowdowns due to the supported instruction set. We use the 518 /// TargetTransformInfo to query the different backends for the cost of 519 /// different operations. 520 class LoopVectorizationCostModel { 521 public: 522 LoopVectorizationCostModel(Loop *L, ScalarEvolution *SE, LoopInfo *LI, 523 LoopVectorizationLegality *Legal, 524 const TargetTransformInfo &TTI, 525 DataLayout *DL) 526 : TheLoop(L), SE(SE), LI(LI), Legal(Legal), TTI(TTI), DL(DL) {} 527 528 /// Information about vectorization costs 529 struct VectorizationFactor { 530 unsigned Width; // Vector width with best cost 531 unsigned Cost; // Cost of the loop with that width 532 }; 533 /// \return The most profitable vectorization factor and the cost of that VF. 534 /// This method checks every power of two up to VF. If UserVF is not ZERO 535 /// then this vectorization factor will be selected if vectorization is 536 /// possible. 537 VectorizationFactor selectVectorizationFactor(bool OptForSize, 538 unsigned UserVF); 539 540 /// \return The size (in bits) of the widest type in the code that 541 /// needs to be vectorized. We ignore values that remain scalar such as 542 /// 64 bit loop indices. 543 unsigned getWidestType(); 544 545 /// \return The most profitable unroll factor. 546 /// If UserUF is non-zero then this method finds the best unroll-factor 547 /// based on register pressure and other parameters. 548 /// VF and LoopCost are the selected vectorization factor and the cost of the 549 /// selected VF. 550 unsigned selectUnrollFactor(bool OptForSize, unsigned UserUF, unsigned VF, 551 unsigned LoopCost); 552 553 /// \brief A struct that represents some properties of the register usage 554 /// of a loop. 555 struct RegisterUsage { 556 /// Holds the number of loop invariant values that are used in the loop. 557 unsigned LoopInvariantRegs; 558 /// Holds the maximum number of concurrent live intervals in the loop. 559 unsigned MaxLocalUsers; 560 /// Holds the number of instructions in the loop. 561 unsigned NumInstructions; 562 }; 563 564 /// \return information about the register usage of the loop. 565 RegisterUsage calculateRegisterUsage(); 566 567 private: 568 /// Returns the expected execution cost. The unit of the cost does 569 /// not matter because we use the 'cost' units to compare different 570 /// vector widths. The cost that is returned is *not* normalized by 571 /// the factor width. 572 unsigned expectedCost(unsigned VF); 573 574 /// Returns the execution time cost of an instruction for a given vector 575 /// width. Vector width of one means scalar. 576 unsigned getInstructionCost(Instruction *I, unsigned VF); 577 578 /// A helper function for converting Scalar types to vector types. 579 /// If the incoming type is void, we return void. If the VF is 1, we return 580 /// the scalar type. 581 static Type* ToVectorTy(Type *Scalar, unsigned VF); 582 583 /// Returns whether the instruction is a load or store and will be a emitted 584 /// as a vector operation. 585 bool isConsecutiveLoadOrStore(Instruction *I); 586 587 /// The loop that we evaluate. 588 Loop *TheLoop; 589 /// Scev analysis. 590 ScalarEvolution *SE; 591 /// Loop Info analysis. 592 LoopInfo *LI; 593 /// Vectorization legality. 594 LoopVectorizationLegality *Legal; 595 /// Vector target information. 596 const TargetTransformInfo &TTI; 597 /// Target data layout information. 598 DataLayout *DL; 599 }; 600 601 /// The LoopVectorize Pass. 602 struct LoopVectorize : public LoopPass { 603 /// Pass identification, replacement for typeid 604 static char ID; 605 606 explicit LoopVectorize() : LoopPass(ID) { 607 initializeLoopVectorizePass(*PassRegistry::getPassRegistry()); 608 } 609 610 ScalarEvolution *SE; 611 DataLayout *DL; 612 LoopInfo *LI; 613 TargetTransformInfo *TTI; 614 DominatorTree *DT; 615 616 virtual bool runOnLoop(Loop *L, LPPassManager &LPM) { 617 // We only vectorize innermost loops. 618 if (!L->empty()) 619 return false; 620 621 SE = &getAnalysis<ScalarEvolution>(); 622 DL = getAnalysisIfAvailable<DataLayout>(); 623 LI = &getAnalysis<LoopInfo>(); 624 TTI = &getAnalysis<TargetTransformInfo>(); 625 DT = &getAnalysis<DominatorTree>(); 626 627 DEBUG(dbgs() << "LV: Checking a loop in \"" << 628 L->getHeader()->getParent()->getName() << "\"\n"); 629 630 // Check if it is legal to vectorize the loop. 631 LoopVectorizationLegality LVL(L, SE, DL, DT); 632 if (!LVL.canVectorize()) { 633 DEBUG(dbgs() << "LV: Not vectorizing.\n"); 634 return false; 635 } 636 637 // Use the cost model. 638 LoopVectorizationCostModel CM(L, SE, LI, &LVL, *TTI, DL); 639 640 // Check the function attribues to find out if this function should be 641 // optimized for size. 642 Function *F = L->getHeader()->getParent(); 643 Attribute::AttrKind SzAttr = Attribute::OptimizeForSize; 644 Attribute::AttrKind FlAttr = Attribute::NoImplicitFloat; 645 unsigned FnIndex = AttributeSet::FunctionIndex; 646 bool OptForSize = F->getAttributes().hasAttribute(FnIndex, SzAttr); 647 bool NoFloat = F->getAttributes().hasAttribute(FnIndex, FlAttr); 648 649 if (NoFloat) { 650 DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat" 651 "attribute is used.\n"); 652 return false; 653 } 654 655 // Select the optimal vectorization factor. 656 LoopVectorizationCostModel::VectorizationFactor VF; 657 VF = CM.selectVectorizationFactor(OptForSize, VectorizationFactor); 658 // Select the unroll factor. 659 unsigned UF = CM.selectUnrollFactor(OptForSize, VectorizationUnroll, 660 VF.Width, VF.Cost); 661 662 if (VF.Width == 1) { 663 DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n"); 664 return false; 665 } 666 667 DEBUG(dbgs() << "LV: Found a vectorizable loop ("<< VF.Width << ") in "<< 668 F->getParent()->getModuleIdentifier()<<"\n"); 669 DEBUG(dbgs() << "LV: Unroll Factor is " << UF << "\n"); 670 671 // If we decided that it is *legal* to vectorizer the loop then do it. 672 InnerLoopVectorizer LB(L, SE, LI, DT, DL, VF.Width, UF); 673 LB.vectorize(&LVL); 674 675 DEBUG(verifyFunction(*L->getHeader()->getParent())); 676 return true; 677 } 678 679 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 680 LoopPass::getAnalysisUsage(AU); 681 AU.addRequiredID(LoopSimplifyID); 682 AU.addRequiredID(LCSSAID); 683 AU.addRequired<DominatorTree>(); 684 AU.addRequired<LoopInfo>(); 685 AU.addRequired<ScalarEvolution>(); 686 AU.addRequired<TargetTransformInfo>(); 687 AU.addPreserved<LoopInfo>(); 688 AU.addPreserved<DominatorTree>(); 689 } 690 691 }; 692 693 } // end anonymous namespace 694 695 //===----------------------------------------------------------------------===// 696 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and 697 // LoopVectorizationCostModel. 698 //===----------------------------------------------------------------------===// 699 700 void 701 LoopVectorizationLegality::RuntimePointerCheck::insert(ScalarEvolution *SE, 702 Loop *Lp, Value *Ptr) { 703 const SCEV *Sc = SE->getSCEV(Ptr); 704 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc); 705 assert(AR && "Invalid addrec expression"); 706 const SCEV *Ex = SE->getExitCount(Lp, Lp->getLoopLatch()); 707 const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE); 708 Pointers.push_back(Ptr); 709 Starts.push_back(AR->getStart()); 710 Ends.push_back(ScEnd); 711 } 712 713 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) { 714 // Save the current insertion location. 715 Instruction *Loc = Builder.GetInsertPoint(); 716 717 // We need to place the broadcast of invariant variables outside the loop. 718 Instruction *Instr = dyn_cast<Instruction>(V); 719 bool NewInstr = (Instr && Instr->getParent() == LoopVectorBody); 720 bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr; 721 722 // Place the code for broadcasting invariant variables in the new preheader. 723 if (Invariant) 724 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator()); 725 726 // Broadcast the scalar into all locations in the vector. 727 Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast"); 728 729 // Restore the builder insertion point. 730 if (Invariant) 731 Builder.SetInsertPoint(Loc); 732 733 return Shuf; 734 } 735 736 Value *InnerLoopVectorizer::getConsecutiveVector(Value* Val, unsigned StartIdx, 737 bool Negate) { 738 assert(Val->getType()->isVectorTy() && "Must be a vector"); 739 assert(Val->getType()->getScalarType()->isIntegerTy() && 740 "Elem must be an integer"); 741 // Create the types. 742 Type *ITy = Val->getType()->getScalarType(); 743 VectorType *Ty = cast<VectorType>(Val->getType()); 744 int VLen = Ty->getNumElements(); 745 SmallVector<Constant*, 8> Indices; 746 747 // Create a vector of consecutive numbers from zero to VF. 748 for (int i = 0; i < VLen; ++i) { 749 int Idx = Negate ? (-i): i; 750 Indices.push_back(ConstantInt::get(ITy, StartIdx + Idx)); 751 } 752 753 // Add the consecutive indices to the vector value. 754 Constant *Cv = ConstantVector::get(Indices); 755 assert(Cv->getType() == Val->getType() && "Invalid consecutive vec"); 756 return Builder.CreateAdd(Val, Cv, "induction"); 757 } 758 759 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) { 760 assert(Ptr->getType()->isPointerTy() && "Unexpected non ptr"); 761 // Make sure that the pointer does not point to structs. 762 if (cast<PointerType>(Ptr->getType())->getElementType()->isAggregateType()) 763 return 0; 764 765 // If this value is a pointer induction variable we know it is consecutive. 766 PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr); 767 if (Phi && Inductions.count(Phi)) { 768 InductionInfo II = Inductions[Phi]; 769 if (IK_PtrInduction == II.IK) 770 return 1; 771 else if (IK_ReversePtrInduction == II.IK) 772 return -1; 773 } 774 775 GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr); 776 if (!Gep) 777 return 0; 778 779 unsigned NumOperands = Gep->getNumOperands(); 780 Value *LastIndex = Gep->getOperand(NumOperands - 1); 781 782 Value *GpPtr = Gep->getPointerOperand(); 783 // If this GEP value is a consecutive pointer induction variable and all of 784 // the indices are constant then we know it is consecutive. We can 785 Phi = dyn_cast<PHINode>(GpPtr); 786 if (Phi && Inductions.count(Phi)) { 787 788 // Make sure that the pointer does not point to structs. 789 PointerType *GepPtrType = cast<PointerType>(GpPtr->getType()); 790 if (GepPtrType->getElementType()->isAggregateType()) 791 return 0; 792 793 // Make sure that all of the index operands are loop invariant. 794 for (unsigned i = 1; i < NumOperands; ++i) 795 if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop)) 796 return 0; 797 798 InductionInfo II = Inductions[Phi]; 799 if (IK_PtrInduction == II.IK) 800 return 1; 801 else if (IK_ReversePtrInduction == II.IK) 802 return -1; 803 } 804 805 // Check that all of the gep indices are uniform except for the last. 806 for (unsigned i = 0; i < NumOperands - 1; ++i) 807 if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop)) 808 return 0; 809 810 // We can emit wide load/stores only if the last index is the induction 811 // variable. 812 const SCEV *Last = SE->getSCEV(LastIndex); 813 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) { 814 const SCEV *Step = AR->getStepRecurrence(*SE); 815 816 // The memory is consecutive because the last index is consecutive 817 // and all other indices are loop invariant. 818 if (Step->isOne()) 819 return 1; 820 if (Step->isAllOnesValue()) 821 return -1; 822 } 823 824 return 0; 825 } 826 827 bool LoopVectorizationLegality::isUniform(Value *V) { 828 return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop)); 829 } 830 831 InnerLoopVectorizer::VectorParts& 832 InnerLoopVectorizer::getVectorValue(Value *V) { 833 assert(V != Induction && "The new induction variable should not be used."); 834 assert(!V->getType()->isVectorTy() && "Can't widen a vector"); 835 836 // If we have this scalar in the map, return it. 837 if (WidenMap.has(V)) 838 return WidenMap.get(V); 839 840 // If this scalar is unknown, assume that it is a constant or that it is 841 // loop invariant. Broadcast V and save the value for future uses. 842 Value *B = getBroadcastInstrs(V); 843 return WidenMap.splat(V, B); 844 } 845 846 Value *InnerLoopVectorizer::reverseVector(Value *Vec) { 847 assert(Vec->getType()->isVectorTy() && "Invalid type"); 848 SmallVector<Constant*, 8> ShuffleMask; 849 for (unsigned i = 0; i < VF; ++i) 850 ShuffleMask.push_back(Builder.getInt32(VF - i - 1)); 851 852 return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()), 853 ConstantVector::get(ShuffleMask), 854 "reverse"); 855 } 856 857 858 void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr, 859 LoopVectorizationLegality *Legal) { 860 // Attempt to issue a wide load. 861 LoadInst *LI = dyn_cast<LoadInst>(Instr); 862 StoreInst *SI = dyn_cast<StoreInst>(Instr); 863 864 assert((LI || SI) && "Invalid Load/Store instruction"); 865 866 Type *ScalarDataTy = LI ? LI->getType() : SI->getValueOperand()->getType(); 867 Type *DataTy = VectorType::get(ScalarDataTy, VF); 868 Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand(); 869 unsigned Alignment = LI ? LI->getAlignment() : SI->getAlignment(); 870 871 // If the pointer is loop invariant or if it is non consecutive, 872 // scalarize the load. 873 int Stride = Legal->isConsecutivePtr(Ptr); 874 bool Reverse = Stride < 0; 875 bool UniformLoad = LI && Legal->isUniform(Ptr); 876 if (Stride == 0 || UniformLoad) 877 return scalarizeInstruction(Instr); 878 879 Constant *Zero = Builder.getInt32(0); 880 VectorParts &Entry = WidenMap.get(Instr); 881 882 // Handle consecutive loads/stores. 883 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr); 884 if (Gep && Legal->isInductionVariable(Gep->getPointerOperand())) { 885 Value *PtrOperand = Gep->getPointerOperand(); 886 Value *FirstBasePtr = getVectorValue(PtrOperand)[0]; 887 FirstBasePtr = Builder.CreateExtractElement(FirstBasePtr, Zero); 888 889 // Create the new GEP with the new induction variable. 890 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone()); 891 Gep2->setOperand(0, FirstBasePtr); 892 Gep2->setName("gep.indvar.base"); 893 Ptr = Builder.Insert(Gep2); 894 } else if (Gep) { 895 assert(SE->isLoopInvariant(SE->getSCEV(Gep->getPointerOperand()), 896 OrigLoop) && "Base ptr must be invariant"); 897 898 // The last index does not have to be the induction. It can be 899 // consecutive and be a function of the index. For example A[I+1]; 900 unsigned NumOperands = Gep->getNumOperands(); 901 902 Value *LastGepOperand = Gep->getOperand(NumOperands - 1); 903 VectorParts &GEPParts = getVectorValue(LastGepOperand); 904 Value *LastIndex = GEPParts[0]; 905 LastIndex = Builder.CreateExtractElement(LastIndex, Zero); 906 907 // Create the new GEP with the new induction variable. 908 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone()); 909 Gep2->setOperand(NumOperands - 1, LastIndex); 910 Gep2->setName("gep.indvar.idx"); 911 Ptr = Builder.Insert(Gep2); 912 } else { 913 // Use the induction element ptr. 914 assert(isa<PHINode>(Ptr) && "Invalid induction ptr"); 915 VectorParts &PtrVal = getVectorValue(Ptr); 916 Ptr = Builder.CreateExtractElement(PtrVal[0], Zero); 917 } 918 919 // Handle Stores: 920 if (SI) { 921 assert(!Legal->isUniform(SI->getPointerOperand()) && 922 "We do not allow storing to uniform addresses"); 923 924 VectorParts &StoredVal = getVectorValue(SI->getValueOperand()); 925 for (unsigned Part = 0; Part < UF; ++Part) { 926 // Calculate the pointer for the specific unroll-part. 927 Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF)); 928 929 if (Reverse) { 930 // If we store to reverse consecutive memory locations then we need 931 // to reverse the order of elements in the stored value. 932 StoredVal[Part] = reverseVector(StoredVal[Part]); 933 // If the address is consecutive but reversed, then the 934 // wide store needs to start at the last vector element. 935 PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF)); 936 PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF)); 937 } 938 939 Value *VecPtr = Builder.CreateBitCast(PartPtr, DataTy->getPointerTo()); 940 Builder.CreateStore(StoredVal[Part], VecPtr)->setAlignment(Alignment); 941 } 942 } 943 944 for (unsigned Part = 0; Part < UF; ++Part) { 945 // Calculate the pointer for the specific unroll-part. 946 Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF)); 947 948 if (Reverse) { 949 // If the address is consecutive but reversed, then the 950 // wide store needs to start at the last vector element. 951 PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF)); 952 PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF)); 953 } 954 955 Value *VecPtr = Builder.CreateBitCast(PartPtr, DataTy->getPointerTo()); 956 Value *LI = Builder.CreateLoad(VecPtr, "wide.load"); 957 cast<LoadInst>(LI)->setAlignment(Alignment); 958 Entry[Part] = Reverse ? reverseVector(LI) : LI; 959 } 960 } 961 962 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr) { 963 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors"); 964 // Holds vector parameters or scalars, in case of uniform vals. 965 SmallVector<VectorParts, 4> Params; 966 967 // Find all of the vectorized parameters. 968 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) { 969 Value *SrcOp = Instr->getOperand(op); 970 971 // If we are accessing the old induction variable, use the new one. 972 if (SrcOp == OldInduction) { 973 Params.push_back(getVectorValue(SrcOp)); 974 continue; 975 } 976 977 // Try using previously calculated values. 978 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp); 979 980 // If the src is an instruction that appeared earlier in the basic block 981 // then it should already be vectorized. 982 if (SrcInst && OrigLoop->contains(SrcInst)) { 983 assert(WidenMap.has(SrcInst) && "Source operand is unavailable"); 984 // The parameter is a vector value from earlier. 985 Params.push_back(WidenMap.get(SrcInst)); 986 } else { 987 // The parameter is a scalar from outside the loop. Maybe even a constant. 988 VectorParts Scalars; 989 Scalars.append(UF, SrcOp); 990 Params.push_back(Scalars); 991 } 992 } 993 994 assert(Params.size() == Instr->getNumOperands() && 995 "Invalid number of operands"); 996 997 // Does this instruction return a value ? 998 bool IsVoidRetTy = Instr->getType()->isVoidTy(); 999 1000 Value *UndefVec = IsVoidRetTy ? 0 : 1001 UndefValue::get(VectorType::get(Instr->getType(), VF)); 1002 // Create a new entry in the WidenMap and initialize it to Undef or Null. 1003 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec); 1004 1005 // For each scalar that we create: 1006 for (unsigned Width = 0; Width < VF; ++Width) { 1007 // For each vector unroll 'part': 1008 for (unsigned Part = 0; Part < UF; ++Part) { 1009 Instruction *Cloned = Instr->clone(); 1010 if (!IsVoidRetTy) 1011 Cloned->setName(Instr->getName() + ".cloned"); 1012 // Replace the operands of the cloned instrucions with extracted scalars. 1013 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) { 1014 Value *Op = Params[op][Part]; 1015 // Param is a vector. Need to extract the right lane. 1016 if (Op->getType()->isVectorTy()) 1017 Op = Builder.CreateExtractElement(Op, Builder.getInt32(Width)); 1018 Cloned->setOperand(op, Op); 1019 } 1020 1021 // Place the cloned scalar in the new loop. 1022 Builder.Insert(Cloned); 1023 1024 // If the original scalar returns a value we need to place it in a vector 1025 // so that future users will be able to use it. 1026 if (!IsVoidRetTy) 1027 VecResults[Part] = Builder.CreateInsertElement(VecResults[Part], Cloned, 1028 Builder.getInt32(Width)); 1029 } 1030 } 1031 } 1032 1033 Instruction * 1034 InnerLoopVectorizer::addRuntimeCheck(LoopVectorizationLegality *Legal, 1035 Instruction *Loc) { 1036 LoopVectorizationLegality::RuntimePointerCheck *PtrRtCheck = 1037 Legal->getRuntimePointerCheck(); 1038 1039 if (!PtrRtCheck->Need) 1040 return NULL; 1041 1042 Instruction *MemoryRuntimeCheck = 0; 1043 unsigned NumPointers = PtrRtCheck->Pointers.size(); 1044 SmallVector<Value* , 2> Starts; 1045 SmallVector<Value* , 2> Ends; 1046 1047 SCEVExpander Exp(*SE, "induction"); 1048 1049 // Use this type for pointer arithmetic. 1050 Type* PtrArithTy = Type::getInt8PtrTy(Loc->getContext(), 0); 1051 1052 for (unsigned i = 0; i < NumPointers; ++i) { 1053 Value *Ptr = PtrRtCheck->Pointers[i]; 1054 const SCEV *Sc = SE->getSCEV(Ptr); 1055 1056 if (SE->isLoopInvariant(Sc, OrigLoop)) { 1057 DEBUG(dbgs() << "LV: Adding RT check for a loop invariant ptr:" << 1058 *Ptr <<"\n"); 1059 Starts.push_back(Ptr); 1060 Ends.push_back(Ptr); 1061 } else { 1062 DEBUG(dbgs() << "LV: Adding RT check for range:" << *Ptr <<"\n"); 1063 1064 Value *Start = Exp.expandCodeFor(PtrRtCheck->Starts[i], PtrArithTy, Loc); 1065 Value *End = Exp.expandCodeFor(PtrRtCheck->Ends[i], PtrArithTy, Loc); 1066 Starts.push_back(Start); 1067 Ends.push_back(End); 1068 } 1069 } 1070 1071 IRBuilder<> ChkBuilder(Loc); 1072 1073 for (unsigned i = 0; i < NumPointers; ++i) { 1074 for (unsigned j = i+1; j < NumPointers; ++j) { 1075 Value *Start0 = ChkBuilder.CreateBitCast(Starts[i], PtrArithTy, "bc"); 1076 Value *Start1 = ChkBuilder.CreateBitCast(Starts[j], PtrArithTy, "bc"); 1077 Value *End0 = ChkBuilder.CreateBitCast(Ends[i], PtrArithTy, "bc"); 1078 Value *End1 = ChkBuilder.CreateBitCast(Ends[j], PtrArithTy, "bc"); 1079 1080 Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0"); 1081 Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1"); 1082 Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict"); 1083 if (MemoryRuntimeCheck) 1084 IsConflict = ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict, 1085 "conflict.rdx"); 1086 1087 MemoryRuntimeCheck = cast<Instruction>(IsConflict); 1088 } 1089 } 1090 1091 return MemoryRuntimeCheck; 1092 } 1093 1094 void 1095 InnerLoopVectorizer::createEmptyLoop(LoopVectorizationLegality *Legal) { 1096 /* 1097 In this function we generate a new loop. The new loop will contain 1098 the vectorized instructions while the old loop will continue to run the 1099 scalar remainder. 1100 1101 [ ] <-- vector loop bypass (may consist of multiple blocks). 1102 / | 1103 / v 1104 | [ ] <-- vector pre header. 1105 | | 1106 | v 1107 | [ ] \ 1108 | [ ]_| <-- vector loop. 1109 | | 1110 \ v 1111 >[ ] <--- middle-block. 1112 / | 1113 / v 1114 | [ ] <--- new preheader. 1115 | | 1116 | v 1117 | [ ] \ 1118 | [ ]_| <-- old scalar loop to handle remainder. 1119 \ | 1120 \ v 1121 >[ ] <-- exit block. 1122 ... 1123 */ 1124 1125 BasicBlock *OldBasicBlock = OrigLoop->getHeader(); 1126 BasicBlock *BypassBlock = OrigLoop->getLoopPreheader(); 1127 BasicBlock *ExitBlock = OrigLoop->getExitBlock(); 1128 assert(ExitBlock && "Must have an exit block"); 1129 1130 // Some loops have a single integer induction variable, while other loops 1131 // don't. One example is c++ iterators that often have multiple pointer 1132 // induction variables. In the code below we also support a case where we 1133 // don't have a single induction variable. 1134 OldInduction = Legal->getInduction(); 1135 Type *IdxTy = OldInduction ? OldInduction->getType() : 1136 DL->getIntPtrType(SE->getContext()); 1137 1138 // Find the loop boundaries. 1139 const SCEV *ExitCount = SE->getExitCount(OrigLoop, OrigLoop->getLoopLatch()); 1140 assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count"); 1141 1142 // Get the total trip count from the count by adding 1. 1143 ExitCount = SE->getAddExpr(ExitCount, 1144 SE->getConstant(ExitCount->getType(), 1)); 1145 1146 // Expand the trip count and place the new instructions in the preheader. 1147 // Notice that the pre-header does not change, only the loop body. 1148 SCEVExpander Exp(*SE, "induction"); 1149 1150 // Count holds the overall loop count (N). 1151 Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(), 1152 BypassBlock->getTerminator()); 1153 1154 // The loop index does not have to start at Zero. Find the original start 1155 // value from the induction PHI node. If we don't have an induction variable 1156 // then we know that it starts at zero. 1157 Value *StartIdx = OldInduction ? 1158 OldInduction->getIncomingValueForBlock(BypassBlock): 1159 ConstantInt::get(IdxTy, 0); 1160 1161 assert(BypassBlock && "Invalid loop structure"); 1162 LoopBypassBlocks.push_back(BypassBlock); 1163 1164 // Split the single block loop into the two loop structure described above. 1165 BasicBlock *VectorPH = 1166 BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph"); 1167 BasicBlock *VecBody = 1168 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body"); 1169 BasicBlock *MiddleBlock = 1170 VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block"); 1171 BasicBlock *ScalarPH = 1172 MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph"); 1173 1174 // Use this IR builder to create the loop instructions (Phi, Br, Cmp) 1175 // inside the loop. 1176 Builder.SetInsertPoint(VecBody->getFirstInsertionPt()); 1177 1178 // Generate the induction variable. 1179 Induction = Builder.CreatePHI(IdxTy, 2, "index"); 1180 // The loop step is equal to the vectorization factor (num of SIMD elements) 1181 // times the unroll factor (num of SIMD instructions). 1182 Constant *Step = ConstantInt::get(IdxTy, VF * UF); 1183 1184 // This is the IR builder that we use to add all of the logic for bypassing 1185 // the new vector loop. 1186 IRBuilder<> BypassBuilder(BypassBlock->getTerminator()); 1187 1188 // We may need to extend the index in case there is a type mismatch. 1189 // We know that the count starts at zero and does not overflow. 1190 if (Count->getType() != IdxTy) { 1191 // The exit count can be of pointer type. Convert it to the correct 1192 // integer type. 1193 if (ExitCount->getType()->isPointerTy()) 1194 Count = BypassBuilder.CreatePointerCast(Count, IdxTy, "ptrcnt.to.int"); 1195 else 1196 Count = BypassBuilder.CreateZExtOrTrunc(Count, IdxTy, "cnt.cast"); 1197 } 1198 1199 // Add the start index to the loop count to get the new end index. 1200 Value *IdxEnd = BypassBuilder.CreateAdd(Count, StartIdx, "end.idx"); 1201 1202 // Now we need to generate the expression for N - (N % VF), which is 1203 // the part that the vectorized body will execute. 1204 Value *R = BypassBuilder.CreateURem(Count, Step, "n.mod.vf"); 1205 Value *CountRoundDown = BypassBuilder.CreateSub(Count, R, "n.vec"); 1206 Value *IdxEndRoundDown = BypassBuilder.CreateAdd(CountRoundDown, StartIdx, 1207 "end.idx.rnd.down"); 1208 1209 // Now, compare the new count to zero. If it is zero skip the vector loop and 1210 // jump to the scalar loop. 1211 Value *Cmp = BypassBuilder.CreateICmpEQ(IdxEndRoundDown, StartIdx, 1212 "cmp.zero"); 1213 1214 BasicBlock *LastBypassBlock = BypassBlock; 1215 1216 // Generate the code that checks in runtime if arrays overlap. We put the 1217 // checks into a separate block to make the more common case of few elements 1218 // faster. 1219 Instruction *MemRuntimeCheck = addRuntimeCheck(Legal, 1220 BypassBlock->getTerminator()); 1221 if (MemRuntimeCheck) { 1222 // Create a new block containing the memory check. 1223 BasicBlock *CheckBlock = BypassBlock->splitBasicBlock(MemRuntimeCheck, 1224 "vector.memcheck"); 1225 LoopBypassBlocks.push_back(CheckBlock); 1226 1227 // Replace the branch into the memory check block with a conditional branch 1228 // for the "few elements case". 1229 Instruction *OldTerm = BypassBlock->getTerminator(); 1230 BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm); 1231 OldTerm->eraseFromParent(); 1232 1233 Cmp = MemRuntimeCheck; 1234 LastBypassBlock = CheckBlock; 1235 } 1236 1237 LastBypassBlock->getTerminator()->eraseFromParent(); 1238 BranchInst::Create(MiddleBlock, VectorPH, Cmp, 1239 LastBypassBlock); 1240 1241 // We are going to resume the execution of the scalar loop. 1242 // Go over all of the induction variables that we found and fix the 1243 // PHIs that are left in the scalar version of the loop. 1244 // The starting values of PHI nodes depend on the counter of the last 1245 // iteration in the vectorized loop. 1246 // If we come from a bypass edge then we need to start from the original 1247 // start value. 1248 1249 // This variable saves the new starting index for the scalar loop. 1250 PHINode *ResumeIndex = 0; 1251 LoopVectorizationLegality::InductionList::iterator I, E; 1252 LoopVectorizationLegality::InductionList *List = Legal->getInductionVars(); 1253 for (I = List->begin(), E = List->end(); I != E; ++I) { 1254 PHINode *OrigPhi = I->first; 1255 LoopVectorizationLegality::InductionInfo II = I->second; 1256 PHINode *ResumeVal = PHINode::Create(OrigPhi->getType(), 2, "resume.val", 1257 MiddleBlock->getTerminator()); 1258 Value *EndValue = 0; 1259 switch (II.IK) { 1260 case LoopVectorizationLegality::IK_NoInduction: 1261 llvm_unreachable("Unknown induction"); 1262 case LoopVectorizationLegality::IK_IntInduction: { 1263 // Handle the integer induction counter: 1264 assert(OrigPhi->getType()->isIntegerTy() && "Invalid type"); 1265 assert(OrigPhi == OldInduction && "Unknown integer PHI"); 1266 // We know what the end value is. 1267 EndValue = IdxEndRoundDown; 1268 // We also know which PHI node holds it. 1269 ResumeIndex = ResumeVal; 1270 break; 1271 } 1272 case LoopVectorizationLegality::IK_ReverseIntInduction: { 1273 // Convert the CountRoundDown variable to the PHI size. 1274 unsigned CRDSize = CountRoundDown->getType()->getScalarSizeInBits(); 1275 unsigned IISize = II.StartValue->getType()->getScalarSizeInBits(); 1276 Value *CRD = CountRoundDown; 1277 if (CRDSize > IISize) 1278 CRD = CastInst::Create(Instruction::Trunc, CountRoundDown, 1279 II.StartValue->getType(), "tr.crd", 1280 LoopBypassBlocks.back()->getTerminator()); 1281 else if (CRDSize < IISize) 1282 CRD = CastInst::Create(Instruction::SExt, CountRoundDown, 1283 II.StartValue->getType(), 1284 "sext.crd", 1285 LoopBypassBlocks.back()->getTerminator()); 1286 // Handle reverse integer induction counter: 1287 EndValue = 1288 BinaryOperator::CreateSub(II.StartValue, CRD, "rev.ind.end", 1289 LoopBypassBlocks.back()->getTerminator()); 1290 break; 1291 } 1292 case LoopVectorizationLegality::IK_PtrInduction: { 1293 // For pointer induction variables, calculate the offset using 1294 // the end index. 1295 EndValue = 1296 GetElementPtrInst::Create(II.StartValue, CountRoundDown, "ptr.ind.end", 1297 LoopBypassBlocks.back()->getTerminator()); 1298 break; 1299 } 1300 case LoopVectorizationLegality::IK_ReversePtrInduction: { 1301 // The value at the end of the loop for the reverse pointer is calculated 1302 // by creating a GEP with a negative index starting from the start value. 1303 Value *Zero = ConstantInt::get(CountRoundDown->getType(), 0); 1304 Value *NegIdx = BinaryOperator::CreateSub(Zero, CountRoundDown, 1305 "rev.ind.end", 1306 LoopBypassBlocks.back()->getTerminator()); 1307 EndValue = GetElementPtrInst::Create(II.StartValue, NegIdx, 1308 "rev.ptr.ind.end", 1309 LoopBypassBlocks.back()->getTerminator()); 1310 break; 1311 } 1312 }// end of case 1313 1314 // The new PHI merges the original incoming value, in case of a bypass, 1315 // or the value at the end of the vectorized loop. 1316 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I) 1317 ResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]); 1318 ResumeVal->addIncoming(EndValue, VecBody); 1319 1320 // Fix the scalar body counter (PHI node). 1321 unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH); 1322 OrigPhi->setIncomingValue(BlockIdx, ResumeVal); 1323 } 1324 1325 // If we are generating a new induction variable then we also need to 1326 // generate the code that calculates the exit value. This value is not 1327 // simply the end of the counter because we may skip the vectorized body 1328 // in case of a runtime check. 1329 if (!OldInduction){ 1330 assert(!ResumeIndex && "Unexpected resume value found"); 1331 ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val", 1332 MiddleBlock->getTerminator()); 1333 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I) 1334 ResumeIndex->addIncoming(StartIdx, LoopBypassBlocks[I]); 1335 ResumeIndex->addIncoming(IdxEndRoundDown, VecBody); 1336 } 1337 1338 // Make sure that we found the index where scalar loop needs to continue. 1339 assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() && 1340 "Invalid resume Index"); 1341 1342 // Add a check in the middle block to see if we have completed 1343 // all of the iterations in the first vector loop. 1344 // If (N - N%VF) == N, then we *don't* need to run the remainder. 1345 Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd, 1346 ResumeIndex, "cmp.n", 1347 MiddleBlock->getTerminator()); 1348 1349 BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator()); 1350 // Remove the old terminator. 1351 MiddleBlock->getTerminator()->eraseFromParent(); 1352 1353 // Create i+1 and fill the PHINode. 1354 Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next"); 1355 Induction->addIncoming(StartIdx, VectorPH); 1356 Induction->addIncoming(NextIdx, VecBody); 1357 // Create the compare. 1358 Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown); 1359 Builder.CreateCondBr(ICmp, MiddleBlock, VecBody); 1360 1361 // Now we have two terminators. Remove the old one from the block. 1362 VecBody->getTerminator()->eraseFromParent(); 1363 1364 // Get ready to start creating new instructions into the vectorized body. 1365 Builder.SetInsertPoint(VecBody->getFirstInsertionPt()); 1366 1367 // Create and register the new vector loop. 1368 Loop* Lp = new Loop(); 1369 Loop *ParentLoop = OrigLoop->getParentLoop(); 1370 1371 // Insert the new loop into the loop nest and register the new basic blocks. 1372 if (ParentLoop) { 1373 ParentLoop->addChildLoop(Lp); 1374 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I) 1375 ParentLoop->addBasicBlockToLoop(LoopBypassBlocks[I], LI->getBase()); 1376 ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase()); 1377 ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase()); 1378 ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase()); 1379 } else { 1380 LI->addTopLevelLoop(Lp); 1381 } 1382 1383 Lp->addBasicBlockToLoop(VecBody, LI->getBase()); 1384 1385 // Save the state. 1386 LoopVectorPreHeader = VectorPH; 1387 LoopScalarPreHeader = ScalarPH; 1388 LoopMiddleBlock = MiddleBlock; 1389 LoopExitBlock = ExitBlock; 1390 LoopVectorBody = VecBody; 1391 LoopScalarBody = OldBasicBlock; 1392 } 1393 1394 /// This function returns the identity element (or neutral element) for 1395 /// the operation K. 1396 static Constant* 1397 getReductionIdentity(LoopVectorizationLegality::ReductionKind K, Type *Tp) { 1398 switch (K) { 1399 case LoopVectorizationLegality:: RK_IntegerXor: 1400 case LoopVectorizationLegality:: RK_IntegerAdd: 1401 case LoopVectorizationLegality:: RK_IntegerOr: 1402 // Adding, Xoring, Oring zero to a number does not change it. 1403 return ConstantInt::get(Tp, 0); 1404 case LoopVectorizationLegality:: RK_IntegerMult: 1405 // Multiplying a number by 1 does not change it. 1406 return ConstantInt::get(Tp, 1); 1407 case LoopVectorizationLegality:: RK_IntegerAnd: 1408 // AND-ing a number with an all-1 value does not change it. 1409 return ConstantInt::get(Tp, -1, true); 1410 case LoopVectorizationLegality:: RK_FloatMult: 1411 // Multiplying a number by 1 does not change it. 1412 return ConstantFP::get(Tp, 1.0L); 1413 case LoopVectorizationLegality:: RK_FloatAdd: 1414 // Adding zero to a number does not change it. 1415 return ConstantFP::get(Tp, 0.0L); 1416 default: 1417 llvm_unreachable("Unknown reduction kind"); 1418 } 1419 } 1420 1421 static bool 1422 isTriviallyVectorizableIntrinsic(Instruction *Inst) { 1423 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst); 1424 if (!II) 1425 return false; 1426 switch (II->getIntrinsicID()) { 1427 case Intrinsic::sqrt: 1428 case Intrinsic::sin: 1429 case Intrinsic::cos: 1430 case Intrinsic::exp: 1431 case Intrinsic::exp2: 1432 case Intrinsic::log: 1433 case Intrinsic::log10: 1434 case Intrinsic::log2: 1435 case Intrinsic::fabs: 1436 case Intrinsic::floor: 1437 case Intrinsic::ceil: 1438 case Intrinsic::trunc: 1439 case Intrinsic::rint: 1440 case Intrinsic::nearbyint: 1441 case Intrinsic::pow: 1442 case Intrinsic::fma: 1443 case Intrinsic::fmuladd: 1444 return true; 1445 default: 1446 return false; 1447 } 1448 return false; 1449 } 1450 1451 /// This function translates the reduction kind to an LLVM binary operator. 1452 static Instruction::BinaryOps 1453 getReductionBinOp(LoopVectorizationLegality::ReductionKind Kind) { 1454 switch (Kind) { 1455 case LoopVectorizationLegality::RK_IntegerAdd: 1456 return Instruction::Add; 1457 case LoopVectorizationLegality::RK_IntegerMult: 1458 return Instruction::Mul; 1459 case LoopVectorizationLegality::RK_IntegerOr: 1460 return Instruction::Or; 1461 case LoopVectorizationLegality::RK_IntegerAnd: 1462 return Instruction::And; 1463 case LoopVectorizationLegality::RK_IntegerXor: 1464 return Instruction::Xor; 1465 case LoopVectorizationLegality::RK_FloatMult: 1466 return Instruction::FMul; 1467 case LoopVectorizationLegality::RK_FloatAdd: 1468 return Instruction::FAdd; 1469 default: 1470 llvm_unreachable("Unknown reduction operation"); 1471 } 1472 } 1473 1474 void 1475 InnerLoopVectorizer::vectorizeLoop(LoopVectorizationLegality *Legal) { 1476 //===------------------------------------------------===// 1477 // 1478 // Notice: any optimization or new instruction that go 1479 // into the code below should be also be implemented in 1480 // the cost-model. 1481 // 1482 //===------------------------------------------------===// 1483 Constant *Zero = Builder.getInt32(0); 1484 1485 // In order to support reduction variables we need to be able to vectorize 1486 // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two 1487 // stages. First, we create a new vector PHI node with no incoming edges. 1488 // We use this value when we vectorize all of the instructions that use the 1489 // PHI. Next, after all of the instructions in the block are complete we 1490 // add the new incoming edges to the PHI. At this point all of the 1491 // instructions in the basic block are vectorized, so we can use them to 1492 // construct the PHI. 1493 PhiVector RdxPHIsToFix; 1494 1495 // Scan the loop in a topological order to ensure that defs are vectorized 1496 // before users. 1497 LoopBlocksDFS DFS(OrigLoop); 1498 DFS.perform(LI); 1499 1500 // Vectorize all of the blocks in the original loop. 1501 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(), 1502 be = DFS.endRPO(); bb != be; ++bb) 1503 vectorizeBlockInLoop(Legal, *bb, &RdxPHIsToFix); 1504 1505 // At this point every instruction in the original loop is widened to 1506 // a vector form. We are almost done. Now, we need to fix the PHI nodes 1507 // that we vectorized. The PHI nodes are currently empty because we did 1508 // not want to introduce cycles. Notice that the remaining PHI nodes 1509 // that we need to fix are reduction variables. 1510 1511 // Create the 'reduced' values for each of the induction vars. 1512 // The reduced values are the vector values that we scalarize and combine 1513 // after the loop is finished. 1514 for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end(); 1515 it != e; ++it) { 1516 PHINode *RdxPhi = *it; 1517 assert(RdxPhi && "Unable to recover vectorized PHI"); 1518 1519 // Find the reduction variable descriptor. 1520 assert(Legal->getReductionVars()->count(RdxPhi) && 1521 "Unable to find the reduction variable"); 1522 LoopVectorizationLegality::ReductionDescriptor RdxDesc = 1523 (*Legal->getReductionVars())[RdxPhi]; 1524 1525 // We need to generate a reduction vector from the incoming scalar. 1526 // To do so, we need to generate the 'identity' vector and overide 1527 // one of the elements with the incoming scalar reduction. We need 1528 // to do it in the vector-loop preheader. 1529 Builder.SetInsertPoint(LoopBypassBlocks.back()->getTerminator()); 1530 1531 // This is the vector-clone of the value that leaves the loop. 1532 VectorParts &VectorExit = getVectorValue(RdxDesc.LoopExitInstr); 1533 Type *VecTy = VectorExit[0]->getType(); 1534 1535 // Find the reduction identity variable. Zero for addition, or, xor, 1536 // one for multiplication, -1 for And. 1537 Constant *Iden = getReductionIdentity(RdxDesc.Kind, VecTy->getScalarType()); 1538 Constant *Identity = ConstantVector::getSplat(VF, Iden); 1539 1540 // This vector is the Identity vector where the first element is the 1541 // incoming scalar reduction. 1542 Value *VectorStart = Builder.CreateInsertElement(Identity, 1543 RdxDesc.StartValue, Zero); 1544 1545 // Fix the vector-loop phi. 1546 // We created the induction variable so we know that the 1547 // preheader is the first entry. 1548 BasicBlock *VecPreheader = Induction->getIncomingBlock(0); 1549 1550 // Reductions do not have to start at zero. They can start with 1551 // any loop invariant values. 1552 VectorParts &VecRdxPhi = WidenMap.get(RdxPhi); 1553 BasicBlock *Latch = OrigLoop->getLoopLatch(); 1554 Value *LoopVal = RdxPhi->getIncomingValueForBlock(Latch); 1555 VectorParts &Val = getVectorValue(LoopVal); 1556 for (unsigned part = 0; part < UF; ++part) { 1557 // Make sure to add the reduction stat value only to the 1558 // first unroll part. 1559 Value *StartVal = (part == 0) ? VectorStart : Identity; 1560 cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal, VecPreheader); 1561 cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part], LoopVectorBody); 1562 } 1563 1564 // Before each round, move the insertion point right between 1565 // the PHIs and the values we are going to write. 1566 // This allows us to write both PHINodes and the extractelement 1567 // instructions. 1568 Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt()); 1569 1570 VectorParts RdxParts; 1571 for (unsigned part = 0; part < UF; ++part) { 1572 // This PHINode contains the vectorized reduction variable, or 1573 // the initial value vector, if we bypass the vector loop. 1574 VectorParts &RdxExitVal = getVectorValue(RdxDesc.LoopExitInstr); 1575 PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi"); 1576 Value *StartVal = (part == 0) ? VectorStart : Identity; 1577 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I) 1578 NewPhi->addIncoming(StartVal, LoopBypassBlocks[I]); 1579 NewPhi->addIncoming(RdxExitVal[part], LoopVectorBody); 1580 RdxParts.push_back(NewPhi); 1581 } 1582 1583 // Reduce all of the unrolled parts into a single vector. 1584 Value *ReducedPartRdx = RdxParts[0]; 1585 for (unsigned part = 1; part < UF; ++part) { 1586 Instruction::BinaryOps Op = getReductionBinOp(RdxDesc.Kind); 1587 ReducedPartRdx = Builder.CreateBinOp(Op, RdxParts[part], ReducedPartRdx, 1588 "bin.rdx"); 1589 } 1590 1591 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles 1592 // and vector ops, reducing the set of values being computed by half each 1593 // round. 1594 assert(isPowerOf2_32(VF) && 1595 "Reduction emission only supported for pow2 vectors!"); 1596 Value *TmpVec = ReducedPartRdx; 1597 SmallVector<Constant*, 32> ShuffleMask(VF, 0); 1598 for (unsigned i = VF; i != 1; i >>= 1) { 1599 // Move the upper half of the vector to the lower half. 1600 for (unsigned j = 0; j != i/2; ++j) 1601 ShuffleMask[j] = Builder.getInt32(i/2 + j); 1602 1603 // Fill the rest of the mask with undef. 1604 std::fill(&ShuffleMask[i/2], ShuffleMask.end(), 1605 UndefValue::get(Builder.getInt32Ty())); 1606 1607 Value *Shuf = 1608 Builder.CreateShuffleVector(TmpVec, 1609 UndefValue::get(TmpVec->getType()), 1610 ConstantVector::get(ShuffleMask), 1611 "rdx.shuf"); 1612 1613 Instruction::BinaryOps Op = getReductionBinOp(RdxDesc.Kind); 1614 TmpVec = Builder.CreateBinOp(Op, TmpVec, Shuf, "bin.rdx"); 1615 } 1616 1617 // The result is in the first element of the vector. 1618 Value *Scalar0 = Builder.CreateExtractElement(TmpVec, Builder.getInt32(0)); 1619 1620 // Now, we need to fix the users of the reduction variable 1621 // inside and outside of the scalar remainder loop. 1622 // We know that the loop is in LCSSA form. We need to update the 1623 // PHI nodes in the exit blocks. 1624 for (BasicBlock::iterator LEI = LoopExitBlock->begin(), 1625 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) { 1626 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI); 1627 if (!LCSSAPhi) continue; 1628 1629 // All PHINodes need to have a single entry edge, or two if 1630 // we already fixed them. 1631 assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI"); 1632 1633 // We found our reduction value exit-PHI. Update it with the 1634 // incoming bypass edge. 1635 if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) { 1636 // Add an edge coming from the bypass. 1637 LCSSAPhi->addIncoming(Scalar0, LoopMiddleBlock); 1638 break; 1639 } 1640 }// end of the LCSSA phi scan. 1641 1642 // Fix the scalar loop reduction variable with the incoming reduction sum 1643 // from the vector body and from the backedge value. 1644 int IncomingEdgeBlockIdx = 1645 (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch()); 1646 assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index"); 1647 // Pick the other block. 1648 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1); 1649 (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, Scalar0); 1650 (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr); 1651 }// end of for each redux variable. 1652 1653 // The Loop exit block may have single value PHI nodes where the incoming 1654 // value is 'undef'. While vectorizing we only handled real values that 1655 // were defined inside the loop. Here we handle the 'undef case'. 1656 // See PR14725. 1657 for (BasicBlock::iterator LEI = LoopExitBlock->begin(), 1658 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) { 1659 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI); 1660 if (!LCSSAPhi) continue; 1661 if (LCSSAPhi->getNumIncomingValues() == 1) 1662 LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()), 1663 LoopMiddleBlock); 1664 } 1665 } 1666 1667 InnerLoopVectorizer::VectorParts 1668 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) { 1669 assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) && 1670 "Invalid edge"); 1671 1672 VectorParts SrcMask = createBlockInMask(Src); 1673 1674 // The terminator has to be a branch inst! 1675 BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator()); 1676 assert(BI && "Unexpected terminator found"); 1677 1678 if (BI->isConditional()) { 1679 VectorParts EdgeMask = getVectorValue(BI->getCondition()); 1680 1681 if (BI->getSuccessor(0) != Dst) 1682 for (unsigned part = 0; part < UF; ++part) 1683 EdgeMask[part] = Builder.CreateNot(EdgeMask[part]); 1684 1685 for (unsigned part = 0; part < UF; ++part) 1686 EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]); 1687 return EdgeMask; 1688 } 1689 1690 return SrcMask; 1691 } 1692 1693 InnerLoopVectorizer::VectorParts 1694 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) { 1695 assert(OrigLoop->contains(BB) && "Block is not a part of a loop"); 1696 1697 // Loop incoming mask is all-one. 1698 if (OrigLoop->getHeader() == BB) { 1699 Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1); 1700 return getVectorValue(C); 1701 } 1702 1703 // This is the block mask. We OR all incoming edges, and with zero. 1704 Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0); 1705 VectorParts BlockMask = getVectorValue(Zero); 1706 1707 // For each pred: 1708 for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) { 1709 VectorParts EM = createEdgeMask(*it, BB); 1710 for (unsigned part = 0; part < UF; ++part) 1711 BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]); 1712 } 1713 1714 return BlockMask; 1715 } 1716 1717 void 1718 InnerLoopVectorizer::vectorizeBlockInLoop(LoopVectorizationLegality *Legal, 1719 BasicBlock *BB, PhiVector *PV) { 1720 // For each instruction in the old loop. 1721 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) { 1722 VectorParts &Entry = WidenMap.get(it); 1723 switch (it->getOpcode()) { 1724 case Instruction::Br: 1725 // Nothing to do for PHIs and BR, since we already took care of the 1726 // loop control flow instructions. 1727 continue; 1728 case Instruction::PHI:{ 1729 PHINode* P = cast<PHINode>(it); 1730 // Handle reduction variables: 1731 if (Legal->getReductionVars()->count(P)) { 1732 for (unsigned part = 0; part < UF; ++part) { 1733 // This is phase one of vectorizing PHIs. 1734 Type *VecTy = VectorType::get(it->getType(), VF); 1735 Entry[part] = PHINode::Create(VecTy, 2, "vec.phi", 1736 LoopVectorBody-> getFirstInsertionPt()); 1737 } 1738 PV->push_back(P); 1739 continue; 1740 } 1741 1742 // Check for PHI nodes that are lowered to vector selects. 1743 if (P->getParent() != OrigLoop->getHeader()) { 1744 // We know that all PHIs in non header blocks are converted into 1745 // selects, so we don't have to worry about the insertion order and we 1746 // can just use the builder. 1747 1748 // At this point we generate the predication tree. There may be 1749 // duplications since this is a simple recursive scan, but future 1750 // optimizations will clean it up. 1751 VectorParts Cond = createEdgeMask(P->getIncomingBlock(0), 1752 P->getParent()); 1753 1754 for (unsigned part = 0; part < UF; ++part) { 1755 VectorParts &In0 = getVectorValue(P->getIncomingValue(0)); 1756 VectorParts &In1 = getVectorValue(P->getIncomingValue(1)); 1757 Entry[part] = Builder.CreateSelect(Cond[part], In0[part], In1[part], 1758 "predphi"); 1759 } 1760 continue; 1761 } 1762 1763 // This PHINode must be an induction variable. 1764 // Make sure that we know about it. 1765 assert(Legal->getInductionVars()->count(P) && 1766 "Not an induction variable"); 1767 1768 LoopVectorizationLegality::InductionInfo II = 1769 Legal->getInductionVars()->lookup(P); 1770 1771 switch (II.IK) { 1772 case LoopVectorizationLegality::IK_NoInduction: 1773 llvm_unreachable("Unknown induction"); 1774 case LoopVectorizationLegality::IK_IntInduction: { 1775 assert(P == OldInduction && "Unexpected PHI"); 1776 Value *Broadcasted = getBroadcastInstrs(Induction); 1777 // After broadcasting the induction variable we need to make the 1778 // vector consecutive by adding 0, 1, 2 ... 1779 for (unsigned part = 0; part < UF; ++part) 1780 Entry[part] = getConsecutiveVector(Broadcasted, VF * part, false); 1781 continue; 1782 } 1783 case LoopVectorizationLegality::IK_ReverseIntInduction: 1784 case LoopVectorizationLegality::IK_PtrInduction: 1785 case LoopVectorizationLegality::IK_ReversePtrInduction: 1786 // Handle reverse integer and pointer inductions. 1787 Value *StartIdx = 0; 1788 // If we have a single integer induction variable then use it. 1789 // Otherwise, start counting at zero. 1790 if (OldInduction) { 1791 LoopVectorizationLegality::InductionInfo OldII = 1792 Legal->getInductionVars()->lookup(OldInduction); 1793 StartIdx = OldII.StartValue; 1794 } else { 1795 StartIdx = ConstantInt::get(Induction->getType(), 0); 1796 } 1797 // This is the normalized GEP that starts counting at zero. 1798 Value *NormalizedIdx = Builder.CreateSub(Induction, StartIdx, 1799 "normalized.idx"); 1800 1801 // Handle the reverse integer induction variable case. 1802 if (LoopVectorizationLegality::IK_ReverseIntInduction == II.IK) { 1803 IntegerType *DstTy = cast<IntegerType>(II.StartValue->getType()); 1804 Value *CNI = Builder.CreateSExtOrTrunc(NormalizedIdx, DstTy, 1805 "resize.norm.idx"); 1806 Value *ReverseInd = Builder.CreateSub(II.StartValue, CNI, 1807 "reverse.idx"); 1808 1809 // This is a new value so do not hoist it out. 1810 Value *Broadcasted = getBroadcastInstrs(ReverseInd); 1811 // After broadcasting the induction variable we need to make the 1812 // vector consecutive by adding ... -3, -2, -1, 0. 1813 for (unsigned part = 0; part < UF; ++part) 1814 Entry[part] = getConsecutiveVector(Broadcasted, -VF * part, true); 1815 continue; 1816 } 1817 1818 // Handle the pointer induction variable case. 1819 assert(P->getType()->isPointerTy() && "Unexpected type."); 1820 1821 // Is this a reverse induction ptr or a consecutive induction ptr. 1822 bool Reverse = (LoopVectorizationLegality::IK_ReversePtrInduction == 1823 II.IK); 1824 1825 // This is the vector of results. Notice that we don't generate 1826 // vector geps because scalar geps result in better code. 1827 for (unsigned part = 0; part < UF; ++part) { 1828 Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF)); 1829 for (unsigned int i = 0; i < VF; ++i) { 1830 int EltIndex = (i + part * VF) * (Reverse ? -1 : 1); 1831 Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex); 1832 Value *GlobalIdx; 1833 if (!Reverse) 1834 GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx, "gep.idx"); 1835 else 1836 GlobalIdx = Builder.CreateSub(Idx, NormalizedIdx, "gep.ridx"); 1837 1838 Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx, 1839 "next.gep"); 1840 VecVal = Builder.CreateInsertElement(VecVal, SclrGep, 1841 Builder.getInt32(i), 1842 "insert.gep"); 1843 } 1844 Entry[part] = VecVal; 1845 } 1846 continue; 1847 } 1848 1849 }// End of PHI. 1850 1851 case Instruction::Add: 1852 case Instruction::FAdd: 1853 case Instruction::Sub: 1854 case Instruction::FSub: 1855 case Instruction::Mul: 1856 case Instruction::FMul: 1857 case Instruction::UDiv: 1858 case Instruction::SDiv: 1859 case Instruction::FDiv: 1860 case Instruction::URem: 1861 case Instruction::SRem: 1862 case Instruction::FRem: 1863 case Instruction::Shl: 1864 case Instruction::LShr: 1865 case Instruction::AShr: 1866 case Instruction::And: 1867 case Instruction::Or: 1868 case Instruction::Xor: { 1869 // Just widen binops. 1870 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it); 1871 VectorParts &A = getVectorValue(it->getOperand(0)); 1872 VectorParts &B = getVectorValue(it->getOperand(1)); 1873 1874 // Use this vector value for all users of the original instruction. 1875 for (unsigned Part = 0; Part < UF; ++Part) { 1876 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]); 1877 1878 // Update the NSW, NUW and Exact flags. Notice: V can be an Undef. 1879 BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V); 1880 if (VecOp && isa<OverflowingBinaryOperator>(BinOp)) { 1881 VecOp->setHasNoSignedWrap(BinOp->hasNoSignedWrap()); 1882 VecOp->setHasNoUnsignedWrap(BinOp->hasNoUnsignedWrap()); 1883 } 1884 if (VecOp && isa<PossiblyExactOperator>(VecOp)) 1885 VecOp->setIsExact(BinOp->isExact()); 1886 1887 Entry[Part] = V; 1888 } 1889 break; 1890 } 1891 case Instruction::Select: { 1892 // Widen selects. 1893 // If the selector is loop invariant we can create a select 1894 // instruction with a scalar condition. Otherwise, use vector-select. 1895 bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)), 1896 OrigLoop); 1897 1898 // The condition can be loop invariant but still defined inside the 1899 // loop. This means that we can't just use the original 'cond' value. 1900 // We have to take the 'vectorized' value and pick the first lane. 1901 // Instcombine will make this a no-op. 1902 VectorParts &Cond = getVectorValue(it->getOperand(0)); 1903 VectorParts &Op0 = getVectorValue(it->getOperand(1)); 1904 VectorParts &Op1 = getVectorValue(it->getOperand(2)); 1905 Value *ScalarCond = Builder.CreateExtractElement(Cond[0], 1906 Builder.getInt32(0)); 1907 for (unsigned Part = 0; Part < UF; ++Part) { 1908 Entry[Part] = Builder.CreateSelect( 1909 InvariantCond ? ScalarCond : Cond[Part], 1910 Op0[Part], 1911 Op1[Part]); 1912 } 1913 break; 1914 } 1915 1916 case Instruction::ICmp: 1917 case Instruction::FCmp: { 1918 // Widen compares. Generate vector compares. 1919 bool FCmp = (it->getOpcode() == Instruction::FCmp); 1920 CmpInst *Cmp = dyn_cast<CmpInst>(it); 1921 VectorParts &A = getVectorValue(it->getOperand(0)); 1922 VectorParts &B = getVectorValue(it->getOperand(1)); 1923 for (unsigned Part = 0; Part < UF; ++Part) { 1924 Value *C = 0; 1925 if (FCmp) 1926 C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]); 1927 else 1928 C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]); 1929 Entry[Part] = C; 1930 } 1931 break; 1932 } 1933 1934 case Instruction::Store: 1935 case Instruction::Load: 1936 vectorizeMemoryInstruction(it, Legal); 1937 break; 1938 case Instruction::ZExt: 1939 case Instruction::SExt: 1940 case Instruction::FPToUI: 1941 case Instruction::FPToSI: 1942 case Instruction::FPExt: 1943 case Instruction::PtrToInt: 1944 case Instruction::IntToPtr: 1945 case Instruction::SIToFP: 1946 case Instruction::UIToFP: 1947 case Instruction::Trunc: 1948 case Instruction::FPTrunc: 1949 case Instruction::BitCast: { 1950 CastInst *CI = dyn_cast<CastInst>(it); 1951 /// Optimize the special case where the source is the induction 1952 /// variable. Notice that we can only optimize the 'trunc' case 1953 /// because: a. FP conversions lose precision, b. sext/zext may wrap, 1954 /// c. other casts depend on pointer size. 1955 if (CI->getOperand(0) == OldInduction && 1956 it->getOpcode() == Instruction::Trunc) { 1957 Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction, 1958 CI->getType()); 1959 Value *Broadcasted = getBroadcastInstrs(ScalarCast); 1960 for (unsigned Part = 0; Part < UF; ++Part) 1961 Entry[Part] = getConsecutiveVector(Broadcasted, VF * Part, false); 1962 break; 1963 } 1964 /// Vectorize casts. 1965 Type *DestTy = VectorType::get(CI->getType()->getScalarType(), VF); 1966 1967 VectorParts &A = getVectorValue(it->getOperand(0)); 1968 for (unsigned Part = 0; Part < UF; ++Part) 1969 Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy); 1970 break; 1971 } 1972 1973 case Instruction::Call: { 1974 assert(isTriviallyVectorizableIntrinsic(it)); 1975 Module *M = BB->getParent()->getParent(); 1976 IntrinsicInst *II = cast<IntrinsicInst>(it); 1977 Intrinsic::ID ID = II->getIntrinsicID(); 1978 for (unsigned Part = 0; Part < UF; ++Part) { 1979 SmallVector<Value*, 4> Args; 1980 for (unsigned i = 0, ie = II->getNumArgOperands(); i != ie; ++i) { 1981 VectorParts &Arg = getVectorValue(II->getArgOperand(i)); 1982 Args.push_back(Arg[Part]); 1983 } 1984 Type *Tys[] = { VectorType::get(II->getType()->getScalarType(), VF) }; 1985 Function *F = Intrinsic::getDeclaration(M, ID, Tys); 1986 Entry[Part] = Builder.CreateCall(F, Args); 1987 } 1988 break; 1989 } 1990 1991 default: 1992 // All other instructions are unsupported. Scalarize them. 1993 scalarizeInstruction(it); 1994 break; 1995 }// end of switch. 1996 }// end of for_each instr. 1997 } 1998 1999 void InnerLoopVectorizer::updateAnalysis() { 2000 // Forget the original basic block. 2001 SE->forgetLoop(OrigLoop); 2002 2003 // Update the dominator tree information. 2004 assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) && 2005 "Entry does not dominate exit."); 2006 2007 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I) 2008 DT->addNewBlock(LoopBypassBlocks[I], LoopBypassBlocks[I-1]); 2009 DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlocks.back()); 2010 DT->addNewBlock(LoopVectorBody, LoopVectorPreHeader); 2011 DT->addNewBlock(LoopMiddleBlock, LoopBypassBlocks.front()); 2012 DT->addNewBlock(LoopScalarPreHeader, LoopMiddleBlock); 2013 DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader); 2014 DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock); 2015 2016 DEBUG(DT->verifyAnalysis()); 2017 } 2018 2019 bool LoopVectorizationLegality::canVectorizeWithIfConvert() { 2020 if (!EnableIfConversion) 2021 return false; 2022 2023 assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable"); 2024 std::vector<BasicBlock*> &LoopBlocks = TheLoop->getBlocksVector(); 2025 2026 // Collect the blocks that need predication. 2027 for (unsigned i = 0, e = LoopBlocks.size(); i < e; ++i) { 2028 BasicBlock *BB = LoopBlocks[i]; 2029 2030 // We don't support switch statements inside loops. 2031 if (!isa<BranchInst>(BB->getTerminator())) 2032 return false; 2033 2034 // We must have at most two predecessors because we need to convert 2035 // all PHIs to selects. 2036 unsigned Preds = std::distance(pred_begin(BB), pred_end(BB)); 2037 if (Preds > 2) 2038 return false; 2039 2040 // We must be able to predicate all blocks that need to be predicated. 2041 if (blockNeedsPredication(BB) && !blockCanBePredicated(BB)) 2042 return false; 2043 } 2044 2045 // We can if-convert this loop. 2046 return true; 2047 } 2048 2049 bool LoopVectorizationLegality::canVectorize() { 2050 assert(TheLoop->getLoopPreheader() && "No preheader!!"); 2051 2052 // We can only vectorize innermost loops. 2053 if (TheLoop->getSubLoopsVector().size()) 2054 return false; 2055 2056 // We must have a single backedge. 2057 if (TheLoop->getNumBackEdges() != 1) 2058 return false; 2059 2060 // We must have a single exiting block. 2061 if (!TheLoop->getExitingBlock()) 2062 return false; 2063 2064 unsigned NumBlocks = TheLoop->getNumBlocks(); 2065 2066 // Check if we can if-convert non single-bb loops. 2067 if (NumBlocks != 1 && !canVectorizeWithIfConvert()) { 2068 DEBUG(dbgs() << "LV: Can't if-convert the loop.\n"); 2069 return false; 2070 } 2071 2072 // We need to have a loop header. 2073 BasicBlock *Latch = TheLoop->getLoopLatch(); 2074 DEBUG(dbgs() << "LV: Found a loop: " << 2075 TheLoop->getHeader()->getName() << "\n"); 2076 2077 // ScalarEvolution needs to be able to find the exit count. 2078 const SCEV *ExitCount = SE->getExitCount(TheLoop, Latch); 2079 if (ExitCount == SE->getCouldNotCompute()) { 2080 DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n"); 2081 return false; 2082 } 2083 2084 // Do not loop-vectorize loops with a tiny trip count. 2085 unsigned TC = SE->getSmallConstantTripCount(TheLoop, Latch); 2086 if (TC > 0u && TC < TinyTripCountVectorThreshold) { 2087 DEBUG(dbgs() << "LV: Found a loop with a very small trip count. " << 2088 "This loop is not worth vectorizing.\n"); 2089 return false; 2090 } 2091 2092 // Check if we can vectorize the instructions and CFG in this loop. 2093 if (!canVectorizeInstrs()) { 2094 DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n"); 2095 return false; 2096 } 2097 2098 // Go over each instruction and look at memory deps. 2099 if (!canVectorizeMemory()) { 2100 DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n"); 2101 return false; 2102 } 2103 2104 // Collect all of the variables that remain uniform after vectorization. 2105 collectLoopUniforms(); 2106 2107 DEBUG(dbgs() << "LV: We can vectorize this loop" << 2108 (PtrRtCheck.Need ? " (with a runtime bound check)" : "") 2109 <<"!\n"); 2110 2111 // Okay! We can vectorize. At this point we don't have any other mem analysis 2112 // which may limit our maximum vectorization factor, so just return true with 2113 // no restrictions. 2114 return true; 2115 } 2116 2117 bool LoopVectorizationLegality::canVectorizeInstrs() { 2118 BasicBlock *PreHeader = TheLoop->getLoopPreheader(); 2119 BasicBlock *Header = TheLoop->getHeader(); 2120 2121 // For each block in the loop. 2122 for (Loop::block_iterator bb = TheLoop->block_begin(), 2123 be = TheLoop->block_end(); bb != be; ++bb) { 2124 2125 // Scan the instructions in the block and look for hazards. 2126 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e; 2127 ++it) { 2128 2129 if (PHINode *Phi = dyn_cast<PHINode>(it)) { 2130 // This should not happen because the loop should be normalized. 2131 if (Phi->getNumIncomingValues() != 2) { 2132 DEBUG(dbgs() << "LV: Found an invalid PHI.\n"); 2133 return false; 2134 } 2135 2136 // Check that this PHI type is allowed. 2137 if (!Phi->getType()->isIntegerTy() && 2138 !Phi->getType()->isFloatingPointTy() && 2139 !Phi->getType()->isPointerTy()) { 2140 DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n"); 2141 return false; 2142 } 2143 2144 // If this PHINode is not in the header block, then we know that we 2145 // can convert it to select during if-conversion. No need to check if 2146 // the PHIs in this block are induction or reduction variables. 2147 if (*bb != Header) 2148 continue; 2149 2150 // This is the value coming from the preheader. 2151 Value *StartValue = Phi->getIncomingValueForBlock(PreHeader); 2152 // Check if this is an induction variable. 2153 InductionKind IK = isInductionVariable(Phi); 2154 2155 if (IK_NoInduction != IK) { 2156 // Int inductions are special because we only allow one IV. 2157 if (IK == IK_IntInduction) { 2158 if (Induction) { 2159 DEBUG(dbgs() << "LV: Found too many inductions."<< *Phi <<"\n"); 2160 return false; 2161 } 2162 Induction = Phi; 2163 } 2164 2165 DEBUG(dbgs() << "LV: Found an induction variable.\n"); 2166 Inductions[Phi] = InductionInfo(StartValue, IK); 2167 continue; 2168 } 2169 2170 if (AddReductionVar(Phi, RK_IntegerAdd)) { 2171 DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n"); 2172 continue; 2173 } 2174 if (AddReductionVar(Phi, RK_IntegerMult)) { 2175 DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n"); 2176 continue; 2177 } 2178 if (AddReductionVar(Phi, RK_IntegerOr)) { 2179 DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n"); 2180 continue; 2181 } 2182 if (AddReductionVar(Phi, RK_IntegerAnd)) { 2183 DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n"); 2184 continue; 2185 } 2186 if (AddReductionVar(Phi, RK_IntegerXor)) { 2187 DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n"); 2188 continue; 2189 } 2190 if (AddReductionVar(Phi, RK_FloatMult)) { 2191 DEBUG(dbgs() << "LV: Found an FMult reduction PHI."<< *Phi <<"\n"); 2192 continue; 2193 } 2194 if (AddReductionVar(Phi, RK_FloatAdd)) { 2195 DEBUG(dbgs() << "LV: Found an FAdd reduction PHI."<< *Phi <<"\n"); 2196 continue; 2197 } 2198 2199 DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n"); 2200 return false; 2201 }// end of PHI handling 2202 2203 // We still don't handle functions. 2204 CallInst *CI = dyn_cast<CallInst>(it); 2205 if (CI && !isTriviallyVectorizableIntrinsic(it)) { 2206 DEBUG(dbgs() << "LV: Found a call site.\n"); 2207 return false; 2208 } 2209 2210 // Check that the instruction return type is vectorizable. 2211 if (!VectorType::isValidElementType(it->getType()) && 2212 !it->getType()->isVoidTy()) { 2213 DEBUG(dbgs() << "LV: Found unvectorizable type." << "\n"); 2214 return false; 2215 } 2216 2217 // Check that the stored type is vectorizable. 2218 if (StoreInst *ST = dyn_cast<StoreInst>(it)) { 2219 Type *T = ST->getValueOperand()->getType(); 2220 if (!VectorType::isValidElementType(T)) 2221 return false; 2222 } 2223 2224 // Reduction instructions are allowed to have exit users. 2225 // All other instructions must not have external users. 2226 if (!AllowedExit.count(it)) 2227 //Check that all of the users of the loop are inside the BB. 2228 for (Value::use_iterator I = it->use_begin(), E = it->use_end(); 2229 I != E; ++I) { 2230 Instruction *U = cast<Instruction>(*I); 2231 // This user may be a reduction exit value. 2232 if (!TheLoop->contains(U)) { 2233 DEBUG(dbgs() << "LV: Found an outside user for : "<< *U << "\n"); 2234 return false; 2235 } 2236 } 2237 } // next instr. 2238 2239 } 2240 2241 if (!Induction) { 2242 DEBUG(dbgs() << "LV: Did not find one integer induction var.\n"); 2243 assert(getInductionVars()->size() && "No induction variables"); 2244 } 2245 2246 return true; 2247 } 2248 2249 void LoopVectorizationLegality::collectLoopUniforms() { 2250 // We now know that the loop is vectorizable! 2251 // Collect variables that will remain uniform after vectorization. 2252 std::vector<Value*> Worklist; 2253 BasicBlock *Latch = TheLoop->getLoopLatch(); 2254 2255 // Start with the conditional branch and walk up the block. 2256 Worklist.push_back(Latch->getTerminator()->getOperand(0)); 2257 2258 while (Worklist.size()) { 2259 Instruction *I = dyn_cast<Instruction>(Worklist.back()); 2260 Worklist.pop_back(); 2261 2262 // Look at instructions inside this loop. 2263 // Stop when reaching PHI nodes. 2264 // TODO: we need to follow values all over the loop, not only in this block. 2265 if (!I || !TheLoop->contains(I) || isa<PHINode>(I)) 2266 continue; 2267 2268 // This is a known uniform. 2269 Uniforms.insert(I); 2270 2271 // Insert all operands. 2272 for (int i = 0, Op = I->getNumOperands(); i < Op; ++i) { 2273 Worklist.push_back(I->getOperand(i)); 2274 } 2275 } 2276 } 2277 2278 bool LoopVectorizationLegality::canVectorizeMemory() { 2279 typedef SmallVector<Value*, 16> ValueVector; 2280 typedef SmallPtrSet<Value*, 16> ValueSet; 2281 // Holds the Load and Store *instructions*. 2282 ValueVector Loads; 2283 ValueVector Stores; 2284 PtrRtCheck.Pointers.clear(); 2285 PtrRtCheck.Need = false; 2286 2287 // For each block. 2288 for (Loop::block_iterator bb = TheLoop->block_begin(), 2289 be = TheLoop->block_end(); bb != be; ++bb) { 2290 2291 // Scan the BB and collect legal loads and stores. 2292 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e; 2293 ++it) { 2294 2295 // If this is a load, save it. If this instruction can read from memory 2296 // but is not a load, then we quit. Notice that we don't handle function 2297 // calls that read or write. 2298 if (it->mayReadFromMemory()) { 2299 LoadInst *Ld = dyn_cast<LoadInst>(it); 2300 if (!Ld) return false; 2301 if (!Ld->isSimple()) { 2302 DEBUG(dbgs() << "LV: Found a non-simple load.\n"); 2303 return false; 2304 } 2305 Loads.push_back(Ld); 2306 continue; 2307 } 2308 2309 // Save 'store' instructions. Abort if other instructions write to memory. 2310 if (it->mayWriteToMemory()) { 2311 StoreInst *St = dyn_cast<StoreInst>(it); 2312 if (!St) return false; 2313 if (!St->isSimple()) { 2314 DEBUG(dbgs() << "LV: Found a non-simple store.\n"); 2315 return false; 2316 } 2317 Stores.push_back(St); 2318 } 2319 } // next instr. 2320 } // next block. 2321 2322 // Now we have two lists that hold the loads and the stores. 2323 // Next, we find the pointers that they use. 2324 2325 // Check if we see any stores. If there are no stores, then we don't 2326 // care if the pointers are *restrict*. 2327 if (!Stores.size()) { 2328 DEBUG(dbgs() << "LV: Found a read-only loop!\n"); 2329 return true; 2330 } 2331 2332 // Holds the read and read-write *pointers* that we find. 2333 ValueVector Reads; 2334 ValueVector ReadWrites; 2335 2336 // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects 2337 // multiple times on the same object. If the ptr is accessed twice, once 2338 // for read and once for write, it will only appear once (on the write 2339 // list). This is okay, since we are going to check for conflicts between 2340 // writes and between reads and writes, but not between reads and reads. 2341 ValueSet Seen; 2342 2343 ValueVector::iterator I, IE; 2344 for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) { 2345 StoreInst *ST = cast<StoreInst>(*I); 2346 Value* Ptr = ST->getPointerOperand(); 2347 2348 if (isUniform(Ptr)) { 2349 DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n"); 2350 return false; 2351 } 2352 2353 // If we did *not* see this pointer before, insert it to 2354 // the read-write list. At this phase it is only a 'write' list. 2355 if (Seen.insert(Ptr)) 2356 ReadWrites.push_back(Ptr); 2357 } 2358 2359 for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) { 2360 LoadInst *LD = cast<LoadInst>(*I); 2361 Value* Ptr = LD->getPointerOperand(); 2362 // If we did *not* see this pointer before, insert it to the 2363 // read list. If we *did* see it before, then it is already in 2364 // the read-write list. This allows us to vectorize expressions 2365 // such as A[i] += x; Because the address of A[i] is a read-write 2366 // pointer. This only works if the index of A[i] is consecutive. 2367 // If the address of i is unknown (for example A[B[i]]) then we may 2368 // read a few words, modify, and write a few words, and some of the 2369 // words may be written to the same address. 2370 if (Seen.insert(Ptr) || 0 == isConsecutivePtr(Ptr)) 2371 Reads.push_back(Ptr); 2372 } 2373 2374 // If we write (or read-write) to a single destination and there are no 2375 // other reads in this loop then is it safe to vectorize. 2376 if (ReadWrites.size() == 1 && Reads.size() == 0) { 2377 DEBUG(dbgs() << "LV: Found a write-only loop!\n"); 2378 return true; 2379 } 2380 2381 // Find pointers with computable bounds. We are going to use this information 2382 // to place a runtime bound check. 2383 bool CanDoRT = true; 2384 for (I = ReadWrites.begin(), IE = ReadWrites.end(); I != IE; ++I) 2385 if (hasComputableBounds(*I)) { 2386 PtrRtCheck.insert(SE, TheLoop, *I); 2387 DEBUG(dbgs() << "LV: Found a runtime check ptr:" << **I <<"\n"); 2388 } else { 2389 CanDoRT = false; 2390 break; 2391 } 2392 for (I = Reads.begin(), IE = Reads.end(); I != IE; ++I) 2393 if (hasComputableBounds(*I)) { 2394 PtrRtCheck.insert(SE, TheLoop, *I); 2395 DEBUG(dbgs() << "LV: Found a runtime check ptr:" << **I <<"\n"); 2396 } else { 2397 CanDoRT = false; 2398 break; 2399 } 2400 2401 // Check that we did not collect too many pointers or found a 2402 // unsizeable pointer. 2403 if (!CanDoRT || PtrRtCheck.Pointers.size() > RuntimeMemoryCheckThreshold) { 2404 PtrRtCheck.reset(); 2405 CanDoRT = false; 2406 } 2407 2408 if (CanDoRT) { 2409 DEBUG(dbgs() << "LV: We can perform a memory runtime check if needed.\n"); 2410 } 2411 2412 bool NeedRTCheck = false; 2413 2414 // Now that the pointers are in two lists (Reads and ReadWrites), we 2415 // can check that there are no conflicts between each of the writes and 2416 // between the writes to the reads. 2417 ValueSet WriteObjects; 2418 ValueVector TempObjects; 2419 2420 // Check that the read-writes do not conflict with other read-write 2421 // pointers. 2422 bool AllWritesIdentified = true; 2423 for (I = ReadWrites.begin(), IE = ReadWrites.end(); I != IE; ++I) { 2424 GetUnderlyingObjects(*I, TempObjects, DL); 2425 for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end(); 2426 it != e; ++it) { 2427 if (!isIdentifiedObject(*it)) { 2428 DEBUG(dbgs() << "LV: Found an unidentified write ptr:"<< **it <<"\n"); 2429 NeedRTCheck = true; 2430 AllWritesIdentified = false; 2431 } 2432 if (!WriteObjects.insert(*it)) { 2433 DEBUG(dbgs() << "LV: Found a possible write-write reorder:" 2434 << **it <<"\n"); 2435 return false; 2436 } 2437 } 2438 TempObjects.clear(); 2439 } 2440 2441 /// Check that the reads don't conflict with the read-writes. 2442 for (I = Reads.begin(), IE = Reads.end(); I != IE; ++I) { 2443 GetUnderlyingObjects(*I, TempObjects, DL); 2444 for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end(); 2445 it != e; ++it) { 2446 // If all of the writes are identified then we don't care if the read 2447 // pointer is identified or not. 2448 if (!AllWritesIdentified && !isIdentifiedObject(*it)) { 2449 DEBUG(dbgs() << "LV: Found an unidentified read ptr:"<< **it <<"\n"); 2450 NeedRTCheck = true; 2451 } 2452 if (WriteObjects.count(*it)) { 2453 DEBUG(dbgs() << "LV: Found a possible read/write reorder:" 2454 << **it <<"\n"); 2455 return false; 2456 } 2457 } 2458 TempObjects.clear(); 2459 } 2460 2461 PtrRtCheck.Need = NeedRTCheck; 2462 if (NeedRTCheck && !CanDoRT) { 2463 DEBUG(dbgs() << "LV: We can't vectorize because we can't find " << 2464 "the array bounds.\n"); 2465 PtrRtCheck.reset(); 2466 return false; 2467 } 2468 2469 DEBUG(dbgs() << "LV: We "<< (NeedRTCheck ? "" : "don't") << 2470 " need a runtime memory check.\n"); 2471 return true; 2472 } 2473 2474 bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi, 2475 ReductionKind Kind) { 2476 if (Phi->getNumIncomingValues() != 2) 2477 return false; 2478 2479 // Reduction variables are only found in the loop header block. 2480 if (Phi->getParent() != TheLoop->getHeader()) 2481 return false; 2482 2483 // Obtain the reduction start value from the value that comes from the loop 2484 // preheader. 2485 Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader()); 2486 2487 // ExitInstruction is the single value which is used outside the loop. 2488 // We only allow for a single reduction value to be used outside the loop. 2489 // This includes users of the reduction, variables (which form a cycle 2490 // which ends in the phi node). 2491 Instruction *ExitInstruction = 0; 2492 // Indicates that we found a binary operation in our scan. 2493 bool FoundBinOp = false; 2494 2495 // Iter is our iterator. We start with the PHI node and scan for all of the 2496 // users of this instruction. All users must be instructions that can be 2497 // used as reduction variables (such as ADD). We may have a single 2498 // out-of-block user. The cycle must end with the original PHI. 2499 Instruction *Iter = Phi; 2500 while (true) { 2501 // If the instruction has no users then this is a broken 2502 // chain and can't be a reduction variable. 2503 if (Iter->use_empty()) 2504 return false; 2505 2506 // Did we find a user inside this loop already ? 2507 bool FoundInBlockUser = false; 2508 // Did we reach the initial PHI node already ? 2509 bool FoundStartPHI = false; 2510 2511 // Is this a bin op ? 2512 FoundBinOp |= !isa<PHINode>(Iter); 2513 2514 // For each of the *users* of iter. 2515 for (Value::use_iterator it = Iter->use_begin(), e = Iter->use_end(); 2516 it != e; ++it) { 2517 Instruction *U = cast<Instruction>(*it); 2518 // We already know that the PHI is a user. 2519 if (U == Phi) { 2520 FoundStartPHI = true; 2521 continue; 2522 } 2523 2524 // Check if we found the exit user. 2525 BasicBlock *Parent = U->getParent(); 2526 if (!TheLoop->contains(Parent)) { 2527 // Exit if you find multiple outside users. 2528 if (ExitInstruction != 0) 2529 return false; 2530 ExitInstruction = Iter; 2531 } 2532 2533 // We allow in-loop PHINodes which are not the original reduction PHI 2534 // node. If this PHI is the only user of Iter (happens in IF w/ no ELSE 2535 // structure) then don't skip this PHI. 2536 if (isa<PHINode>(Iter) && isa<PHINode>(U) && 2537 U->getParent() != TheLoop->getHeader() && 2538 TheLoop->contains(U) && 2539 Iter->getNumUses() > 1) 2540 continue; 2541 2542 // We can't have multiple inside users. 2543 if (FoundInBlockUser) 2544 return false; 2545 FoundInBlockUser = true; 2546 2547 // Any reduction instr must be of one of the allowed kinds. 2548 if (!isReductionInstr(U, Kind)) 2549 return false; 2550 2551 // Reductions of instructions such as Div, and Sub is only 2552 // possible if the LHS is the reduction variable. 2553 if (!U->isCommutative() && !isa<PHINode>(U) && U->getOperand(0) != Iter) 2554 return false; 2555 2556 Iter = U; 2557 } 2558 2559 // We found a reduction var if we have reached the original 2560 // phi node and we only have a single instruction with out-of-loop 2561 // users. 2562 if (FoundStartPHI) { 2563 // This instruction is allowed to have out-of-loop users. 2564 AllowedExit.insert(ExitInstruction); 2565 2566 // Save the description of this reduction variable. 2567 ReductionDescriptor RD(RdxStart, ExitInstruction, Kind); 2568 Reductions[Phi] = RD; 2569 // We've ended the cycle. This is a reduction variable if we have an 2570 // outside user and it has a binary op. 2571 return FoundBinOp && ExitInstruction; 2572 } 2573 } 2574 } 2575 2576 bool 2577 LoopVectorizationLegality::isReductionInstr(Instruction *I, 2578 ReductionKind Kind) { 2579 bool FP = I->getType()->isFloatingPointTy(); 2580 bool FastMath = (FP && I->isCommutative() && I->isAssociative()); 2581 2582 switch (I->getOpcode()) { 2583 default: 2584 return false; 2585 case Instruction::PHI: 2586 if (FP && (Kind != RK_FloatMult && Kind != RK_FloatAdd)) 2587 return false; 2588 // possibly. 2589 return true; 2590 case Instruction::Sub: 2591 case Instruction::Add: 2592 return Kind == RK_IntegerAdd; 2593 case Instruction::SDiv: 2594 case Instruction::UDiv: 2595 case Instruction::Mul: 2596 return Kind == RK_IntegerMult; 2597 case Instruction::And: 2598 return Kind == RK_IntegerAnd; 2599 case Instruction::Or: 2600 return Kind == RK_IntegerOr; 2601 case Instruction::Xor: 2602 return Kind == RK_IntegerXor; 2603 case Instruction::FMul: 2604 return Kind == RK_FloatMult && FastMath; 2605 case Instruction::FAdd: 2606 return Kind == RK_FloatAdd && FastMath; 2607 } 2608 } 2609 2610 LoopVectorizationLegality::InductionKind 2611 LoopVectorizationLegality::isInductionVariable(PHINode *Phi) { 2612 Type *PhiTy = Phi->getType(); 2613 // We only handle integer and pointer inductions variables. 2614 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy()) 2615 return IK_NoInduction; 2616 2617 // Check that the PHI is consecutive. 2618 const SCEV *PhiScev = SE->getSCEV(Phi); 2619 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev); 2620 if (!AR) { 2621 DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n"); 2622 return IK_NoInduction; 2623 } 2624 const SCEV *Step = AR->getStepRecurrence(*SE); 2625 2626 // Integer inductions need to have a stride of one. 2627 if (PhiTy->isIntegerTy()) { 2628 if (Step->isOne()) 2629 return IK_IntInduction; 2630 if (Step->isAllOnesValue()) 2631 return IK_ReverseIntInduction; 2632 return IK_NoInduction; 2633 } 2634 2635 // Calculate the pointer stride and check if it is consecutive. 2636 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step); 2637 if (!C) 2638 return IK_NoInduction; 2639 2640 assert(PhiTy->isPointerTy() && "The PHI must be a pointer"); 2641 uint64_t Size = DL->getTypeAllocSize(PhiTy->getPointerElementType()); 2642 if (C->getValue()->equalsInt(Size)) 2643 return IK_PtrInduction; 2644 else if (C->getValue()->equalsInt(0 - Size)) 2645 return IK_ReversePtrInduction; 2646 2647 return IK_NoInduction; 2648 } 2649 2650 bool LoopVectorizationLegality::isInductionVariable(const Value *V) { 2651 Value *In0 = const_cast<Value*>(V); 2652 PHINode *PN = dyn_cast_or_null<PHINode>(In0); 2653 if (!PN) 2654 return false; 2655 2656 return Inductions.count(PN); 2657 } 2658 2659 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) { 2660 assert(TheLoop->contains(BB) && "Unknown block used"); 2661 2662 // Blocks that do not dominate the latch need predication. 2663 BasicBlock* Latch = TheLoop->getLoopLatch(); 2664 return !DT->dominates(BB, Latch); 2665 } 2666 2667 bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB) { 2668 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) { 2669 // We don't predicate loads/stores at the moment. 2670 if (it->mayReadFromMemory() || it->mayWriteToMemory() || it->mayThrow()) 2671 return false; 2672 2673 // The instructions below can trap. 2674 switch (it->getOpcode()) { 2675 default: continue; 2676 case Instruction::UDiv: 2677 case Instruction::SDiv: 2678 case Instruction::URem: 2679 case Instruction::SRem: 2680 return false; 2681 } 2682 } 2683 2684 return true; 2685 } 2686 2687 bool LoopVectorizationLegality::hasComputableBounds(Value *Ptr) { 2688 const SCEV *PhiScev = SE->getSCEV(Ptr); 2689 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev); 2690 if (!AR) 2691 return false; 2692 2693 return AR->isAffine(); 2694 } 2695 2696 LoopVectorizationCostModel::VectorizationFactor 2697 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize, 2698 unsigned UserVF) { 2699 // Width 1 means no vectorize 2700 VectorizationFactor Factor = { 1U, 0U }; 2701 if (OptForSize && Legal->getRuntimePointerCheck()->Need) { 2702 DEBUG(dbgs() << "LV: Aborting. Runtime ptr check is required in Os.\n"); 2703 return Factor; 2704 } 2705 2706 // Find the trip count. 2707 unsigned TC = SE->getSmallConstantTripCount(TheLoop, TheLoop->getLoopLatch()); 2708 DEBUG(dbgs() << "LV: Found trip count:"<<TC<<"\n"); 2709 2710 unsigned WidestType = getWidestType(); 2711 unsigned WidestRegister = TTI.getRegisterBitWidth(true); 2712 unsigned MaxVectorSize = WidestRegister / WidestType; 2713 DEBUG(dbgs() << "LV: The Widest type: " << WidestType << " bits.\n"); 2714 DEBUG(dbgs() << "LV: The Widest register is:" << WidestRegister << "bits.\n"); 2715 2716 if (MaxVectorSize == 0) { 2717 DEBUG(dbgs() << "LV: The target has no vector registers.\n"); 2718 MaxVectorSize = 1; 2719 } 2720 2721 assert(MaxVectorSize <= 32 && "Did not expect to pack so many elements" 2722 " into one vector!"); 2723 2724 unsigned VF = MaxVectorSize; 2725 2726 // If we optimize the program for size, avoid creating the tail loop. 2727 if (OptForSize) { 2728 // If we are unable to calculate the trip count then don't try to vectorize. 2729 if (TC < 2) { 2730 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n"); 2731 return Factor; 2732 } 2733 2734 // Find the maximum SIMD width that can fit within the trip count. 2735 VF = TC % MaxVectorSize; 2736 2737 if (VF == 0) 2738 VF = MaxVectorSize; 2739 2740 // If the trip count that we found modulo the vectorization factor is not 2741 // zero then we require a tail. 2742 if (VF < 2) { 2743 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n"); 2744 return Factor; 2745 } 2746 } 2747 2748 if (UserVF != 0) { 2749 assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two"); 2750 DEBUG(dbgs() << "LV: Using user VF "<<UserVF<<".\n"); 2751 2752 Factor.Width = UserVF; 2753 return Factor; 2754 } 2755 2756 float Cost = expectedCost(1); 2757 unsigned Width = 1; 2758 DEBUG(dbgs() << "LV: Scalar loop costs: "<< (int)Cost << ".\n"); 2759 for (unsigned i=2; i <= VF; i*=2) { 2760 // Notice that the vector loop needs to be executed less times, so 2761 // we need to divide the cost of the vector loops by the width of 2762 // the vector elements. 2763 float VectorCost = expectedCost(i) / (float)i; 2764 DEBUG(dbgs() << "LV: Vector loop of width "<< i << " costs: " << 2765 (int)VectorCost << ".\n"); 2766 if (VectorCost < Cost) { 2767 Cost = VectorCost; 2768 Width = i; 2769 } 2770 } 2771 2772 DEBUG(dbgs() << "LV: Selecting VF = : "<< Width << ".\n"); 2773 Factor.Width = Width; 2774 Factor.Cost = Width * Cost; 2775 return Factor; 2776 } 2777 2778 unsigned LoopVectorizationCostModel::getWidestType() { 2779 unsigned MaxWidth = 8; 2780 2781 // For each block. 2782 for (Loop::block_iterator bb = TheLoop->block_begin(), 2783 be = TheLoop->block_end(); bb != be; ++bb) { 2784 BasicBlock *BB = *bb; 2785 2786 // For each instruction in the loop. 2787 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) { 2788 Type *T = it->getType(); 2789 2790 // Only examine Loads, Stores and PHINodes. 2791 if (!isa<LoadInst>(it) && !isa<StoreInst>(it) && !isa<PHINode>(it)) 2792 continue; 2793 2794 // Examine PHI nodes that are reduction variables. 2795 if (PHINode *PN = dyn_cast<PHINode>(it)) 2796 if (!Legal->getReductionVars()->count(PN)) 2797 continue; 2798 2799 // Examine the stored values. 2800 StoreInst *ST = 0; 2801 if ((ST = dyn_cast<StoreInst>(it))) 2802 T = ST->getValueOperand()->getType(); 2803 2804 // Ignore loaded pointer types and stored pointer types that are not 2805 // consecutive. However, we do want to take consecutive stores/loads of 2806 // pointer vectors into account. 2807 if (T->isPointerTy() && isConsecutiveLoadOrStore(it)) 2808 MaxWidth = std::max(MaxWidth, DL->getPointerSizeInBits()); 2809 else 2810 MaxWidth = std::max(MaxWidth, T->getScalarSizeInBits()); 2811 } 2812 } 2813 2814 return MaxWidth; 2815 } 2816 2817 unsigned 2818 LoopVectorizationCostModel::selectUnrollFactor(bool OptForSize, 2819 unsigned UserUF, 2820 unsigned VF, 2821 unsigned LoopCost) { 2822 2823 // -- The unroll heuristics -- 2824 // We unroll the loop in order to expose ILP and reduce the loop overhead. 2825 // There are many micro-architectural considerations that we can't predict 2826 // at this level. For example frontend pressure (on decode or fetch) due to 2827 // code size, or the number and capabilities of the execution ports. 2828 // 2829 // We use the following heuristics to select the unroll factor: 2830 // 1. If the code has reductions the we unroll in order to break the cross 2831 // iteration dependency. 2832 // 2. If the loop is really small then we unroll in order to reduce the loop 2833 // overhead. 2834 // 3. We don't unroll if we think that we will spill registers to memory due 2835 // to the increased register pressure. 2836 2837 // Use the user preference, unless 'auto' is selected. 2838 if (UserUF != 0) 2839 return UserUF; 2840 2841 // When we optimize for size we don't unroll. 2842 if (OptForSize) 2843 return 1; 2844 2845 // Do not unroll loops with a relatively small trip count. 2846 unsigned TC = SE->getSmallConstantTripCount(TheLoop, 2847 TheLoop->getLoopLatch()); 2848 if (TC > 1 && TC < TinyTripCountUnrollThreshold) 2849 return 1; 2850 2851 unsigned TargetVectorRegisters = TTI.getNumberOfRegisters(true); 2852 DEBUG(dbgs() << "LV: The target has " << TargetVectorRegisters << 2853 " vector registers\n"); 2854 2855 LoopVectorizationCostModel::RegisterUsage R = calculateRegisterUsage(); 2856 // We divide by these constants so assume that we have at least one 2857 // instruction that uses at least one register. 2858 R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U); 2859 R.NumInstructions = std::max(R.NumInstructions, 1U); 2860 2861 // We calculate the unroll factor using the following formula. 2862 // Subtract the number of loop invariants from the number of available 2863 // registers. These registers are used by all of the unrolled instances. 2864 // Next, divide the remaining registers by the number of registers that is 2865 // required by the loop, in order to estimate how many parallel instances 2866 // fit without causing spills. 2867 unsigned UF = (TargetVectorRegisters - R.LoopInvariantRegs) / R.MaxLocalUsers; 2868 2869 // Clamp the unroll factor ranges to reasonable factors. 2870 unsigned MaxUnrollSize = TTI.getMaximumUnrollFactor(); 2871 2872 // If we did not calculate the cost for VF (because the user selected the VF) 2873 // then we calculate the cost of VF here. 2874 if (LoopCost == 0) 2875 LoopCost = expectedCost(VF); 2876 2877 // Clamp the calculated UF to be between the 1 and the max unroll factor 2878 // that the target allows. 2879 if (UF > MaxUnrollSize) 2880 UF = MaxUnrollSize; 2881 else if (UF < 1) 2882 UF = 1; 2883 2884 if (Legal->getReductionVars()->size()) { 2885 DEBUG(dbgs() << "LV: Unrolling because of reductions. \n"); 2886 return UF; 2887 } 2888 2889 // We want to unroll tiny loops in order to reduce the loop overhead. 2890 // We assume that the cost overhead is 1 and we use the cost model 2891 // to estimate the cost of the loop and unroll until the cost of the 2892 // loop overhead is about 5% of the cost of the loop. 2893 DEBUG(dbgs() << "LV: Loop cost is "<< LoopCost <<" \n"); 2894 if (LoopCost < 20) { 2895 DEBUG(dbgs() << "LV: Unrolling to reduce branch cost. \n"); 2896 unsigned NewUF = 20/LoopCost + 1; 2897 return std::min(NewUF, UF); 2898 } 2899 2900 DEBUG(dbgs() << "LV: Not Unrolling. \n"); 2901 return 1; 2902 } 2903 2904 LoopVectorizationCostModel::RegisterUsage 2905 LoopVectorizationCostModel::calculateRegisterUsage() { 2906 // This function calculates the register usage by measuring the highest number 2907 // of values that are alive at a single location. Obviously, this is a very 2908 // rough estimation. We scan the loop in a topological order in order and 2909 // assign a number to each instruction. We use RPO to ensure that defs are 2910 // met before their users. We assume that each instruction that has in-loop 2911 // users starts an interval. We record every time that an in-loop value is 2912 // used, so we have a list of the first and last occurrences of each 2913 // instruction. Next, we transpose this data structure into a multi map that 2914 // holds the list of intervals that *end* at a specific location. This multi 2915 // map allows us to perform a linear search. We scan the instructions linearly 2916 // and record each time that a new interval starts, by placing it in a set. 2917 // If we find this value in the multi-map then we remove it from the set. 2918 // The max register usage is the maximum size of the set. 2919 // We also search for instructions that are defined outside the loop, but are 2920 // used inside the loop. We need this number separately from the max-interval 2921 // usage number because when we unroll, loop-invariant values do not take 2922 // more register. 2923 LoopBlocksDFS DFS(TheLoop); 2924 DFS.perform(LI); 2925 2926 RegisterUsage R; 2927 R.NumInstructions = 0; 2928 2929 // Each 'key' in the map opens a new interval. The values 2930 // of the map are the index of the 'last seen' usage of the 2931 // instruction that is the key. 2932 typedef DenseMap<Instruction*, unsigned> IntervalMap; 2933 // Maps instruction to its index. 2934 DenseMap<unsigned, Instruction*> IdxToInstr; 2935 // Marks the end of each interval. 2936 IntervalMap EndPoint; 2937 // Saves the list of instruction indices that are used in the loop. 2938 SmallSet<Instruction*, 8> Ends; 2939 // Saves the list of values that are used in the loop but are 2940 // defined outside the loop, such as arguments and constants. 2941 SmallPtrSet<Value*, 8> LoopInvariants; 2942 2943 unsigned Index = 0; 2944 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(), 2945 be = DFS.endRPO(); bb != be; ++bb) { 2946 R.NumInstructions += (*bb)->size(); 2947 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e; 2948 ++it) { 2949 Instruction *I = it; 2950 IdxToInstr[Index++] = I; 2951 2952 // Save the end location of each USE. 2953 for (unsigned i = 0; i < I->getNumOperands(); ++i) { 2954 Value *U = I->getOperand(i); 2955 Instruction *Instr = dyn_cast<Instruction>(U); 2956 2957 // Ignore non-instruction values such as arguments, constants, etc. 2958 if (!Instr) continue; 2959 2960 // If this instruction is outside the loop then record it and continue. 2961 if (!TheLoop->contains(Instr)) { 2962 LoopInvariants.insert(Instr); 2963 continue; 2964 } 2965 2966 // Overwrite previous end points. 2967 EndPoint[Instr] = Index; 2968 Ends.insert(Instr); 2969 } 2970 } 2971 } 2972 2973 // Saves the list of intervals that end with the index in 'key'. 2974 typedef SmallVector<Instruction*, 2> InstrList; 2975 DenseMap<unsigned, InstrList> TransposeEnds; 2976 2977 // Transpose the EndPoints to a list of values that end at each index. 2978 for (IntervalMap::iterator it = EndPoint.begin(), e = EndPoint.end(); 2979 it != e; ++it) 2980 TransposeEnds[it->second].push_back(it->first); 2981 2982 SmallSet<Instruction*, 8> OpenIntervals; 2983 unsigned MaxUsage = 0; 2984 2985 2986 DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n"); 2987 for (unsigned int i = 0; i < Index; ++i) { 2988 Instruction *I = IdxToInstr[i]; 2989 // Ignore instructions that are never used within the loop. 2990 if (!Ends.count(I)) continue; 2991 2992 // Remove all of the instructions that end at this location. 2993 InstrList &List = TransposeEnds[i]; 2994 for (unsigned int j=0, e = List.size(); j < e; ++j) 2995 OpenIntervals.erase(List[j]); 2996 2997 // Count the number of live interals. 2998 MaxUsage = std::max(MaxUsage, OpenIntervals.size()); 2999 3000 DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # " << 3001 OpenIntervals.size() <<"\n"); 3002 3003 // Add the current instruction to the list of open intervals. 3004 OpenIntervals.insert(I); 3005 } 3006 3007 unsigned Invariant = LoopInvariants.size(); 3008 DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsage << " \n"); 3009 DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << " \n"); 3010 DEBUG(dbgs() << "LV(REG): LoopSize: " << R.NumInstructions << " \n"); 3011 3012 R.LoopInvariantRegs = Invariant; 3013 R.MaxLocalUsers = MaxUsage; 3014 return R; 3015 } 3016 3017 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) { 3018 unsigned Cost = 0; 3019 3020 // For each block. 3021 for (Loop::block_iterator bb = TheLoop->block_begin(), 3022 be = TheLoop->block_end(); bb != be; ++bb) { 3023 unsigned BlockCost = 0; 3024 BasicBlock *BB = *bb; 3025 3026 // For each instruction in the old loop. 3027 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) { 3028 unsigned C = getInstructionCost(it, VF); 3029 Cost += C; 3030 DEBUG(dbgs() << "LV: Found an estimated cost of "<< C <<" for VF " << 3031 VF << " For instruction: "<< *it << "\n"); 3032 } 3033 3034 // We assume that if-converted blocks have a 50% chance of being executed. 3035 // When the code is scalar then some of the blocks are avoided due to CF. 3036 // When the code is vectorized we execute all code paths. 3037 if (Legal->blockNeedsPredication(*bb) && VF == 1) 3038 BlockCost /= 2; 3039 3040 Cost += BlockCost; 3041 } 3042 3043 return Cost; 3044 } 3045 3046 unsigned 3047 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) { 3048 // If we know that this instruction will remain uniform, check the cost of 3049 // the scalar version. 3050 if (Legal->isUniformAfterVectorization(I)) 3051 VF = 1; 3052 3053 Type *RetTy = I->getType(); 3054 Type *VectorTy = ToVectorTy(RetTy, VF); 3055 3056 // TODO: We need to estimate the cost of intrinsic calls. 3057 switch (I->getOpcode()) { 3058 case Instruction::GetElementPtr: 3059 // We mark this instruction as zero-cost because scalar GEPs are usually 3060 // lowered to the intruction addressing mode. At the moment we don't 3061 // generate vector geps. 3062 return 0; 3063 case Instruction::Br: { 3064 return TTI.getCFInstrCost(I->getOpcode()); 3065 } 3066 case Instruction::PHI: 3067 //TODO: IF-converted IFs become selects. 3068 return 0; 3069 case Instruction::Add: 3070 case Instruction::FAdd: 3071 case Instruction::Sub: 3072 case Instruction::FSub: 3073 case Instruction::Mul: 3074 case Instruction::FMul: 3075 case Instruction::UDiv: 3076 case Instruction::SDiv: 3077 case Instruction::FDiv: 3078 case Instruction::URem: 3079 case Instruction::SRem: 3080 case Instruction::FRem: 3081 case Instruction::Shl: 3082 case Instruction::LShr: 3083 case Instruction::AShr: 3084 case Instruction::And: 3085 case Instruction::Or: 3086 case Instruction::Xor: 3087 return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy); 3088 case Instruction::Select: { 3089 SelectInst *SI = cast<SelectInst>(I); 3090 const SCEV *CondSCEV = SE->getSCEV(SI->getCondition()); 3091 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop)); 3092 Type *CondTy = SI->getCondition()->getType(); 3093 if (ScalarCond) 3094 CondTy = VectorType::get(CondTy, VF); 3095 3096 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy); 3097 } 3098 case Instruction::ICmp: 3099 case Instruction::FCmp: { 3100 Type *ValTy = I->getOperand(0)->getType(); 3101 VectorTy = ToVectorTy(ValTy, VF); 3102 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy); 3103 } 3104 case Instruction::Store: 3105 case Instruction::Load: { 3106 StoreInst *SI = dyn_cast<StoreInst>(I); 3107 LoadInst *LI = dyn_cast<LoadInst>(I); 3108 Type *ValTy = (SI ? SI->getValueOperand()->getType() : 3109 LI->getType()); 3110 VectorTy = ToVectorTy(ValTy, VF); 3111 3112 unsigned Alignment = SI ? SI->getAlignment() : LI->getAlignment(); 3113 unsigned AS = SI ? SI->getPointerAddressSpace() : 3114 LI->getPointerAddressSpace(); 3115 Value *Ptr = SI ? SI->getPointerOperand() : LI->getPointerOperand(); 3116 3117 if (VF == 1) 3118 return TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS); 3119 3120 // Scalarized loads/stores. 3121 int Stride = Legal->isConsecutivePtr(Ptr); 3122 bool Reverse = Stride < 0; 3123 if (0 == Stride) { 3124 unsigned Cost = 0; 3125 // The cost of extracting from the value vector and pointer vector. 3126 Type *PtrTy = ToVectorTy(Ptr->getType(), VF); 3127 for (unsigned i = 0; i < VF; ++i) { 3128 // The cost of extracting the pointer operand. 3129 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i); 3130 // In case of STORE, the cost of ExtractElement from the vector. 3131 // In case of LOAD, the cost of InsertElement into the returned 3132 // vector. 3133 Cost += TTI.getVectorInstrCost(SI ? Instruction::ExtractElement : 3134 Instruction::InsertElement, 3135 VectorTy, i); 3136 } 3137 3138 // The cost of the scalar stores. 3139 Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(), 3140 Alignment, AS); 3141 return Cost; 3142 } 3143 3144 // Wide load/stores. 3145 unsigned Cost = TTI.getMemoryOpCost(I->getOpcode(), VectorTy, 3146 Alignment, AS); 3147 if (Reverse) 3148 Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, 3149 VectorTy, 0); 3150 return Cost; 3151 } 3152 case Instruction::ZExt: 3153 case Instruction::SExt: 3154 case Instruction::FPToUI: 3155 case Instruction::FPToSI: 3156 case Instruction::FPExt: 3157 case Instruction::PtrToInt: 3158 case Instruction::IntToPtr: 3159 case Instruction::SIToFP: 3160 case Instruction::UIToFP: 3161 case Instruction::Trunc: 3162 case Instruction::FPTrunc: 3163 case Instruction::BitCast: { 3164 // We optimize the truncation of induction variable. 3165 // The cost of these is the same as the scalar operation. 3166 if (I->getOpcode() == Instruction::Trunc && 3167 Legal->isInductionVariable(I->getOperand(0))) 3168 return TTI.getCastInstrCost(I->getOpcode(), I->getType(), 3169 I->getOperand(0)->getType()); 3170 3171 Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF); 3172 return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy); 3173 } 3174 case Instruction::Call: { 3175 assert(isTriviallyVectorizableIntrinsic(I)); 3176 IntrinsicInst *II = cast<IntrinsicInst>(I); 3177 Type *RetTy = ToVectorTy(II->getType(), VF); 3178 SmallVector<Type*, 4> Tys; 3179 for (unsigned i = 0, ie = II->getNumArgOperands(); i != ie; ++i) 3180 Tys.push_back(ToVectorTy(II->getArgOperand(i)->getType(), VF)); 3181 return TTI.getIntrinsicInstrCost(II->getIntrinsicID(), RetTy, Tys); 3182 } 3183 default: { 3184 // We are scalarizing the instruction. Return the cost of the scalar 3185 // instruction, plus the cost of insert and extract into vector 3186 // elements, times the vector width. 3187 unsigned Cost = 0; 3188 3189 if (!RetTy->isVoidTy() && VF != 1) { 3190 unsigned InsCost = TTI.getVectorInstrCost(Instruction::InsertElement, 3191 VectorTy); 3192 unsigned ExtCost = TTI.getVectorInstrCost(Instruction::ExtractElement, 3193 VectorTy); 3194 3195 // The cost of inserting the results plus extracting each one of the 3196 // operands. 3197 Cost += VF * (InsCost + ExtCost * I->getNumOperands()); 3198 } 3199 3200 // The cost of executing VF copies of the scalar instruction. This opcode 3201 // is unknown. Assume that it is the same as 'mul'. 3202 Cost += VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy); 3203 return Cost; 3204 } 3205 }// end of switch. 3206 } 3207 3208 Type* LoopVectorizationCostModel::ToVectorTy(Type *Scalar, unsigned VF) { 3209 if (Scalar->isVoidTy() || VF == 1) 3210 return Scalar; 3211 return VectorType::get(Scalar, VF); 3212 } 3213 3214 char LoopVectorize::ID = 0; 3215 static const char lv_name[] = "Loop Vectorization"; 3216 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false) 3217 INITIALIZE_AG_DEPENDENCY(AliasAnalysis) 3218 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo) 3219 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution) 3220 INITIALIZE_PASS_DEPENDENCY(LoopSimplify) 3221 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false) 3222 3223 namespace llvm { 3224 Pass *createLoopVectorizePass() { 3225 return new LoopVectorize(); 3226 } 3227 } 3228 3229 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) { 3230 // Check for a store. 3231 StoreInst *ST = dyn_cast<StoreInst>(Inst); 3232 if (ST) 3233 return Legal->isConsecutivePtr(ST->getPointerOperand()) != 0; 3234 3235 // Check for a load. 3236 LoadInst *LI = dyn_cast<LoadInst>(Inst); 3237 if (LI) 3238 return Legal->isConsecutivePtr(LI->getPointerOperand()) != 0; 3239 3240 return false; 3241 } 3242