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