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/Module.h"
32 #include "llvm/Type.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/StringExtras.h"
35 #include "llvm/Analysis/AliasAnalysis.h"
36 #include "llvm/Analysis/AliasSetTracker.h"
37 #include "llvm/Transforms/Scalar.h"
38 #include "llvm/Analysis/ScalarEvolution.h"
39 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
40 #include "llvm/Analysis/ScalarEvolutionExpander.h"
41 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
42 #include "llvm/Analysis/ValueTracking.h"
43 #include "llvm/Analysis/LoopInfo.h"
44 #include "llvm/Support/CommandLine.h"
45 #include "llvm/Support/Debug.h"
46 #include "llvm/Support/raw_ostream.h"
47 #include "llvm/DataLayout.h"
48 #include "llvm/Transforms/Utils/Local.h"
52 static cl::opt<unsigned>
53 DefaultVectorizationFactor("default-loop-vectorize-width",
54 cl::init(4), cl::Hidden,
55 cl::desc("Set the default loop vectorization width"));
59 /// Vectorize a simple loop. This class performs the widening of simple single
60 /// basic block loops into vectors. It does not perform any
61 /// vectorization-legality checks, and just does it. It widens the vectors
62 /// to a given vectorization factor (VF).
63 class SingleBlockLoopVectorizer {
67 SingleBlockLoopVectorizer(Loop *OrigLoop, ScalarEvolution *Se, LoopInfo *Li,
69 Orig(OrigLoop), SE(Se), LI(Li), 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 // Delete the old loop.
87 /// Create an empty loop, based on the loop ranges of the old loop.
89 /// Copy and widen the instructions from the old loop.
91 /// Delete the old loop.
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 /// The original loop.
122 // Scev analysis to use.
126 // The vectorization factor to use.
129 // The builder that we use
130 IRBuilder<> *Builder;
132 // --- Vectorization state ---
134 /// The new Induction variable which was added to the new block.
135 Instruction *Induction;
136 /// The induction variable of the old basic block.
137 Instruction *OldInduction;
138 // Maps scalars to widened vectors.
139 DenseMap<Value*, Value*> WidenMap;
143 /// Perform the vectorization legality check. This class does not look at the
144 /// profitability of vectorization, only the legality. At the moment the checks
145 /// are very simple and focus on single basic block loops with a constant
146 /// iteration count and no reductions.
147 class LoopVectorizationLegality {
149 LoopVectorizationLegality(Loop *Lp, ScalarEvolution *Se, DataLayout *Dl):
150 TheLoop(Lp), SE(Se), DL(Dl) { }
152 /// Returns the maximum vectorization factor that we *can* use to vectorize
153 /// this loop. This does not mean that it is profitable to vectorize this
154 /// loop, only that it is legal to do so. This may be a large number. We
155 /// can vectorize to any SIMD width below this number.
156 unsigned getLoopMaxVF();
159 /// Check if a single basic block loop is vectorizable.
160 /// At this point we know that this is a loop with a constant trip count
161 /// and we only need to check individual instructions.
162 bool canVectorizeBlock(BasicBlock &BB);
164 // Check if a pointer value is known to be disjoint.
165 // Example: Alloca, Global, NoAlias.
166 bool isKnownDisjoint(Value* Val);
168 /// The loop that we evaluate.
172 /// DataLayout analysis.
176 struct LoopVectorize : public LoopPass {
177 static char ID; // Pass identification, replacement for typeid
179 LoopVectorize() : LoopPass(ID) {
180 initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
188 virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
189 // Only vectorize innermost loops.
193 AA = &getAnalysis<AliasAnalysis>();
194 SE = &getAnalysis<ScalarEvolution>();
195 DL = getAnalysisIfAvailable<DataLayout>();
196 LI = &getAnalysis<LoopInfo>();
198 BasicBlock *Header = L->getHeader();
199 DEBUG(dbgs() << "LV: Checking a loop in \"" <<
200 Header->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 (MaxVF % DefaultVectorizationFactor)) {
209 DEBUG(dbgs() << "LV: non-vectorizable MaxVF ("<< MaxVF << ").\n");
213 DEBUG(dbgs() << "LV: Found a vectorizable loop ("<< MaxVF << ").\n");
215 // If we decided that is is *legal* to vectorizer the loop. Do it.
216 SingleBlockLoopVectorizer LB(L, SE, LI, DefaultVectorizationFactor);
219 // The loop is now vectorized. Remove it from LMP.
220 LPM.deleteLoopFromQueue(L);
224 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
225 LoopPass::getAnalysisUsage(AU);
226 AU.addRequiredID(LoopSimplifyID);
227 AU.addRequired<AliasAnalysis>();
228 AU.addRequired<LoopInfo>();
229 AU.addRequired<ScalarEvolution>();
234 Value *SingleBlockLoopVectorizer::getBroadcastInstrs(Value *V) {
235 // Instructions that access the old induction variable
236 // actually want to get the new one.
237 if (V == OldInduction)
240 LLVMContext &C = V->getContext();
241 Type *VTy = VectorType::get(V->getType(), VF);
242 Type *I32 = IntegerType::getInt32Ty(C);
243 Constant *Zero = ConstantInt::get(I32, 0);
244 Value *Zeros = ConstantAggregateZero::get(VectorType::get(I32, VF));
245 Value *UndefVal = UndefValue::get(VTy);
246 // Insert the value into a new vector.
247 Value *SingleElem = Builder->CreateInsertElement(UndefVal, V, Zero);
248 // Broadcast the scalar into all locations in the vector.
249 Value *Shuf = Builder->CreateShuffleVector(SingleElem, UndefVal, Zeros,
251 // We are accessing the induction variable. Make sure to promote the
252 // index for each consecutive SIMD lane. This adds 0,1,2 ... to all lanes.
254 return getConsecutiveVector(Shuf);
258 Value *SingleBlockLoopVectorizer::getConsecutiveVector(Value* Val) {
259 assert(Val->getType()->isVectorTy() && "Must be a vector");
260 assert(Val->getType()->getScalarType()->isIntegerTy() &&
261 "Elem must be an integer");
263 Type *ITy = Val->getType()->getScalarType();
264 VectorType *Ty = cast<VectorType>(Val->getType());
265 unsigned VLen = Ty->getNumElements();
266 SmallVector<Constant*, 8> Indices;
268 // Create a vector of consecutive numbers from zero to VF.
269 for (unsigned i = 0; i < VLen; ++i)
270 Indices.push_back(ConstantInt::get(ITy, i));
272 // Add the consecutive indices to the vector value.
273 Constant *Cv = ConstantVector::get(Indices);
274 assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
275 return Builder->CreateAdd(Val, Cv, "induction");
279 bool SingleBlockLoopVectorizer::isConsecutiveGep(GetElementPtrInst *Gep) {
283 unsigned NumOperands = Gep->getNumOperands();
284 Value *LastIndex = Gep->getOperand(NumOperands - 1);
286 // Check that all of the gep indices are uniform except for the last.
287 for (unsigned i = 0; i < NumOperands - 1; ++i)
288 if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), Orig))
291 // The last operand has to be the induction in order to emit
292 // a wide load/store.
293 const SCEV *Last = SE->getSCEV(LastIndex);
294 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
295 const SCEV *Step = AR->getStepRecurrence(*SE);
297 // The memory is consecutive because the last index is consecutive
298 // and all other indices are loop invariant.
306 Value *SingleBlockLoopVectorizer::getVectorValue(Value *V) {
307 if (WidenMap.count(V))
309 return getBroadcastInstrs(V);
312 void SingleBlockLoopVectorizer::scalarizeInstruction(Instruction *Instr) {
313 assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
314 // Holds vector parameters or scalars, in case of uniform vals.
315 SmallVector<Value*, 8> Params;
317 // Find all of the vectorized parameters.
318 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
319 Value *SrcOp = Instr->getOperand(op);
321 // If we are accessing the old induction variable, use the new one.
322 if (SrcOp == OldInduction) {
323 Params.push_back(getBroadcastInstrs(Induction));
327 // Try using previously calculated values.
328 Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
330 // If the src is an instruction that appeared earlier in the basic block
331 // then it should already be vectorized.
332 if (SrcInst && SrcInst->getParent() == Instr->getParent()) {
333 assert(WidenMap.count(SrcInst) && "Source operand is unavailable");
334 // The parameter is a vector value from earlier.
335 Params.push_back(WidenMap[SrcInst]);
337 // The parameter is a scalar from outside the loop. Maybe even a constant.
338 Params.push_back(SrcOp);
342 assert(Params.size() == Instr->getNumOperands() &&
343 "Invalid number of operands");
345 // Does this instruction return a value ?
346 bool IsVoidRetTy = Instr->getType()->isVoidTy();
347 Value *VecResults = 0;
349 // If we have a return value, create an empty vector. We place the scalarized
350 // instructions in this vector.
352 VecResults = UndefValue::get(VectorType::get(Instr->getType(), VF));
354 // For each scalar that we create.
355 for (unsigned i = 0; i < VF; ++i) {
356 Instruction *Cloned = Instr->clone();
358 Cloned->setName(Instr->getName() + ".cloned");
359 // Replace the operands of the cloned instrucions with extracted scalars.
360 for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
361 Value *Op = Params[op];
362 // Param is a vector. Need to extract the right lane.
363 if (Op->getType()->isVectorTy())
364 Op = Builder->CreateExtractElement(Op, Builder->getInt32(i));
365 Cloned->setOperand(op, Op);
368 // Place the cloned scalar in the new loop.
369 Builder->Insert(Cloned);
371 // If the original scalar returns a value we need to place it in a vector
372 // so that future users will be able to use it.
374 VecResults = Builder->CreateInsertElement(VecResults, Cloned,
375 Builder->getInt32(i));
379 WidenMap[Instr] = VecResults;
382 void SingleBlockLoopVectorizer::copyEmptyLoop() {
383 assert(Orig->getNumBlocks() == 1 && "Invalid loop");
384 BasicBlock *PH = Orig->getLoopPreheader();
385 BasicBlock *ExitBlock = Orig->getExitBlock();
386 assert(ExitBlock && "Invalid loop exit");
388 // Create a new single-basic block loop.
389 BasicBlock *BB = BasicBlock::Create(PH->getContext(), "vectorizedloop",
390 PH->getParent(), ExitBlock);
392 // Find the induction variable.
393 BasicBlock *OldBasicBlock = Orig->getHeader();
394 PHINode *OldInd = dyn_cast<PHINode>(OldBasicBlock->begin());
395 assert(OldInd && "We must have a single phi node.");
396 Type *IdxTy = OldInd->getType();
398 // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
400 Builder = new IRBuilder<>(BB);
402 // Generate the induction variable.
403 PHINode *Phi = Builder->CreatePHI(IdxTy, 2, "index");
404 Constant *Zero = ConstantInt::get(IdxTy, 0);
405 Constant *Step = ConstantInt::get(IdxTy, VF);
407 // Find the loop boundaries.
408 const SCEV *ExitCount = SE->getExitCount(Orig, Orig->getHeader());
409 assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
411 // Get the trip count from the count by adding 1.
412 ExitCount = SE->getAddExpr(ExitCount,
413 SE->getConstant(ExitCount->getType(), 1));
415 // Expand the trip count and place the new instructions in the preheader.
416 // Notice that the pre-header does not change, only the loop body.
417 SCEVExpander Exp(*SE, "induction");
418 Instruction *Loc = Orig->getLoopPreheader()->getTerminator();
419 if (ExitCount->getType() != Phi->getType())
420 ExitCount = SE->getSignExtendExpr(ExitCount, Phi->getType());
421 Value *Count = Exp.expandCodeFor(ExitCount, Phi->getType(), Loc);
423 // Create i+1 and fill the PHINode.
424 Value *Next = Builder->CreateAdd(Phi, Step, "index.next");
425 Phi->addIncoming(Zero, PH);
426 Phi->addIncoming(Next, BB);
427 // Create the compare.
428 Value *ICmp = Builder->CreateICmpEQ(Next, Count);
429 Builder->CreateCondBr(ICmp, ExitBlock, BB);
431 PH->getTerminator()->setSuccessor(0, BB);
432 Builder->SetInsertPoint(BB->getFirstInsertionPt());
434 // Save the induction variables.
436 OldInduction = OldInd;
439 void SingleBlockLoopVectorizer::vectorizeLoop() {
440 BasicBlock &BB = *Orig->getHeader();
442 // For each instruction in the old loop.
443 for (BasicBlock::iterator it = BB.begin(), e = BB.end(); it != e; ++it) {
444 Instruction *Inst = it;
446 switch (Inst->getOpcode()) {
447 case Instruction::PHI:
448 case Instruction::Br:
449 // Nothing to do for PHIs and BR, since we already took care of the
450 // loop control flow instructions.
453 case Instruction::Add:
454 case Instruction::FAdd:
455 case Instruction::Sub:
456 case Instruction::FSub:
457 case Instruction::Mul:
458 case Instruction::FMul:
459 case Instruction::UDiv:
460 case Instruction::SDiv:
461 case Instruction::FDiv:
462 case Instruction::URem:
463 case Instruction::SRem:
464 case Instruction::FRem:
465 case Instruction::Shl:
466 case Instruction::LShr:
467 case Instruction::AShr:
468 case Instruction::And:
469 case Instruction::Or:
470 case Instruction::Xor: {
471 // Just widen binops.
472 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
473 Value *A = getVectorValue(Inst->getOperand(0));
474 Value *B = getVectorValue(Inst->getOperand(1));
475 // Use this vector value for all users of the original instruction.
476 WidenMap[Inst] = Builder->CreateBinOp(BinOp->getOpcode(), A, B);
479 case Instruction::Select: {
481 Value *A = getVectorValue(Inst->getOperand(0));
482 Value *B = getVectorValue(Inst->getOperand(1));
483 Value *C = getVectorValue(Inst->getOperand(2));
484 WidenMap[Inst] = Builder->CreateSelect(A, B, C);
488 case Instruction::ICmp:
489 case Instruction::FCmp: {
490 // Widen compares. Generate vector compares.
491 bool FCmp = (Inst->getOpcode() == Instruction::FCmp);
492 CmpInst *Cmp = dyn_cast<CmpInst>(Inst);
493 Value *A = getVectorValue(Inst->getOperand(0));
494 Value *B = getVectorValue(Inst->getOperand(1));
496 WidenMap[Inst] = Builder->CreateFCmp(Cmp->getPredicate(), A, B);
498 WidenMap[Inst] = Builder->CreateICmp(Cmp->getPredicate(), A, B);
502 case Instruction::Store: {
503 // Attempt to issue a wide store.
504 StoreInst *SI = dyn_cast<StoreInst>(Inst);
505 Type *StTy = VectorType::get(SI->getValueOperand()->getType(), VF);
506 Value *Ptr = SI->getPointerOperand();
507 unsigned Alignment = SI->getAlignment();
508 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
509 // This store does not use GEPs.
510 if (!isConsecutiveGep(Gep)) {
511 scalarizeInstruction(Inst);
515 // Create the new GEP with the new induction variable.
516 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
517 unsigned NumOperands = Gep->getNumOperands();
518 Gep2->setOperand(NumOperands - 1, Induction);
519 Ptr = Builder->Insert(Gep2);
520 Ptr = Builder->CreateBitCast(Ptr, StTy->getPointerTo());
521 Value *Val = getVectorValue(SI->getValueOperand());
522 Builder->CreateStore(Val, Ptr)->setAlignment(Alignment);
525 case Instruction::Load: {
526 // Attempt to issue a wide load.
527 LoadInst *LI = dyn_cast<LoadInst>(Inst);
528 Type *RetTy = VectorType::get(LI->getType(), VF);
529 Value *Ptr = LI->getPointerOperand();
530 unsigned Alignment = LI->getAlignment();
531 GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
533 // We don't have a gep. Scalarize the load.
534 if (!isConsecutiveGep(Gep)) {
535 scalarizeInstruction(Inst);
539 // Create the new GEP with the new induction variable.
540 GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
541 unsigned NumOperands = Gep->getNumOperands();
542 Gep2->setOperand(NumOperands - 1, Induction);
543 Ptr = Builder->Insert(Gep2);
544 Ptr = Builder->CreateBitCast(Ptr, RetTy->getPointerTo());
545 LI = Builder->CreateLoad(Ptr);
546 LI->setAlignment(Alignment);
547 // Use this vector value for all users of the load.
551 case Instruction::ZExt:
552 case Instruction::SExt:
553 case Instruction::FPToUI:
554 case Instruction::FPToSI:
555 case Instruction::FPExt:
556 case Instruction::PtrToInt:
557 case Instruction::IntToPtr:
558 case Instruction::SIToFP:
559 case Instruction::UIToFP:
560 case Instruction::Trunc:
561 case Instruction::FPTrunc:
562 case Instruction::BitCast: {
563 /// Vectorize bitcasts.
564 CastInst *CI = dyn_cast<CastInst>(Inst);
565 Value *A = getVectorValue(Inst->getOperand(0));
566 Type *DestTy = VectorType::get(CI->getType()->getScalarType(), VF);
567 WidenMap[Inst] = Builder->CreateCast(CI->getOpcode(), A, DestTy);
572 /// All other instructions are unsupported. Scalarize them.
573 scalarizeInstruction(Inst);
576 }// end of for_each instr.
579 void SingleBlockLoopVectorizer::deleteOldLoop() {
580 // The original basic block.
581 BasicBlock *BB = Orig->getHeader();
582 SE->forgetLoop(Orig);
585 Orig->addBasicBlockToLoop(Induction->getParent(), LI->getBase());
587 // Remove the old loop block.
591 unsigned LoopVectorizationLegality::getLoopMaxVF() {
592 if (!TheLoop->getLoopPreheader()) {
593 assert(false && "No preheader!!");
594 DEBUG(dbgs() << "LV: Loop not normalized." << "\n");
598 // We can only vectorize single basic block loops.
599 unsigned NumBlocks = TheLoop->getNumBlocks();
600 if (NumBlocks != 1) {
601 DEBUG(dbgs() << "LV: Too many blocks:" << NumBlocks << "\n");
605 // We need to have a loop header.
606 BasicBlock *BB = TheLoop->getHeader();
607 DEBUG(dbgs() << "LV: Found a loop: " << BB->getName() << "\n");
609 // Find the max vectorization factor.
610 unsigned MaxVF = SE->getSmallConstantTripMultiple(TheLoop, BB);
613 // Perform an early check. Do not scan the block if we did not find a loop.
615 DEBUG(dbgs() << "LV: Can't find a vectorizable loop structure\n");
619 // Go over each instruction and look at memory deps.
620 if (!canVectorizeBlock(*BB)) {
621 DEBUG(dbgs() << "LV: Can't vectorize this loop header\n");
625 DEBUG(dbgs() << "LV: We can vectorize this loop! VF="<<MaxVF<<"\n");
627 // Okay! We can vectorize. Return the max trip multiple.
631 bool LoopVectorizationLegality::canVectorizeBlock(BasicBlock &BB) {
632 // Holds the read and write pointers that we find.
633 typedef SmallVector<Value*, 10> ValueVector;
637 unsigned NumPhis = 0;
638 for (BasicBlock::iterator it = BB.begin(), e = BB.end(); it != e; ++it) {
641 PHINode *Phi = dyn_cast<PHINode>(I);
644 // We only look at integer phi nodes.
645 if (!Phi->getType()->isIntegerTy()) {
646 DEBUG(dbgs() << "LV: Found an non-int PHI.\n");
650 // If we found an induction variable.
652 DEBUG(dbgs() << "LV: Found more than one PHI.\n");
656 // This should not happen because the loop should be normalized.
657 if (Phi->getNumIncomingValues() != 2) {
658 DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
662 // Check that the PHI is consecutive and starts at zero.
663 const SCEV *PhiScev = SE->getSCEV(Phi);
664 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
666 DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
670 const SCEV *Step = AR->getStepRecurrence(*SE);
671 const SCEV *Start = AR->getStart();
673 if (!Step->isOne() || !Start->isZero()) {
674 DEBUG(dbgs() << "LV: PHI does not start at zero or steps by one.\n");
679 // If this is a load, record its pointer. If it is not a load, abort.
680 // Notice that we don't handle function calls that read or write.
681 if (I->mayReadFromMemory()) {
682 LoadInst *Ld = dyn_cast<LoadInst>(I);
683 if (!Ld) return false;
684 if (!Ld->isSimple()) {
685 DEBUG(dbgs() << "LV: Found a non-simple load.\n");
688 GetUnderlyingObjects(Ld->getPointerOperand(), Reads, DL);
691 // Record store pointers. Abort on all other instructions that write to
693 if (I->mayWriteToMemory()) {
694 StoreInst *St = dyn_cast<StoreInst>(I);
695 if (!St) return false;
696 if (!St->isSimple()) {
697 DEBUG(dbgs() << "LV: Found a non-simple store.\n");
700 GetUnderlyingObjects(St->getPointerOperand(), Writes, DL);
703 // We still don't handle functions.
704 CallInst *CI = dyn_cast<CallInst>(I);
706 DEBUG(dbgs() << "LV: Found a call site:"<<
707 CI->getCalledFunction()->getName() << "\n");
711 // We do not re-vectorize vectors.
712 if (!VectorType::isValidElementType(I->getType()) &&
713 !I->getType()->isVoidTy()) {
714 DEBUG(dbgs() << "LV: Found unvectorizable type." << "\n");
717 //Check that all of the users of the loop are inside the BB.
718 for (Value::use_iterator it = I->use_begin(), e = I->use_end();
720 Instruction *U = cast<Instruction>(*it);
721 BasicBlock *Parent = U->getParent();
723 DEBUG(dbgs() << "LV: Found an outside user for : "<< *U << "\n");
729 // Check that the underlying objects of the reads and writes are either
730 // disjoint memory locations, or that they are no-alias arguments.
731 ValueVector::iterator r, re, w, we;
732 for (r = Reads.begin(), re = Reads.end(); r != re; ++r) {
733 if (!isKnownDisjoint(*r)) {
734 DEBUG(dbgs() << "LV: Found a bad read Ptr: "<< **r << "\n");
739 for (w = Writes.begin(), we = Writes.end(); w != we; ++w) {
740 if (!isKnownDisjoint(*w)) {
741 DEBUG(dbgs() << "LV: Found a bad write Ptr: "<< **w << "\n");
746 // Check that there are no multiple write locations to the same pointer.
747 SmallPtrSet<Value*, 8> BasePointers;
748 for (w = Writes.begin(), we = Writes.end(); w != we; ++w) {
749 if (BasePointers.count(*w)) {
750 DEBUG(dbgs() << "LV: Multiple writes to the same index :"<< **w << "\n");
753 BasePointers.insert(*w);
756 // Sort the writes vector so that we can use a binary search.
757 std::sort(Writes.begin(), Writes.end());
758 // Check that the reads and the writes are disjoint.
759 for (r = Reads.begin(), re = Reads.end(); r != re; ++r) {
760 if (std::binary_search(Writes.begin(), Writes.end(), *r)) {
761 DEBUG(dbgs() << "Vectorizer: Found a read/write ptr:"<< **r << "\n");
770 /// Checks if the value is a Global variable or if it is an Arguments
771 /// marked with the NoAlias attribute.
772 bool LoopVectorizationLegality::isKnownDisjoint(Value* Val) {
773 assert(Val && "Invalid value");
774 if (dyn_cast<GlobalValue>(Val))
776 if (dyn_cast<AllocaInst>(Val))
778 Argument *A = dyn_cast<Argument>(Val);
781 return A->hasNoAliasAttr();
786 char LoopVectorize::ID = 0;
787 static const char lv_name[] = "Loop Vectorization";
788 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
789 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
790 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
791 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
792 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
795 Pass *createLoopVectorizePass() {
796 return new LoopVectorize();