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