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/LLVMContext.h"
116 #include "llvm/IR/Metadata.h"
117 #include "llvm/IR/Module.h"
118 #include "llvm/IR/Operator.h"
119 #include "llvm/IR/PatternMatch.h"
120 #include "llvm/IR/Type.h"
121 #include "llvm/IR/Use.h"
122 #include "llvm/IR/User.h"
123 #include "llvm/IR/Value.h"
124 #include "llvm/IR/ValueHandle.h"
125 #include "llvm/IR/Verifier.h"
126 #include "llvm/InitializePasses.h"
127 #include "llvm/Pass.h"
128 #include "llvm/Support/Casting.h"
129 #include "llvm/Support/CommandLine.h"
130 #include "llvm/Support/Compiler.h"
131 #include "llvm/Support/Debug.h"
132 #include "llvm/Support/ErrorHandling.h"
133 #include "llvm/Support/InstructionCost.h"
134 #include "llvm/Support/MathExtras.h"
135 #include "llvm/Support/raw_ostream.h"
136 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
137 #include "llvm/Transforms/Utils/InjectTLIMappings.h"
138 #include "llvm/Transforms/Utils/LoopSimplify.h"
139 #include "llvm/Transforms/Utils/LoopUtils.h"
140 #include "llvm/Transforms/Utils/LoopVersioning.h"
141 #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
142 #include "llvm/Transforms/Utils/SizeOpts.h"
143 #include "llvm/Transforms/Vectorize/LoopVectorizationLegality.h"
144 #include <algorithm>
145 #include <cassert>
146 #include <cstdint>
147 #include <cstdlib>
148 #include <functional>
149 #include <iterator>
150 #include <limits>
151 #include <memory>
152 #include <string>
153 #include <tuple>
154 #include <utility>
155 
156 using namespace llvm;
157 
158 #define LV_NAME "loop-vectorize"
159 #define DEBUG_TYPE LV_NAME
160 
161 #ifndef NDEBUG
162 const char VerboseDebug[] = DEBUG_TYPE "-verbose";
163 #endif
164 
165 /// @{
166 /// Metadata attribute names
167 const char LLVMLoopVectorizeFollowupAll[] = "llvm.loop.vectorize.followup_all";
168 const char LLVMLoopVectorizeFollowupVectorized[] =
169     "llvm.loop.vectorize.followup_vectorized";
170 const char LLVMLoopVectorizeFollowupEpilogue[] =
171     "llvm.loop.vectorize.followup_epilogue";
172 /// @}
173 
174 STATISTIC(LoopsVectorized, "Number of loops vectorized");
175 STATISTIC(LoopsAnalyzed, "Number of loops analyzed for vectorization");
176 STATISTIC(LoopsEpilogueVectorized, "Number of epilogues vectorized");
177 
178 static cl::opt<bool> EnableEpilogueVectorization(
179     "enable-epilogue-vectorization", cl::init(true), cl::Hidden,
180     cl::desc("Enable vectorization of epilogue loops."));
181 
182 static cl::opt<unsigned> EpilogueVectorizationForceVF(
183     "epilogue-vectorization-force-VF", cl::init(1), cl::Hidden,
184     cl::desc("When epilogue vectorization is enabled, and a value greater than "
185              "1 is specified, forces the given VF for all applicable epilogue "
186              "loops."));
187 
188 static cl::opt<unsigned> EpilogueVectorizationMinVF(
189     "epilogue-vectorization-minimum-VF", cl::init(16), cl::Hidden,
190     cl::desc("Only loops with vectorization factor equal to or larger than "
191              "the specified value are considered for epilogue vectorization."));
192 
193 /// Loops with a known constant trip count below this number are vectorized only
194 /// if no scalar iteration overheads are incurred.
195 static cl::opt<unsigned> TinyTripCountVectorThreshold(
196     "vectorizer-min-trip-count", cl::init(16), cl::Hidden,
197     cl::desc("Loops with a constant trip count that is smaller than this "
198              "value are vectorized only if no scalar iteration overheads "
199              "are incurred."));
200 
201 static cl::opt<unsigned> PragmaVectorizeMemoryCheckThreshold(
202     "pragma-vectorize-memory-check-threshold", cl::init(128), cl::Hidden,
203     cl::desc("The maximum allowed number of runtime memory checks with a "
204              "vectorize(enable) pragma."));
205 
206 // Option prefer-predicate-over-epilogue indicates that an epilogue is undesired,
207 // that predication is preferred, and this lists all options. I.e., the
208 // vectorizer will try to fold the tail-loop (epilogue) into the vector body
209 // and predicate the instructions accordingly. If tail-folding fails, there are
210 // different fallback strategies depending on these values:
211 namespace PreferPredicateTy {
212   enum Option {
213     ScalarEpilogue = 0,
214     PredicateElseScalarEpilogue,
215     PredicateOrDontVectorize
216   };
217 } // namespace PreferPredicateTy
218 
219 static cl::opt<PreferPredicateTy::Option> PreferPredicateOverEpilogue(
220     "prefer-predicate-over-epilogue",
221     cl::init(PreferPredicateTy::ScalarEpilogue),
222     cl::Hidden,
223     cl::desc("Tail-folding and predication preferences over creating a scalar "
224              "epilogue loop."),
225     cl::values(clEnumValN(PreferPredicateTy::ScalarEpilogue,
226                          "scalar-epilogue",
227                          "Don't tail-predicate loops, create scalar epilogue"),
228               clEnumValN(PreferPredicateTy::PredicateElseScalarEpilogue,
229                          "predicate-else-scalar-epilogue",
230                          "prefer tail-folding, create scalar epilogue if tail "
231                          "folding fails."),
232               clEnumValN(PreferPredicateTy::PredicateOrDontVectorize,
233                          "predicate-dont-vectorize",
234                          "prefers tail-folding, don't attempt vectorization if "
235                          "tail-folding fails.")));
236 
237 static cl::opt<bool> MaximizeBandwidth(
238     "vectorizer-maximize-bandwidth", cl::init(false), cl::Hidden,
239     cl::desc("Maximize bandwidth when selecting vectorization factor which "
240              "will be determined by the smallest type in loop."));
241 
242 static cl::opt<bool> EnableInterleavedMemAccesses(
243     "enable-interleaved-mem-accesses", cl::init(false), cl::Hidden,
244     cl::desc("Enable vectorization on interleaved memory accesses in a loop"));
245 
246 /// An interleave-group may need masking if it resides in a block that needs
247 /// predication, or in order to mask away gaps.
248 static cl::opt<bool> EnableMaskedInterleavedMemAccesses(
249     "enable-masked-interleaved-mem-accesses", cl::init(false), cl::Hidden,
250     cl::desc("Enable vectorization on masked interleaved memory accesses in a loop"));
251 
252 static cl::opt<unsigned> TinyTripCountInterleaveThreshold(
253     "tiny-trip-count-interleave-threshold", cl::init(128), cl::Hidden,
254     cl::desc("We don't interleave loops with a estimated constant trip count "
255              "below this number"));
256 
257 static cl::opt<unsigned> ForceTargetNumScalarRegs(
258     "force-target-num-scalar-regs", cl::init(0), cl::Hidden,
259     cl::desc("A flag that overrides the target's number of scalar registers."));
260 
261 static cl::opt<unsigned> ForceTargetNumVectorRegs(
262     "force-target-num-vector-regs", cl::init(0), cl::Hidden,
263     cl::desc("A flag that overrides the target's number of vector registers."));
264 
265 static cl::opt<unsigned> ForceTargetMaxScalarInterleaveFactor(
266     "force-target-max-scalar-interleave", cl::init(0), cl::Hidden,
267     cl::desc("A flag that overrides the target's max interleave factor for "
268              "scalar loops."));
269 
270 static cl::opt<unsigned> ForceTargetMaxVectorInterleaveFactor(
271     "force-target-max-vector-interleave", cl::init(0), cl::Hidden,
272     cl::desc("A flag that overrides the target's max interleave factor for "
273              "vectorized loops."));
274 
275 static cl::opt<unsigned> ForceTargetInstructionCost(
276     "force-target-instruction-cost", cl::init(0), cl::Hidden,
277     cl::desc("A flag that overrides the target's expected cost for "
278              "an instruction to a single constant value. Mostly "
279              "useful for getting consistent testing."));
280 
281 static cl::opt<bool> ForceTargetSupportsScalableVectors(
282     "force-target-supports-scalable-vectors", cl::init(false), cl::Hidden,
283     cl::desc(
284         "Pretend that scalable vectors are supported, even if the target does "
285         "not support them. This flag should only be used for testing."));
286 
287 static cl::opt<unsigned> SmallLoopCost(
288     "small-loop-cost", cl::init(20), cl::Hidden,
289     cl::desc(
290         "The cost of a loop that is considered 'small' by the interleaver."));
291 
292 static cl::opt<bool> LoopVectorizeWithBlockFrequency(
293     "loop-vectorize-with-block-frequency", cl::init(true), cl::Hidden,
294     cl::desc("Enable the use of the block frequency analysis to access PGO "
295              "heuristics minimizing code growth in cold regions and being more "
296              "aggressive in hot regions."));
297 
298 // Runtime interleave loops for load/store throughput.
299 static cl::opt<bool> EnableLoadStoreRuntimeInterleave(
300     "enable-loadstore-runtime-interleave", cl::init(true), cl::Hidden,
301     cl::desc(
302         "Enable runtime interleaving until load/store ports are saturated"));
303 
304 /// Interleave small loops with scalar reductions.
305 static cl::opt<bool> InterleaveSmallLoopScalarReduction(
306     "interleave-small-loop-scalar-reduction", cl::init(false), cl::Hidden,
307     cl::desc("Enable interleaving for loops with small iteration counts that "
308              "contain scalar reductions to expose ILP."));
309 
310 /// The number of stores in a loop that are allowed to need predication.
311 static cl::opt<unsigned> NumberOfStoresToPredicate(
312     "vectorize-num-stores-pred", cl::init(1), cl::Hidden,
313     cl::desc("Max number of stores to be predicated behind an if."));
314 
315 static cl::opt<bool> EnableIndVarRegisterHeur(
316     "enable-ind-var-reg-heur", cl::init(true), cl::Hidden,
317     cl::desc("Count the induction variable only once when interleaving"));
318 
319 static cl::opt<bool> EnableCondStoresVectorization(
320     "enable-cond-stores-vec", cl::init(true), cl::Hidden,
321     cl::desc("Enable if predication of stores during vectorization."));
322 
323 static cl::opt<unsigned> MaxNestedScalarReductionIC(
324     "max-nested-scalar-reduction-interleave", cl::init(2), cl::Hidden,
325     cl::desc("The maximum interleave count to use when interleaving a scalar "
326              "reduction in a nested loop."));
327 
328 static cl::opt<bool>
329     PreferInLoopReductions("prefer-inloop-reductions", cl::init(false),
330                            cl::Hidden,
331                            cl::desc("Prefer in-loop vector reductions, "
332                                     "overriding the targets preference."));
333 
334 static cl::opt<bool> ForceOrderedReductions(
335     "force-ordered-reductions", cl::init(false), cl::Hidden,
336     cl::desc("Enable the vectorisation of loops with in-order (strict) "
337              "FP reductions"));
338 
339 static cl::opt<bool> PreferPredicatedReductionSelect(
340     "prefer-predicated-reduction-select", cl::init(false), cl::Hidden,
341     cl::desc(
342         "Prefer predicating a reduction operation over an after loop select."));
343 
344 cl::opt<bool> EnableVPlanNativePath(
345     "enable-vplan-native-path", cl::init(false), cl::Hidden,
346     cl::desc("Enable VPlan-native vectorization path with "
347              "support for outer loop vectorization."));
348 
349 // FIXME: Remove this switch once we have divergence analysis. Currently we
350 // assume divergent non-backedge branches when this switch is true.
351 cl::opt<bool> EnableVPlanPredication(
352     "enable-vplan-predication", cl::init(false), cl::Hidden,
353     cl::desc("Enable VPlan-native vectorization path predicator with "
354              "support for outer loop vectorization."));
355 
356 // This flag enables the stress testing of the VPlan H-CFG construction in the
357 // VPlan-native vectorization path. It must be used in conjuction with
358 // -enable-vplan-native-path. -vplan-verify-hcfg can also be used to enable the
359 // verification of the H-CFGs built.
360 static cl::opt<bool> VPlanBuildStressTest(
361     "vplan-build-stress-test", cl::init(false), cl::Hidden,
362     cl::desc(
363         "Build VPlan for every supported loop nest in the function and bail "
364         "out right after the build (stress test the VPlan H-CFG construction "
365         "in the VPlan-native vectorization path)."));
366 
367 cl::opt<bool> llvm::EnableLoopInterleaving(
368     "interleave-loops", cl::init(true), cl::Hidden,
369     cl::desc("Enable loop interleaving in Loop vectorization passes"));
370 cl::opt<bool> llvm::EnableLoopVectorization(
371     "vectorize-loops", cl::init(true), cl::Hidden,
372     cl::desc("Run the Loop vectorization passes"));
373 
374 cl::opt<bool> PrintVPlansInDotFormat(
375     "vplan-print-in-dot-format", cl::init(false), cl::Hidden,
376     cl::desc("Use dot format instead of plain text when dumping VPlans"));
377 
378 /// A helper function that returns true if the given type is irregular. The
379 /// type is irregular if its allocated size doesn't equal the store size of an
380 /// element of the corresponding vector type.
381 static bool hasIrregularType(Type *Ty, const DataLayout &DL) {
382   // Determine if an array of N elements of type Ty is "bitcast compatible"
383   // with a <N x Ty> vector.
384   // This is only true if there is no padding between the array elements.
385   return DL.getTypeAllocSizeInBits(Ty) != DL.getTypeSizeInBits(Ty);
386 }
387 
388 /// A helper function that returns the reciprocal of the block probability of
389 /// predicated blocks. If we return X, we are assuming the predicated block
390 /// will execute once for every X iterations of the loop header.
391 ///
392 /// TODO: We should use actual block probability here, if available. Currently,
393 ///       we always assume predicated blocks have a 50% chance of executing.
394 static unsigned getReciprocalPredBlockProb() { return 2; }
395 
396 /// A helper function that returns an integer or floating-point constant with
397 /// value C.
398 static Constant *getSignedIntOrFpConstant(Type *Ty, int64_t C) {
399   return Ty->isIntegerTy() ? ConstantInt::getSigned(Ty, C)
400                            : ConstantFP::get(Ty, C);
401 }
402 
403 /// Returns "best known" trip count for the specified loop \p L as defined by
404 /// the following procedure:
405 ///   1) Returns exact trip count if it is known.
406 ///   2) Returns expected trip count according to profile data if any.
407 ///   3) Returns upper bound estimate if it is known.
408 ///   4) Returns None if all of the above failed.
409 static Optional<unsigned> getSmallBestKnownTC(ScalarEvolution &SE, Loop *L) {
410   // Check if exact trip count is known.
411   if (unsigned ExpectedTC = SE.getSmallConstantTripCount(L))
412     return ExpectedTC;
413 
414   // Check if there is an expected trip count available from profile data.
415   if (LoopVectorizeWithBlockFrequency)
416     if (auto EstimatedTC = getLoopEstimatedTripCount(L))
417       return EstimatedTC;
418 
419   // Check if upper bound estimate is known.
420   if (unsigned ExpectedTC = SE.getSmallConstantMaxTripCount(L))
421     return ExpectedTC;
422 
423   return None;
424 }
425 
426 // Forward declare GeneratedRTChecks.
427 class GeneratedRTChecks;
428 
429 namespace llvm {
430 
431 AnalysisKey ShouldRunExtraVectorPasses::Key;
432 
433 /// InnerLoopVectorizer vectorizes loops which contain only one basic
434 /// block to a specified vectorization factor (VF).
435 /// This class performs the widening of scalars into vectors, or multiple
436 /// scalars. This class also implements the following features:
437 /// * It inserts an epilogue loop for handling loops that don't have iteration
438 ///   counts that are known to be a multiple of the vectorization factor.
439 /// * It handles the code generation for reduction variables.
440 /// * Scalarization (implementation using scalars) of un-vectorizable
441 ///   instructions.
442 /// InnerLoopVectorizer does not perform any vectorization-legality
443 /// checks, and relies on the caller to check for the different legality
444 /// aspects. The InnerLoopVectorizer relies on the
445 /// LoopVectorizationLegality class to provide information about the induction
446 /// and reduction variables that were found to a given vectorization factor.
447 class InnerLoopVectorizer {
448 public:
449   InnerLoopVectorizer(Loop *OrigLoop, PredicatedScalarEvolution &PSE,
450                       LoopInfo *LI, DominatorTree *DT,
451                       const TargetLibraryInfo *TLI,
452                       const TargetTransformInfo *TTI, AssumptionCache *AC,
453                       OptimizationRemarkEmitter *ORE, ElementCount VecWidth,
454                       unsigned UnrollFactor, LoopVectorizationLegality *LVL,
455                       LoopVectorizationCostModel *CM, BlockFrequencyInfo *BFI,
456                       ProfileSummaryInfo *PSI, GeneratedRTChecks &RTChecks)
457       : OrigLoop(OrigLoop), PSE(PSE), LI(LI), DT(DT), TLI(TLI), TTI(TTI),
458         AC(AC), ORE(ORE), VF(VecWidth), UF(UnrollFactor),
459         Builder(PSE.getSE()->getContext()), Legal(LVL), Cost(CM), BFI(BFI),
460         PSI(PSI), RTChecks(RTChecks) {
461     // Query this against the original loop and save it here because the profile
462     // of the original loop header may change as the transformation happens.
463     OptForSizeBasedOnProfile = llvm::shouldOptimizeForSize(
464         OrigLoop->getHeader(), PSI, BFI, PGSOQueryType::IRPass);
465   }
466 
467   virtual ~InnerLoopVectorizer() = default;
468 
469   /// Create a new empty loop that will contain vectorized instructions later
470   /// on, while the old loop will be used as the scalar remainder. Control flow
471   /// is generated around the vectorized (and scalar epilogue) loops consisting
472   /// of various checks and bypasses. Return the pre-header block of the new
473   /// loop.
474   /// In the case of epilogue vectorization, this function is overriden to
475   /// handle the more complex control flow around the loops.
476   virtual BasicBlock *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);
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 first-order recurrence or pointer induction PHINode in
494   /// a block. This method handles the induction variable canonicalization. It
495   /// supports both VF = 1 for unrolled loops and arbitrary length vectors.
496   void widenPHIInstruction(Instruction *PN, VPWidenPHIRecipe *PhiR,
497                            VPTransformState &State);
498 
499   /// A helper function to scalarize a single Instruction in the innermost loop.
500   /// Generates a sequence of scalar instances for each lane between \p MinLane
501   /// and \p MaxLane, times each part between \p MinPart and \p MaxPart,
502   /// inclusive. Uses the VPValue operands from \p RepRecipe instead of \p
503   /// Instr's operands.
504   void scalarizeInstruction(Instruction *Instr, VPReplicateRecipe *RepRecipe,
505                             const VPIteration &Instance, bool IfPredicateInstr,
506                             VPTransformState &State);
507 
508   /// Widen an integer or floating-point induction variable \p IV. If \p Trunc
509   /// is provided, the integer induction variable will first be truncated to
510   /// the corresponding type.
511   void widenIntOrFpInduction(PHINode *IV, const InductionDescriptor &ID,
512                              Value *Start, TruncInst *Trunc, VPValue *Def,
513                              VPTransformState &State);
514 
515   /// Construct the vector value of a scalarized value \p V one lane at a time.
516   void packScalarIntoVectorValue(VPValue *Def, const VPIteration &Instance,
517                                  VPTransformState &State);
518 
519   /// Try to vectorize interleaved access group \p Group with the base address
520   /// given in \p Addr, optionally masking the vector operations if \p
521   /// BlockInMask is non-null. Use \p State to translate given VPValues to IR
522   /// values in the vectorized loop.
523   void vectorizeInterleaveGroup(const InterleaveGroup<Instruction> *Group,
524                                 ArrayRef<VPValue *> VPDefs,
525                                 VPTransformState &State, VPValue *Addr,
526                                 ArrayRef<VPValue *> StoredValues,
527                                 VPValue *BlockInMask = nullptr);
528 
529   /// Set the debug location in the builder \p Ptr using the debug location in
530   /// \p V. If \p Ptr is None then it uses the class member's Builder.
531   void setDebugLocFromInst(const Value *V,
532                            Optional<IRBuilder<> *> CustomBuilder = None);
533 
534   /// Fix the non-induction PHIs in the OrigPHIsToFix vector.
535   void fixNonInductionPHIs(VPTransformState &State);
536 
537   /// Returns true if the reordering of FP operations is not allowed, but we are
538   /// able to vectorize with strict in-order reductions for the given RdxDesc.
539   bool useOrderedReductions(const RecurrenceDescriptor &RdxDesc);
540 
541   /// Create a broadcast instruction. This method generates a broadcast
542   /// instruction (shuffle) for loop invariant values and for the induction
543   /// value. If this is the induction variable then we extend it to N, N+1, ...
544   /// this is needed because each iteration in the loop corresponds to a SIMD
545   /// element.
546   virtual Value *getBroadcastInstrs(Value *V);
547 
548   /// Add metadata from one instruction to another.
549   ///
550   /// This includes both the original MDs from \p From and additional ones (\see
551   /// addNewMetadata).  Use this for *newly created* instructions in the vector
552   /// loop.
553   void addMetadata(Instruction *To, Instruction *From);
554 
555   /// Similar to the previous function but it adds the metadata to a
556   /// vector of instructions.
557   void addMetadata(ArrayRef<Value *> To, Instruction *From);
558 
559 protected:
560   friend class LoopVectorizationPlanner;
561 
562   /// A small list of PHINodes.
563   using PhiVector = SmallVector<PHINode *, 4>;
564 
565   /// A type for scalarized values in the new loop. Each value from the
566   /// original loop, when scalarized, is represented by UF x VF scalar values
567   /// in the new unrolled loop, where UF is the unroll factor and VF is the
568   /// vectorization factor.
569   using ScalarParts = SmallVector<SmallVector<Value *, 4>, 2>;
570 
571   /// Set up the values of the IVs correctly when exiting the vector loop.
572   void fixupIVUsers(PHINode *OrigPhi, const InductionDescriptor &II,
573                     Value *CountRoundDown, Value *EndValue,
574                     BasicBlock *MiddleBlock);
575 
576   /// Create a new induction variable inside L.
577   PHINode *createInductionVariable(Loop *L, Value *Start, Value *End,
578                                    Value *Step, Instruction *DL);
579 
580   /// Handle all cross-iteration phis in the header.
581   void fixCrossIterationPHIs(VPTransformState &State);
582 
583   /// Create the exit value of first order recurrences in the middle block and
584   /// update their users.
585   void fixFirstOrderRecurrence(VPFirstOrderRecurrencePHIRecipe *PhiR,
586                                VPTransformState &State);
587 
588   /// Create code for the loop exit value of the reduction.
589   void fixReduction(VPReductionPHIRecipe *Phi, VPTransformState &State);
590 
591   /// Clear NSW/NUW flags from reduction instructions if necessary.
592   void clearReductionWrapFlags(const RecurrenceDescriptor &RdxDesc,
593                                VPTransformState &State);
594 
595   /// Fixup the LCSSA phi nodes in the unique exit block.  This simply
596   /// means we need to add the appropriate incoming value from the middle
597   /// block as exiting edges from the scalar epilogue loop (if present) are
598   /// already in place, and we exit the vector loop exclusively to the middle
599   /// block.
600   void fixLCSSAPHIs(VPTransformState &State);
601 
602   /// Iteratively sink the scalarized operands of a predicated instruction into
603   /// the block that was created for it.
604   void sinkScalarOperands(Instruction *PredInst);
605 
606   /// Shrinks vector element sizes to the smallest bitwidth they can be legally
607   /// represented as.
608   void truncateToMinimalBitwidths(VPTransformState &State);
609 
610   /// Compute scalar induction steps. \p ScalarIV is the scalar induction
611   /// variable on which to base the steps, \p Step is the size of the step, and
612   /// \p EntryVal is the value from the original loop that maps to the steps.
613   /// Note that \p EntryVal doesn't have to be an induction variable - it
614   /// can also be a truncate instruction.
615   void buildScalarSteps(Value *ScalarIV, Value *Step, Instruction *EntryVal,
616                         const InductionDescriptor &ID, VPValue *Def,
617                         VPTransformState &State);
618 
619   /// Create a vector induction phi node based on an existing scalar one. \p
620   /// EntryVal is the value from the original loop that maps to the vector phi
621   /// node, and \p Step is the loop-invariant step. If \p EntryVal is a
622   /// truncate instruction, instead of widening the original IV, we widen a
623   /// version of the IV truncated to \p EntryVal's type.
624   void createVectorIntOrFpInductionPHI(const InductionDescriptor &II,
625                                        Value *Step, Value *Start,
626                                        Instruction *EntryVal, VPValue *Def,
627                                        VPTransformState &State);
628 
629   /// Returns true if an instruction \p I should be scalarized instead of
630   /// vectorized for the chosen vectorization factor.
631   bool shouldScalarizeInstruction(Instruction *I) const;
632 
633   /// Returns true if we should generate a scalar version of \p IV.
634   bool needsScalarInduction(Instruction *IV) const;
635 
636   /// Returns (and creates if needed) the original loop trip count.
637   Value *getOrCreateTripCount(Loop *NewLoop);
638 
639   /// Returns (and creates if needed) the trip count of the widened loop.
640   Value *getOrCreateVectorTripCount(Loop *NewLoop);
641 
642   /// Returns a bitcasted value to the requested vector type.
643   /// Also handles bitcasts of vector<float> <-> vector<pointer> types.
644   Value *createBitOrPointerCast(Value *V, VectorType *DstVTy,
645                                 const DataLayout &DL);
646 
647   /// Emit a bypass check to see if the vector trip count is zero, including if
648   /// it overflows.
649   void emitMinimumIterationCountCheck(Loop *L, BasicBlock *Bypass);
650 
651   /// Emit a bypass check to see if all of the SCEV assumptions we've
652   /// had to make are correct. Returns the block containing the checks or
653   /// nullptr if no checks have been added.
654   BasicBlock *emitSCEVChecks(Loop *L, BasicBlock *Bypass);
655 
656   /// Emit bypass checks to check any memory assumptions we may have made.
657   /// Returns the block containing the checks or nullptr if no checks have been
658   /// added.
659   BasicBlock *emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass);
660 
661   /// Compute the transformed value of Index at offset StartValue using step
662   /// StepValue.
663   /// For integer induction, returns StartValue + Index * StepValue.
664   /// For pointer induction, returns StartValue[Index * StepValue].
665   /// FIXME: The newly created binary instructions should contain nsw/nuw
666   /// flags, which can be found from the original scalar operations.
667   Value *emitTransformedIndex(IRBuilder<> &B, Value *Index, ScalarEvolution *SE,
668                               const DataLayout &DL,
669                               const InductionDescriptor &ID,
670                               BasicBlock *VectorHeader) const;
671 
672   /// Emit basic blocks (prefixed with \p Prefix) for the iteration check,
673   /// vector loop preheader, middle block and scalar preheader. Also
674   /// allocate a loop object for the new vector loop and return it.
675   Loop *createVectorLoopSkeleton(StringRef Prefix);
676 
677   /// Create new phi nodes for the induction variables to resume iteration count
678   /// in the scalar epilogue, from where the vectorized loop left off (given by
679   /// \p VectorTripCount).
680   /// In cases where the loop skeleton is more complicated (eg. epilogue
681   /// vectorization) and the resume values can come from an additional bypass
682   /// block, the \p AdditionalBypass pair provides information about the bypass
683   /// block and the end value on the edge from bypass to this loop.
684   void createInductionResumeValues(
685       Loop *L, Value *VectorTripCount,
686       std::pair<BasicBlock *, Value *> AdditionalBypass = {nullptr, nullptr});
687 
688   /// Complete the loop skeleton by adding debug MDs, creating appropriate
689   /// conditional branches in the middle block, preparing the builder and
690   /// running the verifier. Take in the vector loop \p L as argument, and return
691   /// the preheader of the completed vector loop.
692   BasicBlock *completeLoopSkeleton(Loop *L, MDNode *OrigLoopID);
693 
694   /// Add additional metadata to \p To that was not present on \p Orig.
695   ///
696   /// Currently this is used to add the noalias annotations based on the
697   /// inserted memchecks.  Use this for instructions that are *cloned* into the
698   /// vector loop.
699   void addNewMetadata(Instruction *To, const Instruction *Orig);
700 
701   /// Collect poison-generating recipes that may generate a poison value that is
702   /// used after vectorization, even when their operands are not poison. Those
703   /// recipes meet the following conditions:
704   ///  * Contribute to the address computation of a recipe generating a widen
705   ///    memory load/store (VPWidenMemoryInstructionRecipe or
706   ///    VPInterleaveRecipe).
707   ///  * Such a widen memory load/store has at least one underlying Instruction
708   ///    that is in a basic block that needs predication and after vectorization
709   ///    the generated instruction won't be predicated.
710   void collectPoisonGeneratingRecipes(VPTransformState &State);
711 
712   /// Allow subclasses to override and print debug traces before/after vplan
713   /// execution, when trace information is requested.
714   virtual void printDebugTracesAtStart(){};
715   virtual void printDebugTracesAtEnd(){};
716 
717   /// The original loop.
718   Loop *OrigLoop;
719 
720   /// A wrapper around ScalarEvolution used to add runtime SCEV checks. Applies
721   /// dynamic knowledge to simplify SCEV expressions and converts them to a
722   /// more usable form.
723   PredicatedScalarEvolution &PSE;
724 
725   /// Loop Info.
726   LoopInfo *LI;
727 
728   /// Dominator Tree.
729   DominatorTree *DT;
730 
731   /// Alias Analysis.
732   AAResults *AA;
733 
734   /// Target Library Info.
735   const TargetLibraryInfo *TLI;
736 
737   /// Target Transform Info.
738   const TargetTransformInfo *TTI;
739 
740   /// Assumption Cache.
741   AssumptionCache *AC;
742 
743   /// Interface to emit optimization remarks.
744   OptimizationRemarkEmitter *ORE;
745 
746   /// LoopVersioning.  It's only set up (non-null) if memchecks were
747   /// used.
748   ///
749   /// This is currently only used to add no-alias metadata based on the
750   /// memchecks.  The actually versioning is performed manually.
751   std::unique_ptr<LoopVersioning> LVer;
752 
753   /// The vectorization SIMD factor to use. Each vector will have this many
754   /// vector elements.
755   ElementCount VF;
756 
757   /// The vectorization unroll factor to use. Each scalar is vectorized to this
758   /// many different vector instructions.
759   unsigned UF;
760 
761   /// The builder that we use
762   IRBuilder<> Builder;
763 
764   // --- Vectorization state ---
765 
766   /// The vector-loop preheader.
767   BasicBlock *LoopVectorPreHeader;
768 
769   /// The scalar-loop preheader.
770   BasicBlock *LoopScalarPreHeader;
771 
772   /// Middle Block between the vector and the scalar.
773   BasicBlock *LoopMiddleBlock;
774 
775   /// The unique ExitBlock of the scalar loop if one exists.  Note that
776   /// there can be multiple exiting edges reaching this block.
777   BasicBlock *LoopExitBlock;
778 
779   /// The vector loop body.
780   BasicBlock *LoopVectorBody;
781 
782   /// The scalar loop body.
783   BasicBlock *LoopScalarBody;
784 
785   /// A list of all bypass blocks. The first block is the entry of the loop.
786   SmallVector<BasicBlock *, 4> LoopBypassBlocks;
787 
788   /// The new Induction variable which was added to the new block.
789   PHINode *Induction = nullptr;
790 
791   /// The induction variable of the old basic block.
792   PHINode *OldInduction = nullptr;
793 
794   /// Store instructions that were predicated.
795   SmallVector<Instruction *, 4> PredicatedInstructions;
796 
797   /// Trip count of the original loop.
798   Value *TripCount = nullptr;
799 
800   /// Trip count of the widened loop (TripCount - TripCount % (VF*UF))
801   Value *VectorTripCount = nullptr;
802 
803   /// The legality analysis.
804   LoopVectorizationLegality *Legal;
805 
806   /// The profitablity analysis.
807   LoopVectorizationCostModel *Cost;
808 
809   // Record whether runtime checks are added.
810   bool AddedSafetyChecks = false;
811 
812   // Holds the end values for each induction variable. We save the end values
813   // so we can later fix-up the external users of the induction variables.
814   DenseMap<PHINode *, Value *> IVEndValues;
815 
816   // Vector of original scalar PHIs whose corresponding widened PHIs need to be
817   // fixed up at the end of vector code generation.
818   SmallVector<PHINode *, 8> OrigPHIsToFix;
819 
820   /// BFI and PSI are used to check for profile guided size optimizations.
821   BlockFrequencyInfo *BFI;
822   ProfileSummaryInfo *PSI;
823 
824   // Whether this loop should be optimized for size based on profile guided size
825   // optimizatios.
826   bool OptForSizeBasedOnProfile;
827 
828   /// Structure to hold information about generated runtime checks, responsible
829   /// for cleaning the checks, if vectorization turns out unprofitable.
830   GeneratedRTChecks &RTChecks;
831 };
832 
833 class InnerLoopUnroller : public InnerLoopVectorizer {
834 public:
835   InnerLoopUnroller(Loop *OrigLoop, PredicatedScalarEvolution &PSE,
836                     LoopInfo *LI, DominatorTree *DT,
837                     const TargetLibraryInfo *TLI,
838                     const TargetTransformInfo *TTI, AssumptionCache *AC,
839                     OptimizationRemarkEmitter *ORE, unsigned UnrollFactor,
840                     LoopVectorizationLegality *LVL,
841                     LoopVectorizationCostModel *CM, BlockFrequencyInfo *BFI,
842                     ProfileSummaryInfo *PSI, GeneratedRTChecks &Check)
843       : InnerLoopVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
844                             ElementCount::getFixed(1), UnrollFactor, LVL, CM,
845                             BFI, PSI, Check) {}
846 
847 private:
848   Value *getBroadcastInstrs(Value *V) override;
849 };
850 
851 /// Encapsulate information regarding vectorization of a loop and its epilogue.
852 /// This information is meant to be updated and used across two stages of
853 /// epilogue vectorization.
854 struct EpilogueLoopVectorizationInfo {
855   ElementCount MainLoopVF = ElementCount::getFixed(0);
856   unsigned MainLoopUF = 0;
857   ElementCount EpilogueVF = ElementCount::getFixed(0);
858   unsigned EpilogueUF = 0;
859   BasicBlock *MainLoopIterationCountCheck = nullptr;
860   BasicBlock *EpilogueIterationCountCheck = nullptr;
861   BasicBlock *SCEVSafetyCheck = nullptr;
862   BasicBlock *MemSafetyCheck = nullptr;
863   Value *TripCount = nullptr;
864   Value *VectorTripCount = nullptr;
865 
866   EpilogueLoopVectorizationInfo(ElementCount MVF, unsigned MUF,
867                                 ElementCount EVF, unsigned EUF)
868       : MainLoopVF(MVF), MainLoopUF(MUF), EpilogueVF(EVF), EpilogueUF(EUF) {
869     assert(EUF == 1 &&
870            "A high UF for the epilogue loop is likely not beneficial.");
871   }
872 };
873 
874 /// An extension of the inner loop vectorizer that creates a skeleton for a
875 /// vectorized loop that has its epilogue (residual) also vectorized.
876 /// The idea is to run the vplan on a given loop twice, firstly to setup the
877 /// skeleton and vectorize the main loop, and secondly to complete the skeleton
878 /// from the first step and vectorize the epilogue.  This is achieved by
879 /// deriving two concrete strategy classes from this base class and invoking
880 /// them in succession from the loop vectorizer planner.
881 class InnerLoopAndEpilogueVectorizer : public InnerLoopVectorizer {
882 public:
883   InnerLoopAndEpilogueVectorizer(
884       Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI,
885       DominatorTree *DT, const TargetLibraryInfo *TLI,
886       const TargetTransformInfo *TTI, AssumptionCache *AC,
887       OptimizationRemarkEmitter *ORE, EpilogueLoopVectorizationInfo &EPI,
888       LoopVectorizationLegality *LVL, llvm::LoopVectorizationCostModel *CM,
889       BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI,
890       GeneratedRTChecks &Checks)
891       : InnerLoopVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
892                             EPI.MainLoopVF, EPI.MainLoopUF, LVL, CM, BFI, PSI,
893                             Checks),
894         EPI(EPI) {}
895 
896   // Override this function to handle the more complex control flow around the
897   // three loops.
898   BasicBlock *createVectorizedLoopSkeleton() final override {
899     return createEpilogueVectorizedLoopSkeleton();
900   }
901 
902   /// The interface for creating a vectorized skeleton using one of two
903   /// different strategies, each corresponding to one execution of the vplan
904   /// as described above.
905   virtual BasicBlock *createEpilogueVectorizedLoopSkeleton() = 0;
906 
907   /// Holds and updates state information required to vectorize the main loop
908   /// and its epilogue in two separate passes. This setup helps us avoid
909   /// regenerating and recomputing runtime safety checks. It also helps us to
910   /// shorten the iteration-count-check path length for the cases where the
911   /// iteration count of the loop is so small that the main vector loop is
912   /// completely skipped.
913   EpilogueLoopVectorizationInfo &EPI;
914 };
915 
916 /// A specialized derived class of inner loop vectorizer that performs
917 /// vectorization of *main* loops in the process of vectorizing loops and their
918 /// epilogues.
919 class EpilogueVectorizerMainLoop : public InnerLoopAndEpilogueVectorizer {
920 public:
921   EpilogueVectorizerMainLoop(
922       Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI,
923       DominatorTree *DT, const TargetLibraryInfo *TLI,
924       const TargetTransformInfo *TTI, AssumptionCache *AC,
925       OptimizationRemarkEmitter *ORE, EpilogueLoopVectorizationInfo &EPI,
926       LoopVectorizationLegality *LVL, llvm::LoopVectorizationCostModel *CM,
927       BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI,
928       GeneratedRTChecks &Check)
929       : InnerLoopAndEpilogueVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
930                                        EPI, LVL, CM, BFI, PSI, Check) {}
931   /// Implements the interface for creating a vectorized skeleton using the
932   /// *main loop* strategy (ie the first pass of vplan execution).
933   BasicBlock *createEpilogueVectorizedLoopSkeleton() final override;
934 
935 protected:
936   /// Emits an iteration count bypass check once for the main loop (when \p
937   /// ForEpilogue is false) and once for the epilogue loop (when \p
938   /// ForEpilogue is true).
939   BasicBlock *emitMinimumIterationCountCheck(Loop *L, BasicBlock *Bypass,
940                                              bool ForEpilogue);
941   void printDebugTracesAtStart() override;
942   void printDebugTracesAtEnd() override;
943 };
944 
945 // A specialized derived class of inner loop vectorizer that performs
946 // vectorization of *epilogue* loops in the process of vectorizing loops and
947 // their epilogues.
948 class EpilogueVectorizerEpilogueLoop : public InnerLoopAndEpilogueVectorizer {
949 public:
950   EpilogueVectorizerEpilogueLoop(
951       Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI,
952       DominatorTree *DT, const TargetLibraryInfo *TLI,
953       const TargetTransformInfo *TTI, AssumptionCache *AC,
954       OptimizationRemarkEmitter *ORE, EpilogueLoopVectorizationInfo &EPI,
955       LoopVectorizationLegality *LVL, llvm::LoopVectorizationCostModel *CM,
956       BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI,
957       GeneratedRTChecks &Checks)
958       : InnerLoopAndEpilogueVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
959                                        EPI, LVL, CM, BFI, PSI, Checks) {}
960   /// Implements the interface for creating a vectorized skeleton using the
961   /// *epilogue loop* strategy (ie the second pass of vplan execution).
962   BasicBlock *createEpilogueVectorizedLoopSkeleton() final override;
963 
964 protected:
965   /// Emits an iteration count bypass check after the main vector loop has
966   /// finished to see if there are any iterations left to execute by either
967   /// the vector epilogue or the scalar epilogue.
968   BasicBlock *emitMinimumVectorEpilogueIterCountCheck(Loop *L,
969                                                       BasicBlock *Bypass,
970                                                       BasicBlock *Insert);
971   void printDebugTracesAtStart() override;
972   void printDebugTracesAtEnd() override;
973 };
974 } // end namespace llvm
975 
976 /// Look for a meaningful debug location on the instruction or it's
977 /// operands.
978 static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
979   if (!I)
980     return I;
981 
982   DebugLoc Empty;
983   if (I->getDebugLoc() != Empty)
984     return I;
985 
986   for (Use &Op : I->operands()) {
987     if (Instruction *OpInst = dyn_cast<Instruction>(Op))
988       if (OpInst->getDebugLoc() != Empty)
989         return OpInst;
990   }
991 
992   return I;
993 }
994 
995 void InnerLoopVectorizer::setDebugLocFromInst(
996     const Value *V, Optional<IRBuilder<> *> CustomBuilder) {
997   IRBuilder<> *B = (CustomBuilder == None) ? &Builder : *CustomBuilder;
998   if (const Instruction *Inst = dyn_cast_or_null<Instruction>(V)) {
999     const DILocation *DIL = Inst->getDebugLoc();
1000 
1001     // When a FSDiscriminator is enabled, we don't need to add the multiply
1002     // factors to the discriminators.
1003     if (DIL && Inst->getFunction()->isDebugInfoForProfiling() &&
1004         !isa<DbgInfoIntrinsic>(Inst) && !EnableFSDiscriminator) {
1005       // FIXME: For scalable vectors, assume vscale=1.
1006       auto NewDIL =
1007           DIL->cloneByMultiplyingDuplicationFactor(UF * VF.getKnownMinValue());
1008       if (NewDIL)
1009         B->SetCurrentDebugLocation(NewDIL.getValue());
1010       else
1011         LLVM_DEBUG(dbgs()
1012                    << "Failed to create new discriminator: "
1013                    << DIL->getFilename() << " Line: " << DIL->getLine());
1014     } else
1015       B->SetCurrentDebugLocation(DIL);
1016   } else
1017     B->SetCurrentDebugLocation(DebugLoc());
1018 }
1019 
1020 /// Write a \p DebugMsg about vectorization to the debug output stream. If \p I
1021 /// is passed, the message relates to that particular instruction.
1022 #ifndef NDEBUG
1023 static void debugVectorizationMessage(const StringRef Prefix,
1024                                       const StringRef DebugMsg,
1025                                       Instruction *I) {
1026   dbgs() << "LV: " << Prefix << DebugMsg;
1027   if (I != nullptr)
1028     dbgs() << " " << *I;
1029   else
1030     dbgs() << '.';
1031   dbgs() << '\n';
1032 }
1033 #endif
1034 
1035 /// Create an analysis remark that explains why vectorization failed
1036 ///
1037 /// \p PassName is the name of the pass (e.g. can be AlwaysPrint).  \p
1038 /// RemarkName is the identifier for the remark.  If \p I is passed it is an
1039 /// instruction that prevents vectorization.  Otherwise \p TheLoop is used for
1040 /// the location of the remark.  \return the remark object that can be
1041 /// streamed to.
1042 static OptimizationRemarkAnalysis createLVAnalysis(const char *PassName,
1043     StringRef RemarkName, Loop *TheLoop, Instruction *I) {
1044   Value *CodeRegion = TheLoop->getHeader();
1045   DebugLoc DL = TheLoop->getStartLoc();
1046 
1047   if (I) {
1048     CodeRegion = I->getParent();
1049     // If there is no debug location attached to the instruction, revert back to
1050     // using the loop's.
1051     if (I->getDebugLoc())
1052       DL = I->getDebugLoc();
1053   }
1054 
1055   return OptimizationRemarkAnalysis(PassName, RemarkName, DL, CodeRegion);
1056 }
1057 
1058 /// Return a value for Step multiplied by VF.
1059 static Value *createStepForVF(IRBuilder<> &B, Type *Ty, ElementCount VF,
1060                               int64_t Step) {
1061   assert(Ty->isIntegerTy() && "Expected an integer step");
1062   Constant *StepVal = ConstantInt::get(Ty, Step * VF.getKnownMinValue());
1063   return VF.isScalable() ? B.CreateVScale(StepVal) : StepVal;
1064 }
1065 
1066 namespace llvm {
1067 
1068 /// Return the runtime value for VF.
1069 Value *getRuntimeVF(IRBuilder<> &B, Type *Ty, ElementCount VF) {
1070   Constant *EC = ConstantInt::get(Ty, VF.getKnownMinValue());
1071   return VF.isScalable() ? B.CreateVScale(EC) : EC;
1072 }
1073 
1074 static Value *getRuntimeVFAsFloat(IRBuilder<> &B, Type *FTy, ElementCount VF) {
1075   assert(FTy->isFloatingPointTy() && "Expected floating point type!");
1076   Type *IntTy = IntegerType::get(FTy->getContext(), FTy->getScalarSizeInBits());
1077   Value *RuntimeVF = getRuntimeVF(B, IntTy, VF);
1078   return B.CreateUIToFP(RuntimeVF, FTy);
1079 }
1080 
1081 void reportVectorizationFailure(const StringRef DebugMsg,
1082                                 const StringRef OREMsg, const StringRef ORETag,
1083                                 OptimizationRemarkEmitter *ORE, Loop *TheLoop,
1084                                 Instruction *I) {
1085   LLVM_DEBUG(debugVectorizationMessage("Not vectorizing: ", DebugMsg, I));
1086   LoopVectorizeHints Hints(TheLoop, true /* doesn't matter */, *ORE);
1087   ORE->emit(
1088       createLVAnalysis(Hints.vectorizeAnalysisPassName(), ORETag, TheLoop, I)
1089       << "loop not vectorized: " << OREMsg);
1090 }
1091 
1092 void reportVectorizationInfo(const StringRef Msg, const StringRef ORETag,
1093                              OptimizationRemarkEmitter *ORE, Loop *TheLoop,
1094                              Instruction *I) {
1095   LLVM_DEBUG(debugVectorizationMessage("", Msg, I));
1096   LoopVectorizeHints Hints(TheLoop, true /* doesn't matter */, *ORE);
1097   ORE->emit(
1098       createLVAnalysis(Hints.vectorizeAnalysisPassName(), ORETag, TheLoop, I)
1099       << Msg);
1100 }
1101 
1102 } // end namespace llvm
1103 
1104 #ifndef NDEBUG
1105 /// \return string containing a file name and a line # for the given loop.
1106 static std::string getDebugLocString(const Loop *L) {
1107   std::string Result;
1108   if (L) {
1109     raw_string_ostream OS(Result);
1110     if (const DebugLoc LoopDbgLoc = L->getStartLoc())
1111       LoopDbgLoc.print(OS);
1112     else
1113       // Just print the module name.
1114       OS << L->getHeader()->getParent()->getParent()->getModuleIdentifier();
1115     OS.flush();
1116   }
1117   return Result;
1118 }
1119 #endif
1120 
1121 void InnerLoopVectorizer::addNewMetadata(Instruction *To,
1122                                          const Instruction *Orig) {
1123   // If the loop was versioned with memchecks, add the corresponding no-alias
1124   // metadata.
1125   if (LVer && (isa<LoadInst>(Orig) || isa<StoreInst>(Orig)))
1126     LVer->annotateInstWithNoAlias(To, Orig);
1127 }
1128 
1129 void InnerLoopVectorizer::collectPoisonGeneratingRecipes(
1130     VPTransformState &State) {
1131 
1132   // Collect recipes in the backward slice of `Root` that may generate a poison
1133   // value that is used after vectorization.
1134   SmallPtrSet<VPRecipeBase *, 16> Visited;
1135   auto collectPoisonGeneratingInstrsInBackwardSlice([&](VPRecipeBase *Root) {
1136     SmallVector<VPRecipeBase *, 16> Worklist;
1137     Worklist.push_back(Root);
1138 
1139     // Traverse the backward slice of Root through its use-def chain.
1140     while (!Worklist.empty()) {
1141       VPRecipeBase *CurRec = Worklist.back();
1142       Worklist.pop_back();
1143 
1144       if (!Visited.insert(CurRec).second)
1145         continue;
1146 
1147       // Prune search if we find another recipe generating a widen memory
1148       // instruction. Widen memory instructions involved in address computation
1149       // will lead to gather/scatter instructions, which don't need to be
1150       // handled.
1151       if (isa<VPWidenMemoryInstructionRecipe>(CurRec) ||
1152           isa<VPInterleaveRecipe>(CurRec))
1153         continue;
1154 
1155       // This recipe contributes to the address computation of a widen
1156       // load/store. Collect recipe if its underlying instruction has
1157       // poison-generating flags.
1158       Instruction *Instr = CurRec->getUnderlyingInstr();
1159       if (Instr && Instr->hasPoisonGeneratingFlags())
1160         State.MayGeneratePoisonRecipes.insert(CurRec);
1161 
1162       // Add new definitions to the worklist.
1163       for (VPValue *operand : CurRec->operands())
1164         if (VPDef *OpDef = operand->getDef())
1165           Worklist.push_back(cast<VPRecipeBase>(OpDef));
1166     }
1167   });
1168 
1169   // Traverse all the recipes in the VPlan and collect the poison-generating
1170   // recipes in the backward slice starting at the address of a VPWidenRecipe or
1171   // VPInterleaveRecipe.
1172   auto Iter = depth_first(
1173       VPBlockRecursiveTraversalWrapper<VPBlockBase *>(State.Plan->getEntry()));
1174   for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(Iter)) {
1175     for (VPRecipeBase &Recipe : *VPBB) {
1176       if (auto *WidenRec = dyn_cast<VPWidenMemoryInstructionRecipe>(&Recipe)) {
1177         Instruction *UnderlyingInstr = WidenRec->getUnderlyingInstr();
1178         VPDef *AddrDef = WidenRec->getAddr()->getDef();
1179         if (AddrDef && WidenRec->isConsecutive() && UnderlyingInstr &&
1180             Legal->blockNeedsPredication(UnderlyingInstr->getParent()))
1181           collectPoisonGeneratingInstrsInBackwardSlice(
1182               cast<VPRecipeBase>(AddrDef));
1183       } else if (auto *InterleaveRec = dyn_cast<VPInterleaveRecipe>(&Recipe)) {
1184         VPDef *AddrDef = InterleaveRec->getAddr()->getDef();
1185         if (AddrDef) {
1186           // Check if any member of the interleave group needs predication.
1187           const InterleaveGroup<Instruction> *InterGroup =
1188               InterleaveRec->getInterleaveGroup();
1189           bool NeedPredication = false;
1190           for (int I = 0, NumMembers = InterGroup->getNumMembers();
1191                I < NumMembers; ++I) {
1192             Instruction *Member = InterGroup->getMember(I);
1193             if (Member)
1194               NeedPredication |=
1195                   Legal->blockNeedsPredication(Member->getParent());
1196           }
1197 
1198           if (NeedPredication)
1199             collectPoisonGeneratingInstrsInBackwardSlice(
1200                 cast<VPRecipeBase>(AddrDef));
1201         }
1202       }
1203     }
1204   }
1205 }
1206 
1207 void InnerLoopVectorizer::addMetadata(Instruction *To,
1208                                       Instruction *From) {
1209   propagateMetadata(To, From);
1210   addNewMetadata(To, From);
1211 }
1212 
1213 void InnerLoopVectorizer::addMetadata(ArrayRef<Value *> To,
1214                                       Instruction *From) {
1215   for (Value *V : To) {
1216     if (Instruction *I = dyn_cast<Instruction>(V))
1217       addMetadata(I, From);
1218   }
1219 }
1220 
1221 namespace llvm {
1222 
1223 // Loop vectorization cost-model hints how the scalar epilogue loop should be
1224 // lowered.
1225 enum ScalarEpilogueLowering {
1226 
1227   // The default: allowing scalar epilogues.
1228   CM_ScalarEpilogueAllowed,
1229 
1230   // Vectorization with OptForSize: don't allow epilogues.
1231   CM_ScalarEpilogueNotAllowedOptSize,
1232 
1233   // A special case of vectorisation with OptForSize: loops with a very small
1234   // trip count are considered for vectorization under OptForSize, thereby
1235   // making sure the cost of their loop body is dominant, free of runtime
1236   // guards and scalar iteration overheads.
1237   CM_ScalarEpilogueNotAllowedLowTripLoop,
1238 
1239   // Loop hint predicate indicating an epilogue is undesired.
1240   CM_ScalarEpilogueNotNeededUsePredicate,
1241 
1242   // Directive indicating we must either tail fold or not vectorize
1243   CM_ScalarEpilogueNotAllowedUsePredicate
1244 };
1245 
1246 /// ElementCountComparator creates a total ordering for ElementCount
1247 /// for the purposes of using it in a set structure.
1248 struct ElementCountComparator {
1249   bool operator()(const ElementCount &LHS, const ElementCount &RHS) const {
1250     return std::make_tuple(LHS.isScalable(), LHS.getKnownMinValue()) <
1251            std::make_tuple(RHS.isScalable(), RHS.getKnownMinValue());
1252   }
1253 };
1254 using ElementCountSet = SmallSet<ElementCount, 16, ElementCountComparator>;
1255 
1256 /// LoopVectorizationCostModel - estimates the expected speedups due to
1257 /// vectorization.
1258 /// In many cases vectorization is not profitable. This can happen because of
1259 /// a number of reasons. In this class we mainly attempt to predict the
1260 /// expected speedup/slowdowns due to the supported instruction set. We use the
1261 /// TargetTransformInfo to query the different backends for the cost of
1262 /// different operations.
1263 class LoopVectorizationCostModel {
1264 public:
1265   LoopVectorizationCostModel(ScalarEpilogueLowering SEL, Loop *L,
1266                              PredicatedScalarEvolution &PSE, LoopInfo *LI,
1267                              LoopVectorizationLegality *Legal,
1268                              const TargetTransformInfo &TTI,
1269                              const TargetLibraryInfo *TLI, DemandedBits *DB,
1270                              AssumptionCache *AC,
1271                              OptimizationRemarkEmitter *ORE, const Function *F,
1272                              const LoopVectorizeHints *Hints,
1273                              InterleavedAccessInfo &IAI)
1274       : ScalarEpilogueStatus(SEL), TheLoop(L), PSE(PSE), LI(LI), Legal(Legal),
1275         TTI(TTI), TLI(TLI), DB(DB), AC(AC), ORE(ORE), TheFunction(F),
1276         Hints(Hints), InterleaveInfo(IAI) {}
1277 
1278   /// \return An upper bound for the vectorization factors (both fixed and
1279   /// scalable). If the factors are 0, vectorization and interleaving should be
1280   /// avoided up front.
1281   FixedScalableVFPair computeMaxVF(ElementCount UserVF, unsigned UserIC);
1282 
1283   /// \return True if runtime checks are required for vectorization, and false
1284   /// otherwise.
1285   bool runtimeChecksRequired();
1286 
1287   /// \return The most profitable vectorization factor and the cost of that VF.
1288   /// This method checks every VF in \p CandidateVFs. If UserVF is not ZERO
1289   /// then this vectorization factor will be selected if vectorization is
1290   /// possible.
1291   VectorizationFactor
1292   selectVectorizationFactor(const ElementCountSet &CandidateVFs);
1293 
1294   VectorizationFactor
1295   selectEpilogueVectorizationFactor(const ElementCount MaxVF,
1296                                     const LoopVectorizationPlanner &LVP);
1297 
1298   /// Setup cost-based decisions for user vectorization factor.
1299   /// \return true if the UserVF is a feasible VF to be chosen.
1300   bool selectUserVectorizationFactor(ElementCount UserVF) {
1301     collectUniformsAndScalars(UserVF);
1302     collectInstsToScalarize(UserVF);
1303     return expectedCost(UserVF).first.isValid();
1304   }
1305 
1306   /// \return The size (in bits) of the smallest and widest types in the code
1307   /// that needs to be vectorized. We ignore values that remain scalar such as
1308   /// 64 bit loop indices.
1309   std::pair<unsigned, unsigned> getSmallestAndWidestTypes();
1310 
1311   /// \return The desired interleave count.
1312   /// If interleave count has been specified by metadata it will be returned.
1313   /// Otherwise, the interleave count is computed and returned. VF and LoopCost
1314   /// are the selected vectorization factor and the cost of the selected VF.
1315   unsigned selectInterleaveCount(ElementCount VF, unsigned LoopCost);
1316 
1317   /// Memory access instruction may be vectorized in more than one way.
1318   /// Form of instruction after vectorization depends on cost.
1319   /// This function takes cost-based decisions for Load/Store instructions
1320   /// and collects them in a map. This decisions map is used for building
1321   /// the lists of loop-uniform and loop-scalar instructions.
1322   /// The calculated cost is saved with widening decision in order to
1323   /// avoid redundant calculations.
1324   void setCostBasedWideningDecision(ElementCount VF);
1325 
1326   /// A struct that represents some properties of the register usage
1327   /// of a loop.
1328   struct RegisterUsage {
1329     /// Holds the number of loop invariant values that are used in the loop.
1330     /// The key is ClassID of target-provided register class.
1331     SmallMapVector<unsigned, unsigned, 4> LoopInvariantRegs;
1332     /// Holds the maximum number of concurrent live intervals in the loop.
1333     /// The key is ClassID of target-provided register class.
1334     SmallMapVector<unsigned, unsigned, 4> MaxLocalUsers;
1335   };
1336 
1337   /// \return Returns information about the register usages of the loop for the
1338   /// given vectorization factors.
1339   SmallVector<RegisterUsage, 8>
1340   calculateRegisterUsage(ArrayRef<ElementCount> VFs);
1341 
1342   /// Collect values we want to ignore in the cost model.
1343   void collectValuesToIgnore();
1344 
1345   /// Collect all element types in the loop for which widening is needed.
1346   void collectElementTypesForWidening();
1347 
1348   /// Split reductions into those that happen in the loop, and those that happen
1349   /// outside. In loop reductions are collected into InLoopReductionChains.
1350   void collectInLoopReductions();
1351 
1352   /// Returns true if we should use strict in-order reductions for the given
1353   /// RdxDesc. This is true if the -enable-strict-reductions flag is passed,
1354   /// the IsOrdered flag of RdxDesc is set and we do not allow reordering
1355   /// of FP operations.
1356   bool useOrderedReductions(const RecurrenceDescriptor &RdxDesc) {
1357     return !Hints->allowReordering() && RdxDesc.isOrdered();
1358   }
1359 
1360   /// \returns The smallest bitwidth each instruction can be represented with.
1361   /// The vector equivalents of these instructions should be truncated to this
1362   /// type.
1363   const MapVector<Instruction *, uint64_t> &getMinimalBitwidths() const {
1364     return MinBWs;
1365   }
1366 
1367   /// \returns True if it is more profitable to scalarize instruction \p I for
1368   /// vectorization factor \p VF.
1369   bool isProfitableToScalarize(Instruction *I, ElementCount VF) const {
1370     assert(VF.isVector() &&
1371            "Profitable to scalarize relevant only for VF > 1.");
1372 
1373     // Cost model is not run in the VPlan-native path - return conservative
1374     // result until this changes.
1375     if (EnableVPlanNativePath)
1376       return false;
1377 
1378     auto Scalars = InstsToScalarize.find(VF);
1379     assert(Scalars != InstsToScalarize.end() &&
1380            "VF not yet analyzed for scalarization profitability");
1381     return Scalars->second.find(I) != Scalars->second.end();
1382   }
1383 
1384   /// Returns true if \p I is known to be uniform after vectorization.
1385   bool isUniformAfterVectorization(Instruction *I, ElementCount VF) const {
1386     if (VF.isScalar())
1387       return true;
1388 
1389     // Cost model is not run in the VPlan-native path - return conservative
1390     // result until this changes.
1391     if (EnableVPlanNativePath)
1392       return false;
1393 
1394     auto UniformsPerVF = Uniforms.find(VF);
1395     assert(UniformsPerVF != Uniforms.end() &&
1396            "VF not yet analyzed for uniformity");
1397     return UniformsPerVF->second.count(I);
1398   }
1399 
1400   /// Returns true if \p I is known to be scalar after vectorization.
1401   bool isScalarAfterVectorization(Instruction *I, ElementCount VF) const {
1402     if (VF.isScalar())
1403       return true;
1404 
1405     // Cost model is not run in the VPlan-native path - return conservative
1406     // result until this changes.
1407     if (EnableVPlanNativePath)
1408       return false;
1409 
1410     auto ScalarsPerVF = Scalars.find(VF);
1411     assert(ScalarsPerVF != Scalars.end() &&
1412            "Scalar values are not calculated for VF");
1413     return ScalarsPerVF->second.count(I);
1414   }
1415 
1416   /// \returns True if instruction \p I can be truncated to a smaller bitwidth
1417   /// for vectorization factor \p VF.
1418   bool canTruncateToMinimalBitwidth(Instruction *I, ElementCount VF) const {
1419     return VF.isVector() && MinBWs.find(I) != MinBWs.end() &&
1420            !isProfitableToScalarize(I, VF) &&
1421            !isScalarAfterVectorization(I, VF);
1422   }
1423 
1424   /// Decision that was taken during cost calculation for memory instruction.
1425   enum InstWidening {
1426     CM_Unknown,
1427     CM_Widen,         // For consecutive accesses with stride +1.
1428     CM_Widen_Reverse, // For consecutive accesses with stride -1.
1429     CM_Interleave,
1430     CM_GatherScatter,
1431     CM_Scalarize
1432   };
1433 
1434   /// Save vectorization decision \p W and \p Cost taken by the cost model for
1435   /// instruction \p I and vector width \p VF.
1436   void setWideningDecision(Instruction *I, ElementCount VF, InstWidening W,
1437                            InstructionCost Cost) {
1438     assert(VF.isVector() && "Expected VF >=2");
1439     WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
1440   }
1441 
1442   /// Save vectorization decision \p W and \p Cost taken by the cost model for
1443   /// interleaving group \p Grp and vector width \p VF.
1444   void setWideningDecision(const InterleaveGroup<Instruction> *Grp,
1445                            ElementCount VF, InstWidening W,
1446                            InstructionCost Cost) {
1447     assert(VF.isVector() && "Expected VF >=2");
1448     /// Broadcast this decicion to all instructions inside the group.
1449     /// But the cost will be assigned to one instruction only.
1450     for (unsigned i = 0; i < Grp->getFactor(); ++i) {
1451       if (auto *I = Grp->getMember(i)) {
1452         if (Grp->getInsertPos() == I)
1453           WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
1454         else
1455           WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, 0);
1456       }
1457     }
1458   }
1459 
1460   /// Return the cost model decision for the given instruction \p I and vector
1461   /// width \p VF. Return CM_Unknown if this instruction did not pass
1462   /// through the cost modeling.
1463   InstWidening getWideningDecision(Instruction *I, ElementCount VF) const {
1464     assert(VF.isVector() && "Expected VF to be a vector VF");
1465     // Cost model is not run in the VPlan-native path - return conservative
1466     // result until this changes.
1467     if (EnableVPlanNativePath)
1468       return CM_GatherScatter;
1469 
1470     std::pair<Instruction *, ElementCount> InstOnVF = std::make_pair(I, VF);
1471     auto Itr = WideningDecisions.find(InstOnVF);
1472     if (Itr == WideningDecisions.end())
1473       return CM_Unknown;
1474     return Itr->second.first;
1475   }
1476 
1477   /// Return the vectorization cost for the given instruction \p I and vector
1478   /// width \p VF.
1479   InstructionCost getWideningCost(Instruction *I, ElementCount VF) {
1480     assert(VF.isVector() && "Expected VF >=2");
1481     std::pair<Instruction *, ElementCount> InstOnVF = std::make_pair(I, VF);
1482     assert(WideningDecisions.find(InstOnVF) != WideningDecisions.end() &&
1483            "The cost is not calculated");
1484     return WideningDecisions[InstOnVF].second;
1485   }
1486 
1487   /// Return True if instruction \p I is an optimizable truncate whose operand
1488   /// is an induction variable. Such a truncate will be removed by adding a new
1489   /// induction variable with the destination type.
1490   bool isOptimizableIVTruncate(Instruction *I, ElementCount VF) {
1491     // If the instruction is not a truncate, return false.
1492     auto *Trunc = dyn_cast<TruncInst>(I);
1493     if (!Trunc)
1494       return false;
1495 
1496     // Get the source and destination types of the truncate.
1497     Type *SrcTy = ToVectorTy(cast<CastInst>(I)->getSrcTy(), VF);
1498     Type *DestTy = ToVectorTy(cast<CastInst>(I)->getDestTy(), VF);
1499 
1500     // If the truncate is free for the given types, return false. Replacing a
1501     // free truncate with an induction variable would add an induction variable
1502     // update instruction to each iteration of the loop. We exclude from this
1503     // check the primary induction variable since it will need an update
1504     // instruction regardless.
1505     Value *Op = Trunc->getOperand(0);
1506     if (Op != Legal->getPrimaryInduction() && TTI.isTruncateFree(SrcTy, DestTy))
1507       return false;
1508 
1509     // If the truncated value is not an induction variable, return false.
1510     return Legal->isInductionPhi(Op);
1511   }
1512 
1513   /// Collects the instructions to scalarize for each predicated instruction in
1514   /// the loop.
1515   void collectInstsToScalarize(ElementCount VF);
1516 
1517   /// Collect Uniform and Scalar values for the given \p VF.
1518   /// The sets depend on CM decision for Load/Store instructions
1519   /// that may be vectorized as interleave, gather-scatter or scalarized.
1520   void collectUniformsAndScalars(ElementCount VF) {
1521     // Do the analysis once.
1522     if (VF.isScalar() || Uniforms.find(VF) != Uniforms.end())
1523       return;
1524     setCostBasedWideningDecision(VF);
1525     collectLoopUniforms(VF);
1526     collectLoopScalars(VF);
1527   }
1528 
1529   /// Returns true if the target machine supports masked store operation
1530   /// for the given \p DataType and kind of access to \p Ptr.
1531   bool isLegalMaskedStore(Type *DataType, Value *Ptr, Align Alignment) const {
1532     return Legal->isConsecutivePtr(DataType, Ptr) &&
1533            TTI.isLegalMaskedStore(DataType, Alignment);
1534   }
1535 
1536   /// Returns true if the target machine supports masked load operation
1537   /// for the given \p DataType and kind of access to \p Ptr.
1538   bool isLegalMaskedLoad(Type *DataType, Value *Ptr, Align Alignment) const {
1539     return Legal->isConsecutivePtr(DataType, Ptr) &&
1540            TTI.isLegalMaskedLoad(DataType, Alignment);
1541   }
1542 
1543   /// Returns true if the target machine can represent \p V as a masked gather
1544   /// or scatter operation.
1545   bool isLegalGatherOrScatter(Value *V) {
1546     bool LI = isa<LoadInst>(V);
1547     bool SI = isa<StoreInst>(V);
1548     if (!LI && !SI)
1549       return false;
1550     auto *Ty = getLoadStoreType(V);
1551     Align Align = getLoadStoreAlignment(V);
1552     return (LI && TTI.isLegalMaskedGather(Ty, Align)) ||
1553            (SI && TTI.isLegalMaskedScatter(Ty, Align));
1554   }
1555 
1556   /// Returns true if the target machine supports all of the reduction
1557   /// variables found for the given VF.
1558   bool canVectorizeReductions(ElementCount VF) const {
1559     return (all_of(Legal->getReductionVars(), [&](auto &Reduction) -> bool {
1560       const RecurrenceDescriptor &RdxDesc = Reduction.second;
1561       return TTI.isLegalToVectorizeReduction(RdxDesc, VF);
1562     }));
1563   }
1564 
1565   /// Returns true if \p I is an instruction that will be scalarized with
1566   /// predication. Such instructions include conditional stores and
1567   /// instructions that may divide by zero.
1568   /// If a non-zero VF has been calculated, we check if I will be scalarized
1569   /// predication for that VF.
1570   bool isScalarWithPredication(Instruction *I) const;
1571 
1572   // Returns true if \p I is an instruction that will be predicated either
1573   // through scalar predication or masked load/store or masked gather/scatter.
1574   // Superset of instructions that return true for isScalarWithPredication.
1575   bool isPredicatedInst(Instruction *I, bool IsKnownUniform = false) {
1576     // When we know the load is uniform and the original scalar loop was not
1577     // predicated we don't need to mark it as a predicated instruction. Any
1578     // vectorised blocks created when tail-folding are something artificial we
1579     // have introduced and we know there is always at least one active lane.
1580     // That's why we call Legal->blockNeedsPredication here because it doesn't
1581     // query tail-folding.
1582     if (IsKnownUniform && isa<LoadInst>(I) &&
1583         !Legal->blockNeedsPredication(I->getParent()))
1584       return false;
1585     if (!blockNeedsPredicationForAnyReason(I->getParent()))
1586       return false;
1587     // Loads and stores that need some form of masked operation are predicated
1588     // instructions.
1589     if (isa<LoadInst>(I) || isa<StoreInst>(I))
1590       return Legal->isMaskRequired(I);
1591     return isScalarWithPredication(I);
1592   }
1593 
1594   /// Returns true if \p I is a memory instruction with consecutive memory
1595   /// access that can be widened.
1596   bool
1597   memoryInstructionCanBeWidened(Instruction *I,
1598                                 ElementCount VF = ElementCount::getFixed(1));
1599 
1600   /// Returns true if \p I is a memory instruction in an interleaved-group
1601   /// of memory accesses that can be vectorized with wide vector loads/stores
1602   /// and shuffles.
1603   bool
1604   interleavedAccessCanBeWidened(Instruction *I,
1605                                 ElementCount VF = ElementCount::getFixed(1));
1606 
1607   /// Check if \p Instr belongs to any interleaved access group.
1608   bool isAccessInterleaved(Instruction *Instr) {
1609     return InterleaveInfo.isInterleaved(Instr);
1610   }
1611 
1612   /// Get the interleaved access group that \p Instr belongs to.
1613   const InterleaveGroup<Instruction> *
1614   getInterleavedAccessGroup(Instruction *Instr) {
1615     return InterleaveInfo.getInterleaveGroup(Instr);
1616   }
1617 
1618   /// Returns true if we're required to use a scalar epilogue for at least
1619   /// the final iteration of the original loop.
1620   bool requiresScalarEpilogue(ElementCount VF) const {
1621     if (!isScalarEpilogueAllowed())
1622       return false;
1623     // If we might exit from anywhere but the latch, must run the exiting
1624     // iteration in scalar form.
1625     if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch())
1626       return true;
1627     return VF.isVector() && InterleaveInfo.requiresScalarEpilogue();
1628   }
1629 
1630   /// Returns true if a scalar epilogue is not allowed due to optsize or a
1631   /// loop hint annotation.
1632   bool isScalarEpilogueAllowed() const {
1633     return ScalarEpilogueStatus == CM_ScalarEpilogueAllowed;
1634   }
1635 
1636   /// Returns true if all loop blocks should be masked to fold tail loop.
1637   bool foldTailByMasking() const { return FoldTailByMasking; }
1638 
1639   /// Returns true if the instructions in this block requires predication
1640   /// for any reason, e.g. because tail folding now requires a predicate
1641   /// or because the block in the original loop was predicated.
1642   bool blockNeedsPredicationForAnyReason(BasicBlock *BB) const {
1643     return foldTailByMasking() || Legal->blockNeedsPredication(BB);
1644   }
1645 
1646   /// A SmallMapVector to store the InLoop reduction op chains, mapping phi
1647   /// nodes to the chain of instructions representing the reductions. Uses a
1648   /// MapVector to ensure deterministic iteration order.
1649   using ReductionChainMap =
1650       SmallMapVector<PHINode *, SmallVector<Instruction *, 4>, 4>;
1651 
1652   /// Return the chain of instructions representing an inloop reduction.
1653   const ReductionChainMap &getInLoopReductionChains() const {
1654     return InLoopReductionChains;
1655   }
1656 
1657   /// Returns true if the Phi is part of an inloop reduction.
1658   bool isInLoopReduction(PHINode *Phi) const {
1659     return InLoopReductionChains.count(Phi);
1660   }
1661 
1662   /// Estimate cost of an intrinsic call instruction CI if it were vectorized
1663   /// with factor VF.  Return the cost of the instruction, including
1664   /// scalarization overhead if it's needed.
1665   InstructionCost getVectorIntrinsicCost(CallInst *CI, ElementCount VF) const;
1666 
1667   /// Estimate cost of a call instruction CI if it were vectorized with factor
1668   /// VF. Return the cost of the instruction, including scalarization overhead
1669   /// if it's needed. The flag NeedToScalarize shows if the call needs to be
1670   /// scalarized -
1671   /// i.e. either vector version isn't available, or is too expensive.
1672   InstructionCost getVectorCallCost(CallInst *CI, ElementCount VF,
1673                                     bool &NeedToScalarize) const;
1674 
1675   /// Returns true if the per-lane cost of VectorizationFactor A is lower than
1676   /// that of B.
1677   bool isMoreProfitable(const VectorizationFactor &A,
1678                         const VectorizationFactor &B) const;
1679 
1680   /// Invalidates decisions already taken by the cost model.
1681   void invalidateCostModelingDecisions() {
1682     WideningDecisions.clear();
1683     Uniforms.clear();
1684     Scalars.clear();
1685   }
1686 
1687 private:
1688   unsigned NumPredStores = 0;
1689 
1690   /// \return An upper bound for the vectorization factors for both
1691   /// fixed and scalable vectorization, where the minimum-known number of
1692   /// elements is a power-of-2 larger than zero. If scalable vectorization is
1693   /// disabled or unsupported, then the scalable part will be equal to
1694   /// ElementCount::getScalable(0).
1695   FixedScalableVFPair computeFeasibleMaxVF(unsigned ConstTripCount,
1696                                            ElementCount UserVF,
1697                                            bool FoldTailByMasking);
1698 
1699   /// \return the maximized element count based on the targets vector
1700   /// registers and the loop trip-count, but limited to a maximum safe VF.
1701   /// This is a helper function of computeFeasibleMaxVF.
1702   /// FIXME: MaxSafeVF is currently passed by reference to avoid some obscure
1703   /// issue that occurred on one of the buildbots which cannot be reproduced
1704   /// without having access to the properietary compiler (see comments on
1705   /// D98509). The issue is currently under investigation and this workaround
1706   /// will be removed as soon as possible.
1707   ElementCount getMaximizedVFForTarget(unsigned ConstTripCount,
1708                                        unsigned SmallestType,
1709                                        unsigned WidestType,
1710                                        const ElementCount &MaxSafeVF,
1711                                        bool FoldTailByMasking);
1712 
1713   /// \return the maximum legal scalable VF, based on the safe max number
1714   /// of elements.
1715   ElementCount getMaxLegalScalableVF(unsigned MaxSafeElements);
1716 
1717   /// The vectorization cost is a combination of the cost itself and a boolean
1718   /// indicating whether any of the contributing operations will actually
1719   /// operate on vector values after type legalization in the backend. If this
1720   /// latter value is false, then all operations will be scalarized (i.e. no
1721   /// vectorization has actually taken place).
1722   using VectorizationCostTy = std::pair<InstructionCost, bool>;
1723 
1724   /// Returns the expected execution cost. The unit of the cost does
1725   /// not matter because we use the 'cost' units to compare different
1726   /// vector widths. The cost that is returned is *not* normalized by
1727   /// the factor width. If \p Invalid is not nullptr, this function
1728   /// will add a pair(Instruction*, ElementCount) to \p Invalid for
1729   /// each instruction that has an Invalid cost for the given VF.
1730   using InstructionVFPair = std::pair<Instruction *, ElementCount>;
1731   VectorizationCostTy
1732   expectedCost(ElementCount VF,
1733                SmallVectorImpl<InstructionVFPair> *Invalid = nullptr);
1734 
1735   /// Returns the execution time cost of an instruction for a given vector
1736   /// width. Vector width of one means scalar.
1737   VectorizationCostTy getInstructionCost(Instruction *I, ElementCount VF);
1738 
1739   /// The cost-computation logic from getInstructionCost which provides
1740   /// the vector type as an output parameter.
1741   InstructionCost getInstructionCost(Instruction *I, ElementCount VF,
1742                                      Type *&VectorTy);
1743 
1744   /// Return the cost of instructions in an inloop reduction pattern, if I is
1745   /// part of that pattern.
1746   Optional<InstructionCost>
1747   getReductionPatternCost(Instruction *I, ElementCount VF, Type *VectorTy,
1748                           TTI::TargetCostKind CostKind);
1749 
1750   /// Calculate vectorization cost of memory instruction \p I.
1751   InstructionCost getMemoryInstructionCost(Instruction *I, ElementCount VF);
1752 
1753   /// The cost computation for scalarized memory instruction.
1754   InstructionCost getMemInstScalarizationCost(Instruction *I, ElementCount VF);
1755 
1756   /// The cost computation for interleaving group of memory instructions.
1757   InstructionCost getInterleaveGroupCost(Instruction *I, ElementCount VF);
1758 
1759   /// The cost computation for Gather/Scatter instruction.
1760   InstructionCost getGatherScatterCost(Instruction *I, ElementCount VF);
1761 
1762   /// The cost computation for widening instruction \p I with consecutive
1763   /// memory access.
1764   InstructionCost getConsecutiveMemOpCost(Instruction *I, ElementCount VF);
1765 
1766   /// The cost calculation for Load/Store instruction \p I with uniform pointer -
1767   /// Load: scalar load + broadcast.
1768   /// Store: scalar store + (loop invariant value stored? 0 : extract of last
1769   /// element)
1770   InstructionCost getUniformMemOpCost(Instruction *I, ElementCount VF);
1771 
1772   /// Estimate the overhead of scalarizing an instruction. This is a
1773   /// convenience wrapper for the type-based getScalarizationOverhead API.
1774   InstructionCost getScalarizationOverhead(Instruction *I,
1775                                            ElementCount VF) const;
1776 
1777   /// Returns whether the instruction is a load or store and will be a emitted
1778   /// as a vector operation.
1779   bool isConsecutiveLoadOrStore(Instruction *I);
1780 
1781   /// Returns true if an artificially high cost for emulated masked memrefs
1782   /// should be used.
1783   bool useEmulatedMaskMemRefHack(Instruction *I);
1784 
1785   /// Map of scalar integer values to the smallest bitwidth they can be legally
1786   /// represented as. The vector equivalents of these values should be truncated
1787   /// to this type.
1788   MapVector<Instruction *, uint64_t> MinBWs;
1789 
1790   /// A type representing the costs for instructions if they were to be
1791   /// scalarized rather than vectorized. The entries are Instruction-Cost
1792   /// pairs.
1793   using ScalarCostsTy = DenseMap<Instruction *, InstructionCost>;
1794 
1795   /// A set containing all BasicBlocks that are known to present after
1796   /// vectorization as a predicated block.
1797   SmallPtrSet<BasicBlock *, 4> PredicatedBBsAfterVectorization;
1798 
1799   /// Records whether it is allowed to have the original scalar loop execute at
1800   /// least once. This may be needed as a fallback loop in case runtime
1801   /// aliasing/dependence checks fail, or to handle the tail/remainder
1802   /// iterations when the trip count is unknown or doesn't divide by the VF,
1803   /// or as a peel-loop to handle gaps in interleave-groups.
1804   /// Under optsize and when the trip count is very small we don't allow any
1805   /// iterations to execute in the scalar loop.
1806   ScalarEpilogueLowering ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
1807 
1808   /// All blocks of loop are to be masked to fold tail of scalar iterations.
1809   bool FoldTailByMasking = false;
1810 
1811   /// A map holding scalar costs for different vectorization factors. The
1812   /// presence of a cost for an instruction in the mapping indicates that the
1813   /// instruction will be scalarized when vectorizing with the associated
1814   /// vectorization factor. The entries are VF-ScalarCostTy pairs.
1815   DenseMap<ElementCount, ScalarCostsTy> InstsToScalarize;
1816 
1817   /// Holds the instructions known to be uniform after vectorization.
1818   /// The data is collected per VF.
1819   DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> Uniforms;
1820 
1821   /// Holds the instructions known to be scalar after vectorization.
1822   /// The data is collected per VF.
1823   DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> Scalars;
1824 
1825   /// Holds the instructions (address computations) that are forced to be
1826   /// scalarized.
1827   DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> ForcedScalars;
1828 
1829   /// PHINodes of the reductions that should be expanded in-loop along with
1830   /// their associated chains of reduction operations, in program order from top
1831   /// (PHI) to bottom
1832   ReductionChainMap InLoopReductionChains;
1833 
1834   /// A Map of inloop reduction operations and their immediate chain operand.
1835   /// FIXME: This can be removed once reductions can be costed correctly in
1836   /// vplan. This was added to allow quick lookup to the inloop operations,
1837   /// without having to loop through InLoopReductionChains.
1838   DenseMap<Instruction *, Instruction *> InLoopReductionImmediateChains;
1839 
1840   /// Returns the expected difference in cost from scalarizing the expression
1841   /// feeding a predicated instruction \p PredInst. The instructions to
1842   /// scalarize and their scalar costs are collected in \p ScalarCosts. A
1843   /// non-negative return value implies the expression will be scalarized.
1844   /// Currently, only single-use chains are considered for scalarization.
1845   int computePredInstDiscount(Instruction *PredInst, ScalarCostsTy &ScalarCosts,
1846                               ElementCount VF);
1847 
1848   /// Collect the instructions that are uniform after vectorization. An
1849   /// instruction is uniform if we represent it with a single scalar value in
1850   /// the vectorized loop corresponding to each vector iteration. Examples of
1851   /// uniform instructions include pointer operands of consecutive or
1852   /// interleaved memory accesses. Note that although uniformity implies an
1853   /// instruction will be scalar, the reverse is not true. In general, a
1854   /// scalarized instruction will be represented by VF scalar values in the
1855   /// vectorized loop, each corresponding to an iteration of the original
1856   /// scalar loop.
1857   void collectLoopUniforms(ElementCount VF);
1858 
1859   /// Collect the instructions that are scalar after vectorization. An
1860   /// instruction is scalar if it is known to be uniform or will be scalarized
1861   /// during vectorization. collectLoopScalars should only add non-uniform nodes
1862   /// to the list if they are used by a load/store instruction that is marked as
1863   /// CM_Scalarize. Non-uniform scalarized instructions will be represented by
1864   /// VF values in the vectorized loop, each corresponding to an iteration of
1865   /// the original scalar loop.
1866   void collectLoopScalars(ElementCount VF);
1867 
1868   /// Keeps cost model vectorization decision and cost for instructions.
1869   /// Right now it is used for memory instructions only.
1870   using DecisionList = DenseMap<std::pair<Instruction *, ElementCount>,
1871                                 std::pair<InstWidening, InstructionCost>>;
1872 
1873   DecisionList WideningDecisions;
1874 
1875   /// Returns true if \p V is expected to be vectorized and it needs to be
1876   /// extracted.
1877   bool needsExtract(Value *V, ElementCount VF) const {
1878     Instruction *I = dyn_cast<Instruction>(V);
1879     if (VF.isScalar() || !I || !TheLoop->contains(I) ||
1880         TheLoop->isLoopInvariant(I))
1881       return false;
1882 
1883     // Assume we can vectorize V (and hence we need extraction) if the
1884     // scalars are not computed yet. This can happen, because it is called
1885     // via getScalarizationOverhead from setCostBasedWideningDecision, before
1886     // the scalars are collected. That should be a safe assumption in most
1887     // cases, because we check if the operands have vectorizable types
1888     // beforehand in LoopVectorizationLegality.
1889     return Scalars.find(VF) == Scalars.end() ||
1890            !isScalarAfterVectorization(I, VF);
1891   };
1892 
1893   /// Returns a range containing only operands needing to be extracted.
1894   SmallVector<Value *, 4> filterExtractingOperands(Instruction::op_range Ops,
1895                                                    ElementCount VF) const {
1896     return SmallVector<Value *, 4>(make_filter_range(
1897         Ops, [this, VF](Value *V) { return this->needsExtract(V, VF); }));
1898   }
1899 
1900   /// Determines if we have the infrastructure to vectorize loop \p L and its
1901   /// epilogue, assuming the main loop is vectorized by \p VF.
1902   bool isCandidateForEpilogueVectorization(const Loop &L,
1903                                            const ElementCount VF) const;
1904 
1905   /// Returns true if epilogue vectorization is considered profitable, and
1906   /// false otherwise.
1907   /// \p VF is the vectorization factor chosen for the original loop.
1908   bool isEpilogueVectorizationProfitable(const ElementCount VF) const;
1909 
1910 public:
1911   /// The loop that we evaluate.
1912   Loop *TheLoop;
1913 
1914   /// Predicated scalar evolution analysis.
1915   PredicatedScalarEvolution &PSE;
1916 
1917   /// Loop Info analysis.
1918   LoopInfo *LI;
1919 
1920   /// Vectorization legality.
1921   LoopVectorizationLegality *Legal;
1922 
1923   /// Vector target information.
1924   const TargetTransformInfo &TTI;
1925 
1926   /// Target Library Info.
1927   const TargetLibraryInfo *TLI;
1928 
1929   /// Demanded bits analysis.
1930   DemandedBits *DB;
1931 
1932   /// Assumption cache.
1933   AssumptionCache *AC;
1934 
1935   /// Interface to emit optimization remarks.
1936   OptimizationRemarkEmitter *ORE;
1937 
1938   const Function *TheFunction;
1939 
1940   /// Loop Vectorize Hint.
1941   const LoopVectorizeHints *Hints;
1942 
1943   /// The interleave access information contains groups of interleaved accesses
1944   /// with the same stride and close to each other.
1945   InterleavedAccessInfo &InterleaveInfo;
1946 
1947   /// Values to ignore in the cost model.
1948   SmallPtrSet<const Value *, 16> ValuesToIgnore;
1949 
1950   /// Values to ignore in the cost model when VF > 1.
1951   SmallPtrSet<const Value *, 16> VecValuesToIgnore;
1952 
1953   /// All element types found in the loop.
1954   SmallPtrSet<Type *, 16> ElementTypesInLoop;
1955 
1956   /// Profitable vector factors.
1957   SmallVector<VectorizationFactor, 8> ProfitableVFs;
1958 };
1959 } // end namespace llvm
1960 
1961 /// Helper struct to manage generating runtime checks for vectorization.
1962 ///
1963 /// The runtime checks are created up-front in temporary blocks to allow better
1964 /// estimating the cost and un-linked from the existing IR. After deciding to
1965 /// vectorize, the checks are moved back. If deciding not to vectorize, the
1966 /// temporary blocks are completely removed.
1967 class GeneratedRTChecks {
1968   /// Basic block which contains the generated SCEV checks, if any.
1969   BasicBlock *SCEVCheckBlock = nullptr;
1970 
1971   /// The value representing the result of the generated SCEV checks. If it is
1972   /// nullptr, either no SCEV checks have been generated or they have been used.
1973   Value *SCEVCheckCond = nullptr;
1974 
1975   /// Basic block which contains the generated memory runtime checks, if any.
1976   BasicBlock *MemCheckBlock = nullptr;
1977 
1978   /// The value representing the result of the generated memory runtime checks.
1979   /// If it is nullptr, either no memory runtime checks have been generated or
1980   /// they have been used.
1981   Value *MemRuntimeCheckCond = nullptr;
1982 
1983   DominatorTree *DT;
1984   LoopInfo *LI;
1985 
1986   SCEVExpander SCEVExp;
1987   SCEVExpander MemCheckExp;
1988 
1989 public:
1990   GeneratedRTChecks(ScalarEvolution &SE, DominatorTree *DT, LoopInfo *LI,
1991                     const DataLayout &DL)
1992       : DT(DT), LI(LI), SCEVExp(SE, DL, "scev.check"),
1993         MemCheckExp(SE, DL, "scev.check") {}
1994 
1995   /// Generate runtime checks in SCEVCheckBlock and MemCheckBlock, so we can
1996   /// accurately estimate the cost of the runtime checks. The blocks are
1997   /// un-linked from the IR and is added back during vector code generation. If
1998   /// there is no vector code generation, the check blocks are removed
1999   /// completely.
2000   void Create(Loop *L, const LoopAccessInfo &LAI,
2001               const SCEVUnionPredicate &UnionPred) {
2002 
2003     BasicBlock *LoopHeader = L->getHeader();
2004     BasicBlock *Preheader = L->getLoopPreheader();
2005 
2006     // Use SplitBlock to create blocks for SCEV & memory runtime checks to
2007     // ensure the blocks are properly added to LoopInfo & DominatorTree. Those
2008     // may be used by SCEVExpander. The blocks will be un-linked from their
2009     // predecessors and removed from LI & DT at the end of the function.
2010     if (!UnionPred.isAlwaysTrue()) {
2011       SCEVCheckBlock = SplitBlock(Preheader, Preheader->getTerminator(), DT, LI,
2012                                   nullptr, "vector.scevcheck");
2013 
2014       SCEVCheckCond = SCEVExp.expandCodeForPredicate(
2015           &UnionPred, SCEVCheckBlock->getTerminator());
2016     }
2017 
2018     const auto &RtPtrChecking = *LAI.getRuntimePointerChecking();
2019     if (RtPtrChecking.Need) {
2020       auto *Pred = SCEVCheckBlock ? SCEVCheckBlock : Preheader;
2021       MemCheckBlock = SplitBlock(Pred, Pred->getTerminator(), DT, LI, nullptr,
2022                                  "vector.memcheck");
2023 
2024       MemRuntimeCheckCond =
2025           addRuntimeChecks(MemCheckBlock->getTerminator(), L,
2026                            RtPtrChecking.getChecks(), MemCheckExp);
2027       assert(MemRuntimeCheckCond &&
2028              "no RT checks generated although RtPtrChecking "
2029              "claimed checks are required");
2030     }
2031 
2032     if (!MemCheckBlock && !SCEVCheckBlock)
2033       return;
2034 
2035     // Unhook the temporary block with the checks, update various places
2036     // accordingly.
2037     if (SCEVCheckBlock)
2038       SCEVCheckBlock->replaceAllUsesWith(Preheader);
2039     if (MemCheckBlock)
2040       MemCheckBlock->replaceAllUsesWith(Preheader);
2041 
2042     if (SCEVCheckBlock) {
2043       SCEVCheckBlock->getTerminator()->moveBefore(Preheader->getTerminator());
2044       new UnreachableInst(Preheader->getContext(), SCEVCheckBlock);
2045       Preheader->getTerminator()->eraseFromParent();
2046     }
2047     if (MemCheckBlock) {
2048       MemCheckBlock->getTerminator()->moveBefore(Preheader->getTerminator());
2049       new UnreachableInst(Preheader->getContext(), MemCheckBlock);
2050       Preheader->getTerminator()->eraseFromParent();
2051     }
2052 
2053     DT->changeImmediateDominator(LoopHeader, Preheader);
2054     if (MemCheckBlock) {
2055       DT->eraseNode(MemCheckBlock);
2056       LI->removeBlock(MemCheckBlock);
2057     }
2058     if (SCEVCheckBlock) {
2059       DT->eraseNode(SCEVCheckBlock);
2060       LI->removeBlock(SCEVCheckBlock);
2061     }
2062   }
2063 
2064   /// Remove the created SCEV & memory runtime check blocks & instructions, if
2065   /// unused.
2066   ~GeneratedRTChecks() {
2067     SCEVExpanderCleaner SCEVCleaner(SCEVExp, *DT);
2068     SCEVExpanderCleaner MemCheckCleaner(MemCheckExp, *DT);
2069     if (!SCEVCheckCond)
2070       SCEVCleaner.markResultUsed();
2071 
2072     if (!MemRuntimeCheckCond)
2073       MemCheckCleaner.markResultUsed();
2074 
2075     if (MemRuntimeCheckCond) {
2076       auto &SE = *MemCheckExp.getSE();
2077       // Memory runtime check generation creates compares that use expanded
2078       // values. Remove them before running the SCEVExpanderCleaners.
2079       for (auto &I : make_early_inc_range(reverse(*MemCheckBlock))) {
2080         if (MemCheckExp.isInsertedInstruction(&I))
2081           continue;
2082         SE.forgetValue(&I);
2083         I.eraseFromParent();
2084       }
2085     }
2086     MemCheckCleaner.cleanup();
2087     SCEVCleaner.cleanup();
2088 
2089     if (SCEVCheckCond)
2090       SCEVCheckBlock->eraseFromParent();
2091     if (MemRuntimeCheckCond)
2092       MemCheckBlock->eraseFromParent();
2093   }
2094 
2095   /// Adds the generated SCEVCheckBlock before \p LoopVectorPreHeader and
2096   /// adjusts the branches to branch to the vector preheader or \p Bypass,
2097   /// depending on the generated condition.
2098   BasicBlock *emitSCEVChecks(Loop *L, BasicBlock *Bypass,
2099                              BasicBlock *LoopVectorPreHeader,
2100                              BasicBlock *LoopExitBlock) {
2101     if (!SCEVCheckCond)
2102       return nullptr;
2103     if (auto *C = dyn_cast<ConstantInt>(SCEVCheckCond))
2104       if (C->isZero())
2105         return nullptr;
2106 
2107     auto *Pred = LoopVectorPreHeader->getSinglePredecessor();
2108 
2109     BranchInst::Create(LoopVectorPreHeader, SCEVCheckBlock);
2110     // Create new preheader for vector loop.
2111     if (auto *PL = LI->getLoopFor(LoopVectorPreHeader))
2112       PL->addBasicBlockToLoop(SCEVCheckBlock, *LI);
2113 
2114     SCEVCheckBlock->getTerminator()->eraseFromParent();
2115     SCEVCheckBlock->moveBefore(LoopVectorPreHeader);
2116     Pred->getTerminator()->replaceSuccessorWith(LoopVectorPreHeader,
2117                                                 SCEVCheckBlock);
2118 
2119     DT->addNewBlock(SCEVCheckBlock, Pred);
2120     DT->changeImmediateDominator(LoopVectorPreHeader, SCEVCheckBlock);
2121 
2122     ReplaceInstWithInst(
2123         SCEVCheckBlock->getTerminator(),
2124         BranchInst::Create(Bypass, LoopVectorPreHeader, SCEVCheckCond));
2125     // Mark the check as used, to prevent it from being removed during cleanup.
2126     SCEVCheckCond = nullptr;
2127     return SCEVCheckBlock;
2128   }
2129 
2130   /// Adds the generated MemCheckBlock before \p LoopVectorPreHeader and adjusts
2131   /// the branches to branch to the vector preheader or \p Bypass, depending on
2132   /// the generated condition.
2133   BasicBlock *emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass,
2134                                    BasicBlock *LoopVectorPreHeader) {
2135     // Check if we generated code that checks in runtime if arrays overlap.
2136     if (!MemRuntimeCheckCond)
2137       return nullptr;
2138 
2139     auto *Pred = LoopVectorPreHeader->getSinglePredecessor();
2140     Pred->getTerminator()->replaceSuccessorWith(LoopVectorPreHeader,
2141                                                 MemCheckBlock);
2142 
2143     DT->addNewBlock(MemCheckBlock, Pred);
2144     DT->changeImmediateDominator(LoopVectorPreHeader, MemCheckBlock);
2145     MemCheckBlock->moveBefore(LoopVectorPreHeader);
2146 
2147     if (auto *PL = LI->getLoopFor(LoopVectorPreHeader))
2148       PL->addBasicBlockToLoop(MemCheckBlock, *LI);
2149 
2150     ReplaceInstWithInst(
2151         MemCheckBlock->getTerminator(),
2152         BranchInst::Create(Bypass, LoopVectorPreHeader, MemRuntimeCheckCond));
2153     MemCheckBlock->getTerminator()->setDebugLoc(
2154         Pred->getTerminator()->getDebugLoc());
2155 
2156     // Mark the check as used, to prevent it from being removed during cleanup.
2157     MemRuntimeCheckCond = nullptr;
2158     return MemCheckBlock;
2159   }
2160 };
2161 
2162 // Return true if \p OuterLp is an outer loop annotated with hints for explicit
2163 // vectorization. The loop needs to be annotated with #pragma omp simd
2164 // simdlen(#) or #pragma clang vectorize(enable) vectorize_width(#). If the
2165 // vector length information is not provided, vectorization is not considered
2166 // explicit. Interleave hints are not allowed either. These limitations will be
2167 // relaxed in the future.
2168 // Please, note that we are currently forced to abuse the pragma 'clang
2169 // vectorize' semantics. This pragma provides *auto-vectorization hints*
2170 // (i.e., LV must check that vectorization is legal) whereas pragma 'omp simd'
2171 // provides *explicit vectorization hints* (LV can bypass legal checks and
2172 // assume that vectorization is legal). However, both hints are implemented
2173 // using the same metadata (llvm.loop.vectorize, processed by
2174 // LoopVectorizeHints). This will be fixed in the future when the native IR
2175 // representation for pragma 'omp simd' is introduced.
2176 static bool isExplicitVecOuterLoop(Loop *OuterLp,
2177                                    OptimizationRemarkEmitter *ORE) {
2178   assert(!OuterLp->isInnermost() && "This is not an outer loop");
2179   LoopVectorizeHints Hints(OuterLp, true /*DisableInterleaving*/, *ORE);
2180 
2181   // Only outer loops with an explicit vectorization hint are supported.
2182   // Unannotated outer loops are ignored.
2183   if (Hints.getForce() == LoopVectorizeHints::FK_Undefined)
2184     return false;
2185 
2186   Function *Fn = OuterLp->getHeader()->getParent();
2187   if (!Hints.allowVectorization(Fn, OuterLp,
2188                                 true /*VectorizeOnlyWhenForced*/)) {
2189     LLVM_DEBUG(dbgs() << "LV: Loop hints prevent outer loop vectorization.\n");
2190     return false;
2191   }
2192 
2193   if (Hints.getInterleave() > 1) {
2194     // TODO: Interleave support is future work.
2195     LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Interleave is not supported for "
2196                          "outer loops.\n");
2197     Hints.emitRemarkWithHints();
2198     return false;
2199   }
2200 
2201   return true;
2202 }
2203 
2204 static void collectSupportedLoops(Loop &L, LoopInfo *LI,
2205                                   OptimizationRemarkEmitter *ORE,
2206                                   SmallVectorImpl<Loop *> &V) {
2207   // Collect inner loops and outer loops without irreducible control flow. For
2208   // now, only collect outer loops that have explicit vectorization hints. If we
2209   // are stress testing the VPlan H-CFG construction, we collect the outermost
2210   // loop of every loop nest.
2211   if (L.isInnermost() || VPlanBuildStressTest ||
2212       (EnableVPlanNativePath && isExplicitVecOuterLoop(&L, ORE))) {
2213     LoopBlocksRPO RPOT(&L);
2214     RPOT.perform(LI);
2215     if (!containsIrreducibleCFG<const BasicBlock *>(RPOT, *LI)) {
2216       V.push_back(&L);
2217       // TODO: Collect inner loops inside marked outer loops in case
2218       // vectorization fails for the outer loop. Do not invoke
2219       // 'containsIrreducibleCFG' again for inner loops when the outer loop is
2220       // already known to be reducible. We can use an inherited attribute for
2221       // that.
2222       return;
2223     }
2224   }
2225   for (Loop *InnerL : L)
2226     collectSupportedLoops(*InnerL, LI, ORE, V);
2227 }
2228 
2229 namespace {
2230 
2231 /// The LoopVectorize Pass.
2232 struct LoopVectorize : public FunctionPass {
2233   /// Pass identification, replacement for typeid
2234   static char ID;
2235 
2236   LoopVectorizePass Impl;
2237 
2238   explicit LoopVectorize(bool InterleaveOnlyWhenForced = false,
2239                          bool VectorizeOnlyWhenForced = false)
2240       : FunctionPass(ID),
2241         Impl({InterleaveOnlyWhenForced, VectorizeOnlyWhenForced}) {
2242     initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
2243   }
2244 
2245   bool runOnFunction(Function &F) override {
2246     if (skipFunction(F))
2247       return false;
2248 
2249     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
2250     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2251     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
2252     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2253     auto *BFI = &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI();
2254     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
2255     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
2256     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
2257     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
2258     auto *LAA = &getAnalysis<LoopAccessLegacyAnalysis>();
2259     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
2260     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
2261     auto *PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
2262 
2263     std::function<const LoopAccessInfo &(Loop &)> GetLAA =
2264         [&](Loop &L) -> const LoopAccessInfo & { return LAA->getInfo(&L); };
2265 
2266     return Impl.runImpl(F, *SE, *LI, *TTI, *DT, *BFI, TLI, *DB, *AA, *AC,
2267                         GetLAA, *ORE, PSI).MadeAnyChange;
2268   }
2269 
2270   void getAnalysisUsage(AnalysisUsage &AU) const override {
2271     AU.addRequired<AssumptionCacheTracker>();
2272     AU.addRequired<BlockFrequencyInfoWrapperPass>();
2273     AU.addRequired<DominatorTreeWrapperPass>();
2274     AU.addRequired<LoopInfoWrapperPass>();
2275     AU.addRequired<ScalarEvolutionWrapperPass>();
2276     AU.addRequired<TargetTransformInfoWrapperPass>();
2277     AU.addRequired<AAResultsWrapperPass>();
2278     AU.addRequired<LoopAccessLegacyAnalysis>();
2279     AU.addRequired<DemandedBitsWrapperPass>();
2280     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
2281     AU.addRequired<InjectTLIMappingsLegacy>();
2282 
2283     // We currently do not preserve loopinfo/dominator analyses with outer loop
2284     // vectorization. Until this is addressed, mark these analyses as preserved
2285     // only for non-VPlan-native path.
2286     // TODO: Preserve Loop and Dominator analyses for VPlan-native path.
2287     if (!EnableVPlanNativePath) {
2288       AU.addPreserved<LoopInfoWrapperPass>();
2289       AU.addPreserved<DominatorTreeWrapperPass>();
2290     }
2291 
2292     AU.addPreserved<BasicAAWrapperPass>();
2293     AU.addPreserved<GlobalsAAWrapperPass>();
2294     AU.addRequired<ProfileSummaryInfoWrapperPass>();
2295   }
2296 };
2297 
2298 } // end anonymous namespace
2299 
2300 //===----------------------------------------------------------------------===//
2301 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
2302 // LoopVectorizationCostModel and LoopVectorizationPlanner.
2303 //===----------------------------------------------------------------------===//
2304 
2305 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
2306   // We need to place the broadcast of invariant variables outside the loop,
2307   // but only if it's proven safe to do so. Else, broadcast will be inside
2308   // vector loop body.
2309   Instruction *Instr = dyn_cast<Instruction>(V);
2310   bool SafeToHoist = OrigLoop->isLoopInvariant(V) &&
2311                      (!Instr ||
2312                       DT->dominates(Instr->getParent(), LoopVectorPreHeader));
2313   // Place the code for broadcasting invariant variables in the new preheader.
2314   IRBuilder<>::InsertPointGuard Guard(Builder);
2315   if (SafeToHoist)
2316     Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
2317 
2318   // Broadcast the scalar into all locations in the vector.
2319   Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
2320 
2321   return Shuf;
2322 }
2323 
2324 /// This function adds
2325 /// (StartIdx * Step, (StartIdx + 1) * Step, (StartIdx + 2) * Step, ...)
2326 /// to each vector element of Val. The sequence starts at StartIndex.
2327 /// \p Opcode is relevant for FP induction variable.
2328 static Value *getStepVector(Value *Val, Value *StartIdx, Value *Step,
2329                             Instruction::BinaryOps BinOp, ElementCount VF,
2330                             IRBuilder<> &Builder) {
2331   if (VF.isScalar()) {
2332     // When unrolling and the VF is 1, we only need to add a simple scalar.
2333     Type *Ty = Val->getType();
2334     assert(!Ty->isVectorTy() && "Val must be a scalar");
2335 
2336     if (Ty->isFloatingPointTy()) {
2337       // Floating-point operations inherit FMF via the builder's flags.
2338       Value *MulOp = Builder.CreateFMul(StartIdx, Step);
2339       return Builder.CreateBinOp(BinOp, Val, MulOp);
2340     }
2341     return Builder.CreateAdd(Val, Builder.CreateMul(StartIdx, Step),
2342                              "induction");
2343   }
2344 
2345   // Create and check the types.
2346   auto *ValVTy = cast<VectorType>(Val->getType());
2347   ElementCount VLen = ValVTy->getElementCount();
2348 
2349   Type *STy = Val->getType()->getScalarType();
2350   assert((STy->isIntegerTy() || STy->isFloatingPointTy()) &&
2351          "Induction Step must be an integer or FP");
2352   assert(Step->getType() == STy && "Step has wrong type");
2353 
2354   SmallVector<Constant *, 8> Indices;
2355 
2356   // Create a vector of consecutive numbers from zero to VF.
2357   VectorType *InitVecValVTy = ValVTy;
2358   Type *InitVecValSTy = STy;
2359   if (STy->isFloatingPointTy()) {
2360     InitVecValSTy =
2361         IntegerType::get(STy->getContext(), STy->getScalarSizeInBits());
2362     InitVecValVTy = VectorType::get(InitVecValSTy, VLen);
2363   }
2364   Value *InitVec = Builder.CreateStepVector(InitVecValVTy);
2365 
2366   // Splat the StartIdx
2367   Value *StartIdxSplat = Builder.CreateVectorSplat(VLen, StartIdx);
2368 
2369   if (STy->isIntegerTy()) {
2370     InitVec = Builder.CreateAdd(InitVec, StartIdxSplat);
2371     Step = Builder.CreateVectorSplat(VLen, Step);
2372     assert(Step->getType() == Val->getType() && "Invalid step vec");
2373     // FIXME: The newly created binary instructions should contain nsw/nuw
2374     // flags, which can be found from the original scalar operations.
2375     Step = Builder.CreateMul(InitVec, Step);
2376     return Builder.CreateAdd(Val, Step, "induction");
2377   }
2378 
2379   // Floating point induction.
2380   assert((BinOp == Instruction::FAdd || BinOp == Instruction::FSub) &&
2381          "Binary Opcode should be specified for FP induction");
2382   InitVec = Builder.CreateUIToFP(InitVec, ValVTy);
2383   InitVec = Builder.CreateFAdd(InitVec, StartIdxSplat);
2384 
2385   Step = Builder.CreateVectorSplat(VLen, Step);
2386   Value *MulOp = Builder.CreateFMul(InitVec, Step);
2387   return Builder.CreateBinOp(BinOp, Val, MulOp, "induction");
2388 }
2389 
2390 void InnerLoopVectorizer::createVectorIntOrFpInductionPHI(
2391     const InductionDescriptor &II, Value *Step, Value *Start,
2392     Instruction *EntryVal, VPValue *Def, VPTransformState &State) {
2393   IRBuilder<> &Builder = State.Builder;
2394   assert((isa<PHINode>(EntryVal) || isa<TruncInst>(EntryVal)) &&
2395          "Expected either an induction phi-node or a truncate of it!");
2396 
2397   // Construct the initial value of the vector IV in the vector loop preheader
2398   auto CurrIP = Builder.saveIP();
2399   Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
2400   if (isa<TruncInst>(EntryVal)) {
2401     assert(Start->getType()->isIntegerTy() &&
2402            "Truncation requires an integer type");
2403     auto *TruncType = cast<IntegerType>(EntryVal->getType());
2404     Step = Builder.CreateTrunc(Step, TruncType);
2405     Start = Builder.CreateCast(Instruction::Trunc, Start, TruncType);
2406   }
2407 
2408   Value *Zero = getSignedIntOrFpConstant(Start->getType(), 0);
2409   Value *SplatStart = Builder.CreateVectorSplat(State.VF, Start);
2410   Value *SteppedStart = getStepVector(
2411       SplatStart, Zero, Step, II.getInductionOpcode(), State.VF, State.Builder);
2412 
2413   // We create vector phi nodes for both integer and floating-point induction
2414   // variables. Here, we determine the kind of arithmetic we will perform.
2415   Instruction::BinaryOps AddOp;
2416   Instruction::BinaryOps MulOp;
2417   if (Step->getType()->isIntegerTy()) {
2418     AddOp = Instruction::Add;
2419     MulOp = Instruction::Mul;
2420   } else {
2421     AddOp = II.getInductionOpcode();
2422     MulOp = Instruction::FMul;
2423   }
2424 
2425   // Multiply the vectorization factor by the step using integer or
2426   // floating-point arithmetic as appropriate.
2427   Type *StepType = Step->getType();
2428   Value *RuntimeVF;
2429   if (Step->getType()->isFloatingPointTy())
2430     RuntimeVF = getRuntimeVFAsFloat(Builder, StepType, State.VF);
2431   else
2432     RuntimeVF = getRuntimeVF(Builder, StepType, State.VF);
2433   Value *Mul = Builder.CreateBinOp(MulOp, Step, RuntimeVF);
2434 
2435   // Create a vector splat to use in the induction update.
2436   //
2437   // FIXME: If the step is non-constant, we create the vector splat with
2438   //        IRBuilder. IRBuilder can constant-fold the multiply, but it doesn't
2439   //        handle a constant vector splat.
2440   Value *SplatVF = isa<Constant>(Mul)
2441                        ? ConstantVector::getSplat(State.VF, cast<Constant>(Mul))
2442                        : Builder.CreateVectorSplat(State.VF, Mul);
2443   Builder.restoreIP(CurrIP);
2444 
2445   // We may need to add the step a number of times, depending on the unroll
2446   // factor. The last of those goes into the PHI.
2447   PHINode *VecInd = PHINode::Create(SteppedStart->getType(), 2, "vec.ind",
2448                                     &*LoopVectorBody->getFirstInsertionPt());
2449   VecInd->setDebugLoc(EntryVal->getDebugLoc());
2450   Instruction *LastInduction = VecInd;
2451   for (unsigned Part = 0; Part < UF; ++Part) {
2452     State.set(Def, LastInduction, Part);
2453 
2454     if (isa<TruncInst>(EntryVal))
2455       addMetadata(LastInduction, EntryVal);
2456 
2457     LastInduction = cast<Instruction>(
2458         Builder.CreateBinOp(AddOp, LastInduction, SplatVF, "step.add"));
2459     LastInduction->setDebugLoc(EntryVal->getDebugLoc());
2460   }
2461 
2462   // Move the last step to the end of the latch block. This ensures consistent
2463   // placement of all induction updates.
2464   auto *LoopVectorLatch = LI->getLoopFor(LoopVectorBody)->getLoopLatch();
2465   auto *Br = cast<BranchInst>(LoopVectorLatch->getTerminator());
2466   auto *ICmp = cast<Instruction>(Br->getCondition());
2467   LastInduction->moveBefore(ICmp);
2468   LastInduction->setName("vec.ind.next");
2469 
2470   VecInd->addIncoming(SteppedStart, LoopVectorPreHeader);
2471   VecInd->addIncoming(LastInduction, LoopVectorLatch);
2472 }
2473 
2474 bool InnerLoopVectorizer::shouldScalarizeInstruction(Instruction *I) const {
2475   return Cost->isScalarAfterVectorization(I, VF) ||
2476          Cost->isProfitableToScalarize(I, VF);
2477 }
2478 
2479 bool InnerLoopVectorizer::needsScalarInduction(Instruction *IV) const {
2480   if (shouldScalarizeInstruction(IV))
2481     return true;
2482   auto isScalarInst = [&](User *U) -> bool {
2483     auto *I = cast<Instruction>(U);
2484     return (OrigLoop->contains(I) && shouldScalarizeInstruction(I));
2485   };
2486   return llvm::any_of(IV->users(), isScalarInst);
2487 }
2488 
2489 void InnerLoopVectorizer::widenIntOrFpInduction(PHINode *IV,
2490                                                 const InductionDescriptor &ID,
2491                                                 Value *Start, TruncInst *Trunc,
2492                                                 VPValue *Def,
2493                                                 VPTransformState &State) {
2494   IRBuilder<> &Builder = State.Builder;
2495   assert((IV->getType()->isIntegerTy() || IV != OldInduction) &&
2496          "Primary induction variable must have an integer type");
2497   assert(IV->getType() == ID.getStartValue()->getType() && "Types must match");
2498   assert(!State.VF.isZero() && "VF must be non-zero");
2499 
2500   // The value from the original loop to which we are mapping the new induction
2501   // variable.
2502   Instruction *EntryVal = Trunc ? cast<Instruction>(Trunc) : IV;
2503 
2504   auto &DL = EntryVal->getModule()->getDataLayout();
2505 
2506   // Generate code for the induction step. Note that induction steps are
2507   // required to be loop-invariant
2508   auto CreateStepValue = [&](const SCEV *Step) -> Value * {
2509     assert(PSE.getSE()->isLoopInvariant(Step, OrigLoop) &&
2510            "Induction step should be loop invariant");
2511     if (PSE.getSE()->isSCEVable(IV->getType())) {
2512       SCEVExpander Exp(*PSE.getSE(), DL, "induction");
2513       return Exp.expandCodeFor(Step, Step->getType(),
2514                                State.CFG.VectorPreHeader->getTerminator());
2515     }
2516     return cast<SCEVUnknown>(Step)->getValue();
2517   };
2518 
2519   // The scalar value to broadcast. This is derived from the canonical
2520   // induction variable. If a truncation type is given, truncate the canonical
2521   // induction variable and step. Otherwise, derive these values from the
2522   // induction descriptor.
2523   auto CreateScalarIV = [&](Value *&Step) -> Value * {
2524     Value *ScalarIV = Induction;
2525     if (IV != OldInduction) {
2526       ScalarIV = IV->getType()->isIntegerTy()
2527                      ? Builder.CreateSExtOrTrunc(Induction, IV->getType())
2528                      : Builder.CreateCast(Instruction::SIToFP, Induction,
2529                                           IV->getType());
2530       ScalarIV = emitTransformedIndex(Builder, ScalarIV, PSE.getSE(), DL, ID,
2531                                       State.CFG.PrevBB);
2532       ScalarIV->setName("offset.idx");
2533     }
2534     if (Trunc) {
2535       auto *TruncType = cast<IntegerType>(Trunc->getType());
2536       assert(Step->getType()->isIntegerTy() &&
2537              "Truncation requires an integer step");
2538       ScalarIV = Builder.CreateTrunc(ScalarIV, TruncType);
2539       Step = Builder.CreateTrunc(Step, TruncType);
2540     }
2541     return ScalarIV;
2542   };
2543 
2544   // Create the vector values from the scalar IV, in the absence of creating a
2545   // vector IV.
2546   auto CreateSplatIV = [&](Value *ScalarIV, Value *Step) {
2547     Value *Broadcasted = getBroadcastInstrs(ScalarIV);
2548     for (unsigned Part = 0; Part < UF; ++Part) {
2549       assert(!State.VF.isScalable() && "scalable vectors not yet supported.");
2550       Value *StartIdx;
2551       if (Step->getType()->isFloatingPointTy())
2552         StartIdx =
2553             getRuntimeVFAsFloat(Builder, Step->getType(), State.VF * Part);
2554       else
2555         StartIdx = getRuntimeVF(Builder, Step->getType(), State.VF * Part);
2556 
2557       Value *EntryPart =
2558           getStepVector(Broadcasted, StartIdx, Step, ID.getInductionOpcode(),
2559                         State.VF, State.Builder);
2560       State.set(Def, EntryPart, Part);
2561       if (Trunc)
2562         addMetadata(EntryPart, Trunc);
2563     }
2564   };
2565 
2566   // Fast-math-flags propagate from the original induction instruction.
2567   IRBuilder<>::FastMathFlagGuard FMFG(Builder);
2568   if (ID.getInductionBinOp() && isa<FPMathOperator>(ID.getInductionBinOp()))
2569     Builder.setFastMathFlags(ID.getInductionBinOp()->getFastMathFlags());
2570 
2571   // Now do the actual transformations, and start with creating the step value.
2572   Value *Step = CreateStepValue(ID.getStep());
2573   if (State.VF.isScalar()) {
2574     Value *ScalarIV = CreateScalarIV(Step);
2575     CreateSplatIV(ScalarIV, Step);
2576     return;
2577   }
2578 
2579   // Determine if we want a scalar version of the induction variable. This is
2580   // true if the induction variable itself is not widened, or if it has at
2581   // least one user in the loop that is not widened.
2582   auto NeedsScalarIV = needsScalarInduction(EntryVal);
2583   if (!NeedsScalarIV) {
2584     createVectorIntOrFpInductionPHI(ID, Step, Start, EntryVal, Def, State);
2585     return;
2586   }
2587 
2588   // Try to create a new independent vector induction variable. If we can't
2589   // create the phi node, we will splat the scalar induction variable in each
2590   // loop iteration.
2591   if (!shouldScalarizeInstruction(EntryVal)) {
2592     createVectorIntOrFpInductionPHI(ID, Step, Start, EntryVal, Def, State);
2593     Value *ScalarIV = CreateScalarIV(Step);
2594     // Create scalar steps that can be used by instructions we will later
2595     // scalarize. Note that the addition of the scalar steps will not increase
2596     // the number of instructions in the loop in the common case prior to
2597     // InstCombine. We will be trading one vector extract for each scalar step.
2598     buildScalarSteps(ScalarIV, Step, EntryVal, ID, Def, State);
2599     return;
2600   }
2601 
2602   // All IV users are scalar instructions, so only emit a scalar IV, not a
2603   // vectorised IV. Except when we tail-fold, then the splat IV feeds the
2604   // predicate used by the masked loads/stores.
2605   Value *ScalarIV = CreateScalarIV(Step);
2606   if (!Cost->isScalarEpilogueAllowed())
2607     CreateSplatIV(ScalarIV, Step);
2608   buildScalarSteps(ScalarIV, Step, EntryVal, ID, Def, State);
2609 }
2610 
2611 void InnerLoopVectorizer::buildScalarSteps(Value *ScalarIV, Value *Step,
2612                                            Instruction *EntryVal,
2613                                            const InductionDescriptor &ID,
2614                                            VPValue *Def,
2615                                            VPTransformState &State) {
2616   IRBuilder<> &Builder = State.Builder;
2617   // We shouldn't have to build scalar steps if we aren't vectorizing.
2618   assert(State.VF.isVector() && "VF should be greater than one");
2619   // Get the value type and ensure it and the step have the same integer type.
2620   Type *ScalarIVTy = ScalarIV->getType()->getScalarType();
2621   assert(ScalarIVTy == Step->getType() &&
2622          "Val and Step should have the same type");
2623 
2624   // We build scalar steps for both integer and floating-point induction
2625   // variables. Here, we determine the kind of arithmetic we will perform.
2626   Instruction::BinaryOps AddOp;
2627   Instruction::BinaryOps MulOp;
2628   if (ScalarIVTy->isIntegerTy()) {
2629     AddOp = Instruction::Add;
2630     MulOp = Instruction::Mul;
2631   } else {
2632     AddOp = ID.getInductionOpcode();
2633     MulOp = Instruction::FMul;
2634   }
2635 
2636   // Determine the number of scalars we need to generate for each unroll
2637   // iteration. If EntryVal is uniform, we only need to generate the first
2638   // lane. Otherwise, we generate all VF values.
2639   bool IsUniform =
2640       Cost->isUniformAfterVectorization(cast<Instruction>(EntryVal), State.VF);
2641   unsigned Lanes = IsUniform ? 1 : State.VF.getKnownMinValue();
2642   // Compute the scalar steps and save the results in State.
2643   Type *IntStepTy = IntegerType::get(ScalarIVTy->getContext(),
2644                                      ScalarIVTy->getScalarSizeInBits());
2645   Type *VecIVTy = nullptr;
2646   Value *UnitStepVec = nullptr, *SplatStep = nullptr, *SplatIV = nullptr;
2647   if (!IsUniform && State.VF.isScalable()) {
2648     VecIVTy = VectorType::get(ScalarIVTy, State.VF);
2649     UnitStepVec =
2650         Builder.CreateStepVector(VectorType::get(IntStepTy, State.VF));
2651     SplatStep = Builder.CreateVectorSplat(State.VF, Step);
2652     SplatIV = Builder.CreateVectorSplat(State.VF, ScalarIV);
2653   }
2654 
2655   for (unsigned Part = 0; Part < State.UF; ++Part) {
2656     Value *StartIdx0 = createStepForVF(Builder, IntStepTy, State.VF, Part);
2657 
2658     if (!IsUniform && State.VF.isScalable()) {
2659       auto *SplatStartIdx = Builder.CreateVectorSplat(State.VF, StartIdx0);
2660       auto *InitVec = Builder.CreateAdd(SplatStartIdx, UnitStepVec);
2661       if (ScalarIVTy->isFloatingPointTy())
2662         InitVec = Builder.CreateSIToFP(InitVec, VecIVTy);
2663       auto *Mul = Builder.CreateBinOp(MulOp, InitVec, SplatStep);
2664       auto *Add = Builder.CreateBinOp(AddOp, SplatIV, Mul);
2665       State.set(Def, Add, Part);
2666       // It's useful to record the lane values too for the known minimum number
2667       // of elements so we do those below. This improves the code quality when
2668       // trying to extract the first element, for example.
2669     }
2670 
2671     if (ScalarIVTy->isFloatingPointTy())
2672       StartIdx0 = Builder.CreateSIToFP(StartIdx0, ScalarIVTy);
2673 
2674     for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
2675       Value *StartIdx = Builder.CreateBinOp(
2676           AddOp, StartIdx0, getSignedIntOrFpConstant(ScalarIVTy, Lane));
2677       // The step returned by `createStepForVF` is a runtime-evaluated value
2678       // when VF is scalable. Otherwise, it should be folded into a Constant.
2679       assert((State.VF.isScalable() || isa<Constant>(StartIdx)) &&
2680              "Expected StartIdx to be folded to a constant when VF is not "
2681              "scalable");
2682       auto *Mul = Builder.CreateBinOp(MulOp, StartIdx, Step);
2683       auto *Add = Builder.CreateBinOp(AddOp, ScalarIV, Mul);
2684       State.set(Def, Add, VPIteration(Part, Lane));
2685     }
2686   }
2687 }
2688 
2689 void InnerLoopVectorizer::packScalarIntoVectorValue(VPValue *Def,
2690                                                     const VPIteration &Instance,
2691                                                     VPTransformState &State) {
2692   Value *ScalarInst = State.get(Def, Instance);
2693   Value *VectorValue = State.get(Def, Instance.Part);
2694   VectorValue = Builder.CreateInsertElement(
2695       VectorValue, ScalarInst,
2696       Instance.Lane.getAsRuntimeExpr(State.Builder, VF));
2697   State.set(Def, VectorValue, Instance.Part);
2698 }
2699 
2700 // Return whether we allow using masked interleave-groups (for dealing with
2701 // strided loads/stores that reside in predicated blocks, or for dealing
2702 // with gaps).
2703 static bool useMaskedInterleavedAccesses(const TargetTransformInfo &TTI) {
2704   // If an override option has been passed in for interleaved accesses, use it.
2705   if (EnableMaskedInterleavedMemAccesses.getNumOccurrences() > 0)
2706     return EnableMaskedInterleavedMemAccesses;
2707 
2708   return TTI.enableMaskedInterleavedAccessVectorization();
2709 }
2710 
2711 // Try to vectorize the interleave group that \p Instr belongs to.
2712 //
2713 // E.g. Translate following interleaved load group (factor = 3):
2714 //   for (i = 0; i < N; i+=3) {
2715 //     R = Pic[i];             // Member of index 0
2716 //     G = Pic[i+1];           // Member of index 1
2717 //     B = Pic[i+2];           // Member of index 2
2718 //     ... // do something to R, G, B
2719 //   }
2720 // To:
2721 //   %wide.vec = load <12 x i32>                       ; Read 4 tuples of R,G,B
2722 //   %R.vec = shuffle %wide.vec, poison, <0, 3, 6, 9>   ; R elements
2723 //   %G.vec = shuffle %wide.vec, poison, <1, 4, 7, 10>  ; G elements
2724 //   %B.vec = shuffle %wide.vec, poison, <2, 5, 8, 11>  ; B elements
2725 //
2726 // Or translate following interleaved store group (factor = 3):
2727 //   for (i = 0; i < N; i+=3) {
2728 //     ... do something to R, G, B
2729 //     Pic[i]   = R;           // Member of index 0
2730 //     Pic[i+1] = G;           // Member of index 1
2731 //     Pic[i+2] = B;           // Member of index 2
2732 //   }
2733 // To:
2734 //   %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
2735 //   %B_U.vec = shuffle %B.vec, poison, <0, 1, 2, 3, u, u, u, u>
2736 //   %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
2737 //        <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>    ; Interleave R,G,B elements
2738 //   store <12 x i32> %interleaved.vec              ; Write 4 tuples of R,G,B
2739 void InnerLoopVectorizer::vectorizeInterleaveGroup(
2740     const InterleaveGroup<Instruction> *Group, ArrayRef<VPValue *> VPDefs,
2741     VPTransformState &State, VPValue *Addr, ArrayRef<VPValue *> StoredValues,
2742     VPValue *BlockInMask) {
2743   Instruction *Instr = Group->getInsertPos();
2744   const DataLayout &DL = Instr->getModule()->getDataLayout();
2745 
2746   // Prepare for the vector type of the interleaved load/store.
2747   Type *ScalarTy = getLoadStoreType(Instr);
2748   unsigned InterleaveFactor = Group->getFactor();
2749   assert(!VF.isScalable() && "scalable vectors not yet supported.");
2750   auto *VecTy = VectorType::get(ScalarTy, VF * InterleaveFactor);
2751 
2752   // Prepare for the new pointers.
2753   SmallVector<Value *, 2> AddrParts;
2754   unsigned Index = Group->getIndex(Instr);
2755 
2756   // TODO: extend the masked interleaved-group support to reversed access.
2757   assert((!BlockInMask || !Group->isReverse()) &&
2758          "Reversed masked interleave-group not supported.");
2759 
2760   // If the group is reverse, adjust the index to refer to the last vector lane
2761   // instead of the first. We adjust the index from the first vector lane,
2762   // rather than directly getting the pointer for lane VF - 1, because the
2763   // pointer operand of the interleaved access is supposed to be uniform. For
2764   // uniform instructions, we're only required to generate a value for the
2765   // first vector lane in each unroll iteration.
2766   if (Group->isReverse())
2767     Index += (VF.getKnownMinValue() - 1) * Group->getFactor();
2768 
2769   for (unsigned Part = 0; Part < UF; Part++) {
2770     Value *AddrPart = State.get(Addr, VPIteration(Part, 0));
2771     setDebugLocFromInst(AddrPart);
2772 
2773     // Notice current instruction could be any index. Need to adjust the address
2774     // to the member of index 0.
2775     //
2776     // E.g.  a = A[i+1];     // Member of index 1 (Current instruction)
2777     //       b = A[i];       // Member of index 0
2778     // Current pointer is pointed to A[i+1], adjust it to A[i].
2779     //
2780     // E.g.  A[i+1] = a;     // Member of index 1
2781     //       A[i]   = b;     // Member of index 0
2782     //       A[i+2] = c;     // Member of index 2 (Current instruction)
2783     // Current pointer is pointed to A[i+2], adjust it to A[i].
2784 
2785     bool InBounds = false;
2786     if (auto *gep = dyn_cast<GetElementPtrInst>(AddrPart->stripPointerCasts()))
2787       InBounds = gep->isInBounds();
2788     AddrPart = Builder.CreateGEP(ScalarTy, AddrPart, Builder.getInt32(-Index));
2789     cast<GetElementPtrInst>(AddrPart)->setIsInBounds(InBounds);
2790 
2791     // Cast to the vector pointer type.
2792     unsigned AddressSpace = AddrPart->getType()->getPointerAddressSpace();
2793     Type *PtrTy = VecTy->getPointerTo(AddressSpace);
2794     AddrParts.push_back(Builder.CreateBitCast(AddrPart, PtrTy));
2795   }
2796 
2797   setDebugLocFromInst(Instr);
2798   Value *PoisonVec = PoisonValue::get(VecTy);
2799 
2800   Value *MaskForGaps = nullptr;
2801   if (Group->requiresScalarEpilogue() && !Cost->isScalarEpilogueAllowed()) {
2802     MaskForGaps = createBitMaskForGaps(Builder, VF.getKnownMinValue(), *Group);
2803     assert(MaskForGaps && "Mask for Gaps is required but it is null");
2804   }
2805 
2806   // Vectorize the interleaved load group.
2807   if (isa<LoadInst>(Instr)) {
2808     // For each unroll part, create a wide load for the group.
2809     SmallVector<Value *, 2> NewLoads;
2810     for (unsigned Part = 0; Part < UF; Part++) {
2811       Instruction *NewLoad;
2812       if (BlockInMask || MaskForGaps) {
2813         assert(useMaskedInterleavedAccesses(*TTI) &&
2814                "masked interleaved groups are not allowed.");
2815         Value *GroupMask = MaskForGaps;
2816         if (BlockInMask) {
2817           Value *BlockInMaskPart = State.get(BlockInMask, Part);
2818           Value *ShuffledMask = Builder.CreateShuffleVector(
2819               BlockInMaskPart,
2820               createReplicatedMask(InterleaveFactor, VF.getKnownMinValue()),
2821               "interleaved.mask");
2822           GroupMask = MaskForGaps
2823                           ? Builder.CreateBinOp(Instruction::And, ShuffledMask,
2824                                                 MaskForGaps)
2825                           : ShuffledMask;
2826         }
2827         NewLoad =
2828             Builder.CreateMaskedLoad(VecTy, AddrParts[Part], Group->getAlign(),
2829                                      GroupMask, PoisonVec, "wide.masked.vec");
2830       }
2831       else
2832         NewLoad = Builder.CreateAlignedLoad(VecTy, AddrParts[Part],
2833                                             Group->getAlign(), "wide.vec");
2834       Group->addMetadata(NewLoad);
2835       NewLoads.push_back(NewLoad);
2836     }
2837 
2838     // For each member in the group, shuffle out the appropriate data from the
2839     // wide loads.
2840     unsigned J = 0;
2841     for (unsigned I = 0; I < InterleaveFactor; ++I) {
2842       Instruction *Member = Group->getMember(I);
2843 
2844       // Skip the gaps in the group.
2845       if (!Member)
2846         continue;
2847 
2848       auto StrideMask =
2849           createStrideMask(I, InterleaveFactor, VF.getKnownMinValue());
2850       for (unsigned Part = 0; Part < UF; Part++) {
2851         Value *StridedVec = Builder.CreateShuffleVector(
2852             NewLoads[Part], StrideMask, "strided.vec");
2853 
2854         // If this member has different type, cast the result type.
2855         if (Member->getType() != ScalarTy) {
2856           assert(!VF.isScalable() && "VF is assumed to be non scalable.");
2857           VectorType *OtherVTy = VectorType::get(Member->getType(), VF);
2858           StridedVec = createBitOrPointerCast(StridedVec, OtherVTy, DL);
2859         }
2860 
2861         if (Group->isReverse())
2862           StridedVec = Builder.CreateVectorReverse(StridedVec, "reverse");
2863 
2864         State.set(VPDefs[J], StridedVec, Part);
2865       }
2866       ++J;
2867     }
2868     return;
2869   }
2870 
2871   // The sub vector type for current instruction.
2872   auto *SubVT = VectorType::get(ScalarTy, VF);
2873 
2874   // Vectorize the interleaved store group.
2875   MaskForGaps = createBitMaskForGaps(Builder, VF.getKnownMinValue(), *Group);
2876   assert((!MaskForGaps || useMaskedInterleavedAccesses(*TTI)) &&
2877          "masked interleaved groups are not allowed.");
2878   assert((!MaskForGaps || !VF.isScalable()) &&
2879          "masking gaps for scalable vectors is not yet supported.");
2880   for (unsigned Part = 0; Part < UF; Part++) {
2881     // Collect the stored vector from each member.
2882     SmallVector<Value *, 4> StoredVecs;
2883     for (unsigned i = 0; i < InterleaveFactor; i++) {
2884       assert((Group->getMember(i) || MaskForGaps) &&
2885              "Fail to get a member from an interleaved store group");
2886       Instruction *Member = Group->getMember(i);
2887 
2888       // Skip the gaps in the group.
2889       if (!Member) {
2890         Value *Undef = PoisonValue::get(SubVT);
2891         StoredVecs.push_back(Undef);
2892         continue;
2893       }
2894 
2895       Value *StoredVec = State.get(StoredValues[i], Part);
2896 
2897       if (Group->isReverse())
2898         StoredVec = Builder.CreateVectorReverse(StoredVec, "reverse");
2899 
2900       // If this member has different type, cast it to a unified type.
2901 
2902       if (StoredVec->getType() != SubVT)
2903         StoredVec = createBitOrPointerCast(StoredVec, SubVT, DL);
2904 
2905       StoredVecs.push_back(StoredVec);
2906     }
2907 
2908     // Concatenate all vectors into a wide vector.
2909     Value *WideVec = concatenateVectors(Builder, StoredVecs);
2910 
2911     // Interleave the elements in the wide vector.
2912     Value *IVec = Builder.CreateShuffleVector(
2913         WideVec, createInterleaveMask(VF.getKnownMinValue(), InterleaveFactor),
2914         "interleaved.vec");
2915 
2916     Instruction *NewStoreInstr;
2917     if (BlockInMask || MaskForGaps) {
2918       Value *GroupMask = MaskForGaps;
2919       if (BlockInMask) {
2920         Value *BlockInMaskPart = State.get(BlockInMask, Part);
2921         Value *ShuffledMask = Builder.CreateShuffleVector(
2922             BlockInMaskPart,
2923             createReplicatedMask(InterleaveFactor, VF.getKnownMinValue()),
2924             "interleaved.mask");
2925         GroupMask = MaskForGaps ? Builder.CreateBinOp(Instruction::And,
2926                                                       ShuffledMask, MaskForGaps)
2927                                 : ShuffledMask;
2928       }
2929       NewStoreInstr = Builder.CreateMaskedStore(IVec, AddrParts[Part],
2930                                                 Group->getAlign(), GroupMask);
2931     } else
2932       NewStoreInstr =
2933           Builder.CreateAlignedStore(IVec, AddrParts[Part], Group->getAlign());
2934 
2935     Group->addMetadata(NewStoreInstr);
2936   }
2937 }
2938 
2939 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr,
2940                                                VPReplicateRecipe *RepRecipe,
2941                                                const VPIteration &Instance,
2942                                                bool IfPredicateInstr,
2943                                                VPTransformState &State) {
2944   assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
2945 
2946   // llvm.experimental.noalias.scope.decl intrinsics must only be duplicated for
2947   // the first lane and part.
2948   if (isa<NoAliasScopeDeclInst>(Instr))
2949     if (!Instance.isFirstIteration())
2950       return;
2951 
2952   setDebugLocFromInst(Instr);
2953 
2954   // Does this instruction return a value ?
2955   bool IsVoidRetTy = Instr->getType()->isVoidTy();
2956 
2957   Instruction *Cloned = Instr->clone();
2958   if (!IsVoidRetTy)
2959     Cloned->setName(Instr->getName() + ".cloned");
2960 
2961   // If the scalarized instruction contributes to the address computation of a
2962   // widen masked load/store which was in a basic block that needed predication
2963   // and is not predicated after vectorization, we can't propagate
2964   // poison-generating flags (nuw/nsw, exact, inbounds, etc.). The scalarized
2965   // instruction could feed a poison value to the base address of the widen
2966   // load/store.
2967   if (State.MayGeneratePoisonRecipes.contains(RepRecipe))
2968     Cloned->dropPoisonGeneratingFlags();
2969 
2970   State.Builder.SetInsertPoint(Builder.GetInsertBlock(),
2971                                Builder.GetInsertPoint());
2972   // Replace the operands of the cloned instructions with their scalar
2973   // equivalents in the new loop.
2974   for (auto &I : enumerate(RepRecipe->operands())) {
2975     auto InputInstance = Instance;
2976     VPValue *Operand = I.value();
2977     if (State.Plan->isUniformAfterVectorization(Operand))
2978       InputInstance.Lane = VPLane::getFirstLane();
2979     Cloned->setOperand(I.index(), State.get(Operand, InputInstance));
2980   }
2981   addNewMetadata(Cloned, Instr);
2982 
2983   // Place the cloned scalar in the new loop.
2984   Builder.Insert(Cloned);
2985 
2986   State.set(RepRecipe, Cloned, Instance);
2987 
2988   // If we just cloned a new assumption, add it the assumption cache.
2989   if (auto *II = dyn_cast<AssumeInst>(Cloned))
2990     AC->registerAssumption(II);
2991 
2992   // End if-block.
2993   if (IfPredicateInstr)
2994     PredicatedInstructions.push_back(Cloned);
2995 }
2996 
2997 PHINode *InnerLoopVectorizer::createInductionVariable(Loop *L, Value *Start,
2998                                                       Value *End, Value *Step,
2999                                                       Instruction *DL) {
3000   BasicBlock *Header = L->getHeader();
3001   BasicBlock *Latch = L->getLoopLatch();
3002   // As we're just creating this loop, it's possible no latch exists
3003   // yet. If so, use the header as this will be a single block loop.
3004   if (!Latch)
3005     Latch = Header;
3006 
3007   IRBuilder<> B(&*Header->getFirstInsertionPt());
3008   Instruction *OldInst = getDebugLocFromInstOrOperands(OldInduction);
3009   setDebugLocFromInst(OldInst, &B);
3010   auto *Induction = B.CreatePHI(Start->getType(), 2, "index");
3011 
3012   B.SetInsertPoint(Latch->getTerminator());
3013   setDebugLocFromInst(OldInst, &B);
3014 
3015   // Create i+1 and fill the PHINode.
3016   //
3017   // If the tail is not folded, we know that End - Start >= Step (either
3018   // statically or through the minimum iteration checks). We also know that both
3019   // Start % Step == 0 and End % Step == 0. We exit the vector loop if %IV +
3020   // %Step == %End. Hence we must exit the loop before %IV + %Step unsigned
3021   // overflows and we can mark the induction increment as NUW.
3022   Value *Next = B.CreateAdd(Induction, Step, "index.next",
3023                             /*NUW=*/!Cost->foldTailByMasking(), /*NSW=*/false);
3024   Induction->addIncoming(Start, L->getLoopPreheader());
3025   Induction->addIncoming(Next, Latch);
3026   // Create the compare.
3027   Value *ICmp = B.CreateICmpEQ(Next, End);
3028   B.CreateCondBr(ICmp, L->getUniqueExitBlock(), Header);
3029 
3030   // Now we have two terminators. Remove the old one from the block.
3031   Latch->getTerminator()->eraseFromParent();
3032 
3033   return Induction;
3034 }
3035 
3036 Value *InnerLoopVectorizer::getOrCreateTripCount(Loop *L) {
3037   if (TripCount)
3038     return TripCount;
3039 
3040   assert(L && "Create Trip Count for null loop.");
3041   IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
3042   // Find the loop boundaries.
3043   ScalarEvolution *SE = PSE.getSE();
3044   const SCEV *BackedgeTakenCount = PSE.getBackedgeTakenCount();
3045   assert(!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
3046          "Invalid loop count");
3047 
3048   Type *IdxTy = Legal->getWidestInductionType();
3049   assert(IdxTy && "No type for induction");
3050 
3051   // The exit count might have the type of i64 while the phi is i32. This can
3052   // happen if we have an induction variable that is sign extended before the
3053   // compare. The only way that we get a backedge taken count is that the
3054   // induction variable was signed and as such will not overflow. In such a case
3055   // truncation is legal.
3056   if (SE->getTypeSizeInBits(BackedgeTakenCount->getType()) >
3057       IdxTy->getPrimitiveSizeInBits())
3058     BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount, IdxTy);
3059   BackedgeTakenCount = SE->getNoopOrZeroExtend(BackedgeTakenCount, IdxTy);
3060 
3061   // Get the total trip count from the count by adding 1.
3062   const SCEV *ExitCount = SE->getAddExpr(
3063       BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType()));
3064 
3065   const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
3066 
3067   // Expand the trip count and place the new instructions in the preheader.
3068   // Notice that the pre-header does not change, only the loop body.
3069   SCEVExpander Exp(*SE, DL, "induction");
3070 
3071   // Count holds the overall loop count (N).
3072   TripCount = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
3073                                 L->getLoopPreheader()->getTerminator());
3074 
3075   if (TripCount->getType()->isPointerTy())
3076     TripCount =
3077         CastInst::CreatePointerCast(TripCount, IdxTy, "exitcount.ptrcnt.to.int",
3078                                     L->getLoopPreheader()->getTerminator());
3079 
3080   return TripCount;
3081 }
3082 
3083 Value *InnerLoopVectorizer::getOrCreateVectorTripCount(Loop *L) {
3084   if (VectorTripCount)
3085     return VectorTripCount;
3086 
3087   Value *TC = getOrCreateTripCount(L);
3088   IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
3089 
3090   Type *Ty = TC->getType();
3091   // This is where we can make the step a runtime constant.
3092   Value *Step = createStepForVF(Builder, Ty, VF, UF);
3093 
3094   // If the tail is to be folded by masking, round the number of iterations N
3095   // up to a multiple of Step instead of rounding down. This is done by first
3096   // adding Step-1 and then rounding down. Note that it's ok if this addition
3097   // overflows: the vector induction variable will eventually wrap to zero given
3098   // that it starts at zero and its Step is a power of two; the loop will then
3099   // exit, with the last early-exit vector comparison also producing all-true.
3100   if (Cost->foldTailByMasking()) {
3101     assert(isPowerOf2_32(VF.getKnownMinValue() * UF) &&
3102            "VF*UF must be a power of 2 when folding tail by masking");
3103     assert(!VF.isScalable() &&
3104            "Tail folding not yet supported for scalable vectors");
3105     TC = Builder.CreateAdd(
3106         TC, ConstantInt::get(Ty, VF.getKnownMinValue() * UF - 1), "n.rnd.up");
3107   }
3108 
3109   // Now we need to generate the expression for the part of the loop that the
3110   // vectorized body will execute. This is equal to N - (N % Step) if scalar
3111   // iterations are not required for correctness, or N - Step, otherwise. Step
3112   // is equal to the vectorization factor (number of SIMD elements) times the
3113   // unroll factor (number of SIMD instructions).
3114   Value *R = Builder.CreateURem(TC, Step, "n.mod.vf");
3115 
3116   // There are cases where we *must* run at least one iteration in the remainder
3117   // loop.  See the cost model for when this can happen.  If the step evenly
3118   // divides the trip count, we set the remainder to be equal to the step. If
3119   // the step does not evenly divide the trip count, no adjustment is necessary
3120   // since there will already be scalar iterations. Note that the minimum
3121   // iterations check ensures that N >= Step.
3122   if (Cost->requiresScalarEpilogue(VF)) {
3123     auto *IsZero = Builder.CreateICmpEQ(R, ConstantInt::get(R->getType(), 0));
3124     R = Builder.CreateSelect(IsZero, Step, R);
3125   }
3126 
3127   VectorTripCount = Builder.CreateSub(TC, R, "n.vec");
3128 
3129   return VectorTripCount;
3130 }
3131 
3132 Value *InnerLoopVectorizer::createBitOrPointerCast(Value *V, VectorType *DstVTy,
3133                                                    const DataLayout &DL) {
3134   // Verify that V is a vector type with same number of elements as DstVTy.
3135   auto *DstFVTy = cast<FixedVectorType>(DstVTy);
3136   unsigned VF = DstFVTy->getNumElements();
3137   auto *SrcVecTy = cast<FixedVectorType>(V->getType());
3138   assert((VF == SrcVecTy->getNumElements()) && "Vector dimensions do not match");
3139   Type *SrcElemTy = SrcVecTy->getElementType();
3140   Type *DstElemTy = DstFVTy->getElementType();
3141   assert((DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy)) &&
3142          "Vector elements must have same size");
3143 
3144   // Do a direct cast if element types are castable.
3145   if (CastInst::isBitOrNoopPointerCastable(SrcElemTy, DstElemTy, DL)) {
3146     return Builder.CreateBitOrPointerCast(V, DstFVTy);
3147   }
3148   // V cannot be directly casted to desired vector type.
3149   // May happen when V is a floating point vector but DstVTy is a vector of
3150   // pointers or vice-versa. Handle this using a two-step bitcast using an
3151   // intermediate Integer type for the bitcast i.e. Ptr <-> Int <-> Float.
3152   assert((DstElemTy->isPointerTy() != SrcElemTy->isPointerTy()) &&
3153          "Only one type should be a pointer type");
3154   assert((DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy()) &&
3155          "Only one type should be a floating point type");
3156   Type *IntTy =
3157       IntegerType::getIntNTy(V->getContext(), DL.getTypeSizeInBits(SrcElemTy));
3158   auto *VecIntTy = FixedVectorType::get(IntTy, VF);
3159   Value *CastVal = Builder.CreateBitOrPointerCast(V, VecIntTy);
3160   return Builder.CreateBitOrPointerCast(CastVal, DstFVTy);
3161 }
3162 
3163 void InnerLoopVectorizer::emitMinimumIterationCountCheck(Loop *L,
3164                                                          BasicBlock *Bypass) {
3165   Value *Count = getOrCreateTripCount(L);
3166   // Reuse existing vector loop preheader for TC checks.
3167   // Note that new preheader block is generated for vector loop.
3168   BasicBlock *const TCCheckBlock = LoopVectorPreHeader;
3169   IRBuilder<> Builder(TCCheckBlock->getTerminator());
3170 
3171   // Generate code to check if the loop's trip count is less than VF * UF, or
3172   // equal to it in case a scalar epilogue is required; this implies that the
3173   // vector trip count is zero. This check also covers the case where adding one
3174   // to the backedge-taken count overflowed leading to an incorrect trip count
3175   // of zero. In this case we will also jump to the scalar loop.
3176   auto P = Cost->requiresScalarEpilogue(VF) ? ICmpInst::ICMP_ULE
3177                                             : ICmpInst::ICMP_ULT;
3178 
3179   // If tail is to be folded, vector loop takes care of all iterations.
3180   Value *CheckMinIters = Builder.getFalse();
3181   if (!Cost->foldTailByMasking()) {
3182     Value *Step = createStepForVF(Builder, Count->getType(), VF, UF);
3183     CheckMinIters = Builder.CreateICmp(P, Count, Step, "min.iters.check");
3184   }
3185   // Create new preheader for vector loop.
3186   LoopVectorPreHeader =
3187       SplitBlock(TCCheckBlock, TCCheckBlock->getTerminator(), DT, LI, nullptr,
3188                  "vector.ph");
3189 
3190   assert(DT->properlyDominates(DT->getNode(TCCheckBlock),
3191                                DT->getNode(Bypass)->getIDom()) &&
3192          "TC check is expected to dominate Bypass");
3193 
3194   // Update dominator for Bypass & LoopExit (if needed).
3195   DT->changeImmediateDominator(Bypass, TCCheckBlock);
3196   if (!Cost->requiresScalarEpilogue(VF))
3197     // If there is an epilogue which must run, there's no edge from the
3198     // middle block to exit blocks  and thus no need to update the immediate
3199     // dominator of the exit blocks.
3200     DT->changeImmediateDominator(LoopExitBlock, TCCheckBlock);
3201 
3202   ReplaceInstWithInst(
3203       TCCheckBlock->getTerminator(),
3204       BranchInst::Create(Bypass, LoopVectorPreHeader, CheckMinIters));
3205   LoopBypassBlocks.push_back(TCCheckBlock);
3206 }
3207 
3208 BasicBlock *InnerLoopVectorizer::emitSCEVChecks(Loop *L, BasicBlock *Bypass) {
3209 
3210   BasicBlock *const SCEVCheckBlock =
3211       RTChecks.emitSCEVChecks(L, Bypass, LoopVectorPreHeader, LoopExitBlock);
3212   if (!SCEVCheckBlock)
3213     return nullptr;
3214 
3215   assert(!(SCEVCheckBlock->getParent()->hasOptSize() ||
3216            (OptForSizeBasedOnProfile &&
3217             Cost->Hints->getForce() != LoopVectorizeHints::FK_Enabled)) &&
3218          "Cannot SCEV check stride or overflow when optimizing for size");
3219 
3220 
3221   // Update dominator only if this is first RT check.
3222   if (LoopBypassBlocks.empty()) {
3223     DT->changeImmediateDominator(Bypass, SCEVCheckBlock);
3224     if (!Cost->requiresScalarEpilogue(VF))
3225       // If there is an epilogue which must run, there's no edge from the
3226       // middle block to exit blocks  and thus no need to update the immediate
3227       // dominator of the exit blocks.
3228       DT->changeImmediateDominator(LoopExitBlock, SCEVCheckBlock);
3229   }
3230 
3231   LoopBypassBlocks.push_back(SCEVCheckBlock);
3232   AddedSafetyChecks = true;
3233   return SCEVCheckBlock;
3234 }
3235 
3236 BasicBlock *InnerLoopVectorizer::emitMemRuntimeChecks(Loop *L,
3237                                                       BasicBlock *Bypass) {
3238   // VPlan-native path does not do any analysis for runtime checks currently.
3239   if (EnableVPlanNativePath)
3240     return nullptr;
3241 
3242   BasicBlock *const MemCheckBlock =
3243       RTChecks.emitMemRuntimeChecks(L, Bypass, LoopVectorPreHeader);
3244 
3245   // Check if we generated code that checks in runtime if arrays overlap. We put
3246   // the checks into a separate block to make the more common case of few
3247   // elements faster.
3248   if (!MemCheckBlock)
3249     return nullptr;
3250 
3251   if (MemCheckBlock->getParent()->hasOptSize() || OptForSizeBasedOnProfile) {
3252     assert(Cost->Hints->getForce() == LoopVectorizeHints::FK_Enabled &&
3253            "Cannot emit memory checks when optimizing for size, unless forced "
3254            "to vectorize.");
3255     ORE->emit([&]() {
3256       return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationCodeSize",
3257                                         L->getStartLoc(), L->getHeader())
3258              << "Code-size may be reduced by not forcing "
3259                 "vectorization, or by source-code modifications "
3260                 "eliminating the need for runtime checks "
3261                 "(e.g., adding 'restrict').";
3262     });
3263   }
3264 
3265   LoopBypassBlocks.push_back(MemCheckBlock);
3266 
3267   AddedSafetyChecks = true;
3268 
3269   // We currently don't use LoopVersioning for the actual loop cloning but we
3270   // still use it to add the noalias metadata.
3271   LVer = std::make_unique<LoopVersioning>(
3272       *Legal->getLAI(),
3273       Legal->getLAI()->getRuntimePointerChecking()->getChecks(), OrigLoop, LI,
3274       DT, PSE.getSE());
3275   LVer->prepareNoAliasMetadata();
3276   return MemCheckBlock;
3277 }
3278 
3279 Value *InnerLoopVectorizer::emitTransformedIndex(
3280     IRBuilder<> &B, Value *Index, ScalarEvolution *SE, const DataLayout &DL,
3281     const InductionDescriptor &ID, BasicBlock *VectorHeader) const {
3282 
3283   SCEVExpander Exp(*SE, DL, "induction");
3284   auto Step = ID.getStep();
3285   auto StartValue = ID.getStartValue();
3286   assert(Index->getType()->getScalarType() == Step->getType() &&
3287          "Index scalar type does not match StepValue type");
3288 
3289   // Note: the IR at this point is broken. We cannot use SE to create any new
3290   // SCEV and then expand it, hoping that SCEV's simplification will give us
3291   // a more optimal code. Unfortunately, attempt of doing so on invalid IR may
3292   // lead to various SCEV crashes. So all we can do is to use builder and rely
3293   // on InstCombine for future simplifications. Here we handle some trivial
3294   // cases only.
3295   auto CreateAdd = [&B](Value *X, Value *Y) {
3296     assert(X->getType() == Y->getType() && "Types don't match!");
3297     if (auto *CX = dyn_cast<ConstantInt>(X))
3298       if (CX->isZero())
3299         return Y;
3300     if (auto *CY = dyn_cast<ConstantInt>(Y))
3301       if (CY->isZero())
3302         return X;
3303     return B.CreateAdd(X, Y);
3304   };
3305 
3306   // We allow X to be a vector type, in which case Y will potentially be
3307   // splatted into a vector with the same element count.
3308   auto CreateMul = [&B](Value *X, Value *Y) {
3309     assert(X->getType()->getScalarType() == Y->getType() &&
3310            "Types don't match!");
3311     if (auto *CX = dyn_cast<ConstantInt>(X))
3312       if (CX->isOne())
3313         return Y;
3314     if (auto *CY = dyn_cast<ConstantInt>(Y))
3315       if (CY->isOne())
3316         return X;
3317     VectorType *XVTy = dyn_cast<VectorType>(X->getType());
3318     if (XVTy && !isa<VectorType>(Y->getType()))
3319       Y = B.CreateVectorSplat(XVTy->getElementCount(), Y);
3320     return B.CreateMul(X, Y);
3321   };
3322 
3323   // Get a suitable insert point for SCEV expansion. For blocks in the vector
3324   // loop, choose the end of the vector loop header (=VectorHeader), because
3325   // the DomTree is not kept up-to-date for additional blocks generated in the
3326   // vector loop. By using the header as insertion point, we guarantee that the
3327   // expanded instructions dominate all their uses.
3328   auto GetInsertPoint = [this, &B, VectorHeader]() {
3329     BasicBlock *InsertBB = B.GetInsertPoint()->getParent();
3330     if (InsertBB != LoopVectorBody &&
3331         LI->getLoopFor(VectorHeader) == LI->getLoopFor(InsertBB))
3332       return VectorHeader->getTerminator();
3333     return &*B.GetInsertPoint();
3334   };
3335 
3336   switch (ID.getKind()) {
3337   case InductionDescriptor::IK_IntInduction: {
3338     assert(!isa<VectorType>(Index->getType()) &&
3339            "Vector indices not supported for integer inductions yet");
3340     assert(Index->getType() == StartValue->getType() &&
3341            "Index type does not match StartValue type");
3342     if (ID.getConstIntStepValue() && ID.getConstIntStepValue()->isMinusOne())
3343       return B.CreateSub(StartValue, Index);
3344     auto *Offset = CreateMul(
3345         Index, Exp.expandCodeFor(Step, Index->getType(), GetInsertPoint()));
3346     return CreateAdd(StartValue, Offset);
3347   }
3348   case InductionDescriptor::IK_PtrInduction: {
3349     assert(isa<SCEVConstant>(Step) &&
3350            "Expected constant step for pointer induction");
3351     return B.CreateGEP(
3352         ID.getElementType(), StartValue,
3353         CreateMul(Index,
3354                   Exp.expandCodeFor(Step, Index->getType()->getScalarType(),
3355                                     GetInsertPoint())));
3356   }
3357   case InductionDescriptor::IK_FpInduction: {
3358     assert(!isa<VectorType>(Index->getType()) &&
3359            "Vector indices not supported for FP inductions yet");
3360     assert(Step->getType()->isFloatingPointTy() && "Expected FP Step value");
3361     auto InductionBinOp = ID.getInductionBinOp();
3362     assert(InductionBinOp &&
3363            (InductionBinOp->getOpcode() == Instruction::FAdd ||
3364             InductionBinOp->getOpcode() == Instruction::FSub) &&
3365            "Original bin op should be defined for FP induction");
3366 
3367     Value *StepValue = cast<SCEVUnknown>(Step)->getValue();
3368     Value *MulExp = B.CreateFMul(StepValue, Index);
3369     return B.CreateBinOp(InductionBinOp->getOpcode(), StartValue, MulExp,
3370                          "induction");
3371   }
3372   case InductionDescriptor::IK_NoInduction:
3373     return nullptr;
3374   }
3375   llvm_unreachable("invalid enum");
3376 }
3377 
3378 Loop *InnerLoopVectorizer::createVectorLoopSkeleton(StringRef Prefix) {
3379   LoopScalarBody = OrigLoop->getHeader();
3380   LoopVectorPreHeader = OrigLoop->getLoopPreheader();
3381   assert(LoopVectorPreHeader && "Invalid loop structure");
3382   LoopExitBlock = OrigLoop->getUniqueExitBlock(); // may be nullptr
3383   assert((LoopExitBlock || Cost->requiresScalarEpilogue(VF)) &&
3384          "multiple exit loop without required epilogue?");
3385 
3386   LoopMiddleBlock =
3387       SplitBlock(LoopVectorPreHeader, LoopVectorPreHeader->getTerminator(), DT,
3388                  LI, nullptr, Twine(Prefix) + "middle.block");
3389   LoopScalarPreHeader =
3390       SplitBlock(LoopMiddleBlock, LoopMiddleBlock->getTerminator(), DT, LI,
3391                  nullptr, Twine(Prefix) + "scalar.ph");
3392 
3393   auto *ScalarLatchTerm = OrigLoop->getLoopLatch()->getTerminator();
3394 
3395   // Set up the middle block terminator.  Two cases:
3396   // 1) If we know that we must execute the scalar epilogue, emit an
3397   //    unconditional branch.
3398   // 2) Otherwise, we must have a single unique exit block (due to how we
3399   //    implement the multiple exit case).  In this case, set up a conditonal
3400   //    branch from the middle block to the loop scalar preheader, and the
3401   //    exit block.  completeLoopSkeleton will update the condition to use an
3402   //    iteration check, if required to decide whether to execute the remainder.
3403   BranchInst *BrInst = Cost->requiresScalarEpilogue(VF) ?
3404     BranchInst::Create(LoopScalarPreHeader) :
3405     BranchInst::Create(LoopExitBlock, LoopScalarPreHeader,
3406                        Builder.getTrue());
3407   BrInst->setDebugLoc(ScalarLatchTerm->getDebugLoc());
3408   ReplaceInstWithInst(LoopMiddleBlock->getTerminator(), BrInst);
3409 
3410   // We intentionally don't let SplitBlock to update LoopInfo since
3411   // LoopVectorBody should belong to another loop than LoopVectorPreHeader.
3412   // LoopVectorBody is explicitly added to the correct place few lines later.
3413   LoopVectorBody =
3414       SplitBlock(LoopVectorPreHeader, LoopVectorPreHeader->getTerminator(), DT,
3415                  nullptr, nullptr, Twine(Prefix) + "vector.body");
3416 
3417   // Update dominator for loop exit.
3418   if (!Cost->requiresScalarEpilogue(VF))
3419     // If there is an epilogue which must run, there's no edge from the
3420     // middle block to exit blocks  and thus no need to update the immediate
3421     // dominator of the exit blocks.
3422     DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
3423 
3424   // Create and register the new vector loop.
3425   Loop *Lp = LI->AllocateLoop();
3426   Loop *ParentLoop = OrigLoop->getParentLoop();
3427 
3428   // Insert the new loop into the loop nest and register the new basic blocks
3429   // before calling any utilities such as SCEV that require valid LoopInfo.
3430   if (ParentLoop) {
3431     ParentLoop->addChildLoop(Lp);
3432   } else {
3433     LI->addTopLevelLoop(Lp);
3434   }
3435   Lp->addBasicBlockToLoop(LoopVectorBody, *LI);
3436   return Lp;
3437 }
3438 
3439 void InnerLoopVectorizer::createInductionResumeValues(
3440     Loop *L, Value *VectorTripCount,
3441     std::pair<BasicBlock *, Value *> AdditionalBypass) {
3442   assert(VectorTripCount && L && "Expected valid arguments");
3443   assert(((AdditionalBypass.first && AdditionalBypass.second) ||
3444           (!AdditionalBypass.first && !AdditionalBypass.second)) &&
3445          "Inconsistent information about additional bypass.");
3446   // We are going to resume the execution of the scalar loop.
3447   // Go over all of the induction variables that we found and fix the
3448   // PHIs that are left in the scalar version of the loop.
3449   // The starting values of PHI nodes depend on the counter of the last
3450   // iteration in the vectorized loop.
3451   // If we come from a bypass edge then we need to start from the original
3452   // start value.
3453   for (auto &InductionEntry : Legal->getInductionVars()) {
3454     PHINode *OrigPhi = InductionEntry.first;
3455     InductionDescriptor II = InductionEntry.second;
3456 
3457     // Create phi nodes to merge from the  backedge-taken check block.
3458     PHINode *BCResumeVal =
3459         PHINode::Create(OrigPhi->getType(), 3, "bc.resume.val",
3460                         LoopScalarPreHeader->getTerminator());
3461     // Copy original phi DL over to the new one.
3462     BCResumeVal->setDebugLoc(OrigPhi->getDebugLoc());
3463     Value *&EndValue = IVEndValues[OrigPhi];
3464     Value *EndValueFromAdditionalBypass = AdditionalBypass.second;
3465     if (OrigPhi == OldInduction) {
3466       // We know what the end value is.
3467       EndValue = VectorTripCount;
3468     } else {
3469       IRBuilder<> B(L->getLoopPreheader()->getTerminator());
3470 
3471       // Fast-math-flags propagate from the original induction instruction.
3472       if (II.getInductionBinOp() && isa<FPMathOperator>(II.getInductionBinOp()))
3473         B.setFastMathFlags(II.getInductionBinOp()->getFastMathFlags());
3474 
3475       Type *StepType = II.getStep()->getType();
3476       Instruction::CastOps CastOp =
3477           CastInst::getCastOpcode(VectorTripCount, true, StepType, true);
3478       Value *CRD = B.CreateCast(CastOp, VectorTripCount, StepType, "cast.crd");
3479       const DataLayout &DL = LoopScalarBody->getModule()->getDataLayout();
3480       EndValue =
3481           emitTransformedIndex(B, CRD, PSE.getSE(), DL, II, LoopVectorBody);
3482       EndValue->setName("ind.end");
3483 
3484       // Compute the end value for the additional bypass (if applicable).
3485       if (AdditionalBypass.first) {
3486         B.SetInsertPoint(&(*AdditionalBypass.first->getFirstInsertionPt()));
3487         CastOp = CastInst::getCastOpcode(AdditionalBypass.second, true,
3488                                          StepType, true);
3489         CRD =
3490             B.CreateCast(CastOp, AdditionalBypass.second, StepType, "cast.crd");
3491         EndValueFromAdditionalBypass =
3492             emitTransformedIndex(B, CRD, PSE.getSE(), DL, II, LoopVectorBody);
3493         EndValueFromAdditionalBypass->setName("ind.end");
3494       }
3495     }
3496     // The new PHI merges the original incoming value, in case of a bypass,
3497     // or the value at the end of the vectorized loop.
3498     BCResumeVal->addIncoming(EndValue, LoopMiddleBlock);
3499 
3500     // Fix the scalar body counter (PHI node).
3501     // The old induction's phi node in the scalar body needs the truncated
3502     // value.
3503     for (BasicBlock *BB : LoopBypassBlocks)
3504       BCResumeVal->addIncoming(II.getStartValue(), BB);
3505 
3506     if (AdditionalBypass.first)
3507       BCResumeVal->setIncomingValueForBlock(AdditionalBypass.first,
3508                                             EndValueFromAdditionalBypass);
3509 
3510     OrigPhi->setIncomingValueForBlock(LoopScalarPreHeader, BCResumeVal);
3511   }
3512 }
3513 
3514 BasicBlock *InnerLoopVectorizer::completeLoopSkeleton(Loop *L,
3515                                                       MDNode *OrigLoopID) {
3516   assert(L && "Expected valid loop.");
3517 
3518   // The trip counts should be cached by now.
3519   Value *Count = getOrCreateTripCount(L);
3520   Value *VectorTripCount = getOrCreateVectorTripCount(L);
3521 
3522   auto *ScalarLatchTerm = OrigLoop->getLoopLatch()->getTerminator();
3523 
3524   // Add a check in the middle block to see if we have completed
3525   // all of the iterations in the first vector loop.  Three cases:
3526   // 1) If we require a scalar epilogue, there is no conditional branch as
3527   //    we unconditionally branch to the scalar preheader.  Do nothing.
3528   // 2) If (N - N%VF) == N, then we *don't* need to run the remainder.
3529   //    Thus if tail is to be folded, we know we don't need to run the
3530   //    remainder and we can use the previous value for the condition (true).
3531   // 3) Otherwise, construct a runtime check.
3532   if (!Cost->requiresScalarEpilogue(VF) && !Cost->foldTailByMasking()) {
3533     Instruction *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
3534                                         Count, VectorTripCount, "cmp.n",
3535                                         LoopMiddleBlock->getTerminator());
3536 
3537     // Here we use the same DebugLoc as the scalar loop latch terminator instead
3538     // of the corresponding compare because they may have ended up with
3539     // different line numbers and we want to avoid awkward line stepping while
3540     // debugging. Eg. if the compare has got a line number inside the loop.
3541     CmpN->setDebugLoc(ScalarLatchTerm->getDebugLoc());
3542     cast<BranchInst>(LoopMiddleBlock->getTerminator())->setCondition(CmpN);
3543   }
3544 
3545   // Get ready to start creating new instructions into the vectorized body.
3546   assert(LoopVectorPreHeader == L->getLoopPreheader() &&
3547          "Inconsistent vector loop preheader");
3548   Builder.SetInsertPoint(&*LoopVectorBody->getFirstInsertionPt());
3549 
3550 #ifdef EXPENSIVE_CHECKS
3551   assert(DT->verify(DominatorTree::VerificationLevel::Fast));
3552   LI->verify(*DT);
3553 #endif
3554 
3555   return LoopVectorPreHeader;
3556 }
3557 
3558 BasicBlock *InnerLoopVectorizer::createVectorizedLoopSkeleton() {
3559   /*
3560    In this function we generate a new loop. The new loop will contain
3561    the vectorized instructions while the old loop will continue to run the
3562    scalar remainder.
3563 
3564        [ ] <-- loop iteration number check.
3565     /   |
3566    /    v
3567   |    [ ] <-- vector loop bypass (may consist of multiple blocks).
3568   |  /  |
3569   | /   v
3570   ||   [ ]     <-- vector pre header.
3571   |/    |
3572   |     v
3573   |    [  ] \
3574   |    [  ]_|   <-- vector loop.
3575   |     |
3576   |     v
3577   \   -[ ]   <--- middle-block.
3578    \/   |
3579    /\   v
3580    | ->[ ]     <--- new preheader.
3581    |    |
3582  (opt)  v      <-- edge from middle to exit iff epilogue is not required.
3583    |   [ ] \
3584    |   [ ]_|   <-- old scalar loop to handle remainder (scalar epilogue).
3585     \   |
3586      \  v
3587       >[ ]     <-- exit block(s).
3588    ...
3589    */
3590 
3591   // Get the metadata of the original loop before it gets modified.
3592   MDNode *OrigLoopID = OrigLoop->getLoopID();
3593 
3594   // Workaround!  Compute the trip count of the original loop and cache it
3595   // before we start modifying the CFG.  This code has a systemic problem
3596   // wherein it tries to run analysis over partially constructed IR; this is
3597   // wrong, and not simply for SCEV.  The trip count of the original loop
3598   // simply happens to be prone to hitting this in practice.  In theory, we
3599   // can hit the same issue for any SCEV, or ValueTracking query done during
3600   // mutation.  See PR49900.
3601   getOrCreateTripCount(OrigLoop);
3602 
3603   // Create an empty vector loop, and prepare basic blocks for the runtime
3604   // checks.
3605   Loop *Lp = createVectorLoopSkeleton("");
3606 
3607   // Now, compare the new count to zero. If it is zero skip the vector loop and
3608   // jump to the scalar loop. This check also covers the case where the
3609   // backedge-taken count is uint##_max: adding one to it will overflow leading
3610   // to an incorrect trip count of zero. In this (rare) case we will also jump
3611   // to the scalar loop.
3612   emitMinimumIterationCountCheck(Lp, LoopScalarPreHeader);
3613 
3614   // Generate the code to check any assumptions that we've made for SCEV
3615   // expressions.
3616   emitSCEVChecks(Lp, LoopScalarPreHeader);
3617 
3618   // Generate the code that checks in runtime if arrays overlap. We put the
3619   // checks into a separate block to make the more common case of few elements
3620   // faster.
3621   emitMemRuntimeChecks(Lp, LoopScalarPreHeader);
3622 
3623   // Some loops have a single integer induction variable, while other loops
3624   // don't. One example is c++ iterators that often have multiple pointer
3625   // induction variables. In the code below we also support a case where we
3626   // don't have a single induction variable.
3627   //
3628   // We try to obtain an induction variable from the original loop as hard
3629   // as possible. However if we don't find one that:
3630   //   - is an integer
3631   //   - counts from zero, stepping by one
3632   //   - is the size of the widest induction variable type
3633   // then we create a new one.
3634   OldInduction = Legal->getPrimaryInduction();
3635   Type *IdxTy = Legal->getWidestInductionType();
3636   Value *StartIdx = ConstantInt::get(IdxTy, 0);
3637   // The loop step is equal to the vectorization factor (num of SIMD elements)
3638   // times the unroll factor (num of SIMD instructions).
3639   Builder.SetInsertPoint(&*Lp->getHeader()->getFirstInsertionPt());
3640   Value *Step = createStepForVF(Builder, IdxTy, VF, UF);
3641   Value *CountRoundDown = getOrCreateVectorTripCount(Lp);
3642   Induction =
3643       createInductionVariable(Lp, StartIdx, CountRoundDown, Step,
3644                               getDebugLocFromInstOrOperands(OldInduction));
3645 
3646   // Emit phis for the new starting index of the scalar loop.
3647   createInductionResumeValues(Lp, CountRoundDown);
3648 
3649   return completeLoopSkeleton(Lp, OrigLoopID);
3650 }
3651 
3652 // Fix up external users of the induction variable. At this point, we are
3653 // in LCSSA form, with all external PHIs that use the IV having one input value,
3654 // coming from the remainder loop. We need those PHIs to also have a correct
3655 // value for the IV when arriving directly from the middle block.
3656 void InnerLoopVectorizer::fixupIVUsers(PHINode *OrigPhi,
3657                                        const InductionDescriptor &II,
3658                                        Value *CountRoundDown, Value *EndValue,
3659                                        BasicBlock *MiddleBlock) {
3660   // There are two kinds of external IV usages - those that use the value
3661   // computed in the last iteration (the PHI) and those that use the penultimate
3662   // value (the value that feeds into the phi from the loop latch).
3663   // We allow both, but they, obviously, have different values.
3664 
3665   assert(OrigLoop->getUniqueExitBlock() && "Expected a single exit block");
3666 
3667   DenseMap<Value *, Value *> MissingVals;
3668 
3669   // An external user of the last iteration's value should see the value that
3670   // the remainder loop uses to initialize its own IV.
3671   Value *PostInc = OrigPhi->getIncomingValueForBlock(OrigLoop->getLoopLatch());
3672   for (User *U : PostInc->users()) {
3673     Instruction *UI = cast<Instruction>(U);
3674     if (!OrigLoop->contains(UI)) {
3675       assert(isa<PHINode>(UI) && "Expected LCSSA form");
3676       MissingVals[UI] = EndValue;
3677     }
3678   }
3679 
3680   // An external user of the penultimate value need to see EndValue - Step.
3681   // The simplest way to get this is to recompute it from the constituent SCEVs,
3682   // that is Start + (Step * (CRD - 1)).
3683   for (User *U : OrigPhi->users()) {
3684     auto *UI = cast<Instruction>(U);
3685     if (!OrigLoop->contains(UI)) {
3686       const DataLayout &DL =
3687           OrigLoop->getHeader()->getModule()->getDataLayout();
3688       assert(isa<PHINode>(UI) && "Expected LCSSA form");
3689 
3690       IRBuilder<> B(MiddleBlock->getTerminator());
3691 
3692       // Fast-math-flags propagate from the original induction instruction.
3693       if (II.getInductionBinOp() && isa<FPMathOperator>(II.getInductionBinOp()))
3694         B.setFastMathFlags(II.getInductionBinOp()->getFastMathFlags());
3695 
3696       Value *CountMinusOne = B.CreateSub(
3697           CountRoundDown, ConstantInt::get(CountRoundDown->getType(), 1));
3698       Value *CMO =
3699           !II.getStep()->getType()->isIntegerTy()
3700               ? B.CreateCast(Instruction::SIToFP, CountMinusOne,
3701                              II.getStep()->getType())
3702               : B.CreateSExtOrTrunc(CountMinusOne, II.getStep()->getType());
3703       CMO->setName("cast.cmo");
3704       Value *Escape =
3705           emitTransformedIndex(B, CMO, PSE.getSE(), DL, II, LoopVectorBody);
3706       Escape->setName("ind.escape");
3707       MissingVals[UI] = Escape;
3708     }
3709   }
3710 
3711   for (auto &I : MissingVals) {
3712     PHINode *PHI = cast<PHINode>(I.first);
3713     // One corner case we have to handle is two IVs "chasing" each-other,
3714     // that is %IV2 = phi [...], [ %IV1, %latch ]
3715     // In this case, if IV1 has an external use, we need to avoid adding both
3716     // "last value of IV1" and "penultimate value of IV2". So, verify that we
3717     // don't already have an incoming value for the middle block.
3718     if (PHI->getBasicBlockIndex(MiddleBlock) == -1)
3719       PHI->addIncoming(I.second, MiddleBlock);
3720   }
3721 }
3722 
3723 namespace {
3724 
3725 struct CSEDenseMapInfo {
3726   static bool canHandle(const Instruction *I) {
3727     return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
3728            isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
3729   }
3730 
3731   static inline Instruction *getEmptyKey() {
3732     return DenseMapInfo<Instruction *>::getEmptyKey();
3733   }
3734 
3735   static inline Instruction *getTombstoneKey() {
3736     return DenseMapInfo<Instruction *>::getTombstoneKey();
3737   }
3738 
3739   static unsigned getHashValue(const Instruction *I) {
3740     assert(canHandle(I) && "Unknown instruction!");
3741     return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
3742                                                            I->value_op_end()));
3743   }
3744 
3745   static bool isEqual(const Instruction *LHS, const Instruction *RHS) {
3746     if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
3747         LHS == getTombstoneKey() || RHS == getTombstoneKey())
3748       return LHS == RHS;
3749     return LHS->isIdenticalTo(RHS);
3750   }
3751 };
3752 
3753 } // end anonymous namespace
3754 
3755 ///Perform cse of induction variable instructions.
3756 static void cse(BasicBlock *BB) {
3757   // Perform simple cse.
3758   SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
3759   for (Instruction &In : llvm::make_early_inc_range(*BB)) {
3760     if (!CSEDenseMapInfo::canHandle(&In))
3761       continue;
3762 
3763     // Check if we can replace this instruction with any of the
3764     // visited instructions.
3765     if (Instruction *V = CSEMap.lookup(&In)) {
3766       In.replaceAllUsesWith(V);
3767       In.eraseFromParent();
3768       continue;
3769     }
3770 
3771     CSEMap[&In] = &In;
3772   }
3773 }
3774 
3775 InstructionCost
3776 LoopVectorizationCostModel::getVectorCallCost(CallInst *CI, ElementCount VF,
3777                                               bool &NeedToScalarize) const {
3778   Function *F = CI->getCalledFunction();
3779   Type *ScalarRetTy = CI->getType();
3780   SmallVector<Type *, 4> Tys, ScalarTys;
3781   for (auto &ArgOp : CI->args())
3782     ScalarTys.push_back(ArgOp->getType());
3783 
3784   // Estimate cost of scalarized vector call. The source operands are assumed
3785   // to be vectors, so we need to extract individual elements from there,
3786   // execute VF scalar calls, and then gather the result into the vector return
3787   // value.
3788   InstructionCost ScalarCallCost =
3789       TTI.getCallInstrCost(F, ScalarRetTy, ScalarTys, TTI::TCK_RecipThroughput);
3790   if (VF.isScalar())
3791     return ScalarCallCost;
3792 
3793   // Compute corresponding vector type for return value and arguments.
3794   Type *RetTy = ToVectorTy(ScalarRetTy, VF);
3795   for (Type *ScalarTy : ScalarTys)
3796     Tys.push_back(ToVectorTy(ScalarTy, VF));
3797 
3798   // Compute costs of unpacking argument values for the scalar calls and
3799   // packing the return values to a vector.
3800   InstructionCost ScalarizationCost = getScalarizationOverhead(CI, VF);
3801 
3802   InstructionCost Cost =
3803       ScalarCallCost * VF.getKnownMinValue() + ScalarizationCost;
3804 
3805   // If we can't emit a vector call for this function, then the currently found
3806   // cost is the cost we need to return.
3807   NeedToScalarize = true;
3808   VFShape Shape = VFShape::get(*CI, VF, false /*HasGlobalPred*/);
3809   Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
3810 
3811   if (!TLI || CI->isNoBuiltin() || !VecFunc)
3812     return Cost;
3813 
3814   // If the corresponding vector cost is cheaper, return its cost.
3815   InstructionCost VectorCallCost =
3816       TTI.getCallInstrCost(nullptr, RetTy, Tys, TTI::TCK_RecipThroughput);
3817   if (VectorCallCost < Cost) {
3818     NeedToScalarize = false;
3819     Cost = VectorCallCost;
3820   }
3821   return Cost;
3822 }
3823 
3824 static Type *MaybeVectorizeType(Type *Elt, ElementCount VF) {
3825   if (VF.isScalar() || (!Elt->isIntOrPtrTy() && !Elt->isFloatingPointTy()))
3826     return Elt;
3827   return VectorType::get(Elt, VF);
3828 }
3829 
3830 InstructionCost
3831 LoopVectorizationCostModel::getVectorIntrinsicCost(CallInst *CI,
3832                                                    ElementCount VF) const {
3833   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
3834   assert(ID && "Expected intrinsic call!");
3835   Type *RetTy = MaybeVectorizeType(CI->getType(), VF);
3836   FastMathFlags FMF;
3837   if (auto *FPMO = dyn_cast<FPMathOperator>(CI))
3838     FMF = FPMO->getFastMathFlags();
3839 
3840   SmallVector<const Value *> Arguments(CI->args());
3841   FunctionType *FTy = CI->getCalledFunction()->getFunctionType();
3842   SmallVector<Type *> ParamTys;
3843   std::transform(FTy->param_begin(), FTy->param_end(),
3844                  std::back_inserter(ParamTys),
3845                  [&](Type *Ty) { return MaybeVectorizeType(Ty, VF); });
3846 
3847   IntrinsicCostAttributes CostAttrs(ID, RetTy, Arguments, ParamTys, FMF,
3848                                     dyn_cast<IntrinsicInst>(CI));
3849   return TTI.getIntrinsicInstrCost(CostAttrs,
3850                                    TargetTransformInfo::TCK_RecipThroughput);
3851 }
3852 
3853 static Type *smallestIntegerVectorType(Type *T1, Type *T2) {
3854   auto *I1 = cast<IntegerType>(cast<VectorType>(T1)->getElementType());
3855   auto *I2 = cast<IntegerType>(cast<VectorType>(T2)->getElementType());
3856   return I1->getBitWidth() < I2->getBitWidth() ? T1 : T2;
3857 }
3858 
3859 static Type *largestIntegerVectorType(Type *T1, Type *T2) {
3860   auto *I1 = cast<IntegerType>(cast<VectorType>(T1)->getElementType());
3861   auto *I2 = cast<IntegerType>(cast<VectorType>(T2)->getElementType());
3862   return I1->getBitWidth() > I2->getBitWidth() ? T1 : T2;
3863 }
3864 
3865 void InnerLoopVectorizer::truncateToMinimalBitwidths(VPTransformState &State) {
3866   // For every instruction `I` in MinBWs, truncate the operands, create a
3867   // truncated version of `I` and reextend its result. InstCombine runs
3868   // later and will remove any ext/trunc pairs.
3869   SmallPtrSet<Value *, 4> Erased;
3870   for (const auto &KV : Cost->getMinimalBitwidths()) {
3871     // If the value wasn't vectorized, we must maintain the original scalar
3872     // type. The absence of the value from State indicates that it
3873     // wasn't vectorized.
3874     // FIXME: Should not rely on getVPValue at this point.
3875     VPValue *Def = State.Plan->getVPValue(KV.first, true);
3876     if (!State.hasAnyVectorValue(Def))
3877       continue;
3878     for (unsigned Part = 0; Part < UF; ++Part) {
3879       Value *I = State.get(Def, Part);
3880       if (Erased.count(I) || I->use_empty() || !isa<Instruction>(I))
3881         continue;
3882       Type *OriginalTy = I->getType();
3883       Type *ScalarTruncatedTy =
3884           IntegerType::get(OriginalTy->getContext(), KV.second);
3885       auto *TruncatedTy = VectorType::get(
3886           ScalarTruncatedTy, cast<VectorType>(OriginalTy)->getElementCount());
3887       if (TruncatedTy == OriginalTy)
3888         continue;
3889 
3890       IRBuilder<> B(cast<Instruction>(I));
3891       auto ShrinkOperand = [&](Value *V) -> Value * {
3892         if (auto *ZI = dyn_cast<ZExtInst>(V))
3893           if (ZI->getSrcTy() == TruncatedTy)
3894             return ZI->getOperand(0);
3895         return B.CreateZExtOrTrunc(V, TruncatedTy);
3896       };
3897 
3898       // The actual instruction modification depends on the instruction type,
3899       // unfortunately.
3900       Value *NewI = nullptr;
3901       if (auto *BO = dyn_cast<BinaryOperator>(I)) {
3902         NewI = B.CreateBinOp(BO->getOpcode(), ShrinkOperand(BO->getOperand(0)),
3903                              ShrinkOperand(BO->getOperand(1)));
3904 
3905         // Any wrapping introduced by shrinking this operation shouldn't be
3906         // considered undefined behavior. So, we can't unconditionally copy
3907         // arithmetic wrapping flags to NewI.
3908         cast<BinaryOperator>(NewI)->copyIRFlags(I, /*IncludeWrapFlags=*/false);
3909       } else if (auto *CI = dyn_cast<ICmpInst>(I)) {
3910         NewI =
3911             B.CreateICmp(CI->getPredicate(), ShrinkOperand(CI->getOperand(0)),
3912                          ShrinkOperand(CI->getOperand(1)));
3913       } else if (auto *SI = dyn_cast<SelectInst>(I)) {
3914         NewI = B.CreateSelect(SI->getCondition(),
3915                               ShrinkOperand(SI->getTrueValue()),
3916                               ShrinkOperand(SI->getFalseValue()));
3917       } else if (auto *CI = dyn_cast<CastInst>(I)) {
3918         switch (CI->getOpcode()) {
3919         default:
3920           llvm_unreachable("Unhandled cast!");
3921         case Instruction::Trunc:
3922           NewI = ShrinkOperand(CI->getOperand(0));
3923           break;
3924         case Instruction::SExt:
3925           NewI = B.CreateSExtOrTrunc(
3926               CI->getOperand(0),
3927               smallestIntegerVectorType(OriginalTy, TruncatedTy));
3928           break;
3929         case Instruction::ZExt:
3930           NewI = B.CreateZExtOrTrunc(
3931               CI->getOperand(0),
3932               smallestIntegerVectorType(OriginalTy, TruncatedTy));
3933           break;
3934         }
3935       } else if (auto *SI = dyn_cast<ShuffleVectorInst>(I)) {
3936         auto Elements0 =
3937             cast<VectorType>(SI->getOperand(0)->getType())->getElementCount();
3938         auto *O0 = B.CreateZExtOrTrunc(
3939             SI->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements0));
3940         auto Elements1 =
3941             cast<VectorType>(SI->getOperand(1)->getType())->getElementCount();
3942         auto *O1 = B.CreateZExtOrTrunc(
3943             SI->getOperand(1), VectorType::get(ScalarTruncatedTy, Elements1));
3944 
3945         NewI = B.CreateShuffleVector(O0, O1, SI->getShuffleMask());
3946       } else if (isa<LoadInst>(I) || isa<PHINode>(I)) {
3947         // Don't do anything with the operands, just extend the result.
3948         continue;
3949       } else if (auto *IE = dyn_cast<InsertElementInst>(I)) {
3950         auto Elements =
3951             cast<VectorType>(IE->getOperand(0)->getType())->getElementCount();
3952         auto *O0 = B.CreateZExtOrTrunc(
3953             IE->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements));
3954         auto *O1 = B.CreateZExtOrTrunc(IE->getOperand(1), ScalarTruncatedTy);
3955         NewI = B.CreateInsertElement(O0, O1, IE->getOperand(2));
3956       } else if (auto *EE = dyn_cast<ExtractElementInst>(I)) {
3957         auto Elements =
3958             cast<VectorType>(EE->getOperand(0)->getType())->getElementCount();
3959         auto *O0 = B.CreateZExtOrTrunc(
3960             EE->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements));
3961         NewI = B.CreateExtractElement(O0, EE->getOperand(2));
3962       } else {
3963         // If we don't know what to do, be conservative and don't do anything.
3964         continue;
3965       }
3966 
3967       // Lastly, extend the result.
3968       NewI->takeName(cast<Instruction>(I));
3969       Value *Res = B.CreateZExtOrTrunc(NewI, OriginalTy);
3970       I->replaceAllUsesWith(Res);
3971       cast<Instruction>(I)->eraseFromParent();
3972       Erased.insert(I);
3973       State.reset(Def, Res, Part);
3974     }
3975   }
3976 
3977   // We'll have created a bunch of ZExts that are now parentless. Clean up.
3978   for (const auto &KV : Cost->getMinimalBitwidths()) {
3979     // If the value wasn't vectorized, we must maintain the original scalar
3980     // type. The absence of the value from State indicates that it
3981     // wasn't vectorized.
3982     // FIXME: Should not rely on getVPValue at this point.
3983     VPValue *Def = State.Plan->getVPValue(KV.first, true);
3984     if (!State.hasAnyVectorValue(Def))
3985       continue;
3986     for (unsigned Part = 0; Part < UF; ++Part) {
3987       Value *I = State.get(Def, Part);
3988       ZExtInst *Inst = dyn_cast<ZExtInst>(I);
3989       if (Inst && Inst->use_empty()) {
3990         Value *NewI = Inst->getOperand(0);
3991         Inst->eraseFromParent();
3992         State.reset(Def, NewI, Part);
3993       }
3994     }
3995   }
3996 }
3997 
3998 void InnerLoopVectorizer::fixVectorizedLoop(VPTransformState &State) {
3999   // Insert truncates and extends for any truncated instructions as hints to
4000   // InstCombine.
4001   if (VF.isVector())
4002     truncateToMinimalBitwidths(State);
4003 
4004   // Fix widened non-induction PHIs by setting up the PHI operands.
4005   if (OrigPHIsToFix.size()) {
4006     assert(EnableVPlanNativePath &&
4007            "Unexpected non-induction PHIs for fixup in non VPlan-native path");
4008     fixNonInductionPHIs(State);
4009   }
4010 
4011   // At this point every instruction in the original loop is widened to a
4012   // vector form. Now we need to fix the recurrences in the loop. These PHI
4013   // nodes are currently empty because we did not want to introduce cycles.
4014   // This is the second stage of vectorizing recurrences.
4015   fixCrossIterationPHIs(State);
4016 
4017   // Forget the original basic block.
4018   PSE.getSE()->forgetLoop(OrigLoop);
4019 
4020   // If we inserted an edge from the middle block to the unique exit block,
4021   // update uses outside the loop (phis) to account for the newly inserted
4022   // edge.
4023   if (!Cost->requiresScalarEpilogue(VF)) {
4024     // Fix-up external users of the induction variables.
4025     for (auto &Entry : Legal->getInductionVars())
4026       fixupIVUsers(Entry.first, Entry.second,
4027                    getOrCreateVectorTripCount(LI->getLoopFor(LoopVectorBody)),
4028                    IVEndValues[Entry.first], LoopMiddleBlock);
4029 
4030     fixLCSSAPHIs(State);
4031   }
4032 
4033   for (Instruction *PI : PredicatedInstructions)
4034     sinkScalarOperands(&*PI);
4035 
4036   // Remove redundant induction instructions.
4037   cse(LoopVectorBody);
4038 
4039   // Set/update profile weights for the vector and remainder loops as original
4040   // loop iterations are now distributed among them. Note that original loop
4041   // represented by LoopScalarBody becomes remainder loop after vectorization.
4042   //
4043   // For cases like foldTailByMasking() and requiresScalarEpiloque() we may
4044   // end up getting slightly roughened result but that should be OK since
4045   // profile is not inherently precise anyway. Note also possible bypass of
4046   // vector code caused by legality checks is ignored, assigning all the weight
4047   // to the vector loop, optimistically.
4048   //
4049   // For scalable vectorization we can't know at compile time how many iterations
4050   // of the loop are handled in one vector iteration, so instead assume a pessimistic
4051   // vscale of '1'.
4052   setProfileInfoAfterUnrolling(
4053       LI->getLoopFor(LoopScalarBody), LI->getLoopFor(LoopVectorBody),
4054       LI->getLoopFor(LoopScalarBody), VF.getKnownMinValue() * UF);
4055 }
4056 
4057 void InnerLoopVectorizer::fixCrossIterationPHIs(VPTransformState &State) {
4058   // In order to support recurrences we need to be able to vectorize Phi nodes.
4059   // Phi nodes have cycles, so we need to vectorize them in two stages. This is
4060   // stage #2: We now need to fix the recurrences by adding incoming edges to
4061   // the currently empty PHI nodes. At this point every instruction in the
4062   // original loop is widened to a vector form so we can use them to construct
4063   // the incoming edges.
4064   VPBasicBlock *Header = State.Plan->getEntry()->getEntryBasicBlock();
4065   for (VPRecipeBase &R : Header->phis()) {
4066     if (auto *ReductionPhi = dyn_cast<VPReductionPHIRecipe>(&R))
4067       fixReduction(ReductionPhi, State);
4068     else if (auto *FOR = dyn_cast<VPFirstOrderRecurrencePHIRecipe>(&R))
4069       fixFirstOrderRecurrence(FOR, State);
4070   }
4071 }
4072 
4073 void InnerLoopVectorizer::fixFirstOrderRecurrence(
4074     VPFirstOrderRecurrencePHIRecipe *PhiR, VPTransformState &State) {
4075   // This is the second phase of vectorizing first-order recurrences. An
4076   // overview of the transformation is described below. Suppose we have the
4077   // following loop.
4078   //
4079   //   for (int i = 0; i < n; ++i)
4080   //     b[i] = a[i] - a[i - 1];
4081   //
4082   // There is a first-order recurrence on "a". For this loop, the shorthand
4083   // scalar IR looks like:
4084   //
4085   //   scalar.ph:
4086   //     s_init = a[-1]
4087   //     br scalar.body
4088   //
4089   //   scalar.body:
4090   //     i = phi [0, scalar.ph], [i+1, scalar.body]
4091   //     s1 = phi [s_init, scalar.ph], [s2, scalar.body]
4092   //     s2 = a[i]
4093   //     b[i] = s2 - s1
4094   //     br cond, scalar.body, ...
4095   //
4096   // In this example, s1 is a recurrence because it's value depends on the
4097   // previous iteration. In the first phase of vectorization, we created a
4098   // vector phi v1 for s1. We now complete the vectorization and produce the
4099   // shorthand vector IR shown below (for VF = 4, UF = 1).
4100   //
4101   //   vector.ph:
4102   //     v_init = vector(..., ..., ..., a[-1])
4103   //     br vector.body
4104   //
4105   //   vector.body
4106   //     i = phi [0, vector.ph], [i+4, vector.body]
4107   //     v1 = phi [v_init, vector.ph], [v2, vector.body]
4108   //     v2 = a[i, i+1, i+2, i+3];
4109   //     v3 = vector(v1(3), v2(0, 1, 2))
4110   //     b[i, i+1, i+2, i+3] = v2 - v3
4111   //     br cond, vector.body, middle.block
4112   //
4113   //   middle.block:
4114   //     x = v2(3)
4115   //     br scalar.ph
4116   //
4117   //   scalar.ph:
4118   //     s_init = phi [x, middle.block], [a[-1], otherwise]
4119   //     br scalar.body
4120   //
4121   // After execution completes the vector loop, we extract the next value of
4122   // the recurrence (x) to use as the initial value in the scalar loop.
4123 
4124   // Extract the last vector element in the middle block. This will be the
4125   // initial value for the recurrence when jumping to the scalar loop.
4126   VPValue *PreviousDef = PhiR->getBackedgeValue();
4127   Value *Incoming = State.get(PreviousDef, UF - 1);
4128   auto *ExtractForScalar = Incoming;
4129   auto *IdxTy = Builder.getInt32Ty();
4130   if (VF.isVector()) {
4131     auto *One = ConstantInt::get(IdxTy, 1);
4132     Builder.SetInsertPoint(LoopMiddleBlock->getTerminator());
4133     auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, VF);
4134     auto *LastIdx = Builder.CreateSub(RuntimeVF, One);
4135     ExtractForScalar = Builder.CreateExtractElement(ExtractForScalar, LastIdx,
4136                                                     "vector.recur.extract");
4137   }
4138   // Extract the second last element in the middle block if the
4139   // Phi is used outside the loop. We need to extract the phi itself
4140   // and not the last element (the phi update in the current iteration). This
4141   // will be the value when jumping to the exit block from the LoopMiddleBlock,
4142   // when the scalar loop is not run at all.
4143   Value *ExtractForPhiUsedOutsideLoop = nullptr;
4144   if (VF.isVector()) {
4145     auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, VF);
4146     auto *Idx = Builder.CreateSub(RuntimeVF, ConstantInt::get(IdxTy, 2));
4147     ExtractForPhiUsedOutsideLoop = Builder.CreateExtractElement(
4148         Incoming, Idx, "vector.recur.extract.for.phi");
4149   } else if (UF > 1)
4150     // When loop is unrolled without vectorizing, initialize
4151     // ExtractForPhiUsedOutsideLoop with the value just prior to unrolled value
4152     // of `Incoming`. This is analogous to the vectorized case above: extracting
4153     // the second last element when VF > 1.
4154     ExtractForPhiUsedOutsideLoop = State.get(PreviousDef, UF - 2);
4155 
4156   // Fix the initial value of the original recurrence in the scalar loop.
4157   Builder.SetInsertPoint(&*LoopScalarPreHeader->begin());
4158   PHINode *Phi = cast<PHINode>(PhiR->getUnderlyingValue());
4159   auto *Start = Builder.CreatePHI(Phi->getType(), 2, "scalar.recur.init");
4160   auto *ScalarInit = PhiR->getStartValue()->getLiveInIRValue();
4161   for (auto *BB : predecessors(LoopScalarPreHeader)) {
4162     auto *Incoming = BB == LoopMiddleBlock ? ExtractForScalar : ScalarInit;
4163     Start->addIncoming(Incoming, BB);
4164   }
4165 
4166   Phi->setIncomingValueForBlock(LoopScalarPreHeader, Start);
4167   Phi->setName("scalar.recur");
4168 
4169   // Finally, fix users of the recurrence outside the loop. The users will need
4170   // either the last value of the scalar recurrence or the last value of the
4171   // vector recurrence we extracted in the middle block. Since the loop is in
4172   // LCSSA form, we just need to find all the phi nodes for the original scalar
4173   // recurrence in the exit block, and then add an edge for the middle block.
4174   // Note that LCSSA does not imply single entry when the original scalar loop
4175   // had multiple exiting edges (as we always run the last iteration in the
4176   // scalar epilogue); in that case, there is no edge from middle to exit and
4177   // and thus no phis which needed updated.
4178   if (!Cost->requiresScalarEpilogue(VF))
4179     for (PHINode &LCSSAPhi : LoopExitBlock->phis())
4180       if (llvm::is_contained(LCSSAPhi.incoming_values(), Phi))
4181         LCSSAPhi.addIncoming(ExtractForPhiUsedOutsideLoop, LoopMiddleBlock);
4182 }
4183 
4184 void InnerLoopVectorizer::fixReduction(VPReductionPHIRecipe *PhiR,
4185                                        VPTransformState &State) {
4186   PHINode *OrigPhi = cast<PHINode>(PhiR->getUnderlyingValue());
4187   // Get it's reduction variable descriptor.
4188   assert(Legal->isReductionVariable(OrigPhi) &&
4189          "Unable to find the reduction variable");
4190   const RecurrenceDescriptor &RdxDesc = PhiR->getRecurrenceDescriptor();
4191 
4192   RecurKind RK = RdxDesc.getRecurrenceKind();
4193   TrackingVH<Value> ReductionStartValue = RdxDesc.getRecurrenceStartValue();
4194   Instruction *LoopExitInst = RdxDesc.getLoopExitInstr();
4195   setDebugLocFromInst(ReductionStartValue);
4196 
4197   VPValue *LoopExitInstDef = PhiR->getBackedgeValue();
4198   // This is the vector-clone of the value that leaves the loop.
4199   Type *VecTy = State.get(LoopExitInstDef, 0)->getType();
4200 
4201   // Wrap flags are in general invalid after vectorization, clear them.
4202   clearReductionWrapFlags(RdxDesc, State);
4203 
4204   // Before each round, move the insertion point right between
4205   // the PHIs and the values we are going to write.
4206   // This allows us to write both PHINodes and the extractelement
4207   // instructions.
4208   Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
4209 
4210   setDebugLocFromInst(LoopExitInst);
4211 
4212   Type *PhiTy = OrigPhi->getType();
4213   // If tail is folded by masking, the vector value to leave the loop should be
4214   // a Select choosing between the vectorized LoopExitInst and vectorized Phi,
4215   // instead of the former. For an inloop reduction the reduction will already
4216   // be predicated, and does not need to be handled here.
4217   if (Cost->foldTailByMasking() && !PhiR->isInLoop()) {
4218     for (unsigned Part = 0; Part < UF; ++Part) {
4219       Value *VecLoopExitInst = State.get(LoopExitInstDef, Part);
4220       Value *Sel = nullptr;
4221       for (User *U : VecLoopExitInst->users()) {
4222         if (isa<SelectInst>(U)) {
4223           assert(!Sel && "Reduction exit feeding two selects");
4224           Sel = U;
4225         } else
4226           assert(isa<PHINode>(U) && "Reduction exit must feed Phi's or select");
4227       }
4228       assert(Sel && "Reduction exit feeds no select");
4229       State.reset(LoopExitInstDef, Sel, Part);
4230 
4231       // If the target can create a predicated operator for the reduction at no
4232       // extra cost in the loop (for example a predicated vadd), it can be
4233       // cheaper for the select to remain in the loop than be sunk out of it,
4234       // and so use the select value for the phi instead of the old
4235       // LoopExitValue.
4236       if (PreferPredicatedReductionSelect ||
4237           TTI->preferPredicatedReductionSelect(
4238               RdxDesc.getOpcode(), PhiTy,
4239               TargetTransformInfo::ReductionFlags())) {
4240         auto *VecRdxPhi =
4241             cast<PHINode>(State.get(PhiR, Part));
4242         VecRdxPhi->setIncomingValueForBlock(
4243             LI->getLoopFor(LoopVectorBody)->getLoopLatch(), Sel);
4244       }
4245     }
4246   }
4247 
4248   // If the vector reduction can be performed in a smaller type, we truncate
4249   // then extend the loop exit value to enable InstCombine to evaluate the
4250   // entire expression in the smaller type.
4251   if (VF.isVector() && PhiTy != RdxDesc.getRecurrenceType()) {
4252     assert(!PhiR->isInLoop() && "Unexpected truncated inloop reduction!");
4253     Type *RdxVecTy = VectorType::get(RdxDesc.getRecurrenceType(), VF);
4254     Builder.SetInsertPoint(
4255         LI->getLoopFor(LoopVectorBody)->getLoopLatch()->getTerminator());
4256     VectorParts RdxParts(UF);
4257     for (unsigned Part = 0; Part < UF; ++Part) {
4258       RdxParts[Part] = State.get(LoopExitInstDef, Part);
4259       Value *Trunc = Builder.CreateTrunc(RdxParts[Part], RdxVecTy);
4260       Value *Extnd = RdxDesc.isSigned() ? Builder.CreateSExt(Trunc, VecTy)
4261                                         : Builder.CreateZExt(Trunc, VecTy);
4262       for (User *U : llvm::make_early_inc_range(RdxParts[Part]->users()))
4263         if (U != Trunc) {
4264           U->replaceUsesOfWith(RdxParts[Part], Extnd);
4265           RdxParts[Part] = Extnd;
4266         }
4267     }
4268     Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
4269     for (unsigned Part = 0; Part < UF; ++Part) {
4270       RdxParts[Part] = Builder.CreateTrunc(RdxParts[Part], RdxVecTy);
4271       State.reset(LoopExitInstDef, RdxParts[Part], Part);
4272     }
4273   }
4274 
4275   // Reduce all of the unrolled parts into a single vector.
4276   Value *ReducedPartRdx = State.get(LoopExitInstDef, 0);
4277   unsigned Op = RecurrenceDescriptor::getOpcode(RK);
4278 
4279   // The middle block terminator has already been assigned a DebugLoc here (the
4280   // OrigLoop's single latch terminator). We want the whole middle block to
4281   // appear to execute on this line because: (a) it is all compiler generated,
4282   // (b) these instructions are always executed after evaluating the latch
4283   // conditional branch, and (c) other passes may add new predecessors which
4284   // terminate on this line. This is the easiest way to ensure we don't
4285   // accidentally cause an extra step back into the loop while debugging.
4286   setDebugLocFromInst(LoopMiddleBlock->getTerminator());
4287   if (PhiR->isOrdered())
4288     ReducedPartRdx = State.get(LoopExitInstDef, UF - 1);
4289   else {
4290     // Floating-point operations should have some FMF to enable the reduction.
4291     IRBuilderBase::FastMathFlagGuard FMFG(Builder);
4292     Builder.setFastMathFlags(RdxDesc.getFastMathFlags());
4293     for (unsigned Part = 1; Part < UF; ++Part) {
4294       Value *RdxPart = State.get(LoopExitInstDef, Part);
4295       if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
4296         ReducedPartRdx = Builder.CreateBinOp(
4297             (Instruction::BinaryOps)Op, RdxPart, ReducedPartRdx, "bin.rdx");
4298       } else if (RecurrenceDescriptor::isSelectCmpRecurrenceKind(RK))
4299         ReducedPartRdx = createSelectCmpOp(Builder, ReductionStartValue, RK,
4300                                            ReducedPartRdx, RdxPart);
4301       else
4302         ReducedPartRdx = createMinMaxOp(Builder, RK, ReducedPartRdx, RdxPart);
4303     }
4304   }
4305 
4306   // Create the reduction after the loop. Note that inloop reductions create the
4307   // target reduction in the loop using a Reduction recipe.
4308   if (VF.isVector() && !PhiR->isInLoop()) {
4309     ReducedPartRdx =
4310         createTargetReduction(Builder, TTI, RdxDesc, ReducedPartRdx, OrigPhi);
4311     // If the reduction can be performed in a smaller type, we need to extend
4312     // the reduction to the wider type before we branch to the original loop.
4313     if (PhiTy != RdxDesc.getRecurrenceType())
4314       ReducedPartRdx = RdxDesc.isSigned()
4315                            ? Builder.CreateSExt(ReducedPartRdx, PhiTy)
4316                            : Builder.CreateZExt(ReducedPartRdx, PhiTy);
4317   }
4318 
4319   // Create a phi node that merges control-flow from the backedge-taken check
4320   // block and the middle block.
4321   PHINode *BCBlockPhi = PHINode::Create(PhiTy, 2, "bc.merge.rdx",
4322                                         LoopScalarPreHeader->getTerminator());
4323   for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
4324     BCBlockPhi->addIncoming(ReductionStartValue, LoopBypassBlocks[I]);
4325   BCBlockPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
4326 
4327   // Now, we need to fix the users of the reduction variable
4328   // inside and outside of the scalar remainder loop.
4329 
4330   // We know that the loop is in LCSSA form. We need to update the PHI nodes
4331   // in the exit blocks.  See comment on analogous loop in
4332   // fixFirstOrderRecurrence for a more complete explaination of the logic.
4333   if (!Cost->requiresScalarEpilogue(VF))
4334     for (PHINode &LCSSAPhi : LoopExitBlock->phis())
4335       if (llvm::is_contained(LCSSAPhi.incoming_values(), LoopExitInst))
4336         LCSSAPhi.addIncoming(ReducedPartRdx, LoopMiddleBlock);
4337 
4338   // Fix the scalar loop reduction variable with the incoming reduction sum
4339   // from the vector body and from the backedge value.
4340   int IncomingEdgeBlockIdx =
4341       OrigPhi->getBasicBlockIndex(OrigLoop->getLoopLatch());
4342   assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
4343   // Pick the other block.
4344   int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
4345   OrigPhi->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi);
4346   OrigPhi->setIncomingValue(IncomingEdgeBlockIdx, LoopExitInst);
4347 }
4348 
4349 void InnerLoopVectorizer::clearReductionWrapFlags(const RecurrenceDescriptor &RdxDesc,
4350                                                   VPTransformState &State) {
4351   RecurKind RK = RdxDesc.getRecurrenceKind();
4352   if (RK != RecurKind::Add && RK != RecurKind::Mul)
4353     return;
4354 
4355   Instruction *LoopExitInstr = RdxDesc.getLoopExitInstr();
4356   assert(LoopExitInstr && "null loop exit instruction");
4357   SmallVector<Instruction *, 8> Worklist;
4358   SmallPtrSet<Instruction *, 8> Visited;
4359   Worklist.push_back(LoopExitInstr);
4360   Visited.insert(LoopExitInstr);
4361 
4362   while (!Worklist.empty()) {
4363     Instruction *Cur = Worklist.pop_back_val();
4364     if (isa<OverflowingBinaryOperator>(Cur))
4365       for (unsigned Part = 0; Part < UF; ++Part) {
4366         // FIXME: Should not rely on getVPValue at this point.
4367         Value *V = State.get(State.Plan->getVPValue(Cur, true), Part);
4368         cast<Instruction>(V)->dropPoisonGeneratingFlags();
4369       }
4370 
4371     for (User *U : Cur->users()) {
4372       Instruction *UI = cast<Instruction>(U);
4373       if ((Cur != LoopExitInstr || OrigLoop->contains(UI->getParent())) &&
4374           Visited.insert(UI).second)
4375         Worklist.push_back(UI);
4376     }
4377   }
4378 }
4379 
4380 void InnerLoopVectorizer::fixLCSSAPHIs(VPTransformState &State) {
4381   for (PHINode &LCSSAPhi : LoopExitBlock->phis()) {
4382     if (LCSSAPhi.getBasicBlockIndex(LoopMiddleBlock) != -1)
4383       // Some phis were already hand updated by the reduction and recurrence
4384       // code above, leave them alone.
4385       continue;
4386 
4387     auto *IncomingValue = LCSSAPhi.getIncomingValue(0);
4388     // Non-instruction incoming values will have only one value.
4389 
4390     VPLane Lane = VPLane::getFirstLane();
4391     if (isa<Instruction>(IncomingValue) &&
4392         !Cost->isUniformAfterVectorization(cast<Instruction>(IncomingValue),
4393                                            VF))
4394       Lane = VPLane::getLastLaneForVF(VF);
4395 
4396     // Can be a loop invariant incoming value or the last scalar value to be
4397     // extracted from the vectorized loop.
4398     // FIXME: Should not rely on getVPValue at this point.
4399     Builder.SetInsertPoint(LoopMiddleBlock->getTerminator());
4400     Value *lastIncomingValue =
4401         OrigLoop->isLoopInvariant(IncomingValue)
4402             ? IncomingValue
4403             : State.get(State.Plan->getVPValue(IncomingValue, true),
4404                         VPIteration(UF - 1, Lane));
4405     LCSSAPhi.addIncoming(lastIncomingValue, LoopMiddleBlock);
4406   }
4407 }
4408 
4409 void InnerLoopVectorizer::sinkScalarOperands(Instruction *PredInst) {
4410   // The basic block and loop containing the predicated instruction.
4411   auto *PredBB = PredInst->getParent();
4412   auto *VectorLoop = LI->getLoopFor(PredBB);
4413 
4414   // Initialize a worklist with the operands of the predicated instruction.
4415   SetVector<Value *> Worklist(PredInst->op_begin(), PredInst->op_end());
4416 
4417   // Holds instructions that we need to analyze again. An instruction may be
4418   // reanalyzed if we don't yet know if we can sink it or not.
4419   SmallVector<Instruction *, 8> InstsToReanalyze;
4420 
4421   // Returns true if a given use occurs in the predicated block. Phi nodes use
4422   // their operands in their corresponding predecessor blocks.
4423   auto isBlockOfUsePredicated = [&](Use &U) -> bool {
4424     auto *I = cast<Instruction>(U.getUser());
4425     BasicBlock *BB = I->getParent();
4426     if (auto *Phi = dyn_cast<PHINode>(I))
4427       BB = Phi->getIncomingBlock(
4428           PHINode::getIncomingValueNumForOperand(U.getOperandNo()));
4429     return BB == PredBB;
4430   };
4431 
4432   // Iteratively sink the scalarized operands of the predicated instruction
4433   // into the block we created for it. When an instruction is sunk, it's
4434   // operands are then added to the worklist. The algorithm ends after one pass
4435   // through the worklist doesn't sink a single instruction.
4436   bool Changed;
4437   do {
4438     // Add the instructions that need to be reanalyzed to the worklist, and
4439     // reset the changed indicator.
4440     Worklist.insert(InstsToReanalyze.begin(), InstsToReanalyze.end());
4441     InstsToReanalyze.clear();
4442     Changed = false;
4443 
4444     while (!Worklist.empty()) {
4445       auto *I = dyn_cast<Instruction>(Worklist.pop_back_val());
4446 
4447       // We can't sink an instruction if it is a phi node, is not in the loop,
4448       // or may have side effects.
4449       if (!I || isa<PHINode>(I) || !VectorLoop->contains(I) ||
4450           I->mayHaveSideEffects())
4451         continue;
4452 
4453       // If the instruction is already in PredBB, check if we can sink its
4454       // operands. In that case, VPlan's sinkScalarOperands() succeeded in
4455       // sinking the scalar instruction I, hence it appears in PredBB; but it
4456       // may have failed to sink I's operands (recursively), which we try
4457       // (again) here.
4458       if (I->getParent() == PredBB) {
4459         Worklist.insert(I->op_begin(), I->op_end());
4460         continue;
4461       }
4462 
4463       // It's legal to sink the instruction if all its uses occur in the
4464       // predicated block. Otherwise, there's nothing to do yet, and we may
4465       // need to reanalyze the instruction.
4466       if (!llvm::all_of(I->uses(), isBlockOfUsePredicated)) {
4467         InstsToReanalyze.push_back(I);
4468         continue;
4469       }
4470 
4471       // Move the instruction to the beginning of the predicated block, and add
4472       // it's operands to the worklist.
4473       I->moveBefore(&*PredBB->getFirstInsertionPt());
4474       Worklist.insert(I->op_begin(), I->op_end());
4475 
4476       // The sinking may have enabled other instructions to be sunk, so we will
4477       // need to iterate.
4478       Changed = true;
4479     }
4480   } while (Changed);
4481 }
4482 
4483 void InnerLoopVectorizer::fixNonInductionPHIs(VPTransformState &State) {
4484   for (PHINode *OrigPhi : OrigPHIsToFix) {
4485     VPWidenPHIRecipe *VPPhi =
4486         cast<VPWidenPHIRecipe>(State.Plan->getVPValue(OrigPhi));
4487     PHINode *NewPhi = cast<PHINode>(State.get(VPPhi, 0));
4488     // Make sure the builder has a valid insert point.
4489     Builder.SetInsertPoint(NewPhi);
4490     for (unsigned i = 0; i < VPPhi->getNumOperands(); ++i) {
4491       VPValue *Inc = VPPhi->getIncomingValue(i);
4492       VPBasicBlock *VPBB = VPPhi->getIncomingBlock(i);
4493       NewPhi->addIncoming(State.get(Inc, 0), State.CFG.VPBB2IRBB[VPBB]);
4494     }
4495   }
4496 }
4497 
4498 bool InnerLoopVectorizer::useOrderedReductions(
4499     const RecurrenceDescriptor &RdxDesc) {
4500   return Cost->useOrderedReductions(RdxDesc);
4501 }
4502 
4503 void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN,
4504                                               VPWidenPHIRecipe *PhiR,
4505                                               VPTransformState &State) {
4506   PHINode *P = cast<PHINode>(PN);
4507   if (EnableVPlanNativePath) {
4508     // Currently we enter here in the VPlan-native path for non-induction
4509     // PHIs where all control flow is uniform. We simply widen these PHIs.
4510     // Create a vector phi with no operands - the vector phi operands will be
4511     // set at the end of vector code generation.
4512     Type *VecTy = (State.VF.isScalar())
4513                       ? PN->getType()
4514                       : VectorType::get(PN->getType(), State.VF);
4515     Value *VecPhi = Builder.CreatePHI(VecTy, PN->getNumOperands(), "vec.phi");
4516     State.set(PhiR, VecPhi, 0);
4517     OrigPHIsToFix.push_back(P);
4518 
4519     return;
4520   }
4521 
4522   assert(PN->getParent() == OrigLoop->getHeader() &&
4523          "Non-header phis should have been handled elsewhere");
4524 
4525   // In order to support recurrences we need to be able to vectorize Phi nodes.
4526   // Phi nodes have cycles, so we need to vectorize them in two stages. This is
4527   // stage #1: We create a new vector PHI node with no incoming edges. We'll use
4528   // this value when we vectorize all of the instructions that use the PHI.
4529 
4530   assert(!Legal->isReductionVariable(P) &&
4531          "reductions should be handled elsewhere");
4532 
4533   setDebugLocFromInst(P);
4534 
4535   // This PHINode must be an induction variable.
4536   // Make sure that we know about it.
4537   assert(Legal->getInductionVars().count(P) && "Not an induction variable");
4538 
4539   InductionDescriptor II = Legal->getInductionVars().lookup(P);
4540   const DataLayout &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
4541 
4542   // FIXME: The newly created binary instructions should contain nsw/nuw flags,
4543   // which can be found from the original scalar operations.
4544   switch (II.getKind()) {
4545   case InductionDescriptor::IK_NoInduction:
4546     llvm_unreachable("Unknown induction");
4547   case InductionDescriptor::IK_IntInduction:
4548   case InductionDescriptor::IK_FpInduction:
4549     llvm_unreachable("Integer/fp induction is handled elsewhere.");
4550   case InductionDescriptor::IK_PtrInduction: {
4551     // Handle the pointer induction variable case.
4552     assert(P->getType()->isPointerTy() && "Unexpected type.");
4553 
4554     if (Cost->isScalarAfterVectorization(P, State.VF)) {
4555       // This is the normalized GEP that starts counting at zero.
4556       Value *PtrInd =
4557           Builder.CreateSExtOrTrunc(Induction, II.getStep()->getType());
4558       // Determine the number of scalars we need to generate for each unroll
4559       // iteration. If the instruction is uniform, we only need to generate the
4560       // first lane. Otherwise, we generate all VF values.
4561       bool IsUniform = Cost->isUniformAfterVectorization(P, State.VF);
4562       assert((IsUniform || !State.VF.isScalable()) &&
4563              "Cannot scalarize a scalable VF");
4564       unsigned Lanes = IsUniform ? 1 : State.VF.getFixedValue();
4565 
4566       for (unsigned Part = 0; Part < UF; ++Part) {
4567         Value *PartStart =
4568             createStepForVF(Builder, PtrInd->getType(), VF, Part);
4569 
4570         for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
4571           Value *Idx = Builder.CreateAdd(
4572               PartStart, ConstantInt::get(PtrInd->getType(), Lane));
4573           Value *GlobalIdx = Builder.CreateAdd(PtrInd, Idx);
4574           Value *SclrGep = emitTransformedIndex(Builder, GlobalIdx, PSE.getSE(),
4575                                                 DL, II, State.CFG.PrevBB);
4576           SclrGep->setName("next.gep");
4577           State.set(PhiR, SclrGep, VPIteration(Part, Lane));
4578         }
4579       }
4580       return;
4581     }
4582     assert(isa<SCEVConstant>(II.getStep()) &&
4583            "Induction step not a SCEV constant!");
4584     Type *PhiType = II.getStep()->getType();
4585 
4586     // Build a pointer phi
4587     Value *ScalarStartValue = PhiR->getStartValue()->getLiveInIRValue();
4588     Type *ScStValueType = ScalarStartValue->getType();
4589     PHINode *NewPointerPhi =
4590         PHINode::Create(ScStValueType, 2, "pointer.phi", Induction);
4591     NewPointerPhi->addIncoming(ScalarStartValue, LoopVectorPreHeader);
4592 
4593     // A pointer induction, performed by using a gep
4594     BasicBlock *LoopLatch = LI->getLoopFor(LoopVectorBody)->getLoopLatch();
4595     Instruction *InductionLoc = LoopLatch->getTerminator();
4596     const SCEV *ScalarStep = II.getStep();
4597     SCEVExpander Exp(*PSE.getSE(), DL, "induction");
4598     Value *ScalarStepValue =
4599         Exp.expandCodeFor(ScalarStep, PhiType, InductionLoc);
4600     Value *RuntimeVF = getRuntimeVF(Builder, PhiType, VF);
4601     Value *NumUnrolledElems =
4602         Builder.CreateMul(RuntimeVF, ConstantInt::get(PhiType, State.UF));
4603     Value *InductionGEP = GetElementPtrInst::Create(
4604         II.getElementType(), NewPointerPhi,
4605         Builder.CreateMul(ScalarStepValue, NumUnrolledElems), "ptr.ind",
4606         InductionLoc);
4607     NewPointerPhi->addIncoming(InductionGEP, LoopLatch);
4608 
4609     // Create UF many actual address geps that use the pointer
4610     // phi as base and a vectorized version of the step value
4611     // (<step*0, ..., step*N>) as offset.
4612     for (unsigned Part = 0; Part < State.UF; ++Part) {
4613       Type *VecPhiType = VectorType::get(PhiType, State.VF);
4614       Value *StartOffsetScalar =
4615           Builder.CreateMul(RuntimeVF, ConstantInt::get(PhiType, Part));
4616       Value *StartOffset =
4617           Builder.CreateVectorSplat(State.VF, StartOffsetScalar);
4618       // Create a vector of consecutive numbers from zero to VF.
4619       StartOffset =
4620           Builder.CreateAdd(StartOffset, Builder.CreateStepVector(VecPhiType));
4621 
4622       Value *GEP = Builder.CreateGEP(
4623           II.getElementType(), NewPointerPhi,
4624           Builder.CreateMul(
4625               StartOffset, Builder.CreateVectorSplat(State.VF, ScalarStepValue),
4626               "vector.gep"));
4627       State.set(PhiR, GEP, Part);
4628     }
4629   }
4630   }
4631 }
4632 
4633 /// A helper function for checking whether an integer division-related
4634 /// instruction may divide by zero (in which case it must be predicated if
4635 /// executed conditionally in the scalar code).
4636 /// TODO: It may be worthwhile to generalize and check isKnownNonZero().
4637 /// Non-zero divisors that are non compile-time constants will not be
4638 /// converted into multiplication, so we will still end up scalarizing
4639 /// the division, but can do so w/o predication.
4640 static bool mayDivideByZero(Instruction &I) {
4641   assert((I.getOpcode() == Instruction::UDiv ||
4642           I.getOpcode() == Instruction::SDiv ||
4643           I.getOpcode() == Instruction::URem ||
4644           I.getOpcode() == Instruction::SRem) &&
4645          "Unexpected instruction");
4646   Value *Divisor = I.getOperand(1);
4647   auto *CInt = dyn_cast<ConstantInt>(Divisor);
4648   return !CInt || CInt->isZero();
4649 }
4650 
4651 void InnerLoopVectorizer::widenCallInstruction(CallInst &I, VPValue *Def,
4652                                                VPUser &ArgOperands,
4653                                                VPTransformState &State) {
4654   assert(!isa<DbgInfoIntrinsic>(I) &&
4655          "DbgInfoIntrinsic should have been dropped during VPlan construction");
4656   setDebugLocFromInst(&I);
4657 
4658   Module *M = I.getParent()->getParent()->getParent();
4659   auto *CI = cast<CallInst>(&I);
4660 
4661   SmallVector<Type *, 4> Tys;
4662   for (Value *ArgOperand : CI->args())
4663     Tys.push_back(ToVectorTy(ArgOperand->getType(), VF.getKnownMinValue()));
4664 
4665   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4666 
4667   // The flag shows whether we use Intrinsic or a usual Call for vectorized
4668   // version of the instruction.
4669   // Is it beneficial to perform intrinsic call compared to lib call?
4670   bool NeedToScalarize = false;
4671   InstructionCost CallCost = Cost->getVectorCallCost(CI, VF, NeedToScalarize);
4672   InstructionCost IntrinsicCost = ID ? Cost->getVectorIntrinsicCost(CI, VF) : 0;
4673   bool UseVectorIntrinsic = ID && IntrinsicCost <= CallCost;
4674   assert((UseVectorIntrinsic || !NeedToScalarize) &&
4675          "Instruction should be scalarized elsewhere.");
4676   assert((IntrinsicCost.isValid() || CallCost.isValid()) &&
4677          "Either the intrinsic cost or vector call cost must be valid");
4678 
4679   for (unsigned Part = 0; Part < UF; ++Part) {
4680     SmallVector<Type *, 2> TysForDecl = {CI->getType()};
4681     SmallVector<Value *, 4> Args;
4682     for (auto &I : enumerate(ArgOperands.operands())) {
4683       // Some intrinsics have a scalar argument - don't replace it with a
4684       // vector.
4685       Value *Arg;
4686       if (!UseVectorIntrinsic || !hasVectorInstrinsicScalarOpd(ID, I.index()))
4687         Arg = State.get(I.value(), Part);
4688       else {
4689         Arg = State.get(I.value(), VPIteration(0, 0));
4690         if (hasVectorInstrinsicOverloadedScalarOpd(ID, I.index()))
4691           TysForDecl.push_back(Arg->getType());
4692       }
4693       Args.push_back(Arg);
4694     }
4695 
4696     Function *VectorF;
4697     if (UseVectorIntrinsic) {
4698       // Use vector version of the intrinsic.
4699       if (VF.isVector())
4700         TysForDecl[0] = VectorType::get(CI->getType()->getScalarType(), VF);
4701       VectorF = Intrinsic::getDeclaration(M, ID, TysForDecl);
4702       assert(VectorF && "Can't retrieve vector intrinsic.");
4703     } else {
4704       // Use vector version of the function call.
4705       const VFShape Shape = VFShape::get(*CI, VF, false /*HasGlobalPred*/);
4706 #ifndef NDEBUG
4707       assert(VFDatabase(*CI).getVectorizedFunction(Shape) != nullptr &&
4708              "Can't create vector function.");
4709 #endif
4710         VectorF = VFDatabase(*CI).getVectorizedFunction(Shape);
4711     }
4712       SmallVector<OperandBundleDef, 1> OpBundles;
4713       CI->getOperandBundlesAsDefs(OpBundles);
4714       CallInst *V = Builder.CreateCall(VectorF, Args, OpBundles);
4715 
4716       if (isa<FPMathOperator>(V))
4717         V->copyFastMathFlags(CI);
4718 
4719       State.set(Def, V, Part);
4720       addMetadata(V, &I);
4721   }
4722 }
4723 
4724 void LoopVectorizationCostModel::collectLoopScalars(ElementCount VF) {
4725   // We should not collect Scalars more than once per VF. Right now, this
4726   // function is called from collectUniformsAndScalars(), which already does
4727   // this check. Collecting Scalars for VF=1 does not make any sense.
4728   assert(VF.isVector() && Scalars.find(VF) == Scalars.end() &&
4729          "This function should not be visited twice for the same VF");
4730 
4731   SmallSetVector<Instruction *, 8> Worklist;
4732 
4733   // These sets are used to seed the analysis with pointers used by memory
4734   // accesses that will remain scalar.
4735   SmallSetVector<Instruction *, 8> ScalarPtrs;
4736   SmallPtrSet<Instruction *, 8> PossibleNonScalarPtrs;
4737   auto *Latch = TheLoop->getLoopLatch();
4738 
4739   // A helper that returns true if the use of Ptr by MemAccess will be scalar.
4740   // The pointer operands of loads and stores will be scalar as long as the
4741   // memory access is not a gather or scatter operation. The value operand of a
4742   // store will remain scalar if the store is scalarized.
4743   auto isScalarUse = [&](Instruction *MemAccess, Value *Ptr) {
4744     InstWidening WideningDecision = getWideningDecision(MemAccess, VF);
4745     assert(WideningDecision != CM_Unknown &&
4746            "Widening decision should be ready at this moment");
4747     if (auto *Store = dyn_cast<StoreInst>(MemAccess))
4748       if (Ptr == Store->getValueOperand())
4749         return WideningDecision == CM_Scalarize;
4750     assert(Ptr == getLoadStorePointerOperand(MemAccess) &&
4751            "Ptr is neither a value or pointer operand");
4752     return WideningDecision != CM_GatherScatter;
4753   };
4754 
4755   // A helper that returns true if the given value is a bitcast or
4756   // getelementptr instruction contained in the loop.
4757   auto isLoopVaryingBitCastOrGEP = [&](Value *V) {
4758     return ((isa<BitCastInst>(V) && V->getType()->isPointerTy()) ||
4759             isa<GetElementPtrInst>(V)) &&
4760            !TheLoop->isLoopInvariant(V);
4761   };
4762 
4763   // A helper that evaluates a memory access's use of a pointer. If the use will
4764   // be a scalar use and the pointer is only used by memory accesses, we place
4765   // the pointer in ScalarPtrs. Otherwise, the pointer is placed in
4766   // PossibleNonScalarPtrs.
4767   auto evaluatePtrUse = [&](Instruction *MemAccess, Value *Ptr) {
4768     // We only care about bitcast and getelementptr instructions contained in
4769     // the loop.
4770     if (!isLoopVaryingBitCastOrGEP(Ptr))
4771       return;
4772 
4773     // If the pointer has already been identified as scalar (e.g., if it was
4774     // also identified as uniform), there's nothing to do.
4775     auto *I = cast<Instruction>(Ptr);
4776     if (Worklist.count(I))
4777       return;
4778 
4779     // If the use of the pointer will be a scalar use, and all users of the
4780     // pointer are memory accesses, place the pointer in ScalarPtrs. Otherwise,
4781     // place the pointer in PossibleNonScalarPtrs.
4782     if (isScalarUse(MemAccess, Ptr) && llvm::all_of(I->users(), [&](User *U) {
4783           return isa<LoadInst>(U) || isa<StoreInst>(U);
4784         }))
4785       ScalarPtrs.insert(I);
4786     else
4787       PossibleNonScalarPtrs.insert(I);
4788   };
4789 
4790   // We seed the scalars analysis with three classes of instructions: (1)
4791   // instructions marked uniform-after-vectorization and (2) bitcast,
4792   // getelementptr and (pointer) phi instructions used by memory accesses
4793   // requiring a scalar use.
4794   //
4795   // (1) Add to the worklist all instructions that have been identified as
4796   // uniform-after-vectorization.
4797   Worklist.insert(Uniforms[VF].begin(), Uniforms[VF].end());
4798 
4799   // (2) Add to the worklist all bitcast and getelementptr instructions used by
4800   // memory accesses requiring a scalar use. The pointer operands of loads and
4801   // stores will be scalar as long as the memory accesses is not a gather or
4802   // scatter operation. The value operand of a store will remain scalar if the
4803   // store is scalarized.
4804   for (auto *BB : TheLoop->blocks())
4805     for (auto &I : *BB) {
4806       if (auto *Load = dyn_cast<LoadInst>(&I)) {
4807         evaluatePtrUse(Load, Load->getPointerOperand());
4808       } else if (auto *Store = dyn_cast<StoreInst>(&I)) {
4809         evaluatePtrUse(Store, Store->getPointerOperand());
4810         evaluatePtrUse(Store, Store->getValueOperand());
4811       }
4812     }
4813   for (auto *I : ScalarPtrs)
4814     if (!PossibleNonScalarPtrs.count(I)) {
4815       LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *I << "\n");
4816       Worklist.insert(I);
4817     }
4818 
4819   // Insert the forced scalars.
4820   // FIXME: Currently widenPHIInstruction() often creates a dead vector
4821   // induction variable when the PHI user is scalarized.
4822   auto ForcedScalar = ForcedScalars.find(VF);
4823   if (ForcedScalar != ForcedScalars.end())
4824     for (auto *I : ForcedScalar->second)
4825       Worklist.insert(I);
4826 
4827   // Expand the worklist by looking through any bitcasts and getelementptr
4828   // instructions we've already identified as scalar. This is similar to the
4829   // expansion step in collectLoopUniforms(); however, here we're only
4830   // expanding to include additional bitcasts and getelementptr instructions.
4831   unsigned Idx = 0;
4832   while (Idx != Worklist.size()) {
4833     Instruction *Dst = Worklist[Idx++];
4834     if (!isLoopVaryingBitCastOrGEP(Dst->getOperand(0)))
4835       continue;
4836     auto *Src = cast<Instruction>(Dst->getOperand(0));
4837     if (llvm::all_of(Src->users(), [&](User *U) -> bool {
4838           auto *J = cast<Instruction>(U);
4839           return !TheLoop->contains(J) || Worklist.count(J) ||
4840                  ((isa<LoadInst>(J) || isa<StoreInst>(J)) &&
4841                   isScalarUse(J, Src));
4842         })) {
4843       Worklist.insert(Src);
4844       LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Src << "\n");
4845     }
4846   }
4847 
4848   // An induction variable will remain scalar if all users of the induction
4849   // variable and induction variable update remain scalar.
4850   for (auto &Induction : Legal->getInductionVars()) {
4851     auto *Ind = Induction.first;
4852     auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
4853 
4854     // If tail-folding is applied, the primary induction variable will be used
4855     // to feed a vector compare.
4856     if (Ind == Legal->getPrimaryInduction() && foldTailByMasking())
4857       continue;
4858 
4859     // Returns true if \p Indvar is a pointer induction that is used directly by
4860     // load/store instruction \p I.
4861     auto IsDirectLoadStoreFromPtrIndvar = [&](Instruction *Indvar,
4862                                               Instruction *I) {
4863       return Induction.second.getKind() ==
4864                  InductionDescriptor::IK_PtrInduction &&
4865              (isa<LoadInst>(I) || isa<StoreInst>(I)) &&
4866              Indvar == getLoadStorePointerOperand(I) && isScalarUse(I, Indvar);
4867     };
4868 
4869     // Determine if all users of the induction variable are scalar after
4870     // vectorization.
4871     auto ScalarInd = llvm::all_of(Ind->users(), [&](User *U) -> bool {
4872       auto *I = cast<Instruction>(U);
4873       return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) ||
4874              IsDirectLoadStoreFromPtrIndvar(Ind, I);
4875     });
4876     if (!ScalarInd)
4877       continue;
4878 
4879     // Determine if all users of the induction variable update instruction are
4880     // scalar after vectorization.
4881     auto ScalarIndUpdate =
4882         llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
4883           auto *I = cast<Instruction>(U);
4884           return I == Ind || !TheLoop->contains(I) || Worklist.count(I) ||
4885                  IsDirectLoadStoreFromPtrIndvar(IndUpdate, I);
4886         });
4887     if (!ScalarIndUpdate)
4888       continue;
4889 
4890     // The induction variable and its update instruction will remain scalar.
4891     Worklist.insert(Ind);
4892     Worklist.insert(IndUpdate);
4893     LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Ind << "\n");
4894     LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *IndUpdate
4895                       << "\n");
4896   }
4897 
4898   Scalars[VF].insert(Worklist.begin(), Worklist.end());
4899 }
4900 
4901 bool LoopVectorizationCostModel::isScalarWithPredication(Instruction *I) const {
4902   if (!blockNeedsPredicationForAnyReason(I->getParent()))
4903     return false;
4904   switch(I->getOpcode()) {
4905   default:
4906     break;
4907   case Instruction::Load:
4908   case Instruction::Store: {
4909     if (!Legal->isMaskRequired(I))
4910       return false;
4911     auto *Ptr = getLoadStorePointerOperand(I);
4912     auto *Ty = getLoadStoreType(I);
4913     const Align Alignment = getLoadStoreAlignment(I);
4914     return isa<LoadInst>(I) ? !(isLegalMaskedLoad(Ty, Ptr, Alignment) ||
4915                                 TTI.isLegalMaskedGather(Ty, Alignment))
4916                             : !(isLegalMaskedStore(Ty, Ptr, Alignment) ||
4917                                 TTI.isLegalMaskedScatter(Ty, Alignment));
4918   }
4919   case Instruction::UDiv:
4920   case Instruction::SDiv:
4921   case Instruction::SRem:
4922   case Instruction::URem:
4923     return mayDivideByZero(*I);
4924   }
4925   return false;
4926 }
4927 
4928 bool LoopVectorizationCostModel::interleavedAccessCanBeWidened(
4929     Instruction *I, ElementCount VF) {
4930   assert(isAccessInterleaved(I) && "Expecting interleaved access.");
4931   assert(getWideningDecision(I, VF) == CM_Unknown &&
4932          "Decision should not be set yet.");
4933   auto *Group = getInterleavedAccessGroup(I);
4934   assert(Group && "Must have a group.");
4935 
4936   // If the instruction's allocated size doesn't equal it's type size, it
4937   // requires padding and will be scalarized.
4938   auto &DL = I->getModule()->getDataLayout();
4939   auto *ScalarTy = getLoadStoreType(I);
4940   if (hasIrregularType(ScalarTy, DL))
4941     return false;
4942 
4943   // Check if masking is required.
4944   // A Group may need masking for one of two reasons: it resides in a block that
4945   // needs predication, or it was decided to use masking to deal with gaps
4946   // (either a gap at the end of a load-access that may result in a speculative
4947   // load, or any gaps in a store-access).
4948   bool PredicatedAccessRequiresMasking =
4949       blockNeedsPredicationForAnyReason(I->getParent()) &&
4950       Legal->isMaskRequired(I);
4951   bool LoadAccessWithGapsRequiresEpilogMasking =
4952       isa<LoadInst>(I) && Group->requiresScalarEpilogue() &&
4953       !isScalarEpilogueAllowed();
4954   bool StoreAccessWithGapsRequiresMasking =
4955       isa<StoreInst>(I) && (Group->getNumMembers() < Group->getFactor());
4956   if (!PredicatedAccessRequiresMasking &&
4957       !LoadAccessWithGapsRequiresEpilogMasking &&
4958       !StoreAccessWithGapsRequiresMasking)
4959     return true;
4960 
4961   // If masked interleaving is required, we expect that the user/target had
4962   // enabled it, because otherwise it either wouldn't have been created or
4963   // it should have been invalidated by the CostModel.
4964   assert(useMaskedInterleavedAccesses(TTI) &&
4965          "Masked interleave-groups for predicated accesses are not enabled.");
4966 
4967   if (Group->isReverse())
4968     return false;
4969 
4970   auto *Ty = getLoadStoreType(I);
4971   const Align Alignment = getLoadStoreAlignment(I);
4972   return isa<LoadInst>(I) ? TTI.isLegalMaskedLoad(Ty, Alignment)
4973                           : TTI.isLegalMaskedStore(Ty, Alignment);
4974 }
4975 
4976 bool LoopVectorizationCostModel::memoryInstructionCanBeWidened(
4977     Instruction *I, ElementCount VF) {
4978   // Get and ensure we have a valid memory instruction.
4979   assert((isa<LoadInst, StoreInst>(I)) && "Invalid memory instruction");
4980 
4981   auto *Ptr = getLoadStorePointerOperand(I);
4982   auto *ScalarTy = getLoadStoreType(I);
4983 
4984   // In order to be widened, the pointer should be consecutive, first of all.
4985   if (!Legal->isConsecutivePtr(ScalarTy, Ptr))
4986     return false;
4987 
4988   // If the instruction is a store located in a predicated block, it will be
4989   // scalarized.
4990   if (isScalarWithPredication(I))
4991     return false;
4992 
4993   // If the instruction's allocated size doesn't equal it's type size, it
4994   // requires padding and will be scalarized.
4995   auto &DL = I->getModule()->getDataLayout();
4996   if (hasIrregularType(ScalarTy, DL))
4997     return false;
4998 
4999   return true;
5000 }
5001 
5002 void LoopVectorizationCostModel::collectLoopUniforms(ElementCount VF) {
5003   // We should not collect Uniforms more than once per VF. Right now,
5004   // this function is called from collectUniformsAndScalars(), which
5005   // already does this check. Collecting Uniforms for VF=1 does not make any
5006   // sense.
5007 
5008   assert(VF.isVector() && Uniforms.find(VF) == Uniforms.end() &&
5009          "This function should not be visited twice for the same VF");
5010 
5011   // Visit the list of Uniforms. If we'll not find any uniform value, we'll
5012   // not analyze again.  Uniforms.count(VF) will return 1.
5013   Uniforms[VF].clear();
5014 
5015   // We now know that the loop is vectorizable!
5016   // Collect instructions inside the loop that will remain uniform after
5017   // vectorization.
5018 
5019   // Global values, params and instructions outside of current loop are out of
5020   // scope.
5021   auto isOutOfScope = [&](Value *V) -> bool {
5022     Instruction *I = dyn_cast<Instruction>(V);
5023     return (!I || !TheLoop->contains(I));
5024   };
5025 
5026   // Worklist containing uniform instructions demanding lane 0.
5027   SetVector<Instruction *> Worklist;
5028   BasicBlock *Latch = TheLoop->getLoopLatch();
5029 
5030   // Add uniform instructions demanding lane 0 to the worklist. Instructions
5031   // that are scalar with predication must not be considered uniform after
5032   // vectorization, because that would create an erroneous replicating region
5033   // where only a single instance out of VF should be formed.
5034   // TODO: optimize such seldom cases if found important, see PR40816.
5035   auto addToWorklistIfAllowed = [&](Instruction *I) -> void {
5036     if (isOutOfScope(I)) {
5037       LLVM_DEBUG(dbgs() << "LV: Found not uniform due to scope: "
5038                         << *I << "\n");
5039       return;
5040     }
5041     if (isScalarWithPredication(I)) {
5042       LLVM_DEBUG(dbgs() << "LV: Found not uniform being ScalarWithPredication: "
5043                         << *I << "\n");
5044       return;
5045     }
5046     LLVM_DEBUG(dbgs() << "LV: Found uniform instruction: " << *I << "\n");
5047     Worklist.insert(I);
5048   };
5049 
5050   // Start with the conditional branch. If the branch condition is an
5051   // instruction contained in the loop that is only used by the branch, it is
5052   // uniform.
5053   auto *Cmp = dyn_cast<Instruction>(Latch->getTerminator()->getOperand(0));
5054   if (Cmp && TheLoop->contains(Cmp) && Cmp->hasOneUse())
5055     addToWorklistIfAllowed(Cmp);
5056 
5057   auto isUniformDecision = [&](Instruction *I, ElementCount VF) {
5058     InstWidening WideningDecision = getWideningDecision(I, VF);
5059     assert(WideningDecision != CM_Unknown &&
5060            "Widening decision should be ready at this moment");
5061 
5062     // A uniform memory op is itself uniform.  We exclude uniform stores
5063     // here as they demand the last lane, not the first one.
5064     if (isa<LoadInst>(I) && Legal->isUniformMemOp(*I)) {
5065       assert(WideningDecision == CM_Scalarize);
5066       return true;
5067     }
5068 
5069     return (WideningDecision == CM_Widen ||
5070             WideningDecision == CM_Widen_Reverse ||
5071             WideningDecision == CM_Interleave);
5072   };
5073 
5074 
5075   // Returns true if Ptr is the pointer operand of a memory access instruction
5076   // I, and I is known to not require scalarization.
5077   auto isVectorizedMemAccessUse = [&](Instruction *I, Value *Ptr) -> bool {
5078     return getLoadStorePointerOperand(I) == Ptr && isUniformDecision(I, VF);
5079   };
5080 
5081   // Holds a list of values which are known to have at least one uniform use.
5082   // Note that there may be other uses which aren't uniform.  A "uniform use"
5083   // here is something which only demands lane 0 of the unrolled iterations;
5084   // it does not imply that all lanes produce the same value (e.g. this is not
5085   // the usual meaning of uniform)
5086   SetVector<Value *> HasUniformUse;
5087 
5088   // Scan the loop for instructions which are either a) known to have only
5089   // lane 0 demanded or b) are uses which demand only lane 0 of their operand.
5090   for (auto *BB : TheLoop->blocks())
5091     for (auto &I : *BB) {
5092       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I)) {
5093         switch (II->getIntrinsicID()) {
5094         case Intrinsic::sideeffect:
5095         case Intrinsic::experimental_noalias_scope_decl:
5096         case Intrinsic::assume:
5097         case Intrinsic::lifetime_start:
5098         case Intrinsic::lifetime_end:
5099           if (TheLoop->hasLoopInvariantOperands(&I))
5100             addToWorklistIfAllowed(&I);
5101           break;
5102         default:
5103           break;
5104         }
5105       }
5106 
5107       // ExtractValue instructions must be uniform, because the operands are
5108       // known to be loop-invariant.
5109       if (auto *EVI = dyn_cast<ExtractValueInst>(&I)) {
5110         assert(isOutOfScope(EVI->getAggregateOperand()) &&
5111                "Expected aggregate value to be loop invariant");
5112         addToWorklistIfAllowed(EVI);
5113         continue;
5114       }
5115 
5116       // If there's no pointer operand, there's nothing to do.
5117       auto *Ptr = getLoadStorePointerOperand(&I);
5118       if (!Ptr)
5119         continue;
5120 
5121       // A uniform memory op is itself uniform.  We exclude uniform stores
5122       // here as they demand the last lane, not the first one.
5123       if (isa<LoadInst>(I) && Legal->isUniformMemOp(I))
5124         addToWorklistIfAllowed(&I);
5125 
5126       if (isUniformDecision(&I, VF)) {
5127         assert(isVectorizedMemAccessUse(&I, Ptr) && "consistency check");
5128         HasUniformUse.insert(Ptr);
5129       }
5130     }
5131 
5132   // Add to the worklist any operands which have *only* uniform (e.g. lane 0
5133   // demanding) users.  Since loops are assumed to be in LCSSA form, this
5134   // disallows uses outside the loop as well.
5135   for (auto *V : HasUniformUse) {
5136     if (isOutOfScope(V))
5137       continue;
5138     auto *I = cast<Instruction>(V);
5139     auto UsersAreMemAccesses =
5140       llvm::all_of(I->users(), [&](User *U) -> bool {
5141         return isVectorizedMemAccessUse(cast<Instruction>(U), V);
5142       });
5143     if (UsersAreMemAccesses)
5144       addToWorklistIfAllowed(I);
5145   }
5146 
5147   // Expand Worklist in topological order: whenever a new instruction
5148   // is added , its users should be already inside Worklist.  It ensures
5149   // a uniform instruction will only be used by uniform instructions.
5150   unsigned idx = 0;
5151   while (idx != Worklist.size()) {
5152     Instruction *I = Worklist[idx++];
5153 
5154     for (auto OV : I->operand_values()) {
5155       // isOutOfScope operands cannot be uniform instructions.
5156       if (isOutOfScope(OV))
5157         continue;
5158       // First order recurrence Phi's should typically be considered
5159       // non-uniform.
5160       auto *OP = dyn_cast<PHINode>(OV);
5161       if (OP && Legal->isFirstOrderRecurrence(OP))
5162         continue;
5163       // If all the users of the operand are uniform, then add the
5164       // operand into the uniform worklist.
5165       auto *OI = cast<Instruction>(OV);
5166       if (llvm::all_of(OI->users(), [&](User *U) -> bool {
5167             auto *J = cast<Instruction>(U);
5168             return Worklist.count(J) || isVectorizedMemAccessUse(J, OI);
5169           }))
5170         addToWorklistIfAllowed(OI);
5171     }
5172   }
5173 
5174   // For an instruction to be added into Worklist above, all its users inside
5175   // the loop should also be in Worklist. However, this condition cannot be
5176   // true for phi nodes that form a cyclic dependence. We must process phi
5177   // nodes separately. An induction variable will remain uniform if all users
5178   // of the induction variable and induction variable update remain uniform.
5179   // The code below handles both pointer and non-pointer induction variables.
5180   for (auto &Induction : Legal->getInductionVars()) {
5181     auto *Ind = Induction.first;
5182     auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
5183 
5184     // Determine if all users of the induction variable are uniform after
5185     // vectorization.
5186     auto UniformInd = llvm::all_of(Ind->users(), [&](User *U) -> bool {
5187       auto *I = cast<Instruction>(U);
5188       return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) ||
5189              isVectorizedMemAccessUse(I, Ind);
5190     });
5191     if (!UniformInd)
5192       continue;
5193 
5194     // Determine if all users of the induction variable update instruction are
5195     // uniform after vectorization.
5196     auto UniformIndUpdate =
5197         llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
5198           auto *I = cast<Instruction>(U);
5199           return I == Ind || !TheLoop->contains(I) || Worklist.count(I) ||
5200                  isVectorizedMemAccessUse(I, IndUpdate);
5201         });
5202     if (!UniformIndUpdate)
5203       continue;
5204 
5205     // The induction variable and its update instruction will remain uniform.
5206     addToWorklistIfAllowed(Ind);
5207     addToWorklistIfAllowed(IndUpdate);
5208   }
5209 
5210   Uniforms[VF].insert(Worklist.begin(), Worklist.end());
5211 }
5212 
5213 bool LoopVectorizationCostModel::runtimeChecksRequired() {
5214   LLVM_DEBUG(dbgs() << "LV: Performing code size checks.\n");
5215 
5216   if (Legal->getRuntimePointerChecking()->Need) {
5217     reportVectorizationFailure("Runtime ptr check is required with -Os/-Oz",
5218         "runtime pointer checks needed. Enable vectorization of this "
5219         "loop with '#pragma clang loop vectorize(enable)' when "
5220         "compiling with -Os/-Oz",
5221         "CantVersionLoopWithOptForSize", ORE, TheLoop);
5222     return true;
5223   }
5224 
5225   if (!PSE.getUnionPredicate().getPredicates().empty()) {
5226     reportVectorizationFailure("Runtime SCEV check is required with -Os/-Oz",
5227         "runtime SCEV checks needed. Enable vectorization of this "
5228         "loop with '#pragma clang loop vectorize(enable)' when "
5229         "compiling with -Os/-Oz",
5230         "CantVersionLoopWithOptForSize", ORE, TheLoop);
5231     return true;
5232   }
5233 
5234   // FIXME: Avoid specializing for stride==1 instead of bailing out.
5235   if (!Legal->getLAI()->getSymbolicStrides().empty()) {
5236     reportVectorizationFailure("Runtime stride check for small trip count",
5237         "runtime stride == 1 checks needed. Enable vectorization of "
5238         "this loop without such check by compiling with -Os/-Oz",
5239         "CantVersionLoopWithOptForSize", ORE, TheLoop);
5240     return true;
5241   }
5242 
5243   return false;
5244 }
5245 
5246 ElementCount
5247 LoopVectorizationCostModel::getMaxLegalScalableVF(unsigned MaxSafeElements) {
5248   if (!TTI.supportsScalableVectors() && !ForceTargetSupportsScalableVectors)
5249     return ElementCount::getScalable(0);
5250 
5251   if (Hints->isScalableVectorizationDisabled()) {
5252     reportVectorizationInfo("Scalable vectorization is explicitly disabled",
5253                             "ScalableVectorizationDisabled", ORE, TheLoop);
5254     return ElementCount::getScalable(0);
5255   }
5256 
5257   LLVM_DEBUG(dbgs() << "LV: Scalable vectorization is available\n");
5258 
5259   auto MaxScalableVF = ElementCount::getScalable(
5260       std::numeric_limits<ElementCount::ScalarTy>::max());
5261 
5262   // Test that the loop-vectorizer can legalize all operations for this MaxVF.
5263   // FIXME: While for scalable vectors this is currently sufficient, this should
5264   // be replaced by a more detailed mechanism that filters out specific VFs,
5265   // instead of invalidating vectorization for a whole set of VFs based on the
5266   // MaxVF.
5267 
5268   // Disable scalable vectorization if the loop contains unsupported reductions.
5269   if (!canVectorizeReductions(MaxScalableVF)) {
5270     reportVectorizationInfo(
5271         "Scalable vectorization not supported for the reduction "
5272         "operations found in this loop.",
5273         "ScalableVFUnfeasible", ORE, TheLoop);
5274     return ElementCount::getScalable(0);
5275   }
5276 
5277   // Disable scalable vectorization if the loop contains any instructions
5278   // with element types not supported for scalable vectors.
5279   if (any_of(ElementTypesInLoop, [&](Type *Ty) {
5280         return !Ty->isVoidTy() &&
5281                !this->TTI.isElementTypeLegalForScalableVector(Ty);
5282       })) {
5283     reportVectorizationInfo("Scalable vectorization is not supported "
5284                             "for all element types found in this loop.",
5285                             "ScalableVFUnfeasible", ORE, TheLoop);
5286     return ElementCount::getScalable(0);
5287   }
5288 
5289   if (Legal->isSafeForAnyVectorWidth())
5290     return MaxScalableVF;
5291 
5292   // Limit MaxScalableVF by the maximum safe dependence distance.
5293   Optional<unsigned> MaxVScale = TTI.getMaxVScale();
5294   if (!MaxVScale && TheFunction->hasFnAttribute(Attribute::VScaleRange))
5295     MaxVScale =
5296         TheFunction->getFnAttribute(Attribute::VScaleRange).getVScaleRangeMax();
5297   MaxScalableVF = ElementCount::getScalable(
5298       MaxVScale ? (MaxSafeElements / MaxVScale.getValue()) : 0);
5299   if (!MaxScalableVF)
5300     reportVectorizationInfo(
5301         "Max legal vector width too small, scalable vectorization "
5302         "unfeasible.",
5303         "ScalableVFUnfeasible", ORE, TheLoop);
5304 
5305   return MaxScalableVF;
5306 }
5307 
5308 FixedScalableVFPair LoopVectorizationCostModel::computeFeasibleMaxVF(
5309     unsigned ConstTripCount, ElementCount UserVF, bool FoldTailByMasking) {
5310   MinBWs = computeMinimumValueSizes(TheLoop->getBlocks(), *DB, &TTI);
5311   unsigned SmallestType, WidestType;
5312   std::tie(SmallestType, WidestType) = getSmallestAndWidestTypes();
5313 
5314   // Get the maximum safe dependence distance in bits computed by LAA.
5315   // It is computed by MaxVF * sizeOf(type) * 8, where type is taken from
5316   // the memory accesses that is most restrictive (involved in the smallest
5317   // dependence distance).
5318   unsigned MaxSafeElements =
5319       PowerOf2Floor(Legal->getMaxSafeVectorWidthInBits() / WidestType);
5320 
5321   auto MaxSafeFixedVF = ElementCount::getFixed(MaxSafeElements);
5322   auto MaxSafeScalableVF = getMaxLegalScalableVF(MaxSafeElements);
5323 
5324   LLVM_DEBUG(dbgs() << "LV: The max safe fixed VF is: " << MaxSafeFixedVF
5325                     << ".\n");
5326   LLVM_DEBUG(dbgs() << "LV: The max safe scalable VF is: " << MaxSafeScalableVF
5327                     << ".\n");
5328 
5329   // First analyze the UserVF, fall back if the UserVF should be ignored.
5330   if (UserVF) {
5331     auto MaxSafeUserVF =
5332         UserVF.isScalable() ? MaxSafeScalableVF : MaxSafeFixedVF;
5333 
5334     if (ElementCount::isKnownLE(UserVF, MaxSafeUserVF)) {
5335       // If `VF=vscale x N` is safe, then so is `VF=N`
5336       if (UserVF.isScalable())
5337         return FixedScalableVFPair(
5338             ElementCount::getFixed(UserVF.getKnownMinValue()), UserVF);
5339       else
5340         return UserVF;
5341     }
5342 
5343     assert(ElementCount::isKnownGT(UserVF, MaxSafeUserVF));
5344 
5345     // Only clamp if the UserVF is not scalable. If the UserVF is scalable, it
5346     // is better to ignore the hint and let the compiler choose a suitable VF.
5347     if (!UserVF.isScalable()) {
5348       LLVM_DEBUG(dbgs() << "LV: User VF=" << UserVF
5349                         << " is unsafe, clamping to max safe VF="
5350                         << MaxSafeFixedVF << ".\n");
5351       ORE->emit([&]() {
5352         return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationFactor",
5353                                           TheLoop->getStartLoc(),
5354                                           TheLoop->getHeader())
5355                << "User-specified vectorization factor "
5356                << ore::NV("UserVectorizationFactor", UserVF)
5357                << " is unsafe, clamping to maximum safe vectorization factor "
5358                << ore::NV("VectorizationFactor", MaxSafeFixedVF);
5359       });
5360       return MaxSafeFixedVF;
5361     }
5362 
5363     if (!TTI.supportsScalableVectors() && !ForceTargetSupportsScalableVectors) {
5364       LLVM_DEBUG(dbgs() << "LV: User VF=" << UserVF
5365                         << " is ignored because scalable vectors are not "
5366                            "available.\n");
5367       ORE->emit([&]() {
5368         return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationFactor",
5369                                           TheLoop->getStartLoc(),
5370                                           TheLoop->getHeader())
5371                << "User-specified vectorization factor "
5372                << ore::NV("UserVectorizationFactor", UserVF)
5373                << " is ignored because the target does not support scalable "
5374                   "vectors. The compiler will pick a more suitable value.";
5375       });
5376     } else {
5377       LLVM_DEBUG(dbgs() << "LV: User VF=" << UserVF
5378                         << " is unsafe. Ignoring scalable UserVF.\n");
5379       ORE->emit([&]() {
5380         return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationFactor",
5381                                           TheLoop->getStartLoc(),
5382                                           TheLoop->getHeader())
5383                << "User-specified vectorization factor "
5384                << ore::NV("UserVectorizationFactor", UserVF)
5385                << " is unsafe. Ignoring the hint to let the compiler pick a "
5386                   "more suitable value.";
5387       });
5388     }
5389   }
5390 
5391   LLVM_DEBUG(dbgs() << "LV: The Smallest and Widest types: " << SmallestType
5392                     << " / " << WidestType << " bits.\n");
5393 
5394   FixedScalableVFPair Result(ElementCount::getFixed(1),
5395                              ElementCount::getScalable(0));
5396   if (auto MaxVF =
5397           getMaximizedVFForTarget(ConstTripCount, SmallestType, WidestType,
5398                                   MaxSafeFixedVF, FoldTailByMasking))
5399     Result.FixedVF = MaxVF;
5400 
5401   if (auto MaxVF =
5402           getMaximizedVFForTarget(ConstTripCount, SmallestType, WidestType,
5403                                   MaxSafeScalableVF, FoldTailByMasking))
5404     if (MaxVF.isScalable()) {
5405       Result.ScalableVF = MaxVF;
5406       LLVM_DEBUG(dbgs() << "LV: Found feasible scalable VF = " << MaxVF
5407                         << "\n");
5408     }
5409 
5410   return Result;
5411 }
5412 
5413 FixedScalableVFPair
5414 LoopVectorizationCostModel::computeMaxVF(ElementCount UserVF, unsigned UserIC) {
5415   if (Legal->getRuntimePointerChecking()->Need && TTI.hasBranchDivergence()) {
5416     // TODO: It may by useful to do since it's still likely to be dynamically
5417     // uniform if the target can skip.
5418     reportVectorizationFailure(
5419         "Not inserting runtime ptr check for divergent target",
5420         "runtime pointer checks needed. Not enabled for divergent target",
5421         "CantVersionLoopWithDivergentTarget", ORE, TheLoop);
5422     return FixedScalableVFPair::getNone();
5423   }
5424 
5425   unsigned TC = PSE.getSE()->getSmallConstantTripCount(TheLoop);
5426   LLVM_DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
5427   if (TC == 1) {
5428     reportVectorizationFailure("Single iteration (non) loop",
5429         "loop trip count is one, irrelevant for vectorization",
5430         "SingleIterationLoop", ORE, TheLoop);
5431     return FixedScalableVFPair::getNone();
5432   }
5433 
5434   switch (ScalarEpilogueStatus) {
5435   case CM_ScalarEpilogueAllowed:
5436     return computeFeasibleMaxVF(TC, UserVF, false);
5437   case CM_ScalarEpilogueNotAllowedUsePredicate:
5438     LLVM_FALLTHROUGH;
5439   case CM_ScalarEpilogueNotNeededUsePredicate:
5440     LLVM_DEBUG(
5441         dbgs() << "LV: vector predicate hint/switch found.\n"
5442                << "LV: Not allowing scalar epilogue, creating predicated "
5443                << "vector loop.\n");
5444     break;
5445   case CM_ScalarEpilogueNotAllowedLowTripLoop:
5446     // fallthrough as a special case of OptForSize
5447   case CM_ScalarEpilogueNotAllowedOptSize:
5448     if (ScalarEpilogueStatus == CM_ScalarEpilogueNotAllowedOptSize)
5449       LLVM_DEBUG(
5450           dbgs() << "LV: Not allowing scalar epilogue due to -Os/-Oz.\n");
5451     else
5452       LLVM_DEBUG(dbgs() << "LV: Not allowing scalar epilogue due to low trip "
5453                         << "count.\n");
5454 
5455     // Bail if runtime checks are required, which are not good when optimising
5456     // for size.
5457     if (runtimeChecksRequired())
5458       return FixedScalableVFPair::getNone();
5459 
5460     break;
5461   }
5462 
5463   // The only loops we can vectorize without a scalar epilogue, are loops with
5464   // a bottom-test and a single exiting block. We'd have to handle the fact
5465   // that not every instruction executes on the last iteration.  This will
5466   // require a lane mask which varies through the vector loop body.  (TODO)
5467   if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
5468     // If there was a tail-folding hint/switch, but we can't fold the tail by
5469     // masking, fallback to a vectorization with a scalar epilogue.
5470     if (ScalarEpilogueStatus == CM_ScalarEpilogueNotNeededUsePredicate) {
5471       LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking: vectorize with a "
5472                            "scalar epilogue instead.\n");
5473       ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
5474       return computeFeasibleMaxVF(TC, UserVF, false);
5475     }
5476     return FixedScalableVFPair::getNone();
5477   }
5478 
5479   // Now try the tail folding
5480 
5481   // Invalidate interleave groups that require an epilogue if we can't mask
5482   // the interleave-group.
5483   if (!useMaskedInterleavedAccesses(TTI)) {
5484     assert(WideningDecisions.empty() && Uniforms.empty() && Scalars.empty() &&
5485            "No decisions should have been taken at this point");
5486     // Note: There is no need to invalidate any cost modeling decisions here, as
5487     // non where taken so far.
5488     InterleaveInfo.invalidateGroupsRequiringScalarEpilogue();
5489   }
5490 
5491   FixedScalableVFPair MaxFactors = computeFeasibleMaxVF(TC, UserVF, true);
5492   // Avoid tail folding if the trip count is known to be a multiple of any VF
5493   // we chose.
5494   // FIXME: The condition below pessimises the case for fixed-width vectors,
5495   // when scalable VFs are also candidates for vectorization.
5496   if (MaxFactors.FixedVF.isVector() && !MaxFactors.ScalableVF) {
5497     ElementCount MaxFixedVF = MaxFactors.FixedVF;
5498     assert((UserVF.isNonZero() || isPowerOf2_32(MaxFixedVF.getFixedValue())) &&
5499            "MaxFixedVF must be a power of 2");
5500     unsigned MaxVFtimesIC = UserIC ? MaxFixedVF.getFixedValue() * UserIC
5501                                    : MaxFixedVF.getFixedValue();
5502     ScalarEvolution *SE = PSE.getSE();
5503     const SCEV *BackedgeTakenCount = PSE.getBackedgeTakenCount();
5504     const SCEV *ExitCount = SE->getAddExpr(
5505         BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType()));
5506     const SCEV *Rem = SE->getURemExpr(
5507         SE->applyLoopGuards(ExitCount, TheLoop),
5508         SE->getConstant(BackedgeTakenCount->getType(), MaxVFtimesIC));
5509     if (Rem->isZero()) {
5510       // Accept MaxFixedVF if we do not have a tail.
5511       LLVM_DEBUG(dbgs() << "LV: No tail will remain for any chosen VF.\n");
5512       return MaxFactors;
5513     }
5514   }
5515 
5516   // For scalable vectors, don't use tail folding as this is currently not yet
5517   // supported. The code is likely to have ended up here if the tripcount is
5518   // low, in which case it makes sense not to use scalable vectors.
5519   if (MaxFactors.ScalableVF.isVector())
5520     MaxFactors.ScalableVF = ElementCount::getScalable(0);
5521 
5522   // If we don't know the precise trip count, or if the trip count that we
5523   // found modulo the vectorization factor is not zero, try to fold the tail
5524   // by masking.
5525   // FIXME: look for a smaller MaxVF that does divide TC rather than masking.
5526   if (Legal->prepareToFoldTailByMasking()) {
5527     FoldTailByMasking = true;
5528     return MaxFactors;
5529   }
5530 
5531   // If there was a tail-folding hint/switch, but we can't fold the tail by
5532   // masking, fallback to a vectorization with a scalar epilogue.
5533   if (ScalarEpilogueStatus == CM_ScalarEpilogueNotNeededUsePredicate) {
5534     LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking: vectorize with a "
5535                          "scalar epilogue instead.\n");
5536     ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
5537     return MaxFactors;
5538   }
5539 
5540   if (ScalarEpilogueStatus == CM_ScalarEpilogueNotAllowedUsePredicate) {
5541     LLVM_DEBUG(dbgs() << "LV: Can't fold tail by masking: don't vectorize\n");
5542     return FixedScalableVFPair::getNone();
5543   }
5544 
5545   if (TC == 0) {
5546     reportVectorizationFailure(
5547         "Unable to calculate the loop count due to complex control flow",
5548         "unable to calculate the loop count due to complex control flow",
5549         "UnknownLoopCountComplexCFG", ORE, TheLoop);
5550     return FixedScalableVFPair::getNone();
5551   }
5552 
5553   reportVectorizationFailure(
5554       "Cannot optimize for size and vectorize at the same time.",
5555       "cannot optimize for size and vectorize at the same time. "
5556       "Enable vectorization of this loop with '#pragma clang loop "
5557       "vectorize(enable)' when compiling with -Os/-Oz",
5558       "NoTailLoopWithOptForSize", ORE, TheLoop);
5559   return FixedScalableVFPair::getNone();
5560 }
5561 
5562 ElementCount LoopVectorizationCostModel::getMaximizedVFForTarget(
5563     unsigned ConstTripCount, unsigned SmallestType, unsigned WidestType,
5564     const ElementCount &MaxSafeVF, bool FoldTailByMasking) {
5565   bool ComputeScalableMaxVF = MaxSafeVF.isScalable();
5566   TypeSize WidestRegister = TTI.getRegisterBitWidth(
5567       ComputeScalableMaxVF ? TargetTransformInfo::RGK_ScalableVector
5568                            : TargetTransformInfo::RGK_FixedWidthVector);
5569 
5570   // Convenience function to return the minimum of two ElementCounts.
5571   auto MinVF = [](const ElementCount &LHS, const ElementCount &RHS) {
5572     assert((LHS.isScalable() == RHS.isScalable()) &&
5573            "Scalable flags must match");
5574     return ElementCount::isKnownLT(LHS, RHS) ? LHS : RHS;
5575   };
5576 
5577   // Ensure MaxVF is a power of 2; the dependence distance bound may not be.
5578   // Note that both WidestRegister and WidestType may not be a powers of 2.
5579   auto MaxVectorElementCount = ElementCount::get(
5580       PowerOf2Floor(WidestRegister.getKnownMinSize() / WidestType),
5581       ComputeScalableMaxVF);
5582   MaxVectorElementCount = MinVF(MaxVectorElementCount, MaxSafeVF);
5583   LLVM_DEBUG(dbgs() << "LV: The Widest register safe to use is: "
5584                     << (MaxVectorElementCount * WidestType) << " bits.\n");
5585 
5586   if (!MaxVectorElementCount) {
5587     LLVM_DEBUG(dbgs() << "LV: The target has no "
5588                       << (ComputeScalableMaxVF ? "scalable" : "fixed")
5589                       << " vector registers.\n");
5590     return ElementCount::getFixed(1);
5591   }
5592 
5593   const auto TripCountEC = ElementCount::getFixed(ConstTripCount);
5594   if (ConstTripCount &&
5595       ElementCount::isKnownLE(TripCountEC, MaxVectorElementCount) &&
5596       (!FoldTailByMasking || isPowerOf2_32(ConstTripCount))) {
5597     // If loop trip count (TC) is known at compile time there is no point in
5598     // choosing VF greater than TC (as done in the loop below). Select maximum
5599     // power of two which doesn't exceed TC.
5600     // If MaxVectorElementCount is scalable, we only fall back on a fixed VF
5601     // when the TC is less than or equal to the known number of lanes.
5602     auto ClampedConstTripCount = PowerOf2Floor(ConstTripCount);
5603     LLVM_DEBUG(dbgs() << "LV: Clamping the MaxVF to maximum power of two not "
5604                          "exceeding the constant trip count: "
5605                       << ClampedConstTripCount << "\n");
5606     return ElementCount::getFixed(ClampedConstTripCount);
5607   }
5608 
5609   ElementCount MaxVF = MaxVectorElementCount;
5610   if (TTI.shouldMaximizeVectorBandwidth() ||
5611       (MaximizeBandwidth && isScalarEpilogueAllowed())) {
5612     auto MaxVectorElementCountMaxBW = ElementCount::get(
5613         PowerOf2Floor(WidestRegister.getKnownMinSize() / SmallestType),
5614         ComputeScalableMaxVF);
5615     MaxVectorElementCountMaxBW = MinVF(MaxVectorElementCountMaxBW, MaxSafeVF);
5616 
5617     // Collect all viable vectorization factors larger than the default MaxVF
5618     // (i.e. MaxVectorElementCount).
5619     SmallVector<ElementCount, 8> VFs;
5620     for (ElementCount VS = MaxVectorElementCount * 2;
5621          ElementCount::isKnownLE(VS, MaxVectorElementCountMaxBW); VS *= 2)
5622       VFs.push_back(VS);
5623 
5624     // For each VF calculate its register usage.
5625     auto RUs = calculateRegisterUsage(VFs);
5626 
5627     // Select the largest VF which doesn't require more registers than existing
5628     // ones.
5629     for (int i = RUs.size() - 1; i >= 0; --i) {
5630       bool Selected = true;
5631       for (auto &pair : RUs[i].MaxLocalUsers) {
5632         unsigned TargetNumRegisters = TTI.getNumberOfRegisters(pair.first);
5633         if (pair.second > TargetNumRegisters)
5634           Selected = false;
5635       }
5636       if (Selected) {
5637         MaxVF = VFs[i];
5638         break;
5639       }
5640     }
5641     if (ElementCount MinVF =
5642             TTI.getMinimumVF(SmallestType, ComputeScalableMaxVF)) {
5643       if (ElementCount::isKnownLT(MaxVF, MinVF)) {
5644         LLVM_DEBUG(dbgs() << "LV: Overriding calculated MaxVF(" << MaxVF
5645                           << ") with target's minimum: " << MinVF << '\n');
5646         MaxVF = MinVF;
5647       }
5648     }
5649   }
5650   return MaxVF;
5651 }
5652 
5653 bool LoopVectorizationCostModel::isMoreProfitable(
5654     const VectorizationFactor &A, const VectorizationFactor &B) const {
5655   InstructionCost CostA = A.Cost;
5656   InstructionCost CostB = B.Cost;
5657 
5658   unsigned MaxTripCount = PSE.getSE()->getSmallConstantMaxTripCount(TheLoop);
5659 
5660   if (!A.Width.isScalable() && !B.Width.isScalable() && FoldTailByMasking &&
5661       MaxTripCount) {
5662     // If we are folding the tail and the trip count is a known (possibly small)
5663     // constant, the trip count will be rounded up to an integer number of
5664     // iterations. The total cost will be PerIterationCost*ceil(TripCount/VF),
5665     // which we compare directly. When not folding the tail, the total cost will
5666     // be PerIterationCost*floor(TC/VF) + Scalar remainder cost, and so is
5667     // approximated with the per-lane cost below instead of using the tripcount
5668     // as here.
5669     auto RTCostA = CostA * divideCeil(MaxTripCount, A.Width.getFixedValue());
5670     auto RTCostB = CostB * divideCeil(MaxTripCount, B.Width.getFixedValue());
5671     return RTCostA < RTCostB;
5672   }
5673 
5674   // Improve estimate for the vector width if it is scalable.
5675   unsigned EstimatedWidthA = A.Width.getKnownMinValue();
5676   unsigned EstimatedWidthB = B.Width.getKnownMinValue();
5677   if (Optional<unsigned> VScale = TTI.getVScaleForTuning()) {
5678     if (A.Width.isScalable())
5679       EstimatedWidthA *= VScale.getValue();
5680     if (B.Width.isScalable())
5681       EstimatedWidthB *= VScale.getValue();
5682   }
5683 
5684   // Assume vscale may be larger than 1 (or the value being tuned for),
5685   // so that scalable vectorization is slightly favorable over fixed-width
5686   // vectorization.
5687   if (A.Width.isScalable() && !B.Width.isScalable())
5688     return (CostA * B.Width.getFixedValue()) <= (CostB * EstimatedWidthA);
5689 
5690   // To avoid the need for FP division:
5691   //      (CostA / A.Width) < (CostB / B.Width)
5692   // <=>  (CostA * B.Width) < (CostB * A.Width)
5693   return (CostA * EstimatedWidthB) < (CostB * EstimatedWidthA);
5694 }
5695 
5696 VectorizationFactor LoopVectorizationCostModel::selectVectorizationFactor(
5697     const ElementCountSet &VFCandidates) {
5698   InstructionCost ExpectedCost = expectedCost(ElementCount::getFixed(1)).first;
5699   LLVM_DEBUG(dbgs() << "LV: Scalar loop costs: " << ExpectedCost << ".\n");
5700   assert(ExpectedCost.isValid() && "Unexpected invalid cost for scalar loop");
5701   assert(VFCandidates.count(ElementCount::getFixed(1)) &&
5702          "Expected Scalar VF to be a candidate");
5703 
5704   const VectorizationFactor ScalarCost(ElementCount::getFixed(1), ExpectedCost);
5705   VectorizationFactor ChosenFactor = ScalarCost;
5706 
5707   bool ForceVectorization = Hints->getForce() == LoopVectorizeHints::FK_Enabled;
5708   if (ForceVectorization && VFCandidates.size() > 1) {
5709     // Ignore scalar width, because the user explicitly wants vectorization.
5710     // Initialize cost to max so that VF = 2 is, at least, chosen during cost
5711     // evaluation.
5712     ChosenFactor.Cost = InstructionCost::getMax();
5713   }
5714 
5715   SmallVector<InstructionVFPair> InvalidCosts;
5716   for (const auto &i : VFCandidates) {
5717     // The cost for scalar VF=1 is already calculated, so ignore it.
5718     if (i.isScalar())
5719       continue;
5720 
5721     VectorizationCostTy C = expectedCost(i, &InvalidCosts);
5722     VectorizationFactor Candidate(i, C.first);
5723 
5724 #ifndef NDEBUG
5725     unsigned AssumedMinimumVscale = 1;
5726     if (Optional<unsigned> VScale = TTI.getVScaleForTuning())
5727       AssumedMinimumVscale = VScale.getValue();
5728     unsigned Width =
5729         Candidate.Width.isScalable()
5730             ? Candidate.Width.getKnownMinValue() * AssumedMinimumVscale
5731             : Candidate.Width.getFixedValue();
5732     LLVM_DEBUG(dbgs() << "LV: Vector loop of width " << i
5733                       << " costs: " << (Candidate.Cost / Width));
5734     if (i.isScalable())
5735       LLVM_DEBUG(dbgs() << " (assuming a minimum vscale of "
5736                         << AssumedMinimumVscale << ")");
5737     LLVM_DEBUG(dbgs() << ".\n");
5738 #endif
5739 
5740     if (!C.second && !ForceVectorization) {
5741       LLVM_DEBUG(
5742           dbgs() << "LV: Not considering vector loop of width " << i
5743                  << " because it will not generate any vector instructions.\n");
5744       continue;
5745     }
5746 
5747     // If profitable add it to ProfitableVF list.
5748     if (isMoreProfitable(Candidate, ScalarCost))
5749       ProfitableVFs.push_back(Candidate);
5750 
5751     if (isMoreProfitable(Candidate, ChosenFactor))
5752       ChosenFactor = Candidate;
5753   }
5754 
5755   // Emit a report of VFs with invalid costs in the loop.
5756   if (!InvalidCosts.empty()) {
5757     // Group the remarks per instruction, keeping the instruction order from
5758     // InvalidCosts.
5759     std::map<Instruction *, unsigned> Numbering;
5760     unsigned I = 0;
5761     for (auto &Pair : InvalidCosts)
5762       if (!Numbering.count(Pair.first))
5763         Numbering[Pair.first] = I++;
5764 
5765     // Sort the list, first on instruction(number) then on VF.
5766     llvm::sort(InvalidCosts,
5767                [&Numbering](InstructionVFPair &A, InstructionVFPair &B) {
5768                  if (Numbering[A.first] != Numbering[B.first])
5769                    return Numbering[A.first] < Numbering[B.first];
5770                  ElementCountComparator ECC;
5771                  return ECC(A.second, B.second);
5772                });
5773 
5774     // For a list of ordered instruction-vf pairs:
5775     //   [(load, vf1), (load, vf2), (store, vf1)]
5776     // Group the instructions together to emit separate remarks for:
5777     //   load  (vf1, vf2)
5778     //   store (vf1)
5779     auto Tail = ArrayRef<InstructionVFPair>(InvalidCosts);
5780     auto Subset = ArrayRef<InstructionVFPair>();
5781     do {
5782       if (Subset.empty())
5783         Subset = Tail.take_front(1);
5784 
5785       Instruction *I = Subset.front().first;
5786 
5787       // If the next instruction is different, or if there are no other pairs,
5788       // emit a remark for the collated subset. e.g.
5789       //   [(load, vf1), (load, vf2))]
5790       // to emit:
5791       //  remark: invalid costs for 'load' at VF=(vf, vf2)
5792       if (Subset == Tail || Tail[Subset.size()].first != I) {
5793         std::string OutString;
5794         raw_string_ostream OS(OutString);
5795         assert(!Subset.empty() && "Unexpected empty range");
5796         OS << "Instruction with invalid costs prevented vectorization at VF=(";
5797         for (auto &Pair : Subset)
5798           OS << (Pair.second == Subset.front().second ? "" : ", ")
5799              << Pair.second;
5800         OS << "):";
5801         if (auto *CI = dyn_cast<CallInst>(I))
5802           OS << " call to " << CI->getCalledFunction()->getName();
5803         else
5804           OS << " " << I->getOpcodeName();
5805         OS.flush();
5806         reportVectorizationInfo(OutString, "InvalidCost", ORE, TheLoop, I);
5807         Tail = Tail.drop_front(Subset.size());
5808         Subset = {};
5809       } else
5810         // Grow the subset by one element
5811         Subset = Tail.take_front(Subset.size() + 1);
5812     } while (!Tail.empty());
5813   }
5814 
5815   if (!EnableCondStoresVectorization && NumPredStores) {
5816     reportVectorizationFailure("There are conditional stores.",
5817         "store that is conditionally executed prevents vectorization",
5818         "ConditionalStore", ORE, TheLoop);
5819     ChosenFactor = ScalarCost;
5820   }
5821 
5822   LLVM_DEBUG(if (ForceVectorization && !ChosenFactor.Width.isScalar() &&
5823                  ChosenFactor.Cost >= ScalarCost.Cost) dbgs()
5824              << "LV: Vectorization seems to be not beneficial, "
5825              << "but was forced by a user.\n");
5826   LLVM_DEBUG(dbgs() << "LV: Selecting VF: " << ChosenFactor.Width << ".\n");
5827   return ChosenFactor;
5828 }
5829 
5830 bool LoopVectorizationCostModel::isCandidateForEpilogueVectorization(
5831     const Loop &L, ElementCount VF) const {
5832   // Cross iteration phis such as reductions need special handling and are
5833   // currently unsupported.
5834   if (any_of(L.getHeader()->phis(), [&](PHINode &Phi) {
5835         return Legal->isFirstOrderRecurrence(&Phi) ||
5836                Legal->isReductionVariable(&Phi);
5837       }))
5838     return false;
5839 
5840   // Phis with uses outside of the loop require special handling and are
5841   // currently unsupported.
5842   for (auto &Entry : Legal->getInductionVars()) {
5843     // Look for uses of the value of the induction at the last iteration.
5844     Value *PostInc = Entry.first->getIncomingValueForBlock(L.getLoopLatch());
5845     for (User *U : PostInc->users())
5846       if (!L.contains(cast<Instruction>(U)))
5847         return false;
5848     // Look for uses of penultimate value of the induction.
5849     for (User *U : Entry.first->users())
5850       if (!L.contains(cast<Instruction>(U)))
5851         return false;
5852   }
5853 
5854   // Induction variables that are widened require special handling that is
5855   // currently not supported.
5856   if (any_of(Legal->getInductionVars(), [&](auto &Entry) {
5857         return !(this->isScalarAfterVectorization(Entry.first, VF) ||
5858                  this->isProfitableToScalarize(Entry.first, VF));
5859       }))
5860     return false;
5861 
5862   // Epilogue vectorization code has not been auditted to ensure it handles
5863   // non-latch exits properly.  It may be fine, but it needs auditted and
5864   // tested.
5865   if (L.getExitingBlock() != L.getLoopLatch())
5866     return false;
5867 
5868   return true;
5869 }
5870 
5871 bool LoopVectorizationCostModel::isEpilogueVectorizationProfitable(
5872     const ElementCount VF) const {
5873   // FIXME: We need a much better cost-model to take different parameters such
5874   // as register pressure, code size increase and cost of extra branches into
5875   // account. For now we apply a very crude heuristic and only consider loops
5876   // with vectorization factors larger than a certain value.
5877   // We also consider epilogue vectorization unprofitable for targets that don't
5878   // consider interleaving beneficial (eg. MVE).
5879   if (TTI.getMaxInterleaveFactor(VF.getKnownMinValue()) <= 1)
5880     return false;
5881   if (VF.getFixedValue() >= EpilogueVectorizationMinVF)
5882     return true;
5883   return false;
5884 }
5885 
5886 VectorizationFactor
5887 LoopVectorizationCostModel::selectEpilogueVectorizationFactor(
5888     const ElementCount MainLoopVF, const LoopVectorizationPlanner &LVP) {
5889   VectorizationFactor Result = VectorizationFactor::Disabled();
5890   if (!EnableEpilogueVectorization) {
5891     LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization is disabled.\n";);
5892     return Result;
5893   }
5894 
5895   if (!isScalarEpilogueAllowed()) {
5896     LLVM_DEBUG(
5897         dbgs() << "LEV: Unable to vectorize epilogue because no epilogue is "
5898                   "allowed.\n";);
5899     return Result;
5900   }
5901 
5902   // Not really a cost consideration, but check for unsupported cases here to
5903   // simplify the logic.
5904   if (!isCandidateForEpilogueVectorization(*TheLoop, MainLoopVF)) {
5905     LLVM_DEBUG(
5906         dbgs() << "LEV: Unable to vectorize epilogue because the loop is "
5907                   "not a supported candidate.\n";);
5908     return Result;
5909   }
5910 
5911   if (EpilogueVectorizationForceVF > 1) {
5912     LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization factor is forced.\n";);
5913     ElementCount ForcedEC = ElementCount::getFixed(EpilogueVectorizationForceVF);
5914     if (LVP.hasPlanWithVF(ForcedEC))
5915       return {ForcedEC, 0};
5916     else {
5917       LLVM_DEBUG(
5918           dbgs()
5919               << "LEV: Epilogue vectorization forced factor is not viable.\n";);
5920       return Result;
5921     }
5922   }
5923 
5924   if (TheLoop->getHeader()->getParent()->hasOptSize() ||
5925       TheLoop->getHeader()->getParent()->hasMinSize()) {
5926     LLVM_DEBUG(
5927         dbgs()
5928             << "LEV: Epilogue vectorization skipped due to opt for size.\n";);
5929     return Result;
5930   }
5931 
5932   auto FixedMainLoopVF = ElementCount::getFixed(MainLoopVF.getKnownMinValue());
5933   if (MainLoopVF.isScalable())
5934     LLVM_DEBUG(
5935         dbgs() << "LEV: Epilogue vectorization using scalable vectors not "
5936                   "yet supported. Converting to fixed-width (VF="
5937                << FixedMainLoopVF << ") instead\n");
5938 
5939   if (!isEpilogueVectorizationProfitable(FixedMainLoopVF)) {
5940     LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization is not profitable for "
5941                          "this loop\n");
5942     return Result;
5943   }
5944 
5945   for (auto &NextVF : ProfitableVFs)
5946     if (ElementCount::isKnownLT(NextVF.Width, FixedMainLoopVF) &&
5947         (Result.Width.getFixedValue() == 1 ||
5948          isMoreProfitable(NextVF, Result)) &&
5949         LVP.hasPlanWithVF(NextVF.Width))
5950       Result = NextVF;
5951 
5952   if (Result != VectorizationFactor::Disabled())
5953     LLVM_DEBUG(dbgs() << "LEV: Vectorizing epilogue loop with VF = "
5954                       << Result.Width.getFixedValue() << "\n";);
5955   return Result;
5956 }
5957 
5958 std::pair<unsigned, unsigned>
5959 LoopVectorizationCostModel::getSmallestAndWidestTypes() {
5960   unsigned MinWidth = -1U;
5961   unsigned MaxWidth = 8;
5962   const DataLayout &DL = TheFunction->getParent()->getDataLayout();
5963   // For in-loop reductions, no element types are added to ElementTypesInLoop
5964   // if there are no loads/stores in the loop. In this case, check through the
5965   // reduction variables to determine the maximum width.
5966   if (ElementTypesInLoop.empty() && !Legal->getReductionVars().empty()) {
5967     // Reset MaxWidth so that we can find the smallest type used by recurrences
5968     // in the loop.
5969     MaxWidth = -1U;
5970     for (auto &PhiDescriptorPair : Legal->getReductionVars()) {
5971       const RecurrenceDescriptor &RdxDesc = PhiDescriptorPair.second;
5972       // When finding the min width used by the recurrence we need to account
5973       // for casts on the input operands of the recurrence.
5974       MaxWidth = std::min<unsigned>(
5975           MaxWidth, std::min<unsigned>(
5976                         RdxDesc.getMinWidthCastToRecurrenceTypeInBits(),
5977                         RdxDesc.getRecurrenceType()->getScalarSizeInBits()));
5978     }
5979   } else {
5980     for (Type *T : ElementTypesInLoop) {
5981       MinWidth = std::min<unsigned>(
5982           MinWidth, DL.getTypeSizeInBits(T->getScalarType()).getFixedSize());
5983       MaxWidth = std::max<unsigned>(
5984           MaxWidth, DL.getTypeSizeInBits(T->getScalarType()).getFixedSize());
5985     }
5986   }
5987   return {MinWidth, MaxWidth};
5988 }
5989 
5990 void LoopVectorizationCostModel::collectElementTypesForWidening() {
5991   ElementTypesInLoop.clear();
5992   // For each block.
5993   for (BasicBlock *BB : TheLoop->blocks()) {
5994     // For each instruction in the loop.
5995     for (Instruction &I : BB->instructionsWithoutDebug()) {
5996       Type *T = I.getType();
5997 
5998       // Skip ignored values.
5999       if (ValuesToIgnore.count(&I))
6000         continue;
6001 
6002       // Only examine Loads, Stores and PHINodes.
6003       if (!isa<LoadInst>(I) && !isa<StoreInst>(I) && !isa<PHINode>(I))
6004         continue;
6005 
6006       // Examine PHI nodes that are reduction variables. Update the type to
6007       // account for the recurrence type.
6008       if (auto *PN = dyn_cast<PHINode>(&I)) {
6009         if (!Legal->isReductionVariable(PN))
6010           continue;
6011         const RecurrenceDescriptor &RdxDesc =
6012             Legal->getReductionVars().find(PN)->second;
6013         if (PreferInLoopReductions || useOrderedReductions(RdxDesc) ||
6014             TTI.preferInLoopReduction(RdxDesc.getOpcode(),
6015                                       RdxDesc.getRecurrenceType(),
6016                                       TargetTransformInfo::ReductionFlags()))
6017           continue;
6018         T = RdxDesc.getRecurrenceType();
6019       }
6020 
6021       // Examine the stored values.
6022       if (auto *ST = dyn_cast<StoreInst>(&I))
6023         T = ST->getValueOperand()->getType();
6024 
6025       // Ignore loaded pointer types and stored pointer types that are not
6026       // vectorizable.
6027       //
6028       // FIXME: The check here attempts to predict whether a load or store will
6029       //        be vectorized. We only know this for certain after a VF has
6030       //        been selected. Here, we assume that if an access can be
6031       //        vectorized, it will be. We should also look at extending this
6032       //        optimization to non-pointer types.
6033       //
6034       if (T->isPointerTy() && !isConsecutiveLoadOrStore(&I) &&
6035           !isAccessInterleaved(&I) && !isLegalGatherOrScatter(&I))
6036         continue;
6037 
6038       ElementTypesInLoop.insert(T);
6039     }
6040   }
6041 }
6042 
6043 unsigned LoopVectorizationCostModel::selectInterleaveCount(ElementCount VF,
6044                                                            unsigned LoopCost) {
6045   // -- The interleave heuristics --
6046   // We interleave the loop in order to expose ILP and reduce the loop overhead.
6047   // There are many micro-architectural considerations that we can't predict
6048   // at this level. For example, frontend pressure (on decode or fetch) due to
6049   // code size, or the number and capabilities of the execution ports.
6050   //
6051   // We use the following heuristics to select the interleave count:
6052   // 1. If the code has reductions, then we interleave to break the cross
6053   // iteration dependency.
6054   // 2. If the loop is really small, then we interleave to reduce the loop
6055   // overhead.
6056   // 3. We don't interleave if we think that we will spill registers to memory
6057   // due to the increased register pressure.
6058 
6059   if (!isScalarEpilogueAllowed())
6060     return 1;
6061 
6062   // We used the distance for the interleave count.
6063   if (Legal->getMaxSafeDepDistBytes() != -1U)
6064     return 1;
6065 
6066   auto BestKnownTC = getSmallBestKnownTC(*PSE.getSE(), TheLoop);
6067   const bool HasReductions = !Legal->getReductionVars().empty();
6068   // Do not interleave loops with a relatively small known or estimated trip
6069   // count. But we will interleave when InterleaveSmallLoopScalarReduction is
6070   // enabled, and the code has scalar reductions(HasReductions && VF = 1),
6071   // because with the above conditions interleaving can expose ILP and break
6072   // cross iteration dependences for reductions.
6073   if (BestKnownTC && (*BestKnownTC < TinyTripCountInterleaveThreshold) &&
6074       !(InterleaveSmallLoopScalarReduction && HasReductions && VF.isScalar()))
6075     return 1;
6076 
6077   RegisterUsage R = calculateRegisterUsage({VF})[0];
6078   // We divide by these constants so assume that we have at least one
6079   // instruction that uses at least one register.
6080   for (auto& pair : R.MaxLocalUsers) {
6081     pair.second = std::max(pair.second, 1U);
6082   }
6083 
6084   // We calculate the interleave count using the following formula.
6085   // Subtract the number of loop invariants from the number of available
6086   // registers. These registers are used by all of the interleaved instances.
6087   // Next, divide the remaining registers by the number of registers that is
6088   // required by the loop, in order to estimate how many parallel instances
6089   // fit without causing spills. All of this is rounded down if necessary to be
6090   // a power of two. We want power of two interleave count to simplify any
6091   // addressing operations or alignment considerations.
6092   // We also want power of two interleave counts to ensure that the induction
6093   // variable of the vector loop wraps to zero, when tail is folded by masking;
6094   // this currently happens when OptForSize, in which case IC is set to 1 above.
6095   unsigned IC = UINT_MAX;
6096 
6097   for (auto& pair : R.MaxLocalUsers) {
6098     unsigned TargetNumRegisters = TTI.getNumberOfRegisters(pair.first);
6099     LLVM_DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters
6100                       << " registers of "
6101                       << TTI.getRegisterClassName(pair.first) << " register class\n");
6102     if (VF.isScalar()) {
6103       if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
6104         TargetNumRegisters = ForceTargetNumScalarRegs;
6105     } else {
6106       if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
6107         TargetNumRegisters = ForceTargetNumVectorRegs;
6108     }
6109     unsigned MaxLocalUsers = pair.second;
6110     unsigned LoopInvariantRegs = 0;
6111     if (R.LoopInvariantRegs.find(pair.first) != R.LoopInvariantRegs.end())
6112       LoopInvariantRegs = R.LoopInvariantRegs[pair.first];
6113 
6114     unsigned TmpIC = PowerOf2Floor((TargetNumRegisters - LoopInvariantRegs) / MaxLocalUsers);
6115     // Don't count the induction variable as interleaved.
6116     if (EnableIndVarRegisterHeur) {
6117       TmpIC =
6118           PowerOf2Floor((TargetNumRegisters - LoopInvariantRegs - 1) /
6119                         std::max(1U, (MaxLocalUsers - 1)));
6120     }
6121 
6122     IC = std::min(IC, TmpIC);
6123   }
6124 
6125   // Clamp the interleave ranges to reasonable counts.
6126   unsigned MaxInterleaveCount =
6127       TTI.getMaxInterleaveFactor(VF.getKnownMinValue());
6128 
6129   // Check if the user has overridden the max.
6130   if (VF.isScalar()) {
6131     if (ForceTargetMaxScalarInterleaveFactor.getNumOccurrences() > 0)
6132       MaxInterleaveCount = ForceTargetMaxScalarInterleaveFactor;
6133   } else {
6134     if (ForceTargetMaxVectorInterleaveFactor.getNumOccurrences() > 0)
6135       MaxInterleaveCount = ForceTargetMaxVectorInterleaveFactor;
6136   }
6137 
6138   // If trip count is known or estimated compile time constant, limit the
6139   // interleave count to be less than the trip count divided by VF, provided it
6140   // is at least 1.
6141   //
6142   // For scalable vectors we can't know if interleaving is beneficial. It may
6143   // not be beneficial for small loops if none of the lanes in the second vector
6144   // iterations is enabled. However, for larger loops, there is likely to be a
6145   // similar benefit as for fixed-width vectors. For now, we choose to leave
6146   // the InterleaveCount as if vscale is '1', although if some information about
6147   // the vector is known (e.g. min vector size), we can make a better decision.
6148   if (BestKnownTC) {
6149     MaxInterleaveCount =
6150         std::min(*BestKnownTC / VF.getKnownMinValue(), MaxInterleaveCount);
6151     // Make sure MaxInterleaveCount is greater than 0.
6152     MaxInterleaveCount = std::max(1u, MaxInterleaveCount);
6153   }
6154 
6155   assert(MaxInterleaveCount > 0 &&
6156          "Maximum interleave count must be greater than 0");
6157 
6158   // Clamp the calculated IC to be between the 1 and the max interleave count
6159   // that the target and trip count allows.
6160   if (IC > MaxInterleaveCount)
6161     IC = MaxInterleaveCount;
6162   else
6163     // Make sure IC is greater than 0.
6164     IC = std::max(1u, IC);
6165 
6166   assert(IC > 0 && "Interleave count must be greater than 0.");
6167 
6168   // If we did not calculate the cost for VF (because the user selected the VF)
6169   // then we calculate the cost of VF here.
6170   if (LoopCost == 0) {
6171     InstructionCost C = expectedCost(VF).first;
6172     assert(C.isValid() && "Expected to have chosen a VF with valid cost");
6173     LoopCost = *C.getValue();
6174   }
6175 
6176   assert(LoopCost && "Non-zero loop cost expected");
6177 
6178   // Interleave if we vectorized this loop and there is a reduction that could
6179   // benefit from interleaving.
6180   if (VF.isVector() && HasReductions) {
6181     LLVM_DEBUG(dbgs() << "LV: Interleaving because of reductions.\n");
6182     return IC;
6183   }
6184 
6185   // Note that if we've already vectorized the loop we will have done the
6186   // runtime check and so interleaving won't require further checks.
6187   bool InterleavingRequiresRuntimePointerCheck =
6188       (VF.isScalar() && Legal->getRuntimePointerChecking()->Need);
6189 
6190   // We want to interleave small loops in order to reduce the loop overhead and
6191   // potentially expose ILP opportunities.
6192   LLVM_DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n'
6193                     << "LV: IC is " << IC << '\n'
6194                     << "LV: VF is " << VF << '\n');
6195   const bool AggressivelyInterleaveReductions =
6196       TTI.enableAggressiveInterleaving(HasReductions);
6197   if (!InterleavingRequiresRuntimePointerCheck && LoopCost < SmallLoopCost) {
6198     // We assume that the cost overhead is 1 and we use the cost model
6199     // to estimate the cost of the loop and interleave until the cost of the
6200     // loop overhead is about 5% of the cost of the loop.
6201     unsigned SmallIC =
6202         std::min(IC, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost));
6203 
6204     // Interleave until store/load ports (estimated by max interleave count) are
6205     // saturated.
6206     unsigned NumStores = Legal->getNumStores();
6207     unsigned NumLoads = Legal->getNumLoads();
6208     unsigned StoresIC = IC / (NumStores ? NumStores : 1);
6209     unsigned LoadsIC = IC / (NumLoads ? NumLoads : 1);
6210 
6211     // There is little point in interleaving for reductions containing selects
6212     // and compares when VF=1 since it may just create more overhead than it's
6213     // worth for loops with small trip counts. This is because we still have to
6214     // do the final reduction after the loop.
6215     bool HasSelectCmpReductions =
6216         HasReductions &&
6217         any_of(Legal->getReductionVars(), [&](auto &Reduction) -> bool {
6218           const RecurrenceDescriptor &RdxDesc = Reduction.second;
6219           return RecurrenceDescriptor::isSelectCmpRecurrenceKind(
6220               RdxDesc.getRecurrenceKind());
6221         });
6222     if (HasSelectCmpReductions) {
6223       LLVM_DEBUG(dbgs() << "LV: Not interleaving select-cmp reductions.\n");
6224       return 1;
6225     }
6226 
6227     // If we have a scalar reduction (vector reductions are already dealt with
6228     // by this point), we can increase the critical path length if the loop
6229     // we're interleaving is inside another loop. For tree-wise reductions
6230     // set the limit to 2, and for ordered reductions it's best to disable
6231     // interleaving entirely.
6232     if (HasReductions && TheLoop->getLoopDepth() > 1) {
6233       bool HasOrderedReductions =
6234           any_of(Legal->getReductionVars(), [&](auto &Reduction) -> bool {
6235             const RecurrenceDescriptor &RdxDesc = Reduction.second;
6236             return RdxDesc.isOrdered();
6237           });
6238       if (HasOrderedReductions) {
6239         LLVM_DEBUG(
6240             dbgs() << "LV: Not interleaving scalar ordered reductions.\n");
6241         return 1;
6242       }
6243 
6244       unsigned F = static_cast<unsigned>(MaxNestedScalarReductionIC);
6245       SmallIC = std::min(SmallIC, F);
6246       StoresIC = std::min(StoresIC, F);
6247       LoadsIC = std::min(LoadsIC, F);
6248     }
6249 
6250     if (EnableLoadStoreRuntimeInterleave &&
6251         std::max(StoresIC, LoadsIC) > SmallIC) {
6252       LLVM_DEBUG(
6253           dbgs() << "LV: Interleaving to saturate store or load ports.\n");
6254       return std::max(StoresIC, LoadsIC);
6255     }
6256 
6257     // If there are scalar reductions and TTI has enabled aggressive
6258     // interleaving for reductions, we will interleave to expose ILP.
6259     if (InterleaveSmallLoopScalarReduction && VF.isScalar() &&
6260         AggressivelyInterleaveReductions) {
6261       LLVM_DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
6262       // Interleave no less than SmallIC but not as aggressive as the normal IC
6263       // to satisfy the rare situation when resources are too limited.
6264       return std::max(IC / 2, SmallIC);
6265     } else {
6266       LLVM_DEBUG(dbgs() << "LV: Interleaving to reduce branch cost.\n");
6267       return SmallIC;
6268     }
6269   }
6270 
6271   // Interleave if this is a large loop (small loops are already dealt with by
6272   // this point) that could benefit from interleaving.
6273   if (AggressivelyInterleaveReductions) {
6274     LLVM_DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
6275     return IC;
6276   }
6277 
6278   LLVM_DEBUG(dbgs() << "LV: Not Interleaving.\n");
6279   return 1;
6280 }
6281 
6282 SmallVector<LoopVectorizationCostModel::RegisterUsage, 8>
6283 LoopVectorizationCostModel::calculateRegisterUsage(ArrayRef<ElementCount> VFs) {
6284   // This function calculates the register usage by measuring the highest number
6285   // of values that are alive at a single location. Obviously, this is a very
6286   // rough estimation. We scan the loop in a topological order in order and
6287   // assign a number to each instruction. We use RPO to ensure that defs are
6288   // met before their users. We assume that each instruction that has in-loop
6289   // users starts an interval. We record every time that an in-loop value is
6290   // used, so we have a list of the first and last occurrences of each
6291   // instruction. Next, we transpose this data structure into a multi map that
6292   // holds the list of intervals that *end* at a specific location. This multi
6293   // map allows us to perform a linear search. We scan the instructions linearly
6294   // and record each time that a new interval starts, by placing it in a set.
6295   // If we find this value in the multi-map then we remove it from the set.
6296   // The max register usage is the maximum size of the set.
6297   // We also search for instructions that are defined outside the loop, but are
6298   // used inside the loop. We need this number separately from the max-interval
6299   // usage number because when we unroll, loop-invariant values do not take
6300   // more register.
6301   LoopBlocksDFS DFS(TheLoop);
6302   DFS.perform(LI);
6303 
6304   RegisterUsage RU;
6305 
6306   // Each 'key' in the map opens a new interval. The values
6307   // of the map are the index of the 'last seen' usage of the
6308   // instruction that is the key.
6309   using IntervalMap = DenseMap<Instruction *, unsigned>;
6310 
6311   // Maps instruction to its index.
6312   SmallVector<Instruction *, 64> IdxToInstr;
6313   // Marks the end of each interval.
6314   IntervalMap EndPoint;
6315   // Saves the list of instruction indices that are used in the loop.
6316   SmallPtrSet<Instruction *, 8> Ends;
6317   // Saves the list of values that are used in the loop but are
6318   // defined outside the loop, such as arguments and constants.
6319   SmallPtrSet<Value *, 8> LoopInvariants;
6320 
6321   for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) {
6322     for (Instruction &I : BB->instructionsWithoutDebug()) {
6323       IdxToInstr.push_back(&I);
6324 
6325       // Save the end location of each USE.
6326       for (Value *U : I.operands()) {
6327         auto *Instr = dyn_cast<Instruction>(U);
6328 
6329         // Ignore non-instruction values such as arguments, constants, etc.
6330         if (!Instr)
6331           continue;
6332 
6333         // If this instruction is outside the loop then record it and continue.
6334         if (!TheLoop->contains(Instr)) {
6335           LoopInvariants.insert(Instr);
6336           continue;
6337         }
6338 
6339         // Overwrite previous end points.
6340         EndPoint[Instr] = IdxToInstr.size();
6341         Ends.insert(Instr);
6342       }
6343     }
6344   }
6345 
6346   // Saves the list of intervals that end with the index in 'key'.
6347   using InstrList = SmallVector<Instruction *, 2>;
6348   DenseMap<unsigned, InstrList> TransposeEnds;
6349 
6350   // Transpose the EndPoints to a list of values that end at each index.
6351   for (auto &Interval : EndPoint)
6352     TransposeEnds[Interval.second].push_back(Interval.first);
6353 
6354   SmallPtrSet<Instruction *, 8> OpenIntervals;
6355   SmallVector<RegisterUsage, 8> RUs(VFs.size());
6356   SmallVector<SmallMapVector<unsigned, unsigned, 4>, 8> MaxUsages(VFs.size());
6357 
6358   LLVM_DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
6359 
6360   // A lambda that gets the register usage for the given type and VF.
6361   const auto &TTICapture = TTI;
6362   auto GetRegUsage = [&TTICapture](Type *Ty, ElementCount VF) -> unsigned {
6363     if (Ty->isTokenTy() || !VectorType::isValidElementType(Ty))
6364       return 0;
6365     InstructionCost::CostType RegUsage =
6366         *TTICapture.getRegUsageForType(VectorType::get(Ty, VF)).getValue();
6367     assert(RegUsage >= 0 && RegUsage <= std::numeric_limits<unsigned>::max() &&
6368            "Nonsensical values for register usage.");
6369     return RegUsage;
6370   };
6371 
6372   for (unsigned int i = 0, s = IdxToInstr.size(); i < s; ++i) {
6373     Instruction *I = IdxToInstr[i];
6374 
6375     // Remove all of the instructions that end at this location.
6376     InstrList &List = TransposeEnds[i];
6377     for (Instruction *ToRemove : List)
6378       OpenIntervals.erase(ToRemove);
6379 
6380     // Ignore instructions that are never used within the loop.
6381     if (!Ends.count(I))
6382       continue;
6383 
6384     // Skip ignored values.
6385     if (ValuesToIgnore.count(I))
6386       continue;
6387 
6388     // For each VF find the maximum usage of registers.
6389     for (unsigned j = 0, e = VFs.size(); j < e; ++j) {
6390       // Count the number of live intervals.
6391       SmallMapVector<unsigned, unsigned, 4> RegUsage;
6392 
6393       if (VFs[j].isScalar()) {
6394         for (auto Inst : OpenIntervals) {
6395           unsigned ClassID = TTI.getRegisterClassForType(false, Inst->getType());
6396           if (RegUsage.find(ClassID) == RegUsage.end())
6397             RegUsage[ClassID] = 1;
6398           else
6399             RegUsage[ClassID] += 1;
6400         }
6401       } else {
6402         collectUniformsAndScalars(VFs[j]);
6403         for (auto Inst : OpenIntervals) {
6404           // Skip ignored values for VF > 1.
6405           if (VecValuesToIgnore.count(Inst))
6406             continue;
6407           if (isScalarAfterVectorization(Inst, VFs[j])) {
6408             unsigned ClassID = TTI.getRegisterClassForType(false, Inst->getType());
6409             if (RegUsage.find(ClassID) == RegUsage.end())
6410               RegUsage[ClassID] = 1;
6411             else
6412               RegUsage[ClassID] += 1;
6413           } else {
6414             unsigned ClassID = TTI.getRegisterClassForType(true, Inst->getType());
6415             if (RegUsage.find(ClassID) == RegUsage.end())
6416               RegUsage[ClassID] = GetRegUsage(Inst->getType(), VFs[j]);
6417             else
6418               RegUsage[ClassID] += GetRegUsage(Inst->getType(), VFs[j]);
6419           }
6420         }
6421       }
6422 
6423       for (auto& pair : RegUsage) {
6424         if (MaxUsages[j].find(pair.first) != MaxUsages[j].end())
6425           MaxUsages[j][pair.first] = std::max(MaxUsages[j][pair.first], pair.second);
6426         else
6427           MaxUsages[j][pair.first] = pair.second;
6428       }
6429     }
6430 
6431     LLVM_DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # "
6432                       << OpenIntervals.size() << '\n');
6433 
6434     // Add the current instruction to the list of open intervals.
6435     OpenIntervals.insert(I);
6436   }
6437 
6438   for (unsigned i = 0, e = VFs.size(); i < e; ++i) {
6439     SmallMapVector<unsigned, unsigned, 4> Invariant;
6440 
6441     for (auto Inst : LoopInvariants) {
6442       unsigned Usage =
6443           VFs[i].isScalar() ? 1 : GetRegUsage(Inst->getType(), VFs[i]);
6444       unsigned ClassID =
6445           TTI.getRegisterClassForType(VFs[i].isVector(), Inst->getType());
6446       if (Invariant.find(ClassID) == Invariant.end())
6447         Invariant[ClassID] = Usage;
6448       else
6449         Invariant[ClassID] += Usage;
6450     }
6451 
6452     LLVM_DEBUG({
6453       dbgs() << "LV(REG): VF = " << VFs[i] << '\n';
6454       dbgs() << "LV(REG): Found max usage: " << MaxUsages[i].size()
6455              << " item\n";
6456       for (const auto &pair : MaxUsages[i]) {
6457         dbgs() << "LV(REG): RegisterClass: "
6458                << TTI.getRegisterClassName(pair.first) << ", " << pair.second
6459                << " registers\n";
6460       }
6461       dbgs() << "LV(REG): Found invariant usage: " << Invariant.size()
6462              << " item\n";
6463       for (const auto &pair : Invariant) {
6464         dbgs() << "LV(REG): RegisterClass: "
6465                << TTI.getRegisterClassName(pair.first) << ", " << pair.second
6466                << " registers\n";
6467       }
6468     });
6469 
6470     RU.LoopInvariantRegs = Invariant;
6471     RU.MaxLocalUsers = MaxUsages[i];
6472     RUs[i] = RU;
6473   }
6474 
6475   return RUs;
6476 }
6477 
6478 bool LoopVectorizationCostModel::useEmulatedMaskMemRefHack(Instruction *I){
6479   // TODO: Cost model for emulated masked load/store is completely
6480   // broken. This hack guides the cost model to use an artificially
6481   // high enough value to practically disable vectorization with such
6482   // operations, except where previously deployed legality hack allowed
6483   // using very low cost values. This is to avoid regressions coming simply
6484   // from moving "masked load/store" check from legality to cost model.
6485   // Masked Load/Gather emulation was previously never allowed.
6486   // Limited number of Masked Store/Scatter emulation was allowed.
6487   assert(isPredicatedInst(I) &&
6488          "Expecting a scalar emulated instruction");
6489   return isa<LoadInst>(I) ||
6490          (isa<StoreInst>(I) &&
6491           NumPredStores > NumberOfStoresToPredicate);
6492 }
6493 
6494 void LoopVectorizationCostModel::collectInstsToScalarize(ElementCount VF) {
6495   // If we aren't vectorizing the loop, or if we've already collected the
6496   // instructions to scalarize, there's nothing to do. Collection may already
6497   // have occurred if we have a user-selected VF and are now computing the
6498   // expected cost for interleaving.
6499   if (VF.isScalar() || VF.isZero() ||
6500       InstsToScalarize.find(VF) != InstsToScalarize.end())
6501     return;
6502 
6503   // Initialize a mapping for VF in InstsToScalalarize. If we find that it's
6504   // not profitable to scalarize any instructions, the presence of VF in the
6505   // map will indicate that we've analyzed it already.
6506   ScalarCostsTy &ScalarCostsVF = InstsToScalarize[VF];
6507 
6508   // Find all the instructions that are scalar with predication in the loop and
6509   // determine if it would be better to not if-convert the blocks they are in.
6510   // If so, we also record the instructions to scalarize.
6511   for (BasicBlock *BB : TheLoop->blocks()) {
6512     if (!blockNeedsPredicationForAnyReason(BB))
6513       continue;
6514     for (Instruction &I : *BB)
6515       if (isScalarWithPredication(&I)) {
6516         ScalarCostsTy ScalarCosts;
6517         // Do not apply discount if scalable, because that would lead to
6518         // invalid scalarization costs.
6519         // Do not apply discount logic if hacked cost is needed
6520         // for emulated masked memrefs.
6521         if (!VF.isScalable() && !useEmulatedMaskMemRefHack(&I) &&
6522             computePredInstDiscount(&I, ScalarCosts, VF) >= 0)
6523           ScalarCostsVF.insert(ScalarCosts.begin(), ScalarCosts.end());
6524         // Remember that BB will remain after vectorization.
6525         PredicatedBBsAfterVectorization.insert(BB);
6526       }
6527   }
6528 }
6529 
6530 int LoopVectorizationCostModel::computePredInstDiscount(
6531     Instruction *PredInst, ScalarCostsTy &ScalarCosts, ElementCount VF) {
6532   assert(!isUniformAfterVectorization(PredInst, VF) &&
6533          "Instruction marked uniform-after-vectorization will be predicated");
6534 
6535   // Initialize the discount to zero, meaning that the scalar version and the
6536   // vector version cost the same.
6537   InstructionCost Discount = 0;
6538 
6539   // Holds instructions to analyze. The instructions we visit are mapped in
6540   // ScalarCosts. Those instructions are the ones that would be scalarized if
6541   // we find that the scalar version costs less.
6542   SmallVector<Instruction *, 8> Worklist;
6543 
6544   // Returns true if the given instruction can be scalarized.
6545   auto canBeScalarized = [&](Instruction *I) -> bool {
6546     // We only attempt to scalarize instructions forming a single-use chain
6547     // from the original predicated block that would otherwise be vectorized.
6548     // Although not strictly necessary, we give up on instructions we know will
6549     // already be scalar to avoid traversing chains that are unlikely to be
6550     // beneficial.
6551     if (!I->hasOneUse() || PredInst->getParent() != I->getParent() ||
6552         isScalarAfterVectorization(I, VF))
6553       return false;
6554 
6555     // If the instruction is scalar with predication, it will be analyzed
6556     // separately. We ignore it within the context of PredInst.
6557     if (isScalarWithPredication(I))
6558       return false;
6559 
6560     // If any of the instruction's operands are uniform after vectorization,
6561     // the instruction cannot be scalarized. This prevents, for example, a
6562     // masked load from being scalarized.
6563     //
6564     // We assume we will only emit a value for lane zero of an instruction
6565     // marked uniform after vectorization, rather than VF identical values.
6566     // Thus, if we scalarize an instruction that uses a uniform, we would
6567     // create uses of values corresponding to the lanes we aren't emitting code
6568     // for. This behavior can be changed by allowing getScalarValue to clone
6569     // the lane zero values for uniforms rather than asserting.
6570     for (Use &U : I->operands())
6571       if (auto *J = dyn_cast<Instruction>(U.get()))
6572         if (isUniformAfterVectorization(J, VF))
6573           return false;
6574 
6575     // Otherwise, we can scalarize the instruction.
6576     return true;
6577   };
6578 
6579   // Compute the expected cost discount from scalarizing the entire expression
6580   // feeding the predicated instruction. We currently only consider expressions
6581   // that are single-use instruction chains.
6582   Worklist.push_back(PredInst);
6583   while (!Worklist.empty()) {
6584     Instruction *I = Worklist.pop_back_val();
6585 
6586     // If we've already analyzed the instruction, there's nothing to do.
6587     if (ScalarCosts.find(I) != ScalarCosts.end())
6588       continue;
6589 
6590     // Compute the cost of the vector instruction. Note that this cost already
6591     // includes the scalarization overhead of the predicated instruction.
6592     InstructionCost VectorCost = getInstructionCost(I, VF).first;
6593 
6594     // Compute the cost of the scalarized instruction. This cost is the cost of
6595     // the instruction as if it wasn't if-converted and instead remained in the
6596     // predicated block. We will scale this cost by block probability after
6597     // computing the scalarization overhead.
6598     InstructionCost ScalarCost =
6599         VF.getFixedValue() *
6600         getInstructionCost(I, ElementCount::getFixed(1)).first;
6601 
6602     // Compute the scalarization overhead of needed insertelement instructions
6603     // and phi nodes.
6604     if (isScalarWithPredication(I) && !I->getType()->isVoidTy()) {
6605       ScalarCost += TTI.getScalarizationOverhead(
6606           cast<VectorType>(ToVectorTy(I->getType(), VF)),
6607           APInt::getAllOnes(VF.getFixedValue()), true, false);
6608       ScalarCost +=
6609           VF.getFixedValue() *
6610           TTI.getCFInstrCost(Instruction::PHI, TTI::TCK_RecipThroughput);
6611     }
6612 
6613     // Compute the scalarization overhead of needed extractelement
6614     // instructions. For each of the instruction's operands, if the operand can
6615     // be scalarized, add it to the worklist; otherwise, account for the
6616     // overhead.
6617     for (Use &U : I->operands())
6618       if (auto *J = dyn_cast<Instruction>(U.get())) {
6619         assert(VectorType::isValidElementType(J->getType()) &&
6620                "Instruction has non-scalar type");
6621         if (canBeScalarized(J))
6622           Worklist.push_back(J);
6623         else if (needsExtract(J, VF)) {
6624           ScalarCost += TTI.getScalarizationOverhead(
6625               cast<VectorType>(ToVectorTy(J->getType(), VF)),
6626               APInt::getAllOnes(VF.getFixedValue()), false, true);
6627         }
6628       }
6629 
6630     // Scale the total scalar cost by block probability.
6631     ScalarCost /= getReciprocalPredBlockProb();
6632 
6633     // Compute the discount. A non-negative discount means the vector version
6634     // of the instruction costs more, and scalarizing would be beneficial.
6635     Discount += VectorCost - ScalarCost;
6636     ScalarCosts[I] = ScalarCost;
6637   }
6638 
6639   return *Discount.getValue();
6640 }
6641 
6642 LoopVectorizationCostModel::VectorizationCostTy
6643 LoopVectorizationCostModel::expectedCost(
6644     ElementCount VF, SmallVectorImpl<InstructionVFPair> *Invalid) {
6645   VectorizationCostTy Cost;
6646 
6647   // For each block.
6648   for (BasicBlock *BB : TheLoop->blocks()) {
6649     VectorizationCostTy BlockCost;
6650 
6651     // For each instruction in the old loop.
6652     for (Instruction &I : BB->instructionsWithoutDebug()) {
6653       // Skip ignored values.
6654       if (ValuesToIgnore.count(&I) ||
6655           (VF.isVector() && VecValuesToIgnore.count(&I)))
6656         continue;
6657 
6658       VectorizationCostTy C = getInstructionCost(&I, VF);
6659 
6660       // Check if we should override the cost.
6661       if (C.first.isValid() &&
6662           ForceTargetInstructionCost.getNumOccurrences() > 0)
6663         C.first = InstructionCost(ForceTargetInstructionCost);
6664 
6665       // Keep a list of instructions with invalid costs.
6666       if (Invalid && !C.first.isValid())
6667         Invalid->emplace_back(&I, VF);
6668 
6669       BlockCost.first += C.first;
6670       BlockCost.second |= C.second;
6671       LLVM_DEBUG(dbgs() << "LV: Found an estimated cost of " << C.first
6672                         << " for VF " << VF << " For instruction: " << I
6673                         << '\n');
6674     }
6675 
6676     // If we are vectorizing a predicated block, it will have been
6677     // if-converted. This means that the block's instructions (aside from
6678     // stores and instructions that may divide by zero) will now be
6679     // unconditionally executed. For the scalar case, we may not always execute
6680     // the predicated block, if it is an if-else block. Thus, scale the block's
6681     // cost by the probability of executing it. blockNeedsPredication from
6682     // Legal is used so as to not include all blocks in tail folded loops.
6683     if (VF.isScalar() && Legal->blockNeedsPredication(BB))
6684       BlockCost.first /= getReciprocalPredBlockProb();
6685 
6686     Cost.first += BlockCost.first;
6687     Cost.second |= BlockCost.second;
6688   }
6689 
6690   return Cost;
6691 }
6692 
6693 /// Gets Address Access SCEV after verifying that the access pattern
6694 /// is loop invariant except the induction variable dependence.
6695 ///
6696 /// This SCEV can be sent to the Target in order to estimate the address
6697 /// calculation cost.
6698 static const SCEV *getAddressAccessSCEV(
6699               Value *Ptr,
6700               LoopVectorizationLegality *Legal,
6701               PredicatedScalarEvolution &PSE,
6702               const Loop *TheLoop) {
6703 
6704   auto *Gep = dyn_cast<GetElementPtrInst>(Ptr);
6705   if (!Gep)
6706     return nullptr;
6707 
6708   // We are looking for a gep with all loop invariant indices except for one
6709   // which should be an induction variable.
6710   auto SE = PSE.getSE();
6711   unsigned NumOperands = Gep->getNumOperands();
6712   for (unsigned i = 1; i < NumOperands; ++i) {
6713     Value *Opd = Gep->getOperand(i);
6714     if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
6715         !Legal->isInductionVariable(Opd))
6716       return nullptr;
6717   }
6718 
6719   // Now we know we have a GEP ptr, %inv, %ind, %inv. return the Ptr SCEV.
6720   return PSE.getSCEV(Ptr);
6721 }
6722 
6723 static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
6724   return Legal->hasStride(I->getOperand(0)) ||
6725          Legal->hasStride(I->getOperand(1));
6726 }
6727 
6728 InstructionCost
6729 LoopVectorizationCostModel::getMemInstScalarizationCost(Instruction *I,
6730                                                         ElementCount VF) {
6731   assert(VF.isVector() &&
6732          "Scalarization cost of instruction implies vectorization.");
6733   if (VF.isScalable())
6734     return InstructionCost::getInvalid();
6735 
6736   Type *ValTy = getLoadStoreType(I);
6737   auto SE = PSE.getSE();
6738 
6739   unsigned AS = getLoadStoreAddressSpace(I);
6740   Value *Ptr = getLoadStorePointerOperand(I);
6741   Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
6742   // NOTE: PtrTy is a vector to signal `TTI::getAddressComputationCost`
6743   //       that it is being called from this specific place.
6744 
6745   // Figure out whether the access is strided and get the stride value
6746   // if it's known in compile time
6747   const SCEV *PtrSCEV = getAddressAccessSCEV(Ptr, Legal, PSE, TheLoop);
6748 
6749   // Get the cost of the scalar memory instruction and address computation.
6750   InstructionCost Cost =
6751       VF.getKnownMinValue() * TTI.getAddressComputationCost(PtrTy, SE, PtrSCEV);
6752 
6753   // Don't pass *I here, since it is scalar but will actually be part of a
6754   // vectorized loop where the user of it is a vectorized instruction.
6755   const Align Alignment = getLoadStoreAlignment(I);
6756   Cost += VF.getKnownMinValue() *
6757           TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(), Alignment,
6758                               AS, TTI::TCK_RecipThroughput);
6759 
6760   // Get the overhead of the extractelement and insertelement instructions
6761   // we might create due to scalarization.
6762   Cost += getScalarizationOverhead(I, VF);
6763 
6764   // If we have a predicated load/store, it will need extra i1 extracts and
6765   // conditional branches, but may not be executed for each vector lane. Scale
6766   // the cost by the probability of executing the predicated block.
6767   if (isPredicatedInst(I)) {
6768     Cost /= getReciprocalPredBlockProb();
6769 
6770     // Add the cost of an i1 extract and a branch
6771     auto *Vec_i1Ty =
6772         VectorType::get(IntegerType::getInt1Ty(ValTy->getContext()), VF);
6773     Cost += TTI.getScalarizationOverhead(
6774         Vec_i1Ty, APInt::getAllOnes(VF.getKnownMinValue()),
6775         /*Insert=*/false, /*Extract=*/true);
6776     Cost += TTI.getCFInstrCost(Instruction::Br, TTI::TCK_RecipThroughput);
6777 
6778     if (useEmulatedMaskMemRefHack(I))
6779       // Artificially setting to a high enough value to practically disable
6780       // vectorization with such operations.
6781       Cost = 3000000;
6782   }
6783 
6784   return Cost;
6785 }
6786 
6787 InstructionCost
6788 LoopVectorizationCostModel::getConsecutiveMemOpCost(Instruction *I,
6789                                                     ElementCount VF) {
6790   Type *ValTy = getLoadStoreType(I);
6791   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
6792   Value *Ptr = getLoadStorePointerOperand(I);
6793   unsigned AS = getLoadStoreAddressSpace(I);
6794   int ConsecutiveStride = Legal->isConsecutivePtr(ValTy, Ptr);
6795   enum TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
6796 
6797   assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
6798          "Stride should be 1 or -1 for consecutive memory access");
6799   const Align Alignment = getLoadStoreAlignment(I);
6800   InstructionCost Cost = 0;
6801   if (Legal->isMaskRequired(I))
6802     Cost += TTI.getMaskedMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS,
6803                                       CostKind);
6804   else
6805     Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS,
6806                                 CostKind, I);
6807 
6808   bool Reverse = ConsecutiveStride < 0;
6809   if (Reverse)
6810     Cost +=
6811         TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, None, 0);
6812   return Cost;
6813 }
6814 
6815 InstructionCost
6816 LoopVectorizationCostModel::getUniformMemOpCost(Instruction *I,
6817                                                 ElementCount VF) {
6818   assert(Legal->isUniformMemOp(*I));
6819 
6820   Type *ValTy = getLoadStoreType(I);
6821   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
6822   const Align Alignment = getLoadStoreAlignment(I);
6823   unsigned AS = getLoadStoreAddressSpace(I);
6824   enum TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
6825   if (isa<LoadInst>(I)) {
6826     return TTI.getAddressComputationCost(ValTy) +
6827            TTI.getMemoryOpCost(Instruction::Load, ValTy, Alignment, AS,
6828                                CostKind) +
6829            TTI.getShuffleCost(TargetTransformInfo::SK_Broadcast, VectorTy);
6830   }
6831   StoreInst *SI = cast<StoreInst>(I);
6832 
6833   bool isLoopInvariantStoreValue = Legal->isUniform(SI->getValueOperand());
6834   return TTI.getAddressComputationCost(ValTy) +
6835          TTI.getMemoryOpCost(Instruction::Store, ValTy, Alignment, AS,
6836                              CostKind) +
6837          (isLoopInvariantStoreValue
6838               ? 0
6839               : TTI.getVectorInstrCost(Instruction::ExtractElement, VectorTy,
6840                                        VF.getKnownMinValue() - 1));
6841 }
6842 
6843 InstructionCost
6844 LoopVectorizationCostModel::getGatherScatterCost(Instruction *I,
6845                                                  ElementCount VF) {
6846   Type *ValTy = getLoadStoreType(I);
6847   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
6848   const Align Alignment = getLoadStoreAlignment(I);
6849   const Value *Ptr = getLoadStorePointerOperand(I);
6850 
6851   return TTI.getAddressComputationCost(VectorTy) +
6852          TTI.getGatherScatterOpCost(
6853              I->getOpcode(), VectorTy, Ptr, Legal->isMaskRequired(I), Alignment,
6854              TargetTransformInfo::TCK_RecipThroughput, I);
6855 }
6856 
6857 InstructionCost
6858 LoopVectorizationCostModel::getInterleaveGroupCost(Instruction *I,
6859                                                    ElementCount VF) {
6860   // TODO: Once we have support for interleaving with scalable vectors
6861   // we can calculate the cost properly here.
6862   if (VF.isScalable())
6863     return InstructionCost::getInvalid();
6864 
6865   Type *ValTy = getLoadStoreType(I);
6866   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
6867   unsigned AS = getLoadStoreAddressSpace(I);
6868 
6869   auto Group = getInterleavedAccessGroup(I);
6870   assert(Group && "Fail to get an interleaved access group.");
6871 
6872   unsigned InterleaveFactor = Group->getFactor();
6873   auto *WideVecTy = VectorType::get(ValTy, VF * InterleaveFactor);
6874 
6875   // Holds the indices of existing members in the interleaved group.
6876   SmallVector<unsigned, 4> Indices;
6877   for (unsigned IF = 0; IF < InterleaveFactor; IF++)
6878     if (Group->getMember(IF))
6879       Indices.push_back(IF);
6880 
6881   // Calculate the cost of the whole interleaved group.
6882   bool UseMaskForGaps =
6883       (Group->requiresScalarEpilogue() && !isScalarEpilogueAllowed()) ||
6884       (isa<StoreInst>(I) && (Group->getNumMembers() < Group->getFactor()));
6885   InstructionCost Cost = TTI.getInterleavedMemoryOpCost(
6886       I->getOpcode(), WideVecTy, Group->getFactor(), Indices, Group->getAlign(),
6887       AS, TTI::TCK_RecipThroughput, Legal->isMaskRequired(I), UseMaskForGaps);
6888 
6889   if (Group->isReverse()) {
6890     // TODO: Add support for reversed masked interleaved access.
6891     assert(!Legal->isMaskRequired(I) &&
6892            "Reverse masked interleaved access not supported.");
6893     Cost +=
6894         Group->getNumMembers() *
6895         TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, None, 0);
6896   }
6897   return Cost;
6898 }
6899 
6900 Optional<InstructionCost> LoopVectorizationCostModel::getReductionPatternCost(
6901     Instruction *I, ElementCount VF, Type *Ty, TTI::TargetCostKind CostKind) {
6902   using namespace llvm::PatternMatch;
6903   // Early exit for no inloop reductions
6904   if (InLoopReductionChains.empty() || VF.isScalar() || !isa<VectorType>(Ty))
6905     return None;
6906   auto *VectorTy = cast<VectorType>(Ty);
6907 
6908   // We are looking for a pattern of, and finding the minimal acceptable cost:
6909   //  reduce(mul(ext(A), ext(B))) or
6910   //  reduce(mul(A, B)) or
6911   //  reduce(ext(A)) or
6912   //  reduce(A).
6913   // The basic idea is that we walk down the tree to do that, finding the root
6914   // reduction instruction in InLoopReductionImmediateChains. From there we find
6915   // the pattern of mul/ext and test the cost of the entire pattern vs the cost
6916   // of the components. If the reduction cost is lower then we return it for the
6917   // reduction instruction and 0 for the other instructions in the pattern. If
6918   // it is not we return an invalid cost specifying the orignal cost method
6919   // should be used.
6920   Instruction *RetI = I;
6921   if (match(RetI, m_ZExtOrSExt(m_Value()))) {
6922     if (!RetI->hasOneUser())
6923       return None;
6924     RetI = RetI->user_back();
6925   }
6926   if (match(RetI, m_Mul(m_Value(), m_Value())) &&
6927       RetI->user_back()->getOpcode() == Instruction::Add) {
6928     if (!RetI->hasOneUser())
6929       return None;
6930     RetI = RetI->user_back();
6931   }
6932 
6933   // Test if the found instruction is a reduction, and if not return an invalid
6934   // cost specifying the parent to use the original cost modelling.
6935   if (!InLoopReductionImmediateChains.count(RetI))
6936     return None;
6937 
6938   // Find the reduction this chain is a part of and calculate the basic cost of
6939   // the reduction on its own.
6940   Instruction *LastChain = InLoopReductionImmediateChains[RetI];
6941   Instruction *ReductionPhi = LastChain;
6942   while (!isa<PHINode>(ReductionPhi))
6943     ReductionPhi = InLoopReductionImmediateChains[ReductionPhi];
6944 
6945   const RecurrenceDescriptor &RdxDesc =
6946       Legal->getReductionVars().find(cast<PHINode>(ReductionPhi))->second;
6947 
6948   InstructionCost BaseCost = TTI.getArithmeticReductionCost(
6949       RdxDesc.getOpcode(), VectorTy, RdxDesc.getFastMathFlags(), CostKind);
6950 
6951   // For a call to the llvm.fmuladd intrinsic we need to add the cost of a
6952   // normal fmul instruction to the cost of the fadd reduction.
6953   if (RdxDesc.getRecurrenceKind() == RecurKind::FMulAdd)
6954     BaseCost +=
6955         TTI.getArithmeticInstrCost(Instruction::FMul, VectorTy, CostKind);
6956 
6957   // If we're using ordered reductions then we can just return the base cost
6958   // here, since getArithmeticReductionCost calculates the full ordered
6959   // reduction cost when FP reassociation is not allowed.
6960   if (useOrderedReductions(RdxDesc))
6961     return BaseCost;
6962 
6963   // Get the operand that was not the reduction chain and match it to one of the
6964   // patterns, returning the better cost if it is found.
6965   Instruction *RedOp = RetI->getOperand(1) == LastChain
6966                            ? dyn_cast<Instruction>(RetI->getOperand(0))
6967                            : dyn_cast<Instruction>(RetI->getOperand(1));
6968 
6969   VectorTy = VectorType::get(I->getOperand(0)->getType(), VectorTy);
6970 
6971   Instruction *Op0, *Op1;
6972   if (RedOp &&
6973       match(RedOp,
6974             m_ZExtOrSExt(m_Mul(m_Instruction(Op0), m_Instruction(Op1)))) &&
6975       match(Op0, m_ZExtOrSExt(m_Value())) &&
6976       Op0->getOpcode() == Op1->getOpcode() &&
6977       Op0->getOperand(0)->getType() == Op1->getOperand(0)->getType() &&
6978       !TheLoop->isLoopInvariant(Op0) && !TheLoop->isLoopInvariant(Op1) &&
6979       (Op0->getOpcode() == RedOp->getOpcode() || Op0 == Op1)) {
6980 
6981     // Matched reduce(ext(mul(ext(A), ext(B)))
6982     // Note that the extend opcodes need to all match, or if A==B they will have
6983     // been converted to zext(mul(sext(A), sext(A))) as it is known positive,
6984     // which is equally fine.
6985     bool IsUnsigned = isa<ZExtInst>(Op0);
6986     auto *ExtType = VectorType::get(Op0->getOperand(0)->getType(), VectorTy);
6987     auto *MulType = VectorType::get(Op0->getType(), VectorTy);
6988 
6989     InstructionCost ExtCost =
6990         TTI.getCastInstrCost(Op0->getOpcode(), MulType, ExtType,
6991                              TTI::CastContextHint::None, CostKind, Op0);
6992     InstructionCost MulCost =
6993         TTI.getArithmeticInstrCost(Instruction::Mul, MulType, CostKind);
6994     InstructionCost Ext2Cost =
6995         TTI.getCastInstrCost(RedOp->getOpcode(), VectorTy, MulType,
6996                              TTI::CastContextHint::None, CostKind, RedOp);
6997 
6998     InstructionCost RedCost = TTI.getExtendedAddReductionCost(
6999         /*IsMLA=*/true, IsUnsigned, RdxDesc.getRecurrenceType(), ExtType,
7000         CostKind);
7001 
7002     if (RedCost.isValid() &&
7003         RedCost < ExtCost * 2 + MulCost + Ext2Cost + BaseCost)
7004       return I == RetI ? RedCost : 0;
7005   } else if (RedOp && match(RedOp, m_ZExtOrSExt(m_Value())) &&
7006              !TheLoop->isLoopInvariant(RedOp)) {
7007     // Matched reduce(ext(A))
7008     bool IsUnsigned = isa<ZExtInst>(RedOp);
7009     auto *ExtType = VectorType::get(RedOp->getOperand(0)->getType(), VectorTy);
7010     InstructionCost RedCost = TTI.getExtendedAddReductionCost(
7011         /*IsMLA=*/false, IsUnsigned, RdxDesc.getRecurrenceType(), ExtType,
7012         CostKind);
7013 
7014     InstructionCost ExtCost =
7015         TTI.getCastInstrCost(RedOp->getOpcode(), VectorTy, ExtType,
7016                              TTI::CastContextHint::None, CostKind, RedOp);
7017     if (RedCost.isValid() && RedCost < BaseCost + ExtCost)
7018       return I == RetI ? RedCost : 0;
7019   } else if (RedOp &&
7020              match(RedOp, m_Mul(m_Instruction(Op0), m_Instruction(Op1)))) {
7021     if (match(Op0, m_ZExtOrSExt(m_Value())) &&
7022         Op0->getOpcode() == Op1->getOpcode() &&
7023         !TheLoop->isLoopInvariant(Op0) && !TheLoop->isLoopInvariant(Op1)) {
7024       bool IsUnsigned = isa<ZExtInst>(Op0);
7025       Type *Op0Ty = Op0->getOperand(0)->getType();
7026       Type *Op1Ty = Op1->getOperand(0)->getType();
7027       Type *LargestOpTy =
7028           Op0Ty->getIntegerBitWidth() < Op1Ty->getIntegerBitWidth() ? Op1Ty
7029                                                                     : Op0Ty;
7030       auto *ExtType = VectorType::get(LargestOpTy, VectorTy);
7031 
7032       // Matched reduce(mul(ext(A), ext(B))), where the two ext may be of
7033       // different sizes. We take the largest type as the ext to reduce, and add
7034       // the remaining cost as, for example reduce(mul(ext(ext(A)), ext(B))).
7035       InstructionCost ExtCost0 = TTI.getCastInstrCost(
7036           Op0->getOpcode(), VectorTy, VectorType::get(Op0Ty, VectorTy),
7037           TTI::CastContextHint::None, CostKind, Op0);
7038       InstructionCost ExtCost1 = TTI.getCastInstrCost(
7039           Op1->getOpcode(), VectorTy, VectorType::get(Op1Ty, VectorTy),
7040           TTI::CastContextHint::None, CostKind, Op1);
7041       InstructionCost MulCost =
7042           TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy, CostKind);
7043 
7044       InstructionCost RedCost = TTI.getExtendedAddReductionCost(
7045           /*IsMLA=*/true, IsUnsigned, RdxDesc.getRecurrenceType(), ExtType,
7046           CostKind);
7047       InstructionCost ExtraExtCost = 0;
7048       if (Op0Ty != LargestOpTy || Op1Ty != LargestOpTy) {
7049         Instruction *ExtraExtOp = (Op0Ty != LargestOpTy) ? Op0 : Op1;
7050         ExtraExtCost = TTI.getCastInstrCost(
7051             ExtraExtOp->getOpcode(), ExtType,
7052             VectorType::get(ExtraExtOp->getOperand(0)->getType(), VectorTy),
7053             TTI::CastContextHint::None, CostKind, ExtraExtOp);
7054       }
7055 
7056       if (RedCost.isValid() &&
7057           (RedCost + ExtraExtCost) < (ExtCost0 + ExtCost1 + MulCost + BaseCost))
7058         return I == RetI ? RedCost : 0;
7059     } else if (!match(I, m_ZExtOrSExt(m_Value()))) {
7060       // Matched reduce(mul())
7061       InstructionCost MulCost =
7062           TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy, CostKind);
7063 
7064       InstructionCost RedCost = TTI.getExtendedAddReductionCost(
7065           /*IsMLA=*/true, true, RdxDesc.getRecurrenceType(), VectorTy,
7066           CostKind);
7067 
7068       if (RedCost.isValid() && RedCost < MulCost + BaseCost)
7069         return I == RetI ? RedCost : 0;
7070     }
7071   }
7072 
7073   return I == RetI ? Optional<InstructionCost>(BaseCost) : None;
7074 }
7075 
7076 InstructionCost
7077 LoopVectorizationCostModel::getMemoryInstructionCost(Instruction *I,
7078                                                      ElementCount VF) {
7079   // Calculate scalar cost only. Vectorization cost should be ready at this
7080   // moment.
7081   if (VF.isScalar()) {
7082     Type *ValTy = getLoadStoreType(I);
7083     const Align Alignment = getLoadStoreAlignment(I);
7084     unsigned AS = getLoadStoreAddressSpace(I);
7085 
7086     return TTI.getAddressComputationCost(ValTy) +
7087            TTI.getMemoryOpCost(I->getOpcode(), ValTy, Alignment, AS,
7088                                TTI::TCK_RecipThroughput, I);
7089   }
7090   return getWideningCost(I, VF);
7091 }
7092 
7093 LoopVectorizationCostModel::VectorizationCostTy
7094 LoopVectorizationCostModel::getInstructionCost(Instruction *I,
7095                                                ElementCount VF) {
7096   // If we know that this instruction will remain uniform, check the cost of
7097   // the scalar version.
7098   if (isUniformAfterVectorization(I, VF))
7099     VF = ElementCount::getFixed(1);
7100 
7101   if (VF.isVector() && isProfitableToScalarize(I, VF))
7102     return VectorizationCostTy(InstsToScalarize[VF][I], false);
7103 
7104   // Forced scalars do not have any scalarization overhead.
7105   auto ForcedScalar = ForcedScalars.find(VF);
7106   if (VF.isVector() && ForcedScalar != ForcedScalars.end()) {
7107     auto InstSet = ForcedScalar->second;
7108     if (InstSet.count(I))
7109       return VectorizationCostTy(
7110           (getInstructionCost(I, ElementCount::getFixed(1)).first *
7111            VF.getKnownMinValue()),
7112           false);
7113   }
7114 
7115   Type *VectorTy;
7116   InstructionCost C = getInstructionCost(I, VF, VectorTy);
7117 
7118   bool TypeNotScalarized = false;
7119   if (VF.isVector() && VectorTy->isVectorTy()) {
7120     unsigned NumParts = TTI.getNumberOfParts(VectorTy);
7121     if (NumParts)
7122       TypeNotScalarized = NumParts < VF.getKnownMinValue();
7123     else
7124       C = InstructionCost::getInvalid();
7125   }
7126   return VectorizationCostTy(C, TypeNotScalarized);
7127 }
7128 
7129 InstructionCost
7130 LoopVectorizationCostModel::getScalarizationOverhead(Instruction *I,
7131                                                      ElementCount VF) const {
7132 
7133   // There is no mechanism yet to create a scalable scalarization loop,
7134   // so this is currently Invalid.
7135   if (VF.isScalable())
7136     return InstructionCost::getInvalid();
7137 
7138   if (VF.isScalar())
7139     return 0;
7140 
7141   InstructionCost Cost = 0;
7142   Type *RetTy = ToVectorTy(I->getType(), VF);
7143   if (!RetTy->isVoidTy() &&
7144       (!isa<LoadInst>(I) || !TTI.supportsEfficientVectorElementLoadStore()))
7145     Cost += TTI.getScalarizationOverhead(
7146         cast<VectorType>(RetTy), APInt::getAllOnes(VF.getKnownMinValue()), true,
7147         false);
7148 
7149   // Some targets keep addresses scalar.
7150   if (isa<LoadInst>(I) && !TTI.prefersVectorizedAddressing())
7151     return Cost;
7152 
7153   // Some targets support efficient element stores.
7154   if (isa<StoreInst>(I) && TTI.supportsEfficientVectorElementLoadStore())
7155     return Cost;
7156 
7157   // Collect operands to consider.
7158   CallInst *CI = dyn_cast<CallInst>(I);
7159   Instruction::op_range Ops = CI ? CI->args() : I->operands();
7160 
7161   // Skip operands that do not require extraction/scalarization and do not incur
7162   // any overhead.
7163   SmallVector<Type *> Tys;
7164   for (auto *V : filterExtractingOperands(Ops, VF))
7165     Tys.push_back(MaybeVectorizeType(V->getType(), VF));
7166   return Cost + TTI.getOperandsScalarizationOverhead(
7167                     filterExtractingOperands(Ops, VF), Tys);
7168 }
7169 
7170 void LoopVectorizationCostModel::setCostBasedWideningDecision(ElementCount VF) {
7171   if (VF.isScalar())
7172     return;
7173   NumPredStores = 0;
7174   for (BasicBlock *BB : TheLoop->blocks()) {
7175     // For each instruction in the old loop.
7176     for (Instruction &I : *BB) {
7177       Value *Ptr =  getLoadStorePointerOperand(&I);
7178       if (!Ptr)
7179         continue;
7180 
7181       // TODO: We should generate better code and update the cost model for
7182       // predicated uniform stores. Today they are treated as any other
7183       // predicated store (see added test cases in
7184       // invariant-store-vectorization.ll).
7185       if (isa<StoreInst>(&I) && isScalarWithPredication(&I))
7186         NumPredStores++;
7187 
7188       if (Legal->isUniformMemOp(I)) {
7189         // TODO: Avoid replicating loads and stores instead of
7190         // relying on instcombine to remove them.
7191         // Load: Scalar load + broadcast
7192         // Store: Scalar store + isLoopInvariantStoreValue ? 0 : extract
7193         InstructionCost Cost;
7194         if (isa<StoreInst>(&I) && VF.isScalable() &&
7195             isLegalGatherOrScatter(&I)) {
7196           Cost = getGatherScatterCost(&I, VF);
7197           setWideningDecision(&I, VF, CM_GatherScatter, Cost);
7198         } else {
7199           assert((isa<LoadInst>(&I) || !VF.isScalable()) &&
7200                  "Cannot yet scalarize uniform stores");
7201           Cost = getUniformMemOpCost(&I, VF);
7202           setWideningDecision(&I, VF, CM_Scalarize, Cost);
7203         }
7204         continue;
7205       }
7206 
7207       // We assume that widening is the best solution when possible.
7208       if (memoryInstructionCanBeWidened(&I, VF)) {
7209         InstructionCost Cost = getConsecutiveMemOpCost(&I, VF);
7210         int ConsecutiveStride = Legal->isConsecutivePtr(
7211             getLoadStoreType(&I), getLoadStorePointerOperand(&I));
7212         assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
7213                "Expected consecutive stride.");
7214         InstWidening Decision =
7215             ConsecutiveStride == 1 ? CM_Widen : CM_Widen_Reverse;
7216         setWideningDecision(&I, VF, Decision, Cost);
7217         continue;
7218       }
7219 
7220       // Choose between Interleaving, Gather/Scatter or Scalarization.
7221       InstructionCost InterleaveCost = InstructionCost::getInvalid();
7222       unsigned NumAccesses = 1;
7223       if (isAccessInterleaved(&I)) {
7224         auto Group = getInterleavedAccessGroup(&I);
7225         assert(Group && "Fail to get an interleaved access group.");
7226 
7227         // Make one decision for the whole group.
7228         if (getWideningDecision(&I, VF) != CM_Unknown)
7229           continue;
7230 
7231         NumAccesses = Group->getNumMembers();
7232         if (interleavedAccessCanBeWidened(&I, VF))
7233           InterleaveCost = getInterleaveGroupCost(&I, VF);
7234       }
7235 
7236       InstructionCost GatherScatterCost =
7237           isLegalGatherOrScatter(&I)
7238               ? getGatherScatterCost(&I, VF) * NumAccesses
7239               : InstructionCost::getInvalid();
7240 
7241       InstructionCost ScalarizationCost =
7242           getMemInstScalarizationCost(&I, VF) * NumAccesses;
7243 
7244       // Choose better solution for the current VF,
7245       // write down this decision and use it during vectorization.
7246       InstructionCost Cost;
7247       InstWidening Decision;
7248       if (InterleaveCost <= GatherScatterCost &&
7249           InterleaveCost < ScalarizationCost) {
7250         Decision = CM_Interleave;
7251         Cost = InterleaveCost;
7252       } else if (GatherScatterCost < ScalarizationCost) {
7253         Decision = CM_GatherScatter;
7254         Cost = GatherScatterCost;
7255       } else {
7256         Decision = CM_Scalarize;
7257         Cost = ScalarizationCost;
7258       }
7259       // If the instructions belongs to an interleave group, the whole group
7260       // receives the same decision. The whole group receives the cost, but
7261       // the cost will actually be assigned to one instruction.
7262       if (auto Group = getInterleavedAccessGroup(&I))
7263         setWideningDecision(Group, VF, Decision, Cost);
7264       else
7265         setWideningDecision(&I, VF, Decision, Cost);
7266     }
7267   }
7268 
7269   // Make sure that any load of address and any other address computation
7270   // remains scalar unless there is gather/scatter support. This avoids
7271   // inevitable extracts into address registers, and also has the benefit of
7272   // activating LSR more, since that pass can't optimize vectorized
7273   // addresses.
7274   if (TTI.prefersVectorizedAddressing())
7275     return;
7276 
7277   // Start with all scalar pointer uses.
7278   SmallPtrSet<Instruction *, 8> AddrDefs;
7279   for (BasicBlock *BB : TheLoop->blocks())
7280     for (Instruction &I : *BB) {
7281       Instruction *PtrDef =
7282         dyn_cast_or_null<Instruction>(getLoadStorePointerOperand(&I));
7283       if (PtrDef && TheLoop->contains(PtrDef) &&
7284           getWideningDecision(&I, VF) != CM_GatherScatter)
7285         AddrDefs.insert(PtrDef);
7286     }
7287 
7288   // Add all instructions used to generate the addresses.
7289   SmallVector<Instruction *, 4> Worklist;
7290   append_range(Worklist, AddrDefs);
7291   while (!Worklist.empty()) {
7292     Instruction *I = Worklist.pop_back_val();
7293     for (auto &Op : I->operands())
7294       if (auto *InstOp = dyn_cast<Instruction>(Op))
7295         if ((InstOp->getParent() == I->getParent()) && !isa<PHINode>(InstOp) &&
7296             AddrDefs.insert(InstOp).second)
7297           Worklist.push_back(InstOp);
7298   }
7299 
7300   for (auto *I : AddrDefs) {
7301     if (isa<LoadInst>(I)) {
7302       // Setting the desired widening decision should ideally be handled in
7303       // by cost functions, but since this involves the task of finding out
7304       // if the loaded register is involved in an address computation, it is
7305       // instead changed here when we know this is the case.
7306       InstWidening Decision = getWideningDecision(I, VF);
7307       if (Decision == CM_Widen || Decision == CM_Widen_Reverse)
7308         // Scalarize a widened load of address.
7309         setWideningDecision(
7310             I, VF, CM_Scalarize,
7311             (VF.getKnownMinValue() *
7312              getMemoryInstructionCost(I, ElementCount::getFixed(1))));
7313       else if (auto Group = getInterleavedAccessGroup(I)) {
7314         // Scalarize an interleave group of address loads.
7315         for (unsigned I = 0; I < Group->getFactor(); ++I) {
7316           if (Instruction *Member = Group->getMember(I))
7317             setWideningDecision(
7318                 Member, VF, CM_Scalarize,
7319                 (VF.getKnownMinValue() *
7320                  getMemoryInstructionCost(Member, ElementCount::getFixed(1))));
7321         }
7322       }
7323     } else
7324       // Make sure I gets scalarized and a cost estimate without
7325       // scalarization overhead.
7326       ForcedScalars[VF].insert(I);
7327   }
7328 }
7329 
7330 InstructionCost
7331 LoopVectorizationCostModel::getInstructionCost(Instruction *I, ElementCount VF,
7332                                                Type *&VectorTy) {
7333   Type *RetTy = I->getType();
7334   if (canTruncateToMinimalBitwidth(I, VF))
7335     RetTy = IntegerType::get(RetTy->getContext(), MinBWs[I]);
7336   auto SE = PSE.getSE();
7337   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
7338 
7339   auto hasSingleCopyAfterVectorization = [this](Instruction *I,
7340                                                 ElementCount VF) -> bool {
7341     if (VF.isScalar())
7342       return true;
7343 
7344     auto Scalarized = InstsToScalarize.find(VF);
7345     assert(Scalarized != InstsToScalarize.end() &&
7346            "VF not yet analyzed for scalarization profitability");
7347     return !Scalarized->second.count(I) &&
7348            llvm::all_of(I->users(), [&](User *U) {
7349              auto *UI = cast<Instruction>(U);
7350              return !Scalarized->second.count(UI);
7351            });
7352   };
7353   (void) hasSingleCopyAfterVectorization;
7354 
7355   if (isScalarAfterVectorization(I, VF)) {
7356     // With the exception of GEPs and PHIs, after scalarization there should
7357     // only be one copy of the instruction generated in the loop. This is
7358     // because the VF is either 1, or any instructions that need scalarizing
7359     // have already been dealt with by the the time we get here. As a result,
7360     // it means we don't have to multiply the instruction cost by VF.
7361     assert(I->getOpcode() == Instruction::GetElementPtr ||
7362            I->getOpcode() == Instruction::PHI ||
7363            (I->getOpcode() == Instruction::BitCast &&
7364             I->getType()->isPointerTy()) ||
7365            hasSingleCopyAfterVectorization(I, VF));
7366     VectorTy = RetTy;
7367   } else
7368     VectorTy = ToVectorTy(RetTy, VF);
7369 
7370   // TODO: We need to estimate the cost of intrinsic calls.
7371   switch (I->getOpcode()) {
7372   case Instruction::GetElementPtr:
7373     // We mark this instruction as zero-cost because the cost of GEPs in
7374     // vectorized code depends on whether the corresponding memory instruction
7375     // is scalarized or not. Therefore, we handle GEPs with the memory
7376     // instruction cost.
7377     return 0;
7378   case Instruction::Br: {
7379     // In cases of scalarized and predicated instructions, there will be VF
7380     // predicated blocks in the vectorized loop. Each branch around these
7381     // blocks requires also an extract of its vector compare i1 element.
7382     bool ScalarPredicatedBB = false;
7383     BranchInst *BI = cast<BranchInst>(I);
7384     if (VF.isVector() && BI->isConditional() &&
7385         (PredicatedBBsAfterVectorization.count(BI->getSuccessor(0)) ||
7386          PredicatedBBsAfterVectorization.count(BI->getSuccessor(1))))
7387       ScalarPredicatedBB = true;
7388 
7389     if (ScalarPredicatedBB) {
7390       // Not possible to scalarize scalable vector with predicated instructions.
7391       if (VF.isScalable())
7392         return InstructionCost::getInvalid();
7393       // Return cost for branches around scalarized and predicated blocks.
7394       auto *Vec_i1Ty =
7395           VectorType::get(IntegerType::getInt1Ty(RetTy->getContext()), VF);
7396       return (
7397           TTI.getScalarizationOverhead(
7398               Vec_i1Ty, APInt::getAllOnes(VF.getFixedValue()), false, true) +
7399           (TTI.getCFInstrCost(Instruction::Br, CostKind) * VF.getFixedValue()));
7400     } else if (I->getParent() == TheLoop->getLoopLatch() || VF.isScalar())
7401       // The back-edge branch will remain, as will all scalar branches.
7402       return TTI.getCFInstrCost(Instruction::Br, CostKind);
7403     else
7404       // This branch will be eliminated by if-conversion.
7405       return 0;
7406     // Note: We currently assume zero cost for an unconditional branch inside
7407     // a predicated block since it will become a fall-through, although we
7408     // may decide in the future to call TTI for all branches.
7409   }
7410   case Instruction::PHI: {
7411     auto *Phi = cast<PHINode>(I);
7412 
7413     // First-order recurrences are replaced by vector shuffles inside the loop.
7414     // NOTE: Don't use ToVectorTy as SK_ExtractSubvector expects a vector type.
7415     if (VF.isVector() && Legal->isFirstOrderRecurrence(Phi))
7416       return TTI.getShuffleCost(
7417           TargetTransformInfo::SK_ExtractSubvector, cast<VectorType>(VectorTy),
7418           None, VF.getKnownMinValue() - 1, FixedVectorType::get(RetTy, 1));
7419 
7420     // Phi nodes in non-header blocks (not inductions, reductions, etc.) are
7421     // converted into select instructions. We require N - 1 selects per phi
7422     // node, where N is the number of incoming values.
7423     if (VF.isVector() && Phi->getParent() != TheLoop->getHeader())
7424       return (Phi->getNumIncomingValues() - 1) *
7425              TTI.getCmpSelInstrCost(
7426                  Instruction::Select, ToVectorTy(Phi->getType(), VF),
7427                  ToVectorTy(Type::getInt1Ty(Phi->getContext()), VF),
7428                  CmpInst::BAD_ICMP_PREDICATE, CostKind);
7429 
7430     return TTI.getCFInstrCost(Instruction::PHI, CostKind);
7431   }
7432   case Instruction::UDiv:
7433   case Instruction::SDiv:
7434   case Instruction::URem:
7435   case Instruction::SRem:
7436     // If we have a predicated instruction, it may not be executed for each
7437     // vector lane. Get the scalarization cost and scale this amount by the
7438     // probability of executing the predicated block. If the instruction is not
7439     // predicated, we fall through to the next case.
7440     if (VF.isVector() && isScalarWithPredication(I)) {
7441       InstructionCost Cost = 0;
7442 
7443       // These instructions have a non-void type, so account for the phi nodes
7444       // that we will create. This cost is likely to be zero. The phi node
7445       // cost, if any, should be scaled by the block probability because it
7446       // models a copy at the end of each predicated block.
7447       Cost += VF.getKnownMinValue() *
7448               TTI.getCFInstrCost(Instruction::PHI, CostKind);
7449 
7450       // The cost of the non-predicated instruction.
7451       Cost += VF.getKnownMinValue() *
7452               TTI.getArithmeticInstrCost(I->getOpcode(), RetTy, CostKind);
7453 
7454       // The cost of insertelement and extractelement instructions needed for
7455       // scalarization.
7456       Cost += getScalarizationOverhead(I, VF);
7457 
7458       // Scale the cost by the probability of executing the predicated blocks.
7459       // This assumes the predicated block for each vector lane is equally
7460       // likely.
7461       return Cost / getReciprocalPredBlockProb();
7462     }
7463     LLVM_FALLTHROUGH;
7464   case Instruction::Add:
7465   case Instruction::FAdd:
7466   case Instruction::Sub:
7467   case Instruction::FSub:
7468   case Instruction::Mul:
7469   case Instruction::FMul:
7470   case Instruction::FDiv:
7471   case Instruction::FRem:
7472   case Instruction::Shl:
7473   case Instruction::LShr:
7474   case Instruction::AShr:
7475   case Instruction::And:
7476   case Instruction::Or:
7477   case Instruction::Xor: {
7478     // Since we will replace the stride by 1 the multiplication should go away.
7479     if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
7480       return 0;
7481 
7482     // Detect reduction patterns
7483     if (auto RedCost = getReductionPatternCost(I, VF, VectorTy, CostKind))
7484       return *RedCost;
7485 
7486     // Certain instructions can be cheaper to vectorize if they have a constant
7487     // second vector operand. One example of this are shifts on x86.
7488     Value *Op2 = I->getOperand(1);
7489     TargetTransformInfo::OperandValueProperties Op2VP;
7490     TargetTransformInfo::OperandValueKind Op2VK =
7491         TTI.getOperandInfo(Op2, Op2VP);
7492     if (Op2VK == TargetTransformInfo::OK_AnyValue && Legal->isUniform(Op2))
7493       Op2VK = TargetTransformInfo::OK_UniformValue;
7494 
7495     SmallVector<const Value *, 4> Operands(I->operand_values());
7496     return TTI.getArithmeticInstrCost(
7497         I->getOpcode(), VectorTy, CostKind, TargetTransformInfo::OK_AnyValue,
7498         Op2VK, TargetTransformInfo::OP_None, Op2VP, Operands, I);
7499   }
7500   case Instruction::FNeg: {
7501     return TTI.getArithmeticInstrCost(
7502         I->getOpcode(), VectorTy, CostKind, TargetTransformInfo::OK_AnyValue,
7503         TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None,
7504         TargetTransformInfo::OP_None, I->getOperand(0), I);
7505   }
7506   case Instruction::Select: {
7507     SelectInst *SI = cast<SelectInst>(I);
7508     const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
7509     bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
7510 
7511     const Value *Op0, *Op1;
7512     using namespace llvm::PatternMatch;
7513     if (!ScalarCond && (match(I, m_LogicalAnd(m_Value(Op0), m_Value(Op1))) ||
7514                         match(I, m_LogicalOr(m_Value(Op0), m_Value(Op1))))) {
7515       // select x, y, false --> x & y
7516       // select x, true, y --> x | y
7517       TTI::OperandValueProperties Op1VP = TTI::OP_None;
7518       TTI::OperandValueProperties Op2VP = TTI::OP_None;
7519       TTI::OperandValueKind Op1VK = TTI::getOperandInfo(Op0, Op1VP);
7520       TTI::OperandValueKind Op2VK = TTI::getOperandInfo(Op1, Op2VP);
7521       assert(Op0->getType()->getScalarSizeInBits() == 1 &&
7522               Op1->getType()->getScalarSizeInBits() == 1);
7523 
7524       SmallVector<const Value *, 2> Operands{Op0, Op1};
7525       return TTI.getArithmeticInstrCost(
7526           match(I, m_LogicalOr()) ? Instruction::Or : Instruction::And, VectorTy,
7527           CostKind, Op1VK, Op2VK, Op1VP, Op2VP, Operands, I);
7528     }
7529 
7530     Type *CondTy = SI->getCondition()->getType();
7531     if (!ScalarCond)
7532       CondTy = VectorType::get(CondTy, VF);
7533 
7534     CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
7535     if (auto *Cmp = dyn_cast<CmpInst>(SI->getCondition()))
7536       Pred = Cmp->getPredicate();
7537     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy, Pred,
7538                                   CostKind, I);
7539   }
7540   case Instruction::ICmp:
7541   case Instruction::FCmp: {
7542     Type *ValTy = I->getOperand(0)->getType();
7543     Instruction *Op0AsInstruction = dyn_cast<Instruction>(I->getOperand(0));
7544     if (canTruncateToMinimalBitwidth(Op0AsInstruction, VF))
7545       ValTy = IntegerType::get(ValTy->getContext(), MinBWs[Op0AsInstruction]);
7546     VectorTy = ToVectorTy(ValTy, VF);
7547     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, nullptr,
7548                                   cast<CmpInst>(I)->getPredicate(), CostKind,
7549                                   I);
7550   }
7551   case Instruction::Store:
7552   case Instruction::Load: {
7553     ElementCount Width = VF;
7554     if (Width.isVector()) {
7555       InstWidening Decision = getWideningDecision(I, Width);
7556       assert(Decision != CM_Unknown &&
7557              "CM decision should be taken at this point");
7558       if (Decision == CM_Scalarize)
7559         Width = ElementCount::getFixed(1);
7560     }
7561     VectorTy = ToVectorTy(getLoadStoreType(I), Width);
7562     return getMemoryInstructionCost(I, VF);
7563   }
7564   case Instruction::BitCast:
7565     if (I->getType()->isPointerTy())
7566       return 0;
7567     LLVM_FALLTHROUGH;
7568   case Instruction::ZExt:
7569   case Instruction::SExt:
7570   case Instruction::FPToUI:
7571   case Instruction::FPToSI:
7572   case Instruction::FPExt:
7573   case Instruction::PtrToInt:
7574   case Instruction::IntToPtr:
7575   case Instruction::SIToFP:
7576   case Instruction::UIToFP:
7577   case Instruction::Trunc:
7578   case Instruction::FPTrunc: {
7579     // Computes the CastContextHint from a Load/Store instruction.
7580     auto ComputeCCH = [&](Instruction *I) -> TTI::CastContextHint {
7581       assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
7582              "Expected a load or a store!");
7583 
7584       if (VF.isScalar() || !TheLoop->contains(I))
7585         return TTI::CastContextHint::Normal;
7586 
7587       switch (getWideningDecision(I, VF)) {
7588       case LoopVectorizationCostModel::CM_GatherScatter:
7589         return TTI::CastContextHint::GatherScatter;
7590       case LoopVectorizationCostModel::CM_Interleave:
7591         return TTI::CastContextHint::Interleave;
7592       case LoopVectorizationCostModel::CM_Scalarize:
7593       case LoopVectorizationCostModel::CM_Widen:
7594         return Legal->isMaskRequired(I) ? TTI::CastContextHint::Masked
7595                                         : TTI::CastContextHint::Normal;
7596       case LoopVectorizationCostModel::CM_Widen_Reverse:
7597         return TTI::CastContextHint::Reversed;
7598       case LoopVectorizationCostModel::CM_Unknown:
7599         llvm_unreachable("Instr did not go through cost modelling?");
7600       }
7601 
7602       llvm_unreachable("Unhandled case!");
7603     };
7604 
7605     unsigned Opcode = I->getOpcode();
7606     TTI::CastContextHint CCH = TTI::CastContextHint::None;
7607     // For Trunc, the context is the only user, which must be a StoreInst.
7608     if (Opcode == Instruction::Trunc || Opcode == Instruction::FPTrunc) {
7609       if (I->hasOneUse())
7610         if (StoreInst *Store = dyn_cast<StoreInst>(*I->user_begin()))
7611           CCH = ComputeCCH(Store);
7612     }
7613     // For Z/Sext, the context is the operand, which must be a LoadInst.
7614     else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt ||
7615              Opcode == Instruction::FPExt) {
7616       if (LoadInst *Load = dyn_cast<LoadInst>(I->getOperand(0)))
7617         CCH = ComputeCCH(Load);
7618     }
7619 
7620     // We optimize the truncation of induction variables having constant
7621     // integer steps. The cost of these truncations is the same as the scalar
7622     // operation.
7623     if (isOptimizableIVTruncate(I, VF)) {
7624       auto *Trunc = cast<TruncInst>(I);
7625       return TTI.getCastInstrCost(Instruction::Trunc, Trunc->getDestTy(),
7626                                   Trunc->getSrcTy(), CCH, CostKind, Trunc);
7627     }
7628 
7629     // Detect reduction patterns
7630     if (auto RedCost = getReductionPatternCost(I, VF, VectorTy, CostKind))
7631       return *RedCost;
7632 
7633     Type *SrcScalarTy = I->getOperand(0)->getType();
7634     Type *SrcVecTy =
7635         VectorTy->isVectorTy() ? ToVectorTy(SrcScalarTy, VF) : SrcScalarTy;
7636     if (canTruncateToMinimalBitwidth(I, VF)) {
7637       // This cast is going to be shrunk. This may remove the cast or it might
7638       // turn it into slightly different cast. For example, if MinBW == 16,
7639       // "zext i8 %1 to i32" becomes "zext i8 %1 to i16".
7640       //
7641       // Calculate the modified src and dest types.
7642       Type *MinVecTy = VectorTy;
7643       if (Opcode == Instruction::Trunc) {
7644         SrcVecTy = smallestIntegerVectorType(SrcVecTy, MinVecTy);
7645         VectorTy =
7646             largestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy);
7647       } else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
7648         SrcVecTy = largestIntegerVectorType(SrcVecTy, MinVecTy);
7649         VectorTy =
7650             smallestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy);
7651       }
7652     }
7653 
7654     return TTI.getCastInstrCost(Opcode, VectorTy, SrcVecTy, CCH, CostKind, I);
7655   }
7656   case Instruction::Call: {
7657     if (RecurrenceDescriptor::isFMulAddIntrinsic(I))
7658       if (auto RedCost = getReductionPatternCost(I, VF, VectorTy, CostKind))
7659         return *RedCost;
7660     bool NeedToScalarize;
7661     CallInst *CI = cast<CallInst>(I);
7662     InstructionCost CallCost = getVectorCallCost(CI, VF, NeedToScalarize);
7663     if (getVectorIntrinsicIDForCall(CI, TLI)) {
7664       InstructionCost IntrinsicCost = getVectorIntrinsicCost(CI, VF);
7665       return std::min(CallCost, IntrinsicCost);
7666     }
7667     return CallCost;
7668   }
7669   case Instruction::ExtractValue:
7670     return TTI.getInstructionCost(I, TTI::TCK_RecipThroughput);
7671   case Instruction::Alloca:
7672     // We cannot easily widen alloca to a scalable alloca, as
7673     // the result would need to be a vector of pointers.
7674     if (VF.isScalable())
7675       return InstructionCost::getInvalid();
7676     LLVM_FALLTHROUGH;
7677   default:
7678     // This opcode is unknown. Assume that it is the same as 'mul'.
7679     return TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy, CostKind);
7680   } // end of switch.
7681 }
7682 
7683 char LoopVectorize::ID = 0;
7684 
7685 static const char lv_name[] = "Loop Vectorization";
7686 
7687 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
7688 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
7689 INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
7690 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
7691 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
7692 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
7693 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
7694 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
7695 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
7696 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
7697 INITIALIZE_PASS_DEPENDENCY(LoopAccessLegacyAnalysis)
7698 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
7699 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
7700 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
7701 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
7702 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
7703 
7704 namespace llvm {
7705 
7706 Pass *createLoopVectorizePass() { return new LoopVectorize(); }
7707 
7708 Pass *createLoopVectorizePass(bool InterleaveOnlyWhenForced,
7709                               bool VectorizeOnlyWhenForced) {
7710   return new LoopVectorize(InterleaveOnlyWhenForced, VectorizeOnlyWhenForced);
7711 }
7712 
7713 } // end namespace llvm
7714 
7715 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
7716   // Check if the pointer operand of a load or store instruction is
7717   // consecutive.
7718   if (auto *Ptr = getLoadStorePointerOperand(Inst))
7719     return Legal->isConsecutivePtr(getLoadStoreType(Inst), Ptr);
7720   return false;
7721 }
7722 
7723 void LoopVectorizationCostModel::collectValuesToIgnore() {
7724   // Ignore ephemeral values.
7725   CodeMetrics::collectEphemeralValues(TheLoop, AC, ValuesToIgnore);
7726 
7727   // Ignore type-promoting instructions we identified during reduction
7728   // detection.
7729   for (auto &Reduction : Legal->getReductionVars()) {
7730     const RecurrenceDescriptor &RedDes = Reduction.second;
7731     const SmallPtrSetImpl<Instruction *> &Casts = RedDes.getCastInsts();
7732     VecValuesToIgnore.insert(Casts.begin(), Casts.end());
7733   }
7734   // Ignore type-casting instructions we identified during induction
7735   // detection.
7736   for (auto &Induction : Legal->getInductionVars()) {
7737     const InductionDescriptor &IndDes = Induction.second;
7738     const SmallVectorImpl<Instruction *> &Casts = IndDes.getCastInsts();
7739     VecValuesToIgnore.insert(Casts.begin(), Casts.end());
7740   }
7741 }
7742 
7743 void LoopVectorizationCostModel::collectInLoopReductions() {
7744   for (auto &Reduction : Legal->getReductionVars()) {
7745     PHINode *Phi = Reduction.first;
7746     const RecurrenceDescriptor &RdxDesc = Reduction.second;
7747 
7748     // We don't collect reductions that are type promoted (yet).
7749     if (RdxDesc.getRecurrenceType() != Phi->getType())
7750       continue;
7751 
7752     // If the target would prefer this reduction to happen "in-loop", then we
7753     // want to record it as such.
7754     unsigned Opcode = RdxDesc.getOpcode();
7755     if (!PreferInLoopReductions && !useOrderedReductions(RdxDesc) &&
7756         !TTI.preferInLoopReduction(Opcode, Phi->getType(),
7757                                    TargetTransformInfo::ReductionFlags()))
7758       continue;
7759 
7760     // Check that we can correctly put the reductions into the loop, by
7761     // finding the chain of operations that leads from the phi to the loop
7762     // exit value.
7763     SmallVector<Instruction *, 4> ReductionOperations =
7764         RdxDesc.getReductionOpChain(Phi, TheLoop);
7765     bool InLoop = !ReductionOperations.empty();
7766     if (InLoop) {
7767       InLoopReductionChains[Phi] = ReductionOperations;
7768       // Add the elements to InLoopReductionImmediateChains for cost modelling.
7769       Instruction *LastChain = Phi;
7770       for (auto *I : ReductionOperations) {
7771         InLoopReductionImmediateChains[I] = LastChain;
7772         LastChain = I;
7773       }
7774     }
7775     LLVM_DEBUG(dbgs() << "LV: Using " << (InLoop ? "inloop" : "out of loop")
7776                       << " reduction for phi: " << *Phi << "\n");
7777   }
7778 }
7779 
7780 // TODO: we could return a pair of values that specify the max VF and
7781 // min VF, to be used in `buildVPlans(MinVF, MaxVF)` instead of
7782 // `buildVPlans(VF, VF)`. We cannot do it because VPLAN at the moment
7783 // doesn't have a cost model that can choose which plan to execute if
7784 // more than one is generated.
7785 static unsigned determineVPlanVF(const unsigned WidestVectorRegBits,
7786                                  LoopVectorizationCostModel &CM) {
7787   unsigned WidestType;
7788   std::tie(std::ignore, WidestType) = CM.getSmallestAndWidestTypes();
7789   return WidestVectorRegBits / WidestType;
7790 }
7791 
7792 VectorizationFactor
7793 LoopVectorizationPlanner::planInVPlanNativePath(ElementCount UserVF) {
7794   assert(!UserVF.isScalable() && "scalable vectors not yet supported");
7795   ElementCount VF = UserVF;
7796   // Outer loop handling: They may require CFG and instruction level
7797   // transformations before even evaluating whether vectorization is profitable.
7798   // Since we cannot modify the incoming IR, we need to build VPlan upfront in
7799   // the vectorization pipeline.
7800   if (!OrigLoop->isInnermost()) {
7801     // If the user doesn't provide a vectorization factor, determine a
7802     // reasonable one.
7803     if (UserVF.isZero()) {
7804       VF = ElementCount::getFixed(determineVPlanVF(
7805           TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector)
7806               .getFixedSize(),
7807           CM));
7808       LLVM_DEBUG(dbgs() << "LV: VPlan computed VF " << VF << ".\n");
7809 
7810       // Make sure we have a VF > 1 for stress testing.
7811       if (VPlanBuildStressTest && (VF.isScalar() || VF.isZero())) {
7812         LLVM_DEBUG(dbgs() << "LV: VPlan stress testing: "
7813                           << "overriding computed VF.\n");
7814         VF = ElementCount::getFixed(4);
7815       }
7816     }
7817     assert(EnableVPlanNativePath && "VPlan-native path is not enabled.");
7818     assert(isPowerOf2_32(VF.getKnownMinValue()) &&
7819            "VF needs to be a power of two");
7820     LLVM_DEBUG(dbgs() << "LV: Using " << (!UserVF.isZero() ? "user " : "")
7821                       << "VF " << VF << " to build VPlans.\n");
7822     buildVPlans(VF, VF);
7823 
7824     // For VPlan build stress testing, we bail out after VPlan construction.
7825     if (VPlanBuildStressTest)
7826       return VectorizationFactor::Disabled();
7827 
7828     return {VF, 0 /*Cost*/};
7829   }
7830 
7831   LLVM_DEBUG(
7832       dbgs() << "LV: Not vectorizing. Inner loops aren't supported in the "
7833                 "VPlan-native path.\n");
7834   return VectorizationFactor::Disabled();
7835 }
7836 
7837 Optional<VectorizationFactor>
7838 LoopVectorizationPlanner::plan(ElementCount UserVF, unsigned UserIC) {
7839   assert(OrigLoop->isInnermost() && "Inner loop expected.");
7840   FixedScalableVFPair MaxFactors = CM.computeMaxVF(UserVF, UserIC);
7841   if (!MaxFactors) // Cases that should not to be vectorized nor interleaved.
7842     return None;
7843 
7844   // Invalidate interleave groups if all blocks of loop will be predicated.
7845   if (CM.blockNeedsPredicationForAnyReason(OrigLoop->getHeader()) &&
7846       !useMaskedInterleavedAccesses(*TTI)) {
7847     LLVM_DEBUG(
7848         dbgs()
7849         << "LV: Invalidate all interleaved groups due to fold-tail by masking "
7850            "which requires masked-interleaved support.\n");
7851     if (CM.InterleaveInfo.invalidateGroups())
7852       // Invalidating interleave groups also requires invalidating all decisions
7853       // based on them, which includes widening decisions and uniform and scalar
7854       // values.
7855       CM.invalidateCostModelingDecisions();
7856   }
7857 
7858   ElementCount MaxUserVF =
7859       UserVF.isScalable() ? MaxFactors.ScalableVF : MaxFactors.FixedVF;
7860   bool UserVFIsLegal = ElementCount::isKnownLE(UserVF, MaxUserVF);
7861   if (!UserVF.isZero() && UserVFIsLegal) {
7862     assert(isPowerOf2_32(UserVF.getKnownMinValue()) &&
7863            "VF needs to be a power of two");
7864     // Collect the instructions (and their associated costs) that will be more
7865     // profitable to scalarize.
7866     if (CM.selectUserVectorizationFactor(UserVF)) {
7867       LLVM_DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
7868       CM.collectInLoopReductions();
7869       buildVPlansWithVPRecipes(UserVF, UserVF);
7870       LLVM_DEBUG(printPlans(dbgs()));
7871       return {{UserVF, 0}};
7872     } else
7873       reportVectorizationInfo("UserVF ignored because of invalid costs.",
7874                               "InvalidCost", ORE, OrigLoop);
7875   }
7876 
7877   // Populate the set of Vectorization Factor Candidates.
7878   ElementCountSet VFCandidates;
7879   for (auto VF = ElementCount::getFixed(1);
7880        ElementCount::isKnownLE(VF, MaxFactors.FixedVF); VF *= 2)
7881     VFCandidates.insert(VF);
7882   for (auto VF = ElementCount::getScalable(1);
7883        ElementCount::isKnownLE(VF, MaxFactors.ScalableVF); VF *= 2)
7884     VFCandidates.insert(VF);
7885 
7886   for (const auto &VF : VFCandidates) {
7887     // Collect Uniform and Scalar instructions after vectorization with VF.
7888     CM.collectUniformsAndScalars(VF);
7889 
7890     // Collect the instructions (and their associated costs) that will be more
7891     // profitable to scalarize.
7892     if (VF.isVector())
7893       CM.collectInstsToScalarize(VF);
7894   }
7895 
7896   CM.collectInLoopReductions();
7897   buildVPlansWithVPRecipes(ElementCount::getFixed(1), MaxFactors.FixedVF);
7898   buildVPlansWithVPRecipes(ElementCount::getScalable(1), MaxFactors.ScalableVF);
7899 
7900   LLVM_DEBUG(printPlans(dbgs()));
7901   if (!MaxFactors.hasVector())
7902     return VectorizationFactor::Disabled();
7903 
7904   // Select the optimal vectorization factor.
7905   auto SelectedVF = CM.selectVectorizationFactor(VFCandidates);
7906 
7907   // Check if it is profitable to vectorize with runtime checks.
7908   unsigned NumRuntimePointerChecks = Requirements.getNumRuntimePointerChecks();
7909   if (SelectedVF.Width.getKnownMinValue() > 1 && NumRuntimePointerChecks) {
7910     bool PragmaThresholdReached =
7911         NumRuntimePointerChecks > PragmaVectorizeMemoryCheckThreshold;
7912     bool ThresholdReached =
7913         NumRuntimePointerChecks > VectorizerParams::RuntimeMemoryCheckThreshold;
7914     if ((ThresholdReached && !Hints.allowReordering()) ||
7915         PragmaThresholdReached) {
7916       ORE->emit([&]() {
7917         return OptimizationRemarkAnalysisAliasing(
7918                    DEBUG_TYPE, "CantReorderMemOps", OrigLoop->getStartLoc(),
7919                    OrigLoop->getHeader())
7920                << "loop not vectorized: cannot prove it is safe to reorder "
7921                   "memory operations";
7922       });
7923       LLVM_DEBUG(dbgs() << "LV: Too many memory checks needed.\n");
7924       Hints.emitRemarkWithHints();
7925       return VectorizationFactor::Disabled();
7926     }
7927   }
7928   return SelectedVF;
7929 }
7930 
7931 VPlan &LoopVectorizationPlanner::getBestPlanFor(ElementCount VF) const {
7932   assert(count_if(VPlans,
7933                   [VF](const VPlanPtr &Plan) { return Plan->hasVF(VF); }) ==
7934              1 &&
7935          "Best VF has not a single VPlan.");
7936 
7937   for (const VPlanPtr &Plan : VPlans) {
7938     if (Plan->hasVF(VF))
7939       return *Plan.get();
7940   }
7941   llvm_unreachable("No plan found!");
7942 }
7943 
7944 void LoopVectorizationPlanner::executePlan(ElementCount BestVF, unsigned BestUF,
7945                                            VPlan &BestVPlan,
7946                                            InnerLoopVectorizer &ILV,
7947                                            DominatorTree *DT) {
7948   LLVM_DEBUG(dbgs() << "Executing best plan with VF=" << BestVF << ", UF=" << BestUF
7949                     << '\n');
7950 
7951   // Perform the actual loop transformation.
7952 
7953   // 1. Create a new empty loop. Unlink the old loop and connect the new one.
7954   VPTransformState State{BestVF, BestUF, LI, DT, ILV.Builder, &ILV, &BestVPlan};
7955   State.CFG.PrevBB = ILV.createVectorizedLoopSkeleton();
7956   State.CanonicalIV = ILV.Induction;
7957   ILV.collectPoisonGeneratingRecipes(State);
7958 
7959   ILV.printDebugTracesAtStart();
7960 
7961   //===------------------------------------------------===//
7962   //
7963   // Notice: any optimization or new instruction that go
7964   // into the code below should also be implemented in
7965   // the cost-model.
7966   //
7967   //===------------------------------------------------===//
7968 
7969   // 2. Copy and widen instructions from the old loop into the new loop.
7970   BestVPlan.prepareToExecute(ILV.getOrCreateTripCount(nullptr), State);
7971   BestVPlan.execute(&State);
7972 
7973   // Keep all loop hints from the original loop on the vector loop (we'll
7974   // replace the vectorizer-specific hints below).
7975   MDNode *OrigLoopID = OrigLoop->getLoopID();
7976 
7977   Optional<MDNode *> VectorizedLoopID =
7978       makeFollowupLoopID(OrigLoopID, {LLVMLoopVectorizeFollowupAll,
7979                                       LLVMLoopVectorizeFollowupVectorized});
7980 
7981   Loop *L = LI->getLoopFor(State.CFG.PrevBB);
7982   if (VectorizedLoopID.hasValue())
7983     L->setLoopID(VectorizedLoopID.getValue());
7984   else {
7985     // Keep all loop hints from the original loop on the vector loop (we'll
7986     // replace the vectorizer-specific hints below).
7987     if (MDNode *LID = OrigLoop->getLoopID())
7988       L->setLoopID(LID);
7989 
7990     LoopVectorizeHints Hints(L, true, *ORE);
7991     Hints.setAlreadyVectorized();
7992   }
7993 
7994   // 3. Fix the vectorized code: take care of header phi's, live-outs,
7995   //    predication, updating analyses.
7996   ILV.fixVectorizedLoop(State);
7997 
7998   ILV.printDebugTracesAtEnd();
7999 }
8000 
8001 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
8002 void LoopVectorizationPlanner::printPlans(raw_ostream &O) {
8003   for (const auto &Plan : VPlans)
8004     if (PrintVPlansInDotFormat)
8005       Plan->printDOT(O);
8006     else
8007       Plan->print(O);
8008 }
8009 #endif
8010 
8011 void LoopVectorizationPlanner::collectTriviallyDeadInstructions(
8012     SmallPtrSetImpl<Instruction *> &DeadInstructions) {
8013 
8014   // We create new control-flow for the vectorized loop, so the original exit
8015   // conditions will be dead after vectorization if it's only used by the
8016   // terminator
8017   SmallVector<BasicBlock*> ExitingBlocks;
8018   OrigLoop->getExitingBlocks(ExitingBlocks);
8019   for (auto *BB : ExitingBlocks) {
8020     auto *Cmp = dyn_cast<Instruction>(BB->getTerminator()->getOperand(0));
8021     if (!Cmp || !Cmp->hasOneUse())
8022       continue;
8023 
8024     // TODO: we should introduce a getUniqueExitingBlocks on Loop
8025     if (!DeadInstructions.insert(Cmp).second)
8026       continue;
8027 
8028     // The operands of the icmp is often a dead trunc, used by IndUpdate.
8029     // TODO: can recurse through operands in general
8030     for (Value *Op : Cmp->operands()) {
8031       if (isa<TruncInst>(Op) && Op->hasOneUse())
8032           DeadInstructions.insert(cast<Instruction>(Op));
8033     }
8034   }
8035 
8036   // We create new "steps" for induction variable updates to which the original
8037   // induction variables map. An original update instruction will be dead if
8038   // all its users except the induction variable are dead.
8039   auto *Latch = OrigLoop->getLoopLatch();
8040   for (auto &Induction : Legal->getInductionVars()) {
8041     PHINode *Ind = Induction.first;
8042     auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
8043 
8044     // If the tail is to be folded by masking, the primary induction variable,
8045     // if exists, isn't dead: it will be used for masking. Don't kill it.
8046     if (CM.foldTailByMasking() && IndUpdate == Legal->getPrimaryInduction())
8047       continue;
8048 
8049     if (llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
8050           return U == Ind || DeadInstructions.count(cast<Instruction>(U));
8051         }))
8052       DeadInstructions.insert(IndUpdate);
8053   }
8054 }
8055 
8056 Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) { return V; }
8057 
8058 static void AddRuntimeUnrollDisableMetaData(Loop *L) {
8059   SmallVector<Metadata *, 4> MDs;
8060   // Reserve first location for self reference to the LoopID metadata node.
8061   MDs.push_back(nullptr);
8062   bool IsUnrollMetadata = false;
8063   MDNode *LoopID = L->getLoopID();
8064   if (LoopID) {
8065     // First find existing loop unrolling disable metadata.
8066     for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
8067       auto *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
8068       if (MD) {
8069         const auto *S = dyn_cast<MDString>(MD->getOperand(0));
8070         IsUnrollMetadata =
8071             S && S->getString().startswith("llvm.loop.unroll.disable");
8072       }
8073       MDs.push_back(LoopID->getOperand(i));
8074     }
8075   }
8076 
8077   if (!IsUnrollMetadata) {
8078     // Add runtime unroll disable metadata.
8079     LLVMContext &Context = L->getHeader()->getContext();
8080     SmallVector<Metadata *, 1> DisableOperands;
8081     DisableOperands.push_back(
8082         MDString::get(Context, "llvm.loop.unroll.runtime.disable"));
8083     MDNode *DisableNode = MDNode::get(Context, DisableOperands);
8084     MDs.push_back(DisableNode);
8085     MDNode *NewLoopID = MDNode::get(Context, MDs);
8086     // Set operand 0 to refer to the loop id itself.
8087     NewLoopID->replaceOperandWith(0, NewLoopID);
8088     L->setLoopID(NewLoopID);
8089   }
8090 }
8091 
8092 //===--------------------------------------------------------------------===//
8093 // EpilogueVectorizerMainLoop
8094 //===--------------------------------------------------------------------===//
8095 
8096 /// This function is partially responsible for generating the control flow
8097 /// depicted in https://llvm.org/docs/Vectorizers.html#epilogue-vectorization.
8098 BasicBlock *EpilogueVectorizerMainLoop::createEpilogueVectorizedLoopSkeleton() {
8099   MDNode *OrigLoopID = OrigLoop->getLoopID();
8100   Loop *Lp = createVectorLoopSkeleton("");
8101 
8102   // Generate the code to check the minimum iteration count of the vector
8103   // epilogue (see below).
8104   EPI.EpilogueIterationCountCheck =
8105       emitMinimumIterationCountCheck(Lp, LoopScalarPreHeader, true);
8106   EPI.EpilogueIterationCountCheck->setName("iter.check");
8107 
8108   // Generate the code to check any assumptions that we've made for SCEV
8109   // expressions.
8110   EPI.SCEVSafetyCheck = emitSCEVChecks(Lp, LoopScalarPreHeader);
8111 
8112   // Generate the code that checks at runtime if arrays overlap. We put the
8113   // checks into a separate block to make the more common case of few elements
8114   // faster.
8115   EPI.MemSafetyCheck = emitMemRuntimeChecks(Lp, LoopScalarPreHeader);
8116 
8117   // Generate the iteration count check for the main loop, *after* the check
8118   // for the epilogue loop, so that the path-length is shorter for the case
8119   // that goes directly through the vector epilogue. The longer-path length for
8120   // the main loop is compensated for, by the gain from vectorizing the larger
8121   // trip count. Note: the branch will get updated later on when we vectorize
8122   // the epilogue.
8123   EPI.MainLoopIterationCountCheck =
8124       emitMinimumIterationCountCheck(Lp, LoopScalarPreHeader, false);
8125 
8126   // Generate the induction variable.
8127   OldInduction = Legal->getPrimaryInduction();
8128   Type *IdxTy = Legal->getWidestInductionType();
8129   Value *StartIdx = ConstantInt::get(IdxTy, 0);
8130 
8131   IRBuilder<> B(&*Lp->getLoopPreheader()->getFirstInsertionPt());
8132   Value *Step = getRuntimeVF(B, IdxTy, VF * UF);
8133   Value *CountRoundDown = getOrCreateVectorTripCount(Lp);
8134   EPI.VectorTripCount = CountRoundDown;
8135   Induction =
8136       createInductionVariable(Lp, StartIdx, CountRoundDown, Step,
8137                               getDebugLocFromInstOrOperands(OldInduction));
8138 
8139   // Skip induction resume value creation here because they will be created in
8140   // the second pass. If we created them here, they wouldn't be used anyway,
8141   // because the vplan in the second pass still contains the inductions from the
8142   // original loop.
8143 
8144   return completeLoopSkeleton(Lp, OrigLoopID);
8145 }
8146 
8147 void EpilogueVectorizerMainLoop::printDebugTracesAtStart() {
8148   LLVM_DEBUG({
8149     dbgs() << "Create Skeleton for epilogue vectorized loop (first pass)\n"
8150            << "Main Loop VF:" << EPI.MainLoopVF
8151            << ", Main Loop UF:" << EPI.MainLoopUF
8152            << ", Epilogue Loop VF:" << EPI.EpilogueVF
8153            << ", Epilogue Loop UF:" << EPI.EpilogueUF << "\n";
8154   });
8155 }
8156 
8157 void EpilogueVectorizerMainLoop::printDebugTracesAtEnd() {
8158   DEBUG_WITH_TYPE(VerboseDebug, {
8159     dbgs() << "intermediate fn:\n"
8160            << *OrigLoop->getHeader()->getParent() << "\n";
8161   });
8162 }
8163 
8164 BasicBlock *EpilogueVectorizerMainLoop::emitMinimumIterationCountCheck(
8165     Loop *L, BasicBlock *Bypass, bool ForEpilogue) {
8166   assert(L && "Expected valid Loop.");
8167   assert(Bypass && "Expected valid bypass basic block.");
8168   ElementCount VFactor = ForEpilogue ? EPI.EpilogueVF : VF;
8169   unsigned UFactor = ForEpilogue ? EPI.EpilogueUF : UF;
8170   Value *Count = getOrCreateTripCount(L);
8171   // Reuse existing vector loop preheader for TC checks.
8172   // Note that new preheader block is generated for vector loop.
8173   BasicBlock *const TCCheckBlock = LoopVectorPreHeader;
8174   IRBuilder<> Builder(TCCheckBlock->getTerminator());
8175 
8176   // Generate code to check if the loop's trip count is less than VF * UF of the
8177   // main vector loop.
8178   auto P = Cost->requiresScalarEpilogue(ForEpilogue ? EPI.EpilogueVF : VF) ?
8179       ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT;
8180 
8181   Value *CheckMinIters = Builder.CreateICmp(
8182       P, Count, createStepForVF(Builder, Count->getType(), VFactor, UFactor),
8183       "min.iters.check");
8184 
8185   if (!ForEpilogue)
8186     TCCheckBlock->setName("vector.main.loop.iter.check");
8187 
8188   // Create new preheader for vector loop.
8189   LoopVectorPreHeader = SplitBlock(TCCheckBlock, TCCheckBlock->getTerminator(),
8190                                    DT, LI, nullptr, "vector.ph");
8191 
8192   if (ForEpilogue) {
8193     assert(DT->properlyDominates(DT->getNode(TCCheckBlock),
8194                                  DT->getNode(Bypass)->getIDom()) &&
8195            "TC check is expected to dominate Bypass");
8196 
8197     // Update dominator for Bypass & LoopExit.
8198     DT->changeImmediateDominator(Bypass, TCCheckBlock);
8199     if (!Cost->requiresScalarEpilogue(EPI.EpilogueVF))
8200       // For loops with multiple exits, there's no edge from the middle block
8201       // to exit blocks (as the epilogue must run) and thus no need to update
8202       // the immediate dominator of the exit blocks.
8203       DT->changeImmediateDominator(LoopExitBlock, TCCheckBlock);
8204 
8205     LoopBypassBlocks.push_back(TCCheckBlock);
8206 
8207     // Save the trip count so we don't have to regenerate it in the
8208     // vec.epilog.iter.check. This is safe to do because the trip count
8209     // generated here dominates the vector epilog iter check.
8210     EPI.TripCount = Count;
8211   }
8212 
8213   ReplaceInstWithInst(
8214       TCCheckBlock->getTerminator(),
8215       BranchInst::Create(Bypass, LoopVectorPreHeader, CheckMinIters));
8216 
8217   return TCCheckBlock;
8218 }
8219 
8220 //===--------------------------------------------------------------------===//
8221 // EpilogueVectorizerEpilogueLoop
8222 //===--------------------------------------------------------------------===//
8223 
8224 /// This function is partially responsible for generating the control flow
8225 /// depicted in https://llvm.org/docs/Vectorizers.html#epilogue-vectorization.
8226 BasicBlock *
8227 EpilogueVectorizerEpilogueLoop::createEpilogueVectorizedLoopSkeleton() {
8228   MDNode *OrigLoopID = OrigLoop->getLoopID();
8229   Loop *Lp = createVectorLoopSkeleton("vec.epilog.");
8230 
8231   // Now, compare the remaining count and if there aren't enough iterations to
8232   // execute the vectorized epilogue skip to the scalar part.
8233   BasicBlock *VecEpilogueIterationCountCheck = LoopVectorPreHeader;
8234   VecEpilogueIterationCountCheck->setName("vec.epilog.iter.check");
8235   LoopVectorPreHeader =
8236       SplitBlock(LoopVectorPreHeader, LoopVectorPreHeader->getTerminator(), DT,
8237                  LI, nullptr, "vec.epilog.ph");
8238   emitMinimumVectorEpilogueIterCountCheck(Lp, LoopScalarPreHeader,
8239                                           VecEpilogueIterationCountCheck);
8240 
8241   // Adjust the control flow taking the state info from the main loop
8242   // vectorization into account.
8243   assert(EPI.MainLoopIterationCountCheck && EPI.EpilogueIterationCountCheck &&
8244          "expected this to be saved from the previous pass.");
8245   EPI.MainLoopIterationCountCheck->getTerminator()->replaceUsesOfWith(
8246       VecEpilogueIterationCountCheck, LoopVectorPreHeader);
8247 
8248   DT->changeImmediateDominator(LoopVectorPreHeader,
8249                                EPI.MainLoopIterationCountCheck);
8250 
8251   EPI.EpilogueIterationCountCheck->getTerminator()->replaceUsesOfWith(
8252       VecEpilogueIterationCountCheck, LoopScalarPreHeader);
8253 
8254   if (EPI.SCEVSafetyCheck)
8255     EPI.SCEVSafetyCheck->getTerminator()->replaceUsesOfWith(
8256         VecEpilogueIterationCountCheck, LoopScalarPreHeader);
8257   if (EPI.MemSafetyCheck)
8258     EPI.MemSafetyCheck->getTerminator()->replaceUsesOfWith(
8259         VecEpilogueIterationCountCheck, LoopScalarPreHeader);
8260 
8261   DT->changeImmediateDominator(
8262       VecEpilogueIterationCountCheck,
8263       VecEpilogueIterationCountCheck->getSinglePredecessor());
8264 
8265   DT->changeImmediateDominator(LoopScalarPreHeader,
8266                                EPI.EpilogueIterationCountCheck);
8267   if (!Cost->requiresScalarEpilogue(EPI.EpilogueVF))
8268     // If there is an epilogue which must run, there's no edge from the
8269     // middle block to exit blocks  and thus no need to update the immediate
8270     // dominator of the exit blocks.
8271     DT->changeImmediateDominator(LoopExitBlock,
8272                                  EPI.EpilogueIterationCountCheck);
8273 
8274   // Keep track of bypass blocks, as they feed start values to the induction
8275   // phis in the scalar loop preheader.
8276   if (EPI.SCEVSafetyCheck)
8277     LoopBypassBlocks.push_back(EPI.SCEVSafetyCheck);
8278   if (EPI.MemSafetyCheck)
8279     LoopBypassBlocks.push_back(EPI.MemSafetyCheck);
8280   LoopBypassBlocks.push_back(EPI.EpilogueIterationCountCheck);
8281 
8282   // Generate a resume induction for the vector epilogue and put it in the
8283   // vector epilogue preheader
8284   Type *IdxTy = Legal->getWidestInductionType();
8285   PHINode *EPResumeVal = PHINode::Create(IdxTy, 2, "vec.epilog.resume.val",
8286                                          LoopVectorPreHeader->getFirstNonPHI());
8287   EPResumeVal->addIncoming(EPI.VectorTripCount, VecEpilogueIterationCountCheck);
8288   EPResumeVal->addIncoming(ConstantInt::get(IdxTy, 0),
8289                            EPI.MainLoopIterationCountCheck);
8290 
8291   // Generate the induction variable.
8292   OldInduction = Legal->getPrimaryInduction();
8293   Value *CountRoundDown = getOrCreateVectorTripCount(Lp);
8294   Constant *Step = ConstantInt::get(IdxTy, VF.getKnownMinValue() * UF);
8295   Value *StartIdx = EPResumeVal;
8296   Induction =
8297       createInductionVariable(Lp, StartIdx, CountRoundDown, Step,
8298                               getDebugLocFromInstOrOperands(OldInduction));
8299 
8300   // Generate induction resume values. These variables save the new starting
8301   // indexes for the scalar loop. They are used to test if there are any tail
8302   // iterations left once the vector loop has completed.
8303   // Note that when the vectorized epilogue is skipped due to iteration count
8304   // check, then the resume value for the induction variable comes from
8305   // the trip count of the main vector loop, hence passing the AdditionalBypass
8306   // argument.
8307   createInductionResumeValues(Lp, CountRoundDown,
8308                               {VecEpilogueIterationCountCheck,
8309                                EPI.VectorTripCount} /* AdditionalBypass */);
8310 
8311   AddRuntimeUnrollDisableMetaData(Lp);
8312   return completeLoopSkeleton(Lp, OrigLoopID);
8313 }
8314 
8315 BasicBlock *
8316 EpilogueVectorizerEpilogueLoop::emitMinimumVectorEpilogueIterCountCheck(
8317     Loop *L, BasicBlock *Bypass, BasicBlock *Insert) {
8318 
8319   assert(EPI.TripCount &&
8320          "Expected trip count to have been safed in the first pass.");
8321   assert(
8322       (!isa<Instruction>(EPI.TripCount) ||
8323        DT->dominates(cast<Instruction>(EPI.TripCount)->getParent(), Insert)) &&
8324       "saved trip count does not dominate insertion point.");
8325   Value *TC = EPI.TripCount;
8326   IRBuilder<> Builder(Insert->getTerminator());
8327   Value *Count = Builder.CreateSub(TC, EPI.VectorTripCount, "n.vec.remaining");
8328 
8329   // Generate code to check if the loop's trip count is less than VF * UF of the
8330   // vector epilogue loop.
8331   auto P = Cost->requiresScalarEpilogue(EPI.EpilogueVF) ?
8332       ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT;
8333 
8334   Value *CheckMinIters =
8335       Builder.CreateICmp(P, Count,
8336                          createStepForVF(Builder, Count->getType(),
8337                                          EPI.EpilogueVF, EPI.EpilogueUF),
8338                          "min.epilog.iters.check");
8339 
8340   ReplaceInstWithInst(
8341       Insert->getTerminator(),
8342       BranchInst::Create(Bypass, LoopVectorPreHeader, CheckMinIters));
8343 
8344   LoopBypassBlocks.push_back(Insert);
8345   return Insert;
8346 }
8347 
8348 void EpilogueVectorizerEpilogueLoop::printDebugTracesAtStart() {
8349   LLVM_DEBUG({
8350     dbgs() << "Create Skeleton for epilogue vectorized loop (second pass)\n"
8351            << "Epilogue Loop VF:" << EPI.EpilogueVF
8352            << ", Epilogue Loop UF:" << EPI.EpilogueUF << "\n";
8353   });
8354 }
8355 
8356 void EpilogueVectorizerEpilogueLoop::printDebugTracesAtEnd() {
8357   DEBUG_WITH_TYPE(VerboseDebug, {
8358     dbgs() << "final fn:\n" << *OrigLoop->getHeader()->getParent() << "\n";
8359   });
8360 }
8361 
8362 bool LoopVectorizationPlanner::getDecisionAndClampRange(
8363     const std::function<bool(ElementCount)> &Predicate, VFRange &Range) {
8364   assert(!Range.isEmpty() && "Trying to test an empty VF range.");
8365   bool PredicateAtRangeStart = Predicate(Range.Start);
8366 
8367   for (ElementCount TmpVF = Range.Start * 2;
8368        ElementCount::isKnownLT(TmpVF, Range.End); TmpVF *= 2)
8369     if (Predicate(TmpVF) != PredicateAtRangeStart) {
8370       Range.End = TmpVF;
8371       break;
8372     }
8373 
8374   return PredicateAtRangeStart;
8375 }
8376 
8377 /// Build VPlans for the full range of feasible VF's = {\p MinVF, 2 * \p MinVF,
8378 /// 4 * \p MinVF, ..., \p MaxVF} by repeatedly building a VPlan for a sub-range
8379 /// of VF's starting at a given VF and extending it as much as possible. Each
8380 /// vectorization decision can potentially shorten this sub-range during
8381 /// buildVPlan().
8382 void LoopVectorizationPlanner::buildVPlans(ElementCount MinVF,
8383                                            ElementCount MaxVF) {
8384   auto MaxVFPlusOne = MaxVF.getWithIncrement(1);
8385   for (ElementCount VF = MinVF; ElementCount::isKnownLT(VF, MaxVFPlusOne);) {
8386     VFRange SubRange = {VF, MaxVFPlusOne};
8387     VPlans.push_back(buildVPlan(SubRange));
8388     VF = SubRange.End;
8389   }
8390 }
8391 
8392 VPValue *VPRecipeBuilder::createEdgeMask(BasicBlock *Src, BasicBlock *Dst,
8393                                          VPlanPtr &Plan) {
8394   assert(is_contained(predecessors(Dst), Src) && "Invalid edge");
8395 
8396   // Look for cached value.
8397   std::pair<BasicBlock *, BasicBlock *> Edge(Src, Dst);
8398   EdgeMaskCacheTy::iterator ECEntryIt = EdgeMaskCache.find(Edge);
8399   if (ECEntryIt != EdgeMaskCache.end())
8400     return ECEntryIt->second;
8401 
8402   VPValue *SrcMask = createBlockInMask(Src, Plan);
8403 
8404   // The terminator has to be a branch inst!
8405   BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
8406   assert(BI && "Unexpected terminator found");
8407 
8408   if (!BI->isConditional() || BI->getSuccessor(0) == BI->getSuccessor(1))
8409     return EdgeMaskCache[Edge] = SrcMask;
8410 
8411   // If source is an exiting block, we know the exit edge is dynamically dead
8412   // in the vector loop, and thus we don't need to restrict the mask.  Avoid
8413   // adding uses of an otherwise potentially dead instruction.
8414   if (OrigLoop->isLoopExiting(Src))
8415     return EdgeMaskCache[Edge] = SrcMask;
8416 
8417   VPValue *EdgeMask = Plan->getOrAddVPValue(BI->getCondition());
8418   assert(EdgeMask && "No Edge Mask found for condition");
8419 
8420   if (BI->getSuccessor(0) != Dst)
8421     EdgeMask = Builder.createNot(EdgeMask, BI->getDebugLoc());
8422 
8423   if (SrcMask) { // Otherwise block in-mask is all-one, no need to AND.
8424     // The condition is 'SrcMask && EdgeMask', which is equivalent to
8425     // 'select i1 SrcMask, i1 EdgeMask, i1 false'.
8426     // The select version does not introduce new UB if SrcMask is false and
8427     // EdgeMask is poison. Using 'and' here introduces undefined behavior.
8428     VPValue *False = Plan->getOrAddVPValue(
8429         ConstantInt::getFalse(BI->getCondition()->getType()));
8430     EdgeMask =
8431         Builder.createSelect(SrcMask, EdgeMask, False, BI->getDebugLoc());
8432   }
8433 
8434   return EdgeMaskCache[Edge] = EdgeMask;
8435 }
8436 
8437 VPValue *VPRecipeBuilder::createBlockInMask(BasicBlock *BB, VPlanPtr &Plan) {
8438   assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
8439 
8440   // Look for cached value.
8441   BlockMaskCacheTy::iterator BCEntryIt = BlockMaskCache.find(BB);
8442   if (BCEntryIt != BlockMaskCache.end())
8443     return BCEntryIt->second;
8444 
8445   // All-one mask is modelled as no-mask following the convention for masked
8446   // load/store/gather/scatter. Initialize BlockMask to no-mask.
8447   VPValue *BlockMask = nullptr;
8448 
8449   if (OrigLoop->getHeader() == BB) {
8450     if (!CM.blockNeedsPredicationForAnyReason(BB))
8451       return BlockMaskCache[BB] = BlockMask; // Loop incoming mask is all-one.
8452 
8453     // Introduce the early-exit compare IV <= BTC to form header block mask.
8454     // This is used instead of IV < TC because TC may wrap, unlike BTC. Start by
8455     // constructing the desired canonical IV in the header block as its first
8456     // non-phi instructions.
8457     assert(CM.foldTailByMasking() && "must fold the tail");
8458     VPBasicBlock *HeaderVPBB = Plan->getEntry()->getEntryBasicBlock();
8459     auto NewInsertionPoint = HeaderVPBB->getFirstNonPhi();
8460 
8461     VPValue *IV = nullptr;
8462     if (Legal->getPrimaryInduction())
8463       IV = Plan->getOrAddVPValue(Legal->getPrimaryInduction());
8464     else {
8465       auto *IVRecipe = new VPWidenCanonicalIVRecipe();
8466       HeaderVPBB->insert(IVRecipe, NewInsertionPoint);
8467       IV = IVRecipe;
8468     }
8469 
8470     VPBuilder::InsertPointGuard Guard(Builder);
8471     Builder.setInsertPoint(HeaderVPBB, NewInsertionPoint);
8472     if (CM.TTI.emitGetActiveLaneMask()) {
8473       VPValue *TC = Plan->getOrCreateTripCount();
8474       BlockMask = Builder.createNaryOp(VPInstruction::ActiveLaneMask, {IV, TC});
8475     } else {
8476       VPValue *BTC = Plan->getOrCreateBackedgeTakenCount();
8477       BlockMask = Builder.createNaryOp(VPInstruction::ICmpULE, {IV, BTC});
8478     }
8479     return BlockMaskCache[BB] = BlockMask;
8480   }
8481 
8482   // This is the block mask. We OR all incoming edges.
8483   for (auto *Predecessor : predecessors(BB)) {
8484     VPValue *EdgeMask = createEdgeMask(Predecessor, BB, Plan);
8485     if (!EdgeMask) // Mask of predecessor is all-one so mask of block is too.
8486       return BlockMaskCache[BB] = EdgeMask;
8487 
8488     if (!BlockMask) { // BlockMask has its initialized nullptr value.
8489       BlockMask = EdgeMask;
8490       continue;
8491     }
8492 
8493     BlockMask = Builder.createOr(BlockMask, EdgeMask, {});
8494   }
8495 
8496   return BlockMaskCache[BB] = BlockMask;
8497 }
8498 
8499 VPRecipeBase *VPRecipeBuilder::tryToWidenMemory(Instruction *I,
8500                                                 ArrayRef<VPValue *> Operands,
8501                                                 VFRange &Range,
8502                                                 VPlanPtr &Plan) {
8503   assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
8504          "Must be called with either a load or store");
8505 
8506   auto willWiden = [&](ElementCount VF) -> bool {
8507     if (VF.isScalar())
8508       return false;
8509     LoopVectorizationCostModel::InstWidening Decision =
8510         CM.getWideningDecision(I, VF);
8511     assert(Decision != LoopVectorizationCostModel::CM_Unknown &&
8512            "CM decision should be taken at this point.");
8513     if (Decision == LoopVectorizationCostModel::CM_Interleave)
8514       return true;
8515     if (CM.isScalarAfterVectorization(I, VF) ||
8516         CM.isProfitableToScalarize(I, VF))
8517       return false;
8518     return Decision != LoopVectorizationCostModel::CM_Scalarize;
8519   };
8520 
8521   if (!LoopVectorizationPlanner::getDecisionAndClampRange(willWiden, Range))
8522     return nullptr;
8523 
8524   VPValue *Mask = nullptr;
8525   if (Legal->isMaskRequired(I))
8526     Mask = createBlockInMask(I->getParent(), Plan);
8527 
8528   // Determine if the pointer operand of the access is either consecutive or
8529   // reverse consecutive.
8530   LoopVectorizationCostModel::InstWidening Decision =
8531       CM.getWideningDecision(I, Range.Start);
8532   bool Reverse = Decision == LoopVectorizationCostModel::CM_Widen_Reverse;
8533   bool Consecutive =
8534       Reverse || Decision == LoopVectorizationCostModel::CM_Widen;
8535 
8536   if (LoadInst *Load = dyn_cast<LoadInst>(I))
8537     return new VPWidenMemoryInstructionRecipe(*Load, Operands[0], Mask,
8538                                               Consecutive, Reverse);
8539 
8540   StoreInst *Store = cast<StoreInst>(I);
8541   return new VPWidenMemoryInstructionRecipe(*Store, Operands[1], Operands[0],
8542                                             Mask, Consecutive, Reverse);
8543 }
8544 
8545 VPWidenIntOrFpInductionRecipe *
8546 VPRecipeBuilder::tryToOptimizeInductionPHI(PHINode *Phi,
8547                                            ArrayRef<VPValue *> Operands) const {
8548   // Check if this is an integer or fp induction. If so, build the recipe that
8549   // produces its scalar and vector values.
8550   if (auto *II = Legal->getIntOrFpInductionDescriptor(Phi)) {
8551     assert(II->getStartValue() ==
8552            Phi->getIncomingValueForBlock(OrigLoop->getLoopPreheader()));
8553     return new VPWidenIntOrFpInductionRecipe(Phi, Operands[0], *II);
8554   }
8555 
8556   return nullptr;
8557 }
8558 
8559 VPWidenIntOrFpInductionRecipe *VPRecipeBuilder::tryToOptimizeInductionTruncate(
8560     TruncInst *I, ArrayRef<VPValue *> Operands, VFRange &Range,
8561     VPlan &Plan) const {
8562   // Optimize the special case where the source is a constant integer
8563   // induction variable. Notice that we can only optimize the 'trunc' case
8564   // because (a) FP conversions lose precision, (b) sext/zext may wrap, and
8565   // (c) other casts depend on pointer size.
8566 
8567   // Determine whether \p K is a truncation based on an induction variable that
8568   // can be optimized.
8569   auto isOptimizableIVTruncate =
8570       [&](Instruction *K) -> std::function<bool(ElementCount)> {
8571     return [=](ElementCount VF) -> bool {
8572       return CM.isOptimizableIVTruncate(K, VF);
8573     };
8574   };
8575 
8576   if (LoopVectorizationPlanner::getDecisionAndClampRange(
8577           isOptimizableIVTruncate(I), Range)) {
8578 
8579     auto *Phi = cast<PHINode>(I->getOperand(0));
8580     const InductionDescriptor &II = *Legal->getIntOrFpInductionDescriptor(Phi);
8581     VPValue *Start = Plan.getOrAddVPValue(II.getStartValue());
8582     return new VPWidenIntOrFpInductionRecipe(Phi, Start, II, I);
8583   }
8584   return nullptr;
8585 }
8586 
8587 VPRecipeOrVPValueTy VPRecipeBuilder::tryToBlend(PHINode *Phi,
8588                                                 ArrayRef<VPValue *> Operands,
8589                                                 VPlanPtr &Plan) {
8590   // If all incoming values are equal, the incoming VPValue can be used directly
8591   // instead of creating a new VPBlendRecipe.
8592   VPValue *FirstIncoming = Operands[0];
8593   if (all_of(Operands, [FirstIncoming](const VPValue *Inc) {
8594         return FirstIncoming == Inc;
8595       })) {
8596     return Operands[0];
8597   }
8598 
8599   // We know that all PHIs in non-header blocks are converted into selects, so
8600   // we don't have to worry about the insertion order and we can just use the
8601   // builder. At this point we generate the predication tree. There may be
8602   // duplications since this is a simple recursive scan, but future
8603   // optimizations will clean it up.
8604   SmallVector<VPValue *, 2> OperandsWithMask;
8605   unsigned NumIncoming = Phi->getNumIncomingValues();
8606 
8607   for (unsigned In = 0; In < NumIncoming; In++) {
8608     VPValue *EdgeMask =
8609       createEdgeMask(Phi->getIncomingBlock(In), Phi->getParent(), Plan);
8610     assert((EdgeMask || NumIncoming == 1) &&
8611            "Multiple predecessors with one having a full mask");
8612     OperandsWithMask.push_back(Operands[In]);
8613     if (EdgeMask)
8614       OperandsWithMask.push_back(EdgeMask);
8615   }
8616   return toVPRecipeResult(new VPBlendRecipe(Phi, OperandsWithMask));
8617 }
8618 
8619 VPWidenCallRecipe *VPRecipeBuilder::tryToWidenCall(CallInst *CI,
8620                                                    ArrayRef<VPValue *> Operands,
8621                                                    VFRange &Range) const {
8622 
8623   bool IsPredicated = LoopVectorizationPlanner::getDecisionAndClampRange(
8624       [this, CI](ElementCount VF) { return CM.isScalarWithPredication(CI); },
8625       Range);
8626 
8627   if (IsPredicated)
8628     return nullptr;
8629 
8630   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
8631   if (ID && (ID == Intrinsic::assume || ID == Intrinsic::lifetime_end ||
8632              ID == Intrinsic::lifetime_start || ID == Intrinsic::sideeffect ||
8633              ID == Intrinsic::pseudoprobe ||
8634              ID == Intrinsic::experimental_noalias_scope_decl))
8635     return nullptr;
8636 
8637   auto willWiden = [&](ElementCount VF) -> bool {
8638     Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
8639     // The following case may be scalarized depending on the VF.
8640     // The flag shows whether we use Intrinsic or a usual Call for vectorized
8641     // version of the instruction.
8642     // Is it beneficial to perform intrinsic call compared to lib call?
8643     bool NeedToScalarize = false;
8644     InstructionCost CallCost = CM.getVectorCallCost(CI, VF, NeedToScalarize);
8645     InstructionCost IntrinsicCost = ID ? CM.getVectorIntrinsicCost(CI, VF) : 0;
8646     bool UseVectorIntrinsic = ID && IntrinsicCost <= CallCost;
8647     return UseVectorIntrinsic || !NeedToScalarize;
8648   };
8649 
8650   if (!LoopVectorizationPlanner::getDecisionAndClampRange(willWiden, Range))
8651     return nullptr;
8652 
8653   ArrayRef<VPValue *> Ops = Operands.take_front(CI->arg_size());
8654   return new VPWidenCallRecipe(*CI, make_range(Ops.begin(), Ops.end()));
8655 }
8656 
8657 bool VPRecipeBuilder::shouldWiden(Instruction *I, VFRange &Range) const {
8658   assert(!isa<BranchInst>(I) && !isa<PHINode>(I) && !isa<LoadInst>(I) &&
8659          !isa<StoreInst>(I) && "Instruction should have been handled earlier");
8660   // Instruction should be widened, unless it is scalar after vectorization,
8661   // scalarization is profitable or it is predicated.
8662   auto WillScalarize = [this, I](ElementCount VF) -> bool {
8663     return CM.isScalarAfterVectorization(I, VF) ||
8664            CM.isProfitableToScalarize(I, VF) || CM.isScalarWithPredication(I);
8665   };
8666   return !LoopVectorizationPlanner::getDecisionAndClampRange(WillScalarize,
8667                                                              Range);
8668 }
8669 
8670 VPWidenRecipe *VPRecipeBuilder::tryToWiden(Instruction *I,
8671                                            ArrayRef<VPValue *> Operands) const {
8672   auto IsVectorizableOpcode = [](unsigned Opcode) {
8673     switch (Opcode) {
8674     case Instruction::Add:
8675     case Instruction::And:
8676     case Instruction::AShr:
8677     case Instruction::BitCast:
8678     case Instruction::FAdd:
8679     case Instruction::FCmp:
8680     case Instruction::FDiv:
8681     case Instruction::FMul:
8682     case Instruction::FNeg:
8683     case Instruction::FPExt:
8684     case Instruction::FPToSI:
8685     case Instruction::FPToUI:
8686     case Instruction::FPTrunc:
8687     case Instruction::FRem:
8688     case Instruction::FSub:
8689     case Instruction::ICmp:
8690     case Instruction::IntToPtr:
8691     case Instruction::LShr:
8692     case Instruction::Mul:
8693     case Instruction::Or:
8694     case Instruction::PtrToInt:
8695     case Instruction::SDiv:
8696     case Instruction::Select:
8697     case Instruction::SExt:
8698     case Instruction::Shl:
8699     case Instruction::SIToFP:
8700     case Instruction::SRem:
8701     case Instruction::Sub:
8702     case Instruction::Trunc:
8703     case Instruction::UDiv:
8704     case Instruction::UIToFP:
8705     case Instruction::URem:
8706     case Instruction::Xor:
8707     case Instruction::ZExt:
8708       return true;
8709     }
8710     return false;
8711   };
8712 
8713   if (!IsVectorizableOpcode(I->getOpcode()))
8714     return nullptr;
8715 
8716   // Success: widen this instruction.
8717   return new VPWidenRecipe(*I, make_range(Operands.begin(), Operands.end()));
8718 }
8719 
8720 void VPRecipeBuilder::fixHeaderPhis() {
8721   BasicBlock *OrigLatch = OrigLoop->getLoopLatch();
8722   for (VPHeaderPHIRecipe *R : PhisToFix) {
8723     auto *PN = cast<PHINode>(R->getUnderlyingValue());
8724     VPRecipeBase *IncR =
8725         getRecipe(cast<Instruction>(PN->getIncomingValueForBlock(OrigLatch)));
8726     R->addOperand(IncR->getVPSingleValue());
8727   }
8728 }
8729 
8730 VPBasicBlock *VPRecipeBuilder::handleReplication(
8731     Instruction *I, VFRange &Range, VPBasicBlock *VPBB,
8732     VPlanPtr &Plan) {
8733   bool IsUniform = LoopVectorizationPlanner::getDecisionAndClampRange(
8734       [&](ElementCount VF) { return CM.isUniformAfterVectorization(I, VF); },
8735       Range);
8736 
8737   bool IsPredicated = LoopVectorizationPlanner::getDecisionAndClampRange(
8738       [&](ElementCount VF) { return CM.isPredicatedInst(I, IsUniform); },
8739       Range);
8740 
8741   // Even if the instruction is not marked as uniform, there are certain
8742   // intrinsic calls that can be effectively treated as such, so we check for
8743   // them here. Conservatively, we only do this for scalable vectors, since
8744   // for fixed-width VFs we can always fall back on full scalarization.
8745   if (!IsUniform && Range.Start.isScalable() && isa<IntrinsicInst>(I)) {
8746     switch (cast<IntrinsicInst>(I)->getIntrinsicID()) {
8747     case Intrinsic::assume:
8748     case Intrinsic::lifetime_start:
8749     case Intrinsic::lifetime_end:
8750       // For scalable vectors if one of the operands is variant then we still
8751       // want to mark as uniform, which will generate one instruction for just
8752       // the first lane of the vector. We can't scalarize the call in the same
8753       // way as for fixed-width vectors because we don't know how many lanes
8754       // there are.
8755       //
8756       // The reasons for doing it this way for scalable vectors are:
8757       //   1. For the assume intrinsic generating the instruction for the first
8758       //      lane is still be better than not generating any at all. For
8759       //      example, the input may be a splat across all lanes.
8760       //   2. For the lifetime start/end intrinsics the pointer operand only
8761       //      does anything useful when the input comes from a stack object,
8762       //      which suggests it should always be uniform. For non-stack objects
8763       //      the effect is to poison the object, which still allows us to
8764       //      remove the call.
8765       IsUniform = true;
8766       break;
8767     default:
8768       break;
8769     }
8770   }
8771 
8772   auto *Recipe = new VPReplicateRecipe(I, Plan->mapToVPValues(I->operands()),
8773                                        IsUniform, IsPredicated);
8774   setRecipe(I, Recipe);
8775   Plan->addVPValue(I, Recipe);
8776 
8777   // Find if I uses a predicated instruction. If so, it will use its scalar
8778   // value. Avoid hoisting the insert-element which packs the scalar value into
8779   // a vector value, as that happens iff all users use the vector value.
8780   for (VPValue *Op : Recipe->operands()) {
8781     auto *PredR = dyn_cast_or_null<VPPredInstPHIRecipe>(Op->getDef());
8782     if (!PredR)
8783       continue;
8784     auto *RepR =
8785         cast_or_null<VPReplicateRecipe>(PredR->getOperand(0)->getDef());
8786     assert(RepR->isPredicated() &&
8787            "expected Replicate recipe to be predicated");
8788     RepR->setAlsoPack(false);
8789   }
8790 
8791   // Finalize the recipe for Instr, first if it is not predicated.
8792   if (!IsPredicated) {
8793     LLVM_DEBUG(dbgs() << "LV: Scalarizing:" << *I << "\n");
8794     VPBB->appendRecipe(Recipe);
8795     return VPBB;
8796   }
8797   LLVM_DEBUG(dbgs() << "LV: Scalarizing and predicating:" << *I << "\n");
8798 
8799   VPBlockBase *SingleSucc = VPBB->getSingleSuccessor();
8800   assert(SingleSucc && "VPBB must have a single successor when handling "
8801                        "predicated replication.");
8802   VPBlockUtils::disconnectBlocks(VPBB, SingleSucc);
8803   // Record predicated instructions for above packing optimizations.
8804   VPBlockBase *Region = createReplicateRegion(I, Recipe, Plan);
8805   VPBlockUtils::insertBlockAfter(Region, VPBB);
8806   auto *RegSucc = new VPBasicBlock();
8807   VPBlockUtils::insertBlockAfter(RegSucc, Region);
8808   VPBlockUtils::connectBlocks(RegSucc, SingleSucc);
8809   return RegSucc;
8810 }
8811 
8812 VPRegionBlock *VPRecipeBuilder::createReplicateRegion(Instruction *Instr,
8813                                                       VPRecipeBase *PredRecipe,
8814                                                       VPlanPtr &Plan) {
8815   // Instructions marked for predication are replicated and placed under an
8816   // if-then construct to prevent side-effects.
8817 
8818   // Generate recipes to compute the block mask for this region.
8819   VPValue *BlockInMask = createBlockInMask(Instr->getParent(), Plan);
8820 
8821   // Build the triangular if-then region.
8822   std::string RegionName = (Twine("pred.") + Instr->getOpcodeName()).str();
8823   assert(Instr->getParent() && "Predicated instruction not in any basic block");
8824   auto *BOMRecipe = new VPBranchOnMaskRecipe(BlockInMask);
8825   auto *Entry = new VPBasicBlock(Twine(RegionName) + ".entry", BOMRecipe);
8826   auto *PHIRecipe = Instr->getType()->isVoidTy()
8827                         ? nullptr
8828                         : new VPPredInstPHIRecipe(Plan->getOrAddVPValue(Instr));
8829   if (PHIRecipe) {
8830     Plan->removeVPValueFor(Instr);
8831     Plan->addVPValue(Instr, PHIRecipe);
8832   }
8833   auto *Exit = new VPBasicBlock(Twine(RegionName) + ".continue", PHIRecipe);
8834   auto *Pred = new VPBasicBlock(Twine(RegionName) + ".if", PredRecipe);
8835   VPRegionBlock *Region = new VPRegionBlock(Entry, Exit, RegionName, true);
8836 
8837   // Note: first set Entry as region entry and then connect successors starting
8838   // from it in order, to propagate the "parent" of each VPBasicBlock.
8839   VPBlockUtils::insertTwoBlocksAfter(Pred, Exit, BlockInMask, Entry);
8840   VPBlockUtils::connectBlocks(Pred, Exit);
8841 
8842   return Region;
8843 }
8844 
8845 VPRecipeOrVPValueTy
8846 VPRecipeBuilder::tryToCreateWidenRecipe(Instruction *Instr,
8847                                         ArrayRef<VPValue *> Operands,
8848                                         VFRange &Range, VPlanPtr &Plan) {
8849   // First, check for specific widening recipes that deal with calls, memory
8850   // operations, inductions and Phi nodes.
8851   if (auto *CI = dyn_cast<CallInst>(Instr))
8852     return toVPRecipeResult(tryToWidenCall(CI, Operands, Range));
8853 
8854   if (isa<LoadInst>(Instr) || isa<StoreInst>(Instr))
8855     return toVPRecipeResult(tryToWidenMemory(Instr, Operands, Range, Plan));
8856 
8857   VPRecipeBase *Recipe;
8858   if (auto Phi = dyn_cast<PHINode>(Instr)) {
8859     if (Phi->getParent() != OrigLoop->getHeader())
8860       return tryToBlend(Phi, Operands, Plan);
8861     if ((Recipe = tryToOptimizeInductionPHI(Phi, Operands)))
8862       return toVPRecipeResult(Recipe);
8863 
8864     VPHeaderPHIRecipe *PhiRecipe = nullptr;
8865     if (Legal->isReductionVariable(Phi) || Legal->isFirstOrderRecurrence(Phi)) {
8866       VPValue *StartV = Operands[0];
8867       if (Legal->isReductionVariable(Phi)) {
8868         const RecurrenceDescriptor &RdxDesc =
8869             Legal->getReductionVars().find(Phi)->second;
8870         assert(RdxDesc.getRecurrenceStartValue() ==
8871                Phi->getIncomingValueForBlock(OrigLoop->getLoopPreheader()));
8872         PhiRecipe = new VPReductionPHIRecipe(Phi, RdxDesc, *StartV,
8873                                              CM.isInLoopReduction(Phi),
8874                                              CM.useOrderedReductions(RdxDesc));
8875       } else {
8876         PhiRecipe = new VPFirstOrderRecurrencePHIRecipe(Phi, *StartV);
8877       }
8878 
8879       // Record the incoming value from the backedge, so we can add the incoming
8880       // value from the backedge after all recipes have been created.
8881       recordRecipeOf(cast<Instruction>(
8882           Phi->getIncomingValueForBlock(OrigLoop->getLoopLatch())));
8883       PhisToFix.push_back(PhiRecipe);
8884     } else {
8885       // TODO: record backedge value for remaining pointer induction phis.
8886       assert(Phi->getType()->isPointerTy() &&
8887              "only pointer phis should be handled here");
8888       assert(Legal->getInductionVars().count(Phi) &&
8889              "Not an induction variable");
8890       InductionDescriptor II = Legal->getInductionVars().lookup(Phi);
8891       VPValue *Start = Plan->getOrAddVPValue(II.getStartValue());
8892       PhiRecipe = new VPWidenPHIRecipe(Phi, Start);
8893     }
8894 
8895     return toVPRecipeResult(PhiRecipe);
8896   }
8897 
8898   if (isa<TruncInst>(Instr) &&
8899       (Recipe = tryToOptimizeInductionTruncate(cast<TruncInst>(Instr), Operands,
8900                                                Range, *Plan)))
8901     return toVPRecipeResult(Recipe);
8902 
8903   if (!shouldWiden(Instr, Range))
8904     return nullptr;
8905 
8906   if (auto GEP = dyn_cast<GetElementPtrInst>(Instr))
8907     return toVPRecipeResult(new VPWidenGEPRecipe(
8908         GEP, make_range(Operands.begin(), Operands.end()), OrigLoop));
8909 
8910   if (auto *SI = dyn_cast<SelectInst>(Instr)) {
8911     bool InvariantCond =
8912         PSE.getSE()->isLoopInvariant(PSE.getSCEV(SI->getOperand(0)), OrigLoop);
8913     return toVPRecipeResult(new VPWidenSelectRecipe(
8914         *SI, make_range(Operands.begin(), Operands.end()), InvariantCond));
8915   }
8916 
8917   return toVPRecipeResult(tryToWiden(Instr, Operands));
8918 }
8919 
8920 void LoopVectorizationPlanner::buildVPlansWithVPRecipes(ElementCount MinVF,
8921                                                         ElementCount MaxVF) {
8922   assert(OrigLoop->isInnermost() && "Inner loop expected.");
8923 
8924   // Collect instructions from the original loop that will become trivially dead
8925   // in the vectorized loop. We don't need to vectorize these instructions. For
8926   // example, original induction update instructions can become dead because we
8927   // separately emit induction "steps" when generating code for the new loop.
8928   // Similarly, we create a new latch condition when setting up the structure
8929   // of the new loop, so the old one can become dead.
8930   SmallPtrSet<Instruction *, 4> DeadInstructions;
8931   collectTriviallyDeadInstructions(DeadInstructions);
8932 
8933   // Add assume instructions we need to drop to DeadInstructions, to prevent
8934   // them from being added to the VPlan.
8935   // TODO: We only need to drop assumes in blocks that get flattend. If the
8936   // control flow is preserved, we should keep them.
8937   auto &ConditionalAssumes = Legal->getConditionalAssumes();
8938   DeadInstructions.insert(ConditionalAssumes.begin(), ConditionalAssumes.end());
8939 
8940   MapVector<Instruction *, Instruction *> &SinkAfter = Legal->getSinkAfter();
8941   // Dead instructions do not need sinking. Remove them from SinkAfter.
8942   for (Instruction *I : DeadInstructions)
8943     SinkAfter.erase(I);
8944 
8945   // Cannot sink instructions after dead instructions (there won't be any
8946   // recipes for them). Instead, find the first non-dead previous instruction.
8947   for (auto &P : Legal->getSinkAfter()) {
8948     Instruction *SinkTarget = P.second;
8949     Instruction *FirstInst = &*SinkTarget->getParent()->begin();
8950     (void)FirstInst;
8951     while (DeadInstructions.contains(SinkTarget)) {
8952       assert(
8953           SinkTarget != FirstInst &&
8954           "Must find a live instruction (at least the one feeding the "
8955           "first-order recurrence PHI) before reaching beginning of the block");
8956       SinkTarget = SinkTarget->getPrevNode();
8957       assert(SinkTarget != P.first &&
8958              "sink source equals target, no sinking required");
8959     }
8960     P.second = SinkTarget;
8961   }
8962 
8963   auto MaxVFPlusOne = MaxVF.getWithIncrement(1);
8964   for (ElementCount VF = MinVF; ElementCount::isKnownLT(VF, MaxVFPlusOne);) {
8965     VFRange SubRange = {VF, MaxVFPlusOne};
8966     VPlans.push_back(
8967         buildVPlanWithVPRecipes(SubRange, DeadInstructions, SinkAfter));
8968     VF = SubRange.End;
8969   }
8970 }
8971 
8972 VPlanPtr LoopVectorizationPlanner::buildVPlanWithVPRecipes(
8973     VFRange &Range, SmallPtrSetImpl<Instruction *> &DeadInstructions,
8974     const MapVector<Instruction *, Instruction *> &SinkAfter) {
8975 
8976   SmallPtrSet<const InterleaveGroup<Instruction> *, 1> InterleaveGroups;
8977 
8978   VPRecipeBuilder RecipeBuilder(OrigLoop, TLI, Legal, CM, PSE, Builder);
8979 
8980   // ---------------------------------------------------------------------------
8981   // Pre-construction: record ingredients whose recipes we'll need to further
8982   // process after constructing the initial VPlan.
8983   // ---------------------------------------------------------------------------
8984 
8985   // Mark instructions we'll need to sink later and their targets as
8986   // ingredients whose recipe we'll need to record.
8987   for (auto &Entry : SinkAfter) {
8988     RecipeBuilder.recordRecipeOf(Entry.first);
8989     RecipeBuilder.recordRecipeOf(Entry.second);
8990   }
8991   for (auto &Reduction : CM.getInLoopReductionChains()) {
8992     PHINode *Phi = Reduction.first;
8993     RecurKind Kind =
8994         Legal->getReductionVars().find(Phi)->second.getRecurrenceKind();
8995     const SmallVector<Instruction *, 4> &ReductionOperations = Reduction.second;
8996 
8997     RecipeBuilder.recordRecipeOf(Phi);
8998     for (auto &R : ReductionOperations) {
8999       RecipeBuilder.recordRecipeOf(R);
9000       // For min/max reducitons, where we have a pair of icmp/select, we also
9001       // need to record the ICmp recipe, so it can be removed later.
9002       assert(!RecurrenceDescriptor::isSelectCmpRecurrenceKind(Kind) &&
9003              "Only min/max recurrences allowed for inloop reductions");
9004       if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind))
9005         RecipeBuilder.recordRecipeOf(cast<Instruction>(R->getOperand(0)));
9006     }
9007   }
9008 
9009   // For each interleave group which is relevant for this (possibly trimmed)
9010   // Range, add it to the set of groups to be later applied to the VPlan and add
9011   // placeholders for its members' Recipes which we'll be replacing with a
9012   // single VPInterleaveRecipe.
9013   for (InterleaveGroup<Instruction> *IG : IAI.getInterleaveGroups()) {
9014     auto applyIG = [IG, this](ElementCount VF) -> bool {
9015       return (VF.isVector() && // Query is illegal for VF == 1
9016               CM.getWideningDecision(IG->getInsertPos(), VF) ==
9017                   LoopVectorizationCostModel::CM_Interleave);
9018     };
9019     if (!getDecisionAndClampRange(applyIG, Range))
9020       continue;
9021     InterleaveGroups.insert(IG);
9022     for (unsigned i = 0; i < IG->getFactor(); i++)
9023       if (Instruction *Member = IG->getMember(i))
9024         RecipeBuilder.recordRecipeOf(Member);
9025   };
9026 
9027   // ---------------------------------------------------------------------------
9028   // Build initial VPlan: Scan the body of the loop in a topological order to
9029   // visit each basic block after having visited its predecessor basic blocks.
9030   // ---------------------------------------------------------------------------
9031 
9032   // Create initial VPlan skeleton, with separate header and latch blocks.
9033   VPBasicBlock *HeaderVPBB = new VPBasicBlock();
9034   VPBasicBlock *LatchVPBB = new VPBasicBlock("vector.latch");
9035   VPBlockUtils::insertBlockAfter(LatchVPBB, HeaderVPBB);
9036   auto *TopRegion = new VPRegionBlock(HeaderVPBB, LatchVPBB, "vector loop");
9037   auto Plan = std::make_unique<VPlan>(TopRegion);
9038 
9039   // Scan the body of the loop in a topological order to visit each basic block
9040   // after having visited its predecessor basic blocks.
9041   LoopBlocksDFS DFS(OrigLoop);
9042   DFS.perform(LI);
9043 
9044   VPBasicBlock *VPBB = HeaderVPBB;
9045   SmallVector<VPWidenIntOrFpInductionRecipe *> InductionsToMove;
9046   for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) {
9047     // Relevant instructions from basic block BB will be grouped into VPRecipe
9048     // ingredients and fill a new VPBasicBlock.
9049     unsigned VPBBsForBB = 0;
9050     VPBB->setName(BB->getName());
9051     Builder.setInsertPoint(VPBB);
9052 
9053     // Introduce each ingredient into VPlan.
9054     // TODO: Model and preserve debug instrinsics in VPlan.
9055     for (Instruction &I : BB->instructionsWithoutDebug()) {
9056       Instruction *Instr = &I;
9057 
9058       // First filter out irrelevant instructions, to ensure no recipes are
9059       // built for them.
9060       if (isa<BranchInst>(Instr) || DeadInstructions.count(Instr))
9061         continue;
9062 
9063       SmallVector<VPValue *, 4> Operands;
9064       auto *Phi = dyn_cast<PHINode>(Instr);
9065       if (Phi && Phi->getParent() == OrigLoop->getHeader()) {
9066         Operands.push_back(Plan->getOrAddVPValue(
9067             Phi->getIncomingValueForBlock(OrigLoop->getLoopPreheader())));
9068       } else {
9069         auto OpRange = Plan->mapToVPValues(Instr->operands());
9070         Operands = {OpRange.begin(), OpRange.end()};
9071       }
9072       if (auto RecipeOrValue = RecipeBuilder.tryToCreateWidenRecipe(
9073               Instr, Operands, Range, Plan)) {
9074         // If Instr can be simplified to an existing VPValue, use it.
9075         if (RecipeOrValue.is<VPValue *>()) {
9076           auto *VPV = RecipeOrValue.get<VPValue *>();
9077           Plan->addVPValue(Instr, VPV);
9078           // If the re-used value is a recipe, register the recipe for the
9079           // instruction, in case the recipe for Instr needs to be recorded.
9080           if (auto *R = dyn_cast_or_null<VPRecipeBase>(VPV->getDef()))
9081             RecipeBuilder.setRecipe(Instr, R);
9082           continue;
9083         }
9084         // Otherwise, add the new recipe.
9085         VPRecipeBase *Recipe = RecipeOrValue.get<VPRecipeBase *>();
9086         for (auto *Def : Recipe->definedValues()) {
9087           auto *UV = Def->getUnderlyingValue();
9088           Plan->addVPValue(UV, Def);
9089         }
9090 
9091         if (isa<VPWidenIntOrFpInductionRecipe>(Recipe) &&
9092             HeaderVPBB->getFirstNonPhi() != VPBB->end()) {
9093           // Keep track of VPWidenIntOrFpInductionRecipes not in the phi section
9094           // of the header block. That can happen for truncates of induction
9095           // variables. Those recipes are moved to the phi section of the header
9096           // block after applying SinkAfter, which relies on the original
9097           // position of the trunc.
9098           assert(isa<TruncInst>(Instr));
9099           InductionsToMove.push_back(
9100               cast<VPWidenIntOrFpInductionRecipe>(Recipe));
9101         }
9102         RecipeBuilder.setRecipe(Instr, Recipe);
9103         VPBB->appendRecipe(Recipe);
9104         continue;
9105       }
9106 
9107       // Otherwise, if all widening options failed, Instruction is to be
9108       // replicated. This may create a successor for VPBB.
9109       VPBasicBlock *NextVPBB =
9110           RecipeBuilder.handleReplication(Instr, Range, VPBB, Plan);
9111       if (NextVPBB != VPBB) {
9112         VPBB = NextVPBB;
9113         VPBB->setName(BB->hasName() ? BB->getName() + "." + Twine(VPBBsForBB++)
9114                                     : "");
9115       }
9116     }
9117 
9118     VPBlockUtils::insertBlockAfter(new VPBasicBlock(), VPBB);
9119     VPBB = cast<VPBasicBlock>(VPBB->getSingleSuccessor());
9120   }
9121 
9122   // Fold the last, empty block into its predecessor.
9123   VPBB = VPBlockUtils::tryToMergeBlockIntoPredecessor(VPBB);
9124   assert(VPBB && "expected to fold last (empty) block");
9125   // After here, VPBB should not be used.
9126   VPBB = nullptr;
9127 
9128   assert(isa<VPRegionBlock>(Plan->getEntry()) &&
9129          !Plan->getEntry()->getEntryBasicBlock()->empty() &&
9130          "entry block must be set to a VPRegionBlock having a non-empty entry "
9131          "VPBasicBlock");
9132   RecipeBuilder.fixHeaderPhis();
9133 
9134   // ---------------------------------------------------------------------------
9135   // Transform initial VPlan: Apply previously taken decisions, in order, to
9136   // bring the VPlan to its final state.
9137   // ---------------------------------------------------------------------------
9138 
9139   // Apply Sink-After legal constraints.
9140   auto GetReplicateRegion = [](VPRecipeBase *R) -> VPRegionBlock * {
9141     auto *Region = dyn_cast_or_null<VPRegionBlock>(R->getParent()->getParent());
9142     if (Region && Region->isReplicator()) {
9143       assert(Region->getNumSuccessors() == 1 &&
9144              Region->getNumPredecessors() == 1 && "Expected SESE region!");
9145       assert(R->getParent()->size() == 1 &&
9146              "A recipe in an original replicator region must be the only "
9147              "recipe in its block");
9148       return Region;
9149     }
9150     return nullptr;
9151   };
9152   for (auto &Entry : SinkAfter) {
9153     VPRecipeBase *Sink = RecipeBuilder.getRecipe(Entry.first);
9154     VPRecipeBase *Target = RecipeBuilder.getRecipe(Entry.second);
9155 
9156     auto *TargetRegion = GetReplicateRegion(Target);
9157     auto *SinkRegion = GetReplicateRegion(Sink);
9158     if (!SinkRegion) {
9159       // If the sink source is not a replicate region, sink the recipe directly.
9160       if (TargetRegion) {
9161         // The target is in a replication region, make sure to move Sink to
9162         // the block after it, not into the replication region itself.
9163         VPBasicBlock *NextBlock =
9164             cast<VPBasicBlock>(TargetRegion->getSuccessors().front());
9165         Sink->moveBefore(*NextBlock, NextBlock->getFirstNonPhi());
9166       } else
9167         Sink->moveAfter(Target);
9168       continue;
9169     }
9170 
9171     // The sink source is in a replicate region. Unhook the region from the CFG.
9172     auto *SinkPred = SinkRegion->getSinglePredecessor();
9173     auto *SinkSucc = SinkRegion->getSingleSuccessor();
9174     VPBlockUtils::disconnectBlocks(SinkPred, SinkRegion);
9175     VPBlockUtils::disconnectBlocks(SinkRegion, SinkSucc);
9176     VPBlockUtils::connectBlocks(SinkPred, SinkSucc);
9177 
9178     if (TargetRegion) {
9179       // The target recipe is also in a replicate region, move the sink region
9180       // after the target region.
9181       auto *TargetSucc = TargetRegion->getSingleSuccessor();
9182       VPBlockUtils::disconnectBlocks(TargetRegion, TargetSucc);
9183       VPBlockUtils::connectBlocks(TargetRegion, SinkRegion);
9184       VPBlockUtils::connectBlocks(SinkRegion, TargetSucc);
9185     } else {
9186       // The sink source is in a replicate region, we need to move the whole
9187       // replicate region, which should only contain a single recipe in the
9188       // main block.
9189       auto *SplitBlock =
9190           Target->getParent()->splitAt(std::next(Target->getIterator()));
9191 
9192       auto *SplitPred = SplitBlock->getSinglePredecessor();
9193 
9194       VPBlockUtils::disconnectBlocks(SplitPred, SplitBlock);
9195       VPBlockUtils::connectBlocks(SplitPred, SinkRegion);
9196       VPBlockUtils::connectBlocks(SinkRegion, SplitBlock);
9197     }
9198   }
9199 
9200   VPlanTransforms::removeRedundantInductionCasts(*Plan);
9201 
9202   // Now that sink-after is done, move induction recipes for optimized truncates
9203   // to the phi section of the header block.
9204   for (VPWidenIntOrFpInductionRecipe *Ind : InductionsToMove)
9205     Ind->moveBefore(*HeaderVPBB, HeaderVPBB->getFirstNonPhi());
9206 
9207   // Adjust the recipes for any inloop reductions.
9208   adjustRecipesForReductions(cast<VPBasicBlock>(TopRegion->getExit()), Plan,
9209                              RecipeBuilder, Range.Start);
9210 
9211   // Introduce a recipe to combine the incoming and previous values of a
9212   // first-order recurrence.
9213   for (VPRecipeBase &R : Plan->getEntry()->getEntryBasicBlock()->phis()) {
9214     auto *RecurPhi = dyn_cast<VPFirstOrderRecurrencePHIRecipe>(&R);
9215     if (!RecurPhi)
9216       continue;
9217 
9218     VPRecipeBase *PrevRecipe = RecurPhi->getBackedgeRecipe();
9219     VPBasicBlock *InsertBlock = PrevRecipe->getParent();
9220     auto *Region = GetReplicateRegion(PrevRecipe);
9221     if (Region)
9222       InsertBlock = cast<VPBasicBlock>(Region->getSingleSuccessor());
9223     if (Region || PrevRecipe->isPhi())
9224       Builder.setInsertPoint(InsertBlock, InsertBlock->getFirstNonPhi());
9225     else
9226       Builder.setInsertPoint(InsertBlock, std::next(PrevRecipe->getIterator()));
9227 
9228     auto *RecurSplice = cast<VPInstruction>(
9229         Builder.createNaryOp(VPInstruction::FirstOrderRecurrenceSplice,
9230                              {RecurPhi, RecurPhi->getBackedgeValue()}));
9231 
9232     RecurPhi->replaceAllUsesWith(RecurSplice);
9233     // Set the first operand of RecurSplice to RecurPhi again, after replacing
9234     // all users.
9235     RecurSplice->setOperand(0, RecurPhi);
9236   }
9237 
9238   // Interleave memory: for each Interleave Group we marked earlier as relevant
9239   // for this VPlan, replace the Recipes widening its memory instructions with a
9240   // single VPInterleaveRecipe at its insertion point.
9241   for (auto IG : InterleaveGroups) {
9242     auto *Recipe = cast<VPWidenMemoryInstructionRecipe>(
9243         RecipeBuilder.getRecipe(IG->getInsertPos()));
9244     SmallVector<VPValue *, 4> StoredValues;
9245     for (unsigned i = 0; i < IG->getFactor(); ++i)
9246       if (auto *SI = dyn_cast_or_null<StoreInst>(IG->getMember(i))) {
9247         auto *StoreR =
9248             cast<VPWidenMemoryInstructionRecipe>(RecipeBuilder.getRecipe(SI));
9249         StoredValues.push_back(StoreR->getStoredValue());
9250       }
9251 
9252     auto *VPIG = new VPInterleaveRecipe(IG, Recipe->getAddr(), StoredValues,
9253                                         Recipe->getMask());
9254     VPIG->insertBefore(Recipe);
9255     unsigned J = 0;
9256     for (unsigned i = 0; i < IG->getFactor(); ++i)
9257       if (Instruction *Member = IG->getMember(i)) {
9258         if (!Member->getType()->isVoidTy()) {
9259           VPValue *OriginalV = Plan->getVPValue(Member);
9260           Plan->removeVPValueFor(Member);
9261           Plan->addVPValue(Member, VPIG->getVPValue(J));
9262           OriginalV->replaceAllUsesWith(VPIG->getVPValue(J));
9263           J++;
9264         }
9265         RecipeBuilder.getRecipe(Member)->eraseFromParent();
9266       }
9267   }
9268 
9269   // From this point onwards, VPlan-to-VPlan transformations may change the plan
9270   // in ways that accessing values using original IR values is incorrect.
9271   Plan->disableValue2VPValue();
9272 
9273   VPlanTransforms::sinkScalarOperands(*Plan);
9274   VPlanTransforms::mergeReplicateRegions(*Plan);
9275 
9276   std::string PlanName;
9277   raw_string_ostream RSO(PlanName);
9278   ElementCount VF = Range.Start;
9279   Plan->addVF(VF);
9280   RSO << "Initial VPlan for VF={" << VF;
9281   for (VF *= 2; ElementCount::isKnownLT(VF, Range.End); VF *= 2) {
9282     Plan->addVF(VF);
9283     RSO << "," << VF;
9284   }
9285   RSO << "},UF>=1";
9286   RSO.flush();
9287   Plan->setName(PlanName);
9288 
9289   // Fold Exit block into its predecessor if possible.
9290   // TODO: Fold block earlier once all VPlan transforms properly maintain a
9291   // VPBasicBlock as exit.
9292   VPBlockUtils::tryToMergeBlockIntoPredecessor(TopRegion->getExit());
9293 
9294   assert(VPlanVerifier::verifyPlanIsValid(*Plan) && "VPlan is invalid");
9295   return Plan;
9296 }
9297 
9298 VPlanPtr LoopVectorizationPlanner::buildVPlan(VFRange &Range) {
9299   // Outer loop handling: They may require CFG and instruction level
9300   // transformations before even evaluating whether vectorization is profitable.
9301   // Since we cannot modify the incoming IR, we need to build VPlan upfront in
9302   // the vectorization pipeline.
9303   assert(!OrigLoop->isInnermost());
9304   assert(EnableVPlanNativePath && "VPlan-native path is not enabled.");
9305 
9306   // Create new empty VPlan
9307   auto Plan = std::make_unique<VPlan>();
9308 
9309   // Build hierarchical CFG
9310   VPlanHCFGBuilder HCFGBuilder(OrigLoop, LI, *Plan);
9311   HCFGBuilder.buildHierarchicalCFG();
9312 
9313   for (ElementCount VF = Range.Start; ElementCount::isKnownLT(VF, Range.End);
9314        VF *= 2)
9315     Plan->addVF(VF);
9316 
9317   if (EnableVPlanPredication) {
9318     VPlanPredicator VPP(*Plan);
9319     VPP.predicate();
9320 
9321     // Avoid running transformation to recipes until masked code generation in
9322     // VPlan-native path is in place.
9323     return Plan;
9324   }
9325 
9326   SmallPtrSet<Instruction *, 1> DeadInstructions;
9327   VPlanTransforms::VPInstructionsToVPRecipes(
9328       OrigLoop, Plan,
9329       [this](PHINode *P) { return Legal->getIntOrFpInductionDescriptor(P); },
9330       DeadInstructions, *PSE.getSE());
9331   return Plan;
9332 }
9333 
9334 // Adjust the recipes for reductions. For in-loop reductions the chain of
9335 // instructions leading from the loop exit instr to the phi need to be converted
9336 // to reductions, with one operand being vector and the other being the scalar
9337 // reduction chain. For other reductions, a select is introduced between the phi
9338 // and live-out recipes when folding the tail.
9339 void LoopVectorizationPlanner::adjustRecipesForReductions(
9340     VPBasicBlock *LatchVPBB, VPlanPtr &Plan, VPRecipeBuilder &RecipeBuilder,
9341     ElementCount MinVF) {
9342   for (auto &Reduction : CM.getInLoopReductionChains()) {
9343     PHINode *Phi = Reduction.first;
9344     const RecurrenceDescriptor &RdxDesc =
9345         Legal->getReductionVars().find(Phi)->second;
9346     const SmallVector<Instruction *, 4> &ReductionOperations = Reduction.second;
9347 
9348     if (MinVF.isScalar() && !CM.useOrderedReductions(RdxDesc))
9349       continue;
9350 
9351     // ReductionOperations are orders top-down from the phi's use to the
9352     // LoopExitValue. We keep a track of the previous item (the Chain) to tell
9353     // which of the two operands will remain scalar and which will be reduced.
9354     // For minmax the chain will be the select instructions.
9355     Instruction *Chain = Phi;
9356     for (Instruction *R : ReductionOperations) {
9357       VPRecipeBase *WidenRecipe = RecipeBuilder.getRecipe(R);
9358       RecurKind Kind = RdxDesc.getRecurrenceKind();
9359 
9360       VPValue *ChainOp = Plan->getVPValue(Chain);
9361       unsigned FirstOpId;
9362       assert(!RecurrenceDescriptor::isSelectCmpRecurrenceKind(Kind) &&
9363              "Only min/max recurrences allowed for inloop reductions");
9364       // Recognize a call to the llvm.fmuladd intrinsic.
9365       bool IsFMulAdd = (Kind == RecurKind::FMulAdd);
9366       assert((!IsFMulAdd || RecurrenceDescriptor::isFMulAddIntrinsic(R)) &&
9367              "Expected instruction to be a call to the llvm.fmuladd intrinsic");
9368       if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind)) {
9369         assert(isa<VPWidenSelectRecipe>(WidenRecipe) &&
9370                "Expected to replace a VPWidenSelectSC");
9371         FirstOpId = 1;
9372       } else {
9373         assert((MinVF.isScalar() || isa<VPWidenRecipe>(WidenRecipe) ||
9374                 (IsFMulAdd && isa<VPWidenCallRecipe>(WidenRecipe))) &&
9375                "Expected to replace a VPWidenSC");
9376         FirstOpId = 0;
9377       }
9378       unsigned VecOpId =
9379           R->getOperand(FirstOpId) == Chain ? FirstOpId + 1 : FirstOpId;
9380       VPValue *VecOp = Plan->getVPValue(R->getOperand(VecOpId));
9381 
9382       auto *CondOp = CM.foldTailByMasking()
9383                          ? RecipeBuilder.createBlockInMask(R->getParent(), Plan)
9384                          : nullptr;
9385 
9386       if (IsFMulAdd) {
9387         // If the instruction is a call to the llvm.fmuladd intrinsic then we
9388         // need to create an fmul recipe to use as the vector operand for the
9389         // fadd reduction.
9390         VPInstruction *FMulRecipe = new VPInstruction(
9391             Instruction::FMul, {VecOp, Plan->getVPValue(R->getOperand(1))});
9392         FMulRecipe->setFastMathFlags(R->getFastMathFlags());
9393         WidenRecipe->getParent()->insert(FMulRecipe,
9394                                          WidenRecipe->getIterator());
9395         VecOp = FMulRecipe;
9396       }
9397       VPReductionRecipe *RedRecipe =
9398           new VPReductionRecipe(&RdxDesc, R, ChainOp, VecOp, CondOp, TTI);
9399       WidenRecipe->getVPSingleValue()->replaceAllUsesWith(RedRecipe);
9400       Plan->removeVPValueFor(R);
9401       Plan->addVPValue(R, RedRecipe);
9402       WidenRecipe->getParent()->insert(RedRecipe, WidenRecipe->getIterator());
9403       WidenRecipe->getVPSingleValue()->replaceAllUsesWith(RedRecipe);
9404       WidenRecipe->eraseFromParent();
9405 
9406       if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind)) {
9407         VPRecipeBase *CompareRecipe =
9408             RecipeBuilder.getRecipe(cast<Instruction>(R->getOperand(0)));
9409         assert(isa<VPWidenRecipe>(CompareRecipe) &&
9410                "Expected to replace a VPWidenSC");
9411         assert(cast<VPWidenRecipe>(CompareRecipe)->getNumUsers() == 0 &&
9412                "Expected no remaining users");
9413         CompareRecipe->eraseFromParent();
9414       }
9415       Chain = R;
9416     }
9417   }
9418 
9419   // If tail is folded by masking, introduce selects between the phi
9420   // and the live-out instruction of each reduction, at the end of the latch.
9421   if (CM.foldTailByMasking()) {
9422     for (VPRecipeBase &R : Plan->getEntry()->getEntryBasicBlock()->phis()) {
9423       VPReductionPHIRecipe *PhiR = dyn_cast<VPReductionPHIRecipe>(&R);
9424       if (!PhiR || PhiR->isInLoop())
9425         continue;
9426       Builder.setInsertPoint(LatchVPBB);
9427       VPValue *Cond =
9428           RecipeBuilder.createBlockInMask(OrigLoop->getHeader(), Plan);
9429       VPValue *Red = PhiR->getBackedgeValue();
9430       Builder.createNaryOp(Instruction::Select, {Cond, Red, PhiR});
9431     }
9432   }
9433 }
9434 
9435 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
9436 void VPInterleaveRecipe::print(raw_ostream &O, const Twine &Indent,
9437                                VPSlotTracker &SlotTracker) const {
9438   O << Indent << "INTERLEAVE-GROUP with factor " << IG->getFactor() << " at ";
9439   IG->getInsertPos()->printAsOperand(O, false);
9440   O << ", ";
9441   getAddr()->printAsOperand(O, SlotTracker);
9442   VPValue *Mask = getMask();
9443   if (Mask) {
9444     O << ", ";
9445     Mask->printAsOperand(O, SlotTracker);
9446   }
9447 
9448   unsigned OpIdx = 0;
9449   for (unsigned i = 0; i < IG->getFactor(); ++i) {
9450     if (!IG->getMember(i))
9451       continue;
9452     if (getNumStoreOperands() > 0) {
9453       O << "\n" << Indent << "  store ";
9454       getOperand(1 + OpIdx)->printAsOperand(O, SlotTracker);
9455       O << " to index " << i;
9456     } else {
9457       O << "\n" << Indent << "  ";
9458       getVPValue(OpIdx)->printAsOperand(O, SlotTracker);
9459       O << " = load from index " << i;
9460     }
9461     ++OpIdx;
9462   }
9463 }
9464 #endif
9465 
9466 void VPWidenCallRecipe::execute(VPTransformState &State) {
9467   State.ILV->widenCallInstruction(*cast<CallInst>(getUnderlyingInstr()), this,
9468                                   *this, State);
9469 }
9470 
9471 void VPWidenSelectRecipe::execute(VPTransformState &State) {
9472   auto &I = *cast<SelectInst>(getUnderlyingInstr());
9473   State.ILV->setDebugLocFromInst(&I);
9474 
9475   // The condition can be loop invariant  but still defined inside the
9476   // loop. This means that we can't just use the original 'cond' value.
9477   // We have to take the 'vectorized' value and pick the first lane.
9478   // Instcombine will make this a no-op.
9479   auto *InvarCond =
9480       InvariantCond ? State.get(getOperand(0), VPIteration(0, 0)) : nullptr;
9481 
9482   for (unsigned Part = 0; Part < State.UF; ++Part) {
9483     Value *Cond = InvarCond ? InvarCond : State.get(getOperand(0), Part);
9484     Value *Op0 = State.get(getOperand(1), Part);
9485     Value *Op1 = State.get(getOperand(2), Part);
9486     Value *Sel = State.Builder.CreateSelect(Cond, Op0, Op1);
9487     State.set(this, Sel, Part);
9488     State.ILV->addMetadata(Sel, &I);
9489   }
9490 }
9491 
9492 void VPWidenRecipe::execute(VPTransformState &State) {
9493   auto &I = *cast<Instruction>(getUnderlyingValue());
9494   auto &Builder = State.Builder;
9495   switch (I.getOpcode()) {
9496   case Instruction::Call:
9497   case Instruction::Br:
9498   case Instruction::PHI:
9499   case Instruction::GetElementPtr:
9500   case Instruction::Select:
9501     llvm_unreachable("This instruction is handled by a different recipe.");
9502   case Instruction::UDiv:
9503   case Instruction::SDiv:
9504   case Instruction::SRem:
9505   case Instruction::URem:
9506   case Instruction::Add:
9507   case Instruction::FAdd:
9508   case Instruction::Sub:
9509   case Instruction::FSub:
9510   case Instruction::FNeg:
9511   case Instruction::Mul:
9512   case Instruction::FMul:
9513   case Instruction::FDiv:
9514   case Instruction::FRem:
9515   case Instruction::Shl:
9516   case Instruction::LShr:
9517   case Instruction::AShr:
9518   case Instruction::And:
9519   case Instruction::Or:
9520   case Instruction::Xor: {
9521     // Just widen unops and binops.
9522     State.ILV->setDebugLocFromInst(&I);
9523 
9524     for (unsigned Part = 0; Part < State.UF; ++Part) {
9525       SmallVector<Value *, 2> Ops;
9526       for (VPValue *VPOp : operands())
9527         Ops.push_back(State.get(VPOp, Part));
9528 
9529       Value *V = Builder.CreateNAryOp(I.getOpcode(), Ops);
9530 
9531       if (auto *VecOp = dyn_cast<Instruction>(V)) {
9532         VecOp->copyIRFlags(&I);
9533 
9534         // If the instruction is vectorized and was in a basic block that needed
9535         // predication, we can't propagate poison-generating flags (nuw/nsw,
9536         // exact, etc.). The control flow has been linearized and the
9537         // instruction is no longer guarded by the predicate, which could make
9538         // the flag properties to no longer hold.
9539         if (State.MayGeneratePoisonRecipes.contains(this))
9540           VecOp->dropPoisonGeneratingFlags();
9541       }
9542 
9543       // Use this vector value for all users of the original instruction.
9544       State.set(this, V, Part);
9545       State.ILV->addMetadata(V, &I);
9546     }
9547 
9548     break;
9549   }
9550   case Instruction::ICmp:
9551   case Instruction::FCmp: {
9552     // Widen compares. Generate vector compares.
9553     bool FCmp = (I.getOpcode() == Instruction::FCmp);
9554     auto *Cmp = cast<CmpInst>(&I);
9555     State.ILV->setDebugLocFromInst(Cmp);
9556     for (unsigned Part = 0; Part < State.UF; ++Part) {
9557       Value *A = State.get(getOperand(0), Part);
9558       Value *B = State.get(getOperand(1), Part);
9559       Value *C = nullptr;
9560       if (FCmp) {
9561         // Propagate fast math flags.
9562         IRBuilder<>::FastMathFlagGuard FMFG(Builder);
9563         Builder.setFastMathFlags(Cmp->getFastMathFlags());
9564         C = Builder.CreateFCmp(Cmp->getPredicate(), A, B);
9565       } else {
9566         C = Builder.CreateICmp(Cmp->getPredicate(), A, B);
9567       }
9568       State.set(this, C, Part);
9569       State.ILV->addMetadata(C, &I);
9570     }
9571 
9572     break;
9573   }
9574 
9575   case Instruction::ZExt:
9576   case Instruction::SExt:
9577   case Instruction::FPToUI:
9578   case Instruction::FPToSI:
9579   case Instruction::FPExt:
9580   case Instruction::PtrToInt:
9581   case Instruction::IntToPtr:
9582   case Instruction::SIToFP:
9583   case Instruction::UIToFP:
9584   case Instruction::Trunc:
9585   case Instruction::FPTrunc:
9586   case Instruction::BitCast: {
9587     auto *CI = cast<CastInst>(&I);
9588     State.ILV->setDebugLocFromInst(CI);
9589 
9590     /// Vectorize casts.
9591     Type *DestTy = (State.VF.isScalar())
9592                        ? CI->getType()
9593                        : VectorType::get(CI->getType(), State.VF);
9594 
9595     for (unsigned Part = 0; Part < State.UF; ++Part) {
9596       Value *A = State.get(getOperand(0), Part);
9597       Value *Cast = Builder.CreateCast(CI->getOpcode(), A, DestTy);
9598       State.set(this, Cast, Part);
9599       State.ILV->addMetadata(Cast, &I);
9600     }
9601     break;
9602   }
9603   default:
9604     // This instruction is not vectorized by simple widening.
9605     LLVM_DEBUG(dbgs() << "LV: Found an unhandled instruction: " << I);
9606     llvm_unreachable("Unhandled instruction!");
9607   } // end of switch.
9608 }
9609 
9610 void VPWidenGEPRecipe::execute(VPTransformState &State) {
9611   auto *GEP = cast<GetElementPtrInst>(getUnderlyingInstr());
9612   // Construct a vector GEP by widening the operands of the scalar GEP as
9613   // necessary. We mark the vector GEP 'inbounds' if appropriate. A GEP
9614   // results in a vector of pointers when at least one operand of the GEP
9615   // is vector-typed. Thus, to keep the representation compact, we only use
9616   // vector-typed operands for loop-varying values.
9617 
9618   if (State.VF.isVector() && IsPtrLoopInvariant && IsIndexLoopInvariant.all()) {
9619     // If we are vectorizing, but the GEP has only loop-invariant operands,
9620     // the GEP we build (by only using vector-typed operands for
9621     // loop-varying values) would be a scalar pointer. Thus, to ensure we
9622     // produce a vector of pointers, we need to either arbitrarily pick an
9623     // operand to broadcast, or broadcast a clone of the original GEP.
9624     // Here, we broadcast a clone of the original.
9625     //
9626     // TODO: If at some point we decide to scalarize instructions having
9627     //       loop-invariant operands, this special case will no longer be
9628     //       required. We would add the scalarization decision to
9629     //       collectLoopScalars() and teach getVectorValue() to broadcast
9630     //       the lane-zero scalar value.
9631     auto *Clone = State.Builder.Insert(GEP->clone());
9632     for (unsigned Part = 0; Part < State.UF; ++Part) {
9633       Value *EntryPart = State.Builder.CreateVectorSplat(State.VF, Clone);
9634       State.set(this, EntryPart, Part);
9635       State.ILV->addMetadata(EntryPart, GEP);
9636     }
9637   } else {
9638     // If the GEP has at least one loop-varying operand, we are sure to
9639     // produce a vector of pointers. But if we are only unrolling, we want
9640     // to produce a scalar GEP for each unroll part. Thus, the GEP we
9641     // produce with the code below will be scalar (if VF == 1) or vector
9642     // (otherwise). Note that for the unroll-only case, we still maintain
9643     // values in the vector mapping with initVector, as we do for other
9644     // instructions.
9645     for (unsigned Part = 0; Part < State.UF; ++Part) {
9646       // The pointer operand of the new GEP. If it's loop-invariant, we
9647       // won't broadcast it.
9648       auto *Ptr = IsPtrLoopInvariant
9649                       ? State.get(getOperand(0), VPIteration(0, 0))
9650                       : State.get(getOperand(0), Part);
9651 
9652       // Collect all the indices for the new GEP. If any index is
9653       // loop-invariant, we won't broadcast it.
9654       SmallVector<Value *, 4> Indices;
9655       for (unsigned I = 1, E = getNumOperands(); I < E; I++) {
9656         VPValue *Operand = getOperand(I);
9657         if (IsIndexLoopInvariant[I - 1])
9658           Indices.push_back(State.get(Operand, VPIteration(0, 0)));
9659         else
9660           Indices.push_back(State.get(Operand, Part));
9661       }
9662 
9663       // If the GEP instruction is vectorized and was in a basic block that
9664       // needed predication, we can't propagate the poison-generating 'inbounds'
9665       // flag. The control flow has been linearized and the GEP is no longer
9666       // guarded by the predicate, which could make the 'inbounds' properties to
9667       // no longer hold.
9668       bool IsInBounds =
9669           GEP->isInBounds() && State.MayGeneratePoisonRecipes.count(this) == 0;
9670 
9671       // Create the new GEP. Note that this GEP may be a scalar if VF == 1,
9672       // but it should be a vector, otherwise.
9673       auto *NewGEP = IsInBounds
9674                          ? State.Builder.CreateInBoundsGEP(
9675                                GEP->getSourceElementType(), Ptr, Indices)
9676                          : State.Builder.CreateGEP(GEP->getSourceElementType(),
9677                                                    Ptr, Indices);
9678       assert((State.VF.isScalar() || NewGEP->getType()->isVectorTy()) &&
9679              "NewGEP is not a pointer vector");
9680       State.set(this, NewGEP, Part);
9681       State.ILV->addMetadata(NewGEP, GEP);
9682     }
9683   }
9684 }
9685 
9686 void VPWidenIntOrFpInductionRecipe::execute(VPTransformState &State) {
9687   assert(!State.Instance && "Int or FP induction being replicated.");
9688   State.ILV->widenIntOrFpInduction(IV, getInductionDescriptor(),
9689                                    getStartValue()->getLiveInIRValue(),
9690                                    getTruncInst(), getVPValue(0), State);
9691 }
9692 
9693 void VPWidenPHIRecipe::execute(VPTransformState &State) {
9694   State.ILV->widenPHIInstruction(cast<PHINode>(getUnderlyingValue()), this,
9695                                  State);
9696 }
9697 
9698 void VPBlendRecipe::execute(VPTransformState &State) {
9699   State.ILV->setDebugLocFromInst(Phi, &State.Builder);
9700   // We know that all PHIs in non-header blocks are converted into
9701   // selects, so we don't have to worry about the insertion order and we
9702   // can just use the builder.
9703   // At this point we generate the predication tree. There may be
9704   // duplications since this is a simple recursive scan, but future
9705   // optimizations will clean it up.
9706 
9707   unsigned NumIncoming = getNumIncomingValues();
9708 
9709   // Generate a sequence of selects of the form:
9710   // SELECT(Mask3, In3,
9711   //        SELECT(Mask2, In2,
9712   //               SELECT(Mask1, In1,
9713   //                      In0)))
9714   // Note that Mask0 is never used: lanes for which no path reaches this phi and
9715   // are essentially undef are taken from In0.
9716   InnerLoopVectorizer::VectorParts Entry(State.UF);
9717   for (unsigned In = 0; In < NumIncoming; ++In) {
9718     for (unsigned Part = 0; Part < State.UF; ++Part) {
9719       // We might have single edge PHIs (blocks) - use an identity
9720       // 'select' for the first PHI operand.
9721       Value *In0 = State.get(getIncomingValue(In), Part);
9722       if (In == 0)
9723         Entry[Part] = In0; // Initialize with the first incoming value.
9724       else {
9725         // Select between the current value and the previous incoming edge
9726         // based on the incoming mask.
9727         Value *Cond = State.get(getMask(In), Part);
9728         Entry[Part] =
9729             State.Builder.CreateSelect(Cond, In0, Entry[Part], "predphi");
9730       }
9731     }
9732   }
9733   for (unsigned Part = 0; Part < State.UF; ++Part)
9734     State.set(this, Entry[Part], Part);
9735 }
9736 
9737 void VPInterleaveRecipe::execute(VPTransformState &State) {
9738   assert(!State.Instance && "Interleave group being replicated.");
9739   State.ILV->vectorizeInterleaveGroup(IG, definedValues(), State, getAddr(),
9740                                       getStoredValues(), getMask());
9741 }
9742 
9743 void VPReductionRecipe::execute(VPTransformState &State) {
9744   assert(!State.Instance && "Reduction being replicated.");
9745   Value *PrevInChain = State.get(getChainOp(), 0);
9746   RecurKind Kind = RdxDesc->getRecurrenceKind();
9747   bool IsOrdered = State.ILV->useOrderedReductions(*RdxDesc);
9748   // Propagate the fast-math flags carried by the underlying instruction.
9749   IRBuilderBase::FastMathFlagGuard FMFGuard(State.Builder);
9750   State.Builder.setFastMathFlags(RdxDesc->getFastMathFlags());
9751   for (unsigned Part = 0; Part < State.UF; ++Part) {
9752     Value *NewVecOp = State.get(getVecOp(), Part);
9753     if (VPValue *Cond = getCondOp()) {
9754       Value *NewCond = State.get(Cond, Part);
9755       VectorType *VecTy = cast<VectorType>(NewVecOp->getType());
9756       Value *Iden = RdxDesc->getRecurrenceIdentity(
9757           Kind, VecTy->getElementType(), RdxDesc->getFastMathFlags());
9758       Value *IdenVec =
9759           State.Builder.CreateVectorSplat(VecTy->getElementCount(), Iden);
9760       Value *Select = State.Builder.CreateSelect(NewCond, NewVecOp, IdenVec);
9761       NewVecOp = Select;
9762     }
9763     Value *NewRed;
9764     Value *NextInChain;
9765     if (IsOrdered) {
9766       if (State.VF.isVector())
9767         NewRed = createOrderedReduction(State.Builder, *RdxDesc, NewVecOp,
9768                                         PrevInChain);
9769       else
9770         NewRed = State.Builder.CreateBinOp(
9771             (Instruction::BinaryOps)RdxDesc->getOpcode(Kind), PrevInChain,
9772             NewVecOp);
9773       PrevInChain = NewRed;
9774     } else {
9775       PrevInChain = State.get(getChainOp(), Part);
9776       NewRed = createTargetReduction(State.Builder, TTI, *RdxDesc, NewVecOp);
9777     }
9778     if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind)) {
9779       NextInChain =
9780           createMinMaxOp(State.Builder, RdxDesc->getRecurrenceKind(),
9781                          NewRed, PrevInChain);
9782     } else if (IsOrdered)
9783       NextInChain = NewRed;
9784     else
9785       NextInChain = State.Builder.CreateBinOp(
9786           (Instruction::BinaryOps)RdxDesc->getOpcode(Kind), NewRed,
9787           PrevInChain);
9788     State.set(this, NextInChain, Part);
9789   }
9790 }
9791 
9792 void VPReplicateRecipe::execute(VPTransformState &State) {
9793   if (State.Instance) { // Generate a single instance.
9794     assert(!State.VF.isScalable() && "Can't scalarize a scalable vector");
9795     State.ILV->scalarizeInstruction(getUnderlyingInstr(), this, *State.Instance,
9796                                     IsPredicated, State);
9797     // Insert scalar instance packing it into a vector.
9798     if (AlsoPack && State.VF.isVector()) {
9799       // If we're constructing lane 0, initialize to start from poison.
9800       if (State.Instance->Lane.isFirstLane()) {
9801         assert(!State.VF.isScalable() && "VF is assumed to be non scalable.");
9802         Value *Poison = PoisonValue::get(
9803             VectorType::get(getUnderlyingValue()->getType(), State.VF));
9804         State.set(this, Poison, State.Instance->Part);
9805       }
9806       State.ILV->packScalarIntoVectorValue(this, *State.Instance, State);
9807     }
9808     return;
9809   }
9810 
9811   // Generate scalar instances for all VF lanes of all UF parts, unless the
9812   // instruction is uniform inwhich case generate only the first lane for each
9813   // of the UF parts.
9814   unsigned EndLane = IsUniform ? 1 : State.VF.getKnownMinValue();
9815   assert((!State.VF.isScalable() || IsUniform) &&
9816          "Can't scalarize a scalable vector");
9817   for (unsigned Part = 0; Part < State.UF; ++Part)
9818     for (unsigned Lane = 0; Lane < EndLane; ++Lane)
9819       State.ILV->scalarizeInstruction(getUnderlyingInstr(), this,
9820                                       VPIteration(Part, Lane), IsPredicated,
9821                                       State);
9822 }
9823 
9824 void VPBranchOnMaskRecipe::execute(VPTransformState &State) {
9825   assert(State.Instance && "Branch on Mask works only on single instance.");
9826 
9827   unsigned Part = State.Instance->Part;
9828   unsigned Lane = State.Instance->Lane.getKnownLane();
9829 
9830   Value *ConditionBit = nullptr;
9831   VPValue *BlockInMask = getMask();
9832   if (BlockInMask) {
9833     ConditionBit = State.get(BlockInMask, Part);
9834     if (ConditionBit->getType()->isVectorTy())
9835       ConditionBit = State.Builder.CreateExtractElement(
9836           ConditionBit, State.Builder.getInt32(Lane));
9837   } else // Block in mask is all-one.
9838     ConditionBit = State.Builder.getTrue();
9839 
9840   // Replace the temporary unreachable terminator with a new conditional branch,
9841   // whose two destinations will be set later when they are created.
9842   auto *CurrentTerminator = State.CFG.PrevBB->getTerminator();
9843   assert(isa<UnreachableInst>(CurrentTerminator) &&
9844          "Expected to replace unreachable terminator with conditional branch.");
9845   auto *CondBr = BranchInst::Create(State.CFG.PrevBB, nullptr, ConditionBit);
9846   CondBr->setSuccessor(0, nullptr);
9847   ReplaceInstWithInst(CurrentTerminator, CondBr);
9848 }
9849 
9850 void VPPredInstPHIRecipe::execute(VPTransformState &State) {
9851   assert(State.Instance && "Predicated instruction PHI works per instance.");
9852   Instruction *ScalarPredInst =
9853       cast<Instruction>(State.get(getOperand(0), *State.Instance));
9854   BasicBlock *PredicatedBB = ScalarPredInst->getParent();
9855   BasicBlock *PredicatingBB = PredicatedBB->getSinglePredecessor();
9856   assert(PredicatingBB && "Predicated block has no single predecessor.");
9857   assert(isa<VPReplicateRecipe>(getOperand(0)) &&
9858          "operand must be VPReplicateRecipe");
9859 
9860   // By current pack/unpack logic we need to generate only a single phi node: if
9861   // a vector value for the predicated instruction exists at this point it means
9862   // the instruction has vector users only, and a phi for the vector value is
9863   // needed. In this case the recipe of the predicated instruction is marked to
9864   // also do that packing, thereby "hoisting" the insert-element sequence.
9865   // Otherwise, a phi node for the scalar value is needed.
9866   unsigned Part = State.Instance->Part;
9867   if (State.hasVectorValue(getOperand(0), Part)) {
9868     Value *VectorValue = State.get(getOperand(0), Part);
9869     InsertElementInst *IEI = cast<InsertElementInst>(VectorValue);
9870     PHINode *VPhi = State.Builder.CreatePHI(IEI->getType(), 2);
9871     VPhi->addIncoming(IEI->getOperand(0), PredicatingBB); // Unmodified vector.
9872     VPhi->addIncoming(IEI, PredicatedBB); // New vector with inserted element.
9873     if (State.hasVectorValue(this, Part))
9874       State.reset(this, VPhi, Part);
9875     else
9876       State.set(this, VPhi, Part);
9877     // NOTE: Currently we need to update the value of the operand, so the next
9878     // predicated iteration inserts its generated value in the correct vector.
9879     State.reset(getOperand(0), VPhi, Part);
9880   } else {
9881     Type *PredInstType = getOperand(0)->getUnderlyingValue()->getType();
9882     PHINode *Phi = State.Builder.CreatePHI(PredInstType, 2);
9883     Phi->addIncoming(PoisonValue::get(ScalarPredInst->getType()),
9884                      PredicatingBB);
9885     Phi->addIncoming(ScalarPredInst, PredicatedBB);
9886     if (State.hasScalarValue(this, *State.Instance))
9887       State.reset(this, Phi, *State.Instance);
9888     else
9889       State.set(this, Phi, *State.Instance);
9890     // NOTE: Currently we need to update the value of the operand, so the next
9891     // predicated iteration inserts its generated value in the correct vector.
9892     State.reset(getOperand(0), Phi, *State.Instance);
9893   }
9894 }
9895 
9896 void VPWidenMemoryInstructionRecipe::execute(VPTransformState &State) {
9897   VPValue *StoredValue = isStore() ? getStoredValue() : nullptr;
9898 
9899   // Attempt to issue a wide load.
9900   LoadInst *LI = dyn_cast<LoadInst>(&Ingredient);
9901   StoreInst *SI = dyn_cast<StoreInst>(&Ingredient);
9902 
9903   assert((LI || SI) && "Invalid Load/Store instruction");
9904   assert((!SI || StoredValue) && "No stored value provided for widened store");
9905   assert((!LI || !StoredValue) && "Stored value provided for widened load");
9906 
9907   Type *ScalarDataTy = getLoadStoreType(&Ingredient);
9908 
9909   auto *DataTy = VectorType::get(ScalarDataTy, State.VF);
9910   const Align Alignment = getLoadStoreAlignment(&Ingredient);
9911   bool CreateGatherScatter = !Consecutive;
9912 
9913   auto &Builder = State.Builder;
9914   InnerLoopVectorizer::VectorParts BlockInMaskParts(State.UF);
9915   bool isMaskRequired = getMask();
9916   if (isMaskRequired)
9917     for (unsigned Part = 0; Part < State.UF; ++Part)
9918       BlockInMaskParts[Part] = State.get(getMask(), Part);
9919 
9920   const auto CreateVecPtr = [&](unsigned Part, Value *Ptr) -> Value * {
9921     // Calculate the pointer for the specific unroll-part.
9922     GetElementPtrInst *PartPtr = nullptr;
9923 
9924     bool InBounds = false;
9925     if (auto *gep = dyn_cast<GetElementPtrInst>(Ptr->stripPointerCasts()))
9926       InBounds = gep->isInBounds();
9927     if (Reverse) {
9928       // If the address is consecutive but reversed, then the
9929       // wide store needs to start at the last vector element.
9930       // RunTimeVF =  VScale * VF.getKnownMinValue()
9931       // For fixed-width VScale is 1, then RunTimeVF = VF.getKnownMinValue()
9932       Value *RunTimeVF = getRuntimeVF(Builder, Builder.getInt32Ty(), State.VF);
9933       // NumElt = -Part * RunTimeVF
9934       Value *NumElt = Builder.CreateMul(Builder.getInt32(-Part), RunTimeVF);
9935       // LastLane = 1 - RunTimeVF
9936       Value *LastLane = Builder.CreateSub(Builder.getInt32(1), RunTimeVF);
9937       PartPtr =
9938           cast<GetElementPtrInst>(Builder.CreateGEP(ScalarDataTy, Ptr, NumElt));
9939       PartPtr->setIsInBounds(InBounds);
9940       PartPtr = cast<GetElementPtrInst>(
9941           Builder.CreateGEP(ScalarDataTy, PartPtr, LastLane));
9942       PartPtr->setIsInBounds(InBounds);
9943       if (isMaskRequired) // Reverse of a null all-one mask is a null mask.
9944         BlockInMaskParts[Part] =
9945             Builder.CreateVectorReverse(BlockInMaskParts[Part], "reverse");
9946     } else {
9947       Value *Increment =
9948           createStepForVF(Builder, Builder.getInt32Ty(), State.VF, Part);
9949       PartPtr = cast<GetElementPtrInst>(
9950           Builder.CreateGEP(ScalarDataTy, Ptr, Increment));
9951       PartPtr->setIsInBounds(InBounds);
9952     }
9953 
9954     unsigned AddressSpace = Ptr->getType()->getPointerAddressSpace();
9955     return Builder.CreateBitCast(PartPtr, DataTy->getPointerTo(AddressSpace));
9956   };
9957 
9958   // Handle Stores:
9959   if (SI) {
9960     State.ILV->setDebugLocFromInst(SI);
9961 
9962     for (unsigned Part = 0; Part < State.UF; ++Part) {
9963       Instruction *NewSI = nullptr;
9964       Value *StoredVal = State.get(StoredValue, Part);
9965       if (CreateGatherScatter) {
9966         Value *MaskPart = isMaskRequired ? BlockInMaskParts[Part] : nullptr;
9967         Value *VectorGep = State.get(getAddr(), Part);
9968         NewSI = Builder.CreateMaskedScatter(StoredVal, VectorGep, Alignment,
9969                                             MaskPart);
9970       } else {
9971         if (Reverse) {
9972           // If we store to reverse consecutive memory locations, then we need
9973           // to reverse the order of elements in the stored value.
9974           StoredVal = Builder.CreateVectorReverse(StoredVal, "reverse");
9975           // We don't want to update the value in the map as it might be used in
9976           // another expression. So don't call resetVectorValue(StoredVal).
9977         }
9978         auto *VecPtr =
9979             CreateVecPtr(Part, State.get(getAddr(), VPIteration(0, 0)));
9980         if (isMaskRequired)
9981           NewSI = Builder.CreateMaskedStore(StoredVal, VecPtr, Alignment,
9982                                             BlockInMaskParts[Part]);
9983         else
9984           NewSI = Builder.CreateAlignedStore(StoredVal, VecPtr, Alignment);
9985       }
9986       State.ILV->addMetadata(NewSI, SI);
9987     }
9988     return;
9989   }
9990 
9991   // Handle loads.
9992   assert(LI && "Must have a load instruction");
9993   State.ILV->setDebugLocFromInst(LI);
9994   for (unsigned Part = 0; Part < State.UF; ++Part) {
9995     Value *NewLI;
9996     if (CreateGatherScatter) {
9997       Value *MaskPart = isMaskRequired ? BlockInMaskParts[Part] : nullptr;
9998       Value *VectorGep = State.get(getAddr(), Part);
9999       NewLI = Builder.CreateMaskedGather(DataTy, VectorGep, Alignment, MaskPart,
10000                                          nullptr, "wide.masked.gather");
10001       State.ILV->addMetadata(NewLI, LI);
10002     } else {
10003       auto *VecPtr =
10004           CreateVecPtr(Part, State.get(getAddr(), VPIteration(0, 0)));
10005       if (isMaskRequired)
10006         NewLI = Builder.CreateMaskedLoad(
10007             DataTy, VecPtr, Alignment, BlockInMaskParts[Part],
10008             PoisonValue::get(DataTy), "wide.masked.load");
10009       else
10010         NewLI =
10011             Builder.CreateAlignedLoad(DataTy, VecPtr, Alignment, "wide.load");
10012 
10013       // Add metadata to the load, but setVectorValue to the reverse shuffle.
10014       State.ILV->addMetadata(NewLI, LI);
10015       if (Reverse)
10016         NewLI = Builder.CreateVectorReverse(NewLI, "reverse");
10017     }
10018 
10019     State.set(getVPSingleValue(), NewLI, Part);
10020   }
10021 }
10022 
10023 // Determine how to lower the scalar epilogue, which depends on 1) optimising
10024 // for minimum code-size, 2) predicate compiler options, 3) loop hints forcing
10025 // predication, and 4) a TTI hook that analyses whether the loop is suitable
10026 // for predication.
10027 static ScalarEpilogueLowering getScalarEpilogueLowering(
10028     Function *F, Loop *L, LoopVectorizeHints &Hints, ProfileSummaryInfo *PSI,
10029     BlockFrequencyInfo *BFI, TargetTransformInfo *TTI, TargetLibraryInfo *TLI,
10030     AssumptionCache *AC, LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT,
10031     LoopVectorizationLegality &LVL) {
10032   // 1) OptSize takes precedence over all other options, i.e. if this is set,
10033   // don't look at hints or options, and don't request a scalar epilogue.
10034   // (For PGSO, as shouldOptimizeForSize isn't currently accessible from
10035   // LoopAccessInfo (due to code dependency and not being able to reliably get
10036   // PSI/BFI from a loop analysis under NPM), we cannot suppress the collection
10037   // of strides in LoopAccessInfo::analyzeLoop() and vectorize without
10038   // versioning when the vectorization is forced, unlike hasOptSize. So revert
10039   // back to the old way and vectorize with versioning when forced. See D81345.)
10040   if (F->hasOptSize() || (llvm::shouldOptimizeForSize(L->getHeader(), PSI, BFI,
10041                                                       PGSOQueryType::IRPass) &&
10042                           Hints.getForce() != LoopVectorizeHints::FK_Enabled))
10043     return CM_ScalarEpilogueNotAllowedOptSize;
10044 
10045   // 2) If set, obey the directives
10046   if (PreferPredicateOverEpilogue.getNumOccurrences()) {
10047     switch (PreferPredicateOverEpilogue) {
10048     case PreferPredicateTy::ScalarEpilogue:
10049       return CM_ScalarEpilogueAllowed;
10050     case PreferPredicateTy::PredicateElseScalarEpilogue:
10051       return CM_ScalarEpilogueNotNeededUsePredicate;
10052     case PreferPredicateTy::PredicateOrDontVectorize:
10053       return CM_ScalarEpilogueNotAllowedUsePredicate;
10054     };
10055   }
10056 
10057   // 3) If set, obey the hints
10058   switch (Hints.getPredicate()) {
10059   case LoopVectorizeHints::FK_Enabled:
10060     return CM_ScalarEpilogueNotNeededUsePredicate;
10061   case LoopVectorizeHints::FK_Disabled:
10062     return CM_ScalarEpilogueAllowed;
10063   };
10064 
10065   // 4) if the TTI hook indicates this is profitable, request predication.
10066   if (TTI->preferPredicateOverEpilogue(L, LI, *SE, *AC, TLI, DT,
10067                                        LVL.getLAI()))
10068     return CM_ScalarEpilogueNotNeededUsePredicate;
10069 
10070   return CM_ScalarEpilogueAllowed;
10071 }
10072 
10073 Value *VPTransformState::get(VPValue *Def, unsigned Part) {
10074   // If Values have been set for this Def return the one relevant for \p Part.
10075   if (hasVectorValue(Def, Part))
10076     return Data.PerPartOutput[Def][Part];
10077 
10078   if (!hasScalarValue(Def, {Part, 0})) {
10079     Value *IRV = Def->getLiveInIRValue();
10080     Value *B = ILV->getBroadcastInstrs(IRV);
10081     set(Def, B, Part);
10082     return B;
10083   }
10084 
10085   Value *ScalarValue = get(Def, {Part, 0});
10086   // If we aren't vectorizing, we can just copy the scalar map values over
10087   // to the vector map.
10088   if (VF.isScalar()) {
10089     set(Def, ScalarValue, Part);
10090     return ScalarValue;
10091   }
10092 
10093   auto *RepR = dyn_cast<VPReplicateRecipe>(Def);
10094   bool IsUniform = RepR && RepR->isUniform();
10095 
10096   unsigned LastLane = IsUniform ? 0 : VF.getKnownMinValue() - 1;
10097   // Check if there is a scalar value for the selected lane.
10098   if (!hasScalarValue(Def, {Part, LastLane})) {
10099     // At the moment, VPWidenIntOrFpInductionRecipes can also be uniform.
10100     assert(isa<VPWidenIntOrFpInductionRecipe>(Def->getDef()) &&
10101            "unexpected recipe found to be invariant");
10102     IsUniform = true;
10103     LastLane = 0;
10104   }
10105 
10106   auto *LastInst = cast<Instruction>(get(Def, {Part, LastLane}));
10107   // Set the insert point after the last scalarized instruction or after the
10108   // last PHI, if LastInst is a PHI. This ensures the insertelement sequence
10109   // will directly follow the scalar definitions.
10110   auto OldIP = Builder.saveIP();
10111   auto NewIP =
10112       isa<PHINode>(LastInst)
10113           ? BasicBlock::iterator(LastInst->getParent()->getFirstNonPHI())
10114           : std::next(BasicBlock::iterator(LastInst));
10115   Builder.SetInsertPoint(&*NewIP);
10116 
10117   // However, if we are vectorizing, we need to construct the vector values.
10118   // If the value is known to be uniform after vectorization, we can just
10119   // broadcast the scalar value corresponding to lane zero for each unroll
10120   // iteration. Otherwise, we construct the vector values using
10121   // insertelement instructions. Since the resulting vectors are stored in
10122   // State, we will only generate the insertelements once.
10123   Value *VectorValue = nullptr;
10124   if (IsUniform) {
10125     VectorValue = ILV->getBroadcastInstrs(ScalarValue);
10126     set(Def, VectorValue, Part);
10127   } else {
10128     // Initialize packing with insertelements to start from undef.
10129     assert(!VF.isScalable() && "VF is assumed to be non scalable.");
10130     Value *Undef = PoisonValue::get(VectorType::get(LastInst->getType(), VF));
10131     set(Def, Undef, Part);
10132     for (unsigned Lane = 0; Lane < VF.getKnownMinValue(); ++Lane)
10133       ILV->packScalarIntoVectorValue(Def, {Part, Lane}, *this);
10134     VectorValue = get(Def, Part);
10135   }
10136   Builder.restoreIP(OldIP);
10137   return VectorValue;
10138 }
10139 
10140 // Process the loop in the VPlan-native vectorization path. This path builds
10141 // VPlan upfront in the vectorization pipeline, which allows to apply
10142 // VPlan-to-VPlan transformations from the very beginning without modifying the
10143 // input LLVM IR.
10144 static bool processLoopInVPlanNativePath(
10145     Loop *L, PredicatedScalarEvolution &PSE, LoopInfo *LI, DominatorTree *DT,
10146     LoopVectorizationLegality *LVL, TargetTransformInfo *TTI,
10147     TargetLibraryInfo *TLI, DemandedBits *DB, AssumptionCache *AC,
10148     OptimizationRemarkEmitter *ORE, BlockFrequencyInfo *BFI,
10149     ProfileSummaryInfo *PSI, LoopVectorizeHints &Hints,
10150     LoopVectorizationRequirements &Requirements) {
10151 
10152   if (isa<SCEVCouldNotCompute>(PSE.getBackedgeTakenCount())) {
10153     LLVM_DEBUG(dbgs() << "LV: cannot compute the outer-loop trip count\n");
10154     return false;
10155   }
10156   assert(EnableVPlanNativePath && "VPlan-native path is disabled.");
10157   Function *F = L->getHeader()->getParent();
10158   InterleavedAccessInfo IAI(PSE, L, DT, LI, LVL->getLAI());
10159 
10160   ScalarEpilogueLowering SEL = getScalarEpilogueLowering(
10161       F, L, Hints, PSI, BFI, TTI, TLI, AC, LI, PSE.getSE(), DT, *LVL);
10162 
10163   LoopVectorizationCostModel CM(SEL, L, PSE, LI, LVL, *TTI, TLI, DB, AC, ORE, F,
10164                                 &Hints, IAI);
10165   // Use the planner for outer loop vectorization.
10166   // TODO: CM is not used at this point inside the planner. Turn CM into an
10167   // optional argument if we don't need it in the future.
10168   LoopVectorizationPlanner LVP(L, LI, TLI, TTI, LVL, CM, IAI, PSE, Hints,
10169                                Requirements, ORE);
10170 
10171   // Get user vectorization factor.
10172   ElementCount UserVF = Hints.getWidth();
10173 
10174   CM.collectElementTypesForWidening();
10175 
10176   // Plan how to best vectorize, return the best VF and its cost.
10177   const VectorizationFactor VF = LVP.planInVPlanNativePath(UserVF);
10178 
10179   // If we are stress testing VPlan builds, do not attempt to generate vector
10180   // code. Masked vector code generation support will follow soon.
10181   // Also, do not attempt to vectorize if no vector code will be produced.
10182   if (VPlanBuildStressTest || EnableVPlanPredication ||
10183       VectorizationFactor::Disabled() == VF)
10184     return false;
10185 
10186   VPlan &BestPlan = LVP.getBestPlanFor(VF.Width);
10187 
10188   {
10189     GeneratedRTChecks Checks(*PSE.getSE(), DT, LI,
10190                              F->getParent()->getDataLayout());
10191     InnerLoopVectorizer LB(L, PSE, LI, DT, TLI, TTI, AC, ORE, VF.Width, 1, LVL,
10192                            &CM, BFI, PSI, Checks);
10193     LLVM_DEBUG(dbgs() << "Vectorizing outer loop in \""
10194                       << L->getHeader()->getParent()->getName() << "\"\n");
10195     LVP.executePlan(VF.Width, 1, BestPlan, LB, DT);
10196   }
10197 
10198   // Mark the loop as already vectorized to avoid vectorizing again.
10199   Hints.setAlreadyVectorized();
10200   assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()));
10201   return true;
10202 }
10203 
10204 // Emit a remark if there are stores to floats that required a floating point
10205 // extension. If the vectorized loop was generated with floating point there
10206 // will be a performance penalty from the conversion overhead and the change in
10207 // the vector width.
10208 static void checkMixedPrecision(Loop *L, OptimizationRemarkEmitter *ORE) {
10209   SmallVector<Instruction *, 4> Worklist;
10210   for (BasicBlock *BB : L->getBlocks()) {
10211     for (Instruction &Inst : *BB) {
10212       if (auto *S = dyn_cast<StoreInst>(&Inst)) {
10213         if (S->getValueOperand()->getType()->isFloatTy())
10214           Worklist.push_back(S);
10215       }
10216     }
10217   }
10218 
10219   // Traverse the floating point stores upwards searching, for floating point
10220   // conversions.
10221   SmallPtrSet<const Instruction *, 4> Visited;
10222   SmallPtrSet<const Instruction *, 4> EmittedRemark;
10223   while (!Worklist.empty()) {
10224     auto *I = Worklist.pop_back_val();
10225     if (!L->contains(I))
10226       continue;
10227     if (!Visited.insert(I).second)
10228       continue;
10229 
10230     // Emit a remark if the floating point store required a floating
10231     // point conversion.
10232     // TODO: More work could be done to identify the root cause such as a
10233     // constant or a function return type and point the user to it.
10234     if (isa<FPExtInst>(I) && EmittedRemark.insert(I).second)
10235       ORE->emit([&]() {
10236         return OptimizationRemarkAnalysis(LV_NAME, "VectorMixedPrecision",
10237                                           I->getDebugLoc(), L->getHeader())
10238                << "floating point conversion changes vector width. "
10239                << "Mixed floating point precision requires an up/down "
10240                << "cast that will negatively impact performance.";
10241       });
10242 
10243     for (Use &Op : I->operands())
10244       if (auto *OpI = dyn_cast<Instruction>(Op))
10245         Worklist.push_back(OpI);
10246   }
10247 }
10248 
10249 LoopVectorizePass::LoopVectorizePass(LoopVectorizeOptions Opts)
10250     : InterleaveOnlyWhenForced(Opts.InterleaveOnlyWhenForced ||
10251                                !EnableLoopInterleaving),
10252       VectorizeOnlyWhenForced(Opts.VectorizeOnlyWhenForced ||
10253                               !EnableLoopVectorization) {}
10254 
10255 bool LoopVectorizePass::processLoop(Loop *L) {
10256   assert((EnableVPlanNativePath || L->isInnermost()) &&
10257          "VPlan-native path is not enabled. Only process inner loops.");
10258 
10259 #ifndef NDEBUG
10260   const std::string DebugLocStr = getDebugLocString(L);
10261 #endif /* NDEBUG */
10262 
10263   LLVM_DEBUG(dbgs() << "\nLV: Checking a loop in \""
10264                     << L->getHeader()->getParent()->getName() << "\" from "
10265                     << DebugLocStr << "\n");
10266 
10267   LoopVectorizeHints Hints(L, InterleaveOnlyWhenForced, *ORE, TTI);
10268 
10269   LLVM_DEBUG(
10270       dbgs() << "LV: Loop hints:"
10271              << " force="
10272              << (Hints.getForce() == LoopVectorizeHints::FK_Disabled
10273                      ? "disabled"
10274                      : (Hints.getForce() == LoopVectorizeHints::FK_Enabled
10275                             ? "enabled"
10276                             : "?"))
10277              << " width=" << Hints.getWidth()
10278              << " interleave=" << Hints.getInterleave() << "\n");
10279 
10280   // Function containing loop
10281   Function *F = L->getHeader()->getParent();
10282 
10283   // Looking at the diagnostic output is the only way to determine if a loop
10284   // was vectorized (other than looking at the IR or machine code), so it
10285   // is important to generate an optimization remark for each loop. Most of
10286   // these messages are generated as OptimizationRemarkAnalysis. Remarks
10287   // generated as OptimizationRemark and OptimizationRemarkMissed are
10288   // less verbose reporting vectorized loops and unvectorized loops that may
10289   // benefit from vectorization, respectively.
10290 
10291   if (!Hints.allowVectorization(F, L, VectorizeOnlyWhenForced)) {
10292     LLVM_DEBUG(dbgs() << "LV: Loop hints prevent vectorization.\n");
10293     return false;
10294   }
10295 
10296   PredicatedScalarEvolution PSE(*SE, *L);
10297 
10298   // Check if it is legal to vectorize the loop.
10299   LoopVectorizationRequirements Requirements;
10300   LoopVectorizationLegality LVL(L, PSE, DT, TTI, TLI, AA, F, GetLAA, LI, ORE,
10301                                 &Requirements, &Hints, DB, AC, BFI, PSI);
10302   if (!LVL.canVectorize(EnableVPlanNativePath)) {
10303     LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
10304     Hints.emitRemarkWithHints();
10305     return false;
10306   }
10307 
10308   // Check the function attributes and profiles to find out if this function
10309   // should be optimized for size.
10310   ScalarEpilogueLowering SEL = getScalarEpilogueLowering(
10311       F, L, Hints, PSI, BFI, TTI, TLI, AC, LI, PSE.getSE(), DT, LVL);
10312 
10313   // Entrance to the VPlan-native vectorization path. Outer loops are processed
10314   // here. They may require CFG and instruction level transformations before
10315   // even evaluating whether vectorization is profitable. Since we cannot modify
10316   // the incoming IR, we need to build VPlan upfront in the vectorization
10317   // pipeline.
10318   if (!L->isInnermost())
10319     return processLoopInVPlanNativePath(L, PSE, LI, DT, &LVL, TTI, TLI, DB, AC,
10320                                         ORE, BFI, PSI, Hints, Requirements);
10321 
10322   assert(L->isInnermost() && "Inner loop expected.");
10323 
10324   // Check the loop for a trip count threshold: vectorize loops with a tiny trip
10325   // count by optimizing for size, to minimize overheads.
10326   auto ExpectedTC = getSmallBestKnownTC(*SE, L);
10327   if (ExpectedTC && *ExpectedTC < TinyTripCountVectorThreshold) {
10328     LLVM_DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "
10329                       << "This loop is worth vectorizing only if no scalar "
10330                       << "iteration overheads are incurred.");
10331     if (Hints.getForce() == LoopVectorizeHints::FK_Enabled)
10332       LLVM_DEBUG(dbgs() << " But vectorizing was explicitly forced.\n");
10333     else {
10334       LLVM_DEBUG(dbgs() << "\n");
10335       SEL = CM_ScalarEpilogueNotAllowedLowTripLoop;
10336     }
10337   }
10338 
10339   // Check the function attributes to see if implicit floats are allowed.
10340   // FIXME: This check doesn't seem possibly correct -- what if the loop is
10341   // an integer loop and the vector instructions selected are purely integer
10342   // vector instructions?
10343   if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10344     reportVectorizationFailure(
10345         "Can't vectorize when the NoImplicitFloat attribute is used",
10346         "loop not vectorized due to NoImplicitFloat attribute",
10347         "NoImplicitFloat", ORE, L);
10348     Hints.emitRemarkWithHints();
10349     return false;
10350   }
10351 
10352   // Check if the target supports potentially unsafe FP vectorization.
10353   // FIXME: Add a check for the type of safety issue (denormal, signaling)
10354   // for the target we're vectorizing for, to make sure none of the
10355   // additional fp-math flags can help.
10356   if (Hints.isPotentiallyUnsafe() &&
10357       TTI->isFPVectorizationPotentiallyUnsafe()) {
10358     reportVectorizationFailure(
10359         "Potentially unsafe FP op prevents vectorization",
10360         "loop not vectorized due to unsafe FP support.",
10361         "UnsafeFP", ORE, L);
10362     Hints.emitRemarkWithHints();
10363     return false;
10364   }
10365 
10366   bool AllowOrderedReductions;
10367   // If the flag is set, use that instead and override the TTI behaviour.
10368   if (ForceOrderedReductions.getNumOccurrences() > 0)
10369     AllowOrderedReductions = ForceOrderedReductions;
10370   else
10371     AllowOrderedReductions = TTI->enableOrderedReductions();
10372   if (!LVL.canVectorizeFPMath(AllowOrderedReductions)) {
10373     ORE->emit([&]() {
10374       auto *ExactFPMathInst = Requirements.getExactFPInst();
10375       return OptimizationRemarkAnalysisFPCommute(DEBUG_TYPE, "CantReorderFPOps",
10376                                                  ExactFPMathInst->getDebugLoc(),
10377                                                  ExactFPMathInst->getParent())
10378              << "loop not vectorized: cannot prove it is safe to reorder "
10379                 "floating-point operations";
10380     });
10381     LLVM_DEBUG(dbgs() << "LV: loop not vectorized: cannot prove it is safe to "
10382                          "reorder floating-point operations\n");
10383     Hints.emitRemarkWithHints();
10384     return false;
10385   }
10386 
10387   bool UseInterleaved = TTI->enableInterleavedAccessVectorization();
10388   InterleavedAccessInfo IAI(PSE, L, DT, LI, LVL.getLAI());
10389 
10390   // If an override option has been passed in for interleaved accesses, use it.
10391   if (EnableInterleavedMemAccesses.getNumOccurrences() > 0)
10392     UseInterleaved = EnableInterleavedMemAccesses;
10393 
10394   // Analyze interleaved memory accesses.
10395   if (UseInterleaved) {
10396     IAI.analyzeInterleaving(useMaskedInterleavedAccesses(*TTI));
10397   }
10398 
10399   // Use the cost model.
10400   LoopVectorizationCostModel CM(SEL, L, PSE, LI, &LVL, *TTI, TLI, DB, AC, ORE,
10401                                 F, &Hints, IAI);
10402   CM.collectValuesToIgnore();
10403   CM.collectElementTypesForWidening();
10404 
10405   // Use the planner for vectorization.
10406   LoopVectorizationPlanner LVP(L, LI, TLI, TTI, &LVL, CM, IAI, PSE, Hints,
10407                                Requirements, ORE);
10408 
10409   // Get user vectorization factor and interleave count.
10410   ElementCount UserVF = Hints.getWidth();
10411   unsigned UserIC = Hints.getInterleave();
10412 
10413   // Plan how to best vectorize, return the best VF and its cost.
10414   Optional<VectorizationFactor> MaybeVF = LVP.plan(UserVF, UserIC);
10415 
10416   VectorizationFactor VF = VectorizationFactor::Disabled();
10417   unsigned IC = 1;
10418 
10419   if (MaybeVF) {
10420     VF = *MaybeVF;
10421     // Select the interleave count.
10422     IC = CM.selectInterleaveCount(VF.Width, *VF.Cost.getValue());
10423   }
10424 
10425   // Identify the diagnostic messages that should be produced.
10426   std::pair<StringRef, std::string> VecDiagMsg, IntDiagMsg;
10427   bool VectorizeLoop = true, InterleaveLoop = true;
10428   if (VF.Width.isScalar()) {
10429     LLVM_DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
10430     VecDiagMsg = std::make_pair(
10431         "VectorizationNotBeneficial",
10432         "the cost-model indicates that vectorization is not beneficial");
10433     VectorizeLoop = false;
10434   }
10435 
10436   if (!MaybeVF && UserIC > 1) {
10437     // Tell the user interleaving was avoided up-front, despite being explicitly
10438     // requested.
10439     LLVM_DEBUG(dbgs() << "LV: Ignoring UserIC, because vectorization and "
10440                          "interleaving should be avoided up front\n");
10441     IntDiagMsg = std::make_pair(
10442         "InterleavingAvoided",
10443         "Ignoring UserIC, because interleaving was avoided up front");
10444     InterleaveLoop = false;
10445   } else if (IC == 1 && UserIC <= 1) {
10446     // Tell the user interleaving is not beneficial.
10447     LLVM_DEBUG(dbgs() << "LV: Interleaving is not beneficial.\n");
10448     IntDiagMsg = std::make_pair(
10449         "InterleavingNotBeneficial",
10450         "the cost-model indicates that interleaving is not beneficial");
10451     InterleaveLoop = false;
10452     if (UserIC == 1) {
10453       IntDiagMsg.first = "InterleavingNotBeneficialAndDisabled";
10454       IntDiagMsg.second +=
10455           " and is explicitly disabled or interleave count is set to 1";
10456     }
10457   } else if (IC > 1 && UserIC == 1) {
10458     // Tell the user interleaving is beneficial, but it explicitly disabled.
10459     LLVM_DEBUG(
10460         dbgs() << "LV: Interleaving is beneficial but is explicitly disabled.");
10461     IntDiagMsg = std::make_pair(
10462         "InterleavingBeneficialButDisabled",
10463         "the cost-model indicates that interleaving is beneficial "
10464         "but is explicitly disabled or interleave count is set to 1");
10465     InterleaveLoop = false;
10466   }
10467 
10468   // Override IC if user provided an interleave count.
10469   IC = UserIC > 0 ? UserIC : IC;
10470 
10471   // Emit diagnostic messages, if any.
10472   const char *VAPassName = Hints.vectorizeAnalysisPassName();
10473   if (!VectorizeLoop && !InterleaveLoop) {
10474     // Do not vectorize or interleaving the loop.
10475     ORE->emit([&]() {
10476       return OptimizationRemarkMissed(VAPassName, VecDiagMsg.first,
10477                                       L->getStartLoc(), L->getHeader())
10478              << VecDiagMsg.second;
10479     });
10480     ORE->emit([&]() {
10481       return OptimizationRemarkMissed(LV_NAME, IntDiagMsg.first,
10482                                       L->getStartLoc(), L->getHeader())
10483              << IntDiagMsg.second;
10484     });
10485     return false;
10486   } else if (!VectorizeLoop && InterleaveLoop) {
10487     LLVM_DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
10488     ORE->emit([&]() {
10489       return OptimizationRemarkAnalysis(VAPassName, VecDiagMsg.first,
10490                                         L->getStartLoc(), L->getHeader())
10491              << VecDiagMsg.second;
10492     });
10493   } else if (VectorizeLoop && !InterleaveLoop) {
10494     LLVM_DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width
10495                       << ") in " << DebugLocStr << '\n');
10496     ORE->emit([&]() {
10497       return OptimizationRemarkAnalysis(LV_NAME, IntDiagMsg.first,
10498                                         L->getStartLoc(), L->getHeader())
10499              << IntDiagMsg.second;
10500     });
10501   } else if (VectorizeLoop && InterleaveLoop) {
10502     LLVM_DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width
10503                       << ") in " << DebugLocStr << '\n');
10504     LLVM_DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
10505   }
10506 
10507   bool DisableRuntimeUnroll = false;
10508   MDNode *OrigLoopID = L->getLoopID();
10509   {
10510     // Optimistically generate runtime checks. Drop them if they turn out to not
10511     // be profitable. Limit the scope of Checks, so the cleanup happens
10512     // immediately after vector codegeneration is done.
10513     GeneratedRTChecks Checks(*PSE.getSE(), DT, LI,
10514                              F->getParent()->getDataLayout());
10515     if (!VF.Width.isScalar() || IC > 1)
10516       Checks.Create(L, *LVL.getLAI(), PSE.getUnionPredicate());
10517 
10518     using namespace ore;
10519     if (!VectorizeLoop) {
10520       assert(IC > 1 && "interleave count should not be 1 or 0");
10521       // If we decided that it is not legal to vectorize the loop, then
10522       // interleave it.
10523       InnerLoopUnroller Unroller(L, PSE, LI, DT, TLI, TTI, AC, ORE, IC, &LVL,
10524                                  &CM, BFI, PSI, Checks);
10525 
10526       VPlan &BestPlan = LVP.getBestPlanFor(VF.Width);
10527       LVP.executePlan(VF.Width, IC, BestPlan, Unroller, DT);
10528 
10529       ORE->emit([&]() {
10530         return OptimizationRemark(LV_NAME, "Interleaved", L->getStartLoc(),
10531                                   L->getHeader())
10532                << "interleaved loop (interleaved count: "
10533                << NV("InterleaveCount", IC) << ")";
10534       });
10535     } else {
10536       // If we decided that it is *legal* to vectorize the loop, then do it.
10537 
10538       // Consider vectorizing the epilogue too if it's profitable.
10539       VectorizationFactor EpilogueVF =
10540           CM.selectEpilogueVectorizationFactor(VF.Width, LVP);
10541       if (EpilogueVF.Width.isVector()) {
10542 
10543         // The first pass vectorizes the main loop and creates a scalar epilogue
10544         // to be vectorized by executing the plan (potentially with a different
10545         // factor) again shortly afterwards.
10546         EpilogueLoopVectorizationInfo EPI(VF.Width, IC, EpilogueVF.Width, 1);
10547         EpilogueVectorizerMainLoop MainILV(L, PSE, LI, DT, TLI, TTI, AC, ORE,
10548                                            EPI, &LVL, &CM, BFI, PSI, Checks);
10549 
10550         VPlan &BestMainPlan = LVP.getBestPlanFor(EPI.MainLoopVF);
10551         LVP.executePlan(EPI.MainLoopVF, EPI.MainLoopUF, BestMainPlan, MainILV,
10552                         DT);
10553         ++LoopsVectorized;
10554 
10555         simplifyLoop(L, DT, LI, SE, AC, nullptr, false /* PreserveLCSSA */);
10556         formLCSSARecursively(*L, *DT, LI, SE);
10557 
10558         // Second pass vectorizes the epilogue and adjusts the control flow
10559         // edges from the first pass.
10560         EPI.MainLoopVF = EPI.EpilogueVF;
10561         EPI.MainLoopUF = EPI.EpilogueUF;
10562         EpilogueVectorizerEpilogueLoop EpilogILV(L, PSE, LI, DT, TLI, TTI, AC,
10563                                                  ORE, EPI, &LVL, &CM, BFI, PSI,
10564                                                  Checks);
10565 
10566         VPlan &BestEpiPlan = LVP.getBestPlanFor(EPI.EpilogueVF);
10567         LVP.executePlan(EPI.EpilogueVF, EPI.EpilogueUF, BestEpiPlan, EpilogILV,
10568                         DT);
10569         ++LoopsEpilogueVectorized;
10570 
10571         if (!MainILV.areSafetyChecksAdded())
10572           DisableRuntimeUnroll = true;
10573       } else {
10574         InnerLoopVectorizer LB(L, PSE, LI, DT, TLI, TTI, AC, ORE, VF.Width, IC,
10575                                &LVL, &CM, BFI, PSI, Checks);
10576 
10577         VPlan &BestPlan = LVP.getBestPlanFor(VF.Width);
10578         LVP.executePlan(VF.Width, IC, BestPlan, LB, DT);
10579         ++LoopsVectorized;
10580 
10581         // Add metadata to disable runtime unrolling a scalar loop when there
10582         // are no runtime checks about strides and memory. A scalar loop that is
10583         // rarely used is not worth unrolling.
10584         if (!LB.areSafetyChecksAdded())
10585           DisableRuntimeUnroll = true;
10586       }
10587       // Report the vectorization decision.
10588       ORE->emit([&]() {
10589         return OptimizationRemark(LV_NAME, "Vectorized", L->getStartLoc(),
10590                                   L->getHeader())
10591                << "vectorized loop (vectorization width: "
10592                << NV("VectorizationFactor", VF.Width)
10593                << ", interleaved count: " << NV("InterleaveCount", IC) << ")";
10594       });
10595     }
10596 
10597     if (ORE->allowExtraAnalysis(LV_NAME))
10598       checkMixedPrecision(L, ORE);
10599   }
10600 
10601   Optional<MDNode *> RemainderLoopID =
10602       makeFollowupLoopID(OrigLoopID, {LLVMLoopVectorizeFollowupAll,
10603                                       LLVMLoopVectorizeFollowupEpilogue});
10604   if (RemainderLoopID.hasValue()) {
10605     L->setLoopID(RemainderLoopID.getValue());
10606   } else {
10607     if (DisableRuntimeUnroll)
10608       AddRuntimeUnrollDisableMetaData(L);
10609 
10610     // Mark the loop as already vectorized to avoid vectorizing again.
10611     Hints.setAlreadyVectorized();
10612   }
10613 
10614   assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()));
10615   return true;
10616 }
10617 
10618 LoopVectorizeResult LoopVectorizePass::runImpl(
10619     Function &F, ScalarEvolution &SE_, LoopInfo &LI_, TargetTransformInfo &TTI_,
10620     DominatorTree &DT_, BlockFrequencyInfo &BFI_, TargetLibraryInfo *TLI_,
10621     DemandedBits &DB_, AAResults &AA_, AssumptionCache &AC_,
10622     std::function<const LoopAccessInfo &(Loop &)> &GetLAA_,
10623     OptimizationRemarkEmitter &ORE_, ProfileSummaryInfo *PSI_) {
10624   SE = &SE_;
10625   LI = &LI_;
10626   TTI = &TTI_;
10627   DT = &DT_;
10628   BFI = &BFI_;
10629   TLI = TLI_;
10630   AA = &AA_;
10631   AC = &AC_;
10632   GetLAA = &GetLAA_;
10633   DB = &DB_;
10634   ORE = &ORE_;
10635   PSI = PSI_;
10636 
10637   // Don't attempt if
10638   // 1. the target claims to have no vector registers, and
10639   // 2. interleaving won't help ILP.
10640   //
10641   // The second condition is necessary because, even if the target has no
10642   // vector registers, loop vectorization may still enable scalar
10643   // interleaving.
10644   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true)) &&
10645       TTI->getMaxInterleaveFactor(1) < 2)
10646     return LoopVectorizeResult(false, false);
10647 
10648   bool Changed = false, CFGChanged = false;
10649 
10650   // The vectorizer requires loops to be in simplified form.
10651   // Since simplification may add new inner loops, it has to run before the
10652   // legality and profitability checks. This means running the loop vectorizer
10653   // will simplify all loops, regardless of whether anything end up being
10654   // vectorized.
10655   for (auto &L : *LI)
10656     Changed |= CFGChanged |=
10657         simplifyLoop(L, DT, LI, SE, AC, nullptr, false /* PreserveLCSSA */);
10658 
10659   // Build up a worklist of inner-loops to vectorize. This is necessary as
10660   // the act of vectorizing or partially unrolling a loop creates new loops
10661   // and can invalidate iterators across the loops.
10662   SmallVector<Loop *, 8> Worklist;
10663 
10664   for (Loop *L : *LI)
10665     collectSupportedLoops(*L, LI, ORE, Worklist);
10666 
10667   LoopsAnalyzed += Worklist.size();
10668 
10669   // Now walk the identified inner loops.
10670   while (!Worklist.empty()) {
10671     Loop *L = Worklist.pop_back_val();
10672 
10673     // For the inner loops we actually process, form LCSSA to simplify the
10674     // transform.
10675     Changed |= formLCSSARecursively(*L, *DT, LI, SE);
10676 
10677     Changed |= CFGChanged |= processLoop(L);
10678   }
10679 
10680   // Process each loop nest in the function.
10681   return LoopVectorizeResult(Changed, CFGChanged);
10682 }
10683 
10684 PreservedAnalyses LoopVectorizePass::run(Function &F,
10685                                          FunctionAnalysisManager &AM) {
10686     auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
10687     auto &LI = AM.getResult<LoopAnalysis>(F);
10688     auto &TTI = AM.getResult<TargetIRAnalysis>(F);
10689     auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
10690     auto &BFI = AM.getResult<BlockFrequencyAnalysis>(F);
10691     auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
10692     auto &AA = AM.getResult<AAManager>(F);
10693     auto &AC = AM.getResult<AssumptionAnalysis>(F);
10694     auto &DB = AM.getResult<DemandedBitsAnalysis>(F);
10695     auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
10696 
10697     auto &LAM = AM.getResult<LoopAnalysisManagerFunctionProxy>(F).getManager();
10698     std::function<const LoopAccessInfo &(Loop &)> GetLAA =
10699         [&](Loop &L) -> const LoopAccessInfo & {
10700       LoopStandardAnalysisResults AR = {AA,  AC,  DT,      LI,      SE,
10701                                         TLI, TTI, nullptr, nullptr, nullptr};
10702       return LAM.getResult<LoopAccessAnalysis>(L, AR);
10703     };
10704     auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
10705     ProfileSummaryInfo *PSI =
10706         MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
10707     LoopVectorizeResult Result =
10708         runImpl(F, SE, LI, TTI, DT, BFI, &TLI, DB, AA, AC, GetLAA, ORE, PSI);
10709     if (!Result.MadeAnyChange)
10710       return PreservedAnalyses::all();
10711     PreservedAnalyses PA;
10712 
10713     // We currently do not preserve loopinfo/dominator analyses with outer loop
10714     // vectorization. Until this is addressed, mark these analyses as preserved
10715     // only for non-VPlan-native path.
10716     // TODO: Preserve Loop and Dominator analyses for VPlan-native path.
10717     if (!EnableVPlanNativePath) {
10718       PA.preserve<LoopAnalysis>();
10719       PA.preserve<DominatorTreeAnalysis>();
10720     }
10721 
10722     if (Result.MadeCFGChange) {
10723       // Making CFG changes likely means a loop got vectorized. Indicate that
10724       // extra simplification passes should be run.
10725       // TODO: MadeCFGChanges is not a prefect proxy. Extra passes should only
10726       // be run if runtime checks have been added.
10727       AM.getResult<ShouldRunExtraVectorPasses>(F);
10728       PA.preserve<ShouldRunExtraVectorPasses>();
10729     } else {
10730       PA.preserveSet<CFGAnalyses>();
10731     }
10732     return PA;
10733 }
10734 
10735 void LoopVectorizePass::printPipeline(
10736     raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
10737   static_cast<PassInfoMixin<LoopVectorizePass> *>(this)->printPipeline(
10738       OS, MapClassName2PassName);
10739 
10740   OS << "<";
10741   OS << (InterleaveOnlyWhenForced ? "" : "no-") << "interleave-forced-only;";
10742   OS << (VectorizeOnlyWhenForced ? "" : "no-") << "vectorize-forced-only;";
10743   OS << ">";
10744 }
10745