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