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;
98 bool OptForSize = F->getFnAttributes().hasAttribute(SzAttr);
100 unsigned VF = CM.selectVectorizationFactor(OptForSize, VectorizationFactor);
103 DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
107 DEBUG(dbgs() << "LV: Found a vectorizable loop ("<< VF << ") in "<<
108 F->getParent()->getModuleIdentifier()<<"\n");
110 // If we decided that it is *legal* to vectorizer the loop then do it.
111 InnerLoopVectorizer LB(L, SE, LI, DT, DL, VF);
114 DEBUG(verifyFunction(*L->getHeader()->getParent()));
118 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
119 LoopPass::getAnalysisUsage(AU);
120 AU.addRequiredID(LoopSimplifyID);
121 AU.addRequiredID(LCSSAID);
122 AU.addRequired<LoopInfo>();
123 AU.addRequired<ScalarEvolution>();
124 AU.addRequired<DominatorTree>();
125 AU.addPreserved<LoopInfo>();
126 AU.addPreserved<DominatorTree>();
133 //===----------------------------------------------------------------------===//
134 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
135 // LoopVectorizationCostModel.
136 //===----------------------------------------------------------------------===//
139 LoopVectorizationLegality::RuntimePointerCheck::insert(ScalarEvolution *SE,
140 Loop *Lp, Value *Ptr) {
141 const SCEV *Sc = SE->getSCEV(Ptr);
142 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
143 assert(AR && "Invalid addrec expression");
144 const SCEV *Ex = SE->getExitCount(Lp, Lp->getLoopLatch());
145 const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
146 Pointers.push_back(Ptr);
147 Starts.push_back(AR->getStart());
148 Ends.push_back(ScEnd);
151 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
153 LLVMContext &C = V->getContext();
154 Type *VTy = VectorType::get(V->getType(), VF);
155 Type *I32 = IntegerType::getInt32Ty(C);
157 // Save the current insertion location.
158 Instruction *Loc = Builder.GetInsertPoint();
160 // We need to place the broadcast of invariant variables outside the loop.
161 Instruction *Instr = dyn_cast<Instruction>(V);
162 bool NewInstr = (Instr && Instr->getParent() == LoopVectorBody);
163 bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
165 // Place the code for broadcasting invariant variables in the new preheader.
167 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
169 Constant *Zero = ConstantInt::get(I32, 0);
170 Value *Zeros = ConstantAggregateZero::get(VectorType::get(I32, VF));
171 Value *UndefVal = UndefValue::get(VTy);
172 // Insert the value into a new vector.
173 Value *SingleElem = Builder.CreateInsertElement(UndefVal, V, Zero);
174 // Broadcast the scalar into all locations in the vector.
175 Value *Shuf = Builder.CreateShuffleVector(SingleElem, UndefVal, Zeros,
178 // Restore the builder insertion point.
180 Builder.SetInsertPoint(Loc);
185 Value *InnerLoopVectorizer::getConsecutiveVector(Value* Val, bool Negate) {
186 assert(Val->getType()->isVectorTy() && "Must be a vector");
187 assert(Val->getType()->getScalarType()->isIntegerTy() &&
188 "Elem must be an integer");
190 Type *ITy = Val->getType()->getScalarType();
191 VectorType *Ty = cast<VectorType>(Val->getType());
192 int VLen = Ty->getNumElements();
193 SmallVector<Constant*, 8> Indices;
195 // Create a vector of consecutive numbers from zero to VF.
196 for (int i = 0; i < VLen; ++i)
197 Indices.push_back(ConstantInt::get(ITy, Negate ? (-i): i ));
199 // Add the consecutive indices to the vector value.
200 Constant *Cv = ConstantVector::get(Indices);
201 assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
202 return Builder.CreateAdd(Val, Cv, "induction");
205 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
206 assert(Ptr->getType()->isPointerTy() && "Unexpected non ptr");
208 // If this value is a pointer induction variable we know it is consecutive.
209 PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
210 if (Phi && Inductions.count(Phi)) {
211 InductionInfo II = Inductions[Phi];
212 if (PtrInduction == II.IK)
216 GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
220 unsigned NumOperands = Gep->getNumOperands();
221 Value *LastIndex = Gep->getOperand(NumOperands - 1);
223 // Check that all of the gep indices are uniform except for the last.
224 for (unsigned i = 0; i < NumOperands - 1; ++i)
225 if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
228 // We can emit wide load/stores only if the last index is the induction
230 const SCEV *Last = SE->getSCEV(LastIndex);
231 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
232 const SCEV *Step = AR->getStepRecurrence(*SE);
234 // The memory is consecutive because the last index is consecutive
235 // and all other indices are loop invariant.
238 if (Step->isAllOnesValue())
245 bool LoopVectorizationLegality::isUniform(Value *V) {
246 return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
249 Value *InnerLoopVectorizer::getVectorValue(Value *V) {
250 assert(V != Induction && "The new induction variable should not be used.");
251 assert(!V->getType()->isVectorTy() && "Can't widen a vector");
252 // If we saved a vectorized copy of V, use it.
253 Value *&MapEntry = WidenMap[V];
257 // Broadcast V and save the value for future uses.
258 Value *B = getBroadcastInstrs(V);
264 InnerLoopVectorizer::getUniformVector(unsigned Val, Type* ScalarTy) {
265 return ConstantVector::getSplat(VF, ConstantInt::get(ScalarTy, Val, true));
268 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
269 assert(Vec->getType()->isVectorTy() && "Invalid type");
270 SmallVector<Constant*, 8> ShuffleMask;
271 for (unsigned i = 0; i < VF; ++i)
272 ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
274 return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
275 ConstantVector::get(ShuffleMask),
279 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr) {
280 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
281 // Holds vector parameters or scalars, in case of uniform vals.
282 SmallVector<Value*, 8> Params;
284 // Find all of the vectorized parameters.
285 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
286 Value *SrcOp = Instr->getOperand(op);
288 // If we are accessing the old induction variable, use the new one.
289 if (SrcOp == OldInduction) {
290 Params.push_back(getVectorValue(SrcOp));
294 // Try using previously calculated values.
295 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
297 // If the src is an instruction that appeared earlier in the basic block
298 // then it should already be vectorized.
299 if (SrcInst && OrigLoop->contains(SrcInst)) {
300 assert(WidenMap.count(SrcInst) && "Source operand is unavailable");
301 // The parameter is a vector value from earlier.
302 Params.push_back(WidenMap[SrcInst]);
304 // The parameter is a scalar from outside the loop. Maybe even a constant.
305 Params.push_back(SrcOp);
309 assert(Params.size() == Instr->getNumOperands() &&
310 "Invalid number of operands");
312 // Does this instruction return a value ?
313 bool IsVoidRetTy = Instr->getType()->isVoidTy();
314 Value *VecResults = 0;
316 // If we have a return value, create an empty vector. We place the scalarized
317 // instructions in this vector.
319 VecResults = UndefValue::get(VectorType::get(Instr->getType(), VF));
321 // For each scalar that we create:
322 for (unsigned i = 0; i < VF; ++i) {
323 Instruction *Cloned = Instr->clone();
325 Cloned->setName(Instr->getName() + ".cloned");
326 // Replace the operands of the cloned instrucions with extracted scalars.
327 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
328 Value *Op = Params[op];
329 // Param is a vector. Need to extract the right lane.
330 if (Op->getType()->isVectorTy())
331 Op = Builder.CreateExtractElement(Op, Builder.getInt32(i));
332 Cloned->setOperand(op, Op);
335 // Place the cloned scalar in the new loop.
336 Builder.Insert(Cloned);
338 // If the original scalar returns a value we need to place it in a vector
339 // so that future users will be able to use it.
341 VecResults = Builder.CreateInsertElement(VecResults, Cloned,
342 Builder.getInt32(i));
346 WidenMap[Instr] = VecResults;
350 InnerLoopVectorizer::addRuntimeCheck(LoopVectorizationLegality *Legal,
352 LoopVectorizationLegality::RuntimePointerCheck *PtrRtCheck =
353 Legal->getRuntimePointerCheck();
355 if (!PtrRtCheck->Need)
358 Value *MemoryRuntimeCheck = 0;
359 unsigned NumPointers = PtrRtCheck->Pointers.size();
360 SmallVector<Value* , 2> Starts;
361 SmallVector<Value* , 2> Ends;
363 SCEVExpander Exp(*SE, "induction");
365 // Use this type for pointer arithmetic.
366 Type* PtrArithTy = Type::getInt8PtrTy(Loc->getContext(), 0);
368 for (unsigned i = 0; i < NumPointers; ++i) {
369 Value *Ptr = PtrRtCheck->Pointers[i];
370 const SCEV *Sc = SE->getSCEV(Ptr);
372 if (SE->isLoopInvariant(Sc, OrigLoop)) {
373 DEBUG(dbgs() << "LV: Adding RT check for a loop invariant ptr:" <<
375 Starts.push_back(Ptr);
378 DEBUG(dbgs() << "LV: Adding RT check for range:" << *Ptr <<"\n");
380 Value *Start = Exp.expandCodeFor(PtrRtCheck->Starts[i], PtrArithTy, Loc);
381 Value *End = Exp.expandCodeFor(PtrRtCheck->Ends[i], PtrArithTy, Loc);
382 Starts.push_back(Start);
387 for (unsigned i = 0; i < NumPointers; ++i) {
388 for (unsigned j = i+1; j < NumPointers; ++j) {
389 Instruction::CastOps Op = Instruction::BitCast;
390 Value *Start0 = CastInst::Create(Op, Starts[i], PtrArithTy, "bc", Loc);
391 Value *Start1 = CastInst::Create(Op, Starts[j], PtrArithTy, "bc", Loc);
392 Value *End0 = CastInst::Create(Op, Ends[i], PtrArithTy, "bc", Loc);
393 Value *End1 = CastInst::Create(Op, Ends[j], PtrArithTy, "bc", Loc);
395 Value *Cmp0 = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_ULE,
396 Start0, End1, "bound0", Loc);
397 Value *Cmp1 = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_ULE,
398 Start1, End0, "bound1", Loc);
399 Value *IsConflict = BinaryOperator::Create(Instruction::And, Cmp0, Cmp1,
400 "found.conflict", Loc);
401 if (MemoryRuntimeCheck)
402 MemoryRuntimeCheck = BinaryOperator::Create(Instruction::Or,
405 "conflict.rdx", Loc);
407 MemoryRuntimeCheck = IsConflict;
412 return MemoryRuntimeCheck;
416 InnerLoopVectorizer::createEmptyLoop(LoopVectorizationLegality *Legal) {
418 In this function we generate a new loop. The new loop will contain
419 the vectorized instructions while the old loop will continue to run the
422 [ ] <-- vector loop bypass.
425 | [ ] <-- vector pre header.
429 | [ ]_| <-- vector loop.
432 >[ ] <--- middle-block.
435 | [ ] <--- new preheader.
439 | [ ]_| <-- old scalar loop to handle remainder.
446 BasicBlock *OldBasicBlock = OrigLoop->getHeader();
447 BasicBlock *BypassBlock = OrigLoop->getLoopPreheader();
448 BasicBlock *ExitBlock = OrigLoop->getExitBlock();
449 assert(ExitBlock && "Must have an exit block");
451 // Some loops have a single integer induction variable, while other loops
452 // don't. One example is c++ iterators that often have multiple pointer
453 // induction variables. In the code below we also support a case where we
454 // don't have a single induction variable.
455 OldInduction = Legal->getInduction();
456 Type *IdxTy = OldInduction ? OldInduction->getType() :
457 DL->getIntPtrType(SE->getContext());
459 // Find the loop boundaries.
460 const SCEV *ExitCount = SE->getExitCount(OrigLoop, OrigLoop->getLoopLatch());
461 assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
463 // Get the total trip count from the count by adding 1.
464 ExitCount = SE->getAddExpr(ExitCount,
465 SE->getConstant(ExitCount->getType(), 1));
467 // Expand the trip count and place the new instructions in the preheader.
468 // Notice that the pre-header does not change, only the loop body.
469 SCEVExpander Exp(*SE, "induction");
471 // Count holds the overall loop count (N).
472 Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
473 BypassBlock->getTerminator());
475 // The loop index does not have to start at Zero. Find the original start
476 // value from the induction PHI node. If we don't have an induction variable
477 // then we know that it starts at zero.
478 Value *StartIdx = OldInduction ?
479 OldInduction->getIncomingValueForBlock(BypassBlock):
480 ConstantInt::get(IdxTy, 0);
482 assert(BypassBlock && "Invalid loop structure");
484 // Generate the code that checks in runtime if arrays overlap.
485 Value *MemoryRuntimeCheck = addRuntimeCheck(Legal,
486 BypassBlock->getTerminator());
488 // Split the single block loop into the two loop structure described above.
489 BasicBlock *VectorPH =
490 BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
491 BasicBlock *VecBody =
492 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
493 BasicBlock *MiddleBlock =
494 VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
495 BasicBlock *ScalarPH =
496 MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
498 // This is the location in which we add all of the logic for bypassing
499 // the new vector loop.
500 Instruction *Loc = BypassBlock->getTerminator();
502 // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
504 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
506 // Generate the induction variable.
507 Induction = Builder.CreatePHI(IdxTy, 2, "index");
508 Constant *Step = ConstantInt::get(IdxTy, VF);
510 // We may need to extend the index in case there is a type mismatch.
511 // We know that the count starts at zero and does not overflow.
512 if (Count->getType() != IdxTy) {
513 // The exit count can be of pointer type. Convert it to the correct
515 if (ExitCount->getType()->isPointerTy())
516 Count = CastInst::CreatePointerCast(Count, IdxTy, "ptrcnt.to.int", Loc);
518 Count = CastInst::CreateZExtOrBitCast(Count, IdxTy, "zext.cnt", Loc);
521 // Add the start index to the loop count to get the new end index.
522 Value *IdxEnd = BinaryOperator::CreateAdd(Count, StartIdx, "end.idx", Loc);
524 // Now we need to generate the expression for N - (N % VF), which is
525 // the part that the vectorized body will execute.
526 Constant *CIVF = ConstantInt::get(IdxTy, VF);
527 Value *R = BinaryOperator::CreateURem(Count, CIVF, "n.mod.vf", Loc);
528 Value *CountRoundDown = BinaryOperator::CreateSub(Count, R, "n.vec", Loc);
529 Value *IdxEndRoundDown = BinaryOperator::CreateAdd(CountRoundDown, StartIdx,
530 "end.idx.rnd.down", Loc);
532 // Now, compare the new count to zero. If it is zero skip the vector loop and
533 // jump to the scalar loop.
534 Value *Cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
539 // If we are using memory runtime checks, include them in.
540 if (MemoryRuntimeCheck)
541 Cmp = BinaryOperator::Create(Instruction::Or, Cmp, MemoryRuntimeCheck,
544 BranchInst::Create(MiddleBlock, VectorPH, Cmp, Loc);
545 // Remove the old terminator.
546 Loc->eraseFromParent();
548 // We are going to resume the execution of the scalar loop.
549 // Go over all of the induction variables that we found and fix the
550 // PHIs that are left in the scalar version of the loop.
551 // The starting values of PHI nodes depend on the counter of the last
552 // iteration in the vectorized loop.
553 // If we come from a bypass edge then we need to start from the original
556 // This variable saves the new starting index for the scalar loop.
557 PHINode *ResumeIndex = 0;
558 LoopVectorizationLegality::InductionList::iterator I, E;
559 LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
560 for (I = List->begin(), E = List->end(); I != E; ++I) {
561 PHINode *OrigPhi = I->first;
562 LoopVectorizationLegality::InductionInfo II = I->second;
563 PHINode *ResumeVal = PHINode::Create(OrigPhi->getType(), 2, "resume.val",
564 MiddleBlock->getTerminator());
567 case LoopVectorizationLegality::NoInduction:
568 llvm_unreachable("Unknown induction");
569 case LoopVectorizationLegality::IntInduction: {
570 // Handle the integer induction counter:
571 assert(OrigPhi->getType()->isIntegerTy() && "Invalid type");
572 assert(OrigPhi == OldInduction && "Unknown integer PHI");
573 // We know what the end value is.
574 EndValue = IdxEndRoundDown;
575 // We also know which PHI node holds it.
576 ResumeIndex = ResumeVal;
579 case LoopVectorizationLegality::ReverseIntInduction: {
580 // Convert the CountRoundDown variable to the PHI size.
581 unsigned CRDSize = CountRoundDown->getType()->getScalarSizeInBits();
582 unsigned IISize = II.StartValue->getType()->getScalarSizeInBits();
583 Value *CRD = CountRoundDown;
584 if (CRDSize > IISize)
585 CRD = CastInst::Create(Instruction::Trunc, CountRoundDown,
586 II.StartValue->getType(),
587 "tr.crd", BypassBlock->getTerminator());
588 else if (CRDSize < IISize)
589 CRD = CastInst::Create(Instruction::SExt, CountRoundDown,
590 II.StartValue->getType(),
591 "sext.crd", BypassBlock->getTerminator());
592 // Handle reverse integer induction counter:
593 EndValue = BinaryOperator::CreateSub(II.StartValue, CRD, "rev.ind.end",
594 BypassBlock->getTerminator());
597 case LoopVectorizationLegality::PtrInduction: {
598 // For pointer induction variables, calculate the offset using
600 EndValue = GetElementPtrInst::Create(II.StartValue, CountRoundDown,
602 BypassBlock->getTerminator());
607 // The new PHI merges the original incoming value, in case of a bypass,
608 // or the value at the end of the vectorized loop.
609 ResumeVal->addIncoming(II.StartValue, BypassBlock);
610 ResumeVal->addIncoming(EndValue, VecBody);
612 // Fix the scalar body counter (PHI node).
613 unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
614 OrigPhi->setIncomingValue(BlockIdx, ResumeVal);
617 // If we are generating a new induction variable then we also need to
618 // generate the code that calculates the exit value. This value is not
619 // simply the end of the counter because we may skip the vectorized body
620 // in case of a runtime check.
622 assert(!ResumeIndex && "Unexpected resume value found");
623 ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val",
624 MiddleBlock->getTerminator());
625 ResumeIndex->addIncoming(StartIdx, BypassBlock);
626 ResumeIndex->addIncoming(IdxEndRoundDown, VecBody);
629 // Make sure that we found the index where scalar loop needs to continue.
630 assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() &&
631 "Invalid resume Index");
633 // Add a check in the middle block to see if we have completed
634 // all of the iterations in the first vector loop.
635 // If (N - N%VF) == N, then we *don't* need to run the remainder.
636 Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd,
637 ResumeIndex, "cmp.n",
638 MiddleBlock->getTerminator());
640 BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
641 // Remove the old terminator.
642 MiddleBlock->getTerminator()->eraseFromParent();
644 // Create i+1 and fill the PHINode.
645 Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
646 Induction->addIncoming(StartIdx, VectorPH);
647 Induction->addIncoming(NextIdx, VecBody);
648 // Create the compare.
649 Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown);
650 Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
652 // Now we have two terminators. Remove the old one from the block.
653 VecBody->getTerminator()->eraseFromParent();
655 // Get ready to start creating new instructions into the vectorized body.
656 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
658 // Create and register the new vector loop.
659 Loop* Lp = new Loop();
660 Loop *ParentLoop = OrigLoop->getParentLoop();
662 // Insert the new loop into the loop nest and register the new basic blocks.
664 ParentLoop->addChildLoop(Lp);
665 ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase());
666 ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase());
667 ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase());
669 LI->addTopLevelLoop(Lp);
672 Lp->addBasicBlockToLoop(VecBody, LI->getBase());
675 LoopVectorPreHeader = VectorPH;
676 LoopScalarPreHeader = ScalarPH;
677 LoopMiddleBlock = MiddleBlock;
678 LoopExitBlock = ExitBlock;
679 LoopVectorBody = VecBody;
680 LoopScalarBody = OldBasicBlock;
681 LoopBypassBlock = BypassBlock;
684 /// This function returns the identity element (or neutral element) for
687 getReductionIdentity(LoopVectorizationLegality::ReductionKind K) {
689 case LoopVectorizationLegality::IntegerXor:
690 case LoopVectorizationLegality::IntegerAdd:
691 case LoopVectorizationLegality::IntegerOr:
692 // Adding, Xoring, Oring zero to a number does not change it.
694 case LoopVectorizationLegality::IntegerMult:
695 // Multiplying a number by 1 does not change it.
697 case LoopVectorizationLegality::IntegerAnd:
698 // AND-ing a number with an all-1 value does not change it.
701 llvm_unreachable("Unknown reduction kind");
706 isTriviallyVectorizableIntrinsic(Instruction *Inst) {
707 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst);
710 switch (II->getIntrinsicID()) {
711 case Intrinsic::sqrt:
715 case Intrinsic::exp2:
717 case Intrinsic::log10:
718 case Intrinsic::log2:
719 case Intrinsic::fabs:
720 case Intrinsic::floor:
721 case Intrinsic::ceil:
722 case Intrinsic::trunc:
723 case Intrinsic::rint:
724 case Intrinsic::nearbyint:
727 case Intrinsic::fmuladd:
736 InnerLoopVectorizer::vectorizeLoop(LoopVectorizationLegality *Legal) {
737 //===------------------------------------------------===//
739 // Notice: any optimization or new instruction that go
740 // into the code below should be also be implemented in
743 //===------------------------------------------------===//
744 BasicBlock &BB = *OrigLoop->getHeader();
746 ConstantInt::get(IntegerType::getInt32Ty(BB.getContext()), 0);
748 // In order to support reduction variables we need to be able to vectorize
749 // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
750 // stages. First, we create a new vector PHI node with no incoming edges.
751 // We use this value when we vectorize all of the instructions that use the
752 // PHI. Next, after all of the instructions in the block are complete we
753 // add the new incoming edges to the PHI. At this point all of the
754 // instructions in the basic block are vectorized, so we can use them to
755 // construct the PHI.
756 PhiVector RdxPHIsToFix;
758 // Scan the loop in a topological order to ensure that defs are vectorized
760 LoopBlocksDFS DFS(OrigLoop);
763 // Vectorize all of the blocks in the original loop.
764 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
765 be = DFS.endRPO(); bb != be; ++bb)
766 vectorizeBlockInLoop(Legal, *bb, &RdxPHIsToFix);
768 // At this point every instruction in the original loop is widened to
769 // a vector form. We are almost done. Now, we need to fix the PHI nodes
770 // that we vectorized. The PHI nodes are currently empty because we did
771 // not want to introduce cycles. Notice that the remaining PHI nodes
772 // that we need to fix are reduction variables.
774 // Create the 'reduced' values for each of the induction vars.
775 // The reduced values are the vector values that we scalarize and combine
776 // after the loop is finished.
777 for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
779 PHINode *RdxPhi = *it;
780 PHINode *VecRdxPhi = dyn_cast<PHINode>(WidenMap[RdxPhi]);
781 assert(RdxPhi && "Unable to recover vectorized PHI");
783 // Find the reduction variable descriptor.
784 assert(Legal->getReductionVars()->count(RdxPhi) &&
785 "Unable to find the reduction variable");
786 LoopVectorizationLegality::ReductionDescriptor RdxDesc =
787 (*Legal->getReductionVars())[RdxPhi];
789 // We need to generate a reduction vector from the incoming scalar.
790 // To do so, we need to generate the 'identity' vector and overide
791 // one of the elements with the incoming scalar reduction. We need
792 // to do it in the vector-loop preheader.
793 Builder.SetInsertPoint(LoopBypassBlock->getTerminator());
795 // This is the vector-clone of the value that leaves the loop.
796 Value *VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
797 Type *VecTy = VectorExit->getType();
799 // Find the reduction identity variable. Zero for addition, or, xor,
800 // one for multiplication, -1 for And.
801 Constant *Identity = getUniformVector(getReductionIdentity(RdxDesc.Kind),
802 VecTy->getScalarType());
804 // This vector is the Identity vector where the first element is the
805 // incoming scalar reduction.
806 Value *VectorStart = Builder.CreateInsertElement(Identity,
807 RdxDesc.StartValue, Zero);
809 // Fix the vector-loop phi.
810 // We created the induction variable so we know that the
811 // preheader is the first entry.
812 BasicBlock *VecPreheader = Induction->getIncomingBlock(0);
814 // Reductions do not have to start at zero. They can start with
815 // any loop invariant values.
816 VecRdxPhi->addIncoming(VectorStart, VecPreheader);
818 getVectorValue(RdxPhi->getIncomingValueForBlock(OrigLoop->getLoopLatch()));
819 VecRdxPhi->addIncoming(Val, LoopVectorBody);
821 // Before each round, move the insertion point right between
822 // the PHIs and the values we are going to write.
823 // This allows us to write both PHINodes and the extractelement
825 Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
827 // This PHINode contains the vectorized reduction variable, or
828 // the initial value vector, if we bypass the vector loop.
829 PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
830 NewPhi->addIncoming(VectorStart, LoopBypassBlock);
831 NewPhi->addIncoming(getVectorValue(RdxDesc.LoopExitInstr), LoopVectorBody);
833 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
834 // and vector ops, reducing the set of values being computed by half each
836 assert(isPowerOf2_32(VF) &&
837 "Reduction emission only supported for pow2 vectors!");
838 Value *TmpVec = NewPhi;
839 SmallVector<Constant*, 32> ShuffleMask(VF, 0);
840 for (unsigned i = VF; i != 1; i >>= 1) {
841 // Move the upper half of the vector to the lower half.
842 for (unsigned j = 0; j != i/2; ++j)
843 ShuffleMask[j] = Builder.getInt32(i/2 + j);
845 // Fill the rest of the mask with undef.
846 std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
847 UndefValue::get(Builder.getInt32Ty()));
850 Builder.CreateShuffleVector(TmpVec,
851 UndefValue::get(TmpVec->getType()),
852 ConstantVector::get(ShuffleMask),
855 // Emit the operation on the shuffled value.
856 switch (RdxDesc.Kind) {
857 case LoopVectorizationLegality::IntegerAdd:
858 TmpVec = Builder.CreateAdd(TmpVec, Shuf, "add.rdx");
860 case LoopVectorizationLegality::IntegerMult:
861 TmpVec = Builder.CreateMul(TmpVec, Shuf, "mul.rdx");
863 case LoopVectorizationLegality::IntegerOr:
864 TmpVec = Builder.CreateOr(TmpVec, Shuf, "or.rdx");
866 case LoopVectorizationLegality::IntegerAnd:
867 TmpVec = Builder.CreateAnd(TmpVec, Shuf, "and.rdx");
869 case LoopVectorizationLegality::IntegerXor:
870 TmpVec = Builder.CreateXor(TmpVec, Shuf, "xor.rdx");
873 llvm_unreachable("Unknown reduction operation");
877 // The result is in the first element of the vector.
878 Value *Scalar0 = Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
880 // Now, we need to fix the users of the reduction variable
881 // inside and outside of the scalar remainder loop.
882 // We know that the loop is in LCSSA form. We need to update the
883 // PHI nodes in the exit blocks.
884 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
885 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
886 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
887 if (!LCSSAPhi) continue;
889 // All PHINodes need to have a single entry edge, or two if
890 // we already fixed them.
891 assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
893 // We found our reduction value exit-PHI. Update it with the
894 // incoming bypass edge.
895 if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
896 // Add an edge coming from the bypass.
897 LCSSAPhi->addIncoming(Scalar0, LoopMiddleBlock);
900 }// end of the LCSSA phi scan.
902 // Fix the scalar loop reduction variable with the incoming reduction sum
903 // from the vector body and from the backedge value.
904 int IncomingEdgeBlockIdx =
905 (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
906 assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
907 // Pick the other block.
908 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
909 (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, Scalar0);
910 (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
911 }// end of for each redux variable.
914 Value *InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
915 assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
918 Value *SrcMask = createBlockInMask(Src);
920 // The terminator has to be a branch inst!
921 BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
922 assert(BI && "Unexpected terminator found");
924 Value *EdgeMask = SrcMask;
925 if (BI->isConditional()) {
926 EdgeMask = getVectorValue(BI->getCondition());
927 if (BI->getSuccessor(0) != Dst)
928 EdgeMask = Builder.CreateNot(EdgeMask);
931 return Builder.CreateAnd(EdgeMask, SrcMask);
934 Value *InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
935 assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
937 // Loop incoming mask is all-one.
938 if (OrigLoop->getHeader() == BB) {
939 Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
940 return getVectorValue(C);
943 // This is the block mask. We OR all incoming edges, and with zero.
944 Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
945 Value *BlockMask = getVectorValue(Zero);
948 for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it)
949 BlockMask = Builder.CreateOr(BlockMask, createEdgeMask(*it, BB));
955 InnerLoopVectorizer::vectorizeBlockInLoop(LoopVectorizationLegality *Legal,
956 BasicBlock *BB, PhiVector *PV) {
957 Constant *Zero = Builder.getInt32(0);
959 // For each instruction in the old loop.
960 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
961 switch (it->getOpcode()) {
962 case Instruction::Br:
963 // Nothing to do for PHIs and BR, since we already took care of the
964 // loop control flow instructions.
966 case Instruction::PHI:{
967 PHINode* P = cast<PHINode>(it);
968 // Handle reduction variables:
969 if (Legal->getReductionVars()->count(P)) {
970 // This is phase one of vectorizing PHIs.
971 Type *VecTy = VectorType::get(it->getType(), VF);
973 PHINode::Create(VecTy, 2, "vec.phi",
974 LoopVectorBody->getFirstInsertionPt());
979 // Check for PHI nodes that are lowered to vector selects.
980 if (P->getParent() != OrigLoop->getHeader()) {
981 // We know that all PHIs in non header blocks are converted into
982 // selects, so we don't have to worry about the insertion order and we
983 // can just use the builder.
985 // At this point we generate the predication tree. There may be
986 // duplications since this is a simple recursive scan, but future
987 // optimizations will clean it up.
988 Value *Cond = createEdgeMask(P->getIncomingBlock(0), P->getParent());
990 Builder.CreateSelect(Cond,
991 getVectorValue(P->getIncomingValue(0)),
992 getVectorValue(P->getIncomingValue(1)),
997 // This PHINode must be an induction variable.
998 // Make sure that we know about it.
999 assert(Legal->getInductionVars()->count(P) &&
1000 "Not an induction variable");
1002 LoopVectorizationLegality::InductionInfo II =
1003 Legal->getInductionVars()->lookup(P);
1006 case LoopVectorizationLegality::NoInduction:
1007 llvm_unreachable("Unknown induction");
1008 case LoopVectorizationLegality::IntInduction: {
1009 assert(P == OldInduction && "Unexpected PHI");
1010 Value *Broadcasted = getBroadcastInstrs(Induction);
1011 // After broadcasting the induction variable we need to make the
1012 // vector consecutive by adding 0, 1, 2 ...
1013 Value *ConsecutiveInduction = getConsecutiveVector(Broadcasted);
1014 WidenMap[OldInduction] = ConsecutiveInduction;
1017 case LoopVectorizationLegality::ReverseIntInduction:
1018 case LoopVectorizationLegality::PtrInduction:
1019 // Handle reverse integer and pointer inductions.
1020 Value *StartIdx = 0;
1021 // If we have a single integer induction variable then use it.
1022 // Otherwise, start counting at zero.
1024 LoopVectorizationLegality::InductionInfo OldII =
1025 Legal->getInductionVars()->lookup(OldInduction);
1026 StartIdx = OldII.StartValue;
1028 StartIdx = ConstantInt::get(Induction->getType(), 0);
1030 // This is the normalized GEP that starts counting at zero.
1031 Value *NormalizedIdx = Builder.CreateSub(Induction, StartIdx,
1034 // Handle the reverse integer induction variable case.
1035 if (LoopVectorizationLegality::ReverseIntInduction == II.IK) {
1036 IntegerType *DstTy = cast<IntegerType>(II.StartValue->getType());
1037 Value *CNI = Builder.CreateSExtOrTrunc(NormalizedIdx, DstTy,
1039 Value *ReverseInd = Builder.CreateSub(II.StartValue, CNI,
1042 // This is a new value so do not hoist it out.
1043 Value *Broadcasted = getBroadcastInstrs(ReverseInd);
1044 // After broadcasting the induction variable we need to make the
1045 // vector consecutive by adding ... -3, -2, -1, 0.
1046 Value *ConsecutiveInduction = getConsecutiveVector(Broadcasted,
1048 WidenMap[it] = ConsecutiveInduction;
1052 // Handle the pointer induction variable case.
1053 assert(P->getType()->isPointerTy() && "Unexpected type.");
1055 // This is the vector of results. Notice that we don't generate
1056 // vector geps because scalar geps result in better code.
1057 Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
1058 for (unsigned int i = 0; i < VF; ++i) {
1059 Constant *Idx = ConstantInt::get(Induction->getType(), i);
1060 Value *GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx,
1062 Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
1064 VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
1065 Builder.getInt32(i),
1069 WidenMap[it] = VecVal;
1075 case Instruction::Add:
1076 case Instruction::FAdd:
1077 case Instruction::Sub:
1078 case Instruction::FSub:
1079 case Instruction::Mul:
1080 case Instruction::FMul:
1081 case Instruction::UDiv:
1082 case Instruction::SDiv:
1083 case Instruction::FDiv:
1084 case Instruction::URem:
1085 case Instruction::SRem:
1086 case Instruction::FRem:
1087 case Instruction::Shl:
1088 case Instruction::LShr:
1089 case Instruction::AShr:
1090 case Instruction::And:
1091 case Instruction::Or:
1092 case Instruction::Xor: {
1093 // Just widen binops.
1094 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
1095 Value *A = getVectorValue(it->getOperand(0));
1096 Value *B = getVectorValue(it->getOperand(1));
1098 // Use this vector value for all users of the original instruction.
1099 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A, B);
1102 // Update the NSW, NUW and Exact flags.
1103 BinaryOperator *VecOp = cast<BinaryOperator>(V);
1104 if (isa<OverflowingBinaryOperator>(BinOp)) {
1105 VecOp->setHasNoSignedWrap(BinOp->hasNoSignedWrap());
1106 VecOp->setHasNoUnsignedWrap(BinOp->hasNoUnsignedWrap());
1108 if (isa<PossiblyExactOperator>(VecOp))
1109 VecOp->setIsExact(BinOp->isExact());
1112 case Instruction::Select: {
1114 // If the selector is loop invariant we can create a select
1115 // instruction with a scalar condition. Otherwise, use vector-select.
1116 Value *Cond = it->getOperand(0);
1117 bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(Cond), OrigLoop);
1119 // The condition can be loop invariant but still defined inside the
1120 // loop. This means that we can't just use the original 'cond' value.
1121 // We have to take the 'vectorized' value and pick the first lane.
1122 // Instcombine will make this a no-op.
1123 Cond = getVectorValue(Cond);
1125 Cond = Builder.CreateExtractElement(Cond, Builder.getInt32(0));
1127 Value *Op0 = getVectorValue(it->getOperand(1));
1128 Value *Op1 = getVectorValue(it->getOperand(2));
1129 WidenMap[it] = Builder.CreateSelect(Cond, Op0, Op1);
1133 case Instruction::ICmp:
1134 case Instruction::FCmp: {
1135 // Widen compares. Generate vector compares.
1136 bool FCmp = (it->getOpcode() == Instruction::FCmp);
1137 CmpInst *Cmp = dyn_cast<CmpInst>(it);
1138 Value *A = getVectorValue(it->getOperand(0));
1139 Value *B = getVectorValue(it->getOperand(1));
1141 WidenMap[it] = Builder.CreateFCmp(Cmp->getPredicate(), A, B);
1143 WidenMap[it] = Builder.CreateICmp(Cmp->getPredicate(), A, B);
1147 case Instruction::Store: {
1148 // Attempt to issue a wide store.
1149 StoreInst *SI = dyn_cast<StoreInst>(it);
1150 Type *StTy = VectorType::get(SI->getValueOperand()->getType(), VF);
1151 Value *Ptr = SI->getPointerOperand();
1152 unsigned Alignment = SI->getAlignment();
1154 assert(!Legal->isUniform(Ptr) &&
1155 "We do not allow storing to uniform addresses");
1158 int Stride = Legal->isConsecutivePtr(Ptr);
1159 bool Reverse = Stride < 0;
1161 scalarizeInstruction(it);
1165 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1167 // The last index does not have to be the induction. It can be
1168 // consecutive and be a function of the index. For example A[I+1];
1169 unsigned NumOperands = Gep->getNumOperands();
1170 Value *LastIndex = getVectorValue(Gep->getOperand(NumOperands - 1));
1171 LastIndex = Builder.CreateExtractElement(LastIndex, Zero);
1173 // Create the new GEP with the new induction variable.
1174 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1175 Gep2->setOperand(NumOperands - 1, LastIndex);
1176 Ptr = Builder.Insert(Gep2);
1178 // Use the induction element ptr.
1179 assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1180 Ptr = Builder.CreateExtractElement(getVectorValue(Ptr), Zero);
1183 // If the address is consecutive but reversed, then the
1184 // wide load needs to start at the last vector element.
1186 Ptr = Builder.CreateGEP(Ptr, Builder.getInt32(1 - VF));
1188 Ptr = Builder.CreateBitCast(Ptr, StTy->getPointerTo());
1189 Value *Val = getVectorValue(SI->getValueOperand());
1191 Val = reverseVector(Val);
1192 Builder.CreateStore(Val, Ptr)->setAlignment(Alignment);
1195 case Instruction::Load: {
1196 // Attempt to issue a wide load.
1197 LoadInst *LI = dyn_cast<LoadInst>(it);
1198 Type *RetTy = VectorType::get(LI->getType(), VF);
1199 Value *Ptr = LI->getPointerOperand();
1200 unsigned Alignment = LI->getAlignment();
1202 // If the pointer is loop invariant or if it is non consecutive,
1203 // scalarize the load.
1204 int Stride = Legal->isConsecutivePtr(Ptr);
1205 bool Reverse = Stride < 0;
1206 if (Legal->isUniform(Ptr) || Stride == 0) {
1207 scalarizeInstruction(it);
1211 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1213 // The last index does not have to be the induction. It can be
1214 // consecutive and be a function of the index. For example A[I+1];
1215 unsigned NumOperands = Gep->getNumOperands();
1216 Value *LastIndex = getVectorValue(Gep->getOperand(NumOperands -1));
1217 LastIndex = Builder.CreateExtractElement(LastIndex, Zero);
1219 // Create the new GEP with the new induction variable.
1220 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1221 Gep2->setOperand(NumOperands - 1, LastIndex);
1222 Ptr = Builder.Insert(Gep2);
1224 // Use the induction element ptr.
1225 assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1226 Ptr = Builder.CreateExtractElement(getVectorValue(Ptr), Zero);
1228 // If the address is consecutive but reversed, then the
1229 // wide load needs to start at the last vector element.
1231 Ptr = Builder.CreateGEP(Ptr, Builder.getInt32(1 - VF));
1233 Ptr = Builder.CreateBitCast(Ptr, RetTy->getPointerTo());
1234 LI = Builder.CreateLoad(Ptr);
1235 LI->setAlignment(Alignment);
1237 // Use this vector value for all users of the load.
1238 WidenMap[it] = Reverse ? reverseVector(LI) : LI;
1241 case Instruction::ZExt:
1242 case Instruction::SExt:
1243 case Instruction::FPToUI:
1244 case Instruction::FPToSI:
1245 case Instruction::FPExt:
1246 case Instruction::PtrToInt:
1247 case Instruction::IntToPtr:
1248 case Instruction::SIToFP:
1249 case Instruction::UIToFP:
1250 case Instruction::Trunc:
1251 case Instruction::FPTrunc:
1252 case Instruction::BitCast: {
1253 CastInst *CI = dyn_cast<CastInst>(it);
1254 /// Optimize the special case where the source is the induction
1255 /// variable. Notice that we can only optimize the 'trunc' case
1256 /// because: a. FP conversions lose precision, b. sext/zext may wrap,
1257 /// c. other casts depend on pointer size.
1258 if (CI->getOperand(0) == OldInduction &&
1259 it->getOpcode() == Instruction::Trunc) {
1260 Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
1262 Value *Broadcasted = getBroadcastInstrs(ScalarCast);
1263 WidenMap[it] = getConsecutiveVector(Broadcasted);
1266 /// Vectorize casts.
1267 Value *A = getVectorValue(it->getOperand(0));
1268 Type *DestTy = VectorType::get(CI->getType()->getScalarType(), VF);
1269 WidenMap[it] = Builder.CreateCast(CI->getOpcode(), A, DestTy);
1273 case Instruction::Call: {
1274 assert(isTriviallyVectorizableIntrinsic(it));
1275 Module *M = BB->getParent()->getParent();
1276 IntrinsicInst *II = cast<IntrinsicInst>(it);
1277 Intrinsic::ID ID = II->getIntrinsicID();
1278 SmallVector<Value*, 4> Args;
1279 for (unsigned i = 0, ie = II->getNumArgOperands(); i != ie; ++i)
1280 Args.push_back(getVectorValue(II->getArgOperand(i)));
1281 Type *Tys[] = { VectorType::get(II->getType()->getScalarType(), VF) };
1282 Function *F = Intrinsic::getDeclaration(M, ID, Tys);
1283 WidenMap[it] = Builder.CreateCall(F, Args);
1288 // All other instructions are unsupported. Scalarize them.
1289 scalarizeInstruction(it);
1292 }// end of for_each instr.
1295 void InnerLoopVectorizer::updateAnalysis() {
1296 // Forget the original basic block.
1297 SE->forgetLoop(OrigLoop);
1299 // Update the dominator tree information.
1300 assert(DT->properlyDominates(LoopBypassBlock, LoopExitBlock) &&
1301 "Entry does not dominate exit.");
1303 DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlock);
1304 DT->addNewBlock(LoopVectorBody, LoopVectorPreHeader);
1305 DT->addNewBlock(LoopMiddleBlock, LoopBypassBlock);
1306 DT->addNewBlock(LoopScalarPreHeader, LoopMiddleBlock);
1307 DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
1308 DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
1310 DEBUG(DT->verifyAnalysis());
1313 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
1314 if (!EnableIfConversion)
1317 assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
1318 std::vector<BasicBlock*> &LoopBlocks = TheLoop->getBlocksVector();
1320 // Collect the blocks that need predication.
1321 for (unsigned i = 0, e = LoopBlocks.size(); i < e; ++i) {
1322 BasicBlock *BB = LoopBlocks[i];
1324 // We don't support switch statements inside loops.
1325 if (!isa<BranchInst>(BB->getTerminator()))
1328 // We must have at most two predecessors because we need to convert
1329 // all PHIs to selects.
1330 unsigned Preds = std::distance(pred_begin(BB), pred_end(BB));
1334 // We must be able to predicate all blocks that need to be predicated.
1335 if (blockNeedsPredication(BB) && !blockCanBePredicated(BB))
1339 // We can if-convert this loop.
1343 bool LoopVectorizationLegality::canVectorize() {
1344 assert(TheLoop->getLoopPreheader() && "No preheader!!");
1346 // We can only vectorize innermost loops.
1347 if (TheLoop->getSubLoopsVector().size())
1350 // We must have a single backedge.
1351 if (TheLoop->getNumBackEdges() != 1)
1354 // We must have a single exiting block.
1355 if (!TheLoop->getExitingBlock())
1358 unsigned NumBlocks = TheLoop->getNumBlocks();
1360 // Check if we can if-convert non single-bb loops.
1361 if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
1362 DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
1366 // We need to have a loop header.
1367 BasicBlock *Latch = TheLoop->getLoopLatch();
1368 DEBUG(dbgs() << "LV: Found a loop: " <<
1369 TheLoop->getHeader()->getName() << "\n");
1371 // ScalarEvolution needs to be able to find the exit count.
1372 const SCEV *ExitCount = SE->getExitCount(TheLoop, Latch);
1373 if (ExitCount == SE->getCouldNotCompute()) {
1374 DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
1378 // Do not loop-vectorize loops with a tiny trip count.
1379 unsigned TC = SE->getSmallConstantTripCount(TheLoop, Latch);
1380 if (TC > 0u && TC < TinyTripCountThreshold) {
1381 DEBUG(dbgs() << "LV: Found a loop with a very small trip count. " <<
1382 "This loop is not worth vectorizing.\n");
1386 // Check if we can vectorize the instructions and CFG in this loop.
1387 if (!canVectorizeInstrs()) {
1388 DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
1392 // Go over each instruction and look at memory deps.
1393 if (!canVectorizeMemory()) {
1394 DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
1398 // Collect all of the variables that remain uniform after vectorization.
1399 collectLoopUniforms();
1401 DEBUG(dbgs() << "LV: We can vectorize this loop" <<
1402 (PtrRtCheck.Need ? " (with a runtime bound check)" : "")
1405 // Okay! We can vectorize. At this point we don't have any other mem analysis
1406 // which may limit our maximum vectorization factor, so just return true with
1411 bool LoopVectorizationLegality::canVectorizeInstrs() {
1412 BasicBlock *PreHeader = TheLoop->getLoopPreheader();
1413 BasicBlock *Header = TheLoop->getHeader();
1415 // For each block in the loop.
1416 for (Loop::block_iterator bb = TheLoop->block_begin(),
1417 be = TheLoop->block_end(); bb != be; ++bb) {
1419 // Scan the instructions in the block and look for hazards.
1420 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
1423 if (PHINode *Phi = dyn_cast<PHINode>(it)) {
1424 // This should not happen because the loop should be normalized.
1425 if (Phi->getNumIncomingValues() != 2) {
1426 DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
1430 // Check that this PHI type is allowed.
1431 if (!Phi->getType()->isIntegerTy() &&
1432 !Phi->getType()->isPointerTy()) {
1433 DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
1437 // If this PHINode is not in the header block, then we know that we
1438 // can convert it to select during if-conversion. No need to check if
1439 // the PHIs in this block are induction or reduction variables.
1443 // This is the value coming from the preheader.
1444 Value *StartValue = Phi->getIncomingValueForBlock(PreHeader);
1445 // Check if this is an induction variable.
1446 InductionKind IK = isInductionVariable(Phi);
1448 if (NoInduction != IK) {
1449 // Int inductions are special because we only allow one IV.
1450 if (IK == IntInduction) {
1452 DEBUG(dbgs() << "LV: Found too many inductions."<< *Phi <<"\n");
1458 DEBUG(dbgs() << "LV: Found an induction variable.\n");
1459 Inductions[Phi] = InductionInfo(StartValue, IK);
1463 if (AddReductionVar(Phi, IntegerAdd)) {
1464 DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
1467 if (AddReductionVar(Phi, IntegerMult)) {
1468 DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n");
1471 if (AddReductionVar(Phi, IntegerOr)) {
1472 DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n");
1475 if (AddReductionVar(Phi, IntegerAnd)) {
1476 DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n");
1479 if (AddReductionVar(Phi, IntegerXor)) {
1480 DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n");
1484 DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
1486 }// end of PHI handling
1488 // We still don't handle functions.
1489 CallInst *CI = dyn_cast<CallInst>(it);
1490 if (CI && !isTriviallyVectorizableIntrinsic(it)) {
1491 DEBUG(dbgs() << "LV: Found a call site.\n");
1495 // Check that the instruction return type is vectorizable.
1496 if (!VectorType::isValidElementType(it->getType()) &&
1497 !it->getType()->isVoidTy()) {
1498 DEBUG(dbgs() << "LV: Found unvectorizable type." << "\n");
1502 // Check that the stored type is vectorizable.
1503 if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
1504 Type *T = ST->getValueOperand()->getType();
1505 if (!VectorType::isValidElementType(T))
1509 // Reduction instructions are allowed to have exit users.
1510 // All other instructions must not have external users.
1511 if (!AllowedExit.count(it))
1512 //Check that all of the users of the loop are inside the BB.
1513 for (Value::use_iterator I = it->use_begin(), E = it->use_end();
1515 Instruction *U = cast<Instruction>(*I);
1516 // This user may be a reduction exit value.
1517 if (!TheLoop->contains(U)) {
1518 DEBUG(dbgs() << "LV: Found an outside user for : "<< *U << "\n");
1527 DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
1528 assert(getInductionVars()->size() && "No induction variables");
1534 void LoopVectorizationLegality::collectLoopUniforms() {
1535 // We now know that the loop is vectorizable!
1536 // Collect variables that will remain uniform after vectorization.
1537 std::vector<Value*> Worklist;
1538 BasicBlock *Latch = TheLoop->getLoopLatch();
1540 // Start with the conditional branch and walk up the block.
1541 Worklist.push_back(Latch->getTerminator()->getOperand(0));
1543 while (Worklist.size()) {
1544 Instruction *I = dyn_cast<Instruction>(Worklist.back());
1545 Worklist.pop_back();
1547 // Look at instructions inside this loop.
1548 // Stop when reaching PHI nodes.
1549 // TODO: we need to follow values all over the loop, not only in this block.
1550 if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
1553 // This is a known uniform.
1556 // Insert all operands.
1557 for (int i = 0, Op = I->getNumOperands(); i < Op; ++i) {
1558 Worklist.push_back(I->getOperand(i));
1563 bool LoopVectorizationLegality::canVectorizeMemory() {
1564 typedef SmallVector<Value*, 16> ValueVector;
1565 typedef SmallPtrSet<Value*, 16> ValueSet;
1566 // Holds the Load and Store *instructions*.
1569 PtrRtCheck.Pointers.clear();
1570 PtrRtCheck.Need = false;
1573 for (Loop::block_iterator bb = TheLoop->block_begin(),
1574 be = TheLoop->block_end(); bb != be; ++bb) {
1576 // Scan the BB and collect legal loads and stores.
1577 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
1580 // If this is a load, save it. If this instruction can read from memory
1581 // but is not a load, then we quit. Notice that we don't handle function
1582 // calls that read or write.
1583 if (it->mayReadFromMemory()) {
1584 LoadInst *Ld = dyn_cast<LoadInst>(it);
1585 if (!Ld) return false;
1586 if (!Ld->isSimple()) {
1587 DEBUG(dbgs() << "LV: Found a non-simple load.\n");
1590 Loads.push_back(Ld);
1594 // Save 'store' instructions. Abort if other instructions write to memory.
1595 if (it->mayWriteToMemory()) {
1596 StoreInst *St = dyn_cast<StoreInst>(it);
1597 if (!St) return false;
1598 if (!St->isSimple()) {
1599 DEBUG(dbgs() << "LV: Found a non-simple store.\n");
1602 Stores.push_back(St);
1607 // Now we have two lists that hold the loads and the stores.
1608 // Next, we find the pointers that they use.
1610 // Check if we see any stores. If there are no stores, then we don't
1611 // care if the pointers are *restrict*.
1612 if (!Stores.size()) {
1613 DEBUG(dbgs() << "LV: Found a read-only loop!\n");
1617 // Holds the read and read-write *pointers* that we find.
1619 ValueVector ReadWrites;
1621 // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
1622 // multiple times on the same object. If the ptr is accessed twice, once
1623 // for read and once for write, it will only appear once (on the write
1624 // list). This is okay, since we are going to check for conflicts between
1625 // writes and between reads and writes, but not between reads and reads.
1628 ValueVector::iterator I, IE;
1629 for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
1630 StoreInst *ST = cast<StoreInst>(*I);
1631 Value* Ptr = ST->getPointerOperand();
1633 if (isUniform(Ptr)) {
1634 DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
1638 // If we did *not* see this pointer before, insert it to
1639 // the read-write list. At this phase it is only a 'write' list.
1640 if (Seen.insert(Ptr))
1641 ReadWrites.push_back(Ptr);
1644 for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
1645 LoadInst *LD = cast<LoadInst>(*I);
1646 Value* Ptr = LD->getPointerOperand();
1647 // If we did *not* see this pointer before, insert it to the
1648 // read list. If we *did* see it before, then it is already in
1649 // the read-write list. This allows us to vectorize expressions
1650 // such as A[i] += x; Because the address of A[i] is a read-write
1651 // pointer. This only works if the index of A[i] is consecutive.
1652 // If the address of i is unknown (for example A[B[i]]) then we may
1653 // read a few words, modify, and write a few words, and some of the
1654 // words may be written to the same address.
1655 if (Seen.insert(Ptr) || 0 == isConsecutivePtr(Ptr))
1656 Reads.push_back(Ptr);
1659 // If we write (or read-write) to a single destination and there are no
1660 // other reads in this loop then is it safe to vectorize.
1661 if (ReadWrites.size() == 1 && Reads.size() == 0) {
1662 DEBUG(dbgs() << "LV: Found a write-only loop!\n");
1666 // Find pointers with computable bounds. We are going to use this information
1667 // to place a runtime bound check.
1668 bool CanDoRT = true;
1669 for (I = ReadWrites.begin(), IE = ReadWrites.end(); I != IE; ++I)
1670 if (hasComputableBounds(*I)) {
1671 PtrRtCheck.insert(SE, TheLoop, *I);
1672 DEBUG(dbgs() << "LV: Found a runtime check ptr:" << **I <<"\n");
1677 for (I = Reads.begin(), IE = Reads.end(); I != IE; ++I)
1678 if (hasComputableBounds(*I)) {
1679 PtrRtCheck.insert(SE, TheLoop, *I);
1680 DEBUG(dbgs() << "LV: Found a runtime check ptr:" << **I <<"\n");
1686 // Check that we did not collect too many pointers or found a
1687 // unsizeable pointer.
1688 if (!CanDoRT || PtrRtCheck.Pointers.size() > RuntimeMemoryCheckThreshold) {
1694 DEBUG(dbgs() << "LV: We can perform a memory runtime check if needed.\n");
1697 bool NeedRTCheck = false;
1699 // Now that the pointers are in two lists (Reads and ReadWrites), we
1700 // can check that there are no conflicts between each of the writes and
1701 // between the writes to the reads.
1702 ValueSet WriteObjects;
1703 ValueVector TempObjects;
1705 // Check that the read-writes do not conflict with other read-write
1707 bool AllWritesIdentified = true;
1708 for (I = ReadWrites.begin(), IE = ReadWrites.end(); I != IE; ++I) {
1709 GetUnderlyingObjects(*I, TempObjects, DL);
1710 for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end();
1712 if (!isIdentifiedObject(*it)) {
1713 DEBUG(dbgs() << "LV: Found an unidentified write ptr:"<< **it <<"\n");
1715 AllWritesIdentified = false;
1717 if (!WriteObjects.insert(*it)) {
1718 DEBUG(dbgs() << "LV: Found a possible write-write reorder:"
1723 TempObjects.clear();
1726 /// Check that the reads don't conflict with the read-writes.
1727 for (I = Reads.begin(), IE = Reads.end(); I != IE; ++I) {
1728 GetUnderlyingObjects(*I, TempObjects, DL);
1729 for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end();
1731 // If all of the writes are identified then we don't care if the read
1732 // pointer is identified or not.
1733 if (!AllWritesIdentified && !isIdentifiedObject(*it)) {
1734 DEBUG(dbgs() << "LV: Found an unidentified read ptr:"<< **it <<"\n");
1737 if (WriteObjects.count(*it)) {
1738 DEBUG(dbgs() << "LV: Found a possible read/write reorder:"
1743 TempObjects.clear();
1746 PtrRtCheck.Need = NeedRTCheck;
1747 if (NeedRTCheck && !CanDoRT) {
1748 DEBUG(dbgs() << "LV: We can't vectorize because we can't find " <<
1749 "the array bounds.\n");
1754 DEBUG(dbgs() << "LV: We "<< (NeedRTCheck ? "" : "don't") <<
1755 " need a runtime memory check.\n");
1759 bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi,
1760 ReductionKind Kind) {
1761 if (Phi->getNumIncomingValues() != 2)
1764 // Reduction variables are only found in the loop header block.
1765 if (Phi->getParent() != TheLoop->getHeader())
1768 // Obtain the reduction start value from the value that comes from the loop
1770 Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
1772 // ExitInstruction is the single value which is used outside the loop.
1773 // We only allow for a single reduction value to be used outside the loop.
1774 // This includes users of the reduction, variables (which form a cycle
1775 // which ends in the phi node).
1776 Instruction *ExitInstruction = 0;
1778 // Iter is our iterator. We start with the PHI node and scan for all of the
1779 // users of this instruction. All users must be instructions that can be
1780 // used as reduction variables (such as ADD). We may have a single
1781 // out-of-block user. The cycle must end with the original PHI.
1782 Instruction *Iter = Phi;
1784 // If the instruction has no users then this is a broken
1785 // chain and can't be a reduction variable.
1786 if (Iter->use_empty())
1789 // Any reduction instr must be of one of the allowed kinds.
1790 if (!isReductionInstr(Iter, Kind))
1793 // Did we find a user inside this loop already ?
1794 bool FoundInBlockUser = false;
1795 // Did we reach the initial PHI node already ?
1796 bool FoundStartPHI = false;
1798 // For each of the *users* of iter.
1799 for (Value::use_iterator it = Iter->use_begin(), e = Iter->use_end();
1801 Instruction *U = cast<Instruction>(*it);
1802 // We already know that the PHI is a user.
1804 FoundStartPHI = true;
1808 // Check if we found the exit user.
1809 BasicBlock *Parent = U->getParent();
1810 if (!TheLoop->contains(Parent)) {
1811 // Exit if you find multiple outside users.
1812 if (ExitInstruction != 0)
1814 ExitInstruction = Iter;
1817 // We allow in-loop PHINodes which are not the original reduction PHI
1818 // node. If this PHI is the only user of Iter (happens in IF w/ no ELSE
1819 // structure) then don't skip this PHI.
1820 if (isa<PHINode>(Iter) && isa<PHINode>(U) &&
1821 U->getParent() != TheLoop->getHeader() &&
1822 TheLoop->contains(U) &&
1823 Iter->getNumUses() > 1)
1826 // We can't have multiple inside users.
1827 if (FoundInBlockUser)
1829 FoundInBlockUser = true;
1833 // We found a reduction var if we have reached the original
1834 // phi node and we only have a single instruction with out-of-loop
1836 if (FoundStartPHI && ExitInstruction) {
1837 // This instruction is allowed to have out-of-loop users.
1838 AllowedExit.insert(ExitInstruction);
1840 // Save the description of this reduction variable.
1841 ReductionDescriptor RD(RdxStart, ExitInstruction, Kind);
1842 Reductions[Phi] = RD;
1846 // If we've reached the start PHI but did not find an outside user then
1847 // this is dead code. Abort.
1854 LoopVectorizationLegality::isReductionInstr(Instruction *I,
1855 ReductionKind Kind) {
1856 switch (I->getOpcode()) {
1859 case Instruction::PHI:
1862 case Instruction::Add:
1863 case Instruction::Sub:
1864 return Kind == IntegerAdd;
1865 case Instruction::Mul:
1866 return Kind == IntegerMult;
1867 case Instruction::And:
1868 return Kind == IntegerAnd;
1869 case Instruction::Or:
1870 return Kind == IntegerOr;
1871 case Instruction::Xor:
1872 return Kind == IntegerXor;
1876 LoopVectorizationLegality::InductionKind
1877 LoopVectorizationLegality::isInductionVariable(PHINode *Phi) {
1878 Type *PhiTy = Phi->getType();
1879 // We only handle integer and pointer inductions variables.
1880 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
1883 // Check that the PHI is consecutive and starts at zero.
1884 const SCEV *PhiScev = SE->getSCEV(Phi);
1885 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
1887 DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
1890 const SCEV *Step = AR->getStepRecurrence(*SE);
1892 // Integer inductions need to have a stride of one.
1893 if (PhiTy->isIntegerTy()) {
1895 return IntInduction;
1896 if (Step->isAllOnesValue())
1897 return ReverseIntInduction;
1901 // Calculate the pointer stride and check if it is consecutive.
1902 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
1906 assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
1907 uint64_t Size = DL->getTypeAllocSize(PhiTy->getPointerElementType());
1908 if (C->getValue()->equalsInt(Size))
1909 return PtrInduction;
1914 bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
1915 Value *In0 = const_cast<Value*>(V);
1916 PHINode *PN = dyn_cast_or_null<PHINode>(In0);
1920 return Inductions.count(PN);
1923 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) {
1924 assert(TheLoop->contains(BB) && "Unknown block used");
1926 // Blocks that do not dominate the latch need predication.
1927 BasicBlock* Latch = TheLoop->getLoopLatch();
1928 return !DT->dominates(BB, Latch);
1931 bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB) {
1932 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1933 // We don't predicate loads/stores at the moment.
1934 if (it->mayReadFromMemory() || it->mayWriteToMemory() || it->mayThrow())
1937 // The instructions below can trap.
1938 switch (it->getOpcode()) {
1940 case Instruction::UDiv:
1941 case Instruction::SDiv:
1942 case Instruction::URem:
1943 case Instruction::SRem:
1951 bool LoopVectorizationLegality::hasComputableBounds(Value *Ptr) {
1952 const SCEV *PhiScev = SE->getSCEV(Ptr);
1953 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
1957 return AR->isAffine();
1961 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize,
1963 if (OptForSize && Legal->getRuntimePointerCheck()->Need) {
1964 DEBUG(dbgs() << "LV: Aborting. Runtime ptr check is required in Os.\n");
1968 // Find the trip count.
1969 unsigned TC = SE->getSmallConstantTripCount(TheLoop, TheLoop->getLoopLatch());
1970 DEBUG(dbgs() << "LV: Found trip count:"<<TC<<"\n");
1972 unsigned VF = MaxVectorSize;
1974 // If we optimize the program for size, avoid creating the tail loop.
1976 // If we are unable to calculate the trip count then don't try to vectorize.
1978 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
1982 // Find the maximum SIMD width that can fit within the trip count.
1983 VF = TC % MaxVectorSize;
1988 // If the trip count that we found modulo the vectorization factor is not
1989 // zero then we require a tail.
1991 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
1997 assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
1998 DEBUG(dbgs() << "LV: Using user VF "<<UserVF<<".\n");
2004 DEBUG(dbgs() << "LV: No vector target information. Not vectorizing. \n");
2008 float Cost = expectedCost(1);
2010 DEBUG(dbgs() << "LV: Scalar loop costs: "<< (int)Cost << ".\n");
2011 for (unsigned i=2; i <= VF; i*=2) {
2012 // Notice that the vector loop needs to be executed less times, so
2013 // we need to divide the cost of the vector loops by the width of
2014 // the vector elements.
2015 float VectorCost = expectedCost(i) / (float)i;
2016 DEBUG(dbgs() << "LV: Vector loop of width "<< i << " costs: " <<
2017 (int)VectorCost << ".\n");
2018 if (VectorCost < Cost) {
2024 DEBUG(dbgs() << "LV: Selecting VF = : "<< Width << ".\n");
2028 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
2032 for (Loop::block_iterator bb = TheLoop->block_begin(),
2033 be = TheLoop->block_end(); bb != be; ++bb) {
2034 unsigned BlockCost = 0;
2035 BasicBlock *BB = *bb;
2037 // For each instruction in the old loop.
2038 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2039 unsigned C = getInstructionCost(it, VF);
2041 DEBUG(dbgs() << "LV: Found an estimated cost of "<< C <<" for VF " <<
2042 VF << " For instruction: "<< *it << "\n");
2045 // We assume that if-converted blocks have a 50% chance of being executed.
2046 // When the code is scalar then some of the blocks are avoided due to CF.
2047 // When the code is vectorized we execute all code paths.
2048 if (Legal->blockNeedsPredication(*bb) && VF == 1)
2058 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
2059 assert(VTTI && "Invalid vector target transformation info");
2061 // If we know that this instruction will remain uniform, check the cost of
2062 // the scalar version.
2063 if (Legal->isUniformAfterVectorization(I))
2066 Type *RetTy = I->getType();
2067 Type *VectorTy = ToVectorTy(RetTy, VF);
2069 // TODO: We need to estimate the cost of intrinsic calls.
2070 switch (I->getOpcode()) {
2071 case Instruction::GetElementPtr:
2072 // We mark this instruction as zero-cost because scalar GEPs are usually
2073 // lowered to the intruction addressing mode. At the moment we don't
2074 // generate vector geps.
2076 case Instruction::Br: {
2077 return VTTI->getCFInstrCost(I->getOpcode());
2079 case Instruction::PHI:
2080 //TODO: IF-converted IFs become selects.
2082 case Instruction::Add:
2083 case Instruction::FAdd:
2084 case Instruction::Sub:
2085 case Instruction::FSub:
2086 case Instruction::Mul:
2087 case Instruction::FMul:
2088 case Instruction::UDiv:
2089 case Instruction::SDiv:
2090 case Instruction::FDiv:
2091 case Instruction::URem:
2092 case Instruction::SRem:
2093 case Instruction::FRem:
2094 case Instruction::Shl:
2095 case Instruction::LShr:
2096 case Instruction::AShr:
2097 case Instruction::And:
2098 case Instruction::Or:
2099 case Instruction::Xor:
2100 return VTTI->getArithmeticInstrCost(I->getOpcode(), VectorTy);
2101 case Instruction::Select: {
2102 SelectInst *SI = cast<SelectInst>(I);
2103 const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
2104 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
2105 Type *CondTy = SI->getCondition()->getType();
2107 CondTy = VectorType::get(CondTy, VF);
2109 return VTTI->getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
2111 case Instruction::ICmp:
2112 case Instruction::FCmp: {
2113 Type *ValTy = I->getOperand(0)->getType();
2114 VectorTy = ToVectorTy(ValTy, VF);
2115 return VTTI->getCmpSelInstrCost(I->getOpcode(), VectorTy);
2117 case Instruction::Store: {
2118 StoreInst *SI = cast<StoreInst>(I);
2119 Type *ValTy = SI->getValueOperand()->getType();
2120 VectorTy = ToVectorTy(ValTy, VF);
2123 return VTTI->getMemoryOpCost(I->getOpcode(), VectorTy,
2125 SI->getPointerAddressSpace());
2127 // Scalarized stores.
2128 int Stride = Legal->isConsecutivePtr(SI->getPointerOperand());
2129 bool Reverse = Stride < 0;
2133 // The cost of extracting from the value vector and pointer vector.
2134 Type *PtrTy = ToVectorTy(I->getOperand(0)->getType(), VF);
2135 for (unsigned i = 0; i < VF; ++i) {
2136 Cost += VTTI->getVectorInstrCost(Instruction::ExtractElement,
2138 Cost += VTTI->getVectorInstrCost(Instruction::ExtractElement,
2142 // The cost of the scalar stores.
2143 Cost += VF * VTTI->getMemoryOpCost(I->getOpcode(),
2144 ValTy->getScalarType(),
2146 SI->getPointerAddressSpace());
2151 unsigned Cost = VTTI->getMemoryOpCost(I->getOpcode(), VectorTy,
2153 SI->getPointerAddressSpace());
2155 Cost += VTTI->getShuffleCost(VectorTargetTransformInfo::Reverse,
2159 case Instruction::Load: {
2160 LoadInst *LI = cast<LoadInst>(I);
2163 return VTTI->getMemoryOpCost(I->getOpcode(), VectorTy,
2165 LI->getPointerAddressSpace());
2167 // Scalarized loads.
2168 int Stride = Legal->isConsecutivePtr(LI->getPointerOperand());
2169 bool Reverse = Stride < 0;
2172 Type *PtrTy = ToVectorTy(I->getOperand(0)->getType(), VF);
2174 // The cost of extracting from the pointer vector.
2175 for (unsigned i = 0; i < VF; ++i)
2176 Cost += VTTI->getVectorInstrCost(Instruction::ExtractElement,
2179 // The cost of inserting data to the result vector.
2180 for (unsigned i = 0; i < VF; ++i)
2181 Cost += VTTI->getVectorInstrCost(Instruction::InsertElement,
2184 // The cost of the scalar stores.
2185 Cost += VF * VTTI->getMemoryOpCost(I->getOpcode(),
2186 RetTy->getScalarType(),
2188 LI->getPointerAddressSpace());
2193 unsigned Cost = VTTI->getMemoryOpCost(I->getOpcode(), VectorTy,
2195 LI->getPointerAddressSpace());
2197 Cost += VTTI->getShuffleCost(VectorTargetTransformInfo::Reverse,
2201 case Instruction::ZExt:
2202 case Instruction::SExt:
2203 case Instruction::FPToUI:
2204 case Instruction::FPToSI:
2205 case Instruction::FPExt:
2206 case Instruction::PtrToInt:
2207 case Instruction::IntToPtr:
2208 case Instruction::SIToFP:
2209 case Instruction::UIToFP:
2210 case Instruction::Trunc:
2211 case Instruction::FPTrunc:
2212 case Instruction::BitCast: {
2213 // We optimize the truncation of induction variable.
2214 // The cost of these is the same as the scalar operation.
2215 if (I->getOpcode() == Instruction::Trunc &&
2216 Legal->isInductionVariable(I->getOperand(0)))
2217 return VTTI->getCastInstrCost(I->getOpcode(), I->getType(),
2218 I->getOperand(0)->getType());
2220 Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
2221 return VTTI->getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
2223 case Instruction::Call: {
2224 assert(isTriviallyVectorizableIntrinsic(I));
2225 IntrinsicInst *II = cast<IntrinsicInst>(I);
2226 Type *RetTy = ToVectorTy(II->getType(), VF);
2227 SmallVector<Type*, 4> Tys;
2228 for (unsigned i = 0, ie = II->getNumArgOperands(); i != ie; ++i)
2229 Tys.push_back(ToVectorTy(II->getArgOperand(i)->getType(), VF));
2230 return VTTI->getIntrinsicInstrCost(II->getIntrinsicID(), RetTy, Tys);
2233 // We are scalarizing the instruction. Return the cost of the scalar
2234 // instruction, plus the cost of insert and extract into vector
2235 // elements, times the vector width.
2238 if (!RetTy->isVoidTy() && VF != 1) {
2239 unsigned InsCost = VTTI->getVectorInstrCost(Instruction::InsertElement,
2241 unsigned ExtCost = VTTI->getVectorInstrCost(Instruction::ExtractElement,
2244 // The cost of inserting the results plus extracting each one of the
2246 Cost += VF * (InsCost + ExtCost * I->getNumOperands());
2249 // The cost of executing VF copies of the scalar instruction. This opcode
2250 // is unknown. Assume that it is the same as 'mul'.
2251 Cost += VF * VTTI->getArithmeticInstrCost(Instruction::Mul, VectorTy);
2257 Type* LoopVectorizationCostModel::ToVectorTy(Type *Scalar, unsigned VF) {
2258 if (Scalar->isVoidTy() || VF == 1)
2260 return VectorType::get(Scalar, VF);
2263 char LoopVectorize::ID = 0;
2264 static const char lv_name[] = "Loop Vectorization";
2265 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
2266 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
2267 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
2268 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
2269 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
2272 Pass *createLoopVectorizePass() {
2273 return new LoopVectorize();