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 //===----------------------------------------------------------------------===//
44 #define LV_NAME "loop-vectorize"
45 #define DEBUG_TYPE LV_NAME
46 #include "llvm/Transforms/Vectorize.h"
47 #include "llvm/ADT/SmallVector.h"
48 #include "llvm/ADT/StringExtras.h"
49 #include "llvm/Analysis/AliasAnalysis.h"
50 #include "llvm/Analysis/AliasSetTracker.h"
51 #include "llvm/Analysis/Dominators.h"
52 #include "llvm/Analysis/LoopInfo.h"
53 #include "llvm/Analysis/LoopIterator.h"
54 #include "llvm/Analysis/LoopPass.h"
55 #include "llvm/Analysis/ScalarEvolution.h"
56 #include "llvm/Analysis/ScalarEvolutionExpander.h"
57 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
58 #include "llvm/Analysis/ValueTracking.h"
59 #include "llvm/Analysis/Verifier.h"
60 #include "llvm/Constants.h"
61 #include "llvm/DataLayout.h"
62 #include "llvm/DerivedTypes.h"
63 #include "llvm/Function.h"
64 #include "llvm/Instructions.h"
65 #include "llvm/LLVMContext.h"
66 #include "llvm/Module.h"
67 #include "llvm/Pass.h"
68 #include "llvm/Support/CommandLine.h"
69 #include "llvm/Support/Debug.h"
70 #include "llvm/Support/raw_ostream.h"
71 #include "llvm/TargetTransformInfo.h"
72 #include "llvm/Transforms/Scalar.h"
73 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
74 #include "llvm/Transforms/Utils/Local.h"
75 #include "llvm/Type.h"
76 #include "llvm/Value.h"
80 static cl::opt<unsigned>
81 VectorizationFactor("force-vector-width", cl::init(0), cl::Hidden,
82 cl::desc("Set the default vectorization width. Zero is autoselect."));
85 EnableIfConversion("enable-if-conversion", cl::init(false), cl::Hidden,
86 cl::desc("Enable if-conversion during vectorization."));
88 /// We don't vectorize loops with a known constant trip count below this number.
89 const unsigned TinyTripCountThreshold = 16;
91 /// When performing a runtime memory check, do not check more than this
92 /// number of pointers. Notice that the check is quadratic!
93 const unsigned RuntimeMemoryCheckThreshold = 2;
95 /// This is the highest vector width that we try to generate.
96 const unsigned MaxVectorSize = 8;
100 // Forward declarations.
101 class LoopVectorizationLegality;
102 class LoopVectorizationCostModel;
104 /// InnerLoopVectorizer vectorizes loops which contain only one basic
105 /// block to a specified vectorization factor (VF).
106 /// This class performs the widening of scalars into vectors, or multiple
107 /// scalars. This class also implements the following features:
108 /// * It inserts an epilogue loop for handling loops that don't have iteration
109 /// counts that are known to be a multiple of the vectorization factor.
110 /// * It handles the code generation for reduction variables.
111 /// * Scalarization (implementation using scalars) of un-vectorizable
113 /// InnerLoopVectorizer does not perform any vectorization-legality
114 /// checks, and relies on the caller to check for the different legality
115 /// aspects. The InnerLoopVectorizer relies on the
116 /// LoopVectorizationLegality class to provide information about the induction
117 /// and reduction variables that were found to a given vectorization factor.
118 class InnerLoopVectorizer {
121 InnerLoopVectorizer(Loop *Orig, ScalarEvolution *Se, LoopInfo *Li,
122 DominatorTree *Dt, DataLayout *Dl, unsigned VecWidth):
123 OrigLoop(Orig), SE(Se), LI(Li), DT(Dt), DL(Dl), VF(VecWidth),
124 Builder(Se->getContext()), Induction(0), OldInduction(0) { }
126 // Perform the actual loop widening (vectorization).
127 void vectorize(LoopVectorizationLegality *Legal) {
128 // Create a new empty loop. Unlink the old loop and connect the new one.
129 createEmptyLoop(Legal);
130 // Widen each instruction in the old loop to a new one in the new loop.
131 // Use the Legality module to find the induction and reduction variables.
132 vectorizeLoop(Legal);
133 // Register the new loop and update the analysis passes.
138 /// A small list of PHINodes.
139 typedef SmallVector<PHINode*, 4> PhiVector;
141 /// Add code that checks at runtime if the accessed arrays overlap.
142 /// Returns the comperator value or NULL if no check is needed.
143 Value *addRuntimeCheck(LoopVectorizationLegality *Legal,
145 /// Create an empty loop, based on the loop ranges of the old loop.
146 void createEmptyLoop(LoopVectorizationLegality *Legal);
147 /// Copy and widen the instructions from the old loop.
148 void vectorizeLoop(LoopVectorizationLegality *Legal);
150 /// A helper function that computes the predicate of the block BB, assuming
151 /// that the header block of the loop is set to True. It returns the *entry*
152 /// mask for the block BB.
153 Value *createBlockInMask(BasicBlock *BB);
154 /// A helper function that computes the predicate of the edge between SRC
156 Value *createEdgeMask(BasicBlock *Src, BasicBlock *Dst);
158 /// A helper function to vectorize a single BB within the innermost loop.
159 void vectorizeBlockInLoop(LoopVectorizationLegality *Legal, BasicBlock *BB,
162 /// Insert the new loop to the loop hierarchy and pass manager
163 /// and update the analysis passes.
164 void updateAnalysis();
166 /// This instruction is un-vectorizable. Implement it as a sequence
168 void scalarizeInstruction(Instruction *Instr);
170 /// Create a broadcast instruction. This method generates a broadcast
171 /// instruction (shuffle) for loop invariant values and for the induction
172 /// value. If this is the induction variable then we extend it to N, N+1, ...
173 /// this is needed because each iteration in the loop corresponds to a SIMD
175 Value *getBroadcastInstrs(Value *V);
177 /// This is a helper function used by getBroadcastInstrs. It adds 0, 1, 2 ..
178 /// for each element in the vector. Starting from zero.
179 Value *getConsecutiveVector(Value* Val);
181 /// When we go over instructions in the basic block we rely on previous
182 /// values within the current basic block or on loop invariant values.
183 /// When we widen (vectorize) values we place them in the map. If the values
184 /// are not within the map, they have to be loop invariant, so we simply
185 /// broadcast them into a vector.
186 Value *getVectorValue(Value *V);
188 /// Get a uniform vector of constant integers. We use this to get
189 /// vectors of ones and zeros for the reduction code.
190 Constant* getUniformVector(unsigned Val, Type* ScalarTy);
192 typedef DenseMap<Value*, Value*> ValueMap;
194 /// The original loop.
196 // Scev analysis to use.
204 // The vectorization factor to use.
207 // The builder that we use
210 // --- Vectorization state ---
212 /// The vector-loop preheader.
213 BasicBlock *LoopVectorPreHeader;
214 /// The scalar-loop preheader.
215 BasicBlock *LoopScalarPreHeader;
216 /// Middle Block between the vector and the scalar.
217 BasicBlock *LoopMiddleBlock;
218 ///The ExitBlock of the scalar loop.
219 BasicBlock *LoopExitBlock;
220 ///The vector loop body.
221 BasicBlock *LoopVectorBody;
222 ///The scalar loop body.
223 BasicBlock *LoopScalarBody;
224 ///The first bypass block.
225 BasicBlock *LoopBypassBlock;
227 /// The new Induction variable which was added to the new block.
229 /// The induction variable of the old basic block.
230 PHINode *OldInduction;
231 // Maps scalars to widened vectors.
235 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
236 /// to what vectorization factor.
237 /// This class does not look at the profitability of vectorization, only the
238 /// legality. This class has two main kinds of checks:
239 /// * Memory checks - The code in canVectorizeMemory checks if vectorization
240 /// will change the order of memory accesses in a way that will change the
241 /// correctness of the program.
242 /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
243 /// checks for a number of different conditions, such as the availability of a
244 /// single induction variable, that all types are supported and vectorize-able,
245 /// etc. This code reflects the capabilities of InnerLoopVectorizer.
246 /// This class is also used by InnerLoopVectorizer for identifying
247 /// induction variable and the different reduction variables.
248 class LoopVectorizationLegality {
250 LoopVectorizationLegality(Loop *Lp, ScalarEvolution *Se, DataLayout *Dl,
252 TheLoop(Lp), SE(Se), DL(Dl), DT(Dt), Induction(0) { }
254 /// This represents the kinds of reductions that we support.
256 NoReduction, /// Not a reduction.
257 IntegerAdd, /// Sum of numbers.
258 IntegerMult, /// Product of numbers.
259 IntegerOr, /// Bitwise or logical OR of numbers.
260 IntegerAnd, /// Bitwise or logical AND of numbers.
261 IntegerXor /// Bitwise or logical XOR of numbers.
264 /// This POD struct holds information about reduction variables.
265 struct ReductionDescriptor {
267 ReductionDescriptor():
268 StartValue(0), LoopExitInstr(0), Kind(NoReduction) {}
271 ReductionDescriptor(Value *Start, Instruction *Exit, ReductionKind K):
272 StartValue(Start), LoopExitInstr(Exit), Kind(K) {}
274 // The starting value of the reduction.
275 // It does not have to be zero!
277 // The instruction who's value is used outside the loop.
278 Instruction *LoopExitInstr;
279 // The kind of the reduction.
283 // This POD struct holds information about the memory runtime legality
284 // check that a group of pointers do not overlap.
285 struct RuntimePointerCheck {
286 RuntimePointerCheck(): Need(false) {}
288 /// Reset the state of the pointer runtime information.
296 /// Insert a pointer and calculate the start and end SCEVs.
297 void insert(ScalarEvolution *SE, Loop *Lp, Value *Ptr) {
298 const SCEV *Sc = SE->getSCEV(Ptr);
299 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
300 assert(AR && "Invalid addrec expression");
301 const SCEV *Ex = SE->getExitCount(Lp, Lp->getLoopLatch());
302 const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
303 Pointers.push_back(Ptr);
304 Starts.push_back(AR->getStart());
305 Ends.push_back(ScEnd);
308 /// This flag indicates if we need to add the runtime check.
310 /// Holds the pointers that we need to check.
311 SmallVector<Value*, 2> Pointers;
312 /// Holds the pointer value at the beginning of the loop.
313 SmallVector<const SCEV*, 2> Starts;
314 /// Holds the pointer value at the end of the loop.
315 SmallVector<const SCEV*, 2> Ends;
318 /// ReductionList contains the reduction descriptors for all
319 /// of the reductions that were found in the loop.
320 typedef DenseMap<PHINode*, ReductionDescriptor> ReductionList;
322 /// InductionList saves induction variables and maps them to the initial
323 /// value entring the loop.
324 typedef DenseMap<PHINode*, Value*> InductionList;
326 /// Returns true if it is legal to vectorize this loop.
327 /// This does not mean that it is profitable to vectorize this
328 /// loop, only that it is legal to do so.
331 /// Returns the Induction variable.
332 PHINode *getInduction() {return Induction;}
334 /// Returns the reduction variables found in the loop.
335 ReductionList *getReductionVars() { return &Reductions; }
337 /// Returns the induction variables found in the loop.
338 InductionList *getInductionVars() { return &Inductions; }
340 /// Return true if the block BB needs to be predicated in order for the loop
341 /// to be vectorized.
342 bool blockNeedsPredication(BasicBlock *BB);
344 /// Check if this pointer is consecutive when vectorizing. This happens
345 /// when the last index of the GEP is the induction variable, or that the
346 /// pointer itself is an induction variable.
347 /// This check allows us to vectorize A[idx] into a wide load/store.
348 bool isConsecutivePtr(Value *Ptr);
350 /// Returns true if the value V is uniform within the loop.
351 bool isUniform(Value *V);
353 /// Returns true if this instruction will remain scalar after vectorization.
354 bool isUniformAfterVectorization(Instruction* I) {return Uniforms.count(I);}
356 /// Returns the information that we collected about runtime memory check.
357 RuntimePointerCheck *getRuntimePointerCheck() {return &PtrRtCheck; }
359 /// Check if a single basic block loop is vectorizable.
360 /// At this point we know that this is a loop with a constant trip count
361 /// and we only need to check individual instructions.
362 bool canVectorizeInstrs();
364 /// When we vectorize loops we may change the order in which
365 /// we read and write from memory. This method checks if it is
366 /// legal to vectorize the code, considering only memory constrains.
367 /// Returns true if the loop is vectorizable
368 bool canVectorizeMemory();
370 /// Return true if we can vectorize this loop using the IF-conversion
372 bool canVectorizeWithIfConvert();
374 /// Collect the variables that need to stay uniform after vectorization.
375 void collectLoopUniforms();
377 /// Return true if all of the instructions in the block can be speculatively
379 bool blockCanBePredicated(BasicBlock *BB);
381 /// Returns True, if 'Phi' is the kind of reduction variable for type
382 /// 'Kind'. If this is a reduction variable, it adds it to ReductionList.
383 bool AddReductionVar(PHINode *Phi, ReductionKind Kind);
384 /// Returns true if the instruction I can be a reduction variable of type
386 bool isReductionInstr(Instruction *I, ReductionKind Kind);
387 /// Returns True, if 'Phi' is an induction variable.
388 bool isInductionVariable(PHINode *Phi);
389 /// Return true if can compute the address bounds of Ptr within the loop.
390 bool hasComputableBounds(Value *Ptr);
392 /// The loop that we evaluate.
396 /// DataLayout analysis.
401 // --- vectorization state --- //
403 /// Holds the integer induction variable. This is the counter of the
406 /// Holds the reduction variables.
407 ReductionList Reductions;
408 /// Holds all of the induction variables that we found in the loop.
409 /// Notice that inductions don't need to start at zero and that induction
410 /// variables can be pointers.
411 InductionList Inductions;
413 /// Allowed outside users. This holds the reduction
414 /// vars which can be accessed from outside the loop.
415 SmallPtrSet<Value*, 4> AllowedExit;
416 /// This set holds the variables which are known to be uniform after
418 SmallPtrSet<Instruction*, 4> Uniforms;
419 /// We need to check that all of the pointers in this list are disjoint
421 RuntimePointerCheck PtrRtCheck;
424 /// LoopVectorizationCostModel - estimates the expected speedups due to
426 /// In many cases vectorization is not profitable. This can happen because
427 /// of a number of reasons. In this class we mainly attempt to predict
428 /// the expected speedup/slowdowns due to the supported instruction set.
429 /// We use the VectorTargetTransformInfo to query the different backends
430 /// for the cost of different operations.
431 class LoopVectorizationCostModel {
434 LoopVectorizationCostModel(Loop *Lp, ScalarEvolution *Se,
435 LoopVectorizationLegality *Leg,
436 const VectorTargetTransformInfo *Vtti):
437 TheLoop(Lp), SE(Se), Legal(Leg), VTTI(Vtti) { }
439 /// Returns the most profitable vectorization factor for the loop that is
440 /// smaller or equal to the VF argument. This method checks every power
442 unsigned findBestVectorizationFactor(unsigned VF = MaxVectorSize);
445 /// Returns the expected execution cost. The unit of the cost does
446 /// not matter because we use the 'cost' units to compare different
447 /// vector widths. The cost that is returned is *not* normalized by
448 /// the factor width.
449 unsigned expectedCost(unsigned VF);
451 /// Returns the execution time cost of an instruction for a given vector
452 /// width. Vector width of one means scalar.
453 unsigned getInstructionCost(Instruction *I, unsigned VF);
455 /// A helper function for converting Scalar types to vector types.
456 /// If the incoming type is void, we return void. If the VF is 1, we return
458 static Type* ToVectorTy(Type *Scalar, unsigned VF);
460 /// The loop that we evaluate.
465 /// Vectorization legality.
466 LoopVectorizationLegality *Legal;
467 /// Vector target information.
468 const VectorTargetTransformInfo *VTTI;
471 struct LoopVectorize : public LoopPass {
472 static char ID; // Pass identification, replacement for typeid
474 LoopVectorize() : LoopPass(ID) {
475 initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
481 TargetTransformInfo *TTI;
484 virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
485 // We only vectorize innermost loops.
489 SE = &getAnalysis<ScalarEvolution>();
490 DL = getAnalysisIfAvailable<DataLayout>();
491 LI = &getAnalysis<LoopInfo>();
492 TTI = getAnalysisIfAvailable<TargetTransformInfo>();
493 DT = &getAnalysis<DominatorTree>();
495 DEBUG(dbgs() << "LV: Checking a loop in \"" <<
496 L->getHeader()->getParent()->getName() << "\"\n");
498 // Check if it is legal to vectorize the loop.
499 LoopVectorizationLegality LVL(L, SE, DL, DT);
500 if (!LVL.canVectorize()) {
501 DEBUG(dbgs() << "LV: Not vectorizing.\n");
505 // Select the preffered vectorization factor.
507 if (VectorizationFactor == 0) {
508 const VectorTargetTransformInfo *VTTI = 0;
510 VTTI = TTI->getVectorTargetTransformInfo();
511 // Use the cost model.
512 LoopVectorizationCostModel CM(L, SE, &LVL, VTTI);
513 VF = CM.findBestVectorizationFactor();
516 DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
521 // Use the user command flag.
522 VF = VectorizationFactor;
525 DEBUG(dbgs() << "LV: Found a vectorizable loop ("<< VF << ") in "<<
526 L->getHeader()->getParent()->getParent()->getModuleIdentifier()<<
529 // If we decided that it is *legal* to vectorizer the loop then do it.
530 InnerLoopVectorizer LB(L, SE, LI, DT, DL, VF);
533 DEBUG(verifyFunction(*L->getHeader()->getParent()));
537 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
538 LoopPass::getAnalysisUsage(AU);
539 AU.addRequiredID(LoopSimplifyID);
540 AU.addRequiredID(LCSSAID);
541 AU.addRequired<LoopInfo>();
542 AU.addRequired<ScalarEvolution>();
543 AU.addRequired<DominatorTree>();
544 AU.addPreserved<LoopInfo>();
545 AU.addPreserved<DominatorTree>();
550 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
552 LLVMContext &C = V->getContext();
553 Type *VTy = VectorType::get(V->getType(), VF);
554 Type *I32 = IntegerType::getInt32Ty(C);
556 // Save the current insertion location.
557 Instruction *Loc = Builder.GetInsertPoint();
559 // We need to place the broadcast of invariant variables outside the loop.
560 bool Invariant = (OrigLoop->isLoopInvariant(V) && V != Induction);
562 // Place the code for broadcasting invariant variables in the new preheader.
564 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
566 Constant *Zero = ConstantInt::get(I32, 0);
567 Value *Zeros = ConstantAggregateZero::get(VectorType::get(I32, VF));
568 Value *UndefVal = UndefValue::get(VTy);
569 // Insert the value into a new vector.
570 Value *SingleElem = Builder.CreateInsertElement(UndefVal, V, Zero);
571 // Broadcast the scalar into all locations in the vector.
572 Value *Shuf = Builder.CreateShuffleVector(SingleElem, UndefVal, Zeros,
575 // Restore the builder insertion point.
577 Builder.SetInsertPoint(Loc);
582 Value *InnerLoopVectorizer::getConsecutiveVector(Value* Val) {
583 assert(Val->getType()->isVectorTy() && "Must be a vector");
584 assert(Val->getType()->getScalarType()->isIntegerTy() &&
585 "Elem must be an integer");
587 Type *ITy = Val->getType()->getScalarType();
588 VectorType *Ty = cast<VectorType>(Val->getType());
589 unsigned VLen = Ty->getNumElements();
590 SmallVector<Constant*, 8> Indices;
592 // Create a vector of consecutive numbers from zero to VF.
593 for (unsigned i = 0; i < VLen; ++i)
594 Indices.push_back(ConstantInt::get(ITy, i));
596 // Add the consecutive indices to the vector value.
597 Constant *Cv = ConstantVector::get(Indices);
598 assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
599 return Builder.CreateAdd(Val, Cv, "induction");
602 bool LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
603 assert(Ptr->getType()->isPointerTy() && "Unexpected non ptr");
605 // If this pointer is an induction variable, return it.
606 PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
607 if (Phi && getInductionVars()->count(Phi))
610 GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
614 unsigned NumOperands = Gep->getNumOperands();
615 Value *LastIndex = Gep->getOperand(NumOperands - 1);
617 // Check that all of the gep indices are uniform except for the last.
618 for (unsigned i = 0; i < NumOperands - 1; ++i)
619 if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
622 // We can emit wide load/stores only if the last index is the induction
624 const SCEV *Last = SE->getSCEV(LastIndex);
625 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
626 const SCEV *Step = AR->getStepRecurrence(*SE);
628 // The memory is consecutive because the last index is consecutive
629 // and all other indices are loop invariant.
637 bool LoopVectorizationLegality::isUniform(Value *V) {
638 return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
641 Value *InnerLoopVectorizer::getVectorValue(Value *V) {
642 assert(V != Induction && "The new induction variable should not be used.");
643 assert(!V->getType()->isVectorTy() && "Can't widen a vector");
644 // If we saved a vectorized copy of V, use it.
645 Value *&MapEntry = WidenMap[V];
649 // Broadcast V and save the value for future uses.
650 Value *B = getBroadcastInstrs(V);
656 InnerLoopVectorizer::getUniformVector(unsigned Val, Type* ScalarTy) {
657 return ConstantVector::getSplat(VF, ConstantInt::get(ScalarTy, Val, true));
660 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr) {
661 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
662 // Holds vector parameters or scalars, in case of uniform vals.
663 SmallVector<Value*, 8> Params;
665 // Find all of the vectorized parameters.
666 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
667 Value *SrcOp = Instr->getOperand(op);
669 // If we are accessing the old induction variable, use the new one.
670 if (SrcOp == OldInduction) {
671 Params.push_back(getVectorValue(SrcOp));
675 // Try using previously calculated values.
676 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
678 // If the src is an instruction that appeared earlier in the basic block
679 // then it should already be vectorized.
680 if (SrcInst && SrcInst->getParent() == Instr->getParent()) {
681 assert(WidenMap.count(SrcInst) && "Source operand is unavailable");
682 // The parameter is a vector value from earlier.
683 Params.push_back(WidenMap[SrcInst]);
685 // The parameter is a scalar from outside the loop. Maybe even a constant.
686 Params.push_back(SrcOp);
690 assert(Params.size() == Instr->getNumOperands() &&
691 "Invalid number of operands");
693 // Does this instruction return a value ?
694 bool IsVoidRetTy = Instr->getType()->isVoidTy();
695 Value *VecResults = 0;
697 // If we have a return value, create an empty vector. We place the scalarized
698 // instructions in this vector.
700 VecResults = UndefValue::get(VectorType::get(Instr->getType(), VF));
702 // For each scalar that we create:
703 for (unsigned i = 0; i < VF; ++i) {
704 Instruction *Cloned = Instr->clone();
706 Cloned->setName(Instr->getName() + ".cloned");
707 // Replace the operands of the cloned instrucions with extracted scalars.
708 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
709 Value *Op = Params[op];
710 // Param is a vector. Need to extract the right lane.
711 if (Op->getType()->isVectorTy())
712 Op = Builder.CreateExtractElement(Op, Builder.getInt32(i));
713 Cloned->setOperand(op, Op);
716 // Place the cloned scalar in the new loop.
717 Builder.Insert(Cloned);
719 // If the original scalar returns a value we need to place it in a vector
720 // so that future users will be able to use it.
722 VecResults = Builder.CreateInsertElement(VecResults, Cloned,
723 Builder.getInt32(i));
727 WidenMap[Instr] = VecResults;
731 InnerLoopVectorizer::addRuntimeCheck(LoopVectorizationLegality *Legal,
733 LoopVectorizationLegality::RuntimePointerCheck *PtrRtCheck =
734 Legal->getRuntimePointerCheck();
736 if (!PtrRtCheck->Need)
739 Value *MemoryRuntimeCheck = 0;
740 unsigned NumPointers = PtrRtCheck->Pointers.size();
741 SmallVector<Value* , 2> Starts;
742 SmallVector<Value* , 2> Ends;
744 SCEVExpander Exp(*SE, "induction");
746 // Use this type for pointer arithmetic.
747 Type* PtrArithTy = PtrRtCheck->Pointers[0]->getType();
749 for (unsigned i = 0; i < NumPointers; ++i) {
750 Value *Ptr = PtrRtCheck->Pointers[i];
751 const SCEV *Sc = SE->getSCEV(Ptr);
753 if (SE->isLoopInvariant(Sc, OrigLoop)) {
754 DEBUG(dbgs() << "LV: Adding RT check for a loop invariant ptr:" <<
756 Starts.push_back(Ptr);
759 DEBUG(dbgs() << "LV: Adding RT check for range:" << *Ptr <<"\n");
761 Value *Start = Exp.expandCodeFor(PtrRtCheck->Starts[i],
763 Value *End = Exp.expandCodeFor(PtrRtCheck->Ends[i], PtrArithTy, Loc);
764 Starts.push_back(Start);
769 for (unsigned i = 0; i < NumPointers; ++i) {
770 for (unsigned j = i+1; j < NumPointers; ++j) {
771 Value *Cmp0 = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_ULE,
772 Starts[i], Ends[j], "bound0", Loc);
773 Value *Cmp1 = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_ULE,
774 Starts[j], Ends[i], "bound1", Loc);
775 Value *IsConflict = BinaryOperator::Create(Instruction::And, Cmp0, Cmp1,
776 "found.conflict", Loc);
777 if (MemoryRuntimeCheck)
778 MemoryRuntimeCheck = BinaryOperator::Create(Instruction::Or,
781 "conflict.rdx", Loc);
783 MemoryRuntimeCheck = IsConflict;
788 return MemoryRuntimeCheck;
792 InnerLoopVectorizer::createEmptyLoop(LoopVectorizationLegality *Legal) {
794 In this function we generate a new loop. The new loop will contain
795 the vectorized instructions while the old loop will continue to run the
798 [ ] <-- vector loop bypass.
801 | [ ] <-- vector pre header.
805 | [ ]_| <-- vector loop.
808 >[ ] <--- middle-block.
811 | [ ] <--- new preheader.
815 | [ ]_| <-- old scalar loop to handle remainder.
822 BasicBlock *OldBasicBlock = OrigLoop->getHeader();
823 BasicBlock *BypassBlock = OrigLoop->getLoopPreheader();
824 BasicBlock *ExitBlock = OrigLoop->getExitBlock();
825 assert(ExitBlock && "Must have an exit block");
827 // Some loops have a single integer induction variable, while other loops
828 // don't. One example is c++ iterators that often have multiple pointer
829 // induction variables. In the code below we also support a case where we
830 // don't have a single induction variable.
831 OldInduction = Legal->getInduction();
832 Type *IdxTy = OldInduction ? OldInduction->getType() :
833 DL->getIntPtrType(SE->getContext());
835 // Find the loop boundaries.
836 const SCEV *ExitCount = SE->getExitCount(OrigLoop, OrigLoop->getLoopLatch());
837 assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
839 // Get the total trip count from the count by adding 1.
840 ExitCount = SE->getAddExpr(ExitCount,
841 SE->getConstant(ExitCount->getType(), 1));
843 // Expand the trip count and place the new instructions in the preheader.
844 // Notice that the pre-header does not change, only the loop body.
845 SCEVExpander Exp(*SE, "induction");
847 // Count holds the overall loop count (N).
848 Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
849 BypassBlock->getTerminator());
851 // The loop index does not have to start at Zero. Find the original start
852 // value from the induction PHI node. If we don't have an induction variable
853 // then we know that it starts at zero.
854 Value *StartIdx = OldInduction ?
855 OldInduction->getIncomingValueForBlock(BypassBlock):
856 ConstantInt::get(IdxTy, 0);
858 assert(BypassBlock && "Invalid loop structure");
860 // Generate the code that checks in runtime if arrays overlap.
861 Value *MemoryRuntimeCheck = addRuntimeCheck(Legal,
862 BypassBlock->getTerminator());
864 // Split the single block loop into the two loop structure described above.
865 BasicBlock *VectorPH =
866 BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
867 BasicBlock *VecBody =
868 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
869 BasicBlock *MiddleBlock =
870 VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
871 BasicBlock *ScalarPH =
872 MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
874 // This is the location in which we add all of the logic for bypassing
875 // the new vector loop.
876 Instruction *Loc = BypassBlock->getTerminator();
878 // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
880 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
882 // Generate the induction variable.
883 Induction = Builder.CreatePHI(IdxTy, 2, "index");
884 Constant *Step = ConstantInt::get(IdxTy, VF);
886 // We may need to extend the index in case there is a type mismatch.
887 // We know that the count starts at zero and does not overflow.
888 if (Count->getType() != IdxTy) {
889 // The exit count can be of pointer type. Convert it to the correct
891 if (ExitCount->getType()->isPointerTy())
892 Count = CastInst::CreatePointerCast(Count, IdxTy, "ptrcnt.to.int", Loc);
894 Count = CastInst::CreateZExtOrBitCast(Count, IdxTy, "zext.cnt", Loc);
897 // Add the start index to the loop count to get the new end index.
898 Value *IdxEnd = BinaryOperator::CreateAdd(Count, StartIdx, "end.idx", Loc);
900 // Now we need to generate the expression for N - (N % VF), which is
901 // the part that the vectorized body will execute.
902 Constant *CIVF = ConstantInt::get(IdxTy, VF);
903 Value *R = BinaryOperator::CreateURem(Count, CIVF, "n.mod.vf", Loc);
904 Value *CountRoundDown = BinaryOperator::CreateSub(Count, R, "n.vec", Loc);
905 Value *IdxEndRoundDown = BinaryOperator::CreateAdd(CountRoundDown, StartIdx,
906 "end.idx.rnd.down", Loc);
908 // Now, compare the new count to zero. If it is zero skip the vector loop and
909 // jump to the scalar loop.
910 Value *Cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
915 // If we are using memory runtime checks, include them in.
916 if (MemoryRuntimeCheck)
917 Cmp = BinaryOperator::Create(Instruction::Or, Cmp, MemoryRuntimeCheck,
920 BranchInst::Create(MiddleBlock, VectorPH, Cmp, Loc);
921 // Remove the old terminator.
922 Loc->eraseFromParent();
924 // We are going to resume the execution of the scalar loop.
925 // Go over all of the induction variables that we found and fix the
926 // PHIs that are left in the scalar version of the loop.
927 // The starting values of PHI nodes depend on the counter of the last
928 // iteration in the vectorized loop.
929 // If we come from a bypass edge then we need to start from the original start
932 // This variable saves the new starting index for the scalar loop.
933 PHINode *ResumeIndex = 0;
934 LoopVectorizationLegality::InductionList::iterator I, E;
935 LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
936 for (I = List->begin(), E = List->end(); I != E; ++I) {
937 PHINode *OrigPhi = I->first;
938 PHINode *ResumeVal = PHINode::Create(OrigPhi->getType(), 2, "resume.val",
939 MiddleBlock->getTerminator());
941 if (OrigPhi->getType()->isIntegerTy()) {
942 // Handle the integer induction counter:
943 assert(OrigPhi == OldInduction && "Unknown integer PHI");
944 // We know what the end value is.
945 EndValue = IdxEndRoundDown;
946 // We also know which PHI node holds it.
947 ResumeIndex = ResumeVal;
949 // For pointer induction variables, calculate the offset using
951 EndValue = GetElementPtrInst::Create(I->second, CountRoundDown,
953 BypassBlock->getTerminator());
956 // The new PHI merges the original incoming value, in case of a bypass,
957 // or the value at the end of the vectorized loop.
958 ResumeVal->addIncoming(I->second, BypassBlock);
959 ResumeVal->addIncoming(EndValue, VecBody);
961 // Fix the scalar body counter (PHI node).
962 unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
963 OrigPhi->setIncomingValue(BlockIdx, ResumeVal);
966 // If we are generating a new induction variable then we also need to
967 // generate the code that calculates the exit value. This value is not
968 // simply the end of the counter because we may skip the vectorized body
969 // in case of a runtime check.
971 assert(!ResumeIndex && "Unexpected resume value found");
972 ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val",
973 MiddleBlock->getTerminator());
974 ResumeIndex->addIncoming(StartIdx, BypassBlock);
975 ResumeIndex->addIncoming(IdxEndRoundDown, VecBody);
978 // Make sure that we found the index where scalar loop needs to continue.
979 assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() &&
980 "Invalid resume Index");
982 // Add a check in the middle block to see if we have completed
983 // all of the iterations in the first vector loop.
984 // If (N - N%VF) == N, then we *don't* need to run the remainder.
985 Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd,
986 ResumeIndex, "cmp.n",
987 MiddleBlock->getTerminator());
989 BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
990 // Remove the old terminator.
991 MiddleBlock->getTerminator()->eraseFromParent();
993 // Create i+1 and fill the PHINode.
994 Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
995 Induction->addIncoming(StartIdx, VectorPH);
996 Induction->addIncoming(NextIdx, VecBody);
997 // Create the compare.
998 Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown);
999 Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
1001 // Now we have two terminators. Remove the old one from the block.
1002 VecBody->getTerminator()->eraseFromParent();
1004 // Get ready to start creating new instructions into the vectorized body.
1005 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
1007 // Create and register the new vector loop.
1008 Loop* Lp = new Loop();
1009 Loop *ParentLoop = OrigLoop->getParentLoop();
1011 // Insert the new loop into the loop nest and register the new basic blocks.
1013 ParentLoop->addChildLoop(Lp);
1014 ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase());
1015 ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase());
1016 ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase());
1018 LI->addTopLevelLoop(Lp);
1021 Lp->addBasicBlockToLoop(VecBody, LI->getBase());
1024 LoopVectorPreHeader = VectorPH;
1025 LoopScalarPreHeader = ScalarPH;
1026 LoopMiddleBlock = MiddleBlock;
1027 LoopExitBlock = ExitBlock;
1028 LoopVectorBody = VecBody;
1029 LoopScalarBody = OldBasicBlock;
1030 LoopBypassBlock = BypassBlock;
1033 /// This function returns the identity element (or neutral element) for
1034 /// the operation K.
1036 getReductionIdentity(LoopVectorizationLegality::ReductionKind K) {
1038 case LoopVectorizationLegality::IntegerXor:
1039 case LoopVectorizationLegality::IntegerAdd:
1040 case LoopVectorizationLegality::IntegerOr:
1041 // Adding, Xoring, Oring zero to a number does not change it.
1043 case LoopVectorizationLegality::IntegerMult:
1044 // Multiplying a number by 1 does not change it.
1046 case LoopVectorizationLegality::IntegerAnd:
1047 // AND-ing a number with an all-1 value does not change it.
1050 llvm_unreachable("Unknown reduction kind");
1055 InnerLoopVectorizer::vectorizeLoop(LoopVectorizationLegality *Legal) {
1056 //===------------------------------------------------===//
1058 // Notice: any optimization or new instruction that go
1059 // into the code below should be also be implemented in
1062 //===------------------------------------------------===//
1063 BasicBlock &BB = *OrigLoop->getHeader();
1064 Constant *Zero = ConstantInt::get(
1065 IntegerType::getInt32Ty(BB.getContext()), 0);
1067 // In order to support reduction variables we need to be able to vectorize
1068 // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
1069 // stages. First, we create a new vector PHI node with no incoming edges.
1070 // We use this value when we vectorize all of the instructions that use the
1071 // PHI. Next, after all of the instructions in the block are complete we
1072 // add the new incoming edges to the PHI. At this point all of the
1073 // instructions in the basic block are vectorized, so we can use them to
1074 // construct the PHI.
1075 PhiVector RdxPHIsToFix;
1077 // Scan the loop in a topological order to ensure that defs are vectorized
1079 LoopBlocksDFS DFS(OrigLoop);
1082 // Vectorize all of the blocks in the original loop.
1083 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
1084 be = DFS.endRPO(); bb != be; ++bb)
1085 vectorizeBlockInLoop(Legal, *bb, &RdxPHIsToFix);
1087 // At this point every instruction in the original loop is widened to
1088 // a vector form. We are almost done. Now, we need to fix the PHI nodes
1089 // that we vectorized. The PHI nodes are currently empty because we did
1090 // not want to introduce cycles. Notice that the remaining PHI nodes
1091 // that we need to fix are reduction variables.
1093 // Create the 'reduced' values for each of the induction vars.
1094 // The reduced values are the vector values that we scalarize and combine
1095 // after the loop is finished.
1096 for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
1098 PHINode *RdxPhi = *it;
1099 PHINode *VecRdxPhi = dyn_cast<PHINode>(WidenMap[RdxPhi]);
1100 assert(RdxPhi && "Unable to recover vectorized PHI");
1102 // Find the reduction variable descriptor.
1103 assert(Legal->getReductionVars()->count(RdxPhi) &&
1104 "Unable to find the reduction variable");
1105 LoopVectorizationLegality::ReductionDescriptor RdxDesc =
1106 (*Legal->getReductionVars())[RdxPhi];
1108 // We need to generate a reduction vector from the incoming scalar.
1109 // To do so, we need to generate the 'identity' vector and overide
1110 // one of the elements with the incoming scalar reduction. We need
1111 // to do it in the vector-loop preheader.
1112 Builder.SetInsertPoint(LoopBypassBlock->getTerminator());
1114 // This is the vector-clone of the value that leaves the loop.
1115 Value *VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
1116 Type *VecTy = VectorExit->getType();
1118 // Find the reduction identity variable. Zero for addition, or, xor,
1119 // one for multiplication, -1 for And.
1120 Constant *Identity = getUniformVector(getReductionIdentity(RdxDesc.Kind),
1121 VecTy->getScalarType());
1123 // This vector is the Identity vector where the first element is the
1124 // incoming scalar reduction.
1125 Value *VectorStart = Builder.CreateInsertElement(Identity,
1126 RdxDesc.StartValue, Zero);
1128 // Fix the vector-loop phi.
1129 // We created the induction variable so we know that the
1130 // preheader is the first entry.
1131 BasicBlock *VecPreheader = Induction->getIncomingBlock(0);
1133 // Reductions do not have to start at zero. They can start with
1134 // any loop invariant values.
1135 VecRdxPhi->addIncoming(VectorStart, VecPreheader);
1136 unsigned SelfEdgeIdx = (RdxPhi)->getBasicBlockIndex(LoopScalarBody);
1137 Value *Val = getVectorValue(RdxPhi->getIncomingValue(SelfEdgeIdx));
1138 VecRdxPhi->addIncoming(Val, LoopVectorBody);
1140 // Before each round, move the insertion point right between
1141 // the PHIs and the values we are going to write.
1142 // This allows us to write both PHINodes and the extractelement
1144 Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
1146 // This PHINode contains the vectorized reduction variable, or
1147 // the initial value vector, if we bypass the vector loop.
1148 PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
1149 NewPhi->addIncoming(VectorStart, LoopBypassBlock);
1150 NewPhi->addIncoming(getVectorValue(RdxDesc.LoopExitInstr), LoopVectorBody);
1152 // Extract the first scalar.
1154 Builder.CreateExtractElement(NewPhi, Builder.getInt32(0));
1155 // Extract and reduce the remaining vector elements.
1156 for (unsigned i=1; i < VF; ++i) {
1158 Builder.CreateExtractElement(NewPhi, Builder.getInt32(i));
1159 switch (RdxDesc.Kind) {
1160 case LoopVectorizationLegality::IntegerAdd:
1161 Scalar0 = Builder.CreateAdd(Scalar0, Scalar1);
1163 case LoopVectorizationLegality::IntegerMult:
1164 Scalar0 = Builder.CreateMul(Scalar0, Scalar1);
1166 case LoopVectorizationLegality::IntegerOr:
1167 Scalar0 = Builder.CreateOr(Scalar0, Scalar1);
1169 case LoopVectorizationLegality::IntegerAnd:
1170 Scalar0 = Builder.CreateAnd(Scalar0, Scalar1);
1172 case LoopVectorizationLegality::IntegerXor:
1173 Scalar0 = Builder.CreateXor(Scalar0, Scalar1);
1176 llvm_unreachable("Unknown reduction operation");
1180 // Now, we need to fix the users of the reduction variable
1181 // inside and outside of the scalar remainder loop.
1182 // We know that the loop is in LCSSA form. We need to update the
1183 // PHI nodes in the exit blocks.
1184 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
1185 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
1186 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
1187 if (!LCSSAPhi) continue;
1189 // All PHINodes need to have a single entry edge, or two if
1190 // we already fixed them.
1191 assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
1193 // We found our reduction value exit-PHI. Update it with the
1194 // incoming bypass edge.
1195 if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
1196 // Add an edge coming from the bypass.
1197 LCSSAPhi->addIncoming(Scalar0, LoopMiddleBlock);
1200 }// end of the LCSSA phi scan.
1202 // Fix the scalar loop reduction variable with the incoming reduction sum
1203 // from the vector body and from the backedge value.
1204 int IncomingEdgeBlockIdx = (RdxPhi)->getBasicBlockIndex(LoopScalarBody);
1205 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1); // The other block.
1206 (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, Scalar0);
1207 (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
1208 }// end of for each redux variable.
1211 Value *InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
1212 assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
1215 Value *SrcMask = createBlockInMask(Src);
1217 // The terminator has to be a branch inst!
1218 BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
1219 assert(BI && "Unexpected terminator found");
1221 Value *EdgeMask = SrcMask;
1222 if (BI->isConditional()) {
1223 EdgeMask = getVectorValue(BI->getCondition());
1224 if (BI->getSuccessor(0) != Dst)
1225 EdgeMask = Builder.CreateNot(EdgeMask);
1228 return Builder.CreateAnd(EdgeMask, SrcMask);
1231 Value *InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
1232 assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
1234 // Loop incoming mask is all-one.
1235 if (OrigLoop->getHeader() == BB)
1236 return getVectorValue(
1237 ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1));
1239 // This is the block mask. We OR all incoming edges, and with zero.
1240 Value *BlockMask = getVectorValue(
1241 ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0));
1244 for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it)
1245 BlockMask = Builder.CreateOr(BlockMask, createEdgeMask(*it, BB));
1251 InnerLoopVectorizer::vectorizeBlockInLoop(LoopVectorizationLegality *Legal,
1252 BasicBlock *BB, PhiVector *PV) {
1254 ConstantInt::get(IntegerType::getInt32Ty(BB->getContext()), 0);
1256 // For each instruction in the old loop.
1257 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1258 switch (it->getOpcode()) {
1259 case Instruction::Br:
1260 // Nothing to do for PHIs and BR, since we already took care of the
1261 // loop control flow instructions.
1263 case Instruction::PHI:{
1264 PHINode* P = cast<PHINode>(it);
1265 // Handle reduction variables:
1266 if (Legal->getReductionVars()->count(P)) {
1267 // This is phase one of vectorizing PHIs.
1268 Type *VecTy = VectorType::get(it->getType(), VF);
1270 PHINode::Create(VecTy, 2, "vec.phi",
1271 LoopVectorBody->getFirstInsertionPt());
1276 // Check for PHI nodes that are lowered to vector selects.
1277 if (P->getParent() != OrigLoop->getHeader()) {
1278 // We know that all PHIs in non header blocks are converted into
1279 // selects, so we don't have to worry about the insertion order and we
1280 // can just use the builder.
1282 // At this point we generate the predication tree. There may be
1283 // duplications since this is a simple recursive scan, but future
1284 // optimizations will clean it up.
1285 Value *Cond = createBlockInMask(P->getIncomingBlock(0));
1287 Builder.CreateSelect(Cond,
1288 getVectorValue(P->getIncomingValue(0)),
1289 getVectorValue(P->getIncomingValue(1)),
1294 // This PHINode must be an induction variable.
1295 // Make sure that we know about it.
1296 assert(Legal->getInductionVars()->count(P) &&
1297 "Not an induction variable");
1299 if (P->getType()->isIntegerTy()) {
1300 assert(P == OldInduction && "Unexpected PHI");
1301 Value *Broadcasted = getBroadcastInstrs(Induction);
1302 // After broadcasting the induction variable we need to make the
1303 // vector consecutive by adding 0, 1, 2 ...
1304 Value *ConsecutiveInduction = getConsecutiveVector(Broadcasted);
1306 WidenMap[OldInduction] = ConsecutiveInduction;
1310 // Handle pointer inductions.
1311 assert(P->getType()->isPointerTy() && "Unexpected type.");
1312 Value *StartIdx = OldInduction ?
1313 Legal->getInductionVars()->lookup(OldInduction) :
1314 ConstantInt::get(Induction->getType(), 0);
1316 // This is the pointer value coming into the loop.
1317 Value *StartPtr = Legal->getInductionVars()->lookup(P);
1319 // This is the normalized GEP that starts counting at zero.
1320 Value *NormalizedIdx = Builder.CreateSub(Induction, StartIdx,
1323 // This is the vector of results. Notice that we don't generate vector
1324 // geps because scalar geps result in better code.
1325 Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
1326 for (unsigned int i = 0; i < VF; ++i) {
1327 Constant *Idx = ConstantInt::get(Induction->getType(), i);
1328 Value *GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx, "gep.idx");
1329 Value *SclrGep = Builder.CreateGEP(StartPtr, GlobalIdx, "next.gep");
1330 VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
1331 Builder.getInt32(i),
1335 WidenMap[it] = VecVal;
1338 case Instruction::Add:
1339 case Instruction::FAdd:
1340 case Instruction::Sub:
1341 case Instruction::FSub:
1342 case Instruction::Mul:
1343 case Instruction::FMul:
1344 case Instruction::UDiv:
1345 case Instruction::SDiv:
1346 case Instruction::FDiv:
1347 case Instruction::URem:
1348 case Instruction::SRem:
1349 case Instruction::FRem:
1350 case Instruction::Shl:
1351 case Instruction::LShr:
1352 case Instruction::AShr:
1353 case Instruction::And:
1354 case Instruction::Or:
1355 case Instruction::Xor: {
1356 // Just widen binops.
1357 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
1358 Value *A = getVectorValue(it->getOperand(0));
1359 Value *B = getVectorValue(it->getOperand(1));
1361 // Use this vector value for all users of the original instruction.
1362 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A, B);
1365 // Update the NSW, NUW and Exact flags.
1366 BinaryOperator *VecOp = cast<BinaryOperator>(V);
1367 if (isa<OverflowingBinaryOperator>(BinOp)) {
1368 VecOp->setHasNoSignedWrap(BinOp->hasNoSignedWrap());
1369 VecOp->setHasNoUnsignedWrap(BinOp->hasNoUnsignedWrap());
1371 if (isa<PossiblyExactOperator>(VecOp))
1372 VecOp->setIsExact(BinOp->isExact());
1375 case Instruction::Select: {
1377 // If the selector is loop invariant we can create a select
1378 // instruction with a scalar condition. Otherwise, use vector-select.
1379 Value *Cond = it->getOperand(0);
1380 bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(Cond), OrigLoop);
1382 // The condition can be loop invariant but still defined inside the
1383 // loop. This means that we can't just use the original 'cond' value.
1384 // We have to take the 'vectorized' value and pick the first lane.
1385 // Instcombine will make this a no-op.
1386 Cond = getVectorValue(Cond);
1388 Cond = Builder.CreateExtractElement(Cond, Builder.getInt32(0));
1390 Value *Op0 = getVectorValue(it->getOperand(1));
1391 Value *Op1 = getVectorValue(it->getOperand(2));
1392 WidenMap[it] = Builder.CreateSelect(Cond, Op0, Op1);
1396 case Instruction::ICmp:
1397 case Instruction::FCmp: {
1398 // Widen compares. Generate vector compares.
1399 bool FCmp = (it->getOpcode() == Instruction::FCmp);
1400 CmpInst *Cmp = dyn_cast<CmpInst>(it);
1401 Value *A = getVectorValue(it->getOperand(0));
1402 Value *B = getVectorValue(it->getOperand(1));
1404 WidenMap[it] = Builder.CreateFCmp(Cmp->getPredicate(), A, B);
1406 WidenMap[it] = Builder.CreateICmp(Cmp->getPredicate(), A, B);
1410 case Instruction::Store: {
1411 // Attempt to issue a wide store.
1412 StoreInst *SI = dyn_cast<StoreInst>(it);
1413 Type *StTy = VectorType::get(SI->getValueOperand()->getType(), VF);
1414 Value *Ptr = SI->getPointerOperand();
1415 unsigned Alignment = SI->getAlignment();
1417 assert(!Legal->isUniform(Ptr) &&
1418 "We do not allow storing to uniform addresses");
1420 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1422 // This store does not use GEPs.
1423 if (!Legal->isConsecutivePtr(Ptr)) {
1424 scalarizeInstruction(it);
1429 // The last index does not have to be the induction. It can be
1430 // consecutive and be a function of the index. For example A[I+1];
1431 unsigned NumOperands = Gep->getNumOperands();
1432 Value *LastIndex = getVectorValue(Gep->getOperand(NumOperands - 1));
1433 LastIndex = Builder.CreateExtractElement(LastIndex, Zero);
1435 // Create the new GEP with the new induction variable.
1436 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1437 Gep2->setOperand(NumOperands - 1, LastIndex);
1438 Ptr = Builder.Insert(Gep2);
1440 // Use the induction element ptr.
1441 assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1442 Ptr = Builder.CreateExtractElement(getVectorValue(Ptr), Zero);
1444 Ptr = Builder.CreateBitCast(Ptr, StTy->getPointerTo());
1445 Value *Val = getVectorValue(SI->getValueOperand());
1446 Builder.CreateStore(Val, Ptr)->setAlignment(Alignment);
1449 case Instruction::Load: {
1450 // Attempt to issue a wide load.
1451 LoadInst *LI = dyn_cast<LoadInst>(it);
1452 Type *RetTy = VectorType::get(LI->getType(), VF);
1453 Value *Ptr = LI->getPointerOperand();
1454 unsigned Alignment = LI->getAlignment();
1455 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1457 // If the pointer is loop invariant or if it is non consecutive,
1458 // scalarize the load.
1459 bool Con = Legal->isConsecutivePtr(Ptr);
1460 if (Legal->isUniform(Ptr) || !Con) {
1461 scalarizeInstruction(it);
1466 // The last index does not have to be the induction. It can be
1467 // consecutive and be a function of the index. For example A[I+1];
1468 unsigned NumOperands = Gep->getNumOperands();
1469 Value *LastIndex = getVectorValue(Gep->getOperand(NumOperands -1));
1470 LastIndex = Builder.CreateExtractElement(LastIndex, Zero);
1472 // Create the new GEP with the new induction variable.
1473 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1474 Gep2->setOperand(NumOperands - 1, LastIndex);
1475 Ptr = Builder.Insert(Gep2);
1477 // Use the induction element ptr.
1478 assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1479 Ptr = Builder.CreateExtractElement(getVectorValue(Ptr), Zero);
1482 Ptr = Builder.CreateBitCast(Ptr, RetTy->getPointerTo());
1483 LI = Builder.CreateLoad(Ptr);
1484 LI->setAlignment(Alignment);
1485 // Use this vector value for all users of the load.
1489 case Instruction::ZExt:
1490 case Instruction::SExt:
1491 case Instruction::FPToUI:
1492 case Instruction::FPToSI:
1493 case Instruction::FPExt:
1494 case Instruction::PtrToInt:
1495 case Instruction::IntToPtr:
1496 case Instruction::SIToFP:
1497 case Instruction::UIToFP:
1498 case Instruction::Trunc:
1499 case Instruction::FPTrunc:
1500 case Instruction::BitCast: {
1501 /// Vectorize bitcasts.
1502 CastInst *CI = dyn_cast<CastInst>(it);
1503 Value *A = getVectorValue(it->getOperand(0));
1504 Type *DestTy = VectorType::get(CI->getType()->getScalarType(), VF);
1505 WidenMap[it] = Builder.CreateCast(CI->getOpcode(), A, DestTy);
1510 /// All other instructions are unsupported. Scalarize them.
1511 scalarizeInstruction(it);
1514 }// end of for_each instr.
1518 void InnerLoopVectorizer::updateAnalysis() {
1519 // Forget the original basic block.
1520 SE->forgetLoop(OrigLoop);
1522 // Update the dominator tree information.
1523 assert(DT->properlyDominates(LoopBypassBlock, LoopExitBlock) &&
1524 "Entry does not dominate exit.");
1526 DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlock);
1527 DT->addNewBlock(LoopVectorBody, LoopVectorPreHeader);
1528 DT->addNewBlock(LoopMiddleBlock, LoopBypassBlock);
1529 DT->addNewBlock(LoopScalarPreHeader, LoopMiddleBlock);
1530 DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
1531 DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
1533 DEBUG(DT->verifyAnalysis());
1537 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
1538 if (!EnableIfConversion)
1541 assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
1542 std::vector<BasicBlock*> &LoopBlocks = TheLoop->getBlocksVector();
1544 // Collect the blocks that need predication.
1545 for (unsigned i = 0, e = LoopBlocks.size(); i < e; ++i) {
1546 BasicBlock *BB = LoopBlocks[i];
1548 // We must have at most two predecessors because we need to convert
1549 // all PHIs to selects.
1550 unsigned Preds = std::distance(pred_begin(BB), pred_end(BB));
1554 // We must be able to predicate all blocks that need to be predicated.
1555 if (blockNeedsPredication(BB) && !blockCanBePredicated(BB))
1559 // We can if-convert this loop.
1563 bool LoopVectorizationLegality::canVectorize() {
1564 assert(TheLoop->getLoopPreheader() && "No preheader!!");
1566 // We can only vectorize innermost loops.
1567 if (TheLoop->getSubLoopsVector().size())
1570 // We must have a single backedge.
1571 if (TheLoop->getNumBackEdges() != 1)
1574 // We must have a single exiting block.
1575 if (!TheLoop->getExitingBlock())
1578 unsigned NumBlocks = TheLoop->getNumBlocks();
1580 // Check if we can if-convert non single-bb loops.
1581 if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
1582 DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
1586 // We need to have a loop header.
1587 BasicBlock *Latch = TheLoop->getLoopLatch();
1588 DEBUG(dbgs() << "LV: Found a loop: " <<
1589 TheLoop->getHeader()->getName() << "\n");
1591 // ScalarEvolution needs to be able to find the exit count.
1592 const SCEV *ExitCount = SE->getExitCount(TheLoop, Latch);
1593 if (ExitCount == SE->getCouldNotCompute()) {
1594 DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
1598 // Do not loop-vectorize loops with a tiny trip count.
1599 unsigned TC = SE->getSmallConstantTripCount(TheLoop, Latch);
1600 if (TC > 0u && TC < TinyTripCountThreshold) {
1601 DEBUG(dbgs() << "LV: Found a loop with a very small trip count. " <<
1602 "This loop is not worth vectorizing.\n");
1606 // Check if we can vectorize the instructions and CFG in this loop.
1607 if (!canVectorizeInstrs()) {
1608 DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
1612 // Go over each instruction and look at memory deps.
1613 if (!canVectorizeMemory()) {
1614 DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
1618 // Collect all of the variables that remain uniform after vectorization.
1619 collectLoopUniforms();
1621 DEBUG(dbgs() << "LV: We can vectorize this loop" <<
1622 (PtrRtCheck.Need ? " (with a runtime bound check)" : "")
1625 // Okay! We can vectorize. At this point we don't have any other mem analysis
1626 // which may limit our maximum vectorization factor, so just return true with
1631 bool LoopVectorizationLegality::canVectorizeInstrs() {
1632 BasicBlock *PreHeader = TheLoop->getLoopPreheader();
1633 BasicBlock *Header = TheLoop->getHeader();
1635 // For each block in the loop.
1636 for (Loop::block_iterator bb = TheLoop->block_begin(),
1637 be = TheLoop->block_end(); bb != be; ++bb) {
1639 // Scan the instructions in the block and look for hazards.
1640 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
1643 if (PHINode *Phi = dyn_cast<PHINode>(it)) {
1644 // This should not happen because the loop should be normalized.
1645 if (Phi->getNumIncomingValues() != 2) {
1646 DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
1650 // If this PHINode is not in the header block, then we know that we
1651 // can convert it to select during if-conversion.
1655 // This is the value coming from the preheader.
1656 Value *StartValue = Phi->getIncomingValueForBlock(PreHeader);
1658 // We only look at integer and pointer phi nodes.
1659 if (Phi->getType()->isPointerTy() && isInductionVariable(Phi)) {
1660 DEBUG(dbgs() << "LV: Found a pointer induction variable.\n");
1661 Inductions[Phi] = StartValue;
1663 } else if (!Phi->getType()->isIntegerTy()) {
1664 DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
1668 // Handle integer PHIs:
1669 if (isInductionVariable(Phi)) {
1671 DEBUG(dbgs() << "LV: Found too many inductions."<< *Phi <<"\n");
1674 DEBUG(dbgs() << "LV: Found the induction PHI."<< *Phi <<"\n");
1676 Inductions[Phi] = StartValue;
1679 if (AddReductionVar(Phi, IntegerAdd)) {
1680 DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
1683 if (AddReductionVar(Phi, IntegerMult)) {
1684 DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n");
1687 if (AddReductionVar(Phi, IntegerOr)) {
1688 DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n");
1691 if (AddReductionVar(Phi, IntegerAnd)) {
1692 DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n");
1695 if (AddReductionVar(Phi, IntegerXor)) {
1696 DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n");
1700 DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
1702 }// end of PHI handling
1704 // We still don't handle functions.
1705 CallInst *CI = dyn_cast<CallInst>(it);
1707 DEBUG(dbgs() << "LV: Found a call site.\n");
1711 // We do not re-vectorize vectors.
1712 if (!VectorType::isValidElementType(it->getType()) &&
1713 !it->getType()->isVoidTy()) {
1714 DEBUG(dbgs() << "LV: Found unvectorizable type." << "\n");
1718 // Reduction instructions are allowed to have exit users.
1719 // All other instructions must not have external users.
1720 if (!AllowedExit.count(it))
1721 //Check that all of the users of the loop are inside the BB.
1722 for (Value::use_iterator I = it->use_begin(), E = it->use_end();
1724 Instruction *U = cast<Instruction>(*I);
1725 // This user may be a reduction exit value.
1726 if (!TheLoop->contains(U)) {
1727 DEBUG(dbgs() << "LV: Found an outside user for : "<< *U << "\n");
1736 DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
1737 assert(getInductionVars()->size() && "No induction variables");
1743 void LoopVectorizationLegality::collectLoopUniforms() {
1744 // We now know that the loop is vectorizable!
1745 // Collect variables that will remain uniform after vectorization.
1746 std::vector<Value*> Worklist;
1747 BasicBlock *Latch = TheLoop->getLoopLatch();
1749 // Start with the conditional branch and walk up the block.
1750 Worklist.push_back(Latch->getTerminator()->getOperand(0));
1752 while (Worklist.size()) {
1753 Instruction *I = dyn_cast<Instruction>(Worklist.back());
1754 Worklist.pop_back();
1756 // Look at instructions inside this loop.
1757 // Stop when reaching PHI nodes.
1758 // TODO: we need to follow values all over the loop, not only in this block.
1759 if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
1762 // This is a known uniform.
1765 // Insert all operands.
1766 for (int i = 0, Op = I->getNumOperands(); i < Op; ++i) {
1767 Worklist.push_back(I->getOperand(i));
1772 bool LoopVectorizationLegality::canVectorizeMemory() {
1773 typedef SmallVector<Value*, 16> ValueVector;
1774 typedef SmallPtrSet<Value*, 16> ValueSet;
1775 // Holds the Load and Store *instructions*.
1778 PtrRtCheck.Pointers.clear();
1779 PtrRtCheck.Need = false;
1782 for (Loop::block_iterator bb = TheLoop->block_begin(),
1783 be = TheLoop->block_end(); bb != be; ++bb) {
1785 // Scan the BB and collect legal loads and stores.
1786 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
1789 // If this is a load, save it. If this instruction can read from memory
1790 // but is not a load, then we quit. Notice that we don't handle function
1791 // calls that read or write.
1792 if (it->mayReadFromMemory()) {
1793 LoadInst *Ld = dyn_cast<LoadInst>(it);
1794 if (!Ld) return false;
1795 if (!Ld->isSimple()) {
1796 DEBUG(dbgs() << "LV: Found a non-simple load.\n");
1799 Loads.push_back(Ld);
1803 // Save 'store' instructions. Abort if other instructions write to memory.
1804 if (it->mayWriteToMemory()) {
1805 StoreInst *St = dyn_cast<StoreInst>(it);
1806 if (!St) return false;
1807 if (!St->isSimple()) {
1808 DEBUG(dbgs() << "LV: Found a non-simple store.\n");
1811 Stores.push_back(St);
1816 // Now we have two lists that hold the loads and the stores.
1817 // Next, we find the pointers that they use.
1819 // Check if we see any stores. If there are no stores, then we don't
1820 // care if the pointers are *restrict*.
1821 if (!Stores.size()) {
1822 DEBUG(dbgs() << "LV: Found a read-only loop!\n");
1826 // Holds the read and read-write *pointers* that we find.
1828 ValueVector ReadWrites;
1830 // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
1831 // multiple times on the same object. If the ptr is accessed twice, once
1832 // for read and once for write, it will only appear once (on the write
1833 // list). This is okay, since we are going to check for conflicts between
1834 // writes and between reads and writes, but not between reads and reads.
1837 ValueVector::iterator I, IE;
1838 for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
1839 StoreInst *ST = dyn_cast<StoreInst>(*I);
1840 assert(ST && "Bad StoreInst");
1841 Value* Ptr = ST->getPointerOperand();
1843 if (isUniform(Ptr)) {
1844 DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
1848 // If we did *not* see this pointer before, insert it to
1849 // the read-write list. At this phase it is only a 'write' list.
1850 if (Seen.insert(Ptr))
1851 ReadWrites.push_back(Ptr);
1854 for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
1855 LoadInst *LD = dyn_cast<LoadInst>(*I);
1856 assert(LD && "Bad LoadInst");
1857 Value* Ptr = LD->getPointerOperand();
1858 // If we did *not* see this pointer before, insert it to the
1859 // read list. If we *did* see it before, then it is already in
1860 // the read-write list. This allows us to vectorize expressions
1861 // such as A[i] += x; Because the address of A[i] is a read-write
1862 // pointer. This only works if the index of A[i] is consecutive.
1863 // If the address of i is unknown (for example A[B[i]]) then we may
1864 // read a few words, modify, and write a few words, and some of the
1865 // words may be written to the same address.
1866 if (Seen.insert(Ptr) || !isConsecutivePtr(Ptr))
1867 Reads.push_back(Ptr);
1870 // If we write (or read-write) to a single destination and there are no
1871 // other reads in this loop then is it safe to vectorize.
1872 if (ReadWrites.size() == 1 && Reads.size() == 0) {
1873 DEBUG(dbgs() << "LV: Found a write-only loop!\n");
1877 // Find pointers with computable bounds. We are going to use this information
1878 // to place a runtime bound check.
1880 for (I = ReadWrites.begin(), IE = ReadWrites.end(); I != IE; ++I)
1881 if (hasComputableBounds(*I)) {
1882 PtrRtCheck.insert(SE, TheLoop, *I);
1883 DEBUG(dbgs() << "LV: Found a runtime check ptr:" << **I <<"\n");
1888 for (I = Reads.begin(), IE = Reads.end(); I != IE; ++I)
1889 if (hasComputableBounds(*I)) {
1890 PtrRtCheck.insert(SE, TheLoop, *I);
1891 DEBUG(dbgs() << "LV: Found a runtime check ptr:" << **I <<"\n");
1897 // Check that we did not collect too many pointers or found a
1898 // unsizeable pointer.
1899 if (!RT || PtrRtCheck.Pointers.size() > RuntimeMemoryCheckThreshold) {
1904 PtrRtCheck.Need = RT;
1907 DEBUG(dbgs() << "LV: We can perform a memory runtime check if needed.\n");
1910 // Now that the pointers are in two lists (Reads and ReadWrites), we
1911 // can check that there are no conflicts between each of the writes and
1912 // between the writes to the reads.
1913 ValueSet WriteObjects;
1914 ValueVector TempObjects;
1916 // Check that the read-writes do not conflict with other read-write
1918 for (I = ReadWrites.begin(), IE = ReadWrites.end(); I != IE; ++I) {
1919 GetUnderlyingObjects(*I, TempObjects, DL);
1920 for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end();
1922 if (!isIdentifiedObject(*it)) {
1923 DEBUG(dbgs() << "LV: Found an unidentified write ptr:"<< **it <<"\n");
1926 if (!WriteObjects.insert(*it)) {
1927 DEBUG(dbgs() << "LV: Found a possible write-write reorder:"
1932 TempObjects.clear();
1935 /// Check that the reads don't conflict with the read-writes.
1936 for (I = Reads.begin(), IE = Reads.end(); I != IE; ++I) {
1937 GetUnderlyingObjects(*I, TempObjects, DL);
1938 for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end();
1940 if (!isIdentifiedObject(*it)) {
1941 DEBUG(dbgs() << "LV: Found an unidentified read ptr:"<< **it <<"\n");
1944 if (WriteObjects.count(*it)) {
1945 DEBUG(dbgs() << "LV: Found a possible read/write reorder:"
1950 TempObjects.clear();
1953 // It is safe to vectorize and we don't need any runtime checks.
1954 DEBUG(dbgs() << "LV: We don't need a runtime memory check.\n");
1959 bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi,
1960 ReductionKind Kind) {
1961 if (Phi->getNumIncomingValues() != 2)
1964 // Find the possible incoming reduction variable.
1965 BasicBlock *BB = Phi->getParent();
1966 int SelfEdgeIdx = Phi->getBasicBlockIndex(BB);
1967 int InEdgeBlockIdx = (SelfEdgeIdx ? 0 : 1); // The other entry.
1968 Value *RdxStart = Phi->getIncomingValue(InEdgeBlockIdx);
1970 // ExitInstruction is the single value which is used outside the loop.
1971 // We only allow for a single reduction value to be used outside the loop.
1972 // This includes users of the reduction, variables (which form a cycle
1973 // which ends in the phi node).
1974 Instruction *ExitInstruction = 0;
1976 // Iter is our iterator. We start with the PHI node and scan for all of the
1977 // users of this instruction. All users must be instructions which can be
1978 // used as reduction variables (such as ADD). We may have a single
1979 // out-of-block user. They cycle must end with the original PHI.
1980 // Also, we can't have multiple block-local users.
1981 Instruction *Iter = Phi;
1983 // Any reduction instr must be of one of the allowed kinds.
1984 if (!isReductionInstr(Iter, Kind))
1987 // Did we found a user inside this block ?
1988 bool FoundInBlockUser = false;
1989 // Did we reach the initial PHI node ?
1990 bool FoundStartPHI = false;
1992 // If the instruction has no users then this is a broken
1993 // chain and can't be a reduction variable.
1994 if (Iter->use_empty())
1997 // For each of the *users* of iter.
1998 for (Value::use_iterator it = Iter->use_begin(), e = Iter->use_end();
2000 Instruction *U = cast<Instruction>(*it);
2001 // We already know that the PHI is a user.
2003 FoundStartPHI = true;
2006 // Check if we found the exit user.
2007 BasicBlock *Parent = U->getParent();
2009 // We must have a single exit instruction.
2010 if (ExitInstruction != 0)
2012 ExitInstruction = Iter;
2014 // We can't have multiple inside users.
2015 if (FoundInBlockUser)
2017 FoundInBlockUser = true;
2021 // We found a reduction var if we have reached the original
2022 // phi node and we only have a single instruction with out-of-loop
2024 if (FoundStartPHI && ExitInstruction) {
2025 // This instruction is allowed to have out-of-loop users.
2026 AllowedExit.insert(ExitInstruction);
2028 // Save the description of this reduction variable.
2029 ReductionDescriptor RD(RdxStart, ExitInstruction, Kind);
2030 Reductions[Phi] = RD;
2037 LoopVectorizationLegality::isReductionInstr(Instruction *I,
2038 ReductionKind Kind) {
2039 switch (I->getOpcode()) {
2042 case Instruction::PHI:
2045 case Instruction::Add:
2046 case Instruction::Sub:
2047 return Kind == IntegerAdd;
2048 case Instruction::Mul:
2049 return Kind == IntegerMult;
2050 case Instruction::And:
2051 return Kind == IntegerAnd;
2052 case Instruction::Or:
2053 return Kind == IntegerOr;
2054 case Instruction::Xor:
2055 return Kind == IntegerXor;
2059 bool LoopVectorizationLegality::isInductionVariable(PHINode *Phi) {
2060 Type *PhiTy = Phi->getType();
2061 // We only handle integer and pointer inductions variables.
2062 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
2065 // Check that the PHI is consecutive and starts at zero.
2066 const SCEV *PhiScev = SE->getSCEV(Phi);
2067 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
2069 DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
2072 const SCEV *Step = AR->getStepRecurrence(*SE);
2074 // Integer inductions need to have a stride of one.
2075 if (PhiTy->isIntegerTy())
2076 return Step->isOne();
2078 // Calculate the pointer stride and check if it is consecutive.
2079 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
2080 if (!C) return false;
2082 assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
2083 uint64_t Size = DL->getTypeAllocSize(PhiTy->getPointerElementType());
2084 return (C->getValue()->equalsInt(Size));
2087 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) {
2088 assert(TheLoop->contains(BB) && "Unknown block used");
2090 // Blocks that do not dominate the latch need predication.
2091 BasicBlock* Latch = TheLoop->getLoopLatch();
2092 return !DT->dominates(BB, Latch);
2095 bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB) {
2096 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2097 // We don't predicate loads/stores at the moment.
2098 if (it->mayReadFromMemory() || it->mayWriteToMemory() || it->mayThrow())
2101 // The isntructions below can trap.
2102 switch (it->getOpcode()) {
2104 case Instruction::UDiv:
2105 case Instruction::SDiv:
2106 case Instruction::URem:
2107 case Instruction::SRem:
2115 bool LoopVectorizationLegality::hasComputableBounds(Value *Ptr) {
2116 const SCEV *PhiScev = SE->getSCEV(Ptr);
2117 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
2121 return AR->isAffine();
2125 LoopVectorizationCostModel::findBestVectorizationFactor(unsigned VF) {
2127 DEBUG(dbgs() << "LV: No vector target information. Not vectorizing. \n");
2131 float Cost = expectedCost(1);
2133 DEBUG(dbgs() << "LV: Scalar loop costs: "<< (int)Cost << ".\n");
2134 for (unsigned i=2; i <= VF; i*=2) {
2135 // Notice that the vector loop needs to be executed less times, so
2136 // we need to divide the cost of the vector loops by the width of
2137 // the vector elements.
2138 float VectorCost = expectedCost(i) / (float)i;
2139 DEBUG(dbgs() << "LV: Vector loop of width "<< i << " costs: " <<
2140 (int)VectorCost << ".\n");
2141 if (VectorCost < Cost) {
2147 DEBUG(dbgs() << "LV: Selecting VF = : "<< Width << ".\n");
2151 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
2155 for (Loop::block_iterator bb = TheLoop->block_begin(),
2156 be = TheLoop->block_end(); bb != be; ++bb) {
2157 unsigned BlockCost = 0;
2158 BasicBlock *BB = *bb;
2160 // For each instruction in the old loop.
2161 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2162 unsigned C = getInstructionCost(it, VF);
2164 DEBUG(dbgs() << "LV: Found an estimated cost of "<< C <<" for VF " <<
2165 VF << " For instruction: "<< *it << "\n");
2168 // We assume that if-converted blocks have a 50% chance of being executed.
2169 // When the code is scalar then some of the blocks are avoided due to CF.
2170 // When the code is vectorized we execute all code paths.
2171 if (Legal->blockNeedsPredication(*bb) && VF == 1)
2181 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
2182 assert(VTTI && "Invalid vector target transformation info");
2184 // If we know that this instruction will remain uniform, check the cost of
2185 // the scalar version.
2186 if (Legal->isUniformAfterVectorization(I))
2189 Type *RetTy = I->getType();
2190 Type *VectorTy = ToVectorTy(RetTy, VF);
2193 // TODO: We need to estimate the cost of intrinsic calls.
2194 switch (I->getOpcode()) {
2195 case Instruction::GetElementPtr:
2196 // We mark this instruction as zero-cost because scalar GEPs are usually
2197 // lowered to the intruction addressing mode. At the moment we don't
2198 // generate vector geps.
2200 case Instruction::Br: {
2201 return VTTI->getCFInstrCost(I->getOpcode());
2203 case Instruction::PHI:
2204 //TODO: IF-converted IFs become selects.
2206 case Instruction::Add:
2207 case Instruction::FAdd:
2208 case Instruction::Sub:
2209 case Instruction::FSub:
2210 case Instruction::Mul:
2211 case Instruction::FMul:
2212 case Instruction::UDiv:
2213 case Instruction::SDiv:
2214 case Instruction::FDiv:
2215 case Instruction::URem:
2216 case Instruction::SRem:
2217 case Instruction::FRem:
2218 case Instruction::Shl:
2219 case Instruction::LShr:
2220 case Instruction::AShr:
2221 case Instruction::And:
2222 case Instruction::Or:
2223 case Instruction::Xor:
2224 return VTTI->getArithmeticInstrCost(I->getOpcode(), VectorTy);
2225 case Instruction::Select: {
2226 SelectInst *SI = cast<SelectInst>(I);
2227 const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
2228 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
2229 Type *CondTy = SI->getCondition()->getType();
2231 CondTy = VectorType::get(CondTy, VF);
2233 return VTTI->getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
2235 case Instruction::ICmp:
2236 case Instruction::FCmp: {
2237 Type *ValTy = I->getOperand(0)->getType();
2238 VectorTy = ToVectorTy(ValTy, VF);
2239 return VTTI->getCmpSelInstrCost(I->getOpcode(), VectorTy);
2241 case Instruction::Store: {
2242 StoreInst *SI = cast<StoreInst>(I);
2243 Type *ValTy = SI->getValueOperand()->getType();
2244 VectorTy = ToVectorTy(ValTy, VF);
2247 return VTTI->getMemoryOpCost(I->getOpcode(), ValTy,
2248 SI->getAlignment(), SI->getPointerAddressSpace());
2250 // Scalarized stores.
2251 if (!Legal->isConsecutivePtr(SI->getPointerOperand())) {
2253 unsigned ExtCost = VTTI->getInstrCost(Instruction::ExtractElement,
2255 // The cost of extracting from the value vector.
2256 Cost += VF * (ExtCost);
2257 // The cost of the scalar stores.
2258 Cost += VF * VTTI->getMemoryOpCost(I->getOpcode(),
2259 ValTy->getScalarType(),
2261 SI->getPointerAddressSpace());
2266 return VTTI->getMemoryOpCost(I->getOpcode(), VectorTy, SI->getAlignment(),
2267 SI->getPointerAddressSpace());
2269 case Instruction::Load: {
2270 LoadInst *LI = cast<LoadInst>(I);
2273 return VTTI->getMemoryOpCost(I->getOpcode(), RetTy,
2275 LI->getPointerAddressSpace());
2277 // Scalarized loads.
2278 if (!Legal->isConsecutivePtr(LI->getPointerOperand())) {
2280 unsigned InCost = VTTI->getInstrCost(Instruction::InsertElement, RetTy);
2281 // The cost of inserting the loaded value into the result vector.
2282 Cost += VF * (InCost);
2283 // The cost of the scalar stores.
2284 Cost += VF * VTTI->getMemoryOpCost(I->getOpcode(),
2285 RetTy->getScalarType(),
2287 LI->getPointerAddressSpace());
2292 return VTTI->getMemoryOpCost(I->getOpcode(), VectorTy, LI->getAlignment(),
2293 LI->getPointerAddressSpace());
2295 case Instruction::ZExt:
2296 case Instruction::SExt:
2297 case Instruction::FPToUI:
2298 case Instruction::FPToSI:
2299 case Instruction::FPExt:
2300 case Instruction::PtrToInt:
2301 case Instruction::IntToPtr:
2302 case Instruction::SIToFP:
2303 case Instruction::UIToFP:
2304 case Instruction::Trunc:
2305 case Instruction::FPTrunc:
2306 case Instruction::BitCast: {
2307 Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
2308 return VTTI->getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
2311 // We are scalarizing the instruction. Return the cost of the scalar
2312 // instruction, plus the cost of insert and extract into vector
2313 // elements, times the vector width.
2316 bool IsVoid = RetTy->isVoidTy();
2318 unsigned InsCost = (IsVoid ? 0 :
2319 VTTI->getInstrCost(Instruction::InsertElement,
2322 unsigned ExtCost = VTTI->getInstrCost(Instruction::ExtractElement,
2325 // The cost of inserting the results plus extracting each one of the
2327 Cost += VF * (InsCost + ExtCost * I->getNumOperands());
2329 // The cost of executing VF copies of the scalar instruction.
2330 Cost += VF * VTTI->getInstrCost(I->getOpcode(), RetTy);
2336 Type* LoopVectorizationCostModel::ToVectorTy(Type *Scalar, unsigned VF) {
2337 if (Scalar->isVoidTy() || VF == 1)
2339 return VectorType::get(Scalar, VF);
2344 char LoopVectorize::ID = 0;
2345 static const char lv_name[] = "Loop Vectorization";
2346 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
2347 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
2348 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
2349 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
2350 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
2353 Pass *createLoopVectorizePass() {
2354 return new LoopVectorize();