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