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