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