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