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/IR/Constants.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/DerivedTypes.h"
24 #include "llvm/IR/Function.h"
25 #include "llvm/IR/Instructions.h"
26 #include "llvm/IR/IntrinsicInst.h"
27 #include "llvm/IR/LLVMContext.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/IR/Type.h"
30 #include "llvm/IR/Value.h"
31 #include "llvm/Pass.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/TargetTransformInfo.h"
36 #include "llvm/Transforms/Scalar.h"
37 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
38 #include "llvm/Transforms/Utils/Local.h"
39 #include "llvm/Transforms/Vectorize.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."));
45 static cl::opt<unsigned>
46 VectorizationUnroll("force-vector-unroll", cl::init(1), cl::Hidden,
47 cl::desc("Sets the vectorization unroll count. "
48 "Zero is autoselect."));
51 EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
52 cl::desc("Enable if-conversion during vectorization."));
56 /// The LoopVectorize Pass.
57 struct LoopVectorize : public LoopPass {
58 /// Pass identification, replacement for typeid
61 explicit LoopVectorize() : LoopPass(ID) {
62 initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
68 TargetTransformInfo *TTI;
71 virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
72 // We only vectorize innermost loops.
76 SE = &getAnalysis<ScalarEvolution>();
77 DL = getAnalysisIfAvailable<DataLayout>();
78 LI = &getAnalysis<LoopInfo>();
79 TTI = getAnalysisIfAvailable<TargetTransformInfo>();
80 DT = &getAnalysis<DominatorTree>();
82 DEBUG(dbgs() << "LV: Checking a loop in \"" <<
83 L->getHeader()->getParent()->getName() << "\"\n");
85 // Check if it is legal to vectorize the loop.
86 LoopVectorizationLegality LVL(L, SE, DL, DT);
87 if (!LVL.canVectorize()) {
88 DEBUG(dbgs() << "LV: Not vectorizing.\n");
92 // Select the preffered vectorization factor.
93 const VectorTargetTransformInfo *VTTI = 0;
95 VTTI = TTI->getVectorTargetTransformInfo();
96 // Use the cost model.
97 LoopVectorizationCostModel CM(L, SE, &LVL, VTTI);
99 // Check the function attribues to find out if this function should be
100 // optimized for size.
101 Function *F = L->getHeader()->getParent();
102 Attribute::AttrKind SzAttr = Attribute::OptimizeForSize;
103 Attribute::AttrKind FlAttr = Attribute::NoImplicitFloat;
104 unsigned FnIndex = AttributeSet::FunctionIndex;
105 bool OptForSize = F->getAttributes().hasAttribute(FnIndex, SzAttr);
106 bool NoFloat = F->getAttributes().hasAttribute(FnIndex, FlAttr);
109 DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
110 "attribute is used.\n");
114 unsigned VF = CM.selectVectorizationFactor(OptForSize, VectorizationFactor);
117 DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
121 DEBUG(dbgs() << "LV: Found a vectorizable loop ("<< VF << ") in "<<
122 F->getParent()->getModuleIdentifier()<<"\n");
124 // If we decided that it is *legal* to vectorizer the loop then do it.
125 InnerLoopVectorizer LB(L, SE, LI, DT, DL, VF, VectorizationUnroll);
128 DEBUG(verifyFunction(*L->getHeader()->getParent()));
132 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
133 LoopPass::getAnalysisUsage(AU);
134 AU.addRequiredID(LoopSimplifyID);
135 AU.addRequiredID(LCSSAID);
136 AU.addRequired<LoopInfo>();
137 AU.addRequired<ScalarEvolution>();
138 AU.addRequired<DominatorTree>();
139 AU.addPreserved<LoopInfo>();
140 AU.addPreserved<DominatorTree>();
147 //===----------------------------------------------------------------------===//
148 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
149 // LoopVectorizationCostModel.
150 //===----------------------------------------------------------------------===//
153 LoopVectorizationLegality::RuntimePointerCheck::insert(ScalarEvolution *SE,
154 Loop *Lp, Value *Ptr) {
155 const SCEV *Sc = SE->getSCEV(Ptr);
156 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
157 assert(AR && "Invalid addrec expression");
158 const SCEV *Ex = SE->getExitCount(Lp, Lp->getLoopLatch());
159 const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
160 Pointers.push_back(Ptr);
161 Starts.push_back(AR->getStart());
162 Ends.push_back(ScEnd);
165 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
166 // Save the current insertion location.
167 Instruction *Loc = Builder.GetInsertPoint();
169 // We need to place the broadcast of invariant variables outside the loop.
170 Instruction *Instr = dyn_cast<Instruction>(V);
171 bool NewInstr = (Instr && Instr->getParent() == LoopVectorBody);
172 bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
174 // Place the code for broadcasting invariant variables in the new preheader.
176 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
178 // Broadcast the scalar into all locations in the vector.
179 Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
181 // Restore the builder insertion point.
183 Builder.SetInsertPoint(Loc);
188 Value *InnerLoopVectorizer::getConsecutiveVector(Value* Val, unsigned StartIdx,
190 assert(Val->getType()->isVectorTy() && "Must be a vector");
191 assert(Val->getType()->getScalarType()->isIntegerTy() &&
192 "Elem must be an integer");
194 Type *ITy = Val->getType()->getScalarType();
195 VectorType *Ty = cast<VectorType>(Val->getType());
196 int VLen = Ty->getNumElements();
197 SmallVector<Constant*, 8> Indices;
199 // Create a vector of consecutive numbers from zero to VF.
200 for (int i = 0; i < VLen; ++i) {
201 int Idx = Negate ? (-i): i;
202 Indices.push_back(ConstantInt::get(ITy, StartIdx + Idx));
205 // Add the consecutive indices to the vector value.
206 Constant *Cv = ConstantVector::get(Indices);
207 assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
208 return Builder.CreateAdd(Val, Cv, "induction");
211 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
212 assert(Ptr->getType()->isPointerTy() && "Unexpected non ptr");
214 // If this value is a pointer induction variable we know it is consecutive.
215 PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
216 if (Phi && Inductions.count(Phi)) {
217 InductionInfo II = Inductions[Phi];
218 if (PtrInduction == II.IK)
222 GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
226 unsigned NumOperands = Gep->getNumOperands();
227 Value *LastIndex = Gep->getOperand(NumOperands - 1);
229 // Check that all of the gep indices are uniform except for the last.
230 for (unsigned i = 0; i < NumOperands - 1; ++i)
231 if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
234 // We can emit wide load/stores only if the last index is the induction
236 const SCEV *Last = SE->getSCEV(LastIndex);
237 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
238 const SCEV *Step = AR->getStepRecurrence(*SE);
240 // The memory is consecutive because the last index is consecutive
241 // and all other indices are loop invariant.
244 if (Step->isAllOnesValue())
251 bool LoopVectorizationLegality::isUniform(Value *V) {
252 return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
255 InnerLoopVectorizer::VectorParts&
256 InnerLoopVectorizer::getVectorValue(Value *V) {
257 assert(V != Induction && "The new induction variable should not be used.");
258 assert(!V->getType()->isVectorTy() && "Can't widen a vector");
260 // If we have this scalar in the map, return it.
262 return WidenMap.get(V);
264 // If this scalar is unknown, assume that it is a constant or that it is
265 // loop invariant. Broadcast V and save the value for future uses.
266 Value *B = getBroadcastInstrs(V);
267 WidenMap.splat(V, B);
268 return WidenMap.get(V);
272 InnerLoopVectorizer::getUniformVector(unsigned Val, Type* ScalarTy) {
273 return ConstantVector::getSplat(VF, ConstantInt::get(ScalarTy, Val, true));
276 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
277 assert(Vec->getType()->isVectorTy() && "Invalid type");
278 SmallVector<Constant*, 8> ShuffleMask;
279 for (unsigned i = 0; i < VF; ++i)
280 ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
282 return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
283 ConstantVector::get(ShuffleMask),
287 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr) {
288 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
289 // Holds vector parameters or scalars, in case of uniform vals.
290 SmallVector<VectorParts, 4> Params;
292 // Find all of the vectorized parameters.
293 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
294 Value *SrcOp = Instr->getOperand(op);
296 // If we are accessing the old induction variable, use the new one.
297 if (SrcOp == OldInduction) {
298 Params.push_back(getVectorValue(SrcOp));
302 // Try using previously calculated values.
303 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
305 // If the src is an instruction that appeared earlier in the basic block
306 // then it should already be vectorized.
307 if (SrcInst && OrigLoop->contains(SrcInst)) {
308 assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
309 // The parameter is a vector value from earlier.
310 Params.push_back(WidenMap.get(SrcInst));
312 // The parameter is a scalar from outside the loop. Maybe even a constant.
314 Scalars.append(UF, SrcOp);
315 Params.push_back(Scalars);
319 assert(Params.size() == Instr->getNumOperands() &&
320 "Invalid number of operands");
322 // Does this instruction return a value ?
323 bool IsVoidRetTy = Instr->getType()->isVoidTy();
325 Value *UndefVec = IsVoidRetTy ? 0 :
326 UndefValue::get(VectorType::get(Instr->getType(), VF));
327 // Create a new entry in the WidenMap and initialize it to Undef or Null.
328 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
330 // For each scalar that we create:
331 for (unsigned Width = 0; Width < VF; ++Width) {
332 // For each vector unroll 'part':
333 for (unsigned Part = 0; Part < UF; ++Part) {
334 Instruction *Cloned = Instr->clone();
336 Cloned->setName(Instr->getName() + ".cloned");
337 // Replace the operands of the cloned instrucions with extracted scalars.
338 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
339 Value *Op = Params[op][Part];
340 // Param is a vector. Need to extract the right lane.
341 if (Op->getType()->isVectorTy())
342 Op = Builder.CreateExtractElement(Op, Builder.getInt32(Width));
343 Cloned->setOperand(op, Op);
346 // Place the cloned scalar in the new loop.
347 Builder.Insert(Cloned);
349 // If the original scalar returns a value we need to place it in a vector
350 // so that future users will be able to use it.
352 VecResults[Part] = Builder.CreateInsertElement(VecResults[Part], Cloned,
353 Builder.getInt32(Width));
359 InnerLoopVectorizer::addRuntimeCheck(LoopVectorizationLegality *Legal,
361 LoopVectorizationLegality::RuntimePointerCheck *PtrRtCheck =
362 Legal->getRuntimePointerCheck();
364 if (!PtrRtCheck->Need)
367 Value *MemoryRuntimeCheck = 0;
368 unsigned NumPointers = PtrRtCheck->Pointers.size();
369 SmallVector<Value* , 2> Starts;
370 SmallVector<Value* , 2> Ends;
372 SCEVExpander Exp(*SE, "induction");
374 // Use this type for pointer arithmetic.
375 Type* PtrArithTy = Type::getInt8PtrTy(Loc->getContext(), 0);
377 for (unsigned i = 0; i < NumPointers; ++i) {
378 Value *Ptr = PtrRtCheck->Pointers[i];
379 const SCEV *Sc = SE->getSCEV(Ptr);
381 if (SE->isLoopInvariant(Sc, OrigLoop)) {
382 DEBUG(dbgs() << "LV: Adding RT check for a loop invariant ptr:" <<
384 Starts.push_back(Ptr);
387 DEBUG(dbgs() << "LV: Adding RT check for range:" << *Ptr <<"\n");
389 Value *Start = Exp.expandCodeFor(PtrRtCheck->Starts[i], PtrArithTy, Loc);
390 Value *End = Exp.expandCodeFor(PtrRtCheck->Ends[i], PtrArithTy, Loc);
391 Starts.push_back(Start);
396 for (unsigned i = 0; i < NumPointers; ++i) {
397 for (unsigned j = i+1; j < NumPointers; ++j) {
398 Instruction::CastOps Op = Instruction::BitCast;
399 Value *Start0 = CastInst::Create(Op, Starts[i], PtrArithTy, "bc", Loc);
400 Value *Start1 = CastInst::Create(Op, Starts[j], PtrArithTy, "bc", Loc);
401 Value *End0 = CastInst::Create(Op, Ends[i], PtrArithTy, "bc", Loc);
402 Value *End1 = CastInst::Create(Op, Ends[j], PtrArithTy, "bc", Loc);
404 Value *Cmp0 = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_ULE,
405 Start0, End1, "bound0", Loc);
406 Value *Cmp1 = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_ULE,
407 Start1, End0, "bound1", Loc);
408 Value *IsConflict = BinaryOperator::Create(Instruction::And, Cmp0, Cmp1,
409 "found.conflict", Loc);
410 if (MemoryRuntimeCheck)
411 MemoryRuntimeCheck = BinaryOperator::Create(Instruction::Or,
414 "conflict.rdx", Loc);
416 MemoryRuntimeCheck = IsConflict;
421 return MemoryRuntimeCheck;
425 InnerLoopVectorizer::createEmptyLoop(LoopVectorizationLegality *Legal) {
427 In this function we generate a new loop. The new loop will contain
428 the vectorized instructions while the old loop will continue to run the
431 [ ] <-- vector loop bypass.
434 | [ ] <-- vector pre header.
438 | [ ]_| <-- vector loop.
441 >[ ] <--- middle-block.
444 | [ ] <--- new preheader.
448 | [ ]_| <-- old scalar loop to handle remainder.
455 BasicBlock *OldBasicBlock = OrigLoop->getHeader();
456 BasicBlock *BypassBlock = OrigLoop->getLoopPreheader();
457 BasicBlock *ExitBlock = OrigLoop->getExitBlock();
458 assert(ExitBlock && "Must have an exit block");
460 // Some loops have a single integer induction variable, while other loops
461 // don't. One example is c++ iterators that often have multiple pointer
462 // induction variables. In the code below we also support a case where we
463 // don't have a single induction variable.
464 OldInduction = Legal->getInduction();
465 Type *IdxTy = OldInduction ? OldInduction->getType() :
466 DL->getIntPtrType(SE->getContext());
468 // Find the loop boundaries.
469 const SCEV *ExitCount = SE->getExitCount(OrigLoop, OrigLoop->getLoopLatch());
470 assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
472 // Get the total trip count from the count by adding 1.
473 ExitCount = SE->getAddExpr(ExitCount,
474 SE->getConstant(ExitCount->getType(), 1));
476 // Expand the trip count and place the new instructions in the preheader.
477 // Notice that the pre-header does not change, only the loop body.
478 SCEVExpander Exp(*SE, "induction");
480 // Count holds the overall loop count (N).
481 Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
482 BypassBlock->getTerminator());
484 // The loop index does not have to start at Zero. Find the original start
485 // value from the induction PHI node. If we don't have an induction variable
486 // then we know that it starts at zero.
487 Value *StartIdx = OldInduction ?
488 OldInduction->getIncomingValueForBlock(BypassBlock):
489 ConstantInt::get(IdxTy, 0);
491 assert(BypassBlock && "Invalid loop structure");
493 // Generate the code that checks in runtime if arrays overlap.
494 Value *MemoryRuntimeCheck = addRuntimeCheck(Legal,
495 BypassBlock->getTerminator());
497 // Split the single block loop into the two loop structure described above.
498 BasicBlock *VectorPH =
499 BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
500 BasicBlock *VecBody =
501 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
502 BasicBlock *MiddleBlock =
503 VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
504 BasicBlock *ScalarPH =
505 MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
507 // This is the location in which we add all of the logic for bypassing
508 // the new vector loop.
509 Instruction *Loc = BypassBlock->getTerminator();
511 // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
513 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
515 // Generate the induction variable.
516 Induction = Builder.CreatePHI(IdxTy, 2, "index");
517 // The loop step is equal to the vectorization factor (num of SIMD elements)
518 // times the unroll factor (num of SIMD instructions).
519 Constant *Step = ConstantInt::get(IdxTy, VF * UF);
521 // We may need to extend the index in case there is a type mismatch.
522 // We know that the count starts at zero and does not overflow.
523 if (Count->getType() != IdxTy) {
524 // The exit count can be of pointer type. Convert it to the correct
526 if (ExitCount->getType()->isPointerTy())
527 Count = CastInst::CreatePointerCast(Count, IdxTy, "ptrcnt.to.int", Loc);
529 Count = CastInst::CreateZExtOrBitCast(Count, IdxTy, "zext.cnt", Loc);
532 // Add the start index to the loop count to get the new end index.
533 Value *IdxEnd = BinaryOperator::CreateAdd(Count, StartIdx, "end.idx", Loc);
535 // Now we need to generate the expression for N - (N % VF), which is
536 // the part that the vectorized body will execute.
537 Value *R = BinaryOperator::CreateURem(Count, Step, "n.mod.vf", Loc);
538 Value *CountRoundDown = BinaryOperator::CreateSub(Count, R, "n.vec", Loc);
539 Value *IdxEndRoundDown = BinaryOperator::CreateAdd(CountRoundDown, StartIdx,
540 "end.idx.rnd.down", Loc);
542 // Now, compare the new count to zero. If it is zero skip the vector loop and
543 // jump to the scalar loop.
544 Value *Cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
549 // If we are using memory runtime checks, include them in.
550 if (MemoryRuntimeCheck)
551 Cmp = BinaryOperator::Create(Instruction::Or, Cmp, MemoryRuntimeCheck,
554 BranchInst::Create(MiddleBlock, VectorPH, Cmp, Loc);
555 // Remove the old terminator.
556 Loc->eraseFromParent();
558 // We are going to resume the execution of the scalar loop.
559 // Go over all of the induction variables that we found and fix the
560 // PHIs that are left in the scalar version of the loop.
561 // The starting values of PHI nodes depend on the counter of the last
562 // iteration in the vectorized loop.
563 // If we come from a bypass edge then we need to start from the original
566 // This variable saves the new starting index for the scalar loop.
567 PHINode *ResumeIndex = 0;
568 LoopVectorizationLegality::InductionList::iterator I, E;
569 LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
570 for (I = List->begin(), E = List->end(); I != E; ++I) {
571 PHINode *OrigPhi = I->first;
572 LoopVectorizationLegality::InductionInfo II = I->second;
573 PHINode *ResumeVal = PHINode::Create(OrigPhi->getType(), 2, "resume.val",
574 MiddleBlock->getTerminator());
577 case LoopVectorizationLegality::NoInduction:
578 llvm_unreachable("Unknown induction");
579 case LoopVectorizationLegality::IntInduction: {
580 // Handle the integer induction counter:
581 assert(OrigPhi->getType()->isIntegerTy() && "Invalid type");
582 assert(OrigPhi == OldInduction && "Unknown integer PHI");
583 // We know what the end value is.
584 EndValue = IdxEndRoundDown;
585 // We also know which PHI node holds it.
586 ResumeIndex = ResumeVal;
589 case LoopVectorizationLegality::ReverseIntInduction: {
590 // Convert the CountRoundDown variable to the PHI size.
591 unsigned CRDSize = CountRoundDown->getType()->getScalarSizeInBits();
592 unsigned IISize = II.StartValue->getType()->getScalarSizeInBits();
593 Value *CRD = CountRoundDown;
594 if (CRDSize > IISize)
595 CRD = CastInst::Create(Instruction::Trunc, CountRoundDown,
596 II.StartValue->getType(),
597 "tr.crd", BypassBlock->getTerminator());
598 else if (CRDSize < IISize)
599 CRD = CastInst::Create(Instruction::SExt, CountRoundDown,
600 II.StartValue->getType(),
601 "sext.crd", BypassBlock->getTerminator());
602 // Handle reverse integer induction counter:
603 EndValue = BinaryOperator::CreateSub(II.StartValue, CRD, "rev.ind.end",
604 BypassBlock->getTerminator());
607 case LoopVectorizationLegality::PtrInduction: {
608 // For pointer induction variables, calculate the offset using
610 EndValue = GetElementPtrInst::Create(II.StartValue, CountRoundDown,
612 BypassBlock->getTerminator());
617 // The new PHI merges the original incoming value, in case of a bypass,
618 // or the value at the end of the vectorized loop.
619 ResumeVal->addIncoming(II.StartValue, BypassBlock);
620 ResumeVal->addIncoming(EndValue, VecBody);
622 // Fix the scalar body counter (PHI node).
623 unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
624 OrigPhi->setIncomingValue(BlockIdx, ResumeVal);
627 // If we are generating a new induction variable then we also need to
628 // generate the code that calculates the exit value. This value is not
629 // simply the end of the counter because we may skip the vectorized body
630 // in case of a runtime check.
632 assert(!ResumeIndex && "Unexpected resume value found");
633 ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val",
634 MiddleBlock->getTerminator());
635 ResumeIndex->addIncoming(StartIdx, BypassBlock);
636 ResumeIndex->addIncoming(IdxEndRoundDown, VecBody);
639 // Make sure that we found the index where scalar loop needs to continue.
640 assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() &&
641 "Invalid resume Index");
643 // Add a check in the middle block to see if we have completed
644 // all of the iterations in the first vector loop.
645 // If (N - N%VF) == N, then we *don't* need to run the remainder.
646 Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd,
647 ResumeIndex, "cmp.n",
648 MiddleBlock->getTerminator());
650 BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
651 // Remove the old terminator.
652 MiddleBlock->getTerminator()->eraseFromParent();
654 // Create i+1 and fill the PHINode.
655 Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
656 Induction->addIncoming(StartIdx, VectorPH);
657 Induction->addIncoming(NextIdx, VecBody);
658 // Create the compare.
659 Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown);
660 Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
662 // Now we have two terminators. Remove the old one from the block.
663 VecBody->getTerminator()->eraseFromParent();
665 // Get ready to start creating new instructions into the vectorized body.
666 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
668 // Create and register the new vector loop.
669 Loop* Lp = new Loop();
670 Loop *ParentLoop = OrigLoop->getParentLoop();
672 // Insert the new loop into the loop nest and register the new basic blocks.
674 ParentLoop->addChildLoop(Lp);
675 ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase());
676 ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase());
677 ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase());
679 LI->addTopLevelLoop(Lp);
682 Lp->addBasicBlockToLoop(VecBody, LI->getBase());
685 LoopVectorPreHeader = VectorPH;
686 LoopScalarPreHeader = ScalarPH;
687 LoopMiddleBlock = MiddleBlock;
688 LoopExitBlock = ExitBlock;
689 LoopVectorBody = VecBody;
690 LoopScalarBody = OldBasicBlock;
691 LoopBypassBlock = BypassBlock;
694 /// This function returns the identity element (or neutral element) for
697 getReductionIdentity(LoopVectorizationLegality::ReductionKind K) {
699 case LoopVectorizationLegality::IntegerXor:
700 case LoopVectorizationLegality::IntegerAdd:
701 case LoopVectorizationLegality::IntegerOr:
702 // Adding, Xoring, Oring zero to a number does not change it.
704 case LoopVectorizationLegality::IntegerMult:
705 // Multiplying a number by 1 does not change it.
707 case LoopVectorizationLegality::IntegerAnd:
708 // AND-ing a number with an all-1 value does not change it.
711 llvm_unreachable("Unknown reduction kind");
716 isTriviallyVectorizableIntrinsic(Instruction *Inst) {
717 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst);
720 switch (II->getIntrinsicID()) {
721 case Intrinsic::sqrt:
725 case Intrinsic::exp2:
727 case Intrinsic::log10:
728 case Intrinsic::log2:
729 case Intrinsic::fabs:
730 case Intrinsic::floor:
731 case Intrinsic::ceil:
732 case Intrinsic::trunc:
733 case Intrinsic::rint:
734 case Intrinsic::nearbyint:
737 case Intrinsic::fmuladd:
746 InnerLoopVectorizer::vectorizeLoop(LoopVectorizationLegality *Legal) {
747 //===------------------------------------------------===//
749 // Notice: any optimization or new instruction that go
750 // into the code below should be also be implemented in
753 //===------------------------------------------------===//
754 BasicBlock &BB = *OrigLoop->getHeader();
756 ConstantInt::get(IntegerType::getInt32Ty(BB.getContext()), 0);
758 // In order to support reduction variables we need to be able to vectorize
759 // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
760 // stages. First, we create a new vector PHI node with no incoming edges.
761 // We use this value when we vectorize all of the instructions that use the
762 // PHI. Next, after all of the instructions in the block are complete we
763 // add the new incoming edges to the PHI. At this point all of the
764 // instructions in the basic block are vectorized, so we can use them to
765 // construct the PHI.
766 PhiVector RdxPHIsToFix;
768 // Scan the loop in a topological order to ensure that defs are vectorized
770 LoopBlocksDFS DFS(OrigLoop);
773 // Vectorize all of the blocks in the original loop.
774 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
775 be = DFS.endRPO(); bb != be; ++bb)
776 vectorizeBlockInLoop(Legal, *bb, &RdxPHIsToFix);
778 // At this point every instruction in the original loop is widened to
779 // a vector form. We are almost done. Now, we need to fix the PHI nodes
780 // that we vectorized. The PHI nodes are currently empty because we did
781 // not want to introduce cycles. Notice that the remaining PHI nodes
782 // that we need to fix are reduction variables.
784 // Create the 'reduced' values for each of the induction vars.
785 // The reduced values are the vector values that we scalarize and combine
786 // after the loop is finished.
787 for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
789 PHINode *RdxPhi = *it;
790 assert(RdxPhi && "Unable to recover vectorized PHI");
792 // Find the reduction variable descriptor.
793 assert(Legal->getReductionVars()->count(RdxPhi) &&
794 "Unable to find the reduction variable");
795 LoopVectorizationLegality::ReductionDescriptor RdxDesc =
796 (*Legal->getReductionVars())[RdxPhi];
798 // We need to generate a reduction vector from the incoming scalar.
799 // To do so, we need to generate the 'identity' vector and overide
800 // one of the elements with the incoming scalar reduction. We need
801 // to do it in the vector-loop preheader.
802 Builder.SetInsertPoint(LoopBypassBlock->getTerminator());
804 // This is the vector-clone of the value that leaves the loop.
805 VectorParts &VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
806 Type *VecTy = VectorExit[0]->getType();
808 // Find the reduction identity variable. Zero for addition, or, xor,
809 // one for multiplication, -1 for And.
810 Constant *Identity = getUniformVector(getReductionIdentity(RdxDesc.Kind),
811 VecTy->getScalarType());
813 // This vector is the Identity vector where the first element is the
814 // incoming scalar reduction.
815 Value *VectorStart = Builder.CreateInsertElement(Identity,
816 RdxDesc.StartValue, Zero);
818 // Fix the vector-loop phi.
819 // We created the induction variable so we know that the
820 // preheader is the first entry.
821 BasicBlock *VecPreheader = Induction->getIncomingBlock(0);
823 // Reductions do not have to start at zero. They can start with
824 // any loop invariant values.
825 VectorParts &VecRdxPhi = WidenMap.get(RdxPhi);
826 BasicBlock *Latch = OrigLoop->getLoopLatch();
827 Value *LoopVal = RdxPhi->getIncomingValueForBlock(Latch);
828 VectorParts &Val = getVectorValue(LoopVal);
829 for (unsigned part = 0; part < UF; ++part) {
830 // Make sure to add the reduction stat value only to the
831 // first unroll part.
832 Value *StartVal = (part == 0) ? VectorStart : Identity;
833 cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal, VecPreheader);
834 cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part], LoopVectorBody);
837 // Before each round, move the insertion point right between
838 // the PHIs and the values we are going to write.
839 // This allows us to write both PHINodes and the extractelement
841 Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
843 VectorParts RdxParts;
844 for (unsigned part = 0; part < UF; ++part) {
845 // This PHINode contains the vectorized reduction variable, or
846 // the initial value vector, if we bypass the vector loop.
847 VectorParts &RdxExitVal = getVectorValue(RdxDesc.LoopExitInstr);
848 PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
849 Value *StartVal = (part == 0) ? VectorStart : Identity;
850 NewPhi->addIncoming(StartVal, LoopBypassBlock);
851 NewPhi->addIncoming(RdxExitVal[part], LoopVectorBody);
852 RdxParts.push_back(NewPhi);
855 // Reduce all of the unrolled parts into a single vector.
856 Value *ReducedPartRdx = RdxParts[0];
857 for (unsigned part = 1; part < UF; ++part) {
858 switch (RdxDesc.Kind) {
859 case LoopVectorizationLegality::IntegerAdd:
861 Builder.CreateAdd(RdxParts[part], ReducedPartRdx, "add.rdx");
863 case LoopVectorizationLegality::IntegerMult:
865 Builder.CreateMul(RdxParts[part], ReducedPartRdx, "mul.rdx");
867 case LoopVectorizationLegality::IntegerOr:
869 Builder.CreateOr(RdxParts[part], ReducedPartRdx, "or.rdx");
871 case LoopVectorizationLegality::IntegerAnd:
873 Builder.CreateAnd(RdxParts[part], ReducedPartRdx, "and.rdx");
875 case LoopVectorizationLegality::IntegerXor:
877 Builder.CreateXor(RdxParts[part], ReducedPartRdx, "xor.rdx");
880 llvm_unreachable("Unknown reduction operation");
885 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
886 // and vector ops, reducing the set of values being computed by half each
888 assert(isPowerOf2_32(VF) &&
889 "Reduction emission only supported for pow2 vectors!");
890 Value *TmpVec = ReducedPartRdx;
891 SmallVector<Constant*, 32> ShuffleMask(VF, 0);
892 for (unsigned i = VF; i != 1; i >>= 1) {
893 // Move the upper half of the vector to the lower half.
894 for (unsigned j = 0; j != i/2; ++j)
895 ShuffleMask[j] = Builder.getInt32(i/2 + j);
897 // Fill the rest of the mask with undef.
898 std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
899 UndefValue::get(Builder.getInt32Ty()));
902 Builder.CreateShuffleVector(TmpVec,
903 UndefValue::get(TmpVec->getType()),
904 ConstantVector::get(ShuffleMask),
907 // Emit the operation on the shuffled value.
908 switch (RdxDesc.Kind) {
909 case LoopVectorizationLegality::IntegerAdd:
910 TmpVec = Builder.CreateAdd(TmpVec, Shuf, "add.rdx");
912 case LoopVectorizationLegality::IntegerMult:
913 TmpVec = Builder.CreateMul(TmpVec, Shuf, "mul.rdx");
915 case LoopVectorizationLegality::IntegerOr:
916 TmpVec = Builder.CreateOr(TmpVec, Shuf, "or.rdx");
918 case LoopVectorizationLegality::IntegerAnd:
919 TmpVec = Builder.CreateAnd(TmpVec, Shuf, "and.rdx");
921 case LoopVectorizationLegality::IntegerXor:
922 TmpVec = Builder.CreateXor(TmpVec, Shuf, "xor.rdx");
925 llvm_unreachable("Unknown reduction operation");
929 // The result is in the first element of the vector.
930 Value *Scalar0 = Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
932 // Now, we need to fix the users of the reduction variable
933 // inside and outside of the scalar remainder loop.
934 // We know that the loop is in LCSSA form. We need to update the
935 // PHI nodes in the exit blocks.
936 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
937 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
938 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
939 if (!LCSSAPhi) continue;
941 // All PHINodes need to have a single entry edge, or two if
942 // we already fixed them.
943 assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
945 // We found our reduction value exit-PHI. Update it with the
946 // incoming bypass edge.
947 if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
948 // Add an edge coming from the bypass.
949 LCSSAPhi->addIncoming(Scalar0, LoopMiddleBlock);
952 }// end of the LCSSA phi scan.
954 // Fix the scalar loop reduction variable with the incoming reduction sum
955 // from the vector body and from the backedge value.
956 int IncomingEdgeBlockIdx =
957 (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
958 assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
959 // Pick the other block.
960 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
961 (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, Scalar0);
962 (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
963 }// end of for each redux variable.
965 // The Loop exit block may have single value PHI nodes where the incoming
966 // value is 'undef'. While vectorizing we only handled real values that
967 // were defined inside the loop. Here we handle the 'undef case'.
969 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
970 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
971 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
972 if (!LCSSAPhi) continue;
973 if (LCSSAPhi->getNumIncomingValues() == 1)
974 LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
979 InnerLoopVectorizer::VectorParts
980 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
981 assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
984 VectorParts SrcMask = createBlockInMask(Src);
986 // The terminator has to be a branch inst!
987 BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
988 assert(BI && "Unexpected terminator found");
990 if (BI->isConditional()) {
991 VectorParts EdgeMask = getVectorValue(BI->getCondition());
993 if (BI->getSuccessor(0) != Dst)
994 for (unsigned part = 0; part < UF; ++part)
995 EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
997 for (unsigned part = 0; part < UF; ++part)
998 EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
1005 InnerLoopVectorizer::VectorParts
1006 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
1007 assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
1009 // Loop incoming mask is all-one.
1010 if (OrigLoop->getHeader() == BB) {
1011 Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
1012 return getVectorValue(C);
1015 // This is the block mask. We OR all incoming edges, and with zero.
1016 Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
1017 VectorParts BlockMask = getVectorValue(Zero);
1020 for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
1021 VectorParts EM = createEdgeMask(*it, BB);
1022 for (unsigned part = 0; part < UF; ++part)
1023 BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
1030 InnerLoopVectorizer::vectorizeBlockInLoop(LoopVectorizationLegality *Legal,
1031 BasicBlock *BB, PhiVector *PV) {
1032 Constant *Zero = Builder.getInt32(0);
1034 // For each instruction in the old loop.
1035 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1036 VectorParts &Entry = WidenMap.get(it);
1037 switch (it->getOpcode()) {
1038 case Instruction::Br:
1039 // Nothing to do for PHIs and BR, since we already took care of the
1040 // loop control flow instructions.
1042 case Instruction::PHI:{
1043 PHINode* P = cast<PHINode>(it);
1044 // Handle reduction variables:
1045 if (Legal->getReductionVars()->count(P)) {
1046 for (unsigned part = 0; part < UF; ++part) {
1047 // This is phase one of vectorizing PHIs.
1048 Type *VecTy = VectorType::get(it->getType(), VF);
1049 Entry[part] = PHINode::Create(VecTy, 2, "vec.phi",
1050 LoopVectorBody-> getFirstInsertionPt());
1056 // Check for PHI nodes that are lowered to vector selects.
1057 if (P->getParent() != OrigLoop->getHeader()) {
1058 // We know that all PHIs in non header blocks are converted into
1059 // selects, so we don't have to worry about the insertion order and we
1060 // can just use the builder.
1062 // At this point we generate the predication tree. There may be
1063 // duplications since this is a simple recursive scan, but future
1064 // optimizations will clean it up.
1065 VectorParts Cond = createEdgeMask(P->getIncomingBlock(0),
1068 for (unsigned part = 0; part < UF; ++part) {
1069 VectorParts &In0 = getVectorValue(P->getIncomingValue(0));
1070 VectorParts &In1 = getVectorValue(P->getIncomingValue(1));
1071 Entry[part] = Builder.CreateSelect(Cond[part], In0[part], In1[part],
1077 // This PHINode must be an induction variable.
1078 // Make sure that we know about it.
1079 assert(Legal->getInductionVars()->count(P) &&
1080 "Not an induction variable");
1082 LoopVectorizationLegality::InductionInfo II =
1083 Legal->getInductionVars()->lookup(P);
1086 case LoopVectorizationLegality::NoInduction:
1087 llvm_unreachable("Unknown induction");
1088 case LoopVectorizationLegality::IntInduction: {
1089 assert(P == OldInduction && "Unexpected PHI");
1090 Value *Broadcasted = getBroadcastInstrs(Induction);
1091 // After broadcasting the induction variable we need to make the
1092 // vector consecutive by adding 0, 1, 2 ...
1093 for (unsigned part = 0; part < UF; ++part)
1094 Entry[part] = getConsecutiveVector(Broadcasted, VF * part, false);
1097 case LoopVectorizationLegality::ReverseIntInduction:
1098 case LoopVectorizationLegality::PtrInduction:
1099 // Handle reverse integer and pointer inductions.
1100 Value *StartIdx = 0;
1101 // If we have a single integer induction variable then use it.
1102 // Otherwise, start counting at zero.
1104 LoopVectorizationLegality::InductionInfo OldII =
1105 Legal->getInductionVars()->lookup(OldInduction);
1106 StartIdx = OldII.StartValue;
1108 StartIdx = ConstantInt::get(Induction->getType(), 0);
1110 // This is the normalized GEP that starts counting at zero.
1111 Value *NormalizedIdx = Builder.CreateSub(Induction, StartIdx,
1114 // Handle the reverse integer induction variable case.
1115 if (LoopVectorizationLegality::ReverseIntInduction == II.IK) {
1116 IntegerType *DstTy = cast<IntegerType>(II.StartValue->getType());
1117 Value *CNI = Builder.CreateSExtOrTrunc(NormalizedIdx, DstTy,
1119 Value *ReverseInd = Builder.CreateSub(II.StartValue, CNI,
1122 // This is a new value so do not hoist it out.
1123 Value *Broadcasted = getBroadcastInstrs(ReverseInd);
1124 // After broadcasting the induction variable we need to make the
1125 // vector consecutive by adding ... -3, -2, -1, 0.
1126 for (unsigned part = 0; part < UF; ++part)
1127 Entry[part] = getConsecutiveVector(Broadcasted, -VF * part, true);
1131 // Handle the pointer induction variable case.
1132 assert(P->getType()->isPointerTy() && "Unexpected type.");
1134 // This is the vector of results. Notice that we don't generate
1135 // vector geps because scalar geps result in better code.
1136 for (unsigned part = 0; part < UF; ++part) {
1137 Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
1138 for (unsigned int i = 0; i < VF; ++i) {
1139 Constant *Idx = ConstantInt::get(Induction->getType(),
1141 Value *GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx,
1143 Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
1145 VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
1146 Builder.getInt32(i),
1149 Entry[part] = VecVal;
1156 case Instruction::Add:
1157 case Instruction::FAdd:
1158 case Instruction::Sub:
1159 case Instruction::FSub:
1160 case Instruction::Mul:
1161 case Instruction::FMul:
1162 case Instruction::UDiv:
1163 case Instruction::SDiv:
1164 case Instruction::FDiv:
1165 case Instruction::URem:
1166 case Instruction::SRem:
1167 case Instruction::FRem:
1168 case Instruction::Shl:
1169 case Instruction::LShr:
1170 case Instruction::AShr:
1171 case Instruction::And:
1172 case Instruction::Or:
1173 case Instruction::Xor: {
1174 // Just widen binops.
1175 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
1176 VectorParts &A = getVectorValue(it->getOperand(0));
1177 VectorParts &B = getVectorValue(it->getOperand(1));
1179 // Use this vector value for all users of the original instruction.
1180 for (unsigned Part = 0; Part < UF; ++Part) {
1181 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
1183 // Update the NSW, NUW and Exact flags.
1184 BinaryOperator *VecOp = cast<BinaryOperator>(V);
1185 if (isa<OverflowingBinaryOperator>(BinOp)) {
1186 VecOp->setHasNoSignedWrap(BinOp->hasNoSignedWrap());
1187 VecOp->setHasNoUnsignedWrap(BinOp->hasNoUnsignedWrap());
1189 if (isa<PossiblyExactOperator>(VecOp))
1190 VecOp->setIsExact(BinOp->isExact());
1196 case Instruction::Select: {
1198 // If the selector is loop invariant we can create a select
1199 // instruction with a scalar condition. Otherwise, use vector-select.
1200 bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)),
1203 // The condition can be loop invariant but still defined inside the
1204 // loop. This means that we can't just use the original 'cond' value.
1205 // We have to take the 'vectorized' value and pick the first lane.
1206 // Instcombine will make this a no-op.
1207 VectorParts &Cond = getVectorValue(it->getOperand(0));
1208 VectorParts &Op0 = getVectorValue(it->getOperand(1));
1209 VectorParts &Op1 = getVectorValue(it->getOperand(2));
1210 Value *ScalarCond = Builder.CreateExtractElement(Cond[0],
1211 Builder.getInt32(0));
1212 for (unsigned Part = 0; Part < UF; ++Part) {
1213 Entry[Part] = Builder.CreateSelect(
1214 InvariantCond ? ScalarCond : Cond[Part],
1221 case Instruction::ICmp:
1222 case Instruction::FCmp: {
1223 // Widen compares. Generate vector compares.
1224 bool FCmp = (it->getOpcode() == Instruction::FCmp);
1225 CmpInst *Cmp = dyn_cast<CmpInst>(it);
1226 VectorParts &A = getVectorValue(it->getOperand(0));
1227 VectorParts &B = getVectorValue(it->getOperand(1));
1228 for (unsigned Part = 0; Part < UF; ++Part) {
1231 C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
1233 C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
1239 case Instruction::Store: {
1240 // Attempt to issue a wide store.
1241 StoreInst *SI = dyn_cast<StoreInst>(it);
1242 Type *StTy = VectorType::get(SI->getValueOperand()->getType(), VF);
1243 Value *Ptr = SI->getPointerOperand();
1244 unsigned Alignment = SI->getAlignment();
1246 assert(!Legal->isUniform(Ptr) &&
1247 "We do not allow storing to uniform addresses");
1250 int Stride = Legal->isConsecutivePtr(Ptr);
1251 bool Reverse = Stride < 0;
1253 scalarizeInstruction(it);
1257 // Handle consecutive stores.
1259 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1261 // The last index does not have to be the induction. It can be
1262 // consecutive and be a function of the index. For example A[I+1];
1263 unsigned NumOperands = Gep->getNumOperands();
1265 Value *LastGepOperand = Gep->getOperand(NumOperands - 1);
1266 VectorParts &GEPParts = getVectorValue(LastGepOperand);
1267 Value *LastIndex = GEPParts[0];
1268 LastIndex = Builder.CreateExtractElement(LastIndex, Zero);
1270 // Create the new GEP with the new induction variable.
1271 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1272 Gep2->setOperand(NumOperands - 1, LastIndex);
1273 Ptr = Builder.Insert(Gep2);
1275 // Use the induction element ptr.
1276 assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1277 VectorParts &PtrVal = getVectorValue(Ptr);
1278 Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
1281 VectorParts &StoredVal = getVectorValue(SI->getValueOperand());
1282 for (unsigned Part = 0; Part < UF; ++Part) {
1283 // Calculate the pointer for the specific unroll-part.
1284 Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1287 // If we store to reverse consecutive memory locations then we need
1288 // to reverse the order of elements in the stored value.
1289 StoredVal[Part] = reverseVector(StoredVal[Part]);
1290 // If the address is consecutive but reversed, then the
1291 // wide store needs to start at the last vector element.
1292 PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1293 PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1296 Value *VecPtr = Builder.CreateBitCast(PartPtr, StTy->getPointerTo());
1297 Builder.CreateStore(StoredVal[Part], VecPtr)->setAlignment(Alignment);
1301 case Instruction::Load: {
1302 // Attempt to issue a wide load.
1303 LoadInst *LI = dyn_cast<LoadInst>(it);
1304 Type *RetTy = VectorType::get(LI->getType(), VF);
1305 Value *Ptr = LI->getPointerOperand();
1306 unsigned Alignment = LI->getAlignment();
1308 // If the pointer is loop invariant or if it is non consecutive,
1309 // scalarize the load.
1310 int Stride = Legal->isConsecutivePtr(Ptr);
1311 bool Reverse = Stride < 0;
1312 if (Legal->isUniform(Ptr) || Stride == 0) {
1313 scalarizeInstruction(it);
1317 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1319 // The last index does not have to be the induction. It can be
1320 // consecutive and be a function of the index. For example A[I+1];
1321 unsigned NumOperands = Gep->getNumOperands();
1323 Value *LastGepOperand = Gep->getOperand(NumOperands - 1);
1324 VectorParts &GEPParts = getVectorValue(LastGepOperand);
1325 Value *LastIndex = GEPParts[0];
1326 LastIndex = Builder.CreateExtractElement(LastIndex, Zero);
1328 // Create the new GEP with the new induction variable.
1329 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1330 Gep2->setOperand(NumOperands - 1, LastIndex);
1331 Ptr = Builder.Insert(Gep2);
1333 // Use the induction element ptr.
1334 assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1335 VectorParts &PtrVal = getVectorValue(Ptr);
1336 Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
1339 for (unsigned Part = 0; Part < UF; ++Part) {
1340 // Calculate the pointer for the specific unroll-part.
1341 Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1344 // If the address is consecutive but reversed, then the
1345 // wide store needs to start at the last vector element.
1346 PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1347 PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1350 Value *VecPtr = Builder.CreateBitCast(PartPtr, RetTy->getPointerTo());
1351 Value *LI = Builder.CreateLoad(VecPtr, "wide.load");
1352 cast<LoadInst>(LI)->setAlignment(Alignment);
1353 Entry[Part] = Reverse ? reverseVector(LI) : LI;
1357 case Instruction::ZExt:
1358 case Instruction::SExt:
1359 case Instruction::FPToUI:
1360 case Instruction::FPToSI:
1361 case Instruction::FPExt:
1362 case Instruction::PtrToInt:
1363 case Instruction::IntToPtr:
1364 case Instruction::SIToFP:
1365 case Instruction::UIToFP:
1366 case Instruction::Trunc:
1367 case Instruction::FPTrunc:
1368 case Instruction::BitCast: {
1369 CastInst *CI = dyn_cast<CastInst>(it);
1370 /// Optimize the special case where the source is the induction
1371 /// variable. Notice that we can only optimize the 'trunc' case
1372 /// because: a. FP conversions lose precision, b. sext/zext may wrap,
1373 /// c. other casts depend on pointer size.
1374 if (CI->getOperand(0) == OldInduction &&
1375 it->getOpcode() == Instruction::Trunc) {
1376 Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
1378 Value *Broadcasted = getBroadcastInstrs(ScalarCast);
1379 for (unsigned Part = 0; Part < UF; ++Part)
1380 Entry[Part] = getConsecutiveVector(Broadcasted, VF * Part, false);
1383 /// Vectorize casts.
1384 Type *DestTy = VectorType::get(CI->getType()->getScalarType(), VF);
1386 VectorParts &A = getVectorValue(it->getOperand(0));
1387 for (unsigned Part = 0; Part < UF; ++Part)
1388 Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
1392 case Instruction::Call: {
1393 assert(isTriviallyVectorizableIntrinsic(it));
1394 Module *M = BB->getParent()->getParent();
1395 IntrinsicInst *II = cast<IntrinsicInst>(it);
1396 Intrinsic::ID ID = II->getIntrinsicID();
1397 for (unsigned Part = 0; Part < UF; ++Part) {
1398 SmallVector<Value*, 4> Args;
1399 for (unsigned i = 0, ie = II->getNumArgOperands(); i != ie; ++i) {
1400 VectorParts &Arg = getVectorValue(II->getArgOperand(i));
1401 Args.push_back(Arg[Part]);
1403 Type *Tys[] = { VectorType::get(II->getType()->getScalarType(), VF) };
1404 Function *F = Intrinsic::getDeclaration(M, ID, Tys);
1405 Entry[Part] = Builder.CreateCall(F, Args);
1411 // All other instructions are unsupported. Scalarize them.
1412 scalarizeInstruction(it);
1415 }// end of for_each instr.
1418 void InnerLoopVectorizer::updateAnalysis() {
1419 // Forget the original basic block.
1420 SE->forgetLoop(OrigLoop);
1422 // Update the dominator tree information.
1423 assert(DT->properlyDominates(LoopBypassBlock, LoopExitBlock) &&
1424 "Entry does not dominate exit.");
1426 DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlock);
1427 DT->addNewBlock(LoopVectorBody, LoopVectorPreHeader);
1428 DT->addNewBlock(LoopMiddleBlock, LoopBypassBlock);
1429 DT->addNewBlock(LoopScalarPreHeader, LoopMiddleBlock);
1430 DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
1431 DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
1433 DEBUG(DT->verifyAnalysis());
1436 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
1437 if (!EnableIfConversion)
1440 assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
1441 std::vector<BasicBlock*> &LoopBlocks = TheLoop->getBlocksVector();
1443 // Collect the blocks that need predication.
1444 for (unsigned i = 0, e = LoopBlocks.size(); i < e; ++i) {
1445 BasicBlock *BB = LoopBlocks[i];
1447 // We don't support switch statements inside loops.
1448 if (!isa<BranchInst>(BB->getTerminator()))
1451 // We must have at most two predecessors because we need to convert
1452 // all PHIs to selects.
1453 unsigned Preds = std::distance(pred_begin(BB), pred_end(BB));
1457 // We must be able to predicate all blocks that need to be predicated.
1458 if (blockNeedsPredication(BB) && !blockCanBePredicated(BB))
1462 // We can if-convert this loop.
1466 bool LoopVectorizationLegality::canVectorize() {
1467 assert(TheLoop->getLoopPreheader() && "No preheader!!");
1469 // We can only vectorize innermost loops.
1470 if (TheLoop->getSubLoopsVector().size())
1473 // We must have a single backedge.
1474 if (TheLoop->getNumBackEdges() != 1)
1477 // We must have a single exiting block.
1478 if (!TheLoop->getExitingBlock())
1481 unsigned NumBlocks = TheLoop->getNumBlocks();
1483 // Check if we can if-convert non single-bb loops.
1484 if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
1485 DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
1489 // We need to have a loop header.
1490 BasicBlock *Latch = TheLoop->getLoopLatch();
1491 DEBUG(dbgs() << "LV: Found a loop: " <<
1492 TheLoop->getHeader()->getName() << "\n");
1494 // ScalarEvolution needs to be able to find the exit count.
1495 const SCEV *ExitCount = SE->getExitCount(TheLoop, Latch);
1496 if (ExitCount == SE->getCouldNotCompute()) {
1497 DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
1501 // Do not loop-vectorize loops with a tiny trip count.
1502 unsigned TC = SE->getSmallConstantTripCount(TheLoop, Latch);
1503 if (TC > 0u && TC < TinyTripCountThreshold) {
1504 DEBUG(dbgs() << "LV: Found a loop with a very small trip count. " <<
1505 "This loop is not worth vectorizing.\n");
1509 // Check if we can vectorize the instructions and CFG in this loop.
1510 if (!canVectorizeInstrs()) {
1511 DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
1515 // Go over each instruction and look at memory deps.
1516 if (!canVectorizeMemory()) {
1517 DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
1521 // Collect all of the variables that remain uniform after vectorization.
1522 collectLoopUniforms();
1524 DEBUG(dbgs() << "LV: We can vectorize this loop" <<
1525 (PtrRtCheck.Need ? " (with a runtime bound check)" : "")
1528 // Okay! We can vectorize. At this point we don't have any other mem analysis
1529 // which may limit our maximum vectorization factor, so just return true with
1534 bool LoopVectorizationLegality::canVectorizeInstrs() {
1535 BasicBlock *PreHeader = TheLoop->getLoopPreheader();
1536 BasicBlock *Header = TheLoop->getHeader();
1538 // For each block in the loop.
1539 for (Loop::block_iterator bb = TheLoop->block_begin(),
1540 be = TheLoop->block_end(); bb != be; ++bb) {
1542 // Scan the instructions in the block and look for hazards.
1543 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
1546 if (PHINode *Phi = dyn_cast<PHINode>(it)) {
1547 // This should not happen because the loop should be normalized.
1548 if (Phi->getNumIncomingValues() != 2) {
1549 DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
1553 // Check that this PHI type is allowed.
1554 if (!Phi->getType()->isIntegerTy() &&
1555 !Phi->getType()->isPointerTy()) {
1556 DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
1560 // If this PHINode is not in the header block, then we know that we
1561 // can convert it to select during if-conversion. No need to check if
1562 // the PHIs in this block are induction or reduction variables.
1566 // This is the value coming from the preheader.
1567 Value *StartValue = Phi->getIncomingValueForBlock(PreHeader);
1568 // Check if this is an induction variable.
1569 InductionKind IK = isInductionVariable(Phi);
1571 if (NoInduction != IK) {
1572 // Int inductions are special because we only allow one IV.
1573 if (IK == IntInduction) {
1575 DEBUG(dbgs() << "LV: Found too many inductions."<< *Phi <<"\n");
1581 DEBUG(dbgs() << "LV: Found an induction variable.\n");
1582 Inductions[Phi] = InductionInfo(StartValue, IK);
1586 if (AddReductionVar(Phi, IntegerAdd)) {
1587 DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
1590 if (AddReductionVar(Phi, IntegerMult)) {
1591 DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n");
1594 if (AddReductionVar(Phi, IntegerOr)) {
1595 DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n");
1598 if (AddReductionVar(Phi, IntegerAnd)) {
1599 DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n");
1602 if (AddReductionVar(Phi, IntegerXor)) {
1603 DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n");
1607 DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
1609 }// end of PHI handling
1611 // We still don't handle functions.
1612 CallInst *CI = dyn_cast<CallInst>(it);
1613 if (CI && !isTriviallyVectorizableIntrinsic(it)) {
1614 DEBUG(dbgs() << "LV: Found a call site.\n");
1618 // Check that the instruction return type is vectorizable.
1619 if (!VectorType::isValidElementType(it->getType()) &&
1620 !it->getType()->isVoidTy()) {
1621 DEBUG(dbgs() << "LV: Found unvectorizable type." << "\n");
1625 // Check that the stored type is vectorizable.
1626 if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
1627 Type *T = ST->getValueOperand()->getType();
1628 if (!VectorType::isValidElementType(T))
1632 // Reduction instructions are allowed to have exit users.
1633 // All other instructions must not have external users.
1634 if (!AllowedExit.count(it))
1635 //Check that all of the users of the loop are inside the BB.
1636 for (Value::use_iterator I = it->use_begin(), E = it->use_end();
1638 Instruction *U = cast<Instruction>(*I);
1639 // This user may be a reduction exit value.
1640 if (!TheLoop->contains(U)) {
1641 DEBUG(dbgs() << "LV: Found an outside user for : "<< *U << "\n");
1650 DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
1651 assert(getInductionVars()->size() && "No induction variables");
1657 void LoopVectorizationLegality::collectLoopUniforms() {
1658 // We now know that the loop is vectorizable!
1659 // Collect variables that will remain uniform after vectorization.
1660 std::vector<Value*> Worklist;
1661 BasicBlock *Latch = TheLoop->getLoopLatch();
1663 // Start with the conditional branch and walk up the block.
1664 Worklist.push_back(Latch->getTerminator()->getOperand(0));
1666 while (Worklist.size()) {
1667 Instruction *I = dyn_cast<Instruction>(Worklist.back());
1668 Worklist.pop_back();
1670 // Look at instructions inside this loop.
1671 // Stop when reaching PHI nodes.
1672 // TODO: we need to follow values all over the loop, not only in this block.
1673 if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
1676 // This is a known uniform.
1679 // Insert all operands.
1680 for (int i = 0, Op = I->getNumOperands(); i < Op; ++i) {
1681 Worklist.push_back(I->getOperand(i));
1686 bool LoopVectorizationLegality::canVectorizeMemory() {
1687 typedef SmallVector<Value*, 16> ValueVector;
1688 typedef SmallPtrSet<Value*, 16> ValueSet;
1689 // Holds the Load and Store *instructions*.
1692 PtrRtCheck.Pointers.clear();
1693 PtrRtCheck.Need = false;
1696 for (Loop::block_iterator bb = TheLoop->block_begin(),
1697 be = TheLoop->block_end(); bb != be; ++bb) {
1699 // Scan the BB and collect legal loads and stores.
1700 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
1703 // If this is a load, save it. If this instruction can read from memory
1704 // but is not a load, then we quit. Notice that we don't handle function
1705 // calls that read or write.
1706 if (it->mayReadFromMemory()) {
1707 LoadInst *Ld = dyn_cast<LoadInst>(it);
1708 if (!Ld) return false;
1709 if (!Ld->isSimple()) {
1710 DEBUG(dbgs() << "LV: Found a non-simple load.\n");
1713 Loads.push_back(Ld);
1717 // Save 'store' instructions. Abort if other instructions write to memory.
1718 if (it->mayWriteToMemory()) {
1719 StoreInst *St = dyn_cast<StoreInst>(it);
1720 if (!St) return false;
1721 if (!St->isSimple()) {
1722 DEBUG(dbgs() << "LV: Found a non-simple store.\n");
1725 Stores.push_back(St);
1730 // Now we have two lists that hold the loads and the stores.
1731 // Next, we find the pointers that they use.
1733 // Check if we see any stores. If there are no stores, then we don't
1734 // care if the pointers are *restrict*.
1735 if (!Stores.size()) {
1736 DEBUG(dbgs() << "LV: Found a read-only loop!\n");
1740 // Holds the read and read-write *pointers* that we find.
1742 ValueVector ReadWrites;
1744 // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
1745 // multiple times on the same object. If the ptr is accessed twice, once
1746 // for read and once for write, it will only appear once (on the write
1747 // list). This is okay, since we are going to check for conflicts between
1748 // writes and between reads and writes, but not between reads and reads.
1751 ValueVector::iterator I, IE;
1752 for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
1753 StoreInst *ST = cast<StoreInst>(*I);
1754 Value* Ptr = ST->getPointerOperand();
1756 if (isUniform(Ptr)) {
1757 DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
1761 // If we did *not* see this pointer before, insert it to
1762 // the read-write list. At this phase it is only a 'write' list.
1763 if (Seen.insert(Ptr))
1764 ReadWrites.push_back(Ptr);
1767 for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
1768 LoadInst *LD = cast<LoadInst>(*I);
1769 Value* Ptr = LD->getPointerOperand();
1770 // If we did *not* see this pointer before, insert it to the
1771 // read list. If we *did* see it before, then it is already in
1772 // the read-write list. This allows us to vectorize expressions
1773 // such as A[i] += x; Because the address of A[i] is a read-write
1774 // pointer. This only works if the index of A[i] is consecutive.
1775 // If the address of i is unknown (for example A[B[i]]) then we may
1776 // read a few words, modify, and write a few words, and some of the
1777 // words may be written to the same address.
1778 if (Seen.insert(Ptr) || 0 == isConsecutivePtr(Ptr))
1779 Reads.push_back(Ptr);
1782 // If we write (or read-write) to a single destination and there are no
1783 // other reads in this loop then is it safe to vectorize.
1784 if (ReadWrites.size() == 1 && Reads.size() == 0) {
1785 DEBUG(dbgs() << "LV: Found a write-only loop!\n");
1789 // Find pointers with computable bounds. We are going to use this information
1790 // to place a runtime bound check.
1791 bool CanDoRT = true;
1792 for (I = ReadWrites.begin(), IE = ReadWrites.end(); I != IE; ++I)
1793 if (hasComputableBounds(*I)) {
1794 PtrRtCheck.insert(SE, TheLoop, *I);
1795 DEBUG(dbgs() << "LV: Found a runtime check ptr:" << **I <<"\n");
1800 for (I = Reads.begin(), IE = Reads.end(); I != IE; ++I)
1801 if (hasComputableBounds(*I)) {
1802 PtrRtCheck.insert(SE, TheLoop, *I);
1803 DEBUG(dbgs() << "LV: Found a runtime check ptr:" << **I <<"\n");
1809 // Check that we did not collect too many pointers or found a
1810 // unsizeable pointer.
1811 if (!CanDoRT || PtrRtCheck.Pointers.size() > RuntimeMemoryCheckThreshold) {
1817 DEBUG(dbgs() << "LV: We can perform a memory runtime check if needed.\n");
1820 bool NeedRTCheck = false;
1822 // Now that the pointers are in two lists (Reads and ReadWrites), we
1823 // can check that there are no conflicts between each of the writes and
1824 // between the writes to the reads.
1825 ValueSet WriteObjects;
1826 ValueVector TempObjects;
1828 // Check that the read-writes do not conflict with other read-write
1830 bool AllWritesIdentified = true;
1831 for (I = ReadWrites.begin(), IE = ReadWrites.end(); I != IE; ++I) {
1832 GetUnderlyingObjects(*I, TempObjects, DL);
1833 for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end();
1835 if (!isIdentifiedObject(*it)) {
1836 DEBUG(dbgs() << "LV: Found an unidentified write ptr:"<< **it <<"\n");
1838 AllWritesIdentified = false;
1840 if (!WriteObjects.insert(*it)) {
1841 DEBUG(dbgs() << "LV: Found a possible write-write reorder:"
1846 TempObjects.clear();
1849 /// Check that the reads don't conflict with the read-writes.
1850 for (I = Reads.begin(), IE = Reads.end(); I != IE; ++I) {
1851 GetUnderlyingObjects(*I, TempObjects, DL);
1852 for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end();
1854 // If all of the writes are identified then we don't care if the read
1855 // pointer is identified or not.
1856 if (!AllWritesIdentified && !isIdentifiedObject(*it)) {
1857 DEBUG(dbgs() << "LV: Found an unidentified read ptr:"<< **it <<"\n");
1860 if (WriteObjects.count(*it)) {
1861 DEBUG(dbgs() << "LV: Found a possible read/write reorder:"
1866 TempObjects.clear();
1869 PtrRtCheck.Need = NeedRTCheck;
1870 if (NeedRTCheck && !CanDoRT) {
1871 DEBUG(dbgs() << "LV: We can't vectorize because we can't find " <<
1872 "the array bounds.\n");
1877 DEBUG(dbgs() << "LV: We "<< (NeedRTCheck ? "" : "don't") <<
1878 " need a runtime memory check.\n");
1882 bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi,
1883 ReductionKind Kind) {
1884 if (Phi->getNumIncomingValues() != 2)
1887 // Reduction variables are only found in the loop header block.
1888 if (Phi->getParent() != TheLoop->getHeader())
1891 // Obtain the reduction start value from the value that comes from the loop
1893 Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
1895 // ExitInstruction is the single value which is used outside the loop.
1896 // We only allow for a single reduction value to be used outside the loop.
1897 // This includes users of the reduction, variables (which form a cycle
1898 // which ends in the phi node).
1899 Instruction *ExitInstruction = 0;
1901 // Iter is our iterator. We start with the PHI node and scan for all of the
1902 // users of this instruction. All users must be instructions that can be
1903 // used as reduction variables (such as ADD). We may have a single
1904 // out-of-block user. The cycle must end with the original PHI.
1905 Instruction *Iter = Phi;
1907 // If the instruction has no users then this is a broken
1908 // chain and can't be a reduction variable.
1909 if (Iter->use_empty())
1912 // Any reduction instr must be of one of the allowed kinds.
1913 if (!isReductionInstr(Iter, Kind))
1916 // Did we find a user inside this loop already ?
1917 bool FoundInBlockUser = false;
1918 // Did we reach the initial PHI node already ?
1919 bool FoundStartPHI = false;
1921 // For each of the *users* of iter.
1922 for (Value::use_iterator it = Iter->use_begin(), e = Iter->use_end();
1924 Instruction *U = cast<Instruction>(*it);
1925 // We already know that the PHI is a user.
1927 FoundStartPHI = true;
1931 // Check if we found the exit user.
1932 BasicBlock *Parent = U->getParent();
1933 if (!TheLoop->contains(Parent)) {
1934 // Exit if you find multiple outside users.
1935 if (ExitInstruction != 0)
1937 ExitInstruction = Iter;
1940 // We allow in-loop PHINodes which are not the original reduction PHI
1941 // node. If this PHI is the only user of Iter (happens in IF w/ no ELSE
1942 // structure) then don't skip this PHI.
1943 if (isa<PHINode>(Iter) && isa<PHINode>(U) &&
1944 U->getParent() != TheLoop->getHeader() &&
1945 TheLoop->contains(U) &&
1946 Iter->getNumUses() > 1)
1949 // We can't have multiple inside users.
1950 if (FoundInBlockUser)
1952 FoundInBlockUser = true;
1956 // We found a reduction var if we have reached the original
1957 // phi node and we only have a single instruction with out-of-loop
1959 if (FoundStartPHI && ExitInstruction) {
1960 // This instruction is allowed to have out-of-loop users.
1961 AllowedExit.insert(ExitInstruction);
1963 // Save the description of this reduction variable.
1964 ReductionDescriptor RD(RdxStart, ExitInstruction, Kind);
1965 Reductions[Phi] = RD;
1969 // If we've reached the start PHI but did not find an outside user then
1970 // this is dead code. Abort.
1977 LoopVectorizationLegality::isReductionInstr(Instruction *I,
1978 ReductionKind Kind) {
1979 switch (I->getOpcode()) {
1982 case Instruction::PHI:
1985 case Instruction::Add:
1986 case Instruction::Sub:
1987 return Kind == IntegerAdd;
1988 case Instruction::Mul:
1989 return Kind == IntegerMult;
1990 case Instruction::And:
1991 return Kind == IntegerAnd;
1992 case Instruction::Or:
1993 return Kind == IntegerOr;
1994 case Instruction::Xor:
1995 return Kind == IntegerXor;
1999 LoopVectorizationLegality::InductionKind
2000 LoopVectorizationLegality::isInductionVariable(PHINode *Phi) {
2001 Type *PhiTy = Phi->getType();
2002 // We only handle integer and pointer inductions variables.
2003 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
2006 // Check that the PHI is consecutive and starts at zero.
2007 const SCEV *PhiScev = SE->getSCEV(Phi);
2008 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
2010 DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
2013 const SCEV *Step = AR->getStepRecurrence(*SE);
2015 // Integer inductions need to have a stride of one.
2016 if (PhiTy->isIntegerTy()) {
2018 return IntInduction;
2019 if (Step->isAllOnesValue())
2020 return ReverseIntInduction;
2024 // Calculate the pointer stride and check if it is consecutive.
2025 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
2029 assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
2030 uint64_t Size = DL->getTypeAllocSize(PhiTy->getPointerElementType());
2031 if (C->getValue()->equalsInt(Size))
2032 return PtrInduction;
2037 bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
2038 Value *In0 = const_cast<Value*>(V);
2039 PHINode *PN = dyn_cast_or_null<PHINode>(In0);
2043 return Inductions.count(PN);
2046 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) {
2047 assert(TheLoop->contains(BB) && "Unknown block used");
2049 // Blocks that do not dominate the latch need predication.
2050 BasicBlock* Latch = TheLoop->getLoopLatch();
2051 return !DT->dominates(BB, Latch);
2054 bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB) {
2055 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2056 // We don't predicate loads/stores at the moment.
2057 if (it->mayReadFromMemory() || it->mayWriteToMemory() || it->mayThrow())
2060 // The instructions below can trap.
2061 switch (it->getOpcode()) {
2063 case Instruction::UDiv:
2064 case Instruction::SDiv:
2065 case Instruction::URem:
2066 case Instruction::SRem:
2074 bool LoopVectorizationLegality::hasComputableBounds(Value *Ptr) {
2075 const SCEV *PhiScev = SE->getSCEV(Ptr);
2076 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
2080 return AR->isAffine();
2084 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize,
2086 if (OptForSize && Legal->getRuntimePointerCheck()->Need) {
2087 DEBUG(dbgs() << "LV: Aborting. Runtime ptr check is required in Os.\n");
2091 // Find the trip count.
2092 unsigned TC = SE->getSmallConstantTripCount(TheLoop, TheLoop->getLoopLatch());
2093 DEBUG(dbgs() << "LV: Found trip count:"<<TC<<"\n");
2095 unsigned VF = MaxVectorSize;
2097 // If we optimize the program for size, avoid creating the tail loop.
2099 // If we are unable to calculate the trip count then don't try to vectorize.
2101 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
2105 // Find the maximum SIMD width that can fit within the trip count.
2106 VF = TC % MaxVectorSize;
2111 // If the trip count that we found modulo the vectorization factor is not
2112 // zero then we require a tail.
2114 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
2120 assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
2121 DEBUG(dbgs() << "LV: Using user VF "<<UserVF<<".\n");
2127 DEBUG(dbgs() << "LV: No vector target information. Not vectorizing. \n");
2131 float Cost = expectedCost(1);
2133 DEBUG(dbgs() << "LV: Scalar loop costs: "<< (int)Cost << ".\n");
2134 for (unsigned i=2; i <= VF; i*=2) {
2135 // Notice that the vector loop needs to be executed less times, so
2136 // we need to divide the cost of the vector loops by the width of
2137 // the vector elements.
2138 float VectorCost = expectedCost(i) / (float)i;
2139 DEBUG(dbgs() << "LV: Vector loop of width "<< i << " costs: " <<
2140 (int)VectorCost << ".\n");
2141 if (VectorCost < Cost) {
2147 DEBUG(dbgs() << "LV: Selecting VF = : "<< Width << ".\n");
2151 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
2155 for (Loop::block_iterator bb = TheLoop->block_begin(),
2156 be = TheLoop->block_end(); bb != be; ++bb) {
2157 unsigned BlockCost = 0;
2158 BasicBlock *BB = *bb;
2160 // For each instruction in the old loop.
2161 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2162 unsigned C = getInstructionCost(it, VF);
2164 DEBUG(dbgs() << "LV: Found an estimated cost of "<< C <<" for VF " <<
2165 VF << " For instruction: "<< *it << "\n");
2168 // We assume that if-converted blocks have a 50% chance of being executed.
2169 // When the code is scalar then some of the blocks are avoided due to CF.
2170 // When the code is vectorized we execute all code paths.
2171 if (Legal->blockNeedsPredication(*bb) && VF == 1)
2181 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
2182 assert(VTTI && "Invalid vector target transformation info");
2184 // If we know that this instruction will remain uniform, check the cost of
2185 // the scalar version.
2186 if (Legal->isUniformAfterVectorization(I))
2189 Type *RetTy = I->getType();
2190 Type *VectorTy = ToVectorTy(RetTy, VF);
2192 // TODO: We need to estimate the cost of intrinsic calls.
2193 switch (I->getOpcode()) {
2194 case Instruction::GetElementPtr:
2195 // We mark this instruction as zero-cost because scalar GEPs are usually
2196 // lowered to the intruction addressing mode. At the moment we don't
2197 // generate vector geps.
2199 case Instruction::Br: {
2200 return VTTI->getCFInstrCost(I->getOpcode());
2202 case Instruction::PHI:
2203 //TODO: IF-converted IFs become selects.
2205 case Instruction::Add:
2206 case Instruction::FAdd:
2207 case Instruction::Sub:
2208 case Instruction::FSub:
2209 case Instruction::Mul:
2210 case Instruction::FMul:
2211 case Instruction::UDiv:
2212 case Instruction::SDiv:
2213 case Instruction::FDiv:
2214 case Instruction::URem:
2215 case Instruction::SRem:
2216 case Instruction::FRem:
2217 case Instruction::Shl:
2218 case Instruction::LShr:
2219 case Instruction::AShr:
2220 case Instruction::And:
2221 case Instruction::Or:
2222 case Instruction::Xor:
2223 return VTTI->getArithmeticInstrCost(I->getOpcode(), VectorTy);
2224 case Instruction::Select: {
2225 SelectInst *SI = cast<SelectInst>(I);
2226 const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
2227 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
2228 Type *CondTy = SI->getCondition()->getType();
2230 CondTy = VectorType::get(CondTy, VF);
2232 return VTTI->getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
2234 case Instruction::ICmp:
2235 case Instruction::FCmp: {
2236 Type *ValTy = I->getOperand(0)->getType();
2237 VectorTy = ToVectorTy(ValTy, VF);
2238 return VTTI->getCmpSelInstrCost(I->getOpcode(), VectorTy);
2240 case Instruction::Store: {
2241 StoreInst *SI = cast<StoreInst>(I);
2242 Type *ValTy = SI->getValueOperand()->getType();
2243 VectorTy = ToVectorTy(ValTy, VF);
2246 return VTTI->getMemoryOpCost(I->getOpcode(), VectorTy,
2248 SI->getPointerAddressSpace());
2250 // Scalarized stores.
2251 int Stride = Legal->isConsecutivePtr(SI->getPointerOperand());
2252 bool Reverse = Stride < 0;
2256 // The cost of extracting from the value vector and pointer vector.
2257 Type *PtrTy = ToVectorTy(I->getOperand(0)->getType(), VF);
2258 for (unsigned i = 0; i < VF; ++i) {
2259 Cost += VTTI->getVectorInstrCost(Instruction::ExtractElement,
2261 Cost += VTTI->getVectorInstrCost(Instruction::ExtractElement,
2265 // The cost of the scalar stores.
2266 Cost += VF * VTTI->getMemoryOpCost(I->getOpcode(),
2267 ValTy->getScalarType(),
2269 SI->getPointerAddressSpace());
2274 unsigned Cost = VTTI->getMemoryOpCost(I->getOpcode(), VectorTy,
2276 SI->getPointerAddressSpace());
2278 Cost += VTTI->getShuffleCost(VectorTargetTransformInfo::Reverse,
2282 case Instruction::Load: {
2283 LoadInst *LI = cast<LoadInst>(I);
2286 return VTTI->getMemoryOpCost(I->getOpcode(), VectorTy,
2288 LI->getPointerAddressSpace());
2290 // Scalarized loads.
2291 int Stride = Legal->isConsecutivePtr(LI->getPointerOperand());
2292 bool Reverse = Stride < 0;
2295 Type *PtrTy = ToVectorTy(I->getOperand(0)->getType(), VF);
2297 // The cost of extracting from the pointer vector.
2298 for (unsigned i = 0; i < VF; ++i)
2299 Cost += VTTI->getVectorInstrCost(Instruction::ExtractElement,
2302 // The cost of inserting data to the result vector.
2303 for (unsigned i = 0; i < VF; ++i)
2304 Cost += VTTI->getVectorInstrCost(Instruction::InsertElement,
2307 // The cost of the scalar stores.
2308 Cost += VF * VTTI->getMemoryOpCost(I->getOpcode(),
2309 RetTy->getScalarType(),
2311 LI->getPointerAddressSpace());
2316 unsigned Cost = VTTI->getMemoryOpCost(I->getOpcode(), VectorTy,
2318 LI->getPointerAddressSpace());
2320 Cost += VTTI->getShuffleCost(VectorTargetTransformInfo::Reverse,
2324 case Instruction::ZExt:
2325 case Instruction::SExt:
2326 case Instruction::FPToUI:
2327 case Instruction::FPToSI:
2328 case Instruction::FPExt:
2329 case Instruction::PtrToInt:
2330 case Instruction::IntToPtr:
2331 case Instruction::SIToFP:
2332 case Instruction::UIToFP:
2333 case Instruction::Trunc:
2334 case Instruction::FPTrunc:
2335 case Instruction::BitCast: {
2336 // We optimize the truncation of induction variable.
2337 // The cost of these is the same as the scalar operation.
2338 if (I->getOpcode() == Instruction::Trunc &&
2339 Legal->isInductionVariable(I->getOperand(0)))
2340 return VTTI->getCastInstrCost(I->getOpcode(), I->getType(),
2341 I->getOperand(0)->getType());
2343 Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
2344 return VTTI->getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
2346 case Instruction::Call: {
2347 assert(isTriviallyVectorizableIntrinsic(I));
2348 IntrinsicInst *II = cast<IntrinsicInst>(I);
2349 Type *RetTy = ToVectorTy(II->getType(), VF);
2350 SmallVector<Type*, 4> Tys;
2351 for (unsigned i = 0, ie = II->getNumArgOperands(); i != ie; ++i)
2352 Tys.push_back(ToVectorTy(II->getArgOperand(i)->getType(), VF));
2353 return VTTI->getIntrinsicInstrCost(II->getIntrinsicID(), RetTy, Tys);
2356 // We are scalarizing the instruction. Return the cost of the scalar
2357 // instruction, plus the cost of insert and extract into vector
2358 // elements, times the vector width.
2361 if (!RetTy->isVoidTy() && VF != 1) {
2362 unsigned InsCost = VTTI->getVectorInstrCost(Instruction::InsertElement,
2364 unsigned ExtCost = VTTI->getVectorInstrCost(Instruction::ExtractElement,
2367 // The cost of inserting the results plus extracting each one of the
2369 Cost += VF * (InsCost + ExtCost * I->getNumOperands());
2372 // The cost of executing VF copies of the scalar instruction. This opcode
2373 // is unknown. Assume that it is the same as 'mul'.
2374 Cost += VF * VTTI->getArithmeticInstrCost(Instruction::Mul, VectorTy);
2380 Type* LoopVectorizationCostModel::ToVectorTy(Type *Scalar, unsigned VF) {
2381 if (Scalar->isVoidTy() || VF == 1)
2383 return VectorType::get(Scalar, VF);
2386 char LoopVectorize::ID = 0;
2387 static const char lv_name[] = "Loop Vectorization";
2388 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
2389 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
2390 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
2391 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
2392 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
2395 Pass *createLoopVectorizePass() {
2396 return new LoopVectorize();