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