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