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