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