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