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