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