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/ScalarEvolutionExpander.h"
19 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
20 #include "llvm/Analysis/ValueTracking.h"
21 #include "llvm/Analysis/Verifier.h"
22 #include "llvm/Constants.h"
23 #include "llvm/DataLayout.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/Function.h"
26 #include "llvm/Instructions.h"
27 #include "llvm/IntrinsicInst.h"
28 #include "llvm/LLVMContext.h"
29 #include "llvm/Module.h"
30 #include "llvm/Pass.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/TargetTransformInfo.h"
35 #include "llvm/Transforms/Scalar.h"
36 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
37 #include "llvm/Transforms/Utils/Local.h"
38 #include "llvm/Transforms/Vectorize.h"
39 #include "llvm/Type.h"
40 #include "llvm/Value.h"
42 static cl::opt<unsigned>
43 VectorizationFactor("force-vector-width", cl::init(0), cl::Hidden,
44 cl::desc("Sets the SIMD width. Zero is autoselect."));
47 EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
48 cl::desc("Enable if-conversion during vectorization."));
52 /// The LoopVectorize Pass.
53 struct LoopVectorize : public LoopPass {
54 /// Pass identification, replacement for typeid
56 /// Optimize for size. Do not generate tail loops.
59 explicit LoopVectorize(bool OptSz = false) : LoopPass(ID), OptForSize(OptSz) {
60 initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
66 TargetTransformInfo *TTI;
69 virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
70 // We only vectorize innermost loops.
74 SE = &getAnalysis<ScalarEvolution>();
75 DL = getAnalysisIfAvailable<DataLayout>();
76 LI = &getAnalysis<LoopInfo>();
77 TTI = getAnalysisIfAvailable<TargetTransformInfo>();
78 DT = &getAnalysis<DominatorTree>();
80 DEBUG(dbgs() << "LV: Checking a loop in \"" <<
81 L->getHeader()->getParent()->getName() << "\"\n");
83 // Check if it is legal to vectorize the loop.
84 LoopVectorizationLegality LVL(L, SE, DL, DT);
85 if (!LVL.canVectorize()) {
86 DEBUG(dbgs() << "LV: Not vectorizing.\n");
90 // Select the preffered vectorization factor.
91 const VectorTargetTransformInfo *VTTI = 0;
93 VTTI = TTI->getVectorTargetTransformInfo();
94 // Use the cost model.
95 LoopVectorizationCostModel CM(L, SE, &LVL, VTTI);
96 unsigned VF = CM.selectVectorizationFactor(OptForSize,
100 DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
104 DEBUG(dbgs() << "LV: Found a vectorizable loop ("<< VF << ") in "<<
105 L->getHeader()->getParent()->getParent()->getModuleIdentifier()<<
108 // If we decided that it is *legal* to vectorizer the loop then do it.
109 InnerLoopVectorizer LB(L, SE, LI, DT, DL, VF);
112 DEBUG(verifyFunction(*L->getHeader()->getParent()));
116 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
117 LoopPass::getAnalysisUsage(AU);
118 AU.addRequiredID(LoopSimplifyID);
119 AU.addRequiredID(LCSSAID);
120 AU.addRequired<LoopInfo>();
121 AU.addRequired<ScalarEvolution>();
122 AU.addRequired<DominatorTree>();
123 AU.addPreserved<LoopInfo>();
124 AU.addPreserved<DominatorTree>();
131 //===----------------------------------------------------------------------===//
132 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
133 // LoopVectorizationCostModel.
134 //===----------------------------------------------------------------------===//
137 LoopVectorizationLegality::RuntimePointerCheck::insert(ScalarEvolution *SE,
138 Loop *Lp, Value *Ptr) {
139 const SCEV *Sc = SE->getSCEV(Ptr);
140 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
141 assert(AR && "Invalid addrec expression");
142 const SCEV *Ex = SE->getExitCount(Lp, Lp->getLoopLatch());
143 const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
144 Pointers.push_back(Ptr);
145 Starts.push_back(AR->getStart());
146 Ends.push_back(ScEnd);
149 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
151 LLVMContext &C = V->getContext();
152 Type *VTy = VectorType::get(V->getType(), VF);
153 Type *I32 = IntegerType::getInt32Ty(C);
155 // Save the current insertion location.
156 Instruction *Loc = Builder.GetInsertPoint();
158 // We need to place the broadcast of invariant variables outside the loop.
159 Instruction *Instr = dyn_cast<Instruction>(V);
160 bool NewInstr = (Instr && Instr->getParent() == LoopVectorBody);
161 bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
163 // Place the code for broadcasting invariant variables in the new preheader.
165 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
167 Constant *Zero = ConstantInt::get(I32, 0);
168 Value *Zeros = ConstantAggregateZero::get(VectorType::get(I32, VF));
169 Value *UndefVal = UndefValue::get(VTy);
170 // Insert the value into a new vector.
171 Value *SingleElem = Builder.CreateInsertElement(UndefVal, V, Zero);
172 // Broadcast the scalar into all locations in the vector.
173 Value *Shuf = Builder.CreateShuffleVector(SingleElem, UndefVal, Zeros,
176 // Restore the builder insertion point.
178 Builder.SetInsertPoint(Loc);
183 Value *InnerLoopVectorizer::getConsecutiveVector(Value* Val, bool Negate) {
184 assert(Val->getType()->isVectorTy() && "Must be a vector");
185 assert(Val->getType()->getScalarType()->isIntegerTy() &&
186 "Elem must be an integer");
188 Type *ITy = Val->getType()->getScalarType();
189 VectorType *Ty = cast<VectorType>(Val->getType());
190 int VLen = Ty->getNumElements();
191 SmallVector<Constant*, 8> Indices;
193 // Create a vector of consecutive numbers from zero to VF.
194 for (int i = 0; i < VLen; ++i)
195 Indices.push_back(ConstantInt::get(ITy, Negate ? (-i): i ));
197 // Add the consecutive indices to the vector value.
198 Constant *Cv = ConstantVector::get(Indices);
199 assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
200 return Builder.CreateAdd(Val, Cv, "induction");
203 bool LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
204 assert(Ptr->getType()->isPointerTy() && "Unexpected non ptr");
206 // If this value is a pointer induction variable we know it is consecutive.
207 PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
208 if (Phi && Inductions.count(Phi)) {
209 InductionInfo II = Inductions[Phi];
210 if (PtrInduction == II.IK)
214 GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
218 unsigned NumOperands = Gep->getNumOperands();
219 Value *LastIndex = Gep->getOperand(NumOperands - 1);
221 // Check that all of the gep indices are uniform except for the last.
222 for (unsigned i = 0; i < NumOperands - 1; ++i)
223 if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
226 // We can emit wide load/stores only if the last index is the induction
228 const SCEV *Last = SE->getSCEV(LastIndex);
229 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
230 const SCEV *Step = AR->getStepRecurrence(*SE);
232 // The memory is consecutive because the last index is consecutive
233 // and all other indices are loop invariant.
241 bool LoopVectorizationLegality::isUniform(Value *V) {
242 return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
245 Value *InnerLoopVectorizer::getVectorValue(Value *V) {
246 assert(V != Induction && "The new induction variable should not be used.");
247 assert(!V->getType()->isVectorTy() && "Can't widen a vector");
248 // If we saved a vectorized copy of V, use it.
249 Value *&MapEntry = WidenMap[V];
253 // Broadcast V and save the value for future uses.
254 Value *B = getBroadcastInstrs(V);
260 InnerLoopVectorizer::getUniformVector(unsigned Val, Type* ScalarTy) {
261 return ConstantVector::getSplat(VF, ConstantInt::get(ScalarTy, Val, true));
264 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr) {
265 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
266 // Holds vector parameters or scalars, in case of uniform vals.
267 SmallVector<Value*, 8> Params;
269 // Find all of the vectorized parameters.
270 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
271 Value *SrcOp = Instr->getOperand(op);
273 // If we are accessing the old induction variable, use the new one.
274 if (SrcOp == OldInduction) {
275 Params.push_back(getVectorValue(SrcOp));
279 // Try using previously calculated values.
280 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
282 // If the src is an instruction that appeared earlier in the basic block
283 // then it should already be vectorized.
284 if (SrcInst && SrcInst->getParent() == Instr->getParent()) {
285 assert(WidenMap.count(SrcInst) && "Source operand is unavailable");
286 // The parameter is a vector value from earlier.
287 Params.push_back(WidenMap[SrcInst]);
289 // The parameter is a scalar from outside the loop. Maybe even a constant.
290 Params.push_back(SrcOp);
294 assert(Params.size() == Instr->getNumOperands() &&
295 "Invalid number of operands");
297 // Does this instruction return a value ?
298 bool IsVoidRetTy = Instr->getType()->isVoidTy();
299 Value *VecResults = 0;
301 // If we have a return value, create an empty vector. We place the scalarized
302 // instructions in this vector.
304 VecResults = UndefValue::get(VectorType::get(Instr->getType(), VF));
306 // For each scalar that we create:
307 for (unsigned i = 0; i < VF; ++i) {
308 Instruction *Cloned = Instr->clone();
310 Cloned->setName(Instr->getName() + ".cloned");
311 // Replace the operands of the cloned instrucions with extracted scalars.
312 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
313 Value *Op = Params[op];
314 // Param is a vector. Need to extract the right lane.
315 if (Op->getType()->isVectorTy())
316 Op = Builder.CreateExtractElement(Op, Builder.getInt32(i));
317 Cloned->setOperand(op, Op);
320 // Place the cloned scalar in the new loop.
321 Builder.Insert(Cloned);
323 // If the original scalar returns a value we need to place it in a vector
324 // so that future users will be able to use it.
326 VecResults = Builder.CreateInsertElement(VecResults, Cloned,
327 Builder.getInt32(i));
331 WidenMap[Instr] = VecResults;
335 InnerLoopVectorizer::addRuntimeCheck(LoopVectorizationLegality *Legal,
337 LoopVectorizationLegality::RuntimePointerCheck *PtrRtCheck =
338 Legal->getRuntimePointerCheck();
340 if (!PtrRtCheck->Need)
343 Value *MemoryRuntimeCheck = 0;
344 unsigned NumPointers = PtrRtCheck->Pointers.size();
345 SmallVector<Value* , 2> Starts;
346 SmallVector<Value* , 2> Ends;
348 SCEVExpander Exp(*SE, "induction");
350 // Use this type for pointer arithmetic.
351 Type* PtrArithTy = Type::getInt8PtrTy(Loc->getContext(), 0);
353 for (unsigned i = 0; i < NumPointers; ++i) {
354 Value *Ptr = PtrRtCheck->Pointers[i];
355 const SCEV *Sc = SE->getSCEV(Ptr);
357 if (SE->isLoopInvariant(Sc, OrigLoop)) {
358 DEBUG(dbgs() << "LV: Adding RT check for a loop invariant ptr:" <<
360 Starts.push_back(Ptr);
363 DEBUG(dbgs() << "LV: Adding RT check for range:" << *Ptr <<"\n");
365 Value *Start = Exp.expandCodeFor(PtrRtCheck->Starts[i], PtrArithTy, Loc);
366 Value *End = Exp.expandCodeFor(PtrRtCheck->Ends[i], PtrArithTy, Loc);
367 Starts.push_back(Start);
372 for (unsigned i = 0; i < NumPointers; ++i) {
373 for (unsigned j = i+1; j < NumPointers; ++j) {
374 Instruction::CastOps Op = Instruction::BitCast;
375 Value *Start0 = CastInst::Create(Op, Starts[i], PtrArithTy, "bc", Loc);
376 Value *Start1 = CastInst::Create(Op, Starts[j], PtrArithTy, "bc", Loc);
377 Value *End0 = CastInst::Create(Op, Ends[i], PtrArithTy, "bc", Loc);
378 Value *End1 = CastInst::Create(Op, Ends[j], PtrArithTy, "bc", Loc);
380 Value *Cmp0 = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_ULE,
381 Start0, End1, "bound0", Loc);
382 Value *Cmp1 = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_ULE,
383 Start1, End0, "bound1", Loc);
384 Value *IsConflict = BinaryOperator::Create(Instruction::And, Cmp0, Cmp1,
385 "found.conflict", Loc);
386 if (MemoryRuntimeCheck)
387 MemoryRuntimeCheck = BinaryOperator::Create(Instruction::Or,
390 "conflict.rdx", Loc);
392 MemoryRuntimeCheck = IsConflict;
397 return MemoryRuntimeCheck;
401 InnerLoopVectorizer::createEmptyLoop(LoopVectorizationLegality *Legal) {
403 In this function we generate a new loop. The new loop will contain
404 the vectorized instructions while the old loop will continue to run the
407 [ ] <-- vector loop bypass.
410 | [ ] <-- vector pre header.
414 | [ ]_| <-- vector loop.
417 >[ ] <--- middle-block.
420 | [ ] <--- new preheader.
424 | [ ]_| <-- old scalar loop to handle remainder.
431 BasicBlock *OldBasicBlock = OrigLoop->getHeader();
432 BasicBlock *BypassBlock = OrigLoop->getLoopPreheader();
433 BasicBlock *ExitBlock = OrigLoop->getExitBlock();
434 assert(ExitBlock && "Must have an exit block");
436 // Some loops have a single integer induction variable, while other loops
437 // don't. One example is c++ iterators that often have multiple pointer
438 // induction variables. In the code below we also support a case where we
439 // don't have a single induction variable.
440 OldInduction = Legal->getInduction();
441 Type *IdxTy = OldInduction ? OldInduction->getType() :
442 DL->getIntPtrType(SE->getContext());
444 // Find the loop boundaries.
445 const SCEV *ExitCount = SE->getExitCount(OrigLoop, OrigLoop->getLoopLatch());
446 assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
448 // Get the total trip count from the count by adding 1.
449 ExitCount = SE->getAddExpr(ExitCount,
450 SE->getConstant(ExitCount->getType(), 1));
452 // Expand the trip count and place the new instructions in the preheader.
453 // Notice that the pre-header does not change, only the loop body.
454 SCEVExpander Exp(*SE, "induction");
456 // Count holds the overall loop count (N).
457 Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
458 BypassBlock->getTerminator());
460 // The loop index does not have to start at Zero. Find the original start
461 // value from the induction PHI node. If we don't have an induction variable
462 // then we know that it starts at zero.
463 Value *StartIdx = OldInduction ?
464 OldInduction->getIncomingValueForBlock(BypassBlock):
465 ConstantInt::get(IdxTy, 0);
467 assert(BypassBlock && "Invalid loop structure");
469 // Generate the code that checks in runtime if arrays overlap.
470 Value *MemoryRuntimeCheck = addRuntimeCheck(Legal,
471 BypassBlock->getTerminator());
473 // Split the single block loop into the two loop structure described above.
474 BasicBlock *VectorPH =
475 BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
476 BasicBlock *VecBody =
477 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
478 BasicBlock *MiddleBlock =
479 VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
480 BasicBlock *ScalarPH =
481 MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
483 // This is the location in which we add all of the logic for bypassing
484 // the new vector loop.
485 Instruction *Loc = BypassBlock->getTerminator();
487 // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
489 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
491 // Generate the induction variable.
492 Induction = Builder.CreatePHI(IdxTy, 2, "index");
493 Constant *Step = ConstantInt::get(IdxTy, VF);
495 // We may need to extend the index in case there is a type mismatch.
496 // We know that the count starts at zero and does not overflow.
497 if (Count->getType() != IdxTy) {
498 // The exit count can be of pointer type. Convert it to the correct
500 if (ExitCount->getType()->isPointerTy())
501 Count = CastInst::CreatePointerCast(Count, IdxTy, "ptrcnt.to.int", Loc);
503 Count = CastInst::CreateZExtOrBitCast(Count, IdxTy, "zext.cnt", Loc);
506 // Add the start index to the loop count to get the new end index.
507 Value *IdxEnd = BinaryOperator::CreateAdd(Count, StartIdx, "end.idx", Loc);
509 // Now we need to generate the expression for N - (N % VF), which is
510 // the part that the vectorized body will execute.
511 Constant *CIVF = ConstantInt::get(IdxTy, VF);
512 Value *R = BinaryOperator::CreateURem(Count, CIVF, "n.mod.vf", Loc);
513 Value *CountRoundDown = BinaryOperator::CreateSub(Count, R, "n.vec", Loc);
514 Value *IdxEndRoundDown = BinaryOperator::CreateAdd(CountRoundDown, StartIdx,
515 "end.idx.rnd.down", Loc);
517 // Now, compare the new count to zero. If it is zero skip the vector loop and
518 // jump to the scalar loop.
519 Value *Cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
524 // If we are using memory runtime checks, include them in.
525 if (MemoryRuntimeCheck)
526 Cmp = BinaryOperator::Create(Instruction::Or, Cmp, MemoryRuntimeCheck,
529 BranchInst::Create(MiddleBlock, VectorPH, Cmp, Loc);
530 // Remove the old terminator.
531 Loc->eraseFromParent();
533 // We are going to resume the execution of the scalar loop.
534 // Go over all of the induction variables that we found and fix the
535 // PHIs that are left in the scalar version of the loop.
536 // The starting values of PHI nodes depend on the counter of the last
537 // iteration in the vectorized loop.
538 // If we come from a bypass edge then we need to start from the original
541 // This variable saves the new starting index for the scalar loop.
542 PHINode *ResumeIndex = 0;
543 LoopVectorizationLegality::InductionList::iterator I, E;
544 LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
545 for (I = List->begin(), E = List->end(); I != E; ++I) {
546 PHINode *OrigPhi = I->first;
547 LoopVectorizationLegality::InductionInfo II = I->second;
548 PHINode *ResumeVal = PHINode::Create(OrigPhi->getType(), 2, "resume.val",
549 MiddleBlock->getTerminator());
552 case LoopVectorizationLegality::NoInduction:
553 llvm_unreachable("Unknown induction");
554 case LoopVectorizationLegality::IntInduction: {
555 // Handle the integer induction counter:
556 assert(OrigPhi->getType()->isIntegerTy() && "Invalid type");
557 assert(OrigPhi == OldInduction && "Unknown integer PHI");
558 // We know what the end value is.
559 EndValue = IdxEndRoundDown;
560 // We also know which PHI node holds it.
561 ResumeIndex = ResumeVal;
564 case LoopVectorizationLegality::ReverseIntInduction: {
565 // Convert the CountRoundDown variable to the PHI size.
566 unsigned CRDSize = CountRoundDown->getType()->getScalarSizeInBits();
567 unsigned IISize = II.StartValue->getType()->getScalarSizeInBits();
568 Value *CRD = CountRoundDown;
569 if (CRDSize > IISize)
570 CRD = CastInst::Create(Instruction::Trunc, CountRoundDown,
571 II.StartValue->getType(),
572 "tr.crd", BypassBlock->getTerminator());
573 else if (CRDSize < IISize)
574 CRD = CastInst::Create(Instruction::SExt, CountRoundDown,
575 II.StartValue->getType(),
576 "sext.crd", BypassBlock->getTerminator());
577 // Handle reverse integer induction counter:
578 EndValue = BinaryOperator::CreateSub(II.StartValue, CRD, "rev.ind.end",
579 BypassBlock->getTerminator());
582 case LoopVectorizationLegality::PtrInduction: {
583 // For pointer induction variables, calculate the offset using
585 EndValue = GetElementPtrInst::Create(II.StartValue, CountRoundDown,
587 BypassBlock->getTerminator());
592 // The new PHI merges the original incoming value, in case of a bypass,
593 // or the value at the end of the vectorized loop.
594 ResumeVal->addIncoming(II.StartValue, BypassBlock);
595 ResumeVal->addIncoming(EndValue, VecBody);
597 // Fix the scalar body counter (PHI node).
598 unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
599 OrigPhi->setIncomingValue(BlockIdx, ResumeVal);
602 // If we are generating a new induction variable then we also need to
603 // generate the code that calculates the exit value. This value is not
604 // simply the end of the counter because we may skip the vectorized body
605 // in case of a runtime check.
607 assert(!ResumeIndex && "Unexpected resume value found");
608 ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val",
609 MiddleBlock->getTerminator());
610 ResumeIndex->addIncoming(StartIdx, BypassBlock);
611 ResumeIndex->addIncoming(IdxEndRoundDown, VecBody);
614 // Make sure that we found the index where scalar loop needs to continue.
615 assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() &&
616 "Invalid resume Index");
618 // Add a check in the middle block to see if we have completed
619 // all of the iterations in the first vector loop.
620 // If (N - N%VF) == N, then we *don't* need to run the remainder.
621 Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd,
622 ResumeIndex, "cmp.n",
623 MiddleBlock->getTerminator());
625 BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
626 // Remove the old terminator.
627 MiddleBlock->getTerminator()->eraseFromParent();
629 // Create i+1 and fill the PHINode.
630 Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
631 Induction->addIncoming(StartIdx, VectorPH);
632 Induction->addIncoming(NextIdx, VecBody);
633 // Create the compare.
634 Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown);
635 Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
637 // Now we have two terminators. Remove the old one from the block.
638 VecBody->getTerminator()->eraseFromParent();
640 // Get ready to start creating new instructions into the vectorized body.
641 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
643 // Create and register the new vector loop.
644 Loop* Lp = new Loop();
645 Loop *ParentLoop = OrigLoop->getParentLoop();
647 // Insert the new loop into the loop nest and register the new basic blocks.
649 ParentLoop->addChildLoop(Lp);
650 ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase());
651 ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase());
652 ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase());
654 LI->addTopLevelLoop(Lp);
657 Lp->addBasicBlockToLoop(VecBody, LI->getBase());
660 LoopVectorPreHeader = VectorPH;
661 LoopScalarPreHeader = ScalarPH;
662 LoopMiddleBlock = MiddleBlock;
663 LoopExitBlock = ExitBlock;
664 LoopVectorBody = VecBody;
665 LoopScalarBody = OldBasicBlock;
666 LoopBypassBlock = BypassBlock;
669 /// This function returns the identity element (or neutral element) for
672 getReductionIdentity(LoopVectorizationLegality::ReductionKind K) {
674 case LoopVectorizationLegality::IntegerXor:
675 case LoopVectorizationLegality::IntegerAdd:
676 case LoopVectorizationLegality::IntegerOr:
677 // Adding, Xoring, Oring zero to a number does not change it.
679 case LoopVectorizationLegality::IntegerMult:
680 // Multiplying a number by 1 does not change it.
682 case LoopVectorizationLegality::IntegerAnd:
683 // AND-ing a number with an all-1 value does not change it.
686 llvm_unreachable("Unknown reduction kind");
691 isTriviallyVectorizableIntrinsic(Instruction *Inst) {
692 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst);
695 switch (II->getIntrinsicID()) {
696 case Intrinsic::sqrt:
700 case Intrinsic::exp2:
702 case Intrinsic::log10:
703 case Intrinsic::log2:
704 case Intrinsic::fabs:
705 case Intrinsic::floor:
706 case Intrinsic::ceil:
707 case Intrinsic::trunc:
708 case Intrinsic::rint:
709 case Intrinsic::nearbyint:
720 InnerLoopVectorizer::vectorizeLoop(LoopVectorizationLegality *Legal) {
721 //===------------------------------------------------===//
723 // Notice: any optimization or new instruction that go
724 // into the code below should be also be implemented in
727 //===------------------------------------------------===//
728 BasicBlock &BB = *OrigLoop->getHeader();
730 ConstantInt::get(IntegerType::getInt32Ty(BB.getContext()), 0);
732 // In order to support reduction variables we need to be able to vectorize
733 // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
734 // stages. First, we create a new vector PHI node with no incoming edges.
735 // We use this value when we vectorize all of the instructions that use the
736 // PHI. Next, after all of the instructions in the block are complete we
737 // add the new incoming edges to the PHI. At this point all of the
738 // instructions in the basic block are vectorized, so we can use them to
739 // construct the PHI.
740 PhiVector RdxPHIsToFix;
742 // Scan the loop in a topological order to ensure that defs are vectorized
744 LoopBlocksDFS DFS(OrigLoop);
747 // Vectorize all of the blocks in the original loop.
748 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
749 be = DFS.endRPO(); bb != be; ++bb)
750 vectorizeBlockInLoop(Legal, *bb, &RdxPHIsToFix);
752 // At this point every instruction in the original loop is widened to
753 // a vector form. We are almost done. Now, we need to fix the PHI nodes
754 // that we vectorized. The PHI nodes are currently empty because we did
755 // not want to introduce cycles. Notice that the remaining PHI nodes
756 // that we need to fix are reduction variables.
758 // Create the 'reduced' values for each of the induction vars.
759 // The reduced values are the vector values that we scalarize and combine
760 // after the loop is finished.
761 for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
763 PHINode *RdxPhi = *it;
764 PHINode *VecRdxPhi = dyn_cast<PHINode>(WidenMap[RdxPhi]);
765 assert(RdxPhi && "Unable to recover vectorized PHI");
767 // Find the reduction variable descriptor.
768 assert(Legal->getReductionVars()->count(RdxPhi) &&
769 "Unable to find the reduction variable");
770 LoopVectorizationLegality::ReductionDescriptor RdxDesc =
771 (*Legal->getReductionVars())[RdxPhi];
773 // We need to generate a reduction vector from the incoming scalar.
774 // To do so, we need to generate the 'identity' vector and overide
775 // one of the elements with the incoming scalar reduction. We need
776 // to do it in the vector-loop preheader.
777 Builder.SetInsertPoint(LoopBypassBlock->getTerminator());
779 // This is the vector-clone of the value that leaves the loop.
780 Value *VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
781 Type *VecTy = VectorExit->getType();
783 // Find the reduction identity variable. Zero for addition, or, xor,
784 // one for multiplication, -1 for And.
785 Constant *Identity = getUniformVector(getReductionIdentity(RdxDesc.Kind),
786 VecTy->getScalarType());
788 // This vector is the Identity vector where the first element is the
789 // incoming scalar reduction.
790 Value *VectorStart = Builder.CreateInsertElement(Identity,
791 RdxDesc.StartValue, Zero);
793 // Fix the vector-loop phi.
794 // We created the induction variable so we know that the
795 // preheader is the first entry.
796 BasicBlock *VecPreheader = Induction->getIncomingBlock(0);
798 // Reductions do not have to start at zero. They can start with
799 // any loop invariant values.
800 VecRdxPhi->addIncoming(VectorStart, VecPreheader);
802 getVectorValue(RdxPhi->getIncomingValueForBlock(OrigLoop->getLoopLatch()));
803 VecRdxPhi->addIncoming(Val, LoopVectorBody);
805 // Before each round, move the insertion point right between
806 // the PHIs and the values we are going to write.
807 // This allows us to write both PHINodes and the extractelement
809 Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
811 // This PHINode contains the vectorized reduction variable, or
812 // the initial value vector, if we bypass the vector loop.
813 PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
814 NewPhi->addIncoming(VectorStart, LoopBypassBlock);
815 NewPhi->addIncoming(getVectorValue(RdxDesc.LoopExitInstr), LoopVectorBody);
817 // Extract the first scalar.
819 Builder.CreateExtractElement(NewPhi, Builder.getInt32(0));
820 // Extract and reduce the remaining vector elements.
821 for (unsigned i=1; i < VF; ++i) {
823 Builder.CreateExtractElement(NewPhi, Builder.getInt32(i));
824 switch (RdxDesc.Kind) {
825 case LoopVectorizationLegality::IntegerAdd:
826 Scalar0 = Builder.CreateAdd(Scalar0, Scalar1, "add.rdx");
828 case LoopVectorizationLegality::IntegerMult:
829 Scalar0 = Builder.CreateMul(Scalar0, Scalar1, "mul.rdx");
831 case LoopVectorizationLegality::IntegerOr:
832 Scalar0 = Builder.CreateOr(Scalar0, Scalar1, "or.rdx");
834 case LoopVectorizationLegality::IntegerAnd:
835 Scalar0 = Builder.CreateAnd(Scalar0, Scalar1, "and.rdx");
837 case LoopVectorizationLegality::IntegerXor:
838 Scalar0 = Builder.CreateXor(Scalar0, Scalar1, "xor.rdx");
841 llvm_unreachable("Unknown reduction operation");
845 // Now, we need to fix the users of the reduction variable
846 // inside and outside of the scalar remainder loop.
847 // We know that the loop is in LCSSA form. We need to update the
848 // PHI nodes in the exit blocks.
849 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
850 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
851 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
852 if (!LCSSAPhi) continue;
854 // All PHINodes need to have a single entry edge, or two if
855 // we already fixed them.
856 assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
858 // We found our reduction value exit-PHI. Update it with the
859 // incoming bypass edge.
860 if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
861 // Add an edge coming from the bypass.
862 LCSSAPhi->addIncoming(Scalar0, LoopMiddleBlock);
865 }// end of the LCSSA phi scan.
867 // Fix the scalar loop reduction variable with the incoming reduction sum
868 // from the vector body and from the backedge value.
869 int IncomingEdgeBlockIdx =
870 (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
871 assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
872 // Pick the other block.
873 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
874 (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, Scalar0);
875 (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
876 }// end of for each redux variable.
879 Value *InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
880 assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
883 Value *SrcMask = createBlockInMask(Src);
885 // The terminator has to be a branch inst!
886 BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
887 assert(BI && "Unexpected terminator found");
889 Value *EdgeMask = SrcMask;
890 if (BI->isConditional()) {
891 EdgeMask = getVectorValue(BI->getCondition());
892 if (BI->getSuccessor(0) != Dst)
893 EdgeMask = Builder.CreateNot(EdgeMask);
896 return Builder.CreateAnd(EdgeMask, SrcMask);
899 Value *InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
900 assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
902 // Loop incoming mask is all-one.
903 if (OrigLoop->getHeader() == BB) {
904 Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
905 return getVectorValue(C);
908 // This is the block mask. We OR all incoming edges, and with zero.
909 Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
910 Value *BlockMask = getVectorValue(Zero);
913 for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it)
914 BlockMask = Builder.CreateOr(BlockMask, createEdgeMask(*it, BB));
920 InnerLoopVectorizer::vectorizeBlockInLoop(LoopVectorizationLegality *Legal,
921 BasicBlock *BB, PhiVector *PV) {
923 ConstantInt::get(IntegerType::getInt32Ty(BB->getContext()), 0);
925 // For each instruction in the old loop.
926 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
927 switch (it->getOpcode()) {
928 case Instruction::Br:
929 // Nothing to do for PHIs and BR, since we already took care of the
930 // loop control flow instructions.
932 case Instruction::PHI:{
933 PHINode* P = cast<PHINode>(it);
934 // Handle reduction variables:
935 if (Legal->getReductionVars()->count(P)) {
936 // This is phase one of vectorizing PHIs.
937 Type *VecTy = VectorType::get(it->getType(), VF);
939 PHINode::Create(VecTy, 2, "vec.phi",
940 LoopVectorBody->getFirstInsertionPt());
945 // Check for PHI nodes that are lowered to vector selects.
946 if (P->getParent() != OrigLoop->getHeader()) {
947 // We know that all PHIs in non header blocks are converted into
948 // selects, so we don't have to worry about the insertion order and we
949 // can just use the builder.
951 // At this point we generate the predication tree. There may be
952 // duplications since this is a simple recursive scan, but future
953 // optimizations will clean it up.
954 Value *Cond = createEdgeMask(P->getIncomingBlock(0), P->getParent());
956 Builder.CreateSelect(Cond,
957 getVectorValue(P->getIncomingValue(0)),
958 getVectorValue(P->getIncomingValue(1)),
963 // This PHINode must be an induction variable.
964 // Make sure that we know about it.
965 assert(Legal->getInductionVars()->count(P) &&
966 "Not an induction variable");
968 LoopVectorizationLegality::InductionInfo II =
969 Legal->getInductionVars()->lookup(P);
972 case LoopVectorizationLegality::NoInduction:
973 llvm_unreachable("Unknown induction");
974 case LoopVectorizationLegality::IntInduction: {
975 assert(P == OldInduction && "Unexpected PHI");
976 Value *Broadcasted = getBroadcastInstrs(Induction);
977 // After broadcasting the induction variable we need to make the
978 // vector consecutive by adding 0, 1, 2 ...
979 Value *ConsecutiveInduction = getConsecutiveVector(Broadcasted);
980 WidenMap[OldInduction] = ConsecutiveInduction;
983 case LoopVectorizationLegality::ReverseIntInduction:
984 case LoopVectorizationLegality::PtrInduction:
985 // Handle reverse integer and pointer inductions.
987 // If we have a single integer induction variable then use it.
988 // Otherwise, start counting at zero.
990 LoopVectorizationLegality::InductionInfo OldII =
991 Legal->getInductionVars()->lookup(OldInduction);
992 StartIdx = OldII.StartValue;
994 StartIdx = ConstantInt::get(Induction->getType(), 0);
996 // This is the normalized GEP that starts counting at zero.
997 Value *NormalizedIdx = Builder.CreateSub(Induction, StartIdx,
1000 // Handle the reverse integer induction variable case.
1001 if (LoopVectorizationLegality::ReverseIntInduction == II.IK) {
1002 IntegerType *DstTy = cast<IntegerType>(II.StartValue->getType());
1003 Value *CNI = Builder.CreateSExtOrTrunc(NormalizedIdx, DstTy,
1005 Value *ReverseInd = Builder.CreateSub(II.StartValue, CNI,
1008 // This is a new value so do not hoist it out.
1009 Value *Broadcasted = getBroadcastInstrs(ReverseInd);
1010 // After broadcasting the induction variable we need to make the
1011 // vector consecutive by adding ... -3, -2, -1, 0.
1012 Value *ConsecutiveInduction = getConsecutiveVector(Broadcasted,
1014 WidenMap[it] = ConsecutiveInduction;
1018 // Handle the pointer induction variable case.
1019 assert(P->getType()->isPointerTy() && "Unexpected type.");
1021 // This is the vector of results. Notice that we don't generate
1022 // vector geps because scalar geps result in better code.
1023 Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
1024 for (unsigned int i = 0; i < VF; ++i) {
1025 Constant *Idx = ConstantInt::get(Induction->getType(), i);
1026 Value *GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx,
1028 Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
1030 VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
1031 Builder.getInt32(i),
1035 WidenMap[it] = VecVal;
1041 case Instruction::Add:
1042 case Instruction::FAdd:
1043 case Instruction::Sub:
1044 case Instruction::FSub:
1045 case Instruction::Mul:
1046 case Instruction::FMul:
1047 case Instruction::UDiv:
1048 case Instruction::SDiv:
1049 case Instruction::FDiv:
1050 case Instruction::URem:
1051 case Instruction::SRem:
1052 case Instruction::FRem:
1053 case Instruction::Shl:
1054 case Instruction::LShr:
1055 case Instruction::AShr:
1056 case Instruction::And:
1057 case Instruction::Or:
1058 case Instruction::Xor: {
1059 // Just widen binops.
1060 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
1061 Value *A = getVectorValue(it->getOperand(0));
1062 Value *B = getVectorValue(it->getOperand(1));
1064 // Use this vector value for all users of the original instruction.
1065 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A, B);
1068 // Update the NSW, NUW and Exact flags.
1069 BinaryOperator *VecOp = cast<BinaryOperator>(V);
1070 if (isa<OverflowingBinaryOperator>(BinOp)) {
1071 VecOp->setHasNoSignedWrap(BinOp->hasNoSignedWrap());
1072 VecOp->setHasNoUnsignedWrap(BinOp->hasNoUnsignedWrap());
1074 if (isa<PossiblyExactOperator>(VecOp))
1075 VecOp->setIsExact(BinOp->isExact());
1078 case Instruction::Select: {
1080 // If the selector is loop invariant we can create a select
1081 // instruction with a scalar condition. Otherwise, use vector-select.
1082 Value *Cond = it->getOperand(0);
1083 bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(Cond), OrigLoop);
1085 // The condition can be loop invariant but still defined inside the
1086 // loop. This means that we can't just use the original 'cond' value.
1087 // We have to take the 'vectorized' value and pick the first lane.
1088 // Instcombine will make this a no-op.
1089 Cond = getVectorValue(Cond);
1091 Cond = Builder.CreateExtractElement(Cond, Builder.getInt32(0));
1093 Value *Op0 = getVectorValue(it->getOperand(1));
1094 Value *Op1 = getVectorValue(it->getOperand(2));
1095 WidenMap[it] = Builder.CreateSelect(Cond, Op0, Op1);
1099 case Instruction::ICmp:
1100 case Instruction::FCmp: {
1101 // Widen compares. Generate vector compares.
1102 bool FCmp = (it->getOpcode() == Instruction::FCmp);
1103 CmpInst *Cmp = dyn_cast<CmpInst>(it);
1104 Value *A = getVectorValue(it->getOperand(0));
1105 Value *B = getVectorValue(it->getOperand(1));
1107 WidenMap[it] = Builder.CreateFCmp(Cmp->getPredicate(), A, B);
1109 WidenMap[it] = Builder.CreateICmp(Cmp->getPredicate(), A, B);
1113 case Instruction::Store: {
1114 // Attempt to issue a wide store.
1115 StoreInst *SI = dyn_cast<StoreInst>(it);
1116 Type *StTy = VectorType::get(SI->getValueOperand()->getType(), VF);
1117 Value *Ptr = SI->getPointerOperand();
1118 unsigned Alignment = SI->getAlignment();
1120 assert(!Legal->isUniform(Ptr) &&
1121 "We do not allow storing to uniform addresses");
1123 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1125 // This store does not use GEPs.
1126 if (!Legal->isConsecutivePtr(Ptr)) {
1127 scalarizeInstruction(it);
1132 // The last index does not have to be the induction. It can be
1133 // consecutive and be a function of the index. For example A[I+1];
1134 unsigned NumOperands = Gep->getNumOperands();
1135 Value *LastIndex = getVectorValue(Gep->getOperand(NumOperands - 1));
1136 LastIndex = Builder.CreateExtractElement(LastIndex, Zero);
1138 // Create the new GEP with the new induction variable.
1139 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1140 Gep2->setOperand(NumOperands - 1, LastIndex);
1141 Ptr = Builder.Insert(Gep2);
1143 // Use the induction element ptr.
1144 assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1145 Ptr = Builder.CreateExtractElement(getVectorValue(Ptr), Zero);
1147 Ptr = Builder.CreateBitCast(Ptr, StTy->getPointerTo());
1148 Value *Val = getVectorValue(SI->getValueOperand());
1149 Builder.CreateStore(Val, Ptr)->setAlignment(Alignment);
1152 case Instruction::Load: {
1153 // Attempt to issue a wide load.
1154 LoadInst *LI = dyn_cast<LoadInst>(it);
1155 Type *RetTy = VectorType::get(LI->getType(), VF);
1156 Value *Ptr = LI->getPointerOperand();
1157 unsigned Alignment = LI->getAlignment();
1158 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1160 // If the pointer is loop invariant or if it is non consecutive,
1161 // scalarize the load.
1162 bool Con = Legal->isConsecutivePtr(Ptr);
1163 if (Legal->isUniform(Ptr) || !Con) {
1164 scalarizeInstruction(it);
1169 // The last index does not have to be the induction. It can be
1170 // consecutive and be a function of the index. For example A[I+1];
1171 unsigned NumOperands = Gep->getNumOperands();
1172 Value *LastIndex = getVectorValue(Gep->getOperand(NumOperands -1));
1173 LastIndex = Builder.CreateExtractElement(LastIndex, Zero);
1175 // Create the new GEP with the new induction variable.
1176 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1177 Gep2->setOperand(NumOperands - 1, LastIndex);
1178 Ptr = Builder.Insert(Gep2);
1180 // Use the induction element ptr.
1181 assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1182 Ptr = Builder.CreateExtractElement(getVectorValue(Ptr), Zero);
1185 Ptr = Builder.CreateBitCast(Ptr, RetTy->getPointerTo());
1186 LI = Builder.CreateLoad(Ptr);
1187 LI->setAlignment(Alignment);
1188 // Use this vector value for all users of the load.
1192 case Instruction::ZExt:
1193 case Instruction::SExt:
1194 case Instruction::FPToUI:
1195 case Instruction::FPToSI:
1196 case Instruction::FPExt:
1197 case Instruction::PtrToInt:
1198 case Instruction::IntToPtr:
1199 case Instruction::SIToFP:
1200 case Instruction::UIToFP:
1201 case Instruction::Trunc:
1202 case Instruction::FPTrunc:
1203 case Instruction::BitCast: {
1204 CastInst *CI = dyn_cast<CastInst>(it);
1205 /// Optimize the special case where the source is the induction
1206 /// variable. Notice that we can only optimize the 'trunc' case
1207 /// because: a. FP conversions lose precision, b. sext/zext may wrap,
1208 /// c. other casts depend on pointer size.
1209 if (CI->getOperand(0) == OldInduction &&
1210 it->getOpcode() == Instruction::Trunc) {
1211 Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
1213 Value *Broadcasted = getBroadcastInstrs(ScalarCast);
1214 WidenMap[it] = getConsecutiveVector(Broadcasted);
1217 /// Vectorize casts.
1218 Value *A = getVectorValue(it->getOperand(0));
1219 Type *DestTy = VectorType::get(CI->getType()->getScalarType(), VF);
1220 WidenMap[it] = Builder.CreateCast(CI->getOpcode(), A, DestTy);
1224 case Instruction::Call: {
1225 assert(isTriviallyVectorizableIntrinsic(it));
1226 Module *M = BB->getParent()->getParent();
1227 IntrinsicInst *II = cast<IntrinsicInst>(it);
1228 Intrinsic::ID ID = II->getIntrinsicID();
1229 SmallVector<Value*, 4> Args;
1230 for (unsigned i = 0, ie = II->getNumArgOperands(); i != ie; ++i)
1231 Args.push_back(getVectorValue(II->getArgOperand(i)));
1232 Type *Tys[] = { VectorType::get(II->getType()->getScalarType(), VF) };
1233 Function *F = Intrinsic::getDeclaration(M, ID, Tys);
1234 WidenMap[it] = Builder.CreateCall(F, Args);
1239 // All other instructions are unsupported. Scalarize them.
1240 scalarizeInstruction(it);
1243 }// end of for_each instr.
1246 void InnerLoopVectorizer::updateAnalysis() {
1247 // Forget the original basic block.
1248 SE->forgetLoop(OrigLoop);
1250 // Update the dominator tree information.
1251 assert(DT->properlyDominates(LoopBypassBlock, LoopExitBlock) &&
1252 "Entry does not dominate exit.");
1254 DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlock);
1255 DT->addNewBlock(LoopVectorBody, LoopVectorPreHeader);
1256 DT->addNewBlock(LoopMiddleBlock, LoopBypassBlock);
1257 DT->addNewBlock(LoopScalarPreHeader, LoopMiddleBlock);
1258 DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
1259 DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
1261 DEBUG(DT->verifyAnalysis());
1264 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
1265 if (!EnableIfConversion)
1268 assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
1269 std::vector<BasicBlock*> &LoopBlocks = TheLoop->getBlocksVector();
1271 // Collect the blocks that need predication.
1272 for (unsigned i = 0, e = LoopBlocks.size(); i < e; ++i) {
1273 BasicBlock *BB = LoopBlocks[i];
1275 // We don't support switch statements inside loops.
1276 if (!isa<BranchInst>(BB->getTerminator()))
1279 // We must have at most two predecessors because we need to convert
1280 // all PHIs to selects.
1281 unsigned Preds = std::distance(pred_begin(BB), pred_end(BB));
1285 // We must be able to predicate all blocks that need to be predicated.
1286 if (blockNeedsPredication(BB) && !blockCanBePredicated(BB))
1290 // We can if-convert this loop.
1294 bool LoopVectorizationLegality::canVectorize() {
1295 assert(TheLoop->getLoopPreheader() && "No preheader!!");
1297 // We can only vectorize innermost loops.
1298 if (TheLoop->getSubLoopsVector().size())
1301 // We must have a single backedge.
1302 if (TheLoop->getNumBackEdges() != 1)
1305 // We must have a single exiting block.
1306 if (!TheLoop->getExitingBlock())
1309 unsigned NumBlocks = TheLoop->getNumBlocks();
1311 // Check if we can if-convert non single-bb loops.
1312 if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
1313 DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
1317 // We need to have a loop header.
1318 BasicBlock *Latch = TheLoop->getLoopLatch();
1319 DEBUG(dbgs() << "LV: Found a loop: " <<
1320 TheLoop->getHeader()->getName() << "\n");
1322 // ScalarEvolution needs to be able to find the exit count.
1323 const SCEV *ExitCount = SE->getExitCount(TheLoop, Latch);
1324 if (ExitCount == SE->getCouldNotCompute()) {
1325 DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
1329 // Do not loop-vectorize loops with a tiny trip count.
1330 unsigned TC = SE->getSmallConstantTripCount(TheLoop, Latch);
1331 if (TC > 0u && TC < TinyTripCountThreshold) {
1332 DEBUG(dbgs() << "LV: Found a loop with a very small trip count. " <<
1333 "This loop is not worth vectorizing.\n");
1337 // Check if we can vectorize the instructions and CFG in this loop.
1338 if (!canVectorizeInstrs()) {
1339 DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
1343 // Go over each instruction and look at memory deps.
1344 if (!canVectorizeMemory()) {
1345 DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
1349 // Collect all of the variables that remain uniform after vectorization.
1350 collectLoopUniforms();
1352 DEBUG(dbgs() << "LV: We can vectorize this loop" <<
1353 (PtrRtCheck.Need ? " (with a runtime bound check)" : "")
1356 // Okay! We can vectorize. At this point we don't have any other mem analysis
1357 // which may limit our maximum vectorization factor, so just return true with
1362 bool LoopVectorizationLegality::canVectorizeInstrs() {
1363 BasicBlock *PreHeader = TheLoop->getLoopPreheader();
1364 BasicBlock *Header = TheLoop->getHeader();
1366 // For each block in the loop.
1367 for (Loop::block_iterator bb = TheLoop->block_begin(),
1368 be = TheLoop->block_end(); bb != be; ++bb) {
1370 // Scan the instructions in the block and look for hazards.
1371 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
1374 if (PHINode *Phi = dyn_cast<PHINode>(it)) {
1375 // This should not happen because the loop should be normalized.
1376 if (Phi->getNumIncomingValues() != 2) {
1377 DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
1381 // Check that this PHI type is allowed.
1382 if (!Phi->getType()->isIntegerTy() &&
1383 !Phi->getType()->isPointerTy()) {
1384 DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
1388 // If this PHINode is not in the header block, then we know that we
1389 // can convert it to select during if-conversion. No need to check if
1390 // the PHIs in this block are induction or reduction variables.
1394 // This is the value coming from the preheader.
1395 Value *StartValue = Phi->getIncomingValueForBlock(PreHeader);
1396 // Check if this is an induction variable.
1397 InductionKind IK = isInductionVariable(Phi);
1399 if (NoInduction != IK) {
1400 // Int inductions are special because we only allow one IV.
1401 if (IK == IntInduction) {
1403 DEBUG(dbgs() << "LV: Found too many inductions."<< *Phi <<"\n");
1409 DEBUG(dbgs() << "LV: Found an induction variable.\n");
1410 Inductions[Phi] = InductionInfo(StartValue, IK);
1414 if (AddReductionVar(Phi, IntegerAdd)) {
1415 DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
1418 if (AddReductionVar(Phi, IntegerMult)) {
1419 DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n");
1422 if (AddReductionVar(Phi, IntegerOr)) {
1423 DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n");
1426 if (AddReductionVar(Phi, IntegerAnd)) {
1427 DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n");
1430 if (AddReductionVar(Phi, IntegerXor)) {
1431 DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n");
1435 DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
1437 }// end of PHI handling
1439 // We still don't handle functions.
1440 CallInst *CI = dyn_cast<CallInst>(it);
1441 if (CI && !isTriviallyVectorizableIntrinsic(it)) {
1442 DEBUG(dbgs() << "LV: Found a call site.\n");
1446 // We do not re-vectorize vectors.
1447 if (!VectorType::isValidElementType(it->getType()) &&
1448 !it->getType()->isVoidTy()) {
1449 DEBUG(dbgs() << "LV: Found unvectorizable type." << "\n");
1453 // Reduction instructions are allowed to have exit users.
1454 // All other instructions must not have external users.
1455 if (!AllowedExit.count(it))
1456 //Check that all of the users of the loop are inside the BB.
1457 for (Value::use_iterator I = it->use_begin(), E = it->use_end();
1459 Instruction *U = cast<Instruction>(*I);
1460 // This user may be a reduction exit value.
1461 if (!TheLoop->contains(U)) {
1462 DEBUG(dbgs() << "LV: Found an outside user for : "<< *U << "\n");
1471 DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
1472 assert(getInductionVars()->size() && "No induction variables");
1478 void LoopVectorizationLegality::collectLoopUniforms() {
1479 // We now know that the loop is vectorizable!
1480 // Collect variables that will remain uniform after vectorization.
1481 std::vector<Value*> Worklist;
1482 BasicBlock *Latch = TheLoop->getLoopLatch();
1484 // Start with the conditional branch and walk up the block.
1485 Worklist.push_back(Latch->getTerminator()->getOperand(0));
1487 while (Worklist.size()) {
1488 Instruction *I = dyn_cast<Instruction>(Worklist.back());
1489 Worklist.pop_back();
1491 // Look at instructions inside this loop.
1492 // Stop when reaching PHI nodes.
1493 // TODO: we need to follow values all over the loop, not only in this block.
1494 if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
1497 // This is a known uniform.
1500 // Insert all operands.
1501 for (int i = 0, Op = I->getNumOperands(); i < Op; ++i) {
1502 Worklist.push_back(I->getOperand(i));
1507 bool LoopVectorizationLegality::canVectorizeMemory() {
1508 typedef SmallVector<Value*, 16> ValueVector;
1509 typedef SmallPtrSet<Value*, 16> ValueSet;
1510 // Holds the Load and Store *instructions*.
1513 PtrRtCheck.Pointers.clear();
1514 PtrRtCheck.Need = false;
1517 for (Loop::block_iterator bb = TheLoop->block_begin(),
1518 be = TheLoop->block_end(); bb != be; ++bb) {
1520 // Scan the BB and collect legal loads and stores.
1521 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
1524 // If this is a load, save it. If this instruction can read from memory
1525 // but is not a load, then we quit. Notice that we don't handle function
1526 // calls that read or write.
1527 if (it->mayReadFromMemory()) {
1528 LoadInst *Ld = dyn_cast<LoadInst>(it);
1529 if (!Ld) return false;
1530 if (!Ld->isSimple()) {
1531 DEBUG(dbgs() << "LV: Found a non-simple load.\n");
1534 Loads.push_back(Ld);
1538 // Save 'store' instructions. Abort if other instructions write to memory.
1539 if (it->mayWriteToMemory()) {
1540 StoreInst *St = dyn_cast<StoreInst>(it);
1541 if (!St) return false;
1542 if (!St->isSimple()) {
1543 DEBUG(dbgs() << "LV: Found a non-simple store.\n");
1546 Stores.push_back(St);
1551 // Now we have two lists that hold the loads and the stores.
1552 // Next, we find the pointers that they use.
1554 // Check if we see any stores. If there are no stores, then we don't
1555 // care if the pointers are *restrict*.
1556 if (!Stores.size()) {
1557 DEBUG(dbgs() << "LV: Found a read-only loop!\n");
1561 // Holds the read and read-write *pointers* that we find.
1563 ValueVector ReadWrites;
1565 // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
1566 // multiple times on the same object. If the ptr is accessed twice, once
1567 // for read and once for write, it will only appear once (on the write
1568 // list). This is okay, since we are going to check for conflicts between
1569 // writes and between reads and writes, but not between reads and reads.
1572 ValueVector::iterator I, IE;
1573 for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
1574 StoreInst *ST = dyn_cast<StoreInst>(*I);
1575 assert(ST && "Bad StoreInst");
1576 Value* Ptr = ST->getPointerOperand();
1578 if (isUniform(Ptr)) {
1579 DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
1583 // If we did *not* see this pointer before, insert it to
1584 // the read-write list. At this phase it is only a 'write' list.
1585 if (Seen.insert(Ptr))
1586 ReadWrites.push_back(Ptr);
1589 for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
1590 LoadInst *LD = dyn_cast<LoadInst>(*I);
1591 assert(LD && "Bad LoadInst");
1592 Value* Ptr = LD->getPointerOperand();
1593 // If we did *not* see this pointer before, insert it to the
1594 // read list. If we *did* see it before, then it is already in
1595 // the read-write list. This allows us to vectorize expressions
1596 // such as A[i] += x; Because the address of A[i] is a read-write
1597 // pointer. This only works if the index of A[i] is consecutive.
1598 // If the address of i is unknown (for example A[B[i]]) then we may
1599 // read a few words, modify, and write a few words, and some of the
1600 // words may be written to the same address.
1601 if (Seen.insert(Ptr) || !isConsecutivePtr(Ptr))
1602 Reads.push_back(Ptr);
1605 // If we write (or read-write) to a single destination and there are no
1606 // other reads in this loop then is it safe to vectorize.
1607 if (ReadWrites.size() == 1 && Reads.size() == 0) {
1608 DEBUG(dbgs() << "LV: Found a write-only loop!\n");
1612 // Find pointers with computable bounds. We are going to use this information
1613 // to place a runtime bound check.
1615 for (I = ReadWrites.begin(), IE = ReadWrites.end(); I != IE; ++I)
1616 if (hasComputableBounds(*I)) {
1617 PtrRtCheck.insert(SE, TheLoop, *I);
1618 DEBUG(dbgs() << "LV: Found a runtime check ptr:" << **I <<"\n");
1623 for (I = Reads.begin(), IE = Reads.end(); I != IE; ++I)
1624 if (hasComputableBounds(*I)) {
1625 PtrRtCheck.insert(SE, TheLoop, *I);
1626 DEBUG(dbgs() << "LV: Found a runtime check ptr:" << **I <<"\n");
1632 // Check that we did not collect too many pointers or found a
1633 // unsizeable pointer.
1634 if (!RT || PtrRtCheck.Pointers.size() > RuntimeMemoryCheckThreshold) {
1639 PtrRtCheck.Need = RT;
1642 DEBUG(dbgs() << "LV: We can perform a memory runtime check if needed.\n");
1645 // Now that the pointers are in two lists (Reads and ReadWrites), we
1646 // can check that there are no conflicts between each of the writes and
1647 // between the writes to the reads.
1648 ValueSet WriteObjects;
1649 ValueVector TempObjects;
1651 // Check that the read-writes do not conflict with other read-write
1653 for (I = ReadWrites.begin(), IE = ReadWrites.end(); I != IE; ++I) {
1654 GetUnderlyingObjects(*I, TempObjects, DL);
1655 for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end();
1657 if (!isIdentifiedObject(*it)) {
1658 DEBUG(dbgs() << "LV: Found an unidentified write ptr:"<< **it <<"\n");
1661 if (!WriteObjects.insert(*it)) {
1662 DEBUG(dbgs() << "LV: Found a possible write-write reorder:"
1667 TempObjects.clear();
1670 /// Check that the reads don't conflict with the read-writes.
1671 for (I = Reads.begin(), IE = Reads.end(); I != IE; ++I) {
1672 GetUnderlyingObjects(*I, TempObjects, DL);
1673 for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end();
1675 if (!isIdentifiedObject(*it)) {
1676 DEBUG(dbgs() << "LV: Found an unidentified read ptr:"<< **it <<"\n");
1679 if (WriteObjects.count(*it)) {
1680 DEBUG(dbgs() << "LV: Found a possible read/write reorder:"
1685 TempObjects.clear();
1688 // It is safe to vectorize and we don't need any runtime checks.
1689 DEBUG(dbgs() << "LV: We don't need a runtime memory check.\n");
1694 bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi,
1695 ReductionKind Kind) {
1696 if (Phi->getNumIncomingValues() != 2)
1699 // Reduction variables are only found in the loop header block.
1700 if (Phi->getParent() != TheLoop->getHeader())
1703 // Obtain the reduction start value from the value that comes from the loop
1705 Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
1707 // ExitInstruction is the single value which is used outside the loop.
1708 // We only allow for a single reduction value to be used outside the loop.
1709 // This includes users of the reduction, variables (which form a cycle
1710 // which ends in the phi node).
1711 Instruction *ExitInstruction = 0;
1713 // Iter is our iterator. We start with the PHI node and scan for all of the
1714 // users of this instruction. All users must be instructions which can be
1715 // used as reduction variables (such as ADD). We may have a single
1716 // out-of-block user. They cycle must end with the original PHI.
1717 // Also, we can't have multiple block-local users.
1718 Instruction *Iter = Phi;
1720 // If the instruction has no users then this is a broken
1721 // chain and can't be a reduction variable.
1722 if (Iter->use_empty())
1725 // Any reduction instr must be of one of the allowed kinds.
1726 if (!isReductionInstr(Iter, Kind))
1729 // Did we find a user inside this block ?
1730 bool FoundInBlockUser = false;
1731 // Did we reach the initial PHI node ?
1732 bool FoundStartPHI = false;
1734 // For each of the *users* of iter.
1735 for (Value::use_iterator it = Iter->use_begin(), e = Iter->use_end();
1737 Instruction *U = cast<Instruction>(*it);
1738 // We already know that the PHI is a user.
1740 FoundStartPHI = true;
1744 // Check if we found the exit user.
1745 BasicBlock *Parent = U->getParent();
1746 if (!TheLoop->contains(Parent)) {
1747 // Exit if you find multiple outside users.
1748 if (ExitInstruction != 0)
1750 ExitInstruction = Iter;
1753 // We allow in-loop PHINodes which are not the original reduction PHI
1754 // node. If this PHI is the only user of Iter (happens in IF w/ no ELSE
1755 // structure) then don't skip this PHI.
1756 if (isa<PHINode>(U) && U->getParent() != TheLoop->getHeader() &&
1757 TheLoop->contains(U) && Iter->getNumUses() > 1)
1760 // We can't have multiple inside users.
1761 if (FoundInBlockUser)
1763 FoundInBlockUser = true;
1767 // We found a reduction var if we have reached the original
1768 // phi node and we only have a single instruction with out-of-loop
1770 if (FoundStartPHI && ExitInstruction) {
1771 // This instruction is allowed to have out-of-loop users.
1772 AllowedExit.insert(ExitInstruction);
1774 // Save the description of this reduction variable.
1775 ReductionDescriptor RD(RdxStart, ExitInstruction, Kind);
1776 Reductions[Phi] = RD;
1780 // If we've reached the start PHI but did not find an outside user then
1781 // this is dead code. Abort.
1788 LoopVectorizationLegality::isReductionInstr(Instruction *I,
1789 ReductionKind Kind) {
1790 switch (I->getOpcode()) {
1793 case Instruction::PHI:
1796 case Instruction::Add:
1797 case Instruction::Sub:
1798 return Kind == IntegerAdd;
1799 case Instruction::Mul:
1800 return Kind == IntegerMult;
1801 case Instruction::And:
1802 return Kind == IntegerAnd;
1803 case Instruction::Or:
1804 return Kind == IntegerOr;
1805 case Instruction::Xor:
1806 return Kind == IntegerXor;
1810 LoopVectorizationLegality::InductionKind
1811 LoopVectorizationLegality::isInductionVariable(PHINode *Phi) {
1812 Type *PhiTy = Phi->getType();
1813 // We only handle integer and pointer inductions variables.
1814 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
1817 // Check that the PHI is consecutive and starts at zero.
1818 const SCEV *PhiScev = SE->getSCEV(Phi);
1819 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
1821 DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
1824 const SCEV *Step = AR->getStepRecurrence(*SE);
1826 // Integer inductions need to have a stride of one.
1827 if (PhiTy->isIntegerTy()) {
1829 return IntInduction;
1830 if (Step->isAllOnesValue())
1831 return ReverseIntInduction;
1835 // Calculate the pointer stride and check if it is consecutive.
1836 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
1840 assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
1841 uint64_t Size = DL->getTypeAllocSize(PhiTy->getPointerElementType());
1842 if (C->getValue()->equalsInt(Size))
1843 return PtrInduction;
1848 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) {
1849 assert(TheLoop->contains(BB) && "Unknown block used");
1851 // Blocks that do not dominate the latch need predication.
1852 BasicBlock* Latch = TheLoop->getLoopLatch();
1853 return !DT->dominates(BB, Latch);
1856 bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB) {
1857 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1858 // We don't predicate loads/stores at the moment.
1859 if (it->mayReadFromMemory() || it->mayWriteToMemory() || it->mayThrow())
1862 // The isntructions below can trap.
1863 switch (it->getOpcode()) {
1865 case Instruction::UDiv:
1866 case Instruction::SDiv:
1867 case Instruction::URem:
1868 case Instruction::SRem:
1876 bool LoopVectorizationLegality::hasComputableBounds(Value *Ptr) {
1877 const SCEV *PhiScev = SE->getSCEV(Ptr);
1878 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
1882 return AR->isAffine();
1886 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize,
1888 if (OptForSize && Legal->getRuntimePointerCheck()->Need) {
1889 DEBUG(dbgs() << "LV: Aborting. Runtime ptr check is required in Os.\n");
1893 // Find the trip count.
1894 unsigned TC = SE->getSmallConstantTripCount(TheLoop, TheLoop->getLoopLatch());
1895 DEBUG(dbgs() << "LV: Found trip count:"<<TC<<"\n");
1897 unsigned VF = MaxVectorSize;
1899 // If we optimize the program for size, avoid creating the tail loop.
1901 // If we are unable to calculate the trip count then don't try to vectorize.
1903 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
1907 // Find the maximum SIMD width that can fit within the trip count.
1908 VF = TC % MaxVectorSize;
1913 // If the trip count that we found modulo the vectorization factor is not
1914 // zero then we require a tail.
1916 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
1922 assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
1923 DEBUG(dbgs() << "LV: Using user VF "<<UserVF<<".\n");
1929 DEBUG(dbgs() << "LV: No vector target information. Not vectorizing. \n");
1933 float Cost = expectedCost(1);
1935 DEBUG(dbgs() << "LV: Scalar loop costs: "<< (int)Cost << ".\n");
1936 for (unsigned i=2; i <= VF; i*=2) {
1937 // Notice that the vector loop needs to be executed less times, so
1938 // we need to divide the cost of the vector loops by the width of
1939 // the vector elements.
1940 float VectorCost = expectedCost(i) / (float)i;
1941 DEBUG(dbgs() << "LV: Vector loop of width "<< i << " costs: " <<
1942 (int)VectorCost << ".\n");
1943 if (VectorCost < Cost) {
1949 DEBUG(dbgs() << "LV: Selecting VF = : "<< Width << ".\n");
1953 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
1957 for (Loop::block_iterator bb = TheLoop->block_begin(),
1958 be = TheLoop->block_end(); bb != be; ++bb) {
1959 unsigned BlockCost = 0;
1960 BasicBlock *BB = *bb;
1962 // For each instruction in the old loop.
1963 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1964 unsigned C = getInstructionCost(it, VF);
1966 DEBUG(dbgs() << "LV: Found an estimated cost of "<< C <<" for VF " <<
1967 VF << " For instruction: "<< *it << "\n");
1970 // We assume that if-converted blocks have a 50% chance of being executed.
1971 // When the code is scalar then some of the blocks are avoided due to CF.
1972 // When the code is vectorized we execute all code paths.
1973 if (Legal->blockNeedsPredication(*bb) && VF == 1)
1983 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
1984 assert(VTTI && "Invalid vector target transformation info");
1986 // If we know that this instruction will remain uniform, check the cost of
1987 // the scalar version.
1988 if (Legal->isUniformAfterVectorization(I))
1991 Type *RetTy = I->getType();
1992 Type *VectorTy = ToVectorTy(RetTy, VF);
1994 // TODO: We need to estimate the cost of intrinsic calls.
1995 switch (I->getOpcode()) {
1996 case Instruction::GetElementPtr:
1997 // We mark this instruction as zero-cost because scalar GEPs are usually
1998 // lowered to the intruction addressing mode. At the moment we don't
1999 // generate vector geps.
2001 case Instruction::Br: {
2002 return VTTI->getCFInstrCost(I->getOpcode());
2004 case Instruction::PHI:
2005 //TODO: IF-converted IFs become selects.
2007 case Instruction::Add:
2008 case Instruction::FAdd:
2009 case Instruction::Sub:
2010 case Instruction::FSub:
2011 case Instruction::Mul:
2012 case Instruction::FMul:
2013 case Instruction::UDiv:
2014 case Instruction::SDiv:
2015 case Instruction::FDiv:
2016 case Instruction::URem:
2017 case Instruction::SRem:
2018 case Instruction::FRem:
2019 case Instruction::Shl:
2020 case Instruction::LShr:
2021 case Instruction::AShr:
2022 case Instruction::And:
2023 case Instruction::Or:
2024 case Instruction::Xor:
2025 return VTTI->getArithmeticInstrCost(I->getOpcode(), VectorTy);
2026 case Instruction::Select: {
2027 SelectInst *SI = cast<SelectInst>(I);
2028 const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
2029 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
2030 Type *CondTy = SI->getCondition()->getType();
2032 CondTy = VectorType::get(CondTy, VF);
2034 return VTTI->getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
2036 case Instruction::ICmp:
2037 case Instruction::FCmp: {
2038 Type *ValTy = I->getOperand(0)->getType();
2039 VectorTy = ToVectorTy(ValTy, VF);
2040 return VTTI->getCmpSelInstrCost(I->getOpcode(), VectorTy);
2042 case Instruction::Store: {
2043 StoreInst *SI = cast<StoreInst>(I);
2044 Type *ValTy = SI->getValueOperand()->getType();
2045 VectorTy = ToVectorTy(ValTy, VF);
2048 return VTTI->getMemoryOpCost(I->getOpcode(), ValTy,
2050 SI->getPointerAddressSpace());
2052 // Scalarized stores.
2053 if (!Legal->isConsecutivePtr(SI->getPointerOperand())) {
2055 unsigned ExtCost = VTTI->getInstrCost(Instruction::ExtractElement,
2057 // The cost of extracting from the value vector.
2058 Cost += VF * (ExtCost);
2059 // The cost of the scalar stores.
2060 Cost += VF * VTTI->getMemoryOpCost(I->getOpcode(),
2061 ValTy->getScalarType(),
2063 SI->getPointerAddressSpace());
2068 return VTTI->getMemoryOpCost(I->getOpcode(), VectorTy, SI->getAlignment(),
2069 SI->getPointerAddressSpace());
2071 case Instruction::Load: {
2072 LoadInst *LI = cast<LoadInst>(I);
2075 return VTTI->getMemoryOpCost(I->getOpcode(), RetTy,
2077 LI->getPointerAddressSpace());
2079 // Scalarized loads.
2080 if (!Legal->isConsecutivePtr(LI->getPointerOperand())) {
2082 unsigned InCost = VTTI->getInstrCost(Instruction::InsertElement, RetTy);
2083 // The cost of inserting the loaded value into the result vector.
2084 Cost += VF * (InCost);
2085 // The cost of the scalar stores.
2086 Cost += VF * VTTI->getMemoryOpCost(I->getOpcode(),
2087 RetTy->getScalarType(),
2089 LI->getPointerAddressSpace());
2094 return VTTI->getMemoryOpCost(I->getOpcode(), VectorTy, LI->getAlignment(),
2095 LI->getPointerAddressSpace());
2097 case Instruction::ZExt:
2098 case Instruction::SExt:
2099 case Instruction::FPToUI:
2100 case Instruction::FPToSI:
2101 case Instruction::FPExt:
2102 case Instruction::PtrToInt:
2103 case Instruction::IntToPtr:
2104 case Instruction::SIToFP:
2105 case Instruction::UIToFP:
2106 case Instruction::Trunc:
2107 case Instruction::FPTrunc:
2108 case Instruction::BitCast: {
2109 Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
2110 return VTTI->getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
2112 case Instruction::Call: {
2113 assert(isTriviallyVectorizableIntrinsic(I));
2114 IntrinsicInst *II = cast<IntrinsicInst>(I);
2115 Type *RetTy = ToVectorTy(II->getType(), VF);
2116 SmallVector<Type*, 4> Tys;
2117 for (unsigned i = 0, ie = II->getNumArgOperands(); i != ie; ++i)
2118 Tys.push_back(ToVectorTy(II->getArgOperand(i)->getType(), VF));
2119 return VTTI->getIntrinsicInstrCost(II->getIntrinsicID(), RetTy, Tys);
2122 // We are scalarizing the instruction. Return the cost of the scalar
2123 // instruction, plus the cost of insert and extract into vector
2124 // elements, times the vector width.
2127 bool IsVoid = RetTy->isVoidTy();
2129 unsigned InsCost = (IsVoid ? 0 :
2130 VTTI->getInstrCost(Instruction::InsertElement,
2133 unsigned ExtCost = VTTI->getInstrCost(Instruction::ExtractElement,
2136 // The cost of inserting the results plus extracting each one of the
2138 Cost += VF * (InsCost + ExtCost * I->getNumOperands());
2140 // The cost of executing VF copies of the scalar instruction.
2141 Cost += VF * VTTI->getInstrCost(I->getOpcode(), RetTy);
2147 Type* LoopVectorizationCostModel::ToVectorTy(Type *Scalar, unsigned VF) {
2148 if (Scalar->isVoidTy() || VF == 1)
2150 return VectorType::get(Scalar, VF);
2153 char LoopVectorize::ID = 0;
2154 static const char lv_name[] = "Loop Vectorization";
2155 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
2156 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
2157 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
2158 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
2159 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
2162 Pass *createLoopVectorizePass(bool OptForSize = false) {
2163 return new LoopVectorize(OptForSize);