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