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