ARM Cost Model: We need to detect the max bitwidth of types in the loop in order...
[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   Value *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   ///The first bypass block.
287   BasicBlock *LoopBypassBlock;
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 Value*
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   Value *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       Value *IsConflict = BinaryOperator::Create(Instruction::And, Cmp0, Cmp1,
922                                                  "found.conflict", Loc);
923       if (MemoryRuntimeCheck)
924         MemoryRuntimeCheck = BinaryOperator::Create(Instruction::Or,
925                                                     MemoryRuntimeCheck,
926                                                     IsConflict,
927                                                     "conflict.rdx", Loc);
928       else
929         MemoryRuntimeCheck = IsConflict;
930
931     }
932   }
933
934   return MemoryRuntimeCheck;
935 }
936
937 void
938 InnerLoopVectorizer::createEmptyLoop(LoopVectorizationLegality *Legal) {
939   /*
940    In this function we generate a new loop. The new loop will contain
941    the vectorized instructions while the old loop will continue to run the
942    scalar remainder.
943
944        [ ] <-- vector loop bypass.
945      /  |
946     /   v
947    |   [ ]     <-- vector pre header.
948    |    |
949    |    v
950    |   [  ] \
951    |   [  ]_|   <-- vector loop.
952    |    |
953     \   v
954       >[ ]   <--- middle-block.
955      /  |
956     /   v
957    |   [ ]     <--- new preheader.
958    |    |
959    |    v
960    |   [ ] \
961    |   [ ]_|   <-- old scalar loop to handle remainder.
962     \   |
963      \  v
964       >[ ]     <-- exit block.
965    ...
966    */
967
968   BasicBlock *OldBasicBlock = OrigLoop->getHeader();
969   BasicBlock *BypassBlock = OrigLoop->getLoopPreheader();
970   BasicBlock *ExitBlock = OrigLoop->getExitBlock();
971   assert(ExitBlock && "Must have an exit block");
972
973   // Some loops have a single integer induction variable, while other loops
974   // don't. One example is c++ iterators that often have multiple pointer
975   // induction variables. In the code below we also support a case where we
976   // don't have a single induction variable.
977   OldInduction = Legal->getInduction();
978   Type *IdxTy = OldInduction ? OldInduction->getType() :
979   DL->getIntPtrType(SE->getContext());
980
981   // Find the loop boundaries.
982   const SCEV *ExitCount = SE->getExitCount(OrigLoop, OrigLoop->getLoopLatch());
983   assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
984
985   // Get the total trip count from the count by adding 1.
986   ExitCount = SE->getAddExpr(ExitCount,
987                              SE->getConstant(ExitCount->getType(), 1));
988
989   // Expand the trip count and place the new instructions in the preheader.
990   // Notice that the pre-header does not change, only the loop body.
991   SCEVExpander Exp(*SE, "induction");
992
993   // Count holds the overall loop count (N).
994   Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
995                                    BypassBlock->getTerminator());
996
997   // The loop index does not have to start at Zero. Find the original start
998   // value from the induction PHI node. If we don't have an induction variable
999   // then we know that it starts at zero.
1000   Value *StartIdx = OldInduction ?
1001   OldInduction->getIncomingValueForBlock(BypassBlock):
1002   ConstantInt::get(IdxTy, 0);
1003
1004   assert(BypassBlock && "Invalid loop structure");
1005
1006   // Generate the code that checks in runtime if arrays overlap.
1007   Value *MemoryRuntimeCheck = addRuntimeCheck(Legal,
1008                                               BypassBlock->getTerminator());
1009
1010   // Split the single block loop into the two loop structure described above.
1011   BasicBlock *VectorPH =
1012   BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
1013   BasicBlock *VecBody =
1014   VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
1015   BasicBlock *MiddleBlock =
1016   VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
1017   BasicBlock *ScalarPH =
1018   MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
1019
1020   // This is the location in which we add all of the logic for bypassing
1021   // the new vector loop.
1022   Instruction *Loc = BypassBlock->getTerminator();
1023
1024   // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
1025   // inside the loop.
1026   Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
1027
1028   // Generate the induction variable.
1029   Induction = Builder.CreatePHI(IdxTy, 2, "index");
1030   // The loop step is equal to the vectorization factor (num of SIMD elements)
1031   // times the unroll factor (num of SIMD instructions).
1032   Constant *Step = ConstantInt::get(IdxTy, VF * UF);
1033
1034   // We may need to extend the index in case there is a type mismatch.
1035   // We know that the count starts at zero and does not overflow.
1036   if (Count->getType() != IdxTy) {
1037     // The exit count can be of pointer type. Convert it to the correct
1038     // integer type.
1039     if (ExitCount->getType()->isPointerTy())
1040       Count = CastInst::CreatePointerCast(Count, IdxTy, "ptrcnt.to.int", Loc);
1041     else
1042       Count = CastInst::CreateZExtOrBitCast(Count, IdxTy, "zext.cnt", Loc);
1043   }
1044
1045   // Add the start index to the loop count to get the new end index.
1046   Value *IdxEnd = BinaryOperator::CreateAdd(Count, StartIdx, "end.idx", Loc);
1047
1048   // Now we need to generate the expression for N - (N % VF), which is
1049   // the part that the vectorized body will execute.
1050   Value *R = BinaryOperator::CreateURem(Count, Step, "n.mod.vf", Loc);
1051   Value *CountRoundDown = BinaryOperator::CreateSub(Count, R, "n.vec", Loc);
1052   Value *IdxEndRoundDown = BinaryOperator::CreateAdd(CountRoundDown, StartIdx,
1053                                                      "end.idx.rnd.down", Loc);
1054
1055   // Now, compare the new count to zero. If it is zero skip the vector loop and
1056   // jump to the scalar loop.
1057   Value *Cmp = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
1058                                IdxEndRoundDown,
1059                                StartIdx,
1060                                "cmp.zero", Loc);
1061
1062   // If we are using memory runtime checks, include them in.
1063   if (MemoryRuntimeCheck)
1064     Cmp = BinaryOperator::Create(Instruction::Or, Cmp, MemoryRuntimeCheck,
1065                                  "CntOrMem", Loc);
1066
1067   BranchInst::Create(MiddleBlock, VectorPH, Cmp, Loc);
1068   // Remove the old terminator.
1069   Loc->eraseFromParent();
1070
1071   // We are going to resume the execution of the scalar loop.
1072   // Go over all of the induction variables that we found and fix the
1073   // PHIs that are left in the scalar version of the loop.
1074   // The starting values of PHI nodes depend on the counter of the last
1075   // iteration in the vectorized loop.
1076   // If we come from a bypass edge then we need to start from the original
1077   // start value.
1078
1079   // This variable saves the new starting index for the scalar loop.
1080   PHINode *ResumeIndex = 0;
1081   LoopVectorizationLegality::InductionList::iterator I, E;
1082   LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
1083   for (I = List->begin(), E = List->end(); I != E; ++I) {
1084     PHINode *OrigPhi = I->first;
1085     LoopVectorizationLegality::InductionInfo II = I->second;
1086     PHINode *ResumeVal = PHINode::Create(OrigPhi->getType(), 2, "resume.val",
1087                                          MiddleBlock->getTerminator());
1088     Value *EndValue = 0;
1089     switch (II.IK) {
1090     case LoopVectorizationLegality::IK_NoInduction:
1091       llvm_unreachable("Unknown induction");
1092     case LoopVectorizationLegality::IK_IntInduction: {
1093       // Handle the integer induction counter:
1094       assert(OrigPhi->getType()->isIntegerTy() && "Invalid type");
1095       assert(OrigPhi == OldInduction && "Unknown integer PHI");
1096       // We know what the end value is.
1097       EndValue = IdxEndRoundDown;
1098       // We also know which PHI node holds it.
1099       ResumeIndex = ResumeVal;
1100       break;
1101     }
1102     case LoopVectorizationLegality::IK_ReverseIntInduction: {
1103       // Convert the CountRoundDown variable to the PHI size.
1104       unsigned CRDSize = CountRoundDown->getType()->getScalarSizeInBits();
1105       unsigned IISize = II.StartValue->getType()->getScalarSizeInBits();
1106       Value *CRD = CountRoundDown;
1107       if (CRDSize > IISize)
1108         CRD = CastInst::Create(Instruction::Trunc, CountRoundDown,
1109                                II.StartValue->getType(),
1110                                "tr.crd", BypassBlock->getTerminator());
1111       else if (CRDSize < IISize)
1112         CRD = CastInst::Create(Instruction::SExt, CountRoundDown,
1113                                II.StartValue->getType(),
1114                                "sext.crd", BypassBlock->getTerminator());
1115       // Handle reverse integer induction counter:
1116       EndValue = BinaryOperator::CreateSub(II.StartValue, CRD, "rev.ind.end",
1117                                            BypassBlock->getTerminator());
1118       break;
1119     }
1120     case LoopVectorizationLegality::IK_PtrInduction: {
1121       // For pointer induction variables, calculate the offset using
1122       // the end index.
1123       EndValue = GetElementPtrInst::Create(II.StartValue, CountRoundDown,
1124                                            "ptr.ind.end",
1125                                            BypassBlock->getTerminator());
1126       break;
1127     }
1128     }// end of case
1129
1130     // The new PHI merges the original incoming value, in case of a bypass,
1131     // or the value at the end of the vectorized loop.
1132     ResumeVal->addIncoming(II.StartValue, BypassBlock);
1133     ResumeVal->addIncoming(EndValue, VecBody);
1134
1135     // Fix the scalar body counter (PHI node).
1136     unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
1137     OrigPhi->setIncomingValue(BlockIdx, ResumeVal);
1138   }
1139
1140   // If we are generating a new induction variable then we also need to
1141   // generate the code that calculates the exit value. This value is not
1142   // simply the end of the counter because we may skip the vectorized body
1143   // in case of a runtime check.
1144   if (!OldInduction){
1145     assert(!ResumeIndex && "Unexpected resume value found");
1146     ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val",
1147                                   MiddleBlock->getTerminator());
1148     ResumeIndex->addIncoming(StartIdx, BypassBlock);
1149     ResumeIndex->addIncoming(IdxEndRoundDown, VecBody);
1150   }
1151
1152   // Make sure that we found the index where scalar loop needs to continue.
1153   assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() &&
1154          "Invalid resume Index");
1155
1156   // Add a check in the middle block to see if we have completed
1157   // all of the iterations in the first vector loop.
1158   // If (N - N%VF) == N, then we *don't* need to run the remainder.
1159   Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd,
1160                                 ResumeIndex, "cmp.n",
1161                                 MiddleBlock->getTerminator());
1162
1163   BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
1164   // Remove the old terminator.
1165   MiddleBlock->getTerminator()->eraseFromParent();
1166
1167   // Create i+1 and fill the PHINode.
1168   Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
1169   Induction->addIncoming(StartIdx, VectorPH);
1170   Induction->addIncoming(NextIdx, VecBody);
1171   // Create the compare.
1172   Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown);
1173   Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
1174
1175   // Now we have two terminators. Remove the old one from the block.
1176   VecBody->getTerminator()->eraseFromParent();
1177
1178   // Get ready to start creating new instructions into the vectorized body.
1179   Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
1180
1181   // Create and register the new vector loop.
1182   Loop* Lp = new Loop();
1183   Loop *ParentLoop = OrigLoop->getParentLoop();
1184
1185   // Insert the new loop into the loop nest and register the new basic blocks.
1186   if (ParentLoop) {
1187     ParentLoop->addChildLoop(Lp);
1188     ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase());
1189     ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase());
1190     ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase());
1191   } else {
1192     LI->addTopLevelLoop(Lp);
1193   }
1194
1195   Lp->addBasicBlockToLoop(VecBody, LI->getBase());
1196
1197   // Save the state.
1198   LoopVectorPreHeader = VectorPH;
1199   LoopScalarPreHeader = ScalarPH;
1200   LoopMiddleBlock = MiddleBlock;
1201   LoopExitBlock = ExitBlock;
1202   LoopVectorBody = VecBody;
1203   LoopScalarBody = OldBasicBlock;
1204   LoopBypassBlock = BypassBlock;
1205 }
1206
1207 /// This function returns the identity element (or neutral element) for
1208 /// the operation K.
1209 static Constant*
1210 getReductionIdentity(LoopVectorizationLegality::ReductionKind K, Type *Tp) {
1211   switch (K) {
1212   case LoopVectorizationLegality:: RK_IntegerXor:
1213   case LoopVectorizationLegality:: RK_IntegerAdd:
1214   case LoopVectorizationLegality:: RK_IntegerOr:
1215     // Adding, Xoring, Oring zero to a number does not change it.
1216     return ConstantInt::get(Tp, 0);
1217   case LoopVectorizationLegality:: RK_IntegerMult:
1218     // Multiplying a number by 1 does not change it.
1219     return ConstantInt::get(Tp, 1);
1220   case LoopVectorizationLegality:: RK_IntegerAnd:
1221     // AND-ing a number with an all-1 value does not change it.
1222     return ConstantInt::get(Tp, -1, true);
1223   case LoopVectorizationLegality:: RK_FloatMult:
1224     // Multiplying a number by 1 does not change it.
1225     return ConstantFP::get(Tp, 1.0L);
1226   case LoopVectorizationLegality:: RK_FloatAdd:
1227     // Adding zero to a number does not change it.
1228     return ConstantFP::get(Tp, 0.0L);
1229   default:
1230     llvm_unreachable("Unknown reduction kind");
1231   }
1232 }
1233
1234 static bool
1235 isTriviallyVectorizableIntrinsic(Instruction *Inst) {
1236   IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst);
1237   if (!II)
1238     return false;
1239   switch (II->getIntrinsicID()) {
1240   case Intrinsic::sqrt:
1241   case Intrinsic::sin:
1242   case Intrinsic::cos:
1243   case Intrinsic::exp:
1244   case Intrinsic::exp2:
1245   case Intrinsic::log:
1246   case Intrinsic::log10:
1247   case Intrinsic::log2:
1248   case Intrinsic::fabs:
1249   case Intrinsic::floor:
1250   case Intrinsic::ceil:
1251   case Intrinsic::trunc:
1252   case Intrinsic::rint:
1253   case Intrinsic::nearbyint:
1254   case Intrinsic::pow:
1255   case Intrinsic::fma:
1256   case Intrinsic::fmuladd:
1257     return true;
1258   default:
1259     return false;
1260   }
1261   return false;
1262 }
1263
1264 /// This function translates the reduction kind to an LLVM binary operator.
1265 static Instruction::BinaryOps
1266 getReductionBinOp(LoopVectorizationLegality::ReductionKind Kind) {
1267   switch (Kind) {
1268     case LoopVectorizationLegality::RK_IntegerAdd:
1269       return Instruction::Add;
1270     case LoopVectorizationLegality::RK_IntegerMult:
1271       return Instruction::Mul;
1272     case LoopVectorizationLegality::RK_IntegerOr:
1273       return Instruction::Or;
1274     case LoopVectorizationLegality::RK_IntegerAnd:
1275       return Instruction::And;
1276     case LoopVectorizationLegality::RK_IntegerXor:
1277       return Instruction::Xor;
1278     case LoopVectorizationLegality::RK_FloatMult:
1279       return Instruction::FMul;
1280     case LoopVectorizationLegality::RK_FloatAdd:
1281       return Instruction::FAdd;
1282     default:
1283       llvm_unreachable("Unknown reduction operation");
1284   }
1285 }
1286
1287 void
1288 InnerLoopVectorizer::vectorizeLoop(LoopVectorizationLegality *Legal) {
1289   //===------------------------------------------------===//
1290   //
1291   // Notice: any optimization or new instruction that go
1292   // into the code below should be also be implemented in
1293   // the cost-model.
1294   //
1295   //===------------------------------------------------===//
1296   BasicBlock &BB = *OrigLoop->getHeader();
1297   Constant *Zero =
1298   ConstantInt::get(IntegerType::getInt32Ty(BB.getContext()), 0);
1299
1300   // In order to support reduction variables we need to be able to vectorize
1301   // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
1302   // stages. First, we create a new vector PHI node with no incoming edges.
1303   // We use this value when we vectorize all of the instructions that use the
1304   // PHI. Next, after all of the instructions in the block are complete we
1305   // add the new incoming edges to the PHI. At this point all of the
1306   // instructions in the basic block are vectorized, so we can use them to
1307   // construct the PHI.
1308   PhiVector RdxPHIsToFix;
1309
1310   // Scan the loop in a topological order to ensure that defs are vectorized
1311   // before users.
1312   LoopBlocksDFS DFS(OrigLoop);
1313   DFS.perform(LI);
1314
1315   // Vectorize all of the blocks in the original loop.
1316   for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
1317        be = DFS.endRPO(); bb != be; ++bb)
1318     vectorizeBlockInLoop(Legal, *bb, &RdxPHIsToFix);
1319
1320   // At this point every instruction in the original loop is widened to
1321   // a vector form. We are almost done. Now, we need to fix the PHI nodes
1322   // that we vectorized. The PHI nodes are currently empty because we did
1323   // not want to introduce cycles. Notice that the remaining PHI nodes
1324   // that we need to fix are reduction variables.
1325
1326   // Create the 'reduced' values for each of the induction vars.
1327   // The reduced values are the vector values that we scalarize and combine
1328   // after the loop is finished.
1329   for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
1330        it != e; ++it) {
1331     PHINode *RdxPhi = *it;
1332     assert(RdxPhi && "Unable to recover vectorized PHI");
1333
1334     // Find the reduction variable descriptor.
1335     assert(Legal->getReductionVars()->count(RdxPhi) &&
1336            "Unable to find the reduction variable");
1337     LoopVectorizationLegality::ReductionDescriptor RdxDesc =
1338     (*Legal->getReductionVars())[RdxPhi];
1339
1340     // We need to generate a reduction vector from the incoming scalar.
1341     // To do so, we need to generate the 'identity' vector and overide
1342     // one of the elements with the incoming scalar reduction. We need
1343     // to do it in the vector-loop preheader.
1344     Builder.SetInsertPoint(LoopBypassBlock->getTerminator());
1345
1346     // This is the vector-clone of the value that leaves the loop.
1347     VectorParts &VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
1348     Type *VecTy = VectorExit[0]->getType();
1349
1350     // Find the reduction identity variable. Zero for addition, or, xor,
1351     // one for multiplication, -1 for And.
1352     Constant *Iden = getReductionIdentity(RdxDesc.Kind, VecTy->getScalarType());
1353     Constant *Identity = ConstantVector::getSplat(VF, Iden);
1354
1355     // This vector is the Identity vector where the first element is the
1356     // incoming scalar reduction.
1357     Value *VectorStart = Builder.CreateInsertElement(Identity,
1358                                                      RdxDesc.StartValue, Zero);
1359
1360     // Fix the vector-loop phi.
1361     // We created the induction variable so we know that the
1362     // preheader is the first entry.
1363     BasicBlock *VecPreheader = Induction->getIncomingBlock(0);
1364
1365     // Reductions do not have to start at zero. They can start with
1366     // any loop invariant values.
1367     VectorParts &VecRdxPhi = WidenMap.get(RdxPhi);
1368     BasicBlock *Latch = OrigLoop->getLoopLatch();
1369     Value *LoopVal = RdxPhi->getIncomingValueForBlock(Latch);
1370     VectorParts &Val = getVectorValue(LoopVal);
1371     for (unsigned part = 0; part < UF; ++part) {
1372       // Make sure to add the reduction stat value only to the 
1373       // first unroll part.
1374       Value *StartVal = (part == 0) ? VectorStart : Identity;
1375       cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal, VecPreheader);
1376       cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part], LoopVectorBody);
1377     }
1378
1379     // Before each round, move the insertion point right between
1380     // the PHIs and the values we are going to write.
1381     // This allows us to write both PHINodes and the extractelement
1382     // instructions.
1383     Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
1384
1385     VectorParts RdxParts;
1386     for (unsigned part = 0; part < UF; ++part) {
1387       // This PHINode contains the vectorized reduction variable, or
1388       // the initial value vector, if we bypass the vector loop.
1389       VectorParts &RdxExitVal = getVectorValue(RdxDesc.LoopExitInstr);
1390       PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
1391       Value *StartVal = (part == 0) ? VectorStart : Identity;
1392       NewPhi->addIncoming(StartVal, LoopBypassBlock);
1393       NewPhi->addIncoming(RdxExitVal[part], LoopVectorBody);
1394       RdxParts.push_back(NewPhi);
1395     }
1396
1397     // Reduce all of the unrolled parts into a single vector.
1398     Value *ReducedPartRdx = RdxParts[0];
1399     for (unsigned part = 1; part < UF; ++part) {
1400       Instruction::BinaryOps Op = getReductionBinOp(RdxDesc.Kind);
1401       ReducedPartRdx = Builder.CreateBinOp(Op, RdxParts[part], ReducedPartRdx,
1402                                            "bin.rdx");
1403     }
1404
1405     // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
1406     // and vector ops, reducing the set of values being computed by half each
1407     // round.
1408     assert(isPowerOf2_32(VF) &&
1409            "Reduction emission only supported for pow2 vectors!");
1410     Value *TmpVec = ReducedPartRdx;
1411     SmallVector<Constant*, 32> ShuffleMask(VF, 0);
1412     for (unsigned i = VF; i != 1; i >>= 1) {
1413       // Move the upper half of the vector to the lower half.
1414       for (unsigned j = 0; j != i/2; ++j)
1415         ShuffleMask[j] = Builder.getInt32(i/2 + j);
1416
1417       // Fill the rest of the mask with undef.
1418       std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
1419                 UndefValue::get(Builder.getInt32Ty()));
1420
1421       Value *Shuf =
1422         Builder.CreateShuffleVector(TmpVec,
1423                                     UndefValue::get(TmpVec->getType()),
1424                                     ConstantVector::get(ShuffleMask),
1425                                     "rdx.shuf");
1426
1427       Instruction::BinaryOps Op = getReductionBinOp(RdxDesc.Kind);
1428       TmpVec = Builder.CreateBinOp(Op, TmpVec, Shuf, "bin.rdx");
1429     }
1430
1431     // The result is in the first element of the vector.
1432     Value *Scalar0 = Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
1433
1434     // Now, we need to fix the users of the reduction variable
1435     // inside and outside of the scalar remainder loop.
1436     // We know that the loop is in LCSSA form. We need to update the
1437     // PHI nodes in the exit blocks.
1438     for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
1439          LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
1440       PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
1441       if (!LCSSAPhi) continue;
1442
1443       // All PHINodes need to have a single entry edge, or two if
1444       // we already fixed them.
1445       assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
1446
1447       // We found our reduction value exit-PHI. Update it with the
1448       // incoming bypass edge.
1449       if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
1450         // Add an edge coming from the bypass.
1451         LCSSAPhi->addIncoming(Scalar0, LoopMiddleBlock);
1452         break;
1453       }
1454     }// end of the LCSSA phi scan.
1455
1456     // Fix the scalar loop reduction variable with the incoming reduction sum
1457     // from the vector body and from the backedge value.
1458     int IncomingEdgeBlockIdx =
1459     (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
1460     assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
1461     // Pick the other block.
1462     int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
1463     (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, Scalar0);
1464     (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
1465   }// end of for each redux variable.
1466
1467   // The Loop exit block may have single value PHI nodes where the incoming
1468   // value is 'undef'. While vectorizing we only handled real values that
1469   // were defined inside the loop. Here we handle the 'undef case'.
1470   // See PR14725.
1471   for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
1472        LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
1473     PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
1474     if (!LCSSAPhi) continue;
1475     if (LCSSAPhi->getNumIncomingValues() == 1)
1476       LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
1477                             LoopMiddleBlock);
1478   }
1479 }
1480
1481 InnerLoopVectorizer::VectorParts
1482 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
1483   assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
1484          "Invalid edge");
1485
1486   VectorParts SrcMask = createBlockInMask(Src);
1487
1488   // The terminator has to be a branch inst!
1489   BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
1490   assert(BI && "Unexpected terminator found");
1491
1492   if (BI->isConditional()) {
1493     VectorParts EdgeMask = getVectorValue(BI->getCondition());
1494
1495     if (BI->getSuccessor(0) != Dst)
1496       for (unsigned part = 0; part < UF; ++part)
1497         EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
1498
1499     for (unsigned part = 0; part < UF; ++part)
1500       EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
1501     return EdgeMask;
1502   }
1503
1504   return SrcMask;
1505 }
1506
1507 InnerLoopVectorizer::VectorParts
1508 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
1509   assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
1510
1511   // Loop incoming mask is all-one.
1512   if (OrigLoop->getHeader() == BB) {
1513     Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
1514     return getVectorValue(C);
1515   }
1516
1517   // This is the block mask. We OR all incoming edges, and with zero.
1518   Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
1519   VectorParts BlockMask = getVectorValue(Zero);
1520
1521   // For each pred:
1522   for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
1523     VectorParts EM = createEdgeMask(*it, BB);
1524     for (unsigned part = 0; part < UF; ++part)
1525       BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
1526   }
1527
1528   return BlockMask;
1529 }
1530
1531 void
1532 InnerLoopVectorizer::vectorizeBlockInLoop(LoopVectorizationLegality *Legal,
1533                                           BasicBlock *BB, PhiVector *PV) {
1534   Constant *Zero = Builder.getInt32(0);
1535
1536   // For each instruction in the old loop.
1537   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
1538     VectorParts &Entry = WidenMap.get(it);
1539     switch (it->getOpcode()) {
1540     case Instruction::Br:
1541       // Nothing to do for PHIs and BR, since we already took care of the
1542       // loop control flow instructions.
1543       continue;
1544     case Instruction::PHI:{
1545       PHINode* P = cast<PHINode>(it);
1546       // Handle reduction variables:
1547       if (Legal->getReductionVars()->count(P)) {
1548         for (unsigned part = 0; part < UF; ++part) {
1549           // This is phase one of vectorizing PHIs.
1550           Type *VecTy = VectorType::get(it->getType(), VF);
1551           Entry[part] = PHINode::Create(VecTy, 2, "vec.phi",
1552                                         LoopVectorBody-> getFirstInsertionPt());
1553         }
1554         PV->push_back(P);
1555         continue;
1556       }
1557
1558       // Check for PHI nodes that are lowered to vector selects.
1559       if (P->getParent() != OrigLoop->getHeader()) {
1560         // We know that all PHIs in non header blocks are converted into
1561         // selects, so we don't have to worry about the insertion order and we
1562         // can just use the builder.
1563
1564         // At this point we generate the predication tree. There may be
1565         // duplications since this is a simple recursive scan, but future
1566         // optimizations will clean it up.
1567         VectorParts Cond = createEdgeMask(P->getIncomingBlock(0),
1568                                                P->getParent());
1569         
1570         for (unsigned part = 0; part < UF; ++part) {
1571         VectorParts &In0 = getVectorValue(P->getIncomingValue(0));
1572         VectorParts &In1 = getVectorValue(P->getIncomingValue(1));
1573           Entry[part] = Builder.CreateSelect(Cond[part], In0[part], In1[part],
1574                                              "predphi");
1575         }
1576         continue;
1577       }
1578
1579       // This PHINode must be an induction variable.
1580       // Make sure that we know about it.
1581       assert(Legal->getInductionVars()->count(P) &&
1582              "Not an induction variable");
1583
1584       LoopVectorizationLegality::InductionInfo II =
1585         Legal->getInductionVars()->lookup(P);
1586
1587       switch (II.IK) {
1588       case LoopVectorizationLegality::IK_NoInduction:
1589         llvm_unreachable("Unknown induction");
1590       case LoopVectorizationLegality::IK_IntInduction: {
1591         assert(P == OldInduction && "Unexpected PHI");
1592         Value *Broadcasted = getBroadcastInstrs(Induction);
1593         // After broadcasting the induction variable we need to make the
1594         // vector consecutive by adding 0, 1, 2 ...
1595         for (unsigned part = 0; part < UF; ++part)
1596           Entry[part] = getConsecutiveVector(Broadcasted, VF * part, false);
1597         continue;
1598       }
1599       case LoopVectorizationLegality::IK_ReverseIntInduction:
1600       case LoopVectorizationLegality::IK_PtrInduction:
1601         // Handle reverse integer and pointer inductions.
1602         Value *StartIdx = 0;
1603         // If we have a single integer induction variable then use it.
1604         // Otherwise, start counting at zero.
1605         if (OldInduction) {
1606           LoopVectorizationLegality::InductionInfo OldII =
1607             Legal->getInductionVars()->lookup(OldInduction);
1608           StartIdx = OldII.StartValue;
1609         } else {
1610           StartIdx = ConstantInt::get(Induction->getType(), 0);
1611         }
1612         // This is the normalized GEP that starts counting at zero.
1613         Value *NormalizedIdx = Builder.CreateSub(Induction, StartIdx,
1614                                                  "normalized.idx");
1615
1616         // Handle the reverse integer induction variable case.
1617         if (LoopVectorizationLegality::IK_ReverseIntInduction == II.IK) {
1618           IntegerType *DstTy = cast<IntegerType>(II.StartValue->getType());
1619           Value *CNI = Builder.CreateSExtOrTrunc(NormalizedIdx, DstTy,
1620                                                  "resize.norm.idx");
1621           Value *ReverseInd  = Builder.CreateSub(II.StartValue, CNI,
1622                                                  "reverse.idx");
1623
1624           // This is a new value so do not hoist it out.
1625           Value *Broadcasted = getBroadcastInstrs(ReverseInd);
1626           // After broadcasting the induction variable we need to make the
1627           // vector consecutive by adding  ... -3, -2, -1, 0.
1628           for (unsigned part = 0; part < UF; ++part)
1629             Entry[part] = getConsecutiveVector(Broadcasted, -VF * part, true);
1630           continue;
1631         }
1632
1633         // Handle the pointer induction variable case.
1634         assert(P->getType()->isPointerTy() && "Unexpected type.");
1635
1636         // This is the vector of results. Notice that we don't generate
1637         // vector geps because scalar geps result in better code.
1638         for (unsigned part = 0; part < UF; ++part) {
1639           Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
1640           for (unsigned int i = 0; i < VF; ++i) {
1641             Constant *Idx = ConstantInt::get(Induction->getType(),
1642                                              i + part * VF);
1643             Value *GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx,
1644                                                  "gep.idx");
1645             Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
1646                                                "next.gep");
1647             VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
1648                                                  Builder.getInt32(i),
1649                                                  "insert.gep");
1650           }
1651           Entry[part] = VecVal;
1652         }
1653         continue;
1654       }
1655
1656     }// End of PHI.
1657
1658     case Instruction::Add:
1659     case Instruction::FAdd:
1660     case Instruction::Sub:
1661     case Instruction::FSub:
1662     case Instruction::Mul:
1663     case Instruction::FMul:
1664     case Instruction::UDiv:
1665     case Instruction::SDiv:
1666     case Instruction::FDiv:
1667     case Instruction::URem:
1668     case Instruction::SRem:
1669     case Instruction::FRem:
1670     case Instruction::Shl:
1671     case Instruction::LShr:
1672     case Instruction::AShr:
1673     case Instruction::And:
1674     case Instruction::Or:
1675     case Instruction::Xor: {
1676       // Just widen binops.
1677       BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
1678       VectorParts &A = getVectorValue(it->getOperand(0));
1679       VectorParts &B = getVectorValue(it->getOperand(1));
1680
1681       // Use this vector value for all users of the original instruction.
1682       for (unsigned Part = 0; Part < UF; ++Part) {
1683         Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
1684
1685         // Update the NSW, NUW and Exact flags. Notice: V can be an Undef.
1686         BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V);
1687         if (VecOp && isa<OverflowingBinaryOperator>(BinOp)) {
1688           VecOp->setHasNoSignedWrap(BinOp->hasNoSignedWrap());
1689           VecOp->setHasNoUnsignedWrap(BinOp->hasNoUnsignedWrap());
1690         }
1691         if (VecOp && isa<PossiblyExactOperator>(VecOp))
1692           VecOp->setIsExact(BinOp->isExact());
1693
1694         Entry[Part] = V;
1695       }
1696       break;
1697     }
1698     case Instruction::Select: {
1699       // Widen selects.
1700       // If the selector is loop invariant we can create a select
1701       // instruction with a scalar condition. Otherwise, use vector-select.
1702       bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)),
1703                                                OrigLoop);
1704
1705       // The condition can be loop invariant  but still defined inside the
1706       // loop. This means that we can't just use the original 'cond' value.
1707       // We have to take the 'vectorized' value and pick the first lane.
1708       // Instcombine will make this a no-op.
1709       VectorParts &Cond = getVectorValue(it->getOperand(0));
1710       VectorParts &Op0  = getVectorValue(it->getOperand(1));
1711       VectorParts &Op1  = getVectorValue(it->getOperand(2));
1712       Value *ScalarCond = Builder.CreateExtractElement(Cond[0],
1713                                                        Builder.getInt32(0));
1714       for (unsigned Part = 0; Part < UF; ++Part) {
1715         Entry[Part] = Builder.CreateSelect(
1716           InvariantCond ? ScalarCond : Cond[Part],
1717           Op0[Part],
1718           Op1[Part]);
1719       }
1720       break;
1721     }
1722
1723     case Instruction::ICmp:
1724     case Instruction::FCmp: {
1725       // Widen compares. Generate vector compares.
1726       bool FCmp = (it->getOpcode() == Instruction::FCmp);
1727       CmpInst *Cmp = dyn_cast<CmpInst>(it);
1728       VectorParts &A = getVectorValue(it->getOperand(0));
1729       VectorParts &B = getVectorValue(it->getOperand(1));
1730       for (unsigned Part = 0; Part < UF; ++Part) {
1731         Value *C = 0;
1732         if (FCmp)
1733           C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
1734         else
1735           C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
1736         Entry[Part] = C;
1737       }
1738       break;
1739     }
1740
1741     case Instruction::Store: {
1742       // Attempt to issue a wide store.
1743       StoreInst *SI = dyn_cast<StoreInst>(it);
1744       Type *StTy = VectorType::get(SI->getValueOperand()->getType(), VF);
1745       Value *Ptr = SI->getPointerOperand();
1746       unsigned Alignment = SI->getAlignment();
1747
1748       assert(!Legal->isUniform(Ptr) &&
1749              "We do not allow storing to uniform addresses");
1750
1751
1752       int Stride = Legal->isConsecutivePtr(Ptr);
1753       bool Reverse = Stride < 0;
1754       if (Stride == 0) {
1755         scalarizeInstruction(it);
1756         break;
1757       }
1758
1759       // Handle consecutive stores.
1760
1761       GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1762       if (Gep) {
1763         // The last index does not have to be the induction. It can be
1764         // consecutive and be a function of the index. For example A[I+1];
1765         unsigned NumOperands = Gep->getNumOperands();
1766
1767         Value *LastGepOperand = Gep->getOperand(NumOperands - 1);
1768         VectorParts &GEPParts = getVectorValue(LastGepOperand);
1769         Value *LastIndex = GEPParts[0];
1770         LastIndex = Builder.CreateExtractElement(LastIndex, Zero);
1771
1772         // Create the new GEP with the new induction variable.
1773         GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1774         Gep2->setOperand(NumOperands - 1, LastIndex);
1775         Ptr = Builder.Insert(Gep2);
1776       } else {
1777         // Use the induction element ptr.
1778         assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1779         VectorParts &PtrVal = getVectorValue(Ptr);
1780         Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
1781       }
1782
1783       VectorParts &StoredVal = getVectorValue(SI->getValueOperand());
1784       for (unsigned Part = 0; Part < UF; ++Part) {
1785         // Calculate the pointer for the specific unroll-part.
1786         Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1787
1788         if (Reverse) {
1789           // If we store to reverse consecutive memory locations then we need
1790           // to reverse the order of elements in the stored value.
1791           StoredVal[Part] = reverseVector(StoredVal[Part]);
1792           // If the address is consecutive but reversed, then the
1793           // wide store needs to start at the last vector element.
1794           PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1795           PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1796         }
1797
1798         Value *VecPtr = Builder.CreateBitCast(PartPtr, StTy->getPointerTo());
1799         Builder.CreateStore(StoredVal[Part], VecPtr)->setAlignment(Alignment);
1800       }
1801       break;
1802     }
1803     case Instruction::Load: {
1804       // Attempt to issue a wide load.
1805       LoadInst *LI = dyn_cast<LoadInst>(it);
1806       Type *RetTy = VectorType::get(LI->getType(), VF);
1807       Value *Ptr = LI->getPointerOperand();
1808       unsigned Alignment = LI->getAlignment();
1809
1810       // If the pointer is loop invariant or if it is non consecutive,
1811       // scalarize the load.
1812       int Stride = Legal->isConsecutivePtr(Ptr);
1813       bool Reverse = Stride < 0;
1814       if (Legal->isUniform(Ptr) || Stride == 0) {
1815         scalarizeInstruction(it);
1816         break;
1817       }
1818
1819       GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1820       if (Gep) {
1821         // The last index does not have to be the induction. It can be
1822         // consecutive and be a function of the index. For example A[I+1];
1823         unsigned NumOperands = Gep->getNumOperands();
1824
1825         Value *LastGepOperand = Gep->getOperand(NumOperands - 1);
1826         VectorParts &GEPParts = getVectorValue(LastGepOperand);
1827         Value *LastIndex = GEPParts[0];
1828         LastIndex = Builder.CreateExtractElement(LastIndex, Zero);
1829
1830         // Create the new GEP with the new induction variable.
1831         GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1832         Gep2->setOperand(NumOperands - 1, LastIndex);
1833         Ptr = Builder.Insert(Gep2);
1834       } else {
1835         // Use the induction element ptr.
1836         assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1837         VectorParts &PtrVal = getVectorValue(Ptr);
1838         Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
1839       }
1840
1841       for (unsigned Part = 0; Part < UF; ++Part) {
1842         // Calculate the pointer for the specific unroll-part.
1843         Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1844
1845         if (Reverse) {
1846           // If the address is consecutive but reversed, then the
1847           // wide store needs to start at the last vector element.
1848           PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1849           PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1850         }
1851
1852         Value *VecPtr = Builder.CreateBitCast(PartPtr, RetTy->getPointerTo());
1853         Value *LI = Builder.CreateLoad(VecPtr, "wide.load");
1854         cast<LoadInst>(LI)->setAlignment(Alignment);
1855         Entry[Part] = Reverse ? reverseVector(LI) :  LI;
1856       }
1857       break;
1858     }
1859     case Instruction::ZExt:
1860     case Instruction::SExt:
1861     case Instruction::FPToUI:
1862     case Instruction::FPToSI:
1863     case Instruction::FPExt:
1864     case Instruction::PtrToInt:
1865     case Instruction::IntToPtr:
1866     case Instruction::SIToFP:
1867     case Instruction::UIToFP:
1868     case Instruction::Trunc:
1869     case Instruction::FPTrunc:
1870     case Instruction::BitCast: {
1871       CastInst *CI = dyn_cast<CastInst>(it);
1872       /// Optimize the special case where the source is the induction
1873       /// variable. Notice that we can only optimize the 'trunc' case
1874       /// because: a. FP conversions lose precision, b. sext/zext may wrap,
1875       /// c. other casts depend on pointer size.
1876       if (CI->getOperand(0) == OldInduction &&
1877           it->getOpcode() == Instruction::Trunc) {
1878         Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
1879                                                CI->getType());
1880         Value *Broadcasted = getBroadcastInstrs(ScalarCast);
1881         for (unsigned Part = 0; Part < UF; ++Part)
1882           Entry[Part] = getConsecutiveVector(Broadcasted, VF * Part, false);
1883         break;
1884       }
1885       /// Vectorize casts.
1886       Type *DestTy = VectorType::get(CI->getType()->getScalarType(), VF);
1887
1888       VectorParts &A = getVectorValue(it->getOperand(0));
1889       for (unsigned Part = 0; Part < UF; ++Part)
1890         Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
1891       break;
1892     }
1893
1894     case Instruction::Call: {
1895       assert(isTriviallyVectorizableIntrinsic(it));
1896       Module *M = BB->getParent()->getParent();
1897       IntrinsicInst *II = cast<IntrinsicInst>(it);
1898       Intrinsic::ID ID = II->getIntrinsicID();
1899       for (unsigned Part = 0; Part < UF; ++Part) {
1900         SmallVector<Value*, 4> Args;
1901         for (unsigned i = 0, ie = II->getNumArgOperands(); i != ie; ++i) {
1902           VectorParts &Arg = getVectorValue(II->getArgOperand(i));
1903           Args.push_back(Arg[Part]);
1904         }
1905         Type *Tys[] = { VectorType::get(II->getType()->getScalarType(), VF) };
1906         Function *F = Intrinsic::getDeclaration(M, ID, Tys);
1907         Entry[Part] = Builder.CreateCall(F, Args);
1908       }
1909       break;
1910     }
1911
1912     default:
1913       // All other instructions are unsupported. Scalarize them.
1914       scalarizeInstruction(it);
1915       break;
1916     }// end of switch.
1917   }// end of for_each instr.
1918 }
1919
1920 void InnerLoopVectorizer::updateAnalysis() {
1921   // Forget the original basic block.
1922   SE->forgetLoop(OrigLoop);
1923
1924   // Update the dominator tree information.
1925   assert(DT->properlyDominates(LoopBypassBlock, LoopExitBlock) &&
1926          "Entry does not dominate exit.");
1927
1928   DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlock);
1929   DT->addNewBlock(LoopVectorBody, LoopVectorPreHeader);
1930   DT->addNewBlock(LoopMiddleBlock, LoopBypassBlock);
1931   DT->addNewBlock(LoopScalarPreHeader, LoopMiddleBlock);
1932   DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
1933   DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
1934
1935   DEBUG(DT->verifyAnalysis());
1936 }
1937
1938 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
1939   if (!EnableIfConversion)
1940     return false;
1941
1942   assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
1943   std::vector<BasicBlock*> &LoopBlocks = TheLoop->getBlocksVector();
1944
1945   // Collect the blocks that need predication.
1946   for (unsigned i = 0, e = LoopBlocks.size(); i < e; ++i) {
1947     BasicBlock *BB = LoopBlocks[i];
1948
1949     // We don't support switch statements inside loops.
1950     if (!isa<BranchInst>(BB->getTerminator()))
1951       return false;
1952
1953     // We must have at most two predecessors because we need to convert
1954     // all PHIs to selects.
1955     unsigned Preds = std::distance(pred_begin(BB), pred_end(BB));
1956     if (Preds > 2)
1957       return false;
1958
1959     // We must be able to predicate all blocks that need to be predicated.
1960     if (blockNeedsPredication(BB) && !blockCanBePredicated(BB))
1961       return false;
1962   }
1963
1964   // We can if-convert this loop.
1965   return true;
1966 }
1967
1968 bool LoopVectorizationLegality::canVectorize() {
1969   assert(TheLoop->getLoopPreheader() && "No preheader!!");
1970
1971   // We can only vectorize innermost loops.
1972   if (TheLoop->getSubLoopsVector().size())
1973     return false;
1974
1975   // We must have a single backedge.
1976   if (TheLoop->getNumBackEdges() != 1)
1977     return false;
1978
1979   // We must have a single exiting block.
1980   if (!TheLoop->getExitingBlock())
1981     return false;
1982
1983   unsigned NumBlocks = TheLoop->getNumBlocks();
1984
1985   // Check if we can if-convert non single-bb loops.
1986   if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
1987     DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
1988     return false;
1989   }
1990
1991   // We need to have a loop header.
1992   BasicBlock *Latch = TheLoop->getLoopLatch();
1993   DEBUG(dbgs() << "LV: Found a loop: " <<
1994         TheLoop->getHeader()->getName() << "\n");
1995
1996   // ScalarEvolution needs to be able to find the exit count.
1997   const SCEV *ExitCount = SE->getExitCount(TheLoop, Latch);
1998   if (ExitCount == SE->getCouldNotCompute()) {
1999     DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
2000     return false;
2001   }
2002
2003   // Do not loop-vectorize loops with a tiny trip count.
2004   unsigned TC = SE->getSmallConstantTripCount(TheLoop, Latch);
2005   if (TC > 0u && TC < TinyTripCountVectorThreshold) {
2006     DEBUG(dbgs() << "LV: Found a loop with a very small trip count. " <<
2007           "This loop is not worth vectorizing.\n");
2008     return false;
2009   }
2010
2011   // Check if we can vectorize the instructions and CFG in this loop.
2012   if (!canVectorizeInstrs()) {
2013     DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
2014     return false;
2015   }
2016
2017   // Go over each instruction and look at memory deps.
2018   if (!canVectorizeMemory()) {
2019     DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
2020     return false;
2021   }
2022
2023   // Collect all of the variables that remain uniform after vectorization.
2024   collectLoopUniforms();
2025
2026   DEBUG(dbgs() << "LV: We can vectorize this loop" <<
2027         (PtrRtCheck.Need ? " (with a runtime bound check)" : "")
2028         <<"!\n");
2029
2030   // Okay! We can vectorize. At this point we don't have any other mem analysis
2031   // which may limit our maximum vectorization factor, so just return true with
2032   // no restrictions.
2033   return true;
2034 }
2035
2036 bool LoopVectorizationLegality::canVectorizeInstrs() {
2037   BasicBlock *PreHeader = TheLoop->getLoopPreheader();
2038   BasicBlock *Header = TheLoop->getHeader();
2039
2040   // For each block in the loop.
2041   for (Loop::block_iterator bb = TheLoop->block_begin(),
2042        be = TheLoop->block_end(); bb != be; ++bb) {
2043
2044     // Scan the instructions in the block and look for hazards.
2045     for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
2046          ++it) {
2047
2048       if (PHINode *Phi = dyn_cast<PHINode>(it)) {
2049         // This should not happen because the loop should be normalized.
2050         if (Phi->getNumIncomingValues() != 2) {
2051           DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
2052           return false;
2053         }
2054
2055         // Check that this PHI type is allowed.
2056         if (!Phi->getType()->isIntegerTy() &&
2057             !Phi->getType()->isFloatingPointTy() &&
2058             !Phi->getType()->isPointerTy()) {
2059           DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
2060           return false;
2061         }
2062
2063         // If this PHINode is not in the header block, then we know that we
2064         // can convert it to select during if-conversion. No need to check if
2065         // the PHIs in this block are induction or reduction variables.
2066         if (*bb != Header)
2067           continue;
2068
2069         // This is the value coming from the preheader.
2070         Value *StartValue = Phi->getIncomingValueForBlock(PreHeader);
2071         // Check if this is an induction variable.
2072         InductionKind IK = isInductionVariable(Phi);
2073
2074         if (IK_NoInduction != IK) {
2075           // Int inductions are special because we only allow one IV.
2076           if (IK == IK_IntInduction) {
2077             if (Induction) {
2078               DEBUG(dbgs() << "LV: Found too many inductions."<< *Phi <<"\n");
2079               return false;
2080             }
2081             Induction = Phi;
2082           }
2083
2084           DEBUG(dbgs() << "LV: Found an induction variable.\n");
2085           Inductions[Phi] = InductionInfo(StartValue, IK);
2086           continue;
2087         }
2088
2089         if (AddReductionVar(Phi, RK_IntegerAdd)) {
2090           DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
2091           continue;
2092         }
2093         if (AddReductionVar(Phi, RK_IntegerMult)) {
2094           DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n");
2095           continue;
2096         }
2097         if (AddReductionVar(Phi, RK_IntegerOr)) {
2098           DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n");
2099           continue;
2100         }
2101         if (AddReductionVar(Phi, RK_IntegerAnd)) {
2102           DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n");
2103           continue;
2104         }
2105         if (AddReductionVar(Phi, RK_IntegerXor)) {
2106           DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n");
2107           continue;
2108         }
2109         if (AddReductionVar(Phi, RK_FloatMult)) {
2110           DEBUG(dbgs() << "LV: Found an FMult reduction PHI."<< *Phi <<"\n");
2111           continue;
2112         }
2113         if (AddReductionVar(Phi, RK_FloatAdd)) {
2114           DEBUG(dbgs() << "LV: Found an FAdd reduction PHI."<< *Phi <<"\n");
2115           continue;
2116         }
2117
2118         DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
2119         return false;
2120       }// end of PHI handling
2121
2122       // We still don't handle functions.
2123       CallInst *CI = dyn_cast<CallInst>(it);
2124       if (CI && !isTriviallyVectorizableIntrinsic(it)) {
2125         DEBUG(dbgs() << "LV: Found a call site.\n");
2126         return false;
2127       }
2128
2129       // Check that the instruction return type is vectorizable.
2130       if (!VectorType::isValidElementType(it->getType()) &&
2131           !it->getType()->isVoidTy()) {
2132         DEBUG(dbgs() << "LV: Found unvectorizable type." << "\n");
2133         return false;
2134       }
2135
2136       // Check that the stored type is vectorizable.
2137       if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
2138         Type *T = ST->getValueOperand()->getType();
2139         if (!VectorType::isValidElementType(T))
2140           return false;
2141       }
2142
2143       // Reduction instructions are allowed to have exit users.
2144       // All other instructions must not have external users.
2145       if (!AllowedExit.count(it))
2146         //Check that all of the users of the loop are inside the BB.
2147         for (Value::use_iterator I = it->use_begin(), E = it->use_end();
2148              I != E; ++I) {
2149           Instruction *U = cast<Instruction>(*I);
2150           // This user may be a reduction exit value.
2151           if (!TheLoop->contains(U)) {
2152             DEBUG(dbgs() << "LV: Found an outside user for : "<< *U << "\n");
2153             return false;
2154           }
2155         }
2156     } // next instr.
2157
2158   }
2159
2160   if (!Induction) {
2161     DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
2162     assert(getInductionVars()->size() && "No induction variables");
2163   }
2164
2165   return true;
2166 }
2167
2168 void LoopVectorizationLegality::collectLoopUniforms() {
2169   // We now know that the loop is vectorizable!
2170   // Collect variables that will remain uniform after vectorization.
2171   std::vector<Value*> Worklist;
2172   BasicBlock *Latch = TheLoop->getLoopLatch();
2173
2174   // Start with the conditional branch and walk up the block.
2175   Worklist.push_back(Latch->getTerminator()->getOperand(0));
2176
2177   while (Worklist.size()) {
2178     Instruction *I = dyn_cast<Instruction>(Worklist.back());
2179     Worklist.pop_back();
2180
2181     // Look at instructions inside this loop.
2182     // Stop when reaching PHI nodes.
2183     // TODO: we need to follow values all over the loop, not only in this block.
2184     if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
2185       continue;
2186
2187     // This is a known uniform.
2188     Uniforms.insert(I);
2189
2190     // Insert all operands.
2191     for (int i = 0, Op = I->getNumOperands(); i < Op; ++i) {
2192       Worklist.push_back(I->getOperand(i));
2193     }
2194   }
2195 }
2196
2197 bool LoopVectorizationLegality::canVectorizeMemory() {
2198   typedef SmallVector<Value*, 16> ValueVector;
2199   typedef SmallPtrSet<Value*, 16> ValueSet;
2200   // Holds the Load and Store *instructions*.
2201   ValueVector Loads;
2202   ValueVector Stores;
2203   PtrRtCheck.Pointers.clear();
2204   PtrRtCheck.Need = false;
2205
2206   // For each block.
2207   for (Loop::block_iterator bb = TheLoop->block_begin(),
2208        be = TheLoop->block_end(); bb != be; ++bb) {
2209
2210     // Scan the BB and collect legal loads and stores.
2211     for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
2212          ++it) {
2213
2214       // If this is a load, save it. If this instruction can read from memory
2215       // but is not a load, then we quit. Notice that we don't handle function
2216       // calls that read or write.
2217       if (it->mayReadFromMemory()) {
2218         LoadInst *Ld = dyn_cast<LoadInst>(it);
2219         if (!Ld) return false;
2220         if (!Ld->isSimple()) {
2221           DEBUG(dbgs() << "LV: Found a non-simple load.\n");
2222           return false;
2223         }
2224         Loads.push_back(Ld);
2225         continue;
2226       }
2227
2228       // Save 'store' instructions. Abort if other instructions write to memory.
2229       if (it->mayWriteToMemory()) {
2230         StoreInst *St = dyn_cast<StoreInst>(it);
2231         if (!St) return false;
2232         if (!St->isSimple()) {
2233           DEBUG(dbgs() << "LV: Found a non-simple store.\n");
2234           return false;
2235         }
2236         Stores.push_back(St);
2237       }
2238     } // next instr.
2239   } // next block.
2240
2241   // Now we have two lists that hold the loads and the stores.
2242   // Next, we find the pointers that they use.
2243
2244   // Check if we see any stores. If there are no stores, then we don't
2245   // care if the pointers are *restrict*.
2246   if (!Stores.size()) {
2247     DEBUG(dbgs() << "LV: Found a read-only loop!\n");
2248     return true;
2249   }
2250
2251   // Holds the read and read-write *pointers* that we find.
2252   ValueVector Reads;
2253   ValueVector ReadWrites;
2254
2255   // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
2256   // multiple times on the same object. If the ptr is accessed twice, once
2257   // for read and once for write, it will only appear once (on the write
2258   // list). This is okay, since we are going to check for conflicts between
2259   // writes and between reads and writes, but not between reads and reads.
2260   ValueSet Seen;
2261
2262   ValueVector::iterator I, IE;
2263   for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
2264     StoreInst *ST = cast<StoreInst>(*I);
2265     Value* Ptr = ST->getPointerOperand();
2266
2267     if (isUniform(Ptr)) {
2268       DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
2269       return false;
2270     }
2271
2272     // If we did *not* see this pointer before, insert it to
2273     // the read-write list. At this phase it is only a 'write' list.
2274     if (Seen.insert(Ptr))
2275       ReadWrites.push_back(Ptr);
2276   }
2277
2278   for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
2279     LoadInst *LD = cast<LoadInst>(*I);
2280     Value* Ptr = LD->getPointerOperand();
2281     // If we did *not* see this pointer before, insert it to the
2282     // read list. If we *did* see it before, then it is already in
2283     // the read-write list. This allows us to vectorize expressions
2284     // such as A[i] += x;  Because the address of A[i] is a read-write
2285     // pointer. This only works if the index of A[i] is consecutive.
2286     // If the address of i is unknown (for example A[B[i]]) then we may
2287     // read a few words, modify, and write a few words, and some of the
2288     // words may be written to the same address.
2289     if (Seen.insert(Ptr) || 0 == isConsecutivePtr(Ptr))
2290       Reads.push_back(Ptr);
2291   }
2292
2293   // If we write (or read-write) to a single destination and there are no
2294   // other reads in this loop then is it safe to vectorize.
2295   if (ReadWrites.size() == 1 && Reads.size() == 0) {
2296     DEBUG(dbgs() << "LV: Found a write-only loop!\n");
2297     return true;
2298   }
2299
2300   // Find pointers with computable bounds. We are going to use this information
2301   // to place a runtime bound check.
2302   bool CanDoRT = true;
2303   for (I = ReadWrites.begin(), IE = ReadWrites.end(); I != IE; ++I)
2304     if (hasComputableBounds(*I)) {
2305       PtrRtCheck.insert(SE, TheLoop, *I);
2306       DEBUG(dbgs() << "LV: Found a runtime check ptr:" << **I <<"\n");
2307     } else {
2308       CanDoRT = false;
2309       break;
2310     }
2311   for (I = Reads.begin(), IE = Reads.end(); I != IE; ++I)
2312     if (hasComputableBounds(*I)) {
2313       PtrRtCheck.insert(SE, TheLoop, *I);
2314       DEBUG(dbgs() << "LV: Found a runtime check ptr:" << **I <<"\n");
2315     } else {
2316       CanDoRT = false;
2317       break;
2318     }
2319
2320   // Check that we did not collect too many pointers or found a
2321   // unsizeable pointer.
2322   if (!CanDoRT || PtrRtCheck.Pointers.size() > RuntimeMemoryCheckThreshold) {
2323     PtrRtCheck.reset();
2324     CanDoRT = false;
2325   }
2326
2327   if (CanDoRT) {
2328     DEBUG(dbgs() << "LV: We can perform a memory runtime check if needed.\n");
2329   }
2330
2331   bool NeedRTCheck = false;
2332
2333   // Now that the pointers are in two lists (Reads and ReadWrites), we
2334   // can check that there are no conflicts between each of the writes and
2335   // between the writes to the reads.
2336   ValueSet WriteObjects;
2337   ValueVector TempObjects;
2338
2339   // Check that the read-writes do not conflict with other read-write
2340   // pointers.
2341   bool AllWritesIdentified = true;
2342   for (I = ReadWrites.begin(), IE = ReadWrites.end(); I != IE; ++I) {
2343     GetUnderlyingObjects(*I, TempObjects, DL);
2344     for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end();
2345          it != e; ++it) {
2346       if (!isIdentifiedObject(*it)) {
2347         DEBUG(dbgs() << "LV: Found an unidentified write ptr:"<< **it <<"\n");
2348         NeedRTCheck = true;
2349         AllWritesIdentified = false;
2350       }
2351       if (!WriteObjects.insert(*it)) {
2352         DEBUG(dbgs() << "LV: Found a possible write-write reorder:"
2353               << **it <<"\n");
2354         return false;
2355       }
2356     }
2357     TempObjects.clear();
2358   }
2359
2360   /// Check that the reads don't conflict with the read-writes.
2361   for (I = Reads.begin(), IE = Reads.end(); I != IE; ++I) {
2362     GetUnderlyingObjects(*I, TempObjects, DL);
2363     for (ValueVector::iterator it=TempObjects.begin(), e=TempObjects.end();
2364          it != e; ++it) {
2365       // If all of the writes are identified then we don't care if the read
2366       // pointer is identified or not.
2367       if (!AllWritesIdentified && !isIdentifiedObject(*it)) {
2368         DEBUG(dbgs() << "LV: Found an unidentified read ptr:"<< **it <<"\n");
2369         NeedRTCheck = true;
2370       }
2371       if (WriteObjects.count(*it)) {
2372         DEBUG(dbgs() << "LV: Found a possible read/write reorder:"
2373               << **it <<"\n");
2374         return false;
2375       }
2376     }
2377     TempObjects.clear();
2378   }
2379
2380   PtrRtCheck.Need = NeedRTCheck;
2381   if (NeedRTCheck && !CanDoRT) {
2382     DEBUG(dbgs() << "LV: We can't vectorize because we can't find " <<
2383           "the array bounds.\n");
2384     PtrRtCheck.reset();
2385     return false;
2386   }
2387
2388   DEBUG(dbgs() << "LV: We "<< (NeedRTCheck ? "" : "don't") <<
2389         " need a runtime memory check.\n");
2390   return true;
2391 }
2392
2393 bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi,
2394                                                 ReductionKind Kind) {
2395   if (Phi->getNumIncomingValues() != 2)
2396     return false;
2397
2398   // Reduction variables are only found in the loop header block.
2399   if (Phi->getParent() != TheLoop->getHeader())
2400     return false;
2401
2402   // Obtain the reduction start value from the value that comes from the loop
2403   // preheader.
2404   Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
2405
2406   // ExitInstruction is the single value which is used outside the loop.
2407   // We only allow for a single reduction value to be used outside the loop.
2408   // This includes users of the reduction, variables (which form a cycle
2409   // which ends in the phi node).
2410   Instruction *ExitInstruction = 0;
2411   // Indicates that we found a binary operation in our scan.
2412   bool FoundBinOp = false;
2413
2414   // Iter is our iterator. We start with the PHI node and scan for all of the
2415   // users of this instruction. All users must be instructions that can be
2416   // used as reduction variables (such as ADD). We may have a single
2417   // out-of-block user. The cycle must end with the original PHI.
2418   Instruction *Iter = Phi;
2419   while (true) {
2420     // If the instruction has no users then this is a broken
2421     // chain and can't be a reduction variable.
2422     if (Iter->use_empty())
2423       return false;
2424
2425     // Did we find a user inside this loop already ?
2426     bool FoundInBlockUser = false;
2427     // Did we reach the initial PHI node already ?
2428     bool FoundStartPHI = false;
2429
2430     // Is this a bin op ?
2431     FoundBinOp |= !isa<PHINode>(Iter);
2432
2433     // For each of the *users* of iter.
2434     for (Value::use_iterator it = Iter->use_begin(), e = Iter->use_end();
2435          it != e; ++it) {
2436       Instruction *U = cast<Instruction>(*it);
2437       // We already know that the PHI is a user.
2438       if (U == Phi) {
2439         FoundStartPHI = true;
2440         continue;
2441       }
2442
2443       // Check if we found the exit user.
2444       BasicBlock *Parent = U->getParent();
2445       if (!TheLoop->contains(Parent)) {
2446         // Exit if you find multiple outside users.
2447         if (ExitInstruction != 0)
2448           return false;
2449         ExitInstruction = Iter;
2450       }
2451
2452       // We allow in-loop PHINodes which are not the original reduction PHI
2453       // node. If this PHI is the only user of Iter (happens in IF w/ no ELSE
2454       // structure) then don't skip this PHI.
2455       if (isa<PHINode>(Iter) && isa<PHINode>(U) &&
2456           U->getParent() != TheLoop->getHeader() &&
2457           TheLoop->contains(U) &&
2458           Iter->getNumUses() > 1)
2459         continue;
2460
2461       // We can't have multiple inside users.
2462       if (FoundInBlockUser)
2463         return false;
2464       FoundInBlockUser = true;
2465
2466       // Any reduction instr must be of one of the allowed kinds.
2467       if (!isReductionInstr(U, Kind))
2468         return false;
2469
2470       // Reductions of instructions such as Div, and Sub is only
2471       // possible if the LHS is the reduction variable.
2472       if (!U->isCommutative() && !isa<PHINode>(U) && U->getOperand(0) != Iter)
2473         return false;
2474
2475       Iter = U;
2476     }
2477
2478     // We found a reduction var if we have reached the original
2479     // phi node and we only have a single instruction with out-of-loop
2480     // users.
2481     if (FoundStartPHI) {
2482       // This instruction is allowed to have out-of-loop users.
2483       AllowedExit.insert(ExitInstruction);
2484
2485       // Save the description of this reduction variable.
2486       ReductionDescriptor RD(RdxStart, ExitInstruction, Kind);
2487       Reductions[Phi] = RD;
2488       // We've ended the cycle. This is a reduction variable if we have an
2489       // outside user and it has a binary op.
2490       return FoundBinOp && ExitInstruction;
2491     }
2492   }
2493 }
2494
2495 bool
2496 LoopVectorizationLegality::isReductionInstr(Instruction *I,
2497                                             ReductionKind Kind) {
2498   bool FP = I->getType()->isFloatingPointTy();
2499   bool FastMath = (FP && I->isCommutative() && I->isAssociative());
2500
2501   switch (I->getOpcode()) {
2502   default:
2503     return false;
2504   case Instruction::PHI:
2505       if (FP && (Kind != RK_FloatMult && Kind != RK_FloatAdd))
2506         return false;
2507     // possibly.
2508     return true;
2509   case Instruction::Sub:
2510   case Instruction::Add:
2511     return Kind == RK_IntegerAdd;
2512   case Instruction::SDiv:
2513   case Instruction::UDiv:
2514   case Instruction::Mul:
2515     return Kind == RK_IntegerMult;
2516   case Instruction::And:
2517     return Kind == RK_IntegerAnd;
2518   case Instruction::Or:
2519     return Kind == RK_IntegerOr;
2520   case Instruction::Xor:
2521     return Kind == RK_IntegerXor;
2522   case Instruction::FMul:
2523     return Kind == RK_FloatMult && FastMath;
2524   case Instruction::FAdd:
2525     return Kind == RK_FloatAdd && FastMath;
2526    }
2527 }
2528
2529 LoopVectorizationLegality::InductionKind
2530 LoopVectorizationLegality::isInductionVariable(PHINode *Phi) {
2531   Type *PhiTy = Phi->getType();
2532   // We only handle integer and pointer inductions variables.
2533   if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
2534     return IK_NoInduction;
2535
2536   // Check that the PHI is consecutive and starts at zero.
2537   const SCEV *PhiScev = SE->getSCEV(Phi);
2538   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
2539   if (!AR) {
2540     DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
2541     return IK_NoInduction;
2542   }
2543   const SCEV *Step = AR->getStepRecurrence(*SE);
2544
2545   // Integer inductions need to have a stride of one.
2546   if (PhiTy->isIntegerTy()) {
2547     if (Step->isOne())
2548       return IK_IntInduction;
2549     if (Step->isAllOnesValue())
2550       return IK_ReverseIntInduction;
2551     return IK_NoInduction;
2552   }
2553
2554   // Calculate the pointer stride and check if it is consecutive.
2555   const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
2556   if (!C)
2557     return IK_NoInduction;
2558
2559   assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
2560   uint64_t Size = DL->getTypeAllocSize(PhiTy->getPointerElementType());
2561   if (C->getValue()->equalsInt(Size))
2562     return IK_PtrInduction;
2563
2564   return IK_NoInduction;
2565 }
2566
2567 bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
2568   Value *In0 = const_cast<Value*>(V);
2569   PHINode *PN = dyn_cast_or_null<PHINode>(In0);
2570   if (!PN)
2571     return false;
2572
2573   return Inductions.count(PN);
2574 }
2575
2576 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB)  {
2577   assert(TheLoop->contains(BB) && "Unknown block used");
2578
2579   // Blocks that do not dominate the latch need predication.
2580   BasicBlock* Latch = TheLoop->getLoopLatch();
2581   return !DT->dominates(BB, Latch);
2582 }
2583
2584 bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB) {
2585   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2586     // We don't predicate loads/stores at the moment.
2587     if (it->mayReadFromMemory() || it->mayWriteToMemory() || it->mayThrow())
2588       return false;
2589
2590     // The instructions below can trap.
2591     switch (it->getOpcode()) {
2592     default: continue;
2593     case Instruction::UDiv:
2594     case Instruction::SDiv:
2595     case Instruction::URem:
2596     case Instruction::SRem:
2597              return false;
2598     }
2599   }
2600
2601   return true;
2602 }
2603
2604 bool LoopVectorizationLegality::hasComputableBounds(Value *Ptr) {
2605   const SCEV *PhiScev = SE->getSCEV(Ptr);
2606   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
2607   if (!AR)
2608     return false;
2609
2610   return AR->isAffine();
2611 }
2612
2613 unsigned
2614 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize,
2615                                                       unsigned UserVF) {
2616   if (OptForSize && Legal->getRuntimePointerCheck()->Need) {
2617     DEBUG(dbgs() << "LV: Aborting. Runtime ptr check is required in Os.\n");
2618     return 1;
2619   }
2620
2621   // Find the trip count.
2622   unsigned TC = SE->getSmallConstantTripCount(TheLoop, TheLoop->getLoopLatch());
2623   DEBUG(dbgs() << "LV: Found trip count:"<<TC<<"\n");
2624
2625   unsigned WidestType = getWidestType();
2626   unsigned WidestRegister = TTI.getRegisterBitWidth(true);
2627   unsigned MaxVectorSize = WidestRegister / WidestType;
2628   DEBUG(dbgs() << "LV: The Widest type: " << WidestType << " bits.\n");
2629   DEBUG(dbgs() << "LV: The Widest register is:" << WidestRegister << "bits.\n");
2630
2631   if (MaxVectorSize == 0) {
2632     DEBUG(dbgs() << "LV: The target has no vector registers.\n");
2633     return 1;
2634   }
2635
2636   assert(MaxVectorSize <= 32 && "Did not expect to pack so many elements"
2637          " into one vector.");
2638
2639   unsigned VF = MaxVectorSize;
2640
2641   // If we optimize the program for size, avoid creating the tail loop.
2642   if (OptForSize) {
2643     // If we are unable to calculate the trip count then don't try to vectorize.
2644     if (TC < 2) {
2645       DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
2646       return 1;
2647     }
2648
2649     // Find the maximum SIMD width that can fit within the trip count.
2650     VF = TC % MaxVectorSize;
2651
2652     if (VF == 0)
2653       VF = MaxVectorSize;
2654
2655     // If the trip count that we found modulo the vectorization factor is not
2656     // zero then we require a tail.
2657     if (VF < 2) {
2658       DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
2659       return 1;
2660     }
2661   }
2662
2663   if (UserVF != 0) {
2664     assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
2665     DEBUG(dbgs() << "LV: Using user VF "<<UserVF<<".\n");
2666
2667     return UserVF;
2668   }
2669
2670   float Cost = expectedCost(1);
2671   unsigned Width = 1;
2672   DEBUG(dbgs() << "LV: Scalar loop costs: "<< (int)Cost << ".\n");
2673   for (unsigned i=2; i <= VF; i*=2) {
2674     // Notice that the vector loop needs to be executed less times, so
2675     // we need to divide the cost of the vector loops by the width of
2676     // the vector elements.
2677     float VectorCost = expectedCost(i) / (float)i;
2678     DEBUG(dbgs() << "LV: Vector loop of width "<< i << " costs: " <<
2679           (int)VectorCost << ".\n");
2680     if (VectorCost < Cost) {
2681       Cost = VectorCost;
2682       Width = i;
2683     }
2684   }
2685
2686   DEBUG(dbgs() << "LV: Selecting VF = : "<< Width << ".\n");
2687   return Width;
2688 }
2689
2690 unsigned LoopVectorizationCostModel::getWidestType() {
2691   unsigned MaxWidth = 8;
2692
2693   // For each block.
2694   for (Loop::block_iterator bb = TheLoop->block_begin(),
2695        be = TheLoop->block_end(); bb != be; ++bb) {
2696     BasicBlock *BB = *bb;
2697
2698     // For each instruction in the loop.
2699     for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2700       Type *T = it->getType();
2701
2702       // Only examine Loads, Stores and PHINodes.
2703       if (!isa<LoadInst>(it) && !isa<StoreInst>(it) && !isa<PHINode>(it))
2704         continue;
2705
2706       // Examine PHI nodes that are reduction variables.
2707       if (PHINode *PN = dyn_cast<PHINode>(it))
2708         if (!Legal->getReductionVars()->count(PN))
2709           continue;
2710
2711       // Examine the stored values.
2712       if (StoreInst *ST = dyn_cast<StoreInst>(it))
2713         T = ST->getValueOperand()->getType();
2714
2715       // Ignore stored/loaded pointer types.
2716       if (T->isPointerTy())
2717         continue;
2718
2719       MaxWidth = std::max(MaxWidth, T->getScalarSizeInBits());
2720     }
2721   }
2722
2723   return MaxWidth;
2724 }
2725
2726 unsigned
2727 LoopVectorizationCostModel::selectUnrollFactor(bool OptForSize,
2728                                                unsigned UserUF) {
2729   // Use the user preference, unless 'auto' is selected.
2730   if (UserUF != 0)
2731     return UserUF;
2732
2733   // When we optimize for size we don't unroll.
2734   if (OptForSize)
2735     return 1;
2736
2737   // Do not unroll loops with a relatively small trip count.
2738   unsigned TC = SE->getSmallConstantTripCount(TheLoop,
2739                                               TheLoop->getLoopLatch());
2740   if (TC > 1 && TC < TinyTripCountUnrollThreshold)
2741     return 1;
2742
2743   unsigned TargetVectorRegisters = TTI.getNumberOfRegisters(true);
2744   DEBUG(dbgs() << "LV: The target has " << TargetVectorRegisters <<
2745         " vector registers\n");
2746
2747   LoopVectorizationCostModel::RegisterUsage R = calculateRegisterUsage();
2748   // We divide by these constants so assume that we have at least one
2749   // instruction that uses at least one register.
2750   R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
2751   R.NumInstructions = std::max(R.NumInstructions, 1U);
2752
2753   // We calculate the unroll factor using the following formula.
2754   // Subtract the number of loop invariants from the number of available
2755   // registers. These registers are used by all of the unrolled instances.
2756   // Next, divide the remaining registers by the number of registers that is
2757   // required by the loop, in order to estimate how many parallel instances
2758   // fit without causing spills.
2759   unsigned UF = (TargetVectorRegisters - R.LoopInvariantRegs) / R.MaxLocalUsers;
2760
2761   // We don't want to unroll the loops to the point where they do not fit into
2762   // the decoded cache. Assume that we only allow 32 IR instructions.
2763   UF = std::min(UF, (MaxLoopSizeThreshold / R.NumInstructions));
2764
2765   // Clamp the unroll factor ranges to reasonable factors.
2766   unsigned MaxUnrollSize = TTI.getMaximumUnrollFactor();
2767   
2768   if (UF > MaxUnrollSize)
2769     UF = MaxUnrollSize;
2770   else if (UF < 1)
2771     UF = 1;
2772
2773   return UF;
2774 }
2775
2776 LoopVectorizationCostModel::RegisterUsage
2777 LoopVectorizationCostModel::calculateRegisterUsage() {
2778   // This function calculates the register usage by measuring the highest number
2779   // of values that are alive at a single location. Obviously, this is a very
2780   // rough estimation. We scan the loop in a topological order in order and
2781   // assign a number to each instruction. We use RPO to ensure that defs are
2782   // met before their users. We assume that each instruction that has in-loop
2783   // users starts an interval. We record every time that an in-loop value is
2784   // used, so we have a list of the first and last occurrences of each
2785   // instruction. Next, we transpose this data structure into a multi map that
2786   // holds the list of intervals that *end* at a specific location. This multi
2787   // map allows us to perform a linear search. We scan the instructions linearly
2788   // and record each time that a new interval starts, by placing it in a set.
2789   // If we find this value in the multi-map then we remove it from the set.
2790   // The max register usage is the maximum size of the set.
2791   // We also search for instructions that are defined outside the loop, but are
2792   // used inside the loop. We need this number separately from the max-interval
2793   // usage number because when we unroll, loop-invariant values do not take
2794   // more register.
2795   LoopBlocksDFS DFS(TheLoop);
2796   DFS.perform(LI);
2797
2798   RegisterUsage R;
2799   R.NumInstructions = 0;
2800
2801   // Each 'key' in the map opens a new interval. The values
2802   // of the map are the index of the 'last seen' usage of the
2803   // instruction that is the key.
2804   typedef DenseMap<Instruction*, unsigned> IntervalMap;
2805   // Maps instruction to its index.
2806   DenseMap<unsigned, Instruction*> IdxToInstr;
2807   // Marks the end of each interval.
2808   IntervalMap EndPoint;
2809   // Saves the list of instruction indices that are used in the loop.
2810   SmallSet<Instruction*, 8> Ends;
2811   // Saves the list of values that are used in the loop but are
2812   // defined outside the loop, such as arguments and constants.
2813   SmallPtrSet<Value*, 8> LoopInvariants;
2814
2815   unsigned Index = 0;
2816   for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
2817        be = DFS.endRPO(); bb != be; ++bb) {
2818     R.NumInstructions += (*bb)->size();
2819     for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
2820          ++it) {
2821       Instruction *I = it;
2822       IdxToInstr[Index++] = I;
2823
2824       // Save the end location of each USE.
2825       for (unsigned i = 0; i < I->getNumOperands(); ++i) {
2826         Value *U = I->getOperand(i);
2827         Instruction *Instr = dyn_cast<Instruction>(U);
2828
2829         // Ignore non-instruction values such as arguments, constants, etc.
2830         if (!Instr) continue;
2831
2832         // If this instruction is outside the loop then record it and continue.
2833         if (!TheLoop->contains(Instr)) {
2834           LoopInvariants.insert(Instr);
2835           continue;
2836         }
2837
2838         // Overwrite previous end points.
2839         EndPoint[Instr] = Index;
2840         Ends.insert(Instr);
2841       }
2842     }
2843   }
2844
2845   // Saves the list of intervals that end with the index in 'key'.
2846   typedef SmallVector<Instruction*, 2> InstrList;
2847   DenseMap<unsigned, InstrList> TransposeEnds;
2848
2849   // Transpose the EndPoints to a list of values that end at each index.
2850   for (IntervalMap::iterator it = EndPoint.begin(), e = EndPoint.end();
2851        it != e; ++it)
2852     TransposeEnds[it->second].push_back(it->first);
2853
2854   SmallSet<Instruction*, 8> OpenIntervals;
2855   unsigned MaxUsage = 0;
2856
2857
2858   DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
2859   for (unsigned int i = 0; i < Index; ++i) {
2860     Instruction *I = IdxToInstr[i];
2861     // Ignore instructions that are never used within the loop.
2862     if (!Ends.count(I)) continue;
2863
2864     // Remove all of the instructions that end at this location.
2865     InstrList &List = TransposeEnds[i];
2866     for (unsigned int j=0, e = List.size(); j < e; ++j)
2867       OpenIntervals.erase(List[j]);
2868
2869     // Count the number of live interals.
2870     MaxUsage = std::max(MaxUsage, OpenIntervals.size());
2871
2872     DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # " <<
2873           OpenIntervals.size() <<"\n");
2874
2875     // Add the current instruction to the list of open intervals.
2876     OpenIntervals.insert(I);
2877   }
2878
2879   unsigned Invariant = LoopInvariants.size();
2880   DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsage << " \n");
2881   DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << " \n");
2882   DEBUG(dbgs() << "LV(REG): LoopSize: " << R.NumInstructions << " \n");
2883
2884   R.LoopInvariantRegs = Invariant;
2885   R.MaxLocalUsers = MaxUsage;
2886   return R;
2887 }
2888
2889 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
2890   unsigned Cost = 0;
2891
2892   // For each block.
2893   for (Loop::block_iterator bb = TheLoop->block_begin(),
2894        be = TheLoop->block_end(); bb != be; ++bb) {
2895     unsigned BlockCost = 0;
2896     BasicBlock *BB = *bb;
2897
2898     // For each instruction in the old loop.
2899     for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2900       unsigned C = getInstructionCost(it, VF);
2901       Cost += C;
2902       DEBUG(dbgs() << "LV: Found an estimated cost of "<< C <<" for VF " <<
2903             VF << " For instruction: "<< *it << "\n");
2904     }
2905
2906     // We assume that if-converted blocks have a 50% chance of being executed.
2907     // When the code is scalar then some of the blocks are avoided due to CF.
2908     // When the code is vectorized we execute all code paths.
2909     if (Legal->blockNeedsPredication(*bb) && VF == 1)
2910       BlockCost /= 2;
2911
2912     Cost += BlockCost;
2913   }
2914
2915   return Cost;
2916 }
2917
2918 unsigned
2919 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
2920   // If we know that this instruction will remain uniform, check the cost of
2921   // the scalar version.
2922   if (Legal->isUniformAfterVectorization(I))
2923     VF = 1;
2924
2925   Type *RetTy = I->getType();
2926   Type *VectorTy = ToVectorTy(RetTy, VF);
2927
2928   // TODO: We need to estimate the cost of intrinsic calls.
2929   switch (I->getOpcode()) {
2930   case Instruction::GetElementPtr:
2931     // We mark this instruction as zero-cost because scalar GEPs are usually
2932     // lowered to the intruction addressing mode. At the moment we don't
2933     // generate vector geps.
2934     return 0;
2935   case Instruction::Br: {
2936     return TTI.getCFInstrCost(I->getOpcode());
2937   }
2938   case Instruction::PHI:
2939     //TODO: IF-converted IFs become selects.
2940     return 0;
2941   case Instruction::Add:
2942   case Instruction::FAdd:
2943   case Instruction::Sub:
2944   case Instruction::FSub:
2945   case Instruction::Mul:
2946   case Instruction::FMul:
2947   case Instruction::UDiv:
2948   case Instruction::SDiv:
2949   case Instruction::FDiv:
2950   case Instruction::URem:
2951   case Instruction::SRem:
2952   case Instruction::FRem:
2953   case Instruction::Shl:
2954   case Instruction::LShr:
2955   case Instruction::AShr:
2956   case Instruction::And:
2957   case Instruction::Or:
2958   case Instruction::Xor:
2959     return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy);
2960   case Instruction::Select: {
2961     SelectInst *SI = cast<SelectInst>(I);
2962     const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
2963     bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
2964     Type *CondTy = SI->getCondition()->getType();
2965     if (ScalarCond)
2966       CondTy = VectorType::get(CondTy, VF);
2967
2968     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
2969   }
2970   case Instruction::ICmp:
2971   case Instruction::FCmp: {
2972     Type *ValTy = I->getOperand(0)->getType();
2973     VectorTy = ToVectorTy(ValTy, VF);
2974     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy);
2975   }
2976   case Instruction::Store: {
2977     StoreInst *SI = cast<StoreInst>(I);
2978     Type *ValTy = SI->getValueOperand()->getType();
2979     VectorTy = ToVectorTy(ValTy, VF);
2980
2981     if (VF == 1)
2982       return TTI.getMemoryOpCost(I->getOpcode(), VectorTy,
2983                                    SI->getAlignment(),
2984                                    SI->getPointerAddressSpace());
2985
2986     // Scalarized stores.
2987     int Stride = Legal->isConsecutivePtr(SI->getPointerOperand());
2988     bool Reverse = Stride < 0;
2989     if (0 == Stride) {
2990       unsigned Cost = 0;
2991
2992       // The cost of extracting from the value vector and pointer vector.
2993       Type *PtrTy = ToVectorTy(I->getOperand(0)->getType(), VF);
2994       for (unsigned i = 0; i < VF; ++i) {
2995         Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, VectorTy,
2996                                        i);
2997         Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
2998       }
2999
3000       // The cost of the scalar stores.
3001       Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(),
3002                                        SI->getAlignment(),
3003                                        SI->getPointerAddressSpace());
3004       return Cost;
3005     }
3006
3007     // Wide stores.
3008     unsigned Cost = TTI.getMemoryOpCost(I->getOpcode(), VectorTy,
3009                                         SI->getAlignment(),
3010                                         SI->getPointerAddressSpace());
3011     if (Reverse)
3012       Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
3013                                   VectorTy, 0);
3014     return Cost;
3015   }
3016   case Instruction::Load: {
3017     LoadInst *LI = cast<LoadInst>(I);
3018
3019     if (VF == 1)
3020       return TTI.getMemoryOpCost(I->getOpcode(), VectorTy, LI->getAlignment(),
3021                                  LI->getPointerAddressSpace());
3022
3023     // Scalarized loads.
3024     int Stride = Legal->isConsecutivePtr(LI->getPointerOperand());
3025     bool Reverse = Stride < 0;
3026     if (0 == Stride) {
3027       unsigned Cost = 0;
3028       Type *PtrTy = ToVectorTy(I->getOperand(0)->getType(), VF);
3029
3030       // The cost of extracting from the pointer vector.
3031       for (unsigned i = 0; i < VF; ++i)
3032         Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
3033
3034       // The cost of inserting data to the result vector.
3035       for (unsigned i = 0; i < VF; ++i)
3036         Cost += TTI.getVectorInstrCost(Instruction::InsertElement, VectorTy, i);
3037
3038       // The cost of the scalar stores.
3039       Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), RetTy->getScalarType(),
3040                                        LI->getAlignment(),
3041                                        LI->getPointerAddressSpace());
3042       return Cost;
3043     }
3044
3045     // Wide loads.
3046     unsigned Cost = TTI.getMemoryOpCost(I->getOpcode(), VectorTy,
3047                                         LI->getAlignment(),
3048                                         LI->getPointerAddressSpace());
3049     if (Reverse)
3050       Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, 0);
3051     return Cost;
3052   }
3053   case Instruction::ZExt:
3054   case Instruction::SExt:
3055   case Instruction::FPToUI:
3056   case Instruction::FPToSI:
3057   case Instruction::FPExt:
3058   case Instruction::PtrToInt:
3059   case Instruction::IntToPtr:
3060   case Instruction::SIToFP:
3061   case Instruction::UIToFP:
3062   case Instruction::Trunc:
3063   case Instruction::FPTrunc:
3064   case Instruction::BitCast: {
3065     // We optimize the truncation of induction variable.
3066     // The cost of these is the same as the scalar operation.
3067     if (I->getOpcode() == Instruction::Trunc &&
3068         Legal->isInductionVariable(I->getOperand(0)))
3069       return TTI.getCastInstrCost(I->getOpcode(), I->getType(),
3070                                   I->getOperand(0)->getType());
3071
3072     Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
3073     return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
3074   }
3075   case Instruction::Call: {
3076     assert(isTriviallyVectorizableIntrinsic(I));
3077     IntrinsicInst *II = cast<IntrinsicInst>(I);
3078     Type *RetTy = ToVectorTy(II->getType(), VF);
3079     SmallVector<Type*, 4> Tys;
3080     for (unsigned i = 0, ie = II->getNumArgOperands(); i != ie; ++i)
3081       Tys.push_back(ToVectorTy(II->getArgOperand(i)->getType(), VF));
3082     return TTI.getIntrinsicInstrCost(II->getIntrinsicID(), RetTy, Tys);
3083   }
3084   default: {
3085     // We are scalarizing the instruction. Return the cost of the scalar
3086     // instruction, plus the cost of insert and extract into vector
3087     // elements, times the vector width.
3088     unsigned Cost = 0;
3089
3090     if (!RetTy->isVoidTy() && VF != 1) {
3091       unsigned InsCost = TTI.getVectorInstrCost(Instruction::InsertElement,
3092                                                 VectorTy);
3093       unsigned ExtCost = TTI.getVectorInstrCost(Instruction::ExtractElement,
3094                                                 VectorTy);
3095
3096       // The cost of inserting the results plus extracting each one of the
3097       // operands.
3098       Cost += VF * (InsCost + ExtCost * I->getNumOperands());
3099     }
3100
3101     // The cost of executing VF copies of the scalar instruction. This opcode
3102     // is unknown. Assume that it is the same as 'mul'.
3103     Cost += VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy);
3104     return Cost;
3105   }
3106   }// end of switch.
3107 }
3108
3109 Type* LoopVectorizationCostModel::ToVectorTy(Type *Scalar, unsigned VF) {
3110   if (Scalar->isVoidTy() || VF == 1)
3111     return Scalar;
3112   return VectorType::get(Scalar, VF);
3113 }
3114
3115 char LoopVectorize::ID = 0;
3116 static const char lv_name[] = "Loop Vectorization";
3117 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
3118 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3119 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
3120 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
3121 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
3122 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
3123
3124 namespace llvm {
3125   Pass *createLoopVectorizePass() {
3126     return new LoopVectorize();
3127   }
3128 }
3129
3130