]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/Transforms/Vectorize/LoopVectorize.cpp
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r304659, and update
[FreeBSD/FreeBSD.git] / contrib / llvm / 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 // The interleaved access vectorization is based on the paper:
38 //  Dorit Nuzman, Ira Rosen and Ayal Zaks.  Auto-Vectorization of Interleaved
39 //  Data for SIMD
40 //
41 // Other ideas/concepts are from:
42 //  A. Zaks and D. Nuzman. Autovectorization in GCC-two years later.
43 //
44 //  S. Maleki, Y. Gao, M. Garzaran, T. Wong and D. Padua.  An Evaluation of
45 //  Vectorizing Compilers.
46 //
47 //===----------------------------------------------------------------------===//
48
49 #include "llvm/Transforms/Vectorize/LoopVectorize.h"
50 #include "llvm/ADT/DenseMap.h"
51 #include "llvm/ADT/Hashing.h"
52 #include "llvm/ADT/MapVector.h"
53 #include "llvm/ADT/Optional.h"
54 #include "llvm/ADT/SCCIterator.h"
55 #include "llvm/ADT/SetVector.h"
56 #include "llvm/ADT/SmallPtrSet.h"
57 #include "llvm/ADT/SmallSet.h"
58 #include "llvm/ADT/SmallVector.h"
59 #include "llvm/ADT/Statistic.h"
60 #include "llvm/ADT/StringExtras.h"
61 #include "llvm/Analysis/CodeMetrics.h"
62 #include "llvm/Analysis/GlobalsModRef.h"
63 #include "llvm/Analysis/LoopInfo.h"
64 #include "llvm/Analysis/LoopIterator.h"
65 #include "llvm/Analysis/LoopPass.h"
66 #include "llvm/Analysis/ScalarEvolutionExpander.h"
67 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
68 #include "llvm/Analysis/ValueTracking.h"
69 #include "llvm/Analysis/VectorUtils.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/User.h"
85 #include "llvm/IR/Value.h"
86 #include "llvm/IR/ValueHandle.h"
87 #include "llvm/IR/Verifier.h"
88 #include "llvm/Pass.h"
89 #include "llvm/Support/BranchProbability.h"
90 #include "llvm/Support/CommandLine.h"
91 #include "llvm/Support/Debug.h"
92 #include "llvm/Support/raw_ostream.h"
93 #include "llvm/Transforms/Scalar.h"
94 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
95 #include "llvm/Transforms/Utils/Local.h"
96 #include "llvm/Transforms/Utils/LoopSimplify.h"
97 #include "llvm/Transforms/Utils/LoopUtils.h"
98 #include "llvm/Transforms/Utils/LoopVersioning.h"
99 #include "llvm/Transforms/Vectorize.h"
100 #include <algorithm>
101 #include <map>
102 #include <tuple>
103
104 using namespace llvm;
105 using namespace llvm::PatternMatch;
106
107 #define LV_NAME "loop-vectorize"
108 #define DEBUG_TYPE LV_NAME
109
110 STATISTIC(LoopsVectorized, "Number of loops vectorized");
111 STATISTIC(LoopsAnalyzed, "Number of loops analyzed for vectorization");
112
113 static cl::opt<bool>
114     EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
115                        cl::desc("Enable if-conversion during vectorization."));
116
117 /// We don't vectorize loops with a known constant trip count below this number.
118 static cl::opt<unsigned> TinyTripCountVectorThreshold(
119     "vectorizer-min-trip-count", cl::init(16), cl::Hidden,
120     cl::desc("Don't vectorize loops with a constant "
121              "trip count that is smaller than this "
122              "value."));
123
124 static cl::opt<bool> MaximizeBandwidth(
125     "vectorizer-maximize-bandwidth", cl::init(false), cl::Hidden,
126     cl::desc("Maximize bandwidth when selecting vectorization factor which "
127              "will be determined by the smallest type in loop."));
128
129 static cl::opt<bool> EnableInterleavedMemAccesses(
130     "enable-interleaved-mem-accesses", cl::init(false), cl::Hidden,
131     cl::desc("Enable vectorization on interleaved memory accesses in a loop"));
132
133 /// Maximum factor for an interleaved memory access.
134 static cl::opt<unsigned> MaxInterleaveGroupFactor(
135     "max-interleave-group-factor", cl::Hidden,
136     cl::desc("Maximum factor for an interleaved access group (default = 8)"),
137     cl::init(8));
138
139 /// We don't interleave loops with a known constant trip count below this
140 /// number.
141 static const unsigned TinyTripCountInterleaveThreshold = 128;
142
143 static cl::opt<unsigned> ForceTargetNumScalarRegs(
144     "force-target-num-scalar-regs", cl::init(0), cl::Hidden,
145     cl::desc("A flag that overrides the target's number of scalar registers."));
146
147 static cl::opt<unsigned> ForceTargetNumVectorRegs(
148     "force-target-num-vector-regs", cl::init(0), cl::Hidden,
149     cl::desc("A flag that overrides the target's number of vector registers."));
150
151 /// Maximum vectorization interleave count.
152 static const unsigned MaxInterleaveFactor = 16;
153
154 static cl::opt<unsigned> ForceTargetMaxScalarInterleaveFactor(
155     "force-target-max-scalar-interleave", cl::init(0), cl::Hidden,
156     cl::desc("A flag that overrides the target's max interleave factor for "
157              "scalar loops."));
158
159 static cl::opt<unsigned> ForceTargetMaxVectorInterleaveFactor(
160     "force-target-max-vector-interleave", cl::init(0), cl::Hidden,
161     cl::desc("A flag that overrides the target's max interleave factor for "
162              "vectorized loops."));
163
164 static cl::opt<unsigned> ForceTargetInstructionCost(
165     "force-target-instruction-cost", cl::init(0), cl::Hidden,
166     cl::desc("A flag that overrides the target's expected cost for "
167              "an instruction to a single constant value. Mostly "
168              "useful for getting consistent testing."));
169
170 static cl::opt<unsigned> SmallLoopCost(
171     "small-loop-cost", cl::init(20), cl::Hidden,
172     cl::desc(
173         "The cost of a loop that is considered 'small' by the interleaver."));
174
175 static cl::opt<bool> LoopVectorizeWithBlockFrequency(
176     "loop-vectorize-with-block-frequency", cl::init(false), cl::Hidden,
177     cl::desc("Enable the use of the block frequency analysis to access PGO "
178              "heuristics minimizing code growth in cold regions and being more "
179              "aggressive in hot regions."));
180
181 // Runtime interleave loops for load/store throughput.
182 static cl::opt<bool> EnableLoadStoreRuntimeInterleave(
183     "enable-loadstore-runtime-interleave", cl::init(true), cl::Hidden,
184     cl::desc(
185         "Enable runtime interleaving until load/store ports are saturated"));
186
187 /// The number of stores in a loop that are allowed to need predication.
188 static cl::opt<unsigned> NumberOfStoresToPredicate(
189     "vectorize-num-stores-pred", cl::init(1), cl::Hidden,
190     cl::desc("Max number of stores to be predicated behind an if."));
191
192 static cl::opt<bool> EnableIndVarRegisterHeur(
193     "enable-ind-var-reg-heur", cl::init(true), cl::Hidden,
194     cl::desc("Count the induction variable only once when interleaving"));
195
196 static cl::opt<bool> EnableCondStoresVectorization(
197     "enable-cond-stores-vec", cl::init(true), cl::Hidden,
198     cl::desc("Enable if predication of stores during vectorization."));
199
200 static cl::opt<unsigned> MaxNestedScalarReductionIC(
201     "max-nested-scalar-reduction-interleave", cl::init(2), cl::Hidden,
202     cl::desc("The maximum interleave count to use when interleaving a scalar "
203              "reduction in a nested loop."));
204
205 static cl::opt<unsigned> PragmaVectorizeMemoryCheckThreshold(
206     "pragma-vectorize-memory-check-threshold", cl::init(128), cl::Hidden,
207     cl::desc("The maximum allowed number of runtime memory checks with a "
208              "vectorize(enable) pragma."));
209
210 static cl::opt<unsigned> VectorizeSCEVCheckThreshold(
211     "vectorize-scev-check-threshold", cl::init(16), cl::Hidden,
212     cl::desc("The maximum number of SCEV checks allowed."));
213
214 static cl::opt<unsigned> PragmaVectorizeSCEVCheckThreshold(
215     "pragma-vectorize-scev-check-threshold", cl::init(128), cl::Hidden,
216     cl::desc("The maximum number of SCEV checks allowed with a "
217              "vectorize(enable) pragma"));
218
219 /// Create an analysis remark that explains why vectorization failed
220 ///
221 /// \p PassName is the name of the pass (e.g. can be AlwaysPrint).  \p
222 /// RemarkName is the identifier for the remark.  If \p I is passed it is an
223 /// instruction that prevents vectorization.  Otherwise \p TheLoop is used for
224 /// the location of the remark.  \return the remark object that can be
225 /// streamed to.
226 static OptimizationRemarkAnalysis
227 createMissedAnalysis(const char *PassName, StringRef RemarkName, Loop *TheLoop,
228                      Instruction *I = nullptr) {
229   Value *CodeRegion = TheLoop->getHeader();
230   DebugLoc DL = TheLoop->getStartLoc();
231
232   if (I) {
233     CodeRegion = I->getParent();
234     // If there is no debug location attached to the instruction, revert back to
235     // using the loop's.
236     if (I->getDebugLoc())
237       DL = I->getDebugLoc();
238   }
239
240   OptimizationRemarkAnalysis R(PassName, RemarkName, DL, CodeRegion);
241   R << "loop not vectorized: ";
242   return R;
243 }
244
245 namespace {
246
247 // Forward declarations.
248 class LoopVectorizeHints;
249 class LoopVectorizationLegality;
250 class LoopVectorizationCostModel;
251 class LoopVectorizationRequirements;
252
253 /// Returns true if the given loop body has a cycle, excluding the loop
254 /// itself.
255 static bool hasCyclesInLoopBody(const Loop &L) {
256   if (!L.empty())
257     return true;
258
259   for (const auto &SCC :
260        make_range(scc_iterator<Loop, LoopBodyTraits>::begin(L),
261                   scc_iterator<Loop, LoopBodyTraits>::end(L))) {
262     if (SCC.size() > 1) {
263       DEBUG(dbgs() << "LVL: Detected a cycle in the loop body:\n");
264       DEBUG(L.dump());
265       return true;
266     }
267   }
268   return false;
269 }
270
271 /// A helper function for converting Scalar types to vector types.
272 /// If the incoming type is void, we return void. If the VF is 1, we return
273 /// the scalar type.
274 static Type *ToVectorTy(Type *Scalar, unsigned VF) {
275   if (Scalar->isVoidTy() || VF == 1)
276     return Scalar;
277   return VectorType::get(Scalar, VF);
278 }
279
280 // FIXME: The following helper functions have multiple implementations
281 // in the project. They can be effectively organized in a common Load/Store
282 // utilities unit.
283
284 /// A helper function that returns the pointer operand of a load or store
285 /// instruction.
286 static Value *getPointerOperand(Value *I) {
287   if (auto *LI = dyn_cast<LoadInst>(I))
288     return LI->getPointerOperand();
289   if (auto *SI = dyn_cast<StoreInst>(I))
290     return SI->getPointerOperand();
291   return nullptr;
292 }
293
294 /// A helper function that returns the type of loaded or stored value.
295 static Type *getMemInstValueType(Value *I) {
296   assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
297          "Expected Load or Store instruction");
298   if (auto *LI = dyn_cast<LoadInst>(I))
299     return LI->getType();
300   return cast<StoreInst>(I)->getValueOperand()->getType();
301 }
302
303 /// A helper function that returns the alignment of load or store instruction.
304 static unsigned getMemInstAlignment(Value *I) {
305   assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
306          "Expected Load or Store instruction");
307   if (auto *LI = dyn_cast<LoadInst>(I))
308     return LI->getAlignment();
309   return cast<StoreInst>(I)->getAlignment();
310 }
311
312 /// A helper function that returns the address space of the pointer operand of
313 /// load or store instruction.
314 static unsigned getMemInstAddressSpace(Value *I) {
315   assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
316          "Expected Load or Store instruction");
317   if (auto *LI = dyn_cast<LoadInst>(I))
318     return LI->getPointerAddressSpace();
319   return cast<StoreInst>(I)->getPointerAddressSpace();
320 }
321
322 /// A helper function that returns true if the given type is irregular. The
323 /// type is irregular if its allocated size doesn't equal the store size of an
324 /// element of the corresponding vector type at the given vectorization factor.
325 static bool hasIrregularType(Type *Ty, const DataLayout &DL, unsigned VF) {
326
327   // Determine if an array of VF elements of type Ty is "bitcast compatible"
328   // with a <VF x Ty> vector.
329   if (VF > 1) {
330     auto *VectorTy = VectorType::get(Ty, VF);
331     return VF * DL.getTypeAllocSize(Ty) != DL.getTypeStoreSize(VectorTy);
332   }
333
334   // If the vectorization factor is one, we just check if an array of type Ty
335   // requires padding between elements.
336   return DL.getTypeAllocSizeInBits(Ty) != DL.getTypeSizeInBits(Ty);
337 }
338
339 /// A helper function that returns the reciprocal of the block probability of
340 /// predicated blocks. If we return X, we are assuming the predicated block
341 /// will execute once for for every X iterations of the loop header.
342 ///
343 /// TODO: We should use actual block probability here, if available. Currently,
344 ///       we always assume predicated blocks have a 50% chance of executing.
345 static unsigned getReciprocalPredBlockProb() { return 2; }
346
347 /// A helper function that adds a 'fast' flag to floating-point operations.
348 static Value *addFastMathFlag(Value *V) {
349   if (isa<FPMathOperator>(V)) {
350     FastMathFlags Flags;
351     Flags.setUnsafeAlgebra();
352     cast<Instruction>(V)->setFastMathFlags(Flags);
353   }
354   return V;
355 }
356
357 /// A helper function that returns an integer or floating-point constant with
358 /// value C.
359 static Constant *getSignedIntOrFpConstant(Type *Ty, int64_t C) {
360   return Ty->isIntegerTy() ? ConstantInt::getSigned(Ty, C)
361                            : ConstantFP::get(Ty, C);
362 }
363
364 /// InnerLoopVectorizer vectorizes loops which contain only one basic
365 /// block to a specified vectorization factor (VF).
366 /// This class performs the widening of scalars into vectors, or multiple
367 /// scalars. This class also implements the following features:
368 /// * It inserts an epilogue loop for handling loops that don't have iteration
369 ///   counts that are known to be a multiple of the vectorization factor.
370 /// * It handles the code generation for reduction variables.
371 /// * Scalarization (implementation using scalars) of un-vectorizable
372 ///   instructions.
373 /// InnerLoopVectorizer does not perform any vectorization-legality
374 /// checks, and relies on the caller to check for the different legality
375 /// aspects. The InnerLoopVectorizer relies on the
376 /// LoopVectorizationLegality class to provide information about the induction
377 /// and reduction variables that were found to a given vectorization factor.
378 class InnerLoopVectorizer {
379 public:
380   InnerLoopVectorizer(Loop *OrigLoop, PredicatedScalarEvolution &PSE,
381                       LoopInfo *LI, DominatorTree *DT,
382                       const TargetLibraryInfo *TLI,
383                       const TargetTransformInfo *TTI, AssumptionCache *AC,
384                       OptimizationRemarkEmitter *ORE, unsigned VecWidth,
385                       unsigned UnrollFactor, LoopVectorizationLegality *LVL,
386                       LoopVectorizationCostModel *CM)
387       : OrigLoop(OrigLoop), PSE(PSE), LI(LI), DT(DT), TLI(TLI), TTI(TTI),
388         AC(AC), ORE(ORE), VF(VecWidth), UF(UnrollFactor),
389         Builder(PSE.getSE()->getContext()), Induction(nullptr),
390         OldInduction(nullptr), VectorLoopValueMap(UnrollFactor, VecWidth),
391         TripCount(nullptr), VectorTripCount(nullptr), Legal(LVL), Cost(CM),
392         AddedSafetyChecks(false) {}
393
394   /// Create a new empty loop. Unlink the old loop and connect the new one.
395   void createVectorizedLoopSkeleton();
396
397   /// Vectorize a single instruction within the innermost loop.
398   void vectorizeInstruction(Instruction &I);
399
400   /// Fix the vectorized code, taking care of header phi's, live-outs, and more.
401   void fixVectorizedLoop();
402
403   // Return true if any runtime check is added.
404   bool areSafetyChecksAdded() { return AddedSafetyChecks; }
405
406   virtual ~InnerLoopVectorizer() {}
407
408 protected:
409   /// A small list of PHINodes.
410   typedef SmallVector<PHINode *, 4> PhiVector;
411
412   /// A type for vectorized values in the new loop. Each value from the
413   /// original loop, when vectorized, is represented by UF vector values in the
414   /// new unrolled loop, where UF is the unroll factor.
415   typedef SmallVector<Value *, 2> VectorParts;
416
417   /// A type for scalarized values in the new loop. Each value from the
418   /// original loop, when scalarized, is represented by UF x VF scalar values
419   /// in the new unrolled loop, where UF is the unroll factor and VF is the
420   /// vectorization factor.
421   typedef SmallVector<SmallVector<Value *, 4>, 2> ScalarParts;
422
423   // When we if-convert we need to create edge masks. We have to cache values
424   // so that we don't end up with exponential recursion/IR.
425   typedef DenseMap<std::pair<BasicBlock *, BasicBlock *>, VectorParts>
426       EdgeMaskCacheTy;
427   typedef DenseMap<BasicBlock *, VectorParts> BlockMaskCacheTy;
428
429   /// Set up the values of the IVs correctly when exiting the vector loop.
430   void fixupIVUsers(PHINode *OrigPhi, const InductionDescriptor &II,
431                     Value *CountRoundDown, Value *EndValue,
432                     BasicBlock *MiddleBlock);
433
434   /// Create a new induction variable inside L.
435   PHINode *createInductionVariable(Loop *L, Value *Start, Value *End,
436                                    Value *Step, Instruction *DL);
437
438   /// Handle all cross-iteration phis in the header.
439   void fixCrossIterationPHIs();
440
441   /// Fix a first-order recurrence. This is the second phase of vectorizing
442   /// this phi node.
443   void fixFirstOrderRecurrence(PHINode *Phi);
444
445   /// Fix a reduction cross-iteration phi. This is the second phase of
446   /// vectorizing this phi node.
447   void fixReduction(PHINode *Phi);
448
449   /// \brief The Loop exit block may have single value PHI nodes with some
450   /// incoming value. While vectorizing we only handled real values
451   /// that were defined inside the loop and we should have one value for
452   /// each predecessor of its parent basic block. See PR14725.
453   void fixLCSSAPHIs();
454
455   /// Iteratively sink the scalarized operands of a predicated instruction into
456   /// the block that was created for it.
457   void sinkScalarOperands(Instruction *PredInst);
458
459   /// Predicate conditional instructions that require predication on their
460   /// respective conditions.
461   void predicateInstructions();
462
463   /// Shrinks vector element sizes to the smallest bitwidth they can be legally
464   /// represented as.
465   void truncateToMinimalBitwidths();
466
467   /// A helper function that computes the predicate of the block BB, assuming
468   /// that the header block of the loop is set to True. It returns the *entry*
469   /// mask for the block BB.
470   VectorParts createBlockInMask(BasicBlock *BB);
471   /// A helper function that computes the predicate of the edge between SRC
472   /// and DST.
473   VectorParts createEdgeMask(BasicBlock *Src, BasicBlock *Dst);
474
475   /// Vectorize a single PHINode in a block. This method handles the induction
476   /// variable canonicalization. It supports both VF = 1 for unrolled loops and
477   /// arbitrary length vectors.
478   void widenPHIInstruction(Instruction *PN, unsigned UF, unsigned VF);
479
480   /// Insert the new loop to the loop hierarchy and pass manager
481   /// and update the analysis passes.
482   void updateAnalysis();
483
484   /// This instruction is un-vectorizable. Implement it as a sequence
485   /// of scalars. If \p IfPredicateInstr is true we need to 'hide' each
486   /// scalarized instruction behind an if block predicated on the control
487   /// dependence of the instruction.
488   virtual void scalarizeInstruction(Instruction *Instr,
489                                     bool IfPredicateInstr = false);
490
491   /// Vectorize Load and Store instructions,
492   virtual void vectorizeMemoryInstruction(Instruction *Instr);
493
494   /// Create a broadcast instruction. This method generates a broadcast
495   /// instruction (shuffle) for loop invariant values and for the induction
496   /// value. If this is the induction variable then we extend it to N, N+1, ...
497   /// this is needed because each iteration in the loop corresponds to a SIMD
498   /// element.
499   virtual Value *getBroadcastInstrs(Value *V);
500
501   /// This function adds (StartIdx, StartIdx + Step, StartIdx + 2*Step, ...)
502   /// to each vector element of Val. The sequence starts at StartIndex.
503   /// \p Opcode is relevant for FP induction variable.
504   virtual Value *getStepVector(Value *Val, int StartIdx, Value *Step,
505                                Instruction::BinaryOps Opcode =
506                                Instruction::BinaryOpsEnd);
507
508   /// Compute scalar induction steps. \p ScalarIV is the scalar induction
509   /// variable on which to base the steps, \p Step is the size of the step, and
510   /// \p EntryVal is the value from the original loop that maps to the steps.
511   /// Note that \p EntryVal doesn't have to be an induction variable (e.g., it
512   /// can be a truncate instruction).
513   void buildScalarSteps(Value *ScalarIV, Value *Step, Value *EntryVal,
514                         const InductionDescriptor &ID);
515
516   /// Create a vector induction phi node based on an existing scalar one. \p
517   /// EntryVal is the value from the original loop that maps to the vector phi
518   /// node, and \p Step is the loop-invariant step. If \p EntryVal is a
519   /// truncate instruction, instead of widening the original IV, we widen a
520   /// version of the IV truncated to \p EntryVal's type.
521   void createVectorIntOrFpInductionPHI(const InductionDescriptor &II,
522                                        Value *Step, Instruction *EntryVal);
523
524   /// Widen an integer or floating-point induction variable \p IV. If \p Trunc
525   /// is provided, the integer induction variable will first be truncated to
526   /// the corresponding type.
527   void widenIntOrFpInduction(PHINode *IV, TruncInst *Trunc = nullptr);
528
529   /// Returns true if an instruction \p I should be scalarized instead of
530   /// vectorized for the chosen vectorization factor.
531   bool shouldScalarizeInstruction(Instruction *I) const;
532
533   /// Returns true if we should generate a scalar version of \p IV.
534   bool needsScalarInduction(Instruction *IV) const;
535
536   /// Return a constant reference to the VectorParts corresponding to \p V from
537   /// the original loop. If the value has already been vectorized, the
538   /// corresponding vector entry in VectorLoopValueMap is returned. If,
539   /// however, the value has a scalar entry in VectorLoopValueMap, we construct
540   /// new vector values on-demand by inserting the scalar values into vectors
541   /// with an insertelement sequence. If the value has been neither vectorized
542   /// nor scalarized, it must be loop invariant, so we simply broadcast the
543   /// value into vectors.
544   const VectorParts &getVectorValue(Value *V);
545
546   /// Return a value in the new loop corresponding to \p V from the original
547   /// loop at unroll index \p Part and vector index \p Lane. If the value has
548   /// been vectorized but not scalarized, the necessary extractelement
549   /// instruction will be generated.
550   Value *getScalarValue(Value *V, unsigned Part, unsigned Lane);
551
552   /// Try to vectorize the interleaved access group that \p Instr belongs to.
553   void vectorizeInterleaveGroup(Instruction *Instr);
554
555   /// Generate a shuffle sequence that will reverse the vector Vec.
556   virtual Value *reverseVector(Value *Vec);
557
558   /// Returns (and creates if needed) the original loop trip count.
559   Value *getOrCreateTripCount(Loop *NewLoop);
560
561   /// Returns (and creates if needed) the trip count of the widened loop.
562   Value *getOrCreateVectorTripCount(Loop *NewLoop);
563
564   /// Emit a bypass check to see if the trip count would overflow, or we
565   /// wouldn't have enough iterations to execute one vector loop.
566   void emitMinimumIterationCountCheck(Loop *L, BasicBlock *Bypass);
567   /// Emit a bypass check to see if the vector trip count is nonzero.
568   void emitVectorLoopEnteredCheck(Loop *L, BasicBlock *Bypass);
569   /// Emit a bypass check to see if all of the SCEV assumptions we've
570   /// had to make are correct.
571   void emitSCEVChecks(Loop *L, BasicBlock *Bypass);
572   /// Emit bypass checks to check any memory assumptions we may have made.
573   void emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass);
574
575   /// Add additional metadata to \p To that was not present on \p Orig.
576   ///
577   /// Currently this is used to add the noalias annotations based on the
578   /// inserted memchecks.  Use this for instructions that are *cloned* into the
579   /// vector loop.
580   void addNewMetadata(Instruction *To, const Instruction *Orig);
581
582   /// Add metadata from one instruction to another.
583   ///
584   /// This includes both the original MDs from \p From and additional ones (\see
585   /// addNewMetadata).  Use this for *newly created* instructions in the vector
586   /// loop.
587   void addMetadata(Instruction *To, Instruction *From);
588
589   /// \brief Similar to the previous function but it adds the metadata to a
590   /// vector of instructions.
591   void addMetadata(ArrayRef<Value *> To, Instruction *From);
592
593   /// \brief Set the debug location in the builder using the debug location in
594   /// the instruction.
595   void setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr);
596
597   /// This is a helper class for maintaining vectorization state. It's used for
598   /// mapping values from the original loop to their corresponding values in
599   /// the new loop. Two mappings are maintained: one for vectorized values and
600   /// one for scalarized values. Vectorized values are represented with UF
601   /// vector values in the new loop, and scalarized values are represented with
602   /// UF x VF scalar values in the new loop. UF and VF are the unroll and
603   /// vectorization factors, respectively.
604   ///
605   /// Entries can be added to either map with initVector and initScalar, which
606   /// initialize and return a constant reference to the new entry. If a
607   /// non-constant reference to a vector entry is required, getVector can be
608   /// used to retrieve a mutable entry. We currently directly modify the mapped
609   /// values during "fix-up" operations that occur once the first phase of
610   /// widening is complete. These operations include type truncation and the
611   /// second phase of recurrence widening.
612   ///
613   /// Otherwise, entries from either map should be accessed using the
614   /// getVectorValue or getScalarValue functions from InnerLoopVectorizer.
615   /// getVectorValue and getScalarValue coordinate to generate a vector or
616   /// scalar value on-demand if one is not yet available. When vectorizing a
617   /// loop, we visit the definition of an instruction before its uses. When
618   /// visiting the definition, we either vectorize or scalarize the
619   /// instruction, creating an entry for it in the corresponding map. (In some
620   /// cases, such as induction variables, we will create both vector and scalar
621   /// entries.) Then, as we encounter uses of the definition, we derive values
622   /// for each scalar or vector use unless such a value is already available.
623   /// For example, if we scalarize a definition and one of its uses is vector,
624   /// we build the required vector on-demand with an insertelement sequence
625   /// when visiting the use. Otherwise, if the use is scalar, we can use the
626   /// existing scalar definition.
627   struct ValueMap {
628
629     /// Construct an empty map with the given unroll and vectorization factors.
630     ValueMap(unsigned UnrollFactor, unsigned VecWidth)
631         : UF(UnrollFactor), VF(VecWidth) {
632       // The unroll and vectorization factors are only used in asserts builds
633       // to verify map entries are sized appropriately.
634       (void)UF;
635       (void)VF;
636     }
637
638     /// \return True if the map has a vector entry for \p Key.
639     bool hasVector(Value *Key) const { return VectorMapStorage.count(Key); }
640
641     /// \return True if the map has a scalar entry for \p Key.
642     bool hasScalar(Value *Key) const { return ScalarMapStorage.count(Key); }
643
644     /// \brief Map \p Key to the given VectorParts \p Entry, and return a
645     /// constant reference to the new vector map entry. The given key should
646     /// not already be in the map, and the given VectorParts should be
647     /// correctly sized for the current unroll factor.
648     const VectorParts &initVector(Value *Key, const VectorParts &Entry) {
649       assert(!hasVector(Key) && "Vector entry already initialized");
650       assert(Entry.size() == UF && "VectorParts has wrong dimensions");
651       VectorMapStorage[Key] = Entry;
652       return VectorMapStorage[Key];
653     }
654
655     /// \brief Map \p Key to the given ScalarParts \p Entry, and return a
656     /// constant reference to the new scalar map entry. The given key should
657     /// not already be in the map, and the given ScalarParts should be
658     /// correctly sized for the current unroll and vectorization factors.
659     const ScalarParts &initScalar(Value *Key, const ScalarParts &Entry) {
660       assert(!hasScalar(Key) && "Scalar entry already initialized");
661       assert(Entry.size() == UF &&
662              all_of(make_range(Entry.begin(), Entry.end()),
663                     [&](const SmallVectorImpl<Value *> &Values) -> bool {
664                       return Values.size() == VF;
665                     }) &&
666              "ScalarParts has wrong dimensions");
667       ScalarMapStorage[Key] = Entry;
668       return ScalarMapStorage[Key];
669     }
670
671     /// \return A reference to the vector map entry corresponding to \p Key.
672     /// The key should already be in the map. This function should only be used
673     /// when it's necessary to update values that have already been vectorized.
674     /// This is the case for "fix-up" operations including type truncation and
675     /// the second phase of recurrence vectorization. If a non-const reference
676     /// isn't required, getVectorValue should be used instead.
677     VectorParts &getVector(Value *Key) {
678       assert(hasVector(Key) && "Vector entry not initialized");
679       return VectorMapStorage.find(Key)->second;
680     }
681
682     /// Retrieve an entry from the vector or scalar maps. The preferred way to
683     /// access an existing mapped entry is with getVectorValue or
684     /// getScalarValue from InnerLoopVectorizer. Until those functions can be
685     /// moved inside ValueMap, we have to declare them as friends.
686     friend const VectorParts &InnerLoopVectorizer::getVectorValue(Value *V);
687     friend Value *InnerLoopVectorizer::getScalarValue(Value *V, unsigned Part,
688                                                       unsigned Lane);
689
690   private:
691     /// The unroll factor. Each entry in the vector map contains UF vector
692     /// values.
693     unsigned UF;
694
695     /// The vectorization factor. Each entry in the scalar map contains UF x VF
696     /// scalar values.
697     unsigned VF;
698
699     /// The vector and scalar map storage. We use std::map and not DenseMap
700     /// because insertions to DenseMap invalidate its iterators.
701     std::map<Value *, VectorParts> VectorMapStorage;
702     std::map<Value *, ScalarParts> ScalarMapStorage;
703   };
704
705   /// The original loop.
706   Loop *OrigLoop;
707   /// A wrapper around ScalarEvolution used to add runtime SCEV checks. Applies
708   /// dynamic knowledge to simplify SCEV expressions and converts them to a
709   /// more usable form.
710   PredicatedScalarEvolution &PSE;
711   /// Loop Info.
712   LoopInfo *LI;
713   /// Dominator Tree.
714   DominatorTree *DT;
715   /// Alias Analysis.
716   AliasAnalysis *AA;
717   /// Target Library Info.
718   const TargetLibraryInfo *TLI;
719   /// Target Transform Info.
720   const TargetTransformInfo *TTI;
721   /// Assumption Cache.
722   AssumptionCache *AC;
723   /// Interface to emit optimization remarks.
724   OptimizationRemarkEmitter *ORE;
725
726   /// \brief LoopVersioning.  It's only set up (non-null) if memchecks were
727   /// used.
728   ///
729   /// This is currently only used to add no-alias metadata based on the
730   /// memchecks.  The actually versioning is performed manually.
731   std::unique_ptr<LoopVersioning> LVer;
732
733   /// The vectorization SIMD factor to use. Each vector will have this many
734   /// vector elements.
735   unsigned VF;
736
737 protected:
738   /// The vectorization unroll factor to use. Each scalar is vectorized to this
739   /// many different vector instructions.
740   unsigned UF;
741
742   /// The builder that we use
743   IRBuilder<> Builder;
744
745   // --- Vectorization state ---
746
747   /// The vector-loop preheader.
748   BasicBlock *LoopVectorPreHeader;
749   /// The scalar-loop preheader.
750   BasicBlock *LoopScalarPreHeader;
751   /// Middle Block between the vector and the scalar.
752   BasicBlock *LoopMiddleBlock;
753   /// The ExitBlock of the scalar loop.
754   BasicBlock *LoopExitBlock;
755   /// The vector loop body.
756   BasicBlock *LoopVectorBody;
757   /// The scalar loop body.
758   BasicBlock *LoopScalarBody;
759   /// A list of all bypass blocks. The first block is the entry of the loop.
760   SmallVector<BasicBlock *, 4> LoopBypassBlocks;
761
762   /// The new Induction variable which was added to the new block.
763   PHINode *Induction;
764   /// The induction variable of the old basic block.
765   PHINode *OldInduction;
766
767   /// Maps values from the original loop to their corresponding values in the
768   /// vectorized loop. A key value can map to either vector values, scalar
769   /// values or both kinds of values, depending on whether the key was
770   /// vectorized and scalarized.
771   ValueMap VectorLoopValueMap;
772
773   /// Store instructions that should be predicated, as a pair
774   ///   <StoreInst, Predicate>
775   SmallVector<std::pair<Instruction *, Value *>, 4> PredicatedInstructions;
776   EdgeMaskCacheTy EdgeMaskCache;
777   BlockMaskCacheTy BlockMaskCache;
778   /// Trip count of the original loop.
779   Value *TripCount;
780   /// Trip count of the widened loop (TripCount - TripCount % (VF*UF))
781   Value *VectorTripCount;
782
783   /// The legality analysis.
784   LoopVectorizationLegality *Legal;
785
786   /// The profitablity analysis.
787   LoopVectorizationCostModel *Cost;
788
789   // Record whether runtime checks are added.
790   bool AddedSafetyChecks;
791
792   // Holds the end values for each induction variable. We save the end values
793   // so we can later fix-up the external users of the induction variables.
794   DenseMap<PHINode *, Value *> IVEndValues;
795 };
796
797 class InnerLoopUnroller : public InnerLoopVectorizer {
798 public:
799   InnerLoopUnroller(Loop *OrigLoop, PredicatedScalarEvolution &PSE,
800                     LoopInfo *LI, DominatorTree *DT,
801                     const TargetLibraryInfo *TLI,
802                     const TargetTransformInfo *TTI, AssumptionCache *AC,
803                     OptimizationRemarkEmitter *ORE, unsigned UnrollFactor,
804                     LoopVectorizationLegality *LVL,
805                     LoopVectorizationCostModel *CM)
806       : InnerLoopVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE, 1,
807                             UnrollFactor, LVL, CM) {}
808
809 private:
810   void vectorizeMemoryInstruction(Instruction *Instr) override;
811   Value *getBroadcastInstrs(Value *V) override;
812   Value *getStepVector(Value *Val, int StartIdx, Value *Step,
813                        Instruction::BinaryOps Opcode =
814                        Instruction::BinaryOpsEnd) override;
815   Value *reverseVector(Value *Vec) override;
816 };
817
818 /// \brief Look for a meaningful debug location on the instruction or it's
819 /// operands.
820 static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
821   if (!I)
822     return I;
823
824   DebugLoc Empty;
825   if (I->getDebugLoc() != Empty)
826     return I;
827
828   for (User::op_iterator OI = I->op_begin(), OE = I->op_end(); OI != OE; ++OI) {
829     if (Instruction *OpInst = dyn_cast<Instruction>(*OI))
830       if (OpInst->getDebugLoc() != Empty)
831         return OpInst;
832   }
833
834   return I;
835 }
836
837 void InnerLoopVectorizer::setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr) {
838   if (const Instruction *Inst = dyn_cast_or_null<Instruction>(Ptr)) {
839     const DILocation *DIL = Inst->getDebugLoc();
840     if (DIL && Inst->getFunction()->isDebugInfoForProfiling())
841       B.SetCurrentDebugLocation(DIL->cloneWithDuplicationFactor(UF * VF));
842     else
843       B.SetCurrentDebugLocation(DIL);
844   } else
845     B.SetCurrentDebugLocation(DebugLoc());
846 }
847
848 #ifndef NDEBUG
849 /// \return string containing a file name and a line # for the given loop.
850 static std::string getDebugLocString(const Loop *L) {
851   std::string Result;
852   if (L) {
853     raw_string_ostream OS(Result);
854     if (const DebugLoc LoopDbgLoc = L->getStartLoc())
855       LoopDbgLoc.print(OS);
856     else
857       // Just print the module name.
858       OS << L->getHeader()->getParent()->getParent()->getModuleIdentifier();
859     OS.flush();
860   }
861   return Result;
862 }
863 #endif
864
865 void InnerLoopVectorizer::addNewMetadata(Instruction *To,
866                                          const Instruction *Orig) {
867   // If the loop was versioned with memchecks, add the corresponding no-alias
868   // metadata.
869   if (LVer && (isa<LoadInst>(Orig) || isa<StoreInst>(Orig)))
870     LVer->annotateInstWithNoAlias(To, Orig);
871 }
872
873 void InnerLoopVectorizer::addMetadata(Instruction *To,
874                                       Instruction *From) {
875   propagateMetadata(To, From);
876   addNewMetadata(To, From);
877 }
878
879 void InnerLoopVectorizer::addMetadata(ArrayRef<Value *> To,
880                                       Instruction *From) {
881   for (Value *V : To) {
882     if (Instruction *I = dyn_cast<Instruction>(V))
883       addMetadata(I, From);
884   }
885 }
886
887 /// \brief The group of interleaved loads/stores sharing the same stride and
888 /// close to each other.
889 ///
890 /// Each member in this group has an index starting from 0, and the largest
891 /// index should be less than interleaved factor, which is equal to the absolute
892 /// value of the access's stride.
893 ///
894 /// E.g. An interleaved load group of factor 4:
895 ///        for (unsigned i = 0; i < 1024; i+=4) {
896 ///          a = A[i];                           // Member of index 0
897 ///          b = A[i+1];                         // Member of index 1
898 ///          d = A[i+3];                         // Member of index 3
899 ///          ...
900 ///        }
901 ///
902 ///      An interleaved store group of factor 4:
903 ///        for (unsigned i = 0; i < 1024; i+=4) {
904 ///          ...
905 ///          A[i]   = a;                         // Member of index 0
906 ///          A[i+1] = b;                         // Member of index 1
907 ///          A[i+2] = c;                         // Member of index 2
908 ///          A[i+3] = d;                         // Member of index 3
909 ///        }
910 ///
911 /// Note: the interleaved load group could have gaps (missing members), but
912 /// the interleaved store group doesn't allow gaps.
913 class InterleaveGroup {
914 public:
915   InterleaveGroup(Instruction *Instr, int Stride, unsigned Align)
916       : Align(Align), SmallestKey(0), LargestKey(0), InsertPos(Instr) {
917     assert(Align && "The alignment should be non-zero");
918
919     Factor = std::abs(Stride);
920     assert(Factor > 1 && "Invalid interleave factor");
921
922     Reverse = Stride < 0;
923     Members[0] = Instr;
924   }
925
926   bool isReverse() const { return Reverse; }
927   unsigned getFactor() const { return Factor; }
928   unsigned getAlignment() const { return Align; }
929   unsigned getNumMembers() const { return Members.size(); }
930
931   /// \brief Try to insert a new member \p Instr with index \p Index and
932   /// alignment \p NewAlign. The index is related to the leader and it could be
933   /// negative if it is the new leader.
934   ///
935   /// \returns false if the instruction doesn't belong to the group.
936   bool insertMember(Instruction *Instr, int Index, unsigned NewAlign) {
937     assert(NewAlign && "The new member's alignment should be non-zero");
938
939     int Key = Index + SmallestKey;
940
941     // Skip if there is already a member with the same index.
942     if (Members.count(Key))
943       return false;
944
945     if (Key > LargestKey) {
946       // The largest index is always less than the interleave factor.
947       if (Index >= static_cast<int>(Factor))
948         return false;
949
950       LargestKey = Key;
951     } else if (Key < SmallestKey) {
952       // The largest index is always less than the interleave factor.
953       if (LargestKey - Key >= static_cast<int>(Factor))
954         return false;
955
956       SmallestKey = Key;
957     }
958
959     // It's always safe to select the minimum alignment.
960     Align = std::min(Align, NewAlign);
961     Members[Key] = Instr;
962     return true;
963   }
964
965   /// \brief Get the member with the given index \p Index
966   ///
967   /// \returns nullptr if contains no such member.
968   Instruction *getMember(unsigned Index) const {
969     int Key = SmallestKey + Index;
970     if (!Members.count(Key))
971       return nullptr;
972
973     return Members.find(Key)->second;
974   }
975
976   /// \brief Get the index for the given member. Unlike the key in the member
977   /// map, the index starts from 0.
978   unsigned getIndex(Instruction *Instr) const {
979     for (auto I : Members)
980       if (I.second == Instr)
981         return I.first - SmallestKey;
982
983     llvm_unreachable("InterleaveGroup contains no such member");
984   }
985
986   Instruction *getInsertPos() const { return InsertPos; }
987   void setInsertPos(Instruction *Inst) { InsertPos = Inst; }
988
989 private:
990   unsigned Factor; // Interleave Factor.
991   bool Reverse;
992   unsigned Align;
993   DenseMap<int, Instruction *> Members;
994   int SmallestKey;
995   int LargestKey;
996
997   // To avoid breaking dependences, vectorized instructions of an interleave
998   // group should be inserted at either the first load or the last store in
999   // program order.
1000   //
1001   // E.g. %even = load i32             // Insert Position
1002   //      %add = add i32 %even         // Use of %even
1003   //      %odd = load i32
1004   //
1005   //      store i32 %even
1006   //      %odd = add i32               // Def of %odd
1007   //      store i32 %odd               // Insert Position
1008   Instruction *InsertPos;
1009 };
1010
1011 /// \brief Drive the analysis of interleaved memory accesses in the loop.
1012 ///
1013 /// Use this class to analyze interleaved accesses only when we can vectorize
1014 /// a loop. Otherwise it's meaningless to do analysis as the vectorization
1015 /// on interleaved accesses is unsafe.
1016 ///
1017 /// The analysis collects interleave groups and records the relationships
1018 /// between the member and the group in a map.
1019 class InterleavedAccessInfo {
1020 public:
1021   InterleavedAccessInfo(PredicatedScalarEvolution &PSE, Loop *L,
1022                         DominatorTree *DT, LoopInfo *LI)
1023       : PSE(PSE), TheLoop(L), DT(DT), LI(LI), LAI(nullptr),
1024         RequiresScalarEpilogue(false) {}
1025
1026   ~InterleavedAccessInfo() {
1027     SmallSet<InterleaveGroup *, 4> DelSet;
1028     // Avoid releasing a pointer twice.
1029     for (auto &I : InterleaveGroupMap)
1030       DelSet.insert(I.second);
1031     for (auto *Ptr : DelSet)
1032       delete Ptr;
1033   }
1034
1035   /// \brief Analyze the interleaved accesses and collect them in interleave
1036   /// groups. Substitute symbolic strides using \p Strides.
1037   void analyzeInterleaving(const ValueToValueMap &Strides);
1038
1039   /// \brief Check if \p Instr belongs to any interleave group.
1040   bool isInterleaved(Instruction *Instr) const {
1041     return InterleaveGroupMap.count(Instr);
1042   }
1043
1044   /// \brief Return the maximum interleave factor of all interleaved groups.
1045   unsigned getMaxInterleaveFactor() const {
1046     unsigned MaxFactor = 1;
1047     for (auto &Entry : InterleaveGroupMap)
1048       MaxFactor = std::max(MaxFactor, Entry.second->getFactor());
1049     return MaxFactor;
1050   }
1051
1052   /// \brief Get the interleave group that \p Instr belongs to.
1053   ///
1054   /// \returns nullptr if doesn't have such group.
1055   InterleaveGroup *getInterleaveGroup(Instruction *Instr) const {
1056     if (InterleaveGroupMap.count(Instr))
1057       return InterleaveGroupMap.find(Instr)->second;
1058     return nullptr;
1059   }
1060
1061   /// \brief Returns true if an interleaved group that may access memory
1062   /// out-of-bounds requires a scalar epilogue iteration for correctness.
1063   bool requiresScalarEpilogue() const { return RequiresScalarEpilogue; }
1064
1065   /// \brief Initialize the LoopAccessInfo used for dependence checking.
1066   void setLAI(const LoopAccessInfo *Info) { LAI = Info; }
1067
1068 private:
1069   /// A wrapper around ScalarEvolution, used to add runtime SCEV checks.
1070   /// Simplifies SCEV expressions in the context of existing SCEV assumptions.
1071   /// The interleaved access analysis can also add new predicates (for example
1072   /// by versioning strides of pointers).
1073   PredicatedScalarEvolution &PSE;
1074   Loop *TheLoop;
1075   DominatorTree *DT;
1076   LoopInfo *LI;
1077   const LoopAccessInfo *LAI;
1078
1079   /// True if the loop may contain non-reversed interleaved groups with
1080   /// out-of-bounds accesses. We ensure we don't speculatively access memory
1081   /// out-of-bounds by executing at least one scalar epilogue iteration.
1082   bool RequiresScalarEpilogue;
1083
1084   /// Holds the relationships between the members and the interleave group.
1085   DenseMap<Instruction *, InterleaveGroup *> InterleaveGroupMap;
1086
1087   /// Holds dependences among the memory accesses in the loop. It maps a source
1088   /// access to a set of dependent sink accesses.
1089   DenseMap<Instruction *, SmallPtrSet<Instruction *, 2>> Dependences;
1090
1091   /// \brief The descriptor for a strided memory access.
1092   struct StrideDescriptor {
1093     StrideDescriptor(int64_t Stride, const SCEV *Scev, uint64_t Size,
1094                      unsigned Align)
1095         : Stride(Stride), Scev(Scev), Size(Size), Align(Align) {}
1096
1097     StrideDescriptor() = default;
1098
1099     // The access's stride. It is negative for a reverse access.
1100     int64_t Stride = 0;
1101     const SCEV *Scev = nullptr; // The scalar expression of this access
1102     uint64_t Size = 0;          // The size of the memory object.
1103     unsigned Align = 0;         // The alignment of this access.
1104   };
1105
1106   /// \brief A type for holding instructions and their stride descriptors.
1107   typedef std::pair<Instruction *, StrideDescriptor> StrideEntry;
1108
1109   /// \brief Create a new interleave group with the given instruction \p Instr,
1110   /// stride \p Stride and alignment \p Align.
1111   ///
1112   /// \returns the newly created interleave group.
1113   InterleaveGroup *createInterleaveGroup(Instruction *Instr, int Stride,
1114                                          unsigned Align) {
1115     assert(!InterleaveGroupMap.count(Instr) &&
1116            "Already in an interleaved access group");
1117     InterleaveGroupMap[Instr] = new InterleaveGroup(Instr, Stride, Align);
1118     return InterleaveGroupMap[Instr];
1119   }
1120
1121   /// \brief Release the group and remove all the relationships.
1122   void releaseGroup(InterleaveGroup *Group) {
1123     for (unsigned i = 0; i < Group->getFactor(); i++)
1124       if (Instruction *Member = Group->getMember(i))
1125         InterleaveGroupMap.erase(Member);
1126
1127     delete Group;
1128   }
1129
1130   /// \brief Collect all the accesses with a constant stride in program order.
1131   void collectConstStrideAccesses(
1132       MapVector<Instruction *, StrideDescriptor> &AccessStrideInfo,
1133       const ValueToValueMap &Strides);
1134
1135   /// \brief Returns true if \p Stride is allowed in an interleaved group.
1136   static bool isStrided(int Stride) {
1137     unsigned Factor = std::abs(Stride);
1138     return Factor >= 2 && Factor <= MaxInterleaveGroupFactor;
1139   }
1140
1141   /// \brief Returns true if \p BB is a predicated block.
1142   bool isPredicated(BasicBlock *BB) const {
1143     return LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT);
1144   }
1145
1146   /// \brief Returns true if LoopAccessInfo can be used for dependence queries.
1147   bool areDependencesValid() const {
1148     return LAI && LAI->getDepChecker().getDependences();
1149   }
1150
1151   /// \brief Returns true if memory accesses \p A and \p B can be reordered, if
1152   /// necessary, when constructing interleaved groups.
1153   ///
1154   /// \p A must precede \p B in program order. We return false if reordering is
1155   /// not necessary or is prevented because \p A and \p B may be dependent.
1156   bool canReorderMemAccessesForInterleavedGroups(StrideEntry *A,
1157                                                  StrideEntry *B) const {
1158
1159     // Code motion for interleaved accesses can potentially hoist strided loads
1160     // and sink strided stores. The code below checks the legality of the
1161     // following two conditions:
1162     //
1163     // 1. Potentially moving a strided load (B) before any store (A) that
1164     //    precedes B, or
1165     //
1166     // 2. Potentially moving a strided store (A) after any load or store (B)
1167     //    that A precedes.
1168     //
1169     // It's legal to reorder A and B if we know there isn't a dependence from A
1170     // to B. Note that this determination is conservative since some
1171     // dependences could potentially be reordered safely.
1172
1173     // A is potentially the source of a dependence.
1174     auto *Src = A->first;
1175     auto SrcDes = A->second;
1176
1177     // B is potentially the sink of a dependence.
1178     auto *Sink = B->first;
1179     auto SinkDes = B->second;
1180
1181     // Code motion for interleaved accesses can't violate WAR dependences.
1182     // Thus, reordering is legal if the source isn't a write.
1183     if (!Src->mayWriteToMemory())
1184       return true;
1185
1186     // At least one of the accesses must be strided.
1187     if (!isStrided(SrcDes.Stride) && !isStrided(SinkDes.Stride))
1188       return true;
1189
1190     // If dependence information is not available from LoopAccessInfo,
1191     // conservatively assume the instructions can't be reordered.
1192     if (!areDependencesValid())
1193       return false;
1194
1195     // If we know there is a dependence from source to sink, assume the
1196     // instructions can't be reordered. Otherwise, reordering is legal.
1197     return !Dependences.count(Src) || !Dependences.lookup(Src).count(Sink);
1198   }
1199
1200   /// \brief Collect the dependences from LoopAccessInfo.
1201   ///
1202   /// We process the dependences once during the interleaved access analysis to
1203   /// enable constant-time dependence queries.
1204   void collectDependences() {
1205     if (!areDependencesValid())
1206       return;
1207     auto *Deps = LAI->getDepChecker().getDependences();
1208     for (auto Dep : *Deps)
1209       Dependences[Dep.getSource(*LAI)].insert(Dep.getDestination(*LAI));
1210   }
1211 };
1212
1213 /// Utility class for getting and setting loop vectorizer hints in the form
1214 /// of loop metadata.
1215 /// This class keeps a number of loop annotations locally (as member variables)
1216 /// and can, upon request, write them back as metadata on the loop. It will
1217 /// initially scan the loop for existing metadata, and will update the local
1218 /// values based on information in the loop.
1219 /// We cannot write all values to metadata, as the mere presence of some info,
1220 /// for example 'force', means a decision has been made. So, we need to be
1221 /// careful NOT to add them if the user hasn't specifically asked so.
1222 class LoopVectorizeHints {
1223   enum HintKind { HK_WIDTH, HK_UNROLL, HK_FORCE };
1224
1225   /// Hint - associates name and validation with the hint value.
1226   struct Hint {
1227     const char *Name;
1228     unsigned Value; // This may have to change for non-numeric values.
1229     HintKind Kind;
1230
1231     Hint(const char *Name, unsigned Value, HintKind Kind)
1232         : Name(Name), Value(Value), Kind(Kind) {}
1233
1234     bool validate(unsigned Val) {
1235       switch (Kind) {
1236       case HK_WIDTH:
1237         return isPowerOf2_32(Val) && Val <= VectorizerParams::MaxVectorWidth;
1238       case HK_UNROLL:
1239         return isPowerOf2_32(Val) && Val <= MaxInterleaveFactor;
1240       case HK_FORCE:
1241         return (Val <= 1);
1242       }
1243       return false;
1244     }
1245   };
1246
1247   /// Vectorization width.
1248   Hint Width;
1249   /// Vectorization interleave factor.
1250   Hint Interleave;
1251   /// Vectorization forced
1252   Hint Force;
1253
1254   /// Return the loop metadata prefix.
1255   static StringRef Prefix() { return "llvm.loop."; }
1256
1257   /// True if there is any unsafe math in the loop.
1258   bool PotentiallyUnsafe;
1259
1260 public:
1261   enum ForceKind {
1262     FK_Undefined = -1, ///< Not selected.
1263     FK_Disabled = 0,   ///< Forcing disabled.
1264     FK_Enabled = 1,    ///< Forcing enabled.
1265   };
1266
1267   LoopVectorizeHints(const Loop *L, bool DisableInterleaving,
1268                      OptimizationRemarkEmitter &ORE)
1269       : Width("vectorize.width", VectorizerParams::VectorizationFactor,
1270               HK_WIDTH),
1271         Interleave("interleave.count", DisableInterleaving, HK_UNROLL),
1272         Force("vectorize.enable", FK_Undefined, HK_FORCE),
1273         PotentiallyUnsafe(false), TheLoop(L), ORE(ORE) {
1274     // Populate values with existing loop metadata.
1275     getHintsFromMetadata();
1276
1277     // force-vector-interleave overrides DisableInterleaving.
1278     if (VectorizerParams::isInterleaveForced())
1279       Interleave.Value = VectorizerParams::VectorizationInterleave;
1280
1281     DEBUG(if (DisableInterleaving && Interleave.Value == 1) dbgs()
1282           << "LV: Interleaving disabled by the pass manager\n");
1283   }
1284
1285   /// Mark the loop L as already vectorized by setting the width to 1.
1286   void setAlreadyVectorized() {
1287     Width.Value = Interleave.Value = 1;
1288     Hint Hints[] = {Width, Interleave};
1289     writeHintsToMetadata(Hints);
1290   }
1291
1292   bool allowVectorization(Function *F, Loop *L, bool AlwaysVectorize) const {
1293     if (getForce() == LoopVectorizeHints::FK_Disabled) {
1294       DEBUG(dbgs() << "LV: Not vectorizing: #pragma vectorize disable.\n");
1295       emitRemarkWithHints();
1296       return false;
1297     }
1298
1299     if (!AlwaysVectorize && getForce() != LoopVectorizeHints::FK_Enabled) {
1300       DEBUG(dbgs() << "LV: Not vectorizing: No #pragma vectorize enable.\n");
1301       emitRemarkWithHints();
1302       return false;
1303     }
1304
1305     if (getWidth() == 1 && getInterleave() == 1) {
1306       // FIXME: Add a separate metadata to indicate when the loop has already
1307       // been vectorized instead of setting width and count to 1.
1308       DEBUG(dbgs() << "LV: Not vectorizing: Disabled/already vectorized.\n");
1309       // FIXME: Add interleave.disable metadata. This will allow
1310       // vectorize.disable to be used without disabling the pass and errors
1311       // to differentiate between disabled vectorization and a width of 1.
1312       ORE.emit(OptimizationRemarkAnalysis(vectorizeAnalysisPassName(),
1313                                           "AllDisabled", L->getStartLoc(),
1314                                           L->getHeader())
1315                << "loop not vectorized: vectorization and interleaving are "
1316                   "explicitly disabled, or vectorize width and interleave "
1317                   "count are both set to 1");
1318       return false;
1319     }
1320
1321     return true;
1322   }
1323
1324   /// Dumps all the hint information.
1325   void emitRemarkWithHints() const {
1326     using namespace ore;
1327     if (Force.Value == LoopVectorizeHints::FK_Disabled)
1328       ORE.emit(OptimizationRemarkMissed(LV_NAME, "MissedExplicitlyDisabled",
1329                                         TheLoop->getStartLoc(),
1330                                         TheLoop->getHeader())
1331                << "loop not vectorized: vectorization is explicitly disabled");
1332     else {
1333       OptimizationRemarkMissed R(LV_NAME, "MissedDetails",
1334                                  TheLoop->getStartLoc(), TheLoop->getHeader());
1335       R << "loop not vectorized";
1336       if (Force.Value == LoopVectorizeHints::FK_Enabled) {
1337         R << " (Force=" << NV("Force", true);
1338         if (Width.Value != 0)
1339           R << ", Vector Width=" << NV("VectorWidth", Width.Value);
1340         if (Interleave.Value != 0)
1341           R << ", Interleave Count=" << NV("InterleaveCount", Interleave.Value);
1342         R << ")";
1343       }
1344       ORE.emit(R);
1345     }
1346   }
1347
1348   unsigned getWidth() const { return Width.Value; }
1349   unsigned getInterleave() const { return Interleave.Value; }
1350   enum ForceKind getForce() const { return (ForceKind)Force.Value; }
1351
1352   /// \brief If hints are provided that force vectorization, use the AlwaysPrint
1353   /// pass name to force the frontend to print the diagnostic.
1354   const char *vectorizeAnalysisPassName() const {
1355     if (getWidth() == 1)
1356       return LV_NAME;
1357     if (getForce() == LoopVectorizeHints::FK_Disabled)
1358       return LV_NAME;
1359     if (getForce() == LoopVectorizeHints::FK_Undefined && getWidth() == 0)
1360       return LV_NAME;
1361     return OptimizationRemarkAnalysis::AlwaysPrint;
1362   }
1363
1364   bool allowReordering() const {
1365     // When enabling loop hints are provided we allow the vectorizer to change
1366     // the order of operations that is given by the scalar loop. This is not
1367     // enabled by default because can be unsafe or inefficient. For example,
1368     // reordering floating-point operations will change the way round-off
1369     // error accumulates in the loop.
1370     return getForce() == LoopVectorizeHints::FK_Enabled || getWidth() > 1;
1371   }
1372
1373   bool isPotentiallyUnsafe() const {
1374     // Avoid FP vectorization if the target is unsure about proper support.
1375     // This may be related to the SIMD unit in the target not handling
1376     // IEEE 754 FP ops properly, or bad single-to-double promotions.
1377     // Otherwise, a sequence of vectorized loops, even without reduction,
1378     // could lead to different end results on the destination vectors.
1379     return getForce() != LoopVectorizeHints::FK_Enabled && PotentiallyUnsafe;
1380   }
1381
1382   void setPotentiallyUnsafe() { PotentiallyUnsafe = true; }
1383
1384 private:
1385   /// Find hints specified in the loop metadata and update local values.
1386   void getHintsFromMetadata() {
1387     MDNode *LoopID = TheLoop->getLoopID();
1388     if (!LoopID)
1389       return;
1390
1391     // First operand should refer to the loop id itself.
1392     assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
1393     assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
1394
1395     for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
1396       const MDString *S = nullptr;
1397       SmallVector<Metadata *, 4> Args;
1398
1399       // The expected hint is either a MDString or a MDNode with the first
1400       // operand a MDString.
1401       if (const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i))) {
1402         if (!MD || MD->getNumOperands() == 0)
1403           continue;
1404         S = dyn_cast<MDString>(MD->getOperand(0));
1405         for (unsigned i = 1, ie = MD->getNumOperands(); i < ie; ++i)
1406           Args.push_back(MD->getOperand(i));
1407       } else {
1408         S = dyn_cast<MDString>(LoopID->getOperand(i));
1409         assert(Args.size() == 0 && "too many arguments for MDString");
1410       }
1411
1412       if (!S)
1413         continue;
1414
1415       // Check if the hint starts with the loop metadata prefix.
1416       StringRef Name = S->getString();
1417       if (Args.size() == 1)
1418         setHint(Name, Args[0]);
1419     }
1420   }
1421
1422   /// Checks string hint with one operand and set value if valid.
1423   void setHint(StringRef Name, Metadata *Arg) {
1424     if (!Name.startswith(Prefix()))
1425       return;
1426     Name = Name.substr(Prefix().size(), StringRef::npos);
1427
1428     const ConstantInt *C = mdconst::dyn_extract<ConstantInt>(Arg);
1429     if (!C)
1430       return;
1431     unsigned Val = C->getZExtValue();
1432
1433     Hint *Hints[] = {&Width, &Interleave, &Force};
1434     for (auto H : Hints) {
1435       if (Name == H->Name) {
1436         if (H->validate(Val))
1437           H->Value = Val;
1438         else
1439           DEBUG(dbgs() << "LV: ignoring invalid hint '" << Name << "'\n");
1440         break;
1441       }
1442     }
1443   }
1444
1445   /// Create a new hint from name / value pair.
1446   MDNode *createHintMetadata(StringRef Name, unsigned V) const {
1447     LLVMContext &Context = TheLoop->getHeader()->getContext();
1448     Metadata *MDs[] = {MDString::get(Context, Name),
1449                        ConstantAsMetadata::get(
1450                            ConstantInt::get(Type::getInt32Ty(Context), V))};
1451     return MDNode::get(Context, MDs);
1452   }
1453
1454   /// Matches metadata with hint name.
1455   bool matchesHintMetadataName(MDNode *Node, ArrayRef<Hint> HintTypes) {
1456     MDString *Name = dyn_cast<MDString>(Node->getOperand(0));
1457     if (!Name)
1458       return false;
1459
1460     for (auto H : HintTypes)
1461       if (Name->getString().endswith(H.Name))
1462         return true;
1463     return false;
1464   }
1465
1466   /// Sets current hints into loop metadata, keeping other values intact.
1467   void writeHintsToMetadata(ArrayRef<Hint> HintTypes) {
1468     if (HintTypes.size() == 0)
1469       return;
1470
1471     // Reserve the first element to LoopID (see below).
1472     SmallVector<Metadata *, 4> MDs(1);
1473     // If the loop already has metadata, then ignore the existing operands.
1474     MDNode *LoopID = TheLoop->getLoopID();
1475     if (LoopID) {
1476       for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
1477         MDNode *Node = cast<MDNode>(LoopID->getOperand(i));
1478         // If node in update list, ignore old value.
1479         if (!matchesHintMetadataName(Node, HintTypes))
1480           MDs.push_back(Node);
1481       }
1482     }
1483
1484     // Now, add the missing hints.
1485     for (auto H : HintTypes)
1486       MDs.push_back(createHintMetadata(Twine(Prefix(), H.Name).str(), H.Value));
1487
1488     // Replace current metadata node with new one.
1489     LLVMContext &Context = TheLoop->getHeader()->getContext();
1490     MDNode *NewLoopID = MDNode::get(Context, MDs);
1491     // Set operand 0 to refer to the loop id itself.
1492     NewLoopID->replaceOperandWith(0, NewLoopID);
1493
1494     TheLoop->setLoopID(NewLoopID);
1495   }
1496
1497   /// The loop these hints belong to.
1498   const Loop *TheLoop;
1499
1500   /// Interface to emit optimization remarks.
1501   OptimizationRemarkEmitter &ORE;
1502 };
1503
1504 static void emitMissedWarning(Function *F, Loop *L,
1505                               const LoopVectorizeHints &LH,
1506                               OptimizationRemarkEmitter *ORE) {
1507   LH.emitRemarkWithHints();
1508
1509   if (LH.getForce() == LoopVectorizeHints::FK_Enabled) {
1510     if (LH.getWidth() != 1)
1511       ORE->emit(DiagnosticInfoOptimizationFailure(
1512                     DEBUG_TYPE, "FailedRequestedVectorization",
1513                     L->getStartLoc(), L->getHeader())
1514                 << "loop not vectorized: "
1515                 << "failed explicitly specified loop vectorization");
1516     else if (LH.getInterleave() != 1)
1517       ORE->emit(DiagnosticInfoOptimizationFailure(
1518                     DEBUG_TYPE, "FailedRequestedInterleaving", L->getStartLoc(),
1519                     L->getHeader())
1520                 << "loop not interleaved: "
1521                 << "failed explicitly specified loop interleaving");
1522   }
1523 }
1524
1525 /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
1526 /// to what vectorization factor.
1527 /// This class does not look at the profitability of vectorization, only the
1528 /// legality. This class has two main kinds of checks:
1529 /// * Memory checks - The code in canVectorizeMemory checks if vectorization
1530 ///   will change the order of memory accesses in a way that will change the
1531 ///   correctness of the program.
1532 /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
1533 /// checks for a number of different conditions, such as the availability of a
1534 /// single induction variable, that all types are supported and vectorize-able,
1535 /// etc. This code reflects the capabilities of InnerLoopVectorizer.
1536 /// This class is also used by InnerLoopVectorizer for identifying
1537 /// induction variable and the different reduction variables.
1538 class LoopVectorizationLegality {
1539 public:
1540   LoopVectorizationLegality(
1541       Loop *L, PredicatedScalarEvolution &PSE, DominatorTree *DT,
1542       TargetLibraryInfo *TLI, AliasAnalysis *AA, Function *F,
1543       const TargetTransformInfo *TTI,
1544       std::function<const LoopAccessInfo &(Loop &)> *GetLAA, LoopInfo *LI,
1545       OptimizationRemarkEmitter *ORE, LoopVectorizationRequirements *R,
1546       LoopVectorizeHints *H)
1547       : NumPredStores(0), TheLoop(L), PSE(PSE), TLI(TLI), TTI(TTI), DT(DT),
1548         GetLAA(GetLAA), LAI(nullptr), ORE(ORE), InterleaveInfo(PSE, L, DT, LI),
1549         PrimaryInduction(nullptr), WidestIndTy(nullptr), HasFunNoNaNAttr(false),
1550         Requirements(R), Hints(H) {}
1551
1552   /// ReductionList contains the reduction descriptors for all
1553   /// of the reductions that were found in the loop.
1554   typedef DenseMap<PHINode *, RecurrenceDescriptor> ReductionList;
1555
1556   /// InductionList saves induction variables and maps them to the
1557   /// induction descriptor.
1558   typedef MapVector<PHINode *, InductionDescriptor> InductionList;
1559
1560   /// RecurrenceSet contains the phi nodes that are recurrences other than
1561   /// inductions and reductions.
1562   typedef SmallPtrSet<const PHINode *, 8> RecurrenceSet;
1563
1564   /// Returns true if it is legal to vectorize this loop.
1565   /// This does not mean that it is profitable to vectorize this
1566   /// loop, only that it is legal to do so.
1567   bool canVectorize();
1568
1569   /// Returns the primary induction variable.
1570   PHINode *getPrimaryInduction() { return PrimaryInduction; }
1571
1572   /// Returns the reduction variables found in the loop.
1573   ReductionList *getReductionVars() { return &Reductions; }
1574
1575   /// Returns the induction variables found in the loop.
1576   InductionList *getInductionVars() { return &Inductions; }
1577
1578   /// Return the first-order recurrences found in the loop.
1579   RecurrenceSet *getFirstOrderRecurrences() { return &FirstOrderRecurrences; }
1580
1581   /// Returns the widest induction type.
1582   Type *getWidestInductionType() { return WidestIndTy; }
1583
1584   /// Returns True if V is an induction variable in this loop.
1585   bool isInductionVariable(const Value *V);
1586
1587   /// Returns True if PN is a reduction variable in this loop.
1588   bool isReductionVariable(PHINode *PN) { return Reductions.count(PN); }
1589
1590   /// Returns True if Phi is a first-order recurrence in this loop.
1591   bool isFirstOrderRecurrence(const PHINode *Phi);
1592
1593   /// Return true if the block BB needs to be predicated in order for the loop
1594   /// to be vectorized.
1595   bool blockNeedsPredication(BasicBlock *BB);
1596
1597   /// Check if this pointer is consecutive when vectorizing. This happens
1598   /// when the last index of the GEP is the induction variable, or that the
1599   /// pointer itself is an induction variable.
1600   /// This check allows us to vectorize A[idx] into a wide load/store.
1601   /// Returns:
1602   /// 0 - Stride is unknown or non-consecutive.
1603   /// 1 - Address is consecutive.
1604   /// -1 - Address is consecutive, and decreasing.
1605   int isConsecutivePtr(Value *Ptr);
1606
1607   /// Returns true if the value V is uniform within the loop.
1608   bool isUniform(Value *V);
1609
1610   /// Returns the information that we collected about runtime memory check.
1611   const RuntimePointerChecking *getRuntimePointerChecking() const {
1612     return LAI->getRuntimePointerChecking();
1613   }
1614
1615   const LoopAccessInfo *getLAI() const { return LAI; }
1616
1617   /// \brief Check if \p Instr belongs to any interleaved access group.
1618   bool isAccessInterleaved(Instruction *Instr) {
1619     return InterleaveInfo.isInterleaved(Instr);
1620   }
1621
1622   /// \brief Return the maximum interleave factor of all interleaved groups.
1623   unsigned getMaxInterleaveFactor() const {
1624     return InterleaveInfo.getMaxInterleaveFactor();
1625   }
1626
1627   /// \brief Get the interleaved access group that \p Instr belongs to.
1628   const InterleaveGroup *getInterleavedAccessGroup(Instruction *Instr) {
1629     return InterleaveInfo.getInterleaveGroup(Instr);
1630   }
1631
1632   /// \brief Returns true if an interleaved group requires a scalar iteration
1633   /// to handle accesses with gaps.
1634   bool requiresScalarEpilogue() const {
1635     return InterleaveInfo.requiresScalarEpilogue();
1636   }
1637
1638   unsigned getMaxSafeDepDistBytes() { return LAI->getMaxSafeDepDistBytes(); }
1639
1640   bool hasStride(Value *V) { return LAI->hasStride(V); }
1641
1642   /// Returns true if the target machine supports masked store operation
1643   /// for the given \p DataType and kind of access to \p Ptr.
1644   bool isLegalMaskedStore(Type *DataType, Value *Ptr) {
1645     return isConsecutivePtr(Ptr) && TTI->isLegalMaskedStore(DataType);
1646   }
1647   /// Returns true if the target machine supports masked load operation
1648   /// for the given \p DataType and kind of access to \p Ptr.
1649   bool isLegalMaskedLoad(Type *DataType, Value *Ptr) {
1650     return isConsecutivePtr(Ptr) && TTI->isLegalMaskedLoad(DataType);
1651   }
1652   /// Returns true if the target machine supports masked scatter operation
1653   /// for the given \p DataType.
1654   bool isLegalMaskedScatter(Type *DataType) {
1655     return TTI->isLegalMaskedScatter(DataType);
1656   }
1657   /// Returns true if the target machine supports masked gather operation
1658   /// for the given \p DataType.
1659   bool isLegalMaskedGather(Type *DataType) {
1660     return TTI->isLegalMaskedGather(DataType);
1661   }
1662   /// Returns true if the target machine can represent \p V as a masked gather
1663   /// or scatter operation.
1664   bool isLegalGatherOrScatter(Value *V) {
1665     auto *LI = dyn_cast<LoadInst>(V);
1666     auto *SI = dyn_cast<StoreInst>(V);
1667     if (!LI && !SI)
1668       return false;
1669     auto *Ptr = getPointerOperand(V);
1670     auto *Ty = cast<PointerType>(Ptr->getType())->getElementType();
1671     return (LI && isLegalMaskedGather(Ty)) || (SI && isLegalMaskedScatter(Ty));
1672   }
1673
1674   /// Returns true if vector representation of the instruction \p I
1675   /// requires mask.
1676   bool isMaskRequired(const Instruction *I) { return (MaskedOp.count(I) != 0); }
1677   unsigned getNumStores() const { return LAI->getNumStores(); }
1678   unsigned getNumLoads() const { return LAI->getNumLoads(); }
1679   unsigned getNumPredStores() const { return NumPredStores; }
1680
1681   /// Returns true if \p I is an instruction that will be scalarized with
1682   /// predication. Such instructions include conditional stores and
1683   /// instructions that may divide by zero.
1684   bool isScalarWithPredication(Instruction *I);
1685
1686   /// Returns true if \p I is a memory instruction with consecutive memory
1687   /// access that can be widened.
1688   bool memoryInstructionCanBeWidened(Instruction *I, unsigned VF = 1);
1689
1690   // Returns true if the NoNaN attribute is set on the function.
1691   bool hasFunNoNaNAttr() const { return HasFunNoNaNAttr; }
1692
1693 private:
1694   /// Check if a single basic block loop is vectorizable.
1695   /// At this point we know that this is a loop with a constant trip count
1696   /// and we only need to check individual instructions.
1697   bool canVectorizeInstrs();
1698
1699   /// When we vectorize loops we may change the order in which
1700   /// we read and write from memory. This method checks if it is
1701   /// legal to vectorize the code, considering only memory constrains.
1702   /// Returns true if the loop is vectorizable
1703   bool canVectorizeMemory();
1704
1705   /// Return true if we can vectorize this loop using the IF-conversion
1706   /// transformation.
1707   bool canVectorizeWithIfConvert();
1708
1709   /// Return true if all of the instructions in the block can be speculatively
1710   /// executed. \p SafePtrs is a list of addresses that are known to be legal
1711   /// and we know that we can read from them without segfault.
1712   bool blockCanBePredicated(BasicBlock *BB, SmallPtrSetImpl<Value *> &SafePtrs);
1713
1714   /// Updates the vectorization state by adding \p Phi to the inductions list.
1715   /// This can set \p Phi as the main induction of the loop if \p Phi is a
1716   /// better choice for the main induction than the existing one.
1717   void addInductionPhi(PHINode *Phi, const InductionDescriptor &ID,
1718                        SmallPtrSetImpl<Value *> &AllowedExit);
1719
1720   /// Create an analysis remark that explains why vectorization failed
1721   ///
1722   /// \p RemarkName is the identifier for the remark.  If \p I is passed it is
1723   /// an instruction that prevents vectorization.  Otherwise the loop is used
1724   /// for the location of the remark.  \return the remark object that can be
1725   /// streamed to.
1726   OptimizationRemarkAnalysis
1727   createMissedAnalysis(StringRef RemarkName, Instruction *I = nullptr) const {
1728     return ::createMissedAnalysis(Hints->vectorizeAnalysisPassName(),
1729                                   RemarkName, TheLoop, I);
1730   }
1731
1732   /// \brief If an access has a symbolic strides, this maps the pointer value to
1733   /// the stride symbol.
1734   const ValueToValueMap *getSymbolicStrides() {
1735     // FIXME: Currently, the set of symbolic strides is sometimes queried before
1736     // it's collected.  This happens from canVectorizeWithIfConvert, when the
1737     // pointer is checked to reference consecutive elements suitable for a
1738     // masked access.
1739     return LAI ? &LAI->getSymbolicStrides() : nullptr;
1740   }
1741
1742   unsigned NumPredStores;
1743
1744   /// The loop that we evaluate.
1745   Loop *TheLoop;
1746   /// A wrapper around ScalarEvolution used to add runtime SCEV checks.
1747   /// Applies dynamic knowledge to simplify SCEV expressions in the context
1748   /// of existing SCEV assumptions. The analysis will also add a minimal set
1749   /// of new predicates if this is required to enable vectorization and
1750   /// unrolling.
1751   PredicatedScalarEvolution &PSE;
1752   /// Target Library Info.
1753   TargetLibraryInfo *TLI;
1754   /// Target Transform Info
1755   const TargetTransformInfo *TTI;
1756   /// Dominator Tree.
1757   DominatorTree *DT;
1758   // LoopAccess analysis.
1759   std::function<const LoopAccessInfo &(Loop &)> *GetLAA;
1760   // And the loop-accesses info corresponding to this loop.  This pointer is
1761   // null until canVectorizeMemory sets it up.
1762   const LoopAccessInfo *LAI;
1763   /// Interface to emit optimization remarks.
1764   OptimizationRemarkEmitter *ORE;
1765
1766   /// The interleave access information contains groups of interleaved accesses
1767   /// with the same stride and close to each other.
1768   InterleavedAccessInfo InterleaveInfo;
1769
1770   //  ---  vectorization state --- //
1771
1772   /// Holds the primary induction variable. This is the counter of the
1773   /// loop.
1774   PHINode *PrimaryInduction;
1775   /// Holds the reduction variables.
1776   ReductionList Reductions;
1777   /// Holds all of the induction variables that we found in the loop.
1778   /// Notice that inductions don't need to start at zero and that induction
1779   /// variables can be pointers.
1780   InductionList Inductions;
1781   /// Holds the phi nodes that are first-order recurrences.
1782   RecurrenceSet FirstOrderRecurrences;
1783   /// Holds the widest induction type encountered.
1784   Type *WidestIndTy;
1785
1786   /// Allowed outside users. This holds the induction and reduction
1787   /// vars which can be accessed from outside the loop.
1788   SmallPtrSet<Value *, 4> AllowedExit;
1789
1790   /// Can we assume the absence of NaNs.
1791   bool HasFunNoNaNAttr;
1792
1793   /// Vectorization requirements that will go through late-evaluation.
1794   LoopVectorizationRequirements *Requirements;
1795
1796   /// Used to emit an analysis of any legality issues.
1797   LoopVectorizeHints *Hints;
1798
1799   /// While vectorizing these instructions we have to generate a
1800   /// call to the appropriate masked intrinsic
1801   SmallPtrSet<const Instruction *, 8> MaskedOp;
1802 };
1803
1804 /// LoopVectorizationCostModel - estimates the expected speedups due to
1805 /// vectorization.
1806 /// In many cases vectorization is not profitable. This can happen because of
1807 /// a number of reasons. In this class we mainly attempt to predict the
1808 /// expected speedup/slowdowns due to the supported instruction set. We use the
1809 /// TargetTransformInfo to query the different backends for the cost of
1810 /// different operations.
1811 class LoopVectorizationCostModel {
1812 public:
1813   LoopVectorizationCostModel(Loop *L, PredicatedScalarEvolution &PSE,
1814                              LoopInfo *LI, LoopVectorizationLegality *Legal,
1815                              const TargetTransformInfo &TTI,
1816                              const TargetLibraryInfo *TLI, DemandedBits *DB,
1817                              AssumptionCache *AC,
1818                              OptimizationRemarkEmitter *ORE, const Function *F,
1819                              const LoopVectorizeHints *Hints)
1820       : TheLoop(L), PSE(PSE), LI(LI), Legal(Legal), TTI(TTI), TLI(TLI), DB(DB),
1821         AC(AC), ORE(ORE), TheFunction(F), Hints(Hints) {}
1822
1823   /// \return An upper bound for the vectorization factor, or None if
1824   /// vectorization should be avoided up front.
1825   Optional<unsigned> computeMaxVF(bool OptForSize);
1826
1827   /// Information about vectorization costs
1828   struct VectorizationFactor {
1829     unsigned Width; // Vector width with best cost
1830     unsigned Cost;  // Cost of the loop with that width
1831   };
1832   /// \return The most profitable vectorization factor and the cost of that VF.
1833   /// This method checks every power of two up to MaxVF. If UserVF is not ZERO
1834   /// then this vectorization factor will be selected if vectorization is
1835   /// possible.
1836   VectorizationFactor selectVectorizationFactor(unsigned MaxVF);
1837
1838   /// Setup cost-based decisions for user vectorization factor.
1839   void selectUserVectorizationFactor(unsigned UserVF) {
1840     collectUniformsAndScalars(UserVF);
1841     collectInstsToScalarize(UserVF);
1842   }
1843
1844   /// \return The size (in bits) of the smallest and widest types in the code
1845   /// that needs to be vectorized. We ignore values that remain scalar such as
1846   /// 64 bit loop indices.
1847   std::pair<unsigned, unsigned> getSmallestAndWidestTypes();
1848
1849   /// \return The desired interleave count.
1850   /// If interleave count has been specified by metadata it will be returned.
1851   /// Otherwise, the interleave count is computed and returned. VF and LoopCost
1852   /// are the selected vectorization factor and the cost of the selected VF.
1853   unsigned selectInterleaveCount(bool OptForSize, unsigned VF,
1854                                  unsigned LoopCost);
1855
1856   /// Memory access instruction may be vectorized in more than one way.
1857   /// Form of instruction after vectorization depends on cost.
1858   /// This function takes cost-based decisions for Load/Store instructions
1859   /// and collects them in a map. This decisions map is used for building
1860   /// the lists of loop-uniform and loop-scalar instructions.
1861   /// The calculated cost is saved with widening decision in order to
1862   /// avoid redundant calculations.
1863   void setCostBasedWideningDecision(unsigned VF);
1864
1865   /// \brief A struct that represents some properties of the register usage
1866   /// of a loop.
1867   struct RegisterUsage {
1868     /// Holds the number of loop invariant values that are used in the loop.
1869     unsigned LoopInvariantRegs;
1870     /// Holds the maximum number of concurrent live intervals in the loop.
1871     unsigned MaxLocalUsers;
1872     /// Holds the number of instructions in the loop.
1873     unsigned NumInstructions;
1874   };
1875
1876   /// \return Returns information about the register usages of the loop for the
1877   /// given vectorization factors.
1878   SmallVector<RegisterUsage, 8> calculateRegisterUsage(ArrayRef<unsigned> VFs);
1879
1880   /// Collect values we want to ignore in the cost model.
1881   void collectValuesToIgnore();
1882
1883   /// \returns The smallest bitwidth each instruction can be represented with.
1884   /// The vector equivalents of these instructions should be truncated to this
1885   /// type.
1886   const MapVector<Instruction *, uint64_t> &getMinimalBitwidths() const {
1887     return MinBWs;
1888   }
1889
1890   /// \returns True if it is more profitable to scalarize instruction \p I for
1891   /// vectorization factor \p VF.
1892   bool isProfitableToScalarize(Instruction *I, unsigned VF) const {
1893     auto Scalars = InstsToScalarize.find(VF);
1894     assert(Scalars != InstsToScalarize.end() &&
1895            "VF not yet analyzed for scalarization profitability");
1896     return Scalars->second.count(I);
1897   }
1898
1899   /// Returns true if \p I is known to be uniform after vectorization.
1900   bool isUniformAfterVectorization(Instruction *I, unsigned VF) const {
1901     if (VF == 1)
1902       return true;
1903     assert(Uniforms.count(VF) && "VF not yet analyzed for uniformity");
1904     auto UniformsPerVF = Uniforms.find(VF);
1905     return UniformsPerVF->second.count(I);
1906   }
1907
1908   /// Returns true if \p I is known to be scalar after vectorization.
1909   bool isScalarAfterVectorization(Instruction *I, unsigned VF) const {
1910     if (VF == 1)
1911       return true;
1912     assert(Scalars.count(VF) && "Scalar values are not calculated for VF");
1913     auto ScalarsPerVF = Scalars.find(VF);
1914     return ScalarsPerVF->second.count(I);
1915   }
1916
1917   /// \returns True if instruction \p I can be truncated to a smaller bitwidth
1918   /// for vectorization factor \p VF.
1919   bool canTruncateToMinimalBitwidth(Instruction *I, unsigned VF) const {
1920     return VF > 1 && MinBWs.count(I) && !isProfitableToScalarize(I, VF) &&
1921            !isScalarAfterVectorization(I, VF);
1922   }
1923
1924   /// Decision that was taken during cost calculation for memory instruction.
1925   enum InstWidening {
1926     CM_Unknown,
1927     CM_Widen,
1928     CM_Interleave,
1929     CM_GatherScatter,
1930     CM_Scalarize
1931   };
1932
1933   /// Save vectorization decision \p W and \p Cost taken by the cost model for
1934   /// instruction \p I and vector width \p VF.
1935   void setWideningDecision(Instruction *I, unsigned VF, InstWidening W,
1936                            unsigned Cost) {
1937     assert(VF >= 2 && "Expected VF >=2");
1938     WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
1939   }
1940
1941   /// Save vectorization decision \p W and \p Cost taken by the cost model for
1942   /// interleaving group \p Grp and vector width \p VF.
1943   void setWideningDecision(const InterleaveGroup *Grp, unsigned VF,
1944                            InstWidening W, unsigned Cost) {
1945     assert(VF >= 2 && "Expected VF >=2");
1946     /// Broadcast this decicion to all instructions inside the group.
1947     /// But the cost will be assigned to one instruction only.
1948     for (unsigned i = 0; i < Grp->getFactor(); ++i) {
1949       if (auto *I = Grp->getMember(i)) {
1950         if (Grp->getInsertPos() == I)
1951           WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
1952         else
1953           WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, 0);
1954       }
1955     }
1956   }
1957
1958   /// Return the cost model decision for the given instruction \p I and vector
1959   /// width \p VF. Return CM_Unknown if this instruction did not pass
1960   /// through the cost modeling.
1961   InstWidening getWideningDecision(Instruction *I, unsigned VF) {
1962     assert(VF >= 2 && "Expected VF >=2");
1963     std::pair<Instruction *, unsigned> InstOnVF = std::make_pair(I, VF);
1964     auto Itr = WideningDecisions.find(InstOnVF);
1965     if (Itr == WideningDecisions.end())
1966       return CM_Unknown;
1967     return Itr->second.first;
1968   }
1969
1970   /// Return the vectorization cost for the given instruction \p I and vector
1971   /// width \p VF.
1972   unsigned getWideningCost(Instruction *I, unsigned VF) {
1973     assert(VF >= 2 && "Expected VF >=2");
1974     std::pair<Instruction *, unsigned> InstOnVF = std::make_pair(I, VF);
1975     assert(WideningDecisions.count(InstOnVF) && "The cost is not calculated");
1976     return WideningDecisions[InstOnVF].second;
1977   }
1978
1979   /// Return True if instruction \p I is an optimizable truncate whose operand
1980   /// is an induction variable. Such a truncate will be removed by adding a new
1981   /// induction variable with the destination type.
1982   bool isOptimizableIVTruncate(Instruction *I, unsigned VF) {
1983
1984     // If the instruction is not a truncate, return false.
1985     auto *Trunc = dyn_cast<TruncInst>(I);
1986     if (!Trunc)
1987       return false;
1988
1989     // Get the source and destination types of the truncate.
1990     Type *SrcTy = ToVectorTy(cast<CastInst>(I)->getSrcTy(), VF);
1991     Type *DestTy = ToVectorTy(cast<CastInst>(I)->getDestTy(), VF);
1992
1993     // If the truncate is free for the given types, return false. Replacing a
1994     // free truncate with an induction variable would add an induction variable
1995     // update instruction to each iteration of the loop. We exclude from this
1996     // check the primary induction variable since it will need an update
1997     // instruction regardless.
1998     Value *Op = Trunc->getOperand(0);
1999     if (Op != Legal->getPrimaryInduction() && TTI.isTruncateFree(SrcTy, DestTy))
2000       return false;
2001
2002     // If the truncated value is not an induction variable, return false.
2003     return Legal->isInductionVariable(Op);
2004   }
2005
2006 private:
2007   /// \return An upper bound for the vectorization factor, larger than zero.
2008   /// One is returned if vectorization should best be avoided due to cost.
2009   unsigned computeFeasibleMaxVF(bool OptForSize);
2010
2011   /// The vectorization cost is a combination of the cost itself and a boolean
2012   /// indicating whether any of the contributing operations will actually
2013   /// operate on
2014   /// vector values after type legalization in the backend. If this latter value
2015   /// is
2016   /// false, then all operations will be scalarized (i.e. no vectorization has
2017   /// actually taken place).
2018   typedef std::pair<unsigned, bool> VectorizationCostTy;
2019
2020   /// Returns the expected execution cost. The unit of the cost does
2021   /// not matter because we use the 'cost' units to compare different
2022   /// vector widths. The cost that is returned is *not* normalized by
2023   /// the factor width.
2024   VectorizationCostTy expectedCost(unsigned VF);
2025
2026   /// Returns the execution time cost of an instruction for a given vector
2027   /// width. Vector width of one means scalar.
2028   VectorizationCostTy getInstructionCost(Instruction *I, unsigned VF);
2029
2030   /// The cost-computation logic from getInstructionCost which provides
2031   /// the vector type as an output parameter.
2032   unsigned getInstructionCost(Instruction *I, unsigned VF, Type *&VectorTy);
2033
2034   /// Calculate vectorization cost of memory instruction \p I.
2035   unsigned getMemoryInstructionCost(Instruction *I, unsigned VF);
2036
2037   /// The cost computation for scalarized memory instruction.
2038   unsigned getMemInstScalarizationCost(Instruction *I, unsigned VF);
2039
2040   /// The cost computation for interleaving group of memory instructions.
2041   unsigned getInterleaveGroupCost(Instruction *I, unsigned VF);
2042
2043   /// The cost computation for Gather/Scatter instruction.
2044   unsigned getGatherScatterCost(Instruction *I, unsigned VF);
2045
2046   /// The cost computation for widening instruction \p I with consecutive
2047   /// memory access.
2048   unsigned getConsecutiveMemOpCost(Instruction *I, unsigned VF);
2049
2050   /// The cost calculation for Load instruction \p I with uniform pointer -
2051   /// scalar load + broadcast.
2052   unsigned getUniformMemOpCost(Instruction *I, unsigned VF);
2053
2054   /// Returns whether the instruction is a load or store and will be a emitted
2055   /// as a vector operation.
2056   bool isConsecutiveLoadOrStore(Instruction *I);
2057
2058   /// Create an analysis remark that explains why vectorization failed
2059   ///
2060   /// \p RemarkName is the identifier for the remark.  \return the remark object
2061   /// that can be streamed to.
2062   OptimizationRemarkAnalysis createMissedAnalysis(StringRef RemarkName) {
2063     return ::createMissedAnalysis(Hints->vectorizeAnalysisPassName(),
2064                                   RemarkName, TheLoop);
2065   }
2066
2067   /// Map of scalar integer values to the smallest bitwidth they can be legally
2068   /// represented as. The vector equivalents of these values should be truncated
2069   /// to this type.
2070   MapVector<Instruction *, uint64_t> MinBWs;
2071
2072   /// A type representing the costs for instructions if they were to be
2073   /// scalarized rather than vectorized. The entries are Instruction-Cost
2074   /// pairs.
2075   typedef DenseMap<Instruction *, unsigned> ScalarCostsTy;
2076
2077   /// A set containing all BasicBlocks that are known to present after
2078   /// vectorization as a predicated block.
2079   SmallPtrSet<BasicBlock *, 4> PredicatedBBsAfterVectorization;
2080
2081   /// A map holding scalar costs for different vectorization factors. The
2082   /// presence of a cost for an instruction in the mapping indicates that the
2083   /// instruction will be scalarized when vectorizing with the associated
2084   /// vectorization factor. The entries are VF-ScalarCostTy pairs.
2085   DenseMap<unsigned, ScalarCostsTy> InstsToScalarize;
2086
2087   /// Holds the instructions known to be uniform after vectorization.
2088   /// The data is collected per VF.
2089   DenseMap<unsigned, SmallPtrSet<Instruction *, 4>> Uniforms;
2090
2091   /// Holds the instructions known to be scalar after vectorization.
2092   /// The data is collected per VF.
2093   DenseMap<unsigned, SmallPtrSet<Instruction *, 4>> Scalars;
2094
2095   /// Holds the instructions (address computations) that are forced to be
2096   /// scalarized.
2097   DenseMap<unsigned, SmallPtrSet<Instruction *, 4>> ForcedScalars;
2098
2099   /// Returns the expected difference in cost from scalarizing the expression
2100   /// feeding a predicated instruction \p PredInst. The instructions to
2101   /// scalarize and their scalar costs are collected in \p ScalarCosts. A
2102   /// non-negative return value implies the expression will be scalarized.
2103   /// Currently, only single-use chains are considered for scalarization.
2104   int computePredInstDiscount(Instruction *PredInst, ScalarCostsTy &ScalarCosts,
2105                               unsigned VF);
2106
2107   /// Collects the instructions to scalarize for each predicated instruction in
2108   /// the loop.
2109   void collectInstsToScalarize(unsigned VF);
2110
2111   /// Collect the instructions that are uniform after vectorization. An
2112   /// instruction is uniform if we represent it with a single scalar value in
2113   /// the vectorized loop corresponding to each vector iteration. Examples of
2114   /// uniform instructions include pointer operands of consecutive or
2115   /// interleaved memory accesses. Note that although uniformity implies an
2116   /// instruction will be scalar, the reverse is not true. In general, a
2117   /// scalarized instruction will be represented by VF scalar values in the
2118   /// vectorized loop, each corresponding to an iteration of the original
2119   /// scalar loop.
2120   void collectLoopUniforms(unsigned VF);
2121
2122   /// Collect the instructions that are scalar after vectorization. An
2123   /// instruction is scalar if it is known to be uniform or will be scalarized
2124   /// during vectorization. Non-uniform scalarized instructions will be
2125   /// represented by VF values in the vectorized loop, each corresponding to an
2126   /// iteration of the original scalar loop.
2127   void collectLoopScalars(unsigned VF);
2128
2129   /// Collect Uniform and Scalar values for the given \p VF.
2130   /// The sets depend on CM decision for Load/Store instructions
2131   /// that may be vectorized as interleave, gather-scatter or scalarized.
2132   void collectUniformsAndScalars(unsigned VF) {
2133     // Do the analysis once.
2134     if (VF == 1 || Uniforms.count(VF))
2135       return;
2136     setCostBasedWideningDecision(VF);
2137     collectLoopUniforms(VF);
2138     collectLoopScalars(VF);
2139   }
2140
2141   /// Keeps cost model vectorization decision and cost for instructions.
2142   /// Right now it is used for memory instructions only.
2143   typedef DenseMap<std::pair<Instruction *, unsigned>,
2144                    std::pair<InstWidening, unsigned>>
2145       DecisionList;
2146
2147   DecisionList WideningDecisions;
2148
2149 public:
2150   /// The loop that we evaluate.
2151   Loop *TheLoop;
2152   /// Predicated scalar evolution analysis.
2153   PredicatedScalarEvolution &PSE;
2154   /// Loop Info analysis.
2155   LoopInfo *LI;
2156   /// Vectorization legality.
2157   LoopVectorizationLegality *Legal;
2158   /// Vector target information.
2159   const TargetTransformInfo &TTI;
2160   /// Target Library Info.
2161   const TargetLibraryInfo *TLI;
2162   /// Demanded bits analysis.
2163   DemandedBits *DB;
2164   /// Assumption cache.
2165   AssumptionCache *AC;
2166   /// Interface to emit optimization remarks.
2167   OptimizationRemarkEmitter *ORE;
2168
2169   const Function *TheFunction;
2170   /// Loop Vectorize Hint.
2171   const LoopVectorizeHints *Hints;
2172   /// Values to ignore in the cost model.
2173   SmallPtrSet<const Value *, 16> ValuesToIgnore;
2174   /// Values to ignore in the cost model when VF > 1.
2175   SmallPtrSet<const Value *, 16> VecValuesToIgnore;
2176 };
2177
2178 /// LoopVectorizationPlanner - drives the vectorization process after having
2179 /// passed Legality checks.
2180 class LoopVectorizationPlanner {
2181 public:
2182   LoopVectorizationPlanner(Loop *OrigLoop, LoopInfo *LI,
2183                            LoopVectorizationLegality *Legal,
2184                            LoopVectorizationCostModel &CM)
2185       : OrigLoop(OrigLoop), LI(LI), Legal(Legal), CM(CM) {}
2186
2187   ~LoopVectorizationPlanner() {}
2188
2189   /// Plan how to best vectorize, return the best VF and its cost.
2190   LoopVectorizationCostModel::VectorizationFactor plan(bool OptForSize,
2191                                                        unsigned UserVF);
2192
2193   /// Generate the IR code for the vectorized loop.
2194   void executePlan(InnerLoopVectorizer &ILV);
2195
2196 protected:
2197   /// Collect the instructions from the original loop that would be trivially
2198   /// dead in the vectorized loop if generated.
2199   void collectTriviallyDeadInstructions(
2200       SmallPtrSetImpl<Instruction *> &DeadInstructions);
2201
2202 private:
2203   /// The loop that we evaluate.
2204   Loop *OrigLoop;
2205
2206   /// Loop Info analysis.
2207   LoopInfo *LI;
2208
2209   /// The legality analysis.
2210   LoopVectorizationLegality *Legal;
2211
2212   /// The profitablity analysis.
2213   LoopVectorizationCostModel &CM;
2214 };
2215
2216 /// \brief This holds vectorization requirements that must be verified late in
2217 /// the process. The requirements are set by legalize and costmodel. Once
2218 /// vectorization has been determined to be possible and profitable the
2219 /// requirements can be verified by looking for metadata or compiler options.
2220 /// For example, some loops require FP commutativity which is only allowed if
2221 /// vectorization is explicitly specified or if the fast-math compiler option
2222 /// has been provided.
2223 /// Late evaluation of these requirements allows helpful diagnostics to be
2224 /// composed that tells the user what need to be done to vectorize the loop. For
2225 /// example, by specifying #pragma clang loop vectorize or -ffast-math. Late
2226 /// evaluation should be used only when diagnostics can generated that can be
2227 /// followed by a non-expert user.
2228 class LoopVectorizationRequirements {
2229 public:
2230   LoopVectorizationRequirements(OptimizationRemarkEmitter &ORE)
2231       : NumRuntimePointerChecks(0), UnsafeAlgebraInst(nullptr), ORE(ORE) {}
2232
2233   void addUnsafeAlgebraInst(Instruction *I) {
2234     // First unsafe algebra instruction.
2235     if (!UnsafeAlgebraInst)
2236       UnsafeAlgebraInst = I;
2237   }
2238
2239   void addRuntimePointerChecks(unsigned Num) { NumRuntimePointerChecks = Num; }
2240
2241   bool doesNotMeet(Function *F, Loop *L, const LoopVectorizeHints &Hints) {
2242     const char *PassName = Hints.vectorizeAnalysisPassName();
2243     bool Failed = false;
2244     if (UnsafeAlgebraInst && !Hints.allowReordering()) {
2245       ORE.emit(
2246           OptimizationRemarkAnalysisFPCommute(PassName, "CantReorderFPOps",
2247                                               UnsafeAlgebraInst->getDebugLoc(),
2248                                               UnsafeAlgebraInst->getParent())
2249           << "loop not vectorized: cannot prove it is safe to reorder "
2250              "floating-point operations");
2251       Failed = true;
2252     }
2253
2254     // Test if runtime memcheck thresholds are exceeded.
2255     bool PragmaThresholdReached =
2256         NumRuntimePointerChecks > PragmaVectorizeMemoryCheckThreshold;
2257     bool ThresholdReached =
2258         NumRuntimePointerChecks > VectorizerParams::RuntimeMemoryCheckThreshold;
2259     if ((ThresholdReached && !Hints.allowReordering()) ||
2260         PragmaThresholdReached) {
2261       ORE.emit(OptimizationRemarkAnalysisAliasing(PassName, "CantReorderMemOps",
2262                                                   L->getStartLoc(),
2263                                                   L->getHeader())
2264                << "loop not vectorized: cannot prove it is safe to reorder "
2265                   "memory operations");
2266       DEBUG(dbgs() << "LV: Too many memory checks needed.\n");
2267       Failed = true;
2268     }
2269
2270     return Failed;
2271   }
2272
2273 private:
2274   unsigned NumRuntimePointerChecks;
2275   Instruction *UnsafeAlgebraInst;
2276
2277   /// Interface to emit optimization remarks.
2278   OptimizationRemarkEmitter &ORE;
2279 };
2280
2281 static void addAcyclicInnerLoop(Loop &L, SmallVectorImpl<Loop *> &V) {
2282   if (L.empty()) {
2283     if (!hasCyclesInLoopBody(L))
2284       V.push_back(&L);
2285     return;
2286   }
2287   for (Loop *InnerL : L)
2288     addAcyclicInnerLoop(*InnerL, V);
2289 }
2290
2291 /// The LoopVectorize Pass.
2292 struct LoopVectorize : public FunctionPass {
2293   /// Pass identification, replacement for typeid
2294   static char ID;
2295
2296   explicit LoopVectorize(bool NoUnrolling = false, bool AlwaysVectorize = true)
2297       : FunctionPass(ID) {
2298     Impl.DisableUnrolling = NoUnrolling;
2299     Impl.AlwaysVectorize = AlwaysVectorize;
2300     initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
2301   }
2302
2303   LoopVectorizePass Impl;
2304
2305   bool runOnFunction(Function &F) override {
2306     if (skipFunction(F))
2307       return false;
2308
2309     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
2310     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2311     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
2312     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2313     auto *BFI = &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI();
2314     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
2315     auto *TLI = TLIP ? &TLIP->getTLI() : nullptr;
2316     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
2317     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
2318     auto *LAA = &getAnalysis<LoopAccessLegacyAnalysis>();
2319     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
2320     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
2321
2322     std::function<const LoopAccessInfo &(Loop &)> GetLAA =
2323         [&](Loop &L) -> const LoopAccessInfo & { return LAA->getInfo(&L); };
2324
2325     return Impl.runImpl(F, *SE, *LI, *TTI, *DT, *BFI, TLI, *DB, *AA, *AC,
2326                         GetLAA, *ORE);
2327   }
2328
2329   void getAnalysisUsage(AnalysisUsage &AU) const override {
2330     AU.addRequired<AssumptionCacheTracker>();
2331     AU.addRequired<BlockFrequencyInfoWrapperPass>();
2332     AU.addRequired<DominatorTreeWrapperPass>();
2333     AU.addRequired<LoopInfoWrapperPass>();
2334     AU.addRequired<ScalarEvolutionWrapperPass>();
2335     AU.addRequired<TargetTransformInfoWrapperPass>();
2336     AU.addRequired<AAResultsWrapperPass>();
2337     AU.addRequired<LoopAccessLegacyAnalysis>();
2338     AU.addRequired<DemandedBitsWrapperPass>();
2339     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
2340     AU.addPreserved<LoopInfoWrapperPass>();
2341     AU.addPreserved<DominatorTreeWrapperPass>();
2342     AU.addPreserved<BasicAAWrapperPass>();
2343     AU.addPreserved<GlobalsAAWrapperPass>();
2344   }
2345 };
2346
2347 } // end anonymous namespace
2348
2349 //===----------------------------------------------------------------------===//
2350 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
2351 // LoopVectorizationCostModel and LoopVectorizationPlanner.
2352 //===----------------------------------------------------------------------===//
2353
2354 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
2355   // We need to place the broadcast of invariant variables outside the loop.
2356   Instruction *Instr = dyn_cast<Instruction>(V);
2357   bool NewInstr = (Instr && Instr->getParent() == LoopVectorBody);
2358   bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
2359
2360   // Place the code for broadcasting invariant variables in the new preheader.
2361   IRBuilder<>::InsertPointGuard Guard(Builder);
2362   if (Invariant)
2363     Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
2364
2365   // Broadcast the scalar into all locations in the vector.
2366   Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
2367
2368   return Shuf;
2369 }
2370
2371 void InnerLoopVectorizer::createVectorIntOrFpInductionPHI(
2372     const InductionDescriptor &II, Value *Step, Instruction *EntryVal) {
2373   Value *Start = II.getStartValue();
2374
2375   // Construct the initial value of the vector IV in the vector loop preheader
2376   auto CurrIP = Builder.saveIP();
2377   Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
2378   if (isa<TruncInst>(EntryVal)) {
2379     assert(Start->getType()->isIntegerTy() &&
2380            "Truncation requires an integer type");
2381     auto *TruncType = cast<IntegerType>(EntryVal->getType());
2382     Step = Builder.CreateTrunc(Step, TruncType);
2383     Start = Builder.CreateCast(Instruction::Trunc, Start, TruncType);
2384   }
2385   Value *SplatStart = Builder.CreateVectorSplat(VF, Start);
2386   Value *SteppedStart =
2387       getStepVector(SplatStart, 0, Step, II.getInductionOpcode());
2388
2389   // We create vector phi nodes for both integer and floating-point induction
2390   // variables. Here, we determine the kind of arithmetic we will perform.
2391   Instruction::BinaryOps AddOp;
2392   Instruction::BinaryOps MulOp;
2393   if (Step->getType()->isIntegerTy()) {
2394     AddOp = Instruction::Add;
2395     MulOp = Instruction::Mul;
2396   } else {
2397     AddOp = II.getInductionOpcode();
2398     MulOp = Instruction::FMul;
2399   }
2400
2401   // Multiply the vectorization factor by the step using integer or
2402   // floating-point arithmetic as appropriate.
2403   Value *ConstVF = getSignedIntOrFpConstant(Step->getType(), VF);
2404   Value *Mul = addFastMathFlag(Builder.CreateBinOp(MulOp, Step, ConstVF));
2405
2406   // Create a vector splat to use in the induction update.
2407   //
2408   // FIXME: If the step is non-constant, we create the vector splat with
2409   //        IRBuilder. IRBuilder can constant-fold the multiply, but it doesn't
2410   //        handle a constant vector splat.
2411   Value *SplatVF = isa<Constant>(Mul)
2412                        ? ConstantVector::getSplat(VF, cast<Constant>(Mul))
2413                        : Builder.CreateVectorSplat(VF, Mul);
2414   Builder.restoreIP(CurrIP);
2415
2416   // We may need to add the step a number of times, depending on the unroll
2417   // factor. The last of those goes into the PHI.
2418   PHINode *VecInd = PHINode::Create(SteppedStart->getType(), 2, "vec.ind",
2419                                     &*LoopVectorBody->getFirstInsertionPt());
2420   Instruction *LastInduction = VecInd;
2421   VectorParts Entry(UF);
2422   for (unsigned Part = 0; Part < UF; ++Part) {
2423     Entry[Part] = LastInduction;
2424     LastInduction = cast<Instruction>(addFastMathFlag(
2425         Builder.CreateBinOp(AddOp, LastInduction, SplatVF, "step.add")));
2426   }
2427   VectorLoopValueMap.initVector(EntryVal, Entry);
2428   if (isa<TruncInst>(EntryVal))
2429     addMetadata(Entry, EntryVal);
2430
2431   // Move the last step to the end of the latch block. This ensures consistent
2432   // placement of all induction updates.
2433   auto *LoopVectorLatch = LI->getLoopFor(LoopVectorBody)->getLoopLatch();
2434   auto *Br = cast<BranchInst>(LoopVectorLatch->getTerminator());
2435   auto *ICmp = cast<Instruction>(Br->getCondition());
2436   LastInduction->moveBefore(ICmp);
2437   LastInduction->setName("vec.ind.next");
2438
2439   VecInd->addIncoming(SteppedStart, LoopVectorPreHeader);
2440   VecInd->addIncoming(LastInduction, LoopVectorLatch);
2441 }
2442
2443 bool InnerLoopVectorizer::shouldScalarizeInstruction(Instruction *I) const {
2444   return Cost->isScalarAfterVectorization(I, VF) ||
2445          Cost->isProfitableToScalarize(I, VF);
2446 }
2447
2448 bool InnerLoopVectorizer::needsScalarInduction(Instruction *IV) const {
2449   if (shouldScalarizeInstruction(IV))
2450     return true;
2451   auto isScalarInst = [&](User *U) -> bool {
2452     auto *I = cast<Instruction>(U);
2453     return (OrigLoop->contains(I) && shouldScalarizeInstruction(I));
2454   };
2455   return any_of(IV->users(), isScalarInst);
2456 }
2457
2458 void InnerLoopVectorizer::widenIntOrFpInduction(PHINode *IV, TruncInst *Trunc) {
2459
2460   assert((IV->getType()->isIntegerTy() || IV != OldInduction) &&
2461          "Primary induction variable must have an integer type");
2462
2463   auto II = Legal->getInductionVars()->find(IV);
2464   assert(II != Legal->getInductionVars()->end() && "IV is not an induction");
2465
2466   auto ID = II->second;
2467   assert(IV->getType() == ID.getStartValue()->getType() && "Types must match");
2468
2469   // The scalar value to broadcast. This will be derived from the canonical
2470   // induction variable.
2471   Value *ScalarIV = nullptr;
2472
2473   // The value from the original loop to which we are mapping the new induction
2474   // variable.
2475   Instruction *EntryVal = Trunc ? cast<Instruction>(Trunc) : IV;
2476
2477   // True if we have vectorized the induction variable.
2478   auto VectorizedIV = false;
2479
2480   // Determine if we want a scalar version of the induction variable. This is
2481   // true if the induction variable itself is not widened, or if it has at
2482   // least one user in the loop that is not widened.
2483   auto NeedsScalarIV = VF > 1 && needsScalarInduction(EntryVal);
2484
2485   // Generate code for the induction step. Note that induction steps are
2486   // required to be loop-invariant
2487   assert(PSE.getSE()->isLoopInvariant(ID.getStep(), OrigLoop) &&
2488          "Induction step should be loop invariant");
2489   auto &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
2490   Value *Step = nullptr;
2491   if (PSE.getSE()->isSCEVable(IV->getType())) {
2492     SCEVExpander Exp(*PSE.getSE(), DL, "induction");
2493     Step = Exp.expandCodeFor(ID.getStep(), ID.getStep()->getType(),
2494                              LoopVectorPreHeader->getTerminator());
2495   } else {
2496     Step = cast<SCEVUnknown>(ID.getStep())->getValue();
2497   }
2498
2499   // Try to create a new independent vector induction variable. If we can't
2500   // create the phi node, we will splat the scalar induction variable in each
2501   // loop iteration.
2502   if (VF > 1 && !shouldScalarizeInstruction(EntryVal)) {
2503     createVectorIntOrFpInductionPHI(ID, Step, EntryVal);
2504     VectorizedIV = true;
2505   }
2506
2507   // If we haven't yet vectorized the induction variable, or if we will create
2508   // a scalar one, we need to define the scalar induction variable and step
2509   // values. If we were given a truncation type, truncate the canonical
2510   // induction variable and step. Otherwise, derive these values from the
2511   // induction descriptor.
2512   if (!VectorizedIV || NeedsScalarIV) {
2513     ScalarIV = Induction;
2514     if (IV != OldInduction) {
2515       ScalarIV = IV->getType()->isIntegerTy()
2516                      ? Builder.CreateSExtOrTrunc(Induction, IV->getType())
2517                      : Builder.CreateCast(Instruction::SIToFP, Induction,
2518                                           IV->getType());
2519       ScalarIV = ID.transform(Builder, ScalarIV, PSE.getSE(), DL);
2520       ScalarIV->setName("offset.idx");
2521     }
2522     if (Trunc) {
2523       auto *TruncType = cast<IntegerType>(Trunc->getType());
2524       assert(Step->getType()->isIntegerTy() &&
2525              "Truncation requires an integer step");
2526       ScalarIV = Builder.CreateTrunc(ScalarIV, TruncType);
2527       Step = Builder.CreateTrunc(Step, TruncType);
2528     }
2529   }
2530
2531   // If we haven't yet vectorized the induction variable, splat the scalar
2532   // induction variable, and build the necessary step vectors.
2533   if (!VectorizedIV) {
2534     Value *Broadcasted = getBroadcastInstrs(ScalarIV);
2535     VectorParts Entry(UF);
2536     for (unsigned Part = 0; Part < UF; ++Part)
2537       Entry[Part] =
2538           getStepVector(Broadcasted, VF * Part, Step, ID.getInductionOpcode());
2539     VectorLoopValueMap.initVector(EntryVal, Entry);
2540     if (Trunc)
2541       addMetadata(Entry, Trunc);
2542   }
2543
2544   // If an induction variable is only used for counting loop iterations or
2545   // calculating addresses, it doesn't need to be widened. Create scalar steps
2546   // that can be used by instructions we will later scalarize. Note that the
2547   // addition of the scalar steps will not increase the number of instructions
2548   // in the loop in the common case prior to InstCombine. We will be trading
2549   // one vector extract for each scalar step.
2550   if (NeedsScalarIV)
2551     buildScalarSteps(ScalarIV, Step, EntryVal, ID);
2552 }
2553
2554 Value *InnerLoopVectorizer::getStepVector(Value *Val, int StartIdx, Value *Step,
2555                                           Instruction::BinaryOps BinOp) {
2556   // Create and check the types.
2557   assert(Val->getType()->isVectorTy() && "Must be a vector");
2558   int VLen = Val->getType()->getVectorNumElements();
2559
2560   Type *STy = Val->getType()->getScalarType();
2561   assert((STy->isIntegerTy() || STy->isFloatingPointTy()) &&
2562          "Induction Step must be an integer or FP");
2563   assert(Step->getType() == STy && "Step has wrong type");
2564
2565   SmallVector<Constant *, 8> Indices;
2566
2567   if (STy->isIntegerTy()) {
2568     // Create a vector of consecutive numbers from zero to VF.
2569     for (int i = 0; i < VLen; ++i)
2570       Indices.push_back(ConstantInt::get(STy, StartIdx + i));
2571
2572     // Add the consecutive indices to the vector value.
2573     Constant *Cv = ConstantVector::get(Indices);
2574     assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
2575     Step = Builder.CreateVectorSplat(VLen, Step);
2576     assert(Step->getType() == Val->getType() && "Invalid step vec");
2577     // FIXME: The newly created binary instructions should contain nsw/nuw flags,
2578     // which can be found from the original scalar operations.
2579     Step = Builder.CreateMul(Cv, Step);
2580     return Builder.CreateAdd(Val, Step, "induction");
2581   }
2582
2583   // Floating point induction.
2584   assert((BinOp == Instruction::FAdd || BinOp == Instruction::FSub) &&
2585          "Binary Opcode should be specified for FP induction");
2586   // Create a vector of consecutive numbers from zero to VF.
2587   for (int i = 0; i < VLen; ++i)
2588     Indices.push_back(ConstantFP::get(STy, (double)(StartIdx + i)));
2589
2590   // Add the consecutive indices to the vector value.
2591   Constant *Cv = ConstantVector::get(Indices);
2592
2593   Step = Builder.CreateVectorSplat(VLen, Step);
2594
2595   // Floating point operations had to be 'fast' to enable the induction.
2596   FastMathFlags Flags;
2597   Flags.setUnsafeAlgebra();
2598
2599   Value *MulOp = Builder.CreateFMul(Cv, Step);
2600   if (isa<Instruction>(MulOp))
2601     // Have to check, MulOp may be a constant
2602     cast<Instruction>(MulOp)->setFastMathFlags(Flags);
2603
2604   Value *BOp = Builder.CreateBinOp(BinOp, Val, MulOp, "induction");
2605   if (isa<Instruction>(BOp))
2606     cast<Instruction>(BOp)->setFastMathFlags(Flags);
2607   return BOp;
2608 }
2609
2610 void InnerLoopVectorizer::buildScalarSteps(Value *ScalarIV, Value *Step,
2611                                            Value *EntryVal,
2612                                            const InductionDescriptor &ID) {
2613
2614   // We shouldn't have to build scalar steps if we aren't vectorizing.
2615   assert(VF > 1 && "VF should be greater than one");
2616
2617   // Get the value type and ensure it and the step have the same integer type.
2618   Type *ScalarIVTy = ScalarIV->getType()->getScalarType();
2619   assert(ScalarIVTy == Step->getType() &&
2620          "Val and Step should have the same type");
2621
2622   // We build scalar steps for both integer and floating-point induction
2623   // variables. Here, we determine the kind of arithmetic we will perform.
2624   Instruction::BinaryOps AddOp;
2625   Instruction::BinaryOps MulOp;
2626   if (ScalarIVTy->isIntegerTy()) {
2627     AddOp = Instruction::Add;
2628     MulOp = Instruction::Mul;
2629   } else {
2630     AddOp = ID.getInductionOpcode();
2631     MulOp = Instruction::FMul;
2632   }
2633
2634   // Determine the number of scalars we need to generate for each unroll
2635   // iteration. If EntryVal is uniform, we only need to generate the first
2636   // lane. Otherwise, we generate all VF values.
2637   unsigned Lanes =
2638     Cost->isUniformAfterVectorization(cast<Instruction>(EntryVal), VF) ? 1 : VF;
2639
2640   // Compute the scalar steps and save the results in VectorLoopValueMap.
2641   ScalarParts Entry(UF);
2642   for (unsigned Part = 0; Part < UF; ++Part) {
2643     Entry[Part].resize(VF);
2644     for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
2645       auto *StartIdx = getSignedIntOrFpConstant(ScalarIVTy, VF * Part + Lane);
2646       auto *Mul = addFastMathFlag(Builder.CreateBinOp(MulOp, StartIdx, Step));
2647       auto *Add = addFastMathFlag(Builder.CreateBinOp(AddOp, ScalarIV, Mul));
2648       Entry[Part][Lane] = Add;
2649     }
2650   }
2651   VectorLoopValueMap.initScalar(EntryVal, Entry);
2652 }
2653
2654 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
2655
2656   const ValueToValueMap &Strides = getSymbolicStrides() ? *getSymbolicStrides() :
2657     ValueToValueMap();
2658
2659   int Stride = getPtrStride(PSE, Ptr, TheLoop, Strides, true, false);
2660   if (Stride == 1 || Stride == -1)
2661     return Stride;
2662   return 0;
2663 }
2664
2665 bool LoopVectorizationLegality::isUniform(Value *V) {
2666   return LAI->isUniform(V);
2667 }
2668
2669 const InnerLoopVectorizer::VectorParts &
2670 InnerLoopVectorizer::getVectorValue(Value *V) {
2671   assert(V != Induction && "The new induction variable should not be used.");
2672   assert(!V->getType()->isVectorTy() && "Can't widen a vector");
2673   assert(!V->getType()->isVoidTy() && "Type does not produce a value");
2674
2675   // If we have a stride that is replaced by one, do it here.
2676   if (Legal->hasStride(V))
2677     V = ConstantInt::get(V->getType(), 1);
2678
2679   // If we have this scalar in the map, return it.
2680   if (VectorLoopValueMap.hasVector(V))
2681     return VectorLoopValueMap.VectorMapStorage[V];
2682
2683   // If the value has not been vectorized, check if it has been scalarized
2684   // instead. If it has been scalarized, and we actually need the value in
2685   // vector form, we will construct the vector values on demand.
2686   if (VectorLoopValueMap.hasScalar(V)) {
2687
2688     // Initialize a new vector map entry.
2689     VectorParts Entry(UF);
2690
2691     // If we've scalarized a value, that value should be an instruction.
2692     auto *I = cast<Instruction>(V);
2693
2694     // If we aren't vectorizing, we can just copy the scalar map values over to
2695     // the vector map.
2696     if (VF == 1) {
2697       for (unsigned Part = 0; Part < UF; ++Part)
2698         Entry[Part] = getScalarValue(V, Part, 0);
2699       return VectorLoopValueMap.initVector(V, Entry);
2700     }
2701
2702     // Get the last scalar instruction we generated for V. If the value is
2703     // known to be uniform after vectorization, this corresponds to lane zero
2704     // of the last unroll iteration. Otherwise, the last instruction is the one
2705     // we created for the last vector lane of the last unroll iteration.
2706     unsigned LastLane = Cost->isUniformAfterVectorization(I, VF) ? 0 : VF - 1;
2707     auto *LastInst = cast<Instruction>(getScalarValue(V, UF - 1, LastLane));
2708
2709     // Set the insert point after the last scalarized instruction. This ensures
2710     // the insertelement sequence will directly follow the scalar definitions.
2711     auto OldIP = Builder.saveIP();
2712     auto NewIP = std::next(BasicBlock::iterator(LastInst));
2713     Builder.SetInsertPoint(&*NewIP);
2714
2715     // However, if we are vectorizing, we need to construct the vector values.
2716     // If the value is known to be uniform after vectorization, we can just
2717     // broadcast the scalar value corresponding to lane zero for each unroll
2718     // iteration. Otherwise, we construct the vector values using insertelement
2719     // instructions. Since the resulting vectors are stored in
2720     // VectorLoopValueMap, we will only generate the insertelements once.
2721     for (unsigned Part = 0; Part < UF; ++Part) {
2722       Value *VectorValue = nullptr;
2723       if (Cost->isUniformAfterVectorization(I, VF)) {
2724         VectorValue = getBroadcastInstrs(getScalarValue(V, Part, 0));
2725       } else {
2726         VectorValue = UndefValue::get(VectorType::get(V->getType(), VF));
2727         for (unsigned Lane = 0; Lane < VF; ++Lane)
2728           VectorValue = Builder.CreateInsertElement(
2729               VectorValue, getScalarValue(V, Part, Lane),
2730               Builder.getInt32(Lane));
2731       }
2732       Entry[Part] = VectorValue;
2733     }
2734     Builder.restoreIP(OldIP);
2735     return VectorLoopValueMap.initVector(V, Entry);
2736   }
2737
2738   // If this scalar is unknown, assume that it is a constant or that it is
2739   // loop invariant. Broadcast V and save the value for future uses.
2740   Value *B = getBroadcastInstrs(V);
2741   return VectorLoopValueMap.initVector(V, VectorParts(UF, B));
2742 }
2743
2744 Value *InnerLoopVectorizer::getScalarValue(Value *V, unsigned Part,
2745                                            unsigned Lane) {
2746
2747   // If the value is not an instruction contained in the loop, it should
2748   // already be scalar.
2749   if (OrigLoop->isLoopInvariant(V))
2750     return V;
2751
2752   assert(Lane > 0 ?
2753          !Cost->isUniformAfterVectorization(cast<Instruction>(V), VF)
2754          : true && "Uniform values only have lane zero");
2755
2756   // If the value from the original loop has not been vectorized, it is
2757   // represented by UF x VF scalar values in the new loop. Return the requested
2758   // scalar value.
2759   if (VectorLoopValueMap.hasScalar(V))
2760     return VectorLoopValueMap.ScalarMapStorage[V][Part][Lane];
2761
2762   // If the value has not been scalarized, get its entry in VectorLoopValueMap
2763   // for the given unroll part. If this entry is not a vector type (i.e., the
2764   // vectorization factor is one), there is no need to generate an
2765   // extractelement instruction.
2766   auto *U = getVectorValue(V)[Part];
2767   if (!U->getType()->isVectorTy()) {
2768     assert(VF == 1 && "Value not scalarized has non-vector type");
2769     return U;
2770   }
2771
2772   // Otherwise, the value from the original loop has been vectorized and is
2773   // represented by UF vector values. Extract and return the requested scalar
2774   // value from the appropriate vector lane.
2775   return Builder.CreateExtractElement(U, Builder.getInt32(Lane));
2776 }
2777
2778 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
2779   assert(Vec->getType()->isVectorTy() && "Invalid type");
2780   SmallVector<Constant *, 8> ShuffleMask;
2781   for (unsigned i = 0; i < VF; ++i)
2782     ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
2783
2784   return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
2785                                      ConstantVector::get(ShuffleMask),
2786                                      "reverse");
2787 }
2788
2789 // Try to vectorize the interleave group that \p Instr belongs to.
2790 //
2791 // E.g. Translate following interleaved load group (factor = 3):
2792 //   for (i = 0; i < N; i+=3) {
2793 //     R = Pic[i];             // Member of index 0
2794 //     G = Pic[i+1];           // Member of index 1
2795 //     B = Pic[i+2];           // Member of index 2
2796 //     ... // do something to R, G, B
2797 //   }
2798 // To:
2799 //   %wide.vec = load <12 x i32>                       ; Read 4 tuples of R,G,B
2800 //   %R.vec = shuffle %wide.vec, undef, <0, 3, 6, 9>   ; R elements
2801 //   %G.vec = shuffle %wide.vec, undef, <1, 4, 7, 10>  ; G elements
2802 //   %B.vec = shuffle %wide.vec, undef, <2, 5, 8, 11>  ; B elements
2803 //
2804 // Or translate following interleaved store group (factor = 3):
2805 //   for (i = 0; i < N; i+=3) {
2806 //     ... do something to R, G, B
2807 //     Pic[i]   = R;           // Member of index 0
2808 //     Pic[i+1] = G;           // Member of index 1
2809 //     Pic[i+2] = B;           // Member of index 2
2810 //   }
2811 // To:
2812 //   %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
2813 //   %B_U.vec = shuffle %B.vec, undef, <0, 1, 2, 3, u, u, u, u>
2814 //   %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
2815 //        <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>    ; Interleave R,G,B elements
2816 //   store <12 x i32> %interleaved.vec              ; Write 4 tuples of R,G,B
2817 void InnerLoopVectorizer::vectorizeInterleaveGroup(Instruction *Instr) {
2818   const InterleaveGroup *Group = Legal->getInterleavedAccessGroup(Instr);
2819   assert(Group && "Fail to get an interleaved access group.");
2820
2821   // Skip if current instruction is not the insert position.
2822   if (Instr != Group->getInsertPos())
2823     return;
2824
2825   Value *Ptr = getPointerOperand(Instr);
2826
2827   // Prepare for the vector type of the interleaved load/store.
2828   Type *ScalarTy = getMemInstValueType(Instr);
2829   unsigned InterleaveFactor = Group->getFactor();
2830   Type *VecTy = VectorType::get(ScalarTy, InterleaveFactor * VF);
2831   Type *PtrTy = VecTy->getPointerTo(getMemInstAddressSpace(Instr));
2832
2833   // Prepare for the new pointers.
2834   setDebugLocFromInst(Builder, Ptr);
2835   SmallVector<Value *, 2> NewPtrs;
2836   unsigned Index = Group->getIndex(Instr);
2837
2838   // If the group is reverse, adjust the index to refer to the last vector lane
2839   // instead of the first. We adjust the index from the first vector lane,
2840   // rather than directly getting the pointer for lane VF - 1, because the
2841   // pointer operand of the interleaved access is supposed to be uniform. For
2842   // uniform instructions, we're only required to generate a value for the
2843   // first vector lane in each unroll iteration.
2844   if (Group->isReverse())
2845     Index += (VF - 1) * Group->getFactor();
2846
2847   for (unsigned Part = 0; Part < UF; Part++) {
2848     Value *NewPtr = getScalarValue(Ptr, Part, 0);
2849
2850     // Notice current instruction could be any index. Need to adjust the address
2851     // to the member of index 0.
2852     //
2853     // E.g.  a = A[i+1];     // Member of index 1 (Current instruction)
2854     //       b = A[i];       // Member of index 0
2855     // Current pointer is pointed to A[i+1], adjust it to A[i].
2856     //
2857     // E.g.  A[i+1] = a;     // Member of index 1
2858     //       A[i]   = b;     // Member of index 0
2859     //       A[i+2] = c;     // Member of index 2 (Current instruction)
2860     // Current pointer is pointed to A[i+2], adjust it to A[i].
2861     NewPtr = Builder.CreateGEP(NewPtr, Builder.getInt32(-Index));
2862
2863     // Cast to the vector pointer type.
2864     NewPtrs.push_back(Builder.CreateBitCast(NewPtr, PtrTy));
2865   }
2866
2867   setDebugLocFromInst(Builder, Instr);
2868   Value *UndefVec = UndefValue::get(VecTy);
2869
2870   // Vectorize the interleaved load group.
2871   if (isa<LoadInst>(Instr)) {
2872
2873     // For each unroll part, create a wide load for the group.
2874     SmallVector<Value *, 2> NewLoads;
2875     for (unsigned Part = 0; Part < UF; Part++) {
2876       auto *NewLoad = Builder.CreateAlignedLoad(
2877           NewPtrs[Part], Group->getAlignment(), "wide.vec");
2878       addMetadata(NewLoad, Instr);
2879       NewLoads.push_back(NewLoad);
2880     }
2881
2882     // For each member in the group, shuffle out the appropriate data from the
2883     // wide loads.
2884     for (unsigned I = 0; I < InterleaveFactor; ++I) {
2885       Instruction *Member = Group->getMember(I);
2886
2887       // Skip the gaps in the group.
2888       if (!Member)
2889         continue;
2890
2891       VectorParts Entry(UF);
2892       Constant *StrideMask = createStrideMask(Builder, I, InterleaveFactor, VF);
2893       for (unsigned Part = 0; Part < UF; Part++) {
2894         Value *StridedVec = Builder.CreateShuffleVector(
2895             NewLoads[Part], UndefVec, StrideMask, "strided.vec");
2896
2897         // If this member has different type, cast the result type.
2898         if (Member->getType() != ScalarTy) {
2899           VectorType *OtherVTy = VectorType::get(Member->getType(), VF);
2900           StridedVec = Builder.CreateBitOrPointerCast(StridedVec, OtherVTy);
2901         }
2902
2903         Entry[Part] =
2904             Group->isReverse() ? reverseVector(StridedVec) : StridedVec;
2905       }
2906       VectorLoopValueMap.initVector(Member, Entry);
2907     }
2908     return;
2909   }
2910
2911   // The sub vector type for current instruction.
2912   VectorType *SubVT = VectorType::get(ScalarTy, VF);
2913
2914   // Vectorize the interleaved store group.
2915   for (unsigned Part = 0; Part < UF; Part++) {
2916     // Collect the stored vector from each member.
2917     SmallVector<Value *, 4> StoredVecs;
2918     for (unsigned i = 0; i < InterleaveFactor; i++) {
2919       // Interleaved store group doesn't allow a gap, so each index has a member
2920       Instruction *Member = Group->getMember(i);
2921       assert(Member && "Fail to get a member from an interleaved store group");
2922
2923       Value *StoredVec =
2924           getVectorValue(cast<StoreInst>(Member)->getValueOperand())[Part];
2925       if (Group->isReverse())
2926         StoredVec = reverseVector(StoredVec);
2927
2928       // If this member has different type, cast it to an unified type.
2929       if (StoredVec->getType() != SubVT)
2930         StoredVec = Builder.CreateBitOrPointerCast(StoredVec, SubVT);
2931
2932       StoredVecs.push_back(StoredVec);
2933     }
2934
2935     // Concatenate all vectors into a wide vector.
2936     Value *WideVec = concatenateVectors(Builder, StoredVecs);
2937
2938     // Interleave the elements in the wide vector.
2939     Constant *IMask = createInterleaveMask(Builder, VF, InterleaveFactor);
2940     Value *IVec = Builder.CreateShuffleVector(WideVec, UndefVec, IMask,
2941                                               "interleaved.vec");
2942
2943     Instruction *NewStoreInstr =
2944         Builder.CreateAlignedStore(IVec, NewPtrs[Part], Group->getAlignment());
2945     addMetadata(NewStoreInstr, Instr);
2946   }
2947 }
2948
2949 void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr) {
2950   // Attempt to issue a wide load.
2951   LoadInst *LI = dyn_cast<LoadInst>(Instr);
2952   StoreInst *SI = dyn_cast<StoreInst>(Instr);
2953
2954   assert((LI || SI) && "Invalid Load/Store instruction");
2955
2956   LoopVectorizationCostModel::InstWidening Decision =
2957       Cost->getWideningDecision(Instr, VF);
2958   assert(Decision != LoopVectorizationCostModel::CM_Unknown &&
2959          "CM decision should be taken at this point");
2960   if (Decision == LoopVectorizationCostModel::CM_Interleave)
2961     return vectorizeInterleaveGroup(Instr);
2962
2963   Type *ScalarDataTy = getMemInstValueType(Instr);
2964   Type *DataTy = VectorType::get(ScalarDataTy, VF);
2965   Value *Ptr = getPointerOperand(Instr);
2966   unsigned Alignment = getMemInstAlignment(Instr);
2967   // An alignment of 0 means target abi alignment. We need to use the scalar's
2968   // target abi alignment in such a case.
2969   const DataLayout &DL = Instr->getModule()->getDataLayout();
2970   if (!Alignment)
2971     Alignment = DL.getABITypeAlignment(ScalarDataTy);
2972   unsigned AddressSpace = getMemInstAddressSpace(Instr);
2973
2974   // Scalarize the memory instruction if necessary.
2975   if (Decision == LoopVectorizationCostModel::CM_Scalarize)
2976     return scalarizeInstruction(Instr, Legal->isScalarWithPredication(Instr));
2977
2978   // Determine if the pointer operand of the access is either consecutive or
2979   // reverse consecutive.
2980   int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
2981   bool Reverse = ConsecutiveStride < 0;
2982   bool CreateGatherScatter =
2983       (Decision == LoopVectorizationCostModel::CM_GatherScatter);
2984
2985   VectorParts VectorGep;
2986
2987   // Handle consecutive loads/stores.
2988   if (ConsecutiveStride) {
2989     Ptr = getScalarValue(Ptr, 0, 0);
2990   } else {
2991     // At this point we should vector version of GEP for Gather or Scatter
2992     assert(CreateGatherScatter && "The instruction should be scalarized");
2993     VectorGep = getVectorValue(Ptr);
2994   }
2995
2996   VectorParts Mask = createBlockInMask(Instr->getParent());
2997   // Handle Stores:
2998   if (SI) {
2999     assert(!Legal->isUniform(SI->getPointerOperand()) &&
3000            "We do not allow storing to uniform addresses");
3001     setDebugLocFromInst(Builder, SI);
3002     // We don't want to update the value in the map as it might be used in
3003     // another expression. So don't use a reference type for "StoredVal".
3004     VectorParts StoredVal = getVectorValue(SI->getValueOperand());
3005
3006     for (unsigned Part = 0; Part < UF; ++Part) {
3007       Instruction *NewSI = nullptr;
3008       if (CreateGatherScatter) {
3009         Value *MaskPart = Legal->isMaskRequired(SI) ? Mask[Part] : nullptr;
3010         NewSI = Builder.CreateMaskedScatter(StoredVal[Part], VectorGep[Part],
3011                                             Alignment, MaskPart);
3012       } else {
3013         // Calculate the pointer for the specific unroll-part.
3014         Value *PartPtr =
3015             Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(Part * VF));
3016
3017         if (Reverse) {
3018           // If we store to reverse consecutive memory locations, then we need
3019           // to reverse the order of elements in the stored value.
3020           StoredVal[Part] = reverseVector(StoredVal[Part]);
3021           // If the address is consecutive but reversed, then the
3022           // wide store needs to start at the last vector element.
3023           PartPtr =
3024               Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(-Part * VF));
3025           PartPtr =
3026               Builder.CreateGEP(nullptr, PartPtr, Builder.getInt32(1 - VF));
3027           Mask[Part] = reverseVector(Mask[Part]);
3028         }
3029
3030         Value *VecPtr =
3031             Builder.CreateBitCast(PartPtr, DataTy->getPointerTo(AddressSpace));
3032
3033         if (Legal->isMaskRequired(SI))
3034           NewSI = Builder.CreateMaskedStore(StoredVal[Part], VecPtr, Alignment,
3035                                             Mask[Part]);
3036         else
3037           NewSI =
3038               Builder.CreateAlignedStore(StoredVal[Part], VecPtr, Alignment);
3039       }
3040       addMetadata(NewSI, SI);
3041     }
3042     return;
3043   }
3044
3045   // Handle loads.
3046   assert(LI && "Must have a load instruction");
3047   setDebugLocFromInst(Builder, LI);
3048   VectorParts Entry(UF);
3049   for (unsigned Part = 0; Part < UF; ++Part) {
3050     Instruction *NewLI;
3051     if (CreateGatherScatter) {
3052       Value *MaskPart = Legal->isMaskRequired(LI) ? Mask[Part] : nullptr;
3053       NewLI = Builder.CreateMaskedGather(VectorGep[Part], Alignment, MaskPart,
3054                                          nullptr, "wide.masked.gather");
3055       Entry[Part] = NewLI;
3056     } else {
3057       // Calculate the pointer for the specific unroll-part.
3058       Value *PartPtr =
3059           Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(Part * VF));
3060
3061       if (Reverse) {
3062         // If the address is consecutive but reversed, then the
3063         // wide load needs to start at the last vector element.
3064         PartPtr = Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(-Part * VF));
3065         PartPtr = Builder.CreateGEP(nullptr, PartPtr, Builder.getInt32(1 - VF));
3066         Mask[Part] = reverseVector(Mask[Part]);
3067       }
3068
3069       Value *VecPtr =
3070           Builder.CreateBitCast(PartPtr, DataTy->getPointerTo(AddressSpace));
3071       if (Legal->isMaskRequired(LI))
3072         NewLI = Builder.CreateMaskedLoad(VecPtr, Alignment, Mask[Part],
3073                                          UndefValue::get(DataTy),
3074                                          "wide.masked.load");
3075       else
3076         NewLI = Builder.CreateAlignedLoad(VecPtr, Alignment, "wide.load");
3077       Entry[Part] = Reverse ? reverseVector(NewLI) : NewLI;
3078     }
3079     addMetadata(NewLI, LI);
3080   }
3081   VectorLoopValueMap.initVector(Instr, Entry);
3082 }
3083
3084 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr,
3085                                                bool IfPredicateInstr) {
3086   assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
3087   DEBUG(dbgs() << "LV: Scalarizing"
3088                << (IfPredicateInstr ? " and predicating:" : ":") << *Instr
3089                << '\n');
3090   // Holds vector parameters or scalars, in case of uniform vals.
3091   SmallVector<VectorParts, 4> Params;
3092
3093   setDebugLocFromInst(Builder, Instr);
3094
3095   // Does this instruction return a value ?
3096   bool IsVoidRetTy = Instr->getType()->isVoidTy();
3097
3098   // Initialize a new scalar map entry.
3099   ScalarParts Entry(UF);
3100
3101   VectorParts Cond;
3102   if (IfPredicateInstr)
3103     Cond = createBlockInMask(Instr->getParent());
3104
3105   // Determine the number of scalars we need to generate for each unroll
3106   // iteration. If the instruction is uniform, we only need to generate the
3107   // first lane. Otherwise, we generate all VF values.
3108   unsigned Lanes = Cost->isUniformAfterVectorization(Instr, VF) ? 1 : VF;
3109
3110   // For each vector unroll 'part':
3111   for (unsigned Part = 0; Part < UF; ++Part) {
3112     Entry[Part].resize(VF);
3113     // For each scalar that we create:
3114     for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
3115
3116       // Start if-block.
3117       Value *Cmp = nullptr;
3118       if (IfPredicateInstr) {
3119         Cmp = Cond[Part];
3120         if (Cmp->getType()->isVectorTy())
3121           Cmp = Builder.CreateExtractElement(Cmp, Builder.getInt32(Lane));
3122         Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cmp,
3123                                  ConstantInt::get(Cmp->getType(), 1));
3124       }
3125
3126       Instruction *Cloned = Instr->clone();
3127       if (!IsVoidRetTy)
3128         Cloned->setName(Instr->getName() + ".cloned");
3129
3130       // Replace the operands of the cloned instructions with their scalar
3131       // equivalents in the new loop.
3132       for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
3133         auto *NewOp = getScalarValue(Instr->getOperand(op), Part, Lane);
3134         Cloned->setOperand(op, NewOp);
3135       }
3136       addNewMetadata(Cloned, Instr);
3137
3138       // Place the cloned scalar in the new loop.
3139       Builder.Insert(Cloned);
3140
3141       // Add the cloned scalar to the scalar map entry.
3142       Entry[Part][Lane] = Cloned;
3143
3144       // If we just cloned a new assumption, add it the assumption cache.
3145       if (auto *II = dyn_cast<IntrinsicInst>(Cloned))
3146         if (II->getIntrinsicID() == Intrinsic::assume)
3147           AC->registerAssumption(II);
3148
3149       // End if-block.
3150       if (IfPredicateInstr)
3151         PredicatedInstructions.push_back(std::make_pair(Cloned, Cmp));
3152     }
3153   }
3154   VectorLoopValueMap.initScalar(Instr, Entry);
3155 }
3156
3157 PHINode *InnerLoopVectorizer::createInductionVariable(Loop *L, Value *Start,
3158                                                       Value *End, Value *Step,
3159                                                       Instruction *DL) {
3160   BasicBlock *Header = L->getHeader();
3161   BasicBlock *Latch = L->getLoopLatch();
3162   // As we're just creating this loop, it's possible no latch exists
3163   // yet. If so, use the header as this will be a single block loop.
3164   if (!Latch)
3165     Latch = Header;
3166
3167   IRBuilder<> Builder(&*Header->getFirstInsertionPt());
3168   Instruction *OldInst = getDebugLocFromInstOrOperands(OldInduction);
3169   setDebugLocFromInst(Builder, OldInst);
3170   auto *Induction = Builder.CreatePHI(Start->getType(), 2, "index");
3171
3172   Builder.SetInsertPoint(Latch->getTerminator());
3173   setDebugLocFromInst(Builder, OldInst);
3174
3175   // Create i+1 and fill the PHINode.
3176   Value *Next = Builder.CreateAdd(Induction, Step, "index.next");
3177   Induction->addIncoming(Start, L->getLoopPreheader());
3178   Induction->addIncoming(Next, Latch);
3179   // Create the compare.
3180   Value *ICmp = Builder.CreateICmpEQ(Next, End);
3181   Builder.CreateCondBr(ICmp, L->getExitBlock(), Header);
3182
3183   // Now we have two terminators. Remove the old one from the block.
3184   Latch->getTerminator()->eraseFromParent();
3185
3186   return Induction;
3187 }
3188
3189 Value *InnerLoopVectorizer::getOrCreateTripCount(Loop *L) {
3190   if (TripCount)
3191     return TripCount;
3192
3193   IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
3194   // Find the loop boundaries.
3195   ScalarEvolution *SE = PSE.getSE();
3196   const SCEV *BackedgeTakenCount = PSE.getBackedgeTakenCount();
3197   assert(BackedgeTakenCount != SE->getCouldNotCompute() &&
3198          "Invalid loop count");
3199
3200   Type *IdxTy = Legal->getWidestInductionType();
3201
3202   // The exit count might have the type of i64 while the phi is i32. This can
3203   // happen if we have an induction variable that is sign extended before the
3204   // compare. The only way that we get a backedge taken count is that the
3205   // induction variable was signed and as such will not overflow. In such a case
3206   // truncation is legal.
3207   if (BackedgeTakenCount->getType()->getPrimitiveSizeInBits() >
3208       IdxTy->getPrimitiveSizeInBits())
3209     BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount, IdxTy);
3210   BackedgeTakenCount = SE->getNoopOrZeroExtend(BackedgeTakenCount, IdxTy);
3211
3212   // Get the total trip count from the count by adding 1.
3213   const SCEV *ExitCount = SE->getAddExpr(
3214       BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType()));
3215
3216   const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
3217
3218   // Expand the trip count and place the new instructions in the preheader.
3219   // Notice that the pre-header does not change, only the loop body.
3220   SCEVExpander Exp(*SE, DL, "induction");
3221
3222   // Count holds the overall loop count (N).
3223   TripCount = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
3224                                 L->getLoopPreheader()->getTerminator());
3225
3226   if (TripCount->getType()->isPointerTy())
3227     TripCount =
3228         CastInst::CreatePointerCast(TripCount, IdxTy, "exitcount.ptrcnt.to.int",
3229                                     L->getLoopPreheader()->getTerminator());
3230
3231   return TripCount;
3232 }
3233
3234 Value *InnerLoopVectorizer::getOrCreateVectorTripCount(Loop *L) {
3235   if (VectorTripCount)
3236     return VectorTripCount;
3237
3238   Value *TC = getOrCreateTripCount(L);
3239   IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
3240
3241   // Now we need to generate the expression for the part of the loop that the
3242   // vectorized body will execute. This is equal to N - (N % Step) if scalar
3243   // iterations are not required for correctness, or N - Step, otherwise. Step
3244   // is equal to the vectorization factor (number of SIMD elements) times the
3245   // unroll factor (number of SIMD instructions).
3246   Constant *Step = ConstantInt::get(TC->getType(), VF * UF);
3247   Value *R = Builder.CreateURem(TC, Step, "n.mod.vf");
3248
3249   // If there is a non-reversed interleaved group that may speculatively access
3250   // memory out-of-bounds, we need to ensure that there will be at least one
3251   // iteration of the scalar epilogue loop. Thus, if the step evenly divides
3252   // the trip count, we set the remainder to be equal to the step. If the step
3253   // does not evenly divide the trip count, no adjustment is necessary since
3254   // there will already be scalar iterations. Note that the minimum iterations
3255   // check ensures that N >= Step.
3256   if (VF > 1 && Legal->requiresScalarEpilogue()) {
3257     auto *IsZero = Builder.CreateICmpEQ(R, ConstantInt::get(R->getType(), 0));
3258     R = Builder.CreateSelect(IsZero, Step, R);
3259   }
3260
3261   VectorTripCount = Builder.CreateSub(TC, R, "n.vec");
3262
3263   return VectorTripCount;
3264 }
3265
3266 void InnerLoopVectorizer::emitMinimumIterationCountCheck(Loop *L,
3267                                                          BasicBlock *Bypass) {
3268   Value *Count = getOrCreateTripCount(L);
3269   BasicBlock *BB = L->getLoopPreheader();
3270   IRBuilder<> Builder(BB->getTerminator());
3271
3272   // Generate code to check that the loop's trip count that we computed by
3273   // adding one to the backedge-taken count will not overflow.
3274   Value *CheckMinIters = Builder.CreateICmpULT(
3275       Count, ConstantInt::get(Count->getType(), VF * UF), "min.iters.check");
3276
3277   BasicBlock *NewBB =
3278       BB->splitBasicBlock(BB->getTerminator(), "min.iters.checked");
3279   // Update dominator tree immediately if the generated block is a
3280   // LoopBypassBlock because SCEV expansions to generate loop bypass
3281   // checks may query it before the current function is finished.
3282   DT->addNewBlock(NewBB, BB);
3283   if (L->getParentLoop())
3284     L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
3285   ReplaceInstWithInst(BB->getTerminator(),
3286                       BranchInst::Create(Bypass, NewBB, CheckMinIters));
3287   LoopBypassBlocks.push_back(BB);
3288 }
3289
3290 void InnerLoopVectorizer::emitVectorLoopEnteredCheck(Loop *L,
3291                                                      BasicBlock *Bypass) {
3292   Value *TC = getOrCreateVectorTripCount(L);
3293   BasicBlock *BB = L->getLoopPreheader();
3294   IRBuilder<> Builder(BB->getTerminator());
3295
3296   // Now, compare the new count to zero. If it is zero skip the vector loop and
3297   // jump to the scalar loop.
3298   Value *Cmp = Builder.CreateICmpEQ(TC, Constant::getNullValue(TC->getType()),
3299                                     "cmp.zero");
3300
3301   // Generate code to check that the loop's trip count that we computed by
3302   // adding one to the backedge-taken count will not overflow.
3303   BasicBlock *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph");
3304   // Update dominator tree immediately if the generated block is a
3305   // LoopBypassBlock because SCEV expansions to generate loop bypass
3306   // checks may query it before the current function is finished.
3307   DT->addNewBlock(NewBB, BB);
3308   if (L->getParentLoop())
3309     L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
3310   ReplaceInstWithInst(BB->getTerminator(),
3311                       BranchInst::Create(Bypass, NewBB, Cmp));
3312   LoopBypassBlocks.push_back(BB);
3313 }
3314
3315 void InnerLoopVectorizer::emitSCEVChecks(Loop *L, BasicBlock *Bypass) {
3316   BasicBlock *BB = L->getLoopPreheader();
3317
3318   // Generate the code to check that the SCEV assumptions that we made.
3319   // We want the new basic block to start at the first instruction in a
3320   // sequence of instructions that form a check.
3321   SCEVExpander Exp(*PSE.getSE(), Bypass->getModule()->getDataLayout(),
3322                    "scev.check");
3323   Value *SCEVCheck =
3324       Exp.expandCodeForPredicate(&PSE.getUnionPredicate(), BB->getTerminator());
3325
3326   if (auto *C = dyn_cast<ConstantInt>(SCEVCheck))
3327     if (C->isZero())
3328       return;
3329
3330   // Create a new block containing the stride check.
3331   BB->setName("vector.scevcheck");
3332   auto *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph");
3333   // Update dominator tree immediately if the generated block is a
3334   // LoopBypassBlock because SCEV expansions to generate loop bypass
3335   // checks may query it before the current function is finished.
3336   DT->addNewBlock(NewBB, BB);
3337   if (L->getParentLoop())
3338     L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
3339   ReplaceInstWithInst(BB->getTerminator(),
3340                       BranchInst::Create(Bypass, NewBB, SCEVCheck));
3341   LoopBypassBlocks.push_back(BB);
3342   AddedSafetyChecks = true;
3343 }
3344
3345 void InnerLoopVectorizer::emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass) {
3346   BasicBlock *BB = L->getLoopPreheader();
3347
3348   // Generate the code that checks in runtime if arrays overlap. We put the
3349   // checks into a separate block to make the more common case of few elements
3350   // faster.
3351   Instruction *FirstCheckInst;
3352   Instruction *MemRuntimeCheck;
3353   std::tie(FirstCheckInst, MemRuntimeCheck) =
3354       Legal->getLAI()->addRuntimeChecks(BB->getTerminator());
3355   if (!MemRuntimeCheck)
3356     return;
3357
3358   // Create a new block containing the memory check.
3359   BB->setName("vector.memcheck");
3360   auto *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph");
3361   // Update dominator tree immediately if the generated block is a
3362   // LoopBypassBlock because SCEV expansions to generate loop bypass
3363   // checks may query it before the current function is finished.
3364   DT->addNewBlock(NewBB, BB);
3365   if (L->getParentLoop())
3366     L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
3367   ReplaceInstWithInst(BB->getTerminator(),
3368                       BranchInst::Create(Bypass, NewBB, MemRuntimeCheck));
3369   LoopBypassBlocks.push_back(BB);
3370   AddedSafetyChecks = true;
3371
3372   // We currently don't use LoopVersioning for the actual loop cloning but we
3373   // still use it to add the noalias metadata.
3374   LVer = llvm::make_unique<LoopVersioning>(*Legal->getLAI(), OrigLoop, LI, DT,
3375                                            PSE.getSE());
3376   LVer->prepareNoAliasMetadata();
3377 }
3378
3379 void InnerLoopVectorizer::createVectorizedLoopSkeleton() {
3380   /*
3381    In this function we generate a new loop. The new loop will contain
3382    the vectorized instructions while the old loop will continue to run the
3383    scalar remainder.
3384
3385        [ ] <-- loop iteration number check.
3386     /   |
3387    /    v
3388   |    [ ] <-- vector loop bypass (may consist of multiple blocks).
3389   |  /  |
3390   | /   v
3391   ||   [ ]     <-- vector pre header.
3392   |/    |
3393   |     v
3394   |    [  ] \
3395   |    [  ]_|   <-- vector loop.
3396   |     |
3397   |     v
3398   |   -[ ]   <--- middle-block.
3399   |  /  |
3400   | /   v
3401   -|- >[ ]     <--- new preheader.
3402    |    |
3403    |    v
3404    |   [ ] \
3405    |   [ ]_|   <-- old scalar loop to handle remainder.
3406     \   |
3407      \  v
3408       >[ ]     <-- exit block.
3409    ...
3410    */
3411
3412   BasicBlock *OldBasicBlock = OrigLoop->getHeader();
3413   BasicBlock *VectorPH = OrigLoop->getLoopPreheader();
3414   BasicBlock *ExitBlock = OrigLoop->getExitBlock();
3415   assert(VectorPH && "Invalid loop structure");
3416   assert(ExitBlock && "Must have an exit block");
3417
3418   // Some loops have a single integer induction variable, while other loops
3419   // don't. One example is c++ iterators that often have multiple pointer
3420   // induction variables. In the code below we also support a case where we
3421   // don't have a single induction variable.
3422   //
3423   // We try to obtain an induction variable from the original loop as hard
3424   // as possible. However if we don't find one that:
3425   //   - is an integer
3426   //   - counts from zero, stepping by one
3427   //   - is the size of the widest induction variable type
3428   // then we create a new one.
3429   OldInduction = Legal->getPrimaryInduction();
3430   Type *IdxTy = Legal->getWidestInductionType();
3431
3432   // Split the single block loop into the two loop structure described above.
3433   BasicBlock *VecBody =
3434       VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
3435   BasicBlock *MiddleBlock =
3436       VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
3437   BasicBlock *ScalarPH =
3438       MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
3439
3440   // Create and register the new vector loop.
3441   Loop *Lp = new Loop();
3442   Loop *ParentLoop = OrigLoop->getParentLoop();
3443
3444   // Insert the new loop into the loop nest and register the new basic blocks
3445   // before calling any utilities such as SCEV that require valid LoopInfo.
3446   if (ParentLoop) {
3447     ParentLoop->addChildLoop(Lp);
3448     ParentLoop->addBasicBlockToLoop(ScalarPH, *LI);
3449     ParentLoop->addBasicBlockToLoop(MiddleBlock, *LI);
3450   } else {
3451     LI->addTopLevelLoop(Lp);
3452   }
3453   Lp->addBasicBlockToLoop(VecBody, *LI);
3454
3455   // Find the loop boundaries.
3456   Value *Count = getOrCreateTripCount(Lp);
3457
3458   Value *StartIdx = ConstantInt::get(IdxTy, 0);
3459
3460   // We need to test whether the backedge-taken count is uint##_max. Adding one
3461   // to it will cause overflow and an incorrect loop trip count in the vector
3462   // body. In case of overflow we want to directly jump to the scalar remainder
3463   // loop.
3464   emitMinimumIterationCountCheck(Lp, ScalarPH);
3465   // Now, compare the new count to zero. If it is zero skip the vector loop and
3466   // jump to the scalar loop.
3467   emitVectorLoopEnteredCheck(Lp, ScalarPH);
3468   // Generate the code to check any assumptions that we've made for SCEV
3469   // expressions.
3470   emitSCEVChecks(Lp, ScalarPH);
3471
3472   // Generate the code that checks in runtime if arrays overlap. We put the
3473   // checks into a separate block to make the more common case of few elements
3474   // faster.
3475   emitMemRuntimeChecks(Lp, ScalarPH);
3476
3477   // Generate the induction variable.
3478   // The loop step is equal to the vectorization factor (num of SIMD elements)
3479   // times the unroll factor (num of SIMD instructions).
3480   Value *CountRoundDown = getOrCreateVectorTripCount(Lp);
3481   Constant *Step = ConstantInt::get(IdxTy, VF * UF);
3482   Induction =
3483       createInductionVariable(Lp, StartIdx, CountRoundDown, Step,
3484                               getDebugLocFromInstOrOperands(OldInduction));
3485
3486   // We are going to resume the execution of the scalar loop.
3487   // Go over all of the induction variables that we found and fix the
3488   // PHIs that are left in the scalar version of the loop.
3489   // The starting values of PHI nodes depend on the counter of the last
3490   // iteration in the vectorized loop.
3491   // If we come from a bypass edge then we need to start from the original
3492   // start value.
3493
3494   // This variable saves the new starting index for the scalar loop. It is used
3495   // to test if there are any tail iterations left once the vector loop has
3496   // completed.
3497   LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
3498   for (auto &InductionEntry : *List) {
3499     PHINode *OrigPhi = InductionEntry.first;
3500     InductionDescriptor II = InductionEntry.second;
3501
3502     // Create phi nodes to merge from the  backedge-taken check block.
3503     PHINode *BCResumeVal = PHINode::Create(
3504         OrigPhi->getType(), 3, "bc.resume.val", ScalarPH->getTerminator());
3505     Value *&EndValue = IVEndValues[OrigPhi];
3506     if (OrigPhi == OldInduction) {
3507       // We know what the end value is.
3508       EndValue = CountRoundDown;
3509     } else {
3510       IRBuilder<> B(LoopBypassBlocks.back()->getTerminator());
3511       Type *StepType = II.getStep()->getType();
3512       Instruction::CastOps CastOp =
3513         CastInst::getCastOpcode(CountRoundDown, true, StepType, true);
3514       Value *CRD = B.CreateCast(CastOp, CountRoundDown, StepType, "cast.crd");
3515       const DataLayout &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
3516       EndValue = II.transform(B, CRD, PSE.getSE(), DL);
3517       EndValue->setName("ind.end");
3518     }
3519
3520     // The new PHI merges the original incoming value, in case of a bypass,
3521     // or the value at the end of the vectorized loop.
3522     BCResumeVal->addIncoming(EndValue, MiddleBlock);
3523
3524     // Fix the scalar body counter (PHI node).
3525     unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
3526
3527     // The old induction's phi node in the scalar body needs the truncated
3528     // value.
3529     for (BasicBlock *BB : LoopBypassBlocks)
3530       BCResumeVal->addIncoming(II.getStartValue(), BB);
3531     OrigPhi->setIncomingValue(BlockIdx, BCResumeVal);
3532   }
3533
3534   // Add a check in the middle block to see if we have completed
3535   // all of the iterations in the first vector loop.
3536   // If (N - N%VF) == N, then we *don't* need to run the remainder.
3537   Value *CmpN =
3538       CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, Count,
3539                       CountRoundDown, "cmp.n", MiddleBlock->getTerminator());
3540   ReplaceInstWithInst(MiddleBlock->getTerminator(),
3541                       BranchInst::Create(ExitBlock, ScalarPH, CmpN));
3542
3543   // Get ready to start creating new instructions into the vectorized body.
3544   Builder.SetInsertPoint(&*VecBody->getFirstInsertionPt());
3545
3546   // Save the state.
3547   LoopVectorPreHeader = Lp->getLoopPreheader();
3548   LoopScalarPreHeader = ScalarPH;
3549   LoopMiddleBlock = MiddleBlock;
3550   LoopExitBlock = ExitBlock;
3551   LoopVectorBody = VecBody;
3552   LoopScalarBody = OldBasicBlock;
3553
3554   // Keep all loop hints from the original loop on the vector loop (we'll
3555   // replace the vectorizer-specific hints below).
3556   if (MDNode *LID = OrigLoop->getLoopID())
3557     Lp->setLoopID(LID);
3558
3559   LoopVectorizeHints Hints(Lp, true, *ORE);
3560   Hints.setAlreadyVectorized();
3561 }
3562
3563 // Fix up external users of the induction variable. At this point, we are
3564 // in LCSSA form, with all external PHIs that use the IV having one input value,
3565 // coming from the remainder loop. We need those PHIs to also have a correct
3566 // value for the IV when arriving directly from the middle block.
3567 void InnerLoopVectorizer::fixupIVUsers(PHINode *OrigPhi,
3568                                        const InductionDescriptor &II,
3569                                        Value *CountRoundDown, Value *EndValue,
3570                                        BasicBlock *MiddleBlock) {
3571   // There are two kinds of external IV usages - those that use the value
3572   // computed in the last iteration (the PHI) and those that use the penultimate
3573   // value (the value that feeds into the phi from the loop latch).
3574   // We allow both, but they, obviously, have different values.
3575
3576   assert(OrigLoop->getExitBlock() && "Expected a single exit block");
3577
3578   DenseMap<Value *, Value *> MissingVals;
3579
3580   // An external user of the last iteration's value should see the value that
3581   // the remainder loop uses to initialize its own IV.
3582   Value *PostInc = OrigPhi->getIncomingValueForBlock(OrigLoop->getLoopLatch());
3583   for (User *U : PostInc->users()) {
3584     Instruction *UI = cast<Instruction>(U);
3585     if (!OrigLoop->contains(UI)) {
3586       assert(isa<PHINode>(UI) && "Expected LCSSA form");
3587       MissingVals[UI] = EndValue;
3588     }
3589   }
3590
3591   // An external user of the penultimate value need to see EndValue - Step.
3592   // The simplest way to get this is to recompute it from the constituent SCEVs,
3593   // that is Start + (Step * (CRD - 1)).
3594   for (User *U : OrigPhi->users()) {
3595     auto *UI = cast<Instruction>(U);
3596     if (!OrigLoop->contains(UI)) {
3597       const DataLayout &DL =
3598           OrigLoop->getHeader()->getModule()->getDataLayout();
3599       assert(isa<PHINode>(UI) && "Expected LCSSA form");
3600
3601       IRBuilder<> B(MiddleBlock->getTerminator());
3602       Value *CountMinusOne = B.CreateSub(
3603           CountRoundDown, ConstantInt::get(CountRoundDown->getType(), 1));
3604       Value *CMO =
3605           !II.getStep()->getType()->isIntegerTy()
3606               ? B.CreateCast(Instruction::SIToFP, CountMinusOne,
3607                              II.getStep()->getType())
3608               : B.CreateSExtOrTrunc(CountMinusOne, II.getStep()->getType());
3609       CMO->setName("cast.cmo");
3610       Value *Escape = II.transform(B, CMO, PSE.getSE(), DL);
3611       Escape->setName("ind.escape");
3612       MissingVals[UI] = Escape;
3613     }
3614   }
3615
3616   for (auto &I : MissingVals) {
3617     PHINode *PHI = cast<PHINode>(I.first);
3618     // One corner case we have to handle is two IVs "chasing" each-other,
3619     // that is %IV2 = phi [...], [ %IV1, %latch ]
3620     // In this case, if IV1 has an external use, we need to avoid adding both
3621     // "last value of IV1" and "penultimate value of IV2". So, verify that we
3622     // don't already have an incoming value for the middle block.
3623     if (PHI->getBasicBlockIndex(MiddleBlock) == -1)
3624       PHI->addIncoming(I.second, MiddleBlock);
3625   }
3626 }
3627
3628 namespace {
3629 struct CSEDenseMapInfo {
3630   static bool canHandle(const Instruction *I) {
3631     return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
3632            isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
3633   }
3634   static inline Instruction *getEmptyKey() {
3635     return DenseMapInfo<Instruction *>::getEmptyKey();
3636   }
3637   static inline Instruction *getTombstoneKey() {
3638     return DenseMapInfo<Instruction *>::getTombstoneKey();
3639   }
3640   static unsigned getHashValue(const Instruction *I) {
3641     assert(canHandle(I) && "Unknown instruction!");
3642     return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
3643                                                            I->value_op_end()));
3644   }
3645   static bool isEqual(const Instruction *LHS, const Instruction *RHS) {
3646     if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
3647         LHS == getTombstoneKey() || RHS == getTombstoneKey())
3648       return LHS == RHS;
3649     return LHS->isIdenticalTo(RHS);
3650   }
3651 };
3652 }
3653
3654 ///\brief Perform cse of induction variable instructions.
3655 static void cse(BasicBlock *BB) {
3656   // Perform simple cse.
3657   SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
3658   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
3659     Instruction *In = &*I++;
3660
3661     if (!CSEDenseMapInfo::canHandle(In))
3662       continue;
3663
3664     // Check if we can replace this instruction with any of the
3665     // visited instructions.
3666     if (Instruction *V = CSEMap.lookup(In)) {
3667       In->replaceAllUsesWith(V);
3668       In->eraseFromParent();
3669       continue;
3670     }
3671
3672     CSEMap[In] = In;
3673   }
3674 }
3675
3676 /// \brief Estimate the overhead of scalarizing an instruction. This is a
3677 /// convenience wrapper for the type-based getScalarizationOverhead API.
3678 static unsigned getScalarizationOverhead(Instruction *I, unsigned VF,
3679                                          const TargetTransformInfo &TTI) {
3680   if (VF == 1)
3681     return 0;
3682
3683   unsigned Cost = 0;
3684   Type *RetTy = ToVectorTy(I->getType(), VF);
3685   if (!RetTy->isVoidTy() &&
3686       (!isa<LoadInst>(I) ||
3687        !TTI.supportsEfficientVectorElementLoadStore()))
3688     Cost += TTI.getScalarizationOverhead(RetTy, true, false);
3689
3690   if (CallInst *CI = dyn_cast<CallInst>(I)) {
3691     SmallVector<const Value *, 4> Operands(CI->arg_operands());
3692     Cost += TTI.getOperandsScalarizationOverhead(Operands, VF);
3693   }
3694   else if (!isa<StoreInst>(I) ||
3695            !TTI.supportsEfficientVectorElementLoadStore()) {
3696     SmallVector<const Value *, 4> Operands(I->operand_values());
3697     Cost += TTI.getOperandsScalarizationOverhead(Operands, VF);
3698   }
3699
3700   return Cost;
3701 }
3702
3703 // Estimate cost of a call instruction CI if it were vectorized with factor VF.
3704 // Return the cost of the instruction, including scalarization overhead if it's
3705 // needed. The flag NeedToScalarize shows if the call needs to be scalarized -
3706 // i.e. either vector version isn't available, or is too expensive.
3707 static unsigned getVectorCallCost(CallInst *CI, unsigned VF,
3708                                   const TargetTransformInfo &TTI,
3709                                   const TargetLibraryInfo *TLI,
3710                                   bool &NeedToScalarize) {
3711   Function *F = CI->getCalledFunction();
3712   StringRef FnName = CI->getCalledFunction()->getName();
3713   Type *ScalarRetTy = CI->getType();
3714   SmallVector<Type *, 4> Tys, ScalarTys;
3715   for (auto &ArgOp : CI->arg_operands())
3716     ScalarTys.push_back(ArgOp->getType());
3717
3718   // Estimate cost of scalarized vector call. The source operands are assumed
3719   // to be vectors, so we need to extract individual elements from there,
3720   // execute VF scalar calls, and then gather the result into the vector return
3721   // value.
3722   unsigned ScalarCallCost = TTI.getCallInstrCost(F, ScalarRetTy, ScalarTys);
3723   if (VF == 1)
3724     return ScalarCallCost;
3725
3726   // Compute corresponding vector type for return value and arguments.
3727   Type *RetTy = ToVectorTy(ScalarRetTy, VF);
3728   for (Type *ScalarTy : ScalarTys)
3729     Tys.push_back(ToVectorTy(ScalarTy, VF));
3730
3731   // Compute costs of unpacking argument values for the scalar calls and
3732   // packing the return values to a vector.
3733   unsigned ScalarizationCost = getScalarizationOverhead(CI, VF, TTI);
3734
3735   unsigned Cost = ScalarCallCost * VF + ScalarizationCost;
3736
3737   // If we can't emit a vector call for this function, then the currently found
3738   // cost is the cost we need to return.
3739   NeedToScalarize = true;
3740   if (!TLI || !TLI->isFunctionVectorizable(FnName, VF) || CI->isNoBuiltin())
3741     return Cost;
3742
3743   // If the corresponding vector cost is cheaper, return its cost.
3744   unsigned VectorCallCost = TTI.getCallInstrCost(nullptr, RetTy, Tys);
3745   if (VectorCallCost < Cost) {
3746     NeedToScalarize = false;
3747     return VectorCallCost;
3748   }
3749   return Cost;
3750 }
3751
3752 // Estimate cost of an intrinsic call instruction CI if it were vectorized with
3753 // factor VF.  Return the cost of the instruction, including scalarization
3754 // overhead if it's needed.
3755 static unsigned getVectorIntrinsicCost(CallInst *CI, unsigned VF,
3756                                        const TargetTransformInfo &TTI,
3757                                        const TargetLibraryInfo *TLI) {
3758   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
3759   assert(ID && "Expected intrinsic call!");
3760
3761   FastMathFlags FMF;
3762   if (auto *FPMO = dyn_cast<FPMathOperator>(CI))
3763     FMF = FPMO->getFastMathFlags();
3764
3765   SmallVector<Value *, 4> Operands(CI->arg_operands());
3766   return TTI.getIntrinsicInstrCost(ID, CI->getType(), Operands, FMF, VF);
3767 }
3768
3769 static Type *smallestIntegerVectorType(Type *T1, Type *T2) {
3770   auto *I1 = cast<IntegerType>(T1->getVectorElementType());
3771   auto *I2 = cast<IntegerType>(T2->getVectorElementType());
3772   return I1->getBitWidth() < I2->getBitWidth() ? T1 : T2;
3773 }
3774 static Type *largestIntegerVectorType(Type *T1, Type *T2) {
3775   auto *I1 = cast<IntegerType>(T1->getVectorElementType());
3776   auto *I2 = cast<IntegerType>(T2->getVectorElementType());
3777   return I1->getBitWidth() > I2->getBitWidth() ? T1 : T2;
3778 }
3779
3780 void InnerLoopVectorizer::truncateToMinimalBitwidths() {
3781   // For every instruction `I` in MinBWs, truncate the operands, create a
3782   // truncated version of `I` and reextend its result. InstCombine runs
3783   // later and will remove any ext/trunc pairs.
3784   //
3785   SmallPtrSet<Value *, 4> Erased;
3786   for (const auto &KV : Cost->getMinimalBitwidths()) {
3787     // If the value wasn't vectorized, we must maintain the original scalar
3788     // type. The absence of the value from VectorLoopValueMap indicates that it
3789     // wasn't vectorized.
3790     if (!VectorLoopValueMap.hasVector(KV.first))
3791       continue;
3792     VectorParts &Parts = VectorLoopValueMap.getVector(KV.first);
3793     for (Value *&I : Parts) {
3794       if (Erased.count(I) || I->use_empty() || !isa<Instruction>(I))
3795         continue;
3796       Type *OriginalTy = I->getType();
3797       Type *ScalarTruncatedTy =
3798           IntegerType::get(OriginalTy->getContext(), KV.second);
3799       Type *TruncatedTy = VectorType::get(ScalarTruncatedTy,
3800                                           OriginalTy->getVectorNumElements());
3801       if (TruncatedTy == OriginalTy)
3802         continue;
3803
3804       IRBuilder<> B(cast<Instruction>(I));
3805       auto ShrinkOperand = [&](Value *V) -> Value * {
3806         if (auto *ZI = dyn_cast<ZExtInst>(V))
3807           if (ZI->getSrcTy() == TruncatedTy)
3808             return ZI->getOperand(0);
3809         return B.CreateZExtOrTrunc(V, TruncatedTy);
3810       };
3811
3812       // The actual instruction modification depends on the instruction type,
3813       // unfortunately.
3814       Value *NewI = nullptr;
3815       if (auto *BO = dyn_cast<BinaryOperator>(I)) {
3816         NewI = B.CreateBinOp(BO->getOpcode(), ShrinkOperand(BO->getOperand(0)),
3817                              ShrinkOperand(BO->getOperand(1)));
3818         cast<BinaryOperator>(NewI)->copyIRFlags(I);
3819       } else if (auto *CI = dyn_cast<ICmpInst>(I)) {
3820         NewI =
3821             B.CreateICmp(CI->getPredicate(), ShrinkOperand(CI->getOperand(0)),
3822                          ShrinkOperand(CI->getOperand(1)));
3823       } else if (auto *SI = dyn_cast<SelectInst>(I)) {
3824         NewI = B.CreateSelect(SI->getCondition(),
3825                               ShrinkOperand(SI->getTrueValue()),
3826                               ShrinkOperand(SI->getFalseValue()));
3827       } else if (auto *CI = dyn_cast<CastInst>(I)) {
3828         switch (CI->getOpcode()) {
3829         default:
3830           llvm_unreachable("Unhandled cast!");
3831         case Instruction::Trunc:
3832           NewI = ShrinkOperand(CI->getOperand(0));
3833           break;
3834         case Instruction::SExt:
3835           NewI = B.CreateSExtOrTrunc(
3836               CI->getOperand(0),
3837               smallestIntegerVectorType(OriginalTy, TruncatedTy));
3838           break;
3839         case Instruction::ZExt:
3840           NewI = B.CreateZExtOrTrunc(
3841               CI->getOperand(0),
3842               smallestIntegerVectorType(OriginalTy, TruncatedTy));
3843           break;
3844         }
3845       } else if (auto *SI = dyn_cast<ShuffleVectorInst>(I)) {
3846         auto Elements0 = SI->getOperand(0)->getType()->getVectorNumElements();
3847         auto *O0 = B.CreateZExtOrTrunc(
3848             SI->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements0));
3849         auto Elements1 = SI->getOperand(1)->getType()->getVectorNumElements();
3850         auto *O1 = B.CreateZExtOrTrunc(
3851             SI->getOperand(1), VectorType::get(ScalarTruncatedTy, Elements1));
3852
3853         NewI = B.CreateShuffleVector(O0, O1, SI->getMask());
3854       } else if (isa<LoadInst>(I)) {
3855         // Don't do anything with the operands, just extend the result.
3856         continue;
3857       } else if (auto *IE = dyn_cast<InsertElementInst>(I)) {
3858         auto Elements = IE->getOperand(0)->getType()->getVectorNumElements();
3859         auto *O0 = B.CreateZExtOrTrunc(
3860             IE->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements));
3861         auto *O1 = B.CreateZExtOrTrunc(IE->getOperand(1), ScalarTruncatedTy);
3862         NewI = B.CreateInsertElement(O0, O1, IE->getOperand(2));
3863       } else if (auto *EE = dyn_cast<ExtractElementInst>(I)) {
3864         auto Elements = EE->getOperand(0)->getType()->getVectorNumElements();
3865         auto *O0 = B.CreateZExtOrTrunc(
3866             EE->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements));
3867         NewI = B.CreateExtractElement(O0, EE->getOperand(2));
3868       } else {
3869         llvm_unreachable("Unhandled instruction type!");
3870       }
3871
3872       // Lastly, extend the result.
3873       NewI->takeName(cast<Instruction>(I));
3874       Value *Res = B.CreateZExtOrTrunc(NewI, OriginalTy);
3875       I->replaceAllUsesWith(Res);
3876       cast<Instruction>(I)->eraseFromParent();
3877       Erased.insert(I);
3878       I = Res;
3879     }
3880   }
3881
3882   // We'll have created a bunch of ZExts that are now parentless. Clean up.
3883   for (const auto &KV : Cost->getMinimalBitwidths()) {
3884     // If the value wasn't vectorized, we must maintain the original scalar
3885     // type. The absence of the value from VectorLoopValueMap indicates that it
3886     // wasn't vectorized.
3887     if (!VectorLoopValueMap.hasVector(KV.first))
3888       continue;
3889     VectorParts &Parts = VectorLoopValueMap.getVector(KV.first);
3890     for (Value *&I : Parts) {
3891       ZExtInst *Inst = dyn_cast<ZExtInst>(I);
3892       if (Inst && Inst->use_empty()) {
3893         Value *NewI = Inst->getOperand(0);
3894         Inst->eraseFromParent();
3895         I = NewI;
3896       }
3897     }
3898   }
3899 }
3900
3901 void InnerLoopVectorizer::fixVectorizedLoop() {
3902   // Insert truncates and extends for any truncated instructions as hints to
3903   // InstCombine.
3904   if (VF > 1)
3905     truncateToMinimalBitwidths();
3906
3907   // At this point every instruction in the original loop is widened to a
3908   // vector form. Now we need to fix the recurrences in the loop. These PHI
3909   // nodes are currently empty because we did not want to introduce cycles.
3910   // This is the second stage of vectorizing recurrences.
3911   fixCrossIterationPHIs();
3912
3913   // Update the dominator tree.
3914   //
3915   // FIXME: After creating the structure of the new loop, the dominator tree is
3916   //        no longer up-to-date, and it remains that way until we update it
3917   //        here. An out-of-date dominator tree is problematic for SCEV,
3918   //        because SCEVExpander uses it to guide code generation. The
3919   //        vectorizer use SCEVExpanders in several places. Instead, we should
3920   //        keep the dominator tree up-to-date as we go.
3921   updateAnalysis();
3922
3923   // Fix-up external users of the induction variables.
3924   for (auto &Entry : *Legal->getInductionVars())
3925     fixupIVUsers(Entry.first, Entry.second,
3926                  getOrCreateVectorTripCount(LI->getLoopFor(LoopVectorBody)),
3927                  IVEndValues[Entry.first], LoopMiddleBlock);
3928
3929   fixLCSSAPHIs();
3930   predicateInstructions();
3931
3932   // Remove redundant induction instructions.
3933   cse(LoopVectorBody);
3934 }
3935
3936 void InnerLoopVectorizer::fixCrossIterationPHIs() {
3937   // In order to support recurrences we need to be able to vectorize Phi nodes.
3938   // Phi nodes have cycles, so we need to vectorize them in two stages. This is
3939   // stage #2: We now need to fix the recurrences by adding incoming edges to
3940   // the currently empty PHI nodes. At this point every instruction in the
3941   // original loop is widened to a vector form so we can use them to construct
3942   // the incoming edges.
3943   for (Instruction &I : *OrigLoop->getHeader()) {
3944     PHINode *Phi = dyn_cast<PHINode>(&I);
3945     if (!Phi)
3946       break;
3947     // Handle first-order recurrences and reductions that need to be fixed.
3948     if (Legal->isFirstOrderRecurrence(Phi))
3949       fixFirstOrderRecurrence(Phi);
3950     else if (Legal->isReductionVariable(Phi))
3951       fixReduction(Phi);
3952   }
3953 }
3954
3955 void InnerLoopVectorizer::fixFirstOrderRecurrence(PHINode *Phi) {
3956
3957   // This is the second phase of vectorizing first-order recurrences. An
3958   // overview of the transformation is described below. Suppose we have the
3959   // following loop.
3960   //
3961   //   for (int i = 0; i < n; ++i)
3962   //     b[i] = a[i] - a[i - 1];
3963   //
3964   // There is a first-order recurrence on "a". For this loop, the shorthand
3965   // scalar IR looks like:
3966   //
3967   //   scalar.ph:
3968   //     s_init = a[-1]
3969   //     br scalar.body
3970   //
3971   //   scalar.body:
3972   //     i = phi [0, scalar.ph], [i+1, scalar.body]
3973   //     s1 = phi [s_init, scalar.ph], [s2, scalar.body]
3974   //     s2 = a[i]
3975   //     b[i] = s2 - s1
3976   //     br cond, scalar.body, ...
3977   //
3978   // In this example, s1 is a recurrence because it's value depends on the
3979   // previous iteration. In the first phase of vectorization, we created a
3980   // temporary value for s1. We now complete the vectorization and produce the
3981   // shorthand vector IR shown below (for VF = 4, UF = 1).
3982   //
3983   //   vector.ph:
3984   //     v_init = vector(..., ..., ..., a[-1])
3985   //     br vector.body
3986   //
3987   //   vector.body
3988   //     i = phi [0, vector.ph], [i+4, vector.body]
3989   //     v1 = phi [v_init, vector.ph], [v2, vector.body]
3990   //     v2 = a[i, i+1, i+2, i+3];
3991   //     v3 = vector(v1(3), v2(0, 1, 2))
3992   //     b[i, i+1, i+2, i+3] = v2 - v3
3993   //     br cond, vector.body, middle.block
3994   //
3995   //   middle.block:
3996   //     x = v2(3)
3997   //     br scalar.ph
3998   //
3999   //   scalar.ph:
4000   //     s_init = phi [x, middle.block], [a[-1], otherwise]
4001   //     br scalar.body
4002   //
4003   // After execution completes the vector loop, we extract the next value of
4004   // the recurrence (x) to use as the initial value in the scalar loop.
4005
4006   // Get the original loop preheader and single loop latch.
4007   auto *Preheader = OrigLoop->getLoopPreheader();
4008   auto *Latch = OrigLoop->getLoopLatch();
4009
4010   // Get the initial and previous values of the scalar recurrence.
4011   auto *ScalarInit = Phi->getIncomingValueForBlock(Preheader);
4012   auto *Previous = Phi->getIncomingValueForBlock(Latch);
4013
4014   // Create a vector from the initial value.
4015   auto *VectorInit = ScalarInit;
4016   if (VF > 1) {
4017     Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
4018     VectorInit = Builder.CreateInsertElement(
4019         UndefValue::get(VectorType::get(VectorInit->getType(), VF)), VectorInit,
4020         Builder.getInt32(VF - 1), "vector.recur.init");
4021   }
4022
4023   // We constructed a temporary phi node in the first phase of vectorization.
4024   // This phi node will eventually be deleted.
4025   VectorParts &PhiParts = VectorLoopValueMap.getVector(Phi);
4026   Builder.SetInsertPoint(cast<Instruction>(PhiParts[0]));
4027
4028   // Create a phi node for the new recurrence. The current value will either be
4029   // the initial value inserted into a vector or loop-varying vector value.
4030   auto *VecPhi = Builder.CreatePHI(VectorInit->getType(), 2, "vector.recur");
4031   VecPhi->addIncoming(VectorInit, LoopVectorPreHeader);
4032
4033   // Get the vectorized previous value.
4034   auto &PreviousParts = getVectorValue(Previous);
4035
4036   // Set the insertion point after the previous value if it is an instruction.
4037   // Note that the previous value may have been constant-folded so it is not
4038   // guaranteed to be an instruction in the vector loop. Also, if the previous
4039   // value is a phi node, we should insert after all the phi nodes to avoid
4040   // breaking basic block verification.
4041   if (LI->getLoopFor(LoopVectorBody)->isLoopInvariant(PreviousParts[UF - 1]) ||
4042       isa<PHINode>(PreviousParts[UF - 1]))
4043     Builder.SetInsertPoint(&*LoopVectorBody->getFirstInsertionPt());
4044   else
4045     Builder.SetInsertPoint(
4046         &*++BasicBlock::iterator(cast<Instruction>(PreviousParts[UF - 1])));
4047
4048   // We will construct a vector for the recurrence by combining the values for
4049   // the current and previous iterations. This is the required shuffle mask.
4050   SmallVector<Constant *, 8> ShuffleMask(VF);
4051   ShuffleMask[0] = Builder.getInt32(VF - 1);
4052   for (unsigned I = 1; I < VF; ++I)
4053     ShuffleMask[I] = Builder.getInt32(I + VF - 1);
4054
4055   // The vector from which to take the initial value for the current iteration
4056   // (actual or unrolled). Initially, this is the vector phi node.
4057   Value *Incoming = VecPhi;
4058
4059   // Shuffle the current and previous vector and update the vector parts.
4060   for (unsigned Part = 0; Part < UF; ++Part) {
4061     auto *Shuffle =
4062         VF > 1
4063             ? Builder.CreateShuffleVector(Incoming, PreviousParts[Part],
4064                                           ConstantVector::get(ShuffleMask))
4065             : Incoming;
4066     PhiParts[Part]->replaceAllUsesWith(Shuffle);
4067     cast<Instruction>(PhiParts[Part])->eraseFromParent();
4068     PhiParts[Part] = Shuffle;
4069     Incoming = PreviousParts[Part];
4070   }
4071
4072   // Fix the latch value of the new recurrence in the vector loop.
4073   VecPhi->addIncoming(Incoming, LI->getLoopFor(LoopVectorBody)->getLoopLatch());
4074
4075   // Extract the last vector element in the middle block. This will be the
4076   // initial value for the recurrence when jumping to the scalar loop.
4077   auto *ExtractForScalar = Incoming;
4078   if (VF > 1) {
4079     Builder.SetInsertPoint(LoopMiddleBlock->getTerminator());
4080     ExtractForScalar = Builder.CreateExtractElement(
4081         ExtractForScalar, Builder.getInt32(VF - 1), "vector.recur.extract");
4082   }
4083   // Extract the second last element in the middle block if the
4084   // Phi is used outside the loop. We need to extract the phi itself
4085   // and not the last element (the phi update in the current iteration). This
4086   // will be the value when jumping to the exit block from the LoopMiddleBlock,
4087   // when the scalar loop is not run at all.
4088   Value *ExtractForPhiUsedOutsideLoop = nullptr;
4089   if (VF > 1)
4090     ExtractForPhiUsedOutsideLoop = Builder.CreateExtractElement(
4091         Incoming, Builder.getInt32(VF - 2), "vector.recur.extract.for.phi");
4092   // When loop is unrolled without vectorizing, initialize
4093   // ExtractForPhiUsedOutsideLoop with the value just prior to unrolled value of
4094   // `Incoming`. This is analogous to the vectorized case above: extracting the
4095   // second last element when VF > 1.
4096   else if (UF > 1)
4097     ExtractForPhiUsedOutsideLoop = PreviousParts[UF - 2];
4098
4099   // Fix the initial value of the original recurrence in the scalar loop.
4100   Builder.SetInsertPoint(&*LoopScalarPreHeader->begin());
4101   auto *Start = Builder.CreatePHI(Phi->getType(), 2, "scalar.recur.init");
4102   for (auto *BB : predecessors(LoopScalarPreHeader)) {
4103     auto *Incoming = BB == LoopMiddleBlock ? ExtractForScalar : ScalarInit;
4104     Start->addIncoming(Incoming, BB);
4105   }
4106
4107   Phi->setIncomingValue(Phi->getBasicBlockIndex(LoopScalarPreHeader), Start);
4108   Phi->setName("scalar.recur");
4109
4110   // Finally, fix users of the recurrence outside the loop. The users will need
4111   // either the last value of the scalar recurrence or the last value of the
4112   // vector recurrence we extracted in the middle block. Since the loop is in
4113   // LCSSA form, we just need to find the phi node for the original scalar
4114   // recurrence in the exit block, and then add an edge for the middle block.
4115   for (auto &I : *LoopExitBlock) {
4116     auto *LCSSAPhi = dyn_cast<PHINode>(&I);
4117     if (!LCSSAPhi)
4118       break;
4119     if (LCSSAPhi->getIncomingValue(0) == Phi) {
4120       LCSSAPhi->addIncoming(ExtractForPhiUsedOutsideLoop, LoopMiddleBlock);
4121       break;
4122     }
4123   }
4124 }
4125
4126 void InnerLoopVectorizer::fixReduction(PHINode *Phi) {
4127   Constant *Zero = Builder.getInt32(0);
4128
4129   // Get it's reduction variable descriptor.
4130   assert(Legal->isReductionVariable(Phi) &&
4131          "Unable to find the reduction variable");
4132   RecurrenceDescriptor RdxDesc = (*Legal->getReductionVars())[Phi];
4133
4134   RecurrenceDescriptor::RecurrenceKind RK = RdxDesc.getRecurrenceKind();
4135   TrackingVH<Value> ReductionStartValue = RdxDesc.getRecurrenceStartValue();
4136   Instruction *LoopExitInst = RdxDesc.getLoopExitInstr();
4137   RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind =
4138     RdxDesc.getMinMaxRecurrenceKind();
4139   setDebugLocFromInst(Builder, ReductionStartValue);
4140
4141   // We need to generate a reduction vector from the incoming scalar.
4142   // To do so, we need to generate the 'identity' vector and override
4143   // one of the elements with the incoming scalar reduction. We need
4144   // to do it in the vector-loop preheader.
4145   Builder.SetInsertPoint(LoopBypassBlocks[1]->getTerminator());
4146
4147   // This is the vector-clone of the value that leaves the loop.
4148   const VectorParts &VectorExit = getVectorValue(LoopExitInst);
4149   Type *VecTy = VectorExit[0]->getType();
4150
4151   // Find the reduction identity variable. Zero for addition, or, xor,
4152   // one for multiplication, -1 for And.
4153   Value *Identity;
4154   Value *VectorStart;
4155   if (RK == RecurrenceDescriptor::RK_IntegerMinMax ||
4156       RK == RecurrenceDescriptor::RK_FloatMinMax) {
4157     // MinMax reduction have the start value as their identify.
4158     if (VF == 1) {
4159       VectorStart = Identity = ReductionStartValue;
4160     } else {
4161       VectorStart = Identity =
4162         Builder.CreateVectorSplat(VF, ReductionStartValue, "minmax.ident");
4163     }
4164   } else {
4165     // Handle other reduction kinds:
4166     Constant *Iden = RecurrenceDescriptor::getRecurrenceIdentity(
4167         RK, VecTy->getScalarType());
4168     if (VF == 1) {
4169       Identity = Iden;
4170       // This vector is the Identity vector where the first element is the
4171       // incoming scalar reduction.
4172       VectorStart = ReductionStartValue;
4173     } else {
4174       Identity = ConstantVector::getSplat(VF, Iden);
4175
4176       // This vector is the Identity vector where the first element is the
4177       // incoming scalar reduction.
4178       VectorStart =
4179         Builder.CreateInsertElement(Identity, ReductionStartValue, Zero);
4180     }
4181   }
4182
4183   // Fix the vector-loop phi.
4184
4185   // Reductions do not have to start at zero. They can start with
4186   // any loop invariant values.
4187   const VectorParts &VecRdxPhi = getVectorValue(Phi);
4188   BasicBlock *Latch = OrigLoop->getLoopLatch();
4189   Value *LoopVal = Phi->getIncomingValueForBlock(Latch);
4190   const VectorParts &Val = getVectorValue(LoopVal);
4191   for (unsigned part = 0; part < UF; ++part) {
4192     // Make sure to add the reduction stat value only to the
4193     // first unroll part.
4194     Value *StartVal = (part == 0) ? VectorStart : Identity;
4195     cast<PHINode>(VecRdxPhi[part])
4196       ->addIncoming(StartVal, LoopVectorPreHeader);
4197     cast<PHINode>(VecRdxPhi[part])
4198       ->addIncoming(Val[part], LI->getLoopFor(LoopVectorBody)->getLoopLatch());
4199   }
4200
4201   // Before each round, move the insertion point right between
4202   // the PHIs and the values we are going to write.
4203   // This allows us to write both PHINodes and the extractelement
4204   // instructions.
4205   Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
4206
4207   VectorParts &RdxParts = VectorLoopValueMap.getVector(LoopExitInst);
4208   setDebugLocFromInst(Builder, LoopExitInst);
4209
4210   // If the vector reduction can be performed in a smaller type, we truncate
4211   // then extend the loop exit value to enable InstCombine to evaluate the
4212   // entire expression in the smaller type.
4213   if (VF > 1 && Phi->getType() != RdxDesc.getRecurrenceType()) {
4214     Type *RdxVecTy = VectorType::get(RdxDesc.getRecurrenceType(), VF);
4215     Builder.SetInsertPoint(LoopVectorBody->getTerminator());
4216     for (unsigned part = 0; part < UF; ++part) {
4217       Value *Trunc = Builder.CreateTrunc(RdxParts[part], RdxVecTy);
4218       Value *Extnd = RdxDesc.isSigned() ? Builder.CreateSExt(Trunc, VecTy)
4219         : Builder.CreateZExt(Trunc, VecTy);
4220       for (Value::user_iterator UI = RdxParts[part]->user_begin();
4221            UI != RdxParts[part]->user_end();)
4222         if (*UI != Trunc) {
4223           (*UI++)->replaceUsesOfWith(RdxParts[part], Extnd);
4224           RdxParts[part] = Extnd;
4225         } else {
4226           ++UI;
4227         }
4228     }
4229     Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
4230     for (unsigned part = 0; part < UF; ++part)
4231       RdxParts[part] = Builder.CreateTrunc(RdxParts[part], RdxVecTy);
4232   }
4233
4234   // Reduce all of the unrolled parts into a single vector.
4235   Value *ReducedPartRdx = RdxParts[0];
4236   unsigned Op = RecurrenceDescriptor::getRecurrenceBinOp(RK);
4237   setDebugLocFromInst(Builder, ReducedPartRdx);
4238   for (unsigned part = 1; part < UF; ++part) {
4239     if (Op != Instruction::ICmp && Op != Instruction::FCmp)
4240       // Floating point operations had to be 'fast' to enable the reduction.
4241       ReducedPartRdx = addFastMathFlag(
4242           Builder.CreateBinOp((Instruction::BinaryOps)Op, RdxParts[part],
4243                               ReducedPartRdx, "bin.rdx"));
4244     else
4245       ReducedPartRdx = RecurrenceDescriptor::createMinMaxOp(
4246           Builder, MinMaxKind, ReducedPartRdx, RdxParts[part]);
4247   }
4248
4249   if (VF > 1) {
4250     bool NoNaN = Legal->hasFunNoNaNAttr();
4251     ReducedPartRdx =
4252         createTargetReduction(Builder, TTI, RdxDesc, ReducedPartRdx, NoNaN);
4253     // If the reduction can be performed in a smaller type, we need to extend
4254     // the reduction to the wider type before we branch to the original loop.
4255     if (Phi->getType() != RdxDesc.getRecurrenceType())
4256       ReducedPartRdx =
4257         RdxDesc.isSigned()
4258         ? Builder.CreateSExt(ReducedPartRdx, Phi->getType())
4259         : Builder.CreateZExt(ReducedPartRdx, Phi->getType());
4260   }
4261
4262   // Create a phi node that merges control-flow from the backedge-taken check
4263   // block and the middle block.
4264   PHINode *BCBlockPhi = PHINode::Create(Phi->getType(), 2, "bc.merge.rdx",
4265                                         LoopScalarPreHeader->getTerminator());
4266   for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
4267     BCBlockPhi->addIncoming(ReductionStartValue, LoopBypassBlocks[I]);
4268   BCBlockPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
4269
4270   // Now, we need to fix the users of the reduction variable
4271   // inside and outside of the scalar remainder loop.
4272   // We know that the loop is in LCSSA form. We need to update the
4273   // PHI nodes in the exit blocks.
4274   for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
4275          LEE = LoopExitBlock->end();
4276        LEI != LEE; ++LEI) {
4277     PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
4278     if (!LCSSAPhi)
4279       break;
4280
4281     // All PHINodes need to have a single entry edge, or two if
4282     // we already fixed them.
4283     assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
4284
4285     // We found a reduction value exit-PHI. Update it with the
4286     // incoming bypass edge.
4287     if (LCSSAPhi->getIncomingValue(0) == LoopExitInst)
4288       LCSSAPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
4289   } // end of the LCSSA phi scan.
4290
4291     // Fix the scalar loop reduction variable with the incoming reduction sum
4292     // from the vector body and from the backedge value.
4293   int IncomingEdgeBlockIdx =
4294     Phi->getBasicBlockIndex(OrigLoop->getLoopLatch());
4295   assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
4296   // Pick the other block.
4297   int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
4298   Phi->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi);
4299   Phi->setIncomingValue(IncomingEdgeBlockIdx, LoopExitInst);
4300 }
4301
4302 void InnerLoopVectorizer::fixLCSSAPHIs() {
4303   for (Instruction &LEI : *LoopExitBlock) {
4304     auto *LCSSAPhi = dyn_cast<PHINode>(&LEI);
4305     if (!LCSSAPhi)
4306       break;
4307     if (LCSSAPhi->getNumIncomingValues() == 1) {
4308       assert(OrigLoop->isLoopInvariant(LCSSAPhi->getIncomingValue(0)) &&
4309              "Incoming value isn't loop invariant");
4310       LCSSAPhi->addIncoming(LCSSAPhi->getIncomingValue(0), LoopMiddleBlock);
4311     }
4312   }
4313 }
4314
4315 void InnerLoopVectorizer::sinkScalarOperands(Instruction *PredInst) {
4316
4317   // The basic block and loop containing the predicated instruction.
4318   auto *PredBB = PredInst->getParent();
4319   auto *VectorLoop = LI->getLoopFor(PredBB);
4320
4321   // Initialize a worklist with the operands of the predicated instruction.
4322   SetVector<Value *> Worklist(PredInst->op_begin(), PredInst->op_end());
4323
4324   // Holds instructions that we need to analyze again. An instruction may be
4325   // reanalyzed if we don't yet know if we can sink it or not.
4326   SmallVector<Instruction *, 8> InstsToReanalyze;
4327
4328   // Returns true if a given use occurs in the predicated block. Phi nodes use
4329   // their operands in their corresponding predecessor blocks.
4330   auto isBlockOfUsePredicated = [&](Use &U) -> bool {
4331     auto *I = cast<Instruction>(U.getUser());
4332     BasicBlock *BB = I->getParent();
4333     if (auto *Phi = dyn_cast<PHINode>(I))
4334       BB = Phi->getIncomingBlock(
4335           PHINode::getIncomingValueNumForOperand(U.getOperandNo()));
4336     return BB == PredBB;
4337   };
4338
4339   // Iteratively sink the scalarized operands of the predicated instruction
4340   // into the block we created for it. When an instruction is sunk, it's
4341   // operands are then added to the worklist. The algorithm ends after one pass
4342   // through the worklist doesn't sink a single instruction.
4343   bool Changed;
4344   do {
4345
4346     // Add the instructions that need to be reanalyzed to the worklist, and
4347     // reset the changed indicator.
4348     Worklist.insert(InstsToReanalyze.begin(), InstsToReanalyze.end());
4349     InstsToReanalyze.clear();
4350     Changed = false;
4351
4352     while (!Worklist.empty()) {
4353       auto *I = dyn_cast<Instruction>(Worklist.pop_back_val());
4354
4355       // We can't sink an instruction if it is a phi node, is already in the
4356       // predicated block, is not in the loop, or may have side effects.
4357       if (!I || isa<PHINode>(I) || I->getParent() == PredBB ||
4358           !VectorLoop->contains(I) || I->mayHaveSideEffects())
4359         continue;
4360
4361       // It's legal to sink the instruction if all its uses occur in the
4362       // predicated block. Otherwise, there's nothing to do yet, and we may
4363       // need to reanalyze the instruction.
4364       if (!all_of(I->uses(), isBlockOfUsePredicated)) {
4365         InstsToReanalyze.push_back(I);
4366         continue;
4367       }
4368
4369       // Move the instruction to the beginning of the predicated block, and add
4370       // it's operands to the worklist.
4371       I->moveBefore(&*PredBB->getFirstInsertionPt());
4372       Worklist.insert(I->op_begin(), I->op_end());
4373
4374       // The sinking may have enabled other instructions to be sunk, so we will
4375       // need to iterate.
4376       Changed = true;
4377     }
4378   } while (Changed);
4379 }
4380
4381 void InnerLoopVectorizer::predicateInstructions() {
4382
4383   // For each instruction I marked for predication on value C, split I into its
4384   // own basic block to form an if-then construct over C. Since I may be fed by
4385   // an extractelement instruction or other scalar operand, we try to
4386   // iteratively sink its scalar operands into the predicated block. If I feeds
4387   // an insertelement instruction, we try to move this instruction into the
4388   // predicated block as well. For non-void types, a phi node will be created
4389   // for the resulting value (either vector or scalar).
4390   //
4391   // So for some predicated instruction, e.g. the conditional sdiv in:
4392   //
4393   // for.body:
4394   //  ...
4395   //  %add = add nsw i32 %mul, %0
4396   //  %cmp5 = icmp sgt i32 %2, 7
4397   //  br i1 %cmp5, label %if.then, label %if.end
4398   //
4399   // if.then:
4400   //  %div = sdiv i32 %0, %1
4401   //  br label %if.end
4402   //
4403   // if.end:
4404   //  %x.0 = phi i32 [ %div, %if.then ], [ %add, %for.body ]
4405   //
4406   // the sdiv at this point is scalarized and if-converted using a select.
4407   // The inactive elements in the vector are not used, but the predicated
4408   // instruction is still executed for all vector elements, essentially:
4409   //
4410   // vector.body:
4411   //  ...
4412   //  %17 = add nsw <2 x i32> %16, %wide.load
4413   //  %29 = extractelement <2 x i32> %wide.load, i32 0
4414   //  %30 = extractelement <2 x i32> %wide.load51, i32 0
4415   //  %31 = sdiv i32 %29, %30
4416   //  %32 = insertelement <2 x i32> undef, i32 %31, i32 0
4417   //  %35 = extractelement <2 x i32> %wide.load, i32 1
4418   //  %36 = extractelement <2 x i32> %wide.load51, i32 1
4419   //  %37 = sdiv i32 %35, %36
4420   //  %38 = insertelement <2 x i32> %32, i32 %37, i32 1
4421   //  %predphi = select <2 x i1> %26, <2 x i32> %38, <2 x i32> %17
4422   //
4423   // Predication will now re-introduce the original control flow to avoid false
4424   // side-effects by the sdiv instructions on the inactive elements, yielding
4425   // (after cleanup):
4426   //
4427   // vector.body:
4428   //  ...
4429   //  %5 = add nsw <2 x i32> %4, %wide.load
4430   //  %8 = icmp sgt <2 x i32> %wide.load52, <i32 7, i32 7>
4431   //  %9 = extractelement <2 x i1> %8, i32 0
4432   //  br i1 %9, label %pred.sdiv.if, label %pred.sdiv.continue
4433   //
4434   // pred.sdiv.if:
4435   //  %10 = extractelement <2 x i32> %wide.load, i32 0
4436   //  %11 = extractelement <2 x i32> %wide.load51, i32 0
4437   //  %12 = sdiv i32 %10, %11
4438   //  %13 = insertelement <2 x i32> undef, i32 %12, i32 0
4439   //  br label %pred.sdiv.continue
4440   //
4441   // pred.sdiv.continue:
4442   //  %14 = phi <2 x i32> [ undef, %vector.body ], [ %13, %pred.sdiv.if ]
4443   //  %15 = extractelement <2 x i1> %8, i32 1
4444   //  br i1 %15, label %pred.sdiv.if54, label %pred.sdiv.continue55
4445   //
4446   // pred.sdiv.if54:
4447   //  %16 = extractelement <2 x i32> %wide.load, i32 1
4448   //  %17 = extractelement <2 x i32> %wide.load51, i32 1
4449   //  %18 = sdiv i32 %16, %17
4450   //  %19 = insertelement <2 x i32> %14, i32 %18, i32 1
4451   //  br label %pred.sdiv.continue55
4452   //
4453   // pred.sdiv.continue55:
4454   //  %20 = phi <2 x i32> [ %14, %pred.sdiv.continue ], [ %19, %pred.sdiv.if54 ]
4455   //  %predphi = select <2 x i1> %8, <2 x i32> %20, <2 x i32> %5
4456
4457   for (auto KV : PredicatedInstructions) {
4458     BasicBlock::iterator I(KV.first);
4459     BasicBlock *Head = I->getParent();
4460     auto *T = SplitBlockAndInsertIfThen(KV.second, &*I, /*Unreachable=*/false,
4461                                         /*BranchWeights=*/nullptr, DT, LI);
4462     I->moveBefore(T);
4463     sinkScalarOperands(&*I);
4464
4465     BasicBlock *PredicatedBlock = I->getParent();
4466     Twine BBNamePrefix = Twine("pred.") + I->getOpcodeName();
4467     PredicatedBlock->setName(BBNamePrefix + ".if");
4468     PredicatedBlock->getSingleSuccessor()->setName(BBNamePrefix + ".continue");
4469
4470     // If the instruction is non-void create a Phi node at reconvergence point.
4471     if (!I->getType()->isVoidTy()) {
4472       Value *IncomingTrue = nullptr;
4473       Value *IncomingFalse = nullptr;
4474
4475       if (I->hasOneUse() && isa<InsertElementInst>(*I->user_begin())) {
4476         // If the predicated instruction is feeding an insert-element, move it
4477         // into the Then block; Phi node will be created for the vector.
4478         InsertElementInst *IEI = cast<InsertElementInst>(*I->user_begin());
4479         IEI->moveBefore(T);
4480         IncomingTrue = IEI; // the new vector with the inserted element.
4481         IncomingFalse = IEI->getOperand(0); // the unmodified vector
4482       } else {
4483         // Phi node will be created for the scalar predicated instruction.
4484         IncomingTrue = &*I;
4485         IncomingFalse = UndefValue::get(I->getType());
4486       }
4487
4488       BasicBlock *PostDom = I->getParent()->getSingleSuccessor();
4489       assert(PostDom && "Then block has multiple successors");
4490       PHINode *Phi =
4491           PHINode::Create(IncomingTrue->getType(), 2, "", &PostDom->front());
4492       IncomingTrue->replaceAllUsesWith(Phi);
4493       Phi->addIncoming(IncomingFalse, Head);
4494       Phi->addIncoming(IncomingTrue, I->getParent());
4495     }
4496   }
4497
4498   DEBUG(DT->verifyDomTree());
4499 }
4500
4501 InnerLoopVectorizer::VectorParts
4502 InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
4503   assert(is_contained(predecessors(Dst), Src) && "Invalid edge");
4504
4505   // Look for cached value.
4506   std::pair<BasicBlock *, BasicBlock *> Edge(Src, Dst);
4507   EdgeMaskCacheTy::iterator ECEntryIt = EdgeMaskCache.find(Edge);
4508   if (ECEntryIt != EdgeMaskCache.end())
4509     return ECEntryIt->second;
4510
4511   VectorParts SrcMask = createBlockInMask(Src);
4512
4513   // The terminator has to be a branch inst!
4514   BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
4515   assert(BI && "Unexpected terminator found");
4516
4517   if (BI->isConditional()) {
4518     VectorParts EdgeMask = getVectorValue(BI->getCondition());
4519
4520     if (BI->getSuccessor(0) != Dst)
4521       for (unsigned part = 0; part < UF; ++part)
4522         EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
4523
4524     for (unsigned part = 0; part < UF; ++part)
4525       EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
4526
4527     EdgeMaskCache[Edge] = EdgeMask;
4528     return EdgeMask;
4529   }
4530
4531   EdgeMaskCache[Edge] = SrcMask;
4532   return SrcMask;
4533 }
4534
4535 InnerLoopVectorizer::VectorParts
4536 InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
4537   assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
4538
4539   // Look for cached value.
4540   BlockMaskCacheTy::iterator BCEntryIt = BlockMaskCache.find(BB);
4541   if (BCEntryIt != BlockMaskCache.end())
4542     return BCEntryIt->second;
4543
4544   // Loop incoming mask is all-one.
4545   if (OrigLoop->getHeader() == BB) {
4546     Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
4547     const VectorParts &BlockMask = getVectorValue(C);
4548     BlockMaskCache[BB] = BlockMask;
4549     return BlockMask;
4550   }
4551
4552   // This is the block mask. We OR all incoming edges, and with zero.
4553   Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
4554   VectorParts BlockMask = getVectorValue(Zero);
4555
4556   // For each pred:
4557   for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
4558     VectorParts EM = createEdgeMask(*it, BB);
4559     for (unsigned part = 0; part < UF; ++part)
4560       BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
4561   }
4562
4563   BlockMaskCache[BB] = BlockMask;
4564   return BlockMask;
4565 }
4566
4567 void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN, unsigned UF,
4568                                               unsigned VF) {
4569   PHINode *P = cast<PHINode>(PN);
4570   // In order to support recurrences we need to be able to vectorize Phi nodes.
4571   // Phi nodes have cycles, so we need to vectorize them in two stages. This is
4572   // stage #1: We create a new vector PHI node with no incoming edges. We'll use
4573   // this value when we vectorize all of the instructions that use the PHI.
4574   if (Legal->isReductionVariable(P) || Legal->isFirstOrderRecurrence(P)) {
4575     VectorParts Entry(UF);
4576     for (unsigned part = 0; part < UF; ++part) {
4577       // This is phase one of vectorizing PHIs.
4578       Type *VecTy =
4579           (VF == 1) ? PN->getType() : VectorType::get(PN->getType(), VF);
4580       Entry[part] = PHINode::Create(
4581           VecTy, 2, "vec.phi", &*LoopVectorBody->getFirstInsertionPt());
4582     }
4583     VectorLoopValueMap.initVector(P, Entry);
4584     return;
4585   }
4586
4587   setDebugLocFromInst(Builder, P);
4588   // Check for PHI nodes that are lowered to vector selects.
4589   if (P->getParent() != OrigLoop->getHeader()) {
4590     // We know that all PHIs in non-header blocks are converted into
4591     // selects, so we don't have to worry about the insertion order and we
4592     // can just use the builder.
4593     // At this point we generate the predication tree. There may be
4594     // duplications since this is a simple recursive scan, but future
4595     // optimizations will clean it up.
4596
4597     unsigned NumIncoming = P->getNumIncomingValues();
4598
4599     // Generate a sequence of selects of the form:
4600     // SELECT(Mask3, In3,
4601     //      SELECT(Mask2, In2,
4602     //                   ( ...)))
4603     VectorParts Entry(UF);
4604     for (unsigned In = 0; In < NumIncoming; In++) {
4605       VectorParts Cond =
4606           createEdgeMask(P->getIncomingBlock(In), P->getParent());
4607       const VectorParts &In0 = getVectorValue(P->getIncomingValue(In));
4608
4609       for (unsigned part = 0; part < UF; ++part) {
4610         // We might have single edge PHIs (blocks) - use an identity
4611         // 'select' for the first PHI operand.
4612         if (In == 0)
4613           Entry[part] = Builder.CreateSelect(Cond[part], In0[part], In0[part]);
4614         else
4615           // Select between the current value and the previous incoming edge
4616           // based on the incoming mask.
4617           Entry[part] = Builder.CreateSelect(Cond[part], In0[part], Entry[part],
4618                                              "predphi");
4619       }
4620     }
4621     VectorLoopValueMap.initVector(P, Entry);
4622     return;
4623   }
4624
4625   // This PHINode must be an induction variable.
4626   // Make sure that we know about it.
4627   assert(Legal->getInductionVars()->count(P) && "Not an induction variable");
4628
4629   InductionDescriptor II = Legal->getInductionVars()->lookup(P);
4630   const DataLayout &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
4631
4632   // FIXME: The newly created binary instructions should contain nsw/nuw flags,
4633   // which can be found from the original scalar operations.
4634   switch (II.getKind()) {
4635   case InductionDescriptor::IK_NoInduction:
4636     llvm_unreachable("Unknown induction");
4637   case InductionDescriptor::IK_IntInduction:
4638   case InductionDescriptor::IK_FpInduction:
4639     return widenIntOrFpInduction(P);
4640   case InductionDescriptor::IK_PtrInduction: {
4641     // Handle the pointer induction variable case.
4642     assert(P->getType()->isPointerTy() && "Unexpected type.");
4643     // This is the normalized GEP that starts counting at zero.
4644     Value *PtrInd = Induction;
4645     PtrInd = Builder.CreateSExtOrTrunc(PtrInd, II.getStep()->getType());
4646     // Determine the number of scalars we need to generate for each unroll
4647     // iteration. If the instruction is uniform, we only need to generate the
4648     // first lane. Otherwise, we generate all VF values.
4649     unsigned Lanes = Cost->isUniformAfterVectorization(P, VF) ? 1 : VF;
4650     // These are the scalar results. Notice that we don't generate vector GEPs
4651     // because scalar GEPs result in better code.
4652     ScalarParts Entry(UF);
4653     for (unsigned Part = 0; Part < UF; ++Part) {
4654       Entry[Part].resize(VF);
4655       for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
4656         Constant *Idx = ConstantInt::get(PtrInd->getType(), Lane + Part * VF);
4657         Value *GlobalIdx = Builder.CreateAdd(PtrInd, Idx);
4658         Value *SclrGep = II.transform(Builder, GlobalIdx, PSE.getSE(), DL);
4659         SclrGep->setName("next.gep");
4660         Entry[Part][Lane] = SclrGep;
4661       }
4662     }
4663     VectorLoopValueMap.initScalar(P, Entry);
4664     return;
4665   }
4666   }
4667 }
4668
4669 /// A helper function for checking whether an integer division-related
4670 /// instruction may divide by zero (in which case it must be predicated if
4671 /// executed conditionally in the scalar code).
4672 /// TODO: It may be worthwhile to generalize and check isKnownNonZero().
4673 /// Non-zero divisors that are non compile-time constants will not be
4674 /// converted into multiplication, so we will still end up scalarizing
4675 /// the division, but can do so w/o predication.
4676 static bool mayDivideByZero(Instruction &I) {
4677   assert((I.getOpcode() == Instruction::UDiv ||
4678           I.getOpcode() == Instruction::SDiv ||
4679           I.getOpcode() == Instruction::URem ||
4680           I.getOpcode() == Instruction::SRem) &&
4681          "Unexpected instruction");
4682   Value *Divisor = I.getOperand(1);
4683   auto *CInt = dyn_cast<ConstantInt>(Divisor);
4684   return !CInt || CInt->isZero();
4685 }
4686
4687 void InnerLoopVectorizer::vectorizeInstruction(Instruction &I) {
4688   // Scalarize instructions that should remain scalar after vectorization.
4689   if (VF > 1 &&
4690       !(isa<BranchInst>(&I) || isa<PHINode>(&I) || isa<DbgInfoIntrinsic>(&I)) &&
4691       shouldScalarizeInstruction(&I)) {
4692     scalarizeInstruction(&I, Legal->isScalarWithPredication(&I));
4693     return;
4694   }
4695
4696   switch (I.getOpcode()) {
4697   case Instruction::Br:
4698     // Nothing to do for PHIs and BR, since we already took care of the
4699     // loop control flow instructions.
4700     break;
4701   case Instruction::PHI: {
4702     // Vectorize PHINodes.
4703     widenPHIInstruction(&I, UF, VF);
4704     break;
4705   } // End of PHI.
4706   case Instruction::GetElementPtr: {
4707     // Construct a vector GEP by widening the operands of the scalar GEP as
4708     // necessary. We mark the vector GEP 'inbounds' if appropriate. A GEP
4709     // results in a vector of pointers when at least one operand of the GEP
4710     // is vector-typed. Thus, to keep the representation compact, we only use
4711     // vector-typed operands for loop-varying values.
4712     auto *GEP = cast<GetElementPtrInst>(&I);
4713     VectorParts Entry(UF);
4714
4715     if (VF > 1 && OrigLoop->hasLoopInvariantOperands(GEP)) {
4716       // If we are vectorizing, but the GEP has only loop-invariant operands,
4717       // the GEP we build (by only using vector-typed operands for
4718       // loop-varying values) would be a scalar pointer. Thus, to ensure we
4719       // produce a vector of pointers, we need to either arbitrarily pick an
4720       // operand to broadcast, or broadcast a clone of the original GEP.
4721       // Here, we broadcast a clone of the original.
4722       //
4723       // TODO: If at some point we decide to scalarize instructions having
4724       //       loop-invariant operands, this special case will no longer be
4725       //       required. We would add the scalarization decision to
4726       //       collectLoopScalars() and teach getVectorValue() to broadcast
4727       //       the lane-zero scalar value.
4728       auto *Clone = Builder.Insert(GEP->clone());
4729       for (unsigned Part = 0; Part < UF; ++Part)
4730         Entry[Part] = Builder.CreateVectorSplat(VF, Clone);
4731     } else {
4732       // If the GEP has at least one loop-varying operand, we are sure to
4733       // produce a vector of pointers. But if we are only unrolling, we want
4734       // to produce a scalar GEP for each unroll part. Thus, the GEP we
4735       // produce with the code below will be scalar (if VF == 1) or vector
4736       // (otherwise). Note that for the unroll-only case, we still maintain
4737       // values in the vector mapping with initVector, as we do for other
4738       // instructions.
4739       for (unsigned Part = 0; Part < UF; ++Part) {
4740
4741         // The pointer operand of the new GEP. If it's loop-invariant, we
4742         // won't broadcast it.
4743         auto *Ptr = OrigLoop->isLoopInvariant(GEP->getPointerOperand())
4744                         ? GEP->getPointerOperand()
4745                         : getVectorValue(GEP->getPointerOperand())[Part];
4746
4747         // Collect all the indices for the new GEP. If any index is
4748         // loop-invariant, we won't broadcast it.
4749         SmallVector<Value *, 4> Indices;
4750         for (auto &U : make_range(GEP->idx_begin(), GEP->idx_end())) {
4751           if (OrigLoop->isLoopInvariant(U.get()))
4752             Indices.push_back(U.get());
4753           else
4754             Indices.push_back(getVectorValue(U.get())[Part]);
4755         }
4756
4757         // Create the new GEP. Note that this GEP may be a scalar if VF == 1,
4758         // but it should be a vector, otherwise.
4759         auto *NewGEP = GEP->isInBounds()
4760                            ? Builder.CreateInBoundsGEP(Ptr, Indices)
4761                            : Builder.CreateGEP(Ptr, Indices);
4762         assert((VF == 1 || NewGEP->getType()->isVectorTy()) &&
4763                "NewGEP is not a pointer vector");
4764         Entry[Part] = NewGEP;
4765       }
4766     }
4767
4768     VectorLoopValueMap.initVector(&I, Entry);
4769     addMetadata(Entry, GEP);
4770     break;
4771   }
4772   case Instruction::UDiv:
4773   case Instruction::SDiv:
4774   case Instruction::SRem:
4775   case Instruction::URem:
4776     // Scalarize with predication if this instruction may divide by zero and
4777     // block execution is conditional, otherwise fallthrough.
4778     if (Legal->isScalarWithPredication(&I)) {
4779       scalarizeInstruction(&I, true);
4780       break;
4781     }
4782     LLVM_FALLTHROUGH;
4783   case Instruction::Add:
4784   case Instruction::FAdd:
4785   case Instruction::Sub:
4786   case Instruction::FSub:
4787   case Instruction::Mul:
4788   case Instruction::FMul:
4789   case Instruction::FDiv:
4790   case Instruction::FRem:
4791   case Instruction::Shl:
4792   case Instruction::LShr:
4793   case Instruction::AShr:
4794   case Instruction::And:
4795   case Instruction::Or:
4796   case Instruction::Xor: {
4797     // Just widen binops.
4798     auto *BinOp = cast<BinaryOperator>(&I);
4799     setDebugLocFromInst(Builder, BinOp);
4800     const VectorParts &A = getVectorValue(BinOp->getOperand(0));
4801     const VectorParts &B = getVectorValue(BinOp->getOperand(1));
4802
4803     // Use this vector value for all users of the original instruction.
4804     VectorParts Entry(UF);
4805     for (unsigned Part = 0; Part < UF; ++Part) {
4806       Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
4807
4808       if (BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V))
4809         VecOp->copyIRFlags(BinOp);
4810
4811       Entry[Part] = V;
4812     }
4813
4814     VectorLoopValueMap.initVector(&I, Entry);
4815     addMetadata(Entry, BinOp);
4816     break;
4817   }
4818   case Instruction::Select: {
4819     // Widen selects.
4820     // If the selector is loop invariant we can create a select
4821     // instruction with a scalar condition. Otherwise, use vector-select.
4822     auto *SE = PSE.getSE();
4823     bool InvariantCond =
4824         SE->isLoopInvariant(PSE.getSCEV(I.getOperand(0)), OrigLoop);
4825     setDebugLocFromInst(Builder, &I);
4826
4827     // The condition can be loop invariant  but still defined inside the
4828     // loop. This means that we can't just use the original 'cond' value.
4829     // We have to take the 'vectorized' value and pick the first lane.
4830     // Instcombine will make this a no-op.
4831     const VectorParts &Cond = getVectorValue(I.getOperand(0));
4832     const VectorParts &Op0 = getVectorValue(I.getOperand(1));
4833     const VectorParts &Op1 = getVectorValue(I.getOperand(2));
4834
4835     auto *ScalarCond = getScalarValue(I.getOperand(0), 0, 0);
4836
4837     VectorParts Entry(UF);
4838     for (unsigned Part = 0; Part < UF; ++Part) {
4839       Entry[Part] = Builder.CreateSelect(
4840           InvariantCond ? ScalarCond : Cond[Part], Op0[Part], Op1[Part]);
4841     }
4842
4843     VectorLoopValueMap.initVector(&I, Entry);
4844     addMetadata(Entry, &I);
4845     break;
4846   }
4847
4848   case Instruction::ICmp:
4849   case Instruction::FCmp: {
4850     // Widen compares. Generate vector compares.
4851     bool FCmp = (I.getOpcode() == Instruction::FCmp);
4852     auto *Cmp = dyn_cast<CmpInst>(&I);
4853     setDebugLocFromInst(Builder, Cmp);
4854     const VectorParts &A = getVectorValue(Cmp->getOperand(0));
4855     const VectorParts &B = getVectorValue(Cmp->getOperand(1));
4856     VectorParts Entry(UF);
4857     for (unsigned Part = 0; Part < UF; ++Part) {
4858       Value *C = nullptr;
4859       if (FCmp) {
4860         C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
4861         cast<FCmpInst>(C)->copyFastMathFlags(Cmp);
4862       } else {
4863         C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
4864       }
4865       Entry[Part] = C;
4866     }
4867
4868     VectorLoopValueMap.initVector(&I, Entry);
4869     addMetadata(Entry, &I);
4870     break;
4871   }
4872
4873   case Instruction::Store:
4874   case Instruction::Load:
4875     vectorizeMemoryInstruction(&I);
4876     break;
4877   case Instruction::ZExt:
4878   case Instruction::SExt:
4879   case Instruction::FPToUI:
4880   case Instruction::FPToSI:
4881   case Instruction::FPExt:
4882   case Instruction::PtrToInt:
4883   case Instruction::IntToPtr:
4884   case Instruction::SIToFP:
4885   case Instruction::UIToFP:
4886   case Instruction::Trunc:
4887   case Instruction::FPTrunc:
4888   case Instruction::BitCast: {
4889     auto *CI = dyn_cast<CastInst>(&I);
4890     setDebugLocFromInst(Builder, CI);
4891
4892     // Optimize the special case where the source is a constant integer
4893     // induction variable. Notice that we can only optimize the 'trunc' case
4894     // because (a) FP conversions lose precision, (b) sext/zext may wrap, and
4895     // (c) other casts depend on pointer size.
4896     if (Cost->isOptimizableIVTruncate(CI, VF)) {
4897       widenIntOrFpInduction(cast<PHINode>(CI->getOperand(0)),
4898                             cast<TruncInst>(CI));
4899       break;
4900     }
4901
4902     /// Vectorize casts.
4903     Type *DestTy =
4904         (VF == 1) ? CI->getType() : VectorType::get(CI->getType(), VF);
4905
4906     const VectorParts &A = getVectorValue(CI->getOperand(0));
4907     VectorParts Entry(UF);
4908     for (unsigned Part = 0; Part < UF; ++Part)
4909       Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
4910     VectorLoopValueMap.initVector(&I, Entry);
4911     addMetadata(Entry, &I);
4912     break;
4913   }
4914
4915   case Instruction::Call: {
4916     // Ignore dbg intrinsics.
4917     if (isa<DbgInfoIntrinsic>(I))
4918       break;
4919     setDebugLocFromInst(Builder, &I);
4920
4921     Module *M = I.getParent()->getParent()->getParent();
4922     auto *CI = cast<CallInst>(&I);
4923
4924     StringRef FnName = CI->getCalledFunction()->getName();
4925     Function *F = CI->getCalledFunction();
4926     Type *RetTy = ToVectorTy(CI->getType(), VF);
4927     SmallVector<Type *, 4> Tys;
4928     for (Value *ArgOperand : CI->arg_operands())
4929       Tys.push_back(ToVectorTy(ArgOperand->getType(), VF));
4930
4931     Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4932     if (ID && (ID == Intrinsic::assume || ID == Intrinsic::lifetime_end ||
4933                ID == Intrinsic::lifetime_start)) {
4934       scalarizeInstruction(&I);
4935       break;
4936     }
4937     // The flag shows whether we use Intrinsic or a usual Call for vectorized
4938     // version of the instruction.
4939     // Is it beneficial to perform intrinsic call compared to lib call?
4940     bool NeedToScalarize;
4941     unsigned CallCost = getVectorCallCost(CI, VF, *TTI, TLI, NeedToScalarize);
4942     bool UseVectorIntrinsic =
4943         ID && getVectorIntrinsicCost(CI, VF, *TTI, TLI) <= CallCost;
4944     if (!UseVectorIntrinsic && NeedToScalarize) {
4945       scalarizeInstruction(&I);
4946       break;
4947     }
4948
4949     VectorParts Entry(UF);
4950     for (unsigned Part = 0; Part < UF; ++Part) {
4951       SmallVector<Value *, 4> Args;
4952       for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
4953         Value *Arg = CI->getArgOperand(i);
4954         // Some intrinsics have a scalar argument - don't replace it with a
4955         // vector.
4956         if (!UseVectorIntrinsic || !hasVectorInstrinsicScalarOpd(ID, i)) {
4957           const VectorParts &VectorArg = getVectorValue(CI->getArgOperand(i));
4958           Arg = VectorArg[Part];
4959         }
4960         Args.push_back(Arg);
4961       }
4962
4963       Function *VectorF;
4964       if (UseVectorIntrinsic) {
4965         // Use vector version of the intrinsic.
4966         Type *TysForDecl[] = {CI->getType()};
4967         if (VF > 1)
4968           TysForDecl[0] = VectorType::get(CI->getType()->getScalarType(), VF);
4969         VectorF = Intrinsic::getDeclaration(M, ID, TysForDecl);
4970       } else {
4971         // Use vector version of the library call.
4972         StringRef VFnName = TLI->getVectorizedFunction(FnName, VF);
4973         assert(!VFnName.empty() && "Vector function name is empty.");
4974         VectorF = M->getFunction(VFnName);
4975         if (!VectorF) {
4976           // Generate a declaration
4977           FunctionType *FTy = FunctionType::get(RetTy, Tys, false);
4978           VectorF =
4979               Function::Create(FTy, Function::ExternalLinkage, VFnName, M);
4980           VectorF->copyAttributesFrom(F);
4981         }
4982       }
4983       assert(VectorF && "Can't create vector function.");
4984
4985       SmallVector<OperandBundleDef, 1> OpBundles;
4986       CI->getOperandBundlesAsDefs(OpBundles);
4987       CallInst *V = Builder.CreateCall(VectorF, Args, OpBundles);
4988
4989       if (isa<FPMathOperator>(V))
4990         V->copyFastMathFlags(CI);
4991
4992       Entry[Part] = V;
4993     }
4994
4995     VectorLoopValueMap.initVector(&I, Entry);
4996     addMetadata(Entry, &I);
4997     break;
4998   }
4999
5000   default:
5001     // All other instructions are unsupported. Scalarize them.
5002     scalarizeInstruction(&I);
5003     break;
5004   } // end of switch.
5005 }
5006
5007 void InnerLoopVectorizer::updateAnalysis() {
5008   // Forget the original basic block.
5009   PSE.getSE()->forgetLoop(OrigLoop);
5010
5011   // Update the dominator tree information.
5012   assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&
5013          "Entry does not dominate exit.");
5014
5015   DT->addNewBlock(LI->getLoopFor(LoopVectorBody)->getHeader(),
5016                   LoopVectorPreHeader);
5017   DT->addNewBlock(LoopMiddleBlock,
5018                   LI->getLoopFor(LoopVectorBody)->getLoopLatch());
5019   DT->addNewBlock(LoopScalarPreHeader, LoopBypassBlocks[0]);
5020   DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
5021   DT->changeImmediateDominator(LoopExitBlock, LoopBypassBlocks[0]);
5022
5023   DEBUG(DT->verifyDomTree());
5024 }
5025
5026 /// \brief Check whether it is safe to if-convert this phi node.
5027 ///
5028 /// Phi nodes with constant expressions that can trap are not safe to if
5029 /// convert.
5030 static bool canIfConvertPHINodes(BasicBlock *BB) {
5031   for (Instruction &I : *BB) {
5032     auto *Phi = dyn_cast<PHINode>(&I);
5033     if (!Phi)
5034       return true;
5035     for (Value *V : Phi->incoming_values())
5036       if (auto *C = dyn_cast<Constant>(V))
5037         if (C->canTrap())
5038           return false;
5039   }
5040   return true;
5041 }
5042
5043 bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
5044   if (!EnableIfConversion) {
5045     ORE->emit(createMissedAnalysis("IfConversionDisabled")
5046               << "if-conversion is disabled");
5047     return false;
5048   }
5049
5050   assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
5051
5052   // A list of pointers that we can safely read and write to.
5053   SmallPtrSet<Value *, 8> SafePointes;
5054
5055   // Collect safe addresses.
5056   for (BasicBlock *BB : TheLoop->blocks()) {
5057     if (blockNeedsPredication(BB))
5058       continue;
5059
5060     for (Instruction &I : *BB)
5061       if (auto *Ptr = getPointerOperand(&I))
5062         SafePointes.insert(Ptr);
5063   }
5064
5065   // Collect the blocks that need predication.
5066   BasicBlock *Header = TheLoop->getHeader();
5067   for (BasicBlock *BB : TheLoop->blocks()) {
5068     // We don't support switch statements inside loops.
5069     if (!isa<BranchInst>(BB->getTerminator())) {
5070       ORE->emit(createMissedAnalysis("LoopContainsSwitch", BB->getTerminator())
5071                 << "loop contains a switch statement");
5072       return false;
5073     }
5074
5075     // We must be able to predicate all blocks that need to be predicated.
5076     if (blockNeedsPredication(BB)) {
5077       if (!blockCanBePredicated(BB, SafePointes)) {
5078         ORE->emit(createMissedAnalysis("NoCFGForSelect", BB->getTerminator())
5079                   << "control flow cannot be substituted for a select");
5080         return false;
5081       }
5082     } else if (BB != Header && !canIfConvertPHINodes(BB)) {
5083       ORE->emit(createMissedAnalysis("NoCFGForSelect", BB->getTerminator())
5084                 << "control flow cannot be substituted for a select");
5085       return false;
5086     }
5087   }
5088
5089   // We can if-convert this loop.
5090   return true;
5091 }
5092
5093 bool LoopVectorizationLegality::canVectorize() {
5094   // Store the result and return it at the end instead of exiting early, in case
5095   // allowExtraAnalysis is used to report multiple reasons for not vectorizing.
5096   bool Result = true;
5097   // We must have a loop in canonical form. Loops with indirectbr in them cannot
5098   // be canonicalized.
5099   if (!TheLoop->getLoopPreheader()) {
5100     ORE->emit(createMissedAnalysis("CFGNotUnderstood")
5101               << "loop control flow is not understood by vectorizer");
5102     if (ORE->allowExtraAnalysis())
5103       Result = false;
5104     else
5105       return false;
5106   }
5107
5108   // FIXME: The code is currently dead, since the loop gets sent to
5109   // LoopVectorizationLegality is already an innermost loop.
5110   //
5111   // We can only vectorize innermost loops.
5112   if (!TheLoop->empty()) {
5113     ORE->emit(createMissedAnalysis("NotInnermostLoop")
5114               << "loop is not the innermost loop");
5115     if (ORE->allowExtraAnalysis())
5116       Result = false;
5117     else
5118       return false;
5119   }
5120
5121   // We must have a single backedge.
5122   if (TheLoop->getNumBackEdges() != 1) {
5123     ORE->emit(createMissedAnalysis("CFGNotUnderstood")
5124               << "loop control flow is not understood by vectorizer");
5125     if (ORE->allowExtraAnalysis())
5126       Result = false;
5127     else
5128       return false;
5129   }
5130
5131   // We must have a single exiting block.
5132   if (!TheLoop->getExitingBlock()) {
5133     ORE->emit(createMissedAnalysis("CFGNotUnderstood")
5134               << "loop control flow is not understood by vectorizer");
5135     if (ORE->allowExtraAnalysis())
5136       Result = false;
5137     else
5138       return false;
5139   }
5140
5141   // We only handle bottom-tested loops, i.e. loop in which the condition is
5142   // checked at the end of each iteration. With that we can assume that all
5143   // instructions in the loop are executed the same number of times.
5144   if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
5145     ORE->emit(createMissedAnalysis("CFGNotUnderstood")
5146               << "loop control flow is not understood by vectorizer");
5147     if (ORE->allowExtraAnalysis())
5148       Result = false;
5149     else
5150       return false;
5151   }
5152
5153   // We need to have a loop header.
5154   DEBUG(dbgs() << "LV: Found a loop: " << TheLoop->getHeader()->getName()
5155                << '\n');
5156
5157   // Check if we can if-convert non-single-bb loops.
5158   unsigned NumBlocks = TheLoop->getNumBlocks();
5159   if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
5160     DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
5161     if (ORE->allowExtraAnalysis())
5162       Result = false;
5163     else
5164       return false;
5165   }
5166
5167   // Check if we can vectorize the instructions and CFG in this loop.
5168   if (!canVectorizeInstrs()) {
5169     DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
5170     if (ORE->allowExtraAnalysis())
5171       Result = false;
5172     else
5173       return false;
5174   }
5175
5176   // Go over each instruction and look at memory deps.
5177   if (!canVectorizeMemory()) {
5178     DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
5179     if (ORE->allowExtraAnalysis())
5180       Result = false;
5181     else
5182       return false;
5183   }
5184
5185   DEBUG(dbgs() << "LV: We can vectorize this loop"
5186                << (LAI->getRuntimePointerChecking()->Need
5187                        ? " (with a runtime bound check)"
5188                        : "")
5189                << "!\n");
5190
5191   bool UseInterleaved = TTI->enableInterleavedAccessVectorization();
5192
5193   // If an override option has been passed in for interleaved accesses, use it.
5194   if (EnableInterleavedMemAccesses.getNumOccurrences() > 0)
5195     UseInterleaved = EnableInterleavedMemAccesses;
5196
5197   // Analyze interleaved memory accesses.
5198   if (UseInterleaved)
5199     InterleaveInfo.analyzeInterleaving(*getSymbolicStrides());
5200
5201   unsigned SCEVThreshold = VectorizeSCEVCheckThreshold;
5202   if (Hints->getForce() == LoopVectorizeHints::FK_Enabled)
5203     SCEVThreshold = PragmaVectorizeSCEVCheckThreshold;
5204
5205   if (PSE.getUnionPredicate().getComplexity() > SCEVThreshold) {
5206     ORE->emit(createMissedAnalysis("TooManySCEVRunTimeChecks")
5207               << "Too many SCEV assumptions need to be made and checked "
5208               << "at runtime");
5209     DEBUG(dbgs() << "LV: Too many SCEV checks needed.\n");
5210     if (ORE->allowExtraAnalysis())
5211       Result = false;
5212     else
5213       return false;
5214   }
5215
5216   // Okay! We've done all the tests. If any have failed, return false. Otherwise
5217   // we can vectorize, and at this point we don't have any other mem analysis
5218   // which may limit our maximum vectorization factor, so just return true with
5219   // no restrictions.
5220   return Result;
5221 }
5222
5223 static Type *convertPointerToIntegerType(const DataLayout &DL, Type *Ty) {
5224   if (Ty->isPointerTy())
5225     return DL.getIntPtrType(Ty);
5226
5227   // It is possible that char's or short's overflow when we ask for the loop's
5228   // trip count, work around this by changing the type size.
5229   if (Ty->getScalarSizeInBits() < 32)
5230     return Type::getInt32Ty(Ty->getContext());
5231
5232   return Ty;
5233 }
5234
5235 static Type *getWiderType(const DataLayout &DL, Type *Ty0, Type *Ty1) {
5236   Ty0 = convertPointerToIntegerType(DL, Ty0);
5237   Ty1 = convertPointerToIntegerType(DL, Ty1);
5238   if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits())
5239     return Ty0;
5240   return Ty1;
5241 }
5242
5243 /// \brief Check that the instruction has outside loop users and is not an
5244 /// identified reduction variable.
5245 static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst,
5246                                SmallPtrSetImpl<Value *> &AllowedExit) {
5247   // Reduction and Induction instructions are allowed to have exit users. All
5248   // other instructions must not have external users.
5249   if (!AllowedExit.count(Inst))
5250     // Check that all of the users of the loop are inside the BB.
5251     for (User *U : Inst->users()) {
5252       Instruction *UI = cast<Instruction>(U);
5253       // This user may be a reduction exit value.
5254       if (!TheLoop->contains(UI)) {
5255         DEBUG(dbgs() << "LV: Found an outside user for : " << *UI << '\n');
5256         return true;
5257       }
5258     }
5259   return false;
5260 }
5261
5262 void LoopVectorizationLegality::addInductionPhi(
5263     PHINode *Phi, const InductionDescriptor &ID,
5264     SmallPtrSetImpl<Value *> &AllowedExit) {
5265   Inductions[Phi] = ID;
5266   Type *PhiTy = Phi->getType();
5267   const DataLayout &DL = Phi->getModule()->getDataLayout();
5268
5269   // Get the widest type.
5270   if (!PhiTy->isFloatingPointTy()) {
5271     if (!WidestIndTy)
5272       WidestIndTy = convertPointerToIntegerType(DL, PhiTy);
5273     else
5274       WidestIndTy = getWiderType(DL, PhiTy, WidestIndTy);
5275   }
5276
5277   // Int inductions are special because we only allow one IV.
5278   if (ID.getKind() == InductionDescriptor::IK_IntInduction &&
5279       ID.getConstIntStepValue() &&
5280       ID.getConstIntStepValue()->isOne() &&
5281       isa<Constant>(ID.getStartValue()) &&
5282       cast<Constant>(ID.getStartValue())->isNullValue()) {
5283
5284     // Use the phi node with the widest type as induction. Use the last
5285     // one if there are multiple (no good reason for doing this other
5286     // than it is expedient). We've checked that it begins at zero and
5287     // steps by one, so this is a canonical induction variable.
5288     if (!PrimaryInduction || PhiTy == WidestIndTy)
5289       PrimaryInduction = Phi;
5290   }
5291
5292   // Both the PHI node itself, and the "post-increment" value feeding
5293   // back into the PHI node may have external users.
5294   AllowedExit.insert(Phi);
5295   AllowedExit.insert(Phi->getIncomingValueForBlock(TheLoop->getLoopLatch()));
5296
5297   DEBUG(dbgs() << "LV: Found an induction variable.\n");
5298   return;
5299 }
5300
5301 bool LoopVectorizationLegality::canVectorizeInstrs() {
5302   BasicBlock *Header = TheLoop->getHeader();
5303
5304   // Look for the attribute signaling the absence of NaNs.
5305   Function &F = *Header->getParent();
5306   HasFunNoNaNAttr =
5307       F.getFnAttribute("no-nans-fp-math").getValueAsString() == "true";
5308
5309   // For each block in the loop.
5310   for (BasicBlock *BB : TheLoop->blocks()) {
5311     // Scan the instructions in the block and look for hazards.
5312     for (Instruction &I : *BB) {
5313       if (auto *Phi = dyn_cast<PHINode>(&I)) {
5314         Type *PhiTy = Phi->getType();
5315         // Check that this PHI type is allowed.
5316         if (!PhiTy->isIntegerTy() && !PhiTy->isFloatingPointTy() &&
5317             !PhiTy->isPointerTy()) {
5318           ORE->emit(createMissedAnalysis("CFGNotUnderstood", Phi)
5319                     << "loop control flow is not understood by vectorizer");
5320           DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
5321           return false;
5322         }
5323
5324         // If this PHINode is not in the header block, then we know that we
5325         // can convert it to select during if-conversion. No need to check if
5326         // the PHIs in this block are induction or reduction variables.
5327         if (BB != Header) {
5328           // Check that this instruction has no outside users or is an
5329           // identified reduction value with an outside user.
5330           if (!hasOutsideLoopUser(TheLoop, Phi, AllowedExit))
5331             continue;
5332           ORE->emit(createMissedAnalysis("NeitherInductionNorReduction", Phi)
5333                     << "value could not be identified as "
5334                        "an induction or reduction variable");
5335           return false;
5336         }
5337
5338         // We only allow if-converted PHIs with exactly two incoming values.
5339         if (Phi->getNumIncomingValues() != 2) {
5340           ORE->emit(createMissedAnalysis("CFGNotUnderstood", Phi)
5341                     << "control flow not understood by vectorizer");
5342           DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
5343           return false;
5344         }
5345
5346         RecurrenceDescriptor RedDes;
5347         if (RecurrenceDescriptor::isReductionPHI(Phi, TheLoop, RedDes)) {
5348           if (RedDes.hasUnsafeAlgebra())
5349             Requirements->addUnsafeAlgebraInst(RedDes.getUnsafeAlgebraInst());
5350           AllowedExit.insert(RedDes.getLoopExitInstr());
5351           Reductions[Phi] = RedDes;
5352           continue;
5353         }
5354
5355         InductionDescriptor ID;
5356         if (InductionDescriptor::isInductionPHI(Phi, TheLoop, PSE, ID)) {
5357           addInductionPhi(Phi, ID, AllowedExit);
5358           if (ID.hasUnsafeAlgebra() && !HasFunNoNaNAttr)
5359             Requirements->addUnsafeAlgebraInst(ID.getUnsafeAlgebraInst());
5360           continue;
5361         }
5362
5363         if (RecurrenceDescriptor::isFirstOrderRecurrence(Phi, TheLoop, DT)) {
5364           FirstOrderRecurrences.insert(Phi);
5365           continue;
5366         }
5367
5368         // As a last resort, coerce the PHI to a AddRec expression
5369         // and re-try classifying it a an induction PHI.
5370         if (InductionDescriptor::isInductionPHI(Phi, TheLoop, PSE, ID, true)) {
5371           addInductionPhi(Phi, ID, AllowedExit);
5372           continue;
5373         }
5374
5375         ORE->emit(createMissedAnalysis("NonReductionValueUsedOutsideLoop", Phi)
5376                   << "value that could not be identified as "
5377                      "reduction is used outside the loop");
5378         DEBUG(dbgs() << "LV: Found an unidentified PHI." << *Phi << "\n");
5379         return false;
5380       } // end of PHI handling
5381
5382       // We handle calls that:
5383       //   * Are debug info intrinsics.
5384       //   * Have a mapping to an IR intrinsic.
5385       //   * Have a vector version available.
5386       auto *CI = dyn_cast<CallInst>(&I);
5387       if (CI && !getVectorIntrinsicIDForCall(CI, TLI) &&
5388           !isa<DbgInfoIntrinsic>(CI) &&
5389           !(CI->getCalledFunction() && TLI &&
5390             TLI->isFunctionVectorizable(CI->getCalledFunction()->getName()))) {
5391         ORE->emit(createMissedAnalysis("CantVectorizeCall", CI)
5392                   << "call instruction cannot be vectorized");
5393         DEBUG(dbgs() << "LV: Found a non-intrinsic, non-libfunc callsite.\n");
5394         return false;
5395       }
5396
5397       // Intrinsics such as powi,cttz and ctlz are legal to vectorize if the
5398       // second argument is the same (i.e. loop invariant)
5399       if (CI && hasVectorInstrinsicScalarOpd(
5400                     getVectorIntrinsicIDForCall(CI, TLI), 1)) {
5401         auto *SE = PSE.getSE();
5402         if (!SE->isLoopInvariant(PSE.getSCEV(CI->getOperand(1)), TheLoop)) {
5403           ORE->emit(createMissedAnalysis("CantVectorizeIntrinsic", CI)
5404                     << "intrinsic instruction cannot be vectorized");
5405           DEBUG(dbgs() << "LV: Found unvectorizable intrinsic " << *CI << "\n");
5406           return false;
5407         }
5408       }
5409
5410       // Check that the instruction return type is vectorizable.
5411       // Also, we can't vectorize extractelement instructions.
5412       if ((!VectorType::isValidElementType(I.getType()) &&
5413            !I.getType()->isVoidTy()) ||
5414           isa<ExtractElementInst>(I)) {
5415         ORE->emit(createMissedAnalysis("CantVectorizeInstructionReturnType", &I)
5416                   << "instruction return type cannot be vectorized");
5417         DEBUG(dbgs() << "LV: Found unvectorizable type.\n");
5418         return false;
5419       }
5420
5421       // Check that the stored type is vectorizable.
5422       if (auto *ST = dyn_cast<StoreInst>(&I)) {
5423         Type *T = ST->getValueOperand()->getType();
5424         if (!VectorType::isValidElementType(T)) {
5425           ORE->emit(createMissedAnalysis("CantVectorizeStore", ST)
5426                     << "store instruction cannot be vectorized");
5427           return false;
5428         }
5429
5430         // FP instructions can allow unsafe algebra, thus vectorizable by
5431         // non-IEEE-754 compliant SIMD units.
5432         // This applies to floating-point math operations and calls, not memory
5433         // operations, shuffles, or casts, as they don't change precision or
5434         // semantics.
5435       } else if (I.getType()->isFloatingPointTy() && (CI || I.isBinaryOp()) &&
5436                  !I.hasUnsafeAlgebra()) {
5437         DEBUG(dbgs() << "LV: Found FP op with unsafe algebra.\n");
5438         Hints->setPotentiallyUnsafe();
5439       }
5440
5441       // Reduction instructions are allowed to have exit users.
5442       // All other instructions must not have external users.
5443       if (hasOutsideLoopUser(TheLoop, &I, AllowedExit)) {
5444         ORE->emit(createMissedAnalysis("ValueUsedOutsideLoop", &I)
5445                   << "value cannot be used outside the loop");
5446         return false;
5447       }
5448
5449     } // next instr.
5450   }
5451
5452   if (!PrimaryInduction) {
5453     DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
5454     if (Inductions.empty()) {
5455       ORE->emit(createMissedAnalysis("NoInductionVariable")
5456                 << "loop induction variable could not be identified");
5457       return false;
5458     }
5459   }
5460
5461   // Now we know the widest induction type, check if our found induction
5462   // is the same size. If it's not, unset it here and InnerLoopVectorizer
5463   // will create another.
5464   if (PrimaryInduction && WidestIndTy != PrimaryInduction->getType())
5465     PrimaryInduction = nullptr;
5466
5467   return true;
5468 }
5469
5470 void LoopVectorizationCostModel::collectLoopScalars(unsigned VF) {
5471
5472   // We should not collect Scalars more than once per VF. Right now, this
5473   // function is called from collectUniformsAndScalars(), which already does
5474   // this check. Collecting Scalars for VF=1 does not make any sense.
5475   assert(VF >= 2 && !Scalars.count(VF) &&
5476          "This function should not be visited twice for the same VF");
5477
5478   SmallSetVector<Instruction *, 8> Worklist;
5479
5480   // These sets are used to seed the analysis with pointers used by memory
5481   // accesses that will remain scalar.
5482   SmallSetVector<Instruction *, 8> ScalarPtrs;
5483   SmallPtrSet<Instruction *, 8> PossibleNonScalarPtrs;
5484
5485   // A helper that returns true if the use of Ptr by MemAccess will be scalar.
5486   // The pointer operands of loads and stores will be scalar as long as the
5487   // memory access is not a gather or scatter operation. The value operand of a
5488   // store will remain scalar if the store is scalarized.
5489   auto isScalarUse = [&](Instruction *MemAccess, Value *Ptr) {
5490     InstWidening WideningDecision = getWideningDecision(MemAccess, VF);
5491     assert(WideningDecision != CM_Unknown &&
5492            "Widening decision should be ready at this moment");
5493     if (auto *Store = dyn_cast<StoreInst>(MemAccess))
5494       if (Ptr == Store->getValueOperand())
5495         return WideningDecision == CM_Scalarize;
5496     assert(Ptr == getPointerOperand(MemAccess) &&
5497            "Ptr is neither a value or pointer operand");
5498     return WideningDecision != CM_GatherScatter;
5499   };
5500
5501   // A helper that returns true if the given value is a bitcast or
5502   // getelementptr instruction contained in the loop.
5503   auto isLoopVaryingBitCastOrGEP = [&](Value *V) {
5504     return ((isa<BitCastInst>(V) && V->getType()->isPointerTy()) ||
5505             isa<GetElementPtrInst>(V)) &&
5506            !TheLoop->isLoopInvariant(V);
5507   };
5508
5509   // A helper that evaluates a memory access's use of a pointer. If the use
5510   // will be a scalar use, and the pointer is only used by memory accesses, we
5511   // place the pointer in ScalarPtrs. Otherwise, the pointer is placed in
5512   // PossibleNonScalarPtrs.
5513   auto evaluatePtrUse = [&](Instruction *MemAccess, Value *Ptr) {
5514
5515     // We only care about bitcast and getelementptr instructions contained in
5516     // the loop.
5517     if (!isLoopVaryingBitCastOrGEP(Ptr))
5518       return;
5519
5520     // If the pointer has already been identified as scalar (e.g., if it was
5521     // also identified as uniform), there's nothing to do.
5522     auto *I = cast<Instruction>(Ptr);
5523     if (Worklist.count(I))
5524       return;
5525
5526     // If the use of the pointer will be a scalar use, and all users of the
5527     // pointer are memory accesses, place the pointer in ScalarPtrs. Otherwise,
5528     // place the pointer in PossibleNonScalarPtrs.
5529     if (isScalarUse(MemAccess, Ptr) && all_of(I->users(), [&](User *U) {
5530           return isa<LoadInst>(U) || isa<StoreInst>(U);
5531         }))
5532       ScalarPtrs.insert(I);
5533     else
5534       PossibleNonScalarPtrs.insert(I);
5535   };
5536
5537   // We seed the scalars analysis with three classes of instructions: (1)
5538   // instructions marked uniform-after-vectorization, (2) bitcast and
5539   // getelementptr instructions used by memory accesses requiring a scalar use,
5540   // and (3) pointer induction variables and their update instructions (we
5541   // currently only scalarize these).
5542   //
5543   // (1) Add to the worklist all instructions that have been identified as
5544   // uniform-after-vectorization.
5545   Worklist.insert(Uniforms[VF].begin(), Uniforms[VF].end());
5546
5547   // (2) Add to the worklist all bitcast and getelementptr instructions used by
5548   // memory accesses requiring a scalar use. The pointer operands of loads and
5549   // stores will be scalar as long as the memory accesses is not a gather or
5550   // scatter operation. The value operand of a store will remain scalar if the
5551   // store is scalarized.
5552   for (auto *BB : TheLoop->blocks())
5553     for (auto &I : *BB) {
5554       if (auto *Load = dyn_cast<LoadInst>(&I)) {
5555         evaluatePtrUse(Load, Load->getPointerOperand());
5556       } else if (auto *Store = dyn_cast<StoreInst>(&I)) {
5557         evaluatePtrUse(Store, Store->getPointerOperand());
5558         evaluatePtrUse(Store, Store->getValueOperand());
5559       }
5560     }
5561   for (auto *I : ScalarPtrs)
5562     if (!PossibleNonScalarPtrs.count(I)) {
5563       DEBUG(dbgs() << "LV: Found scalar instruction: " << *I << "\n");
5564       Worklist.insert(I);
5565     }
5566
5567   // (3) Add to the worklist all pointer induction variables and their update
5568   // instructions.
5569   //
5570   // TODO: Once we are able to vectorize pointer induction variables we should
5571   //       no longer insert them into the worklist here.
5572   auto *Latch = TheLoop->getLoopLatch();
5573   for (auto &Induction : *Legal->getInductionVars()) {
5574     auto *Ind = Induction.first;
5575     auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
5576     if (Induction.second.getKind() != InductionDescriptor::IK_PtrInduction)
5577       continue;
5578     Worklist.insert(Ind);
5579     Worklist.insert(IndUpdate);
5580     DEBUG(dbgs() << "LV: Found scalar instruction: " << *Ind << "\n");
5581     DEBUG(dbgs() << "LV: Found scalar instruction: " << *IndUpdate << "\n");
5582   }
5583
5584   // Insert the forced scalars.
5585   // FIXME: Currently widenPHIInstruction() often creates a dead vector
5586   // induction variable when the PHI user is scalarized.
5587   if (ForcedScalars.count(VF))
5588     for (auto *I : ForcedScalars.find(VF)->second)
5589       Worklist.insert(I);
5590
5591   // Expand the worklist by looking through any bitcasts and getelementptr
5592   // instructions we've already identified as scalar. This is similar to the
5593   // expansion step in collectLoopUniforms(); however, here we're only
5594   // expanding to include additional bitcasts and getelementptr instructions.
5595   unsigned Idx = 0;
5596   while (Idx != Worklist.size()) {
5597     Instruction *Dst = Worklist[Idx++];
5598     if (!isLoopVaryingBitCastOrGEP(Dst->getOperand(0)))
5599       continue;
5600     auto *Src = cast<Instruction>(Dst->getOperand(0));
5601     if (all_of(Src->users(), [&](User *U) -> bool {
5602           auto *J = cast<Instruction>(U);
5603           return !TheLoop->contains(J) || Worklist.count(J) ||
5604                  ((isa<LoadInst>(J) || isa<StoreInst>(J)) &&
5605                   isScalarUse(J, Src));
5606         })) {
5607       Worklist.insert(Src);
5608       DEBUG(dbgs() << "LV: Found scalar instruction: " << *Src << "\n");
5609     }
5610   }
5611
5612   // An induction variable will remain scalar if all users of the induction
5613   // variable and induction variable update remain scalar.
5614   for (auto &Induction : *Legal->getInductionVars()) {
5615     auto *Ind = Induction.first;
5616     auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
5617
5618     // We already considered pointer induction variables, so there's no reason
5619     // to look at their users again.
5620     //
5621     // TODO: Once we are able to vectorize pointer induction variables we
5622     //       should no longer skip over them here.
5623     if (Induction.second.getKind() == InductionDescriptor::IK_PtrInduction)
5624       continue;
5625
5626     // Determine if all users of the induction variable are scalar after
5627     // vectorization.
5628     auto ScalarInd = all_of(Ind->users(), [&](User *U) -> bool {
5629       auto *I = cast<Instruction>(U);
5630       return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I);
5631     });
5632     if (!ScalarInd)
5633       continue;
5634
5635     // Determine if all users of the induction variable update instruction are
5636     // scalar after vectorization.
5637     auto ScalarIndUpdate = all_of(IndUpdate->users(), [&](User *U) -> bool {
5638       auto *I = cast<Instruction>(U);
5639       return I == Ind || !TheLoop->contains(I) || Worklist.count(I);
5640     });
5641     if (!ScalarIndUpdate)
5642       continue;
5643
5644     // The induction variable and its update instruction will remain scalar.
5645     Worklist.insert(Ind);
5646     Worklist.insert(IndUpdate);
5647     DEBUG(dbgs() << "LV: Found scalar instruction: " << *Ind << "\n");
5648     DEBUG(dbgs() << "LV: Found scalar instruction: " << *IndUpdate << "\n");
5649   }
5650
5651   Scalars[VF].insert(Worklist.begin(), Worklist.end());
5652 }
5653
5654 bool LoopVectorizationLegality::isScalarWithPredication(Instruction *I) {
5655   if (!blockNeedsPredication(I->getParent()))
5656     return false;
5657   switch(I->getOpcode()) {
5658   default:
5659     break;
5660   case Instruction::Store:
5661     return !isMaskRequired(I);
5662   case Instruction::UDiv:
5663   case Instruction::SDiv:
5664   case Instruction::SRem:
5665   case Instruction::URem:
5666     return mayDivideByZero(*I);
5667   }
5668   return false;
5669 }
5670
5671 bool LoopVectorizationLegality::memoryInstructionCanBeWidened(Instruction *I,
5672                                                               unsigned VF) {
5673   // Get and ensure we have a valid memory instruction.
5674   LoadInst *LI = dyn_cast<LoadInst>(I);
5675   StoreInst *SI = dyn_cast<StoreInst>(I);
5676   assert((LI || SI) && "Invalid memory instruction");
5677
5678   auto *Ptr = getPointerOperand(I);
5679
5680   // In order to be widened, the pointer should be consecutive, first of all.
5681   if (!isConsecutivePtr(Ptr))
5682     return false;
5683
5684   // If the instruction is a store located in a predicated block, it will be
5685   // scalarized.
5686   if (isScalarWithPredication(I))
5687     return false;
5688
5689   // If the instruction's allocated size doesn't equal it's type size, it
5690   // requires padding and will be scalarized.
5691   auto &DL = I->getModule()->getDataLayout();
5692   auto *ScalarTy = LI ? LI->getType() : SI->getValueOperand()->getType();
5693   if (hasIrregularType(ScalarTy, DL, VF))
5694     return false;
5695
5696   return true;
5697 }
5698
5699 void LoopVectorizationCostModel::collectLoopUniforms(unsigned VF) {
5700
5701   // We should not collect Uniforms more than once per VF. Right now,
5702   // this function is called from collectUniformsAndScalars(), which 
5703   // already does this check. Collecting Uniforms for VF=1 does not make any
5704   // sense.
5705
5706   assert(VF >= 2 && !Uniforms.count(VF) &&
5707          "This function should not be visited twice for the same VF");
5708
5709   // Visit the list of Uniforms. If we'll not find any uniform value, we'll 
5710   // not analyze again.  Uniforms.count(VF) will return 1.
5711   Uniforms[VF].clear();
5712
5713   // We now know that the loop is vectorizable!
5714   // Collect instructions inside the loop that will remain uniform after
5715   // vectorization.
5716
5717   // Global values, params and instructions outside of current loop are out of
5718   // scope.
5719   auto isOutOfScope = [&](Value *V) -> bool {
5720     Instruction *I = dyn_cast<Instruction>(V);
5721     return (!I || !TheLoop->contains(I));
5722   };
5723
5724   SetVector<Instruction *> Worklist;
5725   BasicBlock *Latch = TheLoop->getLoopLatch();
5726
5727   // Start with the conditional branch. If the branch condition is an
5728   // instruction contained in the loop that is only used by the branch, it is
5729   // uniform.
5730   auto *Cmp = dyn_cast<Instruction>(Latch->getTerminator()->getOperand(0));
5731   if (Cmp && TheLoop->contains(Cmp) && Cmp->hasOneUse()) {
5732     Worklist.insert(Cmp);
5733     DEBUG(dbgs() << "LV: Found uniform instruction: " << *Cmp << "\n");
5734   }
5735
5736   // Holds consecutive and consecutive-like pointers. Consecutive-like pointers
5737   // are pointers that are treated like consecutive pointers during
5738   // vectorization. The pointer operands of interleaved accesses are an
5739   // example.
5740   SmallSetVector<Instruction *, 8> ConsecutiveLikePtrs;
5741
5742   // Holds pointer operands of instructions that are possibly non-uniform.
5743   SmallPtrSet<Instruction *, 8> PossibleNonUniformPtrs;
5744
5745   auto isUniformDecision = [&](Instruction *I, unsigned VF) {
5746     InstWidening WideningDecision = getWideningDecision(I, VF);
5747     assert(WideningDecision != CM_Unknown &&
5748            "Widening decision should be ready at this moment");
5749
5750     return (WideningDecision == CM_Widen ||
5751             WideningDecision == CM_Interleave);
5752   };
5753   // Iterate over the instructions in the loop, and collect all
5754   // consecutive-like pointer operands in ConsecutiveLikePtrs. If it's possible
5755   // that a consecutive-like pointer operand will be scalarized, we collect it
5756   // in PossibleNonUniformPtrs instead. We use two sets here because a single
5757   // getelementptr instruction can be used by both vectorized and scalarized
5758   // memory instructions. For example, if a loop loads and stores from the same
5759   // location, but the store is conditional, the store will be scalarized, and
5760   // the getelementptr won't remain uniform.
5761   for (auto *BB : TheLoop->blocks())
5762     for (auto &I : *BB) {
5763
5764       // If there's no pointer operand, there's nothing to do.
5765       auto *Ptr = dyn_cast_or_null<Instruction>(getPointerOperand(&I));
5766       if (!Ptr)
5767         continue;
5768
5769       // True if all users of Ptr are memory accesses that have Ptr as their
5770       // pointer operand.
5771       auto UsersAreMemAccesses = all_of(Ptr->users(), [&](User *U) -> bool {
5772         return getPointerOperand(U) == Ptr;
5773       });
5774
5775       // Ensure the memory instruction will not be scalarized or used by
5776       // gather/scatter, making its pointer operand non-uniform. If the pointer
5777       // operand is used by any instruction other than a memory access, we
5778       // conservatively assume the pointer operand may be non-uniform.
5779       if (!UsersAreMemAccesses || !isUniformDecision(&I, VF))
5780         PossibleNonUniformPtrs.insert(Ptr);
5781
5782       // If the memory instruction will be vectorized and its pointer operand
5783       // is consecutive-like, or interleaving - the pointer operand should
5784       // remain uniform.
5785       else
5786         ConsecutiveLikePtrs.insert(Ptr);
5787     }
5788
5789   // Add to the Worklist all consecutive and consecutive-like pointers that
5790   // aren't also identified as possibly non-uniform.
5791   for (auto *V : ConsecutiveLikePtrs)
5792     if (!PossibleNonUniformPtrs.count(V)) {
5793       DEBUG(dbgs() << "LV: Found uniform instruction: " << *V << "\n");
5794       Worklist.insert(V);
5795     }
5796
5797   // Expand Worklist in topological order: whenever a new instruction
5798   // is added , its users should be either already inside Worklist, or
5799   // out of scope. It ensures a uniform instruction will only be used
5800   // by uniform instructions or out of scope instructions.
5801   unsigned idx = 0;
5802   while (idx != Worklist.size()) {
5803     Instruction *I = Worklist[idx++];
5804
5805     for (auto OV : I->operand_values()) {
5806       if (isOutOfScope(OV))
5807         continue;
5808       auto *OI = cast<Instruction>(OV);
5809       if (all_of(OI->users(), [&](User *U) -> bool {
5810             auto *J = cast<Instruction>(U);
5811             return !TheLoop->contains(J) || Worklist.count(J) ||
5812                    (OI == getPointerOperand(J) && isUniformDecision(J, VF));
5813           })) {
5814         Worklist.insert(OI);
5815         DEBUG(dbgs() << "LV: Found uniform instruction: " << *OI << "\n");
5816       }
5817     }
5818   }
5819
5820   // Returns true if Ptr is the pointer operand of a memory access instruction
5821   // I, and I is known to not require scalarization.
5822   auto isVectorizedMemAccessUse = [&](Instruction *I, Value *Ptr) -> bool {
5823     return getPointerOperand(I) == Ptr && isUniformDecision(I, VF);
5824   };
5825
5826   // For an instruction to be added into Worklist above, all its users inside
5827   // the loop should also be in Worklist. However, this condition cannot be
5828   // true for phi nodes that form a cyclic dependence. We must process phi
5829   // nodes separately. An induction variable will remain uniform if all users
5830   // of the induction variable and induction variable update remain uniform.
5831   // The code below handles both pointer and non-pointer induction variables.
5832   for (auto &Induction : *Legal->getInductionVars()) {
5833     auto *Ind = Induction.first;
5834     auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
5835
5836     // Determine if all users of the induction variable are uniform after
5837     // vectorization.
5838     auto UniformInd = all_of(Ind->users(), [&](User *U) -> bool {
5839       auto *I = cast<Instruction>(U);
5840       return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) ||
5841              isVectorizedMemAccessUse(I, Ind);
5842     });
5843     if (!UniformInd)
5844       continue;
5845
5846     // Determine if all users of the induction variable update instruction are
5847     // uniform after vectorization.
5848     auto UniformIndUpdate = all_of(IndUpdate->users(), [&](User *U) -> bool {
5849       auto *I = cast<Instruction>(U);
5850       return I == Ind || !TheLoop->contains(I) || Worklist.count(I) ||
5851              isVectorizedMemAccessUse(I, IndUpdate);
5852     });
5853     if (!UniformIndUpdate)
5854       continue;
5855
5856     // The induction variable and its update instruction will remain uniform.
5857     Worklist.insert(Ind);
5858     Worklist.insert(IndUpdate);
5859     DEBUG(dbgs() << "LV: Found uniform instruction: " << *Ind << "\n");
5860     DEBUG(dbgs() << "LV: Found uniform instruction: " << *IndUpdate << "\n");
5861   }
5862
5863   Uniforms[VF].insert(Worklist.begin(), Worklist.end());
5864 }
5865
5866 bool LoopVectorizationLegality::canVectorizeMemory() {
5867   LAI = &(*GetLAA)(*TheLoop);
5868   InterleaveInfo.setLAI(LAI);
5869   const OptimizationRemarkAnalysis *LAR = LAI->getReport();
5870   if (LAR) {
5871     OptimizationRemarkAnalysis VR(Hints->vectorizeAnalysisPassName(),
5872                                   "loop not vectorized: ", *LAR);
5873     ORE->emit(VR);
5874   }
5875   if (!LAI->canVectorizeMemory())
5876     return false;
5877
5878   if (LAI->hasStoreToLoopInvariantAddress()) {
5879     ORE->emit(createMissedAnalysis("CantVectorizeStoreToLoopInvariantAddress")
5880               << "write to a loop invariant address could not be vectorized");
5881     DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
5882     return false;
5883   }
5884
5885   Requirements->addRuntimePointerChecks(LAI->getNumRuntimePointerChecks());
5886   PSE.addPredicate(LAI->getPSE().getUnionPredicate());
5887
5888   return true;
5889 }
5890
5891 bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
5892   Value *In0 = const_cast<Value *>(V);
5893   PHINode *PN = dyn_cast_or_null<PHINode>(In0);
5894   if (!PN)
5895     return false;
5896
5897   return Inductions.count(PN);
5898 }
5899
5900 bool LoopVectorizationLegality::isFirstOrderRecurrence(const PHINode *Phi) {
5901   return FirstOrderRecurrences.count(Phi);
5902 }
5903
5904 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) {
5905   return LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT);
5906 }
5907
5908 bool LoopVectorizationLegality::blockCanBePredicated(
5909     BasicBlock *BB, SmallPtrSetImpl<Value *> &SafePtrs) {
5910   const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
5911
5912   for (Instruction &I : *BB) {
5913     // Check that we don't have a constant expression that can trap as operand.
5914     for (Value *Operand : I.operands()) {
5915       if (auto *C = dyn_cast<Constant>(Operand))
5916         if (C->canTrap())
5917           return false;
5918     }
5919     // We might be able to hoist the load.
5920     if (I.mayReadFromMemory()) {
5921       auto *LI = dyn_cast<LoadInst>(&I);
5922       if (!LI)
5923         return false;
5924       if (!SafePtrs.count(LI->getPointerOperand())) {
5925         if (isLegalMaskedLoad(LI->getType(), LI->getPointerOperand()) ||
5926             isLegalMaskedGather(LI->getType())) {
5927           MaskedOp.insert(LI);
5928           continue;
5929         }
5930         // !llvm.mem.parallel_loop_access implies if-conversion safety.
5931         if (IsAnnotatedParallel)
5932           continue;
5933         return false;
5934       }
5935     }
5936
5937     if (I.mayWriteToMemory()) {
5938       auto *SI = dyn_cast<StoreInst>(&I);
5939       // We only support predication of stores in basic blocks with one
5940       // predecessor.
5941       if (!SI)
5942         return false;
5943
5944       // Build a masked store if it is legal for the target.
5945       if (isLegalMaskedStore(SI->getValueOperand()->getType(),
5946                              SI->getPointerOperand()) ||
5947           isLegalMaskedScatter(SI->getValueOperand()->getType())) {
5948         MaskedOp.insert(SI);
5949         continue;
5950       }
5951
5952       bool isSafePtr = (SafePtrs.count(SI->getPointerOperand()) != 0);
5953       bool isSinglePredecessor = SI->getParent()->getSinglePredecessor();
5954
5955       if (++NumPredStores > NumberOfStoresToPredicate || !isSafePtr ||
5956           !isSinglePredecessor)
5957         return false;
5958     }
5959     if (I.mayThrow())
5960       return false;
5961   }
5962
5963   return true;
5964 }
5965
5966 void InterleavedAccessInfo::collectConstStrideAccesses(
5967     MapVector<Instruction *, StrideDescriptor> &AccessStrideInfo,
5968     const ValueToValueMap &Strides) {
5969
5970   auto &DL = TheLoop->getHeader()->getModule()->getDataLayout();
5971
5972   // Since it's desired that the load/store instructions be maintained in
5973   // "program order" for the interleaved access analysis, we have to visit the
5974   // blocks in the loop in reverse postorder (i.e., in a topological order).
5975   // Such an ordering will ensure that any load/store that may be executed
5976   // before a second load/store will precede the second load/store in
5977   // AccessStrideInfo.
5978   LoopBlocksDFS DFS(TheLoop);
5979   DFS.perform(LI);
5980   for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO()))
5981     for (auto &I : *BB) {
5982       auto *LI = dyn_cast<LoadInst>(&I);
5983       auto *SI = dyn_cast<StoreInst>(&I);
5984       if (!LI && !SI)
5985         continue;
5986
5987       Value *Ptr = getPointerOperand(&I);
5988       // We don't check wrapping here because we don't know yet if Ptr will be 
5989       // part of a full group or a group with gaps. Checking wrapping for all 
5990       // pointers (even those that end up in groups with no gaps) will be overly
5991       // conservative. For full groups, wrapping should be ok since if we would 
5992       // wrap around the address space we would do a memory access at nullptr
5993       // even without the transformation. The wrapping checks are therefore
5994       // deferred until after we've formed the interleaved groups.
5995       int64_t Stride = getPtrStride(PSE, Ptr, TheLoop, Strides,
5996                                     /*Assume=*/true, /*ShouldCheckWrap=*/false);
5997
5998       const SCEV *Scev = replaceSymbolicStrideSCEV(PSE, Strides, Ptr);
5999       PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType());
6000       uint64_t Size = DL.getTypeAllocSize(PtrTy->getElementType());
6001
6002       // An alignment of 0 means target ABI alignment.
6003       unsigned Align = getMemInstAlignment(&I);
6004       if (!Align)
6005         Align = DL.getABITypeAlignment(PtrTy->getElementType());
6006
6007       AccessStrideInfo[&I] = StrideDescriptor(Stride, Scev, Size, Align);
6008     }
6009 }
6010
6011 // Analyze interleaved accesses and collect them into interleaved load and
6012 // store groups.
6013 //
6014 // When generating code for an interleaved load group, we effectively hoist all
6015 // loads in the group to the location of the first load in program order. When
6016 // generating code for an interleaved store group, we sink all stores to the
6017 // location of the last store. This code motion can change the order of load
6018 // and store instructions and may break dependences.
6019 //
6020 // The code generation strategy mentioned above ensures that we won't violate
6021 // any write-after-read (WAR) dependences.
6022 //
6023 // E.g., for the WAR dependence:  a = A[i];      // (1)
6024 //                                A[i] = b;      // (2)
6025 //
6026 // The store group of (2) is always inserted at or below (2), and the load
6027 // group of (1) is always inserted at or above (1). Thus, the instructions will
6028 // never be reordered. All other dependences are checked to ensure the
6029 // correctness of the instruction reordering.
6030 //
6031 // The algorithm visits all memory accesses in the loop in bottom-up program
6032 // order. Program order is established by traversing the blocks in the loop in
6033 // reverse postorder when collecting the accesses.
6034 //
6035 // We visit the memory accesses in bottom-up order because it can simplify the
6036 // construction of store groups in the presence of write-after-write (WAW)
6037 // dependences.
6038 //
6039 // E.g., for the WAW dependence:  A[i] = a;      // (1)
6040 //                                A[i] = b;      // (2)
6041 //                                A[i + 1] = c;  // (3)
6042 //
6043 // We will first create a store group with (3) and (2). (1) can't be added to
6044 // this group because it and (2) are dependent. However, (1) can be grouped
6045 // with other accesses that may precede it in program order. Note that a
6046 // bottom-up order does not imply that WAW dependences should not be checked.
6047 void InterleavedAccessInfo::analyzeInterleaving(
6048     const ValueToValueMap &Strides) {
6049   DEBUG(dbgs() << "LV: Analyzing interleaved accesses...\n");
6050
6051   // Holds all accesses with a constant stride.
6052   MapVector<Instruction *, StrideDescriptor> AccessStrideInfo;
6053   collectConstStrideAccesses(AccessStrideInfo, Strides);
6054
6055   if (AccessStrideInfo.empty())
6056     return;
6057
6058   // Collect the dependences in the loop.
6059   collectDependences();
6060
6061   // Holds all interleaved store groups temporarily.
6062   SmallSetVector<InterleaveGroup *, 4> StoreGroups;
6063   // Holds all interleaved load groups temporarily.
6064   SmallSetVector<InterleaveGroup *, 4> LoadGroups;
6065
6066   // Search in bottom-up program order for pairs of accesses (A and B) that can
6067   // form interleaved load or store groups. In the algorithm below, access A
6068   // precedes access B in program order. We initialize a group for B in the
6069   // outer loop of the algorithm, and then in the inner loop, we attempt to
6070   // insert each A into B's group if:
6071   //
6072   //  1. A and B have the same stride,
6073   //  2. A and B have the same memory object size, and
6074   //  3. A belongs in B's group according to its distance from B.
6075   //
6076   // Special care is taken to ensure group formation will not break any
6077   // dependences.
6078   for (auto BI = AccessStrideInfo.rbegin(), E = AccessStrideInfo.rend();
6079        BI != E; ++BI) {
6080     Instruction *B = BI->first;
6081     StrideDescriptor DesB = BI->second;
6082
6083     // Initialize a group for B if it has an allowable stride. Even if we don't
6084     // create a group for B, we continue with the bottom-up algorithm to ensure
6085     // we don't break any of B's dependences.
6086     InterleaveGroup *Group = nullptr;
6087     if (isStrided(DesB.Stride)) {
6088       Group = getInterleaveGroup(B);
6089       if (!Group) {
6090         DEBUG(dbgs() << "LV: Creating an interleave group with:" << *B << '\n');
6091         Group = createInterleaveGroup(B, DesB.Stride, DesB.Align);
6092       }
6093       if (B->mayWriteToMemory())
6094         StoreGroups.insert(Group);
6095       else
6096         LoadGroups.insert(Group);
6097     }
6098
6099     for (auto AI = std::next(BI); AI != E; ++AI) {
6100       Instruction *A = AI->first;
6101       StrideDescriptor DesA = AI->second;
6102
6103       // Our code motion strategy implies that we can't have dependences
6104       // between accesses in an interleaved group and other accesses located
6105       // between the first and last member of the group. Note that this also
6106       // means that a group can't have more than one member at a given offset.
6107       // The accesses in a group can have dependences with other accesses, but
6108       // we must ensure we don't extend the boundaries of the group such that
6109       // we encompass those dependent accesses.
6110       //
6111       // For example, assume we have the sequence of accesses shown below in a
6112       // stride-2 loop:
6113       //
6114       //  (1, 2) is a group | A[i]   = a;  // (1)
6115       //                    | A[i-1] = b;  // (2) |
6116       //                      A[i-3] = c;  // (3)
6117       //                      A[i]   = d;  // (4) | (2, 4) is not a group
6118       //
6119       // Because accesses (2) and (3) are dependent, we can group (2) with (1)
6120       // but not with (4). If we did, the dependent access (3) would be within
6121       // the boundaries of the (2, 4) group.
6122       if (!canReorderMemAccessesForInterleavedGroups(&*AI, &*BI)) {
6123
6124         // If a dependence exists and A is already in a group, we know that A
6125         // must be a store since A precedes B and WAR dependences are allowed.
6126         // Thus, A would be sunk below B. We release A's group to prevent this
6127         // illegal code motion. A will then be free to form another group with
6128         // instructions that precede it.
6129         if (isInterleaved(A)) {
6130           InterleaveGroup *StoreGroup = getInterleaveGroup(A);
6131           StoreGroups.remove(StoreGroup);
6132           releaseGroup(StoreGroup);
6133         }
6134
6135         // If a dependence exists and A is not already in a group (or it was
6136         // and we just released it), B might be hoisted above A (if B is a
6137         // load) or another store might be sunk below A (if B is a store). In
6138         // either case, we can't add additional instructions to B's group. B
6139         // will only form a group with instructions that it precedes.
6140         break;
6141       }
6142
6143       // At this point, we've checked for illegal code motion. If either A or B
6144       // isn't strided, there's nothing left to do.
6145       if (!isStrided(DesA.Stride) || !isStrided(DesB.Stride))
6146         continue;
6147
6148       // Ignore A if it's already in a group or isn't the same kind of memory
6149       // operation as B.
6150       if (isInterleaved(A) || A->mayReadFromMemory() != B->mayReadFromMemory())
6151         continue;
6152
6153       // Check rules 1 and 2. Ignore A if its stride or size is different from
6154       // that of B.
6155       if (DesA.Stride != DesB.Stride || DesA.Size != DesB.Size)
6156         continue;
6157
6158       // Ignore A if the memory object of A and B don't belong to the same
6159       // address space
6160       if (getMemInstAddressSpace(A) != getMemInstAddressSpace(B))
6161         continue;
6162
6163       // Calculate the distance from A to B.
6164       const SCEVConstant *DistToB = dyn_cast<SCEVConstant>(
6165           PSE.getSE()->getMinusSCEV(DesA.Scev, DesB.Scev));
6166       if (!DistToB)
6167         continue;
6168       int64_t DistanceToB = DistToB->getAPInt().getSExtValue();
6169
6170       // Check rule 3. Ignore A if its distance to B is not a multiple of the
6171       // size.
6172       if (DistanceToB % static_cast<int64_t>(DesB.Size))
6173         continue;
6174
6175       // Ignore A if either A or B is in a predicated block. Although we
6176       // currently prevent group formation for predicated accesses, we may be
6177       // able to relax this limitation in the future once we handle more
6178       // complicated blocks.
6179       if (isPredicated(A->getParent()) || isPredicated(B->getParent()))
6180         continue;
6181
6182       // The index of A is the index of B plus A's distance to B in multiples
6183       // of the size.
6184       int IndexA =
6185           Group->getIndex(B) + DistanceToB / static_cast<int64_t>(DesB.Size);
6186
6187       // Try to insert A into B's group.
6188       if (Group->insertMember(A, IndexA, DesA.Align)) {
6189         DEBUG(dbgs() << "LV: Inserted:" << *A << '\n'
6190                      << "    into the interleave group with" << *B << '\n');
6191         InterleaveGroupMap[A] = Group;
6192
6193         // Set the first load in program order as the insert position.
6194         if (A->mayReadFromMemory())
6195           Group->setInsertPos(A);
6196       }
6197     } // Iteration over A accesses.
6198   } // Iteration over B accesses.
6199
6200   // Remove interleaved store groups with gaps.
6201   for (InterleaveGroup *Group : StoreGroups)
6202     if (Group->getNumMembers() != Group->getFactor())
6203       releaseGroup(Group);
6204
6205   // Remove interleaved groups with gaps (currently only loads) whose memory
6206   // accesses may wrap around. We have to revisit the getPtrStride analysis,
6207   // this time with ShouldCheckWrap=true, since collectConstStrideAccesses does
6208   // not check wrapping (see documentation there).
6209   // FORNOW we use Assume=false;
6210   // TODO: Change to Assume=true but making sure we don't exceed the threshold
6211   // of runtime SCEV assumptions checks (thereby potentially failing to
6212   // vectorize altogether).
6213   // Additional optional optimizations:
6214   // TODO: If we are peeling the loop and we know that the first pointer doesn't
6215   // wrap then we can deduce that all pointers in the group don't wrap.
6216   // This means that we can forcefully peel the loop in order to only have to
6217   // check the first pointer for no-wrap. When we'll change to use Assume=true
6218   // we'll only need at most one runtime check per interleaved group.
6219   //
6220   for (InterleaveGroup *Group : LoadGroups) {
6221
6222     // Case 1: A full group. Can Skip the checks; For full groups, if the wide
6223     // load would wrap around the address space we would do a memory access at
6224     // nullptr even without the transformation.
6225     if (Group->getNumMembers() == Group->getFactor())
6226       continue;
6227
6228     // Case 2: If first and last members of the group don't wrap this implies
6229     // that all the pointers in the group don't wrap.
6230     // So we check only group member 0 (which is always guaranteed to exist),
6231     // and group member Factor - 1; If the latter doesn't exist we rely on
6232     // peeling (if it is a non-reveresed accsess -- see Case 3).
6233     Value *FirstMemberPtr = getPointerOperand(Group->getMember(0));
6234     if (!getPtrStride(PSE, FirstMemberPtr, TheLoop, Strides, /*Assume=*/false,
6235                       /*ShouldCheckWrap=*/true)) {
6236       DEBUG(dbgs() << "LV: Invalidate candidate interleaved group due to "
6237                       "first group member potentially pointer-wrapping.\n");
6238       releaseGroup(Group);
6239       continue;
6240     }
6241     Instruction *LastMember = Group->getMember(Group->getFactor() - 1);
6242     if (LastMember) {
6243       Value *LastMemberPtr = getPointerOperand(LastMember);
6244       if (!getPtrStride(PSE, LastMemberPtr, TheLoop, Strides, /*Assume=*/false, 
6245                         /*ShouldCheckWrap=*/true)) {
6246         DEBUG(dbgs() << "LV: Invalidate candidate interleaved group due to "
6247                         "last group member potentially pointer-wrapping.\n");
6248         releaseGroup(Group);
6249       }
6250     } else {
6251       // Case 3: A non-reversed interleaved load group with gaps: We need
6252       // to execute at least one scalar epilogue iteration. This will ensure 
6253       // we don't speculatively access memory out-of-bounds. We only need
6254       // to look for a member at index factor - 1, since every group must have 
6255       // a member at index zero.
6256       if (Group->isReverse()) {
6257         releaseGroup(Group);
6258         continue;
6259       }
6260       DEBUG(dbgs() << "LV: Interleaved group requires epilogue iteration.\n");
6261       RequiresScalarEpilogue = true;
6262     }
6263   }
6264 }
6265
6266 Optional<unsigned> LoopVectorizationCostModel::computeMaxVF(bool OptForSize) {
6267   if (!EnableCondStoresVectorization && Legal->getNumPredStores()) {
6268     ORE->emit(createMissedAnalysis("ConditionalStore")
6269               << "store that is conditionally executed prevents vectorization");
6270     DEBUG(dbgs() << "LV: No vectorization. There are conditional stores.\n");
6271     return None;
6272   }
6273
6274   if (!OptForSize) // Remaining checks deal with scalar loop when OptForSize.
6275     return computeFeasibleMaxVF(OptForSize);
6276
6277   if (Legal->getRuntimePointerChecking()->Need) {
6278     ORE->emit(createMissedAnalysis("CantVersionLoopWithOptForSize")
6279               << "runtime pointer checks needed. Enable vectorization of this "
6280                  "loop with '#pragma clang loop vectorize(enable)' when "
6281                  "compiling with -Os/-Oz");
6282     DEBUG(dbgs()
6283           << "LV: Aborting. Runtime ptr check is required with -Os/-Oz.\n");
6284     return None;
6285   }
6286
6287   // If we optimize the program for size, avoid creating the tail loop.
6288   unsigned TC = PSE.getSE()->getSmallConstantTripCount(TheLoop);
6289   DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
6290
6291   // If we don't know the precise trip count, don't try to vectorize.
6292   if (TC < 2) {
6293     ORE->emit(
6294         createMissedAnalysis("UnknownLoopCountComplexCFG")
6295         << "unable to calculate the loop count due to complex control flow");
6296     DEBUG(dbgs() << "LV: Aborting. A tail loop is required with -Os/-Oz.\n");
6297     return None;
6298   }
6299
6300   unsigned MaxVF = computeFeasibleMaxVF(OptForSize);
6301
6302   if (TC % MaxVF != 0) {
6303     // If the trip count that we found modulo the vectorization factor is not
6304     // zero then we require a tail.
6305     // FIXME: look for a smaller MaxVF that does divide TC rather than give up.
6306     // FIXME: return None if loop requiresScalarEpilog(<MaxVF>), or look for a
6307     //        smaller MaxVF that does not require a scalar epilog.
6308
6309     ORE->emit(createMissedAnalysis("NoTailLoopWithOptForSize")
6310               << "cannot optimize for size and vectorize at the "
6311                  "same time. Enable vectorization of this loop "
6312                  "with '#pragma clang loop vectorize(enable)' "
6313                  "when compiling with -Os/-Oz");
6314     DEBUG(dbgs() << "LV: Aborting. A tail loop is required with -Os/-Oz.\n");
6315     return None;
6316   }
6317
6318   return MaxVF;
6319 }
6320
6321 unsigned LoopVectorizationCostModel::computeFeasibleMaxVF(bool OptForSize) {
6322   MinBWs = computeMinimumValueSizes(TheLoop->getBlocks(), *DB, &TTI);
6323   unsigned SmallestType, WidestType;
6324   std::tie(SmallestType, WidestType) = getSmallestAndWidestTypes();
6325   unsigned WidestRegister = TTI.getRegisterBitWidth(true);
6326   unsigned MaxSafeDepDist = -1U;
6327
6328   // Get the maximum safe dependence distance in bits computed by LAA. If the
6329   // loop contains any interleaved accesses, we divide the dependence distance
6330   // by the maximum interleave factor of all interleaved groups. Note that
6331   // although the division ensures correctness, this is a fairly conservative
6332   // computation because the maximum distance computed by LAA may not involve
6333   // any of the interleaved accesses.
6334   if (Legal->getMaxSafeDepDistBytes() != -1U)
6335     MaxSafeDepDist =
6336         Legal->getMaxSafeDepDistBytes() * 8 / Legal->getMaxInterleaveFactor();
6337
6338   WidestRegister =
6339       ((WidestRegister < MaxSafeDepDist) ? WidestRegister : MaxSafeDepDist);
6340   unsigned MaxVectorSize = WidestRegister / WidestType;
6341
6342   DEBUG(dbgs() << "LV: The Smallest and Widest types: " << SmallestType << " / "
6343                << WidestType << " bits.\n");
6344   DEBUG(dbgs() << "LV: The Widest register is: " << WidestRegister
6345                << " bits.\n");
6346
6347   if (MaxVectorSize == 0) {
6348     DEBUG(dbgs() << "LV: The target has no vector registers.\n");
6349     MaxVectorSize = 1;
6350   }
6351
6352   assert(MaxVectorSize <= 64 && "Did not expect to pack so many elements"
6353                                 " into one vector!");
6354
6355   unsigned MaxVF = MaxVectorSize;
6356   if (MaximizeBandwidth && !OptForSize) {
6357     // Collect all viable vectorization factors.
6358     SmallVector<unsigned, 8> VFs;
6359     unsigned NewMaxVectorSize = WidestRegister / SmallestType;
6360     for (unsigned VS = MaxVectorSize; VS <= NewMaxVectorSize; VS *= 2)
6361       VFs.push_back(VS);
6362
6363     // For each VF calculate its register usage.
6364     auto RUs = calculateRegisterUsage(VFs);
6365
6366     // Select the largest VF which doesn't require more registers than existing
6367     // ones.
6368     unsigned TargetNumRegisters = TTI.getNumberOfRegisters(true);
6369     for (int i = RUs.size() - 1; i >= 0; --i) {
6370       if (RUs[i].MaxLocalUsers <= TargetNumRegisters) {
6371         MaxVF = VFs[i];
6372         break;
6373       }
6374     }
6375   }
6376   return MaxVF;
6377 }
6378
6379 LoopVectorizationCostModel::VectorizationFactor
6380 LoopVectorizationCostModel::selectVectorizationFactor(unsigned MaxVF) {
6381   float Cost = expectedCost(1).first;
6382 #ifndef NDEBUG
6383   const float ScalarCost = Cost;
6384 #endif /* NDEBUG */
6385   unsigned Width = 1;
6386   DEBUG(dbgs() << "LV: Scalar loop costs: " << (int)ScalarCost << ".\n");
6387
6388   bool ForceVectorization = Hints->getForce() == LoopVectorizeHints::FK_Enabled;
6389   // Ignore scalar width, because the user explicitly wants vectorization.
6390   if (ForceVectorization && MaxVF > 1) {
6391     Width = 2;
6392     Cost = expectedCost(Width).first / (float)Width;
6393   }
6394
6395   for (unsigned i = 2; i <= MaxVF; i *= 2) {
6396     // Notice that the vector loop needs to be executed less times, so
6397     // we need to divide the cost of the vector loops by the width of
6398     // the vector elements.
6399     VectorizationCostTy C = expectedCost(i);
6400     float VectorCost = C.first / (float)i;
6401     DEBUG(dbgs() << "LV: Vector loop of width " << i
6402                  << " costs: " << (int)VectorCost << ".\n");
6403     if (!C.second && !ForceVectorization) {
6404       DEBUG(
6405           dbgs() << "LV: Not considering vector loop of width " << i
6406                  << " because it will not generate any vector instructions.\n");
6407       continue;
6408     }
6409     if (VectorCost < Cost) {
6410       Cost = VectorCost;
6411       Width = i;
6412     }
6413   }
6414
6415   DEBUG(if (ForceVectorization && Width > 1 && Cost >= ScalarCost) dbgs()
6416         << "LV: Vectorization seems to be not beneficial, "
6417         << "but was forced by a user.\n");
6418   DEBUG(dbgs() << "LV: Selecting VF: " << Width << ".\n");
6419   VectorizationFactor Factor = {Width, (unsigned)(Width * Cost)};
6420   return Factor;
6421 }
6422
6423 std::pair<unsigned, unsigned>
6424 LoopVectorizationCostModel::getSmallestAndWidestTypes() {
6425   unsigned MinWidth = -1U;
6426   unsigned MaxWidth = 8;
6427   const DataLayout &DL = TheFunction->getParent()->getDataLayout();
6428
6429   // For each block.
6430   for (BasicBlock *BB : TheLoop->blocks()) {
6431     // For each instruction in the loop.
6432     for (Instruction &I : *BB) {
6433       Type *T = I.getType();
6434
6435       // Skip ignored values.
6436       if (ValuesToIgnore.count(&I))
6437         continue;
6438
6439       // Only examine Loads, Stores and PHINodes.
6440       if (!isa<LoadInst>(I) && !isa<StoreInst>(I) && !isa<PHINode>(I))
6441         continue;
6442
6443       // Examine PHI nodes that are reduction variables. Update the type to
6444       // account for the recurrence type.
6445       if (auto *PN = dyn_cast<PHINode>(&I)) {
6446         if (!Legal->isReductionVariable(PN))
6447           continue;
6448         RecurrenceDescriptor RdxDesc = (*Legal->getReductionVars())[PN];
6449         T = RdxDesc.getRecurrenceType();
6450       }
6451
6452       // Examine the stored values.
6453       if (auto *ST = dyn_cast<StoreInst>(&I))
6454         T = ST->getValueOperand()->getType();
6455
6456       // Ignore loaded pointer types and stored pointer types that are not
6457       // vectorizable.
6458       //
6459       // FIXME: The check here attempts to predict whether a load or store will
6460       //        be vectorized. We only know this for certain after a VF has
6461       //        been selected. Here, we assume that if an access can be
6462       //        vectorized, it will be. We should also look at extending this
6463       //        optimization to non-pointer types.
6464       //
6465       if (T->isPointerTy() && !isConsecutiveLoadOrStore(&I) &&
6466           !Legal->isAccessInterleaved(&I) && !Legal->isLegalGatherOrScatter(&I))
6467         continue;
6468
6469       MinWidth = std::min(MinWidth,
6470                           (unsigned)DL.getTypeSizeInBits(T->getScalarType()));
6471       MaxWidth = std::max(MaxWidth,
6472                           (unsigned)DL.getTypeSizeInBits(T->getScalarType()));
6473     }
6474   }
6475
6476   return {MinWidth, MaxWidth};
6477 }
6478
6479 unsigned LoopVectorizationCostModel::selectInterleaveCount(bool OptForSize,
6480                                                            unsigned VF,
6481                                                            unsigned LoopCost) {
6482
6483   // -- The interleave heuristics --
6484   // We interleave the loop in order to expose ILP and reduce the loop overhead.
6485   // There are many micro-architectural considerations that we can't predict
6486   // at this level. For example, frontend pressure (on decode or fetch) due to
6487   // code size, or the number and capabilities of the execution ports.
6488   //
6489   // We use the following heuristics to select the interleave count:
6490   // 1. If the code has reductions, then we interleave to break the cross
6491   // iteration dependency.
6492   // 2. If the loop is really small, then we interleave to reduce the loop
6493   // overhead.
6494   // 3. We don't interleave if we think that we will spill registers to memory
6495   // due to the increased register pressure.
6496
6497   // When we optimize for size, we don't interleave.
6498   if (OptForSize)
6499     return 1;
6500
6501   // We used the distance for the interleave count.
6502   if (Legal->getMaxSafeDepDistBytes() != -1U)
6503     return 1;
6504
6505   // Do not interleave loops with a relatively small trip count.
6506   unsigned TC = PSE.getSE()->getSmallConstantTripCount(TheLoop);
6507   if (TC > 1 && TC < TinyTripCountInterleaveThreshold)
6508     return 1;
6509
6510   unsigned TargetNumRegisters = TTI.getNumberOfRegisters(VF > 1);
6511   DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters
6512                << " registers\n");
6513
6514   if (VF == 1) {
6515     if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
6516       TargetNumRegisters = ForceTargetNumScalarRegs;
6517   } else {
6518     if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
6519       TargetNumRegisters = ForceTargetNumVectorRegs;
6520   }
6521
6522   RegisterUsage R = calculateRegisterUsage({VF})[0];
6523   // We divide by these constants so assume that we have at least one
6524   // instruction that uses at least one register.
6525   R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
6526   R.NumInstructions = std::max(R.NumInstructions, 1U);
6527
6528   // We calculate the interleave count using the following formula.
6529   // Subtract the number of loop invariants from the number of available
6530   // registers. These registers are used by all of the interleaved instances.
6531   // Next, divide the remaining registers by the number of registers that is
6532   // required by the loop, in order to estimate how many parallel instances
6533   // fit without causing spills. All of this is rounded down if necessary to be
6534   // a power of two. We want power of two interleave count to simplify any
6535   // addressing operations or alignment considerations.
6536   unsigned IC = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs) /
6537                               R.MaxLocalUsers);
6538
6539   // Don't count the induction variable as interleaved.
6540   if (EnableIndVarRegisterHeur)
6541     IC = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs - 1) /
6542                        std::max(1U, (R.MaxLocalUsers - 1)));
6543
6544   // Clamp the interleave ranges to reasonable counts.
6545   unsigned MaxInterleaveCount = TTI.getMaxInterleaveFactor(VF);
6546
6547   // Check if the user has overridden the max.
6548   if (VF == 1) {
6549     if (ForceTargetMaxScalarInterleaveFactor.getNumOccurrences() > 0)
6550       MaxInterleaveCount = ForceTargetMaxScalarInterleaveFactor;
6551   } else {
6552     if (ForceTargetMaxVectorInterleaveFactor.getNumOccurrences() > 0)
6553       MaxInterleaveCount = ForceTargetMaxVectorInterleaveFactor;
6554   }
6555
6556   // If we did not calculate the cost for VF (because the user selected the VF)
6557   // then we calculate the cost of VF here.
6558   if (LoopCost == 0)
6559     LoopCost = expectedCost(VF).first;
6560
6561   // Clamp the calculated IC to be between the 1 and the max interleave count
6562   // that the target allows.
6563   if (IC > MaxInterleaveCount)
6564     IC = MaxInterleaveCount;
6565   else if (IC < 1)
6566     IC = 1;
6567
6568   // Interleave if we vectorized this loop and there is a reduction that could
6569   // benefit from interleaving.
6570   if (VF > 1 && Legal->getReductionVars()->size()) {
6571     DEBUG(dbgs() << "LV: Interleaving because of reductions.\n");
6572     return IC;
6573   }
6574
6575   // Note that if we've already vectorized the loop we will have done the
6576   // runtime check and so interleaving won't require further checks.
6577   bool InterleavingRequiresRuntimePointerCheck =
6578       (VF == 1 && Legal->getRuntimePointerChecking()->Need);
6579
6580   // We want to interleave small loops in order to reduce the loop overhead and
6581   // potentially expose ILP opportunities.
6582   DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n');
6583   if (!InterleavingRequiresRuntimePointerCheck && LoopCost < SmallLoopCost) {
6584     // We assume that the cost overhead is 1 and we use the cost model
6585     // to estimate the cost of the loop and interleave until the cost of the
6586     // loop overhead is about 5% of the cost of the loop.
6587     unsigned SmallIC =
6588         std::min(IC, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost));
6589
6590     // Interleave until store/load ports (estimated by max interleave count) are
6591     // saturated.
6592     unsigned NumStores = Legal->getNumStores();
6593     unsigned NumLoads = Legal->getNumLoads();
6594     unsigned StoresIC = IC / (NumStores ? NumStores : 1);
6595     unsigned LoadsIC = IC / (NumLoads ? NumLoads : 1);
6596
6597     // If we have a scalar reduction (vector reductions are already dealt with
6598     // by this point), we can increase the critical path length if the loop
6599     // we're interleaving is inside another loop. Limit, by default to 2, so the
6600     // critical path only gets increased by one reduction operation.
6601     if (Legal->getReductionVars()->size() && TheLoop->getLoopDepth() > 1) {
6602       unsigned F = static_cast<unsigned>(MaxNestedScalarReductionIC);
6603       SmallIC = std::min(SmallIC, F);
6604       StoresIC = std::min(StoresIC, F);
6605       LoadsIC = std::min(LoadsIC, F);
6606     }
6607
6608     if (EnableLoadStoreRuntimeInterleave &&
6609         std::max(StoresIC, LoadsIC) > SmallIC) {
6610       DEBUG(dbgs() << "LV: Interleaving to saturate store or load ports.\n");
6611       return std::max(StoresIC, LoadsIC);
6612     }
6613
6614     DEBUG(dbgs() << "LV: Interleaving to reduce branch cost.\n");
6615     return SmallIC;
6616   }
6617
6618   // Interleave if this is a large loop (small loops are already dealt with by
6619   // this point) that could benefit from interleaving.
6620   bool HasReductions = (Legal->getReductionVars()->size() > 0);
6621   if (TTI.enableAggressiveInterleaving(HasReductions)) {
6622     DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
6623     return IC;
6624   }
6625
6626   DEBUG(dbgs() << "LV: Not Interleaving.\n");
6627   return 1;
6628 }
6629
6630 SmallVector<LoopVectorizationCostModel::RegisterUsage, 8>
6631 LoopVectorizationCostModel::calculateRegisterUsage(ArrayRef<unsigned> VFs) {
6632   // This function calculates the register usage by measuring the highest number
6633   // of values that are alive at a single location. Obviously, this is a very
6634   // rough estimation. We scan the loop in a topological order in order and
6635   // assign a number to each instruction. We use RPO to ensure that defs are
6636   // met before their users. We assume that each instruction that has in-loop
6637   // users starts an interval. We record every time that an in-loop value is
6638   // used, so we have a list of the first and last occurrences of each
6639   // instruction. Next, we transpose this data structure into a multi map that
6640   // holds the list of intervals that *end* at a specific location. This multi
6641   // map allows us to perform a linear search. We scan the instructions linearly
6642   // and record each time that a new interval starts, by placing it in a set.
6643   // If we find this value in the multi-map then we remove it from the set.
6644   // The max register usage is the maximum size of the set.
6645   // We also search for instructions that are defined outside the loop, but are
6646   // used inside the loop. We need this number separately from the max-interval
6647   // usage number because when we unroll, loop-invariant values do not take
6648   // more register.
6649   LoopBlocksDFS DFS(TheLoop);
6650   DFS.perform(LI);
6651
6652   RegisterUsage RU;
6653   RU.NumInstructions = 0;
6654
6655   // Each 'key' in the map opens a new interval. The values
6656   // of the map are the index of the 'last seen' usage of the
6657   // instruction that is the key.
6658   typedef DenseMap<Instruction *, unsigned> IntervalMap;
6659   // Maps instruction to its index.
6660   DenseMap<unsigned, Instruction *> IdxToInstr;
6661   // Marks the end of each interval.
6662   IntervalMap EndPoint;
6663   // Saves the list of instruction indices that are used in the loop.
6664   SmallSet<Instruction *, 8> Ends;
6665   // Saves the list of values that are used in the loop but are
6666   // defined outside the loop, such as arguments and constants.
6667   SmallPtrSet<Value *, 8> LoopInvariants;
6668
6669   unsigned Index = 0;
6670   for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) {
6671     RU.NumInstructions += BB->size();
6672     for (Instruction &I : *BB) {
6673       IdxToInstr[Index++] = &I;
6674
6675       // Save the end location of each USE.
6676       for (Value *U : I.operands()) {
6677         auto *Instr = dyn_cast<Instruction>(U);
6678
6679         // Ignore non-instruction values such as arguments, constants, etc.
6680         if (!Instr)
6681           continue;
6682
6683         // If this instruction is outside the loop then record it and continue.
6684         if (!TheLoop->contains(Instr)) {
6685           LoopInvariants.insert(Instr);
6686           continue;
6687         }
6688
6689         // Overwrite previous end points.
6690         EndPoint[Instr] = Index;
6691         Ends.insert(Instr);
6692       }
6693     }
6694   }
6695
6696   // Saves the list of intervals that end with the index in 'key'.
6697   typedef SmallVector<Instruction *, 2> InstrList;
6698   DenseMap<unsigned, InstrList> TransposeEnds;
6699
6700   // Transpose the EndPoints to a list of values that end at each index.
6701   for (auto &Interval : EndPoint)
6702     TransposeEnds[Interval.second].push_back(Interval.first);
6703
6704   SmallSet<Instruction *, 8> OpenIntervals;
6705
6706   // Get the size of the widest register.
6707   unsigned MaxSafeDepDist = -1U;
6708   if (Legal->getMaxSafeDepDistBytes() != -1U)
6709     MaxSafeDepDist = Legal->getMaxSafeDepDistBytes() * 8;
6710   unsigned WidestRegister =
6711       std::min(TTI.getRegisterBitWidth(true), MaxSafeDepDist);
6712   const DataLayout &DL = TheFunction->getParent()->getDataLayout();
6713
6714   SmallVector<RegisterUsage, 8> RUs(VFs.size());
6715   SmallVector<unsigned, 8> MaxUsages(VFs.size(), 0);
6716
6717   DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
6718
6719   // A lambda that gets the register usage for the given type and VF.
6720   auto GetRegUsage = [&DL, WidestRegister](Type *Ty, unsigned VF) {
6721     if (Ty->isTokenTy())
6722       return 0U;
6723     unsigned TypeSize = DL.getTypeSizeInBits(Ty->getScalarType());
6724     return std::max<unsigned>(1, VF * TypeSize / WidestRegister);
6725   };
6726
6727   for (unsigned int i = 0; i < Index; ++i) {
6728     Instruction *I = IdxToInstr[i];
6729
6730     // Remove all of the instructions that end at this location.
6731     InstrList &List = TransposeEnds[i];
6732     for (Instruction *ToRemove : List)
6733       OpenIntervals.erase(ToRemove);
6734
6735     // Ignore instructions that are never used within the loop.
6736     if (!Ends.count(I))
6737       continue;
6738
6739     // Skip ignored values.
6740     if (ValuesToIgnore.count(I))
6741       continue;
6742
6743     // For each VF find the maximum usage of registers.
6744     for (unsigned j = 0, e = VFs.size(); j < e; ++j) {
6745       if (VFs[j] == 1) {
6746         MaxUsages[j] = std::max(MaxUsages[j], OpenIntervals.size());
6747         continue;
6748       }
6749       collectUniformsAndScalars(VFs[j]);
6750       // Count the number of live intervals.
6751       unsigned RegUsage = 0;
6752       for (auto Inst : OpenIntervals) {
6753         // Skip ignored values for VF > 1.
6754         if (VecValuesToIgnore.count(Inst) ||
6755             isScalarAfterVectorization(Inst, VFs[j]))
6756           continue;
6757         RegUsage += GetRegUsage(Inst->getType(), VFs[j]);
6758       }
6759       MaxUsages[j] = std::max(MaxUsages[j], RegUsage);
6760     }
6761
6762     DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # "
6763                  << OpenIntervals.size() << '\n');
6764
6765     // Add the current instruction to the list of open intervals.
6766     OpenIntervals.insert(I);
6767   }
6768
6769   for (unsigned i = 0, e = VFs.size(); i < e; ++i) {
6770     unsigned Invariant = 0;
6771     if (VFs[i] == 1)
6772       Invariant = LoopInvariants.size();
6773     else {
6774       for (auto Inst : LoopInvariants)
6775         Invariant += GetRegUsage(Inst->getType(), VFs[i]);
6776     }
6777
6778     DEBUG(dbgs() << "LV(REG): VF = " << VFs[i] << '\n');
6779     DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsages[i] << '\n');
6780     DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << '\n');
6781     DEBUG(dbgs() << "LV(REG): LoopSize: " << RU.NumInstructions << '\n');
6782
6783     RU.LoopInvariantRegs = Invariant;
6784     RU.MaxLocalUsers = MaxUsages[i];
6785     RUs[i] = RU;
6786   }
6787
6788   return RUs;
6789 }
6790
6791 void LoopVectorizationCostModel::collectInstsToScalarize(unsigned VF) {
6792
6793   // If we aren't vectorizing the loop, or if we've already collected the
6794   // instructions to scalarize, there's nothing to do. Collection may already
6795   // have occurred if we have a user-selected VF and are now computing the
6796   // expected cost for interleaving.
6797   if (VF < 2 || InstsToScalarize.count(VF))
6798     return;
6799
6800   // Initialize a mapping for VF in InstsToScalalarize. If we find that it's
6801   // not profitable to scalarize any instructions, the presence of VF in the
6802   // map will indicate that we've analyzed it already.
6803   ScalarCostsTy &ScalarCostsVF = InstsToScalarize[VF];
6804
6805   // Find all the instructions that are scalar with predication in the loop and
6806   // determine if it would be better to not if-convert the blocks they are in.
6807   // If so, we also record the instructions to scalarize.
6808   for (BasicBlock *BB : TheLoop->blocks()) {
6809     if (!Legal->blockNeedsPredication(BB))
6810       continue;
6811     for (Instruction &I : *BB)
6812       if (Legal->isScalarWithPredication(&I)) {
6813         ScalarCostsTy ScalarCosts;
6814         if (computePredInstDiscount(&I, ScalarCosts, VF) >= 0)
6815           ScalarCostsVF.insert(ScalarCosts.begin(), ScalarCosts.end());
6816
6817         // Remember that BB will remain after vectorization.
6818         PredicatedBBsAfterVectorization.insert(BB);
6819       }
6820   }
6821 }
6822
6823 int LoopVectorizationCostModel::computePredInstDiscount(
6824     Instruction *PredInst, DenseMap<Instruction *, unsigned> &ScalarCosts,
6825     unsigned VF) {
6826
6827   assert(!isUniformAfterVectorization(PredInst, VF) &&
6828          "Instruction marked uniform-after-vectorization will be predicated");
6829
6830   // Initialize the discount to zero, meaning that the scalar version and the
6831   // vector version cost the same.
6832   int Discount = 0;
6833
6834   // Holds instructions to analyze. The instructions we visit are mapped in
6835   // ScalarCosts. Those instructions are the ones that would be scalarized if
6836   // we find that the scalar version costs less.
6837   SmallVector<Instruction *, 8> Worklist;
6838
6839   // Returns true if the given instruction can be scalarized.
6840   auto canBeScalarized = [&](Instruction *I) -> bool {
6841
6842     // We only attempt to scalarize instructions forming a single-use chain
6843     // from the original predicated block that would otherwise be vectorized.
6844     // Although not strictly necessary, we give up on instructions we know will
6845     // already be scalar to avoid traversing chains that are unlikely to be
6846     // beneficial.
6847     if (!I->hasOneUse() || PredInst->getParent() != I->getParent() ||
6848         isScalarAfterVectorization(I, VF))
6849       return false;
6850
6851     // If the instruction is scalar with predication, it will be analyzed
6852     // separately. We ignore it within the context of PredInst.
6853     if (Legal->isScalarWithPredication(I))
6854       return false;
6855
6856     // If any of the instruction's operands are uniform after vectorization,
6857     // the instruction cannot be scalarized. This prevents, for example, a
6858     // masked load from being scalarized.
6859     //
6860     // We assume we will only emit a value for lane zero of an instruction
6861     // marked uniform after vectorization, rather than VF identical values.
6862     // Thus, if we scalarize an instruction that uses a uniform, we would
6863     // create uses of values corresponding to the lanes we aren't emitting code
6864     // for. This behavior can be changed by allowing getScalarValue to clone
6865     // the lane zero values for uniforms rather than asserting.
6866     for (Use &U : I->operands())
6867       if (auto *J = dyn_cast<Instruction>(U.get()))
6868         if (isUniformAfterVectorization(J, VF))
6869           return false;
6870
6871     // Otherwise, we can scalarize the instruction.
6872     return true;
6873   };
6874
6875   // Returns true if an operand that cannot be scalarized must be extracted
6876   // from a vector. We will account for this scalarization overhead below. Note
6877   // that the non-void predicated instructions are placed in their own blocks,
6878   // and their return values are inserted into vectors. Thus, an extract would
6879   // still be required.
6880   auto needsExtract = [&](Instruction *I) -> bool {
6881     return TheLoop->contains(I) && !isScalarAfterVectorization(I, VF);
6882   };
6883
6884   // Compute the expected cost discount from scalarizing the entire expression
6885   // feeding the predicated instruction. We currently only consider expressions
6886   // that are single-use instruction chains.
6887   Worklist.push_back(PredInst);
6888   while (!Worklist.empty()) {
6889     Instruction *I = Worklist.pop_back_val();
6890
6891     // If we've already analyzed the instruction, there's nothing to do.
6892     if (ScalarCosts.count(I))
6893       continue;
6894
6895     // Compute the cost of the vector instruction. Note that this cost already
6896     // includes the scalarization overhead of the predicated instruction.
6897     unsigned VectorCost = getInstructionCost(I, VF).first;
6898
6899     // Compute the cost of the scalarized instruction. This cost is the cost of
6900     // the instruction as if it wasn't if-converted and instead remained in the
6901     // predicated block. We will scale this cost by block probability after
6902     // computing the scalarization overhead.
6903     unsigned ScalarCost = VF * getInstructionCost(I, 1).first;
6904
6905     // Compute the scalarization overhead of needed insertelement instructions
6906     // and phi nodes.
6907     if (Legal->isScalarWithPredication(I) && !I->getType()->isVoidTy()) {
6908       ScalarCost += TTI.getScalarizationOverhead(ToVectorTy(I->getType(), VF),
6909                                                  true, false);
6910       ScalarCost += VF * TTI.getCFInstrCost(Instruction::PHI);
6911     }
6912
6913     // Compute the scalarization overhead of needed extractelement
6914     // instructions. For each of the instruction's operands, if the operand can
6915     // be scalarized, add it to the worklist; otherwise, account for the
6916     // overhead.
6917     for (Use &U : I->operands())
6918       if (auto *J = dyn_cast<Instruction>(U.get())) {
6919         assert(VectorType::isValidElementType(J->getType()) &&
6920                "Instruction has non-scalar type");
6921         if (canBeScalarized(J))
6922           Worklist.push_back(J);
6923         else if (needsExtract(J))
6924           ScalarCost += TTI.getScalarizationOverhead(
6925                               ToVectorTy(J->getType(),VF), false, true);
6926       }
6927
6928     // Scale the total scalar cost by block probability.
6929     ScalarCost /= getReciprocalPredBlockProb();
6930
6931     // Compute the discount. A non-negative discount means the vector version
6932     // of the instruction costs more, and scalarizing would be beneficial.
6933     Discount += VectorCost - ScalarCost;
6934     ScalarCosts[I] = ScalarCost;
6935   }
6936
6937   return Discount;
6938 }
6939
6940 LoopVectorizationCostModel::VectorizationCostTy
6941 LoopVectorizationCostModel::expectedCost(unsigned VF) {
6942   VectorizationCostTy Cost;
6943
6944   // Collect Uniform and Scalar instructions after vectorization with VF.
6945   collectUniformsAndScalars(VF);
6946
6947   // Collect the instructions (and their associated costs) that will be more
6948   // profitable to scalarize.
6949   collectInstsToScalarize(VF);
6950
6951   // For each block.
6952   for (BasicBlock *BB : TheLoop->blocks()) {
6953     VectorizationCostTy BlockCost;
6954
6955     // For each instruction in the old loop.
6956     for (Instruction &I : *BB) {
6957       // Skip dbg intrinsics.
6958       if (isa<DbgInfoIntrinsic>(I))
6959         continue;
6960
6961       // Skip ignored values.
6962       if (ValuesToIgnore.count(&I))
6963         continue;
6964
6965       VectorizationCostTy C = getInstructionCost(&I, VF);
6966
6967       // Check if we should override the cost.
6968       if (ForceTargetInstructionCost.getNumOccurrences() > 0)
6969         C.first = ForceTargetInstructionCost;
6970
6971       BlockCost.first += C.first;
6972       BlockCost.second |= C.second;
6973       DEBUG(dbgs() << "LV: Found an estimated cost of " << C.first << " for VF "
6974                    << VF << " For instruction: " << I << '\n');
6975     }
6976
6977     // If we are vectorizing a predicated block, it will have been
6978     // if-converted. This means that the block's instructions (aside from
6979     // stores and instructions that may divide by zero) will now be
6980     // unconditionally executed. For the scalar case, we may not always execute
6981     // the predicated block. Thus, scale the block's cost by the probability of
6982     // executing it.
6983     if (VF == 1 && Legal->blockNeedsPredication(BB))
6984       BlockCost.first /= getReciprocalPredBlockProb();
6985
6986     Cost.first += BlockCost.first;
6987     Cost.second |= BlockCost.second;
6988   }
6989
6990   return Cost;
6991 }
6992
6993 /// \brief Gets Address Access SCEV after verifying that the access pattern
6994 /// is loop invariant except the induction variable dependence.
6995 ///
6996 /// This SCEV can be sent to the Target in order to estimate the address
6997 /// calculation cost.
6998 static const SCEV *getAddressAccessSCEV(
6999               Value *Ptr,
7000               LoopVectorizationLegality *Legal,
7001               ScalarEvolution *SE,
7002               const Loop *TheLoop) {
7003   auto *Gep = dyn_cast<GetElementPtrInst>(Ptr);
7004   if (!Gep)
7005     return nullptr;
7006
7007   // We are looking for a gep with all loop invariant indices except for one
7008   // which should be an induction variable.
7009   unsigned NumOperands = Gep->getNumOperands();
7010   for (unsigned i = 1; i < NumOperands; ++i) {
7011     Value *Opd = Gep->getOperand(i);
7012     if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
7013         !Legal->isInductionVariable(Opd))
7014       return nullptr;
7015   }
7016
7017   // Now we know we have a GEP ptr, %inv, %ind, %inv. return the Ptr SCEV.
7018   return SE->getSCEV(Ptr);
7019 }
7020
7021 static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
7022   return Legal->hasStride(I->getOperand(0)) ||
7023          Legal->hasStride(I->getOperand(1));
7024 }
7025
7026 unsigned LoopVectorizationCostModel::getMemInstScalarizationCost(Instruction *I,
7027                                                                  unsigned VF) {
7028   Type *ValTy = getMemInstValueType(I);
7029   auto SE = PSE.getSE();
7030
7031   unsigned Alignment = getMemInstAlignment(I);
7032   unsigned AS = getMemInstAddressSpace(I);
7033   Value *Ptr = getPointerOperand(I);
7034   Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
7035
7036   // Figure out whether the access is strided and get the stride value
7037   // if it's known in compile time
7038   const SCEV *PtrSCEV = getAddressAccessSCEV(Ptr, Legal, SE, TheLoop);
7039
7040   // Get the cost of the scalar memory instruction and address computation.
7041   unsigned Cost = VF * TTI.getAddressComputationCost(PtrTy, SE, PtrSCEV);
7042
7043   Cost += VF *
7044           TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(), Alignment,
7045                               AS, I);
7046
7047   // Get the overhead of the extractelement and insertelement instructions
7048   // we might create due to scalarization.
7049   Cost += getScalarizationOverhead(I, VF, TTI);
7050
7051   // If we have a predicated store, it may not be executed for each vector
7052   // lane. Scale the cost by the probability of executing the predicated
7053   // block.
7054   if (Legal->isScalarWithPredication(I))
7055     Cost /= getReciprocalPredBlockProb();
7056
7057   return Cost;
7058 }
7059
7060 unsigned LoopVectorizationCostModel::getConsecutiveMemOpCost(Instruction *I,
7061                                                              unsigned VF) {
7062   Type *ValTy = getMemInstValueType(I);
7063   Type *VectorTy = ToVectorTy(ValTy, VF);
7064   unsigned Alignment = getMemInstAlignment(I);
7065   Value *Ptr = getPointerOperand(I);
7066   unsigned AS = getMemInstAddressSpace(I);
7067   int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
7068
7069   assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
7070          "Stride should be 1 or -1 for consecutive memory access");
7071   unsigned Cost = 0;
7072   if (Legal->isMaskRequired(I))
7073     Cost += TTI.getMaskedMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
7074   else
7075     Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS, I);
7076
7077   bool Reverse = ConsecutiveStride < 0;
7078   if (Reverse)
7079     Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, 0);
7080   return Cost;
7081 }
7082
7083 unsigned LoopVectorizationCostModel::getUniformMemOpCost(Instruction *I,
7084                                                          unsigned VF) {
7085   LoadInst *LI = cast<LoadInst>(I);
7086   Type *ValTy = LI->getType();
7087   Type *VectorTy = ToVectorTy(ValTy, VF);
7088   unsigned Alignment = LI->getAlignment();
7089   unsigned AS = LI->getPointerAddressSpace();
7090
7091   return TTI.getAddressComputationCost(ValTy) +
7092          TTI.getMemoryOpCost(Instruction::Load, ValTy, Alignment, AS) +
7093          TTI.getShuffleCost(TargetTransformInfo::SK_Broadcast, VectorTy);
7094 }
7095
7096 unsigned LoopVectorizationCostModel::getGatherScatterCost(Instruction *I,
7097                                                           unsigned VF) {
7098   Type *ValTy = getMemInstValueType(I);
7099   Type *VectorTy = ToVectorTy(ValTy, VF);
7100   unsigned Alignment = getMemInstAlignment(I);
7101   Value *Ptr = getPointerOperand(I);
7102
7103   return TTI.getAddressComputationCost(VectorTy) +
7104          TTI.getGatherScatterOpCost(I->getOpcode(), VectorTy, Ptr,
7105                                     Legal->isMaskRequired(I), Alignment);
7106 }
7107
7108 unsigned LoopVectorizationCostModel::getInterleaveGroupCost(Instruction *I,
7109                                                             unsigned VF) {
7110   Type *ValTy = getMemInstValueType(I);
7111   Type *VectorTy = ToVectorTy(ValTy, VF);
7112   unsigned AS = getMemInstAddressSpace(I);
7113
7114   auto Group = Legal->getInterleavedAccessGroup(I);
7115   assert(Group && "Fail to get an interleaved access group.");
7116
7117   unsigned InterleaveFactor = Group->getFactor();
7118   Type *WideVecTy = VectorType::get(ValTy, VF * InterleaveFactor);
7119
7120   // Holds the indices of existing members in an interleaved load group.
7121   // An interleaved store group doesn't need this as it doesn't allow gaps.
7122   SmallVector<unsigned, 4> Indices;
7123   if (isa<LoadInst>(I)) {
7124     for (unsigned i = 0; i < InterleaveFactor; i++)
7125       if (Group->getMember(i))
7126         Indices.push_back(i);
7127   }
7128
7129   // Calculate the cost of the whole interleaved group.
7130   unsigned Cost = TTI.getInterleavedMemoryOpCost(I->getOpcode(), WideVecTy,
7131                                                  Group->getFactor(), Indices,
7132                                                  Group->getAlignment(), AS);
7133
7134   if (Group->isReverse())
7135     Cost += Group->getNumMembers() *
7136             TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, 0);
7137   return Cost;
7138 }
7139
7140 unsigned LoopVectorizationCostModel::getMemoryInstructionCost(Instruction *I,
7141                                                               unsigned VF) {
7142
7143   // Calculate scalar cost only. Vectorization cost should be ready at this
7144   // moment.
7145   if (VF == 1) {
7146     Type *ValTy = getMemInstValueType(I);
7147     unsigned Alignment = getMemInstAlignment(I);
7148     unsigned AS = getMemInstAddressSpace(I);
7149
7150     return TTI.getAddressComputationCost(ValTy) +
7151            TTI.getMemoryOpCost(I->getOpcode(), ValTy, Alignment, AS, I);
7152   }
7153   return getWideningCost(I, VF);
7154 }
7155
7156 LoopVectorizationCostModel::VectorizationCostTy
7157 LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
7158   // If we know that this instruction will remain uniform, check the cost of
7159   // the scalar version.
7160   if (isUniformAfterVectorization(I, VF))
7161     VF = 1;
7162
7163   if (VF > 1 && isProfitableToScalarize(I, VF))
7164     return VectorizationCostTy(InstsToScalarize[VF][I], false);
7165
7166   // Forced scalars do not have any scalarization overhead.
7167   if (VF > 1 && ForcedScalars.count(VF) &&
7168       ForcedScalars.find(VF)->second.count(I))
7169     return VectorizationCostTy((getInstructionCost(I, 1).first * VF), false);
7170
7171   Type *VectorTy;
7172   unsigned C = getInstructionCost(I, VF, VectorTy);
7173
7174   bool TypeNotScalarized =
7175       VF > 1 && VectorTy->isVectorTy() && TTI.getNumberOfParts(VectorTy) < VF;
7176   return VectorizationCostTy(C, TypeNotScalarized);
7177 }
7178
7179 void LoopVectorizationCostModel::setCostBasedWideningDecision(unsigned VF) {
7180   if (VF == 1)
7181     return;
7182   for (BasicBlock *BB : TheLoop->blocks()) {
7183     // For each instruction in the old loop.
7184     for (Instruction &I : *BB) {
7185       Value *Ptr = getPointerOperand(&I);
7186       if (!Ptr)
7187         continue;
7188
7189       if (isa<LoadInst>(&I) && Legal->isUniform(Ptr)) {
7190         // Scalar load + broadcast
7191         unsigned Cost = getUniformMemOpCost(&I, VF);
7192         setWideningDecision(&I, VF, CM_Scalarize, Cost);
7193         continue;
7194       }
7195
7196       // We assume that widening is the best solution when possible.
7197       if (Legal->memoryInstructionCanBeWidened(&I, VF)) {
7198         unsigned Cost = getConsecutiveMemOpCost(&I, VF);
7199         setWideningDecision(&I, VF, CM_Widen, Cost);
7200         continue;
7201       }
7202
7203       // Choose between Interleaving, Gather/Scatter or Scalarization.
7204       unsigned InterleaveCost = UINT_MAX;
7205       unsigned NumAccesses = 1;
7206       if (Legal->isAccessInterleaved(&I)) {
7207         auto Group = Legal->getInterleavedAccessGroup(&I);
7208         assert(Group && "Fail to get an interleaved access group.");
7209
7210         // Make one decision for the whole group.
7211         if (getWideningDecision(&I, VF) != CM_Unknown)
7212           continue;
7213
7214         NumAccesses = Group->getNumMembers();
7215         InterleaveCost = getInterleaveGroupCost(&I, VF);
7216       }
7217
7218       unsigned GatherScatterCost =
7219           Legal->isLegalGatherOrScatter(&I)
7220               ? getGatherScatterCost(&I, VF) * NumAccesses
7221               : UINT_MAX;
7222
7223       unsigned ScalarizationCost =
7224           getMemInstScalarizationCost(&I, VF) * NumAccesses;
7225
7226       // Choose better solution for the current VF,
7227       // write down this decision and use it during vectorization.
7228       unsigned Cost;
7229       InstWidening Decision;
7230       if (InterleaveCost <= GatherScatterCost &&
7231           InterleaveCost < ScalarizationCost) {
7232         Decision = CM_Interleave;
7233         Cost = InterleaveCost;
7234       } else if (GatherScatterCost < ScalarizationCost) {
7235         Decision = CM_GatherScatter;
7236         Cost = GatherScatterCost;
7237       } else {
7238         Decision = CM_Scalarize;
7239         Cost = ScalarizationCost;
7240       }
7241       // If the instructions belongs to an interleave group, the whole group
7242       // receives the same decision. The whole group receives the cost, but
7243       // the cost will actually be assigned to one instruction.
7244       if (auto Group = Legal->getInterleavedAccessGroup(&I))
7245         setWideningDecision(Group, VF, Decision, Cost);
7246       else
7247         setWideningDecision(&I, VF, Decision, Cost);
7248     }
7249   }
7250
7251   // Make sure that any load of address and any other address computation
7252   // remains scalar unless there is gather/scatter support. This avoids
7253   // inevitable extracts into address registers, and also has the benefit of
7254   // activating LSR more, since that pass can't optimize vectorized
7255   // addresses.
7256   if (TTI.prefersVectorizedAddressing())
7257     return;
7258
7259   // Start with all scalar pointer uses.
7260   SmallPtrSet<Instruction *, 8> AddrDefs;
7261   for (BasicBlock *BB : TheLoop->blocks())
7262     for (Instruction &I : *BB) {
7263       Instruction *PtrDef =
7264         dyn_cast_or_null<Instruction>(getPointerOperand(&I));
7265       if (PtrDef && TheLoop->contains(PtrDef) &&
7266           getWideningDecision(&I, VF) != CM_GatherScatter)
7267         AddrDefs.insert(PtrDef);
7268     }
7269
7270   // Add all instructions used to generate the addresses.
7271   SmallVector<Instruction *, 4> Worklist;
7272   for (auto *I : AddrDefs)
7273     Worklist.push_back(I);
7274   while (!Worklist.empty()) {
7275     Instruction *I = Worklist.pop_back_val();
7276     for (auto &Op : I->operands())
7277       if (auto *InstOp = dyn_cast<Instruction>(Op))
7278         if ((InstOp->getParent() == I->getParent()) && !isa<PHINode>(InstOp) &&
7279             AddrDefs.insert(InstOp).second == true)
7280           Worklist.push_back(InstOp);
7281   }
7282
7283   for (auto *I : AddrDefs) {
7284     if (isa<LoadInst>(I)) {
7285       // Setting the desired widening decision should ideally be handled in
7286       // by cost functions, but since this involves the task of finding out
7287       // if the loaded register is involved in an address computation, it is
7288       // instead changed here when we know this is the case.
7289       if (getWideningDecision(I, VF) == CM_Widen)
7290         // Scalarize a widened load of address.
7291         setWideningDecision(I, VF, CM_Scalarize,
7292                             (VF * getMemoryInstructionCost(I, 1)));
7293       else if (auto Group = Legal->getInterleavedAccessGroup(I)) {
7294         // Scalarize an interleave group of address loads.
7295         for (unsigned I = 0; I < Group->getFactor(); ++I) {
7296           if (Instruction *Member = Group->getMember(I))
7297             setWideningDecision(Member, VF, CM_Scalarize,
7298                                 (VF * getMemoryInstructionCost(Member, 1)));
7299         }
7300       }
7301     } else
7302       // Make sure I gets scalarized and a cost estimate without
7303       // scalarization overhead.
7304       ForcedScalars[VF].insert(I);
7305   }
7306 }
7307
7308 unsigned LoopVectorizationCostModel::getInstructionCost(Instruction *I,
7309                                                         unsigned VF,
7310                                                         Type *&VectorTy) {
7311   Type *RetTy = I->getType();
7312   if (canTruncateToMinimalBitwidth(I, VF))
7313     RetTy = IntegerType::get(RetTy->getContext(), MinBWs[I]);
7314   VectorTy = isScalarAfterVectorization(I, VF) ? RetTy : ToVectorTy(RetTy, VF);
7315   auto SE = PSE.getSE();
7316
7317   // TODO: We need to estimate the cost of intrinsic calls.
7318   switch (I->getOpcode()) {
7319   case Instruction::GetElementPtr:
7320     // We mark this instruction as zero-cost because the cost of GEPs in
7321     // vectorized code depends on whether the corresponding memory instruction
7322     // is scalarized or not. Therefore, we handle GEPs with the memory
7323     // instruction cost.
7324     return 0;
7325   case Instruction::Br: {
7326     // In cases of scalarized and predicated instructions, there will be VF
7327     // predicated blocks in the vectorized loop. Each branch around these
7328     // blocks requires also an extract of its vector compare i1 element.
7329     bool ScalarPredicatedBB = false;
7330     BranchInst *BI = cast<BranchInst>(I);
7331     if (VF > 1 && BI->isConditional() &&
7332         (PredicatedBBsAfterVectorization.count(BI->getSuccessor(0)) ||
7333          PredicatedBBsAfterVectorization.count(BI->getSuccessor(1))))
7334       ScalarPredicatedBB = true;
7335
7336     if (ScalarPredicatedBB) {
7337       // Return cost for branches around scalarized and predicated blocks.
7338       Type *Vec_i1Ty =
7339           VectorType::get(IntegerType::getInt1Ty(RetTy->getContext()), VF);
7340       return (TTI.getScalarizationOverhead(Vec_i1Ty, false, true) +
7341               (TTI.getCFInstrCost(Instruction::Br) * VF));
7342     } else if (I->getParent() == TheLoop->getLoopLatch() || VF == 1)
7343       // The back-edge branch will remain, as will all scalar branches.
7344       return TTI.getCFInstrCost(Instruction::Br);
7345     else
7346       // This branch will be eliminated by if-conversion.
7347       return 0;
7348     // Note: We currently assume zero cost for an unconditional branch inside
7349     // a predicated block since it will become a fall-through, although we
7350     // may decide in the future to call TTI for all branches.
7351   }
7352   case Instruction::PHI: {
7353     auto *Phi = cast<PHINode>(I);
7354
7355     // First-order recurrences are replaced by vector shuffles inside the loop.
7356     if (VF > 1 && Legal->isFirstOrderRecurrence(Phi))
7357       return TTI.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
7358                                 VectorTy, VF - 1, VectorTy);
7359
7360     // Phi nodes in non-header blocks (not inductions, reductions, etc.) are
7361     // converted into select instructions. We require N - 1 selects per phi
7362     // node, where N is the number of incoming values.
7363     if (VF > 1 && Phi->getParent() != TheLoop->getHeader())
7364       return (Phi->getNumIncomingValues() - 1) *
7365              TTI.getCmpSelInstrCost(
7366                  Instruction::Select, ToVectorTy(Phi->getType(), VF),
7367                  ToVectorTy(Type::getInt1Ty(Phi->getContext()), VF));
7368
7369     return TTI.getCFInstrCost(Instruction::PHI);
7370   }
7371   case Instruction::UDiv:
7372   case Instruction::SDiv:
7373   case Instruction::URem:
7374   case Instruction::SRem:
7375     // If we have a predicated instruction, it may not be executed for each
7376     // vector lane. Get the scalarization cost and scale this amount by the
7377     // probability of executing the predicated block. If the instruction is not
7378     // predicated, we fall through to the next case.
7379     if (VF > 1 && Legal->isScalarWithPredication(I)) {
7380       unsigned Cost = 0;
7381
7382       // These instructions have a non-void type, so account for the phi nodes
7383       // that we will create. This cost is likely to be zero. The phi node
7384       // cost, if any, should be scaled by the block probability because it
7385       // models a copy at the end of each predicated block.
7386       Cost += VF * TTI.getCFInstrCost(Instruction::PHI);
7387
7388       // The cost of the non-predicated instruction.
7389       Cost += VF * TTI.getArithmeticInstrCost(I->getOpcode(), RetTy);
7390
7391       // The cost of insertelement and extractelement instructions needed for
7392       // scalarization.
7393       Cost += getScalarizationOverhead(I, VF, TTI);
7394
7395       // Scale the cost by the probability of executing the predicated blocks.
7396       // This assumes the predicated block for each vector lane is equally
7397       // likely.
7398       return Cost / getReciprocalPredBlockProb();
7399     }
7400     LLVM_FALLTHROUGH;
7401   case Instruction::Add:
7402   case Instruction::FAdd:
7403   case Instruction::Sub:
7404   case Instruction::FSub:
7405   case Instruction::Mul:
7406   case Instruction::FMul:
7407   case Instruction::FDiv:
7408   case Instruction::FRem:
7409   case Instruction::Shl:
7410   case Instruction::LShr:
7411   case Instruction::AShr:
7412   case Instruction::And:
7413   case Instruction::Or:
7414   case Instruction::Xor: {
7415     // Since we will replace the stride by 1 the multiplication should go away.
7416     if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
7417       return 0;
7418     // Certain instructions can be cheaper to vectorize if they have a constant
7419     // second vector operand. One example of this are shifts on x86.
7420     TargetTransformInfo::OperandValueKind Op1VK =
7421         TargetTransformInfo::OK_AnyValue;
7422     TargetTransformInfo::OperandValueKind Op2VK =
7423         TargetTransformInfo::OK_AnyValue;
7424     TargetTransformInfo::OperandValueProperties Op1VP =
7425         TargetTransformInfo::OP_None;
7426     TargetTransformInfo::OperandValueProperties Op2VP =
7427         TargetTransformInfo::OP_None;
7428     Value *Op2 = I->getOperand(1);
7429
7430     // Check for a splat or for a non uniform vector of constants.
7431     if (isa<ConstantInt>(Op2)) {
7432       ConstantInt *CInt = cast<ConstantInt>(Op2);
7433       if (CInt && CInt->getValue().isPowerOf2())
7434         Op2VP = TargetTransformInfo::OP_PowerOf2;
7435       Op2VK = TargetTransformInfo::OK_UniformConstantValue;
7436     } else if (isa<ConstantVector>(Op2) || isa<ConstantDataVector>(Op2)) {
7437       Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
7438       Constant *SplatValue = cast<Constant>(Op2)->getSplatValue();
7439       if (SplatValue) {
7440         ConstantInt *CInt = dyn_cast<ConstantInt>(SplatValue);
7441         if (CInt && CInt->getValue().isPowerOf2())
7442           Op2VP = TargetTransformInfo::OP_PowerOf2;
7443         Op2VK = TargetTransformInfo::OK_UniformConstantValue;
7444       }
7445     } else if (Legal->isUniform(Op2)) {
7446       Op2VK = TargetTransformInfo::OK_UniformValue;
7447     }
7448     SmallVector<const Value *, 4> Operands(I->operand_values());
7449     unsigned N = isScalarAfterVectorization(I, VF) ? VF : 1;
7450     return N * TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy, Op1VK,
7451                                           Op2VK, Op1VP, Op2VP, Operands);
7452   }
7453   case Instruction::Select: {
7454     SelectInst *SI = cast<SelectInst>(I);
7455     const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
7456     bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
7457     Type *CondTy = SI->getCondition()->getType();
7458     if (!ScalarCond)
7459       CondTy = VectorType::get(CondTy, VF);
7460
7461     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy, I);
7462   }
7463   case Instruction::ICmp:
7464   case Instruction::FCmp: {
7465     Type *ValTy = I->getOperand(0)->getType();
7466     Instruction *Op0AsInstruction = dyn_cast<Instruction>(I->getOperand(0));
7467     if (canTruncateToMinimalBitwidth(Op0AsInstruction, VF))
7468       ValTy = IntegerType::get(ValTy->getContext(), MinBWs[Op0AsInstruction]);
7469     VectorTy = ToVectorTy(ValTy, VF);
7470     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, nullptr, I);
7471   }
7472   case Instruction::Store:
7473   case Instruction::Load: {
7474     unsigned Width = VF;
7475     if (Width > 1) {
7476       InstWidening Decision = getWideningDecision(I, Width);
7477       assert(Decision != CM_Unknown &&
7478              "CM decision should be taken at this point");
7479       if (Decision == CM_Scalarize)
7480         Width = 1;
7481     }
7482     VectorTy = ToVectorTy(getMemInstValueType(I), Width);
7483     return getMemoryInstructionCost(I, VF);
7484   }
7485   case Instruction::ZExt:
7486   case Instruction::SExt:
7487   case Instruction::FPToUI:
7488   case Instruction::FPToSI:
7489   case Instruction::FPExt:
7490   case Instruction::PtrToInt:
7491   case Instruction::IntToPtr:
7492   case Instruction::SIToFP:
7493   case Instruction::UIToFP:
7494   case Instruction::Trunc:
7495   case Instruction::FPTrunc:
7496   case Instruction::BitCast: {
7497     // We optimize the truncation of induction variables having constant
7498     // integer steps. The cost of these truncations is the same as the scalar
7499     // operation.
7500     if (isOptimizableIVTruncate(I, VF)) {
7501       auto *Trunc = cast<TruncInst>(I);
7502       return TTI.getCastInstrCost(Instruction::Trunc, Trunc->getDestTy(),
7503                                   Trunc->getSrcTy(), Trunc);
7504     }
7505
7506     Type *SrcScalarTy = I->getOperand(0)->getType();
7507     Type *SrcVecTy =
7508         VectorTy->isVectorTy() ? ToVectorTy(SrcScalarTy, VF) : SrcScalarTy;
7509     if (canTruncateToMinimalBitwidth(I, VF)) {
7510       // This cast is going to be shrunk. This may remove the cast or it might
7511       // turn it into slightly different cast. For example, if MinBW == 16,
7512       // "zext i8 %1 to i32" becomes "zext i8 %1 to i16".
7513       //
7514       // Calculate the modified src and dest types.
7515       Type *MinVecTy = VectorTy;
7516       if (I->getOpcode() == Instruction::Trunc) {
7517         SrcVecTy = smallestIntegerVectorType(SrcVecTy, MinVecTy);
7518         VectorTy =
7519             largestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy);
7520       } else if (I->getOpcode() == Instruction::ZExt ||
7521                  I->getOpcode() == Instruction::SExt) {
7522         SrcVecTy = largestIntegerVectorType(SrcVecTy, MinVecTy);
7523         VectorTy =
7524             smallestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy);
7525       }
7526     }
7527
7528     unsigned N = isScalarAfterVectorization(I, VF) ? VF : 1;
7529     return N * TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy, I);
7530   }
7531   case Instruction::Call: {
7532     bool NeedToScalarize;
7533     CallInst *CI = cast<CallInst>(I);
7534     unsigned CallCost = getVectorCallCost(CI, VF, TTI, TLI, NeedToScalarize);
7535     if (getVectorIntrinsicIDForCall(CI, TLI))
7536       return std::min(CallCost, getVectorIntrinsicCost(CI, VF, TTI, TLI));
7537     return CallCost;
7538   }
7539   default:
7540     // The cost of executing VF copies of the scalar instruction. This opcode
7541     // is unknown. Assume that it is the same as 'mul'.
7542     return VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy) +
7543            getScalarizationOverhead(I, VF, TTI);
7544   } // end of switch.
7545 }
7546
7547 char LoopVectorize::ID = 0;
7548 static const char lv_name[] = "Loop Vectorization";
7549 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
7550 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
7551 INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
7552 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
7553 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
7554 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
7555 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
7556 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
7557 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
7558 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
7559 INITIALIZE_PASS_DEPENDENCY(LoopAccessLegacyAnalysis)
7560 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
7561 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
7562 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
7563
7564 namespace llvm {
7565 Pass *createLoopVectorizePass(bool NoUnrolling, bool AlwaysVectorize) {
7566   return new LoopVectorize(NoUnrolling, AlwaysVectorize);
7567 }
7568 }
7569
7570 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
7571
7572   // Check if the pointer operand of a load or store instruction is
7573   // consecutive.
7574   if (auto *Ptr = getPointerOperand(Inst))
7575     return Legal->isConsecutivePtr(Ptr);
7576   return false;
7577 }
7578
7579 void LoopVectorizationCostModel::collectValuesToIgnore() {
7580   // Ignore ephemeral values.
7581   CodeMetrics::collectEphemeralValues(TheLoop, AC, ValuesToIgnore);
7582
7583   // Ignore type-promoting instructions we identified during reduction
7584   // detection.
7585   for (auto &Reduction : *Legal->getReductionVars()) {
7586     RecurrenceDescriptor &RedDes = Reduction.second;
7587     SmallPtrSetImpl<Instruction *> &Casts = RedDes.getCastInsts();
7588     VecValuesToIgnore.insert(Casts.begin(), Casts.end());
7589   }
7590 }
7591
7592 LoopVectorizationCostModel::VectorizationFactor
7593 LoopVectorizationPlanner::plan(bool OptForSize, unsigned UserVF) {
7594
7595   // Width 1 means no vectorize, cost 0 means uncomputed cost.
7596   const LoopVectorizationCostModel::VectorizationFactor NoVectorization = {1U,
7597                                                                            0U};
7598   Optional<unsigned> MaybeMaxVF = CM.computeMaxVF(OptForSize);
7599   if (!MaybeMaxVF.hasValue()) // Cases considered too costly to vectorize.
7600     return NoVectorization;
7601
7602   if (UserVF) {
7603     DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
7604     assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
7605     // Collect the instructions (and their associated costs) that will be more
7606     // profitable to scalarize.
7607     CM.selectUserVectorizationFactor(UserVF);
7608     return {UserVF, 0};
7609   }
7610
7611   unsigned MaxVF = MaybeMaxVF.getValue();
7612   assert(MaxVF != 0 && "MaxVF is zero.");
7613   if (MaxVF == 1)
7614     return NoVectorization;
7615
7616   // Select the optimal vectorization factor.
7617   return CM.selectVectorizationFactor(MaxVF);
7618 }
7619
7620 void LoopVectorizationPlanner::executePlan(InnerLoopVectorizer &ILV) {
7621   // Perform the actual loop transformation.
7622
7623   // 1. Create a new empty loop. Unlink the old loop and connect the new one.
7624   ILV.createVectorizedLoopSkeleton();
7625
7626   //===------------------------------------------------===//
7627   //
7628   // Notice: any optimization or new instruction that go
7629   // into the code below should also be implemented in
7630   // the cost-model.
7631   //
7632   //===------------------------------------------------===//
7633
7634   // 2. Copy and widen instructions from the old loop into the new loop.
7635
7636   // Collect instructions from the original loop that will become trivially dead
7637   // in the vectorized loop. We don't need to vectorize these instructions. For
7638   // example, original induction update instructions can become dead because we
7639   // separately emit induction "steps" when generating code for the new loop.
7640   // Similarly, we create a new latch condition when setting up the structure
7641   // of the new loop, so the old one can become dead.
7642   SmallPtrSet<Instruction *, 4> DeadInstructions;
7643   collectTriviallyDeadInstructions(DeadInstructions);
7644
7645   // Scan the loop in a topological order to ensure that defs are vectorized
7646   // before users.
7647   LoopBlocksDFS DFS(OrigLoop);
7648   DFS.perform(LI);
7649
7650   // Vectorize all instructions in the original loop that will not become
7651   // trivially dead when vectorized.
7652   for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO()))
7653     for (Instruction &I : *BB)
7654       if (!DeadInstructions.count(&I))
7655         ILV.vectorizeInstruction(I);
7656
7657   // 3. Fix the vectorized code: take care of header phi's, live-outs,
7658   //    predication, updating analyses.
7659   ILV.fixVectorizedLoop();
7660 }
7661
7662 void LoopVectorizationPlanner::collectTriviallyDeadInstructions(
7663     SmallPtrSetImpl<Instruction *> &DeadInstructions) {
7664   BasicBlock *Latch = OrigLoop->getLoopLatch();
7665
7666   // We create new control-flow for the vectorized loop, so the original
7667   // condition will be dead after vectorization if it's only used by the
7668   // branch.
7669   auto *Cmp = dyn_cast<Instruction>(Latch->getTerminator()->getOperand(0));
7670   if (Cmp && Cmp->hasOneUse())
7671     DeadInstructions.insert(Cmp);
7672
7673   // We create new "steps" for induction variable updates to which the original
7674   // induction variables map. An original update instruction will be dead if
7675   // all its users except the induction variable are dead.
7676   for (auto &Induction : *Legal->getInductionVars()) {
7677     PHINode *Ind = Induction.first;
7678     auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
7679     if (all_of(IndUpdate->users(), [&](User *U) -> bool {
7680           return U == Ind || DeadInstructions.count(cast<Instruction>(U));
7681         }))
7682       DeadInstructions.insert(IndUpdate);
7683   }
7684 }
7685
7686 void InnerLoopUnroller::vectorizeMemoryInstruction(Instruction *Instr) {
7687   auto *SI = dyn_cast<StoreInst>(Instr);
7688   bool IfPredicateInstr = (SI && Legal->blockNeedsPredication(SI->getParent()));
7689
7690   return scalarizeInstruction(Instr, IfPredicateInstr);
7691 }
7692
7693 Value *InnerLoopUnroller::reverseVector(Value *Vec) { return Vec; }
7694
7695 Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) { return V; }
7696
7697 Value *InnerLoopUnroller::getStepVector(Value *Val, int StartIdx, Value *Step,
7698                                         Instruction::BinaryOps BinOp) {
7699   // When unrolling and the VF is 1, we only need to add a simple scalar.
7700   Type *Ty = Val->getType();
7701   assert(!Ty->isVectorTy() && "Val must be a scalar");
7702
7703   if (Ty->isFloatingPointTy()) {
7704     Constant *C = ConstantFP::get(Ty, (double)StartIdx);
7705
7706     // Floating point operations had to be 'fast' to enable the unrolling.
7707     Value *MulOp = addFastMathFlag(Builder.CreateFMul(C, Step));
7708     return addFastMathFlag(Builder.CreateBinOp(BinOp, Val, MulOp));
7709   }
7710   Constant *C = ConstantInt::get(Ty, StartIdx);
7711   return Builder.CreateAdd(Val, Builder.CreateMul(C, Step), "induction");
7712 }
7713
7714 static void AddRuntimeUnrollDisableMetaData(Loop *L) {
7715   SmallVector<Metadata *, 4> MDs;
7716   // Reserve first location for self reference to the LoopID metadata node.
7717   MDs.push_back(nullptr);
7718   bool IsUnrollMetadata = false;
7719   MDNode *LoopID = L->getLoopID();
7720   if (LoopID) {
7721     // First find existing loop unrolling disable metadata.
7722     for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
7723       auto *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
7724       if (MD) {
7725         const auto *S = dyn_cast<MDString>(MD->getOperand(0));
7726         IsUnrollMetadata =
7727             S && S->getString().startswith("llvm.loop.unroll.disable");
7728       }
7729       MDs.push_back(LoopID->getOperand(i));
7730     }
7731   }
7732
7733   if (!IsUnrollMetadata) {
7734     // Add runtime unroll disable metadata.
7735     LLVMContext &Context = L->getHeader()->getContext();
7736     SmallVector<Metadata *, 1> DisableOperands;
7737     DisableOperands.push_back(
7738         MDString::get(Context, "llvm.loop.unroll.runtime.disable"));
7739     MDNode *DisableNode = MDNode::get(Context, DisableOperands);
7740     MDs.push_back(DisableNode);
7741     MDNode *NewLoopID = MDNode::get(Context, MDs);
7742     // Set operand 0 to refer to the loop id itself.
7743     NewLoopID->replaceOperandWith(0, NewLoopID);
7744     L->setLoopID(NewLoopID);
7745   }
7746 }
7747
7748 bool LoopVectorizePass::processLoop(Loop *L) {
7749   assert(L->empty() && "Only process inner loops.");
7750
7751 #ifndef NDEBUG
7752   const std::string DebugLocStr = getDebugLocString(L);
7753 #endif /* NDEBUG */
7754
7755   DEBUG(dbgs() << "\nLV: Checking a loop in \""
7756                << L->getHeader()->getParent()->getName() << "\" from "
7757                << DebugLocStr << "\n");
7758
7759   LoopVectorizeHints Hints(L, DisableUnrolling, *ORE);
7760
7761   DEBUG(dbgs() << "LV: Loop hints:"
7762                << " force="
7763                << (Hints.getForce() == LoopVectorizeHints::FK_Disabled
7764                        ? "disabled"
7765                        : (Hints.getForce() == LoopVectorizeHints::FK_Enabled
7766                               ? "enabled"
7767                               : "?"))
7768                << " width=" << Hints.getWidth()
7769                << " unroll=" << Hints.getInterleave() << "\n");
7770
7771   // Function containing loop
7772   Function *F = L->getHeader()->getParent();
7773
7774   // Looking at the diagnostic output is the only way to determine if a loop
7775   // was vectorized (other than looking at the IR or machine code), so it
7776   // is important to generate an optimization remark for each loop. Most of
7777   // these messages are generated as OptimizationRemarkAnalysis. Remarks
7778   // generated as OptimizationRemark and OptimizationRemarkMissed are
7779   // less verbose reporting vectorized loops and unvectorized loops that may
7780   // benefit from vectorization, respectively.
7781
7782   if (!Hints.allowVectorization(F, L, AlwaysVectorize)) {
7783     DEBUG(dbgs() << "LV: Loop hints prevent vectorization.\n");
7784     return false;
7785   }
7786
7787   // Check the loop for a trip count threshold:
7788   // do not vectorize loops with a tiny trip count.
7789   const unsigned MaxTC = SE->getSmallConstantMaxTripCount(L);
7790   if (MaxTC > 0u && MaxTC < TinyTripCountVectorThreshold) {
7791     DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "
7792                  << "This loop is not worth vectorizing.");
7793     if (Hints.getForce() == LoopVectorizeHints::FK_Enabled)
7794       DEBUG(dbgs() << " But vectorizing was explicitly forced.\n");
7795     else {
7796       DEBUG(dbgs() << "\n");
7797       ORE->emit(createMissedAnalysis(Hints.vectorizeAnalysisPassName(),
7798                                      "NotBeneficial", L)
7799                 << "vectorization is not beneficial "
7800                    "and is not explicitly forced");
7801       return false;
7802     }
7803   }
7804
7805   PredicatedScalarEvolution PSE(*SE, *L);
7806
7807   // Check if it is legal to vectorize the loop.
7808   LoopVectorizationRequirements Requirements(*ORE);
7809   LoopVectorizationLegality LVL(L, PSE, DT, TLI, AA, F, TTI, GetLAA, LI, ORE,
7810                                 &Requirements, &Hints);
7811   if (!LVL.canVectorize()) {
7812     DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
7813     emitMissedWarning(F, L, Hints, ORE);
7814     return false;
7815   }
7816
7817   // Check the function attributes to find out if this function should be
7818   // optimized for size.
7819   bool OptForSize =
7820       Hints.getForce() != LoopVectorizeHints::FK_Enabled && F->optForSize();
7821
7822   // Compute the weighted frequency of this loop being executed and see if it
7823   // is less than 20% of the function entry baseline frequency. Note that we
7824   // always have a canonical loop here because we think we *can* vectorize.
7825   // FIXME: This is hidden behind a flag due to pervasive problems with
7826   // exactly what block frequency models.
7827   if (LoopVectorizeWithBlockFrequency) {
7828     BlockFrequency LoopEntryFreq = BFI->getBlockFreq(L->getLoopPreheader());
7829     if (Hints.getForce() != LoopVectorizeHints::FK_Enabled &&
7830         LoopEntryFreq < ColdEntryFreq)
7831       OptForSize = true;
7832   }
7833
7834   // Check the function attributes to see if implicit floats are allowed.
7835   // FIXME: This check doesn't seem possibly correct -- what if the loop is
7836   // an integer loop and the vector instructions selected are purely integer
7837   // vector instructions?
7838   if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
7839     DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
7840                     "attribute is used.\n");
7841     ORE->emit(createMissedAnalysis(Hints.vectorizeAnalysisPassName(),
7842                                    "NoImplicitFloat", L)
7843               << "loop not vectorized due to NoImplicitFloat attribute");
7844     emitMissedWarning(F, L, Hints, ORE);
7845     return false;
7846   }
7847
7848   // Check if the target supports potentially unsafe FP vectorization.
7849   // FIXME: Add a check for the type of safety issue (denormal, signaling)
7850   // for the target we're vectorizing for, to make sure none of the
7851   // additional fp-math flags can help.
7852   if (Hints.isPotentiallyUnsafe() &&
7853       TTI->isFPVectorizationPotentiallyUnsafe()) {
7854     DEBUG(dbgs() << "LV: Potentially unsafe FP op prevents vectorization.\n");
7855     ORE->emit(
7856         createMissedAnalysis(Hints.vectorizeAnalysisPassName(), "UnsafeFP", L)
7857         << "loop not vectorized due to unsafe FP support.");
7858     emitMissedWarning(F, L, Hints, ORE);
7859     return false;
7860   }
7861
7862   // Use the cost model.
7863   LoopVectorizationCostModel CM(L, PSE, LI, &LVL, *TTI, TLI, DB, AC, ORE, F,
7864                                 &Hints);
7865   CM.collectValuesToIgnore();
7866
7867   // Use the planner for vectorization.
7868   LoopVectorizationPlanner LVP(L, LI, &LVL, CM);
7869
7870   // Get user vectorization factor.
7871   unsigned UserVF = Hints.getWidth();
7872
7873   // Plan how to best vectorize, return the best VF and its cost.
7874   LoopVectorizationCostModel::VectorizationFactor VF =
7875       LVP.plan(OptForSize, UserVF);
7876
7877   // Select the interleave count.
7878   unsigned IC = CM.selectInterleaveCount(OptForSize, VF.Width, VF.Cost);
7879
7880   // Get user interleave count.
7881   unsigned UserIC = Hints.getInterleave();
7882
7883   // Identify the diagnostic messages that should be produced.
7884   std::pair<StringRef, std::string> VecDiagMsg, IntDiagMsg;
7885   bool VectorizeLoop = true, InterleaveLoop = true;
7886   if (Requirements.doesNotMeet(F, L, Hints)) {
7887     DEBUG(dbgs() << "LV: Not vectorizing: loop did not meet vectorization "
7888                     "requirements.\n");
7889     emitMissedWarning(F, L, Hints, ORE);
7890     return false;
7891   }
7892
7893   if (VF.Width == 1) {
7894     DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
7895     VecDiagMsg = std::make_pair(
7896         "VectorizationNotBeneficial",
7897         "the cost-model indicates that vectorization is not beneficial");
7898     VectorizeLoop = false;
7899   }
7900
7901   if (IC == 1 && UserIC <= 1) {
7902     // Tell the user interleaving is not beneficial.
7903     DEBUG(dbgs() << "LV: Interleaving is not beneficial.\n");
7904     IntDiagMsg = std::make_pair(
7905         "InterleavingNotBeneficial",
7906         "the cost-model indicates that interleaving is not beneficial");
7907     InterleaveLoop = false;
7908     if (UserIC == 1) {
7909       IntDiagMsg.first = "InterleavingNotBeneficialAndDisabled";
7910       IntDiagMsg.second +=
7911           " and is explicitly disabled or interleave count is set to 1";
7912     }
7913   } else if (IC > 1 && UserIC == 1) {
7914     // Tell the user interleaving is beneficial, but it explicitly disabled.
7915     DEBUG(dbgs()
7916           << "LV: Interleaving is beneficial but is explicitly disabled.");
7917     IntDiagMsg = std::make_pair(
7918         "InterleavingBeneficialButDisabled",
7919         "the cost-model indicates that interleaving is beneficial "
7920         "but is explicitly disabled or interleave count is set to 1");
7921     InterleaveLoop = false;
7922   }
7923
7924   // Override IC if user provided an interleave count.
7925   IC = UserIC > 0 ? UserIC : IC;
7926
7927   // Emit diagnostic messages, if any.
7928   const char *VAPassName = Hints.vectorizeAnalysisPassName();
7929   if (!VectorizeLoop && !InterleaveLoop) {
7930     // Do not vectorize or interleaving the loop.
7931     ORE->emit(OptimizationRemarkMissed(VAPassName, VecDiagMsg.first,
7932                                          L->getStartLoc(), L->getHeader())
7933               << VecDiagMsg.second);
7934     ORE->emit(OptimizationRemarkMissed(LV_NAME, IntDiagMsg.first,
7935                                          L->getStartLoc(), L->getHeader())
7936               << IntDiagMsg.second);
7937     return false;
7938   } else if (!VectorizeLoop && InterleaveLoop) {
7939     DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
7940     ORE->emit(OptimizationRemarkAnalysis(VAPassName, VecDiagMsg.first,
7941                                          L->getStartLoc(), L->getHeader())
7942               << VecDiagMsg.second);
7943   } else if (VectorizeLoop && !InterleaveLoop) {
7944     DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width << ") in "
7945                  << DebugLocStr << '\n');
7946     ORE->emit(OptimizationRemarkAnalysis(LV_NAME, IntDiagMsg.first,
7947                                          L->getStartLoc(), L->getHeader())
7948               << IntDiagMsg.second);
7949   } else if (VectorizeLoop && InterleaveLoop) {
7950     DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width << ") in "
7951                  << DebugLocStr << '\n');
7952     DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
7953   }
7954
7955   using namespace ore;
7956   if (!VectorizeLoop) {
7957     assert(IC > 1 && "interleave count should not be 1 or 0");
7958     // If we decided that it is not legal to vectorize the loop, then
7959     // interleave it.
7960     InnerLoopUnroller Unroller(L, PSE, LI, DT, TLI, TTI, AC, ORE, IC, &LVL,
7961                                &CM);
7962     LVP.executePlan(Unroller);
7963
7964     ORE->emit(OptimizationRemark(LV_NAME, "Interleaved", L->getStartLoc(),
7965                                  L->getHeader())
7966               << "interleaved loop (interleaved count: "
7967               << NV("InterleaveCount", IC) << ")");
7968   } else {
7969     // If we decided that it is *legal* to vectorize the loop, then do it.
7970     InnerLoopVectorizer LB(L, PSE, LI, DT, TLI, TTI, AC, ORE, VF.Width, IC,
7971                            &LVL, &CM);
7972     LVP.executePlan(LB);
7973     ++LoopsVectorized;
7974
7975     // Add metadata to disable runtime unrolling a scalar loop when there are
7976     // no runtime checks about strides and memory. A scalar loop that is
7977     // rarely used is not worth unrolling.
7978     if (!LB.areSafetyChecksAdded())
7979       AddRuntimeUnrollDisableMetaData(L);
7980
7981     // Report the vectorization decision.
7982     ORE->emit(OptimizationRemark(LV_NAME, "Vectorized", L->getStartLoc(),
7983                                  L->getHeader())
7984               << "vectorized loop (vectorization width: "
7985               << NV("VectorizationFactor", VF.Width)
7986               << ", interleaved count: " << NV("InterleaveCount", IC) << ")");
7987   }
7988
7989   // Mark the loop as already vectorized to avoid vectorizing again.
7990   Hints.setAlreadyVectorized();
7991
7992   DEBUG(verifyFunction(*L->getHeader()->getParent()));
7993   return true;
7994 }
7995
7996 bool LoopVectorizePass::runImpl(
7997     Function &F, ScalarEvolution &SE_, LoopInfo &LI_, TargetTransformInfo &TTI_,
7998     DominatorTree &DT_, BlockFrequencyInfo &BFI_, TargetLibraryInfo *TLI_,
7999     DemandedBits &DB_, AliasAnalysis &AA_, AssumptionCache &AC_,
8000     std::function<const LoopAccessInfo &(Loop &)> &GetLAA_,
8001     OptimizationRemarkEmitter &ORE_) {
8002
8003   SE = &SE_;
8004   LI = &LI_;
8005   TTI = &TTI_;
8006   DT = &DT_;
8007   BFI = &BFI_;
8008   TLI = TLI_;
8009   AA = &AA_;
8010   AC = &AC_;
8011   GetLAA = &GetLAA_;
8012   DB = &DB_;
8013   ORE = &ORE_;
8014
8015   // Compute some weights outside of the loop over the loops. Compute this
8016   // using a BranchProbability to re-use its scaling math.
8017   const BranchProbability ColdProb(1, 5); // 20%
8018   ColdEntryFreq = BlockFrequency(BFI->getEntryFreq()) * ColdProb;
8019
8020   // Don't attempt if
8021   // 1. the target claims to have no vector registers, and
8022   // 2. interleaving won't help ILP.
8023   //
8024   // The second condition is necessary because, even if the target has no
8025   // vector registers, loop vectorization may still enable scalar
8026   // interleaving.
8027   if (!TTI->getNumberOfRegisters(true) && TTI->getMaxInterleaveFactor(1) < 2)
8028     return false;
8029
8030   bool Changed = false;
8031
8032   // The vectorizer requires loops to be in simplified form.
8033   // Since simplification may add new inner loops, it has to run before the
8034   // legality and profitability checks. This means running the loop vectorizer
8035   // will simplify all loops, regardless of whether anything end up being
8036   // vectorized.
8037   for (auto &L : *LI)
8038     Changed |= simplifyLoop(L, DT, LI, SE, AC, false /* PreserveLCSSA */);
8039
8040   // Build up a worklist of inner-loops to vectorize. This is necessary as
8041   // the act of vectorizing or partially unrolling a loop creates new loops
8042   // and can invalidate iterators across the loops.
8043   SmallVector<Loop *, 8> Worklist;
8044
8045   for (Loop *L : *LI)
8046     addAcyclicInnerLoop(*L, Worklist);
8047
8048   LoopsAnalyzed += Worklist.size();
8049
8050   // Now walk the identified inner loops.
8051   while (!Worklist.empty()) {
8052     Loop *L = Worklist.pop_back_val();
8053
8054     // For the inner loops we actually process, form LCSSA to simplify the
8055     // transform.
8056     Changed |= formLCSSARecursively(*L, *DT, LI, SE);
8057
8058     Changed |= processLoop(L);
8059   }
8060
8061   // Process each loop nest in the function.
8062   return Changed;
8063
8064 }
8065
8066
8067 PreservedAnalyses LoopVectorizePass::run(Function &F,
8068                                          FunctionAnalysisManager &AM) {
8069     auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
8070     auto &LI = AM.getResult<LoopAnalysis>(F);
8071     auto &TTI = AM.getResult<TargetIRAnalysis>(F);
8072     auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
8073     auto &BFI = AM.getResult<BlockFrequencyAnalysis>(F);
8074     auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
8075     auto &AA = AM.getResult<AAManager>(F);
8076     auto &AC = AM.getResult<AssumptionAnalysis>(F);
8077     auto &DB = AM.getResult<DemandedBitsAnalysis>(F);
8078     auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
8079
8080     auto &LAM = AM.getResult<LoopAnalysisManagerFunctionProxy>(F).getManager();
8081     std::function<const LoopAccessInfo &(Loop &)> GetLAA =
8082         [&](Loop &L) -> const LoopAccessInfo & {
8083       LoopStandardAnalysisResults AR = {AA, AC, DT, LI, SE, TLI, TTI};
8084       return LAM.getResult<LoopAccessAnalysis>(L, AR);
8085     };
8086     bool Changed =
8087         runImpl(F, SE, LI, TTI, DT, BFI, &TLI, DB, AA, AC, GetLAA, ORE);
8088     if (!Changed)
8089       return PreservedAnalyses::all();
8090     PreservedAnalyses PA;
8091     PA.preserve<LoopAnalysis>();
8092     PA.preserve<DominatorTreeAnalysis>();
8093     PA.preserve<BasicAA>();
8094     PA.preserve<GlobalsAA>();
8095     return PA;
8096 }