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