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