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