f84e3925f1de82c3d6750374b85e4e07844d3734
[oota-llvm.git] / lib / Transforms / Vectorize / LoopVectorize.cpp
1 //===- LoopVectorize.cpp - A Loop Vectorizer ------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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.
19 //
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"
49 #include <algorithm>
50 using namespace llvm;
51
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"));
56
57 namespace {
58
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 {
64 public:
65
66   /// Ctor.
67   SingleBlockLoopVectorizer(Loop *OrigLoop, ScalarEvolution *Se, LoopInfo *Li,
68                             unsigned VecWidth):
69   Orig(OrigLoop), SE(Se), LI(Li), VF(VecWidth),
70    Builder(0), Induction(0), OldInduction(0) { }
71
72   ~SingleBlockLoopVectorizer() {
73     delete Builder;
74   }
75
76   // Perform the actual loop widening (vectorization).
77   void vectorize() {
78     ///Create a new empty loop. Unlink the old loop and connect the new one.
79     copyEmptyLoop();
80     /// Widen each instruction in the old loop to a new one in the new loop.
81     vectorizeLoop();
82     // Delete the old loop.
83     deleteOldLoop();
84  }
85
86 private:
87   /// Create an empty loop, based on the loop ranges of the old loop.
88   void copyEmptyLoop();
89   /// Copy and widen the instructions from the old loop.
90   void vectorizeLoop();
91   /// Delete the old loop.
92   void deleteOldLoop();
93
94   /// This instruction is un-vectorizable. Implement it as a sequence
95   /// of scalars.
96   void scalarizeInstruction(Instruction *Instr);
97
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
102   /// element.
103   Value *getBroadcastInstrs(Value *V);
104
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);
108
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);
112
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);
119
120   /// The original loop.
121   Loop *Orig;
122   // Scev analysis to use.
123   ScalarEvolution *SE;
124   // Loop Info.
125   LoopInfo *LI;
126   // The vectorization factor to use.
127   unsigned VF;
128
129   // The builder that we use
130   IRBuilder<> *Builder;
131
132   // --- Vectorization state ---
133
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;
140 };
141
142
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 {
148 public:
149   LoopVectorizationLegality(Loop *Lp, ScalarEvolution *Se, DataLayout *Dl):
150   TheLoop(Lp), SE(Se), DL(Dl) { }
151
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();
157
158 private:
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);
163
164   // Check if a pointer value is known to be disjoint.
165   // Example: Alloca, Global, NoAlias.
166   bool isKnownDisjoint(Value* Val);
167
168   /// The loop that we evaluate.
169   Loop *TheLoop;
170   /// Scev analysis.
171   ScalarEvolution *SE;
172   /// DataLayout analysis.
173   DataLayout *DL;
174 };
175
176 struct LoopVectorize : public LoopPass {
177   static char ID; // Pass identification, replacement for typeid
178
179   LoopVectorize() : LoopPass(ID) {
180     initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
181   }
182
183   AliasAnalysis *AA;
184   ScalarEvolution *SE;
185   DataLayout *DL;
186   LoopInfo *LI;
187
188   virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
189     // Only vectorize innermost loops.
190     if (!L->empty())
191       return false;
192
193     AA = &getAnalysis<AliasAnalysis>();
194     SE = &getAnalysis<ScalarEvolution>();
195     DL = getAnalysisIfAvailable<DataLayout>();
196     LI = &getAnalysis<LoopInfo>();
197
198     DEBUG(dbgs() << "LV: Checking a loop in \"" <<
199           L->getHeader()->getParent()->getName() << "\"\n");
200
201     // Check if it is legal to vectorize the loop.
202     LoopVectorizationLegality LVL(L, SE, DL);
203     unsigned MaxVF = LVL.getLoopMaxVF();
204
205     // Check that we can vectorize using the chosen vectorization width.
206     if ((MaxVF < DefaultVectorizationFactor) ||
207         (MaxVF % DefaultVectorizationFactor)) {
208       DEBUG(dbgs() << "LV: non-vectorizable MaxVF ("<< MaxVF << ").\n");
209       return false;
210     }
211
212     DEBUG(dbgs() << "LV: Found a vectorizable loop ("<< MaxVF << ").\n");
213
214     // If we decided that is is *legal* to vectorizer the loop. Do it.
215     SingleBlockLoopVectorizer LB(L, SE, LI, DefaultVectorizationFactor);
216     LB.vectorize();
217
218     // The loop is now vectorized. Remove it from LMP.
219     LPM.deleteLoopFromQueue(L);
220     return true;
221   }
222
223   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
224     LoopPass::getAnalysisUsage(AU);
225     AU.addRequiredID(LoopSimplifyID);
226     AU.addRequired<AliasAnalysis>();
227     AU.addRequired<LoopInfo>();
228     AU.addRequired<ScalarEvolution>();
229   }
230
231 };
232
233 Value *SingleBlockLoopVectorizer::getBroadcastInstrs(Value *V) {
234   // Instructions that access the old induction variable
235   // actually want to get the new one.
236   if (V == OldInduction)
237     V = Induction;
238   // Create the types.
239   LLVMContext &C = V->getContext();
240   Type *VTy = VectorType::get(V->getType(), VF);
241   Type *I32 = IntegerType::getInt32Ty(C);
242   Constant *Zero = ConstantInt::get(I32, 0);
243   Value *Zeros = ConstantAggregateZero::get(VectorType::get(I32, VF));
244   Value *UndefVal = UndefValue::get(VTy);
245   // Insert the value into a new vector.
246   Value *SingleElem = Builder->CreateInsertElement(UndefVal, V, Zero);
247   // Broadcast the scalar into all locations in the vector.
248   Value *Shuf = Builder->CreateShuffleVector(SingleElem, UndefVal, Zeros,
249                                              "broadcast");
250   // We are accessing the induction variable. Make sure to promote the
251   // index for each consecutive SIMD lane. This adds 0,1,2 ... to all lanes.
252   if (V == Induction)
253     return getConsecutiveVector(Shuf);
254   return Shuf;
255 }
256
257 Value *SingleBlockLoopVectorizer::getConsecutiveVector(Value* Val) {
258   assert(Val->getType()->isVectorTy() && "Must be a vector");
259   assert(Val->getType()->getScalarType()->isIntegerTy() &&
260          "Elem must be an integer");
261   // Create the types.
262   Type *ITy = Val->getType()->getScalarType();
263   VectorType *Ty = cast<VectorType>(Val->getType());
264   unsigned VLen = Ty->getNumElements();
265   SmallVector<Constant*, 8> Indices;
266
267   // Create a vector of consecutive numbers from zero to VF.
268   for (unsigned i = 0; i < VLen; ++i)
269     Indices.push_back(ConstantInt::get(ITy, i));
270
271   // Add the consecutive indices to the vector value.
272   Constant *Cv = ConstantVector::get(Indices);
273   assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
274   return Builder->CreateAdd(Val, Cv, "induction");
275 }
276
277
278 bool SingleBlockLoopVectorizer::isConsecutiveGep(GetElementPtrInst *Gep) {
279   if (!Gep)
280     return false;
281
282   unsigned NumOperands = Gep->getNumOperands();
283   Value *LastIndex = Gep->getOperand(NumOperands - 1);
284
285   // Check that all of the gep indices are uniform except for the last.
286   for (unsigned i = 0; i < NumOperands - 1; ++i)
287     if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), Orig))
288       return false;
289
290   // The last operand has to be the induction in order to emit
291   // a wide load/store.
292   const SCEV *Last = SE->getSCEV(LastIndex);
293   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
294     const SCEV *Step = AR->getStepRecurrence(*SE);
295
296     // The memory is consecutive because the last index is consecutive
297     // and all other indices are loop invariant.
298     if (Step->isOne())
299       return true;
300   }
301
302   return false;
303 }
304
305 Value *SingleBlockLoopVectorizer::getVectorValue(Value *V) {
306   if (WidenMap.count(V))
307     return WidenMap[V];
308   return getBroadcastInstrs(V);
309 }
310
311 void SingleBlockLoopVectorizer::scalarizeInstruction(Instruction *Instr) {
312   assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
313   // Holds vector parameters or scalars, in case of uniform vals.
314   SmallVector<Value*, 8> Params;
315
316   // Find all of the vectorized parameters.
317   for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
318     Value *SrcOp = Instr->getOperand(op);
319
320     // If we are accessing the old induction variable, use the new one.
321     if (SrcOp == OldInduction) {
322       Params.push_back(getBroadcastInstrs(Induction));
323       continue;
324     }
325
326     // Try using previously calculated values.
327     Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
328
329     // If the src is an instruction that appeared earlier in the basic block
330     // then it should already be vectorized. 
331     if (SrcInst && SrcInst->getParent() == Instr->getParent()) {
332       assert(WidenMap.count(SrcInst) && "Source operand is unavailable");
333       // The parameter is a vector value from earlier.
334       Params.push_back(WidenMap[SrcInst]);
335     } else {
336       // The parameter is a scalar from outside the loop. Maybe even a constant.
337       Params.push_back(SrcOp);
338     }
339   }
340
341   assert(Params.size() == Instr->getNumOperands() &&
342          "Invalid number of operands");
343
344   // Does this instruction return a value ?
345   bool IsVoidRetTy = Instr->getType()->isVoidTy();
346   Value *VecResults = 0;
347
348   // If we have a return value, create an empty vector. We place the scalarized
349   // instructions in this vector.
350   if (!IsVoidRetTy)
351     VecResults = UndefValue::get(VectorType::get(Instr->getType(), VF));
352
353   // For each scalar that we create.
354   for (unsigned i = 0; i < VF; ++i) {
355     Instruction *Cloned = Instr->clone();
356     if (!IsVoidRetTy)
357       Cloned->setName(Instr->getName() + ".cloned");
358     // Replace the operands of the cloned instrucions with extracted scalars.
359     for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
360       Value *Op = Params[op];
361       // Param is a vector. Need to extract the right lane.
362       if (Op->getType()->isVectorTy())
363         Op = Builder->CreateExtractElement(Op, Builder->getInt32(i));
364       Cloned->setOperand(op, Op);
365     }
366
367     // Place the cloned scalar in the new loop.
368     Builder->Insert(Cloned);
369
370     // If the original scalar returns a value we need to place it in a vector
371     // so that future users will be able to use it.
372     if (!IsVoidRetTy)
373       VecResults = Builder->CreateInsertElement(VecResults, Cloned,
374                                                Builder->getInt32(i));
375   }
376
377   if (!IsVoidRetTy)
378     WidenMap[Instr] = VecResults;
379 }
380
381 void SingleBlockLoopVectorizer::copyEmptyLoop() {
382   assert(Orig->getNumBlocks() == 1 && "Invalid loop");
383   BasicBlock *PH = Orig->getLoopPreheader();
384   BasicBlock *ExitBlock = Orig->getExitBlock();
385   assert(ExitBlock && "Invalid loop exit");
386
387   // Create a new single-basic block loop.
388   BasicBlock *BB = BasicBlock::Create(PH->getContext(), "vectorizedloop",
389                                       PH->getParent(), ExitBlock);
390
391   // Find the induction variable.
392   BasicBlock *OldBasicBlock = Orig->getHeader();
393   PHINode *OldInd = dyn_cast<PHINode>(OldBasicBlock->begin());
394   assert(OldInd && "We must have a single phi node.");
395   Type *IdxTy = OldInd->getType();
396
397   // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
398   // inside the loop.
399   Builder = new IRBuilder<>(BB);
400
401   // Generate the induction variable.
402   PHINode *Phi = Builder->CreatePHI(IdxTy, 2, "index");
403   Constant *Zero = ConstantInt::get(IdxTy, 0);
404   Constant *Step = ConstantInt::get(IdxTy, VF);
405
406   // Find the loop boundaries.
407   const SCEV *ExitCount = SE->getExitCount(Orig, Orig->getHeader());
408   assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
409
410   // Get the trip count from the count by adding 1.
411   ExitCount = SE->getAddExpr(ExitCount,
412                              SE->getConstant(ExitCount->getType(), 1));
413
414   // Expand the trip count and place the new instructions in the preheader.
415   // Notice that the pre-header does not change, only the loop body.
416   SCEVExpander Exp(*SE, "induction");
417   Instruction *Loc = Orig->getLoopPreheader()->getTerminator();
418   if (ExitCount->getType() != Phi->getType())
419     ExitCount = SE->getSignExtendExpr(ExitCount, Phi->getType());
420   Value *Count = Exp.expandCodeFor(ExitCount, Phi->getType(), Loc);
421   
422   // Create i+1 and fill the PHINode.
423   Value *Next = Builder->CreateAdd(Phi, Step, "index.next");
424   Phi->addIncoming(Zero, PH);
425   Phi->addIncoming(Next, BB);
426   // Create the compare.
427   Value *ICmp = Builder->CreateICmpEQ(Next, Count);
428   Builder->CreateCondBr(ICmp, ExitBlock, BB);
429   // Fix preheader.
430   PH->getTerminator()->setSuccessor(0, BB);
431   Builder->SetInsertPoint(BB->getFirstInsertionPt());
432
433   // Save the induction variables.
434   Induction = Phi;
435   OldInduction = OldInd;
436 }
437
438 void SingleBlockLoopVectorizer::vectorizeLoop() {
439   BasicBlock &BB = *Orig->getHeader();
440
441   // For each instruction in the old loop.
442   for (BasicBlock::iterator it = BB.begin(), e = BB.end(); it != e; ++it) {
443     Instruction *Inst = it;
444
445     switch (Inst->getOpcode()) {
446       case Instruction::PHI:
447       case Instruction::Br:
448         // Nothing to do for PHIs and BR, since we already took care of the
449         // loop control flow instructions.
450         continue;
451
452       case Instruction::Add:
453       case Instruction::FAdd:
454       case Instruction::Sub:
455       case Instruction::FSub:
456       case Instruction::Mul:
457       case Instruction::FMul:
458       case Instruction::UDiv:
459       case Instruction::SDiv:
460       case Instruction::FDiv:
461       case Instruction::URem:
462       case Instruction::SRem:
463       case Instruction::FRem:
464       case Instruction::Shl:
465       case Instruction::LShr:
466       case Instruction::AShr:
467       case Instruction::And:
468       case Instruction::Or:
469       case Instruction::Xor: {
470         // Just widen binops.
471         BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
472         Value *A = getVectorValue(Inst->getOperand(0));
473         Value *B = getVectorValue(Inst->getOperand(1));
474         // Use this vector value for all users of the original instruction.
475         WidenMap[Inst] = Builder->CreateBinOp(BinOp->getOpcode(), A, B);
476         break;
477       }
478       case Instruction::Select: {
479         // Widen selects.
480         Value *A = getVectorValue(Inst->getOperand(0));
481         Value *B = getVectorValue(Inst->getOperand(1));
482         Value *C = getVectorValue(Inst->getOperand(2));
483         WidenMap[Inst] = Builder->CreateSelect(A, B, C);
484         break;
485       }
486
487       case Instruction::ICmp:
488       case Instruction::FCmp: {
489         // Widen compares. Generate vector compares.
490         bool FCmp = (Inst->getOpcode() == Instruction::FCmp);
491         CmpInst *Cmp = dyn_cast<CmpInst>(Inst);
492         Value *A = getVectorValue(Inst->getOperand(0));
493         Value *B = getVectorValue(Inst->getOperand(1));
494         if (FCmp)
495           WidenMap[Inst] = Builder->CreateFCmp(Cmp->getPredicate(), A, B);
496         else
497           WidenMap[Inst] = Builder->CreateICmp(Cmp->getPredicate(), A, B);
498         break;
499       }
500
501       case Instruction::Store: {
502         // Attempt to issue a wide store.
503         StoreInst *SI = dyn_cast<StoreInst>(Inst);
504         Type *StTy = VectorType::get(SI->getValueOperand()->getType(), VF);
505         Value *Ptr = SI->getPointerOperand();
506         unsigned Alignment = SI->getAlignment();
507         GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
508         // This store does not use GEPs.
509         if (!isConsecutiveGep(Gep)) {
510           scalarizeInstruction(Inst);
511           break;
512         }
513
514         // Create the new GEP with the new induction variable.
515         GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
516         unsigned NumOperands = Gep->getNumOperands();
517         Gep2->setOperand(NumOperands - 1, Induction);
518         Ptr = Builder->Insert(Gep2);
519         Ptr = Builder->CreateBitCast(Ptr, StTy->getPointerTo());
520         Value *Val = getVectorValue(SI->getValueOperand());
521         Builder->CreateStore(Val, Ptr)->setAlignment(Alignment);
522         break;
523       }
524       case Instruction::Load: {
525         // Attempt to issue a wide load.
526         LoadInst *LI = dyn_cast<LoadInst>(Inst);
527         Type *RetTy = VectorType::get(LI->getType(), VF);
528         Value *Ptr = LI->getPointerOperand();
529         unsigned Alignment = LI->getAlignment();
530         GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
531
532         // We don't have a gep. Scalarize the load.
533         if (!isConsecutiveGep(Gep)) {
534           scalarizeInstruction(Inst);
535           break;
536         }
537
538         // Create the new GEP with the new induction variable.
539         GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
540         unsigned NumOperands = Gep->getNumOperands();
541         Gep2->setOperand(NumOperands - 1, Induction);
542         Ptr = Builder->Insert(Gep2);
543         Ptr = Builder->CreateBitCast(Ptr, RetTy->getPointerTo());
544         LI = Builder->CreateLoad(Ptr);
545         LI->setAlignment(Alignment);
546         // Use this vector value for all users of the load.
547         WidenMap[Inst] = LI;
548         break;
549       }
550       case Instruction::ZExt:
551       case Instruction::SExt:
552       case Instruction::FPToUI:
553       case Instruction::FPToSI:
554       case Instruction::FPExt:
555       case Instruction::PtrToInt:
556       case Instruction::IntToPtr:
557       case Instruction::SIToFP:
558       case Instruction::UIToFP:
559       case Instruction::Trunc:
560       case Instruction::FPTrunc:
561       case Instruction::BitCast: {
562         /// Vectorize bitcasts.
563         CastInst *CI = dyn_cast<CastInst>(Inst);
564         Value *A = getVectorValue(Inst->getOperand(0));
565         Type *DestTy = VectorType::get(CI->getType()->getScalarType(), VF);
566         WidenMap[Inst] = Builder->CreateCast(CI->getOpcode(), A, DestTy);
567         break;
568       }
569
570       default:
571         /// All other instructions are unsupported. Scalarize them.
572         scalarizeInstruction(Inst);
573         break;
574     }// end of switch.
575   }// end of for_each instr.
576 }
577
578 void SingleBlockLoopVectorizer::deleteOldLoop() {
579   // The original basic block.
580   BasicBlock *BB = Orig->getHeader();
581   SE->forgetLoop(Orig);
582
583   LI->removeBlock(BB);
584   Orig->addBasicBlockToLoop(Induction->getParent(), LI->getBase());
585
586   // Remove the old loop block.
587   DeleteDeadBlock(BB);
588 }
589
590 unsigned LoopVectorizationLegality::getLoopMaxVF() {
591   if (!TheLoop->getLoopPreheader()) {
592     assert(false && "No preheader!!");
593     DEBUG(dbgs() << "LV: Loop not normalized." << "\n");
594     return  1;
595   }
596
597   // We can only vectorize single basic block loops.
598   unsigned NumBlocks = TheLoop->getNumBlocks();
599   if (NumBlocks != 1) {
600     DEBUG(dbgs() << "LV: Too many blocks:" << NumBlocks << "\n");
601     return 1;
602   }
603
604   // We need to have a loop header.
605   BasicBlock *BB = TheLoop->getHeader();
606   DEBUG(dbgs() << "LV: Found a loop: " << BB->getName() << "\n");
607
608   // Find the max vectorization factor.
609   unsigned MaxVF = SE->getSmallConstantTripMultiple(TheLoop, BB);
610
611
612   // Perform an early check. Do not scan the block if we did not find a loop.
613   if (MaxVF < 2) {
614     DEBUG(dbgs() << "LV: Can't find a vectorizable loop structure\n");
615     return 1;
616   }
617
618   // Go over each instruction and look at memory deps.
619   if (!canVectorizeBlock(*BB)) {
620     DEBUG(dbgs() << "LV: Can't vectorize this loop header\n");
621     return 1;
622   }
623
624   DEBUG(dbgs() << "LV: We can vectorize this loop! VF="<<MaxVF<<"\n");
625   
626   // Okay! We can vectorize. Return the max trip multiple.
627   return MaxVF;
628 }
629
630 bool LoopVectorizationLegality::canVectorizeBlock(BasicBlock &BB) {
631   // Holds the read and write pointers that we find.
632   typedef SmallVector<Value*, 10> ValueVector;
633   ValueVector Reads;
634   ValueVector Writes;
635
636   unsigned NumPhis = 0;
637   for (BasicBlock::iterator it = BB.begin(), e = BB.end(); it != e; ++it) {
638     Instruction *I = it;
639
640     PHINode *Phi = dyn_cast<PHINode>(I);
641     if (Phi) {
642       NumPhis++;
643       // We only look at integer phi nodes.
644       if (!Phi->getType()->isIntegerTy()) {
645         DEBUG(dbgs() << "LV: Found an non-int PHI.\n");
646         return false;
647       }
648
649       // If we found an induction variable.
650       if (NumPhis > 1) {
651         DEBUG(dbgs() << "LV: Found more than one PHI.\n");
652         return false;
653       }
654
655       // This should not happen because the loop should be normalized.
656       if (Phi->getNumIncomingValues() != 2) {
657         DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
658         return false;
659       }
660
661       // Check that the PHI is consecutive and starts at zero.
662       const SCEV *PhiScev = SE->getSCEV(Phi);
663       const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
664       if (!AR) {
665         DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
666         return false;
667       }
668
669       const SCEV *Step = AR->getStepRecurrence(*SE);
670       const SCEV *Start = AR->getStart();
671
672       if (!Step->isOne() || !Start->isZero()) {
673         DEBUG(dbgs() << "LV: PHI does not start at zero or steps by one.\n");
674         return false;
675       }
676     }
677
678     // If this is a load, record its pointer. If it is not a load, abort.
679     // Notice that we don't handle function calls that read or write.
680     if (I->mayReadFromMemory()) {
681       LoadInst *Ld = dyn_cast<LoadInst>(I);
682       if (!Ld) return false;
683       if (!Ld->isSimple()) {
684         DEBUG(dbgs() << "LV: Found a non-simple load.\n");
685         return false;
686       }
687       GetUnderlyingObjects(Ld->getPointerOperand(), Reads, DL);
688     }
689
690     // Record store pointers. Abort on all other instructions that write to
691     // memory.
692     if (I->mayWriteToMemory()) {
693       StoreInst *St = dyn_cast<StoreInst>(I);
694       if (!St) return false;
695       if (!St->isSimple()) {
696         DEBUG(dbgs() << "LV: Found a non-simple store.\n");
697         return false;
698       }
699       GetUnderlyingObjects(St->getPointerOperand(), Writes, DL);
700     }
701
702     // We still don't handle functions.
703     CallInst *CI = dyn_cast<CallInst>(I);
704     if (CI) {
705       DEBUG(dbgs() << "LV: Found a call site:"<<
706             CI->getCalledFunction()->getName() << "\n");
707       return false;
708     }
709
710     // We do not re-vectorize vectors.
711     if (!VectorType::isValidElementType(I->getType()) &&
712         !I->getType()->isVoidTy()) {
713       DEBUG(dbgs() << "LV: Found unvectorizable type." << "\n");
714       return false;
715     }
716     //Check that all of the users of the loop are inside the BB.
717     for (Value::use_iterator it = I->use_begin(), e = I->use_end();
718          it != e; ++it) {
719       Instruction *U = cast<Instruction>(*it);
720       BasicBlock *Parent = U->getParent();
721       if (Parent != &BB) {
722         DEBUG(dbgs() << "LV: Found an outside user for : "<< *U << "\n");
723         return false;
724       }
725     }
726   } // next instr.
727
728   // Check that the underlying objects of the reads and writes are either
729   // disjoint memory locations, or that they are no-alias arguments.
730   ValueVector::iterator r, re, w, we;
731   for (r = Reads.begin(), re = Reads.end(); r != re; ++r) {
732     if (!isKnownDisjoint(*r)) {
733       DEBUG(dbgs() << "LV: Found a bad read Ptr: "<< **r << "\n");
734       return false;
735     }
736   }
737
738   for (w = Writes.begin(), we = Writes.end(); w != we; ++w) {
739     if (!isKnownDisjoint(*w)) {
740       DEBUG(dbgs() << "LV: Found a bad write Ptr: "<< **w << "\n");
741       return false;
742     }
743   }
744
745   // Check that there are no multiple write locations to the same pointer.
746   SmallPtrSet<Value*, 8> BasePointers;
747   for (w = Writes.begin(), we = Writes.end(); w != we; ++w) {
748     if (BasePointers.count(*w)) {
749       DEBUG(dbgs() << "LV: Multiple writes to the same index :"<< **w << "\n");
750       return false;
751     }
752     BasePointers.insert(*w);
753   }
754
755   // Sort the writes vector so that we can use a binary search.
756   std::sort(Writes.begin(), Writes.end());
757   // Check that the reads and the writes are disjoint.
758   for (r = Reads.begin(), re = Reads.end(); r != re; ++r) {
759     if (std::binary_search(Writes.begin(), Writes.end(), *r)) {
760       DEBUG(dbgs() << "Vectorizer: Found a read/write ptr:"<< **r << "\n");
761       return false;
762     }
763   }
764
765   // All is okay.
766   return true;
767 }
768
769 /// Checks if the value is a Global variable or if it is an Arguments
770 /// marked with the NoAlias attribute.
771 bool LoopVectorizationLegality::isKnownDisjoint(Value* Val) {
772   assert(Val && "Invalid value");
773   if (dyn_cast<GlobalValue>(Val))
774     return true;
775   if (dyn_cast<AllocaInst>(Val))
776     return true;
777   Argument *A = dyn_cast<Argument>(Val);
778   if (!A)
779     return false;
780   return A->hasNoAliasAttr();
781 }
782
783 } // namespace
784
785 char LoopVectorize::ID = 0;
786 static const char lv_name[] = "Loop Vectorization";
787 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
788 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
789 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
790 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
791 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
792
793 namespace llvm {
794   Pass *createLoopVectorizePass() {
795     return new LoopVectorize();
796   }
797
798 }
799