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