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/SmallPtrSet.h"
73 #include "llvm/ADT/SmallSet.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/OptimizationRemarkEmitter.h"
91 #include "llvm/Analysis/ProfileSummaryInfo.h"
92 #include "llvm/Analysis/ScalarEvolution.h"
93 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
94 #include "llvm/Analysis/TargetLibraryInfo.h"
95 #include "llvm/Analysis/TargetTransformInfo.h"
96 #include "llvm/Analysis/VectorUtils.h"
97 #include "llvm/IR/Attributes.h"
98 #include "llvm/IR/BasicBlock.h"
99 #include "llvm/IR/CFG.h"
100 #include "llvm/IR/Constant.h"
101 #include "llvm/IR/Constants.h"
102 #include "llvm/IR/DataLayout.h"
103 #include "llvm/IR/DebugInfoMetadata.h"
104 #include "llvm/IR/DebugLoc.h"
105 #include "llvm/IR/DerivedTypes.h"
106 #include "llvm/IR/DiagnosticInfo.h"
107 #include "llvm/IR/Dominators.h"
108 #include "llvm/IR/Function.h"
109 #include "llvm/IR/IRBuilder.h"
110 #include "llvm/IR/InstrTypes.h"
111 #include "llvm/IR/Instruction.h"
112 #include "llvm/IR/Instructions.h"
113 #include "llvm/IR/IntrinsicInst.h"
114 #include "llvm/IR/Intrinsics.h"
115 #include "llvm/IR/Metadata.h"
116 #include "llvm/IR/Module.h"
117 #include "llvm/IR/Operator.h"
118 #include "llvm/IR/PatternMatch.h"
119 #include "llvm/IR/Type.h"
120 #include "llvm/IR/Use.h"
121 #include "llvm/IR/User.h"
122 #include "llvm/IR/Value.h"
123 #include "llvm/IR/ValueHandle.h"
124 #include "llvm/IR/Verifier.h"
125 #include "llvm/InitializePasses.h"
126 #include "llvm/Pass.h"
127 #include "llvm/Support/Casting.h"
128 #include "llvm/Support/CommandLine.h"
129 #include "llvm/Support/Compiler.h"
130 #include "llvm/Support/Debug.h"
131 #include "llvm/Support/ErrorHandling.h"
132 #include "llvm/Support/InstructionCost.h"
133 #include "llvm/Support/MathExtras.h"
134 #include "llvm/Support/raw_ostream.h"
135 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
136 #include "llvm/Transforms/Utils/InjectTLIMappings.h"
137 #include "llvm/Transforms/Utils/LoopSimplify.h"
138 #include "llvm/Transforms/Utils/LoopUtils.h"
139 #include "llvm/Transforms/Utils/LoopVersioning.h"
140 #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
141 #include "llvm/Transforms/Utils/SizeOpts.h"
142 #include "llvm/Transforms/Vectorize/LoopVectorizationLegality.h"
143 #include <algorithm>
144 #include <cassert>
145 #include <cstdint>
146 #include <functional>
147 #include <iterator>
148 #include <limits>
149 #include <map>
150 #include <memory>
151 #include <string>
152 #include <tuple>
153 #include <utility>
154 
155 using namespace llvm;
156 
157 #define LV_NAME "loop-vectorize"
158 #define DEBUG_TYPE LV_NAME
159 
160 #ifndef NDEBUG
161 const char VerboseDebug[] = DEBUG_TYPE "-verbose";
162 #endif
163 
164 /// @{
165 /// Metadata attribute names
166 const char LLVMLoopVectorizeFollowupAll[] = "llvm.loop.vectorize.followup_all";
167 const char LLVMLoopVectorizeFollowupVectorized[] =
168     "llvm.loop.vectorize.followup_vectorized";
169 const char LLVMLoopVectorizeFollowupEpilogue[] =
170     "llvm.loop.vectorize.followup_epilogue";
171 /// @}
172 
173 STATISTIC(LoopsVectorized, "Number of loops vectorized");
174 STATISTIC(LoopsAnalyzed, "Number of loops analyzed for vectorization");
175 STATISTIC(LoopsEpilogueVectorized, "Number of epilogues vectorized");
176 
177 static cl::opt<bool> EnableEpilogueVectorization(
178     "enable-epilogue-vectorization", cl::init(true), cl::Hidden,
179     cl::desc("Enable vectorization of epilogue loops."));
180 
181 static cl::opt<unsigned> EpilogueVectorizationForceVF(
182     "epilogue-vectorization-force-VF", cl::init(1), cl::Hidden,
183     cl::desc("When epilogue vectorization is enabled, and a value greater than "
184              "1 is specified, forces the given VF for all applicable epilogue "
185              "loops."));
186 
187 static cl::opt<unsigned> EpilogueVectorizationMinVF(
188     "epilogue-vectorization-minimum-VF", cl::init(16), cl::Hidden,
189     cl::desc("Only loops with vectorization factor equal to or larger than "
190              "the specified value are considered for epilogue vectorization."));
191 
192 /// Loops with a known constant trip count below this number are vectorized only
193 /// if no scalar iteration overheads are incurred.
194 static cl::opt<unsigned> TinyTripCountVectorThreshold(
195     "vectorizer-min-trip-count", cl::init(16), cl::Hidden,
196     cl::desc("Loops with a constant trip count that is smaller than this "
197              "value are vectorized only if no scalar iteration overheads "
198              "are incurred."));
199 
200 static cl::opt<unsigned> PragmaVectorizeMemoryCheckThreshold(
201     "pragma-vectorize-memory-check-threshold", cl::init(128), cl::Hidden,
202     cl::desc("The maximum allowed number of runtime memory checks with a "
203              "vectorize(enable) pragma."));
204 
205 // Option prefer-predicate-over-epilogue indicates that an epilogue is undesired,
206 // that predication is preferred, and this lists all options. I.e., the
207 // vectorizer will try to fold the tail-loop (epilogue) into the vector body
208 // and predicate the instructions accordingly. If tail-folding fails, there are
209 // different fallback strategies depending on these values:
210 namespace PreferPredicateTy {
211   enum Option {
212     ScalarEpilogue = 0,
213     PredicateElseScalarEpilogue,
214     PredicateOrDontVectorize
215   };
216 } // namespace PreferPredicateTy
217 
218 static cl::opt<PreferPredicateTy::Option> PreferPredicateOverEpilogue(
219     "prefer-predicate-over-epilogue",
220     cl::init(PreferPredicateTy::ScalarEpilogue),
221     cl::Hidden,
222     cl::desc("Tail-folding and predication preferences over creating a scalar "
223              "epilogue loop."),
224     cl::values(clEnumValN(PreferPredicateTy::ScalarEpilogue,
225                          "scalar-epilogue",
226                          "Don't tail-predicate loops, create scalar epilogue"),
227               clEnumValN(PreferPredicateTy::PredicateElseScalarEpilogue,
228                          "predicate-else-scalar-epilogue",
229                          "prefer tail-folding, create scalar epilogue if tail "
230                          "folding fails."),
231               clEnumValN(PreferPredicateTy::PredicateOrDontVectorize,
232                          "predicate-dont-vectorize",
233                          "prefers tail-folding, don't attempt vectorization if "
234                          "tail-folding fails.")));
235 
236 static cl::opt<bool> MaximizeBandwidth(
237     "vectorizer-maximize-bandwidth", cl::init(false), cl::Hidden,
238     cl::desc("Maximize bandwidth when selecting vectorization factor which "
239              "will be determined by the smallest type in loop."));
240 
241 static cl::opt<bool> EnableInterleavedMemAccesses(
242     "enable-interleaved-mem-accesses", cl::init(false), cl::Hidden,
243     cl::desc("Enable vectorization on interleaved memory accesses in a loop"));
244 
245 /// An interleave-group may need masking if it resides in a block that needs
246 /// predication, or in order to mask away gaps.
247 static cl::opt<bool> EnableMaskedInterleavedMemAccesses(
248     "enable-masked-interleaved-mem-accesses", cl::init(false), cl::Hidden,
249     cl::desc("Enable vectorization on masked interleaved memory accesses in a loop"));
250 
251 static cl::opt<unsigned> TinyTripCountInterleaveThreshold(
252     "tiny-trip-count-interleave-threshold", cl::init(128), cl::Hidden,
253     cl::desc("We don't interleave loops with a estimated constant trip count "
254              "below this number"));
255 
256 static cl::opt<unsigned> ForceTargetNumScalarRegs(
257     "force-target-num-scalar-regs", cl::init(0), cl::Hidden,
258     cl::desc("A flag that overrides the target's number of scalar registers."));
259 
260 static cl::opt<unsigned> ForceTargetNumVectorRegs(
261     "force-target-num-vector-regs", cl::init(0), cl::Hidden,
262     cl::desc("A flag that overrides the target's number of vector registers."));
263 
264 static cl::opt<unsigned> ForceTargetMaxScalarInterleaveFactor(
265     "force-target-max-scalar-interleave", cl::init(0), cl::Hidden,
266     cl::desc("A flag that overrides the target's max interleave factor for "
267              "scalar loops."));
268 
269 static cl::opt<unsigned> ForceTargetMaxVectorInterleaveFactor(
270     "force-target-max-vector-interleave", cl::init(0), cl::Hidden,
271     cl::desc("A flag that overrides the target's max interleave factor for "
272              "vectorized loops."));
273 
274 static cl::opt<unsigned> ForceTargetInstructionCost(
275     "force-target-instruction-cost", cl::init(0), cl::Hidden,
276     cl::desc("A flag that overrides the target's expected cost for "
277              "an instruction to a single constant value. Mostly "
278              "useful for getting consistent testing."));
279 
280 static cl::opt<bool> ForceTargetSupportsScalableVectors(
281     "force-target-supports-scalable-vectors", cl::init(false), cl::Hidden,
282     cl::desc(
283         "Pretend that scalable vectors are supported, even if the target does "
284         "not support them. This flag should only be used for testing."));
285 
286 static cl::opt<unsigned> SmallLoopCost(
287     "small-loop-cost", cl::init(20), cl::Hidden,
288     cl::desc(
289         "The cost of a loop that is considered 'small' by the interleaver."));
290 
291 static cl::opt<bool> LoopVectorizeWithBlockFrequency(
292     "loop-vectorize-with-block-frequency", cl::init(true), cl::Hidden,
293     cl::desc("Enable the use of the block frequency analysis to access PGO "
294              "heuristics minimizing code growth in cold regions and being more "
295              "aggressive in hot regions."));
296 
297 // Runtime interleave loops for load/store throughput.
298 static cl::opt<bool> EnableLoadStoreRuntimeInterleave(
299     "enable-loadstore-runtime-interleave", cl::init(true), cl::Hidden,
300     cl::desc(
301         "Enable runtime interleaving until load/store ports are saturated"));
302 
303 /// Interleave small loops with scalar reductions.
304 static cl::opt<bool> InterleaveSmallLoopScalarReduction(
305     "interleave-small-loop-scalar-reduction", cl::init(false), cl::Hidden,
306     cl::desc("Enable interleaving for loops with small iteration counts that "
307              "contain scalar reductions to expose ILP."));
308 
309 /// The number of stores in a loop that are allowed to need predication.
310 static cl::opt<unsigned> NumberOfStoresToPredicate(
311     "vectorize-num-stores-pred", cl::init(1), cl::Hidden,
312     cl::desc("Max number of stores to be predicated behind an if."));
313 
314 static cl::opt<bool> EnableIndVarRegisterHeur(
315     "enable-ind-var-reg-heur", cl::init(true), cl::Hidden,
316     cl::desc("Count the induction variable only once when interleaving"));
317 
318 static cl::opt<bool> EnableCondStoresVectorization(
319     "enable-cond-stores-vec", cl::init(true), cl::Hidden,
320     cl::desc("Enable if predication of stores during vectorization."));
321 
322 static cl::opt<unsigned> MaxNestedScalarReductionIC(
323     "max-nested-scalar-reduction-interleave", cl::init(2), cl::Hidden,
324     cl::desc("The maximum interleave count to use when interleaving a scalar "
325              "reduction in a nested loop."));
326 
327 static cl::opt<bool>
328     PreferInLoopReductions("prefer-inloop-reductions", cl::init(false),
329                            cl::Hidden,
330                            cl::desc("Prefer in-loop vector reductions, "
331                                     "overriding the targets preference."));
332 
333 static cl::opt<bool> ForceOrderedReductions(
334     "force-ordered-reductions", cl::init(false), cl::Hidden,
335     cl::desc("Enable the vectorisation of loops with in-order (strict) "
336              "FP reductions"));
337 
338 static cl::opt<bool> PreferPredicatedReductionSelect(
339     "prefer-predicated-reduction-select", cl::init(false), cl::Hidden,
340     cl::desc(
341         "Prefer predicating a reduction operation over an after loop select."));
342 
343 cl::opt<bool> EnableVPlanNativePath(
344     "enable-vplan-native-path", cl::init(false), cl::Hidden,
345     cl::desc("Enable VPlan-native vectorization path with "
346              "support for outer loop vectorization."));
347 
348 // FIXME: Remove this switch once we have divergence analysis. Currently we
349 // assume divergent non-backedge branches when this switch is true.
350 cl::opt<bool> EnableVPlanPredication(
351     "enable-vplan-predication", cl::init(false), cl::Hidden,
352     cl::desc("Enable VPlan-native vectorization path predicator with "
353              "support for outer loop vectorization."));
354 
355 // This flag enables the stress testing of the VPlan H-CFG construction in the
356 // VPlan-native vectorization path. It must be used in conjuction with
357 // -enable-vplan-native-path. -vplan-verify-hcfg can also be used to enable the
358 // verification of the H-CFGs built.
359 static cl::opt<bool> VPlanBuildStressTest(
360     "vplan-build-stress-test", cl::init(false), cl::Hidden,
361     cl::desc(
362         "Build VPlan for every supported loop nest in the function and bail "
363         "out right after the build (stress test the VPlan H-CFG construction "
364         "in the VPlan-native vectorization path)."));
365 
366 cl::opt<bool> llvm::EnableLoopInterleaving(
367     "interleave-loops", cl::init(true), cl::Hidden,
368     cl::desc("Enable loop interleaving in Loop vectorization passes"));
369 cl::opt<bool> llvm::EnableLoopVectorization(
370     "vectorize-loops", cl::init(true), cl::Hidden,
371     cl::desc("Run the Loop vectorization passes"));
372 
373 cl::opt<bool> PrintVPlansInDotFormat(
374     "vplan-print-in-dot-format", cl::init(false), cl::Hidden,
375     cl::desc("Use dot format instead of plain text when dumping VPlans"));
376 
377 /// A helper function that returns true if the given type is irregular. The
378 /// type is irregular if its allocated size doesn't equal the store size of an
379 /// element of the corresponding vector type.
380 static bool hasIrregularType(Type *Ty, const DataLayout &DL) {
381   // Determine if an array of N elements of type Ty is "bitcast compatible"
382   // with a <N x Ty> vector.
383   // This is only true if there is no padding between the array elements.
384   return DL.getTypeAllocSizeInBits(Ty) != DL.getTypeSizeInBits(Ty);
385 }
386 
387 /// A helper function that returns the reciprocal of the block probability of
388 /// predicated blocks. If we return X, we are assuming the predicated block
389 /// will execute once for every X iterations of the loop header.
390 ///
391 /// TODO: We should use actual block probability here, if available. Currently,
392 ///       we always assume predicated blocks have a 50% chance of executing.
393 static unsigned getReciprocalPredBlockProb() { return 2; }
394 
395 /// A helper function that returns an integer or floating-point constant with
396 /// value C.
397 static Constant *getSignedIntOrFpConstant(Type *Ty, int64_t C) {
398   return Ty->isIntegerTy() ? ConstantInt::getSigned(Ty, C)
399                            : ConstantFP::get(Ty, C);
400 }
401 
402 /// Returns "best known" trip count for the specified loop \p L as defined by
403 /// the following procedure:
404 ///   1) Returns exact trip count if it is known.
405 ///   2) Returns expected trip count according to profile data if any.
406 ///   3) Returns upper bound estimate if it is known.
407 ///   4) Returns None if all of the above failed.
408 static Optional<unsigned> getSmallBestKnownTC(ScalarEvolution &SE, Loop *L) {
409   // Check if exact trip count is known.
410   if (unsigned ExpectedTC = SE.getSmallConstantTripCount(L))
411     return ExpectedTC;
412 
413   // Check if there is an expected trip count available from profile data.
414   if (LoopVectorizeWithBlockFrequency)
415     if (auto EstimatedTC = getLoopEstimatedTripCount(L))
416       return EstimatedTC;
417 
418   // Check if upper bound estimate is known.
419   if (unsigned ExpectedTC = SE.getSmallConstantMaxTripCount(L))
420     return ExpectedTC;
421 
422   return None;
423 }
424 
425 // Forward declare GeneratedRTChecks.
426 class GeneratedRTChecks;
427 
428 namespace llvm {
429 
430 AnalysisKey ShouldRunExtraVectorPasses::Key;
431 
432 /// InnerLoopVectorizer vectorizes loops which contain only one basic
433 /// block to a specified vectorization factor (VF).
434 /// This class performs the widening of scalars into vectors, or multiple
435 /// scalars. This class also implements the following features:
436 /// * It inserts an epilogue loop for handling loops that don't have iteration
437 ///   counts that are known to be a multiple of the vectorization factor.
438 /// * It handles the code generation for reduction variables.
439 /// * Scalarization (implementation using scalars) of un-vectorizable
440 ///   instructions.
441 /// InnerLoopVectorizer does not perform any vectorization-legality
442 /// checks, and relies on the caller to check for the different legality
443 /// aspects. The InnerLoopVectorizer relies on the
444 /// LoopVectorizationLegality class to provide information about the induction
445 /// and reduction variables that were found to a given vectorization factor.
446 class InnerLoopVectorizer {
447 public:
448   InnerLoopVectorizer(Loop *OrigLoop, PredicatedScalarEvolution &PSE,
449                       LoopInfo *LI, DominatorTree *DT,
450                       const TargetLibraryInfo *TLI,
451                       const TargetTransformInfo *TTI, AssumptionCache *AC,
452                       OptimizationRemarkEmitter *ORE, ElementCount VecWidth,
453                       unsigned UnrollFactor, LoopVectorizationLegality *LVL,
454                       LoopVectorizationCostModel *CM, BlockFrequencyInfo *BFI,
455                       ProfileSummaryInfo *PSI, GeneratedRTChecks &RTChecks)
456       : OrigLoop(OrigLoop), PSE(PSE), LI(LI), DT(DT), TLI(TLI), TTI(TTI),
457         AC(AC), ORE(ORE), VF(VecWidth), UF(UnrollFactor),
458         Builder(PSE.getSE()->getContext()), Legal(LVL), Cost(CM), BFI(BFI),
459         PSI(PSI), RTChecks(RTChecks) {
460     // Query this against the original loop and save it here because the profile
461     // of the original loop header may change as the transformation happens.
462     OptForSizeBasedOnProfile = llvm::shouldOptimizeForSize(
463         OrigLoop->getHeader(), PSI, BFI, PGSOQueryType::IRPass);
464   }
465 
466   virtual ~InnerLoopVectorizer() = default;
467 
468   /// Create a new empty loop that will contain vectorized instructions later
469   /// on, while the old loop will be used as the scalar remainder. Control flow
470   /// is generated around the vectorized (and scalar epilogue) loops consisting
471   /// of various checks and bypasses. Return the pre-header block of the new
472   /// loop and the start value for the canonical induction, if it is != 0. The
473   /// latter is the case when vectorizing the epilogue loop. In the case of
474   /// epilogue vectorization, this function is overriden to handle the more
475   /// complex control flow around the loops.
476   virtual std::pair<BasicBlock *, Value *> createVectorizedLoopSkeleton();
477 
478   /// Widen a single call instruction within the innermost loop.
479   void widenCallInstruction(CallInst &I, VPValue *Def, VPUser &ArgOperands,
480                             VPTransformState &State);
481 
482   /// Fix the vectorized code, taking care of header phi's, live-outs, and more.
483   void fixVectorizedLoop(VPTransformState &State, VPlan &Plan);
484 
485   // Return true if any runtime check is added.
486   bool areSafetyChecksAdded() { return AddedSafetyChecks; }
487 
488   /// A type for vectorized values in the new loop. Each value from the
489   /// original loop, when vectorized, is represented by UF vector values in the
490   /// new unrolled loop, where UF is the unroll factor.
491   using VectorParts = SmallVector<Value *, 2>;
492 
493   /// Vectorize a single vector PHINode in a block in the VPlan-native path
494   /// only.
495   void widenPHIInstruction(Instruction *PN, VPWidenPHIRecipe *PhiR,
496                            VPTransformState &State);
497 
498   /// A helper function to scalarize a single Instruction in the innermost loop.
499   /// Generates a sequence of scalar instances for each lane between \p MinLane
500   /// and \p MaxLane, times each part between \p MinPart and \p MaxPart,
501   /// inclusive. Uses the VPValue operands from \p RepRecipe instead of \p
502   /// Instr's operands.
503   void scalarizeInstruction(Instruction *Instr, VPReplicateRecipe *RepRecipe,
504                             const VPIteration &Instance, bool IfPredicateInstr,
505                             VPTransformState &State);
506 
507   /// Construct the vector value of a scalarized value \p V one lane at a time.
508   void packScalarIntoVectorValue(VPValue *Def, const VPIteration &Instance,
509                                  VPTransformState &State);
510 
511   /// Try to vectorize interleaved access group \p Group with the base address
512   /// given in \p Addr, optionally masking the vector operations if \p
513   /// BlockInMask is non-null. Use \p State to translate given VPValues to IR
514   /// values in the vectorized loop.
515   void vectorizeInterleaveGroup(const InterleaveGroup<Instruction> *Group,
516                                 ArrayRef<VPValue *> VPDefs,
517                                 VPTransformState &State, VPValue *Addr,
518                                 ArrayRef<VPValue *> StoredValues,
519                                 VPValue *BlockInMask = nullptr);
520 
521   /// Set the debug location in the builder \p Ptr using the debug location in
522   /// \p V. If \p Ptr is None then it uses the class member's Builder.
523   void setDebugLocFromInst(const Value *V,
524                            Optional<IRBuilderBase *> CustomBuilder = None);
525 
526   /// Fix the non-induction PHIs in the OrigPHIsToFix vector.
527   void fixNonInductionPHIs(VPTransformState &State);
528 
529   /// Returns true if the reordering of FP operations is not allowed, but we are
530   /// able to vectorize with strict in-order reductions for the given RdxDesc.
531   bool useOrderedReductions(const RecurrenceDescriptor &RdxDesc);
532 
533   /// Create a broadcast instruction. This method generates a broadcast
534   /// instruction (shuffle) for loop invariant values and for the induction
535   /// value. If this is the induction variable then we extend it to N, N+1, ...
536   /// this is needed because each iteration in the loop corresponds to a SIMD
537   /// element.
538   virtual Value *getBroadcastInstrs(Value *V);
539 
540   /// Add metadata from one instruction to another.
541   ///
542   /// This includes both the original MDs from \p From and additional ones (\see
543   /// addNewMetadata).  Use this for *newly created* instructions in the vector
544   /// loop.
545   void addMetadata(Instruction *To, Instruction *From);
546 
547   /// Similar to the previous function but it adds the metadata to a
548   /// vector of instructions.
549   void addMetadata(ArrayRef<Value *> To, Instruction *From);
550 
551   // Returns the resume value (bc.merge.rdx) for a reduction as
552   // generated by fixReduction.
553   PHINode *getReductionResumeValue(const RecurrenceDescriptor &RdxDesc);
554 
555 protected:
556   friend class LoopVectorizationPlanner;
557 
558   /// A small list of PHINodes.
559   using PhiVector = SmallVector<PHINode *, 4>;
560 
561   /// A type for scalarized values in the new loop. Each value from the
562   /// original loop, when scalarized, is represented by UF x VF scalar values
563   /// in the new unrolled loop, where UF is the unroll factor and VF is the
564   /// vectorization factor.
565   using ScalarParts = SmallVector<SmallVector<Value *, 4>, 2>;
566 
567   /// Set up the values of the IVs correctly when exiting the vector loop.
568   void fixupIVUsers(PHINode *OrigPhi, const InductionDescriptor &II,
569                     Value *VectorTripCount, Value *EndValue,
570                     BasicBlock *MiddleBlock, BasicBlock *VectorHeader);
571 
572   /// Handle all cross-iteration phis in the header.
573   void fixCrossIterationPHIs(VPTransformState &State);
574 
575   /// Create the exit value of first order recurrences in the middle block and
576   /// update their users.
577   void fixFirstOrderRecurrence(VPFirstOrderRecurrencePHIRecipe *PhiR,
578                                VPTransformState &State);
579 
580   /// Create code for the loop exit value of the reduction.
581   void fixReduction(VPReductionPHIRecipe *Phi, VPTransformState &State);
582 
583   /// Clear NSW/NUW flags from reduction instructions if necessary.
584   void clearReductionWrapFlags(const RecurrenceDescriptor &RdxDesc,
585                                VPTransformState &State);
586 
587   /// Fixup the LCSSA phi nodes in the unique exit block.  This simply
588   /// means we need to add the appropriate incoming value from the middle
589   /// block as exiting edges from the scalar epilogue loop (if present) are
590   /// already in place, and we exit the vector loop exclusively to the middle
591   /// block.
592   void fixLCSSAPHIs(VPTransformState &State);
593 
594   /// Iteratively sink the scalarized operands of a predicated instruction into
595   /// the block that was created for it.
596   void sinkScalarOperands(Instruction *PredInst);
597 
598   /// Shrinks vector element sizes to the smallest bitwidth they can be legally
599   /// represented as.
600   void truncateToMinimalBitwidths(VPTransformState &State);
601 
602   /// Returns (and creates if needed) the original loop trip count.
603   Value *getOrCreateTripCount(BasicBlock *InsertBlock);
604 
605   /// Returns (and creates if needed) the trip count of the widened loop.
606   Value *getOrCreateVectorTripCount(BasicBlock *InsertBlock);
607 
608   /// Returns a bitcasted value to the requested vector type.
609   /// Also handles bitcasts of vector<float> <-> vector<pointer> types.
610   Value *createBitOrPointerCast(Value *V, VectorType *DstVTy,
611                                 const DataLayout &DL);
612 
613   /// Emit a bypass check to see if the vector trip count is zero, including if
614   /// it overflows.
615   void emitIterationCountCheck(BasicBlock *Bypass);
616 
617   /// Emit a bypass check to see if all of the SCEV assumptions we've
618   /// had to make are correct. Returns the block containing the checks or
619   /// nullptr if no checks have been added.
620   BasicBlock *emitSCEVChecks(BasicBlock *Bypass);
621 
622   /// Emit bypass checks to check any memory assumptions we may have made.
623   /// Returns the block containing the checks or nullptr if no checks have been
624   /// added.
625   BasicBlock *emitMemRuntimeChecks(BasicBlock *Bypass);
626 
627   /// Emit basic blocks (prefixed with \p Prefix) for the iteration check,
628   /// vector loop preheader, middle block and scalar preheader.
629   void createVectorLoopSkeleton(StringRef Prefix);
630 
631   /// Create new phi nodes for the induction variables to resume iteration count
632   /// in the scalar epilogue, from where the vectorized loop left off.
633   /// In cases where the loop skeleton is more complicated (eg. epilogue
634   /// vectorization) and the resume values can come from an additional bypass
635   /// block, the \p AdditionalBypass pair provides information about the bypass
636   /// block and the end value on the edge from bypass to this loop.
637   void createInductionResumeValues(
638       std::pair<BasicBlock *, Value *> AdditionalBypass = {nullptr, nullptr});
639 
640   /// Complete the loop skeleton by adding debug MDs, creating appropriate
641   /// conditional branches in the middle block, preparing the builder and
642   /// running the verifier. Return the preheader of the completed vector loop.
643   BasicBlock *completeLoopSkeleton(MDNode *OrigLoopID);
644 
645   /// Add additional metadata to \p To that was not present on \p Orig.
646   ///
647   /// Currently this is used to add the noalias annotations based on the
648   /// inserted memchecks.  Use this for instructions that are *cloned* into the
649   /// vector loop.
650   void addNewMetadata(Instruction *To, const Instruction *Orig);
651 
652   /// Collect poison-generating recipes that may generate a poison value that is
653   /// used after vectorization, even when their operands are not poison. Those
654   /// recipes meet the following conditions:
655   ///  * Contribute to the address computation of a recipe generating a widen
656   ///    memory load/store (VPWidenMemoryInstructionRecipe or
657   ///    VPInterleaveRecipe).
658   ///  * Such a widen memory load/store has at least one underlying Instruction
659   ///    that is in a basic block that needs predication and after vectorization
660   ///    the generated instruction won't be predicated.
661   void collectPoisonGeneratingRecipes(VPTransformState &State);
662 
663   /// Allow subclasses to override and print debug traces before/after vplan
664   /// execution, when trace information is requested.
665   virtual void printDebugTracesAtStart(){};
666   virtual void printDebugTracesAtEnd(){};
667 
668   /// The original loop.
669   Loop *OrigLoop;
670 
671   /// A wrapper around ScalarEvolution used to add runtime SCEV checks. Applies
672   /// dynamic knowledge to simplify SCEV expressions and converts them to a
673   /// more usable form.
674   PredicatedScalarEvolution &PSE;
675 
676   /// Loop Info.
677   LoopInfo *LI;
678 
679   /// Dominator Tree.
680   DominatorTree *DT;
681 
682   /// Alias Analysis.
683   AAResults *AA;
684 
685   /// Target Library Info.
686   const TargetLibraryInfo *TLI;
687 
688   /// Target Transform Info.
689   const TargetTransformInfo *TTI;
690 
691   /// Assumption Cache.
692   AssumptionCache *AC;
693 
694   /// Interface to emit optimization remarks.
695   OptimizationRemarkEmitter *ORE;
696 
697   /// LoopVersioning.  It's only set up (non-null) if memchecks were
698   /// used.
699   ///
700   /// This is currently only used to add no-alias metadata based on the
701   /// memchecks.  The actually versioning is performed manually.
702   std::unique_ptr<LoopVersioning> LVer;
703 
704   /// The vectorization SIMD factor to use. Each vector will have this many
705   /// vector elements.
706   ElementCount VF;
707 
708   /// The vectorization unroll factor to use. Each scalar is vectorized to this
709   /// many different vector instructions.
710   unsigned UF;
711 
712   /// The builder that we use
713   IRBuilder<> Builder;
714 
715   // --- Vectorization state ---
716 
717   /// The vector-loop preheader.
718   BasicBlock *LoopVectorPreHeader;
719 
720   /// The scalar-loop preheader.
721   BasicBlock *LoopScalarPreHeader;
722 
723   /// Middle Block between the vector and the scalar.
724   BasicBlock *LoopMiddleBlock;
725 
726   /// The unique ExitBlock of the scalar loop if one exists.  Note that
727   /// there can be multiple exiting edges reaching this block.
728   BasicBlock *LoopExitBlock;
729 
730   /// The scalar loop body.
731   BasicBlock *LoopScalarBody;
732 
733   /// A list of all bypass blocks. The first block is the entry of the loop.
734   SmallVector<BasicBlock *, 4> LoopBypassBlocks;
735 
736   /// Store instructions that were predicated.
737   SmallVector<Instruction *, 4> PredicatedInstructions;
738 
739   /// Trip count of the original loop.
740   Value *TripCount = nullptr;
741 
742   /// Trip count of the widened loop (TripCount - TripCount % (VF*UF))
743   Value *VectorTripCount = nullptr;
744 
745   /// The legality analysis.
746   LoopVectorizationLegality *Legal;
747 
748   /// The profitablity analysis.
749   LoopVectorizationCostModel *Cost;
750 
751   // Record whether runtime checks are added.
752   bool AddedSafetyChecks = false;
753 
754   // Holds the end values for each induction variable. We save the end values
755   // so we can later fix-up the external users of the induction variables.
756   DenseMap<PHINode *, Value *> IVEndValues;
757 
758   // Vector of original scalar PHIs whose corresponding widened PHIs need to be
759   // fixed up at the end of vector code generation.
760   SmallVector<PHINode *, 8> OrigPHIsToFix;
761 
762   /// BFI and PSI are used to check for profile guided size optimizations.
763   BlockFrequencyInfo *BFI;
764   ProfileSummaryInfo *PSI;
765 
766   // Whether this loop should be optimized for size based on profile guided size
767   // optimizatios.
768   bool OptForSizeBasedOnProfile;
769 
770   /// Structure to hold information about generated runtime checks, responsible
771   /// for cleaning the checks, if vectorization turns out unprofitable.
772   GeneratedRTChecks &RTChecks;
773 
774   // Holds the resume values for reductions in the loops, used to set the
775   // correct start value of reduction PHIs when vectorizing the epilogue.
776   SmallMapVector<const RecurrenceDescriptor *, PHINode *, 4>
777       ReductionResumeValues;
778 };
779 
780 class InnerLoopUnroller : public InnerLoopVectorizer {
781 public:
782   InnerLoopUnroller(Loop *OrigLoop, PredicatedScalarEvolution &PSE,
783                     LoopInfo *LI, DominatorTree *DT,
784                     const TargetLibraryInfo *TLI,
785                     const TargetTransformInfo *TTI, AssumptionCache *AC,
786                     OptimizationRemarkEmitter *ORE, unsigned UnrollFactor,
787                     LoopVectorizationLegality *LVL,
788                     LoopVectorizationCostModel *CM, BlockFrequencyInfo *BFI,
789                     ProfileSummaryInfo *PSI, GeneratedRTChecks &Check)
790       : InnerLoopVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
791                             ElementCount::getFixed(1), UnrollFactor, LVL, CM,
792                             BFI, PSI, Check) {}
793 
794 private:
795   Value *getBroadcastInstrs(Value *V) override;
796 };
797 
798 /// Encapsulate information regarding vectorization of a loop and its epilogue.
799 /// This information is meant to be updated and used across two stages of
800 /// epilogue vectorization.
801 struct EpilogueLoopVectorizationInfo {
802   ElementCount MainLoopVF = ElementCount::getFixed(0);
803   unsigned MainLoopUF = 0;
804   ElementCount EpilogueVF = ElementCount::getFixed(0);
805   unsigned EpilogueUF = 0;
806   BasicBlock *MainLoopIterationCountCheck = nullptr;
807   BasicBlock *EpilogueIterationCountCheck = nullptr;
808   BasicBlock *SCEVSafetyCheck = nullptr;
809   BasicBlock *MemSafetyCheck = nullptr;
810   Value *TripCount = nullptr;
811   Value *VectorTripCount = nullptr;
812 
813   EpilogueLoopVectorizationInfo(ElementCount MVF, unsigned MUF,
814                                 ElementCount EVF, unsigned EUF)
815       : MainLoopVF(MVF), MainLoopUF(MUF), EpilogueVF(EVF), EpilogueUF(EUF) {
816     assert(EUF == 1 &&
817            "A high UF for the epilogue loop is likely not beneficial.");
818   }
819 };
820 
821 /// An extension of the inner loop vectorizer that creates a skeleton for a
822 /// vectorized loop that has its epilogue (residual) also vectorized.
823 /// The idea is to run the vplan on a given loop twice, firstly to setup the
824 /// skeleton and vectorize the main loop, and secondly to complete the skeleton
825 /// from the first step and vectorize the epilogue.  This is achieved by
826 /// deriving two concrete strategy classes from this base class and invoking
827 /// them in succession from the loop vectorizer planner.
828 class InnerLoopAndEpilogueVectorizer : public InnerLoopVectorizer {
829 public:
830   InnerLoopAndEpilogueVectorizer(
831       Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI,
832       DominatorTree *DT, const TargetLibraryInfo *TLI,
833       const TargetTransformInfo *TTI, AssumptionCache *AC,
834       OptimizationRemarkEmitter *ORE, EpilogueLoopVectorizationInfo &EPI,
835       LoopVectorizationLegality *LVL, llvm::LoopVectorizationCostModel *CM,
836       BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI,
837       GeneratedRTChecks &Checks)
838       : InnerLoopVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
839                             EPI.MainLoopVF, EPI.MainLoopUF, LVL, CM, BFI, PSI,
840                             Checks),
841         EPI(EPI) {}
842 
843   // Override this function to handle the more complex control flow around the
844   // three loops.
845   std::pair<BasicBlock *, Value *>
846   createVectorizedLoopSkeleton() final override {
847     return createEpilogueVectorizedLoopSkeleton();
848   }
849 
850   /// The interface for creating a vectorized skeleton using one of two
851   /// different strategies, each corresponding to one execution of the vplan
852   /// as described above.
853   virtual std::pair<BasicBlock *, Value *>
854   createEpilogueVectorizedLoopSkeleton() = 0;
855 
856   /// Holds and updates state information required to vectorize the main loop
857   /// and its epilogue in two separate passes. This setup helps us avoid
858   /// regenerating and recomputing runtime safety checks. It also helps us to
859   /// shorten the iteration-count-check path length for the cases where the
860   /// iteration count of the loop is so small that the main vector loop is
861   /// completely skipped.
862   EpilogueLoopVectorizationInfo &EPI;
863 };
864 
865 /// A specialized derived class of inner loop vectorizer that performs
866 /// vectorization of *main* loops in the process of vectorizing loops and their
867 /// epilogues.
868 class EpilogueVectorizerMainLoop : public InnerLoopAndEpilogueVectorizer {
869 public:
870   EpilogueVectorizerMainLoop(
871       Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI,
872       DominatorTree *DT, const TargetLibraryInfo *TLI,
873       const TargetTransformInfo *TTI, AssumptionCache *AC,
874       OptimizationRemarkEmitter *ORE, EpilogueLoopVectorizationInfo &EPI,
875       LoopVectorizationLegality *LVL, llvm::LoopVectorizationCostModel *CM,
876       BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI,
877       GeneratedRTChecks &Check)
878       : InnerLoopAndEpilogueVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
879                                        EPI, LVL, CM, BFI, PSI, Check) {}
880   /// Implements the interface for creating a vectorized skeleton using the
881   /// *main loop* strategy (ie the first pass of vplan execution).
882   std::pair<BasicBlock *, Value *>
883   createEpilogueVectorizedLoopSkeleton() final override;
884 
885 protected:
886   /// Emits an iteration count bypass check once for the main loop (when \p
887   /// ForEpilogue is false) and once for the epilogue loop (when \p
888   /// ForEpilogue is true).
889   BasicBlock *emitIterationCountCheck(BasicBlock *Bypass, bool ForEpilogue);
890   void printDebugTracesAtStart() override;
891   void printDebugTracesAtEnd() override;
892 };
893 
894 // A specialized derived class of inner loop vectorizer that performs
895 // vectorization of *epilogue* loops in the process of vectorizing loops and
896 // their epilogues.
897 class EpilogueVectorizerEpilogueLoop : public InnerLoopAndEpilogueVectorizer {
898 public:
899   EpilogueVectorizerEpilogueLoop(
900       Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI,
901       DominatorTree *DT, const TargetLibraryInfo *TLI,
902       const TargetTransformInfo *TTI, AssumptionCache *AC,
903       OptimizationRemarkEmitter *ORE, EpilogueLoopVectorizationInfo &EPI,
904       LoopVectorizationLegality *LVL, llvm::LoopVectorizationCostModel *CM,
905       BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI,
906       GeneratedRTChecks &Checks)
907       : InnerLoopAndEpilogueVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
908                                        EPI, LVL, CM, BFI, PSI, Checks) {
909     TripCount = EPI.TripCount;
910   }
911   /// Implements the interface for creating a vectorized skeleton using the
912   /// *epilogue loop* strategy (ie the second pass of vplan execution).
913   std::pair<BasicBlock *, Value *>
914   createEpilogueVectorizedLoopSkeleton() final override;
915 
916 protected:
917   /// Emits an iteration count bypass check after the main vector loop has
918   /// finished to see if there are any iterations left to execute by either
919   /// the vector epilogue or the scalar epilogue.
920   BasicBlock *emitMinimumVectorEpilogueIterCountCheck(
921                                                       BasicBlock *Bypass,
922                                                       BasicBlock *Insert);
923   void printDebugTracesAtStart() override;
924   void printDebugTracesAtEnd() override;
925 };
926 } // end namespace llvm
927 
928 /// Look for a meaningful debug location on the instruction or it's
929 /// operands.
930 static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
931   if (!I)
932     return I;
933 
934   DebugLoc Empty;
935   if (I->getDebugLoc() != Empty)
936     return I;
937 
938   for (Use &Op : I->operands()) {
939     if (Instruction *OpInst = dyn_cast<Instruction>(Op))
940       if (OpInst->getDebugLoc() != Empty)
941         return OpInst;
942   }
943 
944   return I;
945 }
946 
947 void InnerLoopVectorizer::setDebugLocFromInst(
948     const Value *V, Optional<IRBuilderBase *> CustomBuilder) {
949   IRBuilderBase *B = (CustomBuilder == None) ? &Builder : *CustomBuilder;
950   if (const Instruction *Inst = dyn_cast_or_null<Instruction>(V)) {
951     const DILocation *DIL = Inst->getDebugLoc();
952 
953     // When a FSDiscriminator is enabled, we don't need to add the multiply
954     // factors to the discriminators.
955     if (DIL && Inst->getFunction()->isDebugInfoForProfiling() &&
956         !isa<DbgInfoIntrinsic>(Inst) && !EnableFSDiscriminator) {
957       // FIXME: For scalable vectors, assume vscale=1.
958       auto NewDIL =
959           DIL->cloneByMultiplyingDuplicationFactor(UF * VF.getKnownMinValue());
960       if (NewDIL)
961         B->SetCurrentDebugLocation(NewDIL.getValue());
962       else
963         LLVM_DEBUG(dbgs()
964                    << "Failed to create new discriminator: "
965                    << DIL->getFilename() << " Line: " << DIL->getLine());
966     } else
967       B->SetCurrentDebugLocation(DIL);
968   } else
969     B->SetCurrentDebugLocation(DebugLoc());
970 }
971 
972 /// Write a \p DebugMsg about vectorization to the debug output stream. If \p I
973 /// is passed, the message relates to that particular instruction.
974 #ifndef NDEBUG
975 static void debugVectorizationMessage(const StringRef Prefix,
976                                       const StringRef DebugMsg,
977                                       Instruction *I) {
978   dbgs() << "LV: " << Prefix << DebugMsg;
979   if (I != nullptr)
980     dbgs() << " " << *I;
981   else
982     dbgs() << '.';
983   dbgs() << '\n';
984 }
985 #endif
986 
987 /// Create an analysis remark that explains why vectorization failed
988 ///
989 /// \p PassName is the name of the pass (e.g. can be AlwaysPrint).  \p
990 /// RemarkName is the identifier for the remark.  If \p I is passed it is an
991 /// instruction that prevents vectorization.  Otherwise \p TheLoop is used for
992 /// the location of the remark.  \return the remark object that can be
993 /// streamed to.
994 static OptimizationRemarkAnalysis createLVAnalysis(const char *PassName,
995     StringRef RemarkName, Loop *TheLoop, Instruction *I) {
996   Value *CodeRegion = TheLoop->getHeader();
997   DebugLoc DL = TheLoop->getStartLoc();
998 
999   if (I) {
1000     CodeRegion = I->getParent();
1001     // If there is no debug location attached to the instruction, revert back to
1002     // using the loop's.
1003     if (I->getDebugLoc())
1004       DL = I->getDebugLoc();
1005   }
1006 
1007   return OptimizationRemarkAnalysis(PassName, RemarkName, DL, CodeRegion);
1008 }
1009 
1010 namespace llvm {
1011 
1012 /// Return a value for Step multiplied by VF.
1013 Value *createStepForVF(IRBuilderBase &B, Type *Ty, ElementCount VF,
1014                        int64_t Step) {
1015   assert(Ty->isIntegerTy() && "Expected an integer step");
1016   Constant *StepVal = ConstantInt::get(Ty, Step * VF.getKnownMinValue());
1017   return VF.isScalable() ? B.CreateVScale(StepVal) : StepVal;
1018 }
1019 
1020 /// Return the runtime value for VF.
1021 Value *getRuntimeVF(IRBuilderBase &B, Type *Ty, ElementCount VF) {
1022   Constant *EC = ConstantInt::get(Ty, VF.getKnownMinValue());
1023   return VF.isScalable() ? B.CreateVScale(EC) : EC;
1024 }
1025 
1026 static Value *getRuntimeVFAsFloat(IRBuilderBase &B, Type *FTy,
1027                                   ElementCount VF) {
1028   assert(FTy->isFloatingPointTy() && "Expected floating point type!");
1029   Type *IntTy = IntegerType::get(FTy->getContext(), FTy->getScalarSizeInBits());
1030   Value *RuntimeVF = getRuntimeVF(B, IntTy, VF);
1031   return B.CreateUIToFP(RuntimeVF, FTy);
1032 }
1033 
1034 void reportVectorizationFailure(const StringRef DebugMsg,
1035                                 const StringRef OREMsg, const StringRef ORETag,
1036                                 OptimizationRemarkEmitter *ORE, Loop *TheLoop,
1037                                 Instruction *I) {
1038   LLVM_DEBUG(debugVectorizationMessage("Not vectorizing: ", DebugMsg, I));
1039   LoopVectorizeHints Hints(TheLoop, true /* doesn't matter */, *ORE);
1040   ORE->emit(
1041       createLVAnalysis(Hints.vectorizeAnalysisPassName(), ORETag, TheLoop, I)
1042       << "loop not vectorized: " << OREMsg);
1043 }
1044 
1045 void reportVectorizationInfo(const StringRef Msg, const StringRef ORETag,
1046                              OptimizationRemarkEmitter *ORE, Loop *TheLoop,
1047                              Instruction *I) {
1048   LLVM_DEBUG(debugVectorizationMessage("", Msg, I));
1049   LoopVectorizeHints Hints(TheLoop, true /* doesn't matter */, *ORE);
1050   ORE->emit(
1051       createLVAnalysis(Hints.vectorizeAnalysisPassName(), ORETag, TheLoop, I)
1052       << Msg);
1053 }
1054 
1055 } // end namespace llvm
1056 
1057 #ifndef NDEBUG
1058 /// \return string containing a file name and a line # for the given loop.
1059 static std::string getDebugLocString(const Loop *L) {
1060   std::string Result;
1061   if (L) {
1062     raw_string_ostream OS(Result);
1063     if (const DebugLoc LoopDbgLoc = L->getStartLoc())
1064       LoopDbgLoc.print(OS);
1065     else
1066       // Just print the module name.
1067       OS << L->getHeader()->getParent()->getParent()->getModuleIdentifier();
1068     OS.flush();
1069   }
1070   return Result;
1071 }
1072 #endif
1073 
1074 void InnerLoopVectorizer::addNewMetadata(Instruction *To,
1075                                          const Instruction *Orig) {
1076   // If the loop was versioned with memchecks, add the corresponding no-alias
1077   // metadata.
1078   if (LVer && (isa<LoadInst>(Orig) || isa<StoreInst>(Orig)))
1079     LVer->annotateInstWithNoAlias(To, Orig);
1080 }
1081 
1082 void InnerLoopVectorizer::collectPoisonGeneratingRecipes(
1083     VPTransformState &State) {
1084 
1085   // Collect recipes in the backward slice of `Root` that may generate a poison
1086   // value that is used after vectorization.
1087   SmallPtrSet<VPRecipeBase *, 16> Visited;
1088   auto collectPoisonGeneratingInstrsInBackwardSlice([&](VPRecipeBase *Root) {
1089     SmallVector<VPRecipeBase *, 16> Worklist;
1090     Worklist.push_back(Root);
1091 
1092     // Traverse the backward slice of Root through its use-def chain.
1093     while (!Worklist.empty()) {
1094       VPRecipeBase *CurRec = Worklist.back();
1095       Worklist.pop_back();
1096 
1097       if (!Visited.insert(CurRec).second)
1098         continue;
1099 
1100       // Prune search if we find another recipe generating a widen memory
1101       // instruction. Widen memory instructions involved in address computation
1102       // will lead to gather/scatter instructions, which don't need to be
1103       // handled.
1104       if (isa<VPWidenMemoryInstructionRecipe>(CurRec) ||
1105           isa<VPInterleaveRecipe>(CurRec) ||
1106           isa<VPScalarIVStepsRecipe>(CurRec) ||
1107           isa<VPCanonicalIVPHIRecipe>(CurRec))
1108         continue;
1109 
1110       // This recipe contributes to the address computation of a widen
1111       // load/store. Collect recipe if its underlying instruction has
1112       // poison-generating flags.
1113       Instruction *Instr = CurRec->getUnderlyingInstr();
1114       if (Instr && Instr->hasPoisonGeneratingFlags())
1115         State.MayGeneratePoisonRecipes.insert(CurRec);
1116 
1117       // Add new definitions to the worklist.
1118       for (VPValue *operand : CurRec->operands())
1119         if (VPDef *OpDef = operand->getDef())
1120           Worklist.push_back(cast<VPRecipeBase>(OpDef));
1121     }
1122   });
1123 
1124   // Traverse all the recipes in the VPlan and collect the poison-generating
1125   // recipes in the backward slice starting at the address of a VPWidenRecipe or
1126   // VPInterleaveRecipe.
1127   auto Iter = depth_first(
1128       VPBlockRecursiveTraversalWrapper<VPBlockBase *>(State.Plan->getEntry()));
1129   for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(Iter)) {
1130     for (VPRecipeBase &Recipe : *VPBB) {
1131       if (auto *WidenRec = dyn_cast<VPWidenMemoryInstructionRecipe>(&Recipe)) {
1132         Instruction *UnderlyingInstr = WidenRec->getUnderlyingInstr();
1133         VPDef *AddrDef = WidenRec->getAddr()->getDef();
1134         if (AddrDef && WidenRec->isConsecutive() && UnderlyingInstr &&
1135             Legal->blockNeedsPredication(UnderlyingInstr->getParent()))
1136           collectPoisonGeneratingInstrsInBackwardSlice(
1137               cast<VPRecipeBase>(AddrDef));
1138       } else if (auto *InterleaveRec = dyn_cast<VPInterleaveRecipe>(&Recipe)) {
1139         VPDef *AddrDef = InterleaveRec->getAddr()->getDef();
1140         if (AddrDef) {
1141           // Check if any member of the interleave group needs predication.
1142           const InterleaveGroup<Instruction> *InterGroup =
1143               InterleaveRec->getInterleaveGroup();
1144           bool NeedPredication = false;
1145           for (int I = 0, NumMembers = InterGroup->getNumMembers();
1146                I < NumMembers; ++I) {
1147             Instruction *Member = InterGroup->getMember(I);
1148             if (Member)
1149               NeedPredication |=
1150                   Legal->blockNeedsPredication(Member->getParent());
1151           }
1152 
1153           if (NeedPredication)
1154             collectPoisonGeneratingInstrsInBackwardSlice(
1155                 cast<VPRecipeBase>(AddrDef));
1156         }
1157       }
1158     }
1159   }
1160 }
1161 
1162 void InnerLoopVectorizer::addMetadata(Instruction *To,
1163                                       Instruction *From) {
1164   propagateMetadata(To, From);
1165   addNewMetadata(To, From);
1166 }
1167 
1168 void InnerLoopVectorizer::addMetadata(ArrayRef<Value *> To,
1169                                       Instruction *From) {
1170   for (Value *V : To) {
1171     if (Instruction *I = dyn_cast<Instruction>(V))
1172       addMetadata(I, From);
1173   }
1174 }
1175 
1176 PHINode *InnerLoopVectorizer::getReductionResumeValue(
1177     const RecurrenceDescriptor &RdxDesc) {
1178   auto It = ReductionResumeValues.find(&RdxDesc);
1179   assert(It != ReductionResumeValues.end() &&
1180          "Expected to find a resume value for the reduction.");
1181   return It->second;
1182 }
1183 
1184 namespace llvm {
1185 
1186 // Loop vectorization cost-model hints how the scalar epilogue loop should be
1187 // lowered.
1188 enum ScalarEpilogueLowering {
1189 
1190   // The default: allowing scalar epilogues.
1191   CM_ScalarEpilogueAllowed,
1192 
1193   // Vectorization with OptForSize: don't allow epilogues.
1194   CM_ScalarEpilogueNotAllowedOptSize,
1195 
1196   // A special case of vectorisation with OptForSize: loops with a very small
1197   // trip count are considered for vectorization under OptForSize, thereby
1198   // making sure the cost of their loop body is dominant, free of runtime
1199   // guards and scalar iteration overheads.
1200   CM_ScalarEpilogueNotAllowedLowTripLoop,
1201 
1202   // Loop hint predicate indicating an epilogue is undesired.
1203   CM_ScalarEpilogueNotNeededUsePredicate,
1204 
1205   // Directive indicating we must either tail fold or not vectorize
1206   CM_ScalarEpilogueNotAllowedUsePredicate
1207 };
1208 
1209 /// ElementCountComparator creates a total ordering for ElementCount
1210 /// for the purposes of using it in a set structure.
1211 struct ElementCountComparator {
1212   bool operator()(const ElementCount &LHS, const ElementCount &RHS) const {
1213     return std::make_tuple(LHS.isScalable(), LHS.getKnownMinValue()) <
1214            std::make_tuple(RHS.isScalable(), RHS.getKnownMinValue());
1215   }
1216 };
1217 using ElementCountSet = SmallSet<ElementCount, 16, ElementCountComparator>;
1218 
1219 /// LoopVectorizationCostModel - estimates the expected speedups due to
1220 /// vectorization.
1221 /// In many cases vectorization is not profitable. This can happen because of
1222 /// a number of reasons. In this class we mainly attempt to predict the
1223 /// expected speedup/slowdowns due to the supported instruction set. We use the
1224 /// TargetTransformInfo to query the different backends for the cost of
1225 /// different operations.
1226 class LoopVectorizationCostModel {
1227 public:
1228   LoopVectorizationCostModel(ScalarEpilogueLowering SEL, Loop *L,
1229                              PredicatedScalarEvolution &PSE, LoopInfo *LI,
1230                              LoopVectorizationLegality *Legal,
1231                              const TargetTransformInfo &TTI,
1232                              const TargetLibraryInfo *TLI, DemandedBits *DB,
1233                              AssumptionCache *AC,
1234                              OptimizationRemarkEmitter *ORE, const Function *F,
1235                              const LoopVectorizeHints *Hints,
1236                              InterleavedAccessInfo &IAI)
1237       : ScalarEpilogueStatus(SEL), TheLoop(L), PSE(PSE), LI(LI), Legal(Legal),
1238         TTI(TTI), TLI(TLI), DB(DB), AC(AC), ORE(ORE), TheFunction(F),
1239         Hints(Hints), InterleaveInfo(IAI) {}
1240 
1241   /// \return An upper bound for the vectorization factors (both fixed and
1242   /// scalable). If the factors are 0, vectorization and interleaving should be
1243   /// avoided up front.
1244   FixedScalableVFPair computeMaxVF(ElementCount UserVF, unsigned UserIC);
1245 
1246   /// \return True if runtime checks are required for vectorization, and false
1247   /// otherwise.
1248   bool runtimeChecksRequired();
1249 
1250   /// \return The most profitable vectorization factor and the cost of that VF.
1251   /// This method checks every VF in \p CandidateVFs. If UserVF is not ZERO
1252   /// then this vectorization factor will be selected if vectorization is
1253   /// possible.
1254   VectorizationFactor
1255   selectVectorizationFactor(const ElementCountSet &CandidateVFs);
1256 
1257   VectorizationFactor
1258   selectEpilogueVectorizationFactor(const ElementCount MaxVF,
1259                                     const LoopVectorizationPlanner &LVP);
1260 
1261   /// Setup cost-based decisions for user vectorization factor.
1262   /// \return true if the UserVF is a feasible VF to be chosen.
1263   bool selectUserVectorizationFactor(ElementCount UserVF) {
1264     collectUniformsAndScalars(UserVF);
1265     collectInstsToScalarize(UserVF);
1266     return expectedCost(UserVF).first.isValid();
1267   }
1268 
1269   /// \return The size (in bits) of the smallest and widest types in the code
1270   /// that needs to be vectorized. We ignore values that remain scalar such as
1271   /// 64 bit loop indices.
1272   std::pair<unsigned, unsigned> getSmallestAndWidestTypes();
1273 
1274   /// \return The desired interleave count.
1275   /// If interleave count has been specified by metadata it will be returned.
1276   /// Otherwise, the interleave count is computed and returned. VF and LoopCost
1277   /// are the selected vectorization factor and the cost of the selected VF.
1278   unsigned selectInterleaveCount(ElementCount VF, unsigned LoopCost);
1279 
1280   /// Memory access instruction may be vectorized in more than one way.
1281   /// Form of instruction after vectorization depends on cost.
1282   /// This function takes cost-based decisions for Load/Store instructions
1283   /// and collects them in a map. This decisions map is used for building
1284   /// the lists of loop-uniform and loop-scalar instructions.
1285   /// The calculated cost is saved with widening decision in order to
1286   /// avoid redundant calculations.
1287   void setCostBasedWideningDecision(ElementCount VF);
1288 
1289   /// A struct that represents some properties of the register usage
1290   /// of a loop.
1291   struct RegisterUsage {
1292     /// Holds the number of loop invariant values that are used in the loop.
1293     /// The key is ClassID of target-provided register class.
1294     SmallMapVector<unsigned, unsigned, 4> LoopInvariantRegs;
1295     /// Holds the maximum number of concurrent live intervals in the loop.
1296     /// The key is ClassID of target-provided register class.
1297     SmallMapVector<unsigned, unsigned, 4> MaxLocalUsers;
1298   };
1299 
1300   /// \return Returns information about the register usages of the loop for the
1301   /// given vectorization factors.
1302   SmallVector<RegisterUsage, 8>
1303   calculateRegisterUsage(ArrayRef<ElementCount> VFs);
1304 
1305   /// Collect values we want to ignore in the cost model.
1306   void collectValuesToIgnore();
1307 
1308   /// Collect all element types in the loop for which widening is needed.
1309   void collectElementTypesForWidening();
1310 
1311   /// Split reductions into those that happen in the loop, and those that happen
1312   /// outside. In loop reductions are collected into InLoopReductionChains.
1313   void collectInLoopReductions();
1314 
1315   /// Returns true if we should use strict in-order reductions for the given
1316   /// RdxDesc. This is true if the -enable-strict-reductions flag is passed,
1317   /// the IsOrdered flag of RdxDesc is set and we do not allow reordering
1318   /// of FP operations.
1319   bool useOrderedReductions(const RecurrenceDescriptor &RdxDesc) {
1320     return !Hints->allowReordering() && RdxDesc.isOrdered();
1321   }
1322 
1323   /// \returns The smallest bitwidth each instruction can be represented with.
1324   /// The vector equivalents of these instructions should be truncated to this
1325   /// type.
1326   const MapVector<Instruction *, uint64_t> &getMinimalBitwidths() const {
1327     return MinBWs;
1328   }
1329 
1330   /// \returns True if it is more profitable to scalarize instruction \p I for
1331   /// vectorization factor \p VF.
1332   bool isProfitableToScalarize(Instruction *I, ElementCount VF) const {
1333     assert(VF.isVector() &&
1334            "Profitable to scalarize relevant only for VF > 1.");
1335 
1336     // Cost model is not run in the VPlan-native path - return conservative
1337     // result until this changes.
1338     if (EnableVPlanNativePath)
1339       return false;
1340 
1341     auto Scalars = InstsToScalarize.find(VF);
1342     assert(Scalars != InstsToScalarize.end() &&
1343            "VF not yet analyzed for scalarization profitability");
1344     return Scalars->second.find(I) != Scalars->second.end();
1345   }
1346 
1347   /// Returns true if \p I is known to be uniform after vectorization.
1348   bool isUniformAfterVectorization(Instruction *I, ElementCount VF) const {
1349     if (VF.isScalar())
1350       return true;
1351 
1352     // Cost model is not run in the VPlan-native path - return conservative
1353     // result until this changes.
1354     if (EnableVPlanNativePath)
1355       return false;
1356 
1357     auto UniformsPerVF = Uniforms.find(VF);
1358     assert(UniformsPerVF != Uniforms.end() &&
1359            "VF not yet analyzed for uniformity");
1360     return UniformsPerVF->second.count(I);
1361   }
1362 
1363   /// Returns true if \p I is known to be scalar after vectorization.
1364   bool isScalarAfterVectorization(Instruction *I, ElementCount VF) const {
1365     if (VF.isScalar())
1366       return true;
1367 
1368     // Cost model is not run in the VPlan-native path - return conservative
1369     // result until this changes.
1370     if (EnableVPlanNativePath)
1371       return false;
1372 
1373     auto ScalarsPerVF = Scalars.find(VF);
1374     assert(ScalarsPerVF != Scalars.end() &&
1375            "Scalar values are not calculated for VF");
1376     return ScalarsPerVF->second.count(I);
1377   }
1378 
1379   /// \returns True if instruction \p I can be truncated to a smaller bitwidth
1380   /// for vectorization factor \p VF.
1381   bool canTruncateToMinimalBitwidth(Instruction *I, ElementCount VF) const {
1382     return VF.isVector() && MinBWs.find(I) != MinBWs.end() &&
1383            !isProfitableToScalarize(I, VF) &&
1384            !isScalarAfterVectorization(I, VF);
1385   }
1386 
1387   /// Decision that was taken during cost calculation for memory instruction.
1388   enum InstWidening {
1389     CM_Unknown,
1390     CM_Widen,         // For consecutive accesses with stride +1.
1391     CM_Widen_Reverse, // For consecutive accesses with stride -1.
1392     CM_Interleave,
1393     CM_GatherScatter,
1394     CM_Scalarize
1395   };
1396 
1397   /// Save vectorization decision \p W and \p Cost taken by the cost model for
1398   /// instruction \p I and vector width \p VF.
1399   void setWideningDecision(Instruction *I, ElementCount VF, InstWidening W,
1400                            InstructionCost Cost) {
1401     assert(VF.isVector() && "Expected VF >=2");
1402     WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
1403   }
1404 
1405   /// Save vectorization decision \p W and \p Cost taken by the cost model for
1406   /// interleaving group \p Grp and vector width \p VF.
1407   void setWideningDecision(const InterleaveGroup<Instruction> *Grp,
1408                            ElementCount VF, InstWidening W,
1409                            InstructionCost Cost) {
1410     assert(VF.isVector() && "Expected VF >=2");
1411     /// Broadcast this decicion to all instructions inside the group.
1412     /// But the cost will be assigned to one instruction only.
1413     for (unsigned i = 0; i < Grp->getFactor(); ++i) {
1414       if (auto *I = Grp->getMember(i)) {
1415         if (Grp->getInsertPos() == I)
1416           WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
1417         else
1418           WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, 0);
1419       }
1420     }
1421   }
1422 
1423   /// Return the cost model decision for the given instruction \p I and vector
1424   /// width \p VF. Return CM_Unknown if this instruction did not pass
1425   /// through the cost modeling.
1426   InstWidening getWideningDecision(Instruction *I, ElementCount VF) const {
1427     assert(VF.isVector() && "Expected VF to be a vector VF");
1428     // Cost model is not run in the VPlan-native path - return conservative
1429     // result until this changes.
1430     if (EnableVPlanNativePath)
1431       return CM_GatherScatter;
1432 
1433     std::pair<Instruction *, ElementCount> InstOnVF = std::make_pair(I, VF);
1434     auto Itr = WideningDecisions.find(InstOnVF);
1435     if (Itr == WideningDecisions.end())
1436       return CM_Unknown;
1437     return Itr->second.first;
1438   }
1439 
1440   /// Return the vectorization cost for the given instruction \p I and vector
1441   /// width \p VF.
1442   InstructionCost getWideningCost(Instruction *I, ElementCount VF) {
1443     assert(VF.isVector() && "Expected VF >=2");
1444     std::pair<Instruction *, ElementCount> InstOnVF = std::make_pair(I, VF);
1445     assert(WideningDecisions.find(InstOnVF) != WideningDecisions.end() &&
1446            "The cost is not calculated");
1447     return WideningDecisions[InstOnVF].second;
1448   }
1449 
1450   /// Return True if instruction \p I is an optimizable truncate whose operand
1451   /// is an induction variable. Such a truncate will be removed by adding a new
1452   /// induction variable with the destination type.
1453   bool isOptimizableIVTruncate(Instruction *I, ElementCount VF) {
1454     // If the instruction is not a truncate, return false.
1455     auto *Trunc = dyn_cast<TruncInst>(I);
1456     if (!Trunc)
1457       return false;
1458 
1459     // Get the source and destination types of the truncate.
1460     Type *SrcTy = ToVectorTy(cast<CastInst>(I)->getSrcTy(), VF);
1461     Type *DestTy = ToVectorTy(cast<CastInst>(I)->getDestTy(), VF);
1462 
1463     // If the truncate is free for the given types, return false. Replacing a
1464     // free truncate with an induction variable would add an induction variable
1465     // update instruction to each iteration of the loop. We exclude from this
1466     // check the primary induction variable since it will need an update
1467     // instruction regardless.
1468     Value *Op = Trunc->getOperand(0);
1469     if (Op != Legal->getPrimaryInduction() && TTI.isTruncateFree(SrcTy, DestTy))
1470       return false;
1471 
1472     // If the truncated value is not an induction variable, return false.
1473     return Legal->isInductionPhi(Op);
1474   }
1475 
1476   /// Collects the instructions to scalarize for each predicated instruction in
1477   /// the loop.
1478   void collectInstsToScalarize(ElementCount VF);
1479 
1480   /// Collect Uniform and Scalar values for the given \p VF.
1481   /// The sets depend on CM decision for Load/Store instructions
1482   /// that may be vectorized as interleave, gather-scatter or scalarized.
1483   void collectUniformsAndScalars(ElementCount VF) {
1484     // Do the analysis once.
1485     if (VF.isScalar() || Uniforms.find(VF) != Uniforms.end())
1486       return;
1487     setCostBasedWideningDecision(VF);
1488     collectLoopUniforms(VF);
1489     collectLoopScalars(VF);
1490   }
1491 
1492   /// Returns true if the target machine supports masked store operation
1493   /// for the given \p DataType and kind of access to \p Ptr.
1494   bool isLegalMaskedStore(Type *DataType, Value *Ptr, Align Alignment) const {
1495     return Legal->isConsecutivePtr(DataType, Ptr) &&
1496            TTI.isLegalMaskedStore(DataType, Alignment);
1497   }
1498 
1499   /// Returns true if the target machine supports masked load operation
1500   /// for the given \p DataType and kind of access to \p Ptr.
1501   bool isLegalMaskedLoad(Type *DataType, Value *Ptr, Align Alignment) const {
1502     return Legal->isConsecutivePtr(DataType, Ptr) &&
1503            TTI.isLegalMaskedLoad(DataType, Alignment);
1504   }
1505 
1506   /// Returns true if the target machine can represent \p V as a masked gather
1507   /// or scatter operation.
1508   bool isLegalGatherOrScatter(Value *V,
1509                               ElementCount VF = ElementCount::getFixed(1)) {
1510     bool LI = isa<LoadInst>(V);
1511     bool SI = isa<StoreInst>(V);
1512     if (!LI && !SI)
1513       return false;
1514     auto *Ty = getLoadStoreType(V);
1515     Align Align = getLoadStoreAlignment(V);
1516     if (VF.isVector())
1517       Ty = VectorType::get(Ty, VF);
1518     return (LI && TTI.isLegalMaskedGather(Ty, Align)) ||
1519            (SI && TTI.isLegalMaskedScatter(Ty, Align));
1520   }
1521 
1522   /// Returns true if the target machine supports all of the reduction
1523   /// variables found for the given VF.
1524   bool canVectorizeReductions(ElementCount VF) const {
1525     return (all_of(Legal->getReductionVars(), [&](auto &Reduction) -> bool {
1526       const RecurrenceDescriptor &RdxDesc = Reduction.second;
1527       return TTI.isLegalToVectorizeReduction(RdxDesc, VF);
1528     }));
1529   }
1530 
1531   /// Returns true if \p I is an instruction that will be scalarized with
1532   /// predication when vectorizing \p I with vectorization factor \p VF. Such
1533   /// instructions include conditional stores and instructions that may divide
1534   /// by zero.
1535   bool isScalarWithPredication(Instruction *I, ElementCount VF) const;
1536 
1537   // Returns true if \p I is an instruction that will be predicated either
1538   // through scalar predication or masked load/store or masked gather/scatter.
1539   // \p VF is the vectorization factor that will be used to vectorize \p I.
1540   // Superset of instructions that return true for isScalarWithPredication.
1541   bool isPredicatedInst(Instruction *I, ElementCount VF,
1542                         bool IsKnownUniform = false) {
1543     // When we know the load is uniform and the original scalar loop was not
1544     // predicated we don't need to mark it as a predicated instruction. Any
1545     // vectorised blocks created when tail-folding are something artificial we
1546     // have introduced and we know there is always at least one active lane.
1547     // That's why we call Legal->blockNeedsPredication here because it doesn't
1548     // query tail-folding.
1549     if (IsKnownUniform && isa<LoadInst>(I) &&
1550         !Legal->blockNeedsPredication(I->getParent()))
1551       return false;
1552     if (!blockNeedsPredicationForAnyReason(I->getParent()))
1553       return false;
1554     // Loads and stores that need some form of masked operation are predicated
1555     // instructions.
1556     if (isa<LoadInst>(I) || isa<StoreInst>(I))
1557       return Legal->isMaskRequired(I);
1558     return isScalarWithPredication(I, VF);
1559   }
1560 
1561   /// Returns true if \p I is a memory instruction with consecutive memory
1562   /// access that can be widened.
1563   bool
1564   memoryInstructionCanBeWidened(Instruction *I,
1565                                 ElementCount VF = ElementCount::getFixed(1));
1566 
1567   /// Returns true if \p I is a memory instruction in an interleaved-group
1568   /// of memory accesses that can be vectorized with wide vector loads/stores
1569   /// and shuffles.
1570   bool
1571   interleavedAccessCanBeWidened(Instruction *I,
1572                                 ElementCount VF = ElementCount::getFixed(1));
1573 
1574   /// Check if \p Instr belongs to any interleaved access group.
1575   bool isAccessInterleaved(Instruction *Instr) {
1576     return InterleaveInfo.isInterleaved(Instr);
1577   }
1578 
1579   /// Get the interleaved access group that \p Instr belongs to.
1580   const InterleaveGroup<Instruction> *
1581   getInterleavedAccessGroup(Instruction *Instr) {
1582     return InterleaveInfo.getInterleaveGroup(Instr);
1583   }
1584 
1585   /// Returns true if we're required to use a scalar epilogue for at least
1586   /// the final iteration of the original loop.
1587   bool requiresScalarEpilogue(ElementCount VF) const {
1588     if (!isScalarEpilogueAllowed())
1589       return false;
1590     // If we might exit from anywhere but the latch, must run the exiting
1591     // iteration in scalar form.
1592     if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch())
1593       return true;
1594     return VF.isVector() && InterleaveInfo.requiresScalarEpilogue();
1595   }
1596 
1597   /// Returns true if a scalar epilogue is not allowed due to optsize or a
1598   /// loop hint annotation.
1599   bool isScalarEpilogueAllowed() const {
1600     return ScalarEpilogueStatus == CM_ScalarEpilogueAllowed;
1601   }
1602 
1603   /// Returns true if all loop blocks should be masked to fold tail loop.
1604   bool foldTailByMasking() const { return FoldTailByMasking; }
1605 
1606   /// Returns true if the instructions in this block requires predication
1607   /// for any reason, e.g. because tail folding now requires a predicate
1608   /// or because the block in the original loop was predicated.
1609   bool blockNeedsPredicationForAnyReason(BasicBlock *BB) const {
1610     return foldTailByMasking() || Legal->blockNeedsPredication(BB);
1611   }
1612 
1613   /// A SmallMapVector to store the InLoop reduction op chains, mapping phi
1614   /// nodes to the chain of instructions representing the reductions. Uses a
1615   /// MapVector to ensure deterministic iteration order.
1616   using ReductionChainMap =
1617       SmallMapVector<PHINode *, SmallVector<Instruction *, 4>, 4>;
1618 
1619   /// Return the chain of instructions representing an inloop reduction.
1620   const ReductionChainMap &getInLoopReductionChains() const {
1621     return InLoopReductionChains;
1622   }
1623 
1624   /// Returns true if the Phi is part of an inloop reduction.
1625   bool isInLoopReduction(PHINode *Phi) const {
1626     return InLoopReductionChains.count(Phi);
1627   }
1628 
1629   /// Estimate cost of an intrinsic call instruction CI if it were vectorized
1630   /// with factor VF.  Return the cost of the instruction, including
1631   /// scalarization overhead if it's needed.
1632   InstructionCost getVectorIntrinsicCost(CallInst *CI, ElementCount VF) const;
1633 
1634   /// Estimate cost of a call instruction CI if it were vectorized with factor
1635   /// VF. Return the cost of the instruction, including scalarization overhead
1636   /// if it's needed. The flag NeedToScalarize shows if the call needs to be
1637   /// scalarized -
1638   /// i.e. either vector version isn't available, or is too expensive.
1639   InstructionCost getVectorCallCost(CallInst *CI, ElementCount VF,
1640                                     bool &NeedToScalarize) const;
1641 
1642   /// Returns true if the per-lane cost of VectorizationFactor A is lower than
1643   /// that of B.
1644   bool isMoreProfitable(const VectorizationFactor &A,
1645                         const VectorizationFactor &B) const;
1646 
1647   /// Invalidates decisions already taken by the cost model.
1648   void invalidateCostModelingDecisions() {
1649     WideningDecisions.clear();
1650     Uniforms.clear();
1651     Scalars.clear();
1652   }
1653 
1654 private:
1655   unsigned NumPredStores = 0;
1656 
1657   /// Convenience function that returns the value of vscale_range iff
1658   /// vscale_range.min == vscale_range.max or otherwise returns the value
1659   /// returned by the corresponding TLI method.
1660   Optional<unsigned> getVScaleForTuning() const;
1661 
1662   /// \return An upper bound for the vectorization factors for both
1663   /// fixed and scalable vectorization, where the minimum-known number of
1664   /// elements is a power-of-2 larger than zero. If scalable vectorization is
1665   /// disabled or unsupported, then the scalable part will be equal to
1666   /// ElementCount::getScalable(0).
1667   FixedScalableVFPair computeFeasibleMaxVF(unsigned ConstTripCount,
1668                                            ElementCount UserVF,
1669                                            bool FoldTailByMasking);
1670 
1671   /// \return the maximized element count based on the targets vector
1672   /// registers and the loop trip-count, but limited to a maximum safe VF.
1673   /// This is a helper function of computeFeasibleMaxVF.
1674   /// FIXME: MaxSafeVF is currently passed by reference to avoid some obscure
1675   /// issue that occurred on one of the buildbots which cannot be reproduced
1676   /// without having access to the properietary compiler (see comments on
1677   /// D98509). The issue is currently under investigation and this workaround
1678   /// will be removed as soon as possible.
1679   ElementCount getMaximizedVFForTarget(unsigned ConstTripCount,
1680                                        unsigned SmallestType,
1681                                        unsigned WidestType,
1682                                        const ElementCount &MaxSafeVF,
1683                                        bool FoldTailByMasking);
1684 
1685   /// \return the maximum legal scalable VF, based on the safe max number
1686   /// of elements.
1687   ElementCount getMaxLegalScalableVF(unsigned MaxSafeElements);
1688 
1689   /// The vectorization cost is a combination of the cost itself and a boolean
1690   /// indicating whether any of the contributing operations will actually
1691   /// operate on vector values after type legalization in the backend. If this
1692   /// latter value is false, then all operations will be scalarized (i.e. no
1693   /// vectorization has actually taken place).
1694   using VectorizationCostTy = std::pair<InstructionCost, bool>;
1695 
1696   /// Returns the expected execution cost. The unit of the cost does
1697   /// not matter because we use the 'cost' units to compare different
1698   /// vector widths. The cost that is returned is *not* normalized by
1699   /// the factor width. If \p Invalid is not nullptr, this function
1700   /// will add a pair(Instruction*, ElementCount) to \p Invalid for
1701   /// each instruction that has an Invalid cost for the given VF.
1702   using InstructionVFPair = std::pair<Instruction *, ElementCount>;
1703   VectorizationCostTy
1704   expectedCost(ElementCount VF,
1705                SmallVectorImpl<InstructionVFPair> *Invalid = nullptr);
1706 
1707   /// Returns the execution time cost of an instruction for a given vector
1708   /// width. Vector width of one means scalar.
1709   VectorizationCostTy getInstructionCost(Instruction *I, ElementCount VF);
1710 
1711   /// The cost-computation logic from getInstructionCost which provides
1712   /// the vector type as an output parameter.
1713   InstructionCost getInstructionCost(Instruction *I, ElementCount VF,
1714                                      Type *&VectorTy);
1715 
1716   /// Return the cost of instructions in an inloop reduction pattern, if I is
1717   /// part of that pattern.
1718   Optional<InstructionCost>
1719   getReductionPatternCost(Instruction *I, ElementCount VF, Type *VectorTy,
1720                           TTI::TargetCostKind CostKind);
1721 
1722   /// Calculate vectorization cost of memory instruction \p I.
1723   InstructionCost getMemoryInstructionCost(Instruction *I, ElementCount VF);
1724 
1725   /// The cost computation for scalarized memory instruction.
1726   InstructionCost getMemInstScalarizationCost(Instruction *I, ElementCount VF);
1727 
1728   /// The cost computation for interleaving group of memory instructions.
1729   InstructionCost getInterleaveGroupCost(Instruction *I, ElementCount VF);
1730 
1731   /// The cost computation for Gather/Scatter instruction.
1732   InstructionCost getGatherScatterCost(Instruction *I, ElementCount VF);
1733 
1734   /// The cost computation for widening instruction \p I with consecutive
1735   /// memory access.
1736   InstructionCost getConsecutiveMemOpCost(Instruction *I, ElementCount VF);
1737 
1738   /// The cost calculation for Load/Store instruction \p I with uniform pointer -
1739   /// Load: scalar load + broadcast.
1740   /// Store: scalar store + (loop invariant value stored? 0 : extract of last
1741   /// element)
1742   InstructionCost getUniformMemOpCost(Instruction *I, ElementCount VF);
1743 
1744   /// Estimate the overhead of scalarizing an instruction. This is a
1745   /// convenience wrapper for the type-based getScalarizationOverhead API.
1746   InstructionCost getScalarizationOverhead(Instruction *I,
1747                                            ElementCount VF) const;
1748 
1749   /// Returns whether the instruction is a load or store and will be a emitted
1750   /// as a vector operation.
1751   bool isConsecutiveLoadOrStore(Instruction *I);
1752 
1753   /// Returns true if an artificially high cost for emulated masked memrefs
1754   /// should be used.
1755   bool useEmulatedMaskMemRefHack(Instruction *I, ElementCount VF);
1756 
1757   /// Map of scalar integer values to the smallest bitwidth they can be legally
1758   /// represented as. The vector equivalents of these values should be truncated
1759   /// to this type.
1760   MapVector<Instruction *, uint64_t> MinBWs;
1761 
1762   /// A type representing the costs for instructions if they were to be
1763   /// scalarized rather than vectorized. The entries are Instruction-Cost
1764   /// pairs.
1765   using ScalarCostsTy = DenseMap<Instruction *, InstructionCost>;
1766 
1767   /// A set containing all BasicBlocks that are known to present after
1768   /// vectorization as a predicated block.
1769   SmallPtrSet<BasicBlock *, 4> PredicatedBBsAfterVectorization;
1770 
1771   /// Records whether it is allowed to have the original scalar loop execute at
1772   /// least once. This may be needed as a fallback loop in case runtime
1773   /// aliasing/dependence checks fail, or to handle the tail/remainder
1774   /// iterations when the trip count is unknown or doesn't divide by the VF,
1775   /// or as a peel-loop to handle gaps in interleave-groups.
1776   /// Under optsize and when the trip count is very small we don't allow any
1777   /// iterations to execute in the scalar loop.
1778   ScalarEpilogueLowering ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
1779 
1780   /// All blocks of loop are to be masked to fold tail of scalar iterations.
1781   bool FoldTailByMasking = false;
1782 
1783   /// A map holding scalar costs for different vectorization factors. The
1784   /// presence of a cost for an instruction in the mapping indicates that the
1785   /// instruction will be scalarized when vectorizing with the associated
1786   /// vectorization factor. The entries are VF-ScalarCostTy pairs.
1787   DenseMap<ElementCount, ScalarCostsTy> InstsToScalarize;
1788 
1789   /// Holds the instructions known to be uniform after vectorization.
1790   /// The data is collected per VF.
1791   DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> Uniforms;
1792 
1793   /// Holds the instructions known to be scalar after vectorization.
1794   /// The data is collected per VF.
1795   DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> Scalars;
1796 
1797   /// Holds the instructions (address computations) that are forced to be
1798   /// scalarized.
1799   DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> ForcedScalars;
1800 
1801   /// PHINodes of the reductions that should be expanded in-loop along with
1802   /// their associated chains of reduction operations, in program order from top
1803   /// (PHI) to bottom
1804   ReductionChainMap InLoopReductionChains;
1805 
1806   /// A Map of inloop reduction operations and their immediate chain operand.
1807   /// FIXME: This can be removed once reductions can be costed correctly in
1808   /// vplan. This was added to allow quick lookup to the inloop operations,
1809   /// without having to loop through InLoopReductionChains.
1810   DenseMap<Instruction *, Instruction *> InLoopReductionImmediateChains;
1811 
1812   /// Returns the expected difference in cost from scalarizing the expression
1813   /// feeding a predicated instruction \p PredInst. The instructions to
1814   /// scalarize and their scalar costs are collected in \p ScalarCosts. A
1815   /// non-negative return value implies the expression will be scalarized.
1816   /// Currently, only single-use chains are considered for scalarization.
1817   int computePredInstDiscount(Instruction *PredInst, ScalarCostsTy &ScalarCosts,
1818                               ElementCount VF);
1819 
1820   /// Collect the instructions that are uniform after vectorization. An
1821   /// instruction is uniform if we represent it with a single scalar value in
1822   /// the vectorized loop corresponding to each vector iteration. Examples of
1823   /// uniform instructions include pointer operands of consecutive or
1824   /// interleaved memory accesses. Note that although uniformity implies an
1825   /// instruction will be scalar, the reverse is not true. In general, a
1826   /// scalarized instruction will be represented by VF scalar values in the
1827   /// vectorized loop, each corresponding to an iteration of the original
1828   /// scalar loop.
1829   void collectLoopUniforms(ElementCount VF);
1830 
1831   /// Collect the instructions that are scalar after vectorization. An
1832   /// instruction is scalar if it is known to be uniform or will be scalarized
1833   /// during vectorization. collectLoopScalars should only add non-uniform nodes
1834   /// to the list if they are used by a load/store instruction that is marked as
1835   /// CM_Scalarize. Non-uniform scalarized instructions will be represented by
1836   /// VF values in the vectorized loop, each corresponding to an iteration of
1837   /// the original scalar loop.
1838   void collectLoopScalars(ElementCount VF);
1839 
1840   /// Keeps cost model vectorization decision and cost for instructions.
1841   /// Right now it is used for memory instructions only.
1842   using DecisionList = DenseMap<std::pair<Instruction *, ElementCount>,
1843                                 std::pair<InstWidening, InstructionCost>>;
1844 
1845   DecisionList WideningDecisions;
1846 
1847   /// Returns true if \p V is expected to be vectorized and it needs to be
1848   /// extracted.
1849   bool needsExtract(Value *V, ElementCount VF) const {
1850     Instruction *I = dyn_cast<Instruction>(V);
1851     if (VF.isScalar() || !I || !TheLoop->contains(I) ||
1852         TheLoop->isLoopInvariant(I))
1853       return false;
1854 
1855     // Assume we can vectorize V (and hence we need extraction) if the
1856     // scalars are not computed yet. This can happen, because it is called
1857     // via getScalarizationOverhead from setCostBasedWideningDecision, before
1858     // the scalars are collected. That should be a safe assumption in most
1859     // cases, because we check if the operands have vectorizable types
1860     // beforehand in LoopVectorizationLegality.
1861     return Scalars.find(VF) == Scalars.end() ||
1862            !isScalarAfterVectorization(I, VF);
1863   };
1864 
1865   /// Returns a range containing only operands needing to be extracted.
1866   SmallVector<Value *, 4> filterExtractingOperands(Instruction::op_range Ops,
1867                                                    ElementCount VF) const {
1868     return SmallVector<Value *, 4>(make_filter_range(
1869         Ops, [this, VF](Value *V) { return this->needsExtract(V, VF); }));
1870   }
1871 
1872   /// Determines if we have the infrastructure to vectorize loop \p L and its
1873   /// epilogue, assuming the main loop is vectorized by \p VF.
1874   bool isCandidateForEpilogueVectorization(const Loop &L,
1875                                            const ElementCount VF) const;
1876 
1877   /// Returns true if epilogue vectorization is considered profitable, and
1878   /// false otherwise.
1879   /// \p VF is the vectorization factor chosen for the original loop.
1880   bool isEpilogueVectorizationProfitable(const ElementCount VF) const;
1881 
1882 public:
1883   /// The loop that we evaluate.
1884   Loop *TheLoop;
1885 
1886   /// Predicated scalar evolution analysis.
1887   PredicatedScalarEvolution &PSE;
1888 
1889   /// Loop Info analysis.
1890   LoopInfo *LI;
1891 
1892   /// Vectorization legality.
1893   LoopVectorizationLegality *Legal;
1894 
1895   /// Vector target information.
1896   const TargetTransformInfo &TTI;
1897 
1898   /// Target Library Info.
1899   const TargetLibraryInfo *TLI;
1900 
1901   /// Demanded bits analysis.
1902   DemandedBits *DB;
1903 
1904   /// Assumption cache.
1905   AssumptionCache *AC;
1906 
1907   /// Interface to emit optimization remarks.
1908   OptimizationRemarkEmitter *ORE;
1909 
1910   const Function *TheFunction;
1911 
1912   /// Loop Vectorize Hint.
1913   const LoopVectorizeHints *Hints;
1914 
1915   /// The interleave access information contains groups of interleaved accesses
1916   /// with the same stride and close to each other.
1917   InterleavedAccessInfo &InterleaveInfo;
1918 
1919   /// Values to ignore in the cost model.
1920   SmallPtrSet<const Value *, 16> ValuesToIgnore;
1921 
1922   /// Values to ignore in the cost model when VF > 1.
1923   SmallPtrSet<const Value *, 16> VecValuesToIgnore;
1924 
1925   /// All element types found in the loop.
1926   SmallPtrSet<Type *, 16> ElementTypesInLoop;
1927 
1928   /// Profitable vector factors.
1929   SmallVector<VectorizationFactor, 8> ProfitableVFs;
1930 };
1931 } // end namespace llvm
1932 
1933 /// Helper struct to manage generating runtime checks for vectorization.
1934 ///
1935 /// The runtime checks are created up-front in temporary blocks to allow better
1936 /// estimating the cost and un-linked from the existing IR. After deciding to
1937 /// vectorize, the checks are moved back. If deciding not to vectorize, the
1938 /// temporary blocks are completely removed.
1939 class GeneratedRTChecks {
1940   /// Basic block which contains the generated SCEV checks, if any.
1941   BasicBlock *SCEVCheckBlock = nullptr;
1942 
1943   /// The value representing the result of the generated SCEV checks. If it is
1944   /// nullptr, either no SCEV checks have been generated or they have been used.
1945   Value *SCEVCheckCond = nullptr;
1946 
1947   /// Basic block which contains the generated memory runtime checks, if any.
1948   BasicBlock *MemCheckBlock = nullptr;
1949 
1950   /// The value representing the result of the generated memory runtime checks.
1951   /// If it is nullptr, either no memory runtime checks have been generated or
1952   /// they have been used.
1953   Value *MemRuntimeCheckCond = nullptr;
1954 
1955   DominatorTree *DT;
1956   LoopInfo *LI;
1957 
1958   SCEVExpander SCEVExp;
1959   SCEVExpander MemCheckExp;
1960 
1961 public:
1962   GeneratedRTChecks(ScalarEvolution &SE, DominatorTree *DT, LoopInfo *LI,
1963                     const DataLayout &DL)
1964       : DT(DT), LI(LI), SCEVExp(SE, DL, "scev.check"),
1965         MemCheckExp(SE, DL, "scev.check") {}
1966 
1967   /// Generate runtime checks in SCEVCheckBlock and MemCheckBlock, so we can
1968   /// accurately estimate the cost of the runtime checks. The blocks are
1969   /// un-linked from the IR and is added back during vector code generation. If
1970   /// there is no vector code generation, the check blocks are removed
1971   /// completely.
1972   void Create(Loop *L, const LoopAccessInfo &LAI,
1973               const SCEVPredicate &Pred) {
1974 
1975     BasicBlock *LoopHeader = L->getHeader();
1976     BasicBlock *Preheader = L->getLoopPreheader();
1977 
1978     // Use SplitBlock to create blocks for SCEV & memory runtime checks to
1979     // ensure the blocks are properly added to LoopInfo & DominatorTree. Those
1980     // may be used by SCEVExpander. The blocks will be un-linked from their
1981     // predecessors and removed from LI & DT at the end of the function.
1982     if (!Pred.isAlwaysTrue()) {
1983       SCEVCheckBlock = SplitBlock(Preheader, Preheader->getTerminator(), DT, LI,
1984                                   nullptr, "vector.scevcheck");
1985 
1986       SCEVCheckCond = SCEVExp.expandCodeForPredicate(
1987           &Pred, SCEVCheckBlock->getTerminator());
1988     }
1989 
1990     const auto &RtPtrChecking = *LAI.getRuntimePointerChecking();
1991     if (RtPtrChecking.Need) {
1992       auto *Pred = SCEVCheckBlock ? SCEVCheckBlock : Preheader;
1993       MemCheckBlock = SplitBlock(Pred, Pred->getTerminator(), DT, LI, nullptr,
1994                                  "vector.memcheck");
1995 
1996       MemRuntimeCheckCond =
1997           addRuntimeChecks(MemCheckBlock->getTerminator(), L,
1998                            RtPtrChecking.getChecks(), MemCheckExp);
1999       assert(MemRuntimeCheckCond &&
2000              "no RT checks generated although RtPtrChecking "
2001              "claimed checks are required");
2002     }
2003 
2004     if (!MemCheckBlock && !SCEVCheckBlock)
2005       return;
2006 
2007     // Unhook the temporary block with the checks, update various places
2008     // accordingly.
2009     if (SCEVCheckBlock)
2010       SCEVCheckBlock->replaceAllUsesWith(Preheader);
2011     if (MemCheckBlock)
2012       MemCheckBlock->replaceAllUsesWith(Preheader);
2013 
2014     if (SCEVCheckBlock) {
2015       SCEVCheckBlock->getTerminator()->moveBefore(Preheader->getTerminator());
2016       new UnreachableInst(Preheader->getContext(), SCEVCheckBlock);
2017       Preheader->getTerminator()->eraseFromParent();
2018     }
2019     if (MemCheckBlock) {
2020       MemCheckBlock->getTerminator()->moveBefore(Preheader->getTerminator());
2021       new UnreachableInst(Preheader->getContext(), MemCheckBlock);
2022       Preheader->getTerminator()->eraseFromParent();
2023     }
2024 
2025     DT->changeImmediateDominator(LoopHeader, Preheader);
2026     if (MemCheckBlock) {
2027       DT->eraseNode(MemCheckBlock);
2028       LI->removeBlock(MemCheckBlock);
2029     }
2030     if (SCEVCheckBlock) {
2031       DT->eraseNode(SCEVCheckBlock);
2032       LI->removeBlock(SCEVCheckBlock);
2033     }
2034   }
2035 
2036   /// Remove the created SCEV & memory runtime check blocks & instructions, if
2037   /// unused.
2038   ~GeneratedRTChecks() {
2039     SCEVExpanderCleaner SCEVCleaner(SCEVExp);
2040     SCEVExpanderCleaner MemCheckCleaner(MemCheckExp);
2041     if (!SCEVCheckCond)
2042       SCEVCleaner.markResultUsed();
2043 
2044     if (!MemRuntimeCheckCond)
2045       MemCheckCleaner.markResultUsed();
2046 
2047     if (MemRuntimeCheckCond) {
2048       auto &SE = *MemCheckExp.getSE();
2049       // Memory runtime check generation creates compares that use expanded
2050       // values. Remove them before running the SCEVExpanderCleaners.
2051       for (auto &I : make_early_inc_range(reverse(*MemCheckBlock))) {
2052         if (MemCheckExp.isInsertedInstruction(&I))
2053           continue;
2054         SE.forgetValue(&I);
2055         I.eraseFromParent();
2056       }
2057     }
2058     MemCheckCleaner.cleanup();
2059     SCEVCleaner.cleanup();
2060 
2061     if (SCEVCheckCond)
2062       SCEVCheckBlock->eraseFromParent();
2063     if (MemRuntimeCheckCond)
2064       MemCheckBlock->eraseFromParent();
2065   }
2066 
2067   /// Adds the generated SCEVCheckBlock before \p LoopVectorPreHeader and
2068   /// adjusts the branches to branch to the vector preheader or \p Bypass,
2069   /// depending on the generated condition.
2070   BasicBlock *emitSCEVChecks(BasicBlock *Bypass,
2071                              BasicBlock *LoopVectorPreHeader,
2072                              BasicBlock *LoopExitBlock) {
2073     if (!SCEVCheckCond)
2074       return nullptr;
2075     if (auto *C = dyn_cast<ConstantInt>(SCEVCheckCond))
2076       if (C->isZero())
2077         return nullptr;
2078 
2079     auto *Pred = LoopVectorPreHeader->getSinglePredecessor();
2080 
2081     BranchInst::Create(LoopVectorPreHeader, SCEVCheckBlock);
2082     // Create new preheader for vector loop.
2083     if (auto *PL = LI->getLoopFor(LoopVectorPreHeader))
2084       PL->addBasicBlockToLoop(SCEVCheckBlock, *LI);
2085 
2086     SCEVCheckBlock->getTerminator()->eraseFromParent();
2087     SCEVCheckBlock->moveBefore(LoopVectorPreHeader);
2088     Pred->getTerminator()->replaceSuccessorWith(LoopVectorPreHeader,
2089                                                 SCEVCheckBlock);
2090 
2091     DT->addNewBlock(SCEVCheckBlock, Pred);
2092     DT->changeImmediateDominator(LoopVectorPreHeader, SCEVCheckBlock);
2093 
2094     ReplaceInstWithInst(
2095         SCEVCheckBlock->getTerminator(),
2096         BranchInst::Create(Bypass, LoopVectorPreHeader, SCEVCheckCond));
2097     // Mark the check as used, to prevent it from being removed during cleanup.
2098     SCEVCheckCond = nullptr;
2099     return SCEVCheckBlock;
2100   }
2101 
2102   /// Adds the generated MemCheckBlock before \p LoopVectorPreHeader and adjusts
2103   /// the branches to branch to the vector preheader or \p Bypass, depending on
2104   /// the generated condition.
2105   BasicBlock *emitMemRuntimeChecks(BasicBlock *Bypass,
2106                                    BasicBlock *LoopVectorPreHeader) {
2107     // Check if we generated code that checks in runtime if arrays overlap.
2108     if (!MemRuntimeCheckCond)
2109       return nullptr;
2110 
2111     auto *Pred = LoopVectorPreHeader->getSinglePredecessor();
2112     Pred->getTerminator()->replaceSuccessorWith(LoopVectorPreHeader,
2113                                                 MemCheckBlock);
2114 
2115     DT->addNewBlock(MemCheckBlock, Pred);
2116     DT->changeImmediateDominator(LoopVectorPreHeader, MemCheckBlock);
2117     MemCheckBlock->moveBefore(LoopVectorPreHeader);
2118 
2119     if (auto *PL = LI->getLoopFor(LoopVectorPreHeader))
2120       PL->addBasicBlockToLoop(MemCheckBlock, *LI);
2121 
2122     ReplaceInstWithInst(
2123         MemCheckBlock->getTerminator(),
2124         BranchInst::Create(Bypass, LoopVectorPreHeader, MemRuntimeCheckCond));
2125     MemCheckBlock->getTerminator()->setDebugLoc(
2126         Pred->getTerminator()->getDebugLoc());
2127 
2128     // Mark the check as used, to prevent it from being removed during cleanup.
2129     MemRuntimeCheckCond = nullptr;
2130     return MemCheckBlock;
2131   }
2132 };
2133 
2134 // Return true if \p OuterLp is an outer loop annotated with hints for explicit
2135 // vectorization. The loop needs to be annotated with #pragma omp simd
2136 // simdlen(#) or #pragma clang vectorize(enable) vectorize_width(#). If the
2137 // vector length information is not provided, vectorization is not considered
2138 // explicit. Interleave hints are not allowed either. These limitations will be
2139 // relaxed in the future.
2140 // Please, note that we are currently forced to abuse the pragma 'clang
2141 // vectorize' semantics. This pragma provides *auto-vectorization hints*
2142 // (i.e., LV must check that vectorization is legal) whereas pragma 'omp simd'
2143 // provides *explicit vectorization hints* (LV can bypass legal checks and
2144 // assume that vectorization is legal). However, both hints are implemented
2145 // using the same metadata (llvm.loop.vectorize, processed by
2146 // LoopVectorizeHints). This will be fixed in the future when the native IR
2147 // representation for pragma 'omp simd' is introduced.
2148 static bool isExplicitVecOuterLoop(Loop *OuterLp,
2149                                    OptimizationRemarkEmitter *ORE) {
2150   assert(!OuterLp->isInnermost() && "This is not an outer loop");
2151   LoopVectorizeHints Hints(OuterLp, true /*DisableInterleaving*/, *ORE);
2152 
2153   // Only outer loops with an explicit vectorization hint are supported.
2154   // Unannotated outer loops are ignored.
2155   if (Hints.getForce() == LoopVectorizeHints::FK_Undefined)
2156     return false;
2157 
2158   Function *Fn = OuterLp->getHeader()->getParent();
2159   if (!Hints.allowVectorization(Fn, OuterLp,
2160                                 true /*VectorizeOnlyWhenForced*/)) {
2161     LLVM_DEBUG(dbgs() << "LV: Loop hints prevent outer loop vectorization.\n");
2162     return false;
2163   }
2164 
2165   if (Hints.getInterleave() > 1) {
2166     // TODO: Interleave support is future work.
2167     LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Interleave is not supported for "
2168                          "outer loops.\n");
2169     Hints.emitRemarkWithHints();
2170     return false;
2171   }
2172 
2173   return true;
2174 }
2175 
2176 static void collectSupportedLoops(Loop &L, LoopInfo *LI,
2177                                   OptimizationRemarkEmitter *ORE,
2178                                   SmallVectorImpl<Loop *> &V) {
2179   // Collect inner loops and outer loops without irreducible control flow. For
2180   // now, only collect outer loops that have explicit vectorization hints. If we
2181   // are stress testing the VPlan H-CFG construction, we collect the outermost
2182   // loop of every loop nest.
2183   if (L.isInnermost() || VPlanBuildStressTest ||
2184       (EnableVPlanNativePath && isExplicitVecOuterLoop(&L, ORE))) {
2185     LoopBlocksRPO RPOT(&L);
2186     RPOT.perform(LI);
2187     if (!containsIrreducibleCFG<const BasicBlock *>(RPOT, *LI)) {
2188       V.push_back(&L);
2189       // TODO: Collect inner loops inside marked outer loops in case
2190       // vectorization fails for the outer loop. Do not invoke
2191       // 'containsIrreducibleCFG' again for inner loops when the outer loop is
2192       // already known to be reducible. We can use an inherited attribute for
2193       // that.
2194       return;
2195     }
2196   }
2197   for (Loop *InnerL : L)
2198     collectSupportedLoops(*InnerL, LI, ORE, V);
2199 }
2200 
2201 namespace {
2202 
2203 /// The LoopVectorize Pass.
2204 struct LoopVectorize : public FunctionPass {
2205   /// Pass identification, replacement for typeid
2206   static char ID;
2207 
2208   LoopVectorizePass Impl;
2209 
2210   explicit LoopVectorize(bool InterleaveOnlyWhenForced = false,
2211                          bool VectorizeOnlyWhenForced = false)
2212       : FunctionPass(ID),
2213         Impl({InterleaveOnlyWhenForced, VectorizeOnlyWhenForced}) {
2214     initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
2215   }
2216 
2217   bool runOnFunction(Function &F) override {
2218     if (skipFunction(F))
2219       return false;
2220 
2221     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
2222     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2223     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
2224     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2225     auto *BFI = &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI();
2226     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
2227     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
2228     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
2229     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
2230     auto *LAA = &getAnalysis<LoopAccessLegacyAnalysis>();
2231     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
2232     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
2233     auto *PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
2234 
2235     std::function<const LoopAccessInfo &(Loop &)> GetLAA =
2236         [&](Loop &L) -> const LoopAccessInfo & { return LAA->getInfo(&L); };
2237 
2238     return Impl.runImpl(F, *SE, *LI, *TTI, *DT, *BFI, TLI, *DB, *AA, *AC,
2239                         GetLAA, *ORE, PSI).MadeAnyChange;
2240   }
2241 
2242   void getAnalysisUsage(AnalysisUsage &AU) const override {
2243     AU.addRequired<AssumptionCacheTracker>();
2244     AU.addRequired<BlockFrequencyInfoWrapperPass>();
2245     AU.addRequired<DominatorTreeWrapperPass>();
2246     AU.addRequired<LoopInfoWrapperPass>();
2247     AU.addRequired<ScalarEvolutionWrapperPass>();
2248     AU.addRequired<TargetTransformInfoWrapperPass>();
2249     AU.addRequired<AAResultsWrapperPass>();
2250     AU.addRequired<LoopAccessLegacyAnalysis>();
2251     AU.addRequired<DemandedBitsWrapperPass>();
2252     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
2253     AU.addRequired<InjectTLIMappingsLegacy>();
2254 
2255     // We currently do not preserve loopinfo/dominator analyses with outer loop
2256     // vectorization. Until this is addressed, mark these analyses as preserved
2257     // only for non-VPlan-native path.
2258     // TODO: Preserve Loop and Dominator analyses for VPlan-native path.
2259     if (!EnableVPlanNativePath) {
2260       AU.addPreserved<LoopInfoWrapperPass>();
2261       AU.addPreserved<DominatorTreeWrapperPass>();
2262     }
2263 
2264     AU.addPreserved<BasicAAWrapperPass>();
2265     AU.addPreserved<GlobalsAAWrapperPass>();
2266     AU.addRequired<ProfileSummaryInfoWrapperPass>();
2267   }
2268 };
2269 
2270 } // end anonymous namespace
2271 
2272 //===----------------------------------------------------------------------===//
2273 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
2274 // LoopVectorizationCostModel and LoopVectorizationPlanner.
2275 //===----------------------------------------------------------------------===//
2276 
2277 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
2278   // We need to place the broadcast of invariant variables outside the loop,
2279   // but only if it's proven safe to do so. Else, broadcast will be inside
2280   // vector loop body.
2281   Instruction *Instr = dyn_cast<Instruction>(V);
2282   bool SafeToHoist = OrigLoop->isLoopInvariant(V) &&
2283                      (!Instr ||
2284                       DT->dominates(Instr->getParent(), LoopVectorPreHeader));
2285   // Place the code for broadcasting invariant variables in the new preheader.
2286   IRBuilder<>::InsertPointGuard Guard(Builder);
2287   if (SafeToHoist)
2288     Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
2289 
2290   // Broadcast the scalar into all locations in the vector.
2291   Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
2292 
2293   return Shuf;
2294 }
2295 
2296 /// This function adds
2297 /// (StartIdx * Step, (StartIdx + 1) * Step, (StartIdx + 2) * Step, ...)
2298 /// to each vector element of Val. The sequence starts at StartIndex.
2299 /// \p Opcode is relevant for FP induction variable.
2300 static Value *getStepVector(Value *Val, Value *StartIdx, Value *Step,
2301                             Instruction::BinaryOps BinOp, ElementCount VF,
2302                             IRBuilderBase &Builder) {
2303   assert(VF.isVector() && "only vector VFs are supported");
2304 
2305   // Create and check the types.
2306   auto *ValVTy = cast<VectorType>(Val->getType());
2307   ElementCount VLen = ValVTy->getElementCount();
2308 
2309   Type *STy = Val->getType()->getScalarType();
2310   assert((STy->isIntegerTy() || STy->isFloatingPointTy()) &&
2311          "Induction Step must be an integer or FP");
2312   assert(Step->getType() == STy && "Step has wrong type");
2313 
2314   SmallVector<Constant *, 8> Indices;
2315 
2316   // Create a vector of consecutive numbers from zero to VF.
2317   VectorType *InitVecValVTy = ValVTy;
2318   if (STy->isFloatingPointTy()) {
2319     Type *InitVecValSTy =
2320         IntegerType::get(STy->getContext(), STy->getScalarSizeInBits());
2321     InitVecValVTy = VectorType::get(InitVecValSTy, VLen);
2322   }
2323   Value *InitVec = Builder.CreateStepVector(InitVecValVTy);
2324 
2325   // Splat the StartIdx
2326   Value *StartIdxSplat = Builder.CreateVectorSplat(VLen, StartIdx);
2327 
2328   if (STy->isIntegerTy()) {
2329     InitVec = Builder.CreateAdd(InitVec, StartIdxSplat);
2330     Step = Builder.CreateVectorSplat(VLen, Step);
2331     assert(Step->getType() == Val->getType() && "Invalid step vec");
2332     // FIXME: The newly created binary instructions should contain nsw/nuw
2333     // flags, which can be found from the original scalar operations.
2334     Step = Builder.CreateMul(InitVec, Step);
2335     return Builder.CreateAdd(Val, Step, "induction");
2336   }
2337 
2338   // Floating point induction.
2339   assert((BinOp == Instruction::FAdd || BinOp == Instruction::FSub) &&
2340          "Binary Opcode should be specified for FP induction");
2341   InitVec = Builder.CreateUIToFP(InitVec, ValVTy);
2342   InitVec = Builder.CreateFAdd(InitVec, StartIdxSplat);
2343 
2344   Step = Builder.CreateVectorSplat(VLen, Step);
2345   Value *MulOp = Builder.CreateFMul(InitVec, Step);
2346   return Builder.CreateBinOp(BinOp, Val, MulOp, "induction");
2347 }
2348 
2349 /// Compute scalar induction steps. \p ScalarIV is the scalar induction
2350 /// variable on which to base the steps, \p Step is the size of the step.
2351 static void buildScalarSteps(Value *ScalarIV, Value *Step,
2352                              const InductionDescriptor &ID, VPValue *Def,
2353                              VPTransformState &State) {
2354   IRBuilderBase &Builder = State.Builder;
2355   // We shouldn't have to build scalar steps if we aren't vectorizing.
2356   assert(State.VF.isVector() && "VF should be greater than one");
2357   // Get the value type and ensure it and the step have the same integer type.
2358   Type *ScalarIVTy = ScalarIV->getType()->getScalarType();
2359   assert(ScalarIVTy == Step->getType() &&
2360          "Val and Step should have the same type");
2361 
2362   // We build scalar steps for both integer and floating-point induction
2363   // variables. Here, we determine the kind of arithmetic we will perform.
2364   Instruction::BinaryOps AddOp;
2365   Instruction::BinaryOps MulOp;
2366   if (ScalarIVTy->isIntegerTy()) {
2367     AddOp = Instruction::Add;
2368     MulOp = Instruction::Mul;
2369   } else {
2370     AddOp = ID.getInductionOpcode();
2371     MulOp = Instruction::FMul;
2372   }
2373 
2374   // Determine the number of scalars we need to generate for each unroll
2375   // iteration.
2376   bool FirstLaneOnly = vputils::onlyFirstLaneUsed(Def);
2377   unsigned Lanes = FirstLaneOnly ? 1 : State.VF.getKnownMinValue();
2378   // Compute the scalar steps and save the results in State.
2379   Type *IntStepTy = IntegerType::get(ScalarIVTy->getContext(),
2380                                      ScalarIVTy->getScalarSizeInBits());
2381   Type *VecIVTy = nullptr;
2382   Value *UnitStepVec = nullptr, *SplatStep = nullptr, *SplatIV = nullptr;
2383   if (!FirstLaneOnly && State.VF.isScalable()) {
2384     VecIVTy = VectorType::get(ScalarIVTy, State.VF);
2385     UnitStepVec =
2386         Builder.CreateStepVector(VectorType::get(IntStepTy, State.VF));
2387     SplatStep = Builder.CreateVectorSplat(State.VF, Step);
2388     SplatIV = Builder.CreateVectorSplat(State.VF, ScalarIV);
2389   }
2390 
2391   for (unsigned Part = 0; Part < State.UF; ++Part) {
2392     Value *StartIdx0 = createStepForVF(Builder, IntStepTy, State.VF, Part);
2393 
2394     if (!FirstLaneOnly && State.VF.isScalable()) {
2395       auto *SplatStartIdx = Builder.CreateVectorSplat(State.VF, StartIdx0);
2396       auto *InitVec = Builder.CreateAdd(SplatStartIdx, UnitStepVec);
2397       if (ScalarIVTy->isFloatingPointTy())
2398         InitVec = Builder.CreateSIToFP(InitVec, VecIVTy);
2399       auto *Mul = Builder.CreateBinOp(MulOp, InitVec, SplatStep);
2400       auto *Add = Builder.CreateBinOp(AddOp, SplatIV, Mul);
2401       State.set(Def, Add, Part);
2402       // It's useful to record the lane values too for the known minimum number
2403       // of elements so we do those below. This improves the code quality when
2404       // trying to extract the first element, for example.
2405     }
2406 
2407     if (ScalarIVTy->isFloatingPointTy())
2408       StartIdx0 = Builder.CreateSIToFP(StartIdx0, ScalarIVTy);
2409 
2410     for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
2411       Value *StartIdx = Builder.CreateBinOp(
2412           AddOp, StartIdx0, getSignedIntOrFpConstant(ScalarIVTy, Lane));
2413       // The step returned by `createStepForVF` is a runtime-evaluated value
2414       // when VF is scalable. Otherwise, it should be folded into a Constant.
2415       assert((State.VF.isScalable() || isa<Constant>(StartIdx)) &&
2416              "Expected StartIdx to be folded to a constant when VF is not "
2417              "scalable");
2418       auto *Mul = Builder.CreateBinOp(MulOp, StartIdx, Step);
2419       auto *Add = Builder.CreateBinOp(AddOp, ScalarIV, Mul);
2420       State.set(Def, Add, VPIteration(Part, Lane));
2421     }
2422   }
2423 }
2424 
2425 // Generate code for the induction step. Note that induction steps are
2426 // required to be loop-invariant
2427 static Value *CreateStepValue(const SCEV *Step, ScalarEvolution &SE,
2428                               Instruction *InsertBefore,
2429                               Loop *OrigLoop = nullptr) {
2430   const DataLayout &DL = SE.getDataLayout();
2431   assert((!OrigLoop || SE.isLoopInvariant(Step, OrigLoop)) &&
2432          "Induction step should be loop invariant");
2433   if (auto *E = dyn_cast<SCEVUnknown>(Step))
2434     return E->getValue();
2435 
2436   SCEVExpander Exp(SE, DL, "induction");
2437   return Exp.expandCodeFor(Step, Step->getType(), InsertBefore);
2438 }
2439 
2440 /// Compute the transformed value of Index at offset StartValue using step
2441 /// StepValue.
2442 /// For integer induction, returns StartValue + Index * StepValue.
2443 /// For pointer induction, returns StartValue[Index * StepValue].
2444 /// FIXME: The newly created binary instructions should contain nsw/nuw
2445 /// flags, which can be found from the original scalar operations.
2446 static Value *emitTransformedIndex(IRBuilderBase &B, Value *Index,
2447                                    Value *StartValue, Value *Step,
2448                                    const InductionDescriptor &ID) {
2449   assert(Index->getType()->getScalarType() == Step->getType() &&
2450          "Index scalar type does not match StepValue type");
2451 
2452   // Note: the IR at this point is broken. We cannot use SE to create any new
2453   // SCEV and then expand it, hoping that SCEV's simplification will give us
2454   // a more optimal code. Unfortunately, attempt of doing so on invalid IR may
2455   // lead to various SCEV crashes. So all we can do is to use builder and rely
2456   // on InstCombine for future simplifications. Here we handle some trivial
2457   // cases only.
2458   auto CreateAdd = [&B](Value *X, Value *Y) {
2459     assert(X->getType() == Y->getType() && "Types don't match!");
2460     if (auto *CX = dyn_cast<ConstantInt>(X))
2461       if (CX->isZero())
2462         return Y;
2463     if (auto *CY = dyn_cast<ConstantInt>(Y))
2464       if (CY->isZero())
2465         return X;
2466     return B.CreateAdd(X, Y);
2467   };
2468 
2469   // We allow X to be a vector type, in which case Y will potentially be
2470   // splatted into a vector with the same element count.
2471   auto CreateMul = [&B](Value *X, Value *Y) {
2472     assert(X->getType()->getScalarType() == Y->getType() &&
2473            "Types don't match!");
2474     if (auto *CX = dyn_cast<ConstantInt>(X))
2475       if (CX->isOne())
2476         return Y;
2477     if (auto *CY = dyn_cast<ConstantInt>(Y))
2478       if (CY->isOne())
2479         return X;
2480     VectorType *XVTy = dyn_cast<VectorType>(X->getType());
2481     if (XVTy && !isa<VectorType>(Y->getType()))
2482       Y = B.CreateVectorSplat(XVTy->getElementCount(), Y);
2483     return B.CreateMul(X, Y);
2484   };
2485 
2486   switch (ID.getKind()) {
2487   case InductionDescriptor::IK_IntInduction: {
2488     assert(!isa<VectorType>(Index->getType()) &&
2489            "Vector indices not supported for integer inductions yet");
2490     assert(Index->getType() == StartValue->getType() &&
2491            "Index type does not match StartValue type");
2492     if (isa<ConstantInt>(Step) && cast<ConstantInt>(Step)->isMinusOne())
2493       return B.CreateSub(StartValue, Index);
2494     auto *Offset = CreateMul(Index, Step);
2495     return CreateAdd(StartValue, Offset);
2496   }
2497   case InductionDescriptor::IK_PtrInduction: {
2498     assert(isa<Constant>(Step) &&
2499            "Expected constant step for pointer induction");
2500     return B.CreateGEP(ID.getElementType(), StartValue, CreateMul(Index, Step));
2501   }
2502   case InductionDescriptor::IK_FpInduction: {
2503     assert(!isa<VectorType>(Index->getType()) &&
2504            "Vector indices not supported for FP inductions yet");
2505     assert(Step->getType()->isFloatingPointTy() && "Expected FP Step value");
2506     auto InductionBinOp = ID.getInductionBinOp();
2507     assert(InductionBinOp &&
2508            (InductionBinOp->getOpcode() == Instruction::FAdd ||
2509             InductionBinOp->getOpcode() == Instruction::FSub) &&
2510            "Original bin op should be defined for FP induction");
2511 
2512     Value *MulExp = B.CreateFMul(Step, Index);
2513     return B.CreateBinOp(InductionBinOp->getOpcode(), StartValue, MulExp,
2514                          "induction");
2515   }
2516   case InductionDescriptor::IK_NoInduction:
2517     return nullptr;
2518   }
2519   llvm_unreachable("invalid enum");
2520 }
2521 
2522 void InnerLoopVectorizer::packScalarIntoVectorValue(VPValue *Def,
2523                                                     const VPIteration &Instance,
2524                                                     VPTransformState &State) {
2525   Value *ScalarInst = State.get(Def, Instance);
2526   Value *VectorValue = State.get(Def, Instance.Part);
2527   VectorValue = Builder.CreateInsertElement(
2528       VectorValue, ScalarInst,
2529       Instance.Lane.getAsRuntimeExpr(State.Builder, VF));
2530   State.set(Def, VectorValue, Instance.Part);
2531 }
2532 
2533 // Return whether we allow using masked interleave-groups (for dealing with
2534 // strided loads/stores that reside in predicated blocks, or for dealing
2535 // with gaps).
2536 static bool useMaskedInterleavedAccesses(const TargetTransformInfo &TTI) {
2537   // If an override option has been passed in for interleaved accesses, use it.
2538   if (EnableMaskedInterleavedMemAccesses.getNumOccurrences() > 0)
2539     return EnableMaskedInterleavedMemAccesses;
2540 
2541   return TTI.enableMaskedInterleavedAccessVectorization();
2542 }
2543 
2544 // Try to vectorize the interleave group that \p Instr belongs to.
2545 //
2546 // E.g. Translate following interleaved load group (factor = 3):
2547 //   for (i = 0; i < N; i+=3) {
2548 //     R = Pic[i];             // Member of index 0
2549 //     G = Pic[i+1];           // Member of index 1
2550 //     B = Pic[i+2];           // Member of index 2
2551 //     ... // do something to R, G, B
2552 //   }
2553 // To:
2554 //   %wide.vec = load <12 x i32>                       ; Read 4 tuples of R,G,B
2555 //   %R.vec = shuffle %wide.vec, poison, <0, 3, 6, 9>   ; R elements
2556 //   %G.vec = shuffle %wide.vec, poison, <1, 4, 7, 10>  ; G elements
2557 //   %B.vec = shuffle %wide.vec, poison, <2, 5, 8, 11>  ; B elements
2558 //
2559 // Or translate following interleaved store group (factor = 3):
2560 //   for (i = 0; i < N; i+=3) {
2561 //     ... do something to R, G, B
2562 //     Pic[i]   = R;           // Member of index 0
2563 //     Pic[i+1] = G;           // Member of index 1
2564 //     Pic[i+2] = B;           // Member of index 2
2565 //   }
2566 // To:
2567 //   %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
2568 //   %B_U.vec = shuffle %B.vec, poison, <0, 1, 2, 3, u, u, u, u>
2569 //   %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
2570 //        <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>    ; Interleave R,G,B elements
2571 //   store <12 x i32> %interleaved.vec              ; Write 4 tuples of R,G,B
2572 void InnerLoopVectorizer::vectorizeInterleaveGroup(
2573     const InterleaveGroup<Instruction> *Group, ArrayRef<VPValue *> VPDefs,
2574     VPTransformState &State, VPValue *Addr, ArrayRef<VPValue *> StoredValues,
2575     VPValue *BlockInMask) {
2576   Instruction *Instr = Group->getInsertPos();
2577   const DataLayout &DL = Instr->getModule()->getDataLayout();
2578 
2579   // Prepare for the vector type of the interleaved load/store.
2580   Type *ScalarTy = getLoadStoreType(Instr);
2581   unsigned InterleaveFactor = Group->getFactor();
2582   assert(!VF.isScalable() && "scalable vectors not yet supported.");
2583   auto *VecTy = VectorType::get(ScalarTy, VF * InterleaveFactor);
2584 
2585   // Prepare for the new pointers.
2586   SmallVector<Value *, 2> AddrParts;
2587   unsigned Index = Group->getIndex(Instr);
2588 
2589   // TODO: extend the masked interleaved-group support to reversed access.
2590   assert((!BlockInMask || !Group->isReverse()) &&
2591          "Reversed masked interleave-group not supported.");
2592 
2593   // If the group is reverse, adjust the index to refer to the last vector lane
2594   // instead of the first. We adjust the index from the first vector lane,
2595   // rather than directly getting the pointer for lane VF - 1, because the
2596   // pointer operand of the interleaved access is supposed to be uniform. For
2597   // uniform instructions, we're only required to generate a value for the
2598   // first vector lane in each unroll iteration.
2599   if (Group->isReverse())
2600     Index += (VF.getKnownMinValue() - 1) * Group->getFactor();
2601 
2602   for (unsigned Part = 0; Part < UF; Part++) {
2603     Value *AddrPart = State.get(Addr, VPIteration(Part, 0));
2604     setDebugLocFromInst(AddrPart);
2605 
2606     // Notice current instruction could be any index. Need to adjust the address
2607     // to the member of index 0.
2608     //
2609     // E.g.  a = A[i+1];     // Member of index 1 (Current instruction)
2610     //       b = A[i];       // Member of index 0
2611     // Current pointer is pointed to A[i+1], adjust it to A[i].
2612     //
2613     // E.g.  A[i+1] = a;     // Member of index 1
2614     //       A[i]   = b;     // Member of index 0
2615     //       A[i+2] = c;     // Member of index 2 (Current instruction)
2616     // Current pointer is pointed to A[i+2], adjust it to A[i].
2617 
2618     bool InBounds = false;
2619     if (auto *gep = dyn_cast<GetElementPtrInst>(AddrPart->stripPointerCasts()))
2620       InBounds = gep->isInBounds();
2621     AddrPart = Builder.CreateGEP(ScalarTy, AddrPart, Builder.getInt32(-Index));
2622     cast<GetElementPtrInst>(AddrPart)->setIsInBounds(InBounds);
2623 
2624     // Cast to the vector pointer type.
2625     unsigned AddressSpace = AddrPart->getType()->getPointerAddressSpace();
2626     Type *PtrTy = VecTy->getPointerTo(AddressSpace);
2627     AddrParts.push_back(Builder.CreateBitCast(AddrPart, PtrTy));
2628   }
2629 
2630   setDebugLocFromInst(Instr);
2631   Value *PoisonVec = PoisonValue::get(VecTy);
2632 
2633   Value *MaskForGaps = nullptr;
2634   if (Group->requiresScalarEpilogue() && !Cost->isScalarEpilogueAllowed()) {
2635     MaskForGaps = createBitMaskForGaps(Builder, VF.getKnownMinValue(), *Group);
2636     assert(MaskForGaps && "Mask for Gaps is required but it is null");
2637   }
2638 
2639   // Vectorize the interleaved load group.
2640   if (isa<LoadInst>(Instr)) {
2641     // For each unroll part, create a wide load for the group.
2642     SmallVector<Value *, 2> NewLoads;
2643     for (unsigned Part = 0; Part < UF; Part++) {
2644       Instruction *NewLoad;
2645       if (BlockInMask || MaskForGaps) {
2646         assert(useMaskedInterleavedAccesses(*TTI) &&
2647                "masked interleaved groups are not allowed.");
2648         Value *GroupMask = MaskForGaps;
2649         if (BlockInMask) {
2650           Value *BlockInMaskPart = State.get(BlockInMask, Part);
2651           Value *ShuffledMask = Builder.CreateShuffleVector(
2652               BlockInMaskPart,
2653               createReplicatedMask(InterleaveFactor, VF.getKnownMinValue()),
2654               "interleaved.mask");
2655           GroupMask = MaskForGaps
2656                           ? Builder.CreateBinOp(Instruction::And, ShuffledMask,
2657                                                 MaskForGaps)
2658                           : ShuffledMask;
2659         }
2660         NewLoad =
2661             Builder.CreateMaskedLoad(VecTy, AddrParts[Part], Group->getAlign(),
2662                                      GroupMask, PoisonVec, "wide.masked.vec");
2663       }
2664       else
2665         NewLoad = Builder.CreateAlignedLoad(VecTy, AddrParts[Part],
2666                                             Group->getAlign(), "wide.vec");
2667       Group->addMetadata(NewLoad);
2668       NewLoads.push_back(NewLoad);
2669     }
2670 
2671     // For each member in the group, shuffle out the appropriate data from the
2672     // wide loads.
2673     unsigned J = 0;
2674     for (unsigned I = 0; I < InterleaveFactor; ++I) {
2675       Instruction *Member = Group->getMember(I);
2676 
2677       // Skip the gaps in the group.
2678       if (!Member)
2679         continue;
2680 
2681       auto StrideMask =
2682           createStrideMask(I, InterleaveFactor, VF.getKnownMinValue());
2683       for (unsigned Part = 0; Part < UF; Part++) {
2684         Value *StridedVec = Builder.CreateShuffleVector(
2685             NewLoads[Part], StrideMask, "strided.vec");
2686 
2687         // If this member has different type, cast the result type.
2688         if (Member->getType() != ScalarTy) {
2689           assert(!VF.isScalable() && "VF is assumed to be non scalable.");
2690           VectorType *OtherVTy = VectorType::get(Member->getType(), VF);
2691           StridedVec = createBitOrPointerCast(StridedVec, OtherVTy, DL);
2692         }
2693 
2694         if (Group->isReverse())
2695           StridedVec = Builder.CreateVectorReverse(StridedVec, "reverse");
2696 
2697         State.set(VPDefs[J], StridedVec, Part);
2698       }
2699       ++J;
2700     }
2701     return;
2702   }
2703 
2704   // The sub vector type for current instruction.
2705   auto *SubVT = VectorType::get(ScalarTy, VF);
2706 
2707   // Vectorize the interleaved store group.
2708   MaskForGaps = createBitMaskForGaps(Builder, VF.getKnownMinValue(), *Group);
2709   assert((!MaskForGaps || useMaskedInterleavedAccesses(*TTI)) &&
2710          "masked interleaved groups are not allowed.");
2711   assert((!MaskForGaps || !VF.isScalable()) &&
2712          "masking gaps for scalable vectors is not yet supported.");
2713   for (unsigned Part = 0; Part < UF; Part++) {
2714     // Collect the stored vector from each member.
2715     SmallVector<Value *, 4> StoredVecs;
2716     for (unsigned i = 0; i < InterleaveFactor; i++) {
2717       assert((Group->getMember(i) || MaskForGaps) &&
2718              "Fail to get a member from an interleaved store group");
2719       Instruction *Member = Group->getMember(i);
2720 
2721       // Skip the gaps in the group.
2722       if (!Member) {
2723         Value *Undef = PoisonValue::get(SubVT);
2724         StoredVecs.push_back(Undef);
2725         continue;
2726       }
2727 
2728       Value *StoredVec = State.get(StoredValues[i], Part);
2729 
2730       if (Group->isReverse())
2731         StoredVec = Builder.CreateVectorReverse(StoredVec, "reverse");
2732 
2733       // If this member has different type, cast it to a unified type.
2734 
2735       if (StoredVec->getType() != SubVT)
2736         StoredVec = createBitOrPointerCast(StoredVec, SubVT, DL);
2737 
2738       StoredVecs.push_back(StoredVec);
2739     }
2740 
2741     // Concatenate all vectors into a wide vector.
2742     Value *WideVec = concatenateVectors(Builder, StoredVecs);
2743 
2744     // Interleave the elements in the wide vector.
2745     Value *IVec = Builder.CreateShuffleVector(
2746         WideVec, createInterleaveMask(VF.getKnownMinValue(), InterleaveFactor),
2747         "interleaved.vec");
2748 
2749     Instruction *NewStoreInstr;
2750     if (BlockInMask || MaskForGaps) {
2751       Value *GroupMask = MaskForGaps;
2752       if (BlockInMask) {
2753         Value *BlockInMaskPart = State.get(BlockInMask, Part);
2754         Value *ShuffledMask = Builder.CreateShuffleVector(
2755             BlockInMaskPart,
2756             createReplicatedMask(InterleaveFactor, VF.getKnownMinValue()),
2757             "interleaved.mask");
2758         GroupMask = MaskForGaps ? Builder.CreateBinOp(Instruction::And,
2759                                                       ShuffledMask, MaskForGaps)
2760                                 : ShuffledMask;
2761       }
2762       NewStoreInstr = Builder.CreateMaskedStore(IVec, AddrParts[Part],
2763                                                 Group->getAlign(), GroupMask);
2764     } else
2765       NewStoreInstr =
2766           Builder.CreateAlignedStore(IVec, AddrParts[Part], Group->getAlign());
2767 
2768     Group->addMetadata(NewStoreInstr);
2769   }
2770 }
2771 
2772 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr,
2773                                                VPReplicateRecipe *RepRecipe,
2774                                                const VPIteration &Instance,
2775                                                bool IfPredicateInstr,
2776                                                VPTransformState &State) {
2777   assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
2778 
2779   // llvm.experimental.noalias.scope.decl intrinsics must only be duplicated for
2780   // the first lane and part.
2781   if (isa<NoAliasScopeDeclInst>(Instr))
2782     if (!Instance.isFirstIteration())
2783       return;
2784 
2785   // Does this instruction return a value ?
2786   bool IsVoidRetTy = Instr->getType()->isVoidTy();
2787 
2788   Instruction *Cloned = Instr->clone();
2789   if (!IsVoidRetTy)
2790     Cloned->setName(Instr->getName() + ".cloned");
2791 
2792   // If the scalarized instruction contributes to the address computation of a
2793   // widen masked load/store which was in a basic block that needed predication
2794   // and is not predicated after vectorization, we can't propagate
2795   // poison-generating flags (nuw/nsw, exact, inbounds, etc.). The scalarized
2796   // instruction could feed a poison value to the base address of the widen
2797   // load/store.
2798   if (State.MayGeneratePoisonRecipes.contains(RepRecipe))
2799     Cloned->dropPoisonGeneratingFlags();
2800 
2801   if (Instr->getDebugLoc())
2802     setDebugLocFromInst(Instr);
2803 
2804   // Replace the operands of the cloned instructions with their scalar
2805   // equivalents in the new loop.
2806   for (auto &I : enumerate(RepRecipe->operands())) {
2807     auto InputInstance = Instance;
2808     VPValue *Operand = I.value();
2809     VPReplicateRecipe *OperandR = dyn_cast<VPReplicateRecipe>(Operand);
2810     if (OperandR && OperandR->isUniform())
2811       InputInstance.Lane = VPLane::getFirstLane();
2812     Cloned->setOperand(I.index(), State.get(Operand, InputInstance));
2813   }
2814   addNewMetadata(Cloned, Instr);
2815 
2816   // Place the cloned scalar in the new loop.
2817   State.Builder.Insert(Cloned);
2818 
2819   State.set(RepRecipe, Cloned, Instance);
2820 
2821   // If we just cloned a new assumption, add it the assumption cache.
2822   if (auto *II = dyn_cast<AssumeInst>(Cloned))
2823     AC->registerAssumption(II);
2824 
2825   // End if-block.
2826   if (IfPredicateInstr)
2827     PredicatedInstructions.push_back(Cloned);
2828 }
2829 
2830 Value *InnerLoopVectorizer::getOrCreateTripCount(BasicBlock *InsertBlock) {
2831   if (TripCount)
2832     return TripCount;
2833 
2834   assert(InsertBlock);
2835   IRBuilder<> Builder(InsertBlock->getTerminator());
2836   // Find the loop boundaries.
2837   ScalarEvolution *SE = PSE.getSE();
2838   const SCEV *BackedgeTakenCount = PSE.getBackedgeTakenCount();
2839   assert(!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
2840          "Invalid loop count");
2841 
2842   Type *IdxTy = Legal->getWidestInductionType();
2843   assert(IdxTy && "No type for induction");
2844 
2845   // The exit count might have the type of i64 while the phi is i32. This can
2846   // happen if we have an induction variable that is sign extended before the
2847   // compare. The only way that we get a backedge taken count is that the
2848   // induction variable was signed and as such will not overflow. In such a case
2849   // truncation is legal.
2850   if (SE->getTypeSizeInBits(BackedgeTakenCount->getType()) >
2851       IdxTy->getPrimitiveSizeInBits())
2852     BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount, IdxTy);
2853   BackedgeTakenCount = SE->getNoopOrZeroExtend(BackedgeTakenCount, IdxTy);
2854 
2855   // Get the total trip count from the count by adding 1.
2856   const SCEV *ExitCount = SE->getAddExpr(
2857       BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType()));
2858 
2859   const DataLayout &DL = InsertBlock->getModule()->getDataLayout();
2860 
2861   // Expand the trip count and place the new instructions in the preheader.
2862   // Notice that the pre-header does not change, only the loop body.
2863   SCEVExpander Exp(*SE, DL, "induction");
2864 
2865   // Count holds the overall loop count (N).
2866   TripCount = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
2867                                 InsertBlock->getTerminator());
2868 
2869   if (TripCount->getType()->isPointerTy())
2870     TripCount =
2871         CastInst::CreatePointerCast(TripCount, IdxTy, "exitcount.ptrcnt.to.int",
2872                                     InsertBlock->getTerminator());
2873 
2874   return TripCount;
2875 }
2876 
2877 Value *
2878 InnerLoopVectorizer::getOrCreateVectorTripCount(BasicBlock *InsertBlock) {
2879   if (VectorTripCount)
2880     return VectorTripCount;
2881 
2882   Value *TC = getOrCreateTripCount(InsertBlock);
2883   IRBuilder<> Builder(InsertBlock->getTerminator());
2884 
2885   Type *Ty = TC->getType();
2886   // This is where we can make the step a runtime constant.
2887   Value *Step = createStepForVF(Builder, Ty, VF, UF);
2888 
2889   // If the tail is to be folded by masking, round the number of iterations N
2890   // up to a multiple of Step instead of rounding down. This is done by first
2891   // adding Step-1 and then rounding down. Note that it's ok if this addition
2892   // overflows: the vector induction variable will eventually wrap to zero given
2893   // that it starts at zero and its Step is a power of two; the loop will then
2894   // exit, with the last early-exit vector comparison also producing all-true.
2895   // For scalable vectors the VF is not guaranteed to be a power of 2, but this
2896   // is accounted for in emitIterationCountCheck that adds an overflow check.
2897   if (Cost->foldTailByMasking()) {
2898     assert(isPowerOf2_32(VF.getKnownMinValue() * UF) &&
2899            "VF*UF must be a power of 2 when folding tail by masking");
2900     Value *NumLanes = getRuntimeVF(Builder, Ty, VF * UF);
2901     TC = Builder.CreateAdd(
2902         TC, Builder.CreateSub(NumLanes, ConstantInt::get(Ty, 1)), "n.rnd.up");
2903   }
2904 
2905   // Now we need to generate the expression for the part of the loop that the
2906   // vectorized body will execute. This is equal to N - (N % Step) if scalar
2907   // iterations are not required for correctness, or N - Step, otherwise. Step
2908   // is equal to the vectorization factor (number of SIMD elements) times the
2909   // unroll factor (number of SIMD instructions).
2910   Value *R = Builder.CreateURem(TC, Step, "n.mod.vf");
2911 
2912   // There are cases where we *must* run at least one iteration in the remainder
2913   // loop.  See the cost model for when this can happen.  If the step evenly
2914   // divides the trip count, we set the remainder to be equal to the step. If
2915   // the step does not evenly divide the trip count, no adjustment is necessary
2916   // since there will already be scalar iterations. Note that the minimum
2917   // iterations check ensures that N >= Step.
2918   if (Cost->requiresScalarEpilogue(VF)) {
2919     auto *IsZero = Builder.CreateICmpEQ(R, ConstantInt::get(R->getType(), 0));
2920     R = Builder.CreateSelect(IsZero, Step, R);
2921   }
2922 
2923   VectorTripCount = Builder.CreateSub(TC, R, "n.vec");
2924 
2925   return VectorTripCount;
2926 }
2927 
2928 Value *InnerLoopVectorizer::createBitOrPointerCast(Value *V, VectorType *DstVTy,
2929                                                    const DataLayout &DL) {
2930   // Verify that V is a vector type with same number of elements as DstVTy.
2931   auto *DstFVTy = cast<FixedVectorType>(DstVTy);
2932   unsigned VF = DstFVTy->getNumElements();
2933   auto *SrcVecTy = cast<FixedVectorType>(V->getType());
2934   assert((VF == SrcVecTy->getNumElements()) && "Vector dimensions do not match");
2935   Type *SrcElemTy = SrcVecTy->getElementType();
2936   Type *DstElemTy = DstFVTy->getElementType();
2937   assert((DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy)) &&
2938          "Vector elements must have same size");
2939 
2940   // Do a direct cast if element types are castable.
2941   if (CastInst::isBitOrNoopPointerCastable(SrcElemTy, DstElemTy, DL)) {
2942     return Builder.CreateBitOrPointerCast(V, DstFVTy);
2943   }
2944   // V cannot be directly casted to desired vector type.
2945   // May happen when V is a floating point vector but DstVTy is a vector of
2946   // pointers or vice-versa. Handle this using a two-step bitcast using an
2947   // intermediate Integer type for the bitcast i.e. Ptr <-> Int <-> Float.
2948   assert((DstElemTy->isPointerTy() != SrcElemTy->isPointerTy()) &&
2949          "Only one type should be a pointer type");
2950   assert((DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy()) &&
2951          "Only one type should be a floating point type");
2952   Type *IntTy =
2953       IntegerType::getIntNTy(V->getContext(), DL.getTypeSizeInBits(SrcElemTy));
2954   auto *VecIntTy = FixedVectorType::get(IntTy, VF);
2955   Value *CastVal = Builder.CreateBitOrPointerCast(V, VecIntTy);
2956   return Builder.CreateBitOrPointerCast(CastVal, DstFVTy);
2957 }
2958 
2959 void InnerLoopVectorizer::emitIterationCountCheck(BasicBlock *Bypass) {
2960   Value *Count = getOrCreateTripCount(LoopVectorPreHeader);
2961   // Reuse existing vector loop preheader for TC checks.
2962   // Note that new preheader block is generated for vector loop.
2963   BasicBlock *const TCCheckBlock = LoopVectorPreHeader;
2964   IRBuilder<> Builder(TCCheckBlock->getTerminator());
2965 
2966   // Generate code to check if the loop's trip count is less than VF * UF, or
2967   // equal to it in case a scalar epilogue is required; this implies that the
2968   // vector trip count is zero. This check also covers the case where adding one
2969   // to the backedge-taken count overflowed leading to an incorrect trip count
2970   // of zero. In this case we will also jump to the scalar loop.
2971   auto P = Cost->requiresScalarEpilogue(VF) ? ICmpInst::ICMP_ULE
2972                                             : ICmpInst::ICMP_ULT;
2973 
2974   // If tail is to be folded, vector loop takes care of all iterations.
2975   Type *CountTy = Count->getType();
2976   Value *CheckMinIters = Builder.getFalse();
2977   Value *Step = createStepForVF(Builder, CountTy, VF, UF);
2978   if (!Cost->foldTailByMasking())
2979     CheckMinIters = Builder.CreateICmp(P, Count, Step, "min.iters.check");
2980   else if (VF.isScalable()) {
2981     // vscale is not necessarily a power-of-2, which means we cannot guarantee
2982     // an overflow to zero when updating induction variables and so an
2983     // additional overflow check is required before entering the vector loop.
2984 
2985     // Get the maximum unsigned value for the type.
2986     Value *MaxUIntTripCount =
2987         ConstantInt::get(CountTy, cast<IntegerType>(CountTy)->getMask());
2988     Value *LHS = Builder.CreateSub(MaxUIntTripCount, Count);
2989 
2990     // Don't execute the vector loop if (UMax - n) < (VF * UF).
2991     CheckMinIters = Builder.CreateICmp(ICmpInst::ICMP_ULT, LHS, Step);
2992   }
2993   // Create new preheader for vector loop.
2994   LoopVectorPreHeader =
2995       SplitBlock(TCCheckBlock, TCCheckBlock->getTerminator(), DT, LI, nullptr,
2996                  "vector.ph");
2997 
2998   assert(DT->properlyDominates(DT->getNode(TCCheckBlock),
2999                                DT->getNode(Bypass)->getIDom()) &&
3000          "TC check is expected to dominate Bypass");
3001 
3002   // Update dominator for Bypass & LoopExit (if needed).
3003   DT->changeImmediateDominator(Bypass, TCCheckBlock);
3004   if (!Cost->requiresScalarEpilogue(VF))
3005     // If there is an epilogue which must run, there's no edge from the
3006     // middle block to exit blocks  and thus no need to update the immediate
3007     // dominator of the exit blocks.
3008     DT->changeImmediateDominator(LoopExitBlock, TCCheckBlock);
3009 
3010   ReplaceInstWithInst(
3011       TCCheckBlock->getTerminator(),
3012       BranchInst::Create(Bypass, LoopVectorPreHeader, CheckMinIters));
3013   LoopBypassBlocks.push_back(TCCheckBlock);
3014 }
3015 
3016 BasicBlock *InnerLoopVectorizer::emitSCEVChecks(BasicBlock *Bypass) {
3017 
3018   BasicBlock *const SCEVCheckBlock =
3019       RTChecks.emitSCEVChecks(Bypass, LoopVectorPreHeader, LoopExitBlock);
3020   if (!SCEVCheckBlock)
3021     return nullptr;
3022 
3023   assert(!(SCEVCheckBlock->getParent()->hasOptSize() ||
3024            (OptForSizeBasedOnProfile &&
3025             Cost->Hints->getForce() != LoopVectorizeHints::FK_Enabled)) &&
3026          "Cannot SCEV check stride or overflow when optimizing for size");
3027 
3028 
3029   // Update dominator only if this is first RT check.
3030   if (LoopBypassBlocks.empty()) {
3031     DT->changeImmediateDominator(Bypass, SCEVCheckBlock);
3032     if (!Cost->requiresScalarEpilogue(VF))
3033       // If there is an epilogue which must run, there's no edge from the
3034       // middle block to exit blocks  and thus no need to update the immediate
3035       // dominator of the exit blocks.
3036       DT->changeImmediateDominator(LoopExitBlock, SCEVCheckBlock);
3037   }
3038 
3039   LoopBypassBlocks.push_back(SCEVCheckBlock);
3040   AddedSafetyChecks = true;
3041   return SCEVCheckBlock;
3042 }
3043 
3044 BasicBlock *InnerLoopVectorizer::emitMemRuntimeChecks(BasicBlock *Bypass) {
3045   // VPlan-native path does not do any analysis for runtime checks currently.
3046   if (EnableVPlanNativePath)
3047     return nullptr;
3048 
3049   BasicBlock *const MemCheckBlock =
3050       RTChecks.emitMemRuntimeChecks(Bypass, LoopVectorPreHeader);
3051 
3052   // Check if we generated code that checks in runtime if arrays overlap. We put
3053   // the checks into a separate block to make the more common case of few
3054   // elements faster.
3055   if (!MemCheckBlock)
3056     return nullptr;
3057 
3058   if (MemCheckBlock->getParent()->hasOptSize() || OptForSizeBasedOnProfile) {
3059     assert(Cost->Hints->getForce() == LoopVectorizeHints::FK_Enabled &&
3060            "Cannot emit memory checks when optimizing for size, unless forced "
3061            "to vectorize.");
3062     ORE->emit([&]() {
3063       return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationCodeSize",
3064                                         OrigLoop->getStartLoc(),
3065                                         OrigLoop->getHeader())
3066              << "Code-size may be reduced by not forcing "
3067                 "vectorization, or by source-code modifications "
3068                 "eliminating the need for runtime checks "
3069                 "(e.g., adding 'restrict').";
3070     });
3071   }
3072 
3073   LoopBypassBlocks.push_back(MemCheckBlock);
3074 
3075   AddedSafetyChecks = true;
3076 
3077   // We currently don't use LoopVersioning for the actual loop cloning but we
3078   // still use it to add the noalias metadata.
3079   LVer = std::make_unique<LoopVersioning>(
3080       *Legal->getLAI(),
3081       Legal->getLAI()->getRuntimePointerChecking()->getChecks(), OrigLoop, LI,
3082       DT, PSE.getSE());
3083   LVer->prepareNoAliasMetadata();
3084   return MemCheckBlock;
3085 }
3086 
3087 void InnerLoopVectorizer::createVectorLoopSkeleton(StringRef Prefix) {
3088   LoopScalarBody = OrigLoop->getHeader();
3089   LoopVectorPreHeader = OrigLoop->getLoopPreheader();
3090   assert(LoopVectorPreHeader && "Invalid loop structure");
3091   LoopExitBlock = OrigLoop->getUniqueExitBlock(); // may be nullptr
3092   assert((LoopExitBlock || Cost->requiresScalarEpilogue(VF)) &&
3093          "multiple exit loop without required epilogue?");
3094 
3095   LoopMiddleBlock =
3096       SplitBlock(LoopVectorPreHeader, LoopVectorPreHeader->getTerminator(), DT,
3097                  LI, nullptr, Twine(Prefix) + "middle.block");
3098   LoopScalarPreHeader =
3099       SplitBlock(LoopMiddleBlock, LoopMiddleBlock->getTerminator(), DT, LI,
3100                  nullptr, Twine(Prefix) + "scalar.ph");
3101 
3102   auto *ScalarLatchTerm = OrigLoop->getLoopLatch()->getTerminator();
3103 
3104   // Set up the middle block terminator.  Two cases:
3105   // 1) If we know that we must execute the scalar epilogue, emit an
3106   //    unconditional branch.
3107   // 2) Otherwise, we must have a single unique exit block (due to how we
3108   //    implement the multiple exit case).  In this case, set up a conditonal
3109   //    branch from the middle block to the loop scalar preheader, and the
3110   //    exit block.  completeLoopSkeleton will update the condition to use an
3111   //    iteration check, if required to decide whether to execute the remainder.
3112   BranchInst *BrInst = Cost->requiresScalarEpilogue(VF) ?
3113     BranchInst::Create(LoopScalarPreHeader) :
3114     BranchInst::Create(LoopExitBlock, LoopScalarPreHeader,
3115                        Builder.getTrue());
3116   BrInst->setDebugLoc(ScalarLatchTerm->getDebugLoc());
3117   ReplaceInstWithInst(LoopMiddleBlock->getTerminator(), BrInst);
3118 
3119   // Update dominator for loop exit. During skeleton creation, only the vector
3120   // pre-header and the middle block are created. The vector loop is entirely
3121   // created during VPlan exection.
3122   if (!Cost->requiresScalarEpilogue(VF))
3123     // If there is an epilogue which must run, there's no edge from the
3124     // middle block to exit blocks  and thus no need to update the immediate
3125     // dominator of the exit blocks.
3126     DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
3127 }
3128 
3129 void InnerLoopVectorizer::createInductionResumeValues(
3130     std::pair<BasicBlock *, Value *> AdditionalBypass) {
3131   assert(((AdditionalBypass.first && AdditionalBypass.second) ||
3132           (!AdditionalBypass.first && !AdditionalBypass.second)) &&
3133          "Inconsistent information about additional bypass.");
3134 
3135   Value *VectorTripCount = getOrCreateVectorTripCount(LoopVectorPreHeader);
3136   assert(VectorTripCount && "Expected valid arguments");
3137   // We are going to resume the execution of the scalar loop.
3138   // Go over all of the induction variables that we found and fix the
3139   // PHIs that are left in the scalar version of the loop.
3140   // The starting values of PHI nodes depend on the counter of the last
3141   // iteration in the vectorized loop.
3142   // If we come from a bypass edge then we need to start from the original
3143   // start value.
3144   Instruction *OldInduction = Legal->getPrimaryInduction();
3145   for (auto &InductionEntry : Legal->getInductionVars()) {
3146     PHINode *OrigPhi = InductionEntry.first;
3147     InductionDescriptor II = InductionEntry.second;
3148 
3149     // Create phi nodes to merge from the  backedge-taken check block.
3150     PHINode *BCResumeVal =
3151         PHINode::Create(OrigPhi->getType(), 3, "bc.resume.val",
3152                         LoopScalarPreHeader->getTerminator());
3153     // Copy original phi DL over to the new one.
3154     BCResumeVal->setDebugLoc(OrigPhi->getDebugLoc());
3155     Value *&EndValue = IVEndValues[OrigPhi];
3156     Value *EndValueFromAdditionalBypass = AdditionalBypass.second;
3157     if (OrigPhi == OldInduction) {
3158       // We know what the end value is.
3159       EndValue = VectorTripCount;
3160     } else {
3161       IRBuilder<> B(LoopVectorPreHeader->getTerminator());
3162 
3163       // Fast-math-flags propagate from the original induction instruction.
3164       if (II.getInductionBinOp() && isa<FPMathOperator>(II.getInductionBinOp()))
3165         B.setFastMathFlags(II.getInductionBinOp()->getFastMathFlags());
3166 
3167       Type *StepType = II.getStep()->getType();
3168       Instruction::CastOps CastOp =
3169           CastInst::getCastOpcode(VectorTripCount, true, StepType, true);
3170       Value *VTC = B.CreateCast(CastOp, VectorTripCount, StepType, "cast.vtc");
3171       Value *Step =
3172           CreateStepValue(II.getStep(), *PSE.getSE(), &*B.GetInsertPoint());
3173       EndValue = emitTransformedIndex(B, VTC, II.getStartValue(), Step, II);
3174       EndValue->setName("ind.end");
3175 
3176       // Compute the end value for the additional bypass (if applicable).
3177       if (AdditionalBypass.first) {
3178         B.SetInsertPoint(&(*AdditionalBypass.first->getFirstInsertionPt()));
3179         CastOp = CastInst::getCastOpcode(AdditionalBypass.second, true,
3180                                          StepType, true);
3181         Value *Step =
3182             CreateStepValue(II.getStep(), *PSE.getSE(), &*B.GetInsertPoint());
3183         VTC =
3184             B.CreateCast(CastOp, AdditionalBypass.second, StepType, "cast.vtc");
3185         EndValueFromAdditionalBypass =
3186             emitTransformedIndex(B, VTC, II.getStartValue(), Step, II);
3187         EndValueFromAdditionalBypass->setName("ind.end");
3188       }
3189     }
3190     // The new PHI merges the original incoming value, in case of a bypass,
3191     // or the value at the end of the vectorized loop.
3192     BCResumeVal->addIncoming(EndValue, LoopMiddleBlock);
3193 
3194     // Fix the scalar body counter (PHI node).
3195     // The old induction's phi node in the scalar body needs the truncated
3196     // value.
3197     for (BasicBlock *BB : LoopBypassBlocks)
3198       BCResumeVal->addIncoming(II.getStartValue(), BB);
3199 
3200     if (AdditionalBypass.first)
3201       BCResumeVal->setIncomingValueForBlock(AdditionalBypass.first,
3202                                             EndValueFromAdditionalBypass);
3203 
3204     OrigPhi->setIncomingValueForBlock(LoopScalarPreHeader, BCResumeVal);
3205   }
3206 }
3207 
3208 BasicBlock *InnerLoopVectorizer::completeLoopSkeleton(MDNode *OrigLoopID) {
3209   // The trip counts should be cached by now.
3210   Value *Count = getOrCreateTripCount(LoopVectorPreHeader);
3211   Value *VectorTripCount = getOrCreateVectorTripCount(LoopVectorPreHeader);
3212 
3213   auto *ScalarLatchTerm = OrigLoop->getLoopLatch()->getTerminator();
3214 
3215   // Add a check in the middle block to see if we have completed
3216   // all of the iterations in the first vector loop.  Three cases:
3217   // 1) If we require a scalar epilogue, there is no conditional branch as
3218   //    we unconditionally branch to the scalar preheader.  Do nothing.
3219   // 2) If (N - N%VF) == N, then we *don't* need to run the remainder.
3220   //    Thus if tail is to be folded, we know we don't need to run the
3221   //    remainder and we can use the previous value for the condition (true).
3222   // 3) Otherwise, construct a runtime check.
3223   if (!Cost->requiresScalarEpilogue(VF) && !Cost->foldTailByMasking()) {
3224     Instruction *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
3225                                         Count, VectorTripCount, "cmp.n",
3226                                         LoopMiddleBlock->getTerminator());
3227 
3228     // Here we use the same DebugLoc as the scalar loop latch terminator instead
3229     // of the corresponding compare because they may have ended up with
3230     // different line numbers and we want to avoid awkward line stepping while
3231     // debugging. Eg. if the compare has got a line number inside the loop.
3232     CmpN->setDebugLoc(ScalarLatchTerm->getDebugLoc());
3233     cast<BranchInst>(LoopMiddleBlock->getTerminator())->setCondition(CmpN);
3234   }
3235 
3236 #ifdef EXPENSIVE_CHECKS
3237   assert(DT->verify(DominatorTree::VerificationLevel::Fast));
3238 #endif
3239 
3240   return LoopVectorPreHeader;
3241 }
3242 
3243 std::pair<BasicBlock *, Value *>
3244 InnerLoopVectorizer::createVectorizedLoopSkeleton() {
3245   /*
3246    In this function we generate a new loop. The new loop will contain
3247    the vectorized instructions while the old loop will continue to run the
3248    scalar remainder.
3249 
3250        [ ] <-- loop iteration number check.
3251     /   |
3252    /    v
3253   |    [ ] <-- vector loop bypass (may consist of multiple blocks).
3254   |  /  |
3255   | /   v
3256   ||   [ ]     <-- vector pre header.
3257   |/    |
3258   |     v
3259   |    [  ] \
3260   |    [  ]_|   <-- vector loop (created during VPlan execution).
3261   |     |
3262   |     v
3263   \   -[ ]   <--- middle-block.
3264    \/   |
3265    /\   v
3266    | ->[ ]     <--- new preheader.
3267    |    |
3268  (opt)  v      <-- edge from middle to exit iff epilogue is not required.
3269    |   [ ] \
3270    |   [ ]_|   <-- old scalar loop to handle remainder (scalar epilogue).
3271     \   |
3272      \  v
3273       >[ ]     <-- exit block(s).
3274    ...
3275    */
3276 
3277   // Get the metadata of the original loop before it gets modified.
3278   MDNode *OrigLoopID = OrigLoop->getLoopID();
3279 
3280   // Workaround!  Compute the trip count of the original loop and cache it
3281   // before we start modifying the CFG.  This code has a systemic problem
3282   // wherein it tries to run analysis over partially constructed IR; this is
3283   // wrong, and not simply for SCEV.  The trip count of the original loop
3284   // simply happens to be prone to hitting this in practice.  In theory, we
3285   // can hit the same issue for any SCEV, or ValueTracking query done during
3286   // mutation.  See PR49900.
3287   getOrCreateTripCount(OrigLoop->getLoopPreheader());
3288 
3289   // Create an empty vector loop, and prepare basic blocks for the runtime
3290   // checks.
3291   createVectorLoopSkeleton("");
3292 
3293   // Now, compare the new count to zero. If it is zero skip the vector loop and
3294   // jump to the scalar loop. This check also covers the case where the
3295   // backedge-taken count is uint##_max: adding one to it will overflow leading
3296   // to an incorrect trip count of zero. In this (rare) case we will also jump
3297   // to the scalar loop.
3298   emitIterationCountCheck(LoopScalarPreHeader);
3299 
3300   // Generate the code to check any assumptions that we've made for SCEV
3301   // expressions.
3302   emitSCEVChecks(LoopScalarPreHeader);
3303 
3304   // Generate the code that checks in runtime if arrays overlap. We put the
3305   // checks into a separate block to make the more common case of few elements
3306   // faster.
3307   emitMemRuntimeChecks(LoopScalarPreHeader);
3308 
3309   // Emit phis for the new starting index of the scalar loop.
3310   createInductionResumeValues();
3311 
3312   return {completeLoopSkeleton(OrigLoopID), nullptr};
3313 }
3314 
3315 // Fix up external users of the induction variable. At this point, we are
3316 // in LCSSA form, with all external PHIs that use the IV having one input value,
3317 // coming from the remainder loop. We need those PHIs to also have a correct
3318 // value for the IV when arriving directly from the middle block.
3319 void InnerLoopVectorizer::fixupIVUsers(PHINode *OrigPhi,
3320                                        const InductionDescriptor &II,
3321                                        Value *VectorTripCount, Value *EndValue,
3322                                        BasicBlock *MiddleBlock,
3323                                        BasicBlock *VectorHeader) {
3324   // There are two kinds of external IV usages - those that use the value
3325   // computed in the last iteration (the PHI) and those that use the penultimate
3326   // value (the value that feeds into the phi from the loop latch).
3327   // We allow both, but they, obviously, have different values.
3328 
3329   assert(OrigLoop->getUniqueExitBlock() && "Expected a single exit block");
3330 
3331   DenseMap<Value *, Value *> MissingVals;
3332 
3333   // An external user of the last iteration's value should see the value that
3334   // the remainder loop uses to initialize its own IV.
3335   Value *PostInc = OrigPhi->getIncomingValueForBlock(OrigLoop->getLoopLatch());
3336   for (User *U : PostInc->users()) {
3337     Instruction *UI = cast<Instruction>(U);
3338     if (!OrigLoop->contains(UI)) {
3339       assert(isa<PHINode>(UI) && "Expected LCSSA form");
3340       MissingVals[UI] = EndValue;
3341     }
3342   }
3343 
3344   // An external user of the penultimate value need to see EndValue - Step.
3345   // The simplest way to get this is to recompute it from the constituent SCEVs,
3346   // that is Start + (Step * (CRD - 1)).
3347   for (User *U : OrigPhi->users()) {
3348     auto *UI = cast<Instruction>(U);
3349     if (!OrigLoop->contains(UI)) {
3350       assert(isa<PHINode>(UI) && "Expected LCSSA form");
3351 
3352       IRBuilder<> B(MiddleBlock->getTerminator());
3353 
3354       // Fast-math-flags propagate from the original induction instruction.
3355       if (II.getInductionBinOp() && isa<FPMathOperator>(II.getInductionBinOp()))
3356         B.setFastMathFlags(II.getInductionBinOp()->getFastMathFlags());
3357 
3358       Value *CountMinusOne = B.CreateSub(
3359           VectorTripCount, ConstantInt::get(VectorTripCount->getType(), 1));
3360       Value *CMO =
3361           !II.getStep()->getType()->isIntegerTy()
3362               ? B.CreateCast(Instruction::SIToFP, CountMinusOne,
3363                              II.getStep()->getType())
3364               : B.CreateSExtOrTrunc(CountMinusOne, II.getStep()->getType());
3365       CMO->setName("cast.cmo");
3366 
3367       Value *Step = CreateStepValue(II.getStep(), *PSE.getSE(),
3368                                     VectorHeader->getTerminator());
3369       Value *Escape =
3370           emitTransformedIndex(B, CMO, II.getStartValue(), Step, II);
3371       Escape->setName("ind.escape");
3372       MissingVals[UI] = Escape;
3373     }
3374   }
3375 
3376   for (auto &I : MissingVals) {
3377     PHINode *PHI = cast<PHINode>(I.first);
3378     // One corner case we have to handle is two IVs "chasing" each-other,
3379     // that is %IV2 = phi [...], [ %IV1, %latch ]
3380     // In this case, if IV1 has an external use, we need to avoid adding both
3381     // "last value of IV1" and "penultimate value of IV2". So, verify that we
3382     // don't already have an incoming value for the middle block.
3383     if (PHI->getBasicBlockIndex(MiddleBlock) == -1)
3384       PHI->addIncoming(I.second, MiddleBlock);
3385   }
3386 }
3387 
3388 namespace {
3389 
3390 struct CSEDenseMapInfo {
3391   static bool canHandle(const Instruction *I) {
3392     return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
3393            isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
3394   }
3395 
3396   static inline Instruction *getEmptyKey() {
3397     return DenseMapInfo<Instruction *>::getEmptyKey();
3398   }
3399 
3400   static inline Instruction *getTombstoneKey() {
3401     return DenseMapInfo<Instruction *>::getTombstoneKey();
3402   }
3403 
3404   static unsigned getHashValue(const Instruction *I) {
3405     assert(canHandle(I) && "Unknown instruction!");
3406     return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
3407                                                            I->value_op_end()));
3408   }
3409 
3410   static bool isEqual(const Instruction *LHS, const Instruction *RHS) {
3411     if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
3412         LHS == getTombstoneKey() || RHS == getTombstoneKey())
3413       return LHS == RHS;
3414     return LHS->isIdenticalTo(RHS);
3415   }
3416 };
3417 
3418 } // end anonymous namespace
3419 
3420 ///Perform cse of induction variable instructions.
3421 static void cse(BasicBlock *BB) {
3422   // Perform simple cse.
3423   SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
3424   for (Instruction &In : llvm::make_early_inc_range(*BB)) {
3425     if (!CSEDenseMapInfo::canHandle(&In))
3426       continue;
3427 
3428     // Check if we can replace this instruction with any of the
3429     // visited instructions.
3430     if (Instruction *V = CSEMap.lookup(&In)) {
3431       In.replaceAllUsesWith(V);
3432       In.eraseFromParent();
3433       continue;
3434     }
3435 
3436     CSEMap[&In] = &In;
3437   }
3438 }
3439 
3440 InstructionCost
3441 LoopVectorizationCostModel::getVectorCallCost(CallInst *CI, ElementCount VF,
3442                                               bool &NeedToScalarize) const {
3443   Function *F = CI->getCalledFunction();
3444   Type *ScalarRetTy = CI->getType();
3445   SmallVector<Type *, 4> Tys, ScalarTys;
3446   for (auto &ArgOp : CI->args())
3447     ScalarTys.push_back(ArgOp->getType());
3448 
3449   // Estimate cost of scalarized vector call. The source operands are assumed
3450   // to be vectors, so we need to extract individual elements from there,
3451   // execute VF scalar calls, and then gather the result into the vector return
3452   // value.
3453   InstructionCost ScalarCallCost =
3454       TTI.getCallInstrCost(F, ScalarRetTy, ScalarTys, TTI::TCK_RecipThroughput);
3455   if (VF.isScalar())
3456     return ScalarCallCost;
3457 
3458   // Compute corresponding vector type for return value and arguments.
3459   Type *RetTy = ToVectorTy(ScalarRetTy, VF);
3460   for (Type *ScalarTy : ScalarTys)
3461     Tys.push_back(ToVectorTy(ScalarTy, VF));
3462 
3463   // Compute costs of unpacking argument values for the scalar calls and
3464   // packing the return values to a vector.
3465   InstructionCost ScalarizationCost = getScalarizationOverhead(CI, VF);
3466 
3467   InstructionCost Cost =
3468       ScalarCallCost * VF.getKnownMinValue() + ScalarizationCost;
3469 
3470   // If we can't emit a vector call for this function, then the currently found
3471   // cost is the cost we need to return.
3472   NeedToScalarize = true;
3473   VFShape Shape = VFShape::get(*CI, VF, false /*HasGlobalPred*/);
3474   Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
3475 
3476   if (!TLI || CI->isNoBuiltin() || !VecFunc)
3477     return Cost;
3478 
3479   // If the corresponding vector cost is cheaper, return its cost.
3480   InstructionCost VectorCallCost =
3481       TTI.getCallInstrCost(nullptr, RetTy, Tys, TTI::TCK_RecipThroughput);
3482   if (VectorCallCost < Cost) {
3483     NeedToScalarize = false;
3484     Cost = VectorCallCost;
3485   }
3486   return Cost;
3487 }
3488 
3489 static Type *MaybeVectorizeType(Type *Elt, ElementCount VF) {
3490   if (VF.isScalar() || (!Elt->isIntOrPtrTy() && !Elt->isFloatingPointTy()))
3491     return Elt;
3492   return VectorType::get(Elt, VF);
3493 }
3494 
3495 InstructionCost
3496 LoopVectorizationCostModel::getVectorIntrinsicCost(CallInst *CI,
3497                                                    ElementCount VF) const {
3498   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
3499   assert(ID && "Expected intrinsic call!");
3500   Type *RetTy = MaybeVectorizeType(CI->getType(), VF);
3501   FastMathFlags FMF;
3502   if (auto *FPMO = dyn_cast<FPMathOperator>(CI))
3503     FMF = FPMO->getFastMathFlags();
3504 
3505   SmallVector<const Value *> Arguments(CI->args());
3506   FunctionType *FTy = CI->getCalledFunction()->getFunctionType();
3507   SmallVector<Type *> ParamTys;
3508   std::transform(FTy->param_begin(), FTy->param_end(),
3509                  std::back_inserter(ParamTys),
3510                  [&](Type *Ty) { return MaybeVectorizeType(Ty, VF); });
3511 
3512   IntrinsicCostAttributes CostAttrs(ID, RetTy, Arguments, ParamTys, FMF,
3513                                     dyn_cast<IntrinsicInst>(CI));
3514   return TTI.getIntrinsicInstrCost(CostAttrs,
3515                                    TargetTransformInfo::TCK_RecipThroughput);
3516 }
3517 
3518 static Type *smallestIntegerVectorType(Type *T1, Type *T2) {
3519   auto *I1 = cast<IntegerType>(cast<VectorType>(T1)->getElementType());
3520   auto *I2 = cast<IntegerType>(cast<VectorType>(T2)->getElementType());
3521   return I1->getBitWidth() < I2->getBitWidth() ? T1 : T2;
3522 }
3523 
3524 static Type *largestIntegerVectorType(Type *T1, Type *T2) {
3525   auto *I1 = cast<IntegerType>(cast<VectorType>(T1)->getElementType());
3526   auto *I2 = cast<IntegerType>(cast<VectorType>(T2)->getElementType());
3527   return I1->getBitWidth() > I2->getBitWidth() ? T1 : T2;
3528 }
3529 
3530 void InnerLoopVectorizer::truncateToMinimalBitwidths(VPTransformState &State) {
3531   // For every instruction `I` in MinBWs, truncate the operands, create a
3532   // truncated version of `I` and reextend its result. InstCombine runs
3533   // later and will remove any ext/trunc pairs.
3534   SmallPtrSet<Value *, 4> Erased;
3535   for (const auto &KV : Cost->getMinimalBitwidths()) {
3536     // If the value wasn't vectorized, we must maintain the original scalar
3537     // type. The absence of the value from State indicates that it
3538     // wasn't vectorized.
3539     // FIXME: Should not rely on getVPValue at this point.
3540     VPValue *Def = State.Plan->getVPValue(KV.first, true);
3541     if (!State.hasAnyVectorValue(Def))
3542       continue;
3543     for (unsigned Part = 0; Part < UF; ++Part) {
3544       Value *I = State.get(Def, Part);
3545       if (Erased.count(I) || I->use_empty() || !isa<Instruction>(I))
3546         continue;
3547       Type *OriginalTy = I->getType();
3548       Type *ScalarTruncatedTy =
3549           IntegerType::get(OriginalTy->getContext(), KV.second);
3550       auto *TruncatedTy = VectorType::get(
3551           ScalarTruncatedTy, cast<VectorType>(OriginalTy)->getElementCount());
3552       if (TruncatedTy == OriginalTy)
3553         continue;
3554 
3555       IRBuilder<> B(cast<Instruction>(I));
3556       auto ShrinkOperand = [&](Value *V) -> Value * {
3557         if (auto *ZI = dyn_cast<ZExtInst>(V))
3558           if (ZI->getSrcTy() == TruncatedTy)
3559             return ZI->getOperand(0);
3560         return B.CreateZExtOrTrunc(V, TruncatedTy);
3561       };
3562 
3563       // The actual instruction modification depends on the instruction type,
3564       // unfortunately.
3565       Value *NewI = nullptr;
3566       if (auto *BO = dyn_cast<BinaryOperator>(I)) {
3567         NewI = B.CreateBinOp(BO->getOpcode(), ShrinkOperand(BO->getOperand(0)),
3568                              ShrinkOperand(BO->getOperand(1)));
3569 
3570         // Any wrapping introduced by shrinking this operation shouldn't be
3571         // considered undefined behavior. So, we can't unconditionally copy
3572         // arithmetic wrapping flags to NewI.
3573         cast<BinaryOperator>(NewI)->copyIRFlags(I, /*IncludeWrapFlags=*/false);
3574       } else if (auto *CI = dyn_cast<ICmpInst>(I)) {
3575         NewI =
3576             B.CreateICmp(CI->getPredicate(), ShrinkOperand(CI->getOperand(0)),
3577                          ShrinkOperand(CI->getOperand(1)));
3578       } else if (auto *SI = dyn_cast<SelectInst>(I)) {
3579         NewI = B.CreateSelect(SI->getCondition(),
3580                               ShrinkOperand(SI->getTrueValue()),
3581                               ShrinkOperand(SI->getFalseValue()));
3582       } else if (auto *CI = dyn_cast<CastInst>(I)) {
3583         switch (CI->getOpcode()) {
3584         default:
3585           llvm_unreachable("Unhandled cast!");
3586         case Instruction::Trunc:
3587           NewI = ShrinkOperand(CI->getOperand(0));
3588           break;
3589         case Instruction::SExt:
3590           NewI = B.CreateSExtOrTrunc(
3591               CI->getOperand(0),
3592               smallestIntegerVectorType(OriginalTy, TruncatedTy));
3593           break;
3594         case Instruction::ZExt:
3595           NewI = B.CreateZExtOrTrunc(
3596               CI->getOperand(0),
3597               smallestIntegerVectorType(OriginalTy, TruncatedTy));
3598           break;
3599         }
3600       } else if (auto *SI = dyn_cast<ShuffleVectorInst>(I)) {
3601         auto Elements0 =
3602             cast<VectorType>(SI->getOperand(0)->getType())->getElementCount();
3603         auto *O0 = B.CreateZExtOrTrunc(
3604             SI->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements0));
3605         auto Elements1 =
3606             cast<VectorType>(SI->getOperand(1)->getType())->getElementCount();
3607         auto *O1 = B.CreateZExtOrTrunc(
3608             SI->getOperand(1), VectorType::get(ScalarTruncatedTy, Elements1));
3609 
3610         NewI = B.CreateShuffleVector(O0, O1, SI->getShuffleMask());
3611       } else if (isa<LoadInst>(I) || isa<PHINode>(I)) {
3612         // Don't do anything with the operands, just extend the result.
3613         continue;
3614       } else if (auto *IE = dyn_cast<InsertElementInst>(I)) {
3615         auto Elements =
3616             cast<VectorType>(IE->getOperand(0)->getType())->getElementCount();
3617         auto *O0 = B.CreateZExtOrTrunc(
3618             IE->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements));
3619         auto *O1 = B.CreateZExtOrTrunc(IE->getOperand(1), ScalarTruncatedTy);
3620         NewI = B.CreateInsertElement(O0, O1, IE->getOperand(2));
3621       } else if (auto *EE = dyn_cast<ExtractElementInst>(I)) {
3622         auto Elements =
3623             cast<VectorType>(EE->getOperand(0)->getType())->getElementCount();
3624         auto *O0 = B.CreateZExtOrTrunc(
3625             EE->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements));
3626         NewI = B.CreateExtractElement(O0, EE->getOperand(2));
3627       } else {
3628         // If we don't know what to do, be conservative and don't do anything.
3629         continue;
3630       }
3631 
3632       // Lastly, extend the result.
3633       NewI->takeName(cast<Instruction>(I));
3634       Value *Res = B.CreateZExtOrTrunc(NewI, OriginalTy);
3635       I->replaceAllUsesWith(Res);
3636       cast<Instruction>(I)->eraseFromParent();
3637       Erased.insert(I);
3638       State.reset(Def, Res, Part);
3639     }
3640   }
3641 
3642   // We'll have created a bunch of ZExts that are now parentless. Clean up.
3643   for (const auto &KV : Cost->getMinimalBitwidths()) {
3644     // If the value wasn't vectorized, we must maintain the original scalar
3645     // type. The absence of the value from State indicates that it
3646     // wasn't vectorized.
3647     // FIXME: Should not rely on getVPValue at this point.
3648     VPValue *Def = State.Plan->getVPValue(KV.first, true);
3649     if (!State.hasAnyVectorValue(Def))
3650       continue;
3651     for (unsigned Part = 0; Part < UF; ++Part) {
3652       Value *I = State.get(Def, Part);
3653       ZExtInst *Inst = dyn_cast<ZExtInst>(I);
3654       if (Inst && Inst->use_empty()) {
3655         Value *NewI = Inst->getOperand(0);
3656         Inst->eraseFromParent();
3657         State.reset(Def, NewI, Part);
3658       }
3659     }
3660   }
3661 }
3662 
3663 void InnerLoopVectorizer::fixVectorizedLoop(VPTransformState &State,
3664                                             VPlan &Plan) {
3665   // Insert truncates and extends for any truncated instructions as hints to
3666   // InstCombine.
3667   if (VF.isVector())
3668     truncateToMinimalBitwidths(State);
3669 
3670   // Fix widened non-induction PHIs by setting up the PHI operands.
3671   if (OrigPHIsToFix.size()) {
3672     assert(EnableVPlanNativePath &&
3673            "Unexpected non-induction PHIs for fixup in non VPlan-native path");
3674     fixNonInductionPHIs(State);
3675   }
3676 
3677   // At this point every instruction in the original loop is widened to a
3678   // vector form. Now we need to fix the recurrences in the loop. These PHI
3679   // nodes are currently empty because we did not want to introduce cycles.
3680   // This is the second stage of vectorizing recurrences.
3681   fixCrossIterationPHIs(State);
3682 
3683   // Forget the original basic block.
3684   PSE.getSE()->forgetLoop(OrigLoop);
3685 
3686   VPBasicBlock *LatchVPBB = Plan.getVectorLoopRegion()->getExitBasicBlock();
3687   Loop *VectorLoop = LI->getLoopFor(State.CFG.VPBB2IRBB[LatchVPBB]);
3688   // If we inserted an edge from the middle block to the unique exit block,
3689   // update uses outside the loop (phis) to account for the newly inserted
3690   // edge.
3691   if (!Cost->requiresScalarEpilogue(VF)) {
3692     // Fix-up external users of the induction variables.
3693     for (auto &Entry : Legal->getInductionVars())
3694       fixupIVUsers(Entry.first, Entry.second,
3695                    getOrCreateVectorTripCount(VectorLoop->getLoopPreheader()),
3696                    IVEndValues[Entry.first], LoopMiddleBlock,
3697                    VectorLoop->getHeader());
3698 
3699     fixLCSSAPHIs(State);
3700   }
3701 
3702   for (Instruction *PI : PredicatedInstructions)
3703     sinkScalarOperands(&*PI);
3704 
3705   // Remove redundant induction instructions.
3706   cse(VectorLoop->getHeader());
3707 
3708   // Set/update profile weights for the vector and remainder loops as original
3709   // loop iterations are now distributed among them. Note that original loop
3710   // represented by LoopScalarBody becomes remainder loop after vectorization.
3711   //
3712   // For cases like foldTailByMasking() and requiresScalarEpiloque() we may
3713   // end up getting slightly roughened result but that should be OK since
3714   // profile is not inherently precise anyway. Note also possible bypass of
3715   // vector code caused by legality checks is ignored, assigning all the weight
3716   // to the vector loop, optimistically.
3717   //
3718   // For scalable vectorization we can't know at compile time how many iterations
3719   // of the loop are handled in one vector iteration, so instead assume a pessimistic
3720   // vscale of '1'.
3721   setProfileInfoAfterUnrolling(LI->getLoopFor(LoopScalarBody), VectorLoop,
3722                                LI->getLoopFor(LoopScalarBody),
3723                                VF.getKnownMinValue() * UF);
3724 }
3725 
3726 void InnerLoopVectorizer::fixCrossIterationPHIs(VPTransformState &State) {
3727   // In order to support recurrences we need to be able to vectorize Phi nodes.
3728   // Phi nodes have cycles, so we need to vectorize them in two stages. This is
3729   // stage #2: We now need to fix the recurrences by adding incoming edges to
3730   // the currently empty PHI nodes. At this point every instruction in the
3731   // original loop is widened to a vector form so we can use them to construct
3732   // the incoming edges.
3733   VPBasicBlock *Header =
3734       State.Plan->getVectorLoopRegion()->getEntryBasicBlock();
3735   for (VPRecipeBase &R : Header->phis()) {
3736     if (auto *ReductionPhi = dyn_cast<VPReductionPHIRecipe>(&R))
3737       fixReduction(ReductionPhi, State);
3738     else if (auto *FOR = dyn_cast<VPFirstOrderRecurrencePHIRecipe>(&R))
3739       fixFirstOrderRecurrence(FOR, State);
3740   }
3741 }
3742 
3743 void InnerLoopVectorizer::fixFirstOrderRecurrence(
3744     VPFirstOrderRecurrencePHIRecipe *PhiR, VPTransformState &State) {
3745   // This is the second phase of vectorizing first-order recurrences. An
3746   // overview of the transformation is described below. Suppose we have the
3747   // following loop.
3748   //
3749   //   for (int i = 0; i < n; ++i)
3750   //     b[i] = a[i] - a[i - 1];
3751   //
3752   // There is a first-order recurrence on "a". For this loop, the shorthand
3753   // scalar IR looks like:
3754   //
3755   //   scalar.ph:
3756   //     s_init = a[-1]
3757   //     br scalar.body
3758   //
3759   //   scalar.body:
3760   //     i = phi [0, scalar.ph], [i+1, scalar.body]
3761   //     s1 = phi [s_init, scalar.ph], [s2, scalar.body]
3762   //     s2 = a[i]
3763   //     b[i] = s2 - s1
3764   //     br cond, scalar.body, ...
3765   //
3766   // In this example, s1 is a recurrence because it's value depends on the
3767   // previous iteration. In the first phase of vectorization, we created a
3768   // vector phi v1 for s1. We now complete the vectorization and produce the
3769   // shorthand vector IR shown below (for VF = 4, UF = 1).
3770   //
3771   //   vector.ph:
3772   //     v_init = vector(..., ..., ..., a[-1])
3773   //     br vector.body
3774   //
3775   //   vector.body
3776   //     i = phi [0, vector.ph], [i+4, vector.body]
3777   //     v1 = phi [v_init, vector.ph], [v2, vector.body]
3778   //     v2 = a[i, i+1, i+2, i+3];
3779   //     v3 = vector(v1(3), v2(0, 1, 2))
3780   //     b[i, i+1, i+2, i+3] = v2 - v3
3781   //     br cond, vector.body, middle.block
3782   //
3783   //   middle.block:
3784   //     x = v2(3)
3785   //     br scalar.ph
3786   //
3787   //   scalar.ph:
3788   //     s_init = phi [x, middle.block], [a[-1], otherwise]
3789   //     br scalar.body
3790   //
3791   // After execution completes the vector loop, we extract the next value of
3792   // the recurrence (x) to use as the initial value in the scalar loop.
3793 
3794   // Extract the last vector element in the middle block. This will be the
3795   // initial value for the recurrence when jumping to the scalar loop.
3796   VPValue *PreviousDef = PhiR->getBackedgeValue();
3797   Value *Incoming = State.get(PreviousDef, UF - 1);
3798   auto *ExtractForScalar = Incoming;
3799   auto *IdxTy = Builder.getInt32Ty();
3800   if (VF.isVector()) {
3801     auto *One = ConstantInt::get(IdxTy, 1);
3802     Builder.SetInsertPoint(LoopMiddleBlock->getTerminator());
3803     auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, VF);
3804     auto *LastIdx = Builder.CreateSub(RuntimeVF, One);
3805     ExtractForScalar = Builder.CreateExtractElement(ExtractForScalar, LastIdx,
3806                                                     "vector.recur.extract");
3807   }
3808   // Extract the second last element in the middle block if the
3809   // Phi is used outside the loop. We need to extract the phi itself
3810   // and not the last element (the phi update in the current iteration). This
3811   // will be the value when jumping to the exit block from the LoopMiddleBlock,
3812   // when the scalar loop is not run at all.
3813   Value *ExtractForPhiUsedOutsideLoop = nullptr;
3814   if (VF.isVector()) {
3815     auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, VF);
3816     auto *Idx = Builder.CreateSub(RuntimeVF, ConstantInt::get(IdxTy, 2));
3817     ExtractForPhiUsedOutsideLoop = Builder.CreateExtractElement(
3818         Incoming, Idx, "vector.recur.extract.for.phi");
3819   } else if (UF > 1)
3820     // When loop is unrolled without vectorizing, initialize
3821     // ExtractForPhiUsedOutsideLoop with the value just prior to unrolled value
3822     // of `Incoming`. This is analogous to the vectorized case above: extracting
3823     // the second last element when VF > 1.
3824     ExtractForPhiUsedOutsideLoop = State.get(PreviousDef, UF - 2);
3825 
3826   // Fix the initial value of the original recurrence in the scalar loop.
3827   Builder.SetInsertPoint(&*LoopScalarPreHeader->begin());
3828   PHINode *Phi = cast<PHINode>(PhiR->getUnderlyingValue());
3829   auto *Start = Builder.CreatePHI(Phi->getType(), 2, "scalar.recur.init");
3830   auto *ScalarInit = PhiR->getStartValue()->getLiveInIRValue();
3831   for (auto *BB : predecessors(LoopScalarPreHeader)) {
3832     auto *Incoming = BB == LoopMiddleBlock ? ExtractForScalar : ScalarInit;
3833     Start->addIncoming(Incoming, BB);
3834   }
3835 
3836   Phi->setIncomingValueForBlock(LoopScalarPreHeader, Start);
3837   Phi->setName("scalar.recur");
3838 
3839   // Finally, fix users of the recurrence outside the loop. The users will need
3840   // either the last value of the scalar recurrence or the last value of the
3841   // vector recurrence we extracted in the middle block. Since the loop is in
3842   // LCSSA form, we just need to find all the phi nodes for the original scalar
3843   // recurrence in the exit block, and then add an edge for the middle block.
3844   // Note that LCSSA does not imply single entry when the original scalar loop
3845   // had multiple exiting edges (as we always run the last iteration in the
3846   // scalar epilogue); in that case, there is no edge from middle to exit and
3847   // and thus no phis which needed updated.
3848   if (!Cost->requiresScalarEpilogue(VF))
3849     for (PHINode &LCSSAPhi : LoopExitBlock->phis())
3850       if (llvm::is_contained(LCSSAPhi.incoming_values(), Phi))
3851         LCSSAPhi.addIncoming(ExtractForPhiUsedOutsideLoop, LoopMiddleBlock);
3852 }
3853 
3854 void InnerLoopVectorizer::fixReduction(VPReductionPHIRecipe *PhiR,
3855                                        VPTransformState &State) {
3856   PHINode *OrigPhi = cast<PHINode>(PhiR->getUnderlyingValue());
3857   // Get it's reduction variable descriptor.
3858   assert(Legal->isReductionVariable(OrigPhi) &&
3859          "Unable to find the reduction variable");
3860   const RecurrenceDescriptor &RdxDesc = PhiR->getRecurrenceDescriptor();
3861 
3862   RecurKind RK = RdxDesc.getRecurrenceKind();
3863   TrackingVH<Value> ReductionStartValue = RdxDesc.getRecurrenceStartValue();
3864   Instruction *LoopExitInst = RdxDesc.getLoopExitInstr();
3865   setDebugLocFromInst(ReductionStartValue);
3866 
3867   VPValue *LoopExitInstDef = PhiR->getBackedgeValue();
3868   // This is the vector-clone of the value that leaves the loop.
3869   Type *VecTy = State.get(LoopExitInstDef, 0)->getType();
3870 
3871   // Wrap flags are in general invalid after vectorization, clear them.
3872   clearReductionWrapFlags(RdxDesc, State);
3873 
3874   // Before each round, move the insertion point right between
3875   // the PHIs and the values we are going to write.
3876   // This allows us to write both PHINodes and the extractelement
3877   // instructions.
3878   Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
3879 
3880   setDebugLocFromInst(LoopExitInst);
3881 
3882   Type *PhiTy = OrigPhi->getType();
3883 
3884   VPBasicBlock *LatchVPBB =
3885       PhiR->getParent()->getEnclosingLoopRegion()->getExitBasicBlock();
3886   BasicBlock *VectorLoopLatch = State.CFG.VPBB2IRBB[LatchVPBB];
3887   // If tail is folded by masking, the vector value to leave the loop should be
3888   // a Select choosing between the vectorized LoopExitInst and vectorized Phi,
3889   // instead of the former. For an inloop reduction the reduction will already
3890   // be predicated, and does not need to be handled here.
3891   if (Cost->foldTailByMasking() && !PhiR->isInLoop()) {
3892     for (unsigned Part = 0; Part < UF; ++Part) {
3893       Value *VecLoopExitInst = State.get(LoopExitInstDef, Part);
3894       Value *Sel = nullptr;
3895       for (User *U : VecLoopExitInst->users()) {
3896         if (isa<SelectInst>(U)) {
3897           assert(!Sel && "Reduction exit feeding two selects");
3898           Sel = U;
3899         } else
3900           assert(isa<PHINode>(U) && "Reduction exit must feed Phi's or select");
3901       }
3902       assert(Sel && "Reduction exit feeds no select");
3903       State.reset(LoopExitInstDef, Sel, Part);
3904 
3905       // If the target can create a predicated operator for the reduction at no
3906       // extra cost in the loop (for example a predicated vadd), it can be
3907       // cheaper for the select to remain in the loop than be sunk out of it,
3908       // and so use the select value for the phi instead of the old
3909       // LoopExitValue.
3910       if (PreferPredicatedReductionSelect ||
3911           TTI->preferPredicatedReductionSelect(
3912               RdxDesc.getOpcode(), PhiTy,
3913               TargetTransformInfo::ReductionFlags())) {
3914         auto *VecRdxPhi =
3915             cast<PHINode>(State.get(PhiR, Part));
3916         VecRdxPhi->setIncomingValueForBlock(VectorLoopLatch, Sel);
3917       }
3918     }
3919   }
3920 
3921   // If the vector reduction can be performed in a smaller type, we truncate
3922   // then extend the loop exit value to enable InstCombine to evaluate the
3923   // entire expression in the smaller type.
3924   if (VF.isVector() && PhiTy != RdxDesc.getRecurrenceType()) {
3925     assert(!PhiR->isInLoop() && "Unexpected truncated inloop reduction!");
3926     Type *RdxVecTy = VectorType::get(RdxDesc.getRecurrenceType(), VF);
3927     Builder.SetInsertPoint(VectorLoopLatch->getTerminator());
3928     VectorParts RdxParts(UF);
3929     for (unsigned Part = 0; Part < UF; ++Part) {
3930       RdxParts[Part] = State.get(LoopExitInstDef, Part);
3931       Value *Trunc = Builder.CreateTrunc(RdxParts[Part], RdxVecTy);
3932       Value *Extnd = RdxDesc.isSigned() ? Builder.CreateSExt(Trunc, VecTy)
3933                                         : Builder.CreateZExt(Trunc, VecTy);
3934       for (User *U : llvm::make_early_inc_range(RdxParts[Part]->users()))
3935         if (U != Trunc) {
3936           U->replaceUsesOfWith(RdxParts[Part], Extnd);
3937           RdxParts[Part] = Extnd;
3938         }
3939     }
3940     Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
3941     for (unsigned Part = 0; Part < UF; ++Part) {
3942       RdxParts[Part] = Builder.CreateTrunc(RdxParts[Part], RdxVecTy);
3943       State.reset(LoopExitInstDef, RdxParts[Part], Part);
3944     }
3945   }
3946 
3947   // Reduce all of the unrolled parts into a single vector.
3948   Value *ReducedPartRdx = State.get(LoopExitInstDef, 0);
3949   unsigned Op = RecurrenceDescriptor::getOpcode(RK);
3950 
3951   // The middle block terminator has already been assigned a DebugLoc here (the
3952   // OrigLoop's single latch terminator). We want the whole middle block to
3953   // appear to execute on this line because: (a) it is all compiler generated,
3954   // (b) these instructions are always executed after evaluating the latch
3955   // conditional branch, and (c) other passes may add new predecessors which
3956   // terminate on this line. This is the easiest way to ensure we don't
3957   // accidentally cause an extra step back into the loop while debugging.
3958   setDebugLocFromInst(LoopMiddleBlock->getTerminator());
3959   if (PhiR->isOrdered())
3960     ReducedPartRdx = State.get(LoopExitInstDef, UF - 1);
3961   else {
3962     // Floating-point operations should have some FMF to enable the reduction.
3963     IRBuilderBase::FastMathFlagGuard FMFG(Builder);
3964     Builder.setFastMathFlags(RdxDesc.getFastMathFlags());
3965     for (unsigned Part = 1; Part < UF; ++Part) {
3966       Value *RdxPart = State.get(LoopExitInstDef, Part);
3967       if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
3968         ReducedPartRdx = Builder.CreateBinOp(
3969             (Instruction::BinaryOps)Op, RdxPart, ReducedPartRdx, "bin.rdx");
3970       } else if (RecurrenceDescriptor::isSelectCmpRecurrenceKind(RK))
3971         ReducedPartRdx = createSelectCmpOp(Builder, ReductionStartValue, RK,
3972                                            ReducedPartRdx, RdxPart);
3973       else
3974         ReducedPartRdx = createMinMaxOp(Builder, RK, ReducedPartRdx, RdxPart);
3975     }
3976   }
3977 
3978   // Create the reduction after the loop. Note that inloop reductions create the
3979   // target reduction in the loop using a Reduction recipe.
3980   if (VF.isVector() && !PhiR->isInLoop()) {
3981     ReducedPartRdx =
3982         createTargetReduction(Builder, TTI, RdxDesc, ReducedPartRdx, OrigPhi);
3983     // If the reduction can be performed in a smaller type, we need to extend
3984     // the reduction to the wider type before we branch to the original loop.
3985     if (PhiTy != RdxDesc.getRecurrenceType())
3986       ReducedPartRdx = RdxDesc.isSigned()
3987                            ? Builder.CreateSExt(ReducedPartRdx, PhiTy)
3988                            : Builder.CreateZExt(ReducedPartRdx, PhiTy);
3989   }
3990 
3991   PHINode *ResumePhi =
3992       dyn_cast<PHINode>(PhiR->getStartValue()->getUnderlyingValue());
3993 
3994   // Create a phi node that merges control-flow from the backedge-taken check
3995   // block and the middle block.
3996   PHINode *BCBlockPhi = PHINode::Create(PhiTy, 2, "bc.merge.rdx",
3997                                         LoopScalarPreHeader->getTerminator());
3998 
3999   // If we are fixing reductions in the epilogue loop then we should already
4000   // have created a bc.merge.rdx Phi after the main vector body. Ensure that
4001   // we carry over the incoming values correctly.
4002   for (auto *Incoming : predecessors(LoopScalarPreHeader)) {
4003     if (Incoming == LoopMiddleBlock)
4004       BCBlockPhi->addIncoming(ReducedPartRdx, Incoming);
4005     else if (ResumePhi && llvm::is_contained(ResumePhi->blocks(), Incoming))
4006       BCBlockPhi->addIncoming(ResumePhi->getIncomingValueForBlock(Incoming),
4007                               Incoming);
4008     else
4009       BCBlockPhi->addIncoming(ReductionStartValue, Incoming);
4010   }
4011 
4012   // Set the resume value for this reduction
4013   ReductionResumeValues.insert({&RdxDesc, BCBlockPhi});
4014 
4015   // If there were stores of the reduction value to a uniform memory address
4016   // inside the loop, create the final store here.
4017   if (StoreInst *SI = RdxDesc.IntermediateStore) {
4018     StoreInst *NewSI =
4019         Builder.CreateStore(ReducedPartRdx, SI->getPointerOperand());
4020     propagateMetadata(NewSI, SI);
4021 
4022     // If the reduction value is used in other places,
4023     // then let the code below create PHI's for that.
4024   }
4025 
4026   // Now, we need to fix the users of the reduction variable
4027   // inside and outside of the scalar remainder loop.
4028 
4029   // We know that the loop is in LCSSA form. We need to update the PHI nodes
4030   // in the exit blocks.  See comment on analogous loop in
4031   // fixFirstOrderRecurrence for a more complete explaination of the logic.
4032   if (!Cost->requiresScalarEpilogue(VF))
4033     for (PHINode &LCSSAPhi : LoopExitBlock->phis())
4034       if (llvm::is_contained(LCSSAPhi.incoming_values(), LoopExitInst))
4035         LCSSAPhi.addIncoming(ReducedPartRdx, LoopMiddleBlock);
4036 
4037   // Fix the scalar loop reduction variable with the incoming reduction sum
4038   // from the vector body and from the backedge value.
4039   int IncomingEdgeBlockIdx =
4040       OrigPhi->getBasicBlockIndex(OrigLoop->getLoopLatch());
4041   assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
4042   // Pick the other block.
4043   int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
4044   OrigPhi->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi);
4045   OrigPhi->setIncomingValue(IncomingEdgeBlockIdx, LoopExitInst);
4046 }
4047 
4048 void InnerLoopVectorizer::clearReductionWrapFlags(const RecurrenceDescriptor &RdxDesc,
4049                                                   VPTransformState &State) {
4050   RecurKind RK = RdxDesc.getRecurrenceKind();
4051   if (RK != RecurKind::Add && RK != RecurKind::Mul)
4052     return;
4053 
4054   Instruction *LoopExitInstr = RdxDesc.getLoopExitInstr();
4055   assert(LoopExitInstr && "null loop exit instruction");
4056   SmallVector<Instruction *, 8> Worklist;
4057   SmallPtrSet<Instruction *, 8> Visited;
4058   Worklist.push_back(LoopExitInstr);
4059   Visited.insert(LoopExitInstr);
4060 
4061   while (!Worklist.empty()) {
4062     Instruction *Cur = Worklist.pop_back_val();
4063     if (isa<OverflowingBinaryOperator>(Cur))
4064       for (unsigned Part = 0; Part < UF; ++Part) {
4065         // FIXME: Should not rely on getVPValue at this point.
4066         Value *V = State.get(State.Plan->getVPValue(Cur, true), Part);
4067         cast<Instruction>(V)->dropPoisonGeneratingFlags();
4068       }
4069 
4070     for (User *U : Cur->users()) {
4071       Instruction *UI = cast<Instruction>(U);
4072       if ((Cur != LoopExitInstr || OrigLoop->contains(UI->getParent())) &&
4073           Visited.insert(UI).second)
4074         Worklist.push_back(UI);
4075     }
4076   }
4077 }
4078 
4079 void InnerLoopVectorizer::fixLCSSAPHIs(VPTransformState &State) {
4080   for (PHINode &LCSSAPhi : LoopExitBlock->phis()) {
4081     if (LCSSAPhi.getBasicBlockIndex(LoopMiddleBlock) != -1)
4082       // Some phis were already hand updated by the reduction and recurrence
4083       // code above, leave them alone.
4084       continue;
4085 
4086     auto *IncomingValue = LCSSAPhi.getIncomingValue(0);
4087     // Non-instruction incoming values will have only one value.
4088 
4089     VPLane Lane = VPLane::getFirstLane();
4090     if (isa<Instruction>(IncomingValue) &&
4091         !Cost->isUniformAfterVectorization(cast<Instruction>(IncomingValue),
4092                                            VF))
4093       Lane = VPLane::getLastLaneForVF(VF);
4094 
4095     // Can be a loop invariant incoming value or the last scalar value to be
4096     // extracted from the vectorized loop.
4097     // FIXME: Should not rely on getVPValue at this point.
4098     Builder.SetInsertPoint(LoopMiddleBlock->getTerminator());
4099     Value *lastIncomingValue =
4100         OrigLoop->isLoopInvariant(IncomingValue)
4101             ? IncomingValue
4102             : State.get(State.Plan->getVPValue(IncomingValue, true),
4103                         VPIteration(UF - 1, Lane));
4104     LCSSAPhi.addIncoming(lastIncomingValue, LoopMiddleBlock);
4105   }
4106 }
4107 
4108 void InnerLoopVectorizer::sinkScalarOperands(Instruction *PredInst) {
4109   // The basic block and loop containing the predicated instruction.
4110   auto *PredBB = PredInst->getParent();
4111   auto *VectorLoop = LI->getLoopFor(PredBB);
4112 
4113   // Initialize a worklist with the operands of the predicated instruction.
4114   SetVector<Value *> Worklist(PredInst->op_begin(), PredInst->op_end());
4115 
4116   // Holds instructions that we need to analyze again. An instruction may be
4117   // reanalyzed if we don't yet know if we can sink it or not.
4118   SmallVector<Instruction *, 8> InstsToReanalyze;
4119 
4120   // Returns true if a given use occurs in the predicated block. Phi nodes use
4121   // their operands in their corresponding predecessor blocks.
4122   auto isBlockOfUsePredicated = [&](Use &U) -> bool {
4123     auto *I = cast<Instruction>(U.getUser());
4124     BasicBlock *BB = I->getParent();
4125     if (auto *Phi = dyn_cast<PHINode>(I))
4126       BB = Phi->getIncomingBlock(
4127           PHINode::getIncomingValueNumForOperand(U.getOperandNo()));
4128     return BB == PredBB;
4129   };
4130 
4131   // Iteratively sink the scalarized operands of the predicated instruction
4132   // into the block we created for it. When an instruction is sunk, it's
4133   // operands are then added to the worklist. The algorithm ends after one pass
4134   // through the worklist doesn't sink a single instruction.
4135   bool Changed;
4136   do {
4137     // Add the instructions that need to be reanalyzed to the worklist, and
4138     // reset the changed indicator.
4139     Worklist.insert(InstsToReanalyze.begin(), InstsToReanalyze.end());
4140     InstsToReanalyze.clear();
4141     Changed = false;
4142 
4143     while (!Worklist.empty()) {
4144       auto *I = dyn_cast<Instruction>(Worklist.pop_back_val());
4145 
4146       // We can't sink an instruction if it is a phi node, is not in the loop,
4147       // or may have side effects.
4148       if (!I || isa<PHINode>(I) || !VectorLoop->contains(I) ||
4149           I->mayHaveSideEffects())
4150         continue;
4151 
4152       // If the instruction is already in PredBB, check if we can sink its
4153       // operands. In that case, VPlan's sinkScalarOperands() succeeded in
4154       // sinking the scalar instruction I, hence it appears in PredBB; but it
4155       // may have failed to sink I's operands (recursively), which we try
4156       // (again) here.
4157       if (I->getParent() == PredBB) {
4158         Worklist.insert(I->op_begin(), I->op_end());
4159         continue;
4160       }
4161 
4162       // It's legal to sink the instruction if all its uses occur in the
4163       // predicated block. Otherwise, there's nothing to do yet, and we may
4164       // need to reanalyze the instruction.
4165       if (!llvm::all_of(I->uses(), isBlockOfUsePredicated)) {
4166         InstsToReanalyze.push_back(I);
4167         continue;
4168       }
4169 
4170       // Move the instruction to the beginning of the predicated block, and add
4171       // it's operands to the worklist.
4172       I->moveBefore(&*PredBB->getFirstInsertionPt());
4173       Worklist.insert(I->op_begin(), I->op_end());
4174 
4175       // The sinking may have enabled other instructions to be sunk, so we will
4176       // need to iterate.
4177       Changed = true;
4178     }
4179   } while (Changed);
4180 }
4181 
4182 void InnerLoopVectorizer::fixNonInductionPHIs(VPTransformState &State) {
4183   for (PHINode *OrigPhi : OrigPHIsToFix) {
4184     VPWidenPHIRecipe *VPPhi =
4185         cast<VPWidenPHIRecipe>(State.Plan->getVPValue(OrigPhi));
4186     PHINode *NewPhi = cast<PHINode>(State.get(VPPhi, 0));
4187     // Make sure the builder has a valid insert point.
4188     Builder.SetInsertPoint(NewPhi);
4189     for (unsigned i = 0; i < VPPhi->getNumOperands(); ++i) {
4190       VPValue *Inc = VPPhi->getIncomingValue(i);
4191       VPBasicBlock *VPBB = VPPhi->getIncomingBlock(i);
4192       NewPhi->addIncoming(State.get(Inc, 0), State.CFG.VPBB2IRBB[VPBB]);
4193     }
4194   }
4195 }
4196 
4197 bool InnerLoopVectorizer::useOrderedReductions(
4198     const RecurrenceDescriptor &RdxDesc) {
4199   return Cost->useOrderedReductions(RdxDesc);
4200 }
4201 
4202 void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN,
4203                                               VPWidenPHIRecipe *PhiR,
4204                                               VPTransformState &State) {
4205   assert(EnableVPlanNativePath &&
4206          "Non-native vplans are not expected to have VPWidenPHIRecipes.");
4207   // Currently we enter here in the VPlan-native path for non-induction
4208   // PHIs where all control flow is uniform. We simply widen these PHIs.
4209   // Create a vector phi with no operands - the vector phi operands will be
4210   // set at the end of vector code generation.
4211   Type *VecTy = (State.VF.isScalar())
4212                     ? PN->getType()
4213                     : VectorType::get(PN->getType(), State.VF);
4214   Value *VecPhi = Builder.CreatePHI(VecTy, PN->getNumOperands(), "vec.phi");
4215   State.set(PhiR, VecPhi, 0);
4216   OrigPHIsToFix.push_back(cast<PHINode>(PN));
4217 }
4218 
4219 /// A helper function for checking whether an integer division-related
4220 /// instruction may divide by zero (in which case it must be predicated if
4221 /// executed conditionally in the scalar code).
4222 /// TODO: It may be worthwhile to generalize and check isKnownNonZero().
4223 /// Non-zero divisors that are non compile-time constants will not be
4224 /// converted into multiplication, so we will still end up scalarizing
4225 /// the division, but can do so w/o predication.
4226 static bool mayDivideByZero(Instruction &I) {
4227   assert((I.getOpcode() == Instruction::UDiv ||
4228           I.getOpcode() == Instruction::SDiv ||
4229           I.getOpcode() == Instruction::URem ||
4230           I.getOpcode() == Instruction::SRem) &&
4231          "Unexpected instruction");
4232   Value *Divisor = I.getOperand(1);
4233   auto *CInt = dyn_cast<ConstantInt>(Divisor);
4234   return !CInt || CInt->isZero();
4235 }
4236 
4237 void InnerLoopVectorizer::widenCallInstruction(CallInst &I, VPValue *Def,
4238                                                VPUser &ArgOperands,
4239                                                VPTransformState &State) {
4240   assert(!isa<DbgInfoIntrinsic>(I) &&
4241          "DbgInfoIntrinsic should have been dropped during VPlan construction");
4242   setDebugLocFromInst(&I);
4243 
4244   Module *M = I.getParent()->getParent()->getParent();
4245   auto *CI = cast<CallInst>(&I);
4246 
4247   SmallVector<Type *, 4> Tys;
4248   for (Value *ArgOperand : CI->args())
4249     Tys.push_back(ToVectorTy(ArgOperand->getType(), VF.getKnownMinValue()));
4250 
4251   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4252 
4253   // The flag shows whether we use Intrinsic or a usual Call for vectorized
4254   // version of the instruction.
4255   // Is it beneficial to perform intrinsic call compared to lib call?
4256   bool NeedToScalarize = false;
4257   InstructionCost CallCost = Cost->getVectorCallCost(CI, VF, NeedToScalarize);
4258   InstructionCost IntrinsicCost = ID ? Cost->getVectorIntrinsicCost(CI, VF) : 0;
4259   bool UseVectorIntrinsic = ID && IntrinsicCost <= CallCost;
4260   assert((UseVectorIntrinsic || !NeedToScalarize) &&
4261          "Instruction should be scalarized elsewhere.");
4262   assert((IntrinsicCost.isValid() || CallCost.isValid()) &&
4263          "Either the intrinsic cost or vector call cost must be valid");
4264 
4265   for (unsigned Part = 0; Part < UF; ++Part) {
4266     SmallVector<Type *, 2> TysForDecl = {CI->getType()};
4267     SmallVector<Value *, 4> Args;
4268     for (auto &I : enumerate(ArgOperands.operands())) {
4269       // Some intrinsics have a scalar argument - don't replace it with a
4270       // vector.
4271       Value *Arg;
4272       if (!UseVectorIntrinsic ||
4273           !isVectorIntrinsicWithScalarOpAtArg(ID, I.index()))
4274         Arg = State.get(I.value(), Part);
4275       else
4276         Arg = State.get(I.value(), VPIteration(0, 0));
4277       if (isVectorIntrinsicWithOverloadTypeAtArg(ID, I.index()))
4278         TysForDecl.push_back(Arg->getType());
4279       Args.push_back(Arg);
4280     }
4281 
4282     Function *VectorF;
4283     if (UseVectorIntrinsic) {
4284       // Use vector version of the intrinsic.
4285       if (VF.isVector())
4286         TysForDecl[0] = VectorType::get(CI->getType()->getScalarType(), VF);
4287       VectorF = Intrinsic::getDeclaration(M, ID, TysForDecl);
4288       assert(VectorF && "Can't retrieve vector intrinsic.");
4289     } else {
4290       // Use vector version of the function call.
4291       const VFShape Shape = VFShape::get(*CI, VF, false /*HasGlobalPred*/);
4292 #ifndef NDEBUG
4293       assert(VFDatabase(*CI).getVectorizedFunction(Shape) != nullptr &&
4294              "Can't create vector function.");
4295 #endif
4296         VectorF = VFDatabase(*CI).getVectorizedFunction(Shape);
4297     }
4298       SmallVector<OperandBundleDef, 1> OpBundles;
4299       CI->getOperandBundlesAsDefs(OpBundles);
4300       CallInst *V = Builder.CreateCall(VectorF, Args, OpBundles);
4301 
4302       if (isa<FPMathOperator>(V))
4303         V->copyFastMathFlags(CI);
4304 
4305       State.set(Def, V, Part);
4306       addMetadata(V, &I);
4307   }
4308 }
4309 
4310 void LoopVectorizationCostModel::collectLoopScalars(ElementCount VF) {
4311   // We should not collect Scalars more than once per VF. Right now, this
4312   // function is called from collectUniformsAndScalars(), which already does
4313   // this check. Collecting Scalars for VF=1 does not make any sense.
4314   assert(VF.isVector() && Scalars.find(VF) == Scalars.end() &&
4315          "This function should not be visited twice for the same VF");
4316 
4317   // This avoids any chances of creating a REPLICATE recipe during planning
4318   // since that would result in generation of scalarized code during execution,
4319   // which is not supported for scalable vectors.
4320   if (VF.isScalable()) {
4321     Scalars[VF].insert(Uniforms[VF].begin(), Uniforms[VF].end());
4322     return;
4323   }
4324 
4325   SmallSetVector<Instruction *, 8> Worklist;
4326 
4327   // These sets are used to seed the analysis with pointers used by memory
4328   // accesses that will remain scalar.
4329   SmallSetVector<Instruction *, 8> ScalarPtrs;
4330   SmallPtrSet<Instruction *, 8> PossibleNonScalarPtrs;
4331   auto *Latch = TheLoop->getLoopLatch();
4332 
4333   // A helper that returns true if the use of Ptr by MemAccess will be scalar.
4334   // The pointer operands of loads and stores will be scalar as long as the
4335   // memory access is not a gather or scatter operation. The value operand of a
4336   // store will remain scalar if the store is scalarized.
4337   auto isScalarUse = [&](Instruction *MemAccess, Value *Ptr) {
4338     InstWidening WideningDecision = getWideningDecision(MemAccess, VF);
4339     assert(WideningDecision != CM_Unknown &&
4340            "Widening decision should be ready at this moment");
4341     if (auto *Store = dyn_cast<StoreInst>(MemAccess))
4342       if (Ptr == Store->getValueOperand())
4343         return WideningDecision == CM_Scalarize;
4344     assert(Ptr == getLoadStorePointerOperand(MemAccess) &&
4345            "Ptr is neither a value or pointer operand");
4346     return WideningDecision != CM_GatherScatter;
4347   };
4348 
4349   // A helper that returns true if the given value is a bitcast or
4350   // getelementptr instruction contained in the loop.
4351   auto isLoopVaryingBitCastOrGEP = [&](Value *V) {
4352     return ((isa<BitCastInst>(V) && V->getType()->isPointerTy()) ||
4353             isa<GetElementPtrInst>(V)) &&
4354            !TheLoop->isLoopInvariant(V);
4355   };
4356 
4357   // A helper that evaluates a memory access's use of a pointer. If the use will
4358   // be a scalar use and the pointer is only used by memory accesses, we place
4359   // the pointer in ScalarPtrs. Otherwise, the pointer is placed in
4360   // PossibleNonScalarPtrs.
4361   auto evaluatePtrUse = [&](Instruction *MemAccess, Value *Ptr) {
4362     // We only care about bitcast and getelementptr instructions contained in
4363     // the loop.
4364     if (!isLoopVaryingBitCastOrGEP(Ptr))
4365       return;
4366 
4367     // If the pointer has already been identified as scalar (e.g., if it was
4368     // also identified as uniform), there's nothing to do.
4369     auto *I = cast<Instruction>(Ptr);
4370     if (Worklist.count(I))
4371       return;
4372 
4373     // If the use of the pointer will be a scalar use, and all users of the
4374     // pointer are memory accesses, place the pointer in ScalarPtrs. Otherwise,
4375     // place the pointer in PossibleNonScalarPtrs.
4376     if (isScalarUse(MemAccess, Ptr) && llvm::all_of(I->users(), [&](User *U) {
4377           return isa<LoadInst>(U) || isa<StoreInst>(U);
4378         }))
4379       ScalarPtrs.insert(I);
4380     else
4381       PossibleNonScalarPtrs.insert(I);
4382   };
4383 
4384   // We seed the scalars analysis with three classes of instructions: (1)
4385   // instructions marked uniform-after-vectorization and (2) bitcast,
4386   // getelementptr and (pointer) phi instructions used by memory accesses
4387   // requiring a scalar use.
4388   //
4389   // (1) Add to the worklist all instructions that have been identified as
4390   // uniform-after-vectorization.
4391   Worklist.insert(Uniforms[VF].begin(), Uniforms[VF].end());
4392 
4393   // (2) Add to the worklist all bitcast and getelementptr instructions used by
4394   // memory accesses requiring a scalar use. The pointer operands of loads and
4395   // stores will be scalar as long as the memory accesses is not a gather or
4396   // scatter operation. The value operand of a store will remain scalar if the
4397   // store is scalarized.
4398   for (auto *BB : TheLoop->blocks())
4399     for (auto &I : *BB) {
4400       if (auto *Load = dyn_cast<LoadInst>(&I)) {
4401         evaluatePtrUse(Load, Load->getPointerOperand());
4402       } else if (auto *Store = dyn_cast<StoreInst>(&I)) {
4403         evaluatePtrUse(Store, Store->getPointerOperand());
4404         evaluatePtrUse(Store, Store->getValueOperand());
4405       }
4406     }
4407   for (auto *I : ScalarPtrs)
4408     if (!PossibleNonScalarPtrs.count(I)) {
4409       LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *I << "\n");
4410       Worklist.insert(I);
4411     }
4412 
4413   // Insert the forced scalars.
4414   // FIXME: Currently widenPHIInstruction() often creates a dead vector
4415   // induction variable when the PHI user is scalarized.
4416   auto ForcedScalar = ForcedScalars.find(VF);
4417   if (ForcedScalar != ForcedScalars.end())
4418     for (auto *I : ForcedScalar->second)
4419       Worklist.insert(I);
4420 
4421   // Expand the worklist by looking through any bitcasts and getelementptr
4422   // instructions we've already identified as scalar. This is similar to the
4423   // expansion step in collectLoopUniforms(); however, here we're only
4424   // expanding to include additional bitcasts and getelementptr instructions.
4425   unsigned Idx = 0;
4426   while (Idx != Worklist.size()) {
4427     Instruction *Dst = Worklist[Idx++];
4428     if (!isLoopVaryingBitCastOrGEP(Dst->getOperand(0)))
4429       continue;
4430     auto *Src = cast<Instruction>(Dst->getOperand(0));
4431     if (llvm::all_of(Src->users(), [&](User *U) -> bool {
4432           auto *J = cast<Instruction>(U);
4433           return !TheLoop->contains(J) || Worklist.count(J) ||
4434                  ((isa<LoadInst>(J) || isa<StoreInst>(J)) &&
4435                   isScalarUse(J, Src));
4436         })) {
4437       Worklist.insert(Src);
4438       LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Src << "\n");
4439     }
4440   }
4441 
4442   // An induction variable will remain scalar if all users of the induction
4443   // variable and induction variable update remain scalar.
4444   for (auto &Induction : Legal->getInductionVars()) {
4445     auto *Ind = Induction.first;
4446     auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
4447 
4448     // If tail-folding is applied, the primary induction variable will be used
4449     // to feed a vector compare.
4450     if (Ind == Legal->getPrimaryInduction() && foldTailByMasking())
4451       continue;
4452 
4453     // Returns true if \p Indvar is a pointer induction that is used directly by
4454     // load/store instruction \p I.
4455     auto IsDirectLoadStoreFromPtrIndvar = [&](Instruction *Indvar,
4456                                               Instruction *I) {
4457       return Induction.second.getKind() ==
4458                  InductionDescriptor::IK_PtrInduction &&
4459              (isa<LoadInst>(I) || isa<StoreInst>(I)) &&
4460              Indvar == getLoadStorePointerOperand(I) && isScalarUse(I, Indvar);
4461     };
4462 
4463     // Determine if all users of the induction variable are scalar after
4464     // vectorization.
4465     auto ScalarInd = llvm::all_of(Ind->users(), [&](User *U) -> bool {
4466       auto *I = cast<Instruction>(U);
4467       return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) ||
4468              IsDirectLoadStoreFromPtrIndvar(Ind, I);
4469     });
4470     if (!ScalarInd)
4471       continue;
4472 
4473     // Determine if all users of the induction variable update instruction are
4474     // scalar after vectorization.
4475     auto ScalarIndUpdate =
4476         llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
4477           auto *I = cast<Instruction>(U);
4478           return I == Ind || !TheLoop->contains(I) || Worklist.count(I) ||
4479                  IsDirectLoadStoreFromPtrIndvar(IndUpdate, I);
4480         });
4481     if (!ScalarIndUpdate)
4482       continue;
4483 
4484     // The induction variable and its update instruction will remain scalar.
4485     Worklist.insert(Ind);
4486     Worklist.insert(IndUpdate);
4487     LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Ind << "\n");
4488     LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *IndUpdate
4489                       << "\n");
4490   }
4491 
4492   Scalars[VF].insert(Worklist.begin(), Worklist.end());
4493 }
4494 
4495 bool LoopVectorizationCostModel::isScalarWithPredication(
4496     Instruction *I, ElementCount VF) const {
4497   if (!blockNeedsPredicationForAnyReason(I->getParent()))
4498     return false;
4499   switch(I->getOpcode()) {
4500   default:
4501     break;
4502   case Instruction::Load:
4503   case Instruction::Store: {
4504     if (!Legal->isMaskRequired(I))
4505       return false;
4506     auto *Ptr = getLoadStorePointerOperand(I);
4507     auto *Ty = getLoadStoreType(I);
4508     Type *VTy = Ty;
4509     if (VF.isVector())
4510       VTy = VectorType::get(Ty, VF);
4511     const Align Alignment = getLoadStoreAlignment(I);
4512     return isa<LoadInst>(I) ? !(isLegalMaskedLoad(Ty, Ptr, Alignment) ||
4513                                 TTI.isLegalMaskedGather(VTy, Alignment))
4514                             : !(isLegalMaskedStore(Ty, Ptr, Alignment) ||
4515                                 TTI.isLegalMaskedScatter(VTy, Alignment));
4516   }
4517   case Instruction::UDiv:
4518   case Instruction::SDiv:
4519   case Instruction::SRem:
4520   case Instruction::URem:
4521     return mayDivideByZero(*I);
4522   }
4523   return false;
4524 }
4525 
4526 bool LoopVectorizationCostModel::interleavedAccessCanBeWidened(
4527     Instruction *I, ElementCount VF) {
4528   assert(isAccessInterleaved(I) && "Expecting interleaved access.");
4529   assert(getWideningDecision(I, VF) == CM_Unknown &&
4530          "Decision should not be set yet.");
4531   auto *Group = getInterleavedAccessGroup(I);
4532   assert(Group && "Must have a group.");
4533 
4534   // If the instruction's allocated size doesn't equal it's type size, it
4535   // requires padding and will be scalarized.
4536   auto &DL = I->getModule()->getDataLayout();
4537   auto *ScalarTy = getLoadStoreType(I);
4538   if (hasIrregularType(ScalarTy, DL))
4539     return false;
4540 
4541   // If the group involves a non-integral pointer, we may not be able to
4542   // losslessly cast all values to a common type.
4543   unsigned InterleaveFactor = Group->getFactor();
4544   bool ScalarNI = DL.isNonIntegralPointerType(ScalarTy);
4545   for (unsigned i = 0; i < InterleaveFactor; i++) {
4546     Instruction *Member = Group->getMember(i);
4547     if (!Member)
4548       continue;
4549     auto *MemberTy = getLoadStoreType(Member);
4550     bool MemberNI = DL.isNonIntegralPointerType(MemberTy);
4551     // Don't coerce non-integral pointers to integers or vice versa.
4552     if (MemberNI != ScalarNI) {
4553       // TODO: Consider adding special nullptr value case here
4554       return false;
4555     } else if (MemberNI && ScalarNI &&
4556                ScalarTy->getPointerAddressSpace() !=
4557                MemberTy->getPointerAddressSpace()) {
4558       return false;
4559     }
4560   }
4561 
4562   // Check if masking is required.
4563   // A Group may need masking for one of two reasons: it resides in a block that
4564   // needs predication, or it was decided to use masking to deal with gaps
4565   // (either a gap at the end of a load-access that may result in a speculative
4566   // load, or any gaps in a store-access).
4567   bool PredicatedAccessRequiresMasking =
4568       blockNeedsPredicationForAnyReason(I->getParent()) &&
4569       Legal->isMaskRequired(I);
4570   bool LoadAccessWithGapsRequiresEpilogMasking =
4571       isa<LoadInst>(I) && Group->requiresScalarEpilogue() &&
4572       !isScalarEpilogueAllowed();
4573   bool StoreAccessWithGapsRequiresMasking =
4574       isa<StoreInst>(I) && (Group->getNumMembers() < Group->getFactor());
4575   if (!PredicatedAccessRequiresMasking &&
4576       !LoadAccessWithGapsRequiresEpilogMasking &&
4577       !StoreAccessWithGapsRequiresMasking)
4578     return true;
4579 
4580   // If masked interleaving is required, we expect that the user/target had
4581   // enabled it, because otherwise it either wouldn't have been created or
4582   // it should have been invalidated by the CostModel.
4583   assert(useMaskedInterleavedAccesses(TTI) &&
4584          "Masked interleave-groups for predicated accesses are not enabled.");
4585 
4586   if (Group->isReverse())
4587     return false;
4588 
4589   auto *Ty = getLoadStoreType(I);
4590   const Align Alignment = getLoadStoreAlignment(I);
4591   return isa<LoadInst>(I) ? TTI.isLegalMaskedLoad(Ty, Alignment)
4592                           : TTI.isLegalMaskedStore(Ty, Alignment);
4593 }
4594 
4595 bool LoopVectorizationCostModel::memoryInstructionCanBeWidened(
4596     Instruction *I, ElementCount VF) {
4597   // Get and ensure we have a valid memory instruction.
4598   assert((isa<LoadInst, StoreInst>(I)) && "Invalid memory instruction");
4599 
4600   auto *Ptr = getLoadStorePointerOperand(I);
4601   auto *ScalarTy = getLoadStoreType(I);
4602 
4603   // In order to be widened, the pointer should be consecutive, first of all.
4604   if (!Legal->isConsecutivePtr(ScalarTy, Ptr))
4605     return false;
4606 
4607   // If the instruction is a store located in a predicated block, it will be
4608   // scalarized.
4609   if (isScalarWithPredication(I, VF))
4610     return false;
4611 
4612   // If the instruction's allocated size doesn't equal it's type size, it
4613   // requires padding and will be scalarized.
4614   auto &DL = I->getModule()->getDataLayout();
4615   if (hasIrregularType(ScalarTy, DL))
4616     return false;
4617 
4618   return true;
4619 }
4620 
4621 void LoopVectorizationCostModel::collectLoopUniforms(ElementCount VF) {
4622   // We should not collect Uniforms more than once per VF. Right now,
4623   // this function is called from collectUniformsAndScalars(), which
4624   // already does this check. Collecting Uniforms for VF=1 does not make any
4625   // sense.
4626 
4627   assert(VF.isVector() && Uniforms.find(VF) == Uniforms.end() &&
4628          "This function should not be visited twice for the same VF");
4629 
4630   // Visit the list of Uniforms. If we'll not find any uniform value, we'll
4631   // not analyze again.  Uniforms.count(VF) will return 1.
4632   Uniforms[VF].clear();
4633 
4634   // We now know that the loop is vectorizable!
4635   // Collect instructions inside the loop that will remain uniform after
4636   // vectorization.
4637 
4638   // Global values, params and instructions outside of current loop are out of
4639   // scope.
4640   auto isOutOfScope = [&](Value *V) -> bool {
4641     Instruction *I = dyn_cast<Instruction>(V);
4642     return (!I || !TheLoop->contains(I));
4643   };
4644 
4645   // Worklist containing uniform instructions demanding lane 0.
4646   SetVector<Instruction *> Worklist;
4647   BasicBlock *Latch = TheLoop->getLoopLatch();
4648 
4649   // Add uniform instructions demanding lane 0 to the worklist. Instructions
4650   // that are scalar with predication must not be considered uniform after
4651   // vectorization, because that would create an erroneous replicating region
4652   // where only a single instance out of VF should be formed.
4653   // TODO: optimize such seldom cases if found important, see PR40816.
4654   auto addToWorklistIfAllowed = [&](Instruction *I) -> void {
4655     if (isOutOfScope(I)) {
4656       LLVM_DEBUG(dbgs() << "LV: Found not uniform due to scope: "
4657                         << *I << "\n");
4658       return;
4659     }
4660     if (isScalarWithPredication(I, VF)) {
4661       LLVM_DEBUG(dbgs() << "LV: Found not uniform being ScalarWithPredication: "
4662                         << *I << "\n");
4663       return;
4664     }
4665     LLVM_DEBUG(dbgs() << "LV: Found uniform instruction: " << *I << "\n");
4666     Worklist.insert(I);
4667   };
4668 
4669   // Start with the conditional branch. If the branch condition is an
4670   // instruction contained in the loop that is only used by the branch, it is
4671   // uniform.
4672   auto *Cmp = dyn_cast<Instruction>(Latch->getTerminator()->getOperand(0));
4673   if (Cmp && TheLoop->contains(Cmp) && Cmp->hasOneUse())
4674     addToWorklistIfAllowed(Cmp);
4675 
4676   auto isUniformDecision = [&](Instruction *I, ElementCount VF) {
4677     InstWidening WideningDecision = getWideningDecision(I, VF);
4678     assert(WideningDecision != CM_Unknown &&
4679            "Widening decision should be ready at this moment");
4680 
4681     // A uniform memory op is itself uniform.  We exclude uniform stores
4682     // here as they demand the last lane, not the first one.
4683     if (isa<LoadInst>(I) && Legal->isUniformMemOp(*I)) {
4684       assert(WideningDecision == CM_Scalarize);
4685       return true;
4686     }
4687 
4688     return (WideningDecision == CM_Widen ||
4689             WideningDecision == CM_Widen_Reverse ||
4690             WideningDecision == CM_Interleave);
4691   };
4692 
4693 
4694   // Returns true if Ptr is the pointer operand of a memory access instruction
4695   // I, and I is known to not require scalarization.
4696   auto isVectorizedMemAccessUse = [&](Instruction *I, Value *Ptr) -> bool {
4697     return getLoadStorePointerOperand(I) == Ptr && isUniformDecision(I, VF);
4698   };
4699 
4700   // Holds a list of values which are known to have at least one uniform use.
4701   // Note that there may be other uses which aren't uniform.  A "uniform use"
4702   // here is something which only demands lane 0 of the unrolled iterations;
4703   // it does not imply that all lanes produce the same value (e.g. this is not
4704   // the usual meaning of uniform)
4705   SetVector<Value *> HasUniformUse;
4706 
4707   // Scan the loop for instructions which are either a) known to have only
4708   // lane 0 demanded or b) are uses which demand only lane 0 of their operand.
4709   for (auto *BB : TheLoop->blocks())
4710     for (auto &I : *BB) {
4711       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I)) {
4712         switch (II->getIntrinsicID()) {
4713         case Intrinsic::sideeffect:
4714         case Intrinsic::experimental_noalias_scope_decl:
4715         case Intrinsic::assume:
4716         case Intrinsic::lifetime_start:
4717         case Intrinsic::lifetime_end:
4718           if (TheLoop->hasLoopInvariantOperands(&I))
4719             addToWorklistIfAllowed(&I);
4720           break;
4721         default:
4722           break;
4723         }
4724       }
4725 
4726       // ExtractValue instructions must be uniform, because the operands are
4727       // known to be loop-invariant.
4728       if (auto *EVI = dyn_cast<ExtractValueInst>(&I)) {
4729         assert(isOutOfScope(EVI->getAggregateOperand()) &&
4730                "Expected aggregate value to be loop invariant");
4731         addToWorklistIfAllowed(EVI);
4732         continue;
4733       }
4734 
4735       // If there's no pointer operand, there's nothing to do.
4736       auto *Ptr = getLoadStorePointerOperand(&I);
4737       if (!Ptr)
4738         continue;
4739 
4740       // A uniform memory op is itself uniform.  We exclude uniform stores
4741       // here as they demand the last lane, not the first one.
4742       if (isa<LoadInst>(I) && Legal->isUniformMemOp(I))
4743         addToWorklistIfAllowed(&I);
4744 
4745       if (isUniformDecision(&I, VF)) {
4746         assert(isVectorizedMemAccessUse(&I, Ptr) && "consistency check");
4747         HasUniformUse.insert(Ptr);
4748       }
4749     }
4750 
4751   // Add to the worklist any operands which have *only* uniform (e.g. lane 0
4752   // demanding) users.  Since loops are assumed to be in LCSSA form, this
4753   // disallows uses outside the loop as well.
4754   for (auto *V : HasUniformUse) {
4755     if (isOutOfScope(V))
4756       continue;
4757     auto *I = cast<Instruction>(V);
4758     auto UsersAreMemAccesses =
4759       llvm::all_of(I->users(), [&](User *U) -> bool {
4760         return isVectorizedMemAccessUse(cast<Instruction>(U), V);
4761       });
4762     if (UsersAreMemAccesses)
4763       addToWorklistIfAllowed(I);
4764   }
4765 
4766   // Expand Worklist in topological order: whenever a new instruction
4767   // is added , its users should be already inside Worklist.  It ensures
4768   // a uniform instruction will only be used by uniform instructions.
4769   unsigned idx = 0;
4770   while (idx != Worklist.size()) {
4771     Instruction *I = Worklist[idx++];
4772 
4773     for (auto OV : I->operand_values()) {
4774       // isOutOfScope operands cannot be uniform instructions.
4775       if (isOutOfScope(OV))
4776         continue;
4777       // First order recurrence Phi's should typically be considered
4778       // non-uniform.
4779       auto *OP = dyn_cast<PHINode>(OV);
4780       if (OP && Legal->isFirstOrderRecurrence(OP))
4781         continue;
4782       // If all the users of the operand are uniform, then add the
4783       // operand into the uniform worklist.
4784       auto *OI = cast<Instruction>(OV);
4785       if (llvm::all_of(OI->users(), [&](User *U) -> bool {
4786             auto *J = cast<Instruction>(U);
4787             return Worklist.count(J) || isVectorizedMemAccessUse(J, OI);
4788           }))
4789         addToWorklistIfAllowed(OI);
4790     }
4791   }
4792 
4793   // For an instruction to be added into Worklist above, all its users inside
4794   // the loop should also be in Worklist. However, this condition cannot be
4795   // true for phi nodes that form a cyclic dependence. We must process phi
4796   // nodes separately. An induction variable will remain uniform if all users
4797   // of the induction variable and induction variable update remain uniform.
4798   // The code below handles both pointer and non-pointer induction variables.
4799   for (auto &Induction : Legal->getInductionVars()) {
4800     auto *Ind = Induction.first;
4801     auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
4802 
4803     // Determine if all users of the induction variable are uniform after
4804     // vectorization.
4805     auto UniformInd = llvm::all_of(Ind->users(), [&](User *U) -> bool {
4806       auto *I = cast<Instruction>(U);
4807       return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) ||
4808              isVectorizedMemAccessUse(I, Ind);
4809     });
4810     if (!UniformInd)
4811       continue;
4812 
4813     // Determine if all users of the induction variable update instruction are
4814     // uniform after vectorization.
4815     auto UniformIndUpdate =
4816         llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
4817           auto *I = cast<Instruction>(U);
4818           return I == Ind || !TheLoop->contains(I) || Worklist.count(I) ||
4819                  isVectorizedMemAccessUse(I, IndUpdate);
4820         });
4821     if (!UniformIndUpdate)
4822       continue;
4823 
4824     // The induction variable and its update instruction will remain uniform.
4825     addToWorklistIfAllowed(Ind);
4826     addToWorklistIfAllowed(IndUpdate);
4827   }
4828 
4829   Uniforms[VF].insert(Worklist.begin(), Worklist.end());
4830 }
4831 
4832 bool LoopVectorizationCostModel::runtimeChecksRequired() {
4833   LLVM_DEBUG(dbgs() << "LV: Performing code size checks.\n");
4834 
4835   if (Legal->getRuntimePointerChecking()->Need) {
4836     reportVectorizationFailure("Runtime ptr check is required with -Os/-Oz",
4837         "runtime pointer checks needed. Enable vectorization of this "
4838         "loop with '#pragma clang loop vectorize(enable)' when "
4839         "compiling with -Os/-Oz",
4840         "CantVersionLoopWithOptForSize", ORE, TheLoop);
4841     return true;
4842   }
4843 
4844   if (!PSE.getPredicate().isAlwaysTrue()) {
4845     reportVectorizationFailure("Runtime SCEV check is required with -Os/-Oz",
4846         "runtime SCEV checks needed. Enable vectorization of this "
4847         "loop with '#pragma clang loop vectorize(enable)' when "
4848         "compiling with -Os/-Oz",
4849         "CantVersionLoopWithOptForSize", ORE, TheLoop);
4850     return true;
4851   }
4852 
4853   // FIXME: Avoid specializing for stride==1 instead of bailing out.
4854   if (!Legal->getLAI()->getSymbolicStrides().empty()) {
4855     reportVectorizationFailure("Runtime stride check for small trip count",
4856         "runtime stride == 1 checks needed. Enable vectorization of "
4857         "this loop without such check by compiling with -Os/-Oz",
4858         "CantVersionLoopWithOptForSize", ORE, TheLoop);
4859     return true;
4860   }
4861 
4862   return false;
4863 }
4864 
4865 ElementCount
4866 LoopVectorizationCostModel::getMaxLegalScalableVF(unsigned MaxSafeElements) {
4867   if (!TTI.supportsScalableVectors() && !ForceTargetSupportsScalableVectors)
4868     return ElementCount::getScalable(0);
4869 
4870   if (Hints->isScalableVectorizationDisabled()) {
4871     reportVectorizationInfo("Scalable vectorization is explicitly disabled",
4872                             "ScalableVectorizationDisabled", ORE, TheLoop);
4873     return ElementCount::getScalable(0);
4874   }
4875 
4876   LLVM_DEBUG(dbgs() << "LV: Scalable vectorization is available\n");
4877 
4878   auto MaxScalableVF = ElementCount::getScalable(
4879       std::numeric_limits<ElementCount::ScalarTy>::max());
4880 
4881   // Test that the loop-vectorizer can legalize all operations for this MaxVF.
4882   // FIXME: While for scalable vectors this is currently sufficient, this should
4883   // be replaced by a more detailed mechanism that filters out specific VFs,
4884   // instead of invalidating vectorization for a whole set of VFs based on the
4885   // MaxVF.
4886 
4887   // Disable scalable vectorization if the loop contains unsupported reductions.
4888   if (!canVectorizeReductions(MaxScalableVF)) {
4889     reportVectorizationInfo(
4890         "Scalable vectorization not supported for the reduction "
4891         "operations found in this loop.",
4892         "ScalableVFUnfeasible", ORE, TheLoop);
4893     return ElementCount::getScalable(0);
4894   }
4895 
4896   // Disable scalable vectorization if the loop contains any instructions
4897   // with element types not supported for scalable vectors.
4898   if (any_of(ElementTypesInLoop, [&](Type *Ty) {
4899         return !Ty->isVoidTy() &&
4900                !this->TTI.isElementTypeLegalForScalableVector(Ty);
4901       })) {
4902     reportVectorizationInfo("Scalable vectorization is not supported "
4903                             "for all element types found in this loop.",
4904                             "ScalableVFUnfeasible", ORE, TheLoop);
4905     return ElementCount::getScalable(0);
4906   }
4907 
4908   if (Legal->isSafeForAnyVectorWidth())
4909     return MaxScalableVF;
4910 
4911   // Limit MaxScalableVF by the maximum safe dependence distance.
4912   Optional<unsigned> MaxVScale = TTI.getMaxVScale();
4913   if (!MaxVScale && TheFunction->hasFnAttribute(Attribute::VScaleRange))
4914     MaxVScale =
4915         TheFunction->getFnAttribute(Attribute::VScaleRange).getVScaleRangeMax();
4916   MaxScalableVF = ElementCount::getScalable(
4917       MaxVScale ? (MaxSafeElements / MaxVScale.getValue()) : 0);
4918   if (!MaxScalableVF)
4919     reportVectorizationInfo(
4920         "Max legal vector width too small, scalable vectorization "
4921         "unfeasible.",
4922         "ScalableVFUnfeasible", ORE, TheLoop);
4923 
4924   return MaxScalableVF;
4925 }
4926 
4927 FixedScalableVFPair LoopVectorizationCostModel::computeFeasibleMaxVF(
4928     unsigned ConstTripCount, ElementCount UserVF, bool FoldTailByMasking) {
4929   MinBWs = computeMinimumValueSizes(TheLoop->getBlocks(), *DB, &TTI);
4930   unsigned SmallestType, WidestType;
4931   std::tie(SmallestType, WidestType) = getSmallestAndWidestTypes();
4932 
4933   // Get the maximum safe dependence distance in bits computed by LAA.
4934   // It is computed by MaxVF * sizeOf(type) * 8, where type is taken from
4935   // the memory accesses that is most restrictive (involved in the smallest
4936   // dependence distance).
4937   unsigned MaxSafeElements =
4938       PowerOf2Floor(Legal->getMaxSafeVectorWidthInBits() / WidestType);
4939 
4940   auto MaxSafeFixedVF = ElementCount::getFixed(MaxSafeElements);
4941   auto MaxSafeScalableVF = getMaxLegalScalableVF(MaxSafeElements);
4942 
4943   LLVM_DEBUG(dbgs() << "LV: The max safe fixed VF is: " << MaxSafeFixedVF
4944                     << ".\n");
4945   LLVM_DEBUG(dbgs() << "LV: The max safe scalable VF is: " << MaxSafeScalableVF
4946                     << ".\n");
4947 
4948   // First analyze the UserVF, fall back if the UserVF should be ignored.
4949   if (UserVF) {
4950     auto MaxSafeUserVF =
4951         UserVF.isScalable() ? MaxSafeScalableVF : MaxSafeFixedVF;
4952 
4953     if (ElementCount::isKnownLE(UserVF, MaxSafeUserVF)) {
4954       // If `VF=vscale x N` is safe, then so is `VF=N`
4955       if (UserVF.isScalable())
4956         return FixedScalableVFPair(
4957             ElementCount::getFixed(UserVF.getKnownMinValue()), UserVF);
4958       else
4959         return UserVF;
4960     }
4961 
4962     assert(ElementCount::isKnownGT(UserVF, MaxSafeUserVF));
4963 
4964     // Only clamp if the UserVF is not scalable. If the UserVF is scalable, it
4965     // is better to ignore the hint and let the compiler choose a suitable VF.
4966     if (!UserVF.isScalable()) {
4967       LLVM_DEBUG(dbgs() << "LV: User VF=" << UserVF
4968                         << " is unsafe, clamping to max safe VF="
4969                         << MaxSafeFixedVF << ".\n");
4970       ORE->emit([&]() {
4971         return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationFactor",
4972                                           TheLoop->getStartLoc(),
4973                                           TheLoop->getHeader())
4974                << "User-specified vectorization factor "
4975                << ore::NV("UserVectorizationFactor", UserVF)
4976                << " is unsafe, clamping to maximum safe vectorization factor "
4977                << ore::NV("VectorizationFactor", MaxSafeFixedVF);
4978       });
4979       return MaxSafeFixedVF;
4980     }
4981 
4982     if (!TTI.supportsScalableVectors() && !ForceTargetSupportsScalableVectors) {
4983       LLVM_DEBUG(dbgs() << "LV: User VF=" << UserVF
4984                         << " is ignored because scalable vectors are not "
4985                            "available.\n");
4986       ORE->emit([&]() {
4987         return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationFactor",
4988                                           TheLoop->getStartLoc(),
4989                                           TheLoop->getHeader())
4990                << "User-specified vectorization factor "
4991                << ore::NV("UserVectorizationFactor", UserVF)
4992                << " is ignored because the target does not support scalable "
4993                   "vectors. The compiler will pick a more suitable value.";
4994       });
4995     } else {
4996       LLVM_DEBUG(dbgs() << "LV: User VF=" << UserVF
4997                         << " is unsafe. Ignoring scalable UserVF.\n");
4998       ORE->emit([&]() {
4999         return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationFactor",
5000                                           TheLoop->getStartLoc(),
5001                                           TheLoop->getHeader())
5002                << "User-specified vectorization factor "
5003                << ore::NV("UserVectorizationFactor", UserVF)
5004                << " is unsafe. Ignoring the hint to let the compiler pick a "
5005                   "more suitable value.";
5006       });
5007     }
5008   }
5009 
5010   LLVM_DEBUG(dbgs() << "LV: The Smallest and Widest types: " << SmallestType
5011                     << " / " << WidestType << " bits.\n");
5012 
5013   FixedScalableVFPair Result(ElementCount::getFixed(1),
5014                              ElementCount::getScalable(0));
5015   if (auto MaxVF =
5016           getMaximizedVFForTarget(ConstTripCount, SmallestType, WidestType,
5017                                   MaxSafeFixedVF, FoldTailByMasking))
5018     Result.FixedVF = MaxVF;
5019 
5020   if (auto MaxVF =
5021           getMaximizedVFForTarget(ConstTripCount, SmallestType, WidestType,
5022                                   MaxSafeScalableVF, FoldTailByMasking))
5023     if (MaxVF.isScalable()) {
5024       Result.ScalableVF = MaxVF;
5025       LLVM_DEBUG(dbgs() << "LV: Found feasible scalable VF = " << MaxVF
5026                         << "\n");
5027     }
5028 
5029   return Result;
5030 }
5031 
5032 FixedScalableVFPair
5033 LoopVectorizationCostModel::computeMaxVF(ElementCount UserVF, unsigned UserIC) {
5034   if (Legal->getRuntimePointerChecking()->Need && TTI.hasBranchDivergence()) {
5035     // TODO: It may by useful to do since it's still likely to be dynamically
5036     // uniform if the target can skip.
5037     reportVectorizationFailure(
5038         "Not inserting runtime ptr check for divergent target",
5039         "runtime pointer checks needed. Not enabled for divergent target",
5040         "CantVersionLoopWithDivergentTarget", ORE, TheLoop);
5041     return FixedScalableVFPair::getNone();
5042   }
5043 
5044   unsigned TC = PSE.getSE()->getSmallConstantTripCount(TheLoop);
5045   LLVM_DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
5046   if (TC == 1) {
5047     reportVectorizationFailure("Single iteration (non) loop",
5048         "loop trip count is one, irrelevant for vectorization",
5049         "SingleIterationLoop", ORE, TheLoop);
5050     return FixedScalableVFPair::getNone();
5051   }
5052 
5053   switch (ScalarEpilogueStatus) {
5054   case CM_ScalarEpilogueAllowed:
5055     return computeFeasibleMaxVF(TC, UserVF, false);
5056   case CM_ScalarEpilogueNotAllowedUsePredicate:
5057     LLVM_FALLTHROUGH;
5058   case CM_ScalarEpilogueNotNeededUsePredicate:
5059     LLVM_DEBUG(
5060         dbgs() << "LV: vector predicate hint/switch found.\n"
5061                << "LV: Not allowing scalar epilogue, creating predicated "
5062                << "vector loop.\n");
5063     break;
5064   case CM_ScalarEpilogueNotAllowedLowTripLoop:
5065     // fallthrough as a special case of OptForSize
5066   case CM_ScalarEpilogueNotAllowedOptSize:
5067     if (ScalarEpilogueStatus == CM_ScalarEpilogueNotAllowedOptSize)
5068       LLVM_DEBUG(
5069           dbgs() << "LV: Not allowing scalar epilogue due to -Os/-Oz.\n");
5070     else
5071       LLVM_DEBUG(dbgs() << "LV: Not allowing scalar epilogue due to low trip "
5072                         << "count.\n");
5073 
5074     // Bail if runtime checks are required, which are not good when optimising
5075     // for size.
5076     if (runtimeChecksRequired())
5077       return FixedScalableVFPair::getNone();
5078 
5079     break;
5080   }
5081 
5082   // The only loops we can vectorize without a scalar epilogue, are loops with
5083   // a bottom-test and a single exiting block. We'd have to handle the fact
5084   // that not every instruction executes on the last iteration.  This will
5085   // require a lane mask which varies through the vector loop body.  (TODO)
5086   if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
5087     // If there was a tail-folding hint/switch, but we can't fold the tail by
5088     // masking, fallback to a vectorization with a scalar epilogue.
5089     if (ScalarEpilogueStatus == CM_ScalarEpilogueNotNeededUsePredicate) {
5090       LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking: vectorize with a "
5091                            "scalar epilogue instead.\n");
5092       ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
5093       return computeFeasibleMaxVF(TC, UserVF, false);
5094     }
5095     return FixedScalableVFPair::getNone();
5096   }
5097 
5098   // Now try the tail folding
5099 
5100   // Invalidate interleave groups that require an epilogue if we can't mask
5101   // the interleave-group.
5102   if (!useMaskedInterleavedAccesses(TTI)) {
5103     assert(WideningDecisions.empty() && Uniforms.empty() && Scalars.empty() &&
5104            "No decisions should have been taken at this point");
5105     // Note: There is no need to invalidate any cost modeling decisions here, as
5106     // non where taken so far.
5107     InterleaveInfo.invalidateGroupsRequiringScalarEpilogue();
5108   }
5109 
5110   FixedScalableVFPair MaxFactors = computeFeasibleMaxVF(TC, UserVF, true);
5111   // Avoid tail folding if the trip count is known to be a multiple of any VF
5112   // we chose.
5113   // FIXME: The condition below pessimises the case for fixed-width vectors,
5114   // when scalable VFs are also candidates for vectorization.
5115   if (MaxFactors.FixedVF.isVector() && !MaxFactors.ScalableVF) {
5116     ElementCount MaxFixedVF = MaxFactors.FixedVF;
5117     assert((UserVF.isNonZero() || isPowerOf2_32(MaxFixedVF.getFixedValue())) &&
5118            "MaxFixedVF must be a power of 2");
5119     unsigned MaxVFtimesIC = UserIC ? MaxFixedVF.getFixedValue() * UserIC
5120                                    : MaxFixedVF.getFixedValue();
5121     ScalarEvolution *SE = PSE.getSE();
5122     const SCEV *BackedgeTakenCount = PSE.getBackedgeTakenCount();
5123     const SCEV *ExitCount = SE->getAddExpr(
5124         BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType()));
5125     const SCEV *Rem = SE->getURemExpr(
5126         SE->applyLoopGuards(ExitCount, TheLoop),
5127         SE->getConstant(BackedgeTakenCount->getType(), MaxVFtimesIC));
5128     if (Rem->isZero()) {
5129       // Accept MaxFixedVF if we do not have a tail.
5130       LLVM_DEBUG(dbgs() << "LV: No tail will remain for any chosen VF.\n");
5131       return MaxFactors;
5132     }
5133   }
5134 
5135   // For scalable vectors don't use tail folding for low trip counts or
5136   // optimizing for code size. We only permit this if the user has explicitly
5137   // requested it.
5138   if (ScalarEpilogueStatus != CM_ScalarEpilogueNotNeededUsePredicate &&
5139       ScalarEpilogueStatus != CM_ScalarEpilogueNotAllowedUsePredicate &&
5140       MaxFactors.ScalableVF.isVector())
5141     MaxFactors.ScalableVF = ElementCount::getScalable(0);
5142 
5143   // If we don't know the precise trip count, or if the trip count that we
5144   // found modulo the vectorization factor is not zero, try to fold the tail
5145   // by masking.
5146   // FIXME: look for a smaller MaxVF that does divide TC rather than masking.
5147   if (Legal->prepareToFoldTailByMasking()) {
5148     FoldTailByMasking = true;
5149     return MaxFactors;
5150   }
5151 
5152   // If there was a tail-folding hint/switch, but we can't fold the tail by
5153   // masking, fallback to a vectorization with a scalar epilogue.
5154   if (ScalarEpilogueStatus == CM_ScalarEpilogueNotNeededUsePredicate) {
5155     LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking: vectorize with a "
5156                          "scalar epilogue instead.\n");
5157     ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
5158     return MaxFactors;
5159   }
5160 
5161   if (ScalarEpilogueStatus == CM_ScalarEpilogueNotAllowedUsePredicate) {
5162     LLVM_DEBUG(dbgs() << "LV: Can't fold tail by masking: don't vectorize\n");
5163     return FixedScalableVFPair::getNone();
5164   }
5165 
5166   if (TC == 0) {
5167     reportVectorizationFailure(
5168         "Unable to calculate the loop count due to complex control flow",
5169         "unable to calculate the loop count due to complex control flow",
5170         "UnknownLoopCountComplexCFG", ORE, TheLoop);
5171     return FixedScalableVFPair::getNone();
5172   }
5173 
5174   reportVectorizationFailure(
5175       "Cannot optimize for size and vectorize at the same time.",
5176       "cannot optimize for size and vectorize at the same time. "
5177       "Enable vectorization of this loop with '#pragma clang loop "
5178       "vectorize(enable)' when compiling with -Os/-Oz",
5179       "NoTailLoopWithOptForSize", ORE, TheLoop);
5180   return FixedScalableVFPair::getNone();
5181 }
5182 
5183 ElementCount LoopVectorizationCostModel::getMaximizedVFForTarget(
5184     unsigned ConstTripCount, unsigned SmallestType, unsigned WidestType,
5185     const ElementCount &MaxSafeVF, bool FoldTailByMasking) {
5186   bool ComputeScalableMaxVF = MaxSafeVF.isScalable();
5187   TypeSize WidestRegister = TTI.getRegisterBitWidth(
5188       ComputeScalableMaxVF ? TargetTransformInfo::RGK_ScalableVector
5189                            : TargetTransformInfo::RGK_FixedWidthVector);
5190 
5191   // Convenience function to return the minimum of two ElementCounts.
5192   auto MinVF = [](const ElementCount &LHS, const ElementCount &RHS) {
5193     assert((LHS.isScalable() == RHS.isScalable()) &&
5194            "Scalable flags must match");
5195     return ElementCount::isKnownLT(LHS, RHS) ? LHS : RHS;
5196   };
5197 
5198   // Ensure MaxVF is a power of 2; the dependence distance bound may not be.
5199   // Note that both WidestRegister and WidestType may not be a powers of 2.
5200   auto MaxVectorElementCount = ElementCount::get(
5201       PowerOf2Floor(WidestRegister.getKnownMinSize() / WidestType),
5202       ComputeScalableMaxVF);
5203   MaxVectorElementCount = MinVF(MaxVectorElementCount, MaxSafeVF);
5204   LLVM_DEBUG(dbgs() << "LV: The Widest register safe to use is: "
5205                     << (MaxVectorElementCount * WidestType) << " bits.\n");
5206 
5207   if (!MaxVectorElementCount) {
5208     LLVM_DEBUG(dbgs() << "LV: The target has no "
5209                       << (ComputeScalableMaxVF ? "scalable" : "fixed")
5210                       << " vector registers.\n");
5211     return ElementCount::getFixed(1);
5212   }
5213 
5214   const auto TripCountEC = ElementCount::getFixed(ConstTripCount);
5215   if (ConstTripCount &&
5216       ElementCount::isKnownLE(TripCountEC, MaxVectorElementCount) &&
5217       (!FoldTailByMasking || isPowerOf2_32(ConstTripCount))) {
5218     // If loop trip count (TC) is known at compile time there is no point in
5219     // choosing VF greater than TC (as done in the loop below). Select maximum
5220     // power of two which doesn't exceed TC.
5221     // If MaxVectorElementCount is scalable, we only fall back on a fixed VF
5222     // when the TC is less than or equal to the known number of lanes.
5223     auto ClampedConstTripCount = PowerOf2Floor(ConstTripCount);
5224     LLVM_DEBUG(dbgs() << "LV: Clamping the MaxVF to maximum power of two not "
5225                          "exceeding the constant trip count: "
5226                       << ClampedConstTripCount << "\n");
5227     return ElementCount::getFixed(ClampedConstTripCount);
5228   }
5229 
5230   ElementCount MaxVF = MaxVectorElementCount;
5231   if (MaximizeBandwidth || (MaximizeBandwidth.getNumOccurrences() == 0 &&
5232                             TTI.shouldMaximizeVectorBandwidth())) {
5233     auto MaxVectorElementCountMaxBW = ElementCount::get(
5234         PowerOf2Floor(WidestRegister.getKnownMinSize() / SmallestType),
5235         ComputeScalableMaxVF);
5236     MaxVectorElementCountMaxBW = MinVF(MaxVectorElementCountMaxBW, MaxSafeVF);
5237 
5238     // Collect all viable vectorization factors larger than the default MaxVF
5239     // (i.e. MaxVectorElementCount).
5240     SmallVector<ElementCount, 8> VFs;
5241     for (ElementCount VS = MaxVectorElementCount * 2;
5242          ElementCount::isKnownLE(VS, MaxVectorElementCountMaxBW); VS *= 2)
5243       VFs.push_back(VS);
5244 
5245     // For each VF calculate its register usage.
5246     auto RUs = calculateRegisterUsage(VFs);
5247 
5248     // Select the largest VF which doesn't require more registers than existing
5249     // ones.
5250     for (int i = RUs.size() - 1; i >= 0; --i) {
5251       bool Selected = true;
5252       for (auto &pair : RUs[i].MaxLocalUsers) {
5253         unsigned TargetNumRegisters = TTI.getNumberOfRegisters(pair.first);
5254         if (pair.second > TargetNumRegisters)
5255           Selected = false;
5256       }
5257       if (Selected) {
5258         MaxVF = VFs[i];
5259         break;
5260       }
5261     }
5262     if (ElementCount MinVF =
5263             TTI.getMinimumVF(SmallestType, ComputeScalableMaxVF)) {
5264       if (ElementCount::isKnownLT(MaxVF, MinVF)) {
5265         LLVM_DEBUG(dbgs() << "LV: Overriding calculated MaxVF(" << MaxVF
5266                           << ") with target's minimum: " << MinVF << '\n');
5267         MaxVF = MinVF;
5268       }
5269     }
5270 
5271     // Invalidate any widening decisions we might have made, in case the loop
5272     // requires prediction (decided later), but we have already made some
5273     // load/store widening decisions.
5274     invalidateCostModelingDecisions();
5275   }
5276   return MaxVF;
5277 }
5278 
5279 Optional<unsigned> LoopVectorizationCostModel::getVScaleForTuning() const {
5280   if (TheFunction->hasFnAttribute(Attribute::VScaleRange)) {
5281     auto Attr = TheFunction->getFnAttribute(Attribute::VScaleRange);
5282     auto Min = Attr.getVScaleRangeMin();
5283     auto Max = Attr.getVScaleRangeMax();
5284     if (Max && Min == Max)
5285       return Max;
5286   }
5287 
5288   return TTI.getVScaleForTuning();
5289 }
5290 
5291 bool LoopVectorizationCostModel::isMoreProfitable(
5292     const VectorizationFactor &A, const VectorizationFactor &B) const {
5293   InstructionCost CostA = A.Cost;
5294   InstructionCost CostB = B.Cost;
5295 
5296   unsigned MaxTripCount = PSE.getSE()->getSmallConstantMaxTripCount(TheLoop);
5297 
5298   if (!A.Width.isScalable() && !B.Width.isScalable() && FoldTailByMasking &&
5299       MaxTripCount) {
5300     // If we are folding the tail and the trip count is a known (possibly small)
5301     // constant, the trip count will be rounded up to an integer number of
5302     // iterations. The total cost will be PerIterationCost*ceil(TripCount/VF),
5303     // which we compare directly. When not folding the tail, the total cost will
5304     // be PerIterationCost*floor(TC/VF) + Scalar remainder cost, and so is
5305     // approximated with the per-lane cost below instead of using the tripcount
5306     // as here.
5307     auto RTCostA = CostA * divideCeil(MaxTripCount, A.Width.getFixedValue());
5308     auto RTCostB = CostB * divideCeil(MaxTripCount, B.Width.getFixedValue());
5309     return RTCostA < RTCostB;
5310   }
5311 
5312   // Improve estimate for the vector width if it is scalable.
5313   unsigned EstimatedWidthA = A.Width.getKnownMinValue();
5314   unsigned EstimatedWidthB = B.Width.getKnownMinValue();
5315   if (Optional<unsigned> VScale = getVScaleForTuning()) {
5316     if (A.Width.isScalable())
5317       EstimatedWidthA *= VScale.getValue();
5318     if (B.Width.isScalable())
5319       EstimatedWidthB *= VScale.getValue();
5320   }
5321 
5322   // Assume vscale may be larger than 1 (or the value being tuned for),
5323   // so that scalable vectorization is slightly favorable over fixed-width
5324   // vectorization.
5325   if (A.Width.isScalable() && !B.Width.isScalable())
5326     return (CostA * B.Width.getFixedValue()) <= (CostB * EstimatedWidthA);
5327 
5328   // To avoid the need for FP division:
5329   //      (CostA / A.Width) < (CostB / B.Width)
5330   // <=>  (CostA * B.Width) < (CostB * A.Width)
5331   return (CostA * EstimatedWidthB) < (CostB * EstimatedWidthA);
5332 }
5333 
5334 VectorizationFactor LoopVectorizationCostModel::selectVectorizationFactor(
5335     const ElementCountSet &VFCandidates) {
5336   InstructionCost ExpectedCost = expectedCost(ElementCount::getFixed(1)).first;
5337   LLVM_DEBUG(dbgs() << "LV: Scalar loop costs: " << ExpectedCost << ".\n");
5338   assert(ExpectedCost.isValid() && "Unexpected invalid cost for scalar loop");
5339   assert(VFCandidates.count(ElementCount::getFixed(1)) &&
5340          "Expected Scalar VF to be a candidate");
5341 
5342   const VectorizationFactor ScalarCost(ElementCount::getFixed(1), ExpectedCost);
5343   VectorizationFactor ChosenFactor = ScalarCost;
5344 
5345   bool ForceVectorization = Hints->getForce() == LoopVectorizeHints::FK_Enabled;
5346   if (ForceVectorization && VFCandidates.size() > 1) {
5347     // Ignore scalar width, because the user explicitly wants vectorization.
5348     // Initialize cost to max so that VF = 2 is, at least, chosen during cost
5349     // evaluation.
5350     ChosenFactor.Cost = InstructionCost::getMax();
5351   }
5352 
5353   SmallVector<InstructionVFPair> InvalidCosts;
5354   for (const auto &i : VFCandidates) {
5355     // The cost for scalar VF=1 is already calculated, so ignore it.
5356     if (i.isScalar())
5357       continue;
5358 
5359     VectorizationCostTy C = expectedCost(i, &InvalidCosts);
5360     VectorizationFactor Candidate(i, C.first);
5361 
5362 #ifndef NDEBUG
5363     unsigned AssumedMinimumVscale = 1;
5364     if (Optional<unsigned> VScale = getVScaleForTuning())
5365       AssumedMinimumVscale = VScale.getValue();
5366     unsigned Width =
5367         Candidate.Width.isScalable()
5368             ? Candidate.Width.getKnownMinValue() * AssumedMinimumVscale
5369             : Candidate.Width.getFixedValue();
5370     LLVM_DEBUG(dbgs() << "LV: Vector loop of width " << i
5371                       << " costs: " << (Candidate.Cost / Width));
5372     if (i.isScalable())
5373       LLVM_DEBUG(dbgs() << " (assuming a minimum vscale of "
5374                         << AssumedMinimumVscale << ")");
5375     LLVM_DEBUG(dbgs() << ".\n");
5376 #endif
5377 
5378     if (!C.second && !ForceVectorization) {
5379       LLVM_DEBUG(
5380           dbgs() << "LV: Not considering vector loop of width " << i
5381                  << " because it will not generate any vector instructions.\n");
5382       continue;
5383     }
5384 
5385     // If profitable add it to ProfitableVF list.
5386     if (isMoreProfitable(Candidate, ScalarCost))
5387       ProfitableVFs.push_back(Candidate);
5388 
5389     if (isMoreProfitable(Candidate, ChosenFactor))
5390       ChosenFactor = Candidate;
5391   }
5392 
5393   // Emit a report of VFs with invalid costs in the loop.
5394   if (!InvalidCosts.empty()) {
5395     // Group the remarks per instruction, keeping the instruction order from
5396     // InvalidCosts.
5397     std::map<Instruction *, unsigned> Numbering;
5398     unsigned I = 0;
5399     for (auto &Pair : InvalidCosts)
5400       if (!Numbering.count(Pair.first))
5401         Numbering[Pair.first] = I++;
5402 
5403     // Sort the list, first on instruction(number) then on VF.
5404     llvm::sort(InvalidCosts,
5405                [&Numbering](InstructionVFPair &A, InstructionVFPair &B) {
5406                  if (Numbering[A.first] != Numbering[B.first])
5407                    return Numbering[A.first] < Numbering[B.first];
5408                  ElementCountComparator ECC;
5409                  return ECC(A.second, B.second);
5410                });
5411 
5412     // For a list of ordered instruction-vf pairs:
5413     //   [(load, vf1), (load, vf2), (store, vf1)]
5414     // Group the instructions together to emit separate remarks for:
5415     //   load  (vf1, vf2)
5416     //   store (vf1)
5417     auto Tail = ArrayRef<InstructionVFPair>(InvalidCosts);
5418     auto Subset = ArrayRef<InstructionVFPair>();
5419     do {
5420       if (Subset.empty())
5421         Subset = Tail.take_front(1);
5422 
5423       Instruction *I = Subset.front().first;
5424 
5425       // If the next instruction is different, or if there are no other pairs,
5426       // emit a remark for the collated subset. e.g.
5427       //   [(load, vf1), (load, vf2))]
5428       // to emit:
5429       //  remark: invalid costs for 'load' at VF=(vf, vf2)
5430       if (Subset == Tail || Tail[Subset.size()].first != I) {
5431         std::string OutString;
5432         raw_string_ostream OS(OutString);
5433         assert(!Subset.empty() && "Unexpected empty range");
5434         OS << "Instruction with invalid costs prevented vectorization at VF=(";
5435         for (auto &Pair : Subset)
5436           OS << (Pair.second == Subset.front().second ? "" : ", ")
5437              << Pair.second;
5438         OS << "):";
5439         if (auto *CI = dyn_cast<CallInst>(I))
5440           OS << " call to " << CI->getCalledFunction()->getName();
5441         else
5442           OS << " " << I->getOpcodeName();
5443         OS.flush();
5444         reportVectorizationInfo(OutString, "InvalidCost", ORE, TheLoop, I);
5445         Tail = Tail.drop_front(Subset.size());
5446         Subset = {};
5447       } else
5448         // Grow the subset by one element
5449         Subset = Tail.take_front(Subset.size() + 1);
5450     } while (!Tail.empty());
5451   }
5452 
5453   if (!EnableCondStoresVectorization && NumPredStores) {
5454     reportVectorizationFailure("There are conditional stores.",
5455         "store that is conditionally executed prevents vectorization",
5456         "ConditionalStore", ORE, TheLoop);
5457     ChosenFactor = ScalarCost;
5458   }
5459 
5460   LLVM_DEBUG(if (ForceVectorization && !ChosenFactor.Width.isScalar() &&
5461                  ChosenFactor.Cost >= ScalarCost.Cost) dbgs()
5462              << "LV: Vectorization seems to be not beneficial, "
5463              << "but was forced by a user.\n");
5464   LLVM_DEBUG(dbgs() << "LV: Selecting VF: " << ChosenFactor.Width << ".\n");
5465   return ChosenFactor;
5466 }
5467 
5468 bool LoopVectorizationCostModel::isCandidateForEpilogueVectorization(
5469     const Loop &L, ElementCount VF) const {
5470   // Cross iteration phis such as reductions need special handling and are
5471   // currently unsupported.
5472   if (any_of(L.getHeader()->phis(),
5473              [&](PHINode &Phi) { return Legal->isFirstOrderRecurrence(&Phi); }))
5474     return false;
5475 
5476   // Phis with uses outside of the loop require special handling and are
5477   // currently unsupported.
5478   for (auto &Entry : Legal->getInductionVars()) {
5479     // Look for uses of the value of the induction at the last iteration.
5480     Value *PostInc = Entry.first->getIncomingValueForBlock(L.getLoopLatch());
5481     for (User *U : PostInc->users())
5482       if (!L.contains(cast<Instruction>(U)))
5483         return false;
5484     // Look for uses of penultimate value of the induction.
5485     for (User *U : Entry.first->users())
5486       if (!L.contains(cast<Instruction>(U)))
5487         return false;
5488   }
5489 
5490   // Induction variables that are widened require special handling that is
5491   // currently not supported.
5492   if (any_of(Legal->getInductionVars(), [&](auto &Entry) {
5493         return !(this->isScalarAfterVectorization(Entry.first, VF) ||
5494                  this->isProfitableToScalarize(Entry.first, VF));
5495       }))
5496     return false;
5497 
5498   // Epilogue vectorization code has not been auditted to ensure it handles
5499   // non-latch exits properly.  It may be fine, but it needs auditted and
5500   // tested.
5501   if (L.getExitingBlock() != L.getLoopLatch())
5502     return false;
5503 
5504   return true;
5505 }
5506 
5507 bool LoopVectorizationCostModel::isEpilogueVectorizationProfitable(
5508     const ElementCount VF) const {
5509   // FIXME: We need a much better cost-model to take different parameters such
5510   // as register pressure, code size increase and cost of extra branches into
5511   // account. For now we apply a very crude heuristic and only consider loops
5512   // with vectorization factors larger than a certain value.
5513   // We also consider epilogue vectorization unprofitable for targets that don't
5514   // consider interleaving beneficial (eg. MVE).
5515   if (TTI.getMaxInterleaveFactor(VF.getKnownMinValue()) <= 1)
5516     return false;
5517   // FIXME: We should consider changing the threshold for scalable
5518   // vectors to take VScaleForTuning into account.
5519   if (VF.getKnownMinValue() >= EpilogueVectorizationMinVF)
5520     return true;
5521   return false;
5522 }
5523 
5524 VectorizationFactor
5525 LoopVectorizationCostModel::selectEpilogueVectorizationFactor(
5526     const ElementCount MainLoopVF, const LoopVectorizationPlanner &LVP) {
5527   VectorizationFactor Result = VectorizationFactor::Disabled();
5528   if (!EnableEpilogueVectorization) {
5529     LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization is disabled.\n";);
5530     return Result;
5531   }
5532 
5533   if (!isScalarEpilogueAllowed()) {
5534     LLVM_DEBUG(
5535         dbgs() << "LEV: Unable to vectorize epilogue because no epilogue is "
5536                   "allowed.\n";);
5537     return Result;
5538   }
5539 
5540   // Not really a cost consideration, but check for unsupported cases here to
5541   // simplify the logic.
5542   if (!isCandidateForEpilogueVectorization(*TheLoop, MainLoopVF)) {
5543     LLVM_DEBUG(
5544         dbgs() << "LEV: Unable to vectorize epilogue because the loop is "
5545                   "not a supported candidate.\n";);
5546     return Result;
5547   }
5548 
5549   if (EpilogueVectorizationForceVF > 1) {
5550     LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization factor is forced.\n";);
5551     ElementCount ForcedEC = ElementCount::getFixed(EpilogueVectorizationForceVF);
5552     if (LVP.hasPlanWithVF(ForcedEC))
5553       return {ForcedEC, 0};
5554     else {
5555       LLVM_DEBUG(
5556           dbgs()
5557               << "LEV: Epilogue vectorization forced factor is not viable.\n";);
5558       return Result;
5559     }
5560   }
5561 
5562   if (TheLoop->getHeader()->getParent()->hasOptSize() ||
5563       TheLoop->getHeader()->getParent()->hasMinSize()) {
5564     LLVM_DEBUG(
5565         dbgs()
5566             << "LEV: Epilogue vectorization skipped due to opt for size.\n";);
5567     return Result;
5568   }
5569 
5570   if (!isEpilogueVectorizationProfitable(MainLoopVF)) {
5571     LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization is not profitable for "
5572                          "this loop\n");
5573     return Result;
5574   }
5575 
5576   // If MainLoopVF = vscale x 2, and vscale is expected to be 4, then we know
5577   // the main loop handles 8 lanes per iteration. We could still benefit from
5578   // vectorizing the epilogue loop with VF=4.
5579   ElementCount EstimatedRuntimeVF = MainLoopVF;
5580   if (MainLoopVF.isScalable()) {
5581     EstimatedRuntimeVF = ElementCount::getFixed(MainLoopVF.getKnownMinValue());
5582     if (Optional<unsigned> VScale = getVScaleForTuning())
5583       EstimatedRuntimeVF *= VScale.getValue();
5584   }
5585 
5586   for (auto &NextVF : ProfitableVFs)
5587     if (((!NextVF.Width.isScalable() && MainLoopVF.isScalable() &&
5588           ElementCount::isKnownLT(NextVF.Width, EstimatedRuntimeVF)) ||
5589          ElementCount::isKnownLT(NextVF.Width, MainLoopVF)) &&
5590         (Result.Width.isScalar() || isMoreProfitable(NextVF, Result)) &&
5591         LVP.hasPlanWithVF(NextVF.Width))
5592       Result = NextVF;
5593 
5594   if (Result != VectorizationFactor::Disabled())
5595     LLVM_DEBUG(dbgs() << "LEV: Vectorizing epilogue loop with VF = "
5596                       << Result.Width << "\n";);
5597   return Result;
5598 }
5599 
5600 std::pair<unsigned, unsigned>
5601 LoopVectorizationCostModel::getSmallestAndWidestTypes() {
5602   unsigned MinWidth = -1U;
5603   unsigned MaxWidth = 8;
5604   const DataLayout &DL = TheFunction->getParent()->getDataLayout();
5605   // For in-loop reductions, no element types are added to ElementTypesInLoop
5606   // if there are no loads/stores in the loop. In this case, check through the
5607   // reduction variables to determine the maximum width.
5608   if (ElementTypesInLoop.empty() && !Legal->getReductionVars().empty()) {
5609     // Reset MaxWidth so that we can find the smallest type used by recurrences
5610     // in the loop.
5611     MaxWidth = -1U;
5612     for (auto &PhiDescriptorPair : Legal->getReductionVars()) {
5613       const RecurrenceDescriptor &RdxDesc = PhiDescriptorPair.second;
5614       // When finding the min width used by the recurrence we need to account
5615       // for casts on the input operands of the recurrence.
5616       MaxWidth = std::min<unsigned>(
5617           MaxWidth, std::min<unsigned>(
5618                         RdxDesc.getMinWidthCastToRecurrenceTypeInBits(),
5619                         RdxDesc.getRecurrenceType()->getScalarSizeInBits()));
5620     }
5621   } else {
5622     for (Type *T : ElementTypesInLoop) {
5623       MinWidth = std::min<unsigned>(
5624           MinWidth, DL.getTypeSizeInBits(T->getScalarType()).getFixedSize());
5625       MaxWidth = std::max<unsigned>(
5626           MaxWidth, DL.getTypeSizeInBits(T->getScalarType()).getFixedSize());
5627     }
5628   }
5629   return {MinWidth, MaxWidth};
5630 }
5631 
5632 void LoopVectorizationCostModel::collectElementTypesForWidening() {
5633   ElementTypesInLoop.clear();
5634   // For each block.
5635   for (BasicBlock *BB : TheLoop->blocks()) {
5636     // For each instruction in the loop.
5637     for (Instruction &I : BB->instructionsWithoutDebug()) {
5638       Type *T = I.getType();
5639 
5640       // Skip ignored values.
5641       if (ValuesToIgnore.count(&I))
5642         continue;
5643 
5644       // Only examine Loads, Stores and PHINodes.
5645       if (!isa<LoadInst>(I) && !isa<StoreInst>(I) && !isa<PHINode>(I))
5646         continue;
5647 
5648       // Examine PHI nodes that are reduction variables. Update the type to
5649       // account for the recurrence type.
5650       if (auto *PN = dyn_cast<PHINode>(&I)) {
5651         if (!Legal->isReductionVariable(PN))
5652           continue;
5653         const RecurrenceDescriptor &RdxDesc =
5654             Legal->getReductionVars().find(PN)->second;
5655         if (PreferInLoopReductions || useOrderedReductions(RdxDesc) ||
5656             TTI.preferInLoopReduction(RdxDesc.getOpcode(),
5657                                       RdxDesc.getRecurrenceType(),
5658                                       TargetTransformInfo::ReductionFlags()))
5659           continue;
5660         T = RdxDesc.getRecurrenceType();
5661       }
5662 
5663       // Examine the stored values.
5664       if (auto *ST = dyn_cast<StoreInst>(&I))
5665         T = ST->getValueOperand()->getType();
5666 
5667       assert(T->isSized() &&
5668              "Expected the load/store/recurrence type to be sized");
5669 
5670       ElementTypesInLoop.insert(T);
5671     }
5672   }
5673 }
5674 
5675 unsigned LoopVectorizationCostModel::selectInterleaveCount(ElementCount VF,
5676                                                            unsigned LoopCost) {
5677   // -- The interleave heuristics --
5678   // We interleave the loop in order to expose ILP and reduce the loop overhead.
5679   // There are many micro-architectural considerations that we can't predict
5680   // at this level. For example, frontend pressure (on decode or fetch) due to
5681   // code size, or the number and capabilities of the execution ports.
5682   //
5683   // We use the following heuristics to select the interleave count:
5684   // 1. If the code has reductions, then we interleave to break the cross
5685   // iteration dependency.
5686   // 2. If the loop is really small, then we interleave to reduce the loop
5687   // overhead.
5688   // 3. We don't interleave if we think that we will spill registers to memory
5689   // due to the increased register pressure.
5690 
5691   if (!isScalarEpilogueAllowed())
5692     return 1;
5693 
5694   // We used the distance for the interleave count.
5695   if (Legal->getMaxSafeDepDistBytes() != -1U)
5696     return 1;
5697 
5698   auto BestKnownTC = getSmallBestKnownTC(*PSE.getSE(), TheLoop);
5699   const bool HasReductions = !Legal->getReductionVars().empty();
5700   // Do not interleave loops with a relatively small known or estimated trip
5701   // count. But we will interleave when InterleaveSmallLoopScalarReduction is
5702   // enabled, and the code has scalar reductions(HasReductions && VF = 1),
5703   // because with the above conditions interleaving can expose ILP and break
5704   // cross iteration dependences for reductions.
5705   if (BestKnownTC && (*BestKnownTC < TinyTripCountInterleaveThreshold) &&
5706       !(InterleaveSmallLoopScalarReduction && HasReductions && VF.isScalar()))
5707     return 1;
5708 
5709   // If we did not calculate the cost for VF (because the user selected the VF)
5710   // then we calculate the cost of VF here.
5711   if (LoopCost == 0) {
5712     InstructionCost C = expectedCost(VF).first;
5713     assert(C.isValid() && "Expected to have chosen a VF with valid cost");
5714     LoopCost = *C.getValue();
5715 
5716     // Loop body is free and there is no need for interleaving.
5717     if (LoopCost == 0)
5718       return 1;
5719   }
5720 
5721   RegisterUsage R = calculateRegisterUsage({VF})[0];
5722   // We divide by these constants so assume that we have at least one
5723   // instruction that uses at least one register.
5724   for (auto& pair : R.MaxLocalUsers) {
5725     pair.second = std::max(pair.second, 1U);
5726   }
5727 
5728   // We calculate the interleave count using the following formula.
5729   // Subtract the number of loop invariants from the number of available
5730   // registers. These registers are used by all of the interleaved instances.
5731   // Next, divide the remaining registers by the number of registers that is
5732   // required by the loop, in order to estimate how many parallel instances
5733   // fit without causing spills. All of this is rounded down if necessary to be
5734   // a power of two. We want power of two interleave count to simplify any
5735   // addressing operations or alignment considerations.
5736   // We also want power of two interleave counts to ensure that the induction
5737   // variable of the vector loop wraps to zero, when tail is folded by masking;
5738   // this currently happens when OptForSize, in which case IC is set to 1 above.
5739   unsigned IC = UINT_MAX;
5740 
5741   for (auto& pair : R.MaxLocalUsers) {
5742     unsigned TargetNumRegisters = TTI.getNumberOfRegisters(pair.first);
5743     LLVM_DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters
5744                       << " registers of "
5745                       << TTI.getRegisterClassName(pair.first) << " register class\n");
5746     if (VF.isScalar()) {
5747       if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
5748         TargetNumRegisters = ForceTargetNumScalarRegs;
5749     } else {
5750       if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
5751         TargetNumRegisters = ForceTargetNumVectorRegs;
5752     }
5753     unsigned MaxLocalUsers = pair.second;
5754     unsigned LoopInvariantRegs = 0;
5755     if (R.LoopInvariantRegs.find(pair.first) != R.LoopInvariantRegs.end())
5756       LoopInvariantRegs = R.LoopInvariantRegs[pair.first];
5757 
5758     unsigned TmpIC = PowerOf2Floor((TargetNumRegisters - LoopInvariantRegs) / MaxLocalUsers);
5759     // Don't count the induction variable as interleaved.
5760     if (EnableIndVarRegisterHeur) {
5761       TmpIC =
5762           PowerOf2Floor((TargetNumRegisters - LoopInvariantRegs - 1) /
5763                         std::max(1U, (MaxLocalUsers - 1)));
5764     }
5765 
5766     IC = std::min(IC, TmpIC);
5767   }
5768 
5769   // Clamp the interleave ranges to reasonable counts.
5770   unsigned MaxInterleaveCount =
5771       TTI.getMaxInterleaveFactor(VF.getKnownMinValue());
5772 
5773   // Check if the user has overridden the max.
5774   if (VF.isScalar()) {
5775     if (ForceTargetMaxScalarInterleaveFactor.getNumOccurrences() > 0)
5776       MaxInterleaveCount = ForceTargetMaxScalarInterleaveFactor;
5777   } else {
5778     if (ForceTargetMaxVectorInterleaveFactor.getNumOccurrences() > 0)
5779       MaxInterleaveCount = ForceTargetMaxVectorInterleaveFactor;
5780   }
5781 
5782   // If trip count is known or estimated compile time constant, limit the
5783   // interleave count to be less than the trip count divided by VF, provided it
5784   // is at least 1.
5785   //
5786   // For scalable vectors we can't know if interleaving is beneficial. It may
5787   // not be beneficial for small loops if none of the lanes in the second vector
5788   // iterations is enabled. However, for larger loops, there is likely to be a
5789   // similar benefit as for fixed-width vectors. For now, we choose to leave
5790   // the InterleaveCount as if vscale is '1', although if some information about
5791   // the vector is known (e.g. min vector size), we can make a better decision.
5792   if (BestKnownTC) {
5793     MaxInterleaveCount =
5794         std::min(*BestKnownTC / VF.getKnownMinValue(), MaxInterleaveCount);
5795     // Make sure MaxInterleaveCount is greater than 0.
5796     MaxInterleaveCount = std::max(1u, MaxInterleaveCount);
5797   }
5798 
5799   assert(MaxInterleaveCount > 0 &&
5800          "Maximum interleave count must be greater than 0");
5801 
5802   // Clamp the calculated IC to be between the 1 and the max interleave count
5803   // that the target and trip count allows.
5804   if (IC > MaxInterleaveCount)
5805     IC = MaxInterleaveCount;
5806   else
5807     // Make sure IC is greater than 0.
5808     IC = std::max(1u, IC);
5809 
5810   assert(IC > 0 && "Interleave count must be greater than 0.");
5811 
5812   // Interleave if we vectorized this loop and there is a reduction that could
5813   // benefit from interleaving.
5814   if (VF.isVector() && HasReductions) {
5815     LLVM_DEBUG(dbgs() << "LV: Interleaving because of reductions.\n");
5816     return IC;
5817   }
5818 
5819   // For any scalar loop that either requires runtime checks or predication we
5820   // are better off leaving this to the unroller. Note that if we've already
5821   // vectorized the loop we will have done the runtime check and so interleaving
5822   // won't require further checks.
5823   bool ScalarInterleavingRequiresPredication =
5824       (VF.isScalar() && any_of(TheLoop->blocks(), [this](BasicBlock *BB) {
5825          return Legal->blockNeedsPredication(BB);
5826        }));
5827   bool ScalarInterleavingRequiresRuntimePointerCheck =
5828       (VF.isScalar() && Legal->getRuntimePointerChecking()->Need);
5829 
5830   // We want to interleave small loops in order to reduce the loop overhead and
5831   // potentially expose ILP opportunities.
5832   LLVM_DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n'
5833                     << "LV: IC is " << IC << '\n'
5834                     << "LV: VF is " << VF << '\n');
5835   const bool AggressivelyInterleaveReductions =
5836       TTI.enableAggressiveInterleaving(HasReductions);
5837   if (!ScalarInterleavingRequiresRuntimePointerCheck &&
5838       !ScalarInterleavingRequiresPredication && LoopCost < SmallLoopCost) {
5839     // We assume that the cost overhead is 1 and we use the cost model
5840     // to estimate the cost of the loop and interleave until the cost of the
5841     // loop overhead is about 5% of the cost of the loop.
5842     unsigned SmallIC =
5843         std::min(IC, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost));
5844 
5845     // Interleave until store/load ports (estimated by max interleave count) are
5846     // saturated.
5847     unsigned NumStores = Legal->getNumStores();
5848     unsigned NumLoads = Legal->getNumLoads();
5849     unsigned StoresIC = IC / (NumStores ? NumStores : 1);
5850     unsigned LoadsIC = IC / (NumLoads ? NumLoads : 1);
5851 
5852     // There is little point in interleaving for reductions containing selects
5853     // and compares when VF=1 since it may just create more overhead than it's
5854     // worth for loops with small trip counts. This is because we still have to
5855     // do the final reduction after the loop.
5856     bool HasSelectCmpReductions =
5857         HasReductions &&
5858         any_of(Legal->getReductionVars(), [&](auto &Reduction) -> bool {
5859           const RecurrenceDescriptor &RdxDesc = Reduction.second;
5860           return RecurrenceDescriptor::isSelectCmpRecurrenceKind(
5861               RdxDesc.getRecurrenceKind());
5862         });
5863     if (HasSelectCmpReductions) {
5864       LLVM_DEBUG(dbgs() << "LV: Not interleaving select-cmp reductions.\n");
5865       return 1;
5866     }
5867 
5868     // If we have a scalar reduction (vector reductions are already dealt with
5869     // by this point), we can increase the critical path length if the loop
5870     // we're interleaving is inside another loop. For tree-wise reductions
5871     // set the limit to 2, and for ordered reductions it's best to disable
5872     // interleaving entirely.
5873     if (HasReductions && TheLoop->getLoopDepth() > 1) {
5874       bool HasOrderedReductions =
5875           any_of(Legal->getReductionVars(), [&](auto &Reduction) -> bool {
5876             const RecurrenceDescriptor &RdxDesc = Reduction.second;
5877             return RdxDesc.isOrdered();
5878           });
5879       if (HasOrderedReductions) {
5880         LLVM_DEBUG(
5881             dbgs() << "LV: Not interleaving scalar ordered reductions.\n");
5882         return 1;
5883       }
5884 
5885       unsigned F = static_cast<unsigned>(MaxNestedScalarReductionIC);
5886       SmallIC = std::min(SmallIC, F);
5887       StoresIC = std::min(StoresIC, F);
5888       LoadsIC = std::min(LoadsIC, F);
5889     }
5890 
5891     if (EnableLoadStoreRuntimeInterleave &&
5892         std::max(StoresIC, LoadsIC) > SmallIC) {
5893       LLVM_DEBUG(
5894           dbgs() << "LV: Interleaving to saturate store or load ports.\n");
5895       return std::max(StoresIC, LoadsIC);
5896     }
5897 
5898     // If there are scalar reductions and TTI has enabled aggressive
5899     // interleaving for reductions, we will interleave to expose ILP.
5900     if (InterleaveSmallLoopScalarReduction && VF.isScalar() &&
5901         AggressivelyInterleaveReductions) {
5902       LLVM_DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
5903       // Interleave no less than SmallIC but not as aggressive as the normal IC
5904       // to satisfy the rare situation when resources are too limited.
5905       return std::max(IC / 2, SmallIC);
5906     } else {
5907       LLVM_DEBUG(dbgs() << "LV: Interleaving to reduce branch cost.\n");
5908       return SmallIC;
5909     }
5910   }
5911 
5912   // Interleave if this is a large loop (small loops are already dealt with by
5913   // this point) that could benefit from interleaving.
5914   if (AggressivelyInterleaveReductions) {
5915     LLVM_DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
5916     return IC;
5917   }
5918 
5919   LLVM_DEBUG(dbgs() << "LV: Not Interleaving.\n");
5920   return 1;
5921 }
5922 
5923 SmallVector<LoopVectorizationCostModel::RegisterUsage, 8>
5924 LoopVectorizationCostModel::calculateRegisterUsage(ArrayRef<ElementCount> VFs) {
5925   // This function calculates the register usage by measuring the highest number
5926   // of values that are alive at a single location. Obviously, this is a very
5927   // rough estimation. We scan the loop in a topological order in order and
5928   // assign a number to each instruction. We use RPO to ensure that defs are
5929   // met before their users. We assume that each instruction that has in-loop
5930   // users starts an interval. We record every time that an in-loop value is
5931   // used, so we have a list of the first and last occurrences of each
5932   // instruction. Next, we transpose this data structure into a multi map that
5933   // holds the list of intervals that *end* at a specific location. This multi
5934   // map allows us to perform a linear search. We scan the instructions linearly
5935   // and record each time that a new interval starts, by placing it in a set.
5936   // If we find this value in the multi-map then we remove it from the set.
5937   // The max register usage is the maximum size of the set.
5938   // We also search for instructions that are defined outside the loop, but are
5939   // used inside the loop. We need this number separately from the max-interval
5940   // usage number because when we unroll, loop-invariant values do not take
5941   // more register.
5942   LoopBlocksDFS DFS(TheLoop);
5943   DFS.perform(LI);
5944 
5945   RegisterUsage RU;
5946 
5947   // Each 'key' in the map opens a new interval. The values
5948   // of the map are the index of the 'last seen' usage of the
5949   // instruction that is the key.
5950   using IntervalMap = DenseMap<Instruction *, unsigned>;
5951 
5952   // Maps instruction to its index.
5953   SmallVector<Instruction *, 64> IdxToInstr;
5954   // Marks the end of each interval.
5955   IntervalMap EndPoint;
5956   // Saves the list of instruction indices that are used in the loop.
5957   SmallPtrSet<Instruction *, 8> Ends;
5958   // Saves the list of values that are used in the loop but are
5959   // defined outside the loop, such as arguments and constants.
5960   SmallPtrSet<Value *, 8> LoopInvariants;
5961 
5962   for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) {
5963     for (Instruction &I : BB->instructionsWithoutDebug()) {
5964       IdxToInstr.push_back(&I);
5965 
5966       // Save the end location of each USE.
5967       for (Value *U : I.operands()) {
5968         auto *Instr = dyn_cast<Instruction>(U);
5969 
5970         // Ignore non-instruction values such as arguments, constants, etc.
5971         if (!Instr)
5972           continue;
5973 
5974         // If this instruction is outside the loop then record it and continue.
5975         if (!TheLoop->contains(Instr)) {
5976           LoopInvariants.insert(Instr);
5977           continue;
5978         }
5979 
5980         // Overwrite previous end points.
5981         EndPoint[Instr] = IdxToInstr.size();
5982         Ends.insert(Instr);
5983       }
5984     }
5985   }
5986 
5987   // Saves the list of intervals that end with the index in 'key'.
5988   using InstrList = SmallVector<Instruction *, 2>;
5989   DenseMap<unsigned, InstrList> TransposeEnds;
5990 
5991   // Transpose the EndPoints to a list of values that end at each index.
5992   for (auto &Interval : EndPoint)
5993     TransposeEnds[Interval.second].push_back(Interval.first);
5994 
5995   SmallPtrSet<Instruction *, 8> OpenIntervals;
5996   SmallVector<RegisterUsage, 8> RUs(VFs.size());
5997   SmallVector<SmallMapVector<unsigned, unsigned, 4>, 8> MaxUsages(VFs.size());
5998 
5999   LLVM_DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
6000 
6001   // A lambda that gets the register usage for the given type and VF.
6002   const auto &TTICapture = TTI;
6003   auto GetRegUsage = [&TTICapture](Type *Ty, ElementCount VF) -> unsigned {
6004     if (Ty->isTokenTy() || !VectorType::isValidElementType(Ty))
6005       return 0;
6006     InstructionCost::CostType RegUsage =
6007         *TTICapture.getRegUsageForType(VectorType::get(Ty, VF)).getValue();
6008     assert(RegUsage >= 0 && RegUsage <= std::numeric_limits<unsigned>::max() &&
6009            "Nonsensical values for register usage.");
6010     return RegUsage;
6011   };
6012 
6013   for (unsigned int i = 0, s = IdxToInstr.size(); i < s; ++i) {
6014     Instruction *I = IdxToInstr[i];
6015 
6016     // Remove all of the instructions that end at this location.
6017     InstrList &List = TransposeEnds[i];
6018     for (Instruction *ToRemove : List)
6019       OpenIntervals.erase(ToRemove);
6020 
6021     // Ignore instructions that are never used within the loop.
6022     if (!Ends.count(I))
6023       continue;
6024 
6025     // Skip ignored values.
6026     if (ValuesToIgnore.count(I))
6027       continue;
6028 
6029     // For each VF find the maximum usage of registers.
6030     for (unsigned j = 0, e = VFs.size(); j < e; ++j) {
6031       // Count the number of live intervals.
6032       SmallMapVector<unsigned, unsigned, 4> RegUsage;
6033 
6034       if (VFs[j].isScalar()) {
6035         for (auto Inst : OpenIntervals) {
6036           unsigned ClassID = TTI.getRegisterClassForType(false, Inst->getType());
6037           if (RegUsage.find(ClassID) == RegUsage.end())
6038             RegUsage[ClassID] = 1;
6039           else
6040             RegUsage[ClassID] += 1;
6041         }
6042       } else {
6043         collectUniformsAndScalars(VFs[j]);
6044         for (auto Inst : OpenIntervals) {
6045           // Skip ignored values for VF > 1.
6046           if (VecValuesToIgnore.count(Inst))
6047             continue;
6048           if (isScalarAfterVectorization(Inst, VFs[j])) {
6049             unsigned ClassID = TTI.getRegisterClassForType(false, Inst->getType());
6050             if (RegUsage.find(ClassID) == RegUsage.end())
6051               RegUsage[ClassID] = 1;
6052             else
6053               RegUsage[ClassID] += 1;
6054           } else {
6055             unsigned ClassID = TTI.getRegisterClassForType(true, Inst->getType());
6056             if (RegUsage.find(ClassID) == RegUsage.end())
6057               RegUsage[ClassID] = GetRegUsage(Inst->getType(), VFs[j]);
6058             else
6059               RegUsage[ClassID] += GetRegUsage(Inst->getType(), VFs[j]);
6060           }
6061         }
6062       }
6063 
6064       for (auto& pair : RegUsage) {
6065         if (MaxUsages[j].find(pair.first) != MaxUsages[j].end())
6066           MaxUsages[j][pair.first] = std::max(MaxUsages[j][pair.first], pair.second);
6067         else
6068           MaxUsages[j][pair.first] = pair.second;
6069       }
6070     }
6071 
6072     LLVM_DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # "
6073                       << OpenIntervals.size() << '\n');
6074 
6075     // Add the current instruction to the list of open intervals.
6076     OpenIntervals.insert(I);
6077   }
6078 
6079   for (unsigned i = 0, e = VFs.size(); i < e; ++i) {
6080     SmallMapVector<unsigned, unsigned, 4> Invariant;
6081 
6082     for (auto Inst : LoopInvariants) {
6083       unsigned Usage =
6084           VFs[i].isScalar() ? 1 : GetRegUsage(Inst->getType(), VFs[i]);
6085       unsigned ClassID =
6086           TTI.getRegisterClassForType(VFs[i].isVector(), Inst->getType());
6087       if (Invariant.find(ClassID) == Invariant.end())
6088         Invariant[ClassID] = Usage;
6089       else
6090         Invariant[ClassID] += Usage;
6091     }
6092 
6093     LLVM_DEBUG({
6094       dbgs() << "LV(REG): VF = " << VFs[i] << '\n';
6095       dbgs() << "LV(REG): Found max usage: " << MaxUsages[i].size()
6096              << " item\n";
6097       for (const auto &pair : MaxUsages[i]) {
6098         dbgs() << "LV(REG): RegisterClass: "
6099                << TTI.getRegisterClassName(pair.first) << ", " << pair.second
6100                << " registers\n";
6101       }
6102       dbgs() << "LV(REG): Found invariant usage: " << Invariant.size()
6103              << " item\n";
6104       for (const auto &pair : Invariant) {
6105         dbgs() << "LV(REG): RegisterClass: "
6106                << TTI.getRegisterClassName(pair.first) << ", " << pair.second
6107                << " registers\n";
6108       }
6109     });
6110 
6111     RU.LoopInvariantRegs = Invariant;
6112     RU.MaxLocalUsers = MaxUsages[i];
6113     RUs[i] = RU;
6114   }
6115 
6116   return RUs;
6117 }
6118 
6119 bool LoopVectorizationCostModel::useEmulatedMaskMemRefHack(Instruction *I,
6120                                                            ElementCount VF) {
6121   // TODO: Cost model for emulated masked load/store is completely
6122   // broken. This hack guides the cost model to use an artificially
6123   // high enough value to practically disable vectorization with such
6124   // operations, except where previously deployed legality hack allowed
6125   // using very low cost values. This is to avoid regressions coming simply
6126   // from moving "masked load/store" check from legality to cost model.
6127   // Masked Load/Gather emulation was previously never allowed.
6128   // Limited number of Masked Store/Scatter emulation was allowed.
6129   assert(isPredicatedInst(I, VF) && "Expecting a scalar emulated instruction");
6130   return isa<LoadInst>(I) ||
6131          (isa<StoreInst>(I) &&
6132           NumPredStores > NumberOfStoresToPredicate);
6133 }
6134 
6135 void LoopVectorizationCostModel::collectInstsToScalarize(ElementCount VF) {
6136   // If we aren't vectorizing the loop, or if we've already collected the
6137   // instructions to scalarize, there's nothing to do. Collection may already
6138   // have occurred if we have a user-selected VF and are now computing the
6139   // expected cost for interleaving.
6140   if (VF.isScalar() || VF.isZero() ||
6141       InstsToScalarize.find(VF) != InstsToScalarize.end())
6142     return;
6143 
6144   // Initialize a mapping for VF in InstsToScalalarize. If we find that it's
6145   // not profitable to scalarize any instructions, the presence of VF in the
6146   // map will indicate that we've analyzed it already.
6147   ScalarCostsTy &ScalarCostsVF = InstsToScalarize[VF];
6148 
6149   // Find all the instructions that are scalar with predication in the loop and
6150   // determine if it would be better to not if-convert the blocks they are in.
6151   // If so, we also record the instructions to scalarize.
6152   for (BasicBlock *BB : TheLoop->blocks()) {
6153     if (!blockNeedsPredicationForAnyReason(BB))
6154       continue;
6155     for (Instruction &I : *BB)
6156       if (isScalarWithPredication(&I, VF)) {
6157         ScalarCostsTy ScalarCosts;
6158         // Do not apply discount if scalable, because that would lead to
6159         // invalid scalarization costs.
6160         // Do not apply discount logic if hacked cost is needed
6161         // for emulated masked memrefs.
6162         if (!VF.isScalable() && !useEmulatedMaskMemRefHack(&I, VF) &&
6163             computePredInstDiscount(&I, ScalarCosts, VF) >= 0)
6164           ScalarCostsVF.insert(ScalarCosts.begin(), ScalarCosts.end());
6165         // Remember that BB will remain after vectorization.
6166         PredicatedBBsAfterVectorization.insert(BB);
6167       }
6168   }
6169 }
6170 
6171 int LoopVectorizationCostModel::computePredInstDiscount(
6172     Instruction *PredInst, ScalarCostsTy &ScalarCosts, ElementCount VF) {
6173   assert(!isUniformAfterVectorization(PredInst, VF) &&
6174          "Instruction marked uniform-after-vectorization will be predicated");
6175 
6176   // Initialize the discount to zero, meaning that the scalar version and the
6177   // vector version cost the same.
6178   InstructionCost Discount = 0;
6179 
6180   // Holds instructions to analyze. The instructions we visit are mapped in
6181   // ScalarCosts. Those instructions are the ones that would be scalarized if
6182   // we find that the scalar version costs less.
6183   SmallVector<Instruction *, 8> Worklist;
6184 
6185   // Returns true if the given instruction can be scalarized.
6186   auto canBeScalarized = [&](Instruction *I) -> bool {
6187     // We only attempt to scalarize instructions forming a single-use chain
6188     // from the original predicated block that would otherwise be vectorized.
6189     // Although not strictly necessary, we give up on instructions we know will
6190     // already be scalar to avoid traversing chains that are unlikely to be
6191     // beneficial.
6192     if (!I->hasOneUse() || PredInst->getParent() != I->getParent() ||
6193         isScalarAfterVectorization(I, VF))
6194       return false;
6195 
6196     // If the instruction is scalar with predication, it will be analyzed
6197     // separately. We ignore it within the context of PredInst.
6198     if (isScalarWithPredication(I, VF))
6199       return false;
6200 
6201     // If any of the instruction's operands are uniform after vectorization,
6202     // the instruction cannot be scalarized. This prevents, for example, a
6203     // masked load from being scalarized.
6204     //
6205     // We assume we will only emit a value for lane zero of an instruction
6206     // marked uniform after vectorization, rather than VF identical values.
6207     // Thus, if we scalarize an instruction that uses a uniform, we would
6208     // create uses of values corresponding to the lanes we aren't emitting code
6209     // for. This behavior can be changed by allowing getScalarValue to clone
6210     // the lane zero values for uniforms rather than asserting.
6211     for (Use &U : I->operands())
6212       if (auto *J = dyn_cast<Instruction>(U.get()))
6213         if (isUniformAfterVectorization(J, VF))
6214           return false;
6215 
6216     // Otherwise, we can scalarize the instruction.
6217     return true;
6218   };
6219 
6220   // Compute the expected cost discount from scalarizing the entire expression
6221   // feeding the predicated instruction. We currently only consider expressions
6222   // that are single-use instruction chains.
6223   Worklist.push_back(PredInst);
6224   while (!Worklist.empty()) {
6225     Instruction *I = Worklist.pop_back_val();
6226 
6227     // If we've already analyzed the instruction, there's nothing to do.
6228     if (ScalarCosts.find(I) != ScalarCosts.end())
6229       continue;
6230 
6231     // Compute the cost of the vector instruction. Note that this cost already
6232     // includes the scalarization overhead of the predicated instruction.
6233     InstructionCost VectorCost = getInstructionCost(I, VF).first;
6234 
6235     // Compute the cost of the scalarized instruction. This cost is the cost of
6236     // the instruction as if it wasn't if-converted and instead remained in the
6237     // predicated block. We will scale this cost by block probability after
6238     // computing the scalarization overhead.
6239     InstructionCost ScalarCost =
6240         VF.getFixedValue() *
6241         getInstructionCost(I, ElementCount::getFixed(1)).first;
6242 
6243     // Compute the scalarization overhead of needed insertelement instructions
6244     // and phi nodes.
6245     if (isScalarWithPredication(I, VF) && !I->getType()->isVoidTy()) {
6246       ScalarCost += TTI.getScalarizationOverhead(
6247           cast<VectorType>(ToVectorTy(I->getType(), VF)),
6248           APInt::getAllOnes(VF.getFixedValue()), true, false);
6249       ScalarCost +=
6250           VF.getFixedValue() *
6251           TTI.getCFInstrCost(Instruction::PHI, TTI::TCK_RecipThroughput);
6252     }
6253 
6254     // Compute the scalarization overhead of needed extractelement
6255     // instructions. For each of the instruction's operands, if the operand can
6256     // be scalarized, add it to the worklist; otherwise, account for the
6257     // overhead.
6258     for (Use &U : I->operands())
6259       if (auto *J = dyn_cast<Instruction>(U.get())) {
6260         assert(VectorType::isValidElementType(J->getType()) &&
6261                "Instruction has non-scalar type");
6262         if (canBeScalarized(J))
6263           Worklist.push_back(J);
6264         else if (needsExtract(J, VF)) {
6265           ScalarCost += TTI.getScalarizationOverhead(
6266               cast<VectorType>(ToVectorTy(J->getType(), VF)),
6267               APInt::getAllOnes(VF.getFixedValue()), false, true);
6268         }
6269       }
6270 
6271     // Scale the total scalar cost by block probability.
6272     ScalarCost /= getReciprocalPredBlockProb();
6273 
6274     // Compute the discount. A non-negative discount means the vector version
6275     // of the instruction costs more, and scalarizing would be beneficial.
6276     Discount += VectorCost - ScalarCost;
6277     ScalarCosts[I] = ScalarCost;
6278   }
6279 
6280   return *Discount.getValue();
6281 }
6282 
6283 LoopVectorizationCostModel::VectorizationCostTy
6284 LoopVectorizationCostModel::expectedCost(
6285     ElementCount VF, SmallVectorImpl<InstructionVFPair> *Invalid) {
6286   VectorizationCostTy Cost;
6287 
6288   // For each block.
6289   for (BasicBlock *BB : TheLoop->blocks()) {
6290     VectorizationCostTy BlockCost;
6291 
6292     // For each instruction in the old loop.
6293     for (Instruction &I : BB->instructionsWithoutDebug()) {
6294       // Skip ignored values.
6295       if (ValuesToIgnore.count(&I) ||
6296           (VF.isVector() && VecValuesToIgnore.count(&I)))
6297         continue;
6298 
6299       VectorizationCostTy C = getInstructionCost(&I, VF);
6300 
6301       // Check if we should override the cost.
6302       if (C.first.isValid() &&
6303           ForceTargetInstructionCost.getNumOccurrences() > 0)
6304         C.first = InstructionCost(ForceTargetInstructionCost);
6305 
6306       // Keep a list of instructions with invalid costs.
6307       if (Invalid && !C.first.isValid())
6308         Invalid->emplace_back(&I, VF);
6309 
6310       BlockCost.first += C.first;
6311       BlockCost.second |= C.second;
6312       LLVM_DEBUG(dbgs() << "LV: Found an estimated cost of " << C.first
6313                         << " for VF " << VF << " For instruction: " << I
6314                         << '\n');
6315     }
6316 
6317     // If we are vectorizing a predicated block, it will have been
6318     // if-converted. This means that the block's instructions (aside from
6319     // stores and instructions that may divide by zero) will now be
6320     // unconditionally executed. For the scalar case, we may not always execute
6321     // the predicated block, if it is an if-else block. Thus, scale the block's
6322     // cost by the probability of executing it. blockNeedsPredication from
6323     // Legal is used so as to not include all blocks in tail folded loops.
6324     if (VF.isScalar() && Legal->blockNeedsPredication(BB))
6325       BlockCost.first /= getReciprocalPredBlockProb();
6326 
6327     Cost.first += BlockCost.first;
6328     Cost.second |= BlockCost.second;
6329   }
6330 
6331   return Cost;
6332 }
6333 
6334 /// Gets Address Access SCEV after verifying that the access pattern
6335 /// is loop invariant except the induction variable dependence.
6336 ///
6337 /// This SCEV can be sent to the Target in order to estimate the address
6338 /// calculation cost.
6339 static const SCEV *getAddressAccessSCEV(
6340               Value *Ptr,
6341               LoopVectorizationLegality *Legal,
6342               PredicatedScalarEvolution &PSE,
6343               const Loop *TheLoop) {
6344 
6345   auto *Gep = dyn_cast<GetElementPtrInst>(Ptr);
6346   if (!Gep)
6347     return nullptr;
6348 
6349   // We are looking for a gep with all loop invariant indices except for one
6350   // which should be an induction variable.
6351   auto SE = PSE.getSE();
6352   unsigned NumOperands = Gep->getNumOperands();
6353   for (unsigned i = 1; i < NumOperands; ++i) {
6354     Value *Opd = Gep->getOperand(i);
6355     if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
6356         !Legal->isInductionVariable(Opd))
6357       return nullptr;
6358   }
6359 
6360   // Now we know we have a GEP ptr, %inv, %ind, %inv. return the Ptr SCEV.
6361   return PSE.getSCEV(Ptr);
6362 }
6363 
6364 static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
6365   return Legal->hasStride(I->getOperand(0)) ||
6366          Legal->hasStride(I->getOperand(1));
6367 }
6368 
6369 InstructionCost
6370 LoopVectorizationCostModel::getMemInstScalarizationCost(Instruction *I,
6371                                                         ElementCount VF) {
6372   assert(VF.isVector() &&
6373          "Scalarization cost of instruction implies vectorization.");
6374   if (VF.isScalable())
6375     return InstructionCost::getInvalid();
6376 
6377   Type *ValTy = getLoadStoreType(I);
6378   auto SE = PSE.getSE();
6379 
6380   unsigned AS = getLoadStoreAddressSpace(I);
6381   Value *Ptr = getLoadStorePointerOperand(I);
6382   Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
6383   // NOTE: PtrTy is a vector to signal `TTI::getAddressComputationCost`
6384   //       that it is being called from this specific place.
6385 
6386   // Figure out whether the access is strided and get the stride value
6387   // if it's known in compile time
6388   const SCEV *PtrSCEV = getAddressAccessSCEV(Ptr, Legal, PSE, TheLoop);
6389 
6390   // Get the cost of the scalar memory instruction and address computation.
6391   InstructionCost Cost =
6392       VF.getKnownMinValue() * TTI.getAddressComputationCost(PtrTy, SE, PtrSCEV);
6393 
6394   // Don't pass *I here, since it is scalar but will actually be part of a
6395   // vectorized loop where the user of it is a vectorized instruction.
6396   const Align Alignment = getLoadStoreAlignment(I);
6397   Cost += VF.getKnownMinValue() *
6398           TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(), Alignment,
6399                               AS, TTI::TCK_RecipThroughput);
6400 
6401   // Get the overhead of the extractelement and insertelement instructions
6402   // we might create due to scalarization.
6403   Cost += getScalarizationOverhead(I, VF);
6404 
6405   // If we have a predicated load/store, it will need extra i1 extracts and
6406   // conditional branches, but may not be executed for each vector lane. Scale
6407   // the cost by the probability of executing the predicated block.
6408   if (isPredicatedInst(I, VF)) {
6409     Cost /= getReciprocalPredBlockProb();
6410 
6411     // Add the cost of an i1 extract and a branch
6412     auto *Vec_i1Ty =
6413         VectorType::get(IntegerType::getInt1Ty(ValTy->getContext()), VF);
6414     Cost += TTI.getScalarizationOverhead(
6415         Vec_i1Ty, APInt::getAllOnes(VF.getKnownMinValue()),
6416         /*Insert=*/false, /*Extract=*/true);
6417     Cost += TTI.getCFInstrCost(Instruction::Br, TTI::TCK_RecipThroughput);
6418 
6419     if (useEmulatedMaskMemRefHack(I, VF))
6420       // Artificially setting to a high enough value to practically disable
6421       // vectorization with such operations.
6422       Cost = 3000000;
6423   }
6424 
6425   return Cost;
6426 }
6427 
6428 InstructionCost
6429 LoopVectorizationCostModel::getConsecutiveMemOpCost(Instruction *I,
6430                                                     ElementCount VF) {
6431   Type *ValTy = getLoadStoreType(I);
6432   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
6433   Value *Ptr = getLoadStorePointerOperand(I);
6434   unsigned AS = getLoadStoreAddressSpace(I);
6435   int ConsecutiveStride = Legal->isConsecutivePtr(ValTy, Ptr);
6436   enum TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
6437 
6438   assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
6439          "Stride should be 1 or -1 for consecutive memory access");
6440   const Align Alignment = getLoadStoreAlignment(I);
6441   InstructionCost Cost = 0;
6442   if (Legal->isMaskRequired(I))
6443     Cost += TTI.getMaskedMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS,
6444                                       CostKind);
6445   else
6446     Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS,
6447                                 CostKind, I);
6448 
6449   bool Reverse = ConsecutiveStride < 0;
6450   if (Reverse)
6451     Cost +=
6452         TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, None, 0);
6453   return Cost;
6454 }
6455 
6456 InstructionCost
6457 LoopVectorizationCostModel::getUniformMemOpCost(Instruction *I,
6458                                                 ElementCount VF) {
6459   assert(Legal->isUniformMemOp(*I));
6460 
6461   Type *ValTy = getLoadStoreType(I);
6462   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
6463   const Align Alignment = getLoadStoreAlignment(I);
6464   unsigned AS = getLoadStoreAddressSpace(I);
6465   enum TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
6466   if (isa<LoadInst>(I)) {
6467     return TTI.getAddressComputationCost(ValTy) +
6468            TTI.getMemoryOpCost(Instruction::Load, ValTy, Alignment, AS,
6469                                CostKind) +
6470            TTI.getShuffleCost(TargetTransformInfo::SK_Broadcast, VectorTy);
6471   }
6472   StoreInst *SI = cast<StoreInst>(I);
6473 
6474   bool isLoopInvariantStoreValue = Legal->isUniform(SI->getValueOperand());
6475   return TTI.getAddressComputationCost(ValTy) +
6476          TTI.getMemoryOpCost(Instruction::Store, ValTy, Alignment, AS,
6477                              CostKind) +
6478          (isLoopInvariantStoreValue
6479               ? 0
6480               : TTI.getVectorInstrCost(Instruction::ExtractElement, VectorTy,
6481                                        VF.getKnownMinValue() - 1));
6482 }
6483 
6484 InstructionCost
6485 LoopVectorizationCostModel::getGatherScatterCost(Instruction *I,
6486                                                  ElementCount VF) {
6487   Type *ValTy = getLoadStoreType(I);
6488   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
6489   const Align Alignment = getLoadStoreAlignment(I);
6490   const Value *Ptr = getLoadStorePointerOperand(I);
6491 
6492   return TTI.getAddressComputationCost(VectorTy) +
6493          TTI.getGatherScatterOpCost(
6494              I->getOpcode(), VectorTy, Ptr, Legal->isMaskRequired(I), Alignment,
6495              TargetTransformInfo::TCK_RecipThroughput, I);
6496 }
6497 
6498 InstructionCost
6499 LoopVectorizationCostModel::getInterleaveGroupCost(Instruction *I,
6500                                                    ElementCount VF) {
6501   // TODO: Once we have support for interleaving with scalable vectors
6502   // we can calculate the cost properly here.
6503   if (VF.isScalable())
6504     return InstructionCost::getInvalid();
6505 
6506   Type *ValTy = getLoadStoreType(I);
6507   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
6508   unsigned AS = getLoadStoreAddressSpace(I);
6509 
6510   auto Group = getInterleavedAccessGroup(I);
6511   assert(Group && "Fail to get an interleaved access group.");
6512 
6513   unsigned InterleaveFactor = Group->getFactor();
6514   auto *WideVecTy = VectorType::get(ValTy, VF * InterleaveFactor);
6515 
6516   // Holds the indices of existing members in the interleaved group.
6517   SmallVector<unsigned, 4> Indices;
6518   for (unsigned IF = 0; IF < InterleaveFactor; IF++)
6519     if (Group->getMember(IF))
6520       Indices.push_back(IF);
6521 
6522   // Calculate the cost of the whole interleaved group.
6523   bool UseMaskForGaps =
6524       (Group->requiresScalarEpilogue() && !isScalarEpilogueAllowed()) ||
6525       (isa<StoreInst>(I) && (Group->getNumMembers() < Group->getFactor()));
6526   InstructionCost Cost = TTI.getInterleavedMemoryOpCost(
6527       I->getOpcode(), WideVecTy, Group->getFactor(), Indices, Group->getAlign(),
6528       AS, TTI::TCK_RecipThroughput, Legal->isMaskRequired(I), UseMaskForGaps);
6529 
6530   if (Group->isReverse()) {
6531     // TODO: Add support for reversed masked interleaved access.
6532     assert(!Legal->isMaskRequired(I) &&
6533            "Reverse masked interleaved access not supported.");
6534     Cost +=
6535         Group->getNumMembers() *
6536         TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, None, 0);
6537   }
6538   return Cost;
6539 }
6540 
6541 Optional<InstructionCost> LoopVectorizationCostModel::getReductionPatternCost(
6542     Instruction *I, ElementCount VF, Type *Ty, TTI::TargetCostKind CostKind) {
6543   using namespace llvm::PatternMatch;
6544   // Early exit for no inloop reductions
6545   if (InLoopReductionChains.empty() || VF.isScalar() || !isa<VectorType>(Ty))
6546     return None;
6547   auto *VectorTy = cast<VectorType>(Ty);
6548 
6549   // We are looking for a pattern of, and finding the minimal acceptable cost:
6550   //  reduce(mul(ext(A), ext(B))) or
6551   //  reduce(mul(A, B)) or
6552   //  reduce(ext(A)) or
6553   //  reduce(A).
6554   // The basic idea is that we walk down the tree to do that, finding the root
6555   // reduction instruction in InLoopReductionImmediateChains. From there we find
6556   // the pattern of mul/ext and test the cost of the entire pattern vs the cost
6557   // of the components. If the reduction cost is lower then we return it for the
6558   // reduction instruction and 0 for the other instructions in the pattern. If
6559   // it is not we return an invalid cost specifying the orignal cost method
6560   // should be used.
6561   Instruction *RetI = I;
6562   if (match(RetI, m_ZExtOrSExt(m_Value()))) {
6563     if (!RetI->hasOneUser())
6564       return None;
6565     RetI = RetI->user_back();
6566   }
6567   if (match(RetI, m_Mul(m_Value(), m_Value())) &&
6568       RetI->user_back()->getOpcode() == Instruction::Add) {
6569     if (!RetI->hasOneUser())
6570       return None;
6571     RetI = RetI->user_back();
6572   }
6573 
6574   // Test if the found instruction is a reduction, and if not return an invalid
6575   // cost specifying the parent to use the original cost modelling.
6576   if (!InLoopReductionImmediateChains.count(RetI))
6577     return None;
6578 
6579   // Find the reduction this chain is a part of and calculate the basic cost of
6580   // the reduction on its own.
6581   Instruction *LastChain = InLoopReductionImmediateChains[RetI];
6582   Instruction *ReductionPhi = LastChain;
6583   while (!isa<PHINode>(ReductionPhi))
6584     ReductionPhi = InLoopReductionImmediateChains[ReductionPhi];
6585 
6586   const RecurrenceDescriptor &RdxDesc =
6587       Legal->getReductionVars().find(cast<PHINode>(ReductionPhi))->second;
6588 
6589   InstructionCost BaseCost = TTI.getArithmeticReductionCost(
6590       RdxDesc.getOpcode(), VectorTy, RdxDesc.getFastMathFlags(), CostKind);
6591 
6592   // For a call to the llvm.fmuladd intrinsic we need to add the cost of a
6593   // normal fmul instruction to the cost of the fadd reduction.
6594   if (RdxDesc.getRecurrenceKind() == RecurKind::FMulAdd)
6595     BaseCost +=
6596         TTI.getArithmeticInstrCost(Instruction::FMul, VectorTy, CostKind);
6597 
6598   // If we're using ordered reductions then we can just return the base cost
6599   // here, since getArithmeticReductionCost calculates the full ordered
6600   // reduction cost when FP reassociation is not allowed.
6601   if (useOrderedReductions(RdxDesc))
6602     return BaseCost;
6603 
6604   // Get the operand that was not the reduction chain and match it to one of the
6605   // patterns, returning the better cost if it is found.
6606   Instruction *RedOp = RetI->getOperand(1) == LastChain
6607                            ? dyn_cast<Instruction>(RetI->getOperand(0))
6608                            : dyn_cast<Instruction>(RetI->getOperand(1));
6609 
6610   VectorTy = VectorType::get(I->getOperand(0)->getType(), VectorTy);
6611 
6612   Instruction *Op0, *Op1;
6613   if (RedOp &&
6614       match(RedOp,
6615             m_ZExtOrSExt(m_Mul(m_Instruction(Op0), m_Instruction(Op1)))) &&
6616       match(Op0, m_ZExtOrSExt(m_Value())) &&
6617       Op0->getOpcode() == Op1->getOpcode() &&
6618       Op0->getOperand(0)->getType() == Op1->getOperand(0)->getType() &&
6619       !TheLoop->isLoopInvariant(Op0) && !TheLoop->isLoopInvariant(Op1) &&
6620       (Op0->getOpcode() == RedOp->getOpcode() || Op0 == Op1)) {
6621 
6622     // Matched reduce(ext(mul(ext(A), ext(B)))
6623     // Note that the extend opcodes need to all match, or if A==B they will have
6624     // been converted to zext(mul(sext(A), sext(A))) as it is known positive,
6625     // which is equally fine.
6626     bool IsUnsigned = isa<ZExtInst>(Op0);
6627     auto *ExtType = VectorType::get(Op0->getOperand(0)->getType(), VectorTy);
6628     auto *MulType = VectorType::get(Op0->getType(), VectorTy);
6629 
6630     InstructionCost ExtCost =
6631         TTI.getCastInstrCost(Op0->getOpcode(), MulType, ExtType,
6632                              TTI::CastContextHint::None, CostKind, Op0);
6633     InstructionCost MulCost =
6634         TTI.getArithmeticInstrCost(Instruction::Mul, MulType, CostKind);
6635     InstructionCost Ext2Cost =
6636         TTI.getCastInstrCost(RedOp->getOpcode(), VectorTy, MulType,
6637                              TTI::CastContextHint::None, CostKind, RedOp);
6638 
6639     InstructionCost RedCost = TTI.getExtendedAddReductionCost(
6640         /*IsMLA=*/true, IsUnsigned, RdxDesc.getRecurrenceType(), ExtType,
6641         CostKind);
6642 
6643     if (RedCost.isValid() &&
6644         RedCost < ExtCost * 2 + MulCost + Ext2Cost + BaseCost)
6645       return I == RetI ? RedCost : 0;
6646   } else if (RedOp && match(RedOp, m_ZExtOrSExt(m_Value())) &&
6647              !TheLoop->isLoopInvariant(RedOp)) {
6648     // Matched reduce(ext(A))
6649     bool IsUnsigned = isa<ZExtInst>(RedOp);
6650     auto *ExtType = VectorType::get(RedOp->getOperand(0)->getType(), VectorTy);
6651     InstructionCost RedCost = TTI.getExtendedAddReductionCost(
6652         /*IsMLA=*/false, IsUnsigned, RdxDesc.getRecurrenceType(), ExtType,
6653         CostKind);
6654 
6655     InstructionCost ExtCost =
6656         TTI.getCastInstrCost(RedOp->getOpcode(), VectorTy, ExtType,
6657                              TTI::CastContextHint::None, CostKind, RedOp);
6658     if (RedCost.isValid() && RedCost < BaseCost + ExtCost)
6659       return I == RetI ? RedCost : 0;
6660   } else if (RedOp &&
6661              match(RedOp, m_Mul(m_Instruction(Op0), m_Instruction(Op1)))) {
6662     if (match(Op0, m_ZExtOrSExt(m_Value())) &&
6663         Op0->getOpcode() == Op1->getOpcode() &&
6664         !TheLoop->isLoopInvariant(Op0) && !TheLoop->isLoopInvariant(Op1)) {
6665       bool IsUnsigned = isa<ZExtInst>(Op0);
6666       Type *Op0Ty = Op0->getOperand(0)->getType();
6667       Type *Op1Ty = Op1->getOperand(0)->getType();
6668       Type *LargestOpTy =
6669           Op0Ty->getIntegerBitWidth() < Op1Ty->getIntegerBitWidth() ? Op1Ty
6670                                                                     : Op0Ty;
6671       auto *ExtType = VectorType::get(LargestOpTy, VectorTy);
6672 
6673       // Matched reduce(mul(ext(A), ext(B))), where the two ext may be of
6674       // different sizes. We take the largest type as the ext to reduce, and add
6675       // the remaining cost as, for example reduce(mul(ext(ext(A)), ext(B))).
6676       InstructionCost ExtCost0 = TTI.getCastInstrCost(
6677           Op0->getOpcode(), VectorTy, VectorType::get(Op0Ty, VectorTy),
6678           TTI::CastContextHint::None, CostKind, Op0);
6679       InstructionCost ExtCost1 = TTI.getCastInstrCost(
6680           Op1->getOpcode(), VectorTy, VectorType::get(Op1Ty, VectorTy),
6681           TTI::CastContextHint::None, CostKind, Op1);
6682       InstructionCost MulCost =
6683           TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy, CostKind);
6684 
6685       InstructionCost RedCost = TTI.getExtendedAddReductionCost(
6686           /*IsMLA=*/true, IsUnsigned, RdxDesc.getRecurrenceType(), ExtType,
6687           CostKind);
6688       InstructionCost ExtraExtCost = 0;
6689       if (Op0Ty != LargestOpTy || Op1Ty != LargestOpTy) {
6690         Instruction *ExtraExtOp = (Op0Ty != LargestOpTy) ? Op0 : Op1;
6691         ExtraExtCost = TTI.getCastInstrCost(
6692             ExtraExtOp->getOpcode(), ExtType,
6693             VectorType::get(ExtraExtOp->getOperand(0)->getType(), VectorTy),
6694             TTI::CastContextHint::None, CostKind, ExtraExtOp);
6695       }
6696 
6697       if (RedCost.isValid() &&
6698           (RedCost + ExtraExtCost) < (ExtCost0 + ExtCost1 + MulCost + BaseCost))
6699         return I == RetI ? RedCost : 0;
6700     } else if (!match(I, m_ZExtOrSExt(m_Value()))) {
6701       // Matched reduce(mul())
6702       InstructionCost MulCost =
6703           TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy, CostKind);
6704 
6705       InstructionCost RedCost = TTI.getExtendedAddReductionCost(
6706           /*IsMLA=*/true, true, RdxDesc.getRecurrenceType(), VectorTy,
6707           CostKind);
6708 
6709       if (RedCost.isValid() && RedCost < MulCost + BaseCost)
6710         return I == RetI ? RedCost : 0;
6711     }
6712   }
6713 
6714   return I == RetI ? Optional<InstructionCost>(BaseCost) : None;
6715 }
6716 
6717 InstructionCost
6718 LoopVectorizationCostModel::getMemoryInstructionCost(Instruction *I,
6719                                                      ElementCount VF) {
6720   // Calculate scalar cost only. Vectorization cost should be ready at this
6721   // moment.
6722   if (VF.isScalar()) {
6723     Type *ValTy = getLoadStoreType(I);
6724     const Align Alignment = getLoadStoreAlignment(I);
6725     unsigned AS = getLoadStoreAddressSpace(I);
6726 
6727     return TTI.getAddressComputationCost(ValTy) +
6728            TTI.getMemoryOpCost(I->getOpcode(), ValTy, Alignment, AS,
6729                                TTI::TCK_RecipThroughput, I);
6730   }
6731   return getWideningCost(I, VF);
6732 }
6733 
6734 LoopVectorizationCostModel::VectorizationCostTy
6735 LoopVectorizationCostModel::getInstructionCost(Instruction *I,
6736                                                ElementCount VF) {
6737   // If we know that this instruction will remain uniform, check the cost of
6738   // the scalar version.
6739   if (isUniformAfterVectorization(I, VF))
6740     VF = ElementCount::getFixed(1);
6741 
6742   if (VF.isVector() && isProfitableToScalarize(I, VF))
6743     return VectorizationCostTy(InstsToScalarize[VF][I], false);
6744 
6745   // Forced scalars do not have any scalarization overhead.
6746   auto ForcedScalar = ForcedScalars.find(VF);
6747   if (VF.isVector() && ForcedScalar != ForcedScalars.end()) {
6748     auto InstSet = ForcedScalar->second;
6749     if (InstSet.count(I))
6750       return VectorizationCostTy(
6751           (getInstructionCost(I, ElementCount::getFixed(1)).first *
6752            VF.getKnownMinValue()),
6753           false);
6754   }
6755 
6756   Type *VectorTy;
6757   InstructionCost C = getInstructionCost(I, VF, VectorTy);
6758 
6759   bool TypeNotScalarized = false;
6760   if (VF.isVector() && VectorTy->isVectorTy()) {
6761     unsigned NumParts = TTI.getNumberOfParts(VectorTy);
6762     if (NumParts)
6763       TypeNotScalarized = NumParts < VF.getKnownMinValue();
6764     else
6765       C = InstructionCost::getInvalid();
6766   }
6767   return VectorizationCostTy(C, TypeNotScalarized);
6768 }
6769 
6770 InstructionCost
6771 LoopVectorizationCostModel::getScalarizationOverhead(Instruction *I,
6772                                                      ElementCount VF) const {
6773 
6774   // There is no mechanism yet to create a scalable scalarization loop,
6775   // so this is currently Invalid.
6776   if (VF.isScalable())
6777     return InstructionCost::getInvalid();
6778 
6779   if (VF.isScalar())
6780     return 0;
6781 
6782   InstructionCost Cost = 0;
6783   Type *RetTy = ToVectorTy(I->getType(), VF);
6784   if (!RetTy->isVoidTy() &&
6785       (!isa<LoadInst>(I) || !TTI.supportsEfficientVectorElementLoadStore()))
6786     Cost += TTI.getScalarizationOverhead(
6787         cast<VectorType>(RetTy), APInt::getAllOnes(VF.getKnownMinValue()), true,
6788         false);
6789 
6790   // Some targets keep addresses scalar.
6791   if (isa<LoadInst>(I) && !TTI.prefersVectorizedAddressing())
6792     return Cost;
6793 
6794   // Some targets support efficient element stores.
6795   if (isa<StoreInst>(I) && TTI.supportsEfficientVectorElementLoadStore())
6796     return Cost;
6797 
6798   // Collect operands to consider.
6799   CallInst *CI = dyn_cast<CallInst>(I);
6800   Instruction::op_range Ops = CI ? CI->args() : I->operands();
6801 
6802   // Skip operands that do not require extraction/scalarization and do not incur
6803   // any overhead.
6804   SmallVector<Type *> Tys;
6805   for (auto *V : filterExtractingOperands(Ops, VF))
6806     Tys.push_back(MaybeVectorizeType(V->getType(), VF));
6807   return Cost + TTI.getOperandsScalarizationOverhead(
6808                     filterExtractingOperands(Ops, VF), Tys);
6809 }
6810 
6811 void LoopVectorizationCostModel::setCostBasedWideningDecision(ElementCount VF) {
6812   if (VF.isScalar())
6813     return;
6814   NumPredStores = 0;
6815   for (BasicBlock *BB : TheLoop->blocks()) {
6816     // For each instruction in the old loop.
6817     for (Instruction &I : *BB) {
6818       Value *Ptr =  getLoadStorePointerOperand(&I);
6819       if (!Ptr)
6820         continue;
6821 
6822       // TODO: We should generate better code and update the cost model for
6823       // predicated uniform stores. Today they are treated as any other
6824       // predicated store (see added test cases in
6825       // invariant-store-vectorization.ll).
6826       if (isa<StoreInst>(&I) && isScalarWithPredication(&I, VF))
6827         NumPredStores++;
6828 
6829       if (Legal->isUniformMemOp(I)) {
6830         // TODO: Avoid replicating loads and stores instead of
6831         // relying on instcombine to remove them.
6832         // Load: Scalar load + broadcast
6833         // Store: Scalar store + isLoopInvariantStoreValue ? 0 : extract
6834         InstructionCost Cost;
6835         if (isa<StoreInst>(&I) && VF.isScalable() &&
6836             isLegalGatherOrScatter(&I, VF)) {
6837           Cost = getGatherScatterCost(&I, VF);
6838           setWideningDecision(&I, VF, CM_GatherScatter, Cost);
6839         } else {
6840           assert((isa<LoadInst>(&I) || !VF.isScalable()) &&
6841                  "Cannot yet scalarize uniform stores");
6842           Cost = getUniformMemOpCost(&I, VF);
6843           setWideningDecision(&I, VF, CM_Scalarize, Cost);
6844         }
6845         continue;
6846       }
6847 
6848       // We assume that widening is the best solution when possible.
6849       if (memoryInstructionCanBeWidened(&I, VF)) {
6850         InstructionCost Cost = getConsecutiveMemOpCost(&I, VF);
6851         int ConsecutiveStride = Legal->isConsecutivePtr(
6852             getLoadStoreType(&I), getLoadStorePointerOperand(&I));
6853         assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
6854                "Expected consecutive stride.");
6855         InstWidening Decision =
6856             ConsecutiveStride == 1 ? CM_Widen : CM_Widen_Reverse;
6857         setWideningDecision(&I, VF, Decision, Cost);
6858         continue;
6859       }
6860 
6861       // Choose between Interleaving, Gather/Scatter or Scalarization.
6862       InstructionCost InterleaveCost = InstructionCost::getInvalid();
6863       unsigned NumAccesses = 1;
6864       if (isAccessInterleaved(&I)) {
6865         auto Group = getInterleavedAccessGroup(&I);
6866         assert(Group && "Fail to get an interleaved access group.");
6867 
6868         // Make one decision for the whole group.
6869         if (getWideningDecision(&I, VF) != CM_Unknown)
6870           continue;
6871 
6872         NumAccesses = Group->getNumMembers();
6873         if (interleavedAccessCanBeWidened(&I, VF))
6874           InterleaveCost = getInterleaveGroupCost(&I, VF);
6875       }
6876 
6877       InstructionCost GatherScatterCost =
6878           isLegalGatherOrScatter(&I, VF)
6879               ? getGatherScatterCost(&I, VF) * NumAccesses
6880               : InstructionCost::getInvalid();
6881 
6882       InstructionCost ScalarizationCost =
6883           getMemInstScalarizationCost(&I, VF) * NumAccesses;
6884 
6885       // Choose better solution for the current VF,
6886       // write down this decision and use it during vectorization.
6887       InstructionCost Cost;
6888       InstWidening Decision;
6889       if (InterleaveCost <= GatherScatterCost &&
6890           InterleaveCost < ScalarizationCost) {
6891         Decision = CM_Interleave;
6892         Cost = InterleaveCost;
6893       } else if (GatherScatterCost < ScalarizationCost) {
6894         Decision = CM_GatherScatter;
6895         Cost = GatherScatterCost;
6896       } else {
6897         Decision = CM_Scalarize;
6898         Cost = ScalarizationCost;
6899       }
6900       // If the instructions belongs to an interleave group, the whole group
6901       // receives the same decision. The whole group receives the cost, but
6902       // the cost will actually be assigned to one instruction.
6903       if (auto Group = getInterleavedAccessGroup(&I))
6904         setWideningDecision(Group, VF, Decision, Cost);
6905       else
6906         setWideningDecision(&I, VF, Decision, Cost);
6907     }
6908   }
6909 
6910   // Make sure that any load of address and any other address computation
6911   // remains scalar unless there is gather/scatter support. This avoids
6912   // inevitable extracts into address registers, and also has the benefit of
6913   // activating LSR more, since that pass can't optimize vectorized
6914   // addresses.
6915   if (TTI.prefersVectorizedAddressing())
6916     return;
6917 
6918   // Start with all scalar pointer uses.
6919   SmallPtrSet<Instruction *, 8> AddrDefs;
6920   for (BasicBlock *BB : TheLoop->blocks())
6921     for (Instruction &I : *BB) {
6922       Instruction *PtrDef =
6923         dyn_cast_or_null<Instruction>(getLoadStorePointerOperand(&I));
6924       if (PtrDef && TheLoop->contains(PtrDef) &&
6925           getWideningDecision(&I, VF) != CM_GatherScatter)
6926         AddrDefs.insert(PtrDef);
6927     }
6928 
6929   // Add all instructions used to generate the addresses.
6930   SmallVector<Instruction *, 4> Worklist;
6931   append_range(Worklist, AddrDefs);
6932   while (!Worklist.empty()) {
6933     Instruction *I = Worklist.pop_back_val();
6934     for (auto &Op : I->operands())
6935       if (auto *InstOp = dyn_cast<Instruction>(Op))
6936         if ((InstOp->getParent() == I->getParent()) && !isa<PHINode>(InstOp) &&
6937             AddrDefs.insert(InstOp).second)
6938           Worklist.push_back(InstOp);
6939   }
6940 
6941   for (auto *I : AddrDefs) {
6942     if (isa<LoadInst>(I)) {
6943       // Setting the desired widening decision should ideally be handled in
6944       // by cost functions, but since this involves the task of finding out
6945       // if the loaded register is involved in an address computation, it is
6946       // instead changed here when we know this is the case.
6947       InstWidening Decision = getWideningDecision(I, VF);
6948       if (Decision == CM_Widen || Decision == CM_Widen_Reverse)
6949         // Scalarize a widened load of address.
6950         setWideningDecision(
6951             I, VF, CM_Scalarize,
6952             (VF.getKnownMinValue() *
6953              getMemoryInstructionCost(I, ElementCount::getFixed(1))));
6954       else if (auto Group = getInterleavedAccessGroup(I)) {
6955         // Scalarize an interleave group of address loads.
6956         for (unsigned I = 0; I < Group->getFactor(); ++I) {
6957           if (Instruction *Member = Group->getMember(I))
6958             setWideningDecision(
6959                 Member, VF, CM_Scalarize,
6960                 (VF.getKnownMinValue() *
6961                  getMemoryInstructionCost(Member, ElementCount::getFixed(1))));
6962         }
6963       }
6964     } else
6965       // Make sure I gets scalarized and a cost estimate without
6966       // scalarization overhead.
6967       ForcedScalars[VF].insert(I);
6968   }
6969 }
6970 
6971 InstructionCost
6972 LoopVectorizationCostModel::getInstructionCost(Instruction *I, ElementCount VF,
6973                                                Type *&VectorTy) {
6974   Type *RetTy = I->getType();
6975   if (canTruncateToMinimalBitwidth(I, VF))
6976     RetTy = IntegerType::get(RetTy->getContext(), MinBWs[I]);
6977   auto SE = PSE.getSE();
6978   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
6979 
6980   auto hasSingleCopyAfterVectorization = [this](Instruction *I,
6981                                                 ElementCount VF) -> bool {
6982     if (VF.isScalar())
6983       return true;
6984 
6985     auto Scalarized = InstsToScalarize.find(VF);
6986     assert(Scalarized != InstsToScalarize.end() &&
6987            "VF not yet analyzed for scalarization profitability");
6988     return !Scalarized->second.count(I) &&
6989            llvm::all_of(I->users(), [&](User *U) {
6990              auto *UI = cast<Instruction>(U);
6991              return !Scalarized->second.count(UI);
6992            });
6993   };
6994   (void) hasSingleCopyAfterVectorization;
6995 
6996   if (isScalarAfterVectorization(I, VF)) {
6997     // With the exception of GEPs and PHIs, after scalarization there should
6998     // only be one copy of the instruction generated in the loop. This is
6999     // because the VF is either 1, or any instructions that need scalarizing
7000     // have already been dealt with by the the time we get here. As a result,
7001     // it means we don't have to multiply the instruction cost by VF.
7002     assert(I->getOpcode() == Instruction::GetElementPtr ||
7003            I->getOpcode() == Instruction::PHI ||
7004            (I->getOpcode() == Instruction::BitCast &&
7005             I->getType()->isPointerTy()) ||
7006            hasSingleCopyAfterVectorization(I, VF));
7007     VectorTy = RetTy;
7008   } else
7009     VectorTy = ToVectorTy(RetTy, VF);
7010 
7011   // TODO: We need to estimate the cost of intrinsic calls.
7012   switch (I->getOpcode()) {
7013   case Instruction::GetElementPtr:
7014     // We mark this instruction as zero-cost because the cost of GEPs in
7015     // vectorized code depends on whether the corresponding memory instruction
7016     // is scalarized or not. Therefore, we handle GEPs with the memory
7017     // instruction cost.
7018     return 0;
7019   case Instruction::Br: {
7020     // In cases of scalarized and predicated instructions, there will be VF
7021     // predicated blocks in the vectorized loop. Each branch around these
7022     // blocks requires also an extract of its vector compare i1 element.
7023     bool ScalarPredicatedBB = false;
7024     BranchInst *BI = cast<BranchInst>(I);
7025     if (VF.isVector() && BI->isConditional() &&
7026         (PredicatedBBsAfterVectorization.count(BI->getSuccessor(0)) ||
7027          PredicatedBBsAfterVectorization.count(BI->getSuccessor(1))))
7028       ScalarPredicatedBB = true;
7029 
7030     if (ScalarPredicatedBB) {
7031       // Not possible to scalarize scalable vector with predicated instructions.
7032       if (VF.isScalable())
7033         return InstructionCost::getInvalid();
7034       // Return cost for branches around scalarized and predicated blocks.
7035       auto *Vec_i1Ty =
7036           VectorType::get(IntegerType::getInt1Ty(RetTy->getContext()), VF);
7037       return (
7038           TTI.getScalarizationOverhead(
7039               Vec_i1Ty, APInt::getAllOnes(VF.getFixedValue()), false, true) +
7040           (TTI.getCFInstrCost(Instruction::Br, CostKind) * VF.getFixedValue()));
7041     } else if (I->getParent() == TheLoop->getLoopLatch() || VF.isScalar())
7042       // The back-edge branch will remain, as will all scalar branches.
7043       return TTI.getCFInstrCost(Instruction::Br, CostKind);
7044     else
7045       // This branch will be eliminated by if-conversion.
7046       return 0;
7047     // Note: We currently assume zero cost for an unconditional branch inside
7048     // a predicated block since it will become a fall-through, although we
7049     // may decide in the future to call TTI for all branches.
7050   }
7051   case Instruction::PHI: {
7052     auto *Phi = cast<PHINode>(I);
7053 
7054     // First-order recurrences are replaced by vector shuffles inside the loop.
7055     // NOTE: Don't use ToVectorTy as SK_ExtractSubvector expects a vector type.
7056     if (VF.isVector() && Legal->isFirstOrderRecurrence(Phi))
7057       return TTI.getShuffleCost(
7058           TargetTransformInfo::SK_ExtractSubvector, cast<VectorType>(VectorTy),
7059           None, VF.getKnownMinValue() - 1, FixedVectorType::get(RetTy, 1));
7060 
7061     // Phi nodes in non-header blocks (not inductions, reductions, etc.) are
7062     // converted into select instructions. We require N - 1 selects per phi
7063     // node, where N is the number of incoming values.
7064     if (VF.isVector() && Phi->getParent() != TheLoop->getHeader())
7065       return (Phi->getNumIncomingValues() - 1) *
7066              TTI.getCmpSelInstrCost(
7067                  Instruction::Select, ToVectorTy(Phi->getType(), VF),
7068                  ToVectorTy(Type::getInt1Ty(Phi->getContext()), VF),
7069                  CmpInst::BAD_ICMP_PREDICATE, CostKind);
7070 
7071     return TTI.getCFInstrCost(Instruction::PHI, CostKind);
7072   }
7073   case Instruction::UDiv:
7074   case Instruction::SDiv:
7075   case Instruction::URem:
7076   case Instruction::SRem:
7077     // If we have a predicated instruction, it may not be executed for each
7078     // vector lane. Get the scalarization cost and scale this amount by the
7079     // probability of executing the predicated block. If the instruction is not
7080     // predicated, we fall through to the next case.
7081     if (VF.isVector() && isScalarWithPredication(I, VF)) {
7082       InstructionCost Cost = 0;
7083 
7084       // These instructions have a non-void type, so account for the phi nodes
7085       // that we will create. This cost is likely to be zero. The phi node
7086       // cost, if any, should be scaled by the block probability because it
7087       // models a copy at the end of each predicated block.
7088       Cost += VF.getKnownMinValue() *
7089               TTI.getCFInstrCost(Instruction::PHI, CostKind);
7090 
7091       // The cost of the non-predicated instruction.
7092       Cost += VF.getKnownMinValue() *
7093               TTI.getArithmeticInstrCost(I->getOpcode(), RetTy, CostKind);
7094 
7095       // The cost of insertelement and extractelement instructions needed for
7096       // scalarization.
7097       Cost += getScalarizationOverhead(I, VF);
7098 
7099       // Scale the cost by the probability of executing the predicated blocks.
7100       // This assumes the predicated block for each vector lane is equally
7101       // likely.
7102       return Cost / getReciprocalPredBlockProb();
7103     }
7104     LLVM_FALLTHROUGH;
7105   case Instruction::Add:
7106   case Instruction::FAdd:
7107   case Instruction::Sub:
7108   case Instruction::FSub:
7109   case Instruction::Mul:
7110   case Instruction::FMul:
7111   case Instruction::FDiv:
7112   case Instruction::FRem:
7113   case Instruction::Shl:
7114   case Instruction::LShr:
7115   case Instruction::AShr:
7116   case Instruction::And:
7117   case Instruction::Or:
7118   case Instruction::Xor: {
7119     // Since we will replace the stride by 1 the multiplication should go away.
7120     if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
7121       return 0;
7122 
7123     // Detect reduction patterns
7124     if (auto RedCost = getReductionPatternCost(I, VF, VectorTy, CostKind))
7125       return *RedCost;
7126 
7127     // Certain instructions can be cheaper to vectorize if they have a constant
7128     // second vector operand. One example of this are shifts on x86.
7129     Value *Op2 = I->getOperand(1);
7130     TargetTransformInfo::OperandValueProperties Op2VP;
7131     TargetTransformInfo::OperandValueKind Op2VK =
7132         TTI.getOperandInfo(Op2, Op2VP);
7133     if (Op2VK == TargetTransformInfo::OK_AnyValue && Legal->isUniform(Op2))
7134       Op2VK = TargetTransformInfo::OK_UniformValue;
7135 
7136     SmallVector<const Value *, 4> Operands(I->operand_values());
7137     return TTI.getArithmeticInstrCost(
7138         I->getOpcode(), VectorTy, CostKind, TargetTransformInfo::OK_AnyValue,
7139         Op2VK, TargetTransformInfo::OP_None, Op2VP, Operands, I);
7140   }
7141   case Instruction::FNeg: {
7142     return TTI.getArithmeticInstrCost(
7143         I->getOpcode(), VectorTy, CostKind, TargetTransformInfo::OK_AnyValue,
7144         TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None,
7145         TargetTransformInfo::OP_None, I->getOperand(0), I);
7146   }
7147   case Instruction::Select: {
7148     SelectInst *SI = cast<SelectInst>(I);
7149     const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
7150     bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
7151 
7152     const Value *Op0, *Op1;
7153     using namespace llvm::PatternMatch;
7154     if (!ScalarCond && (match(I, m_LogicalAnd(m_Value(Op0), m_Value(Op1))) ||
7155                         match(I, m_LogicalOr(m_Value(Op0), m_Value(Op1))))) {
7156       // select x, y, false --> x & y
7157       // select x, true, y --> x | y
7158       TTI::OperandValueProperties Op1VP = TTI::OP_None;
7159       TTI::OperandValueProperties Op2VP = TTI::OP_None;
7160       TTI::OperandValueKind Op1VK = TTI::getOperandInfo(Op0, Op1VP);
7161       TTI::OperandValueKind Op2VK = TTI::getOperandInfo(Op1, Op2VP);
7162       assert(Op0->getType()->getScalarSizeInBits() == 1 &&
7163               Op1->getType()->getScalarSizeInBits() == 1);
7164 
7165       SmallVector<const Value *, 2> Operands{Op0, Op1};
7166       return TTI.getArithmeticInstrCost(
7167           match(I, m_LogicalOr()) ? Instruction::Or : Instruction::And, VectorTy,
7168           CostKind, Op1VK, Op2VK, Op1VP, Op2VP, Operands, I);
7169     }
7170 
7171     Type *CondTy = SI->getCondition()->getType();
7172     if (!ScalarCond)
7173       CondTy = VectorType::get(CondTy, VF);
7174 
7175     CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
7176     if (auto *Cmp = dyn_cast<CmpInst>(SI->getCondition()))
7177       Pred = Cmp->getPredicate();
7178     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy, Pred,
7179                                   CostKind, I);
7180   }
7181   case Instruction::ICmp:
7182   case Instruction::FCmp: {
7183     Type *ValTy = I->getOperand(0)->getType();
7184     Instruction *Op0AsInstruction = dyn_cast<Instruction>(I->getOperand(0));
7185     if (canTruncateToMinimalBitwidth(Op0AsInstruction, VF))
7186       ValTy = IntegerType::get(ValTy->getContext(), MinBWs[Op0AsInstruction]);
7187     VectorTy = ToVectorTy(ValTy, VF);
7188     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, nullptr,
7189                                   cast<CmpInst>(I)->getPredicate(), CostKind,
7190                                   I);
7191   }
7192   case Instruction::Store:
7193   case Instruction::Load: {
7194     ElementCount Width = VF;
7195     if (Width.isVector()) {
7196       InstWidening Decision = getWideningDecision(I, Width);
7197       assert(Decision != CM_Unknown &&
7198              "CM decision should be taken at this point");
7199       if (Decision == CM_Scalarize)
7200         Width = ElementCount::getFixed(1);
7201     }
7202     VectorTy = ToVectorTy(getLoadStoreType(I), Width);
7203     return getMemoryInstructionCost(I, VF);
7204   }
7205   case Instruction::BitCast:
7206     if (I->getType()->isPointerTy())
7207       return 0;
7208     LLVM_FALLTHROUGH;
7209   case Instruction::ZExt:
7210   case Instruction::SExt:
7211   case Instruction::FPToUI:
7212   case Instruction::FPToSI:
7213   case Instruction::FPExt:
7214   case Instruction::PtrToInt:
7215   case Instruction::IntToPtr:
7216   case Instruction::SIToFP:
7217   case Instruction::UIToFP:
7218   case Instruction::Trunc:
7219   case Instruction::FPTrunc: {
7220     // Computes the CastContextHint from a Load/Store instruction.
7221     auto ComputeCCH = [&](Instruction *I) -> TTI::CastContextHint {
7222       assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
7223              "Expected a load or a store!");
7224 
7225       if (VF.isScalar() || !TheLoop->contains(I))
7226         return TTI::CastContextHint::Normal;
7227 
7228       switch (getWideningDecision(I, VF)) {
7229       case LoopVectorizationCostModel::CM_GatherScatter:
7230         return TTI::CastContextHint::GatherScatter;
7231       case LoopVectorizationCostModel::CM_Interleave:
7232         return TTI::CastContextHint::Interleave;
7233       case LoopVectorizationCostModel::CM_Scalarize:
7234       case LoopVectorizationCostModel::CM_Widen:
7235         return Legal->isMaskRequired(I) ? TTI::CastContextHint::Masked
7236                                         : TTI::CastContextHint::Normal;
7237       case LoopVectorizationCostModel::CM_Widen_Reverse:
7238         return TTI::CastContextHint::Reversed;
7239       case LoopVectorizationCostModel::CM_Unknown:
7240         llvm_unreachable("Instr did not go through cost modelling?");
7241       }
7242 
7243       llvm_unreachable("Unhandled case!");
7244     };
7245 
7246     unsigned Opcode = I->getOpcode();
7247     TTI::CastContextHint CCH = TTI::CastContextHint::None;
7248     // For Trunc, the context is the only user, which must be a StoreInst.
7249     if (Opcode == Instruction::Trunc || Opcode == Instruction::FPTrunc) {
7250       if (I->hasOneUse())
7251         if (StoreInst *Store = dyn_cast<StoreInst>(*I->user_begin()))
7252           CCH = ComputeCCH(Store);
7253     }
7254     // For Z/Sext, the context is the operand, which must be a LoadInst.
7255     else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt ||
7256              Opcode == Instruction::FPExt) {
7257       if (LoadInst *Load = dyn_cast<LoadInst>(I->getOperand(0)))
7258         CCH = ComputeCCH(Load);
7259     }
7260 
7261     // We optimize the truncation of induction variables having constant
7262     // integer steps. The cost of these truncations is the same as the scalar
7263     // operation.
7264     if (isOptimizableIVTruncate(I, VF)) {
7265       auto *Trunc = cast<TruncInst>(I);
7266       return TTI.getCastInstrCost(Instruction::Trunc, Trunc->getDestTy(),
7267                                   Trunc->getSrcTy(), CCH, CostKind, Trunc);
7268     }
7269 
7270     // Detect reduction patterns
7271     if (auto RedCost = getReductionPatternCost(I, VF, VectorTy, CostKind))
7272       return *RedCost;
7273 
7274     Type *SrcScalarTy = I->getOperand(0)->getType();
7275     Type *SrcVecTy =
7276         VectorTy->isVectorTy() ? ToVectorTy(SrcScalarTy, VF) : SrcScalarTy;
7277     if (canTruncateToMinimalBitwidth(I, VF)) {
7278       // This cast is going to be shrunk. This may remove the cast or it might
7279       // turn it into slightly different cast. For example, if MinBW == 16,
7280       // "zext i8 %1 to i32" becomes "zext i8 %1 to i16".
7281       //
7282       // Calculate the modified src and dest types.
7283       Type *MinVecTy = VectorTy;
7284       if (Opcode == Instruction::Trunc) {
7285         SrcVecTy = smallestIntegerVectorType(SrcVecTy, MinVecTy);
7286         VectorTy =
7287             largestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy);
7288       } else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
7289         SrcVecTy = largestIntegerVectorType(SrcVecTy, MinVecTy);
7290         VectorTy =
7291             smallestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy);
7292       }
7293     }
7294 
7295     return TTI.getCastInstrCost(Opcode, VectorTy, SrcVecTy, CCH, CostKind, I);
7296   }
7297   case Instruction::Call: {
7298     if (RecurrenceDescriptor::isFMulAddIntrinsic(I))
7299       if (auto RedCost = getReductionPatternCost(I, VF, VectorTy, CostKind))
7300         return *RedCost;
7301     bool NeedToScalarize;
7302     CallInst *CI = cast<CallInst>(I);
7303     InstructionCost CallCost = getVectorCallCost(CI, VF, NeedToScalarize);
7304     if (getVectorIntrinsicIDForCall(CI, TLI)) {
7305       InstructionCost IntrinsicCost = getVectorIntrinsicCost(CI, VF);
7306       return std::min(CallCost, IntrinsicCost);
7307     }
7308     return CallCost;
7309   }
7310   case Instruction::ExtractValue:
7311     return TTI.getInstructionCost(I, TTI::TCK_RecipThroughput);
7312   case Instruction::Alloca:
7313     // We cannot easily widen alloca to a scalable alloca, as
7314     // the result would need to be a vector of pointers.
7315     if (VF.isScalable())
7316       return InstructionCost::getInvalid();
7317     LLVM_FALLTHROUGH;
7318   default:
7319     // This opcode is unknown. Assume that it is the same as 'mul'.
7320     return TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy, CostKind);
7321   } // end of switch.
7322 }
7323 
7324 char LoopVectorize::ID = 0;
7325 
7326 static const char lv_name[] = "Loop Vectorization";
7327 
7328 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
7329 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
7330 INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
7331 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
7332 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
7333 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
7334 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
7335 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
7336 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
7337 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
7338 INITIALIZE_PASS_DEPENDENCY(LoopAccessLegacyAnalysis)
7339 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
7340 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
7341 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
7342 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
7343 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
7344 
7345 namespace llvm {
7346 
7347 Pass *createLoopVectorizePass() { return new LoopVectorize(); }
7348 
7349 Pass *createLoopVectorizePass(bool InterleaveOnlyWhenForced,
7350                               bool VectorizeOnlyWhenForced) {
7351   return new LoopVectorize(InterleaveOnlyWhenForced, VectorizeOnlyWhenForced);
7352 }
7353 
7354 } // end namespace llvm
7355 
7356 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
7357   // Check if the pointer operand of a load or store instruction is
7358   // consecutive.
7359   if (auto *Ptr = getLoadStorePointerOperand(Inst))
7360     return Legal->isConsecutivePtr(getLoadStoreType(Inst), Ptr);
7361   return false;
7362 }
7363 
7364 void LoopVectorizationCostModel::collectValuesToIgnore() {
7365   // Ignore ephemeral values.
7366   CodeMetrics::collectEphemeralValues(TheLoop, AC, ValuesToIgnore);
7367 
7368   // Find all stores to invariant variables. Since they are going to sink
7369   // outside the loop we do not need calculate cost for them.
7370   for (BasicBlock *BB : TheLoop->blocks())
7371     for (Instruction &I : *BB) {
7372       StoreInst *SI;
7373       if ((SI = dyn_cast<StoreInst>(&I)) &&
7374           Legal->isInvariantAddressOfReduction(SI->getPointerOperand()))
7375         ValuesToIgnore.insert(&I);
7376     }
7377 
7378   // Ignore type-promoting instructions we identified during reduction
7379   // detection.
7380   for (auto &Reduction : Legal->getReductionVars()) {
7381     const RecurrenceDescriptor &RedDes = Reduction.second;
7382     const SmallPtrSetImpl<Instruction *> &Casts = RedDes.getCastInsts();
7383     VecValuesToIgnore.insert(Casts.begin(), Casts.end());
7384   }
7385   // Ignore type-casting instructions we identified during induction
7386   // detection.
7387   for (auto &Induction : Legal->getInductionVars()) {
7388     const InductionDescriptor &IndDes = Induction.second;
7389     const SmallVectorImpl<Instruction *> &Casts = IndDes.getCastInsts();
7390     VecValuesToIgnore.insert(Casts.begin(), Casts.end());
7391   }
7392 }
7393 
7394 void LoopVectorizationCostModel::collectInLoopReductions() {
7395   for (auto &Reduction : Legal->getReductionVars()) {
7396     PHINode *Phi = Reduction.first;
7397     const RecurrenceDescriptor &RdxDesc = Reduction.second;
7398 
7399     // We don't collect reductions that are type promoted (yet).
7400     if (RdxDesc.getRecurrenceType() != Phi->getType())
7401       continue;
7402 
7403     // If the target would prefer this reduction to happen "in-loop", then we
7404     // want to record it as such.
7405     unsigned Opcode = RdxDesc.getOpcode();
7406     if (!PreferInLoopReductions && !useOrderedReductions(RdxDesc) &&
7407         !TTI.preferInLoopReduction(Opcode, Phi->getType(),
7408                                    TargetTransformInfo::ReductionFlags()))
7409       continue;
7410 
7411     // Check that we can correctly put the reductions into the loop, by
7412     // finding the chain of operations that leads from the phi to the loop
7413     // exit value.
7414     SmallVector<Instruction *, 4> ReductionOperations =
7415         RdxDesc.getReductionOpChain(Phi, TheLoop);
7416     bool InLoop = !ReductionOperations.empty();
7417     if (InLoop) {
7418       InLoopReductionChains[Phi] = ReductionOperations;
7419       // Add the elements to InLoopReductionImmediateChains for cost modelling.
7420       Instruction *LastChain = Phi;
7421       for (auto *I : ReductionOperations) {
7422         InLoopReductionImmediateChains[I] = LastChain;
7423         LastChain = I;
7424       }
7425     }
7426     LLVM_DEBUG(dbgs() << "LV: Using " << (InLoop ? "inloop" : "out of loop")
7427                       << " reduction for phi: " << *Phi << "\n");
7428   }
7429 }
7430 
7431 // TODO: we could return a pair of values that specify the max VF and
7432 // min VF, to be used in `buildVPlans(MinVF, MaxVF)` instead of
7433 // `buildVPlans(VF, VF)`. We cannot do it because VPLAN at the moment
7434 // doesn't have a cost model that can choose which plan to execute if
7435 // more than one is generated.
7436 static unsigned determineVPlanVF(const unsigned WidestVectorRegBits,
7437                                  LoopVectorizationCostModel &CM) {
7438   unsigned WidestType;
7439   std::tie(std::ignore, WidestType) = CM.getSmallestAndWidestTypes();
7440   return WidestVectorRegBits / WidestType;
7441 }
7442 
7443 VectorizationFactor
7444 LoopVectorizationPlanner::planInVPlanNativePath(ElementCount UserVF) {
7445   assert(!UserVF.isScalable() && "scalable vectors not yet supported");
7446   ElementCount VF = UserVF;
7447   // Outer loop handling: They may require CFG and instruction level
7448   // transformations before even evaluating whether vectorization is profitable.
7449   // Since we cannot modify the incoming IR, we need to build VPlan upfront in
7450   // the vectorization pipeline.
7451   if (!OrigLoop->isInnermost()) {
7452     // If the user doesn't provide a vectorization factor, determine a
7453     // reasonable one.
7454     if (UserVF.isZero()) {
7455       VF = ElementCount::getFixed(determineVPlanVF(
7456           TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector)
7457               .getFixedSize(),
7458           CM));
7459       LLVM_DEBUG(dbgs() << "LV: VPlan computed VF " << VF << ".\n");
7460 
7461       // Make sure we have a VF > 1 for stress testing.
7462       if (VPlanBuildStressTest && (VF.isScalar() || VF.isZero())) {
7463         LLVM_DEBUG(dbgs() << "LV: VPlan stress testing: "
7464                           << "overriding computed VF.\n");
7465         VF = ElementCount::getFixed(4);
7466       }
7467     }
7468     assert(EnableVPlanNativePath && "VPlan-native path is not enabled.");
7469     assert(isPowerOf2_32(VF.getKnownMinValue()) &&
7470            "VF needs to be a power of two");
7471     LLVM_DEBUG(dbgs() << "LV: Using " << (!UserVF.isZero() ? "user " : "")
7472                       << "VF " << VF << " to build VPlans.\n");
7473     buildVPlans(VF, VF);
7474 
7475     // For VPlan build stress testing, we bail out after VPlan construction.
7476     if (VPlanBuildStressTest)
7477       return VectorizationFactor::Disabled();
7478 
7479     return {VF, 0 /*Cost*/};
7480   }
7481 
7482   LLVM_DEBUG(
7483       dbgs() << "LV: Not vectorizing. Inner loops aren't supported in the "
7484                 "VPlan-native path.\n");
7485   return VectorizationFactor::Disabled();
7486 }
7487 
7488 Optional<VectorizationFactor>
7489 LoopVectorizationPlanner::plan(ElementCount UserVF, unsigned UserIC) {
7490   assert(OrigLoop->isInnermost() && "Inner loop expected.");
7491   FixedScalableVFPair MaxFactors = CM.computeMaxVF(UserVF, UserIC);
7492   if (!MaxFactors) // Cases that should not to be vectorized nor interleaved.
7493     return None;
7494 
7495   // Invalidate interleave groups if all blocks of loop will be predicated.
7496   if (CM.blockNeedsPredicationForAnyReason(OrigLoop->getHeader()) &&
7497       !useMaskedInterleavedAccesses(*TTI)) {
7498     LLVM_DEBUG(
7499         dbgs()
7500         << "LV: Invalidate all interleaved groups due to fold-tail by masking "
7501            "which requires masked-interleaved support.\n");
7502     if (CM.InterleaveInfo.invalidateGroups())
7503       // Invalidating interleave groups also requires invalidating all decisions
7504       // based on them, which includes widening decisions and uniform and scalar
7505       // values.
7506       CM.invalidateCostModelingDecisions();
7507   }
7508 
7509   ElementCount MaxUserVF =
7510       UserVF.isScalable() ? MaxFactors.ScalableVF : MaxFactors.FixedVF;
7511   bool UserVFIsLegal = ElementCount::isKnownLE(UserVF, MaxUserVF);
7512   if (!UserVF.isZero() && UserVFIsLegal) {
7513     assert(isPowerOf2_32(UserVF.getKnownMinValue()) &&
7514            "VF needs to be a power of two");
7515     // Collect the instructions (and their associated costs) that will be more
7516     // profitable to scalarize.
7517     if (CM.selectUserVectorizationFactor(UserVF)) {
7518       LLVM_DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
7519       CM.collectInLoopReductions();
7520       buildVPlansWithVPRecipes(UserVF, UserVF);
7521       LLVM_DEBUG(printPlans(dbgs()));
7522       return {{UserVF, 0}};
7523     } else
7524       reportVectorizationInfo("UserVF ignored because of invalid costs.",
7525                               "InvalidCost", ORE, OrigLoop);
7526   }
7527 
7528   // Populate the set of Vectorization Factor Candidates.
7529   ElementCountSet VFCandidates;
7530   for (auto VF = ElementCount::getFixed(1);
7531        ElementCount::isKnownLE(VF, MaxFactors.FixedVF); VF *= 2)
7532     VFCandidates.insert(VF);
7533   for (auto VF = ElementCount::getScalable(1);
7534        ElementCount::isKnownLE(VF, MaxFactors.ScalableVF); VF *= 2)
7535     VFCandidates.insert(VF);
7536 
7537   for (const auto &VF : VFCandidates) {
7538     // Collect Uniform and Scalar instructions after vectorization with VF.
7539     CM.collectUniformsAndScalars(VF);
7540 
7541     // Collect the instructions (and their associated costs) that will be more
7542     // profitable to scalarize.
7543     if (VF.isVector())
7544       CM.collectInstsToScalarize(VF);
7545   }
7546 
7547   CM.collectInLoopReductions();
7548   buildVPlansWithVPRecipes(ElementCount::getFixed(1), MaxFactors.FixedVF);
7549   buildVPlansWithVPRecipes(ElementCount::getScalable(1), MaxFactors.ScalableVF);
7550 
7551   LLVM_DEBUG(printPlans(dbgs()));
7552   if (!MaxFactors.hasVector())
7553     return VectorizationFactor::Disabled();
7554 
7555   // Select the optimal vectorization factor.
7556   auto SelectedVF = CM.selectVectorizationFactor(VFCandidates);
7557 
7558   // Check if it is profitable to vectorize with runtime checks.
7559   unsigned NumRuntimePointerChecks = Requirements.getNumRuntimePointerChecks();
7560   if (SelectedVF.Width.getKnownMinValue() > 1 && NumRuntimePointerChecks) {
7561     bool PragmaThresholdReached =
7562         NumRuntimePointerChecks > PragmaVectorizeMemoryCheckThreshold;
7563     bool ThresholdReached =
7564         NumRuntimePointerChecks > VectorizerParams::RuntimeMemoryCheckThreshold;
7565     if ((ThresholdReached && !Hints.allowReordering()) ||
7566         PragmaThresholdReached) {
7567       ORE->emit([&]() {
7568         return OptimizationRemarkAnalysisAliasing(
7569                    DEBUG_TYPE, "CantReorderMemOps", OrigLoop->getStartLoc(),
7570                    OrigLoop->getHeader())
7571                << "loop not vectorized: cannot prove it is safe to reorder "
7572                   "memory operations";
7573       });
7574       LLVM_DEBUG(dbgs() << "LV: Too many memory checks needed.\n");
7575       Hints.emitRemarkWithHints();
7576       return VectorizationFactor::Disabled();
7577     }
7578   }
7579   return SelectedVF;
7580 }
7581 
7582 VPlan &LoopVectorizationPlanner::getBestPlanFor(ElementCount VF) const {
7583   assert(count_if(VPlans,
7584                   [VF](const VPlanPtr &Plan) { return Plan->hasVF(VF); }) ==
7585              1 &&
7586          "Best VF has not a single VPlan.");
7587 
7588   for (const VPlanPtr &Plan : VPlans) {
7589     if (Plan->hasVF(VF))
7590       return *Plan.get();
7591   }
7592   llvm_unreachable("No plan found!");
7593 }
7594 
7595 static void AddRuntimeUnrollDisableMetaData(Loop *L) {
7596   SmallVector<Metadata *, 4> MDs;
7597   // Reserve first location for self reference to the LoopID metadata node.
7598   MDs.push_back(nullptr);
7599   bool IsUnrollMetadata = false;
7600   MDNode *LoopID = L->getLoopID();
7601   if (LoopID) {
7602     // First find existing loop unrolling disable metadata.
7603     for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
7604       auto *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
7605       if (MD) {
7606         const auto *S = dyn_cast<MDString>(MD->getOperand(0));
7607         IsUnrollMetadata =
7608             S && S->getString().startswith("llvm.loop.unroll.disable");
7609       }
7610       MDs.push_back(LoopID->getOperand(i));
7611     }
7612   }
7613 
7614   if (!IsUnrollMetadata) {
7615     // Add runtime unroll disable metadata.
7616     LLVMContext &Context = L->getHeader()->getContext();
7617     SmallVector<Metadata *, 1> DisableOperands;
7618     DisableOperands.push_back(
7619         MDString::get(Context, "llvm.loop.unroll.runtime.disable"));
7620     MDNode *DisableNode = MDNode::get(Context, DisableOperands);
7621     MDs.push_back(DisableNode);
7622     MDNode *NewLoopID = MDNode::get(Context, MDs);
7623     // Set operand 0 to refer to the loop id itself.
7624     NewLoopID->replaceOperandWith(0, NewLoopID);
7625     L->setLoopID(NewLoopID);
7626   }
7627 }
7628 
7629 void LoopVectorizationPlanner::executePlan(ElementCount BestVF, unsigned BestUF,
7630                                            VPlan &BestVPlan,
7631                                            InnerLoopVectorizer &ILV,
7632                                            DominatorTree *DT) {
7633   LLVM_DEBUG(dbgs() << "Executing best plan with VF=" << BestVF << ", UF=" << BestUF
7634                     << '\n');
7635 
7636   // Perform the actual loop transformation.
7637 
7638   // 1. Set up the skeleton for vectorization, including vector pre-header and
7639   // middle block. The vector loop is created during VPlan execution.
7640   VPTransformState State{BestVF, BestUF, LI, DT, ILV.Builder, &ILV, &BestVPlan};
7641   Value *CanonicalIVStartValue;
7642   std::tie(State.CFG.PrevBB, CanonicalIVStartValue) =
7643       ILV.createVectorizedLoopSkeleton();
7644   ILV.collectPoisonGeneratingRecipes(State);
7645 
7646   ILV.printDebugTracesAtStart();
7647 
7648   //===------------------------------------------------===//
7649   //
7650   // Notice: any optimization or new instruction that go
7651   // into the code below should also be implemented in
7652   // the cost-model.
7653   //
7654   //===------------------------------------------------===//
7655 
7656   // 2. Copy and widen instructions from the old loop into the new loop.
7657   BestVPlan.prepareToExecute(ILV.getOrCreateTripCount(nullptr),
7658                              ILV.getOrCreateVectorTripCount(nullptr),
7659                              CanonicalIVStartValue, State);
7660   BestVPlan.execute(&State);
7661 
7662   // Keep all loop hints from the original loop on the vector loop (we'll
7663   // replace the vectorizer-specific hints below).
7664   MDNode *OrigLoopID = OrigLoop->getLoopID();
7665 
7666   Optional<MDNode *> VectorizedLoopID =
7667       makeFollowupLoopID(OrigLoopID, {LLVMLoopVectorizeFollowupAll,
7668                                       LLVMLoopVectorizeFollowupVectorized});
7669 
7670   VPBasicBlock *HeaderVPBB =
7671       BestVPlan.getVectorLoopRegion()->getEntryBasicBlock();
7672   Loop *L = LI->getLoopFor(State.CFG.VPBB2IRBB[HeaderVPBB]);
7673   if (VectorizedLoopID.hasValue())
7674     L->setLoopID(VectorizedLoopID.getValue());
7675   else {
7676     // Keep all loop hints from the original loop on the vector loop (we'll
7677     // replace the vectorizer-specific hints below).
7678     if (MDNode *LID = OrigLoop->getLoopID())
7679       L->setLoopID(LID);
7680 
7681     LoopVectorizeHints Hints(L, true, *ORE);
7682     Hints.setAlreadyVectorized();
7683   }
7684   // Disable runtime unrolling when vectorizing the epilogue loop.
7685   if (CanonicalIVStartValue)
7686     AddRuntimeUnrollDisableMetaData(L);
7687 
7688   // 3. Fix the vectorized code: take care of header phi's, live-outs,
7689   //    predication, updating analyses.
7690   ILV.fixVectorizedLoop(State, BestVPlan);
7691 
7692   ILV.printDebugTracesAtEnd();
7693 }
7694 
7695 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
7696 void LoopVectorizationPlanner::printPlans(raw_ostream &O) {
7697   for (const auto &Plan : VPlans)
7698     if (PrintVPlansInDotFormat)
7699       Plan->printDOT(O);
7700     else
7701       Plan->print(O);
7702 }
7703 #endif
7704 
7705 void LoopVectorizationPlanner::collectTriviallyDeadInstructions(
7706     SmallPtrSetImpl<Instruction *> &DeadInstructions) {
7707 
7708   // We create new control-flow for the vectorized loop, so the original exit
7709   // conditions will be dead after vectorization if it's only used by the
7710   // terminator
7711   SmallVector<BasicBlock*> ExitingBlocks;
7712   OrigLoop->getExitingBlocks(ExitingBlocks);
7713   for (auto *BB : ExitingBlocks) {
7714     auto *Cmp = dyn_cast<Instruction>(BB->getTerminator()->getOperand(0));
7715     if (!Cmp || !Cmp->hasOneUse())
7716       continue;
7717 
7718     // TODO: we should introduce a getUniqueExitingBlocks on Loop
7719     if (!DeadInstructions.insert(Cmp).second)
7720       continue;
7721 
7722     // The operands of the icmp is often a dead trunc, used by IndUpdate.
7723     // TODO: can recurse through operands in general
7724     for (Value *Op : Cmp->operands()) {
7725       if (isa<TruncInst>(Op) && Op->hasOneUse())
7726           DeadInstructions.insert(cast<Instruction>(Op));
7727     }
7728   }
7729 
7730   // We create new "steps" for induction variable updates to which the original
7731   // induction variables map. An original update instruction will be dead if
7732   // all its users except the induction variable are dead.
7733   auto *Latch = OrigLoop->getLoopLatch();
7734   for (auto &Induction : Legal->getInductionVars()) {
7735     PHINode *Ind = Induction.first;
7736     auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
7737 
7738     // If the tail is to be folded by masking, the primary induction variable,
7739     // if exists, isn't dead: it will be used for masking. Don't kill it.
7740     if (CM.foldTailByMasking() && IndUpdate == Legal->getPrimaryInduction())
7741       continue;
7742 
7743     if (llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
7744           return U == Ind || DeadInstructions.count(cast<Instruction>(U));
7745         }))
7746       DeadInstructions.insert(IndUpdate);
7747   }
7748 }
7749 
7750 Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) { return V; }
7751 
7752 //===--------------------------------------------------------------------===//
7753 // EpilogueVectorizerMainLoop
7754 //===--------------------------------------------------------------------===//
7755 
7756 /// This function is partially responsible for generating the control flow
7757 /// depicted in https://llvm.org/docs/Vectorizers.html#epilogue-vectorization.
7758 std::pair<BasicBlock *, Value *>
7759 EpilogueVectorizerMainLoop::createEpilogueVectorizedLoopSkeleton() {
7760   MDNode *OrigLoopID = OrigLoop->getLoopID();
7761 
7762   // Workaround!  Compute the trip count of the original loop and cache it
7763   // before we start modifying the CFG.  This code has a systemic problem
7764   // wherein it tries to run analysis over partially constructed IR; this is
7765   // wrong, and not simply for SCEV.  The trip count of the original loop
7766   // simply happens to be prone to hitting this in practice.  In theory, we
7767   // can hit the same issue for any SCEV, or ValueTracking query done during
7768   // mutation.  See PR49900.
7769   getOrCreateTripCount(OrigLoop->getLoopPreheader());
7770   createVectorLoopSkeleton("");
7771 
7772   // Generate the code to check the minimum iteration count of the vector
7773   // epilogue (see below).
7774   EPI.EpilogueIterationCountCheck =
7775       emitIterationCountCheck(LoopScalarPreHeader, true);
7776   EPI.EpilogueIterationCountCheck->setName("iter.check");
7777 
7778   // Generate the code to check any assumptions that we've made for SCEV
7779   // expressions.
7780   EPI.SCEVSafetyCheck = emitSCEVChecks(LoopScalarPreHeader);
7781 
7782   // Generate the code that checks at runtime if arrays overlap. We put the
7783   // checks into a separate block to make the more common case of few elements
7784   // faster.
7785   EPI.MemSafetyCheck = emitMemRuntimeChecks(LoopScalarPreHeader);
7786 
7787   // Generate the iteration count check for the main loop, *after* the check
7788   // for the epilogue loop, so that the path-length is shorter for the case
7789   // that goes directly through the vector epilogue. The longer-path length for
7790   // the main loop is compensated for, by the gain from vectorizing the larger
7791   // trip count. Note: the branch will get updated later on when we vectorize
7792   // the epilogue.
7793   EPI.MainLoopIterationCountCheck =
7794       emitIterationCountCheck(LoopScalarPreHeader, false);
7795 
7796   // Generate the induction variable.
7797   EPI.VectorTripCount = getOrCreateVectorTripCount(LoopVectorPreHeader);
7798 
7799   // Skip induction resume value creation here because they will be created in
7800   // the second pass. If we created them here, they wouldn't be used anyway,
7801   // because the vplan in the second pass still contains the inductions from the
7802   // original loop.
7803 
7804   return {completeLoopSkeleton(OrigLoopID), nullptr};
7805 }
7806 
7807 void EpilogueVectorizerMainLoop::printDebugTracesAtStart() {
7808   LLVM_DEBUG({
7809     dbgs() << "Create Skeleton for epilogue vectorized loop (first pass)\n"
7810            << "Main Loop VF:" << EPI.MainLoopVF
7811            << ", Main Loop UF:" << EPI.MainLoopUF
7812            << ", Epilogue Loop VF:" << EPI.EpilogueVF
7813            << ", Epilogue Loop UF:" << EPI.EpilogueUF << "\n";
7814   });
7815 }
7816 
7817 void EpilogueVectorizerMainLoop::printDebugTracesAtEnd() {
7818   DEBUG_WITH_TYPE(VerboseDebug, {
7819     dbgs() << "intermediate fn:\n"
7820            << *OrigLoop->getHeader()->getParent() << "\n";
7821   });
7822 }
7823 
7824 BasicBlock *
7825 EpilogueVectorizerMainLoop::emitIterationCountCheck(BasicBlock *Bypass,
7826                                                     bool ForEpilogue) {
7827   assert(Bypass && "Expected valid bypass basic block.");
7828   ElementCount VFactor = ForEpilogue ? EPI.EpilogueVF : VF;
7829   unsigned UFactor = ForEpilogue ? EPI.EpilogueUF : UF;
7830   Value *Count = getOrCreateTripCount(LoopVectorPreHeader);
7831   // Reuse existing vector loop preheader for TC checks.
7832   // Note that new preheader block is generated for vector loop.
7833   BasicBlock *const TCCheckBlock = LoopVectorPreHeader;
7834   IRBuilder<> Builder(TCCheckBlock->getTerminator());
7835 
7836   // Generate code to check if the loop's trip count is less than VF * UF of the
7837   // main vector loop.
7838   auto P = Cost->requiresScalarEpilogue(ForEpilogue ? EPI.EpilogueVF : VF) ?
7839       ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT;
7840 
7841   Value *CheckMinIters = Builder.CreateICmp(
7842       P, Count, createStepForVF(Builder, Count->getType(), VFactor, UFactor),
7843       "min.iters.check");
7844 
7845   if (!ForEpilogue)
7846     TCCheckBlock->setName("vector.main.loop.iter.check");
7847 
7848   // Create new preheader for vector loop.
7849   LoopVectorPreHeader = SplitBlock(TCCheckBlock, TCCheckBlock->getTerminator(),
7850                                    DT, LI, nullptr, "vector.ph");
7851 
7852   if (ForEpilogue) {
7853     assert(DT->properlyDominates(DT->getNode(TCCheckBlock),
7854                                  DT->getNode(Bypass)->getIDom()) &&
7855            "TC check is expected to dominate Bypass");
7856 
7857     // Update dominator for Bypass & LoopExit.
7858     DT->changeImmediateDominator(Bypass, TCCheckBlock);
7859     if (!Cost->requiresScalarEpilogue(EPI.EpilogueVF))
7860       // For loops with multiple exits, there's no edge from the middle block
7861       // to exit blocks (as the epilogue must run) and thus no need to update
7862       // the immediate dominator of the exit blocks.
7863       DT->changeImmediateDominator(LoopExitBlock, TCCheckBlock);
7864 
7865     LoopBypassBlocks.push_back(TCCheckBlock);
7866 
7867     // Save the trip count so we don't have to regenerate it in the
7868     // vec.epilog.iter.check. This is safe to do because the trip count
7869     // generated here dominates the vector epilog iter check.
7870     EPI.TripCount = Count;
7871   }
7872 
7873   ReplaceInstWithInst(
7874       TCCheckBlock->getTerminator(),
7875       BranchInst::Create(Bypass, LoopVectorPreHeader, CheckMinIters));
7876 
7877   return TCCheckBlock;
7878 }
7879 
7880 //===--------------------------------------------------------------------===//
7881 // EpilogueVectorizerEpilogueLoop
7882 //===--------------------------------------------------------------------===//
7883 
7884 /// This function is partially responsible for generating the control flow
7885 /// depicted in https://llvm.org/docs/Vectorizers.html#epilogue-vectorization.
7886 std::pair<BasicBlock *, Value *>
7887 EpilogueVectorizerEpilogueLoop::createEpilogueVectorizedLoopSkeleton() {
7888   MDNode *OrigLoopID = OrigLoop->getLoopID();
7889   createVectorLoopSkeleton("vec.epilog.");
7890 
7891   // Now, compare the remaining count and if there aren't enough iterations to
7892   // execute the vectorized epilogue skip to the scalar part.
7893   BasicBlock *VecEpilogueIterationCountCheck = LoopVectorPreHeader;
7894   VecEpilogueIterationCountCheck->setName("vec.epilog.iter.check");
7895   LoopVectorPreHeader =
7896       SplitBlock(LoopVectorPreHeader, LoopVectorPreHeader->getTerminator(), DT,
7897                  LI, nullptr, "vec.epilog.ph");
7898   emitMinimumVectorEpilogueIterCountCheck(LoopScalarPreHeader,
7899                                           VecEpilogueIterationCountCheck);
7900 
7901   // Adjust the control flow taking the state info from the main loop
7902   // vectorization into account.
7903   assert(EPI.MainLoopIterationCountCheck && EPI.EpilogueIterationCountCheck &&
7904          "expected this to be saved from the previous pass.");
7905   EPI.MainLoopIterationCountCheck->getTerminator()->replaceUsesOfWith(
7906       VecEpilogueIterationCountCheck, LoopVectorPreHeader);
7907 
7908   DT->changeImmediateDominator(LoopVectorPreHeader,
7909                                EPI.MainLoopIterationCountCheck);
7910 
7911   EPI.EpilogueIterationCountCheck->getTerminator()->replaceUsesOfWith(
7912       VecEpilogueIterationCountCheck, LoopScalarPreHeader);
7913 
7914   if (EPI.SCEVSafetyCheck)
7915     EPI.SCEVSafetyCheck->getTerminator()->replaceUsesOfWith(
7916         VecEpilogueIterationCountCheck, LoopScalarPreHeader);
7917   if (EPI.MemSafetyCheck)
7918     EPI.MemSafetyCheck->getTerminator()->replaceUsesOfWith(
7919         VecEpilogueIterationCountCheck, LoopScalarPreHeader);
7920 
7921   DT->changeImmediateDominator(
7922       VecEpilogueIterationCountCheck,
7923       VecEpilogueIterationCountCheck->getSinglePredecessor());
7924 
7925   DT->changeImmediateDominator(LoopScalarPreHeader,
7926                                EPI.EpilogueIterationCountCheck);
7927   if (!Cost->requiresScalarEpilogue(EPI.EpilogueVF))
7928     // If there is an epilogue which must run, there's no edge from the
7929     // middle block to exit blocks  and thus no need to update the immediate
7930     // dominator of the exit blocks.
7931     DT->changeImmediateDominator(LoopExitBlock,
7932                                  EPI.EpilogueIterationCountCheck);
7933 
7934   // Keep track of bypass blocks, as they feed start values to the induction
7935   // phis in the scalar loop preheader.
7936   if (EPI.SCEVSafetyCheck)
7937     LoopBypassBlocks.push_back(EPI.SCEVSafetyCheck);
7938   if (EPI.MemSafetyCheck)
7939     LoopBypassBlocks.push_back(EPI.MemSafetyCheck);
7940   LoopBypassBlocks.push_back(EPI.EpilogueIterationCountCheck);
7941 
7942   // The vec.epilog.iter.check block may contain Phi nodes from reductions which
7943   // merge control-flow from the latch block and the middle block. Update the
7944   // incoming values here and move the Phi into the preheader.
7945   SmallVector<PHINode *, 4> PhisInBlock;
7946   for (PHINode &Phi : VecEpilogueIterationCountCheck->phis())
7947     PhisInBlock.push_back(&Phi);
7948 
7949   for (PHINode *Phi : PhisInBlock) {
7950     Phi->replaceIncomingBlockWith(
7951         VecEpilogueIterationCountCheck->getSinglePredecessor(),
7952         VecEpilogueIterationCountCheck);
7953     Phi->removeIncomingValue(EPI.EpilogueIterationCountCheck);
7954     if (EPI.SCEVSafetyCheck)
7955       Phi->removeIncomingValue(EPI.SCEVSafetyCheck);
7956     if (EPI.MemSafetyCheck)
7957       Phi->removeIncomingValue(EPI.MemSafetyCheck);
7958     Phi->moveBefore(LoopVectorPreHeader->getFirstNonPHI());
7959   }
7960 
7961   // Generate a resume induction for the vector epilogue and put it in the
7962   // vector epilogue preheader
7963   Type *IdxTy = Legal->getWidestInductionType();
7964   PHINode *EPResumeVal = PHINode::Create(IdxTy, 2, "vec.epilog.resume.val",
7965                                          LoopVectorPreHeader->getFirstNonPHI());
7966   EPResumeVal->addIncoming(EPI.VectorTripCount, VecEpilogueIterationCountCheck);
7967   EPResumeVal->addIncoming(ConstantInt::get(IdxTy, 0),
7968                            EPI.MainLoopIterationCountCheck);
7969 
7970   // Generate induction resume values. These variables save the new starting
7971   // indexes for the scalar loop. They are used to test if there are any tail
7972   // iterations left once the vector loop has completed.
7973   // Note that when the vectorized epilogue is skipped due to iteration count
7974   // check, then the resume value for the induction variable comes from
7975   // the trip count of the main vector loop, hence passing the AdditionalBypass
7976   // argument.
7977   createInductionResumeValues({VecEpilogueIterationCountCheck,
7978                                EPI.VectorTripCount} /* AdditionalBypass */);
7979 
7980   return {completeLoopSkeleton(OrigLoopID), EPResumeVal};
7981 }
7982 
7983 BasicBlock *
7984 EpilogueVectorizerEpilogueLoop::emitMinimumVectorEpilogueIterCountCheck(
7985     BasicBlock *Bypass, BasicBlock *Insert) {
7986 
7987   assert(EPI.TripCount &&
7988          "Expected trip count to have been safed in the first pass.");
7989   assert(
7990       (!isa<Instruction>(EPI.TripCount) ||
7991        DT->dominates(cast<Instruction>(EPI.TripCount)->getParent(), Insert)) &&
7992       "saved trip count does not dominate insertion point.");
7993   Value *TC = EPI.TripCount;
7994   IRBuilder<> Builder(Insert->getTerminator());
7995   Value *Count = Builder.CreateSub(TC, EPI.VectorTripCount, "n.vec.remaining");
7996 
7997   // Generate code to check if the loop's trip count is less than VF * UF of the
7998   // vector epilogue loop.
7999   auto P = Cost->requiresScalarEpilogue(EPI.EpilogueVF) ?
8000       ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT;
8001 
8002   Value *CheckMinIters =
8003       Builder.CreateICmp(P, Count,
8004                          createStepForVF(Builder, Count->getType(),
8005                                          EPI.EpilogueVF, EPI.EpilogueUF),
8006                          "min.epilog.iters.check");
8007 
8008   ReplaceInstWithInst(
8009       Insert->getTerminator(),
8010       BranchInst::Create(Bypass, LoopVectorPreHeader, CheckMinIters));
8011 
8012   LoopBypassBlocks.push_back(Insert);
8013   return Insert;
8014 }
8015 
8016 void EpilogueVectorizerEpilogueLoop::printDebugTracesAtStart() {
8017   LLVM_DEBUG({
8018     dbgs() << "Create Skeleton for epilogue vectorized loop (second pass)\n"
8019            << "Epilogue Loop VF:" << EPI.EpilogueVF
8020            << ", Epilogue Loop UF:" << EPI.EpilogueUF << "\n";
8021   });
8022 }
8023 
8024 void EpilogueVectorizerEpilogueLoop::printDebugTracesAtEnd() {
8025   DEBUG_WITH_TYPE(VerboseDebug, {
8026     dbgs() << "final fn:\n" << *OrigLoop->getHeader()->getParent() << "\n";
8027   });
8028 }
8029 
8030 bool LoopVectorizationPlanner::getDecisionAndClampRange(
8031     const std::function<bool(ElementCount)> &Predicate, VFRange &Range) {
8032   assert(!Range.isEmpty() && "Trying to test an empty VF range.");
8033   bool PredicateAtRangeStart = Predicate(Range.Start);
8034 
8035   for (ElementCount TmpVF = Range.Start * 2;
8036        ElementCount::isKnownLT(TmpVF, Range.End); TmpVF *= 2)
8037     if (Predicate(TmpVF) != PredicateAtRangeStart) {
8038       Range.End = TmpVF;
8039       break;
8040     }
8041 
8042   return PredicateAtRangeStart;
8043 }
8044 
8045 /// Build VPlans for the full range of feasible VF's = {\p MinVF, 2 * \p MinVF,
8046 /// 4 * \p MinVF, ..., \p MaxVF} by repeatedly building a VPlan for a sub-range
8047 /// of VF's starting at a given VF and extending it as much as possible. Each
8048 /// vectorization decision can potentially shorten this sub-range during
8049 /// buildVPlan().
8050 void LoopVectorizationPlanner::buildVPlans(ElementCount MinVF,
8051                                            ElementCount MaxVF) {
8052   auto MaxVFPlusOne = MaxVF.getWithIncrement(1);
8053   for (ElementCount VF = MinVF; ElementCount::isKnownLT(VF, MaxVFPlusOne);) {
8054     VFRange SubRange = {VF, MaxVFPlusOne};
8055     VPlans.push_back(buildVPlan(SubRange));
8056     VF = SubRange.End;
8057   }
8058 }
8059 
8060 VPValue *VPRecipeBuilder::createEdgeMask(BasicBlock *Src, BasicBlock *Dst,
8061                                          VPlanPtr &Plan) {
8062   assert(is_contained(predecessors(Dst), Src) && "Invalid edge");
8063 
8064   // Look for cached value.
8065   std::pair<BasicBlock *, BasicBlock *> Edge(Src, Dst);
8066   EdgeMaskCacheTy::iterator ECEntryIt = EdgeMaskCache.find(Edge);
8067   if (ECEntryIt != EdgeMaskCache.end())
8068     return ECEntryIt->second;
8069 
8070   VPValue *SrcMask = createBlockInMask(Src, Plan);
8071 
8072   // The terminator has to be a branch inst!
8073   BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
8074   assert(BI && "Unexpected terminator found");
8075 
8076   if (!BI->isConditional() || BI->getSuccessor(0) == BI->getSuccessor(1))
8077     return EdgeMaskCache[Edge] = SrcMask;
8078 
8079   // If source is an exiting block, we know the exit edge is dynamically dead
8080   // in the vector loop, and thus we don't need to restrict the mask.  Avoid
8081   // adding uses of an otherwise potentially dead instruction.
8082   if (OrigLoop->isLoopExiting(Src))
8083     return EdgeMaskCache[Edge] = SrcMask;
8084 
8085   VPValue *EdgeMask = Plan->getOrAddVPValue(BI->getCondition());
8086   assert(EdgeMask && "No Edge Mask found for condition");
8087 
8088   if (BI->getSuccessor(0) != Dst)
8089     EdgeMask = Builder.createNot(EdgeMask, BI->getDebugLoc());
8090 
8091   if (SrcMask) { // Otherwise block in-mask is all-one, no need to AND.
8092     // The condition is 'SrcMask && EdgeMask', which is equivalent to
8093     // 'select i1 SrcMask, i1 EdgeMask, i1 false'.
8094     // The select version does not introduce new UB if SrcMask is false and
8095     // EdgeMask is poison. Using 'and' here introduces undefined behavior.
8096     VPValue *False = Plan->getOrAddVPValue(
8097         ConstantInt::getFalse(BI->getCondition()->getType()));
8098     EdgeMask =
8099         Builder.createSelect(SrcMask, EdgeMask, False, BI->getDebugLoc());
8100   }
8101 
8102   return EdgeMaskCache[Edge] = EdgeMask;
8103 }
8104 
8105 VPValue *VPRecipeBuilder::createBlockInMask(BasicBlock *BB, VPlanPtr &Plan) {
8106   assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
8107 
8108   // Look for cached value.
8109   BlockMaskCacheTy::iterator BCEntryIt = BlockMaskCache.find(BB);
8110   if (BCEntryIt != BlockMaskCache.end())
8111     return BCEntryIt->second;
8112 
8113   // All-one mask is modelled as no-mask following the convention for masked
8114   // load/store/gather/scatter. Initialize BlockMask to no-mask.
8115   VPValue *BlockMask = nullptr;
8116 
8117   if (OrigLoop->getHeader() == BB) {
8118     if (!CM.blockNeedsPredicationForAnyReason(BB))
8119       return BlockMaskCache[BB] = BlockMask; // Loop incoming mask is all-one.
8120 
8121     // Introduce the early-exit compare IV <= BTC to form header block mask.
8122     // This is used instead of IV < TC because TC may wrap, unlike BTC. Start by
8123     // constructing the desired canonical IV in the header block as its first
8124     // non-phi instructions.
8125     assert(CM.foldTailByMasking() && "must fold the tail");
8126     VPBasicBlock *HeaderVPBB =
8127         Plan->getVectorLoopRegion()->getEntryBasicBlock();
8128     auto NewInsertionPoint = HeaderVPBB->getFirstNonPhi();
8129     auto *IV = new VPWidenCanonicalIVRecipe(Plan->getCanonicalIV());
8130     HeaderVPBB->insert(IV, HeaderVPBB->getFirstNonPhi());
8131 
8132     VPBuilder::InsertPointGuard Guard(Builder);
8133     Builder.setInsertPoint(HeaderVPBB, NewInsertionPoint);
8134     if (CM.TTI.emitGetActiveLaneMask()) {
8135       VPValue *TC = Plan->getOrCreateTripCount();
8136       BlockMask = Builder.createNaryOp(VPInstruction::ActiveLaneMask, {IV, TC});
8137     } else {
8138       VPValue *BTC = Plan->getOrCreateBackedgeTakenCount();
8139       BlockMask = Builder.createNaryOp(VPInstruction::ICmpULE, {IV, BTC});
8140     }
8141     return BlockMaskCache[BB] = BlockMask;
8142   }
8143 
8144   // This is the block mask. We OR all incoming edges.
8145   for (auto *Predecessor : predecessors(BB)) {
8146     VPValue *EdgeMask = createEdgeMask(Predecessor, BB, Plan);
8147     if (!EdgeMask) // Mask of predecessor is all-one so mask of block is too.
8148       return BlockMaskCache[BB] = EdgeMask;
8149 
8150     if (!BlockMask) { // BlockMask has its initialized nullptr value.
8151       BlockMask = EdgeMask;
8152       continue;
8153     }
8154 
8155     BlockMask = Builder.createOr(BlockMask, EdgeMask, {});
8156   }
8157 
8158   return BlockMaskCache[BB] = BlockMask;
8159 }
8160 
8161 VPRecipeBase *VPRecipeBuilder::tryToWidenMemory(Instruction *I,
8162                                                 ArrayRef<VPValue *> Operands,
8163                                                 VFRange &Range,
8164                                                 VPlanPtr &Plan) {
8165   assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
8166          "Must be called with either a load or store");
8167 
8168   auto willWiden = [&](ElementCount VF) -> bool {
8169     if (VF.isScalar())
8170       return false;
8171     LoopVectorizationCostModel::InstWidening Decision =
8172         CM.getWideningDecision(I, VF);
8173     assert(Decision != LoopVectorizationCostModel::CM_Unknown &&
8174            "CM decision should be taken at this point.");
8175     if (Decision == LoopVectorizationCostModel::CM_Interleave)
8176       return true;
8177     if (CM.isScalarAfterVectorization(I, VF) ||
8178         CM.isProfitableToScalarize(I, VF))
8179       return false;
8180     return Decision != LoopVectorizationCostModel::CM_Scalarize;
8181   };
8182 
8183   if (!LoopVectorizationPlanner::getDecisionAndClampRange(willWiden, Range))
8184     return nullptr;
8185 
8186   VPValue *Mask = nullptr;
8187   if (Legal->isMaskRequired(I))
8188     Mask = createBlockInMask(I->getParent(), Plan);
8189 
8190   // Determine if the pointer operand of the access is either consecutive or
8191   // reverse consecutive.
8192   LoopVectorizationCostModel::InstWidening Decision =
8193       CM.getWideningDecision(I, Range.Start);
8194   bool Reverse = Decision == LoopVectorizationCostModel::CM_Widen_Reverse;
8195   bool Consecutive =
8196       Reverse || Decision == LoopVectorizationCostModel::CM_Widen;
8197 
8198   if (LoadInst *Load = dyn_cast<LoadInst>(I))
8199     return new VPWidenMemoryInstructionRecipe(*Load, Operands[0], Mask,
8200                                               Consecutive, Reverse);
8201 
8202   StoreInst *Store = cast<StoreInst>(I);
8203   return new VPWidenMemoryInstructionRecipe(*Store, Operands[1], Operands[0],
8204                                             Mask, Consecutive, Reverse);
8205 }
8206 
8207 /// Creates a VPWidenIntOrFpInductionRecpipe for \p Phi. If needed, it will also
8208 /// insert a recipe to expand the step for the induction recipe.
8209 static VPWidenIntOrFpInductionRecipe *createWidenInductionRecipes(
8210     PHINode *Phi, Instruction *PhiOrTrunc, VPValue *Start,
8211     const InductionDescriptor &IndDesc, LoopVectorizationCostModel &CM,
8212     VPlan &Plan, ScalarEvolution &SE, Loop &OrigLoop, VFRange &Range) {
8213   // Returns true if an instruction \p I should be scalarized instead of
8214   // vectorized for the chosen vectorization factor.
8215   auto ShouldScalarizeInstruction = [&CM](Instruction *I, ElementCount VF) {
8216     return CM.isScalarAfterVectorization(I, VF) ||
8217            CM.isProfitableToScalarize(I, VF);
8218   };
8219 
8220   bool NeedsScalarIV = LoopVectorizationPlanner::getDecisionAndClampRange(
8221       [&](ElementCount VF) {
8222         // Returns true if we should generate a scalar version of \p IV.
8223         if (ShouldScalarizeInstruction(PhiOrTrunc, VF))
8224           return true;
8225         auto isScalarInst = [&](User *U) -> bool {
8226           auto *I = cast<Instruction>(U);
8227           return OrigLoop.contains(I) && ShouldScalarizeInstruction(I, VF);
8228         };
8229         return any_of(PhiOrTrunc->users(), isScalarInst);
8230       },
8231       Range);
8232   bool NeedsScalarIVOnly = LoopVectorizationPlanner::getDecisionAndClampRange(
8233       [&](ElementCount VF) {
8234         return ShouldScalarizeInstruction(PhiOrTrunc, VF);
8235       },
8236       Range);
8237   assert(IndDesc.getStartValue() ==
8238          Phi->getIncomingValueForBlock(OrigLoop.getLoopPreheader()));
8239   assert(SE.isLoopInvariant(IndDesc.getStep(), &OrigLoop) &&
8240          "step must be loop invariant");
8241 
8242   VPValue *Step =
8243       vputils::getOrCreateVPValueForSCEVExpr(Plan, IndDesc.getStep(), SE);
8244   if (auto *TruncI = dyn_cast<TruncInst>(PhiOrTrunc)) {
8245     return new VPWidenIntOrFpInductionRecipe(Phi, Start, Step, IndDesc, TruncI,
8246                                              NeedsScalarIV, !NeedsScalarIVOnly);
8247   }
8248   assert(isa<PHINode>(PhiOrTrunc) && "must be a phi node here");
8249   return new VPWidenIntOrFpInductionRecipe(Phi, Start, Step, IndDesc,
8250                                            NeedsScalarIV, !NeedsScalarIVOnly);
8251 }
8252 
8253 VPRecipeBase *VPRecipeBuilder::tryToOptimizeInductionPHI(
8254     PHINode *Phi, ArrayRef<VPValue *> Operands, VPlan &Plan, VFRange &Range) {
8255 
8256   // Check if this is an integer or fp induction. If so, build the recipe that
8257   // produces its scalar and vector values.
8258   if (auto *II = Legal->getIntOrFpInductionDescriptor(Phi))
8259     return createWidenInductionRecipes(Phi, Phi, Operands[0], *II, CM, Plan,
8260                                        *PSE.getSE(), *OrigLoop, Range);
8261 
8262   // Check if this is pointer induction. If so, build the recipe for it.
8263   if (auto *II = Legal->getPointerInductionDescriptor(Phi))
8264     return new VPWidenPointerInductionRecipe(Phi, Operands[0], *II,
8265                                              *PSE.getSE());
8266   return nullptr;
8267 }
8268 
8269 VPWidenIntOrFpInductionRecipe *VPRecipeBuilder::tryToOptimizeInductionTruncate(
8270     TruncInst *I, ArrayRef<VPValue *> Operands, VFRange &Range, VPlan &Plan) {
8271   // Optimize the special case where the source is a constant integer
8272   // induction variable. Notice that we can only optimize the 'trunc' case
8273   // because (a) FP conversions lose precision, (b) sext/zext may wrap, and
8274   // (c) other casts depend on pointer size.
8275 
8276   // Determine whether \p K is a truncation based on an induction variable that
8277   // can be optimized.
8278   auto isOptimizableIVTruncate =
8279       [&](Instruction *K) -> std::function<bool(ElementCount)> {
8280     return [=](ElementCount VF) -> bool {
8281       return CM.isOptimizableIVTruncate(K, VF);
8282     };
8283   };
8284 
8285   if (LoopVectorizationPlanner::getDecisionAndClampRange(
8286           isOptimizableIVTruncate(I), Range)) {
8287 
8288     auto *Phi = cast<PHINode>(I->getOperand(0));
8289     const InductionDescriptor &II = *Legal->getIntOrFpInductionDescriptor(Phi);
8290     VPValue *Start = Plan.getOrAddVPValue(II.getStartValue());
8291     return createWidenInductionRecipes(Phi, I, Start, II, CM, Plan,
8292                                        *PSE.getSE(), *OrigLoop, Range);
8293   }
8294   return nullptr;
8295 }
8296 
8297 VPRecipeOrVPValueTy VPRecipeBuilder::tryToBlend(PHINode *Phi,
8298                                                 ArrayRef<VPValue *> Operands,
8299                                                 VPlanPtr &Plan) {
8300   // If all incoming values are equal, the incoming VPValue can be used directly
8301   // instead of creating a new VPBlendRecipe.
8302   VPValue *FirstIncoming = Operands[0];
8303   if (all_of(Operands, [FirstIncoming](const VPValue *Inc) {
8304         return FirstIncoming == Inc;
8305       })) {
8306     return Operands[0];
8307   }
8308 
8309   unsigned NumIncoming = Phi->getNumIncomingValues();
8310   // For in-loop reductions, we do not need to create an additional select.
8311   VPValue *InLoopVal = nullptr;
8312   for (unsigned In = 0; In < NumIncoming; In++) {
8313     PHINode *PhiOp =
8314         dyn_cast_or_null<PHINode>(Operands[In]->getUnderlyingValue());
8315     if (PhiOp && CM.isInLoopReduction(PhiOp)) {
8316       assert(!InLoopVal && "Found more than one in-loop reduction!");
8317       InLoopVal = Operands[In];
8318     }
8319   }
8320 
8321   assert((!InLoopVal || NumIncoming == 2) &&
8322          "Found an in-loop reduction for PHI with unexpected number of "
8323          "incoming values");
8324   if (InLoopVal)
8325     return Operands[Operands[0] == InLoopVal ? 1 : 0];
8326 
8327   // We know that all PHIs in non-header blocks are converted into selects, so
8328   // we don't have to worry about the insertion order and we can just use the
8329   // builder. At this point we generate the predication tree. There may be
8330   // duplications since this is a simple recursive scan, but future
8331   // optimizations will clean it up.
8332   SmallVector<VPValue *, 2> OperandsWithMask;
8333 
8334   for (unsigned In = 0; In < NumIncoming; In++) {
8335     VPValue *EdgeMask =
8336       createEdgeMask(Phi->getIncomingBlock(In), Phi->getParent(), Plan);
8337     assert((EdgeMask || NumIncoming == 1) &&
8338            "Multiple predecessors with one having a full mask");
8339     OperandsWithMask.push_back(Operands[In]);
8340     if (EdgeMask)
8341       OperandsWithMask.push_back(EdgeMask);
8342   }
8343   return toVPRecipeResult(new VPBlendRecipe(Phi, OperandsWithMask));
8344 }
8345 
8346 VPWidenCallRecipe *VPRecipeBuilder::tryToWidenCall(CallInst *CI,
8347                                                    ArrayRef<VPValue *> Operands,
8348                                                    VFRange &Range) const {
8349 
8350   bool IsPredicated = LoopVectorizationPlanner::getDecisionAndClampRange(
8351       [this, CI](ElementCount VF) {
8352         return CM.isScalarWithPredication(CI, VF);
8353       },
8354       Range);
8355 
8356   if (IsPredicated)
8357     return nullptr;
8358 
8359   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
8360   if (ID && (ID == Intrinsic::assume || ID == Intrinsic::lifetime_end ||
8361              ID == Intrinsic::lifetime_start || ID == Intrinsic::sideeffect ||
8362              ID == Intrinsic::pseudoprobe ||
8363              ID == Intrinsic::experimental_noalias_scope_decl))
8364     return nullptr;
8365 
8366   auto willWiden = [&](ElementCount VF) -> bool {
8367     if (VF.isScalar())
8368        return false;
8369     Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
8370     // The following case may be scalarized depending on the VF.
8371     // The flag shows whether we use Intrinsic or a usual Call for vectorized
8372     // version of the instruction.
8373     // Is it beneficial to perform intrinsic call compared to lib call?
8374     bool NeedToScalarize = false;
8375     InstructionCost CallCost = CM.getVectorCallCost(CI, VF, NeedToScalarize);
8376     InstructionCost IntrinsicCost = ID ? CM.getVectorIntrinsicCost(CI, VF) : 0;
8377     bool UseVectorIntrinsic = ID && IntrinsicCost <= CallCost;
8378     return UseVectorIntrinsic || !NeedToScalarize;
8379   };
8380 
8381   if (!LoopVectorizationPlanner::getDecisionAndClampRange(willWiden, Range))
8382     return nullptr;
8383 
8384   ArrayRef<VPValue *> Ops = Operands.take_front(CI->arg_size());
8385   return new VPWidenCallRecipe(*CI, make_range(Ops.begin(), Ops.end()));
8386 }
8387 
8388 bool VPRecipeBuilder::shouldWiden(Instruction *I, VFRange &Range) const {
8389   assert(!isa<BranchInst>(I) && !isa<PHINode>(I) && !isa<LoadInst>(I) &&
8390          !isa<StoreInst>(I) && "Instruction should have been handled earlier");
8391   // Instruction should be widened, unless it is scalar after vectorization,
8392   // scalarization is profitable or it is predicated.
8393   auto WillScalarize = [this, I](ElementCount VF) -> bool {
8394     return CM.isScalarAfterVectorization(I, VF) ||
8395            CM.isProfitableToScalarize(I, VF) ||
8396            CM.isScalarWithPredication(I, VF);
8397   };
8398   return !LoopVectorizationPlanner::getDecisionAndClampRange(WillScalarize,
8399                                                              Range);
8400 }
8401 
8402 VPWidenRecipe *VPRecipeBuilder::tryToWiden(Instruction *I,
8403                                            ArrayRef<VPValue *> Operands) const {
8404   auto IsVectorizableOpcode = [](unsigned Opcode) {
8405     switch (Opcode) {
8406     case Instruction::Add:
8407     case Instruction::And:
8408     case Instruction::AShr:
8409     case Instruction::BitCast:
8410     case Instruction::FAdd:
8411     case Instruction::FCmp:
8412     case Instruction::FDiv:
8413     case Instruction::FMul:
8414     case Instruction::FNeg:
8415     case Instruction::FPExt:
8416     case Instruction::FPToSI:
8417     case Instruction::FPToUI:
8418     case Instruction::FPTrunc:
8419     case Instruction::FRem:
8420     case Instruction::FSub:
8421     case Instruction::ICmp:
8422     case Instruction::IntToPtr:
8423     case Instruction::LShr:
8424     case Instruction::Mul:
8425     case Instruction::Or:
8426     case Instruction::PtrToInt:
8427     case Instruction::SDiv:
8428     case Instruction::Select:
8429     case Instruction::SExt:
8430     case Instruction::Shl:
8431     case Instruction::SIToFP:
8432     case Instruction::SRem:
8433     case Instruction::Sub:
8434     case Instruction::Trunc:
8435     case Instruction::UDiv:
8436     case Instruction::UIToFP:
8437     case Instruction::URem:
8438     case Instruction::Xor:
8439     case Instruction::ZExt:
8440       return true;
8441     }
8442     return false;
8443   };
8444 
8445   if (!IsVectorizableOpcode(I->getOpcode()))
8446     return nullptr;
8447 
8448   // Success: widen this instruction.
8449   return new VPWidenRecipe(*I, make_range(Operands.begin(), Operands.end()));
8450 }
8451 
8452 void VPRecipeBuilder::fixHeaderPhis() {
8453   BasicBlock *OrigLatch = OrigLoop->getLoopLatch();
8454   for (VPHeaderPHIRecipe *R : PhisToFix) {
8455     auto *PN = cast<PHINode>(R->getUnderlyingValue());
8456     VPRecipeBase *IncR =
8457         getRecipe(cast<Instruction>(PN->getIncomingValueForBlock(OrigLatch)));
8458     R->addOperand(IncR->getVPSingleValue());
8459   }
8460 }
8461 
8462 VPBasicBlock *VPRecipeBuilder::handleReplication(
8463     Instruction *I, VFRange &Range, VPBasicBlock *VPBB,
8464     VPlanPtr &Plan) {
8465   bool IsUniform = LoopVectorizationPlanner::getDecisionAndClampRange(
8466       [&](ElementCount VF) { return CM.isUniformAfterVectorization(I, VF); },
8467       Range);
8468 
8469   bool IsPredicated = LoopVectorizationPlanner::getDecisionAndClampRange(
8470       [&](ElementCount VF) { return CM.isPredicatedInst(I, VF, IsUniform); },
8471       Range);
8472 
8473   // Even if the instruction is not marked as uniform, there are certain
8474   // intrinsic calls that can be effectively treated as such, so we check for
8475   // them here. Conservatively, we only do this for scalable vectors, since
8476   // for fixed-width VFs we can always fall back on full scalarization.
8477   if (!IsUniform && Range.Start.isScalable() && isa<IntrinsicInst>(I)) {
8478     switch (cast<IntrinsicInst>(I)->getIntrinsicID()) {
8479     case Intrinsic::assume:
8480     case Intrinsic::lifetime_start:
8481     case Intrinsic::lifetime_end:
8482       // For scalable vectors if one of the operands is variant then we still
8483       // want to mark as uniform, which will generate one instruction for just
8484       // the first lane of the vector. We can't scalarize the call in the same
8485       // way as for fixed-width vectors because we don't know how many lanes
8486       // there are.
8487       //
8488       // The reasons for doing it this way for scalable vectors are:
8489       //   1. For the assume intrinsic generating the instruction for the first
8490       //      lane is still be better than not generating any at all. For
8491       //      example, the input may be a splat across all lanes.
8492       //   2. For the lifetime start/end intrinsics the pointer operand only
8493       //      does anything useful when the input comes from a stack object,
8494       //      which suggests it should always be uniform. For non-stack objects
8495       //      the effect is to poison the object, which still allows us to
8496       //      remove the call.
8497       IsUniform = true;
8498       break;
8499     default:
8500       break;
8501     }
8502   }
8503 
8504   auto *Recipe = new VPReplicateRecipe(I, Plan->mapToVPValues(I->operands()),
8505                                        IsUniform, IsPredicated);
8506   setRecipe(I, Recipe);
8507   Plan->addVPValue(I, Recipe);
8508 
8509   // Find if I uses a predicated instruction. If so, it will use its scalar
8510   // value. Avoid hoisting the insert-element which packs the scalar value into
8511   // a vector value, as that happens iff all users use the vector value.
8512   for (VPValue *Op : Recipe->operands()) {
8513     auto *PredR = dyn_cast_or_null<VPPredInstPHIRecipe>(Op->getDef());
8514     if (!PredR)
8515       continue;
8516     auto *RepR =
8517         cast_or_null<VPReplicateRecipe>(PredR->getOperand(0)->getDef());
8518     assert(RepR->isPredicated() &&
8519            "expected Replicate recipe to be predicated");
8520     RepR->setAlsoPack(false);
8521   }
8522 
8523   // Finalize the recipe for Instr, first if it is not predicated.
8524   if (!IsPredicated) {
8525     LLVM_DEBUG(dbgs() << "LV: Scalarizing:" << *I << "\n");
8526     VPBB->appendRecipe(Recipe);
8527     return VPBB;
8528   }
8529   LLVM_DEBUG(dbgs() << "LV: Scalarizing and predicating:" << *I << "\n");
8530 
8531   VPBlockBase *SingleSucc = VPBB->getSingleSuccessor();
8532   assert(SingleSucc && "VPBB must have a single successor when handling "
8533                        "predicated replication.");
8534   VPBlockUtils::disconnectBlocks(VPBB, SingleSucc);
8535   // Record predicated instructions for above packing optimizations.
8536   VPBlockBase *Region = createReplicateRegion(I, Recipe, Plan);
8537   VPBlockUtils::insertBlockAfter(Region, VPBB);
8538   auto *RegSucc = new VPBasicBlock();
8539   VPBlockUtils::insertBlockAfter(RegSucc, Region);
8540   VPBlockUtils::connectBlocks(RegSucc, SingleSucc);
8541   return RegSucc;
8542 }
8543 
8544 VPRegionBlock *VPRecipeBuilder::createReplicateRegion(Instruction *Instr,
8545                                                       VPRecipeBase *PredRecipe,
8546                                                       VPlanPtr &Plan) {
8547   // Instructions marked for predication are replicated and placed under an
8548   // if-then construct to prevent side-effects.
8549 
8550   // Generate recipes to compute the block mask for this region.
8551   VPValue *BlockInMask = createBlockInMask(Instr->getParent(), Plan);
8552 
8553   // Build the triangular if-then region.
8554   std::string RegionName = (Twine("pred.") + Instr->getOpcodeName()).str();
8555   assert(Instr->getParent() && "Predicated instruction not in any basic block");
8556   auto *BOMRecipe = new VPBranchOnMaskRecipe(BlockInMask);
8557   auto *Entry = new VPBasicBlock(Twine(RegionName) + ".entry", BOMRecipe);
8558   auto *PHIRecipe = Instr->getType()->isVoidTy()
8559                         ? nullptr
8560                         : new VPPredInstPHIRecipe(Plan->getOrAddVPValue(Instr));
8561   if (PHIRecipe) {
8562     Plan->removeVPValueFor(Instr);
8563     Plan->addVPValue(Instr, PHIRecipe);
8564   }
8565   auto *Exit = new VPBasicBlock(Twine(RegionName) + ".continue", PHIRecipe);
8566   auto *Pred = new VPBasicBlock(Twine(RegionName) + ".if", PredRecipe);
8567   VPRegionBlock *Region = new VPRegionBlock(Entry, Exit, RegionName, true);
8568 
8569   // Note: first set Entry as region entry and then connect successors starting
8570   // from it in order, to propagate the "parent" of each VPBasicBlock.
8571   VPBlockUtils::insertTwoBlocksAfter(Pred, Exit, BlockInMask, Entry);
8572   VPBlockUtils::connectBlocks(Pred, Exit);
8573 
8574   return Region;
8575 }
8576 
8577 VPRecipeOrVPValueTy
8578 VPRecipeBuilder::tryToCreateWidenRecipe(Instruction *Instr,
8579                                         ArrayRef<VPValue *> Operands,
8580                                         VFRange &Range, VPlanPtr &Plan) {
8581   // First, check for specific widening recipes that deal with calls, memory
8582   // operations, inductions and Phi nodes.
8583   if (auto *CI = dyn_cast<CallInst>(Instr))
8584     return toVPRecipeResult(tryToWidenCall(CI, Operands, Range));
8585 
8586   if (isa<LoadInst>(Instr) || isa<StoreInst>(Instr))
8587     return toVPRecipeResult(tryToWidenMemory(Instr, Operands, Range, Plan));
8588 
8589   VPRecipeBase *Recipe;
8590   if (auto Phi = dyn_cast<PHINode>(Instr)) {
8591     if (Phi->getParent() != OrigLoop->getHeader())
8592       return tryToBlend(Phi, Operands, Plan);
8593     if ((Recipe = tryToOptimizeInductionPHI(Phi, Operands, *Plan, Range)))
8594       return toVPRecipeResult(Recipe);
8595 
8596     VPHeaderPHIRecipe *PhiRecipe = nullptr;
8597     assert((Legal->isReductionVariable(Phi) ||
8598             Legal->isFirstOrderRecurrence(Phi)) &&
8599            "can only widen reductions and first-order recurrences here");
8600     VPValue *StartV = Operands[0];
8601     if (Legal->isReductionVariable(Phi)) {
8602       const RecurrenceDescriptor &RdxDesc =
8603           Legal->getReductionVars().find(Phi)->second;
8604       assert(RdxDesc.getRecurrenceStartValue() ==
8605              Phi->getIncomingValueForBlock(OrigLoop->getLoopPreheader()));
8606       PhiRecipe = new VPReductionPHIRecipe(Phi, RdxDesc, *StartV,
8607                                            CM.isInLoopReduction(Phi),
8608                                            CM.useOrderedReductions(RdxDesc));
8609     } else {
8610       PhiRecipe = new VPFirstOrderRecurrencePHIRecipe(Phi, *StartV);
8611     }
8612 
8613       // Record the incoming value from the backedge, so we can add the incoming
8614       // value from the backedge after all recipes have been created.
8615       recordRecipeOf(cast<Instruction>(
8616           Phi->getIncomingValueForBlock(OrigLoop->getLoopLatch())));
8617       PhisToFix.push_back(PhiRecipe);
8618       return toVPRecipeResult(PhiRecipe);
8619   }
8620 
8621   if (isa<TruncInst>(Instr) &&
8622       (Recipe = tryToOptimizeInductionTruncate(cast<TruncInst>(Instr), Operands,
8623                                                Range, *Plan)))
8624     return toVPRecipeResult(Recipe);
8625 
8626   if (!shouldWiden(Instr, Range))
8627     return nullptr;
8628 
8629   if (auto GEP = dyn_cast<GetElementPtrInst>(Instr))
8630     return toVPRecipeResult(new VPWidenGEPRecipe(
8631         GEP, make_range(Operands.begin(), Operands.end()), OrigLoop));
8632 
8633   if (auto *SI = dyn_cast<SelectInst>(Instr)) {
8634     bool InvariantCond =
8635         PSE.getSE()->isLoopInvariant(PSE.getSCEV(SI->getOperand(0)), OrigLoop);
8636     return toVPRecipeResult(new VPWidenSelectRecipe(
8637         *SI, make_range(Operands.begin(), Operands.end()), InvariantCond));
8638   }
8639 
8640   return toVPRecipeResult(tryToWiden(Instr, Operands));
8641 }
8642 
8643 void LoopVectorizationPlanner::buildVPlansWithVPRecipes(ElementCount MinVF,
8644                                                         ElementCount MaxVF) {
8645   assert(OrigLoop->isInnermost() && "Inner loop expected.");
8646 
8647   // Collect instructions from the original loop that will become trivially dead
8648   // in the vectorized loop. We don't need to vectorize these instructions. For
8649   // example, original induction update instructions can become dead because we
8650   // separately emit induction "steps" when generating code for the new loop.
8651   // Similarly, we create a new latch condition when setting up the structure
8652   // of the new loop, so the old one can become dead.
8653   SmallPtrSet<Instruction *, 4> DeadInstructions;
8654   collectTriviallyDeadInstructions(DeadInstructions);
8655 
8656   // Add assume instructions we need to drop to DeadInstructions, to prevent
8657   // them from being added to the VPlan.
8658   // TODO: We only need to drop assumes in blocks that get flattend. If the
8659   // control flow is preserved, we should keep them.
8660   auto &ConditionalAssumes = Legal->getConditionalAssumes();
8661   DeadInstructions.insert(ConditionalAssumes.begin(), ConditionalAssumes.end());
8662 
8663   MapVector<Instruction *, Instruction *> &SinkAfter = Legal->getSinkAfter();
8664   // Dead instructions do not need sinking. Remove them from SinkAfter.
8665   for (Instruction *I : DeadInstructions)
8666     SinkAfter.erase(I);
8667 
8668   // Cannot sink instructions after dead instructions (there won't be any
8669   // recipes for them). Instead, find the first non-dead previous instruction.
8670   for (auto &P : Legal->getSinkAfter()) {
8671     Instruction *SinkTarget = P.second;
8672     Instruction *FirstInst = &*SinkTarget->getParent()->begin();
8673     (void)FirstInst;
8674     while (DeadInstructions.contains(SinkTarget)) {
8675       assert(
8676           SinkTarget != FirstInst &&
8677           "Must find a live instruction (at least the one feeding the "
8678           "first-order recurrence PHI) before reaching beginning of the block");
8679       SinkTarget = SinkTarget->getPrevNode();
8680       assert(SinkTarget != P.first &&
8681              "sink source equals target, no sinking required");
8682     }
8683     P.second = SinkTarget;
8684   }
8685 
8686   auto MaxVFPlusOne = MaxVF.getWithIncrement(1);
8687   for (ElementCount VF = MinVF; ElementCount::isKnownLT(VF, MaxVFPlusOne);) {
8688     VFRange SubRange = {VF, MaxVFPlusOne};
8689     VPlans.push_back(
8690         buildVPlanWithVPRecipes(SubRange, DeadInstructions, SinkAfter));
8691     VF = SubRange.End;
8692   }
8693 }
8694 
8695 // Add a VPCanonicalIVPHIRecipe starting at 0 to the header, a
8696 // CanonicalIVIncrement{NUW} VPInstruction to increment it by VF * UF and a
8697 // BranchOnCount VPInstruction to the latch.
8698 static void addCanonicalIVRecipes(VPlan &Plan, Type *IdxTy, DebugLoc DL,
8699                                   bool HasNUW, bool IsVPlanNative) {
8700   Value *StartIdx = ConstantInt::get(IdxTy, 0);
8701   auto *StartV = Plan.getOrAddVPValue(StartIdx);
8702 
8703   auto *CanonicalIVPHI = new VPCanonicalIVPHIRecipe(StartV, DL);
8704   VPRegionBlock *TopRegion = Plan.getVectorLoopRegion();
8705   VPBasicBlock *Header = TopRegion->getEntryBasicBlock();
8706   Header->insert(CanonicalIVPHI, Header->begin());
8707 
8708   auto *CanonicalIVIncrement =
8709       new VPInstruction(HasNUW ? VPInstruction::CanonicalIVIncrementNUW
8710                                : VPInstruction::CanonicalIVIncrement,
8711                         {CanonicalIVPHI}, DL);
8712   CanonicalIVPHI->addOperand(CanonicalIVIncrement);
8713 
8714   VPBasicBlock *EB = TopRegion->getExitBasicBlock();
8715   if (IsVPlanNative)
8716     EB->setCondBit(nullptr);
8717   EB->appendRecipe(CanonicalIVIncrement);
8718 
8719   auto *BranchOnCount =
8720       new VPInstruction(VPInstruction::BranchOnCount,
8721                         {CanonicalIVIncrement, &Plan.getVectorTripCount()}, DL);
8722   EB->appendRecipe(BranchOnCount);
8723 }
8724 
8725 VPlanPtr LoopVectorizationPlanner::buildVPlanWithVPRecipes(
8726     VFRange &Range, SmallPtrSetImpl<Instruction *> &DeadInstructions,
8727     const MapVector<Instruction *, Instruction *> &SinkAfter) {
8728 
8729   SmallPtrSet<const InterleaveGroup<Instruction> *, 1> InterleaveGroups;
8730 
8731   VPRecipeBuilder RecipeBuilder(OrigLoop, TLI, Legal, CM, PSE, Builder);
8732 
8733   // ---------------------------------------------------------------------------
8734   // Pre-construction: record ingredients whose recipes we'll need to further
8735   // process after constructing the initial VPlan.
8736   // ---------------------------------------------------------------------------
8737 
8738   // Mark instructions we'll need to sink later and their targets as
8739   // ingredients whose recipe we'll need to record.
8740   for (auto &Entry : SinkAfter) {
8741     RecipeBuilder.recordRecipeOf(Entry.first);
8742     RecipeBuilder.recordRecipeOf(Entry.second);
8743   }
8744   for (auto &Reduction : CM.getInLoopReductionChains()) {
8745     PHINode *Phi = Reduction.first;
8746     RecurKind Kind =
8747         Legal->getReductionVars().find(Phi)->second.getRecurrenceKind();
8748     const SmallVector<Instruction *, 4> &ReductionOperations = Reduction.second;
8749 
8750     RecipeBuilder.recordRecipeOf(Phi);
8751     for (auto &R : ReductionOperations) {
8752       RecipeBuilder.recordRecipeOf(R);
8753       // For min/max reductions, where we have a pair of icmp/select, we also
8754       // need to record the ICmp recipe, so it can be removed later.
8755       assert(!RecurrenceDescriptor::isSelectCmpRecurrenceKind(Kind) &&
8756              "Only min/max recurrences allowed for inloop reductions");
8757       if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind))
8758         RecipeBuilder.recordRecipeOf(cast<Instruction>(R->getOperand(0)));
8759     }
8760   }
8761 
8762   // For each interleave group which is relevant for this (possibly trimmed)
8763   // Range, add it to the set of groups to be later applied to the VPlan and add
8764   // placeholders for its members' Recipes which we'll be replacing with a
8765   // single VPInterleaveRecipe.
8766   for (InterleaveGroup<Instruction> *IG : IAI.getInterleaveGroups()) {
8767     auto applyIG = [IG, this](ElementCount VF) -> bool {
8768       return (VF.isVector() && // Query is illegal for VF == 1
8769               CM.getWideningDecision(IG->getInsertPos(), VF) ==
8770                   LoopVectorizationCostModel::CM_Interleave);
8771     };
8772     if (!getDecisionAndClampRange(applyIG, Range))
8773       continue;
8774     InterleaveGroups.insert(IG);
8775     for (unsigned i = 0; i < IG->getFactor(); i++)
8776       if (Instruction *Member = IG->getMember(i))
8777         RecipeBuilder.recordRecipeOf(Member);
8778   };
8779 
8780   // ---------------------------------------------------------------------------
8781   // Build initial VPlan: Scan the body of the loop in a topological order to
8782   // visit each basic block after having visited its predecessor basic blocks.
8783   // ---------------------------------------------------------------------------
8784 
8785   // Create initial VPlan skeleton, starting with a block for the pre-header,
8786   // followed by a region for the vector loop, followed by the middle block. The
8787   // skeleton vector loop region contains a header and latch block.
8788   VPBasicBlock *Preheader = new VPBasicBlock("vector.ph");
8789   auto Plan = std::make_unique<VPlan>(Preheader);
8790 
8791   VPBasicBlock *HeaderVPBB = new VPBasicBlock("vector.body");
8792   VPBasicBlock *LatchVPBB = new VPBasicBlock("vector.latch");
8793   VPBlockUtils::insertBlockAfter(LatchVPBB, HeaderVPBB);
8794   auto *TopRegion = new VPRegionBlock(HeaderVPBB, LatchVPBB, "vector loop");
8795   VPBlockUtils::insertBlockAfter(TopRegion, Preheader);
8796   VPBasicBlock *MiddleVPBB = new VPBasicBlock("middle.block");
8797   VPBlockUtils::insertBlockAfter(MiddleVPBB, TopRegion);
8798 
8799   Instruction *DLInst =
8800       getDebugLocFromInstOrOperands(Legal->getPrimaryInduction());
8801   addCanonicalIVRecipes(*Plan, Legal->getWidestInductionType(),
8802                         DLInst ? DLInst->getDebugLoc() : DebugLoc(),
8803                         !CM.foldTailByMasking(), false);
8804 
8805   // Scan the body of the loop in a topological order to visit each basic block
8806   // after having visited its predecessor basic blocks.
8807   LoopBlocksDFS DFS(OrigLoop);
8808   DFS.perform(LI);
8809 
8810   VPBasicBlock *VPBB = HeaderVPBB;
8811   SmallVector<VPWidenIntOrFpInductionRecipe *> InductionsToMove;
8812   for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) {
8813     // Relevant instructions from basic block BB will be grouped into VPRecipe
8814     // ingredients and fill a new VPBasicBlock.
8815     unsigned VPBBsForBB = 0;
8816     if (VPBB != HeaderVPBB)
8817       VPBB->setName(BB->getName());
8818     Builder.setInsertPoint(VPBB);
8819 
8820     // Introduce each ingredient into VPlan.
8821     // TODO: Model and preserve debug intrinsics in VPlan.
8822     for (Instruction &I : BB->instructionsWithoutDebug()) {
8823       Instruction *Instr = &I;
8824 
8825       // First filter out irrelevant instructions, to ensure no recipes are
8826       // built for them.
8827       if (isa<BranchInst>(Instr) || DeadInstructions.count(Instr))
8828         continue;
8829 
8830       SmallVector<VPValue *, 4> Operands;
8831       auto *Phi = dyn_cast<PHINode>(Instr);
8832       if (Phi && Phi->getParent() == OrigLoop->getHeader()) {
8833         Operands.push_back(Plan->getOrAddVPValue(
8834             Phi->getIncomingValueForBlock(OrigLoop->getLoopPreheader())));
8835       } else {
8836         auto OpRange = Plan->mapToVPValues(Instr->operands());
8837         Operands = {OpRange.begin(), OpRange.end()};
8838       }
8839       if (auto RecipeOrValue = RecipeBuilder.tryToCreateWidenRecipe(
8840               Instr, Operands, Range, Plan)) {
8841         // If Instr can be simplified to an existing VPValue, use it.
8842         if (RecipeOrValue.is<VPValue *>()) {
8843           auto *VPV = RecipeOrValue.get<VPValue *>();
8844           Plan->addVPValue(Instr, VPV);
8845           // If the re-used value is a recipe, register the recipe for the
8846           // instruction, in case the recipe for Instr needs to be recorded.
8847           if (auto *R = dyn_cast_or_null<VPRecipeBase>(VPV->getDef()))
8848             RecipeBuilder.setRecipe(Instr, R);
8849           continue;
8850         }
8851         // Otherwise, add the new recipe.
8852         VPRecipeBase *Recipe = RecipeOrValue.get<VPRecipeBase *>();
8853         for (auto *Def : Recipe->definedValues()) {
8854           auto *UV = Def->getUnderlyingValue();
8855           Plan->addVPValue(UV, Def);
8856         }
8857 
8858         if (isa<VPWidenIntOrFpInductionRecipe>(Recipe) &&
8859             HeaderVPBB->getFirstNonPhi() != VPBB->end()) {
8860           // Keep track of VPWidenIntOrFpInductionRecipes not in the phi section
8861           // of the header block. That can happen for truncates of induction
8862           // variables. Those recipes are moved to the phi section of the header
8863           // block after applying SinkAfter, which relies on the original
8864           // position of the trunc.
8865           assert(isa<TruncInst>(Instr));
8866           InductionsToMove.push_back(
8867               cast<VPWidenIntOrFpInductionRecipe>(Recipe));
8868         }
8869         RecipeBuilder.setRecipe(Instr, Recipe);
8870         VPBB->appendRecipe(Recipe);
8871         continue;
8872       }
8873 
8874       // Invariant stores inside loop will be deleted and a single store
8875       // with the final reduction value will be added to the exit block
8876       StoreInst *SI;
8877       if ((SI = dyn_cast<StoreInst>(&I)) &&
8878           Legal->isInvariantAddressOfReduction(SI->getPointerOperand()))
8879         continue;
8880 
8881       // Otherwise, if all widening options failed, Instruction is to be
8882       // replicated. This may create a successor for VPBB.
8883       VPBasicBlock *NextVPBB =
8884           RecipeBuilder.handleReplication(Instr, Range, VPBB, Plan);
8885       if (NextVPBB != VPBB) {
8886         VPBB = NextVPBB;
8887         VPBB->setName(BB->hasName() ? BB->getName() + "." + Twine(VPBBsForBB++)
8888                                     : "");
8889       }
8890     }
8891 
8892     VPBlockUtils::insertBlockAfter(new VPBasicBlock(), VPBB);
8893     VPBB = cast<VPBasicBlock>(VPBB->getSingleSuccessor());
8894   }
8895 
8896   HeaderVPBB->setName("vector.body");
8897 
8898   // Fold the last, empty block into its predecessor.
8899   VPBB = VPBlockUtils::tryToMergeBlockIntoPredecessor(VPBB);
8900   assert(VPBB && "expected to fold last (empty) block");
8901   // After here, VPBB should not be used.
8902   VPBB = nullptr;
8903 
8904   assert(isa<VPRegionBlock>(Plan->getVectorLoopRegion()) &&
8905          !Plan->getVectorLoopRegion()->getEntryBasicBlock()->empty() &&
8906          "entry block must be set to a VPRegionBlock having a non-empty entry "
8907          "VPBasicBlock");
8908   RecipeBuilder.fixHeaderPhis();
8909 
8910   // ---------------------------------------------------------------------------
8911   // Transform initial VPlan: Apply previously taken decisions, in order, to
8912   // bring the VPlan to its final state.
8913   // ---------------------------------------------------------------------------
8914 
8915   // Apply Sink-After legal constraints.
8916   auto GetReplicateRegion = [](VPRecipeBase *R) -> VPRegionBlock * {
8917     auto *Region = dyn_cast_or_null<VPRegionBlock>(R->getParent()->getParent());
8918     if (Region && Region->isReplicator()) {
8919       assert(Region->getNumSuccessors() == 1 &&
8920              Region->getNumPredecessors() == 1 && "Expected SESE region!");
8921       assert(R->getParent()->size() == 1 &&
8922              "A recipe in an original replicator region must be the only "
8923              "recipe in its block");
8924       return Region;
8925     }
8926     return nullptr;
8927   };
8928   for (auto &Entry : SinkAfter) {
8929     VPRecipeBase *Sink = RecipeBuilder.getRecipe(Entry.first);
8930     VPRecipeBase *Target = RecipeBuilder.getRecipe(Entry.second);
8931 
8932     auto *TargetRegion = GetReplicateRegion(Target);
8933     auto *SinkRegion = GetReplicateRegion(Sink);
8934     if (!SinkRegion) {
8935       // If the sink source is not a replicate region, sink the recipe directly.
8936       if (TargetRegion) {
8937         // The target is in a replication region, make sure to move Sink to
8938         // the block after it, not into the replication region itself.
8939         VPBasicBlock *NextBlock =
8940             cast<VPBasicBlock>(TargetRegion->getSuccessors().front());
8941         Sink->moveBefore(*NextBlock, NextBlock->getFirstNonPhi());
8942       } else
8943         Sink->moveAfter(Target);
8944       continue;
8945     }
8946 
8947     // The sink source is in a replicate region. Unhook the region from the CFG.
8948     auto *SinkPred = SinkRegion->getSinglePredecessor();
8949     auto *SinkSucc = SinkRegion->getSingleSuccessor();
8950     VPBlockUtils::disconnectBlocks(SinkPred, SinkRegion);
8951     VPBlockUtils::disconnectBlocks(SinkRegion, SinkSucc);
8952     VPBlockUtils::connectBlocks(SinkPred, SinkSucc);
8953 
8954     if (TargetRegion) {
8955       // The target recipe is also in a replicate region, move the sink region
8956       // after the target region.
8957       auto *TargetSucc = TargetRegion->getSingleSuccessor();
8958       VPBlockUtils::disconnectBlocks(TargetRegion, TargetSucc);
8959       VPBlockUtils::connectBlocks(TargetRegion, SinkRegion);
8960       VPBlockUtils::connectBlocks(SinkRegion, TargetSucc);
8961     } else {
8962       // The sink source is in a replicate region, we need to move the whole
8963       // replicate region, which should only contain a single recipe in the
8964       // main block.
8965       auto *SplitBlock =
8966           Target->getParent()->splitAt(std::next(Target->getIterator()));
8967 
8968       auto *SplitPred = SplitBlock->getSinglePredecessor();
8969 
8970       VPBlockUtils::disconnectBlocks(SplitPred, SplitBlock);
8971       VPBlockUtils::connectBlocks(SplitPred, SinkRegion);
8972       VPBlockUtils::connectBlocks(SinkRegion, SplitBlock);
8973     }
8974   }
8975 
8976   VPlanTransforms::removeRedundantCanonicalIVs(*Plan);
8977   VPlanTransforms::removeRedundantInductionCasts(*Plan);
8978 
8979   // Now that sink-after is done, move induction recipes for optimized truncates
8980   // to the phi section of the header block.
8981   for (VPWidenIntOrFpInductionRecipe *Ind : InductionsToMove)
8982     Ind->moveBefore(*HeaderVPBB, HeaderVPBB->getFirstNonPhi());
8983 
8984   // Adjust the recipes for any inloop reductions.
8985   adjustRecipesForReductions(cast<VPBasicBlock>(TopRegion->getExit()), Plan,
8986                              RecipeBuilder, Range.Start);
8987 
8988   // Introduce a recipe to combine the incoming and previous values of a
8989   // first-order recurrence.
8990   for (VPRecipeBase &R :
8991        Plan->getVectorLoopRegion()->getEntryBasicBlock()->phis()) {
8992     auto *RecurPhi = dyn_cast<VPFirstOrderRecurrencePHIRecipe>(&R);
8993     if (!RecurPhi)
8994       continue;
8995 
8996     VPRecipeBase *PrevRecipe = RecurPhi->getBackedgeRecipe();
8997     VPBasicBlock *InsertBlock = PrevRecipe->getParent();
8998     auto *Region = GetReplicateRegion(PrevRecipe);
8999     if (Region)
9000       InsertBlock = cast<VPBasicBlock>(Region->getSingleSuccessor());
9001     if (Region || PrevRecipe->isPhi())
9002       Builder.setInsertPoint(InsertBlock, InsertBlock->getFirstNonPhi());
9003     else
9004       Builder.setInsertPoint(InsertBlock, std::next(PrevRecipe->getIterator()));
9005 
9006     auto *RecurSplice = cast<VPInstruction>(
9007         Builder.createNaryOp(VPInstruction::FirstOrderRecurrenceSplice,
9008                              {RecurPhi, RecurPhi->getBackedgeValue()}));
9009 
9010     RecurPhi->replaceAllUsesWith(RecurSplice);
9011     // Set the first operand of RecurSplice to RecurPhi again, after replacing
9012     // all users.
9013     RecurSplice->setOperand(0, RecurPhi);
9014   }
9015 
9016   // Interleave memory: for each Interleave Group we marked earlier as relevant
9017   // for this VPlan, replace the Recipes widening its memory instructions with a
9018   // single VPInterleaveRecipe at its insertion point.
9019   for (auto IG : InterleaveGroups) {
9020     auto *Recipe = cast<VPWidenMemoryInstructionRecipe>(
9021         RecipeBuilder.getRecipe(IG->getInsertPos()));
9022     SmallVector<VPValue *, 4> StoredValues;
9023     for (unsigned i = 0; i < IG->getFactor(); ++i)
9024       if (auto *SI = dyn_cast_or_null<StoreInst>(IG->getMember(i))) {
9025         auto *StoreR =
9026             cast<VPWidenMemoryInstructionRecipe>(RecipeBuilder.getRecipe(SI));
9027         StoredValues.push_back(StoreR->getStoredValue());
9028       }
9029 
9030     auto *VPIG = new VPInterleaveRecipe(IG, Recipe->getAddr(), StoredValues,
9031                                         Recipe->getMask());
9032     VPIG->insertBefore(Recipe);
9033     unsigned J = 0;
9034     for (unsigned i = 0; i < IG->getFactor(); ++i)
9035       if (Instruction *Member = IG->getMember(i)) {
9036         if (!Member->getType()->isVoidTy()) {
9037           VPValue *OriginalV = Plan->getVPValue(Member);
9038           Plan->removeVPValueFor(Member);
9039           Plan->addVPValue(Member, VPIG->getVPValue(J));
9040           OriginalV->replaceAllUsesWith(VPIG->getVPValue(J));
9041           J++;
9042         }
9043         RecipeBuilder.getRecipe(Member)->eraseFromParent();
9044       }
9045   }
9046 
9047   // From this point onwards, VPlan-to-VPlan transformations may change the plan
9048   // in ways that accessing values using original IR values is incorrect.
9049   Plan->disableValue2VPValue();
9050 
9051   VPlanTransforms::optimizeInductions(*Plan, *PSE.getSE());
9052   VPlanTransforms::sinkScalarOperands(*Plan);
9053   VPlanTransforms::mergeReplicateRegions(*Plan);
9054   VPlanTransforms::removeDeadRecipes(*Plan, *OrigLoop);
9055   VPlanTransforms::removeRedundantExpandSCEVRecipes(*Plan);
9056 
9057   std::string PlanName;
9058   raw_string_ostream RSO(PlanName);
9059   ElementCount VF = Range.Start;
9060   Plan->addVF(VF);
9061   RSO << "Initial VPlan for VF={" << VF;
9062   for (VF *= 2; ElementCount::isKnownLT(VF, Range.End); VF *= 2) {
9063     Plan->addVF(VF);
9064     RSO << "," << VF;
9065   }
9066   RSO << "},UF>=1";
9067   RSO.flush();
9068   Plan->setName(PlanName);
9069 
9070   // Fold Exit block into its predecessor if possible.
9071   // TODO: Fold block earlier once all VPlan transforms properly maintain a
9072   // VPBasicBlock as exit.
9073   VPBlockUtils::tryToMergeBlockIntoPredecessor(TopRegion->getExit());
9074 
9075   assert(VPlanVerifier::verifyPlanIsValid(*Plan) && "VPlan is invalid");
9076   return Plan;
9077 }
9078 
9079 VPlanPtr LoopVectorizationPlanner::buildVPlan(VFRange &Range) {
9080   // Outer loop handling: They may require CFG and instruction level
9081   // transformations before even evaluating whether vectorization is profitable.
9082   // Since we cannot modify the incoming IR, we need to build VPlan upfront in
9083   // the vectorization pipeline.
9084   assert(!OrigLoop->isInnermost());
9085   assert(EnableVPlanNativePath && "VPlan-native path is not enabled.");
9086 
9087   // Create new empty VPlan
9088   auto Plan = std::make_unique<VPlan>();
9089 
9090   // Build hierarchical CFG
9091   VPlanHCFGBuilder HCFGBuilder(OrigLoop, LI, *Plan);
9092   HCFGBuilder.buildHierarchicalCFG();
9093 
9094   for (ElementCount VF = Range.Start; ElementCount::isKnownLT(VF, Range.End);
9095        VF *= 2)
9096     Plan->addVF(VF);
9097 
9098   if (EnableVPlanPredication) {
9099     VPlanPredicator VPP(*Plan);
9100     VPP.predicate();
9101 
9102     // Avoid running transformation to recipes until masked code generation in
9103     // VPlan-native path is in place.
9104     return Plan;
9105   }
9106 
9107   SmallPtrSet<Instruction *, 1> DeadInstructions;
9108   VPlanTransforms::VPInstructionsToVPRecipes(
9109       OrigLoop, Plan,
9110       [this](PHINode *P) { return Legal->getIntOrFpInductionDescriptor(P); },
9111       DeadInstructions, *PSE.getSE());
9112 
9113   // Update plan to be compatible with the inner loop vectorizer for
9114   // code-generation.
9115   VPRegionBlock *LoopRegion = Plan->getVectorLoopRegion();
9116   VPBasicBlock *Preheader = LoopRegion->getEntryBasicBlock();
9117   VPBasicBlock *Exit = LoopRegion->getExitBasicBlock();
9118   VPBlockBase *Latch = Exit->getSinglePredecessor();
9119   VPBlockBase *Header = Preheader->getSingleSuccessor();
9120 
9121   // 1. Move preheader block out of main vector loop.
9122   Preheader->setParent(LoopRegion->getParent());
9123   VPBlockUtils::disconnectBlocks(Preheader, Header);
9124   VPBlockUtils::connectBlocks(Preheader, LoopRegion);
9125   Plan->setEntry(Preheader);
9126 
9127   // 2. Disconnect backedge and exit block.
9128   VPBlockUtils::disconnectBlocks(Latch, Header);
9129   VPBlockUtils::disconnectBlocks(Latch, Exit);
9130 
9131   // 3. Update entry and exit of main vector loop region.
9132   LoopRegion->setEntry(Header);
9133   LoopRegion->setExit(Latch);
9134 
9135   // 4. Remove exit block.
9136   delete Exit;
9137 
9138   addCanonicalIVRecipes(*Plan, Legal->getWidestInductionType(), DebugLoc(),
9139                         true, true);
9140   return Plan;
9141 }
9142 
9143 // Adjust the recipes for reductions. For in-loop reductions the chain of
9144 // instructions leading from the loop exit instr to the phi need to be converted
9145 // to reductions, with one operand being vector and the other being the scalar
9146 // reduction chain. For other reductions, a select is introduced between the phi
9147 // and live-out recipes when folding the tail.
9148 void LoopVectorizationPlanner::adjustRecipesForReductions(
9149     VPBasicBlock *LatchVPBB, VPlanPtr &Plan, VPRecipeBuilder &RecipeBuilder,
9150     ElementCount MinVF) {
9151   for (auto &Reduction : CM.getInLoopReductionChains()) {
9152     PHINode *Phi = Reduction.first;
9153     const RecurrenceDescriptor &RdxDesc =
9154         Legal->getReductionVars().find(Phi)->second;
9155     const SmallVector<Instruction *, 4> &ReductionOperations = Reduction.second;
9156 
9157     if (MinVF.isScalar() && !CM.useOrderedReductions(RdxDesc))
9158       continue;
9159 
9160     // ReductionOperations are orders top-down from the phi's use to the
9161     // LoopExitValue. We keep a track of the previous item (the Chain) to tell
9162     // which of the two operands will remain scalar and which will be reduced.
9163     // For minmax the chain will be the select instructions.
9164     Instruction *Chain = Phi;
9165     for (Instruction *R : ReductionOperations) {
9166       VPRecipeBase *WidenRecipe = RecipeBuilder.getRecipe(R);
9167       RecurKind Kind = RdxDesc.getRecurrenceKind();
9168 
9169       VPValue *ChainOp = Plan->getVPValue(Chain);
9170       unsigned FirstOpId;
9171       assert(!RecurrenceDescriptor::isSelectCmpRecurrenceKind(Kind) &&
9172              "Only min/max recurrences allowed for inloop reductions");
9173       // Recognize a call to the llvm.fmuladd intrinsic.
9174       bool IsFMulAdd = (Kind == RecurKind::FMulAdd);
9175       assert((!IsFMulAdd || RecurrenceDescriptor::isFMulAddIntrinsic(R)) &&
9176              "Expected instruction to be a call to the llvm.fmuladd intrinsic");
9177       if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind)) {
9178         assert(isa<VPWidenSelectRecipe>(WidenRecipe) &&
9179                "Expected to replace a VPWidenSelectSC");
9180         FirstOpId = 1;
9181       } else {
9182         assert((MinVF.isScalar() || isa<VPWidenRecipe>(WidenRecipe) ||
9183                 (IsFMulAdd && isa<VPWidenCallRecipe>(WidenRecipe))) &&
9184                "Expected to replace a VPWidenSC");
9185         FirstOpId = 0;
9186       }
9187       unsigned VecOpId =
9188           R->getOperand(FirstOpId) == Chain ? FirstOpId + 1 : FirstOpId;
9189       VPValue *VecOp = Plan->getVPValue(R->getOperand(VecOpId));
9190 
9191       auto *CondOp = CM.blockNeedsPredicationForAnyReason(R->getParent())
9192                          ? RecipeBuilder.createBlockInMask(R->getParent(), Plan)
9193                          : nullptr;
9194 
9195       if (IsFMulAdd) {
9196         // If the instruction is a call to the llvm.fmuladd intrinsic then we
9197         // need to create an fmul recipe to use as the vector operand for the
9198         // fadd reduction.
9199         VPInstruction *FMulRecipe = new VPInstruction(
9200             Instruction::FMul, {VecOp, Plan->getVPValue(R->getOperand(1))});
9201         FMulRecipe->setFastMathFlags(R->getFastMathFlags());
9202         WidenRecipe->getParent()->insert(FMulRecipe,
9203                                          WidenRecipe->getIterator());
9204         VecOp = FMulRecipe;
9205       }
9206       VPReductionRecipe *RedRecipe =
9207           new VPReductionRecipe(&RdxDesc, R, ChainOp, VecOp, CondOp, TTI);
9208       WidenRecipe->getVPSingleValue()->replaceAllUsesWith(RedRecipe);
9209       Plan->removeVPValueFor(R);
9210       Plan->addVPValue(R, RedRecipe);
9211       WidenRecipe->getParent()->insert(RedRecipe, WidenRecipe->getIterator());
9212       WidenRecipe->getVPSingleValue()->replaceAllUsesWith(RedRecipe);
9213       WidenRecipe->eraseFromParent();
9214 
9215       if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind)) {
9216         VPRecipeBase *CompareRecipe =
9217             RecipeBuilder.getRecipe(cast<Instruction>(R->getOperand(0)));
9218         assert(isa<VPWidenRecipe>(CompareRecipe) &&
9219                "Expected to replace a VPWidenSC");
9220         assert(cast<VPWidenRecipe>(CompareRecipe)->getNumUsers() == 0 &&
9221                "Expected no remaining users");
9222         CompareRecipe->eraseFromParent();
9223       }
9224       Chain = R;
9225     }
9226   }
9227 
9228   // If tail is folded by masking, introduce selects between the phi
9229   // and the live-out instruction of each reduction, at the beginning of the
9230   // dedicated latch block.
9231   if (CM.foldTailByMasking()) {
9232     Builder.setInsertPoint(LatchVPBB, LatchVPBB->begin());
9233     for (VPRecipeBase &R :
9234          Plan->getVectorLoopRegion()->getEntryBasicBlock()->phis()) {
9235       VPReductionPHIRecipe *PhiR = dyn_cast<VPReductionPHIRecipe>(&R);
9236       if (!PhiR || PhiR->isInLoop())
9237         continue;
9238       VPValue *Cond =
9239           RecipeBuilder.createBlockInMask(OrigLoop->getHeader(), Plan);
9240       VPValue *Red = PhiR->getBackedgeValue();
9241       assert(cast<VPRecipeBase>(Red->getDef())->getParent() != LatchVPBB &&
9242              "reduction recipe must be defined before latch");
9243       Builder.createNaryOp(Instruction::Select, {Cond, Red, PhiR});
9244     }
9245   }
9246 }
9247 
9248 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
9249 void VPInterleaveRecipe::print(raw_ostream &O, const Twine &Indent,
9250                                VPSlotTracker &SlotTracker) const {
9251   O << Indent << "INTERLEAVE-GROUP with factor " << IG->getFactor() << " at ";
9252   IG->getInsertPos()->printAsOperand(O, false);
9253   O << ", ";
9254   getAddr()->printAsOperand(O, SlotTracker);
9255   VPValue *Mask = getMask();
9256   if (Mask) {
9257     O << ", ";
9258     Mask->printAsOperand(O, SlotTracker);
9259   }
9260 
9261   unsigned OpIdx = 0;
9262   for (unsigned i = 0; i < IG->getFactor(); ++i) {
9263     if (!IG->getMember(i))
9264       continue;
9265     if (getNumStoreOperands() > 0) {
9266       O << "\n" << Indent << "  store ";
9267       getOperand(1 + OpIdx)->printAsOperand(O, SlotTracker);
9268       O << " to index " << i;
9269     } else {
9270       O << "\n" << Indent << "  ";
9271       getVPValue(OpIdx)->printAsOperand(O, SlotTracker);
9272       O << " = load from index " << i;
9273     }
9274     ++OpIdx;
9275   }
9276 }
9277 #endif
9278 
9279 void VPWidenCallRecipe::execute(VPTransformState &State) {
9280   State.ILV->widenCallInstruction(*cast<CallInst>(getUnderlyingInstr()), this,
9281                                   *this, State);
9282 }
9283 
9284 void VPWidenSelectRecipe::execute(VPTransformState &State) {
9285   auto &I = *cast<SelectInst>(getUnderlyingInstr());
9286   State.ILV->setDebugLocFromInst(&I);
9287 
9288   // The condition can be loop invariant  but still defined inside the
9289   // loop. This means that we can't just use the original 'cond' value.
9290   // We have to take the 'vectorized' value and pick the first lane.
9291   // Instcombine will make this a no-op.
9292   auto *InvarCond =
9293       InvariantCond ? State.get(getOperand(0), VPIteration(0, 0)) : nullptr;
9294 
9295   for (unsigned Part = 0; Part < State.UF; ++Part) {
9296     Value *Cond = InvarCond ? InvarCond : State.get(getOperand(0), Part);
9297     Value *Op0 = State.get(getOperand(1), Part);
9298     Value *Op1 = State.get(getOperand(2), Part);
9299     Value *Sel = State.Builder.CreateSelect(Cond, Op0, Op1);
9300     State.set(this, Sel, Part);
9301     State.ILV->addMetadata(Sel, &I);
9302   }
9303 }
9304 
9305 void VPWidenRecipe::execute(VPTransformState &State) {
9306   auto &I = *cast<Instruction>(getUnderlyingValue());
9307   auto &Builder = State.Builder;
9308   switch (I.getOpcode()) {
9309   case Instruction::Call:
9310   case Instruction::Br:
9311   case Instruction::PHI:
9312   case Instruction::GetElementPtr:
9313   case Instruction::Select:
9314     llvm_unreachable("This instruction is handled by a different recipe.");
9315   case Instruction::UDiv:
9316   case Instruction::SDiv:
9317   case Instruction::SRem:
9318   case Instruction::URem:
9319   case Instruction::Add:
9320   case Instruction::FAdd:
9321   case Instruction::Sub:
9322   case Instruction::FSub:
9323   case Instruction::FNeg:
9324   case Instruction::Mul:
9325   case Instruction::FMul:
9326   case Instruction::FDiv:
9327   case Instruction::FRem:
9328   case Instruction::Shl:
9329   case Instruction::LShr:
9330   case Instruction::AShr:
9331   case Instruction::And:
9332   case Instruction::Or:
9333   case Instruction::Xor: {
9334     // Just widen unops and binops.
9335     State.ILV->setDebugLocFromInst(&I);
9336 
9337     for (unsigned Part = 0; Part < State.UF; ++Part) {
9338       SmallVector<Value *, 2> Ops;
9339       for (VPValue *VPOp : operands())
9340         Ops.push_back(State.get(VPOp, Part));
9341 
9342       Value *V = Builder.CreateNAryOp(I.getOpcode(), Ops);
9343 
9344       if (auto *VecOp = dyn_cast<Instruction>(V)) {
9345         VecOp->copyIRFlags(&I);
9346 
9347         // If the instruction is vectorized and was in a basic block that needed
9348         // predication, we can't propagate poison-generating flags (nuw/nsw,
9349         // exact, etc.). The control flow has been linearized and the
9350         // instruction is no longer guarded by the predicate, which could make
9351         // the flag properties to no longer hold.
9352         if (State.MayGeneratePoisonRecipes.contains(this))
9353           VecOp->dropPoisonGeneratingFlags();
9354       }
9355 
9356       // Use this vector value for all users of the original instruction.
9357       State.set(this, V, Part);
9358       State.ILV->addMetadata(V, &I);
9359     }
9360 
9361     break;
9362   }
9363   case Instruction::ICmp:
9364   case Instruction::FCmp: {
9365     // Widen compares. Generate vector compares.
9366     bool FCmp = (I.getOpcode() == Instruction::FCmp);
9367     auto *Cmp = cast<CmpInst>(&I);
9368     State.ILV->setDebugLocFromInst(Cmp);
9369     for (unsigned Part = 0; Part < State.UF; ++Part) {
9370       Value *A = State.get(getOperand(0), Part);
9371       Value *B = State.get(getOperand(1), Part);
9372       Value *C = nullptr;
9373       if (FCmp) {
9374         // Propagate fast math flags.
9375         IRBuilder<>::FastMathFlagGuard FMFG(Builder);
9376         Builder.setFastMathFlags(Cmp->getFastMathFlags());
9377         C = Builder.CreateFCmp(Cmp->getPredicate(), A, B);
9378       } else {
9379         C = Builder.CreateICmp(Cmp->getPredicate(), A, B);
9380       }
9381       State.set(this, C, Part);
9382       State.ILV->addMetadata(C, &I);
9383     }
9384 
9385     break;
9386   }
9387 
9388   case Instruction::ZExt:
9389   case Instruction::SExt:
9390   case Instruction::FPToUI:
9391   case Instruction::FPToSI:
9392   case Instruction::FPExt:
9393   case Instruction::PtrToInt:
9394   case Instruction::IntToPtr:
9395   case Instruction::SIToFP:
9396   case Instruction::UIToFP:
9397   case Instruction::Trunc:
9398   case Instruction::FPTrunc:
9399   case Instruction::BitCast: {
9400     auto *CI = cast<CastInst>(&I);
9401     State.ILV->setDebugLocFromInst(CI);
9402 
9403     /// Vectorize casts.
9404     Type *DestTy = (State.VF.isScalar())
9405                        ? CI->getType()
9406                        : VectorType::get(CI->getType(), State.VF);
9407 
9408     for (unsigned Part = 0; Part < State.UF; ++Part) {
9409       Value *A = State.get(getOperand(0), Part);
9410       Value *Cast = Builder.CreateCast(CI->getOpcode(), A, DestTy);
9411       State.set(this, Cast, Part);
9412       State.ILV->addMetadata(Cast, &I);
9413     }
9414     break;
9415   }
9416   default:
9417     // This instruction is not vectorized by simple widening.
9418     LLVM_DEBUG(dbgs() << "LV: Found an unhandled instruction: " << I);
9419     llvm_unreachable("Unhandled instruction!");
9420   } // end of switch.
9421 }
9422 
9423 void VPWidenGEPRecipe::execute(VPTransformState &State) {
9424   auto *GEP = cast<GetElementPtrInst>(getUnderlyingInstr());
9425   // Construct a vector GEP by widening the operands of the scalar GEP as
9426   // necessary. We mark the vector GEP 'inbounds' if appropriate. A GEP
9427   // results in a vector of pointers when at least one operand of the GEP
9428   // is vector-typed. Thus, to keep the representation compact, we only use
9429   // vector-typed operands for loop-varying values.
9430 
9431   if (State.VF.isVector() && IsPtrLoopInvariant && IsIndexLoopInvariant.all()) {
9432     // If we are vectorizing, but the GEP has only loop-invariant operands,
9433     // the GEP we build (by only using vector-typed operands for
9434     // loop-varying values) would be a scalar pointer. Thus, to ensure we
9435     // produce a vector of pointers, we need to either arbitrarily pick an
9436     // operand to broadcast, or broadcast a clone of the original GEP.
9437     // Here, we broadcast a clone of the original.
9438     //
9439     // TODO: If at some point we decide to scalarize instructions having
9440     //       loop-invariant operands, this special case will no longer be
9441     //       required. We would add the scalarization decision to
9442     //       collectLoopScalars() and teach getVectorValue() to broadcast
9443     //       the lane-zero scalar value.
9444     auto *Clone = State.Builder.Insert(GEP->clone());
9445     for (unsigned Part = 0; Part < State.UF; ++Part) {
9446       Value *EntryPart = State.Builder.CreateVectorSplat(State.VF, Clone);
9447       State.set(this, EntryPart, Part);
9448       State.ILV->addMetadata(EntryPart, GEP);
9449     }
9450   } else {
9451     // If the GEP has at least one loop-varying operand, we are sure to
9452     // produce a vector of pointers. But if we are only unrolling, we want
9453     // to produce a scalar GEP for each unroll part. Thus, the GEP we
9454     // produce with the code below will be scalar (if VF == 1) or vector
9455     // (otherwise). Note that for the unroll-only case, we still maintain
9456     // values in the vector mapping with initVector, as we do for other
9457     // instructions.
9458     for (unsigned Part = 0; Part < State.UF; ++Part) {
9459       // The pointer operand of the new GEP. If it's loop-invariant, we
9460       // won't broadcast it.
9461       auto *Ptr = IsPtrLoopInvariant
9462                       ? State.get(getOperand(0), VPIteration(0, 0))
9463                       : State.get(getOperand(0), Part);
9464 
9465       // Collect all the indices for the new GEP. If any index is
9466       // loop-invariant, we won't broadcast it.
9467       SmallVector<Value *, 4> Indices;
9468       for (unsigned I = 1, E = getNumOperands(); I < E; I++) {
9469         VPValue *Operand = getOperand(I);
9470         if (IsIndexLoopInvariant[I - 1])
9471           Indices.push_back(State.get(Operand, VPIteration(0, 0)));
9472         else
9473           Indices.push_back(State.get(Operand, Part));
9474       }
9475 
9476       // If the GEP instruction is vectorized and was in a basic block that
9477       // needed predication, we can't propagate the poison-generating 'inbounds'
9478       // flag. The control flow has been linearized and the GEP is no longer
9479       // guarded by the predicate, which could make the 'inbounds' properties to
9480       // no longer hold.
9481       bool IsInBounds =
9482           GEP->isInBounds() && State.MayGeneratePoisonRecipes.count(this) == 0;
9483 
9484       // Create the new GEP. Note that this GEP may be a scalar if VF == 1,
9485       // but it should be a vector, otherwise.
9486       auto *NewGEP = State.Builder.CreateGEP(GEP->getSourceElementType(), Ptr,
9487                                              Indices, "", IsInBounds);
9488       assert((State.VF.isScalar() || NewGEP->getType()->isVectorTy()) &&
9489              "NewGEP is not a pointer vector");
9490       State.set(this, NewGEP, Part);
9491       State.ILV->addMetadata(NewGEP, GEP);
9492     }
9493   }
9494 }
9495 
9496 void VPWidenIntOrFpInductionRecipe::execute(VPTransformState &State) {
9497   assert(!State.Instance && "Int or FP induction being replicated.");
9498 
9499   Value *Start = getStartValue()->getLiveInIRValue();
9500   const InductionDescriptor &ID = getInductionDescriptor();
9501   TruncInst *Trunc = getTruncInst();
9502   IRBuilderBase &Builder = State.Builder;
9503   assert(IV->getType() == ID.getStartValue()->getType() && "Types must match");
9504   assert(State.VF.isVector() && "must have vector VF");
9505 
9506   // The value from the original loop to which we are mapping the new induction
9507   // variable.
9508   Instruction *EntryVal = Trunc ? cast<Instruction>(Trunc) : IV;
9509 
9510   // Fast-math-flags propagate from the original induction instruction.
9511   IRBuilder<>::FastMathFlagGuard FMFG(Builder);
9512   if (ID.getInductionBinOp() && isa<FPMathOperator>(ID.getInductionBinOp()))
9513     Builder.setFastMathFlags(ID.getInductionBinOp()->getFastMathFlags());
9514 
9515   // Now do the actual transformations, and start with fetching the step value.
9516   Value *Step = State.get(getStepValue(), VPIteration(0, 0));
9517 
9518   assert((isa<PHINode>(EntryVal) || isa<TruncInst>(EntryVal)) &&
9519          "Expected either an induction phi-node or a truncate of it!");
9520 
9521   // Construct the initial value of the vector IV in the vector loop preheader
9522   auto CurrIP = Builder.saveIP();
9523   BasicBlock *VectorPH = State.CFG.getPreheaderBBFor(this);
9524   Builder.SetInsertPoint(VectorPH->getTerminator());
9525   if (isa<TruncInst>(EntryVal)) {
9526     assert(Start->getType()->isIntegerTy() &&
9527            "Truncation requires an integer type");
9528     auto *TruncType = cast<IntegerType>(EntryVal->getType());
9529     Step = Builder.CreateTrunc(Step, TruncType);
9530     Start = Builder.CreateCast(Instruction::Trunc, Start, TruncType);
9531   }
9532 
9533   Value *Zero = getSignedIntOrFpConstant(Start->getType(), 0);
9534   Value *SplatStart = Builder.CreateVectorSplat(State.VF, Start);
9535   Value *SteppedStart = getStepVector(
9536       SplatStart, Zero, Step, ID.getInductionOpcode(), State.VF, State.Builder);
9537 
9538   // We create vector phi nodes for both integer and floating-point induction
9539   // variables. Here, we determine the kind of arithmetic we will perform.
9540   Instruction::BinaryOps AddOp;
9541   Instruction::BinaryOps MulOp;
9542   if (Step->getType()->isIntegerTy()) {
9543     AddOp = Instruction::Add;
9544     MulOp = Instruction::Mul;
9545   } else {
9546     AddOp = ID.getInductionOpcode();
9547     MulOp = Instruction::FMul;
9548   }
9549 
9550   // Multiply the vectorization factor by the step using integer or
9551   // floating-point arithmetic as appropriate.
9552   Type *StepType = Step->getType();
9553   Value *RuntimeVF;
9554   if (Step->getType()->isFloatingPointTy())
9555     RuntimeVF = getRuntimeVFAsFloat(Builder, StepType, State.VF);
9556   else
9557     RuntimeVF = getRuntimeVF(Builder, StepType, State.VF);
9558   Value *Mul = Builder.CreateBinOp(MulOp, Step, RuntimeVF);
9559 
9560   // Create a vector splat to use in the induction update.
9561   //
9562   // FIXME: If the step is non-constant, we create the vector splat with
9563   //        IRBuilder. IRBuilder can constant-fold the multiply, but it doesn't
9564   //        handle a constant vector splat.
9565   Value *SplatVF = isa<Constant>(Mul)
9566                        ? ConstantVector::getSplat(State.VF, cast<Constant>(Mul))
9567                        : Builder.CreateVectorSplat(State.VF, Mul);
9568   Builder.restoreIP(CurrIP);
9569 
9570   // We may need to add the step a number of times, depending on the unroll
9571   // factor. The last of those goes into the PHI.
9572   PHINode *VecInd = PHINode::Create(SteppedStart->getType(), 2, "vec.ind",
9573                                     &*State.CFG.PrevBB->getFirstInsertionPt());
9574   VecInd->setDebugLoc(EntryVal->getDebugLoc());
9575   Instruction *LastInduction = VecInd;
9576   for (unsigned Part = 0; Part < State.UF; ++Part) {
9577     State.set(this, LastInduction, Part);
9578 
9579     if (isa<TruncInst>(EntryVal))
9580       State.ILV->addMetadata(LastInduction, EntryVal);
9581 
9582     LastInduction = cast<Instruction>(
9583         Builder.CreateBinOp(AddOp, LastInduction, SplatVF, "step.add"));
9584     LastInduction->setDebugLoc(EntryVal->getDebugLoc());
9585   }
9586 
9587   LastInduction->setName("vec.ind.next");
9588   VecInd->addIncoming(SteppedStart, VectorPH);
9589   // Add induction update using an incorrect block temporarily. The phi node
9590   // will be fixed after VPlan execution. Note that at this point the latch
9591   // block cannot be used, as it does not exist yet.
9592   // TODO: Model increment value in VPlan, by turning the recipe into a
9593   // multi-def and a subclass of VPHeaderPHIRecipe.
9594   VecInd->addIncoming(LastInduction, VectorPH);
9595 }
9596 
9597 void VPWidenPointerInductionRecipe::execute(VPTransformState &State) {
9598   assert(IndDesc.getKind() == InductionDescriptor::IK_PtrInduction &&
9599          "Not a pointer induction according to InductionDescriptor!");
9600   assert(cast<PHINode>(getUnderlyingInstr())->getType()->isPointerTy() &&
9601          "Unexpected type.");
9602 
9603   auto *IVR = getParent()->getPlan()->getCanonicalIV();
9604   PHINode *CanonicalIV = cast<PHINode>(State.get(IVR, 0));
9605 
9606   if (all_of(users(), [this](const VPUser *U) {
9607         return cast<VPRecipeBase>(U)->usesScalars(this);
9608       })) {
9609     // This is the normalized GEP that starts counting at zero.
9610     Value *PtrInd = State.Builder.CreateSExtOrTrunc(
9611         CanonicalIV, IndDesc.getStep()->getType());
9612     // Determine the number of scalars we need to generate for each unroll
9613     // iteration. If the instruction is uniform, we only need to generate the
9614     // first lane. Otherwise, we generate all VF values.
9615     bool IsUniform = vputils::onlyFirstLaneUsed(this);
9616     assert((IsUniform || !State.VF.isScalable()) &&
9617            "Cannot scalarize a scalable VF");
9618     unsigned Lanes = IsUniform ? 1 : State.VF.getFixedValue();
9619 
9620     for (unsigned Part = 0; Part < State.UF; ++Part) {
9621       Value *PartStart =
9622           createStepForVF(State.Builder, PtrInd->getType(), State.VF, Part);
9623 
9624       for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
9625         Value *Idx = State.Builder.CreateAdd(
9626             PartStart, ConstantInt::get(PtrInd->getType(), Lane));
9627         Value *GlobalIdx = State.Builder.CreateAdd(PtrInd, Idx);
9628 
9629         Value *Step = CreateStepValue(IndDesc.getStep(), SE,
9630                                       State.CFG.PrevBB->getTerminator());
9631         Value *SclrGep = emitTransformedIndex(
9632             State.Builder, GlobalIdx, IndDesc.getStartValue(), Step, IndDesc);
9633         SclrGep->setName("next.gep");
9634         State.set(this, SclrGep, VPIteration(Part, Lane));
9635       }
9636     }
9637     return;
9638   }
9639 
9640   assert(isa<SCEVConstant>(IndDesc.getStep()) &&
9641          "Induction step not a SCEV constant!");
9642   Type *PhiType = IndDesc.getStep()->getType();
9643 
9644   // Build a pointer phi
9645   Value *ScalarStartValue = getStartValue()->getLiveInIRValue();
9646   Type *ScStValueType = ScalarStartValue->getType();
9647   PHINode *NewPointerPhi =
9648       PHINode::Create(ScStValueType, 2, "pointer.phi", CanonicalIV);
9649 
9650   BasicBlock *VectorPH = State.CFG.getPreheaderBBFor(this);
9651   NewPointerPhi->addIncoming(ScalarStartValue, VectorPH);
9652 
9653   // A pointer induction, performed by using a gep
9654   const DataLayout &DL = NewPointerPhi->getModule()->getDataLayout();
9655   Instruction *InductionLoc = &*State.Builder.GetInsertPoint();
9656 
9657   const SCEV *ScalarStep = IndDesc.getStep();
9658   SCEVExpander Exp(SE, DL, "induction");
9659   Value *ScalarStepValue = Exp.expandCodeFor(ScalarStep, PhiType, InductionLoc);
9660   Value *RuntimeVF = getRuntimeVF(State.Builder, PhiType, State.VF);
9661   Value *NumUnrolledElems =
9662       State.Builder.CreateMul(RuntimeVF, ConstantInt::get(PhiType, State.UF));
9663   Value *InductionGEP = GetElementPtrInst::Create(
9664       IndDesc.getElementType(), NewPointerPhi,
9665       State.Builder.CreateMul(ScalarStepValue, NumUnrolledElems), "ptr.ind",
9666       InductionLoc);
9667   // Add induction update using an incorrect block temporarily. The phi node
9668   // will be fixed after VPlan execution. Note that at this point the latch
9669   // block cannot be used, as it does not exist yet.
9670   // TODO: Model increment value in VPlan, by turning the recipe into a
9671   // multi-def and a subclass of VPHeaderPHIRecipe.
9672   NewPointerPhi->addIncoming(InductionGEP, VectorPH);
9673 
9674   // Create UF many actual address geps that use the pointer
9675   // phi as base and a vectorized version of the step value
9676   // (<step*0, ..., step*N>) as offset.
9677   for (unsigned Part = 0; Part < State.UF; ++Part) {
9678     Type *VecPhiType = VectorType::get(PhiType, State.VF);
9679     Value *StartOffsetScalar =
9680         State.Builder.CreateMul(RuntimeVF, ConstantInt::get(PhiType, Part));
9681     Value *StartOffset =
9682         State.Builder.CreateVectorSplat(State.VF, StartOffsetScalar);
9683     // Create a vector of consecutive numbers from zero to VF.
9684     StartOffset = State.Builder.CreateAdd(
9685         StartOffset, State.Builder.CreateStepVector(VecPhiType));
9686 
9687     Value *GEP = State.Builder.CreateGEP(
9688         IndDesc.getElementType(), NewPointerPhi,
9689         State.Builder.CreateMul(
9690             StartOffset,
9691             State.Builder.CreateVectorSplat(State.VF, ScalarStepValue),
9692             "vector.gep"));
9693     State.set(this, GEP, Part);
9694   }
9695 }
9696 
9697 void VPScalarIVStepsRecipe::execute(VPTransformState &State) {
9698   assert(!State.Instance && "VPScalarIVStepsRecipe being replicated.");
9699 
9700   // Fast-math-flags propagate from the original induction instruction.
9701   IRBuilder<>::FastMathFlagGuard FMFG(State.Builder);
9702   if (IndDesc.getInductionBinOp() &&
9703       isa<FPMathOperator>(IndDesc.getInductionBinOp()))
9704     State.Builder.setFastMathFlags(
9705         IndDesc.getInductionBinOp()->getFastMathFlags());
9706 
9707   Value *Step = State.get(getStepValue(), VPIteration(0, 0));
9708   auto CreateScalarIV = [&](Value *&Step) -> Value * {
9709     Value *ScalarIV = State.get(getCanonicalIV(), VPIteration(0, 0));
9710     auto *CanonicalIV = State.get(getParent()->getPlan()->getCanonicalIV(), 0);
9711     if (!isCanonical() || CanonicalIV->getType() != Ty) {
9712       ScalarIV =
9713           Ty->isIntegerTy()
9714               ? State.Builder.CreateSExtOrTrunc(ScalarIV, Ty)
9715               : State.Builder.CreateCast(Instruction::SIToFP, ScalarIV, Ty);
9716       ScalarIV = emitTransformedIndex(State.Builder, ScalarIV,
9717                                       getStartValue()->getLiveInIRValue(), Step,
9718                                       IndDesc);
9719       ScalarIV->setName("offset.idx");
9720     }
9721     if (TruncToTy) {
9722       assert(Step->getType()->isIntegerTy() &&
9723              "Truncation requires an integer step");
9724       ScalarIV = State.Builder.CreateTrunc(ScalarIV, TruncToTy);
9725       Step = State.Builder.CreateTrunc(Step, TruncToTy);
9726     }
9727     return ScalarIV;
9728   };
9729 
9730   Value *ScalarIV = CreateScalarIV(Step);
9731   if (State.VF.isVector()) {
9732     buildScalarSteps(ScalarIV, Step, IndDesc, this, State);
9733     return;
9734   }
9735 
9736   for (unsigned Part = 0; Part < State.UF; ++Part) {
9737     assert(!State.VF.isScalable() && "scalable vectors not yet supported.");
9738     Value *EntryPart;
9739     if (Step->getType()->isFloatingPointTy()) {
9740       Value *StartIdx =
9741           getRuntimeVFAsFloat(State.Builder, Step->getType(), State.VF * Part);
9742       // Floating-point operations inherit FMF via the builder's flags.
9743       Value *MulOp = State.Builder.CreateFMul(StartIdx, Step);
9744       EntryPart = State.Builder.CreateBinOp(IndDesc.getInductionOpcode(),
9745                                             ScalarIV, MulOp);
9746     } else {
9747       Value *StartIdx =
9748           getRuntimeVF(State.Builder, Step->getType(), State.VF * Part);
9749       EntryPart = State.Builder.CreateAdd(
9750           ScalarIV, State.Builder.CreateMul(StartIdx, Step), "induction");
9751     }
9752     State.set(this, EntryPart, Part);
9753   }
9754 }
9755 
9756 void VPWidenPHIRecipe::execute(VPTransformState &State) {
9757   State.ILV->widenPHIInstruction(cast<PHINode>(getUnderlyingValue()), this,
9758                                  State);
9759 }
9760 
9761 void VPBlendRecipe::execute(VPTransformState &State) {
9762   State.ILV->setDebugLocFromInst(Phi, &State.Builder);
9763   // We know that all PHIs in non-header blocks are converted into
9764   // selects, so we don't have to worry about the insertion order and we
9765   // can just use the builder.
9766   // At this point we generate the predication tree. There may be
9767   // duplications since this is a simple recursive scan, but future
9768   // optimizations will clean it up.
9769 
9770   unsigned NumIncoming = getNumIncomingValues();
9771 
9772   // Generate a sequence of selects of the form:
9773   // SELECT(Mask3, In3,
9774   //        SELECT(Mask2, In2,
9775   //               SELECT(Mask1, In1,
9776   //                      In0)))
9777   // Note that Mask0 is never used: lanes for which no path reaches this phi and
9778   // are essentially undef are taken from In0.
9779   InnerLoopVectorizer::VectorParts Entry(State.UF);
9780   for (unsigned In = 0; In < NumIncoming; ++In) {
9781     for (unsigned Part = 0; Part < State.UF; ++Part) {
9782       // We might have single edge PHIs (blocks) - use an identity
9783       // 'select' for the first PHI operand.
9784       Value *In0 = State.get(getIncomingValue(In), Part);
9785       if (In == 0)
9786         Entry[Part] = In0; // Initialize with the first incoming value.
9787       else {
9788         // Select between the current value and the previous incoming edge
9789         // based on the incoming mask.
9790         Value *Cond = State.get(getMask(In), Part);
9791         Entry[Part] =
9792             State.Builder.CreateSelect(Cond, In0, Entry[Part], "predphi");
9793       }
9794     }
9795   }
9796   for (unsigned Part = 0; Part < State.UF; ++Part)
9797     State.set(this, Entry[Part], Part);
9798 }
9799 
9800 void VPInterleaveRecipe::execute(VPTransformState &State) {
9801   assert(!State.Instance && "Interleave group being replicated.");
9802   State.ILV->vectorizeInterleaveGroup(IG, definedValues(), State, getAddr(),
9803                                       getStoredValues(), getMask());
9804 }
9805 
9806 void VPReductionRecipe::execute(VPTransformState &State) {
9807   assert(!State.Instance && "Reduction being replicated.");
9808   Value *PrevInChain = State.get(getChainOp(), 0);
9809   RecurKind Kind = RdxDesc->getRecurrenceKind();
9810   bool IsOrdered = State.ILV->useOrderedReductions(*RdxDesc);
9811   // Propagate the fast-math flags carried by the underlying instruction.
9812   IRBuilderBase::FastMathFlagGuard FMFGuard(State.Builder);
9813   State.Builder.setFastMathFlags(RdxDesc->getFastMathFlags());
9814   for (unsigned Part = 0; Part < State.UF; ++Part) {
9815     Value *NewVecOp = State.get(getVecOp(), Part);
9816     if (VPValue *Cond = getCondOp()) {
9817       Value *NewCond = State.get(Cond, Part);
9818       VectorType *VecTy = cast<VectorType>(NewVecOp->getType());
9819       Value *Iden = RdxDesc->getRecurrenceIdentity(
9820           Kind, VecTy->getElementType(), RdxDesc->getFastMathFlags());
9821       Value *IdenVec =
9822           State.Builder.CreateVectorSplat(VecTy->getElementCount(), Iden);
9823       Value *Select = State.Builder.CreateSelect(NewCond, NewVecOp, IdenVec);
9824       NewVecOp = Select;
9825     }
9826     Value *NewRed;
9827     Value *NextInChain;
9828     if (IsOrdered) {
9829       if (State.VF.isVector())
9830         NewRed = createOrderedReduction(State.Builder, *RdxDesc, NewVecOp,
9831                                         PrevInChain);
9832       else
9833         NewRed = State.Builder.CreateBinOp(
9834             (Instruction::BinaryOps)RdxDesc->getOpcode(Kind), PrevInChain,
9835             NewVecOp);
9836       PrevInChain = NewRed;
9837     } else {
9838       PrevInChain = State.get(getChainOp(), Part);
9839       NewRed = createTargetReduction(State.Builder, TTI, *RdxDesc, NewVecOp);
9840     }
9841     if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind)) {
9842       NextInChain =
9843           createMinMaxOp(State.Builder, RdxDesc->getRecurrenceKind(),
9844                          NewRed, PrevInChain);
9845     } else if (IsOrdered)
9846       NextInChain = NewRed;
9847     else
9848       NextInChain = State.Builder.CreateBinOp(
9849           (Instruction::BinaryOps)RdxDesc->getOpcode(Kind), NewRed,
9850           PrevInChain);
9851     State.set(this, NextInChain, Part);
9852   }
9853 }
9854 
9855 void VPReplicateRecipe::execute(VPTransformState &State) {
9856   if (State.Instance) { // Generate a single instance.
9857     assert(!State.VF.isScalable() && "Can't scalarize a scalable vector");
9858     State.ILV->scalarizeInstruction(getUnderlyingInstr(), this, *State.Instance,
9859                                     IsPredicated, State);
9860     // Insert scalar instance packing it into a vector.
9861     if (AlsoPack && State.VF.isVector()) {
9862       // If we're constructing lane 0, initialize to start from poison.
9863       if (State.Instance->Lane.isFirstLane()) {
9864         assert(!State.VF.isScalable() && "VF is assumed to be non scalable.");
9865         Value *Poison = PoisonValue::get(
9866             VectorType::get(getUnderlyingValue()->getType(), State.VF));
9867         State.set(this, Poison, State.Instance->Part);
9868       }
9869       State.ILV->packScalarIntoVectorValue(this, *State.Instance, State);
9870     }
9871     return;
9872   }
9873 
9874   // Generate scalar instances for all VF lanes of all UF parts, unless the
9875   // instruction is uniform inwhich case generate only the first lane for each
9876   // of the UF parts.
9877   unsigned EndLane = IsUniform ? 1 : State.VF.getKnownMinValue();
9878   assert((!State.VF.isScalable() || IsUniform) &&
9879          "Can't scalarize a scalable vector");
9880   for (unsigned Part = 0; Part < State.UF; ++Part)
9881     for (unsigned Lane = 0; Lane < EndLane; ++Lane)
9882       State.ILV->scalarizeInstruction(getUnderlyingInstr(), this,
9883                                       VPIteration(Part, Lane), IsPredicated,
9884                                       State);
9885 }
9886 
9887 void VPBranchOnMaskRecipe::execute(VPTransformState &State) {
9888   assert(State.Instance && "Branch on Mask works only on single instance.");
9889 
9890   unsigned Part = State.Instance->Part;
9891   unsigned Lane = State.Instance->Lane.getKnownLane();
9892 
9893   Value *ConditionBit = nullptr;
9894   VPValue *BlockInMask = getMask();
9895   if (BlockInMask) {
9896     ConditionBit = State.get(BlockInMask, Part);
9897     if (ConditionBit->getType()->isVectorTy())
9898       ConditionBit = State.Builder.CreateExtractElement(
9899           ConditionBit, State.Builder.getInt32(Lane));
9900   } else // Block in mask is all-one.
9901     ConditionBit = State.Builder.getTrue();
9902 
9903   // Replace the temporary unreachable terminator with a new conditional branch,
9904   // whose two destinations will be set later when they are created.
9905   auto *CurrentTerminator = State.CFG.PrevBB->getTerminator();
9906   assert(isa<UnreachableInst>(CurrentTerminator) &&
9907          "Expected to replace unreachable terminator with conditional branch.");
9908   auto *CondBr = BranchInst::Create(State.CFG.PrevBB, nullptr, ConditionBit);
9909   CondBr->setSuccessor(0, nullptr);
9910   ReplaceInstWithInst(CurrentTerminator, CondBr);
9911 }
9912 
9913 void VPPredInstPHIRecipe::execute(VPTransformState &State) {
9914   assert(State.Instance && "Predicated instruction PHI works per instance.");
9915   Instruction *ScalarPredInst =
9916       cast<Instruction>(State.get(getOperand(0), *State.Instance));
9917   BasicBlock *PredicatedBB = ScalarPredInst->getParent();
9918   BasicBlock *PredicatingBB = PredicatedBB->getSinglePredecessor();
9919   assert(PredicatingBB && "Predicated block has no single predecessor.");
9920   assert(isa<VPReplicateRecipe>(getOperand(0)) &&
9921          "operand must be VPReplicateRecipe");
9922 
9923   // By current pack/unpack logic we need to generate only a single phi node: if
9924   // a vector value for the predicated instruction exists at this point it means
9925   // the instruction has vector users only, and a phi for the vector value is
9926   // needed. In this case the recipe of the predicated instruction is marked to
9927   // also do that packing, thereby "hoisting" the insert-element sequence.
9928   // Otherwise, a phi node for the scalar value is needed.
9929   unsigned Part = State.Instance->Part;
9930   if (State.hasVectorValue(getOperand(0), Part)) {
9931     Value *VectorValue = State.get(getOperand(0), Part);
9932     InsertElementInst *IEI = cast<InsertElementInst>(VectorValue);
9933     PHINode *VPhi = State.Builder.CreatePHI(IEI->getType(), 2);
9934     VPhi->addIncoming(IEI->getOperand(0), PredicatingBB); // Unmodified vector.
9935     VPhi->addIncoming(IEI, PredicatedBB); // New vector with inserted element.
9936     if (State.hasVectorValue(this, Part))
9937       State.reset(this, VPhi, Part);
9938     else
9939       State.set(this, VPhi, Part);
9940     // NOTE: Currently we need to update the value of the operand, so the next
9941     // predicated iteration inserts its generated value in the correct vector.
9942     State.reset(getOperand(0), VPhi, Part);
9943   } else {
9944     Type *PredInstType = getOperand(0)->getUnderlyingValue()->getType();
9945     PHINode *Phi = State.Builder.CreatePHI(PredInstType, 2);
9946     Phi->addIncoming(PoisonValue::get(ScalarPredInst->getType()),
9947                      PredicatingBB);
9948     Phi->addIncoming(ScalarPredInst, PredicatedBB);
9949     if (State.hasScalarValue(this, *State.Instance))
9950       State.reset(this, Phi, *State.Instance);
9951     else
9952       State.set(this, Phi, *State.Instance);
9953     // NOTE: Currently we need to update the value of the operand, so the next
9954     // predicated iteration inserts its generated value in the correct vector.
9955     State.reset(getOperand(0), Phi, *State.Instance);
9956   }
9957 }
9958 
9959 void VPWidenMemoryInstructionRecipe::execute(VPTransformState &State) {
9960   VPValue *StoredValue = isStore() ? getStoredValue() : nullptr;
9961 
9962   // Attempt to issue a wide load.
9963   LoadInst *LI = dyn_cast<LoadInst>(&Ingredient);
9964   StoreInst *SI = dyn_cast<StoreInst>(&Ingredient);
9965 
9966   assert((LI || SI) && "Invalid Load/Store instruction");
9967   assert((!SI || StoredValue) && "No stored value provided for widened store");
9968   assert((!LI || !StoredValue) && "Stored value provided for widened load");
9969 
9970   Type *ScalarDataTy = getLoadStoreType(&Ingredient);
9971 
9972   auto *DataTy = VectorType::get(ScalarDataTy, State.VF);
9973   const Align Alignment = getLoadStoreAlignment(&Ingredient);
9974   bool CreateGatherScatter = !Consecutive;
9975 
9976   auto &Builder = State.Builder;
9977   InnerLoopVectorizer::VectorParts BlockInMaskParts(State.UF);
9978   bool isMaskRequired = getMask();
9979   if (isMaskRequired)
9980     for (unsigned Part = 0; Part < State.UF; ++Part)
9981       BlockInMaskParts[Part] = State.get(getMask(), Part);
9982 
9983   const auto CreateVecPtr = [&](unsigned Part, Value *Ptr) -> Value * {
9984     // Calculate the pointer for the specific unroll-part.
9985     GetElementPtrInst *PartPtr = nullptr;
9986 
9987     bool InBounds = false;
9988     if (auto *gep = dyn_cast<GetElementPtrInst>(Ptr->stripPointerCasts()))
9989       InBounds = gep->isInBounds();
9990     if (Reverse) {
9991       // If the address is consecutive but reversed, then the
9992       // wide store needs to start at the last vector element.
9993       // RunTimeVF =  VScale * VF.getKnownMinValue()
9994       // For fixed-width VScale is 1, then RunTimeVF = VF.getKnownMinValue()
9995       Value *RunTimeVF = getRuntimeVF(Builder, Builder.getInt32Ty(), State.VF);
9996       // NumElt = -Part * RunTimeVF
9997       Value *NumElt = Builder.CreateMul(Builder.getInt32(-Part), RunTimeVF);
9998       // LastLane = 1 - RunTimeVF
9999       Value *LastLane = Builder.CreateSub(Builder.getInt32(1), RunTimeVF);
10000       PartPtr =
10001           cast<GetElementPtrInst>(Builder.CreateGEP(ScalarDataTy, Ptr, NumElt));
10002       PartPtr->setIsInBounds(InBounds);
10003       PartPtr = cast<GetElementPtrInst>(
10004           Builder.CreateGEP(ScalarDataTy, PartPtr, LastLane));
10005       PartPtr->setIsInBounds(InBounds);
10006       if (isMaskRequired) // Reverse of a null all-one mask is a null mask.
10007         BlockInMaskParts[Part] =
10008             Builder.CreateVectorReverse(BlockInMaskParts[Part], "reverse");
10009     } else {
10010       Value *Increment =
10011           createStepForVF(Builder, Builder.getInt32Ty(), State.VF, Part);
10012       PartPtr = cast<GetElementPtrInst>(
10013           Builder.CreateGEP(ScalarDataTy, Ptr, Increment));
10014       PartPtr->setIsInBounds(InBounds);
10015     }
10016 
10017     unsigned AddressSpace = Ptr->getType()->getPointerAddressSpace();
10018     return Builder.CreateBitCast(PartPtr, DataTy->getPointerTo(AddressSpace));
10019   };
10020 
10021   // Handle Stores:
10022   if (SI) {
10023     State.ILV->setDebugLocFromInst(SI);
10024 
10025     for (unsigned Part = 0; Part < State.UF; ++Part) {
10026       Instruction *NewSI = nullptr;
10027       Value *StoredVal = State.get(StoredValue, Part);
10028       if (CreateGatherScatter) {
10029         Value *MaskPart = isMaskRequired ? BlockInMaskParts[Part] : nullptr;
10030         Value *VectorGep = State.get(getAddr(), Part);
10031         NewSI = Builder.CreateMaskedScatter(StoredVal, VectorGep, Alignment,
10032                                             MaskPart);
10033       } else {
10034         if (Reverse) {
10035           // If we store to reverse consecutive memory locations, then we need
10036           // to reverse the order of elements in the stored value.
10037           StoredVal = Builder.CreateVectorReverse(StoredVal, "reverse");
10038           // We don't want to update the value in the map as it might be used in
10039           // another expression. So don't call resetVectorValue(StoredVal).
10040         }
10041         auto *VecPtr =
10042             CreateVecPtr(Part, State.get(getAddr(), VPIteration(0, 0)));
10043         if (isMaskRequired)
10044           NewSI = Builder.CreateMaskedStore(StoredVal, VecPtr, Alignment,
10045                                             BlockInMaskParts[Part]);
10046         else
10047           NewSI = Builder.CreateAlignedStore(StoredVal, VecPtr, Alignment);
10048       }
10049       State.ILV->addMetadata(NewSI, SI);
10050     }
10051     return;
10052   }
10053 
10054   // Handle loads.
10055   assert(LI && "Must have a load instruction");
10056   State.ILV->setDebugLocFromInst(LI);
10057   for (unsigned Part = 0; Part < State.UF; ++Part) {
10058     Value *NewLI;
10059     if (CreateGatherScatter) {
10060       Value *MaskPart = isMaskRequired ? BlockInMaskParts[Part] : nullptr;
10061       Value *VectorGep = State.get(getAddr(), Part);
10062       NewLI = Builder.CreateMaskedGather(DataTy, VectorGep, Alignment, MaskPart,
10063                                          nullptr, "wide.masked.gather");
10064       State.ILV->addMetadata(NewLI, LI);
10065     } else {
10066       auto *VecPtr =
10067           CreateVecPtr(Part, State.get(getAddr(), VPIteration(0, 0)));
10068       if (isMaskRequired)
10069         NewLI = Builder.CreateMaskedLoad(
10070             DataTy, VecPtr, Alignment, BlockInMaskParts[Part],
10071             PoisonValue::get(DataTy), "wide.masked.load");
10072       else
10073         NewLI =
10074             Builder.CreateAlignedLoad(DataTy, VecPtr, Alignment, "wide.load");
10075 
10076       // Add metadata to the load, but setVectorValue to the reverse shuffle.
10077       State.ILV->addMetadata(NewLI, LI);
10078       if (Reverse)
10079         NewLI = Builder.CreateVectorReverse(NewLI, "reverse");
10080     }
10081 
10082     State.set(this, NewLI, Part);
10083   }
10084 }
10085 
10086 // Determine how to lower the scalar epilogue, which depends on 1) optimising
10087 // for minimum code-size, 2) predicate compiler options, 3) loop hints forcing
10088 // predication, and 4) a TTI hook that analyses whether the loop is suitable
10089 // for predication.
10090 static ScalarEpilogueLowering getScalarEpilogueLowering(
10091     Function *F, Loop *L, LoopVectorizeHints &Hints, ProfileSummaryInfo *PSI,
10092     BlockFrequencyInfo *BFI, TargetTransformInfo *TTI, TargetLibraryInfo *TLI,
10093     AssumptionCache *AC, LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT,
10094     LoopVectorizationLegality &LVL) {
10095   // 1) OptSize takes precedence over all other options, i.e. if this is set,
10096   // don't look at hints or options, and don't request a scalar epilogue.
10097   // (For PGSO, as shouldOptimizeForSize isn't currently accessible from
10098   // LoopAccessInfo (due to code dependency and not being able to reliably get
10099   // PSI/BFI from a loop analysis under NPM), we cannot suppress the collection
10100   // of strides in LoopAccessInfo::analyzeLoop() and vectorize without
10101   // versioning when the vectorization is forced, unlike hasOptSize. So revert
10102   // back to the old way and vectorize with versioning when forced. See D81345.)
10103   if (F->hasOptSize() || (llvm::shouldOptimizeForSize(L->getHeader(), PSI, BFI,
10104                                                       PGSOQueryType::IRPass) &&
10105                           Hints.getForce() != LoopVectorizeHints::FK_Enabled))
10106     return CM_ScalarEpilogueNotAllowedOptSize;
10107 
10108   // 2) If set, obey the directives
10109   if (PreferPredicateOverEpilogue.getNumOccurrences()) {
10110     switch (PreferPredicateOverEpilogue) {
10111     case PreferPredicateTy::ScalarEpilogue:
10112       return CM_ScalarEpilogueAllowed;
10113     case PreferPredicateTy::PredicateElseScalarEpilogue:
10114       return CM_ScalarEpilogueNotNeededUsePredicate;
10115     case PreferPredicateTy::PredicateOrDontVectorize:
10116       return CM_ScalarEpilogueNotAllowedUsePredicate;
10117     };
10118   }
10119 
10120   // 3) If set, obey the hints
10121   switch (Hints.getPredicate()) {
10122   case LoopVectorizeHints::FK_Enabled:
10123     return CM_ScalarEpilogueNotNeededUsePredicate;
10124   case LoopVectorizeHints::FK_Disabled:
10125     return CM_ScalarEpilogueAllowed;
10126   };
10127 
10128   // 4) if the TTI hook indicates this is profitable, request predication.
10129   if (TTI->preferPredicateOverEpilogue(L, LI, *SE, *AC, TLI, DT,
10130                                        LVL.getLAI()))
10131     return CM_ScalarEpilogueNotNeededUsePredicate;
10132 
10133   return CM_ScalarEpilogueAllowed;
10134 }
10135 
10136 Value *VPTransformState::get(VPValue *Def, unsigned Part) {
10137   // If Values have been set for this Def return the one relevant for \p Part.
10138   if (hasVectorValue(Def, Part))
10139     return Data.PerPartOutput[Def][Part];
10140 
10141   if (!hasScalarValue(Def, {Part, 0})) {
10142     Value *IRV = Def->getLiveInIRValue();
10143     Value *B = ILV->getBroadcastInstrs(IRV);
10144     set(Def, B, Part);
10145     return B;
10146   }
10147 
10148   Value *ScalarValue = get(Def, {Part, 0});
10149   // If we aren't vectorizing, we can just copy the scalar map values over
10150   // to the vector map.
10151   if (VF.isScalar()) {
10152     set(Def, ScalarValue, Part);
10153     return ScalarValue;
10154   }
10155 
10156   auto *RepR = dyn_cast<VPReplicateRecipe>(Def);
10157   bool IsUniform = RepR && RepR->isUniform();
10158 
10159   unsigned LastLane = IsUniform ? 0 : VF.getKnownMinValue() - 1;
10160   // Check if there is a scalar value for the selected lane.
10161   if (!hasScalarValue(Def, {Part, LastLane})) {
10162     // At the moment, VPWidenIntOrFpInductionRecipes can also be uniform.
10163     assert((isa<VPWidenIntOrFpInductionRecipe>(Def->getDef()) ||
10164             isa<VPScalarIVStepsRecipe>(Def->getDef())) &&
10165            "unexpected recipe found to be invariant");
10166     IsUniform = true;
10167     LastLane = 0;
10168   }
10169 
10170   auto *LastInst = cast<Instruction>(get(Def, {Part, LastLane}));
10171   // Set the insert point after the last scalarized instruction or after the
10172   // last PHI, if LastInst is a PHI. This ensures the insertelement sequence
10173   // will directly follow the scalar definitions.
10174   auto OldIP = Builder.saveIP();
10175   auto NewIP =
10176       isa<PHINode>(LastInst)
10177           ? BasicBlock::iterator(LastInst->getParent()->getFirstNonPHI())
10178           : std::next(BasicBlock::iterator(LastInst));
10179   Builder.SetInsertPoint(&*NewIP);
10180 
10181   // However, if we are vectorizing, we need to construct the vector values.
10182   // If the value is known to be uniform after vectorization, we can just
10183   // broadcast the scalar value corresponding to lane zero for each unroll
10184   // iteration. Otherwise, we construct the vector values using
10185   // insertelement instructions. Since the resulting vectors are stored in
10186   // State, we will only generate the insertelements once.
10187   Value *VectorValue = nullptr;
10188   if (IsUniform) {
10189     VectorValue = ILV->getBroadcastInstrs(ScalarValue);
10190     set(Def, VectorValue, Part);
10191   } else {
10192     // Initialize packing with insertelements to start from undef.
10193     assert(!VF.isScalable() && "VF is assumed to be non scalable.");
10194     Value *Undef = PoisonValue::get(VectorType::get(LastInst->getType(), VF));
10195     set(Def, Undef, Part);
10196     for (unsigned Lane = 0; Lane < VF.getKnownMinValue(); ++Lane)
10197       ILV->packScalarIntoVectorValue(Def, {Part, Lane}, *this);
10198     VectorValue = get(Def, Part);
10199   }
10200   Builder.restoreIP(OldIP);
10201   return VectorValue;
10202 }
10203 
10204 // Process the loop in the VPlan-native vectorization path. This path builds
10205 // VPlan upfront in the vectorization pipeline, which allows to apply
10206 // VPlan-to-VPlan transformations from the very beginning without modifying the
10207 // input LLVM IR.
10208 static bool processLoopInVPlanNativePath(
10209     Loop *L, PredicatedScalarEvolution &PSE, LoopInfo *LI, DominatorTree *DT,
10210     LoopVectorizationLegality *LVL, TargetTransformInfo *TTI,
10211     TargetLibraryInfo *TLI, DemandedBits *DB, AssumptionCache *AC,
10212     OptimizationRemarkEmitter *ORE, BlockFrequencyInfo *BFI,
10213     ProfileSummaryInfo *PSI, LoopVectorizeHints &Hints,
10214     LoopVectorizationRequirements &Requirements) {
10215 
10216   if (isa<SCEVCouldNotCompute>(PSE.getBackedgeTakenCount())) {
10217     LLVM_DEBUG(dbgs() << "LV: cannot compute the outer-loop trip count\n");
10218     return false;
10219   }
10220   assert(EnableVPlanNativePath && "VPlan-native path is disabled.");
10221   Function *F = L->getHeader()->getParent();
10222   InterleavedAccessInfo IAI(PSE, L, DT, LI, LVL->getLAI());
10223 
10224   ScalarEpilogueLowering SEL = getScalarEpilogueLowering(
10225       F, L, Hints, PSI, BFI, TTI, TLI, AC, LI, PSE.getSE(), DT, *LVL);
10226 
10227   LoopVectorizationCostModel CM(SEL, L, PSE, LI, LVL, *TTI, TLI, DB, AC, ORE, F,
10228                                 &Hints, IAI);
10229   // Use the planner for outer loop vectorization.
10230   // TODO: CM is not used at this point inside the planner. Turn CM into an
10231   // optional argument if we don't need it in the future.
10232   LoopVectorizationPlanner LVP(L, LI, TLI, TTI, LVL, CM, IAI, PSE, Hints,
10233                                Requirements, ORE);
10234 
10235   // Get user vectorization factor.
10236   ElementCount UserVF = Hints.getWidth();
10237 
10238   CM.collectElementTypesForWidening();
10239 
10240   // Plan how to best vectorize, return the best VF and its cost.
10241   const VectorizationFactor VF = LVP.planInVPlanNativePath(UserVF);
10242 
10243   // If we are stress testing VPlan builds, do not attempt to generate vector
10244   // code. Masked vector code generation support will follow soon.
10245   // Also, do not attempt to vectorize if no vector code will be produced.
10246   if (VPlanBuildStressTest || EnableVPlanPredication ||
10247       VectorizationFactor::Disabled() == VF)
10248     return false;
10249 
10250   VPlan &BestPlan = LVP.getBestPlanFor(VF.Width);
10251 
10252   {
10253     GeneratedRTChecks Checks(*PSE.getSE(), DT, LI,
10254                              F->getParent()->getDataLayout());
10255     InnerLoopVectorizer LB(L, PSE, LI, DT, TLI, TTI, AC, ORE, VF.Width, 1, LVL,
10256                            &CM, BFI, PSI, Checks);
10257     LLVM_DEBUG(dbgs() << "Vectorizing outer loop in \""
10258                       << L->getHeader()->getParent()->getName() << "\"\n");
10259     LVP.executePlan(VF.Width, 1, BestPlan, LB, DT);
10260   }
10261 
10262   // Mark the loop as already vectorized to avoid vectorizing again.
10263   Hints.setAlreadyVectorized();
10264   assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()));
10265   return true;
10266 }
10267 
10268 // Emit a remark if there are stores to floats that required a floating point
10269 // extension. If the vectorized loop was generated with floating point there
10270 // will be a performance penalty from the conversion overhead and the change in
10271 // the vector width.
10272 static void checkMixedPrecision(Loop *L, OptimizationRemarkEmitter *ORE) {
10273   SmallVector<Instruction *, 4> Worklist;
10274   for (BasicBlock *BB : L->getBlocks()) {
10275     for (Instruction &Inst : *BB) {
10276       if (auto *S = dyn_cast<StoreInst>(&Inst)) {
10277         if (S->getValueOperand()->getType()->isFloatTy())
10278           Worklist.push_back(S);
10279       }
10280     }
10281   }
10282 
10283   // Traverse the floating point stores upwards searching, for floating point
10284   // conversions.
10285   SmallPtrSet<const Instruction *, 4> Visited;
10286   SmallPtrSet<const Instruction *, 4> EmittedRemark;
10287   while (!Worklist.empty()) {
10288     auto *I = Worklist.pop_back_val();
10289     if (!L->contains(I))
10290       continue;
10291     if (!Visited.insert(I).second)
10292       continue;
10293 
10294     // Emit a remark if the floating point store required a floating
10295     // point conversion.
10296     // TODO: More work could be done to identify the root cause such as a
10297     // constant or a function return type and point the user to it.
10298     if (isa<FPExtInst>(I) && EmittedRemark.insert(I).second)
10299       ORE->emit([&]() {
10300         return OptimizationRemarkAnalysis(LV_NAME, "VectorMixedPrecision",
10301                                           I->getDebugLoc(), L->getHeader())
10302                << "floating point conversion changes vector width. "
10303                << "Mixed floating point precision requires an up/down "
10304                << "cast that will negatively impact performance.";
10305       });
10306 
10307     for (Use &Op : I->operands())
10308       if (auto *OpI = dyn_cast<Instruction>(Op))
10309         Worklist.push_back(OpI);
10310   }
10311 }
10312 
10313 LoopVectorizePass::LoopVectorizePass(LoopVectorizeOptions Opts)
10314     : InterleaveOnlyWhenForced(Opts.InterleaveOnlyWhenForced ||
10315                                !EnableLoopInterleaving),
10316       VectorizeOnlyWhenForced(Opts.VectorizeOnlyWhenForced ||
10317                               !EnableLoopVectorization) {}
10318 
10319 bool LoopVectorizePass::processLoop(Loop *L) {
10320   assert((EnableVPlanNativePath || L->isInnermost()) &&
10321          "VPlan-native path is not enabled. Only process inner loops.");
10322 
10323 #ifndef NDEBUG
10324   const std::string DebugLocStr = getDebugLocString(L);
10325 #endif /* NDEBUG */
10326 
10327   LLVM_DEBUG(dbgs() << "\nLV: Checking a loop in '"
10328                     << L->getHeader()->getParent()->getName() << "' from "
10329                     << DebugLocStr << "\n");
10330 
10331   LoopVectorizeHints Hints(L, InterleaveOnlyWhenForced, *ORE, TTI);
10332 
10333   LLVM_DEBUG(
10334       dbgs() << "LV: Loop hints:"
10335              << " force="
10336              << (Hints.getForce() == LoopVectorizeHints::FK_Disabled
10337                      ? "disabled"
10338                      : (Hints.getForce() == LoopVectorizeHints::FK_Enabled
10339                             ? "enabled"
10340                             : "?"))
10341              << " width=" << Hints.getWidth()
10342              << " interleave=" << Hints.getInterleave() << "\n");
10343 
10344   // Function containing loop
10345   Function *F = L->getHeader()->getParent();
10346 
10347   // Looking at the diagnostic output is the only way to determine if a loop
10348   // was vectorized (other than looking at the IR or machine code), so it
10349   // is important to generate an optimization remark for each loop. Most of
10350   // these messages are generated as OptimizationRemarkAnalysis. Remarks
10351   // generated as OptimizationRemark and OptimizationRemarkMissed are
10352   // less verbose reporting vectorized loops and unvectorized loops that may
10353   // benefit from vectorization, respectively.
10354 
10355   if (!Hints.allowVectorization(F, L, VectorizeOnlyWhenForced)) {
10356     LLVM_DEBUG(dbgs() << "LV: Loop hints prevent vectorization.\n");
10357     return false;
10358   }
10359 
10360   PredicatedScalarEvolution PSE(*SE, *L);
10361 
10362   // Check if it is legal to vectorize the loop.
10363   LoopVectorizationRequirements Requirements;
10364   LoopVectorizationLegality LVL(L, PSE, DT, TTI, TLI, AA, F, GetLAA, LI, ORE,
10365                                 &Requirements, &Hints, DB, AC, BFI, PSI);
10366   if (!LVL.canVectorize(EnableVPlanNativePath)) {
10367     LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
10368     Hints.emitRemarkWithHints();
10369     return false;
10370   }
10371 
10372   // Check the function attributes and profiles to find out if this function
10373   // should be optimized for size.
10374   ScalarEpilogueLowering SEL = getScalarEpilogueLowering(
10375       F, L, Hints, PSI, BFI, TTI, TLI, AC, LI, PSE.getSE(), DT, LVL);
10376 
10377   // Entrance to the VPlan-native vectorization path. Outer loops are processed
10378   // here. They may require CFG and instruction level transformations before
10379   // even evaluating whether vectorization is profitable. Since we cannot modify
10380   // the incoming IR, we need to build VPlan upfront in the vectorization
10381   // pipeline.
10382   if (!L->isInnermost())
10383     return processLoopInVPlanNativePath(L, PSE, LI, DT, &LVL, TTI, TLI, DB, AC,
10384                                         ORE, BFI, PSI, Hints, Requirements);
10385 
10386   assert(L->isInnermost() && "Inner loop expected.");
10387 
10388   // Check the loop for a trip count threshold: vectorize loops with a tiny trip
10389   // count by optimizing for size, to minimize overheads.
10390   auto ExpectedTC = getSmallBestKnownTC(*SE, L);
10391   if (ExpectedTC && *ExpectedTC < TinyTripCountVectorThreshold) {
10392     LLVM_DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "
10393                       << "This loop is worth vectorizing only if no scalar "
10394                       << "iteration overheads are incurred.");
10395     if (Hints.getForce() == LoopVectorizeHints::FK_Enabled)
10396       LLVM_DEBUG(dbgs() << " But vectorizing was explicitly forced.\n");
10397     else {
10398       LLVM_DEBUG(dbgs() << "\n");
10399       SEL = CM_ScalarEpilogueNotAllowedLowTripLoop;
10400     }
10401   }
10402 
10403   // Check the function attributes to see if implicit floats are allowed.
10404   // FIXME: This check doesn't seem possibly correct -- what if the loop is
10405   // an integer loop and the vector instructions selected are purely integer
10406   // vector instructions?
10407   if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10408     reportVectorizationFailure(
10409         "Can't vectorize when the NoImplicitFloat attribute is used",
10410         "loop not vectorized due to NoImplicitFloat attribute",
10411         "NoImplicitFloat", ORE, L);
10412     Hints.emitRemarkWithHints();
10413     return false;
10414   }
10415 
10416   // Check if the target supports potentially unsafe FP vectorization.
10417   // FIXME: Add a check for the type of safety issue (denormal, signaling)
10418   // for the target we're vectorizing for, to make sure none of the
10419   // additional fp-math flags can help.
10420   if (Hints.isPotentiallyUnsafe() &&
10421       TTI->isFPVectorizationPotentiallyUnsafe()) {
10422     reportVectorizationFailure(
10423         "Potentially unsafe FP op prevents vectorization",
10424         "loop not vectorized due to unsafe FP support.",
10425         "UnsafeFP", ORE, L);
10426     Hints.emitRemarkWithHints();
10427     return false;
10428   }
10429 
10430   bool AllowOrderedReductions;
10431   // If the flag is set, use that instead and override the TTI behaviour.
10432   if (ForceOrderedReductions.getNumOccurrences() > 0)
10433     AllowOrderedReductions = ForceOrderedReductions;
10434   else
10435     AllowOrderedReductions = TTI->enableOrderedReductions();
10436   if (!LVL.canVectorizeFPMath(AllowOrderedReductions)) {
10437     ORE->emit([&]() {
10438       auto *ExactFPMathInst = Requirements.getExactFPInst();
10439       return OptimizationRemarkAnalysisFPCommute(DEBUG_TYPE, "CantReorderFPOps",
10440                                                  ExactFPMathInst->getDebugLoc(),
10441                                                  ExactFPMathInst->getParent())
10442              << "loop not vectorized: cannot prove it is safe to reorder "
10443                 "floating-point operations";
10444     });
10445     LLVM_DEBUG(dbgs() << "LV: loop not vectorized: cannot prove it is safe to "
10446                          "reorder floating-point operations\n");
10447     Hints.emitRemarkWithHints();
10448     return false;
10449   }
10450 
10451   bool UseInterleaved = TTI->enableInterleavedAccessVectorization();
10452   InterleavedAccessInfo IAI(PSE, L, DT, LI, LVL.getLAI());
10453 
10454   // If an override option has been passed in for interleaved accesses, use it.
10455   if (EnableInterleavedMemAccesses.getNumOccurrences() > 0)
10456     UseInterleaved = EnableInterleavedMemAccesses;
10457 
10458   // Analyze interleaved memory accesses.
10459   if (UseInterleaved) {
10460     IAI.analyzeInterleaving(useMaskedInterleavedAccesses(*TTI));
10461   }
10462 
10463   // Use the cost model.
10464   LoopVectorizationCostModel CM(SEL, L, PSE, LI, &LVL, *TTI, TLI, DB, AC, ORE,
10465                                 F, &Hints, IAI);
10466   CM.collectValuesToIgnore();
10467   CM.collectElementTypesForWidening();
10468 
10469   // Use the planner for vectorization.
10470   LoopVectorizationPlanner LVP(L, LI, TLI, TTI, &LVL, CM, IAI, PSE, Hints,
10471                                Requirements, ORE);
10472 
10473   // Get user vectorization factor and interleave count.
10474   ElementCount UserVF = Hints.getWidth();
10475   unsigned UserIC = Hints.getInterleave();
10476 
10477   // Plan how to best vectorize, return the best VF and its cost.
10478   Optional<VectorizationFactor> MaybeVF = LVP.plan(UserVF, UserIC);
10479 
10480   VectorizationFactor VF = VectorizationFactor::Disabled();
10481   unsigned IC = 1;
10482 
10483   if (MaybeVF) {
10484     VF = *MaybeVF;
10485     // Select the interleave count.
10486     IC = CM.selectInterleaveCount(VF.Width, *VF.Cost.getValue());
10487   }
10488 
10489   // Identify the diagnostic messages that should be produced.
10490   std::pair<StringRef, std::string> VecDiagMsg, IntDiagMsg;
10491   bool VectorizeLoop = true, InterleaveLoop = true;
10492   if (VF.Width.isScalar()) {
10493     LLVM_DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
10494     VecDiagMsg = std::make_pair(
10495         "VectorizationNotBeneficial",
10496         "the cost-model indicates that vectorization is not beneficial");
10497     VectorizeLoop = false;
10498   }
10499 
10500   if (!MaybeVF && UserIC > 1) {
10501     // Tell the user interleaving was avoided up-front, despite being explicitly
10502     // requested.
10503     LLVM_DEBUG(dbgs() << "LV: Ignoring UserIC, because vectorization and "
10504                          "interleaving should be avoided up front\n");
10505     IntDiagMsg = std::make_pair(
10506         "InterleavingAvoided",
10507         "Ignoring UserIC, because interleaving was avoided up front");
10508     InterleaveLoop = false;
10509   } else if (IC == 1 && UserIC <= 1) {
10510     // Tell the user interleaving is not beneficial.
10511     LLVM_DEBUG(dbgs() << "LV: Interleaving is not beneficial.\n");
10512     IntDiagMsg = std::make_pair(
10513         "InterleavingNotBeneficial",
10514         "the cost-model indicates that interleaving is not beneficial");
10515     InterleaveLoop = false;
10516     if (UserIC == 1) {
10517       IntDiagMsg.first = "InterleavingNotBeneficialAndDisabled";
10518       IntDiagMsg.second +=
10519           " and is explicitly disabled or interleave count is set to 1";
10520     }
10521   } else if (IC > 1 && UserIC == 1) {
10522     // Tell the user interleaving is beneficial, but it explicitly disabled.
10523     LLVM_DEBUG(
10524         dbgs() << "LV: Interleaving is beneficial but is explicitly disabled.");
10525     IntDiagMsg = std::make_pair(
10526         "InterleavingBeneficialButDisabled",
10527         "the cost-model indicates that interleaving is beneficial "
10528         "but is explicitly disabled or interleave count is set to 1");
10529     InterleaveLoop = false;
10530   }
10531 
10532   // Override IC if user provided an interleave count.
10533   IC = UserIC > 0 ? UserIC : IC;
10534 
10535   // Emit diagnostic messages, if any.
10536   const char *VAPassName = Hints.vectorizeAnalysisPassName();
10537   if (!VectorizeLoop && !InterleaveLoop) {
10538     // Do not vectorize or interleaving the loop.
10539     ORE->emit([&]() {
10540       return OptimizationRemarkMissed(VAPassName, VecDiagMsg.first,
10541                                       L->getStartLoc(), L->getHeader())
10542              << VecDiagMsg.second;
10543     });
10544     ORE->emit([&]() {
10545       return OptimizationRemarkMissed(LV_NAME, IntDiagMsg.first,
10546                                       L->getStartLoc(), L->getHeader())
10547              << IntDiagMsg.second;
10548     });
10549     return false;
10550   } else if (!VectorizeLoop && InterleaveLoop) {
10551     LLVM_DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
10552     ORE->emit([&]() {
10553       return OptimizationRemarkAnalysis(VAPassName, VecDiagMsg.first,
10554                                         L->getStartLoc(), L->getHeader())
10555              << VecDiagMsg.second;
10556     });
10557   } else if (VectorizeLoop && !InterleaveLoop) {
10558     LLVM_DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width
10559                       << ") in " << DebugLocStr << '\n');
10560     ORE->emit([&]() {
10561       return OptimizationRemarkAnalysis(LV_NAME, IntDiagMsg.first,
10562                                         L->getStartLoc(), L->getHeader())
10563              << IntDiagMsg.second;
10564     });
10565   } else if (VectorizeLoop && InterleaveLoop) {
10566     LLVM_DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width
10567                       << ") in " << DebugLocStr << '\n');
10568     LLVM_DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
10569   }
10570 
10571   bool DisableRuntimeUnroll = false;
10572   MDNode *OrigLoopID = L->getLoopID();
10573   {
10574     // Optimistically generate runtime checks. Drop them if they turn out to not
10575     // be profitable. Limit the scope of Checks, so the cleanup happens
10576     // immediately after vector codegeneration is done.
10577     GeneratedRTChecks Checks(*PSE.getSE(), DT, LI,
10578                              F->getParent()->getDataLayout());
10579     if (!VF.Width.isScalar() || IC > 1)
10580       Checks.Create(L, *LVL.getLAI(), PSE.getPredicate());
10581 
10582     using namespace ore;
10583     if (!VectorizeLoop) {
10584       assert(IC > 1 && "interleave count should not be 1 or 0");
10585       // If we decided that it is not legal to vectorize the loop, then
10586       // interleave it.
10587       InnerLoopUnroller Unroller(L, PSE, LI, DT, TLI, TTI, AC, ORE, IC, &LVL,
10588                                  &CM, BFI, PSI, Checks);
10589 
10590       VPlan &BestPlan = LVP.getBestPlanFor(VF.Width);
10591       LVP.executePlan(VF.Width, IC, BestPlan, Unroller, DT);
10592 
10593       ORE->emit([&]() {
10594         return OptimizationRemark(LV_NAME, "Interleaved", L->getStartLoc(),
10595                                   L->getHeader())
10596                << "interleaved loop (interleaved count: "
10597                << NV("InterleaveCount", IC) << ")";
10598       });
10599     } else {
10600       // If we decided that it is *legal* to vectorize the loop, then do it.
10601 
10602       // Consider vectorizing the epilogue too if it's profitable.
10603       VectorizationFactor EpilogueVF =
10604           CM.selectEpilogueVectorizationFactor(VF.Width, LVP);
10605       if (EpilogueVF.Width.isVector()) {
10606 
10607         // The first pass vectorizes the main loop and creates a scalar epilogue
10608         // to be vectorized by executing the plan (potentially with a different
10609         // factor) again shortly afterwards.
10610         EpilogueLoopVectorizationInfo EPI(VF.Width, IC, EpilogueVF.Width, 1);
10611         EpilogueVectorizerMainLoop MainILV(L, PSE, LI, DT, TLI, TTI, AC, ORE,
10612                                            EPI, &LVL, &CM, BFI, PSI, Checks);
10613 
10614         VPlan &BestMainPlan = LVP.getBestPlanFor(EPI.MainLoopVF);
10615         LVP.executePlan(EPI.MainLoopVF, EPI.MainLoopUF, BestMainPlan, MainILV,
10616                         DT);
10617         ++LoopsVectorized;
10618 
10619         simplifyLoop(L, DT, LI, SE, AC, nullptr, false /* PreserveLCSSA */);
10620         formLCSSARecursively(*L, *DT, LI, SE);
10621 
10622         // Second pass vectorizes the epilogue and adjusts the control flow
10623         // edges from the first pass.
10624         EPI.MainLoopVF = EPI.EpilogueVF;
10625         EPI.MainLoopUF = EPI.EpilogueUF;
10626         EpilogueVectorizerEpilogueLoop EpilogILV(L, PSE, LI, DT, TLI, TTI, AC,
10627                                                  ORE, EPI, &LVL, &CM, BFI, PSI,
10628                                                  Checks);
10629 
10630         VPlan &BestEpiPlan = LVP.getBestPlanFor(EPI.EpilogueVF);
10631         BestEpiPlan.getVectorLoopRegion()->getEntryBasicBlock()->setName(
10632             "vec.epilog.vector.body");
10633 
10634         // Ensure that the start values for any VPReductionPHIRecipes are
10635         // updated before vectorising the epilogue loop.
10636         VPBasicBlock *Header =
10637             BestEpiPlan.getVectorLoopRegion()->getEntryBasicBlock();
10638         for (VPRecipeBase &R : Header->phis()) {
10639           if (auto *ReductionPhi = dyn_cast<VPReductionPHIRecipe>(&R)) {
10640             if (auto *Resume = MainILV.getReductionResumeValue(
10641                     ReductionPhi->getRecurrenceDescriptor())) {
10642               VPValue *StartVal = BestEpiPlan.getOrAddExternalDef(Resume);
10643               ReductionPhi->setOperand(0, StartVal);
10644             }
10645           }
10646         }
10647 
10648         LVP.executePlan(EPI.EpilogueVF, EPI.EpilogueUF, BestEpiPlan, EpilogILV,
10649                         DT);
10650         ++LoopsEpilogueVectorized;
10651 
10652         if (!MainILV.areSafetyChecksAdded())
10653           DisableRuntimeUnroll = true;
10654       } else {
10655         InnerLoopVectorizer LB(L, PSE, LI, DT, TLI, TTI, AC, ORE, VF.Width, IC,
10656                                &LVL, &CM, BFI, PSI, Checks);
10657 
10658         VPlan &BestPlan = LVP.getBestPlanFor(VF.Width);
10659         LVP.executePlan(VF.Width, IC, BestPlan, LB, DT);
10660         ++LoopsVectorized;
10661 
10662         // Add metadata to disable runtime unrolling a scalar loop when there
10663         // are no runtime checks about strides and memory. A scalar loop that is
10664         // rarely used is not worth unrolling.
10665         if (!LB.areSafetyChecksAdded())
10666           DisableRuntimeUnroll = true;
10667       }
10668       // Report the vectorization decision.
10669       ORE->emit([&]() {
10670         return OptimizationRemark(LV_NAME, "Vectorized", L->getStartLoc(),
10671                                   L->getHeader())
10672                << "vectorized loop (vectorization width: "
10673                << NV("VectorizationFactor", VF.Width)
10674                << ", interleaved count: " << NV("InterleaveCount", IC) << ")";
10675       });
10676     }
10677 
10678     if (ORE->allowExtraAnalysis(LV_NAME))
10679       checkMixedPrecision(L, ORE);
10680   }
10681 
10682   Optional<MDNode *> RemainderLoopID =
10683       makeFollowupLoopID(OrigLoopID, {LLVMLoopVectorizeFollowupAll,
10684                                       LLVMLoopVectorizeFollowupEpilogue});
10685   if (RemainderLoopID.hasValue()) {
10686     L->setLoopID(RemainderLoopID.getValue());
10687   } else {
10688     if (DisableRuntimeUnroll)
10689       AddRuntimeUnrollDisableMetaData(L);
10690 
10691     // Mark the loop as already vectorized to avoid vectorizing again.
10692     Hints.setAlreadyVectorized();
10693   }
10694 
10695   assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()));
10696   return true;
10697 }
10698 
10699 LoopVectorizeResult LoopVectorizePass::runImpl(
10700     Function &F, ScalarEvolution &SE_, LoopInfo &LI_, TargetTransformInfo &TTI_,
10701     DominatorTree &DT_, BlockFrequencyInfo &BFI_, TargetLibraryInfo *TLI_,
10702     DemandedBits &DB_, AAResults &AA_, AssumptionCache &AC_,
10703     std::function<const LoopAccessInfo &(Loop &)> &GetLAA_,
10704     OptimizationRemarkEmitter &ORE_, ProfileSummaryInfo *PSI_) {
10705   SE = &SE_;
10706   LI = &LI_;
10707   TTI = &TTI_;
10708   DT = &DT_;
10709   BFI = &BFI_;
10710   TLI = TLI_;
10711   AA = &AA_;
10712   AC = &AC_;
10713   GetLAA = &GetLAA_;
10714   DB = &DB_;
10715   ORE = &ORE_;
10716   PSI = PSI_;
10717 
10718   // Don't attempt if
10719   // 1. the target claims to have no vector registers, and
10720   // 2. interleaving won't help ILP.
10721   //
10722   // The second condition is necessary because, even if the target has no
10723   // vector registers, loop vectorization may still enable scalar
10724   // interleaving.
10725   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true)) &&
10726       TTI->getMaxInterleaveFactor(1) < 2)
10727     return LoopVectorizeResult(false, false);
10728 
10729   bool Changed = false, CFGChanged = false;
10730 
10731   // The vectorizer requires loops to be in simplified form.
10732   // Since simplification may add new inner loops, it has to run before the
10733   // legality and profitability checks. This means running the loop vectorizer
10734   // will simplify all loops, regardless of whether anything end up being
10735   // vectorized.
10736   for (auto &L : *LI)
10737     Changed |= CFGChanged |=
10738         simplifyLoop(L, DT, LI, SE, AC, nullptr, false /* PreserveLCSSA */);
10739 
10740   // Build up a worklist of inner-loops to vectorize. This is necessary as
10741   // the act of vectorizing or partially unrolling a loop creates new loops
10742   // and can invalidate iterators across the loops.
10743   SmallVector<Loop *, 8> Worklist;
10744 
10745   for (Loop *L : *LI)
10746     collectSupportedLoops(*L, LI, ORE, Worklist);
10747 
10748   LoopsAnalyzed += Worklist.size();
10749 
10750   // Now walk the identified inner loops.
10751   while (!Worklist.empty()) {
10752     Loop *L = Worklist.pop_back_val();
10753 
10754     // For the inner loops we actually process, form LCSSA to simplify the
10755     // transform.
10756     Changed |= formLCSSARecursively(*L, *DT, LI, SE);
10757 
10758     Changed |= CFGChanged |= processLoop(L);
10759   }
10760 
10761   // Process each loop nest in the function.
10762   return LoopVectorizeResult(Changed, CFGChanged);
10763 }
10764 
10765 PreservedAnalyses LoopVectorizePass::run(Function &F,
10766                                          FunctionAnalysisManager &AM) {
10767     auto &LI = AM.getResult<LoopAnalysis>(F);
10768     // There are no loops in the function. Return before computing other expensive
10769     // analyses.
10770     if (LI.empty())
10771       return PreservedAnalyses::all();
10772     auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
10773     auto &TTI = AM.getResult<TargetIRAnalysis>(F);
10774     auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
10775     auto &BFI = AM.getResult<BlockFrequencyAnalysis>(F);
10776     auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
10777     auto &AA = AM.getResult<AAManager>(F);
10778     auto &AC = AM.getResult<AssumptionAnalysis>(F);
10779     auto &DB = AM.getResult<DemandedBitsAnalysis>(F);
10780     auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
10781 
10782     auto &LAM = AM.getResult<LoopAnalysisManagerFunctionProxy>(F).getManager();
10783     std::function<const LoopAccessInfo &(Loop &)> GetLAA =
10784         [&](Loop &L) -> const LoopAccessInfo & {
10785       LoopStandardAnalysisResults AR = {AA,  AC,  DT,      LI,      SE,
10786                                         TLI, TTI, nullptr, nullptr, nullptr};
10787       return LAM.getResult<LoopAccessAnalysis>(L, AR);
10788     };
10789     auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
10790     ProfileSummaryInfo *PSI =
10791         MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
10792     LoopVectorizeResult Result =
10793         runImpl(F, SE, LI, TTI, DT, BFI, &TLI, DB, AA, AC, GetLAA, ORE, PSI);
10794     if (!Result.MadeAnyChange)
10795       return PreservedAnalyses::all();
10796     PreservedAnalyses PA;
10797 
10798     // We currently do not preserve loopinfo/dominator analyses with outer loop
10799     // vectorization. Until this is addressed, mark these analyses as preserved
10800     // only for non-VPlan-native path.
10801     // TODO: Preserve Loop and Dominator analyses for VPlan-native path.
10802     if (!EnableVPlanNativePath) {
10803       PA.preserve<LoopAnalysis>();
10804       PA.preserve<DominatorTreeAnalysis>();
10805     }
10806 
10807     if (Result.MadeCFGChange) {
10808       // Making CFG changes likely means a loop got vectorized. Indicate that
10809       // extra simplification passes should be run.
10810       // TODO: MadeCFGChanges is not a prefect proxy. Extra passes should only
10811       // be run if runtime checks have been added.
10812       AM.getResult<ShouldRunExtraVectorPasses>(F);
10813       PA.preserve<ShouldRunExtraVectorPasses>();
10814     } else {
10815       PA.preserveSet<CFGAnalyses>();
10816     }
10817     return PA;
10818 }
10819 
10820 void LoopVectorizePass::printPipeline(
10821     raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
10822   static_cast<PassInfoMixin<LoopVectorizePass> *>(this)->printPipeline(
10823       OS, MapClassName2PassName);
10824 
10825   OS << "<";
10826   OS << (InterleaveOnlyWhenForced ? "" : "no-") << "interleave-forced-only;";
10827   OS << (VectorizeOnlyWhenForced ? "" : "no-") << "vectorize-forced-only;";
10828   OS << ">";
10829 }
10830