LoopVectorize.cpp: Appease MSC16.
[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   Instruction *tnullptr = 0;
1543   if (!Legal->mustCheckStrides())
1544     return std::pair<Instruction *, Instruction *>(tnullptr, tnullptr);
1545
1546   IRBuilder<> ChkBuilder(Loc);
1547
1548   // Emit checks.
1549   Value *Check = 0;
1550   Instruction *FirstInst = 0;
1551   for (SmallPtrSet<Value *, 8>::iterator SI = Legal->strides_begin(),
1552                                          SE = Legal->strides_end();
1553        SI != SE; ++SI) {
1554     Value *Ptr = stripCast(*SI);
1555     Value *C = ChkBuilder.CreateICmpNE(Ptr, ConstantInt::get(Ptr->getType(), 1),
1556                                        "stride.chk");
1557     // Store the first instruction we create.
1558     FirstInst = getFirstInst(FirstInst, C, Loc);
1559     if (Check)
1560       Check = ChkBuilder.CreateOr(Check, C);
1561     else
1562       Check = C;
1563   }
1564
1565   // We have to do this trickery because the IRBuilder might fold the check to a
1566   // constant expression in which case there is no Instruction anchored in a
1567   // the block.
1568   LLVMContext &Ctx = Loc->getContext();
1569   Instruction *TheCheck =
1570       BinaryOperator::CreateAnd(Check, ConstantInt::getTrue(Ctx));
1571   ChkBuilder.Insert(TheCheck, "stride.not.one");
1572   FirstInst = getFirstInst(FirstInst, TheCheck, Loc);
1573
1574   return std::make_pair(FirstInst, TheCheck);
1575 }
1576
1577 std::pair<Instruction *, Instruction *>
1578 InnerLoopVectorizer::addRuntimeCheck(Instruction *Loc) {
1579   LoopVectorizationLegality::RuntimePointerCheck *PtrRtCheck =
1580   Legal->getRuntimePointerCheck();
1581
1582   Instruction *tnullptr = 0;
1583   if (!PtrRtCheck->Need)
1584     return std::pair<Instruction *, Instruction *>(tnullptr, tnullptr);
1585
1586   unsigned NumPointers = PtrRtCheck->Pointers.size();
1587   SmallVector<TrackingVH<Value> , 2> Starts;
1588   SmallVector<TrackingVH<Value> , 2> Ends;
1589
1590   LLVMContext &Ctx = Loc->getContext();
1591   SCEVExpander Exp(*SE, "induction");
1592   Instruction *FirstInst = 0;
1593
1594   for (unsigned i = 0; i < NumPointers; ++i) {
1595     Value *Ptr = PtrRtCheck->Pointers[i];
1596     const SCEV *Sc = SE->getSCEV(Ptr);
1597
1598     if (SE->isLoopInvariant(Sc, OrigLoop)) {
1599       DEBUG(dbgs() << "LV: Adding RT check for a loop invariant ptr:" <<
1600             *Ptr <<"\n");
1601       Starts.push_back(Ptr);
1602       Ends.push_back(Ptr);
1603     } else {
1604       DEBUG(dbgs() << "LV: Adding RT check for range:" << *Ptr << '\n');
1605       unsigned AS = Ptr->getType()->getPointerAddressSpace();
1606
1607       // Use this type for pointer arithmetic.
1608       Type *PtrArithTy = Type::getInt8PtrTy(Ctx, AS);
1609
1610       Value *Start = Exp.expandCodeFor(PtrRtCheck->Starts[i], PtrArithTy, Loc);
1611       Value *End = Exp.expandCodeFor(PtrRtCheck->Ends[i], PtrArithTy, Loc);
1612       Starts.push_back(Start);
1613       Ends.push_back(End);
1614     }
1615   }
1616
1617   IRBuilder<> ChkBuilder(Loc);
1618   // Our instructions might fold to a constant.
1619   Value *MemoryRuntimeCheck = 0;
1620   for (unsigned i = 0; i < NumPointers; ++i) {
1621     for (unsigned j = i+1; j < NumPointers; ++j) {
1622       // No need to check if two readonly pointers intersect.
1623       if (!PtrRtCheck->IsWritePtr[i] && !PtrRtCheck->IsWritePtr[j])
1624         continue;
1625
1626       // Only need to check pointers between two different dependency sets.
1627       if (PtrRtCheck->DependencySetId[i] == PtrRtCheck->DependencySetId[j])
1628        continue;
1629
1630       unsigned AS0 = Starts[i]->getType()->getPointerAddressSpace();
1631       unsigned AS1 = Starts[j]->getType()->getPointerAddressSpace();
1632
1633       assert((AS0 == Ends[j]->getType()->getPointerAddressSpace()) &&
1634              (AS1 == Ends[i]->getType()->getPointerAddressSpace()) &&
1635              "Trying to bounds check pointers with different address spaces");
1636
1637       Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0);
1638       Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1);
1639
1640       Value *Start0 = ChkBuilder.CreateBitCast(Starts[i], PtrArithTy0, "bc");
1641       Value *Start1 = ChkBuilder.CreateBitCast(Starts[j], PtrArithTy1, "bc");
1642       Value *End0 =   ChkBuilder.CreateBitCast(Ends[i],   PtrArithTy1, "bc");
1643       Value *End1 =   ChkBuilder.CreateBitCast(Ends[j],   PtrArithTy0, "bc");
1644
1645       Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0");
1646       FirstInst = getFirstInst(FirstInst, Cmp0, Loc);
1647       Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1");
1648       FirstInst = getFirstInst(FirstInst, Cmp1, Loc);
1649       Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
1650       FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1651       if (MemoryRuntimeCheck) {
1652         IsConflict = ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict,
1653                                          "conflict.rdx");
1654         FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
1655       }
1656       MemoryRuntimeCheck = IsConflict;
1657     }
1658   }
1659
1660   // We have to do this trickery because the IRBuilder might fold the check to a
1661   // constant expression in which case there is no Instruction anchored in a
1662   // the block.
1663   Instruction *Check = BinaryOperator::CreateAnd(MemoryRuntimeCheck,
1664                                                  ConstantInt::getTrue(Ctx));
1665   ChkBuilder.Insert(Check, "memcheck.conflict");
1666   FirstInst = getFirstInst(FirstInst, Check, Loc);
1667   return std::make_pair(FirstInst, Check);
1668 }
1669
1670 void InnerLoopVectorizer::createEmptyLoop() {
1671   /*
1672    In this function we generate a new loop. The new loop will contain
1673    the vectorized instructions while the old loop will continue to run the
1674    scalar remainder.
1675
1676        [ ] <-- vector loop bypass (may consist of multiple blocks).
1677      /  |
1678     /   v
1679    |   [ ]     <-- vector pre header.
1680    |    |
1681    |    v
1682    |   [  ] \
1683    |   [  ]_|   <-- vector loop.
1684    |    |
1685     \   v
1686       >[ ]   <--- middle-block.
1687      /  |
1688     /   v
1689    |   [ ]     <--- new preheader.
1690    |    |
1691    |    v
1692    |   [ ] \
1693    |   [ ]_|   <-- old scalar loop to handle remainder.
1694     \   |
1695      \  v
1696       >[ ]     <-- exit block.
1697    ...
1698    */
1699
1700   BasicBlock *OldBasicBlock = OrigLoop->getHeader();
1701   BasicBlock *BypassBlock = OrigLoop->getLoopPreheader();
1702   BasicBlock *ExitBlock = OrigLoop->getExitBlock();
1703   assert(ExitBlock && "Must have an exit block");
1704
1705   // Some loops have a single integer induction variable, while other loops
1706   // don't. One example is c++ iterators that often have multiple pointer
1707   // induction variables. In the code below we also support a case where we
1708   // don't have a single induction variable.
1709   OldInduction = Legal->getInduction();
1710   Type *IdxTy = Legal->getWidestInductionType();
1711
1712   // Find the loop boundaries.
1713   const SCEV *ExitCount = SE->getBackedgeTakenCount(OrigLoop);
1714   assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
1715
1716   // The exit count might have the type of i64 while the phi is i32. This can
1717   // happen if we have an induction variable that is sign extended before the
1718   // compare. The only way that we get a backedge taken count is that the
1719   // induction variable was signed and as such will not overflow. In such a case
1720   // truncation is legal.
1721   if (ExitCount->getType()->getPrimitiveSizeInBits() >
1722       IdxTy->getPrimitiveSizeInBits())
1723     ExitCount = SE->getTruncateOrNoop(ExitCount, IdxTy);
1724
1725   ExitCount = SE->getNoopOrZeroExtend(ExitCount, IdxTy);
1726   // Get the total trip count from the count by adding 1.
1727   ExitCount = SE->getAddExpr(ExitCount,
1728                              SE->getConstant(ExitCount->getType(), 1));
1729
1730   // Expand the trip count and place the new instructions in the preheader.
1731   // Notice that the pre-header does not change, only the loop body.
1732   SCEVExpander Exp(*SE, "induction");
1733
1734   // Count holds the overall loop count (N).
1735   Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
1736                                    BypassBlock->getTerminator());
1737
1738   // The loop index does not have to start at Zero. Find the original start
1739   // value from the induction PHI node. If we don't have an induction variable
1740   // then we know that it starts at zero.
1741   Builder.SetInsertPoint(BypassBlock->getTerminator());
1742   Value *StartIdx = ExtendedIdx = OldInduction ?
1743     Builder.CreateZExt(OldInduction->getIncomingValueForBlock(BypassBlock),
1744                        IdxTy):
1745     ConstantInt::get(IdxTy, 0);
1746
1747   assert(BypassBlock && "Invalid loop structure");
1748   LoopBypassBlocks.push_back(BypassBlock);
1749
1750   // Split the single block loop into the two loop structure described above.
1751   BasicBlock *VectorPH =
1752   BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
1753   BasicBlock *VecBody =
1754   VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
1755   BasicBlock *MiddleBlock =
1756   VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
1757   BasicBlock *ScalarPH =
1758   MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
1759
1760   // Create and register the new vector loop.
1761   Loop* Lp = new Loop();
1762   Loop *ParentLoop = OrigLoop->getParentLoop();
1763
1764   // Insert the new loop into the loop nest and register the new basic blocks
1765   // before calling any utilities such as SCEV that require valid LoopInfo.
1766   if (ParentLoop) {
1767     ParentLoop->addChildLoop(Lp);
1768     ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase());
1769     ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase());
1770     ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase());
1771   } else {
1772     LI->addTopLevelLoop(Lp);
1773   }
1774   Lp->addBasicBlockToLoop(VecBody, LI->getBase());
1775
1776   // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
1777   // inside the loop.
1778   Builder.SetInsertPoint(VecBody->getFirstNonPHI());
1779
1780   // Generate the induction variable.
1781   setDebugLocFromInst(Builder, getDebugLocFromInstOrOperands(OldInduction));
1782   Induction = Builder.CreatePHI(IdxTy, 2, "index");
1783   // The loop step is equal to the vectorization factor (num of SIMD elements)
1784   // times the unroll factor (num of SIMD instructions).
1785   Constant *Step = ConstantInt::get(IdxTy, VF * UF);
1786
1787   // This is the IR builder that we use to add all of the logic for bypassing
1788   // the new vector loop.
1789   IRBuilder<> BypassBuilder(BypassBlock->getTerminator());
1790   setDebugLocFromInst(BypassBuilder,
1791                       getDebugLocFromInstOrOperands(OldInduction));
1792
1793   // We may need to extend the index in case there is a type mismatch.
1794   // We know that the count starts at zero and does not overflow.
1795   if (Count->getType() != IdxTy) {
1796     // The exit count can be of pointer type. Convert it to the correct
1797     // integer type.
1798     if (ExitCount->getType()->isPointerTy())
1799       Count = BypassBuilder.CreatePointerCast(Count, IdxTy, "ptrcnt.to.int");
1800     else
1801       Count = BypassBuilder.CreateZExtOrTrunc(Count, IdxTy, "cnt.cast");
1802   }
1803
1804   // Add the start index to the loop count to get the new end index.
1805   Value *IdxEnd = BypassBuilder.CreateAdd(Count, StartIdx, "end.idx");
1806
1807   // Now we need to generate the expression for N - (N % VF), which is
1808   // the part that the vectorized body will execute.
1809   Value *R = BypassBuilder.CreateURem(Count, Step, "n.mod.vf");
1810   Value *CountRoundDown = BypassBuilder.CreateSub(Count, R, "n.vec");
1811   Value *IdxEndRoundDown = BypassBuilder.CreateAdd(CountRoundDown, StartIdx,
1812                                                      "end.idx.rnd.down");
1813
1814   // Now, compare the new count to zero. If it is zero skip the vector loop and
1815   // jump to the scalar loop.
1816   Value *Cmp = BypassBuilder.CreateICmpEQ(IdxEndRoundDown, StartIdx,
1817                                           "cmp.zero");
1818
1819   BasicBlock *LastBypassBlock = BypassBlock;
1820
1821   // Generate the code to check that the strides we assumed to be one are really
1822   // one. We want the new basic block to start at the first instruction in a
1823   // sequence of instructions that form a check.
1824   Instruction *StrideCheck;
1825   Instruction *FirstCheckInst;
1826   tie(FirstCheckInst, StrideCheck) =
1827       addStrideCheck(BypassBlock->getTerminator());
1828   if (StrideCheck) {
1829     // Create a new block containing the stride check.
1830     BasicBlock *CheckBlock =
1831         BypassBlock->splitBasicBlock(FirstCheckInst, "vector.stridecheck");
1832     if (ParentLoop)
1833       ParentLoop->addBasicBlockToLoop(CheckBlock, LI->getBase());
1834     LoopBypassBlocks.push_back(CheckBlock);
1835
1836     // Replace the branch into the memory check block with a conditional branch
1837     // for the "few elements case".
1838     Instruction *OldTerm = BypassBlock->getTerminator();
1839     BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
1840     OldTerm->eraseFromParent();
1841
1842     Cmp = StrideCheck;
1843     LastBypassBlock = CheckBlock;
1844   }
1845
1846   // Generate the code that checks in runtime if arrays overlap. We put the
1847   // checks into a separate block to make the more common case of few elements
1848   // faster.
1849   Instruction *MemRuntimeCheck;
1850   tie(FirstCheckInst, MemRuntimeCheck) =
1851       addRuntimeCheck(LastBypassBlock->getTerminator());
1852   if (MemRuntimeCheck) {
1853     // Create a new block containing the memory check.
1854     BasicBlock *CheckBlock =
1855         LastBypassBlock->splitBasicBlock(MemRuntimeCheck, "vector.memcheck");
1856     if (ParentLoop)
1857       ParentLoop->addBasicBlockToLoop(CheckBlock, LI->getBase());
1858     LoopBypassBlocks.push_back(CheckBlock);
1859
1860     // Replace the branch into the memory check block with a conditional branch
1861     // for the "few elements case".
1862     Instruction *OldTerm = LastBypassBlock->getTerminator();
1863     BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
1864     OldTerm->eraseFromParent();
1865
1866     Cmp = MemRuntimeCheck;
1867     LastBypassBlock = CheckBlock;
1868   }
1869
1870   LastBypassBlock->getTerminator()->eraseFromParent();
1871   BranchInst::Create(MiddleBlock, VectorPH, Cmp,
1872                      LastBypassBlock);
1873
1874   // We are going to resume the execution of the scalar loop.
1875   // Go over all of the induction variables that we found and fix the
1876   // PHIs that are left in the scalar version of the loop.
1877   // The starting values of PHI nodes depend on the counter of the last
1878   // iteration in the vectorized loop.
1879   // If we come from a bypass edge then we need to start from the original
1880   // start value.
1881
1882   // This variable saves the new starting index for the scalar loop.
1883   PHINode *ResumeIndex = 0;
1884   LoopVectorizationLegality::InductionList::iterator I, E;
1885   LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
1886   // Set builder to point to last bypass block.
1887   BypassBuilder.SetInsertPoint(LoopBypassBlocks.back()->getTerminator());
1888   for (I = List->begin(), E = List->end(); I != E; ++I) {
1889     PHINode *OrigPhi = I->first;
1890     LoopVectorizationLegality::InductionInfo II = I->second;
1891
1892     Type *ResumeValTy = (OrigPhi == OldInduction) ? IdxTy : OrigPhi->getType();
1893     PHINode *ResumeVal = PHINode::Create(ResumeValTy, 2, "resume.val",
1894                                          MiddleBlock->getTerminator());
1895     // We might have extended the type of the induction variable but we need a
1896     // truncated version for the scalar loop.
1897     PHINode *TruncResumeVal = (OrigPhi == OldInduction) ?
1898       PHINode::Create(OrigPhi->getType(), 2, "trunc.resume.val",
1899                       MiddleBlock->getTerminator()) : 0;
1900
1901     Value *EndValue = 0;
1902     switch (II.IK) {
1903     case LoopVectorizationLegality::IK_NoInduction:
1904       llvm_unreachable("Unknown induction");
1905     case LoopVectorizationLegality::IK_IntInduction: {
1906       // Handle the integer induction counter.
1907       assert(OrigPhi->getType()->isIntegerTy() && "Invalid type");
1908
1909       // We have the canonical induction variable.
1910       if (OrigPhi == OldInduction) {
1911         // Create a truncated version of the resume value for the scalar loop,
1912         // we might have promoted the type to a larger width.
1913         EndValue =
1914           BypassBuilder.CreateTrunc(IdxEndRoundDown, OrigPhi->getType());
1915         // The new PHI merges the original incoming value, in case of a bypass,
1916         // or the value at the end of the vectorized loop.
1917         for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
1918           TruncResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
1919         TruncResumeVal->addIncoming(EndValue, VecBody);
1920
1921         // We know what the end value is.
1922         EndValue = IdxEndRoundDown;
1923         // We also know which PHI node holds it.
1924         ResumeIndex = ResumeVal;
1925         break;
1926       }
1927
1928       // Not the canonical induction variable - add the vector loop count to the
1929       // start value.
1930       Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown,
1931                                                    II.StartValue->getType(),
1932                                                    "cast.crd");
1933       EndValue = BypassBuilder.CreateAdd(CRD, II.StartValue , "ind.end");
1934       break;
1935     }
1936     case LoopVectorizationLegality::IK_ReverseIntInduction: {
1937       // Convert the CountRoundDown variable to the PHI size.
1938       Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown,
1939                                                    II.StartValue->getType(),
1940                                                    "cast.crd");
1941       // Handle reverse integer induction counter.
1942       EndValue = BypassBuilder.CreateSub(II.StartValue, CRD, "rev.ind.end");
1943       break;
1944     }
1945     case LoopVectorizationLegality::IK_PtrInduction: {
1946       // For pointer induction variables, calculate the offset using
1947       // the end index.
1948       EndValue = BypassBuilder.CreateGEP(II.StartValue, CountRoundDown,
1949                                          "ptr.ind.end");
1950       break;
1951     }
1952     case LoopVectorizationLegality::IK_ReversePtrInduction: {
1953       // The value at the end of the loop for the reverse pointer is calculated
1954       // by creating a GEP with a negative index starting from the start value.
1955       Value *Zero = ConstantInt::get(CountRoundDown->getType(), 0);
1956       Value *NegIdx = BypassBuilder.CreateSub(Zero, CountRoundDown,
1957                                               "rev.ind.end");
1958       EndValue = BypassBuilder.CreateGEP(II.StartValue, NegIdx,
1959                                          "rev.ptr.ind.end");
1960       break;
1961     }
1962     }// end of case
1963
1964     // The new PHI merges the original incoming value, in case of a bypass,
1965     // or the value at the end of the vectorized loop.
1966     for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I) {
1967       if (OrigPhi == OldInduction)
1968         ResumeVal->addIncoming(StartIdx, LoopBypassBlocks[I]);
1969       else
1970         ResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
1971     }
1972     ResumeVal->addIncoming(EndValue, VecBody);
1973
1974     // Fix the scalar body counter (PHI node).
1975     unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
1976     // The old inductions phi node in the scalar body needs the truncated value.
1977     if (OrigPhi == OldInduction)
1978       OrigPhi->setIncomingValue(BlockIdx, TruncResumeVal);
1979     else
1980       OrigPhi->setIncomingValue(BlockIdx, ResumeVal);
1981   }
1982
1983   // If we are generating a new induction variable then we also need to
1984   // generate the code that calculates the exit value. This value is not
1985   // simply the end of the counter because we may skip the vectorized body
1986   // in case of a runtime check.
1987   if (!OldInduction){
1988     assert(!ResumeIndex && "Unexpected resume value found");
1989     ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val",
1990                                   MiddleBlock->getTerminator());
1991     for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
1992       ResumeIndex->addIncoming(StartIdx, LoopBypassBlocks[I]);
1993     ResumeIndex->addIncoming(IdxEndRoundDown, VecBody);
1994   }
1995
1996   // Make sure that we found the index where scalar loop needs to continue.
1997   assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() &&
1998          "Invalid resume Index");
1999
2000   // Add a check in the middle block to see if we have completed
2001   // all of the iterations in the first vector loop.
2002   // If (N - N%VF) == N, then we *don't* need to run the remainder.
2003   Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd,
2004                                 ResumeIndex, "cmp.n",
2005                                 MiddleBlock->getTerminator());
2006
2007   BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
2008   // Remove the old terminator.
2009   MiddleBlock->getTerminator()->eraseFromParent();
2010
2011   // Create i+1 and fill the PHINode.
2012   Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
2013   Induction->addIncoming(StartIdx, VectorPH);
2014   Induction->addIncoming(NextIdx, VecBody);
2015   // Create the compare.
2016   Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown);
2017   Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
2018
2019   // Now we have two terminators. Remove the old one from the block.
2020   VecBody->getTerminator()->eraseFromParent();
2021
2022   // Get ready to start creating new instructions into the vectorized body.
2023   Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
2024
2025   // Save the state.
2026   LoopVectorPreHeader = VectorPH;
2027   LoopScalarPreHeader = ScalarPH;
2028   LoopMiddleBlock = MiddleBlock;
2029   LoopExitBlock = ExitBlock;
2030   LoopVectorBody = VecBody;
2031   LoopScalarBody = OldBasicBlock;
2032
2033   LoopVectorizeHints Hints(Lp, true);
2034   Hints.setAlreadyVectorized(Lp);
2035 }
2036
2037 /// This function returns the identity element (or neutral element) for
2038 /// the operation K.
2039 Constant*
2040 LoopVectorizationLegality::getReductionIdentity(ReductionKind K, Type *Tp) {
2041   switch (K) {
2042   case RK_IntegerXor:
2043   case RK_IntegerAdd:
2044   case RK_IntegerOr:
2045     // Adding, Xoring, Oring zero to a number does not change it.
2046     return ConstantInt::get(Tp, 0);
2047   case RK_IntegerMult:
2048     // Multiplying a number by 1 does not change it.
2049     return ConstantInt::get(Tp, 1);
2050   case RK_IntegerAnd:
2051     // AND-ing a number with an all-1 value does not change it.
2052     return ConstantInt::get(Tp, -1, true);
2053   case  RK_FloatMult:
2054     // Multiplying a number by 1 does not change it.
2055     return ConstantFP::get(Tp, 1.0L);
2056   case  RK_FloatAdd:
2057     // Adding zero to a number does not change it.
2058     return ConstantFP::get(Tp, 0.0L);
2059   default:
2060     llvm_unreachable("Unknown reduction kind");
2061   }
2062 }
2063
2064 static Intrinsic::ID checkUnaryFloatSignature(const CallInst &I,
2065                                               Intrinsic::ID ValidIntrinsicID) {
2066   if (I.getNumArgOperands() != 1 ||
2067       !I.getArgOperand(0)->getType()->isFloatingPointTy() ||
2068       I.getType() != I.getArgOperand(0)->getType() ||
2069       !I.onlyReadsMemory())
2070     return Intrinsic::not_intrinsic;
2071
2072   return ValidIntrinsicID;
2073 }
2074
2075 static Intrinsic::ID checkBinaryFloatSignature(const CallInst &I,
2076                                                Intrinsic::ID ValidIntrinsicID) {
2077   if (I.getNumArgOperands() != 2 ||
2078       !I.getArgOperand(0)->getType()->isFloatingPointTy() ||
2079       !I.getArgOperand(1)->getType()->isFloatingPointTy() ||
2080       I.getType() != I.getArgOperand(0)->getType() ||
2081       I.getType() != I.getArgOperand(1)->getType() ||
2082       !I.onlyReadsMemory())
2083     return Intrinsic::not_intrinsic;
2084
2085   return ValidIntrinsicID;
2086 }
2087
2088
2089 static Intrinsic::ID
2090 getIntrinsicIDForCall(CallInst *CI, const TargetLibraryInfo *TLI) {
2091   // If we have an intrinsic call, check if it is trivially vectorizable.
2092   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
2093     switch (II->getIntrinsicID()) {
2094     case Intrinsic::sqrt:
2095     case Intrinsic::sin:
2096     case Intrinsic::cos:
2097     case Intrinsic::exp:
2098     case Intrinsic::exp2:
2099     case Intrinsic::log:
2100     case Intrinsic::log10:
2101     case Intrinsic::log2:
2102     case Intrinsic::fabs:
2103     case Intrinsic::copysign:
2104     case Intrinsic::floor:
2105     case Intrinsic::ceil:
2106     case Intrinsic::trunc:
2107     case Intrinsic::rint:
2108     case Intrinsic::nearbyint:
2109     case Intrinsic::round:
2110     case Intrinsic::pow:
2111     case Intrinsic::fma:
2112     case Intrinsic::fmuladd:
2113     case Intrinsic::lifetime_start:
2114     case Intrinsic::lifetime_end:
2115       return II->getIntrinsicID();
2116     default:
2117       return Intrinsic::not_intrinsic;
2118     }
2119   }
2120
2121   if (!TLI)
2122     return Intrinsic::not_intrinsic;
2123
2124   LibFunc::Func Func;
2125   Function *F = CI->getCalledFunction();
2126   // We're going to make assumptions on the semantics of the functions, check
2127   // that the target knows that it's available in this environment and it does
2128   // not have local linkage.
2129   if (!F || F->hasLocalLinkage() || !TLI->getLibFunc(F->getName(), Func))
2130     return Intrinsic::not_intrinsic;
2131
2132   // Otherwise check if we have a call to a function that can be turned into a
2133   // vector intrinsic.
2134   switch (Func) {
2135   default:
2136     break;
2137   case LibFunc::sin:
2138   case LibFunc::sinf:
2139   case LibFunc::sinl:
2140     return checkUnaryFloatSignature(*CI, Intrinsic::sin);
2141   case LibFunc::cos:
2142   case LibFunc::cosf:
2143   case LibFunc::cosl:
2144     return checkUnaryFloatSignature(*CI, Intrinsic::cos);
2145   case LibFunc::exp:
2146   case LibFunc::expf:
2147   case LibFunc::expl:
2148     return checkUnaryFloatSignature(*CI, Intrinsic::exp);
2149   case LibFunc::exp2:
2150   case LibFunc::exp2f:
2151   case LibFunc::exp2l:
2152     return checkUnaryFloatSignature(*CI, Intrinsic::exp2);
2153   case LibFunc::log:
2154   case LibFunc::logf:
2155   case LibFunc::logl:
2156     return checkUnaryFloatSignature(*CI, Intrinsic::log);
2157   case LibFunc::log10:
2158   case LibFunc::log10f:
2159   case LibFunc::log10l:
2160     return checkUnaryFloatSignature(*CI, Intrinsic::log10);
2161   case LibFunc::log2:
2162   case LibFunc::log2f:
2163   case LibFunc::log2l:
2164     return checkUnaryFloatSignature(*CI, Intrinsic::log2);
2165   case LibFunc::fabs:
2166   case LibFunc::fabsf:
2167   case LibFunc::fabsl:
2168     return checkUnaryFloatSignature(*CI, Intrinsic::fabs);
2169   case LibFunc::copysign:
2170   case LibFunc::copysignf:
2171   case LibFunc::copysignl:
2172     return checkBinaryFloatSignature(*CI, Intrinsic::copysign);
2173   case LibFunc::floor:
2174   case LibFunc::floorf:
2175   case LibFunc::floorl:
2176     return checkUnaryFloatSignature(*CI, Intrinsic::floor);
2177   case LibFunc::ceil:
2178   case LibFunc::ceilf:
2179   case LibFunc::ceill:
2180     return checkUnaryFloatSignature(*CI, Intrinsic::ceil);
2181   case LibFunc::trunc:
2182   case LibFunc::truncf:
2183   case LibFunc::truncl:
2184     return checkUnaryFloatSignature(*CI, Intrinsic::trunc);
2185   case LibFunc::rint:
2186   case LibFunc::rintf:
2187   case LibFunc::rintl:
2188     return checkUnaryFloatSignature(*CI, Intrinsic::rint);
2189   case LibFunc::nearbyint:
2190   case LibFunc::nearbyintf:
2191   case LibFunc::nearbyintl:
2192     return checkUnaryFloatSignature(*CI, Intrinsic::nearbyint);
2193   case LibFunc::round:
2194   case LibFunc::roundf:
2195   case LibFunc::roundl:
2196     return checkUnaryFloatSignature(*CI, Intrinsic::round);
2197   case LibFunc::pow:
2198   case LibFunc::powf:
2199   case LibFunc::powl:
2200     return checkBinaryFloatSignature(*CI, Intrinsic::pow);
2201   }
2202
2203   return Intrinsic::not_intrinsic;
2204 }
2205
2206 /// This function translates the reduction kind to an LLVM binary operator.
2207 static unsigned
2208 getReductionBinOp(LoopVectorizationLegality::ReductionKind Kind) {
2209   switch (Kind) {
2210     case LoopVectorizationLegality::RK_IntegerAdd:
2211       return Instruction::Add;
2212     case LoopVectorizationLegality::RK_IntegerMult:
2213       return Instruction::Mul;
2214     case LoopVectorizationLegality::RK_IntegerOr:
2215       return Instruction::Or;
2216     case LoopVectorizationLegality::RK_IntegerAnd:
2217       return Instruction::And;
2218     case LoopVectorizationLegality::RK_IntegerXor:
2219       return Instruction::Xor;
2220     case LoopVectorizationLegality::RK_FloatMult:
2221       return Instruction::FMul;
2222     case LoopVectorizationLegality::RK_FloatAdd:
2223       return Instruction::FAdd;
2224     case LoopVectorizationLegality::RK_IntegerMinMax:
2225       return Instruction::ICmp;
2226     case LoopVectorizationLegality::RK_FloatMinMax:
2227       return Instruction::FCmp;
2228     default:
2229       llvm_unreachable("Unknown reduction operation");
2230   }
2231 }
2232
2233 Value *createMinMaxOp(IRBuilder<> &Builder,
2234                       LoopVectorizationLegality::MinMaxReductionKind RK,
2235                       Value *Left,
2236                       Value *Right) {
2237   CmpInst::Predicate P = CmpInst::ICMP_NE;
2238   switch (RK) {
2239   default:
2240     llvm_unreachable("Unknown min/max reduction kind");
2241   case LoopVectorizationLegality::MRK_UIntMin:
2242     P = CmpInst::ICMP_ULT;
2243     break;
2244   case LoopVectorizationLegality::MRK_UIntMax:
2245     P = CmpInst::ICMP_UGT;
2246     break;
2247   case LoopVectorizationLegality::MRK_SIntMin:
2248     P = CmpInst::ICMP_SLT;
2249     break;
2250   case LoopVectorizationLegality::MRK_SIntMax:
2251     P = CmpInst::ICMP_SGT;
2252     break;
2253   case LoopVectorizationLegality::MRK_FloatMin:
2254     P = CmpInst::FCMP_OLT;
2255     break;
2256   case LoopVectorizationLegality::MRK_FloatMax:
2257     P = CmpInst::FCMP_OGT;
2258     break;
2259   }
2260
2261   Value *Cmp;
2262   if (RK == LoopVectorizationLegality::MRK_FloatMin ||
2263       RK == LoopVectorizationLegality::MRK_FloatMax)
2264     Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp");
2265   else
2266     Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp");
2267
2268   Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
2269   return Select;
2270 }
2271
2272 namespace {
2273 struct CSEDenseMapInfo {
2274   static bool canHandle(Instruction *I) {
2275     return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
2276            isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
2277   }
2278   static inline Instruction *getEmptyKey() {
2279     return DenseMapInfo<Instruction *>::getEmptyKey();
2280   }
2281   static inline Instruction *getTombstoneKey() {
2282     return DenseMapInfo<Instruction *>::getTombstoneKey();
2283   }
2284   static unsigned getHashValue(Instruction *I) {
2285     assert(canHandle(I) && "Unknown instruction!");
2286     return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
2287                                                            I->value_op_end()));
2288   }
2289   static bool isEqual(Instruction *LHS, Instruction *RHS) {
2290     if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
2291         LHS == getTombstoneKey() || RHS == getTombstoneKey())
2292       return LHS == RHS;
2293     return LHS->isIdenticalTo(RHS);
2294   }
2295 };
2296 }
2297
2298 ///\brief Perform cse of induction variable instructions.
2299 static void cse(BasicBlock *BB) {
2300   // Perform simple cse.
2301   SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
2302   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
2303     Instruction *In = I++;
2304
2305     if (!CSEDenseMapInfo::canHandle(In))
2306       continue;
2307
2308     // Check if we can replace this instruction with any of the
2309     // visited instructions.
2310     if (Instruction *V = CSEMap.lookup(In)) {
2311       In->replaceAllUsesWith(V);
2312       In->eraseFromParent();
2313       continue;
2314     }
2315
2316     CSEMap[In] = In;
2317   }
2318 }
2319
2320 void InnerLoopVectorizer::vectorizeLoop() {
2321   //===------------------------------------------------===//
2322   //
2323   // Notice: any optimization or new instruction that go
2324   // into the code below should be also be implemented in
2325   // the cost-model.
2326   //
2327   //===------------------------------------------------===//
2328   Constant *Zero = Builder.getInt32(0);
2329
2330   // In order to support reduction variables we need to be able to vectorize
2331   // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
2332   // stages. First, we create a new vector PHI node with no incoming edges.
2333   // We use this value when we vectorize all of the instructions that use the
2334   // PHI. Next, after all of the instructions in the block are complete we
2335   // add the new incoming edges to the PHI. At this point all of the
2336   // instructions in the basic block are vectorized, so we can use them to
2337   // construct the PHI.
2338   PhiVector RdxPHIsToFix;
2339
2340   // Scan the loop in a topological order to ensure that defs are vectorized
2341   // before users.
2342   LoopBlocksDFS DFS(OrigLoop);
2343   DFS.perform(LI);
2344
2345   // Vectorize all of the blocks in the original loop.
2346   for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
2347        be = DFS.endRPO(); bb != be; ++bb)
2348     vectorizeBlockInLoop(*bb, &RdxPHIsToFix);
2349
2350   // At this point every instruction in the original loop is widened to
2351   // a vector form. We are almost done. Now, we need to fix the PHI nodes
2352   // that we vectorized. The PHI nodes are currently empty because we did
2353   // not want to introduce cycles. Notice that the remaining PHI nodes
2354   // that we need to fix are reduction variables.
2355
2356   // Create the 'reduced' values for each of the induction vars.
2357   // The reduced values are the vector values that we scalarize and combine
2358   // after the loop is finished.
2359   for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
2360        it != e; ++it) {
2361     PHINode *RdxPhi = *it;
2362     assert(RdxPhi && "Unable to recover vectorized PHI");
2363
2364     // Find the reduction variable descriptor.
2365     assert(Legal->getReductionVars()->count(RdxPhi) &&
2366            "Unable to find the reduction variable");
2367     LoopVectorizationLegality::ReductionDescriptor RdxDesc =
2368     (*Legal->getReductionVars())[RdxPhi];
2369
2370     setDebugLocFromInst(Builder, RdxDesc.StartValue);
2371
2372     // We need to generate a reduction vector from the incoming scalar.
2373     // To do so, we need to generate the 'identity' vector and overide
2374     // one of the elements with the incoming scalar reduction. We need
2375     // to do it in the vector-loop preheader.
2376     Builder.SetInsertPoint(LoopBypassBlocks.front()->getTerminator());
2377
2378     // This is the vector-clone of the value that leaves the loop.
2379     VectorParts &VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
2380     Type *VecTy = VectorExit[0]->getType();
2381
2382     // Find the reduction identity variable. Zero for addition, or, xor,
2383     // one for multiplication, -1 for And.
2384     Value *Identity;
2385     Value *VectorStart;
2386     if (RdxDesc.Kind == LoopVectorizationLegality::RK_IntegerMinMax ||
2387         RdxDesc.Kind == LoopVectorizationLegality::RK_FloatMinMax) {
2388       // MinMax reduction have the start value as their identify.
2389       if (VF == 1) {
2390         VectorStart = Identity = RdxDesc.StartValue;
2391       } else {
2392         VectorStart = Identity = Builder.CreateVectorSplat(VF,
2393                                                            RdxDesc.StartValue,
2394                                                            "minmax.ident");
2395       }
2396     } else {
2397       // Handle other reduction kinds:
2398       Constant *Iden =
2399       LoopVectorizationLegality::getReductionIdentity(RdxDesc.Kind,
2400                                                       VecTy->getScalarType());
2401       if (VF == 1) {
2402         Identity = Iden;
2403         // This vector is the Identity vector where the first element is the
2404         // incoming scalar reduction.
2405         VectorStart = RdxDesc.StartValue;
2406       } else {
2407         Identity = ConstantVector::getSplat(VF, Iden);
2408
2409         // This vector is the Identity vector where the first element is the
2410         // incoming scalar reduction.
2411         VectorStart = Builder.CreateInsertElement(Identity,
2412                                                   RdxDesc.StartValue, Zero);
2413       }
2414     }
2415
2416     // Fix the vector-loop phi.
2417     // We created the induction variable so we know that the
2418     // preheader is the first entry.
2419     BasicBlock *VecPreheader = Induction->getIncomingBlock(0);
2420
2421     // Reductions do not have to start at zero. They can start with
2422     // any loop invariant values.
2423     VectorParts &VecRdxPhi = WidenMap.get(RdxPhi);
2424     BasicBlock *Latch = OrigLoop->getLoopLatch();
2425     Value *LoopVal = RdxPhi->getIncomingValueForBlock(Latch);
2426     VectorParts &Val = getVectorValue(LoopVal);
2427     for (unsigned part = 0; part < UF; ++part) {
2428       // Make sure to add the reduction stat value only to the
2429       // first unroll part.
2430       Value *StartVal = (part == 0) ? VectorStart : Identity;
2431       cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal, VecPreheader);
2432       cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part], LoopVectorBody);
2433     }
2434
2435     // Before each round, move the insertion point right between
2436     // the PHIs and the values we are going to write.
2437     // This allows us to write both PHINodes and the extractelement
2438     // instructions.
2439     Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
2440
2441     VectorParts RdxParts;
2442     setDebugLocFromInst(Builder, RdxDesc.LoopExitInstr);
2443     for (unsigned part = 0; part < UF; ++part) {
2444       // This PHINode contains the vectorized reduction variable, or
2445       // the initial value vector, if we bypass the vector loop.
2446       VectorParts &RdxExitVal = getVectorValue(RdxDesc.LoopExitInstr);
2447       PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
2448       Value *StartVal = (part == 0) ? VectorStart : Identity;
2449       for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
2450         NewPhi->addIncoming(StartVal, LoopBypassBlocks[I]);
2451       NewPhi->addIncoming(RdxExitVal[part], LoopVectorBody);
2452       RdxParts.push_back(NewPhi);
2453     }
2454
2455     // Reduce all of the unrolled parts into a single vector.
2456     Value *ReducedPartRdx = RdxParts[0];
2457     unsigned Op = getReductionBinOp(RdxDesc.Kind);
2458     setDebugLocFromInst(Builder, ReducedPartRdx);
2459     for (unsigned part = 1; part < UF; ++part) {
2460       if (Op != Instruction::ICmp && Op != Instruction::FCmp)
2461         ReducedPartRdx = Builder.CreateBinOp((Instruction::BinaryOps)Op,
2462                                              RdxParts[part], ReducedPartRdx,
2463                                              "bin.rdx");
2464       else
2465         ReducedPartRdx = createMinMaxOp(Builder, RdxDesc.MinMaxKind,
2466                                         ReducedPartRdx, RdxParts[part]);
2467     }
2468
2469     if (VF > 1) {
2470       // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
2471       // and vector ops, reducing the set of values being computed by half each
2472       // round.
2473       assert(isPowerOf2_32(VF) &&
2474              "Reduction emission only supported for pow2 vectors!");
2475       Value *TmpVec = ReducedPartRdx;
2476       SmallVector<Constant*, 32> ShuffleMask(VF, 0);
2477       for (unsigned i = VF; i != 1; i >>= 1) {
2478         // Move the upper half of the vector to the lower half.
2479         for (unsigned j = 0; j != i/2; ++j)
2480           ShuffleMask[j] = Builder.getInt32(i/2 + j);
2481
2482         // Fill the rest of the mask with undef.
2483         std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
2484                   UndefValue::get(Builder.getInt32Ty()));
2485
2486         Value *Shuf =
2487         Builder.CreateShuffleVector(TmpVec,
2488                                     UndefValue::get(TmpVec->getType()),
2489                                     ConstantVector::get(ShuffleMask),
2490                                     "rdx.shuf");
2491
2492         if (Op != Instruction::ICmp && Op != Instruction::FCmp)
2493           TmpVec = Builder.CreateBinOp((Instruction::BinaryOps)Op, TmpVec, Shuf,
2494                                        "bin.rdx");
2495         else
2496           TmpVec = createMinMaxOp(Builder, RdxDesc.MinMaxKind, TmpVec, Shuf);
2497       }
2498
2499       // The result is in the first element of the vector.
2500       ReducedPartRdx = Builder.CreateExtractElement(TmpVec,
2501                                                     Builder.getInt32(0));
2502     }
2503
2504     // Now, we need to fix the users of the reduction variable
2505     // inside and outside of the scalar remainder loop.
2506     // We know that the loop is in LCSSA form. We need to update the
2507     // PHI nodes in the exit blocks.
2508     for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
2509          LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
2510       PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
2511       if (!LCSSAPhi) break;
2512
2513       // All PHINodes need to have a single entry edge, or two if
2514       // we already fixed them.
2515       assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
2516
2517       // We found our reduction value exit-PHI. Update it with the
2518       // incoming bypass edge.
2519       if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
2520         // Add an edge coming from the bypass.
2521         LCSSAPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
2522         break;
2523       }
2524     }// end of the LCSSA phi scan.
2525
2526     // Fix the scalar loop reduction variable with the incoming reduction sum
2527     // from the vector body and from the backedge value.
2528     int IncomingEdgeBlockIdx =
2529     (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
2530     assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
2531     // Pick the other block.
2532     int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
2533     (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, ReducedPartRdx);
2534     (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
2535   }// end of for each redux variable.
2536
2537   fixLCSSAPHIs();
2538
2539   // Remove redundant induction instructions.
2540   cse(LoopVectorBody);
2541 }
2542
2543 void InnerLoopVectorizer::fixLCSSAPHIs() {
2544   for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
2545        LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
2546     PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
2547     if (!LCSSAPhi) break;
2548     if (LCSSAPhi->getNumIncomingValues() == 1)
2549       LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
2550                             LoopMiddleBlock);
2551   }
2552
2553
2554 InnerLoopVectorizer::VectorParts
2555 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
2556   assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
2557          "Invalid edge");
2558
2559   // Look for cached value.
2560   std::pair<BasicBlock*, BasicBlock*> Edge(Src, Dst);
2561   EdgeMaskCache::iterator ECEntryIt = MaskCache.find(Edge);
2562   if (ECEntryIt != MaskCache.end())
2563     return ECEntryIt->second;
2564
2565   VectorParts SrcMask = createBlockInMask(Src);
2566
2567   // The terminator has to be a branch inst!
2568   BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
2569   assert(BI && "Unexpected terminator found");
2570
2571   if (BI->isConditional()) {
2572     VectorParts EdgeMask = getVectorValue(BI->getCondition());
2573
2574     if (BI->getSuccessor(0) != Dst)
2575       for (unsigned part = 0; part < UF; ++part)
2576         EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
2577
2578     for (unsigned part = 0; part < UF; ++part)
2579       EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
2580
2581     MaskCache[Edge] = EdgeMask;
2582     return EdgeMask;
2583   }
2584
2585   MaskCache[Edge] = SrcMask;
2586   return SrcMask;
2587 }
2588
2589 InnerLoopVectorizer::VectorParts
2590 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
2591   assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
2592
2593   // Loop incoming mask is all-one.
2594   if (OrigLoop->getHeader() == BB) {
2595     Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
2596     return getVectorValue(C);
2597   }
2598
2599   // This is the block mask. We OR all incoming edges, and with zero.
2600   Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
2601   VectorParts BlockMask = getVectorValue(Zero);
2602
2603   // For each pred:
2604   for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
2605     VectorParts EM = createEdgeMask(*it, BB);
2606     for (unsigned part = 0; part < UF; ++part)
2607       BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
2608   }
2609
2610   return BlockMask;
2611 }
2612
2613 void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN,
2614                                               InnerLoopVectorizer::VectorParts &Entry,
2615                                               unsigned UF, unsigned VF, PhiVector *PV) {
2616   PHINode* P = cast<PHINode>(PN);
2617   // Handle reduction variables:
2618   if (Legal->getReductionVars()->count(P)) {
2619     for (unsigned part = 0; part < UF; ++part) {
2620       // This is phase one of vectorizing PHIs.
2621       Type *VecTy = (VF == 1) ? PN->getType() :
2622       VectorType::get(PN->getType(), VF);
2623       Entry[part] = PHINode::Create(VecTy, 2, "vec.phi",
2624                                     LoopVectorBody-> getFirstInsertionPt());
2625     }
2626     PV->push_back(P);
2627     return;
2628   }
2629
2630   setDebugLocFromInst(Builder, P);
2631   // Check for PHI nodes that are lowered to vector selects.
2632   if (P->getParent() != OrigLoop->getHeader()) {
2633     // We know that all PHIs in non-header blocks are converted into
2634     // selects, so we don't have to worry about the insertion order and we
2635     // can just use the builder.
2636     // At this point we generate the predication tree. There may be
2637     // duplications since this is a simple recursive scan, but future
2638     // optimizations will clean it up.
2639
2640     unsigned NumIncoming = P->getNumIncomingValues();
2641
2642     // Generate a sequence of selects of the form:
2643     // SELECT(Mask3, In3,
2644     //      SELECT(Mask2, In2,
2645     //                   ( ...)))
2646     for (unsigned In = 0; In < NumIncoming; In++) {
2647       VectorParts Cond = createEdgeMask(P->getIncomingBlock(In),
2648                                         P->getParent());
2649       VectorParts &In0 = getVectorValue(P->getIncomingValue(In));
2650
2651       for (unsigned part = 0; part < UF; ++part) {
2652         // We might have single edge PHIs (blocks) - use an identity
2653         // 'select' for the first PHI operand.
2654         if (In == 0)
2655           Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
2656                                              In0[part]);
2657         else
2658           // Select between the current value and the previous incoming edge
2659           // based on the incoming mask.
2660           Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
2661                                              Entry[part], "predphi");
2662       }
2663     }
2664     return;
2665   }
2666
2667   // This PHINode must be an induction variable.
2668   // Make sure that we know about it.
2669   assert(Legal->getInductionVars()->count(P) &&
2670          "Not an induction variable");
2671
2672   LoopVectorizationLegality::InductionInfo II =
2673   Legal->getInductionVars()->lookup(P);
2674
2675   switch (II.IK) {
2676     case LoopVectorizationLegality::IK_NoInduction:
2677       llvm_unreachable("Unknown induction");
2678     case LoopVectorizationLegality::IK_IntInduction: {
2679       assert(P->getType() == II.StartValue->getType() && "Types must match");
2680       Type *PhiTy = P->getType();
2681       Value *Broadcasted;
2682       if (P == OldInduction) {
2683         // Handle the canonical induction variable. We might have had to
2684         // extend the type.
2685         Broadcasted = Builder.CreateTrunc(Induction, PhiTy);
2686       } else {
2687         // Handle other induction variables that are now based on the
2688         // canonical one.
2689         Value *NormalizedIdx = Builder.CreateSub(Induction, ExtendedIdx,
2690                                                  "normalized.idx");
2691         NormalizedIdx = Builder.CreateSExtOrTrunc(NormalizedIdx, PhiTy);
2692         Broadcasted = Builder.CreateAdd(II.StartValue, NormalizedIdx,
2693                                         "offset.idx");
2694       }
2695       Broadcasted = getBroadcastInstrs(Broadcasted);
2696       // After broadcasting the induction variable we need to make the vector
2697       // consecutive by adding 0, 1, 2, etc.
2698       for (unsigned part = 0; part < UF; ++part)
2699         Entry[part] = getConsecutiveVector(Broadcasted, VF * part, false);
2700       return;
2701     }
2702     case LoopVectorizationLegality::IK_ReverseIntInduction:
2703     case LoopVectorizationLegality::IK_PtrInduction:
2704     case LoopVectorizationLegality::IK_ReversePtrInduction:
2705       // Handle reverse integer and pointer inductions.
2706       Value *StartIdx = ExtendedIdx;
2707       // This is the normalized GEP that starts counting at zero.
2708       Value *NormalizedIdx = Builder.CreateSub(Induction, StartIdx,
2709                                                "normalized.idx");
2710
2711       // Handle the reverse integer induction variable case.
2712       if (LoopVectorizationLegality::IK_ReverseIntInduction == II.IK) {
2713         IntegerType *DstTy = cast<IntegerType>(II.StartValue->getType());
2714         Value *CNI = Builder.CreateSExtOrTrunc(NormalizedIdx, DstTy,
2715                                                "resize.norm.idx");
2716         Value *ReverseInd  = Builder.CreateSub(II.StartValue, CNI,
2717                                                "reverse.idx");
2718
2719         // This is a new value so do not hoist it out.
2720         Value *Broadcasted = getBroadcastInstrs(ReverseInd);
2721         // After broadcasting the induction variable we need to make the
2722         // vector consecutive by adding  ... -3, -2, -1, 0.
2723         for (unsigned part = 0; part < UF; ++part)
2724           Entry[part] = getConsecutiveVector(Broadcasted, -(int)VF * part,
2725                                              true);
2726         return;
2727       }
2728
2729       // Handle the pointer induction variable case.
2730       assert(P->getType()->isPointerTy() && "Unexpected type.");
2731
2732       // Is this a reverse induction ptr or a consecutive induction ptr.
2733       bool Reverse = (LoopVectorizationLegality::IK_ReversePtrInduction ==
2734                       II.IK);
2735
2736       // This is the vector of results. Notice that we don't generate
2737       // vector geps because scalar geps result in better code.
2738       for (unsigned part = 0; part < UF; ++part) {
2739         if (VF == 1) {
2740           int EltIndex = (part) * (Reverse ? -1 : 1);
2741           Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex);
2742           Value *GlobalIdx;
2743           if (Reverse)
2744             GlobalIdx = Builder.CreateSub(Idx, NormalizedIdx, "gep.ridx");
2745           else
2746             GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx, "gep.idx");
2747
2748           Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
2749                                              "next.gep");
2750           Entry[part] = SclrGep;
2751           continue;
2752         }
2753
2754         Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
2755         for (unsigned int i = 0; i < VF; ++i) {
2756           int EltIndex = (i + part * VF) * (Reverse ? -1 : 1);
2757           Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex);
2758           Value *GlobalIdx;
2759           if (!Reverse)
2760             GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx, "gep.idx");
2761           else
2762             GlobalIdx = Builder.CreateSub(Idx, NormalizedIdx, "gep.ridx");
2763
2764           Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
2765                                              "next.gep");
2766           VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
2767                                                Builder.getInt32(i),
2768                                                "insert.gep");
2769         }
2770         Entry[part] = VecVal;
2771       }
2772       return;
2773   }
2774 }
2775
2776 void InnerLoopVectorizer::vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV) {
2777   // For each instruction in the old loop.
2778   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
2779     VectorParts &Entry = WidenMap.get(it);
2780     switch (it->getOpcode()) {
2781     case Instruction::Br:
2782       // Nothing to do for PHIs and BR, since we already took care of the
2783       // loop control flow instructions.
2784       continue;
2785     case Instruction::PHI:{
2786       // Vectorize PHINodes.
2787       widenPHIInstruction(it, Entry, UF, VF, PV);
2788       continue;
2789     }// End of PHI.
2790
2791     case Instruction::Add:
2792     case Instruction::FAdd:
2793     case Instruction::Sub:
2794     case Instruction::FSub:
2795     case Instruction::Mul:
2796     case Instruction::FMul:
2797     case Instruction::UDiv:
2798     case Instruction::SDiv:
2799     case Instruction::FDiv:
2800     case Instruction::URem:
2801     case Instruction::SRem:
2802     case Instruction::FRem:
2803     case Instruction::Shl:
2804     case Instruction::LShr:
2805     case Instruction::AShr:
2806     case Instruction::And:
2807     case Instruction::Or:
2808     case Instruction::Xor: {
2809       // Just widen binops.
2810       BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
2811       setDebugLocFromInst(Builder, BinOp);
2812       VectorParts &A = getVectorValue(it->getOperand(0));
2813       VectorParts &B = getVectorValue(it->getOperand(1));
2814
2815       // Use this vector value for all users of the original instruction.
2816       for (unsigned Part = 0; Part < UF; ++Part) {
2817         Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
2818
2819         // Update the NSW, NUW and Exact flags. Notice: V can be an Undef.
2820         BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V);
2821         if (VecOp && isa<OverflowingBinaryOperator>(BinOp)) {
2822           VecOp->setHasNoSignedWrap(BinOp->hasNoSignedWrap());
2823           VecOp->setHasNoUnsignedWrap(BinOp->hasNoUnsignedWrap());
2824         }
2825         if (VecOp && isa<PossiblyExactOperator>(VecOp))
2826           VecOp->setIsExact(BinOp->isExact());
2827
2828         Entry[Part] = V;
2829       }
2830       break;
2831     }
2832     case Instruction::Select: {
2833       // Widen selects.
2834       // If the selector is loop invariant we can create a select
2835       // instruction with a scalar condition. Otherwise, use vector-select.
2836       bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)),
2837                                                OrigLoop);
2838       setDebugLocFromInst(Builder, it);
2839
2840       // The condition can be loop invariant  but still defined inside the
2841       // loop. This means that we can't just use the original 'cond' value.
2842       // We have to take the 'vectorized' value and pick the first lane.
2843       // Instcombine will make this a no-op.
2844       VectorParts &Cond = getVectorValue(it->getOperand(0));
2845       VectorParts &Op0  = getVectorValue(it->getOperand(1));
2846       VectorParts &Op1  = getVectorValue(it->getOperand(2));
2847
2848       Value *ScalarCond = (VF == 1) ? Cond[0] :
2849         Builder.CreateExtractElement(Cond[0], Builder.getInt32(0));
2850
2851       for (unsigned Part = 0; Part < UF; ++Part) {
2852         Entry[Part] = Builder.CreateSelect(
2853           InvariantCond ? ScalarCond : Cond[Part],
2854           Op0[Part],
2855           Op1[Part]);
2856       }
2857       break;
2858     }
2859
2860     case Instruction::ICmp:
2861     case Instruction::FCmp: {
2862       // Widen compares. Generate vector compares.
2863       bool FCmp = (it->getOpcode() == Instruction::FCmp);
2864       CmpInst *Cmp = dyn_cast<CmpInst>(it);
2865       setDebugLocFromInst(Builder, it);
2866       VectorParts &A = getVectorValue(it->getOperand(0));
2867       VectorParts &B = getVectorValue(it->getOperand(1));
2868       for (unsigned Part = 0; Part < UF; ++Part) {
2869         Value *C = 0;
2870         if (FCmp)
2871           C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
2872         else
2873           C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
2874         Entry[Part] = C;
2875       }
2876       break;
2877     }
2878
2879     case Instruction::Store:
2880     case Instruction::Load:
2881       vectorizeMemoryInstruction(it);
2882         break;
2883     case Instruction::ZExt:
2884     case Instruction::SExt:
2885     case Instruction::FPToUI:
2886     case Instruction::FPToSI:
2887     case Instruction::FPExt:
2888     case Instruction::PtrToInt:
2889     case Instruction::IntToPtr:
2890     case Instruction::SIToFP:
2891     case Instruction::UIToFP:
2892     case Instruction::Trunc:
2893     case Instruction::FPTrunc:
2894     case Instruction::BitCast: {
2895       CastInst *CI = dyn_cast<CastInst>(it);
2896       setDebugLocFromInst(Builder, it);
2897       /// Optimize the special case where the source is the induction
2898       /// variable. Notice that we can only optimize the 'trunc' case
2899       /// because: a. FP conversions lose precision, b. sext/zext may wrap,
2900       /// c. other casts depend on pointer size.
2901       if (CI->getOperand(0) == OldInduction &&
2902           it->getOpcode() == Instruction::Trunc) {
2903         Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
2904                                                CI->getType());
2905         Value *Broadcasted = getBroadcastInstrs(ScalarCast);
2906         for (unsigned Part = 0; Part < UF; ++Part)
2907           Entry[Part] = getConsecutiveVector(Broadcasted, VF * Part, false);
2908         break;
2909       }
2910       /// Vectorize casts.
2911       Type *DestTy = (VF == 1) ? CI->getType() :
2912                                  VectorType::get(CI->getType(), VF);
2913
2914       VectorParts &A = getVectorValue(it->getOperand(0));
2915       for (unsigned Part = 0; Part < UF; ++Part)
2916         Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
2917       break;
2918     }
2919
2920     case Instruction::Call: {
2921       // Ignore dbg intrinsics.
2922       if (isa<DbgInfoIntrinsic>(it))
2923         break;
2924       setDebugLocFromInst(Builder, it);
2925
2926       Module *M = BB->getParent()->getParent();
2927       CallInst *CI = cast<CallInst>(it);
2928       Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
2929       assert(ID && "Not an intrinsic call!");
2930       switch (ID) {
2931       case Intrinsic::lifetime_end:
2932       case Intrinsic::lifetime_start:
2933         scalarizeInstruction(it);
2934         break;
2935       default:
2936         for (unsigned Part = 0; Part < UF; ++Part) {
2937           SmallVector<Value *, 4> Args;
2938           for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
2939             VectorParts &Arg = getVectorValue(CI->getArgOperand(i));
2940             Args.push_back(Arg[Part]);
2941           }
2942           Type *Tys[] = {CI->getType()};
2943           if (VF > 1)
2944             Tys[0] = VectorType::get(CI->getType()->getScalarType(), VF);
2945
2946           Function *F = Intrinsic::getDeclaration(M, ID, Tys);
2947           Entry[Part] = Builder.CreateCall(F, Args);
2948         }
2949         break;
2950       }
2951       break;
2952     }
2953
2954     default:
2955       // All other instructions are unsupported. Scalarize them.
2956       scalarizeInstruction(it);
2957       break;
2958     }// end of switch.
2959   }// end of for_each instr.
2960 }
2961
2962 void InnerLoopVectorizer::updateAnalysis() {
2963   // Forget the original basic block.
2964   SE->forgetLoop(OrigLoop);
2965
2966   // Update the dominator tree information.
2967   assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&
2968          "Entry does not dominate exit.");
2969
2970   for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
2971     DT->addNewBlock(LoopBypassBlocks[I], LoopBypassBlocks[I-1]);
2972   DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlocks.back());
2973   DT->addNewBlock(LoopVectorBody, LoopVectorPreHeader);
2974   DT->addNewBlock(LoopMiddleBlock, LoopBypassBlocks.front());
2975   DT->addNewBlock(LoopScalarPreHeader, LoopMiddleBlock);
2976   DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
2977   DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
2978
2979   DEBUG(DT->verifyAnalysis());
2980 }
2981
2982 /// \brief Check whether it is safe to if-convert this phi node.
2983 ///
2984 /// Phi nodes with constant expressions that can trap are not safe to if
2985 /// convert.
2986 static bool canIfConvertPHINodes(BasicBlock *BB) {
2987   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2988     PHINode *Phi = dyn_cast<PHINode>(I);
2989     if (!Phi)
2990       return true;
2991     for (unsigned p = 0, e = Phi->getNumIncomingValues(); p != e; ++p)
2992       if (Constant *C = dyn_cast<Constant>(Phi->getIncomingValue(p)))
2993         if (C->canTrap())
2994           return false;
2995   }
2996   return true;
2997 }
2998
2999 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
3000   if (!EnableIfConversion)
3001     return false;
3002
3003   assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
3004
3005   // A list of pointers that we can safely read and write to.
3006   SmallPtrSet<Value *, 8> SafePointes;
3007
3008   // Collect safe addresses.
3009   for (Loop::block_iterator BI = TheLoop->block_begin(),
3010          BE = TheLoop->block_end(); BI != BE; ++BI) {
3011     BasicBlock *BB = *BI;
3012
3013     if (blockNeedsPredication(BB))
3014       continue;
3015
3016     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3017       if (LoadInst *LI = dyn_cast<LoadInst>(I))
3018         SafePointes.insert(LI->getPointerOperand());
3019       else if (StoreInst *SI = dyn_cast<StoreInst>(I))
3020         SafePointes.insert(SI->getPointerOperand());
3021     }
3022   }
3023
3024   // Collect the blocks that need predication.
3025   BasicBlock *Header = TheLoop->getHeader();
3026   for (Loop::block_iterator BI = TheLoop->block_begin(),
3027          BE = TheLoop->block_end(); BI != BE; ++BI) {
3028     BasicBlock *BB = *BI;
3029
3030     // We don't support switch statements inside loops.
3031     if (!isa<BranchInst>(BB->getTerminator()))
3032       return false;
3033
3034     // We must be able to predicate all blocks that need to be predicated.
3035     if (blockNeedsPredication(BB)) {
3036       if (!blockCanBePredicated(BB, SafePointes))
3037         return false;
3038     } else if (BB != Header && !canIfConvertPHINodes(BB))
3039       return false;
3040
3041   }
3042
3043   // We can if-convert this loop.
3044   return true;
3045 }
3046
3047 bool LoopVectorizationLegality::canVectorize() {
3048   // We must have a loop in canonical form. Loops with indirectbr in them cannot
3049   // be canonicalized.
3050   if (!TheLoop->getLoopPreheader())
3051     return false;
3052
3053   // We can only vectorize innermost loops.
3054   if (TheLoop->getSubLoopsVector().size())
3055     return false;
3056
3057   // We must have a single backedge.
3058   if (TheLoop->getNumBackEdges() != 1)
3059     return false;
3060
3061   // We must have a single exiting block.
3062   if (!TheLoop->getExitingBlock())
3063     return false;
3064
3065   // We need to have a loop header.
3066   DEBUG(dbgs() << "LV: Found a loop: " <<
3067         TheLoop->getHeader()->getName() << '\n');
3068
3069   // Check if we can if-convert non-single-bb loops.
3070   unsigned NumBlocks = TheLoop->getNumBlocks();
3071   if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
3072     DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
3073     return false;
3074   }
3075
3076   // ScalarEvolution needs to be able to find the exit count.
3077   const SCEV *ExitCount = SE->getBackedgeTakenCount(TheLoop);
3078   if (ExitCount == SE->getCouldNotCompute()) {
3079     DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
3080     return false;
3081   }
3082
3083   // Do not loop-vectorize loops with a tiny trip count.
3084   BasicBlock *Latch = TheLoop->getLoopLatch();
3085   unsigned TC = SE->getSmallConstantTripCount(TheLoop, Latch);
3086   if (TC > 0u && TC < TinyTripCountVectorThreshold) {
3087     DEBUG(dbgs() << "LV: Found a loop with a very small trip count. " <<
3088           "This loop is not worth vectorizing.\n");
3089     return false;
3090   }
3091
3092   // Check if we can vectorize the instructions and CFG in this loop.
3093   if (!canVectorizeInstrs()) {
3094     DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
3095     return false;
3096   }
3097
3098   // Go over each instruction and look at memory deps.
3099   if (!canVectorizeMemory()) {
3100     DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
3101     return false;
3102   }
3103
3104   // Collect all of the variables that remain uniform after vectorization.
3105   collectLoopUniforms();
3106
3107   DEBUG(dbgs() << "LV: We can vectorize this loop" <<
3108         (PtrRtCheck.Need ? " (with a runtime bound check)" : "")
3109         <<"!\n");
3110
3111   // Okay! We can vectorize. At this point we don't have any other mem analysis
3112   // which may limit our maximum vectorization factor, so just return true with
3113   // no restrictions.
3114   return true;
3115 }
3116
3117 static Type *convertPointerToIntegerType(DataLayout &DL, Type *Ty) {
3118   if (Ty->isPointerTy())
3119     return DL.getIntPtrType(Ty);
3120
3121   // It is possible that char's or short's overflow when we ask for the loop's
3122   // trip count, work around this by changing the type size.
3123   if (Ty->getScalarSizeInBits() < 32)
3124     return Type::getInt32Ty(Ty->getContext());
3125
3126   return Ty;
3127 }
3128
3129 static Type* getWiderType(DataLayout &DL, Type *Ty0, Type *Ty1) {
3130   Ty0 = convertPointerToIntegerType(DL, Ty0);
3131   Ty1 = convertPointerToIntegerType(DL, Ty1);
3132   if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits())
3133     return Ty0;
3134   return Ty1;
3135 }
3136
3137 /// \brief Check that the instruction has outside loop users and is not an
3138 /// identified reduction variable.
3139 static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst,
3140                                SmallPtrSet<Value *, 4> &Reductions) {
3141   // Reduction instructions are allowed to have exit users. All other
3142   // instructions must not have external users.
3143   if (!Reductions.count(Inst))
3144     //Check that all of the users of the loop are inside the BB.
3145     for (Value::use_iterator I = Inst->use_begin(), E = Inst->use_end();
3146          I != E; ++I) {
3147       Instruction *U = cast<Instruction>(*I);
3148       // This user may be a reduction exit value.
3149       if (!TheLoop->contains(U)) {
3150         DEBUG(dbgs() << "LV: Found an outside user for : " << *U << '\n');
3151         return true;
3152       }
3153     }
3154   return false;
3155 }
3156
3157 bool LoopVectorizationLegality::canVectorizeInstrs() {
3158   BasicBlock *PreHeader = TheLoop->getLoopPreheader();
3159   BasicBlock *Header = TheLoop->getHeader();
3160
3161   // Look for the attribute signaling the absence of NaNs.
3162   Function &F = *Header->getParent();
3163   if (F.hasFnAttribute("no-nans-fp-math"))
3164     HasFunNoNaNAttr = F.getAttributes().getAttribute(
3165       AttributeSet::FunctionIndex,
3166       "no-nans-fp-math").getValueAsString() == "true";
3167
3168   // For each block in the loop.
3169   for (Loop::block_iterator bb = TheLoop->block_begin(),
3170        be = TheLoop->block_end(); bb != be; ++bb) {
3171
3172     // Scan the instructions in the block and look for hazards.
3173     for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
3174          ++it) {
3175
3176       if (PHINode *Phi = dyn_cast<PHINode>(it)) {
3177         Type *PhiTy = Phi->getType();
3178         // Check that this PHI type is allowed.
3179         if (!PhiTy->isIntegerTy() &&
3180             !PhiTy->isFloatingPointTy() &&
3181             !PhiTy->isPointerTy()) {
3182           DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
3183           return false;
3184         }
3185
3186         // If this PHINode is not in the header block, then we know that we
3187         // can convert it to select during if-conversion. No need to check if
3188         // the PHIs in this block are induction or reduction variables.
3189         if (*bb != Header) {
3190           // Check that this instruction has no outside users or is an
3191           // identified reduction value with an outside user.
3192           if(!hasOutsideLoopUser(TheLoop, it, AllowedExit))
3193             continue;
3194           return false;
3195         }
3196
3197         // We only allow if-converted PHIs with more than two incoming values.
3198         if (Phi->getNumIncomingValues() != 2) {
3199           DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
3200           return false;
3201         }
3202
3203         // This is the value coming from the preheader.
3204         Value *StartValue = Phi->getIncomingValueForBlock(PreHeader);
3205         // Check if this is an induction variable.
3206         InductionKind IK = isInductionVariable(Phi);
3207
3208         if (IK_NoInduction != IK) {
3209           // Get the widest type.
3210           if (!WidestIndTy)
3211             WidestIndTy = convertPointerToIntegerType(*DL, PhiTy);
3212           else
3213             WidestIndTy = getWiderType(*DL, PhiTy, WidestIndTy);
3214
3215           // Int inductions are special because we only allow one IV.
3216           if (IK == IK_IntInduction) {
3217             // Use the phi node with the widest type as induction. Use the last
3218             // one if there are multiple (no good reason for doing this other
3219             // than it is expedient).
3220             if (!Induction || PhiTy == WidestIndTy)
3221               Induction = Phi;
3222           }
3223
3224           DEBUG(dbgs() << "LV: Found an induction variable.\n");
3225           Inductions[Phi] = InductionInfo(StartValue, IK);
3226
3227           // Until we explicitly handle the case of an induction variable with
3228           // an outside loop user we have to give up vectorizing this loop.
3229           if (hasOutsideLoopUser(TheLoop, it, AllowedExit))
3230             return false;
3231
3232           continue;
3233         }
3234
3235         if (AddReductionVar(Phi, RK_IntegerAdd)) {
3236           DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
3237           continue;
3238         }
3239         if (AddReductionVar(Phi, RK_IntegerMult)) {
3240           DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n");
3241           continue;
3242         }
3243         if (AddReductionVar(Phi, RK_IntegerOr)) {
3244           DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n");
3245           continue;
3246         }
3247         if (AddReductionVar(Phi, RK_IntegerAnd)) {
3248           DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n");
3249           continue;
3250         }
3251         if (AddReductionVar(Phi, RK_IntegerXor)) {
3252           DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n");
3253           continue;
3254         }
3255         if (AddReductionVar(Phi, RK_IntegerMinMax)) {
3256           DEBUG(dbgs() << "LV: Found a MINMAX reduction PHI."<< *Phi <<"\n");
3257           continue;
3258         }
3259         if (AddReductionVar(Phi, RK_FloatMult)) {
3260           DEBUG(dbgs() << "LV: Found an FMult reduction PHI."<< *Phi <<"\n");
3261           continue;
3262         }
3263         if (AddReductionVar(Phi, RK_FloatAdd)) {
3264           DEBUG(dbgs() << "LV: Found an FAdd reduction PHI."<< *Phi <<"\n");
3265           continue;
3266         }
3267         if (AddReductionVar(Phi, RK_FloatMinMax)) {
3268           DEBUG(dbgs() << "LV: Found an float MINMAX reduction PHI."<< *Phi <<
3269                 "\n");
3270           continue;
3271         }
3272
3273         DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
3274         return false;
3275       }// end of PHI handling
3276
3277       // We still don't handle functions. However, we can ignore dbg intrinsic
3278       // calls and we do handle certain intrinsic and libm functions.
3279       CallInst *CI = dyn_cast<CallInst>(it);
3280       if (CI && !getIntrinsicIDForCall(CI, TLI) && !isa<DbgInfoIntrinsic>(CI)) {
3281         DEBUG(dbgs() << "LV: Found a call site.\n");
3282         return false;
3283       }
3284
3285       // Check that the instruction return type is vectorizable.
3286       // Also, we can't vectorize extractelement instructions.
3287       if ((!VectorType::isValidElementType(it->getType()) &&
3288            !it->getType()->isVoidTy()) || isa<ExtractElementInst>(it)) {
3289         DEBUG(dbgs() << "LV: Found unvectorizable type.\n");
3290         return false;
3291       }
3292
3293       // Check that the stored type is vectorizable.
3294       if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
3295         Type *T = ST->getValueOperand()->getType();
3296         if (!VectorType::isValidElementType(T))
3297           return false;
3298         if (EnableMemAccessVersioning)
3299           collectStridedAcccess(ST);
3300       }
3301
3302       if (EnableMemAccessVersioning)
3303         if (LoadInst *LI = dyn_cast<LoadInst>(it))
3304           collectStridedAcccess(LI);
3305
3306       // Reduction instructions are allowed to have exit users.
3307       // All other instructions must not have external users.
3308       if (hasOutsideLoopUser(TheLoop, it, AllowedExit))
3309         return false;
3310
3311     } // next instr.
3312
3313   }
3314
3315   if (!Induction) {
3316     DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
3317     if (Inductions.empty())
3318       return false;
3319   }
3320
3321   return true;
3322 }
3323
3324 ///\brief Remove GEPs whose indices but the last one are loop invariant and
3325 /// return the induction operand of the gep pointer.
3326 static Value *stripGetElementPtr(Value *Ptr, ScalarEvolution *SE,
3327                                  DataLayout *DL, Loop *Lp) {
3328   GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
3329   if (!GEP)
3330     return Ptr;
3331
3332   unsigned InductionOperand = getGEPInductionOperand(DL, GEP);
3333
3334   // Check that all of the gep indices are uniform except for our induction
3335   // operand.
3336   for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i)
3337     if (i != InductionOperand &&
3338         !SE->isLoopInvariant(SE->getSCEV(GEP->getOperand(i)), Lp))
3339       return Ptr;
3340   return GEP->getOperand(InductionOperand);
3341 }
3342
3343 ///\brief Look for a cast use of the passed value.
3344 static Value *getUniqueCastUse(Value *Ptr, Loop *Lp, Type *Ty) {
3345   Value *UniqueCast = 0;
3346   for (Value::use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end(); UI != UE;
3347        ++UI) {
3348     CastInst *CI = dyn_cast<CastInst>(*UI);
3349     if (CI && CI->getType() == Ty) {
3350       if (!UniqueCast)
3351         UniqueCast = CI;
3352       else
3353         return 0;
3354     }
3355   }
3356   return UniqueCast;
3357 }
3358
3359 ///\brief Get the stride of a pointer access in a loop.
3360 /// Looks for symbolic strides "a[i*stride]". Returns the symbolic stride as a
3361 /// pointer to the Value, or null otherwise.
3362 static Value *getStrideFromPointer(Value *Ptr, ScalarEvolution *SE,
3363                                    DataLayout *DL, Loop *Lp) {
3364   const PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType());
3365   if (!PtrTy || PtrTy->isAggregateType())
3366     return 0;
3367
3368   // Try to remove a gep instruction to make the pointer (actually index at this
3369   // point) easier analyzable. If OrigPtr is equal to Ptr we are analzying the
3370   // pointer, otherwise, we are analyzing the index.
3371   Value *OrigPtr = Ptr;
3372
3373   // The size of the pointer access.
3374   int64_t PtrAccessSize = 1;
3375
3376   Ptr = stripGetElementPtr(Ptr, SE, DL, Lp);
3377   const SCEV *V = SE->getSCEV(Ptr);
3378
3379   if (Ptr != OrigPtr)
3380     // Strip off casts.
3381     while (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V))
3382       V = C->getOperand();
3383
3384   const SCEVAddRecExpr *S = dyn_cast<SCEVAddRecExpr>(V);
3385   if (!S)
3386     return 0;
3387
3388   V = S->getStepRecurrence(*SE);
3389   if (!V)
3390     return 0;
3391
3392   // Strip off the size of access multiplication if we are still analyzing the
3393   // pointer.
3394   if (OrigPtr == Ptr) {
3395     DL->getTypeAllocSize(PtrTy->getElementType());
3396     if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(V)) {
3397       if (M->getOperand(0)->getSCEVType() != scConstant)
3398         return 0;
3399
3400       const APInt &APStepVal =
3401           cast<SCEVConstant>(M->getOperand(0))->getValue()->getValue();
3402
3403       // Huge step value - give up.
3404       if (APStepVal.getBitWidth() > 64)
3405         return 0;
3406
3407       int64_t StepVal = APStepVal.getSExtValue();
3408       if (PtrAccessSize != StepVal)
3409         return 0;
3410       V = M->getOperand(1);
3411     }
3412   }
3413
3414   // Strip off casts.
3415   Type *StripedOffRecurrenceCast = 0;
3416   if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V)) {
3417     StripedOffRecurrenceCast = C->getType();
3418     V = C->getOperand();
3419   }
3420
3421   // Look for the loop invariant symbolic value.
3422   const SCEVUnknown *U = dyn_cast<SCEVUnknown>(V);
3423   if (!U)
3424     return 0;
3425
3426   Value *Stride = U->getValue();
3427   if (!Lp->isLoopInvariant(Stride))
3428     return 0;
3429
3430   // If we have stripped off the recurrence cast we have to make sure that we
3431   // return the value that is used in this loop so that we can replace it later.
3432   if (StripedOffRecurrenceCast)
3433     Stride = getUniqueCastUse(Stride, Lp, StripedOffRecurrenceCast);
3434
3435   return Stride;
3436 }
3437
3438 void LoopVectorizationLegality::collectStridedAcccess(Value *MemAccess) {
3439   Value *Ptr = 0;
3440   if (LoadInst *LI = dyn_cast<LoadInst>(MemAccess))
3441     Ptr = LI->getPointerOperand();
3442   else if (StoreInst *SI = dyn_cast<StoreInst>(MemAccess))
3443     Ptr = SI->getPointerOperand();
3444   else
3445     return;
3446
3447   Value *Stride = getStrideFromPointer(Ptr, SE, DL, TheLoop);
3448   if (!Stride)
3449     return;
3450
3451   DEBUG(dbgs() << "LV: Found a strided access that we can version");
3452   DEBUG(dbgs() << "  Ptr: " << *Ptr << " Stride: " << *Stride << "\n");
3453   Strides[Ptr] = Stride;
3454   StrideSet.insert(Stride);
3455 }
3456
3457 void LoopVectorizationLegality::collectLoopUniforms() {
3458   // We now know that the loop is vectorizable!
3459   // Collect variables that will remain uniform after vectorization.
3460   std::vector<Value*> Worklist;
3461   BasicBlock *Latch = TheLoop->getLoopLatch();
3462
3463   // Start with the conditional branch and walk up the block.
3464   Worklist.push_back(Latch->getTerminator()->getOperand(0));
3465
3466   while (Worklist.size()) {
3467     Instruction *I = dyn_cast<Instruction>(Worklist.back());
3468     Worklist.pop_back();
3469
3470     // Look at instructions inside this loop.
3471     // Stop when reaching PHI nodes.
3472     // TODO: we need to follow values all over the loop, not only in this block.
3473     if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
3474       continue;
3475
3476     // This is a known uniform.
3477     Uniforms.insert(I);
3478
3479     // Insert all operands.
3480     Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
3481   }
3482 }
3483
3484 namespace {
3485 /// \brief Analyses memory accesses in a loop.
3486 ///
3487 /// Checks whether run time pointer checks are needed and builds sets for data
3488 /// dependence checking.
3489 class AccessAnalysis {
3490 public:
3491   /// \brief Read or write access location.
3492   typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
3493   typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
3494
3495   /// \brief Set of potential dependent memory accesses.
3496   typedef EquivalenceClasses<MemAccessInfo> DepCandidates;
3497
3498   AccessAnalysis(DataLayout *Dl, DepCandidates &DA) :
3499     DL(Dl), DepCands(DA), AreAllWritesIdentified(true),
3500     AreAllReadsIdentified(true), IsRTCheckNeeded(false) {}
3501
3502   /// \brief Register a load  and whether it is only read from.
3503   void addLoad(Value *Ptr, bool IsReadOnly) {
3504     Accesses.insert(MemAccessInfo(Ptr, false));
3505     if (IsReadOnly)
3506       ReadOnlyPtr.insert(Ptr);
3507   }
3508
3509   /// \brief Register a store.
3510   void addStore(Value *Ptr) {
3511     Accesses.insert(MemAccessInfo(Ptr, true));
3512   }
3513
3514   /// \brief Check whether we can check the pointers at runtime for
3515   /// non-intersection.
3516   bool canCheckPtrAtRT(LoopVectorizationLegality::RuntimePointerCheck &RtCheck,
3517                        unsigned &NumComparisons, ScalarEvolution *SE,
3518                        Loop *TheLoop, ValueToValueMap &Strides,
3519                        bool ShouldCheckStride = false);
3520
3521   /// \brief Goes over all memory accesses, checks whether a RT check is needed
3522   /// and builds sets of dependent accesses.
3523   void buildDependenceSets() {
3524     // Process read-write pointers first.
3525     processMemAccesses(false);
3526     // Next, process read pointers.
3527     processMemAccesses(true);
3528   }
3529
3530   bool isRTCheckNeeded() { return IsRTCheckNeeded; }
3531
3532   bool isDependencyCheckNeeded() { return !CheckDeps.empty(); }
3533   void resetDepChecks() { CheckDeps.clear(); }
3534
3535   MemAccessInfoSet &getDependenciesToCheck() { return CheckDeps; }
3536
3537 private:
3538   typedef SetVector<MemAccessInfo> PtrAccessSet;
3539   typedef DenseMap<Value*, MemAccessInfo> UnderlyingObjToAccessMap;
3540
3541   /// \brief Go over all memory access or only the deferred ones if
3542   /// \p UseDeferred is true and check whether runtime pointer checks are needed
3543   /// and build sets of dependency check candidates.
3544   void processMemAccesses(bool UseDeferred);
3545
3546   /// Set of all accesses.
3547   PtrAccessSet Accesses;
3548
3549   /// Set of access to check after all writes have been processed.
3550   PtrAccessSet DeferredAccesses;
3551
3552   /// Map of pointers to last access encountered.
3553   UnderlyingObjToAccessMap ObjToLastAccess;
3554
3555   /// Set of accesses that need a further dependence check.
3556   MemAccessInfoSet CheckDeps;
3557
3558   /// Set of pointers that are read only.
3559   SmallPtrSet<Value*, 16> ReadOnlyPtr;
3560
3561   /// Set of underlying objects already written to.
3562   SmallPtrSet<Value*, 16> WriteObjects;
3563
3564   DataLayout *DL;
3565
3566   /// Sets of potentially dependent accesses - members of one set share an
3567   /// underlying pointer. The set "CheckDeps" identfies which sets really need a
3568   /// dependence check.
3569   DepCandidates &DepCands;
3570
3571   bool AreAllWritesIdentified;
3572   bool AreAllReadsIdentified;
3573   bool IsRTCheckNeeded;
3574 };
3575
3576 } // end anonymous namespace
3577
3578 /// \brief Check whether a pointer can participate in a runtime bounds check.
3579 static bool hasComputableBounds(ScalarEvolution *SE, ValueToValueMap &Strides,
3580                                 Value *Ptr) {
3581   const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
3582   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
3583   if (!AR)
3584     return false;
3585
3586   return AR->isAffine();
3587 }
3588
3589 /// \brief Check the stride of the pointer and ensure that it does not wrap in
3590 /// the address space.
3591 static int isStridedPtr(ScalarEvolution *SE, DataLayout *DL, Value *Ptr,
3592                         const Loop *Lp, ValueToValueMap &StridesMap);
3593
3594 bool AccessAnalysis::canCheckPtrAtRT(
3595     LoopVectorizationLegality::RuntimePointerCheck &RtCheck,
3596     unsigned &NumComparisons, ScalarEvolution *SE, Loop *TheLoop,
3597     ValueToValueMap &StridesMap, bool ShouldCheckStride) {
3598   // Find pointers with computable bounds. We are going to use this information
3599   // to place a runtime bound check.
3600   unsigned NumReadPtrChecks = 0;
3601   unsigned NumWritePtrChecks = 0;
3602   bool CanDoRT = true;
3603
3604   bool IsDepCheckNeeded = isDependencyCheckNeeded();
3605   // We assign consecutive id to access from different dependence sets.
3606   // Accesses within the same set don't need a runtime check.
3607   unsigned RunningDepId = 1;
3608   DenseMap<Value *, unsigned> DepSetId;
3609
3610   for (PtrAccessSet::iterator AI = Accesses.begin(), AE = Accesses.end();
3611        AI != AE; ++AI) {
3612     const MemAccessInfo &Access = *AI;
3613     Value *Ptr = Access.getPointer();
3614     bool IsWrite = Access.getInt();
3615
3616     // Just add write checks if we have both.
3617     if (!IsWrite && Accesses.count(MemAccessInfo(Ptr, true)))
3618       continue;
3619
3620     if (IsWrite)
3621       ++NumWritePtrChecks;
3622     else
3623       ++NumReadPtrChecks;
3624
3625     if (hasComputableBounds(SE, StridesMap, Ptr) &&
3626         // When we run after a failing dependency check we have to make sure we
3627         // don't have wrapping pointers.
3628         (!ShouldCheckStride ||
3629          isStridedPtr(SE, DL, Ptr, TheLoop, StridesMap) == 1)) {
3630       // The id of the dependence set.
3631       unsigned DepId;
3632
3633       if (IsDepCheckNeeded) {
3634         Value *Leader = DepCands.getLeaderValue(Access).getPointer();
3635         unsigned &LeaderId = DepSetId[Leader];
3636         if (!LeaderId)
3637           LeaderId = RunningDepId++;
3638         DepId = LeaderId;
3639       } else
3640         // Each access has its own dependence set.
3641         DepId = RunningDepId++;
3642
3643       RtCheck.insert(SE, TheLoop, Ptr, IsWrite, DepId, StridesMap);
3644
3645       DEBUG(dbgs() << "LV: Found a runtime check ptr:" << *Ptr << '\n');
3646     } else {
3647       CanDoRT = false;
3648     }
3649   }
3650
3651   if (IsDepCheckNeeded && CanDoRT && RunningDepId == 2)
3652     NumComparisons = 0; // Only one dependence set.
3653   else {
3654     NumComparisons = (NumWritePtrChecks * (NumReadPtrChecks +
3655                                            NumWritePtrChecks - 1));
3656   }
3657
3658   // If the pointers that we would use for the bounds comparison have different
3659   // address spaces, assume the values aren't directly comparable, so we can't
3660   // use them for the runtime check. We also have to assume they could
3661   // overlap. In the future there should be metadata for whether address spaces
3662   // are disjoint.
3663   unsigned NumPointers = RtCheck.Pointers.size();
3664   for (unsigned i = 0; i < NumPointers; ++i) {
3665     for (unsigned j = i + 1; j < NumPointers; ++j) {
3666       // Only need to check pointers between two different dependency sets.
3667       if (RtCheck.DependencySetId[i] == RtCheck.DependencySetId[j])
3668        continue;
3669
3670       Value *PtrI = RtCheck.Pointers[i];
3671       Value *PtrJ = RtCheck.Pointers[j];
3672
3673       unsigned ASi = PtrI->getType()->getPointerAddressSpace();
3674       unsigned ASj = PtrJ->getType()->getPointerAddressSpace();
3675       if (ASi != ASj) {
3676         DEBUG(dbgs() << "LV: Runtime check would require comparison between"
3677                        " different address spaces\n");
3678         return false;
3679       }
3680     }
3681   }
3682
3683   return CanDoRT;
3684 }
3685
3686 static bool isFunctionScopeIdentifiedObject(Value *Ptr) {
3687   return isNoAliasArgument(Ptr) || isNoAliasCall(Ptr) || isa<AllocaInst>(Ptr);
3688 }
3689
3690 void AccessAnalysis::processMemAccesses(bool UseDeferred) {
3691   // We process the set twice: first we process read-write pointers, last we
3692   // process read-only pointers. This allows us to skip dependence tests for
3693   // read-only pointers.
3694
3695   PtrAccessSet &S = UseDeferred ? DeferredAccesses : Accesses;
3696   for (PtrAccessSet::iterator AI = S.begin(), AE = S.end(); AI != AE; ++AI) {
3697     const MemAccessInfo &Access = *AI;
3698     Value *Ptr = Access.getPointer();
3699     bool IsWrite = Access.getInt();
3700
3701     DepCands.insert(Access);
3702
3703     // Memorize read-only pointers for later processing and skip them in the
3704     // first round (they need to be checked after we have seen all write
3705     // pointers). Note: we also mark pointer that are not consecutive as
3706     // "read-only" pointers (so that we check "a[b[i]] +="). Hence, we need the
3707     // second check for "!IsWrite".
3708     bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite;
3709     if (!UseDeferred && IsReadOnlyPtr) {
3710       DeferredAccesses.insert(Access);
3711       continue;
3712     }
3713
3714     bool NeedDepCheck = false;
3715     // Check whether there is the possiblity of dependency because of underlying
3716     // objects being the same.
3717     typedef SmallVector<Value*, 16> ValueVector;
3718     ValueVector TempObjects;
3719     GetUnderlyingObjects(Ptr, TempObjects, DL);
3720     for (ValueVector::iterator UI = TempObjects.begin(), UE = TempObjects.end();
3721          UI != UE; ++UI) {
3722       Value *UnderlyingObj = *UI;
3723
3724       // If this is a write then it needs to be an identified object.  If this a
3725       // read and all writes (so far) are identified function scope objects we
3726       // don't need an identified underlying object but only an Argument (the
3727       // next write is going to invalidate this assumption if it is
3728       // unidentified).
3729       // This is a micro-optimization for the case where all writes are
3730       // identified and we have one argument pointer.
3731       // Otherwise, we do need a runtime check.
3732       if ((IsWrite && !isFunctionScopeIdentifiedObject(UnderlyingObj)) ||
3733           (!IsWrite && (!AreAllWritesIdentified ||
3734                         !isa<Argument>(UnderlyingObj)) &&
3735            !isIdentifiedObject(UnderlyingObj))) {
3736         DEBUG(dbgs() << "LV: Found an unidentified " <<
3737               (IsWrite ?  "write" : "read" ) << " ptr: " << *UnderlyingObj <<
3738               "\n");
3739         IsRTCheckNeeded = (IsRTCheckNeeded ||
3740                            !isIdentifiedObject(UnderlyingObj) ||
3741                            !AreAllReadsIdentified);
3742
3743         if (IsWrite)
3744           AreAllWritesIdentified = false;
3745         if (!IsWrite)
3746           AreAllReadsIdentified = false;
3747       }
3748
3749       // If this is a write - check other reads and writes for conflicts.  If
3750       // this is a read only check other writes for conflicts (but only if there
3751       // is no other write to the ptr - this is an optimization to catch "a[i] =
3752       // a[i] + " without having to do a dependence check).
3753       if ((IsWrite || IsReadOnlyPtr) && WriteObjects.count(UnderlyingObj))
3754         NeedDepCheck = true;
3755
3756       if (IsWrite)
3757         WriteObjects.insert(UnderlyingObj);
3758
3759       // Create sets of pointers connected by shared underlying objects.
3760       UnderlyingObjToAccessMap::iterator Prev =
3761         ObjToLastAccess.find(UnderlyingObj);
3762       if (Prev != ObjToLastAccess.end())
3763         DepCands.unionSets(Access, Prev->second);
3764
3765       ObjToLastAccess[UnderlyingObj] = Access;
3766     }
3767
3768     if (NeedDepCheck)
3769       CheckDeps.insert(Access);
3770   }
3771 }
3772
3773 namespace {
3774 /// \brief Checks memory dependences among accesses to the same underlying
3775 /// object to determine whether there vectorization is legal or not (and at
3776 /// which vectorization factor).
3777 ///
3778 /// This class works under the assumption that we already checked that memory
3779 /// locations with different underlying pointers are "must-not alias".
3780 /// We use the ScalarEvolution framework to symbolically evalutate access
3781 /// functions pairs. Since we currently don't restructure the loop we can rely
3782 /// on the program order of memory accesses to determine their safety.
3783 /// At the moment we will only deem accesses as safe for:
3784 ///  * A negative constant distance assuming program order.
3785 ///
3786 ///      Safe: tmp = a[i + 1];     OR     a[i + 1] = x;
3787 ///            a[i] = tmp;                y = a[i];
3788 ///
3789 ///   The latter case is safe because later checks guarantuee that there can't
3790 ///   be a cycle through a phi node (that is, we check that "x" and "y" is not
3791 ///   the same variable: a header phi can only be an induction or a reduction, a
3792 ///   reduction can't have a memory sink, an induction can't have a memory
3793 ///   source). This is important and must not be violated (or we have to
3794 ///   resort to checking for cycles through memory).
3795 ///
3796 ///  * A positive constant distance assuming program order that is bigger
3797 ///    than the biggest memory access.
3798 ///
3799 ///     tmp = a[i]        OR              b[i] = x
3800 ///     a[i+2] = tmp                      y = b[i+2];
3801 ///
3802 ///     Safe distance: 2 x sizeof(a[0]), and 2 x sizeof(b[0]), respectively.
3803 ///
3804 ///  * Zero distances and all accesses have the same size.
3805 ///
3806 class MemoryDepChecker {
3807 public:
3808   typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
3809   typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
3810
3811   MemoryDepChecker(ScalarEvolution *Se, DataLayout *Dl, const Loop *L)
3812       : SE(Se), DL(Dl), InnermostLoop(L), AccessIdx(0),
3813         ShouldRetryWithRuntimeCheck(false) {}
3814
3815   /// \brief Register the location (instructions are given increasing numbers)
3816   /// of a write access.
3817   void addAccess(StoreInst *SI) {
3818     Value *Ptr = SI->getPointerOperand();
3819     Accesses[MemAccessInfo(Ptr, true)].push_back(AccessIdx);
3820     InstMap.push_back(SI);
3821     ++AccessIdx;
3822   }
3823
3824   /// \brief Register the location (instructions are given increasing numbers)
3825   /// of a write access.
3826   void addAccess(LoadInst *LI) {
3827     Value *Ptr = LI->getPointerOperand();
3828     Accesses[MemAccessInfo(Ptr, false)].push_back(AccessIdx);
3829     InstMap.push_back(LI);
3830     ++AccessIdx;
3831   }
3832
3833   /// \brief Check whether the dependencies between the accesses are safe.
3834   ///
3835   /// Only checks sets with elements in \p CheckDeps.
3836   bool areDepsSafe(AccessAnalysis::DepCandidates &AccessSets,
3837                    MemAccessInfoSet &CheckDeps, ValueToValueMap &Strides);
3838
3839   /// \brief The maximum number of bytes of a vector register we can vectorize
3840   /// the accesses safely with.
3841   unsigned getMaxSafeDepDistBytes() { return MaxSafeDepDistBytes; }
3842
3843   /// \brief In same cases when the dependency check fails we can still
3844   /// vectorize the loop with a dynamic array access check.
3845   bool shouldRetryWithRuntimeCheck() { return ShouldRetryWithRuntimeCheck; }
3846
3847 private:
3848   ScalarEvolution *SE;
3849   DataLayout *DL;
3850   const Loop *InnermostLoop;
3851
3852   /// \brief Maps access locations (ptr, read/write) to program order.
3853   DenseMap<MemAccessInfo, std::vector<unsigned> > Accesses;
3854
3855   /// \brief Memory access instructions in program order.
3856   SmallVector<Instruction *, 16> InstMap;
3857
3858   /// \brief The program order index to be used for the next instruction.
3859   unsigned AccessIdx;
3860
3861   // We can access this many bytes in parallel safely.
3862   unsigned MaxSafeDepDistBytes;
3863
3864   /// \brief If we see a non-constant dependence distance we can still try to
3865   /// vectorize this loop with runtime checks.
3866   bool ShouldRetryWithRuntimeCheck;
3867
3868   /// \brief Check whether there is a plausible dependence between the two
3869   /// accesses.
3870   ///
3871   /// Access \p A must happen before \p B in program order. The two indices
3872   /// identify the index into the program order map.
3873   ///
3874   /// This function checks  whether there is a plausible dependence (or the
3875   /// absence of such can't be proved) between the two accesses. If there is a
3876   /// plausible dependence but the dependence distance is bigger than one
3877   /// element access it records this distance in \p MaxSafeDepDistBytes (if this
3878   /// distance is smaller than any other distance encountered so far).
3879   /// Otherwise, this function returns true signaling a possible dependence.
3880   bool isDependent(const MemAccessInfo &A, unsigned AIdx,
3881                    const MemAccessInfo &B, unsigned BIdx,
3882                    ValueToValueMap &Strides);
3883
3884   /// \brief Check whether the data dependence could prevent store-load
3885   /// forwarding.
3886   bool couldPreventStoreLoadForward(unsigned Distance, unsigned TypeByteSize);
3887 };
3888
3889 } // end anonymous namespace
3890
3891 static bool isInBoundsGep(Value *Ptr) {
3892   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
3893     return GEP->isInBounds();
3894   return false;
3895 }
3896
3897 /// \brief Check whether the access through \p Ptr has a constant stride.
3898 static int isStridedPtr(ScalarEvolution *SE, DataLayout *DL, Value *Ptr,
3899                         const Loop *Lp, ValueToValueMap &StridesMap) {
3900   const Type *Ty = Ptr->getType();
3901   assert(Ty->isPointerTy() && "Unexpected non-ptr");
3902
3903   // Make sure that the pointer does not point to aggregate types.
3904   const PointerType *PtrTy = cast<PointerType>(Ty);
3905   if (PtrTy->getElementType()->isAggregateType()) {
3906     DEBUG(dbgs() << "LV: Bad stride - Not a pointer to a scalar type" << *Ptr <<
3907           "\n");
3908     return 0;
3909   }
3910
3911   const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, StridesMap, Ptr);
3912
3913   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
3914   if (!AR) {
3915     DEBUG(dbgs() << "LV: Bad stride - Not an AddRecExpr pointer "
3916           << *Ptr << " SCEV: " << *PtrScev << "\n");
3917     return 0;
3918   }
3919
3920   // The accesss function must stride over the innermost loop.
3921   if (Lp != AR->getLoop()) {
3922     DEBUG(dbgs() << "LV: Bad stride - Not striding over innermost loop " <<
3923           *Ptr << " SCEV: " << *PtrScev << "\n");
3924   }
3925
3926   // The address calculation must not wrap. Otherwise, a dependence could be
3927   // inverted.
3928   // An inbounds getelementptr that is a AddRec with a unit stride
3929   // cannot wrap per definition. The unit stride requirement is checked later.
3930   // An getelementptr without an inbounds attribute and unit stride would have
3931   // to access the pointer value "0" which is undefined behavior in address
3932   // space 0, therefore we can also vectorize this case.
3933   bool IsInBoundsGEP = isInBoundsGep(Ptr);
3934   bool IsNoWrapAddRec = AR->getNoWrapFlags(SCEV::NoWrapMask);
3935   bool IsInAddressSpaceZero = PtrTy->getAddressSpace() == 0;
3936   if (!IsNoWrapAddRec && !IsInBoundsGEP && !IsInAddressSpaceZero) {
3937     DEBUG(dbgs() << "LV: Bad stride - Pointer may wrap in the address space "
3938           << *Ptr << " SCEV: " << *PtrScev << "\n");
3939     return 0;
3940   }
3941
3942   // Check the step is constant.
3943   const SCEV *Step = AR->getStepRecurrence(*SE);
3944
3945   // Calculate the pointer stride and check if it is consecutive.
3946   const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
3947   if (!C) {
3948     DEBUG(dbgs() << "LV: Bad stride - Not a constant strided " << *Ptr <<
3949           " SCEV: " << *PtrScev << "\n");
3950     return 0;
3951   }
3952
3953   int64_t Size = DL->getTypeAllocSize(PtrTy->getElementType());
3954   const APInt &APStepVal = C->getValue()->getValue();
3955
3956   // Huge step value - give up.
3957   if (APStepVal.getBitWidth() > 64)
3958     return 0;
3959
3960   int64_t StepVal = APStepVal.getSExtValue();
3961
3962   // Strided access.
3963   int64_t Stride = StepVal / Size;
3964   int64_t Rem = StepVal % Size;
3965   if (Rem)
3966     return 0;
3967
3968   // If the SCEV could wrap but we have an inbounds gep with a unit stride we
3969   // know we can't "wrap around the address space". In case of address space
3970   // zero we know that this won't happen without triggering undefined behavior.
3971   if (!IsNoWrapAddRec && (IsInBoundsGEP || IsInAddressSpaceZero) &&
3972       Stride != 1 && Stride != -1)
3973     return 0;
3974
3975   return Stride;
3976 }
3977
3978 bool MemoryDepChecker::couldPreventStoreLoadForward(unsigned Distance,
3979                                                     unsigned TypeByteSize) {
3980   // If loads occur at a distance that is not a multiple of a feasible vector
3981   // factor store-load forwarding does not take place.
3982   // Positive dependences might cause troubles because vectorizing them might
3983   // prevent store-load forwarding making vectorized code run a lot slower.
3984   //   a[i] = a[i-3] ^ a[i-8];
3985   //   The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
3986   //   hence on your typical architecture store-load forwarding does not take
3987   //   place. Vectorizing in such cases does not make sense.
3988   // Store-load forwarding distance.
3989   const unsigned NumCyclesForStoreLoadThroughMemory = 8*TypeByteSize;
3990   // Maximum vector factor.
3991   unsigned MaxVFWithoutSLForwardIssues = MaxVectorWidth*TypeByteSize;
3992   if(MaxSafeDepDistBytes < MaxVFWithoutSLForwardIssues)
3993     MaxVFWithoutSLForwardIssues = MaxSafeDepDistBytes;
3994
3995   for (unsigned vf = 2*TypeByteSize; vf <= MaxVFWithoutSLForwardIssues;
3996        vf *= 2) {
3997     if (Distance % vf && Distance / vf < NumCyclesForStoreLoadThroughMemory) {
3998       MaxVFWithoutSLForwardIssues = (vf >>=1);
3999       break;
4000     }
4001   }
4002
4003   if (MaxVFWithoutSLForwardIssues< 2*TypeByteSize) {
4004     DEBUG(dbgs() << "LV: Distance " << Distance <<
4005           " that could cause a store-load forwarding conflict\n");
4006     return true;
4007   }
4008
4009   if (MaxVFWithoutSLForwardIssues < MaxSafeDepDistBytes &&
4010       MaxVFWithoutSLForwardIssues != MaxVectorWidth*TypeByteSize)
4011     MaxSafeDepDistBytes = MaxVFWithoutSLForwardIssues;
4012   return false;
4013 }
4014
4015 bool MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
4016                                    const MemAccessInfo &B, unsigned BIdx,
4017                                    ValueToValueMap &Strides) {
4018   assert (AIdx < BIdx && "Must pass arguments in program order");
4019
4020   Value *APtr = A.getPointer();
4021   Value *BPtr = B.getPointer();
4022   bool AIsWrite = A.getInt();
4023   bool BIsWrite = B.getInt();
4024
4025   // Two reads are independent.
4026   if (!AIsWrite && !BIsWrite)
4027     return false;
4028
4029   const SCEV *AScev = replaceSymbolicStrideSCEV(SE, Strides, APtr);
4030   const SCEV *BScev = replaceSymbolicStrideSCEV(SE, Strides, BPtr);
4031
4032   int StrideAPtr = isStridedPtr(SE, DL, APtr, InnermostLoop, Strides);
4033   int StrideBPtr = isStridedPtr(SE, DL, BPtr, InnermostLoop, Strides);
4034
4035   const SCEV *Src = AScev;
4036   const SCEV *Sink = BScev;
4037
4038   // If the induction step is negative we have to invert source and sink of the
4039   // dependence.
4040   if (StrideAPtr < 0) {
4041     //Src = BScev;
4042     //Sink = AScev;
4043     std::swap(APtr, BPtr);
4044     std::swap(Src, Sink);
4045     std::swap(AIsWrite, BIsWrite);
4046     std::swap(AIdx, BIdx);
4047     std::swap(StrideAPtr, StrideBPtr);
4048   }
4049
4050   const SCEV *Dist = SE->getMinusSCEV(Sink, Src);
4051
4052   DEBUG(dbgs() << "LV: Src Scev: " << *Src << "Sink Scev: " << *Sink
4053         << "(Induction step: " << StrideAPtr <<  ")\n");
4054   DEBUG(dbgs() << "LV: Distance for " << *InstMap[AIdx] << " to "
4055         << *InstMap[BIdx] << ": " << *Dist << "\n");
4056
4057   // Need consecutive accesses. We don't want to vectorize
4058   // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap in
4059   // the address space.
4060   if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr){
4061     DEBUG(dbgs() << "Non-consecutive pointer access\n");
4062     return true;
4063   }
4064
4065   const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist);
4066   if (!C) {
4067     DEBUG(dbgs() << "LV: Dependence because of non-constant distance\n");
4068     ShouldRetryWithRuntimeCheck = true;
4069     return true;
4070   }
4071
4072   Type *ATy = APtr->getType()->getPointerElementType();
4073   Type *BTy = BPtr->getType()->getPointerElementType();
4074   unsigned TypeByteSize = DL->getTypeAllocSize(ATy);
4075
4076   // Negative distances are not plausible dependencies.
4077   const APInt &Val = C->getValue()->getValue();
4078   if (Val.isNegative()) {
4079     bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
4080     if (IsTrueDataDependence &&
4081         (couldPreventStoreLoadForward(Val.abs().getZExtValue(), TypeByteSize) ||
4082          ATy != BTy))
4083       return true;
4084
4085     DEBUG(dbgs() << "LV: Dependence is negative: NoDep\n");
4086     return false;
4087   }
4088
4089   // Write to the same location with the same size.
4090   // Could be improved to assert type sizes are the same (i32 == float, etc).
4091   if (Val == 0) {
4092     if (ATy == BTy)
4093       return false;
4094     DEBUG(dbgs() << "LV: Zero dependence difference but different types\n");
4095     return true;
4096   }
4097
4098   assert(Val.isStrictlyPositive() && "Expect a positive value");
4099
4100   // Positive distance bigger than max vectorization factor.
4101   if (ATy != BTy) {
4102     DEBUG(dbgs() <<
4103           "LV: ReadWrite-Write positive dependency with different types\n");
4104     return false;
4105   }
4106
4107   unsigned Distance = (unsigned) Val.getZExtValue();
4108
4109   // Bail out early if passed-in parameters make vectorization not feasible.
4110   unsigned ForcedFactor = VectorizationFactor ? VectorizationFactor : 1;
4111   unsigned ForcedUnroll = VectorizationUnroll ? VectorizationUnroll : 1;
4112
4113   // The distance must be bigger than the size needed for a vectorized version
4114   // of the operation and the size of the vectorized operation must not be
4115   // bigger than the currrent maximum size.
4116   if (Distance < 2*TypeByteSize ||
4117       2*TypeByteSize > MaxSafeDepDistBytes ||
4118       Distance < TypeByteSize * ForcedUnroll * ForcedFactor) {
4119     DEBUG(dbgs() << "LV: Failure because of Positive distance "
4120         << Val.getSExtValue() << '\n');
4121     return true;
4122   }
4123
4124   MaxSafeDepDistBytes = Distance < MaxSafeDepDistBytes ?
4125     Distance : MaxSafeDepDistBytes;
4126
4127   bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
4128   if (IsTrueDataDependence &&
4129       couldPreventStoreLoadForward(Distance, TypeByteSize))
4130      return true;
4131
4132   DEBUG(dbgs() << "LV: Positive distance " << Val.getSExtValue() <<
4133         " with max VF = " << MaxSafeDepDistBytes / TypeByteSize << '\n');
4134
4135   return false;
4136 }
4137
4138 bool MemoryDepChecker::areDepsSafe(AccessAnalysis::DepCandidates &AccessSets,
4139                                    MemAccessInfoSet &CheckDeps,
4140                                    ValueToValueMap &Strides) {
4141
4142   MaxSafeDepDistBytes = -1U;
4143   while (!CheckDeps.empty()) {
4144     MemAccessInfo CurAccess = *CheckDeps.begin();
4145
4146     // Get the relevant memory access set.
4147     EquivalenceClasses<MemAccessInfo>::iterator I =
4148       AccessSets.findValue(AccessSets.getLeaderValue(CurAccess));
4149
4150     // Check accesses within this set.
4151     EquivalenceClasses<MemAccessInfo>::member_iterator AI, AE;
4152     AI = AccessSets.member_begin(I), AE = AccessSets.member_end();
4153
4154     // Check every access pair.
4155     while (AI != AE) {
4156       CheckDeps.erase(*AI);
4157       EquivalenceClasses<MemAccessInfo>::member_iterator OI = llvm::next(AI);
4158       while (OI != AE) {
4159         // Check every accessing instruction pair in program order.
4160         for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(),
4161              I1E = Accesses[*AI].end(); I1 != I1E; ++I1)
4162           for (std::vector<unsigned>::iterator I2 = Accesses[*OI].begin(),
4163                I2E = Accesses[*OI].end(); I2 != I2E; ++I2) {
4164             if (*I1 < *I2 && isDependent(*AI, *I1, *OI, *I2, Strides))
4165               return false;
4166             if (*I2 < *I1 && isDependent(*OI, *I2, *AI, *I1, Strides))
4167               return false;
4168           }
4169         ++OI;
4170       }
4171       AI++;
4172     }
4173   }
4174   return true;
4175 }
4176
4177 bool LoopVectorizationLegality::canVectorizeMemory() {
4178
4179   typedef SmallVector<Value*, 16> ValueVector;
4180   typedef SmallPtrSet<Value*, 16> ValueSet;
4181
4182   // Holds the Load and Store *instructions*.
4183   ValueVector Loads;
4184   ValueVector Stores;
4185
4186   // Holds all the different accesses in the loop.
4187   unsigned NumReads = 0;
4188   unsigned NumReadWrites = 0;
4189
4190   PtrRtCheck.Pointers.clear();
4191   PtrRtCheck.Need = false;
4192
4193   const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
4194   MemoryDepChecker DepChecker(SE, DL, TheLoop);
4195
4196   // For each block.
4197   for (Loop::block_iterator bb = TheLoop->block_begin(),
4198        be = TheLoop->block_end(); bb != be; ++bb) {
4199
4200     // Scan the BB and collect legal loads and stores.
4201     for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
4202          ++it) {
4203
4204       // If this is a load, save it. If this instruction can read from memory
4205       // but is not a load, then we quit. Notice that we don't handle function
4206       // calls that read or write.
4207       if (it->mayReadFromMemory()) {
4208         // Many math library functions read the rounding mode. We will only
4209         // vectorize a loop if it contains known function calls that don't set
4210         // the flag. Therefore, it is safe to ignore this read from memory.
4211         CallInst *Call = dyn_cast<CallInst>(it);
4212         if (Call && getIntrinsicIDForCall(Call, TLI))
4213           continue;
4214
4215         LoadInst *Ld = dyn_cast<LoadInst>(it);
4216         if (!Ld) return false;
4217         if (!Ld->isSimple() && !IsAnnotatedParallel) {
4218           DEBUG(dbgs() << "LV: Found a non-simple load.\n");
4219           return false;
4220         }
4221         Loads.push_back(Ld);
4222         DepChecker.addAccess(Ld);
4223         continue;
4224       }
4225
4226       // Save 'store' instructions. Abort if other instructions write to memory.
4227       if (it->mayWriteToMemory()) {
4228         StoreInst *St = dyn_cast<StoreInst>(it);
4229         if (!St) return false;
4230         if (!St->isSimple() && !IsAnnotatedParallel) {
4231           DEBUG(dbgs() << "LV: Found a non-simple store.\n");
4232           return false;
4233         }
4234         Stores.push_back(St);
4235         DepChecker.addAccess(St);
4236       }
4237     } // Next instr.
4238   } // Next block.
4239
4240   // Now we have two lists that hold the loads and the stores.
4241   // Next, we find the pointers that they use.
4242
4243   // Check if we see any stores. If there are no stores, then we don't
4244   // care if the pointers are *restrict*.
4245   if (!Stores.size()) {
4246     DEBUG(dbgs() << "LV: Found a read-only loop!\n");
4247     return true;
4248   }
4249
4250   AccessAnalysis::DepCandidates DependentAccesses;
4251   AccessAnalysis Accesses(DL, DependentAccesses);
4252
4253   // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
4254   // multiple times on the same object. If the ptr is accessed twice, once
4255   // for read and once for write, it will only appear once (on the write
4256   // list). This is okay, since we are going to check for conflicts between
4257   // writes and between reads and writes, but not between reads and reads.
4258   ValueSet Seen;
4259
4260   ValueVector::iterator I, IE;
4261   for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
4262     StoreInst *ST = cast<StoreInst>(*I);
4263     Value* Ptr = ST->getPointerOperand();
4264
4265     if (isUniform(Ptr)) {
4266       DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
4267       return false;
4268     }
4269
4270     // If we did *not* see this pointer before, insert it to  the read-write
4271     // list. At this phase it is only a 'write' list.
4272     if (Seen.insert(Ptr)) {
4273       ++NumReadWrites;
4274       Accesses.addStore(Ptr);
4275     }
4276   }
4277
4278   if (IsAnnotatedParallel) {
4279     DEBUG(dbgs()
4280           << "LV: A loop annotated parallel, ignore memory dependency "
4281           << "checks.\n");
4282     return true;
4283   }
4284
4285   for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
4286     LoadInst *LD = cast<LoadInst>(*I);
4287     Value* Ptr = LD->getPointerOperand();
4288     // If we did *not* see this pointer before, insert it to the
4289     // read list. If we *did* see it before, then it is already in
4290     // the read-write list. This allows us to vectorize expressions
4291     // such as A[i] += x;  Because the address of A[i] is a read-write
4292     // pointer. This only works if the index of A[i] is consecutive.
4293     // If the address of i is unknown (for example A[B[i]]) then we may
4294     // read a few words, modify, and write a few words, and some of the
4295     // words may be written to the same address.
4296     bool IsReadOnlyPtr = false;
4297     if (Seen.insert(Ptr) || !isStridedPtr(SE, DL, Ptr, TheLoop, Strides)) {
4298       ++NumReads;
4299       IsReadOnlyPtr = true;
4300     }
4301     Accesses.addLoad(Ptr, IsReadOnlyPtr);
4302   }
4303
4304   // If we write (or read-write) to a single destination and there are no
4305   // other reads in this loop then is it safe to vectorize.
4306   if (NumReadWrites == 1 && NumReads == 0) {
4307     DEBUG(dbgs() << "LV: Found a write-only loop!\n");
4308     return true;
4309   }
4310
4311   // Build dependence sets and check whether we need a runtime pointer bounds
4312   // check.
4313   Accesses.buildDependenceSets();
4314   bool NeedRTCheck = Accesses.isRTCheckNeeded();
4315
4316   // Find pointers with computable bounds. We are going to use this information
4317   // to place a runtime bound check.
4318   unsigned NumComparisons = 0;
4319   bool CanDoRT = false;
4320   if (NeedRTCheck)
4321     CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE, TheLoop,
4322                                        Strides);
4323
4324   DEBUG(dbgs() << "LV: We need to do " << NumComparisons <<
4325         " pointer comparisons.\n");
4326
4327   // If we only have one set of dependences to check pointers among we don't
4328   // need a runtime check.
4329   if (NumComparisons == 0 && NeedRTCheck)
4330     NeedRTCheck = false;
4331
4332   // Check that we did not collect too many pointers or found an unsizeable
4333   // pointer.
4334   if (!CanDoRT || NumComparisons > RuntimeMemoryCheckThreshold) {
4335     PtrRtCheck.reset();
4336     CanDoRT = false;
4337   }
4338
4339   if (CanDoRT) {
4340     DEBUG(dbgs() << "LV: We can perform a memory runtime check if needed.\n");
4341   }
4342
4343   if (NeedRTCheck && !CanDoRT) {
4344     DEBUG(dbgs() << "LV: We can't vectorize because we can't find " <<
4345           "the array bounds.\n");
4346     PtrRtCheck.reset();
4347     return false;
4348   }
4349
4350   PtrRtCheck.Need = NeedRTCheck;
4351
4352   bool CanVecMem = true;
4353   if (Accesses.isDependencyCheckNeeded()) {
4354     DEBUG(dbgs() << "LV: Checking memory dependencies\n");
4355     CanVecMem = DepChecker.areDepsSafe(
4356         DependentAccesses, Accesses.getDependenciesToCheck(), Strides);
4357     MaxSafeDepDistBytes = DepChecker.getMaxSafeDepDistBytes();
4358
4359     if (!CanVecMem && DepChecker.shouldRetryWithRuntimeCheck()) {
4360       DEBUG(dbgs() << "LV: Retrying with memory checks\n");
4361       NeedRTCheck = true;
4362
4363       // Clear the dependency checks. We assume they are not needed.
4364       Accesses.resetDepChecks();
4365
4366       PtrRtCheck.reset();
4367       PtrRtCheck.Need = true;
4368
4369       CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE,
4370                                          TheLoop, Strides, true);
4371       // Check that we did not collect too many pointers or found an unsizeable
4372       // pointer.
4373       if (!CanDoRT || NumComparisons > RuntimeMemoryCheckThreshold) {
4374         DEBUG(dbgs() << "LV: Can't vectorize with memory checks\n");
4375         PtrRtCheck.reset();
4376         return false;
4377       }
4378
4379       CanVecMem = true;
4380     }
4381   }
4382
4383   DEBUG(dbgs() << "LV: We" << (NeedRTCheck ? "" : " don't") <<
4384         " need a runtime memory check.\n");
4385
4386   return CanVecMem;
4387 }
4388
4389 static bool hasMultipleUsesOf(Instruction *I,
4390                               SmallPtrSet<Instruction *, 8> &Insts) {
4391   unsigned NumUses = 0;
4392   for(User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use) {
4393     if (Insts.count(dyn_cast<Instruction>(*Use)))
4394       ++NumUses;
4395     if (NumUses > 1)
4396       return true;
4397   }
4398
4399   return false;
4400 }
4401
4402 static bool areAllUsesIn(Instruction *I, SmallPtrSet<Instruction *, 8> &Set) {
4403   for(User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use)
4404     if (!Set.count(dyn_cast<Instruction>(*Use)))
4405       return false;
4406   return true;
4407 }
4408
4409 bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi,
4410                                                 ReductionKind Kind) {
4411   if (Phi->getNumIncomingValues() != 2)
4412     return false;
4413
4414   // Reduction variables are only found in the loop header block.
4415   if (Phi->getParent() != TheLoop->getHeader())
4416     return false;
4417
4418   // Obtain the reduction start value from the value that comes from the loop
4419   // preheader.
4420   Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
4421
4422   // ExitInstruction is the single value which is used outside the loop.
4423   // We only allow for a single reduction value to be used outside the loop.
4424   // This includes users of the reduction, variables (which form a cycle
4425   // which ends in the phi node).
4426   Instruction *ExitInstruction = 0;
4427   // Indicates that we found a reduction operation in our scan.
4428   bool FoundReduxOp = false;
4429
4430   // We start with the PHI node and scan for all of the users of this
4431   // instruction. All users must be instructions that can be used as reduction
4432   // variables (such as ADD). We must have a single out-of-block user. The cycle
4433   // must include the original PHI.
4434   bool FoundStartPHI = false;
4435
4436   // To recognize min/max patterns formed by a icmp select sequence, we store
4437   // the number of instruction we saw from the recognized min/max pattern,
4438   //  to make sure we only see exactly the two instructions.
4439   unsigned NumCmpSelectPatternInst = 0;
4440   ReductionInstDesc ReduxDesc(false, 0);
4441
4442   SmallPtrSet<Instruction *, 8> VisitedInsts;
4443   SmallVector<Instruction *, 8> Worklist;
4444   Worklist.push_back(Phi);
4445   VisitedInsts.insert(Phi);
4446
4447   // A value in the reduction can be used:
4448   //  - By the reduction:
4449   //      - Reduction operation:
4450   //        - One use of reduction value (safe).
4451   //        - Multiple use of reduction value (not safe).
4452   //      - PHI:
4453   //        - All uses of the PHI must be the reduction (safe).
4454   //        - Otherwise, not safe.
4455   //  - By one instruction outside of the loop (safe).
4456   //  - By further instructions outside of the loop (not safe).
4457   //  - By an instruction that is not part of the reduction (not safe).
4458   //    This is either:
4459   //      * An instruction type other than PHI or the reduction operation.
4460   //      * A PHI in the header other than the initial PHI.
4461   while (!Worklist.empty()) {
4462     Instruction *Cur = Worklist.back();
4463     Worklist.pop_back();
4464
4465     // No Users.
4466     // If the instruction has no users then this is a broken chain and can't be
4467     // a reduction variable.
4468     if (Cur->use_empty())
4469       return false;
4470
4471     bool IsAPhi = isa<PHINode>(Cur);
4472
4473     // A header PHI use other than the original PHI.
4474     if (Cur != Phi && IsAPhi && Cur->getParent() == Phi->getParent())
4475       return false;
4476
4477     // Reductions of instructions such as Div, and Sub is only possible if the
4478     // LHS is the reduction variable.
4479     if (!Cur->isCommutative() && !IsAPhi && !isa<SelectInst>(Cur) &&
4480         !isa<ICmpInst>(Cur) && !isa<FCmpInst>(Cur) &&
4481         !VisitedInsts.count(dyn_cast<Instruction>(Cur->getOperand(0))))
4482       return false;
4483
4484     // Any reduction instruction must be of one of the allowed kinds.
4485     ReduxDesc = isReductionInstr(Cur, Kind, ReduxDesc);
4486     if (!ReduxDesc.IsReduction)
4487       return false;
4488
4489     // A reduction operation must only have one use of the reduction value.
4490     if (!IsAPhi && Kind != RK_IntegerMinMax && Kind != RK_FloatMinMax &&
4491         hasMultipleUsesOf(Cur, VisitedInsts))
4492       return false;
4493
4494     // All inputs to a PHI node must be a reduction value.
4495     if(IsAPhi && Cur != Phi && !areAllUsesIn(Cur, VisitedInsts))
4496       return false;
4497
4498     if (Kind == RK_IntegerMinMax && (isa<ICmpInst>(Cur) ||
4499                                      isa<SelectInst>(Cur)))
4500       ++NumCmpSelectPatternInst;
4501     if (Kind == RK_FloatMinMax && (isa<FCmpInst>(Cur) ||
4502                                    isa<SelectInst>(Cur)))
4503       ++NumCmpSelectPatternInst;
4504
4505     // Check  whether we found a reduction operator.
4506     FoundReduxOp |= !IsAPhi;
4507
4508     // Process users of current instruction. Push non-PHI nodes after PHI nodes
4509     // onto the stack. This way we are going to have seen all inputs to PHI
4510     // nodes once we get to them.
4511     SmallVector<Instruction *, 8> NonPHIs;
4512     SmallVector<Instruction *, 8> PHIs;
4513     for (Value::use_iterator UI = Cur->use_begin(), E = Cur->use_end(); UI != E;
4514          ++UI) {
4515       Instruction *Usr = cast<Instruction>(*UI);
4516
4517       // Check if we found the exit user.
4518       BasicBlock *Parent = Usr->getParent();
4519       if (!TheLoop->contains(Parent)) {
4520         // Exit if you find multiple outside users or if the header phi node is
4521         // being used. In this case the user uses the value of the previous
4522         // iteration, in which case we would loose "VF-1" iterations of the
4523         // reduction operation if we vectorize.
4524         if (ExitInstruction != 0 || Cur == Phi)
4525           return false;
4526
4527         // The instruction used by an outside user must be the last instruction
4528         // before we feed back to the reduction phi. Otherwise, we loose VF-1
4529         // operations on the value.
4530         if (std::find(Phi->op_begin(), Phi->op_end(), Cur) == Phi->op_end())
4531          return false;
4532
4533         ExitInstruction = Cur;
4534         continue;
4535       }
4536
4537       // Process instructions only once (termination).
4538       if (VisitedInsts.insert(Usr)) {
4539         if (isa<PHINode>(Usr))
4540           PHIs.push_back(Usr);
4541         else
4542           NonPHIs.push_back(Usr);
4543       }
4544       // Remember that we completed the cycle.
4545       if (Usr == Phi)
4546         FoundStartPHI = true;
4547     }
4548     Worklist.append(PHIs.begin(), PHIs.end());
4549     Worklist.append(NonPHIs.begin(), NonPHIs.end());
4550   }
4551
4552   // This means we have seen one but not the other instruction of the
4553   // pattern or more than just a select and cmp.
4554   if ((Kind == RK_IntegerMinMax || Kind == RK_FloatMinMax) &&
4555       NumCmpSelectPatternInst != 2)
4556     return false;
4557
4558   if (!FoundStartPHI || !FoundReduxOp || !ExitInstruction)
4559     return false;
4560
4561   // We found a reduction var if we have reached the original phi node and we
4562   // only have a single instruction with out-of-loop users.
4563
4564   // This instruction is allowed to have out-of-loop users.
4565   AllowedExit.insert(ExitInstruction);
4566
4567   // Save the description of this reduction variable.
4568   ReductionDescriptor RD(RdxStart, ExitInstruction, Kind,
4569                          ReduxDesc.MinMaxKind);
4570   Reductions[Phi] = RD;
4571   // We've ended the cycle. This is a reduction variable if we have an
4572   // outside user and it has a binary op.
4573
4574   return true;
4575 }
4576
4577 /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
4578 /// pattern corresponding to a min(X, Y) or max(X, Y).
4579 LoopVectorizationLegality::ReductionInstDesc
4580 LoopVectorizationLegality::isMinMaxSelectCmpPattern(Instruction *I,
4581                                                     ReductionInstDesc &Prev) {
4582
4583   assert((isa<ICmpInst>(I) || isa<FCmpInst>(I) || isa<SelectInst>(I)) &&
4584          "Expect a select instruction");
4585   Instruction *Cmp = 0;
4586   SelectInst *Select = 0;
4587
4588   // We must handle the select(cmp()) as a single instruction. Advance to the
4589   // select.
4590   if ((Cmp = dyn_cast<ICmpInst>(I)) || (Cmp = dyn_cast<FCmpInst>(I))) {
4591     if (!Cmp->hasOneUse() || !(Select = dyn_cast<SelectInst>(*I->use_begin())))
4592       return ReductionInstDesc(false, I);
4593     return ReductionInstDesc(Select, Prev.MinMaxKind);
4594   }
4595
4596   // Only handle single use cases for now.
4597   if (!(Select = dyn_cast<SelectInst>(I)))
4598     return ReductionInstDesc(false, I);
4599   if (!(Cmp = dyn_cast<ICmpInst>(I->getOperand(0))) &&
4600       !(Cmp = dyn_cast<FCmpInst>(I->getOperand(0))))
4601     return ReductionInstDesc(false, I);
4602   if (!Cmp->hasOneUse())
4603     return ReductionInstDesc(false, I);
4604
4605   Value *CmpLeft;
4606   Value *CmpRight;
4607
4608   // Look for a min/max pattern.
4609   if (m_UMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4610     return ReductionInstDesc(Select, MRK_UIntMin);
4611   else if (m_UMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4612     return ReductionInstDesc(Select, MRK_UIntMax);
4613   else if (m_SMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4614     return ReductionInstDesc(Select, MRK_SIntMax);
4615   else if (m_SMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4616     return ReductionInstDesc(Select, MRK_SIntMin);
4617   else if (m_OrdFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4618     return ReductionInstDesc(Select, MRK_FloatMin);
4619   else if (m_OrdFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4620     return ReductionInstDesc(Select, MRK_FloatMax);
4621   else if (m_UnordFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4622     return ReductionInstDesc(Select, MRK_FloatMin);
4623   else if (m_UnordFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
4624     return ReductionInstDesc(Select, MRK_FloatMax);
4625
4626   return ReductionInstDesc(false, I);
4627 }
4628
4629 LoopVectorizationLegality::ReductionInstDesc
4630 LoopVectorizationLegality::isReductionInstr(Instruction *I,
4631                                             ReductionKind Kind,
4632                                             ReductionInstDesc &Prev) {
4633   bool FP = I->getType()->isFloatingPointTy();
4634   bool FastMath = (FP && I->isCommutative() && I->isAssociative());
4635   switch (I->getOpcode()) {
4636   default:
4637     return ReductionInstDesc(false, I);
4638   case Instruction::PHI:
4639       if (FP && (Kind != RK_FloatMult && Kind != RK_FloatAdd &&
4640                  Kind != RK_FloatMinMax))
4641         return ReductionInstDesc(false, I);
4642     return ReductionInstDesc(I, Prev.MinMaxKind);
4643   case Instruction::Sub:
4644   case Instruction::Add:
4645     return ReductionInstDesc(Kind == RK_IntegerAdd, I);
4646   case Instruction::Mul:
4647     return ReductionInstDesc(Kind == RK_IntegerMult, I);
4648   case Instruction::And:
4649     return ReductionInstDesc(Kind == RK_IntegerAnd, I);
4650   case Instruction::Or:
4651     return ReductionInstDesc(Kind == RK_IntegerOr, I);
4652   case Instruction::Xor:
4653     return ReductionInstDesc(Kind == RK_IntegerXor, I);
4654   case Instruction::FMul:
4655     return ReductionInstDesc(Kind == RK_FloatMult && FastMath, I);
4656   case Instruction::FAdd:
4657     return ReductionInstDesc(Kind == RK_FloatAdd && FastMath, I);
4658   case Instruction::FCmp:
4659   case Instruction::ICmp:
4660   case Instruction::Select:
4661     if (Kind != RK_IntegerMinMax &&
4662         (!HasFunNoNaNAttr || Kind != RK_FloatMinMax))
4663       return ReductionInstDesc(false, I);
4664     return isMinMaxSelectCmpPattern(I, Prev);
4665   }
4666 }
4667
4668 LoopVectorizationLegality::InductionKind
4669 LoopVectorizationLegality::isInductionVariable(PHINode *Phi) {
4670   Type *PhiTy = Phi->getType();
4671   // We only handle integer and pointer inductions variables.
4672   if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
4673     return IK_NoInduction;
4674
4675   // Check that the PHI is consecutive.
4676   const SCEV *PhiScev = SE->getSCEV(Phi);
4677   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
4678   if (!AR) {
4679     DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
4680     return IK_NoInduction;
4681   }
4682   const SCEV *Step = AR->getStepRecurrence(*SE);
4683
4684   // Integer inductions need to have a stride of one.
4685   if (PhiTy->isIntegerTy()) {
4686     if (Step->isOne())
4687       return IK_IntInduction;
4688     if (Step->isAllOnesValue())
4689       return IK_ReverseIntInduction;
4690     return IK_NoInduction;
4691   }
4692
4693   // Calculate the pointer stride and check if it is consecutive.
4694   const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
4695   if (!C)
4696     return IK_NoInduction;
4697
4698   assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
4699   uint64_t Size = DL->getTypeAllocSize(PhiTy->getPointerElementType());
4700   if (C->getValue()->equalsInt(Size))
4701     return IK_PtrInduction;
4702   else if (C->getValue()->equalsInt(0 - Size))
4703     return IK_ReversePtrInduction;
4704
4705   return IK_NoInduction;
4706 }
4707
4708 bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
4709   Value *In0 = const_cast<Value*>(V);
4710   PHINode *PN = dyn_cast_or_null<PHINode>(In0);
4711   if (!PN)
4712     return false;
4713
4714   return Inductions.count(PN);
4715 }
4716
4717 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB)  {
4718   assert(TheLoop->contains(BB) && "Unknown block used");
4719
4720   // Blocks that do not dominate the latch need predication.
4721   BasicBlock* Latch = TheLoop->getLoopLatch();
4722   return !DT->dominates(BB, Latch);
4723 }
4724
4725 bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB,
4726                                             SmallPtrSet<Value *, 8>& SafePtrs) {
4727   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
4728     // We might be able to hoist the load.
4729     if (it->mayReadFromMemory()) {
4730       LoadInst *LI = dyn_cast<LoadInst>(it);
4731       if (!LI || !SafePtrs.count(LI->getPointerOperand()))
4732         return false;
4733     }
4734
4735     // We don't predicate stores at the moment.
4736     if (it->mayWriteToMemory() || it->mayThrow())
4737       return false;
4738
4739     // Check that we don't have a constant expression that can trap as operand.
4740     for (Instruction::op_iterator OI = it->op_begin(), OE = it->op_end();
4741          OI != OE; ++OI) {
4742       if (Constant *C = dyn_cast<Constant>(*OI))
4743         if (C->canTrap())
4744           return false;
4745     }
4746
4747     // The instructions below can trap.
4748     switch (it->getOpcode()) {
4749     default: continue;
4750     case Instruction::UDiv:
4751     case Instruction::SDiv:
4752     case Instruction::URem:
4753     case Instruction::SRem:
4754              return false;
4755     }
4756   }
4757
4758   return true;
4759 }
4760
4761 LoopVectorizationCostModel::VectorizationFactor
4762 LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize,
4763                                                       unsigned UserVF) {
4764   // Width 1 means no vectorize
4765   VectorizationFactor Factor = { 1U, 0U };
4766   if (OptForSize && Legal->getRuntimePointerCheck()->Need) {
4767     DEBUG(dbgs() << "LV: Aborting. Runtime ptr check is required in Os.\n");
4768     return Factor;
4769   }
4770
4771   // Find the trip count.
4772   unsigned TC = SE->getSmallConstantTripCount(TheLoop, TheLoop->getLoopLatch());
4773   DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
4774
4775   unsigned WidestType = getWidestType();
4776   unsigned WidestRegister = TTI.getRegisterBitWidth(true);
4777   unsigned MaxSafeDepDist = -1U;
4778   if (Legal->getMaxSafeDepDistBytes() != -1U)
4779     MaxSafeDepDist = Legal->getMaxSafeDepDistBytes() * 8;
4780   WidestRegister = ((WidestRegister < MaxSafeDepDist) ?
4781                     WidestRegister : MaxSafeDepDist);
4782   unsigned MaxVectorSize = WidestRegister / WidestType;
4783   DEBUG(dbgs() << "LV: The Widest type: " << WidestType << " bits.\n");
4784   DEBUG(dbgs() << "LV: The Widest register is: "
4785           << WidestRegister << " bits.\n");
4786
4787   if (MaxVectorSize == 0) {
4788     DEBUG(dbgs() << "LV: The target has no vector registers.\n");
4789     MaxVectorSize = 1;
4790   }
4791
4792   assert(MaxVectorSize <= 32 && "Did not expect to pack so many elements"
4793          " into one vector!");
4794
4795   unsigned VF = MaxVectorSize;
4796
4797   // If we optimize the program for size, avoid creating the tail loop.
4798   if (OptForSize) {
4799     // If we are unable to calculate the trip count then don't try to vectorize.
4800     if (TC < 2) {
4801       DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
4802       return Factor;
4803     }
4804
4805     // Find the maximum SIMD width that can fit within the trip count.
4806     VF = TC % MaxVectorSize;
4807
4808     if (VF == 0)
4809       VF = MaxVectorSize;
4810
4811     // If the trip count that we found modulo the vectorization factor is not
4812     // zero then we require a tail.
4813     if (VF < 2) {
4814       DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
4815       return Factor;
4816     }
4817   }
4818
4819   if (UserVF != 0) {
4820     assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
4821     DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
4822
4823     Factor.Width = UserVF;
4824     return Factor;
4825   }
4826
4827   float Cost = expectedCost(1);
4828   unsigned Width = 1;
4829   DEBUG(dbgs() << "LV: Scalar loop costs: " << (int)Cost << ".\n");
4830   for (unsigned i=2; i <= VF; i*=2) {
4831     // Notice that the vector loop needs to be executed less times, so
4832     // we need to divide the cost of the vector loops by the width of
4833     // the vector elements.
4834     float VectorCost = expectedCost(i) / (float)i;
4835     DEBUG(dbgs() << "LV: Vector loop of width " << i << " costs: " <<
4836           (int)VectorCost << ".\n");
4837     if (VectorCost < Cost) {
4838       Cost = VectorCost;
4839       Width = i;
4840     }
4841   }
4842
4843   DEBUG(dbgs() << "LV: Selecting VF = : "<< Width << ".\n");
4844   Factor.Width = Width;
4845   Factor.Cost = Width * Cost;
4846   return Factor;
4847 }
4848
4849 unsigned LoopVectorizationCostModel::getWidestType() {
4850   unsigned MaxWidth = 8;
4851
4852   // For each block.
4853   for (Loop::block_iterator bb = TheLoop->block_begin(),
4854        be = TheLoop->block_end(); bb != be; ++bb) {
4855     BasicBlock *BB = *bb;
4856
4857     // For each instruction in the loop.
4858     for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
4859       Type *T = it->getType();
4860
4861       // Only examine Loads, Stores and PHINodes.
4862       if (!isa<LoadInst>(it) && !isa<StoreInst>(it) && !isa<PHINode>(it))
4863         continue;
4864
4865       // Examine PHI nodes that are reduction variables.
4866       if (PHINode *PN = dyn_cast<PHINode>(it))
4867         if (!Legal->getReductionVars()->count(PN))
4868           continue;
4869
4870       // Examine the stored values.
4871       if (StoreInst *ST = dyn_cast<StoreInst>(it))
4872         T = ST->getValueOperand()->getType();
4873
4874       // Ignore loaded pointer types and stored pointer types that are not
4875       // consecutive. However, we do want to take consecutive stores/loads of
4876       // pointer vectors into account.
4877       if (T->isPointerTy() && !isConsecutiveLoadOrStore(it))
4878         continue;
4879
4880       MaxWidth = std::max(MaxWidth,
4881                           (unsigned)DL->getTypeSizeInBits(T->getScalarType()));
4882     }
4883   }
4884
4885   return MaxWidth;
4886 }
4887
4888 unsigned
4889 LoopVectorizationCostModel::selectUnrollFactor(bool OptForSize,
4890                                                unsigned UserUF,
4891                                                unsigned VF,
4892                                                unsigned LoopCost) {
4893
4894   // -- The unroll heuristics --
4895   // We unroll the loop in order to expose ILP and reduce the loop overhead.
4896   // There are many micro-architectural considerations that we can't predict
4897   // at this level. For example frontend pressure (on decode or fetch) due to
4898   // code size, or the number and capabilities of the execution ports.
4899   //
4900   // We use the following heuristics to select the unroll factor:
4901   // 1. If the code has reductions the we unroll in order to break the cross
4902   // iteration dependency.
4903   // 2. If the loop is really small then we unroll in order to reduce the loop
4904   // overhead.
4905   // 3. We don't unroll if we think that we will spill registers to memory due
4906   // to the increased register pressure.
4907
4908   // Use the user preference, unless 'auto' is selected.
4909   if (UserUF != 0)
4910     return UserUF;
4911
4912   // When we optimize for size we don't unroll.
4913   if (OptForSize)
4914     return 1;
4915
4916   // We used the distance for the unroll factor.
4917   if (Legal->getMaxSafeDepDistBytes() != -1U)
4918     return 1;
4919
4920   // Do not unroll loops with a relatively small trip count.
4921   unsigned TC = SE->getSmallConstantTripCount(TheLoop,
4922                                               TheLoop->getLoopLatch());
4923   if (TC > 1 && TC < TinyTripCountUnrollThreshold)
4924     return 1;
4925
4926   unsigned TargetVectorRegisters = TTI.getNumberOfRegisters(true);
4927   DEBUG(dbgs() << "LV: The target has " << TargetVectorRegisters <<
4928         " vector registers\n");
4929
4930   LoopVectorizationCostModel::RegisterUsage R = calculateRegisterUsage();
4931   // We divide by these constants so assume that we have at least one
4932   // instruction that uses at least one register.
4933   R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
4934   R.NumInstructions = std::max(R.NumInstructions, 1U);
4935
4936   // We calculate the unroll factor using the following formula.
4937   // Subtract the number of loop invariants from the number of available
4938   // registers. These registers are used by all of the unrolled instances.
4939   // Next, divide the remaining registers by the number of registers that is
4940   // required by the loop, in order to estimate how many parallel instances
4941   // fit without causing spills.
4942   unsigned UF = (TargetVectorRegisters - R.LoopInvariantRegs) / R.MaxLocalUsers;
4943
4944   // Clamp the unroll factor ranges to reasonable factors.
4945   unsigned MaxUnrollSize = TTI.getMaximumUnrollFactor();
4946
4947   // If we did not calculate the cost for VF (because the user selected the VF)
4948   // then we calculate the cost of VF here.
4949   if (LoopCost == 0)
4950     LoopCost = expectedCost(VF);
4951
4952   // Clamp the calculated UF to be between the 1 and the max unroll factor
4953   // that the target allows.
4954   if (UF > MaxUnrollSize)
4955     UF = MaxUnrollSize;
4956   else if (UF < 1)
4957     UF = 1;
4958
4959   bool HasReductions = Legal->getReductionVars()->size();
4960
4961   // Decide if we want to unroll if we decided that it is legal to vectorize
4962   // but not profitable.
4963   if (VF == 1) {
4964     if (TheLoop->getNumBlocks() > 1 || !HasReductions ||
4965         LoopCost > SmallLoopCost)
4966       return 1;
4967
4968     return UF;
4969   }
4970
4971   if (HasReductions) {
4972     DEBUG(dbgs() << "LV: Unrolling because of reductions.\n");
4973     return UF;
4974   }
4975
4976   // We want to unroll tiny loops in order to reduce the loop overhead.
4977   // We assume that the cost overhead is 1 and we use the cost model
4978   // to estimate the cost of the loop and unroll until the cost of the
4979   // loop overhead is about 5% of the cost of the loop.
4980   DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n');
4981   if (LoopCost < SmallLoopCost) {
4982     DEBUG(dbgs() << "LV: Unrolling to reduce branch cost.\n");
4983     unsigned NewUF = SmallLoopCost / (LoopCost + 1);
4984     return std::min(NewUF, UF);
4985   }
4986
4987   DEBUG(dbgs() << "LV: Not Unrolling.\n");
4988   return 1;
4989 }
4990
4991 LoopVectorizationCostModel::RegisterUsage
4992 LoopVectorizationCostModel::calculateRegisterUsage() {
4993   // This function calculates the register usage by measuring the highest number
4994   // of values that are alive at a single location. Obviously, this is a very
4995   // rough estimation. We scan the loop in a topological order in order and
4996   // assign a number to each instruction. We use RPO to ensure that defs are
4997   // met before their users. We assume that each instruction that has in-loop
4998   // users starts an interval. We record every time that an in-loop value is
4999   // used, so we have a list of the first and last occurrences of each
5000   // instruction. Next, we transpose this data structure into a multi map that
5001   // holds the list of intervals that *end* at a specific location. This multi
5002   // map allows us to perform a linear search. We scan the instructions linearly
5003   // and record each time that a new interval starts, by placing it in a set.
5004   // If we find this value in the multi-map then we remove it from the set.
5005   // The max register usage is the maximum size of the set.
5006   // We also search for instructions that are defined outside the loop, but are
5007   // used inside the loop. We need this number separately from the max-interval
5008   // usage number because when we unroll, loop-invariant values do not take
5009   // more register.
5010   LoopBlocksDFS DFS(TheLoop);
5011   DFS.perform(LI);
5012
5013   RegisterUsage R;
5014   R.NumInstructions = 0;
5015
5016   // Each 'key' in the map opens a new interval. The values
5017   // of the map are the index of the 'last seen' usage of the
5018   // instruction that is the key.
5019   typedef DenseMap<Instruction*, unsigned> IntervalMap;
5020   // Maps instruction to its index.
5021   DenseMap<unsigned, Instruction*> IdxToInstr;
5022   // Marks the end of each interval.
5023   IntervalMap EndPoint;
5024   // Saves the list of instruction indices that are used in the loop.
5025   SmallSet<Instruction*, 8> Ends;
5026   // Saves the list of values that are used in the loop but are
5027   // defined outside the loop, such as arguments and constants.
5028   SmallPtrSet<Value*, 8> LoopInvariants;
5029
5030   unsigned Index = 0;
5031   for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
5032        be = DFS.endRPO(); bb != be; ++bb) {
5033     R.NumInstructions += (*bb)->size();
5034     for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
5035          ++it) {
5036       Instruction *I = it;
5037       IdxToInstr[Index++] = I;
5038
5039       // Save the end location of each USE.
5040       for (unsigned i = 0; i < I->getNumOperands(); ++i) {
5041         Value *U = I->getOperand(i);
5042         Instruction *Instr = dyn_cast<Instruction>(U);
5043
5044         // Ignore non-instruction values such as arguments, constants, etc.
5045         if (!Instr) continue;
5046
5047         // If this instruction is outside the loop then record it and continue.
5048         if (!TheLoop->contains(Instr)) {
5049           LoopInvariants.insert(Instr);
5050           continue;
5051         }
5052
5053         // Overwrite previous end points.
5054         EndPoint[Instr] = Index;
5055         Ends.insert(Instr);
5056       }
5057     }
5058   }
5059
5060   // Saves the list of intervals that end with the index in 'key'.
5061   typedef SmallVector<Instruction*, 2> InstrList;
5062   DenseMap<unsigned, InstrList> TransposeEnds;
5063
5064   // Transpose the EndPoints to a list of values that end at each index.
5065   for (IntervalMap::iterator it = EndPoint.begin(), e = EndPoint.end();
5066        it != e; ++it)
5067     TransposeEnds[it->second].push_back(it->first);
5068
5069   SmallSet<Instruction*, 8> OpenIntervals;
5070   unsigned MaxUsage = 0;
5071
5072
5073   DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
5074   for (unsigned int i = 0; i < Index; ++i) {
5075     Instruction *I = IdxToInstr[i];
5076     // Ignore instructions that are never used within the loop.
5077     if (!Ends.count(I)) continue;
5078
5079     // Remove all of the instructions that end at this location.
5080     InstrList &List = TransposeEnds[i];
5081     for (unsigned int j=0, e = List.size(); j < e; ++j)
5082       OpenIntervals.erase(List[j]);
5083
5084     // Count the number of live interals.
5085     MaxUsage = std::max(MaxUsage, OpenIntervals.size());
5086
5087     DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # " <<
5088           OpenIntervals.size() << '\n');
5089
5090     // Add the current instruction to the list of open intervals.
5091     OpenIntervals.insert(I);
5092   }
5093
5094   unsigned Invariant = LoopInvariants.size();
5095   DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsage << '\n');
5096   DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << '\n');
5097   DEBUG(dbgs() << "LV(REG): LoopSize: " << R.NumInstructions << '\n');
5098
5099   R.LoopInvariantRegs = Invariant;
5100   R.MaxLocalUsers = MaxUsage;
5101   return R;
5102 }
5103
5104 unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
5105   unsigned Cost = 0;
5106
5107   // For each block.
5108   for (Loop::block_iterator bb = TheLoop->block_begin(),
5109        be = TheLoop->block_end(); bb != be; ++bb) {
5110     unsigned BlockCost = 0;
5111     BasicBlock *BB = *bb;
5112
5113     // For each instruction in the old loop.
5114     for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
5115       // Skip dbg intrinsics.
5116       if (isa<DbgInfoIntrinsic>(it))
5117         continue;
5118
5119       unsigned C = getInstructionCost(it, VF);
5120       BlockCost += C;
5121       DEBUG(dbgs() << "LV: Found an estimated cost of " << C << " for VF " <<
5122             VF << " For instruction: " << *it << '\n');
5123     }
5124
5125     // We assume that if-converted blocks have a 50% chance of being executed.
5126     // When the code is scalar then some of the blocks are avoided due to CF.
5127     // When the code is vectorized we execute all code paths.
5128     if (VF == 1 && Legal->blockNeedsPredication(*bb))
5129       BlockCost /= 2;
5130
5131     Cost += BlockCost;
5132   }
5133
5134   return Cost;
5135 }
5136
5137 /// \brief Check whether the address computation for a non-consecutive memory
5138 /// access looks like an unlikely candidate for being merged into the indexing
5139 /// mode.
5140 ///
5141 /// We look for a GEP which has one index that is an induction variable and all
5142 /// other indices are loop invariant. If the stride of this access is also
5143 /// within a small bound we decide that this address computation can likely be
5144 /// merged into the addressing mode.
5145 /// In all other cases, we identify the address computation as complex.
5146 static bool isLikelyComplexAddressComputation(Value *Ptr,
5147                                               LoopVectorizationLegality *Legal,
5148                                               ScalarEvolution *SE,
5149                                               const Loop *TheLoop) {
5150   GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
5151   if (!Gep)
5152     return true;
5153
5154   // We are looking for a gep with all loop invariant indices except for one
5155   // which should be an induction variable.
5156   unsigned NumOperands = Gep->getNumOperands();
5157   for (unsigned i = 1; i < NumOperands; ++i) {
5158     Value *Opd = Gep->getOperand(i);
5159     if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
5160         !Legal->isInductionVariable(Opd))
5161       return true;
5162   }
5163
5164   // Now we know we have a GEP ptr, %inv, %ind, %inv. Make sure that the step
5165   // can likely be merged into the address computation.
5166   unsigned MaxMergeDistance = 64;
5167
5168   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Ptr));
5169   if (!AddRec)
5170     return true;
5171
5172   // Check the step is constant.
5173   const SCEV *Step = AddRec->getStepRecurrence(*SE);
5174   // Calculate the pointer stride and check if it is consecutive.
5175   const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
5176   if (!C)
5177     return true;
5178
5179   const APInt &APStepVal = C->getValue()->getValue();
5180
5181   // Huge step value - give up.
5182   if (APStepVal.getBitWidth() > 64)
5183     return true;
5184
5185   int64_t StepVal = APStepVal.getSExtValue();
5186
5187   return StepVal > MaxMergeDistance;
5188 }
5189
5190 static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
5191   if (Legal->hasStride(I->getOperand(0)) || Legal->hasStride(I->getOperand(1)))
5192     return true;
5193   return false;
5194 }
5195
5196 unsigned
5197 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
5198   // If we know that this instruction will remain uniform, check the cost of
5199   // the scalar version.
5200   if (Legal->isUniformAfterVectorization(I))
5201     VF = 1;
5202
5203   Type *RetTy = I->getType();
5204   Type *VectorTy = ToVectorTy(RetTy, VF);
5205
5206   // TODO: We need to estimate the cost of intrinsic calls.
5207   switch (I->getOpcode()) {
5208   case Instruction::GetElementPtr:
5209     // We mark this instruction as zero-cost because the cost of GEPs in
5210     // vectorized code depends on whether the corresponding memory instruction
5211     // is scalarized or not. Therefore, we handle GEPs with the memory
5212     // instruction cost.
5213     return 0;
5214   case Instruction::Br: {
5215     return TTI.getCFInstrCost(I->getOpcode());
5216   }
5217   case Instruction::PHI:
5218     //TODO: IF-converted IFs become selects.
5219     return 0;
5220   case Instruction::Add:
5221   case Instruction::FAdd:
5222   case Instruction::Sub:
5223   case Instruction::FSub:
5224   case Instruction::Mul:
5225   case Instruction::FMul:
5226   case Instruction::UDiv:
5227   case Instruction::SDiv:
5228   case Instruction::FDiv:
5229   case Instruction::URem:
5230   case Instruction::SRem:
5231   case Instruction::FRem:
5232   case Instruction::Shl:
5233   case Instruction::LShr:
5234   case Instruction::AShr:
5235   case Instruction::And:
5236   case Instruction::Or:
5237   case Instruction::Xor: {
5238     // Since we will replace the stride by 1 the multiplication should go away.
5239     if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
5240       return 0;
5241     // Certain instructions can be cheaper to vectorize if they have a constant
5242     // second vector operand. One example of this are shifts on x86.
5243     TargetTransformInfo::OperandValueKind Op1VK =
5244       TargetTransformInfo::OK_AnyValue;
5245     TargetTransformInfo::OperandValueKind Op2VK =
5246       TargetTransformInfo::OK_AnyValue;
5247
5248     if (isa<ConstantInt>(I->getOperand(1)))
5249       Op2VK = TargetTransformInfo::OK_UniformConstantValue;
5250
5251     return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy, Op1VK, Op2VK);
5252   }
5253   case Instruction::Select: {
5254     SelectInst *SI = cast<SelectInst>(I);
5255     const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
5256     bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
5257     Type *CondTy = SI->getCondition()->getType();
5258     if (!ScalarCond)
5259       CondTy = VectorType::get(CondTy, VF);
5260
5261     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
5262   }
5263   case Instruction::ICmp:
5264   case Instruction::FCmp: {
5265     Type *ValTy = I->getOperand(0)->getType();
5266     VectorTy = ToVectorTy(ValTy, VF);
5267     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy);
5268   }
5269   case Instruction::Store:
5270   case Instruction::Load: {
5271     StoreInst *SI = dyn_cast<StoreInst>(I);
5272     LoadInst *LI = dyn_cast<LoadInst>(I);
5273     Type *ValTy = (SI ? SI->getValueOperand()->getType() :
5274                    LI->getType());
5275     VectorTy = ToVectorTy(ValTy, VF);
5276
5277     unsigned Alignment = SI ? SI->getAlignment() : LI->getAlignment();
5278     unsigned AS = SI ? SI->getPointerAddressSpace() :
5279       LI->getPointerAddressSpace();
5280     Value *Ptr = SI ? SI->getPointerOperand() : LI->getPointerOperand();
5281     // We add the cost of address computation here instead of with the gep
5282     // instruction because only here we know whether the operation is
5283     // scalarized.
5284     if (VF == 1)
5285       return TTI.getAddressComputationCost(VectorTy) +
5286         TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
5287
5288     // Scalarized loads/stores.
5289     int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
5290     bool Reverse = ConsecutiveStride < 0;
5291     unsigned ScalarAllocatedSize = DL->getTypeAllocSize(ValTy);
5292     unsigned VectorElementSize = DL->getTypeStoreSize(VectorTy)/VF;
5293     if (!ConsecutiveStride || ScalarAllocatedSize != VectorElementSize) {
5294       bool IsComplexComputation =
5295         isLikelyComplexAddressComputation(Ptr, Legal, SE, TheLoop);
5296       unsigned Cost = 0;
5297       // The cost of extracting from the value vector and pointer vector.
5298       Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
5299       for (unsigned i = 0; i < VF; ++i) {
5300         //  The cost of extracting the pointer operand.
5301         Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
5302         // In case of STORE, the cost of ExtractElement from the vector.
5303         // In case of LOAD, the cost of InsertElement into the returned
5304         // vector.
5305         Cost += TTI.getVectorInstrCost(SI ? Instruction::ExtractElement :
5306                                             Instruction::InsertElement,
5307                                             VectorTy, i);
5308       }
5309
5310       // The cost of the scalar loads/stores.
5311       Cost += VF * TTI.getAddressComputationCost(PtrTy, IsComplexComputation);
5312       Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(),
5313                                        Alignment, AS);
5314       return Cost;
5315     }
5316
5317     // Wide load/stores.
5318     unsigned Cost = TTI.getAddressComputationCost(VectorTy);
5319     Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
5320
5321     if (Reverse)
5322       Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
5323                                   VectorTy, 0);
5324     return Cost;
5325   }
5326   case Instruction::ZExt:
5327   case Instruction::SExt:
5328   case Instruction::FPToUI:
5329   case Instruction::FPToSI:
5330   case Instruction::FPExt:
5331   case Instruction::PtrToInt:
5332   case Instruction::IntToPtr:
5333   case Instruction::SIToFP:
5334   case Instruction::UIToFP:
5335   case Instruction::Trunc:
5336   case Instruction::FPTrunc:
5337   case Instruction::BitCast: {
5338     // We optimize the truncation of induction variable.
5339     // The cost of these is the same as the scalar operation.
5340     if (I->getOpcode() == Instruction::Trunc &&
5341         Legal->isInductionVariable(I->getOperand(0)))
5342       return TTI.getCastInstrCost(I->getOpcode(), I->getType(),
5343                                   I->getOperand(0)->getType());
5344
5345     Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
5346     return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
5347   }
5348   case Instruction::Call: {
5349     CallInst *CI = cast<CallInst>(I);
5350     Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
5351     assert(ID && "Not an intrinsic call!");
5352     Type *RetTy = ToVectorTy(CI->getType(), VF);
5353     SmallVector<Type*, 4> Tys;
5354     for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
5355       Tys.push_back(ToVectorTy(CI->getArgOperand(i)->getType(), VF));
5356     return TTI.getIntrinsicInstrCost(ID, RetTy, Tys);
5357   }
5358   default: {
5359     // We are scalarizing the instruction. Return the cost of the scalar
5360     // instruction, plus the cost of insert and extract into vector
5361     // elements, times the vector width.
5362     unsigned Cost = 0;
5363
5364     if (!RetTy->isVoidTy() && VF != 1) {
5365       unsigned InsCost = TTI.getVectorInstrCost(Instruction::InsertElement,
5366                                                 VectorTy);
5367       unsigned ExtCost = TTI.getVectorInstrCost(Instruction::ExtractElement,
5368                                                 VectorTy);
5369
5370       // The cost of inserting the results plus extracting each one of the
5371       // operands.
5372       Cost += VF * (InsCost + ExtCost * I->getNumOperands());
5373     }
5374
5375     // The cost of executing VF copies of the scalar instruction. This opcode
5376     // is unknown. Assume that it is the same as 'mul'.
5377     Cost += VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy);
5378     return Cost;
5379   }
5380   }// end of switch.
5381 }
5382
5383 Type* LoopVectorizationCostModel::ToVectorTy(Type *Scalar, unsigned VF) {
5384   if (Scalar->isVoidTy() || VF == 1)
5385     return Scalar;
5386   return VectorType::get(Scalar, VF);
5387 }
5388
5389 char LoopVectorize::ID = 0;
5390 static const char lv_name[] = "Loop Vectorization";
5391 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
5392 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
5393 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
5394 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
5395 INITIALIZE_PASS_DEPENDENCY(LCSSA)
5396 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
5397 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
5398 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
5399
5400 namespace llvm {
5401   Pass *createLoopVectorizePass(bool NoUnrolling, bool AlwaysVectorize) {
5402     return new LoopVectorize(NoUnrolling, AlwaysVectorize);
5403   }
5404 }
5405
5406 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
5407   // Check for a store.
5408   if (StoreInst *ST = dyn_cast<StoreInst>(Inst))
5409     return Legal->isConsecutivePtr(ST->getPointerOperand()) != 0;
5410
5411   // Check for a load.
5412   if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
5413     return Legal->isConsecutivePtr(LI->getPointerOperand()) != 0;
5414
5415   return false;
5416 }
5417
5418
5419 void InnerLoopUnroller::scalarizeInstruction(Instruction *Instr) {
5420   assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
5421   // Holds vector parameters or scalars, in case of uniform vals.
5422   SmallVector<VectorParts, 4> Params;
5423
5424   setDebugLocFromInst(Builder, Instr);
5425
5426   // Find all of the vectorized parameters.
5427   for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
5428     Value *SrcOp = Instr->getOperand(op);
5429
5430     // If we are accessing the old induction variable, use the new one.
5431     if (SrcOp == OldInduction) {
5432       Params.push_back(getVectorValue(SrcOp));
5433       continue;
5434     }
5435
5436     // Try using previously calculated values.
5437     Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
5438
5439     // If the src is an instruction that appeared earlier in the basic block
5440     // then it should already be vectorized.
5441     if (SrcInst && OrigLoop->contains(SrcInst)) {
5442       assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
5443       // The parameter is a vector value from earlier.
5444       Params.push_back(WidenMap.get(SrcInst));
5445     } else {
5446       // The parameter is a scalar from outside the loop. Maybe even a constant.
5447       VectorParts Scalars;
5448       Scalars.append(UF, SrcOp);
5449       Params.push_back(Scalars);
5450     }
5451   }
5452
5453   assert(Params.size() == Instr->getNumOperands() &&
5454          "Invalid number of operands");
5455
5456   // Does this instruction return a value ?
5457   bool IsVoidRetTy = Instr->getType()->isVoidTy();
5458
5459   Value *UndefVec = IsVoidRetTy ? 0 :
5460   UndefValue::get(Instr->getType());
5461   // Create a new entry in the WidenMap and initialize it to Undef or Null.
5462   VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
5463
5464   // For each vector unroll 'part':
5465   for (unsigned Part = 0; Part < UF; ++Part) {
5466     // For each scalar that we create:
5467
5468     Instruction *Cloned = Instr->clone();
5469       if (!IsVoidRetTy)
5470         Cloned->setName(Instr->getName() + ".cloned");
5471       // Replace the operands of the cloned instructions with extracted scalars.
5472       for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
5473         Value *Op = Params[op][Part];
5474         Cloned->setOperand(op, Op);
5475       }
5476
5477       // Place the cloned scalar in the new loop.
5478       Builder.Insert(Cloned);
5479
5480       // If the original scalar returns a value we need to place it in a vector
5481       // so that future users will be able to use it.
5482       if (!IsVoidRetTy)
5483         VecResults[Part] = Cloned;
5484   }
5485 }
5486
5487 void InnerLoopUnroller::vectorizeMemoryInstruction(Instruction *Instr) {
5488   return scalarizeInstruction(Instr);
5489 }
5490
5491 Value *InnerLoopUnroller::reverseVector(Value *Vec) {
5492   return Vec;
5493 }
5494
5495 Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) {
5496   return V;
5497 }
5498
5499 Value *InnerLoopUnroller::getConsecutiveVector(Value* Val, int StartIdx,
5500                                                bool Negate) {
5501   // When unrolling and the VF is 1, we only need to add a simple scalar.
5502   Type *ITy = Val->getType();
5503   assert(!ITy->isVectorTy() && "Val must be a scalar");
5504   Constant *C = ConstantInt::get(ITy, StartIdx, Negate);
5505   return Builder.CreateAdd(Val, C, "induction");
5506 }
5507