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