LoopVectorizer: Emit memory checks into their own basic block.
[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. InnerLoopVectorizer - 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
45 #define LV_NAME "loop-vectorize"
46 #define DEBUG_TYPE LV_NAME
47
48 #include "llvm/Transforms/Vectorize.h"
49 #include "llvm/ADT/DenseMap.h"
50 #include "llvm/ADT/MapVector.h"
51 #include "llvm/ADT/SmallPtrSet.h"
52 #include "llvm/ADT/SmallSet.h"
53 #include "llvm/ADT/SmallVector.h"
54 #include "llvm/ADT/StringExtras.h"
55 #include "llvm/Analysis/AliasAnalysis.h"
56 #include "llvm/Analysis/AliasSetTracker.h"
57 #include "llvm/Analysis/Dominators.h"
58 #include "llvm/Analysis/LoopInfo.h"
59 #include "llvm/Analysis/LoopIterator.h"
60 #include "llvm/Analysis/LoopPass.h"
61 #include "llvm/Analysis/ScalarEvolution.h"
62 #include "llvm/Analysis/ScalarEvolutionExpander.h"
63 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
64 #include "llvm/Analysis/TargetTransformInfo.h"
65 #include "llvm/Analysis/ValueTracking.h"
66 #include "llvm/Analysis/Verifier.h"
67 #include "llvm/IR/Constants.h"
68 #include "llvm/IR/DataLayout.h"
69 #include "llvm/IR/DerivedTypes.h"
70 #include "llvm/IR/Function.h"
71 #include "llvm/IR/IRBuilder.h"
72 #include "llvm/IR/Instructions.h"
73 #include "llvm/IR/IntrinsicInst.h"
74 #include "llvm/IR/LLVMContext.h"
75 #include "llvm/IR/Module.h"
76 #include "llvm/IR/Type.h"
77 #include "llvm/IR/Value.h"
78 #include "llvm/Pass.h"
79 #include "llvm/Support/CommandLine.h"
80 #include "llvm/Support/Debug.h"
81 #include "llvm/Support/raw_ostream.h"
82 #include "llvm/Transforms/Scalar.h"
83 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
84 #include "llvm/Transforms/Utils/Local.h"
85 #include <algorithm>
86 #include <map>
87
88 using namespace llvm;
89
90 static cl::opt<unsigned>
91 VectorizationFactor("force-vector-width", cl::init(0), cl::Hidden,
92                     cl::desc("Sets the SIMD width. Zero is autoselect."));
93
94 static cl::opt<unsigned>
95 VectorizationUnroll("force-vector-unroll", cl::init(0), cl::Hidden,
96                     cl::desc("Sets the vectorization unroll count. "
97                              "Zero is autoselect."));
98
99 static cl::opt<bool>
100 EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
101                    cl::desc("Enable if-conversion during vectorization."));
102
103 /// We don't vectorize loops with a known constant trip count below this number.
104 static const unsigned TinyTripCountVectorThreshold = 16;
105
106 /// We don't unroll loops with a known constant trip count below this number.
107 static const unsigned TinyTripCountUnrollThreshold = 128;
108
109 /// We don't unroll loops that are larget than this threshold.
110 static const unsigned MaxLoopSizeThreshold = 32;
111
112 /// When performing a runtime memory check, do not check more than this
113 /// number of pointers. Notice that the check is quadratic!
114 static const unsigned RuntimeMemoryCheckThreshold = 4;
115
116 namespace {
117
118 // Forward declarations.
119 class LoopVectorizationLegality;
120 class LoopVectorizationCostModel;
121
122 /// InnerLoopVectorizer vectorizes loops which contain only one basic
123 /// block to a specified vectorization factor (VF).
124 /// This class performs the widening of scalars into vectors, or multiple
125 /// scalars. This class also implements the following features:
126 /// * It inserts an epilogue loop for handling loops that don't have iteration
127 ///   counts that are known to be a multiple of the vectorization factor.
128 /// * It handles the code generation for reduction variables.
129 /// * Scalarization (implementation using scalars) of un-vectorizable
130 ///   instructions.
131 /// InnerLoopVectorizer does not perform any vectorization-legality
132 /// checks, and relies on the caller to check for the different legality
133 /// aspects. The InnerLoopVectorizer relies on the
134 /// LoopVectorizationLegality class to provide information about the induction
135 /// and reduction variables that were found to a given vectorization factor.
136 class InnerLoopVectorizer {
137 public:
138   InnerLoopVectorizer(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
139                       DominatorTree *DT, DataLayout *DL, unsigned VecWidth,
140                       unsigned UnrollFactor)
141       : OrigLoop(OrigLoop), SE(SE), LI(LI), DT(DT), DL(DL), VF(VecWidth),
142         UF(UnrollFactor), Builder(SE->getContext()), Induction(0),
143         OldInduction(0), WidenMap(UnrollFactor) {}
144
145   // Perform the actual loop widening (vectorization).
146   void vectorize(LoopVectorizationLegality *Legal) {
147     // Create a new empty loop. Unlink the old loop and connect the new one.
148     createEmptyLoop(Legal);
149     // Widen each instruction in the old loop to a new one in the new loop.
150     // Use the Legality module to find the induction and reduction variables.
151     vectorizeLoop(Legal);
152     // Register the new loop and update the analysis passes.
153     updateAnalysis();
154   }
155
156 private:
157   /// A small list of PHINodes.
158   typedef SmallVector<PHINode*, 4> PhiVector;
159   /// When we unroll loops we have multiple vector values for each scalar.
160   /// This data structure holds the unrolled and vectorized values that
161   /// originated from one scalar instruction.
162   typedef SmallVector<Value*, 2> VectorParts;
163
164   /// Add code that checks at runtime if the accessed arrays overlap.
165   /// Returns the comparator value or NULL if no check is needed.
166   Instruction *addRuntimeCheck(LoopVectorizationLegality *Legal,
167                                Instruction *Loc);
168   /// Create an empty loop, based on the loop ranges of the old loop.
169   void createEmptyLoop(LoopVectorizationLegality *Legal);
170   /// Copy and widen the instructions from the old loop.
171   void vectorizeLoop(LoopVectorizationLegality *Legal);
172
173   /// A helper function that computes the predicate of the block BB, assuming
174   /// that the header block of the loop is set to True. It returns the *entry*
175   /// mask for the block BB.
176   VectorParts createBlockInMask(BasicBlock *BB);
177   /// A helper function that computes the predicate of the edge between SRC
178   /// and DST.
179   VectorParts createEdgeMask(BasicBlock *Src, BasicBlock *Dst);
180
181   /// A helper function to vectorize a single BB within the innermost loop.
182   void vectorizeBlockInLoop(LoopVectorizationLegality *Legal, BasicBlock *BB,
183                             PhiVector *PV);
184
185   /// Insert the new loop to the loop hierarchy and pass manager
186   /// and update the analysis passes.
187   void updateAnalysis();
188
189   /// This instruction is un-vectorizable. Implement it as a sequence
190   /// of scalars.
191   void scalarizeInstruction(Instruction *Instr);
192
193   /// Create a broadcast instruction. This method generates a broadcast
194   /// instruction (shuffle) for loop invariant values and for the induction
195   /// value. If this is the induction variable then we extend it to N, N+1, ...
196   /// this is needed because each iteration in the loop corresponds to a SIMD
197   /// element.
198   Value *getBroadcastInstrs(Value *V);
199
200   /// This function adds 0, 1, 2 ... to each vector element, starting at zero.
201   /// If Negate is set then negative numbers are added e.g. (0, -1, -2, ...).
202   /// The sequence starts at StartIndex.
203   Value *getConsecutiveVector(Value* Val, unsigned StartIdx, bool Negate);
204
205   /// When we go over instructions in the basic block we rely on previous
206   /// values within the current basic block or on loop invariant values.
207   /// When we widen (vectorize) values we place them in the map. If the values
208   /// are not within the map, they have to be loop invariant, so we simply
209   /// broadcast them into a vector.
210   VectorParts &getVectorValue(Value *V);
211
212   /// Generate a shuffle sequence that will reverse the vector Vec.
213   Value *reverseVector(Value *Vec);
214
215   /// This is a helper class that holds the vectorizer state. It maps scalar
216   /// instructions to vector instructions. When the code is 'unrolled' then
217   /// then a single scalar value is mapped to multiple vector parts. The parts
218   /// are stored in the VectorPart type.
219   struct ValueMap {
220     /// C'tor.  UnrollFactor controls the number of vectors ('parts') that
221     /// are mapped.
222     ValueMap(unsigned UnrollFactor) : UF(UnrollFactor) {}
223
224     /// \return True if 'Key' is saved in the Value Map.
225     bool has(Value *Key) { return MapStoreage.count(Key); }
226
227     /// Initializes a new entry in the map. Sets all of the vector parts to the
228     /// save value in 'Val'.
229     /// \return A reference to a vector with splat values.
230     VectorParts &splat(Value *Key, Value *Val) {
231       MapStoreage[Key].clear();
232       MapStoreage[Key].append(UF, Val);
233       return MapStoreage[Key];
234     }
235
236     ///\return A reference to the value that is stored at 'Key'.
237     VectorParts &get(Value *Key) {
238       if (!has(Key))
239         MapStoreage[Key].resize(UF);
240       return MapStoreage[Key];
241     }
242
243     /// The unroll factor. Each entry in the map stores this number of vector
244     /// elements.
245     unsigned UF;
246
247     /// Map storage. We use std::map and not DenseMap because insertions to a
248     /// dense map invalidates its iterators.
249     std::map<Value*, VectorParts> MapStoreage;
250   };
251
252   /// The original loop.
253   Loop *OrigLoop;
254   /// Scev analysis to use.
255   ScalarEvolution *SE;
256   /// Loop Info.
257   LoopInfo *LI;
258   /// Dominator Tree.
259   DominatorTree *DT;
260   /// Data Layout.
261   DataLayout *DL;
262   /// The vectorization SIMD factor to use. Each vector will have this many
263   /// vector elements.
264   unsigned VF;
265   /// The vectorization unroll factor to use. Each scalar is vectorized to this
266   /// many different vector instructions.
267   unsigned UF;
268
269   /// The builder that we use
270   IRBuilder<> Builder;
271
272   // --- Vectorization state ---
273
274   /// The vector-loop preheader.
275   BasicBlock *LoopVectorPreHeader;
276   /// The scalar-loop preheader.
277   BasicBlock *LoopScalarPreHeader;
278   /// Middle Block between the vector and the scalar.
279   BasicBlock *LoopMiddleBlock;
280   ///The ExitBlock of the scalar loop.
281   BasicBlock *LoopExitBlock;
282   ///The vector loop body.
283   BasicBlock *LoopVectorBody;
284   ///The scalar loop body.
285   BasicBlock *LoopScalarBody;
286   /// A list of all bypass blocks. The first block is the entry of the loop.
287   SmallVector<BasicBlock *, 4> LoopBypassBlocks;
288
289   /// The new Induction variable which was added to the new block.
290   PHINode *Induction;
291   /// The induction variable of the old basic block.
292   PHINode *OldInduction;
293   /// Maps scalars to widened vectors.
294   ValueMap WidenMap;
295 };
296
297 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
298 /// to what vectorization factor.
299 /// This class does not look at the profitability of vectorization, only the
300 /// legality. This class has two main kinds of checks:
301 /// * Memory checks - The code in canVectorizeMemory checks if vectorization
302 ///   will change the order of memory accesses in a way that will change the
303 ///   correctness of the program.
304 /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
305 /// checks for a number of different conditions, such as the availability of a
306 /// single induction variable, that all types are supported and vectorize-able,
307 /// etc. This code reflects the capabilities of InnerLoopVectorizer.
308 /// This class is also used by InnerLoopVectorizer for identifying
309 /// induction variable and the different reduction variables.
310 class LoopVectorizationLegality {
311 public:
312   LoopVectorizationLegality(Loop *L, ScalarEvolution *SE, DataLayout *DL,
313                             DominatorTree *DT)
314       : TheLoop(L), SE(SE), DL(DL), DT(DT), Induction(0) {}
315
316   /// This enum represents the kinds of reductions that we support.
317   enum ReductionKind {
318     RK_NoReduction, ///< Not a reduction.
319     RK_IntegerAdd,  ///< Sum of integers.
320     RK_IntegerMult, ///< Product of integers.
321     RK_IntegerOr,   ///< Bitwise or logical OR of numbers.
322     RK_IntegerAnd,  ///< Bitwise or logical AND of numbers.
323     RK_IntegerXor,  ///< Bitwise or logical XOR of numbers.
324     RK_FloatAdd,    ///< Sum of floats.
325     RK_FloatMult    ///< Product of floats.
326   };
327
328   /// This enum represents the kinds of inductions that we support.
329   enum InductionKind {
330     IK_NoInduction,         ///< Not an induction variable.
331     IK_IntInduction,        ///< Integer induction variable. Step = 1.
332     IK_ReverseIntInduction, ///< Reverse int induction variable. Step = -1.
333     IK_PtrInduction         ///< Pointer induction variable. Step = sizeof(elem).
334   };
335
336   /// This POD struct holds information about reduction variables.
337   struct ReductionDescriptor {
338     ReductionDescriptor() : StartValue(0), LoopExitInstr(0),
339       Kind(RK_NoReduction) {}
340
341     ReductionDescriptor(Value *Start, Instruction *Exit, ReductionKind K)
342         : StartValue(Start), LoopExitInstr(Exit), Kind(K) {}
343
344     // The starting value of the reduction.
345     // It does not have to be zero!
346     Value *StartValue;
347     // The instruction who's value is used outside the loop.
348     Instruction *LoopExitInstr;
349     // The kind of the reduction.
350     ReductionKind Kind;
351   };
352
353   // This POD struct holds information about the memory runtime legality
354   // check that a group of pointers do not overlap.
355   struct RuntimePointerCheck {
356     RuntimePointerCheck() : Need(false) {}
357
358     /// Reset the state of the pointer runtime information.
359     void reset() {
360       Need = false;
361       Pointers.clear();
362       Starts.clear();
363       Ends.clear();
364     }
365
366     /// Insert a pointer and calculate the start and end SCEVs.
367     void insert(ScalarEvolution *SE, Loop *Lp, Value *Ptr);
368
369     /// This flag indicates if we need to add the runtime check.
370     bool Need;
371     /// Holds the pointers that we need to check.
372     SmallVector<Value*, 2> Pointers;
373     /// Holds the pointer value at the beginning of the loop.
374     SmallVector<const SCEV*, 2> Starts;
375     /// Holds the pointer value at the end of the loop.
376     SmallVector<const SCEV*, 2> Ends;
377   };
378
379   /// A POD for saving information about induction variables.
380   struct InductionInfo {
381     InductionInfo(Value *Start, InductionKind K) : StartValue(Start), IK(K) {}
382     InductionInfo() : StartValue(0), IK(IK_NoInduction) {}
383     /// Start value.
384     Value *StartValue;
385     /// Induction kind.
386     InductionKind IK;
387   };
388
389   /// ReductionList contains the reduction descriptors for all
390   /// of the reductions that were found in the loop.
391   typedef DenseMap<PHINode*, ReductionDescriptor> ReductionList;
392
393   /// InductionList saves induction variables and maps them to the
394   /// induction descriptor.
395   typedef MapVector<PHINode*, InductionInfo> InductionList;
396
397   /// Returns true if it is legal to vectorize this loop.
398   /// This does not mean that it is profitable to vectorize this
399   /// loop, only that it is legal to do so.
400   bool canVectorize();
401
402   /// Returns the Induction variable.
403   PHINode *getInduction() { return Induction; }
404
405   /// Returns the reduction variables found in the loop.
406   ReductionList *getReductionVars() { return &Reductions; }
407
408   /// Returns the induction variables found in the loop.
409   InductionList *getInductionVars() { return &Inductions; }
410
411   /// Returns True if V is an induction variable in this loop.
412   bool isInductionVariable(const Value *V);
413
414   /// Return true if the block BB needs to be predicated in order for the loop
415   /// to be vectorized.
416   bool blockNeedsPredication(BasicBlock *BB);
417
418   /// Check if this  pointer is consecutive when vectorizing. This happens
419   /// when the last index of the GEP is the induction variable, or that the
420   /// pointer itself is an induction variable.
421   /// This check allows us to vectorize A[idx] into a wide load/store.
422   /// Returns:
423   /// 0 - Stride is unknown or non consecutive.
424   /// 1 - Address is consecutive.
425   /// -1 - Address is consecutive, and decreasing.
426   int isConsecutivePtr(Value *Ptr);
427
428   /// Returns true if the value V is uniform within the loop.
429   bool isUniform(Value *V);
430
431   /// Returns true if this instruction will remain scalar after vectorization.
432   bool isUniformAfterVectorization(Instruction* I) { return Uniforms.count(I); }
433
434   /// Returns the information that we collected about runtime memory check.
435   RuntimePointerCheck *getRuntimePointerCheck() { return &PtrRtCheck; }
436 private:
437   /// Check if a single basic block loop is vectorizable.
438   /// At this point we know that this is a loop with a constant trip count
439   /// and we only need to check individual instructions.
440   bool canVectorizeInstrs();
441
442   /// When we vectorize loops we may change the order in which
443   /// we read and write from memory. This method checks if it is
444   /// legal to vectorize the code, considering only memory constrains.
445   /// Returns true if the loop is vectorizable
446   bool canVectorizeMemory();
447
448   /// Return true if we can vectorize this loop using the IF-conversion
449   /// transformation.
450   bool canVectorizeWithIfConvert();
451
452   /// Collect the variables that need to stay uniform after vectorization.
453   void collectLoopUniforms();
454
455   /// Return true if all of the instructions in the block can be speculatively
456   /// executed.
457   bool blockCanBePredicated(BasicBlock *BB);
458
459   /// Returns True, if 'Phi' is the kind of reduction variable for type
460   /// 'Kind'. If this is a reduction variable, it adds it to ReductionList.
461   bool AddReductionVar(PHINode *Phi, ReductionKind Kind);
462   /// Returns true if the instruction I can be a reduction variable of type
463   /// 'Kind'.
464   bool isReductionInstr(Instruction *I, ReductionKind Kind);
465   /// Returns the induction kind of Phi. This function may return NoInduction
466   /// if the PHI is not an induction variable.
467   InductionKind isInductionVariable(PHINode *Phi);
468   /// Return true if can compute the address bounds of Ptr within the loop.
469   bool hasComputableBounds(Value *Ptr);
470
471   /// The loop that we evaluate.
472   Loop *TheLoop;
473   /// Scev analysis.
474   ScalarEvolution *SE;
475   /// DataLayout analysis.
476   DataLayout *DL;
477   // Dominators.
478   DominatorTree *DT;
479
480   //  ---  vectorization state --- //
481
482   /// Holds the integer induction variable. This is the counter of the
483   /// loop.
484   PHINode *Induction;
485   /// Holds the reduction variables.
486   ReductionList Reductions;
487   /// Holds all of the induction variables that we found in the loop.
488   /// Notice that inductions don't need to start at zero and that induction
489   /// variables can be pointers.
490   InductionList Inductions;
491
492   /// Allowed outside users. This holds the reduction
493   /// vars which can be accessed from outside the loop.
494   SmallPtrSet<Value*, 4> AllowedExit;
495   /// This set holds the variables which are known to be uniform after
496   /// vectorization.
497   SmallPtrSet<Instruction*, 4> Uniforms;
498   /// We need to check that all of the pointers in this list are disjoint
499   /// at runtime.
500   RuntimePointerCheck PtrRtCheck;
501 };
502
503 /// LoopVectorizationCostModel - estimates the expected speedups due to
504 /// vectorization.
505 /// In many cases vectorization is not profitable. This can happen because of
506 /// a number of reasons. In this class we mainly attempt to predict the
507 /// expected speedup/slowdowns due to the supported instruction set. We use the
508 /// TargetTransformInfo to query the different backends for the cost of
509 /// different operations.
510 class LoopVectorizationCostModel {
511 public:
512   LoopVectorizationCostModel(Loop *L, ScalarEvolution *SE, LoopInfo *LI,
513                              LoopVectorizationLegality *Legal,
514                              const TargetTransformInfo &TTI)
515       : TheLoop(L), SE(SE), LI(LI), Legal(Legal), TTI(TTI) {}
516
517   /// \return The most profitable vectorization factor.
518   /// This method checks every power of two up to VF. If UserVF is not ZERO
519   /// then this vectorization factor will be selected if vectorization is
520   /// possible.
521   unsigned selectVectorizationFactor(bool OptForSize, unsigned UserVF);
522
523   /// \returns The size (in bits) of the widest type in the code that
524   /// needs to be vectorized. We ignore values that remain scalar such as
525   /// 64 bit loop indices.
526   unsigned getWidestType();
527
528   /// \return The most profitable unroll factor.
529   /// If UserUF is non-zero then this method finds the best unroll-factor
530   /// based on register pressure and other parameters.
531   unsigned selectUnrollFactor(bool OptForSize, unsigned UserUF);
532
533   /// \brief A struct that represents some properties of the register usage
534   /// of a loop.
535   struct RegisterUsage {
536     /// Holds the number of loop invariant values that are used in the loop.
537     unsigned LoopInvariantRegs;
538     /// Holds the maximum number of concurrent live intervals in the loop.
539     unsigned MaxLocalUsers;
540     /// Holds the number of instructions in the loop.
541     unsigned NumInstructions;
542   };
543
544   /// \return  information about the register usage of the loop.
545   RegisterUsage calculateRegisterUsage();
546
547 private:
548   /// Returns the expected execution cost. The unit of the cost does
549   /// not matter because we use the 'cost' units to compare different
550   /// vector widths. The cost that is returned is *not* normalized by
551   /// the factor width.
552   unsigned expectedCost(unsigned VF);
553
554   /// Returns the execution time cost of an instruction for a given vector
555   /// width. Vector width of one means scalar.
556   unsigned getInstructionCost(Instruction *I, unsigned VF);
557
558   /// A helper function for converting Scalar types to vector types.
559   /// If the incoming type is void, we return void. If the VF is 1, we return
560   /// the scalar type.
561   static Type* ToVectorTy(Type *Scalar, unsigned VF);
562
563   /// The loop that we evaluate.
564   Loop *TheLoop;
565   /// Scev analysis.
566   ScalarEvolution *SE;
567   /// Loop Info analysis.
568   LoopInfo *LI;
569   /// Vectorization legality.
570   LoopVectorizationLegality *Legal;
571   /// Vector target information.
572   const TargetTransformInfo &TTI;
573 };
574
575 /// The LoopVectorize Pass.
576 struct LoopVectorize : public LoopPass {
577   /// Pass identification, replacement for typeid
578   static char ID;
579
580   explicit LoopVectorize() : LoopPass(ID) {
581     initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
582   }
583
584   ScalarEvolution *SE;
585   DataLayout *DL;
586   LoopInfo *LI;
587   TargetTransformInfo *TTI;
588   DominatorTree *DT;
589
590   virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
591     // We only vectorize innermost loops.
592     if (!L->empty())
593       return false;
594
595     SE = &getAnalysis<ScalarEvolution>();
596     DL = getAnalysisIfAvailable<DataLayout>();
597     LI = &getAnalysis<LoopInfo>();
598     TTI = &getAnalysis<TargetTransformInfo>();
599     DT = &getAnalysis<DominatorTree>();
600
601     DEBUG(dbgs() << "LV: Checking a loop in \"" <<
602           L->getHeader()->getParent()->getName() << "\"\n");
603
604     // Check if it is legal to vectorize the loop.
605     LoopVectorizationLegality LVL(L, SE, DL, DT);
606     if (!LVL.canVectorize()) {
607       DEBUG(dbgs() << "LV: Not vectorizing.\n");
608       return false;
609     }
610
611     // Use the cost model.
612     LoopVectorizationCostModel CM(L, SE, LI, &LVL, *TTI);
613
614     // Check the function attribues to find out if this function should be
615     // optimized for size.
616     Function *F = L->getHeader()->getParent();
617     Attribute::AttrKind SzAttr = Attribute::OptimizeForSize;
618     Attribute::AttrKind FlAttr = Attribute::NoImplicitFloat;
619     unsigned FnIndex = AttributeSet::FunctionIndex;
620     bool OptForSize = F->getAttributes().hasAttribute(FnIndex, SzAttr);
621     bool NoFloat = F->getAttributes().hasAttribute(FnIndex, FlAttr);
622
623     if (NoFloat) {
624       DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
625             "attribute is used.\n");
626       return false;
627     }
628
629     unsigned VF = CM.selectVectorizationFactor(OptForSize, VectorizationFactor);
630     unsigned UF = CM.selectUnrollFactor(OptForSize, VectorizationUnroll);
631
632     if (VF == 1) {
633       DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
634       return false;
635     }
636
637     DEBUG(dbgs() << "LV: Found a vectorizable loop ("<< VF << ") in "<<
638           F->getParent()->getModuleIdentifier()<<"\n");
639     DEBUG(dbgs() << "LV: Unroll Factor is " << UF << "\n");
640
641     // If we decided that it is *legal* to vectorizer the loop then do it.
642     InnerLoopVectorizer LB(L, SE, LI, DT, DL, VF, UF);
643     LB.vectorize(&LVL);
644
645     DEBUG(verifyFunction(*L->getHeader()->getParent()));
646     return true;
647   }
648
649   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
650     LoopPass::getAnalysisUsage(AU);
651     AU.addRequiredID(LoopSimplifyID);
652     AU.addRequiredID(LCSSAID);
653     AU.addRequired<DominatorTree>();
654     AU.addRequired<LoopInfo>();
655     AU.addRequired<ScalarEvolution>();
656     AU.addRequired<TargetTransformInfo>();
657     AU.addPreserved<LoopInfo>();
658     AU.addPreserved<DominatorTree>();
659   }
660
661 };
662
663 } // end anonymous namespace
664
665 //===----------------------------------------------------------------------===//
666 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
667 // LoopVectorizationCostModel.
668 //===----------------------------------------------------------------------===//
669
670 void
671 LoopVectorizationLegality::RuntimePointerCheck::insert(ScalarEvolution *SE,
672                                                        Loop *Lp, Value *Ptr) {
673   const SCEV *Sc = SE->getSCEV(Ptr);
674   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
675   assert(AR && "Invalid addrec expression");
676   const SCEV *Ex = SE->getExitCount(Lp, Lp->getLoopLatch());
677   const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
678   Pointers.push_back(Ptr);
679   Starts.push_back(AR->getStart());
680   Ends.push_back(ScEnd);
681 }
682
683 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
684   // Save the current insertion location.
685   Instruction *Loc = Builder.GetInsertPoint();
686
687   // We need to place the broadcast of invariant variables outside the loop.
688   Instruction *Instr = dyn_cast<Instruction>(V);
689   bool NewInstr = (Instr && Instr->getParent() == LoopVectorBody);
690   bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
691
692   // Place the code for broadcasting invariant variables in the new preheader.
693   if (Invariant)
694     Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
695
696   // Broadcast the scalar into all locations in the vector.
697   Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
698
699   // Restore the builder insertion point.
700   if (Invariant)
701     Builder.SetInsertPoint(Loc);
702
703   return Shuf;
704 }
705
706 Value *InnerLoopVectorizer::getConsecutiveVector(Value* Val, unsigned StartIdx,
707                                                  bool Negate) {
708   assert(Val->getType()->isVectorTy() && "Must be a vector");
709   assert(Val->getType()->getScalarType()->isIntegerTy() &&
710          "Elem must be an integer");
711   // Create the types.
712   Type *ITy = Val->getType()->getScalarType();
713   VectorType *Ty = cast<VectorType>(Val->getType());
714   int VLen = Ty->getNumElements();
715   SmallVector<Constant*, 8> Indices;
716
717   // Create a vector of consecutive numbers from zero to VF.
718   for (int i = 0; i < VLen; ++i) {
719     int Idx = Negate ? (-i): i;
720     Indices.push_back(ConstantInt::get(ITy, StartIdx + Idx));
721   }
722
723   // Add the consecutive indices to the vector value.
724   Constant *Cv = ConstantVector::get(Indices);
725   assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
726   return Builder.CreateAdd(Val, Cv, "induction");
727 }
728
729 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
730   assert(Ptr->getType()->isPointerTy() && "Unexpected non ptr");
731
732   // If this value is a pointer induction variable we know it is consecutive.
733   PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
734   if (Phi && Inductions.count(Phi)) {
735     InductionInfo II = Inductions[Phi];
736     if (IK_PtrInduction == II.IK)
737       return 1;
738   }
739
740   GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
741   if (!Gep)
742     return 0;
743
744   unsigned NumOperands = Gep->getNumOperands();
745   Value *LastIndex = Gep->getOperand(NumOperands - 1);
746
747   // Check that all of the gep indices are uniform except for the last.
748   for (unsigned i = 0; i < NumOperands - 1; ++i)
749     if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
750       return 0;
751
752   // We can emit wide load/stores only if the last index is the induction
753   // variable.
754   const SCEV *Last = SE->getSCEV(LastIndex);
755   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
756     const SCEV *Step = AR->getStepRecurrence(*SE);
757
758     // The memory is consecutive because the last index is consecutive
759     // and all other indices are loop invariant.
760     if (Step->isOne())
761       return 1;
762     if (Step->isAllOnesValue())
763       return -1;
764   }
765
766   return 0;
767 }
768
769 bool LoopVectorizationLegality::isUniform(Value *V) {
770   return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
771 }
772
773 InnerLoopVectorizer::VectorParts&
774 InnerLoopVectorizer::getVectorValue(Value *V) {
775   assert(V != Induction && "The new induction variable should not be used.");
776   assert(!V->getType()->isVectorTy() && "Can't widen a vector");
777
778   // If we have this scalar in the map, return it.
779   if (WidenMap.has(V))
780     return WidenMap.get(V);
781
782   // If this scalar is unknown, assume that it is a constant or that it is
783   // loop invariant. Broadcast V and save the value for future uses.
784   Value *B = getBroadcastInstrs(V);
785   WidenMap.splat(V, B);
786   return WidenMap.get(V);
787 }
788
789 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
790   assert(Vec->getType()->isVectorTy() && "Invalid type");
791   SmallVector<Constant*, 8> ShuffleMask;
792   for (unsigned i = 0; i < VF; ++i)
793     ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
794
795   return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
796                                      ConstantVector::get(ShuffleMask),
797                                      "reverse");
798 }
799
800 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr) {
801   assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
802   // Holds vector parameters or scalars, in case of uniform vals.
803   SmallVector<VectorParts, 4> Params;
804
805   // Find all of the vectorized parameters.
806   for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
807     Value *SrcOp = Instr->getOperand(op);
808
809     // If we are accessing the old induction variable, use the new one.
810     if (SrcOp == OldInduction) {
811       Params.push_back(getVectorValue(SrcOp));
812       continue;
813     }
814
815     // Try using previously calculated values.
816     Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
817
818     // If the src is an instruction that appeared earlier in the basic block
819     // then it should already be vectorized.
820     if (SrcInst && OrigLoop->contains(SrcInst)) {
821       assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
822       // The parameter is a vector value from earlier.
823       Params.push_back(WidenMap.get(SrcInst));
824     } else {
825       // The parameter is a scalar from outside the loop. Maybe even a constant.
826       VectorParts Scalars;
827       Scalars.append(UF, SrcOp);
828       Params.push_back(Scalars);
829     }
830   }
831
832   assert(Params.size() == Instr->getNumOperands() &&
833          "Invalid number of operands");
834
835   // Does this instruction return a value ?
836   bool IsVoidRetTy = Instr->getType()->isVoidTy();
837
838   Value *UndefVec = IsVoidRetTy ? 0 :
839     UndefValue::get(VectorType::get(Instr->getType(), VF));
840   // Create a new entry in the WidenMap and initialize it to Undef or Null.
841   VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
842
843   // For each scalar that we create:
844   for (unsigned Width = 0; Width < VF; ++Width) {
845     // For each vector unroll 'part':
846     for (unsigned Part = 0; Part < UF; ++Part) {
847       Instruction *Cloned = Instr->clone();
848       if (!IsVoidRetTy)
849         Cloned->setName(Instr->getName() + ".cloned");
850       // Replace the operands of the cloned instrucions with extracted scalars.
851       for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
852         Value *Op = Params[op][Part];
853         // Param is a vector. Need to extract the right lane.
854         if (Op->getType()->isVectorTy())
855           Op = Builder.CreateExtractElement(Op, Builder.getInt32(Width));
856         Cloned->setOperand(op, Op);
857       }
858
859       // Place the cloned scalar in the new loop.
860       Builder.Insert(Cloned);
861
862       // If the original scalar returns a value we need to place it in a vector
863       // so that future users will be able to use it.
864       if (!IsVoidRetTy)
865         VecResults[Part] = Builder.CreateInsertElement(VecResults[Part], Cloned,
866                                                        Builder.getInt32(Width));
867     }
868   }
869 }
870
871 Instruction *
872 InnerLoopVectorizer::addRuntimeCheck(LoopVectorizationLegality *Legal,
873                                      Instruction *Loc) {
874   LoopVectorizationLegality::RuntimePointerCheck *PtrRtCheck =
875   Legal->getRuntimePointerCheck();
876
877   if (!PtrRtCheck->Need)
878     return NULL;
879
880   Instruction *MemoryRuntimeCheck = 0;
881   unsigned NumPointers = PtrRtCheck->Pointers.size();
882   SmallVector<Value* , 2> Starts;
883   SmallVector<Value* , 2> Ends;
884
885   SCEVExpander Exp(*SE, "induction");
886
887   // Use this type for pointer arithmetic.
888   Type* PtrArithTy = Type::getInt8PtrTy(Loc->getContext(), 0);
889
890   for (unsigned i = 0; i < NumPointers; ++i) {
891     Value *Ptr = PtrRtCheck->Pointers[i];
892     const SCEV *Sc = SE->getSCEV(Ptr);
893
894     if (SE->isLoopInvariant(Sc, OrigLoop)) {
895       DEBUG(dbgs() << "LV: Adding RT check for a loop invariant ptr:" <<
896             *Ptr <<"\n");
897       Starts.push_back(Ptr);
898       Ends.push_back(Ptr);
899     } else {
900       DEBUG(dbgs() << "LV: Adding RT check for range:" << *Ptr <<"\n");
901
902       Value *Start = Exp.expandCodeFor(PtrRtCheck->Starts[i], PtrArithTy, Loc);
903       Value *End = Exp.expandCodeFor(PtrRtCheck->Ends[i], PtrArithTy, Loc);
904       Starts.push_back(Start);
905       Ends.push_back(End);
906     }
907   }
908
909   for (unsigned i = 0; i < NumPointers; ++i) {
910     for (unsigned j = i+1; j < NumPointers; ++j) {
911       Instruction::CastOps Op = Instruction::BitCast;
912       Value *Start0 = CastInst::Create(Op, Starts[i], PtrArithTy, "bc", Loc);
913       Value *Start1 = CastInst::Create(Op, Starts[j], PtrArithTy, "bc", Loc);
914       Value *End0 =   CastInst::Create(Op, Ends[i],   PtrArithTy, "bc", Loc);
915       Value *End1 =   CastInst::Create(Op, Ends[j],   PtrArithTy, "bc", Loc);
916
917       Value *Cmp0 = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_ULE,
918                                     Start0, End1, "bound0", Loc);
919       Value *Cmp1 = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_ULE,
920                                     Start1, End0, "bound1", Loc);
921       Instruction *IsConflict = BinaryOperator::Create(Instruction::And, Cmp0,
922                                                        Cmp1, "found.conflict",
923                                                        Loc);
924       if (MemoryRuntimeCheck)
925         MemoryRuntimeCheck = BinaryOperator::Create(Instruction::Or,
926                                                     MemoryRuntimeCheck,
927                                                     IsConflict,
928                                                     "conflict.rdx", Loc);
929       else
930         MemoryRuntimeCheck = IsConflict;
931
932     }
933   }
934
935   return MemoryRuntimeCheck;
936 }
937
938 void
939 InnerLoopVectorizer::createEmptyLoop(LoopVectorizationLegality *Legal) {
940   /*
941    In this function we generate a new loop. The new loop will contain
942    the vectorized instructions while the old loop will continue to run the
943    scalar remainder.
944
945        [ ] <-- vector loop bypass (may consist of multiple blocks).
946      /  |
947     /   v
948    |   [ ]     <-- vector pre header.
949    |    |
950    |    v
951    |   [  ] \
952    |   [  ]_|   <-- vector loop.
953    |    |
954     \   v
955       >[ ]   <--- middle-block.
956      /  |
957     /   v
958    |   [ ]     <--- new preheader.
959    |    |
960    |    v
961    |   [ ] \
962    |   [ ]_|   <-- old scalar loop to handle remainder.
963     \   |
964      \  v
965       >[ ]     <-- exit block.
966    ...
967    */
968
969   BasicBlock *OldBasicBlock = OrigLoop->getHeader();
970   BasicBlock *BypassBlock = OrigLoop->getLoopPreheader();
971   BasicBlock *ExitBlock = OrigLoop->getExitBlock();
972   assert(ExitBlock && "Must have an exit block");
973
974   // Some loops have a single integer induction variable, while other loops
975   // don't. One example is c++ iterators that often have multiple pointer
976   // induction variables. In the code below we also support a case where we
977   // don't have a single induction variable.
978   OldInduction = Legal->getInduction();
979   Type *IdxTy = OldInduction ? OldInduction->getType() :
980   DL->getIntPtrType(SE->getContext());
981
982   // Find the loop boundaries.
983   const SCEV *ExitCount = SE->getExitCount(OrigLoop, OrigLoop->getLoopLatch());
984   assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
985
986   // Get the total trip count from the count by adding 1.
987   ExitCount = SE->getAddExpr(ExitCount,
988                              SE->getConstant(ExitCount->getType(), 1));
989
990   // Expand the trip count and place the new instructions in the preheader.
991   // Notice that the pre-header does not change, only the loop body.
992   SCEVExpander Exp(*SE, "induction");
993
994   // Count holds the overall loop count (N).
995   Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
996                                    BypassBlock->getTerminator());
997
998   // The loop index does not have to start at Zero. Find the original start
999   // value from the induction PHI node. If we don't have an induction variable
1000   // then we know that it starts at zero.
1001   Value *StartIdx = OldInduction ?
1002   OldInduction->getIncomingValueForBlock(BypassBlock):
1003   ConstantInt::get(IdxTy, 0);
1004
1005   assert(BypassBlock && "Invalid loop structure");
1006   LoopBypassBlocks.push_back(BypassBlock);
1007
1008   // Split the single block loop into the two loop structure described above.
1009   BasicBlock *VectorPH =
1010   BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
1011   BasicBlock *VecBody =
1012   VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
1013   BasicBlock *MiddleBlock =
1014   VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
1015   BasicBlock *ScalarPH =
1016   MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
1017
1018   // This is the location in which we add all of the logic for bypassing
1019   // the new vector loop.
1020   Instruction *Loc = BypassBlock->getTerminator();
1021
1022   // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
1023   // inside the loop.
1024   Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
1025
1026   // Generate the induction variable.
1027   Induction = Builder.CreatePHI(IdxTy, 2, "index");
1028   // The loop step is equal to the vectorization factor (num of SIMD elements)
1029   // times the unroll factor (num of SIMD instructions).
1030   Constant *Step = ConstantInt::get(IdxTy, VF * UF);
1031
1032   // We may need to extend the index in case there is a type mismatch.
1033   // We know that the count starts at zero and does not overflow.
1034   unsigned IdxTyBW = IdxTy->getScalarSizeInBits();
1035   if (Count->getType() != IdxTy) {
1036     // The exit count can be of pointer type. Convert it to the correct
1037     // integer type.
1038     if (ExitCount->getType()->isPointerTy())
1039       Count = CastInst::CreatePointerCast(Count, IdxTy, "ptrcnt.to.int", Loc);
1040     else if (IdxTyBW < Count->getType()->getScalarSizeInBits())
1041       Count = CastInst::CreateTruncOrBitCast(Count, IdxTy, "tr.cnt", Loc);
1042     else
1043       Count = CastInst::CreateZExtOrBitCast(Count, IdxTy, "zext.cnt", Loc);
1044   }
1045
1046   // Add the start index to the loop count to get the new end index.
1047   Value *IdxEnd = BinaryOperator::CreateAdd(Count, StartIdx, "end.idx", Loc);
1048
1049   // Now we need to generate the expression for N - (N % VF), which is
1050   // the part that the vectorized body will execute.
1051   Value *R = BinaryOperator::CreateURem(Count, Step, "n.mod.vf", Loc);
1052   Value *CountRoundDown = BinaryOperator::CreateSub(Count, R, "n.vec", Loc);
1053   Value *IdxEndRoundDown = BinaryOperator::CreateAdd(CountRoundDown, StartIdx,
1054                                                      "end.idx.rnd.down", Loc);
1055
1056   // Now, compare the new count to zero. If it is zero skip the vector loop and
1057   // jump to the scalar loop.
1058   Value *Cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
1059                                IdxEndRoundDown,
1060                                StartIdx,
1061                                "cmp.zero", Loc);
1062
1063   // Generate the code that checks in runtime if arrays overlap. We put the
1064   // checks into a separate block to make the more common case of few elements
1065   // faster.
1066   if (Instruction *MemoryRuntimeCheck = addRuntimeCheck(Legal, Loc)) {
1067     // Create a new block containing the memory check.
1068     BasicBlock *CheckBlock = BypassBlock->splitBasicBlock(MemoryRuntimeCheck,
1069                                                           "vector.memcheck");
1070     LoopBypassBlocks.push_back(CheckBlock);
1071
1072     // Replace the branch into the memory check block with a conditional branch
1073     // for the "few elements case".
1074     Instruction *OldTerm = BypassBlock->getTerminator();
1075     BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
1076     OldTerm->eraseFromParent();
1077
1078     Cmp = MemoryRuntimeCheck;
1079     assert(Loc == CheckBlock->getTerminator());
1080   }
1081
1082   BranchInst::Create(MiddleBlock, VectorPH, Cmp, Loc);
1083   // Remove the old terminator.
1084   Loc->eraseFromParent();
1085
1086   // We are going to resume the execution of the scalar loop.
1087   // Go over all of the induction variables that we found and fix the
1088   // PHIs that are left in the scalar version of the loop.
1089   // The starting values of PHI nodes depend on the counter of the last
1090   // iteration in the vectorized loop.
1091   // If we come from a bypass edge then we need to start from the original
1092   // start value.
1093
1094   // This variable saves the new starting index for the scalar loop.
1095   PHINode *ResumeIndex = 0;
1096   LoopVectorizationLegality::InductionList::iterator I, E;
1097   LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
1098   for (I = List->begin(), E = List->end(); I != E; ++I) {
1099     PHINode *OrigPhi = I->first;
1100     LoopVectorizationLegality::InductionInfo II = I->second;
1101     PHINode *ResumeVal = PHINode::Create(OrigPhi->getType(), 2, "resume.val",
1102                                          MiddleBlock->getTerminator());
1103     Value *EndValue = 0;
1104     switch (II.IK) {
1105     case LoopVectorizationLegality::IK_NoInduction:
1106       llvm_unreachable("Unknown induction");
1107     case LoopVectorizationLegality::IK_IntInduction: {
1108       // Handle the integer induction counter:
1109       assert(OrigPhi->getType()->isIntegerTy() && "Invalid type");
1110       assert(OrigPhi == OldInduction && "Unknown integer PHI");
1111       // We know what the end value is.
1112       EndValue = IdxEndRoundDown;
1113       // We also know which PHI node holds it.
1114       ResumeIndex = ResumeVal;
1115       break;
1116     }
1117     case LoopVectorizationLegality::IK_ReverseIntInduction: {
1118       // Convert the CountRoundDown variable to the PHI size.
1119       unsigned CRDSize = CountRoundDown->getType()->getScalarSizeInBits();
1120       unsigned IISize = II.StartValue->getType()->getScalarSizeInBits();
1121       Value *CRD = CountRoundDown;
1122       if (CRDSize > IISize)
1123         CRD = CastInst::Create(Instruction::Trunc, CountRoundDown,
1124                                II.StartValue->getType(), "tr.crd",
1125                                LoopBypassBlocks.back()->getTerminator());
1126       else if (CRDSize < IISize)
1127         CRD = CastInst::Create(Instruction::SExt, CountRoundDown,
1128                                II.StartValue->getType(),
1129                                "sext.crd",
1130                                LoopBypassBlocks.back()->getTerminator());
1131       // Handle reverse integer induction counter:
1132       EndValue =
1133         BinaryOperator::CreateSub(II.StartValue, CRD, "rev.ind.end",
1134                                   LoopBypassBlocks.back()->getTerminator());
1135       break;
1136     }
1137     case LoopVectorizationLegality::IK_PtrInduction: {
1138       // For pointer induction variables, calculate the offset using
1139       // the end index.
1140       EndValue =
1141         GetElementPtrInst::Create(II.StartValue, CountRoundDown, "ptr.ind.end",
1142                                   LoopBypassBlocks.back()->getTerminator());
1143       break;
1144     }
1145     }// end of case
1146
1147     // The new PHI merges the original incoming value, in case of a bypass,
1148     // or the value at the end of the vectorized loop.
1149     for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
1150       ResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
1151     ResumeVal->addIncoming(EndValue, VecBody);
1152
1153     // Fix the scalar body counter (PHI node).
1154     unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
1155     OrigPhi->setIncomingValue(BlockIdx, ResumeVal);
1156   }
1157
1158   // If we are generating a new induction variable then we also need to
1159   // generate the code that calculates the exit value. This value is not
1160   // simply the end of the counter because we may skip the vectorized body
1161   // in case of a runtime check.
1162   if (!OldInduction){
1163     assert(!ResumeIndex && "Unexpected resume value found");
1164     ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val",
1165                                   MiddleBlock->getTerminator());
1166     for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
1167       ResumeIndex->addIncoming(StartIdx, LoopBypassBlocks[I]);
1168     ResumeIndex->addIncoming(IdxEndRoundDown, VecBody);
1169   }
1170
1171   // Make sure that we found the index where scalar loop needs to continue.
1172   assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() &&
1173          "Invalid resume Index");
1174
1175   // Add a check in the middle block to see if we have completed
1176   // all of the iterations in the first vector loop.
1177   // If (N - N%VF) == N, then we *don't* need to run the remainder.
1178   Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd,
1179                                 ResumeIndex, "cmp.n",
1180                                 MiddleBlock->getTerminator());
1181
1182   BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
1183   // Remove the old terminator.
1184   MiddleBlock->getTerminator()->eraseFromParent();
1185
1186   // Create i+1 and fill the PHINode.
1187   Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
1188   Induction->addIncoming(StartIdx, VectorPH);
1189   Induction->addIncoming(NextIdx, VecBody);
1190   // Create the compare.
1191   Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown);
1192   Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
1193
1194   // Now we have two terminators. Remove the old one from the block.
1195   VecBody->getTerminator()->eraseFromParent();
1196
1197   // Get ready to start creating new instructions into the vectorized body.
1198   Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
1199
1200   // Create and register the new vector loop.
1201   Loop* Lp = new Loop();
1202   Loop *ParentLoop = OrigLoop->getParentLoop();
1203
1204   // Insert the new loop into the loop nest and register the new basic blocks.
1205   if (ParentLoop) {
1206     ParentLoop->addChildLoop(Lp);
1207     for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
1208       ParentLoop->addBasicBlockToLoop(LoopBypassBlocks[I], LI->getBase());
1209     ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase());
1210     ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase());
1211     ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase());
1212   } else {
1213     LI->addTopLevelLoop(Lp);
1214   }
1215
1216   Lp->addBasicBlockToLoop(VecBody, LI->getBase());
1217
1218   // Save the state.
1219   LoopVectorPreHeader = VectorPH;
1220   LoopScalarPreHeader = ScalarPH;
1221   LoopMiddleBlock = MiddleBlock;
1222   LoopExitBlock = ExitBlock;
1223   LoopVectorBody = VecBody;
1224   LoopScalarBody = OldBasicBlock;
1225 }
1226
1227 /// This function returns the identity element (or neutral element) for
1228 /// the operation K.
1229 static Constant*
1230 getReductionIdentity(LoopVectorizationLegality::ReductionKind K, Type *Tp) {
1231   switch (K) {
1232   case LoopVectorizationLegality:: RK_IntegerXor:
1233   case LoopVectorizationLegality:: RK_IntegerAdd:
1234   case LoopVectorizationLegality:: RK_IntegerOr:
1235     // Adding, Xoring, Oring zero to a number does not change it.
1236     return ConstantInt::get(Tp, 0);
1237   case LoopVectorizationLegality:: RK_IntegerMult:
1238     // Multiplying a number by 1 does not change it.
1239     return ConstantInt::get(Tp, 1);
1240   case LoopVectorizationLegality:: RK_IntegerAnd:
1241     // AND-ing a number with an all-1 value does not change it.
1242     return ConstantInt::get(Tp, -1, true);
1243   case LoopVectorizationLegality:: RK_FloatMult:
1244     // Multiplying a number by 1 does not change it.
1245     return ConstantFP::get(Tp, 1.0L);
1246   case LoopVectorizationLegality:: RK_FloatAdd:
1247     // Adding zero to a number does not change it.
1248     return ConstantFP::get(Tp, 0.0L);
1249   default:
1250     llvm_unreachable("Unknown reduction kind");
1251   }
1252 }
1253
1254 static bool
1255 isTriviallyVectorizableIntrinsic(Instruction *Inst) {
1256   IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst);
1257   if (!II)
1258     return false;
1259   switch (II->getIntrinsicID()) {
1260   case Intrinsic::sqrt:
1261   case Intrinsic::sin:
1262   case Intrinsic::cos:
1263   case Intrinsic::exp:
1264   case Intrinsic::exp2:
1265   case Intrinsic::log:
1266   case Intrinsic::log10:
1267   case Intrinsic::log2:
1268   case Intrinsic::fabs:
1269   case Intrinsic::floor:
1270   case Intrinsic::ceil:
1271   case Intrinsic::trunc:
1272   case Intrinsic::rint:
1273   case Intrinsic::nearbyint:
1274   case Intrinsic::pow:
1275   case Intrinsic::fma:
1276   case Intrinsic::fmuladd:
1277     return true;
1278   default:
1279     return false;
1280   }
1281   return false;
1282 }
1283
1284 /// This function translates the reduction kind to an LLVM binary operator.
1285 static Instruction::BinaryOps
1286 getReductionBinOp(LoopVectorizationLegality::ReductionKind Kind) {
1287   switch (Kind) {
1288     case LoopVectorizationLegality::RK_IntegerAdd:
1289       return Instruction::Add;
1290     case LoopVectorizationLegality::RK_IntegerMult:
1291       return Instruction::Mul;
1292     case LoopVectorizationLegality::RK_IntegerOr:
1293       return Instruction::Or;
1294     case LoopVectorizationLegality::RK_IntegerAnd:
1295       return Instruction::And;
1296     case LoopVectorizationLegality::RK_IntegerXor:
1297       return Instruction::Xor;
1298     case LoopVectorizationLegality::RK_FloatMult:
1299       return Instruction::FMul;
1300     case LoopVectorizationLegality::RK_FloatAdd:
1301       return Instruction::FAdd;
1302     default:
1303       llvm_unreachable("Unknown reduction operation");
1304   }
1305 }
1306
1307 void
1308 InnerLoopVectorizer::vectorizeLoop(LoopVectorizationLegality *Legal) {
1309   //===------------------------------------------------===//
1310   //
1311   // Notice: any optimization or new instruction that go
1312   // into the code below should be also be implemented in
1313   // the cost-model.
1314   //
1315   //===------------------------------------------------===//
1316   BasicBlock &BB = *OrigLoop->getHeader();
1317   Constant *Zero =
1318   ConstantInt::get(IntegerType::getInt32Ty(BB.getContext()), 0);
1319
1320   // In order to support reduction variables we need to be able to vectorize
1321   // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
1322   // stages. First, we create a new vector PHI node with no incoming edges.
1323   // We use this value when we vectorize all of the instructions that use the
1324   // PHI. Next, after all of the instructions in the block are complete we
1325   // add the new incoming edges to the PHI. At this point all of the
1326   // instructions in the basic block are vectorized, so we can use them to
1327   // construct the PHI.
1328   PhiVector RdxPHIsToFix;
1329
1330   // Scan the loop in a topological order to ensure that defs are vectorized
1331   // before users.
1332   LoopBlocksDFS DFS(OrigLoop);
1333   DFS.perform(LI);
1334
1335   // Vectorize all of the blocks in the original loop.
1336   for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
1337        be = DFS.endRPO(); bb != be; ++bb)
1338     vectorizeBlockInLoop(Legal, *bb, &RdxPHIsToFix);
1339
1340   // At this point every instruction in the original loop is widened to
1341   // a vector form. We are almost done. Now, we need to fix the PHI nodes
1342   // that we vectorized. The PHI nodes are currently empty because we did
1343   // not want to introduce cycles. Notice that the remaining PHI nodes
1344   // that we need to fix are reduction variables.
1345
1346   // Create the 'reduced' values for each of the induction vars.
1347   // The reduced values are the vector values that we scalarize and combine
1348   // after the loop is finished.
1349   for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
1350        it != e; ++it) {
1351     PHINode *RdxPhi = *it;
1352     assert(RdxPhi && "Unable to recover vectorized PHI");
1353
1354     // Find the reduction variable descriptor.
1355     assert(Legal->getReductionVars()->count(RdxPhi) &&
1356            "Unable to find the reduction variable");
1357     LoopVectorizationLegality::ReductionDescriptor RdxDesc =
1358     (*Legal->getReductionVars())[RdxPhi];
1359
1360     // We need to generate a reduction vector from the incoming scalar.
1361     // To do so, we need to generate the 'identity' vector and overide
1362     // one of the elements with the incoming scalar reduction. We need
1363     // to do it in the vector-loop preheader.
1364     Builder.SetInsertPoint(LoopBypassBlocks.back()->getTerminator());
1365
1366     // This is the vector-clone of the value that leaves the loop.
1367     VectorParts &VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
1368     Type *VecTy = VectorExit[0]->getType();
1369
1370     // Find the reduction identity variable. Zero for addition, or, xor,
1371     // one for multiplication, -1 for And.
1372     Constant *Iden = getReductionIdentity(RdxDesc.Kind, VecTy->getScalarType());
1373     Constant *Identity = ConstantVector::getSplat(VF, Iden);
1374
1375     // This vector is the Identity vector where the first element is the
1376     // incoming scalar reduction.
1377     Value *VectorStart = Builder.CreateInsertElement(Identity,
1378                                                      RdxDesc.StartValue, Zero);
1379
1380     // Fix the vector-loop phi.
1381     // We created the induction variable so we know that the
1382     // preheader is the first entry.
1383     BasicBlock *VecPreheader = Induction->getIncomingBlock(0);
1384
1385     // Reductions do not have to start at zero. They can start with
1386     // any loop invariant values.
1387     VectorParts &VecRdxPhi = WidenMap.get(RdxPhi);
1388     BasicBlock *Latch = OrigLoop->getLoopLatch();
1389     Value *LoopVal = RdxPhi->getIncomingValueForBlock(Latch);
1390     VectorParts &Val = getVectorValue(LoopVal);
1391     for (unsigned part = 0; part < UF; ++part) {
1392       // Make sure to add the reduction stat value only to the 
1393       // first unroll part.
1394       Value *StartVal = (part == 0) ? VectorStart : Identity;
1395       cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal, VecPreheader);
1396       cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part], LoopVectorBody);
1397     }
1398
1399     // Before each round, move the insertion point right between
1400     // the PHIs and the values we are going to write.
1401     // This allows us to write both PHINodes and the extractelement
1402     // instructions.
1403     Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
1404
1405     VectorParts RdxParts;
1406     for (unsigned part = 0; part < UF; ++part) {
1407       // This PHINode contains the vectorized reduction variable, or
1408       // the initial value vector, if we bypass the vector loop.
1409       VectorParts &RdxExitVal = getVectorValue(RdxDesc.LoopExitInstr);
1410       PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
1411       Value *StartVal = (part == 0) ? VectorStart : Identity;
1412       for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
1413         NewPhi->addIncoming(StartVal, LoopBypassBlocks[I]);
1414       NewPhi->addIncoming(RdxExitVal[part], LoopVectorBody);
1415       RdxParts.push_back(NewPhi);
1416     }
1417
1418     // Reduce all of the unrolled parts into a single vector.
1419     Value *ReducedPartRdx = RdxParts[0];
1420     for (unsigned part = 1; part < UF; ++part) {
1421       Instruction::BinaryOps Op = getReductionBinOp(RdxDesc.Kind);
1422       ReducedPartRdx = Builder.CreateBinOp(Op, RdxParts[part], ReducedPartRdx,
1423                                            "bin.rdx");
1424     }
1425
1426     // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
1427     // and vector ops, reducing the set of values being computed by half each
1428     // round.
1429     assert(isPowerOf2_32(VF) &&
1430            "Reduction emission only supported for pow2 vectors!");
1431     Value *TmpVec = ReducedPartRdx;
1432     SmallVector<Constant*, 32> ShuffleMask(VF, 0);
1433     for (unsigned i = VF; i != 1; i >>= 1) {
1434       // Move the upper half of the vector to the lower half.
1435       for (unsigned j = 0; j != i/2; ++j)
1436         ShuffleMask[j] = Builder.getInt32(i/2 + j);
1437
1438       // Fill the rest of the mask with undef.
1439       std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
1440                 UndefValue::get(Builder.getInt32Ty()));
1441
1442       Value *Shuf =
1443         Builder.CreateShuffleVector(TmpVec,
1444                                     UndefValue::get(TmpVec->getType()),
1445                                     ConstantVector::get(ShuffleMask),
1446                                     "rdx.shuf");
1447
1448       Instruction::BinaryOps Op = getReductionBinOp(RdxDesc.Kind);
1449       TmpVec = Builder.CreateBinOp(Op, TmpVec, Shuf, "bin.rdx");
1450     }
1451
1452     // The result is in the first element of the vector.
1453     Value *Scalar0 = Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
1454
1455     // Now, we need to fix the users of the reduction variable
1456     // inside and outside of the scalar remainder loop.
1457     // We know that the loop is in LCSSA form. We need to update the
1458     // PHI nodes in the exit blocks.
1459     for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
1460          LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
1461       PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
1462       if (!LCSSAPhi) continue;
1463
1464       // All PHINodes need to have a single entry edge, or two if
1465       // we already fixed them.
1466       assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
1467
1468       // We found our reduction value exit-PHI. Update it with the
1469       // incoming bypass edge.
1470       if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
1471         // Add an edge coming from the bypass.
1472         LCSSAPhi->addIncoming(Scalar0, LoopMiddleBlock);
1473         break;
1474       }
1475     }// end of the LCSSA phi scan.
1476
1477     // Fix the scalar loop reduction variable with the incoming reduction sum
1478     // from the vector body and from the backedge value.
1479     int IncomingEdgeBlockIdx =
1480     (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
1481     assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
1482     // Pick the other block.
1483     int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
1484     (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, Scalar0);
1485     (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
1486   }// end of for each redux variable.
1487
1488   // The Loop exit block may have single value PHI nodes where the incoming
1489   // value is 'undef'. While vectorizing we only handled real values that
1490   // were defined inside the loop. Here we handle the 'undef case'.
1491   // See PR14725.
1492   for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
1493        LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
1494     PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
1495     if (!LCSSAPhi) continue;
1496     if (LCSSAPhi->getNumIncomingValues() == 1)
1497       LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
1498                             LoopMiddleBlock);
1499   }
1500 }
1501
1502 InnerLoopVectorizer::VectorParts
1503 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
1504   assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
1505          "Invalid edge");
1506
1507   VectorParts SrcMask = createBlockInMask(Src);
1508
1509   // The terminator has to be a branch inst!
1510   BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
1511   assert(BI && "Unexpected terminator found");
1512
1513   if (BI->isConditional()) {
1514     VectorParts EdgeMask = getVectorValue(BI->getCondition());
1515
1516     if (BI->getSuccessor(0) != Dst)
1517       for (unsigned part = 0; part < UF; ++part)
1518         EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
1519
1520     for (unsigned part = 0; part < UF; ++part)
1521       EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
1522     return EdgeMask;
1523   }
1524
1525   return SrcMask;
1526 }
1527
1528 InnerLoopVectorizer::VectorParts
1529 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
1530   assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
1531
1532   // Loop incoming mask is all-one.
1533   if (OrigLoop->getHeader() == BB) {
1534     Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
1535     return getVectorValue(C);
1536   }
1537
1538   // This is the block mask. We OR all incoming edges, and with zero.
1539   Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
1540   VectorParts BlockMask = getVectorValue(Zero);
1541
1542   // For each pred:
1543   for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
1544     VectorParts EM = createEdgeMask(*it, BB);
1545     for (unsigned part = 0; part < UF; ++part)
1546       BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
1547   }
1548
1549   return BlockMask;
1550 }
1551
1552 void
1553 InnerLoopVectorizer::vectorizeBlockInLoop(LoopVectorizationLegality *Legal,
1554                                           BasicBlock *BB, PhiVector *PV) {
1555   Constant *Zero = Builder.getInt32(0);
1556
1557   // For each instruction in the old loop.
1558   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1559     VectorParts &Entry = WidenMap.get(it);
1560     switch (it->getOpcode()) {
1561     case Instruction::Br:
1562       // Nothing to do for PHIs and BR, since we already took care of the
1563       // loop control flow instructions.
1564       continue;
1565     case Instruction::PHI:{
1566       PHINode* P = cast<PHINode>(it);
1567       // Handle reduction variables:
1568       if (Legal->getReductionVars()->count(P)) {
1569         for (unsigned part = 0; part < UF; ++part) {
1570           // This is phase one of vectorizing PHIs.
1571           Type *VecTy = VectorType::get(it->getType(), VF);
1572           Entry[part] = PHINode::Create(VecTy, 2, "vec.phi",
1573                                         LoopVectorBody-> getFirstInsertionPt());
1574         }
1575         PV->push_back(P);
1576         continue;
1577       }
1578
1579       // Check for PHI nodes that are lowered to vector selects.
1580       if (P->getParent() != OrigLoop->getHeader()) {
1581         // We know that all PHIs in non header blocks are converted into
1582         // selects, so we don't have to worry about the insertion order and we
1583         // can just use the builder.
1584
1585         // At this point we generate the predication tree. There may be
1586         // duplications since this is a simple recursive scan, but future
1587         // optimizations will clean it up.
1588         VectorParts Cond = createEdgeMask(P->getIncomingBlock(0),
1589                                                P->getParent());
1590         
1591         for (unsigned part = 0; part < UF; ++part) {
1592         VectorParts &In0 = getVectorValue(P->getIncomingValue(0));
1593         VectorParts &In1 = getVectorValue(P->getIncomingValue(1));
1594           Entry[part] = Builder.CreateSelect(Cond[part], In0[part], In1[part],
1595                                              "predphi");
1596         }
1597         continue;
1598       }
1599
1600       // This PHINode must be an induction variable.
1601       // Make sure that we know about it.
1602       assert(Legal->getInductionVars()->count(P) &&
1603              "Not an induction variable");
1604
1605       LoopVectorizationLegality::InductionInfo II =
1606         Legal->getInductionVars()->lookup(P);
1607
1608       switch (II.IK) {
1609       case LoopVectorizationLegality::IK_NoInduction:
1610         llvm_unreachable("Unknown induction");
1611       case LoopVectorizationLegality::IK_IntInduction: {
1612         assert(P == OldInduction && "Unexpected PHI");
1613         Value *Broadcasted = getBroadcastInstrs(Induction);
1614         // After broadcasting the induction variable we need to make the
1615         // vector consecutive by adding 0, 1, 2 ...
1616         for (unsigned part = 0; part < UF; ++part)
1617           Entry[part] = getConsecutiveVector(Broadcasted, VF * part, false);
1618         continue;
1619       }
1620       case LoopVectorizationLegality::IK_ReverseIntInduction:
1621       case LoopVectorizationLegality::IK_PtrInduction:
1622         // Handle reverse integer and pointer inductions.
1623         Value *StartIdx = 0;
1624         // If we have a single integer induction variable then use it.
1625         // Otherwise, start counting at zero.
1626         if (OldInduction) {
1627           LoopVectorizationLegality::InductionInfo OldII =
1628             Legal->getInductionVars()->lookup(OldInduction);
1629           StartIdx = OldII.StartValue;
1630         } else {
1631           StartIdx = ConstantInt::get(Induction->getType(), 0);
1632         }
1633         // This is the normalized GEP that starts counting at zero.
1634         Value *NormalizedIdx = Builder.CreateSub(Induction, StartIdx,
1635                                                  "normalized.idx");
1636
1637         // Handle the reverse integer induction variable case.
1638         if (LoopVectorizationLegality::IK_ReverseIntInduction == II.IK) {
1639           IntegerType *DstTy = cast<IntegerType>(II.StartValue->getType());
1640           Value *CNI = Builder.CreateSExtOrTrunc(NormalizedIdx, DstTy,
1641                                                  "resize.norm.idx");
1642           Value *ReverseInd  = Builder.CreateSub(II.StartValue, CNI,
1643                                                  "reverse.idx");
1644
1645           // This is a new value so do not hoist it out.
1646           Value *Broadcasted = getBroadcastInstrs(ReverseInd);
1647           // After broadcasting the induction variable we need to make the
1648           // vector consecutive by adding  ... -3, -2, -1, 0.
1649           for (unsigned part = 0; part < UF; ++part)
1650             Entry[part] = getConsecutiveVector(Broadcasted, -VF * part, true);
1651           continue;
1652         }
1653
1654         // Handle the pointer induction variable case.
1655         assert(P->getType()->isPointerTy() && "Unexpected type.");
1656
1657         // This is the vector of results. Notice that we don't generate
1658         // vector geps because scalar geps result in better code.
1659         for (unsigned part = 0; part < UF; ++part) {
1660           Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
1661           for (unsigned int i = 0; i < VF; ++i) {
1662             Constant *Idx = ConstantInt::get(Induction->getType(),
1663                                              i + part * VF);
1664             Value *GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx,
1665                                                  "gep.idx");
1666             Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
1667                                                "next.gep");
1668             VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
1669                                                  Builder.getInt32(i),
1670                                                  "insert.gep");
1671           }
1672           Entry[part] = VecVal;
1673         }
1674         continue;
1675       }
1676
1677     }// End of PHI.
1678
1679     case Instruction::Add:
1680     case Instruction::FAdd:
1681     case Instruction::Sub:
1682     case Instruction::FSub:
1683     case Instruction::Mul:
1684     case Instruction::FMul:
1685     case Instruction::UDiv:
1686     case Instruction::SDiv:
1687     case Instruction::FDiv:
1688     case Instruction::URem:
1689     case Instruction::SRem:
1690     case Instruction::FRem:
1691     case Instruction::Shl:
1692     case Instruction::LShr:
1693     case Instruction::AShr:
1694     case Instruction::And:
1695     case Instruction::Or:
1696     case Instruction::Xor: {
1697       // Just widen binops.
1698       BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
1699       VectorParts &A = getVectorValue(it->getOperand(0));
1700       VectorParts &B = getVectorValue(it->getOperand(1));
1701
1702       // Use this vector value for all users of the original instruction.
1703       for (unsigned Part = 0; Part < UF; ++Part) {
1704         Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
1705
1706         // Update the NSW, NUW and Exact flags. Notice: V can be an Undef.
1707         BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V);
1708         if (VecOp && isa<OverflowingBinaryOperator>(BinOp)) {
1709           VecOp->setHasNoSignedWrap(BinOp->hasNoSignedWrap());
1710           VecOp->setHasNoUnsignedWrap(BinOp->hasNoUnsignedWrap());
1711         }
1712         if (VecOp && isa<PossiblyExactOperator>(VecOp))
1713           VecOp->setIsExact(BinOp->isExact());
1714
1715         Entry[Part] = V;
1716       }
1717       break;
1718     }
1719     case Instruction::Select: {
1720       // Widen selects.
1721       // If the selector is loop invariant we can create a select
1722       // instruction with a scalar condition. Otherwise, use vector-select.
1723       bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)),
1724                                                OrigLoop);
1725
1726       // The condition can be loop invariant  but still defined inside the
1727       // loop. This means that we can't just use the original 'cond' value.
1728       // We have to take the 'vectorized' value and pick the first lane.
1729       // Instcombine will make this a no-op.
1730       VectorParts &Cond = getVectorValue(it->getOperand(0));
1731       VectorParts &Op0  = getVectorValue(it->getOperand(1));
1732       VectorParts &Op1  = getVectorValue(it->getOperand(2));
1733       Value *ScalarCond = Builder.CreateExtractElement(Cond[0],
1734                                                        Builder.getInt32(0));
1735       for (unsigned Part = 0; Part < UF; ++Part) {
1736         Entry[Part] = Builder.CreateSelect(
1737           InvariantCond ? ScalarCond : Cond[Part],
1738           Op0[Part],
1739           Op1[Part]);
1740       }
1741       break;
1742     }
1743
1744     case Instruction::ICmp:
1745     case Instruction::FCmp: {
1746       // Widen compares. Generate vector compares.
1747       bool FCmp = (it->getOpcode() == Instruction::FCmp);
1748       CmpInst *Cmp = dyn_cast<CmpInst>(it);
1749       VectorParts &A = getVectorValue(it->getOperand(0));
1750       VectorParts &B = getVectorValue(it->getOperand(1));
1751       for (unsigned Part = 0; Part < UF; ++Part) {
1752         Value *C = 0;
1753         if (FCmp)
1754           C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
1755         else
1756           C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
1757         Entry[Part] = C;
1758       }
1759       break;
1760     }
1761
1762     case Instruction::Store: {
1763       // Attempt to issue a wide store.
1764       StoreInst *SI = dyn_cast<StoreInst>(it);
1765       Type *StTy = VectorType::get(SI->getValueOperand()->getType(), VF);
1766       Value *Ptr = SI->getPointerOperand();
1767       unsigned Alignment = SI->getAlignment();
1768
1769       assert(!Legal->isUniform(Ptr) &&
1770              "We do not allow storing to uniform addresses");
1771
1772
1773       int Stride = Legal->isConsecutivePtr(Ptr);
1774       bool Reverse = Stride < 0;
1775       if (Stride == 0) {
1776         scalarizeInstruction(it);
1777         break;
1778       }
1779
1780       // Handle consecutive stores.
1781
1782       GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1783       if (Gep) {
1784         // The last index does not have to be the induction. It can be
1785         // consecutive and be a function of the index. For example A[I+1];
1786         unsigned NumOperands = Gep->getNumOperands();
1787
1788         Value *LastGepOperand = Gep->getOperand(NumOperands - 1);
1789         VectorParts &GEPParts = getVectorValue(LastGepOperand);
1790         Value *LastIndex = GEPParts[0];
1791         LastIndex = Builder.CreateExtractElement(LastIndex, Zero);
1792
1793         // Create the new GEP with the new induction variable.
1794         GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1795         Gep2->setOperand(NumOperands - 1, LastIndex);
1796         Ptr = Builder.Insert(Gep2);
1797       } else {
1798         // Use the induction element ptr.
1799         assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1800         VectorParts &PtrVal = getVectorValue(Ptr);
1801         Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
1802       }
1803
1804       VectorParts &StoredVal = getVectorValue(SI->getValueOperand());
1805       for (unsigned Part = 0; Part < UF; ++Part) {
1806         // Calculate the pointer for the specific unroll-part.
1807         Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1808
1809         if (Reverse) {
1810           // If we store to reverse consecutive memory locations then we need
1811           // to reverse the order of elements in the stored value.
1812           StoredVal[Part] = reverseVector(StoredVal[Part]);
1813           // If the address is consecutive but reversed, then the
1814           // wide store needs to start at the last vector element.
1815           PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1816           PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1817         }
1818
1819         Value *VecPtr = Builder.CreateBitCast(PartPtr, StTy->getPointerTo());
1820         Builder.CreateStore(StoredVal[Part], VecPtr)->setAlignment(Alignment);
1821       }
1822       break;
1823     }
1824     case Instruction::Load: {
1825       // Attempt to issue a wide load.
1826       LoadInst *LI = dyn_cast<LoadInst>(it);
1827       Type *RetTy = VectorType::get(LI->getType(), VF);
1828       Value *Ptr = LI->getPointerOperand();
1829       unsigned Alignment = LI->getAlignment();
1830
1831       // If the pointer is loop invariant or if it is non consecutive,
1832       // scalarize the load.
1833       int Stride = Legal->isConsecutivePtr(Ptr);
1834       bool Reverse = Stride < 0;
1835       if (Legal->isUniform(Ptr) || Stride == 0) {
1836         scalarizeInstruction(it);
1837         break;
1838       }
1839
1840       GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1841       if (Gep) {
1842         // The last index does not have to be the induction. It can be
1843         // consecutive and be a function of the index. For example A[I+1];
1844         unsigned NumOperands = Gep->getNumOperands();
1845
1846         Value *LastGepOperand = Gep->getOperand(NumOperands - 1);
1847         VectorParts &GEPParts = getVectorValue(LastGepOperand);
1848         Value *LastIndex = GEPParts[0];
1849         LastIndex = Builder.CreateExtractElement(LastIndex, Zero);
1850
1851         // Create the new GEP with the new induction variable.
1852         GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1853         Gep2->setOperand(NumOperands - 1, LastIndex);
1854         Ptr = Builder.Insert(Gep2);
1855       } else {
1856         // Use the induction element ptr.
1857         assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1858         VectorParts &PtrVal = getVectorValue(Ptr);
1859         Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
1860       }
1861
1862       for (unsigned Part = 0; Part < UF; ++Part) {
1863         // Calculate the pointer for the specific unroll-part.
1864         Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1865
1866         if (Reverse) {
1867           // If the address is consecutive but reversed, then the
1868           // wide store needs to start at the last vector element.
1869           PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1870           PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1871         }
1872
1873         Value *VecPtr = Builder.CreateBitCast(PartPtr, RetTy->getPointerTo());
1874         Value *LI = Builder.CreateLoad(VecPtr, "wide.load");
1875         cast<LoadInst>(LI)->setAlignment(Alignment);
1876         Entry[Part] = Reverse ? reverseVector(LI) :  LI;
1877       }
1878       break;
1879     }
1880     case Instruction::ZExt:
1881     case Instruction::SExt:
1882     case Instruction::FPToUI:
1883     case Instruction::FPToSI:
1884     case Instruction::FPExt:
1885     case Instruction::PtrToInt:
1886     case Instruction::IntToPtr:
1887     case Instruction::SIToFP:
1888     case Instruction::UIToFP:
1889     case Instruction::Trunc:
1890     case Instruction::FPTrunc:
1891     case Instruction::BitCast: {
1892       CastInst *CI = dyn_cast<CastInst>(it);
1893       /// Optimize the special case where the source is the induction
1894       /// variable. Notice that we can only optimize the 'trunc' case
1895       /// because: a. FP conversions lose precision, b. sext/zext may wrap,
1896       /// c. other casts depend on pointer size.
1897       if (CI->getOperand(0) == OldInduction &&
1898           it->getOpcode() == Instruction::Trunc) {
1899         Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
1900                                                CI->getType());
1901         Value *Broadcasted = getBroadcastInstrs(ScalarCast);
1902         for (unsigned Part = 0; Part < UF; ++Part)
1903           Entry[Part] = getConsecutiveVector(Broadcasted, VF * Part, false);
1904         break;
1905       }
1906       /// Vectorize casts.
1907       Type *DestTy = VectorType::get(CI->getType()->getScalarType(), VF);
1908
1909       VectorParts &A = getVectorValue(it->getOperand(0));
1910       for (unsigned Part = 0; Part < UF; ++Part)
1911         Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
1912       break;
1913     }
1914
1915     case Instruction::Call: {
1916       assert(isTriviallyVectorizableIntrinsic(it));
1917       Module *M = BB->getParent()->getParent();
1918       IntrinsicInst *II = cast<IntrinsicInst>(it);
1919       Intrinsic::ID ID = II->getIntrinsicID();
1920       for (unsigned Part = 0; Part < UF; ++Part) {
1921         SmallVector<Value*, 4> Args;
1922         for (unsigned i = 0, ie = II->getNumArgOperands(); i != ie; ++i) {
1923           VectorParts &Arg = getVectorValue(II->getArgOperand(i));
1924           Args.push_back(Arg[Part]);
1925         }
1926         Type *Tys[] = { VectorType::get(II->getType()->getScalarType(), VF) };
1927         Function *F = Intrinsic::getDeclaration(M, ID, Tys);
1928         Entry[Part] = Builder.CreateCall(F, Args);
1929       }
1930       break;
1931     }
1932
1933     default:
1934       // All other instructions are unsupported. Scalarize them.
1935       scalarizeInstruction(it);
1936       break;
1937     }// end of switch.
1938   }// end of for_each instr.
1939 }
1940
1941 void InnerLoopVectorizer::updateAnalysis() {
1942   // Forget the original basic block.
1943   SE->forgetLoop(OrigLoop);
1944
1945   // Update the dominator tree information.
1946   assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&
1947          "Entry does not dominate exit.");
1948
1949   for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
1950     DT->addNewBlock(LoopBypassBlocks[I], LoopBypassBlocks[I-1]);
1951   DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlocks.back());
1952   DT->addNewBlock(LoopVectorBody, LoopVectorPreHeader);
1953   DT->addNewBlock(LoopMiddleBlock, LoopBypassBlocks.front());
1954   DT->addNewBlock(LoopScalarPreHeader, LoopMiddleBlock);
1955   DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
1956   DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
1957
1958   DEBUG(DT->verifyAnalysis());
1959 }
1960
1961 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
1962   if (!EnableIfConversion)
1963     return false;
1964
1965   assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
1966   std::vector<BasicBlock*> &LoopBlocks = TheLoop->getBlocksVector();
1967
1968   // Collect the blocks that need predication.
1969   for (unsigned i = 0, e = LoopBlocks.size(); i < e; ++i) {
1970     BasicBlock *BB = LoopBlocks[i];
1971
1972     // We don't support switch statements inside loops.
1973     if (!isa<BranchInst>(BB->getTerminator()))
1974       return false;
1975
1976     // We must have at most two predecessors because we need to convert
1977     // all PHIs to selects.
1978     unsigned Preds = std::distance(pred_begin(BB), pred_end(BB));
1979     if (Preds > 2)
1980       return false;
1981
1982     // We must be able to predicate all blocks that need to be predicated.
1983     if (blockNeedsPredication(BB) && !blockCanBePredicated(BB))
1984       return false;
1985   }
1986
1987   // We can if-convert this loop.
1988   return true;
1989 }
1990
1991 bool LoopVectorizationLegality::canVectorize() {
1992   assert(TheLoop->getLoopPreheader() && "No preheader!!");
1993
1994   // We can only vectorize innermost loops.
1995   if (TheLoop->getSubLoopsVector().size())
1996     return false;
1997
1998   // We must have a single backedge.
1999   if (TheLoop->getNumBackEdges() != 1)
2000     return false;
2001
2002   // We must have a single exiting block.
2003   if (!TheLoop->getExitingBlock())
2004     return false;
2005
2006   unsigned NumBlocks = TheLoop->getNumBlocks();
2007
2008   // Check if we can if-convert non single-bb loops.
2009   if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
2010     DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
2011     return false;
2012   }
2013
2014   // We need to have a loop header.
2015   BasicBlock *Latch = TheLoop->getLoopLatch();
2016   DEBUG(dbgs() << "LV: Found a loop: " <<
2017         TheLoop->getHeader()->getName() << "\n");
2018
2019   // ScalarEvolution needs to be able to find the exit count.
2020   const SCEV *ExitCount = SE->getExitCount(TheLoop, Latch);
2021   if (ExitCount == SE->getCouldNotCompute()) {
2022     DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
2023     return false;
2024   }
2025
2026   // Do not loop-vectorize loops with a tiny trip count.
2027   unsigned TC = SE->getSmallConstantTripCount(TheLoop, Latch);
2028   if (TC > 0u && TC < TinyTripCountVectorThreshold) {
2029     DEBUG(dbgs() << "LV: Found a loop with a very small trip count. " <<
2030           "This loop is not worth vectorizing.\n");
2031     return false;
2032   }
2033
2034   // Check if we can vectorize the instructions and CFG in this loop.
2035   if (!canVectorizeInstrs()) {
2036     DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
2037     return false;
2038   }
2039
2040   // Go over each instruction and look at memory deps.
2041   if (!canVectorizeMemory()) {
2042     DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
2043     return false;
2044   }
2045
2046   // Collect all of the variables that remain uniform after vectorization.
2047   collectLoopUniforms();
2048
2049   DEBUG(dbgs() << "LV: We can vectorize this loop" <<
2050         (PtrRtCheck.Need ? " (with a runtime bound check)" : "")
2051         <<"!\n");
2052
2053   // Okay! We can vectorize. At this point we don't have any other mem analysis
2054   // which may limit our maximum vectorization factor, so just return true with
2055   // no restrictions.
2056   return true;
2057 }
2058
2059 bool LoopVectorizationLegality::canVectorizeInstrs() {
2060   BasicBlock *PreHeader = TheLoop->getLoopPreheader();
2061   BasicBlock *Header = TheLoop->getHeader();
2062
2063   // For each block in the loop.
2064   for (Loop::block_iterator bb = TheLoop->block_begin(),
2065        be = TheLoop->block_end(); bb != be; ++bb) {
2066
2067     // Scan the instructions in the block and look for hazards.
2068     for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
2069          ++it) {
2070
2071       if (PHINode *Phi = dyn_cast<PHINode>(it)) {
2072         // This should not happen because the loop should be normalized.
2073         if (Phi->getNumIncomingValues() != 2) {
2074           DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
2075           return false;
2076         }
2077
2078         // Check that this PHI type is allowed.
2079         if (!Phi->getType()->isIntegerTy() &&
2080             !Phi->getType()->isFloatingPointTy() &&
2081             !Phi->getType()->isPointerTy()) {
2082           DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
2083           return false;
2084         }
2085
2086         // If this PHINode is not in the header block, then we know that we
2087         // can convert it to select during if-conversion. No need to check if
2088         // the PHIs in this block are induction or reduction variables.
2089         if (*bb != Header)
2090           continue;
2091
2092         // This is the value coming from the preheader.
2093         Value *StartValue = Phi->getIncomingValueForBlock(PreHeader);
2094         // Check if this is an induction variable.
2095         InductionKind IK = isInductionVariable(Phi);
2096
2097         if (IK_NoInduction != IK) {
2098           // Int inductions are special because we only allow one IV.
2099           if (IK == IK_IntInduction) {
2100             if (Induction) {
2101               DEBUG(dbgs() << "LV: Found too many inductions."<< *Phi <<"\n");
2102               return false;
2103             }
2104             Induction = Phi;
2105           }
2106
2107           DEBUG(dbgs() << "LV: Found an induction variable.\n");
2108           Inductions[Phi] = InductionInfo(StartValue, IK);
2109           continue;
2110         }
2111
2112         if (AddReductionVar(Phi, RK_IntegerAdd)) {
2113           DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
2114           continue;
2115         }
2116         if (AddReductionVar(Phi, RK_IntegerMult)) {
2117           DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n");
2118           continue;
2119         }
2120         if (AddReductionVar(Phi, RK_IntegerOr)) {
2121           DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n");
2122           continue;
2123         }
2124         if (AddReductionVar(Phi, RK_IntegerAnd)) {
2125           DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n");
2126           continue;
2127         }
2128         if (AddReductionVar(Phi, RK_IntegerXor)) {
2129           DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n");
2130           continue;
2131         }
2132         if (AddReductionVar(Phi, RK_FloatMult)) {
2133           DEBUG(dbgs() << "LV: Found an FMult reduction PHI."<< *Phi <<"\n");
2134           continue;
2135         }
2136         if (AddReductionVar(Phi, RK_FloatAdd)) {
2137           DEBUG(dbgs() << "LV: Found an FAdd reduction PHI."<< *Phi <<"\n");
2138           continue;
2139         }
2140
2141         DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
2142         return false;
2143       }// end of PHI handling
2144
2145       // We still don't handle functions.
2146       CallInst *CI = dyn_cast<CallInst>(it);
2147       if (CI && !isTriviallyVectorizableIntrinsic(it)) {
2148         DEBUG(dbgs() << "LV: Found a call site.\n");
2149         return false;
2150       }
2151
2152       // Check that the instruction return type is vectorizable.
2153       if (!VectorType::isValidElementType(it->getType()) &&
2154           !it->getType()->isVoidTy()) {
2155         DEBUG(dbgs() << "LV: Found unvectorizable type." << "\n");
2156         return false;
2157       }
2158
2159       // Check that the stored type is vectorizable.
2160       if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
2161         Type *T = ST->getValueOperand()->getType();
2162         if (!VectorType::isValidElementType(T))
2163           return false;
2164       }
2165
2166       // Reduction instructions are allowed to have exit users.
2167       // All other instructions must not have external users.
2168       if (!AllowedExit.count(it))
2169         //Check that all of the users of the loop are inside the BB.
2170         for (Value::use_iterator I = it->use_begin(), E = it->use_end();
2171              I != E; ++I) {
2172           Instruction *U = cast<Instruction>(*I);
2173           // This user may be a reduction exit value.
2174           if (!TheLoop->contains(U)) {
2175             DEBUG(dbgs() << "LV: Found an outside user for : "<< *U << "\n");
2176             return false;
2177           }
2178         }
2179     } // next instr.
2180
2181   }
2182
2183   if (!Induction) {
2184     DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
2185     assert(getInductionVars()->size() && "No induction variables");
2186   }
2187
2188   return true;
2189 }
2190
2191 void LoopVectorizationLegality::collectLoopUniforms() {
2192   // We now know that the loop is vectorizable!
2193   // Collect variables that will remain uniform after vectorization.
2194   std::vector<Value*> Worklist;
2195   BasicBlock *Latch = TheLoop->getLoopLatch();
2196
2197   // Start with the conditional branch and walk up the block.
2198   Worklist.push_back(Latch->getTerminator()->getOperand(0));
2199
2200   while (Worklist.size()) {
2201     Instruction *I = dyn_cast<Instruction>(Worklist.back());
2202     Worklist.pop_back();
2203
2204     // Look at instructions inside this loop.
2205     // Stop when reaching PHI nodes.
2206     // TODO: we need to follow values all over the loop, not only in this block.
2207     if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
2208       continue;
2209
2210     // This is a known uniform.
2211     Uniforms.insert(I);
2212
2213     // Insert all operands.
2214     for (int i = 0, Op = I->getNumOperands(); i < Op; ++i) {
2215       Worklist.push_back(I->getOperand(i));
2216     }
2217   }
2218 }
2219
2220 bool LoopVectorizationLegality::canVectorizeMemory() {
2221   typedef SmallVector<Value*, 16> ValueVector;
2222   typedef SmallPtrSet<Value*, 16> ValueSet;
2223   // Holds the Load and Store *instructions*.
2224   ValueVector Loads;
2225   ValueVector Stores;
2226   PtrRtCheck.Pointers.clear();
2227   PtrRtCheck.Need = false;
2228
2229   // For each block.
2230   for (Loop::block_iterator bb = TheLoop->block_begin(),
2231        be = TheLoop->block_end(); bb != be; ++bb) {
2232
2233     // Scan the BB and collect legal loads and stores.
2234     for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
2235          ++it) {
2236
2237       // If this is a load, save it. If this instruction can read from memory
2238       // but is not a load, then we quit. Notice that we don't handle function
2239       // calls that read or write.
2240       if (it->mayReadFromMemory()) {
2241         LoadInst *Ld = dyn_cast<LoadInst>(it);
2242         if (!Ld) return false;
2243         if (!Ld->isSimple()) {
2244           DEBUG(dbgs() << "LV: Found a non-simple load.\n");
2245           return false;
2246         }
2247         Loads.push_back(Ld);
2248         continue;
2249       }
2250
2251       // Save 'store' instructions. Abort if other instructions write to memory.
2252       if (it->mayWriteToMemory()) {
2253         StoreInst *St = dyn_cast<StoreInst>(it);
2254         if (!St) return false;
2255         if (!St->isSimple()) {
2256           DEBUG(dbgs() << "LV: Found a non-simple store.\n");
2257           return false;
2258         }
2259         Stores.push_back(St);
2260       }
2261     } // next instr.
2262   } // next block.
2263
2264   // Now we have two lists that hold the loads and the stores.
2265   // Next, we find the pointers that they use.
2266
2267   // Check if we see any stores. If there are no stores, then we don't
2268   // care if the pointers are *restrict*.
2269   if (!Stores.size()) {
2270     DEBUG(dbgs() << "LV: Found a read-only loop!\n");
2271     return true;
2272   }
2273
2274   // Holds the read and read-write *pointers* that we find.
2275   ValueVector Reads;
2276   ValueVector ReadWrites;
2277
2278   // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
2279   // multiple times on the same object. If the ptr is accessed twice, once
2280   // for read and once for write, it will only appear once (on the write
2281   // list). This is okay, since we are going to check for conflicts between
2282   // writes and between reads and writes, but not between reads and reads.
2283   ValueSet Seen;
2284
2285   ValueVector::iterator I, IE;
2286   for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
2287     StoreInst *ST = cast<StoreInst>(*I);
2288     Value* Ptr = ST->getPointerOperand();
2289
2290     if (isUniform(Ptr)) {
2291       DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
2292       return false;
2293     }
2294
2295     // If we did *not* see this pointer before, insert it to
2296     // the read-write list. At this phase it is only a 'write' list.
2297     if (Seen.insert(Ptr))
2298       ReadWrites.push_back(Ptr);
2299   }
2300
2301   for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
2302     LoadInst *LD = cast<LoadInst>(*I);
2303     Value* Ptr = LD->getPointerOperand();
2304     // If we did *not* see this pointer before, insert it to the
2305     // read list. If we *did* see it before, then it is already in
2306     // the read-write list. This allows us to vectorize expressions
2307     // such as A[i] += x;  Because the address of A[i] is a read-write
2308     // pointer. This only works if the index of A[i] is consecutive.
2309     // If the address of i is unknown (for example A[B[i]]) then we may
2310     // read a few words, modify, and write a few words, and some of the
2311     // words may be written to the same address.
2312     if (Seen.insert(Ptr) || 0 == isConsecutivePtr(Ptr))
2313       Reads.push_back(Ptr);
2314   }
2315
2316   // If we write (or read-write) to a single destination and there are no
2317   // other reads in this loop then is it safe to vectorize.
2318   if (ReadWrites.size() == 1 && Reads.size() == 0) {
2319     DEBUG(dbgs() << "LV: Found a write-only loop!\n");
2320     return true;
2321   }
2322
2323   // Find pointers with computable bounds. We are going to use this information
2324   // to place a runtime bound check.
2325   bool CanDoRT = true;
2326   for (I = ReadWrites.begin(), IE = ReadWrites.end(); I != IE; ++I)
2327     if (hasComputableBounds(*I)) {
2328       PtrRtCheck.insert(SE, TheLoop, *I);
2329       DEBUG(dbgs() << "LV: Found a runtime check ptr:" << **I <<"\n");
2330     } else {
2331       CanDoRT = false;
2332       break;
2333     }
2334   for (I = Reads.begin(), IE = Reads.end(); I != IE; ++I)
2335     if (hasComputableBounds(*I)) {
2336       PtrRtCheck.insert(SE, TheLoop, *I);
2337       DEBUG(dbgs() << "LV: Found a runtime check ptr:" << **I <<"\n");
2338     } else {
2339       CanDoRT = false;
2340       break;
2341     }
2342
2343   // Check that we did not collect too many pointers or found a
2344   // unsizeable pointer.
2345   if (!CanDoRT || PtrRtCheck.Pointers.size() > RuntimeMemoryCheckThreshold) {
2346     PtrRtCheck.reset();
2347     CanDoRT = false;
2348   }
2349
2350   if (CanDoRT) {
2351     DEBUG(dbgs() << "LV: We can perform a memory runtime check if needed.\n");
2352   }
2353
2354   bool NeedRTCheck = false;
2355
2356   // Now that the pointers are in two lists (Reads and ReadWrites), we
2357   // can check that there are no conflicts between each of the writes and
2358   // between the writes to the reads.
2359   ValueSet WriteObjects;
2360   ValueVector TempObjects;
2361
2362   // Check that the read-writes do not conflict with other read-write
2363   // pointers.
2364   bool AllWritesIdentified = true;
2365   for (I = ReadWrites.begin(), IE = ReadWrites.end(); I != IE; ++I) {
2366     GetUnderlyingObjects(*I, TempObjects, DL);
2367     for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end();
2368          it != e; ++it) {
2369       if (!isIdentifiedObject(*it)) {
2370         DEBUG(dbgs() << "LV: Found an unidentified write ptr:"<< **it <<"\n");
2371         NeedRTCheck = true;
2372         AllWritesIdentified = false;
2373       }
2374       if (!WriteObjects.insert(*it)) {
2375         DEBUG(dbgs() << "LV: Found a possible write-write reorder:"
2376               << **it <<"\n");
2377         return false;
2378       }
2379     }
2380     TempObjects.clear();
2381   }
2382
2383   /// Check that the reads don't conflict with the read-writes.
2384   for (I = Reads.begin(), IE = Reads.end(); I != IE; ++I) {
2385     GetUnderlyingObjects(*I, TempObjects, DL);
2386     for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end();
2387          it != e; ++it) {
2388       // If all of the writes are identified then we don't care if the read
2389       // pointer is identified or not.
2390       if (!AllWritesIdentified && !isIdentifiedObject(*it)) {
2391         DEBUG(dbgs() << "LV: Found an unidentified read ptr:"<< **it <<"\n");
2392         NeedRTCheck = true;
2393       }
2394       if (WriteObjects.count(*it)) {
2395         DEBUG(dbgs() << "LV: Found a possible read/write reorder:"
2396               << **it <<"\n");
2397         return false;
2398       }
2399     }
2400     TempObjects.clear();
2401   }
2402
2403   PtrRtCheck.Need = NeedRTCheck;
2404   if (NeedRTCheck && !CanDoRT) {
2405     DEBUG(dbgs() << "LV: We can't vectorize because we can't find " <<
2406           "the array bounds.\n");
2407     PtrRtCheck.reset();
2408     return false;
2409   }
2410
2411   DEBUG(dbgs() << "LV: We "<< (NeedRTCheck ? "" : "don't") <<
2412         " need a runtime memory check.\n");
2413   return true;
2414 }
2415
2416 bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi,
2417                                                 ReductionKind Kind) {
2418   if (Phi->getNumIncomingValues() != 2)
2419     return false;
2420
2421   // Reduction variables are only found in the loop header block.
2422   if (Phi->getParent() != TheLoop->getHeader())
2423     return false;
2424
2425   // Obtain the reduction start value from the value that comes from the loop
2426   // preheader.
2427   Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
2428
2429   // ExitInstruction is the single value which is used outside the loop.
2430   // We only allow for a single reduction value to be used outside the loop.
2431   // This includes users of the reduction, variables (which form a cycle
2432   // which ends in the phi node).
2433   Instruction *ExitInstruction = 0;
2434   // Indicates that we found a binary operation in our scan.
2435   bool FoundBinOp = false;
2436
2437   // Iter is our iterator. We start with the PHI node and scan for all of the
2438   // users of this instruction. All users must be instructions that can be
2439   // used as reduction variables (such as ADD). We may have a single
2440   // out-of-block user. The cycle must end with the original PHI.
2441   Instruction *Iter = Phi;
2442   while (true) {
2443     // If the instruction has no users then this is a broken
2444     // chain and can't be a reduction variable.
2445     if (Iter->use_empty())
2446       return false;
2447
2448     // Did we find a user inside this loop already ?
2449     bool FoundInBlockUser = false;
2450     // Did we reach the initial PHI node already ?
2451     bool FoundStartPHI = false;
2452
2453     // Is this a bin op ?
2454     FoundBinOp |= !isa<PHINode>(Iter);
2455
2456     // For each of the *users* of iter.
2457     for (Value::use_iterator it = Iter->use_begin(), e = Iter->use_end();
2458          it != e; ++it) {
2459       Instruction *U = cast<Instruction>(*it);
2460       // We already know that the PHI is a user.
2461       if (U == Phi) {
2462         FoundStartPHI = true;
2463         continue;
2464       }
2465
2466       // Check if we found the exit user.
2467       BasicBlock *Parent = U->getParent();
2468       if (!TheLoop->contains(Parent)) {
2469         // Exit if you find multiple outside users.
2470         if (ExitInstruction != 0)
2471           return false;
2472         ExitInstruction = Iter;
2473       }
2474
2475       // We allow in-loop PHINodes which are not the original reduction PHI
2476       // node. If this PHI is the only user of Iter (happens in IF w/ no ELSE
2477       // structure) then don't skip this PHI.
2478       if (isa<PHINode>(Iter) && isa<PHINode>(U) &&
2479           U->getParent() != TheLoop->getHeader() &&
2480           TheLoop->contains(U) &&
2481           Iter->getNumUses() > 1)
2482         continue;
2483
2484       // We can't have multiple inside users.
2485       if (FoundInBlockUser)
2486         return false;
2487       FoundInBlockUser = true;
2488
2489       // Any reduction instr must be of one of the allowed kinds.
2490       if (!isReductionInstr(U, Kind))
2491         return false;
2492
2493       // Reductions of instructions such as Div, and Sub is only
2494       // possible if the LHS is the reduction variable.
2495       if (!U->isCommutative() && !isa<PHINode>(U) && U->getOperand(0) != Iter)
2496         return false;
2497
2498       Iter = U;
2499     }
2500
2501     // We found a reduction var if we have reached the original
2502     // phi node and we only have a single instruction with out-of-loop
2503     // users.
2504     if (FoundStartPHI) {
2505       // This instruction is allowed to have out-of-loop users.
2506       AllowedExit.insert(ExitInstruction);
2507
2508       // Save the description of this reduction variable.
2509       ReductionDescriptor RD(RdxStart, ExitInstruction, Kind);
2510       Reductions[Phi] = RD;
2511       // We've ended the cycle. This is a reduction variable if we have an
2512       // outside user and it has a binary op.
2513       return FoundBinOp && ExitInstruction;
2514     }
2515   }
2516 }
2517
2518 bool
2519 LoopVectorizationLegality::isReductionInstr(Instruction *I,
2520                                             ReductionKind Kind) {
2521   bool FP = I->getType()->isFloatingPointTy();
2522   bool FastMath = (FP && I->isCommutative() && I->isAssociative());
2523
2524   switch (I->getOpcode()) {
2525   default:
2526     return false;
2527   case Instruction::PHI:
2528       if (FP && (Kind != RK_FloatMult && Kind != RK_FloatAdd))
2529         return false;
2530     // possibly.
2531     return true;
2532   case Instruction::Sub:
2533   case Instruction::Add:
2534     return Kind == RK_IntegerAdd;
2535   case Instruction::SDiv:
2536   case Instruction::UDiv:
2537   case Instruction::Mul:
2538     return Kind == RK_IntegerMult;
2539   case Instruction::And:
2540     return Kind == RK_IntegerAnd;
2541   case Instruction::Or:
2542     return Kind == RK_IntegerOr;
2543   case Instruction::Xor:
2544     return Kind == RK_IntegerXor;
2545   case Instruction::FMul:
2546     return Kind == RK_FloatMult && FastMath;
2547   case Instruction::FAdd:
2548     return Kind == RK_FloatAdd && FastMath;
2549    }
2550 }
2551
2552 LoopVectorizationLegality::InductionKind
2553 LoopVectorizationLegality::isInductionVariable(PHINode *Phi) {
2554   Type *PhiTy = Phi->getType();
2555   // We only handle integer and pointer inductions variables.
2556   if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
2557     return IK_NoInduction;
2558
2559   // Check that the PHI is consecutive and starts at zero.
2560   const SCEV *PhiScev = SE->getSCEV(Phi);
2561   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
2562   if (!AR) {
2563     DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
2564     return IK_NoInduction;
2565   }
2566   const SCEV *Step = AR->getStepRecurrence(*SE);
2567
2568   // Integer inductions need to have a stride of one.
2569   if (PhiTy->isIntegerTy()) {
2570     if (Step->isOne())
2571       return IK_IntInduction;
2572     if (Step->isAllOnesValue())
2573       return IK_ReverseIntInduction;
2574     return IK_NoInduction;
2575   }
2576
2577   // Calculate the pointer stride and check if it is consecutive.
2578   const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
2579   if (!C)
2580     return IK_NoInduction;
2581
2582   assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
2583   uint64_t Size = DL->getTypeAllocSize(PhiTy->getPointerElementType());
2584   if (C->getValue()->equalsInt(Size))
2585     return IK_PtrInduction;
2586
2587   return IK_NoInduction;
2588 }
2589
2590 bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
2591   Value *In0 = const_cast<Value*>(V);
2592   PHINode *PN = dyn_cast_or_null<PHINode>(In0);
2593   if (!PN)
2594     return false;
2595
2596   return Inductions.count(PN);
2597 }
2598
2599 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB)  {
2600   assert(TheLoop->contains(BB) && "Unknown block used");
2601
2602   // Blocks that do not dominate the latch need predication.
2603   BasicBlock* Latch = TheLoop->getLoopLatch();
2604   return !DT->dominates(BB, Latch);
2605 }
2606
2607 bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB) {
2608   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2609     // We don't predicate loads/stores at the moment.
2610     if (it->mayReadFromMemory() || it->mayWriteToMemory() || it->mayThrow())
2611       return false;
2612
2613     // The instructions below can trap.
2614     switch (it->getOpcode()) {
2615     default: continue;
2616     case Instruction::UDiv:
2617     case Instruction::SDiv:
2618     case Instruction::URem:
2619     case Instruction::SRem:
2620              return false;
2621     }
2622   }
2623
2624   return true;
2625 }
2626
2627 bool LoopVectorizationLegality::hasComputableBounds(Value *Ptr) {
2628   const SCEV *PhiScev = SE->getSCEV(Ptr);
2629   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
2630   if (!AR)
2631     return false;
2632
2633   return AR->isAffine();
2634 }
2635
2636 unsigned
2637 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize,
2638                                                       unsigned UserVF) {
2639   if (OptForSize && Legal->getRuntimePointerCheck()->Need) {
2640     DEBUG(dbgs() << "LV: Aborting. Runtime ptr check is required in Os.\n");
2641     return 1;
2642   }
2643
2644   // Find the trip count.
2645   unsigned TC = SE->getSmallConstantTripCount(TheLoop, TheLoop->getLoopLatch());
2646   DEBUG(dbgs() << "LV: Found trip count:"<<TC<<"\n");
2647
2648   unsigned WidestType = getWidestType();
2649   unsigned WidestRegister = TTI.getRegisterBitWidth(true);
2650   unsigned MaxVectorSize = WidestRegister / WidestType;
2651   DEBUG(dbgs() << "LV: The Widest type: " << WidestType << " bits.\n");
2652   DEBUG(dbgs() << "LV: The Widest register is:" << WidestRegister << "bits.\n");
2653
2654   if (MaxVectorSize == 0) {
2655     DEBUG(dbgs() << "LV: The target has no vector registers.\n");
2656     MaxVectorSize = 1;
2657   }
2658
2659   assert(MaxVectorSize <= 32 && "Did not expect to pack so many elements"
2660          " into one vector.");
2661
2662   unsigned VF = MaxVectorSize;
2663
2664   // If we optimize the program for size, avoid creating the tail loop.
2665   if (OptForSize) {
2666     // If we are unable to calculate the trip count then don't try to vectorize.
2667     if (TC < 2) {
2668       DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
2669       return 1;
2670     }
2671
2672     // Find the maximum SIMD width that can fit within the trip count.
2673     VF = TC % MaxVectorSize;
2674
2675     if (VF == 0)
2676       VF = MaxVectorSize;
2677
2678     // If the trip count that we found modulo the vectorization factor is not
2679     // zero then we require a tail.
2680     if (VF < 2) {
2681       DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
2682       return 1;
2683     }
2684   }
2685
2686   if (UserVF != 0) {
2687     assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
2688     DEBUG(dbgs() << "LV: Using user VF "<<UserVF<<".\n");
2689
2690     return UserVF;
2691   }
2692
2693   float Cost = expectedCost(1);
2694   unsigned Width = 1;
2695   DEBUG(dbgs() << "LV: Scalar loop costs: "<< (int)Cost << ".\n");
2696   for (unsigned i=2; i <= VF; i*=2) {
2697     // Notice that the vector loop needs to be executed less times, so
2698     // we need to divide the cost of the vector loops by the width of
2699     // the vector elements.
2700     float VectorCost = expectedCost(i) / (float)i;
2701     DEBUG(dbgs() << "LV: Vector loop of width "<< i << " costs: " <<
2702           (int)VectorCost << ".\n");
2703     if (VectorCost < Cost) {
2704       Cost = VectorCost;
2705       Width = i;
2706     }
2707   }
2708
2709   DEBUG(dbgs() << "LV: Selecting VF = : "<< Width << ".\n");
2710   return Width;
2711 }
2712
2713 unsigned LoopVectorizationCostModel::getWidestType() {
2714   unsigned MaxWidth = 8;
2715
2716   // For each block.
2717   for (Loop::block_iterator bb = TheLoop->block_begin(),
2718        be = TheLoop->block_end(); bb != be; ++bb) {
2719     BasicBlock *BB = *bb;
2720
2721     // For each instruction in the loop.
2722     for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2723       Type *T = it->getType();
2724
2725       // Only examine Loads, Stores and PHINodes.
2726       if (!isa<LoadInst>(it) && !isa<StoreInst>(it) && !isa<PHINode>(it))
2727         continue;
2728
2729       // Examine PHI nodes that are reduction variables.
2730       if (PHINode *PN = dyn_cast<PHINode>(it))
2731         if (!Legal->getReductionVars()->count(PN))
2732           continue;
2733
2734       // Examine the stored values.
2735       if (StoreInst *ST = dyn_cast<StoreInst>(it))
2736         T = ST->getValueOperand()->getType();
2737
2738       // Ignore stored/loaded pointer types.
2739       if (T->isPointerTy())
2740         continue;
2741
2742       MaxWidth = std::max(MaxWidth, T->getScalarSizeInBits());
2743     }
2744   }
2745
2746   return MaxWidth;
2747 }
2748
2749 unsigned
2750 LoopVectorizationCostModel::selectUnrollFactor(bool OptForSize,
2751                                                unsigned UserUF) {
2752   // Use the user preference, unless 'auto' is selected.
2753   if (UserUF != 0)
2754     return UserUF;
2755
2756   // When we optimize for size we don't unroll.
2757   if (OptForSize)
2758     return 1;
2759
2760   // Do not unroll loops with a relatively small trip count.
2761   unsigned TC = SE->getSmallConstantTripCount(TheLoop,
2762                                               TheLoop->getLoopLatch());
2763   if (TC > 1 && TC < TinyTripCountUnrollThreshold)
2764     return 1;
2765
2766   unsigned TargetVectorRegisters = TTI.getNumberOfRegisters(true);
2767   DEBUG(dbgs() << "LV: The target has " << TargetVectorRegisters <<
2768         " vector registers\n");
2769
2770   LoopVectorizationCostModel::RegisterUsage R = calculateRegisterUsage();
2771   // We divide by these constants so assume that we have at least one
2772   // instruction that uses at least one register.
2773   R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
2774   R.NumInstructions = std::max(R.NumInstructions, 1U);
2775
2776   // We calculate the unroll factor using the following formula.
2777   // Subtract the number of loop invariants from the number of available
2778   // registers. These registers are used by all of the unrolled instances.
2779   // Next, divide the remaining registers by the number of registers that is
2780   // required by the loop, in order to estimate how many parallel instances
2781   // fit without causing spills.
2782   unsigned UF = (TargetVectorRegisters - R.LoopInvariantRegs) / R.MaxLocalUsers;
2783
2784   // We don't want to unroll the loops to the point where they do not fit into
2785   // the decoded cache. Assume that we only allow 32 IR instructions.
2786   UF = std::min(UF, (MaxLoopSizeThreshold / R.NumInstructions));
2787
2788   // Clamp the unroll factor ranges to reasonable factors.
2789   unsigned MaxUnrollSize = TTI.getMaximumUnrollFactor();
2790   
2791   if (UF > MaxUnrollSize)
2792     UF = MaxUnrollSize;
2793   else if (UF < 1)
2794     UF = 1;
2795
2796   return UF;
2797 }
2798
2799 LoopVectorizationCostModel::RegisterUsage
2800 LoopVectorizationCostModel::calculateRegisterUsage() {
2801   // This function calculates the register usage by measuring the highest number
2802   // of values that are alive at a single location. Obviously, this is a very
2803   // rough estimation. We scan the loop in a topological order in order and
2804   // assign a number to each instruction. We use RPO to ensure that defs are
2805   // met before their users. We assume that each instruction that has in-loop
2806   // users starts an interval. We record every time that an in-loop value is
2807   // used, so we have a list of the first and last occurrences of each
2808   // instruction. Next, we transpose this data structure into a multi map that
2809   // holds the list of intervals that *end* at a specific location. This multi
2810   // map allows us to perform a linear search. We scan the instructions linearly
2811   // and record each time that a new interval starts, by placing it in a set.
2812   // If we find this value in the multi-map then we remove it from the set.
2813   // The max register usage is the maximum size of the set.
2814   // We also search for instructions that are defined outside the loop, but are
2815   // used inside the loop. We need this number separately from the max-interval
2816   // usage number because when we unroll, loop-invariant values do not take
2817   // more register.
2818   LoopBlocksDFS DFS(TheLoop);
2819   DFS.perform(LI);
2820
2821   RegisterUsage R;
2822   R.NumInstructions = 0;
2823
2824   // Each 'key' in the map opens a new interval. The values
2825   // of the map are the index of the 'last seen' usage of the
2826   // instruction that is the key.
2827   typedef DenseMap<Instruction*, unsigned> IntervalMap;
2828   // Maps instruction to its index.
2829   DenseMap<unsigned, Instruction*> IdxToInstr;
2830   // Marks the end of each interval.
2831   IntervalMap EndPoint;
2832   // Saves the list of instruction indices that are used in the loop.
2833   SmallSet<Instruction*, 8> Ends;
2834   // Saves the list of values that are used in the loop but are
2835   // defined outside the loop, such as arguments and constants.
2836   SmallPtrSet<Value*, 8> LoopInvariants;
2837
2838   unsigned Index = 0;
2839   for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
2840        be = DFS.endRPO(); bb != be; ++bb) {
2841     R.NumInstructions += (*bb)->size();
2842     for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
2843          ++it) {
2844       Instruction *I = it;
2845       IdxToInstr[Index++] = I;
2846
2847       // Save the end location of each USE.
2848       for (unsigned i = 0; i < I->getNumOperands(); ++i) {
2849         Value *U = I->getOperand(i);
2850         Instruction *Instr = dyn_cast<Instruction>(U);
2851
2852         // Ignore non-instruction values such as arguments, constants, etc.
2853         if (!Instr) continue;
2854
2855         // If this instruction is outside the loop then record it and continue.
2856         if (!TheLoop->contains(Instr)) {
2857           LoopInvariants.insert(Instr);
2858           continue;
2859         }
2860
2861         // Overwrite previous end points.
2862         EndPoint[Instr] = Index;
2863         Ends.insert(Instr);
2864       }
2865     }
2866   }
2867
2868   // Saves the list of intervals that end with the index in 'key'.
2869   typedef SmallVector<Instruction*, 2> InstrList;
2870   DenseMap<unsigned, InstrList> TransposeEnds;
2871
2872   // Transpose the EndPoints to a list of values that end at each index.
2873   for (IntervalMap::iterator it = EndPoint.begin(), e = EndPoint.end();
2874        it != e; ++it)
2875     TransposeEnds[it->second].push_back(it->first);
2876
2877   SmallSet<Instruction*, 8> OpenIntervals;
2878   unsigned MaxUsage = 0;
2879
2880
2881   DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
2882   for (unsigned int i = 0; i < Index; ++i) {
2883     Instruction *I = IdxToInstr[i];
2884     // Ignore instructions that are never used within the loop.
2885     if (!Ends.count(I)) continue;
2886
2887     // Remove all of the instructions that end at this location.
2888     InstrList &List = TransposeEnds[i];
2889     for (unsigned int j=0, e = List.size(); j < e; ++j)
2890       OpenIntervals.erase(List[j]);
2891
2892     // Count the number of live interals.
2893     MaxUsage = std::max(MaxUsage, OpenIntervals.size());
2894
2895     DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # " <<
2896           OpenIntervals.size() <<"\n");
2897
2898     // Add the current instruction to the list of open intervals.
2899     OpenIntervals.insert(I);
2900   }
2901
2902   unsigned Invariant = LoopInvariants.size();
2903   DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsage << " \n");
2904   DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << " \n");
2905   DEBUG(dbgs() << "LV(REG): LoopSize: " << R.NumInstructions << " \n");
2906
2907   R.LoopInvariantRegs = Invariant;
2908   R.MaxLocalUsers = MaxUsage;
2909   return R;
2910 }
2911
2912 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
2913   unsigned Cost = 0;
2914
2915   // For each block.
2916   for (Loop::block_iterator bb = TheLoop->block_begin(),
2917        be = TheLoop->block_end(); bb != be; ++bb) {
2918     unsigned BlockCost = 0;
2919     BasicBlock *BB = *bb;
2920
2921     // For each instruction in the old loop.
2922     for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2923       unsigned C = getInstructionCost(it, VF);
2924       Cost += C;
2925       DEBUG(dbgs() << "LV: Found an estimated cost of "<< C <<" for VF " <<
2926             VF << " For instruction: "<< *it << "\n");
2927     }
2928
2929     // We assume that if-converted blocks have a 50% chance of being executed.
2930     // When the code is scalar then some of the blocks are avoided due to CF.
2931     // When the code is vectorized we execute all code paths.
2932     if (Legal->blockNeedsPredication(*bb) && VF == 1)
2933       BlockCost /= 2;
2934
2935     Cost += BlockCost;
2936   }
2937
2938   return Cost;
2939 }
2940
2941 unsigned
2942 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
2943   // If we know that this instruction will remain uniform, check the cost of
2944   // the scalar version.
2945   if (Legal->isUniformAfterVectorization(I))
2946     VF = 1;
2947
2948   Type *RetTy = I->getType();
2949   Type *VectorTy = ToVectorTy(RetTy, VF);
2950
2951   // TODO: We need to estimate the cost of intrinsic calls.
2952   switch (I->getOpcode()) {
2953   case Instruction::GetElementPtr:
2954     // We mark this instruction as zero-cost because scalar GEPs are usually
2955     // lowered to the intruction addressing mode. At the moment we don't
2956     // generate vector geps.
2957     return 0;
2958   case Instruction::Br: {
2959     return TTI.getCFInstrCost(I->getOpcode());
2960   }
2961   case Instruction::PHI:
2962     //TODO: IF-converted IFs become selects.
2963     return 0;
2964   case Instruction::Add:
2965   case Instruction::FAdd:
2966   case Instruction::Sub:
2967   case Instruction::FSub:
2968   case Instruction::Mul:
2969   case Instruction::FMul:
2970   case Instruction::UDiv:
2971   case Instruction::SDiv:
2972   case Instruction::FDiv:
2973   case Instruction::URem:
2974   case Instruction::SRem:
2975   case Instruction::FRem:
2976   case Instruction::Shl:
2977   case Instruction::LShr:
2978   case Instruction::AShr:
2979   case Instruction::And:
2980   case Instruction::Or:
2981   case Instruction::Xor:
2982     return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy);
2983   case Instruction::Select: {
2984     SelectInst *SI = cast<SelectInst>(I);
2985     const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
2986     bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
2987     Type *CondTy = SI->getCondition()->getType();
2988     if (ScalarCond)
2989       CondTy = VectorType::get(CondTy, VF);
2990
2991     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
2992   }
2993   case Instruction::ICmp:
2994   case Instruction::FCmp: {
2995     Type *ValTy = I->getOperand(0)->getType();
2996     VectorTy = ToVectorTy(ValTy, VF);
2997     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy);
2998   }
2999   case Instruction::Store: {
3000     StoreInst *SI = cast<StoreInst>(I);
3001     Type *ValTy = SI->getValueOperand()->getType();
3002     VectorTy = ToVectorTy(ValTy, VF);
3003
3004     if (VF == 1)
3005       return TTI.getMemoryOpCost(I->getOpcode(), VectorTy,
3006                                    SI->getAlignment(),
3007                                    SI->getPointerAddressSpace());
3008
3009     // Scalarized stores.
3010     int Stride = Legal->isConsecutivePtr(SI->getPointerOperand());
3011     bool Reverse = Stride < 0;
3012     if (0 == Stride) {
3013       unsigned Cost = 0;
3014
3015       // The cost of extracting from the value vector and pointer vector.
3016       Type *PtrTy = ToVectorTy(I->getOperand(0)->getType(), VF);
3017       for (unsigned i = 0; i < VF; ++i) {
3018         Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, VectorTy,
3019                                        i);
3020         Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
3021       }
3022
3023       // The cost of the scalar stores.
3024       Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(),
3025                                        SI->getAlignment(),
3026                                        SI->getPointerAddressSpace());
3027       return Cost;
3028     }
3029
3030     // Wide stores.
3031     unsigned Cost = TTI.getMemoryOpCost(I->getOpcode(), VectorTy,
3032                                         SI->getAlignment(),
3033                                         SI->getPointerAddressSpace());
3034     if (Reverse)
3035       Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
3036                                   VectorTy, 0);
3037     return Cost;
3038   }
3039   case Instruction::Load: {
3040     LoadInst *LI = cast<LoadInst>(I);
3041
3042     if (VF == 1)
3043       return TTI.getMemoryOpCost(I->getOpcode(), VectorTy, LI->getAlignment(),
3044                                  LI->getPointerAddressSpace());
3045
3046     // Scalarized loads.
3047     int Stride = Legal->isConsecutivePtr(LI->getPointerOperand());
3048     bool Reverse = Stride < 0;
3049     if (0 == Stride) {
3050       unsigned Cost = 0;
3051       Type *PtrTy = ToVectorTy(I->getOperand(0)->getType(), VF);
3052
3053       // The cost of extracting from the pointer vector.
3054       for (unsigned i = 0; i < VF; ++i)
3055         Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
3056
3057       // The cost of inserting data to the result vector.
3058       for (unsigned i = 0; i < VF; ++i)
3059         Cost += TTI.getVectorInstrCost(Instruction::InsertElement, VectorTy, i);
3060
3061       // The cost of the scalar stores.
3062       Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), RetTy->getScalarType(),
3063                                        LI->getAlignment(),
3064                                        LI->getPointerAddressSpace());
3065       return Cost;
3066     }
3067
3068     // Wide loads.
3069     unsigned Cost = TTI.getMemoryOpCost(I->getOpcode(), VectorTy,
3070                                         LI->getAlignment(),
3071                                         LI->getPointerAddressSpace());
3072     if (Reverse)
3073       Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, 0);
3074     return Cost;
3075   }
3076   case Instruction::ZExt:
3077   case Instruction::SExt:
3078   case Instruction::FPToUI:
3079   case Instruction::FPToSI:
3080   case Instruction::FPExt:
3081   case Instruction::PtrToInt:
3082   case Instruction::IntToPtr:
3083   case Instruction::SIToFP:
3084   case Instruction::UIToFP:
3085   case Instruction::Trunc:
3086   case Instruction::FPTrunc:
3087   case Instruction::BitCast: {
3088     // We optimize the truncation of induction variable.
3089     // The cost of these is the same as the scalar operation.
3090     if (I->getOpcode() == Instruction::Trunc &&
3091         Legal->isInductionVariable(I->getOperand(0)))
3092       return TTI.getCastInstrCost(I->getOpcode(), I->getType(),
3093                                   I->getOperand(0)->getType());
3094
3095     Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
3096     return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
3097   }
3098   case Instruction::Call: {
3099     assert(isTriviallyVectorizableIntrinsic(I));
3100     IntrinsicInst *II = cast<IntrinsicInst>(I);
3101     Type *RetTy = ToVectorTy(II->getType(), VF);
3102     SmallVector<Type*, 4> Tys;
3103     for (unsigned i = 0, ie = II->getNumArgOperands(); i != ie; ++i)
3104       Tys.push_back(ToVectorTy(II->getArgOperand(i)->getType(), VF));
3105     return TTI.getIntrinsicInstrCost(II->getIntrinsicID(), RetTy, Tys);
3106   }
3107   default: {
3108     // We are scalarizing the instruction. Return the cost of the scalar
3109     // instruction, plus the cost of insert and extract into vector
3110     // elements, times the vector width.
3111     unsigned Cost = 0;
3112
3113     if (!RetTy->isVoidTy() && VF != 1) {
3114       unsigned InsCost = TTI.getVectorInstrCost(Instruction::InsertElement,
3115                                                 VectorTy);
3116       unsigned ExtCost = TTI.getVectorInstrCost(Instruction::ExtractElement,
3117                                                 VectorTy);
3118
3119       // The cost of inserting the results plus extracting each one of the
3120       // operands.
3121       Cost += VF * (InsCost + ExtCost * I->getNumOperands());
3122     }
3123
3124     // The cost of executing VF copies of the scalar instruction. This opcode
3125     // is unknown. Assume that it is the same as 'mul'.
3126     Cost += VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy);
3127     return Cost;
3128   }
3129   }// end of switch.
3130 }
3131
3132 Type* LoopVectorizationCostModel::ToVectorTy(Type *Scalar, unsigned VF) {
3133   if (Scalar->isVoidTy() || VF == 1)
3134     return Scalar;
3135   return VectorType::get(Scalar, VF);
3136 }
3137
3138 char LoopVectorize::ID = 0;
3139 static const char lv_name[] = "Loop Vectorization";
3140 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
3141 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3142 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
3143 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
3144 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
3145 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
3146
3147 namespace llvm {
3148   Pass *createLoopVectorizePass() {
3149     return new LoopVectorize();
3150   }
3151 }
3152
3153