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