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