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