1 //===- LoopVectorize.cpp - A Loop Vectorizer ------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This is the LLVM loop vectorizer. This pass modifies 'vectorizable' loops
11 // and generates target-independent LLVM-IR. Legalization of the IR is done
12 // in the codegen. However, the vectorizes uses (will use) the codegen
13 // interfaces to generate IR that is likely to result in an optimal binary.
15 // The loop vectorizer combines consecutive loop iteration into a single
16 // 'wide' iteration. After this transformation the index is incremented
17 // by the SIMD vector width, and not by one.
19 // This pass has three parts:
20 // 1. The main loop pass that drives the different parts.
21 // 2. LoopVectorizationLegality - A unit that checks for the legality
22 // of the vectorization.
23 // 3. InnerLoopVectorizer - A unit that performs the actual
24 // widening of instructions.
25 // 4. LoopVectorizationCostModel - A unit that checks for the profitability
26 // of vectorization. It decides on the optimal vector width, which
27 // can be one, if vectorization is not profitable.
29 //===----------------------------------------------------------------------===//
31 // The reduction-variable vectorization is based on the paper:
32 // D. Nuzman and R. Henderson. Multi-platform Auto-vectorization.
34 // Variable uniformity checks are inspired by:
35 // Karrenberg, R. and Hack, S. Whole Function Vectorization.
37 // Other ideas/concepts are from:
38 // A. Zaks and D. Nuzman. Autovectorization in GCC-two years later.
40 // S. Maleki, Y. Gao, M. Garzaran, T. Wong and D. Padua. An Evaluation of
41 // Vectorizing Compilers.
43 //===----------------------------------------------------------------------===//
45 #define LV_NAME "loop-vectorize"
46 #define DEBUG_TYPE LV_NAME
48 #include "llvm/Transforms/Vectorize.h"
49 #include "llvm/ADT/DenseMap.h"
50 #include "llvm/ADT/MapVector.h"
51 #include "llvm/ADT/SmallPtrSet.h"
52 #include "llvm/ADT/SmallSet.h"
53 #include "llvm/ADT/SmallVector.h"
54 #include "llvm/ADT/StringExtras.h"
55 #include "llvm/Analysis/AliasAnalysis.h"
56 #include "llvm/Analysis/AliasSetTracker.h"
57 #include "llvm/Analysis/Dominators.h"
58 #include "llvm/Analysis/LoopInfo.h"
59 #include "llvm/Analysis/LoopIterator.h"
60 #include "llvm/Analysis/LoopPass.h"
61 #include "llvm/Analysis/ScalarEvolution.h"
62 #include "llvm/Analysis/ScalarEvolutionExpander.h"
63 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
64 #include "llvm/Analysis/TargetTransformInfo.h"
65 #include "llvm/Analysis/ValueTracking.h"
66 #include "llvm/Analysis/Verifier.h"
67 #include "llvm/IR/Constants.h"
68 #include "llvm/IR/DataLayout.h"
69 #include "llvm/IR/DerivedTypes.h"
70 #include "llvm/IR/Function.h"
71 #include "llvm/IR/IRBuilder.h"
72 #include "llvm/IR/Instructions.h"
73 #include "llvm/IR/IntrinsicInst.h"
74 #include "llvm/IR/LLVMContext.h"
75 #include "llvm/IR/Module.h"
76 #include "llvm/IR/Type.h"
77 #include "llvm/IR/Value.h"
78 #include "llvm/Pass.h"
79 #include "llvm/Support/CommandLine.h"
80 #include "llvm/Support/Debug.h"
81 #include "llvm/Support/raw_ostream.h"
82 #include "llvm/Transforms/Scalar.h"
83 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
84 #include "llvm/Transforms/Utils/Local.h"
90 static cl::opt<unsigned>
91 VectorizationFactor("force-vector-width", cl::init(0), cl::Hidden,
92 cl::desc("Sets the SIMD width. Zero is autoselect."));
94 static cl::opt<unsigned>
95 VectorizationUnroll("force-vector-unroll", cl::init(0), cl::Hidden,
96 cl::desc("Sets the vectorization unroll count. "
97 "Zero is autoselect."));
100 EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
101 cl::desc("Enable if-conversion during vectorization."));
103 /// We don't vectorize loops with a known constant trip count below this number.
104 static const unsigned TinyTripCountVectorThreshold = 16;
106 /// We don't unroll loops with a known constant trip count below this number.
107 static const unsigned TinyTripCountUnrollThreshold = 128;
109 /// When performing a runtime memory check, do not check more than this
110 /// number of pointers. Notice that the check is quadratic!
111 static const unsigned RuntimeMemoryCheckThreshold = 4;
115 // Forward declarations.
116 class LoopVectorizationLegality;
117 class LoopVectorizationCostModel;
119 /// InnerLoopVectorizer vectorizes loops which contain only one basic
120 /// block to a specified vectorization factor (VF).
121 /// This class performs the widening of scalars into vectors, or multiple
122 /// scalars. This class also implements the following features:
123 /// * It inserts an epilogue loop for handling loops that don't have iteration
124 /// counts that are known to be a multiple of the vectorization factor.
125 /// * It handles the code generation for reduction variables.
126 /// * Scalarization (implementation using scalars) of un-vectorizable
128 /// InnerLoopVectorizer does not perform any vectorization-legality
129 /// checks, and relies on the caller to check for the different legality
130 /// aspects. The InnerLoopVectorizer relies on the
131 /// LoopVectorizationLegality class to provide information about the induction
132 /// and reduction variables that were found to a given vectorization factor.
133 class InnerLoopVectorizer {
135 InnerLoopVectorizer(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
136 DominatorTree *DT, DataLayout *DL, unsigned VecWidth,
137 unsigned UnrollFactor)
138 : OrigLoop(OrigLoop), SE(SE), LI(LI), DT(DT), DL(DL), VF(VecWidth),
139 UF(UnrollFactor), Builder(SE->getContext()), Induction(0),
140 OldInduction(0), WidenMap(UnrollFactor) {}
142 // Perform the actual loop widening (vectorization).
143 void vectorize(LoopVectorizationLegality *Legal) {
144 // Create a new empty loop. Unlink the old loop and connect the new one.
145 createEmptyLoop(Legal);
146 // Widen each instruction in the old loop to a new one in the new loop.
147 // Use the Legality module to find the induction and reduction variables.
148 vectorizeLoop(Legal);
149 // Register the new loop and update the analysis passes.
154 /// A small list of PHINodes.
155 typedef SmallVector<PHINode*, 4> PhiVector;
156 /// When we unroll loops we have multiple vector values for each scalar.
157 /// This data structure holds the unrolled and vectorized values that
158 /// originated from one scalar instruction.
159 typedef SmallVector<Value*, 2> VectorParts;
161 /// Add code that checks at runtime if the accessed arrays overlap.
162 /// Returns the comparator value or NULL if no check is needed.
163 Instruction *addRuntimeCheck(LoopVectorizationLegality *Legal,
165 /// Create an empty loop, based on the loop ranges of the old loop.
166 void createEmptyLoop(LoopVectorizationLegality *Legal);
167 /// Copy and widen the instructions from the old loop.
168 void vectorizeLoop(LoopVectorizationLegality *Legal);
170 /// A helper function that computes the predicate of the block BB, assuming
171 /// that the header block of the loop is set to True. It returns the *entry*
172 /// mask for the block BB.
173 VectorParts createBlockInMask(BasicBlock *BB);
174 /// A helper function that computes the predicate of the edge between SRC
176 VectorParts createEdgeMask(BasicBlock *Src, BasicBlock *Dst);
178 /// A helper function to vectorize a single BB within the innermost loop.
179 void vectorizeBlockInLoop(LoopVectorizationLegality *Legal, BasicBlock *BB,
182 /// Insert the new loop to the loop hierarchy and pass manager
183 /// and update the analysis passes.
184 void updateAnalysis();
186 /// This instruction is un-vectorizable. Implement it as a sequence
188 void scalarizeInstruction(Instruction *Instr);
190 /// Create a broadcast instruction. This method generates a broadcast
191 /// instruction (shuffle) for loop invariant values and for the induction
192 /// value. If this is the induction variable then we extend it to N, N+1, ...
193 /// this is needed because each iteration in the loop corresponds to a SIMD
195 Value *getBroadcastInstrs(Value *V);
197 /// This function adds 0, 1, 2 ... to each vector element, starting at zero.
198 /// If Negate is set then negative numbers are added e.g. (0, -1, -2, ...).
199 /// The sequence starts at StartIndex.
200 Value *getConsecutiveVector(Value* Val, unsigned StartIdx, bool Negate);
202 /// When we go over instructions in the basic block we rely on previous
203 /// values within the current basic block or on loop invariant values.
204 /// When we widen (vectorize) values we place them in the map. If the values
205 /// are not within the map, they have to be loop invariant, so we simply
206 /// broadcast them into a vector.
207 VectorParts &getVectorValue(Value *V);
209 /// Generate a shuffle sequence that will reverse the vector Vec.
210 Value *reverseVector(Value *Vec);
212 /// This is a helper class that holds the vectorizer state. It maps scalar
213 /// instructions to vector instructions. When the code is 'unrolled' then
214 /// then a single scalar value is mapped to multiple vector parts. The parts
215 /// are stored in the VectorPart type.
217 /// C'tor. UnrollFactor controls the number of vectors ('parts') that
219 ValueMap(unsigned UnrollFactor) : UF(UnrollFactor) {}
221 /// \return True if 'Key' is saved in the Value Map.
222 bool has(Value *Key) { return MapStoreage.count(Key); }
224 /// Initializes a new entry in the map. Sets all of the vector parts to the
225 /// save value in 'Val'.
226 /// \return A reference to a vector with splat values.
227 VectorParts &splat(Value *Key, Value *Val) {
228 MapStoreage[Key].clear();
229 MapStoreage[Key].append(UF, Val);
230 return MapStoreage[Key];
233 ///\return A reference to the value that is stored at 'Key'.
234 VectorParts &get(Value *Key) {
236 MapStoreage[Key].resize(UF);
237 return MapStoreage[Key];
240 /// The unroll factor. Each entry in the map stores this number of vector
244 /// Map storage. We use std::map and not DenseMap because insertions to a
245 /// dense map invalidates its iterators.
246 std::map<Value*, VectorParts> MapStoreage;
249 /// The original loop.
251 /// Scev analysis to use.
259 /// The vectorization SIMD factor to use. Each vector will have this many
262 /// The vectorization unroll factor to use. Each scalar is vectorized to this
263 /// many different vector instructions.
266 /// The builder that we use
269 // --- Vectorization state ---
271 /// The vector-loop preheader.
272 BasicBlock *LoopVectorPreHeader;
273 /// The scalar-loop preheader.
274 BasicBlock *LoopScalarPreHeader;
275 /// Middle Block between the vector and the scalar.
276 BasicBlock *LoopMiddleBlock;
277 ///The ExitBlock of the scalar loop.
278 BasicBlock *LoopExitBlock;
279 ///The vector loop body.
280 BasicBlock *LoopVectorBody;
281 ///The scalar loop body.
282 BasicBlock *LoopScalarBody;
283 /// A list of all bypass blocks. The first block is the entry of the loop.
284 SmallVector<BasicBlock *, 4> LoopBypassBlocks;
286 /// The new Induction variable which was added to the new block.
288 /// The induction variable of the old basic block.
289 PHINode *OldInduction;
290 /// Maps scalars to widened vectors.
294 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
295 /// to what vectorization factor.
296 /// This class does not look at the profitability of vectorization, only the
297 /// legality. This class has two main kinds of checks:
298 /// * Memory checks - The code in canVectorizeMemory checks if vectorization
299 /// will change the order of memory accesses in a way that will change the
300 /// correctness of the program.
301 /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
302 /// checks for a number of different conditions, such as the availability of a
303 /// single induction variable, that all types are supported and vectorize-able,
304 /// etc. This code reflects the capabilities of InnerLoopVectorizer.
305 /// This class is also used by InnerLoopVectorizer for identifying
306 /// induction variable and the different reduction variables.
307 class LoopVectorizationLegality {
309 LoopVectorizationLegality(Loop *L, ScalarEvolution *SE, DataLayout *DL,
311 : TheLoop(L), SE(SE), DL(DL), DT(DT), Induction(0) {}
313 /// This enum represents the kinds of reductions that we support.
315 RK_NoReduction, ///< Not a reduction.
316 RK_IntegerAdd, ///< Sum of integers.
317 RK_IntegerMult, ///< Product of integers.
318 RK_IntegerOr, ///< Bitwise or logical OR of numbers.
319 RK_IntegerAnd, ///< Bitwise or logical AND of numbers.
320 RK_IntegerXor, ///< Bitwise or logical XOR of numbers.
321 RK_FloatAdd, ///< Sum of floats.
322 RK_FloatMult ///< Product of floats.
325 /// This enum represents the kinds of inductions that we support.
327 IK_NoInduction, ///< Not an induction variable.
328 IK_IntInduction, ///< Integer induction variable. Step = 1.
329 IK_ReverseIntInduction, ///< Reverse int induction variable. Step = -1.
330 IK_PtrInduction ///< Pointer induction variable. Step = sizeof(elem).
333 /// This POD struct holds information about reduction variables.
334 struct ReductionDescriptor {
335 ReductionDescriptor() : StartValue(0), LoopExitInstr(0),
336 Kind(RK_NoReduction) {}
338 ReductionDescriptor(Value *Start, Instruction *Exit, ReductionKind K)
339 : StartValue(Start), LoopExitInstr(Exit), Kind(K) {}
341 // The starting value of the reduction.
342 // It does not have to be zero!
344 // The instruction who's value is used outside the loop.
345 Instruction *LoopExitInstr;
346 // The kind of the reduction.
350 // This POD struct holds information about the memory runtime legality
351 // check that a group of pointers do not overlap.
352 struct RuntimePointerCheck {
353 RuntimePointerCheck() : Need(false) {}
355 /// Reset the state of the pointer runtime information.
363 /// Insert a pointer and calculate the start and end SCEVs.
364 void insert(ScalarEvolution *SE, Loop *Lp, Value *Ptr);
366 /// This flag indicates if we need to add the runtime check.
368 /// Holds the pointers that we need to check.
369 SmallVector<Value*, 2> Pointers;
370 /// Holds the pointer value at the beginning of the loop.
371 SmallVector<const SCEV*, 2> Starts;
372 /// Holds the pointer value at the end of the loop.
373 SmallVector<const SCEV*, 2> Ends;
376 /// A POD for saving information about induction variables.
377 struct InductionInfo {
378 InductionInfo(Value *Start, InductionKind K) : StartValue(Start), IK(K) {}
379 InductionInfo() : StartValue(0), IK(IK_NoInduction) {}
386 /// ReductionList contains the reduction descriptors for all
387 /// of the reductions that were found in the loop.
388 typedef DenseMap<PHINode*, ReductionDescriptor> ReductionList;
390 /// InductionList saves induction variables and maps them to the
391 /// induction descriptor.
392 typedef MapVector<PHINode*, InductionInfo> InductionList;
394 /// Returns true if it is legal to vectorize this loop.
395 /// This does not mean that it is profitable to vectorize this
396 /// loop, only that it is legal to do so.
399 /// Returns the Induction variable.
400 PHINode *getInduction() { return Induction; }
402 /// Returns the reduction variables found in the loop.
403 ReductionList *getReductionVars() { return &Reductions; }
405 /// Returns the induction variables found in the loop.
406 InductionList *getInductionVars() { return &Inductions; }
408 /// Returns True if V is an induction variable in this loop.
409 bool isInductionVariable(const Value *V);
411 /// Return true if the block BB needs to be predicated in order for the loop
412 /// to be vectorized.
413 bool blockNeedsPredication(BasicBlock *BB);
415 /// Check if this pointer is consecutive when vectorizing. This happens
416 /// when the last index of the GEP is the induction variable, or that the
417 /// pointer itself is an induction variable.
418 /// This check allows us to vectorize A[idx] into a wide load/store.
420 /// 0 - Stride is unknown or non consecutive.
421 /// 1 - Address is consecutive.
422 /// -1 - Address is consecutive, and decreasing.
423 int isConsecutivePtr(Value *Ptr);
425 /// Returns true if the value V is uniform within the loop.
426 bool isUniform(Value *V);
428 /// Returns true if this instruction will remain scalar after vectorization.
429 bool isUniformAfterVectorization(Instruction* I) { return Uniforms.count(I); }
431 /// Returns the information that we collected about runtime memory check.
432 RuntimePointerCheck *getRuntimePointerCheck() { return &PtrRtCheck; }
434 /// Check if a single basic block loop is vectorizable.
435 /// At this point we know that this is a loop with a constant trip count
436 /// and we only need to check individual instructions.
437 bool canVectorizeInstrs();
439 /// When we vectorize loops we may change the order in which
440 /// we read and write from memory. This method checks if it is
441 /// legal to vectorize the code, considering only memory constrains.
442 /// Returns true if the loop is vectorizable
443 bool canVectorizeMemory();
445 /// Return true if we can vectorize this loop using the IF-conversion
447 bool canVectorizeWithIfConvert();
449 /// Collect the variables that need to stay uniform after vectorization.
450 void collectLoopUniforms();
452 /// Return true if all of the instructions in the block can be speculatively
454 bool blockCanBePredicated(BasicBlock *BB);
456 /// Returns True, if 'Phi' is the kind of reduction variable for type
457 /// 'Kind'. If this is a reduction variable, it adds it to ReductionList.
458 bool AddReductionVar(PHINode *Phi, ReductionKind Kind);
459 /// Returns true if the instruction I can be a reduction variable of type
461 bool isReductionInstr(Instruction *I, ReductionKind Kind);
462 /// Returns the induction kind of Phi. This function may return NoInduction
463 /// if the PHI is not an induction variable.
464 InductionKind isInductionVariable(PHINode *Phi);
465 /// Return true if can compute the address bounds of Ptr within the loop.
466 bool hasComputableBounds(Value *Ptr);
468 /// The loop that we evaluate.
472 /// DataLayout analysis.
477 // --- vectorization state --- //
479 /// Holds the integer induction variable. This is the counter of the
482 /// Holds the reduction variables.
483 ReductionList Reductions;
484 /// Holds all of the induction variables that we found in the loop.
485 /// Notice that inductions don't need to start at zero and that induction
486 /// variables can be pointers.
487 InductionList Inductions;
489 /// Allowed outside users. This holds the reduction
490 /// vars which can be accessed from outside the loop.
491 SmallPtrSet<Value*, 4> AllowedExit;
492 /// This set holds the variables which are known to be uniform after
494 SmallPtrSet<Instruction*, 4> Uniforms;
495 /// We need to check that all of the pointers in this list are disjoint
497 RuntimePointerCheck PtrRtCheck;
500 /// LoopVectorizationCostModel - estimates the expected speedups due to
502 /// In many cases vectorization is not profitable. This can happen because of
503 /// a number of reasons. In this class we mainly attempt to predict the
504 /// expected speedup/slowdowns due to the supported instruction set. We use the
505 /// TargetTransformInfo to query the different backends for the cost of
506 /// different operations.
507 class LoopVectorizationCostModel {
509 LoopVectorizationCostModel(Loop *L, ScalarEvolution *SE, LoopInfo *LI,
510 LoopVectorizationLegality *Legal,
511 const TargetTransformInfo &TTI)
512 : TheLoop(L), SE(SE), LI(LI), Legal(Legal), TTI(TTI) {}
514 /// \return The most profitable vectorization factor and the cost of that VF.
515 /// This method checks every power of two up to VF. If UserVF is not ZERO
516 /// then this vectorization factor will be selected if vectorization is
518 std::pair<unsigned, unsigned>
519 selectVectorizationFactor(bool OptForSize, unsigned UserVF);
521 /// \returns The size (in bits) of the widest type in the code that
522 /// needs to be vectorized. We ignore values that remain scalar such as
523 /// 64 bit loop indices.
524 unsigned getWidestType();
526 /// \return The most profitable unroll factor.
527 /// If UserUF is non-zero then this method finds the best unroll-factor
528 /// based on register pressure and other parameters.
529 /// VF and LoopCost are the selected vectorization factor and the cost of the
531 unsigned selectUnrollFactor(bool OptForSize, unsigned UserUF, unsigned VF,
534 /// \brief A struct that represents some properties of the register usage
536 struct RegisterUsage {
537 /// Holds the number of loop invariant values that are used in the loop.
538 unsigned LoopInvariantRegs;
539 /// Holds the maximum number of concurrent live intervals in the loop.
540 unsigned MaxLocalUsers;
541 /// Holds the number of instructions in the loop.
542 unsigned NumInstructions;
545 /// \return information about the register usage of the loop.
546 RegisterUsage calculateRegisterUsage();
549 /// Returns the expected execution cost. The unit of the cost does
550 /// not matter because we use the 'cost' units to compare different
551 /// vector widths. The cost that is returned is *not* normalized by
552 /// the factor width.
553 unsigned expectedCost(unsigned VF);
555 /// Returns the execution time cost of an instruction for a given vector
556 /// width. Vector width of one means scalar.
557 unsigned getInstructionCost(Instruction *I, unsigned VF);
559 /// A helper function for converting Scalar types to vector types.
560 /// If the incoming type is void, we return void. If the VF is 1, we return
562 static Type* ToVectorTy(Type *Scalar, unsigned VF);
564 /// The loop that we evaluate.
568 /// Loop Info analysis.
570 /// Vectorization legality.
571 LoopVectorizationLegality *Legal;
572 /// Vector target information.
573 const TargetTransformInfo &TTI;
576 /// The LoopVectorize Pass.
577 struct LoopVectorize : public LoopPass {
578 /// Pass identification, replacement for typeid
581 explicit LoopVectorize() : LoopPass(ID) {
582 initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
588 TargetTransformInfo *TTI;
591 virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
592 // We only vectorize innermost loops.
596 SE = &getAnalysis<ScalarEvolution>();
597 DL = getAnalysisIfAvailable<DataLayout>();
598 LI = &getAnalysis<LoopInfo>();
599 TTI = &getAnalysis<TargetTransformInfo>();
600 DT = &getAnalysis<DominatorTree>();
602 DEBUG(dbgs() << "LV: Checking a loop in \"" <<
603 L->getHeader()->getParent()->getName() << "\"\n");
605 // Check if it is legal to vectorize the loop.
606 LoopVectorizationLegality LVL(L, SE, DL, DT);
607 if (!LVL.canVectorize()) {
608 DEBUG(dbgs() << "LV: Not vectorizing.\n");
612 // Use the cost model.
613 LoopVectorizationCostModel CM(L, SE, LI, &LVL, *TTI);
615 // Check the function attribues to find out if this function should be
616 // optimized for size.
617 Function *F = L->getHeader()->getParent();
618 Attribute::AttrKind SzAttr = Attribute::OptimizeForSize;
619 Attribute::AttrKind FlAttr = Attribute::NoImplicitFloat;
620 unsigned FnIndex = AttributeSet::FunctionIndex;
621 bool OptForSize = F->getAttributes().hasAttribute(FnIndex, SzAttr);
622 bool NoFloat = F->getAttributes().hasAttribute(FnIndex, FlAttr);
625 DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
626 "attribute is used.\n");
630 // Select the optimal vectorization factor.
631 std::pair<unsigned, unsigned> VFPair;
632 VFPair = CM.selectVectorizationFactor(OptForSize, VectorizationFactor);
633 // Select the unroll factor.
634 unsigned UF = CM.selectUnrollFactor(OptForSize, VectorizationUnroll,
635 VFPair.first, VFPair.second);
636 unsigned VF = VFPair.first;
639 DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
643 DEBUG(dbgs() << "LV: Found a vectorizable loop ("<< VF << ") in "<<
644 F->getParent()->getModuleIdentifier()<<"\n");
645 DEBUG(dbgs() << "LV: Unroll Factor is " << UF << "\n");
647 // If we decided that it is *legal* to vectorizer the loop then do it.
648 InnerLoopVectorizer LB(L, SE, LI, DT, DL, VF, UF);
651 DEBUG(verifyFunction(*L->getHeader()->getParent()));
655 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
656 LoopPass::getAnalysisUsage(AU);
657 AU.addRequiredID(LoopSimplifyID);
658 AU.addRequiredID(LCSSAID);
659 AU.addRequired<DominatorTree>();
660 AU.addRequired<LoopInfo>();
661 AU.addRequired<ScalarEvolution>();
662 AU.addRequired<TargetTransformInfo>();
663 AU.addPreserved<LoopInfo>();
664 AU.addPreserved<DominatorTree>();
669 } // end anonymous namespace
671 //===----------------------------------------------------------------------===//
672 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
673 // LoopVectorizationCostModel.
674 //===----------------------------------------------------------------------===//
677 LoopVectorizationLegality::RuntimePointerCheck::insert(ScalarEvolution *SE,
678 Loop *Lp, Value *Ptr) {
679 const SCEV *Sc = SE->getSCEV(Ptr);
680 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
681 assert(AR && "Invalid addrec expression");
682 const SCEV *Ex = SE->getExitCount(Lp, Lp->getLoopLatch());
683 const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
684 Pointers.push_back(Ptr);
685 Starts.push_back(AR->getStart());
686 Ends.push_back(ScEnd);
689 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
690 // Save the current insertion location.
691 Instruction *Loc = Builder.GetInsertPoint();
693 // We need to place the broadcast of invariant variables outside the loop.
694 Instruction *Instr = dyn_cast<Instruction>(V);
695 bool NewInstr = (Instr && Instr->getParent() == LoopVectorBody);
696 bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
698 // Place the code for broadcasting invariant variables in the new preheader.
700 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
702 // Broadcast the scalar into all locations in the vector.
703 Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
705 // Restore the builder insertion point.
707 Builder.SetInsertPoint(Loc);
712 Value *InnerLoopVectorizer::getConsecutiveVector(Value* Val, unsigned StartIdx,
714 assert(Val->getType()->isVectorTy() && "Must be a vector");
715 assert(Val->getType()->getScalarType()->isIntegerTy() &&
716 "Elem must be an integer");
718 Type *ITy = Val->getType()->getScalarType();
719 VectorType *Ty = cast<VectorType>(Val->getType());
720 int VLen = Ty->getNumElements();
721 SmallVector<Constant*, 8> Indices;
723 // Create a vector of consecutive numbers from zero to VF.
724 for (int i = 0; i < VLen; ++i) {
725 int Idx = Negate ? (-i): i;
726 Indices.push_back(ConstantInt::get(ITy, StartIdx + Idx));
729 // Add the consecutive indices to the vector value.
730 Constant *Cv = ConstantVector::get(Indices);
731 assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
732 return Builder.CreateAdd(Val, Cv, "induction");
735 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
736 assert(Ptr->getType()->isPointerTy() && "Unexpected non ptr");
738 // If this value is a pointer induction variable we know it is consecutive.
739 PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
740 if (Phi && Inductions.count(Phi)) {
741 InductionInfo II = Inductions[Phi];
742 if (IK_PtrInduction == II.IK)
746 GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
750 unsigned NumOperands = Gep->getNumOperands();
751 Value *LastIndex = Gep->getOperand(NumOperands - 1);
753 // Check that all of the gep indices are uniform except for the last.
754 for (unsigned i = 0; i < NumOperands - 1; ++i)
755 if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
758 // We can emit wide load/stores only if the last index is the induction
760 const SCEV *Last = SE->getSCEV(LastIndex);
761 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
762 const SCEV *Step = AR->getStepRecurrence(*SE);
764 // The memory is consecutive because the last index is consecutive
765 // and all other indices are loop invariant.
768 if (Step->isAllOnesValue())
775 bool LoopVectorizationLegality::isUniform(Value *V) {
776 return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
779 InnerLoopVectorizer::VectorParts&
780 InnerLoopVectorizer::getVectorValue(Value *V) {
781 assert(V != Induction && "The new induction variable should not be used.");
782 assert(!V->getType()->isVectorTy() && "Can't widen a vector");
784 // If we have this scalar in the map, return it.
786 return WidenMap.get(V);
788 // If this scalar is unknown, assume that it is a constant or that it is
789 // loop invariant. Broadcast V and save the value for future uses.
790 Value *B = getBroadcastInstrs(V);
791 WidenMap.splat(V, B);
792 return WidenMap.get(V);
795 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
796 assert(Vec->getType()->isVectorTy() && "Invalid type");
797 SmallVector<Constant*, 8> ShuffleMask;
798 for (unsigned i = 0; i < VF; ++i)
799 ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
801 return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
802 ConstantVector::get(ShuffleMask),
806 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr) {
807 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
808 // Holds vector parameters or scalars, in case of uniform vals.
809 SmallVector<VectorParts, 4> Params;
811 // Find all of the vectorized parameters.
812 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
813 Value *SrcOp = Instr->getOperand(op);
815 // If we are accessing the old induction variable, use the new one.
816 if (SrcOp == OldInduction) {
817 Params.push_back(getVectorValue(SrcOp));
821 // Try using previously calculated values.
822 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
824 // If the src is an instruction that appeared earlier in the basic block
825 // then it should already be vectorized.
826 if (SrcInst && OrigLoop->contains(SrcInst)) {
827 assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
828 // The parameter is a vector value from earlier.
829 Params.push_back(WidenMap.get(SrcInst));
831 // The parameter is a scalar from outside the loop. Maybe even a constant.
833 Scalars.append(UF, SrcOp);
834 Params.push_back(Scalars);
838 assert(Params.size() == Instr->getNumOperands() &&
839 "Invalid number of operands");
841 // Does this instruction return a value ?
842 bool IsVoidRetTy = Instr->getType()->isVoidTy();
844 Value *UndefVec = IsVoidRetTy ? 0 :
845 UndefValue::get(VectorType::get(Instr->getType(), VF));
846 // Create a new entry in the WidenMap and initialize it to Undef or Null.
847 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
849 // For each scalar that we create:
850 for (unsigned Width = 0; Width < VF; ++Width) {
851 // For each vector unroll 'part':
852 for (unsigned Part = 0; Part < UF; ++Part) {
853 Instruction *Cloned = Instr->clone();
855 Cloned->setName(Instr->getName() + ".cloned");
856 // Replace the operands of the cloned instrucions with extracted scalars.
857 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
858 Value *Op = Params[op][Part];
859 // Param is a vector. Need to extract the right lane.
860 if (Op->getType()->isVectorTy())
861 Op = Builder.CreateExtractElement(Op, Builder.getInt32(Width));
862 Cloned->setOperand(op, Op);
865 // Place the cloned scalar in the new loop.
866 Builder.Insert(Cloned);
868 // If the original scalar returns a value we need to place it in a vector
869 // so that future users will be able to use it.
871 VecResults[Part] = Builder.CreateInsertElement(VecResults[Part], Cloned,
872 Builder.getInt32(Width));
878 InnerLoopVectorizer::addRuntimeCheck(LoopVectorizationLegality *Legal,
880 LoopVectorizationLegality::RuntimePointerCheck *PtrRtCheck =
881 Legal->getRuntimePointerCheck();
883 if (!PtrRtCheck->Need)
886 Instruction *MemoryRuntimeCheck = 0;
887 unsigned NumPointers = PtrRtCheck->Pointers.size();
888 SmallVector<Value* , 2> Starts;
889 SmallVector<Value* , 2> Ends;
891 SCEVExpander Exp(*SE, "induction");
893 // Use this type for pointer arithmetic.
894 Type* PtrArithTy = Type::getInt8PtrTy(Loc->getContext(), 0);
896 for (unsigned i = 0; i < NumPointers; ++i) {
897 Value *Ptr = PtrRtCheck->Pointers[i];
898 const SCEV *Sc = SE->getSCEV(Ptr);
900 if (SE->isLoopInvariant(Sc, OrigLoop)) {
901 DEBUG(dbgs() << "LV: Adding RT check for a loop invariant ptr:" <<
903 Starts.push_back(Ptr);
906 DEBUG(dbgs() << "LV: Adding RT check for range:" << *Ptr <<"\n");
908 Value *Start = Exp.expandCodeFor(PtrRtCheck->Starts[i], PtrArithTy, Loc);
909 Value *End = Exp.expandCodeFor(PtrRtCheck->Ends[i], PtrArithTy, Loc);
910 Starts.push_back(Start);
915 for (unsigned i = 0; i < NumPointers; ++i) {
916 for (unsigned j = i+1; j < NumPointers; ++j) {
917 Instruction::CastOps Op = Instruction::BitCast;
918 Value *Start0 = CastInst::Create(Op, Starts[i], PtrArithTy, "bc", Loc);
919 Value *Start1 = CastInst::Create(Op, Starts[j], PtrArithTy, "bc", Loc);
920 Value *End0 = CastInst::Create(Op, Ends[i], PtrArithTy, "bc", Loc);
921 Value *End1 = CastInst::Create(Op, Ends[j], PtrArithTy, "bc", Loc);
923 Value *Cmp0 = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_ULE,
924 Start0, End1, "bound0", Loc);
925 Value *Cmp1 = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_ULE,
926 Start1, End0, "bound1", Loc);
927 Instruction *IsConflict = BinaryOperator::Create(Instruction::And, Cmp0,
928 Cmp1, "found.conflict",
930 if (MemoryRuntimeCheck)
931 MemoryRuntimeCheck = BinaryOperator::Create(Instruction::Or,
934 "conflict.rdx", Loc);
936 MemoryRuntimeCheck = IsConflict;
941 return MemoryRuntimeCheck;
945 InnerLoopVectorizer::createEmptyLoop(LoopVectorizationLegality *Legal) {
947 In this function we generate a new loop. The new loop will contain
948 the vectorized instructions while the old loop will continue to run the
951 [ ] <-- vector loop bypass (may consist of multiple blocks).
954 | [ ] <-- vector pre header.
958 | [ ]_| <-- vector loop.
961 >[ ] <--- middle-block.
964 | [ ] <--- new preheader.
968 | [ ]_| <-- old scalar loop to handle remainder.
975 BasicBlock *OldBasicBlock = OrigLoop->getHeader();
976 BasicBlock *BypassBlock = OrigLoop->getLoopPreheader();
977 BasicBlock *ExitBlock = OrigLoop->getExitBlock();
978 assert(ExitBlock && "Must have an exit block");
980 // Some loops have a single integer induction variable, while other loops
981 // don't. One example is c++ iterators that often have multiple pointer
982 // induction variables. In the code below we also support a case where we
983 // don't have a single induction variable.
984 OldInduction = Legal->getInduction();
985 Type *IdxTy = OldInduction ? OldInduction->getType() :
986 DL->getIntPtrType(SE->getContext());
988 // Find the loop boundaries.
989 const SCEV *ExitCount = SE->getExitCount(OrigLoop, OrigLoop->getLoopLatch());
990 assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
992 // Get the total trip count from the count by adding 1.
993 ExitCount = SE->getAddExpr(ExitCount,
994 SE->getConstant(ExitCount->getType(), 1));
996 // Expand the trip count and place the new instructions in the preheader.
997 // Notice that the pre-header does not change, only the loop body.
998 SCEVExpander Exp(*SE, "induction");
1000 // Count holds the overall loop count (N).
1001 Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
1002 BypassBlock->getTerminator());
1004 // The loop index does not have to start at Zero. Find the original start
1005 // value from the induction PHI node. If we don't have an induction variable
1006 // then we know that it starts at zero.
1007 Value *StartIdx = OldInduction ?
1008 OldInduction->getIncomingValueForBlock(BypassBlock):
1009 ConstantInt::get(IdxTy, 0);
1011 assert(BypassBlock && "Invalid loop structure");
1012 LoopBypassBlocks.push_back(BypassBlock);
1014 // Split the single block loop into the two loop structure described above.
1015 BasicBlock *VectorPH =
1016 BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
1017 BasicBlock *VecBody =
1018 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
1019 BasicBlock *MiddleBlock =
1020 VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
1021 BasicBlock *ScalarPH =
1022 MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
1024 // This is the location in which we add all of the logic for bypassing
1025 // the new vector loop.
1026 Instruction *Loc = BypassBlock->getTerminator();
1028 // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
1030 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
1032 // Generate the induction variable.
1033 Induction = Builder.CreatePHI(IdxTy, 2, "index");
1034 // The loop step is equal to the vectorization factor (num of SIMD elements)
1035 // times the unroll factor (num of SIMD instructions).
1036 Constant *Step = ConstantInt::get(IdxTy, VF * UF);
1038 // We may need to extend the index in case there is a type mismatch.
1039 // We know that the count starts at zero and does not overflow.
1040 unsigned IdxTyBW = IdxTy->getScalarSizeInBits();
1041 if (Count->getType() != IdxTy) {
1042 // The exit count can be of pointer type. Convert it to the correct
1044 if (ExitCount->getType()->isPointerTy())
1045 Count = CastInst::CreatePointerCast(Count, IdxTy, "ptrcnt.to.int", Loc);
1046 else if (IdxTyBW < Count->getType()->getScalarSizeInBits())
1047 Count = CastInst::CreateTruncOrBitCast(Count, IdxTy, "tr.cnt", Loc);
1049 Count = CastInst::CreateZExtOrBitCast(Count, IdxTy, "zext.cnt", Loc);
1052 // Add the start index to the loop count to get the new end index.
1053 Value *IdxEnd = BinaryOperator::CreateAdd(Count, StartIdx, "end.idx", Loc);
1055 // Now we need to generate the expression for N - (N % VF), which is
1056 // the part that the vectorized body will execute.
1057 Value *R = BinaryOperator::CreateURem(Count, Step, "n.mod.vf", Loc);
1058 Value *CountRoundDown = BinaryOperator::CreateSub(Count, R, "n.vec", Loc);
1059 Value *IdxEndRoundDown = BinaryOperator::CreateAdd(CountRoundDown, StartIdx,
1060 "end.idx.rnd.down", Loc);
1062 // Now, compare the new count to zero. If it is zero skip the vector loop and
1063 // jump to the scalar loop.
1064 Value *Cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
1069 // Generate the code that checks in runtime if arrays overlap. We put the
1070 // checks into a separate block to make the more common case of few elements
1072 if (Instruction *MemoryRuntimeCheck = addRuntimeCheck(Legal, Loc)) {
1073 // Create a new block containing the memory check.
1074 BasicBlock *CheckBlock = BypassBlock->splitBasicBlock(MemoryRuntimeCheck,
1076 LoopBypassBlocks.push_back(CheckBlock);
1078 // Replace the branch into the memory check block with a conditional branch
1079 // for the "few elements case".
1080 Instruction *OldTerm = BypassBlock->getTerminator();
1081 BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
1082 OldTerm->eraseFromParent();
1084 Cmp = MemoryRuntimeCheck;
1085 assert(Loc == CheckBlock->getTerminator());
1088 BranchInst::Create(MiddleBlock, VectorPH, Cmp, Loc);
1089 // Remove the old terminator.
1090 Loc->eraseFromParent();
1092 // We are going to resume the execution of the scalar loop.
1093 // Go over all of the induction variables that we found and fix the
1094 // PHIs that are left in the scalar version of the loop.
1095 // The starting values of PHI nodes depend on the counter of the last
1096 // iteration in the vectorized loop.
1097 // If we come from a bypass edge then we need to start from the original
1100 // This variable saves the new starting index for the scalar loop.
1101 PHINode *ResumeIndex = 0;
1102 LoopVectorizationLegality::InductionList::iterator I, E;
1103 LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
1104 for (I = List->begin(), E = List->end(); I != E; ++I) {
1105 PHINode *OrigPhi = I->first;
1106 LoopVectorizationLegality::InductionInfo II = I->second;
1107 PHINode *ResumeVal = PHINode::Create(OrigPhi->getType(), 2, "resume.val",
1108 MiddleBlock->getTerminator());
1109 Value *EndValue = 0;
1111 case LoopVectorizationLegality::IK_NoInduction:
1112 llvm_unreachable("Unknown induction");
1113 case LoopVectorizationLegality::IK_IntInduction: {
1114 // Handle the integer induction counter:
1115 assert(OrigPhi->getType()->isIntegerTy() && "Invalid type");
1116 assert(OrigPhi == OldInduction && "Unknown integer PHI");
1117 // We know what the end value is.
1118 EndValue = IdxEndRoundDown;
1119 // We also know which PHI node holds it.
1120 ResumeIndex = ResumeVal;
1123 case LoopVectorizationLegality::IK_ReverseIntInduction: {
1124 // Convert the CountRoundDown variable to the PHI size.
1125 unsigned CRDSize = CountRoundDown->getType()->getScalarSizeInBits();
1126 unsigned IISize = II.StartValue->getType()->getScalarSizeInBits();
1127 Value *CRD = CountRoundDown;
1128 if (CRDSize > IISize)
1129 CRD = CastInst::Create(Instruction::Trunc, CountRoundDown,
1130 II.StartValue->getType(), "tr.crd",
1131 LoopBypassBlocks.back()->getTerminator());
1132 else if (CRDSize < IISize)
1133 CRD = CastInst::Create(Instruction::SExt, CountRoundDown,
1134 II.StartValue->getType(),
1136 LoopBypassBlocks.back()->getTerminator());
1137 // Handle reverse integer induction counter:
1139 BinaryOperator::CreateSub(II.StartValue, CRD, "rev.ind.end",
1140 LoopBypassBlocks.back()->getTerminator());
1143 case LoopVectorizationLegality::IK_PtrInduction: {
1144 // For pointer induction variables, calculate the offset using
1147 GetElementPtrInst::Create(II.StartValue, CountRoundDown, "ptr.ind.end",
1148 LoopBypassBlocks.back()->getTerminator());
1153 // The new PHI merges the original incoming value, in case of a bypass,
1154 // or the value at the end of the vectorized loop.
1155 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
1156 ResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
1157 ResumeVal->addIncoming(EndValue, VecBody);
1159 // Fix the scalar body counter (PHI node).
1160 unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
1161 OrigPhi->setIncomingValue(BlockIdx, ResumeVal);
1164 // If we are generating a new induction variable then we also need to
1165 // generate the code that calculates the exit value. This value is not
1166 // simply the end of the counter because we may skip the vectorized body
1167 // in case of a runtime check.
1169 assert(!ResumeIndex && "Unexpected resume value found");
1170 ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val",
1171 MiddleBlock->getTerminator());
1172 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
1173 ResumeIndex->addIncoming(StartIdx, LoopBypassBlocks[I]);
1174 ResumeIndex->addIncoming(IdxEndRoundDown, VecBody);
1177 // Make sure that we found the index where scalar loop needs to continue.
1178 assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() &&
1179 "Invalid resume Index");
1181 // Add a check in the middle block to see if we have completed
1182 // all of the iterations in the first vector loop.
1183 // If (N - N%VF) == N, then we *don't* need to run the remainder.
1184 Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd,
1185 ResumeIndex, "cmp.n",
1186 MiddleBlock->getTerminator());
1188 BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
1189 // Remove the old terminator.
1190 MiddleBlock->getTerminator()->eraseFromParent();
1192 // Create i+1 and fill the PHINode.
1193 Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
1194 Induction->addIncoming(StartIdx, VectorPH);
1195 Induction->addIncoming(NextIdx, VecBody);
1196 // Create the compare.
1197 Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown);
1198 Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
1200 // Now we have two terminators. Remove the old one from the block.
1201 VecBody->getTerminator()->eraseFromParent();
1203 // Get ready to start creating new instructions into the vectorized body.
1204 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
1206 // Create and register the new vector loop.
1207 Loop* Lp = new Loop();
1208 Loop *ParentLoop = OrigLoop->getParentLoop();
1210 // Insert the new loop into the loop nest and register the new basic blocks.
1212 ParentLoop->addChildLoop(Lp);
1213 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
1214 ParentLoop->addBasicBlockToLoop(LoopBypassBlocks[I], LI->getBase());
1215 ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase());
1216 ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase());
1217 ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase());
1219 LI->addTopLevelLoop(Lp);
1222 Lp->addBasicBlockToLoop(VecBody, LI->getBase());
1225 LoopVectorPreHeader = VectorPH;
1226 LoopScalarPreHeader = ScalarPH;
1227 LoopMiddleBlock = MiddleBlock;
1228 LoopExitBlock = ExitBlock;
1229 LoopVectorBody = VecBody;
1230 LoopScalarBody = OldBasicBlock;
1233 /// This function returns the identity element (or neutral element) for
1234 /// the operation K.
1236 getReductionIdentity(LoopVectorizationLegality::ReductionKind K, Type *Tp) {
1238 case LoopVectorizationLegality:: RK_IntegerXor:
1239 case LoopVectorizationLegality:: RK_IntegerAdd:
1240 case LoopVectorizationLegality:: RK_IntegerOr:
1241 // Adding, Xoring, Oring zero to a number does not change it.
1242 return ConstantInt::get(Tp, 0);
1243 case LoopVectorizationLegality:: RK_IntegerMult:
1244 // Multiplying a number by 1 does not change it.
1245 return ConstantInt::get(Tp, 1);
1246 case LoopVectorizationLegality:: RK_IntegerAnd:
1247 // AND-ing a number with an all-1 value does not change it.
1248 return ConstantInt::get(Tp, -1, true);
1249 case LoopVectorizationLegality:: RK_FloatMult:
1250 // Multiplying a number by 1 does not change it.
1251 return ConstantFP::get(Tp, 1.0L);
1252 case LoopVectorizationLegality:: RK_FloatAdd:
1253 // Adding zero to a number does not change it.
1254 return ConstantFP::get(Tp, 0.0L);
1256 llvm_unreachable("Unknown reduction kind");
1261 isTriviallyVectorizableIntrinsic(Instruction *Inst) {
1262 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst);
1265 switch (II->getIntrinsicID()) {
1266 case Intrinsic::sqrt:
1267 case Intrinsic::sin:
1268 case Intrinsic::cos:
1269 case Intrinsic::exp:
1270 case Intrinsic::exp2:
1271 case Intrinsic::log:
1272 case Intrinsic::log10:
1273 case Intrinsic::log2:
1274 case Intrinsic::fabs:
1275 case Intrinsic::floor:
1276 case Intrinsic::ceil:
1277 case Intrinsic::trunc:
1278 case Intrinsic::rint:
1279 case Intrinsic::nearbyint:
1280 case Intrinsic::pow:
1281 case Intrinsic::fma:
1282 case Intrinsic::fmuladd:
1290 /// This function translates the reduction kind to an LLVM binary operator.
1291 static Instruction::BinaryOps
1292 getReductionBinOp(LoopVectorizationLegality::ReductionKind Kind) {
1294 case LoopVectorizationLegality::RK_IntegerAdd:
1295 return Instruction::Add;
1296 case LoopVectorizationLegality::RK_IntegerMult:
1297 return Instruction::Mul;
1298 case LoopVectorizationLegality::RK_IntegerOr:
1299 return Instruction::Or;
1300 case LoopVectorizationLegality::RK_IntegerAnd:
1301 return Instruction::And;
1302 case LoopVectorizationLegality::RK_IntegerXor:
1303 return Instruction::Xor;
1304 case LoopVectorizationLegality::RK_FloatMult:
1305 return Instruction::FMul;
1306 case LoopVectorizationLegality::RK_FloatAdd:
1307 return Instruction::FAdd;
1309 llvm_unreachable("Unknown reduction operation");
1314 InnerLoopVectorizer::vectorizeLoop(LoopVectorizationLegality *Legal) {
1315 //===------------------------------------------------===//
1317 // Notice: any optimization or new instruction that go
1318 // into the code below should be also be implemented in
1321 //===------------------------------------------------===//
1322 BasicBlock &BB = *OrigLoop->getHeader();
1324 ConstantInt::get(IntegerType::getInt32Ty(BB.getContext()), 0);
1326 // In order to support reduction variables we need to be able to vectorize
1327 // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
1328 // stages. First, we create a new vector PHI node with no incoming edges.
1329 // We use this value when we vectorize all of the instructions that use the
1330 // PHI. Next, after all of the instructions in the block are complete we
1331 // add the new incoming edges to the PHI. At this point all of the
1332 // instructions in the basic block are vectorized, so we can use them to
1333 // construct the PHI.
1334 PhiVector RdxPHIsToFix;
1336 // Scan the loop in a topological order to ensure that defs are vectorized
1338 LoopBlocksDFS DFS(OrigLoop);
1341 // Vectorize all of the blocks in the original loop.
1342 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
1343 be = DFS.endRPO(); bb != be; ++bb)
1344 vectorizeBlockInLoop(Legal, *bb, &RdxPHIsToFix);
1346 // At this point every instruction in the original loop is widened to
1347 // a vector form. We are almost done. Now, we need to fix the PHI nodes
1348 // that we vectorized. The PHI nodes are currently empty because we did
1349 // not want to introduce cycles. Notice that the remaining PHI nodes
1350 // that we need to fix are reduction variables.
1352 // Create the 'reduced' values for each of the induction vars.
1353 // The reduced values are the vector values that we scalarize and combine
1354 // after the loop is finished.
1355 for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
1357 PHINode *RdxPhi = *it;
1358 assert(RdxPhi && "Unable to recover vectorized PHI");
1360 // Find the reduction variable descriptor.
1361 assert(Legal->getReductionVars()->count(RdxPhi) &&
1362 "Unable to find the reduction variable");
1363 LoopVectorizationLegality::ReductionDescriptor RdxDesc =
1364 (*Legal->getReductionVars())[RdxPhi];
1366 // We need to generate a reduction vector from the incoming scalar.
1367 // To do so, we need to generate the 'identity' vector and overide
1368 // one of the elements with the incoming scalar reduction. We need
1369 // to do it in the vector-loop preheader.
1370 Builder.SetInsertPoint(LoopBypassBlocks.back()->getTerminator());
1372 // This is the vector-clone of the value that leaves the loop.
1373 VectorParts &VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
1374 Type *VecTy = VectorExit[0]->getType();
1376 // Find the reduction identity variable. Zero for addition, or, xor,
1377 // one for multiplication, -1 for And.
1378 Constant *Iden = getReductionIdentity(RdxDesc.Kind, VecTy->getScalarType());
1379 Constant *Identity = ConstantVector::getSplat(VF, Iden);
1381 // This vector is the Identity vector where the first element is the
1382 // incoming scalar reduction.
1383 Value *VectorStart = Builder.CreateInsertElement(Identity,
1384 RdxDesc.StartValue, Zero);
1386 // Fix the vector-loop phi.
1387 // We created the induction variable so we know that the
1388 // preheader is the first entry.
1389 BasicBlock *VecPreheader = Induction->getIncomingBlock(0);
1391 // Reductions do not have to start at zero. They can start with
1392 // any loop invariant values.
1393 VectorParts &VecRdxPhi = WidenMap.get(RdxPhi);
1394 BasicBlock *Latch = OrigLoop->getLoopLatch();
1395 Value *LoopVal = RdxPhi->getIncomingValueForBlock(Latch);
1396 VectorParts &Val = getVectorValue(LoopVal);
1397 for (unsigned part = 0; part < UF; ++part) {
1398 // Make sure to add the reduction stat value only to the
1399 // first unroll part.
1400 Value *StartVal = (part == 0) ? VectorStart : Identity;
1401 cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal, VecPreheader);
1402 cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part], LoopVectorBody);
1405 // Before each round, move the insertion point right between
1406 // the PHIs and the values we are going to write.
1407 // This allows us to write both PHINodes and the extractelement
1409 Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
1411 VectorParts RdxParts;
1412 for (unsigned part = 0; part < UF; ++part) {
1413 // This PHINode contains the vectorized reduction variable, or
1414 // the initial value vector, if we bypass the vector loop.
1415 VectorParts &RdxExitVal = getVectorValue(RdxDesc.LoopExitInstr);
1416 PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
1417 Value *StartVal = (part == 0) ? VectorStart : Identity;
1418 for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
1419 NewPhi->addIncoming(StartVal, LoopBypassBlocks[I]);
1420 NewPhi->addIncoming(RdxExitVal[part], LoopVectorBody);
1421 RdxParts.push_back(NewPhi);
1424 // Reduce all of the unrolled parts into a single vector.
1425 Value *ReducedPartRdx = RdxParts[0];
1426 for (unsigned part = 1; part < UF; ++part) {
1427 Instruction::BinaryOps Op = getReductionBinOp(RdxDesc.Kind);
1428 ReducedPartRdx = Builder.CreateBinOp(Op, RdxParts[part], ReducedPartRdx,
1432 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
1433 // and vector ops, reducing the set of values being computed by half each
1435 assert(isPowerOf2_32(VF) &&
1436 "Reduction emission only supported for pow2 vectors!");
1437 Value *TmpVec = ReducedPartRdx;
1438 SmallVector<Constant*, 32> ShuffleMask(VF, 0);
1439 for (unsigned i = VF; i != 1; i >>= 1) {
1440 // Move the upper half of the vector to the lower half.
1441 for (unsigned j = 0; j != i/2; ++j)
1442 ShuffleMask[j] = Builder.getInt32(i/2 + j);
1444 // Fill the rest of the mask with undef.
1445 std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
1446 UndefValue::get(Builder.getInt32Ty()));
1449 Builder.CreateShuffleVector(TmpVec,
1450 UndefValue::get(TmpVec->getType()),
1451 ConstantVector::get(ShuffleMask),
1454 Instruction::BinaryOps Op = getReductionBinOp(RdxDesc.Kind);
1455 TmpVec = Builder.CreateBinOp(Op, TmpVec, Shuf, "bin.rdx");
1458 // The result is in the first element of the vector.
1459 Value *Scalar0 = Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
1461 // Now, we need to fix the users of the reduction variable
1462 // inside and outside of the scalar remainder loop.
1463 // We know that the loop is in LCSSA form. We need to update the
1464 // PHI nodes in the exit blocks.
1465 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
1466 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
1467 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
1468 if (!LCSSAPhi) continue;
1470 // All PHINodes need to have a single entry edge, or two if
1471 // we already fixed them.
1472 assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
1474 // We found our reduction value exit-PHI. Update it with the
1475 // incoming bypass edge.
1476 if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
1477 // Add an edge coming from the bypass.
1478 LCSSAPhi->addIncoming(Scalar0, LoopMiddleBlock);
1481 }// end of the LCSSA phi scan.
1483 // Fix the scalar loop reduction variable with the incoming reduction sum
1484 // from the vector body and from the backedge value.
1485 int IncomingEdgeBlockIdx =
1486 (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
1487 assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
1488 // Pick the other block.
1489 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
1490 (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, Scalar0);
1491 (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
1492 }// end of for each redux variable.
1494 // The Loop exit block may have single value PHI nodes where the incoming
1495 // value is 'undef'. While vectorizing we only handled real values that
1496 // were defined inside the loop. Here we handle the 'undef case'.
1498 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
1499 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
1500 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
1501 if (!LCSSAPhi) continue;
1502 if (LCSSAPhi->getNumIncomingValues() == 1)
1503 LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
1508 InnerLoopVectorizer::VectorParts
1509 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
1510 assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
1513 VectorParts SrcMask = createBlockInMask(Src);
1515 // The terminator has to be a branch inst!
1516 BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
1517 assert(BI && "Unexpected terminator found");
1519 if (BI->isConditional()) {
1520 VectorParts EdgeMask = getVectorValue(BI->getCondition());
1522 if (BI->getSuccessor(0) != Dst)
1523 for (unsigned part = 0; part < UF; ++part)
1524 EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
1526 for (unsigned part = 0; part < UF; ++part)
1527 EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
1534 InnerLoopVectorizer::VectorParts
1535 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
1536 assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
1538 // Loop incoming mask is all-one.
1539 if (OrigLoop->getHeader() == BB) {
1540 Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
1541 return getVectorValue(C);
1544 // This is the block mask. We OR all incoming edges, and with zero.
1545 Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
1546 VectorParts BlockMask = getVectorValue(Zero);
1549 for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
1550 VectorParts EM = createEdgeMask(*it, BB);
1551 for (unsigned part = 0; part < UF; ++part)
1552 BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
1559 InnerLoopVectorizer::vectorizeBlockInLoop(LoopVectorizationLegality *Legal,
1560 BasicBlock *BB, PhiVector *PV) {
1561 Constant *Zero = Builder.getInt32(0);
1563 // For each instruction in the old loop.
1564 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1565 VectorParts &Entry = WidenMap.get(it);
1566 switch (it->getOpcode()) {
1567 case Instruction::Br:
1568 // Nothing to do for PHIs and BR, since we already took care of the
1569 // loop control flow instructions.
1571 case Instruction::PHI:{
1572 PHINode* P = cast<PHINode>(it);
1573 // Handle reduction variables:
1574 if (Legal->getReductionVars()->count(P)) {
1575 for (unsigned part = 0; part < UF; ++part) {
1576 // This is phase one of vectorizing PHIs.
1577 Type *VecTy = VectorType::get(it->getType(), VF);
1578 Entry[part] = PHINode::Create(VecTy, 2, "vec.phi",
1579 LoopVectorBody-> getFirstInsertionPt());
1585 // Check for PHI nodes that are lowered to vector selects.
1586 if (P->getParent() != OrigLoop->getHeader()) {
1587 // We know that all PHIs in non header blocks are converted into
1588 // selects, so we don't have to worry about the insertion order and we
1589 // can just use the builder.
1591 // At this point we generate the predication tree. There may be
1592 // duplications since this is a simple recursive scan, but future
1593 // optimizations will clean it up.
1594 VectorParts Cond = createEdgeMask(P->getIncomingBlock(0),
1597 for (unsigned part = 0; part < UF; ++part) {
1598 VectorParts &In0 = getVectorValue(P->getIncomingValue(0));
1599 VectorParts &In1 = getVectorValue(P->getIncomingValue(1));
1600 Entry[part] = Builder.CreateSelect(Cond[part], In0[part], In1[part],
1606 // This PHINode must be an induction variable.
1607 // Make sure that we know about it.
1608 assert(Legal->getInductionVars()->count(P) &&
1609 "Not an induction variable");
1611 LoopVectorizationLegality::InductionInfo II =
1612 Legal->getInductionVars()->lookup(P);
1615 case LoopVectorizationLegality::IK_NoInduction:
1616 llvm_unreachable("Unknown induction");
1617 case LoopVectorizationLegality::IK_IntInduction: {
1618 assert(P == OldInduction && "Unexpected PHI");
1619 Value *Broadcasted = getBroadcastInstrs(Induction);
1620 // After broadcasting the induction variable we need to make the
1621 // vector consecutive by adding 0, 1, 2 ...
1622 for (unsigned part = 0; part < UF; ++part)
1623 Entry[part] = getConsecutiveVector(Broadcasted, VF * part, false);
1626 case LoopVectorizationLegality::IK_ReverseIntInduction:
1627 case LoopVectorizationLegality::IK_PtrInduction:
1628 // Handle reverse integer and pointer inductions.
1629 Value *StartIdx = 0;
1630 // If we have a single integer induction variable then use it.
1631 // Otherwise, start counting at zero.
1633 LoopVectorizationLegality::InductionInfo OldII =
1634 Legal->getInductionVars()->lookup(OldInduction);
1635 StartIdx = OldII.StartValue;
1637 StartIdx = ConstantInt::get(Induction->getType(), 0);
1639 // This is the normalized GEP that starts counting at zero.
1640 Value *NormalizedIdx = Builder.CreateSub(Induction, StartIdx,
1643 // Handle the reverse integer induction variable case.
1644 if (LoopVectorizationLegality::IK_ReverseIntInduction == II.IK) {
1645 IntegerType *DstTy = cast<IntegerType>(II.StartValue->getType());
1646 Value *CNI = Builder.CreateSExtOrTrunc(NormalizedIdx, DstTy,
1648 Value *ReverseInd = Builder.CreateSub(II.StartValue, CNI,
1651 // This is a new value so do not hoist it out.
1652 Value *Broadcasted = getBroadcastInstrs(ReverseInd);
1653 // After broadcasting the induction variable we need to make the
1654 // vector consecutive by adding ... -3, -2, -1, 0.
1655 for (unsigned part = 0; part < UF; ++part)
1656 Entry[part] = getConsecutiveVector(Broadcasted, -VF * part, true);
1660 // Handle the pointer induction variable case.
1661 assert(P->getType()->isPointerTy() && "Unexpected type.");
1663 // This is the vector of results. Notice that we don't generate
1664 // vector geps because scalar geps result in better code.
1665 for (unsigned part = 0; part < UF; ++part) {
1666 Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
1667 for (unsigned int i = 0; i < VF; ++i) {
1668 Constant *Idx = ConstantInt::get(Induction->getType(),
1670 Value *GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx,
1672 Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
1674 VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
1675 Builder.getInt32(i),
1678 Entry[part] = VecVal;
1685 case Instruction::Add:
1686 case Instruction::FAdd:
1687 case Instruction::Sub:
1688 case Instruction::FSub:
1689 case Instruction::Mul:
1690 case Instruction::FMul:
1691 case Instruction::UDiv:
1692 case Instruction::SDiv:
1693 case Instruction::FDiv:
1694 case Instruction::URem:
1695 case Instruction::SRem:
1696 case Instruction::FRem:
1697 case Instruction::Shl:
1698 case Instruction::LShr:
1699 case Instruction::AShr:
1700 case Instruction::And:
1701 case Instruction::Or:
1702 case Instruction::Xor: {
1703 // Just widen binops.
1704 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
1705 VectorParts &A = getVectorValue(it->getOperand(0));
1706 VectorParts &B = getVectorValue(it->getOperand(1));
1708 // Use this vector value for all users of the original instruction.
1709 for (unsigned Part = 0; Part < UF; ++Part) {
1710 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
1712 // Update the NSW, NUW and Exact flags. Notice: V can be an Undef.
1713 BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V);
1714 if (VecOp && isa<OverflowingBinaryOperator>(BinOp)) {
1715 VecOp->setHasNoSignedWrap(BinOp->hasNoSignedWrap());
1716 VecOp->setHasNoUnsignedWrap(BinOp->hasNoUnsignedWrap());
1718 if (VecOp && isa<PossiblyExactOperator>(VecOp))
1719 VecOp->setIsExact(BinOp->isExact());
1725 case Instruction::Select: {
1727 // If the selector is loop invariant we can create a select
1728 // instruction with a scalar condition. Otherwise, use vector-select.
1729 bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)),
1732 // The condition can be loop invariant but still defined inside the
1733 // loop. This means that we can't just use the original 'cond' value.
1734 // We have to take the 'vectorized' value and pick the first lane.
1735 // Instcombine will make this a no-op.
1736 VectorParts &Cond = getVectorValue(it->getOperand(0));
1737 VectorParts &Op0 = getVectorValue(it->getOperand(1));
1738 VectorParts &Op1 = getVectorValue(it->getOperand(2));
1739 Value *ScalarCond = Builder.CreateExtractElement(Cond[0],
1740 Builder.getInt32(0));
1741 for (unsigned Part = 0; Part < UF; ++Part) {
1742 Entry[Part] = Builder.CreateSelect(
1743 InvariantCond ? ScalarCond : Cond[Part],
1750 case Instruction::ICmp:
1751 case Instruction::FCmp: {
1752 // Widen compares. Generate vector compares.
1753 bool FCmp = (it->getOpcode() == Instruction::FCmp);
1754 CmpInst *Cmp = dyn_cast<CmpInst>(it);
1755 VectorParts &A = getVectorValue(it->getOperand(0));
1756 VectorParts &B = getVectorValue(it->getOperand(1));
1757 for (unsigned Part = 0; Part < UF; ++Part) {
1760 C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
1762 C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
1768 case Instruction::Store: {
1769 // Attempt to issue a wide store.
1770 StoreInst *SI = dyn_cast<StoreInst>(it);
1771 Type *StTy = VectorType::get(SI->getValueOperand()->getType(), VF);
1772 Value *Ptr = SI->getPointerOperand();
1773 unsigned Alignment = SI->getAlignment();
1775 assert(!Legal->isUniform(Ptr) &&
1776 "We do not allow storing to uniform addresses");
1779 int Stride = Legal->isConsecutivePtr(Ptr);
1780 bool Reverse = Stride < 0;
1782 scalarizeInstruction(it);
1786 // Handle consecutive stores.
1788 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1790 // The last index does not have to be the induction. It can be
1791 // consecutive and be a function of the index. For example A[I+1];
1792 unsigned NumOperands = Gep->getNumOperands();
1794 Value *LastGepOperand = Gep->getOperand(NumOperands - 1);
1795 VectorParts &GEPParts = getVectorValue(LastGepOperand);
1796 Value *LastIndex = GEPParts[0];
1797 LastIndex = Builder.CreateExtractElement(LastIndex, Zero);
1799 // Create the new GEP with the new induction variable.
1800 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1801 Gep2->setOperand(NumOperands - 1, LastIndex);
1802 Ptr = Builder.Insert(Gep2);
1804 // Use the induction element ptr.
1805 assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1806 VectorParts &PtrVal = getVectorValue(Ptr);
1807 Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
1810 VectorParts &StoredVal = getVectorValue(SI->getValueOperand());
1811 for (unsigned Part = 0; Part < UF; ++Part) {
1812 // Calculate the pointer for the specific unroll-part.
1813 Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1816 // If we store to reverse consecutive memory locations then we need
1817 // to reverse the order of elements in the stored value.
1818 StoredVal[Part] = reverseVector(StoredVal[Part]);
1819 // If the address is consecutive but reversed, then the
1820 // wide store needs to start at the last vector element.
1821 PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1822 PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1825 Value *VecPtr = Builder.CreateBitCast(PartPtr, StTy->getPointerTo());
1826 Builder.CreateStore(StoredVal[Part], VecPtr)->setAlignment(Alignment);
1830 case Instruction::Load: {
1831 // Attempt to issue a wide load.
1832 LoadInst *LI = dyn_cast<LoadInst>(it);
1833 Type *RetTy = VectorType::get(LI->getType(), VF);
1834 Value *Ptr = LI->getPointerOperand();
1835 unsigned Alignment = LI->getAlignment();
1837 // If the pointer is loop invariant or if it is non consecutive,
1838 // scalarize the load.
1839 int Stride = Legal->isConsecutivePtr(Ptr);
1840 bool Reverse = Stride < 0;
1841 if (Legal->isUniform(Ptr) || Stride == 0) {
1842 scalarizeInstruction(it);
1846 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1848 // The last index does not have to be the induction. It can be
1849 // consecutive and be a function of the index. For example A[I+1];
1850 unsigned NumOperands = Gep->getNumOperands();
1852 Value *LastGepOperand = Gep->getOperand(NumOperands - 1);
1853 VectorParts &GEPParts = getVectorValue(LastGepOperand);
1854 Value *LastIndex = GEPParts[0];
1855 LastIndex = Builder.CreateExtractElement(LastIndex, Zero);
1857 // Create the new GEP with the new induction variable.
1858 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1859 Gep2->setOperand(NumOperands - 1, LastIndex);
1860 Ptr = Builder.Insert(Gep2);
1862 // Use the induction element ptr.
1863 assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1864 VectorParts &PtrVal = getVectorValue(Ptr);
1865 Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
1868 for (unsigned Part = 0; Part < UF; ++Part) {
1869 // Calculate the pointer for the specific unroll-part.
1870 Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1873 // If the address is consecutive but reversed, then the
1874 // wide store needs to start at the last vector element.
1875 PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1876 PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1879 Value *VecPtr = Builder.CreateBitCast(PartPtr, RetTy->getPointerTo());
1880 Value *LI = Builder.CreateLoad(VecPtr, "wide.load");
1881 cast<LoadInst>(LI)->setAlignment(Alignment);
1882 Entry[Part] = Reverse ? reverseVector(LI) : LI;
1886 case Instruction::ZExt:
1887 case Instruction::SExt:
1888 case Instruction::FPToUI:
1889 case Instruction::FPToSI:
1890 case Instruction::FPExt:
1891 case Instruction::PtrToInt:
1892 case Instruction::IntToPtr:
1893 case Instruction::SIToFP:
1894 case Instruction::UIToFP:
1895 case Instruction::Trunc:
1896 case Instruction::FPTrunc:
1897 case Instruction::BitCast: {
1898 CastInst *CI = dyn_cast<CastInst>(it);
1899 /// Optimize the special case where the source is the induction
1900 /// variable. Notice that we can only optimize the 'trunc' case
1901 /// because: a. FP conversions lose precision, b. sext/zext may wrap,
1902 /// c. other casts depend on pointer size.
1903 if (CI->getOperand(0) == OldInduction &&
1904 it->getOpcode() == Instruction::Trunc) {
1905 Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
1907 Value *Broadcasted = getBroadcastInstrs(ScalarCast);
1908 for (unsigned Part = 0; Part < UF; ++Part)
1909 Entry[Part] = getConsecutiveVector(Broadcasted, VF * Part, false);
1912 /// Vectorize casts.
1913 Type *DestTy = VectorType::get(CI->getType()->getScalarType(), VF);
1915 VectorParts &A = getVectorValue(it->getOperand(0));
1916 for (unsigned Part = 0; Part < UF; ++Part)
1917 Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
1921 case Instruction::Call: {
1922 assert(isTriviallyVectorizableIntrinsic(it));
1923 Module *M = BB->getParent()->getParent();
1924 IntrinsicInst *II = cast<IntrinsicInst>(it);
1925 Intrinsic::ID ID = II->getIntrinsicID();
1926 for (unsigned Part = 0; Part < UF; ++Part) {
1927 SmallVector<Value*, 4> Args;
1928 for (unsigned i = 0, ie = II->getNumArgOperands(); i != ie; ++i) {
1929 VectorParts &Arg = getVectorValue(II->getArgOperand(i));
1930 Args.push_back(Arg[Part]);
1932 Type *Tys[] = { VectorType::get(II->getType()->getScalarType(), VF) };
1933 Function *F = Intrinsic::getDeclaration(M, ID, Tys);
1934 Entry[Part] = Builder.CreateCall(F, Args);
1940 // All other instructions are unsupported. Scalarize them.
1941 scalarizeInstruction(it);
1944 }// end of for_each instr.
1947 void InnerLoopVectorizer::updateAnalysis() {
1948 // Forget the original basic block.
1949 SE->forgetLoop(OrigLoop);
1951 // Update the dominator tree information.
1952 assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&
1953 "Entry does not dominate exit.");
1955 for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
1956 DT->addNewBlock(LoopBypassBlocks[I], LoopBypassBlocks[I-1]);
1957 DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlocks.back());
1958 DT->addNewBlock(LoopVectorBody, LoopVectorPreHeader);
1959 DT->addNewBlock(LoopMiddleBlock, LoopBypassBlocks.front());
1960 DT->addNewBlock(LoopScalarPreHeader, LoopMiddleBlock);
1961 DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
1962 DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
1964 DEBUG(DT->verifyAnalysis());
1967 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
1968 if (!EnableIfConversion)
1971 assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
1972 std::vector<BasicBlock*> &LoopBlocks = TheLoop->getBlocksVector();
1974 // Collect the blocks that need predication.
1975 for (unsigned i = 0, e = LoopBlocks.size(); i < e; ++i) {
1976 BasicBlock *BB = LoopBlocks[i];
1978 // We don't support switch statements inside loops.
1979 if (!isa<BranchInst>(BB->getTerminator()))
1982 // We must have at most two predecessors because we need to convert
1983 // all PHIs to selects.
1984 unsigned Preds = std::distance(pred_begin(BB), pred_end(BB));
1988 // We must be able to predicate all blocks that need to be predicated.
1989 if (blockNeedsPredication(BB) && !blockCanBePredicated(BB))
1993 // We can if-convert this loop.
1997 bool LoopVectorizationLegality::canVectorize() {
1998 assert(TheLoop->getLoopPreheader() && "No preheader!!");
2000 // We can only vectorize innermost loops.
2001 if (TheLoop->getSubLoopsVector().size())
2004 // We must have a single backedge.
2005 if (TheLoop->getNumBackEdges() != 1)
2008 // We must have a single exiting block.
2009 if (!TheLoop->getExitingBlock())
2012 unsigned NumBlocks = TheLoop->getNumBlocks();
2014 // Check if we can if-convert non single-bb loops.
2015 if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
2016 DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
2020 // We need to have a loop header.
2021 BasicBlock *Latch = TheLoop->getLoopLatch();
2022 DEBUG(dbgs() << "LV: Found a loop: " <<
2023 TheLoop->getHeader()->getName() << "\n");
2025 // ScalarEvolution needs to be able to find the exit count.
2026 const SCEV *ExitCount = SE->getExitCount(TheLoop, Latch);
2027 if (ExitCount == SE->getCouldNotCompute()) {
2028 DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
2032 // Do not loop-vectorize loops with a tiny trip count.
2033 unsigned TC = SE->getSmallConstantTripCount(TheLoop, Latch);
2034 if (TC > 0u && TC < TinyTripCountVectorThreshold) {
2035 DEBUG(dbgs() << "LV: Found a loop with a very small trip count. " <<
2036 "This loop is not worth vectorizing.\n");
2040 // Check if we can vectorize the instructions and CFG in this loop.
2041 if (!canVectorizeInstrs()) {
2042 DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
2046 // Go over each instruction and look at memory deps.
2047 if (!canVectorizeMemory()) {
2048 DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
2052 // Collect all of the variables that remain uniform after vectorization.
2053 collectLoopUniforms();
2055 DEBUG(dbgs() << "LV: We can vectorize this loop" <<
2056 (PtrRtCheck.Need ? " (with a runtime bound check)" : "")
2059 // Okay! We can vectorize. At this point we don't have any other mem analysis
2060 // which may limit our maximum vectorization factor, so just return true with
2065 bool LoopVectorizationLegality::canVectorizeInstrs() {
2066 BasicBlock *PreHeader = TheLoop->getLoopPreheader();
2067 BasicBlock *Header = TheLoop->getHeader();
2069 // For each block in the loop.
2070 for (Loop::block_iterator bb = TheLoop->block_begin(),
2071 be = TheLoop->block_end(); bb != be; ++bb) {
2073 // Scan the instructions in the block and look for hazards.
2074 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
2077 if (PHINode *Phi = dyn_cast<PHINode>(it)) {
2078 // This should not happen because the loop should be normalized.
2079 if (Phi->getNumIncomingValues() != 2) {
2080 DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
2084 // Check that this PHI type is allowed.
2085 if (!Phi->getType()->isIntegerTy() &&
2086 !Phi->getType()->isFloatingPointTy() &&
2087 !Phi->getType()->isPointerTy()) {
2088 DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
2092 // If this PHINode is not in the header block, then we know that we
2093 // can convert it to select during if-conversion. No need to check if
2094 // the PHIs in this block are induction or reduction variables.
2098 // This is the value coming from the preheader.
2099 Value *StartValue = Phi->getIncomingValueForBlock(PreHeader);
2100 // Check if this is an induction variable.
2101 InductionKind IK = isInductionVariable(Phi);
2103 if (IK_NoInduction != IK) {
2104 // Int inductions are special because we only allow one IV.
2105 if (IK == IK_IntInduction) {
2107 DEBUG(dbgs() << "LV: Found too many inductions."<< *Phi <<"\n");
2113 DEBUG(dbgs() << "LV: Found an induction variable.\n");
2114 Inductions[Phi] = InductionInfo(StartValue, IK);
2118 if (AddReductionVar(Phi, RK_IntegerAdd)) {
2119 DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
2122 if (AddReductionVar(Phi, RK_IntegerMult)) {
2123 DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n");
2126 if (AddReductionVar(Phi, RK_IntegerOr)) {
2127 DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n");
2130 if (AddReductionVar(Phi, RK_IntegerAnd)) {
2131 DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n");
2134 if (AddReductionVar(Phi, RK_IntegerXor)) {
2135 DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n");
2138 if (AddReductionVar(Phi, RK_FloatMult)) {
2139 DEBUG(dbgs() << "LV: Found an FMult reduction PHI."<< *Phi <<"\n");
2142 if (AddReductionVar(Phi, RK_FloatAdd)) {
2143 DEBUG(dbgs() << "LV: Found an FAdd reduction PHI."<< *Phi <<"\n");
2147 DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
2149 }// end of PHI handling
2151 // We still don't handle functions.
2152 CallInst *CI = dyn_cast<CallInst>(it);
2153 if (CI && !isTriviallyVectorizableIntrinsic(it)) {
2154 DEBUG(dbgs() << "LV: Found a call site.\n");
2158 // Check that the instruction return type is vectorizable.
2159 if (!VectorType::isValidElementType(it->getType()) &&
2160 !it->getType()->isVoidTy()) {
2161 DEBUG(dbgs() << "LV: Found unvectorizable type." << "\n");
2165 // Check that the stored type is vectorizable.
2166 if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
2167 Type *T = ST->getValueOperand()->getType();
2168 if (!VectorType::isValidElementType(T))
2172 // Reduction instructions are allowed to have exit users.
2173 // All other instructions must not have external users.
2174 if (!AllowedExit.count(it))
2175 //Check that all of the users of the loop are inside the BB.
2176 for (Value::use_iterator I = it->use_begin(), E = it->use_end();
2178 Instruction *U = cast<Instruction>(*I);
2179 // This user may be a reduction exit value.
2180 if (!TheLoop->contains(U)) {
2181 DEBUG(dbgs() << "LV: Found an outside user for : "<< *U << "\n");
2190 DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
2191 assert(getInductionVars()->size() && "No induction variables");
2197 void LoopVectorizationLegality::collectLoopUniforms() {
2198 // We now know that the loop is vectorizable!
2199 // Collect variables that will remain uniform after vectorization.
2200 std::vector<Value*> Worklist;
2201 BasicBlock *Latch = TheLoop->getLoopLatch();
2203 // Start with the conditional branch and walk up the block.
2204 Worklist.push_back(Latch->getTerminator()->getOperand(0));
2206 while (Worklist.size()) {
2207 Instruction *I = dyn_cast<Instruction>(Worklist.back());
2208 Worklist.pop_back();
2210 // Look at instructions inside this loop.
2211 // Stop when reaching PHI nodes.
2212 // TODO: we need to follow values all over the loop, not only in this block.
2213 if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
2216 // This is a known uniform.
2219 // Insert all operands.
2220 for (int i = 0, Op = I->getNumOperands(); i < Op; ++i) {
2221 Worklist.push_back(I->getOperand(i));
2226 bool LoopVectorizationLegality::canVectorizeMemory() {
2227 typedef SmallVector<Value*, 16> ValueVector;
2228 typedef SmallPtrSet<Value*, 16> ValueSet;
2229 // Holds the Load and Store *instructions*.
2232 PtrRtCheck.Pointers.clear();
2233 PtrRtCheck.Need = false;
2236 for (Loop::block_iterator bb = TheLoop->block_begin(),
2237 be = TheLoop->block_end(); bb != be; ++bb) {
2239 // Scan the BB and collect legal loads and stores.
2240 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
2243 // If this is a load, save it. If this instruction can read from memory
2244 // but is not a load, then we quit. Notice that we don't handle function
2245 // calls that read or write.
2246 if (it->mayReadFromMemory()) {
2247 LoadInst *Ld = dyn_cast<LoadInst>(it);
2248 if (!Ld) return false;
2249 if (!Ld->isSimple()) {
2250 DEBUG(dbgs() << "LV: Found a non-simple load.\n");
2253 Loads.push_back(Ld);
2257 // Save 'store' instructions. Abort if other instructions write to memory.
2258 if (it->mayWriteToMemory()) {
2259 StoreInst *St = dyn_cast<StoreInst>(it);
2260 if (!St) return false;
2261 if (!St->isSimple()) {
2262 DEBUG(dbgs() << "LV: Found a non-simple store.\n");
2265 Stores.push_back(St);
2270 // Now we have two lists that hold the loads and the stores.
2271 // Next, we find the pointers that they use.
2273 // Check if we see any stores. If there are no stores, then we don't
2274 // care if the pointers are *restrict*.
2275 if (!Stores.size()) {
2276 DEBUG(dbgs() << "LV: Found a read-only loop!\n");
2280 // Holds the read and read-write *pointers* that we find.
2282 ValueVector ReadWrites;
2284 // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
2285 // multiple times on the same object. If the ptr is accessed twice, once
2286 // for read and once for write, it will only appear once (on the write
2287 // list). This is okay, since we are going to check for conflicts between
2288 // writes and between reads and writes, but not between reads and reads.
2291 ValueVector::iterator I, IE;
2292 for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
2293 StoreInst *ST = cast<StoreInst>(*I);
2294 Value* Ptr = ST->getPointerOperand();
2296 if (isUniform(Ptr)) {
2297 DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
2301 // If we did *not* see this pointer before, insert it to
2302 // the read-write list. At this phase it is only a 'write' list.
2303 if (Seen.insert(Ptr))
2304 ReadWrites.push_back(Ptr);
2307 for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
2308 LoadInst *LD = cast<LoadInst>(*I);
2309 Value* Ptr = LD->getPointerOperand();
2310 // If we did *not* see this pointer before, insert it to the
2311 // read list. If we *did* see it before, then it is already in
2312 // the read-write list. This allows us to vectorize expressions
2313 // such as A[i] += x; Because the address of A[i] is a read-write
2314 // pointer. This only works if the index of A[i] is consecutive.
2315 // If the address of i is unknown (for example A[B[i]]) then we may
2316 // read a few words, modify, and write a few words, and some of the
2317 // words may be written to the same address.
2318 if (Seen.insert(Ptr) || 0 == isConsecutivePtr(Ptr))
2319 Reads.push_back(Ptr);
2322 // If we write (or read-write) to a single destination and there are no
2323 // other reads in this loop then is it safe to vectorize.
2324 if (ReadWrites.size() == 1 && Reads.size() == 0) {
2325 DEBUG(dbgs() << "LV: Found a write-only loop!\n");
2329 // Find pointers with computable bounds. We are going to use this information
2330 // to place a runtime bound check.
2331 bool CanDoRT = true;
2332 for (I = ReadWrites.begin(), IE = ReadWrites.end(); I != IE; ++I)
2333 if (hasComputableBounds(*I)) {
2334 PtrRtCheck.insert(SE, TheLoop, *I);
2335 DEBUG(dbgs() << "LV: Found a runtime check ptr:" << **I <<"\n");
2340 for (I = Reads.begin(), IE = Reads.end(); I != IE; ++I)
2341 if (hasComputableBounds(*I)) {
2342 PtrRtCheck.insert(SE, TheLoop, *I);
2343 DEBUG(dbgs() << "LV: Found a runtime check ptr:" << **I <<"\n");
2349 // Check that we did not collect too many pointers or found a
2350 // unsizeable pointer.
2351 if (!CanDoRT || PtrRtCheck.Pointers.size() > RuntimeMemoryCheckThreshold) {
2357 DEBUG(dbgs() << "LV: We can perform a memory runtime check if needed.\n");
2360 bool NeedRTCheck = false;
2362 // Now that the pointers are in two lists (Reads and ReadWrites), we
2363 // can check that there are no conflicts between each of the writes and
2364 // between the writes to the reads.
2365 ValueSet WriteObjects;
2366 ValueVector TempObjects;
2368 // Check that the read-writes do not conflict with other read-write
2370 bool AllWritesIdentified = true;
2371 for (I = ReadWrites.begin(), IE = ReadWrites.end(); I != IE; ++I) {
2372 GetUnderlyingObjects(*I, TempObjects, DL);
2373 for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end();
2375 if (!isIdentifiedObject(*it)) {
2376 DEBUG(dbgs() << "LV: Found an unidentified write ptr:"<< **it <<"\n");
2378 AllWritesIdentified = false;
2380 if (!WriteObjects.insert(*it)) {
2381 DEBUG(dbgs() << "LV: Found a possible write-write reorder:"
2386 TempObjects.clear();
2389 /// Check that the reads don't conflict with the read-writes.
2390 for (I = Reads.begin(), IE = Reads.end(); I != IE; ++I) {
2391 GetUnderlyingObjects(*I, TempObjects, DL);
2392 for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end();
2394 // If all of the writes are identified then we don't care if the read
2395 // pointer is identified or not.
2396 if (!AllWritesIdentified && !isIdentifiedObject(*it)) {
2397 DEBUG(dbgs() << "LV: Found an unidentified read ptr:"<< **it <<"\n");
2400 if (WriteObjects.count(*it)) {
2401 DEBUG(dbgs() << "LV: Found a possible read/write reorder:"
2406 TempObjects.clear();
2409 PtrRtCheck.Need = NeedRTCheck;
2410 if (NeedRTCheck && !CanDoRT) {
2411 DEBUG(dbgs() << "LV: We can't vectorize because we can't find " <<
2412 "the array bounds.\n");
2417 DEBUG(dbgs() << "LV: We "<< (NeedRTCheck ? "" : "don't") <<
2418 " need a runtime memory check.\n");
2422 bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi,
2423 ReductionKind Kind) {
2424 if (Phi->getNumIncomingValues() != 2)
2427 // Reduction variables are only found in the loop header block.
2428 if (Phi->getParent() != TheLoop->getHeader())
2431 // Obtain the reduction start value from the value that comes from the loop
2433 Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
2435 // ExitInstruction is the single value which is used outside the loop.
2436 // We only allow for a single reduction value to be used outside the loop.
2437 // This includes users of the reduction, variables (which form a cycle
2438 // which ends in the phi node).
2439 Instruction *ExitInstruction = 0;
2440 // Indicates that we found a binary operation in our scan.
2441 bool FoundBinOp = false;
2443 // Iter is our iterator. We start with the PHI node and scan for all of the
2444 // users of this instruction. All users must be instructions that can be
2445 // used as reduction variables (such as ADD). We may have a single
2446 // out-of-block user. The cycle must end with the original PHI.
2447 Instruction *Iter = Phi;
2449 // If the instruction has no users then this is a broken
2450 // chain and can't be a reduction variable.
2451 if (Iter->use_empty())
2454 // Did we find a user inside this loop already ?
2455 bool FoundInBlockUser = false;
2456 // Did we reach the initial PHI node already ?
2457 bool FoundStartPHI = false;
2459 // Is this a bin op ?
2460 FoundBinOp |= !isa<PHINode>(Iter);
2462 // For each of the *users* of iter.
2463 for (Value::use_iterator it = Iter->use_begin(), e = Iter->use_end();
2465 Instruction *U = cast<Instruction>(*it);
2466 // We already know that the PHI is a user.
2468 FoundStartPHI = true;
2472 // Check if we found the exit user.
2473 BasicBlock *Parent = U->getParent();
2474 if (!TheLoop->contains(Parent)) {
2475 // Exit if you find multiple outside users.
2476 if (ExitInstruction != 0)
2478 ExitInstruction = Iter;
2481 // We allow in-loop PHINodes which are not the original reduction PHI
2482 // node. If this PHI is the only user of Iter (happens in IF w/ no ELSE
2483 // structure) then don't skip this PHI.
2484 if (isa<PHINode>(Iter) && isa<PHINode>(U) &&
2485 U->getParent() != TheLoop->getHeader() &&
2486 TheLoop->contains(U) &&
2487 Iter->getNumUses() > 1)
2490 // We can't have multiple inside users.
2491 if (FoundInBlockUser)
2493 FoundInBlockUser = true;
2495 // Any reduction instr must be of one of the allowed kinds.
2496 if (!isReductionInstr(U, Kind))
2499 // Reductions of instructions such as Div, and Sub is only
2500 // possible if the LHS is the reduction variable.
2501 if (!U->isCommutative() && !isa<PHINode>(U) && U->getOperand(0) != Iter)
2507 // We found a reduction var if we have reached the original
2508 // phi node and we only have a single instruction with out-of-loop
2510 if (FoundStartPHI) {
2511 // This instruction is allowed to have out-of-loop users.
2512 AllowedExit.insert(ExitInstruction);
2514 // Save the description of this reduction variable.
2515 ReductionDescriptor RD(RdxStart, ExitInstruction, Kind);
2516 Reductions[Phi] = RD;
2517 // We've ended the cycle. This is a reduction variable if we have an
2518 // outside user and it has a binary op.
2519 return FoundBinOp && ExitInstruction;
2525 LoopVectorizationLegality::isReductionInstr(Instruction *I,
2526 ReductionKind Kind) {
2527 bool FP = I->getType()->isFloatingPointTy();
2528 bool FastMath = (FP && I->isCommutative() && I->isAssociative());
2530 switch (I->getOpcode()) {
2533 case Instruction::PHI:
2534 if (FP && (Kind != RK_FloatMult && Kind != RK_FloatAdd))
2538 case Instruction::Sub:
2539 case Instruction::Add:
2540 return Kind == RK_IntegerAdd;
2541 case Instruction::SDiv:
2542 case Instruction::UDiv:
2543 case Instruction::Mul:
2544 return Kind == RK_IntegerMult;
2545 case Instruction::And:
2546 return Kind == RK_IntegerAnd;
2547 case Instruction::Or:
2548 return Kind == RK_IntegerOr;
2549 case Instruction::Xor:
2550 return Kind == RK_IntegerXor;
2551 case Instruction::FMul:
2552 return Kind == RK_FloatMult && FastMath;
2553 case Instruction::FAdd:
2554 return Kind == RK_FloatAdd && FastMath;
2558 LoopVectorizationLegality::InductionKind
2559 LoopVectorizationLegality::isInductionVariable(PHINode *Phi) {
2560 Type *PhiTy = Phi->getType();
2561 // We only handle integer and pointer inductions variables.
2562 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
2563 return IK_NoInduction;
2565 // Check that the PHI is consecutive and starts at zero.
2566 const SCEV *PhiScev = SE->getSCEV(Phi);
2567 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
2569 DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
2570 return IK_NoInduction;
2572 const SCEV *Step = AR->getStepRecurrence(*SE);
2574 // Integer inductions need to have a stride of one.
2575 if (PhiTy->isIntegerTy()) {
2577 return IK_IntInduction;
2578 if (Step->isAllOnesValue())
2579 return IK_ReverseIntInduction;
2580 return IK_NoInduction;
2583 // Calculate the pointer stride and check if it is consecutive.
2584 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
2586 return IK_NoInduction;
2588 assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
2589 uint64_t Size = DL->getTypeAllocSize(PhiTy->getPointerElementType());
2590 if (C->getValue()->equalsInt(Size))
2591 return IK_PtrInduction;
2593 return IK_NoInduction;
2596 bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
2597 Value *In0 = const_cast<Value*>(V);
2598 PHINode *PN = dyn_cast_or_null<PHINode>(In0);
2602 return Inductions.count(PN);
2605 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) {
2606 assert(TheLoop->contains(BB) && "Unknown block used");
2608 // Blocks that do not dominate the latch need predication.
2609 BasicBlock* Latch = TheLoop->getLoopLatch();
2610 return !DT->dominates(BB, Latch);
2613 bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB) {
2614 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2615 // We don't predicate loads/stores at the moment.
2616 if (it->mayReadFromMemory() || it->mayWriteToMemory() || it->mayThrow())
2619 // The instructions below can trap.
2620 switch (it->getOpcode()) {
2622 case Instruction::UDiv:
2623 case Instruction::SDiv:
2624 case Instruction::URem:
2625 case Instruction::SRem:
2633 bool LoopVectorizationLegality::hasComputableBounds(Value *Ptr) {
2634 const SCEV *PhiScev = SE->getSCEV(Ptr);
2635 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
2639 return AR->isAffine();
2642 std::pair<unsigned, unsigned>
2643 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize,
2645 if (OptForSize && Legal->getRuntimePointerCheck()->Need) {
2646 DEBUG(dbgs() << "LV: Aborting. Runtime ptr check is required in Os.\n");
2647 return std::make_pair(1U, 0U);
2650 // Find the trip count.
2651 unsigned TC = SE->getSmallConstantTripCount(TheLoop, TheLoop->getLoopLatch());
2652 DEBUG(dbgs() << "LV: Found trip count:"<<TC<<"\n");
2654 unsigned WidestType = getWidestType();
2655 unsigned WidestRegister = TTI.getRegisterBitWidth(true);
2656 unsigned MaxVectorSize = WidestRegister / WidestType;
2657 DEBUG(dbgs() << "LV: The Widest type: " << WidestType << " bits.\n");
2658 DEBUG(dbgs() << "LV: The Widest register is:" << WidestRegister << "bits.\n");
2660 if (MaxVectorSize == 0) {
2661 DEBUG(dbgs() << "LV: The target has no vector registers.\n");
2665 assert(MaxVectorSize <= 32 && "Did not expect to pack so many elements"
2666 " into one vector!");
2668 unsigned VF = MaxVectorSize;
2670 // If we optimize the program for size, avoid creating the tail loop.
2672 // If we are unable to calculate the trip count then don't try to vectorize.
2674 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
2675 return std::make_pair(1U, 0U);
2678 // Find the maximum SIMD width that can fit within the trip count.
2679 VF = TC % MaxVectorSize;
2684 // If the trip count that we found modulo the vectorization factor is not
2685 // zero then we require a tail.
2687 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
2688 return std::make_pair(1U, 0U);
2693 assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
2694 DEBUG(dbgs() << "LV: Using user VF "<<UserVF<<".\n");
2696 return std::make_pair(UserVF, 0U);
2699 float Cost = expectedCost(1);
2701 DEBUG(dbgs() << "LV: Scalar loop costs: "<< (int)Cost << ".\n");
2702 for (unsigned i=2; i <= VF; i*=2) {
2703 // Notice that the vector loop needs to be executed less times, so
2704 // we need to divide the cost of the vector loops by the width of
2705 // the vector elements.
2706 float VectorCost = expectedCost(i) / (float)i;
2707 DEBUG(dbgs() << "LV: Vector loop of width "<< i << " costs: " <<
2708 (int)VectorCost << ".\n");
2709 if (VectorCost < Cost) {
2715 DEBUG(dbgs() << "LV: Selecting VF = : "<< Width << ".\n");
2716 unsigned LoopCost = VF * Cost;
2717 return std::make_pair(Width, LoopCost);
2720 unsigned LoopVectorizationCostModel::getWidestType() {
2721 unsigned MaxWidth = 8;
2724 for (Loop::block_iterator bb = TheLoop->block_begin(),
2725 be = TheLoop->block_end(); bb != be; ++bb) {
2726 BasicBlock *BB = *bb;
2728 // For each instruction in the loop.
2729 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2730 Type *T = it->getType();
2732 // Only examine Loads, Stores and PHINodes.
2733 if (!isa<LoadInst>(it) && !isa<StoreInst>(it) && !isa<PHINode>(it))
2736 // Examine PHI nodes that are reduction variables.
2737 if (PHINode *PN = dyn_cast<PHINode>(it))
2738 if (!Legal->getReductionVars()->count(PN))
2741 // Examine the stored values.
2742 if (StoreInst *ST = dyn_cast<StoreInst>(it))
2743 T = ST->getValueOperand()->getType();
2745 // Ignore stored/loaded pointer types.
2746 if (T->isPointerTy())
2749 MaxWidth = std::max(MaxWidth, T->getScalarSizeInBits());
2757 LoopVectorizationCostModel::selectUnrollFactor(bool OptForSize,
2760 unsigned LoopCost) {
2762 // -- The unroll heuristics --
2763 // We unroll the loop in order to expose ILP and reduce the loop overhead.
2764 // There are many micro-architectural considerations that we can't predict
2765 // at this level. For example frontend pressure (on decode or fetch) due to
2766 // code size, or the number and capabilities of the execution ports.
2768 // We use the following heuristics to select the unroll factor:
2769 // 1. If the code has reductions the we unroll in order to break the cross
2770 // iteration dependency.
2771 // 2. If the loop is really small then we unroll in order to reduce the loop
2773 // 3. We don't unroll if we think that we will spill registers to memory due
2774 // to the increased register pressure.
2776 // Use the user preference, unless 'auto' is selected.
2780 // When we optimize for size we don't unroll.
2784 // Do not unroll loops with a relatively small trip count.
2785 unsigned TC = SE->getSmallConstantTripCount(TheLoop,
2786 TheLoop->getLoopLatch());
2787 if (TC > 1 && TC < TinyTripCountUnrollThreshold)
2790 unsigned TargetVectorRegisters = TTI.getNumberOfRegisters(true);
2791 DEBUG(dbgs() << "LV: The target has " << TargetVectorRegisters <<
2792 " vector registers\n");
2794 LoopVectorizationCostModel::RegisterUsage R = calculateRegisterUsage();
2795 // We divide by these constants so assume that we have at least one
2796 // instruction that uses at least one register.
2797 R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
2798 R.NumInstructions = std::max(R.NumInstructions, 1U);
2800 // We calculate the unroll factor using the following formula.
2801 // Subtract the number of loop invariants from the number of available
2802 // registers. These registers are used by all of the unrolled instances.
2803 // Next, divide the remaining registers by the number of registers that is
2804 // required by the loop, in order to estimate how many parallel instances
2805 // fit without causing spills.
2806 unsigned UF = (TargetVectorRegisters - R.LoopInvariantRegs) / R.MaxLocalUsers;
2808 // Clamp the unroll factor ranges to reasonable factors.
2809 unsigned MaxUnrollSize = TTI.getMaximumUnrollFactor();
2811 // If we did not calculate the cost for VF (because the user selected the VF)
2812 // then we calculate the cost of VF here.
2814 LoopCost = expectedCost(VF);
2816 // Clamp the calculated UF to be between the 1 and the max unroll factor
2817 // that the target allows.
2818 if (UF > MaxUnrollSize)
2823 if (Legal->getReductionVars()->size()) {
2824 DEBUG(dbgs() << "LV: Unrolling because of reductions. \n");
2828 // We want to unroll tiny loops in order to reduce the loop overhead.
2829 // We assume that the cost overhead is 1 and we use the cost model
2830 // to estimate the cost of the loop and unroll until the cost of the
2831 // loop overhead is about 5% of the cost of the loop.
2832 DEBUG(dbgs() << "LV: Loop cost is "<< LoopCost <<" \n");
2833 if (LoopCost < 20) {
2834 DEBUG(dbgs() << "LV: Unrolling to reduce branch cost. \n");
2835 unsigned NewUF = 20/LoopCost + 1;
2836 return std::min(NewUF, UF);
2839 DEBUG(dbgs() << "LV: Not Unrolling. \n");
2843 LoopVectorizationCostModel::RegisterUsage
2844 LoopVectorizationCostModel::calculateRegisterUsage() {
2845 // This function calculates the register usage by measuring the highest number
2846 // of values that are alive at a single location. Obviously, this is a very
2847 // rough estimation. We scan the loop in a topological order in order and
2848 // assign a number to each instruction. We use RPO to ensure that defs are
2849 // met before their users. We assume that each instruction that has in-loop
2850 // users starts an interval. We record every time that an in-loop value is
2851 // used, so we have a list of the first and last occurrences of each
2852 // instruction. Next, we transpose this data structure into a multi map that
2853 // holds the list of intervals that *end* at a specific location. This multi
2854 // map allows us to perform a linear search. We scan the instructions linearly
2855 // and record each time that a new interval starts, by placing it in a set.
2856 // If we find this value in the multi-map then we remove it from the set.
2857 // The max register usage is the maximum size of the set.
2858 // We also search for instructions that are defined outside the loop, but are
2859 // used inside the loop. We need this number separately from the max-interval
2860 // usage number because when we unroll, loop-invariant values do not take
2862 LoopBlocksDFS DFS(TheLoop);
2866 R.NumInstructions = 0;
2868 // Each 'key' in the map opens a new interval. The values
2869 // of the map are the index of the 'last seen' usage of the
2870 // instruction that is the key.
2871 typedef DenseMap<Instruction*, unsigned> IntervalMap;
2872 // Maps instruction to its index.
2873 DenseMap<unsigned, Instruction*> IdxToInstr;
2874 // Marks the end of each interval.
2875 IntervalMap EndPoint;
2876 // Saves the list of instruction indices that are used in the loop.
2877 SmallSet<Instruction*, 8> Ends;
2878 // Saves the list of values that are used in the loop but are
2879 // defined outside the loop, such as arguments and constants.
2880 SmallPtrSet<Value*, 8> LoopInvariants;
2883 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
2884 be = DFS.endRPO(); bb != be; ++bb) {
2885 R.NumInstructions += (*bb)->size();
2886 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
2888 Instruction *I = it;
2889 IdxToInstr[Index++] = I;
2891 // Save the end location of each USE.
2892 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
2893 Value *U = I->getOperand(i);
2894 Instruction *Instr = dyn_cast<Instruction>(U);
2896 // Ignore non-instruction values such as arguments, constants, etc.
2897 if (!Instr) continue;
2899 // If this instruction is outside the loop then record it and continue.
2900 if (!TheLoop->contains(Instr)) {
2901 LoopInvariants.insert(Instr);
2905 // Overwrite previous end points.
2906 EndPoint[Instr] = Index;
2912 // Saves the list of intervals that end with the index in 'key'.
2913 typedef SmallVector<Instruction*, 2> InstrList;
2914 DenseMap<unsigned, InstrList> TransposeEnds;
2916 // Transpose the EndPoints to a list of values that end at each index.
2917 for (IntervalMap::iterator it = EndPoint.begin(), e = EndPoint.end();
2919 TransposeEnds[it->second].push_back(it->first);
2921 SmallSet<Instruction*, 8> OpenIntervals;
2922 unsigned MaxUsage = 0;
2925 DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
2926 for (unsigned int i = 0; i < Index; ++i) {
2927 Instruction *I = IdxToInstr[i];
2928 // Ignore instructions that are never used within the loop.
2929 if (!Ends.count(I)) continue;
2931 // Remove all of the instructions that end at this location.
2932 InstrList &List = TransposeEnds[i];
2933 for (unsigned int j=0, e = List.size(); j < e; ++j)
2934 OpenIntervals.erase(List[j]);
2936 // Count the number of live interals.
2937 MaxUsage = std::max(MaxUsage, OpenIntervals.size());
2939 DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # " <<
2940 OpenIntervals.size() <<"\n");
2942 // Add the current instruction to the list of open intervals.
2943 OpenIntervals.insert(I);
2946 unsigned Invariant = LoopInvariants.size();
2947 DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsage << " \n");
2948 DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << " \n");
2949 DEBUG(dbgs() << "LV(REG): LoopSize: " << R.NumInstructions << " \n");
2951 R.LoopInvariantRegs = Invariant;
2952 R.MaxLocalUsers = MaxUsage;
2956 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
2960 for (Loop::block_iterator bb = TheLoop->block_begin(),
2961 be = TheLoop->block_end(); bb != be; ++bb) {
2962 unsigned BlockCost = 0;
2963 BasicBlock *BB = *bb;
2965 // For each instruction in the old loop.
2966 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2967 unsigned C = getInstructionCost(it, VF);
2969 DEBUG(dbgs() << "LV: Found an estimated cost of "<< C <<" for VF " <<
2970 VF << " For instruction: "<< *it << "\n");
2973 // We assume that if-converted blocks have a 50% chance of being executed.
2974 // When the code is scalar then some of the blocks are avoided due to CF.
2975 // When the code is vectorized we execute all code paths.
2976 if (Legal->blockNeedsPredication(*bb) && VF == 1)
2986 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
2987 // If we know that this instruction will remain uniform, check the cost of
2988 // the scalar version.
2989 if (Legal->isUniformAfterVectorization(I))
2992 Type *RetTy = I->getType();
2993 Type *VectorTy = ToVectorTy(RetTy, VF);
2995 // TODO: We need to estimate the cost of intrinsic calls.
2996 switch (I->getOpcode()) {
2997 case Instruction::GetElementPtr:
2998 // We mark this instruction as zero-cost because scalar GEPs are usually
2999 // lowered to the intruction addressing mode. At the moment we don't
3000 // generate vector geps.
3002 case Instruction::Br: {
3003 return TTI.getCFInstrCost(I->getOpcode());
3005 case Instruction::PHI:
3006 //TODO: IF-converted IFs become selects.
3008 case Instruction::Add:
3009 case Instruction::FAdd:
3010 case Instruction::Sub:
3011 case Instruction::FSub:
3012 case Instruction::Mul:
3013 case Instruction::FMul:
3014 case Instruction::UDiv:
3015 case Instruction::SDiv:
3016 case Instruction::FDiv:
3017 case Instruction::URem:
3018 case Instruction::SRem:
3019 case Instruction::FRem:
3020 case Instruction::Shl:
3021 case Instruction::LShr:
3022 case Instruction::AShr:
3023 case Instruction::And:
3024 case Instruction::Or:
3025 case Instruction::Xor:
3026 return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy);
3027 case Instruction::Select: {
3028 SelectInst *SI = cast<SelectInst>(I);
3029 const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
3030 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
3031 Type *CondTy = SI->getCondition()->getType();
3033 CondTy = VectorType::get(CondTy, VF);
3035 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
3037 case Instruction::ICmp:
3038 case Instruction::FCmp: {
3039 Type *ValTy = I->getOperand(0)->getType();
3040 VectorTy = ToVectorTy(ValTy, VF);
3041 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy);
3043 case Instruction::Store: {
3044 StoreInst *SI = cast<StoreInst>(I);
3045 Type *ValTy = SI->getValueOperand()->getType();
3046 VectorTy = ToVectorTy(ValTy, VF);
3049 return TTI.getMemoryOpCost(I->getOpcode(), VectorTy,
3051 SI->getPointerAddressSpace());
3053 // Scalarized stores.
3054 int Stride = Legal->isConsecutivePtr(SI->getPointerOperand());
3055 bool Reverse = Stride < 0;
3059 // The cost of extracting from the value vector and pointer vector.
3060 Type *PtrTy = ToVectorTy(I->getOperand(0)->getType(), VF);
3061 for (unsigned i = 0; i < VF; ++i) {
3062 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, VectorTy,
3064 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
3067 // The cost of the scalar stores.
3068 Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(),
3070 SI->getPointerAddressSpace());
3075 unsigned Cost = TTI.getMemoryOpCost(I->getOpcode(), VectorTy,
3077 SI->getPointerAddressSpace());
3079 Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
3083 case Instruction::Load: {
3084 LoadInst *LI = cast<LoadInst>(I);
3087 return TTI.getMemoryOpCost(I->getOpcode(), VectorTy, LI->getAlignment(),
3088 LI->getPointerAddressSpace());
3090 // Scalarized loads.
3091 int Stride = Legal->isConsecutivePtr(LI->getPointerOperand());
3092 bool Reverse = Stride < 0;
3095 Type *PtrTy = ToVectorTy(I->getOperand(0)->getType(), VF);
3097 // The cost of extracting from the pointer vector.
3098 for (unsigned i = 0; i < VF; ++i)
3099 Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
3101 // The cost of inserting data to the result vector.
3102 for (unsigned i = 0; i < VF; ++i)
3103 Cost += TTI.getVectorInstrCost(Instruction::InsertElement, VectorTy, i);
3105 // The cost of the scalar stores.
3106 Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), RetTy->getScalarType(),
3108 LI->getPointerAddressSpace());
3113 unsigned Cost = TTI.getMemoryOpCost(I->getOpcode(), VectorTy,
3115 LI->getPointerAddressSpace());
3117 Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, 0);
3120 case Instruction::ZExt:
3121 case Instruction::SExt:
3122 case Instruction::FPToUI:
3123 case Instruction::FPToSI:
3124 case Instruction::FPExt:
3125 case Instruction::PtrToInt:
3126 case Instruction::IntToPtr:
3127 case Instruction::SIToFP:
3128 case Instruction::UIToFP:
3129 case Instruction::Trunc:
3130 case Instruction::FPTrunc:
3131 case Instruction::BitCast: {
3132 // We optimize the truncation of induction variable.
3133 // The cost of these is the same as the scalar operation.
3134 if (I->getOpcode() == Instruction::Trunc &&
3135 Legal->isInductionVariable(I->getOperand(0)))
3136 return TTI.getCastInstrCost(I->getOpcode(), I->getType(),
3137 I->getOperand(0)->getType());
3139 Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
3140 return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
3142 case Instruction::Call: {
3143 assert(isTriviallyVectorizableIntrinsic(I));
3144 IntrinsicInst *II = cast<IntrinsicInst>(I);
3145 Type *RetTy = ToVectorTy(II->getType(), VF);
3146 SmallVector<Type*, 4> Tys;
3147 for (unsigned i = 0, ie = II->getNumArgOperands(); i != ie; ++i)
3148 Tys.push_back(ToVectorTy(II->getArgOperand(i)->getType(), VF));
3149 return TTI.getIntrinsicInstrCost(II->getIntrinsicID(), RetTy, Tys);
3152 // We are scalarizing the instruction. Return the cost of the scalar
3153 // instruction, plus the cost of insert and extract into vector
3154 // elements, times the vector width.
3157 if (!RetTy->isVoidTy() && VF != 1) {
3158 unsigned InsCost = TTI.getVectorInstrCost(Instruction::InsertElement,
3160 unsigned ExtCost = TTI.getVectorInstrCost(Instruction::ExtractElement,
3163 // The cost of inserting the results plus extracting each one of the
3165 Cost += VF * (InsCost + ExtCost * I->getNumOperands());
3168 // The cost of executing VF copies of the scalar instruction. This opcode
3169 // is unknown. Assume that it is the same as 'mul'.
3170 Cost += VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy);
3176 Type* LoopVectorizationCostModel::ToVectorTy(Type *Scalar, unsigned VF) {
3177 if (Scalar->isVoidTy() || VF == 1)
3179 return VectorType::get(Scalar, VF);
3182 char LoopVectorize::ID = 0;
3183 static const char lv_name[] = "Loop Vectorization";
3184 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
3185 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3186 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
3187 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
3188 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
3189 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
3192 Pass *createLoopVectorizePass() {
3193 return new LoopVectorize();