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