e79d526aadc46eaba3a1f9012b85f62d03296c40
[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   Constant *Zero = ConstantInt::get(I32, 0);
520   Value *Zeros = ConstantAggregateZero::get(VectorType::get(I32, VF));
521   Value *UndefVal = UndefValue::get(VTy);
522   // Insert the value into a new vector.
523   Value *SingleElem = Builder.CreateInsertElement(UndefVal, V, Zero);
524   // Broadcast the scalar into all locations in the vector.
525   Value *Shuf = Builder.CreateShuffleVector(SingleElem, UndefVal, Zeros,
526                                              "broadcast");
527   // We are accessing the induction variable. Make sure to promote the
528   // index for each consecutive SIMD lane. This adds 0,1,2 ... to all lanes.
529   if (V == Induction)
530     return getConsecutiveVector(Shuf);
531   return Shuf;
532 }
533
534 Value *SingleBlockLoopVectorizer::getConsecutiveVector(Value* Val) {
535   assert(Val->getType()->isVectorTy() && "Must be a vector");
536   assert(Val->getType()->getScalarType()->isIntegerTy() &&
537          "Elem must be an integer");
538   // Create the types.
539   Type *ITy = Val->getType()->getScalarType();
540   VectorType *Ty = cast<VectorType>(Val->getType());
541   unsigned VLen = Ty->getNumElements();
542   SmallVector<Constant*, 8> Indices;
543
544   // Create a vector of consecutive numbers from zero to VF.
545   for (unsigned i = 0; i < VLen; ++i)
546     Indices.push_back(ConstantInt::get(ITy, i));
547
548   // Add the consecutive indices to the vector value.
549   Constant *Cv = ConstantVector::get(Indices);
550   assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
551   return Builder.CreateAdd(Val, Cv, "induction");
552 }
553
554 bool LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
555   assert(Ptr->getType()->isPointerTy() && "Unexpected non ptr");
556
557   // If this pointer is an induction variable, return it.
558   PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
559   if (Phi && getInductionVars()->count(Phi))
560     return true;
561
562   GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
563   if (!Gep)
564     return false;
565
566   unsigned NumOperands = Gep->getNumOperands();
567   Value *LastIndex = Gep->getOperand(NumOperands - 1);
568
569   // Check that all of the gep indices are uniform except for the last.
570   for (unsigned i = 0; i < NumOperands - 1; ++i)
571     if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
572       return false;
573
574   // We can emit wide load/stores only of the last index is the induction
575   // variable.
576   const SCEV *Last = SE->getSCEV(LastIndex);
577   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
578     const SCEV *Step = AR->getStepRecurrence(*SE);
579
580     // The memory is consecutive because the last index is consecutive
581     // and all other indices are loop invariant.
582     if (Step->isOne())
583       return true;
584   }
585
586   return false;
587 }
588
589 bool LoopVectorizationLegality::isUniform(Value *V) {
590   return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
591 }
592
593 Value *SingleBlockLoopVectorizer::getVectorValue(Value *V) {
594   assert(!V->getType()->isVectorTy() && "Can't widen a vector");
595   // If we saved a vectorized copy of V, use it.
596   Value *&MapEntry = WidenMap[V];
597   if (MapEntry)
598     return MapEntry;
599
600   // Broadcast V and save the value for future uses.
601   Value *B = getBroadcastInstrs(V);
602   MapEntry = B;
603   return B;
604 }
605
606 Constant*
607 SingleBlockLoopVectorizer::getUniformVector(unsigned Val, Type* ScalarTy) {
608   return ConstantVector::getSplat(VF, ConstantInt::get(ScalarTy, Val, true));
609 }
610
611 void SingleBlockLoopVectorizer::scalarizeInstruction(Instruction *Instr) {
612   assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
613   // Holds vector parameters or scalars, in case of uniform vals.
614   SmallVector<Value*, 8> Params;
615
616   // Find all of the vectorized parameters.
617   for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
618     Value *SrcOp = Instr->getOperand(op);
619
620     // If we are accessing the old induction variable, use the new one.
621     if (SrcOp == OldInduction) {
622       Params.push_back(getVectorValue(Induction));
623       continue;
624     }
625
626     // Try using previously calculated values.
627     Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
628
629     // If the src is an instruction that appeared earlier in the basic block
630     // then it should already be vectorized.
631     if (SrcInst && SrcInst->getParent() == Instr->getParent()) {
632       assert(WidenMap.count(SrcInst) && "Source operand is unavailable");
633       // The parameter is a vector value from earlier.
634       Params.push_back(WidenMap[SrcInst]);
635     } else {
636       // The parameter is a scalar from outside the loop. Maybe even a constant.
637       Params.push_back(SrcOp);
638     }
639   }
640
641   assert(Params.size() == Instr->getNumOperands() &&
642          "Invalid number of operands");
643
644   // Does this instruction return a value ?
645   bool IsVoidRetTy = Instr->getType()->isVoidTy();
646   Value *VecResults = 0;
647
648   // If we have a return value, create an empty vector. We place the scalarized
649   // instructions in this vector.
650   if (!IsVoidRetTy)
651     VecResults = UndefValue::get(VectorType::get(Instr->getType(), VF));
652
653   // For each scalar that we create:
654   for (unsigned i = 0; i < VF; ++i) {
655     Instruction *Cloned = Instr->clone();
656     if (!IsVoidRetTy)
657       Cloned->setName(Instr->getName() + ".cloned");
658     // Replace the operands of the cloned instrucions with extracted scalars.
659     for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
660       Value *Op = Params[op];
661       // Param is a vector. Need to extract the right lane.
662       if (Op->getType()->isVectorTy())
663         Op = Builder.CreateExtractElement(Op, Builder.getInt32(i));
664       Cloned->setOperand(op, Op);
665     }
666
667     // Place the cloned scalar in the new loop.
668     Builder.Insert(Cloned);
669
670     // If the original scalar returns a value we need to place it in a vector
671     // so that future users will be able to use it.
672     if (!IsVoidRetTy)
673       VecResults = Builder.CreateInsertElement(VecResults, Cloned,
674                                                Builder.getInt32(i));
675   }
676
677   if (!IsVoidRetTy)
678     WidenMap[Instr] = VecResults;
679 }
680
681 Value*
682 SingleBlockLoopVectorizer::addRuntimeCheck(LoopVectorizationLegality *Legal,
683                                            Instruction *Loc) {
684   LoopVectorizationLegality::RuntimePointerCheck *PtrRtCheck =
685     Legal->getRuntimePointerCheck();
686
687   if (!PtrRtCheck->Need)
688     return NULL;
689
690   Value *MemoryRuntimeCheck = 0;
691   unsigned NumPointers = PtrRtCheck->Pointers.size();
692   SmallVector<Value* , 2> Starts;
693   SmallVector<Value* , 2> Ends;
694
695   SCEVExpander Exp(*SE, "induction");
696
697   // Use this type for pointer arithmetic.
698   Type* PtrArithTy = PtrRtCheck->Pointers[0]->getType();
699
700   for (unsigned i=0; i < NumPointers; ++i) {
701     Value *Ptr = PtrRtCheck->Pointers[i];
702     const SCEV *Sc = SE->getSCEV(Ptr);
703
704     if (SE->isLoopInvariant(Sc, OrigLoop)) {
705       DEBUG(dbgs() << "LV1: Adding RT check for a loop invariant ptr:" <<
706             *Ptr <<"\n");
707       Starts.push_back(Ptr);
708       Ends.push_back(Ptr);
709     } else {
710       DEBUG(dbgs() << "LV: Adding RT check for range:" << *Ptr <<"\n");
711
712       Value *Start = Exp.expandCodeFor(PtrRtCheck->Starts[i],
713                                        PtrArithTy, Loc);
714       Value *End = Exp.expandCodeFor(PtrRtCheck->Ends[i], PtrArithTy, Loc);
715       Starts.push_back(Start);
716       Ends.push_back(End);
717     }
718   }
719
720   for (unsigned i = 0; i < NumPointers; ++i) {
721     for (unsigned j = i+1; j < NumPointers; ++j) {
722       Value *Cmp0 = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_ULE,
723                                     Starts[i], Ends[j], "bound0", Loc);
724       Value *Cmp1 = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_ULE,
725                                     Starts[j], Ends[i], "bound1", Loc);
726       Value *IsConflict = BinaryOperator::Create(Instruction::And, Cmp0, Cmp1,
727                                                  "found.conflict", Loc);
728       if (MemoryRuntimeCheck) {
729         MemoryRuntimeCheck = BinaryOperator::Create(Instruction::Or,
730                                                     MemoryRuntimeCheck,
731                                                     IsConflict,
732                                                     "conflict.rdx", Loc);
733       } else {
734         MemoryRuntimeCheck = IsConflict;
735       }
736     }
737   }
738
739   return MemoryRuntimeCheck;
740 }
741
742 void
743 SingleBlockLoopVectorizer::createEmptyLoop(LoopVectorizationLegality *Legal) {
744   /*
745    In this function we generate a new loop. The new loop will contain
746    the vectorized instructions while the old loop will continue to run the
747    scalar remainder.
748
749     [ ] <-- vector loop bypass.
750   /  |
751  /   v
752 |   [ ]     <-- vector pre header.
753 |    |
754 |    v
755 |   [  ] \
756 |   [  ]_|   <-- vector loop.
757 |    |
758  \   v
759    >[ ]   <--- middle-block.
760   /  |
761  /   v
762 |   [ ]     <--- new preheader.
763 |    |
764 |    v
765 |   [ ] \
766 |   [ ]_|   <-- old scalar loop to handle remainder.
767  \   |
768   \  v
769    >[ ]     <-- exit block.
770    ...
771    */
772
773   // Some loops have a single integer induction variable, while other loops
774   // don't. One example is c++ iterators that often have multiple pointer
775   // induction variables. In the code below we also support a case where we
776   // don't have a single induction variable.
777   OldInduction = Legal->getInduction();
778   Type *IdxTy = OldInduction ? OldInduction->getType() :
779     DL->getIntPtrType(SE->getContext());
780
781   // Find the loop boundaries.
782   const SCEV *ExitCount = SE->getExitCount(OrigLoop, OrigLoop->getHeader());
783   assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
784
785   // Get the total trip count from the count by adding 1.
786   ExitCount = SE->getAddExpr(ExitCount,
787                              SE->getConstant(ExitCount->getType(), 1));
788
789   // This is the original scalar-loop preheader.
790   BasicBlock *BypassBlock = OrigLoop->getLoopPreheader();
791   BasicBlock *ExitBlock = OrigLoop->getExitBlock();
792   assert(ExitBlock && "Must have an exit block");
793
794   // The loop index does not have to start at Zero. Find the original start
795   // value from the induction PHI node. If we don't have an induction variable
796   // then we know that it starts at zero.
797   Value *StartIdx = OldInduction ?
798     OldInduction->getIncomingValueForBlock(BypassBlock):
799     ConstantInt::get(IdxTy, 0);
800
801   assert(OrigLoop->getNumBlocks() == 1 && "Invalid loop");
802   assert(BypassBlock && "Invalid loop structure");
803
804   BasicBlock *VectorPH =
805       BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
806   BasicBlock *VecBody = VectorPH->splitBasicBlock(VectorPH->getTerminator(),
807                                                  "vector.body");
808
809   BasicBlock *MiddleBlock = VecBody->splitBasicBlock(VecBody->getTerminator(),
810                                                   "middle.block");
811   BasicBlock *ScalarPH =
812     MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(),
813                                  "scalar.preheader");
814   // Find the induction variable.
815   BasicBlock *OldBasicBlock = OrigLoop->getHeader();
816
817   // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
818   // inside the loop.
819   Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
820
821   // Generate the induction variable.
822   Induction = Builder.CreatePHI(IdxTy, 2, "index");
823   Constant *Step = ConstantInt::get(IdxTy, VF);
824
825   // Expand the trip count and place the new instructions in the preheader.
826   // Notice that the pre-header does not change, only the loop body.
827   SCEVExpander Exp(*SE, "induction");
828   Instruction *Loc = BypassBlock->getTerminator();
829
830   // Count holds the overall loop count (N).
831   Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(), Loc);
832
833   // We may need to extend the index in case there is a type mismatch.
834   // We know that the count starts at zero and does not overflow.
835   if (Count->getType() != IdxTy) {
836     // The exit count can be of pointer type. Convert it to the correct
837     // integer type.
838     if (ExitCount->getType()->isPointerTy())
839       Count = CastInst::CreatePointerCast(Count, IdxTy, "ptrcnt.to.int", Loc);
840     else
841       Count = CastInst::CreateZExtOrBitCast(Count, IdxTy, "zext.cnt", Loc);
842   }
843
844   // Add the start index to the loop count to get the new end index.
845   Value *IdxEnd = BinaryOperator::CreateAdd(Count, StartIdx, "end.idx", Loc);
846
847   // Now we need to generate the expression for N - (N % VF), which is
848   // the part that the vectorized body will execute.
849   Constant *CIVF = ConstantInt::get(IdxTy, VF);
850   Value *R = BinaryOperator::CreateURem(Count, CIVF, "n.mod.vf", Loc);
851   Value *CountRoundDown = BinaryOperator::CreateSub(Count, R, "n.vec", Loc);
852   Value *IdxEndRoundDown = BinaryOperator::CreateAdd(CountRoundDown, StartIdx,
853                                                      "end.idx.rnd.down", Loc);
854
855   // Now, compare the new count to zero. If it is zero skip the vector loop and
856   // jump to the scalar loop.
857   Value *Cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
858                                IdxEndRoundDown,
859                                StartIdx,
860                                "cmp.zero", Loc);
861
862   Value *MemoryRuntimeCheck = addRuntimeCheck(Legal, Loc);
863
864   // If we are using memory runtime checks, include them in.
865   if (MemoryRuntimeCheck)
866     Cmp = BinaryOperator::Create(Instruction::Or, Cmp, MemoryRuntimeCheck,
867                                  "CntOrMem", Loc);
868
869   BranchInst::Create(MiddleBlock, VectorPH, Cmp, Loc);
870   // Remove the old terminator.
871   Loc->eraseFromParent();
872
873   // We are going to resume the execution of the scalar loop.
874   // Go over all of the induction variables that we found and fix the
875   // PHIs that are left in the scalar version of the loop.
876   // The starting values of PHI nodes depend on the counter of the last
877   // iteration in the vectorized loop.
878   // If we come from a bypass edge then we need to start from the original start
879   // value.
880
881   // This variable saves the new starting index for the scalar loop.
882   PHINode *ResumeIndex = 0;
883   LoopVectorizationLegality::InductionList::iterator I, E;
884   LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
885   for (I = List->begin(), E = List->end(); I != E; ++I) {
886     PHINode *OrigPhi = I->first;
887     PHINode *ResumeVal = PHINode::Create(OrigPhi->getType(), 2, "resume.val",
888                                            MiddleBlock->getTerminator());
889     Value *EndValue = 0;
890     if (OrigPhi->getType()->isIntegerTy()) {
891       // Handle the integer induction counter:
892       assert(OrigPhi == OldInduction && "Unknown integer PHI");
893       // We know what the end value is.
894       EndValue = IdxEndRoundDown;
895       // We also know which PHI node holds it.
896       ResumeIndex = ResumeVal;
897     } else {
898       // For pointer induction variables, calculate the offset using
899       // the end index.
900       EndValue = GetElementPtrInst::Create(I->second, CountRoundDown,
901                                            "ptr.ind.end",
902                                            BypassBlock->getTerminator());
903     }
904
905     // The new PHI merges the original incoming value, in case of a bypass,
906     // or the value at the end of the vectorized loop.
907     ResumeVal->addIncoming(I->second, BypassBlock);
908     ResumeVal->addIncoming(EndValue, VecBody);
909
910     // Fix the scalar body counter (PHI node).
911     unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
912     OrigPhi->setIncomingValue(BlockIdx, ResumeVal);
913   }
914
915   // If we are generating a new induction variable then we also need to
916   // generate the code that calculates the exit value. This value is not
917   // simply the end of the counter because we may skip the vectorized body
918   // in case of a runtime check.
919   if (!OldInduction){
920     assert(!ResumeIndex && "Unexpected resume value found");
921     ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val",
922                                   MiddleBlock->getTerminator());
923     ResumeIndex->addIncoming(StartIdx, BypassBlock);
924     ResumeIndex->addIncoming(IdxEndRoundDown, VecBody);
925   }
926
927   // Make sure that we found the index where scalar loop needs to continue.
928   assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() &&
929          "Invalid resume Index");
930
931   // Add a check in the middle block to see if we have completed
932   // all of the iterations in the first vector loop.
933   // If (N - N%VF) == N, then we *don't* need to run the remainder.
934   Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd,
935                                 ResumeIndex, "cmp.n",
936                                 MiddleBlock->getTerminator());
937
938   BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
939   // Remove the old terminator.
940   MiddleBlock->getTerminator()->eraseFromParent();
941
942   // Create i+1 and fill the PHINode.
943   Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
944   Induction->addIncoming(StartIdx, VectorPH);
945   Induction->addIncoming(NextIdx, VecBody);
946   // Create the compare.
947   Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown);
948   Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
949
950   // Now we have two terminators. Remove the old one from the block.
951   VecBody->getTerminator()->eraseFromParent();
952
953   // Get ready to start creating new instructions into the vectorized body.
954   Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
955
956   // Register the new loop.
957   Loop* Lp = new Loop();
958   LPM->insertLoop(Lp, OrigLoop->getParentLoop());
959
960   Lp->addBasicBlockToLoop(VecBody, LI->getBase());
961
962   Loop *ParentLoop = OrigLoop->getParentLoop();
963   if (ParentLoop) {
964     ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase());
965     ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase());
966     ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase());
967   }
968
969   // Save the state.
970   LoopVectorPreHeader = VectorPH;
971   LoopScalarPreHeader = ScalarPH;
972   LoopMiddleBlock = MiddleBlock;
973   LoopExitBlock = ExitBlock;
974   LoopVectorBody = VecBody;
975   LoopScalarBody = OldBasicBlock;
976   LoopBypassBlock = BypassBlock;
977 }
978
979 /// This function returns the identity element (or neutral element) for
980 /// the operation K.
981 static unsigned
982 getReductionIdentity(LoopVectorizationLegality::ReductionKind K) {
983   switch (K) {
984   case LoopVectorizationLegality::IntegerXor:
985   case LoopVectorizationLegality::IntegerAdd:
986   case LoopVectorizationLegality::IntegerOr:
987     // Adding, Xoring, Oring zero to a number does not change it.
988     return 0;
989   case LoopVectorizationLegality::IntegerMult:
990     // Multiplying a number by 1 does not change it.
991     return 1;
992   case LoopVectorizationLegality::IntegerAnd:
993     // AND-ing a number with an all-1 value does not change it.
994     return -1;
995   default:
996     llvm_unreachable("Unknown reduction kind");
997   }
998 }
999
1000 void
1001 SingleBlockLoopVectorizer::vectorizeLoop(LoopVectorizationLegality *Legal) {
1002   //===------------------------------------------------===//
1003   //
1004   // Notice: any optimization or new instruction that go
1005   // into the code below should be also be implemented in
1006   // the cost-model.
1007   //
1008   //===------------------------------------------------===//
1009   typedef SmallVector<PHINode*, 4> PhiVector;
1010   BasicBlock &BB = *OrigLoop->getHeader();
1011   Constant *Zero = ConstantInt::get(
1012     IntegerType::getInt32Ty(BB.getContext()), 0);
1013
1014   // In order to support reduction variables we need to be able to vectorize
1015   // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
1016   // steages. First, we create a new vector PHI node with no incoming edges.
1017   // We use this value when we vectorize all of the instructions that use the
1018   // PHI. Next, after all of the instructions in the block are complete we
1019   // add the new incoming edges to the PHI. At this point all of the
1020   // instructions in the basic block are vectorized, so we can use them to
1021   // construct the PHI.
1022   PhiVector RdxPHIsToFix;
1023
1024   // For each instruction in the old loop.
1025   for (BasicBlock::iterator it = BB.begin(), e = BB.end(); it != e; ++it) {
1026     Instruction *Inst = it;
1027
1028     switch (Inst->getOpcode()) {
1029       case Instruction::Br:
1030         // Nothing to do for PHIs and BR, since we already took care of the
1031         // loop control flow instructions.
1032         continue;
1033       case Instruction::PHI:{
1034         PHINode* P = cast<PHINode>(Inst);
1035         // Handle reduction variables:
1036         if (Legal->getReductionVars()->count(P)) {
1037           // This is phase one of vectorizing PHIs.
1038           Type *VecTy = VectorType::get(Inst->getType(), VF);
1039           WidenMap[Inst] = PHINode::Create(VecTy, 2, "vec.phi",
1040                                   LoopVectorBody->getFirstInsertionPt());
1041           RdxPHIsToFix.push_back(P);
1042           continue;
1043         }
1044
1045         // This PHINode must be an induction variable.
1046         // Make sure that we know about it.
1047         assert(Legal->getInductionVars()->count(P) &&
1048                "Not an induction variable");
1049
1050         if (P->getType()->isIntegerTy()) {
1051           assert(P == OldInduction && "Unexpected PHI");
1052           WidenMap[Inst] = getBroadcastInstrs(Induction);
1053           continue;
1054         }
1055
1056         // Handle pointer inductions:
1057         assert(P->getType()->isPointerTy() && "Unexpected type.");
1058         Value *StartIdx = OldInduction ?
1059           Legal->getInductionVars()->lookup(OldInduction) :
1060           ConstantInt::get(Induction->getType(), 0);
1061
1062         // This is the pointer value coming into the loop.
1063         Value *StartPtr = Legal->getInductionVars()->lookup(P);
1064
1065         // This is the normalized GEP that starts counting at zero.
1066         Value *NormalizedIdx = Builder.CreateSub(Induction, StartIdx,
1067                                                  "normalized.idx");
1068
1069         // This is the vector of results. Notice that we don't generate vector
1070         // geps because scalar geps result in better code.
1071         Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
1072         for (unsigned int i = 0; i < VF; ++i) {
1073           Constant *Idx = ConstantInt::get(Induction->getType(), i);
1074           Value *GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx, "gep.idx");
1075           Value *SclrGep = Builder.CreateGEP(StartPtr, GlobalIdx, "next.gep");
1076           VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
1077                                                Builder.getInt32(i),
1078                                                "insert.gep");
1079         }
1080
1081         WidenMap[Inst] = VecVal;
1082         continue;
1083       }
1084       case Instruction::Add:
1085       case Instruction::FAdd:
1086       case Instruction::Sub:
1087       case Instruction::FSub:
1088       case Instruction::Mul:
1089       case Instruction::FMul:
1090       case Instruction::UDiv:
1091       case Instruction::SDiv:
1092       case Instruction::FDiv:
1093       case Instruction::URem:
1094       case Instruction::SRem:
1095       case Instruction::FRem:
1096       case Instruction::Shl:
1097       case Instruction::LShr:
1098       case Instruction::AShr:
1099       case Instruction::And:
1100       case Instruction::Or:
1101       case Instruction::Xor: {
1102         // Just widen binops.
1103         BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
1104         Value *A = getVectorValue(Inst->getOperand(0));
1105         Value *B = getVectorValue(Inst->getOperand(1));
1106
1107         // Use this vector value for all users of the original instruction.
1108         Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A, B);
1109         WidenMap[Inst] = V;
1110
1111         // Update the NSW, NUW and Exact flags.
1112         BinaryOperator *VecOp = cast<BinaryOperator>(V);
1113         if (isa<OverflowingBinaryOperator>(BinOp)) {
1114           VecOp->setHasNoSignedWrap(BinOp->hasNoSignedWrap());
1115           VecOp->setHasNoUnsignedWrap(BinOp->hasNoUnsignedWrap());
1116         }
1117         if (isa<PossiblyExactOperator>(VecOp))
1118           VecOp->setIsExact(BinOp->isExact());
1119         break;
1120       }
1121       case Instruction::Select: {
1122         // Widen selects.
1123         // If the selector is loop invariant we can create a select
1124         // instruction with a scalar condition. Otherwise, use vector-select.
1125         Value *Cond = Inst->getOperand(0);
1126         bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(Cond), OrigLoop);
1127
1128         // The condition can be loop invariant  but still defined inside the
1129         // loop. This means that we can't just use the original 'cond' value.
1130         // We have to take the 'vectorized' value and pick the first lane.
1131         // Instcombine will make this a no-op.
1132         Cond = getVectorValue(Cond);
1133         if (InvariantCond)
1134           Cond = Builder.CreateExtractElement(Cond, Builder.getInt32(0));
1135
1136         Value *Op0 = getVectorValue(Inst->getOperand(1));
1137         Value *Op1 = getVectorValue(Inst->getOperand(2));
1138         WidenMap[Inst] = Builder.CreateSelect(Cond, Op0, Op1);
1139         break;
1140       }
1141
1142       case Instruction::ICmp:
1143       case Instruction::FCmp: {
1144         // Widen compares. Generate vector compares.
1145         bool FCmp = (Inst->getOpcode() == Instruction::FCmp);
1146         CmpInst *Cmp = dyn_cast<CmpInst>(Inst);
1147         Value *A = getVectorValue(Inst->getOperand(0));
1148         Value *B = getVectorValue(Inst->getOperand(1));
1149         if (FCmp)
1150           WidenMap[Inst] = Builder.CreateFCmp(Cmp->getPredicate(), A, B);
1151         else
1152           WidenMap[Inst] = Builder.CreateICmp(Cmp->getPredicate(), A, B);
1153         break;
1154       }
1155
1156       case Instruction::Store: {
1157         // Attempt to issue a wide store.
1158         StoreInst *SI = dyn_cast<StoreInst>(Inst);
1159         Type *StTy = VectorType::get(SI->getValueOperand()->getType(), VF);
1160         Value *Ptr = SI->getPointerOperand();
1161         unsigned Alignment = SI->getAlignment();
1162
1163         assert(!Legal->isUniform(Ptr) &&
1164                "We do not allow storing to uniform addresses");
1165
1166         GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1167
1168         // This store does not use GEPs.
1169         if (!Legal->isConsecutivePtr(Ptr)) {
1170           scalarizeInstruction(Inst);
1171           break;
1172         }
1173
1174         if (Gep) {
1175           // The last index does not have to be the induction. It can be
1176           // consecutive and be a function of the index. For example A[I+1];
1177           unsigned NumOperands = Gep->getNumOperands();
1178           Value *LastIndex = getVectorValue(Gep->getOperand(NumOperands - 1));
1179           LastIndex = Builder.CreateExtractElement(LastIndex, Zero);
1180
1181           // Create the new GEP with the new induction variable.
1182           GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1183           Gep2->setOperand(NumOperands - 1, LastIndex);
1184           Ptr = Builder.Insert(Gep2);
1185         } else {
1186           // Use the induction element ptr.
1187           assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1188           Ptr = Builder.CreateExtractElement(getVectorValue(Ptr), Zero);
1189         }
1190         Ptr = Builder.CreateBitCast(Ptr, StTy->getPointerTo());
1191         Value *Val = getVectorValue(SI->getValueOperand());
1192         Builder.CreateStore(Val, Ptr)->setAlignment(Alignment);
1193         break;
1194       }
1195       case Instruction::Load: {
1196         // Attempt to issue a wide load.
1197         LoadInst *LI = dyn_cast<LoadInst>(Inst);
1198         Type *RetTy = VectorType::get(LI->getType(), VF);
1199         Value *Ptr = LI->getPointerOperand();
1200         unsigned Alignment = LI->getAlignment();
1201         GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1202
1203         // If the pointer is loop invariant or if it is non consecutive,
1204         // scalarize the load.
1205         bool Con = Legal->isConsecutivePtr(Ptr);
1206         if (Legal->isUniform(Ptr) || !Con) {
1207           scalarizeInstruction(Inst);
1208           break;
1209         }
1210
1211         if (Gep) {
1212           // The last index does not have to be the induction. It can be
1213           // consecutive and be a function of the index. For example A[I+1];
1214           unsigned NumOperands = Gep->getNumOperands();
1215           Value *LastIndex = getVectorValue(Gep->getOperand(NumOperands -1));
1216           LastIndex = Builder.CreateExtractElement(LastIndex, Zero);
1217
1218           // Create the new GEP with the new induction variable.
1219           GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1220           Gep2->setOperand(NumOperands - 1, LastIndex);
1221           Ptr = Builder.Insert(Gep2);
1222         } else {
1223           // Use the induction element ptr.
1224           assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1225           Ptr = Builder.CreateExtractElement(getVectorValue(Ptr), Zero);
1226         }
1227
1228         Ptr = Builder.CreateBitCast(Ptr, RetTy->getPointerTo());
1229         LI = Builder.CreateLoad(Ptr);
1230         LI->setAlignment(Alignment);
1231         // Use this vector value for all users of the load.
1232         WidenMap[Inst] = LI;
1233         break;
1234       }
1235       case Instruction::ZExt:
1236       case Instruction::SExt:
1237       case Instruction::FPToUI:
1238       case Instruction::FPToSI:
1239       case Instruction::FPExt:
1240       case Instruction::PtrToInt:
1241       case Instruction::IntToPtr:
1242       case Instruction::SIToFP:
1243       case Instruction::UIToFP:
1244       case Instruction::Trunc:
1245       case Instruction::FPTrunc:
1246       case Instruction::BitCast: {
1247         /// Vectorize bitcasts.
1248         CastInst *CI = dyn_cast<CastInst>(Inst);
1249         Value *A = getVectorValue(Inst->getOperand(0));
1250         Type *DestTy = VectorType::get(CI->getType()->getScalarType(), VF);
1251         WidenMap[Inst] = Builder.CreateCast(CI->getOpcode(), A, DestTy);
1252         break;
1253       }
1254
1255       default:
1256         /// All other instructions are unsupported. Scalarize them.
1257         scalarizeInstruction(Inst);
1258         break;
1259     }// end of switch.
1260   }// end of for_each instr.
1261
1262   // At this point every instruction in the original loop is widended to
1263   // a vector form. We are almost done. Now, we need to fix the PHI nodes
1264   // that we vectorized. The PHI nodes are currently empty because we did
1265   // not want to introduce cycles. Notice that the remaining PHI nodes
1266   // that we need to fix are reduction variables.
1267
1268   // Create the 'reduced' values for each of the induction vars.
1269   // The reduced values are the vector values that we scalarize and combine
1270   // after the loop is finished.
1271   for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
1272        it != e; ++it) {
1273     PHINode *RdxPhi = *it;
1274     PHINode *VecRdxPhi = dyn_cast<PHINode>(WidenMap[RdxPhi]);
1275     assert(RdxPhi && "Unable to recover vectorized PHI");
1276
1277     // Find the reduction variable descriptor.
1278     assert(Legal->getReductionVars()->count(RdxPhi) &&
1279            "Unable to find the reduction variable");
1280     LoopVectorizationLegality::ReductionDescriptor RdxDesc =
1281       (*Legal->getReductionVars())[RdxPhi];
1282
1283     // We need to generate a reduction vector from the incoming scalar.
1284     // To do so, we need to generate the 'identity' vector and overide
1285     // one of the elements with the incoming scalar reduction. We need
1286     // to do it in the vector-loop preheader.
1287     Builder.SetInsertPoint(LoopBypassBlock->getTerminator());
1288
1289     // This is the vector-clone of the value that leaves the loop.
1290     Value *VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
1291     Type *VecTy = VectorExit->getType();
1292
1293     // Find the reduction identity variable. Zero for addition, or, xor,
1294     // one for multiplication, -1 for And.
1295     Constant *Identity = getUniformVector(getReductionIdentity(RdxDesc.Kind),
1296                                           VecTy->getScalarType());
1297
1298     // This vector is the Identity vector where the first element is the
1299     // incoming scalar reduction.
1300     Value *VectorStart = Builder.CreateInsertElement(Identity,
1301                                                     RdxDesc.StartValue, Zero);
1302
1303     // Fix the vector-loop phi.
1304     // We created the induction variable so we know that the
1305     // preheader is the first entry.
1306     BasicBlock *VecPreheader = Induction->getIncomingBlock(0);
1307
1308     // Reductions do not have to start at zero. They can start with
1309     // any loop invariant values.
1310     VecRdxPhi->addIncoming(VectorStart, VecPreheader);
1311     unsigned SelfEdgeIdx = (RdxPhi)->getBasicBlockIndex(LoopScalarBody);
1312     Value *Val = getVectorValue(RdxPhi->getIncomingValue(SelfEdgeIdx));
1313     VecRdxPhi->addIncoming(Val, LoopVectorBody);
1314
1315     // Before each round, move the insertion point right between
1316     // the PHIs and the values we are going to write.
1317     // This allows us to write both PHINodes and the extractelement
1318     // instructions.
1319     Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
1320
1321     // This PHINode contains the vectorized reduction variable, or
1322     // the initial value vector, if we bypass the vector loop.
1323     PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
1324     NewPhi->addIncoming(VectorStart, LoopBypassBlock);
1325     NewPhi->addIncoming(getVectorValue(RdxDesc.LoopExitInstr), LoopVectorBody);
1326
1327     // Extract the first scalar.
1328     Value *Scalar0 =
1329       Builder.CreateExtractElement(NewPhi, Builder.getInt32(0));
1330     // Extract and reduce the remaining vector elements.
1331     for (unsigned i=1; i < VF; ++i) {
1332       Value *Scalar1 =
1333         Builder.CreateExtractElement(NewPhi, Builder.getInt32(i));
1334       switch (RdxDesc.Kind) {
1335         case LoopVectorizationLegality::IntegerAdd:
1336           Scalar0 = Builder.CreateAdd(Scalar0, Scalar1);
1337           break;
1338         case LoopVectorizationLegality::IntegerMult:
1339           Scalar0 = Builder.CreateMul(Scalar0, Scalar1);
1340           break;
1341         case LoopVectorizationLegality::IntegerOr:
1342           Scalar0 = Builder.CreateOr(Scalar0, Scalar1);
1343           break;
1344         case LoopVectorizationLegality::IntegerAnd:
1345           Scalar0 = Builder.CreateAnd(Scalar0, Scalar1);
1346           break;
1347         case LoopVectorizationLegality::IntegerXor:
1348           Scalar0 = Builder.CreateXor(Scalar0, Scalar1);
1349           break;
1350         default:
1351           llvm_unreachable("Unknown reduction operation");
1352       }
1353     }
1354
1355     // Now, we need to fix the users of the reduction variable
1356     // inside and outside of the scalar remainder loop.
1357     // We know that the loop is in LCSSA form. We need to update the
1358     // PHI nodes in the exit blocks.
1359     for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
1360          LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
1361       PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
1362       if (!LCSSAPhi) continue;
1363
1364       // All PHINodes need to have a single entry edge, or two if
1365       // we already fixed them.
1366       assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
1367
1368       // We found our reduction value exit-PHI. Update it with the
1369       // incoming bypass edge.
1370       if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
1371         // Add an edge coming from the bypass.
1372         LCSSAPhi->addIncoming(Scalar0, LoopMiddleBlock);
1373         break;
1374       }
1375     }// end of the LCSSA phi scan.
1376
1377     // Fix the scalar loop reduction variable with the incoming reduction sum
1378     // from the vector body and from the backedge value.
1379     int IncomingEdgeBlockIdx = (RdxPhi)->getBasicBlockIndex(LoopScalarBody);
1380     int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1); // The other block.
1381     (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, Scalar0);
1382     (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
1383   }// end of for each redux variable.
1384 }
1385
1386 void SingleBlockLoopVectorizer::updateAnalysis() {
1387   // The original basic block.
1388   SE->forgetLoop(OrigLoop);
1389
1390   // Update the dominator tree information.
1391   assert(DT->properlyDominates(LoopBypassBlock, LoopExitBlock) &&
1392          "Entry does not dominate exit.");
1393
1394   DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlock);
1395   DT->addNewBlock(LoopVectorBody, LoopVectorPreHeader);
1396   DT->addNewBlock(LoopMiddleBlock, LoopBypassBlock);
1397   DT->addNewBlock(LoopScalarPreHeader, LoopMiddleBlock);
1398   DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
1399   DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
1400
1401   DEBUG(DT->verifyAnalysis());
1402 }
1403
1404 bool LoopVectorizationLegality::canVectorize() {
1405   if (!TheLoop->getLoopPreheader()) {
1406     assert(false && "No preheader!!");
1407     DEBUG(dbgs() << "LV: Loop not normalized." << "\n");
1408     return false;
1409   }
1410
1411   // We can only vectorize single basic block loops.
1412   unsigned NumBlocks = TheLoop->getNumBlocks();
1413   if (NumBlocks != 1) {
1414     DEBUG(dbgs() << "LV: Too many blocks:" << NumBlocks << "\n");
1415     return false;
1416   }
1417
1418   // We need to have a loop header.
1419   BasicBlock *BB = TheLoop->getHeader();
1420   DEBUG(dbgs() << "LV: Found a loop: " << BB->getName() << "\n");
1421
1422   // ScalarEvolution needs to be able to find the exit count.
1423   const SCEV *ExitCount = SE->getExitCount(TheLoop, BB);
1424   if (ExitCount == SE->getCouldNotCompute()) {
1425     DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
1426     return false;
1427   }
1428
1429   // Do not loop-vectorize loops with a tiny trip count.
1430   unsigned TC = SE->getSmallConstantTripCount(TheLoop, BB);
1431   if (TC > 0u && TC < TinyTripCountThreshold) {
1432     DEBUG(dbgs() << "LV: Found a loop with a very small trip count. " <<
1433           "This loop is not worth vectorizing.\n");
1434     return false;
1435   }
1436
1437   // Go over each instruction and look at memory deps.
1438   if (!canVectorizeBlock(*BB)) {
1439     DEBUG(dbgs() << "LV: Can't vectorize this loop header\n");
1440     return false;
1441   }
1442
1443   DEBUG(dbgs() << "LV: We can vectorize this loop" <<
1444         (PtrRtCheck.Need ? " (with a runtime bound check)" : "")
1445         <<"!\n");
1446
1447   // Okay! We can vectorize. At this point we don't have any other mem analysis
1448   // which may limit our maximum vectorization factor, so just return true with
1449   // no restrictions.
1450   return true;
1451 }
1452
1453 bool LoopVectorizationLegality::canVectorizeBlock(BasicBlock &BB) {
1454
1455   BasicBlock *PreHeader = TheLoop->getLoopPreheader();
1456
1457   // Scan the instructions in the block and look for hazards.
1458   for (BasicBlock::iterator it = BB.begin(), e = BB.end(); it != e; ++it) {
1459     Instruction *I = it;
1460
1461     if (PHINode *Phi = dyn_cast<PHINode>(I)) {
1462       // This should not happen because the loop should be normalized.
1463       if (Phi->getNumIncomingValues() != 2) {
1464         DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
1465         return false;
1466       }
1467
1468       // This is the value coming from the preheader.
1469       Value *StartValue = Phi->getIncomingValueForBlock(PreHeader);
1470
1471       // We only look at integer and pointer phi nodes.
1472       if (Phi->getType()->isPointerTy() && isInductionVariable(Phi)) {
1473         DEBUG(dbgs() << "LV: Found a pointer induction variable.\n");
1474         Inductions[Phi] = StartValue;
1475         continue;
1476       } else if (!Phi->getType()->isIntegerTy()) {
1477         DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
1478         return false;
1479       }
1480
1481       // Handle integer PHIs:
1482       if (isInductionVariable(Phi)) {
1483         if (Induction) {
1484           DEBUG(dbgs() << "LV: Found too many inductions."<< *Phi <<"\n");
1485           return false;
1486         }
1487         DEBUG(dbgs() << "LV: Found the induction PHI."<< *Phi <<"\n");
1488         Induction = Phi;
1489         Inductions[Phi] = StartValue;
1490         continue;
1491       }
1492       if (AddReductionVar(Phi, IntegerAdd)) {
1493         DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
1494         continue;
1495       }
1496       if (AddReductionVar(Phi, IntegerMult)) {
1497         DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n");
1498         continue;
1499       }
1500       if (AddReductionVar(Phi, IntegerOr)) {
1501         DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n");
1502         continue;
1503       }
1504       if (AddReductionVar(Phi, IntegerAnd)) {
1505         DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n");
1506         continue;
1507       }
1508       if (AddReductionVar(Phi, IntegerXor)) {
1509         DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n");
1510         continue;
1511       }
1512
1513       DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
1514       return false;
1515     }// end of PHI handling
1516
1517     // We still don't handle functions.
1518     CallInst *CI = dyn_cast<CallInst>(I);
1519     if (CI) {
1520       DEBUG(dbgs() << "LV: Found a call site.\n");
1521       return false;
1522     }
1523
1524     // We do not re-vectorize vectors.
1525     if (!VectorType::isValidElementType(I->getType()) &&
1526         !I->getType()->isVoidTy()) {
1527       DEBUG(dbgs() << "LV: Found unvectorizable type." << "\n");
1528       return false;
1529     }
1530
1531     // Reduction instructions are allowed to have exit users.
1532     // All other instructions must not have external users.
1533     if (!AllowedExit.count(I))
1534       //Check that all of the users of the loop are inside the BB.
1535       for (Value::use_iterator it = I->use_begin(), e = I->use_end();
1536            it != e; ++it) {
1537         Instruction *U = cast<Instruction>(*it);
1538         // This user may be a reduction exit value.
1539         BasicBlock *Parent = U->getParent();
1540         if (Parent != &BB) {
1541           DEBUG(dbgs() << "LV: Found an outside user for : "<< *U << "\n");
1542           return false;
1543         }
1544     }
1545   } // next instr.
1546
1547   if (!Induction) {
1548     DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
1549     assert(getInductionVars()->size() && "No induction variables");
1550   }
1551
1552   // Don't vectorize if the memory dependencies do not allow vectorization.
1553   if (!canVectorizeMemory(BB))
1554     return false;
1555
1556   // We now know that the loop is vectorizable!
1557   // Collect variables that will remain uniform after vectorization.
1558   std::vector<Value*> Worklist;
1559
1560   // Start with the conditional branch and walk up the block.
1561   Worklist.push_back(BB.getTerminator()->getOperand(0));
1562
1563   while (Worklist.size()) {
1564     Instruction *I = dyn_cast<Instruction>(Worklist.back());
1565     Worklist.pop_back();
1566
1567     // Look at instructions inside this block. Stop when reaching PHI nodes.
1568     if (!I || I->getParent() != &BB || isa<PHINode>(I))
1569       continue;
1570
1571     // This is a known uniform.
1572     Uniforms.insert(I);
1573
1574     // Insert all operands.
1575     for (int i=0, Op = I->getNumOperands(); i < Op; ++i) {
1576       Worklist.push_back(I->getOperand(i));
1577     }
1578   }
1579
1580   return true;
1581 }
1582
1583 bool LoopVectorizationLegality::canVectorizeMemory(BasicBlock &BB) {
1584   typedef SmallVector<Value*, 16> ValueVector;
1585   typedef SmallPtrSet<Value*, 16> ValueSet;
1586   // Holds the Load and Store *instructions*.
1587   ValueVector Loads;
1588   ValueVector Stores;
1589   PtrRtCheck.Pointers.clear();
1590   PtrRtCheck.Need = false;
1591
1592   // Scan the BB and collect legal loads and stores.
1593   for (BasicBlock::iterator it = BB.begin(), e = BB.end(); it != e; ++it) {
1594     Instruction *I = it;
1595
1596     // If this is a load, save it. If this instruction can read from memory
1597     // but is not a load, then we quit. Notice that we don't handle function
1598     // calls that read or write.
1599     if (I->mayReadFromMemory()) {
1600       LoadInst *Ld = dyn_cast<LoadInst>(I);
1601       if (!Ld) return false;
1602       if (!Ld->isSimple()) {
1603         DEBUG(dbgs() << "LV: Found a non-simple load.\n");
1604         return false;
1605       }
1606       Loads.push_back(Ld);
1607       continue;
1608     }
1609
1610     // Save store instructions. Abort if other instructions write to memory.
1611     if (I->mayWriteToMemory()) {
1612       StoreInst *St = dyn_cast<StoreInst>(I);
1613       if (!St) return false;
1614       if (!St->isSimple()) {
1615         DEBUG(dbgs() << "LV: Found a non-simple store.\n");
1616         return false;
1617       }
1618       Stores.push_back(St);
1619     }
1620   } // next instr.
1621
1622   // Now we have two lists that hold the loads and the stores.
1623   // Next, we find the pointers that they use.
1624
1625   // Check if we see any stores. If there are no stores, then we don't
1626   // care if the pointers are *restrict*.
1627   if (!Stores.size()) {
1628         DEBUG(dbgs() << "LV: Found a read-only loop!\n");
1629         return true;
1630   }
1631
1632   // Holds the read and read-write *pointers* that we find.
1633   ValueVector Reads;
1634   ValueVector ReadWrites;
1635
1636   // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
1637   // multiple times on the same object. If the ptr is accessed twice, once
1638   // for read and once for write, it will only appear once (on the write
1639   // list). This is okay, since we are going to check for conflicts between
1640   // writes and between reads and writes, but not between reads and reads.
1641   ValueSet Seen;
1642
1643   ValueVector::iterator I, IE;
1644   for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
1645     StoreInst *ST = dyn_cast<StoreInst>(*I);
1646     assert(ST && "Bad StoreInst");
1647     Value* Ptr = ST->getPointerOperand();
1648
1649     if (isUniform(Ptr)) {
1650       DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
1651       return false;
1652     }
1653
1654     // If we did *not* see this pointer before, insert it to
1655     // the read-write list. At this phase it is only a 'write' list.
1656     if (Seen.insert(Ptr))
1657       ReadWrites.push_back(Ptr);
1658   }
1659
1660   for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
1661     LoadInst *LD = dyn_cast<LoadInst>(*I);
1662     assert(LD && "Bad LoadInst");
1663     Value* Ptr = LD->getPointerOperand();
1664     // If we did *not* see this pointer before, insert it to the
1665     // read list. If we *did* see it before, then it is already in
1666     // the read-write list. This allows us to vectorize expressions
1667     // such as A[i] += x;  Because the address of A[i] is a read-write
1668     // pointer. This only works if the index of A[i] is consecutive.
1669     // If the address of i is unknown (for example A[B[i]]) then we may
1670     // read a few words, modify, and write a few words, and some of the
1671     // words may be written to the same address.
1672     if (Seen.insert(Ptr) || !isConsecutivePtr(Ptr))
1673       Reads.push_back(Ptr);
1674   }
1675
1676   // If we write (or read-write) to a single destination and there are no
1677   // other reads in this loop then is it safe to vectorize.
1678   if (ReadWrites.size() == 1 && Reads.size() == 0) {
1679     DEBUG(dbgs() << "LV: Found a write-only loop!\n");
1680     return true;
1681   }
1682
1683   // Find pointers with computable bounds. We are going to use this information
1684   // to place a runtime bound check.
1685   bool RT = true;
1686   for (I = ReadWrites.begin(), IE = ReadWrites.end(); I != IE; ++I)
1687     if (hasComputableBounds(*I)) {
1688       PtrRtCheck.insert(SE, TheLoop, *I);
1689       DEBUG(dbgs() << "LV: Found a runtime check ptr:" << **I <<"\n");
1690     } else {
1691       RT = false;
1692       break;
1693     }
1694   for (I = Reads.begin(), IE = Reads.end(); I != IE; ++I)
1695     if (hasComputableBounds(*I)) {
1696       PtrRtCheck.insert(SE, TheLoop, *I);
1697       DEBUG(dbgs() << "LV: Found a runtime check ptr:" << **I <<"\n");
1698     } else {
1699       RT = false;
1700       break;
1701     }
1702
1703   // Check that we did not collect too many pointers or found a
1704   // unsizeable pointer.
1705   if (!RT || PtrRtCheck.Pointers.size() > RuntimeMemoryCheckThreshold) {
1706     PtrRtCheck.reset();
1707     RT = false;
1708   }
1709
1710   PtrRtCheck.Need = RT;
1711
1712   if (RT) {
1713     DEBUG(dbgs() << "LV: We can perform a memory runtime check if needed.\n");
1714   }
1715
1716   // Now that the pointers are in two lists (Reads and ReadWrites), we
1717   // can check that there are no conflicts between each of the writes and
1718   // between the writes to the reads.
1719   ValueSet WriteObjects;
1720   ValueVector TempObjects;
1721
1722   // Check that the read-writes do not conflict with other read-write
1723   // pointers.
1724   for (I = ReadWrites.begin(), IE = ReadWrites.end(); I != IE; ++I) {
1725     GetUnderlyingObjects(*I, TempObjects, DL);
1726     for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end();
1727          it != e; ++it) {
1728       if (!isIdentifiedObject(*it)) {
1729         DEBUG(dbgs() << "LV: Found an unidentified write ptr:"<< **it <<"\n");
1730         return RT;
1731       }
1732       if (!WriteObjects.insert(*it)) {
1733         DEBUG(dbgs() << "LV: Found a possible write-write reorder:"
1734               << **it <<"\n");
1735         return RT;
1736       }
1737     }
1738     TempObjects.clear();
1739   }
1740
1741   /// Check that the reads don't conflict with the read-writes.
1742   for (I = Reads.begin(), IE = Reads.end(); I != IE; ++I) {
1743     GetUnderlyingObjects(*I, TempObjects, DL);
1744     for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end();
1745          it != e; ++it) {
1746       if (!isIdentifiedObject(*it)) {
1747         DEBUG(dbgs() << "LV: Found an unidentified read ptr:"<< **it <<"\n");
1748         return RT;
1749       }
1750       if (WriteObjects.count(*it)) {
1751         DEBUG(dbgs() << "LV: Found a possible read/write reorder:"
1752               << **it <<"\n");
1753         return RT;
1754       }
1755     }
1756     TempObjects.clear();
1757   }
1758
1759   // It is safe to vectorize and we don't need any runtime checks.
1760   DEBUG(dbgs() << "LV: We don't need a runtime memory check.\n");
1761   PtrRtCheck.reset();
1762   return true;
1763 }
1764
1765 bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi,
1766                                                 ReductionKind Kind) {
1767   if (Phi->getNumIncomingValues() != 2)
1768     return false;
1769
1770   // Find the possible incoming reduction variable.
1771   BasicBlock *BB = Phi->getParent();
1772   int SelfEdgeIdx = Phi->getBasicBlockIndex(BB);
1773   int InEdgeBlockIdx = (SelfEdgeIdx ? 0 : 1); // The other entry.
1774   Value *RdxStart = Phi->getIncomingValue(InEdgeBlockIdx);
1775
1776   // ExitInstruction is the single value which is used outside the loop.
1777   // We only allow for a single reduction value to be used outside the loop.
1778   // This includes users of the reduction, variables (which form a cycle
1779   // which ends in the phi node).
1780   Instruction *ExitInstruction = 0;
1781
1782   // Iter is our iterator. We start with the PHI node and scan for all of the
1783   // users of this instruction. All users must be instructions which can be
1784   // used as reduction variables (such as ADD). We may have a single
1785   // out-of-block user. They cycle must end with the original PHI.
1786   // Also, we can't have multiple block-local users.
1787   Instruction *Iter = Phi;
1788   while (true) {
1789     // Any reduction instr must be of one of the allowed kinds.
1790     if (!isReductionInstr(Iter, Kind))
1791       return false;
1792
1793     // Did we found a user inside this block ?
1794     bool FoundInBlockUser = false;
1795     // Did we reach the initial PHI node ?
1796     bool FoundStartPHI = false;
1797
1798     // If the instruction has no users then this is a broken
1799     // chain and can't be a reduction variable.
1800     if (Iter->use_empty())
1801       return false;
1802
1803     // For each of the *users* of iter.
1804     for (Value::use_iterator it = Iter->use_begin(), e = Iter->use_end();
1805          it != e; ++it) {
1806       Instruction *U = cast<Instruction>(*it);
1807       // We already know that the PHI is a user.
1808       if (U == Phi) {
1809         FoundStartPHI = true;
1810         continue;
1811       }
1812       // Check if we found the exit user.
1813       BasicBlock *Parent = U->getParent();
1814       if (Parent != BB) {
1815         // We must have a single exit instruction.
1816         if (ExitInstruction != 0)
1817           return false;
1818         ExitInstruction = Iter;
1819       }
1820       // We can't have multiple inside users.
1821       if (FoundInBlockUser)
1822         return false;
1823       FoundInBlockUser = true;
1824       Iter = U;
1825     }
1826
1827     // We found a reduction var if we have reached the original
1828     // phi node and we only have a single instruction with out-of-loop
1829     // users.
1830    if (FoundStartPHI && ExitInstruction) {
1831      // This instruction is allowed to have out-of-loop users.
1832      AllowedExit.insert(ExitInstruction);
1833
1834      // Save the description of this reduction variable.
1835      ReductionDescriptor RD(RdxStart, ExitInstruction, Kind);
1836      Reductions[Phi] = RD;
1837      return true;
1838    }
1839   }
1840 }
1841
1842 bool
1843 LoopVectorizationLegality::isReductionInstr(Instruction *I,
1844                                             ReductionKind Kind) {
1845     switch (I->getOpcode()) {
1846     default:
1847       return false;
1848     case Instruction::PHI:
1849       // possibly.
1850       return true;
1851     case Instruction::Add:
1852     case Instruction::Sub:
1853       return Kind == IntegerAdd;
1854     case Instruction::Mul:
1855       return Kind == IntegerMult;
1856     case Instruction::And:
1857       return Kind == IntegerAnd;
1858     case Instruction::Or:
1859       return Kind == IntegerOr;
1860     case Instruction::Xor:
1861       return Kind == IntegerXor;
1862     }
1863 }
1864
1865 bool LoopVectorizationLegality::isInductionVariable(PHINode *Phi) {
1866   Type *PhiTy = Phi->getType();
1867   // We only handle integer and pointer inductions variables.
1868   if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
1869     return false;
1870
1871   // Check that the PHI is consecutive and starts at zero.
1872   const SCEV *PhiScev = SE->getSCEV(Phi);
1873   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
1874   if (!AR) {
1875     DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
1876     return false;
1877   }
1878   const SCEV *Step = AR->getStepRecurrence(*SE);
1879
1880   // Integer inductions need to have a stride of one.
1881   if (PhiTy->isIntegerTy())
1882     return Step->isOne();
1883
1884   // Calculate the pointer stride and check if it is consecutive.
1885   const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
1886   if (!C) return false;
1887
1888   assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
1889   uint64_t Size = DL->getTypeAllocSize(PhiTy->getPointerElementType());
1890   return (C->getValue()->equalsInt(Size));
1891 }
1892
1893 bool LoopVectorizationLegality::hasComputableBounds(Value *Ptr) {
1894   const SCEV *PhiScev = SE->getSCEV(Ptr);
1895   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
1896   if (!AR)
1897     return false;
1898
1899   return AR->isAffine();
1900 }
1901
1902 unsigned
1903 LoopVectorizationCostModel::findBestVectorizationFactor(unsigned VF) {
1904   if (!VTTI) {
1905     DEBUG(dbgs() << "LV: No vector target information. Not vectorizing. \n");
1906     return 1;
1907   }
1908
1909   float Cost = expectedCost(1);
1910   unsigned Width = 1;
1911   DEBUG(dbgs() << "LV: Scalar loop costs: "<< (int)Cost << ".\n");
1912   for (unsigned i=2; i <= VF; i*=2) {
1913     // Notice that the vector loop needs to be executed less times, so
1914     // we need to divide the cost of the vector loops by the width of
1915     // the vector elements.
1916     float VectorCost = expectedCost(i) / (float)i;
1917     DEBUG(dbgs() << "LV: Vector loop of width "<< i << " costs: " <<
1918           (int)VectorCost << ".\n");
1919     if (VectorCost < Cost) {
1920       Cost = VectorCost;
1921       Width = i;
1922     }
1923   }
1924
1925   DEBUG(dbgs() << "LV: Selecting VF = : "<< Width << ".\n");
1926   return Width;
1927 }
1928
1929 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
1930   // We can only estimate the cost of single basic block loops.
1931   assert(1 == TheLoop->getNumBlocks() && "Too many blocks in loop");
1932
1933   BasicBlock *BB = TheLoop->getHeader();
1934   unsigned Cost = 0;
1935
1936   // For each instruction in the old loop.
1937   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1938     Instruction *Inst = it;
1939     unsigned C = getInstructionCost(Inst, VF);
1940     Cost += C;
1941     DEBUG(dbgs() << "LV: Found an estimated cost of "<< C <<" for VF "<< VF <<
1942           " For instruction: "<< *Inst << "\n");
1943   }
1944
1945   return Cost;
1946 }
1947
1948 unsigned
1949 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
1950   assert(VTTI && "Invalid vector target transformation info");
1951
1952   // If we know that this instruction will remain uniform, check the cost of
1953   // the scalar version.
1954   if (Legal->isUniformAfterVectorization(I))
1955     VF = 1;
1956
1957   Type *RetTy = I->getType();
1958   Type *VectorTy = ToVectorTy(RetTy, VF);
1959
1960
1961   // TODO: We need to estimate the cost of intrinsic calls.
1962   switch (I->getOpcode()) {
1963     case Instruction::GetElementPtr:
1964       // We mark this instruction as zero-cost because scalar GEPs are usually
1965       // lowered to the intruction addressing mode. At the moment we don't
1966       // generate vector geps.
1967       return 0;
1968     case Instruction::Br: {
1969       return VTTI->getCFInstrCost(I->getOpcode());
1970     }
1971     case Instruction::PHI:
1972       return 0;
1973     case Instruction::Add:
1974     case Instruction::FAdd:
1975     case Instruction::Sub:
1976     case Instruction::FSub:
1977     case Instruction::Mul:
1978     case Instruction::FMul:
1979     case Instruction::UDiv:
1980     case Instruction::SDiv:
1981     case Instruction::FDiv:
1982     case Instruction::URem:
1983     case Instruction::SRem:
1984     case Instruction::FRem:
1985     case Instruction::Shl:
1986     case Instruction::LShr:
1987     case Instruction::AShr:
1988     case Instruction::And:
1989     case Instruction::Or:
1990     case Instruction::Xor: {
1991       return VTTI->getArithmeticInstrCost(I->getOpcode(), VectorTy);
1992     }
1993     case Instruction::Select: {
1994       SelectInst *SI = cast<SelectInst>(I);
1995       const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
1996       bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
1997       Type *CondTy = SI->getCondition()->getType();
1998       if (ScalarCond)
1999         CondTy = VectorType::get(CondTy, VF);
2000
2001       return VTTI->getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
2002     }
2003     case Instruction::ICmp:
2004     case Instruction::FCmp: {
2005       Type *ValTy = I->getOperand(0)->getType();
2006       VectorTy = ToVectorTy(ValTy, VF);
2007       return VTTI->getCmpSelInstrCost(I->getOpcode(), VectorTy);
2008     }
2009     case Instruction::Store: {
2010       StoreInst *SI = cast<StoreInst>(I);
2011       Type *ValTy = SI->getValueOperand()->getType();
2012       VectorTy = ToVectorTy(ValTy, VF);
2013
2014       if (VF == 1)
2015         return VTTI->getMemoryOpCost(I->getOpcode(), ValTy,
2016                               SI->getAlignment(), SI->getPointerAddressSpace());
2017
2018       // Scalarized stores.
2019       if (!Legal->isConsecutivePtr(SI->getPointerOperand())) {
2020         unsigned Cost = 0;
2021         unsigned ExtCost = VTTI->getInstrCost(Instruction::ExtractElement,
2022                                               ValTy);
2023         // The cost of extracting from the value vector.
2024         Cost += VF * (ExtCost);
2025         // The cost of the scalar stores.
2026         Cost += VF * VTTI->getMemoryOpCost(I->getOpcode(),
2027                                            ValTy->getScalarType(),
2028                                            SI->getAlignment(),
2029                                            SI->getPointerAddressSpace());
2030         return Cost;
2031       }
2032
2033       // Wide stores.
2034       return VTTI->getMemoryOpCost(I->getOpcode(), VectorTy, SI->getAlignment(),
2035                                    SI->getPointerAddressSpace());
2036     }
2037     case Instruction::Load: {
2038       LoadInst *LI = cast<LoadInst>(I);
2039
2040       if (VF == 1)
2041         return VTTI->getMemoryOpCost(I->getOpcode(), RetTy,
2042                                      LI->getAlignment(),
2043                                      LI->getPointerAddressSpace());
2044
2045       // Scalarized loads.
2046       if (!Legal->isConsecutivePtr(LI->getPointerOperand())) {
2047         unsigned Cost = 0;
2048         unsigned InCost = VTTI->getInstrCost(Instruction::InsertElement, RetTy);
2049         // The cost of inserting the loaded value into the result vector.
2050         Cost += VF * (InCost);
2051         // The cost of the scalar stores.
2052         Cost += VF * VTTI->getMemoryOpCost(I->getOpcode(),
2053                                            RetTy->getScalarType(),
2054                                            LI->getAlignment(),
2055                                            LI->getPointerAddressSpace());
2056         return Cost;
2057       }
2058
2059       // Wide loads.
2060       return VTTI->getMemoryOpCost(I->getOpcode(), VectorTy, LI->getAlignment(),
2061                                    LI->getPointerAddressSpace());
2062     }
2063     case Instruction::ZExt:
2064     case Instruction::SExt:
2065     case Instruction::FPToUI:
2066     case Instruction::FPToSI:
2067     case Instruction::FPExt:
2068     case Instruction::PtrToInt:
2069     case Instruction::IntToPtr:
2070     case Instruction::SIToFP:
2071     case Instruction::UIToFP:
2072     case Instruction::Trunc:
2073     case Instruction::FPTrunc:
2074     case Instruction::BitCast: {
2075       Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
2076       return VTTI->getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
2077     }
2078     default: {
2079       // We are scalarizing the instruction. Return the cost of the scalar
2080       // instruction, plus the cost of insert and extract into vector
2081       // elements, times the vector width.
2082       unsigned Cost = 0;
2083
2084       bool IsVoid = RetTy->isVoidTy();
2085
2086       unsigned InsCost = (IsVoid ? 0 :
2087                           VTTI->getInstrCost(Instruction::InsertElement,
2088                                              VectorTy));
2089
2090       unsigned ExtCost = VTTI->getInstrCost(Instruction::ExtractElement,
2091                                             VectorTy);
2092
2093       // The cost of inserting the results plus extracting each one of the
2094       // operands.
2095       Cost += VF * (InsCost + ExtCost * I->getNumOperands());
2096
2097       // The cost of executing VF copies of the scalar instruction.
2098       Cost += VF * VTTI->getInstrCost(I->getOpcode(), RetTy);
2099       return Cost;
2100     }
2101   }// end of switch.
2102 }
2103
2104 Type* LoopVectorizationCostModel::ToVectorTy(Type *Scalar, unsigned VF) {
2105   if (Scalar->isVoidTy() || VF == 1)
2106     return Scalar;
2107   return VectorType::get(Scalar, VF);
2108 }
2109
2110 } // namespace
2111
2112 char LoopVectorize::ID = 0;
2113 static const char lv_name[] = "Loop Vectorization";
2114 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
2115 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
2116 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
2117 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
2118 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
2119
2120 namespace llvm {
2121   Pass *createLoopVectorizePass() {
2122     return new LoopVectorize();
2123   }
2124 }
2125