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 //===----------------------------------------------------------------------===//
9 #include "LoopVectorize.h"
10 #include "llvm/ADT/StringExtras.h"
11 #include "llvm/Analysis/AliasAnalysis.h"
12 #include "llvm/Analysis/AliasSetTracker.h"
13 #include "llvm/Analysis/Dominators.h"
14 #include "llvm/Analysis/LoopInfo.h"
15 #include "llvm/Analysis/LoopIterator.h"
16 #include "llvm/Analysis/LoopPass.h"
17 #include "llvm/Analysis/ScalarEvolutionExpander.h"
18 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
19 #include "llvm/Analysis/ValueTracking.h"
20 #include "llvm/Analysis/Verifier.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DataLayout.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/Function.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/IntrinsicInst.h"
27 #include "llvm/LLVMContext.h"
28 #include "llvm/Module.h"
29 #include "llvm/Pass.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/TargetTransformInfo.h"
34 #include "llvm/Transforms/Scalar.h"
35 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
36 #include "llvm/Transforms/Utils/Local.h"
37 #include "llvm/Transforms/Vectorize.h"
38 #include "llvm/Type.h"
39 #include "llvm/Value.h"
41 static cl::opt<unsigned>
42 VectorizationFactor("force-vector-width", cl::init(0), cl::Hidden,
43 cl::desc("Sets the SIMD width. Zero is autoselect."));
46 EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
47 cl::desc("Enable if-conversion during vectorization."));
51 /// The LoopVectorize Pass.
52 struct LoopVectorize : public LoopPass {
53 /// Pass identification, replacement for typeid
56 explicit LoopVectorize() : LoopPass(ID) {
57 initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
63 TargetTransformInfo *TTI;
66 virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
67 // We only vectorize innermost loops.
71 SE = &getAnalysis<ScalarEvolution>();
72 DL = getAnalysisIfAvailable<DataLayout>();
73 LI = &getAnalysis<LoopInfo>();
74 TTI = getAnalysisIfAvailable<TargetTransformInfo>();
75 DT = &getAnalysis<DominatorTree>();
77 DEBUG(dbgs() << "LV: Checking a loop in \"" <<
78 L->getHeader()->getParent()->getName() << "\"\n");
80 // Check if it is legal to vectorize the loop.
81 LoopVectorizationLegality LVL(L, SE, DL, DT);
82 if (!LVL.canVectorize()) {
83 DEBUG(dbgs() << "LV: Not vectorizing.\n");
87 // Select the preffered vectorization factor.
88 const VectorTargetTransformInfo *VTTI = 0;
90 VTTI = TTI->getVectorTargetTransformInfo();
91 // Use the cost model.
92 LoopVectorizationCostModel CM(L, SE, &LVL, VTTI);
94 // Check the function attribues to find out if this function should be
95 // optimized for size.
96 Function *F = L->getHeader()->getParent();
97 Attribute::AttrKind SzAttr= Attribute::OptimizeForSize;
99 F->getAttributes().hasAttribute(AttributeSet::FunctionIndex, SzAttr);
101 unsigned VF = CM.selectVectorizationFactor(OptForSize, VectorizationFactor);
104 DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
108 DEBUG(dbgs() << "LV: Found a vectorizable loop ("<< VF << ") in "<<
109 F->getParent()->getModuleIdentifier()<<"\n");
111 // If we decided that it is *legal* to vectorizer the loop then do it.
112 InnerLoopVectorizer LB(L, SE, LI, DT, DL, VF);
115 DEBUG(verifyFunction(*L->getHeader()->getParent()));
119 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
120 LoopPass::getAnalysisUsage(AU);
121 AU.addRequiredID(LoopSimplifyID);
122 AU.addRequiredID(LCSSAID);
123 AU.addRequired<LoopInfo>();
124 AU.addRequired<ScalarEvolution>();
125 AU.addRequired<DominatorTree>();
126 AU.addPreserved<LoopInfo>();
127 AU.addPreserved<DominatorTree>();
134 //===----------------------------------------------------------------------===//
135 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
136 // LoopVectorizationCostModel.
137 //===----------------------------------------------------------------------===//
140 LoopVectorizationLegality::RuntimePointerCheck::insert(ScalarEvolution *SE,
141 Loop *Lp, Value *Ptr) {
142 const SCEV *Sc = SE->getSCEV(Ptr);
143 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
144 assert(AR && "Invalid addrec expression");
145 const SCEV *Ex = SE->getExitCount(Lp, Lp->getLoopLatch());
146 const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
147 Pointers.push_back(Ptr);
148 Starts.push_back(AR->getStart());
149 Ends.push_back(ScEnd);
152 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
154 LLVMContext &C = V->getContext();
155 Type *VTy = VectorType::get(V->getType(), VF);
156 Type *I32 = IntegerType::getInt32Ty(C);
158 // Save the current insertion location.
159 Instruction *Loc = Builder.GetInsertPoint();
161 // We need to place the broadcast of invariant variables outside the loop.
162 Instruction *Instr = dyn_cast<Instruction>(V);
163 bool NewInstr = (Instr && Instr->getParent() == LoopVectorBody);
164 bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
166 // Place the code for broadcasting invariant variables in the new preheader.
168 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
170 Constant *Zero = ConstantInt::get(I32, 0);
171 Value *Zeros = ConstantAggregateZero::get(VectorType::get(I32, VF));
172 Value *UndefVal = UndefValue::get(VTy);
173 // Insert the value into a new vector.
174 Value *SingleElem = Builder.CreateInsertElement(UndefVal, V, Zero);
175 // Broadcast the scalar into all locations in the vector.
176 Value *Shuf = Builder.CreateShuffleVector(SingleElem, UndefVal, Zeros,
179 // Restore the builder insertion point.
181 Builder.SetInsertPoint(Loc);
186 Value *InnerLoopVectorizer::getConsecutiveVector(Value* Val, bool Negate) {
187 assert(Val->getType()->isVectorTy() && "Must be a vector");
188 assert(Val->getType()->getScalarType()->isIntegerTy() &&
189 "Elem must be an integer");
191 Type *ITy = Val->getType()->getScalarType();
192 VectorType *Ty = cast<VectorType>(Val->getType());
193 int VLen = Ty->getNumElements();
194 SmallVector<Constant*, 8> Indices;
196 // Create a vector of consecutive numbers from zero to VF.
197 for (int i = 0; i < VLen; ++i)
198 Indices.push_back(ConstantInt::get(ITy, Negate ? (-i): i ));
200 // Add the consecutive indices to the vector value.
201 Constant *Cv = ConstantVector::get(Indices);
202 assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
203 return Builder.CreateAdd(Val, Cv, "induction");
206 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
207 assert(Ptr->getType()->isPointerTy() && "Unexpected non ptr");
209 // If this value is a pointer induction variable we know it is consecutive.
210 PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
211 if (Phi && Inductions.count(Phi)) {
212 InductionInfo II = Inductions[Phi];
213 if (PtrInduction == II.IK)
217 GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
221 unsigned NumOperands = Gep->getNumOperands();
222 Value *LastIndex = Gep->getOperand(NumOperands - 1);
224 // Check that all of the gep indices are uniform except for the last.
225 for (unsigned i = 0; i < NumOperands - 1; ++i)
226 if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
229 // We can emit wide load/stores only if the last index is the induction
231 const SCEV *Last = SE->getSCEV(LastIndex);
232 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
233 const SCEV *Step = AR->getStepRecurrence(*SE);
235 // The memory is consecutive because the last index is consecutive
236 // and all other indices are loop invariant.
239 if (Step->isAllOnesValue())
246 bool LoopVectorizationLegality::isUniform(Value *V) {
247 return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
250 Value *InnerLoopVectorizer::getVectorValue(Value *V) {
251 assert(V != Induction && "The new induction variable should not be used.");
252 assert(!V->getType()->isVectorTy() && "Can't widen a vector");
253 // If we saved a vectorized copy of V, use it.
254 Value *&MapEntry = WidenMap[V];
258 // Broadcast V and save the value for future uses.
259 Value *B = getBroadcastInstrs(V);
265 InnerLoopVectorizer::getUniformVector(unsigned Val, Type* ScalarTy) {
266 return ConstantVector::getSplat(VF, ConstantInt::get(ScalarTy, Val, true));
269 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
270 assert(Vec->getType()->isVectorTy() && "Invalid type");
271 SmallVector<Constant*, 8> ShuffleMask;
272 for (unsigned i = 0; i < VF; ++i)
273 ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
275 return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
276 ConstantVector::get(ShuffleMask),
280 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr) {
281 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
282 // Holds vector parameters or scalars, in case of uniform vals.
283 SmallVector<Value*, 8> Params;
285 // Find all of the vectorized parameters.
286 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
287 Value *SrcOp = Instr->getOperand(op);
289 // If we are accessing the old induction variable, use the new one.
290 if (SrcOp == OldInduction) {
291 Params.push_back(getVectorValue(SrcOp));
295 // Try using previously calculated values.
296 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
298 // If the src is an instruction that appeared earlier in the basic block
299 // then it should already be vectorized.
300 if (SrcInst && OrigLoop->contains(SrcInst)) {
301 assert(WidenMap.count(SrcInst) && "Source operand is unavailable");
302 // The parameter is a vector value from earlier.
303 Params.push_back(WidenMap[SrcInst]);
305 // The parameter is a scalar from outside the loop. Maybe even a constant.
306 Params.push_back(SrcOp);
310 assert(Params.size() == Instr->getNumOperands() &&
311 "Invalid number of operands");
313 // Does this instruction return a value ?
314 bool IsVoidRetTy = Instr->getType()->isVoidTy();
315 Value *VecResults = 0;
317 // If we have a return value, create an empty vector. We place the scalarized
318 // instructions in this vector.
320 VecResults = UndefValue::get(VectorType::get(Instr->getType(), VF));
322 // For each scalar that we create:
323 for (unsigned i = 0; i < VF; ++i) {
324 Instruction *Cloned = Instr->clone();
326 Cloned->setName(Instr->getName() + ".cloned");
327 // Replace the operands of the cloned instrucions with extracted scalars.
328 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
329 Value *Op = Params[op];
330 // Param is a vector. Need to extract the right lane.
331 if (Op->getType()->isVectorTy())
332 Op = Builder.CreateExtractElement(Op, Builder.getInt32(i));
333 Cloned->setOperand(op, Op);
336 // Place the cloned scalar in the new loop.
337 Builder.Insert(Cloned);
339 // If the original scalar returns a value we need to place it in a vector
340 // so that future users will be able to use it.
342 VecResults = Builder.CreateInsertElement(VecResults, Cloned,
343 Builder.getInt32(i));
347 WidenMap[Instr] = VecResults;
351 InnerLoopVectorizer::addRuntimeCheck(LoopVectorizationLegality *Legal,
353 LoopVectorizationLegality::RuntimePointerCheck *PtrRtCheck =
354 Legal->getRuntimePointerCheck();
356 if (!PtrRtCheck->Need)
359 Value *MemoryRuntimeCheck = 0;
360 unsigned NumPointers = PtrRtCheck->Pointers.size();
361 SmallVector<Value* , 2> Starts;
362 SmallVector<Value* , 2> Ends;
364 SCEVExpander Exp(*SE, "induction");
366 // Use this type for pointer arithmetic.
367 Type* PtrArithTy = Type::getInt8PtrTy(Loc->getContext(), 0);
369 for (unsigned i = 0; i < NumPointers; ++i) {
370 Value *Ptr = PtrRtCheck->Pointers[i];
371 const SCEV *Sc = SE->getSCEV(Ptr);
373 if (SE->isLoopInvariant(Sc, OrigLoop)) {
374 DEBUG(dbgs() << "LV: Adding RT check for a loop invariant ptr:" <<
376 Starts.push_back(Ptr);
379 DEBUG(dbgs() << "LV: Adding RT check for range:" << *Ptr <<"\n");
381 Value *Start = Exp.expandCodeFor(PtrRtCheck->Starts[i], PtrArithTy, Loc);
382 Value *End = Exp.expandCodeFor(PtrRtCheck->Ends[i], PtrArithTy, Loc);
383 Starts.push_back(Start);
388 for (unsigned i = 0; i < NumPointers; ++i) {
389 for (unsigned j = i+1; j < NumPointers; ++j) {
390 Instruction::CastOps Op = Instruction::BitCast;
391 Value *Start0 = CastInst::Create(Op, Starts[i], PtrArithTy, "bc", Loc);
392 Value *Start1 = CastInst::Create(Op, Starts[j], PtrArithTy, "bc", Loc);
393 Value *End0 = CastInst::Create(Op, Ends[i], PtrArithTy, "bc", Loc);
394 Value *End1 = CastInst::Create(Op, Ends[j], PtrArithTy, "bc", Loc);
396 Value *Cmp0 = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_ULE,
397 Start0, End1, "bound0", Loc);
398 Value *Cmp1 = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_ULE,
399 Start1, End0, "bound1", Loc);
400 Value *IsConflict = BinaryOperator::Create(Instruction::And, Cmp0, Cmp1,
401 "found.conflict", Loc);
402 if (MemoryRuntimeCheck)
403 MemoryRuntimeCheck = BinaryOperator::Create(Instruction::Or,
406 "conflict.rdx", Loc);
408 MemoryRuntimeCheck = IsConflict;
413 return MemoryRuntimeCheck;
417 InnerLoopVectorizer::createEmptyLoop(LoopVectorizationLegality *Legal) {
419 In this function we generate a new loop. The new loop will contain
420 the vectorized instructions while the old loop will continue to run the
423 [ ] <-- vector loop bypass.
426 | [ ] <-- vector pre header.
430 | [ ]_| <-- vector loop.
433 >[ ] <--- middle-block.
436 | [ ] <--- new preheader.
440 | [ ]_| <-- old scalar loop to handle remainder.
447 BasicBlock *OldBasicBlock = OrigLoop->getHeader();
448 BasicBlock *BypassBlock = OrigLoop->getLoopPreheader();
449 BasicBlock *ExitBlock = OrigLoop->getExitBlock();
450 assert(ExitBlock && "Must have an exit block");
452 // Some loops have a single integer induction variable, while other loops
453 // don't. One example is c++ iterators that often have multiple pointer
454 // induction variables. In the code below we also support a case where we
455 // don't have a single induction variable.
456 OldInduction = Legal->getInduction();
457 Type *IdxTy = OldInduction ? OldInduction->getType() :
458 DL->getIntPtrType(SE->getContext());
460 // Find the loop boundaries.
461 const SCEV *ExitCount = SE->getExitCount(OrigLoop, OrigLoop->getLoopLatch());
462 assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
464 // Get the total trip count from the count by adding 1.
465 ExitCount = SE->getAddExpr(ExitCount,
466 SE->getConstant(ExitCount->getType(), 1));
468 // Expand the trip count and place the new instructions in the preheader.
469 // Notice that the pre-header does not change, only the loop body.
470 SCEVExpander Exp(*SE, "induction");
472 // Count holds the overall loop count (N).
473 Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
474 BypassBlock->getTerminator());
476 // The loop index does not have to start at Zero. Find the original start
477 // value from the induction PHI node. If we don't have an induction variable
478 // then we know that it starts at zero.
479 Value *StartIdx = OldInduction ?
480 OldInduction->getIncomingValueForBlock(BypassBlock):
481 ConstantInt::get(IdxTy, 0);
483 assert(BypassBlock && "Invalid loop structure");
485 // Generate the code that checks in runtime if arrays overlap.
486 Value *MemoryRuntimeCheck = addRuntimeCheck(Legal,
487 BypassBlock->getTerminator());
489 // Split the single block loop into the two loop structure described above.
490 BasicBlock *VectorPH =
491 BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
492 BasicBlock *VecBody =
493 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
494 BasicBlock *MiddleBlock =
495 VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
496 BasicBlock *ScalarPH =
497 MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
499 // This is the location in which we add all of the logic for bypassing
500 // the new vector loop.
501 Instruction *Loc = BypassBlock->getTerminator();
503 // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
505 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
507 // Generate the induction variable.
508 Induction = Builder.CreatePHI(IdxTy, 2, "index");
509 Constant *Step = ConstantInt::get(IdxTy, VF);
511 // We may need to extend the index in case there is a type mismatch.
512 // We know that the count starts at zero and does not overflow.
513 if (Count->getType() != IdxTy) {
514 // The exit count can be of pointer type. Convert it to the correct
516 if (ExitCount->getType()->isPointerTy())
517 Count = CastInst::CreatePointerCast(Count, IdxTy, "ptrcnt.to.int", Loc);
519 Count = CastInst::CreateZExtOrBitCast(Count, IdxTy, "zext.cnt", Loc);
522 // Add the start index to the loop count to get the new end index.
523 Value *IdxEnd = BinaryOperator::CreateAdd(Count, StartIdx, "end.idx", Loc);
525 // Now we need to generate the expression for N - (N % VF), which is
526 // the part that the vectorized body will execute.
527 Constant *CIVF = ConstantInt::get(IdxTy, VF);
528 Value *R = BinaryOperator::CreateURem(Count, CIVF, "n.mod.vf", Loc);
529 Value *CountRoundDown = BinaryOperator::CreateSub(Count, R, "n.vec", Loc);
530 Value *IdxEndRoundDown = BinaryOperator::CreateAdd(CountRoundDown, StartIdx,
531 "end.idx.rnd.down", Loc);
533 // Now, compare the new count to zero. If it is zero skip the vector loop and
534 // jump to the scalar loop.
535 Value *Cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
540 // If we are using memory runtime checks, include them in.
541 if (MemoryRuntimeCheck)
542 Cmp = BinaryOperator::Create(Instruction::Or, Cmp, MemoryRuntimeCheck,
545 BranchInst::Create(MiddleBlock, VectorPH, Cmp, Loc);
546 // Remove the old terminator.
547 Loc->eraseFromParent();
549 // We are going to resume the execution of the scalar loop.
550 // Go over all of the induction variables that we found and fix the
551 // PHIs that are left in the scalar version of the loop.
552 // The starting values of PHI nodes depend on the counter of the last
553 // iteration in the vectorized loop.
554 // If we come from a bypass edge then we need to start from the original
557 // This variable saves the new starting index for the scalar loop.
558 PHINode *ResumeIndex = 0;
559 LoopVectorizationLegality::InductionList::iterator I, E;
560 LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
561 for (I = List->begin(), E = List->end(); I != E; ++I) {
562 PHINode *OrigPhi = I->first;
563 LoopVectorizationLegality::InductionInfo II = I->second;
564 PHINode *ResumeVal = PHINode::Create(OrigPhi->getType(), 2, "resume.val",
565 MiddleBlock->getTerminator());
568 case LoopVectorizationLegality::NoInduction:
569 llvm_unreachable("Unknown induction");
570 case LoopVectorizationLegality::IntInduction: {
571 // Handle the integer induction counter:
572 assert(OrigPhi->getType()->isIntegerTy() && "Invalid type");
573 assert(OrigPhi == OldInduction && "Unknown integer PHI");
574 // We know what the end value is.
575 EndValue = IdxEndRoundDown;
576 // We also know which PHI node holds it.
577 ResumeIndex = ResumeVal;
580 case LoopVectorizationLegality::ReverseIntInduction: {
581 // Convert the CountRoundDown variable to the PHI size.
582 unsigned CRDSize = CountRoundDown->getType()->getScalarSizeInBits();
583 unsigned IISize = II.StartValue->getType()->getScalarSizeInBits();
584 Value *CRD = CountRoundDown;
585 if (CRDSize > IISize)
586 CRD = CastInst::Create(Instruction::Trunc, CountRoundDown,
587 II.StartValue->getType(),
588 "tr.crd", BypassBlock->getTerminator());
589 else if (CRDSize < IISize)
590 CRD = CastInst::Create(Instruction::SExt, CountRoundDown,
591 II.StartValue->getType(),
592 "sext.crd", BypassBlock->getTerminator());
593 // Handle reverse integer induction counter:
594 EndValue = BinaryOperator::CreateSub(II.StartValue, CRD, "rev.ind.end",
595 BypassBlock->getTerminator());
598 case LoopVectorizationLegality::PtrInduction: {
599 // For pointer induction variables, calculate the offset using
601 EndValue = GetElementPtrInst::Create(II.StartValue, CountRoundDown,
603 BypassBlock->getTerminator());
608 // The new PHI merges the original incoming value, in case of a bypass,
609 // or the value at the end of the vectorized loop.
610 ResumeVal->addIncoming(II.StartValue, BypassBlock);
611 ResumeVal->addIncoming(EndValue, VecBody);
613 // Fix the scalar body counter (PHI node).
614 unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
615 OrigPhi->setIncomingValue(BlockIdx, ResumeVal);
618 // If we are generating a new induction variable then we also need to
619 // generate the code that calculates the exit value. This value is not
620 // simply the end of the counter because we may skip the vectorized body
621 // in case of a runtime check.
623 assert(!ResumeIndex && "Unexpected resume value found");
624 ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val",
625 MiddleBlock->getTerminator());
626 ResumeIndex->addIncoming(StartIdx, BypassBlock);
627 ResumeIndex->addIncoming(IdxEndRoundDown, VecBody);
630 // Make sure that we found the index where scalar loop needs to continue.
631 assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() &&
632 "Invalid resume Index");
634 // Add a check in the middle block to see if we have completed
635 // all of the iterations in the first vector loop.
636 // If (N - N%VF) == N, then we *don't* need to run the remainder.
637 Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd,
638 ResumeIndex, "cmp.n",
639 MiddleBlock->getTerminator());
641 BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
642 // Remove the old terminator.
643 MiddleBlock->getTerminator()->eraseFromParent();
645 // Create i+1 and fill the PHINode.
646 Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
647 Induction->addIncoming(StartIdx, VectorPH);
648 Induction->addIncoming(NextIdx, VecBody);
649 // Create the compare.
650 Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown);
651 Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
653 // Now we have two terminators. Remove the old one from the block.
654 VecBody->getTerminator()->eraseFromParent();
656 // Get ready to start creating new instructions into the vectorized body.
657 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
659 // Create and register the new vector loop.
660 Loop* Lp = new Loop();
661 Loop *ParentLoop = OrigLoop->getParentLoop();
663 // Insert the new loop into the loop nest and register the new basic blocks.
665 ParentLoop->addChildLoop(Lp);
666 ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase());
667 ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase());
668 ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase());
670 LI->addTopLevelLoop(Lp);
673 Lp->addBasicBlockToLoop(VecBody, LI->getBase());
676 LoopVectorPreHeader = VectorPH;
677 LoopScalarPreHeader = ScalarPH;
678 LoopMiddleBlock = MiddleBlock;
679 LoopExitBlock = ExitBlock;
680 LoopVectorBody = VecBody;
681 LoopScalarBody = OldBasicBlock;
682 LoopBypassBlock = BypassBlock;
685 /// This function returns the identity element (or neutral element) for
688 getReductionIdentity(LoopVectorizationLegality::ReductionKind K) {
690 case LoopVectorizationLegality::IntegerXor:
691 case LoopVectorizationLegality::IntegerAdd:
692 case LoopVectorizationLegality::IntegerOr:
693 // Adding, Xoring, Oring zero to a number does not change it.
695 case LoopVectorizationLegality::IntegerMult:
696 // Multiplying a number by 1 does not change it.
698 case LoopVectorizationLegality::IntegerAnd:
699 // AND-ing a number with an all-1 value does not change it.
702 llvm_unreachable("Unknown reduction kind");
707 isTriviallyVectorizableIntrinsic(Instruction *Inst) {
708 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst);
711 switch (II->getIntrinsicID()) {
712 case Intrinsic::sqrt:
716 case Intrinsic::exp2:
718 case Intrinsic::log10:
719 case Intrinsic::log2:
720 case Intrinsic::fabs:
721 case Intrinsic::floor:
722 case Intrinsic::ceil:
723 case Intrinsic::trunc:
724 case Intrinsic::rint:
725 case Intrinsic::nearbyint:
728 case Intrinsic::fmuladd:
737 InnerLoopVectorizer::vectorizeLoop(LoopVectorizationLegality *Legal) {
738 //===------------------------------------------------===//
740 // Notice: any optimization or new instruction that go
741 // into the code below should be also be implemented in
744 //===------------------------------------------------===//
745 BasicBlock &BB = *OrigLoop->getHeader();
747 ConstantInt::get(IntegerType::getInt32Ty(BB.getContext()), 0);
749 // In order to support reduction variables we need to be able to vectorize
750 // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
751 // stages. First, we create a new vector PHI node with no incoming edges.
752 // We use this value when we vectorize all of the instructions that use the
753 // PHI. Next, after all of the instructions in the block are complete we
754 // add the new incoming edges to the PHI. At this point all of the
755 // instructions in the basic block are vectorized, so we can use them to
756 // construct the PHI.
757 PhiVector RdxPHIsToFix;
759 // Scan the loop in a topological order to ensure that defs are vectorized
761 LoopBlocksDFS DFS(OrigLoop);
764 // Vectorize all of the blocks in the original loop.
765 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
766 be = DFS.endRPO(); bb != be; ++bb)
767 vectorizeBlockInLoop(Legal, *bb, &RdxPHIsToFix);
769 // At this point every instruction in the original loop is widened to
770 // a vector form. We are almost done. Now, we need to fix the PHI nodes
771 // that we vectorized. The PHI nodes are currently empty because we did
772 // not want to introduce cycles. Notice that the remaining PHI nodes
773 // that we need to fix are reduction variables.
775 // Create the 'reduced' values for each of the induction vars.
776 // The reduced values are the vector values that we scalarize and combine
777 // after the loop is finished.
778 for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
780 PHINode *RdxPhi = *it;
781 PHINode *VecRdxPhi = dyn_cast<PHINode>(WidenMap[RdxPhi]);
782 assert(RdxPhi && "Unable to recover vectorized PHI");
784 // Find the reduction variable descriptor.
785 assert(Legal->getReductionVars()->count(RdxPhi) &&
786 "Unable to find the reduction variable");
787 LoopVectorizationLegality::ReductionDescriptor RdxDesc =
788 (*Legal->getReductionVars())[RdxPhi];
790 // We need to generate a reduction vector from the incoming scalar.
791 // To do so, we need to generate the 'identity' vector and overide
792 // one of the elements with the incoming scalar reduction. We need
793 // to do it in the vector-loop preheader.
794 Builder.SetInsertPoint(LoopBypassBlock->getTerminator());
796 // This is the vector-clone of the value that leaves the loop.
797 Value *VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
798 Type *VecTy = VectorExit->getType();
800 // Find the reduction identity variable. Zero for addition, or, xor,
801 // one for multiplication, -1 for And.
802 Constant *Identity = getUniformVector(getReductionIdentity(RdxDesc.Kind),
803 VecTy->getScalarType());
805 // This vector is the Identity vector where the first element is the
806 // incoming scalar reduction.
807 Value *VectorStart = Builder.CreateInsertElement(Identity,
808 RdxDesc.StartValue, Zero);
810 // Fix the vector-loop phi.
811 // We created the induction variable so we know that the
812 // preheader is the first entry.
813 BasicBlock *VecPreheader = Induction->getIncomingBlock(0);
815 // Reductions do not have to start at zero. They can start with
816 // any loop invariant values.
817 VecRdxPhi->addIncoming(VectorStart, VecPreheader);
819 getVectorValue(RdxPhi->getIncomingValueForBlock(OrigLoop->getLoopLatch()));
820 VecRdxPhi->addIncoming(Val, LoopVectorBody);
822 // Before each round, move the insertion point right between
823 // the PHIs and the values we are going to write.
824 // This allows us to write both PHINodes and the extractelement
826 Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
828 // This PHINode contains the vectorized reduction variable, or
829 // the initial value vector, if we bypass the vector loop.
830 PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
831 NewPhi->addIncoming(VectorStart, LoopBypassBlock);
832 NewPhi->addIncoming(getVectorValue(RdxDesc.LoopExitInstr), LoopVectorBody);
834 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
835 // and vector ops, reducing the set of values being computed by half each
837 assert(isPowerOf2_32(VF) &&
838 "Reduction emission only supported for pow2 vectors!");
839 Value *TmpVec = NewPhi;
840 SmallVector<Constant*, 32> ShuffleMask(VF, 0);
841 for (unsigned i = VF; i != 1; i >>= 1) {
842 // Move the upper half of the vector to the lower half.
843 for (unsigned j = 0; j != i/2; ++j)
844 ShuffleMask[j] = Builder.getInt32(i/2 + j);
846 // Fill the rest of the mask with undef.
847 std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
848 UndefValue::get(Builder.getInt32Ty()));
851 Builder.CreateShuffleVector(TmpVec,
852 UndefValue::get(TmpVec->getType()),
853 ConstantVector::get(ShuffleMask),
856 // Emit the operation on the shuffled value.
857 switch (RdxDesc.Kind) {
858 case LoopVectorizationLegality::IntegerAdd:
859 TmpVec = Builder.CreateAdd(TmpVec, Shuf, "add.rdx");
861 case LoopVectorizationLegality::IntegerMult:
862 TmpVec = Builder.CreateMul(TmpVec, Shuf, "mul.rdx");
864 case LoopVectorizationLegality::IntegerOr:
865 TmpVec = Builder.CreateOr(TmpVec, Shuf, "or.rdx");
867 case LoopVectorizationLegality::IntegerAnd:
868 TmpVec = Builder.CreateAnd(TmpVec, Shuf, "and.rdx");
870 case LoopVectorizationLegality::IntegerXor:
871 TmpVec = Builder.CreateXor(TmpVec, Shuf, "xor.rdx");
874 llvm_unreachable("Unknown reduction operation");
878 // The result is in the first element of the vector.
879 Value *Scalar0 = Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
881 // Now, we need to fix the users of the reduction variable
882 // inside and outside of the scalar remainder loop.
883 // We know that the loop is in LCSSA form. We need to update the
884 // PHI nodes in the exit blocks.
885 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
886 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
887 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
888 if (!LCSSAPhi) continue;
890 // All PHINodes need to have a single entry edge, or two if
891 // we already fixed them.
892 assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
894 // We found our reduction value exit-PHI. Update it with the
895 // incoming bypass edge.
896 if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
897 // Add an edge coming from the bypass.
898 LCSSAPhi->addIncoming(Scalar0, LoopMiddleBlock);
901 }// end of the LCSSA phi scan.
903 // Fix the scalar loop reduction variable with the incoming reduction sum
904 // from the vector body and from the backedge value.
905 int IncomingEdgeBlockIdx =
906 (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
907 assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
908 // Pick the other block.
909 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
910 (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, Scalar0);
911 (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
912 }// end of for each redux variable.
914 // The Loop exit block may have single value PHI nodes where the incoming
915 // value is 'undef'. While vectorizing we only handled real values that
916 // were defined inside the loop. Here we handle the 'undef case'.
918 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
919 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
920 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
921 if (!LCSSAPhi) continue;
922 if (LCSSAPhi->getNumIncomingValues() == 1)
923 LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
928 Value *InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
929 assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
932 Value *SrcMask = createBlockInMask(Src);
934 // The terminator has to be a branch inst!
935 BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
936 assert(BI && "Unexpected terminator found");
938 Value *EdgeMask = SrcMask;
939 if (BI->isConditional()) {
940 EdgeMask = getVectorValue(BI->getCondition());
941 if (BI->getSuccessor(0) != Dst)
942 EdgeMask = Builder.CreateNot(EdgeMask);
945 return Builder.CreateAnd(EdgeMask, SrcMask);
948 Value *InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
949 assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
951 // Loop incoming mask is all-one.
952 if (OrigLoop->getHeader() == BB) {
953 Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
954 return getVectorValue(C);
957 // This is the block mask. We OR all incoming edges, and with zero.
958 Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
959 Value *BlockMask = getVectorValue(Zero);
962 for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it)
963 BlockMask = Builder.CreateOr(BlockMask, createEdgeMask(*it, BB));
969 InnerLoopVectorizer::vectorizeBlockInLoop(LoopVectorizationLegality *Legal,
970 BasicBlock *BB, PhiVector *PV) {
971 Constant *Zero = Builder.getInt32(0);
973 // For each instruction in the old loop.
974 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
975 switch (it->getOpcode()) {
976 case Instruction::Br:
977 // Nothing to do for PHIs and BR, since we already took care of the
978 // loop control flow instructions.
980 case Instruction::PHI:{
981 PHINode* P = cast<PHINode>(it);
982 // Handle reduction variables:
983 if (Legal->getReductionVars()->count(P)) {
984 // This is phase one of vectorizing PHIs.
985 Type *VecTy = VectorType::get(it->getType(), VF);
987 PHINode::Create(VecTy, 2, "vec.phi",
988 LoopVectorBody->getFirstInsertionPt());
993 // Check for PHI nodes that are lowered to vector selects.
994 if (P->getParent() != OrigLoop->getHeader()) {
995 // We know that all PHIs in non header blocks are converted into
996 // selects, so we don't have to worry about the insertion order and we
997 // can just use the builder.
999 // At this point we generate the predication tree. There may be
1000 // duplications since this is a simple recursive scan, but future
1001 // optimizations will clean it up.
1002 Value *Cond = createEdgeMask(P->getIncomingBlock(0), P->getParent());
1004 Builder.CreateSelect(Cond,
1005 getVectorValue(P->getIncomingValue(0)),
1006 getVectorValue(P->getIncomingValue(1)),
1011 // This PHINode must be an induction variable.
1012 // Make sure that we know about it.
1013 assert(Legal->getInductionVars()->count(P) &&
1014 "Not an induction variable");
1016 LoopVectorizationLegality::InductionInfo II =
1017 Legal->getInductionVars()->lookup(P);
1020 case LoopVectorizationLegality::NoInduction:
1021 llvm_unreachable("Unknown induction");
1022 case LoopVectorizationLegality::IntInduction: {
1023 assert(P == OldInduction && "Unexpected PHI");
1024 Value *Broadcasted = getBroadcastInstrs(Induction);
1025 // After broadcasting the induction variable we need to make the
1026 // vector consecutive by adding 0, 1, 2 ...
1027 Value *ConsecutiveInduction = getConsecutiveVector(Broadcasted);
1028 WidenMap[OldInduction] = ConsecutiveInduction;
1031 case LoopVectorizationLegality::ReverseIntInduction:
1032 case LoopVectorizationLegality::PtrInduction:
1033 // Handle reverse integer and pointer inductions.
1034 Value *StartIdx = 0;
1035 // If we have a single integer induction variable then use it.
1036 // Otherwise, start counting at zero.
1038 LoopVectorizationLegality::InductionInfo OldII =
1039 Legal->getInductionVars()->lookup(OldInduction);
1040 StartIdx = OldII.StartValue;
1042 StartIdx = ConstantInt::get(Induction->getType(), 0);
1044 // This is the normalized GEP that starts counting at zero.
1045 Value *NormalizedIdx = Builder.CreateSub(Induction, StartIdx,
1048 // Handle the reverse integer induction variable case.
1049 if (LoopVectorizationLegality::ReverseIntInduction == II.IK) {
1050 IntegerType *DstTy = cast<IntegerType>(II.StartValue->getType());
1051 Value *CNI = Builder.CreateSExtOrTrunc(NormalizedIdx, DstTy,
1053 Value *ReverseInd = Builder.CreateSub(II.StartValue, CNI,
1056 // This is a new value so do not hoist it out.
1057 Value *Broadcasted = getBroadcastInstrs(ReverseInd);
1058 // After broadcasting the induction variable we need to make the
1059 // vector consecutive by adding ... -3, -2, -1, 0.
1060 Value *ConsecutiveInduction = getConsecutiveVector(Broadcasted,
1062 WidenMap[it] = ConsecutiveInduction;
1066 // Handle the pointer induction variable case.
1067 assert(P->getType()->isPointerTy() && "Unexpected type.");
1069 // This is the vector of results. Notice that we don't generate
1070 // vector geps because scalar geps result in better code.
1071 Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
1072 for (unsigned int i = 0; i < VF; ++i) {
1073 Constant *Idx = ConstantInt::get(Induction->getType(), i);
1074 Value *GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx,
1076 Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
1078 VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
1079 Builder.getInt32(i),
1083 WidenMap[it] = VecVal;
1089 case Instruction::Add:
1090 case Instruction::FAdd:
1091 case Instruction::Sub:
1092 case Instruction::FSub:
1093 case Instruction::Mul:
1094 case Instruction::FMul:
1095 case Instruction::UDiv:
1096 case Instruction::SDiv:
1097 case Instruction::FDiv:
1098 case Instruction::URem:
1099 case Instruction::SRem:
1100 case Instruction::FRem:
1101 case Instruction::Shl:
1102 case Instruction::LShr:
1103 case Instruction::AShr:
1104 case Instruction::And:
1105 case Instruction::Or:
1106 case Instruction::Xor: {
1107 // Just widen binops.
1108 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
1109 Value *A = getVectorValue(it->getOperand(0));
1110 Value *B = getVectorValue(it->getOperand(1));
1112 // Use this vector value for all users of the original instruction.
1113 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A, B);
1116 // Update the NSW, NUW and Exact flags.
1117 BinaryOperator *VecOp = cast<BinaryOperator>(V);
1118 if (isa<OverflowingBinaryOperator>(BinOp)) {
1119 VecOp->setHasNoSignedWrap(BinOp->hasNoSignedWrap());
1120 VecOp->setHasNoUnsignedWrap(BinOp->hasNoUnsignedWrap());
1122 if (isa<PossiblyExactOperator>(VecOp))
1123 VecOp->setIsExact(BinOp->isExact());
1126 case Instruction::Select: {
1128 // If the selector is loop invariant we can create a select
1129 // instruction with a scalar condition. Otherwise, use vector-select.
1130 Value *Cond = it->getOperand(0);
1131 bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(Cond), OrigLoop);
1133 // The condition can be loop invariant but still defined inside the
1134 // loop. This means that we can't just use the original 'cond' value.
1135 // We have to take the 'vectorized' value and pick the first lane.
1136 // Instcombine will make this a no-op.
1137 Cond = getVectorValue(Cond);
1139 Cond = Builder.CreateExtractElement(Cond, Builder.getInt32(0));
1141 Value *Op0 = getVectorValue(it->getOperand(1));
1142 Value *Op1 = getVectorValue(it->getOperand(2));
1143 WidenMap[it] = Builder.CreateSelect(Cond, Op0, Op1);
1147 case Instruction::ICmp:
1148 case Instruction::FCmp: {
1149 // Widen compares. Generate vector compares.
1150 bool FCmp = (it->getOpcode() == Instruction::FCmp);
1151 CmpInst *Cmp = dyn_cast<CmpInst>(it);
1152 Value *A = getVectorValue(it->getOperand(0));
1153 Value *B = getVectorValue(it->getOperand(1));
1155 WidenMap[it] = Builder.CreateFCmp(Cmp->getPredicate(), A, B);
1157 WidenMap[it] = Builder.CreateICmp(Cmp->getPredicate(), A, B);
1161 case Instruction::Store: {
1162 // Attempt to issue a wide store.
1163 StoreInst *SI = dyn_cast<StoreInst>(it);
1164 Type *StTy = VectorType::get(SI->getValueOperand()->getType(), VF);
1165 Value *Ptr = SI->getPointerOperand();
1166 unsigned Alignment = SI->getAlignment();
1168 assert(!Legal->isUniform(Ptr) &&
1169 "We do not allow storing to uniform addresses");
1172 int Stride = Legal->isConsecutivePtr(Ptr);
1173 bool Reverse = Stride < 0;
1175 scalarizeInstruction(it);
1179 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1181 // The last index does not have to be the induction. It can be
1182 // consecutive and be a function of the index. For example A[I+1];
1183 unsigned NumOperands = Gep->getNumOperands();
1184 Value *LastIndex = getVectorValue(Gep->getOperand(NumOperands - 1));
1185 LastIndex = Builder.CreateExtractElement(LastIndex, Zero);
1187 // Create the new GEP with the new induction variable.
1188 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1189 Gep2->setOperand(NumOperands - 1, LastIndex);
1190 Ptr = Builder.Insert(Gep2);
1192 // Use the induction element ptr.
1193 assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1194 Ptr = Builder.CreateExtractElement(getVectorValue(Ptr), Zero);
1197 // If the address is consecutive but reversed, then the
1198 // wide load needs to start at the last vector element.
1200 Ptr = Builder.CreateGEP(Ptr, Builder.getInt32(1 - VF));
1202 Ptr = Builder.CreateBitCast(Ptr, StTy->getPointerTo());
1203 Value *Val = getVectorValue(SI->getValueOperand());
1205 Val = reverseVector(Val);
1206 Builder.CreateStore(Val, Ptr)->setAlignment(Alignment);
1209 case Instruction::Load: {
1210 // Attempt to issue a wide load.
1211 LoadInst *LI = dyn_cast<LoadInst>(it);
1212 Type *RetTy = VectorType::get(LI->getType(), VF);
1213 Value *Ptr = LI->getPointerOperand();
1214 unsigned Alignment = LI->getAlignment();
1216 // If the pointer is loop invariant or if it is non consecutive,
1217 // scalarize the load.
1218 int Stride = Legal->isConsecutivePtr(Ptr);
1219 bool Reverse = Stride < 0;
1220 if (Legal->isUniform(Ptr) || Stride == 0) {
1221 scalarizeInstruction(it);
1225 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1227 // The last index does not have to be the induction. It can be
1228 // consecutive and be a function of the index. For example A[I+1];
1229 unsigned NumOperands = Gep->getNumOperands();
1230 Value *LastIndex = getVectorValue(Gep->getOperand(NumOperands -1));
1231 LastIndex = Builder.CreateExtractElement(LastIndex, Zero);
1233 // Create the new GEP with the new induction variable.
1234 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1235 Gep2->setOperand(NumOperands - 1, LastIndex);
1236 Ptr = Builder.Insert(Gep2);
1238 // Use the induction element ptr.
1239 assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1240 Ptr = Builder.CreateExtractElement(getVectorValue(Ptr), Zero);
1242 // If the address is consecutive but reversed, then the
1243 // wide load needs to start at the last vector element.
1245 Ptr = Builder.CreateGEP(Ptr, Builder.getInt32(1 - VF));
1247 Ptr = Builder.CreateBitCast(Ptr, RetTy->getPointerTo());
1248 LI = Builder.CreateLoad(Ptr);
1249 LI->setAlignment(Alignment);
1251 // Use this vector value for all users of the load.
1252 WidenMap[it] = Reverse ? reverseVector(LI) : LI;
1255 case Instruction::ZExt:
1256 case Instruction::SExt:
1257 case Instruction::FPToUI:
1258 case Instruction::FPToSI:
1259 case Instruction::FPExt:
1260 case Instruction::PtrToInt:
1261 case Instruction::IntToPtr:
1262 case Instruction::SIToFP:
1263 case Instruction::UIToFP:
1264 case Instruction::Trunc:
1265 case Instruction::FPTrunc:
1266 case Instruction::BitCast: {
1267 CastInst *CI = dyn_cast<CastInst>(it);
1268 /// Optimize the special case where the source is the induction
1269 /// variable. Notice that we can only optimize the 'trunc' case
1270 /// because: a. FP conversions lose precision, b. sext/zext may wrap,
1271 /// c. other casts depend on pointer size.
1272 if (CI->getOperand(0) == OldInduction &&
1273 it->getOpcode() == Instruction::Trunc) {
1274 Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
1276 Value *Broadcasted = getBroadcastInstrs(ScalarCast);
1277 WidenMap[it] = getConsecutiveVector(Broadcasted);
1280 /// Vectorize casts.
1281 Value *A = getVectorValue(it->getOperand(0));
1282 Type *DestTy = VectorType::get(CI->getType()->getScalarType(), VF);
1283 WidenMap[it] = Builder.CreateCast(CI->getOpcode(), A, DestTy);
1287 case Instruction::Call: {
1288 assert(isTriviallyVectorizableIntrinsic(it));
1289 Module *M = BB->getParent()->getParent();
1290 IntrinsicInst *II = cast<IntrinsicInst>(it);
1291 Intrinsic::ID ID = II->getIntrinsicID();
1292 SmallVector<Value*, 4> Args;
1293 for (unsigned i = 0, ie = II->getNumArgOperands(); i != ie; ++i)
1294 Args.push_back(getVectorValue(II->getArgOperand(i)));
1295 Type *Tys[] = { VectorType::get(II->getType()->getScalarType(), VF) };
1296 Function *F = Intrinsic::getDeclaration(M, ID, Tys);
1297 WidenMap[it] = Builder.CreateCall(F, Args);
1302 // All other instructions are unsupported. Scalarize them.
1303 scalarizeInstruction(it);
1306 }// end of for_each instr.
1309 void InnerLoopVectorizer::updateAnalysis() {
1310 // Forget the original basic block.
1311 SE->forgetLoop(OrigLoop);
1313 // Update the dominator tree information.
1314 assert(DT->properlyDominates(LoopBypassBlock, LoopExitBlock) &&
1315 "Entry does not dominate exit.");
1317 DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlock);
1318 DT->addNewBlock(LoopVectorBody, LoopVectorPreHeader);
1319 DT->addNewBlock(LoopMiddleBlock, LoopBypassBlock);
1320 DT->addNewBlock(LoopScalarPreHeader, LoopMiddleBlock);
1321 DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
1322 DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
1324 DEBUG(DT->verifyAnalysis());
1327 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
1328 if (!EnableIfConversion)
1331 assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
1332 std::vector<BasicBlock*> &LoopBlocks = TheLoop->getBlocksVector();
1334 // Collect the blocks that need predication.
1335 for (unsigned i = 0, e = LoopBlocks.size(); i < e; ++i) {
1336 BasicBlock *BB = LoopBlocks[i];
1338 // We don't support switch statements inside loops.
1339 if (!isa<BranchInst>(BB->getTerminator()))
1342 // We must have at most two predecessors because we need to convert
1343 // all PHIs to selects.
1344 unsigned Preds = std::distance(pred_begin(BB), pred_end(BB));
1348 // We must be able to predicate all blocks that need to be predicated.
1349 if (blockNeedsPredication(BB) && !blockCanBePredicated(BB))
1353 // We can if-convert this loop.
1357 bool LoopVectorizationLegality::canVectorize() {
1358 assert(TheLoop->getLoopPreheader() && "No preheader!!");
1360 // We can only vectorize innermost loops.
1361 if (TheLoop->getSubLoopsVector().size())
1364 // We must have a single backedge.
1365 if (TheLoop->getNumBackEdges() != 1)
1368 // We must have a single exiting block.
1369 if (!TheLoop->getExitingBlock())
1372 unsigned NumBlocks = TheLoop->getNumBlocks();
1374 // Check if we can if-convert non single-bb loops.
1375 if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
1376 DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
1380 // We need to have a loop header.
1381 BasicBlock *Latch = TheLoop->getLoopLatch();
1382 DEBUG(dbgs() << "LV: Found a loop: " <<
1383 TheLoop->getHeader()->getName() << "\n");
1385 // ScalarEvolution needs to be able to find the exit count.
1386 const SCEV *ExitCount = SE->getExitCount(TheLoop, Latch);
1387 if (ExitCount == SE->getCouldNotCompute()) {
1388 DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
1392 // Do not loop-vectorize loops with a tiny trip count.
1393 unsigned TC = SE->getSmallConstantTripCount(TheLoop, Latch);
1394 if (TC > 0u && TC < TinyTripCountThreshold) {
1395 DEBUG(dbgs() << "LV: Found a loop with a very small trip count. " <<
1396 "This loop is not worth vectorizing.\n");
1400 // Check if we can vectorize the instructions and CFG in this loop.
1401 if (!canVectorizeInstrs()) {
1402 DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
1406 // Go over each instruction and look at memory deps.
1407 if (!canVectorizeMemory()) {
1408 DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
1412 // Collect all of the variables that remain uniform after vectorization.
1413 collectLoopUniforms();
1415 DEBUG(dbgs() << "LV: We can vectorize this loop" <<
1416 (PtrRtCheck.Need ? " (with a runtime bound check)" : "")
1419 // Okay! We can vectorize. At this point we don't have any other mem analysis
1420 // which may limit our maximum vectorization factor, so just return true with
1425 bool LoopVectorizationLegality::canVectorizeInstrs() {
1426 BasicBlock *PreHeader = TheLoop->getLoopPreheader();
1427 BasicBlock *Header = TheLoop->getHeader();
1429 // For each block in the loop.
1430 for (Loop::block_iterator bb = TheLoop->block_begin(),
1431 be = TheLoop->block_end(); bb != be; ++bb) {
1433 // Scan the instructions in the block and look for hazards.
1434 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
1437 if (PHINode *Phi = dyn_cast<PHINode>(it)) {
1438 // This should not happen because the loop should be normalized.
1439 if (Phi->getNumIncomingValues() != 2) {
1440 DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
1444 // Check that this PHI type is allowed.
1445 if (!Phi->getType()->isIntegerTy() &&
1446 !Phi->getType()->isPointerTy()) {
1447 DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
1451 // If this PHINode is not in the header block, then we know that we
1452 // can convert it to select during if-conversion. No need to check if
1453 // the PHIs in this block are induction or reduction variables.
1457 // This is the value coming from the preheader.
1458 Value *StartValue = Phi->getIncomingValueForBlock(PreHeader);
1459 // Check if this is an induction variable.
1460 InductionKind IK = isInductionVariable(Phi);
1462 if (NoInduction != IK) {
1463 // Int inductions are special because we only allow one IV.
1464 if (IK == IntInduction) {
1466 DEBUG(dbgs() << "LV: Found too many inductions."<< *Phi <<"\n");
1472 DEBUG(dbgs() << "LV: Found an induction variable.\n");
1473 Inductions[Phi] = InductionInfo(StartValue, IK);
1477 if (AddReductionVar(Phi, IntegerAdd)) {
1478 DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
1481 if (AddReductionVar(Phi, IntegerMult)) {
1482 DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n");
1485 if (AddReductionVar(Phi, IntegerOr)) {
1486 DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n");
1489 if (AddReductionVar(Phi, IntegerAnd)) {
1490 DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n");
1493 if (AddReductionVar(Phi, IntegerXor)) {
1494 DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n");
1498 DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
1500 }// end of PHI handling
1502 // We still don't handle functions.
1503 CallInst *CI = dyn_cast<CallInst>(it);
1504 if (CI && !isTriviallyVectorizableIntrinsic(it)) {
1505 DEBUG(dbgs() << "LV: Found a call site.\n");
1509 // Check that the instruction return type is vectorizable.
1510 if (!VectorType::isValidElementType(it->getType()) &&
1511 !it->getType()->isVoidTy()) {
1512 DEBUG(dbgs() << "LV: Found unvectorizable type." << "\n");
1516 // Check that the stored type is vectorizable.
1517 if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
1518 Type *T = ST->getValueOperand()->getType();
1519 if (!VectorType::isValidElementType(T))
1523 // Reduction instructions are allowed to have exit users.
1524 // All other instructions must not have external users.
1525 if (!AllowedExit.count(it))
1526 //Check that all of the users of the loop are inside the BB.
1527 for (Value::use_iterator I = it->use_begin(), E = it->use_end();
1529 Instruction *U = cast<Instruction>(*I);
1530 // This user may be a reduction exit value.
1531 if (!TheLoop->contains(U)) {
1532 DEBUG(dbgs() << "LV: Found an outside user for : "<< *U << "\n");
1541 DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
1542 assert(getInductionVars()->size() && "No induction variables");
1548 void LoopVectorizationLegality::collectLoopUniforms() {
1549 // We now know that the loop is vectorizable!
1550 // Collect variables that will remain uniform after vectorization.
1551 std::vector<Value*> Worklist;
1552 BasicBlock *Latch = TheLoop->getLoopLatch();
1554 // Start with the conditional branch and walk up the block.
1555 Worklist.push_back(Latch->getTerminator()->getOperand(0));
1557 while (Worklist.size()) {
1558 Instruction *I = dyn_cast<Instruction>(Worklist.back());
1559 Worklist.pop_back();
1561 // Look at instructions inside this loop.
1562 // Stop when reaching PHI nodes.
1563 // TODO: we need to follow values all over the loop, not only in this block.
1564 if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
1567 // This is a known uniform.
1570 // Insert all operands.
1571 for (int i = 0, Op = I->getNumOperands(); i < Op; ++i) {
1572 Worklist.push_back(I->getOperand(i));
1577 bool LoopVectorizationLegality::canVectorizeMemory() {
1578 typedef SmallVector<Value*, 16> ValueVector;
1579 typedef SmallPtrSet<Value*, 16> ValueSet;
1580 // Holds the Load and Store *instructions*.
1583 PtrRtCheck.Pointers.clear();
1584 PtrRtCheck.Need = false;
1587 for (Loop::block_iterator bb = TheLoop->block_begin(),
1588 be = TheLoop->block_end(); bb != be; ++bb) {
1590 // Scan the BB and collect legal loads and stores.
1591 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
1594 // If this is a load, save it. If this instruction can read from memory
1595 // but is not a load, then we quit. Notice that we don't handle function
1596 // calls that read or write.
1597 if (it->mayReadFromMemory()) {
1598 LoadInst *Ld = dyn_cast<LoadInst>(it);
1599 if (!Ld) return false;
1600 if (!Ld->isSimple()) {
1601 DEBUG(dbgs() << "LV: Found a non-simple load.\n");
1604 Loads.push_back(Ld);
1608 // Save 'store' instructions. Abort if other instructions write to memory.
1609 if (it->mayWriteToMemory()) {
1610 StoreInst *St = dyn_cast<StoreInst>(it);
1611 if (!St) return false;
1612 if (!St->isSimple()) {
1613 DEBUG(dbgs() << "LV: Found a non-simple store.\n");
1616 Stores.push_back(St);
1621 // Now we have two lists that hold the loads and the stores.
1622 // Next, we find the pointers that they use.
1624 // Check if we see any stores. If there are no stores, then we don't
1625 // care if the pointers are *restrict*.
1626 if (!Stores.size()) {
1627 DEBUG(dbgs() << "LV: Found a read-only loop!\n");
1631 // Holds the read and read-write *pointers* that we find.
1633 ValueVector ReadWrites;
1635 // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
1636 // multiple times on the same object. If the ptr is accessed twice, once
1637 // for read and once for write, it will only appear once (on the write
1638 // list). This is okay, since we are going to check for conflicts between
1639 // writes and between reads and writes, but not between reads and reads.
1642 ValueVector::iterator I, IE;
1643 for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
1644 StoreInst *ST = cast<StoreInst>(*I);
1645 Value* Ptr = ST->getPointerOperand();
1647 if (isUniform(Ptr)) {
1648 DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
1652 // If we did *not* see this pointer before, insert it to
1653 // the read-write list. At this phase it is only a 'write' list.
1654 if (Seen.insert(Ptr))
1655 ReadWrites.push_back(Ptr);
1658 for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
1659 LoadInst *LD = cast<LoadInst>(*I);
1660 Value* Ptr = LD->getPointerOperand();
1661 // If we did *not* see this pointer before, insert it to the
1662 // read list. If we *did* see it before, then it is already in
1663 // the read-write list. This allows us to vectorize expressions
1664 // such as A[i] += x; Because the address of A[i] is a read-write
1665 // pointer. This only works if the index of A[i] is consecutive.
1666 // If the address of i is unknown (for example A[B[i]]) then we may
1667 // read a few words, modify, and write a few words, and some of the
1668 // words may be written to the same address.
1669 if (Seen.insert(Ptr) || 0 == isConsecutivePtr(Ptr))
1670 Reads.push_back(Ptr);
1673 // If we write (or read-write) to a single destination and there are no
1674 // other reads in this loop then is it safe to vectorize.
1675 if (ReadWrites.size() == 1 && Reads.size() == 0) {
1676 DEBUG(dbgs() << "LV: Found a write-only loop!\n");
1680 // Find pointers with computable bounds. We are going to use this information
1681 // to place a runtime bound check.
1682 bool CanDoRT = true;
1683 for (I = ReadWrites.begin(), IE = ReadWrites.end(); I != IE; ++I)
1684 if (hasComputableBounds(*I)) {
1685 PtrRtCheck.insert(SE, TheLoop, *I);
1686 DEBUG(dbgs() << "LV: Found a runtime check ptr:" << **I <<"\n");
1691 for (I = Reads.begin(), IE = Reads.end(); I != IE; ++I)
1692 if (hasComputableBounds(*I)) {
1693 PtrRtCheck.insert(SE, TheLoop, *I);
1694 DEBUG(dbgs() << "LV: Found a runtime check ptr:" << **I <<"\n");
1700 // Check that we did not collect too many pointers or found a
1701 // unsizeable pointer.
1702 if (!CanDoRT || PtrRtCheck.Pointers.size() > RuntimeMemoryCheckThreshold) {
1708 DEBUG(dbgs() << "LV: We can perform a memory runtime check if needed.\n");
1711 bool NeedRTCheck = false;
1713 // Now that the pointers are in two lists (Reads and ReadWrites), we
1714 // can check that there are no conflicts between each of the writes and
1715 // between the writes to the reads.
1716 ValueSet WriteObjects;
1717 ValueVector TempObjects;
1719 // Check that the read-writes do not conflict with other read-write
1721 bool AllWritesIdentified = true;
1722 for (I = ReadWrites.begin(), IE = ReadWrites.end(); I != IE; ++I) {
1723 GetUnderlyingObjects(*I, TempObjects, DL);
1724 for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end();
1726 if (!isIdentifiedObject(*it)) {
1727 DEBUG(dbgs() << "LV: Found an unidentified write ptr:"<< **it <<"\n");
1729 AllWritesIdentified = false;
1731 if (!WriteObjects.insert(*it)) {
1732 DEBUG(dbgs() << "LV: Found a possible write-write reorder:"
1737 TempObjects.clear();
1740 /// Check that the reads don't conflict with the read-writes.
1741 for (I = Reads.begin(), IE = Reads.end(); I != IE; ++I) {
1742 GetUnderlyingObjects(*I, TempObjects, DL);
1743 for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end();
1745 // If all of the writes are identified then we don't care if the read
1746 // pointer is identified or not.
1747 if (!AllWritesIdentified && !isIdentifiedObject(*it)) {
1748 DEBUG(dbgs() << "LV: Found an unidentified read ptr:"<< **it <<"\n");
1751 if (WriteObjects.count(*it)) {
1752 DEBUG(dbgs() << "LV: Found a possible read/write reorder:"
1757 TempObjects.clear();
1760 PtrRtCheck.Need = NeedRTCheck;
1761 if (NeedRTCheck && !CanDoRT) {
1762 DEBUG(dbgs() << "LV: We can't vectorize because we can't find " <<
1763 "the array bounds.\n");
1768 DEBUG(dbgs() << "LV: We "<< (NeedRTCheck ? "" : "don't") <<
1769 " need a runtime memory check.\n");
1773 bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi,
1774 ReductionKind Kind) {
1775 if (Phi->getNumIncomingValues() != 2)
1778 // Reduction variables are only found in the loop header block.
1779 if (Phi->getParent() != TheLoop->getHeader())
1782 // Obtain the reduction start value from the value that comes from the loop
1784 Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
1786 // ExitInstruction is the single value which is used outside the loop.
1787 // We only allow for a single reduction value to be used outside the loop.
1788 // This includes users of the reduction, variables (which form a cycle
1789 // which ends in the phi node).
1790 Instruction *ExitInstruction = 0;
1792 // Iter is our iterator. We start with the PHI node and scan for all of the
1793 // users of this instruction. All users must be instructions that can be
1794 // used as reduction variables (such as ADD). We may have a single
1795 // out-of-block user. The cycle must end with the original PHI.
1796 Instruction *Iter = Phi;
1798 // If the instruction has no users then this is a broken
1799 // chain and can't be a reduction variable.
1800 if (Iter->use_empty())
1803 // Any reduction instr must be of one of the allowed kinds.
1804 if (!isReductionInstr(Iter, Kind))
1807 // Did we find a user inside this loop already ?
1808 bool FoundInBlockUser = false;
1809 // Did we reach the initial PHI node already ?
1810 bool FoundStartPHI = false;
1812 // For each of the *users* of iter.
1813 for (Value::use_iterator it = Iter->use_begin(), e = Iter->use_end();
1815 Instruction *U = cast<Instruction>(*it);
1816 // We already know that the PHI is a user.
1818 FoundStartPHI = true;
1822 // Check if we found the exit user.
1823 BasicBlock *Parent = U->getParent();
1824 if (!TheLoop->contains(Parent)) {
1825 // Exit if you find multiple outside users.
1826 if (ExitInstruction != 0)
1828 ExitInstruction = Iter;
1831 // We allow in-loop PHINodes which are not the original reduction PHI
1832 // node. If this PHI is the only user of Iter (happens in IF w/ no ELSE
1833 // structure) then don't skip this PHI.
1834 if (isa<PHINode>(Iter) && isa<PHINode>(U) &&
1835 U->getParent() != TheLoop->getHeader() &&
1836 TheLoop->contains(U) &&
1837 Iter->getNumUses() > 1)
1840 // We can't have multiple inside users.
1841 if (FoundInBlockUser)
1843 FoundInBlockUser = true;
1847 // We found a reduction var if we have reached the original
1848 // phi node and we only have a single instruction with out-of-loop
1850 if (FoundStartPHI && ExitInstruction) {
1851 // This instruction is allowed to have out-of-loop users.
1852 AllowedExit.insert(ExitInstruction);
1854 // Save the description of this reduction variable.
1855 ReductionDescriptor RD(RdxStart, ExitInstruction, Kind);
1856 Reductions[Phi] = RD;
1860 // If we've reached the start PHI but did not find an outside user then
1861 // this is dead code. Abort.
1868 LoopVectorizationLegality::isReductionInstr(Instruction *I,
1869 ReductionKind Kind) {
1870 switch (I->getOpcode()) {
1873 case Instruction::PHI:
1876 case Instruction::Add:
1877 case Instruction::Sub:
1878 return Kind == IntegerAdd;
1879 case Instruction::Mul:
1880 return Kind == IntegerMult;
1881 case Instruction::And:
1882 return Kind == IntegerAnd;
1883 case Instruction::Or:
1884 return Kind == IntegerOr;
1885 case Instruction::Xor:
1886 return Kind == IntegerXor;
1890 LoopVectorizationLegality::InductionKind
1891 LoopVectorizationLegality::isInductionVariable(PHINode *Phi) {
1892 Type *PhiTy = Phi->getType();
1893 // We only handle integer and pointer inductions variables.
1894 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
1897 // Check that the PHI is consecutive and starts at zero.
1898 const SCEV *PhiScev = SE->getSCEV(Phi);
1899 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
1901 DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
1904 const SCEV *Step = AR->getStepRecurrence(*SE);
1906 // Integer inductions need to have a stride of one.
1907 if (PhiTy->isIntegerTy()) {
1909 return IntInduction;
1910 if (Step->isAllOnesValue())
1911 return ReverseIntInduction;
1915 // Calculate the pointer stride and check if it is consecutive.
1916 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
1920 assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
1921 uint64_t Size = DL->getTypeAllocSize(PhiTy->getPointerElementType());
1922 if (C->getValue()->equalsInt(Size))
1923 return PtrInduction;
1928 bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
1929 Value *In0 = const_cast<Value*>(V);
1930 PHINode *PN = dyn_cast_or_null<PHINode>(In0);
1934 return Inductions.count(PN);
1937 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) {
1938 assert(TheLoop->contains(BB) && "Unknown block used");
1940 // Blocks that do not dominate the latch need predication.
1941 BasicBlock* Latch = TheLoop->getLoopLatch();
1942 return !DT->dominates(BB, Latch);
1945 bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB) {
1946 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1947 // We don't predicate loads/stores at the moment.
1948 if (it->mayReadFromMemory() || it->mayWriteToMemory() || it->mayThrow())
1951 // The instructions below can trap.
1952 switch (it->getOpcode()) {
1954 case Instruction::UDiv:
1955 case Instruction::SDiv:
1956 case Instruction::URem:
1957 case Instruction::SRem:
1965 bool LoopVectorizationLegality::hasComputableBounds(Value *Ptr) {
1966 const SCEV *PhiScev = SE->getSCEV(Ptr);
1967 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
1971 return AR->isAffine();
1975 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize,
1977 if (OptForSize && Legal->getRuntimePointerCheck()->Need) {
1978 DEBUG(dbgs() << "LV: Aborting. Runtime ptr check is required in Os.\n");
1982 // Find the trip count.
1983 unsigned TC = SE->getSmallConstantTripCount(TheLoop, TheLoop->getLoopLatch());
1984 DEBUG(dbgs() << "LV: Found trip count:"<<TC<<"\n");
1986 unsigned VF = MaxVectorSize;
1988 // If we optimize the program for size, avoid creating the tail loop.
1990 // If we are unable to calculate the trip count then don't try to vectorize.
1992 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
1996 // Find the maximum SIMD width that can fit within the trip count.
1997 VF = TC % MaxVectorSize;
2002 // If the trip count that we found modulo the vectorization factor is not
2003 // zero then we require a tail.
2005 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
2011 assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
2012 DEBUG(dbgs() << "LV: Using user VF "<<UserVF<<".\n");
2018 DEBUG(dbgs() << "LV: No vector target information. Not vectorizing. \n");
2022 float Cost = expectedCost(1);
2024 DEBUG(dbgs() << "LV: Scalar loop costs: "<< (int)Cost << ".\n");
2025 for (unsigned i=2; i <= VF; i*=2) {
2026 // Notice that the vector loop needs to be executed less times, so
2027 // we need to divide the cost of the vector loops by the width of
2028 // the vector elements.
2029 float VectorCost = expectedCost(i) / (float)i;
2030 DEBUG(dbgs() << "LV: Vector loop of width "<< i << " costs: " <<
2031 (int)VectorCost << ".\n");
2032 if (VectorCost < Cost) {
2038 DEBUG(dbgs() << "LV: Selecting VF = : "<< Width << ".\n");
2042 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
2046 for (Loop::block_iterator bb = TheLoop->block_begin(),
2047 be = TheLoop->block_end(); bb != be; ++bb) {
2048 unsigned BlockCost = 0;
2049 BasicBlock *BB = *bb;
2051 // For each instruction in the old loop.
2052 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2053 unsigned C = getInstructionCost(it, VF);
2055 DEBUG(dbgs() << "LV: Found an estimated cost of "<< C <<" for VF " <<
2056 VF << " For instruction: "<< *it << "\n");
2059 // We assume that if-converted blocks have a 50% chance of being executed.
2060 // When the code is scalar then some of the blocks are avoided due to CF.
2061 // When the code is vectorized we execute all code paths.
2062 if (Legal->blockNeedsPredication(*bb) && VF == 1)
2072 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
2073 assert(VTTI && "Invalid vector target transformation info");
2075 // If we know that this instruction will remain uniform, check the cost of
2076 // the scalar version.
2077 if (Legal->isUniformAfterVectorization(I))
2080 Type *RetTy = I->getType();
2081 Type *VectorTy = ToVectorTy(RetTy, VF);
2083 // TODO: We need to estimate the cost of intrinsic calls.
2084 switch (I->getOpcode()) {
2085 case Instruction::GetElementPtr:
2086 // We mark this instruction as zero-cost because scalar GEPs are usually
2087 // lowered to the intruction addressing mode. At the moment we don't
2088 // generate vector geps.
2090 case Instruction::Br: {
2091 return VTTI->getCFInstrCost(I->getOpcode());
2093 case Instruction::PHI:
2094 //TODO: IF-converted IFs become selects.
2096 case Instruction::Add:
2097 case Instruction::FAdd:
2098 case Instruction::Sub:
2099 case Instruction::FSub:
2100 case Instruction::Mul:
2101 case Instruction::FMul:
2102 case Instruction::UDiv:
2103 case Instruction::SDiv:
2104 case Instruction::FDiv:
2105 case Instruction::URem:
2106 case Instruction::SRem:
2107 case Instruction::FRem:
2108 case Instruction::Shl:
2109 case Instruction::LShr:
2110 case Instruction::AShr:
2111 case Instruction::And:
2112 case Instruction::Or:
2113 case Instruction::Xor:
2114 return VTTI->getArithmeticInstrCost(I->getOpcode(), VectorTy);
2115 case Instruction::Select: {
2116 SelectInst *SI = cast<SelectInst>(I);
2117 const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
2118 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
2119 Type *CondTy = SI->getCondition()->getType();
2121 CondTy = VectorType::get(CondTy, VF);
2123 return VTTI->getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
2125 case Instruction::ICmp:
2126 case Instruction::FCmp: {
2127 Type *ValTy = I->getOperand(0)->getType();
2128 VectorTy = ToVectorTy(ValTy, VF);
2129 return VTTI->getCmpSelInstrCost(I->getOpcode(), VectorTy);
2131 case Instruction::Store: {
2132 StoreInst *SI = cast<StoreInst>(I);
2133 Type *ValTy = SI->getValueOperand()->getType();
2134 VectorTy = ToVectorTy(ValTy, VF);
2137 return VTTI->getMemoryOpCost(I->getOpcode(), VectorTy,
2139 SI->getPointerAddressSpace());
2141 // Scalarized stores.
2142 int Stride = Legal->isConsecutivePtr(SI->getPointerOperand());
2143 bool Reverse = Stride < 0;
2147 // The cost of extracting from the value vector and pointer vector.
2148 Type *PtrTy = ToVectorTy(I->getOperand(0)->getType(), VF);
2149 for (unsigned i = 0; i < VF; ++i) {
2150 Cost += VTTI->getVectorInstrCost(Instruction::ExtractElement,
2152 Cost += VTTI->getVectorInstrCost(Instruction::ExtractElement,
2156 // The cost of the scalar stores.
2157 Cost += VF * VTTI->getMemoryOpCost(I->getOpcode(),
2158 ValTy->getScalarType(),
2160 SI->getPointerAddressSpace());
2165 unsigned Cost = VTTI->getMemoryOpCost(I->getOpcode(), VectorTy,
2167 SI->getPointerAddressSpace());
2169 Cost += VTTI->getShuffleCost(VectorTargetTransformInfo::Reverse,
2173 case Instruction::Load: {
2174 LoadInst *LI = cast<LoadInst>(I);
2177 return VTTI->getMemoryOpCost(I->getOpcode(), VectorTy,
2179 LI->getPointerAddressSpace());
2181 // Scalarized loads.
2182 int Stride = Legal->isConsecutivePtr(LI->getPointerOperand());
2183 bool Reverse = Stride < 0;
2186 Type *PtrTy = ToVectorTy(I->getOperand(0)->getType(), VF);
2188 // The cost of extracting from the pointer vector.
2189 for (unsigned i = 0; i < VF; ++i)
2190 Cost += VTTI->getVectorInstrCost(Instruction::ExtractElement,
2193 // The cost of inserting data to the result vector.
2194 for (unsigned i = 0; i < VF; ++i)
2195 Cost += VTTI->getVectorInstrCost(Instruction::InsertElement,
2198 // The cost of the scalar stores.
2199 Cost += VF * VTTI->getMemoryOpCost(I->getOpcode(),
2200 RetTy->getScalarType(),
2202 LI->getPointerAddressSpace());
2207 unsigned Cost = VTTI->getMemoryOpCost(I->getOpcode(), VectorTy,
2209 LI->getPointerAddressSpace());
2211 Cost += VTTI->getShuffleCost(VectorTargetTransformInfo::Reverse,
2215 case Instruction::ZExt:
2216 case Instruction::SExt:
2217 case Instruction::FPToUI:
2218 case Instruction::FPToSI:
2219 case Instruction::FPExt:
2220 case Instruction::PtrToInt:
2221 case Instruction::IntToPtr:
2222 case Instruction::SIToFP:
2223 case Instruction::UIToFP:
2224 case Instruction::Trunc:
2225 case Instruction::FPTrunc:
2226 case Instruction::BitCast: {
2227 // We optimize the truncation of induction variable.
2228 // The cost of these is the same as the scalar operation.
2229 if (I->getOpcode() == Instruction::Trunc &&
2230 Legal->isInductionVariable(I->getOperand(0)))
2231 return VTTI->getCastInstrCost(I->getOpcode(), I->getType(),
2232 I->getOperand(0)->getType());
2234 Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
2235 return VTTI->getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
2237 case Instruction::Call: {
2238 assert(isTriviallyVectorizableIntrinsic(I));
2239 IntrinsicInst *II = cast<IntrinsicInst>(I);
2240 Type *RetTy = ToVectorTy(II->getType(), VF);
2241 SmallVector<Type*, 4> Tys;
2242 for (unsigned i = 0, ie = II->getNumArgOperands(); i != ie; ++i)
2243 Tys.push_back(ToVectorTy(II->getArgOperand(i)->getType(), VF));
2244 return VTTI->getIntrinsicInstrCost(II->getIntrinsicID(), RetTy, Tys);
2247 // We are scalarizing the instruction. Return the cost of the scalar
2248 // instruction, plus the cost of insert and extract into vector
2249 // elements, times the vector width.
2252 if (!RetTy->isVoidTy() && VF != 1) {
2253 unsigned InsCost = VTTI->getVectorInstrCost(Instruction::InsertElement,
2255 unsigned ExtCost = VTTI->getVectorInstrCost(Instruction::ExtractElement,
2258 // The cost of inserting the results plus extracting each one of the
2260 Cost += VF * (InsCost + ExtCost * I->getNumOperands());
2263 // The cost of executing VF copies of the scalar instruction. This opcode
2264 // is unknown. Assume that it is the same as 'mul'.
2265 Cost += VF * VTTI->getArithmeticInstrCost(Instruction::Mul, VectorTy);
2271 Type* LoopVectorizationCostModel::ToVectorTy(Type *Scalar, unsigned VF) {
2272 if (Scalar->isVoidTy() || VF == 1)
2274 return VectorType::get(Scalar, VF);
2277 char LoopVectorize::ID = 0;
2278 static const char lv_name[] = "Loop Vectorization";
2279 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
2280 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
2281 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
2282 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
2283 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
2286 Pass *createLoopVectorizePass() {
2287 return new LoopVectorize();