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