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