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