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. SingleBlockLoopVectorizer - 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.
28 //===----------------------------------------------------------------------===//
30 // The reduction-variable vectorization is based on the paper:
31 // D. Nuzman and R. Henderson. Multi-platform Auto-vectorization.
33 // Variable uniformity checks are inspired by:
34 // Karrenberg, R. and Hack, S. Whole Function Vectorization.
36 // Other ideas/concepts are from:
37 // A. Zaks and D. Nuzman. Autovectorization in GCC-two years later.
39 //===----------------------------------------------------------------------===//
40 #define LV_NAME "loop-vectorize"
41 #define DEBUG_TYPE LV_NAME
42 #include "llvm/Constants.h"
43 #include "llvm/DerivedTypes.h"
44 #include "llvm/Instructions.h"
45 #include "llvm/LLVMContext.h"
46 #include "llvm/Pass.h"
47 #include "llvm/Analysis/LoopPass.h"
48 #include "llvm/Value.h"
49 #include "llvm/Function.h"
50 #include "llvm/Analysis/Verifier.h"
51 #include "llvm/Module.h"
52 #include "llvm/Type.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/ScalarEvolution.h"
58 #include "llvm/Analysis/Dominators.h"
59 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
60 #include "llvm/Analysis/ScalarEvolutionExpander.h"
61 #include "llvm/Analysis/LoopInfo.h"
62 #include "llvm/Analysis/ValueTracking.h"
63 #include "llvm/Transforms/Scalar.h"
64 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
65 #include "llvm/TargetTransformInfo.h"
66 #include "llvm/Support/CommandLine.h"
67 #include "llvm/Support/Debug.h"
68 #include "llvm/Support/raw_ostream.h"
69 #include "llvm/DataLayout.h"
70 #include "llvm/Transforms/Utils/Local.h"
74 static cl::opt<unsigned>
75 VectorizationFactor("force-vector-width", cl::init(0), cl::Hidden,
76 cl::desc("Set the default vectorization width. Zero is autoselect."));
78 /// We don't vectorize loops with a known constant trip count below this number.
79 const int TinyTripCountThreshold = 16;
83 // Forward declarations.
84 class LoopVectorizationLegality;
85 class LoopVectorizationCostModel;
87 /// SingleBlockLoopVectorizer vectorizes loops which contain only one basic
88 /// block to a specified vectorization factor (VF).
89 /// This class performs the widening of scalars into vectors, or multiple
90 /// scalars. This class also implements the following features:
91 /// * It inserts an epilogue loop for handling loops that don't have iteration
92 /// counts that are known to be a multiple of the vectorization factor.
93 /// * It handles the code generation for reduction variables.
94 /// * Scalarization (implementation using scalars) of un-vectorizable
96 /// SingleBlockLoopVectorizer does not perform any vectorization-legality
97 /// checks, and relies on the caller to check for the different legality
98 /// aspects. The SingleBlockLoopVectorizer relies on the
99 /// LoopVectorizationLegality class to provide information about the induction
100 /// and reduction variables that were found to a given vectorization factor.
101 class SingleBlockLoopVectorizer {
104 SingleBlockLoopVectorizer(Loop *Orig, ScalarEvolution *Se, LoopInfo *Li,
105 DominatorTree *dt, LPPassManager *Lpm,
107 OrigLoop(Orig), SE(Se), LI(Li), DT(dt), LPM(Lpm), VF(VecWidth),
108 Builder(Se->getContext()), Induction(0), OldInduction(0) { }
110 // Perform the actual loop widening (vectorization).
111 void vectorize(LoopVectorizationLegality *Legal) {
112 ///Create a new empty loop. Unlink the old loop and connect the new one.
113 createEmptyLoop(Legal);
114 /// Widen each instruction in the old loop to a new one in the new loop.
115 /// Use the Legality module to find the induction and reduction variables.
116 vectorizeLoop(Legal);
117 // register the new loop.
122 /// Create an empty loop, based on the loop ranges of the old loop.
123 void createEmptyLoop(LoopVectorizationLegality *Legal);
124 /// Copy and widen the instructions from the old loop.
125 void vectorizeLoop(LoopVectorizationLegality *Legal);
126 /// Insert the new loop to the loop hierarchy and pass manager.
127 void updateAnalysis();
129 /// This instruction is un-vectorizable. Implement it as a sequence
131 void scalarizeInstruction(Instruction *Instr);
133 /// Create a broadcast instruction. This method generates a broadcast
134 /// instruction (shuffle) for loop invariant values and for the induction
135 /// value. If this is the induction variable then we extend it to N, N+1, ...
136 /// this is needed because each iteration in the loop corresponds to a SIMD
138 Value *getBroadcastInstrs(Value *V);
140 /// This is a helper function used by getBroadcastInstrs. It adds 0, 1, 2 ..
141 /// for each element in the vector. Starting from zero.
142 Value *getConsecutiveVector(Value* Val);
144 /// When we go over instructions in the basic block we rely on previous
145 /// values within the current basic block or on loop invariant values.
146 /// When we widen (vectorize) values we place them in the map. If the values
147 /// are not within the map, they have to be loop invariant, so we simply
148 /// broadcast them into a vector.
149 Value *getVectorValue(Value *V);
151 /// Get a uniform vector of constant integers. We use this to get
152 /// vectors of ones and zeros for the reduction code.
153 Constant* getUniformVector(unsigned Val, Type* ScalarTy);
155 typedef DenseMap<Value*, Value*> ValueMap;
157 /// The original loop.
159 // Scev analysis to use.
165 // Loop Pass Manager;
167 // The vectorization factor to use.
170 // The builder that we use
173 // --- Vectorization state ---
175 /// The vector-loop preheader.
176 BasicBlock *LoopVectorPreHeader;
177 /// The scalar-loop preheader.
178 BasicBlock *LoopScalarPreHeader;
179 /// Middle Block between the vector and the scalar.
180 BasicBlock *LoopMiddleBlock;
181 ///The ExitBlock of the scalar loop.
182 BasicBlock *LoopExitBlock;
183 ///The vector loop body.
184 BasicBlock *LoopVectorBody;
185 ///The scalar loop body.
186 BasicBlock *LoopScalarBody;
187 ///The first bypass block.
188 BasicBlock *LoopBypassBlock;
190 /// The new Induction variable which was added to the new block.
192 /// The induction variable of the old basic block.
193 PHINode *OldInduction;
194 // Maps scalars to widened vectors.
198 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
199 /// to what vectorization factor.
200 /// This class does not look at the profitability of vectorization, only the
201 /// legality. This class has two main kinds of checks:
202 /// * Memory checks - The code in canVectorizeMemory checks if vectorization
203 /// will change the order of memory accesses in a way that will change the
204 /// correctness of the program.
205 /// * Scalars checks - The code in canVectorizeBlock checks for a number
206 /// of different conditions, such as the availability of a single induction
207 /// variable, that all types are supported and vectorize-able, etc.
208 /// This code reflects the capabilities of SingleBlockLoopVectorizer.
209 /// This class is also used by SingleBlockLoopVectorizer for identifying
210 /// induction variable and the different reduction variables.
211 class LoopVectorizationLegality {
213 LoopVectorizationLegality(Loop *Lp, ScalarEvolution *Se, DataLayout *Dl):
214 TheLoop(Lp), SE(Se), DL(Dl), Induction(0) { }
216 /// This represents the kinds of reductions that we support.
218 NoReduction, /// Not a reduction.
219 IntegerAdd, /// Sum of numbers.
220 IntegerMult, /// Product of numbers.
221 IntegerOr, /// Bitwise or logical OR of numbers.
222 IntegerAnd, /// Bitwise or logical AND of numbers.
223 IntegerXor /// Bitwise or logical XOR of numbers.
226 /// This POD struct holds information about reduction variables.
227 struct ReductionDescriptor {
229 ReductionDescriptor():
230 StartValue(0), LoopExitInstr(0), Kind(NoReduction) {}
233 ReductionDescriptor(Value *Start, Instruction *Exit, ReductionKind K):
234 StartValue(Start), LoopExitInstr(Exit), Kind(K) {}
236 // The starting value of the reduction.
237 // It does not have to be zero!
239 // The instruction who's value is used outside the loop.
240 Instruction *LoopExitInstr;
241 // The kind of the reduction.
245 /// ReductionList contains the reduction descriptors for all
246 /// of the reductions that were found in the loop.
247 typedef DenseMap<PHINode*, ReductionDescriptor> ReductionList;
249 /// Returns true if it is legal to vectorize this loop.
250 /// This does not mean that it is profitable to vectorize this
251 /// loop, only that it is legal to do so.
254 /// Returns the Induction variable.
255 PHINode *getInduction() {return Induction;}
257 /// Returns the reduction variables found in the loop.
258 ReductionList *getReductionVars() { return &Reductions; }
260 /// Check if the pointer returned by this GEP is consecutive
261 /// when the index is vectorized. This happens when the last
262 /// index of the GEP is consecutive, like the induction variable.
263 /// This check allows us to vectorize A[idx] into a wide load/store.
264 bool isConsecutiveGep(Value *Ptr);
266 /// Returns true if this instruction will remain scalar after vectorization.
267 bool isUniformAfterVectorization(Instruction* I) {return Uniforms.count(I);}
270 /// Check if a single basic block loop is vectorizable.
271 /// At this point we know that this is a loop with a constant trip count
272 /// and we only need to check individual instructions.
273 bool canVectorizeBlock(BasicBlock &BB);
275 /// When we vectorize loops we may change the order in which
276 /// we read and write from memory. This method checks if it is
277 /// legal to vectorize the code, considering only memory constrains.
278 /// Returns true if BB is vectorizable
279 bool canVectorizeMemory(BasicBlock &BB);
281 /// Returns True, if 'Phi' is the kind of reduction variable for type
282 /// 'Kind'. If this is a reduction variable, it adds it to ReductionList.
283 bool AddReductionVar(PHINode *Phi, ReductionKind Kind);
284 /// Returns true if the instruction I can be a reduction variable of type
286 bool isReductionInstr(Instruction *I, ReductionKind Kind);
287 /// Returns True, if 'Phi' is an induction variable.
288 bool isInductionVariable(PHINode *Phi);
290 /// The loop that we evaluate.
294 /// DataLayout analysis.
297 // --- vectorization state --- //
299 /// Holds the induction variable.
301 /// Holds the reduction variables.
302 ReductionList Reductions;
303 /// Allowed outside users. This holds the reduction
304 /// vars which can be accessed from outside the loop.
305 SmallPtrSet<Value*, 4> AllowedExit;
306 /// This set holds the variables which are known to be uniform after
308 SmallPtrSet<Instruction*, 4> Uniforms;
311 /// LoopVectorizationCostModel - estimates the expected speedups due to
313 /// In many cases vectorization is not profitable. This can happen because
314 /// of a number of reasons. In this class we mainly attempt to predict
315 /// the expected speedup/slowdowns due to the supported instruction set.
316 /// We use the VectorTargetTransformInfo to query the different backends
317 /// for the cost of different operations.
318 class LoopVectorizationCostModel {
321 LoopVectorizationCostModel(Loop *Lp, ScalarEvolution *Se,
322 LoopVectorizationLegality *Leg,
323 const VectorTargetTransformInfo *Vtti):
324 TheLoop(Lp), SE(Se), Legal(Leg), VTTI(Vtti) { }
326 /// Returns the most profitable vectorization factor for the loop that is
327 /// smaller or equal to the VF argument. This method checks every power
329 unsigned findBestVectorizationFactor(unsigned VF = 8);
332 /// Returns the expected execution cost. The unit of the cost does
333 /// not matter because we use the 'cost' units to compare different
334 /// vector widths. The cost that is returned is *not* normalized by
335 /// the factor width.
336 unsigned expectedCost(unsigned VF);
338 /// Returns the execution time cost of an instruction for a given vector
339 /// width. Vector width of one means scalar.
340 unsigned getInstructionCost(Instruction *I, unsigned VF);
342 /// A helper function for converting Scalar types to vector types.
343 /// If the incoming type is void, we return void. If the VF is 1, we return
345 static Type* ToVectorTy(Type *Scalar, unsigned VF);
347 /// The loop that we evaluate.
352 /// Vectorization legality.
353 LoopVectorizationLegality *Legal;
354 /// Vector target information.
355 const VectorTargetTransformInfo *VTTI;
358 struct LoopVectorize : public LoopPass {
359 static char ID; // Pass identification, replacement for typeid
361 LoopVectorize() : LoopPass(ID) {
362 initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
368 TargetTransformInfo *TTI;
371 virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
372 // We only vectorize innermost loops.
376 SE = &getAnalysis<ScalarEvolution>();
377 DL = getAnalysisIfAvailable<DataLayout>();
378 LI = &getAnalysis<LoopInfo>();
379 TTI = getAnalysisIfAvailable<TargetTransformInfo>();
380 DT = &getAnalysis<DominatorTree>();
382 DEBUG(dbgs() << "LV: Checking a loop in \"" <<
383 L->getHeader()->getParent()->getName() << "\"\n");
385 // Check if it is legal to vectorize the loop.
386 LoopVectorizationLegality LVL(L, SE, DL);
387 if (!LVL.canVectorize()) {
388 DEBUG(dbgs() << "LV: Not vectorizing.\n");
392 // Select the preffered vectorization factor.
394 if (VectorizationFactor == 0) {
395 const VectorTargetTransformInfo *VTTI = 0;
397 VTTI = TTI->getVectorTargetTransformInfo();
398 // Use the cost model.
399 LoopVectorizationCostModel CM(L, SE, &LVL, VTTI);
400 VF = CM.findBestVectorizationFactor();
403 DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
408 // Use the user command flag.
409 VF = VectorizationFactor;
412 DEBUG(dbgs() << "LV: Found a vectorizable loop ("<< VF << ") in "<<
413 L->getHeader()->getParent()->getParent()->getModuleIdentifier()<<
416 // If we decided that it is *legal* to vectorizer the loop then do it.
417 SingleBlockLoopVectorizer LB(L, SE, LI, DT, &LPM, VF);
420 DEBUG(verifyFunction(*L->getHeader()->getParent()));
424 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
425 LoopPass::getAnalysisUsage(AU);
426 AU.addRequiredID(LoopSimplifyID);
427 AU.addRequiredID(LCSSAID);
428 AU.addRequired<LoopInfo>();
429 AU.addRequired<ScalarEvolution>();
430 AU.addRequired<DominatorTree>();
431 AU.addPreserved<LoopInfo>();
432 AU.addPreserved<DominatorTree>();
437 Value *SingleBlockLoopVectorizer::getBroadcastInstrs(Value *V) {
438 // Instructions that access the old induction variable
439 // actually want to get the new one.
440 if (V == OldInduction)
443 LLVMContext &C = V->getContext();
444 Type *VTy = VectorType::get(V->getType(), VF);
445 Type *I32 = IntegerType::getInt32Ty(C);
446 Constant *Zero = ConstantInt::get(I32, 0);
447 Value *Zeros = ConstantAggregateZero::get(VectorType::get(I32, VF));
448 Value *UndefVal = UndefValue::get(VTy);
449 // Insert the value into a new vector.
450 Value *SingleElem = Builder.CreateInsertElement(UndefVal, V, Zero);
451 // Broadcast the scalar into all locations in the vector.
452 Value *Shuf = Builder.CreateShuffleVector(SingleElem, UndefVal, Zeros,
454 // We are accessing the induction variable. Make sure to promote the
455 // index for each consecutive SIMD lane. This adds 0,1,2 ... to all lanes.
457 return getConsecutiveVector(Shuf);
461 Value *SingleBlockLoopVectorizer::getConsecutiveVector(Value* Val) {
462 assert(Val->getType()->isVectorTy() && "Must be a vector");
463 assert(Val->getType()->getScalarType()->isIntegerTy() &&
464 "Elem must be an integer");
466 Type *ITy = Val->getType()->getScalarType();
467 VectorType *Ty = cast<VectorType>(Val->getType());
468 unsigned VLen = Ty->getNumElements();
469 SmallVector<Constant*, 8> Indices;
471 // Create a vector of consecutive numbers from zero to VF.
472 for (unsigned i = 0; i < VLen; ++i)
473 Indices.push_back(ConstantInt::get(ITy, i));
475 // Add the consecutive indices to the vector value.
476 Constant *Cv = ConstantVector::get(Indices);
477 assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
478 return Builder.CreateAdd(Val, Cv, "induction");
481 bool LoopVectorizationLegality::isConsecutiveGep(Value *Ptr) {
482 GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
486 unsigned NumOperands = Gep->getNumOperands();
487 Value *LastIndex = Gep->getOperand(NumOperands - 1);
489 // Check that all of the gep indices are uniform except for the last.
490 for (unsigned i = 0; i < NumOperands - 1; ++i)
491 if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
494 // We can emit wide load/stores only of the last index is the induction
496 const SCEV *Last = SE->getSCEV(LastIndex);
497 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
498 const SCEV *Step = AR->getStepRecurrence(*SE);
500 // The memory is consecutive because the last index is consecutive
501 // and all other indices are loop invariant.
509 Value *SingleBlockLoopVectorizer::getVectorValue(Value *V) {
510 assert(!V->getType()->isVectorTy() && "Can't widen a vector");
511 // If we saved a vectorized copy of V, use it.
512 Value *&MapEntry = WidenMap[V];
516 // Broadcast V and save the value for future uses.
517 Value *B = getBroadcastInstrs(V);
523 SingleBlockLoopVectorizer::getUniformVector(unsigned Val, Type* ScalarTy) {
524 SmallVector<Constant*, 8> Indices;
525 // Create a vector of consecutive numbers from zero to VF.
526 for (unsigned i = 0; i < VF; ++i)
527 Indices.push_back(ConstantInt::get(ScalarTy, Val, true));
529 // Add the consecutive indices to the vector value.
530 return ConstantVector::get(Indices);
533 void SingleBlockLoopVectorizer::scalarizeInstruction(Instruction *Instr) {
534 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
535 // Holds vector parameters or scalars, in case of uniform vals.
536 SmallVector<Value*, 8> Params;
538 // Find all of the vectorized parameters.
539 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
540 Value *SrcOp = Instr->getOperand(op);
542 // If we are accessing the old induction variable, use the new one.
543 if (SrcOp == OldInduction) {
544 Params.push_back(getBroadcastInstrs(Induction));
548 // Try using previously calculated values.
549 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
551 // If the src is an instruction that appeared earlier in the basic block
552 // then it should already be vectorized.
553 if (SrcInst && SrcInst->getParent() == Instr->getParent()) {
554 assert(WidenMap.count(SrcInst) && "Source operand is unavailable");
555 // The parameter is a vector value from earlier.
556 Params.push_back(WidenMap[SrcInst]);
558 // The parameter is a scalar from outside the loop. Maybe even a constant.
559 Params.push_back(SrcOp);
563 assert(Params.size() == Instr->getNumOperands() &&
564 "Invalid number of operands");
566 // Does this instruction return a value ?
567 bool IsVoidRetTy = Instr->getType()->isVoidTy();
568 Value *VecResults = 0;
570 // If we have a return value, create an empty vector. We place the scalarized
571 // instructions in this vector.
573 VecResults = UndefValue::get(VectorType::get(Instr->getType(), VF));
575 // For each scalar that we create:
576 for (unsigned i = 0; i < VF; ++i) {
577 Instruction *Cloned = Instr->clone();
579 Cloned->setName(Instr->getName() + ".cloned");
580 // Replace the operands of the cloned instrucions with extracted scalars.
581 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
582 Value *Op = Params[op];
583 // Param is a vector. Need to extract the right lane.
584 if (Op->getType()->isVectorTy())
585 Op = Builder.CreateExtractElement(Op, Builder.getInt32(i));
586 Cloned->setOperand(op, Op);
589 // Place the cloned scalar in the new loop.
590 Builder.Insert(Cloned);
592 // If the original scalar returns a value we need to place it in a vector
593 // so that future users will be able to use it.
595 VecResults = Builder.CreateInsertElement(VecResults, Cloned,
596 Builder.getInt32(i));
600 WidenMap[Instr] = VecResults;
604 SingleBlockLoopVectorizer::createEmptyLoop(LoopVectorizationLegality *Legal) {
606 In this function we generate a new loop. The new loop will contain
607 the vectorized instructions while the old loop will continue to run the
610 [ ] <-- vector loop bypass.
613 | [ ] <-- vector pre header.
617 | [ ]_| <-- vector loop.
620 >[ ] <--- middle-block.
623 | [ ] <--- new preheader.
627 | [ ]_| <-- old scalar loop to handle remainder.
634 // This is the original scalar-loop preheader.
635 BasicBlock *BypassBlock = OrigLoop->getLoopPreheader();
636 BasicBlock *ExitBlock = OrigLoop->getExitBlock();
637 assert(ExitBlock && "Must have an exit block");
639 // The loop index does not have to start at Zero. It starts with this value.
640 OldInduction = Legal->getInduction();
641 Value *StartIdx = OldInduction->getIncomingValueForBlock(BypassBlock);
643 assert(OrigLoop->getNumBlocks() == 1 && "Invalid loop");
644 assert(BypassBlock && "Invalid loop structure");
646 BasicBlock *VectorPH =
647 BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
648 BasicBlock *VecBody = VectorPH->splitBasicBlock(VectorPH->getTerminator(),
651 BasicBlock *MiddleBlock = VecBody->splitBasicBlock(VecBody->getTerminator(),
653 BasicBlock *ScalarPH =
654 MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(),
656 // Find the induction variable.
657 BasicBlock *OldBasicBlock = OrigLoop->getHeader();
658 assert(OldInduction && "We must have a single phi node.");
659 Type *IdxTy = OldInduction->getType();
661 // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
663 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
665 // Generate the induction variable.
666 Induction = Builder.CreatePHI(IdxTy, 2, "index");
667 Constant *Step = ConstantInt::get(IdxTy, VF);
669 // Find the loop boundaries.
670 const SCEV *ExitCount = SE->getExitCount(OrigLoop, OrigLoop->getHeader());
671 assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
673 // Get the total trip count from the count by adding 1.
674 ExitCount = SE->getAddExpr(ExitCount,
675 SE->getConstant(ExitCount->getType(), 1));
677 // Expand the trip count and place the new instructions in the preheader.
678 // Notice that the pre-header does not change, only the loop body.
679 SCEVExpander Exp(*SE, "induction");
680 Instruction *Loc = BypassBlock->getTerminator();
682 // We may need to extend the index in case there is a type mismatch.
683 // We know that the count starts at zero and does not overflow.
684 // We are using Zext because it should be less expensive.
685 if (ExitCount->getType() != Induction->getType())
686 ExitCount = SE->getZeroExtendExpr(ExitCount, IdxTy);
688 // Count holds the overall loop count (N).
689 Value *Count = Exp.expandCodeFor(ExitCount, Induction->getType(), Loc);
691 // Add the start index to the loop count to get the new end index.
692 Value *IdxEnd = BinaryOperator::CreateAdd(Count, StartIdx, "end.idx", Loc);
694 // Now we need to generate the expression for N - (N % VF), which is
695 // the part that the vectorized body will execute.
696 Constant *CIVF = ConstantInt::get(IdxTy, VF);
697 Value *R = BinaryOperator::CreateURem(Count, CIVF, "n.mod.vf", Loc);
698 Value *CountRoundDown = BinaryOperator::CreateSub(Count, R, "n.vec", Loc);
699 Value *IdxEndRoundDown = BinaryOperator::CreateAdd(CountRoundDown, StartIdx,
700 "end.idx.rnd.down", Loc);
702 // Now, compare the new count to zero. If it is zero, jump to the scalar part.
703 Value *Cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
707 BranchInst::Create(MiddleBlock, VectorPH, Cmp, Loc);
708 // Remove the old terminator.
709 Loc->eraseFromParent();
711 // Add a check in the middle block to see if we have completed
712 // all of the iterations in the first vector loop.
713 // If (N - N%VF) == N, then we *don't* need to run the remainder.
714 Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd,
715 IdxEndRoundDown, "cmp.n",
716 MiddleBlock->getTerminator());
718 BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
719 // Remove the old terminator.
720 MiddleBlock->getTerminator()->eraseFromParent();
722 // Create i+1 and fill the PHINode.
723 Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
724 Induction->addIncoming(StartIdx, VectorPH);
725 Induction->addIncoming(NextIdx, VecBody);
726 // Create the compare.
727 Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown);
728 Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
730 // Now we have two terminators. Remove the old one from the block.
731 VecBody->getTerminator()->eraseFromParent();
733 // Fix the scalar body iteration count.
734 unsigned BlockIdx = OldInduction->getBasicBlockIndex(ScalarPH);
735 OldInduction->setIncomingValue(BlockIdx, IdxEndRoundDown);
737 // Get ready to start creating new instructions into the vectorized body.
738 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
740 // Register the new loop.
741 Loop* Lp = new Loop();
742 LPM->insertLoop(Lp, OrigLoop->getParentLoop());
744 Lp->addBasicBlockToLoop(VecBody, LI->getBase());
746 Loop *ParentLoop = OrigLoop->getParentLoop();
748 ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase());
749 ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase());
750 ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase());
754 LoopVectorPreHeader = VectorPH;
755 LoopScalarPreHeader = ScalarPH;
756 LoopMiddleBlock = MiddleBlock;
757 LoopExitBlock = ExitBlock;
758 LoopVectorBody = VecBody;
759 LoopScalarBody = OldBasicBlock;
760 LoopBypassBlock = BypassBlock;
763 /// This function returns the identity element (or neutral element) for
766 getReductionIdentity(LoopVectorizationLegality::ReductionKind K) {
768 case LoopVectorizationLegality::IntegerXor:
769 case LoopVectorizationLegality::IntegerAdd:
770 case LoopVectorizationLegality::IntegerOr:
771 // Adding, Xoring, Oring zero to a number does not change it.
773 case LoopVectorizationLegality::IntegerMult:
774 // Multiplying a number by 1 does not change it.
776 case LoopVectorizationLegality::IntegerAnd:
777 // AND-ing a number with an all-1 value does not change it.
780 llvm_unreachable("Unknown reduction kind");
785 SingleBlockLoopVectorizer::vectorizeLoop(LoopVectorizationLegality *Legal) {
786 //===------------------------------------------------===//
788 // Notice: any optimization or new instruction that go
789 // into the code below should be also be implemented in
792 //===------------------------------------------------===//
793 typedef SmallVector<PHINode*, 4> PhiVector;
794 BasicBlock &BB = *OrigLoop->getHeader();
795 Constant *Zero = ConstantInt::get(
796 IntegerType::getInt32Ty(BB.getContext()), 0);
798 // In order to support reduction variables we need to be able to vectorize
799 // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
800 // steages. First, we create a new vector PHI node with no incoming edges.
801 // We use this value when we vectorize all of the instructions that use the
802 // PHI. Next, after all of the instructions in the block are complete we
803 // add the new incoming edges to the PHI. At this point all of the
804 // instructions in the basic block are vectorized, so we can use them to
805 // construct the PHI.
808 // For each instruction in the old loop.
809 for (BasicBlock::iterator it = BB.begin(), e = BB.end(); it != e; ++it) {
810 Instruction *Inst = it;
812 switch (Inst->getOpcode()) {
813 case Instruction::Br:
814 // Nothing to do for PHIs and BR, since we already took care of the
815 // loop control flow instructions.
817 case Instruction::PHI:{
818 PHINode* P = cast<PHINode>(Inst);
819 // Special handling for the induction var.
820 if (OldInduction == Inst)
822 // This is phase one of vectorizing PHIs.
823 // This has to be a reduction variable.
824 assert(Legal->getReductionVars()->count(P) && "Not a Reduction");
825 Type *VecTy = VectorType::get(Inst->getType(), VF);
826 WidenMap[Inst] = Builder.CreatePHI(VecTy, 2, "vec.phi");
827 PHIsToFix.push_back(P);
830 case Instruction::Add:
831 case Instruction::FAdd:
832 case Instruction::Sub:
833 case Instruction::FSub:
834 case Instruction::Mul:
835 case Instruction::FMul:
836 case Instruction::UDiv:
837 case Instruction::SDiv:
838 case Instruction::FDiv:
839 case Instruction::URem:
840 case Instruction::SRem:
841 case Instruction::FRem:
842 case Instruction::Shl:
843 case Instruction::LShr:
844 case Instruction::AShr:
845 case Instruction::And:
846 case Instruction::Or:
847 case Instruction::Xor: {
848 // Just widen binops.
849 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
850 Value *A = getVectorValue(Inst->getOperand(0));
851 Value *B = getVectorValue(Inst->getOperand(1));
852 // Use this vector value for all users of the original instruction.
853 WidenMap[Inst] = Builder.CreateBinOp(BinOp->getOpcode(), A, B);
856 case Instruction::Select: {
858 // If the selector is loop invariant we can create a select
859 // instruction with a scalar condition. Otherwise, use vector-select.
860 Value *Cond = Inst->getOperand(0);
861 bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(Cond), OrigLoop);
863 // The condition can be loop invariant but still defined inside the
864 // loop. This means that we can't just use the original 'cond' value.
865 // We have to take the 'vectorized' value and pick the first lane.
866 // Instcombine will make this a no-op.
867 Cond = getVectorValue(Cond);
869 Cond = Builder.CreateExtractElement(Cond, Builder.getInt32(0));
871 Value *Op0 = getVectorValue(Inst->getOperand(1));
872 Value *Op1 = getVectorValue(Inst->getOperand(2));
873 WidenMap[Inst] = Builder.CreateSelect(Cond, Op0, Op1);
877 case Instruction::ICmp:
878 case Instruction::FCmp: {
879 // Widen compares. Generate vector compares.
880 bool FCmp = (Inst->getOpcode() == Instruction::FCmp);
881 CmpInst *Cmp = dyn_cast<CmpInst>(Inst);
882 Value *A = getVectorValue(Inst->getOperand(0));
883 Value *B = getVectorValue(Inst->getOperand(1));
885 WidenMap[Inst] = Builder.CreateFCmp(Cmp->getPredicate(), A, B);
887 WidenMap[Inst] = Builder.CreateICmp(Cmp->getPredicate(), A, B);
891 case Instruction::Store: {
892 // Attempt to issue a wide store.
893 StoreInst *SI = dyn_cast<StoreInst>(Inst);
894 Type *StTy = VectorType::get(SI->getValueOperand()->getType(), VF);
895 Value *Ptr = SI->getPointerOperand();
896 unsigned Alignment = SI->getAlignment();
897 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
898 // This store does not use GEPs.
899 if (!Legal->isConsecutiveGep(Gep)) {
900 scalarizeInstruction(Inst);
904 // The last index does not have to be the induction. It can be
905 // consecutive and be a function of the index. For example A[I+1];
906 unsigned NumOperands = Gep->getNumOperands();
907 Value *LastIndex = getVectorValue(Gep->getOperand(NumOperands - 1));
908 LastIndex = Builder.CreateExtractElement(LastIndex, Zero);
910 // Create the new GEP with the new induction variable.
911 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
912 Gep2->setOperand(NumOperands - 1, LastIndex);
913 Ptr = Builder.Insert(Gep2);
914 Ptr = Builder.CreateBitCast(Ptr, StTy->getPointerTo());
915 Value *Val = getVectorValue(SI->getValueOperand());
916 Builder.CreateStore(Val, Ptr)->setAlignment(Alignment);
919 case Instruction::Load: {
920 // Attempt to issue a wide load.
921 LoadInst *LI = dyn_cast<LoadInst>(Inst);
922 Type *RetTy = VectorType::get(LI->getType(), VF);
923 Value *Ptr = LI->getPointerOperand();
924 unsigned Alignment = LI->getAlignment();
925 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
927 // We don't have a gep. Scalarize the load.
928 if (!Legal->isConsecutiveGep(Gep)) {
929 scalarizeInstruction(Inst);
933 // The last index does not have to be the induction. It can be
934 // consecutive and be a function of the index. For example A[I+1];
935 unsigned NumOperands = Gep->getNumOperands();
936 Value *LastIndex = getVectorValue(Gep->getOperand(NumOperands -1));
937 LastIndex = Builder.CreateExtractElement(LastIndex, Zero);
939 // Create the new GEP with the new induction variable.
940 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
941 Gep2->setOperand(NumOperands - 1, LastIndex);
942 Ptr = Builder.Insert(Gep2);
943 Ptr = Builder.CreateBitCast(Ptr, RetTy->getPointerTo());
944 LI = Builder.CreateLoad(Ptr);
945 LI->setAlignment(Alignment);
946 // Use this vector value for all users of the load.
950 case Instruction::ZExt:
951 case Instruction::SExt:
952 case Instruction::FPToUI:
953 case Instruction::FPToSI:
954 case Instruction::FPExt:
955 case Instruction::PtrToInt:
956 case Instruction::IntToPtr:
957 case Instruction::SIToFP:
958 case Instruction::UIToFP:
959 case Instruction::Trunc:
960 case Instruction::FPTrunc:
961 case Instruction::BitCast: {
962 /// Vectorize bitcasts.
963 CastInst *CI = dyn_cast<CastInst>(Inst);
964 Value *A = getVectorValue(Inst->getOperand(0));
965 Type *DestTy = VectorType::get(CI->getType()->getScalarType(), VF);
966 WidenMap[Inst] = Builder.CreateCast(CI->getOpcode(), A, DestTy);
971 /// All other instructions are unsupported. Scalarize them.
972 scalarizeInstruction(Inst);
975 }// end of for_each instr.
977 // At this point every instruction in the original loop is widended to
978 // a vector form. We are almost done. Now, we need to fix the PHI nodes
979 // that we vectorized. The PHI nodes are currently empty because we did
980 // not want to introduce cycles. Notice that the remaining PHI nodes
981 // that we need to fix are reduction variables.
983 // Create the 'reduced' values for each of the induction vars.
984 // The reduced values are the vector values that we scalarize and combine
985 // after the loop is finished.
986 for (PhiVector::iterator it = PHIsToFix.begin(), e = PHIsToFix.end();
988 PHINode *RdxPhi = *it;
989 PHINode *VecRdxPhi = dyn_cast<PHINode>(WidenMap[RdxPhi]);
990 assert(RdxPhi && "Unable to recover vectorized PHI");
992 // Find the reduction variable descriptor.
993 assert(Legal->getReductionVars()->count(RdxPhi) &&
994 "Unable to find the reduction variable");
995 LoopVectorizationLegality::ReductionDescriptor RdxDesc =
996 (*Legal->getReductionVars())[RdxPhi];
998 // We need to generate a reduction vector from the incoming scalar.
999 // To do so, we need to generate the 'identity' vector and overide
1000 // one of the elements with the incoming scalar reduction. We need
1001 // to do it in the vector-loop preheader.
1002 Builder.SetInsertPoint(LoopBypassBlock->getTerminator());
1004 // This is the vector-clone of the value that leaves the loop.
1005 Value *VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
1006 Type *VecTy = VectorExit->getType();
1008 // Find the reduction identity variable. Zero for addition, or, xor,
1009 // one for multiplication, -1 for And.
1010 Constant *Identity = getUniformVector(getReductionIdentity(RdxDesc.Kind),
1011 VecTy->getScalarType());
1013 // This vector is the Identity vector where the first element is the
1014 // incoming scalar reduction.
1015 Value *VectorStart = Builder.CreateInsertElement(Identity,
1016 RdxDesc.StartValue, Zero);
1019 // Fix the vector-loop phi.
1020 // We created the induction variable so we know that the
1021 // preheader is the first entry.
1022 BasicBlock *VecPreheader = Induction->getIncomingBlock(0);
1024 // Reductions do not have to start at zero. They can start with
1025 // any loop invariant values.
1026 VecRdxPhi->addIncoming(VectorStart, VecPreheader);
1027 unsigned SelfEdgeIdx = (RdxPhi)->getBasicBlockIndex(LoopScalarBody);
1028 Value *Val = getVectorValue(RdxPhi->getIncomingValue(SelfEdgeIdx));
1029 VecRdxPhi->addIncoming(Val, LoopVectorBody);
1031 // Before each round, move the insertion point right between
1032 // the PHIs and the values we are going to write.
1033 // This allows us to write both PHINodes and the extractelement
1035 Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
1037 // This PHINode contains the vectorized reduction variable, or
1038 // the initial value vector, if we bypass the vector loop.
1039 PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
1040 NewPhi->addIncoming(VectorStart, LoopBypassBlock);
1041 NewPhi->addIncoming(getVectorValue(RdxDesc.LoopExitInstr), LoopVectorBody);
1043 // Extract the first scalar.
1045 Builder.CreateExtractElement(NewPhi, Builder.getInt32(0));
1046 // Extract and reduce the remaining vector elements.
1047 for (unsigned i=1; i < VF; ++i) {
1049 Builder.CreateExtractElement(NewPhi, Builder.getInt32(i));
1050 switch (RdxDesc.Kind) {
1051 case LoopVectorizationLegality::IntegerAdd:
1052 Scalar0 = Builder.CreateAdd(Scalar0, Scalar1);
1054 case LoopVectorizationLegality::IntegerMult:
1055 Scalar0 = Builder.CreateMul(Scalar0, Scalar1);
1057 case LoopVectorizationLegality::IntegerOr:
1058 Scalar0 = Builder.CreateOr(Scalar0, Scalar1);
1060 case LoopVectorizationLegality::IntegerAnd:
1061 Scalar0 = Builder.CreateAnd(Scalar0, Scalar1);
1063 case LoopVectorizationLegality::IntegerXor:
1064 Scalar0 = Builder.CreateXor(Scalar0, Scalar1);
1067 llvm_unreachable("Unknown reduction operation");
1071 // Now, we need to fix the users of the reduction variable
1072 // inside and outside of the scalar remainder loop.
1073 // We know that the loop is in LCSSA form. We need to update the
1074 // PHI nodes in the exit blocks.
1075 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
1076 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
1077 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
1078 if (!LCSSAPhi) continue;
1080 // All PHINodes need to have a single entry edge, or two if
1081 // we already fixed them.
1082 assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
1084 // We found our reduction value exit-PHI. Update it with the
1085 // incoming bypass edge.
1086 if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
1087 // Add an edge coming from the bypass.
1088 LCSSAPhi->addIncoming(Scalar0, LoopMiddleBlock);
1091 }// end of the LCSSA phi scan.
1093 // Fix the scalar loop reduction variable with the incoming reduction sum
1094 // from the vector body and from the backedge value.
1095 int IncomingEdgeBlockIdx = (RdxPhi)->getBasicBlockIndex(LoopScalarBody);
1096 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1); // The other block.
1097 (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, Scalar0);
1098 (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
1099 }// end of for each redux variable.
1102 void SingleBlockLoopVectorizer::updateAnalysis() {
1103 // The original basic block.
1104 SE->forgetLoop(OrigLoop);
1106 // Update the dominator tree information.
1107 assert(DT->properlyDominates(LoopBypassBlock, LoopExitBlock) &&
1108 "Entry does not dominate exit.");
1110 DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlock);
1111 DT->addNewBlock(LoopVectorBody, LoopVectorPreHeader);
1112 DT->addNewBlock(LoopMiddleBlock, LoopBypassBlock);
1113 DT->addNewBlock(LoopScalarPreHeader, LoopMiddleBlock);
1114 DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
1115 DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
1117 DEBUG(DT->verifyAnalysis());
1120 bool LoopVectorizationLegality::canVectorize() {
1121 if (!TheLoop->getLoopPreheader()) {
1122 assert(false && "No preheader!!");
1123 DEBUG(dbgs() << "LV: Loop not normalized." << "\n");
1127 // We can only vectorize single basic block loops.
1128 unsigned NumBlocks = TheLoop->getNumBlocks();
1129 if (NumBlocks != 1) {
1130 DEBUG(dbgs() << "LV: Too many blocks:" << NumBlocks << "\n");
1134 // We need to have a loop header.
1135 BasicBlock *BB = TheLoop->getHeader();
1136 DEBUG(dbgs() << "LV: Found a loop: " << BB->getName() << "\n");
1138 // Go over each instruction and look at memory deps.
1139 if (!canVectorizeBlock(*BB)) {
1140 DEBUG(dbgs() << "LV: Can't vectorize this loop header\n");
1144 // ScalarEvolution needs to be able to find the exit count.
1145 const SCEV *ExitCount = SE->getExitCount(TheLoop, BB);
1146 if (ExitCount == SE->getCouldNotCompute()) {
1147 DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
1151 // Do not loop-vectorize loops with a tiny trip count.
1152 unsigned TC = SE->getSmallConstantTripCount(TheLoop, BB);
1153 if (TC > 0 && TC < TinyTripCountThreshold) {
1154 DEBUG(dbgs() << "LV: Found a loop with a very small trip count. " <<
1155 "This loop is not worth vectorizing.\n");
1159 DEBUG(dbgs() << "LV: We can vectorize this loop!\n");
1161 // Okay! We can vectorize. At this point we don't have any other mem analysis
1162 // which may limit our maximum vectorization factor, so just return true with
1167 bool LoopVectorizationLegality::canVectorizeBlock(BasicBlock &BB) {
1168 // Scan the instructions in the block and look for hazards.
1169 for (BasicBlock::iterator it = BB.begin(), e = BB.end(); it != e; ++it) {
1170 Instruction *I = it;
1172 PHINode *Phi = dyn_cast<PHINode>(I);
1174 // This should not happen because the loop should be normalized.
1175 if (Phi->getNumIncomingValues() != 2) {
1176 DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
1179 // We only look at integer phi nodes.
1180 if (!Phi->getType()->isIntegerTy()) {
1181 DEBUG(dbgs() << "LV: Found an non-int PHI.\n");
1185 if (isInductionVariable(Phi)) {
1187 DEBUG(dbgs() << "LV: Found too many inductions."<< *Phi <<"\n");
1190 DEBUG(dbgs() << "LV: Found the induction PHI."<< *Phi <<"\n");
1194 if (AddReductionVar(Phi, IntegerAdd)) {
1195 DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
1198 if (AddReductionVar(Phi, IntegerMult)) {
1199 DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n");
1202 if (AddReductionVar(Phi, IntegerOr)) {
1203 DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n");
1206 if (AddReductionVar(Phi, IntegerAnd)) {
1207 DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n");
1210 if (AddReductionVar(Phi, IntegerXor)) {
1211 DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n");
1215 DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
1217 }// end of PHI handling
1219 // We still don't handle functions.
1220 CallInst *CI = dyn_cast<CallInst>(I);
1222 DEBUG(dbgs() << "LV: Found a call site.\n");
1226 // We do not re-vectorize vectors.
1227 if (!VectorType::isValidElementType(I->getType()) &&
1228 !I->getType()->isVoidTy()) {
1229 DEBUG(dbgs() << "LV: Found unvectorizable type." << "\n");
1233 // Reduction instructions are allowed to have exit users.
1234 // All other instructions must not have external users.
1235 if (!AllowedExit.count(I))
1236 //Check that all of the users of the loop are inside the BB.
1237 for (Value::use_iterator it = I->use_begin(), e = I->use_end();
1239 Instruction *U = cast<Instruction>(*it);
1240 // This user may be a reduction exit value.
1241 BasicBlock *Parent = U->getParent();
1242 if (Parent != &BB) {
1243 DEBUG(dbgs() << "LV: Found an outside user for : "<< *U << "\n");
1250 DEBUG(dbgs() << "LV: Did not find an induction var.\n");
1254 // Don't vectorize if the memory dependencies do not allow vectorization.
1255 if (!canVectorizeMemory(BB))
1258 // We now know that the loop is vectorizable!
1259 // Collect variables that will remain uniform after vectorization.
1260 std::vector<Value*> Worklist;
1262 // Start with the conditional branch and walk up the block.
1263 Worklist.push_back(BB.getTerminator()->getOperand(0));
1265 while (Worklist.size()) {
1266 Instruction *I = dyn_cast<Instruction>(Worklist.back());
1267 Worklist.pop_back();
1268 // Look at instructions inside this block.
1270 if (I->getParent() != &BB) continue;
1272 // Stop when reaching PHI nodes.
1273 if (isa<PHINode>(I)) {
1274 assert(I == Induction && "Found a uniform PHI that is not the induction");
1278 // This is a known uniform.
1281 // Insert all operands.
1282 for (int i=0, Op = I->getNumOperands(); i < Op; ++i) {
1283 Worklist.push_back(I->getOperand(i));
1290 bool LoopVectorizationLegality::canVectorizeMemory(BasicBlock &BB) {
1291 typedef SmallVector<Value*, 16> ValueVector;
1292 typedef SmallPtrSet<Value*, 16> ValueSet;
1293 // Holds the Load and Store *instructions*.
1297 // Scan the BB and collect legal loads and stores.
1298 for (BasicBlock::iterator it = BB.begin(), e = BB.end(); it != e; ++it) {
1299 Instruction *I = it;
1301 // If this is a load, save it. If this instruction can read from memory
1302 // but is not a load, then we quit. Notice that we don't handle function
1303 // calls that read or write.
1304 if (I->mayReadFromMemory()) {
1305 LoadInst *Ld = dyn_cast<LoadInst>(I);
1306 if (!Ld) return false;
1307 if (!Ld->isSimple()) {
1308 DEBUG(dbgs() << "LV: Found a non-simple load.\n");
1311 Loads.push_back(Ld);
1315 // Save store instructions. Abort if other instructions write to memory.
1316 if (I->mayWriteToMemory()) {
1317 StoreInst *St = dyn_cast<StoreInst>(I);
1318 if (!St) return false;
1319 if (!St->isSimple()) {
1320 DEBUG(dbgs() << "LV: Found a non-simple store.\n");
1323 Stores.push_back(St);
1327 // Now we have two lists that hold the loads and the stores.
1328 // Next, we find the pointers that they use.
1330 // Check if we see any stores. If there are no stores, then we don't
1331 // care if the pointers are *restrict*.
1332 if (!Stores.size()) {
1333 DEBUG(dbgs() << "LV: Found a read-only loop!\n");
1337 // Holds the read and read-write *pointers* that we find.
1339 ValueVector ReadWrites;
1341 // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
1342 // multiple times on the same object. If the ptr is accessed twice, once
1343 // for read and once for write, it will only appear once (on the write
1344 // list). This is okay, since we are going to check for conflicts between
1345 // writes and between reads and writes, but not between reads and reads.
1348 ValueVector::iterator I, IE;
1349 for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
1350 StoreInst *ST = dyn_cast<StoreInst>(*I);
1351 assert(ST && "Bad StoreInst");
1352 Value* Ptr = ST->getPointerOperand();
1353 // If we did *not* see this pointer before, insert it to
1354 // the read-write list. At this phase it is only a 'write' list.
1355 if (Seen.insert(Ptr))
1356 ReadWrites.push_back(Ptr);
1359 for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
1360 LoadInst *LD = dyn_cast<LoadInst>(*I);
1361 assert(LD && "Bad LoadInst");
1362 Value* Ptr = LD->getPointerOperand();
1363 // If we did *not* see this pointer before, insert it to the
1364 // read list. If we *did* see it before, then it is already in
1365 // the read-write list. This allows us to vectorize expressions
1366 // such as A[i] += x; Because the address of A[i] is a read-write
1367 // pointer. This only works if the index of A[i] is consecutive.
1368 // If the address of i is unknown (for example A[B[i]]) then we may
1369 // read a few words, modify, and write a few words, and some of the
1370 // words may be written to the same address.
1371 if (Seen.insert(Ptr) || !isConsecutiveGep(Ptr))
1372 Reads.push_back(Ptr);
1375 // If we write (or read-write) to a single destination and there are no
1376 // other reads in this loop then is it safe to vectorize.
1377 if (ReadWrites.size() == 1 && Reads.size() == 0) {
1378 DEBUG(dbgs() << "LV: Found a write-only loop!\n");
1382 // Now that the pointers are in two lists (Reads and ReadWrites), we
1383 // can check that there are no conflicts between each of the writes and
1384 // between the writes to the reads.
1385 ValueSet WriteObjects;
1386 ValueVector TempObjects;
1388 // Check that the read-writes do not conflict with other read-write
1390 for (I = ReadWrites.begin(), IE = ReadWrites.end(); I != IE; ++I) {
1391 GetUnderlyingObjects(*I, TempObjects, DL);
1392 for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end();
1394 if (!isIdentifiedObject(*it)) {
1395 DEBUG(dbgs() << "LV: Found an unidentified write ptr:"<< **it <<"\n");
1398 if (!WriteObjects.insert(*it)) {
1399 DEBUG(dbgs() << "LV: Found a possible write-write reorder:"
1404 TempObjects.clear();
1407 /// Check that the reads don't conflict with the read-writes.
1408 for (I = Reads.begin(), IE = Reads.end(); I != IE; ++I) {
1409 GetUnderlyingObjects(*I, TempObjects, DL);
1410 for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end();
1412 if (!isIdentifiedObject(*it)) {
1413 DEBUG(dbgs() << "LV: Found an unidentified read ptr:"<< **it <<"\n");
1416 if (WriteObjects.count(*it)) {
1417 DEBUG(dbgs() << "LV: Found a possible read/write reorder:"
1422 TempObjects.clear();
1429 bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi,
1430 ReductionKind Kind) {
1431 if (Phi->getNumIncomingValues() != 2)
1434 // Find the possible incoming reduction variable.
1435 BasicBlock *BB = Phi->getParent();
1436 int SelfEdgeIdx = Phi->getBasicBlockIndex(BB);
1437 int InEdgeBlockIdx = (SelfEdgeIdx ? 0 : 1); // The other entry.
1438 Value *RdxStart = Phi->getIncomingValue(InEdgeBlockIdx);
1440 // ExitInstruction is the single value which is used outside the loop.
1441 // We only allow for a single reduction value to be used outside the loop.
1442 // This includes users of the reduction, variables (which form a cycle
1443 // which ends in the phi node).
1444 Instruction *ExitInstruction = 0;
1446 // Iter is our iterator. We start with the PHI node and scan for all of the
1447 // users of this instruction. All users must be instructions which can be
1448 // used as reduction variables (such as ADD). We may have a single
1449 // out-of-block user. They cycle must end with the original PHI.
1450 // Also, we can't have multiple block-local users.
1451 Instruction *Iter = Phi;
1453 // Any reduction instr must be of one of the allowed kinds.
1454 if (!isReductionInstr(Iter, Kind))
1457 // Did we found a user inside this block ?
1458 bool FoundInBlockUser = false;
1459 // Did we reach the initial PHI node ?
1460 bool FoundStartPHI = false;
1462 // If the instruction has no users then this is a broken
1463 // chain and can't be a reduction variable.
1464 if (Iter->use_empty())
1467 // For each of the *users* of iter.
1468 for (Value::use_iterator it = Iter->use_begin(), e = Iter->use_end();
1470 Instruction *U = cast<Instruction>(*it);
1471 // We already know that the PHI is a user.
1473 FoundStartPHI = true;
1476 // Check if we found the exit user.
1477 BasicBlock *Parent = U->getParent();
1479 // We must have a single exit instruction.
1480 if (ExitInstruction != 0)
1482 ExitInstruction = Iter;
1484 // We can't have multiple inside users.
1485 if (FoundInBlockUser)
1487 FoundInBlockUser = true;
1491 // We found a reduction var if we have reached the original
1492 // phi node and we only have a single instruction with out-of-loop
1494 if (FoundStartPHI && ExitInstruction) {
1495 // This instruction is allowed to have out-of-loop users.
1496 AllowedExit.insert(ExitInstruction);
1498 // Save the description of this reduction variable.
1499 ReductionDescriptor RD(RdxStart, ExitInstruction, Kind);
1500 Reductions[Phi] = RD;
1507 LoopVectorizationLegality::isReductionInstr(Instruction *I,
1508 ReductionKind Kind) {
1509 switch (I->getOpcode()) {
1512 case Instruction::PHI:
1515 case Instruction::Add:
1516 case Instruction::Sub:
1517 return Kind == IntegerAdd;
1518 case Instruction::Mul:
1519 case Instruction::UDiv:
1520 case Instruction::SDiv:
1521 return Kind == IntegerMult;
1522 case Instruction::And:
1523 return Kind == IntegerAnd;
1524 case Instruction::Or:
1525 return Kind == IntegerOr;
1526 case Instruction::Xor:
1527 return Kind == IntegerXor;
1531 bool LoopVectorizationLegality::isInductionVariable(PHINode *Phi) {
1532 // Check that the PHI is consecutive and starts at zero.
1533 const SCEV *PhiScev = SE->getSCEV(Phi);
1534 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
1536 DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
1539 const SCEV *Step = AR->getStepRecurrence(*SE);
1541 if (!Step->isOne()) {
1542 DEBUG(dbgs() << "LV: PHI stride does not equal one.\n");
1549 LoopVectorizationCostModel::findBestVectorizationFactor(unsigned VF) {
1551 DEBUG(dbgs() << "LV: No vector target information. Not vectorizing. \n");
1555 float Cost = expectedCost(1);
1557 DEBUG(dbgs() << "LV: Scalar loop costs: "<< (int)Cost << ".\n");
1558 for (unsigned i=2; i <= VF; i*=2) {
1559 // Notice that the vector loop needs to be executed less times, so
1560 // we need to divide the cost of the vector loops by the width of
1561 // the vector elements.
1562 float VectorCost = expectedCost(i) / (float)i;
1563 DEBUG(dbgs() << "LV: Vector loop of width "<< i << " costs: " <<
1564 (int)VectorCost << ".\n");
1565 if (VectorCost < Cost) {
1571 DEBUG(dbgs() << "LV: Selecting VF = : "<< Width << ".\n");
1575 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
1576 // We can only estimate the cost of single basic block loops.
1577 assert(1 == TheLoop->getNumBlocks() && "Too many blocks in loop");
1579 BasicBlock *BB = TheLoop->getHeader();
1582 // For each instruction in the old loop.
1583 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1584 Instruction *Inst = it;
1585 unsigned C = getInstructionCost(Inst, VF);
1587 DEBUG(dbgs() << "LV: Found an estimated cost of "<< C <<" for VF "<< VF <<
1588 " For instruction: "<< *Inst << "\n");
1595 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
1596 assert(VTTI && "Invalid vector target transformation info");
1598 // If we know that this instruction will remain uniform, check the cost of
1599 // the scalar version.
1600 if (Legal->isUniformAfterVectorization(I))
1603 Type *RetTy = I->getType();
1604 Type *VectorTy = ToVectorTy(RetTy, VF);
1607 // TODO: We need to estimate the cost of intrinsic calls.
1608 switch (I->getOpcode()) {
1609 case Instruction::GetElementPtr:
1610 // We mark this instruction as zero-cost because scalar GEPs are usually
1611 // lowered to the intruction addressing mode. At the moment we don't
1612 // generate vector geps.
1614 case Instruction::Br: {
1615 return VTTI->getCFInstrCost(I->getOpcode());
1617 case Instruction::PHI:
1619 case Instruction::Add:
1620 case Instruction::FAdd:
1621 case Instruction::Sub:
1622 case Instruction::FSub:
1623 case Instruction::Mul:
1624 case Instruction::FMul:
1625 case Instruction::UDiv:
1626 case Instruction::SDiv:
1627 case Instruction::FDiv:
1628 case Instruction::URem:
1629 case Instruction::SRem:
1630 case Instruction::FRem:
1631 case Instruction::Shl:
1632 case Instruction::LShr:
1633 case Instruction::AShr:
1634 case Instruction::And:
1635 case Instruction::Or:
1636 case Instruction::Xor: {
1637 return VTTI->getArithmeticInstrCost(I->getOpcode(), VectorTy);
1639 case Instruction::Select: {
1640 SelectInst *SI = cast<SelectInst>(I);
1641 const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
1642 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
1643 Type *CondTy = SI->getCondition()->getType();
1645 CondTy = VectorType::get(CondTy, VF);
1647 return VTTI->getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
1649 case Instruction::ICmp:
1650 case Instruction::FCmp: {
1651 Type *ValTy = I->getOperand(0)->getType();
1652 VectorTy = ToVectorTy(ValTy, VF);
1653 return VTTI->getCmpSelInstrCost(I->getOpcode(), VectorTy);
1655 case Instruction::Store: {
1656 StoreInst *SI = cast<StoreInst>(I);
1657 Type *ValTy = SI->getValueOperand()->getType();
1658 VectorTy = ToVectorTy(ValTy, VF);
1661 return VTTI->getMemoryOpCost(I->getOpcode(), ValTy,
1662 SI->getAlignment(), SI->getPointerAddressSpace());
1664 // Scalarized stores.
1665 if (!Legal->isConsecutiveGep(SI->getPointerOperand())) {
1667 unsigned ExtCost = VTTI->getInstrCost(Instruction::ExtractElement,
1669 // The cost of extracting from the value vector.
1670 Cost += VF * (ExtCost);
1671 // The cost of the scalar stores.
1672 Cost += VF * VTTI->getMemoryOpCost(I->getOpcode(),
1673 ValTy->getScalarType(),
1675 SI->getPointerAddressSpace());
1680 return VTTI->getMemoryOpCost(I->getOpcode(), VectorTy, SI->getAlignment(),
1681 SI->getPointerAddressSpace());
1683 case Instruction::Load: {
1684 LoadInst *LI = cast<LoadInst>(I);
1687 return VTTI->getMemoryOpCost(I->getOpcode(), RetTy,
1689 LI->getPointerAddressSpace());
1691 // Scalarized loads.
1692 if (!Legal->isConsecutiveGep(LI->getPointerOperand())) {
1694 unsigned InCost = VTTI->getInstrCost(Instruction::InsertElement, RetTy);
1695 // The cost of inserting the loaded value into the result vector.
1696 Cost += VF * (InCost);
1697 // The cost of the scalar stores.
1698 Cost += VF * VTTI->getMemoryOpCost(I->getOpcode(),
1699 RetTy->getScalarType(),
1701 LI->getPointerAddressSpace());
1706 return VTTI->getMemoryOpCost(I->getOpcode(), VectorTy, LI->getAlignment(),
1707 LI->getPointerAddressSpace());
1709 case Instruction::ZExt:
1710 case Instruction::SExt:
1711 case Instruction::FPToUI:
1712 case Instruction::FPToSI:
1713 case Instruction::FPExt:
1714 case Instruction::PtrToInt:
1715 case Instruction::IntToPtr:
1716 case Instruction::SIToFP:
1717 case Instruction::UIToFP:
1718 case Instruction::Trunc:
1719 case Instruction::FPTrunc:
1720 case Instruction::BitCast: {
1721 Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
1722 return VTTI->getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
1725 // We are scalarizing the instruction. Return the cost of the scalar
1726 // instruction, plus the cost of insert and extract into vector
1727 // elements, times the vector width.
1730 bool IsVoid = RetTy->isVoidTy();
1732 unsigned InsCost = (IsVoid ? 0 :
1733 VTTI->getInstrCost(Instruction::InsertElement,
1736 unsigned ExtCost = VTTI->getInstrCost(Instruction::ExtractElement,
1739 // The cost of inserting the results plus extracting each one of the
1741 Cost += VF * (InsCost + ExtCost * I->getNumOperands());
1743 // The cost of executing VF copies of the scalar instruction.
1744 Cost += VF * VTTI->getInstrCost(I->getOpcode(), RetTy);
1750 Type* LoopVectorizationCostModel::ToVectorTy(Type *Scalar, unsigned VF) {
1751 if (Scalar->isVoidTy() || VF == 1)
1753 return VectorType::get(Scalar, VF);
1758 char LoopVectorize::ID = 0;
1759 static const char lv_name[] = "Loop Vectorization";
1760 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
1761 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
1762 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
1763 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
1764 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
1767 Pass *createLoopVectorizePass() {
1768 return new LoopVectorize();