Refactor 'vectorizeLoop' no functionality change.
[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.
12 // The vectorizer uses the TargetTransformInfo analysis to estimate the costs
13 // of instructions in order to estimate the profitability of vectorization.
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/EquivalenceClasses.h"
51 #include "llvm/ADT/MapVector.h"
52 #include "llvm/ADT/SetVector.h"
53 #include "llvm/ADT/SmallPtrSet.h"
54 #include "llvm/ADT/SmallSet.h"
55 #include "llvm/ADT/SmallVector.h"
56 #include "llvm/ADT/StringExtras.h"
57 #include "llvm/Analysis/AliasAnalysis.h"
58 #include "llvm/Analysis/Dominators.h"
59 #include "llvm/Analysis/LoopInfo.h"
60 #include "llvm/Analysis/LoopIterator.h"
61 #include "llvm/Analysis/LoopPass.h"
62 #include "llvm/Analysis/ScalarEvolution.h"
63 #include "llvm/Analysis/ScalarEvolutionExpander.h"
64 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
65 #include "llvm/Analysis/TargetTransformInfo.h"
66 #include "llvm/Analysis/ValueTracking.h"
67 #include "llvm/Analysis/Verifier.h"
68 #include "llvm/IR/Constants.h"
69 #include "llvm/IR/DataLayout.h"
70 #include "llvm/IR/DerivedTypes.h"
71 #include "llvm/IR/Function.h"
72 #include "llvm/IR/IRBuilder.h"
73 #include "llvm/IR/Instructions.h"
74 #include "llvm/IR/IntrinsicInst.h"
75 #include "llvm/IR/LLVMContext.h"
76 #include "llvm/IR/Module.h"
77 #include "llvm/IR/Type.h"
78 #include "llvm/IR/Value.h"
79 #include "llvm/Pass.h"
80 #include "llvm/Support/CommandLine.h"
81 #include "llvm/Support/Debug.h"
82 #include "llvm/Support/PatternMatch.h"
83 #include "llvm/Support/raw_ostream.h"
84 #include "llvm/Support/ValueHandle.h"
85 #include "llvm/Target/TargetLibraryInfo.h"
86 #include "llvm/Transforms/Scalar.h"
87 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
88 #include "llvm/Transforms/Utils/Local.h"
89 #include <algorithm>
90 #include <map>
91
92 using namespace llvm;
93 using namespace llvm::PatternMatch;
94
95 static cl::opt<unsigned>
96 VectorizationFactor("force-vector-width", cl::init(0), cl::Hidden,
97                     cl::desc("Sets the SIMD width. Zero is autoselect."));
98
99 static cl::opt<unsigned>
100 VectorizationUnroll("force-vector-unroll", cl::init(0), cl::Hidden,
101                     cl::desc("Sets the vectorization unroll count. "
102                              "Zero is autoselect."));
103
104 static cl::opt<bool>
105 EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
106                    cl::desc("Enable if-conversion during vectorization."));
107
108 /// We don't vectorize loops with a known constant trip count below this number.
109 static cl::opt<unsigned>
110 TinyTripCountVectorThreshold("vectorizer-min-trip-count", cl::init(16),
111                              cl::Hidden,
112                              cl::desc("Don't vectorize loops with a constant "
113                                       "trip count that is smaller than this "
114                                       "value."));
115
116 /// We don't unroll loops with a known constant trip count below this number.
117 static const unsigned TinyTripCountUnrollThreshold = 128;
118
119 /// When performing memory disambiguation checks at runtime do not make more
120 /// than this number of comparisons.
121 static const unsigned RuntimeMemoryCheckThreshold = 8;
122
123 /// Maximum simd width.
124 static const unsigned MaxVectorWidth = 64;
125
126 /// Maximum vectorization unroll count.
127 static const unsigned MaxUnrollFactor = 16;
128
129 /// The cost of a loop that is considered 'small' by the unroller.
130 static const unsigned SmallLoopCost = 20;
131
132 namespace {
133
134 // Forward declarations.
135 class LoopVectorizationLegality;
136 class LoopVectorizationCostModel;
137
138 /// InnerLoopVectorizer vectorizes loops which contain only one basic
139 /// block to a specified vectorization factor (VF).
140 /// This class performs the widening of scalars into vectors, or multiple
141 /// scalars. This class also implements the following features:
142 /// * It inserts an epilogue loop for handling loops that don't have iteration
143 ///   counts that are known to be a multiple of the vectorization factor.
144 /// * It handles the code generation for reduction variables.
145 /// * Scalarization (implementation using scalars) of un-vectorizable
146 ///   instructions.
147 /// InnerLoopVectorizer does not perform any vectorization-legality
148 /// checks, and relies on the caller to check for the different legality
149 /// aspects. The InnerLoopVectorizer relies on the
150 /// LoopVectorizationLegality class to provide information about the induction
151 /// and reduction variables that were found to a given vectorization factor.
152 class InnerLoopVectorizer {
153 public:
154   InnerLoopVectorizer(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
155                       DominatorTree *DT, DataLayout *DL,
156                       const TargetLibraryInfo *TLI, unsigned VecWidth,
157                       unsigned UnrollFactor)
158       : OrigLoop(OrigLoop), SE(SE), LI(LI), DT(DT), DL(DL), TLI(TLI),
159         VF(VecWidth), UF(UnrollFactor), Builder(SE->getContext()), Induction(0),
160         OldInduction(0), WidenMap(UnrollFactor) {}
161
162   // Perform the actual loop widening (vectorization).
163   void vectorize(LoopVectorizationLegality *Legal) {
164     // Create a new empty loop. Unlink the old loop and connect the new one.
165     createEmptyLoop(Legal);
166     // Widen each instruction in the old loop to a new one in the new loop.
167     // Use the Legality module to find the induction and reduction variables.
168     vectorizeLoop(Legal);
169     // Register the new loop and update the analysis passes.
170     updateAnalysis();
171   }
172
173   virtual ~InnerLoopVectorizer() {}
174
175 protected:
176   /// A small list of PHINodes.
177   typedef SmallVector<PHINode*, 4> PhiVector;
178   /// When we unroll loops we have multiple vector values for each scalar.
179   /// This data structure holds the unrolled and vectorized values that
180   /// originated from one scalar instruction.
181   typedef SmallVector<Value*, 2> VectorParts;
182
183   // When we if-convert we need create edge masks. We have to cache values so
184   // that we don't end up with exponential recursion/IR.
185   typedef DenseMap<std::pair<BasicBlock*, BasicBlock*>,
186                    VectorParts> EdgeMaskCache;
187
188   /// Add code that checks at runtime if the accessed arrays overlap.
189   /// Returns the comparator value or NULL if no check is needed.
190   Instruction *addRuntimeCheck(LoopVectorizationLegality *Legal,
191                                Instruction *Loc);
192   /// Create an empty loop, based on the loop ranges of the old loop.
193   void createEmptyLoop(LoopVectorizationLegality *Legal);
194   /// Copy and widen the instructions from the old loop.
195   virtual void vectorizeLoop(LoopVectorizationLegality *Legal);
196
197   /// \brief The Loop exit block may have single value PHI nodes where the
198   /// incoming value is 'Undef'. While vectorizing we only handled real values
199   /// that were defined inside the loop. Here we fix the 'undef case'.
200   /// See PR14725.
201   void fixLCSSAPHIs();
202
203   /// A helper function that computes the predicate of the block BB, assuming
204   /// that the header block of the loop is set to True. It returns the *entry*
205   /// mask for the block BB.
206   VectorParts createBlockInMask(BasicBlock *BB);
207   /// A helper function that computes the predicate of the edge between SRC
208   /// and DST.
209   VectorParts createEdgeMask(BasicBlock *Src, BasicBlock *Dst);
210
211   /// A helper function to vectorize a single BB within the innermost loop.
212   void vectorizeBlockInLoop(LoopVectorizationLegality *Legal, BasicBlock *BB,
213                             PhiVector *PV);
214
215   /// Vectorize a single PHINode in a block. This method handles the induction
216   /// variable canonicalization. It supports both VF = 1 for unrolled loops and
217   /// arbitrary length vectors.
218   void widenPHIInstruction(Instruction *PN, VectorParts &Entry,
219                            LoopVectorizationLegality *Legal,
220                            unsigned UF, unsigned VF, PhiVector *PV);
221
222   /// Insert the new loop to the loop hierarchy and pass manager
223   /// and update the analysis passes.
224   void updateAnalysis();
225
226   /// This instruction is un-vectorizable. Implement it as a sequence
227   /// of scalars.
228   virtual void scalarizeInstruction(Instruction *Instr);
229
230   /// Vectorize Load and Store instructions,
231   virtual void vectorizeMemoryInstruction(Instruction *Instr,
232                                   LoopVectorizationLegality *Legal);
233
234   /// Create a broadcast instruction. This method generates a broadcast
235   /// instruction (shuffle) for loop invariant values and for the induction
236   /// value. If this is the induction variable then we extend it to N, N+1, ...
237   /// this is needed because each iteration in the loop corresponds to a SIMD
238   /// element.
239   virtual Value *getBroadcastInstrs(Value *V);
240
241   /// This function adds 0, 1, 2 ... to each vector element, starting at zero.
242   /// If Negate is set then negative numbers are added e.g. (0, -1, -2, ...).
243   /// The sequence starts at StartIndex.
244   virtual Value *getConsecutiveVector(Value* Val, int StartIdx, bool Negate);
245
246   /// When we go over instructions in the basic block we rely on previous
247   /// values within the current basic block or on loop invariant values.
248   /// When we widen (vectorize) values we place them in the map. If the values
249   /// are not within the map, they have to be loop invariant, so we simply
250   /// broadcast them into a vector.
251   VectorParts &getVectorValue(Value *V);
252
253   /// Generate a shuffle sequence that will reverse the vector Vec.
254   virtual Value *reverseVector(Value *Vec);
255
256   /// This is a helper class that holds the vectorizer state. It maps scalar
257   /// instructions to vector instructions. When the code is 'unrolled' then
258   /// then a single scalar value is mapped to multiple vector parts. The parts
259   /// are stored in the VectorPart type.
260   struct ValueMap {
261     /// C'tor.  UnrollFactor controls the number of vectors ('parts') that
262     /// are mapped.
263     ValueMap(unsigned UnrollFactor) : UF(UnrollFactor) {}
264
265     /// \return True if 'Key' is saved in the Value Map.
266     bool has(Value *Key) const { return MapStorage.count(Key); }
267
268     /// Initializes a new entry in the map. Sets all of the vector parts to the
269     /// save value in 'Val'.
270     /// \return A reference to a vector with splat values.
271     VectorParts &splat(Value *Key, Value *Val) {
272       VectorParts &Entry = MapStorage[Key];
273       Entry.assign(UF, Val);
274       return Entry;
275     }
276
277     ///\return A reference to the value that is stored at 'Key'.
278     VectorParts &get(Value *Key) {
279       VectorParts &Entry = MapStorage[Key];
280       if (Entry.empty())
281         Entry.resize(UF);
282       assert(Entry.size() == UF);
283       return Entry;
284     }
285
286   private:
287     /// The unroll factor. Each entry in the map stores this number of vector
288     /// elements.
289     unsigned UF;
290
291     /// Map storage. We use std::map and not DenseMap because insertions to a
292     /// dense map invalidates its iterators.
293     std::map<Value *, VectorParts> MapStorage;
294   };
295
296   /// The original loop.
297   Loop *OrigLoop;
298   /// Scev analysis to use.
299   ScalarEvolution *SE;
300   /// Loop Info.
301   LoopInfo *LI;
302   /// Dominator Tree.
303   DominatorTree *DT;
304   /// Data Layout.
305   DataLayout *DL;
306   /// Target Library Info.
307   const TargetLibraryInfo *TLI;
308
309   /// The vectorization SIMD factor to use. Each vector will have this many
310   /// vector elements.
311   unsigned VF;
312
313 protected:
314   /// The vectorization unroll factor to use. Each scalar is vectorized to this
315   /// many different vector instructions.
316   unsigned UF;
317
318   /// The builder that we use
319   IRBuilder<> Builder;
320
321   // --- Vectorization state ---
322
323   /// The vector-loop preheader.
324   BasicBlock *LoopVectorPreHeader;
325   /// The scalar-loop preheader.
326   BasicBlock *LoopScalarPreHeader;
327   /// Middle Block between the vector and the scalar.
328   BasicBlock *LoopMiddleBlock;
329   ///The ExitBlock of the scalar loop.
330   BasicBlock *LoopExitBlock;
331   ///The vector loop body.
332   BasicBlock *LoopVectorBody;
333   ///The scalar loop body.
334   BasicBlock *LoopScalarBody;
335   /// A list of all bypass blocks. The first block is the entry of the loop.
336   SmallVector<BasicBlock *, 4> LoopBypassBlocks;
337
338   /// The new Induction variable which was added to the new block.
339   PHINode *Induction;
340   /// The induction variable of the old basic block.
341   PHINode *OldInduction;
342   /// Holds the extended (to the widest induction type) start index.
343   Value *ExtendedIdx;
344   /// Maps scalars to widened vectors.
345   ValueMap WidenMap;
346   EdgeMaskCache MaskCache;
347 };
348
349 class InnerLoopUnroller : public InnerLoopVectorizer {
350 public:
351   InnerLoopUnroller(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
352                     DominatorTree *DT, DataLayout *DL,
353                     const TargetLibraryInfo *TLI, unsigned UnrollFactor) :
354     InnerLoopVectorizer(OrigLoop, SE, LI, DT, DL, TLI, 1, UnrollFactor) { }
355
356 private:
357   virtual void scalarizeInstruction(Instruction *Instr);
358   virtual void vectorizeMemoryInstruction(Instruction *Instr,
359                                           LoopVectorizationLegality *Legal);
360   virtual Value *getBroadcastInstrs(Value *V);
361   virtual Value *getConsecutiveVector(Value* Val, int StartIdx, bool Negate);
362   virtual Value *reverseVector(Value *Vec);
363 };
364
365 /// \brief Look for a meaningful debug location on the instruction or it's
366 /// operands.
367 static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
368   if (!I)
369     return I;
370
371   DebugLoc Empty;
372   if (I->getDebugLoc() != Empty)
373     return I;
374
375   for (User::op_iterator OI = I->op_begin(), OE = I->op_end(); OI != OE; ++OI) {
376     if (Instruction *OpInst = dyn_cast<Instruction>(*OI))
377       if (OpInst->getDebugLoc() != Empty)
378         return OpInst;
379   }
380
381   return I;
382 }
383
384 /// \brief Set the debug location in the builder using the debug location in the
385 /// instruction.
386 static void setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr) {
387   if (const Instruction *Inst = dyn_cast_or_null<Instruction>(Ptr))
388     B.SetCurrentDebugLocation(Inst->getDebugLoc());
389   else
390     B.SetCurrentDebugLocation(DebugLoc());
391 }
392
393 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
394 /// to what vectorization factor.
395 /// This class does not look at the profitability of vectorization, only the
396 /// legality. This class has two main kinds of checks:
397 /// * Memory checks - The code in canVectorizeMemory checks if vectorization
398 ///   will change the order of memory accesses in a way that will change the
399 ///   correctness of the program.
400 /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
401 /// checks for a number of different conditions, such as the availability of a
402 /// single induction variable, that all types are supported and vectorize-able,
403 /// etc. This code reflects the capabilities of InnerLoopVectorizer.
404 /// This class is also used by InnerLoopVectorizer for identifying
405 /// induction variable and the different reduction variables.
406 class LoopVectorizationLegality {
407 public:
408   LoopVectorizationLegality(Loop *L, ScalarEvolution *SE, DataLayout *DL,
409                             DominatorTree *DT, TargetLibraryInfo *TLI)
410       : TheLoop(L), SE(SE), DL(DL), DT(DT), TLI(TLI),
411         Induction(0), WidestIndTy(0), HasFunNoNaNAttr(false),
412         MaxSafeDepDistBytes(-1U) {}
413
414   /// This enum represents the kinds of reductions that we support.
415   enum ReductionKind {
416     RK_NoReduction, ///< Not a reduction.
417     RK_IntegerAdd,  ///< Sum of integers.
418     RK_IntegerMult, ///< Product of integers.
419     RK_IntegerOr,   ///< Bitwise or logical OR of numbers.
420     RK_IntegerAnd,  ///< Bitwise or logical AND of numbers.
421     RK_IntegerXor,  ///< Bitwise or logical XOR of numbers.
422     RK_IntegerMinMax, ///< Min/max implemented in terms of select(cmp()).
423     RK_FloatAdd,    ///< Sum of floats.
424     RK_FloatMult,   ///< Product of floats.
425     RK_FloatMinMax  ///< Min/max implemented in terms of select(cmp()).
426   };
427
428   /// This enum represents the kinds of inductions that we support.
429   enum InductionKind {
430     IK_NoInduction,         ///< Not an induction variable.
431     IK_IntInduction,        ///< Integer induction variable. Step = 1.
432     IK_ReverseIntInduction, ///< Reverse int induction variable. Step = -1.
433     IK_PtrInduction,        ///< Pointer induction var. Step = sizeof(elem).
434     IK_ReversePtrInduction  ///< Reverse ptr indvar. Step = - sizeof(elem).
435   };
436
437   // This enum represents the kind of minmax reduction.
438   enum MinMaxReductionKind {
439     MRK_Invalid,
440     MRK_UIntMin,
441     MRK_UIntMax,
442     MRK_SIntMin,
443     MRK_SIntMax,
444     MRK_FloatMin,
445     MRK_FloatMax
446   };
447
448   /// This POD struct holds information about reduction variables.
449   struct ReductionDescriptor {
450     ReductionDescriptor() : StartValue(0), LoopExitInstr(0),
451       Kind(RK_NoReduction), MinMaxKind(MRK_Invalid) {}
452
453     ReductionDescriptor(Value *Start, Instruction *Exit, ReductionKind K,
454                         MinMaxReductionKind MK)
455         : StartValue(Start), LoopExitInstr(Exit), Kind(K), MinMaxKind(MK) {}
456
457     // The starting value of the reduction.
458     // It does not have to be zero!
459     TrackingVH<Value> StartValue;
460     // The instruction who's value is used outside the loop.
461     Instruction *LoopExitInstr;
462     // The kind of the reduction.
463     ReductionKind Kind;
464     // If this a min/max reduction the kind of reduction.
465     MinMaxReductionKind MinMaxKind;
466   };
467
468   /// This POD struct holds information about a potential reduction operation.
469   struct ReductionInstDesc {
470     ReductionInstDesc(bool IsRedux, Instruction *I) :
471       IsReduction(IsRedux), PatternLastInst(I), MinMaxKind(MRK_Invalid) {}
472
473     ReductionInstDesc(Instruction *I, MinMaxReductionKind K) :
474       IsReduction(true), PatternLastInst(I), MinMaxKind(K) {}
475
476     // Is this instruction a reduction candidate.
477     bool IsReduction;
478     // The last instruction in a min/max pattern (select of the select(icmp())
479     // pattern), or the current reduction instruction otherwise.
480     Instruction *PatternLastInst;
481     // If this is a min/max pattern the comparison predicate.
482     MinMaxReductionKind MinMaxKind;
483   };
484
485   // This POD struct holds information about the memory runtime legality
486   // check that a group of pointers do not overlap.
487   struct RuntimePointerCheck {
488     RuntimePointerCheck() : Need(false) {}
489
490     /// Reset the state of the pointer runtime information.
491     void reset() {
492       Need = false;
493       Pointers.clear();
494       Starts.clear();
495       Ends.clear();
496     }
497
498     /// Insert a pointer and calculate the start and end SCEVs.
499     void insert(ScalarEvolution *SE, Loop *Lp, Value *Ptr, bool WritePtr,
500                 unsigned DepSetId);
501
502     /// This flag indicates if we need to add the runtime check.
503     bool Need;
504     /// Holds the pointers that we need to check.
505     SmallVector<TrackingVH<Value>, 2> Pointers;
506     /// Holds the pointer value at the beginning of the loop.
507     SmallVector<const SCEV*, 2> Starts;
508     /// Holds the pointer value at the end of the loop.
509     SmallVector<const SCEV*, 2> Ends;
510     /// Holds the information if this pointer is used for writing to memory.
511     SmallVector<bool, 2> IsWritePtr;
512     /// Holds the id of the set of pointers that could be dependent because of a
513     /// shared underlying object.
514     SmallVector<unsigned, 2> DependencySetId;
515   };
516
517   /// A POD for saving information about induction variables.
518   struct InductionInfo {
519     InductionInfo(Value *Start, InductionKind K) : StartValue(Start), IK(K) {}
520     InductionInfo() : StartValue(0), IK(IK_NoInduction) {}
521     /// Start value.
522     TrackingVH<Value> StartValue;
523     /// Induction kind.
524     InductionKind IK;
525   };
526
527   /// ReductionList contains the reduction descriptors for all
528   /// of the reductions that were found in the loop.
529   typedef DenseMap<PHINode*, ReductionDescriptor> ReductionList;
530
531   /// InductionList saves induction variables and maps them to the
532   /// induction descriptor.
533   typedef MapVector<PHINode*, InductionInfo> InductionList;
534
535   /// Returns true if it is legal to vectorize this loop.
536   /// This does not mean that it is profitable to vectorize this
537   /// loop, only that it is legal to do so.
538   bool canVectorize();
539
540   /// Returns the Induction variable.
541   PHINode *getInduction() { return Induction; }
542
543   /// Returns the reduction variables found in the loop.
544   ReductionList *getReductionVars() { return &Reductions; }
545
546   /// Returns the induction variables found in the loop.
547   InductionList *getInductionVars() { return &Inductions; }
548
549   /// Returns the widest induction type.
550   Type *getWidestInductionType() { return WidestIndTy; }
551
552   /// Returns True if V is an induction variable in this loop.
553   bool isInductionVariable(const Value *V);
554
555   /// Return true if the block BB needs to be predicated in order for the loop
556   /// to be vectorized.
557   bool blockNeedsPredication(BasicBlock *BB);
558
559   /// Check if this  pointer is consecutive when vectorizing. This happens
560   /// when the last index of the GEP is the induction variable, or that the
561   /// pointer itself is an induction variable.
562   /// This check allows us to vectorize A[idx] into a wide load/store.
563   /// Returns:
564   /// 0 - Stride is unknown or non consecutive.
565   /// 1 - Address is consecutive.
566   /// -1 - Address is consecutive, and decreasing.
567   int isConsecutivePtr(Value *Ptr);
568
569   /// Returns true if the value V is uniform within the loop.
570   bool isUniform(Value *V);
571
572   /// Returns true if this instruction will remain scalar after vectorization.
573   bool isUniformAfterVectorization(Instruction* I) { return Uniforms.count(I); }
574
575   /// Returns the information that we collected about runtime memory check.
576   RuntimePointerCheck *getRuntimePointerCheck() { return &PtrRtCheck; }
577
578   /// This function returns the identity element (or neutral element) for
579   /// the operation K.
580   static Constant *getReductionIdentity(ReductionKind K, Type *Tp);
581
582   unsigned getMaxSafeDepDistBytes() { return MaxSafeDepDistBytes; }
583
584 private:
585   /// Check if a single basic block loop is vectorizable.
586   /// At this point we know that this is a loop with a constant trip count
587   /// and we only need to check individual instructions.
588   bool canVectorizeInstrs();
589
590   /// When we vectorize loops we may change the order in which
591   /// we read and write from memory. This method checks if it is
592   /// legal to vectorize the code, considering only memory constrains.
593   /// Returns true if the loop is vectorizable
594   bool canVectorizeMemory();
595
596   /// Return true if we can vectorize this loop using the IF-conversion
597   /// transformation.
598   bool canVectorizeWithIfConvert();
599
600   /// Collect the variables that need to stay uniform after vectorization.
601   void collectLoopUniforms();
602
603   /// Return true if all of the instructions in the block can be speculatively
604   /// executed. \p SafePtrs is a list of addresses that are known to be legal
605   /// and we know that we can read from them without segfault.
606   bool blockCanBePredicated(BasicBlock *BB, SmallPtrSet<Value *, 8>& SafePtrs);
607
608   /// Returns True, if 'Phi' is the kind of reduction variable for type
609   /// 'Kind'. If this is a reduction variable, it adds it to ReductionList.
610   bool AddReductionVar(PHINode *Phi, ReductionKind Kind);
611   /// Returns a struct describing if the instruction 'I' can be a reduction
612   /// variable of type 'Kind'. If the reduction is a min/max pattern of
613   /// select(icmp()) this function advances the instruction pointer 'I' from the
614   /// compare instruction to the select instruction and stores this pointer in
615   /// 'PatternLastInst' member of the returned struct.
616   ReductionInstDesc isReductionInstr(Instruction *I, ReductionKind Kind,
617                                      ReductionInstDesc &Desc);
618   /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
619   /// pattern corresponding to a min(X, Y) or max(X, Y).
620   static ReductionInstDesc isMinMaxSelectCmpPattern(Instruction *I,
621                                                     ReductionInstDesc &Prev);
622   /// Returns the induction kind of Phi. This function may return NoInduction
623   /// if the PHI is not an induction variable.
624   InductionKind isInductionVariable(PHINode *Phi);
625
626   /// The loop that we evaluate.
627   Loop *TheLoop;
628   /// Scev analysis.
629   ScalarEvolution *SE;
630   /// DataLayout analysis.
631   DataLayout *DL;
632   /// Dominators.
633   DominatorTree *DT;
634   /// Target Library Info.
635   TargetLibraryInfo *TLI;
636
637   //  ---  vectorization state --- //
638
639   /// Holds the integer induction variable. This is the counter of the
640   /// loop.
641   PHINode *Induction;
642   /// Holds the reduction variables.
643   ReductionList Reductions;
644   /// Holds all of the induction variables that we found in the loop.
645   /// Notice that inductions don't need to start at zero and that induction
646   /// variables can be pointers.
647   InductionList Inductions;
648   /// Holds the widest induction type encountered.
649   Type *WidestIndTy;
650
651   /// Allowed outside users. This holds the reduction
652   /// vars which can be accessed from outside the loop.
653   SmallPtrSet<Value*, 4> AllowedExit;
654   /// This set holds the variables which are known to be uniform after
655   /// vectorization.
656   SmallPtrSet<Instruction*, 4> Uniforms;
657   /// We need to check that all of the pointers in this list are disjoint
658   /// at runtime.
659   RuntimePointerCheck PtrRtCheck;
660   /// Can we assume the absence of NaNs.
661   bool HasFunNoNaNAttr;
662
663   unsigned MaxSafeDepDistBytes;
664 };
665
666 /// LoopVectorizationCostModel - estimates the expected speedups due to
667 /// vectorization.
668 /// In many cases vectorization is not profitable. This can happen because of
669 /// a number of reasons. In this class we mainly attempt to predict the
670 /// expected speedup/slowdowns due to the supported instruction set. We use the
671 /// TargetTransformInfo to query the different backends for the cost of
672 /// different operations.
673 class LoopVectorizationCostModel {
674 public:
675   LoopVectorizationCostModel(Loop *L, ScalarEvolution *SE, LoopInfo *LI,
676                              LoopVectorizationLegality *Legal,
677                              const TargetTransformInfo &TTI,
678                              DataLayout *DL, const TargetLibraryInfo *TLI)
679       : TheLoop(L), SE(SE), LI(LI), Legal(Legal), TTI(TTI), DL(DL), TLI(TLI) {}
680
681   /// Information about vectorization costs
682   struct VectorizationFactor {
683     unsigned Width; // Vector width with best cost
684     unsigned Cost; // Cost of the loop with that width
685   };
686   /// \return The most profitable vectorization factor and the cost of that VF.
687   /// This method checks every power of two up to VF. If UserVF is not ZERO
688   /// then this vectorization factor will be selected if vectorization is
689   /// possible.
690   VectorizationFactor selectVectorizationFactor(bool OptForSize,
691                                                 unsigned UserVF);
692
693   /// \return The size (in bits) of the widest type in the code that
694   /// needs to be vectorized. We ignore values that remain scalar such as
695   /// 64 bit loop indices.
696   unsigned getWidestType();
697
698   /// \return The most profitable unroll factor.
699   /// If UserUF is non-zero then this method finds the best unroll-factor
700   /// based on register pressure and other parameters.
701   /// VF and LoopCost are the selected vectorization factor and the cost of the
702   /// selected VF.
703   unsigned selectUnrollFactor(bool OptForSize, unsigned UserUF, unsigned VF,
704                               unsigned LoopCost);
705
706   /// \brief A struct that represents some properties of the register usage
707   /// of a loop.
708   struct RegisterUsage {
709     /// Holds the number of loop invariant values that are used in the loop.
710     unsigned LoopInvariantRegs;
711     /// Holds the maximum number of concurrent live intervals in the loop.
712     unsigned MaxLocalUsers;
713     /// Holds the number of instructions in the loop.
714     unsigned NumInstructions;
715   };
716
717   /// \return  information about the register usage of the loop.
718   RegisterUsage calculateRegisterUsage();
719
720 private:
721   /// Returns the expected execution cost. The unit of the cost does
722   /// not matter because we use the 'cost' units to compare different
723   /// vector widths. The cost that is returned is *not* normalized by
724   /// the factor width.
725   unsigned expectedCost(unsigned VF);
726
727   /// Returns the execution time cost of an instruction for a given vector
728   /// width. Vector width of one means scalar.
729   unsigned getInstructionCost(Instruction *I, unsigned VF);
730
731   /// A helper function for converting Scalar types to vector types.
732   /// If the incoming type is void, we return void. If the VF is 1, we return
733   /// the scalar type.
734   static Type* ToVectorTy(Type *Scalar, unsigned VF);
735
736   /// Returns whether the instruction is a load or store and will be a emitted
737   /// as a vector operation.
738   bool isConsecutiveLoadOrStore(Instruction *I);
739
740   /// The loop that we evaluate.
741   Loop *TheLoop;
742   /// Scev analysis.
743   ScalarEvolution *SE;
744   /// Loop Info analysis.
745   LoopInfo *LI;
746   /// Vectorization legality.
747   LoopVectorizationLegality *Legal;
748   /// Vector target information.
749   const TargetTransformInfo &TTI;
750   /// Target data layout information.
751   DataLayout *DL;
752   /// Target Library Info.
753   const TargetLibraryInfo *TLI;
754 };
755
756 /// Utility class for getting and setting loop vectorizer hints in the form
757 /// of loop metadata.
758 struct LoopVectorizeHints {
759   /// Vectorization width.
760   unsigned Width;
761   /// Vectorization unroll factor.
762   unsigned Unroll;
763
764   LoopVectorizeHints(const Loop *L)
765   : Width(VectorizationFactor)
766   , Unroll(VectorizationUnroll)
767   , LoopID(L->getLoopID()) {
768     getHints(L);
769     // The command line options override any loop metadata except for when
770     // width == 1 which is used to indicate the loop is already vectorized.
771     if (VectorizationFactor.getNumOccurrences() > 0 && Width != 1)
772       Width = VectorizationFactor;
773     if (VectorizationUnroll.getNumOccurrences() > 0)
774       Unroll = VectorizationUnroll;
775   }
776
777   /// Return the loop vectorizer metadata prefix.
778   static StringRef Prefix() { return "llvm.vectorizer."; }
779
780   MDNode *createHint(LLVMContext &Context, StringRef Name, unsigned V) {
781     SmallVector<Value*, 2> Vals;
782     Vals.push_back(MDString::get(Context, Name));
783     Vals.push_back(ConstantInt::get(Type::getInt32Ty(Context), V));
784     return MDNode::get(Context, Vals);
785   }
786
787   /// Mark the loop L as already vectorized by setting the width to 1.
788   void setAlreadyVectorized(Loop *L) {
789     LLVMContext &Context = L->getHeader()->getContext();
790
791     Width = 1;
792
793     // Create a new loop id with one more operand for the already_vectorized
794     // hint. If the loop already has a loop id then copy the existing operands.
795     SmallVector<Value*, 4> Vals(1);
796     if (LoopID)
797       for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i)
798         Vals.push_back(LoopID->getOperand(i));
799
800     Vals.push_back(createHint(Context, Twine(Prefix(), "width").str(), Width));
801
802     MDNode *NewLoopID = MDNode::get(Context, Vals);
803     // Set operand 0 to refer to the loop id itself.
804     NewLoopID->replaceOperandWith(0, NewLoopID);
805
806     L->setLoopID(NewLoopID);
807     if (LoopID)
808       LoopID->replaceAllUsesWith(NewLoopID);
809
810     LoopID = NewLoopID;
811   }
812
813 private:
814   MDNode *LoopID;
815
816   /// Find hints specified in the loop metadata.
817   void getHints(const Loop *L) {
818     if (!LoopID)
819       return;
820
821     // First operand should refer to the loop id itself.
822     assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
823     assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
824
825     for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
826       const MDString *S = 0;
827       SmallVector<Value*, 4> Args;
828
829       // The expected hint is either a MDString or a MDNode with the first
830       // operand a MDString.
831       if (const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i))) {
832         if (!MD || MD->getNumOperands() == 0)
833           continue;
834         S = dyn_cast<MDString>(MD->getOperand(0));
835         for (unsigned i = 1, ie = MD->getNumOperands(); i < ie; ++i)
836           Args.push_back(MD->getOperand(i));
837       } else {
838         S = dyn_cast<MDString>(LoopID->getOperand(i));
839         assert(Args.size() == 0 && "too many arguments for MDString");
840       }
841
842       if (!S)
843         continue;
844
845       // Check if the hint starts with the vectorizer prefix.
846       StringRef Hint = S->getString();
847       if (!Hint.startswith(Prefix()))
848         continue;
849       // Remove the prefix.
850       Hint = Hint.substr(Prefix().size(), StringRef::npos);
851
852       if (Args.size() == 1)
853         getHint(Hint, Args[0]);
854     }
855   }
856
857   // Check string hint with one operand.
858   void getHint(StringRef Hint, Value *Arg) {
859     const ConstantInt *C = dyn_cast<ConstantInt>(Arg);
860     if (!C) return;
861     unsigned Val = C->getZExtValue();
862
863     if (Hint == "width") {
864       assert(isPowerOf2_32(Val) && Val <= MaxVectorWidth &&
865              "Invalid width metadata");
866       Width = Val;
867     } else if (Hint == "unroll") {
868       assert(isPowerOf2_32(Val) && Val <= MaxUnrollFactor &&
869              "Invalid unroll metadata");
870       Unroll = Val;
871     } else
872       DEBUG(dbgs() << "LV: ignoring unknown hint " << Hint);
873   }
874 };
875
876 /// The LoopVectorize Pass.
877 struct LoopVectorize : public LoopPass {
878   /// Pass identification, replacement for typeid
879   static char ID;
880
881   explicit LoopVectorize() : LoopPass(ID) {
882     initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
883   }
884
885   ScalarEvolution *SE;
886   DataLayout *DL;
887   LoopInfo *LI;
888   TargetTransformInfo *TTI;
889   DominatorTree *DT;
890   TargetLibraryInfo *TLI;
891
892   virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
893     // We only vectorize innermost loops.
894     if (!L->empty())
895       return false;
896
897     SE = &getAnalysis<ScalarEvolution>();
898     DL = getAnalysisIfAvailable<DataLayout>();
899     LI = &getAnalysis<LoopInfo>();
900     TTI = &getAnalysis<TargetTransformInfo>();
901     DT = &getAnalysis<DominatorTree>();
902     TLI = getAnalysisIfAvailable<TargetLibraryInfo>();
903
904     if (DL == NULL) {
905       DEBUG(dbgs() << "LV: Not vectorizing because of missing data layout");
906       return false;
907     }
908
909     DEBUG(dbgs() << "LV: Checking a loop in \"" <<
910           L->getHeader()->getParent()->getName() << "\"\n");
911
912     LoopVectorizeHints Hints(L);
913
914     if (Hints.Width == 1 && Hints.Unroll == 1) {
915       DEBUG(dbgs() << "LV: Not vectorizing.\n");
916       return false;
917     }
918
919     // Check if it is legal to vectorize the loop.
920     LoopVectorizationLegality LVL(L, SE, DL, DT, TLI);
921     if (!LVL.canVectorize()) {
922       DEBUG(dbgs() << "LV: Not vectorizing.\n");
923       return false;
924     }
925
926     // Use the cost model.
927     LoopVectorizationCostModel CM(L, SE, LI, &LVL, *TTI, DL, TLI);
928
929     // Check the function attributes to find out if this function should be
930     // optimized for size.
931     Function *F = L->getHeader()->getParent();
932     Attribute::AttrKind SzAttr = Attribute::OptimizeForSize;
933     Attribute::AttrKind FlAttr = Attribute::NoImplicitFloat;
934     unsigned FnIndex = AttributeSet::FunctionIndex;
935     bool OptForSize = F->getAttributes().hasAttribute(FnIndex, SzAttr);
936     bool NoFloat = F->getAttributes().hasAttribute(FnIndex, FlAttr);
937
938     if (NoFloat) {
939       DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
940             "attribute is used.\n");
941       return false;
942     }
943
944     // Select the optimal vectorization factor.
945     LoopVectorizationCostModel::VectorizationFactor VF;
946     VF = CM.selectVectorizationFactor(OptForSize, Hints.Width);
947     // Select the unroll factor.
948     unsigned UF = CM.selectUnrollFactor(OptForSize, Hints.Unroll, VF.Width,
949                                         VF.Cost);
950
951     if (VF.Width == 1) {
952       DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
953     }
954
955     DEBUG(dbgs() << "LV: Found a vectorizable loop ("<< VF.Width << ") in "<<
956           F->getParent()->getModuleIdentifier()<<"\n");
957     DEBUG(dbgs() << "LV: Unroll Factor is " << UF << "\n");
958
959     if (VF.Width == 1) {
960       if (UF == 1)
961         return false;
962       // We decided not to vectorize, but we may want to unroll.
963       InnerLoopUnroller Unroller(L, SE, LI, DT, DL, TLI, UF);
964       Unroller.vectorize(&LVL);
965     } else {
966       // If we decided that it is *legal* to vectorize the loop then do it.
967       InnerLoopVectorizer LB(L, SE, LI, DT, DL, TLI, VF.Width, UF);
968       LB.vectorize(&LVL);
969     }
970
971     // Mark the loop as already vectorized to avoid vectorizing again.
972     Hints.setAlreadyVectorized(L);
973
974     DEBUG(verifyFunction(*L->getHeader()->getParent()));
975     return true;
976   }
977
978   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
979     LoopPass::getAnalysisUsage(AU);
980     AU.addRequiredID(LoopSimplifyID);
981     AU.addRequiredID(LCSSAID);
982     AU.addRequired<DominatorTree>();
983     AU.addRequired<LoopInfo>();
984     AU.addRequired<ScalarEvolution>();
985     AU.addRequired<TargetTransformInfo>();
986     AU.addPreserved<LoopInfo>();
987     AU.addPreserved<DominatorTree>();
988   }
989
990 };
991
992 } // end anonymous namespace
993
994 //===----------------------------------------------------------------------===//
995 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
996 // LoopVectorizationCostModel.
997 //===----------------------------------------------------------------------===//
998
999 void
1000 LoopVectorizationLegality::RuntimePointerCheck::insert(ScalarEvolution *SE,
1001                                                        Loop *Lp, Value *Ptr,
1002                                                        bool WritePtr,
1003                                                        unsigned DepSetId) {
1004   const SCEV *Sc = SE->getSCEV(Ptr);
1005   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
1006   assert(AR && "Invalid addrec expression");
1007   const SCEV *Ex = SE->getBackedgeTakenCount(Lp);
1008   const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
1009   Pointers.push_back(Ptr);
1010   Starts.push_back(AR->getStart());
1011   Ends.push_back(ScEnd);
1012   IsWritePtr.push_back(WritePtr);
1013   DependencySetId.push_back(DepSetId);
1014 }
1015
1016 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
1017   // Save the current insertion location.
1018   Instruction *Loc = Builder.GetInsertPoint();
1019
1020   // We need to place the broadcast of invariant variables outside the loop.
1021   Instruction *Instr = dyn_cast<Instruction>(V);
1022   bool NewInstr = (Instr && Instr->getParent() == LoopVectorBody);
1023   bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
1024
1025   // Place the code for broadcasting invariant variables in the new preheader.
1026   if (Invariant)
1027     Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
1028
1029   // Broadcast the scalar into all locations in the vector.
1030   Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
1031
1032   // Restore the builder insertion point.
1033   if (Invariant)
1034     Builder.SetInsertPoint(Loc);
1035
1036   return Shuf;
1037 }
1038
1039 Value *InnerLoopVectorizer::getConsecutiveVector(Value* Val, int StartIdx,
1040                                                  bool Negate) {
1041   assert(Val->getType()->isVectorTy() && "Must be a vector");
1042   assert(Val->getType()->getScalarType()->isIntegerTy() &&
1043          "Elem must be an integer");
1044   // Create the types.
1045   Type *ITy = Val->getType()->getScalarType();
1046   VectorType *Ty = cast<VectorType>(Val->getType());
1047   int VLen = Ty->getNumElements();
1048   SmallVector<Constant*, 8> Indices;
1049
1050   // Create a vector of consecutive numbers from zero to VF.
1051   for (int i = 0; i < VLen; ++i) {
1052     int64_t Idx = Negate ? (-i) : i;
1053     Indices.push_back(ConstantInt::get(ITy, StartIdx + Idx, Negate));
1054   }
1055
1056   // Add the consecutive indices to the vector value.
1057   Constant *Cv = ConstantVector::get(Indices);
1058   assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
1059   return Builder.CreateAdd(Val, Cv, "induction");
1060 }
1061
1062 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
1063   assert(Ptr->getType()->isPointerTy() && "Unexpected non ptr");
1064   // Make sure that the pointer does not point to structs.
1065   if (cast<PointerType>(Ptr->getType())->getElementType()->isAggregateType())
1066     return 0;
1067
1068   // If this value is a pointer induction variable we know it is consecutive.
1069   PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
1070   if (Phi && Inductions.count(Phi)) {
1071     InductionInfo II = Inductions[Phi];
1072     if (IK_PtrInduction == II.IK)
1073       return 1;
1074     else if (IK_ReversePtrInduction == II.IK)
1075       return -1;
1076   }
1077
1078   GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
1079   if (!Gep)
1080     return 0;
1081
1082   unsigned NumOperands = Gep->getNumOperands();
1083   Value *LastIndex = Gep->getOperand(NumOperands - 1);
1084
1085   Value *GpPtr = Gep->getPointerOperand();
1086   // If this GEP value is a consecutive pointer induction variable and all of
1087   // the indices are constant then we know it is consecutive. We can
1088   Phi = dyn_cast<PHINode>(GpPtr);
1089   if (Phi && Inductions.count(Phi)) {
1090
1091     // Make sure that the pointer does not point to structs.
1092     PointerType *GepPtrType = cast<PointerType>(GpPtr->getType());
1093     if (GepPtrType->getElementType()->isAggregateType())
1094       return 0;
1095
1096     // Make sure that all of the index operands are loop invariant.
1097     for (unsigned i = 1; i < NumOperands; ++i)
1098       if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
1099         return 0;
1100
1101     InductionInfo II = Inductions[Phi];
1102     if (IK_PtrInduction == II.IK)
1103       return 1;
1104     else if (IK_ReversePtrInduction == II.IK)
1105       return -1;
1106   }
1107
1108   // Check that all of the gep indices are uniform except for the last.
1109   for (unsigned i = 0; i < NumOperands - 1; ++i)
1110     if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
1111       return 0;
1112
1113   // We can emit wide load/stores only if the last index is the induction
1114   // variable.
1115   const SCEV *Last = SE->getSCEV(LastIndex);
1116   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
1117     const SCEV *Step = AR->getStepRecurrence(*SE);
1118
1119     // The memory is consecutive because the last index is consecutive
1120     // and all other indices are loop invariant.
1121     if (Step->isOne())
1122       return 1;
1123     if (Step->isAllOnesValue())
1124       return -1;
1125   }
1126
1127   return 0;
1128 }
1129
1130 bool LoopVectorizationLegality::isUniform(Value *V) {
1131   return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
1132 }
1133
1134 InnerLoopVectorizer::VectorParts&
1135 InnerLoopVectorizer::getVectorValue(Value *V) {
1136   assert(V != Induction && "The new induction variable should not be used.");
1137   assert(!V->getType()->isVectorTy() && "Can't widen a vector");
1138
1139   // If we have this scalar in the map, return it.
1140   if (WidenMap.has(V))
1141     return WidenMap.get(V);
1142
1143   // If this scalar is unknown, assume that it is a constant or that it is
1144   // loop invariant. Broadcast V and save the value for future uses.
1145   Value *B = getBroadcastInstrs(V);
1146   return WidenMap.splat(V, B);
1147 }
1148
1149 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
1150   assert(Vec->getType()->isVectorTy() && "Invalid type");
1151   SmallVector<Constant*, 8> ShuffleMask;
1152   for (unsigned i = 0; i < VF; ++i)
1153     ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
1154
1155   return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
1156                                      ConstantVector::get(ShuffleMask),
1157                                      "reverse");
1158 }
1159
1160
1161 void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr,
1162                                              LoopVectorizationLegality *Legal) {
1163   // Attempt to issue a wide load.
1164   LoadInst *LI = dyn_cast<LoadInst>(Instr);
1165   StoreInst *SI = dyn_cast<StoreInst>(Instr);
1166
1167   assert((LI || SI) && "Invalid Load/Store instruction");
1168
1169   Type *ScalarDataTy = LI ? LI->getType() : SI->getValueOperand()->getType();
1170   Type *DataTy = VectorType::get(ScalarDataTy, VF);
1171   Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
1172   unsigned Alignment = LI ? LI->getAlignment() : SI->getAlignment();
1173   unsigned AddressSpace = Ptr->getType()->getPointerAddressSpace();
1174   unsigned ScalarAllocatedSize = DL->getTypeAllocSize(ScalarDataTy);
1175   unsigned VectorElementSize = DL->getTypeStoreSize(DataTy)/VF;
1176
1177   if (ScalarAllocatedSize != VectorElementSize)
1178     return scalarizeInstruction(Instr);
1179
1180   // If the pointer is loop invariant or if it is non consecutive,
1181   // scalarize the load.
1182   int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
1183   bool Reverse = ConsecutiveStride < 0;
1184   bool UniformLoad = LI && Legal->isUniform(Ptr);
1185   if (!ConsecutiveStride || UniformLoad)
1186     return scalarizeInstruction(Instr);
1187
1188   Constant *Zero = Builder.getInt32(0);
1189   VectorParts &Entry = WidenMap.get(Instr);
1190
1191   // Handle consecutive loads/stores.
1192   GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
1193   if (Gep && Legal->isInductionVariable(Gep->getPointerOperand())) {
1194     setDebugLocFromInst(Builder, Gep);
1195     Value *PtrOperand = Gep->getPointerOperand();
1196     Value *FirstBasePtr = getVectorValue(PtrOperand)[0];
1197     FirstBasePtr = Builder.CreateExtractElement(FirstBasePtr, Zero);
1198
1199     // Create the new GEP with the new induction variable.
1200     GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1201     Gep2->setOperand(0, FirstBasePtr);
1202     Gep2->setName("gep.indvar.base");
1203     Ptr = Builder.Insert(Gep2);
1204   } else if (Gep) {
1205     setDebugLocFromInst(Builder, Gep);
1206     assert(SE->isLoopInvariant(SE->getSCEV(Gep->getPointerOperand()),
1207                                OrigLoop) && "Base ptr must be invariant");
1208
1209     // The last index does not have to be the induction. It can be
1210     // consecutive and be a function of the index. For example A[I+1];
1211     unsigned NumOperands = Gep->getNumOperands();
1212     unsigned LastOperand = NumOperands - 1;
1213     // Create the new GEP with the new induction variable.
1214     GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
1215
1216     for (unsigned i = 0; i < NumOperands; ++i) {
1217       Value *GepOperand = Gep->getOperand(i);
1218       Instruction *GepOperandInst = dyn_cast<Instruction>(GepOperand);
1219
1220       // Update last index or loop invariant instruction anchored in loop.
1221       if (i == LastOperand ||
1222           (GepOperandInst && OrigLoop->contains(GepOperandInst))) {
1223         assert((i == LastOperand ||
1224                SE->isLoopInvariant(SE->getSCEV(GepOperandInst), OrigLoop)) &&
1225                "Must be last index or loop invariant");
1226
1227         VectorParts &GEPParts = getVectorValue(GepOperand);
1228         Value *Index = GEPParts[0];
1229         Index = Builder.CreateExtractElement(Index, Zero);
1230         Gep2->setOperand(i, Index);
1231         Gep2->setName("gep.indvar.idx");
1232       }
1233     }
1234     Ptr = Builder.Insert(Gep2);
1235   } else {
1236     // Use the induction element ptr.
1237     assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
1238     setDebugLocFromInst(Builder, Ptr);
1239     VectorParts &PtrVal = getVectorValue(Ptr);
1240     Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
1241   }
1242
1243   // Handle Stores:
1244   if (SI) {
1245     assert(!Legal->isUniform(SI->getPointerOperand()) &&
1246            "We do not allow storing to uniform addresses");
1247     setDebugLocFromInst(Builder, SI);
1248     // We don't want to update the value in the map as it might be used in
1249     // another expression. So don't use a reference type for "StoredVal".
1250     VectorParts StoredVal = getVectorValue(SI->getValueOperand());
1251
1252     for (unsigned Part = 0; Part < UF; ++Part) {
1253       // Calculate the pointer for the specific unroll-part.
1254       Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1255
1256       if (Reverse) {
1257         // If we store to reverse consecutive memory locations then we need
1258         // to reverse the order of elements in the stored value.
1259         StoredVal[Part] = reverseVector(StoredVal[Part]);
1260         // If the address is consecutive but reversed, then the
1261         // wide store needs to start at the last vector element.
1262         PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1263         PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1264       }
1265
1266       Value *VecPtr = Builder.CreateBitCast(PartPtr,
1267                                             DataTy->getPointerTo(AddressSpace));
1268       Builder.CreateStore(StoredVal[Part], VecPtr)->setAlignment(Alignment);
1269     }
1270     return;
1271   }
1272
1273   // Handle loads.
1274   assert(LI && "Must have a load instruction");
1275   setDebugLocFromInst(Builder, LI);
1276   for (unsigned Part = 0; Part < UF; ++Part) {
1277     // Calculate the pointer for the specific unroll-part.
1278     Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
1279
1280     if (Reverse) {
1281       // If the address is consecutive but reversed, then the
1282       // wide store needs to start at the last vector element.
1283       PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
1284       PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
1285     }
1286
1287     Value *VecPtr = Builder.CreateBitCast(PartPtr,
1288                                           DataTy->getPointerTo(AddressSpace));
1289     Value *LI = Builder.CreateLoad(VecPtr, "wide.load");
1290     cast<LoadInst>(LI)->setAlignment(Alignment);
1291     Entry[Part] = Reverse ? reverseVector(LI) :  LI;
1292   }
1293 }
1294
1295 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr) {
1296   assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
1297   // Holds vector parameters or scalars, in case of uniform vals.
1298   SmallVector<VectorParts, 4> Params;
1299
1300   setDebugLocFromInst(Builder, Instr);
1301
1302   // Find all of the vectorized parameters.
1303   for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
1304     Value *SrcOp = Instr->getOperand(op);
1305
1306     // If we are accessing the old induction variable, use the new one.
1307     if (SrcOp == OldInduction) {
1308       Params.push_back(getVectorValue(SrcOp));
1309       continue;
1310     }
1311
1312     // Try using previously calculated values.
1313     Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
1314
1315     // If the src is an instruction that appeared earlier in the basic block
1316     // then it should already be vectorized.
1317     if (SrcInst && OrigLoop->contains(SrcInst)) {
1318       assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
1319       // The parameter is a vector value from earlier.
1320       Params.push_back(WidenMap.get(SrcInst));
1321     } else {
1322       // The parameter is a scalar from outside the loop. Maybe even a constant.
1323       VectorParts Scalars;
1324       Scalars.append(UF, SrcOp);
1325       Params.push_back(Scalars);
1326     }
1327   }
1328
1329   assert(Params.size() == Instr->getNumOperands() &&
1330          "Invalid number of operands");
1331
1332   // Does this instruction return a value ?
1333   bool IsVoidRetTy = Instr->getType()->isVoidTy();
1334
1335   Value *UndefVec = IsVoidRetTy ? 0 :
1336     UndefValue::get(VectorType::get(Instr->getType(), VF));
1337   // Create a new entry in the WidenMap and initialize it to Undef or Null.
1338   VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
1339
1340   // For each vector unroll 'part':
1341   for (unsigned Part = 0; Part < UF; ++Part) {
1342     // For each scalar that we create:
1343     for (unsigned Width = 0; Width < VF; ++Width) {
1344       Instruction *Cloned = Instr->clone();
1345       if (!IsVoidRetTy)
1346         Cloned->setName(Instr->getName() + ".cloned");
1347       // Replace the operands of the cloned instrucions with extracted scalars.
1348       for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
1349         Value *Op = Params[op][Part];
1350         // Param is a vector. Need to extract the right lane.
1351         if (Op->getType()->isVectorTy())
1352           Op = Builder.CreateExtractElement(Op, Builder.getInt32(Width));
1353         Cloned->setOperand(op, Op);
1354       }
1355
1356       // Place the cloned scalar in the new loop.
1357       Builder.Insert(Cloned);
1358
1359       // If the original scalar returns a value we need to place it in a vector
1360       // so that future users will be able to use it.
1361       if (!IsVoidRetTy)
1362         VecResults[Part] = Builder.CreateInsertElement(VecResults[Part], Cloned,
1363                                                        Builder.getInt32(Width));
1364     }
1365   }
1366 }
1367
1368 Instruction *
1369 InnerLoopVectorizer::addRuntimeCheck(LoopVectorizationLegality *Legal,
1370                                      Instruction *Loc) {
1371   LoopVectorizationLegality::RuntimePointerCheck *PtrRtCheck =
1372   Legal->getRuntimePointerCheck();
1373
1374   if (!PtrRtCheck->Need)
1375     return NULL;
1376
1377   unsigned NumPointers = PtrRtCheck->Pointers.size();
1378   SmallVector<TrackingVH<Value> , 2> Starts;
1379   SmallVector<TrackingVH<Value> , 2> Ends;
1380
1381   SCEVExpander Exp(*SE, "induction");
1382
1383   // Use this type for pointer arithmetic.
1384   Type* PtrArithTy = Type::getInt8PtrTy(Loc->getContext(), 0);
1385
1386   for (unsigned i = 0; i < NumPointers; ++i) {
1387     Value *Ptr = PtrRtCheck->Pointers[i];
1388     const SCEV *Sc = SE->getSCEV(Ptr);
1389
1390     if (SE->isLoopInvariant(Sc, OrigLoop)) {
1391       DEBUG(dbgs() << "LV: Adding RT check for a loop invariant ptr:" <<
1392             *Ptr <<"\n");
1393       Starts.push_back(Ptr);
1394       Ends.push_back(Ptr);
1395     } else {
1396       DEBUG(dbgs() << "LV: Adding RT check for range:" << *Ptr <<"\n");
1397
1398       Value *Start = Exp.expandCodeFor(PtrRtCheck->Starts[i], PtrArithTy, Loc);
1399       Value *End = Exp.expandCodeFor(PtrRtCheck->Ends[i], PtrArithTy, Loc);
1400       Starts.push_back(Start);
1401       Ends.push_back(End);
1402     }
1403   }
1404
1405   IRBuilder<> ChkBuilder(Loc);
1406   // Our instructions might fold to a constant.
1407   Value *MemoryRuntimeCheck = 0;
1408   for (unsigned i = 0; i < NumPointers; ++i) {
1409     for (unsigned j = i+1; j < NumPointers; ++j) {
1410       // No need to check if two readonly pointers intersect.
1411       if (!PtrRtCheck->IsWritePtr[i] && !PtrRtCheck->IsWritePtr[j])
1412         continue;
1413
1414       // Only need to check pointers between two different dependency sets.
1415       if (PtrRtCheck->DependencySetId[i] == PtrRtCheck->DependencySetId[j])
1416        continue;
1417
1418       Value *Start0 = ChkBuilder.CreateBitCast(Starts[i], PtrArithTy, "bc");
1419       Value *Start1 = ChkBuilder.CreateBitCast(Starts[j], PtrArithTy, "bc");
1420       Value *End0 =   ChkBuilder.CreateBitCast(Ends[i],   PtrArithTy, "bc");
1421       Value *End1 =   ChkBuilder.CreateBitCast(Ends[j],   PtrArithTy, "bc");
1422
1423       Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0");
1424       Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1");
1425       Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
1426       if (MemoryRuntimeCheck)
1427         IsConflict = ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict,
1428                                          "conflict.rdx");
1429       MemoryRuntimeCheck = IsConflict;
1430     }
1431   }
1432
1433   // We have to do this trickery because the IRBuilder might fold the check to a
1434   // constant expression in which case there is no Instruction anchored in a
1435   // the block.
1436   LLVMContext &Ctx = Loc->getContext();
1437   Instruction * Check = BinaryOperator::CreateAnd(MemoryRuntimeCheck,
1438                                                   ConstantInt::getTrue(Ctx));
1439   ChkBuilder.Insert(Check, "memcheck.conflict");
1440   return Check;
1441 }
1442
1443 void
1444 InnerLoopVectorizer::createEmptyLoop(LoopVectorizationLegality *Legal) {
1445   /*
1446    In this function we generate a new loop. The new loop will contain
1447    the vectorized instructions while the old loop will continue to run the
1448    scalar remainder.
1449
1450        [ ] <-- vector loop bypass (may consist of multiple blocks).
1451      /  |
1452     /   v
1453    |   [ ]     <-- vector pre header.
1454    |    |
1455    |    v
1456    |   [  ] \
1457    |   [  ]_|   <-- vector loop.
1458    |    |
1459     \   v
1460       >[ ]   <--- middle-block.
1461      /  |
1462     /   v
1463    |   [ ]     <--- new preheader.
1464    |    |
1465    |    v
1466    |   [ ] \
1467    |   [ ]_|   <-- old scalar loop to handle remainder.
1468     \   |
1469      \  v
1470       >[ ]     <-- exit block.
1471    ...
1472    */
1473
1474   BasicBlock *OldBasicBlock = OrigLoop->getHeader();
1475   BasicBlock *BypassBlock = OrigLoop->getLoopPreheader();
1476   BasicBlock *ExitBlock = OrigLoop->getExitBlock();
1477   assert(ExitBlock && "Must have an exit block");
1478
1479   // Some loops have a single integer induction variable, while other loops
1480   // don't. One example is c++ iterators that often have multiple pointer
1481   // induction variables. In the code below we also support a case where we
1482   // don't have a single induction variable.
1483   OldInduction = Legal->getInduction();
1484   Type *IdxTy = Legal->getWidestInductionType();
1485
1486   // Find the loop boundaries.
1487   const SCEV *ExitCount = SE->getBackedgeTakenCount(OrigLoop);
1488   assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
1489
1490   // Get the total trip count from the count by adding 1.
1491   ExitCount = SE->getAddExpr(ExitCount,
1492                              SE->getConstant(ExitCount->getType(), 1));
1493
1494   // Expand the trip count and place the new instructions in the preheader.
1495   // Notice that the pre-header does not change, only the loop body.
1496   SCEVExpander Exp(*SE, "induction");
1497
1498   // Count holds the overall loop count (N).
1499   Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
1500                                    BypassBlock->getTerminator());
1501
1502   // The loop index does not have to start at Zero. Find the original start
1503   // value from the induction PHI node. If we don't have an induction variable
1504   // then we know that it starts at zero.
1505   Builder.SetInsertPoint(BypassBlock->getTerminator());
1506   Value *StartIdx = ExtendedIdx = OldInduction ?
1507     Builder.CreateZExt(OldInduction->getIncomingValueForBlock(BypassBlock),
1508                        IdxTy):
1509     ConstantInt::get(IdxTy, 0);
1510
1511   assert(BypassBlock && "Invalid loop structure");
1512   LoopBypassBlocks.push_back(BypassBlock);
1513
1514   // Split the single block loop into the two loop structure described above.
1515   BasicBlock *VectorPH =
1516   BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
1517   BasicBlock *VecBody =
1518   VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
1519   BasicBlock *MiddleBlock =
1520   VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
1521   BasicBlock *ScalarPH =
1522   MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
1523
1524   // Create and register the new vector loop.
1525   Loop* Lp = new Loop();
1526   Loop *ParentLoop = OrigLoop->getParentLoop();
1527
1528   // Insert the new loop into the loop nest and register the new basic blocks
1529   // before calling any utilities such as SCEV that require valid LoopInfo.
1530   if (ParentLoop) {
1531     ParentLoop->addChildLoop(Lp);
1532     ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase());
1533     ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase());
1534     ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase());
1535   } else {
1536     LI->addTopLevelLoop(Lp);
1537   }
1538   Lp->addBasicBlockToLoop(VecBody, LI->getBase());
1539
1540   // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
1541   // inside the loop.
1542   Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
1543
1544   // Generate the induction variable.
1545   setDebugLocFromInst(Builder, getDebugLocFromInstOrOperands(OldInduction));
1546   Induction = Builder.CreatePHI(IdxTy, 2, "index");
1547   // The loop step is equal to the vectorization factor (num of SIMD elements)
1548   // times the unroll factor (num of SIMD instructions).
1549   Constant *Step = ConstantInt::get(IdxTy, VF * UF);
1550
1551   // This is the IR builder that we use to add all of the logic for bypassing
1552   // the new vector loop.
1553   IRBuilder<> BypassBuilder(BypassBlock->getTerminator());
1554   setDebugLocFromInst(BypassBuilder,
1555                       getDebugLocFromInstOrOperands(OldInduction));
1556
1557   // We may need to extend the index in case there is a type mismatch.
1558   // We know that the count starts at zero and does not overflow.
1559   if (Count->getType() != IdxTy) {
1560     // The exit count can be of pointer type. Convert it to the correct
1561     // integer type.
1562     if (ExitCount->getType()->isPointerTy())
1563       Count = BypassBuilder.CreatePointerCast(Count, IdxTy, "ptrcnt.to.int");
1564     else
1565       Count = BypassBuilder.CreateZExtOrTrunc(Count, IdxTy, "cnt.cast");
1566   }
1567
1568   // Add the start index to the loop count to get the new end index.
1569   Value *IdxEnd = BypassBuilder.CreateAdd(Count, StartIdx, "end.idx");
1570
1571   // Now we need to generate the expression for N - (N % VF), which is
1572   // the part that the vectorized body will execute.
1573   Value *R = BypassBuilder.CreateURem(Count, Step, "n.mod.vf");
1574   Value *CountRoundDown = BypassBuilder.CreateSub(Count, R, "n.vec");
1575   Value *IdxEndRoundDown = BypassBuilder.CreateAdd(CountRoundDown, StartIdx,
1576                                                      "end.idx.rnd.down");
1577
1578   // Now, compare the new count to zero. If it is zero skip the vector loop and
1579   // jump to the scalar loop.
1580   Value *Cmp = BypassBuilder.CreateICmpEQ(IdxEndRoundDown, StartIdx,
1581                                           "cmp.zero");
1582
1583   BasicBlock *LastBypassBlock = BypassBlock;
1584
1585   // Generate the code that checks in runtime if arrays overlap. We put the
1586   // checks into a separate block to make the more common case of few elements
1587   // faster.
1588   Instruction *MemRuntimeCheck = addRuntimeCheck(Legal,
1589                                                  BypassBlock->getTerminator());
1590   if (MemRuntimeCheck) {
1591     // Create a new block containing the memory check.
1592     BasicBlock *CheckBlock = BypassBlock->splitBasicBlock(MemRuntimeCheck,
1593                                                           "vector.memcheck");
1594     if (ParentLoop)
1595       ParentLoop->addBasicBlockToLoop(CheckBlock, LI->getBase());
1596     LoopBypassBlocks.push_back(CheckBlock);
1597
1598     // Replace the branch into the memory check block with a conditional branch
1599     // for the "few elements case".
1600     Instruction *OldTerm = BypassBlock->getTerminator();
1601     BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
1602     OldTerm->eraseFromParent();
1603
1604     Cmp = MemRuntimeCheck;
1605     LastBypassBlock = CheckBlock;
1606   }
1607
1608   LastBypassBlock->getTerminator()->eraseFromParent();
1609   BranchInst::Create(MiddleBlock, VectorPH, Cmp,
1610                      LastBypassBlock);
1611
1612   // We are going to resume the execution of the scalar loop.
1613   // Go over all of the induction variables that we found and fix the
1614   // PHIs that are left in the scalar version of the loop.
1615   // The starting values of PHI nodes depend on the counter of the last
1616   // iteration in the vectorized loop.
1617   // If we come from a bypass edge then we need to start from the original
1618   // start value.
1619
1620   // This variable saves the new starting index for the scalar loop.
1621   PHINode *ResumeIndex = 0;
1622   LoopVectorizationLegality::InductionList::iterator I, E;
1623   LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
1624   // Set builder to point to last bypass block.
1625   BypassBuilder.SetInsertPoint(LoopBypassBlocks.back()->getTerminator());
1626   for (I = List->begin(), E = List->end(); I != E; ++I) {
1627     PHINode *OrigPhi = I->first;
1628     LoopVectorizationLegality::InductionInfo II = I->second;
1629
1630     Type *ResumeValTy = (OrigPhi == OldInduction) ? IdxTy : OrigPhi->getType();
1631     PHINode *ResumeVal = PHINode::Create(ResumeValTy, 2, "resume.val",
1632                                          MiddleBlock->getTerminator());
1633     // We might have extended the type of the induction variable but we need a
1634     // truncated version for the scalar loop.
1635     PHINode *TruncResumeVal = (OrigPhi == OldInduction) ?
1636       PHINode::Create(OrigPhi->getType(), 2, "trunc.resume.val",
1637                       MiddleBlock->getTerminator()) : 0;
1638
1639     Value *EndValue = 0;
1640     switch (II.IK) {
1641     case LoopVectorizationLegality::IK_NoInduction:
1642       llvm_unreachable("Unknown induction");
1643     case LoopVectorizationLegality::IK_IntInduction: {
1644       // Handle the integer induction counter.
1645       assert(OrigPhi->getType()->isIntegerTy() && "Invalid type");
1646
1647       // We have the canonical induction variable.
1648       if (OrigPhi == OldInduction) {
1649         // Create a truncated version of the resume value for the scalar loop,
1650         // we might have promoted the type to a larger width.
1651         EndValue =
1652           BypassBuilder.CreateTrunc(IdxEndRoundDown, OrigPhi->getType());
1653         // The new PHI merges the original incoming value, in case of a bypass,
1654         // or the value at the end of the vectorized loop.
1655         for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
1656           TruncResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
1657         TruncResumeVal->addIncoming(EndValue, VecBody);
1658
1659         // We know what the end value is.
1660         EndValue = IdxEndRoundDown;
1661         // We also know which PHI node holds it.
1662         ResumeIndex = ResumeVal;
1663         break;
1664       }
1665
1666       // Not the canonical induction variable - add the vector loop count to the
1667       // start value.
1668       Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown,
1669                                                    II.StartValue->getType(),
1670                                                    "cast.crd");
1671       EndValue = BypassBuilder.CreateAdd(CRD, II.StartValue , "ind.end");
1672       break;
1673     }
1674     case LoopVectorizationLegality::IK_ReverseIntInduction: {
1675       // Convert the CountRoundDown variable to the PHI size.
1676       Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown,
1677                                                    II.StartValue->getType(),
1678                                                    "cast.crd");
1679       // Handle reverse integer induction counter.
1680       EndValue = BypassBuilder.CreateSub(II.StartValue, CRD, "rev.ind.end");
1681       break;
1682     }
1683     case LoopVectorizationLegality::IK_PtrInduction: {
1684       // For pointer induction variables, calculate the offset using
1685       // the end index.
1686       EndValue = BypassBuilder.CreateGEP(II.StartValue, CountRoundDown,
1687                                          "ptr.ind.end");
1688       break;
1689     }
1690     case LoopVectorizationLegality::IK_ReversePtrInduction: {
1691       // The value at the end of the loop for the reverse pointer is calculated
1692       // by creating a GEP with a negative index starting from the start value.
1693       Value *Zero = ConstantInt::get(CountRoundDown->getType(), 0);
1694       Value *NegIdx = BypassBuilder.CreateSub(Zero, CountRoundDown,
1695                                               "rev.ind.end");
1696       EndValue = BypassBuilder.CreateGEP(II.StartValue, NegIdx,
1697                                          "rev.ptr.ind.end");
1698       break;
1699     }
1700     }// end of case
1701
1702     // The new PHI merges the original incoming value, in case of a bypass,
1703     // or the value at the end of the vectorized loop.
1704     for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I) {
1705       if (OrigPhi == OldInduction)
1706         ResumeVal->addIncoming(StartIdx, LoopBypassBlocks[I]);
1707       else
1708         ResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
1709     }
1710     ResumeVal->addIncoming(EndValue, VecBody);
1711
1712     // Fix the scalar body counter (PHI node).
1713     unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
1714     // The old inductions phi node in the scalar body needs the truncated value.
1715     if (OrigPhi == OldInduction)
1716       OrigPhi->setIncomingValue(BlockIdx, TruncResumeVal);
1717     else
1718       OrigPhi->setIncomingValue(BlockIdx, ResumeVal);
1719   }
1720
1721   // If we are generating a new induction variable then we also need to
1722   // generate the code that calculates the exit value. This value is not
1723   // simply the end of the counter because we may skip the vectorized body
1724   // in case of a runtime check.
1725   if (!OldInduction){
1726     assert(!ResumeIndex && "Unexpected resume value found");
1727     ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val",
1728                                   MiddleBlock->getTerminator());
1729     for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
1730       ResumeIndex->addIncoming(StartIdx, LoopBypassBlocks[I]);
1731     ResumeIndex->addIncoming(IdxEndRoundDown, VecBody);
1732   }
1733
1734   // Make sure that we found the index where scalar loop needs to continue.
1735   assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() &&
1736          "Invalid resume Index");
1737
1738   // Add a check in the middle block to see if we have completed
1739   // all of the iterations in the first vector loop.
1740   // If (N - N%VF) == N, then we *don't* need to run the remainder.
1741   Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd,
1742                                 ResumeIndex, "cmp.n",
1743                                 MiddleBlock->getTerminator());
1744
1745   BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
1746   // Remove the old terminator.
1747   MiddleBlock->getTerminator()->eraseFromParent();
1748
1749   // Create i+1 and fill the PHINode.
1750   Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
1751   Induction->addIncoming(StartIdx, VectorPH);
1752   Induction->addIncoming(NextIdx, VecBody);
1753   // Create the compare.
1754   Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown);
1755   Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
1756
1757   // Now we have two terminators. Remove the old one from the block.
1758   VecBody->getTerminator()->eraseFromParent();
1759
1760   // Get ready to start creating new instructions into the vectorized body.
1761   Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
1762
1763   // Save the state.
1764   LoopVectorPreHeader = VectorPH;
1765   LoopScalarPreHeader = ScalarPH;
1766   LoopMiddleBlock = MiddleBlock;
1767   LoopExitBlock = ExitBlock;
1768   LoopVectorBody = VecBody;
1769   LoopScalarBody = OldBasicBlock;
1770 }
1771
1772 /// This function returns the identity element (or neutral element) for
1773 /// the operation K.
1774 Constant*
1775 LoopVectorizationLegality::getReductionIdentity(ReductionKind K, Type *Tp) {
1776   switch (K) {
1777   case RK_IntegerXor:
1778   case RK_IntegerAdd:
1779   case RK_IntegerOr:
1780     // Adding, Xoring, Oring zero to a number does not change it.
1781     return ConstantInt::get(Tp, 0);
1782   case RK_IntegerMult:
1783     // Multiplying a number by 1 does not change it.
1784     return ConstantInt::get(Tp, 1);
1785   case RK_IntegerAnd:
1786     // AND-ing a number with an all-1 value does not change it.
1787     return ConstantInt::get(Tp, -1, true);
1788   case  RK_FloatMult:
1789     // Multiplying a number by 1 does not change it.
1790     return ConstantFP::get(Tp, 1.0L);
1791   case  RK_FloatAdd:
1792     // Adding zero to a number does not change it.
1793     return ConstantFP::get(Tp, 0.0L);
1794   default:
1795     llvm_unreachable("Unknown reduction kind");
1796   }
1797 }
1798
1799 static Intrinsic::ID
1800 getIntrinsicIDForCall(CallInst *CI, const TargetLibraryInfo *TLI) {
1801   // If we have an intrinsic call, check if it is trivially vectorizable.
1802   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
1803     switch (II->getIntrinsicID()) {
1804     case Intrinsic::sqrt:
1805     case Intrinsic::sin:
1806     case Intrinsic::cos:
1807     case Intrinsic::exp:
1808     case Intrinsic::exp2:
1809     case Intrinsic::log:
1810     case Intrinsic::log10:
1811     case Intrinsic::log2:
1812     case Intrinsic::fabs:
1813     case Intrinsic::copysign:
1814     case Intrinsic::floor:
1815     case Intrinsic::ceil:
1816     case Intrinsic::trunc:
1817     case Intrinsic::rint:
1818     case Intrinsic::nearbyint:
1819     case Intrinsic::round:
1820     case Intrinsic::pow:
1821     case Intrinsic::fma:
1822     case Intrinsic::fmuladd:
1823     case Intrinsic::lifetime_start:
1824     case Intrinsic::lifetime_end:
1825       return II->getIntrinsicID();
1826     default:
1827       return Intrinsic::not_intrinsic;
1828     }
1829   }
1830
1831   if (!TLI)
1832     return Intrinsic::not_intrinsic;
1833
1834   LibFunc::Func Func;
1835   Function *F = CI->getCalledFunction();
1836   // We're going to make assumptions on the semantics of the functions, check
1837   // that the target knows that it's available in this environment.
1838   if (!F || !TLI->getLibFunc(F->getName(), Func))
1839     return Intrinsic::not_intrinsic;
1840
1841   // Otherwise check if we have a call to a function that can be turned into a
1842   // vector intrinsic.
1843   switch (Func) {
1844   default:
1845     break;
1846   case LibFunc::sin:
1847   case LibFunc::sinf:
1848   case LibFunc::sinl:
1849     return Intrinsic::sin;
1850   case LibFunc::cos:
1851   case LibFunc::cosf:
1852   case LibFunc::cosl:
1853     return Intrinsic::cos;
1854   case LibFunc::exp:
1855   case LibFunc::expf:
1856   case LibFunc::expl:
1857     return Intrinsic::exp;
1858   case LibFunc::exp2:
1859   case LibFunc::exp2f:
1860   case LibFunc::exp2l:
1861     return Intrinsic::exp2;
1862   case LibFunc::log:
1863   case LibFunc::logf:
1864   case LibFunc::logl:
1865     return Intrinsic::log;
1866   case LibFunc::log10:
1867   case LibFunc::log10f:
1868   case LibFunc::log10l:
1869     return Intrinsic::log10;
1870   case LibFunc::log2:
1871   case LibFunc::log2f:
1872   case LibFunc::log2l:
1873     return Intrinsic::log2;
1874   case LibFunc::fabs:
1875   case LibFunc::fabsf:
1876   case LibFunc::fabsl:
1877     return Intrinsic::fabs;
1878   case LibFunc::copysign:
1879   case LibFunc::copysignf:
1880   case LibFunc::copysignl:
1881     return Intrinsic::copysign;
1882   case LibFunc::floor:
1883   case LibFunc::floorf:
1884   case LibFunc::floorl:
1885     return Intrinsic::floor;
1886   case LibFunc::ceil:
1887   case LibFunc::ceilf:
1888   case LibFunc::ceill:
1889     return Intrinsic::ceil;
1890   case LibFunc::trunc:
1891   case LibFunc::truncf:
1892   case LibFunc::truncl:
1893     return Intrinsic::trunc;
1894   case LibFunc::rint:
1895   case LibFunc::rintf:
1896   case LibFunc::rintl:
1897     return Intrinsic::rint;
1898   case LibFunc::nearbyint:
1899   case LibFunc::nearbyintf:
1900   case LibFunc::nearbyintl:
1901     return Intrinsic::nearbyint;
1902   case LibFunc::round:
1903   case LibFunc::roundf:
1904   case LibFunc::roundl:
1905     return Intrinsic::round;
1906   case LibFunc::pow:
1907   case LibFunc::powf:
1908   case LibFunc::powl:
1909     return Intrinsic::pow;
1910   }
1911
1912   return Intrinsic::not_intrinsic;
1913 }
1914
1915 /// This function translates the reduction kind to an LLVM binary operator.
1916 static unsigned
1917 getReductionBinOp(LoopVectorizationLegality::ReductionKind Kind) {
1918   switch (Kind) {
1919     case LoopVectorizationLegality::RK_IntegerAdd:
1920       return Instruction::Add;
1921     case LoopVectorizationLegality::RK_IntegerMult:
1922       return Instruction::Mul;
1923     case LoopVectorizationLegality::RK_IntegerOr:
1924       return Instruction::Or;
1925     case LoopVectorizationLegality::RK_IntegerAnd:
1926       return Instruction::And;
1927     case LoopVectorizationLegality::RK_IntegerXor:
1928       return Instruction::Xor;
1929     case LoopVectorizationLegality::RK_FloatMult:
1930       return Instruction::FMul;
1931     case LoopVectorizationLegality::RK_FloatAdd:
1932       return Instruction::FAdd;
1933     case LoopVectorizationLegality::RK_IntegerMinMax:
1934       return Instruction::ICmp;
1935     case LoopVectorizationLegality::RK_FloatMinMax:
1936       return Instruction::FCmp;
1937     default:
1938       llvm_unreachable("Unknown reduction operation");
1939   }
1940 }
1941
1942 Value *createMinMaxOp(IRBuilder<> &Builder,
1943                       LoopVectorizationLegality::MinMaxReductionKind RK,
1944                       Value *Left,
1945                       Value *Right) {
1946   CmpInst::Predicate P = CmpInst::ICMP_NE;
1947   switch (RK) {
1948   default:
1949     llvm_unreachable("Unknown min/max reduction kind");
1950   case LoopVectorizationLegality::MRK_UIntMin:
1951     P = CmpInst::ICMP_ULT;
1952     break;
1953   case LoopVectorizationLegality::MRK_UIntMax:
1954     P = CmpInst::ICMP_UGT;
1955     break;
1956   case LoopVectorizationLegality::MRK_SIntMin:
1957     P = CmpInst::ICMP_SLT;
1958     break;
1959   case LoopVectorizationLegality::MRK_SIntMax:
1960     P = CmpInst::ICMP_SGT;
1961     break;
1962   case LoopVectorizationLegality::MRK_FloatMin:
1963     P = CmpInst::FCMP_OLT;
1964     break;
1965   case LoopVectorizationLegality::MRK_FloatMax:
1966     P = CmpInst::FCMP_OGT;
1967     break;
1968   }
1969
1970   Value *Cmp;
1971   if (RK == LoopVectorizationLegality::MRK_FloatMin ||
1972       RK == LoopVectorizationLegality::MRK_FloatMax)
1973     Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp");
1974   else
1975     Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp");
1976
1977   Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
1978   return Select;
1979 }
1980
1981 void
1982 InnerLoopVectorizer::vectorizeLoop(LoopVectorizationLegality *Legal) {
1983   //===------------------------------------------------===//
1984   //
1985   // Notice: any optimization or new instruction that go
1986   // into the code below should be also be implemented in
1987   // the cost-model.
1988   //
1989   //===------------------------------------------------===//
1990   Constant *Zero = Builder.getInt32(0);
1991
1992   // In order to support reduction variables we need to be able to vectorize
1993   // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
1994   // stages. First, we create a new vector PHI node with no incoming edges.
1995   // We use this value when we vectorize all of the instructions that use the
1996   // PHI. Next, after all of the instructions in the block are complete we
1997   // add the new incoming edges to the PHI. At this point all of the
1998   // instructions in the basic block are vectorized, so we can use them to
1999   // construct the PHI.
2000   PhiVector RdxPHIsToFix;
2001
2002   // Scan the loop in a topological order to ensure that defs are vectorized
2003   // before users.
2004   LoopBlocksDFS DFS(OrigLoop);
2005   DFS.perform(LI);
2006
2007   // Vectorize all of the blocks in the original loop.
2008   for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
2009        be = DFS.endRPO(); bb != be; ++bb)
2010     vectorizeBlockInLoop(Legal, *bb, &RdxPHIsToFix);
2011
2012   // At this point every instruction in the original loop is widened to
2013   // a vector form. We are almost done. Now, we need to fix the PHI nodes
2014   // that we vectorized. The PHI nodes are currently empty because we did
2015   // not want to introduce cycles. Notice that the remaining PHI nodes
2016   // that we need to fix are reduction variables.
2017
2018   // Create the 'reduced' values for each of the induction vars.
2019   // The reduced values are the vector values that we scalarize and combine
2020   // after the loop is finished.
2021   for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
2022        it != e; ++it) {
2023     PHINode *RdxPhi = *it;
2024     assert(RdxPhi && "Unable to recover vectorized PHI");
2025
2026     // Find the reduction variable descriptor.
2027     assert(Legal->getReductionVars()->count(RdxPhi) &&
2028            "Unable to find the reduction variable");
2029     LoopVectorizationLegality::ReductionDescriptor RdxDesc =
2030     (*Legal->getReductionVars())[RdxPhi];
2031
2032     setDebugLocFromInst(Builder, RdxDesc.StartValue);
2033
2034     // We need to generate a reduction vector from the incoming scalar.
2035     // To do so, we need to generate the 'identity' vector and overide
2036     // one of the elements with the incoming scalar reduction. We need
2037     // to do it in the vector-loop preheader.
2038     Builder.SetInsertPoint(LoopBypassBlocks.front()->getTerminator());
2039
2040     // This is the vector-clone of the value that leaves the loop.
2041     VectorParts &VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
2042     Type *VecTy = VectorExit[0]->getType();
2043
2044     // Find the reduction identity variable. Zero for addition, or, xor,
2045     // one for multiplication, -1 for And.
2046     Value *Identity;
2047     Value *VectorStart;
2048     if (RdxDesc.Kind == LoopVectorizationLegality::RK_IntegerMinMax ||
2049         RdxDesc.Kind == LoopVectorizationLegality::RK_FloatMinMax) {
2050       // MinMax reduction have the start value as their identify.
2051       if (VF == 1) {
2052         VectorStart = Identity = RdxDesc.StartValue;
2053       } else {
2054         VectorStart = Identity = Builder.CreateVectorSplat(VF,
2055                                                            RdxDesc.StartValue,
2056                                                            "minmax.ident");
2057       }
2058     } else {
2059       // Handle other reduction kinds:
2060       Constant *Iden =
2061       LoopVectorizationLegality::getReductionIdentity(RdxDesc.Kind,
2062                                                       VecTy->getScalarType());
2063       if (VF == 1) {
2064         Identity = Iden;
2065         // This vector is the Identity vector where the first element is the
2066         // incoming scalar reduction.
2067         VectorStart = RdxDesc.StartValue;
2068       } else {
2069         Identity = ConstantVector::getSplat(VF, Iden);
2070
2071         // This vector is the Identity vector where the first element is the
2072         // incoming scalar reduction.
2073         VectorStart = Builder.CreateInsertElement(Identity,
2074                                                   RdxDesc.StartValue, Zero);
2075       }
2076     }
2077
2078     // Fix the vector-loop phi.
2079     // We created the induction variable so we know that the
2080     // preheader is the first entry.
2081     BasicBlock *VecPreheader = Induction->getIncomingBlock(0);
2082
2083     // Reductions do not have to start at zero. They can start with
2084     // any loop invariant values.
2085     VectorParts &VecRdxPhi = WidenMap.get(RdxPhi);
2086     BasicBlock *Latch = OrigLoop->getLoopLatch();
2087     Value *LoopVal = RdxPhi->getIncomingValueForBlock(Latch);
2088     VectorParts &Val = getVectorValue(LoopVal);
2089     for (unsigned part = 0; part < UF; ++part) {
2090       // Make sure to add the reduction stat value only to the
2091       // first unroll part.
2092       Value *StartVal = (part == 0) ? VectorStart : Identity;
2093       cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal, VecPreheader);
2094       cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part], LoopVectorBody);
2095     }
2096
2097     // Before each round, move the insertion point right between
2098     // the PHIs and the values we are going to write.
2099     // This allows us to write both PHINodes and the extractelement
2100     // instructions.
2101     Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
2102
2103     VectorParts RdxParts;
2104     setDebugLocFromInst(Builder, RdxDesc.LoopExitInstr);
2105     for (unsigned part = 0; part < UF; ++part) {
2106       // This PHINode contains the vectorized reduction variable, or
2107       // the initial value vector, if we bypass the vector loop.
2108       VectorParts &RdxExitVal = getVectorValue(RdxDesc.LoopExitInstr);
2109       PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
2110       Value *StartVal = (part == 0) ? VectorStart : Identity;
2111       for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
2112         NewPhi->addIncoming(StartVal, LoopBypassBlocks[I]);
2113       NewPhi->addIncoming(RdxExitVal[part], LoopVectorBody);
2114       RdxParts.push_back(NewPhi);
2115     }
2116
2117     // Reduce all of the unrolled parts into a single vector.
2118     Value *ReducedPartRdx = RdxParts[0];
2119     unsigned Op = getReductionBinOp(RdxDesc.Kind);
2120     setDebugLocFromInst(Builder, ReducedPartRdx);
2121     for (unsigned part = 1; part < UF; ++part) {
2122       if (Op != Instruction::ICmp && Op != Instruction::FCmp)
2123         ReducedPartRdx = Builder.CreateBinOp((Instruction::BinaryOps)Op,
2124                                              RdxParts[part], ReducedPartRdx,
2125                                              "bin.rdx");
2126       else
2127         ReducedPartRdx = createMinMaxOp(Builder, RdxDesc.MinMaxKind,
2128                                         ReducedPartRdx, RdxParts[part]);
2129     }
2130
2131     if (VF > 1) {
2132       // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
2133       // and vector ops, reducing the set of values being computed by half each
2134       // round.
2135       assert(isPowerOf2_32(VF) &&
2136              "Reduction emission only supported for pow2 vectors!");
2137       Value *TmpVec = ReducedPartRdx;
2138       SmallVector<Constant*, 32> ShuffleMask(VF, 0);
2139       for (unsigned i = VF; i != 1; i >>= 1) {
2140         // Move the upper half of the vector to the lower half.
2141         for (unsigned j = 0; j != i/2; ++j)
2142           ShuffleMask[j] = Builder.getInt32(i/2 + j);
2143
2144         // Fill the rest of the mask with undef.
2145         std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
2146                   UndefValue::get(Builder.getInt32Ty()));
2147
2148         Value *Shuf =
2149         Builder.CreateShuffleVector(TmpVec,
2150                                     UndefValue::get(TmpVec->getType()),
2151                                     ConstantVector::get(ShuffleMask),
2152                                     "rdx.shuf");
2153
2154         if (Op != Instruction::ICmp && Op != Instruction::FCmp)
2155           TmpVec = Builder.CreateBinOp((Instruction::BinaryOps)Op, TmpVec, Shuf,
2156                                        "bin.rdx");
2157         else
2158           TmpVec = createMinMaxOp(Builder, RdxDesc.MinMaxKind, TmpVec, Shuf);
2159       }
2160
2161       // The result is in the first element of the vector.
2162       ReducedPartRdx = Builder.CreateExtractElement(TmpVec,
2163                                                     Builder.getInt32(0));
2164     }
2165
2166     // Now, we need to fix the users of the reduction variable
2167     // inside and outside of the scalar remainder loop.
2168     // We know that the loop is in LCSSA form. We need to update the
2169     // PHI nodes in the exit blocks.
2170     for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
2171          LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
2172       PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
2173       if (!LCSSAPhi) continue;
2174
2175       // All PHINodes need to have a single entry edge, or two if
2176       // we already fixed them.
2177       assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
2178
2179       // We found our reduction value exit-PHI. Update it with the
2180       // incoming bypass edge.
2181       if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
2182         // Add an edge coming from the bypass.
2183         LCSSAPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
2184         break;
2185       }
2186     }// end of the LCSSA phi scan.
2187
2188     // Fix the scalar loop reduction variable with the incoming reduction sum
2189     // from the vector body and from the backedge value.
2190     int IncomingEdgeBlockIdx =
2191     (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
2192     assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
2193     // Pick the other block.
2194     int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
2195     (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, ReducedPartRdx);
2196     (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
2197   }// end of for each redux variable.
2198  
2199   fixLCSSAPHIs();
2200 }
2201
2202 void InnerLoopVectorizer::fixLCSSAPHIs() {
2203   for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
2204        LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
2205     PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
2206     if (!LCSSAPhi) continue;
2207     if (LCSSAPhi->getNumIncomingValues() == 1)
2208       LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
2209                             LoopMiddleBlock);
2210   }
2211
2212
2213 InnerLoopVectorizer::VectorParts
2214 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
2215   assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
2216          "Invalid edge");
2217
2218   // Look for cached value.
2219   std::pair<BasicBlock*, BasicBlock*> Edge(Src, Dst);
2220   EdgeMaskCache::iterator ECEntryIt = MaskCache.find(Edge);
2221   if (ECEntryIt != MaskCache.end())
2222     return ECEntryIt->second;
2223
2224   VectorParts SrcMask = createBlockInMask(Src);
2225
2226   // The terminator has to be a branch inst!
2227   BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
2228   assert(BI && "Unexpected terminator found");
2229
2230   if (BI->isConditional()) {
2231     VectorParts EdgeMask = getVectorValue(BI->getCondition());
2232
2233     if (BI->getSuccessor(0) != Dst)
2234       for (unsigned part = 0; part < UF; ++part)
2235         EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
2236
2237     for (unsigned part = 0; part < UF; ++part)
2238       EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
2239
2240     MaskCache[Edge] = EdgeMask;
2241     return EdgeMask;
2242   }
2243
2244   MaskCache[Edge] = SrcMask;
2245   return SrcMask;
2246 }
2247
2248 InnerLoopVectorizer::VectorParts
2249 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
2250   assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
2251
2252   // Loop incoming mask is all-one.
2253   if (OrigLoop->getHeader() == BB) {
2254     Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
2255     return getVectorValue(C);
2256   }
2257
2258   // This is the block mask. We OR all incoming edges, and with zero.
2259   Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
2260   VectorParts BlockMask = getVectorValue(Zero);
2261
2262   // For each pred:
2263   for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
2264     VectorParts EM = createEdgeMask(*it, BB);
2265     for (unsigned part = 0; part < UF; ++part)
2266       BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
2267   }
2268
2269   return BlockMask;
2270 }
2271
2272 void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN,
2273                                               InnerLoopVectorizer::VectorParts &Entry,
2274                                               LoopVectorizationLegality *Legal,
2275                                               unsigned UF, unsigned VF, PhiVector *PV) {
2276   PHINode* P = cast<PHINode>(PN);
2277   // Handle reduction variables:
2278   if (Legal->getReductionVars()->count(P)) {
2279     for (unsigned part = 0; part < UF; ++part) {
2280       // This is phase one of vectorizing PHIs.
2281       Type *VecTy = (VF == 1) ? PN->getType() :
2282       VectorType::get(PN->getType(), VF);
2283       Entry[part] = PHINode::Create(VecTy, 2, "vec.phi",
2284                                     LoopVectorBody-> getFirstInsertionPt());
2285     }
2286     PV->push_back(P);
2287     return;
2288   }
2289
2290   setDebugLocFromInst(Builder, P);
2291   // Check for PHI nodes that are lowered to vector selects.
2292   if (P->getParent() != OrigLoop->getHeader()) {
2293     // We know that all PHIs in non header blocks are converted into
2294     // selects, so we don't have to worry about the insertion order and we
2295     // can just use the builder.
2296     // At this point we generate the predication tree. There may be
2297     // duplications since this is a simple recursive scan, but future
2298     // optimizations will clean it up.
2299
2300     unsigned NumIncoming = P->getNumIncomingValues();
2301
2302     // Generate a sequence of selects of the form:
2303     // SELECT(Mask3, In3,
2304     //      SELECT(Mask2, In2,
2305     //                   ( ...)))
2306     for (unsigned In = 0; In < NumIncoming; In++) {
2307       VectorParts Cond = createEdgeMask(P->getIncomingBlock(In),
2308                                         P->getParent());
2309       VectorParts &In0 = getVectorValue(P->getIncomingValue(In));
2310
2311       for (unsigned part = 0; part < UF; ++part) {
2312         // We might have single edge PHIs (blocks) - use an identity
2313         // 'select' for the first PHI operand.
2314         if (In == 0)
2315           Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
2316                                              In0[part]);
2317         else
2318           // Select between the current value and the previous incoming edge
2319           // based on the incoming mask.
2320           Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
2321                                              Entry[part], "predphi");
2322       }
2323     }
2324     return;
2325   }
2326
2327   // This PHINode must be an induction variable.
2328   // Make sure that we know about it.
2329   assert(Legal->getInductionVars()->count(P) &&
2330          "Not an induction variable");
2331
2332   LoopVectorizationLegality::InductionInfo II =
2333   Legal->getInductionVars()->lookup(P);
2334
2335   switch (II.IK) {
2336     case LoopVectorizationLegality::IK_NoInduction:
2337       llvm_unreachable("Unknown induction");
2338     case LoopVectorizationLegality::IK_IntInduction: {
2339       assert(P->getType() == II.StartValue->getType() && "Types must match");
2340       Type *PhiTy = P->getType();
2341       Value *Broadcasted;
2342       if (P == OldInduction) {
2343         // Handle the canonical induction variable. We might have had to
2344         // extend the type.
2345         Broadcasted = Builder.CreateTrunc(Induction, PhiTy);
2346       } else {
2347         // Handle other induction variables that are now based on the
2348         // canonical one.
2349         Value *NormalizedIdx = Builder.CreateSub(Induction, ExtendedIdx,
2350                                                  "normalized.idx");
2351         NormalizedIdx = Builder.CreateSExtOrTrunc(NormalizedIdx, PhiTy);
2352         Broadcasted = Builder.CreateAdd(II.StartValue, NormalizedIdx,
2353                                         "offset.idx");
2354       }
2355       Broadcasted = getBroadcastInstrs(Broadcasted);
2356       // After broadcasting the induction variable we need to make the vector
2357       // consecutive by adding 0, 1, 2, etc.
2358       for (unsigned part = 0; part < UF; ++part)
2359         Entry[part] = getConsecutiveVector(Broadcasted, VF * part, false);
2360       return;
2361     }
2362     case LoopVectorizationLegality::IK_ReverseIntInduction:
2363     case LoopVectorizationLegality::IK_PtrInduction:
2364     case LoopVectorizationLegality::IK_ReversePtrInduction:
2365       // Handle reverse integer and pointer inductions.
2366       Value *StartIdx = ExtendedIdx;
2367       // This is the normalized GEP that starts counting at zero.
2368       Value *NormalizedIdx = Builder.CreateSub(Induction, StartIdx,
2369                                                "normalized.idx");
2370
2371       // Handle the reverse integer induction variable case.
2372       if (LoopVectorizationLegality::IK_ReverseIntInduction == II.IK) {
2373         IntegerType *DstTy = cast<IntegerType>(II.StartValue->getType());
2374         Value *CNI = Builder.CreateSExtOrTrunc(NormalizedIdx, DstTy,
2375                                                "resize.norm.idx");
2376         Value *ReverseInd  = Builder.CreateSub(II.StartValue, CNI,
2377                                                "reverse.idx");
2378
2379         // This is a new value so do not hoist it out.
2380         Value *Broadcasted = getBroadcastInstrs(ReverseInd);
2381         // After broadcasting the induction variable we need to make the
2382         // vector consecutive by adding  ... -3, -2, -1, 0.
2383         for (unsigned part = 0; part < UF; ++part)
2384           Entry[part] = getConsecutiveVector(Broadcasted, -(int)VF * part,
2385                                              true);
2386         return;
2387       }
2388
2389       // Handle the pointer induction variable case.
2390       assert(P->getType()->isPointerTy() && "Unexpected type.");
2391
2392       // Is this a reverse induction ptr or a consecutive induction ptr.
2393       bool Reverse = (LoopVectorizationLegality::IK_ReversePtrInduction ==
2394                       II.IK);
2395
2396       // This is the vector of results. Notice that we don't generate
2397       // vector geps because scalar geps result in better code.
2398       for (unsigned part = 0; part < UF; ++part) {
2399         if (VF == 1) {
2400           int EltIndex = (part) * (Reverse ? -1 : 1);
2401           Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex);
2402           Value *GlobalIdx;
2403           if (Reverse)
2404             GlobalIdx = Builder.CreateSub(Idx, NormalizedIdx, "gep.ridx");
2405           else
2406             GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx, "gep.idx");
2407
2408           Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
2409                                              "next.gep");
2410           Entry[part] = SclrGep;
2411           continue;
2412         }
2413
2414         Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
2415         for (unsigned int i = 0; i < VF; ++i) {
2416           int EltIndex = (i + part * VF) * (Reverse ? -1 : 1);
2417           Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex);
2418           Value *GlobalIdx;
2419           if (!Reverse)
2420             GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx, "gep.idx");
2421           else
2422             GlobalIdx = Builder.CreateSub(Idx, NormalizedIdx, "gep.ridx");
2423
2424           Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
2425                                              "next.gep");
2426           VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
2427                                                Builder.getInt32(i),
2428                                                "insert.gep");
2429         }
2430         Entry[part] = VecVal;
2431       }
2432       return;
2433   }
2434 }
2435
2436 void
2437 InnerLoopVectorizer::vectorizeBlockInLoop(LoopVectorizationLegality *Legal,
2438                                           BasicBlock *BB, PhiVector *PV) {
2439   // For each instruction in the old loop.
2440   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2441     VectorParts &Entry = WidenMap.get(it);
2442     switch (it->getOpcode()) {
2443     case Instruction::Br:
2444       // Nothing to do for PHIs and BR, since we already took care of the
2445       // loop control flow instructions.
2446       continue;
2447     case Instruction::PHI:{
2448       // Vectorize PHINodes.
2449       widenPHIInstruction(it, Entry, Legal, UF, VF, PV);
2450       continue;
2451     }// End of PHI.
2452
2453     case Instruction::Add:
2454     case Instruction::FAdd:
2455     case Instruction::Sub:
2456     case Instruction::FSub:
2457     case Instruction::Mul:
2458     case Instruction::FMul:
2459     case Instruction::UDiv:
2460     case Instruction::SDiv:
2461     case Instruction::FDiv:
2462     case Instruction::URem:
2463     case Instruction::SRem:
2464     case Instruction::FRem:
2465     case Instruction::Shl:
2466     case Instruction::LShr:
2467     case Instruction::AShr:
2468     case Instruction::And:
2469     case Instruction::Or:
2470     case Instruction::Xor: {
2471       // Just widen binops.
2472       BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
2473       setDebugLocFromInst(Builder, BinOp);
2474       VectorParts &A = getVectorValue(it->getOperand(0));
2475       VectorParts &B = getVectorValue(it->getOperand(1));
2476
2477       // Use this vector value for all users of the original instruction.
2478       for (unsigned Part = 0; Part < UF; ++Part) {
2479         Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
2480
2481         // Update the NSW, NUW and Exact flags. Notice: V can be an Undef.
2482         BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V);
2483         if (VecOp && isa<OverflowingBinaryOperator>(BinOp)) {
2484           VecOp->setHasNoSignedWrap(BinOp->hasNoSignedWrap());
2485           VecOp->setHasNoUnsignedWrap(BinOp->hasNoUnsignedWrap());
2486         }
2487         if (VecOp && isa<PossiblyExactOperator>(VecOp))
2488           VecOp->setIsExact(BinOp->isExact());
2489
2490         Entry[Part] = V;
2491       }
2492       break;
2493     }
2494     case Instruction::Select: {
2495       // Widen selects.
2496       // If the selector is loop invariant we can create a select
2497       // instruction with a scalar condition. Otherwise, use vector-select.
2498       bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)),
2499                                                OrigLoop);
2500       setDebugLocFromInst(Builder, it);
2501
2502       // The condition can be loop invariant  but still defined inside the
2503       // loop. This means that we can't just use the original 'cond' value.
2504       // We have to take the 'vectorized' value and pick the first lane.
2505       // Instcombine will make this a no-op.
2506       VectorParts &Cond = getVectorValue(it->getOperand(0));
2507       VectorParts &Op0  = getVectorValue(it->getOperand(1));
2508       VectorParts &Op1  = getVectorValue(it->getOperand(2));
2509
2510       Value *ScalarCond = (VF == 1) ? Cond[0] :
2511         Builder.CreateExtractElement(Cond[0], Builder.getInt32(0));
2512
2513       for (unsigned Part = 0; Part < UF; ++Part) {
2514         Entry[Part] = Builder.CreateSelect(
2515           InvariantCond ? ScalarCond : Cond[Part],
2516           Op0[Part],
2517           Op1[Part]);
2518       }
2519       break;
2520     }
2521
2522     case Instruction::ICmp:
2523     case Instruction::FCmp: {
2524       // Widen compares. Generate vector compares.
2525       bool FCmp = (it->getOpcode() == Instruction::FCmp);
2526       CmpInst *Cmp = dyn_cast<CmpInst>(it);
2527       setDebugLocFromInst(Builder, it);
2528       VectorParts &A = getVectorValue(it->getOperand(0));
2529       VectorParts &B = getVectorValue(it->getOperand(1));
2530       for (unsigned Part = 0; Part < UF; ++Part) {
2531         Value *C = 0;
2532         if (FCmp)
2533           C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
2534         else
2535           C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
2536         Entry[Part] = C;
2537       }
2538       break;
2539     }
2540
2541     case Instruction::Store:
2542     case Instruction::Load:
2543         vectorizeMemoryInstruction(it, Legal);
2544         break;
2545     case Instruction::ZExt:
2546     case Instruction::SExt:
2547     case Instruction::FPToUI:
2548     case Instruction::FPToSI:
2549     case Instruction::FPExt:
2550     case Instruction::PtrToInt:
2551     case Instruction::IntToPtr:
2552     case Instruction::SIToFP:
2553     case Instruction::UIToFP:
2554     case Instruction::Trunc:
2555     case Instruction::FPTrunc:
2556     case Instruction::BitCast: {
2557       CastInst *CI = dyn_cast<CastInst>(it);
2558       setDebugLocFromInst(Builder, it);
2559       /// Optimize the special case where the source is the induction
2560       /// variable. Notice that we can only optimize the 'trunc' case
2561       /// because: a. FP conversions lose precision, b. sext/zext may wrap,
2562       /// c. other casts depend on pointer size.
2563       if (CI->getOperand(0) == OldInduction &&
2564           it->getOpcode() == Instruction::Trunc) {
2565         Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
2566                                                CI->getType());
2567         Value *Broadcasted = getBroadcastInstrs(ScalarCast);
2568         for (unsigned Part = 0; Part < UF; ++Part)
2569           Entry[Part] = getConsecutiveVector(Broadcasted, VF * Part, false);
2570         break;
2571       }
2572       /// Vectorize casts.
2573       Type *DestTy = (VF == 1) ? CI->getType() :
2574                                  VectorType::get(CI->getType(), VF);
2575
2576       VectorParts &A = getVectorValue(it->getOperand(0));
2577       for (unsigned Part = 0; Part < UF; ++Part)
2578         Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
2579       break;
2580     }
2581
2582     case Instruction::Call: {
2583       // Ignore dbg intrinsics.
2584       if (isa<DbgInfoIntrinsic>(it))
2585         break;
2586       setDebugLocFromInst(Builder, it);
2587
2588       Module *M = BB->getParent()->getParent();
2589       CallInst *CI = cast<CallInst>(it);
2590       Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
2591       assert(ID && "Not an intrinsic call!");
2592       switch (ID) {
2593       case Intrinsic::lifetime_end:
2594       case Intrinsic::lifetime_start:
2595         scalarizeInstruction(it);
2596         break;
2597       default:
2598         for (unsigned Part = 0; Part < UF; ++Part) {
2599           SmallVector<Value *, 4> Args;
2600           for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
2601             VectorParts &Arg = getVectorValue(CI->getArgOperand(i));
2602             Args.push_back(Arg[Part]);
2603           }
2604           Type *Tys[] = {CI->getType()};
2605           if (VF > 1)
2606             Tys[0] = VectorType::get(CI->getType()->getScalarType(), VF);
2607
2608           Function *F = Intrinsic::getDeclaration(M, ID, Tys);
2609           Entry[Part] = Builder.CreateCall(F, Args);
2610         }
2611         break;
2612       }
2613       break;
2614     }
2615
2616     default:
2617       // All other instructions are unsupported. Scalarize them.
2618       scalarizeInstruction(it);
2619       break;
2620     }// end of switch.
2621   }// end of for_each instr.
2622 }
2623
2624 void InnerLoopVectorizer::updateAnalysis() {
2625   // Forget the original basic block.
2626   SE->forgetLoop(OrigLoop);
2627
2628   // Update the dominator tree information.
2629   assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&
2630          "Entry does not dominate exit.");
2631
2632   for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
2633     DT->addNewBlock(LoopBypassBlocks[I], LoopBypassBlocks[I-1]);
2634   DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlocks.back());
2635   DT->addNewBlock(LoopVectorBody, LoopVectorPreHeader);
2636   DT->addNewBlock(LoopMiddleBlock, LoopBypassBlocks.front());
2637   DT->addNewBlock(LoopScalarPreHeader, LoopMiddleBlock);
2638   DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
2639   DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
2640
2641   DEBUG(DT->verifyAnalysis());
2642 }
2643
2644 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
2645   if (!EnableIfConversion)
2646     return false;
2647
2648   assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
2649   std::vector<BasicBlock*> &LoopBlocks = TheLoop->getBlocksVector();
2650
2651   // A list of pointers that we can safely read and write to.
2652   SmallPtrSet<Value *, 8> SafePointes;
2653
2654   // Collect safe addresses.
2655   for (unsigned i = 0, e = LoopBlocks.size(); i < e; ++i) {
2656     BasicBlock *BB = LoopBlocks[i];
2657
2658     if (blockNeedsPredication(BB))
2659       continue;
2660
2661     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2662       if (LoadInst *LI = dyn_cast<LoadInst>(I))
2663         SafePointes.insert(LI->getPointerOperand());
2664       else if (StoreInst *SI = dyn_cast<StoreInst>(I))
2665         SafePointes.insert(SI->getPointerOperand());
2666     }
2667   }
2668
2669   // Collect the blocks that need predication.
2670   for (unsigned i = 0, e = LoopBlocks.size(); i < e; ++i) {
2671     BasicBlock *BB = LoopBlocks[i];
2672
2673     // We don't support switch statements inside loops.
2674     if (!isa<BranchInst>(BB->getTerminator()))
2675       return false;
2676
2677     // We must be able to predicate all blocks that need to be predicated.
2678     if (blockNeedsPredication(BB) && !blockCanBePredicated(BB, SafePointes))
2679       return false;
2680   }
2681
2682   // We can if-convert this loop.
2683   return true;
2684 }
2685
2686 bool LoopVectorizationLegality::canVectorize() {
2687   // We must have a loop in canonical form. Loops with indirectbr in them cannot
2688   // be canonicalized.
2689   if (!TheLoop->getLoopPreheader())
2690     return false;
2691
2692   // We can only vectorize innermost loops.
2693   if (TheLoop->getSubLoopsVector().size())
2694     return false;
2695
2696   // We must have a single backedge.
2697   if (TheLoop->getNumBackEdges() != 1)
2698     return false;
2699
2700   // We must have a single exiting block.
2701   if (!TheLoop->getExitingBlock())
2702     return false;
2703
2704   unsigned NumBlocks = TheLoop->getNumBlocks();
2705
2706   // Check if we can if-convert non single-bb loops.
2707   if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
2708     DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
2709     return false;
2710   }
2711
2712   // We need to have a loop header.
2713   BasicBlock *Latch = TheLoop->getLoopLatch();
2714   DEBUG(dbgs() << "LV: Found a loop: " <<
2715         TheLoop->getHeader()->getName() << "\n");
2716
2717   // ScalarEvolution needs to be able to find the exit count.
2718   const SCEV *ExitCount = SE->getBackedgeTakenCount(TheLoop);
2719   if (ExitCount == SE->getCouldNotCompute()) {
2720     DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
2721     return false;
2722   }
2723
2724   // Do not loop-vectorize loops with a tiny trip count.
2725   unsigned TC = SE->getSmallConstantTripCount(TheLoop, Latch);
2726   if (TC > 0u && TC < TinyTripCountVectorThreshold) {
2727     DEBUG(dbgs() << "LV: Found a loop with a very small trip count. " <<
2728           "This loop is not worth vectorizing.\n");
2729     return false;
2730   }
2731
2732   // Check if we can vectorize the instructions and CFG in this loop.
2733   if (!canVectorizeInstrs()) {
2734     DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
2735     return false;
2736   }
2737
2738   // Go over each instruction and look at memory deps.
2739   if (!canVectorizeMemory()) {
2740     DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
2741     return false;
2742   }
2743
2744   // Collect all of the variables that remain uniform after vectorization.
2745   collectLoopUniforms();
2746
2747   DEBUG(dbgs() << "LV: We can vectorize this loop" <<
2748         (PtrRtCheck.Need ? " (with a runtime bound check)" : "")
2749         <<"!\n");
2750
2751   // Okay! We can vectorize. At this point we don't have any other mem analysis
2752   // which may limit our maximum vectorization factor, so just return true with
2753   // no restrictions.
2754   return true;
2755 }
2756
2757 static Type *convertPointerToIntegerType(DataLayout &DL, Type *Ty) {
2758   if (Ty->isPointerTy())
2759     return DL.getIntPtrType(Ty);
2760
2761   return Ty;
2762 }
2763
2764 static Type* getWiderType(DataLayout &DL, Type *Ty0, Type *Ty1) {
2765   Ty0 = convertPointerToIntegerType(DL, Ty0);
2766   Ty1 = convertPointerToIntegerType(DL, Ty1);
2767   if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits())
2768     return Ty0;
2769   return Ty1;
2770 }
2771
2772 /// \brief Check that the instruction has outside loop users and is not an
2773 /// identified reduction variable.
2774 static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst,
2775                                SmallPtrSet<Value *, 4> &Reductions) {
2776   // Reduction instructions are allowed to have exit users. All other
2777   // instructions must not have external users.
2778   if (!Reductions.count(Inst))
2779     //Check that all of the users of the loop are inside the BB.
2780     for (Value::use_iterator I = Inst->use_begin(), E = Inst->use_end();
2781          I != E; ++I) {
2782       Instruction *U = cast<Instruction>(*I);
2783       // This user may be a reduction exit value.
2784       if (!TheLoop->contains(U)) {
2785         DEBUG(dbgs() << "LV: Found an outside user for : "<< *U << "\n");
2786         return true;
2787       }
2788     }
2789   return false;
2790 }
2791
2792 bool LoopVectorizationLegality::canVectorizeInstrs() {
2793   BasicBlock *PreHeader = TheLoop->getLoopPreheader();
2794   BasicBlock *Header = TheLoop->getHeader();
2795
2796   // Look for the attribute signaling the absence of NaNs.
2797   Function &F = *Header->getParent();
2798   if (F.hasFnAttribute("no-nans-fp-math"))
2799     HasFunNoNaNAttr = F.getAttributes().getAttribute(
2800       AttributeSet::FunctionIndex,
2801       "no-nans-fp-math").getValueAsString() == "true";
2802
2803   // For each block in the loop.
2804   for (Loop::block_iterator bb = TheLoop->block_begin(),
2805        be = TheLoop->block_end(); bb != be; ++bb) {
2806
2807     // Scan the instructions in the block and look for hazards.
2808     for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
2809          ++it) {
2810
2811       if (PHINode *Phi = dyn_cast<PHINode>(it)) {
2812         Type *PhiTy = Phi->getType();
2813         // Check that this PHI type is allowed.
2814         if (!PhiTy->isIntegerTy() &&
2815             !PhiTy->isFloatingPointTy() &&
2816             !PhiTy->isPointerTy()) {
2817           DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
2818           return false;
2819         }
2820
2821         // If this PHINode is not in the header block, then we know that we
2822         // can convert it to select during if-conversion. No need to check if
2823         // the PHIs in this block are induction or reduction variables.
2824         if (*bb != Header) {
2825           // Check that this instruction has no outside users or is an
2826           // identified reduction value with an outside user.
2827           if(!hasOutsideLoopUser(TheLoop, it, AllowedExit))
2828             continue;
2829           return false;
2830         }
2831
2832         // We only allow if-converted PHIs with more than two incoming values.
2833         if (Phi->getNumIncomingValues() != 2) {
2834           DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
2835           return false;
2836         }
2837
2838         // This is the value coming from the preheader.
2839         Value *StartValue = Phi->getIncomingValueForBlock(PreHeader);
2840         // Check if this is an induction variable.
2841         InductionKind IK = isInductionVariable(Phi);
2842
2843         if (IK_NoInduction != IK) {
2844           // Get the widest type.
2845           if (!WidestIndTy)
2846             WidestIndTy = convertPointerToIntegerType(*DL, PhiTy);
2847           else
2848             WidestIndTy = getWiderType(*DL, PhiTy, WidestIndTy);
2849
2850           // Int inductions are special because we only allow one IV.
2851           if (IK == IK_IntInduction) {
2852             // Use the phi node with the widest type as induction. Use the last
2853             // one if there are multiple (no good reason for doing this other
2854             // than it is expedient).
2855             if (!Induction || PhiTy == WidestIndTy)
2856               Induction = Phi;
2857           }
2858
2859           DEBUG(dbgs() << "LV: Found an induction variable.\n");
2860           Inductions[Phi] = InductionInfo(StartValue, IK);
2861           continue;
2862         }
2863
2864         if (AddReductionVar(Phi, RK_IntegerAdd)) {
2865           DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
2866           continue;
2867         }
2868         if (AddReductionVar(Phi, RK_IntegerMult)) {
2869           DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n");
2870           continue;
2871         }
2872         if (AddReductionVar(Phi, RK_IntegerOr)) {
2873           DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n");
2874           continue;
2875         }
2876         if (AddReductionVar(Phi, RK_IntegerAnd)) {
2877           DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n");
2878           continue;
2879         }
2880         if (AddReductionVar(Phi, RK_IntegerXor)) {
2881           DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n");
2882           continue;
2883         }
2884         if (AddReductionVar(Phi, RK_IntegerMinMax)) {
2885           DEBUG(dbgs() << "LV: Found a MINMAX reduction PHI."<< *Phi <<"\n");
2886           continue;
2887         }
2888         if (AddReductionVar(Phi, RK_FloatMult)) {
2889           DEBUG(dbgs() << "LV: Found an FMult reduction PHI."<< *Phi <<"\n");
2890           continue;
2891         }
2892         if (AddReductionVar(Phi, RK_FloatAdd)) {
2893           DEBUG(dbgs() << "LV: Found an FAdd reduction PHI."<< *Phi <<"\n");
2894           continue;
2895         }
2896         if (AddReductionVar(Phi, RK_FloatMinMax)) {
2897           DEBUG(dbgs() << "LV: Found an float MINMAX reduction PHI."<< *Phi <<
2898                 "\n");
2899           continue;
2900         }
2901
2902         DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
2903         return false;
2904       }// end of PHI handling
2905
2906       // We still don't handle functions. However, we can ignore dbg intrinsic
2907       // calls and we do handle certain intrinsic and libm functions.
2908       CallInst *CI = dyn_cast<CallInst>(it);
2909       if (CI && !getIntrinsicIDForCall(CI, TLI) && !isa<DbgInfoIntrinsic>(CI)) {
2910         DEBUG(dbgs() << "LV: Found a call site.\n");
2911         return false;
2912       }
2913
2914       // Check that the instruction return type is vectorizable.
2915       if (!VectorType::isValidElementType(it->getType()) &&
2916           !it->getType()->isVoidTy()) {
2917         DEBUG(dbgs() << "LV: Found unvectorizable type." << "\n");
2918         return false;
2919       }
2920
2921       // Check that the stored type is vectorizable.
2922       if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
2923         Type *T = ST->getValueOperand()->getType();
2924         if (!VectorType::isValidElementType(T))
2925           return false;
2926       }
2927
2928       // Reduction instructions are allowed to have exit users.
2929       // All other instructions must not have external users.
2930       if (hasOutsideLoopUser(TheLoop, it, AllowedExit))
2931         return false;
2932
2933     } // next instr.
2934
2935   }
2936
2937   if (!Induction) {
2938     DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
2939     if (Inductions.empty())
2940       return false;
2941   }
2942
2943   return true;
2944 }
2945
2946 void LoopVectorizationLegality::collectLoopUniforms() {
2947   // We now know that the loop is vectorizable!
2948   // Collect variables that will remain uniform after vectorization.
2949   std::vector<Value*> Worklist;
2950   BasicBlock *Latch = TheLoop->getLoopLatch();
2951
2952   // Start with the conditional branch and walk up the block.
2953   Worklist.push_back(Latch->getTerminator()->getOperand(0));
2954
2955   while (Worklist.size()) {
2956     Instruction *I = dyn_cast<Instruction>(Worklist.back());
2957     Worklist.pop_back();
2958
2959     // Look at instructions inside this loop.
2960     // Stop when reaching PHI nodes.
2961     // TODO: we need to follow values all over the loop, not only in this block.
2962     if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
2963       continue;
2964
2965     // This is a known uniform.
2966     Uniforms.insert(I);
2967
2968     // Insert all operands.
2969     Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
2970   }
2971 }
2972
2973 namespace {
2974 /// \brief Analyses memory accesses in a loop.
2975 ///
2976 /// Checks whether run time pointer checks are needed and builds sets for data
2977 /// dependence checking.
2978 class AccessAnalysis {
2979 public:
2980   /// \brief Read or write access location.
2981   typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
2982   typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
2983
2984   /// \brief Set of potential dependent memory accesses.
2985   typedef EquivalenceClasses<MemAccessInfo> DepCandidates;
2986
2987   AccessAnalysis(DataLayout *Dl, DepCandidates &DA) :
2988     DL(Dl), DepCands(DA), AreAllWritesIdentified(true),
2989     AreAllReadsIdentified(true), IsRTCheckNeeded(false) {}
2990
2991   /// \brief Register a load  and whether it is only read from.
2992   void addLoad(Value *Ptr, bool IsReadOnly) {
2993     Accesses.insert(MemAccessInfo(Ptr, false));
2994     if (IsReadOnly)
2995       ReadOnlyPtr.insert(Ptr);
2996   }
2997
2998   /// \brief Register a store.
2999   void addStore(Value *Ptr) {
3000     Accesses.insert(MemAccessInfo(Ptr, true));
3001   }
3002
3003   /// \brief Check whether we can check the pointers at runtime for
3004   /// non-intersection.
3005   bool canCheckPtrAtRT(LoopVectorizationLegality::RuntimePointerCheck &RtCheck,
3006                        unsigned &NumComparisons, ScalarEvolution *SE,
3007                        Loop *TheLoop);
3008
3009   /// \brief Goes over all memory accesses, checks whether a RT check is needed
3010   /// and builds sets of dependent accesses.
3011   void buildDependenceSets() {
3012     // Process read-write pointers first.
3013     processMemAccesses(false);
3014     // Next, process read pointers.
3015     processMemAccesses(true);
3016   }
3017
3018   bool isRTCheckNeeded() { return IsRTCheckNeeded; }
3019
3020   bool isDependencyCheckNeeded() { return !CheckDeps.empty(); }
3021
3022   MemAccessInfoSet &getDependenciesToCheck() { return CheckDeps; }
3023
3024 private:
3025   typedef SetVector<MemAccessInfo> PtrAccessSet;
3026   typedef DenseMap<Value*, MemAccessInfo> UnderlyingObjToAccessMap;
3027
3028   /// \brief Go over all memory access or only the deferred ones if
3029   /// \p UseDeferred is true and check whether runtime pointer checks are needed
3030   /// and build sets of dependency check candidates.
3031   void processMemAccesses(bool UseDeferred);
3032
3033   /// Set of all accesses.
3034   PtrAccessSet Accesses;
3035
3036   /// Set of access to check after all writes have been processed.
3037   PtrAccessSet DeferredAccesses;
3038
3039   /// Map of pointers to last access encountered.
3040   UnderlyingObjToAccessMap ObjToLastAccess;
3041
3042   /// Set of accesses that need a further dependence check.
3043   MemAccessInfoSet CheckDeps;
3044
3045   /// Set of pointers that are read only.
3046   SmallPtrSet<Value*, 16> ReadOnlyPtr;
3047
3048   /// Set of underlying objects already written to.
3049   SmallPtrSet<Value*, 16> WriteObjects;
3050
3051   DataLayout *DL;
3052
3053   /// Sets of potentially dependent accesses - members of one set share an
3054   /// underlying pointer. The set "CheckDeps" identfies which sets really need a
3055   /// dependence check.
3056   DepCandidates &DepCands;
3057
3058   bool AreAllWritesIdentified;
3059   bool AreAllReadsIdentified;
3060   bool IsRTCheckNeeded;
3061 };
3062
3063 } // end anonymous namespace
3064
3065 /// \brief Check whether a pointer can participate in a runtime bounds check.
3066 static bool hasComputableBounds(ScalarEvolution *SE, Value *Ptr) {
3067   const SCEV *PtrScev = SE->getSCEV(Ptr);
3068   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
3069   if (!AR)
3070     return false;
3071
3072   return AR->isAffine();
3073 }
3074
3075 bool AccessAnalysis::canCheckPtrAtRT(
3076                        LoopVectorizationLegality::RuntimePointerCheck &RtCheck,
3077                         unsigned &NumComparisons, ScalarEvolution *SE,
3078                         Loop *TheLoop) {
3079   // Find pointers with computable bounds. We are going to use this information
3080   // to place a runtime bound check.
3081   unsigned NumReadPtrChecks = 0;
3082   unsigned NumWritePtrChecks = 0;
3083   bool CanDoRT = true;
3084
3085   bool IsDepCheckNeeded = isDependencyCheckNeeded();
3086   // We assign consecutive id to access from different dependence sets.
3087   // Accesses within the same set don't need a runtime check.
3088   unsigned RunningDepId = 1;
3089   DenseMap<Value *, unsigned> DepSetId;
3090
3091   for (PtrAccessSet::iterator AI = Accesses.begin(), AE = Accesses.end();
3092        AI != AE; ++AI) {
3093     const MemAccessInfo &Access = *AI;
3094     Value *Ptr = Access.getPointer();
3095     bool IsWrite = Access.getInt();
3096
3097     // Just add write checks if we have both.
3098     if (!IsWrite && Accesses.count(MemAccessInfo(Ptr, true)))
3099       continue;
3100
3101     if (IsWrite)
3102       ++NumWritePtrChecks;
3103     else
3104       ++NumReadPtrChecks;
3105
3106     if (hasComputableBounds(SE, Ptr)) {
3107       // The id of the dependence set.
3108       unsigned DepId;
3109
3110       if (IsDepCheckNeeded) {
3111         Value *Leader = DepCands.getLeaderValue(Access).getPointer();
3112         unsigned &LeaderId = DepSetId[Leader];
3113         if (!LeaderId)
3114           LeaderId = RunningDepId++;
3115         DepId = LeaderId;
3116       } else
3117         // Each access has its own dependence set.
3118         DepId = RunningDepId++;
3119
3120       RtCheck.insert(SE, TheLoop, Ptr, IsWrite, DepId);
3121
3122       DEBUG(dbgs() << "LV: Found a runtime check ptr:" << *Ptr <<"\n");
3123     } else {
3124       CanDoRT = false;
3125     }
3126   }
3127
3128   if (IsDepCheckNeeded && CanDoRT && RunningDepId == 2)
3129     NumComparisons = 0; // Only one dependence set.
3130   else
3131     NumComparisons = (NumWritePtrChecks * (NumReadPtrChecks +
3132                                            NumWritePtrChecks - 1));
3133   return CanDoRT;
3134 }
3135
3136 static bool isFunctionScopeIdentifiedObject(Value *Ptr) {
3137   return isNoAliasArgument(Ptr) || isNoAliasCall(Ptr) || isa<AllocaInst>(Ptr);
3138 }
3139
3140 void AccessAnalysis::processMemAccesses(bool UseDeferred) {
3141   // We process the set twice: first we process read-write pointers, last we
3142   // process read-only pointers. This allows us to skip dependence tests for
3143   // read-only pointers.
3144
3145   PtrAccessSet &S = UseDeferred ? DeferredAccesses : Accesses;
3146   for (PtrAccessSet::iterator AI = S.begin(), AE = S.end(); AI != AE; ++AI) {
3147     const MemAccessInfo &Access = *AI;
3148     Value *Ptr = Access.getPointer();
3149     bool IsWrite = Access.getInt();
3150
3151     DepCands.insert(Access);
3152
3153     // Memorize read-only pointers for later processing and skip them in the
3154     // first round (they need to be checked after we have seen all write
3155     // pointers). Note: we also mark pointer that are not consecutive as
3156     // "read-only" pointers (so that we check "a[b[i]] +="). Hence, we need the
3157     // second check for "!IsWrite".
3158     bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite;
3159     if (!UseDeferred && IsReadOnlyPtr) {
3160       DeferredAccesses.insert(Access);
3161       continue;
3162     }
3163
3164     bool NeedDepCheck = false;
3165     // Check whether there is the possiblity of dependency because of underlying
3166     // objects being the same.
3167     typedef SmallVector<Value*, 16> ValueVector;
3168     ValueVector TempObjects;
3169     GetUnderlyingObjects(Ptr, TempObjects, DL);
3170     for (ValueVector::iterator UI = TempObjects.begin(), UE = TempObjects.end();
3171          UI != UE; ++UI) {
3172       Value *UnderlyingObj = *UI;
3173
3174       // If this is a write then it needs to be an identified object.  If this a
3175       // read and all writes (so far) are identified function scope objects we
3176       // don't need an identified underlying object but only an Argument (the
3177       // next write is going to invalidate this assumption if it is
3178       // unidentified).
3179       // This is a micro-optimization for the case where all writes are
3180       // identified and we have one argument pointer.
3181       // Otherwise, we do need a runtime check.
3182       if ((IsWrite && !isFunctionScopeIdentifiedObject(UnderlyingObj)) ||
3183           (!IsWrite && (!AreAllWritesIdentified ||
3184                         !isa<Argument>(UnderlyingObj)) &&
3185            !isIdentifiedObject(UnderlyingObj))) {
3186         DEBUG(dbgs() << "LV: Found an unidentified " <<
3187               (IsWrite ?  "write" : "read" ) << " ptr:" << *UnderlyingObj <<
3188               "\n");
3189         IsRTCheckNeeded = (IsRTCheckNeeded ||
3190                            !isIdentifiedObject(UnderlyingObj) ||
3191                            !AreAllReadsIdentified);
3192
3193         if (IsWrite)
3194           AreAllWritesIdentified = false;
3195         if (!IsWrite)
3196           AreAllReadsIdentified = false;
3197       }
3198
3199       // If this is a write - check other reads and writes for conflicts.  If
3200       // this is a read only check other writes for conflicts (but only if there
3201       // is no other write to the ptr - this is an optimization to catch "a[i] =
3202       // a[i] + " without having to do a dependence check).
3203       if ((IsWrite || IsReadOnlyPtr) && WriteObjects.count(UnderlyingObj))
3204         NeedDepCheck = true;
3205
3206       if (IsWrite)
3207         WriteObjects.insert(UnderlyingObj);
3208
3209       // Create sets of pointers connected by shared underlying objects.
3210       UnderlyingObjToAccessMap::iterator Prev =
3211         ObjToLastAccess.find(UnderlyingObj);
3212       if (Prev != ObjToLastAccess.end())
3213         DepCands.unionSets(Access, Prev->second);
3214
3215       ObjToLastAccess[UnderlyingObj] = Access;
3216     }
3217
3218     if (NeedDepCheck)
3219       CheckDeps.insert(Access);
3220   }
3221 }
3222
3223 namespace {
3224 /// \brief Checks memory dependences among accesses to the same underlying
3225 /// object to determine whether there vectorization is legal or not (and at
3226 /// which vectorization factor).
3227 ///
3228 /// This class works under the assumption that we already checked that memory
3229 /// locations with different underlying pointers are "must-not alias".
3230 /// We use the ScalarEvolution framework to symbolically evalutate access
3231 /// functions pairs. Since we currently don't restructure the loop we can rely
3232 /// on the program order of memory accesses to determine their safety.
3233 /// At the moment we will only deem accesses as safe for:
3234 ///  * A negative constant distance assuming program order.
3235 ///
3236 ///      Safe: tmp = a[i + 1];     OR     a[i + 1] = x;
3237 ///            a[i] = tmp;                y = a[i];
3238 ///
3239 ///   The latter case is safe because later checks guarantuee that there can't
3240 ///   be a cycle through a phi node (that is, we check that "x" and "y" is not
3241 ///   the same variable: a header phi can only be an induction or a reduction, a
3242 ///   reduction can't have a memory sink, an induction can't have a memory
3243 ///   source). This is important and must not be violated (or we have to
3244 ///   resort to checking for cycles through memory).
3245 ///
3246 ///  * A positive constant distance assuming program order that is bigger
3247 ///    than the biggest memory access.
3248 ///
3249 ///     tmp = a[i]        OR              b[i] = x
3250 ///     a[i+2] = tmp                      y = b[i+2];
3251 ///
3252 ///     Safe distance: 2 x sizeof(a[0]), and 2 x sizeof(b[0]), respectively.
3253 ///
3254 ///  * Zero distances and all accesses have the same size.
3255 ///
3256 class MemoryDepChecker {
3257 public:
3258   typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
3259   typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
3260
3261   MemoryDepChecker(ScalarEvolution *Se, DataLayout *Dl, const Loop *L) :
3262     SE(Se), DL(Dl), InnermostLoop(L), AccessIdx(0) {}
3263
3264   /// \brief Register the location (instructions are given increasing numbers)
3265   /// of a write access.
3266   void addAccess(StoreInst *SI) {
3267     Value *Ptr = SI->getPointerOperand();
3268     Accesses[MemAccessInfo(Ptr, true)].push_back(AccessIdx);
3269     InstMap.push_back(SI);
3270     ++AccessIdx;
3271   }
3272
3273   /// \brief Register the location (instructions are given increasing numbers)
3274   /// of a write access.
3275   void addAccess(LoadInst *LI) {
3276     Value *Ptr = LI->getPointerOperand();
3277     Accesses[MemAccessInfo(Ptr, false)].push_back(AccessIdx);
3278     InstMap.push_back(LI);
3279     ++AccessIdx;
3280   }
3281
3282   /// \brief Check whether the dependencies between the accesses are safe.
3283   ///
3284   /// Only checks sets with elements in \p CheckDeps.
3285   bool areDepsSafe(AccessAnalysis::DepCandidates &AccessSets,
3286                    MemAccessInfoSet &CheckDeps);
3287
3288   /// \brief The maximum number of bytes of a vector register we can vectorize
3289   /// the accesses safely with.
3290   unsigned getMaxSafeDepDistBytes() { return MaxSafeDepDistBytes; }
3291
3292 private:
3293   ScalarEvolution *SE;
3294   DataLayout *DL;
3295   const Loop *InnermostLoop;
3296
3297   /// \brief Maps access locations (ptr, read/write) to program order.
3298   DenseMap<MemAccessInfo, std::vector<unsigned> > Accesses;
3299
3300   /// \brief Memory access instructions in program order.
3301   SmallVector<Instruction *, 16> InstMap;
3302
3303   /// \brief The program order index to be used for the next instruction.
3304   unsigned AccessIdx;
3305
3306   // We can access this many bytes in parallel safely.
3307   unsigned MaxSafeDepDistBytes;
3308
3309   /// \brief Check whether there is a plausible dependence between the two
3310   /// accesses.
3311   ///
3312   /// Access \p A must happen before \p B in program order. The two indices
3313   /// identify the index into the program order map.
3314   ///
3315   /// This function checks  whether there is a plausible dependence (or the
3316   /// absence of such can't be proved) between the two accesses. If there is a
3317   /// plausible dependence but the dependence distance is bigger than one
3318   /// element access it records this distance in \p MaxSafeDepDistBytes (if this
3319   /// distance is smaller than any other distance encountered so far).
3320   /// Otherwise, this function returns true signaling a possible dependence.
3321   bool isDependent(const MemAccessInfo &A, unsigned AIdx,
3322                    const MemAccessInfo &B, unsigned BIdx);
3323
3324   /// \brief Check whether the data dependence could prevent store-load
3325   /// forwarding.
3326   bool couldPreventStoreLoadForward(unsigned Distance, unsigned TypeByteSize);
3327 };
3328
3329 } // end anonymous namespace
3330
3331 static bool isInBoundsGep(Value *Ptr) {
3332   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
3333     return GEP->isInBounds();
3334   return false;
3335 }
3336
3337 /// \brief Check whether the access through \p Ptr has a constant stride.
3338 static int isStridedPtr(ScalarEvolution *SE, DataLayout *DL, Value *Ptr,
3339                         const Loop *Lp) {
3340   const Type *Ty = Ptr->getType();
3341   assert(Ty->isPointerTy() && "Unexpected non ptr");
3342
3343   // Make sure that the pointer does not point to aggregate types.
3344   const PointerType *PtrTy = cast<PointerType>(Ty);
3345   if (PtrTy->getElementType()->isAggregateType()) {
3346     DEBUG(dbgs() << "LV: Bad stride - Not a pointer to a scalar type" << *Ptr <<
3347           "\n");
3348     return 0;
3349   }
3350
3351   const SCEV *PtrScev = SE->getSCEV(Ptr);
3352   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
3353   if (!AR) {
3354     DEBUG(dbgs() << "LV: Bad stride - Not an AddRecExpr pointer "
3355           << *Ptr << " SCEV: " << *PtrScev << "\n");
3356     return 0;
3357   }
3358
3359   // The accesss function must stride over the innermost loop.
3360   if (Lp != AR->getLoop()) {
3361     DEBUG(dbgs() << "LV: Bad stride - Not striding over innermost loop " <<
3362           *Ptr << " SCEV: " << *PtrScev << "\n");
3363   }
3364
3365   // The address calculation must not wrap. Otherwise, a dependence could be
3366   // inverted.
3367   // An inbounds getelementptr that is a AddRec with a unit stride
3368   // cannot wrap per definition. The unit stride requirement is checked later.
3369   // An getelementptr without an inbounds attribute and unit stride would have
3370   // to access the pointer value "0" which is undefined behavior in address
3371   // space 0, therefore we can also vectorize this case.
3372   bool IsInBoundsGEP = isInBoundsGep(Ptr);
3373   bool IsNoWrapAddRec = AR->getNoWrapFlags(SCEV::NoWrapMask);
3374   bool IsInAddressSpaceZero = PtrTy->getAddressSpace() == 0;
3375   if (!IsNoWrapAddRec && !IsInBoundsGEP && !IsInAddressSpaceZero) {
3376     DEBUG(dbgs() << "LV: Bad stride - Pointer may wrap in the address space "
3377           << *Ptr << " SCEV: " << *PtrScev << "\n");
3378     return 0;
3379   }
3380
3381   // Check the step is constant.
3382   const SCEV *Step = AR->getStepRecurrence(*SE);
3383
3384   // Calculate the pointer stride and check if it is consecutive.
3385   const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
3386   if (!C) {
3387     DEBUG(dbgs() << "LV: Bad stride - Not a constant strided " << *Ptr <<
3388           " SCEV: " << *PtrScev << "\n");
3389     return 0;
3390   }
3391
3392   int64_t Size = DL->getTypeAllocSize(PtrTy->getElementType());
3393   const APInt &APStepVal = C->getValue()->getValue();
3394
3395   // Huge step value - give up.
3396   if (APStepVal.getBitWidth() > 64)
3397     return 0;
3398
3399   int64_t StepVal = APStepVal.getSExtValue();
3400
3401   // Strided access.
3402   int64_t Stride = StepVal / Size;
3403   int64_t Rem = StepVal % Size;
3404   if (Rem)
3405     return 0;
3406
3407   // If the SCEV could wrap but we have an inbounds gep with a unit stride we
3408   // know we can't "wrap around the address space". In case of address space
3409   // zero we know that this won't happen without triggering undefined behavior.
3410   if (!IsNoWrapAddRec && (IsInBoundsGEP || IsInAddressSpaceZero) &&
3411       Stride != 1 && Stride != -1)
3412     return 0;
3413
3414   return Stride;
3415 }
3416
3417 bool MemoryDepChecker::couldPreventStoreLoadForward(unsigned Distance,
3418                                                     unsigned TypeByteSize) {
3419   // If loads occur at a distance that is not a multiple of a feasible vector
3420   // factor store-load forwarding does not take place.
3421   // Positive dependences might cause troubles because vectorizing them might
3422   // prevent store-load forwarding making vectorized code run a lot slower.
3423   //   a[i] = a[i-3] ^ a[i-8];
3424   //   The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
3425   //   hence on your typical architecture store-load forwarding does not take
3426   //   place. Vectorizing in such cases does not make sense.
3427   // Store-load forwarding distance.
3428   const unsigned NumCyclesForStoreLoadThroughMemory = 8*TypeByteSize;
3429   // Maximum vector factor.
3430   unsigned MaxVFWithoutSLForwardIssues = MaxVectorWidth*TypeByteSize;
3431   if(MaxSafeDepDistBytes < MaxVFWithoutSLForwardIssues)
3432     MaxVFWithoutSLForwardIssues = MaxSafeDepDistBytes;
3433
3434   for (unsigned vf = 2*TypeByteSize; vf <= MaxVFWithoutSLForwardIssues;
3435        vf *= 2) {
3436     if (Distance % vf && Distance / vf < NumCyclesForStoreLoadThroughMemory) {
3437       MaxVFWithoutSLForwardIssues = (vf >>=1);
3438       break;
3439     }
3440   }
3441
3442   if (MaxVFWithoutSLForwardIssues< 2*TypeByteSize) {
3443     DEBUG(dbgs() << "LV: Distance " << Distance <<
3444           " that could cause a store-load forwarding conflict\n");
3445     return true;
3446   }
3447
3448   if (MaxVFWithoutSLForwardIssues < MaxSafeDepDistBytes &&
3449       MaxVFWithoutSLForwardIssues != MaxVectorWidth*TypeByteSize)
3450     MaxSafeDepDistBytes = MaxVFWithoutSLForwardIssues;
3451   return false;
3452 }
3453
3454 bool MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
3455                                    const MemAccessInfo &B, unsigned BIdx) {
3456   assert (AIdx < BIdx && "Must pass arguments in program order");
3457
3458   Value *APtr = A.getPointer();
3459   Value *BPtr = B.getPointer();
3460   bool AIsWrite = A.getInt();
3461   bool BIsWrite = B.getInt();
3462
3463   // Two reads are independent.
3464   if (!AIsWrite && !BIsWrite)
3465     return false;
3466
3467   const SCEV *AScev = SE->getSCEV(APtr);
3468   const SCEV *BScev = SE->getSCEV(BPtr);
3469
3470   int StrideAPtr = isStridedPtr(SE, DL, APtr, InnermostLoop);
3471   int StrideBPtr = isStridedPtr(SE, DL, BPtr, InnermostLoop);
3472
3473   const SCEV *Src = AScev;
3474   const SCEV *Sink = BScev;
3475
3476   // If the induction step is negative we have to invert source and sink of the
3477   // dependence.
3478   if (StrideAPtr < 0) {
3479     //Src = BScev;
3480     //Sink = AScev;
3481     std::swap(APtr, BPtr);
3482     std::swap(Src, Sink);
3483     std::swap(AIsWrite, BIsWrite);
3484     std::swap(AIdx, BIdx);
3485     std::swap(StrideAPtr, StrideBPtr);
3486   }
3487
3488   const SCEV *Dist = SE->getMinusSCEV(Sink, Src);
3489
3490   DEBUG(dbgs() << "LV: Src Scev: " << *Src << "Sink Scev: " << *Sink
3491         << "(Induction step: " << StrideAPtr <<  ")\n");
3492   DEBUG(dbgs() << "LV: Distance for " << *InstMap[AIdx] << " to "
3493         << *InstMap[BIdx] << ": " << *Dist << "\n");
3494
3495   // Need consecutive accesses. We don't want to vectorize
3496   // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap in
3497   // the address space.
3498   if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr){
3499     DEBUG(dbgs() << "Non-consecutive pointer access\n");
3500     return true;
3501   }
3502
3503   const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist);
3504   if (!C) {
3505     DEBUG(dbgs() << "LV: Dependence because of non constant distance\n");
3506     return true;
3507   }
3508
3509   Type *ATy = APtr->getType()->getPointerElementType();
3510   Type *BTy = BPtr->getType()->getPointerElementType();
3511   unsigned TypeByteSize = DL->getTypeAllocSize(ATy);
3512
3513   // Negative distances are not plausible dependencies.
3514   const APInt &Val = C->getValue()->getValue();
3515   if (Val.isNegative()) {
3516     bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
3517     if (IsTrueDataDependence &&
3518         (couldPreventStoreLoadForward(Val.abs().getZExtValue(), TypeByteSize) ||
3519          ATy != BTy))
3520       return true;
3521
3522     DEBUG(dbgs() << "LV: Dependence is negative: NoDep\n");
3523     return false;
3524   }
3525
3526   // Write to the same location with the same size.
3527   // Could be improved to assert type sizes are the same (i32 == float, etc).
3528   if (Val == 0) {
3529     if (ATy == BTy)
3530       return false;
3531     DEBUG(dbgs() << "LV: Zero dependence difference but different types");
3532     return true;
3533   }
3534
3535   assert(Val.isStrictlyPositive() && "Expect a positive value");
3536
3537   // Positive distance bigger than max vectorization factor.
3538   if (ATy != BTy) {
3539     DEBUG(dbgs() <<
3540           "LV: ReadWrite-Write positive dependency with different types");
3541     return false;
3542   }
3543
3544   unsigned Distance = (unsigned) Val.getZExtValue();
3545
3546   // Bail out early if passed-in parameters make vectorization not feasible.
3547   unsigned ForcedFactor = VectorizationFactor ? VectorizationFactor : 1;
3548   unsigned ForcedUnroll = VectorizationUnroll ? VectorizationUnroll : 1;
3549
3550   // The distance must be bigger than the size needed for a vectorized version
3551   // of the operation and the size of the vectorized operation must not be
3552   // bigger than the currrent maximum size.
3553   if (Distance < 2*TypeByteSize ||
3554       2*TypeByteSize > MaxSafeDepDistBytes ||
3555       Distance < TypeByteSize * ForcedUnroll * ForcedFactor) {
3556     DEBUG(dbgs() << "LV: Failure because of Positive distance "
3557         << Val.getSExtValue() << "\n");
3558     return true;
3559   }
3560
3561   MaxSafeDepDistBytes = Distance < MaxSafeDepDistBytes ?
3562     Distance : MaxSafeDepDistBytes;
3563
3564   bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
3565   if (IsTrueDataDependence &&
3566       couldPreventStoreLoadForward(Distance, TypeByteSize))
3567      return true;
3568
3569   DEBUG(dbgs() << "LV: Positive distance " << Val.getSExtValue() <<
3570         " with max VF=" << MaxSafeDepDistBytes/TypeByteSize << "\n");
3571
3572   return false;
3573 }
3574
3575 bool
3576 MemoryDepChecker::areDepsSafe(AccessAnalysis::DepCandidates &AccessSets,
3577                               MemAccessInfoSet &CheckDeps) {
3578
3579   MaxSafeDepDistBytes = -1U;
3580   while (!CheckDeps.empty()) {
3581     MemAccessInfo CurAccess = *CheckDeps.begin();
3582
3583     // Get the relevant memory access set.
3584     EquivalenceClasses<MemAccessInfo>::iterator I =
3585       AccessSets.findValue(AccessSets.getLeaderValue(CurAccess));
3586
3587     // Check accesses within this set.
3588     EquivalenceClasses<MemAccessInfo>::member_iterator AI, AE;
3589     AI = AccessSets.member_begin(I), AE = AccessSets.member_end();
3590
3591     // Check every access pair.
3592     while (AI != AE) {
3593       CheckDeps.erase(*AI);
3594       EquivalenceClasses<MemAccessInfo>::member_iterator OI = llvm::next(AI);
3595       while (OI != AE) {
3596         // Check every accessing instruction pair in program order.
3597         for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(),
3598              I1E = Accesses[*AI].end(); I1 != I1E; ++I1)
3599           for (std::vector<unsigned>::iterator I2 = Accesses[*OI].begin(),
3600                I2E = Accesses[*OI].end(); I2 != I2E; ++I2) {
3601             if (*I1 < *I2 && isDependent(*AI, *I1, *OI, *I2))
3602               return false;
3603             if (*I2 < *I1 && isDependent(*OI, *I2, *AI, *I1))
3604               return false;
3605           }
3606         ++OI;
3607       }
3608       AI++;
3609     }
3610   }
3611   return true;
3612 }
3613
3614 bool LoopVectorizationLegality::canVectorizeMemory() {
3615
3616   typedef SmallVector<Value*, 16> ValueVector;
3617   typedef SmallPtrSet<Value*, 16> ValueSet;
3618
3619   // Holds the Load and Store *instructions*.
3620   ValueVector Loads;
3621   ValueVector Stores;
3622
3623   // Holds all the different accesses in the loop.
3624   unsigned NumReads = 0;
3625   unsigned NumReadWrites = 0;
3626
3627   PtrRtCheck.Pointers.clear();
3628   PtrRtCheck.Need = false;
3629
3630   const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
3631   MemoryDepChecker DepChecker(SE, DL, TheLoop);
3632
3633   // For each block.
3634   for (Loop::block_iterator bb = TheLoop->block_begin(),
3635        be = TheLoop->block_end(); bb != be; ++bb) {
3636
3637     // Scan the BB and collect legal loads and stores.
3638     for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
3639          ++it) {
3640
3641       // If this is a load, save it. If this instruction can read from memory
3642       // but is not a load, then we quit. Notice that we don't handle function
3643       // calls that read or write.
3644       if (it->mayReadFromMemory()) {
3645         // Many math library functions read the rounding mode. We will only
3646         // vectorize a loop if it contains known function calls that don't set
3647         // the flag. Therefore, it is safe to ignore this read from memory.
3648         CallInst *Call = dyn_cast<CallInst>(it);
3649         if (Call && getIntrinsicIDForCall(Call, TLI))
3650           continue;
3651
3652         LoadInst *Ld = dyn_cast<LoadInst>(it);
3653         if (!Ld) return false;
3654         if (!Ld->isSimple() && !IsAnnotatedParallel) {
3655           DEBUG(dbgs() << "LV: Found a non-simple load.\n");
3656           return false;
3657         }
3658         Loads.push_back(Ld);
3659         DepChecker.addAccess(Ld);
3660         continue;
3661       }
3662
3663       // Save 'store' instructions. Abort if other instructions write to memory.
3664       if (it->mayWriteToMemory()) {
3665         StoreInst *St = dyn_cast<StoreInst>(it);
3666         if (!St) return false;
3667         if (!St->isSimple() && !IsAnnotatedParallel) {
3668           DEBUG(dbgs() << "LV: Found a non-simple store.\n");
3669           return false;
3670         }
3671         Stores.push_back(St);
3672         DepChecker.addAccess(St);
3673       }
3674     } // next instr.
3675   } // next block.
3676
3677   // Now we have two lists that hold the loads and the stores.
3678   // Next, we find the pointers that they use.
3679
3680   // Check if we see any stores. If there are no stores, then we don't
3681   // care if the pointers are *restrict*.
3682   if (!Stores.size()) {
3683     DEBUG(dbgs() << "LV: Found a read-only loop!\n");
3684     return true;
3685   }
3686
3687   AccessAnalysis::DepCandidates DependentAccesses;
3688   AccessAnalysis Accesses(DL, DependentAccesses);
3689
3690   // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
3691   // multiple times on the same object. If the ptr is accessed twice, once
3692   // for read and once for write, it will only appear once (on the write
3693   // list). This is okay, since we are going to check for conflicts between
3694   // writes and between reads and writes, but not between reads and reads.
3695   ValueSet Seen;
3696
3697   ValueVector::iterator I, IE;
3698   for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
3699     StoreInst *ST = cast<StoreInst>(*I);
3700     Value* Ptr = ST->getPointerOperand();
3701
3702     if (isUniform(Ptr)) {
3703       DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
3704       return false;
3705     }
3706
3707     // If we did *not* see this pointer before, insert it to  the read-write
3708     // list. At this phase it is only a 'write' list.
3709     if (Seen.insert(Ptr)) {
3710       ++NumReadWrites;
3711       Accesses.addStore(Ptr);
3712     }
3713   }
3714
3715   if (IsAnnotatedParallel) {
3716     DEBUG(dbgs()
3717           << "LV: A loop annotated parallel, ignore memory dependency "
3718           << "checks.\n");
3719     return true;
3720   }
3721
3722   SmallPtrSet<Value *, 16> ReadOnlyPtr;
3723   for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
3724     LoadInst *LD = cast<LoadInst>(*I);
3725     Value* Ptr = LD->getPointerOperand();
3726     // If we did *not* see this pointer before, insert it to the
3727     // read list. If we *did* see it before, then it is already in
3728     // the read-write list. This allows us to vectorize expressions
3729     // such as A[i] += x;  Because the address of A[i] is a read-write
3730     // pointer. This only works if the index of A[i] is consecutive.
3731     // If the address of i is unknown (for example A[B[i]]) then we may
3732     // read a few words, modify, and write a few words, and some of the
3733     // words may be written to the same address.
3734     bool IsReadOnlyPtr = false;
3735     if (Seen.insert(Ptr) || !isStridedPtr(SE, DL, Ptr, TheLoop)) {
3736       ++NumReads;
3737       IsReadOnlyPtr = true;
3738     }
3739     Accesses.addLoad(Ptr, IsReadOnlyPtr);
3740   }
3741
3742   // If we write (or read-write) to a single destination and there are no
3743   // other reads in this loop then is it safe to vectorize.
3744   if (NumReadWrites == 1 && NumReads == 0) {
3745     DEBUG(dbgs() << "LV: Found a write-only loop!\n");
3746     return true;
3747   }
3748
3749   // Build dependence sets and check whether we need a runtime pointer bounds
3750   // check.
3751   Accesses.buildDependenceSets();
3752   bool NeedRTCheck = Accesses.isRTCheckNeeded();
3753
3754   // Find pointers with computable bounds. We are going to use this information
3755   // to place a runtime bound check.
3756   unsigned NumComparisons = 0;
3757   bool CanDoRT = false;
3758   if (NeedRTCheck)
3759     CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE, TheLoop);
3760
3761
3762   DEBUG(dbgs() << "LV: We need to do " << NumComparisons <<
3763         " pointer comparisons.\n");
3764
3765   // If we only have one set of dependences to check pointers among we don't
3766   // need a runtime check.
3767   if (NumComparisons == 0 && NeedRTCheck)
3768     NeedRTCheck = false;
3769
3770   // Check that we did not collect too many pointers or found a unsizeable
3771   // pointer.
3772   if (!CanDoRT || NumComparisons > RuntimeMemoryCheckThreshold) {
3773     PtrRtCheck.reset();
3774     CanDoRT = false;
3775   }
3776
3777   if (CanDoRT) {
3778     DEBUG(dbgs() << "LV: We can perform a memory runtime check if needed.\n");
3779   }
3780
3781   if (NeedRTCheck && !CanDoRT) {
3782     DEBUG(dbgs() << "LV: We can't vectorize because we can't find " <<
3783           "the array bounds.\n");
3784     PtrRtCheck.reset();
3785     return false;
3786   }
3787
3788   PtrRtCheck.Need = NeedRTCheck;
3789
3790   bool CanVecMem = true;
3791   if (Accesses.isDependencyCheckNeeded()) {
3792     DEBUG(dbgs() << "LV: Checking memory dependencies\n");
3793     CanVecMem = DepChecker.areDepsSafe(DependentAccesses,
3794                                        Accesses.getDependenciesToCheck());
3795     MaxSafeDepDistBytes = DepChecker.getMaxSafeDepDistBytes();
3796   }
3797
3798   DEBUG(dbgs() << "LV: We "<< (NeedRTCheck ? "" : "don't") <<
3799         " need a runtime memory check.\n");
3800
3801   return CanVecMem;
3802 }
3803
3804 static bool hasMultipleUsesOf(Instruction *I,
3805                               SmallPtrSet<Instruction *, 8> &Insts) {
3806   unsigned NumUses = 0;
3807   for(User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use) {
3808     if (Insts.count(dyn_cast<Instruction>(*Use)))
3809       ++NumUses;
3810     if (NumUses > 1)
3811       return true;
3812   }
3813
3814   return false;
3815 }
3816
3817 static bool areAllUsesIn(Instruction *I, SmallPtrSet<Instruction *, 8> &Set) {
3818   for(User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use)
3819     if (!Set.count(dyn_cast<Instruction>(*Use)))
3820       return false;
3821   return true;
3822 }
3823
3824 bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi,
3825                                                 ReductionKind Kind) {
3826   if (Phi->getNumIncomingValues() != 2)
3827     return false;
3828
3829   // Reduction variables are only found in the loop header block.
3830   if (Phi->getParent() != TheLoop->getHeader())
3831     return false;
3832
3833   // Obtain the reduction start value from the value that comes from the loop
3834   // preheader.
3835   Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
3836
3837   // ExitInstruction is the single value which is used outside the loop.
3838   // We only allow for a single reduction value to be used outside the loop.
3839   // This includes users of the reduction, variables (which form a cycle
3840   // which ends in the phi node).
3841   Instruction *ExitInstruction = 0;
3842   // Indicates that we found a reduction operation in our scan.
3843   bool FoundReduxOp = false;
3844
3845   // We start with the PHI node and scan for all of the users of this
3846   // instruction. All users must be instructions that can be used as reduction
3847   // variables (such as ADD). We must have a single out-of-block user. The cycle
3848   // must include the original PHI.
3849   bool FoundStartPHI = false;
3850
3851   // To recognize min/max patterns formed by a icmp select sequence, we store
3852   // the number of instruction we saw from the recognized min/max pattern,
3853   //  to make sure we only see exactly the two instructions.
3854   unsigned NumCmpSelectPatternInst = 0;
3855   ReductionInstDesc ReduxDesc(false, 0);
3856
3857   SmallPtrSet<Instruction *, 8> VisitedInsts;
3858   SmallVector<Instruction *, 8> Worklist;
3859   Worklist.push_back(Phi);
3860   VisitedInsts.insert(Phi);
3861
3862   // A value in the reduction can be used:
3863   //  - By the reduction:
3864   //      - Reduction operation:
3865   //        - One use of reduction value (safe).
3866   //        - Multiple use of reduction value (not safe).
3867   //      - PHI:
3868   //        - All uses of the PHI must be the reduction (safe).
3869   //        - Otherwise, not safe.
3870   //  - By one instruction outside of the loop (safe).
3871   //  - By further instructions outside of the loop (not safe).
3872   //  - By an instruction that is not part of the reduction (not safe).
3873   //    This is either:
3874   //      * An instruction type other than PHI or the reduction operation.
3875   //      * A PHI in the header other than the initial PHI.
3876   while (!Worklist.empty()) {
3877     Instruction *Cur = Worklist.back();
3878     Worklist.pop_back();
3879
3880     // No Users.
3881     // If the instruction has no users then this is a broken chain and can't be
3882     // a reduction variable.
3883     if (Cur->use_empty())
3884       return false;
3885
3886     bool IsAPhi = isa<PHINode>(Cur);
3887
3888     // A header PHI use other than the original PHI.
3889     if (Cur != Phi && IsAPhi && Cur->getParent() == Phi->getParent())
3890       return false;
3891
3892     // Reductions of instructions such as Div, and Sub is only possible if the
3893     // LHS is the reduction variable.
3894     if (!Cur->isCommutative() && !IsAPhi && !isa<SelectInst>(Cur) &&
3895         !isa<ICmpInst>(Cur) && !isa<FCmpInst>(Cur) &&
3896         !VisitedInsts.count(dyn_cast<Instruction>(Cur->getOperand(0))))
3897       return false;
3898
3899     // Any reduction instruction must be of one of the allowed kinds.
3900     ReduxDesc = isReductionInstr(Cur, Kind, ReduxDesc);
3901     if (!ReduxDesc.IsReduction)
3902       return false;
3903
3904     // A reduction operation must only have one use of the reduction value.
3905     if (!IsAPhi && Kind != RK_IntegerMinMax && Kind != RK_FloatMinMax &&
3906         hasMultipleUsesOf(Cur, VisitedInsts))
3907       return false;
3908
3909     // All inputs to a PHI node must be a reduction value.
3910     if(IsAPhi && Cur != Phi && !areAllUsesIn(Cur, VisitedInsts))
3911       return false;
3912
3913     if (Kind == RK_IntegerMinMax && (isa<ICmpInst>(Cur) ||
3914                                      isa<SelectInst>(Cur)))
3915       ++NumCmpSelectPatternInst;
3916     if (Kind == RK_FloatMinMax && (isa<FCmpInst>(Cur) ||
3917                                    isa<SelectInst>(Cur)))
3918       ++NumCmpSelectPatternInst;
3919
3920     // Check  whether we found a reduction operator.
3921     FoundReduxOp |= !IsAPhi;
3922
3923     // Process users of current instruction. Push non PHI nodes after PHI nodes
3924     // onto the stack. This way we are going to have seen all inputs to PHI
3925     // nodes once we get to them.
3926     SmallVector<Instruction *, 8> NonPHIs;
3927     SmallVector<Instruction *, 8> PHIs;
3928     for (Value::use_iterator UI = Cur->use_begin(), E = Cur->use_end(); UI != E;
3929          ++UI) {
3930       Instruction *Usr = cast<Instruction>(*UI);
3931
3932       // Check if we found the exit user.
3933       BasicBlock *Parent = Usr->getParent();
3934       if (!TheLoop->contains(Parent)) {
3935         // Exit if you find multiple outside users or if the header phi node is
3936         // being used. In this case the user uses the value of the previous
3937         // iteration, in which case we would loose "VF-1" iterations of the
3938         // reduction operation if we vectorize.
3939         if (ExitInstruction != 0 || Cur == Phi)
3940           return false;
3941
3942         ExitInstruction = Cur;
3943         continue;
3944       }
3945
3946       // Process instructions only once (termination).
3947       if (VisitedInsts.insert(Usr)) {
3948         if (isa<PHINode>(Usr))
3949           PHIs.push_back(Usr);
3950         else
3951           NonPHIs.push_back(Usr);
3952       }
3953       // Remember that we completed the cycle.
3954       if (Usr == Phi)
3955         FoundStartPHI = true;
3956     }
3957     Worklist.append(PHIs.begin(), PHIs.end());
3958     Worklist.append(NonPHIs.begin(), NonPHIs.end());
3959   }
3960
3961   // This means we have seen one but not the other instruction of the
3962   // pattern or more than just a select and cmp.
3963   if ((Kind == RK_IntegerMinMax || Kind == RK_FloatMinMax) &&
3964       NumCmpSelectPatternInst != 2)
3965     return false;
3966
3967   if (!FoundStartPHI || !FoundReduxOp || !ExitInstruction)
3968     return false;
3969
3970   // We found a reduction var if we have reached the original phi node and we
3971   // only have a single instruction with out-of-loop users.
3972
3973   // This instruction is allowed to have out-of-loop users.
3974   AllowedExit.insert(ExitInstruction);
3975
3976   // Save the description of this reduction variable.
3977   ReductionDescriptor RD(RdxStart, ExitInstruction, Kind,
3978                          ReduxDesc.MinMaxKind);
3979   Reductions[Phi] = RD;
3980   // We've ended the cycle. This is a reduction variable if we have an
3981   // outside user and it has a binary op.
3982
3983   return true;
3984 }
3985
3986 /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
3987 /// pattern corresponding to a min(X, Y) or max(X, Y).
3988 LoopVectorizationLegality::ReductionInstDesc
3989 LoopVectorizationLegality::isMinMaxSelectCmpPattern(Instruction *I,
3990                                                     ReductionInstDesc &Prev) {
3991
3992   assert((isa<ICmpInst>(I) || isa<FCmpInst>(I) || isa<SelectInst>(I)) &&
3993          "Expect a select instruction");
3994   Instruction *Cmp = 0;
3995   SelectInst *Select = 0;
3996
3997   // We must handle the select(cmp()) as a single instruction. Advance to the
3998   // select.
3999   if ((Cmp = dyn_cast<ICmpInst>(I)) || (Cmp = dyn_cast<FCmpInst>(I))) {
4000     if (!Cmp->hasOneUse() || !(Select = dyn_cast<SelectInst>(*I->use_begin())))
4001       return ReductionInstDesc(false, I);
4002     return ReductionInstDesc(Select, Prev.MinMaxKind);
4003   }
4004
4005   // Only handle single use cases for now.
4006   if (!(Select = dyn_cast<SelectInst>(I)))
4007     return ReductionInstDesc(false, I);
4008   if (!(Cmp = dyn_cast<ICmpInst>(I->getOperand(0))) &&
4009       !(Cmp = dyn_cast<FCmpInst>(I->getOperand(0))))
4010     return ReductionInstDesc(false, I);
4011   if (!Cmp->hasOneUse())
4012     return ReductionInstDesc(false, I);
4013
4014   Value *CmpLeft;
4015   Value *CmpRight;
4016
4017   // Look for a min/max pattern.
4018   if (m_UMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4019     return ReductionInstDesc(Select, MRK_UIntMin);
4020   else if (m_UMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4021     return ReductionInstDesc(Select, MRK_UIntMax);
4022   else if (m_SMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4023     return ReductionInstDesc(Select, MRK_SIntMax);
4024   else if (m_SMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4025     return ReductionInstDesc(Select, MRK_SIntMin);
4026   else if (m_OrdFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4027     return ReductionInstDesc(Select, MRK_FloatMin);
4028   else if (m_OrdFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4029     return ReductionInstDesc(Select, MRK_FloatMax);
4030   else if (m_UnordFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4031     return ReductionInstDesc(Select, MRK_FloatMin);
4032   else if (m_UnordFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4033     return ReductionInstDesc(Select, MRK_FloatMax);
4034
4035   return ReductionInstDesc(false, I);
4036 }
4037
4038 LoopVectorizationLegality::ReductionInstDesc
4039 LoopVectorizationLegality::isReductionInstr(Instruction *I,
4040                                             ReductionKind Kind,
4041                                             ReductionInstDesc &Prev) {
4042   bool FP = I->getType()->isFloatingPointTy();
4043   bool FastMath = (FP && I->isCommutative() && I->isAssociative());
4044   switch (I->getOpcode()) {
4045   default:
4046     return ReductionInstDesc(false, I);
4047   case Instruction::PHI:
4048       if (FP && (Kind != RK_FloatMult && Kind != RK_FloatAdd &&
4049                  Kind != RK_FloatMinMax))
4050         return ReductionInstDesc(false, I);
4051     return ReductionInstDesc(I, Prev.MinMaxKind);
4052   case Instruction::Sub:
4053   case Instruction::Add:
4054     return ReductionInstDesc(Kind == RK_IntegerAdd, I);
4055   case Instruction::Mul:
4056     return ReductionInstDesc(Kind == RK_IntegerMult, I);
4057   case Instruction::And:
4058     return ReductionInstDesc(Kind == RK_IntegerAnd, I);
4059   case Instruction::Or:
4060     return ReductionInstDesc(Kind == RK_IntegerOr, I);
4061   case Instruction::Xor:
4062     return ReductionInstDesc(Kind == RK_IntegerXor, I);
4063   case Instruction::FMul:
4064     return ReductionInstDesc(Kind == RK_FloatMult && FastMath, I);
4065   case Instruction::FAdd:
4066     return ReductionInstDesc(Kind == RK_FloatAdd && FastMath, I);
4067   case Instruction::FCmp:
4068   case Instruction::ICmp:
4069   case Instruction::Select:
4070     if (Kind != RK_IntegerMinMax &&
4071         (!HasFunNoNaNAttr || Kind != RK_FloatMinMax))
4072       return ReductionInstDesc(false, I);
4073     return isMinMaxSelectCmpPattern(I, Prev);
4074   }
4075 }
4076
4077 LoopVectorizationLegality::InductionKind
4078 LoopVectorizationLegality::isInductionVariable(PHINode *Phi) {
4079   Type *PhiTy = Phi->getType();
4080   // We only handle integer and pointer inductions variables.
4081   if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
4082     return IK_NoInduction;
4083
4084   // Check that the PHI is consecutive.
4085   const SCEV *PhiScev = SE->getSCEV(Phi);
4086   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
4087   if (!AR) {
4088     DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
4089     return IK_NoInduction;
4090   }
4091   const SCEV *Step = AR->getStepRecurrence(*SE);
4092
4093   // Integer inductions need to have a stride of one.
4094   if (PhiTy->isIntegerTy()) {
4095     if (Step->isOne())
4096       return IK_IntInduction;
4097     if (Step->isAllOnesValue())
4098       return IK_ReverseIntInduction;
4099     return IK_NoInduction;
4100   }
4101
4102   // Calculate the pointer stride and check if it is consecutive.
4103   const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
4104   if (!C)
4105     return IK_NoInduction;
4106
4107   assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
4108   uint64_t Size = DL->getTypeAllocSize(PhiTy->getPointerElementType());
4109   if (C->getValue()->equalsInt(Size))
4110     return IK_PtrInduction;
4111   else if (C->getValue()->equalsInt(0 - Size))
4112     return IK_ReversePtrInduction;
4113
4114   return IK_NoInduction;
4115 }
4116
4117 bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
4118   Value *In0 = const_cast<Value*>(V);
4119   PHINode *PN = dyn_cast_or_null<PHINode>(In0);
4120   if (!PN)
4121     return false;
4122
4123   return Inductions.count(PN);
4124 }
4125
4126 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB)  {
4127   assert(TheLoop->contains(BB) && "Unknown block used");
4128
4129   // Blocks that do not dominate the latch need predication.
4130   BasicBlock* Latch = TheLoop->getLoopLatch();
4131   return !DT->dominates(BB, Latch);
4132 }
4133
4134 bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB,
4135                                             SmallPtrSet<Value *, 8>& SafePtrs) {
4136   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
4137     // We might be able to hoist the load.
4138     if (it->mayReadFromMemory()) {
4139       LoadInst *LI = dyn_cast<LoadInst>(it);
4140       if (!LI || !SafePtrs.count(LI->getPointerOperand()))
4141         return false;
4142     }
4143
4144     // We don't predicate stores at the moment.
4145     if (it->mayWriteToMemory() || it->mayThrow())
4146       return false;
4147
4148     // The instructions below can trap.
4149     switch (it->getOpcode()) {
4150     default: continue;
4151     case Instruction::UDiv:
4152     case Instruction::SDiv:
4153     case Instruction::URem:
4154     case Instruction::SRem:
4155              return false;
4156     }
4157   }
4158
4159   return true;
4160 }
4161
4162 LoopVectorizationCostModel::VectorizationFactor
4163 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize,
4164                                                       unsigned UserVF) {
4165   // Width 1 means no vectorize
4166   VectorizationFactor Factor = { 1U, 0U };
4167   if (OptForSize && Legal->getRuntimePointerCheck()->Need) {
4168     DEBUG(dbgs() << "LV: Aborting. Runtime ptr check is required in Os.\n");
4169     return Factor;
4170   }
4171
4172   // Find the trip count.
4173   unsigned TC = SE->getSmallConstantTripCount(TheLoop, TheLoop->getLoopLatch());
4174   DEBUG(dbgs() << "LV: Found trip count:"<<TC<<"\n");
4175
4176   unsigned WidestType = getWidestType();
4177   unsigned WidestRegister = TTI.getRegisterBitWidth(true);
4178   unsigned MaxSafeDepDist = -1U;
4179   if (Legal->getMaxSafeDepDistBytes() != -1U)
4180     MaxSafeDepDist = Legal->getMaxSafeDepDistBytes() * 8;
4181   WidestRegister = ((WidestRegister < MaxSafeDepDist) ?
4182                     WidestRegister : MaxSafeDepDist);
4183   unsigned MaxVectorSize = WidestRegister / WidestType;
4184   DEBUG(dbgs() << "LV: The Widest type: " << WidestType << " bits.\n");
4185   DEBUG(dbgs() << "LV: The Widest register is:" << WidestRegister << "bits.\n");
4186
4187   if (MaxVectorSize == 0) {
4188     DEBUG(dbgs() << "LV: The target has no vector registers.\n");
4189     MaxVectorSize = 1;
4190   }
4191
4192   assert(MaxVectorSize <= 32 && "Did not expect to pack so many elements"
4193          " into one vector!");
4194
4195   unsigned VF = MaxVectorSize;
4196
4197   // If we optimize the program for size, avoid creating the tail loop.
4198   if (OptForSize) {
4199     // If we are unable to calculate the trip count then don't try to vectorize.
4200     if (TC < 2) {
4201       DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
4202       return Factor;
4203     }
4204
4205     // Find the maximum SIMD width that can fit within the trip count.
4206     VF = TC % MaxVectorSize;
4207
4208     if (VF == 0)
4209       VF = MaxVectorSize;
4210
4211     // If the trip count that we found modulo the vectorization factor is not
4212     // zero then we require a tail.
4213     if (VF < 2) {
4214       DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
4215       return Factor;
4216     }
4217   }
4218
4219   if (UserVF != 0) {
4220     assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
4221     DEBUG(dbgs() << "LV: Using user VF "<<UserVF<<".\n");
4222
4223     Factor.Width = UserVF;
4224     return Factor;
4225   }
4226
4227   float Cost = expectedCost(1);
4228   unsigned Width = 1;
4229   DEBUG(dbgs() << "LV: Scalar loop costs: "<< (int)Cost << ".\n");
4230   for (unsigned i=2; i <= VF; i*=2) {
4231     // Notice that the vector loop needs to be executed less times, so
4232     // we need to divide the cost of the vector loops by the width of
4233     // the vector elements.
4234     float VectorCost = expectedCost(i) / (float)i;
4235     DEBUG(dbgs() << "LV: Vector loop of width "<< i << " costs: " <<
4236           (int)VectorCost << ".\n");
4237     if (VectorCost < Cost) {
4238       Cost = VectorCost;
4239       Width = i;
4240     }
4241   }
4242
4243   DEBUG(dbgs() << "LV: Selecting VF = : "<< Width << ".\n");
4244   Factor.Width = Width;
4245   Factor.Cost = Width * Cost;
4246   return Factor;
4247 }
4248
4249 unsigned LoopVectorizationCostModel::getWidestType() {
4250   unsigned MaxWidth = 8;
4251
4252   // For each block.
4253   for (Loop::block_iterator bb = TheLoop->block_begin(),
4254        be = TheLoop->block_end(); bb != be; ++bb) {
4255     BasicBlock *BB = *bb;
4256
4257     // For each instruction in the loop.
4258     for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
4259       Type *T = it->getType();
4260
4261       // Only examine Loads, Stores and PHINodes.
4262       if (!isa<LoadInst>(it) && !isa<StoreInst>(it) && !isa<PHINode>(it))
4263         continue;
4264
4265       // Examine PHI nodes that are reduction variables.
4266       if (PHINode *PN = dyn_cast<PHINode>(it))
4267         if (!Legal->getReductionVars()->count(PN))
4268           continue;
4269
4270       // Examine the stored values.
4271       if (StoreInst *ST = dyn_cast<StoreInst>(it))
4272         T = ST->getValueOperand()->getType();
4273
4274       // Ignore loaded pointer types and stored pointer types that are not
4275       // consecutive. However, we do want to take consecutive stores/loads of
4276       // pointer vectors into account.
4277       if (T->isPointerTy() && !isConsecutiveLoadOrStore(it))
4278         continue;
4279
4280       MaxWidth = std::max(MaxWidth,
4281                           (unsigned)DL->getTypeSizeInBits(T->getScalarType()));
4282     }
4283   }
4284
4285   return MaxWidth;
4286 }
4287
4288 unsigned
4289 LoopVectorizationCostModel::selectUnrollFactor(bool OptForSize,
4290                                                unsigned UserUF,
4291                                                unsigned VF,
4292                                                unsigned LoopCost) {
4293
4294   // -- The unroll heuristics --
4295   // We unroll the loop in order to expose ILP and reduce the loop overhead.
4296   // There are many micro-architectural considerations that we can't predict
4297   // at this level. For example frontend pressure (on decode or fetch) due to
4298   // code size, or the number and capabilities of the execution ports.
4299   //
4300   // We use the following heuristics to select the unroll factor:
4301   // 1. If the code has reductions the we unroll in order to break the cross
4302   // iteration dependency.
4303   // 2. If the loop is really small then we unroll in order to reduce the loop
4304   // overhead.
4305   // 3. We don't unroll if we think that we will spill registers to memory due
4306   // to the increased register pressure.
4307
4308   // Use the user preference, unless 'auto' is selected.
4309   if (UserUF != 0)
4310     return UserUF;
4311
4312   // When we optimize for size we don't unroll.
4313   if (OptForSize)
4314     return 1;
4315
4316   // We used the distance for the unroll factor.
4317   if (Legal->getMaxSafeDepDistBytes() != -1U)
4318     return 1;
4319
4320   // Do not unroll loops with a relatively small trip count.
4321   unsigned TC = SE->getSmallConstantTripCount(TheLoop,
4322                                               TheLoop->getLoopLatch());
4323   if (TC > 1 && TC < TinyTripCountUnrollThreshold)
4324     return 1;
4325
4326   unsigned TargetVectorRegisters = TTI.getNumberOfRegisters(true);
4327   DEBUG(dbgs() << "LV: The target has " << TargetVectorRegisters <<
4328         " vector registers\n");
4329
4330   LoopVectorizationCostModel::RegisterUsage R = calculateRegisterUsage();
4331   // We divide by these constants so assume that we have at least one
4332   // instruction that uses at least one register.
4333   R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
4334   R.NumInstructions = std::max(R.NumInstructions, 1U);
4335
4336   // We calculate the unroll factor using the following formula.
4337   // Subtract the number of loop invariants from the number of available
4338   // registers. These registers are used by all of the unrolled instances.
4339   // Next, divide the remaining registers by the number of registers that is
4340   // required by the loop, in order to estimate how many parallel instances
4341   // fit without causing spills.
4342   unsigned UF = (TargetVectorRegisters - R.LoopInvariantRegs) / R.MaxLocalUsers;
4343
4344   // Clamp the unroll factor ranges to reasonable factors.
4345   unsigned MaxUnrollSize = TTI.getMaximumUnrollFactor();
4346
4347   // If we did not calculate the cost for VF (because the user selected the VF)
4348   // then we calculate the cost of VF here.
4349   if (LoopCost == 0)
4350     LoopCost = expectedCost(VF);
4351
4352   // Clamp the calculated UF to be between the 1 and the max unroll factor
4353   // that the target allows.
4354   if (UF > MaxUnrollSize)
4355     UF = MaxUnrollSize;
4356   else if (UF < 1)
4357     UF = 1;
4358
4359   bool HasReductions = Legal->getReductionVars()->size();
4360
4361   // Decide if we want to unroll if we decided that it is legal to vectorize
4362   // but not profitable.
4363   if (VF == 1) {
4364     if (TheLoop->getNumBlocks() > 1 || !HasReductions ||
4365         LoopCost > SmallLoopCost)
4366       return 1;
4367
4368     return UF;
4369   }
4370
4371   if (HasReductions) {
4372     DEBUG(dbgs() << "LV: Unrolling because of reductions. \n");
4373     return UF;
4374   }
4375
4376   // We want to unroll tiny loops in order to reduce the loop overhead.
4377   // We assume that the cost overhead is 1 and we use the cost model
4378   // to estimate the cost of the loop and unroll until the cost of the
4379   // loop overhead is about 5% of the cost of the loop.
4380   DEBUG(dbgs() << "LV: Loop cost is "<< LoopCost <<" \n");
4381   if (LoopCost < SmallLoopCost) {
4382     DEBUG(dbgs() << "LV: Unrolling to reduce branch cost. \n");
4383     unsigned NewUF = SmallLoopCost / (LoopCost + 1);
4384     return std::min(NewUF, UF);
4385   }
4386
4387   DEBUG(dbgs() << "LV: Not Unrolling. \n");
4388   return 1;
4389 }
4390
4391 LoopVectorizationCostModel::RegisterUsage
4392 LoopVectorizationCostModel::calculateRegisterUsage() {
4393   // This function calculates the register usage by measuring the highest number
4394   // of values that are alive at a single location. Obviously, this is a very
4395   // rough estimation. We scan the loop in a topological order in order and
4396   // assign a number to each instruction. We use RPO to ensure that defs are
4397   // met before their users. We assume that each instruction that has in-loop
4398   // users starts an interval. We record every time that an in-loop value is
4399   // used, so we have a list of the first and last occurrences of each
4400   // instruction. Next, we transpose this data structure into a multi map that
4401   // holds the list of intervals that *end* at a specific location. This multi
4402   // map allows us to perform a linear search. We scan the instructions linearly
4403   // and record each time that a new interval starts, by placing it in a set.
4404   // If we find this value in the multi-map then we remove it from the set.
4405   // The max register usage is the maximum size of the set.
4406   // We also search for instructions that are defined outside the loop, but are
4407   // used inside the loop. We need this number separately from the max-interval
4408   // usage number because when we unroll, loop-invariant values do not take
4409   // more register.
4410   LoopBlocksDFS DFS(TheLoop);
4411   DFS.perform(LI);
4412
4413   RegisterUsage R;
4414   R.NumInstructions = 0;
4415
4416   // Each 'key' in the map opens a new interval. The values
4417   // of the map are the index of the 'last seen' usage of the
4418   // instruction that is the key.
4419   typedef DenseMap<Instruction*, unsigned> IntervalMap;
4420   // Maps instruction to its index.
4421   DenseMap<unsigned, Instruction*> IdxToInstr;
4422   // Marks the end of each interval.
4423   IntervalMap EndPoint;
4424   // Saves the list of instruction indices that are used in the loop.
4425   SmallSet<Instruction*, 8> Ends;
4426   // Saves the list of values that are used in the loop but are
4427   // defined outside the loop, such as arguments and constants.
4428   SmallPtrSet<Value*, 8> LoopInvariants;
4429
4430   unsigned Index = 0;
4431   for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
4432        be = DFS.endRPO(); bb != be; ++bb) {
4433     R.NumInstructions += (*bb)->size();
4434     for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
4435          ++it) {
4436       Instruction *I = it;
4437       IdxToInstr[Index++] = I;
4438
4439       // Save the end location of each USE.
4440       for (unsigned i = 0; i < I->getNumOperands(); ++i) {
4441         Value *U = I->getOperand(i);
4442         Instruction *Instr = dyn_cast<Instruction>(U);
4443
4444         // Ignore non-instruction values such as arguments, constants, etc.
4445         if (!Instr) continue;
4446
4447         // If this instruction is outside the loop then record it and continue.
4448         if (!TheLoop->contains(Instr)) {
4449           LoopInvariants.insert(Instr);
4450           continue;
4451         }
4452
4453         // Overwrite previous end points.
4454         EndPoint[Instr] = Index;
4455         Ends.insert(Instr);
4456       }
4457     }
4458   }
4459
4460   // Saves the list of intervals that end with the index in 'key'.
4461   typedef SmallVector<Instruction*, 2> InstrList;
4462   DenseMap<unsigned, InstrList> TransposeEnds;
4463
4464   // Transpose the EndPoints to a list of values that end at each index.
4465   for (IntervalMap::iterator it = EndPoint.begin(), e = EndPoint.end();
4466        it != e; ++it)
4467     TransposeEnds[it->second].push_back(it->first);
4468
4469   SmallSet<Instruction*, 8> OpenIntervals;
4470   unsigned MaxUsage = 0;
4471
4472
4473   DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
4474   for (unsigned int i = 0; i < Index; ++i) {
4475     Instruction *I = IdxToInstr[i];
4476     // Ignore instructions that are never used within the loop.
4477     if (!Ends.count(I)) continue;
4478
4479     // Remove all of the instructions that end at this location.
4480     InstrList &List = TransposeEnds[i];
4481     for (unsigned int j=0, e = List.size(); j < e; ++j)
4482       OpenIntervals.erase(List[j]);
4483
4484     // Count the number of live interals.
4485     MaxUsage = std::max(MaxUsage, OpenIntervals.size());
4486
4487     DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # " <<
4488           OpenIntervals.size() <<"\n");
4489
4490     // Add the current instruction to the list of open intervals.
4491     OpenIntervals.insert(I);
4492   }
4493
4494   unsigned Invariant = LoopInvariants.size();
4495   DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsage << " \n");
4496   DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << " \n");
4497   DEBUG(dbgs() << "LV(REG): LoopSize: " << R.NumInstructions << " \n");
4498
4499   R.LoopInvariantRegs = Invariant;
4500   R.MaxLocalUsers = MaxUsage;
4501   return R;
4502 }
4503
4504 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
4505   unsigned Cost = 0;
4506
4507   // For each block.
4508   for (Loop::block_iterator bb = TheLoop->block_begin(),
4509        be = TheLoop->block_end(); bb != be; ++bb) {
4510     unsigned BlockCost = 0;
4511     BasicBlock *BB = *bb;
4512
4513     // For each instruction in the old loop.
4514     for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
4515       // Skip dbg intrinsics.
4516       if (isa<DbgInfoIntrinsic>(it))
4517         continue;
4518
4519       unsigned C = getInstructionCost(it, VF);
4520       BlockCost += C;
4521       DEBUG(dbgs() << "LV: Found an estimated cost of "<< C <<" for VF " <<
4522             VF << " For instruction: "<< *it << "\n");
4523     }
4524
4525     // We assume that if-converted blocks have a 50% chance of being executed.
4526     // When the code is scalar then some of the blocks are avoided due to CF.
4527     // When the code is vectorized we execute all code paths.
4528     if (VF == 1 && Legal->blockNeedsPredication(*bb))
4529       BlockCost /= 2;
4530
4531     Cost += BlockCost;
4532   }
4533
4534   return Cost;
4535 }
4536
4537 /// \brief Check whether the address computation for a non-consecutive memory
4538 /// access looks like an unlikely candidate for being merged into the indexing
4539 /// mode.
4540 ///
4541 /// We look for a GEP which has one index that is an induction variable and all
4542 /// other indices are loop invariant. If the stride of this access is also
4543 /// within a small bound we decide that this address computation can likely be
4544 /// merged into the addressing mode.
4545 /// In all other cases, we identify the address computation as complex.
4546 static bool isLikelyComplexAddressComputation(Value *Ptr,
4547                                               LoopVectorizationLegality *Legal,
4548                                               ScalarEvolution *SE,
4549                                               const Loop *TheLoop) {
4550   GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
4551   if (!Gep)
4552     return true;
4553
4554   // We are looking for a gep with all loop invariant indices except for one
4555   // which should be an induction variable.
4556   unsigned NumOperands = Gep->getNumOperands();
4557   for (unsigned i = 1; i < NumOperands; ++i) {
4558     Value *Opd = Gep->getOperand(i);
4559     if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
4560         !Legal->isInductionVariable(Opd))
4561       return true;
4562   }
4563
4564   // Now we know we have a GEP ptr, %inv, %ind, %inv. Make sure that the step
4565   // can likely be merged into the address computation.
4566   unsigned MaxMergeDistance = 64;
4567
4568   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Ptr));
4569   if (!AddRec)
4570     return true;
4571
4572   // Check the step is constant.
4573   const SCEV *Step = AddRec->getStepRecurrence(*SE);
4574   // Calculate the pointer stride and check if it is consecutive.
4575   const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
4576   if (!C)
4577     return true;
4578
4579   const APInt &APStepVal = C->getValue()->getValue();
4580
4581   // Huge step value - give up.
4582   if (APStepVal.getBitWidth() > 64)
4583     return true;
4584
4585   int64_t StepVal = APStepVal.getSExtValue();
4586
4587   return StepVal > MaxMergeDistance;
4588 }
4589
4590 unsigned
4591 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
4592   // If we know that this instruction will remain uniform, check the cost of
4593   // the scalar version.
4594   if (Legal->isUniformAfterVectorization(I))
4595     VF = 1;
4596
4597   Type *RetTy = I->getType();
4598   Type *VectorTy = ToVectorTy(RetTy, VF);
4599
4600   // TODO: We need to estimate the cost of intrinsic calls.
4601   switch (I->getOpcode()) {
4602   case Instruction::GetElementPtr:
4603     // We mark this instruction as zero-cost because the cost of GEPs in
4604     // vectorized code depends on whether the corresponding memory instruction
4605     // is scalarized or not. Therefore, we handle GEPs with the memory
4606     // instruction cost.
4607     return 0;
4608   case Instruction::Br: {
4609     return TTI.getCFInstrCost(I->getOpcode());
4610   }
4611   case Instruction::PHI:
4612     //TODO: IF-converted IFs become selects.
4613     return 0;
4614   case Instruction::Add:
4615   case Instruction::FAdd:
4616   case Instruction::Sub:
4617   case Instruction::FSub:
4618   case Instruction::Mul:
4619   case Instruction::FMul:
4620   case Instruction::UDiv:
4621   case Instruction::SDiv:
4622   case Instruction::FDiv:
4623   case Instruction::URem:
4624   case Instruction::SRem:
4625   case Instruction::FRem:
4626   case Instruction::Shl:
4627   case Instruction::LShr:
4628   case Instruction::AShr:
4629   case Instruction::And:
4630   case Instruction::Or:
4631   case Instruction::Xor: {
4632     // Certain instructions can be cheaper to vectorize if they have a constant
4633     // second vector operand. One example of this are shifts on x86.
4634     TargetTransformInfo::OperandValueKind Op1VK =
4635       TargetTransformInfo::OK_AnyValue;
4636     TargetTransformInfo::OperandValueKind Op2VK =
4637       TargetTransformInfo::OK_AnyValue;
4638
4639     if (isa<ConstantInt>(I->getOperand(1)))
4640       Op2VK = TargetTransformInfo::OK_UniformConstantValue;
4641
4642     return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy, Op1VK, Op2VK);
4643   }
4644   case Instruction::Select: {
4645     SelectInst *SI = cast<SelectInst>(I);
4646     const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
4647     bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
4648     Type *CondTy = SI->getCondition()->getType();
4649     if (!ScalarCond)
4650       CondTy = VectorType::get(CondTy, VF);
4651
4652     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
4653   }
4654   case Instruction::ICmp:
4655   case Instruction::FCmp: {
4656     Type *ValTy = I->getOperand(0)->getType();
4657     VectorTy = ToVectorTy(ValTy, VF);
4658     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy);
4659   }
4660   case Instruction::Store:
4661   case Instruction::Load: {
4662     StoreInst *SI = dyn_cast<StoreInst>(I);
4663     LoadInst *LI = dyn_cast<LoadInst>(I);
4664     Type *ValTy = (SI ? SI->getValueOperand()->getType() :
4665                    LI->getType());
4666     VectorTy = ToVectorTy(ValTy, VF);
4667
4668     unsigned Alignment = SI ? SI->getAlignment() : LI->getAlignment();
4669     unsigned AS = SI ? SI->getPointerAddressSpace() :
4670       LI->getPointerAddressSpace();
4671     Value *Ptr = SI ? SI->getPointerOperand() : LI->getPointerOperand();
4672     // We add the cost of address computation here instead of with the gep
4673     // instruction because only here we know whether the operation is
4674     // scalarized.
4675     if (VF == 1)
4676       return TTI.getAddressComputationCost(VectorTy) +
4677         TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
4678
4679     // Scalarized loads/stores.
4680     int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
4681     bool Reverse = ConsecutiveStride < 0;
4682     unsigned ScalarAllocatedSize = DL->getTypeAllocSize(ValTy);
4683     unsigned VectorElementSize = DL->getTypeStoreSize(VectorTy)/VF;
4684     if (!ConsecutiveStride || ScalarAllocatedSize != VectorElementSize) {
4685       bool IsComplexComputation =
4686         isLikelyComplexAddressComputation(Ptr, Legal, SE, TheLoop);
4687       unsigned Cost = 0;
4688       // The cost of extracting from the value vector and pointer vector.
4689       Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
4690       for (unsigned i = 0; i < VF; ++i) {
4691         //  The cost of extracting the pointer operand.
4692         Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
4693         // In case of STORE, the cost of ExtractElement from the vector.
4694         // In case of LOAD, the cost of InsertElement into the returned
4695         // vector.
4696         Cost += TTI.getVectorInstrCost(SI ? Instruction::ExtractElement :
4697                                             Instruction::InsertElement,
4698                                             VectorTy, i);
4699       }
4700
4701       // The cost of the scalar loads/stores.
4702       Cost += VF * TTI.getAddressComputationCost(PtrTy, IsComplexComputation);
4703       Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(),
4704                                        Alignment, AS);
4705       return Cost;
4706     }
4707
4708     // Wide load/stores.
4709     unsigned Cost = TTI.getAddressComputationCost(VectorTy);
4710     Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
4711
4712     if (Reverse)
4713       Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
4714                                   VectorTy, 0);
4715     return Cost;
4716   }
4717   case Instruction::ZExt:
4718   case Instruction::SExt:
4719   case Instruction::FPToUI:
4720   case Instruction::FPToSI:
4721   case Instruction::FPExt:
4722   case Instruction::PtrToInt:
4723   case Instruction::IntToPtr:
4724   case Instruction::SIToFP:
4725   case Instruction::UIToFP:
4726   case Instruction::Trunc:
4727   case Instruction::FPTrunc:
4728   case Instruction::BitCast: {
4729     // We optimize the truncation of induction variable.
4730     // The cost of these is the same as the scalar operation.
4731     if (I->getOpcode() == Instruction::Trunc &&
4732         Legal->isInductionVariable(I->getOperand(0)))
4733       return TTI.getCastInstrCost(I->getOpcode(), I->getType(),
4734                                   I->getOperand(0)->getType());
4735
4736     Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
4737     return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
4738   }
4739   case Instruction::Call: {
4740     CallInst *CI = cast<CallInst>(I);
4741     Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
4742     assert(ID && "Not an intrinsic call!");
4743     Type *RetTy = ToVectorTy(CI->getType(), VF);
4744     SmallVector<Type*, 4> Tys;
4745     for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
4746       Tys.push_back(ToVectorTy(CI->getArgOperand(i)->getType(), VF));
4747     return TTI.getIntrinsicInstrCost(ID, RetTy, Tys);
4748   }
4749   default: {
4750     // We are scalarizing the instruction. Return the cost of the scalar
4751     // instruction, plus the cost of insert and extract into vector
4752     // elements, times the vector width.
4753     unsigned Cost = 0;
4754
4755     if (!RetTy->isVoidTy() && VF != 1) {
4756       unsigned InsCost = TTI.getVectorInstrCost(Instruction::InsertElement,
4757                                                 VectorTy);
4758       unsigned ExtCost = TTI.getVectorInstrCost(Instruction::ExtractElement,
4759                                                 VectorTy);
4760
4761       // The cost of inserting the results plus extracting each one of the
4762       // operands.
4763       Cost += VF * (InsCost + ExtCost * I->getNumOperands());
4764     }
4765
4766     // The cost of executing VF copies of the scalar instruction. This opcode
4767     // is unknown. Assume that it is the same as 'mul'.
4768     Cost += VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy);
4769     return Cost;
4770   }
4771   }// end of switch.
4772 }
4773
4774 Type* LoopVectorizationCostModel::ToVectorTy(Type *Scalar, unsigned VF) {
4775   if (Scalar->isVoidTy() || VF == 1)
4776     return Scalar;
4777   return VectorType::get(Scalar, VF);
4778 }
4779
4780 char LoopVectorize::ID = 0;
4781 static const char lv_name[] = "Loop Vectorization";
4782 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
4783 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
4784 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
4785 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
4786 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
4787
4788 namespace llvm {
4789   Pass *createLoopVectorizePass() {
4790     return new LoopVectorize();
4791   }
4792 }
4793
4794 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
4795   // Check for a store.
4796   if (StoreInst *ST = dyn_cast<StoreInst>(Inst))
4797     return Legal->isConsecutivePtr(ST->getPointerOperand()) != 0;
4798
4799   // Check for a load.
4800   if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
4801     return Legal->isConsecutivePtr(LI->getPointerOperand()) != 0;
4802
4803   return false;
4804 }
4805
4806
4807 void InnerLoopUnroller::scalarizeInstruction(Instruction *Instr) {
4808   assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
4809   // Holds vector parameters or scalars, in case of uniform vals.
4810   SmallVector<VectorParts, 4> Params;
4811
4812   setDebugLocFromInst(Builder, Instr);
4813
4814   // Find all of the vectorized parameters.
4815   for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
4816     Value *SrcOp = Instr->getOperand(op);
4817
4818     // If we are accessing the old induction variable, use the new one.
4819     if (SrcOp == OldInduction) {
4820       Params.push_back(getVectorValue(SrcOp));
4821       continue;
4822     }
4823
4824     // Try using previously calculated values.
4825     Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
4826
4827     // If the src is an instruction that appeared earlier in the basic block
4828     // then it should already be vectorized.
4829     if (SrcInst && OrigLoop->contains(SrcInst)) {
4830       assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
4831       // The parameter is a vector value from earlier.
4832       Params.push_back(WidenMap.get(SrcInst));
4833     } else {
4834       // The parameter is a scalar from outside the loop. Maybe even a constant.
4835       VectorParts Scalars;
4836       Scalars.append(UF, SrcOp);
4837       Params.push_back(Scalars);
4838     }
4839   }
4840
4841   assert(Params.size() == Instr->getNumOperands() &&
4842          "Invalid number of operands");
4843
4844   // Does this instruction return a value ?
4845   bool IsVoidRetTy = Instr->getType()->isVoidTy();
4846
4847   Value *UndefVec = IsVoidRetTy ? 0 :
4848   UndefValue::get(Instr->getType());
4849   // Create a new entry in the WidenMap and initialize it to Undef or Null.
4850   VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
4851
4852   // For each vector unroll 'part':
4853   for (unsigned Part = 0; Part < UF; ++Part) {
4854     // For each scalar that we create:
4855
4856     Instruction *Cloned = Instr->clone();
4857       if (!IsVoidRetTy)
4858         Cloned->setName(Instr->getName() + ".cloned");
4859       // Replace the operands of the cloned instrucions with extracted scalars.
4860       for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
4861         Value *Op = Params[op][Part];
4862         Cloned->setOperand(op, Op);
4863       }
4864
4865       // Place the cloned scalar in the new loop.
4866       Builder.Insert(Cloned);
4867
4868       // If the original scalar returns a value we need to place it in a vector
4869       // so that future users will be able to use it.
4870       if (!IsVoidRetTy)
4871         VecResults[Part] = Cloned;
4872   }
4873 }
4874
4875 void
4876 InnerLoopUnroller::vectorizeMemoryInstruction(Instruction *Instr,
4877                                               LoopVectorizationLegality*) {
4878   return scalarizeInstruction(Instr);
4879 }
4880
4881 Value *InnerLoopUnroller::reverseVector(Value *Vec) {
4882   return Vec;
4883 }
4884
4885 Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) {
4886   return V;
4887 }
4888
4889 Value *InnerLoopUnroller::getConsecutiveVector(Value* Val, int StartIdx,
4890                                                bool Negate) {
4891   // When unrolling and the VF is 1, we only need to add a simple scalar.
4892   Type *ITy = Val->getType();
4893   assert(!ITy->isVectorTy() && "Val must be a scalar");
4894   Constant *C = ConstantInt::get(ITy, StartIdx, Negate);
4895   return Builder.CreateAdd(Val, C, "induction");
4896 }
4897