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