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