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