1 //===- LoopVectorize.cpp - A Loop Vectorizer ------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This is the LLVM loop vectorizer. This pass modifies 'vectorizable' loops
10 // and generates target-independent LLVM-IR.
11 // The vectorizer uses the TargetTransformInfo analysis to estimate the costs
12 // of instructions in order to estimate the profitability of vectorization.
13 //
14 // The loop vectorizer combines consecutive loop iterations into a single
15 // 'wide' iteration. After this transformation the index is incremented
16 // by the SIMD vector width, and not by one.
17 //
18 // This pass has three parts:
19 // 1. The main loop pass that drives the different parts.
20 // 2. LoopVectorizationLegality - A unit that checks for the legality
21 //    of the vectorization.
22 // 3. InnerLoopVectorizer - A unit that performs the actual
23 //    widening of instructions.
24 // 4. LoopVectorizationCostModel - A unit that checks for the profitability
25 //    of vectorization. It decides on the optimal vector width, which
26 //    can be one, if vectorization is not profitable.
27 //
28 // There is a development effort going on to migrate loop vectorizer to the
29 // VPlan infrastructure and to introduce outer loop vectorization support (see
30 // docs/Proposal/VectorizationPlan.rst and
31 // http://lists.llvm.org/pipermail/llvm-dev/2017-December/119523.html). For this
32 // purpose, we temporarily introduced the VPlan-native vectorization path: an
33 // alternative vectorization path that is natively implemented on top of the
34 // VPlan infrastructure. See EnableVPlanNativePath for enabling.
35 //
36 //===----------------------------------------------------------------------===//
37 //
38 // The reduction-variable vectorization is based on the paper:
39 //  D. Nuzman and R. Henderson. Multi-platform Auto-vectorization.
40 //
41 // Variable uniformity checks are inspired by:
42 //  Karrenberg, R. and Hack, S. Whole Function Vectorization.
43 //
44 // The interleaved access vectorization is based on the paper:
45 //  Dorit Nuzman, Ira Rosen and Ayal Zaks.  Auto-Vectorization of Interleaved
46 //  Data for SIMD
47 //
48 // Other ideas/concepts are from:
49 //  A. Zaks and D. Nuzman. Autovectorization in GCC-two years later.
50 //
51 //  S. Maleki, Y. Gao, M. Garzaran, T. Wong and D. Padua.  An Evaluation of
52 //  Vectorizing Compilers.
53 //
54 //===----------------------------------------------------------------------===//
55 
56 #include "llvm/Transforms/Vectorize/LoopVectorize.h"
57 #include "LoopVectorizationPlanner.h"
58 #include "VPRecipeBuilder.h"
59 #include "VPlan.h"
60 #include "VPlanHCFGBuilder.h"
61 #include "VPlanPredicator.h"
62 #include "VPlanTransforms.h"
63 #include "llvm/ADT/APInt.h"
64 #include "llvm/ADT/ArrayRef.h"
65 #include "llvm/ADT/DenseMap.h"
66 #include "llvm/ADT/DenseMapInfo.h"
67 #include "llvm/ADT/Hashing.h"
68 #include "llvm/ADT/MapVector.h"
69 #include "llvm/ADT/None.h"
70 #include "llvm/ADT/Optional.h"
71 #include "llvm/ADT/STLExtras.h"
72 #include "llvm/ADT/SetVector.h"
73 #include "llvm/ADT/SmallPtrSet.h"
74 #include "llvm/ADT/SmallVector.h"
75 #include "llvm/ADT/Statistic.h"
76 #include "llvm/ADT/StringRef.h"
77 #include "llvm/ADT/Twine.h"
78 #include "llvm/ADT/iterator_range.h"
79 #include "llvm/Analysis/AssumptionCache.h"
80 #include "llvm/Analysis/BasicAliasAnalysis.h"
81 #include "llvm/Analysis/BlockFrequencyInfo.h"
82 #include "llvm/Analysis/CFG.h"
83 #include "llvm/Analysis/CodeMetrics.h"
84 #include "llvm/Analysis/DemandedBits.h"
85 #include "llvm/Analysis/GlobalsModRef.h"
86 #include "llvm/Analysis/LoopAccessAnalysis.h"
87 #include "llvm/Analysis/LoopAnalysisManager.h"
88 #include "llvm/Analysis/LoopInfo.h"
89 #include "llvm/Analysis/LoopIterator.h"
90 #include "llvm/Analysis/MemorySSA.h"
91 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
92 #include "llvm/Analysis/ProfileSummaryInfo.h"
93 #include "llvm/Analysis/ScalarEvolution.h"
94 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
95 #include "llvm/Analysis/TargetLibraryInfo.h"
96 #include "llvm/Analysis/TargetTransformInfo.h"
97 #include "llvm/Analysis/VectorUtils.h"
98 #include "llvm/IR/Attributes.h"
99 #include "llvm/IR/BasicBlock.h"
100 #include "llvm/IR/CFG.h"
101 #include "llvm/IR/Constant.h"
102 #include "llvm/IR/Constants.h"
103 #include "llvm/IR/DataLayout.h"
104 #include "llvm/IR/DebugInfoMetadata.h"
105 #include "llvm/IR/DebugLoc.h"
106 #include "llvm/IR/DerivedTypes.h"
107 #include "llvm/IR/DiagnosticInfo.h"
108 #include "llvm/IR/Dominators.h"
109 #include "llvm/IR/Function.h"
110 #include "llvm/IR/IRBuilder.h"
111 #include "llvm/IR/InstrTypes.h"
112 #include "llvm/IR/Instruction.h"
113 #include "llvm/IR/Instructions.h"
114 #include "llvm/IR/IntrinsicInst.h"
115 #include "llvm/IR/Intrinsics.h"
116 #include "llvm/IR/LLVMContext.h"
117 #include "llvm/IR/Metadata.h"
118 #include "llvm/IR/Module.h"
119 #include "llvm/IR/Operator.h"
120 #include "llvm/IR/Type.h"
121 #include "llvm/IR/Use.h"
122 #include "llvm/IR/User.h"
123 #include "llvm/IR/Value.h"
124 #include "llvm/IR/ValueHandle.h"
125 #include "llvm/IR/Verifier.h"
126 #include "llvm/InitializePasses.h"
127 #include "llvm/Pass.h"
128 #include "llvm/Support/Casting.h"
129 #include "llvm/Support/CommandLine.h"
130 #include "llvm/Support/Compiler.h"
131 #include "llvm/Support/Debug.h"
132 #include "llvm/Support/ErrorHandling.h"
133 #include "llvm/Support/InstructionCost.h"
134 #include "llvm/Support/MathExtras.h"
135 #include "llvm/Support/raw_ostream.h"
136 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
137 #include "llvm/Transforms/Utils/InjectTLIMappings.h"
138 #include "llvm/Transforms/Utils/LoopSimplify.h"
139 #include "llvm/Transforms/Utils/LoopUtils.h"
140 #include "llvm/Transforms/Utils/LoopVersioning.h"
141 #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
142 #include "llvm/Transforms/Utils/SizeOpts.h"
143 #include "llvm/Transforms/Vectorize/LoopVectorizationLegality.h"
144 #include <algorithm>
145 #include <cassert>
146 #include <cstdint>
147 #include <cstdlib>
148 #include <functional>
149 #include <iterator>
150 #include <limits>
151 #include <memory>
152 #include <string>
153 #include <tuple>
154 #include <utility>
155 
156 using namespace llvm;
157 
158 #define LV_NAME "loop-vectorize"
159 #define DEBUG_TYPE LV_NAME
160 
161 #ifndef NDEBUG
162 const char VerboseDebug[] = DEBUG_TYPE "-verbose";
163 #endif
164 
165 /// @{
166 /// Metadata attribute names
167 const char LLVMLoopVectorizeFollowupAll[] = "llvm.loop.vectorize.followup_all";
168 const char LLVMLoopVectorizeFollowupVectorized[] =
169     "llvm.loop.vectorize.followup_vectorized";
170 const char LLVMLoopVectorizeFollowupEpilogue[] =
171     "llvm.loop.vectorize.followup_epilogue";
172 /// @}
173 
174 STATISTIC(LoopsVectorized, "Number of loops vectorized");
175 STATISTIC(LoopsAnalyzed, "Number of loops analyzed for vectorization");
176 STATISTIC(LoopsEpilogueVectorized, "Number of epilogues vectorized");
177 
178 static cl::opt<bool> EnableEpilogueVectorization(
179     "enable-epilogue-vectorization", cl::init(true), cl::Hidden,
180     cl::desc("Enable vectorization of epilogue loops."));
181 
182 static cl::opt<unsigned> EpilogueVectorizationForceVF(
183     "epilogue-vectorization-force-VF", cl::init(1), cl::Hidden,
184     cl::desc("When epilogue vectorization is enabled, and a value greater than "
185              "1 is specified, forces the given VF for all applicable epilogue "
186              "loops."));
187 
188 static cl::opt<unsigned> EpilogueVectorizationMinVF(
189     "epilogue-vectorization-minimum-VF", cl::init(16), cl::Hidden,
190     cl::desc("Only loops with vectorization factor equal to or larger than "
191              "the specified value are considered for epilogue vectorization."));
192 
193 /// Loops with a known constant trip count below this number are vectorized only
194 /// if no scalar iteration overheads are incurred.
195 static cl::opt<unsigned> TinyTripCountVectorThreshold(
196     "vectorizer-min-trip-count", cl::init(16), cl::Hidden,
197     cl::desc("Loops with a constant trip count that is smaller than this "
198              "value are vectorized only if no scalar iteration overheads "
199              "are incurred."));
200 
201 // Option prefer-predicate-over-epilogue indicates that an epilogue is undesired,
202 // that predication is preferred, and this lists all options. I.e., the
203 // vectorizer will try to fold the tail-loop (epilogue) into the vector body
204 // and predicate the instructions accordingly. If tail-folding fails, there are
205 // different fallback strategies depending on these values:
206 namespace PreferPredicateTy {
207   enum Option {
208     ScalarEpilogue = 0,
209     PredicateElseScalarEpilogue,
210     PredicateOrDontVectorize
211   };
212 } // namespace PreferPredicateTy
213 
214 static cl::opt<PreferPredicateTy::Option> PreferPredicateOverEpilogue(
215     "prefer-predicate-over-epilogue",
216     cl::init(PreferPredicateTy::ScalarEpilogue),
217     cl::Hidden,
218     cl::desc("Tail-folding and predication preferences over creating a scalar "
219              "epilogue loop."),
220     cl::values(clEnumValN(PreferPredicateTy::ScalarEpilogue,
221                          "scalar-epilogue",
222                          "Don't tail-predicate loops, create scalar epilogue"),
223               clEnumValN(PreferPredicateTy::PredicateElseScalarEpilogue,
224                          "predicate-else-scalar-epilogue",
225                          "prefer tail-folding, create scalar epilogue if tail "
226                          "folding fails."),
227               clEnumValN(PreferPredicateTy::PredicateOrDontVectorize,
228                          "predicate-dont-vectorize",
229                          "prefers tail-folding, don't attempt vectorization if "
230                          "tail-folding fails.")));
231 
232 static cl::opt<bool> MaximizeBandwidth(
233     "vectorizer-maximize-bandwidth", cl::init(false), cl::Hidden,
234     cl::desc("Maximize bandwidth when selecting vectorization factor which "
235              "will be determined by the smallest type in loop."));
236 
237 static cl::opt<bool> EnableInterleavedMemAccesses(
238     "enable-interleaved-mem-accesses", cl::init(false), cl::Hidden,
239     cl::desc("Enable vectorization on interleaved memory accesses in a loop"));
240 
241 /// An interleave-group may need masking if it resides in a block that needs
242 /// predication, or in order to mask away gaps.
243 static cl::opt<bool> EnableMaskedInterleavedMemAccesses(
244     "enable-masked-interleaved-mem-accesses", cl::init(false), cl::Hidden,
245     cl::desc("Enable vectorization on masked interleaved memory accesses in a loop"));
246 
247 static cl::opt<unsigned> TinyTripCountInterleaveThreshold(
248     "tiny-trip-count-interleave-threshold", cl::init(128), cl::Hidden,
249     cl::desc("We don't interleave loops with a estimated constant trip count "
250              "below this number"));
251 
252 static cl::opt<unsigned> ForceTargetNumScalarRegs(
253     "force-target-num-scalar-regs", cl::init(0), cl::Hidden,
254     cl::desc("A flag that overrides the target's number of scalar registers."));
255 
256 static cl::opt<unsigned> ForceTargetNumVectorRegs(
257     "force-target-num-vector-regs", cl::init(0), cl::Hidden,
258     cl::desc("A flag that overrides the target's number of vector registers."));
259 
260 static cl::opt<unsigned> ForceTargetMaxScalarInterleaveFactor(
261     "force-target-max-scalar-interleave", cl::init(0), cl::Hidden,
262     cl::desc("A flag that overrides the target's max interleave factor for "
263              "scalar loops."));
264 
265 static cl::opt<unsigned> ForceTargetMaxVectorInterleaveFactor(
266     "force-target-max-vector-interleave", cl::init(0), cl::Hidden,
267     cl::desc("A flag that overrides the target's max interleave factor for "
268              "vectorized loops."));
269 
270 static cl::opt<unsigned> ForceTargetInstructionCost(
271     "force-target-instruction-cost", cl::init(0), cl::Hidden,
272     cl::desc("A flag that overrides the target's expected cost for "
273              "an instruction to a single constant value. Mostly "
274              "useful for getting consistent testing."));
275 
276 static cl::opt<bool> ForceTargetSupportsScalableVectors(
277     "force-target-supports-scalable-vectors", cl::init(false), cl::Hidden,
278     cl::desc(
279         "Pretend that scalable vectors are supported, even if the target does "
280         "not support them. This flag should only be used for testing."));
281 
282 static cl::opt<unsigned> SmallLoopCost(
283     "small-loop-cost", cl::init(20), cl::Hidden,
284     cl::desc(
285         "The cost of a loop that is considered 'small' by the interleaver."));
286 
287 static cl::opt<bool> LoopVectorizeWithBlockFrequency(
288     "loop-vectorize-with-block-frequency", cl::init(true), cl::Hidden,
289     cl::desc("Enable the use of the block frequency analysis to access PGO "
290              "heuristics minimizing code growth in cold regions and being more "
291              "aggressive in hot regions."));
292 
293 // Runtime interleave loops for load/store throughput.
294 static cl::opt<bool> EnableLoadStoreRuntimeInterleave(
295     "enable-loadstore-runtime-interleave", cl::init(true), cl::Hidden,
296     cl::desc(
297         "Enable runtime interleaving until load/store ports are saturated"));
298 
299 /// Interleave small loops with scalar reductions.
300 static cl::opt<bool> InterleaveSmallLoopScalarReduction(
301     "interleave-small-loop-scalar-reduction", cl::init(false), cl::Hidden,
302     cl::desc("Enable interleaving for loops with small iteration counts that "
303              "contain scalar reductions to expose ILP."));
304 
305 /// The number of stores in a loop that are allowed to need predication.
306 static cl::opt<unsigned> NumberOfStoresToPredicate(
307     "vectorize-num-stores-pred", cl::init(1), cl::Hidden,
308     cl::desc("Max number of stores to be predicated behind an if."));
309 
310 static cl::opt<bool> EnableIndVarRegisterHeur(
311     "enable-ind-var-reg-heur", cl::init(true), cl::Hidden,
312     cl::desc("Count the induction variable only once when interleaving"));
313 
314 static cl::opt<bool> EnableCondStoresVectorization(
315     "enable-cond-stores-vec", cl::init(true), cl::Hidden,
316     cl::desc("Enable if predication of stores during vectorization."));
317 
318 static cl::opt<unsigned> MaxNestedScalarReductionIC(
319     "max-nested-scalar-reduction-interleave", cl::init(2), cl::Hidden,
320     cl::desc("The maximum interleave count to use when interleaving a scalar "
321              "reduction in a nested loop."));
322 
323 static cl::opt<bool>
324     PreferInLoopReductions("prefer-inloop-reductions", cl::init(false),
325                            cl::Hidden,
326                            cl::desc("Prefer in-loop vector reductions, "
327                                     "overriding the targets preference."));
328 
329 static cl::opt<bool> PreferPredicatedReductionSelect(
330     "prefer-predicated-reduction-select", cl::init(false), cl::Hidden,
331     cl::desc(
332         "Prefer predicating a reduction operation over an after loop select."));
333 
334 cl::opt<bool> EnableVPlanNativePath(
335     "enable-vplan-native-path", cl::init(false), cl::Hidden,
336     cl::desc("Enable VPlan-native vectorization path with "
337              "support for outer loop vectorization."));
338 
339 // FIXME: Remove this switch once we have divergence analysis. Currently we
340 // assume divergent non-backedge branches when this switch is true.
341 cl::opt<bool> EnableVPlanPredication(
342     "enable-vplan-predication", cl::init(false), cl::Hidden,
343     cl::desc("Enable VPlan-native vectorization path predicator with "
344              "support for outer loop vectorization."));
345 
346 // This flag enables the stress testing of the VPlan H-CFG construction in the
347 // VPlan-native vectorization path. It must be used in conjuction with
348 // -enable-vplan-native-path. -vplan-verify-hcfg can also be used to enable the
349 // verification of the H-CFGs built.
350 static cl::opt<bool> VPlanBuildStressTest(
351     "vplan-build-stress-test", cl::init(false), cl::Hidden,
352     cl::desc(
353         "Build VPlan for every supported loop nest in the function and bail "
354         "out right after the build (stress test the VPlan H-CFG construction "
355         "in the VPlan-native vectorization path)."));
356 
357 cl::opt<bool> llvm::EnableLoopInterleaving(
358     "interleave-loops", cl::init(true), cl::Hidden,
359     cl::desc("Enable loop interleaving in Loop vectorization passes"));
360 cl::opt<bool> llvm::EnableLoopVectorization(
361     "vectorize-loops", cl::init(true), cl::Hidden,
362     cl::desc("Run the Loop vectorization passes"));
363 
364 /// A helper function that returns the type of loaded or stored value.
365 static Type *getMemInstValueType(Value *I) {
366   assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
367          "Expected Load or Store instruction");
368   if (auto *LI = dyn_cast<LoadInst>(I))
369     return LI->getType();
370   return cast<StoreInst>(I)->getValueOperand()->getType();
371 }
372 
373 /// A helper function that returns true if the given type is irregular. The
374 /// type is irregular if its allocated size doesn't equal the store size of an
375 /// element of the corresponding vector type at the given vectorization factor.
376 static bool hasIrregularType(Type *Ty, const DataLayout &DL, ElementCount VF) {
377   // Determine if an array of VF elements of type Ty is "bitcast compatible"
378   // with a <VF x Ty> vector.
379   if (VF.isVector()) {
380     auto *VectorTy = VectorType::get(Ty, VF);
381     return TypeSize::get(VF.getKnownMinValue() *
382                              DL.getTypeAllocSize(Ty).getFixedValue(),
383                          VF.isScalable()) != DL.getTypeStoreSize(VectorTy);
384   }
385 
386   // If the vectorization factor is one, we just check if an array of type Ty
387   // requires padding between elements.
388   return DL.getTypeAllocSizeInBits(Ty) != DL.getTypeSizeInBits(Ty);
389 }
390 
391 /// A helper function that returns the reciprocal of the block probability of
392 /// predicated blocks. If we return X, we are assuming the predicated block
393 /// will execute once for every X iterations of the loop header.
394 ///
395 /// TODO: We should use actual block probability here, if available. Currently,
396 ///       we always assume predicated blocks have a 50% chance of executing.
397 static unsigned getReciprocalPredBlockProb() { return 2; }
398 
399 /// A helper function that adds a 'fast' flag to floating-point operations.
400 static Value *addFastMathFlag(Value *V) {
401   if (isa<FPMathOperator>(V))
402     cast<Instruction>(V)->setFastMathFlags(FastMathFlags::getFast());
403   return V;
404 }
405 
406 /// A helper function that returns an integer or floating-point constant with
407 /// value C.
408 static Constant *getSignedIntOrFpConstant(Type *Ty, int64_t C) {
409   return Ty->isIntegerTy() ? ConstantInt::getSigned(Ty, C)
410                            : ConstantFP::get(Ty, C);
411 }
412 
413 /// Returns "best known" trip count for the specified loop \p L as defined by
414 /// the following procedure:
415 ///   1) Returns exact trip count if it is known.
416 ///   2) Returns expected trip count according to profile data if any.
417 ///   3) Returns upper bound estimate if it is known.
418 ///   4) Returns None if all of the above failed.
419 static Optional<unsigned> getSmallBestKnownTC(ScalarEvolution &SE, Loop *L) {
420   // Check if exact trip count is known.
421   if (unsigned ExpectedTC = SE.getSmallConstantTripCount(L))
422     return ExpectedTC;
423 
424   // Check if there is an expected trip count available from profile data.
425   if (LoopVectorizeWithBlockFrequency)
426     if (auto EstimatedTC = getLoopEstimatedTripCount(L))
427       return EstimatedTC;
428 
429   // Check if upper bound estimate is known.
430   if (unsigned ExpectedTC = SE.getSmallConstantMaxTripCount(L))
431     return ExpectedTC;
432 
433   return None;
434 }
435 
436 namespace llvm {
437 
438 /// InnerLoopVectorizer vectorizes loops which contain only one basic
439 /// block to a specified vectorization factor (VF).
440 /// This class performs the widening of scalars into vectors, or multiple
441 /// scalars. This class also implements the following features:
442 /// * It inserts an epilogue loop for handling loops that don't have iteration
443 ///   counts that are known to be a multiple of the vectorization factor.
444 /// * It handles the code generation for reduction variables.
445 /// * Scalarization (implementation using scalars) of un-vectorizable
446 ///   instructions.
447 /// InnerLoopVectorizer does not perform any vectorization-legality
448 /// checks, and relies on the caller to check for the different legality
449 /// aspects. The InnerLoopVectorizer relies on the
450 /// LoopVectorizationLegality class to provide information about the induction
451 /// and reduction variables that were found to a given vectorization factor.
452 class InnerLoopVectorizer {
453 public:
454   InnerLoopVectorizer(Loop *OrigLoop, PredicatedScalarEvolution &PSE,
455                       LoopInfo *LI, DominatorTree *DT,
456                       const TargetLibraryInfo *TLI,
457                       const TargetTransformInfo *TTI, AssumptionCache *AC,
458                       OptimizationRemarkEmitter *ORE, ElementCount VecWidth,
459                       unsigned UnrollFactor, LoopVectorizationLegality *LVL,
460                       LoopVectorizationCostModel *CM, BlockFrequencyInfo *BFI,
461                       ProfileSummaryInfo *PSI)
462       : OrigLoop(OrigLoop), PSE(PSE), LI(LI), DT(DT), TLI(TLI), TTI(TTI),
463         AC(AC), ORE(ORE), VF(VecWidth), UF(UnrollFactor),
464         Builder(PSE.getSE()->getContext()),
465         VectorLoopValueMap(UnrollFactor, VecWidth), Legal(LVL), Cost(CM),
466         BFI(BFI), PSI(PSI) {
467     // Query this against the original loop and save it here because the profile
468     // of the original loop header may change as the transformation happens.
469     OptForSizeBasedOnProfile = llvm::shouldOptimizeForSize(
470         OrigLoop->getHeader(), PSI, BFI, PGSOQueryType::IRPass);
471   }
472 
473   virtual ~InnerLoopVectorizer() = default;
474 
475   /// Create a new empty loop that will contain vectorized instructions later
476   /// on, while the old loop will be used as the scalar remainder. Control flow
477   /// is generated around the vectorized (and scalar epilogue) loops consisting
478   /// of various checks and bypasses. Return the pre-header block of the new
479   /// loop.
480   /// In the case of epilogue vectorization, this function is overriden to
481   /// handle the more complex control flow around the loops.
482   virtual BasicBlock *createVectorizedLoopSkeleton();
483 
484   /// Widen a single instruction within the innermost loop.
485   void widenInstruction(Instruction &I, VPValue *Def, VPUser &Operands,
486                         VPTransformState &State);
487 
488   /// Widen a single call instruction within the innermost loop.
489   void widenCallInstruction(CallInst &I, VPValue *Def, VPUser &ArgOperands,
490                             VPTransformState &State);
491 
492   /// Widen a single select instruction within the innermost loop.
493   void widenSelectInstruction(SelectInst &I, VPValue *VPDef, VPUser &Operands,
494                               bool InvariantCond, VPTransformState &State);
495 
496   /// Fix the vectorized code, taking care of header phi's, live-outs, and more.
497   void fixVectorizedLoop(VPTransformState &State);
498 
499   // Return true if any runtime check is added.
500   bool areSafetyChecksAdded() { return AddedSafetyChecks; }
501 
502   /// A type for vectorized values in the new loop. Each value from the
503   /// original loop, when vectorized, is represented by UF vector values in the
504   /// new unrolled loop, where UF is the unroll factor.
505   using VectorParts = SmallVector<Value *, 2>;
506 
507   /// Vectorize a single GetElementPtrInst based on information gathered and
508   /// decisions taken during planning.
509   void widenGEP(GetElementPtrInst *GEP, VPValue *VPDef, VPUser &Indices,
510                 unsigned UF, ElementCount VF, bool IsPtrLoopInvariant,
511                 SmallBitVector &IsIndexLoopInvariant, VPTransformState &State);
512 
513   /// Vectorize a single PHINode in a block. This method handles the induction
514   /// variable canonicalization. It supports both VF = 1 for unrolled loops and
515   /// arbitrary length vectors.
516   void widenPHIInstruction(Instruction *PN, RecurrenceDescriptor *RdxDesc,
517                            Value *StartV, unsigned UF, ElementCount VF);
518 
519   /// A helper function to scalarize a single Instruction in the innermost loop.
520   /// Generates a sequence of scalar instances for each lane between \p MinLane
521   /// and \p MaxLane, times each part between \p MinPart and \p MaxPart,
522   /// inclusive. Uses the VPValue operands from \p Operands instead of \p
523   /// Instr's operands.
524   void scalarizeInstruction(Instruction *Instr, VPUser &Operands,
525                             const VPIteration &Instance, bool IfPredicateInstr,
526                             VPTransformState &State);
527 
528   /// Widen an integer or floating-point induction variable \p IV. If \p Trunc
529   /// is provided, the integer induction variable will first be truncated to
530   /// the corresponding type.
531   void widenIntOrFpInduction(PHINode *IV, Value *Start, TruncInst *Trunc,
532                              VPValue *Def, VPValue *CastDef,
533                              VPTransformState &State);
534 
535   /// getOrCreateVectorValue and getOrCreateScalarValue coordinate to generate a
536   /// vector or scalar value on-demand if one is not yet available. When
537   /// vectorizing a loop, we visit the definition of an instruction before its
538   /// uses. When visiting the definition, we either vectorize or scalarize the
539   /// instruction, creating an entry for it in the corresponding map. (In some
540   /// cases, such as induction variables, we will create both vector and scalar
541   /// entries.) Then, as we encounter uses of the definition, we derive values
542   /// for each scalar or vector use unless such a value is already available.
543   /// For example, if we scalarize a definition and one of its uses is vector,
544   /// we build the required vector on-demand with an insertelement sequence
545   /// when visiting the use. Otherwise, if the use is scalar, we can use the
546   /// existing scalar definition.
547   ///
548   /// Return a value in the new loop corresponding to \p V from the original
549   /// loop at unroll index \p Part. If the value has already been vectorized,
550   /// the corresponding vector entry in VectorLoopValueMap is returned. If,
551   /// however, the value has a scalar entry in VectorLoopValueMap, we construct
552   /// a new vector value on-demand by inserting the scalar values into a vector
553   /// with an insertelement sequence. If the value has been neither vectorized
554   /// nor scalarized, it must be loop invariant, so we simply broadcast the
555   /// value into a vector.
556   Value *getOrCreateVectorValue(Value *V, unsigned Part);
557 
558   void setVectorValue(Value *Scalar, unsigned Part, Value *Vector) {
559     VectorLoopValueMap.setVectorValue(Scalar, Part, Vector);
560   }
561 
562   void resetVectorValue(Value *Scalar, unsigned Part, Value *Vector) {
563     VectorLoopValueMap.resetVectorValue(Scalar, Part, Vector);
564   }
565 
566   void setScalarValue(Value *Scalar, const VPIteration &Instance, Value *V) {
567     VectorLoopValueMap.setScalarValue(Scalar, Instance, V);
568   }
569 
570   /// Return a value in the new loop corresponding to \p V from the original
571   /// loop at unroll and vector indices \p Instance. If the value has been
572   /// vectorized but not scalarized, the necessary extractelement instruction
573   /// will be generated.
574   Value *getOrCreateScalarValue(Value *V, const VPIteration &Instance);
575 
576   /// Construct the vector value of a scalarized value \p V one lane at a time.
577   void packScalarIntoVectorValue(Value *V, const VPIteration &Instance);
578 
579   void packScalarIntoVectorValue(VPValue *Def, const VPIteration &Instance,
580                                  VPTransformState &State);
581 
582   /// Try to vectorize interleaved access group \p Group with the base address
583   /// given in \p Addr, optionally masking the vector operations if \p
584   /// BlockInMask is non-null. Use \p State to translate given VPValues to IR
585   /// values in the vectorized loop.
586   void vectorizeInterleaveGroup(const InterleaveGroup<Instruction> *Group,
587                                 ArrayRef<VPValue *> VPDefs,
588                                 VPTransformState &State, VPValue *Addr,
589                                 ArrayRef<VPValue *> StoredValues,
590                                 VPValue *BlockInMask = nullptr);
591 
592   /// Vectorize Load and Store instructions with the base address given in \p
593   /// Addr, optionally masking the vector operations if \p BlockInMask is
594   /// non-null. Use \p State to translate given VPValues to IR values in the
595   /// vectorized loop.
596   void vectorizeMemoryInstruction(Instruction *Instr, VPTransformState &State,
597                                   VPValue *Def, VPValue *Addr,
598                                   VPValue *StoredValue, VPValue *BlockInMask);
599 
600   /// Set the debug location in the builder using the debug location in
601   /// the instruction.
602   void setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr);
603 
604   /// Fix the non-induction PHIs in the OrigPHIsToFix vector.
605   void fixNonInductionPHIs(VPTransformState &State);
606 
607   /// Create a broadcast instruction. This method generates a broadcast
608   /// instruction (shuffle) for loop invariant values and for the induction
609   /// value. If this is the induction variable then we extend it to N, N+1, ...
610   /// this is needed because each iteration in the loop corresponds to a SIMD
611   /// element.
612   virtual Value *getBroadcastInstrs(Value *V);
613 
614 protected:
615   friend class LoopVectorizationPlanner;
616 
617   /// A small list of PHINodes.
618   using PhiVector = SmallVector<PHINode *, 4>;
619 
620   /// A type for scalarized values in the new loop. Each value from the
621   /// original loop, when scalarized, is represented by UF x VF scalar values
622   /// in the new unrolled loop, where UF is the unroll factor and VF is the
623   /// vectorization factor.
624   using ScalarParts = SmallVector<SmallVector<Value *, 4>, 2>;
625 
626   /// Set up the values of the IVs correctly when exiting the vector loop.
627   void fixupIVUsers(PHINode *OrigPhi, const InductionDescriptor &II,
628                     Value *CountRoundDown, Value *EndValue,
629                     BasicBlock *MiddleBlock);
630 
631   /// Create a new induction variable inside L.
632   PHINode *createInductionVariable(Loop *L, Value *Start, Value *End,
633                                    Value *Step, Instruction *DL);
634 
635   /// Handle all cross-iteration phis in the header.
636   void fixCrossIterationPHIs(VPTransformState &State);
637 
638   /// Fix a first-order recurrence. This is the second phase of vectorizing
639   /// this phi node.
640   void fixFirstOrderRecurrence(PHINode *Phi, VPTransformState &State);
641 
642   /// Fix a reduction cross-iteration phi. This is the second phase of
643   /// vectorizing this phi node.
644   void fixReduction(PHINode *Phi, VPTransformState &State);
645 
646   /// Clear NSW/NUW flags from reduction instructions if necessary.
647   void clearReductionWrapFlags(RecurrenceDescriptor &RdxDesc);
648 
649   /// Fixup the LCSSA phi nodes in the unique exit block.  This simply
650   /// means we need to add the appropriate incoming value from the middle
651   /// block as exiting edges from the scalar epilogue loop (if present) are
652   /// already in place, and we exit the vector loop exclusively to the middle
653   /// block.
654   void fixLCSSAPHIs(VPTransformState &State);
655 
656   /// Iteratively sink the scalarized operands of a predicated instruction into
657   /// the block that was created for it.
658   void sinkScalarOperands(Instruction *PredInst);
659 
660   /// Shrinks vector element sizes to the smallest bitwidth they can be legally
661   /// represented as.
662   void truncateToMinimalBitwidths();
663 
664   /// This function adds (StartIdx, StartIdx + Step, StartIdx + 2*Step, ...)
665   /// to each vector element of Val. The sequence starts at StartIndex.
666   /// \p Opcode is relevant for FP induction variable.
667   virtual Value *getStepVector(Value *Val, int StartIdx, Value *Step,
668                                Instruction::BinaryOps Opcode =
669                                Instruction::BinaryOpsEnd);
670 
671   /// Compute scalar induction steps. \p ScalarIV is the scalar induction
672   /// variable on which to base the steps, \p Step is the size of the step, and
673   /// \p EntryVal is the value from the original loop that maps to the steps.
674   /// Note that \p EntryVal doesn't have to be an induction variable - it
675   /// can also be a truncate instruction.
676   void buildScalarSteps(Value *ScalarIV, Value *Step, Instruction *EntryVal,
677                         const InductionDescriptor &ID, VPValue *Def,
678                         VPValue *CastDef, VPTransformState &State);
679 
680   /// Create a vector induction phi node based on an existing scalar one. \p
681   /// EntryVal is the value from the original loop that maps to the vector phi
682   /// node, and \p Step is the loop-invariant step. If \p EntryVal is a
683   /// truncate instruction, instead of widening the original IV, we widen a
684   /// version of the IV truncated to \p EntryVal's type.
685   void createVectorIntOrFpInductionPHI(const InductionDescriptor &II,
686                                        Value *Step, Value *Start,
687                                        Instruction *EntryVal, VPValue *Def,
688                                        VPValue *CastDef,
689                                        VPTransformState &State);
690 
691   /// Returns true if an instruction \p I should be scalarized instead of
692   /// vectorized for the chosen vectorization factor.
693   bool shouldScalarizeInstruction(Instruction *I) const;
694 
695   /// Returns true if we should generate a scalar version of \p IV.
696   bool needsScalarInduction(Instruction *IV) const;
697 
698   /// If there is a cast involved in the induction variable \p ID, which should
699   /// be ignored in the vectorized loop body, this function records the
700   /// VectorLoopValue of the respective Phi also as the VectorLoopValue of the
701   /// cast. We had already proved that the casted Phi is equal to the uncasted
702   /// Phi in the vectorized loop (under a runtime guard), and therefore
703   /// there is no need to vectorize the cast - the same value can be used in the
704   /// vector loop for both the Phi and the cast.
705   /// If \p VectorLoopValue is a scalarized value, \p Lane is also specified,
706   /// Otherwise, \p VectorLoopValue is a widened/vectorized value.
707   ///
708   /// \p EntryVal is the value from the original loop that maps to the vector
709   /// phi node and is used to distinguish what is the IV currently being
710   /// processed - original one (if \p EntryVal is a phi corresponding to the
711   /// original IV) or the "newly-created" one based on the proof mentioned above
712   /// (see also buildScalarSteps() and createVectorIntOrFPInductionPHI()). In the
713   /// latter case \p EntryVal is a TruncInst and we must not record anything for
714   /// that IV, but it's error-prone to expect callers of this routine to care
715   /// about that, hence this explicit parameter.
716   void recordVectorLoopValueForInductionCast(
717       const InductionDescriptor &ID, const Instruction *EntryVal,
718       Value *VectorLoopValue, VPValue *CastDef, VPTransformState &State,
719       unsigned Part, unsigned Lane = UINT_MAX);
720 
721   /// Generate a shuffle sequence that will reverse the vector Vec.
722   virtual Value *reverseVector(Value *Vec);
723 
724   /// Returns (and creates if needed) the original loop trip count.
725   Value *getOrCreateTripCount(Loop *NewLoop);
726 
727   /// Returns (and creates if needed) the trip count of the widened loop.
728   Value *getOrCreateVectorTripCount(Loop *NewLoop);
729 
730   /// Returns a bitcasted value to the requested vector type.
731   /// Also handles bitcasts of vector<float> <-> vector<pointer> types.
732   Value *createBitOrPointerCast(Value *V, VectorType *DstVTy,
733                                 const DataLayout &DL);
734 
735   /// Emit a bypass check to see if the vector trip count is zero, including if
736   /// it overflows.
737   void emitMinimumIterationCountCheck(Loop *L, BasicBlock *Bypass);
738 
739   /// Emit a bypass check to see if all of the SCEV assumptions we've
740   /// had to make are correct.
741   void emitSCEVChecks(Loop *L, BasicBlock *Bypass);
742 
743   /// Emit bypass checks to check any memory assumptions we may have made.
744   void emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass);
745 
746   /// Compute the transformed value of Index at offset StartValue using step
747   /// StepValue.
748   /// For integer induction, returns StartValue + Index * StepValue.
749   /// For pointer induction, returns StartValue[Index * StepValue].
750   /// FIXME: The newly created binary instructions should contain nsw/nuw
751   /// flags, which can be found from the original scalar operations.
752   Value *emitTransformedIndex(IRBuilder<> &B, Value *Index, ScalarEvolution *SE,
753                               const DataLayout &DL,
754                               const InductionDescriptor &ID) const;
755 
756   /// Emit basic blocks (prefixed with \p Prefix) for the iteration check,
757   /// vector loop preheader, middle block and scalar preheader. Also
758   /// allocate a loop object for the new vector loop and return it.
759   Loop *createVectorLoopSkeleton(StringRef Prefix);
760 
761   /// Create new phi nodes for the induction variables to resume iteration count
762   /// in the scalar epilogue, from where the vectorized loop left off (given by
763   /// \p VectorTripCount).
764   /// In cases where the loop skeleton is more complicated (eg. epilogue
765   /// vectorization) and the resume values can come from an additional bypass
766   /// block, the \p AdditionalBypass pair provides information about the bypass
767   /// block and the end value on the edge from bypass to this loop.
768   void createInductionResumeValues(
769       Loop *L, Value *VectorTripCount,
770       std::pair<BasicBlock *, Value *> AdditionalBypass = {nullptr, nullptr});
771 
772   /// Complete the loop skeleton by adding debug MDs, creating appropriate
773   /// conditional branches in the middle block, preparing the builder and
774   /// running the verifier. Take in the vector loop \p L as argument, and return
775   /// the preheader of the completed vector loop.
776   BasicBlock *completeLoopSkeleton(Loop *L, MDNode *OrigLoopID);
777 
778   /// Add additional metadata to \p To that was not present on \p Orig.
779   ///
780   /// Currently this is used to add the noalias annotations based on the
781   /// inserted memchecks.  Use this for instructions that are *cloned* into the
782   /// vector loop.
783   void addNewMetadata(Instruction *To, const Instruction *Orig);
784 
785   /// Add metadata from one instruction to another.
786   ///
787   /// This includes both the original MDs from \p From and additional ones (\see
788   /// addNewMetadata).  Use this for *newly created* instructions in the vector
789   /// loop.
790   void addMetadata(Instruction *To, Instruction *From);
791 
792   /// Similar to the previous function but it adds the metadata to a
793   /// vector of instructions.
794   void addMetadata(ArrayRef<Value *> To, Instruction *From);
795 
796   /// Allow subclasses to override and print debug traces before/after vplan
797   /// execution, when trace information is requested.
798   virtual void printDebugTracesAtStart(){};
799   virtual void printDebugTracesAtEnd(){};
800 
801   /// The original loop.
802   Loop *OrigLoop;
803 
804   /// A wrapper around ScalarEvolution used to add runtime SCEV checks. Applies
805   /// dynamic knowledge to simplify SCEV expressions and converts them to a
806   /// more usable form.
807   PredicatedScalarEvolution &PSE;
808 
809   /// Loop Info.
810   LoopInfo *LI;
811 
812   /// Dominator Tree.
813   DominatorTree *DT;
814 
815   /// Alias Analysis.
816   AAResults *AA;
817 
818   /// Target Library Info.
819   const TargetLibraryInfo *TLI;
820 
821   /// Target Transform Info.
822   const TargetTransformInfo *TTI;
823 
824   /// Assumption Cache.
825   AssumptionCache *AC;
826 
827   /// Interface to emit optimization remarks.
828   OptimizationRemarkEmitter *ORE;
829 
830   /// LoopVersioning.  It's only set up (non-null) if memchecks were
831   /// used.
832   ///
833   /// This is currently only used to add no-alias metadata based on the
834   /// memchecks.  The actually versioning is performed manually.
835   std::unique_ptr<LoopVersioning> LVer;
836 
837   /// The vectorization SIMD factor to use. Each vector will have this many
838   /// vector elements.
839   ElementCount VF;
840 
841   /// The vectorization unroll factor to use. Each scalar is vectorized to this
842   /// many different vector instructions.
843   unsigned UF;
844 
845   /// The builder that we use
846   IRBuilder<> Builder;
847 
848   // --- Vectorization state ---
849 
850   /// The vector-loop preheader.
851   BasicBlock *LoopVectorPreHeader;
852 
853   /// The scalar-loop preheader.
854   BasicBlock *LoopScalarPreHeader;
855 
856   /// Middle Block between the vector and the scalar.
857   BasicBlock *LoopMiddleBlock;
858 
859   /// The (unique) ExitBlock of the scalar loop.  Note that
860   /// there can be multiple exiting edges reaching this block.
861   BasicBlock *LoopExitBlock;
862 
863   /// The vector loop body.
864   BasicBlock *LoopVectorBody;
865 
866   /// The scalar loop body.
867   BasicBlock *LoopScalarBody;
868 
869   /// A list of all bypass blocks. The first block is the entry of the loop.
870   SmallVector<BasicBlock *, 4> LoopBypassBlocks;
871 
872   /// The new Induction variable which was added to the new block.
873   PHINode *Induction = nullptr;
874 
875   /// The induction variable of the old basic block.
876   PHINode *OldInduction = nullptr;
877 
878   /// Maps values from the original loop to their corresponding values in the
879   /// vectorized loop. A key value can map to either vector values, scalar
880   /// values or both kinds of values, depending on whether the key was
881   /// vectorized and scalarized.
882   VectorizerValueMap VectorLoopValueMap;
883 
884   /// Store instructions that were predicated.
885   SmallVector<Instruction *, 4> PredicatedInstructions;
886 
887   /// Trip count of the original loop.
888   Value *TripCount = nullptr;
889 
890   /// Trip count of the widened loop (TripCount - TripCount % (VF*UF))
891   Value *VectorTripCount = nullptr;
892 
893   /// The legality analysis.
894   LoopVectorizationLegality *Legal;
895 
896   /// The profitablity analysis.
897   LoopVectorizationCostModel *Cost;
898 
899   // Record whether runtime checks are added.
900   bool AddedSafetyChecks = false;
901 
902   // Holds the end values for each induction variable. We save the end values
903   // so we can later fix-up the external users of the induction variables.
904   DenseMap<PHINode *, Value *> IVEndValues;
905 
906   // Vector of original scalar PHIs whose corresponding widened PHIs need to be
907   // fixed up at the end of vector code generation.
908   SmallVector<PHINode *, 8> OrigPHIsToFix;
909 
910   /// BFI and PSI are used to check for profile guided size optimizations.
911   BlockFrequencyInfo *BFI;
912   ProfileSummaryInfo *PSI;
913 
914   // Whether this loop should be optimized for size based on profile guided size
915   // optimizatios.
916   bool OptForSizeBasedOnProfile;
917 };
918 
919 class InnerLoopUnroller : public InnerLoopVectorizer {
920 public:
921   InnerLoopUnroller(Loop *OrigLoop, PredicatedScalarEvolution &PSE,
922                     LoopInfo *LI, DominatorTree *DT,
923                     const TargetLibraryInfo *TLI,
924                     const TargetTransformInfo *TTI, AssumptionCache *AC,
925                     OptimizationRemarkEmitter *ORE, unsigned UnrollFactor,
926                     LoopVectorizationLegality *LVL,
927                     LoopVectorizationCostModel *CM, BlockFrequencyInfo *BFI,
928                     ProfileSummaryInfo *PSI)
929       : InnerLoopVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
930                             ElementCount::getFixed(1), UnrollFactor, LVL, CM,
931                             BFI, PSI) {}
932 
933 private:
934   Value *getBroadcastInstrs(Value *V) override;
935   Value *getStepVector(Value *Val, int StartIdx, Value *Step,
936                        Instruction::BinaryOps Opcode =
937                        Instruction::BinaryOpsEnd) override;
938   Value *reverseVector(Value *Vec) override;
939 };
940 
941 /// Encapsulate information regarding vectorization of a loop and its epilogue.
942 /// This information is meant to be updated and used across two stages of
943 /// epilogue vectorization.
944 struct EpilogueLoopVectorizationInfo {
945   ElementCount MainLoopVF = ElementCount::getFixed(0);
946   unsigned MainLoopUF = 0;
947   ElementCount EpilogueVF = ElementCount::getFixed(0);
948   unsigned EpilogueUF = 0;
949   BasicBlock *MainLoopIterationCountCheck = nullptr;
950   BasicBlock *EpilogueIterationCountCheck = nullptr;
951   BasicBlock *SCEVSafetyCheck = nullptr;
952   BasicBlock *MemSafetyCheck = nullptr;
953   Value *TripCount = nullptr;
954   Value *VectorTripCount = nullptr;
955 
956   EpilogueLoopVectorizationInfo(unsigned MVF, unsigned MUF, unsigned EVF,
957                                 unsigned EUF)
958       : MainLoopVF(ElementCount::getFixed(MVF)), MainLoopUF(MUF),
959         EpilogueVF(ElementCount::getFixed(EVF)), EpilogueUF(EUF) {
960     assert(EUF == 1 &&
961            "A high UF for the epilogue loop is likely not beneficial.");
962   }
963 };
964 
965 /// An extension of the inner loop vectorizer that creates a skeleton for a
966 /// vectorized loop that has its epilogue (residual) also vectorized.
967 /// The idea is to run the vplan on a given loop twice, firstly to setup the
968 /// skeleton and vectorize the main loop, and secondly to complete the skeleton
969 /// from the first step and vectorize the epilogue.  This is achieved by
970 /// deriving two concrete strategy classes from this base class and invoking
971 /// them in succession from the loop vectorizer planner.
972 class InnerLoopAndEpilogueVectorizer : public InnerLoopVectorizer {
973 public:
974   InnerLoopAndEpilogueVectorizer(
975       Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI,
976       DominatorTree *DT, const TargetLibraryInfo *TLI,
977       const TargetTransformInfo *TTI, AssumptionCache *AC,
978       OptimizationRemarkEmitter *ORE, EpilogueLoopVectorizationInfo &EPI,
979       LoopVectorizationLegality *LVL, llvm::LoopVectorizationCostModel *CM,
980       BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI)
981       : InnerLoopVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
982                             EPI.MainLoopVF, EPI.MainLoopUF, LVL, CM, BFI, PSI),
983         EPI(EPI) {}
984 
985   // Override this function to handle the more complex control flow around the
986   // three loops.
987   BasicBlock *createVectorizedLoopSkeleton() final override {
988     return createEpilogueVectorizedLoopSkeleton();
989   }
990 
991   /// The interface for creating a vectorized skeleton using one of two
992   /// different strategies, each corresponding to one execution of the vplan
993   /// as described above.
994   virtual BasicBlock *createEpilogueVectorizedLoopSkeleton() = 0;
995 
996   /// Holds and updates state information required to vectorize the main loop
997   /// and its epilogue in two separate passes. This setup helps us avoid
998   /// regenerating and recomputing runtime safety checks. It also helps us to
999   /// shorten the iteration-count-check path length for the cases where the
1000   /// iteration count of the loop is so small that the main vector loop is
1001   /// completely skipped.
1002   EpilogueLoopVectorizationInfo &EPI;
1003 };
1004 
1005 /// A specialized derived class of inner loop vectorizer that performs
1006 /// vectorization of *main* loops in the process of vectorizing loops and their
1007 /// epilogues.
1008 class EpilogueVectorizerMainLoop : public InnerLoopAndEpilogueVectorizer {
1009 public:
1010   EpilogueVectorizerMainLoop(
1011       Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI,
1012       DominatorTree *DT, const TargetLibraryInfo *TLI,
1013       const TargetTransformInfo *TTI, AssumptionCache *AC,
1014       OptimizationRemarkEmitter *ORE, EpilogueLoopVectorizationInfo &EPI,
1015       LoopVectorizationLegality *LVL, llvm::LoopVectorizationCostModel *CM,
1016       BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI)
1017       : InnerLoopAndEpilogueVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
1018                                        EPI, LVL, CM, BFI, PSI) {}
1019   /// Implements the interface for creating a vectorized skeleton using the
1020   /// *main loop* strategy (ie the first pass of vplan execution).
1021   BasicBlock *createEpilogueVectorizedLoopSkeleton() final override;
1022 
1023 protected:
1024   /// Emits an iteration count bypass check once for the main loop (when \p
1025   /// ForEpilogue is false) and once for the epilogue loop (when \p
1026   /// ForEpilogue is true).
1027   BasicBlock *emitMinimumIterationCountCheck(Loop *L, BasicBlock *Bypass,
1028                                              bool ForEpilogue);
1029   void printDebugTracesAtStart() override;
1030   void printDebugTracesAtEnd() override;
1031 };
1032 
1033 // A specialized derived class of inner loop vectorizer that performs
1034 // vectorization of *epilogue* loops in the process of vectorizing loops and
1035 // their epilogues.
1036 class EpilogueVectorizerEpilogueLoop : public InnerLoopAndEpilogueVectorizer {
1037 public:
1038   EpilogueVectorizerEpilogueLoop(Loop *OrigLoop, PredicatedScalarEvolution &PSE,
1039                     LoopInfo *LI, DominatorTree *DT,
1040                     const TargetLibraryInfo *TLI,
1041                     const TargetTransformInfo *TTI, AssumptionCache *AC,
1042                     OptimizationRemarkEmitter *ORE,
1043                     EpilogueLoopVectorizationInfo &EPI,
1044                     LoopVectorizationLegality *LVL,
1045                     llvm::LoopVectorizationCostModel *CM,
1046                     BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI)
1047       : InnerLoopAndEpilogueVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
1048                                        EPI, LVL, CM, BFI, PSI) {}
1049   /// Implements the interface for creating a vectorized skeleton using the
1050   /// *epilogue loop* strategy (ie the second pass of vplan execution).
1051   BasicBlock *createEpilogueVectorizedLoopSkeleton() final override;
1052 
1053 protected:
1054   /// Emits an iteration count bypass check after the main vector loop has
1055   /// finished to see if there are any iterations left to execute by either
1056   /// the vector epilogue or the scalar epilogue.
1057   BasicBlock *emitMinimumVectorEpilogueIterCountCheck(Loop *L,
1058                                                       BasicBlock *Bypass,
1059                                                       BasicBlock *Insert);
1060   void printDebugTracesAtStart() override;
1061   void printDebugTracesAtEnd() override;
1062 };
1063 } // end namespace llvm
1064 
1065 /// Look for a meaningful debug location on the instruction or it's
1066 /// operands.
1067 static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
1068   if (!I)
1069     return I;
1070 
1071   DebugLoc Empty;
1072   if (I->getDebugLoc() != Empty)
1073     return I;
1074 
1075   for (Use &Op : I->operands()) {
1076     if (Instruction *OpInst = dyn_cast<Instruction>(Op))
1077       if (OpInst->getDebugLoc() != Empty)
1078         return OpInst;
1079   }
1080 
1081   return I;
1082 }
1083 
1084 void InnerLoopVectorizer::setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr) {
1085   if (const Instruction *Inst = dyn_cast_or_null<Instruction>(Ptr)) {
1086     const DILocation *DIL = Inst->getDebugLoc();
1087     if (DIL && Inst->getFunction()->isDebugInfoForProfiling() &&
1088         !isa<DbgInfoIntrinsic>(Inst)) {
1089       assert(!VF.isScalable() && "scalable vectors not yet supported.");
1090       auto NewDIL =
1091           DIL->cloneByMultiplyingDuplicationFactor(UF * VF.getKnownMinValue());
1092       if (NewDIL)
1093         B.SetCurrentDebugLocation(NewDIL.getValue());
1094       else
1095         LLVM_DEBUG(dbgs()
1096                    << "Failed to create new discriminator: "
1097                    << DIL->getFilename() << " Line: " << DIL->getLine());
1098     }
1099     else
1100       B.SetCurrentDebugLocation(DIL);
1101   } else
1102     B.SetCurrentDebugLocation(DebugLoc());
1103 }
1104 
1105 /// Write a record \p DebugMsg about vectorization failure to the debug
1106 /// output stream. If \p I is passed, it is an instruction that prevents
1107 /// vectorization.
1108 #ifndef NDEBUG
1109 static void debugVectorizationFailure(const StringRef DebugMsg,
1110     Instruction *I) {
1111   dbgs() << "LV: Not vectorizing: " << DebugMsg;
1112   if (I != nullptr)
1113     dbgs() << " " << *I;
1114   else
1115     dbgs() << '.';
1116   dbgs() << '\n';
1117 }
1118 #endif
1119 
1120 /// Create an analysis remark that explains why vectorization failed
1121 ///
1122 /// \p PassName is the name of the pass (e.g. can be AlwaysPrint).  \p
1123 /// RemarkName is the identifier for the remark.  If \p I is passed it is an
1124 /// instruction that prevents vectorization.  Otherwise \p TheLoop is used for
1125 /// the location of the remark.  \return the remark object that can be
1126 /// streamed to.
1127 static OptimizationRemarkAnalysis createLVAnalysis(const char *PassName,
1128     StringRef RemarkName, Loop *TheLoop, Instruction *I) {
1129   Value *CodeRegion = TheLoop->getHeader();
1130   DebugLoc DL = TheLoop->getStartLoc();
1131 
1132   if (I) {
1133     CodeRegion = I->getParent();
1134     // If there is no debug location attached to the instruction, revert back to
1135     // using the loop's.
1136     if (I->getDebugLoc())
1137       DL = I->getDebugLoc();
1138   }
1139 
1140   OptimizationRemarkAnalysis R(PassName, RemarkName, DL, CodeRegion);
1141   R << "loop not vectorized: ";
1142   return R;
1143 }
1144 
1145 /// Return a value for Step multiplied by VF.
1146 static Value *createStepForVF(IRBuilder<> &B, Constant *Step, ElementCount VF) {
1147   assert(isa<ConstantInt>(Step) && "Expected an integer step");
1148   Constant *StepVal = ConstantInt::get(
1149       Step->getType(),
1150       cast<ConstantInt>(Step)->getSExtValue() * VF.getKnownMinValue());
1151   return VF.isScalable() ? B.CreateVScale(StepVal) : StepVal;
1152 }
1153 
1154 namespace llvm {
1155 
1156 void reportVectorizationFailure(const StringRef DebugMsg,
1157     const StringRef OREMsg, const StringRef ORETag,
1158     OptimizationRemarkEmitter *ORE, Loop *TheLoop, Instruction *I) {
1159   LLVM_DEBUG(debugVectorizationFailure(DebugMsg, I));
1160   LoopVectorizeHints Hints(TheLoop, true /* doesn't matter */, *ORE);
1161   ORE->emit(createLVAnalysis(Hints.vectorizeAnalysisPassName(),
1162                 ORETag, TheLoop, I) << OREMsg);
1163 }
1164 
1165 } // end namespace llvm
1166 
1167 #ifndef NDEBUG
1168 /// \return string containing a file name and a line # for the given loop.
1169 static std::string getDebugLocString(const Loop *L) {
1170   std::string Result;
1171   if (L) {
1172     raw_string_ostream OS(Result);
1173     if (const DebugLoc LoopDbgLoc = L->getStartLoc())
1174       LoopDbgLoc.print(OS);
1175     else
1176       // Just print the module name.
1177       OS << L->getHeader()->getParent()->getParent()->getModuleIdentifier();
1178     OS.flush();
1179   }
1180   return Result;
1181 }
1182 #endif
1183 
1184 void InnerLoopVectorizer::addNewMetadata(Instruction *To,
1185                                          const Instruction *Orig) {
1186   // If the loop was versioned with memchecks, add the corresponding no-alias
1187   // metadata.
1188   if (LVer && (isa<LoadInst>(Orig) || isa<StoreInst>(Orig)))
1189     LVer->annotateInstWithNoAlias(To, Orig);
1190 }
1191 
1192 void InnerLoopVectorizer::addMetadata(Instruction *To,
1193                                       Instruction *From) {
1194   propagateMetadata(To, From);
1195   addNewMetadata(To, From);
1196 }
1197 
1198 void InnerLoopVectorizer::addMetadata(ArrayRef<Value *> To,
1199                                       Instruction *From) {
1200   for (Value *V : To) {
1201     if (Instruction *I = dyn_cast<Instruction>(V))
1202       addMetadata(I, From);
1203   }
1204 }
1205 
1206 namespace llvm {
1207 
1208 // Loop vectorization cost-model hints how the scalar epilogue loop should be
1209 // lowered.
1210 enum ScalarEpilogueLowering {
1211 
1212   // The default: allowing scalar epilogues.
1213   CM_ScalarEpilogueAllowed,
1214 
1215   // Vectorization with OptForSize: don't allow epilogues.
1216   CM_ScalarEpilogueNotAllowedOptSize,
1217 
1218   // A special case of vectorisation with OptForSize: loops with a very small
1219   // trip count are considered for vectorization under OptForSize, thereby
1220   // making sure the cost of their loop body is dominant, free of runtime
1221   // guards and scalar iteration overheads.
1222   CM_ScalarEpilogueNotAllowedLowTripLoop,
1223 
1224   // Loop hint predicate indicating an epilogue is undesired.
1225   CM_ScalarEpilogueNotNeededUsePredicate,
1226 
1227   // Directive indicating we must either tail fold or not vectorize
1228   CM_ScalarEpilogueNotAllowedUsePredicate
1229 };
1230 
1231 /// LoopVectorizationCostModel - estimates the expected speedups due to
1232 /// vectorization.
1233 /// In many cases vectorization is not profitable. This can happen because of
1234 /// a number of reasons. In this class we mainly attempt to predict the
1235 /// expected speedup/slowdowns due to the supported instruction set. We use the
1236 /// TargetTransformInfo to query the different backends for the cost of
1237 /// different operations.
1238 class LoopVectorizationCostModel {
1239 public:
1240   LoopVectorizationCostModel(ScalarEpilogueLowering SEL, Loop *L,
1241                              PredicatedScalarEvolution &PSE, LoopInfo *LI,
1242                              LoopVectorizationLegality *Legal,
1243                              const TargetTransformInfo &TTI,
1244                              const TargetLibraryInfo *TLI, DemandedBits *DB,
1245                              AssumptionCache *AC,
1246                              OptimizationRemarkEmitter *ORE, const Function *F,
1247                              const LoopVectorizeHints *Hints,
1248                              InterleavedAccessInfo &IAI)
1249       : ScalarEpilogueStatus(SEL), TheLoop(L), PSE(PSE), LI(LI), Legal(Legal),
1250         TTI(TTI), TLI(TLI), DB(DB), AC(AC), ORE(ORE), TheFunction(F),
1251         Hints(Hints), InterleaveInfo(IAI) {}
1252 
1253   /// \return An upper bound for the vectorization factor, or None if
1254   /// vectorization and interleaving should be avoided up front.
1255   Optional<ElementCount> computeMaxVF(ElementCount UserVF, unsigned UserIC);
1256 
1257   /// \return True if runtime checks are required for vectorization, and false
1258   /// otherwise.
1259   bool runtimeChecksRequired();
1260 
1261   /// \return The most profitable vectorization factor and the cost of that VF.
1262   /// This method checks every power of two up to MaxVF. If UserVF is not ZERO
1263   /// then this vectorization factor will be selected if vectorization is
1264   /// possible.
1265   VectorizationFactor selectVectorizationFactor(ElementCount MaxVF);
1266   VectorizationFactor
1267   selectEpilogueVectorizationFactor(const ElementCount MaxVF,
1268                                     const LoopVectorizationPlanner &LVP);
1269 
1270   /// Setup cost-based decisions for user vectorization factor.
1271   void selectUserVectorizationFactor(ElementCount UserVF) {
1272     collectUniformsAndScalars(UserVF);
1273     collectInstsToScalarize(UserVF);
1274   }
1275 
1276   /// \return The size (in bits) of the smallest and widest types in the code
1277   /// that needs to be vectorized. We ignore values that remain scalar such as
1278   /// 64 bit loop indices.
1279   std::pair<unsigned, unsigned> getSmallestAndWidestTypes();
1280 
1281   /// \return The desired interleave count.
1282   /// If interleave count has been specified by metadata it will be returned.
1283   /// Otherwise, the interleave count is computed and returned. VF and LoopCost
1284   /// are the selected vectorization factor and the cost of the selected VF.
1285   unsigned selectInterleaveCount(ElementCount VF, unsigned LoopCost);
1286 
1287   /// Memory access instruction may be vectorized in more than one way.
1288   /// Form of instruction after vectorization depends on cost.
1289   /// This function takes cost-based decisions for Load/Store instructions
1290   /// and collects them in a map. This decisions map is used for building
1291   /// the lists of loop-uniform and loop-scalar instructions.
1292   /// The calculated cost is saved with widening decision in order to
1293   /// avoid redundant calculations.
1294   void setCostBasedWideningDecision(ElementCount VF);
1295 
1296   /// A struct that represents some properties of the register usage
1297   /// of a loop.
1298   struct RegisterUsage {
1299     /// Holds the number of loop invariant values that are used in the loop.
1300     /// The key is ClassID of target-provided register class.
1301     SmallMapVector<unsigned, unsigned, 4> LoopInvariantRegs;
1302     /// Holds the maximum number of concurrent live intervals in the loop.
1303     /// The key is ClassID of target-provided register class.
1304     SmallMapVector<unsigned, unsigned, 4> MaxLocalUsers;
1305   };
1306 
1307   /// \return Returns information about the register usages of the loop for the
1308   /// given vectorization factors.
1309   SmallVector<RegisterUsage, 8>
1310   calculateRegisterUsage(ArrayRef<ElementCount> VFs);
1311 
1312   /// Collect values we want to ignore in the cost model.
1313   void collectValuesToIgnore();
1314 
1315   /// Split reductions into those that happen in the loop, and those that happen
1316   /// outside. In loop reductions are collected into InLoopReductionChains.
1317   void collectInLoopReductions();
1318 
1319   /// \returns The smallest bitwidth each instruction can be represented with.
1320   /// The vector equivalents of these instructions should be truncated to this
1321   /// type.
1322   const MapVector<Instruction *, uint64_t> &getMinimalBitwidths() const {
1323     return MinBWs;
1324   }
1325 
1326   /// \returns True if it is more profitable to scalarize instruction \p I for
1327   /// vectorization factor \p VF.
1328   bool isProfitableToScalarize(Instruction *I, ElementCount VF) const {
1329     assert(VF.isVector() &&
1330            "Profitable to scalarize relevant only for VF > 1.");
1331 
1332     // Cost model is not run in the VPlan-native path - return conservative
1333     // result until this changes.
1334     if (EnableVPlanNativePath)
1335       return false;
1336 
1337     auto Scalars = InstsToScalarize.find(VF);
1338     assert(Scalars != InstsToScalarize.end() &&
1339            "VF not yet analyzed for scalarization profitability");
1340     return Scalars->second.find(I) != Scalars->second.end();
1341   }
1342 
1343   /// Returns true if \p I is known to be uniform after vectorization.
1344   bool isUniformAfterVectorization(Instruction *I, ElementCount VF) const {
1345     if (VF.isScalar())
1346       return true;
1347 
1348     // Cost model is not run in the VPlan-native path - return conservative
1349     // result until this changes.
1350     if (EnableVPlanNativePath)
1351       return false;
1352 
1353     auto UniformsPerVF = Uniforms.find(VF);
1354     assert(UniformsPerVF != Uniforms.end() &&
1355            "VF not yet analyzed for uniformity");
1356     return UniformsPerVF->second.count(I);
1357   }
1358 
1359   /// Returns true if \p I is known to be scalar after vectorization.
1360   bool isScalarAfterVectorization(Instruction *I, ElementCount VF) const {
1361     if (VF.isScalar())
1362       return true;
1363 
1364     // Cost model is not run in the VPlan-native path - return conservative
1365     // result until this changes.
1366     if (EnableVPlanNativePath)
1367       return false;
1368 
1369     auto ScalarsPerVF = Scalars.find(VF);
1370     assert(ScalarsPerVF != Scalars.end() &&
1371            "Scalar values are not calculated for VF");
1372     return ScalarsPerVF->second.count(I);
1373   }
1374 
1375   /// \returns True if instruction \p I can be truncated to a smaller bitwidth
1376   /// for vectorization factor \p VF.
1377   bool canTruncateToMinimalBitwidth(Instruction *I, ElementCount VF) const {
1378     return VF.isVector() && MinBWs.find(I) != MinBWs.end() &&
1379            !isProfitableToScalarize(I, VF) &&
1380            !isScalarAfterVectorization(I, VF);
1381   }
1382 
1383   /// Decision that was taken during cost calculation for memory instruction.
1384   enum InstWidening {
1385     CM_Unknown,
1386     CM_Widen,         // For consecutive accesses with stride +1.
1387     CM_Widen_Reverse, // For consecutive accesses with stride -1.
1388     CM_Interleave,
1389     CM_GatherScatter,
1390     CM_Scalarize
1391   };
1392 
1393   /// Save vectorization decision \p W and \p Cost taken by the cost model for
1394   /// instruction \p I and vector width \p VF.
1395   void setWideningDecision(Instruction *I, ElementCount VF, InstWidening W,
1396                            InstructionCost Cost) {
1397     assert(VF.isVector() && "Expected VF >=2");
1398     WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
1399   }
1400 
1401   /// Save vectorization decision \p W and \p Cost taken by the cost model for
1402   /// interleaving group \p Grp and vector width \p VF.
1403   void setWideningDecision(const InterleaveGroup<Instruction> *Grp,
1404                            ElementCount VF, InstWidening W,
1405                            InstructionCost Cost) {
1406     assert(VF.isVector() && "Expected VF >=2");
1407     /// Broadcast this decicion to all instructions inside the group.
1408     /// But the cost will be assigned to one instruction only.
1409     for (unsigned i = 0; i < Grp->getFactor(); ++i) {
1410       if (auto *I = Grp->getMember(i)) {
1411         if (Grp->getInsertPos() == I)
1412           WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
1413         else
1414           WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, 0);
1415       }
1416     }
1417   }
1418 
1419   /// Return the cost model decision for the given instruction \p I and vector
1420   /// width \p VF. Return CM_Unknown if this instruction did not pass
1421   /// through the cost modeling.
1422   InstWidening getWideningDecision(Instruction *I, ElementCount VF) {
1423     assert(VF.isVector() && "Expected VF to be a vector VF");
1424     // Cost model is not run in the VPlan-native path - return conservative
1425     // result until this changes.
1426     if (EnableVPlanNativePath)
1427       return CM_GatherScatter;
1428 
1429     std::pair<Instruction *, ElementCount> InstOnVF = std::make_pair(I, VF);
1430     auto Itr = WideningDecisions.find(InstOnVF);
1431     if (Itr == WideningDecisions.end())
1432       return CM_Unknown;
1433     return Itr->second.first;
1434   }
1435 
1436   /// Return the vectorization cost for the given instruction \p I and vector
1437   /// width \p VF.
1438   InstructionCost getWideningCost(Instruction *I, ElementCount VF) {
1439     assert(VF.isVector() && "Expected VF >=2");
1440     std::pair<Instruction *, ElementCount> InstOnVF = std::make_pair(I, VF);
1441     assert(WideningDecisions.find(InstOnVF) != WideningDecisions.end() &&
1442            "The cost is not calculated");
1443     return WideningDecisions[InstOnVF].second;
1444   }
1445 
1446   /// Return True if instruction \p I is an optimizable truncate whose operand
1447   /// is an induction variable. Such a truncate will be removed by adding a new
1448   /// induction variable with the destination type.
1449   bool isOptimizableIVTruncate(Instruction *I, ElementCount VF) {
1450     // If the instruction is not a truncate, return false.
1451     auto *Trunc = dyn_cast<TruncInst>(I);
1452     if (!Trunc)
1453       return false;
1454 
1455     // Get the source and destination types of the truncate.
1456     Type *SrcTy = ToVectorTy(cast<CastInst>(I)->getSrcTy(), VF);
1457     Type *DestTy = ToVectorTy(cast<CastInst>(I)->getDestTy(), VF);
1458 
1459     // If the truncate is free for the given types, return false. Replacing a
1460     // free truncate with an induction variable would add an induction variable
1461     // update instruction to each iteration of the loop. We exclude from this
1462     // check the primary induction variable since it will need an update
1463     // instruction regardless.
1464     Value *Op = Trunc->getOperand(0);
1465     if (Op != Legal->getPrimaryInduction() && TTI.isTruncateFree(SrcTy, DestTy))
1466       return false;
1467 
1468     // If the truncated value is not an induction variable, return false.
1469     return Legal->isInductionPhi(Op);
1470   }
1471 
1472   /// Collects the instructions to scalarize for each predicated instruction in
1473   /// the loop.
1474   void collectInstsToScalarize(ElementCount VF);
1475 
1476   /// Collect Uniform and Scalar values for the given \p VF.
1477   /// The sets depend on CM decision for Load/Store instructions
1478   /// that may be vectorized as interleave, gather-scatter or scalarized.
1479   void collectUniformsAndScalars(ElementCount VF) {
1480     // Do the analysis once.
1481     if (VF.isScalar() || Uniforms.find(VF) != Uniforms.end())
1482       return;
1483     setCostBasedWideningDecision(VF);
1484     collectLoopUniforms(VF);
1485     collectLoopScalars(VF);
1486   }
1487 
1488   /// Returns true if the target machine supports masked store operation
1489   /// for the given \p DataType and kind of access to \p Ptr.
1490   bool isLegalMaskedStore(Type *DataType, Value *Ptr, Align Alignment) {
1491     return Legal->isConsecutivePtr(Ptr) &&
1492            TTI.isLegalMaskedStore(DataType, Alignment);
1493   }
1494 
1495   /// Returns true if the target machine supports masked load operation
1496   /// for the given \p DataType and kind of access to \p Ptr.
1497   bool isLegalMaskedLoad(Type *DataType, Value *Ptr, Align Alignment) {
1498     return Legal->isConsecutivePtr(Ptr) &&
1499            TTI.isLegalMaskedLoad(DataType, Alignment);
1500   }
1501 
1502   /// Returns true if the target machine supports masked scatter operation
1503   /// for the given \p DataType.
1504   bool isLegalMaskedScatter(Type *DataType, Align Alignment) {
1505     return TTI.isLegalMaskedScatter(DataType, Alignment);
1506   }
1507 
1508   /// Returns true if the target machine supports masked gather operation
1509   /// for the given \p DataType.
1510   bool isLegalMaskedGather(Type *DataType, Align Alignment) {
1511     return TTI.isLegalMaskedGather(DataType, Alignment);
1512   }
1513 
1514   /// Returns true if the target machine can represent \p V as a masked gather
1515   /// or scatter operation.
1516   bool isLegalGatherOrScatter(Value *V) {
1517     bool LI = isa<LoadInst>(V);
1518     bool SI = isa<StoreInst>(V);
1519     if (!LI && !SI)
1520       return false;
1521     auto *Ty = getMemInstValueType(V);
1522     Align Align = getLoadStoreAlignment(V);
1523     return (LI && isLegalMaskedGather(Ty, Align)) ||
1524            (SI && isLegalMaskedScatter(Ty, Align));
1525   }
1526 
1527   /// Returns true if \p I is an instruction that will be scalarized with
1528   /// predication. Such instructions include conditional stores and
1529   /// instructions that may divide by zero.
1530   /// If a non-zero VF has been calculated, we check if I will be scalarized
1531   /// predication for that VF.
1532   bool isScalarWithPredication(Instruction *I,
1533                                ElementCount VF = ElementCount::getFixed(1));
1534 
1535   // Returns true if \p I is an instruction that will be predicated either
1536   // through scalar predication or masked load/store or masked gather/scatter.
1537   // Superset of instructions that return true for isScalarWithPredication.
1538   bool isPredicatedInst(Instruction *I) {
1539     if (!blockNeedsPredication(I->getParent()))
1540       return false;
1541     // Loads and stores that need some form of masked operation are predicated
1542     // instructions.
1543     if (isa<LoadInst>(I) || isa<StoreInst>(I))
1544       return Legal->isMaskRequired(I);
1545     return isScalarWithPredication(I);
1546   }
1547 
1548   /// Returns true if \p I is a memory instruction with consecutive memory
1549   /// access that can be widened.
1550   bool
1551   memoryInstructionCanBeWidened(Instruction *I,
1552                                 ElementCount VF = ElementCount::getFixed(1));
1553 
1554   /// Returns true if \p I is a memory instruction in an interleaved-group
1555   /// of memory accesses that can be vectorized with wide vector loads/stores
1556   /// and shuffles.
1557   bool
1558   interleavedAccessCanBeWidened(Instruction *I,
1559                                 ElementCount VF = ElementCount::getFixed(1));
1560 
1561   /// Check if \p Instr belongs to any interleaved access group.
1562   bool isAccessInterleaved(Instruction *Instr) {
1563     return InterleaveInfo.isInterleaved(Instr);
1564   }
1565 
1566   /// Get the interleaved access group that \p Instr belongs to.
1567   const InterleaveGroup<Instruction> *
1568   getInterleavedAccessGroup(Instruction *Instr) {
1569     return InterleaveInfo.getInterleaveGroup(Instr);
1570   }
1571 
1572   /// Returns true if we're required to use a scalar epilogue for at least
1573   /// the final iteration of the original loop.
1574   bool requiresScalarEpilogue() const {
1575     if (!isScalarEpilogueAllowed())
1576       return false;
1577     // If we might exit from anywhere but the latch, must run the exiting
1578     // iteration in scalar form.
1579     if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch())
1580       return true;
1581     return InterleaveInfo.requiresScalarEpilogue();
1582   }
1583 
1584   /// Returns true if a scalar epilogue is not allowed due to optsize or a
1585   /// loop hint annotation.
1586   bool isScalarEpilogueAllowed() const {
1587     return ScalarEpilogueStatus == CM_ScalarEpilogueAllowed;
1588   }
1589 
1590   /// Returns true if all loop blocks should be masked to fold tail loop.
1591   bool foldTailByMasking() const { return FoldTailByMasking; }
1592 
1593   bool blockNeedsPredication(BasicBlock *BB) {
1594     return foldTailByMasking() || Legal->blockNeedsPredication(BB);
1595   }
1596 
1597   /// A SmallMapVector to store the InLoop reduction op chains, mapping phi
1598   /// nodes to the chain of instructions representing the reductions. Uses a
1599   /// MapVector to ensure deterministic iteration order.
1600   using ReductionChainMap =
1601       SmallMapVector<PHINode *, SmallVector<Instruction *, 4>, 4>;
1602 
1603   /// Return the chain of instructions representing an inloop reduction.
1604   const ReductionChainMap &getInLoopReductionChains() const {
1605     return InLoopReductionChains;
1606   }
1607 
1608   /// Returns true if the Phi is part of an inloop reduction.
1609   bool isInLoopReduction(PHINode *Phi) const {
1610     return InLoopReductionChains.count(Phi);
1611   }
1612 
1613   /// Estimate cost of an intrinsic call instruction CI if it were vectorized
1614   /// with factor VF.  Return the cost of the instruction, including
1615   /// scalarization overhead if it's needed.
1616   InstructionCost getVectorIntrinsicCost(CallInst *CI, ElementCount VF);
1617 
1618   /// Estimate cost of a call instruction CI if it were vectorized with factor
1619   /// VF. Return the cost of the instruction, including scalarization overhead
1620   /// if it's needed. The flag NeedToScalarize shows if the call needs to be
1621   /// scalarized -
1622   /// i.e. either vector version isn't available, or is too expensive.
1623   InstructionCost getVectorCallCost(CallInst *CI, ElementCount VF,
1624                                     bool &NeedToScalarize);
1625 
1626   /// Invalidates decisions already taken by the cost model.
1627   void invalidateCostModelingDecisions() {
1628     WideningDecisions.clear();
1629     Uniforms.clear();
1630     Scalars.clear();
1631   }
1632 
1633 private:
1634   unsigned NumPredStores = 0;
1635 
1636   /// \return An upper bound for the vectorization factor, a power-of-2 larger
1637   /// than zero. One is returned if vectorization should best be avoided due
1638   /// to cost.
1639   ElementCount computeFeasibleMaxVF(unsigned ConstTripCount,
1640                                     ElementCount UserVF);
1641 
1642   /// The vectorization cost is a combination of the cost itself and a boolean
1643   /// indicating whether any of the contributing operations will actually
1644   /// operate on
1645   /// vector values after type legalization in the backend. If this latter value
1646   /// is
1647   /// false, then all operations will be scalarized (i.e. no vectorization has
1648   /// actually taken place).
1649   using VectorizationCostTy = std::pair<InstructionCost, bool>;
1650 
1651   /// Returns the expected execution cost. The unit of the cost does
1652   /// not matter because we use the 'cost' units to compare different
1653   /// vector widths. The cost that is returned is *not* normalized by
1654   /// the factor width.
1655   VectorizationCostTy expectedCost(ElementCount VF);
1656 
1657   /// Returns the execution time cost of an instruction for a given vector
1658   /// width. Vector width of one means scalar.
1659   VectorizationCostTy getInstructionCost(Instruction *I, ElementCount VF);
1660 
1661   /// The cost-computation logic from getInstructionCost which provides
1662   /// the vector type as an output parameter.
1663   InstructionCost getInstructionCost(Instruction *I, ElementCount VF,
1664                                      Type *&VectorTy);
1665 
1666   /// Return the cost of instructions in an inloop reduction pattern, if I is
1667   /// part of that pattern.
1668   InstructionCost getReductionPatternCost(Instruction *I, ElementCount VF,
1669                                           Type *VectorTy,
1670                                           TTI::TargetCostKind CostKind);
1671 
1672   /// Calculate vectorization cost of memory instruction \p I.
1673   InstructionCost getMemoryInstructionCost(Instruction *I, ElementCount VF);
1674 
1675   /// The cost computation for scalarized memory instruction.
1676   InstructionCost getMemInstScalarizationCost(Instruction *I, ElementCount VF);
1677 
1678   /// The cost computation for interleaving group of memory instructions.
1679   InstructionCost getInterleaveGroupCost(Instruction *I, ElementCount VF);
1680 
1681   /// The cost computation for Gather/Scatter instruction.
1682   InstructionCost getGatherScatterCost(Instruction *I, ElementCount VF);
1683 
1684   /// The cost computation for widening instruction \p I with consecutive
1685   /// memory access.
1686   InstructionCost getConsecutiveMemOpCost(Instruction *I, ElementCount VF);
1687 
1688   /// The cost calculation for Load/Store instruction \p I with uniform pointer -
1689   /// Load: scalar load + broadcast.
1690   /// Store: scalar store + (loop invariant value stored? 0 : extract of last
1691   /// element)
1692   InstructionCost getUniformMemOpCost(Instruction *I, ElementCount VF);
1693 
1694   /// Estimate the overhead of scalarizing an instruction. This is a
1695   /// convenience wrapper for the type-based getScalarizationOverhead API.
1696   InstructionCost getScalarizationOverhead(Instruction *I, ElementCount VF);
1697 
1698   /// Returns whether the instruction is a load or store and will be a emitted
1699   /// as a vector operation.
1700   bool isConsecutiveLoadOrStore(Instruction *I);
1701 
1702   /// Returns true if an artificially high cost for emulated masked memrefs
1703   /// should be used.
1704   bool useEmulatedMaskMemRefHack(Instruction *I);
1705 
1706   /// Map of scalar integer values to the smallest bitwidth they can be legally
1707   /// represented as. The vector equivalents of these values should be truncated
1708   /// to this type.
1709   MapVector<Instruction *, uint64_t> MinBWs;
1710 
1711   /// A type representing the costs for instructions if they were to be
1712   /// scalarized rather than vectorized. The entries are Instruction-Cost
1713   /// pairs.
1714   using ScalarCostsTy = DenseMap<Instruction *, InstructionCost>;
1715 
1716   /// A set containing all BasicBlocks that are known to present after
1717   /// vectorization as a predicated block.
1718   SmallPtrSet<BasicBlock *, 4> PredicatedBBsAfterVectorization;
1719 
1720   /// Records whether it is allowed to have the original scalar loop execute at
1721   /// least once. This may be needed as a fallback loop in case runtime
1722   /// aliasing/dependence checks fail, or to handle the tail/remainder
1723   /// iterations when the trip count is unknown or doesn't divide by the VF,
1724   /// or as a peel-loop to handle gaps in interleave-groups.
1725   /// Under optsize and when the trip count is very small we don't allow any
1726   /// iterations to execute in the scalar loop.
1727   ScalarEpilogueLowering ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
1728 
1729   /// All blocks of loop are to be masked to fold tail of scalar iterations.
1730   bool FoldTailByMasking = false;
1731 
1732   /// A map holding scalar costs for different vectorization factors. The
1733   /// presence of a cost for an instruction in the mapping indicates that the
1734   /// instruction will be scalarized when vectorizing with the associated
1735   /// vectorization factor. The entries are VF-ScalarCostTy pairs.
1736   DenseMap<ElementCount, ScalarCostsTy> InstsToScalarize;
1737 
1738   /// Holds the instructions known to be uniform after vectorization.
1739   /// The data is collected per VF.
1740   DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> Uniforms;
1741 
1742   /// Holds the instructions known to be scalar after vectorization.
1743   /// The data is collected per VF.
1744   DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> Scalars;
1745 
1746   /// Holds the instructions (address computations) that are forced to be
1747   /// scalarized.
1748   DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> ForcedScalars;
1749 
1750   /// PHINodes of the reductions that should be expanded in-loop along with
1751   /// their associated chains of reduction operations, in program order from top
1752   /// (PHI) to bottom
1753   ReductionChainMap InLoopReductionChains;
1754 
1755   /// A Map of inloop reduction operations and their immediate chain operand.
1756   /// FIXME: This can be removed once reductions can be costed correctly in
1757   /// vplan. This was added to allow quick lookup to the inloop operations,
1758   /// without having to loop through InLoopReductionChains.
1759   DenseMap<Instruction *, Instruction *> InLoopReductionImmediateChains;
1760 
1761   /// Returns the expected difference in cost from scalarizing the expression
1762   /// feeding a predicated instruction \p PredInst. The instructions to
1763   /// scalarize and their scalar costs are collected in \p ScalarCosts. A
1764   /// non-negative return value implies the expression will be scalarized.
1765   /// Currently, only single-use chains are considered for scalarization.
1766   int computePredInstDiscount(Instruction *PredInst, ScalarCostsTy &ScalarCosts,
1767                               ElementCount VF);
1768 
1769   /// Collect the instructions that are uniform after vectorization. An
1770   /// instruction is uniform if we represent it with a single scalar value in
1771   /// the vectorized loop corresponding to each vector iteration. Examples of
1772   /// uniform instructions include pointer operands of consecutive or
1773   /// interleaved memory accesses. Note that although uniformity implies an
1774   /// instruction will be scalar, the reverse is not true. In general, a
1775   /// scalarized instruction will be represented by VF scalar values in the
1776   /// vectorized loop, each corresponding to an iteration of the original
1777   /// scalar loop.
1778   void collectLoopUniforms(ElementCount VF);
1779 
1780   /// Collect the instructions that are scalar after vectorization. An
1781   /// instruction is scalar if it is known to be uniform or will be scalarized
1782   /// during vectorization. Non-uniform scalarized instructions will be
1783   /// represented by VF values in the vectorized loop, each corresponding to an
1784   /// iteration of the original scalar loop.
1785   void collectLoopScalars(ElementCount VF);
1786 
1787   /// Keeps cost model vectorization decision and cost for instructions.
1788   /// Right now it is used for memory instructions only.
1789   using DecisionList = DenseMap<std::pair<Instruction *, ElementCount>,
1790                                 std::pair<InstWidening, InstructionCost>>;
1791 
1792   DecisionList WideningDecisions;
1793 
1794   /// Returns true if \p V is expected to be vectorized and it needs to be
1795   /// extracted.
1796   bool needsExtract(Value *V, ElementCount VF) const {
1797     Instruction *I = dyn_cast<Instruction>(V);
1798     if (VF.isScalar() || !I || !TheLoop->contains(I) ||
1799         TheLoop->isLoopInvariant(I))
1800       return false;
1801 
1802     // Assume we can vectorize V (and hence we need extraction) if the
1803     // scalars are not computed yet. This can happen, because it is called
1804     // via getScalarizationOverhead from setCostBasedWideningDecision, before
1805     // the scalars are collected. That should be a safe assumption in most
1806     // cases, because we check if the operands have vectorizable types
1807     // beforehand in LoopVectorizationLegality.
1808     return Scalars.find(VF) == Scalars.end() ||
1809            !isScalarAfterVectorization(I, VF);
1810   };
1811 
1812   /// Returns a range containing only operands needing to be extracted.
1813   SmallVector<Value *, 4> filterExtractingOperands(Instruction::op_range Ops,
1814                                                    ElementCount VF) {
1815     return SmallVector<Value *, 4>(make_filter_range(
1816         Ops, [this, VF](Value *V) { return this->needsExtract(V, VF); }));
1817   }
1818 
1819   /// Determines if we have the infrastructure to vectorize loop \p L and its
1820   /// epilogue, assuming the main loop is vectorized by \p VF.
1821   bool isCandidateForEpilogueVectorization(const Loop &L,
1822                                            const ElementCount VF) const;
1823 
1824   /// Returns true if epilogue vectorization is considered profitable, and
1825   /// false otherwise.
1826   /// \p VF is the vectorization factor chosen for the original loop.
1827   bool isEpilogueVectorizationProfitable(const ElementCount VF) const;
1828 
1829 public:
1830   /// The loop that we evaluate.
1831   Loop *TheLoop;
1832 
1833   /// Predicated scalar evolution analysis.
1834   PredicatedScalarEvolution &PSE;
1835 
1836   /// Loop Info analysis.
1837   LoopInfo *LI;
1838 
1839   /// Vectorization legality.
1840   LoopVectorizationLegality *Legal;
1841 
1842   /// Vector target information.
1843   const TargetTransformInfo &TTI;
1844 
1845   /// Target Library Info.
1846   const TargetLibraryInfo *TLI;
1847 
1848   /// Demanded bits analysis.
1849   DemandedBits *DB;
1850 
1851   /// Assumption cache.
1852   AssumptionCache *AC;
1853 
1854   /// Interface to emit optimization remarks.
1855   OptimizationRemarkEmitter *ORE;
1856 
1857   const Function *TheFunction;
1858 
1859   /// Loop Vectorize Hint.
1860   const LoopVectorizeHints *Hints;
1861 
1862   /// The interleave access information contains groups of interleaved accesses
1863   /// with the same stride and close to each other.
1864   InterleavedAccessInfo &InterleaveInfo;
1865 
1866   /// Values to ignore in the cost model.
1867   SmallPtrSet<const Value *, 16> ValuesToIgnore;
1868 
1869   /// Values to ignore in the cost model when VF > 1.
1870   SmallPtrSet<const Value *, 16> VecValuesToIgnore;
1871 
1872   /// Profitable vector factors.
1873   SmallVector<VectorizationFactor, 8> ProfitableVFs;
1874 };
1875 
1876 } // end namespace llvm
1877 
1878 // Return true if \p OuterLp is an outer loop annotated with hints for explicit
1879 // vectorization. The loop needs to be annotated with #pragma omp simd
1880 // simdlen(#) or #pragma clang vectorize(enable) vectorize_width(#). If the
1881 // vector length information is not provided, vectorization is not considered
1882 // explicit. Interleave hints are not allowed either. These limitations will be
1883 // relaxed in the future.
1884 // Please, note that we are currently forced to abuse the pragma 'clang
1885 // vectorize' semantics. This pragma provides *auto-vectorization hints*
1886 // (i.e., LV must check that vectorization is legal) whereas pragma 'omp simd'
1887 // provides *explicit vectorization hints* (LV can bypass legal checks and
1888 // assume that vectorization is legal). However, both hints are implemented
1889 // using the same metadata (llvm.loop.vectorize, processed by
1890 // LoopVectorizeHints). This will be fixed in the future when the native IR
1891 // representation for pragma 'omp simd' is introduced.
1892 static bool isExplicitVecOuterLoop(Loop *OuterLp,
1893                                    OptimizationRemarkEmitter *ORE) {
1894   assert(!OuterLp->isInnermost() && "This is not an outer loop");
1895   LoopVectorizeHints Hints(OuterLp, true /*DisableInterleaving*/, *ORE);
1896 
1897   // Only outer loops with an explicit vectorization hint are supported.
1898   // Unannotated outer loops are ignored.
1899   if (Hints.getForce() == LoopVectorizeHints::FK_Undefined)
1900     return false;
1901 
1902   Function *Fn = OuterLp->getHeader()->getParent();
1903   if (!Hints.allowVectorization(Fn, OuterLp,
1904                                 true /*VectorizeOnlyWhenForced*/)) {
1905     LLVM_DEBUG(dbgs() << "LV: Loop hints prevent outer loop vectorization.\n");
1906     return false;
1907   }
1908 
1909   if (Hints.getInterleave() > 1) {
1910     // TODO: Interleave support is future work.
1911     LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Interleave is not supported for "
1912                          "outer loops.\n");
1913     Hints.emitRemarkWithHints();
1914     return false;
1915   }
1916 
1917   return true;
1918 }
1919 
1920 static void collectSupportedLoops(Loop &L, LoopInfo *LI,
1921                                   OptimizationRemarkEmitter *ORE,
1922                                   SmallVectorImpl<Loop *> &V) {
1923   // Collect inner loops and outer loops without irreducible control flow. For
1924   // now, only collect outer loops that have explicit vectorization hints. If we
1925   // are stress testing the VPlan H-CFG construction, we collect the outermost
1926   // loop of every loop nest.
1927   if (L.isInnermost() || VPlanBuildStressTest ||
1928       (EnableVPlanNativePath && isExplicitVecOuterLoop(&L, ORE))) {
1929     LoopBlocksRPO RPOT(&L);
1930     RPOT.perform(LI);
1931     if (!containsIrreducibleCFG<const BasicBlock *>(RPOT, *LI)) {
1932       V.push_back(&L);
1933       // TODO: Collect inner loops inside marked outer loops in case
1934       // vectorization fails for the outer loop. Do not invoke
1935       // 'containsIrreducibleCFG' again for inner loops when the outer loop is
1936       // already known to be reducible. We can use an inherited attribute for
1937       // that.
1938       return;
1939     }
1940   }
1941   for (Loop *InnerL : L)
1942     collectSupportedLoops(*InnerL, LI, ORE, V);
1943 }
1944 
1945 namespace {
1946 
1947 /// The LoopVectorize Pass.
1948 struct LoopVectorize : public FunctionPass {
1949   /// Pass identification, replacement for typeid
1950   static char ID;
1951 
1952   LoopVectorizePass Impl;
1953 
1954   explicit LoopVectorize(bool InterleaveOnlyWhenForced = false,
1955                          bool VectorizeOnlyWhenForced = false)
1956       : FunctionPass(ID),
1957         Impl({InterleaveOnlyWhenForced, VectorizeOnlyWhenForced}) {
1958     initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
1959   }
1960 
1961   bool runOnFunction(Function &F) override {
1962     if (skipFunction(F))
1963       return false;
1964 
1965     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1966     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1967     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
1968     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1969     auto *BFI = &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI();
1970     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
1971     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
1972     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
1973     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1974     auto *LAA = &getAnalysis<LoopAccessLegacyAnalysis>();
1975     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
1976     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
1977     auto *PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
1978 
1979     std::function<const LoopAccessInfo &(Loop &)> GetLAA =
1980         [&](Loop &L) -> const LoopAccessInfo & { return LAA->getInfo(&L); };
1981 
1982     return Impl.runImpl(F, *SE, *LI, *TTI, *DT, *BFI, TLI, *DB, *AA, *AC,
1983                         GetLAA, *ORE, PSI).MadeAnyChange;
1984   }
1985 
1986   void getAnalysisUsage(AnalysisUsage &AU) const override {
1987     AU.addRequired<AssumptionCacheTracker>();
1988     AU.addRequired<BlockFrequencyInfoWrapperPass>();
1989     AU.addRequired<DominatorTreeWrapperPass>();
1990     AU.addRequired<LoopInfoWrapperPass>();
1991     AU.addRequired<ScalarEvolutionWrapperPass>();
1992     AU.addRequired<TargetTransformInfoWrapperPass>();
1993     AU.addRequired<AAResultsWrapperPass>();
1994     AU.addRequired<LoopAccessLegacyAnalysis>();
1995     AU.addRequired<DemandedBitsWrapperPass>();
1996     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
1997     AU.addRequired<InjectTLIMappingsLegacy>();
1998 
1999     // We currently do not preserve loopinfo/dominator analyses with outer loop
2000     // vectorization. Until this is addressed, mark these analyses as preserved
2001     // only for non-VPlan-native path.
2002     // TODO: Preserve Loop and Dominator analyses for VPlan-native path.
2003     if (!EnableVPlanNativePath) {
2004       AU.addPreserved<LoopInfoWrapperPass>();
2005       AU.addPreserved<DominatorTreeWrapperPass>();
2006     }
2007 
2008     AU.addPreserved<BasicAAWrapperPass>();
2009     AU.addPreserved<GlobalsAAWrapperPass>();
2010     AU.addRequired<ProfileSummaryInfoWrapperPass>();
2011   }
2012 };
2013 
2014 } // end anonymous namespace
2015 
2016 //===----------------------------------------------------------------------===//
2017 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
2018 // LoopVectorizationCostModel and LoopVectorizationPlanner.
2019 //===----------------------------------------------------------------------===//
2020 
2021 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
2022   // We need to place the broadcast of invariant variables outside the loop,
2023   // but only if it's proven safe to do so. Else, broadcast will be inside
2024   // vector loop body.
2025   Instruction *Instr = dyn_cast<Instruction>(V);
2026   bool SafeToHoist = OrigLoop->isLoopInvariant(V) &&
2027                      (!Instr ||
2028                       DT->dominates(Instr->getParent(), LoopVectorPreHeader));
2029   // Place the code for broadcasting invariant variables in the new preheader.
2030   IRBuilder<>::InsertPointGuard Guard(Builder);
2031   if (SafeToHoist)
2032     Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
2033 
2034   // Broadcast the scalar into all locations in the vector.
2035   Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
2036 
2037   return Shuf;
2038 }
2039 
2040 void InnerLoopVectorizer::createVectorIntOrFpInductionPHI(
2041     const InductionDescriptor &II, Value *Step, Value *Start,
2042     Instruction *EntryVal, VPValue *Def, VPValue *CastDef,
2043     VPTransformState &State) {
2044   assert((isa<PHINode>(EntryVal) || isa<TruncInst>(EntryVal)) &&
2045          "Expected either an induction phi-node or a truncate of it!");
2046 
2047   // Construct the initial value of the vector IV in the vector loop preheader
2048   auto CurrIP = Builder.saveIP();
2049   Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
2050   if (isa<TruncInst>(EntryVal)) {
2051     assert(Start->getType()->isIntegerTy() &&
2052            "Truncation requires an integer type");
2053     auto *TruncType = cast<IntegerType>(EntryVal->getType());
2054     Step = Builder.CreateTrunc(Step, TruncType);
2055     Start = Builder.CreateCast(Instruction::Trunc, Start, TruncType);
2056   }
2057   Value *SplatStart = Builder.CreateVectorSplat(VF, Start);
2058   Value *SteppedStart =
2059       getStepVector(SplatStart, 0, Step, II.getInductionOpcode());
2060 
2061   // We create vector phi nodes for both integer and floating-point induction
2062   // variables. Here, we determine the kind of arithmetic we will perform.
2063   Instruction::BinaryOps AddOp;
2064   Instruction::BinaryOps MulOp;
2065   if (Step->getType()->isIntegerTy()) {
2066     AddOp = Instruction::Add;
2067     MulOp = Instruction::Mul;
2068   } else {
2069     AddOp = II.getInductionOpcode();
2070     MulOp = Instruction::FMul;
2071   }
2072 
2073   // Multiply the vectorization factor by the step using integer or
2074   // floating-point arithmetic as appropriate.
2075   Value *ConstVF =
2076       getSignedIntOrFpConstant(Step->getType(), VF.getKnownMinValue());
2077   Value *Mul = addFastMathFlag(Builder.CreateBinOp(MulOp, Step, ConstVF));
2078 
2079   // Create a vector splat to use in the induction update.
2080   //
2081   // FIXME: If the step is non-constant, we create the vector splat with
2082   //        IRBuilder. IRBuilder can constant-fold the multiply, but it doesn't
2083   //        handle a constant vector splat.
2084   assert(!VF.isScalable() && "scalable vectors not yet supported.");
2085   Value *SplatVF = isa<Constant>(Mul)
2086                        ? ConstantVector::getSplat(VF, cast<Constant>(Mul))
2087                        : Builder.CreateVectorSplat(VF, Mul);
2088   Builder.restoreIP(CurrIP);
2089 
2090   // We may need to add the step a number of times, depending on the unroll
2091   // factor. The last of those goes into the PHI.
2092   PHINode *VecInd = PHINode::Create(SteppedStart->getType(), 2, "vec.ind",
2093                                     &*LoopVectorBody->getFirstInsertionPt());
2094   VecInd->setDebugLoc(EntryVal->getDebugLoc());
2095   Instruction *LastInduction = VecInd;
2096   for (unsigned Part = 0; Part < UF; ++Part) {
2097     State.set(Def, EntryVal, LastInduction, Part);
2098 
2099     if (isa<TruncInst>(EntryVal))
2100       addMetadata(LastInduction, EntryVal);
2101     recordVectorLoopValueForInductionCast(II, EntryVal, LastInduction, CastDef,
2102                                           State, Part);
2103 
2104     LastInduction = cast<Instruction>(addFastMathFlag(
2105         Builder.CreateBinOp(AddOp, LastInduction, SplatVF, "step.add")));
2106     LastInduction->setDebugLoc(EntryVal->getDebugLoc());
2107   }
2108 
2109   // Move the last step to the end of the latch block. This ensures consistent
2110   // placement of all induction updates.
2111   auto *LoopVectorLatch = LI->getLoopFor(LoopVectorBody)->getLoopLatch();
2112   auto *Br = cast<BranchInst>(LoopVectorLatch->getTerminator());
2113   auto *ICmp = cast<Instruction>(Br->getCondition());
2114   LastInduction->moveBefore(ICmp);
2115   LastInduction->setName("vec.ind.next");
2116 
2117   VecInd->addIncoming(SteppedStart, LoopVectorPreHeader);
2118   VecInd->addIncoming(LastInduction, LoopVectorLatch);
2119 }
2120 
2121 bool InnerLoopVectorizer::shouldScalarizeInstruction(Instruction *I) const {
2122   return Cost->isScalarAfterVectorization(I, VF) ||
2123          Cost->isProfitableToScalarize(I, VF);
2124 }
2125 
2126 bool InnerLoopVectorizer::needsScalarInduction(Instruction *IV) const {
2127   if (shouldScalarizeInstruction(IV))
2128     return true;
2129   auto isScalarInst = [&](User *U) -> bool {
2130     auto *I = cast<Instruction>(U);
2131     return (OrigLoop->contains(I) && shouldScalarizeInstruction(I));
2132   };
2133   return llvm::any_of(IV->users(), isScalarInst);
2134 }
2135 
2136 void InnerLoopVectorizer::recordVectorLoopValueForInductionCast(
2137     const InductionDescriptor &ID, const Instruction *EntryVal,
2138     Value *VectorLoopVal, VPValue *CastDef, VPTransformState &State,
2139     unsigned Part, unsigned Lane) {
2140   assert((isa<PHINode>(EntryVal) || isa<TruncInst>(EntryVal)) &&
2141          "Expected either an induction phi-node or a truncate of it!");
2142 
2143   // This induction variable is not the phi from the original loop but the
2144   // newly-created IV based on the proof that casted Phi is equal to the
2145   // uncasted Phi in the vectorized loop (under a runtime guard possibly). It
2146   // re-uses the same InductionDescriptor that original IV uses but we don't
2147   // have to do any recording in this case - that is done when original IV is
2148   // processed.
2149   if (isa<TruncInst>(EntryVal))
2150     return;
2151 
2152   const SmallVectorImpl<Instruction *> &Casts = ID.getCastInsts();
2153   if (Casts.empty())
2154     return;
2155   // Only the first Cast instruction in the Casts vector is of interest.
2156   // The rest of the Casts (if exist) have no uses outside the
2157   // induction update chain itself.
2158   if (Lane < UINT_MAX)
2159     State.set(CastDef, VectorLoopVal, VPIteration(Part, Lane));
2160   else
2161     State.set(CastDef, VectorLoopVal, Part);
2162 }
2163 
2164 void InnerLoopVectorizer::widenIntOrFpInduction(PHINode *IV, Value *Start,
2165                                                 TruncInst *Trunc, VPValue *Def,
2166                                                 VPValue *CastDef,
2167                                                 VPTransformState &State) {
2168   assert((IV->getType()->isIntegerTy() || IV != OldInduction) &&
2169          "Primary induction variable must have an integer type");
2170 
2171   auto II = Legal->getInductionVars().find(IV);
2172   assert(II != Legal->getInductionVars().end() && "IV is not an induction");
2173 
2174   auto ID = II->second;
2175   assert(IV->getType() == ID.getStartValue()->getType() && "Types must match");
2176 
2177   // The value from the original loop to which we are mapping the new induction
2178   // variable.
2179   Instruction *EntryVal = Trunc ? cast<Instruction>(Trunc) : IV;
2180 
2181   auto &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
2182 
2183   // Generate code for the induction step. Note that induction steps are
2184   // required to be loop-invariant
2185   auto CreateStepValue = [&](const SCEV *Step) -> Value * {
2186     assert(PSE.getSE()->isLoopInvariant(Step, OrigLoop) &&
2187            "Induction step should be loop invariant");
2188     if (PSE.getSE()->isSCEVable(IV->getType())) {
2189       SCEVExpander Exp(*PSE.getSE(), DL, "induction");
2190       return Exp.expandCodeFor(Step, Step->getType(),
2191                                LoopVectorPreHeader->getTerminator());
2192     }
2193     return cast<SCEVUnknown>(Step)->getValue();
2194   };
2195 
2196   // The scalar value to broadcast. This is derived from the canonical
2197   // induction variable. If a truncation type is given, truncate the canonical
2198   // induction variable and step. Otherwise, derive these values from the
2199   // induction descriptor.
2200   auto CreateScalarIV = [&](Value *&Step) -> Value * {
2201     Value *ScalarIV = Induction;
2202     if (IV != OldInduction) {
2203       ScalarIV = IV->getType()->isIntegerTy()
2204                      ? Builder.CreateSExtOrTrunc(Induction, IV->getType())
2205                      : Builder.CreateCast(Instruction::SIToFP, Induction,
2206                                           IV->getType());
2207       ScalarIV = emitTransformedIndex(Builder, ScalarIV, PSE.getSE(), DL, ID);
2208       ScalarIV->setName("offset.idx");
2209     }
2210     if (Trunc) {
2211       auto *TruncType = cast<IntegerType>(Trunc->getType());
2212       assert(Step->getType()->isIntegerTy() &&
2213              "Truncation requires an integer step");
2214       ScalarIV = Builder.CreateTrunc(ScalarIV, TruncType);
2215       Step = Builder.CreateTrunc(Step, TruncType);
2216     }
2217     return ScalarIV;
2218   };
2219 
2220   // Create the vector values from the scalar IV, in the absence of creating a
2221   // vector IV.
2222   auto CreateSplatIV = [&](Value *ScalarIV, Value *Step) {
2223     Value *Broadcasted = getBroadcastInstrs(ScalarIV);
2224     for (unsigned Part = 0; Part < UF; ++Part) {
2225       assert(!VF.isScalable() && "scalable vectors not yet supported.");
2226       Value *EntryPart =
2227           getStepVector(Broadcasted, VF.getKnownMinValue() * Part, Step,
2228                         ID.getInductionOpcode());
2229       State.set(Def, EntryVal, EntryPart, Part);
2230       if (Trunc)
2231         addMetadata(EntryPart, Trunc);
2232       recordVectorLoopValueForInductionCast(ID, EntryVal, EntryPart, CastDef,
2233                                             State, Part);
2234     }
2235   };
2236 
2237   // Now do the actual transformations, and start with creating the step value.
2238   Value *Step = CreateStepValue(ID.getStep());
2239   if (VF.isZero() || VF.isScalar()) {
2240     Value *ScalarIV = CreateScalarIV(Step);
2241     CreateSplatIV(ScalarIV, Step);
2242     return;
2243   }
2244 
2245   // Determine if we want a scalar version of the induction variable. This is
2246   // true if the induction variable itself is not widened, or if it has at
2247   // least one user in the loop that is not widened.
2248   auto NeedsScalarIV = needsScalarInduction(EntryVal);
2249   if (!NeedsScalarIV) {
2250     createVectorIntOrFpInductionPHI(ID, Step, Start, EntryVal, Def, CastDef,
2251                                     State);
2252     return;
2253   }
2254 
2255   // Try to create a new independent vector induction variable. If we can't
2256   // create the phi node, we will splat the scalar induction variable in each
2257   // loop iteration.
2258   if (!shouldScalarizeInstruction(EntryVal)) {
2259     createVectorIntOrFpInductionPHI(ID, Step, Start, EntryVal, Def, CastDef,
2260                                     State);
2261     Value *ScalarIV = CreateScalarIV(Step);
2262     // Create scalar steps that can be used by instructions we will later
2263     // scalarize. Note that the addition of the scalar steps will not increase
2264     // the number of instructions in the loop in the common case prior to
2265     // InstCombine. We will be trading one vector extract for each scalar step.
2266     buildScalarSteps(ScalarIV, Step, EntryVal, ID, Def, CastDef, State);
2267     return;
2268   }
2269 
2270   // All IV users are scalar instructions, so only emit a scalar IV, not a
2271   // vectorised IV. Except when we tail-fold, then the splat IV feeds the
2272   // predicate used by the masked loads/stores.
2273   Value *ScalarIV = CreateScalarIV(Step);
2274   if (!Cost->isScalarEpilogueAllowed())
2275     CreateSplatIV(ScalarIV, Step);
2276   buildScalarSteps(ScalarIV, Step, EntryVal, ID, Def, CastDef, State);
2277 }
2278 
2279 Value *InnerLoopVectorizer::getStepVector(Value *Val, int StartIdx, Value *Step,
2280                                           Instruction::BinaryOps BinOp) {
2281   // Create and check the types.
2282   auto *ValVTy = cast<FixedVectorType>(Val->getType());
2283   int VLen = ValVTy->getNumElements();
2284 
2285   Type *STy = Val->getType()->getScalarType();
2286   assert((STy->isIntegerTy() || STy->isFloatingPointTy()) &&
2287          "Induction Step must be an integer or FP");
2288   assert(Step->getType() == STy && "Step has wrong type");
2289 
2290   SmallVector<Constant *, 8> Indices;
2291 
2292   if (STy->isIntegerTy()) {
2293     // Create a vector of consecutive numbers from zero to VF.
2294     for (int i = 0; i < VLen; ++i)
2295       Indices.push_back(ConstantInt::get(STy, StartIdx + i));
2296 
2297     // Add the consecutive indices to the vector value.
2298     Constant *Cv = ConstantVector::get(Indices);
2299     assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
2300     Step = Builder.CreateVectorSplat(VLen, Step);
2301     assert(Step->getType() == Val->getType() && "Invalid step vec");
2302     // FIXME: The newly created binary instructions should contain nsw/nuw flags,
2303     // which can be found from the original scalar operations.
2304     Step = Builder.CreateMul(Cv, Step);
2305     return Builder.CreateAdd(Val, Step, "induction");
2306   }
2307 
2308   // Floating point induction.
2309   assert((BinOp == Instruction::FAdd || BinOp == Instruction::FSub) &&
2310          "Binary Opcode should be specified for FP induction");
2311   // Create a vector of consecutive numbers from zero to VF.
2312   for (int i = 0; i < VLen; ++i)
2313     Indices.push_back(ConstantFP::get(STy, (double)(StartIdx + i)));
2314 
2315   // Add the consecutive indices to the vector value.
2316   Constant *Cv = ConstantVector::get(Indices);
2317 
2318   Step = Builder.CreateVectorSplat(VLen, Step);
2319 
2320   // Floating point operations had to be 'fast' to enable the induction.
2321   FastMathFlags Flags;
2322   Flags.setFast();
2323 
2324   Value *MulOp = Builder.CreateFMul(Cv, Step);
2325   if (isa<Instruction>(MulOp))
2326     // Have to check, MulOp may be a constant
2327     cast<Instruction>(MulOp)->setFastMathFlags(Flags);
2328 
2329   Value *BOp = Builder.CreateBinOp(BinOp, Val, MulOp, "induction");
2330   if (isa<Instruction>(BOp))
2331     cast<Instruction>(BOp)->setFastMathFlags(Flags);
2332   return BOp;
2333 }
2334 
2335 void InnerLoopVectorizer::buildScalarSteps(Value *ScalarIV, Value *Step,
2336                                            Instruction *EntryVal,
2337                                            const InductionDescriptor &ID,
2338                                            VPValue *Def, VPValue *CastDef,
2339                                            VPTransformState &State) {
2340   // We shouldn't have to build scalar steps if we aren't vectorizing.
2341   assert(VF.isVector() && "VF should be greater than one");
2342   // Get the value type and ensure it and the step have the same integer type.
2343   Type *ScalarIVTy = ScalarIV->getType()->getScalarType();
2344   assert(ScalarIVTy == Step->getType() &&
2345          "Val and Step should have the same type");
2346 
2347   // We build scalar steps for both integer and floating-point induction
2348   // variables. Here, we determine the kind of arithmetic we will perform.
2349   Instruction::BinaryOps AddOp;
2350   Instruction::BinaryOps MulOp;
2351   if (ScalarIVTy->isIntegerTy()) {
2352     AddOp = Instruction::Add;
2353     MulOp = Instruction::Mul;
2354   } else {
2355     AddOp = ID.getInductionOpcode();
2356     MulOp = Instruction::FMul;
2357   }
2358 
2359   // Determine the number of scalars we need to generate for each unroll
2360   // iteration. If EntryVal is uniform, we only need to generate the first
2361   // lane. Otherwise, we generate all VF values.
2362   unsigned Lanes =
2363       Cost->isUniformAfterVectorization(cast<Instruction>(EntryVal), VF)
2364           ? 1
2365           : VF.getKnownMinValue();
2366   assert((!VF.isScalable() || Lanes == 1) &&
2367          "Should never scalarize a scalable vector");
2368   // Compute the scalar steps and save the results in VectorLoopValueMap.
2369   for (unsigned Part = 0; Part < UF; ++Part) {
2370     for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
2371       auto *IntStepTy = IntegerType::get(ScalarIVTy->getContext(),
2372                                          ScalarIVTy->getScalarSizeInBits());
2373       Value *StartIdx =
2374           createStepForVF(Builder, ConstantInt::get(IntStepTy, Part), VF);
2375       if (ScalarIVTy->isFloatingPointTy())
2376         StartIdx = Builder.CreateSIToFP(StartIdx, ScalarIVTy);
2377       StartIdx = addFastMathFlag(Builder.CreateBinOp(
2378           AddOp, StartIdx, getSignedIntOrFpConstant(ScalarIVTy, Lane)));
2379       // The step returned by `createStepForVF` is a runtime-evaluated value
2380       // when VF is scalable. Otherwise, it should be folded into a Constant.
2381       assert((VF.isScalable() || isa<Constant>(StartIdx)) &&
2382              "Expected StartIdx to be folded to a constant when VF is not "
2383              "scalable");
2384       auto *Mul = addFastMathFlag(Builder.CreateBinOp(MulOp, StartIdx, Step));
2385       auto *Add = addFastMathFlag(Builder.CreateBinOp(AddOp, ScalarIV, Mul));
2386       State.set(Def, Add, VPIteration(Part, Lane));
2387       recordVectorLoopValueForInductionCast(ID, EntryVal, Add, CastDef, State,
2388                                             Part, Lane);
2389     }
2390   }
2391 }
2392 
2393 Value *InnerLoopVectorizer::getOrCreateVectorValue(Value *V, unsigned Part) {
2394   assert(V != Induction && "The new induction variable should not be used.");
2395   assert(!V->getType()->isVectorTy() && "Can't widen a vector");
2396   assert(!V->getType()->isVoidTy() && "Type does not produce a value");
2397 
2398   // If we have a stride that is replaced by one, do it here. Defer this for
2399   // the VPlan-native path until we start running Legal checks in that path.
2400   if (!EnableVPlanNativePath && Legal->hasStride(V))
2401     V = ConstantInt::get(V->getType(), 1);
2402 
2403   // If we have a vector mapped to this value, return it.
2404   if (VectorLoopValueMap.hasVectorValue(V, Part))
2405     return VectorLoopValueMap.getVectorValue(V, Part);
2406 
2407   // If the value has not been vectorized, check if it has been scalarized
2408   // instead. If it has been scalarized, and we actually need the value in
2409   // vector form, we will construct the vector values on demand.
2410   if (VectorLoopValueMap.hasAnyScalarValue(V)) {
2411     Value *ScalarValue =
2412         VectorLoopValueMap.getScalarValue(V, VPIteration(Part, 0));
2413 
2414     // If we've scalarized a value, that value should be an instruction.
2415     auto *I = cast<Instruction>(V);
2416 
2417     // If we aren't vectorizing, we can just copy the scalar map values over to
2418     // the vector map.
2419     if (VF.isScalar()) {
2420       VectorLoopValueMap.setVectorValue(V, Part, ScalarValue);
2421       return ScalarValue;
2422     }
2423 
2424     // Get the last scalar instruction we generated for V and Part. If the value
2425     // is known to be uniform after vectorization, this corresponds to lane zero
2426     // of the Part unroll iteration. Otherwise, the last instruction is the one
2427     // we created for the last vector lane of the Part unroll iteration.
2428     unsigned LastLane = Cost->isUniformAfterVectorization(I, VF)
2429                             ? 0
2430                             : VF.getKnownMinValue() - 1;
2431     assert((!VF.isScalable() || LastLane == 0) &&
2432            "Scalable vectorization can't lead to any scalarized values.");
2433     auto *LastInst = cast<Instruction>(
2434         VectorLoopValueMap.getScalarValue(V, VPIteration(Part, LastLane)));
2435 
2436     // Set the insert point after the last scalarized instruction. This ensures
2437     // the insertelement sequence will directly follow the scalar definitions.
2438     auto OldIP = Builder.saveIP();
2439     auto NewIP = std::next(BasicBlock::iterator(LastInst));
2440     Builder.SetInsertPoint(&*NewIP);
2441 
2442     // However, if we are vectorizing, we need to construct the vector values.
2443     // If the value is known to be uniform after vectorization, we can just
2444     // broadcast the scalar value corresponding to lane zero for each unroll
2445     // iteration. Otherwise, we construct the vector values using insertelement
2446     // instructions. Since the resulting vectors are stored in
2447     // VectorLoopValueMap, we will only generate the insertelements once.
2448     Value *VectorValue = nullptr;
2449     if (Cost->isUniformAfterVectorization(I, VF)) {
2450       VectorValue = getBroadcastInstrs(ScalarValue);
2451       VectorLoopValueMap.setVectorValue(V, Part, VectorValue);
2452     } else {
2453       // Initialize packing with insertelements to start from poison.
2454       assert(!VF.isScalable() && "VF is assumed to be non scalable.");
2455       Value *Poison = PoisonValue::get(VectorType::get(V->getType(), VF));
2456       VectorLoopValueMap.setVectorValue(V, Part, Poison);
2457       for (unsigned Lane = 0; Lane < VF.getKnownMinValue(); ++Lane)
2458         packScalarIntoVectorValue(V, VPIteration(Part, Lane));
2459       VectorValue = VectorLoopValueMap.getVectorValue(V, Part);
2460     }
2461     Builder.restoreIP(OldIP);
2462     return VectorValue;
2463   }
2464 
2465   // If this scalar is unknown, assume that it is a constant or that it is
2466   // loop invariant. Broadcast V and save the value for future uses.
2467   Value *B = getBroadcastInstrs(V);
2468   VectorLoopValueMap.setVectorValue(V, Part, B);
2469   return B;
2470 }
2471 
2472 Value *
2473 InnerLoopVectorizer::getOrCreateScalarValue(Value *V,
2474                                             const VPIteration &Instance) {
2475   // If the value is not an instruction contained in the loop, it should
2476   // already be scalar.
2477   if (OrigLoop->isLoopInvariant(V))
2478     return V;
2479 
2480   assert(Instance.Lane > 0
2481              ? !Cost->isUniformAfterVectorization(cast<Instruction>(V), VF)
2482              : true && "Uniform values only have lane zero");
2483 
2484   // If the value from the original loop has not been vectorized, it is
2485   // represented by UF x VF scalar values in the new loop. Return the requested
2486   // scalar value.
2487   if (VectorLoopValueMap.hasScalarValue(V, Instance))
2488     return VectorLoopValueMap.getScalarValue(V, Instance);
2489 
2490   // If the value has not been scalarized, get its entry in VectorLoopValueMap
2491   // for the given unroll part. If this entry is not a vector type (i.e., the
2492   // vectorization factor is one), there is no need to generate an
2493   // extractelement instruction.
2494   auto *U = getOrCreateVectorValue(V, Instance.Part);
2495   if (!U->getType()->isVectorTy()) {
2496     assert(VF.isScalar() && "Value not scalarized has non-vector type");
2497     return U;
2498   }
2499 
2500   // Otherwise, the value from the original loop has been vectorized and is
2501   // represented by UF vector values. Extract and return the requested scalar
2502   // value from the appropriate vector lane.
2503   return Builder.CreateExtractElement(U, Builder.getInt32(Instance.Lane));
2504 }
2505 
2506 void InnerLoopVectorizer::packScalarIntoVectorValue(
2507     Value *V, const VPIteration &Instance) {
2508   assert(V != Induction && "The new induction variable should not be used.");
2509   assert(!V->getType()->isVectorTy() && "Can't pack a vector");
2510   assert(!V->getType()->isVoidTy() && "Type does not produce a value");
2511 
2512   Value *ScalarInst = VectorLoopValueMap.getScalarValue(V, Instance);
2513   Value *VectorValue = VectorLoopValueMap.getVectorValue(V, Instance.Part);
2514   VectorValue = Builder.CreateInsertElement(VectorValue, ScalarInst,
2515                                             Builder.getInt32(Instance.Lane));
2516   VectorLoopValueMap.resetVectorValue(V, Instance.Part, VectorValue);
2517 }
2518 
2519 void InnerLoopVectorizer::packScalarIntoVectorValue(VPValue *Def,
2520                                                     const VPIteration &Instance,
2521                                                     VPTransformState &State) {
2522   Value *ScalarInst = State.get(Def, Instance);
2523   Value *VectorValue = State.get(Def, Instance.Part);
2524   VectorValue = Builder.CreateInsertElement(
2525       VectorValue, ScalarInst, State.Builder.getInt32(Instance.Lane));
2526   State.set(Def, VectorValue, Instance.Part);
2527 }
2528 
2529 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
2530   assert(Vec->getType()->isVectorTy() && "Invalid type");
2531   assert(!VF.isScalable() && "Cannot reverse scalable vectors");
2532   SmallVector<int, 8> ShuffleMask;
2533   for (unsigned i = 0; i < VF.getKnownMinValue(); ++i)
2534     ShuffleMask.push_back(VF.getKnownMinValue() - i - 1);
2535 
2536   return Builder.CreateShuffleVector(Vec, ShuffleMask, "reverse");
2537 }
2538 
2539 // Return whether we allow using masked interleave-groups (for dealing with
2540 // strided loads/stores that reside in predicated blocks, or for dealing
2541 // with gaps).
2542 static bool useMaskedInterleavedAccesses(const TargetTransformInfo &TTI) {
2543   // If an override option has been passed in for interleaved accesses, use it.
2544   if (EnableMaskedInterleavedMemAccesses.getNumOccurrences() > 0)
2545     return EnableMaskedInterleavedMemAccesses;
2546 
2547   return TTI.enableMaskedInterleavedAccessVectorization();
2548 }
2549 
2550 // Try to vectorize the interleave group that \p Instr belongs to.
2551 //
2552 // E.g. Translate following interleaved load group (factor = 3):
2553 //   for (i = 0; i < N; i+=3) {
2554 //     R = Pic[i];             // Member of index 0
2555 //     G = Pic[i+1];           // Member of index 1
2556 //     B = Pic[i+2];           // Member of index 2
2557 //     ... // do something to R, G, B
2558 //   }
2559 // To:
2560 //   %wide.vec = load <12 x i32>                       ; Read 4 tuples of R,G,B
2561 //   %R.vec = shuffle %wide.vec, poison, <0, 3, 6, 9>   ; R elements
2562 //   %G.vec = shuffle %wide.vec, poison, <1, 4, 7, 10>  ; G elements
2563 //   %B.vec = shuffle %wide.vec, poison, <2, 5, 8, 11>  ; B elements
2564 //
2565 // Or translate following interleaved store group (factor = 3):
2566 //   for (i = 0; i < N; i+=3) {
2567 //     ... do something to R, G, B
2568 //     Pic[i]   = R;           // Member of index 0
2569 //     Pic[i+1] = G;           // Member of index 1
2570 //     Pic[i+2] = B;           // Member of index 2
2571 //   }
2572 // To:
2573 //   %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
2574 //   %B_U.vec = shuffle %B.vec, poison, <0, 1, 2, 3, u, u, u, u>
2575 //   %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
2576 //        <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>    ; Interleave R,G,B elements
2577 //   store <12 x i32> %interleaved.vec              ; Write 4 tuples of R,G,B
2578 void InnerLoopVectorizer::vectorizeInterleaveGroup(
2579     const InterleaveGroup<Instruction> *Group, ArrayRef<VPValue *> VPDefs,
2580     VPTransformState &State, VPValue *Addr, ArrayRef<VPValue *> StoredValues,
2581     VPValue *BlockInMask) {
2582   Instruction *Instr = Group->getInsertPos();
2583   const DataLayout &DL = Instr->getModule()->getDataLayout();
2584 
2585   // Prepare for the vector type of the interleaved load/store.
2586   Type *ScalarTy = getMemInstValueType(Instr);
2587   unsigned InterleaveFactor = Group->getFactor();
2588   assert(!VF.isScalable() && "scalable vectors not yet supported.");
2589   auto *VecTy = VectorType::get(ScalarTy, VF * InterleaveFactor);
2590 
2591   // Prepare for the new pointers.
2592   SmallVector<Value *, 2> AddrParts;
2593   unsigned Index = Group->getIndex(Instr);
2594 
2595   // TODO: extend the masked interleaved-group support to reversed access.
2596   assert((!BlockInMask || !Group->isReverse()) &&
2597          "Reversed masked interleave-group not supported.");
2598 
2599   // If the group is reverse, adjust the index to refer to the last vector lane
2600   // instead of the first. We adjust the index from the first vector lane,
2601   // rather than directly getting the pointer for lane VF - 1, because the
2602   // pointer operand of the interleaved access is supposed to be uniform. For
2603   // uniform instructions, we're only required to generate a value for the
2604   // first vector lane in each unroll iteration.
2605   assert(!VF.isScalable() &&
2606          "scalable vector reverse operation is not implemented");
2607   if (Group->isReverse())
2608     Index += (VF.getKnownMinValue() - 1) * Group->getFactor();
2609 
2610   for (unsigned Part = 0; Part < UF; Part++) {
2611     Value *AddrPart = State.get(Addr, VPIteration(Part, 0));
2612     setDebugLocFromInst(Builder, AddrPart);
2613 
2614     // Notice current instruction could be any index. Need to adjust the address
2615     // to the member of index 0.
2616     //
2617     // E.g.  a = A[i+1];     // Member of index 1 (Current instruction)
2618     //       b = A[i];       // Member of index 0
2619     // Current pointer is pointed to A[i+1], adjust it to A[i].
2620     //
2621     // E.g.  A[i+1] = a;     // Member of index 1
2622     //       A[i]   = b;     // Member of index 0
2623     //       A[i+2] = c;     // Member of index 2 (Current instruction)
2624     // Current pointer is pointed to A[i+2], adjust it to A[i].
2625 
2626     bool InBounds = false;
2627     if (auto *gep = dyn_cast<GetElementPtrInst>(AddrPart->stripPointerCasts()))
2628       InBounds = gep->isInBounds();
2629     AddrPart = Builder.CreateGEP(ScalarTy, AddrPart, Builder.getInt32(-Index));
2630     cast<GetElementPtrInst>(AddrPart)->setIsInBounds(InBounds);
2631 
2632     // Cast to the vector pointer type.
2633     unsigned AddressSpace = AddrPart->getType()->getPointerAddressSpace();
2634     Type *PtrTy = VecTy->getPointerTo(AddressSpace);
2635     AddrParts.push_back(Builder.CreateBitCast(AddrPart, PtrTy));
2636   }
2637 
2638   setDebugLocFromInst(Builder, Instr);
2639   Value *PoisonVec = PoisonValue::get(VecTy);
2640 
2641   Value *MaskForGaps = nullptr;
2642   if (Group->requiresScalarEpilogue() && !Cost->isScalarEpilogueAllowed()) {
2643     assert(!VF.isScalable() && "scalable vectors not yet supported.");
2644     MaskForGaps = createBitMaskForGaps(Builder, VF.getKnownMinValue(), *Group);
2645     assert(MaskForGaps && "Mask for Gaps is required but it is null");
2646   }
2647 
2648   // Vectorize the interleaved load group.
2649   if (isa<LoadInst>(Instr)) {
2650     // For each unroll part, create a wide load for the group.
2651     SmallVector<Value *, 2> NewLoads;
2652     for (unsigned Part = 0; Part < UF; Part++) {
2653       Instruction *NewLoad;
2654       if (BlockInMask || MaskForGaps) {
2655         assert(useMaskedInterleavedAccesses(*TTI) &&
2656                "masked interleaved groups are not allowed.");
2657         Value *GroupMask = MaskForGaps;
2658         if (BlockInMask) {
2659           Value *BlockInMaskPart = State.get(BlockInMask, Part);
2660           assert(!VF.isScalable() && "scalable vectors not yet supported.");
2661           Value *ShuffledMask = Builder.CreateShuffleVector(
2662               BlockInMaskPart,
2663               createReplicatedMask(InterleaveFactor, VF.getKnownMinValue()),
2664               "interleaved.mask");
2665           GroupMask = MaskForGaps
2666                           ? Builder.CreateBinOp(Instruction::And, ShuffledMask,
2667                                                 MaskForGaps)
2668                           : ShuffledMask;
2669         }
2670         NewLoad =
2671             Builder.CreateMaskedLoad(AddrParts[Part], Group->getAlign(),
2672                                      GroupMask, PoisonVec, "wide.masked.vec");
2673       }
2674       else
2675         NewLoad = Builder.CreateAlignedLoad(VecTy, AddrParts[Part],
2676                                             Group->getAlign(), "wide.vec");
2677       Group->addMetadata(NewLoad);
2678       NewLoads.push_back(NewLoad);
2679     }
2680 
2681     // For each member in the group, shuffle out the appropriate data from the
2682     // wide loads.
2683     unsigned J = 0;
2684     for (unsigned I = 0; I < InterleaveFactor; ++I) {
2685       Instruction *Member = Group->getMember(I);
2686 
2687       // Skip the gaps in the group.
2688       if (!Member)
2689         continue;
2690 
2691       assert(!VF.isScalable() && "scalable vectors not yet supported.");
2692       auto StrideMask =
2693           createStrideMask(I, InterleaveFactor, VF.getKnownMinValue());
2694       for (unsigned Part = 0; Part < UF; Part++) {
2695         Value *StridedVec = Builder.CreateShuffleVector(
2696             NewLoads[Part], StrideMask, "strided.vec");
2697 
2698         // If this member has different type, cast the result type.
2699         if (Member->getType() != ScalarTy) {
2700           assert(!VF.isScalable() && "VF is assumed to be non scalable.");
2701           VectorType *OtherVTy = VectorType::get(Member->getType(), VF);
2702           StridedVec = createBitOrPointerCast(StridedVec, OtherVTy, DL);
2703         }
2704 
2705         if (Group->isReverse())
2706           StridedVec = reverseVector(StridedVec);
2707 
2708         State.set(VPDefs[J], Member, StridedVec, Part);
2709       }
2710       ++J;
2711     }
2712     return;
2713   }
2714 
2715   // The sub vector type for current instruction.
2716   assert(!VF.isScalable() && "VF is assumed to be non scalable.");
2717   auto *SubVT = VectorType::get(ScalarTy, VF);
2718 
2719   // Vectorize the interleaved store group.
2720   for (unsigned Part = 0; Part < UF; Part++) {
2721     // Collect the stored vector from each member.
2722     SmallVector<Value *, 4> StoredVecs;
2723     for (unsigned i = 0; i < InterleaveFactor; i++) {
2724       // Interleaved store group doesn't allow a gap, so each index has a member
2725       assert(Group->getMember(i) && "Fail to get a member from an interleaved store group");
2726 
2727       Value *StoredVec = State.get(StoredValues[i], Part);
2728 
2729       if (Group->isReverse())
2730         StoredVec = reverseVector(StoredVec);
2731 
2732       // If this member has different type, cast it to a unified type.
2733 
2734       if (StoredVec->getType() != SubVT)
2735         StoredVec = createBitOrPointerCast(StoredVec, SubVT, DL);
2736 
2737       StoredVecs.push_back(StoredVec);
2738     }
2739 
2740     // Concatenate all vectors into a wide vector.
2741     Value *WideVec = concatenateVectors(Builder, StoredVecs);
2742 
2743     // Interleave the elements in the wide vector.
2744     assert(!VF.isScalable() && "scalable vectors not yet supported.");
2745     Value *IVec = Builder.CreateShuffleVector(
2746         WideVec, createInterleaveMask(VF.getKnownMinValue(), InterleaveFactor),
2747         "interleaved.vec");
2748 
2749     Instruction *NewStoreInstr;
2750     if (BlockInMask) {
2751       Value *BlockInMaskPart = State.get(BlockInMask, Part);
2752       Value *ShuffledMask = Builder.CreateShuffleVector(
2753           BlockInMaskPart,
2754           createReplicatedMask(InterleaveFactor, VF.getKnownMinValue()),
2755           "interleaved.mask");
2756       NewStoreInstr = Builder.CreateMaskedStore(
2757           IVec, AddrParts[Part], Group->getAlign(), ShuffledMask);
2758     }
2759     else
2760       NewStoreInstr =
2761           Builder.CreateAlignedStore(IVec, AddrParts[Part], Group->getAlign());
2762 
2763     Group->addMetadata(NewStoreInstr);
2764   }
2765 }
2766 
2767 void InnerLoopVectorizer::vectorizeMemoryInstruction(
2768     Instruction *Instr, VPTransformState &State, VPValue *Def, VPValue *Addr,
2769     VPValue *StoredValue, VPValue *BlockInMask) {
2770   // Attempt to issue a wide load.
2771   LoadInst *LI = dyn_cast<LoadInst>(Instr);
2772   StoreInst *SI = dyn_cast<StoreInst>(Instr);
2773 
2774   assert((LI || SI) && "Invalid Load/Store instruction");
2775   assert((!SI || StoredValue) && "No stored value provided for widened store");
2776   assert((!LI || !StoredValue) && "Stored value provided for widened load");
2777 
2778   LoopVectorizationCostModel::InstWidening Decision =
2779       Cost->getWideningDecision(Instr, VF);
2780   assert((Decision == LoopVectorizationCostModel::CM_Widen ||
2781           Decision == LoopVectorizationCostModel::CM_Widen_Reverse ||
2782           Decision == LoopVectorizationCostModel::CM_GatherScatter) &&
2783          "CM decision is not to widen the memory instruction");
2784 
2785   Type *ScalarDataTy = getMemInstValueType(Instr);
2786 
2787   auto *DataTy = VectorType::get(ScalarDataTy, VF);
2788   const Align Alignment = getLoadStoreAlignment(Instr);
2789 
2790   // Determine if the pointer operand of the access is either consecutive or
2791   // reverse consecutive.
2792   bool Reverse = (Decision == LoopVectorizationCostModel::CM_Widen_Reverse);
2793   bool ConsecutiveStride =
2794       Reverse || (Decision == LoopVectorizationCostModel::CM_Widen);
2795   bool CreateGatherScatter =
2796       (Decision == LoopVectorizationCostModel::CM_GatherScatter);
2797 
2798   // Either Ptr feeds a vector load/store, or a vector GEP should feed a vector
2799   // gather/scatter. Otherwise Decision should have been to Scalarize.
2800   assert((ConsecutiveStride || CreateGatherScatter) &&
2801          "The instruction should be scalarized");
2802   (void)ConsecutiveStride;
2803 
2804   VectorParts BlockInMaskParts(UF);
2805   bool isMaskRequired = BlockInMask;
2806   if (isMaskRequired)
2807     for (unsigned Part = 0; Part < UF; ++Part)
2808       BlockInMaskParts[Part] = State.get(BlockInMask, Part);
2809 
2810   const auto CreateVecPtr = [&](unsigned Part, Value *Ptr) -> Value * {
2811     // Calculate the pointer for the specific unroll-part.
2812     GetElementPtrInst *PartPtr = nullptr;
2813 
2814     bool InBounds = false;
2815     if (auto *gep = dyn_cast<GetElementPtrInst>(Ptr->stripPointerCasts()))
2816       InBounds = gep->isInBounds();
2817 
2818     if (Reverse) {
2819       assert(!VF.isScalable() &&
2820              "Reversing vectors is not yet supported for scalable vectors.");
2821 
2822       // If the address is consecutive but reversed, then the
2823       // wide store needs to start at the last vector element.
2824       PartPtr = cast<GetElementPtrInst>(Builder.CreateGEP(
2825           ScalarDataTy, Ptr, Builder.getInt32(-Part * VF.getKnownMinValue())));
2826       PartPtr->setIsInBounds(InBounds);
2827       PartPtr = cast<GetElementPtrInst>(Builder.CreateGEP(
2828           ScalarDataTy, PartPtr, Builder.getInt32(1 - VF.getKnownMinValue())));
2829       PartPtr->setIsInBounds(InBounds);
2830       if (isMaskRequired) // Reverse of a null all-one mask is a null mask.
2831         BlockInMaskParts[Part] = reverseVector(BlockInMaskParts[Part]);
2832     } else {
2833       Value *Increment = createStepForVF(Builder, Builder.getInt32(Part), VF);
2834       PartPtr = cast<GetElementPtrInst>(
2835           Builder.CreateGEP(ScalarDataTy, Ptr, Increment));
2836       PartPtr->setIsInBounds(InBounds);
2837     }
2838 
2839     unsigned AddressSpace = Ptr->getType()->getPointerAddressSpace();
2840     return Builder.CreateBitCast(PartPtr, DataTy->getPointerTo(AddressSpace));
2841   };
2842 
2843   // Handle Stores:
2844   if (SI) {
2845     setDebugLocFromInst(Builder, SI);
2846 
2847     for (unsigned Part = 0; Part < UF; ++Part) {
2848       Instruction *NewSI = nullptr;
2849       Value *StoredVal = State.get(StoredValue, Part);
2850       if (CreateGatherScatter) {
2851         Value *MaskPart = isMaskRequired ? BlockInMaskParts[Part] : nullptr;
2852         Value *VectorGep = State.get(Addr, Part);
2853         NewSI = Builder.CreateMaskedScatter(StoredVal, VectorGep, Alignment,
2854                                             MaskPart);
2855       } else {
2856         if (Reverse) {
2857           // If we store to reverse consecutive memory locations, then we need
2858           // to reverse the order of elements in the stored value.
2859           StoredVal = reverseVector(StoredVal);
2860           // We don't want to update the value in the map as it might be used in
2861           // another expression. So don't call resetVectorValue(StoredVal).
2862         }
2863         auto *VecPtr = CreateVecPtr(Part, State.get(Addr, VPIteration(0, 0)));
2864         if (isMaskRequired)
2865           NewSI = Builder.CreateMaskedStore(StoredVal, VecPtr, Alignment,
2866                                             BlockInMaskParts[Part]);
2867         else
2868           NewSI = Builder.CreateAlignedStore(StoredVal, VecPtr, Alignment);
2869       }
2870       addMetadata(NewSI, SI);
2871     }
2872     return;
2873   }
2874 
2875   // Handle loads.
2876   assert(LI && "Must have a load instruction");
2877   setDebugLocFromInst(Builder, LI);
2878   for (unsigned Part = 0; Part < UF; ++Part) {
2879     Value *NewLI;
2880     if (CreateGatherScatter) {
2881       Value *MaskPart = isMaskRequired ? BlockInMaskParts[Part] : nullptr;
2882       Value *VectorGep = State.get(Addr, Part);
2883       NewLI = Builder.CreateMaskedGather(VectorGep, Alignment, MaskPart,
2884                                          nullptr, "wide.masked.gather");
2885       addMetadata(NewLI, LI);
2886     } else {
2887       auto *VecPtr = CreateVecPtr(Part, State.get(Addr, VPIteration(0, 0)));
2888       if (isMaskRequired)
2889         NewLI = Builder.CreateMaskedLoad(
2890             VecPtr, Alignment, BlockInMaskParts[Part], PoisonValue::get(DataTy),
2891             "wide.masked.load");
2892       else
2893         NewLI =
2894             Builder.CreateAlignedLoad(DataTy, VecPtr, Alignment, "wide.load");
2895 
2896       // Add metadata to the load, but setVectorValue to the reverse shuffle.
2897       addMetadata(NewLI, LI);
2898       if (Reverse)
2899         NewLI = reverseVector(NewLI);
2900     }
2901 
2902     State.set(Def, Instr, NewLI, Part);
2903   }
2904 }
2905 
2906 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr, VPUser &User,
2907                                                const VPIteration &Instance,
2908                                                bool IfPredicateInstr,
2909                                                VPTransformState &State) {
2910   assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
2911 
2912   // llvm.experimental.noalias.scope.decl intrinsics must only be duplicated for
2913   // the first lane and part.
2914   if (isa<NoAliasScopeDeclInst>(Instr))
2915     if (!Instance.isFirstIteration())
2916       return;
2917 
2918   setDebugLocFromInst(Builder, Instr);
2919 
2920   // Does this instruction return a value ?
2921   bool IsVoidRetTy = Instr->getType()->isVoidTy();
2922 
2923   Instruction *Cloned = Instr->clone();
2924   if (!IsVoidRetTy)
2925     Cloned->setName(Instr->getName() + ".cloned");
2926 
2927   // Replace the operands of the cloned instructions with their scalar
2928   // equivalents in the new loop.
2929   for (unsigned op = 0, e = User.getNumOperands(); op != e; ++op) {
2930     auto *Operand = dyn_cast<Instruction>(Instr->getOperand(op));
2931     auto InputInstance = Instance;
2932     if (!Operand || !OrigLoop->contains(Operand) ||
2933         (Cost->isUniformAfterVectorization(Operand, State.VF)))
2934       InputInstance.Lane = 0;
2935     auto *NewOp = State.get(User.getOperand(op), InputInstance);
2936     Cloned->setOperand(op, NewOp);
2937   }
2938   addNewMetadata(Cloned, Instr);
2939 
2940   // Place the cloned scalar in the new loop.
2941   Builder.Insert(Cloned);
2942 
2943   // TODO: Set result for VPValue of VPReciplicateRecipe. This requires
2944   // representing scalar values in VPTransformState. Add the cloned scalar to
2945   // the scalar map entry.
2946   VectorLoopValueMap.setScalarValue(Instr, Instance, Cloned);
2947 
2948   // If we just cloned a new assumption, add it the assumption cache.
2949   if (auto *II = dyn_cast<IntrinsicInst>(Cloned))
2950     if (II->getIntrinsicID() == Intrinsic::assume)
2951       AC->registerAssumption(II);
2952 
2953   // End if-block.
2954   if (IfPredicateInstr)
2955     PredicatedInstructions.push_back(Cloned);
2956 }
2957 
2958 PHINode *InnerLoopVectorizer::createInductionVariable(Loop *L, Value *Start,
2959                                                       Value *End, Value *Step,
2960                                                       Instruction *DL) {
2961   BasicBlock *Header = L->getHeader();
2962   BasicBlock *Latch = L->getLoopLatch();
2963   // As we're just creating this loop, it's possible no latch exists
2964   // yet. If so, use the header as this will be a single block loop.
2965   if (!Latch)
2966     Latch = Header;
2967 
2968   IRBuilder<> Builder(&*Header->getFirstInsertionPt());
2969   Instruction *OldInst = getDebugLocFromInstOrOperands(OldInduction);
2970   setDebugLocFromInst(Builder, OldInst);
2971   auto *Induction = Builder.CreatePHI(Start->getType(), 2, "index");
2972 
2973   Builder.SetInsertPoint(Latch->getTerminator());
2974   setDebugLocFromInst(Builder, OldInst);
2975 
2976   // Create i+1 and fill the PHINode.
2977   Value *Next = Builder.CreateAdd(Induction, Step, "index.next");
2978   Induction->addIncoming(Start, L->getLoopPreheader());
2979   Induction->addIncoming(Next, Latch);
2980   // Create the compare.
2981   Value *ICmp = Builder.CreateICmpEQ(Next, End);
2982   Builder.CreateCondBr(ICmp, L->getUniqueExitBlock(), Header);
2983 
2984   // Now we have two terminators. Remove the old one from the block.
2985   Latch->getTerminator()->eraseFromParent();
2986 
2987   return Induction;
2988 }
2989 
2990 Value *InnerLoopVectorizer::getOrCreateTripCount(Loop *L) {
2991   if (TripCount)
2992     return TripCount;
2993 
2994   assert(L && "Create Trip Count for null loop.");
2995   IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
2996   // Find the loop boundaries.
2997   ScalarEvolution *SE = PSE.getSE();
2998   const SCEV *BackedgeTakenCount = PSE.getBackedgeTakenCount();
2999   assert(!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
3000          "Invalid loop count");
3001 
3002   Type *IdxTy = Legal->getWidestInductionType();
3003   assert(IdxTy && "No type for induction");
3004 
3005   // The exit count might have the type of i64 while the phi is i32. This can
3006   // happen if we have an induction variable that is sign extended before the
3007   // compare. The only way that we get a backedge taken count is that the
3008   // induction variable was signed and as such will not overflow. In such a case
3009   // truncation is legal.
3010   if (SE->getTypeSizeInBits(BackedgeTakenCount->getType()) >
3011       IdxTy->getPrimitiveSizeInBits())
3012     BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount, IdxTy);
3013   BackedgeTakenCount = SE->getNoopOrZeroExtend(BackedgeTakenCount, IdxTy);
3014 
3015   // Get the total trip count from the count by adding 1.
3016   const SCEV *ExitCount = SE->getAddExpr(
3017       BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType()));
3018 
3019   const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
3020 
3021   // Expand the trip count and place the new instructions in the preheader.
3022   // Notice that the pre-header does not change, only the loop body.
3023   SCEVExpander Exp(*SE, DL, "induction");
3024 
3025   // Count holds the overall loop count (N).
3026   TripCount = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
3027                                 L->getLoopPreheader()->getTerminator());
3028 
3029   if (TripCount->getType()->isPointerTy())
3030     TripCount =
3031         CastInst::CreatePointerCast(TripCount, IdxTy, "exitcount.ptrcnt.to.int",
3032                                     L->getLoopPreheader()->getTerminator());
3033 
3034   return TripCount;
3035 }
3036 
3037 Value *InnerLoopVectorizer::getOrCreateVectorTripCount(Loop *L) {
3038   if (VectorTripCount)
3039     return VectorTripCount;
3040 
3041   Value *TC = getOrCreateTripCount(L);
3042   IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
3043 
3044   Type *Ty = TC->getType();
3045   // This is where we can make the step a runtime constant.
3046   Value *Step = createStepForVF(Builder, ConstantInt::get(Ty, UF), VF);
3047 
3048   // If the tail is to be folded by masking, round the number of iterations N
3049   // up to a multiple of Step instead of rounding down. This is done by first
3050   // adding Step-1 and then rounding down. Note that it's ok if this addition
3051   // overflows: the vector induction variable will eventually wrap to zero given
3052   // that it starts at zero and its Step is a power of two; the loop will then
3053   // exit, with the last early-exit vector comparison also producing all-true.
3054   if (Cost->foldTailByMasking()) {
3055     assert(isPowerOf2_32(VF.getKnownMinValue() * UF) &&
3056            "VF*UF must be a power of 2 when folding tail by masking");
3057     assert(!VF.isScalable() &&
3058            "Tail folding not yet supported for scalable vectors");
3059     TC = Builder.CreateAdd(
3060         TC, ConstantInt::get(Ty, VF.getKnownMinValue() * UF - 1), "n.rnd.up");
3061   }
3062 
3063   // Now we need to generate the expression for the part of the loop that the
3064   // vectorized body will execute. This is equal to N - (N % Step) if scalar
3065   // iterations are not required for correctness, or N - Step, otherwise. Step
3066   // is equal to the vectorization factor (number of SIMD elements) times the
3067   // unroll factor (number of SIMD instructions).
3068   Value *R = Builder.CreateURem(TC, Step, "n.mod.vf");
3069 
3070   // There are two cases where we need to ensure (at least) the last iteration
3071   // runs in the scalar remainder loop. Thus, if the step evenly divides
3072   // the trip count, we set the remainder to be equal to the step. If the step
3073   // does not evenly divide the trip count, no adjustment is necessary since
3074   // there will already be scalar iterations. Note that the minimum iterations
3075   // check ensures that N >= Step. The cases are:
3076   // 1) If there is a non-reversed interleaved group that may speculatively
3077   //    access memory out-of-bounds.
3078   // 2) If any instruction may follow a conditionally taken exit. That is, if
3079   //    the loop contains multiple exiting blocks, or a single exiting block
3080   //    which is not the latch.
3081   if (VF.isVector() && Cost->requiresScalarEpilogue()) {
3082     auto *IsZero = Builder.CreateICmpEQ(R, ConstantInt::get(R->getType(), 0));
3083     R = Builder.CreateSelect(IsZero, Step, R);
3084   }
3085 
3086   VectorTripCount = Builder.CreateSub(TC, R, "n.vec");
3087 
3088   return VectorTripCount;
3089 }
3090 
3091 Value *InnerLoopVectorizer::createBitOrPointerCast(Value *V, VectorType *DstVTy,
3092                                                    const DataLayout &DL) {
3093   // Verify that V is a vector type with same number of elements as DstVTy.
3094   auto *DstFVTy = cast<FixedVectorType>(DstVTy);
3095   unsigned VF = DstFVTy->getNumElements();
3096   auto *SrcVecTy = cast<FixedVectorType>(V->getType());
3097   assert((VF == SrcVecTy->getNumElements()) && "Vector dimensions do not match");
3098   Type *SrcElemTy = SrcVecTy->getElementType();
3099   Type *DstElemTy = DstFVTy->getElementType();
3100   assert((DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy)) &&
3101          "Vector elements must have same size");
3102 
3103   // Do a direct cast if element types are castable.
3104   if (CastInst::isBitOrNoopPointerCastable(SrcElemTy, DstElemTy, DL)) {
3105     return Builder.CreateBitOrPointerCast(V, DstFVTy);
3106   }
3107   // V cannot be directly casted to desired vector type.
3108   // May happen when V is a floating point vector but DstVTy is a vector of
3109   // pointers or vice-versa. Handle this using a two-step bitcast using an
3110   // intermediate Integer type for the bitcast i.e. Ptr <-> Int <-> Float.
3111   assert((DstElemTy->isPointerTy() != SrcElemTy->isPointerTy()) &&
3112          "Only one type should be a pointer type");
3113   assert((DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy()) &&
3114          "Only one type should be a floating point type");
3115   Type *IntTy =
3116       IntegerType::getIntNTy(V->getContext(), DL.getTypeSizeInBits(SrcElemTy));
3117   auto *VecIntTy = FixedVectorType::get(IntTy, VF);
3118   Value *CastVal = Builder.CreateBitOrPointerCast(V, VecIntTy);
3119   return Builder.CreateBitOrPointerCast(CastVal, DstFVTy);
3120 }
3121 
3122 void InnerLoopVectorizer::emitMinimumIterationCountCheck(Loop *L,
3123                                                          BasicBlock *Bypass) {
3124   Value *Count = getOrCreateTripCount(L);
3125   // Reuse existing vector loop preheader for TC checks.
3126   // Note that new preheader block is generated for vector loop.
3127   BasicBlock *const TCCheckBlock = LoopVectorPreHeader;
3128   IRBuilder<> Builder(TCCheckBlock->getTerminator());
3129 
3130   // Generate code to check if the loop's trip count is less than VF * UF, or
3131   // equal to it in case a scalar epilogue is required; this implies that the
3132   // vector trip count is zero. This check also covers the case where adding one
3133   // to the backedge-taken count overflowed leading to an incorrect trip count
3134   // of zero. In this case we will also jump to the scalar loop.
3135   auto P = Cost->requiresScalarEpilogue() ? ICmpInst::ICMP_ULE
3136                                           : ICmpInst::ICMP_ULT;
3137 
3138   // If tail is to be folded, vector loop takes care of all iterations.
3139   Value *CheckMinIters = Builder.getFalse();
3140   if (!Cost->foldTailByMasking()) {
3141     Value *Step =
3142         createStepForVF(Builder, ConstantInt::get(Count->getType(), UF), VF);
3143     CheckMinIters = Builder.CreateICmp(P, Count, Step, "min.iters.check");
3144   }
3145   // Create new preheader for vector loop.
3146   LoopVectorPreHeader =
3147       SplitBlock(TCCheckBlock, TCCheckBlock->getTerminator(), DT, LI, nullptr,
3148                  "vector.ph");
3149 
3150   assert(DT->properlyDominates(DT->getNode(TCCheckBlock),
3151                                DT->getNode(Bypass)->getIDom()) &&
3152          "TC check is expected to dominate Bypass");
3153 
3154   // Update dominator for Bypass & LoopExit.
3155   DT->changeImmediateDominator(Bypass, TCCheckBlock);
3156   DT->changeImmediateDominator(LoopExitBlock, TCCheckBlock);
3157 
3158   ReplaceInstWithInst(
3159       TCCheckBlock->getTerminator(),
3160       BranchInst::Create(Bypass, LoopVectorPreHeader, CheckMinIters));
3161   LoopBypassBlocks.push_back(TCCheckBlock);
3162 }
3163 
3164 void InnerLoopVectorizer::emitSCEVChecks(Loop *L, BasicBlock *Bypass) {
3165   // Reuse existing vector loop preheader for SCEV checks.
3166   // Note that new preheader block is generated for vector loop.
3167   BasicBlock *const SCEVCheckBlock = LoopVectorPreHeader;
3168 
3169   // Generate the code to check that the SCEV assumptions that we made.
3170   // We want the new basic block to start at the first instruction in a
3171   // sequence of instructions that form a check.
3172   SCEVExpander Exp(*PSE.getSE(), Bypass->getModule()->getDataLayout(),
3173                    "scev.check");
3174   Value *SCEVCheck = Exp.expandCodeForPredicate(
3175       &PSE.getUnionPredicate(), SCEVCheckBlock->getTerminator());
3176 
3177   if (auto *C = dyn_cast<ConstantInt>(SCEVCheck))
3178     if (C->isZero())
3179       return;
3180 
3181   assert(!(SCEVCheckBlock->getParent()->hasOptSize() ||
3182            (OptForSizeBasedOnProfile &&
3183             Cost->Hints->getForce() != LoopVectorizeHints::FK_Enabled)) &&
3184          "Cannot SCEV check stride or overflow when optimizing for size");
3185 
3186   SCEVCheckBlock->setName("vector.scevcheck");
3187   // Create new preheader for vector loop.
3188   LoopVectorPreHeader =
3189       SplitBlock(SCEVCheckBlock, SCEVCheckBlock->getTerminator(), DT, LI,
3190                  nullptr, "vector.ph");
3191 
3192   // Update dominator only if this is first RT check.
3193   if (LoopBypassBlocks.empty()) {
3194     DT->changeImmediateDominator(Bypass, SCEVCheckBlock);
3195     DT->changeImmediateDominator(LoopExitBlock, SCEVCheckBlock);
3196   }
3197 
3198   ReplaceInstWithInst(
3199       SCEVCheckBlock->getTerminator(),
3200       BranchInst::Create(Bypass, LoopVectorPreHeader, SCEVCheck));
3201   LoopBypassBlocks.push_back(SCEVCheckBlock);
3202   AddedSafetyChecks = true;
3203 }
3204 
3205 void InnerLoopVectorizer::emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass) {
3206   // VPlan-native path does not do any analysis for runtime checks currently.
3207   if (EnableVPlanNativePath)
3208     return;
3209 
3210   // Reuse existing vector loop preheader for runtime memory checks.
3211   // Note that new preheader block is generated for vector loop.
3212   BasicBlock *const MemCheckBlock = L->getLoopPreheader();
3213 
3214   // Generate the code that checks in runtime if arrays overlap. We put the
3215   // checks into a separate block to make the more common case of few elements
3216   // faster.
3217   auto *LAI = Legal->getLAI();
3218   const auto &RtPtrChecking = *LAI->getRuntimePointerChecking();
3219   if (!RtPtrChecking.Need)
3220     return;
3221 
3222   if (MemCheckBlock->getParent()->hasOptSize() || OptForSizeBasedOnProfile) {
3223     assert(Cost->Hints->getForce() == LoopVectorizeHints::FK_Enabled &&
3224            "Cannot emit memory checks when optimizing for size, unless forced "
3225            "to vectorize.");
3226     ORE->emit([&]() {
3227       return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationCodeSize",
3228                                         L->getStartLoc(), L->getHeader())
3229              << "Code-size may be reduced by not forcing "
3230                 "vectorization, or by source-code modifications "
3231                 "eliminating the need for runtime checks "
3232                 "(e.g., adding 'restrict').";
3233     });
3234   }
3235 
3236   MemCheckBlock->setName("vector.memcheck");
3237   // Create new preheader for vector loop.
3238   LoopVectorPreHeader =
3239       SplitBlock(MemCheckBlock, MemCheckBlock->getTerminator(), DT, LI, nullptr,
3240                  "vector.ph");
3241 
3242   auto *CondBranch = cast<BranchInst>(
3243       Builder.CreateCondBr(Builder.getTrue(), Bypass, LoopVectorPreHeader));
3244   ReplaceInstWithInst(MemCheckBlock->getTerminator(), CondBranch);
3245   LoopBypassBlocks.push_back(MemCheckBlock);
3246   AddedSafetyChecks = true;
3247 
3248   // Update dominator only if this is first RT check.
3249   if (LoopBypassBlocks.empty()) {
3250     DT->changeImmediateDominator(Bypass, MemCheckBlock);
3251     DT->changeImmediateDominator(LoopExitBlock, MemCheckBlock);
3252   }
3253 
3254   Instruction *FirstCheckInst;
3255   Instruction *MemRuntimeCheck;
3256   SCEVExpander Exp(*PSE.getSE(), MemCheckBlock->getModule()->getDataLayout(),
3257                    "induction");
3258   std::tie(FirstCheckInst, MemRuntimeCheck) = addRuntimeChecks(
3259       MemCheckBlock->getTerminator(), OrigLoop, RtPtrChecking.getChecks(), Exp);
3260   assert(MemRuntimeCheck && "no RT checks generated although RtPtrChecking "
3261                             "claimed checks are required");
3262   CondBranch->setCondition(MemRuntimeCheck);
3263 
3264   // We currently don't use LoopVersioning for the actual loop cloning but we
3265   // still use it to add the noalias metadata.
3266   LVer = std::make_unique<LoopVersioning>(
3267       *Legal->getLAI(),
3268       Legal->getLAI()->getRuntimePointerChecking()->getChecks(), OrigLoop, LI,
3269       DT, PSE.getSE());
3270   LVer->prepareNoAliasMetadata();
3271 }
3272 
3273 Value *InnerLoopVectorizer::emitTransformedIndex(
3274     IRBuilder<> &B, Value *Index, ScalarEvolution *SE, const DataLayout &DL,
3275     const InductionDescriptor &ID) const {
3276 
3277   SCEVExpander Exp(*SE, DL, "induction");
3278   auto Step = ID.getStep();
3279   auto StartValue = ID.getStartValue();
3280   assert(Index->getType() == Step->getType() &&
3281          "Index type does not match StepValue type");
3282 
3283   // Note: the IR at this point is broken. We cannot use SE to create any new
3284   // SCEV and then expand it, hoping that SCEV's simplification will give us
3285   // a more optimal code. Unfortunately, attempt of doing so on invalid IR may
3286   // lead to various SCEV crashes. So all we can do is to use builder and rely
3287   // on InstCombine for future simplifications. Here we handle some trivial
3288   // cases only.
3289   auto CreateAdd = [&B](Value *X, Value *Y) {
3290     assert(X->getType() == Y->getType() && "Types don't match!");
3291     if (auto *CX = dyn_cast<ConstantInt>(X))
3292       if (CX->isZero())
3293         return Y;
3294     if (auto *CY = dyn_cast<ConstantInt>(Y))
3295       if (CY->isZero())
3296         return X;
3297     return B.CreateAdd(X, Y);
3298   };
3299 
3300   auto CreateMul = [&B](Value *X, Value *Y) {
3301     assert(X->getType() == Y->getType() && "Types don't match!");
3302     if (auto *CX = dyn_cast<ConstantInt>(X))
3303       if (CX->isOne())
3304         return Y;
3305     if (auto *CY = dyn_cast<ConstantInt>(Y))
3306       if (CY->isOne())
3307         return X;
3308     return B.CreateMul(X, Y);
3309   };
3310 
3311   // Get a suitable insert point for SCEV expansion. For blocks in the vector
3312   // loop, choose the end of the vector loop header (=LoopVectorBody), because
3313   // the DomTree is not kept up-to-date for additional blocks generated in the
3314   // vector loop. By using the header as insertion point, we guarantee that the
3315   // expanded instructions dominate all their uses.
3316   auto GetInsertPoint = [this, &B]() {
3317     BasicBlock *InsertBB = B.GetInsertPoint()->getParent();
3318     if (InsertBB != LoopVectorBody &&
3319         LI->getLoopFor(LoopVectorBody) == LI->getLoopFor(InsertBB))
3320       return LoopVectorBody->getTerminator();
3321     return &*B.GetInsertPoint();
3322   };
3323   switch (ID.getKind()) {
3324   case InductionDescriptor::IK_IntInduction: {
3325     assert(Index->getType() == StartValue->getType() &&
3326            "Index type does not match StartValue type");
3327     if (ID.getConstIntStepValue() && ID.getConstIntStepValue()->isMinusOne())
3328       return B.CreateSub(StartValue, Index);
3329     auto *Offset = CreateMul(
3330         Index, Exp.expandCodeFor(Step, Index->getType(), GetInsertPoint()));
3331     return CreateAdd(StartValue, Offset);
3332   }
3333   case InductionDescriptor::IK_PtrInduction: {
3334     assert(isa<SCEVConstant>(Step) &&
3335            "Expected constant step for pointer induction");
3336     return B.CreateGEP(
3337         StartValue->getType()->getPointerElementType(), StartValue,
3338         CreateMul(Index,
3339                   Exp.expandCodeFor(Step, Index->getType(), GetInsertPoint())));
3340   }
3341   case InductionDescriptor::IK_FpInduction: {
3342     assert(Step->getType()->isFloatingPointTy() && "Expected FP Step value");
3343     auto InductionBinOp = ID.getInductionBinOp();
3344     assert(InductionBinOp &&
3345            (InductionBinOp->getOpcode() == Instruction::FAdd ||
3346             InductionBinOp->getOpcode() == Instruction::FSub) &&
3347            "Original bin op should be defined for FP induction");
3348 
3349     Value *StepValue = cast<SCEVUnknown>(Step)->getValue();
3350 
3351     // Floating point operations had to be 'fast' to enable the induction.
3352     FastMathFlags Flags;
3353     Flags.setFast();
3354 
3355     Value *MulExp = B.CreateFMul(StepValue, Index);
3356     if (isa<Instruction>(MulExp))
3357       // We have to check, the MulExp may be a constant.
3358       cast<Instruction>(MulExp)->setFastMathFlags(Flags);
3359 
3360     Value *BOp = B.CreateBinOp(InductionBinOp->getOpcode(), StartValue, MulExp,
3361                                "induction");
3362     if (isa<Instruction>(BOp))
3363       cast<Instruction>(BOp)->setFastMathFlags(Flags);
3364 
3365     return BOp;
3366   }
3367   case InductionDescriptor::IK_NoInduction:
3368     return nullptr;
3369   }
3370   llvm_unreachable("invalid enum");
3371 }
3372 
3373 Loop *InnerLoopVectorizer::createVectorLoopSkeleton(StringRef Prefix) {
3374   LoopScalarBody = OrigLoop->getHeader();
3375   LoopVectorPreHeader = OrigLoop->getLoopPreheader();
3376   LoopExitBlock = OrigLoop->getUniqueExitBlock();
3377   assert(LoopExitBlock && "Must have an exit block");
3378   assert(LoopVectorPreHeader && "Invalid loop structure");
3379 
3380   LoopMiddleBlock =
3381       SplitBlock(LoopVectorPreHeader, LoopVectorPreHeader->getTerminator(), DT,
3382                  LI, nullptr, Twine(Prefix) + "middle.block");
3383   LoopScalarPreHeader =
3384       SplitBlock(LoopMiddleBlock, LoopMiddleBlock->getTerminator(), DT, LI,
3385                  nullptr, Twine(Prefix) + "scalar.ph");
3386 
3387   // Set up branch from middle block to the exit and scalar preheader blocks.
3388   // completeLoopSkeleton will update the condition to use an iteration check,
3389   // if required to decide whether to execute the remainder.
3390   BranchInst *BrInst =
3391       BranchInst::Create(LoopExitBlock, LoopScalarPreHeader, Builder.getTrue());
3392   auto *ScalarLatchTerm = OrigLoop->getLoopLatch()->getTerminator();
3393   BrInst->setDebugLoc(ScalarLatchTerm->getDebugLoc());
3394   ReplaceInstWithInst(LoopMiddleBlock->getTerminator(), BrInst);
3395 
3396   // We intentionally don't let SplitBlock to update LoopInfo since
3397   // LoopVectorBody should belong to another loop than LoopVectorPreHeader.
3398   // LoopVectorBody is explicitly added to the correct place few lines later.
3399   LoopVectorBody =
3400       SplitBlock(LoopVectorPreHeader, LoopVectorPreHeader->getTerminator(), DT,
3401                  nullptr, nullptr, Twine(Prefix) + "vector.body");
3402 
3403   // Update dominator for loop exit.
3404   DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
3405 
3406   // Create and register the new vector loop.
3407   Loop *Lp = LI->AllocateLoop();
3408   Loop *ParentLoop = OrigLoop->getParentLoop();
3409 
3410   // Insert the new loop into the loop nest and register the new basic blocks
3411   // before calling any utilities such as SCEV that require valid LoopInfo.
3412   if (ParentLoop) {
3413     ParentLoop->addChildLoop(Lp);
3414   } else {
3415     LI->addTopLevelLoop(Lp);
3416   }
3417   Lp->addBasicBlockToLoop(LoopVectorBody, *LI);
3418   return Lp;
3419 }
3420 
3421 void InnerLoopVectorizer::createInductionResumeValues(
3422     Loop *L, Value *VectorTripCount,
3423     std::pair<BasicBlock *, Value *> AdditionalBypass) {
3424   assert(VectorTripCount && L && "Expected valid arguments");
3425   assert(((AdditionalBypass.first && AdditionalBypass.second) ||
3426           (!AdditionalBypass.first && !AdditionalBypass.second)) &&
3427          "Inconsistent information about additional bypass.");
3428   // We are going to resume the execution of the scalar loop.
3429   // Go over all of the induction variables that we found and fix the
3430   // PHIs that are left in the scalar version of the loop.
3431   // The starting values of PHI nodes depend on the counter of the last
3432   // iteration in the vectorized loop.
3433   // If we come from a bypass edge then we need to start from the original
3434   // start value.
3435   for (auto &InductionEntry : Legal->getInductionVars()) {
3436     PHINode *OrigPhi = InductionEntry.first;
3437     InductionDescriptor II = InductionEntry.second;
3438 
3439     // Create phi nodes to merge from the  backedge-taken check block.
3440     PHINode *BCResumeVal =
3441         PHINode::Create(OrigPhi->getType(), 3, "bc.resume.val",
3442                         LoopScalarPreHeader->getTerminator());
3443     // Copy original phi DL over to the new one.
3444     BCResumeVal->setDebugLoc(OrigPhi->getDebugLoc());
3445     Value *&EndValue = IVEndValues[OrigPhi];
3446     Value *EndValueFromAdditionalBypass = AdditionalBypass.second;
3447     if (OrigPhi == OldInduction) {
3448       // We know what the end value is.
3449       EndValue = VectorTripCount;
3450     } else {
3451       IRBuilder<> B(L->getLoopPreheader()->getTerminator());
3452       Type *StepType = II.getStep()->getType();
3453       Instruction::CastOps CastOp =
3454           CastInst::getCastOpcode(VectorTripCount, true, StepType, true);
3455       Value *CRD = B.CreateCast(CastOp, VectorTripCount, StepType, "cast.crd");
3456       const DataLayout &DL = LoopScalarBody->getModule()->getDataLayout();
3457       EndValue = emitTransformedIndex(B, CRD, PSE.getSE(), DL, II);
3458       EndValue->setName("ind.end");
3459 
3460       // Compute the end value for the additional bypass (if applicable).
3461       if (AdditionalBypass.first) {
3462         B.SetInsertPoint(&(*AdditionalBypass.first->getFirstInsertionPt()));
3463         CastOp = CastInst::getCastOpcode(AdditionalBypass.second, true,
3464                                          StepType, true);
3465         CRD =
3466             B.CreateCast(CastOp, AdditionalBypass.second, StepType, "cast.crd");
3467         EndValueFromAdditionalBypass =
3468             emitTransformedIndex(B, CRD, PSE.getSE(), DL, II);
3469         EndValueFromAdditionalBypass->setName("ind.end");
3470       }
3471     }
3472     // The new PHI merges the original incoming value, in case of a bypass,
3473     // or the value at the end of the vectorized loop.
3474     BCResumeVal->addIncoming(EndValue, LoopMiddleBlock);
3475 
3476     // Fix the scalar body counter (PHI node).
3477     // The old induction's phi node in the scalar body needs the truncated
3478     // value.
3479     for (BasicBlock *BB : LoopBypassBlocks)
3480       BCResumeVal->addIncoming(II.getStartValue(), BB);
3481 
3482     if (AdditionalBypass.first)
3483       BCResumeVal->setIncomingValueForBlock(AdditionalBypass.first,
3484                                             EndValueFromAdditionalBypass);
3485 
3486     OrigPhi->setIncomingValueForBlock(LoopScalarPreHeader, BCResumeVal);
3487   }
3488 }
3489 
3490 BasicBlock *InnerLoopVectorizer::completeLoopSkeleton(Loop *L,
3491                                                       MDNode *OrigLoopID) {
3492   assert(L && "Expected valid loop.");
3493 
3494   // The trip counts should be cached by now.
3495   Value *Count = getOrCreateTripCount(L);
3496   Value *VectorTripCount = getOrCreateVectorTripCount(L);
3497 
3498   auto *ScalarLatchTerm = OrigLoop->getLoopLatch()->getTerminator();
3499 
3500   // Add a check in the middle block to see if we have completed
3501   // all of the iterations in the first vector loop.
3502   // If (N - N%VF) == N, then we *don't* need to run the remainder.
3503   // If tail is to be folded, we know we don't need to run the remainder.
3504   if (!Cost->foldTailByMasking()) {
3505     Instruction *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
3506                                         Count, VectorTripCount, "cmp.n",
3507                                         LoopMiddleBlock->getTerminator());
3508 
3509     // Here we use the same DebugLoc as the scalar loop latch terminator instead
3510     // of the corresponding compare because they may have ended up with
3511     // different line numbers and we want to avoid awkward line stepping while
3512     // debugging. Eg. if the compare has got a line number inside the loop.
3513     CmpN->setDebugLoc(ScalarLatchTerm->getDebugLoc());
3514     cast<BranchInst>(LoopMiddleBlock->getTerminator())->setCondition(CmpN);
3515   }
3516 
3517   // Get ready to start creating new instructions into the vectorized body.
3518   assert(LoopVectorPreHeader == L->getLoopPreheader() &&
3519          "Inconsistent vector loop preheader");
3520   Builder.SetInsertPoint(&*LoopVectorBody->getFirstInsertionPt());
3521 
3522   Optional<MDNode *> VectorizedLoopID =
3523       makeFollowupLoopID(OrigLoopID, {LLVMLoopVectorizeFollowupAll,
3524                                       LLVMLoopVectorizeFollowupVectorized});
3525   if (VectorizedLoopID.hasValue()) {
3526     L->setLoopID(VectorizedLoopID.getValue());
3527 
3528     // Do not setAlreadyVectorized if loop attributes have been defined
3529     // explicitly.
3530     return LoopVectorPreHeader;
3531   }
3532 
3533   // Keep all loop hints from the original loop on the vector loop (we'll
3534   // replace the vectorizer-specific hints below).
3535   if (MDNode *LID = OrigLoop->getLoopID())
3536     L->setLoopID(LID);
3537 
3538   LoopVectorizeHints Hints(L, true, *ORE);
3539   Hints.setAlreadyVectorized();
3540 
3541 #ifdef EXPENSIVE_CHECKS
3542   assert(DT->verify(DominatorTree::VerificationLevel::Fast));
3543   LI->verify(*DT);
3544 #endif
3545 
3546   return LoopVectorPreHeader;
3547 }
3548 
3549 BasicBlock *InnerLoopVectorizer::createVectorizedLoopSkeleton() {
3550   /*
3551    In this function we generate a new loop. The new loop will contain
3552    the vectorized instructions while the old loop will continue to run the
3553    scalar remainder.
3554 
3555        [ ] <-- loop iteration number check.
3556     /   |
3557    /    v
3558   |    [ ] <-- vector loop bypass (may consist of multiple blocks).
3559   |  /  |
3560   | /   v
3561   ||   [ ]     <-- vector pre header.
3562   |/    |
3563   |     v
3564   |    [  ] \
3565   |    [  ]_|   <-- vector loop.
3566   |     |
3567   |     v
3568   |   -[ ]   <--- middle-block.
3569   |  /  |
3570   | /   v
3571   -|- >[ ]     <--- new preheader.
3572    |    |
3573    |    v
3574    |   [ ] \
3575    |   [ ]_|   <-- old scalar loop to handle remainder.
3576     \   |
3577      \  v
3578       >[ ]     <-- exit block.
3579    ...
3580    */
3581 
3582   // Get the metadata of the original loop before it gets modified.
3583   MDNode *OrigLoopID = OrigLoop->getLoopID();
3584 
3585   // Create an empty vector loop, and prepare basic blocks for the runtime
3586   // checks.
3587   Loop *Lp = createVectorLoopSkeleton("");
3588 
3589   // Now, compare the new count to zero. If it is zero skip the vector loop and
3590   // jump to the scalar loop. This check also covers the case where the
3591   // backedge-taken count is uint##_max: adding one to it will overflow leading
3592   // to an incorrect trip count of zero. In this (rare) case we will also jump
3593   // to the scalar loop.
3594   emitMinimumIterationCountCheck(Lp, LoopScalarPreHeader);
3595 
3596   // Generate the code to check any assumptions that we've made for SCEV
3597   // expressions.
3598   emitSCEVChecks(Lp, LoopScalarPreHeader);
3599 
3600   // Generate the code that checks in runtime if arrays overlap. We put the
3601   // checks into a separate block to make the more common case of few elements
3602   // faster.
3603   emitMemRuntimeChecks(Lp, LoopScalarPreHeader);
3604 
3605   // Some loops have a single integer induction variable, while other loops
3606   // don't. One example is c++ iterators that often have multiple pointer
3607   // induction variables. In the code below we also support a case where we
3608   // don't have a single induction variable.
3609   //
3610   // We try to obtain an induction variable from the original loop as hard
3611   // as possible. However if we don't find one that:
3612   //   - is an integer
3613   //   - counts from zero, stepping by one
3614   //   - is the size of the widest induction variable type
3615   // then we create a new one.
3616   OldInduction = Legal->getPrimaryInduction();
3617   Type *IdxTy = Legal->getWidestInductionType();
3618   Value *StartIdx = ConstantInt::get(IdxTy, 0);
3619   // The loop step is equal to the vectorization factor (num of SIMD elements)
3620   // times the unroll factor (num of SIMD instructions).
3621   Builder.SetInsertPoint(&*Lp->getHeader()->getFirstInsertionPt());
3622   Value *Step = createStepForVF(Builder, ConstantInt::get(IdxTy, UF), VF);
3623   Value *CountRoundDown = getOrCreateVectorTripCount(Lp);
3624   Induction =
3625       createInductionVariable(Lp, StartIdx, CountRoundDown, Step,
3626                               getDebugLocFromInstOrOperands(OldInduction));
3627 
3628   // Emit phis for the new starting index of the scalar loop.
3629   createInductionResumeValues(Lp, CountRoundDown);
3630 
3631   return completeLoopSkeleton(Lp, OrigLoopID);
3632 }
3633 
3634 // Fix up external users of the induction variable. At this point, we are
3635 // in LCSSA form, with all external PHIs that use the IV having one input value,
3636 // coming from the remainder loop. We need those PHIs to also have a correct
3637 // value for the IV when arriving directly from the middle block.
3638 void InnerLoopVectorizer::fixupIVUsers(PHINode *OrigPhi,
3639                                        const InductionDescriptor &II,
3640                                        Value *CountRoundDown, Value *EndValue,
3641                                        BasicBlock *MiddleBlock) {
3642   // There are two kinds of external IV usages - those that use the value
3643   // computed in the last iteration (the PHI) and those that use the penultimate
3644   // value (the value that feeds into the phi from the loop latch).
3645   // We allow both, but they, obviously, have different values.
3646 
3647   assert(OrigLoop->getUniqueExitBlock() && "Expected a single exit block");
3648 
3649   DenseMap<Value *, Value *> MissingVals;
3650 
3651   // An external user of the last iteration's value should see the value that
3652   // the remainder loop uses to initialize its own IV.
3653   Value *PostInc = OrigPhi->getIncomingValueForBlock(OrigLoop->getLoopLatch());
3654   for (User *U : PostInc->users()) {
3655     Instruction *UI = cast<Instruction>(U);
3656     if (!OrigLoop->contains(UI)) {
3657       assert(isa<PHINode>(UI) && "Expected LCSSA form");
3658       MissingVals[UI] = EndValue;
3659     }
3660   }
3661 
3662   // An external user of the penultimate value need to see EndValue - Step.
3663   // The simplest way to get this is to recompute it from the constituent SCEVs,
3664   // that is Start + (Step * (CRD - 1)).
3665   for (User *U : OrigPhi->users()) {
3666     auto *UI = cast<Instruction>(U);
3667     if (!OrigLoop->contains(UI)) {
3668       const DataLayout &DL =
3669           OrigLoop->getHeader()->getModule()->getDataLayout();
3670       assert(isa<PHINode>(UI) && "Expected LCSSA form");
3671 
3672       IRBuilder<> B(MiddleBlock->getTerminator());
3673       Value *CountMinusOne = B.CreateSub(
3674           CountRoundDown, ConstantInt::get(CountRoundDown->getType(), 1));
3675       Value *CMO =
3676           !II.getStep()->getType()->isIntegerTy()
3677               ? B.CreateCast(Instruction::SIToFP, CountMinusOne,
3678                              II.getStep()->getType())
3679               : B.CreateSExtOrTrunc(CountMinusOne, II.getStep()->getType());
3680       CMO->setName("cast.cmo");
3681       Value *Escape = emitTransformedIndex(B, CMO, PSE.getSE(), DL, II);
3682       Escape->setName("ind.escape");
3683       MissingVals[UI] = Escape;
3684     }
3685   }
3686 
3687   for (auto &I : MissingVals) {
3688     PHINode *PHI = cast<PHINode>(I.first);
3689     // One corner case we have to handle is two IVs "chasing" each-other,
3690     // that is %IV2 = phi [...], [ %IV1, %latch ]
3691     // In this case, if IV1 has an external use, we need to avoid adding both
3692     // "last value of IV1" and "penultimate value of IV2". So, verify that we
3693     // don't already have an incoming value for the middle block.
3694     if (PHI->getBasicBlockIndex(MiddleBlock) == -1)
3695       PHI->addIncoming(I.second, MiddleBlock);
3696   }
3697 }
3698 
3699 namespace {
3700 
3701 struct CSEDenseMapInfo {
3702   static bool canHandle(const Instruction *I) {
3703     return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
3704            isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
3705   }
3706 
3707   static inline Instruction *getEmptyKey() {
3708     return DenseMapInfo<Instruction *>::getEmptyKey();
3709   }
3710 
3711   static inline Instruction *getTombstoneKey() {
3712     return DenseMapInfo<Instruction *>::getTombstoneKey();
3713   }
3714 
3715   static unsigned getHashValue(const Instruction *I) {
3716     assert(canHandle(I) && "Unknown instruction!");
3717     return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
3718                                                            I->value_op_end()));
3719   }
3720 
3721   static bool isEqual(const Instruction *LHS, const Instruction *RHS) {
3722     if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
3723         LHS == getTombstoneKey() || RHS == getTombstoneKey())
3724       return LHS == RHS;
3725     return LHS->isIdenticalTo(RHS);
3726   }
3727 };
3728 
3729 } // end anonymous namespace
3730 
3731 ///Perform cse of induction variable instructions.
3732 static void cse(BasicBlock *BB) {
3733   // Perform simple cse.
3734   SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
3735   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
3736     Instruction *In = &*I++;
3737 
3738     if (!CSEDenseMapInfo::canHandle(In))
3739       continue;
3740 
3741     // Check if we can replace this instruction with any of the
3742     // visited instructions.
3743     if (Instruction *V = CSEMap.lookup(In)) {
3744       In->replaceAllUsesWith(V);
3745       In->eraseFromParent();
3746       continue;
3747     }
3748 
3749     CSEMap[In] = In;
3750   }
3751 }
3752 
3753 InstructionCost
3754 LoopVectorizationCostModel::getVectorCallCost(CallInst *CI, ElementCount VF,
3755                                               bool &NeedToScalarize) {
3756   Function *F = CI->getCalledFunction();
3757   Type *ScalarRetTy = CI->getType();
3758   SmallVector<Type *, 4> Tys, ScalarTys;
3759   for (auto &ArgOp : CI->arg_operands())
3760     ScalarTys.push_back(ArgOp->getType());
3761 
3762   // Estimate cost of scalarized vector call. The source operands are assumed
3763   // to be vectors, so we need to extract individual elements from there,
3764   // execute VF scalar calls, and then gather the result into the vector return
3765   // value.
3766   InstructionCost ScalarCallCost =
3767       TTI.getCallInstrCost(F, ScalarRetTy, ScalarTys, TTI::TCK_RecipThroughput);
3768   if (VF.isScalar())
3769     return ScalarCallCost;
3770 
3771   // Compute corresponding vector type for return value and arguments.
3772   Type *RetTy = ToVectorTy(ScalarRetTy, VF);
3773   for (Type *ScalarTy : ScalarTys)
3774     Tys.push_back(ToVectorTy(ScalarTy, VF));
3775 
3776   // Compute costs of unpacking argument values for the scalar calls and
3777   // packing the return values to a vector.
3778   InstructionCost ScalarizationCost = getScalarizationOverhead(CI, VF);
3779 
3780   InstructionCost Cost =
3781       ScalarCallCost * VF.getKnownMinValue() + ScalarizationCost;
3782 
3783   // If we can't emit a vector call for this function, then the currently found
3784   // cost is the cost we need to return.
3785   NeedToScalarize = true;
3786   VFShape Shape = VFShape::get(*CI, VF, false /*HasGlobalPred*/);
3787   Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
3788 
3789   if (!TLI || CI->isNoBuiltin() || !VecFunc)
3790     return Cost;
3791 
3792   // If the corresponding vector cost is cheaper, return its cost.
3793   InstructionCost VectorCallCost =
3794       TTI.getCallInstrCost(nullptr, RetTy, Tys, TTI::TCK_RecipThroughput);
3795   if (VectorCallCost < Cost) {
3796     NeedToScalarize = false;
3797     Cost = VectorCallCost;
3798   }
3799   return Cost;
3800 }
3801 
3802 InstructionCost
3803 LoopVectorizationCostModel::getVectorIntrinsicCost(CallInst *CI,
3804                                                    ElementCount VF) {
3805   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
3806   assert(ID && "Expected intrinsic call!");
3807 
3808   IntrinsicCostAttributes CostAttrs(ID, *CI, VF);
3809   return TTI.getIntrinsicInstrCost(CostAttrs,
3810                                    TargetTransformInfo::TCK_RecipThroughput);
3811 }
3812 
3813 static Type *smallestIntegerVectorType(Type *T1, Type *T2) {
3814   auto *I1 = cast<IntegerType>(cast<VectorType>(T1)->getElementType());
3815   auto *I2 = cast<IntegerType>(cast<VectorType>(T2)->getElementType());
3816   return I1->getBitWidth() < I2->getBitWidth() ? T1 : T2;
3817 }
3818 
3819 static Type *largestIntegerVectorType(Type *T1, Type *T2) {
3820   auto *I1 = cast<IntegerType>(cast<VectorType>(T1)->getElementType());
3821   auto *I2 = cast<IntegerType>(cast<VectorType>(T2)->getElementType());
3822   return I1->getBitWidth() > I2->getBitWidth() ? T1 : T2;
3823 }
3824 
3825 void InnerLoopVectorizer::truncateToMinimalBitwidths() {
3826   // For every instruction `I` in MinBWs, truncate the operands, create a
3827   // truncated version of `I` and reextend its result. InstCombine runs
3828   // later and will remove any ext/trunc pairs.
3829   SmallPtrSet<Value *, 4> Erased;
3830   for (const auto &KV : Cost->getMinimalBitwidths()) {
3831     // If the value wasn't vectorized, we must maintain the original scalar
3832     // type. The absence of the value from VectorLoopValueMap indicates that it
3833     // wasn't vectorized.
3834     if (!VectorLoopValueMap.hasAnyVectorValue(KV.first))
3835       continue;
3836     for (unsigned Part = 0; Part < UF; ++Part) {
3837       Value *I = getOrCreateVectorValue(KV.first, Part);
3838       if (Erased.count(I) || I->use_empty() || !isa<Instruction>(I))
3839         continue;
3840       Type *OriginalTy = I->getType();
3841       Type *ScalarTruncatedTy =
3842           IntegerType::get(OriginalTy->getContext(), KV.second);
3843       auto *TruncatedTy = FixedVectorType::get(
3844           ScalarTruncatedTy,
3845           cast<FixedVectorType>(OriginalTy)->getNumElements());
3846       if (TruncatedTy == OriginalTy)
3847         continue;
3848 
3849       IRBuilder<> B(cast<Instruction>(I));
3850       auto ShrinkOperand = [&](Value *V) -> Value * {
3851         if (auto *ZI = dyn_cast<ZExtInst>(V))
3852           if (ZI->getSrcTy() == TruncatedTy)
3853             return ZI->getOperand(0);
3854         return B.CreateZExtOrTrunc(V, TruncatedTy);
3855       };
3856 
3857       // The actual instruction modification depends on the instruction type,
3858       // unfortunately.
3859       Value *NewI = nullptr;
3860       if (auto *BO = dyn_cast<BinaryOperator>(I)) {
3861         NewI = B.CreateBinOp(BO->getOpcode(), ShrinkOperand(BO->getOperand(0)),
3862                              ShrinkOperand(BO->getOperand(1)));
3863 
3864         // Any wrapping introduced by shrinking this operation shouldn't be
3865         // considered undefined behavior. So, we can't unconditionally copy
3866         // arithmetic wrapping flags to NewI.
3867         cast<BinaryOperator>(NewI)->copyIRFlags(I, /*IncludeWrapFlags=*/false);
3868       } else if (auto *CI = dyn_cast<ICmpInst>(I)) {
3869         NewI =
3870             B.CreateICmp(CI->getPredicate(), ShrinkOperand(CI->getOperand(0)),
3871                          ShrinkOperand(CI->getOperand(1)));
3872       } else if (auto *SI = dyn_cast<SelectInst>(I)) {
3873         NewI = B.CreateSelect(SI->getCondition(),
3874                               ShrinkOperand(SI->getTrueValue()),
3875                               ShrinkOperand(SI->getFalseValue()));
3876       } else if (auto *CI = dyn_cast<CastInst>(I)) {
3877         switch (CI->getOpcode()) {
3878         default:
3879           llvm_unreachable("Unhandled cast!");
3880         case Instruction::Trunc:
3881           NewI = ShrinkOperand(CI->getOperand(0));
3882           break;
3883         case Instruction::SExt:
3884           NewI = B.CreateSExtOrTrunc(
3885               CI->getOperand(0),
3886               smallestIntegerVectorType(OriginalTy, TruncatedTy));
3887           break;
3888         case Instruction::ZExt:
3889           NewI = B.CreateZExtOrTrunc(
3890               CI->getOperand(0),
3891               smallestIntegerVectorType(OriginalTy, TruncatedTy));
3892           break;
3893         }
3894       } else if (auto *SI = dyn_cast<ShuffleVectorInst>(I)) {
3895         auto Elements0 = cast<FixedVectorType>(SI->getOperand(0)->getType())
3896                              ->getNumElements();
3897         auto *O0 = B.CreateZExtOrTrunc(
3898             SI->getOperand(0),
3899             FixedVectorType::get(ScalarTruncatedTy, Elements0));
3900         auto Elements1 = cast<FixedVectorType>(SI->getOperand(1)->getType())
3901                              ->getNumElements();
3902         auto *O1 = B.CreateZExtOrTrunc(
3903             SI->getOperand(1),
3904             FixedVectorType::get(ScalarTruncatedTy, Elements1));
3905 
3906         NewI = B.CreateShuffleVector(O0, O1, SI->getShuffleMask());
3907       } else if (isa<LoadInst>(I) || isa<PHINode>(I)) {
3908         // Don't do anything with the operands, just extend the result.
3909         continue;
3910       } else if (auto *IE = dyn_cast<InsertElementInst>(I)) {
3911         auto Elements = cast<FixedVectorType>(IE->getOperand(0)->getType())
3912                             ->getNumElements();
3913         auto *O0 = B.CreateZExtOrTrunc(
3914             IE->getOperand(0),
3915             FixedVectorType::get(ScalarTruncatedTy, Elements));
3916         auto *O1 = B.CreateZExtOrTrunc(IE->getOperand(1), ScalarTruncatedTy);
3917         NewI = B.CreateInsertElement(O0, O1, IE->getOperand(2));
3918       } else if (auto *EE = dyn_cast<ExtractElementInst>(I)) {
3919         auto Elements = cast<FixedVectorType>(EE->getOperand(0)->getType())
3920                             ->getNumElements();
3921         auto *O0 = B.CreateZExtOrTrunc(
3922             EE->getOperand(0),
3923             FixedVectorType::get(ScalarTruncatedTy, Elements));
3924         NewI = B.CreateExtractElement(O0, EE->getOperand(2));
3925       } else {
3926         // If we don't know what to do, be conservative and don't do anything.
3927         continue;
3928       }
3929 
3930       // Lastly, extend the result.
3931       NewI->takeName(cast<Instruction>(I));
3932       Value *Res = B.CreateZExtOrTrunc(NewI, OriginalTy);
3933       I->replaceAllUsesWith(Res);
3934       cast<Instruction>(I)->eraseFromParent();
3935       Erased.insert(I);
3936       VectorLoopValueMap.resetVectorValue(KV.first, Part, Res);
3937     }
3938   }
3939 
3940   // We'll have created a bunch of ZExts that are now parentless. Clean up.
3941   for (const auto &KV : Cost->getMinimalBitwidths()) {
3942     // If the value wasn't vectorized, we must maintain the original scalar
3943     // type. The absence of the value from VectorLoopValueMap indicates that it
3944     // wasn't vectorized.
3945     if (!VectorLoopValueMap.hasAnyVectorValue(KV.first))
3946       continue;
3947     for (unsigned Part = 0; Part < UF; ++Part) {
3948       Value *I = getOrCreateVectorValue(KV.first, Part);
3949       ZExtInst *Inst = dyn_cast<ZExtInst>(I);
3950       if (Inst && Inst->use_empty()) {
3951         Value *NewI = Inst->getOperand(0);
3952         Inst->eraseFromParent();
3953         VectorLoopValueMap.resetVectorValue(KV.first, Part, NewI);
3954       }
3955     }
3956   }
3957 }
3958 
3959 void InnerLoopVectorizer::fixVectorizedLoop(VPTransformState &State) {
3960   // Insert truncates and extends for any truncated instructions as hints to
3961   // InstCombine.
3962   if (VF.isVector())
3963     truncateToMinimalBitwidths();
3964 
3965   // Fix widened non-induction PHIs by setting up the PHI operands.
3966   if (OrigPHIsToFix.size()) {
3967     assert(EnableVPlanNativePath &&
3968            "Unexpected non-induction PHIs for fixup in non VPlan-native path");
3969     fixNonInductionPHIs(State);
3970   }
3971 
3972   // At this point every instruction in the original loop is widened to a
3973   // vector form. Now we need to fix the recurrences in the loop. These PHI
3974   // nodes are currently empty because we did not want to introduce cycles.
3975   // This is the second stage of vectorizing recurrences.
3976   fixCrossIterationPHIs(State);
3977 
3978   // Forget the original basic block.
3979   PSE.getSE()->forgetLoop(OrigLoop);
3980 
3981   // Fix-up external users of the induction variables.
3982   for (auto &Entry : Legal->getInductionVars())
3983     fixupIVUsers(Entry.first, Entry.second,
3984                  getOrCreateVectorTripCount(LI->getLoopFor(LoopVectorBody)),
3985                  IVEndValues[Entry.first], LoopMiddleBlock);
3986 
3987   fixLCSSAPHIs(State);
3988   for (Instruction *PI : PredicatedInstructions)
3989     sinkScalarOperands(&*PI);
3990 
3991   // Remove redundant induction instructions.
3992   cse(LoopVectorBody);
3993 
3994   // Set/update profile weights for the vector and remainder loops as original
3995   // loop iterations are now distributed among them. Note that original loop
3996   // represented by LoopScalarBody becomes remainder loop after vectorization.
3997   //
3998   // For cases like foldTailByMasking() and requiresScalarEpiloque() we may
3999   // end up getting slightly roughened result but that should be OK since
4000   // profile is not inherently precise anyway. Note also possible bypass of
4001   // vector code caused by legality checks is ignored, assigning all the weight
4002   // to the vector loop, optimistically.
4003   //
4004   // For scalable vectorization we can't know at compile time how many iterations
4005   // of the loop are handled in one vector iteration, so instead assume a pessimistic
4006   // vscale of '1'.
4007   setProfileInfoAfterUnrolling(
4008       LI->getLoopFor(LoopScalarBody), LI->getLoopFor(LoopVectorBody),
4009       LI->getLoopFor(LoopScalarBody), VF.getKnownMinValue() * UF);
4010 }
4011 
4012 void InnerLoopVectorizer::fixCrossIterationPHIs(VPTransformState &State) {
4013   // In order to support recurrences we need to be able to vectorize Phi nodes.
4014   // Phi nodes have cycles, so we need to vectorize them in two stages. This is
4015   // stage #2: We now need to fix the recurrences by adding incoming edges to
4016   // the currently empty PHI nodes. At this point every instruction in the
4017   // original loop is widened to a vector form so we can use them to construct
4018   // the incoming edges.
4019   for (PHINode &Phi : OrigLoop->getHeader()->phis()) {
4020     // Handle first-order recurrences and reductions that need to be fixed.
4021     if (Legal->isFirstOrderRecurrence(&Phi))
4022       fixFirstOrderRecurrence(&Phi, State);
4023     else if (Legal->isReductionVariable(&Phi))
4024       fixReduction(&Phi, State);
4025   }
4026 }
4027 
4028 void InnerLoopVectorizer::fixFirstOrderRecurrence(PHINode *Phi,
4029                                                   VPTransformState &State) {
4030   // This is the second phase of vectorizing first-order recurrences. An
4031   // overview of the transformation is described below. Suppose we have the
4032   // following loop.
4033   //
4034   //   for (int i = 0; i < n; ++i)
4035   //     b[i] = a[i] - a[i - 1];
4036   //
4037   // There is a first-order recurrence on "a". For this loop, the shorthand
4038   // scalar IR looks like:
4039   //
4040   //   scalar.ph:
4041   //     s_init = a[-1]
4042   //     br scalar.body
4043   //
4044   //   scalar.body:
4045   //     i = phi [0, scalar.ph], [i+1, scalar.body]
4046   //     s1 = phi [s_init, scalar.ph], [s2, scalar.body]
4047   //     s2 = a[i]
4048   //     b[i] = s2 - s1
4049   //     br cond, scalar.body, ...
4050   //
4051   // In this example, s1 is a recurrence because it's value depends on the
4052   // previous iteration. In the first phase of vectorization, we created a
4053   // temporary value for s1. We now complete the vectorization and produce the
4054   // shorthand vector IR shown below (for VF = 4, UF = 1).
4055   //
4056   //   vector.ph:
4057   //     v_init = vector(..., ..., ..., a[-1])
4058   //     br vector.body
4059   //
4060   //   vector.body
4061   //     i = phi [0, vector.ph], [i+4, vector.body]
4062   //     v1 = phi [v_init, vector.ph], [v2, vector.body]
4063   //     v2 = a[i, i+1, i+2, i+3];
4064   //     v3 = vector(v1(3), v2(0, 1, 2))
4065   //     b[i, i+1, i+2, i+3] = v2 - v3
4066   //     br cond, vector.body, middle.block
4067   //
4068   //   middle.block:
4069   //     x = v2(3)
4070   //     br scalar.ph
4071   //
4072   //   scalar.ph:
4073   //     s_init = phi [x, middle.block], [a[-1], otherwise]
4074   //     br scalar.body
4075   //
4076   // After execution completes the vector loop, we extract the next value of
4077   // the recurrence (x) to use as the initial value in the scalar loop.
4078 
4079   // Get the original loop preheader and single loop latch.
4080   auto *Preheader = OrigLoop->getLoopPreheader();
4081   auto *Latch = OrigLoop->getLoopLatch();
4082 
4083   // Get the initial and previous values of the scalar recurrence.
4084   auto *ScalarInit = Phi->getIncomingValueForBlock(Preheader);
4085   auto *Previous = Phi->getIncomingValueForBlock(Latch);
4086 
4087   // Create a vector from the initial value.
4088   auto *VectorInit = ScalarInit;
4089   if (VF.isVector()) {
4090     Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
4091     assert(!VF.isScalable() && "VF is assumed to be non scalable.");
4092     VectorInit = Builder.CreateInsertElement(
4093         PoisonValue::get(VectorType::get(VectorInit->getType(), VF)), VectorInit,
4094         Builder.getInt32(VF.getKnownMinValue() - 1), "vector.recur.init");
4095   }
4096 
4097   VPValue *PhiDef = State.Plan->getVPValue(Phi);
4098   VPValue *PreviousDef = State.Plan->getVPValue(Previous);
4099   // We constructed a temporary phi node in the first phase of vectorization.
4100   // This phi node will eventually be deleted.
4101   Builder.SetInsertPoint(cast<Instruction>(State.get(PhiDef, 0)));
4102 
4103   // Create a phi node for the new recurrence. The current value will either be
4104   // the initial value inserted into a vector or loop-varying vector value.
4105   auto *VecPhi = Builder.CreatePHI(VectorInit->getType(), 2, "vector.recur");
4106   VecPhi->addIncoming(VectorInit, LoopVectorPreHeader);
4107 
4108   // Get the vectorized previous value of the last part UF - 1. It appears last
4109   // among all unrolled iterations, due to the order of their construction.
4110   Value *PreviousLastPart = State.get(PreviousDef, UF - 1);
4111 
4112   // Find and set the insertion point after the previous value if it is an
4113   // instruction.
4114   BasicBlock::iterator InsertPt;
4115   // Note that the previous value may have been constant-folded so it is not
4116   // guaranteed to be an instruction in the vector loop.
4117   // FIXME: Loop invariant values do not form recurrences. We should deal with
4118   //        them earlier.
4119   if (LI->getLoopFor(LoopVectorBody)->isLoopInvariant(PreviousLastPart))
4120     InsertPt = LoopVectorBody->getFirstInsertionPt();
4121   else {
4122     Instruction *PreviousInst = cast<Instruction>(PreviousLastPart);
4123     if (isa<PHINode>(PreviousLastPart))
4124       // If the previous value is a phi node, we should insert after all the phi
4125       // nodes in the block containing the PHI to avoid breaking basic block
4126       // verification. Note that the basic block may be different to
4127       // LoopVectorBody, in case we predicate the loop.
4128       InsertPt = PreviousInst->getParent()->getFirstInsertionPt();
4129     else
4130       InsertPt = ++PreviousInst->getIterator();
4131   }
4132   Builder.SetInsertPoint(&*InsertPt);
4133 
4134   // We will construct a vector for the recurrence by combining the values for
4135   // the current and previous iterations. This is the required shuffle mask.
4136   assert(!VF.isScalable());
4137   SmallVector<int, 8> ShuffleMask(VF.getKnownMinValue());
4138   ShuffleMask[0] = VF.getKnownMinValue() - 1;
4139   for (unsigned I = 1; I < VF.getKnownMinValue(); ++I)
4140     ShuffleMask[I] = I + VF.getKnownMinValue() - 1;
4141 
4142   // The vector from which to take the initial value for the current iteration
4143   // (actual or unrolled). Initially, this is the vector phi node.
4144   Value *Incoming = VecPhi;
4145 
4146   // Shuffle the current and previous vector and update the vector parts.
4147   for (unsigned Part = 0; Part < UF; ++Part) {
4148     Value *PreviousPart = State.get(PreviousDef, Part);
4149     Value *PhiPart = State.get(PhiDef, Part);
4150     auto *Shuffle =
4151         VF.isVector()
4152             ? Builder.CreateShuffleVector(Incoming, PreviousPart, ShuffleMask)
4153             : Incoming;
4154     PhiPart->replaceAllUsesWith(Shuffle);
4155     cast<Instruction>(PhiPart)->eraseFromParent();
4156     State.reset(PhiDef, Phi, Shuffle, Part);
4157     Incoming = PreviousPart;
4158   }
4159 
4160   // Fix the latch value of the new recurrence in the vector loop.
4161   VecPhi->addIncoming(Incoming, LI->getLoopFor(LoopVectorBody)->getLoopLatch());
4162 
4163   // Extract the last vector element in the middle block. This will be the
4164   // initial value for the recurrence when jumping to the scalar loop.
4165   auto *ExtractForScalar = Incoming;
4166   if (VF.isVector()) {
4167     Builder.SetInsertPoint(LoopMiddleBlock->getTerminator());
4168     ExtractForScalar = Builder.CreateExtractElement(
4169         ExtractForScalar, Builder.getInt32(VF.getKnownMinValue() - 1),
4170         "vector.recur.extract");
4171   }
4172   // Extract the second last element in the middle block if the
4173   // Phi is used outside the loop. We need to extract the phi itself
4174   // and not the last element (the phi update in the current iteration). This
4175   // will be the value when jumping to the exit block from the LoopMiddleBlock,
4176   // when the scalar loop is not run at all.
4177   Value *ExtractForPhiUsedOutsideLoop = nullptr;
4178   if (VF.isVector())
4179     ExtractForPhiUsedOutsideLoop = Builder.CreateExtractElement(
4180         Incoming, Builder.getInt32(VF.getKnownMinValue() - 2),
4181         "vector.recur.extract.for.phi");
4182   // When loop is unrolled without vectorizing, initialize
4183   // ExtractForPhiUsedOutsideLoop with the value just prior to unrolled value of
4184   // `Incoming`. This is analogous to the vectorized case above: extracting the
4185   // second last element when VF > 1.
4186   else if (UF > 1)
4187     ExtractForPhiUsedOutsideLoop = State.get(PreviousDef, UF - 2);
4188 
4189   // Fix the initial value of the original recurrence in the scalar loop.
4190   Builder.SetInsertPoint(&*LoopScalarPreHeader->begin());
4191   auto *Start = Builder.CreatePHI(Phi->getType(), 2, "scalar.recur.init");
4192   for (auto *BB : predecessors(LoopScalarPreHeader)) {
4193     auto *Incoming = BB == LoopMiddleBlock ? ExtractForScalar : ScalarInit;
4194     Start->addIncoming(Incoming, BB);
4195   }
4196 
4197   Phi->setIncomingValueForBlock(LoopScalarPreHeader, Start);
4198   Phi->setName("scalar.recur");
4199 
4200   // Finally, fix users of the recurrence outside the loop. The users will need
4201   // either the last value of the scalar recurrence or the last value of the
4202   // vector recurrence we extracted in the middle block. Since the loop is in
4203   // LCSSA form, we just need to find all the phi nodes for the original scalar
4204   // recurrence in the exit block, and then add an edge for the middle block.
4205   // Note that LCSSA does not imply single entry when the original scalar loop
4206   // had multiple exiting edges (as we always run the last iteration in the
4207   // scalar epilogue); in that case, the exiting path through middle will be
4208   // dynamically dead and the value picked for the phi doesn't matter.
4209   for (PHINode &LCSSAPhi : LoopExitBlock->phis())
4210     if (any_of(LCSSAPhi.incoming_values(),
4211                [Phi](Value *V) { return V == Phi; }))
4212       LCSSAPhi.addIncoming(ExtractForPhiUsedOutsideLoop, LoopMiddleBlock);
4213 }
4214 
4215 void InnerLoopVectorizer::fixReduction(PHINode *Phi, VPTransformState &State) {
4216   // Get it's reduction variable descriptor.
4217   assert(Legal->isReductionVariable(Phi) &&
4218          "Unable to find the reduction variable");
4219   RecurrenceDescriptor RdxDesc = Legal->getReductionVars()[Phi];
4220 
4221   RecurKind RK = RdxDesc.getRecurrenceKind();
4222   TrackingVH<Value> ReductionStartValue = RdxDesc.getRecurrenceStartValue();
4223   Instruction *LoopExitInst = RdxDesc.getLoopExitInstr();
4224   setDebugLocFromInst(Builder, ReductionStartValue);
4225   bool IsInLoopReductionPhi = Cost->isInLoopReduction(Phi);
4226 
4227   VPValue *LoopExitInstDef = State.Plan->getVPValue(LoopExitInst);
4228   // This is the vector-clone of the value that leaves the loop.
4229   Type *VecTy = State.get(LoopExitInstDef, 0)->getType();
4230 
4231   // Wrap flags are in general invalid after vectorization, clear them.
4232   clearReductionWrapFlags(RdxDesc);
4233 
4234   // Fix the vector-loop phi.
4235 
4236   // Reductions do not have to start at zero. They can start with
4237   // any loop invariant values.
4238   BasicBlock *Latch = OrigLoop->getLoopLatch();
4239   Value *LoopVal = Phi->getIncomingValueForBlock(Latch);
4240 
4241   for (unsigned Part = 0; Part < UF; ++Part) {
4242     Value *VecRdxPhi = State.get(State.Plan->getVPValue(Phi), Part);
4243     Value *Val = State.get(State.Plan->getVPValue(LoopVal), Part);
4244     cast<PHINode>(VecRdxPhi)
4245       ->addIncoming(Val, LI->getLoopFor(LoopVectorBody)->getLoopLatch());
4246   }
4247 
4248   // Before each round, move the insertion point right between
4249   // the PHIs and the values we are going to write.
4250   // This allows us to write both PHINodes and the extractelement
4251   // instructions.
4252   Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
4253 
4254   setDebugLocFromInst(Builder, LoopExitInst);
4255 
4256   // If tail is folded by masking, the vector value to leave the loop should be
4257   // a Select choosing between the vectorized LoopExitInst and vectorized Phi,
4258   // instead of the former. For an inloop reduction the reduction will already
4259   // be predicated, and does not need to be handled here.
4260   if (Cost->foldTailByMasking() && !IsInLoopReductionPhi) {
4261     for (unsigned Part = 0; Part < UF; ++Part) {
4262       Value *VecLoopExitInst = State.get(LoopExitInstDef, Part);
4263       Value *Sel = nullptr;
4264       for (User *U : VecLoopExitInst->users()) {
4265         if (isa<SelectInst>(U)) {
4266           assert(!Sel && "Reduction exit feeding two selects");
4267           Sel = U;
4268         } else
4269           assert(isa<PHINode>(U) && "Reduction exit must feed Phi's or select");
4270       }
4271       assert(Sel && "Reduction exit feeds no select");
4272       State.reset(LoopExitInstDef, LoopExitInst, Sel, Part);
4273 
4274       // If the target can create a predicated operator for the reduction at no
4275       // extra cost in the loop (for example a predicated vadd), it can be
4276       // cheaper for the select to remain in the loop than be sunk out of it,
4277       // and so use the select value for the phi instead of the old
4278       // LoopExitValue.
4279       RecurrenceDescriptor RdxDesc = Legal->getReductionVars()[Phi];
4280       if (PreferPredicatedReductionSelect ||
4281           TTI->preferPredicatedReductionSelect(
4282               RdxDesc.getOpcode(), Phi->getType(),
4283               TargetTransformInfo::ReductionFlags())) {
4284         auto *VecRdxPhi =
4285             cast<PHINode>(State.get(State.Plan->getVPValue(Phi), Part));
4286         VecRdxPhi->setIncomingValueForBlock(
4287             LI->getLoopFor(LoopVectorBody)->getLoopLatch(), Sel);
4288       }
4289     }
4290   }
4291 
4292   // If the vector reduction can be performed in a smaller type, we truncate
4293   // then extend the loop exit value to enable InstCombine to evaluate the
4294   // entire expression in the smaller type.
4295   if (VF.isVector() && Phi->getType() != RdxDesc.getRecurrenceType()) {
4296     assert(!IsInLoopReductionPhi && "Unexpected truncated inloop reduction!");
4297     assert(!VF.isScalable() && "scalable vectors not yet supported.");
4298     Type *RdxVecTy = VectorType::get(RdxDesc.getRecurrenceType(), VF);
4299     Builder.SetInsertPoint(
4300         LI->getLoopFor(LoopVectorBody)->getLoopLatch()->getTerminator());
4301     VectorParts RdxParts(UF);
4302     for (unsigned Part = 0; Part < UF; ++Part) {
4303       RdxParts[Part] = State.get(LoopExitInstDef, Part);
4304       Value *Trunc = Builder.CreateTrunc(RdxParts[Part], RdxVecTy);
4305       Value *Extnd = RdxDesc.isSigned() ? Builder.CreateSExt(Trunc, VecTy)
4306                                         : Builder.CreateZExt(Trunc, VecTy);
4307       for (Value::user_iterator UI = RdxParts[Part]->user_begin();
4308            UI != RdxParts[Part]->user_end();)
4309         if (*UI != Trunc) {
4310           (*UI++)->replaceUsesOfWith(RdxParts[Part], Extnd);
4311           RdxParts[Part] = Extnd;
4312         } else {
4313           ++UI;
4314         }
4315     }
4316     Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
4317     for (unsigned Part = 0; Part < UF; ++Part) {
4318       RdxParts[Part] = Builder.CreateTrunc(RdxParts[Part], RdxVecTy);
4319       State.reset(LoopExitInstDef, LoopExitInst, RdxParts[Part], Part);
4320     }
4321   }
4322 
4323   // Reduce all of the unrolled parts into a single vector.
4324   Value *ReducedPartRdx = State.get(LoopExitInstDef, 0);
4325   unsigned Op = RecurrenceDescriptor::getOpcode(RK);
4326 
4327   // The middle block terminator has already been assigned a DebugLoc here (the
4328   // OrigLoop's single latch terminator). We want the whole middle block to
4329   // appear to execute on this line because: (a) it is all compiler generated,
4330   // (b) these instructions are always executed after evaluating the latch
4331   // conditional branch, and (c) other passes may add new predecessors which
4332   // terminate on this line. This is the easiest way to ensure we don't
4333   // accidentally cause an extra step back into the loop while debugging.
4334   setDebugLocFromInst(Builder, LoopMiddleBlock->getTerminator());
4335   {
4336     // Floating-point operations should have some FMF to enable the reduction.
4337     IRBuilderBase::FastMathFlagGuard FMFG(Builder);
4338     Builder.setFastMathFlags(RdxDesc.getFastMathFlags());
4339     for (unsigned Part = 1; Part < UF; ++Part) {
4340       Value *RdxPart = State.get(LoopExitInstDef, Part);
4341       if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
4342         ReducedPartRdx = Builder.CreateBinOp(
4343             (Instruction::BinaryOps)Op, RdxPart, ReducedPartRdx, "bin.rdx");
4344       } else {
4345         ReducedPartRdx = createMinMaxOp(Builder, RK, ReducedPartRdx, RdxPart);
4346       }
4347     }
4348   }
4349 
4350   // Create the reduction after the loop. Note that inloop reductions create the
4351   // target reduction in the loop using a Reduction recipe.
4352   if (VF.isVector() && !IsInLoopReductionPhi) {
4353     ReducedPartRdx =
4354         createTargetReduction(Builder, TTI, RdxDesc, ReducedPartRdx);
4355     // If the reduction can be performed in a smaller type, we need to extend
4356     // the reduction to the wider type before we branch to the original loop.
4357     if (Phi->getType() != RdxDesc.getRecurrenceType())
4358       ReducedPartRdx =
4359         RdxDesc.isSigned()
4360         ? Builder.CreateSExt(ReducedPartRdx, Phi->getType())
4361         : Builder.CreateZExt(ReducedPartRdx, Phi->getType());
4362   }
4363 
4364   // Create a phi node that merges control-flow from the backedge-taken check
4365   // block and the middle block.
4366   PHINode *BCBlockPhi = PHINode::Create(Phi->getType(), 2, "bc.merge.rdx",
4367                                         LoopScalarPreHeader->getTerminator());
4368   for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
4369     BCBlockPhi->addIncoming(ReductionStartValue, LoopBypassBlocks[I]);
4370   BCBlockPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
4371 
4372   // Now, we need to fix the users of the reduction variable
4373   // inside and outside of the scalar remainder loop.
4374 
4375   // We know that the loop is in LCSSA form. We need to update the PHI nodes
4376   // in the exit blocks.  See comment on analogous loop in
4377   // fixFirstOrderRecurrence for a more complete explaination of the logic.
4378   for (PHINode &LCSSAPhi : LoopExitBlock->phis())
4379     if (any_of(LCSSAPhi.incoming_values(),
4380                [LoopExitInst](Value *V) { return V == LoopExitInst; }))
4381       LCSSAPhi.addIncoming(ReducedPartRdx, LoopMiddleBlock);
4382 
4383   // Fix the scalar loop reduction variable with the incoming reduction sum
4384   // from the vector body and from the backedge value.
4385   int IncomingEdgeBlockIdx =
4386     Phi->getBasicBlockIndex(OrigLoop->getLoopLatch());
4387   assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
4388   // Pick the other block.
4389   int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
4390   Phi->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi);
4391   Phi->setIncomingValue(IncomingEdgeBlockIdx, LoopExitInst);
4392 }
4393 
4394 void InnerLoopVectorizer::clearReductionWrapFlags(
4395     RecurrenceDescriptor &RdxDesc) {
4396   RecurKind RK = RdxDesc.getRecurrenceKind();
4397   if (RK != RecurKind::Add && RK != RecurKind::Mul)
4398     return;
4399 
4400   Instruction *LoopExitInstr = RdxDesc.getLoopExitInstr();
4401   assert(LoopExitInstr && "null loop exit instruction");
4402   SmallVector<Instruction *, 8> Worklist;
4403   SmallPtrSet<Instruction *, 8> Visited;
4404   Worklist.push_back(LoopExitInstr);
4405   Visited.insert(LoopExitInstr);
4406 
4407   while (!Worklist.empty()) {
4408     Instruction *Cur = Worklist.pop_back_val();
4409     if (isa<OverflowingBinaryOperator>(Cur))
4410       for (unsigned Part = 0; Part < UF; ++Part) {
4411         Value *V = getOrCreateVectorValue(Cur, Part);
4412         cast<Instruction>(V)->dropPoisonGeneratingFlags();
4413       }
4414 
4415     for (User *U : Cur->users()) {
4416       Instruction *UI = cast<Instruction>(U);
4417       if ((Cur != LoopExitInstr || OrigLoop->contains(UI->getParent())) &&
4418           Visited.insert(UI).second)
4419         Worklist.push_back(UI);
4420     }
4421   }
4422 }
4423 
4424 void InnerLoopVectorizer::fixLCSSAPHIs(VPTransformState &State) {
4425   for (PHINode &LCSSAPhi : LoopExitBlock->phis()) {
4426     if (LCSSAPhi.getBasicBlockIndex(LoopMiddleBlock) != -1)
4427       // Some phis were already hand updated by the reduction and recurrence
4428       // code above, leave them alone.
4429       continue;
4430 
4431     auto *IncomingValue = LCSSAPhi.getIncomingValue(0);
4432     // Non-instruction incoming values will have only one value.
4433     unsigned LastLane = 0;
4434     if (isa<Instruction>(IncomingValue))
4435       LastLane = Cost->isUniformAfterVectorization(
4436                      cast<Instruction>(IncomingValue), VF)
4437                      ? 0
4438                      : VF.getKnownMinValue() - 1;
4439     assert((!VF.isScalable() || LastLane == 0) &&
4440            "scalable vectors dont support non-uniform scalars yet");
4441     // Can be a loop invariant incoming value or the last scalar value to be
4442     // extracted from the vectorized loop.
4443     Builder.SetInsertPoint(LoopMiddleBlock->getTerminator());
4444     Value *lastIncomingValue =
4445         OrigLoop->isLoopInvariant(IncomingValue)
4446             ? IncomingValue
4447             : State.get(State.Plan->getVPValue(IncomingValue),
4448                         VPIteration(UF - 1, LastLane));
4449     LCSSAPhi.addIncoming(lastIncomingValue, LoopMiddleBlock);
4450   }
4451 }
4452 
4453 void InnerLoopVectorizer::sinkScalarOperands(Instruction *PredInst) {
4454   // The basic block and loop containing the predicated instruction.
4455   auto *PredBB = PredInst->getParent();
4456   auto *VectorLoop = LI->getLoopFor(PredBB);
4457 
4458   // Initialize a worklist with the operands of the predicated instruction.
4459   SetVector<Value *> Worklist(PredInst->op_begin(), PredInst->op_end());
4460 
4461   // Holds instructions that we need to analyze again. An instruction may be
4462   // reanalyzed if we don't yet know if we can sink it or not.
4463   SmallVector<Instruction *, 8> InstsToReanalyze;
4464 
4465   // Returns true if a given use occurs in the predicated block. Phi nodes use
4466   // their operands in their corresponding predecessor blocks.
4467   auto isBlockOfUsePredicated = [&](Use &U) -> bool {
4468     auto *I = cast<Instruction>(U.getUser());
4469     BasicBlock *BB = I->getParent();
4470     if (auto *Phi = dyn_cast<PHINode>(I))
4471       BB = Phi->getIncomingBlock(
4472           PHINode::getIncomingValueNumForOperand(U.getOperandNo()));
4473     return BB == PredBB;
4474   };
4475 
4476   // Iteratively sink the scalarized operands of the predicated instruction
4477   // into the block we created for it. When an instruction is sunk, it's
4478   // operands are then added to the worklist. The algorithm ends after one pass
4479   // through the worklist doesn't sink a single instruction.
4480   bool Changed;
4481   do {
4482     // Add the instructions that need to be reanalyzed to the worklist, and
4483     // reset the changed indicator.
4484     Worklist.insert(InstsToReanalyze.begin(), InstsToReanalyze.end());
4485     InstsToReanalyze.clear();
4486     Changed = false;
4487 
4488     while (!Worklist.empty()) {
4489       auto *I = dyn_cast<Instruction>(Worklist.pop_back_val());
4490 
4491       // We can't sink an instruction if it is a phi node, is already in the
4492       // predicated block, is not in the loop, or may have side effects.
4493       if (!I || isa<PHINode>(I) || I->getParent() == PredBB ||
4494           !VectorLoop->contains(I) || I->mayHaveSideEffects())
4495         continue;
4496 
4497       // It's legal to sink the instruction if all its uses occur in the
4498       // predicated block. Otherwise, there's nothing to do yet, and we may
4499       // need to reanalyze the instruction.
4500       if (!llvm::all_of(I->uses(), isBlockOfUsePredicated)) {
4501         InstsToReanalyze.push_back(I);
4502         continue;
4503       }
4504 
4505       // Move the instruction to the beginning of the predicated block, and add
4506       // it's operands to the worklist.
4507       I->moveBefore(&*PredBB->getFirstInsertionPt());
4508       Worklist.insert(I->op_begin(), I->op_end());
4509 
4510       // The sinking may have enabled other instructions to be sunk, so we will
4511       // need to iterate.
4512       Changed = true;
4513     }
4514   } while (Changed);
4515 }
4516 
4517 void InnerLoopVectorizer::fixNonInductionPHIs(VPTransformState &State) {
4518   for (PHINode *OrigPhi : OrigPHIsToFix) {
4519     PHINode *NewPhi =
4520         cast<PHINode>(State.get(State.Plan->getVPValue(OrigPhi), 0));
4521     unsigned NumIncomingValues = OrigPhi->getNumIncomingValues();
4522 
4523     SmallVector<BasicBlock *, 2> ScalarBBPredecessors(
4524         predecessors(OrigPhi->getParent()));
4525     SmallVector<BasicBlock *, 2> VectorBBPredecessors(
4526         predecessors(NewPhi->getParent()));
4527     assert(ScalarBBPredecessors.size() == VectorBBPredecessors.size() &&
4528            "Scalar and Vector BB should have the same number of predecessors");
4529 
4530     // The insertion point in Builder may be invalidated by the time we get
4531     // here. Force the Builder insertion point to something valid so that we do
4532     // not run into issues during insertion point restore in
4533     // getOrCreateVectorValue calls below.
4534     Builder.SetInsertPoint(NewPhi);
4535 
4536     // The predecessor order is preserved and we can rely on mapping between
4537     // scalar and vector block predecessors.
4538     for (unsigned i = 0; i < NumIncomingValues; ++i) {
4539       BasicBlock *NewPredBB = VectorBBPredecessors[i];
4540 
4541       // When looking up the new scalar/vector values to fix up, use incoming
4542       // values from original phi.
4543       Value *ScIncV =
4544           OrigPhi->getIncomingValueForBlock(ScalarBBPredecessors[i]);
4545 
4546       // Scalar incoming value may need a broadcast
4547       Value *NewIncV = getOrCreateVectorValue(ScIncV, 0);
4548       NewPhi->addIncoming(NewIncV, NewPredBB);
4549     }
4550   }
4551 }
4552 
4553 void InnerLoopVectorizer::widenGEP(GetElementPtrInst *GEP, VPValue *VPDef,
4554                                    VPUser &Operands, unsigned UF,
4555                                    ElementCount VF, bool IsPtrLoopInvariant,
4556                                    SmallBitVector &IsIndexLoopInvariant,
4557                                    VPTransformState &State) {
4558   // Construct a vector GEP by widening the operands of the scalar GEP as
4559   // necessary. We mark the vector GEP 'inbounds' if appropriate. A GEP
4560   // results in a vector of pointers when at least one operand of the GEP
4561   // is vector-typed. Thus, to keep the representation compact, we only use
4562   // vector-typed operands for loop-varying values.
4563 
4564   if (VF.isVector() && IsPtrLoopInvariant && IsIndexLoopInvariant.all()) {
4565     // If we are vectorizing, but the GEP has only loop-invariant operands,
4566     // the GEP we build (by only using vector-typed operands for
4567     // loop-varying values) would be a scalar pointer. Thus, to ensure we
4568     // produce a vector of pointers, we need to either arbitrarily pick an
4569     // operand to broadcast, or broadcast a clone of the original GEP.
4570     // Here, we broadcast a clone of the original.
4571     //
4572     // TODO: If at some point we decide to scalarize instructions having
4573     //       loop-invariant operands, this special case will no longer be
4574     //       required. We would add the scalarization decision to
4575     //       collectLoopScalars() and teach getVectorValue() to broadcast
4576     //       the lane-zero scalar value.
4577     auto *Clone = Builder.Insert(GEP->clone());
4578     for (unsigned Part = 0; Part < UF; ++Part) {
4579       Value *EntryPart = Builder.CreateVectorSplat(VF, Clone);
4580       State.set(VPDef, GEP, EntryPart, Part);
4581       addMetadata(EntryPart, GEP);
4582     }
4583   } else {
4584     // If the GEP has at least one loop-varying operand, we are sure to
4585     // produce a vector of pointers. But if we are only unrolling, we want
4586     // to produce a scalar GEP for each unroll part. Thus, the GEP we
4587     // produce with the code below will be scalar (if VF == 1) or vector
4588     // (otherwise). Note that for the unroll-only case, we still maintain
4589     // values in the vector mapping with initVector, as we do for other
4590     // instructions.
4591     for (unsigned Part = 0; Part < UF; ++Part) {
4592       // The pointer operand of the new GEP. If it's loop-invariant, we
4593       // won't broadcast it.
4594       auto *Ptr = IsPtrLoopInvariant
4595                       ? State.get(Operands.getOperand(0), VPIteration(0, 0))
4596                       : State.get(Operands.getOperand(0), Part);
4597 
4598       // Collect all the indices for the new GEP. If any index is
4599       // loop-invariant, we won't broadcast it.
4600       SmallVector<Value *, 4> Indices;
4601       for (unsigned I = 1, E = Operands.getNumOperands(); I < E; I++) {
4602         VPValue *Operand = Operands.getOperand(I);
4603         if (IsIndexLoopInvariant[I - 1])
4604           Indices.push_back(State.get(Operand, VPIteration(0, 0)));
4605         else
4606           Indices.push_back(State.get(Operand, Part));
4607       }
4608 
4609       // Create the new GEP. Note that this GEP may be a scalar if VF == 1,
4610       // but it should be a vector, otherwise.
4611       auto *NewGEP =
4612           GEP->isInBounds()
4613               ? Builder.CreateInBoundsGEP(GEP->getSourceElementType(), Ptr,
4614                                           Indices)
4615               : Builder.CreateGEP(GEP->getSourceElementType(), Ptr, Indices);
4616       assert((VF.isScalar() || NewGEP->getType()->isVectorTy()) &&
4617              "NewGEP is not a pointer vector");
4618       State.set(VPDef, GEP, NewGEP, Part);
4619       addMetadata(NewGEP, GEP);
4620     }
4621   }
4622 }
4623 
4624 void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN,
4625                                               RecurrenceDescriptor *RdxDesc,
4626                                               Value *StartV, unsigned UF,
4627                                               ElementCount VF) {
4628   assert(!VF.isScalable() && "scalable vectors not yet supported.");
4629   PHINode *P = cast<PHINode>(PN);
4630   if (EnableVPlanNativePath) {
4631     // Currently we enter here in the VPlan-native path for non-induction
4632     // PHIs where all control flow is uniform. We simply widen these PHIs.
4633     // Create a vector phi with no operands - the vector phi operands will be
4634     // set at the end of vector code generation.
4635     Type *VecTy =
4636         (VF.isScalar()) ? PN->getType() : VectorType::get(PN->getType(), VF);
4637     Value *VecPhi = Builder.CreatePHI(VecTy, PN->getNumOperands(), "vec.phi");
4638     VectorLoopValueMap.setVectorValue(P, 0, VecPhi);
4639     OrigPHIsToFix.push_back(P);
4640 
4641     return;
4642   }
4643 
4644   assert(PN->getParent() == OrigLoop->getHeader() &&
4645          "Non-header phis should have been handled elsewhere");
4646 
4647   // In order to support recurrences we need to be able to vectorize Phi nodes.
4648   // Phi nodes have cycles, so we need to vectorize them in two stages. This is
4649   // stage #1: We create a new vector PHI node with no incoming edges. We'll use
4650   // this value when we vectorize all of the instructions that use the PHI.
4651   if (RdxDesc || Legal->isFirstOrderRecurrence(P)) {
4652     Value *Iden = nullptr;
4653     bool ScalarPHI =
4654         (VF.isScalar()) || Cost->isInLoopReduction(cast<PHINode>(PN));
4655     Type *VecTy =
4656         ScalarPHI ? PN->getType() : VectorType::get(PN->getType(), VF);
4657 
4658     if (RdxDesc) {
4659       assert(Legal->isReductionVariable(P) && StartV &&
4660              "RdxDesc should only be set for reduction variables; in that case "
4661              "a StartV is also required");
4662       RecurKind RK = RdxDesc->getRecurrenceKind();
4663       if (RecurrenceDescriptor::isMinMaxRecurrenceKind(RK)) {
4664         // MinMax reduction have the start value as their identify.
4665         if (ScalarPHI) {
4666           Iden = StartV;
4667         } else {
4668           IRBuilderBase::InsertPointGuard IPBuilder(Builder);
4669           Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
4670           StartV = Iden = Builder.CreateVectorSplat(VF, StartV, "minmax.ident");
4671         }
4672       } else {
4673         Constant *IdenC = RecurrenceDescriptor::getRecurrenceIdentity(
4674             RK, VecTy->getScalarType());
4675         Iden = IdenC;
4676 
4677         if (!ScalarPHI) {
4678           Iden = ConstantVector::getSplat(VF, IdenC);
4679           IRBuilderBase::InsertPointGuard IPBuilder(Builder);
4680           Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
4681           Constant *Zero = Builder.getInt32(0);
4682           StartV = Builder.CreateInsertElement(Iden, StartV, Zero);
4683         }
4684       }
4685     }
4686 
4687     for (unsigned Part = 0; Part < UF; ++Part) {
4688       // This is phase one of vectorizing PHIs.
4689       Value *EntryPart = PHINode::Create(
4690           VecTy, 2, "vec.phi", &*LoopVectorBody->getFirstInsertionPt());
4691       VectorLoopValueMap.setVectorValue(P, Part, EntryPart);
4692       if (StartV) {
4693         // Make sure to add the reduction start value only to the
4694         // first unroll part.
4695         Value *StartVal = (Part == 0) ? StartV : Iden;
4696         cast<PHINode>(EntryPart)->addIncoming(StartVal, LoopVectorPreHeader);
4697       }
4698     }
4699     return;
4700   }
4701 
4702   assert(!Legal->isReductionVariable(P) &&
4703          "reductions should be handled above");
4704 
4705   setDebugLocFromInst(Builder, P);
4706 
4707   // This PHINode must be an induction variable.
4708   // Make sure that we know about it.
4709   assert(Legal->getInductionVars().count(P) && "Not an induction variable");
4710 
4711   InductionDescriptor II = Legal->getInductionVars().lookup(P);
4712   const DataLayout &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
4713 
4714   // FIXME: The newly created binary instructions should contain nsw/nuw flags,
4715   // which can be found from the original scalar operations.
4716   switch (II.getKind()) {
4717   case InductionDescriptor::IK_NoInduction:
4718     llvm_unreachable("Unknown induction");
4719   case InductionDescriptor::IK_IntInduction:
4720   case InductionDescriptor::IK_FpInduction:
4721     llvm_unreachable("Integer/fp induction is handled elsewhere.");
4722   case InductionDescriptor::IK_PtrInduction: {
4723     // Handle the pointer induction variable case.
4724     assert(P->getType()->isPointerTy() && "Unexpected type.");
4725 
4726     if (Cost->isScalarAfterVectorization(P, VF)) {
4727       // This is the normalized GEP that starts counting at zero.
4728       Value *PtrInd =
4729           Builder.CreateSExtOrTrunc(Induction, II.getStep()->getType());
4730       // Determine the number of scalars we need to generate for each unroll
4731       // iteration. If the instruction is uniform, we only need to generate the
4732       // first lane. Otherwise, we generate all VF values.
4733       unsigned Lanes =
4734           Cost->isUniformAfterVectorization(P, VF) ? 1 : VF.getKnownMinValue();
4735       for (unsigned Part = 0; Part < UF; ++Part) {
4736         for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
4737           Constant *Idx = ConstantInt::get(PtrInd->getType(),
4738                                            Lane + Part * VF.getKnownMinValue());
4739           Value *GlobalIdx = Builder.CreateAdd(PtrInd, Idx);
4740           Value *SclrGep =
4741               emitTransformedIndex(Builder, GlobalIdx, PSE.getSE(), DL, II);
4742           SclrGep->setName("next.gep");
4743           VectorLoopValueMap.setScalarValue(P, VPIteration(Part, Lane),
4744                                             SclrGep);
4745         }
4746       }
4747       return;
4748     }
4749     assert(isa<SCEVConstant>(II.getStep()) &&
4750            "Induction step not a SCEV constant!");
4751     Type *PhiType = II.getStep()->getType();
4752 
4753     // Build a pointer phi
4754     Value *ScalarStartValue = II.getStartValue();
4755     Type *ScStValueType = ScalarStartValue->getType();
4756     PHINode *NewPointerPhi =
4757         PHINode::Create(ScStValueType, 2, "pointer.phi", Induction);
4758     NewPointerPhi->addIncoming(ScalarStartValue, LoopVectorPreHeader);
4759 
4760     // A pointer induction, performed by using a gep
4761     BasicBlock *LoopLatch = LI->getLoopFor(LoopVectorBody)->getLoopLatch();
4762     Instruction *InductionLoc = LoopLatch->getTerminator();
4763     const SCEV *ScalarStep = II.getStep();
4764     SCEVExpander Exp(*PSE.getSE(), DL, "induction");
4765     Value *ScalarStepValue =
4766         Exp.expandCodeFor(ScalarStep, PhiType, InductionLoc);
4767     Value *InductionGEP = GetElementPtrInst::Create(
4768         ScStValueType->getPointerElementType(), NewPointerPhi,
4769         Builder.CreateMul(
4770             ScalarStepValue,
4771             ConstantInt::get(PhiType, VF.getKnownMinValue() * UF)),
4772         "ptr.ind", InductionLoc);
4773     NewPointerPhi->addIncoming(InductionGEP, LoopLatch);
4774 
4775     // Create UF many actual address geps that use the pointer
4776     // phi as base and a vectorized version of the step value
4777     // (<step*0, ..., step*N>) as offset.
4778     for (unsigned Part = 0; Part < UF; ++Part) {
4779       SmallVector<Constant *, 8> Indices;
4780       // Create a vector of consecutive numbers from zero to VF.
4781       for (unsigned i = 0; i < VF.getKnownMinValue(); ++i)
4782         Indices.push_back(
4783             ConstantInt::get(PhiType, i + Part * VF.getKnownMinValue()));
4784       Constant *StartOffset = ConstantVector::get(Indices);
4785 
4786       Value *GEP = Builder.CreateGEP(
4787           ScStValueType->getPointerElementType(), NewPointerPhi,
4788           Builder.CreateMul(
4789               StartOffset,
4790               Builder.CreateVectorSplat(VF.getKnownMinValue(), ScalarStepValue),
4791               "vector.gep"));
4792       VectorLoopValueMap.setVectorValue(P, Part, GEP);
4793     }
4794   }
4795   }
4796 }
4797 
4798 /// A helper function for checking whether an integer division-related
4799 /// instruction may divide by zero (in which case it must be predicated if
4800 /// executed conditionally in the scalar code).
4801 /// TODO: It may be worthwhile to generalize and check isKnownNonZero().
4802 /// Non-zero divisors that are non compile-time constants will not be
4803 /// converted into multiplication, so we will still end up scalarizing
4804 /// the division, but can do so w/o predication.
4805 static bool mayDivideByZero(Instruction &I) {
4806   assert((I.getOpcode() == Instruction::UDiv ||
4807           I.getOpcode() == Instruction::SDiv ||
4808           I.getOpcode() == Instruction::URem ||
4809           I.getOpcode() == Instruction::SRem) &&
4810          "Unexpected instruction");
4811   Value *Divisor = I.getOperand(1);
4812   auto *CInt = dyn_cast<ConstantInt>(Divisor);
4813   return !CInt || CInt->isZero();
4814 }
4815 
4816 void InnerLoopVectorizer::widenInstruction(Instruction &I, VPValue *Def,
4817                                            VPUser &User,
4818                                            VPTransformState &State) {
4819   switch (I.getOpcode()) {
4820   case Instruction::Call:
4821   case Instruction::Br:
4822   case Instruction::PHI:
4823   case Instruction::GetElementPtr:
4824   case Instruction::Select:
4825     llvm_unreachable("This instruction is handled by a different recipe.");
4826   case Instruction::UDiv:
4827   case Instruction::SDiv:
4828   case Instruction::SRem:
4829   case Instruction::URem:
4830   case Instruction::Add:
4831   case Instruction::FAdd:
4832   case Instruction::Sub:
4833   case Instruction::FSub:
4834   case Instruction::FNeg:
4835   case Instruction::Mul:
4836   case Instruction::FMul:
4837   case Instruction::FDiv:
4838   case Instruction::FRem:
4839   case Instruction::Shl:
4840   case Instruction::LShr:
4841   case Instruction::AShr:
4842   case Instruction::And:
4843   case Instruction::Or:
4844   case Instruction::Xor: {
4845     // Just widen unops and binops.
4846     setDebugLocFromInst(Builder, &I);
4847 
4848     for (unsigned Part = 0; Part < UF; ++Part) {
4849       SmallVector<Value *, 2> Ops;
4850       for (VPValue *VPOp : User.operands())
4851         Ops.push_back(State.get(VPOp, Part));
4852 
4853       Value *V = Builder.CreateNAryOp(I.getOpcode(), Ops);
4854 
4855       if (auto *VecOp = dyn_cast<Instruction>(V))
4856         VecOp->copyIRFlags(&I);
4857 
4858       // Use this vector value for all users of the original instruction.
4859       State.set(Def, &I, V, Part);
4860       addMetadata(V, &I);
4861     }
4862 
4863     break;
4864   }
4865   case Instruction::ICmp:
4866   case Instruction::FCmp: {
4867     // Widen compares. Generate vector compares.
4868     bool FCmp = (I.getOpcode() == Instruction::FCmp);
4869     auto *Cmp = cast<CmpInst>(&I);
4870     setDebugLocFromInst(Builder, Cmp);
4871     for (unsigned Part = 0; Part < UF; ++Part) {
4872       Value *A = State.get(User.getOperand(0), Part);
4873       Value *B = State.get(User.getOperand(1), Part);
4874       Value *C = nullptr;
4875       if (FCmp) {
4876         // Propagate fast math flags.
4877         IRBuilder<>::FastMathFlagGuard FMFG(Builder);
4878         Builder.setFastMathFlags(Cmp->getFastMathFlags());
4879         C = Builder.CreateFCmp(Cmp->getPredicate(), A, B);
4880       } else {
4881         C = Builder.CreateICmp(Cmp->getPredicate(), A, B);
4882       }
4883       State.set(Def, &I, C, Part);
4884       addMetadata(C, &I);
4885     }
4886 
4887     break;
4888   }
4889 
4890   case Instruction::ZExt:
4891   case Instruction::SExt:
4892   case Instruction::FPToUI:
4893   case Instruction::FPToSI:
4894   case Instruction::FPExt:
4895   case Instruction::PtrToInt:
4896   case Instruction::IntToPtr:
4897   case Instruction::SIToFP:
4898   case Instruction::UIToFP:
4899   case Instruction::Trunc:
4900   case Instruction::FPTrunc:
4901   case Instruction::BitCast: {
4902     auto *CI = cast<CastInst>(&I);
4903     setDebugLocFromInst(Builder, CI);
4904 
4905     /// Vectorize casts.
4906     Type *DestTy =
4907         (VF.isScalar()) ? CI->getType() : VectorType::get(CI->getType(), VF);
4908 
4909     for (unsigned Part = 0; Part < UF; ++Part) {
4910       Value *A = State.get(User.getOperand(0), Part);
4911       Value *Cast = Builder.CreateCast(CI->getOpcode(), A, DestTy);
4912       State.set(Def, &I, Cast, Part);
4913       addMetadata(Cast, &I);
4914     }
4915     break;
4916   }
4917   default:
4918     // This instruction is not vectorized by simple widening.
4919     LLVM_DEBUG(dbgs() << "LV: Found an unhandled instruction: " << I);
4920     llvm_unreachable("Unhandled instruction!");
4921   } // end of switch.
4922 }
4923 
4924 void InnerLoopVectorizer::widenCallInstruction(CallInst &I, VPValue *Def,
4925                                                VPUser &ArgOperands,
4926                                                VPTransformState &State) {
4927   assert(!isa<DbgInfoIntrinsic>(I) &&
4928          "DbgInfoIntrinsic should have been dropped during VPlan construction");
4929   setDebugLocFromInst(Builder, &I);
4930 
4931   Module *M = I.getParent()->getParent()->getParent();
4932   auto *CI = cast<CallInst>(&I);
4933 
4934   SmallVector<Type *, 4> Tys;
4935   for (Value *ArgOperand : CI->arg_operands())
4936     Tys.push_back(ToVectorTy(ArgOperand->getType(), VF.getKnownMinValue()));
4937 
4938   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4939 
4940   // The flag shows whether we use Intrinsic or a usual Call for vectorized
4941   // version of the instruction.
4942   // Is it beneficial to perform intrinsic call compared to lib call?
4943   bool NeedToScalarize = false;
4944   InstructionCost CallCost = Cost->getVectorCallCost(CI, VF, NeedToScalarize);
4945   InstructionCost IntrinsicCost = ID ? Cost->getVectorIntrinsicCost(CI, VF) : 0;
4946   bool UseVectorIntrinsic = ID && IntrinsicCost <= CallCost;
4947   assert((UseVectorIntrinsic || !NeedToScalarize) &&
4948          "Instruction should be scalarized elsewhere.");
4949   assert(IntrinsicCost.isValid() && CallCost.isValid() &&
4950          "Cannot have invalid costs while widening");
4951 
4952   for (unsigned Part = 0; Part < UF; ++Part) {
4953     SmallVector<Value *, 4> Args;
4954     for (auto &I : enumerate(ArgOperands.operands())) {
4955       // Some intrinsics have a scalar argument - don't replace it with a
4956       // vector.
4957       Value *Arg;
4958       if (!UseVectorIntrinsic || !hasVectorInstrinsicScalarOpd(ID, I.index()))
4959         Arg = State.get(I.value(), Part);
4960       else
4961         Arg = State.get(I.value(), VPIteration(0, 0));
4962       Args.push_back(Arg);
4963     }
4964 
4965     Function *VectorF;
4966     if (UseVectorIntrinsic) {
4967       // Use vector version of the intrinsic.
4968       Type *TysForDecl[] = {CI->getType()};
4969       if (VF.isVector())
4970         TysForDecl[0] = VectorType::get(CI->getType()->getScalarType(), VF);
4971       VectorF = Intrinsic::getDeclaration(M, ID, TysForDecl);
4972       assert(VectorF && "Can't retrieve vector intrinsic.");
4973     } else {
4974       // Use vector version of the function call.
4975       const VFShape Shape = VFShape::get(*CI, VF, false /*HasGlobalPred*/);
4976 #ifndef NDEBUG
4977       assert(VFDatabase(*CI).getVectorizedFunction(Shape) != nullptr &&
4978              "Can't create vector function.");
4979 #endif
4980         VectorF = VFDatabase(*CI).getVectorizedFunction(Shape);
4981     }
4982       SmallVector<OperandBundleDef, 1> OpBundles;
4983       CI->getOperandBundlesAsDefs(OpBundles);
4984       CallInst *V = Builder.CreateCall(VectorF, Args, OpBundles);
4985 
4986       if (isa<FPMathOperator>(V))
4987         V->copyFastMathFlags(CI);
4988 
4989       State.set(Def, &I, V, Part);
4990       addMetadata(V, &I);
4991   }
4992 }
4993 
4994 void InnerLoopVectorizer::widenSelectInstruction(SelectInst &I, VPValue *VPDef,
4995                                                  VPUser &Operands,
4996                                                  bool InvariantCond,
4997                                                  VPTransformState &State) {
4998   setDebugLocFromInst(Builder, &I);
4999 
5000   // The condition can be loop invariant  but still defined inside the
5001   // loop. This means that we can't just use the original 'cond' value.
5002   // We have to take the 'vectorized' value and pick the first lane.
5003   // Instcombine will make this a no-op.
5004   auto *InvarCond = InvariantCond
5005                         ? State.get(Operands.getOperand(0), VPIteration(0, 0))
5006                         : nullptr;
5007 
5008   for (unsigned Part = 0; Part < UF; ++Part) {
5009     Value *Cond =
5010         InvarCond ? InvarCond : State.get(Operands.getOperand(0), Part);
5011     Value *Op0 = State.get(Operands.getOperand(1), Part);
5012     Value *Op1 = State.get(Operands.getOperand(2), Part);
5013     Value *Sel = Builder.CreateSelect(Cond, Op0, Op1);
5014     State.set(VPDef, &I, Sel, Part);
5015     addMetadata(Sel, &I);
5016   }
5017 }
5018 
5019 void LoopVectorizationCostModel::collectLoopScalars(ElementCount VF) {
5020   // We should not collect Scalars more than once per VF. Right now, this
5021   // function is called from collectUniformsAndScalars(), which already does
5022   // this check. Collecting Scalars for VF=1 does not make any sense.
5023   assert(VF.isVector() && Scalars.find(VF) == Scalars.end() &&
5024          "This function should not be visited twice for the same VF");
5025 
5026   SmallSetVector<Instruction *, 8> Worklist;
5027 
5028   // These sets are used to seed the analysis with pointers used by memory
5029   // accesses that will remain scalar.
5030   SmallSetVector<Instruction *, 8> ScalarPtrs;
5031   SmallPtrSet<Instruction *, 8> PossibleNonScalarPtrs;
5032   auto *Latch = TheLoop->getLoopLatch();
5033 
5034   // A helper that returns true if the use of Ptr by MemAccess will be scalar.
5035   // The pointer operands of loads and stores will be scalar as long as the
5036   // memory access is not a gather or scatter operation. The value operand of a
5037   // store will remain scalar if the store is scalarized.
5038   auto isScalarUse = [&](Instruction *MemAccess, Value *Ptr) {
5039     InstWidening WideningDecision = getWideningDecision(MemAccess, VF);
5040     assert(WideningDecision != CM_Unknown &&
5041            "Widening decision should be ready at this moment");
5042     if (auto *Store = dyn_cast<StoreInst>(MemAccess))
5043       if (Ptr == Store->getValueOperand())
5044         return WideningDecision == CM_Scalarize;
5045     assert(Ptr == getLoadStorePointerOperand(MemAccess) &&
5046            "Ptr is neither a value or pointer operand");
5047     return WideningDecision != CM_GatherScatter;
5048   };
5049 
5050   // A helper that returns true if the given value is a bitcast or
5051   // getelementptr instruction contained in the loop.
5052   auto isLoopVaryingBitCastOrGEP = [&](Value *V) {
5053     return ((isa<BitCastInst>(V) && V->getType()->isPointerTy()) ||
5054             isa<GetElementPtrInst>(V)) &&
5055            !TheLoop->isLoopInvariant(V);
5056   };
5057 
5058   auto isScalarPtrInduction = [&](Instruction *MemAccess, Value *Ptr) {
5059     if (!isa<PHINode>(Ptr) ||
5060         !Legal->getInductionVars().count(cast<PHINode>(Ptr)))
5061       return false;
5062     auto &Induction = Legal->getInductionVars()[cast<PHINode>(Ptr)];
5063     if (Induction.getKind() != InductionDescriptor::IK_PtrInduction)
5064       return false;
5065     return isScalarUse(MemAccess, Ptr);
5066   };
5067 
5068   // A helper that evaluates a memory access's use of a pointer. If the
5069   // pointer is actually the pointer induction of a loop, it is being
5070   // inserted into Worklist. If the use will be a scalar use, and the
5071   // pointer is only used by memory accesses, we place the pointer in
5072   // ScalarPtrs. Otherwise, the pointer is placed in PossibleNonScalarPtrs.
5073   auto evaluatePtrUse = [&](Instruction *MemAccess, Value *Ptr) {
5074     if (isScalarPtrInduction(MemAccess, Ptr)) {
5075       Worklist.insert(cast<Instruction>(Ptr));
5076       Instruction *Update = cast<Instruction>(
5077           cast<PHINode>(Ptr)->getIncomingValueForBlock(Latch));
5078       Worklist.insert(Update);
5079       LLVM_DEBUG(dbgs() << "LV: Found new scalar instruction: " << *Ptr
5080                         << "\n");
5081       LLVM_DEBUG(dbgs() << "LV: Found new scalar instruction: " << *Update
5082                         << "\n");
5083       return;
5084     }
5085     // We only care about bitcast and getelementptr instructions contained in
5086     // the loop.
5087     if (!isLoopVaryingBitCastOrGEP(Ptr))
5088       return;
5089 
5090     // If the pointer has already been identified as scalar (e.g., if it was
5091     // also identified as uniform), there's nothing to do.
5092     auto *I = cast<Instruction>(Ptr);
5093     if (Worklist.count(I))
5094       return;
5095 
5096     // If the use of the pointer will be a scalar use, and all users of the
5097     // pointer are memory accesses, place the pointer in ScalarPtrs. Otherwise,
5098     // place the pointer in PossibleNonScalarPtrs.
5099     if (isScalarUse(MemAccess, Ptr) && llvm::all_of(I->users(), [&](User *U) {
5100           return isa<LoadInst>(U) || isa<StoreInst>(U);
5101         }))
5102       ScalarPtrs.insert(I);
5103     else
5104       PossibleNonScalarPtrs.insert(I);
5105   };
5106 
5107   // We seed the scalars analysis with three classes of instructions: (1)
5108   // instructions marked uniform-after-vectorization and (2) bitcast,
5109   // getelementptr and (pointer) phi instructions used by memory accesses
5110   // requiring a scalar use.
5111   //
5112   // (1) Add to the worklist all instructions that have been identified as
5113   // uniform-after-vectorization.
5114   Worklist.insert(Uniforms[VF].begin(), Uniforms[VF].end());
5115 
5116   // (2) Add to the worklist all bitcast and getelementptr instructions used by
5117   // memory accesses requiring a scalar use. The pointer operands of loads and
5118   // stores will be scalar as long as the memory accesses is not a gather or
5119   // scatter operation. The value operand of a store will remain scalar if the
5120   // store is scalarized.
5121   for (auto *BB : TheLoop->blocks())
5122     for (auto &I : *BB) {
5123       if (auto *Load = dyn_cast<LoadInst>(&I)) {
5124         evaluatePtrUse(Load, Load->getPointerOperand());
5125       } else if (auto *Store = dyn_cast<StoreInst>(&I)) {
5126         evaluatePtrUse(Store, Store->getPointerOperand());
5127         evaluatePtrUse(Store, Store->getValueOperand());
5128       }
5129     }
5130   for (auto *I : ScalarPtrs)
5131     if (!PossibleNonScalarPtrs.count(I)) {
5132       LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *I << "\n");
5133       Worklist.insert(I);
5134     }
5135 
5136   // Insert the forced scalars.
5137   // FIXME: Currently widenPHIInstruction() often creates a dead vector
5138   // induction variable when the PHI user is scalarized.
5139   auto ForcedScalar = ForcedScalars.find(VF);
5140   if (ForcedScalar != ForcedScalars.end())
5141     for (auto *I : ForcedScalar->second)
5142       Worklist.insert(I);
5143 
5144   // Expand the worklist by looking through any bitcasts and getelementptr
5145   // instructions we've already identified as scalar. This is similar to the
5146   // expansion step in collectLoopUniforms(); however, here we're only
5147   // expanding to include additional bitcasts and getelementptr instructions.
5148   unsigned Idx = 0;
5149   while (Idx != Worklist.size()) {
5150     Instruction *Dst = Worklist[Idx++];
5151     if (!isLoopVaryingBitCastOrGEP(Dst->getOperand(0)))
5152       continue;
5153     auto *Src = cast<Instruction>(Dst->getOperand(0));
5154     if (llvm::all_of(Src->users(), [&](User *U) -> bool {
5155           auto *J = cast<Instruction>(U);
5156           return !TheLoop->contains(J) || Worklist.count(J) ||
5157                  ((isa<LoadInst>(J) || isa<StoreInst>(J)) &&
5158                   isScalarUse(J, Src));
5159         })) {
5160       Worklist.insert(Src);
5161       LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Src << "\n");
5162     }
5163   }
5164 
5165   // An induction variable will remain scalar if all users of the induction
5166   // variable and induction variable update remain scalar.
5167   for (auto &Induction : Legal->getInductionVars()) {
5168     auto *Ind = Induction.first;
5169     auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
5170 
5171     // If tail-folding is applied, the primary induction variable will be used
5172     // to feed a vector compare.
5173     if (Ind == Legal->getPrimaryInduction() && foldTailByMasking())
5174       continue;
5175 
5176     // Determine if all users of the induction variable are scalar after
5177     // vectorization.
5178     auto ScalarInd = llvm::all_of(Ind->users(), [&](User *U) -> bool {
5179       auto *I = cast<Instruction>(U);
5180       return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I);
5181     });
5182     if (!ScalarInd)
5183       continue;
5184 
5185     // Determine if all users of the induction variable update instruction are
5186     // scalar after vectorization.
5187     auto ScalarIndUpdate =
5188         llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
5189           auto *I = cast<Instruction>(U);
5190           return I == Ind || !TheLoop->contains(I) || Worklist.count(I);
5191         });
5192     if (!ScalarIndUpdate)
5193       continue;
5194 
5195     // The induction variable and its update instruction will remain scalar.
5196     Worklist.insert(Ind);
5197     Worklist.insert(IndUpdate);
5198     LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Ind << "\n");
5199     LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *IndUpdate
5200                       << "\n");
5201   }
5202 
5203   Scalars[VF].insert(Worklist.begin(), Worklist.end());
5204 }
5205 
5206 bool LoopVectorizationCostModel::isScalarWithPredication(Instruction *I,
5207                                                          ElementCount VF) {
5208   if (!blockNeedsPredication(I->getParent()))
5209     return false;
5210   switch(I->getOpcode()) {
5211   default:
5212     break;
5213   case Instruction::Load:
5214   case Instruction::Store: {
5215     if (!Legal->isMaskRequired(I))
5216       return false;
5217     auto *Ptr = getLoadStorePointerOperand(I);
5218     auto *Ty = getMemInstValueType(I);
5219     // We have already decided how to vectorize this instruction, get that
5220     // result.
5221     if (VF.isVector()) {
5222       InstWidening WideningDecision = getWideningDecision(I, VF);
5223       assert(WideningDecision != CM_Unknown &&
5224              "Widening decision should be ready at this moment");
5225       return WideningDecision == CM_Scalarize;
5226     }
5227     const Align Alignment = getLoadStoreAlignment(I);
5228     return isa<LoadInst>(I) ? !(isLegalMaskedLoad(Ty, Ptr, Alignment) ||
5229                                 isLegalMaskedGather(Ty, Alignment))
5230                             : !(isLegalMaskedStore(Ty, Ptr, Alignment) ||
5231                                 isLegalMaskedScatter(Ty, Alignment));
5232   }
5233   case Instruction::UDiv:
5234   case Instruction::SDiv:
5235   case Instruction::SRem:
5236   case Instruction::URem:
5237     return mayDivideByZero(*I);
5238   }
5239   return false;
5240 }
5241 
5242 bool LoopVectorizationCostModel::interleavedAccessCanBeWidened(
5243     Instruction *I, ElementCount VF) {
5244   assert(isAccessInterleaved(I) && "Expecting interleaved access.");
5245   assert(getWideningDecision(I, VF) == CM_Unknown &&
5246          "Decision should not be set yet.");
5247   auto *Group = getInterleavedAccessGroup(I);
5248   assert(Group && "Must have a group.");
5249 
5250   // If the instruction's allocated size doesn't equal it's type size, it
5251   // requires padding and will be scalarized.
5252   auto &DL = I->getModule()->getDataLayout();
5253   auto *ScalarTy = getMemInstValueType(I);
5254   if (hasIrregularType(ScalarTy, DL, VF))
5255     return false;
5256 
5257   // Check if masking is required.
5258   // A Group may need masking for one of two reasons: it resides in a block that
5259   // needs predication, or it was decided to use masking to deal with gaps.
5260   bool PredicatedAccessRequiresMasking =
5261       Legal->blockNeedsPredication(I->getParent()) && Legal->isMaskRequired(I);
5262   bool AccessWithGapsRequiresMasking =
5263       Group->requiresScalarEpilogue() && !isScalarEpilogueAllowed();
5264   if (!PredicatedAccessRequiresMasking && !AccessWithGapsRequiresMasking)
5265     return true;
5266 
5267   // If masked interleaving is required, we expect that the user/target had
5268   // enabled it, because otherwise it either wouldn't have been created or
5269   // it should have been invalidated by the CostModel.
5270   assert(useMaskedInterleavedAccesses(TTI) &&
5271          "Masked interleave-groups for predicated accesses are not enabled.");
5272 
5273   auto *Ty = getMemInstValueType(I);
5274   const Align Alignment = getLoadStoreAlignment(I);
5275   return isa<LoadInst>(I) ? TTI.isLegalMaskedLoad(Ty, Alignment)
5276                           : TTI.isLegalMaskedStore(Ty, Alignment);
5277 }
5278 
5279 bool LoopVectorizationCostModel::memoryInstructionCanBeWidened(
5280     Instruction *I, ElementCount VF) {
5281   // Get and ensure we have a valid memory instruction.
5282   LoadInst *LI = dyn_cast<LoadInst>(I);
5283   StoreInst *SI = dyn_cast<StoreInst>(I);
5284   assert((LI || SI) && "Invalid memory instruction");
5285 
5286   auto *Ptr = getLoadStorePointerOperand(I);
5287 
5288   // In order to be widened, the pointer should be consecutive, first of all.
5289   if (!Legal->isConsecutivePtr(Ptr))
5290     return false;
5291 
5292   // If the instruction is a store located in a predicated block, it will be
5293   // scalarized.
5294   if (isScalarWithPredication(I))
5295     return false;
5296 
5297   // If the instruction's allocated size doesn't equal it's type size, it
5298   // requires padding and will be scalarized.
5299   auto &DL = I->getModule()->getDataLayout();
5300   auto *ScalarTy = LI ? LI->getType() : SI->getValueOperand()->getType();
5301   if (hasIrregularType(ScalarTy, DL, VF))
5302     return false;
5303 
5304   return true;
5305 }
5306 
5307 void LoopVectorizationCostModel::collectLoopUniforms(ElementCount VF) {
5308   // We should not collect Uniforms more than once per VF. Right now,
5309   // this function is called from collectUniformsAndScalars(), which
5310   // already does this check. Collecting Uniforms for VF=1 does not make any
5311   // sense.
5312 
5313   assert(VF.isVector() && Uniforms.find(VF) == Uniforms.end() &&
5314          "This function should not be visited twice for the same VF");
5315 
5316   // Visit the list of Uniforms. If we'll not find any uniform value, we'll
5317   // not analyze again.  Uniforms.count(VF) will return 1.
5318   Uniforms[VF].clear();
5319 
5320   // We now know that the loop is vectorizable!
5321   // Collect instructions inside the loop that will remain uniform after
5322   // vectorization.
5323 
5324   // Global values, params and instructions outside of current loop are out of
5325   // scope.
5326   auto isOutOfScope = [&](Value *V) -> bool {
5327     Instruction *I = dyn_cast<Instruction>(V);
5328     return (!I || !TheLoop->contains(I));
5329   };
5330 
5331   SetVector<Instruction *> Worklist;
5332   BasicBlock *Latch = TheLoop->getLoopLatch();
5333 
5334   // Instructions that are scalar with predication must not be considered
5335   // uniform after vectorization, because that would create an erroneous
5336   // replicating region where only a single instance out of VF should be formed.
5337   // TODO: optimize such seldom cases if found important, see PR40816.
5338   auto addToWorklistIfAllowed = [&](Instruction *I) -> void {
5339     if (isOutOfScope(I)) {
5340       LLVM_DEBUG(dbgs() << "LV: Found not uniform due to scope: "
5341                         << *I << "\n");
5342       return;
5343     }
5344     if (isScalarWithPredication(I, VF)) {
5345       LLVM_DEBUG(dbgs() << "LV: Found not uniform being ScalarWithPredication: "
5346                         << *I << "\n");
5347       return;
5348     }
5349     LLVM_DEBUG(dbgs() << "LV: Found uniform instruction: " << *I << "\n");
5350     Worklist.insert(I);
5351   };
5352 
5353   // Start with the conditional branch. If the branch condition is an
5354   // instruction contained in the loop that is only used by the branch, it is
5355   // uniform.
5356   auto *Cmp = dyn_cast<Instruction>(Latch->getTerminator()->getOperand(0));
5357   if (Cmp && TheLoop->contains(Cmp) && Cmp->hasOneUse())
5358     addToWorklistIfAllowed(Cmp);
5359 
5360   auto isUniformDecision = [&](Instruction *I, ElementCount VF) {
5361     InstWidening WideningDecision = getWideningDecision(I, VF);
5362     assert(WideningDecision != CM_Unknown &&
5363            "Widening decision should be ready at this moment");
5364 
5365     // A uniform memory op is itself uniform.  We exclude uniform stores
5366     // here as they demand the last lane, not the first one.
5367     if (isa<LoadInst>(I) && Legal->isUniformMemOp(*I)) {
5368       assert(WideningDecision == CM_Scalarize);
5369       return true;
5370     }
5371 
5372     return (WideningDecision == CM_Widen ||
5373             WideningDecision == CM_Widen_Reverse ||
5374             WideningDecision == CM_Interleave);
5375   };
5376 
5377 
5378   // Returns true if Ptr is the pointer operand of a memory access instruction
5379   // I, and I is known to not require scalarization.
5380   auto isVectorizedMemAccessUse = [&](Instruction *I, Value *Ptr) -> bool {
5381     return getLoadStorePointerOperand(I) == Ptr && isUniformDecision(I, VF);
5382   };
5383 
5384   // Holds a list of values which are known to have at least one uniform use.
5385   // Note that there may be other uses which aren't uniform.  A "uniform use"
5386   // here is something which only demands lane 0 of the unrolled iterations;
5387   // it does not imply that all lanes produce the same value (e.g. this is not
5388   // the usual meaning of uniform)
5389   SmallPtrSet<Value *, 8> HasUniformUse;
5390 
5391   // Scan the loop for instructions which are either a) known to have only
5392   // lane 0 demanded or b) are uses which demand only lane 0 of their operand.
5393   for (auto *BB : TheLoop->blocks())
5394     for (auto &I : *BB) {
5395       // If there's no pointer operand, there's nothing to do.
5396       auto *Ptr = getLoadStorePointerOperand(&I);
5397       if (!Ptr)
5398         continue;
5399 
5400       // A uniform memory op is itself uniform.  We exclude uniform stores
5401       // here as they demand the last lane, not the first one.
5402       if (isa<LoadInst>(I) && Legal->isUniformMemOp(I))
5403         addToWorklistIfAllowed(&I);
5404 
5405       if (isUniformDecision(&I, VF)) {
5406         assert(isVectorizedMemAccessUse(&I, Ptr) && "consistency check");
5407         HasUniformUse.insert(Ptr);
5408       }
5409     }
5410 
5411   // Add to the worklist any operands which have *only* uniform (e.g. lane 0
5412   // demanding) users.  Since loops are assumed to be in LCSSA form, this
5413   // disallows uses outside the loop as well.
5414   for (auto *V : HasUniformUse) {
5415     if (isOutOfScope(V))
5416       continue;
5417     auto *I = cast<Instruction>(V);
5418     auto UsersAreMemAccesses =
5419       llvm::all_of(I->users(), [&](User *U) -> bool {
5420         return isVectorizedMemAccessUse(cast<Instruction>(U), V);
5421       });
5422     if (UsersAreMemAccesses)
5423       addToWorklistIfAllowed(I);
5424   }
5425 
5426   // Expand Worklist in topological order: whenever a new instruction
5427   // is added , its users should be already inside Worklist.  It ensures
5428   // a uniform instruction will only be used by uniform instructions.
5429   unsigned idx = 0;
5430   while (idx != Worklist.size()) {
5431     Instruction *I = Worklist[idx++];
5432 
5433     for (auto OV : I->operand_values()) {
5434       // isOutOfScope operands cannot be uniform instructions.
5435       if (isOutOfScope(OV))
5436         continue;
5437       // First order recurrence Phi's should typically be considered
5438       // non-uniform.
5439       auto *OP = dyn_cast<PHINode>(OV);
5440       if (OP && Legal->isFirstOrderRecurrence(OP))
5441         continue;
5442       // If all the users of the operand are uniform, then add the
5443       // operand into the uniform worklist.
5444       auto *OI = cast<Instruction>(OV);
5445       if (llvm::all_of(OI->users(), [&](User *U) -> bool {
5446             auto *J = cast<Instruction>(U);
5447             return Worklist.count(J) || isVectorizedMemAccessUse(J, OI);
5448           }))
5449         addToWorklistIfAllowed(OI);
5450     }
5451   }
5452 
5453   // For an instruction to be added into Worklist above, all its users inside
5454   // the loop should also be in Worklist. However, this condition cannot be
5455   // true for phi nodes that form a cyclic dependence. We must process phi
5456   // nodes separately. An induction variable will remain uniform if all users
5457   // of the induction variable and induction variable update remain uniform.
5458   // The code below handles both pointer and non-pointer induction variables.
5459   for (auto &Induction : Legal->getInductionVars()) {
5460     auto *Ind = Induction.first;
5461     auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
5462 
5463     // Determine if all users of the induction variable are uniform after
5464     // vectorization.
5465     auto UniformInd = llvm::all_of(Ind->users(), [&](User *U) -> bool {
5466       auto *I = cast<Instruction>(U);
5467       return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) ||
5468              isVectorizedMemAccessUse(I, Ind);
5469     });
5470     if (!UniformInd)
5471       continue;
5472 
5473     // Determine if all users of the induction variable update instruction are
5474     // uniform after vectorization.
5475     auto UniformIndUpdate =
5476         llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
5477           auto *I = cast<Instruction>(U);
5478           return I == Ind || !TheLoop->contains(I) || Worklist.count(I) ||
5479                  isVectorizedMemAccessUse(I, IndUpdate);
5480         });
5481     if (!UniformIndUpdate)
5482       continue;
5483 
5484     // The induction variable and its update instruction will remain uniform.
5485     addToWorklistIfAllowed(Ind);
5486     addToWorklistIfAllowed(IndUpdate);
5487   }
5488 
5489   Uniforms[VF].insert(Worklist.begin(), Worklist.end());
5490 }
5491 
5492 bool LoopVectorizationCostModel::runtimeChecksRequired() {
5493   LLVM_DEBUG(dbgs() << "LV: Performing code size checks.\n");
5494 
5495   if (Legal->getRuntimePointerChecking()->Need) {
5496     reportVectorizationFailure("Runtime ptr check is required with -Os/-Oz",
5497         "runtime pointer checks needed. Enable vectorization of this "
5498         "loop with '#pragma clang loop vectorize(enable)' when "
5499         "compiling with -Os/-Oz",
5500         "CantVersionLoopWithOptForSize", ORE, TheLoop);
5501     return true;
5502   }
5503 
5504   if (!PSE.getUnionPredicate().getPredicates().empty()) {
5505     reportVectorizationFailure("Runtime SCEV check is required with -Os/-Oz",
5506         "runtime SCEV checks needed. Enable vectorization of this "
5507         "loop with '#pragma clang loop vectorize(enable)' when "
5508         "compiling with -Os/-Oz",
5509         "CantVersionLoopWithOptForSize", ORE, TheLoop);
5510     return true;
5511   }
5512 
5513   // FIXME: Avoid specializing for stride==1 instead of bailing out.
5514   if (!Legal->getLAI()->getSymbolicStrides().empty()) {
5515     reportVectorizationFailure("Runtime stride check for small trip count",
5516         "runtime stride == 1 checks needed. Enable vectorization of "
5517         "this loop without such check by compiling with -Os/-Oz",
5518         "CantVersionLoopWithOptForSize", ORE, TheLoop);
5519     return true;
5520   }
5521 
5522   return false;
5523 }
5524 
5525 Optional<ElementCount>
5526 LoopVectorizationCostModel::computeMaxVF(ElementCount UserVF, unsigned UserIC) {
5527   if (Legal->getRuntimePointerChecking()->Need && TTI.hasBranchDivergence()) {
5528     // TODO: It may by useful to do since it's still likely to be dynamically
5529     // uniform if the target can skip.
5530     reportVectorizationFailure(
5531         "Not inserting runtime ptr check for divergent target",
5532         "runtime pointer checks needed. Not enabled for divergent target",
5533         "CantVersionLoopWithDivergentTarget", ORE, TheLoop);
5534     return None;
5535   }
5536 
5537   unsigned TC = PSE.getSE()->getSmallConstantTripCount(TheLoop);
5538   LLVM_DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
5539   if (TC == 1) {
5540     reportVectorizationFailure("Single iteration (non) loop",
5541         "loop trip count is one, irrelevant for vectorization",
5542         "SingleIterationLoop", ORE, TheLoop);
5543     return None;
5544   }
5545 
5546   switch (ScalarEpilogueStatus) {
5547   case CM_ScalarEpilogueAllowed:
5548     return computeFeasibleMaxVF(TC, UserVF);
5549   case CM_ScalarEpilogueNotAllowedUsePredicate:
5550     LLVM_FALLTHROUGH;
5551   case CM_ScalarEpilogueNotNeededUsePredicate:
5552     LLVM_DEBUG(
5553         dbgs() << "LV: vector predicate hint/switch found.\n"
5554                << "LV: Not allowing scalar epilogue, creating predicated "
5555                << "vector loop.\n");
5556     break;
5557   case CM_ScalarEpilogueNotAllowedLowTripLoop:
5558     // fallthrough as a special case of OptForSize
5559   case CM_ScalarEpilogueNotAllowedOptSize:
5560     if (ScalarEpilogueStatus == CM_ScalarEpilogueNotAllowedOptSize)
5561       LLVM_DEBUG(
5562           dbgs() << "LV: Not allowing scalar epilogue due to -Os/-Oz.\n");
5563     else
5564       LLVM_DEBUG(dbgs() << "LV: Not allowing scalar epilogue due to low trip "
5565                         << "count.\n");
5566 
5567     // Bail if runtime checks are required, which are not good when optimising
5568     // for size.
5569     if (runtimeChecksRequired())
5570       return None;
5571 
5572     break;
5573   }
5574 
5575   // The only loops we can vectorize without a scalar epilogue, are loops with
5576   // a bottom-test and a single exiting block. We'd have to handle the fact
5577   // that not every instruction executes on the last iteration.  This will
5578   // require a lane mask which varies through the vector loop body.  (TODO)
5579   if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
5580     // If there was a tail-folding hint/switch, but we can't fold the tail by
5581     // masking, fallback to a vectorization with a scalar epilogue.
5582     if (ScalarEpilogueStatus == CM_ScalarEpilogueNotNeededUsePredicate) {
5583       LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking: vectorize with a "
5584                            "scalar epilogue instead.\n");
5585       ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
5586       return computeFeasibleMaxVF(TC, UserVF);
5587     }
5588     return None;
5589   }
5590 
5591   // Now try the tail folding
5592 
5593   // Invalidate interleave groups that require an epilogue if we can't mask
5594   // the interleave-group.
5595   if (!useMaskedInterleavedAccesses(TTI)) {
5596     assert(WideningDecisions.empty() && Uniforms.empty() && Scalars.empty() &&
5597            "No decisions should have been taken at this point");
5598     // Note: There is no need to invalidate any cost modeling decisions here, as
5599     // non where taken so far.
5600     InterleaveInfo.invalidateGroupsRequiringScalarEpilogue();
5601   }
5602 
5603   ElementCount MaxVF = computeFeasibleMaxVF(TC, UserVF);
5604   assert(!MaxVF.isScalable() &&
5605          "Scalable vectors do not yet support tail folding");
5606   assert((UserVF.isNonZero() || isPowerOf2_32(MaxVF.getFixedValue())) &&
5607          "MaxVF must be a power of 2");
5608   unsigned MaxVFtimesIC =
5609       UserIC ? MaxVF.getFixedValue() * UserIC : MaxVF.getFixedValue();
5610   // Avoid tail folding if the trip count is known to be a multiple of any VF we
5611   // chose.
5612   ScalarEvolution *SE = PSE.getSE();
5613   const SCEV *BackedgeTakenCount = PSE.getBackedgeTakenCount();
5614   const SCEV *ExitCount = SE->getAddExpr(
5615       BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType()));
5616   const SCEV *Rem = SE->getURemExpr(
5617       SE->applyLoopGuards(ExitCount, TheLoop),
5618       SE->getConstant(BackedgeTakenCount->getType(), MaxVFtimesIC));
5619   if (Rem->isZero()) {
5620     // Accept MaxVF if we do not have a tail.
5621     LLVM_DEBUG(dbgs() << "LV: No tail will remain for any chosen VF.\n");
5622     return MaxVF;
5623   }
5624 
5625   // If we don't know the precise trip count, or if the trip count that we
5626   // found modulo the vectorization factor is not zero, try to fold the tail
5627   // by masking.
5628   // FIXME: look for a smaller MaxVF that does divide TC rather than masking.
5629   if (Legal->prepareToFoldTailByMasking()) {
5630     FoldTailByMasking = true;
5631     return MaxVF;
5632   }
5633 
5634   // If there was a tail-folding hint/switch, but we can't fold the tail by
5635   // masking, fallback to a vectorization with a scalar epilogue.
5636   if (ScalarEpilogueStatus == CM_ScalarEpilogueNotNeededUsePredicate) {
5637     LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking: vectorize with a "
5638                          "scalar epilogue instead.\n");
5639     ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
5640     return MaxVF;
5641   }
5642 
5643   if (ScalarEpilogueStatus == CM_ScalarEpilogueNotAllowedUsePredicate) {
5644     LLVM_DEBUG(dbgs() << "LV: Can't fold tail by masking: don't vectorize\n");
5645     return None;
5646   }
5647 
5648   if (TC == 0) {
5649     reportVectorizationFailure(
5650         "Unable to calculate the loop count due to complex control flow",
5651         "unable to calculate the loop count due to complex control flow",
5652         "UnknownLoopCountComplexCFG", ORE, TheLoop);
5653     return None;
5654   }
5655 
5656   reportVectorizationFailure(
5657       "Cannot optimize for size and vectorize at the same time.",
5658       "cannot optimize for size and vectorize at the same time. "
5659       "Enable vectorization of this loop with '#pragma clang loop "
5660       "vectorize(enable)' when compiling with -Os/-Oz",
5661       "NoTailLoopWithOptForSize", ORE, TheLoop);
5662   return None;
5663 }
5664 
5665 ElementCount
5666 LoopVectorizationCostModel::computeFeasibleMaxVF(unsigned ConstTripCount,
5667                                                  ElementCount UserVF) {
5668   bool IgnoreScalableUserVF = UserVF.isScalable() &&
5669                               !TTI.supportsScalableVectors() &&
5670                               !ForceTargetSupportsScalableVectors;
5671   if (IgnoreScalableUserVF) {
5672     LLVM_DEBUG(
5673         dbgs() << "LV: Ignoring VF=" << UserVF
5674                << " because target does not support scalable vectors.\n");
5675     ORE->emit([&]() {
5676       return OptimizationRemarkAnalysis(DEBUG_TYPE, "IgnoreScalableUserVF",
5677                                         TheLoop->getStartLoc(),
5678                                         TheLoop->getHeader())
5679              << "Ignoring VF=" << ore::NV("UserVF", UserVF)
5680              << " because target does not support scalable vectors.";
5681     });
5682   }
5683 
5684   // Beyond this point two scenarios are handled. If UserVF isn't specified
5685   // then a suitable VF is chosen. If UserVF is specified and there are
5686   // dependencies, check if it's legal. However, if a UserVF is specified and
5687   // there are no dependencies, then there's nothing to do.
5688   if (UserVF.isNonZero() && !IgnoreScalableUserVF &&
5689       Legal->isSafeForAnyVectorWidth())
5690     return UserVF;
5691 
5692   MinBWs = computeMinimumValueSizes(TheLoop->getBlocks(), *DB, &TTI);
5693   unsigned SmallestType, WidestType;
5694   std::tie(SmallestType, WidestType) = getSmallestAndWidestTypes();
5695   unsigned WidestRegister = TTI.getRegisterBitWidth(true);
5696 
5697   // Get the maximum safe dependence distance in bits computed by LAA.
5698   // It is computed by MaxVF * sizeOf(type) * 8, where type is taken from
5699   // the memory accesses that is most restrictive (involved in the smallest
5700   // dependence distance).
5701   unsigned MaxSafeVectorWidthInBits = Legal->getMaxSafeVectorWidthInBits();
5702 
5703   // If the user vectorization factor is legally unsafe, clamp it to a safe
5704   // value. Otherwise, return as is.
5705   if (UserVF.isNonZero() && !IgnoreScalableUserVF) {
5706     unsigned MaxSafeElements =
5707         PowerOf2Floor(MaxSafeVectorWidthInBits / WidestType);
5708     ElementCount MaxSafeVF = ElementCount::getFixed(MaxSafeElements);
5709 
5710     if (UserVF.isScalable()) {
5711       Optional<unsigned> MaxVScale = TTI.getMaxVScale();
5712 
5713       // Scale VF by vscale before checking if it's safe.
5714       MaxSafeVF = ElementCount::getScalable(
5715           MaxVScale ? (MaxSafeElements / MaxVScale.getValue()) : 0);
5716 
5717       if (MaxSafeVF.isZero()) {
5718         // The dependence distance is too small to use scalable vectors,
5719         // fallback on fixed.
5720         LLVM_DEBUG(
5721             dbgs()
5722             << "LV: Max legal vector width too small, scalable vectorization "
5723                "unfeasible. Using fixed-width vectorization instead.\n");
5724         ORE->emit([&]() {
5725           return OptimizationRemarkAnalysis(DEBUG_TYPE, "ScalableVFUnfeasible",
5726                                             TheLoop->getStartLoc(),
5727                                             TheLoop->getHeader())
5728                  << "Max legal vector width too small, scalable vectorization "
5729                  << "unfeasible. Using fixed-width vectorization instead.";
5730         });
5731         return computeFeasibleMaxVF(
5732             ConstTripCount, ElementCount::getFixed(UserVF.getKnownMinValue()));
5733       }
5734     }
5735 
5736     LLVM_DEBUG(dbgs() << "LV: The max safe VF is: " << MaxSafeVF << ".\n");
5737 
5738     if (ElementCount::isKnownLE(UserVF, MaxSafeVF))
5739       return UserVF;
5740 
5741     LLVM_DEBUG(dbgs() << "LV: User VF=" << UserVF
5742                       << " is unsafe, clamping to max safe VF=" << MaxSafeVF
5743                       << ".\n");
5744     ORE->emit([&]() {
5745       return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationFactor",
5746                                         TheLoop->getStartLoc(),
5747                                         TheLoop->getHeader())
5748              << "User-specified vectorization factor "
5749              << ore::NV("UserVectorizationFactor", UserVF)
5750              << " is unsafe, clamping to maximum safe vectorization factor "
5751              << ore::NV("VectorizationFactor", MaxSafeVF);
5752     });
5753     return MaxSafeVF;
5754   }
5755 
5756   WidestRegister = std::min(WidestRegister, MaxSafeVectorWidthInBits);
5757 
5758   // Ensure MaxVF is a power of 2; the dependence distance bound may not be.
5759   // Note that both WidestRegister and WidestType may not be a powers of 2.
5760   auto MaxVectorSize =
5761       ElementCount::getFixed(PowerOf2Floor(WidestRegister / WidestType));
5762 
5763   LLVM_DEBUG(dbgs() << "LV: The Smallest and Widest types: " << SmallestType
5764                     << " / " << WidestType << " bits.\n");
5765   LLVM_DEBUG(dbgs() << "LV: The Widest register safe to use is: "
5766                     << WidestRegister << " bits.\n");
5767 
5768   assert(MaxVectorSize.getFixedValue() <= WidestRegister &&
5769          "Did not expect to pack so many elements"
5770          " into one vector!");
5771   if (MaxVectorSize.getFixedValue() == 0) {
5772     LLVM_DEBUG(dbgs() << "LV: The target has no vector registers.\n");
5773     return ElementCount::getFixed(1);
5774   } else if (ConstTripCount && ConstTripCount < MaxVectorSize.getFixedValue() &&
5775              isPowerOf2_32(ConstTripCount)) {
5776     // We need to clamp the VF to be the ConstTripCount. There is no point in
5777     // choosing a higher viable VF as done in the loop below.
5778     LLVM_DEBUG(dbgs() << "LV: Clamping the MaxVF to the constant trip count: "
5779                       << ConstTripCount << "\n");
5780     return ElementCount::getFixed(ConstTripCount);
5781   }
5782 
5783   ElementCount MaxVF = MaxVectorSize;
5784   if (TTI.shouldMaximizeVectorBandwidth(!isScalarEpilogueAllowed()) ||
5785       (MaximizeBandwidth && isScalarEpilogueAllowed())) {
5786     // Collect all viable vectorization factors larger than the default MaxVF
5787     // (i.e. MaxVectorSize).
5788     SmallVector<ElementCount, 8> VFs;
5789     auto MaxVectorSizeMaxBW =
5790         ElementCount::getFixed(WidestRegister / SmallestType);
5791     for (ElementCount VS = MaxVectorSize * 2;
5792          ElementCount::isKnownLE(VS, MaxVectorSizeMaxBW); VS *= 2)
5793       VFs.push_back(VS);
5794 
5795     // For each VF calculate its register usage.
5796     auto RUs = calculateRegisterUsage(VFs);
5797 
5798     // Select the largest VF which doesn't require more registers than existing
5799     // ones.
5800     for (int i = RUs.size() - 1; i >= 0; --i) {
5801       bool Selected = true;
5802       for (auto &pair : RUs[i].MaxLocalUsers) {
5803         unsigned TargetNumRegisters = TTI.getNumberOfRegisters(pair.first);
5804         if (pair.second > TargetNumRegisters)
5805           Selected = false;
5806       }
5807       if (Selected) {
5808         MaxVF = VFs[i];
5809         break;
5810       }
5811     }
5812     if (ElementCount MinVF =
5813             TTI.getMinimumVF(SmallestType, /*IsScalable=*/false)) {
5814       if (ElementCount::isKnownLT(MaxVF, MinVF)) {
5815         LLVM_DEBUG(dbgs() << "LV: Overriding calculated MaxVF(" << MaxVF
5816                           << ") with target's minimum: " << MinVF << '\n');
5817         MaxVF = MinVF;
5818       }
5819     }
5820   }
5821   return MaxVF;
5822 }
5823 
5824 VectorizationFactor
5825 LoopVectorizationCostModel::selectVectorizationFactor(ElementCount MaxVF) {
5826   // FIXME: This can be fixed for scalable vectors later, because at this stage
5827   // the LoopVectorizer will only consider vectorizing a loop with scalable
5828   // vectors when the loop has a hint to enable vectorization for a given VF.
5829   assert(!MaxVF.isScalable() && "scalable vectors not yet supported");
5830 
5831   InstructionCost ExpectedCost = expectedCost(ElementCount::getFixed(1)).first;
5832   LLVM_DEBUG(dbgs() << "LV: Scalar loop costs: " << ExpectedCost << ".\n");
5833   assert(ExpectedCost.isValid() && "Unexpected invalid cost for scalar loop");
5834 
5835   auto Width = ElementCount::getFixed(1);
5836   const float ScalarCost = *ExpectedCost.getValue();
5837   float Cost = ScalarCost;
5838 
5839   bool ForceVectorization = Hints->getForce() == LoopVectorizeHints::FK_Enabled;
5840   if (ForceVectorization && MaxVF.isVector()) {
5841     // Ignore scalar width, because the user explicitly wants vectorization.
5842     // Initialize cost to max so that VF = 2 is, at least, chosen during cost
5843     // evaluation.
5844     Cost = std::numeric_limits<float>::max();
5845   }
5846 
5847   for (auto i = ElementCount::getFixed(2); ElementCount::isKnownLE(i, MaxVF);
5848        i *= 2) {
5849     // Notice that the vector loop needs to be executed less times, so
5850     // we need to divide the cost of the vector loops by the width of
5851     // the vector elements.
5852     VectorizationCostTy C = expectedCost(i);
5853     assert(C.first.isValid() && "Unexpected invalid cost for vector loop");
5854     float VectorCost = *C.first.getValue() / (float)i.getFixedValue();
5855     LLVM_DEBUG(dbgs() << "LV: Vector loop of width " << i
5856                       << " costs: " << (int)VectorCost << ".\n");
5857     if (!C.second && !ForceVectorization) {
5858       LLVM_DEBUG(
5859           dbgs() << "LV: Not considering vector loop of width " << i
5860                  << " because it will not generate any vector instructions.\n");
5861       continue;
5862     }
5863 
5864     // If profitable add it to ProfitableVF list.
5865     if (VectorCost < ScalarCost) {
5866       ProfitableVFs.push_back(VectorizationFactor(
5867           {i, (unsigned)VectorCost}));
5868     }
5869 
5870     if (VectorCost < Cost) {
5871       Cost = VectorCost;
5872       Width = i;
5873     }
5874   }
5875 
5876   if (!EnableCondStoresVectorization && NumPredStores) {
5877     reportVectorizationFailure("There are conditional stores.",
5878         "store that is conditionally executed prevents vectorization",
5879         "ConditionalStore", ORE, TheLoop);
5880     Width = ElementCount::getFixed(1);
5881     Cost = ScalarCost;
5882   }
5883 
5884   LLVM_DEBUG(if (ForceVectorization && !Width.isScalar() && Cost >= ScalarCost) dbgs()
5885              << "LV: Vectorization seems to be not beneficial, "
5886              << "but was forced by a user.\n");
5887   LLVM_DEBUG(dbgs() << "LV: Selecting VF: " << Width << ".\n");
5888   VectorizationFactor Factor = {Width,
5889                                 (unsigned)(Width.getKnownMinValue() * Cost)};
5890   return Factor;
5891 }
5892 
5893 bool LoopVectorizationCostModel::isCandidateForEpilogueVectorization(
5894     const Loop &L, ElementCount VF) const {
5895   // Cross iteration phis such as reductions need special handling and are
5896   // currently unsupported.
5897   if (any_of(L.getHeader()->phis(), [&](PHINode &Phi) {
5898         return Legal->isFirstOrderRecurrence(&Phi) ||
5899                Legal->isReductionVariable(&Phi);
5900       }))
5901     return false;
5902 
5903   // Phis with uses outside of the loop require special handling and are
5904   // currently unsupported.
5905   for (auto &Entry : Legal->getInductionVars()) {
5906     // Look for uses of the value of the induction at the last iteration.
5907     Value *PostInc = Entry.first->getIncomingValueForBlock(L.getLoopLatch());
5908     for (User *U : PostInc->users())
5909       if (!L.contains(cast<Instruction>(U)))
5910         return false;
5911     // Look for uses of penultimate value of the induction.
5912     for (User *U : Entry.first->users())
5913       if (!L.contains(cast<Instruction>(U)))
5914         return false;
5915   }
5916 
5917   // Induction variables that are widened require special handling that is
5918   // currently not supported.
5919   if (any_of(Legal->getInductionVars(), [&](auto &Entry) {
5920         return !(this->isScalarAfterVectorization(Entry.first, VF) ||
5921                  this->isProfitableToScalarize(Entry.first, VF));
5922       }))
5923     return false;
5924 
5925   return true;
5926 }
5927 
5928 bool LoopVectorizationCostModel::isEpilogueVectorizationProfitable(
5929     const ElementCount VF) const {
5930   // FIXME: We need a much better cost-model to take different parameters such
5931   // as register pressure, code size increase and cost of extra branches into
5932   // account. For now we apply a very crude heuristic and only consider loops
5933   // with vectorization factors larger than a certain value.
5934   // We also consider epilogue vectorization unprofitable for targets that don't
5935   // consider interleaving beneficial (eg. MVE).
5936   if (TTI.getMaxInterleaveFactor(VF.getKnownMinValue()) <= 1)
5937     return false;
5938   if (VF.getFixedValue() >= EpilogueVectorizationMinVF)
5939     return true;
5940   return false;
5941 }
5942 
5943 VectorizationFactor
5944 LoopVectorizationCostModel::selectEpilogueVectorizationFactor(
5945     const ElementCount MainLoopVF, const LoopVectorizationPlanner &LVP) {
5946   VectorizationFactor Result = VectorizationFactor::Disabled();
5947   if (!EnableEpilogueVectorization) {
5948     LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization is disabled.\n";);
5949     return Result;
5950   }
5951 
5952   if (!isScalarEpilogueAllowed()) {
5953     LLVM_DEBUG(
5954         dbgs() << "LEV: Unable to vectorize epilogue because no epilogue is "
5955                   "allowed.\n";);
5956     return Result;
5957   }
5958 
5959   // FIXME: This can be fixed for scalable vectors later, because at this stage
5960   // the LoopVectorizer will only consider vectorizing a loop with scalable
5961   // vectors when the loop has a hint to enable vectorization for a given VF.
5962   if (MainLoopVF.isScalable()) {
5963     LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization for scalable vectors not "
5964                          "yet supported.\n");
5965     return Result;
5966   }
5967 
5968   // Not really a cost consideration, but check for unsupported cases here to
5969   // simplify the logic.
5970   if (!isCandidateForEpilogueVectorization(*TheLoop, MainLoopVF)) {
5971     LLVM_DEBUG(
5972         dbgs() << "LEV: Unable to vectorize epilogue because the loop is "
5973                   "not a supported candidate.\n";);
5974     return Result;
5975   }
5976 
5977   if (EpilogueVectorizationForceVF > 1) {
5978     LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization factor is forced.\n";);
5979     if (LVP.hasPlanWithVFs(
5980             {MainLoopVF, ElementCount::getFixed(EpilogueVectorizationForceVF)}))
5981       return {ElementCount::getFixed(EpilogueVectorizationForceVF), 0};
5982     else {
5983       LLVM_DEBUG(
5984           dbgs()
5985               << "LEV: Epilogue vectorization forced factor is not viable.\n";);
5986       return Result;
5987     }
5988   }
5989 
5990   if (TheLoop->getHeader()->getParent()->hasOptSize() ||
5991       TheLoop->getHeader()->getParent()->hasMinSize()) {
5992     LLVM_DEBUG(
5993         dbgs()
5994             << "LEV: Epilogue vectorization skipped due to opt for size.\n";);
5995     return Result;
5996   }
5997 
5998   if (!isEpilogueVectorizationProfitable(MainLoopVF))
5999     return Result;
6000 
6001   for (auto &NextVF : ProfitableVFs)
6002     if (ElementCount::isKnownLT(NextVF.Width, MainLoopVF) &&
6003         (Result.Width.getFixedValue() == 1 || NextVF.Cost < Result.Cost) &&
6004         LVP.hasPlanWithVFs({MainLoopVF, NextVF.Width}))
6005       Result = NextVF;
6006 
6007   if (Result != VectorizationFactor::Disabled())
6008     LLVM_DEBUG(dbgs() << "LEV: Vectorizing epilogue loop with VF = "
6009                       << Result.Width.getFixedValue() << "\n";);
6010   return Result;
6011 }
6012 
6013 std::pair<unsigned, unsigned>
6014 LoopVectorizationCostModel::getSmallestAndWidestTypes() {
6015   unsigned MinWidth = -1U;
6016   unsigned MaxWidth = 8;
6017   const DataLayout &DL = TheFunction->getParent()->getDataLayout();
6018 
6019   // For each block.
6020   for (BasicBlock *BB : TheLoop->blocks()) {
6021     // For each instruction in the loop.
6022     for (Instruction &I : BB->instructionsWithoutDebug()) {
6023       Type *T = I.getType();
6024 
6025       // Skip ignored values.
6026       if (ValuesToIgnore.count(&I))
6027         continue;
6028 
6029       // Only examine Loads, Stores and PHINodes.
6030       if (!isa<LoadInst>(I) && !isa<StoreInst>(I) && !isa<PHINode>(I))
6031         continue;
6032 
6033       // Examine PHI nodes that are reduction variables. Update the type to
6034       // account for the recurrence type.
6035       if (auto *PN = dyn_cast<PHINode>(&I)) {
6036         if (!Legal->isReductionVariable(PN))
6037           continue;
6038         RecurrenceDescriptor RdxDesc = Legal->getReductionVars()[PN];
6039         if (PreferInLoopReductions ||
6040             TTI.preferInLoopReduction(RdxDesc.getOpcode(),
6041                                       RdxDesc.getRecurrenceType(),
6042                                       TargetTransformInfo::ReductionFlags()))
6043           continue;
6044         T = RdxDesc.getRecurrenceType();
6045       }
6046 
6047       // Examine the stored values.
6048       if (auto *ST = dyn_cast<StoreInst>(&I))
6049         T = ST->getValueOperand()->getType();
6050 
6051       // Ignore loaded pointer types and stored pointer types that are not
6052       // vectorizable.
6053       //
6054       // FIXME: The check here attempts to predict whether a load or store will
6055       //        be vectorized. We only know this for certain after a VF has
6056       //        been selected. Here, we assume that if an access can be
6057       //        vectorized, it will be. We should also look at extending this
6058       //        optimization to non-pointer types.
6059       //
6060       if (T->isPointerTy() && !isConsecutiveLoadOrStore(&I) &&
6061           !isAccessInterleaved(&I) && !isLegalGatherOrScatter(&I))
6062         continue;
6063 
6064       MinWidth = std::min(MinWidth,
6065                           (unsigned)DL.getTypeSizeInBits(T->getScalarType()));
6066       MaxWidth = std::max(MaxWidth,
6067                           (unsigned)DL.getTypeSizeInBits(T->getScalarType()));
6068     }
6069   }
6070 
6071   return {MinWidth, MaxWidth};
6072 }
6073 
6074 unsigned LoopVectorizationCostModel::selectInterleaveCount(ElementCount VF,
6075                                                            unsigned LoopCost) {
6076   // -- The interleave heuristics --
6077   // We interleave the loop in order to expose ILP and reduce the loop overhead.
6078   // There are many micro-architectural considerations that we can't predict
6079   // at this level. For example, frontend pressure (on decode or fetch) due to
6080   // code size, or the number and capabilities of the execution ports.
6081   //
6082   // We use the following heuristics to select the interleave count:
6083   // 1. If the code has reductions, then we interleave to break the cross
6084   // iteration dependency.
6085   // 2. If the loop is really small, then we interleave to reduce the loop
6086   // overhead.
6087   // 3. We don't interleave if we think that we will spill registers to memory
6088   // due to the increased register pressure.
6089 
6090   if (!isScalarEpilogueAllowed())
6091     return 1;
6092 
6093   // We used the distance for the interleave count.
6094   if (Legal->getMaxSafeDepDistBytes() != -1U)
6095     return 1;
6096 
6097   auto BestKnownTC = getSmallBestKnownTC(*PSE.getSE(), TheLoop);
6098   const bool HasReductions = !Legal->getReductionVars().empty();
6099   // Do not interleave loops with a relatively small known or estimated trip
6100   // count. But we will interleave when InterleaveSmallLoopScalarReduction is
6101   // enabled, and the code has scalar reductions(HasReductions && VF = 1),
6102   // because with the above conditions interleaving can expose ILP and break
6103   // cross iteration dependences for reductions.
6104   if (BestKnownTC && (*BestKnownTC < TinyTripCountInterleaveThreshold) &&
6105       !(InterleaveSmallLoopScalarReduction && HasReductions && VF.isScalar()))
6106     return 1;
6107 
6108   RegisterUsage R = calculateRegisterUsage({VF})[0];
6109   // We divide by these constants so assume that we have at least one
6110   // instruction that uses at least one register.
6111   for (auto& pair : R.MaxLocalUsers) {
6112     pair.second = std::max(pair.second, 1U);
6113   }
6114 
6115   // We calculate the interleave count using the following formula.
6116   // Subtract the number of loop invariants from the number of available
6117   // registers. These registers are used by all of the interleaved instances.
6118   // Next, divide the remaining registers by the number of registers that is
6119   // required by the loop, in order to estimate how many parallel instances
6120   // fit without causing spills. All of this is rounded down if necessary to be
6121   // a power of two. We want power of two interleave count to simplify any
6122   // addressing operations or alignment considerations.
6123   // We also want power of two interleave counts to ensure that the induction
6124   // variable of the vector loop wraps to zero, when tail is folded by masking;
6125   // this currently happens when OptForSize, in which case IC is set to 1 above.
6126   unsigned IC = UINT_MAX;
6127 
6128   for (auto& pair : R.MaxLocalUsers) {
6129     unsigned TargetNumRegisters = TTI.getNumberOfRegisters(pair.first);
6130     LLVM_DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters
6131                       << " registers of "
6132                       << TTI.getRegisterClassName(pair.first) << " register class\n");
6133     if (VF.isScalar()) {
6134       if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
6135         TargetNumRegisters = ForceTargetNumScalarRegs;
6136     } else {
6137       if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
6138         TargetNumRegisters = ForceTargetNumVectorRegs;
6139     }
6140     unsigned MaxLocalUsers = pair.second;
6141     unsigned LoopInvariantRegs = 0;
6142     if (R.LoopInvariantRegs.find(pair.first) != R.LoopInvariantRegs.end())
6143       LoopInvariantRegs = R.LoopInvariantRegs[pair.first];
6144 
6145     unsigned TmpIC = PowerOf2Floor((TargetNumRegisters - LoopInvariantRegs) / MaxLocalUsers);
6146     // Don't count the induction variable as interleaved.
6147     if (EnableIndVarRegisterHeur) {
6148       TmpIC =
6149           PowerOf2Floor((TargetNumRegisters - LoopInvariantRegs - 1) /
6150                         std::max(1U, (MaxLocalUsers - 1)));
6151     }
6152 
6153     IC = std::min(IC, TmpIC);
6154   }
6155 
6156   // Clamp the interleave ranges to reasonable counts.
6157   unsigned MaxInterleaveCount =
6158       TTI.getMaxInterleaveFactor(VF.getKnownMinValue());
6159 
6160   // Check if the user has overridden the max.
6161   if (VF.isScalar()) {
6162     if (ForceTargetMaxScalarInterleaveFactor.getNumOccurrences() > 0)
6163       MaxInterleaveCount = ForceTargetMaxScalarInterleaveFactor;
6164   } else {
6165     if (ForceTargetMaxVectorInterleaveFactor.getNumOccurrences() > 0)
6166       MaxInterleaveCount = ForceTargetMaxVectorInterleaveFactor;
6167   }
6168 
6169   // If trip count is known or estimated compile time constant, limit the
6170   // interleave count to be less than the trip count divided by VF, provided it
6171   // is at least 1.
6172   //
6173   // For scalable vectors we can't know if interleaving is beneficial. It may
6174   // not be beneficial for small loops if none of the lanes in the second vector
6175   // iterations is enabled. However, for larger loops, there is likely to be a
6176   // similar benefit as for fixed-width vectors. For now, we choose to leave
6177   // the InterleaveCount as if vscale is '1', although if some information about
6178   // the vector is known (e.g. min vector size), we can make a better decision.
6179   if (BestKnownTC) {
6180     MaxInterleaveCount =
6181         std::min(*BestKnownTC / VF.getKnownMinValue(), MaxInterleaveCount);
6182     // Make sure MaxInterleaveCount is greater than 0.
6183     MaxInterleaveCount = std::max(1u, MaxInterleaveCount);
6184   }
6185 
6186   assert(MaxInterleaveCount > 0 &&
6187          "Maximum interleave count must be greater than 0");
6188 
6189   // Clamp the calculated IC to be between the 1 and the max interleave count
6190   // that the target and trip count allows.
6191   if (IC > MaxInterleaveCount)
6192     IC = MaxInterleaveCount;
6193   else
6194     // Make sure IC is greater than 0.
6195     IC = std::max(1u, IC);
6196 
6197   assert(IC > 0 && "Interleave count must be greater than 0.");
6198 
6199   // If we did not calculate the cost for VF (because the user selected the VF)
6200   // then we calculate the cost of VF here.
6201   if (LoopCost == 0) {
6202     assert(expectedCost(VF).first.isValid() && "Expected a valid cost");
6203     LoopCost = *expectedCost(VF).first.getValue();
6204   }
6205 
6206   assert(LoopCost && "Non-zero loop cost expected");
6207 
6208   // Interleave if we vectorized this loop and there is a reduction that could
6209   // benefit from interleaving.
6210   if (VF.isVector() && HasReductions) {
6211     LLVM_DEBUG(dbgs() << "LV: Interleaving because of reductions.\n");
6212     return IC;
6213   }
6214 
6215   // Note that if we've already vectorized the loop we will have done the
6216   // runtime check and so interleaving won't require further checks.
6217   bool InterleavingRequiresRuntimePointerCheck =
6218       (VF.isScalar() && Legal->getRuntimePointerChecking()->Need);
6219 
6220   // We want to interleave small loops in order to reduce the loop overhead and
6221   // potentially expose ILP opportunities.
6222   LLVM_DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n'
6223                     << "LV: IC is " << IC << '\n'
6224                     << "LV: VF is " << VF << '\n');
6225   const bool AggressivelyInterleaveReductions =
6226       TTI.enableAggressiveInterleaving(HasReductions);
6227   if (!InterleavingRequiresRuntimePointerCheck && LoopCost < SmallLoopCost) {
6228     // We assume that the cost overhead is 1 and we use the cost model
6229     // to estimate the cost of the loop and interleave until the cost of the
6230     // loop overhead is about 5% of the cost of the loop.
6231     unsigned SmallIC =
6232         std::min(IC, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost));
6233 
6234     // Interleave until store/load ports (estimated by max interleave count) are
6235     // saturated.
6236     unsigned NumStores = Legal->getNumStores();
6237     unsigned NumLoads = Legal->getNumLoads();
6238     unsigned StoresIC = IC / (NumStores ? NumStores : 1);
6239     unsigned LoadsIC = IC / (NumLoads ? NumLoads : 1);
6240 
6241     // If we have a scalar reduction (vector reductions are already dealt with
6242     // by this point), we can increase the critical path length if the loop
6243     // we're interleaving is inside another loop. Limit, by default to 2, so the
6244     // critical path only gets increased by one reduction operation.
6245     if (HasReductions && TheLoop->getLoopDepth() > 1) {
6246       unsigned F = static_cast<unsigned>(MaxNestedScalarReductionIC);
6247       SmallIC = std::min(SmallIC, F);
6248       StoresIC = std::min(StoresIC, F);
6249       LoadsIC = std::min(LoadsIC, F);
6250     }
6251 
6252     if (EnableLoadStoreRuntimeInterleave &&
6253         std::max(StoresIC, LoadsIC) > SmallIC) {
6254       LLVM_DEBUG(
6255           dbgs() << "LV: Interleaving to saturate store or load ports.\n");
6256       return std::max(StoresIC, LoadsIC);
6257     }
6258 
6259     // If there are scalar reductions and TTI has enabled aggressive
6260     // interleaving for reductions, we will interleave to expose ILP.
6261     if (InterleaveSmallLoopScalarReduction && VF.isScalar() &&
6262         AggressivelyInterleaveReductions) {
6263       LLVM_DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
6264       // Interleave no less than SmallIC but not as aggressive as the normal IC
6265       // to satisfy the rare situation when resources are too limited.
6266       return std::max(IC / 2, SmallIC);
6267     } else {
6268       LLVM_DEBUG(dbgs() << "LV: Interleaving to reduce branch cost.\n");
6269       return SmallIC;
6270     }
6271   }
6272 
6273   // Interleave if this is a large loop (small loops are already dealt with by
6274   // this point) that could benefit from interleaving.
6275   if (AggressivelyInterleaveReductions) {
6276     LLVM_DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
6277     return IC;
6278   }
6279 
6280   LLVM_DEBUG(dbgs() << "LV: Not Interleaving.\n");
6281   return 1;
6282 }
6283 
6284 SmallVector<LoopVectorizationCostModel::RegisterUsage, 8>
6285 LoopVectorizationCostModel::calculateRegisterUsage(ArrayRef<ElementCount> VFs) {
6286   // This function calculates the register usage by measuring the highest number
6287   // of values that are alive at a single location. Obviously, this is a very
6288   // rough estimation. We scan the loop in a topological order in order and
6289   // assign a number to each instruction. We use RPO to ensure that defs are
6290   // met before their users. We assume that each instruction that has in-loop
6291   // users starts an interval. We record every time that an in-loop value is
6292   // used, so we have a list of the first and last occurrences of each
6293   // instruction. Next, we transpose this data structure into a multi map that
6294   // holds the list of intervals that *end* at a specific location. This multi
6295   // map allows us to perform a linear search. We scan the instructions linearly
6296   // and record each time that a new interval starts, by placing it in a set.
6297   // If we find this value in the multi-map then we remove it from the set.
6298   // The max register usage is the maximum size of the set.
6299   // We also search for instructions that are defined outside the loop, but are
6300   // used inside the loop. We need this number separately from the max-interval
6301   // usage number because when we unroll, loop-invariant values do not take
6302   // more register.
6303   LoopBlocksDFS DFS(TheLoop);
6304   DFS.perform(LI);
6305 
6306   RegisterUsage RU;
6307 
6308   // Each 'key' in the map opens a new interval. The values
6309   // of the map are the index of the 'last seen' usage of the
6310   // instruction that is the key.
6311   using IntervalMap = DenseMap<Instruction *, unsigned>;
6312 
6313   // Maps instruction to its index.
6314   SmallVector<Instruction *, 64> IdxToInstr;
6315   // Marks the end of each interval.
6316   IntervalMap EndPoint;
6317   // Saves the list of instruction indices that are used in the loop.
6318   SmallPtrSet<Instruction *, 8> Ends;
6319   // Saves the list of values that are used in the loop but are
6320   // defined outside the loop, such as arguments and constants.
6321   SmallPtrSet<Value *, 8> LoopInvariants;
6322 
6323   for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) {
6324     for (Instruction &I : BB->instructionsWithoutDebug()) {
6325       IdxToInstr.push_back(&I);
6326 
6327       // Save the end location of each USE.
6328       for (Value *U : I.operands()) {
6329         auto *Instr = dyn_cast<Instruction>(U);
6330 
6331         // Ignore non-instruction values such as arguments, constants, etc.
6332         if (!Instr)
6333           continue;
6334 
6335         // If this instruction is outside the loop then record it and continue.
6336         if (!TheLoop->contains(Instr)) {
6337           LoopInvariants.insert(Instr);
6338           continue;
6339         }
6340 
6341         // Overwrite previous end points.
6342         EndPoint[Instr] = IdxToInstr.size();
6343         Ends.insert(Instr);
6344       }
6345     }
6346   }
6347 
6348   // Saves the list of intervals that end with the index in 'key'.
6349   using InstrList = SmallVector<Instruction *, 2>;
6350   DenseMap<unsigned, InstrList> TransposeEnds;
6351 
6352   // Transpose the EndPoints to a list of values that end at each index.
6353   for (auto &Interval : EndPoint)
6354     TransposeEnds[Interval.second].push_back(Interval.first);
6355 
6356   SmallPtrSet<Instruction *, 8> OpenIntervals;
6357   SmallVector<RegisterUsage, 8> RUs(VFs.size());
6358   SmallVector<SmallMapVector<unsigned, unsigned, 4>, 8> MaxUsages(VFs.size());
6359 
6360   LLVM_DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
6361 
6362   // A lambda that gets the register usage for the given type and VF.
6363   const auto &TTICapture = TTI;
6364   auto GetRegUsage = [&TTICapture](Type *Ty, ElementCount VF) {
6365     if (Ty->isTokenTy() || !VectorType::isValidElementType(Ty))
6366       return 0U;
6367     return TTICapture.getRegUsageForType(VectorType::get(Ty, VF));
6368   };
6369 
6370   for (unsigned int i = 0, s = IdxToInstr.size(); i < s; ++i) {
6371     Instruction *I = IdxToInstr[i];
6372 
6373     // Remove all of the instructions that end at this location.
6374     InstrList &List = TransposeEnds[i];
6375     for (Instruction *ToRemove : List)
6376       OpenIntervals.erase(ToRemove);
6377 
6378     // Ignore instructions that are never used within the loop.
6379     if (!Ends.count(I))
6380       continue;
6381 
6382     // Skip ignored values.
6383     if (ValuesToIgnore.count(I))
6384       continue;
6385 
6386     // For each VF find the maximum usage of registers.
6387     for (unsigned j = 0, e = VFs.size(); j < e; ++j) {
6388       // Count the number of live intervals.
6389       SmallMapVector<unsigned, unsigned, 4> RegUsage;
6390 
6391       if (VFs[j].isScalar()) {
6392         for (auto Inst : OpenIntervals) {
6393           unsigned ClassID = TTI.getRegisterClassForType(false, Inst->getType());
6394           if (RegUsage.find(ClassID) == RegUsage.end())
6395             RegUsage[ClassID] = 1;
6396           else
6397             RegUsage[ClassID] += 1;
6398         }
6399       } else {
6400         collectUniformsAndScalars(VFs[j]);
6401         for (auto Inst : OpenIntervals) {
6402           // Skip ignored values for VF > 1.
6403           if (VecValuesToIgnore.count(Inst))
6404             continue;
6405           if (isScalarAfterVectorization(Inst, VFs[j])) {
6406             unsigned ClassID = TTI.getRegisterClassForType(false, Inst->getType());
6407             if (RegUsage.find(ClassID) == RegUsage.end())
6408               RegUsage[ClassID] = 1;
6409             else
6410               RegUsage[ClassID] += 1;
6411           } else {
6412             unsigned ClassID = TTI.getRegisterClassForType(true, Inst->getType());
6413             if (RegUsage.find(ClassID) == RegUsage.end())
6414               RegUsage[ClassID] = GetRegUsage(Inst->getType(), VFs[j]);
6415             else
6416               RegUsage[ClassID] += GetRegUsage(Inst->getType(), VFs[j]);
6417           }
6418         }
6419       }
6420 
6421       for (auto& pair : RegUsage) {
6422         if (MaxUsages[j].find(pair.first) != MaxUsages[j].end())
6423           MaxUsages[j][pair.first] = std::max(MaxUsages[j][pair.first], pair.second);
6424         else
6425           MaxUsages[j][pair.first] = pair.second;
6426       }
6427     }
6428 
6429     LLVM_DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # "
6430                       << OpenIntervals.size() << '\n');
6431 
6432     // Add the current instruction to the list of open intervals.
6433     OpenIntervals.insert(I);
6434   }
6435 
6436   for (unsigned i = 0, e = VFs.size(); i < e; ++i) {
6437     SmallMapVector<unsigned, unsigned, 4> Invariant;
6438 
6439     for (auto Inst : LoopInvariants) {
6440       unsigned Usage =
6441           VFs[i].isScalar() ? 1 : GetRegUsage(Inst->getType(), VFs[i]);
6442       unsigned ClassID =
6443           TTI.getRegisterClassForType(VFs[i].isVector(), Inst->getType());
6444       if (Invariant.find(ClassID) == Invariant.end())
6445         Invariant[ClassID] = Usage;
6446       else
6447         Invariant[ClassID] += Usage;
6448     }
6449 
6450     LLVM_DEBUG({
6451       dbgs() << "LV(REG): VF = " << VFs[i] << '\n';
6452       dbgs() << "LV(REG): Found max usage: " << MaxUsages[i].size()
6453              << " item\n";
6454       for (const auto &pair : MaxUsages[i]) {
6455         dbgs() << "LV(REG): RegisterClass: "
6456                << TTI.getRegisterClassName(pair.first) << ", " << pair.second
6457                << " registers\n";
6458       }
6459       dbgs() << "LV(REG): Found invariant usage: " << Invariant.size()
6460              << " item\n";
6461       for (const auto &pair : Invariant) {
6462         dbgs() << "LV(REG): RegisterClass: "
6463                << TTI.getRegisterClassName(pair.first) << ", " << pair.second
6464                << " registers\n";
6465       }
6466     });
6467 
6468     RU.LoopInvariantRegs = Invariant;
6469     RU.MaxLocalUsers = MaxUsages[i];
6470     RUs[i] = RU;
6471   }
6472 
6473   return RUs;
6474 }
6475 
6476 bool LoopVectorizationCostModel::useEmulatedMaskMemRefHack(Instruction *I){
6477   // TODO: Cost model for emulated masked load/store is completely
6478   // broken. This hack guides the cost model to use an artificially
6479   // high enough value to practically disable vectorization with such
6480   // operations, except where previously deployed legality hack allowed
6481   // using very low cost values. This is to avoid regressions coming simply
6482   // from moving "masked load/store" check from legality to cost model.
6483   // Masked Load/Gather emulation was previously never allowed.
6484   // Limited number of Masked Store/Scatter emulation was allowed.
6485   assert(isPredicatedInst(I) && "Expecting a scalar emulated instruction");
6486   return isa<LoadInst>(I) ||
6487          (isa<StoreInst>(I) &&
6488           NumPredStores > NumberOfStoresToPredicate);
6489 }
6490 
6491 void LoopVectorizationCostModel::collectInstsToScalarize(ElementCount VF) {
6492   // If we aren't vectorizing the loop, or if we've already collected the
6493   // instructions to scalarize, there's nothing to do. Collection may already
6494   // have occurred if we have a user-selected VF and are now computing the
6495   // expected cost for interleaving.
6496   if (VF.isScalar() || VF.isZero() ||
6497       InstsToScalarize.find(VF) != InstsToScalarize.end())
6498     return;
6499 
6500   // Initialize a mapping for VF in InstsToScalalarize. If we find that it's
6501   // not profitable to scalarize any instructions, the presence of VF in the
6502   // map will indicate that we've analyzed it already.
6503   ScalarCostsTy &ScalarCostsVF = InstsToScalarize[VF];
6504 
6505   // Find all the instructions that are scalar with predication in the loop and
6506   // determine if it would be better to not if-convert the blocks they are in.
6507   // If so, we also record the instructions to scalarize.
6508   for (BasicBlock *BB : TheLoop->blocks()) {
6509     if (!blockNeedsPredication(BB))
6510       continue;
6511     for (Instruction &I : *BB)
6512       if (isScalarWithPredication(&I)) {
6513         ScalarCostsTy ScalarCosts;
6514         // Do not apply discount logic if hacked cost is needed
6515         // for emulated masked memrefs.
6516         if (!useEmulatedMaskMemRefHack(&I) &&
6517             computePredInstDiscount(&I, ScalarCosts, VF) >= 0)
6518           ScalarCostsVF.insert(ScalarCosts.begin(), ScalarCosts.end());
6519         // Remember that BB will remain after vectorization.
6520         PredicatedBBsAfterVectorization.insert(BB);
6521       }
6522   }
6523 }
6524 
6525 int LoopVectorizationCostModel::computePredInstDiscount(
6526     Instruction *PredInst, ScalarCostsTy &ScalarCosts, ElementCount VF) {
6527   assert(!isUniformAfterVectorization(PredInst, VF) &&
6528          "Instruction marked uniform-after-vectorization will be predicated");
6529 
6530   // Initialize the discount to zero, meaning that the scalar version and the
6531   // vector version cost the same.
6532   InstructionCost Discount = 0;
6533 
6534   // Holds instructions to analyze. The instructions we visit are mapped in
6535   // ScalarCosts. Those instructions are the ones that would be scalarized if
6536   // we find that the scalar version costs less.
6537   SmallVector<Instruction *, 8> Worklist;
6538 
6539   // Returns true if the given instruction can be scalarized.
6540   auto canBeScalarized = [&](Instruction *I) -> bool {
6541     // We only attempt to scalarize instructions forming a single-use chain
6542     // from the original predicated block that would otherwise be vectorized.
6543     // Although not strictly necessary, we give up on instructions we know will
6544     // already be scalar to avoid traversing chains that are unlikely to be
6545     // beneficial.
6546     if (!I->hasOneUse() || PredInst->getParent() != I->getParent() ||
6547         isScalarAfterVectorization(I, VF))
6548       return false;
6549 
6550     // If the instruction is scalar with predication, it will be analyzed
6551     // separately. We ignore it within the context of PredInst.
6552     if (isScalarWithPredication(I))
6553       return false;
6554 
6555     // If any of the instruction's operands are uniform after vectorization,
6556     // the instruction cannot be scalarized. This prevents, for example, a
6557     // masked load from being scalarized.
6558     //
6559     // We assume we will only emit a value for lane zero of an instruction
6560     // marked uniform after vectorization, rather than VF identical values.
6561     // Thus, if we scalarize an instruction that uses a uniform, we would
6562     // create uses of values corresponding to the lanes we aren't emitting code
6563     // for. This behavior can be changed by allowing getScalarValue to clone
6564     // the lane zero values for uniforms rather than asserting.
6565     for (Use &U : I->operands())
6566       if (auto *J = dyn_cast<Instruction>(U.get()))
6567         if (isUniformAfterVectorization(J, VF))
6568           return false;
6569 
6570     // Otherwise, we can scalarize the instruction.
6571     return true;
6572   };
6573 
6574   // Compute the expected cost discount from scalarizing the entire expression
6575   // feeding the predicated instruction. We currently only consider expressions
6576   // that are single-use instruction chains.
6577   Worklist.push_back(PredInst);
6578   while (!Worklist.empty()) {
6579     Instruction *I = Worklist.pop_back_val();
6580 
6581     // If we've already analyzed the instruction, there's nothing to do.
6582     if (ScalarCosts.find(I) != ScalarCosts.end())
6583       continue;
6584 
6585     // Compute the cost of the vector instruction. Note that this cost already
6586     // includes the scalarization overhead of the predicated instruction.
6587     InstructionCost VectorCost = getInstructionCost(I, VF).first;
6588 
6589     // Compute the cost of the scalarized instruction. This cost is the cost of
6590     // the instruction as if it wasn't if-converted and instead remained in the
6591     // predicated block. We will scale this cost by block probability after
6592     // computing the scalarization overhead.
6593     assert(!VF.isScalable() && "scalable vectors not yet supported.");
6594     InstructionCost ScalarCost =
6595         VF.getKnownMinValue() *
6596         getInstructionCost(I, ElementCount::getFixed(1)).first;
6597 
6598     // Compute the scalarization overhead of needed insertelement instructions
6599     // and phi nodes.
6600     if (isScalarWithPredication(I) && !I->getType()->isVoidTy()) {
6601       ScalarCost += TTI.getScalarizationOverhead(
6602           cast<VectorType>(ToVectorTy(I->getType(), VF)),
6603           APInt::getAllOnesValue(VF.getKnownMinValue()), true, false);
6604       assert(!VF.isScalable() && "scalable vectors not yet supported.");
6605       ScalarCost +=
6606           VF.getKnownMinValue() *
6607           TTI.getCFInstrCost(Instruction::PHI, TTI::TCK_RecipThroughput);
6608     }
6609 
6610     // Compute the scalarization overhead of needed extractelement
6611     // instructions. For each of the instruction's operands, if the operand can
6612     // be scalarized, add it to the worklist; otherwise, account for the
6613     // overhead.
6614     for (Use &U : I->operands())
6615       if (auto *J = dyn_cast<Instruction>(U.get())) {
6616         assert(VectorType::isValidElementType(J->getType()) &&
6617                "Instruction has non-scalar type");
6618         if (canBeScalarized(J))
6619           Worklist.push_back(J);
6620         else if (needsExtract(J, VF)) {
6621           assert(!VF.isScalable() && "scalable vectors not yet supported.");
6622           ScalarCost += TTI.getScalarizationOverhead(
6623               cast<VectorType>(ToVectorTy(J->getType(), VF)),
6624               APInt::getAllOnesValue(VF.getKnownMinValue()), false, true);
6625         }
6626       }
6627 
6628     // Scale the total scalar cost by block probability.
6629     ScalarCost /= getReciprocalPredBlockProb();
6630 
6631     // Compute the discount. A non-negative discount means the vector version
6632     // of the instruction costs more, and scalarizing would be beneficial.
6633     Discount += VectorCost - ScalarCost;
6634     ScalarCosts[I] = ScalarCost;
6635   }
6636 
6637   return *Discount.getValue();
6638 }
6639 
6640 LoopVectorizationCostModel::VectorizationCostTy
6641 LoopVectorizationCostModel::expectedCost(ElementCount VF) {
6642   VectorizationCostTy Cost;
6643 
6644   // For each block.
6645   for (BasicBlock *BB : TheLoop->blocks()) {
6646     VectorizationCostTy BlockCost;
6647 
6648     // For each instruction in the old loop.
6649     for (Instruction &I : BB->instructionsWithoutDebug()) {
6650       // Skip ignored values.
6651       if (ValuesToIgnore.count(&I) ||
6652           (VF.isVector() && VecValuesToIgnore.count(&I)))
6653         continue;
6654 
6655       VectorizationCostTy C = getInstructionCost(&I, VF);
6656 
6657       // Check if we should override the cost.
6658       if (ForceTargetInstructionCost.getNumOccurrences() > 0)
6659         C.first = InstructionCost(ForceTargetInstructionCost);
6660 
6661       BlockCost.first += C.first;
6662       BlockCost.second |= C.second;
6663       LLVM_DEBUG(dbgs() << "LV: Found an estimated cost of " << C.first
6664                         << " for VF " << VF << " For instruction: " << I
6665                         << '\n');
6666     }
6667 
6668     // If we are vectorizing a predicated block, it will have been
6669     // if-converted. This means that the block's instructions (aside from
6670     // stores and instructions that may divide by zero) will now be
6671     // unconditionally executed. For the scalar case, we may not always execute
6672     // the predicated block, if it is an if-else block. Thus, scale the block's
6673     // cost by the probability of executing it. blockNeedsPredication from
6674     // Legal is used so as to not include all blocks in tail folded loops.
6675     if (VF.isScalar() && Legal->blockNeedsPredication(BB))
6676       BlockCost.first /= getReciprocalPredBlockProb();
6677 
6678     Cost.first += BlockCost.first;
6679     Cost.second |= BlockCost.second;
6680   }
6681 
6682   return Cost;
6683 }
6684 
6685 /// Gets Address Access SCEV after verifying that the access pattern
6686 /// is loop invariant except the induction variable dependence.
6687 ///
6688 /// This SCEV can be sent to the Target in order to estimate the address
6689 /// calculation cost.
6690 static const SCEV *getAddressAccessSCEV(
6691               Value *Ptr,
6692               LoopVectorizationLegality *Legal,
6693               PredicatedScalarEvolution &PSE,
6694               const Loop *TheLoop) {
6695 
6696   auto *Gep = dyn_cast<GetElementPtrInst>(Ptr);
6697   if (!Gep)
6698     return nullptr;
6699 
6700   // We are looking for a gep with all loop invariant indices except for one
6701   // which should be an induction variable.
6702   auto SE = PSE.getSE();
6703   unsigned NumOperands = Gep->getNumOperands();
6704   for (unsigned i = 1; i < NumOperands; ++i) {
6705     Value *Opd = Gep->getOperand(i);
6706     if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
6707         !Legal->isInductionVariable(Opd))
6708       return nullptr;
6709   }
6710 
6711   // Now we know we have a GEP ptr, %inv, %ind, %inv. return the Ptr SCEV.
6712   return PSE.getSCEV(Ptr);
6713 }
6714 
6715 static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
6716   return Legal->hasStride(I->getOperand(0)) ||
6717          Legal->hasStride(I->getOperand(1));
6718 }
6719 
6720 InstructionCost
6721 LoopVectorizationCostModel::getMemInstScalarizationCost(Instruction *I,
6722                                                         ElementCount VF) {
6723   assert(VF.isVector() &&
6724          "Scalarization cost of instruction implies vectorization.");
6725   assert(!VF.isScalable() && "scalable vectors not yet supported.");
6726   Type *ValTy = getMemInstValueType(I);
6727   auto SE = PSE.getSE();
6728 
6729   unsigned AS = getLoadStoreAddressSpace(I);
6730   Value *Ptr = getLoadStorePointerOperand(I);
6731   Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
6732 
6733   // Figure out whether the access is strided and get the stride value
6734   // if it's known in compile time
6735   const SCEV *PtrSCEV = getAddressAccessSCEV(Ptr, Legal, PSE, TheLoop);
6736 
6737   // Get the cost of the scalar memory instruction and address computation.
6738   InstructionCost Cost =
6739       VF.getKnownMinValue() * TTI.getAddressComputationCost(PtrTy, SE, PtrSCEV);
6740 
6741   // Don't pass *I here, since it is scalar but will actually be part of a
6742   // vectorized loop where the user of it is a vectorized instruction.
6743   const Align Alignment = getLoadStoreAlignment(I);
6744   Cost += VF.getKnownMinValue() *
6745           TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(), Alignment,
6746                               AS, TTI::TCK_RecipThroughput);
6747 
6748   // Get the overhead of the extractelement and insertelement instructions
6749   // we might create due to scalarization.
6750   Cost += getScalarizationOverhead(I, VF);
6751 
6752   // If we have a predicated store, it may not be executed for each vector
6753   // lane. Scale the cost by the probability of executing the predicated
6754   // block.
6755   if (isPredicatedInst(I)) {
6756     Cost /= getReciprocalPredBlockProb();
6757 
6758     if (useEmulatedMaskMemRefHack(I))
6759       // Artificially setting to a high enough value to practically disable
6760       // vectorization with such operations.
6761       Cost = 3000000;
6762   }
6763 
6764   return Cost;
6765 }
6766 
6767 InstructionCost
6768 LoopVectorizationCostModel::getConsecutiveMemOpCost(Instruction *I,
6769                                                     ElementCount VF) {
6770   Type *ValTy = getMemInstValueType(I);
6771   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
6772   Value *Ptr = getLoadStorePointerOperand(I);
6773   unsigned AS = getLoadStoreAddressSpace(I);
6774   int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
6775   enum TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
6776 
6777   assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
6778          "Stride should be 1 or -1 for consecutive memory access");
6779   const Align Alignment = getLoadStoreAlignment(I);
6780   InstructionCost Cost = 0;
6781   if (Legal->isMaskRequired(I))
6782     Cost += TTI.getMaskedMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS,
6783                                       CostKind);
6784   else
6785     Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS,
6786                                 CostKind, I);
6787 
6788   bool Reverse = ConsecutiveStride < 0;
6789   if (Reverse)
6790     Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, 0);
6791   return Cost;
6792 }
6793 
6794 InstructionCost
6795 LoopVectorizationCostModel::getUniformMemOpCost(Instruction *I,
6796                                                 ElementCount VF) {
6797   assert(Legal->isUniformMemOp(*I));
6798 
6799   Type *ValTy = getMemInstValueType(I);
6800   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
6801   const Align Alignment = getLoadStoreAlignment(I);
6802   unsigned AS = getLoadStoreAddressSpace(I);
6803   enum TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
6804   if (isa<LoadInst>(I)) {
6805     return TTI.getAddressComputationCost(ValTy) +
6806            TTI.getMemoryOpCost(Instruction::Load, ValTy, Alignment, AS,
6807                                CostKind) +
6808            TTI.getShuffleCost(TargetTransformInfo::SK_Broadcast, VectorTy);
6809   }
6810   StoreInst *SI = cast<StoreInst>(I);
6811 
6812   bool isLoopInvariantStoreValue = Legal->isUniform(SI->getValueOperand());
6813   return TTI.getAddressComputationCost(ValTy) +
6814          TTI.getMemoryOpCost(Instruction::Store, ValTy, Alignment, AS,
6815                              CostKind) +
6816          (isLoopInvariantStoreValue
6817               ? 0
6818               : TTI.getVectorInstrCost(Instruction::ExtractElement, VectorTy,
6819                                        VF.getKnownMinValue() - 1));
6820 }
6821 
6822 InstructionCost
6823 LoopVectorizationCostModel::getGatherScatterCost(Instruction *I,
6824                                                  ElementCount VF) {
6825   Type *ValTy = getMemInstValueType(I);
6826   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
6827   const Align Alignment = getLoadStoreAlignment(I);
6828   const Value *Ptr = getLoadStorePointerOperand(I);
6829 
6830   return TTI.getAddressComputationCost(VectorTy) +
6831          TTI.getGatherScatterOpCost(
6832              I->getOpcode(), VectorTy, Ptr, Legal->isMaskRequired(I), Alignment,
6833              TargetTransformInfo::TCK_RecipThroughput, I);
6834 }
6835 
6836 InstructionCost
6837 LoopVectorizationCostModel::getInterleaveGroupCost(Instruction *I,
6838                                                    ElementCount VF) {
6839   // TODO: Once we have support for interleaving with scalable vectors
6840   // we can calculate the cost properly here.
6841   if (VF.isScalable())
6842     return InstructionCost::getInvalid();
6843 
6844   Type *ValTy = getMemInstValueType(I);
6845   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
6846   unsigned AS = getLoadStoreAddressSpace(I);
6847 
6848   auto Group = getInterleavedAccessGroup(I);
6849   assert(Group && "Fail to get an interleaved access group.");
6850 
6851   unsigned InterleaveFactor = Group->getFactor();
6852   auto *WideVecTy = VectorType::get(ValTy, VF * InterleaveFactor);
6853 
6854   // Holds the indices of existing members in an interleaved load group.
6855   // An interleaved store group doesn't need this as it doesn't allow gaps.
6856   SmallVector<unsigned, 4> Indices;
6857   if (isa<LoadInst>(I)) {
6858     for (unsigned i = 0; i < InterleaveFactor; i++)
6859       if (Group->getMember(i))
6860         Indices.push_back(i);
6861   }
6862 
6863   // Calculate the cost of the whole interleaved group.
6864   bool UseMaskForGaps =
6865       Group->requiresScalarEpilogue() && !isScalarEpilogueAllowed();
6866   InstructionCost Cost = TTI.getInterleavedMemoryOpCost(
6867       I->getOpcode(), WideVecTy, Group->getFactor(), Indices, Group->getAlign(),
6868       AS, TTI::TCK_RecipThroughput, Legal->isMaskRequired(I), UseMaskForGaps);
6869 
6870   if (Group->isReverse()) {
6871     // TODO: Add support for reversed masked interleaved access.
6872     assert(!Legal->isMaskRequired(I) &&
6873            "Reverse masked interleaved access not supported.");
6874     Cost += Group->getNumMembers() *
6875             TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, 0);
6876   }
6877   return Cost;
6878 }
6879 
6880 InstructionCost LoopVectorizationCostModel::getReductionPatternCost(
6881     Instruction *I, ElementCount VF, Type *Ty, TTI::TargetCostKind CostKind) {
6882   // Early exit for no inloop reductions
6883   if (InLoopReductionChains.empty() || VF.isScalar() || !isa<VectorType>(Ty))
6884     return InstructionCost::getInvalid();
6885   auto *VectorTy = cast<VectorType>(Ty);
6886 
6887   // We are looking for a pattern of, and finding the minimal acceptable cost:
6888   //  reduce(mul(ext(A), ext(B))) or
6889   //  reduce(mul(A, B)) or
6890   //  reduce(ext(A)) or
6891   //  reduce(A).
6892   // The basic idea is that we walk down the tree to do that, finding the root
6893   // reduction instruction in InLoopReductionImmediateChains. From there we find
6894   // the pattern of mul/ext and test the cost of the entire pattern vs the cost
6895   // of the components. If the reduction cost is lower then we return it for the
6896   // reduction instruction and 0 for the other instructions in the pattern. If
6897   // it is not we return an invalid cost specifying the orignal cost method
6898   // should be used.
6899   Instruction *RetI = I;
6900   if ((RetI->getOpcode() == Instruction::SExt ||
6901        RetI->getOpcode() == Instruction::ZExt)) {
6902     if (!RetI->hasOneUser())
6903       return InstructionCost::getInvalid();
6904     RetI = RetI->user_back();
6905   }
6906   if (RetI->getOpcode() == Instruction::Mul &&
6907       RetI->user_back()->getOpcode() == Instruction::Add) {
6908     if (!RetI->hasOneUser())
6909       return InstructionCost::getInvalid();
6910     RetI = RetI->user_back();
6911   }
6912 
6913   // Test if the found instruction is a reduction, and if not return an invalid
6914   // cost specifying the parent to use the original cost modelling.
6915   if (!InLoopReductionImmediateChains.count(RetI))
6916     return InstructionCost::getInvalid();
6917 
6918   // Find the reduction this chain is a part of and calculate the basic cost of
6919   // the reduction on its own.
6920   Instruction *LastChain = InLoopReductionImmediateChains[RetI];
6921   Instruction *ReductionPhi = LastChain;
6922   while (!isa<PHINode>(ReductionPhi))
6923     ReductionPhi = InLoopReductionImmediateChains[ReductionPhi];
6924 
6925   RecurrenceDescriptor RdxDesc =
6926       Legal->getReductionVars()[cast<PHINode>(ReductionPhi)];
6927   unsigned BaseCost = TTI.getArithmeticReductionCost(RdxDesc.getOpcode(),
6928                                                      VectorTy, false, CostKind);
6929 
6930   // Get the operand that was not the reduction chain and match it to one of the
6931   // patterns, returning the better cost if it is found.
6932   Instruction *RedOp = RetI->getOperand(1) == LastChain
6933                            ? dyn_cast<Instruction>(RetI->getOperand(0))
6934                            : dyn_cast<Instruction>(RetI->getOperand(1));
6935 
6936   VectorTy = VectorType::get(I->getOperand(0)->getType(), VectorTy);
6937 
6938   if (RedOp && (isa<SExtInst>(RedOp) || isa<ZExtInst>(RedOp)) &&
6939       !TheLoop->isLoopInvariant(RedOp)) {
6940     bool IsUnsigned = isa<ZExtInst>(RedOp);
6941     auto *ExtType = VectorType::get(RedOp->getOperand(0)->getType(), VectorTy);
6942     InstructionCost RedCost = TTI.getExtendedAddReductionCost(
6943         /*IsMLA=*/false, IsUnsigned, RdxDesc.getRecurrenceType(), ExtType,
6944         CostKind);
6945 
6946     unsigned ExtCost =
6947         TTI.getCastInstrCost(RedOp->getOpcode(), VectorTy, ExtType,
6948                              TTI::CastContextHint::None, CostKind, RedOp);
6949     if (RedCost.isValid() && RedCost < BaseCost + ExtCost)
6950       return I == RetI ? *RedCost.getValue() : 0;
6951   } else if (RedOp && RedOp->getOpcode() == Instruction::Mul) {
6952     Instruction *Mul = RedOp;
6953     Instruction *Op0 = dyn_cast<Instruction>(Mul->getOperand(0));
6954     Instruction *Op1 = dyn_cast<Instruction>(Mul->getOperand(1));
6955     if (Op0 && Op1 && (isa<SExtInst>(Op0) || isa<ZExtInst>(Op0)) &&
6956         Op0->getOpcode() == Op1->getOpcode() &&
6957         Op0->getOperand(0)->getType() == Op1->getOperand(0)->getType() &&
6958         !TheLoop->isLoopInvariant(Op0) && !TheLoop->isLoopInvariant(Op1)) {
6959       bool IsUnsigned = isa<ZExtInst>(Op0);
6960       auto *ExtType = VectorType::get(Op0->getOperand(0)->getType(), VectorTy);
6961       // reduce(mul(ext, ext))
6962       unsigned ExtCost =
6963           TTI.getCastInstrCost(Op0->getOpcode(), VectorTy, ExtType,
6964                                TTI::CastContextHint::None, CostKind, Op0);
6965       unsigned MulCost =
6966           TTI.getArithmeticInstrCost(Mul->getOpcode(), VectorTy, CostKind);
6967 
6968       InstructionCost RedCost = TTI.getExtendedAddReductionCost(
6969           /*IsMLA=*/true, IsUnsigned, RdxDesc.getRecurrenceType(), ExtType,
6970           CostKind);
6971 
6972       if (RedCost.isValid() && RedCost < ExtCost * 2 + MulCost + BaseCost)
6973         return I == RetI ? *RedCost.getValue() : 0;
6974     } else {
6975       unsigned MulCost =
6976           TTI.getArithmeticInstrCost(Mul->getOpcode(), VectorTy, CostKind);
6977 
6978       InstructionCost RedCost = TTI.getExtendedAddReductionCost(
6979           /*IsMLA=*/true, true, RdxDesc.getRecurrenceType(), VectorTy,
6980           CostKind);
6981 
6982       if (RedCost.isValid() && RedCost < MulCost + BaseCost)
6983         return I == RetI ? *RedCost.getValue() : 0;
6984     }
6985   }
6986 
6987   return I == RetI ? BaseCost : InstructionCost::getInvalid();
6988 }
6989 
6990 InstructionCost
6991 LoopVectorizationCostModel::getMemoryInstructionCost(Instruction *I,
6992                                                      ElementCount VF) {
6993   // Calculate scalar cost only. Vectorization cost should be ready at this
6994   // moment.
6995   if (VF.isScalar()) {
6996     Type *ValTy = getMemInstValueType(I);
6997     const Align Alignment = getLoadStoreAlignment(I);
6998     unsigned AS = getLoadStoreAddressSpace(I);
6999 
7000     return TTI.getAddressComputationCost(ValTy) +
7001            TTI.getMemoryOpCost(I->getOpcode(), ValTy, Alignment, AS,
7002                                TTI::TCK_RecipThroughput, I);
7003   }
7004   return getWideningCost(I, VF);
7005 }
7006 
7007 LoopVectorizationCostModel::VectorizationCostTy
7008 LoopVectorizationCostModel::getInstructionCost(Instruction *I,
7009                                                ElementCount VF) {
7010   // If we know that this instruction will remain uniform, check the cost of
7011   // the scalar version.
7012   if (isUniformAfterVectorization(I, VF))
7013     VF = ElementCount::getFixed(1);
7014 
7015   if (VF.isVector() && isProfitableToScalarize(I, VF))
7016     return VectorizationCostTy(InstsToScalarize[VF][I], false);
7017 
7018   // Forced scalars do not have any scalarization overhead.
7019   auto ForcedScalar = ForcedScalars.find(VF);
7020   if (VF.isVector() && ForcedScalar != ForcedScalars.end()) {
7021     auto InstSet = ForcedScalar->second;
7022     if (InstSet.count(I))
7023       return VectorizationCostTy(
7024           (getInstructionCost(I, ElementCount::getFixed(1)).first *
7025            VF.getKnownMinValue()),
7026           false);
7027   }
7028 
7029   Type *VectorTy;
7030   InstructionCost C = getInstructionCost(I, VF, VectorTy);
7031 
7032   bool TypeNotScalarized =
7033       VF.isVector() && VectorTy->isVectorTy() &&
7034       TTI.getNumberOfParts(VectorTy) < VF.getKnownMinValue();
7035   return VectorizationCostTy(C, TypeNotScalarized);
7036 }
7037 
7038 InstructionCost
7039 LoopVectorizationCostModel::getScalarizationOverhead(Instruction *I,
7040                                                      ElementCount VF) {
7041 
7042   if (VF.isScalable())
7043     return InstructionCost::getInvalid();
7044 
7045   if (VF.isScalar())
7046     return 0;
7047 
7048   InstructionCost Cost = 0;
7049   Type *RetTy = ToVectorTy(I->getType(), VF);
7050   if (!RetTy->isVoidTy() &&
7051       (!isa<LoadInst>(I) || !TTI.supportsEfficientVectorElementLoadStore()))
7052     Cost += TTI.getScalarizationOverhead(
7053         cast<VectorType>(RetTy), APInt::getAllOnesValue(VF.getKnownMinValue()),
7054         true, false);
7055 
7056   // Some targets keep addresses scalar.
7057   if (isa<LoadInst>(I) && !TTI.prefersVectorizedAddressing())
7058     return Cost;
7059 
7060   // Some targets support efficient element stores.
7061   if (isa<StoreInst>(I) && TTI.supportsEfficientVectorElementLoadStore())
7062     return Cost;
7063 
7064   // Collect operands to consider.
7065   CallInst *CI = dyn_cast<CallInst>(I);
7066   Instruction::op_range Ops = CI ? CI->arg_operands() : I->operands();
7067 
7068   // Skip operands that do not require extraction/scalarization and do not incur
7069   // any overhead.
7070   return Cost + TTI.getOperandsScalarizationOverhead(
7071                     filterExtractingOperands(Ops, VF), VF.getKnownMinValue());
7072 }
7073 
7074 void LoopVectorizationCostModel::setCostBasedWideningDecision(ElementCount VF) {
7075   if (VF.isScalar())
7076     return;
7077   NumPredStores = 0;
7078   for (BasicBlock *BB : TheLoop->blocks()) {
7079     // For each instruction in the old loop.
7080     for (Instruction &I : *BB) {
7081       Value *Ptr =  getLoadStorePointerOperand(&I);
7082       if (!Ptr)
7083         continue;
7084 
7085       // TODO: We should generate better code and update the cost model for
7086       // predicated uniform stores. Today they are treated as any other
7087       // predicated store (see added test cases in
7088       // invariant-store-vectorization.ll).
7089       if (isa<StoreInst>(&I) && isScalarWithPredication(&I))
7090         NumPredStores++;
7091 
7092       if (Legal->isUniformMemOp(I)) {
7093         // TODO: Avoid replicating loads and stores instead of
7094         // relying on instcombine to remove them.
7095         // Load: Scalar load + broadcast
7096         // Store: Scalar store + isLoopInvariantStoreValue ? 0 : extract
7097         InstructionCost Cost = getUniformMemOpCost(&I, VF);
7098         setWideningDecision(&I, VF, CM_Scalarize, Cost);
7099         continue;
7100       }
7101 
7102       // We assume that widening is the best solution when possible.
7103       if (memoryInstructionCanBeWidened(&I, VF)) {
7104         InstructionCost Cost = getConsecutiveMemOpCost(&I, VF);
7105         int ConsecutiveStride =
7106                Legal->isConsecutivePtr(getLoadStorePointerOperand(&I));
7107         assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
7108                "Expected consecutive stride.");
7109         InstWidening Decision =
7110             ConsecutiveStride == 1 ? CM_Widen : CM_Widen_Reverse;
7111         setWideningDecision(&I, VF, Decision, Cost);
7112         continue;
7113       }
7114 
7115       // Choose between Interleaving, Gather/Scatter or Scalarization.
7116       InstructionCost InterleaveCost = InstructionCost::getInvalid();
7117       unsigned NumAccesses = 1;
7118       if (isAccessInterleaved(&I)) {
7119         auto Group = getInterleavedAccessGroup(&I);
7120         assert(Group && "Fail to get an interleaved access group.");
7121 
7122         // Make one decision for the whole group.
7123         if (getWideningDecision(&I, VF) != CM_Unknown)
7124           continue;
7125 
7126         NumAccesses = Group->getNumMembers();
7127         if (interleavedAccessCanBeWidened(&I, VF))
7128           InterleaveCost = getInterleaveGroupCost(&I, VF);
7129       }
7130 
7131       InstructionCost GatherScatterCost =
7132           isLegalGatherOrScatter(&I)
7133               ? getGatherScatterCost(&I, VF) * NumAccesses
7134               : InstructionCost::getInvalid();
7135 
7136       InstructionCost ScalarizationCost =
7137           !VF.isScalable() ? getMemInstScalarizationCost(&I, VF) * NumAccesses
7138                            : InstructionCost::getInvalid();
7139 
7140       // Choose better solution for the current VF,
7141       // write down this decision and use it during vectorization.
7142       InstructionCost Cost;
7143       InstWidening Decision;
7144       if (InterleaveCost <= GatherScatterCost &&
7145           InterleaveCost < ScalarizationCost) {
7146         Decision = CM_Interleave;
7147         Cost = InterleaveCost;
7148       } else if (GatherScatterCost < ScalarizationCost) {
7149         Decision = CM_GatherScatter;
7150         Cost = GatherScatterCost;
7151       } else {
7152         assert(!VF.isScalable() &&
7153                "We cannot yet scalarise for scalable vectors");
7154         Decision = CM_Scalarize;
7155         Cost = ScalarizationCost;
7156       }
7157       // If the instructions belongs to an interleave group, the whole group
7158       // receives the same decision. The whole group receives the cost, but
7159       // the cost will actually be assigned to one instruction.
7160       if (auto Group = getInterleavedAccessGroup(&I))
7161         setWideningDecision(Group, VF, Decision, Cost);
7162       else
7163         setWideningDecision(&I, VF, Decision, Cost);
7164     }
7165   }
7166 
7167   // Make sure that any load of address and any other address computation
7168   // remains scalar unless there is gather/scatter support. This avoids
7169   // inevitable extracts into address registers, and also has the benefit of
7170   // activating LSR more, since that pass can't optimize vectorized
7171   // addresses.
7172   if (TTI.prefersVectorizedAddressing())
7173     return;
7174 
7175   // Start with all scalar pointer uses.
7176   SmallPtrSet<Instruction *, 8> AddrDefs;
7177   for (BasicBlock *BB : TheLoop->blocks())
7178     for (Instruction &I : *BB) {
7179       Instruction *PtrDef =
7180         dyn_cast_or_null<Instruction>(getLoadStorePointerOperand(&I));
7181       if (PtrDef && TheLoop->contains(PtrDef) &&
7182           getWideningDecision(&I, VF) != CM_GatherScatter)
7183         AddrDefs.insert(PtrDef);
7184     }
7185 
7186   // Add all instructions used to generate the addresses.
7187   SmallVector<Instruction *, 4> Worklist;
7188   append_range(Worklist, AddrDefs);
7189   while (!Worklist.empty()) {
7190     Instruction *I = Worklist.pop_back_val();
7191     for (auto &Op : I->operands())
7192       if (auto *InstOp = dyn_cast<Instruction>(Op))
7193         if ((InstOp->getParent() == I->getParent()) && !isa<PHINode>(InstOp) &&
7194             AddrDefs.insert(InstOp).second)
7195           Worklist.push_back(InstOp);
7196   }
7197 
7198   for (auto *I : AddrDefs) {
7199     if (isa<LoadInst>(I)) {
7200       // Setting the desired widening decision should ideally be handled in
7201       // by cost functions, but since this involves the task of finding out
7202       // if the loaded register is involved in an address computation, it is
7203       // instead changed here when we know this is the case.
7204       InstWidening Decision = getWideningDecision(I, VF);
7205       if (Decision == CM_Widen || Decision == CM_Widen_Reverse)
7206         // Scalarize a widened load of address.
7207         setWideningDecision(
7208             I, VF, CM_Scalarize,
7209             (VF.getKnownMinValue() *
7210              getMemoryInstructionCost(I, ElementCount::getFixed(1))));
7211       else if (auto Group = getInterleavedAccessGroup(I)) {
7212         // Scalarize an interleave group of address loads.
7213         for (unsigned I = 0; I < Group->getFactor(); ++I) {
7214           if (Instruction *Member = Group->getMember(I))
7215             setWideningDecision(
7216                 Member, VF, CM_Scalarize,
7217                 (VF.getKnownMinValue() *
7218                  getMemoryInstructionCost(Member, ElementCount::getFixed(1))));
7219         }
7220       }
7221     } else
7222       // Make sure I gets scalarized and a cost estimate without
7223       // scalarization overhead.
7224       ForcedScalars[VF].insert(I);
7225   }
7226 }
7227 
7228 InstructionCost
7229 LoopVectorizationCostModel::getInstructionCost(Instruction *I, ElementCount VF,
7230                                                Type *&VectorTy) {
7231   Type *RetTy = I->getType();
7232   if (canTruncateToMinimalBitwidth(I, VF))
7233     RetTy = IntegerType::get(RetTy->getContext(), MinBWs[I]);
7234   VectorTy = isScalarAfterVectorization(I, VF) ? RetTy : ToVectorTy(RetTy, VF);
7235   auto SE = PSE.getSE();
7236   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
7237 
7238   // TODO: We need to estimate the cost of intrinsic calls.
7239   switch (I->getOpcode()) {
7240   case Instruction::GetElementPtr:
7241     // We mark this instruction as zero-cost because the cost of GEPs in
7242     // vectorized code depends on whether the corresponding memory instruction
7243     // is scalarized or not. Therefore, we handle GEPs with the memory
7244     // instruction cost.
7245     return 0;
7246   case Instruction::Br: {
7247     // In cases of scalarized and predicated instructions, there will be VF
7248     // predicated blocks in the vectorized loop. Each branch around these
7249     // blocks requires also an extract of its vector compare i1 element.
7250     bool ScalarPredicatedBB = false;
7251     BranchInst *BI = cast<BranchInst>(I);
7252     if (VF.isVector() && BI->isConditional() &&
7253         (PredicatedBBsAfterVectorization.count(BI->getSuccessor(0)) ||
7254          PredicatedBBsAfterVectorization.count(BI->getSuccessor(1))))
7255       ScalarPredicatedBB = true;
7256 
7257     if (ScalarPredicatedBB) {
7258       // Return cost for branches around scalarized and predicated blocks.
7259       assert(!VF.isScalable() && "scalable vectors not yet supported.");
7260       auto *Vec_i1Ty =
7261           VectorType::get(IntegerType::getInt1Ty(RetTy->getContext()), VF);
7262       return (TTI.getScalarizationOverhead(
7263                   Vec_i1Ty, APInt::getAllOnesValue(VF.getKnownMinValue()),
7264                   false, true) +
7265               (TTI.getCFInstrCost(Instruction::Br, CostKind) *
7266                VF.getKnownMinValue()));
7267     } else if (I->getParent() == TheLoop->getLoopLatch() || VF.isScalar())
7268       // The back-edge branch will remain, as will all scalar branches.
7269       return TTI.getCFInstrCost(Instruction::Br, CostKind);
7270     else
7271       // This branch will be eliminated by if-conversion.
7272       return 0;
7273     // Note: We currently assume zero cost for an unconditional branch inside
7274     // a predicated block since it will become a fall-through, although we
7275     // may decide in the future to call TTI for all branches.
7276   }
7277   case Instruction::PHI: {
7278     auto *Phi = cast<PHINode>(I);
7279 
7280     // First-order recurrences are replaced by vector shuffles inside the loop.
7281     // NOTE: Don't use ToVectorTy as SK_ExtractSubvector expects a vector type.
7282     if (VF.isVector() && Legal->isFirstOrderRecurrence(Phi))
7283       return TTI.getShuffleCost(
7284           TargetTransformInfo::SK_ExtractSubvector, cast<VectorType>(VectorTy),
7285           VF.getKnownMinValue() - 1, FixedVectorType::get(RetTy, 1));
7286 
7287     // Phi nodes in non-header blocks (not inductions, reductions, etc.) are
7288     // converted into select instructions. We require N - 1 selects per phi
7289     // node, where N is the number of incoming values.
7290     if (VF.isVector() && Phi->getParent() != TheLoop->getHeader())
7291       return (Phi->getNumIncomingValues() - 1) *
7292              TTI.getCmpSelInstrCost(
7293                  Instruction::Select, ToVectorTy(Phi->getType(), VF),
7294                  ToVectorTy(Type::getInt1Ty(Phi->getContext()), VF),
7295                  CmpInst::BAD_ICMP_PREDICATE, CostKind);
7296 
7297     return TTI.getCFInstrCost(Instruction::PHI, CostKind);
7298   }
7299   case Instruction::UDiv:
7300   case Instruction::SDiv:
7301   case Instruction::URem:
7302   case Instruction::SRem:
7303     // If we have a predicated instruction, it may not be executed for each
7304     // vector lane. Get the scalarization cost and scale this amount by the
7305     // probability of executing the predicated block. If the instruction is not
7306     // predicated, we fall through to the next case.
7307     if (VF.isVector() && isScalarWithPredication(I)) {
7308       InstructionCost Cost = 0;
7309 
7310       // These instructions have a non-void type, so account for the phi nodes
7311       // that we will create. This cost is likely to be zero. The phi node
7312       // cost, if any, should be scaled by the block probability because it
7313       // models a copy at the end of each predicated block.
7314       Cost += VF.getKnownMinValue() *
7315               TTI.getCFInstrCost(Instruction::PHI, CostKind);
7316 
7317       // The cost of the non-predicated instruction.
7318       Cost += VF.getKnownMinValue() *
7319               TTI.getArithmeticInstrCost(I->getOpcode(), RetTy, CostKind);
7320 
7321       // The cost of insertelement and extractelement instructions needed for
7322       // scalarization.
7323       Cost += getScalarizationOverhead(I, VF);
7324 
7325       // Scale the cost by the probability of executing the predicated blocks.
7326       // This assumes the predicated block for each vector lane is equally
7327       // likely.
7328       return Cost / getReciprocalPredBlockProb();
7329     }
7330     LLVM_FALLTHROUGH;
7331   case Instruction::Add:
7332   case Instruction::FAdd:
7333   case Instruction::Sub:
7334   case Instruction::FSub:
7335   case Instruction::Mul:
7336   case Instruction::FMul:
7337   case Instruction::FDiv:
7338   case Instruction::FRem:
7339   case Instruction::Shl:
7340   case Instruction::LShr:
7341   case Instruction::AShr:
7342   case Instruction::And:
7343   case Instruction::Or:
7344   case Instruction::Xor: {
7345     // Since we will replace the stride by 1 the multiplication should go away.
7346     if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
7347       return 0;
7348 
7349     // Detect reduction patterns
7350     InstructionCost RedCost;
7351     if ((RedCost = getReductionPatternCost(I, VF, VectorTy, CostKind))
7352             .isValid())
7353       return RedCost;
7354 
7355     // Certain instructions can be cheaper to vectorize if they have a constant
7356     // second vector operand. One example of this are shifts on x86.
7357     Value *Op2 = I->getOperand(1);
7358     TargetTransformInfo::OperandValueProperties Op2VP;
7359     TargetTransformInfo::OperandValueKind Op2VK =
7360         TTI.getOperandInfo(Op2, Op2VP);
7361     if (Op2VK == TargetTransformInfo::OK_AnyValue && Legal->isUniform(Op2))
7362       Op2VK = TargetTransformInfo::OK_UniformValue;
7363 
7364     SmallVector<const Value *, 4> Operands(I->operand_values());
7365     unsigned N = isScalarAfterVectorization(I, VF) ? VF.getKnownMinValue() : 1;
7366     return N * TTI.getArithmeticInstrCost(
7367                    I->getOpcode(), VectorTy, CostKind,
7368                    TargetTransformInfo::OK_AnyValue,
7369                    Op2VK, TargetTransformInfo::OP_None, Op2VP, Operands, I);
7370   }
7371   case Instruction::FNeg: {
7372     assert(!VF.isScalable() && "VF is assumed to be non scalable.");
7373     unsigned N = isScalarAfterVectorization(I, VF) ? VF.getKnownMinValue() : 1;
7374     return N * TTI.getArithmeticInstrCost(
7375                    I->getOpcode(), VectorTy, CostKind,
7376                    TargetTransformInfo::OK_AnyValue,
7377                    TargetTransformInfo::OK_AnyValue,
7378                    TargetTransformInfo::OP_None, TargetTransformInfo::OP_None,
7379                    I->getOperand(0), I);
7380   }
7381   case Instruction::Select: {
7382     SelectInst *SI = cast<SelectInst>(I);
7383     const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
7384     bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
7385     Type *CondTy = SI->getCondition()->getType();
7386     if (!ScalarCond)
7387       CondTy = VectorType::get(CondTy, VF);
7388     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy,
7389                                   CmpInst::BAD_ICMP_PREDICATE, CostKind, I);
7390   }
7391   case Instruction::ICmp:
7392   case Instruction::FCmp: {
7393     Type *ValTy = I->getOperand(0)->getType();
7394     Instruction *Op0AsInstruction = dyn_cast<Instruction>(I->getOperand(0));
7395     if (canTruncateToMinimalBitwidth(Op0AsInstruction, VF))
7396       ValTy = IntegerType::get(ValTy->getContext(), MinBWs[Op0AsInstruction]);
7397     VectorTy = ToVectorTy(ValTy, VF);
7398     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, nullptr,
7399                                   CmpInst::BAD_ICMP_PREDICATE, CostKind, I);
7400   }
7401   case Instruction::Store:
7402   case Instruction::Load: {
7403     ElementCount Width = VF;
7404     if (Width.isVector()) {
7405       InstWidening Decision = getWideningDecision(I, Width);
7406       assert(Decision != CM_Unknown &&
7407              "CM decision should be taken at this point");
7408       if (Decision == CM_Scalarize)
7409         Width = ElementCount::getFixed(1);
7410     }
7411     VectorTy = ToVectorTy(getMemInstValueType(I), Width);
7412     return getMemoryInstructionCost(I, VF);
7413   }
7414   case Instruction::ZExt:
7415   case Instruction::SExt:
7416   case Instruction::FPToUI:
7417   case Instruction::FPToSI:
7418   case Instruction::FPExt:
7419   case Instruction::PtrToInt:
7420   case Instruction::IntToPtr:
7421   case Instruction::SIToFP:
7422   case Instruction::UIToFP:
7423   case Instruction::Trunc:
7424   case Instruction::FPTrunc:
7425   case Instruction::BitCast: {
7426     // Computes the CastContextHint from a Load/Store instruction.
7427     auto ComputeCCH = [&](Instruction *I) -> TTI::CastContextHint {
7428       assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
7429              "Expected a load or a store!");
7430 
7431       if (VF.isScalar() || !TheLoop->contains(I))
7432         return TTI::CastContextHint::Normal;
7433 
7434       switch (getWideningDecision(I, VF)) {
7435       case LoopVectorizationCostModel::CM_GatherScatter:
7436         return TTI::CastContextHint::GatherScatter;
7437       case LoopVectorizationCostModel::CM_Interleave:
7438         return TTI::CastContextHint::Interleave;
7439       case LoopVectorizationCostModel::CM_Scalarize:
7440       case LoopVectorizationCostModel::CM_Widen:
7441         return Legal->isMaskRequired(I) ? TTI::CastContextHint::Masked
7442                                         : TTI::CastContextHint::Normal;
7443       case LoopVectorizationCostModel::CM_Widen_Reverse:
7444         return TTI::CastContextHint::Reversed;
7445       case LoopVectorizationCostModel::CM_Unknown:
7446         llvm_unreachable("Instr did not go through cost modelling?");
7447       }
7448 
7449       llvm_unreachable("Unhandled case!");
7450     };
7451 
7452     unsigned Opcode = I->getOpcode();
7453     TTI::CastContextHint CCH = TTI::CastContextHint::None;
7454     // For Trunc, the context is the only user, which must be a StoreInst.
7455     if (Opcode == Instruction::Trunc || Opcode == Instruction::FPTrunc) {
7456       if (I->hasOneUse())
7457         if (StoreInst *Store = dyn_cast<StoreInst>(*I->user_begin()))
7458           CCH = ComputeCCH(Store);
7459     }
7460     // For Z/Sext, the context is the operand, which must be a LoadInst.
7461     else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt ||
7462              Opcode == Instruction::FPExt) {
7463       if (LoadInst *Load = dyn_cast<LoadInst>(I->getOperand(0)))
7464         CCH = ComputeCCH(Load);
7465     }
7466 
7467     // We optimize the truncation of induction variables having constant
7468     // integer steps. The cost of these truncations is the same as the scalar
7469     // operation.
7470     if (isOptimizableIVTruncate(I, VF)) {
7471       auto *Trunc = cast<TruncInst>(I);
7472       return TTI.getCastInstrCost(Instruction::Trunc, Trunc->getDestTy(),
7473                                   Trunc->getSrcTy(), CCH, CostKind, Trunc);
7474     }
7475 
7476     // Detect reduction patterns
7477     InstructionCost RedCost;
7478     if ((RedCost = getReductionPatternCost(I, VF, VectorTy, CostKind))
7479             .isValid())
7480       return RedCost;
7481 
7482     Type *SrcScalarTy = I->getOperand(0)->getType();
7483     Type *SrcVecTy =
7484         VectorTy->isVectorTy() ? ToVectorTy(SrcScalarTy, VF) : SrcScalarTy;
7485     if (canTruncateToMinimalBitwidth(I, VF)) {
7486       // This cast is going to be shrunk. This may remove the cast or it might
7487       // turn it into slightly different cast. For example, if MinBW == 16,
7488       // "zext i8 %1 to i32" becomes "zext i8 %1 to i16".
7489       //
7490       // Calculate the modified src and dest types.
7491       Type *MinVecTy = VectorTy;
7492       if (Opcode == Instruction::Trunc) {
7493         SrcVecTy = smallestIntegerVectorType(SrcVecTy, MinVecTy);
7494         VectorTy =
7495             largestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy);
7496       } else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
7497         SrcVecTy = largestIntegerVectorType(SrcVecTy, MinVecTy);
7498         VectorTy =
7499             smallestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy);
7500       }
7501     }
7502 
7503     unsigned N;
7504     if (isScalarAfterVectorization(I, VF)) {
7505       assert(!VF.isScalable() && "VF is assumed to be non scalable");
7506       N = VF.getKnownMinValue();
7507     } else
7508       N = 1;
7509     return N *
7510            TTI.getCastInstrCost(Opcode, VectorTy, SrcVecTy, CCH, CostKind, I);
7511   }
7512   case Instruction::Call: {
7513     bool NeedToScalarize;
7514     CallInst *CI = cast<CallInst>(I);
7515     InstructionCost CallCost = getVectorCallCost(CI, VF, NeedToScalarize);
7516     if (getVectorIntrinsicIDForCall(CI, TLI)) {
7517       InstructionCost IntrinsicCost = getVectorIntrinsicCost(CI, VF);
7518       return std::min(CallCost, IntrinsicCost);
7519     }
7520     return CallCost;
7521   }
7522   case Instruction::ExtractValue:
7523     return TTI.getInstructionCost(I, TTI::TCK_RecipThroughput);
7524   default:
7525     // The cost of executing VF copies of the scalar instruction. This opcode
7526     // is unknown. Assume that it is the same as 'mul'.
7527     return VF.getKnownMinValue() * TTI.getArithmeticInstrCost(
7528                                        Instruction::Mul, VectorTy, CostKind) +
7529            getScalarizationOverhead(I, VF);
7530   } // end of switch.
7531 }
7532 
7533 char LoopVectorize::ID = 0;
7534 
7535 static const char lv_name[] = "Loop Vectorization";
7536 
7537 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
7538 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
7539 INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
7540 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
7541 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
7542 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
7543 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
7544 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
7545 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
7546 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
7547 INITIALIZE_PASS_DEPENDENCY(LoopAccessLegacyAnalysis)
7548 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
7549 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
7550 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
7551 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
7552 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
7553 
7554 namespace llvm {
7555 
7556 Pass *createLoopVectorizePass() { return new LoopVectorize(); }
7557 
7558 Pass *createLoopVectorizePass(bool InterleaveOnlyWhenForced,
7559                               bool VectorizeOnlyWhenForced) {
7560   return new LoopVectorize(InterleaveOnlyWhenForced, VectorizeOnlyWhenForced);
7561 }
7562 
7563 } // end namespace llvm
7564 
7565 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
7566   // Check if the pointer operand of a load or store instruction is
7567   // consecutive.
7568   if (auto *Ptr = getLoadStorePointerOperand(Inst))
7569     return Legal->isConsecutivePtr(Ptr);
7570   return false;
7571 }
7572 
7573 void LoopVectorizationCostModel::collectValuesToIgnore() {
7574   // Ignore ephemeral values.
7575   CodeMetrics::collectEphemeralValues(TheLoop, AC, ValuesToIgnore);
7576 
7577   // Ignore type-promoting instructions we identified during reduction
7578   // detection.
7579   for (auto &Reduction : Legal->getReductionVars()) {
7580     RecurrenceDescriptor &RedDes = Reduction.second;
7581     const SmallPtrSetImpl<Instruction *> &Casts = RedDes.getCastInsts();
7582     VecValuesToIgnore.insert(Casts.begin(), Casts.end());
7583   }
7584   // Ignore type-casting instructions we identified during induction
7585   // detection.
7586   for (auto &Induction : Legal->getInductionVars()) {
7587     InductionDescriptor &IndDes = Induction.second;
7588     const SmallVectorImpl<Instruction *> &Casts = IndDes.getCastInsts();
7589     VecValuesToIgnore.insert(Casts.begin(), Casts.end());
7590   }
7591 }
7592 
7593 void LoopVectorizationCostModel::collectInLoopReductions() {
7594   for (auto &Reduction : Legal->getReductionVars()) {
7595     PHINode *Phi = Reduction.first;
7596     RecurrenceDescriptor &RdxDesc = Reduction.second;
7597 
7598     // We don't collect reductions that are type promoted (yet).
7599     if (RdxDesc.getRecurrenceType() != Phi->getType())
7600       continue;
7601 
7602     // If the target would prefer this reduction to happen "in-loop", then we
7603     // want to record it as such.
7604     unsigned Opcode = RdxDesc.getOpcode();
7605     if (!PreferInLoopReductions &&
7606         !TTI.preferInLoopReduction(Opcode, Phi->getType(),
7607                                    TargetTransformInfo::ReductionFlags()))
7608       continue;
7609 
7610     // Check that we can correctly put the reductions into the loop, by
7611     // finding the chain of operations that leads from the phi to the loop
7612     // exit value.
7613     SmallVector<Instruction *, 4> ReductionOperations =
7614         RdxDesc.getReductionOpChain(Phi, TheLoop);
7615     bool InLoop = !ReductionOperations.empty();
7616     if (InLoop) {
7617       InLoopReductionChains[Phi] = ReductionOperations;
7618       // Add the elements to InLoopReductionImmediateChains for cost modelling.
7619       Instruction *LastChain = Phi;
7620       for (auto *I : ReductionOperations) {
7621         InLoopReductionImmediateChains[I] = LastChain;
7622         LastChain = I;
7623       }
7624     }
7625     LLVM_DEBUG(dbgs() << "LV: Using " << (InLoop ? "inloop" : "out of loop")
7626                       << " reduction for phi: " << *Phi << "\n");
7627   }
7628 }
7629 
7630 // TODO: we could return a pair of values that specify the max VF and
7631 // min VF, to be used in `buildVPlans(MinVF, MaxVF)` instead of
7632 // `buildVPlans(VF, VF)`. We cannot do it because VPLAN at the moment
7633 // doesn't have a cost model that can choose which plan to execute if
7634 // more than one is generated.
7635 static unsigned determineVPlanVF(const unsigned WidestVectorRegBits,
7636                                  LoopVectorizationCostModel &CM) {
7637   unsigned WidestType;
7638   std::tie(std::ignore, WidestType) = CM.getSmallestAndWidestTypes();
7639   return WidestVectorRegBits / WidestType;
7640 }
7641 
7642 VectorizationFactor
7643 LoopVectorizationPlanner::planInVPlanNativePath(ElementCount UserVF) {
7644   assert(!UserVF.isScalable() && "scalable vectors not yet supported");
7645   ElementCount VF = UserVF;
7646   // Outer loop handling: They may require CFG and instruction level
7647   // transformations before even evaluating whether vectorization is profitable.
7648   // Since we cannot modify the incoming IR, we need to build VPlan upfront in
7649   // the vectorization pipeline.
7650   if (!OrigLoop->isInnermost()) {
7651     // If the user doesn't provide a vectorization factor, determine a
7652     // reasonable one.
7653     if (UserVF.isZero()) {
7654       VF = ElementCount::getFixed(
7655           determineVPlanVF(TTI->getRegisterBitWidth(true /* Vector*/), CM));
7656       LLVM_DEBUG(dbgs() << "LV: VPlan computed VF " << VF << ".\n");
7657 
7658       // Make sure we have a VF > 1 for stress testing.
7659       if (VPlanBuildStressTest && (VF.isScalar() || VF.isZero())) {
7660         LLVM_DEBUG(dbgs() << "LV: VPlan stress testing: "
7661                           << "overriding computed VF.\n");
7662         VF = ElementCount::getFixed(4);
7663       }
7664     }
7665     assert(EnableVPlanNativePath && "VPlan-native path is not enabled.");
7666     assert(isPowerOf2_32(VF.getKnownMinValue()) &&
7667            "VF needs to be a power of two");
7668     LLVM_DEBUG(dbgs() << "LV: Using " << (!UserVF.isZero() ? "user " : "")
7669                       << "VF " << VF << " to build VPlans.\n");
7670     buildVPlans(VF, VF);
7671 
7672     // For VPlan build stress testing, we bail out after VPlan construction.
7673     if (VPlanBuildStressTest)
7674       return VectorizationFactor::Disabled();
7675 
7676     return {VF, 0 /*Cost*/};
7677   }
7678 
7679   LLVM_DEBUG(
7680       dbgs() << "LV: Not vectorizing. Inner loops aren't supported in the "
7681                 "VPlan-native path.\n");
7682   return VectorizationFactor::Disabled();
7683 }
7684 
7685 Optional<VectorizationFactor>
7686 LoopVectorizationPlanner::plan(ElementCount UserVF, unsigned UserIC) {
7687   assert(OrigLoop->isInnermost() && "Inner loop expected.");
7688   Optional<ElementCount> MaybeMaxVF = CM.computeMaxVF(UserVF, UserIC);
7689   if (!MaybeMaxVF) // Cases that should not to be vectorized nor interleaved.
7690     return None;
7691 
7692   // Invalidate interleave groups if all blocks of loop will be predicated.
7693   if (CM.blockNeedsPredication(OrigLoop->getHeader()) &&
7694       !useMaskedInterleavedAccesses(*TTI)) {
7695     LLVM_DEBUG(
7696         dbgs()
7697         << "LV: Invalidate all interleaved groups due to fold-tail by masking "
7698            "which requires masked-interleaved support.\n");
7699     if (CM.InterleaveInfo.invalidateGroups())
7700       // Invalidating interleave groups also requires invalidating all decisions
7701       // based on them, which includes widening decisions and uniform and scalar
7702       // values.
7703       CM.invalidateCostModelingDecisions();
7704   }
7705 
7706   ElementCount MaxVF = MaybeMaxVF.getValue();
7707   assert(MaxVF.isNonZero() && "MaxVF is zero.");
7708 
7709   bool UserVFIsLegal = ElementCount::isKnownLE(UserVF, MaxVF);
7710   if (!UserVF.isZero() &&
7711       (UserVFIsLegal || (UserVF.isScalable() && MaxVF.isScalable()))) {
7712     // FIXME: MaxVF is temporarily used inplace of UserVF for illegal scalable
7713     // VFs here, this should be reverted to only use legal UserVFs once the
7714     // loop below supports scalable VFs.
7715     ElementCount VF = UserVFIsLegal ? UserVF : MaxVF;
7716     LLVM_DEBUG(dbgs() << "LV: Using " << (UserVFIsLegal ? "user" : "max")
7717                       << " VF " << VF << ".\n");
7718     assert(isPowerOf2_32(VF.getKnownMinValue()) &&
7719            "VF needs to be a power of two");
7720     // Collect the instructions (and their associated costs) that will be more
7721     // profitable to scalarize.
7722     CM.selectUserVectorizationFactor(VF);
7723     CM.collectInLoopReductions();
7724     buildVPlansWithVPRecipes(VF, VF);
7725     LLVM_DEBUG(printPlans(dbgs()));
7726     return {{VF, 0}};
7727   }
7728 
7729   assert(!MaxVF.isScalable() &&
7730          "Scalable vectors not yet supported beyond this point");
7731 
7732   for (ElementCount VF = ElementCount::getFixed(1);
7733        ElementCount::isKnownLE(VF, MaxVF); VF *= 2) {
7734     // Collect Uniform and Scalar instructions after vectorization with VF.
7735     CM.collectUniformsAndScalars(VF);
7736 
7737     // Collect the instructions (and their associated costs) that will be more
7738     // profitable to scalarize.
7739     if (VF.isVector())
7740       CM.collectInstsToScalarize(VF);
7741   }
7742 
7743   CM.collectInLoopReductions();
7744 
7745   buildVPlansWithVPRecipes(ElementCount::getFixed(1), MaxVF);
7746   LLVM_DEBUG(printPlans(dbgs()));
7747   if (MaxVF.isScalar())
7748     return VectorizationFactor::Disabled();
7749 
7750   // Select the optimal vectorization factor.
7751   return CM.selectVectorizationFactor(MaxVF);
7752 }
7753 
7754 void LoopVectorizationPlanner::setBestPlan(ElementCount VF, unsigned UF) {
7755   LLVM_DEBUG(dbgs() << "Setting best plan to VF=" << VF << ", UF=" << UF
7756                     << '\n');
7757   BestVF = VF;
7758   BestUF = UF;
7759 
7760   erase_if(VPlans, [VF](const VPlanPtr &Plan) {
7761     return !Plan->hasVF(VF);
7762   });
7763   assert(VPlans.size() == 1 && "Best VF has not a single VPlan.");
7764 }
7765 
7766 void LoopVectorizationPlanner::executePlan(InnerLoopVectorizer &ILV,
7767                                            DominatorTree *DT) {
7768   // Perform the actual loop transformation.
7769 
7770   // 1. Create a new empty loop. Unlink the old loop and connect the new one.
7771   VPCallbackILV CallbackILV(ILV);
7772 
7773   assert(BestVF.hasValue() && "Vectorization Factor is missing");
7774   assert(VPlans.size() == 1 && "Not a single VPlan to execute.");
7775 
7776   VPTransformState State{*BestVF,     BestUF,
7777                          LI,          DT,
7778                          ILV.Builder, ILV.VectorLoopValueMap,
7779                          &ILV,        VPlans.front().get(),
7780                          CallbackILV};
7781   State.CFG.PrevBB = ILV.createVectorizedLoopSkeleton();
7782   State.TripCount = ILV.getOrCreateTripCount(nullptr);
7783   State.CanonicalIV = ILV.Induction;
7784 
7785   ILV.printDebugTracesAtStart();
7786 
7787   //===------------------------------------------------===//
7788   //
7789   // Notice: any optimization or new instruction that go
7790   // into the code below should also be implemented in
7791   // the cost-model.
7792   //
7793   //===------------------------------------------------===//
7794 
7795   // 2. Copy and widen instructions from the old loop into the new loop.
7796   VPlans.front()->execute(&State);
7797 
7798   // 3. Fix the vectorized code: take care of header phi's, live-outs,
7799   //    predication, updating analyses.
7800   ILV.fixVectorizedLoop(State);
7801 
7802   ILV.printDebugTracesAtEnd();
7803 }
7804 
7805 void LoopVectorizationPlanner::collectTriviallyDeadInstructions(
7806     SmallPtrSetImpl<Instruction *> &DeadInstructions) {
7807 
7808   // We create new control-flow for the vectorized loop, so the original exit
7809   // conditions will be dead after vectorization if it's only used by the
7810   // terminator
7811   SmallVector<BasicBlock*> ExitingBlocks;
7812   OrigLoop->getExitingBlocks(ExitingBlocks);
7813   for (auto *BB : ExitingBlocks) {
7814     auto *Cmp = dyn_cast<Instruction>(BB->getTerminator()->getOperand(0));
7815     if (!Cmp || !Cmp->hasOneUse())
7816       continue;
7817 
7818     // TODO: we should introduce a getUniqueExitingBlocks on Loop
7819     if (!DeadInstructions.insert(Cmp).second)
7820       continue;
7821 
7822     // The operands of the icmp is often a dead trunc, used by IndUpdate.
7823     // TODO: can recurse through operands in general
7824     for (Value *Op : Cmp->operands()) {
7825       if (isa<TruncInst>(Op) && Op->hasOneUse())
7826           DeadInstructions.insert(cast<Instruction>(Op));
7827     }
7828   }
7829 
7830   // We create new "steps" for induction variable updates to which the original
7831   // induction variables map. An original update instruction will be dead if
7832   // all its users except the induction variable are dead.
7833   auto *Latch = OrigLoop->getLoopLatch();
7834   for (auto &Induction : Legal->getInductionVars()) {
7835     PHINode *Ind = Induction.first;
7836     auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
7837 
7838     // If the tail is to be folded by masking, the primary induction variable,
7839     // if exists, isn't dead: it will be used for masking. Don't kill it.
7840     if (CM.foldTailByMasking() && IndUpdate == Legal->getPrimaryInduction())
7841       continue;
7842 
7843     if (llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
7844           return U == Ind || DeadInstructions.count(cast<Instruction>(U));
7845         }))
7846       DeadInstructions.insert(IndUpdate);
7847 
7848     // We record as "Dead" also the type-casting instructions we had identified
7849     // during induction analysis. We don't need any handling for them in the
7850     // vectorized loop because we have proven that, under a proper runtime
7851     // test guarding the vectorized loop, the value of the phi, and the casted
7852     // value of the phi, are the same. The last instruction in this casting chain
7853     // will get its scalar/vector/widened def from the scalar/vector/widened def
7854     // of the respective phi node. Any other casts in the induction def-use chain
7855     // have no other uses outside the phi update chain, and will be ignored.
7856     InductionDescriptor &IndDes = Induction.second;
7857     const SmallVectorImpl<Instruction *> &Casts = IndDes.getCastInsts();
7858     DeadInstructions.insert(Casts.begin(), Casts.end());
7859   }
7860 }
7861 
7862 Value *InnerLoopUnroller::reverseVector(Value *Vec) { return Vec; }
7863 
7864 Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) { return V; }
7865 
7866 Value *InnerLoopUnroller::getStepVector(Value *Val, int StartIdx, Value *Step,
7867                                         Instruction::BinaryOps BinOp) {
7868   // When unrolling and the VF is 1, we only need to add a simple scalar.
7869   Type *Ty = Val->getType();
7870   assert(!Ty->isVectorTy() && "Val must be a scalar");
7871 
7872   if (Ty->isFloatingPointTy()) {
7873     Constant *C = ConstantFP::get(Ty, (double)StartIdx);
7874 
7875     // Floating point operations had to be 'fast' to enable the unrolling.
7876     Value *MulOp = addFastMathFlag(Builder.CreateFMul(C, Step));
7877     return addFastMathFlag(Builder.CreateBinOp(BinOp, Val, MulOp));
7878   }
7879   Constant *C = ConstantInt::get(Ty, StartIdx);
7880   return Builder.CreateAdd(Val, Builder.CreateMul(C, Step), "induction");
7881 }
7882 
7883 static void AddRuntimeUnrollDisableMetaData(Loop *L) {
7884   SmallVector<Metadata *, 4> MDs;
7885   // Reserve first location for self reference to the LoopID metadata node.
7886   MDs.push_back(nullptr);
7887   bool IsUnrollMetadata = false;
7888   MDNode *LoopID = L->getLoopID();
7889   if (LoopID) {
7890     // First find existing loop unrolling disable metadata.
7891     for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
7892       auto *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
7893       if (MD) {
7894         const auto *S = dyn_cast<MDString>(MD->getOperand(0));
7895         IsUnrollMetadata =
7896             S && S->getString().startswith("llvm.loop.unroll.disable");
7897       }
7898       MDs.push_back(LoopID->getOperand(i));
7899     }
7900   }
7901 
7902   if (!IsUnrollMetadata) {
7903     // Add runtime unroll disable metadata.
7904     LLVMContext &Context = L->getHeader()->getContext();
7905     SmallVector<Metadata *, 1> DisableOperands;
7906     DisableOperands.push_back(
7907         MDString::get(Context, "llvm.loop.unroll.runtime.disable"));
7908     MDNode *DisableNode = MDNode::get(Context, DisableOperands);
7909     MDs.push_back(DisableNode);
7910     MDNode *NewLoopID = MDNode::get(Context, MDs);
7911     // Set operand 0 to refer to the loop id itself.
7912     NewLoopID->replaceOperandWith(0, NewLoopID);
7913     L->setLoopID(NewLoopID);
7914   }
7915 }
7916 
7917 //===--------------------------------------------------------------------===//
7918 // EpilogueVectorizerMainLoop
7919 //===--------------------------------------------------------------------===//
7920 
7921 /// This function is partially responsible for generating the control flow
7922 /// depicted in https://llvm.org/docs/Vectorizers.html#epilogue-vectorization.
7923 BasicBlock *EpilogueVectorizerMainLoop::createEpilogueVectorizedLoopSkeleton() {
7924   MDNode *OrigLoopID = OrigLoop->getLoopID();
7925   Loop *Lp = createVectorLoopSkeleton("");
7926 
7927   // Generate the code to check the minimum iteration count of the vector
7928   // epilogue (see below).
7929   EPI.EpilogueIterationCountCheck =
7930       emitMinimumIterationCountCheck(Lp, LoopScalarPreHeader, true);
7931   EPI.EpilogueIterationCountCheck->setName("iter.check");
7932 
7933   // Generate the code to check any assumptions that we've made for SCEV
7934   // expressions.
7935   BasicBlock *SavedPreHeader = LoopVectorPreHeader;
7936   emitSCEVChecks(Lp, LoopScalarPreHeader);
7937 
7938   // If a safety check was generated save it.
7939   if (SavedPreHeader != LoopVectorPreHeader)
7940     EPI.SCEVSafetyCheck = SavedPreHeader;
7941 
7942   // Generate the code that checks at runtime if arrays overlap. We put the
7943   // checks into a separate block to make the more common case of few elements
7944   // faster.
7945   SavedPreHeader = LoopVectorPreHeader;
7946   emitMemRuntimeChecks(Lp, LoopScalarPreHeader);
7947 
7948   // If a safety check was generated save/overwite it.
7949   if (SavedPreHeader != LoopVectorPreHeader)
7950     EPI.MemSafetyCheck = SavedPreHeader;
7951 
7952   // Generate the iteration count check for the main loop, *after* the check
7953   // for the epilogue loop, so that the path-length is shorter for the case
7954   // that goes directly through the vector epilogue. The longer-path length for
7955   // the main loop is compensated for, by the gain from vectorizing the larger
7956   // trip count. Note: the branch will get updated later on when we vectorize
7957   // the epilogue.
7958   EPI.MainLoopIterationCountCheck =
7959       emitMinimumIterationCountCheck(Lp, LoopScalarPreHeader, false);
7960 
7961   // Generate the induction variable.
7962   OldInduction = Legal->getPrimaryInduction();
7963   Type *IdxTy = Legal->getWidestInductionType();
7964   Value *StartIdx = ConstantInt::get(IdxTy, 0);
7965   Constant *Step = ConstantInt::get(IdxTy, VF.getKnownMinValue() * UF);
7966   Value *CountRoundDown = getOrCreateVectorTripCount(Lp);
7967   EPI.VectorTripCount = CountRoundDown;
7968   Induction =
7969       createInductionVariable(Lp, StartIdx, CountRoundDown, Step,
7970                               getDebugLocFromInstOrOperands(OldInduction));
7971 
7972   // Skip induction resume value creation here because they will be created in
7973   // the second pass. If we created them here, they wouldn't be used anyway,
7974   // because the vplan in the second pass still contains the inductions from the
7975   // original loop.
7976 
7977   return completeLoopSkeleton(Lp, OrigLoopID);
7978 }
7979 
7980 void EpilogueVectorizerMainLoop::printDebugTracesAtStart() {
7981   LLVM_DEBUG({
7982     dbgs() << "Create Skeleton for epilogue vectorized loop (first pass)\n"
7983            << "Main Loop VF:" << EPI.MainLoopVF.getKnownMinValue()
7984            << ", Main Loop UF:" << EPI.MainLoopUF
7985            << ", Epilogue Loop VF:" << EPI.EpilogueVF.getKnownMinValue()
7986            << ", Epilogue Loop UF:" << EPI.EpilogueUF << "\n";
7987   });
7988 }
7989 
7990 void EpilogueVectorizerMainLoop::printDebugTracesAtEnd() {
7991   DEBUG_WITH_TYPE(VerboseDebug, {
7992     dbgs() << "intermediate fn:\n" << *Induction->getFunction() << "\n";
7993   });
7994 }
7995 
7996 BasicBlock *EpilogueVectorizerMainLoop::emitMinimumIterationCountCheck(
7997     Loop *L, BasicBlock *Bypass, bool ForEpilogue) {
7998   assert(L && "Expected valid Loop.");
7999   assert(Bypass && "Expected valid bypass basic block.");
8000   unsigned VFactor =
8001       ForEpilogue ? EPI.EpilogueVF.getKnownMinValue() : VF.getKnownMinValue();
8002   unsigned UFactor = ForEpilogue ? EPI.EpilogueUF : UF;
8003   Value *Count = getOrCreateTripCount(L);
8004   // Reuse existing vector loop preheader for TC checks.
8005   // Note that new preheader block is generated for vector loop.
8006   BasicBlock *const TCCheckBlock = LoopVectorPreHeader;
8007   IRBuilder<> Builder(TCCheckBlock->getTerminator());
8008 
8009   // Generate code to check if the loop's trip count is less than VF * UF of the
8010   // main vector loop.
8011   auto P =
8012       Cost->requiresScalarEpilogue() ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT;
8013 
8014   Value *CheckMinIters = Builder.CreateICmp(
8015       P, Count, ConstantInt::get(Count->getType(), VFactor * UFactor),
8016       "min.iters.check");
8017 
8018   if (!ForEpilogue)
8019     TCCheckBlock->setName("vector.main.loop.iter.check");
8020 
8021   // Create new preheader for vector loop.
8022   LoopVectorPreHeader = SplitBlock(TCCheckBlock, TCCheckBlock->getTerminator(),
8023                                    DT, LI, nullptr, "vector.ph");
8024 
8025   if (ForEpilogue) {
8026     assert(DT->properlyDominates(DT->getNode(TCCheckBlock),
8027                                  DT->getNode(Bypass)->getIDom()) &&
8028            "TC check is expected to dominate Bypass");
8029 
8030     // Update dominator for Bypass & LoopExit.
8031     DT->changeImmediateDominator(Bypass, TCCheckBlock);
8032     DT->changeImmediateDominator(LoopExitBlock, TCCheckBlock);
8033 
8034     LoopBypassBlocks.push_back(TCCheckBlock);
8035 
8036     // Save the trip count so we don't have to regenerate it in the
8037     // vec.epilog.iter.check. This is safe to do because the trip count
8038     // generated here dominates the vector epilog iter check.
8039     EPI.TripCount = Count;
8040   }
8041 
8042   ReplaceInstWithInst(
8043       TCCheckBlock->getTerminator(),
8044       BranchInst::Create(Bypass, LoopVectorPreHeader, CheckMinIters));
8045 
8046   return TCCheckBlock;
8047 }
8048 
8049 //===--------------------------------------------------------------------===//
8050 // EpilogueVectorizerEpilogueLoop
8051 //===--------------------------------------------------------------------===//
8052 
8053 /// This function is partially responsible for generating the control flow
8054 /// depicted in https://llvm.org/docs/Vectorizers.html#epilogue-vectorization.
8055 BasicBlock *
8056 EpilogueVectorizerEpilogueLoop::createEpilogueVectorizedLoopSkeleton() {
8057   MDNode *OrigLoopID = OrigLoop->getLoopID();
8058   Loop *Lp = createVectorLoopSkeleton("vec.epilog.");
8059 
8060   // Now, compare the remaining count and if there aren't enough iterations to
8061   // execute the vectorized epilogue skip to the scalar part.
8062   BasicBlock *VecEpilogueIterationCountCheck = LoopVectorPreHeader;
8063   VecEpilogueIterationCountCheck->setName("vec.epilog.iter.check");
8064   LoopVectorPreHeader =
8065       SplitBlock(LoopVectorPreHeader, LoopVectorPreHeader->getTerminator(), DT,
8066                  LI, nullptr, "vec.epilog.ph");
8067   emitMinimumVectorEpilogueIterCountCheck(Lp, LoopScalarPreHeader,
8068                                           VecEpilogueIterationCountCheck);
8069 
8070   // Adjust the control flow taking the state info from the main loop
8071   // vectorization into account.
8072   assert(EPI.MainLoopIterationCountCheck && EPI.EpilogueIterationCountCheck &&
8073          "expected this to be saved from the previous pass.");
8074   EPI.MainLoopIterationCountCheck->getTerminator()->replaceUsesOfWith(
8075       VecEpilogueIterationCountCheck, LoopVectorPreHeader);
8076 
8077   DT->changeImmediateDominator(LoopVectorPreHeader,
8078                                EPI.MainLoopIterationCountCheck);
8079 
8080   EPI.EpilogueIterationCountCheck->getTerminator()->replaceUsesOfWith(
8081       VecEpilogueIterationCountCheck, LoopScalarPreHeader);
8082 
8083   if (EPI.SCEVSafetyCheck)
8084     EPI.SCEVSafetyCheck->getTerminator()->replaceUsesOfWith(
8085         VecEpilogueIterationCountCheck, LoopScalarPreHeader);
8086   if (EPI.MemSafetyCheck)
8087     EPI.MemSafetyCheck->getTerminator()->replaceUsesOfWith(
8088         VecEpilogueIterationCountCheck, LoopScalarPreHeader);
8089 
8090   DT->changeImmediateDominator(
8091       VecEpilogueIterationCountCheck,
8092       VecEpilogueIterationCountCheck->getSinglePredecessor());
8093 
8094   DT->changeImmediateDominator(LoopScalarPreHeader,
8095                                EPI.EpilogueIterationCountCheck);
8096   DT->changeImmediateDominator(LoopExitBlock, EPI.EpilogueIterationCountCheck);
8097 
8098   // Keep track of bypass blocks, as they feed start values to the induction
8099   // phis in the scalar loop preheader.
8100   if (EPI.SCEVSafetyCheck)
8101     LoopBypassBlocks.push_back(EPI.SCEVSafetyCheck);
8102   if (EPI.MemSafetyCheck)
8103     LoopBypassBlocks.push_back(EPI.MemSafetyCheck);
8104   LoopBypassBlocks.push_back(EPI.EpilogueIterationCountCheck);
8105 
8106   // Generate a resume induction for the vector epilogue and put it in the
8107   // vector epilogue preheader
8108   Type *IdxTy = Legal->getWidestInductionType();
8109   PHINode *EPResumeVal = PHINode::Create(IdxTy, 2, "vec.epilog.resume.val",
8110                                          LoopVectorPreHeader->getFirstNonPHI());
8111   EPResumeVal->addIncoming(EPI.VectorTripCount, VecEpilogueIterationCountCheck);
8112   EPResumeVal->addIncoming(ConstantInt::get(IdxTy, 0),
8113                            EPI.MainLoopIterationCountCheck);
8114 
8115   // Generate the induction variable.
8116   OldInduction = Legal->getPrimaryInduction();
8117   Value *CountRoundDown = getOrCreateVectorTripCount(Lp);
8118   Constant *Step = ConstantInt::get(IdxTy, VF.getKnownMinValue() * UF);
8119   Value *StartIdx = EPResumeVal;
8120   Induction =
8121       createInductionVariable(Lp, StartIdx, CountRoundDown, Step,
8122                               getDebugLocFromInstOrOperands(OldInduction));
8123 
8124   // Generate induction resume values. These variables save the new starting
8125   // indexes for the scalar loop. They are used to test if there are any tail
8126   // iterations left once the vector loop has completed.
8127   // Note that when the vectorized epilogue is skipped due to iteration count
8128   // check, then the resume value for the induction variable comes from
8129   // the trip count of the main vector loop, hence passing the AdditionalBypass
8130   // argument.
8131   createInductionResumeValues(Lp, CountRoundDown,
8132                               {VecEpilogueIterationCountCheck,
8133                                EPI.VectorTripCount} /* AdditionalBypass */);
8134 
8135   AddRuntimeUnrollDisableMetaData(Lp);
8136   return completeLoopSkeleton(Lp, OrigLoopID);
8137 }
8138 
8139 BasicBlock *
8140 EpilogueVectorizerEpilogueLoop::emitMinimumVectorEpilogueIterCountCheck(
8141     Loop *L, BasicBlock *Bypass, BasicBlock *Insert) {
8142 
8143   assert(EPI.TripCount &&
8144          "Expected trip count to have been safed in the first pass.");
8145   assert(
8146       (!isa<Instruction>(EPI.TripCount) ||
8147        DT->dominates(cast<Instruction>(EPI.TripCount)->getParent(), Insert)) &&
8148       "saved trip count does not dominate insertion point.");
8149   Value *TC = EPI.TripCount;
8150   IRBuilder<> Builder(Insert->getTerminator());
8151   Value *Count = Builder.CreateSub(TC, EPI.VectorTripCount, "n.vec.remaining");
8152 
8153   // Generate code to check if the loop's trip count is less than VF * UF of the
8154   // vector epilogue loop.
8155   auto P =
8156       Cost->requiresScalarEpilogue() ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT;
8157 
8158   Value *CheckMinIters = Builder.CreateICmp(
8159       P, Count,
8160       ConstantInt::get(Count->getType(),
8161                        EPI.EpilogueVF.getKnownMinValue() * EPI.EpilogueUF),
8162       "min.epilog.iters.check");
8163 
8164   ReplaceInstWithInst(
8165       Insert->getTerminator(),
8166       BranchInst::Create(Bypass, LoopVectorPreHeader, CheckMinIters));
8167 
8168   LoopBypassBlocks.push_back(Insert);
8169   return Insert;
8170 }
8171 
8172 void EpilogueVectorizerEpilogueLoop::printDebugTracesAtStart() {
8173   LLVM_DEBUG({
8174     dbgs() << "Create Skeleton for epilogue vectorized loop (second pass)\n"
8175            << "Main Loop VF:" << EPI.MainLoopVF.getKnownMinValue()
8176            << ", Main Loop UF:" << EPI.MainLoopUF
8177            << ", Epilogue Loop VF:" << EPI.EpilogueVF.getKnownMinValue()
8178            << ", Epilogue Loop UF:" << EPI.EpilogueUF << "\n";
8179   });
8180 }
8181 
8182 void EpilogueVectorizerEpilogueLoop::printDebugTracesAtEnd() {
8183   DEBUG_WITH_TYPE(VerboseDebug, {
8184     dbgs() << "final fn:\n" << *Induction->getFunction() << "\n";
8185   });
8186 }
8187 
8188 bool LoopVectorizationPlanner::getDecisionAndClampRange(
8189     const std::function<bool(ElementCount)> &Predicate, VFRange &Range) {
8190   assert(!Range.isEmpty() && "Trying to test an empty VF range.");
8191   bool PredicateAtRangeStart = Predicate(Range.Start);
8192 
8193   for (ElementCount TmpVF = Range.Start * 2;
8194        ElementCount::isKnownLT(TmpVF, Range.End); TmpVF *= 2)
8195     if (Predicate(TmpVF) != PredicateAtRangeStart) {
8196       Range.End = TmpVF;
8197       break;
8198     }
8199 
8200   return PredicateAtRangeStart;
8201 }
8202 
8203 /// Build VPlans for the full range of feasible VF's = {\p MinVF, 2 * \p MinVF,
8204 /// 4 * \p MinVF, ..., \p MaxVF} by repeatedly building a VPlan for a sub-range
8205 /// of VF's starting at a given VF and extending it as much as possible. Each
8206 /// vectorization decision can potentially shorten this sub-range during
8207 /// buildVPlan().
8208 void LoopVectorizationPlanner::buildVPlans(ElementCount MinVF,
8209                                            ElementCount MaxVF) {
8210   auto MaxVFPlusOne = MaxVF.getWithIncrement(1);
8211   for (ElementCount VF = MinVF; ElementCount::isKnownLT(VF, MaxVFPlusOne);) {
8212     VFRange SubRange = {VF, MaxVFPlusOne};
8213     VPlans.push_back(buildVPlan(SubRange));
8214     VF = SubRange.End;
8215   }
8216 }
8217 
8218 VPValue *VPRecipeBuilder::createEdgeMask(BasicBlock *Src, BasicBlock *Dst,
8219                                          VPlanPtr &Plan) {
8220   assert(is_contained(predecessors(Dst), Src) && "Invalid edge");
8221 
8222   // Look for cached value.
8223   std::pair<BasicBlock *, BasicBlock *> Edge(Src, Dst);
8224   EdgeMaskCacheTy::iterator ECEntryIt = EdgeMaskCache.find(Edge);
8225   if (ECEntryIt != EdgeMaskCache.end())
8226     return ECEntryIt->second;
8227 
8228   VPValue *SrcMask = createBlockInMask(Src, Plan);
8229 
8230   // The terminator has to be a branch inst!
8231   BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
8232   assert(BI && "Unexpected terminator found");
8233 
8234   if (!BI->isConditional() || BI->getSuccessor(0) == BI->getSuccessor(1))
8235     return EdgeMaskCache[Edge] = SrcMask;
8236 
8237   // If source is an exiting block, we know the exit edge is dynamically dead
8238   // in the vector loop, and thus we don't need to restrict the mask.  Avoid
8239   // adding uses of an otherwise potentially dead instruction.
8240   if (OrigLoop->isLoopExiting(Src))
8241     return EdgeMaskCache[Edge] = SrcMask;
8242 
8243   VPValue *EdgeMask = Plan->getOrAddVPValue(BI->getCondition());
8244   assert(EdgeMask && "No Edge Mask found for condition");
8245 
8246   if (BI->getSuccessor(0) != Dst)
8247     EdgeMask = Builder.createNot(EdgeMask);
8248 
8249   if (SrcMask) { // Otherwise block in-mask is all-one, no need to AND.
8250     // The condition is 'SrcMask && EdgeMask', which is equivalent to
8251     // 'select i1 SrcMask, i1 EdgeMask, i1 false'.
8252     // The select version does not introduce new UB if SrcMask is false and
8253     // EdgeMask is poison. Using 'and' here introduces undefined behavior.
8254     VPValue *False = Plan->getOrAddVPValue(
8255         ConstantInt::getFalse(BI->getCondition()->getType()));
8256     EdgeMask = Builder.createSelect(SrcMask, EdgeMask, False);
8257   }
8258 
8259   return EdgeMaskCache[Edge] = EdgeMask;
8260 }
8261 
8262 VPValue *VPRecipeBuilder::createBlockInMask(BasicBlock *BB, VPlanPtr &Plan) {
8263   assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
8264 
8265   // Look for cached value.
8266   BlockMaskCacheTy::iterator BCEntryIt = BlockMaskCache.find(BB);
8267   if (BCEntryIt != BlockMaskCache.end())
8268     return BCEntryIt->second;
8269 
8270   // All-one mask is modelled as no-mask following the convention for masked
8271   // load/store/gather/scatter. Initialize BlockMask to no-mask.
8272   VPValue *BlockMask = nullptr;
8273 
8274   if (OrigLoop->getHeader() == BB) {
8275     if (!CM.blockNeedsPredication(BB))
8276       return BlockMaskCache[BB] = BlockMask; // Loop incoming mask is all-one.
8277 
8278     // Create the block in mask as the first non-phi instruction in the block.
8279     VPBuilder::InsertPointGuard Guard(Builder);
8280     auto NewInsertionPoint = Builder.getInsertBlock()->getFirstNonPhi();
8281     Builder.setInsertPoint(Builder.getInsertBlock(), NewInsertionPoint);
8282 
8283     // Introduce the early-exit compare IV <= BTC to form header block mask.
8284     // This is used instead of IV < TC because TC may wrap, unlike BTC.
8285     // Start by constructing the desired canonical IV.
8286     VPValue *IV = nullptr;
8287     if (Legal->getPrimaryInduction())
8288       IV = Plan->getOrAddVPValue(Legal->getPrimaryInduction());
8289     else {
8290       auto IVRecipe = new VPWidenCanonicalIVRecipe();
8291       Builder.getInsertBlock()->insert(IVRecipe, NewInsertionPoint);
8292       IV = IVRecipe->getVPValue();
8293     }
8294     VPValue *BTC = Plan->getOrCreateBackedgeTakenCount();
8295     bool TailFolded = !CM.isScalarEpilogueAllowed();
8296 
8297     if (TailFolded && CM.TTI.emitGetActiveLaneMask()) {
8298       // While ActiveLaneMask is a binary op that consumes the loop tripcount
8299       // as a second argument, we only pass the IV here and extract the
8300       // tripcount from the transform state where codegen of the VP instructions
8301       // happen.
8302       BlockMask = Builder.createNaryOp(VPInstruction::ActiveLaneMask, {IV});
8303     } else {
8304       BlockMask = Builder.createNaryOp(VPInstruction::ICmpULE, {IV, BTC});
8305     }
8306     return BlockMaskCache[BB] = BlockMask;
8307   }
8308 
8309   // This is the block mask. We OR all incoming edges.
8310   for (auto *Predecessor : predecessors(BB)) {
8311     VPValue *EdgeMask = createEdgeMask(Predecessor, BB, Plan);
8312     if (!EdgeMask) // Mask of predecessor is all-one so mask of block is too.
8313       return BlockMaskCache[BB] = EdgeMask;
8314 
8315     if (!BlockMask) { // BlockMask has its initialized nullptr value.
8316       BlockMask = EdgeMask;
8317       continue;
8318     }
8319 
8320     BlockMask = Builder.createOr(BlockMask, EdgeMask);
8321   }
8322 
8323   return BlockMaskCache[BB] = BlockMask;
8324 }
8325 
8326 VPRecipeBase *VPRecipeBuilder::tryToWidenMemory(Instruction *I, VFRange &Range,
8327                                                 VPlanPtr &Plan) {
8328   assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
8329          "Must be called with either a load or store");
8330 
8331   auto willWiden = [&](ElementCount VF) -> bool {
8332     if (VF.isScalar())
8333       return false;
8334     LoopVectorizationCostModel::InstWidening Decision =
8335         CM.getWideningDecision(I, VF);
8336     assert(Decision != LoopVectorizationCostModel::CM_Unknown &&
8337            "CM decision should be taken at this point.");
8338     if (Decision == LoopVectorizationCostModel::CM_Interleave)
8339       return true;
8340     if (CM.isScalarAfterVectorization(I, VF) ||
8341         CM.isProfitableToScalarize(I, VF))
8342       return false;
8343     return Decision != LoopVectorizationCostModel::CM_Scalarize;
8344   };
8345 
8346   if (!LoopVectorizationPlanner::getDecisionAndClampRange(willWiden, Range))
8347     return nullptr;
8348 
8349   VPValue *Mask = nullptr;
8350   if (Legal->isMaskRequired(I))
8351     Mask = createBlockInMask(I->getParent(), Plan);
8352 
8353   VPValue *Addr = Plan->getOrAddVPValue(getLoadStorePointerOperand(I));
8354   if (LoadInst *Load = dyn_cast<LoadInst>(I))
8355     return new VPWidenMemoryInstructionRecipe(*Load, Addr, Mask);
8356 
8357   StoreInst *Store = cast<StoreInst>(I);
8358   VPValue *StoredValue = Plan->getOrAddVPValue(Store->getValueOperand());
8359   return new VPWidenMemoryInstructionRecipe(*Store, Addr, StoredValue, Mask);
8360 }
8361 
8362 VPWidenIntOrFpInductionRecipe *
8363 VPRecipeBuilder::tryToOptimizeInductionPHI(PHINode *Phi, VPlan &Plan) const {
8364   // Check if this is an integer or fp induction. If so, build the recipe that
8365   // produces its scalar and vector values.
8366   InductionDescriptor II = Legal->getInductionVars().lookup(Phi);
8367   if (II.getKind() == InductionDescriptor::IK_IntInduction ||
8368       II.getKind() == InductionDescriptor::IK_FpInduction) {
8369     VPValue *Start = Plan.getOrAddVPValue(II.getStartValue());
8370     const SmallVectorImpl<Instruction *> &Casts = II.getCastInsts();
8371     return new VPWidenIntOrFpInductionRecipe(
8372         Phi, Start, Casts.empty() ? nullptr : Casts.front());
8373   }
8374 
8375   return nullptr;
8376 }
8377 
8378 VPWidenIntOrFpInductionRecipe *
8379 VPRecipeBuilder::tryToOptimizeInductionTruncate(TruncInst *I, VFRange &Range,
8380                                                 VPlan &Plan) const {
8381   // Optimize the special case where the source is a constant integer
8382   // induction variable. Notice that we can only optimize the 'trunc' case
8383   // because (a) FP conversions lose precision, (b) sext/zext may wrap, and
8384   // (c) other casts depend on pointer size.
8385 
8386   // Determine whether \p K is a truncation based on an induction variable that
8387   // can be optimized.
8388   auto isOptimizableIVTruncate =
8389       [&](Instruction *K) -> std::function<bool(ElementCount)> {
8390     return [=](ElementCount VF) -> bool {
8391       return CM.isOptimizableIVTruncate(K, VF);
8392     };
8393   };
8394 
8395   if (LoopVectorizationPlanner::getDecisionAndClampRange(
8396           isOptimizableIVTruncate(I), Range)) {
8397 
8398     InductionDescriptor II =
8399         Legal->getInductionVars().lookup(cast<PHINode>(I->getOperand(0)));
8400     VPValue *Start = Plan.getOrAddVPValue(II.getStartValue());
8401     return new VPWidenIntOrFpInductionRecipe(cast<PHINode>(I->getOperand(0)),
8402                                              Start, nullptr, I);
8403   }
8404   return nullptr;
8405 }
8406 
8407 VPBlendRecipe *VPRecipeBuilder::tryToBlend(PHINode *Phi, VPlanPtr &Plan) {
8408   // We know that all PHIs in non-header blocks are converted into selects, so
8409   // we don't have to worry about the insertion order and we can just use the
8410   // builder. At this point we generate the predication tree. There may be
8411   // duplications since this is a simple recursive scan, but future
8412   // optimizations will clean it up.
8413 
8414   SmallVector<VPValue *, 2> Operands;
8415   unsigned NumIncoming = Phi->getNumIncomingValues();
8416   for (unsigned In = 0; In < NumIncoming; In++) {
8417     VPValue *EdgeMask =
8418       createEdgeMask(Phi->getIncomingBlock(In), Phi->getParent(), Plan);
8419     assert((EdgeMask || NumIncoming == 1) &&
8420            "Multiple predecessors with one having a full mask");
8421     Operands.push_back(Plan->getOrAddVPValue(Phi->getIncomingValue(In)));
8422     if (EdgeMask)
8423       Operands.push_back(EdgeMask);
8424   }
8425   return new VPBlendRecipe(Phi, Operands);
8426 }
8427 
8428 VPWidenCallRecipe *VPRecipeBuilder::tryToWidenCall(CallInst *CI, VFRange &Range,
8429                                                    VPlan &Plan) const {
8430 
8431   bool IsPredicated = LoopVectorizationPlanner::getDecisionAndClampRange(
8432       [this, CI](ElementCount VF) {
8433         return CM.isScalarWithPredication(CI, VF);
8434       },
8435       Range);
8436 
8437   if (IsPredicated)
8438     return nullptr;
8439 
8440   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
8441   if (ID && (ID == Intrinsic::assume || ID == Intrinsic::lifetime_end ||
8442              ID == Intrinsic::lifetime_start || ID == Intrinsic::sideeffect ||
8443              ID == Intrinsic::pseudoprobe ||
8444              ID == Intrinsic::experimental_noalias_scope_decl))
8445     return nullptr;
8446 
8447   auto willWiden = [&](ElementCount VF) -> bool {
8448     Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
8449     // The following case may be scalarized depending on the VF.
8450     // The flag shows whether we use Intrinsic or a usual Call for vectorized
8451     // version of the instruction.
8452     // Is it beneficial to perform intrinsic call compared to lib call?
8453     bool NeedToScalarize = false;
8454     InstructionCost CallCost = CM.getVectorCallCost(CI, VF, NeedToScalarize);
8455     InstructionCost IntrinsicCost = ID ? CM.getVectorIntrinsicCost(CI, VF) : 0;
8456     bool UseVectorIntrinsic = ID && IntrinsicCost <= CallCost;
8457     assert(IntrinsicCost.isValid() && CallCost.isValid() &&
8458            "Cannot have invalid costs while widening");
8459     return UseVectorIntrinsic || !NeedToScalarize;
8460   };
8461 
8462   if (!LoopVectorizationPlanner::getDecisionAndClampRange(willWiden, Range))
8463     return nullptr;
8464 
8465   return new VPWidenCallRecipe(*CI, Plan.mapToVPValues(CI->arg_operands()));
8466 }
8467 
8468 bool VPRecipeBuilder::shouldWiden(Instruction *I, VFRange &Range) const {
8469   assert(!isa<BranchInst>(I) && !isa<PHINode>(I) && !isa<LoadInst>(I) &&
8470          !isa<StoreInst>(I) && "Instruction should have been handled earlier");
8471   // Instruction should be widened, unless it is scalar after vectorization,
8472   // scalarization is profitable or it is predicated.
8473   auto WillScalarize = [this, I](ElementCount VF) -> bool {
8474     return CM.isScalarAfterVectorization(I, VF) ||
8475            CM.isProfitableToScalarize(I, VF) ||
8476            CM.isScalarWithPredication(I, VF);
8477   };
8478   return !LoopVectorizationPlanner::getDecisionAndClampRange(WillScalarize,
8479                                                              Range);
8480 }
8481 
8482 VPWidenRecipe *VPRecipeBuilder::tryToWiden(Instruction *I, VPlan &Plan) const {
8483   auto IsVectorizableOpcode = [](unsigned Opcode) {
8484     switch (Opcode) {
8485     case Instruction::Add:
8486     case Instruction::And:
8487     case Instruction::AShr:
8488     case Instruction::BitCast:
8489     case Instruction::FAdd:
8490     case Instruction::FCmp:
8491     case Instruction::FDiv:
8492     case Instruction::FMul:
8493     case Instruction::FNeg:
8494     case Instruction::FPExt:
8495     case Instruction::FPToSI:
8496     case Instruction::FPToUI:
8497     case Instruction::FPTrunc:
8498     case Instruction::FRem:
8499     case Instruction::FSub:
8500     case Instruction::ICmp:
8501     case Instruction::IntToPtr:
8502     case Instruction::LShr:
8503     case Instruction::Mul:
8504     case Instruction::Or:
8505     case Instruction::PtrToInt:
8506     case Instruction::SDiv:
8507     case Instruction::Select:
8508     case Instruction::SExt:
8509     case Instruction::Shl:
8510     case Instruction::SIToFP:
8511     case Instruction::SRem:
8512     case Instruction::Sub:
8513     case Instruction::Trunc:
8514     case Instruction::UDiv:
8515     case Instruction::UIToFP:
8516     case Instruction::URem:
8517     case Instruction::Xor:
8518     case Instruction::ZExt:
8519       return true;
8520     }
8521     return false;
8522   };
8523 
8524   if (!IsVectorizableOpcode(I->getOpcode()))
8525     return nullptr;
8526 
8527   // Success: widen this instruction.
8528   return new VPWidenRecipe(*I, Plan.mapToVPValues(I->operands()));
8529 }
8530 
8531 VPBasicBlock *VPRecipeBuilder::handleReplication(
8532     Instruction *I, VFRange &Range, VPBasicBlock *VPBB,
8533     DenseMap<Instruction *, VPReplicateRecipe *> &PredInst2Recipe,
8534     VPlanPtr &Plan) {
8535   bool IsUniform = LoopVectorizationPlanner::getDecisionAndClampRange(
8536       [&](ElementCount VF) { return CM.isUniformAfterVectorization(I, VF); },
8537       Range);
8538 
8539   bool IsPredicated = LoopVectorizationPlanner::getDecisionAndClampRange(
8540       [&](ElementCount VF) { return CM.isScalarWithPredication(I, VF); },
8541       Range);
8542 
8543   auto *Recipe = new VPReplicateRecipe(I, Plan->mapToVPValues(I->operands()),
8544                                        IsUniform, IsPredicated);
8545   setRecipe(I, Recipe);
8546   Plan->addVPValue(I, Recipe);
8547 
8548   // Find if I uses a predicated instruction. If so, it will use its scalar
8549   // value. Avoid hoisting the insert-element which packs the scalar value into
8550   // a vector value, as that happens iff all users use the vector value.
8551   for (auto &Op : I->operands())
8552     if (auto *PredInst = dyn_cast<Instruction>(Op))
8553       if (PredInst2Recipe.find(PredInst) != PredInst2Recipe.end())
8554         PredInst2Recipe[PredInst]->setAlsoPack(false);
8555 
8556   // Finalize the recipe for Instr, first if it is not predicated.
8557   if (!IsPredicated) {
8558     LLVM_DEBUG(dbgs() << "LV: Scalarizing:" << *I << "\n");
8559     VPBB->appendRecipe(Recipe);
8560     return VPBB;
8561   }
8562   LLVM_DEBUG(dbgs() << "LV: Scalarizing and predicating:" << *I << "\n");
8563   assert(VPBB->getSuccessors().empty() &&
8564          "VPBB has successors when handling predicated replication.");
8565   // Record predicated instructions for above packing optimizations.
8566   PredInst2Recipe[I] = Recipe;
8567   VPBlockBase *Region = createReplicateRegion(I, Recipe, Plan);
8568   VPBlockUtils::insertBlockAfter(Region, VPBB);
8569   auto *RegSucc = new VPBasicBlock();
8570   VPBlockUtils::insertBlockAfter(RegSucc, Region);
8571   return RegSucc;
8572 }
8573 
8574 VPRegionBlock *VPRecipeBuilder::createReplicateRegion(Instruction *Instr,
8575                                                       VPRecipeBase *PredRecipe,
8576                                                       VPlanPtr &Plan) {
8577   // Instructions marked for predication are replicated and placed under an
8578   // if-then construct to prevent side-effects.
8579 
8580   // Generate recipes to compute the block mask for this region.
8581   VPValue *BlockInMask = createBlockInMask(Instr->getParent(), Plan);
8582 
8583   // Build the triangular if-then region.
8584   std::string RegionName = (Twine("pred.") + Instr->getOpcodeName()).str();
8585   assert(Instr->getParent() && "Predicated instruction not in any basic block");
8586   auto *BOMRecipe = new VPBranchOnMaskRecipe(BlockInMask);
8587   auto *Entry = new VPBasicBlock(Twine(RegionName) + ".entry", BOMRecipe);
8588   auto *PHIRecipe = Instr->getType()->isVoidTy()
8589                         ? nullptr
8590                         : new VPPredInstPHIRecipe(Plan->getOrAddVPValue(Instr));
8591   auto *Exit = new VPBasicBlock(Twine(RegionName) + ".continue", PHIRecipe);
8592   auto *Pred = new VPBasicBlock(Twine(RegionName) + ".if", PredRecipe);
8593   VPRegionBlock *Region = new VPRegionBlock(Entry, Exit, RegionName, true);
8594 
8595   // Note: first set Entry as region entry and then connect successors starting
8596   // from it in order, to propagate the "parent" of each VPBasicBlock.
8597   VPBlockUtils::insertTwoBlocksAfter(Pred, Exit, BlockInMask, Entry);
8598   VPBlockUtils::connectBlocks(Pred, Exit);
8599 
8600   return Region;
8601 }
8602 
8603 VPRecipeBase *VPRecipeBuilder::tryToCreateWidenRecipe(Instruction *Instr,
8604                                                       VFRange &Range,
8605                                                       VPlanPtr &Plan) {
8606   // First, check for specific widening recipes that deal with calls, memory
8607   // operations, inductions and Phi nodes.
8608   if (auto *CI = dyn_cast<CallInst>(Instr))
8609     return tryToWidenCall(CI, Range, *Plan);
8610 
8611   if (isa<LoadInst>(Instr) || isa<StoreInst>(Instr))
8612     return tryToWidenMemory(Instr, Range, Plan);
8613 
8614   VPRecipeBase *Recipe;
8615   if (auto Phi = dyn_cast<PHINode>(Instr)) {
8616     if (Phi->getParent() != OrigLoop->getHeader())
8617       return tryToBlend(Phi, Plan);
8618     if ((Recipe = tryToOptimizeInductionPHI(Phi, *Plan)))
8619       return Recipe;
8620 
8621     if (Legal->isReductionVariable(Phi)) {
8622       RecurrenceDescriptor &RdxDesc = Legal->getReductionVars()[Phi];
8623       VPValue *StartV =
8624           Plan->getOrAddVPValue(RdxDesc.getRecurrenceStartValue());
8625       return new VPWidenPHIRecipe(Phi, RdxDesc, *StartV);
8626     }
8627 
8628     return new VPWidenPHIRecipe(Phi);
8629   }
8630 
8631   if (isa<TruncInst>(Instr) && (Recipe = tryToOptimizeInductionTruncate(
8632                                     cast<TruncInst>(Instr), Range, *Plan)))
8633     return Recipe;
8634 
8635   if (!shouldWiden(Instr, Range))
8636     return nullptr;
8637 
8638   if (auto GEP = dyn_cast<GetElementPtrInst>(Instr))
8639     return new VPWidenGEPRecipe(GEP, Plan->mapToVPValues(GEP->operands()),
8640                                 OrigLoop);
8641 
8642   if (auto *SI = dyn_cast<SelectInst>(Instr)) {
8643     bool InvariantCond =
8644         PSE.getSE()->isLoopInvariant(PSE.getSCEV(SI->getOperand(0)), OrigLoop);
8645     return new VPWidenSelectRecipe(*SI, Plan->mapToVPValues(SI->operands()),
8646                                    InvariantCond);
8647   }
8648 
8649   return tryToWiden(Instr, *Plan);
8650 }
8651 
8652 void LoopVectorizationPlanner::buildVPlansWithVPRecipes(ElementCount MinVF,
8653                                                         ElementCount MaxVF) {
8654   assert(OrigLoop->isInnermost() && "Inner loop expected.");
8655 
8656   // Collect instructions from the original loop that will become trivially dead
8657   // in the vectorized loop. We don't need to vectorize these instructions. For
8658   // example, original induction update instructions can become dead because we
8659   // separately emit induction "steps" when generating code for the new loop.
8660   // Similarly, we create a new latch condition when setting up the structure
8661   // of the new loop, so the old one can become dead.
8662   SmallPtrSet<Instruction *, 4> DeadInstructions;
8663   collectTriviallyDeadInstructions(DeadInstructions);
8664 
8665   // Add assume instructions we need to drop to DeadInstructions, to prevent
8666   // them from being added to the VPlan.
8667   // TODO: We only need to drop assumes in blocks that get flattend. If the
8668   // control flow is preserved, we should keep them.
8669   auto &ConditionalAssumes = Legal->getConditionalAssumes();
8670   DeadInstructions.insert(ConditionalAssumes.begin(), ConditionalAssumes.end());
8671 
8672   DenseMap<Instruction *, Instruction *> &SinkAfter = Legal->getSinkAfter();
8673   // Dead instructions do not need sinking. Remove them from SinkAfter.
8674   for (Instruction *I : DeadInstructions)
8675     SinkAfter.erase(I);
8676 
8677   auto MaxVFPlusOne = MaxVF.getWithIncrement(1);
8678   for (ElementCount VF = MinVF; ElementCount::isKnownLT(VF, MaxVFPlusOne);) {
8679     VFRange SubRange = {VF, MaxVFPlusOne};
8680     VPlans.push_back(
8681         buildVPlanWithVPRecipes(SubRange, DeadInstructions, SinkAfter));
8682     VF = SubRange.End;
8683   }
8684 }
8685 
8686 VPlanPtr LoopVectorizationPlanner::buildVPlanWithVPRecipes(
8687     VFRange &Range, SmallPtrSetImpl<Instruction *> &DeadInstructions,
8688     const DenseMap<Instruction *, Instruction *> &SinkAfter) {
8689 
8690   // Hold a mapping from predicated instructions to their recipes, in order to
8691   // fix their AlsoPack behavior if a user is determined to replicate and use a
8692   // scalar instead of vector value.
8693   DenseMap<Instruction *, VPReplicateRecipe *> PredInst2Recipe;
8694 
8695   SmallPtrSet<const InterleaveGroup<Instruction> *, 1> InterleaveGroups;
8696 
8697   VPRecipeBuilder RecipeBuilder(OrigLoop, TLI, Legal, CM, PSE, Builder);
8698 
8699   // ---------------------------------------------------------------------------
8700   // Pre-construction: record ingredients whose recipes we'll need to further
8701   // process after constructing the initial VPlan.
8702   // ---------------------------------------------------------------------------
8703 
8704   // Mark instructions we'll need to sink later and their targets as
8705   // ingredients whose recipe we'll need to record.
8706   for (auto &Entry : SinkAfter) {
8707     RecipeBuilder.recordRecipeOf(Entry.first);
8708     RecipeBuilder.recordRecipeOf(Entry.second);
8709   }
8710   for (auto &Reduction : CM.getInLoopReductionChains()) {
8711     PHINode *Phi = Reduction.first;
8712     RecurKind Kind = Legal->getReductionVars()[Phi].getRecurrenceKind();
8713     const SmallVector<Instruction *, 4> &ReductionOperations = Reduction.second;
8714 
8715     RecipeBuilder.recordRecipeOf(Phi);
8716     for (auto &R : ReductionOperations) {
8717       RecipeBuilder.recordRecipeOf(R);
8718       // For min/max reducitons, where we have a pair of icmp/select, we also
8719       // need to record the ICmp recipe, so it can be removed later.
8720       if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind))
8721         RecipeBuilder.recordRecipeOf(cast<Instruction>(R->getOperand(0)));
8722     }
8723   }
8724 
8725   // For each interleave group which is relevant for this (possibly trimmed)
8726   // Range, add it to the set of groups to be later applied to the VPlan and add
8727   // placeholders for its members' Recipes which we'll be replacing with a
8728   // single VPInterleaveRecipe.
8729   for (InterleaveGroup<Instruction> *IG : IAI.getInterleaveGroups()) {
8730     auto applyIG = [IG, this](ElementCount VF) -> bool {
8731       return (VF.isVector() && // Query is illegal for VF == 1
8732               CM.getWideningDecision(IG->getInsertPos(), VF) ==
8733                   LoopVectorizationCostModel::CM_Interleave);
8734     };
8735     if (!getDecisionAndClampRange(applyIG, Range))
8736       continue;
8737     InterleaveGroups.insert(IG);
8738     for (unsigned i = 0; i < IG->getFactor(); i++)
8739       if (Instruction *Member = IG->getMember(i))
8740         RecipeBuilder.recordRecipeOf(Member);
8741   };
8742 
8743   // ---------------------------------------------------------------------------
8744   // Build initial VPlan: Scan the body of the loop in a topological order to
8745   // visit each basic block after having visited its predecessor basic blocks.
8746   // ---------------------------------------------------------------------------
8747 
8748   // Create a dummy pre-entry VPBasicBlock to start building the VPlan.
8749   auto Plan = std::make_unique<VPlan>();
8750   VPBasicBlock *VPBB = new VPBasicBlock("Pre-Entry");
8751   Plan->setEntry(VPBB);
8752 
8753   // Scan the body of the loop in a topological order to visit each basic block
8754   // after having visited its predecessor basic blocks.
8755   LoopBlocksDFS DFS(OrigLoop);
8756   DFS.perform(LI);
8757 
8758   for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) {
8759     // Relevant instructions from basic block BB will be grouped into VPRecipe
8760     // ingredients and fill a new VPBasicBlock.
8761     unsigned VPBBsForBB = 0;
8762     auto *FirstVPBBForBB = new VPBasicBlock(BB->getName());
8763     VPBlockUtils::insertBlockAfter(FirstVPBBForBB, VPBB);
8764     VPBB = FirstVPBBForBB;
8765     Builder.setInsertPoint(VPBB);
8766 
8767     // Introduce each ingredient into VPlan.
8768     // TODO: Model and preserve debug instrinsics in VPlan.
8769     for (Instruction &I : BB->instructionsWithoutDebug()) {
8770       Instruction *Instr = &I;
8771 
8772       // First filter out irrelevant instructions, to ensure no recipes are
8773       // built for them.
8774       if (isa<BranchInst>(Instr) || DeadInstructions.count(Instr))
8775         continue;
8776 
8777       if (auto Recipe =
8778               RecipeBuilder.tryToCreateWidenRecipe(Instr, Range, Plan)) {
8779         for (auto *Def : Recipe->definedValues()) {
8780           auto *UV = Def->getUnderlyingValue();
8781           Plan->addVPValue(UV, Def);
8782         }
8783 
8784         RecipeBuilder.setRecipe(Instr, Recipe);
8785         VPBB->appendRecipe(Recipe);
8786         continue;
8787       }
8788 
8789       // Otherwise, if all widening options failed, Instruction is to be
8790       // replicated. This may create a successor for VPBB.
8791       VPBasicBlock *NextVPBB = RecipeBuilder.handleReplication(
8792           Instr, Range, VPBB, PredInst2Recipe, Plan);
8793       if (NextVPBB != VPBB) {
8794         VPBB = NextVPBB;
8795         VPBB->setName(BB->hasName() ? BB->getName() + "." + Twine(VPBBsForBB++)
8796                                     : "");
8797       }
8798     }
8799   }
8800 
8801   // Discard empty dummy pre-entry VPBasicBlock. Note that other VPBasicBlocks
8802   // may also be empty, such as the last one VPBB, reflecting original
8803   // basic-blocks with no recipes.
8804   VPBasicBlock *PreEntry = cast<VPBasicBlock>(Plan->getEntry());
8805   assert(PreEntry->empty() && "Expecting empty pre-entry block.");
8806   VPBlockBase *Entry = Plan->setEntry(PreEntry->getSingleSuccessor());
8807   VPBlockUtils::disconnectBlocks(PreEntry, Entry);
8808   delete PreEntry;
8809 
8810   // ---------------------------------------------------------------------------
8811   // Transform initial VPlan: Apply previously taken decisions, in order, to
8812   // bring the VPlan to its final state.
8813   // ---------------------------------------------------------------------------
8814 
8815   // Apply Sink-After legal constraints.
8816   for (auto &Entry : SinkAfter) {
8817     VPRecipeBase *Sink = RecipeBuilder.getRecipe(Entry.first);
8818     VPRecipeBase *Target = RecipeBuilder.getRecipe(Entry.second);
8819     // If the target is in a replication region, make sure to move Sink to the
8820     // block after it, not into the replication region itself.
8821     if (auto *Region =
8822             dyn_cast_or_null<VPRegionBlock>(Target->getParent()->getParent())) {
8823       if (Region->isReplicator()) {
8824         assert(Region->getNumSuccessors() == 1 && "Expected SESE region!");
8825         VPBasicBlock *NextBlock =
8826             cast<VPBasicBlock>(Region->getSuccessors().front());
8827         Sink->moveBefore(*NextBlock, NextBlock->getFirstNonPhi());
8828         continue;
8829       }
8830     }
8831     Sink->moveAfter(Target);
8832   }
8833 
8834   // Interleave memory: for each Interleave Group we marked earlier as relevant
8835   // for this VPlan, replace the Recipes widening its memory instructions with a
8836   // single VPInterleaveRecipe at its insertion point.
8837   for (auto IG : InterleaveGroups) {
8838     auto *Recipe = cast<VPWidenMemoryInstructionRecipe>(
8839         RecipeBuilder.getRecipe(IG->getInsertPos()));
8840     SmallVector<VPValue *, 4> StoredValues;
8841     for (unsigned i = 0; i < IG->getFactor(); ++i)
8842       if (auto *SI = dyn_cast_or_null<StoreInst>(IG->getMember(i)))
8843         StoredValues.push_back(Plan->getOrAddVPValue(SI->getOperand(0)));
8844 
8845     auto *VPIG = new VPInterleaveRecipe(IG, Recipe->getAddr(), StoredValues,
8846                                         Recipe->getMask());
8847     VPIG->insertBefore(Recipe);
8848     unsigned J = 0;
8849     for (unsigned i = 0; i < IG->getFactor(); ++i)
8850       if (Instruction *Member = IG->getMember(i)) {
8851         if (!Member->getType()->isVoidTy()) {
8852           VPValue *OriginalV = Plan->getVPValue(Member);
8853           Plan->removeVPValueFor(Member);
8854           Plan->addVPValue(Member, VPIG->getVPValue(J));
8855           OriginalV->replaceAllUsesWith(VPIG->getVPValue(J));
8856           J++;
8857         }
8858         RecipeBuilder.getRecipe(Member)->eraseFromParent();
8859       }
8860   }
8861 
8862   // Adjust the recipes for any inloop reductions.
8863   if (Range.Start.isVector())
8864     adjustRecipesForInLoopReductions(Plan, RecipeBuilder);
8865 
8866   // Finally, if tail is folded by masking, introduce selects between the phi
8867   // and the live-out instruction of each reduction, at the end of the latch.
8868   if (CM.foldTailByMasking() && !Legal->getReductionVars().empty()) {
8869     Builder.setInsertPoint(VPBB);
8870     auto *Cond = RecipeBuilder.createBlockInMask(OrigLoop->getHeader(), Plan);
8871     for (auto &Reduction : Legal->getReductionVars()) {
8872       if (CM.isInLoopReduction(Reduction.first))
8873         continue;
8874       VPValue *Phi = Plan->getOrAddVPValue(Reduction.first);
8875       VPValue *Red = Plan->getOrAddVPValue(Reduction.second.getLoopExitInstr());
8876       Builder.createNaryOp(Instruction::Select, {Cond, Red, Phi});
8877     }
8878   }
8879 
8880   std::string PlanName;
8881   raw_string_ostream RSO(PlanName);
8882   ElementCount VF = Range.Start;
8883   Plan->addVF(VF);
8884   RSO << "Initial VPlan for VF={" << VF;
8885   for (VF *= 2; ElementCount::isKnownLT(VF, Range.End); VF *= 2) {
8886     Plan->addVF(VF);
8887     RSO << "," << VF;
8888   }
8889   RSO << "},UF>=1";
8890   RSO.flush();
8891   Plan->setName(PlanName);
8892 
8893   return Plan;
8894 }
8895 
8896 VPlanPtr LoopVectorizationPlanner::buildVPlan(VFRange &Range) {
8897   // Outer loop handling: They may require CFG and instruction level
8898   // transformations before even evaluating whether vectorization is profitable.
8899   // Since we cannot modify the incoming IR, we need to build VPlan upfront in
8900   // the vectorization pipeline.
8901   assert(!OrigLoop->isInnermost());
8902   assert(EnableVPlanNativePath && "VPlan-native path is not enabled.");
8903 
8904   // Create new empty VPlan
8905   auto Plan = std::make_unique<VPlan>();
8906 
8907   // Build hierarchical CFG
8908   VPlanHCFGBuilder HCFGBuilder(OrigLoop, LI, *Plan);
8909   HCFGBuilder.buildHierarchicalCFG();
8910 
8911   for (ElementCount VF = Range.Start; ElementCount::isKnownLT(VF, Range.End);
8912        VF *= 2)
8913     Plan->addVF(VF);
8914 
8915   if (EnableVPlanPredication) {
8916     VPlanPredicator VPP(*Plan);
8917     VPP.predicate();
8918 
8919     // Avoid running transformation to recipes until masked code generation in
8920     // VPlan-native path is in place.
8921     return Plan;
8922   }
8923 
8924   SmallPtrSet<Instruction *, 1> DeadInstructions;
8925   VPlanTransforms::VPInstructionsToVPRecipes(
8926       OrigLoop, Plan, Legal->getInductionVars(), DeadInstructions);
8927   return Plan;
8928 }
8929 
8930 // Adjust the recipes for any inloop reductions. The chain of instructions
8931 // leading from the loop exit instr to the phi need to be converted to
8932 // reductions, with one operand being vector and the other being the scalar
8933 // reduction chain.
8934 void LoopVectorizationPlanner::adjustRecipesForInLoopReductions(
8935     VPlanPtr &Plan, VPRecipeBuilder &RecipeBuilder) {
8936   for (auto &Reduction : CM.getInLoopReductionChains()) {
8937     PHINode *Phi = Reduction.first;
8938     RecurrenceDescriptor &RdxDesc = Legal->getReductionVars()[Phi];
8939     const SmallVector<Instruction *, 4> &ReductionOperations = Reduction.second;
8940 
8941     // ReductionOperations are orders top-down from the phi's use to the
8942     // LoopExitValue. We keep a track of the previous item (the Chain) to tell
8943     // which of the two operands will remain scalar and which will be reduced.
8944     // For minmax the chain will be the select instructions.
8945     Instruction *Chain = Phi;
8946     for (Instruction *R : ReductionOperations) {
8947       VPRecipeBase *WidenRecipe = RecipeBuilder.getRecipe(R);
8948       RecurKind Kind = RdxDesc.getRecurrenceKind();
8949 
8950       VPValue *ChainOp = Plan->getVPValue(Chain);
8951       unsigned FirstOpId;
8952       if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind)) {
8953         assert(isa<VPWidenSelectRecipe>(WidenRecipe) &&
8954                "Expected to replace a VPWidenSelectSC");
8955         FirstOpId = 1;
8956       } else {
8957         assert(isa<VPWidenRecipe>(WidenRecipe) &&
8958                "Expected to replace a VPWidenSC");
8959         FirstOpId = 0;
8960       }
8961       unsigned VecOpId =
8962           R->getOperand(FirstOpId) == Chain ? FirstOpId + 1 : FirstOpId;
8963       VPValue *VecOp = Plan->getVPValue(R->getOperand(VecOpId));
8964 
8965       auto *CondOp = CM.foldTailByMasking()
8966                          ? RecipeBuilder.createBlockInMask(R->getParent(), Plan)
8967                          : nullptr;
8968       VPReductionRecipe *RedRecipe = new VPReductionRecipe(
8969           &RdxDesc, R, ChainOp, VecOp, CondOp, TTI);
8970       WidenRecipe->getVPValue()->replaceAllUsesWith(RedRecipe);
8971       Plan->removeVPValueFor(R);
8972       Plan->addVPValue(R, RedRecipe);
8973       WidenRecipe->getParent()->insert(RedRecipe, WidenRecipe->getIterator());
8974       WidenRecipe->getVPValue()->replaceAllUsesWith(RedRecipe);
8975       WidenRecipe->eraseFromParent();
8976 
8977       if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind)) {
8978         VPRecipeBase *CompareRecipe =
8979             RecipeBuilder.getRecipe(cast<Instruction>(R->getOperand(0)));
8980         assert(isa<VPWidenRecipe>(CompareRecipe) &&
8981                "Expected to replace a VPWidenSC");
8982         assert(cast<VPWidenRecipe>(CompareRecipe)->getNumUsers() == 0 &&
8983                "Expected no remaining users");
8984         CompareRecipe->eraseFromParent();
8985       }
8986       Chain = R;
8987     }
8988   }
8989 }
8990 
8991 Value* LoopVectorizationPlanner::VPCallbackILV::
8992 getOrCreateVectorValues(Value *V, unsigned Part) {
8993       return ILV.getOrCreateVectorValue(V, Part);
8994 }
8995 
8996 Value *LoopVectorizationPlanner::VPCallbackILV::getOrCreateScalarValue(
8997     Value *V, const VPIteration &Instance) {
8998   return ILV.getOrCreateScalarValue(V, Instance);
8999 }
9000 
9001 void VPInterleaveRecipe::print(raw_ostream &O, const Twine &Indent,
9002                                VPSlotTracker &SlotTracker) const {
9003   O << "\"INTERLEAVE-GROUP with factor " << IG->getFactor() << " at ";
9004   IG->getInsertPos()->printAsOperand(O, false);
9005   O << ", ";
9006   getAddr()->printAsOperand(O, SlotTracker);
9007   VPValue *Mask = getMask();
9008   if (Mask) {
9009     O << ", ";
9010     Mask->printAsOperand(O, SlotTracker);
9011   }
9012   for (unsigned i = 0; i < IG->getFactor(); ++i)
9013     if (Instruction *I = IG->getMember(i))
9014       O << "\\l\" +\n" << Indent << "\"  " << VPlanIngredient(I) << " " << i;
9015 }
9016 
9017 void VPWidenCallRecipe::execute(VPTransformState &State) {
9018   State.ILV->widenCallInstruction(*cast<CallInst>(getUnderlyingInstr()), this,
9019                                   *this, State);
9020 }
9021 
9022 void VPWidenSelectRecipe::execute(VPTransformState &State) {
9023   State.ILV->widenSelectInstruction(*cast<SelectInst>(getUnderlyingInstr()),
9024                                     this, *this, InvariantCond, State);
9025 }
9026 
9027 void VPWidenRecipe::execute(VPTransformState &State) {
9028   State.ILV->widenInstruction(*getUnderlyingInstr(), this, *this, State);
9029 }
9030 
9031 void VPWidenGEPRecipe::execute(VPTransformState &State) {
9032   State.ILV->widenGEP(cast<GetElementPtrInst>(getUnderlyingInstr()), this,
9033                       *this, State.UF, State.VF, IsPtrLoopInvariant,
9034                       IsIndexLoopInvariant, State);
9035 }
9036 
9037 void VPWidenIntOrFpInductionRecipe::execute(VPTransformState &State) {
9038   assert(!State.Instance && "Int or FP induction being replicated.");
9039   State.ILV->widenIntOrFpInduction(IV, getStartValue()->getLiveInIRValue(),
9040                                    getTruncInst(), getVPValue(0),
9041                                    getCastValue(), State);
9042 }
9043 
9044 void VPWidenPHIRecipe::execute(VPTransformState &State) {
9045   Value *StartV =
9046       getStartValue() ? getStartValue()->getLiveInIRValue() : nullptr;
9047   State.ILV->widenPHIInstruction(Phi, RdxDesc, StartV, State.UF, State.VF);
9048 }
9049 
9050 void VPBlendRecipe::execute(VPTransformState &State) {
9051   State.ILV->setDebugLocFromInst(State.Builder, Phi);
9052   // We know that all PHIs in non-header blocks are converted into
9053   // selects, so we don't have to worry about the insertion order and we
9054   // can just use the builder.
9055   // At this point we generate the predication tree. There may be
9056   // duplications since this is a simple recursive scan, but future
9057   // optimizations will clean it up.
9058 
9059   unsigned NumIncoming = getNumIncomingValues();
9060 
9061   // Generate a sequence of selects of the form:
9062   // SELECT(Mask3, In3,
9063   //        SELECT(Mask2, In2,
9064   //               SELECT(Mask1, In1,
9065   //                      In0)))
9066   // Note that Mask0 is never used: lanes for which no path reaches this phi and
9067   // are essentially undef are taken from In0.
9068   InnerLoopVectorizer::VectorParts Entry(State.UF);
9069   for (unsigned In = 0; In < NumIncoming; ++In) {
9070     for (unsigned Part = 0; Part < State.UF; ++Part) {
9071       // We might have single edge PHIs (blocks) - use an identity
9072       // 'select' for the first PHI operand.
9073       Value *In0 = State.get(getIncomingValue(In), Part);
9074       if (In == 0)
9075         Entry[Part] = In0; // Initialize with the first incoming value.
9076       else {
9077         // Select between the current value and the previous incoming edge
9078         // based on the incoming mask.
9079         Value *Cond = State.get(getMask(In), Part);
9080         Entry[Part] =
9081             State.Builder.CreateSelect(Cond, In0, Entry[Part], "predphi");
9082       }
9083     }
9084   }
9085   for (unsigned Part = 0; Part < State.UF; ++Part)
9086     State.ValueMap.setVectorValue(Phi, Part, Entry[Part]);
9087 }
9088 
9089 void VPInterleaveRecipe::execute(VPTransformState &State) {
9090   assert(!State.Instance && "Interleave group being replicated.");
9091   State.ILV->vectorizeInterleaveGroup(IG, definedValues(), State, getAddr(),
9092                                       getStoredValues(), getMask());
9093 }
9094 
9095 void VPReductionRecipe::execute(VPTransformState &State) {
9096   assert(!State.Instance && "Reduction being replicated.");
9097   for (unsigned Part = 0; Part < State.UF; ++Part) {
9098     RecurKind Kind = RdxDesc->getRecurrenceKind();
9099     Value *NewVecOp = State.get(getVecOp(), Part);
9100     if (VPValue *Cond = getCondOp()) {
9101       Value *NewCond = State.get(Cond, Part);
9102       VectorType *VecTy = cast<VectorType>(NewVecOp->getType());
9103       Constant *Iden = RecurrenceDescriptor::getRecurrenceIdentity(
9104           Kind, VecTy->getElementType());
9105       Constant *IdenVec =
9106           ConstantVector::getSplat(VecTy->getElementCount(), Iden);
9107       Value *Select = State.Builder.CreateSelect(NewCond, NewVecOp, IdenVec);
9108       NewVecOp = Select;
9109     }
9110     Value *NewRed =
9111         createTargetReduction(State.Builder, TTI, *RdxDesc, NewVecOp);
9112     Value *PrevInChain = State.get(getChainOp(), Part);
9113     Value *NextInChain;
9114     if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind)) {
9115       NextInChain =
9116           createMinMaxOp(State.Builder, RdxDesc->getRecurrenceKind(),
9117                          NewRed, PrevInChain);
9118     } else {
9119       NextInChain = State.Builder.CreateBinOp(
9120           (Instruction::BinaryOps)getUnderlyingInstr()->getOpcode(), NewRed,
9121           PrevInChain);
9122     }
9123     State.set(this, getUnderlyingInstr(), NextInChain, Part);
9124   }
9125 }
9126 
9127 void VPReplicateRecipe::execute(VPTransformState &State) {
9128   if (State.Instance) { // Generate a single instance.
9129     assert(!State.VF.isScalable() && "Can't scalarize a scalable vector");
9130     State.ILV->scalarizeInstruction(getUnderlyingInstr(), *this,
9131                                     *State.Instance, IsPredicated, State);
9132     // Insert scalar instance packing it into a vector.
9133     if (AlsoPack && State.VF.isVector()) {
9134       // If we're constructing lane 0, initialize to start from poison.
9135       if (State.Instance->Lane == 0) {
9136         assert(!State.VF.isScalable() && "VF is assumed to be non scalable.");
9137         Value *Poison = PoisonValue::get(
9138             VectorType::get(getUnderlyingValue()->getType(), State.VF));
9139         State.ValueMap.setVectorValue(getUnderlyingInstr(),
9140                                       State.Instance->Part, Poison);
9141       }
9142       State.ILV->packScalarIntoVectorValue(getUnderlyingInstr(),
9143                                            *State.Instance);
9144     }
9145     return;
9146   }
9147 
9148   // Generate scalar instances for all VF lanes of all UF parts, unless the
9149   // instruction is uniform inwhich case generate only the first lane for each
9150   // of the UF parts.
9151   unsigned EndLane = IsUniform ? 1 : State.VF.getKnownMinValue();
9152   assert((!State.VF.isScalable() || IsUniform) &&
9153          "Can't scalarize a scalable vector");
9154   for (unsigned Part = 0; Part < State.UF; ++Part)
9155     for (unsigned Lane = 0; Lane < EndLane; ++Lane)
9156       State.ILV->scalarizeInstruction(getUnderlyingInstr(), *this,
9157                                       VPIteration(Part, Lane), IsPredicated,
9158                                       State);
9159 }
9160 
9161 void VPBranchOnMaskRecipe::execute(VPTransformState &State) {
9162   assert(State.Instance && "Branch on Mask works only on single instance.");
9163 
9164   unsigned Part = State.Instance->Part;
9165   unsigned Lane = State.Instance->Lane;
9166 
9167   Value *ConditionBit = nullptr;
9168   VPValue *BlockInMask = getMask();
9169   if (BlockInMask) {
9170     ConditionBit = State.get(BlockInMask, Part);
9171     if (ConditionBit->getType()->isVectorTy())
9172       ConditionBit = State.Builder.CreateExtractElement(
9173           ConditionBit, State.Builder.getInt32(Lane));
9174   } else // Block in mask is all-one.
9175     ConditionBit = State.Builder.getTrue();
9176 
9177   // Replace the temporary unreachable terminator with a new conditional branch,
9178   // whose two destinations will be set later when they are created.
9179   auto *CurrentTerminator = State.CFG.PrevBB->getTerminator();
9180   assert(isa<UnreachableInst>(CurrentTerminator) &&
9181          "Expected to replace unreachable terminator with conditional branch.");
9182   auto *CondBr = BranchInst::Create(State.CFG.PrevBB, nullptr, ConditionBit);
9183   CondBr->setSuccessor(0, nullptr);
9184   ReplaceInstWithInst(CurrentTerminator, CondBr);
9185 }
9186 
9187 void VPPredInstPHIRecipe::execute(VPTransformState &State) {
9188   assert(State.Instance && "Predicated instruction PHI works per instance.");
9189   Instruction *ScalarPredInst =
9190       cast<Instruction>(State.get(getOperand(0), *State.Instance));
9191   BasicBlock *PredicatedBB = ScalarPredInst->getParent();
9192   BasicBlock *PredicatingBB = PredicatedBB->getSinglePredecessor();
9193   assert(PredicatingBB && "Predicated block has no single predecessor.");
9194 
9195   // By current pack/unpack logic we need to generate only a single phi node: if
9196   // a vector value for the predicated instruction exists at this point it means
9197   // the instruction has vector users only, and a phi for the vector value is
9198   // needed. In this case the recipe of the predicated instruction is marked to
9199   // also do that packing, thereby "hoisting" the insert-element sequence.
9200   // Otherwise, a phi node for the scalar value is needed.
9201   unsigned Part = State.Instance->Part;
9202   Instruction *PredInst =
9203       cast<Instruction>(getOperand(0)->getUnderlyingValue());
9204   if (State.ValueMap.hasVectorValue(PredInst, Part)) {
9205     Value *VectorValue = State.ValueMap.getVectorValue(PredInst, Part);
9206     InsertElementInst *IEI = cast<InsertElementInst>(VectorValue);
9207     PHINode *VPhi = State.Builder.CreatePHI(IEI->getType(), 2);
9208     VPhi->addIncoming(IEI->getOperand(0), PredicatingBB); // Unmodified vector.
9209     VPhi->addIncoming(IEI, PredicatedBB); // New vector with inserted element.
9210     State.ValueMap.resetVectorValue(PredInst, Part, VPhi); // Update cache.
9211   } else {
9212     Type *PredInstType = PredInst->getType();
9213     PHINode *Phi = State.Builder.CreatePHI(PredInstType, 2);
9214     Phi->addIncoming(PoisonValue::get(ScalarPredInst->getType()), PredicatingBB);
9215     Phi->addIncoming(ScalarPredInst, PredicatedBB);
9216     State.ValueMap.resetScalarValue(PredInst, *State.Instance, Phi);
9217   }
9218 }
9219 
9220 void VPWidenMemoryInstructionRecipe::execute(VPTransformState &State) {
9221   VPValue *StoredValue = isStore() ? getStoredValue() : nullptr;
9222   State.ILV->vectorizeMemoryInstruction(&Ingredient, State,
9223                                         StoredValue ? nullptr : getVPValue(),
9224                                         getAddr(), StoredValue, getMask());
9225 }
9226 
9227 // Determine how to lower the scalar epilogue, which depends on 1) optimising
9228 // for minimum code-size, 2) predicate compiler options, 3) loop hints forcing
9229 // predication, and 4) a TTI hook that analyses whether the loop is suitable
9230 // for predication.
9231 static ScalarEpilogueLowering getScalarEpilogueLowering(
9232     Function *F, Loop *L, LoopVectorizeHints &Hints, ProfileSummaryInfo *PSI,
9233     BlockFrequencyInfo *BFI, TargetTransformInfo *TTI, TargetLibraryInfo *TLI,
9234     AssumptionCache *AC, LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT,
9235     LoopVectorizationLegality &LVL) {
9236   // 1) OptSize takes precedence over all other options, i.e. if this is set,
9237   // don't look at hints or options, and don't request a scalar epilogue.
9238   // (For PGSO, as shouldOptimizeForSize isn't currently accessible from
9239   // LoopAccessInfo (due to code dependency and not being able to reliably get
9240   // PSI/BFI from a loop analysis under NPM), we cannot suppress the collection
9241   // of strides in LoopAccessInfo::analyzeLoop() and vectorize without
9242   // versioning when the vectorization is forced, unlike hasOptSize. So revert
9243   // back to the old way and vectorize with versioning when forced. See D81345.)
9244   if (F->hasOptSize() || (llvm::shouldOptimizeForSize(L->getHeader(), PSI, BFI,
9245                                                       PGSOQueryType::IRPass) &&
9246                           Hints.getForce() != LoopVectorizeHints::FK_Enabled))
9247     return CM_ScalarEpilogueNotAllowedOptSize;
9248 
9249   // 2) If set, obey the directives
9250   if (PreferPredicateOverEpilogue.getNumOccurrences()) {
9251     switch (PreferPredicateOverEpilogue) {
9252     case PreferPredicateTy::ScalarEpilogue:
9253       return CM_ScalarEpilogueAllowed;
9254     case PreferPredicateTy::PredicateElseScalarEpilogue:
9255       return CM_ScalarEpilogueNotNeededUsePredicate;
9256     case PreferPredicateTy::PredicateOrDontVectorize:
9257       return CM_ScalarEpilogueNotAllowedUsePredicate;
9258     };
9259   }
9260 
9261   // 3) If set, obey the hints
9262   switch (Hints.getPredicate()) {
9263   case LoopVectorizeHints::FK_Enabled:
9264     return CM_ScalarEpilogueNotNeededUsePredicate;
9265   case LoopVectorizeHints::FK_Disabled:
9266     return CM_ScalarEpilogueAllowed;
9267   };
9268 
9269   // 4) if the TTI hook indicates this is profitable, request predication.
9270   if (TTI->preferPredicateOverEpilogue(L, LI, *SE, *AC, TLI, DT,
9271                                        LVL.getLAI()))
9272     return CM_ScalarEpilogueNotNeededUsePredicate;
9273 
9274   return CM_ScalarEpilogueAllowed;
9275 }
9276 
9277 void VPTransformState::set(VPValue *Def, Value *IRDef, Value *V,
9278                            const VPIteration &Instance) {
9279   set(Def, V, Instance);
9280   ILV->setScalarValue(IRDef, Instance, V);
9281 }
9282 
9283 void VPTransformState::set(VPValue *Def, Value *IRDef, Value *V,
9284                            unsigned Part) {
9285   set(Def, V, Part);
9286   ILV->setVectorValue(IRDef, Part, V);
9287 }
9288 
9289 void VPTransformState::reset(VPValue *Def, Value *IRDef, Value *V,
9290                              unsigned Part) {
9291   set(Def, V, Part);
9292   ILV->resetVectorValue(IRDef, Part, V);
9293 }
9294 
9295 Value *VPTransformState::get(VPValue *Def, unsigned Part) {
9296   // If Values have been set for this Def return the one relevant for \p Part.
9297   if (hasVectorValue(Def, Part))
9298     return Data.PerPartOutput[Def][Part];
9299 
9300   // TODO: Remove the callback once all scalar recipes are managed using
9301   // VPValues.
9302   if (!hasScalarValue(Def, {Part, 0}))
9303     return Callback.getOrCreateVectorValues(VPValue2Value[Def], Part);
9304 
9305   Value *ScalarValue = get(Def, {Part, 0});
9306   // If we aren't vectorizing, we can just copy the scalar map values over
9307   // to the vector map.
9308   if (VF.isScalar()) {
9309     set(Def, ScalarValue, Part);
9310     return ScalarValue;
9311   }
9312 
9313   auto *RepR = dyn_cast<VPReplicateRecipe>(Def);
9314   bool IsUniform = RepR && RepR->isUniform();
9315 
9316   unsigned LastLane = IsUniform ? 0 : VF.getKnownMinValue() - 1;
9317   auto *LastInst = cast<Instruction>(get(Def, {Part, LastLane}));
9318 
9319   // Set the insert point after the last scalarized instruction. This
9320   // ensures the insertelement sequence will directly follow the scalar
9321   // definitions.
9322   auto OldIP = Builder.saveIP();
9323   auto NewIP = std::next(BasicBlock::iterator(LastInst));
9324   Builder.SetInsertPoint(&*NewIP);
9325 
9326   // However, if we are vectorizing, we need to construct the vector values.
9327   // If the value is known to be uniform after vectorization, we can just
9328   // broadcast the scalar value corresponding to lane zero for each unroll
9329   // iteration. Otherwise, we construct the vector values using
9330   // insertelement instructions. Since the resulting vectors are stored in
9331   // VectorLoopValueMap, we will only generate the insertelements once.
9332   Value *VectorValue = nullptr;
9333   if (IsUniform) {
9334     VectorValue = ILV->getBroadcastInstrs(ScalarValue);
9335     set(Def, VectorValue, Part);
9336   } else {
9337     // Initialize packing with insertelements to start from undef.
9338     assert(!VF.isScalable() && "VF is assumed to be non scalable.");
9339     Value *Undef = UndefValue::get(VectorType::get(LastInst->getType(), VF));
9340     set(Def, Undef, Part);
9341     for (unsigned Lane = 0; Lane < VF.getKnownMinValue(); ++Lane)
9342       ILV->packScalarIntoVectorValue(Def, {Part, Lane}, *this);
9343     VectorValue = get(Def, Part);
9344   }
9345   Builder.restoreIP(OldIP);
9346   return VectorValue;
9347 }
9348 
9349 // Process the loop in the VPlan-native vectorization path. This path builds
9350 // VPlan upfront in the vectorization pipeline, which allows to apply
9351 // VPlan-to-VPlan transformations from the very beginning without modifying the
9352 // input LLVM IR.
9353 static bool processLoopInVPlanNativePath(
9354     Loop *L, PredicatedScalarEvolution &PSE, LoopInfo *LI, DominatorTree *DT,
9355     LoopVectorizationLegality *LVL, TargetTransformInfo *TTI,
9356     TargetLibraryInfo *TLI, DemandedBits *DB, AssumptionCache *AC,
9357     OptimizationRemarkEmitter *ORE, BlockFrequencyInfo *BFI,
9358     ProfileSummaryInfo *PSI, LoopVectorizeHints &Hints) {
9359 
9360   if (isa<SCEVCouldNotCompute>(PSE.getBackedgeTakenCount())) {
9361     LLVM_DEBUG(dbgs() << "LV: cannot compute the outer-loop trip count\n");
9362     return false;
9363   }
9364   assert(EnableVPlanNativePath && "VPlan-native path is disabled.");
9365   Function *F = L->getHeader()->getParent();
9366   InterleavedAccessInfo IAI(PSE, L, DT, LI, LVL->getLAI());
9367 
9368   ScalarEpilogueLowering SEL = getScalarEpilogueLowering(
9369       F, L, Hints, PSI, BFI, TTI, TLI, AC, LI, PSE.getSE(), DT, *LVL);
9370 
9371   LoopVectorizationCostModel CM(SEL, L, PSE, LI, LVL, *TTI, TLI, DB, AC, ORE, F,
9372                                 &Hints, IAI);
9373   // Use the planner for outer loop vectorization.
9374   // TODO: CM is not used at this point inside the planner. Turn CM into an
9375   // optional argument if we don't need it in the future.
9376   LoopVectorizationPlanner LVP(L, LI, TLI, TTI, LVL, CM, IAI, PSE);
9377 
9378   // Get user vectorization factor.
9379   ElementCount UserVF = Hints.getWidth();
9380 
9381   // Plan how to best vectorize, return the best VF and its cost.
9382   const VectorizationFactor VF = LVP.planInVPlanNativePath(UserVF);
9383 
9384   // If we are stress testing VPlan builds, do not attempt to generate vector
9385   // code. Masked vector code generation support will follow soon.
9386   // Also, do not attempt to vectorize if no vector code will be produced.
9387   if (VPlanBuildStressTest || EnableVPlanPredication ||
9388       VectorizationFactor::Disabled() == VF)
9389     return false;
9390 
9391   LVP.setBestPlan(VF.Width, 1);
9392 
9393   InnerLoopVectorizer LB(L, PSE, LI, DT, TLI, TTI, AC, ORE, VF.Width, 1, LVL,
9394                          &CM, BFI, PSI);
9395   LLVM_DEBUG(dbgs() << "Vectorizing outer loop in \""
9396                     << L->getHeader()->getParent()->getName() << "\"\n");
9397   LVP.executePlan(LB, DT);
9398 
9399   // Mark the loop as already vectorized to avoid vectorizing again.
9400   Hints.setAlreadyVectorized();
9401 
9402   assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()));
9403   return true;
9404 }
9405 
9406 LoopVectorizePass::LoopVectorizePass(LoopVectorizeOptions Opts)
9407     : InterleaveOnlyWhenForced(Opts.InterleaveOnlyWhenForced ||
9408                                !EnableLoopInterleaving),
9409       VectorizeOnlyWhenForced(Opts.VectorizeOnlyWhenForced ||
9410                               !EnableLoopVectorization) {}
9411 
9412 bool LoopVectorizePass::processLoop(Loop *L) {
9413   assert((EnableVPlanNativePath || L->isInnermost()) &&
9414          "VPlan-native path is not enabled. Only process inner loops.");
9415 
9416 #ifndef NDEBUG
9417   const std::string DebugLocStr = getDebugLocString(L);
9418 #endif /* NDEBUG */
9419 
9420   LLVM_DEBUG(dbgs() << "\nLV: Checking a loop in \""
9421                     << L->getHeader()->getParent()->getName() << "\" from "
9422                     << DebugLocStr << "\n");
9423 
9424   LoopVectorizeHints Hints(L, InterleaveOnlyWhenForced, *ORE);
9425 
9426   LLVM_DEBUG(
9427       dbgs() << "LV: Loop hints:"
9428              << " force="
9429              << (Hints.getForce() == LoopVectorizeHints::FK_Disabled
9430                      ? "disabled"
9431                      : (Hints.getForce() == LoopVectorizeHints::FK_Enabled
9432                             ? "enabled"
9433                             : "?"))
9434              << " width=" << Hints.getWidth()
9435              << " unroll=" << Hints.getInterleave() << "\n");
9436 
9437   // Function containing loop
9438   Function *F = L->getHeader()->getParent();
9439 
9440   // Looking at the diagnostic output is the only way to determine if a loop
9441   // was vectorized (other than looking at the IR or machine code), so it
9442   // is important to generate an optimization remark for each loop. Most of
9443   // these messages are generated as OptimizationRemarkAnalysis. Remarks
9444   // generated as OptimizationRemark and OptimizationRemarkMissed are
9445   // less verbose reporting vectorized loops and unvectorized loops that may
9446   // benefit from vectorization, respectively.
9447 
9448   if (!Hints.allowVectorization(F, L, VectorizeOnlyWhenForced)) {
9449     LLVM_DEBUG(dbgs() << "LV: Loop hints prevent vectorization.\n");
9450     return false;
9451   }
9452 
9453   PredicatedScalarEvolution PSE(*SE, *L);
9454 
9455   // Check if it is legal to vectorize the loop.
9456   LoopVectorizationRequirements Requirements(*ORE);
9457   LoopVectorizationLegality LVL(L, PSE, DT, TTI, TLI, AA, F, GetLAA, LI, ORE,
9458                                 &Requirements, &Hints, DB, AC, BFI, PSI);
9459   if (!LVL.canVectorize(EnableVPlanNativePath)) {
9460     LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
9461     Hints.emitRemarkWithHints();
9462     return false;
9463   }
9464 
9465   // Check the function attributes and profiles to find out if this function
9466   // should be optimized for size.
9467   ScalarEpilogueLowering SEL = getScalarEpilogueLowering(
9468       F, L, Hints, PSI, BFI, TTI, TLI, AC, LI, PSE.getSE(), DT, LVL);
9469 
9470   // Entrance to the VPlan-native vectorization path. Outer loops are processed
9471   // here. They may require CFG and instruction level transformations before
9472   // even evaluating whether vectorization is profitable. Since we cannot modify
9473   // the incoming IR, we need to build VPlan upfront in the vectorization
9474   // pipeline.
9475   if (!L->isInnermost())
9476     return processLoopInVPlanNativePath(L, PSE, LI, DT, &LVL, TTI, TLI, DB, AC,
9477                                         ORE, BFI, PSI, Hints);
9478 
9479   assert(L->isInnermost() && "Inner loop expected.");
9480 
9481   // Check the loop for a trip count threshold: vectorize loops with a tiny trip
9482   // count by optimizing for size, to minimize overheads.
9483   auto ExpectedTC = getSmallBestKnownTC(*SE, L);
9484   if (ExpectedTC && *ExpectedTC < TinyTripCountVectorThreshold) {
9485     LLVM_DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "
9486                       << "This loop is worth vectorizing only if no scalar "
9487                       << "iteration overheads are incurred.");
9488     if (Hints.getForce() == LoopVectorizeHints::FK_Enabled)
9489       LLVM_DEBUG(dbgs() << " But vectorizing was explicitly forced.\n");
9490     else {
9491       LLVM_DEBUG(dbgs() << "\n");
9492       SEL = CM_ScalarEpilogueNotAllowedLowTripLoop;
9493     }
9494   }
9495 
9496   // Check the function attributes to see if implicit floats are allowed.
9497   // FIXME: This check doesn't seem possibly correct -- what if the loop is
9498   // an integer loop and the vector instructions selected are purely integer
9499   // vector instructions?
9500   if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
9501     reportVectorizationFailure(
9502         "Can't vectorize when the NoImplicitFloat attribute is used",
9503         "loop not vectorized due to NoImplicitFloat attribute",
9504         "NoImplicitFloat", ORE, L);
9505     Hints.emitRemarkWithHints();
9506     return false;
9507   }
9508 
9509   // Check if the target supports potentially unsafe FP vectorization.
9510   // FIXME: Add a check for the type of safety issue (denormal, signaling)
9511   // for the target we're vectorizing for, to make sure none of the
9512   // additional fp-math flags can help.
9513   if (Hints.isPotentiallyUnsafe() &&
9514       TTI->isFPVectorizationPotentiallyUnsafe()) {
9515     reportVectorizationFailure(
9516         "Potentially unsafe FP op prevents vectorization",
9517         "loop not vectorized due to unsafe FP support.",
9518         "UnsafeFP", ORE, L);
9519     Hints.emitRemarkWithHints();
9520     return false;
9521   }
9522 
9523   bool UseInterleaved = TTI->enableInterleavedAccessVectorization();
9524   InterleavedAccessInfo IAI(PSE, L, DT, LI, LVL.getLAI());
9525 
9526   // If an override option has been passed in for interleaved accesses, use it.
9527   if (EnableInterleavedMemAccesses.getNumOccurrences() > 0)
9528     UseInterleaved = EnableInterleavedMemAccesses;
9529 
9530   // Analyze interleaved memory accesses.
9531   if (UseInterleaved) {
9532     IAI.analyzeInterleaving(useMaskedInterleavedAccesses(*TTI));
9533   }
9534 
9535   // Use the cost model.
9536   LoopVectorizationCostModel CM(SEL, L, PSE, LI, &LVL, *TTI, TLI, DB, AC, ORE,
9537                                 F, &Hints, IAI);
9538   CM.collectValuesToIgnore();
9539 
9540   // Use the planner for vectorization.
9541   LoopVectorizationPlanner LVP(L, LI, TLI, TTI, &LVL, CM, IAI, PSE);
9542 
9543   // Get user vectorization factor and interleave count.
9544   ElementCount UserVF = Hints.getWidth();
9545   unsigned UserIC = Hints.getInterleave();
9546 
9547   // Plan how to best vectorize, return the best VF and its cost.
9548   Optional<VectorizationFactor> MaybeVF = LVP.plan(UserVF, UserIC);
9549 
9550   VectorizationFactor VF = VectorizationFactor::Disabled();
9551   unsigned IC = 1;
9552 
9553   if (MaybeVF) {
9554     VF = *MaybeVF;
9555     // Select the interleave count.
9556     IC = CM.selectInterleaveCount(VF.Width, VF.Cost);
9557   }
9558 
9559   // Identify the diagnostic messages that should be produced.
9560   std::pair<StringRef, std::string> VecDiagMsg, IntDiagMsg;
9561   bool VectorizeLoop = true, InterleaveLoop = true;
9562   if (Requirements.doesNotMeet(F, L, Hints)) {
9563     LLVM_DEBUG(dbgs() << "LV: Not vectorizing: loop did not meet vectorization "
9564                          "requirements.\n");
9565     Hints.emitRemarkWithHints();
9566     return false;
9567   }
9568 
9569   if (VF.Width.isScalar()) {
9570     LLVM_DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
9571     VecDiagMsg = std::make_pair(
9572         "VectorizationNotBeneficial",
9573         "the cost-model indicates that vectorization is not beneficial");
9574     VectorizeLoop = false;
9575   }
9576 
9577   if (!MaybeVF && UserIC > 1) {
9578     // Tell the user interleaving was avoided up-front, despite being explicitly
9579     // requested.
9580     LLVM_DEBUG(dbgs() << "LV: Ignoring UserIC, because vectorization and "
9581                          "interleaving should be avoided up front\n");
9582     IntDiagMsg = std::make_pair(
9583         "InterleavingAvoided",
9584         "Ignoring UserIC, because interleaving was avoided up front");
9585     InterleaveLoop = false;
9586   } else if (IC == 1 && UserIC <= 1) {
9587     // Tell the user interleaving is not beneficial.
9588     LLVM_DEBUG(dbgs() << "LV: Interleaving is not beneficial.\n");
9589     IntDiagMsg = std::make_pair(
9590         "InterleavingNotBeneficial",
9591         "the cost-model indicates that interleaving is not beneficial");
9592     InterleaveLoop = false;
9593     if (UserIC == 1) {
9594       IntDiagMsg.first = "InterleavingNotBeneficialAndDisabled";
9595       IntDiagMsg.second +=
9596           " and is explicitly disabled or interleave count is set to 1";
9597     }
9598   } else if (IC > 1 && UserIC == 1) {
9599     // Tell the user interleaving is beneficial, but it explicitly disabled.
9600     LLVM_DEBUG(
9601         dbgs() << "LV: Interleaving is beneficial but is explicitly disabled.");
9602     IntDiagMsg = std::make_pair(
9603         "InterleavingBeneficialButDisabled",
9604         "the cost-model indicates that interleaving is beneficial "
9605         "but is explicitly disabled or interleave count is set to 1");
9606     InterleaveLoop = false;
9607   }
9608 
9609   // Override IC if user provided an interleave count.
9610   IC = UserIC > 0 ? UserIC : IC;
9611 
9612   // Emit diagnostic messages, if any.
9613   const char *VAPassName = Hints.vectorizeAnalysisPassName();
9614   if (!VectorizeLoop && !InterleaveLoop) {
9615     // Do not vectorize or interleaving the loop.
9616     ORE->emit([&]() {
9617       return OptimizationRemarkMissed(VAPassName, VecDiagMsg.first,
9618                                       L->getStartLoc(), L->getHeader())
9619              << VecDiagMsg.second;
9620     });
9621     ORE->emit([&]() {
9622       return OptimizationRemarkMissed(LV_NAME, IntDiagMsg.first,
9623                                       L->getStartLoc(), L->getHeader())
9624              << IntDiagMsg.second;
9625     });
9626     return false;
9627   } else if (!VectorizeLoop && InterleaveLoop) {
9628     LLVM_DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
9629     ORE->emit([&]() {
9630       return OptimizationRemarkAnalysis(VAPassName, VecDiagMsg.first,
9631                                         L->getStartLoc(), L->getHeader())
9632              << VecDiagMsg.second;
9633     });
9634   } else if (VectorizeLoop && !InterleaveLoop) {
9635     LLVM_DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width
9636                       << ") in " << DebugLocStr << '\n');
9637     ORE->emit([&]() {
9638       return OptimizationRemarkAnalysis(LV_NAME, IntDiagMsg.first,
9639                                         L->getStartLoc(), L->getHeader())
9640              << IntDiagMsg.second;
9641     });
9642   } else if (VectorizeLoop && InterleaveLoop) {
9643     LLVM_DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width
9644                       << ") in " << DebugLocStr << '\n');
9645     LLVM_DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
9646   }
9647 
9648   LVP.setBestPlan(VF.Width, IC);
9649 
9650   using namespace ore;
9651   bool DisableRuntimeUnroll = false;
9652   MDNode *OrigLoopID = L->getLoopID();
9653 
9654   if (!VectorizeLoop) {
9655     assert(IC > 1 && "interleave count should not be 1 or 0");
9656     // If we decided that it is not legal to vectorize the loop, then
9657     // interleave it.
9658     InnerLoopUnroller Unroller(L, PSE, LI, DT, TLI, TTI, AC, ORE, IC, &LVL, &CM,
9659                                BFI, PSI);
9660     LVP.executePlan(Unroller, DT);
9661 
9662     ORE->emit([&]() {
9663       return OptimizationRemark(LV_NAME, "Interleaved", L->getStartLoc(),
9664                                 L->getHeader())
9665              << "interleaved loop (interleaved count: "
9666              << NV("InterleaveCount", IC) << ")";
9667     });
9668   } else {
9669     // If we decided that it is *legal* to vectorize the loop, then do it.
9670 
9671     // Consider vectorizing the epilogue too if it's profitable.
9672     VectorizationFactor EpilogueVF =
9673       CM.selectEpilogueVectorizationFactor(VF.Width, LVP);
9674     if (EpilogueVF.Width.isVector()) {
9675 
9676       // The first pass vectorizes the main loop and creates a scalar epilogue
9677       // to be vectorized by executing the plan (potentially with a different
9678       // factor) again shortly afterwards.
9679       EpilogueLoopVectorizationInfo EPI(VF.Width.getKnownMinValue(), IC,
9680                                         EpilogueVF.Width.getKnownMinValue(), 1);
9681       EpilogueVectorizerMainLoop MainILV(L, PSE, LI, DT, TLI, TTI, AC, ORE, EPI,
9682                                          &LVL, &CM, BFI, PSI);
9683 
9684       LVP.setBestPlan(EPI.MainLoopVF, EPI.MainLoopUF);
9685       LVP.executePlan(MainILV, DT);
9686       ++LoopsVectorized;
9687 
9688       simplifyLoop(L, DT, LI, SE, AC, nullptr, false /* PreserveLCSSA */);
9689       formLCSSARecursively(*L, *DT, LI, SE);
9690 
9691       // Second pass vectorizes the epilogue and adjusts the control flow
9692       // edges from the first pass.
9693       LVP.setBestPlan(EPI.EpilogueVF, EPI.EpilogueUF);
9694       EPI.MainLoopVF = EPI.EpilogueVF;
9695       EPI.MainLoopUF = EPI.EpilogueUF;
9696       EpilogueVectorizerEpilogueLoop EpilogILV(L, PSE, LI, DT, TLI, TTI, AC,
9697                                                ORE, EPI, &LVL, &CM, BFI, PSI);
9698       LVP.executePlan(EpilogILV, DT);
9699       ++LoopsEpilogueVectorized;
9700 
9701       if (!MainILV.areSafetyChecksAdded())
9702         DisableRuntimeUnroll = true;
9703     } else {
9704       InnerLoopVectorizer LB(L, PSE, LI, DT, TLI, TTI, AC, ORE, VF.Width, IC,
9705                              &LVL, &CM, BFI, PSI);
9706       LVP.executePlan(LB, DT);
9707       ++LoopsVectorized;
9708 
9709       // Add metadata to disable runtime unrolling a scalar loop when there are
9710       // no runtime checks about strides and memory. A scalar loop that is
9711       // rarely used is not worth unrolling.
9712       if (!LB.areSafetyChecksAdded())
9713         DisableRuntimeUnroll = true;
9714     }
9715 
9716     // Report the vectorization decision.
9717     ORE->emit([&]() {
9718       return OptimizationRemark(LV_NAME, "Vectorized", L->getStartLoc(),
9719                                 L->getHeader())
9720              << "vectorized loop (vectorization width: "
9721              << NV("VectorizationFactor", VF.Width)
9722              << ", interleaved count: " << NV("InterleaveCount", IC) << ")";
9723     });
9724   }
9725 
9726   Optional<MDNode *> RemainderLoopID =
9727       makeFollowupLoopID(OrigLoopID, {LLVMLoopVectorizeFollowupAll,
9728                                       LLVMLoopVectorizeFollowupEpilogue});
9729   if (RemainderLoopID.hasValue()) {
9730     L->setLoopID(RemainderLoopID.getValue());
9731   } else {
9732     if (DisableRuntimeUnroll)
9733       AddRuntimeUnrollDisableMetaData(L);
9734 
9735     // Mark the loop as already vectorized to avoid vectorizing again.
9736     Hints.setAlreadyVectorized();
9737   }
9738 
9739   assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()));
9740   return true;
9741 }
9742 
9743 LoopVectorizeResult LoopVectorizePass::runImpl(
9744     Function &F, ScalarEvolution &SE_, LoopInfo &LI_, TargetTransformInfo &TTI_,
9745     DominatorTree &DT_, BlockFrequencyInfo &BFI_, TargetLibraryInfo *TLI_,
9746     DemandedBits &DB_, AAResults &AA_, AssumptionCache &AC_,
9747     std::function<const LoopAccessInfo &(Loop &)> &GetLAA_,
9748     OptimizationRemarkEmitter &ORE_, ProfileSummaryInfo *PSI_) {
9749   SE = &SE_;
9750   LI = &LI_;
9751   TTI = &TTI_;
9752   DT = &DT_;
9753   BFI = &BFI_;
9754   TLI = TLI_;
9755   AA = &AA_;
9756   AC = &AC_;
9757   GetLAA = &GetLAA_;
9758   DB = &DB_;
9759   ORE = &ORE_;
9760   PSI = PSI_;
9761 
9762   // Don't attempt if
9763   // 1. the target claims to have no vector registers, and
9764   // 2. interleaving won't help ILP.
9765   //
9766   // The second condition is necessary because, even if the target has no
9767   // vector registers, loop vectorization may still enable scalar
9768   // interleaving.
9769   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true)) &&
9770       TTI->getMaxInterleaveFactor(1) < 2)
9771     return LoopVectorizeResult(false, false);
9772 
9773   bool Changed = false, CFGChanged = false;
9774 
9775   // The vectorizer requires loops to be in simplified form.
9776   // Since simplification may add new inner loops, it has to run before the
9777   // legality and profitability checks. This means running the loop vectorizer
9778   // will simplify all loops, regardless of whether anything end up being
9779   // vectorized.
9780   for (auto &L : *LI)
9781     Changed |= CFGChanged |=
9782         simplifyLoop(L, DT, LI, SE, AC, nullptr, false /* PreserveLCSSA */);
9783 
9784   // Build up a worklist of inner-loops to vectorize. This is necessary as
9785   // the act of vectorizing or partially unrolling a loop creates new loops
9786   // and can invalidate iterators across the loops.
9787   SmallVector<Loop *, 8> Worklist;
9788 
9789   for (Loop *L : *LI)
9790     collectSupportedLoops(*L, LI, ORE, Worklist);
9791 
9792   LoopsAnalyzed += Worklist.size();
9793 
9794   // Now walk the identified inner loops.
9795   while (!Worklist.empty()) {
9796     Loop *L = Worklist.pop_back_val();
9797 
9798     // For the inner loops we actually process, form LCSSA to simplify the
9799     // transform.
9800     Changed |= formLCSSARecursively(*L, *DT, LI, SE);
9801 
9802     Changed |= CFGChanged |= processLoop(L);
9803   }
9804 
9805   // Process each loop nest in the function.
9806   return LoopVectorizeResult(Changed, CFGChanged);
9807 }
9808 
9809 PreservedAnalyses LoopVectorizePass::run(Function &F,
9810                                          FunctionAnalysisManager &AM) {
9811     auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
9812     auto &LI = AM.getResult<LoopAnalysis>(F);
9813     auto &TTI = AM.getResult<TargetIRAnalysis>(F);
9814     auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
9815     auto &BFI = AM.getResult<BlockFrequencyAnalysis>(F);
9816     auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
9817     auto &AA = AM.getResult<AAManager>(F);
9818     auto &AC = AM.getResult<AssumptionAnalysis>(F);
9819     auto &DB = AM.getResult<DemandedBitsAnalysis>(F);
9820     auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
9821     MemorySSA *MSSA = EnableMSSALoopDependency
9822                           ? &AM.getResult<MemorySSAAnalysis>(F).getMSSA()
9823                           : nullptr;
9824 
9825     auto &LAM = AM.getResult<LoopAnalysisManagerFunctionProxy>(F).getManager();
9826     std::function<const LoopAccessInfo &(Loop &)> GetLAA =
9827         [&](Loop &L) -> const LoopAccessInfo & {
9828       LoopStandardAnalysisResults AR = {AA,  AC,  DT,      LI,  SE,
9829                                         TLI, TTI, nullptr, MSSA};
9830       return LAM.getResult<LoopAccessAnalysis>(L, AR);
9831     };
9832     auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
9833     ProfileSummaryInfo *PSI =
9834         MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
9835     LoopVectorizeResult Result =
9836         runImpl(F, SE, LI, TTI, DT, BFI, &TLI, DB, AA, AC, GetLAA, ORE, PSI);
9837     if (!Result.MadeAnyChange)
9838       return PreservedAnalyses::all();
9839     PreservedAnalyses PA;
9840 
9841     // We currently do not preserve loopinfo/dominator analyses with outer loop
9842     // vectorization. Until this is addressed, mark these analyses as preserved
9843     // only for non-VPlan-native path.
9844     // TODO: Preserve Loop and Dominator analyses for VPlan-native path.
9845     if (!EnableVPlanNativePath) {
9846       PA.preserve<LoopAnalysis>();
9847       PA.preserve<DominatorTreeAnalysis>();
9848     }
9849     PA.preserve<BasicAA>();
9850     PA.preserve<GlobalsAA>();
9851     if (!Result.MadeCFGChange)
9852       PA.preserveSet<CFGAnalyses>();
9853     return PA;
9854 }
9855