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