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