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. Legalization of the IR is done
12 // in the codegen. However, the vectorizer uses (will use) the codegen
13 // interfaces to generate IR that is likely to result in an optimal binary.
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/MapVector.h"
51 #include "llvm/ADT/SmallPtrSet.h"
52 #include "llvm/ADT/SmallSet.h"
53 #include "llvm/ADT/SmallVector.h"
54 #include "llvm/ADT/StringExtras.h"
55 #include "llvm/Analysis/AliasAnalysis.h"
56 #include "llvm/Analysis/AliasSetTracker.h"
57 #include "llvm/Analysis/Dominators.h"
58 #include "llvm/Analysis/LoopInfo.h"
59 #include "llvm/Analysis/LoopIterator.h"
60 #include "llvm/Analysis/LoopPass.h"
61 #include "llvm/Analysis/ScalarEvolution.h"
62 #include "llvm/Analysis/ScalarEvolutionExpander.h"
63 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
64 #include "llvm/Analysis/TargetTransformInfo.h"
65 #include "llvm/Analysis/ValueTracking.h"
66 #include "llvm/Analysis/Verifier.h"
67 #include "llvm/IR/Constants.h"
68 #include "llvm/IR/DataLayout.h"
69 #include "llvm/IR/DerivedTypes.h"
70 #include "llvm/IR/Function.h"
71 #include "llvm/IR/IRBuilder.h"
72 #include "llvm/IR/Instructions.h"
73 #include "llvm/IR/IntrinsicInst.h"
74 #include "llvm/IR/LLVMContext.h"
75 #include "llvm/IR/Module.h"
76 #include "llvm/IR/Type.h"
77 #include "llvm/IR/Value.h"
78 #include "llvm/Pass.h"
79 #include "llvm/Support/CommandLine.h"
80 #include "llvm/Support/Debug.h"
81 #include "llvm/Support/raw_ostream.h"
82 #include "llvm/Target/TargetLibraryInfo.h"
83 #include "llvm/Transforms/Scalar.h"
84 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
85 #include "llvm/Transforms/Utils/Local.h"
91 static cl::opt<unsigned>
92 VectorizationFactor("force-vector-width", cl::init(0), cl::Hidden,
93 cl::desc("Sets the SIMD width. Zero is autoselect."));
95 static cl::opt<unsigned>
96 VectorizationUnroll("force-vector-unroll", cl::init(0), cl::Hidden,
97 cl::desc("Sets the vectorization unroll count. "
98 "Zero is autoselect."));
101 EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
102 cl::desc("Enable if-conversion during vectorization."));
104 /// We don't vectorize loops with a known constant trip count below this number.
105 static cl::opt<unsigned>
106 TinyTripCountVectorThreshold("vectorizer-min-trip-count", cl::init(16),
108 cl::desc("Don't vectorize loops with a constant "
109 "trip count that is smaller than this "
112 /// We don't unroll loops with a known constant trip count below this number.
113 static const unsigned TinyTripCountUnrollThreshold = 128;
115 /// When performing a runtime memory check, do not check more than this
116 /// number of pointers. Notice that the check is quadratic!
117 static const unsigned RuntimeMemoryCheckThreshold = 4;
119 /// We use a metadata with this name to indicate that a scalar loop was
120 /// vectorized and that we don't need to re-vectorize it if we run into it
123 AlreadyVectorizedMDName = "llvm.vectorizer.already_vectorized";
127 // Forward declarations.
128 class LoopVectorizationLegality;
129 class LoopVectorizationCostModel;
131 /// InnerLoopVectorizer vectorizes loops which contain only one basic
132 /// block to a specified vectorization factor (VF).
133 /// This class performs the widening of scalars into vectors, or multiple
134 /// scalars. This class also implements the following features:
135 /// * It inserts an epilogue loop for handling loops that don't have iteration
136 /// counts that are known to be a multiple of the vectorization factor.
137 /// * It handles the code generation for reduction variables.
138 /// * Scalarization (implementation using scalars) of un-vectorizable
140 /// InnerLoopVectorizer does not perform any vectorization-legality
141 /// checks, and relies on the caller to check for the different legality
142 /// aspects. The InnerLoopVectorizer relies on the
143 /// LoopVectorizationLegality class to provide information about the induction
144 /// and reduction variables that were found to a given vectorization factor.
145 class InnerLoopVectorizer {
147 InnerLoopVectorizer(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
148 DominatorTree *DT, DataLayout *DL,
149 const TargetLibraryInfo *TLI, unsigned VecWidth,
150 unsigned UnrollFactor)
151 : OrigLoop(OrigLoop), SE(SE), LI(LI), DT(DT), DL(DL), TLI(TLI),
152 VF(VecWidth), UF(UnrollFactor), Builder(SE->getContext()), Induction(0),
153 OldInduction(0), WidenMap(UnrollFactor) {}
155 // Perform the actual loop widening (vectorization).
156 void vectorize(LoopVectorizationLegality *Legal) {
157 // Create a new empty loop. Unlink the old loop and connect the new one.
158 createEmptyLoop(Legal);
159 // Widen each instruction in the old loop to a new one in the new loop.
160 // Use the Legality module to find the induction and reduction variables.
161 vectorizeLoop(Legal);
162 // Register the new loop and update the analysis passes.
167 /// A small list of PHINodes.
168 typedef SmallVector<PHINode*, 4> PhiVector;
169 /// When we unroll loops we have multiple vector values for each scalar.
170 /// This data structure holds the unrolled and vectorized values that
171 /// originated from one scalar instruction.
172 typedef SmallVector<Value*, 2> VectorParts;
174 /// Add code that checks at runtime if the accessed arrays overlap.
175 /// Returns the comparator value or NULL if no check is needed.
176 Instruction *addRuntimeCheck(LoopVectorizationLegality *Legal,
178 /// Create an empty loop, based on the loop ranges of the old loop.
179 void createEmptyLoop(LoopVectorizationLegality *Legal);
180 /// Copy and widen the instructions from the old loop.
181 void vectorizeLoop(LoopVectorizationLegality *Legal);
183 /// A helper function that computes the predicate of the block BB, assuming
184 /// that the header block of the loop is set to True. It returns the *entry*
185 /// mask for the block BB.
186 VectorParts createBlockInMask(BasicBlock *BB);
187 /// A helper function that computes the predicate of the edge between SRC
189 VectorParts createEdgeMask(BasicBlock *Src, BasicBlock *Dst);
191 /// A helper function to vectorize a single BB within the innermost loop.
192 void vectorizeBlockInLoop(LoopVectorizationLegality *Legal, BasicBlock *BB,
195 /// Insert the new loop to the loop hierarchy and pass manager
196 /// and update the analysis passes.
197 void updateAnalysis();
199 /// This instruction is un-vectorizable. Implement it as a sequence
201 void scalarizeInstruction(Instruction *Instr);
203 /// Vectorize Load and Store instructions,
204 void vectorizeMemoryInstruction(Instruction *Instr,
205 LoopVectorizationLegality *Legal);
207 /// Create a broadcast instruction. This method generates a broadcast
208 /// instruction (shuffle) for loop invariant values and for the induction
209 /// value. If this is the induction variable then we extend it to N, N+1, ...
210 /// this is needed because each iteration in the loop corresponds to a SIMD
212 Value *getBroadcastInstrs(Value *V);
214 /// This function adds 0, 1, 2 ... to each vector element, starting at zero.
215 /// If Negate is set then negative numbers are added e.g. (0, -1, -2, ...).
216 /// The sequence starts at StartIndex.
217 Value *getConsecutiveVector(Value* Val, unsigned StartIdx, bool Negate);
219 /// When we go over instructions in the basic block we rely on previous
220 /// values within the current basic block or on loop invariant values.
221 /// When we widen (vectorize) values we place them in the map. If the values
222 /// are not within the map, they have to be loop invariant, so we simply
223 /// broadcast them into a vector.
224 VectorParts &getVectorValue(Value *V);
226 /// Generate a shuffle sequence that will reverse the vector Vec.
227 Value *reverseVector(Value *Vec);
229 /// This is a helper class that holds the vectorizer state. It maps scalar
230 /// instructions to vector instructions. When the code is 'unrolled' then
231 /// then a single scalar value is mapped to multiple vector parts. The parts
232 /// are stored in the VectorPart type.
234 /// C'tor. UnrollFactor controls the number of vectors ('parts') that
236 ValueMap(unsigned UnrollFactor) : UF(UnrollFactor) {}
238 /// \return True if 'Key' is saved in the Value Map.
239 bool has(Value *Key) const { return MapStorage.count(Key); }
241 /// Initializes a new entry in the map. Sets all of the vector parts to the
242 /// save value in 'Val'.
243 /// \return A reference to a vector with splat values.
244 VectorParts &splat(Value *Key, Value *Val) {
245 VectorParts &Entry = MapStorage[Key];
246 Entry.assign(UF, Val);
250 ///\return A reference to the value that is stored at 'Key'.
251 VectorParts &get(Value *Key) {
252 VectorParts &Entry = MapStorage[Key];
255 assert(Entry.size() == UF);
260 /// The unroll factor. Each entry in the map stores this number of vector
264 /// Map storage. We use std::map and not DenseMap because insertions to a
265 /// dense map invalidates its iterators.
266 std::map<Value *, VectorParts> MapStorage;
269 /// The original loop.
271 /// Scev analysis to use.
279 /// Target Library Info.
280 const TargetLibraryInfo *TLI;
282 /// The vectorization SIMD factor to use. Each vector will have this many
285 /// The vectorization unroll factor to use. Each scalar is vectorized to this
286 /// many different vector instructions.
289 /// The builder that we use
292 // --- Vectorization state ---
294 /// The vector-loop preheader.
295 BasicBlock *LoopVectorPreHeader;
296 /// The scalar-loop preheader.
297 BasicBlock *LoopScalarPreHeader;
298 /// Middle Block between the vector and the scalar.
299 BasicBlock *LoopMiddleBlock;
300 ///The ExitBlock of the scalar loop.
301 BasicBlock *LoopExitBlock;
302 ///The vector loop body.
303 BasicBlock *LoopVectorBody;
304 ///The scalar loop body.
305 BasicBlock *LoopScalarBody;
306 /// A list of all bypass blocks. The first block is the entry of the loop.
307 SmallVector<BasicBlock *, 4> LoopBypassBlocks;
309 /// The new Induction variable which was added to the new block.
311 /// The induction variable of the old basic block.
312 PHINode *OldInduction;
313 /// Maps scalars to widened vectors.
317 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
318 /// to what vectorization factor.
319 /// This class does not look at the profitability of vectorization, only the
320 /// legality. This class has two main kinds of checks:
321 /// * Memory checks - The code in canVectorizeMemory checks if vectorization
322 /// will change the order of memory accesses in a way that will change the
323 /// correctness of the program.
324 /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
325 /// checks for a number of different conditions, such as the availability of a
326 /// single induction variable, that all types are supported and vectorize-able,
327 /// etc. This code reflects the capabilities of InnerLoopVectorizer.
328 /// This class is also used by InnerLoopVectorizer for identifying
329 /// induction variable and the different reduction variables.
330 class LoopVectorizationLegality {
332 LoopVectorizationLegality(Loop *L, ScalarEvolution *SE, DataLayout *DL,
333 DominatorTree *DT, TargetTransformInfo* TTI,
334 AliasAnalysis *AA, TargetLibraryInfo *TLI)
335 : TheLoop(L), SE(SE), DL(DL), DT(DT), TTI(TTI), AA(AA), TLI(TLI),
338 /// This enum represents the kinds of reductions that we support.
340 RK_NoReduction, ///< Not a reduction.
341 RK_IntegerAdd, ///< Sum of integers.
342 RK_IntegerMult, ///< Product of integers.
343 RK_IntegerOr, ///< Bitwise or logical OR of numbers.
344 RK_IntegerAnd, ///< Bitwise or logical AND of numbers.
345 RK_IntegerXor, ///< Bitwise or logical XOR of numbers.
346 RK_IntegerMinMax, //< Min/max implemented in terms of select(cmp()).
347 RK_FloatAdd, ///< Sum of floats.
348 RK_FloatMult ///< Product of floats.
351 /// This enum represents the kinds of inductions that we support.
353 IK_NoInduction, ///< Not an induction variable.
354 IK_IntInduction, ///< Integer induction variable. Step = 1.
355 IK_ReverseIntInduction, ///< Reverse int induction variable. Step = -1.
356 IK_PtrInduction, ///< Pointer induction var. Step = sizeof(elem).
357 IK_ReversePtrInduction ///< Reverse ptr indvar. Step = - sizeof(elem).
360 /// This POD struct holds information about reduction variables.
361 struct ReductionDescriptor {
362 ReductionDescriptor() : StartValue(0), LoopExitInstr(0),
363 Kind(RK_NoReduction) {}
365 ReductionDescriptor(Value *Start, Instruction *Exit, ReductionKind K,
366 CmpInst::Predicate P)
367 : StartValue(Start), LoopExitInstr(Exit), Kind(K), MinMaxPred(P) {}
369 // The starting value of the reduction.
370 // It does not have to be zero!
372 // The instruction who's value is used outside the loop.
373 Instruction *LoopExitInstr;
374 // The kind of the reduction.
376 // If this a min/max reduction the kind of reduction.
377 CmpInst::Predicate MinMaxPred;
380 /// This POD struct holds information about a potential reduction operation.
381 struct ReductionInstDesc {
382 ReductionInstDesc(bool IsRedux, Instruction *I) :
383 IsReduction(IsRedux), PatternLastInst(I), Predicate(ICmpInst::ICMP_EQ) {}
385 ReductionInstDesc(Instruction *I, CmpInst::Predicate P) :
386 IsReduction(true), PatternLastInst(I), Predicate(P) {}
388 // Is this instruction a reduction candidate.
390 // The last instruction in a min/max pattern (select of the select(icmp())
391 // pattern), or the current reduction instruction otherwise.
392 Instruction *PatternLastInst;
393 // If this is a min/max pattern the comparison predicate.
394 CmpInst::Predicate Predicate;
397 // This POD struct holds information about the memory runtime legality
398 // check that a group of pointers do not overlap.
399 struct RuntimePointerCheck {
400 RuntimePointerCheck() : Need(false) {}
402 /// Reset the state of the pointer runtime information.
410 /// Insert a pointer and calculate the start and end SCEVs.
411 void insert(ScalarEvolution *SE, Loop *Lp, Value *Ptr);
413 /// This flag indicates if we need to add the runtime check.
415 /// Holds the pointers that we need to check.
416 SmallVector<Value*, 2> Pointers;
417 /// Holds the pointer value at the beginning of the loop.
418 SmallVector<const SCEV*, 2> Starts;
419 /// Holds the pointer value at the end of the loop.
420 SmallVector<const SCEV*, 2> Ends;
423 /// A POD for saving information about induction variables.
424 struct InductionInfo {
425 InductionInfo(Value *Start, InductionKind K) : StartValue(Start), IK(K) {}
426 InductionInfo() : StartValue(0), IK(IK_NoInduction) {}
433 /// ReductionList contains the reduction descriptors for all
434 /// of the reductions that were found in the loop.
435 typedef DenseMap<PHINode*, ReductionDescriptor> ReductionList;
437 /// InductionList saves induction variables and maps them to the
438 /// induction descriptor.
439 typedef MapVector<PHINode*, InductionInfo> InductionList;
441 /// Alias(Multi)Map stores the values (GEPs or underlying objects and their
442 /// respective Store/Load instruction(s) to calculate aliasing.
443 typedef MapVector<Value*, Instruction* > AliasMap;
444 typedef DenseMap<Value*, std::vector<Instruction*> > AliasMultiMap;
446 /// Returns true if it is legal to vectorize this loop.
447 /// This does not mean that it is profitable to vectorize this
448 /// loop, only that it is legal to do so.
451 /// Returns the Induction variable.
452 PHINode *getInduction() { return Induction; }
454 /// Returns the reduction variables found in the loop.
455 ReductionList *getReductionVars() { return &Reductions; }
457 /// Returns the induction variables found in the loop.
458 InductionList *getInductionVars() { return &Inductions; }
460 /// Returns True if V is an induction variable in this loop.
461 bool isInductionVariable(const Value *V);
463 /// Return true if the block BB needs to be predicated in order for the loop
464 /// to be vectorized.
465 bool blockNeedsPredication(BasicBlock *BB);
467 /// Check if this pointer is consecutive when vectorizing. This happens
468 /// when the last index of the GEP is the induction variable, or that the
469 /// pointer itself is an induction variable.
470 /// This check allows us to vectorize A[idx] into a wide load/store.
472 /// 0 - Stride is unknown or non consecutive.
473 /// 1 - Address is consecutive.
474 /// -1 - Address is consecutive, and decreasing.
475 int isConsecutivePtr(Value *Ptr);
477 /// Returns true if the value V is uniform within the loop.
478 bool isUniform(Value *V);
480 /// Returns true if this instruction will remain scalar after vectorization.
481 bool isUniformAfterVectorization(Instruction* I) { return Uniforms.count(I); }
483 /// Returns the information that we collected about runtime memory check.
484 RuntimePointerCheck *getRuntimePointerCheck() { return &PtrRtCheck; }
486 /// Check if a single basic block loop is vectorizable.
487 /// At this point we know that this is a loop with a constant trip count
488 /// and we only need to check individual instructions.
489 bool canVectorizeInstrs();
491 /// When we vectorize loops we may change the order in which
492 /// we read and write from memory. This method checks if it is
493 /// legal to vectorize the code, considering only memory constrains.
494 /// Returns true if the loop is vectorizable
495 bool canVectorizeMemory();
497 /// Return true if we can vectorize this loop using the IF-conversion
499 bool canVectorizeWithIfConvert();
501 /// Collect the variables that need to stay uniform after vectorization.
502 void collectLoopUniforms();
504 /// Return true if all of the instructions in the block can be speculatively
506 bool blockCanBePredicated(BasicBlock *BB);
508 /// Returns True, if 'Phi' is the kind of reduction variable for type
509 /// 'Kind'. If this is a reduction variable, it adds it to ReductionList.
510 bool AddReductionVar(PHINode *Phi, ReductionKind Kind);
511 /// Returns a struct describing if the instruction 'I' can be a reduction
512 /// variable of type 'Kind'. If the reduction is a min/max pattern of
513 /// select(icmp()) this function advances the instruction pointer 'I' from the
514 /// compare instruction to the select instruction and stores this pointer in
515 /// 'PatternLastInst' member of the returned struct.
516 ReductionInstDesc isReductionInstr(Instruction *I, ReductionKind Kind,
517 ReductionInstDesc Desc);
518 /// Returns the induction kind of Phi. This function may return NoInduction
519 /// if the PHI is not an induction variable.
520 InductionKind isInductionVariable(PHINode *Phi);
521 /// Return true if can compute the address bounds of Ptr within the loop.
522 bool hasComputableBounds(Value *Ptr);
523 /// Return true if there is the chance of write reorder.
524 bool hasPossibleGlobalWriteReorder(Value *Object,
526 AliasMultiMap &WriteObjects,
527 unsigned MaxByteWidth);
528 /// Return the AA location for a load or a store.
529 AliasAnalysis::Location getLoadStoreLocation(Instruction *Inst);
532 /// The loop that we evaluate.
536 /// DataLayout analysis.
541 TargetTransformInfo *TTI;
544 /// Target Library Info.
545 TargetLibraryInfo *TLI;
547 // --- vectorization state --- //
549 /// Holds the integer induction variable. This is the counter of the
552 /// Holds the reduction variables.
553 ReductionList Reductions;
554 /// Holds all of the induction variables that we found in the loop.
555 /// Notice that inductions don't need to start at zero and that induction
556 /// variables can be pointers.
557 InductionList Inductions;
559 /// Allowed outside users. This holds the reduction
560 /// vars which can be accessed from outside the loop.
561 SmallPtrSet<Value*, 4> AllowedExit;
562 /// This set holds the variables which are known to be uniform after
564 SmallPtrSet<Instruction*, 4> Uniforms;
565 /// We need to check that all of the pointers in this list are disjoint
567 RuntimePointerCheck PtrRtCheck;
570 /// LoopVectorizationCostModel - estimates the expected speedups due to
572 /// In many cases vectorization is not profitable. This can happen because of
573 /// a number of reasons. In this class we mainly attempt to predict the
574 /// expected speedup/slowdowns due to the supported instruction set. We use the
575 /// TargetTransformInfo to query the different backends for the cost of
576 /// different operations.
577 class LoopVectorizationCostModel {
579 LoopVectorizationCostModel(Loop *L, ScalarEvolution *SE, LoopInfo *LI,
580 LoopVectorizationLegality *Legal,
581 const TargetTransformInfo &TTI,
582 DataLayout *DL, const TargetLibraryInfo *TLI)
583 : TheLoop(L), SE(SE), LI(LI), Legal(Legal), TTI(TTI), DL(DL), TLI(TLI) {}
585 /// Information about vectorization costs
586 struct VectorizationFactor {
587 unsigned Width; // Vector width with best cost
588 unsigned Cost; // Cost of the loop with that width
590 /// \return The most profitable vectorization factor and the cost of that VF.
591 /// This method checks every power of two up to VF. If UserVF is not ZERO
592 /// then this vectorization factor will be selected if vectorization is
594 VectorizationFactor selectVectorizationFactor(bool OptForSize,
597 /// \return The size (in bits) of the widest type in the code that
598 /// needs to be vectorized. We ignore values that remain scalar such as
599 /// 64 bit loop indices.
600 unsigned getWidestType();
602 /// \return The most profitable unroll factor.
603 /// If UserUF is non-zero then this method finds the best unroll-factor
604 /// based on register pressure and other parameters.
605 /// VF and LoopCost are the selected vectorization factor and the cost of the
607 unsigned selectUnrollFactor(bool OptForSize, unsigned UserUF, unsigned VF,
610 /// \brief A struct that represents some properties of the register usage
612 struct RegisterUsage {
613 /// Holds the number of loop invariant values that are used in the loop.
614 unsigned LoopInvariantRegs;
615 /// Holds the maximum number of concurrent live intervals in the loop.
616 unsigned MaxLocalUsers;
617 /// Holds the number of instructions in the loop.
618 unsigned NumInstructions;
621 /// \return information about the register usage of the loop.
622 RegisterUsage calculateRegisterUsage();
625 /// Returns the expected execution cost. The unit of the cost does
626 /// not matter because we use the 'cost' units to compare different
627 /// vector widths. The cost that is returned is *not* normalized by
628 /// the factor width.
629 unsigned expectedCost(unsigned VF);
631 /// Returns the execution time cost of an instruction for a given vector
632 /// width. Vector width of one means scalar.
633 unsigned getInstructionCost(Instruction *I, unsigned VF);
635 /// A helper function for converting Scalar types to vector types.
636 /// If the incoming type is void, we return void. If the VF is 1, we return
638 static Type* ToVectorTy(Type *Scalar, unsigned VF);
640 /// Returns whether the instruction is a load or store and will be a emitted
641 /// as a vector operation.
642 bool isConsecutiveLoadOrStore(Instruction *I);
644 /// The loop that we evaluate.
648 /// Loop Info analysis.
650 /// Vectorization legality.
651 LoopVectorizationLegality *Legal;
652 /// Vector target information.
653 const TargetTransformInfo &TTI;
654 /// Target data layout information.
656 /// Target Library Info.
657 const TargetLibraryInfo *TLI;
660 /// The LoopVectorize Pass.
661 struct LoopVectorize : public LoopPass {
662 /// Pass identification, replacement for typeid
665 explicit LoopVectorize() : LoopPass(ID) {
666 initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
672 TargetTransformInfo *TTI;
675 TargetLibraryInfo *TLI;
677 virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
678 // We only vectorize innermost loops.
682 SE = &getAnalysis<ScalarEvolution>();
683 DL = getAnalysisIfAvailable<DataLayout>();
684 LI = &getAnalysis<LoopInfo>();
685 TTI = &getAnalysis<TargetTransformInfo>();
686 DT = &getAnalysis<DominatorTree>();
687 AA = getAnalysisIfAvailable<AliasAnalysis>();
688 TLI = getAnalysisIfAvailable<TargetLibraryInfo>();
690 DEBUG(dbgs() << "LV: Checking a loop in \"" <<
691 L->getHeader()->getParent()->getName() << "\"\n");
693 // Check if it is legal to vectorize the loop.
694 LoopVectorizationLegality LVL(L, SE, DL, DT, TTI, AA, TLI);
695 if (!LVL.canVectorize()) {
696 DEBUG(dbgs() << "LV: Not vectorizing.\n");
700 // Use the cost model.
701 LoopVectorizationCostModel CM(L, SE, LI, &LVL, *TTI, DL, TLI);
703 // Check the function attributes to find out if this function should be
704 // optimized for size.
705 Function *F = L->getHeader()->getParent();
706 Attribute::AttrKind SzAttr = Attribute::OptimizeForSize;
707 Attribute::AttrKind FlAttr = Attribute::NoImplicitFloat;
708 unsigned FnIndex = AttributeSet::FunctionIndex;
709 bool OptForSize = F->getAttributes().hasAttribute(FnIndex, SzAttr);
710 bool NoFloat = F->getAttributes().hasAttribute(FnIndex, FlAttr);
713 DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
714 "attribute is used.\n");
718 // Select the optimal vectorization factor.
719 LoopVectorizationCostModel::VectorizationFactor VF;
720 VF = CM.selectVectorizationFactor(OptForSize, VectorizationFactor);
721 // Select the unroll factor.
722 unsigned UF = CM.selectUnrollFactor(OptForSize, VectorizationUnroll,
726 DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
730 DEBUG(dbgs() << "LV: Found a vectorizable loop ("<< VF.Width << ") in "<<
731 F->getParent()->getModuleIdentifier()<<"\n");
732 DEBUG(dbgs() << "LV: Unroll Factor is " << UF << "\n");
734 // If we decided that it is *legal* to vectorize the loop then do it.
735 InnerLoopVectorizer LB(L, SE, LI, DT, DL, TLI, VF.Width, UF);
738 DEBUG(verifyFunction(*L->getHeader()->getParent()));
742 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
743 LoopPass::getAnalysisUsage(AU);
744 AU.addRequiredID(LoopSimplifyID);
745 AU.addRequiredID(LCSSAID);
746 AU.addRequired<DominatorTree>();
747 AU.addRequired<LoopInfo>();
748 AU.addRequired<ScalarEvolution>();
749 AU.addRequired<TargetTransformInfo>();
750 AU.addPreserved<LoopInfo>();
751 AU.addPreserved<DominatorTree>();
756 } // end anonymous namespace
758 //===----------------------------------------------------------------------===//
759 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
760 // LoopVectorizationCostModel.
761 //===----------------------------------------------------------------------===//
764 LoopVectorizationLegality::RuntimePointerCheck::insert(ScalarEvolution *SE,
765 Loop *Lp, Value *Ptr) {
766 const SCEV *Sc = SE->getSCEV(Ptr);
767 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
768 assert(AR && "Invalid addrec expression");
769 const SCEV *Ex = SE->getExitCount(Lp, Lp->getLoopLatch());
770 const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
771 Pointers.push_back(Ptr);
772 Starts.push_back(AR->getStart());
773 Ends.push_back(ScEnd);
776 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
777 // Save the current insertion location.
778 Instruction *Loc = Builder.GetInsertPoint();
780 // We need to place the broadcast of invariant variables outside the loop.
781 Instruction *Instr = dyn_cast<Instruction>(V);
782 bool NewInstr = (Instr && Instr->getParent() == LoopVectorBody);
783 bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
785 // Place the code for broadcasting invariant variables in the new preheader.
787 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
789 // Broadcast the scalar into all locations in the vector.
790 Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
792 // Restore the builder insertion point.
794 Builder.SetInsertPoint(Loc);
799 Value *InnerLoopVectorizer::getConsecutiveVector(Value* Val, unsigned StartIdx,
801 assert(Val->getType()->isVectorTy() && "Must be a vector");
802 assert(Val->getType()->getScalarType()->isIntegerTy() &&
803 "Elem must be an integer");
805 Type *ITy = Val->getType()->getScalarType();
806 VectorType *Ty = cast<VectorType>(Val->getType());
807 int VLen = Ty->getNumElements();
808 SmallVector<Constant*, 8> Indices;
810 // Create a vector of consecutive numbers from zero to VF.
811 for (int i = 0; i < VLen; ++i) {
812 int Idx = Negate ? (-i): i;
813 Indices.push_back(ConstantInt::get(ITy, StartIdx + Idx));
816 // Add the consecutive indices to the vector value.
817 Constant *Cv = ConstantVector::get(Indices);
818 assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
819 return Builder.CreateAdd(Val, Cv, "induction");
822 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
823 assert(Ptr->getType()->isPointerTy() && "Unexpected non ptr");
824 // Make sure that the pointer does not point to structs.
825 if (cast<PointerType>(Ptr->getType())->getElementType()->isAggregateType())
828 // If this value is a pointer induction variable we know it is consecutive.
829 PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
830 if (Phi && Inductions.count(Phi)) {
831 InductionInfo II = Inductions[Phi];
832 if (IK_PtrInduction == II.IK)
834 else if (IK_ReversePtrInduction == II.IK)
838 GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
842 unsigned NumOperands = Gep->getNumOperands();
843 Value *LastIndex = Gep->getOperand(NumOperands - 1);
845 Value *GpPtr = Gep->getPointerOperand();
846 // If this GEP value is a consecutive pointer induction variable and all of
847 // the indices are constant then we know it is consecutive. We can
848 Phi = dyn_cast<PHINode>(GpPtr);
849 if (Phi && Inductions.count(Phi)) {
851 // Make sure that the pointer does not point to structs.
852 PointerType *GepPtrType = cast<PointerType>(GpPtr->getType());
853 if (GepPtrType->getElementType()->isAggregateType())
856 // Make sure that all of the index operands are loop invariant.
857 for (unsigned i = 1; i < NumOperands; ++i)
858 if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
861 InductionInfo II = Inductions[Phi];
862 if (IK_PtrInduction == II.IK)
864 else if (IK_ReversePtrInduction == II.IK)
868 // Check that all of the gep indices are uniform except for the last.
869 for (unsigned i = 0; i < NumOperands - 1; ++i)
870 if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
873 // We can emit wide load/stores only if the last index is the induction
875 const SCEV *Last = SE->getSCEV(LastIndex);
876 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
877 const SCEV *Step = AR->getStepRecurrence(*SE);
879 // The memory is consecutive because the last index is consecutive
880 // and all other indices are loop invariant.
883 if (Step->isAllOnesValue())
890 bool LoopVectorizationLegality::isUniform(Value *V) {
891 return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
894 InnerLoopVectorizer::VectorParts&
895 InnerLoopVectorizer::getVectorValue(Value *V) {
896 assert(V != Induction && "The new induction variable should not be used.");
897 assert(!V->getType()->isVectorTy() && "Can't widen a vector");
899 // If we have this scalar in the map, return it.
901 return WidenMap.get(V);
903 // If this scalar is unknown, assume that it is a constant or that it is
904 // loop invariant. Broadcast V and save the value for future uses.
905 Value *B = getBroadcastInstrs(V);
906 return WidenMap.splat(V, B);
909 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
910 assert(Vec->getType()->isVectorTy() && "Invalid type");
911 SmallVector<Constant*, 8> ShuffleMask;
912 for (unsigned i = 0; i < VF; ++i)
913 ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
915 return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
916 ConstantVector::get(ShuffleMask),
921 void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr,
922 LoopVectorizationLegality *Legal) {
923 // Attempt to issue a wide load.
924 LoadInst *LI = dyn_cast<LoadInst>(Instr);
925 StoreInst *SI = dyn_cast<StoreInst>(Instr);
927 assert((LI || SI) && "Invalid Load/Store instruction");
929 Type *ScalarDataTy = LI ? LI->getType() : SI->getValueOperand()->getType();
930 Type *DataTy = VectorType::get(ScalarDataTy, VF);
931 Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
932 unsigned Alignment = LI ? LI->getAlignment() : SI->getAlignment();
934 // If the pointer is loop invariant or if it is non consecutive,
935 // scalarize the load.
936 int Stride = Legal->isConsecutivePtr(Ptr);
937 bool Reverse = Stride < 0;
938 bool UniformLoad = LI && Legal->isUniform(Ptr);
939 if (Stride == 0 || UniformLoad)
940 return scalarizeInstruction(Instr);
942 Constant *Zero = Builder.getInt32(0);
943 VectorParts &Entry = WidenMap.get(Instr);
945 // Handle consecutive loads/stores.
946 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
947 if (Gep && Legal->isInductionVariable(Gep->getPointerOperand())) {
948 Value *PtrOperand = Gep->getPointerOperand();
949 Value *FirstBasePtr = getVectorValue(PtrOperand)[0];
950 FirstBasePtr = Builder.CreateExtractElement(FirstBasePtr, Zero);
952 // Create the new GEP with the new induction variable.
953 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
954 Gep2->setOperand(0, FirstBasePtr);
955 Gep2->setName("gep.indvar.base");
956 Ptr = Builder.Insert(Gep2);
958 assert(SE->isLoopInvariant(SE->getSCEV(Gep->getPointerOperand()),
959 OrigLoop) && "Base ptr must be invariant");
961 // The last index does not have to be the induction. It can be
962 // consecutive and be a function of the index. For example A[I+1];
963 unsigned NumOperands = Gep->getNumOperands();
965 Value *LastGepOperand = Gep->getOperand(NumOperands - 1);
966 VectorParts &GEPParts = getVectorValue(LastGepOperand);
967 Value *LastIndex = GEPParts[0];
968 LastIndex = Builder.CreateExtractElement(LastIndex, Zero);
970 // Create the new GEP with the new induction variable.
971 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
972 Gep2->setOperand(NumOperands - 1, LastIndex);
973 Gep2->setName("gep.indvar.idx");
974 Ptr = Builder.Insert(Gep2);
976 // Use the induction element ptr.
977 assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
978 VectorParts &PtrVal = getVectorValue(Ptr);
979 Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
984 assert(!Legal->isUniform(SI->getPointerOperand()) &&
985 "We do not allow storing to uniform addresses");
987 VectorParts &StoredVal = getVectorValue(SI->getValueOperand());
988 for (unsigned Part = 0; Part < UF; ++Part) {
989 // Calculate the pointer for the specific unroll-part.
990 Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
993 // If we store to reverse consecutive memory locations then we need
994 // to reverse the order of elements in the stored value.
995 StoredVal[Part] = reverseVector(StoredVal[Part]);
996 // If the address is consecutive but reversed, then the
997 // wide store needs to start at the last vector element.
998 PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
999 PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1002 Value *VecPtr = Builder.CreateBitCast(PartPtr, DataTy->getPointerTo());
1003 Builder.CreateStore(StoredVal[Part], VecPtr)->setAlignment(Alignment);
1007 for (unsigned Part = 0; Part < UF; ++Part) {
1008 // Calculate the pointer for the specific unroll-part.
1009 Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1012 // If the address is consecutive but reversed, then the
1013 // wide store needs to start at the last vector element.
1014 PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1015 PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1018 Value *VecPtr = Builder.CreateBitCast(PartPtr, DataTy->getPointerTo());
1019 Value *LI = Builder.CreateLoad(VecPtr, "wide.load");
1020 cast<LoadInst>(LI)->setAlignment(Alignment);
1021 Entry[Part] = Reverse ? reverseVector(LI) : LI;
1025 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr) {
1026 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
1027 // Holds vector parameters or scalars, in case of uniform vals.
1028 SmallVector<VectorParts, 4> Params;
1030 // Find all of the vectorized parameters.
1031 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
1032 Value *SrcOp = Instr->getOperand(op);
1034 // If we are accessing the old induction variable, use the new one.
1035 if (SrcOp == OldInduction) {
1036 Params.push_back(getVectorValue(SrcOp));
1040 // Try using previously calculated values.
1041 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
1043 // If the src is an instruction that appeared earlier in the basic block
1044 // then it should already be vectorized.
1045 if (SrcInst && OrigLoop->contains(SrcInst)) {
1046 assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
1047 // The parameter is a vector value from earlier.
1048 Params.push_back(WidenMap.get(SrcInst));
1050 // The parameter is a scalar from outside the loop. Maybe even a constant.
1051 VectorParts Scalars;
1052 Scalars.append(UF, SrcOp);
1053 Params.push_back(Scalars);
1057 assert(Params.size() == Instr->getNumOperands() &&
1058 "Invalid number of operands");
1060 // Does this instruction return a value ?
1061 bool IsVoidRetTy = Instr->getType()->isVoidTy();
1063 Value *UndefVec = IsVoidRetTy ? 0 :
1064 UndefValue::get(VectorType::get(Instr->getType(), VF));
1065 // Create a new entry in the WidenMap and initialize it to Undef or Null.
1066 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
1068 // For each scalar that we create:
1069 for (unsigned Width = 0; Width < VF; ++Width) {
1070 // For each vector unroll 'part':
1071 for (unsigned Part = 0; Part < UF; ++Part) {
1072 Instruction *Cloned = Instr->clone();
1074 Cloned->setName(Instr->getName() + ".cloned");
1075 // Replace the operands of the cloned instrucions with extracted scalars.
1076 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
1077 Value *Op = Params[op][Part];
1078 // Param is a vector. Need to extract the right lane.
1079 if (Op->getType()->isVectorTy())
1080 Op = Builder.CreateExtractElement(Op, Builder.getInt32(Width));
1081 Cloned->setOperand(op, Op);
1084 // Place the cloned scalar in the new loop.
1085 Builder.Insert(Cloned);
1087 // If the original scalar returns a value we need to place it in a vector
1088 // so that future users will be able to use it.
1090 VecResults[Part] = Builder.CreateInsertElement(VecResults[Part], Cloned,
1091 Builder.getInt32(Width));
1097 InnerLoopVectorizer::addRuntimeCheck(LoopVectorizationLegality *Legal,
1099 LoopVectorizationLegality::RuntimePointerCheck *PtrRtCheck =
1100 Legal->getRuntimePointerCheck();
1102 if (!PtrRtCheck->Need)
1105 Instruction *MemoryRuntimeCheck = 0;
1106 unsigned NumPointers = PtrRtCheck->Pointers.size();
1107 SmallVector<Value* , 2> Starts;
1108 SmallVector<Value* , 2> Ends;
1110 SCEVExpander Exp(*SE, "induction");
1112 // Use this type for pointer arithmetic.
1113 Type* PtrArithTy = Type::getInt8PtrTy(Loc->getContext(), 0);
1115 for (unsigned i = 0; i < NumPointers; ++i) {
1116 Value *Ptr = PtrRtCheck->Pointers[i];
1117 const SCEV *Sc = SE->getSCEV(Ptr);
1119 if (SE->isLoopInvariant(Sc, OrigLoop)) {
1120 DEBUG(dbgs() << "LV: Adding RT check for a loop invariant ptr:" <<
1122 Starts.push_back(Ptr);
1123 Ends.push_back(Ptr);
1125 DEBUG(dbgs() << "LV: Adding RT check for range:" << *Ptr <<"\n");
1127 Value *Start = Exp.expandCodeFor(PtrRtCheck->Starts[i], PtrArithTy, Loc);
1128 Value *End = Exp.expandCodeFor(PtrRtCheck->Ends[i], PtrArithTy, Loc);
1129 Starts.push_back(Start);
1130 Ends.push_back(End);
1134 IRBuilder<> ChkBuilder(Loc);
1136 for (unsigned i = 0; i < NumPointers; ++i) {
1137 for (unsigned j = i+1; j < NumPointers; ++j) {
1138 Value *Start0 = ChkBuilder.CreateBitCast(Starts[i], PtrArithTy, "bc");
1139 Value *Start1 = ChkBuilder.CreateBitCast(Starts[j], PtrArithTy, "bc");
1140 Value *End0 = ChkBuilder.CreateBitCast(Ends[i], PtrArithTy, "bc");
1141 Value *End1 = ChkBuilder.CreateBitCast(Ends[j], PtrArithTy, "bc");
1143 Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0");
1144 Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1");
1145 Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
1146 if (MemoryRuntimeCheck)
1147 IsConflict = ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict,
1150 MemoryRuntimeCheck = cast<Instruction>(IsConflict);
1154 return MemoryRuntimeCheck;
1158 InnerLoopVectorizer::createEmptyLoop(LoopVectorizationLegality *Legal) {
1160 In this function we generate a new loop. The new loop will contain
1161 the vectorized instructions while the old loop will continue to run the
1164 [ ] <-- vector loop bypass (may consist of multiple blocks).
1167 | [ ] <-- vector pre header.
1171 | [ ]_| <-- vector loop.
1174 >[ ] <--- middle-block.
1177 | [ ] <--- new preheader.
1181 | [ ]_| <-- old scalar loop to handle remainder.
1184 >[ ] <-- exit block.
1188 BasicBlock *OldBasicBlock = OrigLoop->getHeader();
1189 BasicBlock *BypassBlock = OrigLoop->getLoopPreheader();
1190 BasicBlock *ExitBlock = OrigLoop->getExitBlock();
1191 assert(ExitBlock && "Must have an exit block");
1193 // Mark the old scalar loop with metadata that tells us not to vectorize this
1194 // loop again if we run into it.
1195 MDNode *MD = MDNode::get(OldBasicBlock->getContext(), ArrayRef<Value*>());
1196 OldBasicBlock->getTerminator()->setMetadata(AlreadyVectorizedMDName, MD);
1198 // Some loops have a single integer induction variable, while other loops
1199 // don't. One example is c++ iterators that often have multiple pointer
1200 // induction variables. In the code below we also support a case where we
1201 // don't have a single induction variable.
1202 OldInduction = Legal->getInduction();
1203 Type *IdxTy = OldInduction ? OldInduction->getType() :
1204 DL->getIntPtrType(SE->getContext());
1206 // Find the loop boundaries.
1207 const SCEV *ExitCount = SE->getExitCount(OrigLoop, OrigLoop->getLoopLatch());
1208 assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
1210 // Get the total trip count from the count by adding 1.
1211 ExitCount = SE->getAddExpr(ExitCount,
1212 SE->getConstant(ExitCount->getType(), 1));
1214 // Expand the trip count and place the new instructions in the preheader.
1215 // Notice that the pre-header does not change, only the loop body.
1216 SCEVExpander Exp(*SE, "induction");
1218 // Count holds the overall loop count (N).
1219 Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
1220 BypassBlock->getTerminator());
1222 // The loop index does not have to start at Zero. Find the original start
1223 // value from the induction PHI node. If we don't have an induction variable
1224 // then we know that it starts at zero.
1225 Value *StartIdx = OldInduction ?
1226 OldInduction->getIncomingValueForBlock(BypassBlock):
1227 ConstantInt::get(IdxTy, 0);
1229 assert(BypassBlock && "Invalid loop structure");
1230 LoopBypassBlocks.push_back(BypassBlock);
1232 // Split the single block loop into the two loop structure described above.
1233 BasicBlock *VectorPH =
1234 BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
1235 BasicBlock *VecBody =
1236 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
1237 BasicBlock *MiddleBlock =
1238 VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
1239 BasicBlock *ScalarPH =
1240 MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
1242 // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
1244 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
1246 // Generate the induction variable.
1247 Induction = Builder.CreatePHI(IdxTy, 2, "index");
1248 // The loop step is equal to the vectorization factor (num of SIMD elements)
1249 // times the unroll factor (num of SIMD instructions).
1250 Constant *Step = ConstantInt::get(IdxTy, VF * UF);
1252 // This is the IR builder that we use to add all of the logic for bypassing
1253 // the new vector loop.
1254 IRBuilder<> BypassBuilder(BypassBlock->getTerminator());
1256 // We may need to extend the index in case there is a type mismatch.
1257 // We know that the count starts at zero and does not overflow.
1258 if (Count->getType() != IdxTy) {
1259 // The exit count can be of pointer type. Convert it to the correct
1261 if (ExitCount->getType()->isPointerTy())
1262 Count = BypassBuilder.CreatePointerCast(Count, IdxTy, "ptrcnt.to.int");
1264 Count = BypassBuilder.CreateZExtOrTrunc(Count, IdxTy, "cnt.cast");
1267 // Add the start index to the loop count to get the new end index.
1268 Value *IdxEnd = BypassBuilder.CreateAdd(Count, StartIdx, "end.idx");
1270 // Now we need to generate the expression for N - (N % VF), which is
1271 // the part that the vectorized body will execute.
1272 Value *R = BypassBuilder.CreateURem(Count, Step, "n.mod.vf");
1273 Value *CountRoundDown = BypassBuilder.CreateSub(Count, R, "n.vec");
1274 Value *IdxEndRoundDown = BypassBuilder.CreateAdd(CountRoundDown, StartIdx,
1275 "end.idx.rnd.down");
1277 // Now, compare the new count to zero. If it is zero skip the vector loop and
1278 // jump to the scalar loop.
1279 Value *Cmp = BypassBuilder.CreateICmpEQ(IdxEndRoundDown, StartIdx,
1282 BasicBlock *LastBypassBlock = BypassBlock;
1284 // Generate the code that checks in runtime if arrays overlap. We put the
1285 // checks into a separate block to make the more common case of few elements
1287 Instruction *MemRuntimeCheck = addRuntimeCheck(Legal,
1288 BypassBlock->getTerminator());
1289 if (MemRuntimeCheck) {
1290 // Create a new block containing the memory check.
1291 BasicBlock *CheckBlock = BypassBlock->splitBasicBlock(MemRuntimeCheck,
1293 LoopBypassBlocks.push_back(CheckBlock);
1295 // Replace the branch into the memory check block with a conditional branch
1296 // for the "few elements case".
1297 Instruction *OldTerm = BypassBlock->getTerminator();
1298 BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
1299 OldTerm->eraseFromParent();
1301 Cmp = MemRuntimeCheck;
1302 LastBypassBlock = CheckBlock;
1305 LastBypassBlock->getTerminator()->eraseFromParent();
1306 BranchInst::Create(MiddleBlock, VectorPH, Cmp,
1309 // We are going to resume the execution of the scalar loop.
1310 // Go over all of the induction variables that we found and fix the
1311 // PHIs that are left in the scalar version of the loop.
1312 // The starting values of PHI nodes depend on the counter of the last
1313 // iteration in the vectorized loop.
1314 // If we come from a bypass edge then we need to start from the original
1317 // This variable saves the new starting index for the scalar loop.
1318 PHINode *ResumeIndex = 0;
1319 LoopVectorizationLegality::InductionList::iterator I, E;
1320 LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
1321 for (I = List->begin(), E = List->end(); I != E; ++I) {
1322 PHINode *OrigPhi = I->first;
1323 LoopVectorizationLegality::InductionInfo II = I->second;
1324 PHINode *ResumeVal = PHINode::Create(OrigPhi->getType(), 2, "resume.val",
1325 MiddleBlock->getTerminator());
1326 Value *EndValue = 0;
1328 case LoopVectorizationLegality::IK_NoInduction:
1329 llvm_unreachable("Unknown induction");
1330 case LoopVectorizationLegality::IK_IntInduction: {
1331 // Handle the integer induction counter:
1332 assert(OrigPhi->getType()->isIntegerTy() && "Invalid type");
1333 assert(OrigPhi == OldInduction && "Unknown integer PHI");
1334 // We know what the end value is.
1335 EndValue = IdxEndRoundDown;
1336 // We also know which PHI node holds it.
1337 ResumeIndex = ResumeVal;
1340 case LoopVectorizationLegality::IK_ReverseIntInduction: {
1341 // Convert the CountRoundDown variable to the PHI size.
1342 unsigned CRDSize = CountRoundDown->getType()->getScalarSizeInBits();
1343 unsigned IISize = II.StartValue->getType()->getScalarSizeInBits();
1344 Value *CRD = CountRoundDown;
1345 if (CRDSize > IISize)
1346 CRD = CastInst::Create(Instruction::Trunc, CountRoundDown,
1347 II.StartValue->getType(), "tr.crd",
1348 LoopBypassBlocks.back()->getTerminator());
1349 else if (CRDSize < IISize)
1350 CRD = CastInst::Create(Instruction::SExt, CountRoundDown,
1351 II.StartValue->getType(),
1353 LoopBypassBlocks.back()->getTerminator());
1354 // Handle reverse integer induction counter:
1356 BinaryOperator::CreateSub(II.StartValue, CRD, "rev.ind.end",
1357 LoopBypassBlocks.back()->getTerminator());
1360 case LoopVectorizationLegality::IK_PtrInduction: {
1361 // For pointer induction variables, calculate the offset using
1364 GetElementPtrInst::Create(II.StartValue, CountRoundDown, "ptr.ind.end",
1365 LoopBypassBlocks.back()->getTerminator());
1368 case LoopVectorizationLegality::IK_ReversePtrInduction: {
1369 // The value at the end of the loop for the reverse pointer is calculated
1370 // by creating a GEP with a negative index starting from the start value.
1371 Value *Zero = ConstantInt::get(CountRoundDown->getType(), 0);
1372 Value *NegIdx = BinaryOperator::CreateSub(Zero, CountRoundDown,
1374 LoopBypassBlocks.back()->getTerminator());
1375 EndValue = GetElementPtrInst::Create(II.StartValue, NegIdx,
1377 LoopBypassBlocks.back()->getTerminator());
1382 // The new PHI merges the original incoming value, in case of a bypass,
1383 // or the value at the end of the vectorized loop.
1384 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
1385 ResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
1386 ResumeVal->addIncoming(EndValue, VecBody);
1388 // Fix the scalar body counter (PHI node).
1389 unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
1390 OrigPhi->setIncomingValue(BlockIdx, ResumeVal);
1393 // If we are generating a new induction variable then we also need to
1394 // generate the code that calculates the exit value. This value is not
1395 // simply the end of the counter because we may skip the vectorized body
1396 // in case of a runtime check.
1398 assert(!ResumeIndex && "Unexpected resume value found");
1399 ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val",
1400 MiddleBlock->getTerminator());
1401 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
1402 ResumeIndex->addIncoming(StartIdx, LoopBypassBlocks[I]);
1403 ResumeIndex->addIncoming(IdxEndRoundDown, VecBody);
1406 // Make sure that we found the index where scalar loop needs to continue.
1407 assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() &&
1408 "Invalid resume Index");
1410 // Add a check in the middle block to see if we have completed
1411 // all of the iterations in the first vector loop.
1412 // If (N - N%VF) == N, then we *don't* need to run the remainder.
1413 Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd,
1414 ResumeIndex, "cmp.n",
1415 MiddleBlock->getTerminator());
1417 BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
1418 // Remove the old terminator.
1419 MiddleBlock->getTerminator()->eraseFromParent();
1421 // Create i+1 and fill the PHINode.
1422 Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
1423 Induction->addIncoming(StartIdx, VectorPH);
1424 Induction->addIncoming(NextIdx, VecBody);
1425 // Create the compare.
1426 Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown);
1427 Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
1429 // Now we have two terminators. Remove the old one from the block.
1430 VecBody->getTerminator()->eraseFromParent();
1432 // Get ready to start creating new instructions into the vectorized body.
1433 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
1435 // Create and register the new vector loop.
1436 Loop* Lp = new Loop();
1437 Loop *ParentLoop = OrigLoop->getParentLoop();
1439 // Insert the new loop into the loop nest and register the new basic blocks.
1441 ParentLoop->addChildLoop(Lp);
1442 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
1443 ParentLoop->addBasicBlockToLoop(LoopBypassBlocks[I], LI->getBase());
1444 ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase());
1445 ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase());
1446 ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase());
1448 LI->addTopLevelLoop(Lp);
1451 Lp->addBasicBlockToLoop(VecBody, LI->getBase());
1454 LoopVectorPreHeader = VectorPH;
1455 LoopScalarPreHeader = ScalarPH;
1456 LoopMiddleBlock = MiddleBlock;
1457 LoopExitBlock = ExitBlock;
1458 LoopVectorBody = VecBody;
1459 LoopScalarBody = OldBasicBlock;
1462 /// This function returns the identity element (or neutral element) for
1463 /// the operation K.
1465 getReductionIdentity(LoopVectorizationLegality::ReductionKind K, Type *Tp,
1466 CmpInst::Predicate Pred) {
1468 case LoopVectorizationLegality:: RK_IntegerXor:
1469 case LoopVectorizationLegality:: RK_IntegerAdd:
1470 case LoopVectorizationLegality:: RK_IntegerOr:
1471 // Adding, Xoring, Oring zero to a number does not change it.
1472 return ConstantInt::get(Tp, 0);
1473 case LoopVectorizationLegality:: RK_IntegerMult:
1474 // Multiplying a number by 1 does not change it.
1475 return ConstantInt::get(Tp, 1);
1476 case LoopVectorizationLegality:: RK_IntegerAnd:
1477 // AND-ing a number with an all-1 value does not change it.
1478 return ConstantInt::get(Tp, -1, true);
1479 case LoopVectorizationLegality:: RK_FloatMult:
1480 // Multiplying a number by 1 does not change it.
1481 return ConstantFP::get(Tp, 1.0L);
1482 case LoopVectorizationLegality:: RK_FloatAdd:
1483 // Adding zero to a number does not change it.
1484 return ConstantFP::get(Tp, 0.0L);
1485 case LoopVectorizationLegality:: RK_IntegerMinMax:
1487 default: llvm_unreachable("Unknown min/max predicate");
1488 case CmpInst::ICMP_ULT:
1489 case CmpInst::ICMP_ULE:
1490 return ConstantInt::getAllOnesValue(Tp);
1491 case CmpInst::ICMP_UGT:
1492 case CmpInst::ICMP_UGE:
1493 return ConstantInt::get(Tp, 0);
1494 case CmpInst::ICMP_SLT:
1495 case CmpInst::ICMP_SLE: {
1496 unsigned BitWidth = Tp->getPrimitiveSizeInBits();
1497 return ConstantInt::get(Tp->getContext(),
1498 APInt::getSignedMaxValue(BitWidth));
1500 case CmpInst::ICMP_SGT:
1501 case CmpInst::ICMP_SGE: {
1502 unsigned BitWidth = Tp->getPrimitiveSizeInBits();
1503 return ConstantInt::get(Tp->getContext(),
1504 APInt::getSignedMinValue(BitWidth));
1508 llvm_unreachable("Unknown reduction kind");
1512 static Intrinsic::ID
1513 getIntrinsicIDForCall(CallInst *CI, const TargetLibraryInfo *TLI) {
1514 // If we have an intrinsic call, check if it is trivially vectorizable.
1515 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
1516 switch (II->getIntrinsicID()) {
1517 case Intrinsic::sqrt:
1518 case Intrinsic::sin:
1519 case Intrinsic::cos:
1520 case Intrinsic::exp:
1521 case Intrinsic::exp2:
1522 case Intrinsic::log:
1523 case Intrinsic::log10:
1524 case Intrinsic::log2:
1525 case Intrinsic::fabs:
1526 case Intrinsic::floor:
1527 case Intrinsic::ceil:
1528 case Intrinsic::trunc:
1529 case Intrinsic::rint:
1530 case Intrinsic::nearbyint:
1531 case Intrinsic::pow:
1532 case Intrinsic::fma:
1533 case Intrinsic::fmuladd:
1534 return II->getIntrinsicID();
1536 return Intrinsic::not_intrinsic;
1541 return Intrinsic::not_intrinsic;
1544 Function *F = CI->getCalledFunction();
1545 // We're going to make assumptions on the semantics of the functions, check
1546 // that the target knows that it's available in this environment.
1547 if (!F || !TLI->getLibFunc(F->getName(), Func))
1548 return Intrinsic::not_intrinsic;
1550 // Otherwise check if we have a call to a function that can be turned into a
1551 // vector intrinsic.
1558 return Intrinsic::sin;
1562 return Intrinsic::cos;
1566 return Intrinsic::exp;
1568 case LibFunc::exp2f:
1569 case LibFunc::exp2l:
1570 return Intrinsic::exp2;
1574 return Intrinsic::log;
1575 case LibFunc::log10:
1576 case LibFunc::log10f:
1577 case LibFunc::log10l:
1578 return Intrinsic::log10;
1580 case LibFunc::log2f:
1581 case LibFunc::log2l:
1582 return Intrinsic::log2;
1584 case LibFunc::fabsf:
1585 case LibFunc::fabsl:
1586 return Intrinsic::fabs;
1587 case LibFunc::floor:
1588 case LibFunc::floorf:
1589 case LibFunc::floorl:
1590 return Intrinsic::floor;
1592 case LibFunc::ceilf:
1593 case LibFunc::ceill:
1594 return Intrinsic::ceil;
1595 case LibFunc::trunc:
1596 case LibFunc::truncf:
1597 case LibFunc::truncl:
1598 return Intrinsic::trunc;
1600 case LibFunc::rintf:
1601 case LibFunc::rintl:
1602 return Intrinsic::rint;
1603 case LibFunc::nearbyint:
1604 case LibFunc::nearbyintf:
1605 case LibFunc::nearbyintl:
1606 return Intrinsic::nearbyint;
1610 return Intrinsic::pow;
1613 return Intrinsic::not_intrinsic;
1616 /// This function translates the reduction kind to an LLVM binary operator.
1618 getReductionBinOp(LoopVectorizationLegality::ReductionKind Kind) {
1620 case LoopVectorizationLegality::RK_IntegerAdd:
1621 return Instruction::Add;
1622 case LoopVectorizationLegality::RK_IntegerMult:
1623 return Instruction::Mul;
1624 case LoopVectorizationLegality::RK_IntegerOr:
1625 return Instruction::Or;
1626 case LoopVectorizationLegality::RK_IntegerAnd:
1627 return Instruction::And;
1628 case LoopVectorizationLegality::RK_IntegerXor:
1629 return Instruction::Xor;
1630 case LoopVectorizationLegality::RK_FloatMult:
1631 return Instruction::FMul;
1632 case LoopVectorizationLegality::RK_FloatAdd:
1633 return Instruction::FAdd;
1634 case LoopVectorizationLegality::RK_IntegerMinMax:
1635 return Instruction::ICmp;
1637 llvm_unreachable("Unknown reduction operation");
1641 Value *createMinMaxOp(IRBuilder<> &Builder, ICmpInst::Predicate P, Value *Left,
1643 Value *Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp");
1644 Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
1649 InnerLoopVectorizer::vectorizeLoop(LoopVectorizationLegality *Legal) {
1650 //===------------------------------------------------===//
1652 // Notice: any optimization or new instruction that go
1653 // into the code below should be also be implemented in
1656 //===------------------------------------------------===//
1657 Constant *Zero = Builder.getInt32(0);
1659 // In order to support reduction variables we need to be able to vectorize
1660 // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
1661 // stages. First, we create a new vector PHI node with no incoming edges.
1662 // We use this value when we vectorize all of the instructions that use the
1663 // PHI. Next, after all of the instructions in the block are complete we
1664 // add the new incoming edges to the PHI. At this point all of the
1665 // instructions in the basic block are vectorized, so we can use them to
1666 // construct the PHI.
1667 PhiVector RdxPHIsToFix;
1669 // Scan the loop in a topological order to ensure that defs are vectorized
1671 LoopBlocksDFS DFS(OrigLoop);
1674 // Vectorize all of the blocks in the original loop.
1675 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
1676 be = DFS.endRPO(); bb != be; ++bb)
1677 vectorizeBlockInLoop(Legal, *bb, &RdxPHIsToFix);
1679 // At this point every instruction in the original loop is widened to
1680 // a vector form. We are almost done. Now, we need to fix the PHI nodes
1681 // that we vectorized. The PHI nodes are currently empty because we did
1682 // not want to introduce cycles. Notice that the remaining PHI nodes
1683 // that we need to fix are reduction variables.
1685 // Create the 'reduced' values for each of the induction vars.
1686 // The reduced values are the vector values that we scalarize and combine
1687 // after the loop is finished.
1688 for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
1690 PHINode *RdxPhi = *it;
1691 assert(RdxPhi && "Unable to recover vectorized PHI");
1693 // Find the reduction variable descriptor.
1694 assert(Legal->getReductionVars()->count(RdxPhi) &&
1695 "Unable to find the reduction variable");
1696 LoopVectorizationLegality::ReductionDescriptor RdxDesc =
1697 (*Legal->getReductionVars())[RdxPhi];
1699 // We need to generate a reduction vector from the incoming scalar.
1700 // To do so, we need to generate the 'identity' vector and overide
1701 // one of the elements with the incoming scalar reduction. We need
1702 // to do it in the vector-loop preheader.
1703 Builder.SetInsertPoint(LoopBypassBlocks.front()->getTerminator());
1705 // This is the vector-clone of the value that leaves the loop.
1706 VectorParts &VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
1707 Type *VecTy = VectorExit[0]->getType();
1709 // Find the reduction identity variable. Zero for addition, or, xor,
1710 // one for multiplication, -1 for And.
1711 Constant *Iden = getReductionIdentity(RdxDesc.Kind, VecTy->getScalarType(),
1712 RdxDesc.MinMaxPred);
1713 Constant *Identity = ConstantVector::getSplat(VF, Iden);
1715 // This vector is the Identity vector where the first element is the
1716 // incoming scalar reduction.
1717 Value *VectorStart = Builder.CreateInsertElement(Identity,
1718 RdxDesc.StartValue, Zero);
1720 // Fix the vector-loop phi.
1721 // We created the induction variable so we know that the
1722 // preheader is the first entry.
1723 BasicBlock *VecPreheader = Induction->getIncomingBlock(0);
1725 // Reductions do not have to start at zero. They can start with
1726 // any loop invariant values.
1727 VectorParts &VecRdxPhi = WidenMap.get(RdxPhi);
1728 BasicBlock *Latch = OrigLoop->getLoopLatch();
1729 Value *LoopVal = RdxPhi->getIncomingValueForBlock(Latch);
1730 VectorParts &Val = getVectorValue(LoopVal);
1731 for (unsigned part = 0; part < UF; ++part) {
1732 // Make sure to add the reduction stat value only to the
1733 // first unroll part.
1734 Value *StartVal = (part == 0) ? VectorStart : Identity;
1735 cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal, VecPreheader);
1736 cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part], LoopVectorBody);
1739 // Before each round, move the insertion point right between
1740 // the PHIs and the values we are going to write.
1741 // This allows us to write both PHINodes and the extractelement
1743 Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
1745 VectorParts RdxParts;
1746 for (unsigned part = 0; part < UF; ++part) {
1747 // This PHINode contains the vectorized reduction variable, or
1748 // the initial value vector, if we bypass the vector loop.
1749 VectorParts &RdxExitVal = getVectorValue(RdxDesc.LoopExitInstr);
1750 PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
1751 Value *StartVal = (part == 0) ? VectorStart : Identity;
1752 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
1753 NewPhi->addIncoming(StartVal, LoopBypassBlocks[I]);
1754 NewPhi->addIncoming(RdxExitVal[part], LoopVectorBody);
1755 RdxParts.push_back(NewPhi);
1758 // Reduce all of the unrolled parts into a single vector.
1759 Value *ReducedPartRdx = RdxParts[0];
1760 unsigned Op = getReductionBinOp(RdxDesc.Kind);
1761 for (unsigned part = 1; part < UF; ++part) {
1762 if (Op != Instruction::ICmp)
1763 ReducedPartRdx = Builder.CreateBinOp((Instruction::BinaryOps)Op,
1764 RdxParts[part], ReducedPartRdx,
1767 ReducedPartRdx = createMinMaxOp(Builder, RdxDesc.MinMaxPred,
1768 ReducedPartRdx, RdxParts[part]);
1771 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
1772 // and vector ops, reducing the set of values being computed by half each
1774 assert(isPowerOf2_32(VF) &&
1775 "Reduction emission only supported for pow2 vectors!");
1776 Value *TmpVec = ReducedPartRdx;
1777 SmallVector<Constant*, 32> ShuffleMask(VF, 0);
1778 for (unsigned i = VF; i != 1; i >>= 1) {
1779 // Move the upper half of the vector to the lower half.
1780 for (unsigned j = 0; j != i/2; ++j)
1781 ShuffleMask[j] = Builder.getInt32(i/2 + j);
1783 // Fill the rest of the mask with undef.
1784 std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
1785 UndefValue::get(Builder.getInt32Ty()));
1788 Builder.CreateShuffleVector(TmpVec,
1789 UndefValue::get(TmpVec->getType()),
1790 ConstantVector::get(ShuffleMask),
1793 if (Op != Instruction::ICmp)
1794 TmpVec = Builder.CreateBinOp((Instruction::BinaryOps)Op, TmpVec, Shuf,
1797 TmpVec = createMinMaxOp(Builder, RdxDesc.MinMaxPred, TmpVec, Shuf);
1800 // The result is in the first element of the vector.
1801 Value *Scalar0 = Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
1803 // Now, we need to fix the users of the reduction variable
1804 // inside and outside of the scalar remainder loop.
1805 // We know that the loop is in LCSSA form. We need to update the
1806 // PHI nodes in the exit blocks.
1807 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
1808 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
1809 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
1810 if (!LCSSAPhi) continue;
1812 // All PHINodes need to have a single entry edge, or two if
1813 // we already fixed them.
1814 assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
1816 // We found our reduction value exit-PHI. Update it with the
1817 // incoming bypass edge.
1818 if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
1819 // Add an edge coming from the bypass.
1820 LCSSAPhi->addIncoming(Scalar0, LoopMiddleBlock);
1823 }// end of the LCSSA phi scan.
1825 // Fix the scalar loop reduction variable with the incoming reduction sum
1826 // from the vector body and from the backedge value.
1827 int IncomingEdgeBlockIdx =
1828 (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
1829 assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
1830 // Pick the other block.
1831 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
1832 (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, Scalar0);
1833 (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
1834 }// end of for each redux variable.
1836 // The Loop exit block may have single value PHI nodes where the incoming
1837 // value is 'undef'. While vectorizing we only handled real values that
1838 // were defined inside the loop. Here we handle the 'undef case'.
1840 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
1841 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
1842 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
1843 if (!LCSSAPhi) continue;
1844 if (LCSSAPhi->getNumIncomingValues() == 1)
1845 LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
1850 InnerLoopVectorizer::VectorParts
1851 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
1852 assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
1855 VectorParts SrcMask = createBlockInMask(Src);
1857 // The terminator has to be a branch inst!
1858 BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
1859 assert(BI && "Unexpected terminator found");
1861 if (BI->isConditional()) {
1862 VectorParts EdgeMask = getVectorValue(BI->getCondition());
1864 if (BI->getSuccessor(0) != Dst)
1865 for (unsigned part = 0; part < UF; ++part)
1866 EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
1868 for (unsigned part = 0; part < UF; ++part)
1869 EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
1876 InnerLoopVectorizer::VectorParts
1877 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
1878 assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
1880 // Loop incoming mask is all-one.
1881 if (OrigLoop->getHeader() == BB) {
1882 Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
1883 return getVectorValue(C);
1886 // This is the block mask. We OR all incoming edges, and with zero.
1887 Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
1888 VectorParts BlockMask = getVectorValue(Zero);
1891 for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
1892 VectorParts EM = createEdgeMask(*it, BB);
1893 for (unsigned part = 0; part < UF; ++part)
1894 BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
1901 InnerLoopVectorizer::vectorizeBlockInLoop(LoopVectorizationLegality *Legal,
1902 BasicBlock *BB, PhiVector *PV) {
1903 // For each instruction in the old loop.
1904 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1905 VectorParts &Entry = WidenMap.get(it);
1906 switch (it->getOpcode()) {
1907 case Instruction::Br:
1908 // Nothing to do for PHIs and BR, since we already took care of the
1909 // loop control flow instructions.
1911 case Instruction::PHI:{
1912 PHINode* P = cast<PHINode>(it);
1913 // Handle reduction variables:
1914 if (Legal->getReductionVars()->count(P)) {
1915 for (unsigned part = 0; part < UF; ++part) {
1916 // This is phase one of vectorizing PHIs.
1917 Type *VecTy = VectorType::get(it->getType(), VF);
1918 Entry[part] = PHINode::Create(VecTy, 2, "vec.phi",
1919 LoopVectorBody-> getFirstInsertionPt());
1925 // Check for PHI nodes that are lowered to vector selects.
1926 if (P->getParent() != OrigLoop->getHeader()) {
1927 // We know that all PHIs in non header blocks are converted into
1928 // selects, so we don't have to worry about the insertion order and we
1929 // can just use the builder.
1931 // At this point we generate the predication tree. There may be
1932 // duplications since this is a simple recursive scan, but future
1933 // optimizations will clean it up.
1934 VectorParts Cond = createEdgeMask(P->getIncomingBlock(0),
1937 for (unsigned part = 0; part < UF; ++part) {
1938 VectorParts &In0 = getVectorValue(P->getIncomingValue(0));
1939 VectorParts &In1 = getVectorValue(P->getIncomingValue(1));
1940 Entry[part] = Builder.CreateSelect(Cond[part], In0[part], In1[part],
1946 // This PHINode must be an induction variable.
1947 // Make sure that we know about it.
1948 assert(Legal->getInductionVars()->count(P) &&
1949 "Not an induction variable");
1951 LoopVectorizationLegality::InductionInfo II =
1952 Legal->getInductionVars()->lookup(P);
1955 case LoopVectorizationLegality::IK_NoInduction:
1956 llvm_unreachable("Unknown induction");
1957 case LoopVectorizationLegality::IK_IntInduction: {
1958 assert(P == OldInduction && "Unexpected PHI");
1959 Value *Broadcasted = getBroadcastInstrs(Induction);
1960 // After broadcasting the induction variable we need to make the
1961 // vector consecutive by adding 0, 1, 2 ...
1962 for (unsigned part = 0; part < UF; ++part)
1963 Entry[part] = getConsecutiveVector(Broadcasted, VF * part, false);
1966 case LoopVectorizationLegality::IK_ReverseIntInduction:
1967 case LoopVectorizationLegality::IK_PtrInduction:
1968 case LoopVectorizationLegality::IK_ReversePtrInduction:
1969 // Handle reverse integer and pointer inductions.
1970 Value *StartIdx = 0;
1971 // If we have a single integer induction variable then use it.
1972 // Otherwise, start counting at zero.
1974 LoopVectorizationLegality::InductionInfo OldII =
1975 Legal->getInductionVars()->lookup(OldInduction);
1976 StartIdx = OldII.StartValue;
1978 StartIdx = ConstantInt::get(Induction->getType(), 0);
1980 // This is the normalized GEP that starts counting at zero.
1981 Value *NormalizedIdx = Builder.CreateSub(Induction, StartIdx,
1984 // Handle the reverse integer induction variable case.
1985 if (LoopVectorizationLegality::IK_ReverseIntInduction == II.IK) {
1986 IntegerType *DstTy = cast<IntegerType>(II.StartValue->getType());
1987 Value *CNI = Builder.CreateSExtOrTrunc(NormalizedIdx, DstTy,
1989 Value *ReverseInd = Builder.CreateSub(II.StartValue, CNI,
1992 // This is a new value so do not hoist it out.
1993 Value *Broadcasted = getBroadcastInstrs(ReverseInd);
1994 // After broadcasting the induction variable we need to make the
1995 // vector consecutive by adding ... -3, -2, -1, 0.
1996 for (unsigned part = 0; part < UF; ++part)
1997 Entry[part] = getConsecutiveVector(Broadcasted, -VF * part, true);
2001 // Handle the pointer induction variable case.
2002 assert(P->getType()->isPointerTy() && "Unexpected type.");
2004 // Is this a reverse induction ptr or a consecutive induction ptr.
2005 bool Reverse = (LoopVectorizationLegality::IK_ReversePtrInduction ==
2008 // This is the vector of results. Notice that we don't generate
2009 // vector geps because scalar geps result in better code.
2010 for (unsigned part = 0; part < UF; ++part) {
2011 Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
2012 for (unsigned int i = 0; i < VF; ++i) {
2013 int EltIndex = (i + part * VF) * (Reverse ? -1 : 1);
2014 Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex);
2017 GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx, "gep.idx");
2019 GlobalIdx = Builder.CreateSub(Idx, NormalizedIdx, "gep.ridx");
2021 Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
2023 VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
2024 Builder.getInt32(i),
2027 Entry[part] = VecVal;
2034 case Instruction::Add:
2035 case Instruction::FAdd:
2036 case Instruction::Sub:
2037 case Instruction::FSub:
2038 case Instruction::Mul:
2039 case Instruction::FMul:
2040 case Instruction::UDiv:
2041 case Instruction::SDiv:
2042 case Instruction::FDiv:
2043 case Instruction::URem:
2044 case Instruction::SRem:
2045 case Instruction::FRem:
2046 case Instruction::Shl:
2047 case Instruction::LShr:
2048 case Instruction::AShr:
2049 case Instruction::And:
2050 case Instruction::Or:
2051 case Instruction::Xor: {
2052 // Just widen binops.
2053 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
2054 VectorParts &A = getVectorValue(it->getOperand(0));
2055 VectorParts &B = getVectorValue(it->getOperand(1));
2057 // Use this vector value for all users of the original instruction.
2058 for (unsigned Part = 0; Part < UF; ++Part) {
2059 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
2061 // Update the NSW, NUW and Exact flags. Notice: V can be an Undef.
2062 BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V);
2063 if (VecOp && isa<OverflowingBinaryOperator>(BinOp)) {
2064 VecOp->setHasNoSignedWrap(BinOp->hasNoSignedWrap());
2065 VecOp->setHasNoUnsignedWrap(BinOp->hasNoUnsignedWrap());
2067 if (VecOp && isa<PossiblyExactOperator>(VecOp))
2068 VecOp->setIsExact(BinOp->isExact());
2074 case Instruction::Select: {
2076 // If the selector is loop invariant we can create a select
2077 // instruction with a scalar condition. Otherwise, use vector-select.
2078 bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)),
2081 // The condition can be loop invariant but still defined inside the
2082 // loop. This means that we can't just use the original 'cond' value.
2083 // We have to take the 'vectorized' value and pick the first lane.
2084 // Instcombine will make this a no-op.
2085 VectorParts &Cond = getVectorValue(it->getOperand(0));
2086 VectorParts &Op0 = getVectorValue(it->getOperand(1));
2087 VectorParts &Op1 = getVectorValue(it->getOperand(2));
2088 Value *ScalarCond = Builder.CreateExtractElement(Cond[0],
2089 Builder.getInt32(0));
2090 for (unsigned Part = 0; Part < UF; ++Part) {
2091 Entry[Part] = Builder.CreateSelect(
2092 InvariantCond ? ScalarCond : Cond[Part],
2099 case Instruction::ICmp:
2100 case Instruction::FCmp: {
2101 // Widen compares. Generate vector compares.
2102 bool FCmp = (it->getOpcode() == Instruction::FCmp);
2103 CmpInst *Cmp = dyn_cast<CmpInst>(it);
2104 VectorParts &A = getVectorValue(it->getOperand(0));
2105 VectorParts &B = getVectorValue(it->getOperand(1));
2106 for (unsigned Part = 0; Part < UF; ++Part) {
2109 C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
2111 C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
2117 case Instruction::Store:
2118 case Instruction::Load:
2119 vectorizeMemoryInstruction(it, Legal);
2121 case Instruction::ZExt:
2122 case Instruction::SExt:
2123 case Instruction::FPToUI:
2124 case Instruction::FPToSI:
2125 case Instruction::FPExt:
2126 case Instruction::PtrToInt:
2127 case Instruction::IntToPtr:
2128 case Instruction::SIToFP:
2129 case Instruction::UIToFP:
2130 case Instruction::Trunc:
2131 case Instruction::FPTrunc:
2132 case Instruction::BitCast: {
2133 CastInst *CI = dyn_cast<CastInst>(it);
2134 /// Optimize the special case where the source is the induction
2135 /// variable. Notice that we can only optimize the 'trunc' case
2136 /// because: a. FP conversions lose precision, b. sext/zext may wrap,
2137 /// c. other casts depend on pointer size.
2138 if (CI->getOperand(0) == OldInduction &&
2139 it->getOpcode() == Instruction::Trunc) {
2140 Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
2142 Value *Broadcasted = getBroadcastInstrs(ScalarCast);
2143 for (unsigned Part = 0; Part < UF; ++Part)
2144 Entry[Part] = getConsecutiveVector(Broadcasted, VF * Part, false);
2147 /// Vectorize casts.
2148 Type *DestTy = VectorType::get(CI->getType()->getScalarType(), VF);
2150 VectorParts &A = getVectorValue(it->getOperand(0));
2151 for (unsigned Part = 0; Part < UF; ++Part)
2152 Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
2156 case Instruction::Call: {
2157 // Ignore dbg intrinsics.
2158 if (isa<DbgInfoIntrinsic>(it))
2161 Module *M = BB->getParent()->getParent();
2162 CallInst *CI = cast<CallInst>(it);
2163 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
2164 assert(ID && "Not an intrinsic call!");
2165 for (unsigned Part = 0; Part < UF; ++Part) {
2166 SmallVector<Value*, 4> Args;
2167 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
2168 VectorParts &Arg = getVectorValue(CI->getArgOperand(i));
2169 Args.push_back(Arg[Part]);
2171 Type *Tys[] = { VectorType::get(CI->getType()->getScalarType(), VF) };
2172 Function *F = Intrinsic::getDeclaration(M, ID, Tys);
2173 Entry[Part] = Builder.CreateCall(F, Args);
2179 // All other instructions are unsupported. Scalarize them.
2180 scalarizeInstruction(it);
2183 }// end of for_each instr.
2186 void InnerLoopVectorizer::updateAnalysis() {
2187 // Forget the original basic block.
2188 SE->forgetLoop(OrigLoop);
2190 // Update the dominator tree information.
2191 assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&
2192 "Entry does not dominate exit.");
2194 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
2195 DT->addNewBlock(LoopBypassBlocks[I], LoopBypassBlocks[I-1]);
2196 DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlocks.back());
2197 DT->addNewBlock(LoopVectorBody, LoopVectorPreHeader);
2198 DT->addNewBlock(LoopMiddleBlock, LoopBypassBlocks.front());
2199 DT->addNewBlock(LoopScalarPreHeader, LoopMiddleBlock);
2200 DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
2201 DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
2203 DEBUG(DT->verifyAnalysis());
2206 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
2207 if (!EnableIfConversion)
2210 assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
2211 std::vector<BasicBlock*> &LoopBlocks = TheLoop->getBlocksVector();
2213 // Collect the blocks that need predication.
2214 for (unsigned i = 0, e = LoopBlocks.size(); i < e; ++i) {
2215 BasicBlock *BB = LoopBlocks[i];
2217 // We don't support switch statements inside loops.
2218 if (!isa<BranchInst>(BB->getTerminator()))
2221 // We must have at most two predecessors because we need to convert
2222 // all PHIs to selects.
2223 unsigned Preds = std::distance(pred_begin(BB), pred_end(BB));
2227 // We must be able to predicate all blocks that need to be predicated.
2228 if (blockNeedsPredication(BB) && !blockCanBePredicated(BB))
2232 // We can if-convert this loop.
2236 bool LoopVectorizationLegality::canVectorize() {
2237 assert(TheLoop->getLoopPreheader() && "No preheader!!");
2239 // We can only vectorize innermost loops.
2240 if (TheLoop->getSubLoopsVector().size())
2243 // We must have a single backedge.
2244 if (TheLoop->getNumBackEdges() != 1)
2247 // We must have a single exiting block.
2248 if (!TheLoop->getExitingBlock())
2251 unsigned NumBlocks = TheLoop->getNumBlocks();
2253 // Check if we can if-convert non single-bb loops.
2254 if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
2255 DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
2259 // We need to have a loop header.
2260 BasicBlock *Latch = TheLoop->getLoopLatch();
2261 DEBUG(dbgs() << "LV: Found a loop: " <<
2262 TheLoop->getHeader()->getName() << "\n");
2264 // ScalarEvolution needs to be able to find the exit count.
2265 const SCEV *ExitCount = SE->getExitCount(TheLoop, Latch);
2266 if (ExitCount == SE->getCouldNotCompute()) {
2267 DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
2271 // Do not loop-vectorize loops with a tiny trip count.
2272 unsigned TC = SE->getSmallConstantTripCount(TheLoop, Latch);
2273 if (TC > 0u && TC < TinyTripCountVectorThreshold) {
2274 DEBUG(dbgs() << "LV: Found a loop with a very small trip count. " <<
2275 "This loop is not worth vectorizing.\n");
2279 // Check if we can vectorize the instructions and CFG in this loop.
2280 if (!canVectorizeInstrs()) {
2281 DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
2285 // Go over each instruction and look at memory deps.
2286 if (!canVectorizeMemory()) {
2287 DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
2291 // Collect all of the variables that remain uniform after vectorization.
2292 collectLoopUniforms();
2294 DEBUG(dbgs() << "LV: We can vectorize this loop" <<
2295 (PtrRtCheck.Need ? " (with a runtime bound check)" : "")
2298 // Okay! We can vectorize. At this point we don't have any other mem analysis
2299 // which may limit our maximum vectorization factor, so just return true with
2304 bool LoopVectorizationLegality::canVectorizeInstrs() {
2305 BasicBlock *PreHeader = TheLoop->getLoopPreheader();
2306 BasicBlock *Header = TheLoop->getHeader();
2308 // If we marked the scalar loop as "already vectorized" then no need
2309 // to vectorize it again.
2310 if (Header->getTerminator()->getMetadata(AlreadyVectorizedMDName)) {
2311 DEBUG(dbgs() << "LV: This loop was vectorized before\n");
2315 // For each block in the loop.
2316 for (Loop::block_iterator bb = TheLoop->block_begin(),
2317 be = TheLoop->block_end(); bb != be; ++bb) {
2319 // Scan the instructions in the block and look for hazards.
2320 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
2323 if (PHINode *Phi = dyn_cast<PHINode>(it)) {
2324 // This should not happen because the loop should be normalized.
2325 if (Phi->getNumIncomingValues() != 2) {
2326 DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
2330 // Check that this PHI type is allowed.
2331 if (!Phi->getType()->isIntegerTy() &&
2332 !Phi->getType()->isFloatingPointTy() &&
2333 !Phi->getType()->isPointerTy()) {
2334 DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
2338 // If this PHINode is not in the header block, then we know that we
2339 // can convert it to select during if-conversion. No need to check if
2340 // the PHIs in this block are induction or reduction variables.
2344 // This is the value coming from the preheader.
2345 Value *StartValue = Phi->getIncomingValueForBlock(PreHeader);
2346 // Check if this is an induction variable.
2347 InductionKind IK = isInductionVariable(Phi);
2349 if (IK_NoInduction != IK) {
2350 // Int inductions are special because we only allow one IV.
2351 if (IK == IK_IntInduction) {
2353 DEBUG(dbgs() << "LV: Found too many inductions."<< *Phi <<"\n");
2359 DEBUG(dbgs() << "LV: Found an induction variable.\n");
2360 Inductions[Phi] = InductionInfo(StartValue, IK);
2364 if (AddReductionVar(Phi, RK_IntegerAdd)) {
2365 DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
2368 if (AddReductionVar(Phi, RK_IntegerMult)) {
2369 DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n");
2372 if (AddReductionVar(Phi, RK_IntegerOr)) {
2373 DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n");
2376 if (AddReductionVar(Phi, RK_IntegerAnd)) {
2377 DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n");
2380 if (AddReductionVar(Phi, RK_IntegerXor)) {
2381 DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n");
2384 if (AddReductionVar(Phi, RK_IntegerMinMax)) {
2385 DEBUG(dbgs() << "LV: Found a MINMAX reduction PHI."<< *Phi <<"\n");
2388 if (AddReductionVar(Phi, RK_FloatMult)) {
2389 DEBUG(dbgs() << "LV: Found an FMult reduction PHI."<< *Phi <<"\n");
2392 if (AddReductionVar(Phi, RK_FloatAdd)) {
2393 DEBUG(dbgs() << "LV: Found an FAdd reduction PHI."<< *Phi <<"\n");
2397 DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
2399 }// end of PHI handling
2401 // We still don't handle functions. However, we can ignore dbg intrinsic
2402 // calls and we do handle certain intrinsic and libm functions.
2403 CallInst *CI = dyn_cast<CallInst>(it);
2404 if (CI && !getIntrinsicIDForCall(CI, TLI) && !isa<DbgInfoIntrinsic>(CI)) {
2405 DEBUG(dbgs() << "LV: Found a call site.\n");
2409 // Check that the instruction return type is vectorizable.
2410 if (!VectorType::isValidElementType(it->getType()) &&
2411 !it->getType()->isVoidTy()) {
2412 DEBUG(dbgs() << "LV: Found unvectorizable type." << "\n");
2416 // Check that the stored type is vectorizable.
2417 if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
2418 Type *T = ST->getValueOperand()->getType();
2419 if (!VectorType::isValidElementType(T))
2423 // Reduction instructions are allowed to have exit users.
2424 // All other instructions must not have external users.
2425 if (!AllowedExit.count(it))
2426 //Check that all of the users of the loop are inside the BB.
2427 for (Value::use_iterator I = it->use_begin(), E = it->use_end();
2429 Instruction *U = cast<Instruction>(*I);
2430 // This user may be a reduction exit value.
2431 if (!TheLoop->contains(U)) {
2432 DEBUG(dbgs() << "LV: Found an outside user for : "<< *U << "\n");
2441 DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
2442 assert(getInductionVars()->size() && "No induction variables");
2448 void LoopVectorizationLegality::collectLoopUniforms() {
2449 // We now know that the loop is vectorizable!
2450 // Collect variables that will remain uniform after vectorization.
2451 std::vector<Value*> Worklist;
2452 BasicBlock *Latch = TheLoop->getLoopLatch();
2454 // Start with the conditional branch and walk up the block.
2455 Worklist.push_back(Latch->getTerminator()->getOperand(0));
2457 while (Worklist.size()) {
2458 Instruction *I = dyn_cast<Instruction>(Worklist.back());
2459 Worklist.pop_back();
2461 // Look at instructions inside this loop.
2462 // Stop when reaching PHI nodes.
2463 // TODO: we need to follow values all over the loop, not only in this block.
2464 if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
2467 // This is a known uniform.
2470 // Insert all operands.
2471 for (int i = 0, Op = I->getNumOperands(); i < Op; ++i) {
2472 Worklist.push_back(I->getOperand(i));
2477 AliasAnalysis::Location
2478 LoopVectorizationLegality::getLoadStoreLocation(Instruction *Inst) {
2479 if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
2480 return AA->getLocation(Store);
2481 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
2482 return AA->getLocation(Load);
2484 llvm_unreachable("Should be either load or store instruction");
2488 LoopVectorizationLegality::hasPossibleGlobalWriteReorder(
2491 AliasMultiMap& WriteObjects,
2492 unsigned MaxByteWidth) {
2494 AliasAnalysis::Location ThisLoc = getLoadStoreLocation(Inst);
2496 std::vector<Instruction*>::iterator
2497 it = WriteObjects[Object].begin(),
2498 end = WriteObjects[Object].end();
2500 for (; it != end; ++it) {
2501 Instruction* I = *it;
2505 AliasAnalysis::Location ThatLoc = getLoadStoreLocation(I);
2506 if (AA->alias(ThisLoc.getWithNewSize(MaxByteWidth),
2507 ThatLoc.getWithNewSize(MaxByteWidth)))
2513 bool LoopVectorizationLegality::canVectorizeMemory() {
2515 if (TheLoop->isAnnotatedParallel()) {
2517 << "LV: A loop annotated parallel, ignore memory dependency "
2522 typedef SmallVector<Value*, 16> ValueVector;
2523 typedef SmallPtrSet<Value*, 16> ValueSet;
2524 // Holds the Load and Store *instructions*.
2527 PtrRtCheck.Pointers.clear();
2528 PtrRtCheck.Need = false;
2531 for (Loop::block_iterator bb = TheLoop->block_begin(),
2532 be = TheLoop->block_end(); bb != be; ++bb) {
2534 // Scan the BB and collect legal loads and stores.
2535 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
2538 // If this is a load, save it. If this instruction can read from memory
2539 // but is not a load, then we quit. Notice that we don't handle function
2540 // calls that read or write.
2541 if (it->mayReadFromMemory()) {
2542 LoadInst *Ld = dyn_cast<LoadInst>(it);
2543 if (!Ld) return false;
2544 if (!Ld->isSimple()) {
2545 DEBUG(dbgs() << "LV: Found a non-simple load.\n");
2548 Loads.push_back(Ld);
2552 // Save 'store' instructions. Abort if other instructions write to memory.
2553 if (it->mayWriteToMemory()) {
2554 StoreInst *St = dyn_cast<StoreInst>(it);
2555 if (!St) return false;
2556 if (!St->isSimple()) {
2557 DEBUG(dbgs() << "LV: Found a non-simple store.\n");
2560 Stores.push_back(St);
2565 // Now we have two lists that hold the loads and the stores.
2566 // Next, we find the pointers that they use.
2568 // Check if we see any stores. If there are no stores, then we don't
2569 // care if the pointers are *restrict*.
2570 if (!Stores.size()) {
2571 DEBUG(dbgs() << "LV: Found a read-only loop!\n");
2575 // Holds the read and read-write *pointers* that we find. These maps hold
2576 // unique values for pointers (so no need for multi-map).
2578 AliasMap ReadWrites;
2580 // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
2581 // multiple times on the same object. If the ptr is accessed twice, once
2582 // for read and once for write, it will only appear once (on the write
2583 // list). This is okay, since we are going to check for conflicts between
2584 // writes and between reads and writes, but not between reads and reads.
2587 ValueVector::iterator I, IE;
2588 for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
2589 StoreInst *ST = cast<StoreInst>(*I);
2590 Value* Ptr = ST->getPointerOperand();
2592 if (isUniform(Ptr)) {
2593 DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
2597 // If we did *not* see this pointer before, insert it to
2598 // the read-write list. At this phase it is only a 'write' list.
2599 if (Seen.insert(Ptr))
2600 ReadWrites.insert(std::make_pair(Ptr, ST));
2603 for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
2604 LoadInst *LD = cast<LoadInst>(*I);
2605 Value* Ptr = LD->getPointerOperand();
2606 // If we did *not* see this pointer before, insert it to the
2607 // read list. If we *did* see it before, then it is already in
2608 // the read-write list. This allows us to vectorize expressions
2609 // such as A[i] += x; Because the address of A[i] is a read-write
2610 // pointer. This only works if the index of A[i] is consecutive.
2611 // If the address of i is unknown (for example A[B[i]]) then we may
2612 // read a few words, modify, and write a few words, and some of the
2613 // words may be written to the same address.
2614 if (Seen.insert(Ptr) || 0 == isConsecutivePtr(Ptr))
2615 Reads.insert(std::make_pair(Ptr, LD));
2618 // If we write (or read-write) to a single destination and there are no
2619 // other reads in this loop then is it safe to vectorize.
2620 if (ReadWrites.size() == 1 && Reads.size() == 0) {
2621 DEBUG(dbgs() << "LV: Found a write-only loop!\n");
2625 // Find pointers with computable bounds. We are going to use this information
2626 // to place a runtime bound check.
2627 bool CanDoRT = true;
2628 AliasMap::iterator MI, ME;
2629 for (MI = ReadWrites.begin(), ME = ReadWrites.end(); MI != ME; ++MI) {
2630 Value *V = (*MI).first;
2631 if (hasComputableBounds(V)) {
2632 PtrRtCheck.insert(SE, TheLoop, V);
2633 DEBUG(dbgs() << "LV: Found a runtime check ptr:" << *V <<"\n");
2639 for (MI = Reads.begin(), ME = Reads.end(); MI != ME; ++MI) {
2640 Value *V = (*MI).first;
2641 if (hasComputableBounds(V)) {
2642 PtrRtCheck.insert(SE, TheLoop, V);
2643 DEBUG(dbgs() << "LV: Found a runtime check ptr:" << *V <<"\n");
2650 // Check that we did not collect too many pointers or found a
2651 // unsizeable pointer.
2652 if (!CanDoRT || PtrRtCheck.Pointers.size() > RuntimeMemoryCheckThreshold) {
2658 DEBUG(dbgs() << "LV: We can perform a memory runtime check if needed.\n");
2661 bool NeedRTCheck = false;
2663 // Biggest vectorized access possible, vector width * unroll factor.
2664 // TODO: We're being very pessimistic here, find a way to know the
2665 // real access width before getting here.
2666 unsigned MaxByteWidth = (TTI->getRegisterBitWidth(true) / 8) *
2667 TTI->getMaximumUnrollFactor();
2668 // Now that the pointers are in two lists (Reads and ReadWrites), we
2669 // can check that there are no conflicts between each of the writes and
2670 // between the writes to the reads.
2671 // Note that WriteObjects duplicates the stores (indexed now by underlying
2672 // objects) to avoid pointing to elements inside ReadWrites.
2673 // TODO: Maybe create a new type where they can interact without duplication.
2674 AliasMultiMap WriteObjects;
2675 ValueVector TempObjects;
2677 // Check that the read-writes do not conflict with other read-write
2679 bool AllWritesIdentified = true;
2680 for (MI = ReadWrites.begin(), ME = ReadWrites.end(); MI != ME; ++MI) {
2681 Value *Val = (*MI).first;
2682 Instruction *Inst = (*MI).second;
2684 GetUnderlyingObjects(Val, TempObjects, DL);
2685 for (ValueVector::iterator UI=TempObjects.begin(), UE=TempObjects.end();
2687 if (!isIdentifiedObject(*UI)) {
2688 DEBUG(dbgs() << "LV: Found an unidentified write ptr:"<< **UI <<"\n");
2690 AllWritesIdentified = false;
2693 // Never seen it before, can't alias.
2694 if (WriteObjects[*UI].empty()) {
2695 DEBUG(dbgs() << "LV: Adding Underlying value:" << **UI <<"\n");
2696 WriteObjects[*UI].push_back(Inst);
2699 // Direct alias found.
2700 if (!AA || dyn_cast<GlobalValue>(*UI) == NULL) {
2701 DEBUG(dbgs() << "LV: Found a possible write-write reorder:"
2705 DEBUG(dbgs() << "LV: Found a conflicting global value:"
2707 DEBUG(dbgs() << "LV: While examining store:" << *Inst <<"\n");
2708 DEBUG(dbgs() << "LV: On value:" << *Val <<"\n");
2710 // If global alias, make sure they do alias.
2711 if (hasPossibleGlobalWriteReorder(*UI,
2715 DEBUG(dbgs() << "LV: Found a possible write-write reorder:"
2720 // Didn't alias, insert into map for further reference.
2721 WriteObjects[*UI].push_back(Inst);
2723 TempObjects.clear();
2726 /// Check that the reads don't conflict with the read-writes.
2727 for (MI = Reads.begin(), ME = Reads.end(); MI != ME; ++MI) {
2728 Value *Val = (*MI).first;
2729 GetUnderlyingObjects(Val, TempObjects, DL);
2730 for (ValueVector::iterator UI=TempObjects.begin(), UE=TempObjects.end();
2732 // If all of the writes are identified then we don't care if the read
2733 // pointer is identified or not.
2734 if (!AllWritesIdentified && !isIdentifiedObject(*UI)) {
2735 DEBUG(dbgs() << "LV: Found an unidentified read ptr:"<< **UI <<"\n");
2739 // Never seen it before, can't alias.
2740 if (WriteObjects[*UI].empty())
2742 // Direct alias found.
2743 if (!AA || dyn_cast<GlobalValue>(*UI) == NULL) {
2744 DEBUG(dbgs() << "LV: Found a possible write-write reorder:"
2748 DEBUG(dbgs() << "LV: Found a global value: "
2750 Instruction *Inst = (*MI).second;
2751 DEBUG(dbgs() << "LV: While examining load:" << *Inst <<"\n");
2752 DEBUG(dbgs() << "LV: On value:" << *Val <<"\n");
2754 // If global alias, make sure they do alias.
2755 if (hasPossibleGlobalWriteReorder(*UI,
2759 DEBUG(dbgs() << "LV: Found a possible read-write reorder:"
2764 TempObjects.clear();
2767 PtrRtCheck.Need = NeedRTCheck;
2768 if (NeedRTCheck && !CanDoRT) {
2769 DEBUG(dbgs() << "LV: We can't vectorize because we can't find " <<
2770 "the array bounds.\n");
2775 DEBUG(dbgs() << "LV: We "<< (NeedRTCheck ? "" : "don't") <<
2776 " need a runtime memory check.\n");
2780 bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi,
2781 ReductionKind Kind) {
2782 if (Phi->getNumIncomingValues() != 2)
2785 // Reduction variables are only found in the loop header block.
2786 if (Phi->getParent() != TheLoop->getHeader())
2789 // Obtain the reduction start value from the value that comes from the loop
2791 Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
2793 // ExitInstruction is the single value which is used outside the loop.
2794 // We only allow for a single reduction value to be used outside the loop.
2795 // This includes users of the reduction, variables (which form a cycle
2796 // which ends in the phi node).
2797 Instruction *ExitInstruction = 0;
2798 // Indicates that we found a binary operation in our scan.
2799 bool FoundBinOp = false;
2801 // Iter is our iterator. We start with the PHI node and scan for all of the
2802 // users of this instruction. All users must be instructions that can be
2803 // used as reduction variables (such as ADD). We may have a single
2804 // out-of-block user. The cycle must end with the original PHI.
2805 Instruction *Iter = Phi;
2807 // To recognize min/max patterns formed by a icmp select sequence, we store
2808 // the number of instruction we saw from the recognized min/max pattern,
2809 // such that we don't stop when we see the phi has two uses (one by the select
2810 // and one by the icmp) and to make sure we only see exactly the two
2812 unsigned NumICmpSelectPatternInst = 0;
2813 ReductionInstDesc ReduxDesc(false, 0);
2815 // Avoid cycles in the chain.
2816 SmallPtrSet<Instruction *, 8> VisitedInsts;
2817 while (VisitedInsts.insert(Iter)) {
2818 // If the instruction has no users then this is a broken
2819 // chain and can't be a reduction variable.
2820 if (Iter->use_empty())
2823 // Did we find a user inside this loop already ?
2824 bool FoundInBlockUser = false;
2825 // Did we reach the initial PHI node already ?
2826 bool FoundStartPHI = false;
2828 // Is this a bin op ?
2829 FoundBinOp |= !isa<PHINode>(Iter);
2831 // For each of the *users* of iter.
2832 for (Value::use_iterator it = Iter->use_begin(), e = Iter->use_end();
2834 Instruction *U = cast<Instruction>(*it);
2835 // We already know that the PHI is a user.
2837 FoundStartPHI = true;
2841 // Check if we found the exit user.
2842 BasicBlock *Parent = U->getParent();
2843 if (!TheLoop->contains(Parent)) {
2844 // Exit if you find multiple outside users.
2845 if (ExitInstruction != 0)
2847 ExitInstruction = Iter;
2850 // We allow in-loop PHINodes which are not the original reduction PHI
2851 // node. If this PHI is the only user of Iter (happens in IF w/ no ELSE
2852 // structure) then don't skip this PHI.
2853 if (isa<PHINode>(Iter) && isa<PHINode>(U) &&
2854 U->getParent() != TheLoop->getHeader() &&
2855 TheLoop->contains(U) &&
2856 Iter->hasNUsesOrMore(2))
2859 // We can't have multiple inside users except for a combination of
2860 // icmp/select both using the phi.
2861 if (FoundInBlockUser && !NumICmpSelectPatternInst)
2863 FoundInBlockUser = true;
2865 // Any reduction instr must be of one of the allowed kinds.
2866 ReduxDesc = isReductionInstr(U, Kind, ReduxDesc);
2867 if (!ReduxDesc.IsReduction)
2870 if (Kind == RK_IntegerMinMax && (isa<ICmpInst>(U) ||
2871 isa<SelectInst>(U)))
2872 ++NumICmpSelectPatternInst;
2874 // Reductions of instructions such as Div, and Sub is only
2875 // possible if the LHS is the reduction variable.
2876 if (!U->isCommutative() && !isa<PHINode>(U) && !isa<SelectInst>(U) &&
2877 !isa<ICmpInst>(U) && U->getOperand(0) != Iter)
2880 Iter = ReduxDesc.PatternLastInst;
2883 // This means we have seen one but not the other instruction of the
2884 // pattern or more than just a select and cmp.
2885 if (Kind == RK_IntegerMinMax && NumICmpSelectPatternInst != 2)
2888 // We found a reduction var if we have reached the original
2889 // phi node and we only have a single instruction with out-of-loop
2891 if (FoundStartPHI) {
2892 // This instruction is allowed to have out-of-loop users.
2893 AllowedExit.insert(ExitInstruction);
2895 // Save the description of this reduction variable.
2896 ReductionDescriptor RD(RdxStart, ExitInstruction, Kind,
2897 ReduxDesc.Predicate);
2898 Reductions[Phi] = RD;
2899 // We've ended the cycle. This is a reduction variable if we have an
2900 // outside user and it has a binary op.
2901 return FoundBinOp && ExitInstruction;
2908 static CmpInst::Predicate getPredicateSense(CmpInst::Predicate P,
2909 bool ShouldRevert) {
2910 if (!ShouldRevert) return P;
2914 llvm_unreachable("Unknown predicate sense");
2915 case CmpInst::ICMP_UGT:
2916 case CmpInst::ICMP_UGE:
2917 return CmpInst::ICMP_ULT;
2918 case CmpInst::ICMP_SGT:
2919 case CmpInst::ICMP_SGE:
2920 return CmpInst::ICMP_SLT;
2921 case CmpInst::ICMP_ULT:
2922 case CmpInst::ICMP_ULE:
2923 return CmpInst::ICMP_UGT;
2924 case CmpInst::ICMP_SLT:
2925 case CmpInst::ICMP_SLE:
2926 return CmpInst::ICMP_SGT;
2930 /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
2931 /// pattern corresponding to a min(X, Y) or max(X, Y).
2932 static LoopVectorizationLegality::ReductionInstDesc
2933 isMinMaxSelectCmpPattern(Instruction *I) {
2935 assert((isa<ICmpInst>(I) || isa<SelectInst>(I)) &&
2936 "Expect a select instruction");
2938 SelectInst *Select = 0;
2940 // Look for a select(icmp(),...) pattern. Only handle integer reductions for
2942 if ((Select = dyn_cast<SelectInst>(I))) {
2943 if (!(Cmp = dyn_cast<ICmpInst>(I->getOperand(0))))
2944 return LoopVectorizationLegality::ReductionInstDesc(false, I);
2945 // Only handle the single user case
2946 if (!Cmp->hasOneUse())
2947 return LoopVectorizationLegality::ReductionInstDesc(false, I);
2948 } else if ((Cmp = dyn_cast<ICmpInst>(I))) {
2949 // Only handle the single user case.
2950 if (!Cmp->hasOneUse())
2951 return LoopVectorizationLegality::ReductionInstDesc(false, I);
2952 // Look for the select.
2953 if (!(Select = dyn_cast<SelectInst>(*I->use_begin())))
2954 return LoopVectorizationLegality::ReductionInstDesc(false, I);
2955 // Compare must be the first operand of the select.
2956 if (Select->getOperand(0) != Cmp)
2957 return LoopVectorizationLegality::ReductionInstDesc(false, I);
2960 CmpInst::Predicate Pred = Cmp->getPredicate();
2962 // Only (u/s)lt/gt/ge/le are min or max patterns.
2963 if (Pred == CmpInst::ICMP_EQ ||
2964 Pred == CmpInst::ICMP_NE)
2965 return LoopVectorizationLegality::ReductionInstDesc(false, I);
2967 Value *SelectOp1 = Select->getOperand(1);
2968 Value *SelectOp2 = Select->getOperand(2);
2970 Value *CmpLeft = Cmp->getOperand(0);
2971 Value *CmpRight = Cmp->getOperand(1);
2973 // Can have reversed sense.
2974 // select(slt(X, Y), Y, X) == select(sge(X, Y), X, Y).
2975 bool IsInverted = (SelectOp2 == CmpLeft && SelectOp1 == CmpRight);
2976 bool IsMinMaxPattern = (SelectOp1 == CmpLeft && SelectOp2 == CmpRight) ||
2979 // Advance the instruction pointer from the icmp to the select instruction.
2980 if (IsMinMaxPattern) {
2981 CmpInst::Predicate P = getPredicateSense(Pred, IsInverted);
2982 return LoopVectorizationLegality::ReductionInstDesc(Select, P);
2985 return LoopVectorizationLegality::ReductionInstDesc(false, I);
2988 LoopVectorizationLegality::ReductionInstDesc
2989 LoopVectorizationLegality::isReductionInstr(Instruction *I,
2991 ReductionInstDesc Desc) {
2992 bool FP = I->getType()->isFloatingPointTy();
2993 bool FastMath = (FP && I->isCommutative() && I->isAssociative());
2994 switch (I->getOpcode()) {
2996 return ReductionInstDesc(false, I);
2997 case Instruction::PHI:
2998 if (FP && (Kind != RK_FloatMult && Kind != RK_FloatAdd))
2999 return ReductionInstDesc(false, I);
3000 return ReductionInstDesc(I, Desc.Predicate);
3001 case Instruction::Sub:
3002 case Instruction::Add:
3003 return ReductionInstDesc(Kind == RK_IntegerAdd, I);
3004 case Instruction::Mul:
3005 return ReductionInstDesc(Kind == RK_IntegerMult, I);
3006 case Instruction::And:
3007 return ReductionInstDesc(Kind == RK_IntegerAnd, I);
3008 case Instruction::Or:
3009 return ReductionInstDesc(Kind == RK_IntegerOr, I);
3010 case Instruction::Xor:
3011 return ReductionInstDesc(Kind == RK_IntegerXor, I);
3012 case Instruction::FMul:
3013 return ReductionInstDesc(Kind == RK_FloatMult && FastMath, I);
3014 case Instruction::FAdd:
3015 return ReductionInstDesc(Kind == RK_FloatAdd && FastMath, I);
3016 case Instruction::ICmp:
3017 case Instruction::Select:
3018 if (Kind != RK_IntegerMinMax)
3019 return ReductionInstDesc(false, I);
3020 return isMinMaxSelectCmpPattern(I);
3024 LoopVectorizationLegality::InductionKind
3025 LoopVectorizationLegality::isInductionVariable(PHINode *Phi) {
3026 Type *PhiTy = Phi->getType();
3027 // We only handle integer and pointer inductions variables.
3028 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
3029 return IK_NoInduction;
3031 // Check that the PHI is consecutive.
3032 const SCEV *PhiScev = SE->getSCEV(Phi);
3033 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
3035 DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
3036 return IK_NoInduction;
3038 const SCEV *Step = AR->getStepRecurrence(*SE);
3040 // Integer inductions need to have a stride of one.
3041 if (PhiTy->isIntegerTy()) {
3043 return IK_IntInduction;
3044 if (Step->isAllOnesValue())
3045 return IK_ReverseIntInduction;
3046 return IK_NoInduction;
3049 // Calculate the pointer stride and check if it is consecutive.
3050 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
3052 return IK_NoInduction;
3054 assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
3055 uint64_t Size = DL->getTypeAllocSize(PhiTy->getPointerElementType());
3056 if (C->getValue()->equalsInt(Size))
3057 return IK_PtrInduction;
3058 else if (C->getValue()->equalsInt(0 - Size))
3059 return IK_ReversePtrInduction;
3061 return IK_NoInduction;
3064 bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
3065 Value *In0 = const_cast<Value*>(V);
3066 PHINode *PN = dyn_cast_or_null<PHINode>(In0);
3070 return Inductions.count(PN);
3073 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) {
3074 assert(TheLoop->contains(BB) && "Unknown block used");
3076 // Blocks that do not dominate the latch need predication.
3077 BasicBlock* Latch = TheLoop->getLoopLatch();
3078 return !DT->dominates(BB, Latch);
3081 bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB) {
3082 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
3083 // We don't predicate loads/stores at the moment.
3084 if (it->mayReadFromMemory() || it->mayWriteToMemory() || it->mayThrow())
3087 // The instructions below can trap.
3088 switch (it->getOpcode()) {
3090 case Instruction::UDiv:
3091 case Instruction::SDiv:
3092 case Instruction::URem:
3093 case Instruction::SRem:
3101 bool LoopVectorizationLegality::hasComputableBounds(Value *Ptr) {
3102 const SCEV *PhiScev = SE->getSCEV(Ptr);
3103 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
3107 return AR->isAffine();
3110 LoopVectorizationCostModel::VectorizationFactor
3111 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize,
3113 // Width 1 means no vectorize
3114 VectorizationFactor Factor = { 1U, 0U };
3115 if (OptForSize && Legal->getRuntimePointerCheck()->Need) {
3116 DEBUG(dbgs() << "LV: Aborting. Runtime ptr check is required in Os.\n");
3120 // Find the trip count.
3121 unsigned TC = SE->getSmallConstantTripCount(TheLoop, TheLoop->getLoopLatch());
3122 DEBUG(dbgs() << "LV: Found trip count:"<<TC<<"\n");
3124 unsigned WidestType = getWidestType();
3125 unsigned WidestRegister = TTI.getRegisterBitWidth(true);
3126 unsigned MaxVectorSize = WidestRegister / WidestType;
3127 DEBUG(dbgs() << "LV: The Widest type: " << WidestType << " bits.\n");
3128 DEBUG(dbgs() << "LV: The Widest register is:" << WidestRegister << "bits.\n");
3130 if (MaxVectorSize == 0) {
3131 DEBUG(dbgs() << "LV: The target has no vector registers.\n");
3135 assert(MaxVectorSize <= 32 && "Did not expect to pack so many elements"
3136 " into one vector!");
3138 unsigned VF = MaxVectorSize;
3140 // If we optimize the program for size, avoid creating the tail loop.
3142 // If we are unable to calculate the trip count then don't try to vectorize.
3144 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
3148 // Find the maximum SIMD width that can fit within the trip count.
3149 VF = TC % MaxVectorSize;
3154 // If the trip count that we found modulo the vectorization factor is not
3155 // zero then we require a tail.
3157 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
3163 assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
3164 DEBUG(dbgs() << "LV: Using user VF "<<UserVF<<".\n");
3166 Factor.Width = UserVF;
3170 float Cost = expectedCost(1);
3172 DEBUG(dbgs() << "LV: Scalar loop costs: "<< (int)Cost << ".\n");
3173 for (unsigned i=2; i <= VF; i*=2) {
3174 // Notice that the vector loop needs to be executed less times, so
3175 // we need to divide the cost of the vector loops by the width of
3176 // the vector elements.
3177 float VectorCost = expectedCost(i) / (float)i;
3178 DEBUG(dbgs() << "LV: Vector loop of width "<< i << " costs: " <<
3179 (int)VectorCost << ".\n");
3180 if (VectorCost < Cost) {
3186 DEBUG(dbgs() << "LV: Selecting VF = : "<< Width << ".\n");
3187 Factor.Width = Width;
3188 Factor.Cost = Width * Cost;
3192 unsigned LoopVectorizationCostModel::getWidestType() {
3193 unsigned MaxWidth = 8;
3196 for (Loop::block_iterator bb = TheLoop->block_begin(),
3197 be = TheLoop->block_end(); bb != be; ++bb) {
3198 BasicBlock *BB = *bb;
3200 // For each instruction in the loop.
3201 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
3202 Type *T = it->getType();
3204 // Only examine Loads, Stores and PHINodes.
3205 if (!isa<LoadInst>(it) && !isa<StoreInst>(it) && !isa<PHINode>(it))
3208 // Examine PHI nodes that are reduction variables.
3209 if (PHINode *PN = dyn_cast<PHINode>(it))
3210 if (!Legal->getReductionVars()->count(PN))
3213 // Examine the stored values.
3214 if (StoreInst *ST = dyn_cast<StoreInst>(it))
3215 T = ST->getValueOperand()->getType();
3217 // Ignore loaded pointer types and stored pointer types that are not
3218 // consecutive. However, we do want to take consecutive stores/loads of
3219 // pointer vectors into account.
3220 if (T->isPointerTy() && !isConsecutiveLoadOrStore(it))
3223 MaxWidth = std::max(MaxWidth,
3224 (unsigned)DL->getTypeSizeInBits(T->getScalarType()));
3232 LoopVectorizationCostModel::selectUnrollFactor(bool OptForSize,
3235 unsigned LoopCost) {
3237 // -- The unroll heuristics --
3238 // We unroll the loop in order to expose ILP and reduce the loop overhead.
3239 // There are many micro-architectural considerations that we can't predict
3240 // at this level. For example frontend pressure (on decode or fetch) due to
3241 // code size, or the number and capabilities of the execution ports.
3243 // We use the following heuristics to select the unroll factor:
3244 // 1. If the code has reductions the we unroll in order to break the cross
3245 // iteration dependency.
3246 // 2. If the loop is really small then we unroll in order to reduce the loop
3248 // 3. We don't unroll if we think that we will spill registers to memory due
3249 // to the increased register pressure.
3251 // Use the user preference, unless 'auto' is selected.
3255 // When we optimize for size we don't unroll.
3259 // Do not unroll loops with a relatively small trip count.
3260 unsigned TC = SE->getSmallConstantTripCount(TheLoop,
3261 TheLoop->getLoopLatch());
3262 if (TC > 1 && TC < TinyTripCountUnrollThreshold)
3265 unsigned TargetVectorRegisters = TTI.getNumberOfRegisters(true);
3266 DEBUG(dbgs() << "LV: The target has " << TargetVectorRegisters <<
3267 " vector registers\n");
3269 LoopVectorizationCostModel::RegisterUsage R = calculateRegisterUsage();
3270 // We divide by these constants so assume that we have at least one
3271 // instruction that uses at least one register.
3272 R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
3273 R.NumInstructions = std::max(R.NumInstructions, 1U);
3275 // We calculate the unroll factor using the following formula.
3276 // Subtract the number of loop invariants from the number of available
3277 // registers. These registers are used by all of the unrolled instances.
3278 // Next, divide the remaining registers by the number of registers that is
3279 // required by the loop, in order to estimate how many parallel instances
3280 // fit without causing spills.
3281 unsigned UF = (TargetVectorRegisters - R.LoopInvariantRegs) / R.MaxLocalUsers;
3283 // Clamp the unroll factor ranges to reasonable factors.
3284 unsigned MaxUnrollSize = TTI.getMaximumUnrollFactor();
3286 // If we did not calculate the cost for VF (because the user selected the VF)
3287 // then we calculate the cost of VF here.
3289 LoopCost = expectedCost(VF);
3291 // Clamp the calculated UF to be between the 1 and the max unroll factor
3292 // that the target allows.
3293 if (UF > MaxUnrollSize)
3298 if (Legal->getReductionVars()->size()) {
3299 DEBUG(dbgs() << "LV: Unrolling because of reductions. \n");
3303 // We want to unroll tiny loops in order to reduce the loop overhead.
3304 // We assume that the cost overhead is 1 and we use the cost model
3305 // to estimate the cost of the loop and unroll until the cost of the
3306 // loop overhead is about 5% of the cost of the loop.
3307 DEBUG(dbgs() << "LV: Loop cost is "<< LoopCost <<" \n");
3308 if (LoopCost < 20) {
3309 DEBUG(dbgs() << "LV: Unrolling to reduce branch cost. \n");
3310 unsigned NewUF = 20/LoopCost + 1;
3311 return std::min(NewUF, UF);
3314 DEBUG(dbgs() << "LV: Not Unrolling. \n");
3318 LoopVectorizationCostModel::RegisterUsage
3319 LoopVectorizationCostModel::calculateRegisterUsage() {
3320 // This function calculates the register usage by measuring the highest number
3321 // of values that are alive at a single location. Obviously, this is a very
3322 // rough estimation. We scan the loop in a topological order in order and
3323 // assign a number to each instruction. We use RPO to ensure that defs are
3324 // met before their users. We assume that each instruction that has in-loop
3325 // users starts an interval. We record every time that an in-loop value is
3326 // used, so we have a list of the first and last occurrences of each
3327 // instruction. Next, we transpose this data structure into a multi map that
3328 // holds the list of intervals that *end* at a specific location. This multi
3329 // map allows us to perform a linear search. We scan the instructions linearly
3330 // and record each time that a new interval starts, by placing it in a set.
3331 // If we find this value in the multi-map then we remove it from the set.
3332 // The max register usage is the maximum size of the set.
3333 // We also search for instructions that are defined outside the loop, but are
3334 // used inside the loop. We need this number separately from the max-interval
3335 // usage number because when we unroll, loop-invariant values do not take
3337 LoopBlocksDFS DFS(TheLoop);
3341 R.NumInstructions = 0;
3343 // Each 'key' in the map opens a new interval. The values
3344 // of the map are the index of the 'last seen' usage of the
3345 // instruction that is the key.
3346 typedef DenseMap<Instruction*, unsigned> IntervalMap;
3347 // Maps instruction to its index.
3348 DenseMap<unsigned, Instruction*> IdxToInstr;
3349 // Marks the end of each interval.
3350 IntervalMap EndPoint;
3351 // Saves the list of instruction indices that are used in the loop.
3352 SmallSet<Instruction*, 8> Ends;
3353 // Saves the list of values that are used in the loop but are
3354 // defined outside the loop, such as arguments and constants.
3355 SmallPtrSet<Value*, 8> LoopInvariants;
3358 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
3359 be = DFS.endRPO(); bb != be; ++bb) {
3360 R.NumInstructions += (*bb)->size();
3361 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
3363 Instruction *I = it;
3364 IdxToInstr[Index++] = I;
3366 // Save the end location of each USE.
3367 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
3368 Value *U = I->getOperand(i);
3369 Instruction *Instr = dyn_cast<Instruction>(U);
3371 // Ignore non-instruction values such as arguments, constants, etc.
3372 if (!Instr) continue;
3374 // If this instruction is outside the loop then record it and continue.
3375 if (!TheLoop->contains(Instr)) {
3376 LoopInvariants.insert(Instr);
3380 // Overwrite previous end points.
3381 EndPoint[Instr] = Index;
3387 // Saves the list of intervals that end with the index in 'key'.
3388 typedef SmallVector<Instruction*, 2> InstrList;
3389 DenseMap<unsigned, InstrList> TransposeEnds;
3391 // Transpose the EndPoints to a list of values that end at each index.
3392 for (IntervalMap::iterator it = EndPoint.begin(), e = EndPoint.end();
3394 TransposeEnds[it->second].push_back(it->first);
3396 SmallSet<Instruction*, 8> OpenIntervals;
3397 unsigned MaxUsage = 0;
3400 DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
3401 for (unsigned int i = 0; i < Index; ++i) {
3402 Instruction *I = IdxToInstr[i];
3403 // Ignore instructions that are never used within the loop.
3404 if (!Ends.count(I)) continue;
3406 // Remove all of the instructions that end at this location.
3407 InstrList &List = TransposeEnds[i];
3408 for (unsigned int j=0, e = List.size(); j < e; ++j)
3409 OpenIntervals.erase(List[j]);
3411 // Count the number of live interals.
3412 MaxUsage = std::max(MaxUsage, OpenIntervals.size());
3414 DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # " <<
3415 OpenIntervals.size() <<"\n");
3417 // Add the current instruction to the list of open intervals.
3418 OpenIntervals.insert(I);
3421 unsigned Invariant = LoopInvariants.size();
3422 DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsage << " \n");
3423 DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << " \n");
3424 DEBUG(dbgs() << "LV(REG): LoopSize: " << R.NumInstructions << " \n");
3426 R.LoopInvariantRegs = Invariant;
3427 R.MaxLocalUsers = MaxUsage;
3431 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
3435 for (Loop::block_iterator bb = TheLoop->block_begin(),
3436 be = TheLoop->block_end(); bb != be; ++bb) {
3437 unsigned BlockCost = 0;
3438 BasicBlock *BB = *bb;
3440 // For each instruction in the old loop.
3441 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
3442 // Skip dbg intrinsics.
3443 if (isa<DbgInfoIntrinsic>(it))
3446 unsigned C = getInstructionCost(it, VF);
3448 DEBUG(dbgs() << "LV: Found an estimated cost of "<< C <<" for VF " <<
3449 VF << " For instruction: "<< *it << "\n");
3452 // We assume that if-converted blocks have a 50% chance of being executed.
3453 // When the code is scalar then some of the blocks are avoided due to CF.
3454 // When the code is vectorized we execute all code paths.
3455 if (Legal->blockNeedsPredication(*bb) && VF == 1)
3465 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
3466 // If we know that this instruction will remain uniform, check the cost of
3467 // the scalar version.
3468 if (Legal->isUniformAfterVectorization(I))
3471 Type *RetTy = I->getType();
3472 Type *VectorTy = ToVectorTy(RetTy, VF);
3474 // TODO: We need to estimate the cost of intrinsic calls.
3475 switch (I->getOpcode()) {
3476 case Instruction::GetElementPtr:
3477 // We mark this instruction as zero-cost because the cost of GEPs in
3478 // vectorized code depends on whether the corresponding memory instruction
3479 // is scalarized or not. Therefore, we handle GEPs with the memory
3480 // instruction cost.
3482 case Instruction::Br: {
3483 return TTI.getCFInstrCost(I->getOpcode());
3485 case Instruction::PHI:
3486 //TODO: IF-converted IFs become selects.
3488 case Instruction::Add:
3489 case Instruction::FAdd:
3490 case Instruction::Sub:
3491 case Instruction::FSub:
3492 case Instruction::Mul:
3493 case Instruction::FMul:
3494 case Instruction::UDiv:
3495 case Instruction::SDiv:
3496 case Instruction::FDiv:
3497 case Instruction::URem:
3498 case Instruction::SRem:
3499 case Instruction::FRem:
3500 case Instruction::Shl:
3501 case Instruction::LShr:
3502 case Instruction::AShr:
3503 case Instruction::And:
3504 case Instruction::Or:
3505 case Instruction::Xor: {
3506 // Certain instructions can be cheaper to vectorize if they have a constant
3507 // second vector operand. One example of this are shifts on x86.
3508 TargetTransformInfo::OperandValueKind Op1VK =
3509 TargetTransformInfo::OK_AnyValue;
3510 TargetTransformInfo::OperandValueKind Op2VK =
3511 TargetTransformInfo::OK_AnyValue;
3513 if (isa<ConstantInt>(I->getOperand(1)))
3514 Op2VK = TargetTransformInfo::OK_UniformConstantValue;
3516 return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy, Op1VK, Op2VK);
3518 case Instruction::Select: {
3519 SelectInst *SI = cast<SelectInst>(I);
3520 const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
3521 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
3522 Type *CondTy = SI->getCondition()->getType();
3524 CondTy = VectorType::get(CondTy, VF);
3526 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
3528 case Instruction::ICmp:
3529 case Instruction::FCmp: {
3530 Type *ValTy = I->getOperand(0)->getType();
3531 VectorTy = ToVectorTy(ValTy, VF);
3532 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy);
3534 case Instruction::Store:
3535 case Instruction::Load: {
3536 StoreInst *SI = dyn_cast<StoreInst>(I);
3537 LoadInst *LI = dyn_cast<LoadInst>(I);
3538 Type *ValTy = (SI ? SI->getValueOperand()->getType() :
3540 VectorTy = ToVectorTy(ValTy, VF);
3542 unsigned Alignment = SI ? SI->getAlignment() : LI->getAlignment();
3543 unsigned AS = SI ? SI->getPointerAddressSpace() :
3544 LI->getPointerAddressSpace();
3545 Value *Ptr = SI ? SI->getPointerOperand() : LI->getPointerOperand();
3546 // We add the cost of address computation here instead of with the gep
3547 // instruction because only here we know whether the operation is
3550 return TTI.getAddressComputationCost(VectorTy) +
3551 TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
3553 // Scalarized loads/stores.
3554 int Stride = Legal->isConsecutivePtr(Ptr);
3555 bool Reverse = Stride < 0;
3558 // The cost of extracting from the value vector and pointer vector.
3559 Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
3560 for (unsigned i = 0; i < VF; ++i) {
3561 // The cost of extracting the pointer operand.
3562 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
3563 // In case of STORE, the cost of ExtractElement from the vector.
3564 // In case of LOAD, the cost of InsertElement into the returned
3566 Cost += TTI.getVectorInstrCost(SI ? Instruction::ExtractElement :
3567 Instruction::InsertElement,
3571 // The cost of the scalar loads/stores.
3572 Cost += VF * TTI.getAddressComputationCost(ValTy->getScalarType());
3573 Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(),
3578 // Wide load/stores.
3579 unsigned Cost = TTI.getAddressComputationCost(VectorTy);
3580 Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
3583 Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
3587 case Instruction::ZExt:
3588 case Instruction::SExt:
3589 case Instruction::FPToUI:
3590 case Instruction::FPToSI:
3591 case Instruction::FPExt:
3592 case Instruction::PtrToInt:
3593 case Instruction::IntToPtr:
3594 case Instruction::SIToFP:
3595 case Instruction::UIToFP:
3596 case Instruction::Trunc:
3597 case Instruction::FPTrunc:
3598 case Instruction::BitCast: {
3599 // We optimize the truncation of induction variable.
3600 // The cost of these is the same as the scalar operation.
3601 if (I->getOpcode() == Instruction::Trunc &&
3602 Legal->isInductionVariable(I->getOperand(0)))
3603 return TTI.getCastInstrCost(I->getOpcode(), I->getType(),
3604 I->getOperand(0)->getType());
3606 Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
3607 return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
3609 case Instruction::Call: {
3610 CallInst *CI = cast<CallInst>(I);
3611 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
3612 assert(ID && "Not an intrinsic call!");
3613 Type *RetTy = ToVectorTy(CI->getType(), VF);
3614 SmallVector<Type*, 4> Tys;
3615 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
3616 Tys.push_back(ToVectorTy(CI->getArgOperand(i)->getType(), VF));
3617 return TTI.getIntrinsicInstrCost(ID, RetTy, Tys);
3620 // We are scalarizing the instruction. Return the cost of the scalar
3621 // instruction, plus the cost of insert and extract into vector
3622 // elements, times the vector width.
3625 if (!RetTy->isVoidTy() && VF != 1) {
3626 unsigned InsCost = TTI.getVectorInstrCost(Instruction::InsertElement,
3628 unsigned ExtCost = TTI.getVectorInstrCost(Instruction::ExtractElement,
3631 // The cost of inserting the results plus extracting each one of the
3633 Cost += VF * (InsCost + ExtCost * I->getNumOperands());
3636 // The cost of executing VF copies of the scalar instruction. This opcode
3637 // is unknown. Assume that it is the same as 'mul'.
3638 Cost += VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy);
3644 Type* LoopVectorizationCostModel::ToVectorTy(Type *Scalar, unsigned VF) {
3645 if (Scalar->isVoidTy() || VF == 1)
3647 return VectorType::get(Scalar, VF);
3650 char LoopVectorize::ID = 0;
3651 static const char lv_name[] = "Loop Vectorization";
3652 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
3653 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3654 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
3655 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
3656 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
3657 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
3660 Pass *createLoopVectorizePass() {
3661 return new LoopVectorize();
3665 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
3666 // Check for a store.
3667 if (StoreInst *ST = dyn_cast<StoreInst>(Inst))
3668 return Legal->isConsecutivePtr(ST->getPointerOperand()) != 0;
3670 // Check for a load.
3671 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
3672 return Legal->isConsecutivePtr(LI->getPointerOperand()) != 0;