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