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