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