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