When broadcasting invariant scalars into vectors, place the broadcast code in the...
[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 unit that checks for the legality
22 //    of the vectorization.
23 // 3. SingleBlockLoopVectorizer - A unit that performs the actual
24 //    widening of instructions.
25 // 4. LoopVectorizationCostModel - A unit that checks for the profitability
26 //    of vectorization. It decides on the optimal vector width, which
27 //    can be one, if vectorization is not profitable.
28 //
29 //===----------------------------------------------------------------------===//
30 //
31 // The reduction-variable vectorization is based on the paper:
32 //  D. Nuzman and R. Henderson. Multi-platform Auto-vectorization.
33 //
34 // Variable uniformity checks are inspired by:
35 // Karrenberg, R. and Hack, S. Whole Function Vectorization.
36 //
37 // Other ideas/concepts are from:
38 //  A. Zaks and D. Nuzman. Autovectorization in GCC-two years later.
39 //
40 //  S. Maleki, Y. Gao, M. Garzaran, T. Wong and D. Padua.  An Evaluation of
41 //  Vectorizing Compilers.
42 //
43 //===----------------------------------------------------------------------===//
44 #define LV_NAME "loop-vectorize"
45 #define DEBUG_TYPE LV_NAME
46 #include "llvm/Constants.h"
47 #include "llvm/DerivedTypes.h"
48 #include "llvm/Instructions.h"
49 #include "llvm/LLVMContext.h"
50 #include "llvm/Pass.h"
51 #include "llvm/Analysis/LoopPass.h"
52 #include "llvm/Value.h"
53 #include "llvm/Function.h"
54 #include "llvm/Analysis/Verifier.h"
55 #include "llvm/Module.h"
56 #include "llvm/Type.h"
57 #include "llvm/ADT/SmallVector.h"
58 #include "llvm/ADT/StringExtras.h"
59 #include "llvm/Analysis/AliasAnalysis.h"
60 #include "llvm/Analysis/AliasSetTracker.h"
61 #include "llvm/Analysis/ScalarEvolution.h"
62 #include "llvm/Analysis/Dominators.h"
63 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
64 #include "llvm/Analysis/ScalarEvolutionExpander.h"
65 #include "llvm/Analysis/LoopInfo.h"
66 #include "llvm/Analysis/ValueTracking.h"
67 #include "llvm/Transforms/Scalar.h"
68 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
69 #include "llvm/TargetTransformInfo.h"
70 #include "llvm/Support/CommandLine.h"
71 #include "llvm/Support/Debug.h"
72 #include "llvm/Support/raw_ostream.h"
73 #include "llvm/DataLayout.h"
74 #include "llvm/Transforms/Utils/Local.h"
75 #include <algorithm>
76 using namespace llvm;
77
78 static cl::opt<unsigned>
79 VectorizationFactor("force-vector-width", cl::init(0), cl::Hidden,
80           cl::desc("Set the default vectorization width. Zero is autoselect."));
81
82 /// We don't vectorize loops with a known constant trip count below this number.
83 const unsigned TinyTripCountThreshold = 16;
84
85 /// When performing a runtime memory check, do not check more than this
86 /// number of pointers. Notice that the check is quadratic!
87 const unsigned RuntimeMemoryCheckThreshold = 2;
88
89 /// This is the highest vector width that we try to generate.
90 const unsigned MaxVectorSize = 8;
91
92 namespace {
93
94 // Forward declarations.
95 class LoopVectorizationLegality;
96 class LoopVectorizationCostModel;
97
98 /// SingleBlockLoopVectorizer vectorizes loops which contain only one basic
99 /// block to a specified vectorization factor (VF).
100 /// This class performs the widening of scalars into vectors, or multiple
101 /// scalars. This class also implements the following features:
102 /// * It inserts an epilogue loop for handling loops that don't have iteration
103 ///   counts that are known to be a multiple of the vectorization factor.
104 /// * It handles the code generation for reduction variables.
105 /// * Scalarization (implementation using scalars) of un-vectorizable
106 ///   instructions.
107 /// SingleBlockLoopVectorizer does not perform any vectorization-legality
108 /// checks, and relies on the caller to check for the different legality
109 /// aspects. The SingleBlockLoopVectorizer relies on the
110 /// LoopVectorizationLegality class to provide information about the induction
111 /// and reduction variables that were found to a given vectorization factor.
112 class SingleBlockLoopVectorizer {
113 public:
114   /// Ctor.
115   SingleBlockLoopVectorizer(Loop *Orig, ScalarEvolution *Se, LoopInfo *Li,
116                             DominatorTree *Dt, DataLayout *Dl,
117                             LPPassManager *Lpm,
118                             unsigned VecWidth):
119   OrigLoop(Orig), SE(Se), LI(Li), DT(Dt), DL(Dl), LPM(Lpm), VF(VecWidth),
120   Builder(Se->getContext()), Induction(0), OldInduction(0) { }
121
122   // Perform the actual loop widening (vectorization).
123   void vectorize(LoopVectorizationLegality *Legal) {
124     // Create a new empty loop. Unlink the old loop and connect the new one.
125     createEmptyLoop(Legal);
126     // Widen each instruction in the old loop to a new one in the new loop.
127     // Use the Legality module to find the induction and reduction variables.
128     vectorizeLoop(Legal);
129     // Register the new loop and update the analysis passes.
130     updateAnalysis();
131  }
132
133 private:
134   /// Add code that checks at runtime if the accessed arrays overlap.
135   /// Returns the comperator value or NULL if no check is needed.
136   Value *addRuntimeCheck(LoopVectorizationLegality *Legal,
137                          Instruction *Loc);
138   /// Create an empty loop, based on the loop ranges of the old loop.
139   void createEmptyLoop(LoopVectorizationLegality *Legal);
140   /// Copy and widen the instructions from the old loop.
141   void vectorizeLoop(LoopVectorizationLegality *Legal);
142   /// Insert the new loop to the loop hierarchy and pass manager
143   /// and update the analysis passes.
144   void updateAnalysis();
145
146   /// This instruction is un-vectorizable. Implement it as a sequence
147   /// of scalars.
148   void scalarizeInstruction(Instruction *Instr);
149
150   /// Create a broadcast instruction. This method generates a broadcast
151   /// instruction (shuffle) for loop invariant values and for the induction
152   /// value. If this is the induction variable then we extend it to N, N+1, ...
153   /// this is needed because each iteration in the loop corresponds to a SIMD
154   /// element.
155   Value *getBroadcastInstrs(Value *V);
156
157   /// This is a helper function used by getBroadcastInstrs. It adds 0, 1, 2 ..
158   /// for each element in the vector. Starting from zero.
159   Value *getConsecutiveVector(Value* Val);
160
161   /// When we go over instructions in the basic block we rely on previous
162   /// values within the current basic block or on loop invariant values.
163   /// When we widen (vectorize) values we place them in the map. If the values
164   /// are not within the map, they have to be loop invariant, so we simply
165   /// broadcast them into a vector.
166   Value *getVectorValue(Value *V);
167
168   /// Get a uniform vector of constant integers. We use this to get
169   /// vectors of ones and zeros for the reduction code.
170   Constant* getUniformVector(unsigned Val, Type* ScalarTy);
171
172   typedef DenseMap<Value*, Value*> ValueMap;
173
174   /// The original loop.
175   Loop *OrigLoop;
176   // Scev analysis to use.
177   ScalarEvolution *SE;
178   // Loop Info.
179   LoopInfo *LI;
180   // Dominator Tree.
181   DominatorTree *DT;
182   // Data Layout.
183   DataLayout *DL;
184   // Loop Pass Manager;
185   LPPassManager *LPM;
186   // The vectorization factor to use.
187   unsigned VF;
188
189   // The builder that we use
190   IRBuilder<> Builder;
191
192   // --- Vectorization state ---
193
194   /// The vector-loop preheader.
195   BasicBlock *LoopVectorPreHeader;
196   /// The scalar-loop preheader.
197   BasicBlock *LoopScalarPreHeader;
198   /// Middle Block between the vector and the scalar.
199   BasicBlock *LoopMiddleBlock;
200   ///The ExitBlock of the scalar loop.
201   BasicBlock *LoopExitBlock;
202   ///The vector loop body.
203   BasicBlock *LoopVectorBody;
204   ///The scalar loop body.
205   BasicBlock *LoopScalarBody;
206   ///The first bypass block.
207   BasicBlock *LoopBypassBlock;
208
209   /// The new Induction variable which was added to the new block.
210   PHINode *Induction;
211   /// The induction variable of the old basic block.
212   PHINode *OldInduction;
213   // Maps scalars to widened vectors.
214   ValueMap WidenMap;
215 };
216
217 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
218 /// to what vectorization factor.
219 /// This class does not look at the profitability of vectorization, only the
220 /// legality. This class has two main kinds of checks:
221 /// * Memory checks - The code in canVectorizeMemory checks if vectorization
222 ///   will change the order of memory accesses in a way that will change the
223 ///   correctness of the program.
224 /// * Scalars checks - The code in canVectorizeBlock checks for a number
225 ///   of different conditions, such as the availability of a single induction
226 ///   variable, that all types are supported and vectorize-able, etc.
227 /// This code reflects the capabilities of SingleBlockLoopVectorizer.
228 /// This class is also used by SingleBlockLoopVectorizer for identifying
229 /// induction variable and the different reduction variables.
230 class LoopVectorizationLegality {
231 public:
232   LoopVectorizationLegality(Loop *Lp, ScalarEvolution *Se, DataLayout *Dl):
233   TheLoop(Lp), SE(Se), DL(Dl), Induction(0) { }
234
235   /// This represents the kinds of reductions that we support.
236   enum ReductionKind {
237     NoReduction, /// Not a reduction.
238     IntegerAdd,  /// Sum of numbers.
239     IntegerMult, /// Product of numbers.
240     IntegerOr,   /// Bitwise or logical OR of numbers.
241     IntegerAnd,  /// Bitwise or logical AND of numbers.
242     IntegerXor   /// Bitwise or logical XOR of numbers.
243   };
244
245   /// This POD struct holds information about reduction variables.
246   struct ReductionDescriptor {
247     // Default C'tor
248     ReductionDescriptor():
249     StartValue(0), LoopExitInstr(0), Kind(NoReduction) {}
250
251     // C'tor.
252     ReductionDescriptor(Value *Start, Instruction *Exit, ReductionKind K):
253     StartValue(Start), LoopExitInstr(Exit), Kind(K) {}
254
255     // The starting value of the reduction.
256     // It does not have to be zero!
257     Value *StartValue;
258     // The instruction who's value is used outside the loop.
259     Instruction *LoopExitInstr;
260     // The kind of the reduction.
261     ReductionKind Kind;
262   };
263
264   // This POD struct holds information about the memory runtime legality
265   // check that a group of pointers do not overlap.
266   struct RuntimePointerCheck {
267     RuntimePointerCheck(): Need(false) {}
268
269     /// Reset the state of the pointer runtime information.
270     void reset() {
271       Need = false;
272       Pointers.clear();
273       Starts.clear();
274       Ends.clear();
275     }
276
277     /// Insert a pointer and calculate the start and end SCEVs.
278     void insert(ScalarEvolution *SE, Loop *Lp, Value *Ptr) {
279       const SCEV *Sc = SE->getSCEV(Ptr);
280       const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
281       assert(AR && "Invalid addrec expression");
282       const SCEV *Ex = SE->getExitCount(Lp, Lp->getHeader());
283       const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
284       Pointers.push_back(Ptr);
285       Starts.push_back(AR->getStart());
286       Ends.push_back(ScEnd);
287     }
288
289     /// This flag indicates if we need to add the runtime check.
290     bool Need;
291     /// Holds the pointers that we need to check.
292     SmallVector<Value*, 2> Pointers;
293     /// Holds the pointer value at the beginning of the loop.
294     SmallVector<const SCEV*, 2> Starts;
295     /// Holds the pointer value at the end of the loop.
296     SmallVector<const SCEV*, 2> Ends;
297   };
298
299   /// ReductionList contains the reduction descriptors for all
300   /// of the reductions that were found in the loop.
301   typedef DenseMap<PHINode*, ReductionDescriptor> ReductionList;
302
303   /// InductionList saves induction variables and maps them to the initial
304   /// value entring the loop.
305   typedef DenseMap<PHINode*, Value*> InductionList;
306
307   /// Returns true if it is legal to vectorize this loop.
308   /// This does not mean that it is profitable to vectorize this
309   /// loop, only that it is legal to do so.
310   bool canVectorize();
311
312   /// Returns the Induction variable.
313   PHINode *getInduction() {return Induction;}
314
315   /// Returns the reduction variables found in the loop.
316   ReductionList *getReductionVars() { return &Reductions; }
317
318   /// Returns the induction variables found in the loop.
319   InductionList *getInductionVars() { return &Inductions; }
320
321   /// Check if this  pointer is consecutive when vectorizing. This happens
322   /// when the last index of the GEP is the induction variable, or that the
323   /// pointer itself is an induction variable.
324   /// This check allows us to vectorize A[idx] into a wide load/store.
325   bool isConsecutivePtr(Value *Ptr);
326
327   /// Returns true if the value V is uniform within the loop.
328   bool isUniform(Value *V);
329
330   /// Returns true if this instruction will remain scalar after vectorization.
331   bool isUniformAfterVectorization(Instruction* I) {return Uniforms.count(I);}
332
333   /// Returns the information that we collected about runtime memory check.
334   RuntimePointerCheck *getRuntimePointerCheck() {return &PtrRtCheck; }
335 private:
336   /// Check if a single basic block loop is vectorizable.
337   /// At this point we know that this is a loop with a constant trip count
338   /// and we only need to check individual instructions.
339   bool canVectorizeBlock(BasicBlock &BB);
340
341   /// When we vectorize loops we may change the order in which
342   /// we read and write from memory. This method checks if it is
343   /// legal to vectorize the code, considering only memory constrains.
344   /// Returns true if BB is vectorizable
345   bool canVectorizeMemory(BasicBlock &BB);
346
347   /// Returns True, if 'Phi' is the kind of reduction variable for type
348   /// 'Kind'. If this is a reduction variable, it adds it to ReductionList.
349   bool AddReductionVar(PHINode *Phi, ReductionKind Kind);
350   /// Returns true if the instruction I can be a reduction variable of type
351   /// 'Kind'.
352   bool isReductionInstr(Instruction *I, ReductionKind Kind);
353   /// Returns True, if 'Phi' is an induction variable.
354   bool isInductionVariable(PHINode *Phi);
355   /// Return true if can compute the address bounds of Ptr within the loop.
356   bool hasComputableBounds(Value *Ptr);
357
358   /// The loop that we evaluate.
359   Loop *TheLoop;
360   /// Scev analysis.
361   ScalarEvolution *SE;
362   /// DataLayout analysis.
363   DataLayout *DL;
364
365   //  ---  vectorization state --- //
366
367   /// Holds the integer induction variable. This is the counter of the
368   /// loop.
369   PHINode *Induction;
370   /// Holds the reduction variables.
371   ReductionList Reductions;
372   /// Holds all of the induction variables that we found in the loop.
373   /// Notice that inductions don't need to start at zero and that induction
374   /// variables can be pointers.
375   InductionList Inductions;
376
377   /// Allowed outside users. This holds the reduction
378   /// vars which can be accessed from outside the loop.
379   SmallPtrSet<Value*, 4> AllowedExit;
380   /// This set holds the variables which are known to be uniform after
381   /// vectorization.
382   SmallPtrSet<Instruction*, 4> Uniforms;
383   /// We need to check that all of the pointers in this list are disjoint
384   /// at runtime.
385   RuntimePointerCheck PtrRtCheck;
386 };
387
388 /// LoopVectorizationCostModel - estimates the expected speedups due to
389 /// vectorization.
390 /// In many cases vectorization is not profitable. This can happen because
391 /// of a number of reasons. In this class we mainly attempt to predict
392 /// the expected speedup/slowdowns due to the supported instruction set.
393 /// We use the VectorTargetTransformInfo to query the different backends
394 /// for the cost of different operations.
395 class LoopVectorizationCostModel {
396 public:
397   /// C'tor.
398   LoopVectorizationCostModel(Loop *Lp, ScalarEvolution *Se,
399                              LoopVectorizationLegality *Leg,
400                              const VectorTargetTransformInfo *Vtti):
401   TheLoop(Lp), SE(Se), Legal(Leg), VTTI(Vtti) { }
402
403   /// Returns the most profitable vectorization factor for the loop that is
404   /// smaller or equal to the VF argument. This method checks every power
405   /// of two up to VF.
406   unsigned findBestVectorizationFactor(unsigned VF = MaxVectorSize);
407
408 private:
409   /// Returns the expected execution cost. The unit of the cost does
410   /// not matter because we use the 'cost' units to compare different
411   /// vector widths. The cost that is returned is *not* normalized by
412   /// the factor width.
413   unsigned expectedCost(unsigned VF);
414
415   /// Returns the execution time cost of an instruction for a given vector
416   /// width. Vector width of one means scalar.
417   unsigned getInstructionCost(Instruction *I, unsigned VF);
418
419   /// A helper function for converting Scalar types to vector types.
420   /// If the incoming type is void, we return void. If the VF is 1, we return
421   /// the scalar type.
422   static Type* ToVectorTy(Type *Scalar, unsigned VF);
423
424   /// The loop that we evaluate.
425   Loop *TheLoop;
426   /// Scev analysis.
427   ScalarEvolution *SE;
428
429   /// Vectorization legality.
430   LoopVectorizationLegality *Legal;
431   /// Vector target information.
432   const VectorTargetTransformInfo *VTTI;
433 };
434
435 struct LoopVectorize : public LoopPass {
436   static char ID; // Pass identification, replacement for typeid
437
438   LoopVectorize() : LoopPass(ID) {
439     initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
440   }
441
442   ScalarEvolution *SE;
443   DataLayout *DL;
444   LoopInfo *LI;
445   TargetTransformInfo *TTI;
446   DominatorTree *DT;
447
448   virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
449     // We only vectorize innermost loops.
450     if (!L->empty())
451       return false;
452
453     SE = &getAnalysis<ScalarEvolution>();
454     DL = getAnalysisIfAvailable<DataLayout>();
455     LI = &getAnalysis<LoopInfo>();
456     TTI = getAnalysisIfAvailable<TargetTransformInfo>();
457     DT = &getAnalysis<DominatorTree>();
458
459     DEBUG(dbgs() << "LV: Checking a loop in \"" <<
460           L->getHeader()->getParent()->getName() << "\"\n");
461
462     // Check if it is legal to vectorize the loop.
463     LoopVectorizationLegality LVL(L, SE, DL);
464     if (!LVL.canVectorize()) {
465       DEBUG(dbgs() << "LV: Not vectorizing.\n");
466       return false;
467     }
468
469     // Select the preffered vectorization factor.
470     unsigned VF = 1;
471     if (VectorizationFactor == 0) {
472       const VectorTargetTransformInfo *VTTI = 0;
473       if (TTI)
474         VTTI = TTI->getVectorTargetTransformInfo();
475       // Use the cost model.
476       LoopVectorizationCostModel CM(L, SE, &LVL, VTTI);
477       VF = CM.findBestVectorizationFactor();
478
479       if (VF == 1) {
480         DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
481         return false;
482       }
483
484     } else {
485       // Use the user command flag.
486       VF = VectorizationFactor;
487     }
488
489     DEBUG(dbgs() << "LV: Found a vectorizable loop ("<< VF << ") in "<<
490           L->getHeader()->getParent()->getParent()->getModuleIdentifier()<<
491           "\n");
492
493     // If we decided that it is *legal* to vectorizer the loop then do it.
494     SingleBlockLoopVectorizer LB(L, SE, LI, DT, DL, &LPM, VF);
495     LB.vectorize(&LVL);
496
497     DEBUG(verifyFunction(*L->getHeader()->getParent()));
498     return true;
499   }
500
501   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
502     LoopPass::getAnalysisUsage(AU);
503     AU.addRequiredID(LoopSimplifyID);
504     AU.addRequiredID(LCSSAID);
505     AU.addRequired<LoopInfo>();
506     AU.addRequired<ScalarEvolution>();
507     AU.addRequired<DominatorTree>();
508     AU.addPreserved<LoopInfo>();
509     AU.addPreserved<DominatorTree>();
510   }
511
512 };
513
514 Value *SingleBlockLoopVectorizer::getBroadcastInstrs(Value *V) {
515   // Create the types.
516   LLVMContext &C = V->getContext();
517   Type *VTy = VectorType::get(V->getType(), VF);
518   Type *I32 = IntegerType::getInt32Ty(C);
519
520   // Save the current insertion location.
521   Instruction *Loc = Builder.GetInsertPoint();
522
523   // We need to place the broadcast of invariant variables outside the loop.
524   bool Invariant = (OrigLoop->isLoopInvariant(V) && V != Induction);
525
526   // Place the code for broadcasting invariant variables in the new preheader.
527   if (Invariant)
528     Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
529
530   Constant *Zero = ConstantInt::get(I32, 0);
531   Value *Zeros = ConstantAggregateZero::get(VectorType::get(I32, VF));
532   Value *UndefVal = UndefValue::get(VTy);
533   // Insert the value into a new vector.
534   Value *SingleElem = Builder.CreateInsertElement(UndefVal, V, Zero);
535   // Broadcast the scalar into all locations in the vector.
536   Value *Shuf = Builder.CreateShuffleVector(SingleElem, UndefVal, Zeros,
537                                              "broadcast");
538
539   // Restore the builder insertion point.
540   if (Invariant)
541     Builder.SetInsertPoint(Loc);
542
543   return Shuf;
544 }
545
546 Value *SingleBlockLoopVectorizer::getConsecutiveVector(Value* Val) {
547   assert(Val->getType()->isVectorTy() && "Must be a vector");
548   assert(Val->getType()->getScalarType()->isIntegerTy() &&
549          "Elem must be an integer");
550   // Create the types.
551   Type *ITy = Val->getType()->getScalarType();
552   VectorType *Ty = cast<VectorType>(Val->getType());
553   unsigned VLen = Ty->getNumElements();
554   SmallVector<Constant*, 8> Indices;
555
556   // Create a vector of consecutive numbers from zero to VF.
557   for (unsigned i = 0; i < VLen; ++i)
558     Indices.push_back(ConstantInt::get(ITy, i));
559
560   // Add the consecutive indices to the vector value.
561   Constant *Cv = ConstantVector::get(Indices);
562   assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
563   return Builder.CreateAdd(Val, Cv, "induction");
564 }
565
566 bool LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
567   assert(Ptr->getType()->isPointerTy() && "Unexpected non ptr");
568
569   // If this pointer is an induction variable, return it.
570   PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
571   if (Phi && getInductionVars()->count(Phi))
572     return true;
573
574   GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
575   if (!Gep)
576     return false;
577
578   unsigned NumOperands = Gep->getNumOperands();
579   Value *LastIndex = Gep->getOperand(NumOperands - 1);
580
581   // Check that all of the gep indices are uniform except for the last.
582   for (unsigned i = 0; i < NumOperands - 1; ++i)
583     if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
584       return false;
585
586   // We can emit wide load/stores only if the last index is the induction
587   // variable.
588   const SCEV *Last = SE->getSCEV(LastIndex);
589   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
590     const SCEV *Step = AR->getStepRecurrence(*SE);
591
592     // The memory is consecutive because the last index is consecutive
593     // and all other indices are loop invariant.
594     if (Step->isOne())
595       return true;
596   }
597
598   return false;
599 }
600
601 bool LoopVectorizationLegality::isUniform(Value *V) {
602   return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
603 }
604
605 Value *SingleBlockLoopVectorizer::getVectorValue(Value *V) {
606   assert(V != Induction && "The new induction variable should not be used.");
607   assert(!V->getType()->isVectorTy() && "Can't widen a vector");
608   // If we saved a vectorized copy of V, use it.
609   Value *&MapEntry = WidenMap[V];
610   if (MapEntry)
611     return MapEntry;
612
613   // Broadcast V and save the value for future uses.
614   Value *B = getBroadcastInstrs(V);
615   MapEntry = B;
616   return B;
617 }
618
619 Constant*
620 SingleBlockLoopVectorizer::getUniformVector(unsigned Val, Type* ScalarTy) {
621   return ConstantVector::getSplat(VF, ConstantInt::get(ScalarTy, Val, true));
622 }
623
624 void SingleBlockLoopVectorizer::scalarizeInstruction(Instruction *Instr) {
625   assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
626   // Holds vector parameters or scalars, in case of uniform vals.
627   SmallVector<Value*, 8> Params;
628
629   // Find all of the vectorized parameters.
630   for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
631     Value *SrcOp = Instr->getOperand(op);
632
633     // If we are accessing the old induction variable, use the new one.
634     if (SrcOp == OldInduction) {
635       Params.push_back(getVectorValue(SrcOp));
636       continue;
637     }
638
639     // Try using previously calculated values.
640     Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
641
642     // If the src is an instruction that appeared earlier in the basic block
643     // then it should already be vectorized.
644     if (SrcInst && SrcInst->getParent() == Instr->getParent()) {
645       assert(WidenMap.count(SrcInst) && "Source operand is unavailable");
646       // The parameter is a vector value from earlier.
647       Params.push_back(WidenMap[SrcInst]);
648     } else {
649       // The parameter is a scalar from outside the loop. Maybe even a constant.
650       Params.push_back(SrcOp);
651     }
652   }
653
654   assert(Params.size() == Instr->getNumOperands() &&
655          "Invalid number of operands");
656
657   // Does this instruction return a value ?
658   bool IsVoidRetTy = Instr->getType()->isVoidTy();
659   Value *VecResults = 0;
660
661   // If we have a return value, create an empty vector. We place the scalarized
662   // instructions in this vector.
663   if (!IsVoidRetTy)
664     VecResults = UndefValue::get(VectorType::get(Instr->getType(), VF));
665
666   // For each scalar that we create:
667   for (unsigned i = 0; i < VF; ++i) {
668     Instruction *Cloned = Instr->clone();
669     if (!IsVoidRetTy)
670       Cloned->setName(Instr->getName() + ".cloned");
671     // Replace the operands of the cloned instrucions with extracted scalars.
672     for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
673       Value *Op = Params[op];
674       // Param is a vector. Need to extract the right lane.
675       if (Op->getType()->isVectorTy())
676         Op = Builder.CreateExtractElement(Op, Builder.getInt32(i));
677       Cloned->setOperand(op, Op);
678     }
679
680     // Place the cloned scalar in the new loop.
681     Builder.Insert(Cloned);
682
683     // If the original scalar returns a value we need to place it in a vector
684     // so that future users will be able to use it.
685     if (!IsVoidRetTy)
686       VecResults = Builder.CreateInsertElement(VecResults, Cloned,
687                                                Builder.getInt32(i));
688   }
689
690   if (!IsVoidRetTy)
691     WidenMap[Instr] = VecResults;
692 }
693
694 Value*
695 SingleBlockLoopVectorizer::addRuntimeCheck(LoopVectorizationLegality *Legal,
696                                            Instruction *Loc) {
697   LoopVectorizationLegality::RuntimePointerCheck *PtrRtCheck =
698     Legal->getRuntimePointerCheck();
699
700   if (!PtrRtCheck->Need)
701     return NULL;
702
703   Value *MemoryRuntimeCheck = 0;
704   unsigned NumPointers = PtrRtCheck->Pointers.size();
705   SmallVector<Value* , 2> Starts;
706   SmallVector<Value* , 2> Ends;
707
708   SCEVExpander Exp(*SE, "induction");
709
710   // Use this type for pointer arithmetic.
711   Type* PtrArithTy = PtrRtCheck->Pointers[0]->getType();
712
713   for (unsigned i = 0; i < NumPointers; ++i) {
714     Value *Ptr = PtrRtCheck->Pointers[i];
715     const SCEV *Sc = SE->getSCEV(Ptr);
716
717     if (SE->isLoopInvariant(Sc, OrigLoop)) {
718       DEBUG(dbgs() << "LV1: Adding RT check for a loop invariant ptr:" <<
719             *Ptr <<"\n");
720       Starts.push_back(Ptr);
721       Ends.push_back(Ptr);
722     } else {
723       DEBUG(dbgs() << "LV: Adding RT check for range:" << *Ptr <<"\n");
724
725       Value *Start = Exp.expandCodeFor(PtrRtCheck->Starts[i],
726                                        PtrArithTy, Loc);
727       Value *End = Exp.expandCodeFor(PtrRtCheck->Ends[i], PtrArithTy, Loc);
728       Starts.push_back(Start);
729       Ends.push_back(End);
730     }
731   }
732
733   for (unsigned i = 0; i < NumPointers; ++i) {
734     for (unsigned j = i+1; j < NumPointers; ++j) {
735       Value *Cmp0 = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_ULE,
736                                     Starts[i], Ends[j], "bound0", Loc);
737       Value *Cmp1 = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_ULE,
738                                     Starts[j], Ends[i], "bound1", Loc);
739       Value *IsConflict = BinaryOperator::Create(Instruction::And, Cmp0, Cmp1,
740                                                  "found.conflict", Loc);
741       if (MemoryRuntimeCheck)
742         MemoryRuntimeCheck = BinaryOperator::Create(Instruction::Or,
743                                                     MemoryRuntimeCheck,
744                                                     IsConflict,
745                                                     "conflict.rdx", Loc);
746       else
747         MemoryRuntimeCheck = IsConflict;
748
749     }
750   }
751
752   return MemoryRuntimeCheck;
753 }
754
755 void
756 SingleBlockLoopVectorizer::createEmptyLoop(LoopVectorizationLegality *Legal) {
757   /*
758    In this function we generate a new loop. The new loop will contain
759    the vectorized instructions while the old loop will continue to run the
760    scalar remainder.
761
762     [ ] <-- vector loop bypass.
763   /  |
764  /   v
765 |   [ ]     <-- vector pre header.
766 |    |
767 |    v
768 |   [  ] \
769 |   [  ]_|   <-- vector loop.
770 |    |
771  \   v
772    >[ ]   <--- middle-block.
773   /  |
774  /   v
775 |   [ ]     <--- new preheader.
776 |    |
777 |    v
778 |   [ ] \
779 |   [ ]_|   <-- old scalar loop to handle remainder.
780  \   |
781   \  v
782    >[ ]     <-- exit block.
783    ...
784    */
785
786   BasicBlock *OldBasicBlock = OrigLoop->getHeader();
787   BasicBlock *BypassBlock = OrigLoop->getLoopPreheader();
788   BasicBlock *ExitBlock = OrigLoop->getExitBlock();
789   assert(ExitBlock && "Must have an exit block");
790
791   // Some loops have a single integer induction variable, while other loops
792   // don't. One example is c++ iterators that often have multiple pointer
793   // induction variables. In the code below we also support a case where we
794   // don't have a single induction variable.
795   OldInduction = Legal->getInduction();
796   Type *IdxTy = OldInduction ? OldInduction->getType() :
797     DL->getIntPtrType(SE->getContext());
798
799   // Find the loop boundaries.
800   const SCEV *ExitCount = SE->getExitCount(OrigLoop, OrigLoop->getHeader());
801   assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
802
803   // Get the total trip count from the count by adding 1.
804   ExitCount = SE->getAddExpr(ExitCount,
805                              SE->getConstant(ExitCount->getType(), 1));
806
807   // Expand the trip count and place the new instructions in the preheader.
808   // Notice that the pre-header does not change, only the loop body.
809   SCEVExpander Exp(*SE, "induction");
810
811   // Count holds the overall loop count (N).
812   Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
813                                    BypassBlock->getTerminator());
814
815   // The loop index does not have to start at Zero. Find the original start
816   // value from the induction PHI node. If we don't have an induction variable
817   // then we know that it starts at zero.
818   Value *StartIdx = OldInduction ?
819     OldInduction->getIncomingValueForBlock(BypassBlock):
820     ConstantInt::get(IdxTy, 0);
821
822   assert(OrigLoop->getNumBlocks() == 1 && "Invalid loop");
823   assert(BypassBlock && "Invalid loop structure");
824
825   // Generate the code that checks in runtime if arrays overlap.
826   Value *MemoryRuntimeCheck = addRuntimeCheck(Legal,
827                                               BypassBlock->getTerminator());
828
829   // Split the single block loop into the two loop structure described above.
830   BasicBlock *VectorPH =
831       BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
832   BasicBlock *VecBody =
833     VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
834   BasicBlock *MiddleBlock =
835     VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
836   BasicBlock *ScalarPH =
837     MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
838
839   // This is the location in which we add all of the logic for bypassing
840   // the new vector loop.
841   Instruction *Loc = BypassBlock->getTerminator();
842
843   // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
844   // inside the loop.
845   Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
846
847   // Generate the induction variable.
848   Induction = Builder.CreatePHI(IdxTy, 2, "index");
849   Constant *Step = ConstantInt::get(IdxTy, VF);
850
851   // We may need to extend the index in case there is a type mismatch.
852   // We know that the count starts at zero and does not overflow.
853   if (Count->getType() != IdxTy) {
854     // The exit count can be of pointer type. Convert it to the correct
855     // integer type.
856     if (ExitCount->getType()->isPointerTy())
857       Count = CastInst::CreatePointerCast(Count, IdxTy, "ptrcnt.to.int", Loc);
858     else
859       Count = CastInst::CreateZExtOrBitCast(Count, IdxTy, "zext.cnt", Loc);
860   }
861
862   // Add the start index to the loop count to get the new end index.
863   Value *IdxEnd = BinaryOperator::CreateAdd(Count, StartIdx, "end.idx", Loc);
864
865   // Now we need to generate the expression for N - (N % VF), which is
866   // the part that the vectorized body will execute.
867   Constant *CIVF = ConstantInt::get(IdxTy, VF);
868   Value *R = BinaryOperator::CreateURem(Count, CIVF, "n.mod.vf", Loc);
869   Value *CountRoundDown = BinaryOperator::CreateSub(Count, R, "n.vec", Loc);
870   Value *IdxEndRoundDown = BinaryOperator::CreateAdd(CountRoundDown, StartIdx,
871                                                      "end.idx.rnd.down", Loc);
872
873   // Now, compare the new count to zero. If it is zero skip the vector loop and
874   // jump to the scalar loop.
875   Value *Cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
876                                IdxEndRoundDown,
877                                StartIdx,
878                                "cmp.zero", Loc);
879
880   // If we are using memory runtime checks, include them in.
881   if (MemoryRuntimeCheck)
882     Cmp = BinaryOperator::Create(Instruction::Or, Cmp, MemoryRuntimeCheck,
883                                  "CntOrMem", Loc);
884
885   BranchInst::Create(MiddleBlock, VectorPH, Cmp, Loc);
886   // Remove the old terminator.
887   Loc->eraseFromParent();
888
889   // We are going to resume the execution of the scalar loop.
890   // Go over all of the induction variables that we found and fix the
891   // PHIs that are left in the scalar version of the loop.
892   // The starting values of PHI nodes depend on the counter of the last
893   // iteration in the vectorized loop.
894   // If we come from a bypass edge then we need to start from the original start
895   // value.
896
897   // This variable saves the new starting index for the scalar loop.
898   PHINode *ResumeIndex = 0;
899   LoopVectorizationLegality::InductionList::iterator I, E;
900   LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
901   for (I = List->begin(), E = List->end(); I != E; ++I) {
902     PHINode *OrigPhi = I->first;
903     PHINode *ResumeVal = PHINode::Create(OrigPhi->getType(), 2, "resume.val",
904                                            MiddleBlock->getTerminator());
905     Value *EndValue = 0;
906     if (OrigPhi->getType()->isIntegerTy()) {
907       // Handle the integer induction counter:
908       assert(OrigPhi == OldInduction && "Unknown integer PHI");
909       // We know what the end value is.
910       EndValue = IdxEndRoundDown;
911       // We also know which PHI node holds it.
912       ResumeIndex = ResumeVal;
913     } else {
914       // For pointer induction variables, calculate the offset using
915       // the end index.
916       EndValue = GetElementPtrInst::Create(I->second, CountRoundDown,
917                                            "ptr.ind.end",
918                                            BypassBlock->getTerminator());
919     }
920
921     // The new PHI merges the original incoming value, in case of a bypass,
922     // or the value at the end of the vectorized loop.
923     ResumeVal->addIncoming(I->second, BypassBlock);
924     ResumeVal->addIncoming(EndValue, VecBody);
925
926     // Fix the scalar body counter (PHI node).
927     unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
928     OrigPhi->setIncomingValue(BlockIdx, ResumeVal);
929   }
930
931   // If we are generating a new induction variable then we also need to
932   // generate the code that calculates the exit value. This value is not
933   // simply the end of the counter because we may skip the vectorized body
934   // in case of a runtime check.
935   if (!OldInduction){
936     assert(!ResumeIndex && "Unexpected resume value found");
937     ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val",
938                                   MiddleBlock->getTerminator());
939     ResumeIndex->addIncoming(StartIdx, BypassBlock);
940     ResumeIndex->addIncoming(IdxEndRoundDown, VecBody);
941   }
942
943   // Make sure that we found the index where scalar loop needs to continue.
944   assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() &&
945          "Invalid resume Index");
946
947   // Add a check in the middle block to see if we have completed
948   // all of the iterations in the first vector loop.
949   // If (N - N%VF) == N, then we *don't* need to run the remainder.
950   Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd,
951                                 ResumeIndex, "cmp.n",
952                                 MiddleBlock->getTerminator());
953
954   BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
955   // Remove the old terminator.
956   MiddleBlock->getTerminator()->eraseFromParent();
957
958   // Create i+1 and fill the PHINode.
959   Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
960   Induction->addIncoming(StartIdx, VectorPH);
961   Induction->addIncoming(NextIdx, VecBody);
962   // Create the compare.
963   Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown);
964   Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
965
966   // Now we have two terminators. Remove the old one from the block.
967   VecBody->getTerminator()->eraseFromParent();
968
969   // Get ready to start creating new instructions into the vectorized body.
970   Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
971
972   // Register the new loop.
973   Loop* Lp = new Loop();
974   LPM->insertLoop(Lp, OrigLoop->getParentLoop());
975
976   Lp->addBasicBlockToLoop(VecBody, LI->getBase());
977
978   Loop *ParentLoop = OrigLoop->getParentLoop();
979   if (ParentLoop) {
980     ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase());
981     ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase());
982     ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase());
983   }
984
985   // Save the state.
986   LoopVectorPreHeader = VectorPH;
987   LoopScalarPreHeader = ScalarPH;
988   LoopMiddleBlock = MiddleBlock;
989   LoopExitBlock = ExitBlock;
990   LoopVectorBody = VecBody;
991   LoopScalarBody = OldBasicBlock;
992   LoopBypassBlock = BypassBlock;
993 }
994
995 /// This function returns the identity element (or neutral element) for
996 /// the operation K.
997 static unsigned
998 getReductionIdentity(LoopVectorizationLegality::ReductionKind K) {
999   switch (K) {
1000   case LoopVectorizationLegality::IntegerXor:
1001   case LoopVectorizationLegality::IntegerAdd:
1002   case LoopVectorizationLegality::IntegerOr:
1003     // Adding, Xoring, Oring zero to a number does not change it.
1004     return 0;
1005   case LoopVectorizationLegality::IntegerMult:
1006     // Multiplying a number by 1 does not change it.
1007     return 1;
1008   case LoopVectorizationLegality::IntegerAnd:
1009     // AND-ing a number with an all-1 value does not change it.
1010     return -1;
1011   default:
1012     llvm_unreachable("Unknown reduction kind");
1013   }
1014 }
1015
1016 void
1017 SingleBlockLoopVectorizer::vectorizeLoop(LoopVectorizationLegality *Legal) {
1018   //===------------------------------------------------===//
1019   //
1020   // Notice: any optimization or new instruction that go
1021   // into the code below should be also be implemented in
1022   // the cost-model.
1023   //
1024   //===------------------------------------------------===//
1025   typedef SmallVector<PHINode*, 4> PhiVector;
1026   BasicBlock &BB = *OrigLoop->getHeader();
1027   Constant *Zero = ConstantInt::get(
1028     IntegerType::getInt32Ty(BB.getContext()), 0);
1029
1030   // In order to support reduction variables we need to be able to vectorize
1031   // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
1032   // stages. First, we create a new vector PHI node with no incoming edges.
1033   // We use this value when we vectorize all of the instructions that use the
1034   // PHI. Next, after all of the instructions in the block are complete we
1035   // add the new incoming edges to the PHI. At this point all of the
1036   // instructions in the basic block are vectorized, so we can use them to
1037   // construct the PHI.
1038   PhiVector RdxPHIsToFix;
1039
1040   // For each instruction in the old loop.
1041   for (BasicBlock::iterator it = BB.begin(), e = BB.end(); it != e; ++it) {
1042     Instruction *Inst = it;
1043
1044     switch (Inst->getOpcode()) {
1045       case Instruction::Br:
1046         // Nothing to do for PHIs and BR, since we already took care of the
1047         // loop control flow instructions.
1048         continue;
1049       case Instruction::PHI:{
1050         PHINode* P = cast<PHINode>(Inst);
1051         // Handle reduction variables:
1052         if (Legal->getReductionVars()->count(P)) {
1053           // This is phase one of vectorizing PHIs.
1054           Type *VecTy = VectorType::get(Inst->getType(), VF);
1055           WidenMap[Inst] = PHINode::Create(VecTy, 2, "vec.phi",
1056                                   LoopVectorBody->getFirstInsertionPt());
1057           RdxPHIsToFix.push_back(P);
1058           continue;
1059         }
1060
1061         // This PHINode must be an induction variable.
1062         // Make sure that we know about it.
1063         assert(Legal->getInductionVars()->count(P) &&
1064                "Not an induction variable");
1065
1066         if (P->getType()->isIntegerTy()) {
1067           assert(P == OldInduction && "Unexpected PHI");
1068           Value *Broadcasted = getBroadcastInstrs(Induction);
1069           // After broadcasting the induction variable we need to make the
1070           // vector consecutive by adding 0, 1, 2 ...
1071           Value *ConsecutiveInduction = getConsecutiveVector(Broadcasted);
1072            
1073           WidenMap[OldInduction] = ConsecutiveInduction;
1074           continue;
1075         }
1076
1077         // Handle pointer inductions.
1078         assert(P->getType()->isPointerTy() && "Unexpected type.");
1079         Value *StartIdx = OldInduction ?
1080           Legal->getInductionVars()->lookup(OldInduction) :
1081           ConstantInt::get(Induction->getType(), 0);
1082
1083         // This is the pointer value coming into the loop.
1084         Value *StartPtr = Legal->getInductionVars()->lookup(P);
1085
1086         // This is the normalized GEP that starts counting at zero.
1087         Value *NormalizedIdx = Builder.CreateSub(Induction, StartIdx,
1088                                                  "normalized.idx");
1089
1090         // This is the vector of results. Notice that we don't generate vector
1091         // geps because scalar geps result in better code.
1092         Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
1093         for (unsigned int i = 0; i < VF; ++i) {
1094           Constant *Idx = ConstantInt::get(Induction->getType(), i);
1095           Value *GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx, "gep.idx");
1096           Value *SclrGep = Builder.CreateGEP(StartPtr, GlobalIdx, "next.gep");
1097           VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
1098                                                Builder.getInt32(i),
1099                                                "insert.gep");
1100         }
1101
1102         WidenMap[Inst] = VecVal;
1103         continue;
1104       }
1105       case Instruction::Add:
1106       case Instruction::FAdd:
1107       case Instruction::Sub:
1108       case Instruction::FSub:
1109       case Instruction::Mul:
1110       case Instruction::FMul:
1111       case Instruction::UDiv:
1112       case Instruction::SDiv:
1113       case Instruction::FDiv:
1114       case Instruction::URem:
1115       case Instruction::SRem:
1116       case Instruction::FRem:
1117       case Instruction::Shl:
1118       case Instruction::LShr:
1119       case Instruction::AShr:
1120       case Instruction::And:
1121       case Instruction::Or:
1122       case Instruction::Xor: {
1123         // Just widen binops.
1124         BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
1125         Value *A = getVectorValue(Inst->getOperand(0));
1126         Value *B = getVectorValue(Inst->getOperand(1));
1127
1128         // Use this vector value for all users of the original instruction.
1129         Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A, B);
1130         WidenMap[Inst] = V;
1131
1132         // Update the NSW, NUW and Exact flags.
1133         BinaryOperator *VecOp = cast<BinaryOperator>(V);
1134         if (isa<OverflowingBinaryOperator>(BinOp)) {
1135           VecOp->setHasNoSignedWrap(BinOp->hasNoSignedWrap());
1136           VecOp->setHasNoUnsignedWrap(BinOp->hasNoUnsignedWrap());
1137         }
1138         if (isa<PossiblyExactOperator>(VecOp))
1139           VecOp->setIsExact(BinOp->isExact());
1140         break;
1141       }
1142       case Instruction::Select: {
1143         // Widen selects.
1144         // If the selector is loop invariant we can create a select
1145         // instruction with a scalar condition. Otherwise, use vector-select.
1146         Value *Cond = Inst->getOperand(0);
1147         bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(Cond), OrigLoop);
1148
1149         // The condition can be loop invariant  but still defined inside the
1150         // loop. This means that we can't just use the original 'cond' value.
1151         // We have to take the 'vectorized' value and pick the first lane.
1152         // Instcombine will make this a no-op.
1153         Cond = getVectorValue(Cond);
1154         if (InvariantCond)
1155           Cond = Builder.CreateExtractElement(Cond, Builder.getInt32(0));
1156
1157         Value *Op0 = getVectorValue(Inst->getOperand(1));
1158         Value *Op1 = getVectorValue(Inst->getOperand(2));
1159         WidenMap[Inst] = Builder.CreateSelect(Cond, Op0, Op1);
1160         break;
1161       }
1162
1163       case Instruction::ICmp:
1164       case Instruction::FCmp: {
1165         // Widen compares. Generate vector compares.
1166         bool FCmp = (Inst->getOpcode() == Instruction::FCmp);
1167         CmpInst *Cmp = dyn_cast<CmpInst>(Inst);
1168         Value *A = getVectorValue(Inst->getOperand(0));
1169         Value *B = getVectorValue(Inst->getOperand(1));
1170         if (FCmp)
1171           WidenMap[Inst] = Builder.CreateFCmp(Cmp->getPredicate(), A, B);
1172         else
1173           WidenMap[Inst] = Builder.CreateICmp(Cmp->getPredicate(), A, B);
1174         break;
1175       }
1176
1177       case Instruction::Store: {
1178         // Attempt to issue a wide store.
1179         StoreInst *SI = dyn_cast<StoreInst>(Inst);
1180         Type *StTy = VectorType::get(SI->getValueOperand()->getType(), VF);
1181         Value *Ptr = SI->getPointerOperand();
1182         unsigned Alignment = SI->getAlignment();
1183
1184         assert(!Legal->isUniform(Ptr) &&
1185                "We do not allow storing to uniform addresses");
1186
1187         GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1188
1189         // This store does not use GEPs.
1190         if (!Legal->isConsecutivePtr(Ptr)) {
1191           scalarizeInstruction(Inst);
1192           break;
1193         }
1194
1195         if (Gep) {
1196           // The last index does not have to be the induction. It can be
1197           // consecutive and be a function of the index. For example A[I+1];
1198           unsigned NumOperands = Gep->getNumOperands();
1199           Value *LastIndex = getVectorValue(Gep->getOperand(NumOperands - 1));
1200           LastIndex = Builder.CreateExtractElement(LastIndex, Zero);
1201
1202           // Create the new GEP with the new induction variable.
1203           GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1204           Gep2->setOperand(NumOperands - 1, LastIndex);
1205           Ptr = Builder.Insert(Gep2);
1206         } else {
1207           // Use the induction element ptr.
1208           assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1209           Ptr = Builder.CreateExtractElement(getVectorValue(Ptr), Zero);
1210         }
1211         Ptr = Builder.CreateBitCast(Ptr, StTy->getPointerTo());
1212         Value *Val = getVectorValue(SI->getValueOperand());
1213         Builder.CreateStore(Val, Ptr)->setAlignment(Alignment);
1214         break;
1215       }
1216       case Instruction::Load: {
1217         // Attempt to issue a wide load.
1218         LoadInst *LI = dyn_cast<LoadInst>(Inst);
1219         Type *RetTy = VectorType::get(LI->getType(), VF);
1220         Value *Ptr = LI->getPointerOperand();
1221         unsigned Alignment = LI->getAlignment();
1222         GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1223
1224         // If the pointer is loop invariant or if it is non consecutive,
1225         // scalarize the load.
1226         bool Con = Legal->isConsecutivePtr(Ptr);
1227         if (Legal->isUniform(Ptr) || !Con) {
1228           scalarizeInstruction(Inst);
1229           break;
1230         }
1231
1232         if (Gep) {
1233           // The last index does not have to be the induction. It can be
1234           // consecutive and be a function of the index. For example A[I+1];
1235           unsigned NumOperands = Gep->getNumOperands();
1236           Value *LastIndex = getVectorValue(Gep->getOperand(NumOperands -1));
1237           LastIndex = Builder.CreateExtractElement(LastIndex, Zero);
1238
1239           // Create the new GEP with the new induction variable.
1240           GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1241           Gep2->setOperand(NumOperands - 1, LastIndex);
1242           Ptr = Builder.Insert(Gep2);
1243         } else {
1244           // Use the induction element ptr.
1245           assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1246           Ptr = Builder.CreateExtractElement(getVectorValue(Ptr), Zero);
1247         }
1248
1249         Ptr = Builder.CreateBitCast(Ptr, RetTy->getPointerTo());
1250         LI = Builder.CreateLoad(Ptr);
1251         LI->setAlignment(Alignment);
1252         // Use this vector value for all users of the load.
1253         WidenMap[Inst] = LI;
1254         break;
1255       }
1256       case Instruction::ZExt:
1257       case Instruction::SExt:
1258       case Instruction::FPToUI:
1259       case Instruction::FPToSI:
1260       case Instruction::FPExt:
1261       case Instruction::PtrToInt:
1262       case Instruction::IntToPtr:
1263       case Instruction::SIToFP:
1264       case Instruction::UIToFP:
1265       case Instruction::Trunc:
1266       case Instruction::FPTrunc:
1267       case Instruction::BitCast: {
1268         /// Vectorize bitcasts.
1269         CastInst *CI = dyn_cast<CastInst>(Inst);
1270         Value *A = getVectorValue(Inst->getOperand(0));
1271         Type *DestTy = VectorType::get(CI->getType()->getScalarType(), VF);
1272         WidenMap[Inst] = Builder.CreateCast(CI->getOpcode(), A, DestTy);
1273         break;
1274       }
1275
1276       default:
1277         /// All other instructions are unsupported. Scalarize them.
1278         scalarizeInstruction(Inst);
1279         break;
1280     }// end of switch.
1281   }// end of for_each instr.
1282
1283   // At this point every instruction in the original loop is widended to
1284   // a vector form. We are almost done. Now, we need to fix the PHI nodes
1285   // that we vectorized. The PHI nodes are currently empty because we did
1286   // not want to introduce cycles. Notice that the remaining PHI nodes
1287   // that we need to fix are reduction variables.
1288
1289   // Create the 'reduced' values for each of the induction vars.
1290   // The reduced values are the vector values that we scalarize and combine
1291   // after the loop is finished.
1292   for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
1293        it != e; ++it) {
1294     PHINode *RdxPhi = *it;
1295     PHINode *VecRdxPhi = dyn_cast<PHINode>(WidenMap[RdxPhi]);
1296     assert(RdxPhi && "Unable to recover vectorized PHI");
1297
1298     // Find the reduction variable descriptor.
1299     assert(Legal->getReductionVars()->count(RdxPhi) &&
1300            "Unable to find the reduction variable");
1301     LoopVectorizationLegality::ReductionDescriptor RdxDesc =
1302       (*Legal->getReductionVars())[RdxPhi];
1303
1304     // We need to generate a reduction vector from the incoming scalar.
1305     // To do so, we need to generate the 'identity' vector and overide
1306     // one of the elements with the incoming scalar reduction. We need
1307     // to do it in the vector-loop preheader.
1308     Builder.SetInsertPoint(LoopBypassBlock->getTerminator());
1309
1310     // This is the vector-clone of the value that leaves the loop.
1311     Value *VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
1312     Type *VecTy = VectorExit->getType();
1313
1314     // Find the reduction identity variable. Zero for addition, or, xor,
1315     // one for multiplication, -1 for And.
1316     Constant *Identity = getUniformVector(getReductionIdentity(RdxDesc.Kind),
1317                                           VecTy->getScalarType());
1318
1319     // This vector is the Identity vector where the first element is the
1320     // incoming scalar reduction.
1321     Value *VectorStart = Builder.CreateInsertElement(Identity,
1322                                                     RdxDesc.StartValue, Zero);
1323
1324     // Fix the vector-loop phi.
1325     // We created the induction variable so we know that the
1326     // preheader is the first entry.
1327     BasicBlock *VecPreheader = Induction->getIncomingBlock(0);
1328
1329     // Reductions do not have to start at zero. They can start with
1330     // any loop invariant values.
1331     VecRdxPhi->addIncoming(VectorStart, VecPreheader);
1332     unsigned SelfEdgeIdx = (RdxPhi)->getBasicBlockIndex(LoopScalarBody);
1333     Value *Val = getVectorValue(RdxPhi->getIncomingValue(SelfEdgeIdx));
1334     VecRdxPhi->addIncoming(Val, LoopVectorBody);
1335
1336     // Before each round, move the insertion point right between
1337     // the PHIs and the values we are going to write.
1338     // This allows us to write both PHINodes and the extractelement
1339     // instructions.
1340     Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
1341
1342     // This PHINode contains the vectorized reduction variable, or
1343     // the initial value vector, if we bypass the vector loop.
1344     PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
1345     NewPhi->addIncoming(VectorStart, LoopBypassBlock);
1346     NewPhi->addIncoming(getVectorValue(RdxDesc.LoopExitInstr), LoopVectorBody);
1347
1348     // Extract the first scalar.
1349     Value *Scalar0 =
1350       Builder.CreateExtractElement(NewPhi, Builder.getInt32(0));
1351     // Extract and reduce the remaining vector elements.
1352     for (unsigned i=1; i < VF; ++i) {
1353       Value *Scalar1 =
1354         Builder.CreateExtractElement(NewPhi, Builder.getInt32(i));
1355       switch (RdxDesc.Kind) {
1356         case LoopVectorizationLegality::IntegerAdd:
1357           Scalar0 = Builder.CreateAdd(Scalar0, Scalar1);
1358           break;
1359         case LoopVectorizationLegality::IntegerMult:
1360           Scalar0 = Builder.CreateMul(Scalar0, Scalar1);
1361           break;
1362         case LoopVectorizationLegality::IntegerOr:
1363           Scalar0 = Builder.CreateOr(Scalar0, Scalar1);
1364           break;
1365         case LoopVectorizationLegality::IntegerAnd:
1366           Scalar0 = Builder.CreateAnd(Scalar0, Scalar1);
1367           break;
1368         case LoopVectorizationLegality::IntegerXor:
1369           Scalar0 = Builder.CreateXor(Scalar0, Scalar1);
1370           break;
1371         default:
1372           llvm_unreachable("Unknown reduction operation");
1373       }
1374     }
1375
1376     // Now, we need to fix the users of the reduction variable
1377     // inside and outside of the scalar remainder loop.
1378     // We know that the loop is in LCSSA form. We need to update the
1379     // PHI nodes in the exit blocks.
1380     for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
1381          LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
1382       PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
1383       if (!LCSSAPhi) continue;
1384
1385       // All PHINodes need to have a single entry edge, or two if
1386       // we already fixed them.
1387       assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
1388
1389       // We found our reduction value exit-PHI. Update it with the
1390       // incoming bypass edge.
1391       if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
1392         // Add an edge coming from the bypass.
1393         LCSSAPhi->addIncoming(Scalar0, LoopMiddleBlock);
1394         break;
1395       }
1396     }// end of the LCSSA phi scan.
1397
1398     // Fix the scalar loop reduction variable with the incoming reduction sum
1399     // from the vector body and from the backedge value.
1400     int IncomingEdgeBlockIdx = (RdxPhi)->getBasicBlockIndex(LoopScalarBody);
1401     int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1); // The other block.
1402     (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, Scalar0);
1403     (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
1404   }// end of for each redux variable.
1405 }
1406
1407 void SingleBlockLoopVectorizer::updateAnalysis() {
1408   // Forget the original basic block.
1409   SE->forgetLoop(OrigLoop);
1410
1411   // Update the dominator tree information.
1412   assert(DT->properlyDominates(LoopBypassBlock, LoopExitBlock) &&
1413          "Entry does not dominate exit.");
1414
1415   DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlock);
1416   DT->addNewBlock(LoopVectorBody, LoopVectorPreHeader);
1417   DT->addNewBlock(LoopMiddleBlock, LoopBypassBlock);
1418   DT->addNewBlock(LoopScalarPreHeader, LoopMiddleBlock);
1419   DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
1420   DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
1421
1422   DEBUG(DT->verifyAnalysis());
1423 }
1424
1425 bool LoopVectorizationLegality::canVectorize() {
1426   if (!TheLoop->getLoopPreheader()) {
1427     assert(false && "No preheader!!");
1428     DEBUG(dbgs() << "LV: Loop not normalized." << "\n");
1429     return false;
1430   }
1431
1432   // We can only vectorize single basic block loops.
1433   unsigned NumBlocks = TheLoop->getNumBlocks();
1434   if (NumBlocks != 1) {
1435     DEBUG(dbgs() << "LV: Too many blocks:" << NumBlocks << "\n");
1436     return false;
1437   }
1438
1439   // We need to have a loop header.
1440   BasicBlock *BB = TheLoop->getHeader();
1441   DEBUG(dbgs() << "LV: Found a loop: " << BB->getName() << "\n");
1442
1443   // ScalarEvolution needs to be able to find the exit count.
1444   const SCEV *ExitCount = SE->getExitCount(TheLoop, BB);
1445   if (ExitCount == SE->getCouldNotCompute()) {
1446     DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
1447     return false;
1448   }
1449
1450   // Do not loop-vectorize loops with a tiny trip count.
1451   unsigned TC = SE->getSmallConstantTripCount(TheLoop, BB);
1452   if (TC > 0u && TC < TinyTripCountThreshold) {
1453     DEBUG(dbgs() << "LV: Found a loop with a very small trip count. " <<
1454           "This loop is not worth vectorizing.\n");
1455     return false;
1456   }
1457
1458   // Go over each instruction and look at memory deps.
1459   if (!canVectorizeBlock(*BB)) {
1460     DEBUG(dbgs() << "LV: Can't vectorize this loop header\n");
1461     return false;
1462   }
1463
1464   DEBUG(dbgs() << "LV: We can vectorize this loop" <<
1465         (PtrRtCheck.Need ? " (with a runtime bound check)" : "")
1466         <<"!\n");
1467
1468   // Okay! We can vectorize. At this point we don't have any other mem analysis
1469   // which may limit our maximum vectorization factor, so just return true with
1470   // no restrictions.
1471   return true;
1472 }
1473
1474 bool LoopVectorizationLegality::canVectorizeBlock(BasicBlock &BB) {
1475
1476   BasicBlock *PreHeader = TheLoop->getLoopPreheader();
1477
1478   // Scan the instructions in the block and look for hazards.
1479   for (BasicBlock::iterator it = BB.begin(), e = BB.end(); it != e; ++it) {
1480     Instruction *I = it;
1481
1482     if (PHINode *Phi = dyn_cast<PHINode>(I)) {
1483       // This should not happen because the loop should be normalized.
1484       if (Phi->getNumIncomingValues() != 2) {
1485         DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
1486         return false;
1487       }
1488
1489       // This is the value coming from the preheader.
1490       Value *StartValue = Phi->getIncomingValueForBlock(PreHeader);
1491
1492       // We only look at integer and pointer phi nodes.
1493       if (Phi->getType()->isPointerTy() && isInductionVariable(Phi)) {
1494         DEBUG(dbgs() << "LV: Found a pointer induction variable.\n");
1495         Inductions[Phi] = StartValue;
1496         continue;
1497       } else if (!Phi->getType()->isIntegerTy()) {
1498         DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
1499         return false;
1500       }
1501
1502       // Handle integer PHIs:
1503       if (isInductionVariable(Phi)) {
1504         if (Induction) {
1505           DEBUG(dbgs() << "LV: Found too many inductions."<< *Phi <<"\n");
1506           return false;
1507         }
1508         DEBUG(dbgs() << "LV: Found the induction PHI."<< *Phi <<"\n");
1509         Induction = Phi;
1510         Inductions[Phi] = StartValue;
1511         continue;
1512       }
1513       if (AddReductionVar(Phi, IntegerAdd)) {
1514         DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
1515         continue;
1516       }
1517       if (AddReductionVar(Phi, IntegerMult)) {
1518         DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n");
1519         continue;
1520       }
1521       if (AddReductionVar(Phi, IntegerOr)) {
1522         DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n");
1523         continue;
1524       }
1525       if (AddReductionVar(Phi, IntegerAnd)) {
1526         DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n");
1527         continue;
1528       }
1529       if (AddReductionVar(Phi, IntegerXor)) {
1530         DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n");
1531         continue;
1532       }
1533
1534       DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
1535       return false;
1536     }// end of PHI handling
1537
1538     // We still don't handle functions.
1539     CallInst *CI = dyn_cast<CallInst>(I);
1540     if (CI) {
1541       DEBUG(dbgs() << "LV: Found a call site.\n");
1542       return false;
1543     }
1544
1545     // We do not re-vectorize vectors.
1546     if (!VectorType::isValidElementType(I->getType()) &&
1547         !I->getType()->isVoidTy()) {
1548       DEBUG(dbgs() << "LV: Found unvectorizable type." << "\n");
1549       return false;
1550     }
1551
1552     // Reduction instructions are allowed to have exit users.
1553     // All other instructions must not have external users.
1554     if (!AllowedExit.count(I))
1555       //Check that all of the users of the loop are inside the BB.
1556       for (Value::use_iterator it = I->use_begin(), e = I->use_end();
1557            it != e; ++it) {
1558         Instruction *U = cast<Instruction>(*it);
1559         // This user may be a reduction exit value.
1560         BasicBlock *Parent = U->getParent();
1561         if (Parent != &BB) {
1562           DEBUG(dbgs() << "LV: Found an outside user for : "<< *U << "\n");
1563           return false;
1564         }
1565     }
1566   } // next instr.
1567
1568   if (!Induction) {
1569     DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
1570     assert(getInductionVars()->size() && "No induction variables");
1571   }
1572
1573   // Don't vectorize if the memory dependencies do not allow vectorization.
1574   if (!canVectorizeMemory(BB))
1575     return false;
1576
1577   // We now know that the loop is vectorizable!
1578   // Collect variables that will remain uniform after vectorization.
1579   std::vector<Value*> Worklist;
1580
1581   // Start with the conditional branch and walk up the block.
1582   Worklist.push_back(BB.getTerminator()->getOperand(0));
1583
1584   while (Worklist.size()) {
1585     Instruction *I = dyn_cast<Instruction>(Worklist.back());
1586     Worklist.pop_back();
1587
1588     // Look at instructions inside this block. Stop when reaching PHI nodes.
1589     if (!I || I->getParent() != &BB || isa<PHINode>(I))
1590       continue;
1591
1592     // This is a known uniform.
1593     Uniforms.insert(I);
1594
1595     // Insert all operands.
1596     for (int i = 0, Op = I->getNumOperands(); i < Op; ++i) {
1597       Worklist.push_back(I->getOperand(i));
1598     }
1599   }
1600
1601   return true;
1602 }
1603
1604 bool LoopVectorizationLegality::canVectorizeMemory(BasicBlock &BB) {
1605   typedef SmallVector<Value*, 16> ValueVector;
1606   typedef SmallPtrSet<Value*, 16> ValueSet;
1607   // Holds the Load and Store *instructions*.
1608   ValueVector Loads;
1609   ValueVector Stores;
1610   PtrRtCheck.Pointers.clear();
1611   PtrRtCheck.Need = false;
1612
1613   // Scan the BB and collect legal loads and stores.
1614   for (BasicBlock::iterator it = BB.begin(), e = BB.end(); it != e; ++it) {
1615     Instruction *I = it;
1616
1617     // If this is a load, save it. If this instruction can read from memory
1618     // but is not a load, then we quit. Notice that we don't handle function
1619     // calls that read or write.
1620     if (I->mayReadFromMemory()) {
1621       LoadInst *Ld = dyn_cast<LoadInst>(I);
1622       if (!Ld) return false;
1623       if (!Ld->isSimple()) {
1624         DEBUG(dbgs() << "LV: Found a non-simple load.\n");
1625         return false;
1626       }
1627       Loads.push_back(Ld);
1628       continue;
1629     }
1630
1631     // Save store instructions. Abort if other instructions write to memory.
1632     if (I->mayWriteToMemory()) {
1633       StoreInst *St = dyn_cast<StoreInst>(I);
1634       if (!St) return false;
1635       if (!St->isSimple()) {
1636         DEBUG(dbgs() << "LV: Found a non-simple store.\n");
1637         return false;
1638       }
1639       Stores.push_back(St);
1640     }
1641   } // next instr.
1642
1643   // Now we have two lists that hold the loads and the stores.
1644   // Next, we find the pointers that they use.
1645
1646   // Check if we see any stores. If there are no stores, then we don't
1647   // care if the pointers are *restrict*.
1648   if (!Stores.size()) {
1649         DEBUG(dbgs() << "LV: Found a read-only loop!\n");
1650         return true;
1651   }
1652
1653   // Holds the read and read-write *pointers* that we find.
1654   ValueVector Reads;
1655   ValueVector ReadWrites;
1656
1657   // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
1658   // multiple times on the same object. If the ptr is accessed twice, once
1659   // for read and once for write, it will only appear once (on the write
1660   // list). This is okay, since we are going to check for conflicts between
1661   // writes and between reads and writes, but not between reads and reads.
1662   ValueSet Seen;
1663
1664   ValueVector::iterator I, IE;
1665   for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
1666     StoreInst *ST = dyn_cast<StoreInst>(*I);
1667     assert(ST && "Bad StoreInst");
1668     Value* Ptr = ST->getPointerOperand();
1669
1670     if (isUniform(Ptr)) {
1671       DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
1672       return false;
1673     }
1674
1675     // If we did *not* see this pointer before, insert it to
1676     // the read-write list. At this phase it is only a 'write' list.
1677     if (Seen.insert(Ptr))
1678       ReadWrites.push_back(Ptr);
1679   }
1680
1681   for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
1682     LoadInst *LD = dyn_cast<LoadInst>(*I);
1683     assert(LD && "Bad LoadInst");
1684     Value* Ptr = LD->getPointerOperand();
1685     // If we did *not* see this pointer before, insert it to the
1686     // read list. If we *did* see it before, then it is already in
1687     // the read-write list. This allows us to vectorize expressions
1688     // such as A[i] += x;  Because the address of A[i] is a read-write
1689     // pointer. This only works if the index of A[i] is consecutive.
1690     // If the address of i is unknown (for example A[B[i]]) then we may
1691     // read a few words, modify, and write a few words, and some of the
1692     // words may be written to the same address.
1693     if (Seen.insert(Ptr) || !isConsecutivePtr(Ptr))
1694       Reads.push_back(Ptr);
1695   }
1696
1697   // If we write (or read-write) to a single destination and there are no
1698   // other reads in this loop then is it safe to vectorize.
1699   if (ReadWrites.size() == 1 && Reads.size() == 0) {
1700     DEBUG(dbgs() << "LV: Found a write-only loop!\n");
1701     return true;
1702   }
1703
1704   // Find pointers with computable bounds. We are going to use this information
1705   // to place a runtime bound check.
1706   bool RT = true;
1707   for (I = ReadWrites.begin(), IE = ReadWrites.end(); I != IE; ++I)
1708     if (hasComputableBounds(*I)) {
1709       PtrRtCheck.insert(SE, TheLoop, *I);
1710       DEBUG(dbgs() << "LV: Found a runtime check ptr:" << **I <<"\n");
1711     } else {
1712       RT = false;
1713       break;
1714     }
1715   for (I = Reads.begin(), IE = Reads.end(); I != IE; ++I)
1716     if (hasComputableBounds(*I)) {
1717       PtrRtCheck.insert(SE, TheLoop, *I);
1718       DEBUG(dbgs() << "LV: Found a runtime check ptr:" << **I <<"\n");
1719     } else {
1720       RT = false;
1721       break;
1722     }
1723
1724   // Check that we did not collect too many pointers or found a
1725   // unsizeable pointer.
1726   if (!RT || PtrRtCheck.Pointers.size() > RuntimeMemoryCheckThreshold) {
1727     PtrRtCheck.reset();
1728     RT = false;
1729   }
1730
1731   PtrRtCheck.Need = RT;
1732
1733   if (RT) {
1734     DEBUG(dbgs() << "LV: We can perform a memory runtime check if needed.\n");
1735   }
1736
1737   // Now that the pointers are in two lists (Reads and ReadWrites), we
1738   // can check that there are no conflicts between each of the writes and
1739   // between the writes to the reads.
1740   ValueSet WriteObjects;
1741   ValueVector TempObjects;
1742
1743   // Check that the read-writes do not conflict with other read-write
1744   // pointers.
1745   for (I = ReadWrites.begin(), IE = ReadWrites.end(); I != IE; ++I) {
1746     GetUnderlyingObjects(*I, TempObjects, DL);
1747     for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end();
1748          it != e; ++it) {
1749       if (!isIdentifiedObject(*it)) {
1750         DEBUG(dbgs() << "LV: Found an unidentified write ptr:"<< **it <<"\n");
1751         return RT;
1752       }
1753       if (!WriteObjects.insert(*it)) {
1754         DEBUG(dbgs() << "LV: Found a possible write-write reorder:"
1755               << **it <<"\n");
1756         return RT;
1757       }
1758     }
1759     TempObjects.clear();
1760   }
1761
1762   /// Check that the reads don't conflict with the read-writes.
1763   for (I = Reads.begin(), IE = Reads.end(); I != IE; ++I) {
1764     GetUnderlyingObjects(*I, TempObjects, DL);
1765     for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end();
1766          it != e; ++it) {
1767       if (!isIdentifiedObject(*it)) {
1768         DEBUG(dbgs() << "LV: Found an unidentified read ptr:"<< **it <<"\n");
1769         return RT;
1770       }
1771       if (WriteObjects.count(*it)) {
1772         DEBUG(dbgs() << "LV: Found a possible read/write reorder:"
1773               << **it <<"\n");
1774         return RT;
1775       }
1776     }
1777     TempObjects.clear();
1778   }
1779
1780   // It is safe to vectorize and we don't need any runtime checks.
1781   DEBUG(dbgs() << "LV: We don't need a runtime memory check.\n");
1782   PtrRtCheck.reset();
1783   return true;
1784 }
1785
1786 bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi,
1787                                                 ReductionKind Kind) {
1788   if (Phi->getNumIncomingValues() != 2)
1789     return false;
1790
1791   // Find the possible incoming reduction variable.
1792   BasicBlock *BB = Phi->getParent();
1793   int SelfEdgeIdx = Phi->getBasicBlockIndex(BB);
1794   int InEdgeBlockIdx = (SelfEdgeIdx ? 0 : 1); // The other entry.
1795   Value *RdxStart = Phi->getIncomingValue(InEdgeBlockIdx);
1796
1797   // ExitInstruction is the single value which is used outside the loop.
1798   // We only allow for a single reduction value to be used outside the loop.
1799   // This includes users of the reduction, variables (which form a cycle
1800   // which ends in the phi node).
1801   Instruction *ExitInstruction = 0;
1802
1803   // Iter is our iterator. We start with the PHI node and scan for all of the
1804   // users of this instruction. All users must be instructions which can be
1805   // used as reduction variables (such as ADD). We may have a single
1806   // out-of-block user. They cycle must end with the original PHI.
1807   // Also, we can't have multiple block-local users.
1808   Instruction *Iter = Phi;
1809   while (true) {
1810     // Any reduction instr must be of one of the allowed kinds.
1811     if (!isReductionInstr(Iter, Kind))
1812       return false;
1813
1814     // Did we found a user inside this block ?
1815     bool FoundInBlockUser = false;
1816     // Did we reach the initial PHI node ?
1817     bool FoundStartPHI = false;
1818
1819     // If the instruction has no users then this is a broken
1820     // chain and can't be a reduction variable.
1821     if (Iter->use_empty())
1822       return false;
1823
1824     // For each of the *users* of iter.
1825     for (Value::use_iterator it = Iter->use_begin(), e = Iter->use_end();
1826          it != e; ++it) {
1827       Instruction *U = cast<Instruction>(*it);
1828       // We already know that the PHI is a user.
1829       if (U == Phi) {
1830         FoundStartPHI = true;
1831         continue;
1832       }
1833       // Check if we found the exit user.
1834       BasicBlock *Parent = U->getParent();
1835       if (Parent != BB) {
1836         // We must have a single exit instruction.
1837         if (ExitInstruction != 0)
1838           return false;
1839         ExitInstruction = Iter;
1840       }
1841       // We can't have multiple inside users.
1842       if (FoundInBlockUser)
1843         return false;
1844       FoundInBlockUser = true;
1845       Iter = U;
1846     }
1847
1848     // We found a reduction var if we have reached the original
1849     // phi node and we only have a single instruction with out-of-loop
1850     // users.
1851    if (FoundStartPHI && ExitInstruction) {
1852      // This instruction is allowed to have out-of-loop users.
1853      AllowedExit.insert(ExitInstruction);
1854
1855      // Save the description of this reduction variable.
1856      ReductionDescriptor RD(RdxStart, ExitInstruction, Kind);
1857      Reductions[Phi] = RD;
1858      return true;
1859    }
1860   }
1861 }
1862
1863 bool
1864 LoopVectorizationLegality::isReductionInstr(Instruction *I,
1865                                             ReductionKind Kind) {
1866     switch (I->getOpcode()) {
1867     default:
1868       return false;
1869     case Instruction::PHI:
1870       // possibly.
1871       return true;
1872     case Instruction::Add:
1873     case Instruction::Sub:
1874       return Kind == IntegerAdd;
1875     case Instruction::Mul:
1876       return Kind == IntegerMult;
1877     case Instruction::And:
1878       return Kind == IntegerAnd;
1879     case Instruction::Or:
1880       return Kind == IntegerOr;
1881     case Instruction::Xor:
1882       return Kind == IntegerXor;
1883     }
1884 }
1885
1886 bool LoopVectorizationLegality::isInductionVariable(PHINode *Phi) {
1887   Type *PhiTy = Phi->getType();
1888   // We only handle integer and pointer inductions variables.
1889   if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
1890     return false;
1891
1892   // Check that the PHI is consecutive and starts at zero.
1893   const SCEV *PhiScev = SE->getSCEV(Phi);
1894   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
1895   if (!AR) {
1896     DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
1897     return false;
1898   }
1899   const SCEV *Step = AR->getStepRecurrence(*SE);
1900
1901   // Integer inductions need to have a stride of one.
1902   if (PhiTy->isIntegerTy())
1903     return Step->isOne();
1904
1905   // Calculate the pointer stride and check if it is consecutive.
1906   const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
1907   if (!C) return false;
1908
1909   assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
1910   uint64_t Size = DL->getTypeAllocSize(PhiTy->getPointerElementType());
1911   return (C->getValue()->equalsInt(Size));
1912 }
1913
1914 bool LoopVectorizationLegality::hasComputableBounds(Value *Ptr) {
1915   const SCEV *PhiScev = SE->getSCEV(Ptr);
1916   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
1917   if (!AR)
1918     return false;
1919
1920   return AR->isAffine();
1921 }
1922
1923 unsigned
1924 LoopVectorizationCostModel::findBestVectorizationFactor(unsigned VF) {
1925   if (!VTTI) {
1926     DEBUG(dbgs() << "LV: No vector target information. Not vectorizing. \n");
1927     return 1;
1928   }
1929
1930   float Cost = expectedCost(1);
1931   unsigned Width = 1;
1932   DEBUG(dbgs() << "LV: Scalar loop costs: "<< (int)Cost << ".\n");
1933   for (unsigned i=2; i <= VF; i*=2) {
1934     // Notice that the vector loop needs to be executed less times, so
1935     // we need to divide the cost of the vector loops by the width of
1936     // the vector elements.
1937     float VectorCost = expectedCost(i) / (float)i;
1938     DEBUG(dbgs() << "LV: Vector loop of width "<< i << " costs: " <<
1939           (int)VectorCost << ".\n");
1940     if (VectorCost < Cost) {
1941       Cost = VectorCost;
1942       Width = i;
1943     }
1944   }
1945
1946   DEBUG(dbgs() << "LV: Selecting VF = : "<< Width << ".\n");
1947   return Width;
1948 }
1949
1950 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
1951   // We can only estimate the cost of single basic block loops.
1952   assert(1 == TheLoop->getNumBlocks() && "Too many blocks in loop");
1953
1954   BasicBlock *BB = TheLoop->getHeader();
1955   unsigned Cost = 0;
1956
1957   // For each instruction in the old loop.
1958   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1959     Instruction *Inst = it;
1960     unsigned C = getInstructionCost(Inst, VF);
1961     Cost += C;
1962     DEBUG(dbgs() << "LV: Found an estimated cost of "<< C <<" for VF "<< VF <<
1963           " For instruction: "<< *Inst << "\n");
1964   }
1965
1966   return Cost;
1967 }
1968
1969 unsigned
1970 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
1971   assert(VTTI && "Invalid vector target transformation info");
1972
1973   // If we know that this instruction will remain uniform, check the cost of
1974   // the scalar version.
1975   if (Legal->isUniformAfterVectorization(I))
1976     VF = 1;
1977
1978   Type *RetTy = I->getType();
1979   Type *VectorTy = ToVectorTy(RetTy, VF);
1980
1981
1982   // TODO: We need to estimate the cost of intrinsic calls.
1983   switch (I->getOpcode()) {
1984     case Instruction::GetElementPtr:
1985       // We mark this instruction as zero-cost because scalar GEPs are usually
1986       // lowered to the intruction addressing mode. At the moment we don't
1987       // generate vector geps.
1988       return 0;
1989     case Instruction::Br: {
1990       return VTTI->getCFInstrCost(I->getOpcode());
1991     }
1992     case Instruction::PHI:
1993       return 0;
1994     case Instruction::Add:
1995     case Instruction::FAdd:
1996     case Instruction::Sub:
1997     case Instruction::FSub:
1998     case Instruction::Mul:
1999     case Instruction::FMul:
2000     case Instruction::UDiv:
2001     case Instruction::SDiv:
2002     case Instruction::FDiv:
2003     case Instruction::URem:
2004     case Instruction::SRem:
2005     case Instruction::FRem:
2006     case Instruction::Shl:
2007     case Instruction::LShr:
2008     case Instruction::AShr:
2009     case Instruction::And:
2010     case Instruction::Or:
2011     case Instruction::Xor: {
2012       return VTTI->getArithmeticInstrCost(I->getOpcode(), VectorTy);
2013     }
2014     case Instruction::Select: {
2015       SelectInst *SI = cast<SelectInst>(I);
2016       const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
2017       bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
2018       Type *CondTy = SI->getCondition()->getType();
2019       if (ScalarCond)
2020         CondTy = VectorType::get(CondTy, VF);
2021
2022       return VTTI->getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
2023     }
2024     case Instruction::ICmp:
2025     case Instruction::FCmp: {
2026       Type *ValTy = I->getOperand(0)->getType();
2027       VectorTy = ToVectorTy(ValTy, VF);
2028       return VTTI->getCmpSelInstrCost(I->getOpcode(), VectorTy);
2029     }
2030     case Instruction::Store: {
2031       StoreInst *SI = cast<StoreInst>(I);
2032       Type *ValTy = SI->getValueOperand()->getType();
2033       VectorTy = ToVectorTy(ValTy, VF);
2034
2035       if (VF == 1)
2036         return VTTI->getMemoryOpCost(I->getOpcode(), ValTy,
2037                               SI->getAlignment(), SI->getPointerAddressSpace());
2038
2039       // Scalarized stores.
2040       if (!Legal->isConsecutivePtr(SI->getPointerOperand())) {
2041         unsigned Cost = 0;
2042         unsigned ExtCost = VTTI->getInstrCost(Instruction::ExtractElement,
2043                                               ValTy);
2044         // The cost of extracting from the value vector.
2045         Cost += VF * (ExtCost);
2046         // The cost of the scalar stores.
2047         Cost += VF * VTTI->getMemoryOpCost(I->getOpcode(),
2048                                            ValTy->getScalarType(),
2049                                            SI->getAlignment(),
2050                                            SI->getPointerAddressSpace());
2051         return Cost;
2052       }
2053
2054       // Wide stores.
2055       return VTTI->getMemoryOpCost(I->getOpcode(), VectorTy, SI->getAlignment(),
2056                                    SI->getPointerAddressSpace());
2057     }
2058     case Instruction::Load: {
2059       LoadInst *LI = cast<LoadInst>(I);
2060
2061       if (VF == 1)
2062         return VTTI->getMemoryOpCost(I->getOpcode(), RetTy,
2063                                      LI->getAlignment(),
2064                                      LI->getPointerAddressSpace());
2065
2066       // Scalarized loads.
2067       if (!Legal->isConsecutivePtr(LI->getPointerOperand())) {
2068         unsigned Cost = 0;
2069         unsigned InCost = VTTI->getInstrCost(Instruction::InsertElement, RetTy);
2070         // The cost of inserting the loaded value into the result vector.
2071         Cost += VF * (InCost);
2072         // The cost of the scalar stores.
2073         Cost += VF * VTTI->getMemoryOpCost(I->getOpcode(),
2074                                            RetTy->getScalarType(),
2075                                            LI->getAlignment(),
2076                                            LI->getPointerAddressSpace());
2077         return Cost;
2078       }
2079
2080       // Wide loads.
2081       return VTTI->getMemoryOpCost(I->getOpcode(), VectorTy, LI->getAlignment(),
2082                                    LI->getPointerAddressSpace());
2083     }
2084     case Instruction::ZExt:
2085     case Instruction::SExt:
2086     case Instruction::FPToUI:
2087     case Instruction::FPToSI:
2088     case Instruction::FPExt:
2089     case Instruction::PtrToInt:
2090     case Instruction::IntToPtr:
2091     case Instruction::SIToFP:
2092     case Instruction::UIToFP:
2093     case Instruction::Trunc:
2094     case Instruction::FPTrunc:
2095     case Instruction::BitCast: {
2096       Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
2097       return VTTI->getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
2098     }
2099     default: {
2100       // We are scalarizing the instruction. Return the cost of the scalar
2101       // instruction, plus the cost of insert and extract into vector
2102       // elements, times the vector width.
2103       unsigned Cost = 0;
2104
2105       bool IsVoid = RetTy->isVoidTy();
2106
2107       unsigned InsCost = (IsVoid ? 0 :
2108                           VTTI->getInstrCost(Instruction::InsertElement,
2109                                              VectorTy));
2110
2111       unsigned ExtCost = VTTI->getInstrCost(Instruction::ExtractElement,
2112                                             VectorTy);
2113
2114       // The cost of inserting the results plus extracting each one of the
2115       // operands.
2116       Cost += VF * (InsCost + ExtCost * I->getNumOperands());
2117
2118       // The cost of executing VF copies of the scalar instruction.
2119       Cost += VF * VTTI->getInstrCost(I->getOpcode(), RetTy);
2120       return Cost;
2121     }
2122   }// end of switch.
2123 }
2124
2125 Type* LoopVectorizationCostModel::ToVectorTy(Type *Scalar, unsigned VF) {
2126   if (Scalar->isVoidTy() || VF == 1)
2127     return Scalar;
2128   return VectorType::get(Scalar, VF);
2129 }
2130
2131 } // namespace
2132
2133 char LoopVectorize::ID = 0;
2134 static const char lv_name[] = "Loop Vectorization";
2135 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
2136 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
2137 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
2138 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
2139 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
2140
2141 namespace llvm {
2142   Pass *createLoopVectorizePass() {
2143     return new LoopVectorize();
2144   }
2145 }
2146