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