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/SmallSet.h"
11 #include "llvm/ADT/StringExtras.h"
12 #include "llvm/Analysis/AliasAnalysis.h"
13 #include "llvm/Analysis/AliasSetTracker.h"
14 #include "llvm/Analysis/Dominators.h"
15 #include "llvm/Analysis/LoopInfo.h"
16 #include "llvm/Analysis/LoopIterator.h"
17 #include "llvm/Analysis/LoopPass.h"
18 #include "llvm/Analysis/ScalarEvolutionExpander.h"
19 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
20 #include "llvm/Analysis/ValueTracking.h"
21 #include "llvm/Analysis/Verifier.h"
22 #include "llvm/IR/Constants.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/DerivedTypes.h"
25 #include "llvm/IR/Function.h"
26 #include "llvm/IR/Instructions.h"
27 #include "llvm/IR/IntrinsicInst.h"
28 #include "llvm/IR/LLVMContext.h"
29 #include "llvm/IR/Module.h"
30 #include "llvm/IR/Type.h"
31 #include "llvm/IR/Value.h"
32 #include "llvm/Pass.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/TargetTransformInfo.h"
37 #include "llvm/Transforms/Scalar.h"
38 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
39 #include "llvm/Transforms/Utils/Local.h"
40 #include "llvm/Transforms/Vectorize.h"
42 static cl::opt<unsigned>
43 VectorizationFactor("force-vector-width", cl::init(0), cl::Hidden,
44 cl::desc("Sets the SIMD width. Zero is autoselect."));
46 static cl::opt<unsigned>
47 VectorizationUnroll("force-vector-unroll", cl::init(0), cl::Hidden,
48 cl::desc("Sets the vectorization unroll count. "
49 "Zero is autoselect."));
52 EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
53 cl::desc("Enable if-conversion during vectorization."));
57 /// The LoopVectorize Pass.
58 struct LoopVectorize : public LoopPass {
59 /// Pass identification, replacement for typeid
62 explicit LoopVectorize() : LoopPass(ID) {
63 initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
69 TargetTransformInfo *TTI;
72 virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
73 // We only vectorize innermost loops.
77 SE = &getAnalysis<ScalarEvolution>();
78 DL = getAnalysisIfAvailable<DataLayout>();
79 LI = &getAnalysis<LoopInfo>();
80 TTI = getAnalysisIfAvailable<TargetTransformInfo>();
81 DT = &getAnalysis<DominatorTree>();
83 DEBUG(dbgs() << "LV: Checking a loop in \"" <<
84 L->getHeader()->getParent()->getName() << "\"\n");
86 // Check if it is legal to vectorize the loop.
87 LoopVectorizationLegality LVL(L, SE, DL, DT);
88 if (!LVL.canVectorize()) {
89 DEBUG(dbgs() << "LV: Not vectorizing.\n");
93 // Select the preffered vectorization factor.
94 const VectorTargetTransformInfo *VTTI = 0;
96 VTTI = TTI->getVectorTargetTransformInfo();
97 // Use the cost model.
98 LoopVectorizationCostModel CM(L, SE, LI, &LVL, VTTI);
100 // Check the function attribues to find out if this function should be
101 // optimized for size.
102 Function *F = L->getHeader()->getParent();
103 Attribute::AttrKind SzAttr = Attribute::OptimizeForSize;
104 Attribute::AttrKind FlAttr = Attribute::NoImplicitFloat;
105 unsigned FnIndex = AttributeSet::FunctionIndex;
106 bool OptForSize = F->getAttributes().hasAttribute(FnIndex, SzAttr);
107 bool NoFloat = F->getAttributes().hasAttribute(FnIndex, FlAttr);
110 DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
111 "attribute is used.\n");
115 unsigned VF = CM.selectVectorizationFactor(OptForSize, VectorizationFactor);
116 unsigned UF = CM.selectUnrollFactor(OptForSize, VectorizationUnroll);
119 DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
123 DEBUG(dbgs() << "LV: Found a vectorizable loop ("<< VF << ") in "<<
124 F->getParent()->getModuleIdentifier()<<"\n");
125 DEBUG(dbgs() << "LV: Unroll Factor is " << UF << "\n");
127 // If we decided that it is *legal* to vectorizer the loop then do it.
128 InnerLoopVectorizer LB(L, SE, LI, DT, DL, VF, UF);
131 DEBUG(verifyFunction(*L->getHeader()->getParent()));
135 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
136 LoopPass::getAnalysisUsage(AU);
137 AU.addRequiredID(LoopSimplifyID);
138 AU.addRequiredID(LCSSAID);
139 AU.addRequired<LoopInfo>();
140 AU.addRequired<ScalarEvolution>();
141 AU.addRequired<DominatorTree>();
142 AU.addPreserved<LoopInfo>();
143 AU.addPreserved<DominatorTree>();
150 //===----------------------------------------------------------------------===//
151 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
152 // LoopVectorizationCostModel.
153 //===----------------------------------------------------------------------===//
156 LoopVectorizationLegality::RuntimePointerCheck::insert(ScalarEvolution *SE,
157 Loop *Lp, Value *Ptr) {
158 const SCEV *Sc = SE->getSCEV(Ptr);
159 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
160 assert(AR && "Invalid addrec expression");
161 const SCEV *Ex = SE->getExitCount(Lp, Lp->getLoopLatch());
162 const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
163 Pointers.push_back(Ptr);
164 Starts.push_back(AR->getStart());
165 Ends.push_back(ScEnd);
168 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
169 // Save the current insertion location.
170 Instruction *Loc = Builder.GetInsertPoint();
172 // We need to place the broadcast of invariant variables outside the loop.
173 Instruction *Instr = dyn_cast<Instruction>(V);
174 bool NewInstr = (Instr && Instr->getParent() == LoopVectorBody);
175 bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
177 // Place the code for broadcasting invariant variables in the new preheader.
179 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
181 // Broadcast the scalar into all locations in the vector.
182 Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
184 // Restore the builder insertion point.
186 Builder.SetInsertPoint(Loc);
191 Value *InnerLoopVectorizer::getConsecutiveVector(Value* Val, unsigned StartIdx,
193 assert(Val->getType()->isVectorTy() && "Must be a vector");
194 assert(Val->getType()->getScalarType()->isIntegerTy() &&
195 "Elem must be an integer");
197 Type *ITy = Val->getType()->getScalarType();
198 VectorType *Ty = cast<VectorType>(Val->getType());
199 int VLen = Ty->getNumElements();
200 SmallVector<Constant*, 8> Indices;
202 // Create a vector of consecutive numbers from zero to VF.
203 for (int i = 0; i < VLen; ++i) {
204 int Idx = Negate ? (-i): i;
205 Indices.push_back(ConstantInt::get(ITy, StartIdx + Idx));
208 // Add the consecutive indices to the vector value.
209 Constant *Cv = ConstantVector::get(Indices);
210 assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
211 return Builder.CreateAdd(Val, Cv, "induction");
214 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
215 assert(Ptr->getType()->isPointerTy() && "Unexpected non ptr");
217 // If this value is a pointer induction variable we know it is consecutive.
218 PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
219 if (Phi && Inductions.count(Phi)) {
220 InductionInfo II = Inductions[Phi];
221 if (PtrInduction == II.IK)
225 GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
229 unsigned NumOperands = Gep->getNumOperands();
230 Value *LastIndex = Gep->getOperand(NumOperands - 1);
232 // Check that all of the gep indices are uniform except for the last.
233 for (unsigned i = 0; i < NumOperands - 1; ++i)
234 if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
237 // We can emit wide load/stores only if the last index is the induction
239 const SCEV *Last = SE->getSCEV(LastIndex);
240 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
241 const SCEV *Step = AR->getStepRecurrence(*SE);
243 // The memory is consecutive because the last index is consecutive
244 // and all other indices are loop invariant.
247 if (Step->isAllOnesValue())
254 bool LoopVectorizationLegality::isUniform(Value *V) {
255 return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
258 InnerLoopVectorizer::VectorParts&
259 InnerLoopVectorizer::getVectorValue(Value *V) {
260 assert(V != Induction && "The new induction variable should not be used.");
261 assert(!V->getType()->isVectorTy() && "Can't widen a vector");
263 // If we have this scalar in the map, return it.
265 return WidenMap.get(V);
267 // If this scalar is unknown, assume that it is a constant or that it is
268 // loop invariant. Broadcast V and save the value for future uses.
269 Value *B = getBroadcastInstrs(V);
270 WidenMap.splat(V, B);
271 return WidenMap.get(V);
275 InnerLoopVectorizer::getUniformVector(unsigned Val, Type* ScalarTy) {
276 return ConstantVector::getSplat(VF, ConstantInt::get(ScalarTy, Val, true));
279 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
280 assert(Vec->getType()->isVectorTy() && "Invalid type");
281 SmallVector<Constant*, 8> ShuffleMask;
282 for (unsigned i = 0; i < VF; ++i)
283 ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
285 return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
286 ConstantVector::get(ShuffleMask),
290 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr) {
291 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
292 // Holds vector parameters or scalars, in case of uniform vals.
293 SmallVector<VectorParts, 4> Params;
295 // Find all of the vectorized parameters.
296 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
297 Value *SrcOp = Instr->getOperand(op);
299 // If we are accessing the old induction variable, use the new one.
300 if (SrcOp == OldInduction) {
301 Params.push_back(getVectorValue(SrcOp));
305 // Try using previously calculated values.
306 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
308 // If the src is an instruction that appeared earlier in the basic block
309 // then it should already be vectorized.
310 if (SrcInst && OrigLoop->contains(SrcInst)) {
311 assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
312 // The parameter is a vector value from earlier.
313 Params.push_back(WidenMap.get(SrcInst));
315 // The parameter is a scalar from outside the loop. Maybe even a constant.
317 Scalars.append(UF, SrcOp);
318 Params.push_back(Scalars);
322 assert(Params.size() == Instr->getNumOperands() &&
323 "Invalid number of operands");
325 // Does this instruction return a value ?
326 bool IsVoidRetTy = Instr->getType()->isVoidTy();
328 Value *UndefVec = IsVoidRetTy ? 0 :
329 UndefValue::get(VectorType::get(Instr->getType(), VF));
330 // Create a new entry in the WidenMap and initialize it to Undef or Null.
331 VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
333 // For each scalar that we create:
334 for (unsigned Width = 0; Width < VF; ++Width) {
335 // For each vector unroll 'part':
336 for (unsigned Part = 0; Part < UF; ++Part) {
337 Instruction *Cloned = Instr->clone();
339 Cloned->setName(Instr->getName() + ".cloned");
340 // Replace the operands of the cloned instrucions with extracted scalars.
341 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
342 Value *Op = Params[op][Part];
343 // Param is a vector. Need to extract the right lane.
344 if (Op->getType()->isVectorTy())
345 Op = Builder.CreateExtractElement(Op, Builder.getInt32(Width));
346 Cloned->setOperand(op, Op);
349 // Place the cloned scalar in the new loop.
350 Builder.Insert(Cloned);
352 // If the original scalar returns a value we need to place it in a vector
353 // so that future users will be able to use it.
355 VecResults[Part] = Builder.CreateInsertElement(VecResults[Part], Cloned,
356 Builder.getInt32(Width));
362 InnerLoopVectorizer::addRuntimeCheck(LoopVectorizationLegality *Legal,
364 LoopVectorizationLegality::RuntimePointerCheck *PtrRtCheck =
365 Legal->getRuntimePointerCheck();
367 if (!PtrRtCheck->Need)
370 Value *MemoryRuntimeCheck = 0;
371 unsigned NumPointers = PtrRtCheck->Pointers.size();
372 SmallVector<Value* , 2> Starts;
373 SmallVector<Value* , 2> Ends;
375 SCEVExpander Exp(*SE, "induction");
377 // Use this type for pointer arithmetic.
378 Type* PtrArithTy = Type::getInt8PtrTy(Loc->getContext(), 0);
380 for (unsigned i = 0; i < NumPointers; ++i) {
381 Value *Ptr = PtrRtCheck->Pointers[i];
382 const SCEV *Sc = SE->getSCEV(Ptr);
384 if (SE->isLoopInvariant(Sc, OrigLoop)) {
385 DEBUG(dbgs() << "LV: Adding RT check for a loop invariant ptr:" <<
387 Starts.push_back(Ptr);
390 DEBUG(dbgs() << "LV: Adding RT check for range:" << *Ptr <<"\n");
392 Value *Start = Exp.expandCodeFor(PtrRtCheck->Starts[i], PtrArithTy, Loc);
393 Value *End = Exp.expandCodeFor(PtrRtCheck->Ends[i], PtrArithTy, Loc);
394 Starts.push_back(Start);
399 for (unsigned i = 0; i < NumPointers; ++i) {
400 for (unsigned j = i+1; j < NumPointers; ++j) {
401 Instruction::CastOps Op = Instruction::BitCast;
402 Value *Start0 = CastInst::Create(Op, Starts[i], PtrArithTy, "bc", Loc);
403 Value *Start1 = CastInst::Create(Op, Starts[j], PtrArithTy, "bc", Loc);
404 Value *End0 = CastInst::Create(Op, Ends[i], PtrArithTy, "bc", Loc);
405 Value *End1 = CastInst::Create(Op, Ends[j], PtrArithTy, "bc", Loc);
407 Value *Cmp0 = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_ULE,
408 Start0, End1, "bound0", Loc);
409 Value *Cmp1 = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_ULE,
410 Start1, End0, "bound1", Loc);
411 Value *IsConflict = BinaryOperator::Create(Instruction::And, Cmp0, Cmp1,
412 "found.conflict", Loc);
413 if (MemoryRuntimeCheck)
414 MemoryRuntimeCheck = BinaryOperator::Create(Instruction::Or,
417 "conflict.rdx", Loc);
419 MemoryRuntimeCheck = IsConflict;
424 return MemoryRuntimeCheck;
428 InnerLoopVectorizer::createEmptyLoop(LoopVectorizationLegality *Legal) {
430 In this function we generate a new loop. The new loop will contain
431 the vectorized instructions while the old loop will continue to run the
434 [ ] <-- vector loop bypass.
437 | [ ] <-- vector pre header.
441 | [ ]_| <-- vector loop.
444 >[ ] <--- middle-block.
447 | [ ] <--- new preheader.
451 | [ ]_| <-- old scalar loop to handle remainder.
458 BasicBlock *OldBasicBlock = OrigLoop->getHeader();
459 BasicBlock *BypassBlock = OrigLoop->getLoopPreheader();
460 BasicBlock *ExitBlock = OrigLoop->getExitBlock();
461 assert(ExitBlock && "Must have an exit block");
463 // Some loops have a single integer induction variable, while other loops
464 // don't. One example is c++ iterators that often have multiple pointer
465 // induction variables. In the code below we also support a case where we
466 // don't have a single induction variable.
467 OldInduction = Legal->getInduction();
468 Type *IdxTy = OldInduction ? OldInduction->getType() :
469 DL->getIntPtrType(SE->getContext());
471 // Find the loop boundaries.
472 const SCEV *ExitCount = SE->getExitCount(OrigLoop, OrigLoop->getLoopLatch());
473 assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
475 // Get the total trip count from the count by adding 1.
476 ExitCount = SE->getAddExpr(ExitCount,
477 SE->getConstant(ExitCount->getType(), 1));
479 // Expand the trip count and place the new instructions in the preheader.
480 // Notice that the pre-header does not change, only the loop body.
481 SCEVExpander Exp(*SE, "induction");
483 // Count holds the overall loop count (N).
484 Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
485 BypassBlock->getTerminator());
487 // The loop index does not have to start at Zero. Find the original start
488 // value from the induction PHI node. If we don't have an induction variable
489 // then we know that it starts at zero.
490 Value *StartIdx = OldInduction ?
491 OldInduction->getIncomingValueForBlock(BypassBlock):
492 ConstantInt::get(IdxTy, 0);
494 assert(BypassBlock && "Invalid loop structure");
496 // Generate the code that checks in runtime if arrays overlap.
497 Value *MemoryRuntimeCheck = addRuntimeCheck(Legal,
498 BypassBlock->getTerminator());
500 // Split the single block loop into the two loop structure described above.
501 BasicBlock *VectorPH =
502 BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
503 BasicBlock *VecBody =
504 VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
505 BasicBlock *MiddleBlock =
506 VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
507 BasicBlock *ScalarPH =
508 MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
510 // This is the location in which we add all of the logic for bypassing
511 // the new vector loop.
512 Instruction *Loc = BypassBlock->getTerminator();
514 // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
516 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
518 // Generate the induction variable.
519 Induction = Builder.CreatePHI(IdxTy, 2, "index");
520 // The loop step is equal to the vectorization factor (num of SIMD elements)
521 // times the unroll factor (num of SIMD instructions).
522 Constant *Step = ConstantInt::get(IdxTy, VF * UF);
524 // We may need to extend the index in case there is a type mismatch.
525 // We know that the count starts at zero and does not overflow.
526 if (Count->getType() != IdxTy) {
527 // The exit count can be of pointer type. Convert it to the correct
529 if (ExitCount->getType()->isPointerTy())
530 Count = CastInst::CreatePointerCast(Count, IdxTy, "ptrcnt.to.int", Loc);
532 Count = CastInst::CreateZExtOrBitCast(Count, IdxTy, "zext.cnt", Loc);
535 // Add the start index to the loop count to get the new end index.
536 Value *IdxEnd = BinaryOperator::CreateAdd(Count, StartIdx, "end.idx", Loc);
538 // Now we need to generate the expression for N - (N % VF), which is
539 // the part that the vectorized body will execute.
540 Value *R = BinaryOperator::CreateURem(Count, Step, "n.mod.vf", Loc);
541 Value *CountRoundDown = BinaryOperator::CreateSub(Count, R, "n.vec", Loc);
542 Value *IdxEndRoundDown = BinaryOperator::CreateAdd(CountRoundDown, StartIdx,
543 "end.idx.rnd.down", Loc);
545 // Now, compare the new count to zero. If it is zero skip the vector loop and
546 // jump to the scalar loop.
547 Value *Cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
552 // If we are using memory runtime checks, include them in.
553 if (MemoryRuntimeCheck)
554 Cmp = BinaryOperator::Create(Instruction::Or, Cmp, MemoryRuntimeCheck,
557 BranchInst::Create(MiddleBlock, VectorPH, Cmp, Loc);
558 // Remove the old terminator.
559 Loc->eraseFromParent();
561 // We are going to resume the execution of the scalar loop.
562 // Go over all of the induction variables that we found and fix the
563 // PHIs that are left in the scalar version of the loop.
564 // The starting values of PHI nodes depend on the counter of the last
565 // iteration in the vectorized loop.
566 // If we come from a bypass edge then we need to start from the original
569 // This variable saves the new starting index for the scalar loop.
570 PHINode *ResumeIndex = 0;
571 LoopVectorizationLegality::InductionList::iterator I, E;
572 LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
573 for (I = List->begin(), E = List->end(); I != E; ++I) {
574 PHINode *OrigPhi = I->first;
575 LoopVectorizationLegality::InductionInfo II = I->second;
576 PHINode *ResumeVal = PHINode::Create(OrigPhi->getType(), 2, "resume.val",
577 MiddleBlock->getTerminator());
580 case LoopVectorizationLegality::NoInduction:
581 llvm_unreachable("Unknown induction");
582 case LoopVectorizationLegality::IntInduction: {
583 // Handle the integer induction counter:
584 assert(OrigPhi->getType()->isIntegerTy() && "Invalid type");
585 assert(OrigPhi == OldInduction && "Unknown integer PHI");
586 // We know what the end value is.
587 EndValue = IdxEndRoundDown;
588 // We also know which PHI node holds it.
589 ResumeIndex = ResumeVal;
592 case LoopVectorizationLegality::ReverseIntInduction: {
593 // Convert the CountRoundDown variable to the PHI size.
594 unsigned CRDSize = CountRoundDown->getType()->getScalarSizeInBits();
595 unsigned IISize = II.StartValue->getType()->getScalarSizeInBits();
596 Value *CRD = CountRoundDown;
597 if (CRDSize > IISize)
598 CRD = CastInst::Create(Instruction::Trunc, CountRoundDown,
599 II.StartValue->getType(),
600 "tr.crd", BypassBlock->getTerminator());
601 else if (CRDSize < IISize)
602 CRD = CastInst::Create(Instruction::SExt, CountRoundDown,
603 II.StartValue->getType(),
604 "sext.crd", BypassBlock->getTerminator());
605 // Handle reverse integer induction counter:
606 EndValue = BinaryOperator::CreateSub(II.StartValue, CRD, "rev.ind.end",
607 BypassBlock->getTerminator());
610 case LoopVectorizationLegality::PtrInduction: {
611 // For pointer induction variables, calculate the offset using
613 EndValue = GetElementPtrInst::Create(II.StartValue, CountRoundDown,
615 BypassBlock->getTerminator());
620 // The new PHI merges the original incoming value, in case of a bypass,
621 // or the value at the end of the vectorized loop.
622 ResumeVal->addIncoming(II.StartValue, BypassBlock);
623 ResumeVal->addIncoming(EndValue, VecBody);
625 // Fix the scalar body counter (PHI node).
626 unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
627 OrigPhi->setIncomingValue(BlockIdx, ResumeVal);
630 // If we are generating a new induction variable then we also need to
631 // generate the code that calculates the exit value. This value is not
632 // simply the end of the counter because we may skip the vectorized body
633 // in case of a runtime check.
635 assert(!ResumeIndex && "Unexpected resume value found");
636 ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val",
637 MiddleBlock->getTerminator());
638 ResumeIndex->addIncoming(StartIdx, BypassBlock);
639 ResumeIndex->addIncoming(IdxEndRoundDown, VecBody);
642 // Make sure that we found the index where scalar loop needs to continue.
643 assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() &&
644 "Invalid resume Index");
646 // Add a check in the middle block to see if we have completed
647 // all of the iterations in the first vector loop.
648 // If (N - N%VF) == N, then we *don't* need to run the remainder.
649 Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd,
650 ResumeIndex, "cmp.n",
651 MiddleBlock->getTerminator());
653 BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
654 // Remove the old terminator.
655 MiddleBlock->getTerminator()->eraseFromParent();
657 // Create i+1 and fill the PHINode.
658 Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
659 Induction->addIncoming(StartIdx, VectorPH);
660 Induction->addIncoming(NextIdx, VecBody);
661 // Create the compare.
662 Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown);
663 Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
665 // Now we have two terminators. Remove the old one from the block.
666 VecBody->getTerminator()->eraseFromParent();
668 // Get ready to start creating new instructions into the vectorized body.
669 Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
671 // Create and register the new vector loop.
672 Loop* Lp = new Loop();
673 Loop *ParentLoop = OrigLoop->getParentLoop();
675 // Insert the new loop into the loop nest and register the new basic blocks.
677 ParentLoop->addChildLoop(Lp);
678 ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase());
679 ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase());
680 ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase());
682 LI->addTopLevelLoop(Lp);
685 Lp->addBasicBlockToLoop(VecBody, LI->getBase());
688 LoopVectorPreHeader = VectorPH;
689 LoopScalarPreHeader = ScalarPH;
690 LoopMiddleBlock = MiddleBlock;
691 LoopExitBlock = ExitBlock;
692 LoopVectorBody = VecBody;
693 LoopScalarBody = OldBasicBlock;
694 LoopBypassBlock = BypassBlock;
697 /// This function returns the identity element (or neutral element) for
700 getReductionIdentity(LoopVectorizationLegality::ReductionKind K) {
702 case LoopVectorizationLegality::IntegerXor:
703 case LoopVectorizationLegality::IntegerAdd:
704 case LoopVectorizationLegality::IntegerOr:
705 // Adding, Xoring, Oring zero to a number does not change it.
707 case LoopVectorizationLegality::IntegerMult:
708 // Multiplying a number by 1 does not change it.
710 case LoopVectorizationLegality::IntegerAnd:
711 // AND-ing a number with an all-1 value does not change it.
714 llvm_unreachable("Unknown reduction kind");
719 isTriviallyVectorizableIntrinsic(Instruction *Inst) {
720 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst);
723 switch (II->getIntrinsicID()) {
724 case Intrinsic::sqrt:
728 case Intrinsic::exp2:
730 case Intrinsic::log10:
731 case Intrinsic::log2:
732 case Intrinsic::fabs:
733 case Intrinsic::floor:
734 case Intrinsic::ceil:
735 case Intrinsic::trunc:
736 case Intrinsic::rint:
737 case Intrinsic::nearbyint:
740 case Intrinsic::fmuladd:
749 InnerLoopVectorizer::vectorizeLoop(LoopVectorizationLegality *Legal) {
750 //===------------------------------------------------===//
752 // Notice: any optimization or new instruction that go
753 // into the code below should be also be implemented in
756 //===------------------------------------------------===//
757 BasicBlock &BB = *OrigLoop->getHeader();
759 ConstantInt::get(IntegerType::getInt32Ty(BB.getContext()), 0);
761 // In order to support reduction variables we need to be able to vectorize
762 // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
763 // stages. First, we create a new vector PHI node with no incoming edges.
764 // We use this value when we vectorize all of the instructions that use the
765 // PHI. Next, after all of the instructions in the block are complete we
766 // add the new incoming edges to the PHI. At this point all of the
767 // instructions in the basic block are vectorized, so we can use them to
768 // construct the PHI.
769 PhiVector RdxPHIsToFix;
771 // Scan the loop in a topological order to ensure that defs are vectorized
773 LoopBlocksDFS DFS(OrigLoop);
776 // Vectorize all of the blocks in the original loop.
777 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
778 be = DFS.endRPO(); bb != be; ++bb)
779 vectorizeBlockInLoop(Legal, *bb, &RdxPHIsToFix);
781 // At this point every instruction in the original loop is widened to
782 // a vector form. We are almost done. Now, we need to fix the PHI nodes
783 // that we vectorized. The PHI nodes are currently empty because we did
784 // not want to introduce cycles. Notice that the remaining PHI nodes
785 // that we need to fix are reduction variables.
787 // Create the 'reduced' values for each of the induction vars.
788 // The reduced values are the vector values that we scalarize and combine
789 // after the loop is finished.
790 for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
792 PHINode *RdxPhi = *it;
793 assert(RdxPhi && "Unable to recover vectorized PHI");
795 // Find the reduction variable descriptor.
796 assert(Legal->getReductionVars()->count(RdxPhi) &&
797 "Unable to find the reduction variable");
798 LoopVectorizationLegality::ReductionDescriptor RdxDesc =
799 (*Legal->getReductionVars())[RdxPhi];
801 // We need to generate a reduction vector from the incoming scalar.
802 // To do so, we need to generate the 'identity' vector and overide
803 // one of the elements with the incoming scalar reduction. We need
804 // to do it in the vector-loop preheader.
805 Builder.SetInsertPoint(LoopBypassBlock->getTerminator());
807 // This is the vector-clone of the value that leaves the loop.
808 VectorParts &VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
809 Type *VecTy = VectorExit[0]->getType();
811 // Find the reduction identity variable. Zero for addition, or, xor,
812 // one for multiplication, -1 for And.
813 Constant *Identity = getUniformVector(getReductionIdentity(RdxDesc.Kind),
814 VecTy->getScalarType());
816 // This vector is the Identity vector where the first element is the
817 // incoming scalar reduction.
818 Value *VectorStart = Builder.CreateInsertElement(Identity,
819 RdxDesc.StartValue, Zero);
821 // Fix the vector-loop phi.
822 // We created the induction variable so we know that the
823 // preheader is the first entry.
824 BasicBlock *VecPreheader = Induction->getIncomingBlock(0);
826 // Reductions do not have to start at zero. They can start with
827 // any loop invariant values.
828 VectorParts &VecRdxPhi = WidenMap.get(RdxPhi);
829 BasicBlock *Latch = OrigLoop->getLoopLatch();
830 Value *LoopVal = RdxPhi->getIncomingValueForBlock(Latch);
831 VectorParts &Val = getVectorValue(LoopVal);
832 for (unsigned part = 0; part < UF; ++part) {
833 // Make sure to add the reduction stat value only to the
834 // first unroll part.
835 Value *StartVal = (part == 0) ? VectorStart : Identity;
836 cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal, VecPreheader);
837 cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part], LoopVectorBody);
840 // Before each round, move the insertion point right between
841 // the PHIs and the values we are going to write.
842 // This allows us to write both PHINodes and the extractelement
844 Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
846 VectorParts RdxParts;
847 for (unsigned part = 0; part < UF; ++part) {
848 // This PHINode contains the vectorized reduction variable, or
849 // the initial value vector, if we bypass the vector loop.
850 VectorParts &RdxExitVal = getVectorValue(RdxDesc.LoopExitInstr);
851 PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
852 Value *StartVal = (part == 0) ? VectorStart : Identity;
853 NewPhi->addIncoming(StartVal, LoopBypassBlock);
854 NewPhi->addIncoming(RdxExitVal[part], LoopVectorBody);
855 RdxParts.push_back(NewPhi);
858 // Reduce all of the unrolled parts into a single vector.
859 Value *ReducedPartRdx = RdxParts[0];
860 for (unsigned part = 1; part < UF; ++part) {
861 switch (RdxDesc.Kind) {
862 case LoopVectorizationLegality::IntegerAdd:
864 Builder.CreateAdd(RdxParts[part], ReducedPartRdx, "add.rdx");
866 case LoopVectorizationLegality::IntegerMult:
868 Builder.CreateMul(RdxParts[part], ReducedPartRdx, "mul.rdx");
870 case LoopVectorizationLegality::IntegerOr:
872 Builder.CreateOr(RdxParts[part], ReducedPartRdx, "or.rdx");
874 case LoopVectorizationLegality::IntegerAnd:
876 Builder.CreateAnd(RdxParts[part], ReducedPartRdx, "and.rdx");
878 case LoopVectorizationLegality::IntegerXor:
880 Builder.CreateXor(RdxParts[part], ReducedPartRdx, "xor.rdx");
883 llvm_unreachable("Unknown reduction operation");
888 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
889 // and vector ops, reducing the set of values being computed by half each
891 assert(isPowerOf2_32(VF) &&
892 "Reduction emission only supported for pow2 vectors!");
893 Value *TmpVec = ReducedPartRdx;
894 SmallVector<Constant*, 32> ShuffleMask(VF, 0);
895 for (unsigned i = VF; i != 1; i >>= 1) {
896 // Move the upper half of the vector to the lower half.
897 for (unsigned j = 0; j != i/2; ++j)
898 ShuffleMask[j] = Builder.getInt32(i/2 + j);
900 // Fill the rest of the mask with undef.
901 std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
902 UndefValue::get(Builder.getInt32Ty()));
905 Builder.CreateShuffleVector(TmpVec,
906 UndefValue::get(TmpVec->getType()),
907 ConstantVector::get(ShuffleMask),
910 // Emit the operation on the shuffled value.
911 switch (RdxDesc.Kind) {
912 case LoopVectorizationLegality::IntegerAdd:
913 TmpVec = Builder.CreateAdd(TmpVec, Shuf, "add.rdx");
915 case LoopVectorizationLegality::IntegerMult:
916 TmpVec = Builder.CreateMul(TmpVec, Shuf, "mul.rdx");
918 case LoopVectorizationLegality::IntegerOr:
919 TmpVec = Builder.CreateOr(TmpVec, Shuf, "or.rdx");
921 case LoopVectorizationLegality::IntegerAnd:
922 TmpVec = Builder.CreateAnd(TmpVec, Shuf, "and.rdx");
924 case LoopVectorizationLegality::IntegerXor:
925 TmpVec = Builder.CreateXor(TmpVec, Shuf, "xor.rdx");
928 llvm_unreachable("Unknown reduction operation");
932 // The result is in the first element of the vector.
933 Value *Scalar0 = Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
935 // Now, we need to fix the users of the reduction variable
936 // inside and outside of the scalar remainder loop.
937 // We know that the loop is in LCSSA form. We need to update the
938 // PHI nodes in the exit blocks.
939 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
940 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
941 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
942 if (!LCSSAPhi) continue;
944 // All PHINodes need to have a single entry edge, or two if
945 // we already fixed them.
946 assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
948 // We found our reduction value exit-PHI. Update it with the
949 // incoming bypass edge.
950 if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
951 // Add an edge coming from the bypass.
952 LCSSAPhi->addIncoming(Scalar0, LoopMiddleBlock);
955 }// end of the LCSSA phi scan.
957 // Fix the scalar loop reduction variable with the incoming reduction sum
958 // from the vector body and from the backedge value.
959 int IncomingEdgeBlockIdx =
960 (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
961 assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
962 // Pick the other block.
963 int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
964 (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, Scalar0);
965 (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
966 }// end of for each redux variable.
968 // The Loop exit block may have single value PHI nodes where the incoming
969 // value is 'undef'. While vectorizing we only handled real values that
970 // were defined inside the loop. Here we handle the 'undef case'.
972 for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
973 LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
974 PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
975 if (!LCSSAPhi) continue;
976 if (LCSSAPhi->getNumIncomingValues() == 1)
977 LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
982 InnerLoopVectorizer::VectorParts
983 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
984 assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
987 VectorParts SrcMask = createBlockInMask(Src);
989 // The terminator has to be a branch inst!
990 BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
991 assert(BI && "Unexpected terminator found");
993 if (BI->isConditional()) {
994 VectorParts EdgeMask = getVectorValue(BI->getCondition());
996 if (BI->getSuccessor(0) != Dst)
997 for (unsigned part = 0; part < UF; ++part)
998 EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
1000 for (unsigned part = 0; part < UF; ++part)
1001 EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
1008 InnerLoopVectorizer::VectorParts
1009 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
1010 assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
1012 // Loop incoming mask is all-one.
1013 if (OrigLoop->getHeader() == BB) {
1014 Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
1015 return getVectorValue(C);
1018 // This is the block mask. We OR all incoming edges, and with zero.
1019 Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
1020 VectorParts BlockMask = getVectorValue(Zero);
1023 for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
1024 VectorParts EM = createEdgeMask(*it, BB);
1025 for (unsigned part = 0; part < UF; ++part)
1026 BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
1033 InnerLoopVectorizer::vectorizeBlockInLoop(LoopVectorizationLegality *Legal,
1034 BasicBlock *BB, PhiVector *PV) {
1035 Constant *Zero = Builder.getInt32(0);
1037 // For each instruction in the old loop.
1038 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1039 VectorParts &Entry = WidenMap.get(it);
1040 switch (it->getOpcode()) {
1041 case Instruction::Br:
1042 // Nothing to do for PHIs and BR, since we already took care of the
1043 // loop control flow instructions.
1045 case Instruction::PHI:{
1046 PHINode* P = cast<PHINode>(it);
1047 // Handle reduction variables:
1048 if (Legal->getReductionVars()->count(P)) {
1049 for (unsigned part = 0; part < UF; ++part) {
1050 // This is phase one of vectorizing PHIs.
1051 Type *VecTy = VectorType::get(it->getType(), VF);
1052 Entry[part] = PHINode::Create(VecTy, 2, "vec.phi",
1053 LoopVectorBody-> getFirstInsertionPt());
1059 // Check for PHI nodes that are lowered to vector selects.
1060 if (P->getParent() != OrigLoop->getHeader()) {
1061 // We know that all PHIs in non header blocks are converted into
1062 // selects, so we don't have to worry about the insertion order and we
1063 // can just use the builder.
1065 // At this point we generate the predication tree. There may be
1066 // duplications since this is a simple recursive scan, but future
1067 // optimizations will clean it up.
1068 VectorParts Cond = createEdgeMask(P->getIncomingBlock(0),
1071 for (unsigned part = 0; part < UF; ++part) {
1072 VectorParts &In0 = getVectorValue(P->getIncomingValue(0));
1073 VectorParts &In1 = getVectorValue(P->getIncomingValue(1));
1074 Entry[part] = Builder.CreateSelect(Cond[part], In0[part], In1[part],
1080 // This PHINode must be an induction variable.
1081 // Make sure that we know about it.
1082 assert(Legal->getInductionVars()->count(P) &&
1083 "Not an induction variable");
1085 LoopVectorizationLegality::InductionInfo II =
1086 Legal->getInductionVars()->lookup(P);
1089 case LoopVectorizationLegality::NoInduction:
1090 llvm_unreachable("Unknown induction");
1091 case LoopVectorizationLegality::IntInduction: {
1092 assert(P == OldInduction && "Unexpected PHI");
1093 Value *Broadcasted = getBroadcastInstrs(Induction);
1094 // After broadcasting the induction variable we need to make the
1095 // vector consecutive by adding 0, 1, 2 ...
1096 for (unsigned part = 0; part < UF; ++part)
1097 Entry[part] = getConsecutiveVector(Broadcasted, VF * part, false);
1100 case LoopVectorizationLegality::ReverseIntInduction:
1101 case LoopVectorizationLegality::PtrInduction:
1102 // Handle reverse integer and pointer inductions.
1103 Value *StartIdx = 0;
1104 // If we have a single integer induction variable then use it.
1105 // Otherwise, start counting at zero.
1107 LoopVectorizationLegality::InductionInfo OldII =
1108 Legal->getInductionVars()->lookup(OldInduction);
1109 StartIdx = OldII.StartValue;
1111 StartIdx = ConstantInt::get(Induction->getType(), 0);
1113 // This is the normalized GEP that starts counting at zero.
1114 Value *NormalizedIdx = Builder.CreateSub(Induction, StartIdx,
1117 // Handle the reverse integer induction variable case.
1118 if (LoopVectorizationLegality::ReverseIntInduction == II.IK) {
1119 IntegerType *DstTy = cast<IntegerType>(II.StartValue->getType());
1120 Value *CNI = Builder.CreateSExtOrTrunc(NormalizedIdx, DstTy,
1122 Value *ReverseInd = Builder.CreateSub(II.StartValue, CNI,
1125 // This is a new value so do not hoist it out.
1126 Value *Broadcasted = getBroadcastInstrs(ReverseInd);
1127 // After broadcasting the induction variable we need to make the
1128 // vector consecutive by adding ... -3, -2, -1, 0.
1129 for (unsigned part = 0; part < UF; ++part)
1130 Entry[part] = getConsecutiveVector(Broadcasted, -VF * part, true);
1134 // Handle the pointer induction variable case.
1135 assert(P->getType()->isPointerTy() && "Unexpected type.");
1137 // This is the vector of results. Notice that we don't generate
1138 // vector geps because scalar geps result in better code.
1139 for (unsigned part = 0; part < UF; ++part) {
1140 Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
1141 for (unsigned int i = 0; i < VF; ++i) {
1142 Constant *Idx = ConstantInt::get(Induction->getType(),
1144 Value *GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx,
1146 Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
1148 VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
1149 Builder.getInt32(i),
1152 Entry[part] = VecVal;
1159 case Instruction::Add:
1160 case Instruction::FAdd:
1161 case Instruction::Sub:
1162 case Instruction::FSub:
1163 case Instruction::Mul:
1164 case Instruction::FMul:
1165 case Instruction::UDiv:
1166 case Instruction::SDiv:
1167 case Instruction::FDiv:
1168 case Instruction::URem:
1169 case Instruction::SRem:
1170 case Instruction::FRem:
1171 case Instruction::Shl:
1172 case Instruction::LShr:
1173 case Instruction::AShr:
1174 case Instruction::And:
1175 case Instruction::Or:
1176 case Instruction::Xor: {
1177 // Just widen binops.
1178 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
1179 VectorParts &A = getVectorValue(it->getOperand(0));
1180 VectorParts &B = getVectorValue(it->getOperand(1));
1182 // Use this vector value for all users of the original instruction.
1183 for (unsigned Part = 0; Part < UF; ++Part) {
1184 Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
1186 // Update the NSW, NUW and Exact flags.
1187 BinaryOperator *VecOp = cast<BinaryOperator>(V);
1188 if (isa<OverflowingBinaryOperator>(BinOp)) {
1189 VecOp->setHasNoSignedWrap(BinOp->hasNoSignedWrap());
1190 VecOp->setHasNoUnsignedWrap(BinOp->hasNoUnsignedWrap());
1192 if (isa<PossiblyExactOperator>(VecOp))
1193 VecOp->setIsExact(BinOp->isExact());
1199 case Instruction::Select: {
1201 // If the selector is loop invariant we can create a select
1202 // instruction with a scalar condition. Otherwise, use vector-select.
1203 bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)),
1206 // The condition can be loop invariant but still defined inside the
1207 // loop. This means that we can't just use the original 'cond' value.
1208 // We have to take the 'vectorized' value and pick the first lane.
1209 // Instcombine will make this a no-op.
1210 VectorParts &Cond = getVectorValue(it->getOperand(0));
1211 VectorParts &Op0 = getVectorValue(it->getOperand(1));
1212 VectorParts &Op1 = getVectorValue(it->getOperand(2));
1213 Value *ScalarCond = Builder.CreateExtractElement(Cond[0],
1214 Builder.getInt32(0));
1215 for (unsigned Part = 0; Part < UF; ++Part) {
1216 Entry[Part] = Builder.CreateSelect(
1217 InvariantCond ? ScalarCond : Cond[Part],
1224 case Instruction::ICmp:
1225 case Instruction::FCmp: {
1226 // Widen compares. Generate vector compares.
1227 bool FCmp = (it->getOpcode() == Instruction::FCmp);
1228 CmpInst *Cmp = dyn_cast<CmpInst>(it);
1229 VectorParts &A = getVectorValue(it->getOperand(0));
1230 VectorParts &B = getVectorValue(it->getOperand(1));
1231 for (unsigned Part = 0; Part < UF; ++Part) {
1234 C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
1236 C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
1242 case Instruction::Store: {
1243 // Attempt to issue a wide store.
1244 StoreInst *SI = dyn_cast<StoreInst>(it);
1245 Type *StTy = VectorType::get(SI->getValueOperand()->getType(), VF);
1246 Value *Ptr = SI->getPointerOperand();
1247 unsigned Alignment = SI->getAlignment();
1249 assert(!Legal->isUniform(Ptr) &&
1250 "We do not allow storing to uniform addresses");
1253 int Stride = Legal->isConsecutivePtr(Ptr);
1254 bool Reverse = Stride < 0;
1256 scalarizeInstruction(it);
1260 // Handle consecutive stores.
1262 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1264 // The last index does not have to be the induction. It can be
1265 // consecutive and be a function of the index. For example A[I+1];
1266 unsigned NumOperands = Gep->getNumOperands();
1268 Value *LastGepOperand = Gep->getOperand(NumOperands - 1);
1269 VectorParts &GEPParts = getVectorValue(LastGepOperand);
1270 Value *LastIndex = GEPParts[0];
1271 LastIndex = Builder.CreateExtractElement(LastIndex, Zero);
1273 // Create the new GEP with the new induction variable.
1274 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1275 Gep2->setOperand(NumOperands - 1, LastIndex);
1276 Ptr = Builder.Insert(Gep2);
1278 // Use the induction element ptr.
1279 assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1280 VectorParts &PtrVal = getVectorValue(Ptr);
1281 Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
1284 VectorParts &StoredVal = getVectorValue(SI->getValueOperand());
1285 for (unsigned Part = 0; Part < UF; ++Part) {
1286 // Calculate the pointer for the specific unroll-part.
1287 Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1290 // If we store to reverse consecutive memory locations then we need
1291 // to reverse the order of elements in the stored value.
1292 StoredVal[Part] = reverseVector(StoredVal[Part]);
1293 // If the address is consecutive but reversed, then the
1294 // wide store needs to start at the last vector element.
1295 PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1296 PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1299 Value *VecPtr = Builder.CreateBitCast(PartPtr, StTy->getPointerTo());
1300 Builder.CreateStore(StoredVal[Part], VecPtr)->setAlignment(Alignment);
1304 case Instruction::Load: {
1305 // Attempt to issue a wide load.
1306 LoadInst *LI = dyn_cast<LoadInst>(it);
1307 Type *RetTy = VectorType::get(LI->getType(), VF);
1308 Value *Ptr = LI->getPointerOperand();
1309 unsigned Alignment = LI->getAlignment();
1311 // If the pointer is loop invariant or if it is non consecutive,
1312 // scalarize the load.
1313 int Stride = Legal->isConsecutivePtr(Ptr);
1314 bool Reverse = Stride < 0;
1315 if (Legal->isUniform(Ptr) || Stride == 0) {
1316 scalarizeInstruction(it);
1320 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1322 // The last index does not have to be the induction. It can be
1323 // consecutive and be a function of the index. For example A[I+1];
1324 unsigned NumOperands = Gep->getNumOperands();
1326 Value *LastGepOperand = Gep->getOperand(NumOperands - 1);
1327 VectorParts &GEPParts = getVectorValue(LastGepOperand);
1328 Value *LastIndex = GEPParts[0];
1329 LastIndex = Builder.CreateExtractElement(LastIndex, Zero);
1331 // Create the new GEP with the new induction variable.
1332 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1333 Gep2->setOperand(NumOperands - 1, LastIndex);
1334 Ptr = Builder.Insert(Gep2);
1336 // Use the induction element ptr.
1337 assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1338 VectorParts &PtrVal = getVectorValue(Ptr);
1339 Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
1342 for (unsigned Part = 0; Part < UF; ++Part) {
1343 // Calculate the pointer for the specific unroll-part.
1344 Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1347 // If the address is consecutive but reversed, then the
1348 // wide store needs to start at the last vector element.
1349 PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1350 PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1353 Value *VecPtr = Builder.CreateBitCast(PartPtr, RetTy->getPointerTo());
1354 Value *LI = Builder.CreateLoad(VecPtr, "wide.load");
1355 cast<LoadInst>(LI)->setAlignment(Alignment);
1356 Entry[Part] = Reverse ? reverseVector(LI) : LI;
1360 case Instruction::ZExt:
1361 case Instruction::SExt:
1362 case Instruction::FPToUI:
1363 case Instruction::FPToSI:
1364 case Instruction::FPExt:
1365 case Instruction::PtrToInt:
1366 case Instruction::IntToPtr:
1367 case Instruction::SIToFP:
1368 case Instruction::UIToFP:
1369 case Instruction::Trunc:
1370 case Instruction::FPTrunc:
1371 case Instruction::BitCast: {
1372 CastInst *CI = dyn_cast<CastInst>(it);
1373 /// Optimize the special case where the source is the induction
1374 /// variable. Notice that we can only optimize the 'trunc' case
1375 /// because: a. FP conversions lose precision, b. sext/zext may wrap,
1376 /// c. other casts depend on pointer size.
1377 if (CI->getOperand(0) == OldInduction &&
1378 it->getOpcode() == Instruction::Trunc) {
1379 Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
1381 Value *Broadcasted = getBroadcastInstrs(ScalarCast);
1382 for (unsigned Part = 0; Part < UF; ++Part)
1383 Entry[Part] = getConsecutiveVector(Broadcasted, VF * Part, false);
1386 /// Vectorize casts.
1387 Type *DestTy = VectorType::get(CI->getType()->getScalarType(), VF);
1389 VectorParts &A = getVectorValue(it->getOperand(0));
1390 for (unsigned Part = 0; Part < UF; ++Part)
1391 Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
1395 case Instruction::Call: {
1396 assert(isTriviallyVectorizableIntrinsic(it));
1397 Module *M = BB->getParent()->getParent();
1398 IntrinsicInst *II = cast<IntrinsicInst>(it);
1399 Intrinsic::ID ID = II->getIntrinsicID();
1400 for (unsigned Part = 0; Part < UF; ++Part) {
1401 SmallVector<Value*, 4> Args;
1402 for (unsigned i = 0, ie = II->getNumArgOperands(); i != ie; ++i) {
1403 VectorParts &Arg = getVectorValue(II->getArgOperand(i));
1404 Args.push_back(Arg[Part]);
1406 Type *Tys[] = { VectorType::get(II->getType()->getScalarType(), VF) };
1407 Function *F = Intrinsic::getDeclaration(M, ID, Tys);
1408 Entry[Part] = Builder.CreateCall(F, Args);
1414 // All other instructions are unsupported. Scalarize them.
1415 scalarizeInstruction(it);
1418 }// end of for_each instr.
1421 void InnerLoopVectorizer::updateAnalysis() {
1422 // Forget the original basic block.
1423 SE->forgetLoop(OrigLoop);
1425 // Update the dominator tree information.
1426 assert(DT->properlyDominates(LoopBypassBlock, LoopExitBlock) &&
1427 "Entry does not dominate exit.");
1429 DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlock);
1430 DT->addNewBlock(LoopVectorBody, LoopVectorPreHeader);
1431 DT->addNewBlock(LoopMiddleBlock, LoopBypassBlock);
1432 DT->addNewBlock(LoopScalarPreHeader, LoopMiddleBlock);
1433 DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
1434 DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
1436 DEBUG(DT->verifyAnalysis());
1439 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
1440 if (!EnableIfConversion)
1443 assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
1444 std::vector<BasicBlock*> &LoopBlocks = TheLoop->getBlocksVector();
1446 // Collect the blocks that need predication.
1447 for (unsigned i = 0, e = LoopBlocks.size(); i < e; ++i) {
1448 BasicBlock *BB = LoopBlocks[i];
1450 // We don't support switch statements inside loops.
1451 if (!isa<BranchInst>(BB->getTerminator()))
1454 // We must have at most two predecessors because we need to convert
1455 // all PHIs to selects.
1456 unsigned Preds = std::distance(pred_begin(BB), pred_end(BB));
1460 // We must be able to predicate all blocks that need to be predicated.
1461 if (blockNeedsPredication(BB) && !blockCanBePredicated(BB))
1465 // We can if-convert this loop.
1469 bool LoopVectorizationLegality::canVectorize() {
1470 assert(TheLoop->getLoopPreheader() && "No preheader!!");
1472 // We can only vectorize innermost loops.
1473 if (TheLoop->getSubLoopsVector().size())
1476 // We must have a single backedge.
1477 if (TheLoop->getNumBackEdges() != 1)
1480 // We must have a single exiting block.
1481 if (!TheLoop->getExitingBlock())
1484 unsigned NumBlocks = TheLoop->getNumBlocks();
1486 // Check if we can if-convert non single-bb loops.
1487 if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
1488 DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
1492 // We need to have a loop header.
1493 BasicBlock *Latch = TheLoop->getLoopLatch();
1494 DEBUG(dbgs() << "LV: Found a loop: " <<
1495 TheLoop->getHeader()->getName() << "\n");
1497 // ScalarEvolution needs to be able to find the exit count.
1498 const SCEV *ExitCount = SE->getExitCount(TheLoop, Latch);
1499 if (ExitCount == SE->getCouldNotCompute()) {
1500 DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
1504 // Do not loop-vectorize loops with a tiny trip count.
1505 unsigned TC = SE->getSmallConstantTripCount(TheLoop, Latch);
1506 if (TC > 0u && TC < TinyTripCountThreshold) {
1507 DEBUG(dbgs() << "LV: Found a loop with a very small trip count. " <<
1508 "This loop is not worth vectorizing.\n");
1512 // Check if we can vectorize the instructions and CFG in this loop.
1513 if (!canVectorizeInstrs()) {
1514 DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
1518 // Go over each instruction and look at memory deps.
1519 if (!canVectorizeMemory()) {
1520 DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
1524 // Collect all of the variables that remain uniform after vectorization.
1525 collectLoopUniforms();
1527 DEBUG(dbgs() << "LV: We can vectorize this loop" <<
1528 (PtrRtCheck.Need ? " (with a runtime bound check)" : "")
1531 // Okay! We can vectorize. At this point we don't have any other mem analysis
1532 // which may limit our maximum vectorization factor, so just return true with
1537 bool LoopVectorizationLegality::canVectorizeInstrs() {
1538 BasicBlock *PreHeader = TheLoop->getLoopPreheader();
1539 BasicBlock *Header = TheLoop->getHeader();
1541 // For each block in the loop.
1542 for (Loop::block_iterator bb = TheLoop->block_begin(),
1543 be = TheLoop->block_end(); bb != be; ++bb) {
1545 // Scan the instructions in the block and look for hazards.
1546 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
1549 if (PHINode *Phi = dyn_cast<PHINode>(it)) {
1550 // This should not happen because the loop should be normalized.
1551 if (Phi->getNumIncomingValues() != 2) {
1552 DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
1556 // Check that this PHI type is allowed.
1557 if (!Phi->getType()->isIntegerTy() &&
1558 !Phi->getType()->isPointerTy()) {
1559 DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
1563 // If this PHINode is not in the header block, then we know that we
1564 // can convert it to select during if-conversion. No need to check if
1565 // the PHIs in this block are induction or reduction variables.
1569 // This is the value coming from the preheader.
1570 Value *StartValue = Phi->getIncomingValueForBlock(PreHeader);
1571 // Check if this is an induction variable.
1572 InductionKind IK = isInductionVariable(Phi);
1574 if (NoInduction != IK) {
1575 // Int inductions are special because we only allow one IV.
1576 if (IK == IntInduction) {
1578 DEBUG(dbgs() << "LV: Found too many inductions."<< *Phi <<"\n");
1584 DEBUG(dbgs() << "LV: Found an induction variable.\n");
1585 Inductions[Phi] = InductionInfo(StartValue, IK);
1589 if (AddReductionVar(Phi, IntegerAdd)) {
1590 DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
1593 if (AddReductionVar(Phi, IntegerMult)) {
1594 DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n");
1597 if (AddReductionVar(Phi, IntegerOr)) {
1598 DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n");
1601 if (AddReductionVar(Phi, IntegerAnd)) {
1602 DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n");
1605 if (AddReductionVar(Phi, IntegerXor)) {
1606 DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n");
1610 DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
1612 }// end of PHI handling
1614 // We still don't handle functions.
1615 CallInst *CI = dyn_cast<CallInst>(it);
1616 if (CI && !isTriviallyVectorizableIntrinsic(it)) {
1617 DEBUG(dbgs() << "LV: Found a call site.\n");
1621 // Check that the instruction return type is vectorizable.
1622 if (!VectorType::isValidElementType(it->getType()) &&
1623 !it->getType()->isVoidTy()) {
1624 DEBUG(dbgs() << "LV: Found unvectorizable type." << "\n");
1628 // Check that the stored type is vectorizable.
1629 if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
1630 Type *T = ST->getValueOperand()->getType();
1631 if (!VectorType::isValidElementType(T))
1635 // Reduction instructions are allowed to have exit users.
1636 // All other instructions must not have external users.
1637 if (!AllowedExit.count(it))
1638 //Check that all of the users of the loop are inside the BB.
1639 for (Value::use_iterator I = it->use_begin(), E = it->use_end();
1641 Instruction *U = cast<Instruction>(*I);
1642 // This user may be a reduction exit value.
1643 if (!TheLoop->contains(U)) {
1644 DEBUG(dbgs() << "LV: Found an outside user for : "<< *U << "\n");
1653 DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
1654 assert(getInductionVars()->size() && "No induction variables");
1660 void LoopVectorizationLegality::collectLoopUniforms() {
1661 // We now know that the loop is vectorizable!
1662 // Collect variables that will remain uniform after vectorization.
1663 std::vector<Value*> Worklist;
1664 BasicBlock *Latch = TheLoop->getLoopLatch();
1666 // Start with the conditional branch and walk up the block.
1667 Worklist.push_back(Latch->getTerminator()->getOperand(0));
1669 while (Worklist.size()) {
1670 Instruction *I = dyn_cast<Instruction>(Worklist.back());
1671 Worklist.pop_back();
1673 // Look at instructions inside this loop.
1674 // Stop when reaching PHI nodes.
1675 // TODO: we need to follow values all over the loop, not only in this block.
1676 if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
1679 // This is a known uniform.
1682 // Insert all operands.
1683 for (int i = 0, Op = I->getNumOperands(); i < Op; ++i) {
1684 Worklist.push_back(I->getOperand(i));
1689 bool LoopVectorizationLegality::canVectorizeMemory() {
1690 typedef SmallVector<Value*, 16> ValueVector;
1691 typedef SmallPtrSet<Value*, 16> ValueSet;
1692 // Holds the Load and Store *instructions*.
1695 PtrRtCheck.Pointers.clear();
1696 PtrRtCheck.Need = false;
1699 for (Loop::block_iterator bb = TheLoop->block_begin(),
1700 be = TheLoop->block_end(); bb != be; ++bb) {
1702 // Scan the BB and collect legal loads and stores.
1703 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
1706 // If this is a load, save it. If this instruction can read from memory
1707 // but is not a load, then we quit. Notice that we don't handle function
1708 // calls that read or write.
1709 if (it->mayReadFromMemory()) {
1710 LoadInst *Ld = dyn_cast<LoadInst>(it);
1711 if (!Ld) return false;
1712 if (!Ld->isSimple()) {
1713 DEBUG(dbgs() << "LV: Found a non-simple load.\n");
1716 Loads.push_back(Ld);
1720 // Save 'store' instructions. Abort if other instructions write to memory.
1721 if (it->mayWriteToMemory()) {
1722 StoreInst *St = dyn_cast<StoreInst>(it);
1723 if (!St) return false;
1724 if (!St->isSimple()) {
1725 DEBUG(dbgs() << "LV: Found a non-simple store.\n");
1728 Stores.push_back(St);
1733 // Now we have two lists that hold the loads and the stores.
1734 // Next, we find the pointers that they use.
1736 // Check if we see any stores. If there are no stores, then we don't
1737 // care if the pointers are *restrict*.
1738 if (!Stores.size()) {
1739 DEBUG(dbgs() << "LV: Found a read-only loop!\n");
1743 // Holds the read and read-write *pointers* that we find.
1745 ValueVector ReadWrites;
1747 // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
1748 // multiple times on the same object. If the ptr is accessed twice, once
1749 // for read and once for write, it will only appear once (on the write
1750 // list). This is okay, since we are going to check for conflicts between
1751 // writes and between reads and writes, but not between reads and reads.
1754 ValueVector::iterator I, IE;
1755 for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
1756 StoreInst *ST = cast<StoreInst>(*I);
1757 Value* Ptr = ST->getPointerOperand();
1759 if (isUniform(Ptr)) {
1760 DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
1764 // If we did *not* see this pointer before, insert it to
1765 // the read-write list. At this phase it is only a 'write' list.
1766 if (Seen.insert(Ptr))
1767 ReadWrites.push_back(Ptr);
1770 for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
1771 LoadInst *LD = cast<LoadInst>(*I);
1772 Value* Ptr = LD->getPointerOperand();
1773 // If we did *not* see this pointer before, insert it to the
1774 // read list. If we *did* see it before, then it is already in
1775 // the read-write list. This allows us to vectorize expressions
1776 // such as A[i] += x; Because the address of A[i] is a read-write
1777 // pointer. This only works if the index of A[i] is consecutive.
1778 // If the address of i is unknown (for example A[B[i]]) then we may
1779 // read a few words, modify, and write a few words, and some of the
1780 // words may be written to the same address.
1781 if (Seen.insert(Ptr) || 0 == isConsecutivePtr(Ptr))
1782 Reads.push_back(Ptr);
1785 // If we write (or read-write) to a single destination and there are no
1786 // other reads in this loop then is it safe to vectorize.
1787 if (ReadWrites.size() == 1 && Reads.size() == 0) {
1788 DEBUG(dbgs() << "LV: Found a write-only loop!\n");
1792 // Find pointers with computable bounds. We are going to use this information
1793 // to place a runtime bound check.
1794 bool CanDoRT = true;
1795 for (I = ReadWrites.begin(), IE = ReadWrites.end(); I != IE; ++I)
1796 if (hasComputableBounds(*I)) {
1797 PtrRtCheck.insert(SE, TheLoop, *I);
1798 DEBUG(dbgs() << "LV: Found a runtime check ptr:" << **I <<"\n");
1803 for (I = Reads.begin(), IE = Reads.end(); I != IE; ++I)
1804 if (hasComputableBounds(*I)) {
1805 PtrRtCheck.insert(SE, TheLoop, *I);
1806 DEBUG(dbgs() << "LV: Found a runtime check ptr:" << **I <<"\n");
1812 // Check that we did not collect too many pointers or found a
1813 // unsizeable pointer.
1814 if (!CanDoRT || PtrRtCheck.Pointers.size() > RuntimeMemoryCheckThreshold) {
1820 DEBUG(dbgs() << "LV: We can perform a memory runtime check if needed.\n");
1823 bool NeedRTCheck = false;
1825 // Now that the pointers are in two lists (Reads and ReadWrites), we
1826 // can check that there are no conflicts between each of the writes and
1827 // between the writes to the reads.
1828 ValueSet WriteObjects;
1829 ValueVector TempObjects;
1831 // Check that the read-writes do not conflict with other read-write
1833 bool AllWritesIdentified = true;
1834 for (I = ReadWrites.begin(), IE = ReadWrites.end(); I != IE; ++I) {
1835 GetUnderlyingObjects(*I, TempObjects, DL);
1836 for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end();
1838 if (!isIdentifiedObject(*it)) {
1839 DEBUG(dbgs() << "LV: Found an unidentified write ptr:"<< **it <<"\n");
1841 AllWritesIdentified = false;
1843 if (!WriteObjects.insert(*it)) {
1844 DEBUG(dbgs() << "LV: Found a possible write-write reorder:"
1849 TempObjects.clear();
1852 /// Check that the reads don't conflict with the read-writes.
1853 for (I = Reads.begin(), IE = Reads.end(); I != IE; ++I) {
1854 GetUnderlyingObjects(*I, TempObjects, DL);
1855 for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end();
1857 // If all of the writes are identified then we don't care if the read
1858 // pointer is identified or not.
1859 if (!AllWritesIdentified && !isIdentifiedObject(*it)) {
1860 DEBUG(dbgs() << "LV: Found an unidentified read ptr:"<< **it <<"\n");
1863 if (WriteObjects.count(*it)) {
1864 DEBUG(dbgs() << "LV: Found a possible read/write reorder:"
1869 TempObjects.clear();
1872 PtrRtCheck.Need = NeedRTCheck;
1873 if (NeedRTCheck && !CanDoRT) {
1874 DEBUG(dbgs() << "LV: We can't vectorize because we can't find " <<
1875 "the array bounds.\n");
1880 DEBUG(dbgs() << "LV: We "<< (NeedRTCheck ? "" : "don't") <<
1881 " need a runtime memory check.\n");
1885 bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi,
1886 ReductionKind Kind) {
1887 if (Phi->getNumIncomingValues() != 2)
1890 // Reduction variables are only found in the loop header block.
1891 if (Phi->getParent() != TheLoop->getHeader())
1894 // Obtain the reduction start value from the value that comes from the loop
1896 Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
1898 // ExitInstruction is the single value which is used outside the loop.
1899 // We only allow for a single reduction value to be used outside the loop.
1900 // This includes users of the reduction, variables (which form a cycle
1901 // which ends in the phi node).
1902 Instruction *ExitInstruction = 0;
1904 // Iter is our iterator. We start with the PHI node and scan for all of the
1905 // users of this instruction. All users must be instructions that can be
1906 // used as reduction variables (such as ADD). We may have a single
1907 // out-of-block user. The cycle must end with the original PHI.
1908 Instruction *Iter = Phi;
1910 // If the instruction has no users then this is a broken
1911 // chain and can't be a reduction variable.
1912 if (Iter->use_empty())
1915 // Did we find a user inside this loop already ?
1916 bool FoundInBlockUser = false;
1917 // Did we reach the initial PHI node already ?
1918 bool FoundStartPHI = false;
1920 // For each of the *users* of iter.
1921 for (Value::use_iterator it = Iter->use_begin(), e = Iter->use_end();
1923 Instruction *U = cast<Instruction>(*it);
1924 // We already know that the PHI is a user.
1926 FoundStartPHI = true;
1930 // Check if we found the exit user.
1931 BasicBlock *Parent = U->getParent();
1932 if (!TheLoop->contains(Parent)) {
1933 // Exit if you find multiple outside users.
1934 if (ExitInstruction != 0)
1936 ExitInstruction = Iter;
1939 // We allow in-loop PHINodes which are not the original reduction PHI
1940 // node. If this PHI is the only user of Iter (happens in IF w/ no ELSE
1941 // structure) then don't skip this PHI.
1942 if (isa<PHINode>(Iter) && isa<PHINode>(U) &&
1943 U->getParent() != TheLoop->getHeader() &&
1944 TheLoop->contains(U) &&
1945 Iter->getNumUses() > 1)
1948 // We can't have multiple inside users.
1949 if (FoundInBlockUser)
1951 FoundInBlockUser = true;
1953 // Any reduction instr must be of one of the allowed kinds.
1954 if (!isReductionInstr(U, Kind))
1957 // Reductions of instructions such as Div, and Sub is only
1958 // possible if the LHS is the reduction variable.
1959 if (!U->isCommutative() && U->getOperand(0) != Iter)
1965 // We found a reduction var if we have reached the original
1966 // phi node and we only have a single instruction with out-of-loop
1968 if (FoundStartPHI && ExitInstruction) {
1969 // This instruction is allowed to have out-of-loop users.
1970 AllowedExit.insert(ExitInstruction);
1972 // Save the description of this reduction variable.
1973 ReductionDescriptor RD(RdxStart, ExitInstruction, Kind);
1974 Reductions[Phi] = RD;
1978 // If we've reached the start PHI but did not find an outside user then
1979 // this is dead code. Abort.
1986 LoopVectorizationLegality::isReductionInstr(Instruction *I,
1987 ReductionKind Kind) {
1988 switch (I->getOpcode()) {
1991 case Instruction::PHI:
1994 case Instruction::Sub:
1995 case Instruction::Add:
1996 return Kind == IntegerAdd;
1997 case Instruction::SDiv:
1998 case Instruction::UDiv:
1999 case Instruction::Mul:
2000 return Kind == IntegerMult;
2001 case Instruction::And:
2002 return Kind == IntegerAnd;
2003 case Instruction::Or:
2004 return Kind == IntegerOr;
2005 case Instruction::Xor:
2006 return Kind == IntegerXor;
2010 LoopVectorizationLegality::InductionKind
2011 LoopVectorizationLegality::isInductionVariable(PHINode *Phi) {
2012 Type *PhiTy = Phi->getType();
2013 // We only handle integer and pointer inductions variables.
2014 if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
2017 // Check that the PHI is consecutive and starts at zero.
2018 const SCEV *PhiScev = SE->getSCEV(Phi);
2019 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
2021 DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
2024 const SCEV *Step = AR->getStepRecurrence(*SE);
2026 // Integer inductions need to have a stride of one.
2027 if (PhiTy->isIntegerTy()) {
2029 return IntInduction;
2030 if (Step->isAllOnesValue())
2031 return ReverseIntInduction;
2035 // Calculate the pointer stride and check if it is consecutive.
2036 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
2040 assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
2041 uint64_t Size = DL->getTypeAllocSize(PhiTy->getPointerElementType());
2042 if (C->getValue()->equalsInt(Size))
2043 return PtrInduction;
2048 bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
2049 Value *In0 = const_cast<Value*>(V);
2050 PHINode *PN = dyn_cast_or_null<PHINode>(In0);
2054 return Inductions.count(PN);
2057 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) {
2058 assert(TheLoop->contains(BB) && "Unknown block used");
2060 // Blocks that do not dominate the latch need predication.
2061 BasicBlock* Latch = TheLoop->getLoopLatch();
2062 return !DT->dominates(BB, Latch);
2065 bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB) {
2066 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2067 // We don't predicate loads/stores at the moment.
2068 if (it->mayReadFromMemory() || it->mayWriteToMemory() || it->mayThrow())
2071 // The instructions below can trap.
2072 switch (it->getOpcode()) {
2074 case Instruction::UDiv:
2075 case Instruction::SDiv:
2076 case Instruction::URem:
2077 case Instruction::SRem:
2085 bool LoopVectorizationLegality::hasComputableBounds(Value *Ptr) {
2086 const SCEV *PhiScev = SE->getSCEV(Ptr);
2087 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
2091 return AR->isAffine();
2095 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize,
2097 if (OptForSize && Legal->getRuntimePointerCheck()->Need) {
2098 DEBUG(dbgs() << "LV: Aborting. Runtime ptr check is required in Os.\n");
2102 // Find the trip count.
2103 unsigned TC = SE->getSmallConstantTripCount(TheLoop, TheLoop->getLoopLatch());
2104 DEBUG(dbgs() << "LV: Found trip count:"<<TC<<"\n");
2106 unsigned VF = MaxVectorSize;
2108 // If we optimize the program for size, avoid creating the tail loop.
2110 // If we are unable to calculate the trip count then don't try to vectorize.
2112 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
2116 // Find the maximum SIMD width that can fit within the trip count.
2117 VF = TC % MaxVectorSize;
2122 // If the trip count that we found modulo the vectorization factor is not
2123 // zero then we require a tail.
2125 DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
2131 assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
2132 DEBUG(dbgs() << "LV: Using user VF "<<UserVF<<".\n");
2138 DEBUG(dbgs() << "LV: No vector target information. Not vectorizing. \n");
2142 float Cost = expectedCost(1);
2144 DEBUG(dbgs() << "LV: Scalar loop costs: "<< (int)Cost << ".\n");
2145 for (unsigned i=2; i <= VF; i*=2) {
2146 // Notice that the vector loop needs to be executed less times, so
2147 // we need to divide the cost of the vector loops by the width of
2148 // the vector elements.
2149 float VectorCost = expectedCost(i) / (float)i;
2150 DEBUG(dbgs() << "LV: Vector loop of width "<< i << " costs: " <<
2151 (int)VectorCost << ".\n");
2152 if (VectorCost < Cost) {
2158 DEBUG(dbgs() << "LV: Selecting VF = : "<< Width << ".\n");
2163 LoopVectorizationCostModel::selectUnrollFactor(bool OptForSize,
2165 // Use the user preference, unless 'auto' is selected.
2169 // When we optimize for size we don't unroll.
2173 unsigned TargetVectorRegisters = VTTI->getNumberOfRegisters(true);
2174 DEBUG(dbgs() << "LV: The target has " << TargetVectorRegisters <<
2175 " vector registers\n");
2177 LoopVectorizationCostModel::RegisterUsage R = calculateRegisterUsage();
2178 // We divide by these constants so assume that we have at least one
2179 // instruction that uses at least one register.
2180 R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
2181 R.NumInstructions = std::max(R.NumInstructions, 1U);
2183 // We calculate the unroll factor using the following formula.
2184 // Subtract the number of loop invariants from the number of available
2185 // registers. These registers are used by all of the unrolled instances.
2186 // Next, divide the remaining registers by the number of registers that is
2187 // required by the loop, in order to estimate how many parallel instances
2188 // fit without causing spills.
2189 unsigned UF = (TargetVectorRegisters - R.LoopInvariantRegs) / R.MaxLocalUsers;
2191 // We don't want to unroll the loops to the point where they do not fit into
2192 // the decoded cache. Assume that we only allow 32 IR instructions.
2193 UF = std::min(UF, (32 / R.NumInstructions));
2195 // Clamp the unroll factor ranges to reasonable factors.
2196 if (UF > MaxUnrollSize)
2204 LoopVectorizationCostModel::RegisterUsage
2205 LoopVectorizationCostModel::calculateRegisterUsage() {
2206 // This function calculates the register usage by measuring the highest number
2207 // of values that are alive at a single location. Obviously, this is a very
2208 // rough estimation. We scan the loop in a topological order in order and
2209 // assign a number to each instruction. We use RPO to ensure that defs are
2210 // met before their users. We assume that each instruction that has in-loop
2211 // users starts an interval. We record every time that an in-loop value is
2212 // used, so we have a list of the first and last occurrences of each
2213 // instruction. Next, we transpose this data structure into a multi map that
2214 // holds the list of intervals that *end* at a specific location. This multi
2215 // map allows us to perform a linear search. We scan the instructions linearly
2216 // and record each time that a new interval starts, by placing it in a set.
2217 // If we find this value in the multi-map then we remove it from the set.
2218 // The max register usage is the maximum size of the set.
2219 // We also search for instructions that are defined outside the loop, but are
2220 // used inside the loop. We need this number separately from the max-interval
2221 // usage number because when we unroll, loop-invariant values do not take
2223 LoopBlocksDFS DFS(TheLoop);
2227 R.NumInstructions = 0;
2229 // Each 'key' in the map opens a new interval. The values
2230 // of the map are the index of the 'last seen' usage of the
2231 // instruction that is the key.
2232 typedef DenseMap<Instruction*, unsigned> IntervalMap;
2233 // Maps instruction to its index.
2234 DenseMap<unsigned, Instruction*> IdxToInstr;
2235 // Marks the end of each interval.
2236 IntervalMap EndPoint;
2237 // Saves the list of instruction indices that are used in the loop.
2238 SmallSet<Instruction*, 8> Ends;
2239 // Saves the list of values that are used in the loop but are
2240 // defined outside the loop, such as arguments and constants.
2241 SmallPtrSet<Value*, 8> LoopInvariants;
2244 for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
2245 be = DFS.endRPO(); bb != be; ++bb) {
2246 R.NumInstructions += (*bb)->size();
2247 for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
2249 Instruction *I = it;
2250 IdxToInstr[Index++] = I;
2252 // Save the end location of each USE.
2253 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
2254 Value *U = I->getOperand(i);
2255 Instruction *Instr = dyn_cast<Instruction>(U);
2257 // Ignore non-instruction values such as arguments, constants, etc.
2258 if (!Instr) continue;
2260 // If this instruction is outside the loop then record it and continue.
2261 if (!TheLoop->contains(Instr)) {
2262 LoopInvariants.insert(Instr);
2266 // Overwrite previous end points.
2267 EndPoint[Instr] = Index;
2273 // Saves the list of intervals that end with the index in 'key'.
2274 typedef SmallVector<Instruction*, 2> InstrList;
2275 DenseMap<unsigned, InstrList> TransposeEnds;
2277 // Transpose the EndPoints to a list of values that end at each index.
2278 for (IntervalMap::iterator it = EndPoint.begin(), e = EndPoint.end();
2280 TransposeEnds[it->second].push_back(it->first);
2282 SmallSet<Instruction*, 8> OpenIntervals;
2283 unsigned MaxUsage = 0;
2286 DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
2287 for (unsigned int i = 0; i < Index; ++i) {
2288 Instruction *I = IdxToInstr[i];
2289 // Ignore instructions that are never used within the loop.
2290 if (!Ends.count(I)) continue;
2292 // Remove all of the instructions that end at this location.
2293 InstrList &List = TransposeEnds[i];
2294 for (unsigned int j=0, e = List.size(); j < e; ++j)
2295 OpenIntervals.erase(List[j]);
2297 // Count the number of live interals.
2298 MaxUsage = std::max(MaxUsage, OpenIntervals.size());
2300 DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # " <<
2301 OpenIntervals.size() <<"\n");
2303 // Add the current instruction to the list of open intervals.
2304 OpenIntervals.insert(I);
2307 unsigned Invariant = LoopInvariants.size();
2308 DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsage << " \n");
2309 DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << " \n");
2310 DEBUG(dbgs() << "LV(REG): LoopSize: " << R.NumInstructions << " \n");
2312 R.LoopInvariantRegs = Invariant;
2313 R.MaxLocalUsers = MaxUsage;
2317 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
2321 for (Loop::block_iterator bb = TheLoop->block_begin(),
2322 be = TheLoop->block_end(); bb != be; ++bb) {
2323 unsigned BlockCost = 0;
2324 BasicBlock *BB = *bb;
2326 // For each instruction in the old loop.
2327 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2328 unsigned C = getInstructionCost(it, VF);
2330 DEBUG(dbgs() << "LV: Found an estimated cost of "<< C <<" for VF " <<
2331 VF << " For instruction: "<< *it << "\n");
2334 // We assume that if-converted blocks have a 50% chance of being executed.
2335 // When the code is scalar then some of the blocks are avoided due to CF.
2336 // When the code is vectorized we execute all code paths.
2337 if (Legal->blockNeedsPredication(*bb) && VF == 1)
2347 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
2348 assert(VTTI && "Invalid vector target transformation info");
2350 // If we know that this instruction will remain uniform, check the cost of
2351 // the scalar version.
2352 if (Legal->isUniformAfterVectorization(I))
2355 Type *RetTy = I->getType();
2356 Type *VectorTy = ToVectorTy(RetTy, VF);
2358 // TODO: We need to estimate the cost of intrinsic calls.
2359 switch (I->getOpcode()) {
2360 case Instruction::GetElementPtr:
2361 // We mark this instruction as zero-cost because scalar GEPs are usually
2362 // lowered to the intruction addressing mode. At the moment we don't
2363 // generate vector geps.
2365 case Instruction::Br: {
2366 return VTTI->getCFInstrCost(I->getOpcode());
2368 case Instruction::PHI:
2369 //TODO: IF-converted IFs become selects.
2371 case Instruction::Add:
2372 case Instruction::FAdd:
2373 case Instruction::Sub:
2374 case Instruction::FSub:
2375 case Instruction::Mul:
2376 case Instruction::FMul:
2377 case Instruction::UDiv:
2378 case Instruction::SDiv:
2379 case Instruction::FDiv:
2380 case Instruction::URem:
2381 case Instruction::SRem:
2382 case Instruction::FRem:
2383 case Instruction::Shl:
2384 case Instruction::LShr:
2385 case Instruction::AShr:
2386 case Instruction::And:
2387 case Instruction::Or:
2388 case Instruction::Xor:
2389 return VTTI->getArithmeticInstrCost(I->getOpcode(), VectorTy);
2390 case Instruction::Select: {
2391 SelectInst *SI = cast<SelectInst>(I);
2392 const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
2393 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
2394 Type *CondTy = SI->getCondition()->getType();
2396 CondTy = VectorType::get(CondTy, VF);
2398 return VTTI->getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
2400 case Instruction::ICmp:
2401 case Instruction::FCmp: {
2402 Type *ValTy = I->getOperand(0)->getType();
2403 VectorTy = ToVectorTy(ValTy, VF);
2404 return VTTI->getCmpSelInstrCost(I->getOpcode(), VectorTy);
2406 case Instruction::Store: {
2407 StoreInst *SI = cast<StoreInst>(I);
2408 Type *ValTy = SI->getValueOperand()->getType();
2409 VectorTy = ToVectorTy(ValTy, VF);
2412 return VTTI->getMemoryOpCost(I->getOpcode(), VectorTy,
2414 SI->getPointerAddressSpace());
2416 // Scalarized stores.
2417 int Stride = Legal->isConsecutivePtr(SI->getPointerOperand());
2418 bool Reverse = Stride < 0;
2422 // The cost of extracting from the value vector and pointer vector.
2423 Type *PtrTy = ToVectorTy(I->getOperand(0)->getType(), VF);
2424 for (unsigned i = 0; i < VF; ++i) {
2425 Cost += VTTI->getVectorInstrCost(Instruction::ExtractElement,
2427 Cost += VTTI->getVectorInstrCost(Instruction::ExtractElement,
2431 // The cost of the scalar stores.
2432 Cost += VF * VTTI->getMemoryOpCost(I->getOpcode(),
2433 ValTy->getScalarType(),
2435 SI->getPointerAddressSpace());
2440 unsigned Cost = VTTI->getMemoryOpCost(I->getOpcode(), VectorTy,
2442 SI->getPointerAddressSpace());
2444 Cost += VTTI->getShuffleCost(VectorTargetTransformInfo::Reverse,
2448 case Instruction::Load: {
2449 LoadInst *LI = cast<LoadInst>(I);
2452 return VTTI->getMemoryOpCost(I->getOpcode(), VectorTy,
2454 LI->getPointerAddressSpace());
2456 // Scalarized loads.
2457 int Stride = Legal->isConsecutivePtr(LI->getPointerOperand());
2458 bool Reverse = Stride < 0;
2461 Type *PtrTy = ToVectorTy(I->getOperand(0)->getType(), VF);
2463 // The cost of extracting from the pointer vector.
2464 for (unsigned i = 0; i < VF; ++i)
2465 Cost += VTTI->getVectorInstrCost(Instruction::ExtractElement,
2468 // The cost of inserting data to the result vector.
2469 for (unsigned i = 0; i < VF; ++i)
2470 Cost += VTTI->getVectorInstrCost(Instruction::InsertElement,
2473 // The cost of the scalar stores.
2474 Cost += VF * VTTI->getMemoryOpCost(I->getOpcode(),
2475 RetTy->getScalarType(),
2477 LI->getPointerAddressSpace());
2482 unsigned Cost = VTTI->getMemoryOpCost(I->getOpcode(), VectorTy,
2484 LI->getPointerAddressSpace());
2486 Cost += VTTI->getShuffleCost(VectorTargetTransformInfo::Reverse,
2490 case Instruction::ZExt:
2491 case Instruction::SExt:
2492 case Instruction::FPToUI:
2493 case Instruction::FPToSI:
2494 case Instruction::FPExt:
2495 case Instruction::PtrToInt:
2496 case Instruction::IntToPtr:
2497 case Instruction::SIToFP:
2498 case Instruction::UIToFP:
2499 case Instruction::Trunc:
2500 case Instruction::FPTrunc:
2501 case Instruction::BitCast: {
2502 // We optimize the truncation of induction variable.
2503 // The cost of these is the same as the scalar operation.
2504 if (I->getOpcode() == Instruction::Trunc &&
2505 Legal->isInductionVariable(I->getOperand(0)))
2506 return VTTI->getCastInstrCost(I->getOpcode(), I->getType(),
2507 I->getOperand(0)->getType());
2509 Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
2510 return VTTI->getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
2512 case Instruction::Call: {
2513 assert(isTriviallyVectorizableIntrinsic(I));
2514 IntrinsicInst *II = cast<IntrinsicInst>(I);
2515 Type *RetTy = ToVectorTy(II->getType(), VF);
2516 SmallVector<Type*, 4> Tys;
2517 for (unsigned i = 0, ie = II->getNumArgOperands(); i != ie; ++i)
2518 Tys.push_back(ToVectorTy(II->getArgOperand(i)->getType(), VF));
2519 return VTTI->getIntrinsicInstrCost(II->getIntrinsicID(), RetTy, Tys);
2522 // We are scalarizing the instruction. Return the cost of the scalar
2523 // instruction, plus the cost of insert and extract into vector
2524 // elements, times the vector width.
2527 if (!RetTy->isVoidTy() && VF != 1) {
2528 unsigned InsCost = VTTI->getVectorInstrCost(Instruction::InsertElement,
2530 unsigned ExtCost = VTTI->getVectorInstrCost(Instruction::ExtractElement,
2533 // The cost of inserting the results plus extracting each one of the
2535 Cost += VF * (InsCost + ExtCost * I->getNumOperands());
2538 // The cost of executing VF copies of the scalar instruction. This opcode
2539 // is unknown. Assume that it is the same as 'mul'.
2540 Cost += VF * VTTI->getArithmeticInstrCost(Instruction::Mul, VectorTy);
2546 Type* LoopVectorizationCostModel::ToVectorTy(Type *Scalar, unsigned VF) {
2547 if (Scalar->isVoidTy() || VF == 1)
2549 return VectorType::get(Scalar, VF);
2552 char LoopVectorize::ID = 0;
2553 static const char lv_name[] = "Loop Vectorization";
2554 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
2555 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
2556 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
2557 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
2558 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
2561 Pass *createLoopVectorizePass() {
2562 return new LoopVectorize();