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