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 //===----------------------------------------------------------------------===//
10 // This is a simple loop vectorizer. We currently only support single block
11 // loops. We have a very simple and restrictive legality check: we need to read
12 // and write from disjoint memory locations. We still don't have a cost model.
13 // This pass has three parts:
14 // 1. The main loop pass that drives the different parts.
15 // 2. LoopVectorizationLegality - A helper class that checks for the legality
16 // of the vectorization.
17 // 3. SingleBlockLoopVectorizer - A helper class that performs the actual
18 // widening of instructions.
20 //===----------------------------------------------------------------------===//
21 #define LV_NAME "loop-vectorize"
22 #define DEBUG_TYPE LV_NAME
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/LLVMContext.h"
27 #include "llvm/Pass.h"
28 #include "llvm/Analysis/LoopPass.h"
29 #include "llvm/Value.h"
30 #include "llvm/Function.h"
31 #include "llvm/Analysis/Verifier.h"
32 #include "llvm/Module.h"
33 #include "llvm/Type.h"
34 #include "llvm/ADT/SmallVector.h"
35 #include "llvm/ADT/StringExtras.h"
36 #include "llvm/Analysis/AliasAnalysis.h"
37 #include "llvm/Analysis/AliasSetTracker.h"
38 #include "llvm/Transforms/Scalar.h"
39 #include "llvm/Analysis/ScalarEvolution.h"
40 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
41 #include "llvm/Analysis/ScalarEvolutionExpander.h"
42 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
43 #include "llvm/Analysis/ValueTracking.h"
44 #include "llvm/Analysis/LoopInfo.h"
45 #include "llvm/Support/CommandLine.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/raw_ostream.h"
48 #include "llvm/DataLayout.h"
49 #include "llvm/Transforms/Utils/Local.h"
53 static cl::opt<unsigned>
54 DefaultVectorizationFactor("default-loop-vectorize-width",
55 cl::init(4), cl::Hidden,
56 cl::desc("Set the default loop vectorization width"));
60 /// Vectorize a simple loop. This class performs the widening of simple single
61 /// basic block loops into vectors. It does not perform any
62 /// vectorization-legality checks, and just does it. It widens the vectors
63 /// to a given vectorization factor (VF).
64 class SingleBlockLoopVectorizer {
67 SingleBlockLoopVectorizer(Loop *OrigLoop, ScalarEvolution *Se, LoopInfo *Li,
68 LPPassManager *Lpm, unsigned VecWidth):
69 Orig(OrigLoop), SE(Se), LI(Li), LPM(Lpm), VF(VecWidth),
70 Builder(0), Induction(0), OldInduction(0) { }
72 ~SingleBlockLoopVectorizer() {
76 // Perform the actual loop widening (vectorization).
78 ///Create a new empty loop. Unlink the old loop and connect the new one.
80 /// Widen each instruction in the old loop to a new one in the new loop.
82 // register the new loop.
87 /// Create an empty loop, based on the loop ranges of the old loop.
88 void createEmptyLoop();
89 /// Copy and widen the instructions from the old loop.
91 /// Insert the new loop to the loop hierarchy and pass manager.
94 /// This instruction is un-vectorizable. Implement it as a sequence
96 void scalarizeInstruction(Instruction *Instr);
98 /// Create a broadcast instruction. This method generates a broadcast
99 /// instruction (shuffle) for loop invariant values and for the induction
100 /// value. If this is the induction variable then we extend it to N, N+1, ...
101 /// this is needed because each iteration in the loop corresponds to a SIMD
103 Value *getBroadcastInstrs(Value *V);
105 /// This is a helper function used by getBroadcastInstrs. It adds 0, 1, 2 ..
106 /// for each element in the vector. Starting from zero.
107 Value *getConsecutiveVector(Value* Val);
109 /// Check that the GEP operands are all uniform except for the last index
110 /// which has to be the induction variable.
111 bool isConsecutiveGep(GetElementPtrInst *Gep);
113 /// When we go over instructions in the basic block we rely on previous
114 /// values within the current basic block or on loop invariant values.
115 /// When we widen (vectorize) values we place them in the map. If the values
116 /// are not within the map, they have to be loop invariant, so we simply
117 /// broadcast them into a vector.
118 Value *getVectorValue(Value *V);
120 typedef DenseMap<Value*, Value*> ValueMap;
122 /// The original loop.
124 // Scev analysis to use.
128 // Loop Pass Manager;
130 // The vectorization factor to use.
133 // The builder that we use
134 IRBuilder<> *Builder;
136 // --- Vectorization state ---
138 /// The new Induction variable which was added to the new block.
140 /// The induction variable of the old basic block.
141 PHINode *OldInduction;
142 // Maps scalars to widened vectors.
146 /// Perform the vectorization legality check. This class does not look at the
147 /// profitability of vectorization, only the legality. At the moment the checks
148 /// are very simple and focus on single basic block loops with a constant
149 /// iteration count and no reductions.
150 class LoopVectorizationLegality {
152 LoopVectorizationLegality(Loop *Lp, ScalarEvolution *Se, DataLayout *Dl):
153 TheLoop(Lp), SE(Se), DL(Dl) { }
155 /// Returns the maximum vectorization factor that we *can* use to vectorize
156 /// this loop. This does not mean that it is profitable to vectorize this
157 /// loop, only that it is legal to do so. This may be a large number. We
158 /// can vectorize to any SIMD width below this number.
159 unsigned getLoopMaxVF();
162 /// Check if a single basic block loop is vectorizable.
163 /// At this point we know that this is a loop with a constant trip count
164 /// and we only need to check individual instructions.
165 bool canVectorizeBlock(BasicBlock &BB);
167 // Check if a pointer value is known to be disjoint.
168 // Example: Alloca, Global, NoAlias.
169 bool isidentifiedSafeObject(Value* Val);
171 /// The loop that we evaluate.
175 /// DataLayout analysis.
179 struct LoopVectorize : public LoopPass {
180 static char ID; // Pass identification, replacement for typeid
182 LoopVectorize() : LoopPass(ID) {
183 initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
190 virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
191 // Only vectorize innermost loops.
195 SE = &getAnalysis<ScalarEvolution>();
196 DL = getAnalysisIfAvailable<DataLayout>();
197 LI = &getAnalysis<LoopInfo>();
199 DEBUG(dbgs() << "LV: Checking a loop in \"" <<
200 L->getHeader()->getParent()->getName() << "\"\n");
202 // Check if it is legal to vectorize the loop.
203 LoopVectorizationLegality LVL(L, SE, DL);
204 unsigned MaxVF = LVL.getLoopMaxVF();
206 // Check that we can vectorize using the chosen vectorization width.
207 if (MaxVF < DefaultVectorizationFactor) {
208 DEBUG(dbgs() << "LV: non-vectorizable MaxVF ("<< MaxVF << ").\n");
212 DEBUG(dbgs() << "LV: Found a vectorizable loop ("<< MaxVF << ").\n");
214 // If we decided that is is *legal* to vectorizer the loop. Do it.
215 SingleBlockLoopVectorizer LB(L, SE, LI, &LPM, DefaultVectorizationFactor);
218 DEBUG(verifyFunction(*L->getHeader()->getParent()));
222 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
223 LoopPass::getAnalysisUsage(AU);
224 AU.addRequiredID(LoopSimplifyID);
225 AU.addRequired<LoopInfo>();
226 AU.addRequired<ScalarEvolution>();
231 Value *SingleBlockLoopVectorizer::getBroadcastInstrs(Value *V) {
232 // Instructions that access the old induction variable
233 // actually want to get the new one.
234 if (V == OldInduction)
237 LLVMContext &C = V->getContext();
238 Type *VTy = VectorType::get(V->getType(), VF);
239 Type *I32 = IntegerType::getInt32Ty(C);
240 Constant *Zero = ConstantInt::get(I32, 0);
241 Value *Zeros = ConstantAggregateZero::get(VectorType::get(I32, VF));
242 Value *UndefVal = UndefValue::get(VTy);
243 // Insert the value into a new vector.
244 Value *SingleElem = Builder->CreateInsertElement(UndefVal, V, Zero);
245 // Broadcast the scalar into all locations in the vector.
246 Value *Shuf = Builder->CreateShuffleVector(SingleElem, UndefVal, Zeros,
248 // We are accessing the induction variable. Make sure to promote the
249 // index for each consecutive SIMD lane. This adds 0,1,2 ... to all lanes.
251 return getConsecutiveVector(Shuf);
255 Value *SingleBlockLoopVectorizer::getConsecutiveVector(Value* Val) {
256 assert(Val->getType()->isVectorTy() && "Must be a vector");
257 assert(Val->getType()->getScalarType()->isIntegerTy() &&
258 "Elem must be an integer");
260 Type *ITy = Val->getType()->getScalarType();
261 VectorType *Ty = cast<VectorType>(Val->getType());
262 unsigned VLen = Ty->getNumElements();
263 SmallVector<Constant*, 8> Indices;
265 // Create a vector of consecutive numbers from zero to VF.
266 for (unsigned i = 0; i < VLen; ++i)
267 Indices.push_back(ConstantInt::get(ITy, i));
269 // Add the consecutive indices to the vector value.
270 Constant *Cv = ConstantVector::get(Indices);
271 assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
272 return Builder->CreateAdd(Val, Cv, "induction");
276 bool SingleBlockLoopVectorizer::isConsecutiveGep(GetElementPtrInst *Gep) {
280 unsigned NumOperands = Gep->getNumOperands();
281 Value *LastIndex = Gep->getOperand(NumOperands - 1);
283 // Check that all of the gep indices are uniform except for the last.
284 for (unsigned i = 0; i < NumOperands - 1; ++i)
285 if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), Orig))
288 // We can emit wide load/stores only of the last index is the induction
290 const SCEV *Last = SE->getSCEV(LastIndex);
291 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
292 const SCEV *Step = AR->getStepRecurrence(*SE);
294 // The memory is consecutive because the last index is consecutive
295 // and all other indices are loop invariant.
303 Value *SingleBlockLoopVectorizer::getVectorValue(Value *V) {
304 // If we saved a vectorized copy of V, use it.
305 ValueMap::iterator it = WidenMap.find(V);
306 if (it != WidenMap.end())
309 // Broadcast V and save the value for future uses.
310 Value *B = getBroadcastInstrs(V);
315 void SingleBlockLoopVectorizer::scalarizeInstruction(Instruction *Instr) {
316 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
317 // Holds vector parameters or scalars, in case of uniform vals.
318 SmallVector<Value*, 8> Params;
320 // Find all of the vectorized parameters.
321 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
322 Value *SrcOp = Instr->getOperand(op);
324 // If we are accessing the old induction variable, use the new one.
325 if (SrcOp == OldInduction) {
326 Params.push_back(getBroadcastInstrs(Induction));
330 // Try using previously calculated values.
331 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
333 // If the src is an instruction that appeared earlier in the basic block
334 // then it should already be vectorized.
335 if (SrcInst && SrcInst->getParent() == Instr->getParent()) {
336 assert(WidenMap.count(SrcInst) && "Source operand is unavailable");
337 // The parameter is a vector value from earlier.
338 Params.push_back(WidenMap[SrcInst]);
340 // The parameter is a scalar from outside the loop. Maybe even a constant.
341 Params.push_back(SrcOp);
345 assert(Params.size() == Instr->getNumOperands() &&
346 "Invalid number of operands");
348 // Does this instruction return a value ?
349 bool IsVoidRetTy = Instr->getType()->isVoidTy();
350 Value *VecResults = 0;
352 // If we have a return value, create an empty vector. We place the scalarized
353 // instructions in this vector.
355 VecResults = UndefValue::get(VectorType::get(Instr->getType(), VF));
357 // For each scalar that we create.
358 for (unsigned i = 0; i < VF; ++i) {
359 Instruction *Cloned = Instr->clone();
361 Cloned->setName(Instr->getName() + ".cloned");
362 // Replace the operands of the cloned instrucions with extracted scalars.
363 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
364 Value *Op = Params[op];
365 // Param is a vector. Need to extract the right lane.
366 if (Op->getType()->isVectorTy())
367 Op = Builder->CreateExtractElement(Op, Builder->getInt32(i));
368 Cloned->setOperand(op, Op);
371 // Place the cloned scalar in the new loop.
372 Builder->Insert(Cloned);
374 // If the original scalar returns a value we need to place it in a vector
375 // so that future users will be able to use it.
377 VecResults = Builder->CreateInsertElement(VecResults, Cloned,
378 Builder->getInt32(i));
382 WidenMap[Instr] = VecResults;
385 void SingleBlockLoopVectorizer::createEmptyLoop() {
387 In this function we generate a new loop. The new loop will contain
388 the vectorized instructions while the old loop will continue to run the
391 [ ] <-- vector loop bypass.
394 | [ ] <-- vector pre header.
398 | [ ]_| <-- vector loop.
401 >[ ] <--- middle-block.
404 | [ ] <--- new preheader.
408 | [ ]_| <-- old scalar loop to handle remainder. ()
415 // This is the original scalar-loop preheader.
416 BasicBlock *BypassBlock = Orig->getLoopPreheader();
417 BasicBlock *ExitBlock = Orig->getExitBlock();
418 assert(ExitBlock && "Must have an exit block");
420 assert(Orig->getNumBlocks() == 1 && "Invalid loop");
421 assert(BypassBlock && "Invalid loop structure");
423 BasicBlock *VectorPH =
424 BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
425 BasicBlock *VecBody = VectorPH->splitBasicBlock(VectorPH->getTerminator(),
428 BasicBlock *MiddleBlock = VecBody->splitBasicBlock(VecBody->getTerminator(),
432 BasicBlock *ScalarPH =
433 MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(),
436 // Find the induction variable.
437 BasicBlock *OldBasicBlock = Orig->getHeader();
438 OldInduction = dyn_cast<PHINode>(OldBasicBlock->begin());
439 assert(OldInduction && "We must have a single phi node.");
440 Type *IdxTy = OldInduction->getType();
442 // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
444 Builder = new IRBuilder<>(VecBody);
445 Builder->SetInsertPoint(VecBody->getFirstInsertionPt());
447 // Generate the induction variable.
448 Induction = Builder->CreatePHI(IdxTy, 2, "index");
449 Constant *Zero = ConstantInt::get(IdxTy, 0);
450 Constant *Step = ConstantInt::get(IdxTy, VF);
452 // Find the loop boundaries.
453 const SCEV *ExitCount = SE->getExitCount(Orig, Orig->getHeader());
454 assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
456 // Get the total trip count from the count by adding 1.
457 ExitCount = SE->getAddExpr(ExitCount,
458 SE->getConstant(ExitCount->getType(), 1));
460 // Expand the trip count and place the new instructions in the preheader.
461 // Notice that the pre-header does not change, only the loop body.
462 SCEVExpander Exp(*SE, "induction");
463 Instruction *Loc = BypassBlock->getTerminator();
465 // We may need to extend the index in case there is a type mismatch.
466 // We know that the count starts at zero and does not overflow.
467 // We are using Zext because it should be less expensive.
468 if (ExitCount->getType() != Induction->getType())
469 ExitCount = SE->getZeroExtendExpr(ExitCount, IdxTy);
471 // Count holds the overall loop count (N).
472 Value *Count = Exp.expandCodeFor(ExitCount, Induction->getType(), Loc);
473 // Now we need to generate the expression for N - (N % VF), which is
474 // the part that the vectorized body will execute.
475 Constant *CIVF = ConstantInt::get(IdxTy, VF);
476 Value *R = BinaryOperator::CreateURem(Count, CIVF, "n.mod.vf", Loc);
477 Value *CountRoundDown = BinaryOperator::CreateSub(Count, R, "n.vec", Loc);
479 // Now, compare the new count to zero. If it is zero, jump to the scalar part.
480 Value *Cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
481 CountRoundDown, ConstantInt::getNullValue(IdxTy),
483 BranchInst::Create(MiddleBlock, VectorPH, Cmp, Loc);
484 // Remove the old terminator.
485 Loc->eraseFromParent();
487 // Add a check in the middle block to see if we have completed
488 // all of the iterations in the first vector loop.
489 // If (N - N%VF) == N, then we *don't* need to run the remainder.
490 Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, Count,
491 CountRoundDown, "cmp.n",
492 MiddleBlock->getTerminator());
494 BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
495 // Remove the old terminator.
496 MiddleBlock->getTerminator()->eraseFromParent();
498 // Create i+1 and fill the PHINode.
499 Value *NextIdx = Builder->CreateAdd(Induction, Step, "index.next");
500 Induction->addIncoming(Zero, VectorPH);
501 Induction->addIncoming(NextIdx, VecBody);
502 // Create the compare.
503 Value *ICmp = Builder->CreateICmpEQ(NextIdx, CountRoundDown);
504 Builder->CreateCondBr(ICmp, MiddleBlock, VecBody);
506 // Now we have two terminators. Remove the old one from the block.
507 VecBody->getTerminator()->eraseFromParent();
509 // Fix the scalar body iteration count.
510 unsigned BlockIdx = OldInduction->getBasicBlockIndex(ScalarPH);
511 OldInduction->setIncomingValue(BlockIdx, CountRoundDown);
513 // Get ready to start creating new instructions into the vectorized body.
514 Builder->SetInsertPoint(VecBody->getFirstInsertionPt());
516 // Register the new loop.
517 Loop* Lp = new Loop();
518 LPM->insertLoop(Lp, Orig->getParentLoop());
520 Lp->addBasicBlockToLoop(VecBody, LI->getBase());
522 Loop *ParentLoop = Orig->getParentLoop();
524 ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase());
525 ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase());
526 ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase());
530 void SingleBlockLoopVectorizer::vectorizeLoop() {
531 BasicBlock &BB = *Orig->getHeader();
533 // For each instruction in the old loop.
534 for (BasicBlock::iterator it = BB.begin(), e = BB.end(); it != e; ++it) {
535 Instruction *Inst = it;
537 switch (Inst->getOpcode()) {
538 case Instruction::PHI:
539 case Instruction::Br:
540 // Nothing to do for PHIs and BR, since we already took care of the
541 // loop control flow instructions.
544 case Instruction::Add:
545 case Instruction::FAdd:
546 case Instruction::Sub:
547 case Instruction::FSub:
548 case Instruction::Mul:
549 case Instruction::FMul:
550 case Instruction::UDiv:
551 case Instruction::SDiv:
552 case Instruction::FDiv:
553 case Instruction::URem:
554 case Instruction::SRem:
555 case Instruction::FRem:
556 case Instruction::Shl:
557 case Instruction::LShr:
558 case Instruction::AShr:
559 case Instruction::And:
560 case Instruction::Or:
561 case Instruction::Xor: {
562 // Just widen binops.
563 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
564 Value *A = getVectorValue(Inst->getOperand(0));
565 Value *B = getVectorValue(Inst->getOperand(1));
566 // Use this vector value for all users of the original instruction.
567 WidenMap[Inst] = Builder->CreateBinOp(BinOp->getOpcode(), A, B);
570 case Instruction::Select: {
572 Value *A = getVectorValue(Inst->getOperand(0));
573 Value *B = getVectorValue(Inst->getOperand(1));
574 Value *C = getVectorValue(Inst->getOperand(2));
575 WidenMap[Inst] = Builder->CreateSelect(A, B, C);
579 case Instruction::ICmp:
580 case Instruction::FCmp: {
581 // Widen compares. Generate vector compares.
582 bool FCmp = (Inst->getOpcode() == Instruction::FCmp);
583 CmpInst *Cmp = dyn_cast<CmpInst>(Inst);
584 Value *A = getVectorValue(Inst->getOperand(0));
585 Value *B = getVectorValue(Inst->getOperand(1));
587 WidenMap[Inst] = Builder->CreateFCmp(Cmp->getPredicate(), A, B);
589 WidenMap[Inst] = Builder->CreateICmp(Cmp->getPredicate(), A, B);
593 case Instruction::Store: {
594 // Attempt to issue a wide store.
595 StoreInst *SI = dyn_cast<StoreInst>(Inst);
596 Type *StTy = VectorType::get(SI->getValueOperand()->getType(), VF);
597 Value *Ptr = SI->getPointerOperand();
598 unsigned Alignment = SI->getAlignment();
599 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
600 // This store does not use GEPs.
601 if (!isConsecutiveGep(Gep)) {
602 scalarizeInstruction(Inst);
606 // Create the new GEP with the new induction variable.
607 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
608 unsigned NumOperands = Gep->getNumOperands();
609 Gep2->setOperand(NumOperands - 1, Induction);
610 Ptr = Builder->Insert(Gep2);
611 Ptr = Builder->CreateBitCast(Ptr, StTy->getPointerTo());
612 Value *Val = getVectorValue(SI->getValueOperand());
613 Builder->CreateStore(Val, Ptr)->setAlignment(Alignment);
616 case Instruction::Load: {
617 // Attempt to issue a wide load.
618 LoadInst *LI = dyn_cast<LoadInst>(Inst);
619 Type *RetTy = VectorType::get(LI->getType(), VF);
620 Value *Ptr = LI->getPointerOperand();
621 unsigned Alignment = LI->getAlignment();
622 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
624 // We don't have a gep. Scalarize the load.
625 if (!isConsecutiveGep(Gep)) {
626 scalarizeInstruction(Inst);
630 // Create the new GEP with the new induction variable.
631 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
632 unsigned NumOperands = Gep->getNumOperands();
633 Gep2->setOperand(NumOperands - 1, Induction);
634 Ptr = Builder->Insert(Gep2);
635 Ptr = Builder->CreateBitCast(Ptr, RetTy->getPointerTo());
636 LI = Builder->CreateLoad(Ptr);
637 LI->setAlignment(Alignment);
638 // Use this vector value for all users of the load.
642 case Instruction::ZExt:
643 case Instruction::SExt:
644 case Instruction::FPToUI:
645 case Instruction::FPToSI:
646 case Instruction::FPExt:
647 case Instruction::PtrToInt:
648 case Instruction::IntToPtr:
649 case Instruction::SIToFP:
650 case Instruction::UIToFP:
651 case Instruction::Trunc:
652 case Instruction::FPTrunc:
653 case Instruction::BitCast: {
654 /// Vectorize bitcasts.
655 CastInst *CI = dyn_cast<CastInst>(Inst);
656 Value *A = getVectorValue(Inst->getOperand(0));
657 Type *DestTy = VectorType::get(CI->getType()->getScalarType(), VF);
658 WidenMap[Inst] = Builder->CreateCast(CI->getOpcode(), A, DestTy);
663 /// All other instructions are unsupported. Scalarize them.
664 scalarizeInstruction(Inst);
667 }// end of for_each instr.
670 void SingleBlockLoopVectorizer::cleanup() {
671 // The original basic block.
672 SE->forgetLoop(Orig);
675 unsigned LoopVectorizationLegality::getLoopMaxVF() {
676 if (!TheLoop->getLoopPreheader()) {
677 assert(false && "No preheader!!");
678 DEBUG(dbgs() << "LV: Loop not normalized." << "\n");
682 // We can only vectorize single basic block loops.
683 unsigned NumBlocks = TheLoop->getNumBlocks();
684 if (NumBlocks != 1) {
685 DEBUG(dbgs() << "LV: Too many blocks:" << NumBlocks << "\n");
689 // We need to have a loop header.
690 BasicBlock *BB = TheLoop->getHeader();
691 DEBUG(dbgs() << "LV: Found a loop: " << BB->getName() << "\n");
693 // Go over each instruction and look at memory deps.
694 if (!canVectorizeBlock(*BB)) {
695 DEBUG(dbgs() << "LV: Can't vectorize this loop header\n");
699 // ScalarEvolution needs to be able to find the exit count.
700 const SCEV *ExitCount = SE->getExitCount(TheLoop, BB);
701 if (ExitCount == SE->getCouldNotCompute()) {
702 DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
706 DEBUG(dbgs() << "LV: We can vectorize this loop!\n");
708 // Okay! We can vectorize. At this point we don't have any other mem analysis
709 // which may limit our maximum vectorization factor, so just return the
710 // maximum SIMD size.
711 return DefaultVectorizationFactor;
714 bool LoopVectorizationLegality::canVectorizeBlock(BasicBlock &BB) {
715 // Holds the read and write pointers that we find.
716 typedef SmallVector<Value*, 10> ValueVector;
720 unsigned NumPhis = 0;
721 for (BasicBlock::iterator it = BB.begin(), e = BB.end(); it != e; ++it) {
724 PHINode *Phi = dyn_cast<PHINode>(I);
727 // We only look at integer phi nodes.
728 if (!Phi->getType()->isIntegerTy()) {
729 DEBUG(dbgs() << "LV: Found an non-int PHI.\n");
733 // If we found an induction variable.
735 DEBUG(dbgs() << "LV: Found more than one PHI.\n");
739 // This should not happen because the loop should be normalized.
740 if (Phi->getNumIncomingValues() != 2) {
741 DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
745 // Check that the PHI is consecutive and starts at zero.
746 const SCEV *PhiScev = SE->getSCEV(Phi);
747 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
749 DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
753 const SCEV *Step = AR->getStepRecurrence(*SE);
754 const SCEV *Start = AR->getStart();
756 if (!Step->isOne() || !Start->isZero()) {
757 DEBUG(dbgs() << "LV: PHI does not start at zero or steps by one.\n");
762 // If this is a load, record its pointer. If it is not a load, abort.
763 // Notice that we don't handle function calls that read or write.
764 if (I->mayReadFromMemory()) {
765 LoadInst *Ld = dyn_cast<LoadInst>(I);
766 if (!Ld) return false;
767 if (!Ld->isSimple()) {
768 DEBUG(dbgs() << "LV: Found a non-simple load.\n");
771 GetUnderlyingObjects(Ld->getPointerOperand(), Reads, DL);
774 // Record store pointers. Abort on all other instructions that write to
776 if (I->mayWriteToMemory()) {
777 StoreInst *St = dyn_cast<StoreInst>(I);
778 if (!St) return false;
779 if (!St->isSimple()) {
780 DEBUG(dbgs() << "LV: Found a non-simple store.\n");
783 GetUnderlyingObjects(St->getPointerOperand(), Writes, DL);
786 // We still don't handle functions.
787 CallInst *CI = dyn_cast<CallInst>(I);
789 DEBUG(dbgs() << "LV: Found a call site:"<<
790 CI->getCalledFunction()->getName() << "\n");
794 // We do not re-vectorize vectors.
795 if (!VectorType::isValidElementType(I->getType()) &&
796 !I->getType()->isVoidTy()) {
797 DEBUG(dbgs() << "LV: Found unvectorizable type." << "\n");
800 //Check that all of the users of the loop are inside the BB.
801 for (Value::use_iterator it = I->use_begin(), e = I->use_end();
803 Instruction *U = cast<Instruction>(*it);
804 BasicBlock *Parent = U->getParent();
806 DEBUG(dbgs() << "LV: Found an outside user for : "<< *U << "\n");
813 DEBUG(dbgs() << "LV: Did not find a Phi node.\n");
817 // Check that the underlying objects of the reads and writes are either
818 // disjoint memory locations, or that they are no-alias arguments.
819 ValueVector::iterator r, re, w, we;
820 for (r = Reads.begin(), re = Reads.end(); r != re; ++r) {
821 if (!isidentifiedSafeObject(*r)) {
822 DEBUG(dbgs() << "LV: Found a bad read Ptr: "<< **r << "\n");
827 for (w = Writes.begin(), we = Writes.end(); w != we; ++w) {
828 if (!isidentifiedSafeObject(*w)) {
829 DEBUG(dbgs() << "LV: Found a bad write Ptr: "<< **w << "\n");
834 // Check that there are no multiple write locations to the same pointer.
835 SmallPtrSet<Value*, 8> WritePointerSet;
836 for (w = Writes.begin(), we = Writes.end(); w != we; ++w) {
837 if (!WritePointerSet.insert(*w)) {
838 DEBUG(dbgs() << "LV: Multiple writes to the same index :"<< **w << "\n");
843 // Check that the reads and the writes are disjoint.
844 for (r = Reads.begin(), re = Reads.end(); r != re; ++r) {
845 if (WritePointerSet.count(*r)) {
846 DEBUG(dbgs() << "Vectorizer: Found a read/write ptr:"<< **r << "\n");
855 /// Checks if the value is a Global variable or if it is an Arguments
856 /// marked with the NoAlias attribute.
857 bool LoopVectorizationLegality::isidentifiedSafeObject(Value* Val) {
858 assert(Val && "Invalid value");
859 if (dyn_cast<GlobalValue>(Val))
861 if (dyn_cast<AllocaInst>(Val))
863 Argument *A = dyn_cast<Argument>(Val);
866 return A->hasNoAliasAttr();
871 char LoopVectorize::ID = 0;
872 static const char lv_name[] = "Loop Vectorization";
873 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
874 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
875 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
876 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
877 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
880 Pass *createLoopVectorizePass() {
881 return new LoopVectorize();