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