Avoid an extra hash lookup when inserting a value into the widen map.
[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 the LLVM loop vectorizer. This pass modifies 'vectorizable' loops
11 // and generates target-independent LLVM-IR. Legalization of the IR is done
12 // in the codegen. However, the vectorizes uses (will use) the codegen
13 // interfaces to generate IR that is likely to result in an optimal binary.
14 //
15 // The loop vectorizer combines consecutive loop iteration into a single
16 // 'wide' iteration. After this transformation the index is incremented
17 // by the SIMD vector width, and not by one.
18 //
19 // This pass has three parts:
20 // 1. The main loop pass that drives the different parts.
21 // 2. LoopVectorizationLegality - A helper class that checks for the legality
22 //    of the vectorization.
23 // 3. SingleBlockLoopVectorizer - A helper class that performs the actual
24 //    widening of instructions.
25 //===----------------------------------------------------------------------===//
26 //
27 // The reduction-variable vectorization is based on the paper:
28 //  D. Nuzman and R. Henderson. Multi-platform Auto-vectorization.
29 //
30 // Variable uniformity checks are inspired by:
31 // Karrenberg, R. and Hack, S. Whole Function Vectorization.
32 //
33 // Other ideas/concepts are from:
34 //  A. Zaks and D. Nuzman. Autovectorization in GCC—two years later.
35 //
36 //===----------------------------------------------------------------------===//
37 #define LV_NAME "loop-vectorize"
38 #define DEBUG_TYPE LV_NAME
39 #include "llvm/Constants.h"
40 #include "llvm/DerivedTypes.h"
41 #include "llvm/Instructions.h"
42 #include "llvm/LLVMContext.h"
43 #include "llvm/Pass.h"
44 #include "llvm/Analysis/LoopPass.h"
45 #include "llvm/Value.h"
46 #include "llvm/Function.h"
47 #include "llvm/Analysis/Verifier.h"
48 #include "llvm/Module.h"
49 #include "llvm/Type.h"
50 #include "llvm/ADT/SmallVector.h"
51 #include "llvm/ADT/StringExtras.h"
52 #include "llvm/Analysis/AliasAnalysis.h"
53 #include "llvm/Analysis/AliasSetTracker.h"
54 #include "llvm/Transforms/Scalar.h"
55 #include "llvm/Analysis/ScalarEvolution.h"
56 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
57 #include "llvm/Analysis/ScalarEvolutionExpander.h"
58 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
59 #include "llvm/Analysis/ValueTracking.h"
60 #include "llvm/Analysis/LoopInfo.h"
61 #include "llvm/Support/CommandLine.h"
62 #include "llvm/Support/Debug.h"
63 #include "llvm/Support/raw_ostream.h"
64 #include "llvm/DataLayout.h"
65 #include "llvm/Transforms/Utils/Local.h"
66 #include <algorithm>
67 using namespace llvm;
68
69 static cl::opt<unsigned>
70 DefaultVectorizationFactor("default-loop-vectorize-width",
71                           cl::init(4), cl::Hidden,
72                           cl::desc("Set the default loop vectorization width"));
73 namespace {
74
75 // Forward declaration.
76 class LoopVectorizationLegality;
77
78 /// Vectorize a simple loop. This class performs the widening of simple single
79 /// basic block loops into vectors. It does not perform any
80 /// vectorization-legality checks, and just does it.  It widens the vectors
81 /// to a given vectorization factor (VF).
82 class SingleBlockLoopVectorizer {
83 public:
84   /// Ctor.
85   SingleBlockLoopVectorizer(Loop *OrigLoop, ScalarEvolution *Se, LoopInfo *Li,
86                             LPPassManager *Lpm, unsigned VecWidth):
87   Orig(OrigLoop), SE(Se), LI(Li), LPM(Lpm), VF(VecWidth),
88   Builder(Se->getContext()), Induction(0), OldInduction(0) { }
89
90   // Perform the actual loop widening (vectorization).
91   void vectorize(LoopVectorizationLegality *Legal) {
92     ///Create a new empty loop. Unlink the old loop and connect the new one.
93     createEmptyLoop(Legal);
94     /// Widen each instruction in the old loop to a new one in the new loop.
95     /// Use the Legality module to find the induction and reduction variables.
96    vectorizeLoop(Legal);
97     // register the new loop.
98     cleanup();
99  }
100
101 private:
102   /// Create an empty loop, based on the loop ranges of the old loop.
103   void createEmptyLoop(LoopVectorizationLegality *Legal);
104   /// Copy and widen the instructions from the old loop.
105   void vectorizeLoop(LoopVectorizationLegality *Legal);
106   /// Insert the new loop to the loop hierarchy and pass manager.
107   void cleanup();
108
109   /// This instruction is un-vectorizable. Implement it as a sequence
110   /// of scalars.
111   void scalarizeInstruction(Instruction *Instr);
112
113   /// Create a broadcast instruction. This method generates a broadcast
114   /// instruction (shuffle) for loop invariant values and for the induction
115   /// value. If this is the induction variable then we extend it to N, N+1, ...
116   /// this is needed because each iteration in the loop corresponds to a SIMD
117   /// element.
118   Value *getBroadcastInstrs(Value *V);
119
120   /// This is a helper function used by getBroadcastInstrs. It adds 0, 1, 2 ..
121   /// for each element in the vector. Starting from zero.
122   Value *getConsecutiveVector(Value* Val);
123
124   /// When we go over instructions in the basic block we rely on previous
125   /// values within the current basic block or on loop invariant values.
126   /// When we widen (vectorize) values we place them in the map. If the values
127   /// are not within the map, they have to be loop invariant, so we simply
128   /// broadcast them into a vector.
129   Value *getVectorValue(Value *V);
130
131   /// Get a uniform vector of constant integers. We use this to get
132   /// vectors of ones and zeros for the reduction code.
133   Constant* getUniformVector(unsigned Val, Type* ScalarTy);
134
135   typedef DenseMap<Value*, Value*> ValueMap;
136
137   /// The original loop.
138   Loop *Orig;
139   // Scev analysis to use.
140   ScalarEvolution *SE;
141   // Loop Info.
142   LoopInfo *LI;
143   // Loop Pass Manager;
144   LPPassManager *LPM;
145   // The vectorization factor to use.
146   unsigned VF;
147
148   // The builder that we use
149   IRBuilder<> Builder;
150
151   // --- Vectorization state ---
152
153   /// Middle Block between the vector and the scalar.
154   BasicBlock *LoopMiddleBlock;
155   ///The ExitBlock of the scalar loop.
156   BasicBlock *LoopExitBlock;
157   ///The vector loop body.
158   BasicBlock *LoopVectorBody;
159   ///The scalar loop body.
160   BasicBlock *LoopScalarBody;
161   ///The first bypass block.
162   BasicBlock *LoopBypassBlock;
163
164   /// The new Induction variable which was added to the new block.
165   PHINode *Induction;
166   /// The induction variable of the old basic block.
167   PHINode *OldInduction;
168   // Maps scalars to widened vectors.
169   ValueMap WidenMap;
170 };
171
172 /// Perform the vectorization legality check. This class does not look at the
173 /// profitability of vectorization, only the legality. At the moment the checks
174 /// are very simple and focus on single basic block loops with a constant
175 /// iteration count and no reductions.
176 class LoopVectorizationLegality {
177 public:
178   LoopVectorizationLegality(Loop *Lp, ScalarEvolution *Se, DataLayout *Dl):
179   TheLoop(Lp), SE(Se), DL(Dl), Induction(0) { }
180
181   /// This represents the kinds of reductions that we support.
182   /// We use the enum values to hold the 'identity' value for
183   /// each operand. This value does not change the result if applied.
184   enum ReductionKind {
185     NoReduction = -1, /// Not a reduction.
186     IntegerAdd  = 0,  /// Sum of numbers.
187     IntegerMult = 1  /// Product of numbers.
188   };
189
190   /// This POD struct holds information about reduction variables.
191   struct ReductionDescriptor {
192     // Default C'tor
193     ReductionDescriptor():
194     StartValue(0), LoopExitInstr(0), Kind(NoReduction) {}
195
196     // C'tor.
197     ReductionDescriptor(Value *Start, Instruction *Exit, ReductionKind K):
198     StartValue(Start), LoopExitInstr(Exit), Kind(K) {}
199
200     // The starting value of the reduction.
201     // It does not have to be zero!
202     Value *StartValue;
203     // The instruction who's value is used outside the loop.
204     Instruction *LoopExitInstr;
205     // The kind of the reduction.
206     ReductionKind Kind;
207   };
208
209   /// ReductionList contains the reduction descriptors for all
210   /// of the reductions that were found in the loop.
211   typedef DenseMap<PHINode*, ReductionDescriptor> ReductionList;
212
213   /// Returns the maximum vectorization factor that we *can* use to vectorize
214   /// this loop. This does not mean that it is profitable to vectorize this
215   /// loop, only that it is legal to do so. This may be a large number. We
216   /// can vectorize to any SIMD width below this number.
217   unsigned getLoopMaxVF();
218
219   /// Returns the Induction variable.
220   PHINode *getInduction() {return Induction;}
221
222   /// Returns the reduction variables found in the loop.
223   ReductionList *getReductionVars() { return &Reductions; }
224
225   /// Check that the GEP operands are all uniform except for the last index
226   /// which has to be the induction variable.
227   bool isConsecutiveGep(Value *Ptr);
228
229 private:
230   /// Check if a single basic block loop is vectorizable.
231   /// At this point we know that this is a loop with a constant trip count
232   /// and we only need to check individual instructions.
233   bool canVectorizeBlock(BasicBlock &BB);
234
235   /// When we vectorize loops we may change the order in which
236   /// we read and write from memory. This method checks if it is
237   /// legal to vectorize the code, considering only memory constrains.
238   /// Returns true if BB is vectorizable
239   bool canVectorizeMemory(BasicBlock &BB);
240
241   // Check if a pointer value is known to be disjoint.
242   // Example: Alloca, Global, NoAlias.
243   bool isIdentifiedSafeObject(Value* Val);
244
245   /// Returns True, if 'Phi' is the kind of reduction variable for type
246   /// 'Kind'. If this is a reduction variable, it adds it to ReductionList.
247   bool AddReductionVar(PHINode *Phi, ReductionKind Kind);
248   /// Returns true if the instruction I can be a reduction variable of type
249   /// 'Kind'.
250   bool isReductionInstr(Instruction *I, ReductionKind Kind);
251   /// Returns True, if 'Phi' is an induction variable.
252   bool isInductionVariable(PHINode *Phi);
253
254   /// The loop that we evaluate.
255   Loop *TheLoop;
256   /// Scev analysis.
257   ScalarEvolution *SE;
258   /// DataLayout analysis.
259   DataLayout *DL;
260
261   //  ---  vectorization state --- //
262
263   /// Holds the induction variable.
264   PHINode *Induction;
265   /// Holds the reduction variables.
266   ReductionList Reductions;
267   /// Allowed outside users. This holds the reduction
268   /// vars which can be accessed from outside the loop.
269   SmallPtrSet<Value*, 4> AllowedExit;
270 };
271
272 struct LoopVectorize : public LoopPass {
273   static char ID; // Pass identification, replacement for typeid
274
275   LoopVectorize() : LoopPass(ID) {
276     initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
277   }
278
279   ScalarEvolution *SE;
280   DataLayout *DL;
281   LoopInfo *LI;
282
283   virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
284
285     // Only vectorize innermost loops.
286     if (!L->empty())
287       return false;
288
289     SE = &getAnalysis<ScalarEvolution>();
290     DL = getAnalysisIfAvailable<DataLayout>();
291     LI = &getAnalysis<LoopInfo>();
292
293     DEBUG(dbgs() << "LV: Checking a loop in \"" <<
294           L->getHeader()->getParent()->getName() << "\"\n");
295
296     // Check if it is legal to vectorize the loop.
297     LoopVectorizationLegality LVL(L, SE, DL);
298     unsigned MaxVF = LVL.getLoopMaxVF();
299
300     // Check that we can vectorize using the chosen vectorization width.
301     if (MaxVF < DefaultVectorizationFactor) {
302       DEBUG(dbgs() << "LV: non-vectorizable MaxVF ("<< MaxVF << ").\n");
303       return false;
304     }
305
306     DEBUG(dbgs() << "LV: Found a vectorizable loop ("<< MaxVF << ").\n");
307
308     // If we decided that is is *legal* to vectorizer the loop. Do it.
309     SingleBlockLoopVectorizer LB(L, SE, LI, &LPM, DefaultVectorizationFactor);
310     LB.vectorize(&LVL);
311
312     DEBUG(verifyFunction(*L->getHeader()->getParent()));
313     return true;
314   }
315
316   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
317     LoopPass::getAnalysisUsage(AU);
318     AU.addRequiredID(LoopSimplifyID);
319     AU.addRequiredID(LCSSAID);
320     AU.addRequired<LoopInfo>();
321     AU.addRequired<ScalarEvolution>();
322   }
323
324 };
325
326 Value *SingleBlockLoopVectorizer::getBroadcastInstrs(Value *V) {
327   // Instructions that access the old induction variable
328   // actually want to get the new one.
329   if (V == OldInduction)
330     V = Induction;
331   // Create the types.
332   LLVMContext &C = V->getContext();
333   Type *VTy = VectorType::get(V->getType(), VF);
334   Type *I32 = IntegerType::getInt32Ty(C);
335   Constant *Zero = ConstantInt::get(I32, 0);
336   Value *Zeros = ConstantAggregateZero::get(VectorType::get(I32, VF));
337   Value *UndefVal = UndefValue::get(VTy);
338   // Insert the value into a new vector.
339   Value *SingleElem = Builder.CreateInsertElement(UndefVal, V, Zero);
340   // Broadcast the scalar into all locations in the vector.
341   Value *Shuf = Builder.CreateShuffleVector(SingleElem, UndefVal, Zeros,
342                                              "broadcast");
343   // We are accessing the induction variable. Make sure to promote the
344   // index for each consecutive SIMD lane. This adds 0,1,2 ... to all lanes.
345   if (V == Induction)
346     return getConsecutiveVector(Shuf);
347   return Shuf;
348 }
349
350 Value *SingleBlockLoopVectorizer::getConsecutiveVector(Value* Val) {
351   assert(Val->getType()->isVectorTy() && "Must be a vector");
352   assert(Val->getType()->getScalarType()->isIntegerTy() &&
353          "Elem must be an integer");
354   // Create the types.
355   Type *ITy = Val->getType()->getScalarType();
356   VectorType *Ty = cast<VectorType>(Val->getType());
357   unsigned VLen = Ty->getNumElements();
358   SmallVector<Constant*, 8> Indices;
359
360   // Create a vector of consecutive numbers from zero to VF.
361   for (unsigned i = 0; i < VLen; ++i)
362     Indices.push_back(ConstantInt::get(ITy, i));
363
364   // Add the consecutive indices to the vector value.
365   Constant *Cv = ConstantVector::get(Indices);
366   assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
367   return Builder.CreateAdd(Val, Cv, "induction");
368 }
369
370 bool LoopVectorizationLegality::isConsecutiveGep(Value *Ptr) {
371   GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
372   if (!Gep)
373     return false;
374
375   unsigned NumOperands = Gep->getNumOperands();
376   Value *LastIndex = Gep->getOperand(NumOperands - 1);
377
378   // Check that all of the gep indices are uniform except for the last.
379   for (unsigned i = 0; i < NumOperands - 1; ++i)
380     if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
381       return false;
382
383   // We can emit wide load/stores only of the last index is the induction
384   // variable.
385   const SCEV *Last = SE->getSCEV(LastIndex);
386   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
387     const SCEV *Step = AR->getStepRecurrence(*SE);
388
389     // The memory is consecutive because the last index is consecutive
390     // and all other indices are loop invariant.
391     if (Step->isOne())
392       return true;
393   }
394
395   return false;
396 }
397
398 Value *SingleBlockLoopVectorizer::getVectorValue(Value *V) {
399   assert(!V->getType()->isVectorTy() && "Can't widen a vector");
400   // If we saved a vectorized copy of V, use it.
401   Value *&MapEntry = WidenMap[V];
402   if (MapEntry)
403     return MapEntry;
404
405   // Broadcast V and save the value for future uses.
406   Value *B = getBroadcastInstrs(V);
407   MapEntry = B;
408   return B;
409 }
410
411 Constant*
412 SingleBlockLoopVectorizer::getUniformVector(unsigned Val, Type* ScalarTy) {
413   SmallVector<Constant*, 8> Indices;
414   // Create a vector of consecutive numbers from zero to VF.
415   for (unsigned i = 0; i < VF; ++i)
416     Indices.push_back(ConstantInt::get(ScalarTy, Val));
417
418   // Add the consecutive indices to the vector value.
419   return ConstantVector::get(Indices);
420 }
421
422 void SingleBlockLoopVectorizer::scalarizeInstruction(Instruction *Instr) {
423   assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
424   // Holds vector parameters or scalars, in case of uniform vals.
425   SmallVector<Value*, 8> Params;
426
427   // Find all of the vectorized parameters.
428   for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
429     Value *SrcOp = Instr->getOperand(op);
430
431     // If we are accessing the old induction variable, use the new one.
432     if (SrcOp == OldInduction) {
433       Params.push_back(getBroadcastInstrs(Induction));
434       continue;
435     }
436
437     // Try using previously calculated values.
438     Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
439
440     // If the src is an instruction that appeared earlier in the basic block
441     // then it should already be vectorized.
442     if (SrcInst && SrcInst->getParent() == Instr->getParent()) {
443       assert(WidenMap.count(SrcInst) && "Source operand is unavailable");
444       // The parameter is a vector value from earlier.
445       Params.push_back(WidenMap[SrcInst]);
446     } else {
447       // The parameter is a scalar from outside the loop. Maybe even a constant.
448       Params.push_back(SrcOp);
449     }
450   }
451
452   assert(Params.size() == Instr->getNumOperands() &&
453          "Invalid number of operands");
454
455   // Does this instruction return a value ?
456   bool IsVoidRetTy = Instr->getType()->isVoidTy();
457   Value *VecResults = 0;
458
459   // If we have a return value, create an empty vector. We place the scalarized
460   // instructions in this vector.
461   if (!IsVoidRetTy)
462     VecResults = UndefValue::get(VectorType::get(Instr->getType(), VF));
463
464   // For each scalar that we create.
465   for (unsigned i = 0; i < VF; ++i) {
466     Instruction *Cloned = Instr->clone();
467     if (!IsVoidRetTy)
468       Cloned->setName(Instr->getName() + ".cloned");
469     // Replace the operands of the cloned instrucions with extracted scalars.
470     for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
471       Value *Op = Params[op];
472       // Param is a vector. Need to extract the right lane.
473       if (Op->getType()->isVectorTy())
474         Op = Builder.CreateExtractElement(Op, Builder.getInt32(i));
475       Cloned->setOperand(op, Op);
476     }
477
478     // Place the cloned scalar in the new loop.
479     Builder.Insert(Cloned);
480
481     // If the original scalar returns a value we need to place it in a vector
482     // so that future users will be able to use it.
483     if (!IsVoidRetTy)
484       VecResults = Builder.CreateInsertElement(VecResults, Cloned,
485                                                Builder.getInt32(i));
486   }
487
488   if (!IsVoidRetTy)
489     WidenMap[Instr] = VecResults;
490 }
491
492 void SingleBlockLoopVectorizer::createEmptyLoop(LoopVectorizationLegality *Legal) {
493   /*
494    In this function we generate a new loop. The new loop will contain
495    the vectorized instructions while the old loop will continue to run the
496    scalar remainder.
497
498    [  ] <-- vector loop bypass.
499   /  |
500  /   v
501 |   [ ]     <-- vector pre header.
502 |    |
503 |    v
504 |   [  ] \
505 |   [  ]_|   <-- vector loop.
506 |    |
507  \   v
508    >[ ]   <--- middle-block.
509   /  |
510  /   v
511 |   [ ]     <--- new preheader.
512 |    |
513 |    v
514 |   [ ] \
515 |   [ ]_|   <-- old scalar loop to handle remainder.
516  \   |
517   \  v
518    >[ ]     <-- exit block.
519    ...
520    */
521
522   // This is the original scalar-loop preheader.
523   BasicBlock *BypassBlock = Orig->getLoopPreheader();
524   BasicBlock *ExitBlock = Orig->getExitBlock();
525   assert(ExitBlock && "Must have an exit block");
526
527   assert(Orig->getNumBlocks() == 1 && "Invalid loop");
528   assert(BypassBlock && "Invalid loop structure");
529
530   BasicBlock *VectorPH =
531       BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
532   BasicBlock *VecBody = VectorPH->splitBasicBlock(VectorPH->getTerminator(),
533                                                  "vector.body");
534
535   BasicBlock *MiddleBlock = VecBody->splitBasicBlock(VecBody->getTerminator(),
536                                                   "middle.block");
537   BasicBlock *ScalarPH =
538     MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(),
539                                  "scalar.preheader");
540   // Find the induction variable.
541   BasicBlock *OldBasicBlock = Orig->getHeader();
542   OldInduction = Legal->getInduction();
543   assert(OldInduction && "We must have a single phi node.");
544   Type *IdxTy = OldInduction->getType();
545
546   // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
547   // inside the loop.
548   Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
549
550   // Generate the induction variable.
551   Induction = Builder.CreatePHI(IdxTy, 2, "index");
552   Constant *Zero = ConstantInt::get(IdxTy, 0);
553   Constant *Step = ConstantInt::get(IdxTy, VF);
554
555   // Find the loop boundaries.
556   const SCEV *ExitCount = SE->getExitCount(Orig, Orig->getHeader());
557   assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
558
559   // Get the total trip count from the count by adding 1.
560   ExitCount = SE->getAddExpr(ExitCount,
561                              SE->getConstant(ExitCount->getType(), 1));
562
563   // Expand the trip count and place the new instructions in the preheader.
564   // Notice that the pre-header does not change, only the loop body.
565   SCEVExpander Exp(*SE, "induction");
566   Instruction *Loc = BypassBlock->getTerminator();
567
568   // We may need to extend the index in case there is a type mismatch.
569   // We know that the count starts at zero and does not overflow.
570   // We are using Zext because it should be less expensive.
571   if (ExitCount->getType() != Induction->getType())
572     ExitCount = SE->getZeroExtendExpr(ExitCount, IdxTy);
573
574   // Count holds the overall loop count (N).
575   Value *Count = Exp.expandCodeFor(ExitCount, Induction->getType(), Loc);
576   // Now we need to generate the expression for N - (N % VF), which is
577   // the part that the vectorized body will execute.
578   Constant *CIVF = ConstantInt::get(IdxTy, VF);
579   Value *R = BinaryOperator::CreateURem(Count, CIVF, "n.mod.vf", Loc);
580   Value *CountRoundDown = BinaryOperator::CreateSub(Count, R, "n.vec", Loc);
581
582   // Now, compare the new count to zero. If it is zero, jump to the scalar part.
583   Value *Cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
584                                CountRoundDown, ConstantInt::getNullValue(IdxTy),
585                                "cmp.zero", Loc);
586   BranchInst::Create(MiddleBlock, VectorPH, Cmp, Loc);
587   // Remove the old terminator.
588   Loc->eraseFromParent();
589
590   // Add a check in the middle block to see if we have completed
591   // all of the iterations in the first vector loop.
592   // If (N - N%VF) == N, then we *don't* need to run the remainder.
593   Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, Count,
594                                 CountRoundDown, "cmp.n",
595                                 MiddleBlock->getTerminator());
596
597   BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
598   // Remove the old terminator.
599   MiddleBlock->getTerminator()->eraseFromParent();
600
601   // Create i+1 and fill the PHINode.
602   Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
603   Induction->addIncoming(Zero, VectorPH);
604   Induction->addIncoming(NextIdx, VecBody);
605   // Create the compare.
606   Value *ICmp = Builder.CreateICmpEQ(NextIdx, CountRoundDown);
607   Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
608
609   // Now we have two terminators. Remove the old one from the block.
610   VecBody->getTerminator()->eraseFromParent();
611
612   // Fix the scalar body iteration count.
613   unsigned BlockIdx = OldInduction->getBasicBlockIndex(ScalarPH);
614   OldInduction->setIncomingValue(BlockIdx, CountRoundDown);
615
616   // Get ready to start creating new instructions into the vectorized body.
617   Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
618
619   // Register the new loop.
620   Loop* Lp = new Loop();
621   LPM->insertLoop(Lp, Orig->getParentLoop());
622
623   Lp->addBasicBlockToLoop(VecBody, LI->getBase());
624
625   Loop *ParentLoop = Orig->getParentLoop();
626   if (ParentLoop) {
627     ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase());
628     ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase());
629     ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase());
630   }
631
632   // Save the state.
633   LoopMiddleBlock = MiddleBlock;
634   LoopExitBlock = ExitBlock;
635   LoopVectorBody = VecBody;
636   LoopScalarBody = OldBasicBlock;
637   LoopBypassBlock = BypassBlock;
638 }
639
640 void
641 SingleBlockLoopVectorizer::vectorizeLoop(LoopVectorizationLegality *Legal) {
642   typedef SmallVector<PHINode*, 4> PhiVector;
643   BasicBlock &BB = *Orig->getHeader();
644   Constant *Zero = ConstantInt::get(
645     IntegerType::getInt32Ty(BB.getContext()), 0);
646
647   // In order to support reduction variables we need to be able to vectorize
648   // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
649   // steages. First, we create a new vector PHI node with no incoming edges.
650   // We use this value when we vectorize all of the instructions that use the
651   // PHI. Next, after all of the instructions in the block are complete we
652   // add the new incoming edges to the PHI. At this point all of the
653   // instructions in the basic block are vectorized, so we can use them to
654   // construct the PHI.
655   PhiVector PHIsToFix;
656
657   // For each instruction in the old loop.
658   for (BasicBlock::iterator it = BB.begin(), e = BB.end(); it != e; ++it) {
659     Instruction *Inst = it;
660
661     switch (Inst->getOpcode()) {
662       case Instruction::Br:
663         // Nothing to do for PHIs and BR, since we already took care of the
664         // loop control flow instructions.
665         continue;
666       case Instruction::PHI:{
667         PHINode* P = cast<PHINode>(Inst);
668         // Special handling for the induction var.
669         if (OldInduction == Inst)
670           continue;
671         // This is phase one of vectorizing PHIs.
672         // This has to be a reduction variable.
673         assert(Legal->getReductionVars()->count(P) && "Not a Reduction");
674         Type *VecTy = VectorType::get(Inst->getType(), VF);
675         WidenMap[Inst] = Builder.CreatePHI(VecTy, 2, "vec.phi");
676         PHIsToFix.push_back(P);
677         continue;
678       }
679       case Instruction::Add:
680       case Instruction::FAdd:
681       case Instruction::Sub:
682       case Instruction::FSub:
683       case Instruction::Mul:
684       case Instruction::FMul:
685       case Instruction::UDiv:
686       case Instruction::SDiv:
687       case Instruction::FDiv:
688       case Instruction::URem:
689       case Instruction::SRem:
690       case Instruction::FRem:
691       case Instruction::Shl:
692       case Instruction::LShr:
693       case Instruction::AShr:
694       case Instruction::And:
695       case Instruction::Or:
696       case Instruction::Xor: {
697         // Just widen binops.
698         BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
699         Value *A = getVectorValue(Inst->getOperand(0));
700         Value *B = getVectorValue(Inst->getOperand(1));
701         // Use this vector value for all users of the original instruction.
702         WidenMap[Inst] = Builder.CreateBinOp(BinOp->getOpcode(), A, B);
703         break;
704       }
705       case Instruction::Select: {
706         // Widen selects.
707         // TODO: If the selector is loop invariant we can issue a select
708         // instruction with a scalar condition.
709         Value *A = getVectorValue(Inst->getOperand(0));
710         Value *B = getVectorValue(Inst->getOperand(1));
711         Value *C = getVectorValue(Inst->getOperand(2));
712         WidenMap[Inst] = Builder.CreateSelect(A, B, C);
713         break;
714       }
715
716       case Instruction::ICmp:
717       case Instruction::FCmp: {
718         // Widen compares. Generate vector compares.
719         bool FCmp = (Inst->getOpcode() == Instruction::FCmp);
720         CmpInst *Cmp = dyn_cast<CmpInst>(Inst);
721         Value *A = getVectorValue(Inst->getOperand(0));
722         Value *B = getVectorValue(Inst->getOperand(1));
723         if (FCmp)
724           WidenMap[Inst] = Builder.CreateFCmp(Cmp->getPredicate(), A, B);
725         else
726           WidenMap[Inst] = Builder.CreateICmp(Cmp->getPredicate(), A, B);
727         break;
728       }
729
730       case Instruction::Store: {
731         // Attempt to issue a wide store.
732         StoreInst *SI = dyn_cast<StoreInst>(Inst);
733         Type *StTy = VectorType::get(SI->getValueOperand()->getType(), VF);
734         Value *Ptr = SI->getPointerOperand();
735         unsigned Alignment = SI->getAlignment();
736         GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
737         // This store does not use GEPs.
738         if (!Legal->isConsecutiveGep(Gep)) {
739           scalarizeInstruction(Inst);
740           break;
741         }
742
743         // The last index does not have to be the induction. It can be
744         // consecutive and be a function of the index. For example A[I+1];
745         unsigned NumOperands = Gep->getNumOperands();
746         Value *LastIndex = getVectorValue(Gep->getOperand(NumOperands -1));
747         LastIndex = Builder.CreateExtractElement(LastIndex, Builder.getInt32(0));
748
749         // Create the new GEP with the new induction variable.
750         GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
751         Gep2->setOperand(NumOperands - 1, LastIndex);
752         Ptr = Builder.Insert(Gep2);
753         Ptr = Builder.CreateBitCast(Ptr, StTy->getPointerTo());
754         Value *Val = getVectorValue(SI->getValueOperand());
755         Builder.CreateStore(Val, Ptr)->setAlignment(Alignment);
756         break;
757       }
758       case Instruction::Load: {
759         // Attempt to issue a wide load.
760         LoadInst *LI = dyn_cast<LoadInst>(Inst);
761         Type *RetTy = VectorType::get(LI->getType(), VF);
762         Value *Ptr = LI->getPointerOperand();
763         unsigned Alignment = LI->getAlignment();
764         GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
765
766         // We don't have a gep. Scalarize the load.
767         if (!Legal->isConsecutiveGep(Gep)) {
768           scalarizeInstruction(Inst);
769           break;
770         }
771
772         // The last index does not have to be the induction. It can be
773         // consecutive and be a function of the index. For example A[I+1];
774         unsigned NumOperands = Gep->getNumOperands();
775         Value *LastIndex = getVectorValue(Gep->getOperand(NumOperands -1));
776         LastIndex = Builder.CreateExtractElement(LastIndex, Builder.getInt32(0));
777
778         // Create the new GEP with the new induction variable.
779         GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
780         Gep2->setOperand(NumOperands - 1, LastIndex);
781         Ptr = Builder.Insert(Gep2);
782         Ptr = Builder.CreateBitCast(Ptr, RetTy->getPointerTo());
783         LI = Builder.CreateLoad(Ptr);
784         LI->setAlignment(Alignment);
785         // Use this vector value for all users of the load.
786         WidenMap[Inst] = LI;
787         break;
788       }
789       case Instruction::ZExt:
790       case Instruction::SExt:
791       case Instruction::FPToUI:
792       case Instruction::FPToSI:
793       case Instruction::FPExt:
794       case Instruction::PtrToInt:
795       case Instruction::IntToPtr:
796       case Instruction::SIToFP:
797       case Instruction::UIToFP:
798       case Instruction::Trunc:
799       case Instruction::FPTrunc:
800       case Instruction::BitCast: {
801         /// Vectorize bitcasts.
802         CastInst *CI = dyn_cast<CastInst>(Inst);
803         Value *A = getVectorValue(Inst->getOperand(0));
804         Type *DestTy = VectorType::get(CI->getType()->getScalarType(), VF);
805         WidenMap[Inst] = Builder.CreateCast(CI->getOpcode(), A, DestTy);
806         break;
807       }
808
809       default:
810         /// All other instructions are unsupported. Scalarize them.
811         scalarizeInstruction(Inst);
812         break;
813     }// end of switch.
814   }// end of for_each instr.
815
816   // At this point every instruction in the original loop is widended to
817   // a vector form. We are almost done. Now, we need to fix the PHI nodes
818   // that we vectorized. The PHI nodes are currently empty because we did
819   // not want to introduce cycles. Notice that the remaining PHI nodes
820   // that we need to fix are reduction variables.
821
822   // Create the 'reduced' values for each of the induction vars.
823   // The reduced values are the vector values that we scalarize and combine
824   // after the loop is finished.
825   for (PhiVector::iterator it = PHIsToFix.begin(), e = PHIsToFix.end();
826        it != e; ++it) {
827     PHINode *RdxPhi = *it;
828     PHINode *VecRdxPhi = dyn_cast<PHINode>(WidenMap[RdxPhi]);
829     assert(RdxPhi && "Unable to recover vectorized PHI");
830
831     // Find the reduction variable descriptor.
832     assert(Legal->getReductionVars()->count(RdxPhi) &&
833            "Unable to find the reduction variable");
834     LoopVectorizationLegality::ReductionDescriptor RdxDesc =
835       (*Legal->getReductionVars())[RdxPhi];
836
837     // We need to generate a reduction vector from the incoming scalar.
838     // To do so, we need to generate the 'identity' vector and overide
839     // one of the elements with the incoming scalar reduction. We need
840     // to do it in the vector-loop preheader.
841     Builder.SetInsertPoint(LoopBypassBlock->getTerminator());
842
843     // This is the vector-clone of the value that leaves the loop.
844     Value *VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
845     Type *VecTy = VectorExit->getType();
846
847     // Find the reduction identity variable. The value of the enum is the
848     // identity. Zero for addition. One for Multiplication.
849     unsigned IdentitySclr =  RdxDesc.Kind;
850     Constant *Identity = getUniformVector(IdentitySclr,
851                                           VecTy->getScalarType());
852
853     // This vector is the Identity vector where the first element is the
854     // incoming scalar reduction.
855     Value *VectorStart = Builder.CreateInsertElement(Identity,
856                                                     RdxDesc.StartValue, Zero);
857
858
859     // Fix the vector-loop phi.
860     // We created the induction variable so we know that the
861     // preheader is the first entry.
862     BasicBlock *VecPreheader = Induction->getIncomingBlock(0);
863
864     // Reductions do not have to start at zero. They can start with
865     // any loop invariant values.
866     VecRdxPhi->addIncoming(VectorStart, VecPreheader);
867     unsigned SelfEdgeIdx = (RdxPhi)->getBasicBlockIndex(LoopScalarBody);
868     Value *Val = getVectorValue(RdxPhi->getIncomingValue(SelfEdgeIdx));
869     VecRdxPhi->addIncoming(Val, LoopVectorBody);
870
871     // Before each round, move the insertion point right between
872     // the PHIs and the values we are going to write.
873     // This allows us to write both PHINodes and the extractelement
874     // instructions.
875     Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
876
877     // This PHINode contains the vectorized reduction variable, or
878     // the initial value vector, if we bypass the vector loop.
879     PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
880     NewPhi->addIncoming(VectorStart, LoopBypassBlock);
881     NewPhi->addIncoming(getVectorValue(RdxDesc.LoopExitInstr), LoopVectorBody);
882
883     // Extract the first scalar.
884     Value *Scalar0 =
885       Builder.CreateExtractElement(NewPhi, Builder.getInt32(0));
886     // Extract and sum the remaining vector elements.
887     for (unsigned i=1; i < VF; ++i) {
888       Value *Scalar1 =
889         Builder.CreateExtractElement(NewPhi, Builder.getInt32(i));
890       if (RdxDesc.Kind == LoopVectorizationLegality::IntegerAdd) {
891         Scalar0 = Builder.CreateAdd(Scalar0, Scalar1);
892       } else {
893         Scalar0 = Builder.CreateMul(Scalar0, Scalar1);
894       }
895     }
896
897     // Now, we need to fix the users of the reduction variable
898     // inside and outside of the scalar remainder loop.
899     // We know that the loop is in LCSSA form. We need to update the
900     // PHI nodes in the exit blocks.
901     for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
902          LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
903       PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
904       if (!LCSSAPhi) continue;
905
906       // All PHINodes need to have a single entry edge, or two if
907       // we already fixed them.
908       assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
909
910       // We found our reduction value exit-PHI. Update it with the
911       // incoming bypass edge.
912       if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
913         // Add an edge coming from the bypass.
914         LCSSAPhi->addIncoming(Scalar0, LoopMiddleBlock);
915         break;
916       }
917     }// end of the LCSSA phi scan.
918
919     // Fix the scalar loop reduction variable with the incoming reduction sum
920     // from the vector body and from the backedge value.
921     int IncomingEdgeBlockIdx = (RdxPhi)->getBasicBlockIndex(LoopScalarBody);
922     int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1); // The other block.
923     (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, Scalar0);
924     (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
925   }// end of for each redux variable.
926 }
927
928 void SingleBlockLoopVectorizer::cleanup() {
929   // The original basic block.
930   SE->forgetLoop(Orig);
931 }
932
933 unsigned LoopVectorizationLegality::getLoopMaxVF() {
934   if (!TheLoop->getLoopPreheader()) {
935     assert(false && "No preheader!!");
936     DEBUG(dbgs() << "LV: Loop not normalized." << "\n");
937     return  1;
938   }
939
940   // We can only vectorize single basic block loops.
941   unsigned NumBlocks = TheLoop->getNumBlocks();
942   if (NumBlocks != 1) {
943     DEBUG(dbgs() << "LV: Too many blocks:" << NumBlocks << "\n");
944     return 1;
945   }
946
947   // We need to have a loop header.
948   BasicBlock *BB = TheLoop->getHeader();
949   DEBUG(dbgs() << "LV: Found a loop: " << BB->getName() << "\n");
950
951   // Go over each instruction and look at memory deps.
952   if (!canVectorizeBlock(*BB)) {
953     DEBUG(dbgs() << "LV: Can't vectorize this loop header\n");
954     return 1;
955   }
956
957   // ScalarEvolution needs to be able to find the exit count.
958   const SCEV *ExitCount = SE->getExitCount(TheLoop, BB);
959   if (ExitCount == SE->getCouldNotCompute()) {
960     DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
961     return 1;
962   }
963
964   DEBUG(dbgs() << "LV: We can vectorize this loop!\n");
965
966   // Okay! We can vectorize. At this point we don't have any other mem analysis
967   // which may limit our maximum vectorization factor, so just return the
968   // maximum SIMD size.
969   return DefaultVectorizationFactor;
970 }
971
972 bool LoopVectorizationLegality::canVectorizeBlock(BasicBlock &BB) {
973   // Scan the instructions in the block and look for hazards.
974   for (BasicBlock::iterator it = BB.begin(), e = BB.end(); it != e; ++it) {
975     Instruction *I = it;
976
977     PHINode *Phi = dyn_cast<PHINode>(I);
978     if (Phi) {
979       // This should not happen because the loop should be normalized.
980       if (Phi->getNumIncomingValues() != 2) {
981         DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
982         return false;
983       }
984       // We only look at integer phi nodes.
985       if (!Phi->getType()->isIntegerTy()) {
986         DEBUG(dbgs() << "LV: Found an non-int PHI.\n");
987         return false;
988       }
989
990       if (isInductionVariable(Phi)) {
991         if (Induction) {
992           DEBUG(dbgs() << "LV: Found too many inductions."<< *Phi <<"\n");
993           return false;
994         }
995         DEBUG(dbgs() << "LV: Found the induction PHI."<< *Phi <<"\n");
996         Induction = Phi;
997         continue;
998       }
999       if (AddReductionVar(Phi, IntegerAdd)) {
1000         DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
1001         continue;
1002       }
1003       if (AddReductionVar(Phi, IntegerMult)) {
1004         DEBUG(dbgs() << "LV: Found an Mult reduction PHI."<< *Phi <<"\n");
1005         continue;
1006       }
1007
1008       DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
1009       return false;
1010     }// end of PHI handling
1011
1012     // We still don't handle functions.
1013     CallInst *CI = dyn_cast<CallInst>(I);
1014     if (CI) {
1015       DEBUG(dbgs() << "LV: Found a call site:"<<
1016             CI->getCalledFunction()->getName() << "\n");
1017       return false;
1018     }
1019
1020     // We do not re-vectorize vectors.
1021     if (!VectorType::isValidElementType(I->getType()) &&
1022         !I->getType()->isVoidTy()) {
1023       DEBUG(dbgs() << "LV: Found unvectorizable type." << "\n");
1024       return false;
1025     }
1026
1027     // Reduction instructions are allowed to have exit users.
1028     // All other instructions must not have external users.
1029     if (!AllowedExit.count(I))
1030       //Check that all of the users of the loop are inside the BB.
1031       for (Value::use_iterator it = I->use_begin(), e = I->use_end();
1032            it != e; ++it) {
1033         Instruction *U = cast<Instruction>(*it);
1034         // This user may be a reduction exit value.
1035         BasicBlock *Parent = U->getParent();
1036         if (Parent != &BB) {
1037           DEBUG(dbgs() << "LV: Found an outside user for : "<< *U << "\n");
1038           return false;
1039         }
1040     }
1041   } // next instr.
1042
1043   if (!Induction) {
1044       DEBUG(dbgs() << "LV: Did not find an induction var.\n");
1045       return false;
1046   }
1047
1048   // If the memory dependencies do not prevent us from
1049   // vectorizing, then vectorize.
1050   return canVectorizeMemory(BB);
1051 }
1052
1053 bool LoopVectorizationLegality::canVectorizeMemory(BasicBlock &BB) {
1054   typedef SmallVector<Value*, 16> ValueVector;
1055   typedef SmallPtrSet<Value*, 16> ValueSet;
1056   // Holds the Load and Store *instructions*.
1057   ValueVector Loads;
1058   ValueVector Stores;
1059
1060   // Scan the BB and collect legal loads and stores.
1061   for (BasicBlock::iterator it = BB.begin(), e = BB.end(); it != e; ++it) {
1062     Instruction *I = it;
1063
1064     // If this is a load, save it. If this instruction can read from memory
1065     // but is not a load, then we quit. Notice that we don't handle function
1066     // calls that read or write.
1067     if (I->mayReadFromMemory()) {
1068       LoadInst *Ld = dyn_cast<LoadInst>(I);
1069       if (!Ld) return false;
1070       if (!Ld->isSimple()) {
1071         DEBUG(dbgs() << "LV: Found a non-simple load.\n");
1072         return false;
1073       }
1074       Loads.push_back(Ld);
1075       continue;
1076     }
1077
1078     // Save store instructions. Abort if other instructions write to memory.
1079     if (I->mayWriteToMemory()) {
1080       StoreInst *St = dyn_cast<StoreInst>(I);
1081       if (!St) return false;
1082       if (!St->isSimple()) {
1083         DEBUG(dbgs() << "LV: Found a non-simple store.\n");
1084         return false;
1085       }
1086       Stores.push_back(St);
1087     }
1088   } // next instr.
1089
1090   // Now we have two lists that hold the loads and the stores.
1091   // Next, we find the pointers that they use.
1092
1093   // Check if we see any stores. If there are no stores, then we don't
1094   // care if the pointers are *restrict*.
1095   if (!Stores.size()) {
1096         DEBUG(dbgs() << "LV: Found a read-only loop!\n");
1097         return true;
1098   }
1099
1100   // Holds the read and read-write *pointers* that we find.
1101   ValueVector Reads;
1102   ValueVector ReadWrites;
1103
1104   // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
1105   // multiple times on the same object. If the ptr is accessed twice, once
1106   // for read and once for write, it will only appear once (on the write
1107   // list). This is okay, since we are going to check for conflicts between
1108   // writes and between reads and writes, but not between reads and reads.
1109   ValueSet Seen;
1110
1111   ValueVector::iterator I, IE;
1112   for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
1113     StoreInst *ST = dyn_cast<StoreInst>(*I);
1114     assert(ST && "Bad StoreInst");
1115     Value* Ptr = ST->getPointerOperand();
1116     // If we did *not* see this pointer before, insert it to
1117     // the read-write list. At this phase it is only a 'write' list.
1118     if (Seen.insert(Ptr))
1119       ReadWrites.push_back(Ptr);
1120   }
1121
1122   for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
1123     LoadInst *LD = dyn_cast<LoadInst>(*I);
1124     assert(LD && "Bad LoadInst");
1125     Value* Ptr = LD->getPointerOperand();
1126     // If we did *not* see this pointer before, insert it to the
1127     // read list. If we *did* see it before, then it is already in
1128     // the read-write list. This allows us to vectorize expressions
1129     // such as A[i] += x;  Because the address of A[i] is a read-write
1130     // pointer. This only works if the index of A[i] is consecutive.
1131     // If the address of i is unknown (for example A[B[i]]) then we may
1132     // read a few words, modify, and write a few words, and some of the
1133     // words may be written to the same address.
1134     if (Seen.insert(Ptr) || !isConsecutiveGep(Ptr))
1135       Reads.push_back(Ptr);
1136   }
1137
1138   // Now that the pointers are in two lists (Reads and ReadWrites), we
1139   // can check that there are no conflicts between each of the writes and
1140   // between the writes to the reads.
1141   ValueSet WriteObjects;
1142   ValueVector TempObjects;
1143
1144   // Check that the read-writes do not conflict with other read-write
1145   // pointers.
1146   for (I = ReadWrites.begin(), IE = ReadWrites.end(); I != IE; ++I) {
1147     GetUnderlyingObjects(*I, TempObjects, DL);
1148     for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end();
1149          it != e; ++it) {
1150       if (!isIdentifiedSafeObject(*it)) {
1151         DEBUG(dbgs() << "LV: Found an unidentified write ptr:"<< **it <<"\n");
1152         return false;
1153       }
1154       if (!WriteObjects.insert(*it)) {
1155         DEBUG(dbgs() << "LV: Found a possible write-write reorder:"
1156               << **it <<"\n");
1157         return false;
1158       }
1159     }
1160     TempObjects.clear();
1161   }
1162
1163   /// Check that the reads don't conflict with the read-writes.
1164   for (I = Reads.begin(), IE = Reads.end(); I != IE; ++I) {
1165     GetUnderlyingObjects(*I, TempObjects, DL);
1166     for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end();
1167          it != e; ++it) {
1168       if (!isIdentifiedSafeObject(*it)) {
1169         DEBUG(dbgs() << "LV: Found an unidentified read ptr:"<< **it <<"\n");
1170         return false;
1171       }
1172       if (WriteObjects.count(*it)) {
1173         DEBUG(dbgs() << "LV: Found a possible read/write reorder:"
1174               << **it <<"\n");
1175         return false;
1176       }
1177     }
1178     TempObjects.clear();
1179   }
1180
1181   // All is okay.
1182   return true;
1183 }
1184
1185 /// Checks if the value is a Global variable or if it is an Arguments
1186 /// marked with the NoAlias attribute.
1187 bool LoopVectorizationLegality::isIdentifiedSafeObject(Value* Val) {
1188   assert(Val && "Invalid value");
1189   if (isa<GlobalValue>(Val))
1190     return true;
1191   if (isa<AllocaInst>(Val))
1192     return true;
1193   if (Argument *A = dyn_cast<Argument>(Val))
1194     return A->hasNoAliasAttr();
1195   return false;
1196 }
1197
1198 bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi,
1199                                                 ReductionKind Kind) {
1200   if (Phi->getNumIncomingValues() != 2)
1201     return false;
1202
1203   // Find the possible incoming reduction variable.
1204   BasicBlock *BB = Phi->getParent();
1205   int SelfEdgeIdx = Phi->getBasicBlockIndex(BB);
1206   int InEdgeBlockIdx = (SelfEdgeIdx ? 0 : 1); // The other entry.
1207   Value *RdxStart = Phi->getIncomingValue(InEdgeBlockIdx);
1208
1209   // ExitInstruction is the single value which is used outside the loop.
1210   // We only allow for a single reduction value to be used outside the loop.
1211   // This includes users of the reduction, variables (which form a cycle
1212   // which ends in the phi node).
1213   Instruction *ExitInstruction = 0;
1214
1215   // Iter is our iterator. We start with the PHI node and scan for all of the
1216   // users of this instruction. All users must be instructions which can be
1217   // used as reduction variables (such as ADD). We may have a single
1218   // out-of-block user. They cycle must end with the original PHI.
1219   // Also, we can't have multiple block-local users.
1220   Instruction *Iter = Phi;
1221   while (true) {
1222     // Any reduction instr must be of one of the allowed kinds.
1223     if (!isReductionInstr(Iter, Kind))
1224       return false;
1225
1226     // Did we found a user inside this block ?
1227     bool FoundInBlockUser = false;
1228     // Did we reach the initial PHI node ?
1229     bool FoundStartPHI = false;
1230
1231     // If the instruction has no users then this is a broken
1232     // chain and can't be a reduction variable.
1233     if (Iter->use_empty())
1234       return false;
1235
1236     // For each of the *users* of iter.
1237     for (Value::use_iterator it = Iter->use_begin(), e = Iter->use_end();
1238          it != e; ++it) {
1239       Instruction *U = cast<Instruction>(*it);
1240       // We already know that the PHI is a user.
1241       if (U == Phi) {
1242         FoundStartPHI = true;
1243         continue;
1244       }
1245       // Check if we found the exit user.
1246       BasicBlock *Parent = U->getParent();
1247       if (Parent != BB) {
1248         // We must have a single exit instruction.
1249         if (ExitInstruction != 0)
1250           return false;
1251         ExitInstruction = Iter;
1252       }
1253       // We can't have multiple inside users.
1254       if (FoundInBlockUser)
1255         return false;
1256       FoundInBlockUser = true;
1257       Iter = U;
1258     }
1259
1260     // We found a reduction var if we have reached the original
1261     // phi node and we only have a single instruction with out-of-loop
1262     // users.
1263    if (FoundStartPHI && ExitInstruction) {
1264      // This instruction is allowed to have out-of-loop users.
1265      AllowedExit.insert(ExitInstruction);
1266
1267      // Save the description of this reduction variable.
1268      ReductionDescriptor RD(RdxStart, ExitInstruction, Kind);
1269      Reductions[Phi] = RD;
1270      return true;
1271    }
1272   }
1273 }
1274
1275 bool
1276 LoopVectorizationLegality::isReductionInstr(Instruction *I,
1277                                             ReductionKind Kind) {
1278     switch (I->getOpcode()) {
1279     default:
1280       return false;
1281     case Instruction::PHI:
1282       // possibly.
1283       return true;
1284     case Instruction::Add:
1285     case Instruction::Sub:
1286       return Kind == IntegerAdd;
1287     case Instruction::Mul:
1288     case Instruction::UDiv:
1289     case Instruction::SDiv:
1290       return Kind == IntegerMult;
1291     }
1292 }
1293
1294 bool LoopVectorizationLegality::isInductionVariable(PHINode *Phi) {
1295   // Check that the PHI is consecutive and starts at zero.
1296   const SCEV *PhiScev = SE->getSCEV(Phi);
1297   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
1298   if (!AR) {
1299     DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
1300     return false;
1301   }
1302   const SCEV *Step = AR->getStepRecurrence(*SE);
1303   const SCEV *Start = AR->getStart();
1304
1305   if (!Step->isOne() || !Start->isZero()) {
1306     DEBUG(dbgs() << "LV: PHI does not start at zero or steps by one.\n");
1307     return false;
1308   }
1309   return true;
1310 }
1311
1312 } // namespace
1313
1314 char LoopVectorize::ID = 0;
1315 static const char lv_name[] = "Loop Vectorization";
1316 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
1317 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
1318 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
1319 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
1320 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
1321
1322 namespace llvm {
1323   Pass *createLoopVectorizePass() {
1324     return new LoopVectorize();
1325   }
1326 }
1327