1 //===- LoopVectorize.cpp - A Loop Vectorizer ------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This is the LLVM loop vectorizer. This pass modifies 'vectorizable' loops
11 // and generates target-independent LLVM-IR.
12 // The vectorizer uses the TargetTransformInfo analysis to estimate the costs
13 // of instructions in order to estimate the profitability of vectorization.
15 // The loop vectorizer combines consecutive loop iterations into a single
16 // 'wide' iteration. After this transformation the index is incremented
17 // by the SIMD vector width, and not by one.
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.
29 //===----------------------------------------------------------------------===//
31 // The reduction-variable vectorization is based on the paper:
32 // D. Nuzman and R. Henderson. Multi-platform Auto-vectorization.
34 // Variable uniformity checks are inspired by:
35 // Karrenberg, R. and Hack, S. Whole Function Vectorization.
37 // Other ideas/concepts are from:
38 // A. Zaks and D. Nuzman. Autovectorization in GCC-two years later.
40 // S. Maleki, Y. Gao, M. Garzaran, T. Wong and D. Padua. An Evaluation of
41 // Vectorizing Compilers.
43 //===----------------------------------------------------------------------===//
45 #define LV_NAME "loop-vectorize"
46 #define DEBUG_TYPE LV_NAME
48 #include "llvm/Transforms/Vectorize.h"
49 #include "llvm/ADT/DenseMap.h"
50 #include "llvm/ADT/EquivalenceClasses.h"
51 #include "llvm/ADT/MapVector.h"
52 #include "llvm/ADT/SmallPtrSet.h"
53 #include "llvm/ADT/SmallSet.h"
54 #include "llvm/ADT/SmallVector.h"
55 #include "llvm/ADT/StringExtras.h"
56 #include "llvm/Analysis/AliasAnalysis.h"
57 #include "llvm/Analysis/AliasSetTracker.h"
58 #include "llvm/Analysis/Dominators.h"
59 #include "llvm/Analysis/LoopInfo.h"
60 #include "llvm/Analysis/LoopIterator.h"
61 #include "llvm/Analysis/LoopPass.h"
62 #include "llvm/Analysis/ScalarEvolution.h"
63 #include "llvm/Analysis/ScalarEvolutionExpander.h"
64 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
65 #include "llvm/Analysis/TargetTransformInfo.h"
66 #include "llvm/Analysis/ValueTracking.h"
67 #include "llvm/Analysis/Verifier.h"
68 #include "llvm/IR/Constants.h"
69 #include "llvm/IR/DataLayout.h"
70 #include "llvm/IR/DerivedTypes.h"
71 #include "llvm/IR/Function.h"
72 #include "llvm/IR/IRBuilder.h"
73 #include "llvm/IR/Instructions.h"
74 #include "llvm/IR/IntrinsicInst.h"
75 #include "llvm/IR/LLVMContext.h"
76 #include "llvm/IR/Module.h"
77 #include "llvm/IR/Type.h"
78 #include "llvm/IR/Value.h"
79 #include "llvm/Pass.h"
80 #include "llvm/Support/CommandLine.h"
81 #include "llvm/Support/Debug.h"
82 #include "llvm/Support/PatternMatch.h"
83 #include "llvm/Support/raw_ostream.h"
84 #include "llvm/Support/ValueHandle.h"
85 #include "llvm/Target/TargetLibraryInfo.h"
86 #include "llvm/Transforms/Scalar.h"
87 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
88 #include "llvm/Transforms/Utils/Local.h"
93 using namespace llvm::PatternMatch;
95 static cl::opt<unsigned>
96 VectorizationFactor("force-vector-width", cl::init(0), cl::Hidden,
97 cl::desc("Sets the SIMD width. Zero is autoselect."));
99 static cl::opt<unsigned>
100 VectorizationUnroll("force-vector-unroll", cl::init(0), cl::Hidden,
101 cl::desc("Sets the vectorization unroll count. "
102 "Zero is autoselect."));
105 EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
106 cl::desc("Enable if-conversion during vectorization."));
108 /// We don't vectorize loops with a known constant trip count below this number.
109 static cl::opt<unsigned>
110 TinyTripCountVectorThreshold("vectorizer-min-trip-count", cl::init(16),
112 cl::desc("Don't vectorize loops with a constant "
113 "trip count that is smaller than this "
116 /// We don't unroll loops with a known constant trip count below this number.
117 static const unsigned TinyTripCountUnrollThreshold = 128;
119 /// When performing memory disambiguation checks at runtime do not make more
120 /// than this number of comparisons.
121 static const unsigned RuntimeMemoryCheckThreshold = 8;
123 /// Maximum simd width.
124 static const unsigned MaxVectorWidth = 64;
126 /// Maximum vectorization unroll count.
127 static const unsigned MaxUnrollFactor = 16;
131 // Forward declarations.
132 class LoopVectorizationLegality;
133 class LoopVectorizationCostModel;
135 /// InnerLoopVectorizer vectorizes loops which contain only one basic
136 /// block to a specified vectorization factor (VF).
137 /// This class performs the widening of scalars into vectors, or multiple
138 /// scalars. This class also implements the following features:
139 /// * It inserts an epilogue loop for handling loops that don't have iteration
140 /// counts that are known to be a multiple of the vectorization factor.
141 /// * It handles the code generation for reduction variables.
142 /// * Scalarization (implementation using scalars) of un-vectorizable
144 /// InnerLoopVectorizer does not perform any vectorization-legality
145 /// checks, and relies on the caller to check for the different legality
146 /// aspects. The InnerLoopVectorizer relies on the
147 /// LoopVectorizationLegality class to provide information about the induction
148 /// and reduction variables that were found to a given vectorization factor.
149 class InnerLoopVectorizer {
151 InnerLoopVectorizer(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
152 DominatorTree *DT, DataLayout *DL,
153 const TargetLibraryInfo *TLI, unsigned VecWidth,
154 unsigned UnrollFactor)
155 : OrigLoop(OrigLoop), SE(SE), LI(LI), DT(DT), DL(DL), TLI(TLI),
156 VF(VecWidth), UF(UnrollFactor), Builder(SE->getContext()), Induction(0),
157 OldInduction(0), WidenMap(UnrollFactor) {}
159 // Perform the actual loop widening (vectorization).
160 void vectorize(LoopVectorizationLegality *Legal) {
161 // Create a new empty loop. Unlink the old loop and connect the new one.
162 createEmptyLoop(Legal);
163 // Widen each instruction in the old loop to a new one in the new loop.
164 // Use the Legality module to find the induction and reduction variables.
165 vectorizeLoop(Legal);
166 // Register the new loop and update the analysis passes.
171 /// A small list of PHINodes.
172 typedef SmallVector<PHINode*, 4> PhiVector;
173 /// When we unroll loops we have multiple vector values for each scalar.
174 /// This data structure holds the unrolled and vectorized values that
175 /// originated from one scalar instruction.
176 typedef SmallVector<Value*, 2> VectorParts;
178 /// Add code that checks at runtime if the accessed arrays overlap.
179 /// Returns the comparator value or NULL if no check is needed.
180 Instruction *addRuntimeCheck(LoopVectorizationLegality *Legal,
182 /// Create an empty loop, based on the loop ranges of the old loop.
183 void createEmptyLoop(LoopVectorizationLegality *Legal);
184 /// Copy and widen the instructions from the old loop.
185 void vectorizeLoop(LoopVectorizationLegality *Legal);
187 /// A helper function that computes the predicate of the block BB, assuming
188 /// that the header block of the loop is set to True. It returns the *entry*
189 /// mask for the block BB.
190 VectorParts createBlockInMask(BasicBlock *BB);
191 /// A helper function that computes the predicate of the edge between SRC
193 VectorParts createEdgeMask(BasicBlock *Src, BasicBlock *Dst);
195 /// A helper function to vectorize a single BB within the innermost loop.
196 void vectorizeBlockInLoop(LoopVectorizationLegality *Legal, BasicBlock *BB,
199 /// Insert the new loop to the loop hierarchy and pass manager
200 /// and update the analysis passes.
201 void updateAnalysis();
203 /// This instruction is un-vectorizable. Implement it as a sequence
205 void scalarizeInstruction(Instruction *Instr);
207 /// Vectorize Load and Store instructions,
208 void vectorizeMemoryInstruction(Instruction *Instr,
209 LoopVectorizationLegality *Legal);
211 /// Create a broadcast instruction. This method generates a broadcast
212 /// instruction (shuffle) for loop invariant values and for the induction
213 /// value. If this is the induction variable then we extend it to N, N+1, ...
214 /// this is needed because each iteration in the loop corresponds to a SIMD
216 Value *getBroadcastInstrs(Value *V);
218 /// This function adds 0, 1, 2 ... to each vector element, starting at zero.
219 /// If Negate is set then negative numbers are added e.g. (0, -1, -2, ...).
220 /// The sequence starts at StartIndex.
221 Value *getConsecutiveVector(Value* Val, int StartIdx, bool Negate);
223 /// When we go over instructions in the basic block we rely on previous
224 /// values within the current basic block or on loop invariant values.
225 /// When we widen (vectorize) values we place them in the map. If the values
226 /// are not within the map, they have to be loop invariant, so we simply
227 /// broadcast them into a vector.
228 VectorParts &getVectorValue(Value *V);
230 /// Generate a shuffle sequence that will reverse the vector Vec.
231 Value *reverseVector(Value *Vec);
233 /// This is a helper class that holds the vectorizer state. It maps scalar
234 /// instructions to vector instructions. When the code is 'unrolled' then
235 /// then a single scalar value is mapped to multiple vector parts. The parts
236 /// are stored in the VectorPart type.
238 /// C'tor. UnrollFactor controls the number of vectors ('parts') that
240 ValueMap(unsigned UnrollFactor) : UF(UnrollFactor) {}
242 /// \return True if 'Key' is saved in the Value Map.
243 bool has(Value *Key) const { return MapStorage.count(Key); }
245 /// Initializes a new entry in the map. Sets all of the vector parts to the
246 /// save value in 'Val'.
247 /// \return A reference to a vector with splat values.
248 VectorParts &splat(Value *Key, Value *Val) {
249 VectorParts &Entry = MapStorage[Key];
250 Entry.assign(UF, Val);
254 ///\return A reference to the value that is stored at 'Key'.
255 VectorParts &get(Value *Key) {
256 VectorParts &Entry = MapStorage[Key];
259 assert(Entry.size() == UF);
264 /// The unroll factor. Each entry in the map stores this number of vector
268 /// Map storage. We use std::map and not DenseMap because insertions to a
269 /// dense map invalidates its iterators.
270 std::map<Value *, VectorParts> MapStorage;
273 /// The original loop.
275 /// Scev analysis to use.
283 /// Target Library Info.
284 const TargetLibraryInfo *TLI;
286 /// The vectorization SIMD factor to use. Each vector will have this many
289 /// The vectorization unroll factor to use. Each scalar is vectorized to this
290 /// many different vector instructions.
293 /// The builder that we use
296 // --- Vectorization state ---
298 /// The vector-loop preheader.
299 BasicBlock *LoopVectorPreHeader;
300 /// The scalar-loop preheader.
301 BasicBlock *LoopScalarPreHeader;
302 /// Middle Block between the vector and the scalar.
303 BasicBlock *LoopMiddleBlock;
304 ///The ExitBlock of the scalar loop.
305 BasicBlock *LoopExitBlock;
306 ///The vector loop body.
307 BasicBlock *LoopVectorBody;
308 ///The scalar loop body.
309 BasicBlock *LoopScalarBody;
310 /// A list of all bypass blocks. The first block is the entry of the loop.
311 SmallVector<BasicBlock *, 4> LoopBypassBlocks;
313 /// The new Induction variable which was added to the new block.
315 /// The induction variable of the old basic block.
316 PHINode *OldInduction;
317 /// Holds the extended (to the widest induction type) start index.
319 /// Maps scalars to widened vectors.
323 /// \brief Check if conditionally executed loads are hoistable.
325 /// This class has two functions: isHoistableLoad and canHoistAllLoads.
326 /// isHoistableLoad should be called on all load instructions that are executed
327 /// conditionally. After all conditional loads are processed, the client should
328 /// call canHoistAllLoads to determine if all of the conditional executed loads
329 /// have an unconditional memory access to the same memory address in the loop.
331 typedef SmallPtrSet<Value *, 8> MemorySet;
335 MemorySet CondLoadAddrSet;
338 LoadHoisting(Loop *L, DominatorTree *D) : TheLoop(L), DT(D) {}
340 /// \brief Check if the instruction is a load with a identifiable address.
341 bool isHoistableLoad(Instruction *L);
343 /// \brief Check if all of the conditional loads are hoistable because there
344 /// exists an unconditional memory access to the same address in the loop.
345 bool canHoistAllLoads();
348 bool LoadHoisting::isHoistableLoad(Instruction *L) {
349 LoadInst *LI = dyn_cast<LoadInst>(L);
353 CondLoadAddrSet.insert(LI->getPointerOperand());
357 static void addMemAccesses(BasicBlock *BB, SmallPtrSet<Value *, 8> &Set) {
358 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE; ++BI) {
359 if (LoadInst *LI = dyn_cast<LoadInst>(BI)) // Try a load.
360 Set.insert(LI->getPointerOperand());
361 else if (StoreInst *SI = dyn_cast<StoreInst>(BI)) // Try a store.
362 Set.insert(SI->getPointerOperand());
366 bool LoadHoisting::canHoistAllLoads() {
367 // No conditional loads.
368 if (CondLoadAddrSet.empty())
371 MemorySet UncondMemAccesses;
372 std::vector<BasicBlock*> &LoopBlocks = TheLoop->getBlocksVector();
373 BasicBlock *LoopLatch = TheLoop->getLoopLatch();
375 // Iterate over the unconditional blocks and collect memory access addresses.
376 for (unsigned i = 0, e = LoopBlocks.size(); i < e; ++i) {
377 BasicBlock *BB = LoopBlocks[i];
379 // Ignore conditional blocks.
380 if (BB != LoopLatch && !DT->dominates(BB, LoopLatch))
383 addMemAccesses(BB, UncondMemAccesses);
386 // And make sure there is a matching unconditional access for every
388 for (MemorySet::iterator MI = CondLoadAddrSet.begin(),
389 ME = CondLoadAddrSet.end(); MI != ME; ++MI)
390 if (!UncondMemAccesses.count(*MI))
396 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
397 /// to what vectorization factor.
398 /// This class does not look at the profitability of vectorization, only the
399 /// legality. This class has two main kinds of checks:
400 /// * Memory checks - The code in canVectorizeMemory checks if vectorization
401 /// will change the order of memory accesses in a way that will change the
402 /// correctness of the program.
403 /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
404 /// checks for a number of different conditions, such as the availability of a
405 /// single induction variable, that all types are supported and vectorize-able,
406 /// etc. This code reflects the capabilities of InnerLoopVectorizer.
407 /// This class is also used by InnerLoopVectorizer for identifying
408 /// induction variable and the different reduction variables.
409 class LoopVectorizationLegality {
411 LoopVectorizationLegality(Loop *L, ScalarEvolution *SE, DataLayout *DL,
412 DominatorTree *DT, TargetTransformInfo* TTI,
413 AliasAnalysis *AA, TargetLibraryInfo *TLI)
414 : TheLoop(L), SE(SE), DL(DL), DT(DT), TTI(TTI), AA(AA), TLI(TLI),
415 Induction(0), WidestIndTy(0), HasFunNoNaNAttr(false),
416 LoadSpeculation(L, DT) {}
418 /// This enum represents the kinds of reductions that we support.
420 RK_NoReduction, ///< Not a reduction.
421 RK_IntegerAdd, ///< Sum of integers.
422 RK_IntegerMult, ///< Product of integers.
423 RK_IntegerOr, ///< Bitwise or logical OR of numbers.
424 RK_IntegerAnd, ///< Bitwise or logical AND of numbers.
425 RK_IntegerXor, ///< Bitwise or logical XOR of numbers.
426 RK_IntegerMinMax, ///< Min/max implemented in terms of select(cmp()).
427 RK_FloatAdd, ///< Sum of floats.
428 RK_FloatMult, ///< Product of floats.
429 RK_FloatMinMax ///< Min/max implemented in terms of select(cmp()).
432 /// This enum represents the kinds of inductions that we support.
434 IK_NoInduction, ///< Not an induction variable.
435 IK_IntInduction, ///< Integer induction variable. Step = 1.
436 IK_ReverseIntInduction, ///< Reverse int induction variable. Step = -1.
437 IK_PtrInduction, ///< Pointer induction var. Step = sizeof(elem).
438 IK_ReversePtrInduction ///< Reverse ptr indvar. Step = - sizeof(elem).
441 // This enum represents the kind of minmax reduction.
442 enum MinMaxReductionKind {
452 /// This POD struct holds information about reduction variables.
453 struct ReductionDescriptor {
454 ReductionDescriptor() : StartValue(0), LoopExitInstr(0),
455 Kind(RK_NoReduction), MinMaxKind(MRK_Invalid) {}
457 ReductionDescriptor(Value *Start, Instruction *Exit, ReductionKind K,
458 MinMaxReductionKind MK)
459 : StartValue(Start), LoopExitInstr(Exit), Kind(K), MinMaxKind(MK) {}
461 // The starting value of the reduction.
462 // It does not have to be zero!
463 TrackingVH<Value> StartValue;
464 // The instruction who's value is used outside the loop.
465 Instruction *LoopExitInstr;
466 // The kind of the reduction.
468 // If this a min/max reduction the kind of reduction.
469 MinMaxReductionKind MinMaxKind;
472 /// This POD struct holds information about a potential reduction operation.
473 struct ReductionInstDesc {
474 ReductionInstDesc(bool IsRedux, Instruction *I) :
475 IsReduction(IsRedux), PatternLastInst(I), MinMaxKind(MRK_Invalid) {}
477 ReductionInstDesc(Instruction *I, MinMaxReductionKind K) :
478 IsReduction(true), PatternLastInst(I), MinMaxKind(K) {}
480 // Is this instruction a reduction candidate.
482 // The last instruction in a min/max pattern (select of the select(icmp())
483 // pattern), or the current reduction instruction otherwise.
484 Instruction *PatternLastInst;
485 // If this is a min/max pattern the comparison predicate.
486 MinMaxReductionKind MinMaxKind;
489 // This POD struct holds information about the memory runtime legality
490 // check that a group of pointers do not overlap.
491 struct RuntimePointerCheck {
492 RuntimePointerCheck() : Need(false) {}
494 /// Reset the state of the pointer runtime information.
502 /// Insert a pointer and calculate the start and end SCEVs.
503 void insert(ScalarEvolution *SE, Loop *Lp, Value *Ptr, bool WritePtr);
505 /// This flag indicates if we need to add the runtime check.
507 /// Holds the pointers that we need to check.
508 SmallVector<TrackingVH<Value>, 2> Pointers;
509 /// Holds the pointer value at the beginning of the loop.
510 SmallVector<const SCEV*, 2> Starts;
511 /// Holds the pointer value at the end of the loop.
512 SmallVector<const SCEV*, 2> Ends;
513 /// Holds the information if this pointer is used for writing to memory.
514 SmallVector<bool, 2> IsWritePtr;
517 /// A POD for saving information about induction variables.
518 struct InductionInfo {
519 InductionInfo(Value *Start, InductionKind K) : StartValue(Start), IK(K) {}
520 InductionInfo() : StartValue(0), IK(IK_NoInduction) {}
522 TrackingVH<Value> StartValue;
527 /// ReductionList contains the reduction descriptors for all
528 /// of the reductions that were found in the loop.
529 typedef DenseMap<PHINode*, ReductionDescriptor> ReductionList;
531 /// InductionList saves induction variables and maps them to the
532 /// induction descriptor.
533 typedef MapVector<PHINode*, InductionInfo> InductionList;
535 /// Alias(Multi)Map stores the values (GEPs or underlying objects and their
536 /// respective Store/Load instruction(s) to calculate aliasing.
537 typedef MapVector<Value*, Instruction* > AliasMap;
538 typedef DenseMap<Value*, std::vector<Instruction*> > AliasMultiMap;
540 /// Returns true if it is legal to vectorize this loop.
541 /// This does not mean that it is profitable to vectorize this
542 /// loop, only that it is legal to do so.
545 /// Returns the Induction variable.
546 PHINode *getInduction() { return Induction; }
548 /// Returns the reduction variables found in the loop.
549 ReductionList *getReductionVars() { return &Reductions; }
551 /// Returns the induction variables found in the loop.
552 InductionList *getInductionVars() { return &Inductions; }
554 /// Returns the widest induction type.
555 Type *getWidestInductionType() { return WidestIndTy; }
557 /// Returns True if V is an induction variable in this loop.
558 bool isInductionVariable(const Value *V);
560 /// Return true if the block BB needs to be predicated in order for the loop
561 /// to be vectorized.
562 bool blockNeedsPredication(BasicBlock *BB);
564 /// Check if this pointer is consecutive when vectorizing. This happens
565 /// when the last index of the GEP is the induction variable, or that the
566 /// pointer itself is an induction variable.
567 /// This check allows us to vectorize A[idx] into a wide load/store.
569 /// 0 - Stride is unknown or non consecutive.
570 /// 1 - Address is consecutive.
571 /// -1 - Address is consecutive, and decreasing.
572 int isConsecutivePtr(Value *Ptr);
574 /// Returns true if the value V is uniform within the loop.
575 bool isUniform(Value *V);
577 /// Returns true if this instruction will remain scalar after vectorization.
578 bool isUniformAfterVectorization(Instruction* I) { return Uniforms.count(I); }
580 /// Returns the information that we collected about runtime memory check.
581 RuntimePointerCheck *getRuntimePointerCheck() { return &PtrRtCheck; }
583 /// This function returns the identity element (or neutral element) for
585 static Constant *getReductionIdentity(ReductionKind K, Type *Tp);
587 /// Check if a single basic block loop is vectorizable.
588 /// At this point we know that this is a loop with a constant trip count
589 /// and we only need to check individual instructions.
590 bool canVectorizeInstrs();
592 /// When we vectorize loops we may change the order in which
593 /// we read and write from memory. This method checks if it is
594 /// legal to vectorize the code, considering only memory constrains.
595 /// Returns true if the loop is vectorizable
596 bool canVectorizeMemory();
598 /// Return true if we can vectorize this loop using the IF-conversion
600 bool canVectorizeWithIfConvert();
602 /// Collect the variables that need to stay uniform after vectorization.
603 void collectLoopUniforms();
605 /// Return true if all of the instructions in the block can be speculatively
607 bool blockCanBePredicated(BasicBlock *BB);
609 /// Returns True, if 'Phi' is the kind of reduction variable for type
610 /// 'Kind'. If this is a reduction variable, it adds it to ReductionList.
611 bool AddReductionVar(PHINode *Phi, ReductionKind Kind);
612 /// Returns a struct describing if the instruction 'I' can be a reduction
613 /// variable of type 'Kind'. If the reduction is a min/max pattern of
614 /// select(icmp()) this function advances the instruction pointer 'I' from the
615 /// compare instruction to the select instruction and stores this pointer in
616 /// 'PatternLastInst' member of the returned struct.
617 ReductionInstDesc isReductionInstr(Instruction *I, ReductionKind Kind,
618 ReductionInstDesc &Desc);
619 /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
620 /// pattern corresponding to a min(X, Y) or max(X, Y).
621 static ReductionInstDesc isMinMaxSelectCmpPattern(Instruction *I,
622 ReductionInstDesc &Prev);
623 /// Returns the induction kind of Phi. This function may return NoInduction
624 /// if the PHI is not an induction variable.
625 InductionKind isInductionVariable(PHINode *Phi);
626 /// Return true if can compute the address bounds of Ptr within the loop.
627 bool hasComputableBounds(Value *Ptr);
628 /// Return true if there is the chance of write reorder.
629 bool hasPossibleGlobalWriteReorder(Value *Object,
631 AliasMultiMap &WriteObjects,
632 unsigned MaxByteWidth);
633 /// Return the AA location for a load or a store.
634 AliasAnalysis::Location getLoadStoreLocation(Instruction *Inst);
637 /// The loop that we evaluate.
641 /// DataLayout analysis.
646 TargetTransformInfo *TTI;
649 /// Target Library Info.
650 TargetLibraryInfo *TLI;
652 // --- vectorization state --- //
654 /// Holds the integer induction variable. This is the counter of the
657 /// Holds the reduction variables.
658 ReductionList Reductions;
659 /// Holds all of the induction variables that we found in the loop.
660 /// Notice that inductions don't need to start at zero and that induction
661 /// variables can be pointers.
662 InductionList Inductions;
663 /// Holds the widest induction type encountered.
666 /// Allowed outside users. This holds the reduction
667 /// vars which can be accessed from outside the loop.
668 SmallPtrSet<Value*, 4> AllowedExit;
669 /// This set holds the variables which are known to be uniform after
671 SmallPtrSet<Instruction*, 4> Uniforms;
672 /// We need to check that all of the pointers in this list are disjoint
674 RuntimePointerCheck PtrRtCheck;
675 /// Can we assume the absence of NaNs.
676 bool HasFunNoNaNAttr;
678 /// Utility to determine whether loads can be speculated.
679 LoadHoisting LoadSpeculation;
682 /// LoopVectorizationCostModel - estimates the expected speedups due to
684 /// In many cases vectorization is not profitable. This can happen because of
685 /// a number of reasons. In this class we mainly attempt to predict the
686 /// expected speedup/slowdowns due to the supported instruction set. We use the
687 /// TargetTransformInfo to query the different backends for the cost of
688 /// different operations.
689 class LoopVectorizationCostModel {
691 LoopVectorizationCostModel(Loop *L, ScalarEvolution *SE, LoopInfo *LI,
692 LoopVectorizationLegality *Legal,
693 const TargetTransformInfo &TTI,
694 DataLayout *DL, const TargetLibraryInfo *TLI)
695 : TheLoop(L), SE(SE), LI(LI), Legal(Legal), TTI(TTI), DL(DL), TLI(TLI) {}
697 /// Information about vectorization costs
698 struct VectorizationFactor {
699 unsigned Width; // Vector width with best cost
700 unsigned Cost; // Cost of the loop with that width
702 /// \return The most profitable vectorization factor and the cost of that VF.
703 /// This method checks every power of two up to VF. If UserVF is not ZERO
704 /// then this vectorization factor will be selected if vectorization is
706 VectorizationFactor selectVectorizationFactor(bool OptForSize,
709 /// \return The size (in bits) of the widest type in the code that
710 /// needs to be vectorized. We ignore values that remain scalar such as
711 /// 64 bit loop indices.
712 unsigned getWidestType();
714 /// \return The most profitable unroll factor.
715 /// If UserUF is non-zero then this method finds the best unroll-factor
716 /// based on register pressure and other parameters.
717 /// VF and LoopCost are the selected vectorization factor and the cost of the
719 unsigned selectUnrollFactor(bool OptForSize, unsigned UserUF, unsigned VF,
722 /// \brief A struct that represents some properties of the register usage
724 struct RegisterUsage {
725 /// Holds the number of loop invariant values that are used in the loop.
726 unsigned LoopInvariantRegs;
727 /// Holds the maximum number of concurrent live intervals in the loop.
728 unsigned MaxLocalUsers;
729 /// Holds the number of instructions in the loop.
730 unsigned NumInstructions;
733 /// \return information about the register usage of the loop.
734 RegisterUsage calculateRegisterUsage();
737 /// Returns the expected execution cost. The unit of the cost does
738 /// not matter because we use the 'cost' units to compare different
739 /// vector widths. The cost that is returned is *not* normalized by
740 /// the factor width.
741 unsigned expectedCost(unsigned VF);
743 /// Returns the execution time cost of an instruction for a given vector
744 /// width. Vector width of one means scalar.
745 unsigned getInstructionCost(Instruction *I, unsigned VF);
747 /// A helper function for converting Scalar types to vector types.
748 /// If the incoming type is void, we return void. If the VF is 1, we return
750 static Type* ToVectorTy(Type *Scalar, unsigned VF);
752 /// Returns whether the instruction is a load or store and will be a emitted
753 /// as a vector operation.
754 bool isConsecutiveLoadOrStore(Instruction *I);
756 /// The loop that we evaluate.
760 /// Loop Info analysis.
762 /// Vectorization legality.
763 LoopVectorizationLegality *Legal;
764 /// Vector target information.
765 const TargetTransformInfo &TTI;
766 /// Target data layout information.
768 /// Target Library Info.
769 const TargetLibraryInfo *TLI;
772 /// Utility class for getting and setting loop vectorizer hints in the form
773 /// of loop metadata.
774 struct LoopVectorizeHints {
775 /// Vectorization width.
777 /// Vectorization unroll factor.
780 LoopVectorizeHints(const Loop *L)
781 : Width(VectorizationFactor)
782 , Unroll(VectorizationUnroll)
783 , LoopID(L->getLoopID()) {
785 // The command line options override any loop metadata except for when
786 // width == 1 which is used to indicate the loop is already vectorized.
787 if (VectorizationFactor.getNumOccurrences() > 0 && Width != 1)
788 Width = VectorizationFactor;
789 if (VectorizationUnroll.getNumOccurrences() > 0)
790 Unroll = VectorizationUnroll;
793 /// Return the loop vectorizer metadata prefix.
794 static StringRef Prefix() { return "llvm.vectorizer."; }
796 MDNode *createHint(LLVMContext &Context, StringRef Name, unsigned V) {
797 SmallVector<Value*, 2> Vals;
798 Vals.push_back(MDString::get(Context, Name));
799 Vals.push_back(ConstantInt::get(Type::getInt32Ty(Context), V));
800 return MDNode::get(Context, Vals);
803 /// Mark the loop L as already vectorized by setting the width to 1.
804 void setAlreadyVectorized(Loop *L) {
805 LLVMContext &Context = L->getHeader()->getContext();
809 // Create a new loop id with one more operand for the already_vectorized
810 // hint. If the loop already has a loop id then copy the existing operands.
811 SmallVector<Value*, 4> Vals(1);
813 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i)
814 Vals.push_back(LoopID->getOperand(i));
816 Vals.push_back(createHint(Context, Twine(Prefix(), "width").str(), Width));
818 MDNode *NewLoopID = MDNode::get(Context, Vals);
819 // Set operand 0 to refer to the loop id itself.
820 NewLoopID->replaceOperandWith(0, NewLoopID);
822 L->setLoopID(NewLoopID);
824 LoopID->replaceAllUsesWith(NewLoopID);
832 /// Find hints specified in the loop metadata.
833 void getHints(const Loop *L) {
837 // First operand should refer to the loop id itself.
838 assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
839 assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
841 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
842 const MDString *S = 0;
843 SmallVector<Value*, 4> Args;
845 // The expected hint is either a MDString or a MDNode with the first
846 // operand a MDString.
847 if (const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i))) {
848 if (!MD || MD->getNumOperands() == 0)
850 S = dyn_cast<MDString>(MD->getOperand(0));
851 for (unsigned i = 1, ie = MD->getNumOperands(); i < ie; ++i)
852 Args.push_back(MD->getOperand(i));
854 S = dyn_cast<MDString>(LoopID->getOperand(i));
855 assert(Args.size() == 0 && "too many arguments for MDString");
861 // Check if the hint starts with the vectorizer prefix.
862 StringRef Hint = S->getString();
863 if (!Hint.startswith(Prefix()))
865 // Remove the prefix.
866 Hint = Hint.substr(Prefix().size(), StringRef::npos);
868 if (Args.size() == 1)
869 getHint(Hint, Args[0]);
873 // Check string hint with one operand.
874 void getHint(StringRef Hint, Value *Arg) {
875 const ConstantInt *C = dyn_cast<ConstantInt>(Arg);
877 unsigned Val = C->getZExtValue();
879 if (Hint == "width") {
880 assert(isPowerOf2_32(Val) && Val <= MaxVectorWidth &&
881 "Invalid width metadata");
883 } else if (Hint == "unroll") {
884 assert(isPowerOf2_32(Val) && Val <= MaxUnrollFactor &&
885 "Invalid unroll metadata");
888 DEBUG(dbgs() << "LV: ignoring unknown hint " << Hint);
892 /// The LoopVectorize Pass.
893 struct LoopVectorize : public LoopPass {
894 /// Pass identification, replacement for typeid
897 explicit LoopVectorize() : LoopPass(ID) {
898 initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
904 TargetTransformInfo *TTI;
907 TargetLibraryInfo *TLI;
909 virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
910 // We only vectorize innermost loops.
914 SE = &getAnalysis<ScalarEvolution>();
915 DL = getAnalysisIfAvailable<DataLayout>();
916 LI = &getAnalysis<LoopInfo>();
917 TTI = &getAnalysis<TargetTransformInfo>();
918 DT = &getAnalysis<DominatorTree>();
919 AA = getAnalysisIfAvailable<AliasAnalysis>();
920 TLI = getAnalysisIfAvailable<TargetLibraryInfo>();
923 DEBUG(dbgs() << "LV: Not vectorizing because of missing data layout");
927 DEBUG(dbgs() << "LV: Checking a loop in \"" <<
928 L->getHeader()->getParent()->getName() << "\"\n");
930 LoopVectorizeHints Hints(L);
932 if (Hints.Width == 1) {
933 DEBUG(dbgs() << "LV: Not vectorizing.\n");
937 // Check if it is legal to vectorize the loop.
938 LoopVectorizationLegality LVL(L, SE, DL, DT, TTI, AA, TLI);
939 if (!LVL.canVectorize()) {
940 DEBUG(dbgs() << "LV: Not vectorizing.\n");
944 // Use the cost model.
945 LoopVectorizationCostModel CM(L, SE, LI, &LVL, *TTI, DL, TLI);
947 // Check the function attributes to find out if this function should be
948 // optimized for size.
949 Function *F = L->getHeader()->getParent();
950 Attribute::AttrKind SzAttr = Attribute::OptimizeForSize;
951 Attribute::AttrKind FlAttr = Attribute::NoImplicitFloat;
952 unsigned FnIndex = AttributeSet::FunctionIndex;
953 bool OptForSize = F->getAttributes().hasAttribute(FnIndex, SzAttr);
954 bool NoFloat = F->getAttributes().hasAttribute(FnIndex, FlAttr);
957 DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
958 "attribute is used.\n");
962 // Select the optimal vectorization factor.
963 LoopVectorizationCostModel::VectorizationFactor VF;
964 VF = CM.selectVectorizationFactor(OptForSize, Hints.Width);
965 // Select the unroll factor.
966 unsigned UF = CM.selectUnrollFactor(OptForSize, Hints.Unroll, VF.Width,
970 DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
974 DEBUG(dbgs() << "LV: Found a vectorizable loop ("<< VF.Width << ") in "<<
975 F->getParent()->getModuleIdentifier()<<"\n");
976 DEBUG(dbgs() << "LV: Unroll Factor is " << UF << "\n");
978 // If we decided that it is *legal* to vectorize the loop then do it.
979 InnerLoopVectorizer LB(L, SE, LI, DT, DL, TLI, VF.Width, UF);
982 // Mark the loop as already vectorized to avoid vectorizing again.
983 Hints.setAlreadyVectorized(L);
985 DEBUG(verifyFunction(*L->getHeader()->getParent()));
989 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
990 LoopPass::getAnalysisUsage(AU);
991 AU.addRequiredID(LoopSimplifyID);
992 AU.addRequiredID(LCSSAID);
993 AU.addRequired<DominatorTree>();
994 AU.addRequired<LoopInfo>();
995 AU.addRequired<ScalarEvolution>();
996 AU.addRequired<TargetTransformInfo>();
997 AU.addPreserved<LoopInfo>();
998 AU.addPreserved<DominatorTree>();
1003 } // end anonymous namespace
1005 //===----------------------------------------------------------------------===//
1006 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
1007 // LoopVectorizationCostModel.
1008 //===----------------------------------------------------------------------===//
1011 LoopVectorizationLegality::RuntimePointerCheck::insert(ScalarEvolution *SE,
1012 Loop *Lp, Value *Ptr,
1014 const SCEV *Sc = SE->getSCEV(Ptr);
1015 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
1016 assert(AR && "Invalid addrec expression");
1017 const SCEV *Ex = SE->getBackedgeTakenCount(Lp);
1018 const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
1019 Pointers.push_back(Ptr);
1020 Starts.push_back(AR->getStart());
1021 Ends.push_back(ScEnd);
1022 IsWritePtr.push_back(WritePtr);
1025 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
1026 // Save the current insertion location.
1027 Instruction *Loc = Builder.GetInsertPoint();
1029 // We need to place the broadcast of invariant variables outside the loop.
1030 Instruction *Instr = dyn_cast<Instruction>(V);
1031 bool NewInstr = (Instr && Instr->getParent() == LoopVectorBody);
1032 bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
1034 // Place the code for broadcasting invariant variables in the new preheader.
1036 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
1038 // Broadcast the scalar into all locations in the vector.
1039 Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
1041 // Restore the builder insertion point.
1043 Builder.SetInsertPoint(Loc);
1048 Value *InnerLoopVectorizer::getConsecutiveVector(Value* Val, int StartIdx,
1050 assert(Val->getType()->isVectorTy() && "Must be a vector");
1051 assert(Val->getType()->getScalarType()->isIntegerTy() &&
1052 "Elem must be an integer");
1053 // Create the types.
1054 Type *ITy = Val->getType()->getScalarType();
1055 VectorType *Ty = cast<VectorType>(Val->getType());
1056 int VLen = Ty->getNumElements();
1057 SmallVector<Constant*, 8> Indices;
1059 // Create a vector of consecutive numbers from zero to VF.
1060 for (int i = 0; i < VLen; ++i) {
1061 int64_t Idx = Negate ? (-i) : i;
1062 Indices.push_back(ConstantInt::get(ITy, StartIdx + Idx, Negate));
1065 // Add the consecutive indices to the vector value.
1066 Constant *Cv = ConstantVector::get(Indices);
1067 assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
1068 return Builder.CreateAdd(Val, Cv, "induction");
1071 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
1072 assert(Ptr->getType()->isPointerTy() && "Unexpected non ptr");
1073 // Make sure that the pointer does not point to structs.
1074 if (cast<PointerType>(Ptr->getType())->getElementType()->isAggregateType())
1077 // If this value is a pointer induction variable we know it is consecutive.
1078 PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
1079 if (Phi && Inductions.count(Phi)) {
1080 InductionInfo II = Inductions[Phi];
1081 if (IK_PtrInduction == II.IK)
1083 else if (IK_ReversePtrInduction == II.IK)
1087 GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
1091 unsigned NumOperands = Gep->getNumOperands();
1092 Value *LastIndex = Gep->getOperand(NumOperands - 1);
1094 Value *GpPtr = Gep->getPointerOperand();
1095 // If this GEP value is a consecutive pointer induction variable and all of
1096 // the indices are constant then we know it is consecutive. We can
1097 Phi = dyn_cast<PHINode>(GpPtr);
1098 if (Phi && Inductions.count(Phi)) {
1100 // Make sure that the pointer does not point to structs.
1101 PointerType *GepPtrType = cast<PointerType>(GpPtr->getType());
1102 if (GepPtrType->getElementType()->isAggregateType())
1105 // Make sure that all of the index operands are loop invariant.
1106 for (unsigned i = 1; i < NumOperands; ++i)
1107 if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
1110 InductionInfo II = Inductions[Phi];
1111 if (IK_PtrInduction == II.IK)
1113 else if (IK_ReversePtrInduction == II.IK)
1117 // Check that all of the gep indices are uniform except for the last.
1118 for (unsigned i = 0; i < NumOperands - 1; ++i)
1119 if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
1122 // We can emit wide load/stores only if the last index is the induction
1124 const SCEV *Last = SE->getSCEV(LastIndex);
1125 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
1126 const SCEV *Step = AR->getStepRecurrence(*SE);
1128 // The memory is consecutive because the last index is consecutive
1129 // and all other indices are loop invariant.
1132 if (Step->isAllOnesValue())
1139 bool LoopVectorizationLegality::isUniform(Value *V) {
1140 return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
1143 InnerLoopVectorizer::VectorParts&
1144 InnerLoopVectorizer::getVectorValue(Value *V) {
1145 assert(V != Induction && "The new induction variable should not be used.");
1146 assert(!V->getType()->isVectorTy() && "Can't widen a vector");
1148 // If we have this scalar in the map, return it.
1149 if (WidenMap.has(V))
1150 return WidenMap.get(V);
1152 // If this scalar is unknown, assume that it is a constant or that it is
1153 // loop invariant. Broadcast V and save the value for future uses.
1154 Value *B = getBroadcastInstrs(V);
1155 return WidenMap.splat(V, B);
1158 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
1159 assert(Vec->getType()->isVectorTy() && "Invalid type");
1160 SmallVector<Constant*, 8> ShuffleMask;
1161 for (unsigned i = 0; i < VF; ++i)
1162 ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
1164 return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
1165 ConstantVector::get(ShuffleMask),
1170 void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr,
1171 LoopVectorizationLegality *Legal) {
1172 // Attempt to issue a wide load.
1173 LoadInst *LI = dyn_cast<LoadInst>(Instr);
1174 StoreInst *SI = dyn_cast<StoreInst>(Instr);
1176 assert((LI || SI) && "Invalid Load/Store instruction");
1178 Type *ScalarDataTy = LI ? LI->getType() : SI->getValueOperand()->getType();
1179 Type *DataTy = VectorType::get(ScalarDataTy, VF);
1180 Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
1181 unsigned Alignment = LI ? LI->getAlignment() : SI->getAlignment();
1182 unsigned AddressSpace = Ptr->getType()->getPointerAddressSpace();
1183 unsigned ScalarAllocatedSize = DL->getTypeAllocSize(ScalarDataTy);
1184 unsigned VectorElementSize = DL->getTypeStoreSize(DataTy)/VF;
1186 if (ScalarAllocatedSize != VectorElementSize)
1187 return scalarizeInstruction(Instr);
1189 // If the pointer is loop invariant or if it is non consecutive,
1190 // scalarize the load.
1191 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
1192 bool Reverse = ConsecutiveStride < 0;
1193 bool UniformLoad = LI && Legal->isUniform(Ptr);
1194 if (!ConsecutiveStride || UniformLoad)
1195 return scalarizeInstruction(Instr);
1197 Constant *Zero = Builder.getInt32(0);
1198 VectorParts &Entry = WidenMap.get(Instr);
1200 // Handle consecutive loads/stores.
1201 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1202 if (Gep && Legal->isInductionVariable(Gep->getPointerOperand())) {
1203 Value *PtrOperand = Gep->getPointerOperand();
1204 Value *FirstBasePtr = getVectorValue(PtrOperand)[0];
1205 FirstBasePtr = Builder.CreateExtractElement(FirstBasePtr, Zero);
1207 // Create the new GEP with the new induction variable.
1208 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1209 Gep2->setOperand(0, FirstBasePtr);
1210 Gep2->setName("gep.indvar.base");
1211 Ptr = Builder.Insert(Gep2);
1213 assert(SE->isLoopInvariant(SE->getSCEV(Gep->getPointerOperand()),
1214 OrigLoop) && "Base ptr must be invariant");
1216 // The last index does not have to be the induction. It can be
1217 // consecutive and be a function of the index. For example A[I+1];
1218 unsigned NumOperands = Gep->getNumOperands();
1220 Value *LastGepOperand = Gep->getOperand(NumOperands - 1);
1221 VectorParts &GEPParts = getVectorValue(LastGepOperand);
1222 Value *LastIndex = GEPParts[0];
1223 LastIndex = Builder.CreateExtractElement(LastIndex, Zero);
1225 // Create the new GEP with the new induction variable.
1226 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1227 Gep2->setOperand(NumOperands - 1, LastIndex);
1228 Gep2->setName("gep.indvar.idx");
1229 Ptr = Builder.Insert(Gep2);
1231 // Use the induction element ptr.
1232 assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1233 VectorParts &PtrVal = getVectorValue(Ptr);
1234 Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
1239 assert(!Legal->isUniform(SI->getPointerOperand()) &&
1240 "We do not allow storing to uniform addresses");
1242 VectorParts &StoredVal = getVectorValue(SI->getValueOperand());
1243 for (unsigned Part = 0; Part < UF; ++Part) {
1244 // Calculate the pointer for the specific unroll-part.
1245 Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1248 // If we store to reverse consecutive memory locations then we need
1249 // to reverse the order of elements in the stored value.
1250 StoredVal[Part] = reverseVector(StoredVal[Part]);
1251 // If the address is consecutive but reversed, then the
1252 // wide store needs to start at the last vector element.
1253 PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1254 PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1257 Value *VecPtr = Builder.CreateBitCast(PartPtr, DataTy->getPointerTo(AddressSpace));
1258 Builder.CreateStore(StoredVal[Part], VecPtr)->setAlignment(Alignment);
1262 for (unsigned Part = 0; Part < UF; ++Part) {
1263 // Calculate the pointer for the specific unroll-part.
1264 Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1267 // If the address is consecutive but reversed, then the
1268 // wide store needs to start at the last vector element.
1269 PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1270 PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1273 Value *VecPtr = Builder.CreateBitCast(PartPtr, DataTy->getPointerTo(AddressSpace));
1274 Value *LI = Builder.CreateLoad(VecPtr, "wide.load");
1275 cast<LoadInst>(LI)->setAlignment(Alignment);
1276 Entry[Part] = Reverse ? reverseVector(LI) : LI;
1280 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr) {
1281 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
1282 // Holds vector parameters or scalars, in case of uniform vals.
1283 SmallVector<VectorParts, 4> Params;
1285 // Find all of the vectorized parameters.
1286 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
1287 Value *SrcOp = Instr->getOperand(op);
1289 // If we are accessing the old induction variable, use the new one.
1290 if (SrcOp == OldInduction) {
1291 Params.push_back(getVectorValue(SrcOp));
1295 // Try using previously calculated values.
1296 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
1298 // If the src is an instruction that appeared earlier in the basic block
1299 // then it should already be vectorized.
1300 if (SrcInst && OrigLoop->contains(SrcInst)) {
1301 assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
1302 // The parameter is a vector value from earlier.
1303 Params.push_back(WidenMap.get(SrcInst));
1305 // The parameter is a scalar from outside the loop. Maybe even a constant.
1306 VectorParts Scalars;
1307 Scalars.append(UF, SrcOp);
1308 Params.push_back(Scalars);
1312 assert(Params.size() == Instr->getNumOperands() &&
1313 "Invalid number of operands");
1315 // Does this instruction return a value ?
1316 bool IsVoidRetTy = Instr->getType()->isVoidTy();
1318 Value *UndefVec = IsVoidRetTy ? 0 :
1319 UndefValue::get(VectorType::get(Instr->getType(), VF));
1320 // Create a new entry in the WidenMap and initialize it to Undef or Null.
1321 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
1323 // For each vector unroll 'part':
1324 for (unsigned Part = 0; Part < UF; ++Part) {
1325 // For each scalar that we create:
1326 for (unsigned Width = 0; Width < VF; ++Width) {
1327 Instruction *Cloned = Instr->clone();
1329 Cloned->setName(Instr->getName() + ".cloned");
1330 // Replace the operands of the cloned instrucions with extracted scalars.
1331 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
1332 Value *Op = Params[op][Part];
1333 // Param is a vector. Need to extract the right lane.
1334 if (Op->getType()->isVectorTy())
1335 Op = Builder.CreateExtractElement(Op, Builder.getInt32(Width));
1336 Cloned->setOperand(op, Op);
1339 // Place the cloned scalar in the new loop.
1340 Builder.Insert(Cloned);
1342 // If the original scalar returns a value we need to place it in a vector
1343 // so that future users will be able to use it.
1345 VecResults[Part] = Builder.CreateInsertElement(VecResults[Part], Cloned,
1346 Builder.getInt32(Width));
1352 InnerLoopVectorizer::addRuntimeCheck(LoopVectorizationLegality *Legal,
1354 LoopVectorizationLegality::RuntimePointerCheck *PtrRtCheck =
1355 Legal->getRuntimePointerCheck();
1357 if (!PtrRtCheck->Need)
1360 Instruction *MemoryRuntimeCheck = 0;
1361 unsigned NumPointers = PtrRtCheck->Pointers.size();
1362 SmallVector<Value* , 2> Starts;
1363 SmallVector<Value* , 2> Ends;
1365 SCEVExpander Exp(*SE, "induction");
1367 // Use this type for pointer arithmetic.
1368 Type* PtrArithTy = Type::getInt8PtrTy(Loc->getContext(), 0);
1370 for (unsigned i = 0; i < NumPointers; ++i) {
1371 Value *Ptr = PtrRtCheck->Pointers[i];
1372 const SCEV *Sc = SE->getSCEV(Ptr);
1374 if (SE->isLoopInvariant(Sc, OrigLoop)) {
1375 DEBUG(dbgs() << "LV: Adding RT check for a loop invariant ptr:" <<
1377 Starts.push_back(Ptr);
1378 Ends.push_back(Ptr);
1380 DEBUG(dbgs() << "LV: Adding RT check for range:" << *Ptr <<"\n");
1382 Value *Start = Exp.expandCodeFor(PtrRtCheck->Starts[i], PtrArithTy, Loc);
1383 Value *End = Exp.expandCodeFor(PtrRtCheck->Ends[i], PtrArithTy, Loc);
1384 Starts.push_back(Start);
1385 Ends.push_back(End);
1389 IRBuilder<> ChkBuilder(Loc);
1391 for (unsigned i = 0; i < NumPointers; ++i) {
1392 for (unsigned j = i+1; j < NumPointers; ++j) {
1393 // No need to check if two readonly pointers intersect.
1394 if (!PtrRtCheck->IsWritePtr[i] && !PtrRtCheck->IsWritePtr[j])
1397 Value *Start0 = ChkBuilder.CreateBitCast(Starts[i], PtrArithTy, "bc");
1398 Value *Start1 = ChkBuilder.CreateBitCast(Starts[j], PtrArithTy, "bc");
1399 Value *End0 = ChkBuilder.CreateBitCast(Ends[i], PtrArithTy, "bc");
1400 Value *End1 = ChkBuilder.CreateBitCast(Ends[j], PtrArithTy, "bc");
1402 Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0");
1403 Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1");
1404 Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
1405 if (MemoryRuntimeCheck)
1406 IsConflict = ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict,
1409 MemoryRuntimeCheck = cast<Instruction>(IsConflict);
1413 return MemoryRuntimeCheck;
1417 InnerLoopVectorizer::createEmptyLoop(LoopVectorizationLegality *Legal) {
1419 In this function we generate a new loop. The new loop will contain
1420 the vectorized instructions while the old loop will continue to run the
1423 [ ] <-- vector loop bypass (may consist of multiple blocks).
1426 | [ ] <-- vector pre header.
1430 | [ ]_| <-- vector loop.
1433 >[ ] <--- middle-block.
1436 | [ ] <--- new preheader.
1440 | [ ]_| <-- old scalar loop to handle remainder.
1443 >[ ] <-- exit block.
1447 BasicBlock *OldBasicBlock = OrigLoop->getHeader();
1448 BasicBlock *BypassBlock = OrigLoop->getLoopPreheader();
1449 BasicBlock *ExitBlock = OrigLoop->getExitBlock();
1450 assert(ExitBlock && "Must have an exit block");
1452 // Some loops have a single integer induction variable, while other loops
1453 // don't. One example is c++ iterators that often have multiple pointer
1454 // induction variables. In the code below we also support a case where we
1455 // don't have a single induction variable.
1456 OldInduction = Legal->getInduction();
1457 Type *IdxTy = Legal->getWidestInductionType();
1459 // Find the loop boundaries.
1460 const SCEV *ExitCount = SE->getBackedgeTakenCount(OrigLoop);
1461 assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
1463 // Get the total trip count from the count by adding 1.
1464 ExitCount = SE->getAddExpr(ExitCount,
1465 SE->getConstant(ExitCount->getType(), 1));
1467 // Expand the trip count and place the new instructions in the preheader.
1468 // Notice that the pre-header does not change, only the loop body.
1469 SCEVExpander Exp(*SE, "induction");
1471 // Count holds the overall loop count (N).
1472 Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
1473 BypassBlock->getTerminator());
1475 // The loop index does not have to start at Zero. Find the original start
1476 // value from the induction PHI node. If we don't have an induction variable
1477 // then we know that it starts at zero.
1478 Builder.SetInsertPoint(BypassBlock->getTerminator());
1479 Value *StartIdx = ExtendedIdx = OldInduction ?
1480 Builder.CreateZExt(OldInduction->getIncomingValueForBlock(BypassBlock),
1482 ConstantInt::get(IdxTy, 0);
1484 assert(BypassBlock && "Invalid loop structure");
1485 LoopBypassBlocks.push_back(BypassBlock);
1487 // Split the single block loop into the two loop structure described above.
1488 BasicBlock *VectorPH =
1489 BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
1490 BasicBlock *VecBody =
1491 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
1492 BasicBlock *MiddleBlock =
1493 VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
1494 BasicBlock *ScalarPH =
1495 MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
1497 // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
1499 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
1501 // Generate the induction variable.
1502 Induction = Builder.CreatePHI(IdxTy, 2, "index");
1503 // The loop step is equal to the vectorization factor (num of SIMD elements)
1504 // times the unroll factor (num of SIMD instructions).
1505 Constant *Step = ConstantInt::get(IdxTy, VF * UF);
1507 // This is the IR builder that we use to add all of the logic for bypassing
1508 // the new vector loop.
1509 IRBuilder<> BypassBuilder(BypassBlock->getTerminator());
1511 // We may need to extend the index in case there is a type mismatch.
1512 // We know that the count starts at zero and does not overflow.
1513 if (Count->getType() != IdxTy) {
1514 // The exit count can be of pointer type. Convert it to the correct
1516 if (ExitCount->getType()->isPointerTy())
1517 Count = BypassBuilder.CreatePointerCast(Count, IdxTy, "ptrcnt.to.int");
1519 Count = BypassBuilder.CreateZExtOrTrunc(Count, IdxTy, "cnt.cast");
1522 // Add the start index to the loop count to get the new end index.
1523 Value *IdxEnd = BypassBuilder.CreateAdd(Count, StartIdx, "end.idx");
1525 // Now we need to generate the expression for N - (N % VF), which is
1526 // the part that the vectorized body will execute.
1527 Value *R = BypassBuilder.CreateURem(Count, Step, "n.mod.vf");
1528 Value *CountRoundDown = BypassBuilder.CreateSub(Count, R, "n.vec");
1529 Value *IdxEndRoundDown = BypassBuilder.CreateAdd(CountRoundDown, StartIdx,
1530 "end.idx.rnd.down");
1532 // Now, compare the new count to zero. If it is zero skip the vector loop and
1533 // jump to the scalar loop.
1534 Value *Cmp = BypassBuilder.CreateICmpEQ(IdxEndRoundDown, StartIdx,
1537 BasicBlock *LastBypassBlock = BypassBlock;
1539 // Generate the code that checks in runtime if arrays overlap. We put the
1540 // checks into a separate block to make the more common case of few elements
1542 Instruction *MemRuntimeCheck = addRuntimeCheck(Legal,
1543 BypassBlock->getTerminator());
1544 if (MemRuntimeCheck) {
1545 // Create a new block containing the memory check.
1546 BasicBlock *CheckBlock = BypassBlock->splitBasicBlock(MemRuntimeCheck,
1548 LoopBypassBlocks.push_back(CheckBlock);
1550 // Replace the branch into the memory check block with a conditional branch
1551 // for the "few elements case".
1552 Instruction *OldTerm = BypassBlock->getTerminator();
1553 BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
1554 OldTerm->eraseFromParent();
1556 Cmp = MemRuntimeCheck;
1557 LastBypassBlock = CheckBlock;
1560 LastBypassBlock->getTerminator()->eraseFromParent();
1561 BranchInst::Create(MiddleBlock, VectorPH, Cmp,
1564 // We are going to resume the execution of the scalar loop.
1565 // Go over all of the induction variables that we found and fix the
1566 // PHIs that are left in the scalar version of the loop.
1567 // The starting values of PHI nodes depend on the counter of the last
1568 // iteration in the vectorized loop.
1569 // If we come from a bypass edge then we need to start from the original
1572 // This variable saves the new starting index for the scalar loop.
1573 PHINode *ResumeIndex = 0;
1574 LoopVectorizationLegality::InductionList::iterator I, E;
1575 LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
1576 // Set builder to point to last bypass block.
1577 BypassBuilder.SetInsertPoint(LoopBypassBlocks.back()->getTerminator());
1578 for (I = List->begin(), E = List->end(); I != E; ++I) {
1579 PHINode *OrigPhi = I->first;
1580 LoopVectorizationLegality::InductionInfo II = I->second;
1582 Type *ResumeValTy = (OrigPhi == OldInduction) ? IdxTy : OrigPhi->getType();
1583 PHINode *ResumeVal = PHINode::Create(ResumeValTy, 2, "resume.val",
1584 MiddleBlock->getTerminator());
1585 // We might have extended the type of the induction variable but we need a
1586 // truncated version for the scalar loop.
1587 PHINode *TruncResumeVal = (OrigPhi == OldInduction) ?
1588 PHINode::Create(OrigPhi->getType(), 2, "trunc.resume.val",
1589 MiddleBlock->getTerminator()) : 0;
1591 Value *EndValue = 0;
1593 case LoopVectorizationLegality::IK_NoInduction:
1594 llvm_unreachable("Unknown induction");
1595 case LoopVectorizationLegality::IK_IntInduction: {
1596 // Handle the integer induction counter.
1597 assert(OrigPhi->getType()->isIntegerTy() && "Invalid type");
1599 // We have the canonical induction variable.
1600 if (OrigPhi == OldInduction) {
1601 // Create a truncated version of the resume value for the scalar loop,
1602 // we might have promoted the type to a larger width.
1604 BypassBuilder.CreateTrunc(IdxEndRoundDown, OrigPhi->getType());
1605 // The new PHI merges the original incoming value, in case of a bypass,
1606 // or the value at the end of the vectorized loop.
1607 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
1608 TruncResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
1609 TruncResumeVal->addIncoming(EndValue, VecBody);
1611 // We know what the end value is.
1612 EndValue = IdxEndRoundDown;
1613 // We also know which PHI node holds it.
1614 ResumeIndex = ResumeVal;
1618 // Not the canonical induction variable - add the vector loop count to the
1620 Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown,
1621 II.StartValue->getType(),
1623 EndValue = BypassBuilder.CreateAdd(CRD, II.StartValue , "ind.end");
1626 case LoopVectorizationLegality::IK_ReverseIntInduction: {
1627 // Convert the CountRoundDown variable to the PHI size.
1628 Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown,
1629 II.StartValue->getType(),
1631 // Handle reverse integer induction counter.
1632 EndValue = BypassBuilder.CreateSub(II.StartValue, CRD, "rev.ind.end");
1635 case LoopVectorizationLegality::IK_PtrInduction: {
1636 // For pointer induction variables, calculate the offset using
1638 EndValue = BypassBuilder.CreateGEP(II.StartValue, CountRoundDown,
1642 case LoopVectorizationLegality::IK_ReversePtrInduction: {
1643 // The value at the end of the loop for the reverse pointer is calculated
1644 // by creating a GEP with a negative index starting from the start value.
1645 Value *Zero = ConstantInt::get(CountRoundDown->getType(), 0);
1646 Value *NegIdx = BypassBuilder.CreateSub(Zero, CountRoundDown,
1648 EndValue = BypassBuilder.CreateGEP(II.StartValue, NegIdx,
1654 // The new PHI merges the original incoming value, in case of a bypass,
1655 // or the value at the end of the vectorized loop.
1656 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I) {
1657 if (OrigPhi == OldInduction)
1658 ResumeVal->addIncoming(StartIdx, LoopBypassBlocks[I]);
1660 ResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
1662 ResumeVal->addIncoming(EndValue, VecBody);
1664 // Fix the scalar body counter (PHI node).
1665 unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
1666 // The old inductions phi node in the scalar body needs the truncated value.
1667 if (OrigPhi == OldInduction)
1668 OrigPhi->setIncomingValue(BlockIdx, TruncResumeVal);
1670 OrigPhi->setIncomingValue(BlockIdx, ResumeVal);
1673 // If we are generating a new induction variable then we also need to
1674 // generate the code that calculates the exit value. This value is not
1675 // simply the end of the counter because we may skip the vectorized body
1676 // in case of a runtime check.
1678 assert(!ResumeIndex && "Unexpected resume value found");
1679 ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val",
1680 MiddleBlock->getTerminator());
1681 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
1682 ResumeIndex->addIncoming(StartIdx, LoopBypassBlocks[I]);
1683 ResumeIndex->addIncoming(IdxEndRoundDown, VecBody);
1686 // Make sure that we found the index where scalar loop needs to continue.
1687 assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() &&
1688 "Invalid resume Index");
1690 // Add a check in the middle block to see if we have completed
1691 // all of the iterations in the first vector loop.
1692 // If (N - N%VF) == N, then we *don't* need to run the remainder.
1693 Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd,
1694 ResumeIndex, "cmp.n",
1695 MiddleBlock->getTerminator());
1697 BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
1698 // Remove the old terminator.
1699 MiddleBlock->getTerminator()->eraseFromParent();
1701 // Create i+1 and fill the PHINode.
1702 Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
1703 Induction->addIncoming(StartIdx, VectorPH);
1704 Induction->addIncoming(NextIdx, VecBody);
1705 // Create the compare.
1706 Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown);
1707 Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
1709 // Now we have two terminators. Remove the old one from the block.
1710 VecBody->getTerminator()->eraseFromParent();
1712 // Get ready to start creating new instructions into the vectorized body.
1713 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
1715 // Create and register the new vector loop.
1716 Loop* Lp = new Loop();
1717 Loop *ParentLoop = OrigLoop->getParentLoop();
1719 // Insert the new loop into the loop nest and register the new basic blocks.
1721 ParentLoop->addChildLoop(Lp);
1722 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
1723 ParentLoop->addBasicBlockToLoop(LoopBypassBlocks[I], LI->getBase());
1724 ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase());
1725 ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase());
1726 ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase());
1728 LI->addTopLevelLoop(Lp);
1731 Lp->addBasicBlockToLoop(VecBody, LI->getBase());
1734 LoopVectorPreHeader = VectorPH;
1735 LoopScalarPreHeader = ScalarPH;
1736 LoopMiddleBlock = MiddleBlock;
1737 LoopExitBlock = ExitBlock;
1738 LoopVectorBody = VecBody;
1739 LoopScalarBody = OldBasicBlock;
1742 /// This function returns the identity element (or neutral element) for
1743 /// the operation K.
1745 LoopVectorizationLegality::getReductionIdentity(ReductionKind K, Type *Tp) {
1750 // Adding, Xoring, Oring zero to a number does not change it.
1751 return ConstantInt::get(Tp, 0);
1752 case RK_IntegerMult:
1753 // Multiplying a number by 1 does not change it.
1754 return ConstantInt::get(Tp, 1);
1756 // AND-ing a number with an all-1 value does not change it.
1757 return ConstantInt::get(Tp, -1, true);
1759 // Multiplying a number by 1 does not change it.
1760 return ConstantFP::get(Tp, 1.0L);
1762 // Adding zero to a number does not change it.
1763 return ConstantFP::get(Tp, 0.0L);
1765 llvm_unreachable("Unknown reduction kind");
1769 static Intrinsic::ID
1770 getIntrinsicIDForCall(CallInst *CI, const TargetLibraryInfo *TLI) {
1771 // If we have an intrinsic call, check if it is trivially vectorizable.
1772 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
1773 switch (II->getIntrinsicID()) {
1774 case Intrinsic::sqrt:
1775 case Intrinsic::sin:
1776 case Intrinsic::cos:
1777 case Intrinsic::exp:
1778 case Intrinsic::exp2:
1779 case Intrinsic::log:
1780 case Intrinsic::log10:
1781 case Intrinsic::log2:
1782 case Intrinsic::fabs:
1783 case Intrinsic::floor:
1784 case Intrinsic::ceil:
1785 case Intrinsic::trunc:
1786 case Intrinsic::rint:
1787 case Intrinsic::nearbyint:
1788 case Intrinsic::pow:
1789 case Intrinsic::fma:
1790 case Intrinsic::fmuladd:
1791 return II->getIntrinsicID();
1793 return Intrinsic::not_intrinsic;
1798 return Intrinsic::not_intrinsic;
1801 Function *F = CI->getCalledFunction();
1802 // We're going to make assumptions on the semantics of the functions, check
1803 // that the target knows that it's available in this environment.
1804 if (!F || !TLI->getLibFunc(F->getName(), Func))
1805 return Intrinsic::not_intrinsic;
1807 // Otherwise check if we have a call to a function that can be turned into a
1808 // vector intrinsic.
1815 return Intrinsic::sin;
1819 return Intrinsic::cos;
1823 return Intrinsic::exp;
1825 case LibFunc::exp2f:
1826 case LibFunc::exp2l:
1827 return Intrinsic::exp2;
1831 return Intrinsic::log;
1832 case LibFunc::log10:
1833 case LibFunc::log10f:
1834 case LibFunc::log10l:
1835 return Intrinsic::log10;
1837 case LibFunc::log2f:
1838 case LibFunc::log2l:
1839 return Intrinsic::log2;
1841 case LibFunc::fabsf:
1842 case LibFunc::fabsl:
1843 return Intrinsic::fabs;
1844 case LibFunc::floor:
1845 case LibFunc::floorf:
1846 case LibFunc::floorl:
1847 return Intrinsic::floor;
1849 case LibFunc::ceilf:
1850 case LibFunc::ceill:
1851 return Intrinsic::ceil;
1852 case LibFunc::trunc:
1853 case LibFunc::truncf:
1854 case LibFunc::truncl:
1855 return Intrinsic::trunc;
1857 case LibFunc::rintf:
1858 case LibFunc::rintl:
1859 return Intrinsic::rint;
1860 case LibFunc::nearbyint:
1861 case LibFunc::nearbyintf:
1862 case LibFunc::nearbyintl:
1863 return Intrinsic::nearbyint;
1867 return Intrinsic::pow;
1870 return Intrinsic::not_intrinsic;
1873 /// This function translates the reduction kind to an LLVM binary operator.
1875 getReductionBinOp(LoopVectorizationLegality::ReductionKind Kind) {
1877 case LoopVectorizationLegality::RK_IntegerAdd:
1878 return Instruction::Add;
1879 case LoopVectorizationLegality::RK_IntegerMult:
1880 return Instruction::Mul;
1881 case LoopVectorizationLegality::RK_IntegerOr:
1882 return Instruction::Or;
1883 case LoopVectorizationLegality::RK_IntegerAnd:
1884 return Instruction::And;
1885 case LoopVectorizationLegality::RK_IntegerXor:
1886 return Instruction::Xor;
1887 case LoopVectorizationLegality::RK_FloatMult:
1888 return Instruction::FMul;
1889 case LoopVectorizationLegality::RK_FloatAdd:
1890 return Instruction::FAdd;
1891 case LoopVectorizationLegality::RK_IntegerMinMax:
1892 return Instruction::ICmp;
1893 case LoopVectorizationLegality::RK_FloatMinMax:
1894 return Instruction::FCmp;
1896 llvm_unreachable("Unknown reduction operation");
1900 Value *createMinMaxOp(IRBuilder<> &Builder,
1901 LoopVectorizationLegality::MinMaxReductionKind RK,
1904 CmpInst::Predicate P = CmpInst::ICMP_NE;
1907 llvm_unreachable("Unknown min/max reduction kind");
1908 case LoopVectorizationLegality::MRK_UIntMin:
1909 P = CmpInst::ICMP_ULT;
1911 case LoopVectorizationLegality::MRK_UIntMax:
1912 P = CmpInst::ICMP_UGT;
1914 case LoopVectorizationLegality::MRK_SIntMin:
1915 P = CmpInst::ICMP_SLT;
1917 case LoopVectorizationLegality::MRK_SIntMax:
1918 P = CmpInst::ICMP_SGT;
1920 case LoopVectorizationLegality::MRK_FloatMin:
1921 P = CmpInst::FCMP_OLT;
1923 case LoopVectorizationLegality::MRK_FloatMax:
1924 P = CmpInst::FCMP_OGT;
1929 if (RK == LoopVectorizationLegality::MRK_FloatMin || RK == LoopVectorizationLegality::MRK_FloatMax)
1930 Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp");
1932 Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp");
1934 Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
1939 InnerLoopVectorizer::vectorizeLoop(LoopVectorizationLegality *Legal) {
1940 //===------------------------------------------------===//
1942 // Notice: any optimization or new instruction that go
1943 // into the code below should be also be implemented in
1946 //===------------------------------------------------===//
1947 Constant *Zero = Builder.getInt32(0);
1949 // In order to support reduction variables we need to be able to vectorize
1950 // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
1951 // stages. First, we create a new vector PHI node with no incoming edges.
1952 // We use this value when we vectorize all of the instructions that use the
1953 // PHI. Next, after all of the instructions in the block are complete we
1954 // add the new incoming edges to the PHI. At this point all of the
1955 // instructions in the basic block are vectorized, so we can use them to
1956 // construct the PHI.
1957 PhiVector RdxPHIsToFix;
1959 // Scan the loop in a topological order to ensure that defs are vectorized
1961 LoopBlocksDFS DFS(OrigLoop);
1964 // Vectorize all of the blocks in the original loop.
1965 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
1966 be = DFS.endRPO(); bb != be; ++bb)
1967 vectorizeBlockInLoop(Legal, *bb, &RdxPHIsToFix);
1969 // At this point every instruction in the original loop is widened to
1970 // a vector form. We are almost done. Now, we need to fix the PHI nodes
1971 // that we vectorized. The PHI nodes are currently empty because we did
1972 // not want to introduce cycles. Notice that the remaining PHI nodes
1973 // that we need to fix are reduction variables.
1975 // Create the 'reduced' values for each of the induction vars.
1976 // The reduced values are the vector values that we scalarize and combine
1977 // after the loop is finished.
1978 for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
1980 PHINode *RdxPhi = *it;
1981 assert(RdxPhi && "Unable to recover vectorized PHI");
1983 // Find the reduction variable descriptor.
1984 assert(Legal->getReductionVars()->count(RdxPhi) &&
1985 "Unable to find the reduction variable");
1986 LoopVectorizationLegality::ReductionDescriptor RdxDesc =
1987 (*Legal->getReductionVars())[RdxPhi];
1989 // We need to generate a reduction vector from the incoming scalar.
1990 // To do so, we need to generate the 'identity' vector and overide
1991 // one of the elements with the incoming scalar reduction. We need
1992 // to do it in the vector-loop preheader.
1993 Builder.SetInsertPoint(LoopBypassBlocks.front()->getTerminator());
1995 // This is the vector-clone of the value that leaves the loop.
1996 VectorParts &VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
1997 Type *VecTy = VectorExit[0]->getType();
1999 // Find the reduction identity variable. Zero for addition, or, xor,
2000 // one for multiplication, -1 for And.
2003 if (RdxDesc.Kind == LoopVectorizationLegality::RK_IntegerMinMax ||
2004 RdxDesc.Kind == LoopVectorizationLegality::RK_FloatMinMax) {
2005 // MinMax reduction have the start value as their identify.
2006 VectorStart = Identity = Builder.CreateVectorSplat(VF, RdxDesc.StartValue,
2010 LoopVectorizationLegality::getReductionIdentity(RdxDesc.Kind,
2011 VecTy->getScalarType());
2012 Identity = ConstantVector::getSplat(VF, Iden);
2014 // This vector is the Identity vector where the first element is the
2015 // incoming scalar reduction.
2016 VectorStart = Builder.CreateInsertElement(Identity,
2017 RdxDesc.StartValue, Zero);
2020 // Fix the vector-loop phi.
2021 // We created the induction variable so we know that the
2022 // preheader is the first entry.
2023 BasicBlock *VecPreheader = Induction->getIncomingBlock(0);
2025 // Reductions do not have to start at zero. They can start with
2026 // any loop invariant values.
2027 VectorParts &VecRdxPhi = WidenMap.get(RdxPhi);
2028 BasicBlock *Latch = OrigLoop->getLoopLatch();
2029 Value *LoopVal = RdxPhi->getIncomingValueForBlock(Latch);
2030 VectorParts &Val = getVectorValue(LoopVal);
2031 for (unsigned part = 0; part < UF; ++part) {
2032 // Make sure to add the reduction stat value only to the
2033 // first unroll part.
2034 Value *StartVal = (part == 0) ? VectorStart : Identity;
2035 cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal, VecPreheader);
2036 cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part], LoopVectorBody);
2039 // Before each round, move the insertion point right between
2040 // the PHIs and the values we are going to write.
2041 // This allows us to write both PHINodes and the extractelement
2043 Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
2045 VectorParts RdxParts;
2046 for (unsigned part = 0; part < UF; ++part) {
2047 // This PHINode contains the vectorized reduction variable, or
2048 // the initial value vector, if we bypass the vector loop.
2049 VectorParts &RdxExitVal = getVectorValue(RdxDesc.LoopExitInstr);
2050 PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
2051 Value *StartVal = (part == 0) ? VectorStart : Identity;
2052 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
2053 NewPhi->addIncoming(StartVal, LoopBypassBlocks[I]);
2054 NewPhi->addIncoming(RdxExitVal[part], LoopVectorBody);
2055 RdxParts.push_back(NewPhi);
2058 // Reduce all of the unrolled parts into a single vector.
2059 Value *ReducedPartRdx = RdxParts[0];
2060 unsigned Op = getReductionBinOp(RdxDesc.Kind);
2061 for (unsigned part = 1; part < UF; ++part) {
2062 if (Op != Instruction::ICmp && Op != Instruction::FCmp)
2063 ReducedPartRdx = Builder.CreateBinOp((Instruction::BinaryOps)Op,
2064 RdxParts[part], ReducedPartRdx,
2067 ReducedPartRdx = createMinMaxOp(Builder, RdxDesc.MinMaxKind,
2068 ReducedPartRdx, RdxParts[part]);
2071 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
2072 // and vector ops, reducing the set of values being computed by half each
2074 assert(isPowerOf2_32(VF) &&
2075 "Reduction emission only supported for pow2 vectors!");
2076 Value *TmpVec = ReducedPartRdx;
2077 SmallVector<Constant*, 32> ShuffleMask(VF, 0);
2078 for (unsigned i = VF; i != 1; i >>= 1) {
2079 // Move the upper half of the vector to the lower half.
2080 for (unsigned j = 0; j != i/2; ++j)
2081 ShuffleMask[j] = Builder.getInt32(i/2 + j);
2083 // Fill the rest of the mask with undef.
2084 std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
2085 UndefValue::get(Builder.getInt32Ty()));
2088 Builder.CreateShuffleVector(TmpVec,
2089 UndefValue::get(TmpVec->getType()),
2090 ConstantVector::get(ShuffleMask),
2093 if (Op != Instruction::ICmp && Op != Instruction::FCmp)
2094 TmpVec = Builder.CreateBinOp((Instruction::BinaryOps)Op, TmpVec, Shuf,
2097 TmpVec = createMinMaxOp(Builder, RdxDesc.MinMaxKind, TmpVec, Shuf);
2100 // The result is in the first element of the vector.
2101 Value *Scalar0 = Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
2103 // Now, we need to fix the users of the reduction variable
2104 // inside and outside of the scalar remainder loop.
2105 // We know that the loop is in LCSSA form. We need to update the
2106 // PHI nodes in the exit blocks.
2107 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
2108 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
2109 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
2110 if (!LCSSAPhi) continue;
2112 // All PHINodes need to have a single entry edge, or two if
2113 // we already fixed them.
2114 assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
2116 // We found our reduction value exit-PHI. Update it with the
2117 // incoming bypass edge.
2118 if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
2119 // Add an edge coming from the bypass.
2120 LCSSAPhi->addIncoming(Scalar0, LoopMiddleBlock);
2123 }// end of the LCSSA phi scan.
2125 // Fix the scalar loop reduction variable with the incoming reduction sum
2126 // from the vector body and from the backedge value.
2127 int IncomingEdgeBlockIdx =
2128 (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
2129 assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
2130 // Pick the other block.
2131 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
2132 (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, Scalar0);
2133 (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
2134 }// end of for each redux variable.
2136 // The Loop exit block may have single value PHI nodes where the incoming
2137 // value is 'undef'. While vectorizing we only handled real values that
2138 // were defined inside the loop. Here we handle the 'undef case'.
2140 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
2141 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
2142 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
2143 if (!LCSSAPhi) continue;
2144 if (LCSSAPhi->getNumIncomingValues() == 1)
2145 LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
2150 InnerLoopVectorizer::VectorParts
2151 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
2152 assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
2155 VectorParts SrcMask = createBlockInMask(Src);
2157 // The terminator has to be a branch inst!
2158 BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
2159 assert(BI && "Unexpected terminator found");
2161 if (BI->isConditional()) {
2162 VectorParts EdgeMask = getVectorValue(BI->getCondition());
2164 if (BI->getSuccessor(0) != Dst)
2165 for (unsigned part = 0; part < UF; ++part)
2166 EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
2168 for (unsigned part = 0; part < UF; ++part)
2169 EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
2176 InnerLoopVectorizer::VectorParts
2177 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
2178 assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
2180 // Loop incoming mask is all-one.
2181 if (OrigLoop->getHeader() == BB) {
2182 Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
2183 return getVectorValue(C);
2186 // This is the block mask. We OR all incoming edges, and with zero.
2187 Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
2188 VectorParts BlockMask = getVectorValue(Zero);
2191 for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
2192 VectorParts EM = createEdgeMask(*it, BB);
2193 for (unsigned part = 0; part < UF; ++part)
2194 BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
2201 InnerLoopVectorizer::vectorizeBlockInLoop(LoopVectorizationLegality *Legal,
2202 BasicBlock *BB, PhiVector *PV) {
2203 // For each instruction in the old loop.
2204 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2205 VectorParts &Entry = WidenMap.get(it);
2206 switch (it->getOpcode()) {
2207 case Instruction::Br:
2208 // Nothing to do for PHIs and BR, since we already took care of the
2209 // loop control flow instructions.
2211 case Instruction::PHI:{
2212 PHINode* P = cast<PHINode>(it);
2213 // Handle reduction variables:
2214 if (Legal->getReductionVars()->count(P)) {
2215 for (unsigned part = 0; part < UF; ++part) {
2216 // This is phase one of vectorizing PHIs.
2217 Type *VecTy = VectorType::get(it->getType(), VF);
2218 Entry[part] = PHINode::Create(VecTy, 2, "vec.phi",
2219 LoopVectorBody-> getFirstInsertionPt());
2225 // Check for PHI nodes that are lowered to vector selects.
2226 if (P->getParent() != OrigLoop->getHeader()) {
2227 // We know that all PHIs in non header blocks are converted into
2228 // selects, so we don't have to worry about the insertion order and we
2229 // can just use the builder.
2230 // At this point we generate the predication tree. There may be
2231 // duplications since this is a simple recursive scan, but future
2232 // optimizations will clean it up.
2234 unsigned NumIncoming = P->getNumIncomingValues();
2236 // Generate a sequence of selects of the form:
2237 // SELECT(Mask3, In3,
2238 // SELECT(Mask2, In2,
2240 for (unsigned In = 0; In < NumIncoming; In++) {
2241 VectorParts Cond = createEdgeMask(P->getIncomingBlock(In),
2243 VectorParts &In0 = getVectorValue(P->getIncomingValue(In));
2245 for (unsigned part = 0; part < UF; ++part) {
2246 // We might have single edge PHIs (blocks) - use an identity
2247 // 'select' for the first PHI operand.
2249 Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
2252 // Select between the current value and the previous incoming edge
2253 // based on the incoming mask.
2254 Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
2255 Entry[part], "predphi");
2261 // This PHINode must be an induction variable.
2262 // Make sure that we know about it.
2263 assert(Legal->getInductionVars()->count(P) &&
2264 "Not an induction variable");
2266 LoopVectorizationLegality::InductionInfo II =
2267 Legal->getInductionVars()->lookup(P);
2270 case LoopVectorizationLegality::IK_NoInduction:
2271 llvm_unreachable("Unknown induction");
2272 case LoopVectorizationLegality::IK_IntInduction: {
2273 assert(P->getType() == II.StartValue->getType() && "Types must match");
2274 Type *PhiTy = P->getType();
2276 if (P == OldInduction) {
2277 // Handle the canonical induction variable. We might have had to
2279 Broadcasted = Builder.CreateTrunc(Induction, PhiTy);
2281 // Handle other induction variables that are now based on the
2283 Value *NormalizedIdx = Builder.CreateSub(Induction, ExtendedIdx,
2285 NormalizedIdx = Builder.CreateSExtOrTrunc(NormalizedIdx, PhiTy);
2286 Broadcasted = Builder.CreateAdd(II.StartValue, NormalizedIdx,
2289 Broadcasted = getBroadcastInstrs(Broadcasted);
2290 // After broadcasting the induction variable we need to make the vector
2291 // consecutive by adding 0, 1, 2, etc.
2292 for (unsigned part = 0; part < UF; ++part)
2293 Entry[part] = getConsecutiveVector(Broadcasted, VF * part, false);
2296 case LoopVectorizationLegality::IK_ReverseIntInduction:
2297 case LoopVectorizationLegality::IK_PtrInduction:
2298 case LoopVectorizationLegality::IK_ReversePtrInduction:
2299 // Handle reverse integer and pointer inductions.
2300 Value *StartIdx = ExtendedIdx;
2301 // This is the normalized GEP that starts counting at zero.
2302 Value *NormalizedIdx = Builder.CreateSub(Induction, StartIdx,
2305 // Handle the reverse integer induction variable case.
2306 if (LoopVectorizationLegality::IK_ReverseIntInduction == II.IK) {
2307 IntegerType *DstTy = cast<IntegerType>(II.StartValue->getType());
2308 Value *CNI = Builder.CreateSExtOrTrunc(NormalizedIdx, DstTy,
2310 Value *ReverseInd = Builder.CreateSub(II.StartValue, CNI,
2313 // This is a new value so do not hoist it out.
2314 Value *Broadcasted = getBroadcastInstrs(ReverseInd);
2315 // After broadcasting the induction variable we need to make the
2316 // vector consecutive by adding ... -3, -2, -1, 0.
2317 for (unsigned part = 0; part < UF; ++part)
2318 Entry[part] = getConsecutiveVector(Broadcasted, -(int)VF * part,
2323 // Handle the pointer induction variable case.
2324 assert(P->getType()->isPointerTy() && "Unexpected type.");
2326 // Is this a reverse induction ptr or a consecutive induction ptr.
2327 bool Reverse = (LoopVectorizationLegality::IK_ReversePtrInduction ==
2330 // This is the vector of results. Notice that we don't generate
2331 // vector geps because scalar geps result in better code.
2332 for (unsigned part = 0; part < UF; ++part) {
2333 Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
2334 for (unsigned int i = 0; i < VF; ++i) {
2335 int EltIndex = (i + part * VF) * (Reverse ? -1 : 1);
2336 Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex);
2339 GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx, "gep.idx");
2341 GlobalIdx = Builder.CreateSub(Idx, NormalizedIdx, "gep.ridx");
2343 Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
2345 VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
2346 Builder.getInt32(i),
2349 Entry[part] = VecVal;
2356 case Instruction::Add:
2357 case Instruction::FAdd:
2358 case Instruction::Sub:
2359 case Instruction::FSub:
2360 case Instruction::Mul:
2361 case Instruction::FMul:
2362 case Instruction::UDiv:
2363 case Instruction::SDiv:
2364 case Instruction::FDiv:
2365 case Instruction::URem:
2366 case Instruction::SRem:
2367 case Instruction::FRem:
2368 case Instruction::Shl:
2369 case Instruction::LShr:
2370 case Instruction::AShr:
2371 case Instruction::And:
2372 case Instruction::Or:
2373 case Instruction::Xor: {
2374 // Just widen binops.
2375 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
2376 VectorParts &A = getVectorValue(it->getOperand(0));
2377 VectorParts &B = getVectorValue(it->getOperand(1));
2379 // Use this vector value for all users of the original instruction.
2380 for (unsigned Part = 0; Part < UF; ++Part) {
2381 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
2383 // Update the NSW, NUW and Exact flags. Notice: V can be an Undef.
2384 BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V);
2385 if (VecOp && isa<OverflowingBinaryOperator>(BinOp)) {
2386 VecOp->setHasNoSignedWrap(BinOp->hasNoSignedWrap());
2387 VecOp->setHasNoUnsignedWrap(BinOp->hasNoUnsignedWrap());
2389 if (VecOp && isa<PossiblyExactOperator>(VecOp))
2390 VecOp->setIsExact(BinOp->isExact());
2396 case Instruction::Select: {
2398 // If the selector is loop invariant we can create a select
2399 // instruction with a scalar condition. Otherwise, use vector-select.
2400 bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)),
2403 // The condition can be loop invariant but still defined inside the
2404 // loop. This means that we can't just use the original 'cond' value.
2405 // We have to take the 'vectorized' value and pick the first lane.
2406 // Instcombine will make this a no-op.
2407 VectorParts &Cond = getVectorValue(it->getOperand(0));
2408 VectorParts &Op0 = getVectorValue(it->getOperand(1));
2409 VectorParts &Op1 = getVectorValue(it->getOperand(2));
2410 Value *ScalarCond = Builder.CreateExtractElement(Cond[0],
2411 Builder.getInt32(0));
2412 for (unsigned Part = 0; Part < UF; ++Part) {
2413 Entry[Part] = Builder.CreateSelect(
2414 InvariantCond ? ScalarCond : Cond[Part],
2421 case Instruction::ICmp:
2422 case Instruction::FCmp: {
2423 // Widen compares. Generate vector compares.
2424 bool FCmp = (it->getOpcode() == Instruction::FCmp);
2425 CmpInst *Cmp = dyn_cast<CmpInst>(it);
2426 VectorParts &A = getVectorValue(it->getOperand(0));
2427 VectorParts &B = getVectorValue(it->getOperand(1));
2428 for (unsigned Part = 0; Part < UF; ++Part) {
2431 C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
2433 C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
2439 case Instruction::Store:
2440 case Instruction::Load:
2441 vectorizeMemoryInstruction(it, Legal);
2443 case Instruction::ZExt:
2444 case Instruction::SExt:
2445 case Instruction::FPToUI:
2446 case Instruction::FPToSI:
2447 case Instruction::FPExt:
2448 case Instruction::PtrToInt:
2449 case Instruction::IntToPtr:
2450 case Instruction::SIToFP:
2451 case Instruction::UIToFP:
2452 case Instruction::Trunc:
2453 case Instruction::FPTrunc:
2454 case Instruction::BitCast: {
2455 CastInst *CI = dyn_cast<CastInst>(it);
2456 /// Optimize the special case where the source is the induction
2457 /// variable. Notice that we can only optimize the 'trunc' case
2458 /// because: a. FP conversions lose precision, b. sext/zext may wrap,
2459 /// c. other casts depend on pointer size.
2460 if (CI->getOperand(0) == OldInduction &&
2461 it->getOpcode() == Instruction::Trunc) {
2462 Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
2464 Value *Broadcasted = getBroadcastInstrs(ScalarCast);
2465 for (unsigned Part = 0; Part < UF; ++Part)
2466 Entry[Part] = getConsecutiveVector(Broadcasted, VF * Part, false);
2469 /// Vectorize casts.
2470 Type *DestTy = VectorType::get(CI->getType()->getScalarType(), VF);
2472 VectorParts &A = getVectorValue(it->getOperand(0));
2473 for (unsigned Part = 0; Part < UF; ++Part)
2474 Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
2478 case Instruction::Call: {
2479 // Ignore dbg intrinsics.
2480 if (isa<DbgInfoIntrinsic>(it))
2483 Module *M = BB->getParent()->getParent();
2484 CallInst *CI = cast<CallInst>(it);
2485 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
2486 assert(ID && "Not an intrinsic call!");
2487 for (unsigned Part = 0; Part < UF; ++Part) {
2488 SmallVector<Value*, 4> Args;
2489 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
2490 VectorParts &Arg = getVectorValue(CI->getArgOperand(i));
2491 Args.push_back(Arg[Part]);
2493 Type *Tys[] = { VectorType::get(CI->getType()->getScalarType(), VF) };
2494 Function *F = Intrinsic::getDeclaration(M, ID, Tys);
2495 Entry[Part] = Builder.CreateCall(F, Args);
2501 // All other instructions are unsupported. Scalarize them.
2502 scalarizeInstruction(it);
2505 }// end of for_each instr.
2508 void InnerLoopVectorizer::updateAnalysis() {
2509 // Forget the original basic block.
2510 SE->forgetLoop(OrigLoop);
2512 // Update the dominator tree information.
2513 assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&
2514 "Entry does not dominate exit.");
2516 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
2517 DT->addNewBlock(LoopBypassBlocks[I], LoopBypassBlocks[I-1]);
2518 DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlocks.back());
2519 DT->addNewBlock(LoopVectorBody, LoopVectorPreHeader);
2520 DT->addNewBlock(LoopMiddleBlock, LoopBypassBlocks.front());
2521 DT->addNewBlock(LoopScalarPreHeader, LoopMiddleBlock);
2522 DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
2523 DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
2525 DEBUG(DT->verifyAnalysis());
2528 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
2529 if (!EnableIfConversion)
2532 assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
2533 std::vector<BasicBlock*> &LoopBlocks = TheLoop->getBlocksVector();
2535 // Collect the blocks that need predication.
2536 for (unsigned i = 0, e = LoopBlocks.size(); i < e; ++i) {
2537 BasicBlock *BB = LoopBlocks[i];
2539 // We don't support switch statements inside loops.
2540 if (!isa<BranchInst>(BB->getTerminator()))
2543 // We must be able to predicate all blocks that need to be predicated.
2544 if (blockNeedsPredication(BB) && !blockCanBePredicated(BB))
2548 // Check that we can actually speculate the hoistable loads.
2549 if (!LoadSpeculation.canHoistAllLoads())
2552 // We can if-convert this loop.
2556 bool LoopVectorizationLegality::canVectorize() {
2557 // We must have a loop in canonical form. Loops with indirectbr in them cannot
2558 // be canonicalized.
2559 if (!TheLoop->getLoopPreheader())
2562 // We can only vectorize innermost loops.
2563 if (TheLoop->getSubLoopsVector().size())
2566 // We must have a single backedge.
2567 if (TheLoop->getNumBackEdges() != 1)
2570 // We must have a single exiting block.
2571 if (!TheLoop->getExitingBlock())
2574 unsigned NumBlocks = TheLoop->getNumBlocks();
2576 // Check if we can if-convert non single-bb loops.
2577 if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
2578 DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
2582 // We need to have a loop header.
2583 BasicBlock *Latch = TheLoop->getLoopLatch();
2584 DEBUG(dbgs() << "LV: Found a loop: " <<
2585 TheLoop->getHeader()->getName() << "\n");
2587 // ScalarEvolution needs to be able to find the exit count.
2588 const SCEV *ExitCount = SE->getBackedgeTakenCount(TheLoop);
2589 if (ExitCount == SE->getCouldNotCompute()) {
2590 DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
2594 // Do not loop-vectorize loops with a tiny trip count.
2595 unsigned TC = SE->getSmallConstantTripCount(TheLoop, Latch);
2596 if (TC > 0u && TC < TinyTripCountVectorThreshold) {
2597 DEBUG(dbgs() << "LV: Found a loop with a very small trip count. " <<
2598 "This loop is not worth vectorizing.\n");
2602 // Check if we can vectorize the instructions and CFG in this loop.
2603 if (!canVectorizeInstrs()) {
2604 DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
2608 // Go over each instruction and look at memory deps.
2609 if (!canVectorizeMemory()) {
2610 DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
2614 // Collect all of the variables that remain uniform after vectorization.
2615 collectLoopUniforms();
2617 DEBUG(dbgs() << "LV: We can vectorize this loop" <<
2618 (PtrRtCheck.Need ? " (with a runtime bound check)" : "")
2621 // Okay! We can vectorize. At this point we don't have any other mem analysis
2622 // which may limit our maximum vectorization factor, so just return true with
2627 static Type *convertPointerToIntegerType(DataLayout &DL, Type *Ty) {
2628 if (Ty->isPointerTy())
2629 return DL.getIntPtrType(Ty->getContext());
2633 static Type* getWiderType(DataLayout &DL, Type *Ty0, Type *Ty1) {
2634 Ty0 = convertPointerToIntegerType(DL, Ty0);
2635 Ty1 = convertPointerToIntegerType(DL, Ty1);
2636 if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits())
2641 /// \brief Check that the instruction has outside loop users and is not an
2642 /// identified reduction variable.
2643 static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst,
2644 SmallPtrSet<Value *, 4> &Reductions) {
2645 // Reduction instructions are allowed to have exit users. All other
2646 // instructions must not have external users.
2647 if (!Reductions.count(Inst))
2648 //Check that all of the users of the loop are inside the BB.
2649 for (Value::use_iterator I = Inst->use_begin(), E = Inst->use_end();
2651 Instruction *U = cast<Instruction>(*I);
2652 // This user may be a reduction exit value.
2653 if (!TheLoop->contains(U)) {
2654 DEBUG(dbgs() << "LV: Found an outside user for : "<< *U << "\n");
2661 bool LoopVectorizationLegality::canVectorizeInstrs() {
2662 BasicBlock *PreHeader = TheLoop->getLoopPreheader();
2663 BasicBlock *Header = TheLoop->getHeader();
2665 // Look for the attribute signaling the absence of NaNs.
2666 Function &F = *Header->getParent();
2667 if (F.hasFnAttribute("no-nans-fp-math"))
2668 HasFunNoNaNAttr = F.getAttributes().getAttribute(
2669 AttributeSet::FunctionIndex,
2670 "no-nans-fp-math").getValueAsString() == "true";
2672 // For each block in the loop.
2673 for (Loop::block_iterator bb = TheLoop->block_begin(),
2674 be = TheLoop->block_end(); bb != be; ++bb) {
2676 // Scan the instructions in the block and look for hazards.
2677 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
2680 if (PHINode *Phi = dyn_cast<PHINode>(it)) {
2681 Type *PhiTy = Phi->getType();
2682 // Check that this PHI type is allowed.
2683 if (!PhiTy->isIntegerTy() &&
2684 !PhiTy->isFloatingPointTy() &&
2685 !PhiTy->isPointerTy()) {
2686 DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
2690 // If this PHINode is not in the header block, then we know that we
2691 // can convert it to select during if-conversion. No need to check if
2692 // the PHIs in this block are induction or reduction variables.
2693 if (*bb != Header) {
2694 // Check that this instruction has no outside users or is an
2695 // identified reduction value with an outside user.
2696 if(!hasOutsideLoopUser(TheLoop, it, AllowedExit))
2701 // We only allow if-converted PHIs with more than two incoming values.
2702 if (Phi->getNumIncomingValues() != 2) {
2703 DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
2707 // This is the value coming from the preheader.
2708 Value *StartValue = Phi->getIncomingValueForBlock(PreHeader);
2709 // Check if this is an induction variable.
2710 InductionKind IK = isInductionVariable(Phi);
2712 if (IK_NoInduction != IK) {
2713 // Get the widest type.
2715 WidestIndTy = convertPointerToIntegerType(*DL, PhiTy);
2717 WidestIndTy = getWiderType(*DL, PhiTy, WidestIndTy);
2719 // Int inductions are special because we only allow one IV.
2720 if (IK == IK_IntInduction) {
2721 // Use the phi node with the widest type as induction. Use the last
2722 // one if there are multiple (no good reason for doing this other
2723 // than it is expedient).
2724 if (!Induction || PhiTy == WidestIndTy)
2728 DEBUG(dbgs() << "LV: Found an induction variable.\n");
2729 Inductions[Phi] = InductionInfo(StartValue, IK);
2733 if (AddReductionVar(Phi, RK_IntegerAdd)) {
2734 DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
2737 if (AddReductionVar(Phi, RK_IntegerMult)) {
2738 DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n");
2741 if (AddReductionVar(Phi, RK_IntegerOr)) {
2742 DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n");
2745 if (AddReductionVar(Phi, RK_IntegerAnd)) {
2746 DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n");
2749 if (AddReductionVar(Phi, RK_IntegerXor)) {
2750 DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n");
2753 if (AddReductionVar(Phi, RK_IntegerMinMax)) {
2754 DEBUG(dbgs() << "LV: Found a MINMAX reduction PHI."<< *Phi <<"\n");
2757 if (AddReductionVar(Phi, RK_FloatMult)) {
2758 DEBUG(dbgs() << "LV: Found an FMult reduction PHI."<< *Phi <<"\n");
2761 if (AddReductionVar(Phi, RK_FloatAdd)) {
2762 DEBUG(dbgs() << "LV: Found an FAdd reduction PHI."<< *Phi <<"\n");
2765 if (AddReductionVar(Phi, RK_FloatMinMax)) {
2766 DEBUG(dbgs() << "LV: Found an float MINMAX reduction PHI."<< *Phi <<"\n");
2770 DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
2772 }// end of PHI handling
2774 // We still don't handle functions. However, we can ignore dbg intrinsic
2775 // calls and we do handle certain intrinsic and libm functions.
2776 CallInst *CI = dyn_cast<CallInst>(it);
2777 if (CI && !getIntrinsicIDForCall(CI, TLI) && !isa<DbgInfoIntrinsic>(CI)) {
2778 DEBUG(dbgs() << "LV: Found a call site.\n");
2782 // Check that the instruction return type is vectorizable.
2783 if (!VectorType::isValidElementType(it->getType()) &&
2784 !it->getType()->isVoidTy()) {
2785 DEBUG(dbgs() << "LV: Found unvectorizable type." << "\n");
2789 // Check that the stored type is vectorizable.
2790 if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
2791 Type *T = ST->getValueOperand()->getType();
2792 if (!VectorType::isValidElementType(T))
2796 // Reduction instructions are allowed to have exit users.
2797 // All other instructions must not have external users.
2798 if (hasOutsideLoopUser(TheLoop, it, AllowedExit))
2806 DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
2807 if (Inductions.empty())
2814 void LoopVectorizationLegality::collectLoopUniforms() {
2815 // We now know that the loop is vectorizable!
2816 // Collect variables that will remain uniform after vectorization.
2817 std::vector<Value*> Worklist;
2818 BasicBlock *Latch = TheLoop->getLoopLatch();
2820 // Start with the conditional branch and walk up the block.
2821 Worklist.push_back(Latch->getTerminator()->getOperand(0));
2823 while (Worklist.size()) {
2824 Instruction *I = dyn_cast<Instruction>(Worklist.back());
2825 Worklist.pop_back();
2827 // Look at instructions inside this loop.
2828 // Stop when reaching PHI nodes.
2829 // TODO: we need to follow values all over the loop, not only in this block.
2830 if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
2833 // This is a known uniform.
2836 // Insert all operands.
2837 Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
2841 /// \brief Analyses memory accesses in a loop.
2843 /// Checks whether run time pointer checks are needed and builds sets for data
2844 /// dependence checking.
2845 class AccessAnalysis {
2847 /// \brief Read or write access location.
2848 typedef std::pair<Value*, char> MemAccessInfo;
2850 /// \brief Set of potential dependent memory accesses.
2851 typedef EquivalenceClasses<MemAccessInfo> DepCandidates;
2853 AccessAnalysis(DataLayout *Dl, DepCandidates &DA) :
2854 DL(Dl), DepCands(DA), AreAllWritesIdentified(true),
2855 AreAllReadsIdentified(true), IsRTCheckNeeded(false) {}
2857 /// \brief Register a load and whether it is only read from.
2858 void addLoad(Value *Ptr, bool IsReadOnly) {
2859 Accesses.insert(std::make_pair(Ptr, false));
2861 ReadOnlyPtr.insert(Ptr);
2864 /// \brief Register a store.
2865 void addStore(Value *Ptr) {
2866 Accesses.insert(std::make_pair(Ptr, true));
2869 /// \brief Check whether we can check the pointers at runtime for
2870 /// non-intersection.
2871 bool canCheckPtrAtRT(LoopVectorizationLegality::RuntimePointerCheck &RtCheck,
2872 unsigned &NumComparisons, ScalarEvolution *SE,
2875 /// \brief Goes over all memory accesses, checks whether a RT check is needed
2876 /// and builds sets of dependent accesses.
2877 void buildDependenceSets() {
2878 // Process read-write pointers first.
2879 processMemAccesses(false);
2880 // Next, process read pointers.
2881 processMemAccesses(true);
2884 bool isRTCheckNeeded() { return IsRTCheckNeeded; }
2886 bool isDependencyCheckNeeded() { return !CheckDeps.empty(); }
2888 DenseSet<MemAccessInfo> &getDependenciesToCheck() { return CheckDeps; }
2891 typedef DenseSet<MemAccessInfo> PtrAccessSet;
2892 typedef DenseMap<Value*, MemAccessInfo> UnderlyingObjToAccessMap;
2894 /// \brief Go over all memory access or only the deferred ones if
2895 /// \p UseDeferred is true and check whether runtime pointer checks are needed
2896 /// and build sets of dependency check candidates.
2897 void processMemAccesses(bool UseDeferred);
2899 /// Set of all accesses.
2900 PtrAccessSet Accesses;
2902 /// Set of access to check after all writes have been processed.
2903 PtrAccessSet DeferredAccesses;
2905 /// Map of pointers to last access encountered.
2906 UnderlyingObjToAccessMap ObjToLastAccess;
2908 /// Set of accesses that need a further dependence check.
2909 DenseSet<MemAccessInfo> CheckDeps;
2911 /// Set of pointers that are read only.
2912 SmallPtrSet<Value*, 16> ReadOnlyPtr;
2914 /// Set of underlying objects already written to.
2915 SmallPtrSet<Value*, 16> WriteObjects;
2919 /// Sets of potentially dependent accesses - members of one set share an
2920 /// underlying pointer. The set "CheckDeps" identfies which sets really need a
2921 /// dependence check.
2922 DepCandidates &DepCands;
2924 bool AreAllWritesIdentified;
2925 bool AreAllReadsIdentified;
2926 bool IsRTCheckNeeded;
2929 /// \brief Check whether a pointer can participate in a runtime bounds check.
2930 static bool hasComputableBounds(ScalarEvolution *SE, Value *Ptr) {
2931 const SCEV *PtrScev = SE->getSCEV(Ptr);
2932 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
2936 return AR->isAffine();
2939 bool AccessAnalysis::canCheckPtrAtRT(
2940 LoopVectorizationLegality::RuntimePointerCheck &RtCheck,
2941 unsigned &NumComparisons, ScalarEvolution *SE,
2943 // Find pointers with computable bounds. We are going to use this information
2944 // to place a runtime bound check.
2945 unsigned NumReadPtrChecks = 0;
2946 unsigned NumWritePtrChecks = 0;
2947 bool CanDoRT = true;
2949 bool IsDepCheckNeeded = isDependencyCheckNeeded();
2950 // We assign consecutive id to access from different dependence sets.
2951 // Accesses within the same set don't need a runtime check.
2952 unsigned RunningDepId = 1;
2953 DenseMap<Value *, unsigned> DepSetId;
2955 for (PtrAccessSet::iterator AI = Accesses.begin(), AE = Accesses.end();
2957 const MemAccessInfo &Access = *AI;
2958 Value *Ptr = Access.first;
2959 bool IsWrite = Access.second;
2961 // Just add write checks if we have both.
2962 if (!IsWrite && Accesses.count(std::make_pair(Ptr, true)))
2966 ++NumWritePtrChecks;
2970 if (hasComputableBounds(SE, Ptr)) {
2971 // The id of the dependence set.
2974 if (IsDepCheckNeeded) {
2975 Value *Leader = DepCands.getLeaderValue(Access).first;
2976 unsigned &LeaderId = DepSetId[Leader];
2978 LeaderId = RunningDepId++;
2981 // Each access has its own dependence set.
2982 DepId = RunningDepId++;
2984 //RtCheck.insert(SE, TheLoop, Ptr, IsWrite, DepId);
2986 DEBUG(dbgs() << "LV: Found a runtime check ptr:" << *Ptr <<"\n");
2992 if (IsDepCheckNeeded && CanDoRT && RunningDepId == 2)
2993 NumComparisons = 0; // Only one dependence set.
2995 NumComparisons = (NumWritePtrChecks * (NumReadPtrChecks +
2996 NumWritePtrChecks - 1));
3000 static bool isFunctionScopeIdentifiedObject(Value *Ptr) {
3001 return isNoAliasArgument(Ptr) || isNoAliasCall(Ptr) || isa<AllocaInst>(Ptr);
3004 void AccessAnalysis::processMemAccesses(bool UseDeferred) {
3005 // We process the set twice: first we process read-write pointers, last we
3006 // process read-only pointers. This allows us to skip dependence tests for
3007 // read-only pointers.
3009 PtrAccessSet &S = UseDeferred ? DeferredAccesses : Accesses;
3010 for (PtrAccessSet::iterator AI = S.begin(), AE = S.end(); AI != AE; ++AI) {
3011 const MemAccessInfo &Access = *AI;
3012 Value *Ptr = Access.first;
3013 bool IsWrite = Access.second;
3015 DepCands.insert(Access);
3017 // Memorize read-only pointers for later processing and skip them in the
3018 // first round (they need to be checked after we have seen all write
3019 // pointers). Note: we also mark pointer that are not consecutive as
3020 // "read-only" pointers (so that we check "a[b[i]] +="). Hence, we need the
3021 // second check for "!IsWrite".
3022 bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite;
3023 if (!UseDeferred && IsReadOnlyPtr) {
3024 DeferredAccesses.insert(Access);
3028 bool NeedDepCheck = false;
3029 // Check whether there is the possiblity of dependency because of underlying
3030 // objects being the same.
3031 typedef SmallVector<Value*, 16> ValueVector;
3032 ValueVector TempObjects;
3033 GetUnderlyingObjects(Ptr, TempObjects, DL);
3034 for (ValueVector::iterator UI = TempObjects.begin(), UE = TempObjects.end();
3036 Value *UnderlyingObj = *UI;
3038 // If this is a write then it needs to be an identified object. If this a
3039 // read and all writes (so far) are identified function scope objects we
3040 // don't need an identified underlying object but only an Argument (the
3041 // next write is going to invalidate this assumption if it is
3043 // This is a micro-optimization for the case where all writes are
3044 // identified and we have one argument pointer.
3045 // Otherwise, we do need a runtime check.
3046 if ((IsWrite && !isFunctionScopeIdentifiedObject(UnderlyingObj)) ||
3047 (!IsWrite && (!AreAllWritesIdentified ||
3048 !isa<Argument>(UnderlyingObj)) &&
3049 !isIdentifiedObject(UnderlyingObj))) {
3050 DEBUG(dbgs() << "LV: Found an unidentified " <<
3051 (IsWrite ? "write" : "read" ) << " ptr:" << *UnderlyingObj <<
3053 IsRTCheckNeeded = (IsRTCheckNeeded ||
3054 !isIdentifiedObject(UnderlyingObj) ||
3055 !AreAllReadsIdentified);
3058 AreAllWritesIdentified = false;
3060 AreAllReadsIdentified = false;
3063 // If this is a write - check other reads and writes for conflicts. If
3064 // this is a read only check other writes for conflicts (but only if there
3065 // is no other write to the ptr - this is an optimization to catch "a[i] =
3066 // a[i] + " without having to do a dependence check).
3067 if ((IsWrite || IsReadOnlyPtr) && WriteObjects.count(UnderlyingObj))
3068 NeedDepCheck = true;
3071 WriteObjects.insert(UnderlyingObj);
3073 // Create sets of pointers connected by shared underlying objects.
3074 UnderlyingObjToAccessMap::iterator Prev =
3075 ObjToLastAccess.find(UnderlyingObj);
3076 if (Prev != ObjToLastAccess.end())
3077 DepCands.unionSets(Access, Prev->second);
3079 ObjToLastAccess[UnderlyingObj] = Access;
3083 CheckDeps.insert(Access);
3087 /// \brief Checks memory dependences among accesses to the same underlying
3088 /// object to determine whether there vectorization is legal or not (and at
3089 /// which vectorization factor).
3091 /// This class works under the assumption that we already checked that memory
3092 /// locations with different underlying pointers are "must-not alias".
3093 /// We use the ScalarEvolution framework to symbolically evalutate access
3094 /// functions pairs. Since we currently don't restructure the loop we can rely
3095 /// on the program order of memory accesses to determine their safety.
3096 /// At the moment we will only deem accesses as safe for:
3097 /// * A negative constant distance assuming program order.
3099 /// Safe: tmp = a[i + 1]; OR a[i + 1] = x;
3100 /// a[i] = tmp; y = a[i];
3102 /// The latter case is safe because later checks guarantuee that there can't
3103 /// be a cycle through a phi node (that is, we check that "x" and "y" is not
3104 /// the same variable: a header phi can only be an induction or a reduction, a
3105 /// reduction can't have a memory sink, an induction can't have a memory
3106 /// source). This is important and must not be violated (or we have to
3107 /// resort to checking for cycles through memory).
3109 /// * A positive constant distance assuming program order that is bigger
3110 /// than the biggest memory access.
3112 /// tmp = a[i] OR b[i] = x
3113 /// a[i+2] = tmp y = b[i+2];
3115 /// Safe distance: 2 x sizeof(a[0]), and 2 x sizeof(b[0]), respectively.
3117 /// * Zero distances and all accesses have the same size.
3119 class MemoryDepChecker {
3121 typedef std::pair<Value*, char> MemAccessInfo;
3123 MemoryDepChecker(ScalarEvolution *Se, DataLayout *Dl, const Loop *L) :
3124 SE(Se), DL(Dl), InnermostLoop(L), AccessIdx(0) {}
3126 /// \brief Register the location (instructions are given increasing numbers)
3127 /// of a write access.
3128 void addAccess(StoreInst *SI) {
3129 Value *Ptr = SI->getPointerOperand();
3130 Accesses[std::make_pair(Ptr, true)].push_back(AccessIdx);
3131 InstMap.push_back(SI);
3135 /// \brief Register the location (instructions are given increasing numbers)
3136 /// of a write access.
3137 void addAccess(LoadInst *LI) {
3138 Value *Ptr = LI->getPointerOperand();
3139 Accesses[std::make_pair(Ptr, false)].push_back(AccessIdx);
3140 InstMap.push_back(LI);
3144 /// \brief Check whether the dependencies between the accesses are safe.
3146 /// Only checks sets with elements in \p CheckDeps.
3147 bool areDepsSafe(AccessAnalysis::DepCandidates &AccessSets,
3148 DenseSet<MemAccessInfo> &CheckDeps);
3150 /// \brief The maximum number of bytes of a vector register we can vectorize
3151 /// the accesses safely with.
3152 unsigned getMaxSafeDepDistBytes() { return MaxSafeDepDistBytes; }
3155 ScalarEvolution *SE;
3157 const Loop *InnermostLoop;
3159 /// \brief Maps access locations (ptr, read/write) to program order.
3160 DenseMap<MemAccessInfo, std::vector<unsigned> > Accesses;
3162 /// \brief Memory access instructions in program order.
3163 SmallVector<Instruction *, 16> InstMap;
3165 /// \brief The program order index to be used for the next instruction.
3168 // We can access this many bytes in parallel safely.
3169 unsigned MaxSafeDepDistBytes;
3171 /// \brief Check whether there is a plausible dependence between the two
3174 /// Access \p A must happen before \p B in program order. The two indices
3175 /// identify the index into the program order map.
3177 /// This function checks whether there is a plausible dependence (or the
3178 /// absence of such can't be proved) between the two accesses. If there is a
3179 /// plausible dependence but the dependence distance is bigger than one
3180 /// element access it records this distance in \p MaxSafeDepDistBytes (if this
3181 /// distance is smaller than any other distance encountered so far).
3182 /// Otherwise, this function returns true signaling a possible dependence.
3183 bool isDependent(const MemAccessInfo &A, unsigned AIdx,
3184 const MemAccessInfo &B, unsigned BIdx);
3186 /// \brief Check whether the data dependence could prevent store-load
3188 bool couldPreventStoreLoadForward(unsigned Distance, unsigned TypeByteSize);
3191 static bool isInBoundsGep(Value *Ptr) {
3192 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
3193 return GEP->isInBounds();
3197 /// \brief Check whether the access through \p Ptr has a constant stride.
3198 static int isStridedPtr(ScalarEvolution *SE, DataLayout *DL, Value *Ptr,
3200 const Type *PtrTy = Ptr->getType();
3201 assert(PtrTy->isPointerTy() && "Unexpected non ptr");
3203 // Make sure that the pointer does not point to aggregate types.
3204 if (cast<PointerType>(Ptr->getType())->getElementType()->isAggregateType()) {
3205 DEBUG(dbgs() << "LV: Bad stride - Not a pointer to a scalar type" << *Ptr
3210 const SCEV *PtrScev = SE->getSCEV(Ptr);
3211 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
3213 DEBUG(dbgs() << "LV: Bad stride - Not an AddRecExpr pointer "
3214 << *Ptr << " SCEV: " << *PtrScev << "\n");
3218 // The accesss function must stride over the innermost loop.
3219 if (Lp != AR->getLoop()) {
3220 DEBUG(dbgs() << "LV: Bad stride - Not striding over innermost loop " << *Ptr
3221 << " SCEV: " << *PtrScev << "\n");
3224 // The address calculation must not wrap. Otherwise, a dependence could be
3225 // inverted. An inbounds getelementptr that is a AddRec with a unit stride
3226 // cannot wrap per definition. The unit stride requirement is checked later.
3227 bool IsInBoundsGEP = isInBoundsGep(Ptr);
3228 bool IsNoWrapAddRec = AR->getNoWrapFlags(SCEV::NoWrapMask);
3229 if (!IsNoWrapAddRec && !IsInBoundsGEP) {
3230 DEBUG(dbgs() << "LV: Bad stride - Pointer may wrap in the address space "
3231 << *Ptr << " SCEV: " << *PtrScev << "\n");
3235 // Check the step is constant.
3236 const SCEV *Step = AR->getStepRecurrence(*SE);
3238 // Calculate the pointer stride and check if it is consecutive.
3239 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
3241 DEBUG(dbgs() << "LV: Bad stride - Not a constant strided " << *Ptr <<
3242 " SCEV: " << *PtrScev << "\n");
3246 int64_t Size = DL->getTypeAllocSize(PtrTy->getPointerElementType());
3247 const APInt &APStepVal = C->getValue()->getValue();
3249 // Huge step value - give up.
3250 if (APStepVal.getBitWidth() > 64)
3253 int64_t StepVal = APStepVal.getSExtValue();
3256 int64_t Stride = StepVal / Size;
3257 int64_t Rem = StepVal % Size;
3261 // If the SCEV could wrap but we have an inbounds gep with a unit stride we
3262 // know we can't "wrap around the address space".
3263 if (!IsNoWrapAddRec && IsInBoundsGEP && Stride != 1 && Stride != -1)
3269 bool MemoryDepChecker::couldPreventStoreLoadForward(unsigned Distance,
3270 unsigned TypeByteSize) {
3271 // If loads occur at a distance that is not a multiple of a feasible vector
3272 // factor store-load forwarding does not take place.
3273 // Positive dependences might cause troubles because vectorizing them might
3274 // prevent store-load forwarding making vectorized code run a lot slower.
3275 // a[i] = a[i-3] ^ a[i-8];
3276 // The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
3277 // hence on your typical architecture store-load forwarding does not take
3278 // place. Vectorizing in such cases does not make sense.
3279 // Store-load forwarding distance.
3280 const unsigned NumCyclesForStoreLoadThroughMemory = 8*TypeByteSize;
3281 // Maximum vector factor.
3282 unsigned MaxVFWithoutSLForwardIssues = MaxVectorWidth*TypeByteSize;
3283 if(MaxSafeDepDistBytes < MaxVFWithoutSLForwardIssues)
3284 MaxVFWithoutSLForwardIssues = MaxSafeDepDistBytes;
3286 for (unsigned vf = 2*TypeByteSize; vf <= MaxVFWithoutSLForwardIssues;
3288 if (Distance % vf && Distance / vf < NumCyclesForStoreLoadThroughMemory) {
3289 MaxVFWithoutSLForwardIssues = (vf >>=1);
3294 if (MaxVFWithoutSLForwardIssues< 2*TypeByteSize) {
3295 DEBUG(dbgs() << "LV: Distance " << Distance <<
3296 " that could cause a store-load forwarding conflict\n");
3300 if (MaxVFWithoutSLForwardIssues < MaxSafeDepDistBytes &&
3301 MaxVFWithoutSLForwardIssues != MaxVectorWidth*TypeByteSize)
3302 MaxSafeDepDistBytes = MaxVFWithoutSLForwardIssues;
3306 bool MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
3307 const MemAccessInfo &B, unsigned BIdx) {
3308 assert (AIdx < BIdx && "Must pass arguments in program order");
3310 Value *APtr = A.first;
3311 Value *BPtr = B.first;
3312 bool AIsWrite = A.second;
3313 bool BIsWrite = B.second;
3315 // Two reads are independent.
3316 if (!AIsWrite && !BIsWrite)
3319 const SCEV *AScev = SE->getSCEV(APtr);
3320 const SCEV *BScev = SE->getSCEV(BPtr);
3322 int StrideAPtr = isStridedPtr(SE, DL, APtr, InnermostLoop);
3323 int StrideBPtr = isStridedPtr(SE, DL, BPtr, InnermostLoop);
3325 const SCEV *Src = AScev;
3326 const SCEV *Sink = BScev;
3328 // If the induction step is negative we have to invert source and sink of the
3330 if (StrideAPtr < 0) {
3333 std::swap(APtr, BPtr);
3334 std::swap(Src, Sink);
3335 std::swap(AIsWrite, BIsWrite);
3336 std::swap(AIdx, BIdx);
3337 std::swap(StrideAPtr, StrideBPtr);
3340 const SCEV *Dist = SE->getMinusSCEV(Sink, Src);
3342 DEBUG(dbgs() << "LV: Src Scev: " << *Src << "Sink Scev: " << *Sink
3343 << "(Induction step: " << StrideAPtr << ")\n");
3344 DEBUG(dbgs() << "LV: Distance for " << *InstMap[AIdx] << " to "
3345 << *InstMap[BIdx] << ": " << *Dist << "\n");
3347 // Need consecutive accesses. We don't want to vectorize
3348 // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap in
3349 // the address space.
3350 if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr){
3351 DEBUG(dbgs() << "Non-consecutive pointer access\n");
3355 const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist);
3357 DEBUG(dbgs() << "LV: Dependence because of non constant distance\n");
3361 Type *ATy = APtr->getType()->getPointerElementType();
3362 Type *BTy = BPtr->getType()->getPointerElementType();
3363 unsigned TypeByteSize = DL->getTypeAllocSize(ATy);
3365 // Negative distances are not plausible dependencies.
3366 const APInt &Val = C->getValue()->getValue();
3367 if (Val.isNegative()) {
3368 bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
3369 if (IsTrueDataDependence &&
3370 (couldPreventStoreLoadForward(Val.abs().getZExtValue(), TypeByteSize) ||
3374 DEBUG(dbgs() << "LV: Dependence is negative: NoDep\n");
3378 // Write to the same location with the same size.
3379 // Could be improved to assert type sizes are the same (i32 == float, etc).
3383 DEBUG(dbgs() << "LV: Zero dependence difference but different types");
3387 assert(Val.isStrictlyPositive() && "Expect a positive value");
3389 // Positive distance bigger than max vectorization factor.
3392 "LV: ReadWrite-Write positive dependency with different types");
3396 unsigned Distance = (unsigned) Val.getZExtValue();
3398 // Bail out early if passed-in parameters make vectorization not feasible.
3399 unsigned ForcedFactor = VectorizationFactor ? VectorizationFactor : 1;
3400 unsigned ForcedUnroll = VectorizationUnroll ? VectorizationUnroll : 1;
3402 // The distance must be bigger than the size needed for a vectorized version
3403 // of the operation and the size of the vectorized operation must not be
3404 // bigger than the currrent maximum size.
3405 if (Distance < 2*TypeByteSize ||
3406 2*TypeByteSize > MaxSafeDepDistBytes ||
3407 Distance < TypeByteSize * ForcedUnroll * ForcedFactor) {
3408 DEBUG(dbgs() << "LV: Failure because of Positive distance "
3409 << Val.getSExtValue() << "\n");
3413 MaxSafeDepDistBytes = Distance < MaxSafeDepDistBytes ?
3414 Distance : MaxSafeDepDistBytes;
3416 bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
3417 if (IsTrueDataDependence &&
3418 couldPreventStoreLoadForward(Distance, TypeByteSize))
3421 DEBUG(dbgs() << "LV: Positive distance " << Val.getSExtValue() <<
3422 " with max VF=" << MaxSafeDepDistBytes/TypeByteSize << "\n");
3428 MemoryDepChecker::areDepsSafe(AccessAnalysis::DepCandidates &AccessSets,
3429 DenseSet<MemAccessInfo> &CheckDeps) {
3431 MaxSafeDepDistBytes = -1U;
3432 while (!CheckDeps.empty()) {
3433 MemAccessInfo CurAccess = *CheckDeps.begin();
3435 // Get the relevant memory access set.
3436 EquivalenceClasses<MemAccessInfo>::iterator I =
3437 AccessSets.findValue(AccessSets.getLeaderValue(CurAccess));
3439 // Check accesses within this set.
3440 EquivalenceClasses<MemAccessInfo>::member_iterator AI, AE;
3441 AI = AccessSets.member_begin(I), AE = AccessSets.member_end();
3443 // Check every access pair.
3445 CheckDeps.erase(*AI);
3446 EquivalenceClasses<MemAccessInfo>::member_iterator OI = llvm::next(AI);
3448 // Check every accessing instruction pair in program order.
3449 for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(),
3450 I1E = Accesses[*AI].end(); I1 != I1E; ++I1)
3451 for (std::vector<unsigned>::iterator I2 = Accesses[*OI].begin(),
3452 I2E = Accesses[*OI].end(); I2 != I2E; ++I2) {
3453 if (*I1 < *I2 && isDependent(*AI, *I1, *OI, *I2))
3455 if (*I2 < *I1 && isDependent(*OI, *I2, *AI, *I1))
3466 AliasAnalysis::Location
3467 LoopVectorizationLegality::getLoadStoreLocation(Instruction *Inst) {
3468 if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
3469 return AA->getLocation(Store);
3470 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
3471 return AA->getLocation(Load);
3473 llvm_unreachable("Should be either load or store instruction");
3477 LoopVectorizationLegality::hasPossibleGlobalWriteReorder(
3480 AliasMultiMap& WriteObjects,
3481 unsigned MaxByteWidth) {
3483 AliasAnalysis::Location ThisLoc = getLoadStoreLocation(Inst);
3485 std::vector<Instruction*>::iterator
3486 it = WriteObjects[Object].begin(),
3487 end = WriteObjects[Object].end();
3489 for (; it != end; ++it) {
3490 Instruction* I = *it;
3494 AliasAnalysis::Location ThatLoc = getLoadStoreLocation(I);
3495 if (AA->alias(ThisLoc.getWithNewSize(MaxByteWidth),
3496 ThatLoc.getWithNewSize(MaxByteWidth)))
3502 bool LoopVectorizationLegality::canVectorizeMemory() {
3504 typedef SmallVector<Value*, 16> ValueVector;
3505 typedef SmallPtrSet<Value*, 16> ValueSet;
3506 // Holds the Load and Store *instructions*.
3509 PtrRtCheck.Pointers.clear();
3510 PtrRtCheck.Need = false;
3512 const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
3515 for (Loop::block_iterator bb = TheLoop->block_begin(),
3516 be = TheLoop->block_end(); bb != be; ++bb) {
3518 // Scan the BB and collect legal loads and stores.
3519 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
3522 // If this is a load, save it. If this instruction can read from memory
3523 // but is not a load, then we quit. Notice that we don't handle function
3524 // calls that read or write.
3525 if (it->mayReadFromMemory()) {
3526 LoadInst *Ld = dyn_cast<LoadInst>(it);
3527 if (!Ld) return false;
3528 if (!Ld->isSimple() && !IsAnnotatedParallel) {
3529 DEBUG(dbgs() << "LV: Found a non-simple load.\n");
3532 Loads.push_back(Ld);
3536 // Save 'store' instructions. Abort if other instructions write to memory.
3537 if (it->mayWriteToMemory()) {
3538 StoreInst *St = dyn_cast<StoreInst>(it);
3539 if (!St) return false;
3540 if (!St->isSimple() && !IsAnnotatedParallel) {
3541 DEBUG(dbgs() << "LV: Found a non-simple store.\n");
3544 Stores.push_back(St);
3549 // Now we have two lists that hold the loads and the stores.
3550 // Next, we find the pointers that they use.
3552 // Check if we see any stores. If there are no stores, then we don't
3553 // care if the pointers are *restrict*.
3554 if (!Stores.size()) {
3555 DEBUG(dbgs() << "LV: Found a read-only loop!\n");
3559 // Holds the read and read-write *pointers* that we find. These maps hold
3560 // unique values for pointers (so no need for multi-map).
3562 AliasMap ReadWrites;
3564 // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
3565 // multiple times on the same object. If the ptr is accessed twice, once
3566 // for read and once for write, it will only appear once (on the write
3567 // list). This is okay, since we are going to check for conflicts between
3568 // writes and between reads and writes, but not between reads and reads.
3571 ValueVector::iterator I, IE;
3572 for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
3573 StoreInst *ST = cast<StoreInst>(*I);
3574 Value* Ptr = ST->getPointerOperand();
3576 if (isUniform(Ptr)) {
3577 DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
3581 // If we did *not* see this pointer before, insert it to
3582 // the read-write list. At this phase it is only a 'write' list.
3583 if (Seen.insert(Ptr))
3584 ReadWrites.insert(std::make_pair(Ptr, ST));
3587 if (IsAnnotatedParallel) {
3589 << "LV: A loop annotated parallel, ignore memory dependency "
3594 for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
3595 LoadInst *LD = cast<LoadInst>(*I);
3596 Value* Ptr = LD->getPointerOperand();
3597 // If we did *not* see this pointer before, insert it to the
3598 // read list. If we *did* see it before, then it is already in
3599 // the read-write list. This allows us to vectorize expressions
3600 // such as A[i] += x; Because the address of A[i] is a read-write
3601 // pointer. This only works if the index of A[i] is consecutive.
3602 // If the address of i is unknown (for example A[B[i]]) then we may
3603 // read a few words, modify, and write a few words, and some of the
3604 // words may be written to the same address.
3605 if (Seen.insert(Ptr) || 0 == isConsecutivePtr(Ptr))
3606 Reads.insert(std::make_pair(Ptr, LD));
3609 // If we write (or read-write) to a single destination and there are no
3610 // other reads in this loop then is it safe to vectorize.
3611 if (ReadWrites.size() == 1 && Reads.size() == 0) {
3612 DEBUG(dbgs() << "LV: Found a write-only loop!\n");
3616 unsigned NumReadPtrs = 0;
3617 unsigned NumWritePtrs = 0;
3619 // Find pointers with computable bounds. We are going to use this information
3620 // to place a runtime bound check.
3621 bool CanDoRT = true;
3622 AliasMap::iterator MI, ME;
3623 for (MI = ReadWrites.begin(), ME = ReadWrites.end(); MI != ME; ++MI) {
3624 Value *V = (*MI).first;
3625 if (hasComputableBounds(V)) {
3626 PtrRtCheck.insert(SE, TheLoop, V, true);
3628 DEBUG(dbgs() << "LV: Found a runtime check ptr:" << *V <<"\n");
3634 for (MI = Reads.begin(), ME = Reads.end(); MI != ME; ++MI) {
3635 Value *V = (*MI).first;
3636 if (hasComputableBounds(V)) {
3637 PtrRtCheck.insert(SE, TheLoop, V, false);
3639 DEBUG(dbgs() << "LV: Found a runtime check ptr:" << *V <<"\n");
3646 // Check that we did not collect too many pointers or found a
3647 // unsizeable pointer.
3648 unsigned NumComparisons = (NumWritePtrs * (NumReadPtrs + NumWritePtrs - 1));
3649 DEBUG(dbgs() << "LV: We need to compare " << NumComparisons << " ptrs.\n");
3650 if (!CanDoRT || NumComparisons > RuntimeMemoryCheckThreshold) {
3656 DEBUG(dbgs() << "LV: We can perform a memory runtime check if needed.\n");
3659 bool NeedRTCheck = false;
3661 // Biggest vectorized access possible, vector width * unroll factor.
3662 // TODO: We're being very pessimistic here, find a way to know the
3663 // real access width before getting here.
3664 unsigned MaxByteWidth = (TTI->getRegisterBitWidth(true) / 8) *
3665 TTI->getMaximumUnrollFactor();
3666 // Now that the pointers are in two lists (Reads and ReadWrites), we
3667 // can check that there are no conflicts between each of the writes and
3668 // between the writes to the reads.
3669 // Note that WriteObjects duplicates the stores (indexed now by underlying
3670 // objects) to avoid pointing to elements inside ReadWrites.
3671 // TODO: Maybe create a new type where they can interact without duplication.
3672 AliasMultiMap WriteObjects;
3673 ValueVector TempObjects;
3675 // Check that the read-writes do not conflict with other read-write
3677 bool AllWritesIdentified = true;
3678 for (MI = ReadWrites.begin(), ME = ReadWrites.end(); MI != ME; ++MI) {
3679 Value *Val = (*MI).first;
3680 Instruction *Inst = (*MI).second;
3682 GetUnderlyingObjects(Val, TempObjects, DL);
3683 for (ValueVector::iterator UI=TempObjects.begin(), UE=TempObjects.end();
3685 if (!isIdentifiedObject(*UI)) {
3686 DEBUG(dbgs() << "LV: Found an unidentified write ptr:"<< **UI <<"\n");
3688 AllWritesIdentified = false;
3691 // Never seen it before, can't alias.
3692 if (WriteObjects[*UI].empty()) {
3693 DEBUG(dbgs() << "LV: Adding Underlying value:" << **UI <<"\n");
3694 WriteObjects[*UI].push_back(Inst);
3697 // Direct alias found.
3698 if (!AA || dyn_cast<GlobalValue>(*UI) == NULL) {
3699 DEBUG(dbgs() << "LV: Found a possible write-write reorder:"
3703 DEBUG(dbgs() << "LV: Found a conflicting global value:"
3705 DEBUG(dbgs() << "LV: While examining store:" << *Inst <<"\n");
3706 DEBUG(dbgs() << "LV: On value:" << *Val <<"\n");
3708 // If global alias, make sure they do alias.
3709 if (hasPossibleGlobalWriteReorder(*UI,
3713 DEBUG(dbgs() << "LV: Found a possible write-write reorder:" << **UI
3718 // Didn't alias, insert into map for further reference.
3719 WriteObjects[*UI].push_back(Inst);
3721 TempObjects.clear();
3724 /// Check that the reads don't conflict with the read-writes.
3725 for (MI = Reads.begin(), ME = Reads.end(); MI != ME; ++MI) {
3726 Value *Val = (*MI).first;
3727 GetUnderlyingObjects(Val, TempObjects, DL);
3728 for (ValueVector::iterator UI=TempObjects.begin(), UE=TempObjects.end();
3730 // If all of the writes are identified then we don't care if the read
3731 // pointer is identified or not.
3732 if (!AllWritesIdentified && !isIdentifiedObject(*UI)) {
3733 DEBUG(dbgs() << "LV: Found an unidentified read ptr:"<< **UI <<"\n");
3737 // Never seen it before, can't alias.
3738 if (WriteObjects[*UI].empty())
3740 // Direct alias found.
3741 if (!AA || dyn_cast<GlobalValue>(*UI) == NULL) {
3742 DEBUG(dbgs() << "LV: Found a possible write-write reorder:"
3746 DEBUG(dbgs() << "LV: Found a global value: "
3748 Instruction *Inst = (*MI).second;
3749 DEBUG(dbgs() << "LV: While examining load:" << *Inst <<"\n");
3750 DEBUG(dbgs() << "LV: On value:" << *Val <<"\n");
3752 // If global alias, make sure they do alias.
3753 if (hasPossibleGlobalWriteReorder(*UI,
3757 DEBUG(dbgs() << "LV: Found a possible read-write reorder:" << **UI
3762 TempObjects.clear();
3765 PtrRtCheck.Need = NeedRTCheck;
3766 if (NeedRTCheck && !CanDoRT) {
3767 DEBUG(dbgs() << "LV: We can't vectorize because we can't find " <<
3768 "the array bounds.\n");
3773 DEBUG(dbgs() << "LV: We "<< (NeedRTCheck ? "" : "don't") <<
3774 " need a runtime memory check.\n");
3778 static bool hasMultipleUsesOf(Instruction *I,
3779 SmallPtrSet<Instruction *, 8> &Insts) {
3780 unsigned NumUses = 0;
3781 for(User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use) {
3782 if (Insts.count(dyn_cast<Instruction>(*Use)))
3791 static bool areAllUsesIn(Instruction *I, SmallPtrSet<Instruction *, 8> &Set) {
3792 for(User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use)
3793 if (!Set.count(dyn_cast<Instruction>(*Use)))
3798 bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi,
3799 ReductionKind Kind) {
3800 if (Phi->getNumIncomingValues() != 2)
3803 // Reduction variables are only found in the loop header block.
3804 if (Phi->getParent() != TheLoop->getHeader())
3807 // Obtain the reduction start value from the value that comes from the loop
3809 Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
3811 // ExitInstruction is the single value which is used outside the loop.
3812 // We only allow for a single reduction value to be used outside the loop.
3813 // This includes users of the reduction, variables (which form a cycle
3814 // which ends in the phi node).
3815 Instruction *ExitInstruction = 0;
3816 // Indicates that we found a reduction operation in our scan.
3817 bool FoundReduxOp = false;
3819 // We start with the PHI node and scan for all of the users of this
3820 // instruction. All users must be instructions that can be used as reduction
3821 // variables (such as ADD). We must have a single out-of-block user. The cycle
3822 // must include the original PHI.
3823 bool FoundStartPHI = false;
3825 // To recognize min/max patterns formed by a icmp select sequence, we store
3826 // the number of instruction we saw from the recognized min/max pattern,
3827 // to make sure we only see exactly the two instructions.
3828 unsigned NumCmpSelectPatternInst = 0;
3829 ReductionInstDesc ReduxDesc(false, 0);
3831 SmallPtrSet<Instruction *, 8> VisitedInsts;
3832 SmallVector<Instruction *, 8> Worklist;
3833 Worklist.push_back(Phi);
3834 VisitedInsts.insert(Phi);
3836 // A value in the reduction can be used:
3837 // - By the reduction:
3838 // - Reduction operation:
3839 // - One use of reduction value (safe).
3840 // - Multiple use of reduction value (not safe).
3842 // - All uses of the PHI must be the reduction (safe).
3843 // - Otherwise, not safe.
3844 // - By one instruction outside of the loop (safe).
3845 // - By further instructions outside of the loop (not safe).
3846 // - By an instruction that is not part of the reduction (not safe).
3848 // * An instruction type other than PHI or the reduction operation.
3849 // * A PHI in the header other than the initial PHI.
3850 while (!Worklist.empty()) {
3851 Instruction *Cur = Worklist.back();
3852 Worklist.pop_back();
3855 // If the instruction has no users then this is a broken chain and can't be
3856 // a reduction variable.
3857 if (Cur->use_empty())
3860 bool IsAPhi = isa<PHINode>(Cur);
3862 // A header PHI use other than the original PHI.
3863 if (Cur != Phi && IsAPhi && Cur->getParent() == Phi->getParent())
3866 // Reductions of instructions such as Div, and Sub is only possible if the
3867 // LHS is the reduction variable.
3868 if (!Cur->isCommutative() && !IsAPhi && !isa<SelectInst>(Cur) &&
3869 !isa<ICmpInst>(Cur) && !isa<FCmpInst>(Cur) &&
3870 !VisitedInsts.count(dyn_cast<Instruction>(Cur->getOperand(0))))
3873 // Any reduction instruction must be of one of the allowed kinds.
3874 ReduxDesc = isReductionInstr(Cur, Kind, ReduxDesc);
3875 if (!ReduxDesc.IsReduction)
3878 // A reduction operation must only have one use of the reduction value.
3879 if (!IsAPhi && Kind != RK_IntegerMinMax && Kind != RK_FloatMinMax &&
3880 hasMultipleUsesOf(Cur, VisitedInsts))
3883 // All inputs to a PHI node must be a reduction value.
3884 if(IsAPhi && Cur != Phi && !areAllUsesIn(Cur, VisitedInsts))
3887 if (Kind == RK_IntegerMinMax && (isa<ICmpInst>(Cur) ||
3888 isa<SelectInst>(Cur)))
3889 ++NumCmpSelectPatternInst;
3890 if (Kind == RK_FloatMinMax && (isa<FCmpInst>(Cur) ||
3891 isa<SelectInst>(Cur)))
3892 ++NumCmpSelectPatternInst;
3894 // Check whether we found a reduction operator.
3895 FoundReduxOp |= !IsAPhi;
3897 // Process users of current instruction. Push non PHI nodes after PHI nodes
3898 // onto the stack. This way we are going to have seen all inputs to PHI
3899 // nodes once we get to them.
3900 SmallVector<Instruction *, 8> NonPHIs;
3901 SmallVector<Instruction *, 8> PHIs;
3902 for (Value::use_iterator UI = Cur->use_begin(), E = Cur->use_end(); UI != E;
3904 Instruction *Usr = cast<Instruction>(*UI);
3906 // Check if we found the exit user.
3907 BasicBlock *Parent = Usr->getParent();
3908 if (!TheLoop->contains(Parent)) {
3909 // Exit if you find multiple outside users.
3910 if (ExitInstruction != 0)
3912 ExitInstruction = Cur;
3916 // Process instructions only once (termination).
3917 if (VisitedInsts.insert(Usr)) {
3918 if (isa<PHINode>(Usr))
3919 PHIs.push_back(Usr);
3921 NonPHIs.push_back(Usr);
3923 // Remember that we completed the cycle.
3925 FoundStartPHI = true;
3927 Worklist.append(PHIs.begin(), PHIs.end());
3928 Worklist.append(NonPHIs.begin(), NonPHIs.end());
3931 // This means we have seen one but not the other instruction of the
3932 // pattern or more than just a select and cmp.
3933 if ((Kind == RK_IntegerMinMax || Kind == RK_FloatMinMax) &&
3934 NumCmpSelectPatternInst != 2)
3937 if (!FoundStartPHI || !FoundReduxOp || !ExitInstruction)
3940 // We found a reduction var if we have reached the original phi node and we
3941 // only have a single instruction with out-of-loop users.
3943 // This instruction is allowed to have out-of-loop users.
3944 AllowedExit.insert(ExitInstruction);
3946 // Save the description of this reduction variable.
3947 ReductionDescriptor RD(RdxStart, ExitInstruction, Kind,
3948 ReduxDesc.MinMaxKind);
3949 Reductions[Phi] = RD;
3950 // We've ended the cycle. This is a reduction variable if we have an
3951 // outside user and it has a binary op.
3956 /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
3957 /// pattern corresponding to a min(X, Y) or max(X, Y).
3958 LoopVectorizationLegality::ReductionInstDesc
3959 LoopVectorizationLegality::isMinMaxSelectCmpPattern(Instruction *I,
3960 ReductionInstDesc &Prev) {
3962 assert((isa<ICmpInst>(I) || isa<FCmpInst>(I) || isa<SelectInst>(I)) &&
3963 "Expect a select instruction");
3964 Instruction *Cmp = 0;
3965 SelectInst *Select = 0;
3967 // We must handle the select(cmp()) as a single instruction. Advance to the
3969 if ((Cmp = dyn_cast<ICmpInst>(I)) || (Cmp = dyn_cast<FCmpInst>(I))) {
3970 if (!Cmp->hasOneUse() || !(Select = dyn_cast<SelectInst>(*I->use_begin())))
3971 return ReductionInstDesc(false, I);
3972 return ReductionInstDesc(Select, Prev.MinMaxKind);
3975 // Only handle single use cases for now.
3976 if (!(Select = dyn_cast<SelectInst>(I)))
3977 return ReductionInstDesc(false, I);
3978 if (!(Cmp = dyn_cast<ICmpInst>(I->getOperand(0))) &&
3979 !(Cmp = dyn_cast<FCmpInst>(I->getOperand(0))))
3980 return ReductionInstDesc(false, I);
3981 if (!Cmp->hasOneUse())
3982 return ReductionInstDesc(false, I);
3987 // Look for a min/max pattern.
3988 if (m_UMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
3989 return ReductionInstDesc(Select, MRK_UIntMin);
3990 else if (m_UMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
3991 return ReductionInstDesc(Select, MRK_UIntMax);
3992 else if (m_SMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
3993 return ReductionInstDesc(Select, MRK_SIntMax);
3994 else if (m_SMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
3995 return ReductionInstDesc(Select, MRK_SIntMin);
3996 else if (m_OrdFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
3997 return ReductionInstDesc(Select, MRK_FloatMin);
3998 else if (m_OrdFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
3999 return ReductionInstDesc(Select, MRK_FloatMax);
4000 else if (m_UnordFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4001 return ReductionInstDesc(Select, MRK_FloatMin);
4002 else if (m_UnordFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4003 return ReductionInstDesc(Select, MRK_FloatMax);
4005 return ReductionInstDesc(false, I);
4008 LoopVectorizationLegality::ReductionInstDesc
4009 LoopVectorizationLegality::isReductionInstr(Instruction *I,
4011 ReductionInstDesc &Prev) {
4012 bool FP = I->getType()->isFloatingPointTy();
4013 bool FastMath = (FP && I->isCommutative() && I->isAssociative());
4014 switch (I->getOpcode()) {
4016 return ReductionInstDesc(false, I);
4017 case Instruction::PHI:
4018 if (FP && (Kind != RK_FloatMult && Kind != RK_FloatAdd &&
4019 Kind != RK_FloatMinMax))
4020 return ReductionInstDesc(false, I);
4021 return ReductionInstDesc(I, Prev.MinMaxKind);
4022 case Instruction::Sub:
4023 case Instruction::Add:
4024 return ReductionInstDesc(Kind == RK_IntegerAdd, I);
4025 case Instruction::Mul:
4026 return ReductionInstDesc(Kind == RK_IntegerMult, I);
4027 case Instruction::And:
4028 return ReductionInstDesc(Kind == RK_IntegerAnd, I);
4029 case Instruction::Or:
4030 return ReductionInstDesc(Kind == RK_IntegerOr, I);
4031 case Instruction::Xor:
4032 return ReductionInstDesc(Kind == RK_IntegerXor, I);
4033 case Instruction::FMul:
4034 return ReductionInstDesc(Kind == RK_FloatMult && FastMath, I);
4035 case Instruction::FAdd:
4036 return ReductionInstDesc(Kind == RK_FloatAdd && FastMath, I);
4037 case Instruction::FCmp:
4038 case Instruction::ICmp:
4039 case Instruction::Select:
4040 if (Kind != RK_IntegerMinMax &&
4041 (!HasFunNoNaNAttr || Kind != RK_FloatMinMax))
4042 return ReductionInstDesc(false, I);
4043 return isMinMaxSelectCmpPattern(I, Prev);
4047 LoopVectorizationLegality::InductionKind
4048 LoopVectorizationLegality::isInductionVariable(PHINode *Phi) {
4049 Type *PhiTy = Phi->getType();
4050 // We only handle integer and pointer inductions variables.
4051 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
4052 return IK_NoInduction;
4054 // Check that the PHI is consecutive.
4055 const SCEV *PhiScev = SE->getSCEV(Phi);
4056 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
4058 DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
4059 return IK_NoInduction;
4061 const SCEV *Step = AR->getStepRecurrence(*SE);
4063 // Integer inductions need to have a stride of one.
4064 if (PhiTy->isIntegerTy()) {
4066 return IK_IntInduction;
4067 if (Step->isAllOnesValue())
4068 return IK_ReverseIntInduction;
4069 return IK_NoInduction;
4072 // Calculate the pointer stride and check if it is consecutive.
4073 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
4075 return IK_NoInduction;
4077 assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
4078 uint64_t Size = DL->getTypeAllocSize(PhiTy->getPointerElementType());
4079 if (C->getValue()->equalsInt(Size))
4080 return IK_PtrInduction;
4081 else if (C->getValue()->equalsInt(0 - Size))
4082 return IK_ReversePtrInduction;
4084 return IK_NoInduction;
4087 bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
4088 Value *In0 = const_cast<Value*>(V);
4089 PHINode *PN = dyn_cast_or_null<PHINode>(In0);
4093 return Inductions.count(PN);
4096 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) {
4097 assert(TheLoop->contains(BB) && "Unknown block used");
4099 // Blocks that do not dominate the latch need predication.
4100 BasicBlock* Latch = TheLoop->getLoopLatch();
4101 return !DT->dominates(BB, Latch);
4104 bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB) {
4105 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
4106 // We might be able to hoist the load.
4107 if (it->mayReadFromMemory() && !LoadSpeculation.isHoistableLoad(it))
4110 // We don't predicate stores at the moment.
4111 if (it->mayWriteToMemory() || it->mayThrow())
4114 // The instructions below can trap.
4115 switch (it->getOpcode()) {
4117 case Instruction::UDiv:
4118 case Instruction::SDiv:
4119 case Instruction::URem:
4120 case Instruction::SRem:
4128 bool LoopVectorizationLegality::hasComputableBounds(Value *Ptr) {
4129 const SCEV *PhiScev = SE->getSCEV(Ptr);
4130 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
4134 return AR->isAffine();
4137 LoopVectorizationCostModel::VectorizationFactor
4138 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize,
4140 // Width 1 means no vectorize
4141 VectorizationFactor Factor = { 1U, 0U };
4142 if (OptForSize && Legal->getRuntimePointerCheck()->Need) {
4143 DEBUG(dbgs() << "LV: Aborting. Runtime ptr check is required in Os.\n");
4147 // Find the trip count.
4148 unsigned TC = SE->getSmallConstantTripCount(TheLoop, TheLoop->getLoopLatch());
4149 DEBUG(dbgs() << "LV: Found trip count:"<<TC<<"\n");
4151 unsigned WidestType = getWidestType();
4152 unsigned WidestRegister = TTI.getRegisterBitWidth(true);
4153 unsigned MaxVectorSize = WidestRegister / WidestType;
4154 DEBUG(dbgs() << "LV: The Widest type: " << WidestType << " bits.\n");
4155 DEBUG(dbgs() << "LV: The Widest register is:" << WidestRegister << "bits.\n");
4157 if (MaxVectorSize == 0) {
4158 DEBUG(dbgs() << "LV: The target has no vector registers.\n");
4162 assert(MaxVectorSize <= 32 && "Did not expect to pack so many elements"
4163 " into one vector!");
4165 unsigned VF = MaxVectorSize;
4167 // If we optimize the program for size, avoid creating the tail loop.
4169 // If we are unable to calculate the trip count then don't try to vectorize.
4171 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
4175 // Find the maximum SIMD width that can fit within the trip count.
4176 VF = TC % MaxVectorSize;
4181 // If the trip count that we found modulo the vectorization factor is not
4182 // zero then we require a tail.
4184 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
4190 assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
4191 DEBUG(dbgs() << "LV: Using user VF "<<UserVF<<".\n");
4193 Factor.Width = UserVF;
4197 float Cost = expectedCost(1);
4199 DEBUG(dbgs() << "LV: Scalar loop costs: "<< (int)Cost << ".\n");
4200 for (unsigned i=2; i <= VF; i*=2) {
4201 // Notice that the vector loop needs to be executed less times, so
4202 // we need to divide the cost of the vector loops by the width of
4203 // the vector elements.
4204 float VectorCost = expectedCost(i) / (float)i;
4205 DEBUG(dbgs() << "LV: Vector loop of width "<< i << " costs: " <<
4206 (int)VectorCost << ".\n");
4207 if (VectorCost < Cost) {
4213 DEBUG(dbgs() << "LV: Selecting VF = : "<< Width << ".\n");
4214 Factor.Width = Width;
4215 Factor.Cost = Width * Cost;
4219 unsigned LoopVectorizationCostModel::getWidestType() {
4220 unsigned MaxWidth = 8;
4223 for (Loop::block_iterator bb = TheLoop->block_begin(),
4224 be = TheLoop->block_end(); bb != be; ++bb) {
4225 BasicBlock *BB = *bb;
4227 // For each instruction in the loop.
4228 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
4229 Type *T = it->getType();
4231 // Only examine Loads, Stores and PHINodes.
4232 if (!isa<LoadInst>(it) && !isa<StoreInst>(it) && !isa<PHINode>(it))
4235 // Examine PHI nodes that are reduction variables.
4236 if (PHINode *PN = dyn_cast<PHINode>(it))
4237 if (!Legal->getReductionVars()->count(PN))
4240 // Examine the stored values.
4241 if (StoreInst *ST = dyn_cast<StoreInst>(it))
4242 T = ST->getValueOperand()->getType();
4244 // Ignore loaded pointer types and stored pointer types that are not
4245 // consecutive. However, we do want to take consecutive stores/loads of
4246 // pointer vectors into account.
4247 if (T->isPointerTy() && !isConsecutiveLoadOrStore(it))
4250 MaxWidth = std::max(MaxWidth,
4251 (unsigned)DL->getTypeSizeInBits(T->getScalarType()));
4259 LoopVectorizationCostModel::selectUnrollFactor(bool OptForSize,
4262 unsigned LoopCost) {
4264 // -- The unroll heuristics --
4265 // We unroll the loop in order to expose ILP and reduce the loop overhead.
4266 // There are many micro-architectural considerations that we can't predict
4267 // at this level. For example frontend pressure (on decode or fetch) due to
4268 // code size, or the number and capabilities of the execution ports.
4270 // We use the following heuristics to select the unroll factor:
4271 // 1. If the code has reductions the we unroll in order to break the cross
4272 // iteration dependency.
4273 // 2. If the loop is really small then we unroll in order to reduce the loop
4275 // 3. We don't unroll if we think that we will spill registers to memory due
4276 // to the increased register pressure.
4278 // Use the user preference, unless 'auto' is selected.
4282 // When we optimize for size we don't unroll.
4286 // Do not unroll loops with a relatively small trip count.
4287 unsigned TC = SE->getSmallConstantTripCount(TheLoop,
4288 TheLoop->getLoopLatch());
4289 if (TC > 1 && TC < TinyTripCountUnrollThreshold)
4292 unsigned TargetVectorRegisters = TTI.getNumberOfRegisters(true);
4293 DEBUG(dbgs() << "LV: The target has " << TargetVectorRegisters <<
4294 " vector registers\n");
4296 LoopVectorizationCostModel::RegisterUsage R = calculateRegisterUsage();
4297 // We divide by these constants so assume that we have at least one
4298 // instruction that uses at least one register.
4299 R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
4300 R.NumInstructions = std::max(R.NumInstructions, 1U);
4302 // We calculate the unroll factor using the following formula.
4303 // Subtract the number of loop invariants from the number of available
4304 // registers. These registers are used by all of the unrolled instances.
4305 // Next, divide the remaining registers by the number of registers that is
4306 // required by the loop, in order to estimate how many parallel instances
4307 // fit without causing spills.
4308 unsigned UF = (TargetVectorRegisters - R.LoopInvariantRegs) / R.MaxLocalUsers;
4310 // Clamp the unroll factor ranges to reasonable factors.
4311 unsigned MaxUnrollSize = TTI.getMaximumUnrollFactor();
4313 // If we did not calculate the cost for VF (because the user selected the VF)
4314 // then we calculate the cost of VF here.
4316 LoopCost = expectedCost(VF);
4318 // Clamp the calculated UF to be between the 1 and the max unroll factor
4319 // that the target allows.
4320 if (UF > MaxUnrollSize)
4325 if (Legal->getReductionVars()->size()) {
4326 DEBUG(dbgs() << "LV: Unrolling because of reductions. \n");
4330 // We want to unroll tiny loops in order to reduce the loop overhead.
4331 // We assume that the cost overhead is 1 and we use the cost model
4332 // to estimate the cost of the loop and unroll until the cost of the
4333 // loop overhead is about 5% of the cost of the loop.
4334 DEBUG(dbgs() << "LV: Loop cost is "<< LoopCost <<" \n");
4335 if (LoopCost < 20) {
4336 DEBUG(dbgs() << "LV: Unrolling to reduce branch cost. \n");
4337 unsigned NewUF = 20/LoopCost + 1;
4338 return std::min(NewUF, UF);
4341 DEBUG(dbgs() << "LV: Not Unrolling. \n");
4345 LoopVectorizationCostModel::RegisterUsage
4346 LoopVectorizationCostModel::calculateRegisterUsage() {
4347 // This function calculates the register usage by measuring the highest number
4348 // of values that are alive at a single location. Obviously, this is a very
4349 // rough estimation. We scan the loop in a topological order in order and
4350 // assign a number to each instruction. We use RPO to ensure that defs are
4351 // met before their users. We assume that each instruction that has in-loop
4352 // users starts an interval. We record every time that an in-loop value is
4353 // used, so we have a list of the first and last occurrences of each
4354 // instruction. Next, we transpose this data structure into a multi map that
4355 // holds the list of intervals that *end* at a specific location. This multi
4356 // map allows us to perform a linear search. We scan the instructions linearly
4357 // and record each time that a new interval starts, by placing it in a set.
4358 // If we find this value in the multi-map then we remove it from the set.
4359 // The max register usage is the maximum size of the set.
4360 // We also search for instructions that are defined outside the loop, but are
4361 // used inside the loop. We need this number separately from the max-interval
4362 // usage number because when we unroll, loop-invariant values do not take
4364 LoopBlocksDFS DFS(TheLoop);
4368 R.NumInstructions = 0;
4370 // Each 'key' in the map opens a new interval. The values
4371 // of the map are the index of the 'last seen' usage of the
4372 // instruction that is the key.
4373 typedef DenseMap<Instruction*, unsigned> IntervalMap;
4374 // Maps instruction to its index.
4375 DenseMap<unsigned, Instruction*> IdxToInstr;
4376 // Marks the end of each interval.
4377 IntervalMap EndPoint;
4378 // Saves the list of instruction indices that are used in the loop.
4379 SmallSet<Instruction*, 8> Ends;
4380 // Saves the list of values that are used in the loop but are
4381 // defined outside the loop, such as arguments and constants.
4382 SmallPtrSet<Value*, 8> LoopInvariants;
4385 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
4386 be = DFS.endRPO(); bb != be; ++bb) {
4387 R.NumInstructions += (*bb)->size();
4388 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
4390 Instruction *I = it;
4391 IdxToInstr[Index++] = I;
4393 // Save the end location of each USE.
4394 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
4395 Value *U = I->getOperand(i);
4396 Instruction *Instr = dyn_cast<Instruction>(U);
4398 // Ignore non-instruction values such as arguments, constants, etc.
4399 if (!Instr) continue;
4401 // If this instruction is outside the loop then record it and continue.
4402 if (!TheLoop->contains(Instr)) {
4403 LoopInvariants.insert(Instr);
4407 // Overwrite previous end points.
4408 EndPoint[Instr] = Index;
4414 // Saves the list of intervals that end with the index in 'key'.
4415 typedef SmallVector<Instruction*, 2> InstrList;
4416 DenseMap<unsigned, InstrList> TransposeEnds;
4418 // Transpose the EndPoints to a list of values that end at each index.
4419 for (IntervalMap::iterator it = EndPoint.begin(), e = EndPoint.end();
4421 TransposeEnds[it->second].push_back(it->first);
4423 SmallSet<Instruction*, 8> OpenIntervals;
4424 unsigned MaxUsage = 0;
4427 DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
4428 for (unsigned int i = 0; i < Index; ++i) {
4429 Instruction *I = IdxToInstr[i];
4430 // Ignore instructions that are never used within the loop.
4431 if (!Ends.count(I)) continue;
4433 // Remove all of the instructions that end at this location.
4434 InstrList &List = TransposeEnds[i];
4435 for (unsigned int j=0, e = List.size(); j < e; ++j)
4436 OpenIntervals.erase(List[j]);
4438 // Count the number of live interals.
4439 MaxUsage = std::max(MaxUsage, OpenIntervals.size());
4441 DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # " <<
4442 OpenIntervals.size() <<"\n");
4444 // Add the current instruction to the list of open intervals.
4445 OpenIntervals.insert(I);
4448 unsigned Invariant = LoopInvariants.size();
4449 DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsage << " \n");
4450 DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << " \n");
4451 DEBUG(dbgs() << "LV(REG): LoopSize: " << R.NumInstructions << " \n");
4453 R.LoopInvariantRegs = Invariant;
4454 R.MaxLocalUsers = MaxUsage;
4458 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
4462 for (Loop::block_iterator bb = TheLoop->block_begin(),
4463 be = TheLoop->block_end(); bb != be; ++bb) {
4464 unsigned BlockCost = 0;
4465 BasicBlock *BB = *bb;
4467 // For each instruction in the old loop.
4468 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
4469 // Skip dbg intrinsics.
4470 if (isa<DbgInfoIntrinsic>(it))
4473 unsigned C = getInstructionCost(it, VF);
4475 DEBUG(dbgs() << "LV: Found an estimated cost of "<< C <<" for VF " <<
4476 VF << " For instruction: "<< *it << "\n");
4479 // We assume that if-converted blocks have a 50% chance of being executed.
4480 // When the code is scalar then some of the blocks are avoided due to CF.
4481 // When the code is vectorized we execute all code paths.
4482 if (Legal->blockNeedsPredication(*bb) && VF == 1)
4492 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
4493 // If we know that this instruction will remain uniform, check the cost of
4494 // the scalar version.
4495 if (Legal->isUniformAfterVectorization(I))
4498 Type *RetTy = I->getType();
4499 Type *VectorTy = ToVectorTy(RetTy, VF);
4501 // TODO: We need to estimate the cost of intrinsic calls.
4502 switch (I->getOpcode()) {
4503 case Instruction::GetElementPtr:
4504 // We mark this instruction as zero-cost because the cost of GEPs in
4505 // vectorized code depends on whether the corresponding memory instruction
4506 // is scalarized or not. Therefore, we handle GEPs with the memory
4507 // instruction cost.
4509 case Instruction::Br: {
4510 return TTI.getCFInstrCost(I->getOpcode());
4512 case Instruction::PHI:
4513 //TODO: IF-converted IFs become selects.
4515 case Instruction::Add:
4516 case Instruction::FAdd:
4517 case Instruction::Sub:
4518 case Instruction::FSub:
4519 case Instruction::Mul:
4520 case Instruction::FMul:
4521 case Instruction::UDiv:
4522 case Instruction::SDiv:
4523 case Instruction::FDiv:
4524 case Instruction::URem:
4525 case Instruction::SRem:
4526 case Instruction::FRem:
4527 case Instruction::Shl:
4528 case Instruction::LShr:
4529 case Instruction::AShr:
4530 case Instruction::And:
4531 case Instruction::Or:
4532 case Instruction::Xor: {
4533 // Certain instructions can be cheaper to vectorize if they have a constant
4534 // second vector operand. One example of this are shifts on x86.
4535 TargetTransformInfo::OperandValueKind Op1VK =
4536 TargetTransformInfo::OK_AnyValue;
4537 TargetTransformInfo::OperandValueKind Op2VK =
4538 TargetTransformInfo::OK_AnyValue;
4540 if (isa<ConstantInt>(I->getOperand(1)))
4541 Op2VK = TargetTransformInfo::OK_UniformConstantValue;
4543 return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy, Op1VK, Op2VK);
4545 case Instruction::Select: {
4546 SelectInst *SI = cast<SelectInst>(I);
4547 const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
4548 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
4549 Type *CondTy = SI->getCondition()->getType();
4551 CondTy = VectorType::get(CondTy, VF);
4553 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
4555 case Instruction::ICmp:
4556 case Instruction::FCmp: {
4557 Type *ValTy = I->getOperand(0)->getType();
4558 VectorTy = ToVectorTy(ValTy, VF);
4559 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy);
4561 case Instruction::Store:
4562 case Instruction::Load: {
4563 StoreInst *SI = dyn_cast<StoreInst>(I);
4564 LoadInst *LI = dyn_cast<LoadInst>(I);
4565 Type *ValTy = (SI ? SI->getValueOperand()->getType() :
4567 VectorTy = ToVectorTy(ValTy, VF);
4569 unsigned Alignment = SI ? SI->getAlignment() : LI->getAlignment();
4570 unsigned AS = SI ? SI->getPointerAddressSpace() :
4571 LI->getPointerAddressSpace();
4572 Value *Ptr = SI ? SI->getPointerOperand() : LI->getPointerOperand();
4573 // We add the cost of address computation here instead of with the gep
4574 // instruction because only here we know whether the operation is
4577 return TTI.getAddressComputationCost(VectorTy) +
4578 TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
4580 // Scalarized loads/stores.
4581 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
4582 bool Reverse = ConsecutiveStride < 0;
4583 unsigned ScalarAllocatedSize = DL->getTypeAllocSize(ValTy);
4584 unsigned VectorElementSize = DL->getTypeStoreSize(VectorTy)/VF;
4585 if (!ConsecutiveStride || ScalarAllocatedSize != VectorElementSize) {
4587 // The cost of extracting from the value vector and pointer vector.
4588 Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
4589 for (unsigned i = 0; i < VF; ++i) {
4590 // The cost of extracting the pointer operand.
4591 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
4592 // In case of STORE, the cost of ExtractElement from the vector.
4593 // In case of LOAD, the cost of InsertElement into the returned
4595 Cost += TTI.getVectorInstrCost(SI ? Instruction::ExtractElement :
4596 Instruction::InsertElement,
4600 // The cost of the scalar loads/stores.
4601 Cost += VF * TTI.getAddressComputationCost(ValTy->getScalarType());
4602 Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(),
4607 // Wide load/stores.
4608 unsigned Cost = TTI.getAddressComputationCost(VectorTy);
4609 Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
4612 Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
4616 case Instruction::ZExt:
4617 case Instruction::SExt:
4618 case Instruction::FPToUI:
4619 case Instruction::FPToSI:
4620 case Instruction::FPExt:
4621 case Instruction::PtrToInt:
4622 case Instruction::IntToPtr:
4623 case Instruction::SIToFP:
4624 case Instruction::UIToFP:
4625 case Instruction::Trunc:
4626 case Instruction::FPTrunc:
4627 case Instruction::BitCast: {
4628 // We optimize the truncation of induction variable.
4629 // The cost of these is the same as the scalar operation.
4630 if (I->getOpcode() == Instruction::Trunc &&
4631 Legal->isInductionVariable(I->getOperand(0)))
4632 return TTI.getCastInstrCost(I->getOpcode(), I->getType(),
4633 I->getOperand(0)->getType());
4635 Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
4636 return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
4638 case Instruction::Call: {
4639 CallInst *CI = cast<CallInst>(I);
4640 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
4641 assert(ID && "Not an intrinsic call!");
4642 Type *RetTy = ToVectorTy(CI->getType(), VF);
4643 SmallVector<Type*, 4> Tys;
4644 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
4645 Tys.push_back(ToVectorTy(CI->getArgOperand(i)->getType(), VF));
4646 return TTI.getIntrinsicInstrCost(ID, RetTy, Tys);
4649 // We are scalarizing the instruction. Return the cost of the scalar
4650 // instruction, plus the cost of insert and extract into vector
4651 // elements, times the vector width.
4654 if (!RetTy->isVoidTy() && VF != 1) {
4655 unsigned InsCost = TTI.getVectorInstrCost(Instruction::InsertElement,
4657 unsigned ExtCost = TTI.getVectorInstrCost(Instruction::ExtractElement,
4660 // The cost of inserting the results plus extracting each one of the
4662 Cost += VF * (InsCost + ExtCost * I->getNumOperands());
4665 // The cost of executing VF copies of the scalar instruction. This opcode
4666 // is unknown. Assume that it is the same as 'mul'.
4667 Cost += VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy);
4673 Type* LoopVectorizationCostModel::ToVectorTy(Type *Scalar, unsigned VF) {
4674 if (Scalar->isVoidTy() || VF == 1)
4676 return VectorType::get(Scalar, VF);
4679 char LoopVectorize::ID = 0;
4680 static const char lv_name[] = "Loop Vectorization";
4681 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
4682 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
4683 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
4684 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
4685 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
4686 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
4689 Pass *createLoopVectorizePass() {
4690 return new LoopVectorize();
4694 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
4695 // Check for a store.
4696 if (StoreInst *ST = dyn_cast<StoreInst>(Inst))
4697 return Legal->isConsecutivePtr(ST->getPointerOperand()) != 0;
4699 // Check for a load.
4700 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
4701 return Legal->isConsecutivePtr(LI->getPointerOperand()) != 0;