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