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