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