1 //===- LoopVectorize.cpp - A Loop Vectorizer ------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This is the LLVM loop vectorizer. This pass modifies 'vectorizable' loops
11 // and generates target-independent LLVM-IR.
12 // The vectorizer uses the TargetTransformInfo analysis to estimate the costs
13 // of instructions in order to estimate the profitability of vectorization.
15 // The loop vectorizer combines consecutive loop iterations into a single
16 // 'wide' iteration. After this transformation the index is incremented
17 // by the SIMD vector width, and not by one.
19 // This pass has three parts:
20 // 1. The main loop pass that drives the different parts.
21 // 2. LoopVectorizationLegality - A unit that checks for the legality
22 // of the vectorization.
23 // 3. InnerLoopVectorizer - A unit that performs the actual
24 // widening of instructions.
25 // 4. LoopVectorizationCostModel - A unit that checks for the profitability
26 // of vectorization. It decides on the optimal vector width, which
27 // can be one, if vectorization is not profitable.
29 //===----------------------------------------------------------------------===//
31 // The reduction-variable vectorization is based on the paper:
32 // D. Nuzman and R. Henderson. Multi-platform Auto-vectorization.
34 // Variable uniformity checks are inspired by:
35 // Karrenberg, R. and Hack, S. Whole Function Vectorization.
37 // Other ideas/concepts are from:
38 // A. Zaks and D. Nuzman. Autovectorization in GCC-two years later.
40 // S. Maleki, Y. Gao, M. Garzaran, T. Wong and D. Padua. An Evaluation of
41 // Vectorizing Compilers.
43 //===----------------------------------------------------------------------===//
45 #define LV_NAME "loop-vectorize"
46 #define DEBUG_TYPE LV_NAME
48 #include "llvm/Transforms/Vectorize.h"
49 #include "llvm/ADT/DenseMap.h"
50 #include "llvm/ADT/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/PatternMatch.h"
82 #include "llvm/Support/raw_ostream.h"
83 #include "llvm/Target/TargetLibraryInfo.h"
84 #include "llvm/Transforms/Scalar.h"
85 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
86 #include "llvm/Transforms/Utils/Local.h"
91 using namespace llvm::PatternMatch;
93 static cl::opt<unsigned>
94 VectorizationFactor("force-vector-width", cl::init(0), cl::Hidden,
95 cl::desc("Sets the SIMD width. Zero is autoselect."));
97 static cl::opt<unsigned>
98 VectorizationUnroll("force-vector-unroll", cl::init(0), cl::Hidden,
99 cl::desc("Sets the vectorization unroll count. "
100 "Zero is autoselect."));
103 EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
104 cl::desc("Enable if-conversion during vectorization."));
106 /// We don't vectorize loops with a known constant trip count below this number.
107 static cl::opt<unsigned>
108 TinyTripCountVectorThreshold("vectorizer-min-trip-count", cl::init(16),
110 cl::desc("Don't vectorize loops with a constant "
111 "trip count that is smaller than this "
114 /// We don't unroll loops with a known constant trip count below this number.
115 static const unsigned TinyTripCountUnrollThreshold = 128;
117 /// When performing memory disambiguation checks at runtime do not make more
118 /// than this number of comparisons.
119 static const unsigned RuntimeMemoryCheckThreshold = 8;
121 /// We use a metadata with this name to indicate that a scalar loop was
122 /// vectorized and that we don't need to re-vectorize it if we run into it
125 AlreadyVectorizedMDName = "llvm.vectorizer.already_vectorized";
129 // Forward declarations.
130 class LoopVectorizationLegality;
131 class LoopVectorizationCostModel;
133 /// InnerLoopVectorizer vectorizes loops which contain only one basic
134 /// block to a specified vectorization factor (VF).
135 /// This class performs the widening of scalars into vectors, or multiple
136 /// scalars. This class also implements the following features:
137 /// * It inserts an epilogue loop for handling loops that don't have iteration
138 /// counts that are known to be a multiple of the vectorization factor.
139 /// * It handles the code generation for reduction variables.
140 /// * Scalarization (implementation using scalars) of un-vectorizable
142 /// InnerLoopVectorizer does not perform any vectorization-legality
143 /// checks, and relies on the caller to check for the different legality
144 /// aspects. The InnerLoopVectorizer relies on the
145 /// LoopVectorizationLegality class to provide information about the induction
146 /// and reduction variables that were found to a given vectorization factor.
147 class InnerLoopVectorizer {
149 InnerLoopVectorizer(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
150 DominatorTree *DT, DataLayout *DL,
151 const TargetLibraryInfo *TLI, unsigned VecWidth,
152 unsigned UnrollFactor)
153 : OrigLoop(OrigLoop), SE(SE), LI(LI), DT(DT), DL(DL), TLI(TLI),
154 VF(VecWidth), UF(UnrollFactor), Builder(SE->getContext()), Induction(0),
155 OldInduction(0), WidenMap(UnrollFactor) {}
157 // Perform the actual loop widening (vectorization).
158 void vectorize(LoopVectorizationLegality *Legal) {
159 // Create a new empty loop. Unlink the old loop and connect the new one.
160 createEmptyLoop(Legal);
161 // Widen each instruction in the old loop to a new one in the new loop.
162 // Use the Legality module to find the induction and reduction variables.
163 vectorizeLoop(Legal);
164 // Register the new loop and update the analysis passes.
169 /// A small list of PHINodes.
170 typedef SmallVector<PHINode*, 4> PhiVector;
171 /// When we unroll loops we have multiple vector values for each scalar.
172 /// This data structure holds the unrolled and vectorized values that
173 /// originated from one scalar instruction.
174 typedef SmallVector<Value*, 2> VectorParts;
176 /// Add code that checks at runtime if the accessed arrays overlap.
177 /// Returns the comparator value or NULL if no check is needed.
178 Instruction *addRuntimeCheck(LoopVectorizationLegality *Legal,
180 /// Create an empty loop, based on the loop ranges of the old loop.
181 void createEmptyLoop(LoopVectorizationLegality *Legal);
182 /// Copy and widen the instructions from the old loop.
183 void vectorizeLoop(LoopVectorizationLegality *Legal);
185 /// A helper function that computes the predicate of the block BB, assuming
186 /// that the header block of the loop is set to True. It returns the *entry*
187 /// mask for the block BB.
188 VectorParts createBlockInMask(BasicBlock *BB);
189 /// A helper function that computes the predicate of the edge between SRC
191 VectorParts createEdgeMask(BasicBlock *Src, BasicBlock *Dst);
193 /// A helper function to vectorize a single BB within the innermost loop.
194 void vectorizeBlockInLoop(LoopVectorizationLegality *Legal, BasicBlock *BB,
197 /// Insert the new loop to the loop hierarchy and pass manager
198 /// and update the analysis passes.
199 void updateAnalysis();
201 /// This instruction is un-vectorizable. Implement it as a sequence
203 void scalarizeInstruction(Instruction *Instr);
205 /// Vectorize Load and Store instructions,
206 void vectorizeMemoryInstruction(Instruction *Instr,
207 LoopVectorizationLegality *Legal);
209 /// Create a broadcast instruction. This method generates a broadcast
210 /// instruction (shuffle) for loop invariant values and for the induction
211 /// value. If this is the induction variable then we extend it to N, N+1, ...
212 /// this is needed because each iteration in the loop corresponds to a SIMD
214 Value *getBroadcastInstrs(Value *V);
216 /// This function adds 0, 1, 2 ... to each vector element, starting at zero.
217 /// If Negate is set then negative numbers are added e.g. (0, -1, -2, ...).
218 /// The sequence starts at StartIndex.
219 Value *getConsecutiveVector(Value* Val, int StartIdx, bool Negate);
221 /// When we go over instructions in the basic block we rely on previous
222 /// values within the current basic block or on loop invariant values.
223 /// When we widen (vectorize) values we place them in the map. If the values
224 /// are not within the map, they have to be loop invariant, so we simply
225 /// broadcast them into a vector.
226 VectorParts &getVectorValue(Value *V);
228 /// Generate a shuffle sequence that will reverse the vector Vec.
229 Value *reverseVector(Value *Vec);
231 /// This is a helper class that holds the vectorizer state. It maps scalar
232 /// instructions to vector instructions. When the code is 'unrolled' then
233 /// then a single scalar value is mapped to multiple vector parts. The parts
234 /// are stored in the VectorPart type.
236 /// C'tor. UnrollFactor controls the number of vectors ('parts') that
238 ValueMap(unsigned UnrollFactor) : UF(UnrollFactor) {}
240 /// \return True if 'Key' is saved in the Value Map.
241 bool has(Value *Key) const { return MapStorage.count(Key); }
243 /// Initializes a new entry in the map. Sets all of the vector parts to the
244 /// save value in 'Val'.
245 /// \return A reference to a vector with splat values.
246 VectorParts &splat(Value *Key, Value *Val) {
247 VectorParts &Entry = MapStorage[Key];
248 Entry.assign(UF, Val);
252 ///\return A reference to the value that is stored at 'Key'.
253 VectorParts &get(Value *Key) {
254 VectorParts &Entry = MapStorage[Key];
257 assert(Entry.size() == UF);
262 /// The unroll factor. Each entry in the map stores this number of vector
266 /// Map storage. We use std::map and not DenseMap because insertions to a
267 /// dense map invalidates its iterators.
268 std::map<Value *, VectorParts> MapStorage;
271 /// The original loop.
273 /// Scev analysis to use.
281 /// Target Library Info.
282 const TargetLibraryInfo *TLI;
284 /// The vectorization SIMD factor to use. Each vector will have this many
287 /// The vectorization unroll factor to use. Each scalar is vectorized to this
288 /// many different vector instructions.
291 /// The builder that we use
294 // --- Vectorization state ---
296 /// The vector-loop preheader.
297 BasicBlock *LoopVectorPreHeader;
298 /// The scalar-loop preheader.
299 BasicBlock *LoopScalarPreHeader;
300 /// Middle Block between the vector and the scalar.
301 BasicBlock *LoopMiddleBlock;
302 ///The ExitBlock of the scalar loop.
303 BasicBlock *LoopExitBlock;
304 ///The vector loop body.
305 BasicBlock *LoopVectorBody;
306 ///The scalar loop body.
307 BasicBlock *LoopScalarBody;
308 /// A list of all bypass blocks. The first block is the entry of the loop.
309 SmallVector<BasicBlock *, 4> LoopBypassBlocks;
311 /// The new Induction variable which was added to the new block.
313 /// The induction variable of the old basic block.
314 PHINode *OldInduction;
315 /// Holds the extended (to the widest induction type) start index.
317 /// Maps scalars to widened vectors.
321 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
322 /// to what vectorization factor.
323 /// This class does not look at the profitability of vectorization, only the
324 /// legality. This class has two main kinds of checks:
325 /// * Memory checks - The code in canVectorizeMemory checks if vectorization
326 /// will change the order of memory accesses in a way that will change the
327 /// correctness of the program.
328 /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
329 /// checks for a number of different conditions, such as the availability of a
330 /// single induction variable, that all types are supported and vectorize-able,
331 /// etc. This code reflects the capabilities of InnerLoopVectorizer.
332 /// This class is also used by InnerLoopVectorizer for identifying
333 /// induction variable and the different reduction variables.
334 class LoopVectorizationLegality {
336 LoopVectorizationLegality(Loop *L, ScalarEvolution *SE, DataLayout *DL,
337 DominatorTree *DT, TargetTransformInfo* TTI,
338 AliasAnalysis *AA, TargetLibraryInfo *TLI)
339 : TheLoop(L), SE(SE), DL(DL), DT(DT), TTI(TTI), AA(AA), TLI(TLI),
340 Induction(0), WidestIndTy(0), HasFunNoNaNAttr(false) {}
342 /// This enum represents the kinds of reductions that we support.
344 RK_NoReduction, ///< Not a reduction.
345 RK_IntegerAdd, ///< Sum of integers.
346 RK_IntegerMult, ///< Product of integers.
347 RK_IntegerOr, ///< Bitwise or logical OR of numbers.
348 RK_IntegerAnd, ///< Bitwise or logical AND of numbers.
349 RK_IntegerXor, ///< Bitwise or logical XOR of numbers.
350 RK_IntegerMinMax, ///< Min/max implemented in terms of select(cmp()).
351 RK_FloatAdd, ///< Sum of floats.
352 RK_FloatMult, ///< Product of floats.
353 RK_FloatMinMax ///< Min/max implemented in terms of select(cmp()).
356 /// This enum represents the kinds of inductions that we support.
358 IK_NoInduction, ///< Not an induction variable.
359 IK_IntInduction, ///< Integer induction variable. Step = 1.
360 IK_ReverseIntInduction, ///< Reverse int induction variable. Step = -1.
361 IK_PtrInduction, ///< Pointer induction var. Step = sizeof(elem).
362 IK_ReversePtrInduction ///< Reverse ptr indvar. Step = - sizeof(elem).
365 // This enum represents the kind of minmax reduction.
366 enum MinMaxReductionKind {
376 /// This POD struct holds information about reduction variables.
377 struct ReductionDescriptor {
378 ReductionDescriptor() : StartValue(0), LoopExitInstr(0),
379 Kind(RK_NoReduction), MinMaxKind(MRK_Invalid) {}
381 ReductionDescriptor(Value *Start, Instruction *Exit, ReductionKind K,
382 MinMaxReductionKind MK)
383 : StartValue(Start), LoopExitInstr(Exit), Kind(K), MinMaxKind(MK) {}
385 // The starting value of the reduction.
386 // It does not have to be zero!
388 // The instruction who's value is used outside the loop.
389 Instruction *LoopExitInstr;
390 // The kind of the reduction.
392 // If this a min/max reduction the kind of reduction.
393 MinMaxReductionKind MinMaxKind;
396 /// This POD struct holds information about a potential reduction operation.
397 struct ReductionInstDesc {
398 ReductionInstDesc(bool IsRedux, Instruction *I) :
399 IsReduction(IsRedux), PatternLastInst(I), MinMaxKind(MRK_Invalid) {}
401 ReductionInstDesc(Instruction *I, MinMaxReductionKind K) :
402 IsReduction(true), PatternLastInst(I), MinMaxKind(K) {}
404 // Is this instruction a reduction candidate.
406 // The last instruction in a min/max pattern (select of the select(icmp())
407 // pattern), or the current reduction instruction otherwise.
408 Instruction *PatternLastInst;
409 // If this is a min/max pattern the comparison predicate.
410 MinMaxReductionKind MinMaxKind;
413 // This POD struct holds information about the memory runtime legality
414 // check that a group of pointers do not overlap.
415 struct RuntimePointerCheck {
416 RuntimePointerCheck() : Need(false) {}
418 /// Reset the state of the pointer runtime information.
426 /// Insert a pointer and calculate the start and end SCEVs.
427 void insert(ScalarEvolution *SE, Loop *Lp, Value *Ptr, bool WritePtr);
429 /// This flag indicates if we need to add the runtime check.
431 /// Holds the pointers that we need to check.
432 SmallVector<Value*, 2> Pointers;
433 /// Holds the pointer value at the beginning of the loop.
434 SmallVector<const SCEV*, 2> Starts;
435 /// Holds the pointer value at the end of the loop.
436 SmallVector<const SCEV*, 2> Ends;
437 /// Holds the information if this pointer is used for writing to memory.
438 SmallVector<bool, 2> IsWritePtr;
441 /// A POD for saving information about induction variables.
442 struct InductionInfo {
443 InductionInfo(Value *Start, InductionKind K) : StartValue(Start), IK(K) {}
444 InductionInfo() : StartValue(0), IK(IK_NoInduction) {}
451 /// ReductionList contains the reduction descriptors for all
452 /// of the reductions that were found in the loop.
453 typedef DenseMap<PHINode*, ReductionDescriptor> ReductionList;
455 /// InductionList saves induction variables and maps them to the
456 /// induction descriptor.
457 typedef MapVector<PHINode*, InductionInfo> InductionList;
459 /// Alias(Multi)Map stores the values (GEPs or underlying objects and their
460 /// respective Store/Load instruction(s) to calculate aliasing.
461 typedef MapVector<Value*, Instruction* > AliasMap;
462 typedef DenseMap<Value*, std::vector<Instruction*> > AliasMultiMap;
464 /// Returns true if it is legal to vectorize this loop.
465 /// This does not mean that it is profitable to vectorize this
466 /// loop, only that it is legal to do so.
469 /// Returns the Induction variable.
470 PHINode *getInduction() { return Induction; }
472 /// Returns the reduction variables found in the loop.
473 ReductionList *getReductionVars() { return &Reductions; }
475 /// Returns the induction variables found in the loop.
476 InductionList *getInductionVars() { return &Inductions; }
478 /// Returns the widest induction type.
479 Type *getWidestInductionType() { return WidestIndTy; }
481 /// Returns True if V is an induction variable in this loop.
482 bool isInductionVariable(const Value *V);
484 /// Return true if the block BB needs to be predicated in order for the loop
485 /// to be vectorized.
486 bool blockNeedsPredication(BasicBlock *BB);
488 /// Check if this pointer is consecutive when vectorizing. This happens
489 /// when the last index of the GEP is the induction variable, or that the
490 /// pointer itself is an induction variable.
491 /// This check allows us to vectorize A[idx] into a wide load/store.
493 /// 0 - Stride is unknown or non consecutive.
494 /// 1 - Address is consecutive.
495 /// -1 - Address is consecutive, and decreasing.
496 int isConsecutivePtr(Value *Ptr);
498 /// Returns true if the value V is uniform within the loop.
499 bool isUniform(Value *V);
501 /// Returns true if this instruction will remain scalar after vectorization.
502 bool isUniformAfterVectorization(Instruction* I) { return Uniforms.count(I); }
504 /// Returns the information that we collected about runtime memory check.
505 RuntimePointerCheck *getRuntimePointerCheck() { return &PtrRtCheck; }
507 /// This function returns the identity element (or neutral element) for
509 static Constant *getReductionIdentity(ReductionKind K, Type *Tp);
511 /// Check if a single basic block loop is vectorizable.
512 /// At this point we know that this is a loop with a constant trip count
513 /// and we only need to check individual instructions.
514 bool canVectorizeInstrs();
516 /// When we vectorize loops we may change the order in which
517 /// we read and write from memory. This method checks if it is
518 /// legal to vectorize the code, considering only memory constrains.
519 /// Returns true if the loop is vectorizable
520 bool canVectorizeMemory();
522 /// Return true if we can vectorize this loop using the IF-conversion
524 bool canVectorizeWithIfConvert();
526 /// Collect the variables that need to stay uniform after vectorization.
527 void collectLoopUniforms();
529 /// Return true if all of the instructions in the block can be speculatively
531 bool blockCanBePredicated(BasicBlock *BB);
533 /// Returns True, if 'Phi' is the kind of reduction variable for type
534 /// 'Kind'. If this is a reduction variable, it adds it to ReductionList.
535 bool AddReductionVar(PHINode *Phi, ReductionKind Kind);
536 /// Returns a struct describing if the instruction 'I' can be a reduction
537 /// variable of type 'Kind'. If the reduction is a min/max pattern of
538 /// select(icmp()) this function advances the instruction pointer 'I' from the
539 /// compare instruction to the select instruction and stores this pointer in
540 /// 'PatternLastInst' member of the returned struct.
541 ReductionInstDesc isReductionInstr(Instruction *I, ReductionKind Kind,
542 ReductionInstDesc &Desc);
543 /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
544 /// pattern corresponding to a min(X, Y) or max(X, Y).
545 static ReductionInstDesc isMinMaxSelectCmpPattern(Instruction *I,
546 ReductionInstDesc &Prev);
547 /// Returns the induction kind of Phi. This function may return NoInduction
548 /// if the PHI is not an induction variable.
549 InductionKind isInductionVariable(PHINode *Phi);
550 /// Return true if can compute the address bounds of Ptr within the loop.
551 bool hasComputableBounds(Value *Ptr);
552 /// Return true if there is the chance of write reorder.
553 bool hasPossibleGlobalWriteReorder(Value *Object,
555 AliasMultiMap &WriteObjects,
556 unsigned MaxByteWidth);
557 /// Return the AA location for a load or a store.
558 AliasAnalysis::Location getLoadStoreLocation(Instruction *Inst);
561 /// The loop that we evaluate.
565 /// DataLayout analysis.
570 TargetTransformInfo *TTI;
573 /// Target Library Info.
574 TargetLibraryInfo *TLI;
576 // --- vectorization state --- //
578 /// Holds the integer induction variable. This is the counter of the
581 /// Holds the reduction variables.
582 ReductionList Reductions;
583 /// Holds all of the induction variables that we found in the loop.
584 /// Notice that inductions don't need to start at zero and that induction
585 /// variables can be pointers.
586 InductionList Inductions;
587 /// Holds the widest induction type encountered.
590 /// Allowed outside users. This holds the reduction
591 /// vars which can be accessed from outside the loop.
592 SmallPtrSet<Value*, 4> AllowedExit;
593 /// This set holds the variables which are known to be uniform after
595 SmallPtrSet<Instruction*, 4> Uniforms;
596 /// We need to check that all of the pointers in this list are disjoint
598 RuntimePointerCheck PtrRtCheck;
599 /// Can we assume the absence of NaNs.
600 bool HasFunNoNaNAttr;
603 /// LoopVectorizationCostModel - estimates the expected speedups due to
605 /// In many cases vectorization is not profitable. This can happen because of
606 /// a number of reasons. In this class we mainly attempt to predict the
607 /// expected speedup/slowdowns due to the supported instruction set. We use the
608 /// TargetTransformInfo to query the different backends for the cost of
609 /// different operations.
610 class LoopVectorizationCostModel {
612 LoopVectorizationCostModel(Loop *L, ScalarEvolution *SE, LoopInfo *LI,
613 LoopVectorizationLegality *Legal,
614 const TargetTransformInfo &TTI,
615 DataLayout *DL, const TargetLibraryInfo *TLI)
616 : TheLoop(L), SE(SE), LI(LI), Legal(Legal), TTI(TTI), DL(DL), TLI(TLI) {}
618 /// Information about vectorization costs
619 struct VectorizationFactor {
620 unsigned Width; // Vector width with best cost
621 unsigned Cost; // Cost of the loop with that width
623 /// \return The most profitable vectorization factor and the cost of that VF.
624 /// This method checks every power of two up to VF. If UserVF is not ZERO
625 /// then this vectorization factor will be selected if vectorization is
627 VectorizationFactor selectVectorizationFactor(bool OptForSize,
630 /// \return The size (in bits) of the widest type in the code that
631 /// needs to be vectorized. We ignore values that remain scalar such as
632 /// 64 bit loop indices.
633 unsigned getWidestType();
635 /// \return The most profitable unroll factor.
636 /// If UserUF is non-zero then this method finds the best unroll-factor
637 /// based on register pressure and other parameters.
638 /// VF and LoopCost are the selected vectorization factor and the cost of the
640 unsigned selectUnrollFactor(bool OptForSize, unsigned UserUF, unsigned VF,
643 /// \brief A struct that represents some properties of the register usage
645 struct RegisterUsage {
646 /// Holds the number of loop invariant values that are used in the loop.
647 unsigned LoopInvariantRegs;
648 /// Holds the maximum number of concurrent live intervals in the loop.
649 unsigned MaxLocalUsers;
650 /// Holds the number of instructions in the loop.
651 unsigned NumInstructions;
654 /// \return information about the register usage of the loop.
655 RegisterUsage calculateRegisterUsage();
658 /// Returns the expected execution cost. The unit of the cost does
659 /// not matter because we use the 'cost' units to compare different
660 /// vector widths. The cost that is returned is *not* normalized by
661 /// the factor width.
662 unsigned expectedCost(unsigned VF);
664 /// Returns the execution time cost of an instruction for a given vector
665 /// width. Vector width of one means scalar.
666 unsigned getInstructionCost(Instruction *I, unsigned VF);
668 /// A helper function for converting Scalar types to vector types.
669 /// If the incoming type is void, we return void. If the VF is 1, we return
671 static Type* ToVectorTy(Type *Scalar, unsigned VF);
673 /// Returns whether the instruction is a load or store and will be a emitted
674 /// as a vector operation.
675 bool isConsecutiveLoadOrStore(Instruction *I);
677 /// The loop that we evaluate.
681 /// Loop Info analysis.
683 /// Vectorization legality.
684 LoopVectorizationLegality *Legal;
685 /// Vector target information.
686 const TargetTransformInfo &TTI;
687 /// Target data layout information.
689 /// Target Library Info.
690 const TargetLibraryInfo *TLI;
693 /// The LoopVectorize Pass.
694 struct LoopVectorize : public LoopPass {
695 /// Pass identification, replacement for typeid
698 explicit LoopVectorize() : LoopPass(ID) {
699 initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
705 TargetTransformInfo *TTI;
708 TargetLibraryInfo *TLI;
710 virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
711 // We only vectorize innermost loops.
715 SE = &getAnalysis<ScalarEvolution>();
716 DL = getAnalysisIfAvailable<DataLayout>();
717 LI = &getAnalysis<LoopInfo>();
718 TTI = &getAnalysis<TargetTransformInfo>();
719 DT = &getAnalysis<DominatorTree>();
720 AA = getAnalysisIfAvailable<AliasAnalysis>();
721 TLI = getAnalysisIfAvailable<TargetLibraryInfo>();
724 DEBUG(dbgs() << "LV: Not vectorizing because of missing data layout");
728 DEBUG(dbgs() << "LV: Checking a loop in \"" <<
729 L->getHeader()->getParent()->getName() << "\"\n");
731 // Check if it is legal to vectorize the loop.
732 LoopVectorizationLegality LVL(L, SE, DL, DT, TTI, AA, TLI);
733 if (!LVL.canVectorize()) {
734 DEBUG(dbgs() << "LV: Not vectorizing.\n");
738 // Use the cost model.
739 LoopVectorizationCostModel CM(L, SE, LI, &LVL, *TTI, DL, TLI);
741 // Check the function attributes to find out if this function should be
742 // optimized for size.
743 Function *F = L->getHeader()->getParent();
744 Attribute::AttrKind SzAttr = Attribute::OptimizeForSize;
745 Attribute::AttrKind FlAttr = Attribute::NoImplicitFloat;
746 unsigned FnIndex = AttributeSet::FunctionIndex;
747 bool OptForSize = F->getAttributes().hasAttribute(FnIndex, SzAttr);
748 bool NoFloat = F->getAttributes().hasAttribute(FnIndex, FlAttr);
751 DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
752 "attribute is used.\n");
756 // Select the optimal vectorization factor.
757 LoopVectorizationCostModel::VectorizationFactor VF;
758 VF = CM.selectVectorizationFactor(OptForSize, VectorizationFactor);
759 // Select the unroll factor.
760 unsigned UF = CM.selectUnrollFactor(OptForSize, VectorizationUnroll,
764 DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
768 DEBUG(dbgs() << "LV: Found a vectorizable loop ("<< VF.Width << ") in "<<
769 F->getParent()->getModuleIdentifier()<<"\n");
770 DEBUG(dbgs() << "LV: Unroll Factor is " << UF << "\n");
772 // If we decided that it is *legal* to vectorize the loop then do it.
773 InnerLoopVectorizer LB(L, SE, LI, DT, DL, TLI, VF.Width, UF);
776 DEBUG(verifyFunction(*L->getHeader()->getParent()));
780 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
781 LoopPass::getAnalysisUsage(AU);
782 AU.addRequiredID(LoopSimplifyID);
783 AU.addRequiredID(LCSSAID);
784 AU.addRequired<DominatorTree>();
785 AU.addRequired<LoopInfo>();
786 AU.addRequired<ScalarEvolution>();
787 AU.addRequired<TargetTransformInfo>();
788 AU.addPreserved<LoopInfo>();
789 AU.addPreserved<DominatorTree>();
794 } // end anonymous namespace
796 //===----------------------------------------------------------------------===//
797 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
798 // LoopVectorizationCostModel.
799 //===----------------------------------------------------------------------===//
802 LoopVectorizationLegality::RuntimePointerCheck::insert(ScalarEvolution *SE,
803 Loop *Lp, Value *Ptr,
805 const SCEV *Sc = SE->getSCEV(Ptr);
806 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
807 assert(AR && "Invalid addrec expression");
808 const SCEV *Ex = SE->getExitCount(Lp, Lp->getLoopLatch());
809 const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
810 Pointers.push_back(Ptr);
811 Starts.push_back(AR->getStart());
812 Ends.push_back(ScEnd);
813 IsWritePtr.push_back(WritePtr);
816 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
817 // Save the current insertion location.
818 Instruction *Loc = Builder.GetInsertPoint();
820 // We need to place the broadcast of invariant variables outside the loop.
821 Instruction *Instr = dyn_cast<Instruction>(V);
822 bool NewInstr = (Instr && Instr->getParent() == LoopVectorBody);
823 bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
825 // Place the code for broadcasting invariant variables in the new preheader.
827 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
829 // Broadcast the scalar into all locations in the vector.
830 Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
832 // Restore the builder insertion point.
834 Builder.SetInsertPoint(Loc);
839 Value *InnerLoopVectorizer::getConsecutiveVector(Value* Val, int StartIdx,
841 assert(Val->getType()->isVectorTy() && "Must be a vector");
842 assert(Val->getType()->getScalarType()->isIntegerTy() &&
843 "Elem must be an integer");
845 Type *ITy = Val->getType()->getScalarType();
846 VectorType *Ty = cast<VectorType>(Val->getType());
847 int VLen = Ty->getNumElements();
848 SmallVector<Constant*, 8> Indices;
850 // Create a vector of consecutive numbers from zero to VF.
851 for (int i = 0; i < VLen; ++i) {
852 int64_t Idx = Negate ? (-i) : i;
853 Indices.push_back(ConstantInt::get(ITy, StartIdx + Idx, Negate));
856 // Add the consecutive indices to the vector value.
857 Constant *Cv = ConstantVector::get(Indices);
858 assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
859 return Builder.CreateAdd(Val, Cv, "induction");
862 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
863 assert(Ptr->getType()->isPointerTy() && "Unexpected non ptr");
864 // Make sure that the pointer does not point to structs.
865 if (cast<PointerType>(Ptr->getType())->getElementType()->isAggregateType())
868 // If this value is a pointer induction variable we know it is consecutive.
869 PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
870 if (Phi && Inductions.count(Phi)) {
871 InductionInfo II = Inductions[Phi];
872 if (IK_PtrInduction == II.IK)
874 else if (IK_ReversePtrInduction == II.IK)
878 GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
882 unsigned NumOperands = Gep->getNumOperands();
883 Value *LastIndex = Gep->getOperand(NumOperands - 1);
885 Value *GpPtr = Gep->getPointerOperand();
886 // If this GEP value is a consecutive pointer induction variable and all of
887 // the indices are constant then we know it is consecutive. We can
888 Phi = dyn_cast<PHINode>(GpPtr);
889 if (Phi && Inductions.count(Phi)) {
891 // Make sure that the pointer does not point to structs.
892 PointerType *GepPtrType = cast<PointerType>(GpPtr->getType());
893 if (GepPtrType->getElementType()->isAggregateType())
896 // Make sure that all of the index operands are loop invariant.
897 for (unsigned i = 1; i < NumOperands; ++i)
898 if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
901 InductionInfo II = Inductions[Phi];
902 if (IK_PtrInduction == II.IK)
904 else if (IK_ReversePtrInduction == II.IK)
908 // Check that all of the gep indices are uniform except for the last.
909 for (unsigned i = 0; i < NumOperands - 1; ++i)
910 if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
913 // We can emit wide load/stores only if the last index is the induction
915 const SCEV *Last = SE->getSCEV(LastIndex);
916 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
917 const SCEV *Step = AR->getStepRecurrence(*SE);
919 // The memory is consecutive because the last index is consecutive
920 // and all other indices are loop invariant.
923 if (Step->isAllOnesValue())
930 bool LoopVectorizationLegality::isUniform(Value *V) {
931 return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
934 InnerLoopVectorizer::VectorParts&
935 InnerLoopVectorizer::getVectorValue(Value *V) {
936 assert(V != Induction && "The new induction variable should not be used.");
937 assert(!V->getType()->isVectorTy() && "Can't widen a vector");
939 // If we have this scalar in the map, return it.
941 return WidenMap.get(V);
943 // If this scalar is unknown, assume that it is a constant or that it is
944 // loop invariant. Broadcast V and save the value for future uses.
945 Value *B = getBroadcastInstrs(V);
946 return WidenMap.splat(V, B);
949 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
950 assert(Vec->getType()->isVectorTy() && "Invalid type");
951 SmallVector<Constant*, 8> ShuffleMask;
952 for (unsigned i = 0; i < VF; ++i)
953 ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
955 return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
956 ConstantVector::get(ShuffleMask),
961 void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr,
962 LoopVectorizationLegality *Legal) {
963 // Attempt to issue a wide load.
964 LoadInst *LI = dyn_cast<LoadInst>(Instr);
965 StoreInst *SI = dyn_cast<StoreInst>(Instr);
967 assert((LI || SI) && "Invalid Load/Store instruction");
969 Type *ScalarDataTy = LI ? LI->getType() : SI->getValueOperand()->getType();
970 Type *DataTy = VectorType::get(ScalarDataTy, VF);
971 Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
972 unsigned Alignment = LI ? LI->getAlignment() : SI->getAlignment();
974 unsigned ScalarAllocatedSize = DL->getTypeAllocSize(ScalarDataTy);
975 unsigned VectorElementSize = DL->getTypeStoreSize(DataTy)/VF;
977 if (ScalarAllocatedSize != VectorElementSize)
978 return scalarizeInstruction(Instr);
980 // If the pointer is loop invariant or if it is non consecutive,
981 // scalarize the load.
982 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
983 bool Reverse = ConsecutiveStride < 0;
984 bool UniformLoad = LI && Legal->isUniform(Ptr);
985 if (!ConsecutiveStride || UniformLoad)
986 return scalarizeInstruction(Instr);
988 Constant *Zero = Builder.getInt32(0);
989 VectorParts &Entry = WidenMap.get(Instr);
991 // Handle consecutive loads/stores.
992 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
993 if (Gep && Legal->isInductionVariable(Gep->getPointerOperand())) {
994 Value *PtrOperand = Gep->getPointerOperand();
995 Value *FirstBasePtr = getVectorValue(PtrOperand)[0];
996 FirstBasePtr = Builder.CreateExtractElement(FirstBasePtr, Zero);
998 // Create the new GEP with the new induction variable.
999 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1000 Gep2->setOperand(0, FirstBasePtr);
1001 Gep2->setName("gep.indvar.base");
1002 Ptr = Builder.Insert(Gep2);
1004 assert(SE->isLoopInvariant(SE->getSCEV(Gep->getPointerOperand()),
1005 OrigLoop) && "Base ptr must be invariant");
1007 // The last index does not have to be the induction. It can be
1008 // consecutive and be a function of the index. For example A[I+1];
1009 unsigned NumOperands = Gep->getNumOperands();
1011 Value *LastGepOperand = Gep->getOperand(NumOperands - 1);
1012 VectorParts &GEPParts = getVectorValue(LastGepOperand);
1013 Value *LastIndex = GEPParts[0];
1014 LastIndex = Builder.CreateExtractElement(LastIndex, Zero);
1016 // Create the new GEP with the new induction variable.
1017 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1018 Gep2->setOperand(NumOperands - 1, LastIndex);
1019 Gep2->setName("gep.indvar.idx");
1020 Ptr = Builder.Insert(Gep2);
1022 // Use the induction element ptr.
1023 assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1024 VectorParts &PtrVal = getVectorValue(Ptr);
1025 Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
1030 assert(!Legal->isUniform(SI->getPointerOperand()) &&
1031 "We do not allow storing to uniform addresses");
1033 VectorParts &StoredVal = getVectorValue(SI->getValueOperand());
1034 for (unsigned Part = 0; Part < UF; ++Part) {
1035 // Calculate the pointer for the specific unroll-part.
1036 Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1039 // If we store to reverse consecutive memory locations then we need
1040 // to reverse the order of elements in the stored value.
1041 StoredVal[Part] = reverseVector(StoredVal[Part]);
1042 // If the address is consecutive but reversed, then the
1043 // wide store needs to start at the last vector element.
1044 PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1045 PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1048 Value *VecPtr = Builder.CreateBitCast(PartPtr, DataTy->getPointerTo());
1049 Builder.CreateStore(StoredVal[Part], VecPtr)->setAlignment(Alignment);
1053 for (unsigned Part = 0; Part < UF; ++Part) {
1054 // Calculate the pointer for the specific unroll-part.
1055 Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1058 // If the address is consecutive but reversed, then the
1059 // wide store needs to start at the last vector element.
1060 PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1061 PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1064 Value *VecPtr = Builder.CreateBitCast(PartPtr, DataTy->getPointerTo());
1065 Value *LI = Builder.CreateLoad(VecPtr, "wide.load");
1066 cast<LoadInst>(LI)->setAlignment(Alignment);
1067 Entry[Part] = Reverse ? reverseVector(LI) : LI;
1071 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr) {
1072 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
1073 // Holds vector parameters or scalars, in case of uniform vals.
1074 SmallVector<VectorParts, 4> Params;
1076 // Find all of the vectorized parameters.
1077 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
1078 Value *SrcOp = Instr->getOperand(op);
1080 // If we are accessing the old induction variable, use the new one.
1081 if (SrcOp == OldInduction) {
1082 Params.push_back(getVectorValue(SrcOp));
1086 // Try using previously calculated values.
1087 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
1089 // If the src is an instruction that appeared earlier in the basic block
1090 // then it should already be vectorized.
1091 if (SrcInst && OrigLoop->contains(SrcInst)) {
1092 assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
1093 // The parameter is a vector value from earlier.
1094 Params.push_back(WidenMap.get(SrcInst));
1096 // The parameter is a scalar from outside the loop. Maybe even a constant.
1097 VectorParts Scalars;
1098 Scalars.append(UF, SrcOp);
1099 Params.push_back(Scalars);
1103 assert(Params.size() == Instr->getNumOperands() &&
1104 "Invalid number of operands");
1106 // Does this instruction return a value ?
1107 bool IsVoidRetTy = Instr->getType()->isVoidTy();
1109 Value *UndefVec = IsVoidRetTy ? 0 :
1110 UndefValue::get(VectorType::get(Instr->getType(), VF));
1111 // Create a new entry in the WidenMap and initialize it to Undef or Null.
1112 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
1114 // For each vector unroll 'part':
1115 for (unsigned Part = 0; Part < UF; ++Part) {
1116 // For each scalar that we create:
1117 for (unsigned Width = 0; Width < VF; ++Width) {
1118 Instruction *Cloned = Instr->clone();
1120 Cloned->setName(Instr->getName() + ".cloned");
1121 // Replace the operands of the cloned instrucions with extracted scalars.
1122 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
1123 Value *Op = Params[op][Part];
1124 // Param is a vector. Need to extract the right lane.
1125 if (Op->getType()->isVectorTy())
1126 Op = Builder.CreateExtractElement(Op, Builder.getInt32(Width));
1127 Cloned->setOperand(op, Op);
1130 // Place the cloned scalar in the new loop.
1131 Builder.Insert(Cloned);
1133 // If the original scalar returns a value we need to place it in a vector
1134 // so that future users will be able to use it.
1136 VecResults[Part] = Builder.CreateInsertElement(VecResults[Part], Cloned,
1137 Builder.getInt32(Width));
1143 InnerLoopVectorizer::addRuntimeCheck(LoopVectorizationLegality *Legal,
1145 LoopVectorizationLegality::RuntimePointerCheck *PtrRtCheck =
1146 Legal->getRuntimePointerCheck();
1148 if (!PtrRtCheck->Need)
1151 Instruction *MemoryRuntimeCheck = 0;
1152 unsigned NumPointers = PtrRtCheck->Pointers.size();
1153 SmallVector<Value* , 2> Starts;
1154 SmallVector<Value* , 2> Ends;
1156 SCEVExpander Exp(*SE, "induction");
1158 // Use this type for pointer arithmetic.
1159 Type* PtrArithTy = Type::getInt8PtrTy(Loc->getContext(), 0);
1161 for (unsigned i = 0; i < NumPointers; ++i) {
1162 Value *Ptr = PtrRtCheck->Pointers[i];
1163 const SCEV *Sc = SE->getSCEV(Ptr);
1165 if (SE->isLoopInvariant(Sc, OrigLoop)) {
1166 DEBUG(dbgs() << "LV: Adding RT check for a loop invariant ptr:" <<
1168 Starts.push_back(Ptr);
1169 Ends.push_back(Ptr);
1171 DEBUG(dbgs() << "LV: Adding RT check for range:" << *Ptr <<"\n");
1173 Value *Start = Exp.expandCodeFor(PtrRtCheck->Starts[i], PtrArithTy, Loc);
1174 Value *End = Exp.expandCodeFor(PtrRtCheck->Ends[i], PtrArithTy, Loc);
1175 Starts.push_back(Start);
1176 Ends.push_back(End);
1180 IRBuilder<> ChkBuilder(Loc);
1182 for (unsigned i = 0; i < NumPointers; ++i) {
1183 for (unsigned j = i+1; j < NumPointers; ++j) {
1184 // No need to check if two readonly pointers intersect.
1185 if (!PtrRtCheck->IsWritePtr[i] && !PtrRtCheck->IsWritePtr[j])
1188 Value *Start0 = ChkBuilder.CreateBitCast(Starts[i], PtrArithTy, "bc");
1189 Value *Start1 = ChkBuilder.CreateBitCast(Starts[j], PtrArithTy, "bc");
1190 Value *End0 = ChkBuilder.CreateBitCast(Ends[i], PtrArithTy, "bc");
1191 Value *End1 = ChkBuilder.CreateBitCast(Ends[j], PtrArithTy, "bc");
1193 Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0");
1194 Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1");
1195 Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
1196 if (MemoryRuntimeCheck)
1197 IsConflict = ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict,
1200 MemoryRuntimeCheck = cast<Instruction>(IsConflict);
1204 return MemoryRuntimeCheck;
1208 InnerLoopVectorizer::createEmptyLoop(LoopVectorizationLegality *Legal) {
1210 In this function we generate a new loop. The new loop will contain
1211 the vectorized instructions while the old loop will continue to run the
1214 [ ] <-- vector loop bypass (may consist of multiple blocks).
1217 | [ ] <-- vector pre header.
1221 | [ ]_| <-- vector loop.
1224 >[ ] <--- middle-block.
1227 | [ ] <--- new preheader.
1231 | [ ]_| <-- old scalar loop to handle remainder.
1234 >[ ] <-- exit block.
1238 BasicBlock *OldBasicBlock = OrigLoop->getHeader();
1239 BasicBlock *BypassBlock = OrigLoop->getLoopPreheader();
1240 BasicBlock *ExitBlock = OrigLoop->getExitBlock();
1241 assert(ExitBlock && "Must have an exit block");
1243 // Mark the old scalar loop with metadata that tells us not to vectorize this
1244 // loop again if we run into it.
1245 MDNode *MD = MDNode::get(OldBasicBlock->getContext(), None);
1246 OldBasicBlock->getTerminator()->setMetadata(AlreadyVectorizedMDName, MD);
1248 // Some loops have a single integer induction variable, while other loops
1249 // don't. One example is c++ iterators that often have multiple pointer
1250 // induction variables. In the code below we also support a case where we
1251 // don't have a single induction variable.
1252 OldInduction = Legal->getInduction();
1253 Type *IdxTy = Legal->getWidestInductionType();
1255 // Find the loop boundaries.
1256 const SCEV *ExitCount = SE->getExitCount(OrigLoop, OrigLoop->getLoopLatch());
1257 assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
1259 // Get the total trip count from the count by adding 1.
1260 ExitCount = SE->getAddExpr(ExitCount,
1261 SE->getConstant(ExitCount->getType(), 1));
1263 // Expand the trip count and place the new instructions in the preheader.
1264 // Notice that the pre-header does not change, only the loop body.
1265 SCEVExpander Exp(*SE, "induction");
1267 // Count holds the overall loop count (N).
1268 Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
1269 BypassBlock->getTerminator());
1271 // The loop index does not have to start at Zero. Find the original start
1272 // value from the induction PHI node. If we don't have an induction variable
1273 // then we know that it starts at zero.
1274 Builder.SetInsertPoint(BypassBlock->getTerminator());
1275 Value *StartIdx = ExtendedIdx = OldInduction ?
1276 Builder.CreateZExt(OldInduction->getIncomingValueForBlock(BypassBlock),
1278 ConstantInt::get(IdxTy, 0);
1280 assert(BypassBlock && "Invalid loop structure");
1281 LoopBypassBlocks.push_back(BypassBlock);
1283 // Split the single block loop into the two loop structure described above.
1284 BasicBlock *VectorPH =
1285 BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
1286 BasicBlock *VecBody =
1287 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
1288 BasicBlock *MiddleBlock =
1289 VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
1290 BasicBlock *ScalarPH =
1291 MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
1293 // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
1295 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
1297 // Generate the induction variable.
1298 Induction = Builder.CreatePHI(IdxTy, 2, "index");
1299 // The loop step is equal to the vectorization factor (num of SIMD elements)
1300 // times the unroll factor (num of SIMD instructions).
1301 Constant *Step = ConstantInt::get(IdxTy, VF * UF);
1303 // This is the IR builder that we use to add all of the logic for bypassing
1304 // the new vector loop.
1305 IRBuilder<> BypassBuilder(BypassBlock->getTerminator());
1307 // We may need to extend the index in case there is a type mismatch.
1308 // We know that the count starts at zero and does not overflow.
1309 if (Count->getType() != IdxTy) {
1310 // The exit count can be of pointer type. Convert it to the correct
1312 if (ExitCount->getType()->isPointerTy())
1313 Count = BypassBuilder.CreatePointerCast(Count, IdxTy, "ptrcnt.to.int");
1315 Count = BypassBuilder.CreateZExtOrTrunc(Count, IdxTy, "cnt.cast");
1318 // Add the start index to the loop count to get the new end index.
1319 Value *IdxEnd = BypassBuilder.CreateAdd(Count, StartIdx, "end.idx");
1321 // Now we need to generate the expression for N - (N % VF), which is
1322 // the part that the vectorized body will execute.
1323 Value *R = BypassBuilder.CreateURem(Count, Step, "n.mod.vf");
1324 Value *CountRoundDown = BypassBuilder.CreateSub(Count, R, "n.vec");
1325 Value *IdxEndRoundDown = BypassBuilder.CreateAdd(CountRoundDown, StartIdx,
1326 "end.idx.rnd.down");
1328 // Now, compare the new count to zero. If it is zero skip the vector loop and
1329 // jump to the scalar loop.
1330 Value *Cmp = BypassBuilder.CreateICmpEQ(IdxEndRoundDown, StartIdx,
1333 BasicBlock *LastBypassBlock = BypassBlock;
1335 // Generate the code that checks in runtime if arrays overlap. We put the
1336 // checks into a separate block to make the more common case of few elements
1338 Instruction *MemRuntimeCheck = addRuntimeCheck(Legal,
1339 BypassBlock->getTerminator());
1340 if (MemRuntimeCheck) {
1341 // Create a new block containing the memory check.
1342 BasicBlock *CheckBlock = BypassBlock->splitBasicBlock(MemRuntimeCheck,
1344 LoopBypassBlocks.push_back(CheckBlock);
1346 // Replace the branch into the memory check block with a conditional branch
1347 // for the "few elements case".
1348 Instruction *OldTerm = BypassBlock->getTerminator();
1349 BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
1350 OldTerm->eraseFromParent();
1352 Cmp = MemRuntimeCheck;
1353 LastBypassBlock = CheckBlock;
1356 LastBypassBlock->getTerminator()->eraseFromParent();
1357 BranchInst::Create(MiddleBlock, VectorPH, Cmp,
1360 // We are going to resume the execution of the scalar loop.
1361 // Go over all of the induction variables that we found and fix the
1362 // PHIs that are left in the scalar version of the loop.
1363 // The starting values of PHI nodes depend on the counter of the last
1364 // iteration in the vectorized loop.
1365 // If we come from a bypass edge then we need to start from the original
1368 // This variable saves the new starting index for the scalar loop.
1369 PHINode *ResumeIndex = 0;
1370 LoopVectorizationLegality::InductionList::iterator I, E;
1371 LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
1372 // Set builder to point to last bypass block.
1373 BypassBuilder.SetInsertPoint(LoopBypassBlocks.back()->getTerminator());
1374 for (I = List->begin(), E = List->end(); I != E; ++I) {
1375 PHINode *OrigPhi = I->first;
1376 LoopVectorizationLegality::InductionInfo II = I->second;
1378 Type *ResumeValTy = (OrigPhi == OldInduction) ? IdxTy : OrigPhi->getType();
1379 PHINode *ResumeVal = PHINode::Create(ResumeValTy, 2, "resume.val",
1380 MiddleBlock->getTerminator());
1381 // We might have extended the type of the induction variable but we need a
1382 // truncated version for the scalar loop.
1383 PHINode *TruncResumeVal = (OrigPhi == OldInduction) ?
1384 PHINode::Create(OrigPhi->getType(), 2, "trunc.resume.val",
1385 MiddleBlock->getTerminator()) : 0;
1387 Value *EndValue = 0;
1389 case LoopVectorizationLegality::IK_NoInduction:
1390 llvm_unreachable("Unknown induction");
1391 case LoopVectorizationLegality::IK_IntInduction: {
1392 // Handle the integer induction counter.
1393 assert(OrigPhi->getType()->isIntegerTy() && "Invalid type");
1395 // We have the canonical induction variable.
1396 if (OrigPhi == OldInduction) {
1397 // Create a truncated version of the resume value for the scalar loop,
1398 // we might have promoted the type to a larger width.
1400 BypassBuilder.CreateTrunc(IdxEndRoundDown, OrigPhi->getType());
1401 // The new PHI merges the original incoming value, in case of a bypass,
1402 // or the value at the end of the vectorized loop.
1403 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
1404 TruncResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
1405 TruncResumeVal->addIncoming(EndValue, VecBody);
1407 // We know what the end value is.
1408 EndValue = IdxEndRoundDown;
1409 // We also know which PHI node holds it.
1410 ResumeIndex = ResumeVal;
1414 // Not the canonical induction variable - add the vector loop count to the
1416 Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown,
1417 II.StartValue->getType(),
1419 EndValue = BypassBuilder.CreateAdd(CRD, II.StartValue , "ind.end");
1422 case LoopVectorizationLegality::IK_ReverseIntInduction: {
1423 // Convert the CountRoundDown variable to the PHI size.
1424 Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown,
1425 II.StartValue->getType(),
1427 // Handle reverse integer induction counter.
1428 EndValue = BypassBuilder.CreateSub(II.StartValue, CRD, "rev.ind.end");
1431 case LoopVectorizationLegality::IK_PtrInduction: {
1432 // For pointer induction variables, calculate the offset using
1434 EndValue = BypassBuilder.CreateGEP(II.StartValue, CountRoundDown,
1438 case LoopVectorizationLegality::IK_ReversePtrInduction: {
1439 // The value at the end of the loop for the reverse pointer is calculated
1440 // by creating a GEP with a negative index starting from the start value.
1441 Value *Zero = ConstantInt::get(CountRoundDown->getType(), 0);
1442 Value *NegIdx = BypassBuilder.CreateSub(Zero, CountRoundDown,
1444 EndValue = BypassBuilder.CreateGEP(II.StartValue, NegIdx,
1450 // The new PHI merges the original incoming value, in case of a bypass,
1451 // or the value at the end of the vectorized loop.
1452 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I) {
1453 if (OrigPhi == OldInduction)
1454 ResumeVal->addIncoming(StartIdx, LoopBypassBlocks[I]);
1456 ResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
1458 ResumeVal->addIncoming(EndValue, VecBody);
1460 // Fix the scalar body counter (PHI node).
1461 unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
1462 // The old inductions phi node in the scalar body needs the truncated value.
1463 if (OrigPhi == OldInduction)
1464 OrigPhi->setIncomingValue(BlockIdx, TruncResumeVal);
1466 OrigPhi->setIncomingValue(BlockIdx, ResumeVal);
1469 // If we are generating a new induction variable then we also need to
1470 // generate the code that calculates the exit value. This value is not
1471 // simply the end of the counter because we may skip the vectorized body
1472 // in case of a runtime check.
1474 assert(!ResumeIndex && "Unexpected resume value found");
1475 ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val",
1476 MiddleBlock->getTerminator());
1477 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
1478 ResumeIndex->addIncoming(StartIdx, LoopBypassBlocks[I]);
1479 ResumeIndex->addIncoming(IdxEndRoundDown, VecBody);
1482 // Make sure that we found the index where scalar loop needs to continue.
1483 assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() &&
1484 "Invalid resume Index");
1486 // Add a check in the middle block to see if we have completed
1487 // all of the iterations in the first vector loop.
1488 // If (N - N%VF) == N, then we *don't* need to run the remainder.
1489 Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd,
1490 ResumeIndex, "cmp.n",
1491 MiddleBlock->getTerminator());
1493 BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
1494 // Remove the old terminator.
1495 MiddleBlock->getTerminator()->eraseFromParent();
1497 // Create i+1 and fill the PHINode.
1498 Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
1499 Induction->addIncoming(StartIdx, VectorPH);
1500 Induction->addIncoming(NextIdx, VecBody);
1501 // Create the compare.
1502 Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown);
1503 Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
1505 // Now we have two terminators. Remove the old one from the block.
1506 VecBody->getTerminator()->eraseFromParent();
1508 // Get ready to start creating new instructions into the vectorized body.
1509 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
1511 // Create and register the new vector loop.
1512 Loop* Lp = new Loop();
1513 Loop *ParentLoop = OrigLoop->getParentLoop();
1515 // Insert the new loop into the loop nest and register the new basic blocks.
1517 ParentLoop->addChildLoop(Lp);
1518 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
1519 ParentLoop->addBasicBlockToLoop(LoopBypassBlocks[I], LI->getBase());
1520 ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase());
1521 ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase());
1522 ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase());
1524 LI->addTopLevelLoop(Lp);
1527 Lp->addBasicBlockToLoop(VecBody, LI->getBase());
1530 LoopVectorPreHeader = VectorPH;
1531 LoopScalarPreHeader = ScalarPH;
1532 LoopMiddleBlock = MiddleBlock;
1533 LoopExitBlock = ExitBlock;
1534 LoopVectorBody = VecBody;
1535 LoopScalarBody = OldBasicBlock;
1538 /// This function returns the identity element (or neutral element) for
1539 /// the operation K.
1541 LoopVectorizationLegality::getReductionIdentity(ReductionKind K, Type *Tp) {
1546 // Adding, Xoring, Oring zero to a number does not change it.
1547 return ConstantInt::get(Tp, 0);
1548 case RK_IntegerMult:
1549 // Multiplying a number by 1 does not change it.
1550 return ConstantInt::get(Tp, 1);
1552 // AND-ing a number with an all-1 value does not change it.
1553 return ConstantInt::get(Tp, -1, true);
1555 // Multiplying a number by 1 does not change it.
1556 return ConstantFP::get(Tp, 1.0L);
1558 // Adding zero to a number does not change it.
1559 return ConstantFP::get(Tp, 0.0L);
1561 llvm_unreachable("Unknown reduction kind");
1565 static Intrinsic::ID
1566 getIntrinsicIDForCall(CallInst *CI, const TargetLibraryInfo *TLI) {
1567 // If we have an intrinsic call, check if it is trivially vectorizable.
1568 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
1569 switch (II->getIntrinsicID()) {
1570 case Intrinsic::sqrt:
1571 case Intrinsic::sin:
1572 case Intrinsic::cos:
1573 case Intrinsic::exp:
1574 case Intrinsic::exp2:
1575 case Intrinsic::log:
1576 case Intrinsic::log10:
1577 case Intrinsic::log2:
1578 case Intrinsic::fabs:
1579 case Intrinsic::floor:
1580 case Intrinsic::ceil:
1581 case Intrinsic::trunc:
1582 case Intrinsic::rint:
1583 case Intrinsic::nearbyint:
1584 case Intrinsic::pow:
1585 case Intrinsic::fma:
1586 case Intrinsic::fmuladd:
1587 return II->getIntrinsicID();
1589 return Intrinsic::not_intrinsic;
1594 return Intrinsic::not_intrinsic;
1597 Function *F = CI->getCalledFunction();
1598 // We're going to make assumptions on the semantics of the functions, check
1599 // that the target knows that it's available in this environment.
1600 if (!F || !TLI->getLibFunc(F->getName(), Func))
1601 return Intrinsic::not_intrinsic;
1603 // Otherwise check if we have a call to a function that can be turned into a
1604 // vector intrinsic.
1611 return Intrinsic::sin;
1615 return Intrinsic::cos;
1619 return Intrinsic::exp;
1621 case LibFunc::exp2f:
1622 case LibFunc::exp2l:
1623 return Intrinsic::exp2;
1627 return Intrinsic::log;
1628 case LibFunc::log10:
1629 case LibFunc::log10f:
1630 case LibFunc::log10l:
1631 return Intrinsic::log10;
1633 case LibFunc::log2f:
1634 case LibFunc::log2l:
1635 return Intrinsic::log2;
1637 case LibFunc::fabsf:
1638 case LibFunc::fabsl:
1639 return Intrinsic::fabs;
1640 case LibFunc::floor:
1641 case LibFunc::floorf:
1642 case LibFunc::floorl:
1643 return Intrinsic::floor;
1645 case LibFunc::ceilf:
1646 case LibFunc::ceill:
1647 return Intrinsic::ceil;
1648 case LibFunc::trunc:
1649 case LibFunc::truncf:
1650 case LibFunc::truncl:
1651 return Intrinsic::trunc;
1653 case LibFunc::rintf:
1654 case LibFunc::rintl:
1655 return Intrinsic::rint;
1656 case LibFunc::nearbyint:
1657 case LibFunc::nearbyintf:
1658 case LibFunc::nearbyintl:
1659 return Intrinsic::nearbyint;
1663 return Intrinsic::pow;
1666 return Intrinsic::not_intrinsic;
1669 /// This function translates the reduction kind to an LLVM binary operator.
1671 getReductionBinOp(LoopVectorizationLegality::ReductionKind Kind) {
1673 case LoopVectorizationLegality::RK_IntegerAdd:
1674 return Instruction::Add;
1675 case LoopVectorizationLegality::RK_IntegerMult:
1676 return Instruction::Mul;
1677 case LoopVectorizationLegality::RK_IntegerOr:
1678 return Instruction::Or;
1679 case LoopVectorizationLegality::RK_IntegerAnd:
1680 return Instruction::And;
1681 case LoopVectorizationLegality::RK_IntegerXor:
1682 return Instruction::Xor;
1683 case LoopVectorizationLegality::RK_FloatMult:
1684 return Instruction::FMul;
1685 case LoopVectorizationLegality::RK_FloatAdd:
1686 return Instruction::FAdd;
1687 case LoopVectorizationLegality::RK_IntegerMinMax:
1688 return Instruction::ICmp;
1689 case LoopVectorizationLegality::RK_FloatMinMax:
1690 return Instruction::FCmp;
1692 llvm_unreachable("Unknown reduction operation");
1696 Value *createMinMaxOp(IRBuilder<> &Builder,
1697 LoopVectorizationLegality::MinMaxReductionKind RK,
1700 CmpInst::Predicate P = CmpInst::ICMP_NE;
1703 llvm_unreachable("Unknown min/max reduction kind");
1704 case LoopVectorizationLegality::MRK_UIntMin:
1705 P = CmpInst::ICMP_ULT;
1707 case LoopVectorizationLegality::MRK_UIntMax:
1708 P = CmpInst::ICMP_UGT;
1710 case LoopVectorizationLegality::MRK_SIntMin:
1711 P = CmpInst::ICMP_SLT;
1713 case LoopVectorizationLegality::MRK_SIntMax:
1714 P = CmpInst::ICMP_SGT;
1716 case LoopVectorizationLegality::MRK_FloatMin:
1717 P = CmpInst::FCMP_OLT;
1719 case LoopVectorizationLegality::MRK_FloatMax:
1720 P = CmpInst::FCMP_OGT;
1725 if (RK == LoopVectorizationLegality::MRK_FloatMin || RK == LoopVectorizationLegality::MRK_FloatMax)
1726 Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp");
1728 Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp");
1730 Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
1735 InnerLoopVectorizer::vectorizeLoop(LoopVectorizationLegality *Legal) {
1736 //===------------------------------------------------===//
1738 // Notice: any optimization or new instruction that go
1739 // into the code below should be also be implemented in
1742 //===------------------------------------------------===//
1743 Constant *Zero = Builder.getInt32(0);
1745 // In order to support reduction variables we need to be able to vectorize
1746 // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
1747 // stages. First, we create a new vector PHI node with no incoming edges.
1748 // We use this value when we vectorize all of the instructions that use the
1749 // PHI. Next, after all of the instructions in the block are complete we
1750 // add the new incoming edges to the PHI. At this point all of the
1751 // instructions in the basic block are vectorized, so we can use them to
1752 // construct the PHI.
1753 PhiVector RdxPHIsToFix;
1755 // Scan the loop in a topological order to ensure that defs are vectorized
1757 LoopBlocksDFS DFS(OrigLoop);
1760 // Vectorize all of the blocks in the original loop.
1761 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
1762 be = DFS.endRPO(); bb != be; ++bb)
1763 vectorizeBlockInLoop(Legal, *bb, &RdxPHIsToFix);
1765 // At this point every instruction in the original loop is widened to
1766 // a vector form. We are almost done. Now, we need to fix the PHI nodes
1767 // that we vectorized. The PHI nodes are currently empty because we did
1768 // not want to introduce cycles. Notice that the remaining PHI nodes
1769 // that we need to fix are reduction variables.
1771 // Create the 'reduced' values for each of the induction vars.
1772 // The reduced values are the vector values that we scalarize and combine
1773 // after the loop is finished.
1774 for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
1776 PHINode *RdxPhi = *it;
1777 assert(RdxPhi && "Unable to recover vectorized PHI");
1779 // Find the reduction variable descriptor.
1780 assert(Legal->getReductionVars()->count(RdxPhi) &&
1781 "Unable to find the reduction variable");
1782 LoopVectorizationLegality::ReductionDescriptor RdxDesc =
1783 (*Legal->getReductionVars())[RdxPhi];
1785 // We need to generate a reduction vector from the incoming scalar.
1786 // To do so, we need to generate the 'identity' vector and overide
1787 // one of the elements with the incoming scalar reduction. We need
1788 // to do it in the vector-loop preheader.
1789 Builder.SetInsertPoint(LoopBypassBlocks.front()->getTerminator());
1791 // This is the vector-clone of the value that leaves the loop.
1792 VectorParts &VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
1793 Type *VecTy = VectorExit[0]->getType();
1795 // Find the reduction identity variable. Zero for addition, or, xor,
1796 // one for multiplication, -1 for And.
1799 if (RdxDesc.Kind == LoopVectorizationLegality::RK_IntegerMinMax ||
1800 RdxDesc.Kind == LoopVectorizationLegality::RK_FloatMinMax) {
1801 // MinMax reduction have the start value as their identify.
1802 VectorStart = Identity = Builder.CreateVectorSplat(VF, RdxDesc.StartValue,
1806 LoopVectorizationLegality::getReductionIdentity(RdxDesc.Kind,
1807 VecTy->getScalarType());
1808 Identity = ConstantVector::getSplat(VF, Iden);
1810 // This vector is the Identity vector where the first element is the
1811 // incoming scalar reduction.
1812 VectorStart = Builder.CreateInsertElement(Identity,
1813 RdxDesc.StartValue, Zero);
1816 // Fix the vector-loop phi.
1817 // We created the induction variable so we know that the
1818 // preheader is the first entry.
1819 BasicBlock *VecPreheader = Induction->getIncomingBlock(0);
1821 // Reductions do not have to start at zero. They can start with
1822 // any loop invariant values.
1823 VectorParts &VecRdxPhi = WidenMap.get(RdxPhi);
1824 BasicBlock *Latch = OrigLoop->getLoopLatch();
1825 Value *LoopVal = RdxPhi->getIncomingValueForBlock(Latch);
1826 VectorParts &Val = getVectorValue(LoopVal);
1827 for (unsigned part = 0; part < UF; ++part) {
1828 // Make sure to add the reduction stat value only to the
1829 // first unroll part.
1830 Value *StartVal = (part == 0) ? VectorStart : Identity;
1831 cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal, VecPreheader);
1832 cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part], LoopVectorBody);
1835 // Before each round, move the insertion point right between
1836 // the PHIs and the values we are going to write.
1837 // This allows us to write both PHINodes and the extractelement
1839 Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
1841 VectorParts RdxParts;
1842 for (unsigned part = 0; part < UF; ++part) {
1843 // This PHINode contains the vectorized reduction variable, or
1844 // the initial value vector, if we bypass the vector loop.
1845 VectorParts &RdxExitVal = getVectorValue(RdxDesc.LoopExitInstr);
1846 PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
1847 Value *StartVal = (part == 0) ? VectorStart : Identity;
1848 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
1849 NewPhi->addIncoming(StartVal, LoopBypassBlocks[I]);
1850 NewPhi->addIncoming(RdxExitVal[part], LoopVectorBody);
1851 RdxParts.push_back(NewPhi);
1854 // Reduce all of the unrolled parts into a single vector.
1855 Value *ReducedPartRdx = RdxParts[0];
1856 unsigned Op = getReductionBinOp(RdxDesc.Kind);
1857 for (unsigned part = 1; part < UF; ++part) {
1858 if (Op != Instruction::ICmp && Op != Instruction::FCmp)
1859 ReducedPartRdx = Builder.CreateBinOp((Instruction::BinaryOps)Op,
1860 RdxParts[part], ReducedPartRdx,
1863 ReducedPartRdx = createMinMaxOp(Builder, RdxDesc.MinMaxKind,
1864 ReducedPartRdx, RdxParts[part]);
1867 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
1868 // and vector ops, reducing the set of values being computed by half each
1870 assert(isPowerOf2_32(VF) &&
1871 "Reduction emission only supported for pow2 vectors!");
1872 Value *TmpVec = ReducedPartRdx;
1873 SmallVector<Constant*, 32> ShuffleMask(VF, 0);
1874 for (unsigned i = VF; i != 1; i >>= 1) {
1875 // Move the upper half of the vector to the lower half.
1876 for (unsigned j = 0; j != i/2; ++j)
1877 ShuffleMask[j] = Builder.getInt32(i/2 + j);
1879 // Fill the rest of the mask with undef.
1880 std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
1881 UndefValue::get(Builder.getInt32Ty()));
1884 Builder.CreateShuffleVector(TmpVec,
1885 UndefValue::get(TmpVec->getType()),
1886 ConstantVector::get(ShuffleMask),
1889 if (Op != Instruction::ICmp && Op != Instruction::FCmp)
1890 TmpVec = Builder.CreateBinOp((Instruction::BinaryOps)Op, TmpVec, Shuf,
1893 TmpVec = createMinMaxOp(Builder, RdxDesc.MinMaxKind, TmpVec, Shuf);
1896 // The result is in the first element of the vector.
1897 Value *Scalar0 = Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
1899 // Now, we need to fix the users of the reduction variable
1900 // inside and outside of the scalar remainder loop.
1901 // We know that the loop is in LCSSA form. We need to update the
1902 // PHI nodes in the exit blocks.
1903 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
1904 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
1905 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
1906 if (!LCSSAPhi) continue;
1908 // All PHINodes need to have a single entry edge, or two if
1909 // we already fixed them.
1910 assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
1912 // We found our reduction value exit-PHI. Update it with the
1913 // incoming bypass edge.
1914 if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
1915 // Add an edge coming from the bypass.
1916 LCSSAPhi->addIncoming(Scalar0, LoopMiddleBlock);
1919 }// end of the LCSSA phi scan.
1921 // Fix the scalar loop reduction variable with the incoming reduction sum
1922 // from the vector body and from the backedge value.
1923 int IncomingEdgeBlockIdx =
1924 (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
1925 assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
1926 // Pick the other block.
1927 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
1928 (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, Scalar0);
1929 (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
1930 }// end of for each redux variable.
1932 // The Loop exit block may have single value PHI nodes where the incoming
1933 // value is 'undef'. While vectorizing we only handled real values that
1934 // were defined inside the loop. Here we handle the 'undef case'.
1936 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
1937 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
1938 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
1939 if (!LCSSAPhi) continue;
1940 if (LCSSAPhi->getNumIncomingValues() == 1)
1941 LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
1946 InnerLoopVectorizer::VectorParts
1947 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
1948 assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
1951 VectorParts SrcMask = createBlockInMask(Src);
1953 // The terminator has to be a branch inst!
1954 BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
1955 assert(BI && "Unexpected terminator found");
1957 if (BI->isConditional()) {
1958 VectorParts EdgeMask = getVectorValue(BI->getCondition());
1960 if (BI->getSuccessor(0) != Dst)
1961 for (unsigned part = 0; part < UF; ++part)
1962 EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
1964 for (unsigned part = 0; part < UF; ++part)
1965 EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
1972 InnerLoopVectorizer::VectorParts
1973 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
1974 assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
1976 // Loop incoming mask is all-one.
1977 if (OrigLoop->getHeader() == BB) {
1978 Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
1979 return getVectorValue(C);
1982 // This is the block mask. We OR all incoming edges, and with zero.
1983 Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
1984 VectorParts BlockMask = getVectorValue(Zero);
1987 for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
1988 VectorParts EM = createEdgeMask(*it, BB);
1989 for (unsigned part = 0; part < UF; ++part)
1990 BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
1997 InnerLoopVectorizer::vectorizeBlockInLoop(LoopVectorizationLegality *Legal,
1998 BasicBlock *BB, PhiVector *PV) {
1999 // For each instruction in the old loop.
2000 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2001 VectorParts &Entry = WidenMap.get(it);
2002 switch (it->getOpcode()) {
2003 case Instruction::Br:
2004 // Nothing to do for PHIs and BR, since we already took care of the
2005 // loop control flow instructions.
2007 case Instruction::PHI:{
2008 PHINode* P = cast<PHINode>(it);
2009 // Handle reduction variables:
2010 if (Legal->getReductionVars()->count(P)) {
2011 for (unsigned part = 0; part < UF; ++part) {
2012 // This is phase one of vectorizing PHIs.
2013 Type *VecTy = VectorType::get(it->getType(), VF);
2014 Entry[part] = PHINode::Create(VecTy, 2, "vec.phi",
2015 LoopVectorBody-> getFirstInsertionPt());
2021 // Check for PHI nodes that are lowered to vector selects.
2022 if (P->getParent() != OrigLoop->getHeader()) {
2023 // We know that all PHIs in non header blocks are converted into
2024 // selects, so we don't have to worry about the insertion order and we
2025 // can just use the builder.
2026 // At this point we generate the predication tree. There may be
2027 // duplications since this is a simple recursive scan, but future
2028 // optimizations will clean it up.
2030 unsigned NumIncoming = P->getNumIncomingValues();
2031 assert(NumIncoming > 1 && "Invalid PHI");
2033 // Generate a sequence of selects of the form:
2034 // SELECT(Mask3, In3,
2035 // SELECT(Mask2, In2,
2037 for (unsigned In = 0; In < NumIncoming; In++) {
2038 VectorParts Cond = createEdgeMask(P->getIncomingBlock(In),
2040 VectorParts &In0 = getVectorValue(P->getIncomingValue(In));
2042 for (unsigned part = 0; part < UF; ++part) {
2043 // We don't need to 'select' the first PHI operand because it is
2044 // the default value if all of the other masks don't match.
2046 Entry[part] = In0[part];
2048 // Select between the current value and the previous incoming edge
2049 // based on the incoming mask.
2050 Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
2051 Entry[part], "predphi");
2057 // This PHINode must be an induction variable.
2058 // Make sure that we know about it.
2059 assert(Legal->getInductionVars()->count(P) &&
2060 "Not an induction variable");
2062 LoopVectorizationLegality::InductionInfo II =
2063 Legal->getInductionVars()->lookup(P);
2066 case LoopVectorizationLegality::IK_NoInduction:
2067 llvm_unreachable("Unknown induction");
2068 case LoopVectorizationLegality::IK_IntInduction: {
2069 assert(P->getType() == II.StartValue->getType() && "Types must match");
2070 Type *PhiTy = P->getType();
2072 if (P == OldInduction) {
2073 // Handle the canonical induction variable. We might have had to
2075 Broadcasted = Builder.CreateTrunc(Induction, PhiTy);
2077 // Handle other induction variables that are now based on the
2079 Value *NormalizedIdx = Builder.CreateSub(Induction, ExtendedIdx,
2081 NormalizedIdx = Builder.CreateSExtOrTrunc(NormalizedIdx, PhiTy);
2082 Broadcasted = Builder.CreateAdd(II.StartValue, NormalizedIdx,
2085 Broadcasted = getBroadcastInstrs(Broadcasted);
2086 // After broadcasting the induction variable we need to make the vector
2087 // consecutive by adding 0, 1, 2, etc.
2088 for (unsigned part = 0; part < UF; ++part)
2089 Entry[part] = getConsecutiveVector(Broadcasted, VF * part, false);
2092 case LoopVectorizationLegality::IK_ReverseIntInduction:
2093 case LoopVectorizationLegality::IK_PtrInduction:
2094 case LoopVectorizationLegality::IK_ReversePtrInduction:
2095 // Handle reverse integer and pointer inductions.
2096 Value *StartIdx = ExtendedIdx;
2097 // This is the normalized GEP that starts counting at zero.
2098 Value *NormalizedIdx = Builder.CreateSub(Induction, StartIdx,
2101 // Handle the reverse integer induction variable case.
2102 if (LoopVectorizationLegality::IK_ReverseIntInduction == II.IK) {
2103 IntegerType *DstTy = cast<IntegerType>(II.StartValue->getType());
2104 Value *CNI = Builder.CreateSExtOrTrunc(NormalizedIdx, DstTy,
2106 Value *ReverseInd = Builder.CreateSub(II.StartValue, CNI,
2109 // This is a new value so do not hoist it out.
2110 Value *Broadcasted = getBroadcastInstrs(ReverseInd);
2111 // After broadcasting the induction variable we need to make the
2112 // vector consecutive by adding ... -3, -2, -1, 0.
2113 for (unsigned part = 0; part < UF; ++part)
2114 Entry[part] = getConsecutiveVector(Broadcasted, -(int)VF * part,
2119 // Handle the pointer induction variable case.
2120 assert(P->getType()->isPointerTy() && "Unexpected type.");
2122 // Is this a reverse induction ptr or a consecutive induction ptr.
2123 bool Reverse = (LoopVectorizationLegality::IK_ReversePtrInduction ==
2126 // This is the vector of results. Notice that we don't generate
2127 // vector geps because scalar geps result in better code.
2128 for (unsigned part = 0; part < UF; ++part) {
2129 Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
2130 for (unsigned int i = 0; i < VF; ++i) {
2131 int EltIndex = (i + part * VF) * (Reverse ? -1 : 1);
2132 Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex);
2135 GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx, "gep.idx");
2137 GlobalIdx = Builder.CreateSub(Idx, NormalizedIdx, "gep.ridx");
2139 Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
2141 VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
2142 Builder.getInt32(i),
2145 Entry[part] = VecVal;
2152 case Instruction::Add:
2153 case Instruction::FAdd:
2154 case Instruction::Sub:
2155 case Instruction::FSub:
2156 case Instruction::Mul:
2157 case Instruction::FMul:
2158 case Instruction::UDiv:
2159 case Instruction::SDiv:
2160 case Instruction::FDiv:
2161 case Instruction::URem:
2162 case Instruction::SRem:
2163 case Instruction::FRem:
2164 case Instruction::Shl:
2165 case Instruction::LShr:
2166 case Instruction::AShr:
2167 case Instruction::And:
2168 case Instruction::Or:
2169 case Instruction::Xor: {
2170 // Just widen binops.
2171 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
2172 VectorParts &A = getVectorValue(it->getOperand(0));
2173 VectorParts &B = getVectorValue(it->getOperand(1));
2175 // Use this vector value for all users of the original instruction.
2176 for (unsigned Part = 0; Part < UF; ++Part) {
2177 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
2179 // Update the NSW, NUW and Exact flags. Notice: V can be an Undef.
2180 BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V);
2181 if (VecOp && isa<OverflowingBinaryOperator>(BinOp)) {
2182 VecOp->setHasNoSignedWrap(BinOp->hasNoSignedWrap());
2183 VecOp->setHasNoUnsignedWrap(BinOp->hasNoUnsignedWrap());
2185 if (VecOp && isa<PossiblyExactOperator>(VecOp))
2186 VecOp->setIsExact(BinOp->isExact());
2192 case Instruction::Select: {
2194 // If the selector is loop invariant we can create a select
2195 // instruction with a scalar condition. Otherwise, use vector-select.
2196 bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)),
2199 // The condition can be loop invariant but still defined inside the
2200 // loop. This means that we can't just use the original 'cond' value.
2201 // We have to take the 'vectorized' value and pick the first lane.
2202 // Instcombine will make this a no-op.
2203 VectorParts &Cond = getVectorValue(it->getOperand(0));
2204 VectorParts &Op0 = getVectorValue(it->getOperand(1));
2205 VectorParts &Op1 = getVectorValue(it->getOperand(2));
2206 Value *ScalarCond = Builder.CreateExtractElement(Cond[0],
2207 Builder.getInt32(0));
2208 for (unsigned Part = 0; Part < UF; ++Part) {
2209 Entry[Part] = Builder.CreateSelect(
2210 InvariantCond ? ScalarCond : Cond[Part],
2217 case Instruction::ICmp:
2218 case Instruction::FCmp: {
2219 // Widen compares. Generate vector compares.
2220 bool FCmp = (it->getOpcode() == Instruction::FCmp);
2221 CmpInst *Cmp = dyn_cast<CmpInst>(it);
2222 VectorParts &A = getVectorValue(it->getOperand(0));
2223 VectorParts &B = getVectorValue(it->getOperand(1));
2224 for (unsigned Part = 0; Part < UF; ++Part) {
2227 C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
2229 C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
2235 case Instruction::Store:
2236 case Instruction::Load:
2237 vectorizeMemoryInstruction(it, Legal);
2239 case Instruction::ZExt:
2240 case Instruction::SExt:
2241 case Instruction::FPToUI:
2242 case Instruction::FPToSI:
2243 case Instruction::FPExt:
2244 case Instruction::PtrToInt:
2245 case Instruction::IntToPtr:
2246 case Instruction::SIToFP:
2247 case Instruction::UIToFP:
2248 case Instruction::Trunc:
2249 case Instruction::FPTrunc:
2250 case Instruction::BitCast: {
2251 CastInst *CI = dyn_cast<CastInst>(it);
2252 /// Optimize the special case where the source is the induction
2253 /// variable. Notice that we can only optimize the 'trunc' case
2254 /// because: a. FP conversions lose precision, b. sext/zext may wrap,
2255 /// c. other casts depend on pointer size.
2256 if (CI->getOperand(0) == OldInduction &&
2257 it->getOpcode() == Instruction::Trunc) {
2258 Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
2260 Value *Broadcasted = getBroadcastInstrs(ScalarCast);
2261 for (unsigned Part = 0; Part < UF; ++Part)
2262 Entry[Part] = getConsecutiveVector(Broadcasted, VF * Part, false);
2265 /// Vectorize casts.
2266 Type *DestTy = VectorType::get(CI->getType()->getScalarType(), VF);
2268 VectorParts &A = getVectorValue(it->getOperand(0));
2269 for (unsigned Part = 0; Part < UF; ++Part)
2270 Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
2274 case Instruction::Call: {
2275 // Ignore dbg intrinsics.
2276 if (isa<DbgInfoIntrinsic>(it))
2279 Module *M = BB->getParent()->getParent();
2280 CallInst *CI = cast<CallInst>(it);
2281 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
2282 assert(ID && "Not an intrinsic call!");
2283 for (unsigned Part = 0; Part < UF; ++Part) {
2284 SmallVector<Value*, 4> Args;
2285 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
2286 VectorParts &Arg = getVectorValue(CI->getArgOperand(i));
2287 Args.push_back(Arg[Part]);
2289 Type *Tys[] = { VectorType::get(CI->getType()->getScalarType(), VF) };
2290 Function *F = Intrinsic::getDeclaration(M, ID, Tys);
2291 Entry[Part] = Builder.CreateCall(F, Args);
2297 // All other instructions are unsupported. Scalarize them.
2298 scalarizeInstruction(it);
2301 }// end of for_each instr.
2304 void InnerLoopVectorizer::updateAnalysis() {
2305 // Forget the original basic block.
2306 SE->forgetLoop(OrigLoop);
2308 // Update the dominator tree information.
2309 assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&
2310 "Entry does not dominate exit.");
2312 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
2313 DT->addNewBlock(LoopBypassBlocks[I], LoopBypassBlocks[I-1]);
2314 DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlocks.back());
2315 DT->addNewBlock(LoopVectorBody, LoopVectorPreHeader);
2316 DT->addNewBlock(LoopMiddleBlock, LoopBypassBlocks.front());
2317 DT->addNewBlock(LoopScalarPreHeader, LoopMiddleBlock);
2318 DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
2319 DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
2321 DEBUG(DT->verifyAnalysis());
2324 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
2325 if (!EnableIfConversion)
2328 assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
2329 std::vector<BasicBlock*> &LoopBlocks = TheLoop->getBlocksVector();
2331 // Collect the blocks that need predication.
2332 for (unsigned i = 0, e = LoopBlocks.size(); i < e; ++i) {
2333 BasicBlock *BB = LoopBlocks[i];
2335 // We don't support switch statements inside loops.
2336 if (!isa<BranchInst>(BB->getTerminator()))
2339 // We must be able to predicate all blocks that need to be predicated.
2340 if (blockNeedsPredication(BB) && !blockCanBePredicated(BB))
2344 // We can if-convert this loop.
2348 bool LoopVectorizationLegality::canVectorize() {
2349 assert(TheLoop->getLoopPreheader() && "No preheader!!");
2351 // We can only vectorize innermost loops.
2352 if (TheLoop->getSubLoopsVector().size())
2355 // We must have a single backedge.
2356 if (TheLoop->getNumBackEdges() != 1)
2359 // We must have a single exiting block.
2360 if (!TheLoop->getExitingBlock())
2363 unsigned NumBlocks = TheLoop->getNumBlocks();
2365 // Check if we can if-convert non single-bb loops.
2366 if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
2367 DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
2371 // We need to have a loop header.
2372 BasicBlock *Latch = TheLoop->getLoopLatch();
2373 DEBUG(dbgs() << "LV: Found a loop: " <<
2374 TheLoop->getHeader()->getName() << "\n");
2376 // ScalarEvolution needs to be able to find the exit count.
2377 const SCEV *ExitCount = SE->getExitCount(TheLoop, Latch);
2378 if (ExitCount == SE->getCouldNotCompute()) {
2379 DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
2383 // Do not loop-vectorize loops with a tiny trip count.
2384 unsigned TC = SE->getSmallConstantTripCount(TheLoop, Latch);
2385 if (TC > 0u && TC < TinyTripCountVectorThreshold) {
2386 DEBUG(dbgs() << "LV: Found a loop with a very small trip count. " <<
2387 "This loop is not worth vectorizing.\n");
2391 // Check if we can vectorize the instructions and CFG in this loop.
2392 if (!canVectorizeInstrs()) {
2393 DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
2397 // Go over each instruction and look at memory deps.
2398 if (!canVectorizeMemory()) {
2399 DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
2403 // Collect all of the variables that remain uniform after vectorization.
2404 collectLoopUniforms();
2406 DEBUG(dbgs() << "LV: We can vectorize this loop" <<
2407 (PtrRtCheck.Need ? " (with a runtime bound check)" : "")
2410 // Okay! We can vectorize. At this point we don't have any other mem analysis
2411 // which may limit our maximum vectorization factor, so just return true with
2416 static Type *convertPointerToIntegerType(DataLayout &DL, Type *Ty) {
2417 if (Ty->isPointerTy())
2418 return DL.getIntPtrType(Ty->getContext());
2422 static Type* getWiderType(DataLayout &DL, Type *Ty0, Type *Ty1) {
2423 Ty0 = convertPointerToIntegerType(DL, Ty0);
2424 Ty1 = convertPointerToIntegerType(DL, Ty1);
2425 if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits())
2430 bool LoopVectorizationLegality::canVectorizeInstrs() {
2431 BasicBlock *PreHeader = TheLoop->getLoopPreheader();
2432 BasicBlock *Header = TheLoop->getHeader();
2434 // If we marked the scalar loop as "already vectorized" then no need
2435 // to vectorize it again.
2436 if (Header->getTerminator()->getMetadata(AlreadyVectorizedMDName)) {
2437 DEBUG(dbgs() << "LV: This loop was vectorized before\n");
2441 // Look for the attribute signaling the absence of NaNs.
2442 Function &F = *Header->getParent();
2443 if (F.hasFnAttribute("no-nans-fp-math"))
2444 HasFunNoNaNAttr = F.getAttributes().getAttribute(
2445 AttributeSet::FunctionIndex,
2446 "no-nans-fp-math").getValueAsString() == "true";
2448 // For each block in the loop.
2449 for (Loop::block_iterator bb = TheLoop->block_begin(),
2450 be = TheLoop->block_end(); bb != be; ++bb) {
2452 // Scan the instructions in the block and look for hazards.
2453 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
2456 if (PHINode *Phi = dyn_cast<PHINode>(it)) {
2457 Type *PhiTy = Phi->getType();
2458 // Check that this PHI type is allowed.
2459 if (!PhiTy->isIntegerTy() &&
2460 !PhiTy->isFloatingPointTy() &&
2461 !PhiTy->isPointerTy()) {
2462 DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
2466 // If this PHINode is not in the header block, then we know that we
2467 // can convert it to select during if-conversion. No need to check if
2468 // the PHIs in this block are induction or reduction variables.
2472 // We only allow if-converted PHIs with more than two incoming values.
2473 if (Phi->getNumIncomingValues() != 2) {
2474 DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
2478 // This is the value coming from the preheader.
2479 Value *StartValue = Phi->getIncomingValueForBlock(PreHeader);
2480 // Check if this is an induction variable.
2481 InductionKind IK = isInductionVariable(Phi);
2483 if (IK_NoInduction != IK) {
2484 // Get the widest type.
2486 WidestIndTy = convertPointerToIntegerType(*DL, PhiTy);
2488 WidestIndTy = getWiderType(*DL, PhiTy, WidestIndTy);
2490 // Int inductions are special because we only allow one IV.
2491 if (IK == IK_IntInduction) {
2492 // Use the phi node with the widest type as induction. Use the last
2493 // one if there are multiple (no good reason for doing this other
2494 // than it is expedient).
2495 if (!Induction || PhiTy == WidestIndTy)
2499 DEBUG(dbgs() << "LV: Found an induction variable.\n");
2500 Inductions[Phi] = InductionInfo(StartValue, IK);
2504 if (AddReductionVar(Phi, RK_IntegerAdd)) {
2505 DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
2508 if (AddReductionVar(Phi, RK_IntegerMult)) {
2509 DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n");
2512 if (AddReductionVar(Phi, RK_IntegerOr)) {
2513 DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n");
2516 if (AddReductionVar(Phi, RK_IntegerAnd)) {
2517 DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n");
2520 if (AddReductionVar(Phi, RK_IntegerXor)) {
2521 DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n");
2524 if (AddReductionVar(Phi, RK_IntegerMinMax)) {
2525 DEBUG(dbgs() << "LV: Found a MINMAX reduction PHI."<< *Phi <<"\n");
2528 if (AddReductionVar(Phi, RK_FloatMult)) {
2529 DEBUG(dbgs() << "LV: Found an FMult reduction PHI."<< *Phi <<"\n");
2532 if (AddReductionVar(Phi, RK_FloatAdd)) {
2533 DEBUG(dbgs() << "LV: Found an FAdd reduction PHI."<< *Phi <<"\n");
2536 if (AddReductionVar(Phi, RK_FloatMinMax)) {
2537 DEBUG(dbgs() << "LV: Found an float MINMAX reduction PHI."<< *Phi <<"\n");
2541 DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
2543 }// end of PHI handling
2545 // We still don't handle functions. However, we can ignore dbg intrinsic
2546 // calls and we do handle certain intrinsic and libm functions.
2547 CallInst *CI = dyn_cast<CallInst>(it);
2548 if (CI && !getIntrinsicIDForCall(CI, TLI) && !isa<DbgInfoIntrinsic>(CI)) {
2549 DEBUG(dbgs() << "LV: Found a call site.\n");
2553 // Check that the instruction return type is vectorizable.
2554 if (!VectorType::isValidElementType(it->getType()) &&
2555 !it->getType()->isVoidTy()) {
2556 DEBUG(dbgs() << "LV: Found unvectorizable type." << "\n");
2560 // Check that the stored type is vectorizable.
2561 if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
2562 Type *T = ST->getValueOperand()->getType();
2563 if (!VectorType::isValidElementType(T))
2567 // Reduction instructions are allowed to have exit users.
2568 // All other instructions must not have external users.
2569 if (!AllowedExit.count(it))
2570 //Check that all of the users of the loop are inside the BB.
2571 for (Value::use_iterator I = it->use_begin(), E = it->use_end();
2573 Instruction *U = cast<Instruction>(*I);
2574 // This user may be a reduction exit value.
2575 if (!TheLoop->contains(U)) {
2576 DEBUG(dbgs() << "LV: Found an outside user for : "<< *U << "\n");
2585 DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
2586 if (Inductions.empty())
2593 void LoopVectorizationLegality::collectLoopUniforms() {
2594 // We now know that the loop is vectorizable!
2595 // Collect variables that will remain uniform after vectorization.
2596 std::vector<Value*> Worklist;
2597 BasicBlock *Latch = TheLoop->getLoopLatch();
2599 // Start with the conditional branch and walk up the block.
2600 Worklist.push_back(Latch->getTerminator()->getOperand(0));
2602 while (Worklist.size()) {
2603 Instruction *I = dyn_cast<Instruction>(Worklist.back());
2604 Worklist.pop_back();
2606 // Look at instructions inside this loop.
2607 // Stop when reaching PHI nodes.
2608 // TODO: we need to follow values all over the loop, not only in this block.
2609 if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
2612 // This is a known uniform.
2615 // Insert all operands.
2616 for (int i = 0, Op = I->getNumOperands(); i < Op; ++i) {
2617 Worklist.push_back(I->getOperand(i));
2622 AliasAnalysis::Location
2623 LoopVectorizationLegality::getLoadStoreLocation(Instruction *Inst) {
2624 if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
2625 return AA->getLocation(Store);
2626 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
2627 return AA->getLocation(Load);
2629 llvm_unreachable("Should be either load or store instruction");
2633 LoopVectorizationLegality::hasPossibleGlobalWriteReorder(
2636 AliasMultiMap& WriteObjects,
2637 unsigned MaxByteWidth) {
2639 AliasAnalysis::Location ThisLoc = getLoadStoreLocation(Inst);
2641 std::vector<Instruction*>::iterator
2642 it = WriteObjects[Object].begin(),
2643 end = WriteObjects[Object].end();
2645 for (; it != end; ++it) {
2646 Instruction* I = *it;
2650 AliasAnalysis::Location ThatLoc = getLoadStoreLocation(I);
2651 if (AA->alias(ThisLoc.getWithNewSize(MaxByteWidth),
2652 ThatLoc.getWithNewSize(MaxByteWidth)))
2658 bool LoopVectorizationLegality::canVectorizeMemory() {
2660 typedef SmallVector<Value*, 16> ValueVector;
2661 typedef SmallPtrSet<Value*, 16> ValueSet;
2662 // Holds the Load and Store *instructions*.
2665 PtrRtCheck.Pointers.clear();
2666 PtrRtCheck.Need = false;
2668 const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
2671 for (Loop::block_iterator bb = TheLoop->block_begin(),
2672 be = TheLoop->block_end(); bb != be; ++bb) {
2674 // Scan the BB and collect legal loads and stores.
2675 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
2678 // If this is a load, save it. If this instruction can read from memory
2679 // but is not a load, then we quit. Notice that we don't handle function
2680 // calls that read or write.
2681 if (it->mayReadFromMemory()) {
2682 LoadInst *Ld = dyn_cast<LoadInst>(it);
2683 if (!Ld) return false;
2684 if (!Ld->isSimple() && !IsAnnotatedParallel) {
2685 DEBUG(dbgs() << "LV: Found a non-simple load.\n");
2688 Loads.push_back(Ld);
2692 // Save 'store' instructions. Abort if other instructions write to memory.
2693 if (it->mayWriteToMemory()) {
2694 StoreInst *St = dyn_cast<StoreInst>(it);
2695 if (!St) return false;
2696 if (!St->isSimple() && !IsAnnotatedParallel) {
2697 DEBUG(dbgs() << "LV: Found a non-simple store.\n");
2700 Stores.push_back(St);
2705 // Now we have two lists that hold the loads and the stores.
2706 // Next, we find the pointers that they use.
2708 // Check if we see any stores. If there are no stores, then we don't
2709 // care if the pointers are *restrict*.
2710 if (!Stores.size()) {
2711 DEBUG(dbgs() << "LV: Found a read-only loop!\n");
2715 // Holds the read and read-write *pointers* that we find. These maps hold
2716 // unique values for pointers (so no need for multi-map).
2718 AliasMap ReadWrites;
2720 // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
2721 // multiple times on the same object. If the ptr is accessed twice, once
2722 // for read and once for write, it will only appear once (on the write
2723 // list). This is okay, since we are going to check for conflicts between
2724 // writes and between reads and writes, but not between reads and reads.
2727 ValueVector::iterator I, IE;
2728 for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
2729 StoreInst *ST = cast<StoreInst>(*I);
2730 Value* Ptr = ST->getPointerOperand();
2732 if (isUniform(Ptr)) {
2733 DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
2737 // If we did *not* see this pointer before, insert it to
2738 // the read-write list. At this phase it is only a 'write' list.
2739 if (Seen.insert(Ptr))
2740 ReadWrites.insert(std::make_pair(Ptr, ST));
2743 if (IsAnnotatedParallel) {
2745 << "LV: A loop annotated parallel, ignore memory dependency "
2750 for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
2751 LoadInst *LD = cast<LoadInst>(*I);
2752 Value* Ptr = LD->getPointerOperand();
2753 // If we did *not* see this pointer before, insert it to the
2754 // read list. If we *did* see it before, then it is already in
2755 // the read-write list. This allows us to vectorize expressions
2756 // such as A[i] += x; Because the address of A[i] is a read-write
2757 // pointer. This only works if the index of A[i] is consecutive.
2758 // If the address of i is unknown (for example A[B[i]]) then we may
2759 // read a few words, modify, and write a few words, and some of the
2760 // words may be written to the same address.
2761 if (Seen.insert(Ptr) || 0 == isConsecutivePtr(Ptr))
2762 Reads.insert(std::make_pair(Ptr, LD));
2765 // If we write (or read-write) to a single destination and there are no
2766 // other reads in this loop then is it safe to vectorize.
2767 if (ReadWrites.size() == 1 && Reads.size() == 0) {
2768 DEBUG(dbgs() << "LV: Found a write-only loop!\n");
2772 unsigned NumReadPtrs = 0;
2773 unsigned NumWritePtrs = 0;
2775 // Find pointers with computable bounds. We are going to use this information
2776 // to place a runtime bound check.
2777 bool CanDoRT = true;
2778 AliasMap::iterator MI, ME;
2779 for (MI = ReadWrites.begin(), ME = ReadWrites.end(); MI != ME; ++MI) {
2780 Value *V = (*MI).first;
2781 if (hasComputableBounds(V)) {
2782 PtrRtCheck.insert(SE, TheLoop, V, true);
2784 DEBUG(dbgs() << "LV: Found a runtime check ptr:" << *V <<"\n");
2790 for (MI = Reads.begin(), ME = Reads.end(); MI != ME; ++MI) {
2791 Value *V = (*MI).first;
2792 if (hasComputableBounds(V)) {
2793 PtrRtCheck.insert(SE, TheLoop, V, false);
2795 DEBUG(dbgs() << "LV: Found a runtime check ptr:" << *V <<"\n");
2802 // Check that we did not collect too many pointers or found a
2803 // unsizeable pointer.
2804 unsigned NumComparisons = (NumWritePtrs * (NumReadPtrs + NumWritePtrs - 1));
2805 DEBUG(dbgs() << "LV: We need to compare " << NumComparisons << " ptrs.\n");
2806 if (!CanDoRT || NumComparisons > RuntimeMemoryCheckThreshold) {
2812 DEBUG(dbgs() << "LV: We can perform a memory runtime check if needed.\n");
2815 bool NeedRTCheck = false;
2817 // Biggest vectorized access possible, vector width * unroll factor.
2818 // TODO: We're being very pessimistic here, find a way to know the
2819 // real access width before getting here.
2820 unsigned MaxByteWidth = (TTI->getRegisterBitWidth(true) / 8) *
2821 TTI->getMaximumUnrollFactor();
2822 // Now that the pointers are in two lists (Reads and ReadWrites), we
2823 // can check that there are no conflicts between each of the writes and
2824 // between the writes to the reads.
2825 // Note that WriteObjects duplicates the stores (indexed now by underlying
2826 // objects) to avoid pointing to elements inside ReadWrites.
2827 // TODO: Maybe create a new type where they can interact without duplication.
2828 AliasMultiMap WriteObjects;
2829 ValueVector TempObjects;
2831 // Check that the read-writes do not conflict with other read-write
2833 bool AllWritesIdentified = true;
2834 for (MI = ReadWrites.begin(), ME = ReadWrites.end(); MI != ME; ++MI) {
2835 Value *Val = (*MI).first;
2836 Instruction *Inst = (*MI).second;
2838 GetUnderlyingObjects(Val, TempObjects, DL);
2839 for (ValueVector::iterator UI=TempObjects.begin(), UE=TempObjects.end();
2841 if (!isIdentifiedObject(*UI)) {
2842 DEBUG(dbgs() << "LV: Found an unidentified write ptr:"<< **UI <<"\n");
2844 AllWritesIdentified = false;
2847 // Never seen it before, can't alias.
2848 if (WriteObjects[*UI].empty()) {
2849 DEBUG(dbgs() << "LV: Adding Underlying value:" << **UI <<"\n");
2850 WriteObjects[*UI].push_back(Inst);
2853 // Direct alias found.
2854 if (!AA || dyn_cast<GlobalValue>(*UI) == NULL) {
2855 DEBUG(dbgs() << "LV: Found a possible write-write reorder:"
2859 DEBUG(dbgs() << "LV: Found a conflicting global value:"
2861 DEBUG(dbgs() << "LV: While examining store:" << *Inst <<"\n");
2862 DEBUG(dbgs() << "LV: On value:" << *Val <<"\n");
2864 // If global alias, make sure they do alias.
2865 if (hasPossibleGlobalWriteReorder(*UI,
2869 DEBUG(dbgs() << "LV: Found a possible write-write reorder:" << **UI
2874 // Didn't alias, insert into map for further reference.
2875 WriteObjects[*UI].push_back(Inst);
2877 TempObjects.clear();
2880 /// Check that the reads don't conflict with the read-writes.
2881 for (MI = Reads.begin(), ME = Reads.end(); MI != ME; ++MI) {
2882 Value *Val = (*MI).first;
2883 GetUnderlyingObjects(Val, TempObjects, DL);
2884 for (ValueVector::iterator UI=TempObjects.begin(), UE=TempObjects.end();
2886 // If all of the writes are identified then we don't care if the read
2887 // pointer is identified or not.
2888 if (!AllWritesIdentified && !isIdentifiedObject(*UI)) {
2889 DEBUG(dbgs() << "LV: Found an unidentified read ptr:"<< **UI <<"\n");
2893 // Never seen it before, can't alias.
2894 if (WriteObjects[*UI].empty())
2896 // Direct alias found.
2897 if (!AA || dyn_cast<GlobalValue>(*UI) == NULL) {
2898 DEBUG(dbgs() << "LV: Found a possible write-write reorder:"
2902 DEBUG(dbgs() << "LV: Found a global value: "
2904 Instruction *Inst = (*MI).second;
2905 DEBUG(dbgs() << "LV: While examining load:" << *Inst <<"\n");
2906 DEBUG(dbgs() << "LV: On value:" << *Val <<"\n");
2908 // If global alias, make sure they do alias.
2909 if (hasPossibleGlobalWriteReorder(*UI,
2913 DEBUG(dbgs() << "LV: Found a possible read-write reorder:" << **UI
2918 TempObjects.clear();
2921 PtrRtCheck.Need = NeedRTCheck;
2922 if (NeedRTCheck && !CanDoRT) {
2923 DEBUG(dbgs() << "LV: We can't vectorize because we can't find " <<
2924 "the array bounds.\n");
2929 DEBUG(dbgs() << "LV: We "<< (NeedRTCheck ? "" : "don't") <<
2930 " need a runtime memory check.\n");
2934 static bool hasMultipleUsesOf(Instruction *I,
2935 SmallPtrSet<Instruction *, 8> &Insts) {
2936 unsigned NumUses = 0;
2937 for(User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use) {
2938 if (Insts.count(dyn_cast<Instruction>(*Use)))
2947 static bool areAllUsesIn(Instruction *I, SmallPtrSet<Instruction *, 8> &Set) {
2948 for(User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use)
2949 if (!Set.count(dyn_cast<Instruction>(*Use)))
2954 bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi,
2955 ReductionKind Kind) {
2956 if (Phi->getNumIncomingValues() != 2)
2959 // Reduction variables are only found in the loop header block.
2960 if (Phi->getParent() != TheLoop->getHeader())
2963 // Obtain the reduction start value from the value that comes from the loop
2965 Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
2967 // ExitInstruction is the single value which is used outside the loop.
2968 // We only allow for a single reduction value to be used outside the loop.
2969 // This includes users of the reduction, variables (which form a cycle
2970 // which ends in the phi node).
2971 Instruction *ExitInstruction = 0;
2972 // Indicates that we found a reduction operation in our scan.
2973 bool FoundReduxOp = false;
2975 // We start with the PHI node and scan for all of the users of this
2976 // instruction. All users must be instructions that can be used as reduction
2977 // variables (such as ADD). We must have a single out-of-block user. The cycle
2978 // must include the original PHI.
2979 bool FoundStartPHI = false;
2981 // To recognize min/max patterns formed by a icmp select sequence, we store
2982 // the number of instruction we saw from the recognized min/max pattern,
2983 // to make sure we only see exactly the two instructions.
2984 unsigned NumCmpSelectPatternInst = 0;
2985 ReductionInstDesc ReduxDesc(false, 0);
2987 SmallPtrSet<Instruction *, 8> VisitedInsts;
2988 SmallVector<Instruction *, 8> Worklist;
2989 Worklist.push_back(Phi);
2990 VisitedInsts.insert(Phi);
2992 // A value in the reduction can be used:
2993 // - By the reduction:
2994 // - Reduction operation:
2995 // - One use of reduction value (safe).
2996 // - Multiple use of reduction value (not safe).
2998 // - All uses of the PHI must be the reduction (safe).
2999 // - Otherwise, not safe.
3000 // - By one instruction outside of the loop (safe).
3001 // - By further instructions outside of the loop (not safe).
3002 // - By an instruction that is not part of the reduction (not safe).
3004 // * An instruction type other than PHI or the reduction operation.
3005 // * A PHI in the header other than the initial PHI.
3006 while (!Worklist.empty()) {
3007 Instruction *Cur = Worklist.back();
3008 Worklist.pop_back();
3011 // If the instruction has no users then this is a broken chain and can't be
3012 // a reduction variable.
3013 if (Cur->use_empty())
3016 bool IsAPhi = isa<PHINode>(Cur);
3018 // A header PHI use other than the original PHI.
3019 if (Cur != Phi && IsAPhi && Cur->getParent() == Phi->getParent())
3022 // Reductions of instructions such as Div, and Sub is only possible if the
3023 // LHS is the reduction variable.
3024 if (!Cur->isCommutative() && !IsAPhi && !isa<SelectInst>(Cur) &&
3025 !isa<ICmpInst>(Cur) && !isa<FCmpInst>(Cur) &&
3026 !VisitedInsts.count(dyn_cast<Instruction>(Cur->getOperand(0))))
3029 // Any reduction instruction must be of one of the allowed kinds.
3030 ReduxDesc = isReductionInstr(Cur, Kind, ReduxDesc);
3031 if (!ReduxDesc.IsReduction)
3034 // A reduction operation must only have one use of the reduction value.
3035 if (!IsAPhi && Kind != RK_IntegerMinMax && Kind != RK_FloatMinMax &&
3036 hasMultipleUsesOf(Cur, VisitedInsts))
3039 // All inputs to a PHI node must be a reduction value.
3040 if(IsAPhi && Cur != Phi && !areAllUsesIn(Cur, VisitedInsts))
3043 if (Kind == RK_IntegerMinMax && (isa<ICmpInst>(Cur) ||
3044 isa<SelectInst>(Cur)))
3045 ++NumCmpSelectPatternInst;
3046 if (Kind == RK_FloatMinMax && (isa<FCmpInst>(Cur) ||
3047 isa<SelectInst>(Cur)))
3048 ++NumCmpSelectPatternInst;
3050 // Check whether we found a reduction operator.
3051 FoundReduxOp |= !IsAPhi;
3053 // Process users of current instruction. Push non PHI nodes after PHI nodes
3054 // onto the stack. This way we are going to have seen all inputs to PHI
3055 // nodes once we get to them.
3056 SmallVector<Instruction *, 8> NonPHIs;
3057 SmallVector<Instruction *, 8> PHIs;
3058 for (Value::use_iterator UI = Cur->use_begin(), E = Cur->use_end(); UI != E;
3060 Instruction *Usr = cast<Instruction>(*UI);
3062 // Check if we found the exit user.
3063 BasicBlock *Parent = Usr->getParent();
3064 if (!TheLoop->contains(Parent)) {
3065 // Exit if you find multiple outside users.
3066 if (ExitInstruction != 0)
3068 ExitInstruction = Cur;
3072 // Process instructions only once (termination).
3073 if (VisitedInsts.insert(Usr)) {
3074 if (isa<PHINode>(Usr))
3075 PHIs.push_back(Usr);
3077 NonPHIs.push_back(Usr);
3079 // Remember that we completed the cycle.
3081 FoundStartPHI = true;
3083 Worklist.append(PHIs.begin(), PHIs.end());
3084 Worklist.append(NonPHIs.begin(), NonPHIs.end());
3087 // This means we have seen one but not the other instruction of the
3088 // pattern or more than just a select and cmp.
3089 if ((Kind == RK_IntegerMinMax || Kind == RK_FloatMinMax) &&
3090 NumCmpSelectPatternInst != 2)
3093 if (!FoundStartPHI || !FoundReduxOp || !ExitInstruction)
3096 // We found a reduction var if we have reached the original phi node and we
3097 // only have a single instruction with out-of-loop users.
3099 // This instruction is allowed to have out-of-loop users.
3100 AllowedExit.insert(ExitInstruction);
3102 // Save the description of this reduction variable.
3103 ReductionDescriptor RD(RdxStart, ExitInstruction, Kind,
3104 ReduxDesc.MinMaxKind);
3105 Reductions[Phi] = RD;
3106 // We've ended the cycle. This is a reduction variable if we have an
3107 // outside user and it has a binary op.
3112 /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
3113 /// pattern corresponding to a min(X, Y) or max(X, Y).
3114 LoopVectorizationLegality::ReductionInstDesc
3115 LoopVectorizationLegality::isMinMaxSelectCmpPattern(Instruction *I,
3116 ReductionInstDesc &Prev) {
3118 assert((isa<ICmpInst>(I) || isa<FCmpInst>(I) || isa<SelectInst>(I)) &&
3119 "Expect a select instruction");
3120 Instruction *Cmp = 0;
3121 SelectInst *Select = 0;
3123 // We must handle the select(cmp()) as a single instruction. Advance to the
3125 if ((Cmp = dyn_cast<ICmpInst>(I)) || (Cmp = dyn_cast<FCmpInst>(I))) {
3126 if (!Cmp->hasOneUse() || !(Select = dyn_cast<SelectInst>(*I->use_begin())))
3127 return ReductionInstDesc(false, I);
3128 return ReductionInstDesc(Select, Prev.MinMaxKind);
3131 // Only handle single use cases for now.
3132 if (!(Select = dyn_cast<SelectInst>(I)))
3133 return ReductionInstDesc(false, I);
3134 if (!(Cmp = dyn_cast<ICmpInst>(I->getOperand(0))) &&
3135 !(Cmp = dyn_cast<FCmpInst>(I->getOperand(0))))
3136 return ReductionInstDesc(false, I);
3137 if (!Cmp->hasOneUse())
3138 return ReductionInstDesc(false, I);
3143 // Look for a min/max pattern.
3144 if (m_UMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
3145 return ReductionInstDesc(Select, MRK_UIntMin);
3146 else if (m_UMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
3147 return ReductionInstDesc(Select, MRK_UIntMax);
3148 else if (m_SMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
3149 return ReductionInstDesc(Select, MRK_SIntMax);
3150 else if (m_SMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
3151 return ReductionInstDesc(Select, MRK_SIntMin);
3152 else if (m_OrdFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
3153 return ReductionInstDesc(Select, MRK_FloatMin);
3154 else if (m_OrdFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
3155 return ReductionInstDesc(Select, MRK_FloatMax);
3156 else if (m_UnordFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
3157 return ReductionInstDesc(Select, MRK_FloatMin);
3158 else if (m_UnordFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
3159 return ReductionInstDesc(Select, MRK_FloatMax);
3161 return ReductionInstDesc(false, I);
3164 LoopVectorizationLegality::ReductionInstDesc
3165 LoopVectorizationLegality::isReductionInstr(Instruction *I,
3167 ReductionInstDesc &Prev) {
3168 bool FP = I->getType()->isFloatingPointTy();
3169 bool FastMath = (FP && I->isCommutative() && I->isAssociative());
3170 switch (I->getOpcode()) {
3172 return ReductionInstDesc(false, I);
3173 case Instruction::PHI:
3174 if (FP && (Kind != RK_FloatMult && Kind != RK_FloatAdd &&
3175 Kind != RK_FloatMinMax))
3176 return ReductionInstDesc(false, I);
3177 return ReductionInstDesc(I, Prev.MinMaxKind);
3178 case Instruction::Sub:
3179 case Instruction::Add:
3180 return ReductionInstDesc(Kind == RK_IntegerAdd, I);
3181 case Instruction::Mul:
3182 return ReductionInstDesc(Kind == RK_IntegerMult, I);
3183 case Instruction::And:
3184 return ReductionInstDesc(Kind == RK_IntegerAnd, I);
3185 case Instruction::Or:
3186 return ReductionInstDesc(Kind == RK_IntegerOr, I);
3187 case Instruction::Xor:
3188 return ReductionInstDesc(Kind == RK_IntegerXor, I);
3189 case Instruction::FMul:
3190 return ReductionInstDesc(Kind == RK_FloatMult && FastMath, I);
3191 case Instruction::FAdd:
3192 return ReductionInstDesc(Kind == RK_FloatAdd && FastMath, I);
3193 case Instruction::FCmp:
3194 case Instruction::ICmp:
3195 case Instruction::Select:
3196 if (Kind != RK_IntegerMinMax &&
3197 (!HasFunNoNaNAttr || Kind != RK_FloatMinMax))
3198 return ReductionInstDesc(false, I);
3199 return isMinMaxSelectCmpPattern(I, Prev);
3203 LoopVectorizationLegality::InductionKind
3204 LoopVectorizationLegality::isInductionVariable(PHINode *Phi) {
3205 Type *PhiTy = Phi->getType();
3206 // We only handle integer and pointer inductions variables.
3207 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
3208 return IK_NoInduction;
3210 // Check that the PHI is consecutive.
3211 const SCEV *PhiScev = SE->getSCEV(Phi);
3212 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
3214 DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
3215 return IK_NoInduction;
3217 const SCEV *Step = AR->getStepRecurrence(*SE);
3219 // Integer inductions need to have a stride of one.
3220 if (PhiTy->isIntegerTy()) {
3222 return IK_IntInduction;
3223 if (Step->isAllOnesValue())
3224 return IK_ReverseIntInduction;
3225 return IK_NoInduction;
3228 // Calculate the pointer stride and check if it is consecutive.
3229 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
3231 return IK_NoInduction;
3233 assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
3234 uint64_t Size = DL->getTypeAllocSize(PhiTy->getPointerElementType());
3235 if (C->getValue()->equalsInt(Size))
3236 return IK_PtrInduction;
3237 else if (C->getValue()->equalsInt(0 - Size))
3238 return IK_ReversePtrInduction;
3240 return IK_NoInduction;
3243 bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
3244 Value *In0 = const_cast<Value*>(V);
3245 PHINode *PN = dyn_cast_or_null<PHINode>(In0);
3249 return Inductions.count(PN);
3252 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) {
3253 assert(TheLoop->contains(BB) && "Unknown block used");
3255 // Blocks that do not dominate the latch need predication.
3256 BasicBlock* Latch = TheLoop->getLoopLatch();
3257 return !DT->dominates(BB, Latch);
3260 bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB) {
3261 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
3262 // We don't predicate loads/stores at the moment.
3263 if (it->mayReadFromMemory() || it->mayWriteToMemory() || it->mayThrow())
3266 // The instructions below can trap.
3267 switch (it->getOpcode()) {
3269 case Instruction::UDiv:
3270 case Instruction::SDiv:
3271 case Instruction::URem:
3272 case Instruction::SRem:
3280 bool LoopVectorizationLegality::hasComputableBounds(Value *Ptr) {
3281 const SCEV *PhiScev = SE->getSCEV(Ptr);
3282 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
3286 return AR->isAffine();
3289 LoopVectorizationCostModel::VectorizationFactor
3290 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize,
3292 // Width 1 means no vectorize
3293 VectorizationFactor Factor = { 1U, 0U };
3294 if (OptForSize && Legal->getRuntimePointerCheck()->Need) {
3295 DEBUG(dbgs() << "LV: Aborting. Runtime ptr check is required in Os.\n");
3299 // Find the trip count.
3300 unsigned TC = SE->getSmallConstantTripCount(TheLoop, TheLoop->getLoopLatch());
3301 DEBUG(dbgs() << "LV: Found trip count:"<<TC<<"\n");
3303 unsigned WidestType = getWidestType();
3304 unsigned WidestRegister = TTI.getRegisterBitWidth(true);
3305 unsigned MaxVectorSize = WidestRegister / WidestType;
3306 DEBUG(dbgs() << "LV: The Widest type: " << WidestType << " bits.\n");
3307 DEBUG(dbgs() << "LV: The Widest register is:" << WidestRegister << "bits.\n");
3309 if (MaxVectorSize == 0) {
3310 DEBUG(dbgs() << "LV: The target has no vector registers.\n");
3314 assert(MaxVectorSize <= 32 && "Did not expect to pack so many elements"
3315 " into one vector!");
3317 unsigned VF = MaxVectorSize;
3319 // If we optimize the program for size, avoid creating the tail loop.
3321 // If we are unable to calculate the trip count then don't try to vectorize.
3323 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
3327 // Find the maximum SIMD width that can fit within the trip count.
3328 VF = TC % MaxVectorSize;
3333 // If the trip count that we found modulo the vectorization factor is not
3334 // zero then we require a tail.
3336 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
3342 assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
3343 DEBUG(dbgs() << "LV: Using user VF "<<UserVF<<".\n");
3345 Factor.Width = UserVF;
3349 float Cost = expectedCost(1);
3351 DEBUG(dbgs() << "LV: Scalar loop costs: "<< (int)Cost << ".\n");
3352 for (unsigned i=2; i <= VF; i*=2) {
3353 // Notice that the vector loop needs to be executed less times, so
3354 // we need to divide the cost of the vector loops by the width of
3355 // the vector elements.
3356 float VectorCost = expectedCost(i) / (float)i;
3357 DEBUG(dbgs() << "LV: Vector loop of width "<< i << " costs: " <<
3358 (int)VectorCost << ".\n");
3359 if (VectorCost < Cost) {
3365 DEBUG(dbgs() << "LV: Selecting VF = : "<< Width << ".\n");
3366 Factor.Width = Width;
3367 Factor.Cost = Width * Cost;
3371 unsigned LoopVectorizationCostModel::getWidestType() {
3372 unsigned MaxWidth = 8;
3375 for (Loop::block_iterator bb = TheLoop->block_begin(),
3376 be = TheLoop->block_end(); bb != be; ++bb) {
3377 BasicBlock *BB = *bb;
3379 // For each instruction in the loop.
3380 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
3381 Type *T = it->getType();
3383 // Only examine Loads, Stores and PHINodes.
3384 if (!isa<LoadInst>(it) && !isa<StoreInst>(it) && !isa<PHINode>(it))
3387 // Examine PHI nodes that are reduction variables.
3388 if (PHINode *PN = dyn_cast<PHINode>(it))
3389 if (!Legal->getReductionVars()->count(PN))
3392 // Examine the stored values.
3393 if (StoreInst *ST = dyn_cast<StoreInst>(it))
3394 T = ST->getValueOperand()->getType();
3396 // Ignore loaded pointer types and stored pointer types that are not
3397 // consecutive. However, we do want to take consecutive stores/loads of
3398 // pointer vectors into account.
3399 if (T->isPointerTy() && !isConsecutiveLoadOrStore(it))
3402 MaxWidth = std::max(MaxWidth,
3403 (unsigned)DL->getTypeSizeInBits(T->getScalarType()));
3411 LoopVectorizationCostModel::selectUnrollFactor(bool OptForSize,
3414 unsigned LoopCost) {
3416 // -- The unroll heuristics --
3417 // We unroll the loop in order to expose ILP and reduce the loop overhead.
3418 // There are many micro-architectural considerations that we can't predict
3419 // at this level. For example frontend pressure (on decode or fetch) due to
3420 // code size, or the number and capabilities of the execution ports.
3422 // We use the following heuristics to select the unroll factor:
3423 // 1. If the code has reductions the we unroll in order to break the cross
3424 // iteration dependency.
3425 // 2. If the loop is really small then we unroll in order to reduce the loop
3427 // 3. We don't unroll if we think that we will spill registers to memory due
3428 // to the increased register pressure.
3430 // Use the user preference, unless 'auto' is selected.
3434 // When we optimize for size we don't unroll.
3438 // Do not unroll loops with a relatively small trip count.
3439 unsigned TC = SE->getSmallConstantTripCount(TheLoop,
3440 TheLoop->getLoopLatch());
3441 if (TC > 1 && TC < TinyTripCountUnrollThreshold)
3444 unsigned TargetVectorRegisters = TTI.getNumberOfRegisters(true);
3445 DEBUG(dbgs() << "LV: The target has " << TargetVectorRegisters <<
3446 " vector registers\n");
3448 LoopVectorizationCostModel::RegisterUsage R = calculateRegisterUsage();
3449 // We divide by these constants so assume that we have at least one
3450 // instruction that uses at least one register.
3451 R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
3452 R.NumInstructions = std::max(R.NumInstructions, 1U);
3454 // We calculate the unroll factor using the following formula.
3455 // Subtract the number of loop invariants from the number of available
3456 // registers. These registers are used by all of the unrolled instances.
3457 // Next, divide the remaining registers by the number of registers that is
3458 // required by the loop, in order to estimate how many parallel instances
3459 // fit without causing spills.
3460 unsigned UF = (TargetVectorRegisters - R.LoopInvariantRegs) / R.MaxLocalUsers;
3462 // Clamp the unroll factor ranges to reasonable factors.
3463 unsigned MaxUnrollSize = TTI.getMaximumUnrollFactor();
3465 // If we did not calculate the cost for VF (because the user selected the VF)
3466 // then we calculate the cost of VF here.
3468 LoopCost = expectedCost(VF);
3470 // Clamp the calculated UF to be between the 1 and the max unroll factor
3471 // that the target allows.
3472 if (UF > MaxUnrollSize)
3477 if (Legal->getReductionVars()->size()) {
3478 DEBUG(dbgs() << "LV: Unrolling because of reductions. \n");
3482 // We want to unroll tiny loops in order to reduce the loop overhead.
3483 // We assume that the cost overhead is 1 and we use the cost model
3484 // to estimate the cost of the loop and unroll until the cost of the
3485 // loop overhead is about 5% of the cost of the loop.
3486 DEBUG(dbgs() << "LV: Loop cost is "<< LoopCost <<" \n");
3487 if (LoopCost < 20) {
3488 DEBUG(dbgs() << "LV: Unrolling to reduce branch cost. \n");
3489 unsigned NewUF = 20/LoopCost + 1;
3490 return std::min(NewUF, UF);
3493 DEBUG(dbgs() << "LV: Not Unrolling. \n");
3497 LoopVectorizationCostModel::RegisterUsage
3498 LoopVectorizationCostModel::calculateRegisterUsage() {
3499 // This function calculates the register usage by measuring the highest number
3500 // of values that are alive at a single location. Obviously, this is a very
3501 // rough estimation. We scan the loop in a topological order in order and
3502 // assign a number to each instruction. We use RPO to ensure that defs are
3503 // met before their users. We assume that each instruction that has in-loop
3504 // users starts an interval. We record every time that an in-loop value is
3505 // used, so we have a list of the first and last occurrences of each
3506 // instruction. Next, we transpose this data structure into a multi map that
3507 // holds the list of intervals that *end* at a specific location. This multi
3508 // map allows us to perform a linear search. We scan the instructions linearly
3509 // and record each time that a new interval starts, by placing it in a set.
3510 // If we find this value in the multi-map then we remove it from the set.
3511 // The max register usage is the maximum size of the set.
3512 // We also search for instructions that are defined outside the loop, but are
3513 // used inside the loop. We need this number separately from the max-interval
3514 // usage number because when we unroll, loop-invariant values do not take
3516 LoopBlocksDFS DFS(TheLoop);
3520 R.NumInstructions = 0;
3522 // Each 'key' in the map opens a new interval. The values
3523 // of the map are the index of the 'last seen' usage of the
3524 // instruction that is the key.
3525 typedef DenseMap<Instruction*, unsigned> IntervalMap;
3526 // Maps instruction to its index.
3527 DenseMap<unsigned, Instruction*> IdxToInstr;
3528 // Marks the end of each interval.
3529 IntervalMap EndPoint;
3530 // Saves the list of instruction indices that are used in the loop.
3531 SmallSet<Instruction*, 8> Ends;
3532 // Saves the list of values that are used in the loop but are
3533 // defined outside the loop, such as arguments and constants.
3534 SmallPtrSet<Value*, 8> LoopInvariants;
3537 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
3538 be = DFS.endRPO(); bb != be; ++bb) {
3539 R.NumInstructions += (*bb)->size();
3540 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
3542 Instruction *I = it;
3543 IdxToInstr[Index++] = I;
3545 // Save the end location of each USE.
3546 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
3547 Value *U = I->getOperand(i);
3548 Instruction *Instr = dyn_cast<Instruction>(U);
3550 // Ignore non-instruction values such as arguments, constants, etc.
3551 if (!Instr) continue;
3553 // If this instruction is outside the loop then record it and continue.
3554 if (!TheLoop->contains(Instr)) {
3555 LoopInvariants.insert(Instr);
3559 // Overwrite previous end points.
3560 EndPoint[Instr] = Index;
3566 // Saves the list of intervals that end with the index in 'key'.
3567 typedef SmallVector<Instruction*, 2> InstrList;
3568 DenseMap<unsigned, InstrList> TransposeEnds;
3570 // Transpose the EndPoints to a list of values that end at each index.
3571 for (IntervalMap::iterator it = EndPoint.begin(), e = EndPoint.end();
3573 TransposeEnds[it->second].push_back(it->first);
3575 SmallSet<Instruction*, 8> OpenIntervals;
3576 unsigned MaxUsage = 0;
3579 DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
3580 for (unsigned int i = 0; i < Index; ++i) {
3581 Instruction *I = IdxToInstr[i];
3582 // Ignore instructions that are never used within the loop.
3583 if (!Ends.count(I)) continue;
3585 // Remove all of the instructions that end at this location.
3586 InstrList &List = TransposeEnds[i];
3587 for (unsigned int j=0, e = List.size(); j < e; ++j)
3588 OpenIntervals.erase(List[j]);
3590 // Count the number of live interals.
3591 MaxUsage = std::max(MaxUsage, OpenIntervals.size());
3593 DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # " <<
3594 OpenIntervals.size() <<"\n");
3596 // Add the current instruction to the list of open intervals.
3597 OpenIntervals.insert(I);
3600 unsigned Invariant = LoopInvariants.size();
3601 DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsage << " \n");
3602 DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << " \n");
3603 DEBUG(dbgs() << "LV(REG): LoopSize: " << R.NumInstructions << " \n");
3605 R.LoopInvariantRegs = Invariant;
3606 R.MaxLocalUsers = MaxUsage;
3610 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
3614 for (Loop::block_iterator bb = TheLoop->block_begin(),
3615 be = TheLoop->block_end(); bb != be; ++bb) {
3616 unsigned BlockCost = 0;
3617 BasicBlock *BB = *bb;
3619 // For each instruction in the old loop.
3620 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
3621 // Skip dbg intrinsics.
3622 if (isa<DbgInfoIntrinsic>(it))
3625 unsigned C = getInstructionCost(it, VF);
3627 DEBUG(dbgs() << "LV: Found an estimated cost of "<< C <<" for VF " <<
3628 VF << " For instruction: "<< *it << "\n");
3631 // We assume that if-converted blocks have a 50% chance of being executed.
3632 // When the code is scalar then some of the blocks are avoided due to CF.
3633 // When the code is vectorized we execute all code paths.
3634 if (Legal->blockNeedsPredication(*bb) && VF == 1)
3644 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
3645 // If we know that this instruction will remain uniform, check the cost of
3646 // the scalar version.
3647 if (Legal->isUniformAfterVectorization(I))
3650 Type *RetTy = I->getType();
3651 Type *VectorTy = ToVectorTy(RetTy, VF);
3653 // TODO: We need to estimate the cost of intrinsic calls.
3654 switch (I->getOpcode()) {
3655 case Instruction::GetElementPtr:
3656 // We mark this instruction as zero-cost because the cost of GEPs in
3657 // vectorized code depends on whether the corresponding memory instruction
3658 // is scalarized or not. Therefore, we handle GEPs with the memory
3659 // instruction cost.
3661 case Instruction::Br: {
3662 return TTI.getCFInstrCost(I->getOpcode());
3664 case Instruction::PHI:
3665 //TODO: IF-converted IFs become selects.
3667 case Instruction::Add:
3668 case Instruction::FAdd:
3669 case Instruction::Sub:
3670 case Instruction::FSub:
3671 case Instruction::Mul:
3672 case Instruction::FMul:
3673 case Instruction::UDiv:
3674 case Instruction::SDiv:
3675 case Instruction::FDiv:
3676 case Instruction::URem:
3677 case Instruction::SRem:
3678 case Instruction::FRem:
3679 case Instruction::Shl:
3680 case Instruction::LShr:
3681 case Instruction::AShr:
3682 case Instruction::And:
3683 case Instruction::Or:
3684 case Instruction::Xor: {
3685 // Certain instructions can be cheaper to vectorize if they have a constant
3686 // second vector operand. One example of this are shifts on x86.
3687 TargetTransformInfo::OperandValueKind Op1VK =
3688 TargetTransformInfo::OK_AnyValue;
3689 TargetTransformInfo::OperandValueKind Op2VK =
3690 TargetTransformInfo::OK_AnyValue;
3692 if (isa<ConstantInt>(I->getOperand(1)))
3693 Op2VK = TargetTransformInfo::OK_UniformConstantValue;
3695 return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy, Op1VK, Op2VK);
3697 case Instruction::Select: {
3698 SelectInst *SI = cast<SelectInst>(I);
3699 const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
3700 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
3701 Type *CondTy = SI->getCondition()->getType();
3703 CondTy = VectorType::get(CondTy, VF);
3705 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
3707 case Instruction::ICmp:
3708 case Instruction::FCmp: {
3709 Type *ValTy = I->getOperand(0)->getType();
3710 VectorTy = ToVectorTy(ValTy, VF);
3711 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy);
3713 case Instruction::Store:
3714 case Instruction::Load: {
3715 StoreInst *SI = dyn_cast<StoreInst>(I);
3716 LoadInst *LI = dyn_cast<LoadInst>(I);
3717 Type *ValTy = (SI ? SI->getValueOperand()->getType() :
3719 VectorTy = ToVectorTy(ValTy, VF);
3721 unsigned Alignment = SI ? SI->getAlignment() : LI->getAlignment();
3722 unsigned AS = SI ? SI->getPointerAddressSpace() :
3723 LI->getPointerAddressSpace();
3724 Value *Ptr = SI ? SI->getPointerOperand() : LI->getPointerOperand();
3725 // We add the cost of address computation here instead of with the gep
3726 // instruction because only here we know whether the operation is
3729 return TTI.getAddressComputationCost(VectorTy) +
3730 TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
3732 // Scalarized loads/stores.
3733 int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
3734 bool Reverse = ConsecutiveStride < 0;
3735 unsigned ScalarAllocatedSize = DL->getTypeAllocSize(ValTy);
3736 unsigned VectorElementSize = DL->getTypeStoreSize(VectorTy)/VF;
3737 if (!ConsecutiveStride || ScalarAllocatedSize != VectorElementSize) {
3739 // The cost of extracting from the value vector and pointer vector.
3740 Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
3741 for (unsigned i = 0; i < VF; ++i) {
3742 // The cost of extracting the pointer operand.
3743 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
3744 // In case of STORE, the cost of ExtractElement from the vector.
3745 // In case of LOAD, the cost of InsertElement into the returned
3747 Cost += TTI.getVectorInstrCost(SI ? Instruction::ExtractElement :
3748 Instruction::InsertElement,
3752 // The cost of the scalar loads/stores.
3753 Cost += VF * TTI.getAddressComputationCost(ValTy->getScalarType());
3754 Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(),
3759 // Wide load/stores.
3760 unsigned Cost = TTI.getAddressComputationCost(VectorTy);
3761 Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
3764 Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
3768 case Instruction::ZExt:
3769 case Instruction::SExt:
3770 case Instruction::FPToUI:
3771 case Instruction::FPToSI:
3772 case Instruction::FPExt:
3773 case Instruction::PtrToInt:
3774 case Instruction::IntToPtr:
3775 case Instruction::SIToFP:
3776 case Instruction::UIToFP:
3777 case Instruction::Trunc:
3778 case Instruction::FPTrunc:
3779 case Instruction::BitCast: {
3780 // We optimize the truncation of induction variable.
3781 // The cost of these is the same as the scalar operation.
3782 if (I->getOpcode() == Instruction::Trunc &&
3783 Legal->isInductionVariable(I->getOperand(0)))
3784 return TTI.getCastInstrCost(I->getOpcode(), I->getType(),
3785 I->getOperand(0)->getType());
3787 Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
3788 return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
3790 case Instruction::Call: {
3791 CallInst *CI = cast<CallInst>(I);
3792 Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
3793 assert(ID && "Not an intrinsic call!");
3794 Type *RetTy = ToVectorTy(CI->getType(), VF);
3795 SmallVector<Type*, 4> Tys;
3796 for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
3797 Tys.push_back(ToVectorTy(CI->getArgOperand(i)->getType(), VF));
3798 return TTI.getIntrinsicInstrCost(ID, RetTy, Tys);
3801 // We are scalarizing the instruction. Return the cost of the scalar
3802 // instruction, plus the cost of insert and extract into vector
3803 // elements, times the vector width.
3806 if (!RetTy->isVoidTy() && VF != 1) {
3807 unsigned InsCost = TTI.getVectorInstrCost(Instruction::InsertElement,
3809 unsigned ExtCost = TTI.getVectorInstrCost(Instruction::ExtractElement,
3812 // The cost of inserting the results plus extracting each one of the
3814 Cost += VF * (InsCost + ExtCost * I->getNumOperands());
3817 // The cost of executing VF copies of the scalar instruction. This opcode
3818 // is unknown. Assume that it is the same as 'mul'.
3819 Cost += VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy);
3825 Type* LoopVectorizationCostModel::ToVectorTy(Type *Scalar, unsigned VF) {
3826 if (Scalar->isVoidTy() || VF == 1)
3828 return VectorType::get(Scalar, VF);
3831 char LoopVectorize::ID = 0;
3832 static const char lv_name[] = "Loop Vectorization";
3833 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
3834 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3835 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
3836 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
3837 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
3838 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
3841 Pass *createLoopVectorizePass() {
3842 return new LoopVectorize();
3846 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
3847 // Check for a store.
3848 if (StoreInst *ST = dyn_cast<StoreInst>(Inst))
3849 return Legal->isConsecutivePtr(ST->getPointerOperand()) != 0;
3851 // Check for a load.
3852 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
3853 return Legal->isConsecutivePtr(LI->getPointerOperand()) != 0;