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