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 "VPlanTransforms.h"
62 #include "llvm/ADT/APInt.h"
63 #include "llvm/ADT/ArrayRef.h"
64 #include "llvm/ADT/DenseMap.h"
65 #include "llvm/ADT/DenseMapInfo.h"
66 #include "llvm/ADT/Hashing.h"
67 #include "llvm/ADT/MapVector.h"
68 #include "llvm/ADT/None.h"
69 #include "llvm/ADT/Optional.h"
70 #include "llvm/ADT/STLExtras.h"
71 #include "llvm/ADT/SmallPtrSet.h"
72 #include "llvm/ADT/SmallSet.h"
73 #include "llvm/ADT/SmallVector.h"
74 #include "llvm/ADT/Statistic.h"
75 #include "llvm/ADT/StringRef.h"
76 #include "llvm/ADT/Twine.h"
77 #include "llvm/ADT/iterator_range.h"
78 #include "llvm/Analysis/AssumptionCache.h"
79 #include "llvm/Analysis/BasicAliasAnalysis.h"
80 #include "llvm/Analysis/BlockFrequencyInfo.h"
81 #include "llvm/Analysis/CFG.h"
82 #include "llvm/Analysis/CodeMetrics.h"
83 #include "llvm/Analysis/DemandedBits.h"
84 #include "llvm/Analysis/GlobalsModRef.h"
85 #include "llvm/Analysis/LoopAccessAnalysis.h"
86 #include "llvm/Analysis/LoopAnalysisManager.h"
87 #include "llvm/Analysis/LoopInfo.h"
88 #include "llvm/Analysis/LoopIterator.h"
89 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
90 #include "llvm/Analysis/ProfileSummaryInfo.h"
91 #include "llvm/Analysis/ScalarEvolution.h"
92 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
93 #include "llvm/Analysis/TargetLibraryInfo.h"
94 #include "llvm/Analysis/TargetTransformInfo.h"
95 #include "llvm/Analysis/VectorUtils.h"
96 #include "llvm/IR/Attributes.h"
97 #include "llvm/IR/BasicBlock.h"
98 #include "llvm/IR/CFG.h"
99 #include "llvm/IR/Constant.h"
100 #include "llvm/IR/Constants.h"
101 #include "llvm/IR/DataLayout.h"
102 #include "llvm/IR/DebugInfoMetadata.h"
103 #include "llvm/IR/DebugLoc.h"
104 #include "llvm/IR/DerivedTypes.h"
105 #include "llvm/IR/DiagnosticInfo.h"
106 #include "llvm/IR/Dominators.h"
107 #include "llvm/IR/Function.h"
108 #include "llvm/IR/IRBuilder.h"
109 #include "llvm/IR/InstrTypes.h"
110 #include "llvm/IR/Instruction.h"
111 #include "llvm/IR/Instructions.h"
112 #include "llvm/IR/IntrinsicInst.h"
113 #include "llvm/IR/Intrinsics.h"
114 #include "llvm/IR/Metadata.h"
115 #include "llvm/IR/Module.h"
116 #include "llvm/IR/Operator.h"
117 #include "llvm/IR/PatternMatch.h"
118 #include "llvm/IR/Type.h"
119 #include "llvm/IR/Use.h"
120 #include "llvm/IR/User.h"
121 #include "llvm/IR/Value.h"
122 #include "llvm/IR/ValueHandle.h"
123 #include "llvm/IR/Verifier.h"
124 #include "llvm/InitializePasses.h"
125 #include "llvm/Pass.h"
126 #include "llvm/Support/Casting.h"
127 #include "llvm/Support/CommandLine.h"
128 #include "llvm/Support/Compiler.h"
129 #include "llvm/Support/Debug.h"
130 #include "llvm/Support/ErrorHandling.h"
131 #include "llvm/Support/InstructionCost.h"
132 #include "llvm/Support/MathExtras.h"
133 #include "llvm/Support/raw_ostream.h"
134 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
135 #include "llvm/Transforms/Utils/InjectTLIMappings.h"
136 #include "llvm/Transforms/Utils/LoopSimplify.h"
137 #include "llvm/Transforms/Utils/LoopUtils.h"
138 #include "llvm/Transforms/Utils/LoopVersioning.h"
139 #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
140 #include "llvm/Transforms/Utils/SizeOpts.h"
141 #include "llvm/Transforms/Vectorize/LoopVectorizationLegality.h"
142 #include <algorithm>
143 #include <cassert>
144 #include <cstdint>
145 #include <functional>
146 #include <iterator>
147 #include <limits>
148 #include <map>
149 #include <memory>
150 #include <string>
151 #include <tuple>
152 #include <utility>
153 
154 using namespace llvm;
155 
156 #define LV_NAME "loop-vectorize"
157 #define DEBUG_TYPE LV_NAME
158 
159 #ifndef NDEBUG
160 const char VerboseDebug[] = DEBUG_TYPE "-verbose";
161 #endif
162 
163 /// @{
164 /// Metadata attribute names
165 const char LLVMLoopVectorizeFollowupAll[] = "llvm.loop.vectorize.followup_all";
166 const char LLVMLoopVectorizeFollowupVectorized[] =
167     "llvm.loop.vectorize.followup_vectorized";
168 const char LLVMLoopVectorizeFollowupEpilogue[] =
169     "llvm.loop.vectorize.followup_epilogue";
170 /// @}
171 
172 STATISTIC(LoopsVectorized, "Number of loops vectorized");
173 STATISTIC(LoopsAnalyzed, "Number of loops analyzed for vectorization");
174 STATISTIC(LoopsEpilogueVectorized, "Number of epilogues vectorized");
175 
176 static cl::opt<bool> EnableEpilogueVectorization(
177     "enable-epilogue-vectorization", cl::init(true), cl::Hidden,
178     cl::desc("Enable vectorization of epilogue loops."));
179 
180 static cl::opt<unsigned> EpilogueVectorizationForceVF(
181     "epilogue-vectorization-force-VF", cl::init(1), cl::Hidden,
182     cl::desc("When epilogue vectorization is enabled, and a value greater than "
183              "1 is specified, forces the given VF for all applicable epilogue "
184              "loops."));
185 
186 static cl::opt<unsigned> EpilogueVectorizationMinVF(
187     "epilogue-vectorization-minimum-VF", cl::init(16), cl::Hidden,
188     cl::desc("Only loops with vectorization factor equal to or larger than "
189              "the specified value are considered for epilogue vectorization."));
190 
191 /// Loops with a known constant trip count below this number are vectorized only
192 /// if no scalar iteration overheads are incurred.
193 static cl::opt<unsigned> TinyTripCountVectorThreshold(
194     "vectorizer-min-trip-count", cl::init(16), cl::Hidden,
195     cl::desc("Loops with a constant trip count that is smaller than this "
196              "value are vectorized only if no scalar iteration overheads "
197              "are incurred."));
198 
199 static cl::opt<unsigned> VectorizeMemoryCheckThreshold(
200     "vectorize-memory-check-threshold", cl::init(128), cl::Hidden,
201     cl::desc("The maximum allowed number of runtime memory checks"));
202 
203 // Option prefer-predicate-over-epilogue indicates that an epilogue is undesired,
204 // that predication is preferred, and this lists all options. I.e., the
205 // vectorizer will try to fold the tail-loop (epilogue) into the vector body
206 // and predicate the instructions accordingly. If tail-folding fails, there are
207 // different fallback strategies depending on these values:
208 namespace PreferPredicateTy {
209   enum Option {
210     ScalarEpilogue = 0,
211     PredicateElseScalarEpilogue,
212     PredicateOrDontVectorize
213   };
214 } // namespace PreferPredicateTy
215 
216 static cl::opt<PreferPredicateTy::Option> PreferPredicateOverEpilogue(
217     "prefer-predicate-over-epilogue",
218     cl::init(PreferPredicateTy::ScalarEpilogue),
219     cl::Hidden,
220     cl::desc("Tail-folding and predication preferences over creating a scalar "
221              "epilogue loop."),
222     cl::values(clEnumValN(PreferPredicateTy::ScalarEpilogue,
223                          "scalar-epilogue",
224                          "Don't tail-predicate loops, create scalar epilogue"),
225               clEnumValN(PreferPredicateTy::PredicateElseScalarEpilogue,
226                          "predicate-else-scalar-epilogue",
227                          "prefer tail-folding, create scalar epilogue if tail "
228                          "folding fails."),
229               clEnumValN(PreferPredicateTy::PredicateOrDontVectorize,
230                          "predicate-dont-vectorize",
231                          "prefers tail-folding, don't attempt vectorization if "
232                          "tail-folding fails.")));
233 
234 static cl::opt<bool> MaximizeBandwidth(
235     "vectorizer-maximize-bandwidth", cl::init(false), cl::Hidden,
236     cl::desc("Maximize bandwidth when selecting vectorization factor which "
237              "will be determined by the smallest type in loop."));
238 
239 static cl::opt<bool> EnableInterleavedMemAccesses(
240     "enable-interleaved-mem-accesses", cl::init(false), cl::Hidden,
241     cl::desc("Enable vectorization on interleaved memory accesses in a loop"));
242 
243 /// An interleave-group may need masking if it resides in a block that needs
244 /// predication, or in order to mask away gaps.
245 static cl::opt<bool> EnableMaskedInterleavedMemAccesses(
246     "enable-masked-interleaved-mem-accesses", cl::init(false), cl::Hidden,
247     cl::desc("Enable vectorization on masked interleaved memory accesses in a loop"));
248 
249 static cl::opt<unsigned> TinyTripCountInterleaveThreshold(
250     "tiny-trip-count-interleave-threshold", cl::init(128), cl::Hidden,
251     cl::desc("We don't interleave loops with a estimated constant trip count "
252              "below this number"));
253 
254 static cl::opt<unsigned> ForceTargetNumScalarRegs(
255     "force-target-num-scalar-regs", cl::init(0), cl::Hidden,
256     cl::desc("A flag that overrides the target's number of scalar registers."));
257 
258 static cl::opt<unsigned> ForceTargetNumVectorRegs(
259     "force-target-num-vector-regs", cl::init(0), cl::Hidden,
260     cl::desc("A flag that overrides the target's number of vector registers."));
261 
262 static cl::opt<unsigned> ForceTargetMaxScalarInterleaveFactor(
263     "force-target-max-scalar-interleave", cl::init(0), cl::Hidden,
264     cl::desc("A flag that overrides the target's max interleave factor for "
265              "scalar loops."));
266 
267 static cl::opt<unsigned> ForceTargetMaxVectorInterleaveFactor(
268     "force-target-max-vector-interleave", cl::init(0), cl::Hidden,
269     cl::desc("A flag that overrides the target's max interleave factor for "
270              "vectorized loops."));
271 
272 static cl::opt<unsigned> ForceTargetInstructionCost(
273     "force-target-instruction-cost", cl::init(0), cl::Hidden,
274     cl::desc("A flag that overrides the target's expected cost for "
275              "an instruction to a single constant value. Mostly "
276              "useful for getting consistent testing."));
277 
278 static cl::opt<bool> ForceTargetSupportsScalableVectors(
279     "force-target-supports-scalable-vectors", cl::init(false), cl::Hidden,
280     cl::desc(
281         "Pretend that scalable vectors are supported, even if the target does "
282         "not support them. This flag should only be used for testing."));
283 
284 static cl::opt<unsigned> SmallLoopCost(
285     "small-loop-cost", cl::init(20), cl::Hidden,
286     cl::desc(
287         "The cost of a loop that is considered 'small' by the interleaver."));
288 
289 static cl::opt<bool> LoopVectorizeWithBlockFrequency(
290     "loop-vectorize-with-block-frequency", cl::init(true), cl::Hidden,
291     cl::desc("Enable the use of the block frequency analysis to access PGO "
292              "heuristics minimizing code growth in cold regions and being more "
293              "aggressive in hot regions."));
294 
295 // Runtime interleave loops for load/store throughput.
296 static cl::opt<bool> EnableLoadStoreRuntimeInterleave(
297     "enable-loadstore-runtime-interleave", cl::init(true), cl::Hidden,
298     cl::desc(
299         "Enable runtime interleaving until load/store ports are saturated"));
300 
301 /// Interleave small loops with scalar reductions.
302 static cl::opt<bool> InterleaveSmallLoopScalarReduction(
303     "interleave-small-loop-scalar-reduction", cl::init(false), cl::Hidden,
304     cl::desc("Enable interleaving for loops with small iteration counts that "
305              "contain scalar reductions to expose ILP."));
306 
307 /// The number of stores in a loop that are allowed to need predication.
308 static cl::opt<unsigned> NumberOfStoresToPredicate(
309     "vectorize-num-stores-pred", cl::init(1), cl::Hidden,
310     cl::desc("Max number of stores to be predicated behind an if."));
311 
312 static cl::opt<bool> EnableIndVarRegisterHeur(
313     "enable-ind-var-reg-heur", cl::init(true), cl::Hidden,
314     cl::desc("Count the induction variable only once when interleaving"));
315 
316 static cl::opt<bool> EnableCondStoresVectorization(
317     "enable-cond-stores-vec", cl::init(true), cl::Hidden,
318     cl::desc("Enable if predication of stores during vectorization."));
319 
320 static cl::opt<unsigned> MaxNestedScalarReductionIC(
321     "max-nested-scalar-reduction-interleave", cl::init(2), cl::Hidden,
322     cl::desc("The maximum interleave count to use when interleaving a scalar "
323              "reduction in a nested loop."));
324 
325 static cl::opt<bool>
326     PreferInLoopReductions("prefer-inloop-reductions", cl::init(false),
327                            cl::Hidden,
328                            cl::desc("Prefer in-loop vector reductions, "
329                                     "overriding the targets preference."));
330 
331 static cl::opt<bool> ForceOrderedReductions(
332     "force-ordered-reductions", cl::init(false), cl::Hidden,
333     cl::desc("Enable the vectorisation of loops with in-order (strict) "
334              "FP reductions"));
335 
336 static cl::opt<bool> PreferPredicatedReductionSelect(
337     "prefer-predicated-reduction-select", cl::init(false), cl::Hidden,
338     cl::desc(
339         "Prefer predicating a reduction operation over an after loop select."));
340 
341 cl::opt<bool> EnableVPlanNativePath(
342     "enable-vplan-native-path", cl::init(false), cl::Hidden,
343     cl::desc("Enable VPlan-native vectorization path with "
344              "support for outer loop vectorization."));
345 
346 // This flag enables the stress testing of the VPlan H-CFG construction in the
347 // VPlan-native vectorization path. It must be used in conjuction with
348 // -enable-vplan-native-path. -vplan-verify-hcfg can also be used to enable the
349 // verification of the H-CFGs built.
350 static cl::opt<bool> VPlanBuildStressTest(
351     "vplan-build-stress-test", cl::init(false), cl::Hidden,
352     cl::desc(
353         "Build VPlan for every supported loop nest in the function and bail "
354         "out right after the build (stress test the VPlan H-CFG construction "
355         "in the VPlan-native vectorization path)."));
356 
357 cl::opt<bool> llvm::EnableLoopInterleaving(
358     "interleave-loops", cl::init(true), cl::Hidden,
359     cl::desc("Enable loop interleaving in Loop vectorization passes"));
360 cl::opt<bool> llvm::EnableLoopVectorization(
361     "vectorize-loops", cl::init(true), cl::Hidden,
362     cl::desc("Run the Loop vectorization passes"));
363 
364 cl::opt<bool> PrintVPlansInDotFormat(
365     "vplan-print-in-dot-format", cl::init(false), cl::Hidden,
366     cl::desc("Use dot format instead of plain text when dumping VPlans"));
367 
368 /// A helper function that returns true if the given type is irregular. The
369 /// type is irregular if its allocated size doesn't equal the store size of an
370 /// element of the corresponding vector type.
371 static bool hasIrregularType(Type *Ty, const DataLayout &DL) {
372   // Determine if an array of N elements of type Ty is "bitcast compatible"
373   // with a <N x Ty> vector.
374   // This is only true if there is no padding between the array elements.
375   return DL.getTypeAllocSizeInBits(Ty) != DL.getTypeSizeInBits(Ty);
376 }
377 
378 /// A helper function that returns the reciprocal of the block probability of
379 /// predicated blocks. If we return X, we are assuming the predicated block
380 /// will execute once for every X iterations of the loop header.
381 ///
382 /// TODO: We should use actual block probability here, if available. Currently,
383 ///       we always assume predicated blocks have a 50% chance of executing.
384 static unsigned getReciprocalPredBlockProb() { return 2; }
385 
386 /// A helper function that returns an integer or floating-point constant with
387 /// value C.
388 static Constant *getSignedIntOrFpConstant(Type *Ty, int64_t C) {
389   return Ty->isIntegerTy() ? ConstantInt::getSigned(Ty, C)
390                            : ConstantFP::get(Ty, C);
391 }
392 
393 /// Returns "best known" trip count for the specified loop \p L as defined by
394 /// the following procedure:
395 ///   1) Returns exact trip count if it is known.
396 ///   2) Returns expected trip count according to profile data if any.
397 ///   3) Returns upper bound estimate if it is known.
398 ///   4) Returns None if all of the above failed.
399 static Optional<unsigned> getSmallBestKnownTC(ScalarEvolution &SE, Loop *L) {
400   // Check if exact trip count is known.
401   if (unsigned ExpectedTC = SE.getSmallConstantTripCount(L))
402     return ExpectedTC;
403 
404   // Check if there is an expected trip count available from profile data.
405   if (LoopVectorizeWithBlockFrequency)
406     if (auto EstimatedTC = getLoopEstimatedTripCount(L))
407       return EstimatedTC;
408 
409   // Check if upper bound estimate is known.
410   if (unsigned ExpectedTC = SE.getSmallConstantMaxTripCount(L))
411     return ExpectedTC;
412 
413   return None;
414 }
415 
416 // Forward declare GeneratedRTChecks.
417 class GeneratedRTChecks;
418 
419 namespace llvm {
420 
421 AnalysisKey ShouldRunExtraVectorPasses::Key;
422 
423 /// InnerLoopVectorizer vectorizes loops which contain only one basic
424 /// block to a specified vectorization factor (VF).
425 /// This class performs the widening of scalars into vectors, or multiple
426 /// scalars. This class also implements the following features:
427 /// * It inserts an epilogue loop for handling loops that don't have iteration
428 ///   counts that are known to be a multiple of the vectorization factor.
429 /// * It handles the code generation for reduction variables.
430 /// * Scalarization (implementation using scalars) of un-vectorizable
431 ///   instructions.
432 /// InnerLoopVectorizer does not perform any vectorization-legality
433 /// checks, and relies on the caller to check for the different legality
434 /// aspects. The InnerLoopVectorizer relies on the
435 /// LoopVectorizationLegality class to provide information about the induction
436 /// and reduction variables that were found to a given vectorization factor.
437 class InnerLoopVectorizer {
438 public:
439   InnerLoopVectorizer(Loop *OrigLoop, PredicatedScalarEvolution &PSE,
440                       LoopInfo *LI, DominatorTree *DT,
441                       const TargetLibraryInfo *TLI,
442                       const TargetTransformInfo *TTI, AssumptionCache *AC,
443                       OptimizationRemarkEmitter *ORE, ElementCount VecWidth,
444                       ElementCount MinProfitableTripCount,
445                       unsigned UnrollFactor, LoopVectorizationLegality *LVL,
446                       LoopVectorizationCostModel *CM, BlockFrequencyInfo *BFI,
447                       ProfileSummaryInfo *PSI, GeneratedRTChecks &RTChecks)
448       : OrigLoop(OrigLoop), PSE(PSE), LI(LI), DT(DT), TLI(TLI), TTI(TTI),
449         AC(AC), ORE(ORE), VF(VecWidth), UF(UnrollFactor),
450         Builder(PSE.getSE()->getContext()), Legal(LVL), Cost(CM), BFI(BFI),
451         PSI(PSI), RTChecks(RTChecks) {
452     // Query this against the original loop and save it here because the profile
453     // of the original loop header may change as the transformation happens.
454     OptForSizeBasedOnProfile = llvm::shouldOptimizeForSize(
455         OrigLoop->getHeader(), PSI, BFI, PGSOQueryType::IRPass);
456 
457     if (MinProfitableTripCount.isZero())
458       this->MinProfitableTripCount = VecWidth;
459     else
460       this->MinProfitableTripCount = MinProfitableTripCount;
461   }
462 
463   virtual ~InnerLoopVectorizer() = default;
464 
465   /// Create a new empty loop that will contain vectorized instructions later
466   /// on, while the old loop will be used as the scalar remainder. Control flow
467   /// is generated around the vectorized (and scalar epilogue) loops consisting
468   /// of various checks and bypasses. Return the pre-header block of the new
469   /// loop and the start value for the canonical induction, if it is != 0. The
470   /// latter is the case when vectorizing the epilogue loop. In the case of
471   /// epilogue vectorization, this function is overriden to handle the more
472   /// complex control flow around the loops.
473   virtual std::pair<BasicBlock *, Value *> createVectorizedLoopSkeleton();
474 
475   /// Widen a single call instruction within the innermost loop.
476   void widenCallInstruction(CallInst &I, VPValue *Def, VPUser &ArgOperands,
477                             VPTransformState &State);
478 
479   /// Fix the vectorized code, taking care of header phi's, live-outs, and more.
480   void fixVectorizedLoop(VPTransformState &State, VPlan &Plan);
481 
482   // Return true if any runtime check is added.
483   bool areSafetyChecksAdded() { return AddedSafetyChecks; }
484 
485   /// A type for vectorized values in the new loop. Each value from the
486   /// original loop, when vectorized, is represented by UF vector values in the
487   /// new unrolled loop, where UF is the unroll factor.
488   using VectorParts = SmallVector<Value *, 2>;
489 
490   /// A helper function to scalarize a single Instruction in the innermost loop.
491   /// Generates a sequence of scalar instances for each lane between \p MinLane
492   /// and \p MaxLane, times each part between \p MinPart and \p MaxPart,
493   /// inclusive. Uses the VPValue operands from \p RepRecipe instead of \p
494   /// Instr's operands.
495   void scalarizeInstruction(Instruction *Instr, VPReplicateRecipe *RepRecipe,
496                             const VPIteration &Instance, bool IfPredicateInstr,
497                             VPTransformState &State);
498 
499   /// Construct the vector value of a scalarized value \p V one lane at a time.
500   void packScalarIntoVectorValue(VPValue *Def, const VPIteration &Instance,
501                                  VPTransformState &State);
502 
503   /// Try to vectorize interleaved access group \p Group with the base address
504   /// given in \p Addr, optionally masking the vector operations if \p
505   /// BlockInMask is non-null. Use \p State to translate given VPValues to IR
506   /// values in the vectorized loop.
507   void vectorizeInterleaveGroup(const InterleaveGroup<Instruction> *Group,
508                                 ArrayRef<VPValue *> VPDefs,
509                                 VPTransformState &State, VPValue *Addr,
510                                 ArrayRef<VPValue *> StoredValues,
511                                 VPValue *BlockInMask = nullptr);
512 
513   /// Fix the non-induction PHIs in \p Plan.
514   void fixNonInductionPHIs(VPlan &Plan, VPTransformState &State);
515 
516   /// Returns true if the reordering of FP operations is not allowed, but we are
517   /// able to vectorize with strict in-order reductions for the given RdxDesc.
518   bool useOrderedReductions(const RecurrenceDescriptor &RdxDesc);
519 
520   /// Create a broadcast instruction. This method generates a broadcast
521   /// instruction (shuffle) for loop invariant values and for the induction
522   /// value. If this is the induction variable then we extend it to N, N+1, ...
523   /// this is needed because each iteration in the loop corresponds to a SIMD
524   /// element.
525   virtual Value *getBroadcastInstrs(Value *V);
526 
527   // Returns the resume value (bc.merge.rdx) for a reduction as
528   // generated by fixReduction.
529   PHINode *getReductionResumeValue(const RecurrenceDescriptor &RdxDesc);
530 
531 protected:
532   friend class LoopVectorizationPlanner;
533 
534   /// A small list of PHINodes.
535   using PhiVector = SmallVector<PHINode *, 4>;
536 
537   /// A type for scalarized values in the new loop. Each value from the
538   /// original loop, when scalarized, is represented by UF x VF scalar values
539   /// in the new unrolled loop, where UF is the unroll factor and VF is the
540   /// vectorization factor.
541   using ScalarParts = SmallVector<SmallVector<Value *, 4>, 2>;
542 
543   /// Set up the values of the IVs correctly when exiting the vector loop.
544   void fixupIVUsers(PHINode *OrigPhi, const InductionDescriptor &II,
545                     Value *VectorTripCount, Value *EndValue,
546                     BasicBlock *MiddleBlock, BasicBlock *VectorHeader,
547                     VPlan &Plan);
548 
549   /// Handle all cross-iteration phis in the header.
550   void fixCrossIterationPHIs(VPTransformState &State);
551 
552   /// Create the exit value of first order recurrences in the middle block and
553   /// update their users.
554   void fixFirstOrderRecurrence(VPFirstOrderRecurrencePHIRecipe *PhiR,
555                                VPTransformState &State);
556 
557   /// Create code for the loop exit value of the reduction.
558   void fixReduction(VPReductionPHIRecipe *Phi, VPTransformState &State);
559 
560   /// Clear NSW/NUW flags from reduction instructions if necessary.
561   void clearReductionWrapFlags(VPReductionPHIRecipe *PhiR,
562                                VPTransformState &State);
563 
564   /// Iteratively sink the scalarized operands of a predicated instruction into
565   /// the block that was created for it.
566   void sinkScalarOperands(Instruction *PredInst);
567 
568   /// Shrinks vector element sizes to the smallest bitwidth they can be legally
569   /// represented as.
570   void truncateToMinimalBitwidths(VPTransformState &State);
571 
572   /// Returns (and creates if needed) the original loop trip count.
573   Value *getOrCreateTripCount(BasicBlock *InsertBlock);
574 
575   /// Returns (and creates if needed) the trip count of the widened loop.
576   Value *getOrCreateVectorTripCount(BasicBlock *InsertBlock);
577 
578   /// Returns a bitcasted value to the requested vector type.
579   /// Also handles bitcasts of vector<float> <-> vector<pointer> types.
580   Value *createBitOrPointerCast(Value *V, VectorType *DstVTy,
581                                 const DataLayout &DL);
582 
583   /// Emit a bypass check to see if the vector trip count is zero, including if
584   /// it overflows.
585   void emitIterationCountCheck(BasicBlock *Bypass);
586 
587   /// Emit a bypass check to see if all of the SCEV assumptions we've
588   /// had to make are correct. Returns the block containing the checks or
589   /// nullptr if no checks have been added.
590   BasicBlock *emitSCEVChecks(BasicBlock *Bypass);
591 
592   /// Emit bypass checks to check any memory assumptions we may have made.
593   /// Returns the block containing the checks or nullptr if no checks have been
594   /// added.
595   BasicBlock *emitMemRuntimeChecks(BasicBlock *Bypass);
596 
597   /// Emit basic blocks (prefixed with \p Prefix) for the iteration check,
598   /// vector loop preheader, middle block and scalar preheader.
599   void createVectorLoopSkeleton(StringRef Prefix);
600 
601   /// Create new phi nodes for the induction variables to resume iteration count
602   /// in the scalar epilogue, from where the vectorized loop left off.
603   /// In cases where the loop skeleton is more complicated (eg. epilogue
604   /// vectorization) and the resume values can come from an additional bypass
605   /// block, the \p AdditionalBypass pair provides information about the bypass
606   /// block and the end value on the edge from bypass to this loop.
607   void createInductionResumeValues(
608       std::pair<BasicBlock *, Value *> AdditionalBypass = {nullptr, nullptr});
609 
610   /// Complete the loop skeleton by adding debug MDs, creating appropriate
611   /// conditional branches in the middle block, preparing the builder and
612   /// running the verifier. Return the preheader of the completed vector loop.
613   BasicBlock *completeLoopSkeleton(MDNode *OrigLoopID);
614 
615   /// Collect poison-generating recipes that may generate a poison value that is
616   /// used after vectorization, even when their operands are not poison. Those
617   /// recipes meet the following conditions:
618   ///  * Contribute to the address computation of a recipe generating a widen
619   ///    memory load/store (VPWidenMemoryInstructionRecipe or
620   ///    VPInterleaveRecipe).
621   ///  * Such a widen memory load/store has at least one underlying Instruction
622   ///    that is in a basic block that needs predication and after vectorization
623   ///    the generated instruction won't be predicated.
624   void collectPoisonGeneratingRecipes(VPTransformState &State);
625 
626   /// Allow subclasses to override and print debug traces before/after vplan
627   /// execution, when trace information is requested.
628   virtual void printDebugTracesAtStart(){};
629   virtual void printDebugTracesAtEnd(){};
630 
631   /// The original loop.
632   Loop *OrigLoop;
633 
634   /// A wrapper around ScalarEvolution used to add runtime SCEV checks. Applies
635   /// dynamic knowledge to simplify SCEV expressions and converts them to a
636   /// more usable form.
637   PredicatedScalarEvolution &PSE;
638 
639   /// Loop Info.
640   LoopInfo *LI;
641 
642   /// Dominator Tree.
643   DominatorTree *DT;
644 
645   /// Alias Analysis.
646   AAResults *AA;
647 
648   /// Target Library Info.
649   const TargetLibraryInfo *TLI;
650 
651   /// Target Transform Info.
652   const TargetTransformInfo *TTI;
653 
654   /// Assumption Cache.
655   AssumptionCache *AC;
656 
657   /// Interface to emit optimization remarks.
658   OptimizationRemarkEmitter *ORE;
659 
660   /// The vectorization SIMD factor to use. Each vector will have this many
661   /// vector elements.
662   ElementCount VF;
663 
664   ElementCount MinProfitableTripCount;
665 
666   /// The vectorization unroll factor to use. Each scalar is vectorized to this
667   /// many different vector instructions.
668   unsigned UF;
669 
670   /// The builder that we use
671   IRBuilder<> Builder;
672 
673   // --- Vectorization state ---
674 
675   /// The vector-loop preheader.
676   BasicBlock *LoopVectorPreHeader;
677 
678   /// The scalar-loop preheader.
679   BasicBlock *LoopScalarPreHeader;
680 
681   /// Middle Block between the vector and the scalar.
682   BasicBlock *LoopMiddleBlock;
683 
684   /// The unique ExitBlock of the scalar loop if one exists.  Note that
685   /// there can be multiple exiting edges reaching this block.
686   BasicBlock *LoopExitBlock;
687 
688   /// The scalar loop body.
689   BasicBlock *LoopScalarBody;
690 
691   /// A list of all bypass blocks. The first block is the entry of the loop.
692   SmallVector<BasicBlock *, 4> LoopBypassBlocks;
693 
694   /// Store instructions that were predicated.
695   SmallVector<Instruction *, 4> PredicatedInstructions;
696 
697   /// Trip count of the original loop.
698   Value *TripCount = nullptr;
699 
700   /// Trip count of the widened loop (TripCount - TripCount % (VF*UF))
701   Value *VectorTripCount = nullptr;
702 
703   /// The legality analysis.
704   LoopVectorizationLegality *Legal;
705 
706   /// The profitablity analysis.
707   LoopVectorizationCostModel *Cost;
708 
709   // Record whether runtime checks are added.
710   bool AddedSafetyChecks = false;
711 
712   // Holds the end values for each induction variable. We save the end values
713   // so we can later fix-up the external users of the induction variables.
714   DenseMap<PHINode *, Value *> IVEndValues;
715 
716   /// BFI and PSI are used to check for profile guided size optimizations.
717   BlockFrequencyInfo *BFI;
718   ProfileSummaryInfo *PSI;
719 
720   // Whether this loop should be optimized for size based on profile guided size
721   // optimizatios.
722   bool OptForSizeBasedOnProfile;
723 
724   /// Structure to hold information about generated runtime checks, responsible
725   /// for cleaning the checks, if vectorization turns out unprofitable.
726   GeneratedRTChecks &RTChecks;
727 
728   // Holds the resume values for reductions in the loops, used to set the
729   // correct start value of reduction PHIs when vectorizing the epilogue.
730   SmallMapVector<const RecurrenceDescriptor *, PHINode *, 4>
731       ReductionResumeValues;
732 };
733 
734 class InnerLoopUnroller : public InnerLoopVectorizer {
735 public:
736   InnerLoopUnroller(Loop *OrigLoop, PredicatedScalarEvolution &PSE,
737                     LoopInfo *LI, DominatorTree *DT,
738                     const TargetLibraryInfo *TLI,
739                     const TargetTransformInfo *TTI, AssumptionCache *AC,
740                     OptimizationRemarkEmitter *ORE, unsigned UnrollFactor,
741                     LoopVectorizationLegality *LVL,
742                     LoopVectorizationCostModel *CM, BlockFrequencyInfo *BFI,
743                     ProfileSummaryInfo *PSI, GeneratedRTChecks &Check)
744       : InnerLoopVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
745                             ElementCount::getFixed(1),
746                             ElementCount::getFixed(1), UnrollFactor, LVL, CM,
747                             BFI, PSI, Check) {}
748 
749 private:
750   Value *getBroadcastInstrs(Value *V) override;
751 };
752 
753 /// Encapsulate information regarding vectorization of a loop and its epilogue.
754 /// This information is meant to be updated and used across two stages of
755 /// epilogue vectorization.
756 struct EpilogueLoopVectorizationInfo {
757   ElementCount MainLoopVF = ElementCount::getFixed(0);
758   unsigned MainLoopUF = 0;
759   ElementCount EpilogueVF = ElementCount::getFixed(0);
760   unsigned EpilogueUF = 0;
761   BasicBlock *MainLoopIterationCountCheck = nullptr;
762   BasicBlock *EpilogueIterationCountCheck = nullptr;
763   BasicBlock *SCEVSafetyCheck = nullptr;
764   BasicBlock *MemSafetyCheck = nullptr;
765   Value *TripCount = nullptr;
766   Value *VectorTripCount = nullptr;
767 
768   EpilogueLoopVectorizationInfo(ElementCount MVF, unsigned MUF,
769                                 ElementCount EVF, unsigned EUF)
770       : MainLoopVF(MVF), MainLoopUF(MUF), EpilogueVF(EVF), EpilogueUF(EUF) {
771     assert(EUF == 1 &&
772            "A high UF for the epilogue loop is likely not beneficial.");
773   }
774 };
775 
776 /// An extension of the inner loop vectorizer that creates a skeleton for a
777 /// vectorized loop that has its epilogue (residual) also vectorized.
778 /// The idea is to run the vplan on a given loop twice, firstly to setup the
779 /// skeleton and vectorize the main loop, and secondly to complete the skeleton
780 /// from the first step and vectorize the epilogue.  This is achieved by
781 /// deriving two concrete strategy classes from this base class and invoking
782 /// them in succession from the loop vectorizer planner.
783 class InnerLoopAndEpilogueVectorizer : public InnerLoopVectorizer {
784 public:
785   InnerLoopAndEpilogueVectorizer(
786       Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI,
787       DominatorTree *DT, const TargetLibraryInfo *TLI,
788       const TargetTransformInfo *TTI, AssumptionCache *AC,
789       OptimizationRemarkEmitter *ORE, EpilogueLoopVectorizationInfo &EPI,
790       LoopVectorizationLegality *LVL, llvm::LoopVectorizationCostModel *CM,
791       BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI,
792       GeneratedRTChecks &Checks)
793       : InnerLoopVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
794                             EPI.MainLoopVF, EPI.MainLoopVF, EPI.MainLoopUF, LVL,
795                             CM, BFI, PSI, Checks),
796         EPI(EPI) {}
797 
798   // Override this function to handle the more complex control flow around the
799   // three loops.
800   std::pair<BasicBlock *, Value *>
801   createVectorizedLoopSkeleton() final override {
802     return createEpilogueVectorizedLoopSkeleton();
803   }
804 
805   /// The interface for creating a vectorized skeleton using one of two
806   /// different strategies, each corresponding to one execution of the vplan
807   /// as described above.
808   virtual std::pair<BasicBlock *, Value *>
809   createEpilogueVectorizedLoopSkeleton() = 0;
810 
811   /// Holds and updates state information required to vectorize the main loop
812   /// and its epilogue in two separate passes. This setup helps us avoid
813   /// regenerating and recomputing runtime safety checks. It also helps us to
814   /// shorten the iteration-count-check path length for the cases where the
815   /// iteration count of the loop is so small that the main vector loop is
816   /// completely skipped.
817   EpilogueLoopVectorizationInfo &EPI;
818 };
819 
820 /// A specialized derived class of inner loop vectorizer that performs
821 /// vectorization of *main* loops in the process of vectorizing loops and their
822 /// epilogues.
823 class EpilogueVectorizerMainLoop : public InnerLoopAndEpilogueVectorizer {
824 public:
825   EpilogueVectorizerMainLoop(
826       Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI,
827       DominatorTree *DT, const TargetLibraryInfo *TLI,
828       const TargetTransformInfo *TTI, AssumptionCache *AC,
829       OptimizationRemarkEmitter *ORE, EpilogueLoopVectorizationInfo &EPI,
830       LoopVectorizationLegality *LVL, llvm::LoopVectorizationCostModel *CM,
831       BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI,
832       GeneratedRTChecks &Check)
833       : InnerLoopAndEpilogueVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
834                                        EPI, LVL, CM, BFI, PSI, Check) {}
835   /// Implements the interface for creating a vectorized skeleton using the
836   /// *main loop* strategy (ie the first pass of vplan execution).
837   std::pair<BasicBlock *, Value *>
838   createEpilogueVectorizedLoopSkeleton() final override;
839 
840 protected:
841   /// Emits an iteration count bypass check once for the main loop (when \p
842   /// ForEpilogue is false) and once for the epilogue loop (when \p
843   /// ForEpilogue is true).
844   BasicBlock *emitIterationCountCheck(BasicBlock *Bypass, bool ForEpilogue);
845   void printDebugTracesAtStart() override;
846   void printDebugTracesAtEnd() override;
847 };
848 
849 // A specialized derived class of inner loop vectorizer that performs
850 // vectorization of *epilogue* loops in the process of vectorizing loops and
851 // their epilogues.
852 class EpilogueVectorizerEpilogueLoop : public InnerLoopAndEpilogueVectorizer {
853 public:
854   EpilogueVectorizerEpilogueLoop(
855       Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI,
856       DominatorTree *DT, const TargetLibraryInfo *TLI,
857       const TargetTransformInfo *TTI, AssumptionCache *AC,
858       OptimizationRemarkEmitter *ORE, EpilogueLoopVectorizationInfo &EPI,
859       LoopVectorizationLegality *LVL, llvm::LoopVectorizationCostModel *CM,
860       BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI,
861       GeneratedRTChecks &Checks)
862       : InnerLoopAndEpilogueVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
863                                        EPI, LVL, CM, BFI, PSI, Checks) {
864     TripCount = EPI.TripCount;
865   }
866   /// Implements the interface for creating a vectorized skeleton using the
867   /// *epilogue loop* strategy (ie the second pass of vplan execution).
868   std::pair<BasicBlock *, Value *>
869   createEpilogueVectorizedLoopSkeleton() final override;
870 
871 protected:
872   /// Emits an iteration count bypass check after the main vector loop has
873   /// finished to see if there are any iterations left to execute by either
874   /// the vector epilogue or the scalar epilogue.
875   BasicBlock *emitMinimumVectorEpilogueIterCountCheck(
876                                                       BasicBlock *Bypass,
877                                                       BasicBlock *Insert);
878   void printDebugTracesAtStart() override;
879   void printDebugTracesAtEnd() override;
880 };
881 } // end namespace llvm
882 
883 /// Look for a meaningful debug location on the instruction or it's
884 /// operands.
885 static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
886   if (!I)
887     return I;
888 
889   DebugLoc Empty;
890   if (I->getDebugLoc() != Empty)
891     return I;
892 
893   for (Use &Op : I->operands()) {
894     if (Instruction *OpInst = dyn_cast<Instruction>(Op))
895       if (OpInst->getDebugLoc() != Empty)
896         return OpInst;
897   }
898 
899   return I;
900 }
901 
902 /// Write a \p DebugMsg about vectorization to the debug output stream. If \p I
903 /// is passed, the message relates to that particular instruction.
904 #ifndef NDEBUG
905 static void debugVectorizationMessage(const StringRef Prefix,
906                                       const StringRef DebugMsg,
907                                       Instruction *I) {
908   dbgs() << "LV: " << Prefix << DebugMsg;
909   if (I != nullptr)
910     dbgs() << " " << *I;
911   else
912     dbgs() << '.';
913   dbgs() << '\n';
914 }
915 #endif
916 
917 /// Create an analysis remark that explains why vectorization failed
918 ///
919 /// \p PassName is the name of the pass (e.g. can be AlwaysPrint).  \p
920 /// RemarkName is the identifier for the remark.  If \p I is passed it is an
921 /// instruction that prevents vectorization.  Otherwise \p TheLoop is used for
922 /// the location of the remark.  \return the remark object that can be
923 /// streamed to.
924 static OptimizationRemarkAnalysis createLVAnalysis(const char *PassName,
925     StringRef RemarkName, Loop *TheLoop, Instruction *I) {
926   Value *CodeRegion = TheLoop->getHeader();
927   DebugLoc DL = TheLoop->getStartLoc();
928 
929   if (I) {
930     CodeRegion = I->getParent();
931     // If there is no debug location attached to the instruction, revert back to
932     // using the loop's.
933     if (I->getDebugLoc())
934       DL = I->getDebugLoc();
935   }
936 
937   return OptimizationRemarkAnalysis(PassName, RemarkName, DL, CodeRegion);
938 }
939 
940 namespace llvm {
941 
942 /// Return a value for Step multiplied by VF.
943 Value *createStepForVF(IRBuilderBase &B, Type *Ty, ElementCount VF,
944                        int64_t Step) {
945   assert(Ty->isIntegerTy() && "Expected an integer step");
946   Constant *StepVal = ConstantInt::get(Ty, Step * VF.getKnownMinValue());
947   return VF.isScalable() ? B.CreateVScale(StepVal) : StepVal;
948 }
949 
950 /// Return the runtime value for VF.
951 Value *getRuntimeVF(IRBuilderBase &B, Type *Ty, ElementCount VF) {
952   Constant *EC = ConstantInt::get(Ty, VF.getKnownMinValue());
953   return VF.isScalable() ? B.CreateVScale(EC) : EC;
954 }
955 
956 static Value *getRuntimeVFAsFloat(IRBuilderBase &B, Type *FTy,
957                                   ElementCount VF) {
958   assert(FTy->isFloatingPointTy() && "Expected floating point type!");
959   Type *IntTy = IntegerType::get(FTy->getContext(), FTy->getScalarSizeInBits());
960   Value *RuntimeVF = getRuntimeVF(B, IntTy, VF);
961   return B.CreateUIToFP(RuntimeVF, FTy);
962 }
963 
964 void reportVectorizationFailure(const StringRef DebugMsg,
965                                 const StringRef OREMsg, const StringRef ORETag,
966                                 OptimizationRemarkEmitter *ORE, Loop *TheLoop,
967                                 Instruction *I) {
968   LLVM_DEBUG(debugVectorizationMessage("Not vectorizing: ", DebugMsg, I));
969   LoopVectorizeHints Hints(TheLoop, true /* doesn't matter */, *ORE);
970   ORE->emit(
971       createLVAnalysis(Hints.vectorizeAnalysisPassName(), ORETag, TheLoop, I)
972       << "loop not vectorized: " << OREMsg);
973 }
974 
975 void reportVectorizationInfo(const StringRef Msg, const StringRef ORETag,
976                              OptimizationRemarkEmitter *ORE, Loop *TheLoop,
977                              Instruction *I) {
978   LLVM_DEBUG(debugVectorizationMessage("", Msg, I));
979   LoopVectorizeHints Hints(TheLoop, true /* doesn't matter */, *ORE);
980   ORE->emit(
981       createLVAnalysis(Hints.vectorizeAnalysisPassName(), ORETag, TheLoop, I)
982       << Msg);
983 }
984 
985 } // end namespace llvm
986 
987 #ifndef NDEBUG
988 /// \return string containing a file name and a line # for the given loop.
989 static std::string getDebugLocString(const Loop *L) {
990   std::string Result;
991   if (L) {
992     raw_string_ostream OS(Result);
993     if (const DebugLoc LoopDbgLoc = L->getStartLoc())
994       LoopDbgLoc.print(OS);
995     else
996       // Just print the module name.
997       OS << L->getHeader()->getParent()->getParent()->getModuleIdentifier();
998     OS.flush();
999   }
1000   return Result;
1001 }
1002 #endif
1003 
1004 void InnerLoopVectorizer::collectPoisonGeneratingRecipes(
1005     VPTransformState &State) {
1006 
1007   // Collect recipes in the backward slice of `Root` that may generate a poison
1008   // value that is used after vectorization.
1009   SmallPtrSet<VPRecipeBase *, 16> Visited;
1010   auto collectPoisonGeneratingInstrsInBackwardSlice([&](VPRecipeBase *Root) {
1011     SmallVector<VPRecipeBase *, 16> Worklist;
1012     Worklist.push_back(Root);
1013 
1014     // Traverse the backward slice of Root through its use-def chain.
1015     while (!Worklist.empty()) {
1016       VPRecipeBase *CurRec = Worklist.back();
1017       Worklist.pop_back();
1018 
1019       if (!Visited.insert(CurRec).second)
1020         continue;
1021 
1022       // Prune search if we find another recipe generating a widen memory
1023       // instruction. Widen memory instructions involved in address computation
1024       // will lead to gather/scatter instructions, which don't need to be
1025       // handled.
1026       if (isa<VPWidenMemoryInstructionRecipe>(CurRec) ||
1027           isa<VPInterleaveRecipe>(CurRec) ||
1028           isa<VPScalarIVStepsRecipe>(CurRec) ||
1029           isa<VPCanonicalIVPHIRecipe>(CurRec) ||
1030           isa<VPActiveLaneMaskPHIRecipe>(CurRec))
1031         continue;
1032 
1033       // This recipe contributes to the address computation of a widen
1034       // load/store. Collect recipe if its underlying instruction has
1035       // poison-generating flags.
1036       Instruction *Instr = CurRec->getUnderlyingInstr();
1037       if (Instr && Instr->hasPoisonGeneratingFlags())
1038         State.MayGeneratePoisonRecipes.insert(CurRec);
1039 
1040       // Add new definitions to the worklist.
1041       for (VPValue *operand : CurRec->operands())
1042         if (VPDef *OpDef = operand->getDef())
1043           Worklist.push_back(cast<VPRecipeBase>(OpDef));
1044     }
1045   });
1046 
1047   // Traverse all the recipes in the VPlan and collect the poison-generating
1048   // recipes in the backward slice starting at the address of a VPWidenRecipe or
1049   // VPInterleaveRecipe.
1050   auto Iter = depth_first(
1051       VPBlockRecursiveTraversalWrapper<VPBlockBase *>(State.Plan->getEntry()));
1052   for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(Iter)) {
1053     for (VPRecipeBase &Recipe : *VPBB) {
1054       if (auto *WidenRec = dyn_cast<VPWidenMemoryInstructionRecipe>(&Recipe)) {
1055         Instruction &UnderlyingInstr = WidenRec->getIngredient();
1056         VPDef *AddrDef = WidenRec->getAddr()->getDef();
1057         if (AddrDef && WidenRec->isConsecutive() &&
1058             Legal->blockNeedsPredication(UnderlyingInstr.getParent()))
1059           collectPoisonGeneratingInstrsInBackwardSlice(
1060               cast<VPRecipeBase>(AddrDef));
1061       } else if (auto *InterleaveRec = dyn_cast<VPInterleaveRecipe>(&Recipe)) {
1062         VPDef *AddrDef = InterleaveRec->getAddr()->getDef();
1063         if (AddrDef) {
1064           // Check if any member of the interleave group needs predication.
1065           const InterleaveGroup<Instruction> *InterGroup =
1066               InterleaveRec->getInterleaveGroup();
1067           bool NeedPredication = false;
1068           for (int I = 0, NumMembers = InterGroup->getNumMembers();
1069                I < NumMembers; ++I) {
1070             Instruction *Member = InterGroup->getMember(I);
1071             if (Member)
1072               NeedPredication |=
1073                   Legal->blockNeedsPredication(Member->getParent());
1074           }
1075 
1076           if (NeedPredication)
1077             collectPoisonGeneratingInstrsInBackwardSlice(
1078                 cast<VPRecipeBase>(AddrDef));
1079         }
1080       }
1081     }
1082   }
1083 }
1084 
1085 PHINode *InnerLoopVectorizer::getReductionResumeValue(
1086     const RecurrenceDescriptor &RdxDesc) {
1087   auto It = ReductionResumeValues.find(&RdxDesc);
1088   assert(It != ReductionResumeValues.end() &&
1089          "Expected to find a resume value for the reduction.");
1090   return It->second;
1091 }
1092 
1093 namespace llvm {
1094 
1095 // Loop vectorization cost-model hints how the scalar epilogue loop should be
1096 // lowered.
1097 enum ScalarEpilogueLowering {
1098 
1099   // The default: allowing scalar epilogues.
1100   CM_ScalarEpilogueAllowed,
1101 
1102   // Vectorization with OptForSize: don't allow epilogues.
1103   CM_ScalarEpilogueNotAllowedOptSize,
1104 
1105   // A special case of vectorisation with OptForSize: loops with a very small
1106   // trip count are considered for vectorization under OptForSize, thereby
1107   // making sure the cost of their loop body is dominant, free of runtime
1108   // guards and scalar iteration overheads.
1109   CM_ScalarEpilogueNotAllowedLowTripLoop,
1110 
1111   // Loop hint predicate indicating an epilogue is undesired.
1112   CM_ScalarEpilogueNotNeededUsePredicate,
1113 
1114   // Directive indicating we must either tail fold or not vectorize
1115   CM_ScalarEpilogueNotAllowedUsePredicate
1116 };
1117 
1118 /// ElementCountComparator creates a total ordering for ElementCount
1119 /// for the purposes of using it in a set structure.
1120 struct ElementCountComparator {
1121   bool operator()(const ElementCount &LHS, const ElementCount &RHS) const {
1122     return std::make_tuple(LHS.isScalable(), LHS.getKnownMinValue()) <
1123            std::make_tuple(RHS.isScalable(), RHS.getKnownMinValue());
1124   }
1125 };
1126 using ElementCountSet = SmallSet<ElementCount, 16, ElementCountComparator>;
1127 
1128 /// LoopVectorizationCostModel - estimates the expected speedups due to
1129 /// vectorization.
1130 /// In many cases vectorization is not profitable. This can happen because of
1131 /// a number of reasons. In this class we mainly attempt to predict the
1132 /// expected speedup/slowdowns due to the supported instruction set. We use the
1133 /// TargetTransformInfo to query the different backends for the cost of
1134 /// different operations.
1135 class LoopVectorizationCostModel {
1136 public:
1137   LoopVectorizationCostModel(ScalarEpilogueLowering SEL, Loop *L,
1138                              PredicatedScalarEvolution &PSE, LoopInfo *LI,
1139                              LoopVectorizationLegality *Legal,
1140                              const TargetTransformInfo &TTI,
1141                              const TargetLibraryInfo *TLI, DemandedBits *DB,
1142                              AssumptionCache *AC,
1143                              OptimizationRemarkEmitter *ORE, const Function *F,
1144                              const LoopVectorizeHints *Hints,
1145                              InterleavedAccessInfo &IAI)
1146       : ScalarEpilogueStatus(SEL), TheLoop(L), PSE(PSE), LI(LI), Legal(Legal),
1147         TTI(TTI), TLI(TLI), DB(DB), AC(AC), ORE(ORE), TheFunction(F),
1148         Hints(Hints), InterleaveInfo(IAI) {}
1149 
1150   /// \return An upper bound for the vectorization factors (both fixed and
1151   /// scalable). If the factors are 0, vectorization and interleaving should be
1152   /// avoided up front.
1153   FixedScalableVFPair computeMaxVF(ElementCount UserVF, unsigned UserIC);
1154 
1155   /// \return True if runtime checks are required for vectorization, and false
1156   /// otherwise.
1157   bool runtimeChecksRequired();
1158 
1159   /// \return The most profitable vectorization factor and the cost of that VF.
1160   /// This method checks every VF in \p CandidateVFs. If UserVF is not ZERO
1161   /// then this vectorization factor will be selected if vectorization is
1162   /// possible.
1163   VectorizationFactor
1164   selectVectorizationFactor(const ElementCountSet &CandidateVFs);
1165 
1166   VectorizationFactor
1167   selectEpilogueVectorizationFactor(const ElementCount MaxVF,
1168                                     const LoopVectorizationPlanner &LVP);
1169 
1170   /// Setup cost-based decisions for user vectorization factor.
1171   /// \return true if the UserVF is a feasible VF to be chosen.
1172   bool selectUserVectorizationFactor(ElementCount UserVF) {
1173     collectUniformsAndScalars(UserVF);
1174     collectInstsToScalarize(UserVF);
1175     return expectedCost(UserVF).first.isValid();
1176   }
1177 
1178   /// \return The size (in bits) of the smallest and widest types in the code
1179   /// that needs to be vectorized. We ignore values that remain scalar such as
1180   /// 64 bit loop indices.
1181   std::pair<unsigned, unsigned> getSmallestAndWidestTypes();
1182 
1183   /// \return The desired interleave count.
1184   /// If interleave count has been specified by metadata it will be returned.
1185   /// Otherwise, the interleave count is computed and returned. VF and LoopCost
1186   /// are the selected vectorization factor and the cost of the selected VF.
1187   unsigned selectInterleaveCount(ElementCount VF, unsigned LoopCost);
1188 
1189   /// Memory access instruction may be vectorized in more than one way.
1190   /// Form of instruction after vectorization depends on cost.
1191   /// This function takes cost-based decisions for Load/Store instructions
1192   /// and collects them in a map. This decisions map is used for building
1193   /// the lists of loop-uniform and loop-scalar instructions.
1194   /// The calculated cost is saved with widening decision in order to
1195   /// avoid redundant calculations.
1196   void setCostBasedWideningDecision(ElementCount VF);
1197 
1198   /// A struct that represents some properties of the register usage
1199   /// of a loop.
1200   struct RegisterUsage {
1201     /// Holds the number of loop invariant values that are used in the loop.
1202     /// The key is ClassID of target-provided register class.
1203     SmallMapVector<unsigned, unsigned, 4> LoopInvariantRegs;
1204     /// Holds the maximum number of concurrent live intervals in the loop.
1205     /// The key is ClassID of target-provided register class.
1206     SmallMapVector<unsigned, unsigned, 4> MaxLocalUsers;
1207   };
1208 
1209   /// \return Returns information about the register usages of the loop for the
1210   /// given vectorization factors.
1211   SmallVector<RegisterUsage, 8>
1212   calculateRegisterUsage(ArrayRef<ElementCount> VFs);
1213 
1214   /// Collect values we want to ignore in the cost model.
1215   void collectValuesToIgnore();
1216 
1217   /// Collect all element types in the loop for which widening is needed.
1218   void collectElementTypesForWidening();
1219 
1220   /// Split reductions into those that happen in the loop, and those that happen
1221   /// outside. In loop reductions are collected into InLoopReductionChains.
1222   void collectInLoopReductions();
1223 
1224   /// Returns true if we should use strict in-order reductions for the given
1225   /// RdxDesc. This is true if the -enable-strict-reductions flag is passed,
1226   /// the IsOrdered flag of RdxDesc is set and we do not allow reordering
1227   /// of FP operations.
1228   bool useOrderedReductions(const RecurrenceDescriptor &RdxDesc) const {
1229     return !Hints->allowReordering() && RdxDesc.isOrdered();
1230   }
1231 
1232   /// \returns The smallest bitwidth each instruction can be represented with.
1233   /// The vector equivalents of these instructions should be truncated to this
1234   /// type.
1235   const MapVector<Instruction *, uint64_t> &getMinimalBitwidths() const {
1236     return MinBWs;
1237   }
1238 
1239   /// \returns True if it is more profitable to scalarize instruction \p I for
1240   /// vectorization factor \p VF.
1241   bool isProfitableToScalarize(Instruction *I, ElementCount VF) const {
1242     assert(VF.isVector() &&
1243            "Profitable to scalarize relevant only for VF > 1.");
1244 
1245     // Cost model is not run in the VPlan-native path - return conservative
1246     // result until this changes.
1247     if (EnableVPlanNativePath)
1248       return false;
1249 
1250     auto Scalars = InstsToScalarize.find(VF);
1251     assert(Scalars != InstsToScalarize.end() &&
1252            "VF not yet analyzed for scalarization profitability");
1253     return Scalars->second.find(I) != Scalars->second.end();
1254   }
1255 
1256   /// Returns true if \p I is known to be uniform after vectorization.
1257   bool isUniformAfterVectorization(Instruction *I, ElementCount VF) const {
1258     if (VF.isScalar())
1259       return true;
1260 
1261     // Cost model is not run in the VPlan-native path - return conservative
1262     // result until this changes.
1263     if (EnableVPlanNativePath)
1264       return false;
1265 
1266     auto UniformsPerVF = Uniforms.find(VF);
1267     assert(UniformsPerVF != Uniforms.end() &&
1268            "VF not yet analyzed for uniformity");
1269     return UniformsPerVF->second.count(I);
1270   }
1271 
1272   /// Returns true if \p I is known to be scalar after vectorization.
1273   bool isScalarAfterVectorization(Instruction *I, ElementCount VF) const {
1274     if (VF.isScalar())
1275       return true;
1276 
1277     // Cost model is not run in the VPlan-native path - return conservative
1278     // result until this changes.
1279     if (EnableVPlanNativePath)
1280       return false;
1281 
1282     auto ScalarsPerVF = Scalars.find(VF);
1283     assert(ScalarsPerVF != Scalars.end() &&
1284            "Scalar values are not calculated for VF");
1285     return ScalarsPerVF->second.count(I);
1286   }
1287 
1288   /// \returns True if instruction \p I can be truncated to a smaller bitwidth
1289   /// for vectorization factor \p VF.
1290   bool canTruncateToMinimalBitwidth(Instruction *I, ElementCount VF) const {
1291     return VF.isVector() && MinBWs.find(I) != MinBWs.end() &&
1292            !isProfitableToScalarize(I, VF) &&
1293            !isScalarAfterVectorization(I, VF);
1294   }
1295 
1296   /// Decision that was taken during cost calculation for memory instruction.
1297   enum InstWidening {
1298     CM_Unknown,
1299     CM_Widen,         // For consecutive accesses with stride +1.
1300     CM_Widen_Reverse, // For consecutive accesses with stride -1.
1301     CM_Interleave,
1302     CM_GatherScatter,
1303     CM_Scalarize
1304   };
1305 
1306   /// Save vectorization decision \p W and \p Cost taken by the cost model for
1307   /// instruction \p I and vector width \p VF.
1308   void setWideningDecision(Instruction *I, ElementCount VF, InstWidening W,
1309                            InstructionCost Cost) {
1310     assert(VF.isVector() && "Expected VF >=2");
1311     WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
1312   }
1313 
1314   /// Save vectorization decision \p W and \p Cost taken by the cost model for
1315   /// interleaving group \p Grp and vector width \p VF.
1316   void setWideningDecision(const InterleaveGroup<Instruction> *Grp,
1317                            ElementCount VF, InstWidening W,
1318                            InstructionCost Cost) {
1319     assert(VF.isVector() && "Expected VF >=2");
1320     /// Broadcast this decicion to all instructions inside the group.
1321     /// But the cost will be assigned to one instruction only.
1322     for (unsigned i = 0; i < Grp->getFactor(); ++i) {
1323       if (auto *I = Grp->getMember(i)) {
1324         if (Grp->getInsertPos() == I)
1325           WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
1326         else
1327           WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, 0);
1328       }
1329     }
1330   }
1331 
1332   /// Return the cost model decision for the given instruction \p I and vector
1333   /// width \p VF. Return CM_Unknown if this instruction did not pass
1334   /// through the cost modeling.
1335   InstWidening getWideningDecision(Instruction *I, ElementCount VF) const {
1336     assert(VF.isVector() && "Expected VF to be a vector VF");
1337     // Cost model is not run in the VPlan-native path - return conservative
1338     // result until this changes.
1339     if (EnableVPlanNativePath)
1340       return CM_GatherScatter;
1341 
1342     std::pair<Instruction *, ElementCount> InstOnVF = std::make_pair(I, VF);
1343     auto Itr = WideningDecisions.find(InstOnVF);
1344     if (Itr == WideningDecisions.end())
1345       return CM_Unknown;
1346     return Itr->second.first;
1347   }
1348 
1349   /// Return the vectorization cost for the given instruction \p I and vector
1350   /// width \p VF.
1351   InstructionCost getWideningCost(Instruction *I, ElementCount VF) {
1352     assert(VF.isVector() && "Expected VF >=2");
1353     std::pair<Instruction *, ElementCount> InstOnVF = std::make_pair(I, VF);
1354     assert(WideningDecisions.find(InstOnVF) != WideningDecisions.end() &&
1355            "The cost is not calculated");
1356     return WideningDecisions[InstOnVF].second;
1357   }
1358 
1359   /// Return True if instruction \p I is an optimizable truncate whose operand
1360   /// is an induction variable. Such a truncate will be removed by adding a new
1361   /// induction variable with the destination type.
1362   bool isOptimizableIVTruncate(Instruction *I, ElementCount VF) {
1363     // If the instruction is not a truncate, return false.
1364     auto *Trunc = dyn_cast<TruncInst>(I);
1365     if (!Trunc)
1366       return false;
1367 
1368     // Get the source and destination types of the truncate.
1369     Type *SrcTy = ToVectorTy(cast<CastInst>(I)->getSrcTy(), VF);
1370     Type *DestTy = ToVectorTy(cast<CastInst>(I)->getDestTy(), VF);
1371 
1372     // If the truncate is free for the given types, return false. Replacing a
1373     // free truncate with an induction variable would add an induction variable
1374     // update instruction to each iteration of the loop. We exclude from this
1375     // check the primary induction variable since it will need an update
1376     // instruction regardless.
1377     Value *Op = Trunc->getOperand(0);
1378     if (Op != Legal->getPrimaryInduction() && TTI.isTruncateFree(SrcTy, DestTy))
1379       return false;
1380 
1381     // If the truncated value is not an induction variable, return false.
1382     return Legal->isInductionPhi(Op);
1383   }
1384 
1385   /// Collects the instructions to scalarize for each predicated instruction in
1386   /// the loop.
1387   void collectInstsToScalarize(ElementCount VF);
1388 
1389   /// Collect Uniform and Scalar values for the given \p VF.
1390   /// The sets depend on CM decision for Load/Store instructions
1391   /// that may be vectorized as interleave, gather-scatter or scalarized.
1392   void collectUniformsAndScalars(ElementCount VF) {
1393     // Do the analysis once.
1394     if (VF.isScalar() || Uniforms.find(VF) != Uniforms.end())
1395       return;
1396     setCostBasedWideningDecision(VF);
1397     collectLoopUniforms(VF);
1398     collectLoopScalars(VF);
1399   }
1400 
1401   /// Returns true if the target machine supports masked store operation
1402   /// for the given \p DataType and kind of access to \p Ptr.
1403   bool isLegalMaskedStore(Type *DataType, Value *Ptr, Align Alignment) const {
1404     return Legal->isConsecutivePtr(DataType, Ptr) &&
1405            TTI.isLegalMaskedStore(DataType, Alignment);
1406   }
1407 
1408   /// Returns true if the target machine supports masked load operation
1409   /// for the given \p DataType and kind of access to \p Ptr.
1410   bool isLegalMaskedLoad(Type *DataType, Value *Ptr, Align Alignment) const {
1411     return Legal->isConsecutivePtr(DataType, Ptr) &&
1412            TTI.isLegalMaskedLoad(DataType, Alignment);
1413   }
1414 
1415   /// Returns true if the target machine can represent \p V as a masked gather
1416   /// or scatter operation.
1417   bool isLegalGatherOrScatter(Value *V,
1418                               ElementCount VF = ElementCount::getFixed(1)) {
1419     bool LI = isa<LoadInst>(V);
1420     bool SI = isa<StoreInst>(V);
1421     if (!LI && !SI)
1422       return false;
1423     auto *Ty = getLoadStoreType(V);
1424     Align Align = getLoadStoreAlignment(V);
1425     if (VF.isVector())
1426       Ty = VectorType::get(Ty, VF);
1427     return (LI && TTI.isLegalMaskedGather(Ty, Align)) ||
1428            (SI && TTI.isLegalMaskedScatter(Ty, Align));
1429   }
1430 
1431   /// Returns true if the target machine supports all of the reduction
1432   /// variables found for the given VF.
1433   bool canVectorizeReductions(ElementCount VF) const {
1434     return (all_of(Legal->getReductionVars(), [&](auto &Reduction) -> bool {
1435       const RecurrenceDescriptor &RdxDesc = Reduction.second;
1436       return TTI.isLegalToVectorizeReduction(RdxDesc, VF);
1437     }));
1438   }
1439 
1440   /// Returns true if \p I is an instruction that will be scalarized with
1441   /// predication when vectorizing \p I with vectorization factor \p VF. Such
1442   /// instructions include conditional stores and instructions that may divide
1443   /// by zero.
1444   bool isScalarWithPredication(Instruction *I, ElementCount VF) const;
1445 
1446   // Returns true if \p I is an instruction that will be predicated either
1447   // through scalar predication or masked load/store or masked gather/scatter.
1448   // \p VF is the vectorization factor that will be used to vectorize \p I.
1449   // Superset of instructions that return true for isScalarWithPredication.
1450   bool isPredicatedInst(Instruction *I, ElementCount VF,
1451                         bool IsKnownUniform = false) {
1452     // When we know the load is uniform and the original scalar loop was not
1453     // predicated we don't need to mark it as a predicated instruction. Any
1454     // vectorised blocks created when tail-folding are something artificial we
1455     // have introduced and we know there is always at least one active lane.
1456     // That's why we call Legal->blockNeedsPredication here because it doesn't
1457     // query tail-folding.
1458     if (IsKnownUniform && isa<LoadInst>(I) &&
1459         !Legal->blockNeedsPredication(I->getParent()))
1460       return false;
1461     if (!blockNeedsPredicationForAnyReason(I->getParent()))
1462       return false;
1463     // Loads and stores that need some form of masked operation are predicated
1464     // instructions.
1465     if (isa<LoadInst>(I) || isa<StoreInst>(I))
1466       return Legal->isMaskRequired(I);
1467     return isScalarWithPredication(I, VF);
1468   }
1469 
1470   /// Returns true if \p I is a memory instruction with consecutive memory
1471   /// access that can be widened.
1472   bool
1473   memoryInstructionCanBeWidened(Instruction *I,
1474                                 ElementCount VF = ElementCount::getFixed(1));
1475 
1476   /// Returns true if \p I is a memory instruction in an interleaved-group
1477   /// of memory accesses that can be vectorized with wide vector loads/stores
1478   /// and shuffles.
1479   bool
1480   interleavedAccessCanBeWidened(Instruction *I,
1481                                 ElementCount VF = ElementCount::getFixed(1));
1482 
1483   /// Check if \p Instr belongs to any interleaved access group.
1484   bool isAccessInterleaved(Instruction *Instr) {
1485     return InterleaveInfo.isInterleaved(Instr);
1486   }
1487 
1488   /// Get the interleaved access group that \p Instr belongs to.
1489   const InterleaveGroup<Instruction> *
1490   getInterleavedAccessGroup(Instruction *Instr) {
1491     return InterleaveInfo.getInterleaveGroup(Instr);
1492   }
1493 
1494   /// Returns true if we're required to use a scalar epilogue for at least
1495   /// the final iteration of the original loop.
1496   bool requiresScalarEpilogue(ElementCount VF) const {
1497     if (!isScalarEpilogueAllowed())
1498       return false;
1499     // If we might exit from anywhere but the latch, must run the exiting
1500     // iteration in scalar form.
1501     if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch())
1502       return true;
1503     return VF.isVector() && InterleaveInfo.requiresScalarEpilogue();
1504   }
1505 
1506   /// Returns true if a scalar epilogue is not allowed due to optsize or a
1507   /// loop hint annotation.
1508   bool isScalarEpilogueAllowed() const {
1509     return ScalarEpilogueStatus == CM_ScalarEpilogueAllowed;
1510   }
1511 
1512   /// Returns true if all loop blocks should be masked to fold tail loop.
1513   bool foldTailByMasking() const { return FoldTailByMasking; }
1514 
1515   /// Returns true if were tail-folding and want to use the active lane mask
1516   /// for vector loop control flow.
1517   bool useActiveLaneMaskForControlFlow() const {
1518     return FoldTailByMasking &&
1519            TTI.emitGetActiveLaneMask() == PredicationStyle::DataAndControlFlow;
1520   }
1521 
1522   /// Returns true if the instructions in this block requires predication
1523   /// for any reason, e.g. because tail folding now requires a predicate
1524   /// or because the block in the original loop was predicated.
1525   bool blockNeedsPredicationForAnyReason(BasicBlock *BB) const {
1526     return foldTailByMasking() || Legal->blockNeedsPredication(BB);
1527   }
1528 
1529   /// A SmallMapVector to store the InLoop reduction op chains, mapping phi
1530   /// nodes to the chain of instructions representing the reductions. Uses a
1531   /// MapVector to ensure deterministic iteration order.
1532   using ReductionChainMap =
1533       SmallMapVector<PHINode *, SmallVector<Instruction *, 4>, 4>;
1534 
1535   /// Return the chain of instructions representing an inloop reduction.
1536   const ReductionChainMap &getInLoopReductionChains() const {
1537     return InLoopReductionChains;
1538   }
1539 
1540   /// Returns true if the Phi is part of an inloop reduction.
1541   bool isInLoopReduction(PHINode *Phi) const {
1542     return InLoopReductionChains.count(Phi);
1543   }
1544 
1545   /// Estimate cost of an intrinsic call instruction CI if it were vectorized
1546   /// with factor VF.  Return the cost of the instruction, including
1547   /// scalarization overhead if it's needed.
1548   InstructionCost getVectorIntrinsicCost(CallInst *CI, ElementCount VF) const;
1549 
1550   /// Estimate cost of a call instruction CI if it were vectorized with factor
1551   /// VF. Return the cost of the instruction, including scalarization overhead
1552   /// if it's needed. The flag NeedToScalarize shows if the call needs to be
1553   /// scalarized -
1554   /// i.e. either vector version isn't available, or is too expensive.
1555   InstructionCost getVectorCallCost(CallInst *CI, ElementCount VF,
1556                                     bool &NeedToScalarize) const;
1557 
1558   /// Returns true if the per-lane cost of VectorizationFactor A is lower than
1559   /// that of B.
1560   bool isMoreProfitable(const VectorizationFactor &A,
1561                         const VectorizationFactor &B) const;
1562 
1563   /// Invalidates decisions already taken by the cost model.
1564   void invalidateCostModelingDecisions() {
1565     WideningDecisions.clear();
1566     Uniforms.clear();
1567     Scalars.clear();
1568   }
1569 
1570   /// Convenience function that returns the value of vscale_range iff
1571   /// vscale_range.min == vscale_range.max or otherwise returns the value
1572   /// returned by the corresponding TLI method.
1573   Optional<unsigned> getVScaleForTuning() const;
1574 
1575 private:
1576   unsigned NumPredStores = 0;
1577 
1578   /// \return An upper bound for the vectorization factors for both
1579   /// fixed and scalable vectorization, where the minimum-known number of
1580   /// elements is a power-of-2 larger than zero. If scalable vectorization is
1581   /// disabled or unsupported, then the scalable part will be equal to
1582   /// ElementCount::getScalable(0).
1583   FixedScalableVFPair computeFeasibleMaxVF(unsigned ConstTripCount,
1584                                            ElementCount UserVF,
1585                                            bool FoldTailByMasking);
1586 
1587   /// \return the maximized element count based on the targets vector
1588   /// registers and the loop trip-count, but limited to a maximum safe VF.
1589   /// This is a helper function of computeFeasibleMaxVF.
1590   ElementCount getMaximizedVFForTarget(unsigned ConstTripCount,
1591                                        unsigned SmallestType,
1592                                        unsigned WidestType,
1593                                        ElementCount MaxSafeVF,
1594                                        bool FoldTailByMasking);
1595 
1596   /// \return the maximum legal scalable VF, based on the safe max number
1597   /// of elements.
1598   ElementCount getMaxLegalScalableVF(unsigned MaxSafeElements);
1599 
1600   /// The vectorization cost is a combination of the cost itself and a boolean
1601   /// indicating whether any of the contributing operations will actually
1602   /// operate on vector values after type legalization in the backend. If this
1603   /// latter value is false, then all operations will be scalarized (i.e. no
1604   /// vectorization has actually taken place).
1605   using VectorizationCostTy = std::pair<InstructionCost, bool>;
1606 
1607   /// Returns the expected execution cost. The unit of the cost does
1608   /// not matter because we use the 'cost' units to compare different
1609   /// vector widths. The cost that is returned is *not* normalized by
1610   /// the factor width. If \p Invalid is not nullptr, this function
1611   /// will add a pair(Instruction*, ElementCount) to \p Invalid for
1612   /// each instruction that has an Invalid cost for the given VF.
1613   using InstructionVFPair = std::pair<Instruction *, ElementCount>;
1614   VectorizationCostTy
1615   expectedCost(ElementCount VF,
1616                SmallVectorImpl<InstructionVFPair> *Invalid = nullptr);
1617 
1618   /// Returns the execution time cost of an instruction for a given vector
1619   /// width. Vector width of one means scalar.
1620   VectorizationCostTy getInstructionCost(Instruction *I, ElementCount VF);
1621 
1622   /// The cost-computation logic from getInstructionCost which provides
1623   /// the vector type as an output parameter.
1624   InstructionCost getInstructionCost(Instruction *I, ElementCount VF,
1625                                      Type *&VectorTy);
1626 
1627   /// Return the cost of instructions in an inloop reduction pattern, if I is
1628   /// part of that pattern.
1629   Optional<InstructionCost>
1630   getReductionPatternCost(Instruction *I, ElementCount VF, Type *VectorTy,
1631                           TTI::TargetCostKind CostKind);
1632 
1633   /// Calculate vectorization cost of memory instruction \p I.
1634   InstructionCost getMemoryInstructionCost(Instruction *I, ElementCount VF);
1635 
1636   /// The cost computation for scalarized memory instruction.
1637   InstructionCost getMemInstScalarizationCost(Instruction *I, ElementCount VF);
1638 
1639   /// The cost computation for interleaving group of memory instructions.
1640   InstructionCost getInterleaveGroupCost(Instruction *I, ElementCount VF);
1641 
1642   /// The cost computation for Gather/Scatter instruction.
1643   InstructionCost getGatherScatterCost(Instruction *I, ElementCount VF);
1644 
1645   /// The cost computation for widening instruction \p I with consecutive
1646   /// memory access.
1647   InstructionCost getConsecutiveMemOpCost(Instruction *I, ElementCount VF);
1648 
1649   /// The cost calculation for Load/Store instruction \p I with uniform pointer -
1650   /// Load: scalar load + broadcast.
1651   /// Store: scalar store + (loop invariant value stored? 0 : extract of last
1652   /// element)
1653   InstructionCost getUniformMemOpCost(Instruction *I, ElementCount VF);
1654 
1655   /// Estimate the overhead of scalarizing an instruction. This is a
1656   /// convenience wrapper for the type-based getScalarizationOverhead API.
1657   InstructionCost getScalarizationOverhead(Instruction *I,
1658                                            ElementCount VF) const;
1659 
1660   /// Returns whether the instruction is a load or store and will be a emitted
1661   /// as a vector operation.
1662   bool isConsecutiveLoadOrStore(Instruction *I);
1663 
1664   /// Returns true if an artificially high cost for emulated masked memrefs
1665   /// should be used.
1666   bool useEmulatedMaskMemRefHack(Instruction *I, ElementCount VF);
1667 
1668   /// Map of scalar integer values to the smallest bitwidth they can be legally
1669   /// represented as. The vector equivalents of these values should be truncated
1670   /// to this type.
1671   MapVector<Instruction *, uint64_t> MinBWs;
1672 
1673   /// A type representing the costs for instructions if they were to be
1674   /// scalarized rather than vectorized. The entries are Instruction-Cost
1675   /// pairs.
1676   using ScalarCostsTy = DenseMap<Instruction *, InstructionCost>;
1677 
1678   /// A set containing all BasicBlocks that are known to present after
1679   /// vectorization as a predicated block.
1680   DenseMap<ElementCount, SmallPtrSet<BasicBlock *, 4>>
1681       PredicatedBBsAfterVectorization;
1682 
1683   /// Records whether it is allowed to have the original scalar loop execute at
1684   /// least once. This may be needed as a fallback loop in case runtime
1685   /// aliasing/dependence checks fail, or to handle the tail/remainder
1686   /// iterations when the trip count is unknown or doesn't divide by the VF,
1687   /// or as a peel-loop to handle gaps in interleave-groups.
1688   /// Under optsize and when the trip count is very small we don't allow any
1689   /// iterations to execute in the scalar loop.
1690   ScalarEpilogueLowering ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
1691 
1692   /// All blocks of loop are to be masked to fold tail of scalar iterations.
1693   bool FoldTailByMasking = false;
1694 
1695   /// A map holding scalar costs for different vectorization factors. The
1696   /// presence of a cost for an instruction in the mapping indicates that the
1697   /// instruction will be scalarized when vectorizing with the associated
1698   /// vectorization factor. The entries are VF-ScalarCostTy pairs.
1699   DenseMap<ElementCount, ScalarCostsTy> InstsToScalarize;
1700 
1701   /// Holds the instructions known to be uniform after vectorization.
1702   /// The data is collected per VF.
1703   DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> Uniforms;
1704 
1705   /// Holds the instructions known to be scalar after vectorization.
1706   /// The data is collected per VF.
1707   DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> Scalars;
1708 
1709   /// Holds the instructions (address computations) that are forced to be
1710   /// scalarized.
1711   DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> ForcedScalars;
1712 
1713   /// PHINodes of the reductions that should be expanded in-loop along with
1714   /// their associated chains of reduction operations, in program order from top
1715   /// (PHI) to bottom
1716   ReductionChainMap InLoopReductionChains;
1717 
1718   /// A Map of inloop reduction operations and their immediate chain operand.
1719   /// FIXME: This can be removed once reductions can be costed correctly in
1720   /// vplan. This was added to allow quick lookup to the inloop operations,
1721   /// without having to loop through InLoopReductionChains.
1722   DenseMap<Instruction *, Instruction *> InLoopReductionImmediateChains;
1723 
1724   /// Returns the expected difference in cost from scalarizing the expression
1725   /// feeding a predicated instruction \p PredInst. The instructions to
1726   /// scalarize and their scalar costs are collected in \p ScalarCosts. A
1727   /// non-negative return value implies the expression will be scalarized.
1728   /// Currently, only single-use chains are considered for scalarization.
1729   int computePredInstDiscount(Instruction *PredInst, ScalarCostsTy &ScalarCosts,
1730                               ElementCount VF);
1731 
1732   /// Collect the instructions that are uniform after vectorization. An
1733   /// instruction is uniform if we represent it with a single scalar value in
1734   /// the vectorized loop corresponding to each vector iteration. Examples of
1735   /// uniform instructions include pointer operands of consecutive or
1736   /// interleaved memory accesses. Note that although uniformity implies an
1737   /// instruction will be scalar, the reverse is not true. In general, a
1738   /// scalarized instruction will be represented by VF scalar values in the
1739   /// vectorized loop, each corresponding to an iteration of the original
1740   /// scalar loop.
1741   void collectLoopUniforms(ElementCount VF);
1742 
1743   /// Collect the instructions that are scalar after vectorization. An
1744   /// instruction is scalar if it is known to be uniform or will be scalarized
1745   /// during vectorization. collectLoopScalars should only add non-uniform nodes
1746   /// to the list if they are used by a load/store instruction that is marked as
1747   /// CM_Scalarize. Non-uniform scalarized instructions will be represented by
1748   /// VF values in the vectorized loop, each corresponding to an iteration of
1749   /// the original scalar loop.
1750   void collectLoopScalars(ElementCount VF);
1751 
1752   /// Keeps cost model vectorization decision and cost for instructions.
1753   /// Right now it is used for memory instructions only.
1754   using DecisionList = DenseMap<std::pair<Instruction *, ElementCount>,
1755                                 std::pair<InstWidening, InstructionCost>>;
1756 
1757   DecisionList WideningDecisions;
1758 
1759   /// Returns true if \p V is expected to be vectorized and it needs to be
1760   /// extracted.
1761   bool needsExtract(Value *V, ElementCount VF) const {
1762     Instruction *I = dyn_cast<Instruction>(V);
1763     if (VF.isScalar() || !I || !TheLoop->contains(I) ||
1764         TheLoop->isLoopInvariant(I))
1765       return false;
1766 
1767     // Assume we can vectorize V (and hence we need extraction) if the
1768     // scalars are not computed yet. This can happen, because it is called
1769     // via getScalarizationOverhead from setCostBasedWideningDecision, before
1770     // the scalars are collected. That should be a safe assumption in most
1771     // cases, because we check if the operands have vectorizable types
1772     // beforehand in LoopVectorizationLegality.
1773     return Scalars.find(VF) == Scalars.end() ||
1774            !isScalarAfterVectorization(I, VF);
1775   };
1776 
1777   /// Returns a range containing only operands needing to be extracted.
1778   SmallVector<Value *, 4> filterExtractingOperands(Instruction::op_range Ops,
1779                                                    ElementCount VF) const {
1780     return SmallVector<Value *, 4>(make_filter_range(
1781         Ops, [this, VF](Value *V) { return this->needsExtract(V, VF); }));
1782   }
1783 
1784   /// Determines if we have the infrastructure to vectorize loop \p L and its
1785   /// epilogue, assuming the main loop is vectorized by \p VF.
1786   bool isCandidateForEpilogueVectorization(const Loop &L,
1787                                            const ElementCount VF) const;
1788 
1789   /// Returns true if epilogue vectorization is considered profitable, and
1790   /// false otherwise.
1791   /// \p VF is the vectorization factor chosen for the original loop.
1792   bool isEpilogueVectorizationProfitable(const ElementCount VF) const;
1793 
1794 public:
1795   /// The loop that we evaluate.
1796   Loop *TheLoop;
1797 
1798   /// Predicated scalar evolution analysis.
1799   PredicatedScalarEvolution &PSE;
1800 
1801   /// Loop Info analysis.
1802   LoopInfo *LI;
1803 
1804   /// Vectorization legality.
1805   LoopVectorizationLegality *Legal;
1806 
1807   /// Vector target information.
1808   const TargetTransformInfo &TTI;
1809 
1810   /// Target Library Info.
1811   const TargetLibraryInfo *TLI;
1812 
1813   /// Demanded bits analysis.
1814   DemandedBits *DB;
1815 
1816   /// Assumption cache.
1817   AssumptionCache *AC;
1818 
1819   /// Interface to emit optimization remarks.
1820   OptimizationRemarkEmitter *ORE;
1821 
1822   const Function *TheFunction;
1823 
1824   /// Loop Vectorize Hint.
1825   const LoopVectorizeHints *Hints;
1826 
1827   /// The interleave access information contains groups of interleaved accesses
1828   /// with the same stride and close to each other.
1829   InterleavedAccessInfo &InterleaveInfo;
1830 
1831   /// Values to ignore in the cost model.
1832   SmallPtrSet<const Value *, 16> ValuesToIgnore;
1833 
1834   /// Values to ignore in the cost model when VF > 1.
1835   SmallPtrSet<const Value *, 16> VecValuesToIgnore;
1836 
1837   /// All element types found in the loop.
1838   SmallPtrSet<Type *, 16> ElementTypesInLoop;
1839 
1840   /// Profitable vector factors.
1841   SmallVector<VectorizationFactor, 8> ProfitableVFs;
1842 };
1843 } // end namespace llvm
1844 
1845 /// Helper struct to manage generating runtime checks for vectorization.
1846 ///
1847 /// The runtime checks are created up-front in temporary blocks to allow better
1848 /// estimating the cost and un-linked from the existing IR. After deciding to
1849 /// vectorize, the checks are moved back. If deciding not to vectorize, the
1850 /// temporary blocks are completely removed.
1851 class GeneratedRTChecks {
1852   /// Basic block which contains the generated SCEV checks, if any.
1853   BasicBlock *SCEVCheckBlock = nullptr;
1854 
1855   /// The value representing the result of the generated SCEV checks. If it is
1856   /// nullptr, either no SCEV checks have been generated or they have been used.
1857   Value *SCEVCheckCond = nullptr;
1858 
1859   /// Basic block which contains the generated memory runtime checks, if any.
1860   BasicBlock *MemCheckBlock = nullptr;
1861 
1862   /// The value representing the result of the generated memory runtime checks.
1863   /// If it is nullptr, either no memory runtime checks have been generated or
1864   /// they have been used.
1865   Value *MemRuntimeCheckCond = nullptr;
1866 
1867   DominatorTree *DT;
1868   LoopInfo *LI;
1869   TargetTransformInfo *TTI;
1870 
1871   SCEVExpander SCEVExp;
1872   SCEVExpander MemCheckExp;
1873 
1874   bool CostTooHigh = false;
1875 
1876 public:
1877   GeneratedRTChecks(ScalarEvolution &SE, DominatorTree *DT, LoopInfo *LI,
1878                     TargetTransformInfo *TTI, const DataLayout &DL)
1879       : DT(DT), LI(LI), TTI(TTI), SCEVExp(SE, DL, "scev.check"),
1880         MemCheckExp(SE, DL, "scev.check") {}
1881 
1882   /// Generate runtime checks in SCEVCheckBlock and MemCheckBlock, so we can
1883   /// accurately estimate the cost of the runtime checks. The blocks are
1884   /// un-linked from the IR and is added back during vector code generation. If
1885   /// there is no vector code generation, the check blocks are removed
1886   /// completely.
1887   void Create(Loop *L, const LoopAccessInfo &LAI,
1888               const SCEVPredicate &UnionPred, ElementCount VF, unsigned IC) {
1889 
1890     // Hard cutoff to limit compile-time increase in case a very large number of
1891     // runtime checks needs to be generated.
1892     // TODO: Skip cutoff if the loop is guaranteed to execute, e.g. due to
1893     // profile info.
1894     CostTooHigh =
1895         LAI.getNumRuntimePointerChecks() > VectorizeMemoryCheckThreshold;
1896     if (CostTooHigh)
1897       return;
1898 
1899     BasicBlock *LoopHeader = L->getHeader();
1900     BasicBlock *Preheader = L->getLoopPreheader();
1901 
1902     // Use SplitBlock to create blocks for SCEV & memory runtime checks to
1903     // ensure the blocks are properly added to LoopInfo & DominatorTree. Those
1904     // may be used by SCEVExpander. The blocks will be un-linked from their
1905     // predecessors and removed from LI & DT at the end of the function.
1906     if (!UnionPred.isAlwaysTrue()) {
1907       SCEVCheckBlock = SplitBlock(Preheader, Preheader->getTerminator(), DT, LI,
1908                                   nullptr, "vector.scevcheck");
1909 
1910       SCEVCheckCond = SCEVExp.expandCodeForPredicate(
1911           &UnionPred, SCEVCheckBlock->getTerminator());
1912     }
1913 
1914     const auto &RtPtrChecking = *LAI.getRuntimePointerChecking();
1915     if (RtPtrChecking.Need) {
1916       auto *Pred = SCEVCheckBlock ? SCEVCheckBlock : Preheader;
1917       MemCheckBlock = SplitBlock(Pred, Pred->getTerminator(), DT, LI, nullptr,
1918                                  "vector.memcheck");
1919 
1920       auto DiffChecks = RtPtrChecking.getDiffChecks();
1921       if (DiffChecks) {
1922         MemRuntimeCheckCond = addDiffRuntimeChecks(
1923             MemCheckBlock->getTerminator(), L, *DiffChecks, MemCheckExp,
1924             [VF](IRBuilderBase &B, unsigned Bits) {
1925               return getRuntimeVF(B, B.getIntNTy(Bits), VF);
1926             },
1927             IC);
1928       } else {
1929         MemRuntimeCheckCond =
1930             addRuntimeChecks(MemCheckBlock->getTerminator(), L,
1931                              RtPtrChecking.getChecks(), MemCheckExp);
1932       }
1933       assert(MemRuntimeCheckCond &&
1934              "no RT checks generated although RtPtrChecking "
1935              "claimed checks are required");
1936     }
1937 
1938     if (!MemCheckBlock && !SCEVCheckBlock)
1939       return;
1940 
1941     // Unhook the temporary block with the checks, update various places
1942     // accordingly.
1943     if (SCEVCheckBlock)
1944       SCEVCheckBlock->replaceAllUsesWith(Preheader);
1945     if (MemCheckBlock)
1946       MemCheckBlock->replaceAllUsesWith(Preheader);
1947 
1948     if (SCEVCheckBlock) {
1949       SCEVCheckBlock->getTerminator()->moveBefore(Preheader->getTerminator());
1950       new UnreachableInst(Preheader->getContext(), SCEVCheckBlock);
1951       Preheader->getTerminator()->eraseFromParent();
1952     }
1953     if (MemCheckBlock) {
1954       MemCheckBlock->getTerminator()->moveBefore(Preheader->getTerminator());
1955       new UnreachableInst(Preheader->getContext(), MemCheckBlock);
1956       Preheader->getTerminator()->eraseFromParent();
1957     }
1958 
1959     DT->changeImmediateDominator(LoopHeader, Preheader);
1960     if (MemCheckBlock) {
1961       DT->eraseNode(MemCheckBlock);
1962       LI->removeBlock(MemCheckBlock);
1963     }
1964     if (SCEVCheckBlock) {
1965       DT->eraseNode(SCEVCheckBlock);
1966       LI->removeBlock(SCEVCheckBlock);
1967     }
1968   }
1969 
1970   InstructionCost getCost() {
1971     if (SCEVCheckBlock || MemCheckBlock)
1972       LLVM_DEBUG(dbgs() << "Calculating cost of runtime checks:\n");
1973 
1974     if (CostTooHigh) {
1975       InstructionCost Cost;
1976       Cost.setInvalid();
1977       LLVM_DEBUG(dbgs() << "  number of checks exceeded threshold\n");
1978       return Cost;
1979     }
1980 
1981     InstructionCost RTCheckCost = 0;
1982     if (SCEVCheckBlock)
1983       for (Instruction &I : *SCEVCheckBlock) {
1984         if (SCEVCheckBlock->getTerminator() == &I)
1985           continue;
1986         InstructionCost C =
1987             TTI->getInstructionCost(&I, TTI::TCK_RecipThroughput);
1988         LLVM_DEBUG(dbgs() << "  " << C << "  for " << I << "\n");
1989         RTCheckCost += C;
1990       }
1991     if (MemCheckBlock)
1992       for (Instruction &I : *MemCheckBlock) {
1993         if (MemCheckBlock->getTerminator() == &I)
1994           continue;
1995         InstructionCost C =
1996             TTI->getInstructionCost(&I, TTI::TCK_RecipThroughput);
1997         LLVM_DEBUG(dbgs() << "  " << C << "  for " << I << "\n");
1998         RTCheckCost += C;
1999       }
2000 
2001     if (SCEVCheckBlock || MemCheckBlock)
2002       LLVM_DEBUG(dbgs() << "Total cost of runtime checks: " << RTCheckCost
2003                         << "\n");
2004 
2005     return RTCheckCost;
2006   }
2007 
2008   /// Remove the created SCEV & memory runtime check blocks & instructions, if
2009   /// unused.
2010   ~GeneratedRTChecks() {
2011     SCEVExpanderCleaner SCEVCleaner(SCEVExp);
2012     SCEVExpanderCleaner MemCheckCleaner(MemCheckExp);
2013     if (!SCEVCheckCond)
2014       SCEVCleaner.markResultUsed();
2015 
2016     if (!MemRuntimeCheckCond)
2017       MemCheckCleaner.markResultUsed();
2018 
2019     if (MemRuntimeCheckCond) {
2020       auto &SE = *MemCheckExp.getSE();
2021       // Memory runtime check generation creates compares that use expanded
2022       // values. Remove them before running the SCEVExpanderCleaners.
2023       for (auto &I : make_early_inc_range(reverse(*MemCheckBlock))) {
2024         if (MemCheckExp.isInsertedInstruction(&I))
2025           continue;
2026         SE.forgetValue(&I);
2027         I.eraseFromParent();
2028       }
2029     }
2030     MemCheckCleaner.cleanup();
2031     SCEVCleaner.cleanup();
2032 
2033     if (SCEVCheckCond)
2034       SCEVCheckBlock->eraseFromParent();
2035     if (MemRuntimeCheckCond)
2036       MemCheckBlock->eraseFromParent();
2037   }
2038 
2039   /// Adds the generated SCEVCheckBlock before \p LoopVectorPreHeader and
2040   /// adjusts the branches to branch to the vector preheader or \p Bypass,
2041   /// depending on the generated condition.
2042   BasicBlock *emitSCEVChecks(BasicBlock *Bypass,
2043                              BasicBlock *LoopVectorPreHeader,
2044                              BasicBlock *LoopExitBlock) {
2045     if (!SCEVCheckCond)
2046       return nullptr;
2047 
2048     Value *Cond = SCEVCheckCond;
2049     // Mark the check as used, to prevent it from being removed during cleanup.
2050     SCEVCheckCond = nullptr;
2051     if (auto *C = dyn_cast<ConstantInt>(Cond))
2052       if (C->isZero())
2053         return nullptr;
2054 
2055     auto *Pred = LoopVectorPreHeader->getSinglePredecessor();
2056 
2057     BranchInst::Create(LoopVectorPreHeader, SCEVCheckBlock);
2058     // Create new preheader for vector loop.
2059     if (auto *PL = LI->getLoopFor(LoopVectorPreHeader))
2060       PL->addBasicBlockToLoop(SCEVCheckBlock, *LI);
2061 
2062     SCEVCheckBlock->getTerminator()->eraseFromParent();
2063     SCEVCheckBlock->moveBefore(LoopVectorPreHeader);
2064     Pred->getTerminator()->replaceSuccessorWith(LoopVectorPreHeader,
2065                                                 SCEVCheckBlock);
2066 
2067     DT->addNewBlock(SCEVCheckBlock, Pred);
2068     DT->changeImmediateDominator(LoopVectorPreHeader, SCEVCheckBlock);
2069 
2070     ReplaceInstWithInst(SCEVCheckBlock->getTerminator(),
2071                         BranchInst::Create(Bypass, LoopVectorPreHeader, Cond));
2072     return SCEVCheckBlock;
2073   }
2074 
2075   /// Adds the generated MemCheckBlock before \p LoopVectorPreHeader and adjusts
2076   /// the branches to branch to the vector preheader or \p Bypass, depending on
2077   /// the generated condition.
2078   BasicBlock *emitMemRuntimeChecks(BasicBlock *Bypass,
2079                                    BasicBlock *LoopVectorPreHeader) {
2080     // Check if we generated code that checks in runtime if arrays overlap.
2081     if (!MemRuntimeCheckCond)
2082       return nullptr;
2083 
2084     auto *Pred = LoopVectorPreHeader->getSinglePredecessor();
2085     Pred->getTerminator()->replaceSuccessorWith(LoopVectorPreHeader,
2086                                                 MemCheckBlock);
2087 
2088     DT->addNewBlock(MemCheckBlock, Pred);
2089     DT->changeImmediateDominator(LoopVectorPreHeader, MemCheckBlock);
2090     MemCheckBlock->moveBefore(LoopVectorPreHeader);
2091 
2092     if (auto *PL = LI->getLoopFor(LoopVectorPreHeader))
2093       PL->addBasicBlockToLoop(MemCheckBlock, *LI);
2094 
2095     ReplaceInstWithInst(
2096         MemCheckBlock->getTerminator(),
2097         BranchInst::Create(Bypass, LoopVectorPreHeader, MemRuntimeCheckCond));
2098     MemCheckBlock->getTerminator()->setDebugLoc(
2099         Pred->getTerminator()->getDebugLoc());
2100 
2101     // Mark the check as used, to prevent it from being removed during cleanup.
2102     MemRuntimeCheckCond = nullptr;
2103     return MemCheckBlock;
2104   }
2105 };
2106 
2107 // Return true if \p OuterLp is an outer loop annotated with hints for explicit
2108 // vectorization. The loop needs to be annotated with #pragma omp simd
2109 // simdlen(#) or #pragma clang vectorize(enable) vectorize_width(#). If the
2110 // vector length information is not provided, vectorization is not considered
2111 // explicit. Interleave hints are not allowed either. These limitations will be
2112 // relaxed in the future.
2113 // Please, note that we are currently forced to abuse the pragma 'clang
2114 // vectorize' semantics. This pragma provides *auto-vectorization hints*
2115 // (i.e., LV must check that vectorization is legal) whereas pragma 'omp simd'
2116 // provides *explicit vectorization hints* (LV can bypass legal checks and
2117 // assume that vectorization is legal). However, both hints are implemented
2118 // using the same metadata (llvm.loop.vectorize, processed by
2119 // LoopVectorizeHints). This will be fixed in the future when the native IR
2120 // representation for pragma 'omp simd' is introduced.
2121 static bool isExplicitVecOuterLoop(Loop *OuterLp,
2122                                    OptimizationRemarkEmitter *ORE) {
2123   assert(!OuterLp->isInnermost() && "This is not an outer loop");
2124   LoopVectorizeHints Hints(OuterLp, true /*DisableInterleaving*/, *ORE);
2125 
2126   // Only outer loops with an explicit vectorization hint are supported.
2127   // Unannotated outer loops are ignored.
2128   if (Hints.getForce() == LoopVectorizeHints::FK_Undefined)
2129     return false;
2130 
2131   Function *Fn = OuterLp->getHeader()->getParent();
2132   if (!Hints.allowVectorization(Fn, OuterLp,
2133                                 true /*VectorizeOnlyWhenForced*/)) {
2134     LLVM_DEBUG(dbgs() << "LV: Loop hints prevent outer loop vectorization.\n");
2135     return false;
2136   }
2137 
2138   if (Hints.getInterleave() > 1) {
2139     // TODO: Interleave support is future work.
2140     LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Interleave is not supported for "
2141                          "outer loops.\n");
2142     Hints.emitRemarkWithHints();
2143     return false;
2144   }
2145 
2146   return true;
2147 }
2148 
2149 static void collectSupportedLoops(Loop &L, LoopInfo *LI,
2150                                   OptimizationRemarkEmitter *ORE,
2151                                   SmallVectorImpl<Loop *> &V) {
2152   // Collect inner loops and outer loops without irreducible control flow. For
2153   // now, only collect outer loops that have explicit vectorization hints. If we
2154   // are stress testing the VPlan H-CFG construction, we collect the outermost
2155   // loop of every loop nest.
2156   if (L.isInnermost() || VPlanBuildStressTest ||
2157       (EnableVPlanNativePath && isExplicitVecOuterLoop(&L, ORE))) {
2158     LoopBlocksRPO RPOT(&L);
2159     RPOT.perform(LI);
2160     if (!containsIrreducibleCFG<const BasicBlock *>(RPOT, *LI)) {
2161       V.push_back(&L);
2162       // TODO: Collect inner loops inside marked outer loops in case
2163       // vectorization fails for the outer loop. Do not invoke
2164       // 'containsIrreducibleCFG' again for inner loops when the outer loop is
2165       // already known to be reducible. We can use an inherited attribute for
2166       // that.
2167       return;
2168     }
2169   }
2170   for (Loop *InnerL : L)
2171     collectSupportedLoops(*InnerL, LI, ORE, V);
2172 }
2173 
2174 namespace {
2175 
2176 /// The LoopVectorize Pass.
2177 struct LoopVectorize : public FunctionPass {
2178   /// Pass identification, replacement for typeid
2179   static char ID;
2180 
2181   LoopVectorizePass Impl;
2182 
2183   explicit LoopVectorize(bool InterleaveOnlyWhenForced = false,
2184                          bool VectorizeOnlyWhenForced = false)
2185       : FunctionPass(ID),
2186         Impl({InterleaveOnlyWhenForced, VectorizeOnlyWhenForced}) {
2187     initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
2188   }
2189 
2190   bool runOnFunction(Function &F) override {
2191     if (skipFunction(F))
2192       return false;
2193 
2194     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
2195     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2196     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
2197     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2198     auto *BFI = &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI();
2199     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
2200     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
2201     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
2202     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
2203     auto *LAA = &getAnalysis<LoopAccessLegacyAnalysis>();
2204     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
2205     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
2206     auto *PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
2207 
2208     std::function<const LoopAccessInfo &(Loop &)> GetLAA =
2209         [&](Loop &L) -> const LoopAccessInfo & { return LAA->getInfo(&L); };
2210 
2211     return Impl.runImpl(F, *SE, *LI, *TTI, *DT, *BFI, TLI, *DB, *AA, *AC,
2212                         GetLAA, *ORE, PSI).MadeAnyChange;
2213   }
2214 
2215   void getAnalysisUsage(AnalysisUsage &AU) const override {
2216     AU.addRequired<AssumptionCacheTracker>();
2217     AU.addRequired<BlockFrequencyInfoWrapperPass>();
2218     AU.addRequired<DominatorTreeWrapperPass>();
2219     AU.addRequired<LoopInfoWrapperPass>();
2220     AU.addRequired<ScalarEvolutionWrapperPass>();
2221     AU.addRequired<TargetTransformInfoWrapperPass>();
2222     AU.addRequired<AAResultsWrapperPass>();
2223     AU.addRequired<LoopAccessLegacyAnalysis>();
2224     AU.addRequired<DemandedBitsWrapperPass>();
2225     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
2226     AU.addRequired<InjectTLIMappingsLegacy>();
2227 
2228     // We currently do not preserve loopinfo/dominator analyses with outer loop
2229     // vectorization. Until this is addressed, mark these analyses as preserved
2230     // only for non-VPlan-native path.
2231     // TODO: Preserve Loop and Dominator analyses for VPlan-native path.
2232     if (!EnableVPlanNativePath) {
2233       AU.addPreserved<LoopInfoWrapperPass>();
2234       AU.addPreserved<DominatorTreeWrapperPass>();
2235     }
2236 
2237     AU.addPreserved<BasicAAWrapperPass>();
2238     AU.addPreserved<GlobalsAAWrapperPass>();
2239     AU.addRequired<ProfileSummaryInfoWrapperPass>();
2240   }
2241 };
2242 
2243 } // end anonymous namespace
2244 
2245 //===----------------------------------------------------------------------===//
2246 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
2247 // LoopVectorizationCostModel and LoopVectorizationPlanner.
2248 //===----------------------------------------------------------------------===//
2249 
2250 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
2251   // We need to place the broadcast of invariant variables outside the loop,
2252   // but only if it's proven safe to do so. Else, broadcast will be inside
2253   // vector loop body.
2254   Instruction *Instr = dyn_cast<Instruction>(V);
2255   bool SafeToHoist = OrigLoop->isLoopInvariant(V) &&
2256                      (!Instr ||
2257                       DT->dominates(Instr->getParent(), LoopVectorPreHeader));
2258   // Place the code for broadcasting invariant variables in the new preheader.
2259   IRBuilder<>::InsertPointGuard Guard(Builder);
2260   if (SafeToHoist)
2261     Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
2262 
2263   // Broadcast the scalar into all locations in the vector.
2264   Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
2265 
2266   return Shuf;
2267 }
2268 
2269 /// This function adds
2270 /// (StartIdx * Step, (StartIdx + 1) * Step, (StartIdx + 2) * Step, ...)
2271 /// to each vector element of Val. The sequence starts at StartIndex.
2272 /// \p Opcode is relevant for FP induction variable.
2273 static Value *getStepVector(Value *Val, Value *StartIdx, Value *Step,
2274                             Instruction::BinaryOps BinOp, ElementCount VF,
2275                             IRBuilderBase &Builder) {
2276   assert(VF.isVector() && "only vector VFs are supported");
2277 
2278   // Create and check the types.
2279   auto *ValVTy = cast<VectorType>(Val->getType());
2280   ElementCount VLen = ValVTy->getElementCount();
2281 
2282   Type *STy = Val->getType()->getScalarType();
2283   assert((STy->isIntegerTy() || STy->isFloatingPointTy()) &&
2284          "Induction Step must be an integer or FP");
2285   assert(Step->getType() == STy && "Step has wrong type");
2286 
2287   SmallVector<Constant *, 8> Indices;
2288 
2289   // Create a vector of consecutive numbers from zero to VF.
2290   VectorType *InitVecValVTy = ValVTy;
2291   if (STy->isFloatingPointTy()) {
2292     Type *InitVecValSTy =
2293         IntegerType::get(STy->getContext(), STy->getScalarSizeInBits());
2294     InitVecValVTy = VectorType::get(InitVecValSTy, VLen);
2295   }
2296   Value *InitVec = Builder.CreateStepVector(InitVecValVTy);
2297 
2298   // Splat the StartIdx
2299   Value *StartIdxSplat = Builder.CreateVectorSplat(VLen, StartIdx);
2300 
2301   if (STy->isIntegerTy()) {
2302     InitVec = Builder.CreateAdd(InitVec, StartIdxSplat);
2303     Step = Builder.CreateVectorSplat(VLen, Step);
2304     assert(Step->getType() == Val->getType() && "Invalid step vec");
2305     // FIXME: The newly created binary instructions should contain nsw/nuw
2306     // flags, which can be found from the original scalar operations.
2307     Step = Builder.CreateMul(InitVec, Step);
2308     return Builder.CreateAdd(Val, Step, "induction");
2309   }
2310 
2311   // Floating point induction.
2312   assert((BinOp == Instruction::FAdd || BinOp == Instruction::FSub) &&
2313          "Binary Opcode should be specified for FP induction");
2314   InitVec = Builder.CreateUIToFP(InitVec, ValVTy);
2315   InitVec = Builder.CreateFAdd(InitVec, StartIdxSplat);
2316 
2317   Step = Builder.CreateVectorSplat(VLen, Step);
2318   Value *MulOp = Builder.CreateFMul(InitVec, Step);
2319   return Builder.CreateBinOp(BinOp, Val, MulOp, "induction");
2320 }
2321 
2322 /// Compute scalar induction steps. \p ScalarIV is the scalar induction
2323 /// variable on which to base the steps, \p Step is the size of the step.
2324 static void buildScalarSteps(Value *ScalarIV, Value *Step,
2325                              const InductionDescriptor &ID, VPValue *Def,
2326                              VPTransformState &State) {
2327   IRBuilderBase &Builder = State.Builder;
2328   // We shouldn't have to build scalar steps if we aren't vectorizing.
2329   assert(State.VF.isVector() && "VF should be greater than one");
2330   // Get the value type and ensure it and the step have the same integer type.
2331   Type *ScalarIVTy = ScalarIV->getType()->getScalarType();
2332   assert(ScalarIVTy == Step->getType() &&
2333          "Val and Step should have the same type");
2334 
2335   // We build scalar steps for both integer and floating-point induction
2336   // variables. Here, we determine the kind of arithmetic we will perform.
2337   Instruction::BinaryOps AddOp;
2338   Instruction::BinaryOps MulOp;
2339   if (ScalarIVTy->isIntegerTy()) {
2340     AddOp = Instruction::Add;
2341     MulOp = Instruction::Mul;
2342   } else {
2343     AddOp = ID.getInductionOpcode();
2344     MulOp = Instruction::FMul;
2345   }
2346 
2347   // Determine the number of scalars we need to generate for each unroll
2348   // iteration.
2349   bool FirstLaneOnly = vputils::onlyFirstLaneUsed(Def);
2350   unsigned Lanes = FirstLaneOnly ? 1 : State.VF.getKnownMinValue();
2351   // Compute the scalar steps and save the results in State.
2352   Type *IntStepTy = IntegerType::get(ScalarIVTy->getContext(),
2353                                      ScalarIVTy->getScalarSizeInBits());
2354   Type *VecIVTy = nullptr;
2355   Value *UnitStepVec = nullptr, *SplatStep = nullptr, *SplatIV = nullptr;
2356   if (!FirstLaneOnly && State.VF.isScalable()) {
2357     VecIVTy = VectorType::get(ScalarIVTy, State.VF);
2358     UnitStepVec =
2359         Builder.CreateStepVector(VectorType::get(IntStepTy, State.VF));
2360     SplatStep = Builder.CreateVectorSplat(State.VF, Step);
2361     SplatIV = Builder.CreateVectorSplat(State.VF, ScalarIV);
2362   }
2363 
2364   for (unsigned Part = 0; Part < State.UF; ++Part) {
2365     Value *StartIdx0 = createStepForVF(Builder, IntStepTy, State.VF, Part);
2366 
2367     if (!FirstLaneOnly && State.VF.isScalable()) {
2368       auto *SplatStartIdx = Builder.CreateVectorSplat(State.VF, StartIdx0);
2369       auto *InitVec = Builder.CreateAdd(SplatStartIdx, UnitStepVec);
2370       if (ScalarIVTy->isFloatingPointTy())
2371         InitVec = Builder.CreateSIToFP(InitVec, VecIVTy);
2372       auto *Mul = Builder.CreateBinOp(MulOp, InitVec, SplatStep);
2373       auto *Add = Builder.CreateBinOp(AddOp, SplatIV, Mul);
2374       State.set(Def, Add, Part);
2375       // It's useful to record the lane values too for the known minimum number
2376       // of elements so we do those below. This improves the code quality when
2377       // trying to extract the first element, for example.
2378     }
2379 
2380     if (ScalarIVTy->isFloatingPointTy())
2381       StartIdx0 = Builder.CreateSIToFP(StartIdx0, ScalarIVTy);
2382 
2383     for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
2384       Value *StartIdx = Builder.CreateBinOp(
2385           AddOp, StartIdx0, getSignedIntOrFpConstant(ScalarIVTy, Lane));
2386       // The step returned by `createStepForVF` is a runtime-evaluated value
2387       // when VF is scalable. Otherwise, it should be folded into a Constant.
2388       assert((State.VF.isScalable() || isa<Constant>(StartIdx)) &&
2389              "Expected StartIdx to be folded to a constant when VF is not "
2390              "scalable");
2391       auto *Mul = Builder.CreateBinOp(MulOp, StartIdx, Step);
2392       auto *Add = Builder.CreateBinOp(AddOp, ScalarIV, Mul);
2393       State.set(Def, Add, VPIteration(Part, Lane));
2394     }
2395   }
2396 }
2397 
2398 // Generate code for the induction step. Note that induction steps are
2399 // required to be loop-invariant
2400 static Value *CreateStepValue(const SCEV *Step, ScalarEvolution &SE,
2401                               Instruction *InsertBefore,
2402                               Loop *OrigLoop = nullptr) {
2403   const DataLayout &DL = SE.getDataLayout();
2404   assert((!OrigLoop || SE.isLoopInvariant(Step, OrigLoop)) &&
2405          "Induction step should be loop invariant");
2406   if (auto *E = dyn_cast<SCEVUnknown>(Step))
2407     return E->getValue();
2408 
2409   SCEVExpander Exp(SE, DL, "induction");
2410   return Exp.expandCodeFor(Step, Step->getType(), InsertBefore);
2411 }
2412 
2413 /// Compute the transformed value of Index at offset StartValue using step
2414 /// StepValue.
2415 /// For integer induction, returns StartValue + Index * StepValue.
2416 /// For pointer induction, returns StartValue[Index * StepValue].
2417 /// FIXME: The newly created binary instructions should contain nsw/nuw
2418 /// flags, which can be found from the original scalar operations.
2419 static Value *emitTransformedIndex(IRBuilderBase &B, Value *Index,
2420                                    Value *StartValue, Value *Step,
2421                                    const InductionDescriptor &ID) {
2422   assert(Index->getType()->getScalarType() == Step->getType() &&
2423          "Index scalar type does not match StepValue type");
2424 
2425   // Note: the IR at this point is broken. We cannot use SE to create any new
2426   // SCEV and then expand it, hoping that SCEV's simplification will give us
2427   // a more optimal code. Unfortunately, attempt of doing so on invalid IR may
2428   // lead to various SCEV crashes. So all we can do is to use builder and rely
2429   // on InstCombine for future simplifications. Here we handle some trivial
2430   // cases only.
2431   auto CreateAdd = [&B](Value *X, Value *Y) {
2432     assert(X->getType() == Y->getType() && "Types don't match!");
2433     if (auto *CX = dyn_cast<ConstantInt>(X))
2434       if (CX->isZero())
2435         return Y;
2436     if (auto *CY = dyn_cast<ConstantInt>(Y))
2437       if (CY->isZero())
2438         return X;
2439     return B.CreateAdd(X, Y);
2440   };
2441 
2442   // We allow X to be a vector type, in which case Y will potentially be
2443   // splatted into a vector with the same element count.
2444   auto CreateMul = [&B](Value *X, Value *Y) {
2445     assert(X->getType()->getScalarType() == Y->getType() &&
2446            "Types don't match!");
2447     if (auto *CX = dyn_cast<ConstantInt>(X))
2448       if (CX->isOne())
2449         return Y;
2450     if (auto *CY = dyn_cast<ConstantInt>(Y))
2451       if (CY->isOne())
2452         return X;
2453     VectorType *XVTy = dyn_cast<VectorType>(X->getType());
2454     if (XVTy && !isa<VectorType>(Y->getType()))
2455       Y = B.CreateVectorSplat(XVTy->getElementCount(), Y);
2456     return B.CreateMul(X, Y);
2457   };
2458 
2459   switch (ID.getKind()) {
2460   case InductionDescriptor::IK_IntInduction: {
2461     assert(!isa<VectorType>(Index->getType()) &&
2462            "Vector indices not supported for integer inductions yet");
2463     assert(Index->getType() == StartValue->getType() &&
2464            "Index type does not match StartValue type");
2465     if (isa<ConstantInt>(Step) && cast<ConstantInt>(Step)->isMinusOne())
2466       return B.CreateSub(StartValue, Index);
2467     auto *Offset = CreateMul(Index, Step);
2468     return CreateAdd(StartValue, Offset);
2469   }
2470   case InductionDescriptor::IK_PtrInduction: {
2471     assert(isa<Constant>(Step) &&
2472            "Expected constant step for pointer induction");
2473     return B.CreateGEP(ID.getElementType(), StartValue, CreateMul(Index, Step));
2474   }
2475   case InductionDescriptor::IK_FpInduction: {
2476     assert(!isa<VectorType>(Index->getType()) &&
2477            "Vector indices not supported for FP inductions yet");
2478     assert(Step->getType()->isFloatingPointTy() && "Expected FP Step value");
2479     auto InductionBinOp = ID.getInductionBinOp();
2480     assert(InductionBinOp &&
2481            (InductionBinOp->getOpcode() == Instruction::FAdd ||
2482             InductionBinOp->getOpcode() == Instruction::FSub) &&
2483            "Original bin op should be defined for FP induction");
2484 
2485     Value *MulExp = B.CreateFMul(Step, Index);
2486     return B.CreateBinOp(InductionBinOp->getOpcode(), StartValue, MulExp,
2487                          "induction");
2488   }
2489   case InductionDescriptor::IK_NoInduction:
2490     return nullptr;
2491   }
2492   llvm_unreachable("invalid enum");
2493 }
2494 
2495 void InnerLoopVectorizer::packScalarIntoVectorValue(VPValue *Def,
2496                                                     const VPIteration &Instance,
2497                                                     VPTransformState &State) {
2498   Value *ScalarInst = State.get(Def, Instance);
2499   Value *VectorValue = State.get(Def, Instance.Part);
2500   VectorValue = Builder.CreateInsertElement(
2501       VectorValue, ScalarInst,
2502       Instance.Lane.getAsRuntimeExpr(State.Builder, VF));
2503   State.set(Def, VectorValue, Instance.Part);
2504 }
2505 
2506 // Return whether we allow using masked interleave-groups (for dealing with
2507 // strided loads/stores that reside in predicated blocks, or for dealing
2508 // with gaps).
2509 static bool useMaskedInterleavedAccesses(const TargetTransformInfo &TTI) {
2510   // If an override option has been passed in for interleaved accesses, use it.
2511   if (EnableMaskedInterleavedMemAccesses.getNumOccurrences() > 0)
2512     return EnableMaskedInterleavedMemAccesses;
2513 
2514   return TTI.enableMaskedInterleavedAccessVectorization();
2515 }
2516 
2517 // Try to vectorize the interleave group that \p Instr belongs to.
2518 //
2519 // E.g. Translate following interleaved load group (factor = 3):
2520 //   for (i = 0; i < N; i+=3) {
2521 //     R = Pic[i];             // Member of index 0
2522 //     G = Pic[i+1];           // Member of index 1
2523 //     B = Pic[i+2];           // Member of index 2
2524 //     ... // do something to R, G, B
2525 //   }
2526 // To:
2527 //   %wide.vec = load <12 x i32>                       ; Read 4 tuples of R,G,B
2528 //   %R.vec = shuffle %wide.vec, poison, <0, 3, 6, 9>   ; R elements
2529 //   %G.vec = shuffle %wide.vec, poison, <1, 4, 7, 10>  ; G elements
2530 //   %B.vec = shuffle %wide.vec, poison, <2, 5, 8, 11>  ; B elements
2531 //
2532 // Or translate following interleaved store group (factor = 3):
2533 //   for (i = 0; i < N; i+=3) {
2534 //     ... do something to R, G, B
2535 //     Pic[i]   = R;           // Member of index 0
2536 //     Pic[i+1] = G;           // Member of index 1
2537 //     Pic[i+2] = B;           // Member of index 2
2538 //   }
2539 // To:
2540 //   %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
2541 //   %B_U.vec = shuffle %B.vec, poison, <0, 1, 2, 3, u, u, u, u>
2542 //   %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
2543 //        <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>    ; Interleave R,G,B elements
2544 //   store <12 x i32> %interleaved.vec              ; Write 4 tuples of R,G,B
2545 void InnerLoopVectorizer::vectorizeInterleaveGroup(
2546     const InterleaveGroup<Instruction> *Group, ArrayRef<VPValue *> VPDefs,
2547     VPTransformState &State, VPValue *Addr, ArrayRef<VPValue *> StoredValues,
2548     VPValue *BlockInMask) {
2549   Instruction *Instr = Group->getInsertPos();
2550   const DataLayout &DL = Instr->getModule()->getDataLayout();
2551 
2552   // Prepare for the vector type of the interleaved load/store.
2553   Type *ScalarTy = getLoadStoreType(Instr);
2554   unsigned InterleaveFactor = Group->getFactor();
2555   assert(!VF.isScalable() && "scalable vectors not yet supported.");
2556   auto *VecTy = VectorType::get(ScalarTy, VF * InterleaveFactor);
2557 
2558   // Prepare for the new pointers.
2559   SmallVector<Value *, 2> AddrParts;
2560   unsigned Index = Group->getIndex(Instr);
2561 
2562   // TODO: extend the masked interleaved-group support to reversed access.
2563   assert((!BlockInMask || !Group->isReverse()) &&
2564          "Reversed masked interleave-group not supported.");
2565 
2566   // If the group is reverse, adjust the index to refer to the last vector lane
2567   // instead of the first. We adjust the index from the first vector lane,
2568   // rather than directly getting the pointer for lane VF - 1, because the
2569   // pointer operand of the interleaved access is supposed to be uniform. For
2570   // uniform instructions, we're only required to generate a value for the
2571   // first vector lane in each unroll iteration.
2572   if (Group->isReverse())
2573     Index += (VF.getKnownMinValue() - 1) * Group->getFactor();
2574 
2575   for (unsigned Part = 0; Part < UF; Part++) {
2576     Value *AddrPart = State.get(Addr, VPIteration(Part, 0));
2577     State.setDebugLocFromInst(AddrPart);
2578 
2579     // Notice current instruction could be any index. Need to adjust the address
2580     // to the member of index 0.
2581     //
2582     // E.g.  a = A[i+1];     // Member of index 1 (Current instruction)
2583     //       b = A[i];       // Member of index 0
2584     // Current pointer is pointed to A[i+1], adjust it to A[i].
2585     //
2586     // E.g.  A[i+1] = a;     // Member of index 1
2587     //       A[i]   = b;     // Member of index 0
2588     //       A[i+2] = c;     // Member of index 2 (Current instruction)
2589     // Current pointer is pointed to A[i+2], adjust it to A[i].
2590 
2591     bool InBounds = false;
2592     if (auto *gep = dyn_cast<GetElementPtrInst>(AddrPart->stripPointerCasts()))
2593       InBounds = gep->isInBounds();
2594     AddrPart = Builder.CreateGEP(ScalarTy, AddrPart, Builder.getInt32(-Index));
2595     cast<GetElementPtrInst>(AddrPart)->setIsInBounds(InBounds);
2596 
2597     // Cast to the vector pointer type.
2598     unsigned AddressSpace = AddrPart->getType()->getPointerAddressSpace();
2599     Type *PtrTy = VecTy->getPointerTo(AddressSpace);
2600     AddrParts.push_back(Builder.CreateBitCast(AddrPart, PtrTy));
2601   }
2602 
2603   State.setDebugLocFromInst(Instr);
2604   Value *PoisonVec = PoisonValue::get(VecTy);
2605 
2606   Value *MaskForGaps = nullptr;
2607   if (Group->requiresScalarEpilogue() && !Cost->isScalarEpilogueAllowed()) {
2608     MaskForGaps = createBitMaskForGaps(Builder, VF.getKnownMinValue(), *Group);
2609     assert(MaskForGaps && "Mask for Gaps is required but it is null");
2610   }
2611 
2612   // Vectorize the interleaved load group.
2613   if (isa<LoadInst>(Instr)) {
2614     // For each unroll part, create a wide load for the group.
2615     SmallVector<Value *, 2> NewLoads;
2616     for (unsigned Part = 0; Part < UF; Part++) {
2617       Instruction *NewLoad;
2618       if (BlockInMask || MaskForGaps) {
2619         assert(useMaskedInterleavedAccesses(*TTI) &&
2620                "masked interleaved groups are not allowed.");
2621         Value *GroupMask = MaskForGaps;
2622         if (BlockInMask) {
2623           Value *BlockInMaskPart = State.get(BlockInMask, Part);
2624           Value *ShuffledMask = Builder.CreateShuffleVector(
2625               BlockInMaskPart,
2626               createReplicatedMask(InterleaveFactor, VF.getKnownMinValue()),
2627               "interleaved.mask");
2628           GroupMask = MaskForGaps
2629                           ? Builder.CreateBinOp(Instruction::And, ShuffledMask,
2630                                                 MaskForGaps)
2631                           : ShuffledMask;
2632         }
2633         NewLoad =
2634             Builder.CreateMaskedLoad(VecTy, AddrParts[Part], Group->getAlign(),
2635                                      GroupMask, PoisonVec, "wide.masked.vec");
2636       }
2637       else
2638         NewLoad = Builder.CreateAlignedLoad(VecTy, AddrParts[Part],
2639                                             Group->getAlign(), "wide.vec");
2640       Group->addMetadata(NewLoad);
2641       NewLoads.push_back(NewLoad);
2642     }
2643 
2644     // For each member in the group, shuffle out the appropriate data from the
2645     // wide loads.
2646     unsigned J = 0;
2647     for (unsigned I = 0; I < InterleaveFactor; ++I) {
2648       Instruction *Member = Group->getMember(I);
2649 
2650       // Skip the gaps in the group.
2651       if (!Member)
2652         continue;
2653 
2654       auto StrideMask =
2655           createStrideMask(I, InterleaveFactor, VF.getKnownMinValue());
2656       for (unsigned Part = 0; Part < UF; Part++) {
2657         Value *StridedVec = Builder.CreateShuffleVector(
2658             NewLoads[Part], StrideMask, "strided.vec");
2659 
2660         // If this member has different type, cast the result type.
2661         if (Member->getType() != ScalarTy) {
2662           assert(!VF.isScalable() && "VF is assumed to be non scalable.");
2663           VectorType *OtherVTy = VectorType::get(Member->getType(), VF);
2664           StridedVec = createBitOrPointerCast(StridedVec, OtherVTy, DL);
2665         }
2666 
2667         if (Group->isReverse())
2668           StridedVec = Builder.CreateVectorReverse(StridedVec, "reverse");
2669 
2670         State.set(VPDefs[J], StridedVec, Part);
2671       }
2672       ++J;
2673     }
2674     return;
2675   }
2676 
2677   // The sub vector type for current instruction.
2678   auto *SubVT = VectorType::get(ScalarTy, VF);
2679 
2680   // Vectorize the interleaved store group.
2681   MaskForGaps = createBitMaskForGaps(Builder, VF.getKnownMinValue(), *Group);
2682   assert((!MaskForGaps || useMaskedInterleavedAccesses(*TTI)) &&
2683          "masked interleaved groups are not allowed.");
2684   assert((!MaskForGaps || !VF.isScalable()) &&
2685          "masking gaps for scalable vectors is not yet supported.");
2686   for (unsigned Part = 0; Part < UF; Part++) {
2687     // Collect the stored vector from each member.
2688     SmallVector<Value *, 4> StoredVecs;
2689     for (unsigned i = 0; i < InterleaveFactor; i++) {
2690       assert((Group->getMember(i) || MaskForGaps) &&
2691              "Fail to get a member from an interleaved store group");
2692       Instruction *Member = Group->getMember(i);
2693 
2694       // Skip the gaps in the group.
2695       if (!Member) {
2696         Value *Undef = PoisonValue::get(SubVT);
2697         StoredVecs.push_back(Undef);
2698         continue;
2699       }
2700 
2701       Value *StoredVec = State.get(StoredValues[i], Part);
2702 
2703       if (Group->isReverse())
2704         StoredVec = Builder.CreateVectorReverse(StoredVec, "reverse");
2705 
2706       // If this member has different type, cast it to a unified type.
2707 
2708       if (StoredVec->getType() != SubVT)
2709         StoredVec = createBitOrPointerCast(StoredVec, SubVT, DL);
2710 
2711       StoredVecs.push_back(StoredVec);
2712     }
2713 
2714     // Concatenate all vectors into a wide vector.
2715     Value *WideVec = concatenateVectors(Builder, StoredVecs);
2716 
2717     // Interleave the elements in the wide vector.
2718     Value *IVec = Builder.CreateShuffleVector(
2719         WideVec, createInterleaveMask(VF.getKnownMinValue(), InterleaveFactor),
2720         "interleaved.vec");
2721 
2722     Instruction *NewStoreInstr;
2723     if (BlockInMask || MaskForGaps) {
2724       Value *GroupMask = MaskForGaps;
2725       if (BlockInMask) {
2726         Value *BlockInMaskPart = State.get(BlockInMask, Part);
2727         Value *ShuffledMask = Builder.CreateShuffleVector(
2728             BlockInMaskPart,
2729             createReplicatedMask(InterleaveFactor, VF.getKnownMinValue()),
2730             "interleaved.mask");
2731         GroupMask = MaskForGaps ? Builder.CreateBinOp(Instruction::And,
2732                                                       ShuffledMask, MaskForGaps)
2733                                 : ShuffledMask;
2734       }
2735       NewStoreInstr = Builder.CreateMaskedStore(IVec, AddrParts[Part],
2736                                                 Group->getAlign(), GroupMask);
2737     } else
2738       NewStoreInstr =
2739           Builder.CreateAlignedStore(IVec, AddrParts[Part], Group->getAlign());
2740 
2741     Group->addMetadata(NewStoreInstr);
2742   }
2743 }
2744 
2745 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr,
2746                                                VPReplicateRecipe *RepRecipe,
2747                                                const VPIteration &Instance,
2748                                                bool IfPredicateInstr,
2749                                                VPTransformState &State) {
2750   assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
2751 
2752   // llvm.experimental.noalias.scope.decl intrinsics must only be duplicated for
2753   // the first lane and part.
2754   if (isa<NoAliasScopeDeclInst>(Instr))
2755     if (!Instance.isFirstIteration())
2756       return;
2757 
2758   // Does this instruction return a value ?
2759   bool IsVoidRetTy = Instr->getType()->isVoidTy();
2760 
2761   Instruction *Cloned = Instr->clone();
2762   if (!IsVoidRetTy)
2763     Cloned->setName(Instr->getName() + ".cloned");
2764 
2765   // If the scalarized instruction contributes to the address computation of a
2766   // widen masked load/store which was in a basic block that needed predication
2767   // and is not predicated after vectorization, we can't propagate
2768   // poison-generating flags (nuw/nsw, exact, inbounds, etc.). The scalarized
2769   // instruction could feed a poison value to the base address of the widen
2770   // load/store.
2771   if (State.MayGeneratePoisonRecipes.contains(RepRecipe))
2772     Cloned->dropPoisonGeneratingFlags();
2773 
2774   if (Instr->getDebugLoc())
2775     State.setDebugLocFromInst(Instr);
2776 
2777   // Replace the operands of the cloned instructions with their scalar
2778   // equivalents in the new loop.
2779   for (auto &I : enumerate(RepRecipe->operands())) {
2780     auto InputInstance = Instance;
2781     VPValue *Operand = I.value();
2782     VPReplicateRecipe *OperandR = dyn_cast<VPReplicateRecipe>(Operand);
2783     if (OperandR && OperandR->isUniform())
2784       InputInstance.Lane = VPLane::getFirstLane();
2785     Cloned->setOperand(I.index(), State.get(Operand, InputInstance));
2786   }
2787   State.addNewMetadata(Cloned, Instr);
2788 
2789   // Place the cloned scalar in the new loop.
2790   State.Builder.Insert(Cloned);
2791 
2792   State.set(RepRecipe, Cloned, Instance);
2793 
2794   // If we just cloned a new assumption, add it the assumption cache.
2795   if (auto *II = dyn_cast<AssumeInst>(Cloned))
2796     AC->registerAssumption(II);
2797 
2798   // End if-block.
2799   if (IfPredicateInstr)
2800     PredicatedInstructions.push_back(Cloned);
2801 }
2802 
2803 Value *InnerLoopVectorizer::getOrCreateTripCount(BasicBlock *InsertBlock) {
2804   if (TripCount)
2805     return TripCount;
2806 
2807   assert(InsertBlock);
2808   IRBuilder<> Builder(InsertBlock->getTerminator());
2809   // Find the loop boundaries.
2810   ScalarEvolution *SE = PSE.getSE();
2811   const SCEV *BackedgeTakenCount = PSE.getBackedgeTakenCount();
2812   assert(!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
2813          "Invalid loop count");
2814 
2815   Type *IdxTy = Legal->getWidestInductionType();
2816   assert(IdxTy && "No type for induction");
2817 
2818   // The exit count might have the type of i64 while the phi is i32. This can
2819   // happen if we have an induction variable that is sign extended before the
2820   // compare. The only way that we get a backedge taken count is that the
2821   // induction variable was signed and as such will not overflow. In such a case
2822   // truncation is legal.
2823   if (SE->getTypeSizeInBits(BackedgeTakenCount->getType()) >
2824       IdxTy->getPrimitiveSizeInBits())
2825     BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount, IdxTy);
2826   BackedgeTakenCount = SE->getNoopOrZeroExtend(BackedgeTakenCount, IdxTy);
2827 
2828   // Get the total trip count from the count by adding 1.
2829   const SCEV *ExitCount = SE->getAddExpr(
2830       BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType()));
2831 
2832   const DataLayout &DL = InsertBlock->getModule()->getDataLayout();
2833 
2834   // Expand the trip count and place the new instructions in the preheader.
2835   // Notice that the pre-header does not change, only the loop body.
2836   SCEVExpander Exp(*SE, DL, "induction");
2837 
2838   // Count holds the overall loop count (N).
2839   TripCount = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
2840                                 InsertBlock->getTerminator());
2841 
2842   if (TripCount->getType()->isPointerTy())
2843     TripCount =
2844         CastInst::CreatePointerCast(TripCount, IdxTy, "exitcount.ptrcnt.to.int",
2845                                     InsertBlock->getTerminator());
2846 
2847   return TripCount;
2848 }
2849 
2850 Value *
2851 InnerLoopVectorizer::getOrCreateVectorTripCount(BasicBlock *InsertBlock) {
2852   if (VectorTripCount)
2853     return VectorTripCount;
2854 
2855   Value *TC = getOrCreateTripCount(InsertBlock);
2856   IRBuilder<> Builder(InsertBlock->getTerminator());
2857 
2858   Type *Ty = TC->getType();
2859   // This is where we can make the step a runtime constant.
2860   Value *Step = createStepForVF(Builder, Ty, VF, UF);
2861 
2862   // If the tail is to be folded by masking, round the number of iterations N
2863   // up to a multiple of Step instead of rounding down. This is done by first
2864   // adding Step-1 and then rounding down. Note that it's ok if this addition
2865   // overflows: the vector induction variable will eventually wrap to zero given
2866   // that it starts at zero and its Step is a power of two; the loop will then
2867   // exit, with the last early-exit vector comparison also producing all-true.
2868   // For scalable vectors the VF is not guaranteed to be a power of 2, but this
2869   // is accounted for in emitIterationCountCheck that adds an overflow check.
2870   if (Cost->foldTailByMasking()) {
2871     assert(isPowerOf2_32(VF.getKnownMinValue() * UF) &&
2872            "VF*UF must be a power of 2 when folding tail by masking");
2873     Value *NumLanes = getRuntimeVF(Builder, Ty, VF * UF);
2874     TC = Builder.CreateAdd(
2875         TC, Builder.CreateSub(NumLanes, ConstantInt::get(Ty, 1)), "n.rnd.up");
2876   }
2877 
2878   // Now we need to generate the expression for the part of the loop that the
2879   // vectorized body will execute. This is equal to N - (N % Step) if scalar
2880   // iterations are not required for correctness, or N - Step, otherwise. Step
2881   // is equal to the vectorization factor (number of SIMD elements) times the
2882   // unroll factor (number of SIMD instructions).
2883   Value *R = Builder.CreateURem(TC, Step, "n.mod.vf");
2884 
2885   // There are cases where we *must* run at least one iteration in the remainder
2886   // loop.  See the cost model for when this can happen.  If the step evenly
2887   // divides the trip count, we set the remainder to be equal to the step. If
2888   // the step does not evenly divide the trip count, no adjustment is necessary
2889   // since there will already be scalar iterations. Note that the minimum
2890   // iterations check ensures that N >= Step.
2891   if (Cost->requiresScalarEpilogue(VF)) {
2892     auto *IsZero = Builder.CreateICmpEQ(R, ConstantInt::get(R->getType(), 0));
2893     R = Builder.CreateSelect(IsZero, Step, R);
2894   }
2895 
2896   VectorTripCount = Builder.CreateSub(TC, R, "n.vec");
2897 
2898   return VectorTripCount;
2899 }
2900 
2901 Value *InnerLoopVectorizer::createBitOrPointerCast(Value *V, VectorType *DstVTy,
2902                                                    const DataLayout &DL) {
2903   // Verify that V is a vector type with same number of elements as DstVTy.
2904   auto *DstFVTy = cast<FixedVectorType>(DstVTy);
2905   unsigned VF = DstFVTy->getNumElements();
2906   auto *SrcVecTy = cast<FixedVectorType>(V->getType());
2907   assert((VF == SrcVecTy->getNumElements()) && "Vector dimensions do not match");
2908   Type *SrcElemTy = SrcVecTy->getElementType();
2909   Type *DstElemTy = DstFVTy->getElementType();
2910   assert((DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy)) &&
2911          "Vector elements must have same size");
2912 
2913   // Do a direct cast if element types are castable.
2914   if (CastInst::isBitOrNoopPointerCastable(SrcElemTy, DstElemTy, DL)) {
2915     return Builder.CreateBitOrPointerCast(V, DstFVTy);
2916   }
2917   // V cannot be directly casted to desired vector type.
2918   // May happen when V is a floating point vector but DstVTy is a vector of
2919   // pointers or vice-versa. Handle this using a two-step bitcast using an
2920   // intermediate Integer type for the bitcast i.e. Ptr <-> Int <-> Float.
2921   assert((DstElemTy->isPointerTy() != SrcElemTy->isPointerTy()) &&
2922          "Only one type should be a pointer type");
2923   assert((DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy()) &&
2924          "Only one type should be a floating point type");
2925   Type *IntTy =
2926       IntegerType::getIntNTy(V->getContext(), DL.getTypeSizeInBits(SrcElemTy));
2927   auto *VecIntTy = FixedVectorType::get(IntTy, VF);
2928   Value *CastVal = Builder.CreateBitOrPointerCast(V, VecIntTy);
2929   return Builder.CreateBitOrPointerCast(CastVal, DstFVTy);
2930 }
2931 
2932 void InnerLoopVectorizer::emitIterationCountCheck(BasicBlock *Bypass) {
2933   Value *Count = getOrCreateTripCount(LoopVectorPreHeader);
2934   // Reuse existing vector loop preheader for TC checks.
2935   // Note that new preheader block is generated for vector loop.
2936   BasicBlock *const TCCheckBlock = LoopVectorPreHeader;
2937   IRBuilder<> Builder(TCCheckBlock->getTerminator());
2938 
2939   // Generate code to check if the loop's trip count is less than VF * UF, or
2940   // equal to it in case a scalar epilogue is required; this implies that the
2941   // vector trip count is zero. This check also covers the case where adding one
2942   // to the backedge-taken count overflowed leading to an incorrect trip count
2943   // of zero. In this case we will also jump to the scalar loop.
2944   auto P = Cost->requiresScalarEpilogue(VF) ? ICmpInst::ICMP_ULE
2945                                             : ICmpInst::ICMP_ULT;
2946 
2947   // If tail is to be folded, vector loop takes care of all iterations.
2948   Type *CountTy = Count->getType();
2949   Value *CheckMinIters = Builder.getFalse();
2950   auto CreateStep = [&]() -> Value * {
2951     // Create step with max(MinProTripCount, UF * VF).
2952     if (UF * VF.getKnownMinValue() >= MinProfitableTripCount.getKnownMinValue())
2953       return createStepForVF(Builder, CountTy, VF, UF);
2954 
2955     Value *MinProfTC =
2956         createStepForVF(Builder, CountTy, MinProfitableTripCount, 1);
2957     if (!VF.isScalable())
2958       return MinProfTC;
2959     return Builder.CreateBinaryIntrinsic(
2960         Intrinsic::umax, MinProfTC, createStepForVF(Builder, CountTy, VF, UF));
2961   };
2962 
2963   if (!Cost->foldTailByMasking())
2964     CheckMinIters =
2965         Builder.CreateICmp(P, Count, CreateStep(), "min.iters.check");
2966   else if (VF.isScalable()) {
2967     // vscale is not necessarily a power-of-2, which means we cannot guarantee
2968     // an overflow to zero when updating induction variables and so an
2969     // additional overflow check is required before entering the vector loop.
2970 
2971     // Get the maximum unsigned value for the type.
2972     Value *MaxUIntTripCount =
2973         ConstantInt::get(CountTy, cast<IntegerType>(CountTy)->getMask());
2974     Value *LHS = Builder.CreateSub(MaxUIntTripCount, Count);
2975 
2976     // Don't execute the vector loop if (UMax - n) < (VF * UF).
2977     CheckMinIters = Builder.CreateICmp(ICmpInst::ICMP_ULT, LHS, CreateStep());
2978   }
2979 
2980   // Create new preheader for vector loop.
2981   LoopVectorPreHeader =
2982       SplitBlock(TCCheckBlock, TCCheckBlock->getTerminator(), DT, LI, nullptr,
2983                  "vector.ph");
2984 
2985   assert(DT->properlyDominates(DT->getNode(TCCheckBlock),
2986                                DT->getNode(Bypass)->getIDom()) &&
2987          "TC check is expected to dominate Bypass");
2988 
2989   // Update dominator for Bypass & LoopExit (if needed).
2990   DT->changeImmediateDominator(Bypass, TCCheckBlock);
2991   if (!Cost->requiresScalarEpilogue(VF))
2992     // If there is an epilogue which must run, there's no edge from the
2993     // middle block to exit blocks  and thus no need to update the immediate
2994     // dominator of the exit blocks.
2995     DT->changeImmediateDominator(LoopExitBlock, TCCheckBlock);
2996 
2997   ReplaceInstWithInst(
2998       TCCheckBlock->getTerminator(),
2999       BranchInst::Create(Bypass, LoopVectorPreHeader, CheckMinIters));
3000   LoopBypassBlocks.push_back(TCCheckBlock);
3001 }
3002 
3003 BasicBlock *InnerLoopVectorizer::emitSCEVChecks(BasicBlock *Bypass) {
3004   BasicBlock *const SCEVCheckBlock =
3005       RTChecks.emitSCEVChecks(Bypass, LoopVectorPreHeader, LoopExitBlock);
3006   if (!SCEVCheckBlock)
3007     return nullptr;
3008 
3009   assert(!(SCEVCheckBlock->getParent()->hasOptSize() ||
3010            (OptForSizeBasedOnProfile &&
3011             Cost->Hints->getForce() != LoopVectorizeHints::FK_Enabled)) &&
3012          "Cannot SCEV check stride or overflow when optimizing for size");
3013 
3014 
3015   // Update dominator only if this is first RT check.
3016   if (LoopBypassBlocks.empty()) {
3017     DT->changeImmediateDominator(Bypass, SCEVCheckBlock);
3018     if (!Cost->requiresScalarEpilogue(VF))
3019       // If there is an epilogue which must run, there's no edge from the
3020       // middle block to exit blocks  and thus no need to update the immediate
3021       // dominator of the exit blocks.
3022       DT->changeImmediateDominator(LoopExitBlock, SCEVCheckBlock);
3023   }
3024 
3025   LoopBypassBlocks.push_back(SCEVCheckBlock);
3026   AddedSafetyChecks = true;
3027   return SCEVCheckBlock;
3028 }
3029 
3030 BasicBlock *InnerLoopVectorizer::emitMemRuntimeChecks(BasicBlock *Bypass) {
3031   // VPlan-native path does not do any analysis for runtime checks currently.
3032   if (EnableVPlanNativePath)
3033     return nullptr;
3034 
3035   BasicBlock *const MemCheckBlock =
3036       RTChecks.emitMemRuntimeChecks(Bypass, LoopVectorPreHeader);
3037 
3038   // Check if we generated code that checks in runtime if arrays overlap. We put
3039   // the checks into a separate block to make the more common case of few
3040   // elements faster.
3041   if (!MemCheckBlock)
3042     return nullptr;
3043 
3044   if (MemCheckBlock->getParent()->hasOptSize() || OptForSizeBasedOnProfile) {
3045     assert(Cost->Hints->getForce() == LoopVectorizeHints::FK_Enabled &&
3046            "Cannot emit memory checks when optimizing for size, unless forced "
3047            "to vectorize.");
3048     ORE->emit([&]() {
3049       return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationCodeSize",
3050                                         OrigLoop->getStartLoc(),
3051                                         OrigLoop->getHeader())
3052              << "Code-size may be reduced by not forcing "
3053                 "vectorization, or by source-code modifications "
3054                 "eliminating the need for runtime checks "
3055                 "(e.g., adding 'restrict').";
3056     });
3057   }
3058 
3059   LoopBypassBlocks.push_back(MemCheckBlock);
3060 
3061   AddedSafetyChecks = true;
3062 
3063   return MemCheckBlock;
3064 }
3065 
3066 void InnerLoopVectorizer::createVectorLoopSkeleton(StringRef Prefix) {
3067   LoopScalarBody = OrigLoop->getHeader();
3068   LoopVectorPreHeader = OrigLoop->getLoopPreheader();
3069   assert(LoopVectorPreHeader && "Invalid loop structure");
3070   LoopExitBlock = OrigLoop->getUniqueExitBlock(); // may be nullptr
3071   assert((LoopExitBlock || Cost->requiresScalarEpilogue(VF)) &&
3072          "multiple exit loop without required epilogue?");
3073 
3074   LoopMiddleBlock =
3075       SplitBlock(LoopVectorPreHeader, LoopVectorPreHeader->getTerminator(), DT,
3076                  LI, nullptr, Twine(Prefix) + "middle.block");
3077   LoopScalarPreHeader =
3078       SplitBlock(LoopMiddleBlock, LoopMiddleBlock->getTerminator(), DT, LI,
3079                  nullptr, Twine(Prefix) + "scalar.ph");
3080 
3081   auto *ScalarLatchTerm = OrigLoop->getLoopLatch()->getTerminator();
3082 
3083   // Set up the middle block terminator.  Two cases:
3084   // 1) If we know that we must execute the scalar epilogue, emit an
3085   //    unconditional branch.
3086   // 2) Otherwise, we must have a single unique exit block (due to how we
3087   //    implement the multiple exit case).  In this case, set up a conditonal
3088   //    branch from the middle block to the loop scalar preheader, and the
3089   //    exit block.  completeLoopSkeleton will update the condition to use an
3090   //    iteration check, if required to decide whether to execute the remainder.
3091   BranchInst *BrInst = Cost->requiresScalarEpilogue(VF) ?
3092     BranchInst::Create(LoopScalarPreHeader) :
3093     BranchInst::Create(LoopExitBlock, LoopScalarPreHeader,
3094                        Builder.getTrue());
3095   BrInst->setDebugLoc(ScalarLatchTerm->getDebugLoc());
3096   ReplaceInstWithInst(LoopMiddleBlock->getTerminator(), BrInst);
3097 
3098   // Update dominator for loop exit. During skeleton creation, only the vector
3099   // pre-header and the middle block are created. The vector loop is entirely
3100   // created during VPlan exection.
3101   if (!Cost->requiresScalarEpilogue(VF))
3102     // If there is an epilogue which must run, there's no edge from the
3103     // middle block to exit blocks  and thus no need to update the immediate
3104     // dominator of the exit blocks.
3105     DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
3106 }
3107 
3108 void InnerLoopVectorizer::createInductionResumeValues(
3109     std::pair<BasicBlock *, Value *> AdditionalBypass) {
3110   assert(((AdditionalBypass.first && AdditionalBypass.second) ||
3111           (!AdditionalBypass.first && !AdditionalBypass.second)) &&
3112          "Inconsistent information about additional bypass.");
3113 
3114   Value *VectorTripCount = getOrCreateVectorTripCount(LoopVectorPreHeader);
3115   assert(VectorTripCount && "Expected valid arguments");
3116   // We are going to resume the execution of the scalar loop.
3117   // Go over all of the induction variables that we found and fix the
3118   // PHIs that are left in the scalar version of the loop.
3119   // The starting values of PHI nodes depend on the counter of the last
3120   // iteration in the vectorized loop.
3121   // If we come from a bypass edge then we need to start from the original
3122   // start value.
3123   Instruction *OldInduction = Legal->getPrimaryInduction();
3124   for (auto &InductionEntry : Legal->getInductionVars()) {
3125     PHINode *OrigPhi = InductionEntry.first;
3126     InductionDescriptor II = InductionEntry.second;
3127 
3128     Value *&EndValue = IVEndValues[OrigPhi];
3129     Value *EndValueFromAdditionalBypass = AdditionalBypass.second;
3130     if (OrigPhi == OldInduction) {
3131       // We know what the end value is.
3132       EndValue = VectorTripCount;
3133     } else {
3134       IRBuilder<> B(LoopVectorPreHeader->getTerminator());
3135 
3136       // Fast-math-flags propagate from the original induction instruction.
3137       if (II.getInductionBinOp() && isa<FPMathOperator>(II.getInductionBinOp()))
3138         B.setFastMathFlags(II.getInductionBinOp()->getFastMathFlags());
3139 
3140       Type *StepType = II.getStep()->getType();
3141       Instruction::CastOps CastOp =
3142           CastInst::getCastOpcode(VectorTripCount, true, StepType, true);
3143       Value *VTC = B.CreateCast(CastOp, VectorTripCount, StepType, "cast.vtc");
3144       Value *Step =
3145           CreateStepValue(II.getStep(), *PSE.getSE(), &*B.GetInsertPoint());
3146       EndValue = emitTransformedIndex(B, VTC, II.getStartValue(), Step, II);
3147       EndValue->setName("ind.end");
3148 
3149       // Compute the end value for the additional bypass (if applicable).
3150       if (AdditionalBypass.first) {
3151         B.SetInsertPoint(&(*AdditionalBypass.first->getFirstInsertionPt()));
3152         CastOp = CastInst::getCastOpcode(AdditionalBypass.second, true,
3153                                          StepType, true);
3154         Value *Step =
3155             CreateStepValue(II.getStep(), *PSE.getSE(), &*B.GetInsertPoint());
3156         VTC =
3157             B.CreateCast(CastOp, AdditionalBypass.second, StepType, "cast.vtc");
3158         EndValueFromAdditionalBypass =
3159             emitTransformedIndex(B, VTC, II.getStartValue(), Step, II);
3160         EndValueFromAdditionalBypass->setName("ind.end");
3161       }
3162     }
3163 
3164     // Create phi nodes to merge from the  backedge-taken check block.
3165     PHINode *BCResumeVal =
3166         PHINode::Create(OrigPhi->getType(), 3, "bc.resume.val",
3167                         LoopScalarPreHeader->getTerminator());
3168     // Copy original phi DL over to the new one.
3169     BCResumeVal->setDebugLoc(OrigPhi->getDebugLoc());
3170 
3171     // The new PHI merges the original incoming value, in case of a bypass,
3172     // or the value at the end of the vectorized loop.
3173     BCResumeVal->addIncoming(EndValue, LoopMiddleBlock);
3174 
3175     // Fix the scalar body counter (PHI node).
3176     // The old induction's phi node in the scalar body needs the truncated
3177     // value.
3178     for (BasicBlock *BB : LoopBypassBlocks)
3179       BCResumeVal->addIncoming(II.getStartValue(), BB);
3180 
3181     if (AdditionalBypass.first)
3182       BCResumeVal->setIncomingValueForBlock(AdditionalBypass.first,
3183                                             EndValueFromAdditionalBypass);
3184 
3185     OrigPhi->setIncomingValueForBlock(LoopScalarPreHeader, BCResumeVal);
3186   }
3187 }
3188 
3189 BasicBlock *InnerLoopVectorizer::completeLoopSkeleton(MDNode *OrigLoopID) {
3190   // The trip counts should be cached by now.
3191   Value *Count = getOrCreateTripCount(LoopVectorPreHeader);
3192   Value *VectorTripCount = getOrCreateVectorTripCount(LoopVectorPreHeader);
3193 
3194   auto *ScalarLatchTerm = OrigLoop->getLoopLatch()->getTerminator();
3195 
3196   // Add a check in the middle block to see if we have completed
3197   // all of the iterations in the first vector loop.  Three cases:
3198   // 1) If we require a scalar epilogue, there is no conditional branch as
3199   //    we unconditionally branch to the scalar preheader.  Do nothing.
3200   // 2) If (N - N%VF) == N, then we *don't* need to run the remainder.
3201   //    Thus if tail is to be folded, we know we don't need to run the
3202   //    remainder and we can use the previous value for the condition (true).
3203   // 3) Otherwise, construct a runtime check.
3204   if (!Cost->requiresScalarEpilogue(VF) && !Cost->foldTailByMasking()) {
3205     Instruction *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
3206                                         Count, VectorTripCount, "cmp.n",
3207                                         LoopMiddleBlock->getTerminator());
3208 
3209     // Here we use the same DebugLoc as the scalar loop latch terminator instead
3210     // of the corresponding compare because they may have ended up with
3211     // different line numbers and we want to avoid awkward line stepping while
3212     // debugging. Eg. if the compare has got a line number inside the loop.
3213     CmpN->setDebugLoc(ScalarLatchTerm->getDebugLoc());
3214     cast<BranchInst>(LoopMiddleBlock->getTerminator())->setCondition(CmpN);
3215   }
3216 
3217 #ifdef EXPENSIVE_CHECKS
3218   assert(DT->verify(DominatorTree::VerificationLevel::Fast));
3219 #endif
3220 
3221   return LoopVectorPreHeader;
3222 }
3223 
3224 std::pair<BasicBlock *, Value *>
3225 InnerLoopVectorizer::createVectorizedLoopSkeleton() {
3226   /*
3227    In this function we generate a new loop. The new loop will contain
3228    the vectorized instructions while the old loop will continue to run the
3229    scalar remainder.
3230 
3231        [ ] <-- loop iteration number check.
3232     /   |
3233    /    v
3234   |    [ ] <-- vector loop bypass (may consist of multiple blocks).
3235   |  /  |
3236   | /   v
3237   ||   [ ]     <-- vector pre header.
3238   |/    |
3239   |     v
3240   |    [  ] \
3241   |    [  ]_|   <-- vector loop (created during VPlan execution).
3242   |     |
3243   |     v
3244   \   -[ ]   <--- middle-block.
3245    \/   |
3246    /\   v
3247    | ->[ ]     <--- new preheader.
3248    |    |
3249  (opt)  v      <-- edge from middle to exit iff epilogue is not required.
3250    |   [ ] \
3251    |   [ ]_|   <-- old scalar loop to handle remainder (scalar epilogue).
3252     \   |
3253      \  v
3254       >[ ]     <-- exit block(s).
3255    ...
3256    */
3257 
3258   // Get the metadata of the original loop before it gets modified.
3259   MDNode *OrigLoopID = OrigLoop->getLoopID();
3260 
3261   // Workaround!  Compute the trip count of the original loop and cache it
3262   // before we start modifying the CFG.  This code has a systemic problem
3263   // wherein it tries to run analysis over partially constructed IR; this is
3264   // wrong, and not simply for SCEV.  The trip count of the original loop
3265   // simply happens to be prone to hitting this in practice.  In theory, we
3266   // can hit the same issue for any SCEV, or ValueTracking query done during
3267   // mutation.  See PR49900.
3268   getOrCreateTripCount(OrigLoop->getLoopPreheader());
3269 
3270   // Create an empty vector loop, and prepare basic blocks for the runtime
3271   // checks.
3272   createVectorLoopSkeleton("");
3273 
3274   // Now, compare the new count to zero. If it is zero skip the vector loop and
3275   // jump to the scalar loop. This check also covers the case where the
3276   // backedge-taken count is uint##_max: adding one to it will overflow leading
3277   // to an incorrect trip count of zero. In this (rare) case we will also jump
3278   // to the scalar loop.
3279   emitIterationCountCheck(LoopScalarPreHeader);
3280 
3281   // Generate the code to check any assumptions that we've made for SCEV
3282   // expressions.
3283   emitSCEVChecks(LoopScalarPreHeader);
3284 
3285   // Generate the code that checks in runtime if arrays overlap. We put the
3286   // checks into a separate block to make the more common case of few elements
3287   // faster.
3288   emitMemRuntimeChecks(LoopScalarPreHeader);
3289 
3290   // Emit phis for the new starting index of the scalar loop.
3291   createInductionResumeValues();
3292 
3293   return {completeLoopSkeleton(OrigLoopID), nullptr};
3294 }
3295 
3296 // Fix up external users of the induction variable. At this point, we are
3297 // in LCSSA form, with all external PHIs that use the IV having one input value,
3298 // coming from the remainder loop. We need those PHIs to also have a correct
3299 // value for the IV when arriving directly from the middle block.
3300 void InnerLoopVectorizer::fixupIVUsers(PHINode *OrigPhi,
3301                                        const InductionDescriptor &II,
3302                                        Value *VectorTripCount, Value *EndValue,
3303                                        BasicBlock *MiddleBlock,
3304                                        BasicBlock *VectorHeader, VPlan &Plan) {
3305   // There are two kinds of external IV usages - those that use the value
3306   // computed in the last iteration (the PHI) and those that use the penultimate
3307   // value (the value that feeds into the phi from the loop latch).
3308   // We allow both, but they, obviously, have different values.
3309 
3310   assert(OrigLoop->getUniqueExitBlock() && "Expected a single exit block");
3311 
3312   DenseMap<Value *, Value *> MissingVals;
3313 
3314   // An external user of the last iteration's value should see the value that
3315   // the remainder loop uses to initialize its own IV.
3316   Value *PostInc = OrigPhi->getIncomingValueForBlock(OrigLoop->getLoopLatch());
3317   for (User *U : PostInc->users()) {
3318     Instruction *UI = cast<Instruction>(U);
3319     if (!OrigLoop->contains(UI)) {
3320       assert(isa<PHINode>(UI) && "Expected LCSSA form");
3321       MissingVals[UI] = EndValue;
3322     }
3323   }
3324 
3325   // An external user of the penultimate value need to see EndValue - Step.
3326   // The simplest way to get this is to recompute it from the constituent SCEVs,
3327   // that is Start + (Step * (CRD - 1)).
3328   for (User *U : OrigPhi->users()) {
3329     auto *UI = cast<Instruction>(U);
3330     if (!OrigLoop->contains(UI)) {
3331       assert(isa<PHINode>(UI) && "Expected LCSSA form");
3332 
3333       IRBuilder<> B(MiddleBlock->getTerminator());
3334 
3335       // Fast-math-flags propagate from the original induction instruction.
3336       if (II.getInductionBinOp() && isa<FPMathOperator>(II.getInductionBinOp()))
3337         B.setFastMathFlags(II.getInductionBinOp()->getFastMathFlags());
3338 
3339       Value *CountMinusOne = B.CreateSub(
3340           VectorTripCount, ConstantInt::get(VectorTripCount->getType(), 1));
3341       Value *CMO =
3342           !II.getStep()->getType()->isIntegerTy()
3343               ? B.CreateCast(Instruction::SIToFP, CountMinusOne,
3344                              II.getStep()->getType())
3345               : B.CreateSExtOrTrunc(CountMinusOne, II.getStep()->getType());
3346       CMO->setName("cast.cmo");
3347 
3348       Value *Step = CreateStepValue(II.getStep(), *PSE.getSE(),
3349                                     VectorHeader->getTerminator());
3350       Value *Escape =
3351           emitTransformedIndex(B, CMO, II.getStartValue(), Step, II);
3352       Escape->setName("ind.escape");
3353       MissingVals[UI] = Escape;
3354     }
3355   }
3356 
3357   for (auto &I : MissingVals) {
3358     PHINode *PHI = cast<PHINode>(I.first);
3359     // One corner case we have to handle is two IVs "chasing" each-other,
3360     // that is %IV2 = phi [...], [ %IV1, %latch ]
3361     // In this case, if IV1 has an external use, we need to avoid adding both
3362     // "last value of IV1" and "penultimate value of IV2". So, verify that we
3363     // don't already have an incoming value for the middle block.
3364     if (PHI->getBasicBlockIndex(MiddleBlock) == -1) {
3365       PHI->addIncoming(I.second, MiddleBlock);
3366       Plan.removeLiveOut(PHI);
3367     }
3368   }
3369 }
3370 
3371 namespace {
3372 
3373 struct CSEDenseMapInfo {
3374   static bool canHandle(const Instruction *I) {
3375     return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
3376            isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
3377   }
3378 
3379   static inline Instruction *getEmptyKey() {
3380     return DenseMapInfo<Instruction *>::getEmptyKey();
3381   }
3382 
3383   static inline Instruction *getTombstoneKey() {
3384     return DenseMapInfo<Instruction *>::getTombstoneKey();
3385   }
3386 
3387   static unsigned getHashValue(const Instruction *I) {
3388     assert(canHandle(I) && "Unknown instruction!");
3389     return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
3390                                                            I->value_op_end()));
3391   }
3392 
3393   static bool isEqual(const Instruction *LHS, const Instruction *RHS) {
3394     if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
3395         LHS == getTombstoneKey() || RHS == getTombstoneKey())
3396       return LHS == RHS;
3397     return LHS->isIdenticalTo(RHS);
3398   }
3399 };
3400 
3401 } // end anonymous namespace
3402 
3403 ///Perform cse of induction variable instructions.
3404 static void cse(BasicBlock *BB) {
3405   // Perform simple cse.
3406   SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
3407   for (Instruction &In : llvm::make_early_inc_range(*BB)) {
3408     if (!CSEDenseMapInfo::canHandle(&In))
3409       continue;
3410 
3411     // Check if we can replace this instruction with any of the
3412     // visited instructions.
3413     if (Instruction *V = CSEMap.lookup(&In)) {
3414       In.replaceAllUsesWith(V);
3415       In.eraseFromParent();
3416       continue;
3417     }
3418 
3419     CSEMap[&In] = &In;
3420   }
3421 }
3422 
3423 InstructionCost
3424 LoopVectorizationCostModel::getVectorCallCost(CallInst *CI, ElementCount VF,
3425                                               bool &NeedToScalarize) const {
3426   Function *F = CI->getCalledFunction();
3427   Type *ScalarRetTy = CI->getType();
3428   SmallVector<Type *, 4> Tys, ScalarTys;
3429   for (auto &ArgOp : CI->args())
3430     ScalarTys.push_back(ArgOp->getType());
3431 
3432   // Estimate cost of scalarized vector call. The source operands are assumed
3433   // to be vectors, so we need to extract individual elements from there,
3434   // execute VF scalar calls, and then gather the result into the vector return
3435   // value.
3436   InstructionCost ScalarCallCost =
3437       TTI.getCallInstrCost(F, ScalarRetTy, ScalarTys, TTI::TCK_RecipThroughput);
3438   if (VF.isScalar())
3439     return ScalarCallCost;
3440 
3441   // Compute corresponding vector type for return value and arguments.
3442   Type *RetTy = ToVectorTy(ScalarRetTy, VF);
3443   for (Type *ScalarTy : ScalarTys)
3444     Tys.push_back(ToVectorTy(ScalarTy, VF));
3445 
3446   // Compute costs of unpacking argument values for the scalar calls and
3447   // packing the return values to a vector.
3448   InstructionCost ScalarizationCost = getScalarizationOverhead(CI, VF);
3449 
3450   InstructionCost Cost =
3451       ScalarCallCost * VF.getKnownMinValue() + ScalarizationCost;
3452 
3453   // If we can't emit a vector call for this function, then the currently found
3454   // cost is the cost we need to return.
3455   NeedToScalarize = true;
3456   VFShape Shape = VFShape::get(*CI, VF, false /*HasGlobalPred*/);
3457   Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
3458 
3459   if (!TLI || CI->isNoBuiltin() || !VecFunc)
3460     return Cost;
3461 
3462   // If the corresponding vector cost is cheaper, return its cost.
3463   InstructionCost VectorCallCost =
3464       TTI.getCallInstrCost(nullptr, RetTy, Tys, TTI::TCK_RecipThroughput);
3465   if (VectorCallCost < Cost) {
3466     NeedToScalarize = false;
3467     Cost = VectorCallCost;
3468   }
3469   return Cost;
3470 }
3471 
3472 static Type *MaybeVectorizeType(Type *Elt, ElementCount VF) {
3473   if (VF.isScalar() || (!Elt->isIntOrPtrTy() && !Elt->isFloatingPointTy()))
3474     return Elt;
3475   return VectorType::get(Elt, VF);
3476 }
3477 
3478 InstructionCost
3479 LoopVectorizationCostModel::getVectorIntrinsicCost(CallInst *CI,
3480                                                    ElementCount VF) const {
3481   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
3482   assert(ID && "Expected intrinsic call!");
3483   Type *RetTy = MaybeVectorizeType(CI->getType(), VF);
3484   FastMathFlags FMF;
3485   if (auto *FPMO = dyn_cast<FPMathOperator>(CI))
3486     FMF = FPMO->getFastMathFlags();
3487 
3488   SmallVector<const Value *> Arguments(CI->args());
3489   FunctionType *FTy = CI->getCalledFunction()->getFunctionType();
3490   SmallVector<Type *> ParamTys;
3491   std::transform(FTy->param_begin(), FTy->param_end(),
3492                  std::back_inserter(ParamTys),
3493                  [&](Type *Ty) { return MaybeVectorizeType(Ty, VF); });
3494 
3495   IntrinsicCostAttributes CostAttrs(ID, RetTy, Arguments, ParamTys, FMF,
3496                                     dyn_cast<IntrinsicInst>(CI));
3497   return TTI.getIntrinsicInstrCost(CostAttrs,
3498                                    TargetTransformInfo::TCK_RecipThroughput);
3499 }
3500 
3501 static Type *smallestIntegerVectorType(Type *T1, Type *T2) {
3502   auto *I1 = cast<IntegerType>(cast<VectorType>(T1)->getElementType());
3503   auto *I2 = cast<IntegerType>(cast<VectorType>(T2)->getElementType());
3504   return I1->getBitWidth() < I2->getBitWidth() ? T1 : T2;
3505 }
3506 
3507 static Type *largestIntegerVectorType(Type *T1, Type *T2) {
3508   auto *I1 = cast<IntegerType>(cast<VectorType>(T1)->getElementType());
3509   auto *I2 = cast<IntegerType>(cast<VectorType>(T2)->getElementType());
3510   return I1->getBitWidth() > I2->getBitWidth() ? T1 : T2;
3511 }
3512 
3513 void InnerLoopVectorizer::truncateToMinimalBitwidths(VPTransformState &State) {
3514   // For every instruction `I` in MinBWs, truncate the operands, create a
3515   // truncated version of `I` and reextend its result. InstCombine runs
3516   // later and will remove any ext/trunc pairs.
3517   SmallPtrSet<Value *, 4> Erased;
3518   for (const auto &KV : Cost->getMinimalBitwidths()) {
3519     // If the value wasn't vectorized, we must maintain the original scalar
3520     // type. The absence of the value from State indicates that it
3521     // wasn't vectorized.
3522     // FIXME: Should not rely on getVPValue at this point.
3523     VPValue *Def = State.Plan->getVPValue(KV.first, true);
3524     if (!State.hasAnyVectorValue(Def))
3525       continue;
3526     for (unsigned Part = 0; Part < UF; ++Part) {
3527       Value *I = State.get(Def, Part);
3528       if (Erased.count(I) || I->use_empty() || !isa<Instruction>(I))
3529         continue;
3530       Type *OriginalTy = I->getType();
3531       Type *ScalarTruncatedTy =
3532           IntegerType::get(OriginalTy->getContext(), KV.second);
3533       auto *TruncatedTy = VectorType::get(
3534           ScalarTruncatedTy, cast<VectorType>(OriginalTy)->getElementCount());
3535       if (TruncatedTy == OriginalTy)
3536         continue;
3537 
3538       IRBuilder<> B(cast<Instruction>(I));
3539       auto ShrinkOperand = [&](Value *V) -> Value * {
3540         if (auto *ZI = dyn_cast<ZExtInst>(V))
3541           if (ZI->getSrcTy() == TruncatedTy)
3542             return ZI->getOperand(0);
3543         return B.CreateZExtOrTrunc(V, TruncatedTy);
3544       };
3545 
3546       // The actual instruction modification depends on the instruction type,
3547       // unfortunately.
3548       Value *NewI = nullptr;
3549       if (auto *BO = dyn_cast<BinaryOperator>(I)) {
3550         NewI = B.CreateBinOp(BO->getOpcode(), ShrinkOperand(BO->getOperand(0)),
3551                              ShrinkOperand(BO->getOperand(1)));
3552 
3553         // Any wrapping introduced by shrinking this operation shouldn't be
3554         // considered undefined behavior. So, we can't unconditionally copy
3555         // arithmetic wrapping flags to NewI.
3556         cast<BinaryOperator>(NewI)->copyIRFlags(I, /*IncludeWrapFlags=*/false);
3557       } else if (auto *CI = dyn_cast<ICmpInst>(I)) {
3558         NewI =
3559             B.CreateICmp(CI->getPredicate(), ShrinkOperand(CI->getOperand(0)),
3560                          ShrinkOperand(CI->getOperand(1)));
3561       } else if (auto *SI = dyn_cast<SelectInst>(I)) {
3562         NewI = B.CreateSelect(SI->getCondition(),
3563                               ShrinkOperand(SI->getTrueValue()),
3564                               ShrinkOperand(SI->getFalseValue()));
3565       } else if (auto *CI = dyn_cast<CastInst>(I)) {
3566         switch (CI->getOpcode()) {
3567         default:
3568           llvm_unreachable("Unhandled cast!");
3569         case Instruction::Trunc:
3570           NewI = ShrinkOperand(CI->getOperand(0));
3571           break;
3572         case Instruction::SExt:
3573           NewI = B.CreateSExtOrTrunc(
3574               CI->getOperand(0),
3575               smallestIntegerVectorType(OriginalTy, TruncatedTy));
3576           break;
3577         case Instruction::ZExt:
3578           NewI = B.CreateZExtOrTrunc(
3579               CI->getOperand(0),
3580               smallestIntegerVectorType(OriginalTy, TruncatedTy));
3581           break;
3582         }
3583       } else if (auto *SI = dyn_cast<ShuffleVectorInst>(I)) {
3584         auto Elements0 =
3585             cast<VectorType>(SI->getOperand(0)->getType())->getElementCount();
3586         auto *O0 = B.CreateZExtOrTrunc(
3587             SI->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements0));
3588         auto Elements1 =
3589             cast<VectorType>(SI->getOperand(1)->getType())->getElementCount();
3590         auto *O1 = B.CreateZExtOrTrunc(
3591             SI->getOperand(1), VectorType::get(ScalarTruncatedTy, Elements1));
3592 
3593         NewI = B.CreateShuffleVector(O0, O1, SI->getShuffleMask());
3594       } else if (isa<LoadInst>(I) || isa<PHINode>(I)) {
3595         // Don't do anything with the operands, just extend the result.
3596         continue;
3597       } else if (auto *IE = dyn_cast<InsertElementInst>(I)) {
3598         auto Elements =
3599             cast<VectorType>(IE->getOperand(0)->getType())->getElementCount();
3600         auto *O0 = B.CreateZExtOrTrunc(
3601             IE->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements));
3602         auto *O1 = B.CreateZExtOrTrunc(IE->getOperand(1), ScalarTruncatedTy);
3603         NewI = B.CreateInsertElement(O0, O1, IE->getOperand(2));
3604       } else if (auto *EE = dyn_cast<ExtractElementInst>(I)) {
3605         auto Elements =
3606             cast<VectorType>(EE->getOperand(0)->getType())->getElementCount();
3607         auto *O0 = B.CreateZExtOrTrunc(
3608             EE->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements));
3609         NewI = B.CreateExtractElement(O0, EE->getOperand(2));
3610       } else {
3611         // If we don't know what to do, be conservative and don't do anything.
3612         continue;
3613       }
3614 
3615       // Lastly, extend the result.
3616       NewI->takeName(cast<Instruction>(I));
3617       Value *Res = B.CreateZExtOrTrunc(NewI, OriginalTy);
3618       I->replaceAllUsesWith(Res);
3619       cast<Instruction>(I)->eraseFromParent();
3620       Erased.insert(I);
3621       State.reset(Def, Res, Part);
3622     }
3623   }
3624 
3625   // We'll have created a bunch of ZExts that are now parentless. Clean up.
3626   for (const auto &KV : Cost->getMinimalBitwidths()) {
3627     // If the value wasn't vectorized, we must maintain the original scalar
3628     // type. The absence of the value from State indicates that it
3629     // wasn't vectorized.
3630     // FIXME: Should not rely on getVPValue at this point.
3631     VPValue *Def = State.Plan->getVPValue(KV.first, true);
3632     if (!State.hasAnyVectorValue(Def))
3633       continue;
3634     for (unsigned Part = 0; Part < UF; ++Part) {
3635       Value *I = State.get(Def, Part);
3636       ZExtInst *Inst = dyn_cast<ZExtInst>(I);
3637       if (Inst && Inst->use_empty()) {
3638         Value *NewI = Inst->getOperand(0);
3639         Inst->eraseFromParent();
3640         State.reset(Def, NewI, Part);
3641       }
3642     }
3643   }
3644 }
3645 
3646 void InnerLoopVectorizer::fixVectorizedLoop(VPTransformState &State,
3647                                             VPlan &Plan) {
3648   // Insert truncates and extends for any truncated instructions as hints to
3649   // InstCombine.
3650   if (VF.isVector())
3651     truncateToMinimalBitwidths(State);
3652 
3653   // Fix widened non-induction PHIs by setting up the PHI operands.
3654   if (EnableVPlanNativePath)
3655     fixNonInductionPHIs(Plan, State);
3656 
3657   // At this point every instruction in the original loop is widened to a
3658   // vector form. Now we need to fix the recurrences in the loop. These PHI
3659   // nodes are currently empty because we did not want to introduce cycles.
3660   // This is the second stage of vectorizing recurrences.
3661   fixCrossIterationPHIs(State);
3662 
3663   // Forget the original basic block.
3664   PSE.getSE()->forgetLoop(OrigLoop);
3665 
3666   VPBasicBlock *LatchVPBB = Plan.getVectorLoopRegion()->getExitingBasicBlock();
3667   Loop *VectorLoop = LI->getLoopFor(State.CFG.VPBB2IRBB[LatchVPBB]);
3668   if (Cost->requiresScalarEpilogue(VF)) {
3669     // No edge from the middle block to the unique exit block has been inserted
3670     // and there is nothing to fix from vector loop; phis should have incoming
3671     // from scalar loop only.
3672     Plan.clearLiveOuts();
3673   } else {
3674     // If we inserted an edge from the middle block to the unique exit block,
3675     // update uses outside the loop (phis) to account for the newly inserted
3676     // edge.
3677 
3678     // Fix-up external users of the induction variables.
3679     for (auto &Entry : Legal->getInductionVars())
3680       fixupIVUsers(Entry.first, Entry.second,
3681                    getOrCreateVectorTripCount(VectorLoop->getLoopPreheader()),
3682                    IVEndValues[Entry.first], LoopMiddleBlock,
3683                    VectorLoop->getHeader(), Plan);
3684   }
3685 
3686   // Fix LCSSA phis not already fixed earlier. Extracts may need to be generated
3687   // in the exit block, so update the builder.
3688   State.Builder.SetInsertPoint(State.CFG.ExitBB->getFirstNonPHI());
3689   for (auto &KV : Plan.getLiveOuts())
3690     KV.second->fixPhi(Plan, State);
3691 
3692   for (Instruction *PI : PredicatedInstructions)
3693     sinkScalarOperands(&*PI);
3694 
3695   // Remove redundant induction instructions.
3696   cse(VectorLoop->getHeader());
3697 
3698   // Set/update profile weights for the vector and remainder loops as original
3699   // loop iterations are now distributed among them. Note that original loop
3700   // represented by LoopScalarBody becomes remainder loop after vectorization.
3701   //
3702   // For cases like foldTailByMasking() and requiresScalarEpiloque() we may
3703   // end up getting slightly roughened result but that should be OK since
3704   // profile is not inherently precise anyway. Note also possible bypass of
3705   // vector code caused by legality checks is ignored, assigning all the weight
3706   // to the vector loop, optimistically.
3707   //
3708   // For scalable vectorization we can't know at compile time how many iterations
3709   // of the loop are handled in one vector iteration, so instead assume a pessimistic
3710   // vscale of '1'.
3711   setProfileInfoAfterUnrolling(LI->getLoopFor(LoopScalarBody), VectorLoop,
3712                                LI->getLoopFor(LoopScalarBody),
3713                                VF.getKnownMinValue() * UF);
3714 }
3715 
3716 void InnerLoopVectorizer::fixCrossIterationPHIs(VPTransformState &State) {
3717   // In order to support recurrences we need to be able to vectorize Phi nodes.
3718   // Phi nodes have cycles, so we need to vectorize them in two stages. This is
3719   // stage #2: We now need to fix the recurrences by adding incoming edges to
3720   // the currently empty PHI nodes. At this point every instruction in the
3721   // original loop is widened to a vector form so we can use them to construct
3722   // the incoming edges.
3723   VPBasicBlock *Header =
3724       State.Plan->getVectorLoopRegion()->getEntryBasicBlock();
3725   for (VPRecipeBase &R : Header->phis()) {
3726     if (auto *ReductionPhi = dyn_cast<VPReductionPHIRecipe>(&R))
3727       fixReduction(ReductionPhi, State);
3728     else if (auto *FOR = dyn_cast<VPFirstOrderRecurrencePHIRecipe>(&R))
3729       fixFirstOrderRecurrence(FOR, State);
3730   }
3731 }
3732 
3733 void InnerLoopVectorizer::fixFirstOrderRecurrence(
3734     VPFirstOrderRecurrencePHIRecipe *PhiR, VPTransformState &State) {
3735   // This is the second phase of vectorizing first-order recurrences. An
3736   // overview of the transformation is described below. Suppose we have the
3737   // following loop.
3738   //
3739   //   for (int i = 0; i < n; ++i)
3740   //     b[i] = a[i] - a[i - 1];
3741   //
3742   // There is a first-order recurrence on "a". For this loop, the shorthand
3743   // scalar IR looks like:
3744   //
3745   //   scalar.ph:
3746   //     s_init = a[-1]
3747   //     br scalar.body
3748   //
3749   //   scalar.body:
3750   //     i = phi [0, scalar.ph], [i+1, scalar.body]
3751   //     s1 = phi [s_init, scalar.ph], [s2, scalar.body]
3752   //     s2 = a[i]
3753   //     b[i] = s2 - s1
3754   //     br cond, scalar.body, ...
3755   //
3756   // In this example, s1 is a recurrence because it's value depends on the
3757   // previous iteration. In the first phase of vectorization, we created a
3758   // vector phi v1 for s1. We now complete the vectorization and produce the
3759   // shorthand vector IR shown below (for VF = 4, UF = 1).
3760   //
3761   //   vector.ph:
3762   //     v_init = vector(..., ..., ..., a[-1])
3763   //     br vector.body
3764   //
3765   //   vector.body
3766   //     i = phi [0, vector.ph], [i+4, vector.body]
3767   //     v1 = phi [v_init, vector.ph], [v2, vector.body]
3768   //     v2 = a[i, i+1, i+2, i+3];
3769   //     v3 = vector(v1(3), v2(0, 1, 2))
3770   //     b[i, i+1, i+2, i+3] = v2 - v3
3771   //     br cond, vector.body, middle.block
3772   //
3773   //   middle.block:
3774   //     x = v2(3)
3775   //     br scalar.ph
3776   //
3777   //   scalar.ph:
3778   //     s_init = phi [x, middle.block], [a[-1], otherwise]
3779   //     br scalar.body
3780   //
3781   // After execution completes the vector loop, we extract the next value of
3782   // the recurrence (x) to use as the initial value in the scalar loop.
3783 
3784   // Extract the last vector element in the middle block. This will be the
3785   // initial value for the recurrence when jumping to the scalar loop.
3786   VPValue *PreviousDef = PhiR->getBackedgeValue();
3787   Value *Incoming = State.get(PreviousDef, UF - 1);
3788   auto *ExtractForScalar = Incoming;
3789   auto *IdxTy = Builder.getInt32Ty();
3790   if (VF.isVector()) {
3791     auto *One = ConstantInt::get(IdxTy, 1);
3792     Builder.SetInsertPoint(LoopMiddleBlock->getTerminator());
3793     auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, VF);
3794     auto *LastIdx = Builder.CreateSub(RuntimeVF, One);
3795     ExtractForScalar = Builder.CreateExtractElement(ExtractForScalar, LastIdx,
3796                                                     "vector.recur.extract");
3797   }
3798   // Extract the second last element in the middle block if the
3799   // Phi is used outside the loop. We need to extract the phi itself
3800   // and not the last element (the phi update in the current iteration). This
3801   // will be the value when jumping to the exit block from the LoopMiddleBlock,
3802   // when the scalar loop is not run at all.
3803   Value *ExtractForPhiUsedOutsideLoop = nullptr;
3804   if (VF.isVector()) {
3805     auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, VF);
3806     auto *Idx = Builder.CreateSub(RuntimeVF, ConstantInt::get(IdxTy, 2));
3807     ExtractForPhiUsedOutsideLoop = Builder.CreateExtractElement(
3808         Incoming, Idx, "vector.recur.extract.for.phi");
3809   } else if (UF > 1)
3810     // When loop is unrolled without vectorizing, initialize
3811     // ExtractForPhiUsedOutsideLoop with the value just prior to unrolled value
3812     // of `Incoming`. This is analogous to the vectorized case above: extracting
3813     // the second last element when VF > 1.
3814     ExtractForPhiUsedOutsideLoop = State.get(PreviousDef, UF - 2);
3815 
3816   // Fix the initial value of the original recurrence in the scalar loop.
3817   Builder.SetInsertPoint(&*LoopScalarPreHeader->begin());
3818   PHINode *Phi = cast<PHINode>(PhiR->getUnderlyingValue());
3819   auto *Start = Builder.CreatePHI(Phi->getType(), 2, "scalar.recur.init");
3820   auto *ScalarInit = PhiR->getStartValue()->getLiveInIRValue();
3821   for (auto *BB : predecessors(LoopScalarPreHeader)) {
3822     auto *Incoming = BB == LoopMiddleBlock ? ExtractForScalar : ScalarInit;
3823     Start->addIncoming(Incoming, BB);
3824   }
3825 
3826   Phi->setIncomingValueForBlock(LoopScalarPreHeader, Start);
3827   Phi->setName("scalar.recur");
3828 
3829   // Finally, fix users of the recurrence outside the loop. The users will need
3830   // either the last value of the scalar recurrence or the last value of the
3831   // vector recurrence we extracted in the middle block. Since the loop is in
3832   // LCSSA form, we just need to find all the phi nodes for the original scalar
3833   // recurrence in the exit block, and then add an edge for the middle block.
3834   // Note that LCSSA does not imply single entry when the original scalar loop
3835   // had multiple exiting edges (as we always run the last iteration in the
3836   // scalar epilogue); in that case, there is no edge from middle to exit and
3837   // and thus no phis which needed updated.
3838   if (!Cost->requiresScalarEpilogue(VF))
3839     for (PHINode &LCSSAPhi : LoopExitBlock->phis())
3840       if (llvm::is_contained(LCSSAPhi.incoming_values(), Phi)) {
3841         LCSSAPhi.addIncoming(ExtractForPhiUsedOutsideLoop, LoopMiddleBlock);
3842         State.Plan->removeLiveOut(&LCSSAPhi);
3843       }
3844 }
3845 
3846 void InnerLoopVectorizer::fixReduction(VPReductionPHIRecipe *PhiR,
3847                                        VPTransformState &State) {
3848   PHINode *OrigPhi = cast<PHINode>(PhiR->getUnderlyingValue());
3849   // Get it's reduction variable descriptor.
3850   assert(Legal->isReductionVariable(OrigPhi) &&
3851          "Unable to find the reduction variable");
3852   const RecurrenceDescriptor &RdxDesc = PhiR->getRecurrenceDescriptor();
3853 
3854   RecurKind RK = RdxDesc.getRecurrenceKind();
3855   TrackingVH<Value> ReductionStartValue = RdxDesc.getRecurrenceStartValue();
3856   Instruction *LoopExitInst = RdxDesc.getLoopExitInstr();
3857   State.setDebugLocFromInst(ReductionStartValue);
3858 
3859   VPValue *LoopExitInstDef = PhiR->getBackedgeValue();
3860   // This is the vector-clone of the value that leaves the loop.
3861   Type *VecTy = State.get(LoopExitInstDef, 0)->getType();
3862 
3863   // Wrap flags are in general invalid after vectorization, clear them.
3864   clearReductionWrapFlags(PhiR, State);
3865 
3866   // Before each round, move the insertion point right between
3867   // the PHIs and the values we are going to write.
3868   // This allows us to write both PHINodes and the extractelement
3869   // instructions.
3870   Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
3871 
3872   State.setDebugLocFromInst(LoopExitInst);
3873 
3874   Type *PhiTy = OrigPhi->getType();
3875 
3876   VPBasicBlock *LatchVPBB =
3877       PhiR->getParent()->getEnclosingLoopRegion()->getExitingBasicBlock();
3878   BasicBlock *VectorLoopLatch = State.CFG.VPBB2IRBB[LatchVPBB];
3879   // If tail is folded by masking, the vector value to leave the loop should be
3880   // a Select choosing between the vectorized LoopExitInst and vectorized Phi,
3881   // instead of the former. For an inloop reduction the reduction will already
3882   // be predicated, and does not need to be handled here.
3883   if (Cost->foldTailByMasking() && !PhiR->isInLoop()) {
3884     for (unsigned Part = 0; Part < UF; ++Part) {
3885       Value *VecLoopExitInst = State.get(LoopExitInstDef, Part);
3886       SelectInst *Sel = nullptr;
3887       for (User *U : VecLoopExitInst->users()) {
3888         if (isa<SelectInst>(U)) {
3889           assert(!Sel && "Reduction exit feeding two selects");
3890           Sel = cast<SelectInst>(U);
3891         } else
3892           assert(isa<PHINode>(U) && "Reduction exit must feed Phi's or select");
3893       }
3894       assert(Sel && "Reduction exit feeds no select");
3895       State.reset(LoopExitInstDef, Sel, Part);
3896 
3897       if (isa<FPMathOperator>(Sel))
3898         Sel->setFastMathFlags(RdxDesc.getFastMathFlags());
3899 
3900       // If the target can create a predicated operator for the reduction at no
3901       // extra cost in the loop (for example a predicated vadd), it can be
3902       // cheaper for the select to remain in the loop than be sunk out of it,
3903       // and so use the select value for the phi instead of the old
3904       // LoopExitValue.
3905       if (PreferPredicatedReductionSelect ||
3906           TTI->preferPredicatedReductionSelect(
3907               RdxDesc.getOpcode(), PhiTy,
3908               TargetTransformInfo::ReductionFlags())) {
3909         auto *VecRdxPhi =
3910             cast<PHINode>(State.get(PhiR, Part));
3911         VecRdxPhi->setIncomingValueForBlock(VectorLoopLatch, Sel);
3912       }
3913     }
3914   }
3915 
3916   // If the vector reduction can be performed in a smaller type, we truncate
3917   // then extend the loop exit value to enable InstCombine to evaluate the
3918   // entire expression in the smaller type.
3919   if (VF.isVector() && PhiTy != RdxDesc.getRecurrenceType()) {
3920     assert(!PhiR->isInLoop() && "Unexpected truncated inloop reduction!");
3921     Type *RdxVecTy = VectorType::get(RdxDesc.getRecurrenceType(), VF);
3922     Builder.SetInsertPoint(VectorLoopLatch->getTerminator());
3923     VectorParts RdxParts(UF);
3924     for (unsigned Part = 0; Part < UF; ++Part) {
3925       RdxParts[Part] = State.get(LoopExitInstDef, Part);
3926       Value *Trunc = Builder.CreateTrunc(RdxParts[Part], RdxVecTy);
3927       Value *Extnd = RdxDesc.isSigned() ? Builder.CreateSExt(Trunc, VecTy)
3928                                         : Builder.CreateZExt(Trunc, VecTy);
3929       for (User *U : llvm::make_early_inc_range(RdxParts[Part]->users()))
3930         if (U != Trunc) {
3931           U->replaceUsesOfWith(RdxParts[Part], Extnd);
3932           RdxParts[Part] = Extnd;
3933         }
3934     }
3935     Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
3936     for (unsigned Part = 0; Part < UF; ++Part) {
3937       RdxParts[Part] = Builder.CreateTrunc(RdxParts[Part], RdxVecTy);
3938       State.reset(LoopExitInstDef, RdxParts[Part], Part);
3939     }
3940   }
3941 
3942   // Reduce all of the unrolled parts into a single vector.
3943   Value *ReducedPartRdx = State.get(LoopExitInstDef, 0);
3944   unsigned Op = RecurrenceDescriptor::getOpcode(RK);
3945 
3946   // The middle block terminator has already been assigned a DebugLoc here (the
3947   // OrigLoop's single latch terminator). We want the whole middle block to
3948   // appear to execute on this line because: (a) it is all compiler generated,
3949   // (b) these instructions are always executed after evaluating the latch
3950   // conditional branch, and (c) other passes may add new predecessors which
3951   // terminate on this line. This is the easiest way to ensure we don't
3952   // accidentally cause an extra step back into the loop while debugging.
3953   State.setDebugLocFromInst(LoopMiddleBlock->getTerminator());
3954   if (PhiR->isOrdered())
3955     ReducedPartRdx = State.get(LoopExitInstDef, UF - 1);
3956   else {
3957     // Floating-point operations should have some FMF to enable the reduction.
3958     IRBuilderBase::FastMathFlagGuard FMFG(Builder);
3959     Builder.setFastMathFlags(RdxDesc.getFastMathFlags());
3960     for (unsigned Part = 1; Part < UF; ++Part) {
3961       Value *RdxPart = State.get(LoopExitInstDef, Part);
3962       if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
3963         ReducedPartRdx = Builder.CreateBinOp(
3964             (Instruction::BinaryOps)Op, RdxPart, ReducedPartRdx, "bin.rdx");
3965       } else if (RecurrenceDescriptor::isSelectCmpRecurrenceKind(RK))
3966         ReducedPartRdx = createSelectCmpOp(Builder, ReductionStartValue, RK,
3967                                            ReducedPartRdx, RdxPart);
3968       else
3969         ReducedPartRdx = createMinMaxOp(Builder, RK, ReducedPartRdx, RdxPart);
3970     }
3971   }
3972 
3973   // Create the reduction after the loop. Note that inloop reductions create the
3974   // target reduction in the loop using a Reduction recipe.
3975   if (VF.isVector() && !PhiR->isInLoop()) {
3976     ReducedPartRdx =
3977         createTargetReduction(Builder, TTI, RdxDesc, ReducedPartRdx, OrigPhi);
3978     // If the reduction can be performed in a smaller type, we need to extend
3979     // the reduction to the wider type before we branch to the original loop.
3980     if (PhiTy != RdxDesc.getRecurrenceType())
3981       ReducedPartRdx = RdxDesc.isSigned()
3982                            ? Builder.CreateSExt(ReducedPartRdx, PhiTy)
3983                            : Builder.CreateZExt(ReducedPartRdx, PhiTy);
3984   }
3985 
3986   PHINode *ResumePhi =
3987       dyn_cast<PHINode>(PhiR->getStartValue()->getUnderlyingValue());
3988 
3989   // Create a phi node that merges control-flow from the backedge-taken check
3990   // block and the middle block.
3991   PHINode *BCBlockPhi = PHINode::Create(PhiTy, 2, "bc.merge.rdx",
3992                                         LoopScalarPreHeader->getTerminator());
3993 
3994   // If we are fixing reductions in the epilogue loop then we should already
3995   // have created a bc.merge.rdx Phi after the main vector body. Ensure that
3996   // we carry over the incoming values correctly.
3997   for (auto *Incoming : predecessors(LoopScalarPreHeader)) {
3998     if (Incoming == LoopMiddleBlock)
3999       BCBlockPhi->addIncoming(ReducedPartRdx, Incoming);
4000     else if (ResumePhi && llvm::is_contained(ResumePhi->blocks(), Incoming))
4001       BCBlockPhi->addIncoming(ResumePhi->getIncomingValueForBlock(Incoming),
4002                               Incoming);
4003     else
4004       BCBlockPhi->addIncoming(ReductionStartValue, Incoming);
4005   }
4006 
4007   // Set the resume value for this reduction
4008   ReductionResumeValues.insert({&RdxDesc, BCBlockPhi});
4009 
4010   // If there were stores of the reduction value to a uniform memory address
4011   // inside the loop, create the final store here.
4012   if (StoreInst *SI = RdxDesc.IntermediateStore) {
4013     StoreInst *NewSI =
4014         Builder.CreateStore(ReducedPartRdx, SI->getPointerOperand());
4015     propagateMetadata(NewSI, SI);
4016 
4017     // If the reduction value is used in other places,
4018     // then let the code below create PHI's for that.
4019   }
4020 
4021   // Now, we need to fix the users of the reduction variable
4022   // inside and outside of the scalar remainder loop.
4023 
4024   // We know that the loop is in LCSSA form. We need to update the PHI nodes
4025   // in the exit blocks.  See comment on analogous loop in
4026   // fixFirstOrderRecurrence for a more complete explaination of the logic.
4027   if (!Cost->requiresScalarEpilogue(VF))
4028     for (PHINode &LCSSAPhi : LoopExitBlock->phis())
4029       if (llvm::is_contained(LCSSAPhi.incoming_values(), LoopExitInst)) {
4030         LCSSAPhi.addIncoming(ReducedPartRdx, LoopMiddleBlock);
4031         State.Plan->removeLiveOut(&LCSSAPhi);
4032       }
4033 
4034   // Fix the scalar loop reduction variable with the incoming reduction sum
4035   // from the vector body and from the backedge value.
4036   int IncomingEdgeBlockIdx =
4037       OrigPhi->getBasicBlockIndex(OrigLoop->getLoopLatch());
4038   assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
4039   // Pick the other block.
4040   int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
4041   OrigPhi->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi);
4042   OrigPhi->setIncomingValue(IncomingEdgeBlockIdx, LoopExitInst);
4043 }
4044 
4045 void InnerLoopVectorizer::clearReductionWrapFlags(VPReductionPHIRecipe *PhiR,
4046                                                   VPTransformState &State) {
4047   const RecurrenceDescriptor &RdxDesc = PhiR->getRecurrenceDescriptor();
4048   RecurKind RK = RdxDesc.getRecurrenceKind();
4049   if (RK != RecurKind::Add && RK != RecurKind::Mul)
4050     return;
4051 
4052   SmallVector<VPValue *, 8> Worklist;
4053   SmallPtrSet<VPValue *, 8> Visited;
4054   Worklist.push_back(PhiR);
4055   Visited.insert(PhiR);
4056 
4057   while (!Worklist.empty()) {
4058     VPValue *Cur = Worklist.pop_back_val();
4059     for (unsigned Part = 0; Part < UF; ++Part) {
4060       Value *V = State.get(Cur, Part);
4061       if (!isa<OverflowingBinaryOperator>(V))
4062         break;
4063       cast<Instruction>(V)->dropPoisonGeneratingFlags();
4064       }
4065 
4066       for (VPUser *U : Cur->users()) {
4067         auto *UserRecipe = dyn_cast<VPRecipeBase>(U);
4068         if (!UserRecipe)
4069           continue;
4070         for (VPValue *V : UserRecipe->definedValues())
4071           if (Visited.insert(V).second)
4072             Worklist.push_back(V);
4073       }
4074   }
4075 }
4076 
4077 void InnerLoopVectorizer::sinkScalarOperands(Instruction *PredInst) {
4078   // The basic block and loop containing the predicated instruction.
4079   auto *PredBB = PredInst->getParent();
4080   auto *VectorLoop = LI->getLoopFor(PredBB);
4081 
4082   // Initialize a worklist with the operands of the predicated instruction.
4083   SetVector<Value *> Worklist(PredInst->op_begin(), PredInst->op_end());
4084 
4085   // Holds instructions that we need to analyze again. An instruction may be
4086   // reanalyzed if we don't yet know if we can sink it or not.
4087   SmallVector<Instruction *, 8> InstsToReanalyze;
4088 
4089   // Returns true if a given use occurs in the predicated block. Phi nodes use
4090   // their operands in their corresponding predecessor blocks.
4091   auto isBlockOfUsePredicated = [&](Use &U) -> bool {
4092     auto *I = cast<Instruction>(U.getUser());
4093     BasicBlock *BB = I->getParent();
4094     if (auto *Phi = dyn_cast<PHINode>(I))
4095       BB = Phi->getIncomingBlock(
4096           PHINode::getIncomingValueNumForOperand(U.getOperandNo()));
4097     return BB == PredBB;
4098   };
4099 
4100   // Iteratively sink the scalarized operands of the predicated instruction
4101   // into the block we created for it. When an instruction is sunk, it's
4102   // operands are then added to the worklist. The algorithm ends after one pass
4103   // through the worklist doesn't sink a single instruction.
4104   bool Changed;
4105   do {
4106     // Add the instructions that need to be reanalyzed to the worklist, and
4107     // reset the changed indicator.
4108     Worklist.insert(InstsToReanalyze.begin(), InstsToReanalyze.end());
4109     InstsToReanalyze.clear();
4110     Changed = false;
4111 
4112     while (!Worklist.empty()) {
4113       auto *I = dyn_cast<Instruction>(Worklist.pop_back_val());
4114 
4115       // We can't sink an instruction if it is a phi node, is not in the loop,
4116       // or may have side effects.
4117       if (!I || isa<PHINode>(I) || !VectorLoop->contains(I) ||
4118           I->mayHaveSideEffects())
4119         continue;
4120 
4121       // If the instruction is already in PredBB, check if we can sink its
4122       // operands. In that case, VPlan's sinkScalarOperands() succeeded in
4123       // sinking the scalar instruction I, hence it appears in PredBB; but it
4124       // may have failed to sink I's operands (recursively), which we try
4125       // (again) here.
4126       if (I->getParent() == PredBB) {
4127         Worklist.insert(I->op_begin(), I->op_end());
4128         continue;
4129       }
4130 
4131       // It's legal to sink the instruction if all its uses occur in the
4132       // predicated block. Otherwise, there's nothing to do yet, and we may
4133       // need to reanalyze the instruction.
4134       if (!llvm::all_of(I->uses(), isBlockOfUsePredicated)) {
4135         InstsToReanalyze.push_back(I);
4136         continue;
4137       }
4138 
4139       // Move the instruction to the beginning of the predicated block, and add
4140       // it's operands to the worklist.
4141       I->moveBefore(&*PredBB->getFirstInsertionPt());
4142       Worklist.insert(I->op_begin(), I->op_end());
4143 
4144       // The sinking may have enabled other instructions to be sunk, so we will
4145       // need to iterate.
4146       Changed = true;
4147     }
4148   } while (Changed);
4149 }
4150 
4151 void InnerLoopVectorizer::fixNonInductionPHIs(VPlan &Plan,
4152                                               VPTransformState &State) {
4153   auto Iter = depth_first(
4154       VPBlockRecursiveTraversalWrapper<VPBlockBase *>(Plan.getEntry()));
4155   for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(Iter)) {
4156     for (VPRecipeBase &P : VPBB->phis()) {
4157       VPWidenPHIRecipe *VPPhi = dyn_cast<VPWidenPHIRecipe>(&P);
4158       if (!VPPhi)
4159         continue;
4160       PHINode *NewPhi = cast<PHINode>(State.get(VPPhi, 0));
4161       // Make sure the builder has a valid insert point.
4162       Builder.SetInsertPoint(NewPhi);
4163       for (unsigned i = 0; i < VPPhi->getNumOperands(); ++i) {
4164         VPValue *Inc = VPPhi->getIncomingValue(i);
4165         VPBasicBlock *VPBB = VPPhi->getIncomingBlock(i);
4166         NewPhi->addIncoming(State.get(Inc, 0), State.CFG.VPBB2IRBB[VPBB]);
4167       }
4168     }
4169   }
4170 }
4171 
4172 bool InnerLoopVectorizer::useOrderedReductions(
4173     const RecurrenceDescriptor &RdxDesc) {
4174   return Cost->useOrderedReductions(RdxDesc);
4175 }
4176 
4177 /// A helper function for checking whether an integer division-related
4178 /// instruction may divide by zero (in which case it must be predicated if
4179 /// executed conditionally in the scalar code).
4180 /// TODO: It may be worthwhile to generalize and check isKnownNonZero().
4181 /// Non-zero divisors that are non compile-time constants will not be
4182 /// converted into multiplication, so we will still end up scalarizing
4183 /// the division, but can do so w/o predication.
4184 static bool mayDivideByZero(Instruction &I) {
4185   assert((I.getOpcode() == Instruction::UDiv ||
4186           I.getOpcode() == Instruction::SDiv ||
4187           I.getOpcode() == Instruction::URem ||
4188           I.getOpcode() == Instruction::SRem) &&
4189          "Unexpected instruction");
4190   Value *Divisor = I.getOperand(1);
4191   auto *CInt = dyn_cast<ConstantInt>(Divisor);
4192   return !CInt || CInt->isZero();
4193 }
4194 
4195 void InnerLoopVectorizer::widenCallInstruction(CallInst &I, VPValue *Def,
4196                                                VPUser &ArgOperands,
4197                                                VPTransformState &State) {
4198   assert(!isa<DbgInfoIntrinsic>(I) &&
4199          "DbgInfoIntrinsic should have been dropped during VPlan construction");
4200   State.setDebugLocFromInst(&I);
4201 
4202   Module *M = I.getParent()->getParent()->getParent();
4203   auto *CI = cast<CallInst>(&I);
4204 
4205   SmallVector<Type *, 4> Tys;
4206   for (Value *ArgOperand : CI->args())
4207     Tys.push_back(ToVectorTy(ArgOperand->getType(), VF.getKnownMinValue()));
4208 
4209   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4210 
4211   // The flag shows whether we use Intrinsic or a usual Call for vectorized
4212   // version of the instruction.
4213   // Is it beneficial to perform intrinsic call compared to lib call?
4214   bool NeedToScalarize = false;
4215   InstructionCost CallCost = Cost->getVectorCallCost(CI, VF, NeedToScalarize);
4216   InstructionCost IntrinsicCost = ID ? Cost->getVectorIntrinsicCost(CI, VF) : 0;
4217   bool UseVectorIntrinsic = ID && IntrinsicCost <= CallCost;
4218   assert((UseVectorIntrinsic || !NeedToScalarize) &&
4219          "Instruction should be scalarized elsewhere.");
4220   assert((IntrinsicCost.isValid() || CallCost.isValid()) &&
4221          "Either the intrinsic cost or vector call cost must be valid");
4222 
4223   for (unsigned Part = 0; Part < UF; ++Part) {
4224     SmallVector<Type *, 2> TysForDecl = {CI->getType()};
4225     SmallVector<Value *, 4> Args;
4226     for (auto &I : enumerate(ArgOperands.operands())) {
4227       // Some intrinsics have a scalar argument - don't replace it with a
4228       // vector.
4229       Value *Arg;
4230       if (!UseVectorIntrinsic ||
4231           !isVectorIntrinsicWithScalarOpAtArg(ID, I.index()))
4232         Arg = State.get(I.value(), Part);
4233       else
4234         Arg = State.get(I.value(), VPIteration(0, 0));
4235       if (isVectorIntrinsicWithOverloadTypeAtArg(ID, I.index()))
4236         TysForDecl.push_back(Arg->getType());
4237       Args.push_back(Arg);
4238     }
4239 
4240     Function *VectorF;
4241     if (UseVectorIntrinsic) {
4242       // Use vector version of the intrinsic.
4243       if (VF.isVector())
4244         TysForDecl[0] = VectorType::get(CI->getType()->getScalarType(), VF);
4245       VectorF = Intrinsic::getDeclaration(M, ID, TysForDecl);
4246       assert(VectorF && "Can't retrieve vector intrinsic.");
4247     } else {
4248       // Use vector version of the function call.
4249       const VFShape Shape = VFShape::get(*CI, VF, false /*HasGlobalPred*/);
4250 #ifndef NDEBUG
4251       assert(VFDatabase(*CI).getVectorizedFunction(Shape) != nullptr &&
4252              "Can't create vector function.");
4253 #endif
4254         VectorF = VFDatabase(*CI).getVectorizedFunction(Shape);
4255     }
4256       SmallVector<OperandBundleDef, 1> OpBundles;
4257       CI->getOperandBundlesAsDefs(OpBundles);
4258       CallInst *V = Builder.CreateCall(VectorF, Args, OpBundles);
4259 
4260       if (isa<FPMathOperator>(V))
4261         V->copyFastMathFlags(CI);
4262 
4263       State.set(Def, V, Part);
4264       State.addMetadata(V, &I);
4265   }
4266 }
4267 
4268 void LoopVectorizationCostModel::collectLoopScalars(ElementCount VF) {
4269   // We should not collect Scalars more than once per VF. Right now, this
4270   // function is called from collectUniformsAndScalars(), which already does
4271   // this check. Collecting Scalars for VF=1 does not make any sense.
4272   assert(VF.isVector() && Scalars.find(VF) == Scalars.end() &&
4273          "This function should not be visited twice for the same VF");
4274 
4275   // This avoids any chances of creating a REPLICATE recipe during planning
4276   // since that would result in generation of scalarized code during execution,
4277   // which is not supported for scalable vectors.
4278   if (VF.isScalable()) {
4279     Scalars[VF].insert(Uniforms[VF].begin(), Uniforms[VF].end());
4280     return;
4281   }
4282 
4283   SmallSetVector<Instruction *, 8> Worklist;
4284 
4285   // These sets are used to seed the analysis with pointers used by memory
4286   // accesses that will remain scalar.
4287   SmallSetVector<Instruction *, 8> ScalarPtrs;
4288   SmallPtrSet<Instruction *, 8> PossibleNonScalarPtrs;
4289   auto *Latch = TheLoop->getLoopLatch();
4290 
4291   // A helper that returns true if the use of Ptr by MemAccess will be scalar.
4292   // The pointer operands of loads and stores will be scalar as long as the
4293   // memory access is not a gather or scatter operation. The value operand of a
4294   // store will remain scalar if the store is scalarized.
4295   auto isScalarUse = [&](Instruction *MemAccess, Value *Ptr) {
4296     InstWidening WideningDecision = getWideningDecision(MemAccess, VF);
4297     assert(WideningDecision != CM_Unknown &&
4298            "Widening decision should be ready at this moment");
4299     if (auto *Store = dyn_cast<StoreInst>(MemAccess))
4300       if (Ptr == Store->getValueOperand())
4301         return WideningDecision == CM_Scalarize;
4302     assert(Ptr == getLoadStorePointerOperand(MemAccess) &&
4303            "Ptr is neither a value or pointer operand");
4304     return WideningDecision != CM_GatherScatter;
4305   };
4306 
4307   // A helper that returns true if the given value is a bitcast or
4308   // getelementptr instruction contained in the loop.
4309   auto isLoopVaryingBitCastOrGEP = [&](Value *V) {
4310     return ((isa<BitCastInst>(V) && V->getType()->isPointerTy()) ||
4311             isa<GetElementPtrInst>(V)) &&
4312            !TheLoop->isLoopInvariant(V);
4313   };
4314 
4315   // A helper that evaluates a memory access's use of a pointer. If the use will
4316   // be a scalar use and the pointer is only used by memory accesses, we place
4317   // the pointer in ScalarPtrs. Otherwise, the pointer is placed in
4318   // PossibleNonScalarPtrs.
4319   auto evaluatePtrUse = [&](Instruction *MemAccess, Value *Ptr) {
4320     // We only care about bitcast and getelementptr instructions contained in
4321     // the loop.
4322     if (!isLoopVaryingBitCastOrGEP(Ptr))
4323       return;
4324 
4325     // If the pointer has already been identified as scalar (e.g., if it was
4326     // also identified as uniform), there's nothing to do.
4327     auto *I = cast<Instruction>(Ptr);
4328     if (Worklist.count(I))
4329       return;
4330 
4331     // If the use of the pointer will be a scalar use, and all users of the
4332     // pointer are memory accesses, place the pointer in ScalarPtrs. Otherwise,
4333     // place the pointer in PossibleNonScalarPtrs.
4334     if (isScalarUse(MemAccess, Ptr) && llvm::all_of(I->users(), [&](User *U) {
4335           return isa<LoadInst>(U) || isa<StoreInst>(U);
4336         }))
4337       ScalarPtrs.insert(I);
4338     else
4339       PossibleNonScalarPtrs.insert(I);
4340   };
4341 
4342   // We seed the scalars analysis with three classes of instructions: (1)
4343   // instructions marked uniform-after-vectorization and (2) bitcast,
4344   // getelementptr and (pointer) phi instructions used by memory accesses
4345   // requiring a scalar use.
4346   //
4347   // (1) Add to the worklist all instructions that have been identified as
4348   // uniform-after-vectorization.
4349   Worklist.insert(Uniforms[VF].begin(), Uniforms[VF].end());
4350 
4351   // (2) Add to the worklist all bitcast and getelementptr instructions used by
4352   // memory accesses requiring a scalar use. The pointer operands of loads and
4353   // stores will be scalar as long as the memory accesses is not a gather or
4354   // scatter operation. The value operand of a store will remain scalar if the
4355   // store is scalarized.
4356   for (auto *BB : TheLoop->blocks())
4357     for (auto &I : *BB) {
4358       if (auto *Load = dyn_cast<LoadInst>(&I)) {
4359         evaluatePtrUse(Load, Load->getPointerOperand());
4360       } else if (auto *Store = dyn_cast<StoreInst>(&I)) {
4361         evaluatePtrUse(Store, Store->getPointerOperand());
4362         evaluatePtrUse(Store, Store->getValueOperand());
4363       }
4364     }
4365   for (auto *I : ScalarPtrs)
4366     if (!PossibleNonScalarPtrs.count(I)) {
4367       LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *I << "\n");
4368       Worklist.insert(I);
4369     }
4370 
4371   // Insert the forced scalars.
4372   // FIXME: Currently VPWidenPHIRecipe() often creates a dead vector
4373   // induction variable when the PHI user is scalarized.
4374   auto ForcedScalar = ForcedScalars.find(VF);
4375   if (ForcedScalar != ForcedScalars.end())
4376     for (auto *I : ForcedScalar->second)
4377       Worklist.insert(I);
4378 
4379   // Expand the worklist by looking through any bitcasts and getelementptr
4380   // instructions we've already identified as scalar. This is similar to the
4381   // expansion step in collectLoopUniforms(); however, here we're only
4382   // expanding to include additional bitcasts and getelementptr instructions.
4383   unsigned Idx = 0;
4384   while (Idx != Worklist.size()) {
4385     Instruction *Dst = Worklist[Idx++];
4386     if (!isLoopVaryingBitCastOrGEP(Dst->getOperand(0)))
4387       continue;
4388     auto *Src = cast<Instruction>(Dst->getOperand(0));
4389     if (llvm::all_of(Src->users(), [&](User *U) -> bool {
4390           auto *J = cast<Instruction>(U);
4391           return !TheLoop->contains(J) || Worklist.count(J) ||
4392                  ((isa<LoadInst>(J) || isa<StoreInst>(J)) &&
4393                   isScalarUse(J, Src));
4394         })) {
4395       Worklist.insert(Src);
4396       LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Src << "\n");
4397     }
4398   }
4399 
4400   // An induction variable will remain scalar if all users of the induction
4401   // variable and induction variable update remain scalar.
4402   for (auto &Induction : Legal->getInductionVars()) {
4403     auto *Ind = Induction.first;
4404     auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
4405 
4406     // If tail-folding is applied, the primary induction variable will be used
4407     // to feed a vector compare.
4408     if (Ind == Legal->getPrimaryInduction() && foldTailByMasking())
4409       continue;
4410 
4411     // Returns true if \p Indvar is a pointer induction that is used directly by
4412     // load/store instruction \p I.
4413     auto IsDirectLoadStoreFromPtrIndvar = [&](Instruction *Indvar,
4414                                               Instruction *I) {
4415       return Induction.second.getKind() ==
4416                  InductionDescriptor::IK_PtrInduction &&
4417              (isa<LoadInst>(I) || isa<StoreInst>(I)) &&
4418              Indvar == getLoadStorePointerOperand(I) && isScalarUse(I, Indvar);
4419     };
4420 
4421     // Determine if all users of the induction variable are scalar after
4422     // vectorization.
4423     auto ScalarInd = llvm::all_of(Ind->users(), [&](User *U) -> bool {
4424       auto *I = cast<Instruction>(U);
4425       return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) ||
4426              IsDirectLoadStoreFromPtrIndvar(Ind, I);
4427     });
4428     if (!ScalarInd)
4429       continue;
4430 
4431     // Determine if all users of the induction variable update instruction are
4432     // scalar after vectorization.
4433     auto ScalarIndUpdate =
4434         llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
4435           auto *I = cast<Instruction>(U);
4436           return I == Ind || !TheLoop->contains(I) || Worklist.count(I) ||
4437                  IsDirectLoadStoreFromPtrIndvar(IndUpdate, I);
4438         });
4439     if (!ScalarIndUpdate)
4440       continue;
4441 
4442     // The induction variable and its update instruction will remain scalar.
4443     Worklist.insert(Ind);
4444     Worklist.insert(IndUpdate);
4445     LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Ind << "\n");
4446     LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *IndUpdate
4447                       << "\n");
4448   }
4449 
4450   Scalars[VF].insert(Worklist.begin(), Worklist.end());
4451 }
4452 
4453 bool LoopVectorizationCostModel::isScalarWithPredication(
4454     Instruction *I, ElementCount VF) const {
4455   if (!blockNeedsPredicationForAnyReason(I->getParent()))
4456     return false;
4457   switch(I->getOpcode()) {
4458   default:
4459     break;
4460   case Instruction::Load:
4461   case Instruction::Store: {
4462     if (!Legal->isMaskRequired(I))
4463       return false;
4464     auto *Ptr = getLoadStorePointerOperand(I);
4465     auto *Ty = getLoadStoreType(I);
4466     Type *VTy = Ty;
4467     if (VF.isVector())
4468       VTy = VectorType::get(Ty, VF);
4469     const Align Alignment = getLoadStoreAlignment(I);
4470     return isa<LoadInst>(I) ? !(isLegalMaskedLoad(Ty, Ptr, Alignment) ||
4471                                 TTI.isLegalMaskedGather(VTy, Alignment))
4472                             : !(isLegalMaskedStore(Ty, Ptr, Alignment) ||
4473                                 TTI.isLegalMaskedScatter(VTy, Alignment));
4474   }
4475   case Instruction::UDiv:
4476   case Instruction::SDiv:
4477   case Instruction::SRem:
4478   case Instruction::URem:
4479     return mayDivideByZero(*I);
4480   }
4481   return false;
4482 }
4483 
4484 bool LoopVectorizationCostModel::interleavedAccessCanBeWidened(
4485     Instruction *I, ElementCount VF) {
4486   assert(isAccessInterleaved(I) && "Expecting interleaved access.");
4487   assert(getWideningDecision(I, VF) == CM_Unknown &&
4488          "Decision should not be set yet.");
4489   auto *Group = getInterleavedAccessGroup(I);
4490   assert(Group && "Must have a group.");
4491 
4492   // If the instruction's allocated size doesn't equal it's type size, it
4493   // requires padding and will be scalarized.
4494   auto &DL = I->getModule()->getDataLayout();
4495   auto *ScalarTy = getLoadStoreType(I);
4496   if (hasIrregularType(ScalarTy, DL))
4497     return false;
4498 
4499   // If the group involves a non-integral pointer, we may not be able to
4500   // losslessly cast all values to a common type.
4501   unsigned InterleaveFactor = Group->getFactor();
4502   bool ScalarNI = DL.isNonIntegralPointerType(ScalarTy);
4503   for (unsigned i = 0; i < InterleaveFactor; i++) {
4504     Instruction *Member = Group->getMember(i);
4505     if (!Member)
4506       continue;
4507     auto *MemberTy = getLoadStoreType(Member);
4508     bool MemberNI = DL.isNonIntegralPointerType(MemberTy);
4509     // Don't coerce non-integral pointers to integers or vice versa.
4510     if (MemberNI != ScalarNI) {
4511       // TODO: Consider adding special nullptr value case here
4512       return false;
4513     } else if (MemberNI && ScalarNI &&
4514                ScalarTy->getPointerAddressSpace() !=
4515                MemberTy->getPointerAddressSpace()) {
4516       return false;
4517     }
4518   }
4519 
4520   // Check if masking is required.
4521   // A Group may need masking for one of two reasons: it resides in a block that
4522   // needs predication, or it was decided to use masking to deal with gaps
4523   // (either a gap at the end of a load-access that may result in a speculative
4524   // load, or any gaps in a store-access).
4525   bool PredicatedAccessRequiresMasking =
4526       blockNeedsPredicationForAnyReason(I->getParent()) &&
4527       Legal->isMaskRequired(I);
4528   bool LoadAccessWithGapsRequiresEpilogMasking =
4529       isa<LoadInst>(I) && Group->requiresScalarEpilogue() &&
4530       !isScalarEpilogueAllowed();
4531   bool StoreAccessWithGapsRequiresMasking =
4532       isa<StoreInst>(I) && (Group->getNumMembers() < Group->getFactor());
4533   if (!PredicatedAccessRequiresMasking &&
4534       !LoadAccessWithGapsRequiresEpilogMasking &&
4535       !StoreAccessWithGapsRequiresMasking)
4536     return true;
4537 
4538   // If masked interleaving is required, we expect that the user/target had
4539   // enabled it, because otherwise it either wouldn't have been created or
4540   // it should have been invalidated by the CostModel.
4541   assert(useMaskedInterleavedAccesses(TTI) &&
4542          "Masked interleave-groups for predicated accesses are not enabled.");
4543 
4544   if (Group->isReverse())
4545     return false;
4546 
4547   auto *Ty = getLoadStoreType(I);
4548   const Align Alignment = getLoadStoreAlignment(I);
4549   return isa<LoadInst>(I) ? TTI.isLegalMaskedLoad(Ty, Alignment)
4550                           : TTI.isLegalMaskedStore(Ty, Alignment);
4551 }
4552 
4553 bool LoopVectorizationCostModel::memoryInstructionCanBeWidened(
4554     Instruction *I, ElementCount VF) {
4555   // Get and ensure we have a valid memory instruction.
4556   assert((isa<LoadInst, StoreInst>(I)) && "Invalid memory instruction");
4557 
4558   auto *Ptr = getLoadStorePointerOperand(I);
4559   auto *ScalarTy = getLoadStoreType(I);
4560 
4561   // In order to be widened, the pointer should be consecutive, first of all.
4562   if (!Legal->isConsecutivePtr(ScalarTy, Ptr))
4563     return false;
4564 
4565   // If the instruction is a store located in a predicated block, it will be
4566   // scalarized.
4567   if (isScalarWithPredication(I, VF))
4568     return false;
4569 
4570   // If the instruction's allocated size doesn't equal it's type size, it
4571   // requires padding and will be scalarized.
4572   auto &DL = I->getModule()->getDataLayout();
4573   if (hasIrregularType(ScalarTy, DL))
4574     return false;
4575 
4576   return true;
4577 }
4578 
4579 void LoopVectorizationCostModel::collectLoopUniforms(ElementCount VF) {
4580   // We should not collect Uniforms more than once per VF. Right now,
4581   // this function is called from collectUniformsAndScalars(), which
4582   // already does this check. Collecting Uniforms for VF=1 does not make any
4583   // sense.
4584 
4585   assert(VF.isVector() && Uniforms.find(VF) == Uniforms.end() &&
4586          "This function should not be visited twice for the same VF");
4587 
4588   // Visit the list of Uniforms. If we'll not find any uniform value, we'll
4589   // not analyze again.  Uniforms.count(VF) will return 1.
4590   Uniforms[VF].clear();
4591 
4592   // We now know that the loop is vectorizable!
4593   // Collect instructions inside the loop that will remain uniform after
4594   // vectorization.
4595 
4596   // Global values, params and instructions outside of current loop are out of
4597   // scope.
4598   auto isOutOfScope = [&](Value *V) -> bool {
4599     Instruction *I = dyn_cast<Instruction>(V);
4600     return (!I || !TheLoop->contains(I));
4601   };
4602 
4603   // Worklist containing uniform instructions demanding lane 0.
4604   SetVector<Instruction *> Worklist;
4605   BasicBlock *Latch = TheLoop->getLoopLatch();
4606 
4607   // Add uniform instructions demanding lane 0 to the worklist. Instructions
4608   // that are scalar with predication must not be considered uniform after
4609   // vectorization, because that would create an erroneous replicating region
4610   // where only a single instance out of VF should be formed.
4611   // TODO: optimize such seldom cases if found important, see PR40816.
4612   auto addToWorklistIfAllowed = [&](Instruction *I) -> void {
4613     if (isOutOfScope(I)) {
4614       LLVM_DEBUG(dbgs() << "LV: Found not uniform due to scope: "
4615                         << *I << "\n");
4616       return;
4617     }
4618     if (isScalarWithPredication(I, VF)) {
4619       LLVM_DEBUG(dbgs() << "LV: Found not uniform being ScalarWithPredication: "
4620                         << *I << "\n");
4621       return;
4622     }
4623     LLVM_DEBUG(dbgs() << "LV: Found uniform instruction: " << *I << "\n");
4624     Worklist.insert(I);
4625   };
4626 
4627   // Start with the conditional branch. If the branch condition is an
4628   // instruction contained in the loop that is only used by the branch, it is
4629   // uniform.
4630   auto *Cmp = dyn_cast<Instruction>(Latch->getTerminator()->getOperand(0));
4631   if (Cmp && TheLoop->contains(Cmp) && Cmp->hasOneUse())
4632     addToWorklistIfAllowed(Cmp);
4633 
4634   auto isUniformDecision = [&](Instruction *I, ElementCount VF) {
4635     InstWidening WideningDecision = getWideningDecision(I, VF);
4636     assert(WideningDecision != CM_Unknown &&
4637            "Widening decision should be ready at this moment");
4638 
4639     // A uniform memory op is itself uniform.  We exclude uniform stores
4640     // here as they demand the last lane, not the first one.
4641     if (isa<LoadInst>(I) && Legal->isUniformMemOp(*I)) {
4642       assert(WideningDecision == CM_Scalarize);
4643       return true;
4644     }
4645 
4646     return (WideningDecision == CM_Widen ||
4647             WideningDecision == CM_Widen_Reverse ||
4648             WideningDecision == CM_Interleave);
4649   };
4650 
4651 
4652   // Returns true if Ptr is the pointer operand of a memory access instruction
4653   // I, and I is known to not require scalarization.
4654   auto isVectorizedMemAccessUse = [&](Instruction *I, Value *Ptr) -> bool {
4655     return getLoadStorePointerOperand(I) == Ptr && isUniformDecision(I, VF);
4656   };
4657 
4658   // Holds a list of values which are known to have at least one uniform use.
4659   // Note that there may be other uses which aren't uniform.  A "uniform use"
4660   // here is something which only demands lane 0 of the unrolled iterations;
4661   // it does not imply that all lanes produce the same value (e.g. this is not
4662   // the usual meaning of uniform)
4663   SetVector<Value *> HasUniformUse;
4664 
4665   // Scan the loop for instructions which are either a) known to have only
4666   // lane 0 demanded or b) are uses which demand only lane 0 of their operand.
4667   for (auto *BB : TheLoop->blocks())
4668     for (auto &I : *BB) {
4669       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I)) {
4670         switch (II->getIntrinsicID()) {
4671         case Intrinsic::sideeffect:
4672         case Intrinsic::experimental_noalias_scope_decl:
4673         case Intrinsic::assume:
4674         case Intrinsic::lifetime_start:
4675         case Intrinsic::lifetime_end:
4676           if (TheLoop->hasLoopInvariantOperands(&I))
4677             addToWorklistIfAllowed(&I);
4678           break;
4679         default:
4680           break;
4681         }
4682       }
4683 
4684       // ExtractValue instructions must be uniform, because the operands are
4685       // known to be loop-invariant.
4686       if (auto *EVI = dyn_cast<ExtractValueInst>(&I)) {
4687         assert(isOutOfScope(EVI->getAggregateOperand()) &&
4688                "Expected aggregate value to be loop invariant");
4689         addToWorklistIfAllowed(EVI);
4690         continue;
4691       }
4692 
4693       // If there's no pointer operand, there's nothing to do.
4694       auto *Ptr = getLoadStorePointerOperand(&I);
4695       if (!Ptr)
4696         continue;
4697 
4698       // A uniform memory op is itself uniform.  We exclude uniform stores
4699       // here as they demand the last lane, not the first one.
4700       if (isa<LoadInst>(I) && Legal->isUniformMemOp(I))
4701         addToWorklistIfAllowed(&I);
4702 
4703       if (isUniformDecision(&I, VF)) {
4704         assert(isVectorizedMemAccessUse(&I, Ptr) && "consistency check");
4705         HasUniformUse.insert(Ptr);
4706       }
4707     }
4708 
4709   // Add to the worklist any operands which have *only* uniform (e.g. lane 0
4710   // demanding) users.  Since loops are assumed to be in LCSSA form, this
4711   // disallows uses outside the loop as well.
4712   for (auto *V : HasUniformUse) {
4713     if (isOutOfScope(V))
4714       continue;
4715     auto *I = cast<Instruction>(V);
4716     auto UsersAreMemAccesses =
4717       llvm::all_of(I->users(), [&](User *U) -> bool {
4718         return isVectorizedMemAccessUse(cast<Instruction>(U), V);
4719       });
4720     if (UsersAreMemAccesses)
4721       addToWorklistIfAllowed(I);
4722   }
4723 
4724   // Expand Worklist in topological order: whenever a new instruction
4725   // is added , its users should be already inside Worklist.  It ensures
4726   // a uniform instruction will only be used by uniform instructions.
4727   unsigned idx = 0;
4728   while (idx != Worklist.size()) {
4729     Instruction *I = Worklist[idx++];
4730 
4731     for (auto OV : I->operand_values()) {
4732       // isOutOfScope operands cannot be uniform instructions.
4733       if (isOutOfScope(OV))
4734         continue;
4735       // First order recurrence Phi's should typically be considered
4736       // non-uniform.
4737       auto *OP = dyn_cast<PHINode>(OV);
4738       if (OP && Legal->isFirstOrderRecurrence(OP))
4739         continue;
4740       // If all the users of the operand are uniform, then add the
4741       // operand into the uniform worklist.
4742       auto *OI = cast<Instruction>(OV);
4743       if (llvm::all_of(OI->users(), [&](User *U) -> bool {
4744             auto *J = cast<Instruction>(U);
4745             return Worklist.count(J) || isVectorizedMemAccessUse(J, OI);
4746           }))
4747         addToWorklistIfAllowed(OI);
4748     }
4749   }
4750 
4751   // For an instruction to be added into Worklist above, all its users inside
4752   // the loop should also be in Worklist. However, this condition cannot be
4753   // true for phi nodes that form a cyclic dependence. We must process phi
4754   // nodes separately. An induction variable will remain uniform if all users
4755   // of the induction variable and induction variable update remain uniform.
4756   // The code below handles both pointer and non-pointer induction variables.
4757   for (auto &Induction : Legal->getInductionVars()) {
4758     auto *Ind = Induction.first;
4759     auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
4760 
4761     // Determine if all users of the induction variable are uniform after
4762     // vectorization.
4763     auto UniformInd = llvm::all_of(Ind->users(), [&](User *U) -> bool {
4764       auto *I = cast<Instruction>(U);
4765       return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) ||
4766              isVectorizedMemAccessUse(I, Ind);
4767     });
4768     if (!UniformInd)
4769       continue;
4770 
4771     // Determine if all users of the induction variable update instruction are
4772     // uniform after vectorization.
4773     auto UniformIndUpdate =
4774         llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
4775           auto *I = cast<Instruction>(U);
4776           return I == Ind || !TheLoop->contains(I) || Worklist.count(I) ||
4777                  isVectorizedMemAccessUse(I, IndUpdate);
4778         });
4779     if (!UniformIndUpdate)
4780       continue;
4781 
4782     // The induction variable and its update instruction will remain uniform.
4783     addToWorklistIfAllowed(Ind);
4784     addToWorklistIfAllowed(IndUpdate);
4785   }
4786 
4787   Uniforms[VF].insert(Worklist.begin(), Worklist.end());
4788 }
4789 
4790 bool LoopVectorizationCostModel::runtimeChecksRequired() {
4791   LLVM_DEBUG(dbgs() << "LV: Performing code size checks.\n");
4792 
4793   if (Legal->getRuntimePointerChecking()->Need) {
4794     reportVectorizationFailure("Runtime ptr check is required with -Os/-Oz",
4795         "runtime pointer checks needed. Enable vectorization of this "
4796         "loop with '#pragma clang loop vectorize(enable)' when "
4797         "compiling with -Os/-Oz",
4798         "CantVersionLoopWithOptForSize", ORE, TheLoop);
4799     return true;
4800   }
4801 
4802   if (!PSE.getPredicate().isAlwaysTrue()) {
4803     reportVectorizationFailure("Runtime SCEV check is required with -Os/-Oz",
4804         "runtime SCEV checks needed. Enable vectorization of this "
4805         "loop with '#pragma clang loop vectorize(enable)' when "
4806         "compiling with -Os/-Oz",
4807         "CantVersionLoopWithOptForSize", ORE, TheLoop);
4808     return true;
4809   }
4810 
4811   // FIXME: Avoid specializing for stride==1 instead of bailing out.
4812   if (!Legal->getLAI()->getSymbolicStrides().empty()) {
4813     reportVectorizationFailure("Runtime stride check for small trip count",
4814         "runtime stride == 1 checks needed. Enable vectorization of "
4815         "this loop without such check by compiling with -Os/-Oz",
4816         "CantVersionLoopWithOptForSize", ORE, TheLoop);
4817     return true;
4818   }
4819 
4820   return false;
4821 }
4822 
4823 ElementCount
4824 LoopVectorizationCostModel::getMaxLegalScalableVF(unsigned MaxSafeElements) {
4825   if (!TTI.supportsScalableVectors() && !ForceTargetSupportsScalableVectors)
4826     return ElementCount::getScalable(0);
4827 
4828   if (Hints->isScalableVectorizationDisabled()) {
4829     reportVectorizationInfo("Scalable vectorization is explicitly disabled",
4830                             "ScalableVectorizationDisabled", ORE, TheLoop);
4831     return ElementCount::getScalable(0);
4832   }
4833 
4834   LLVM_DEBUG(dbgs() << "LV: Scalable vectorization is available\n");
4835 
4836   auto MaxScalableVF = ElementCount::getScalable(
4837       std::numeric_limits<ElementCount::ScalarTy>::max());
4838 
4839   // Test that the loop-vectorizer can legalize all operations for this MaxVF.
4840   // FIXME: While for scalable vectors this is currently sufficient, this should
4841   // be replaced by a more detailed mechanism that filters out specific VFs,
4842   // instead of invalidating vectorization for a whole set of VFs based on the
4843   // MaxVF.
4844 
4845   // Disable scalable vectorization if the loop contains unsupported reductions.
4846   if (!canVectorizeReductions(MaxScalableVF)) {
4847     reportVectorizationInfo(
4848         "Scalable vectorization not supported for the reduction "
4849         "operations found in this loop.",
4850         "ScalableVFUnfeasible", ORE, TheLoop);
4851     return ElementCount::getScalable(0);
4852   }
4853 
4854   // Disable scalable vectorization if the loop contains any instructions
4855   // with element types not supported for scalable vectors.
4856   if (any_of(ElementTypesInLoop, [&](Type *Ty) {
4857         return !Ty->isVoidTy() &&
4858                !this->TTI.isElementTypeLegalForScalableVector(Ty);
4859       })) {
4860     reportVectorizationInfo("Scalable vectorization is not supported "
4861                             "for all element types found in this loop.",
4862                             "ScalableVFUnfeasible", ORE, TheLoop);
4863     return ElementCount::getScalable(0);
4864   }
4865 
4866   if (Legal->isSafeForAnyVectorWidth())
4867     return MaxScalableVF;
4868 
4869   // Limit MaxScalableVF by the maximum safe dependence distance.
4870   Optional<unsigned> MaxVScale = TTI.getMaxVScale();
4871   if (!MaxVScale && TheFunction->hasFnAttribute(Attribute::VScaleRange))
4872     MaxVScale =
4873         TheFunction->getFnAttribute(Attribute::VScaleRange).getVScaleRangeMax();
4874   MaxScalableVF = ElementCount::getScalable(
4875       MaxVScale ? (MaxSafeElements / MaxVScale.value()) : 0);
4876   if (!MaxScalableVF)
4877     reportVectorizationInfo(
4878         "Max legal vector width too small, scalable vectorization "
4879         "unfeasible.",
4880         "ScalableVFUnfeasible", ORE, TheLoop);
4881 
4882   return MaxScalableVF;
4883 }
4884 
4885 FixedScalableVFPair LoopVectorizationCostModel::computeFeasibleMaxVF(
4886     unsigned ConstTripCount, ElementCount UserVF, bool FoldTailByMasking) {
4887   MinBWs = computeMinimumValueSizes(TheLoop->getBlocks(), *DB, &TTI);
4888   unsigned SmallestType, WidestType;
4889   std::tie(SmallestType, WidestType) = getSmallestAndWidestTypes();
4890 
4891   // Get the maximum safe dependence distance in bits computed by LAA.
4892   // It is computed by MaxVF * sizeOf(type) * 8, where type is taken from
4893   // the memory accesses that is most restrictive (involved in the smallest
4894   // dependence distance).
4895   unsigned MaxSafeElements =
4896       PowerOf2Floor(Legal->getMaxSafeVectorWidthInBits() / WidestType);
4897 
4898   auto MaxSafeFixedVF = ElementCount::getFixed(MaxSafeElements);
4899   auto MaxSafeScalableVF = getMaxLegalScalableVF(MaxSafeElements);
4900 
4901   LLVM_DEBUG(dbgs() << "LV: The max safe fixed VF is: " << MaxSafeFixedVF
4902                     << ".\n");
4903   LLVM_DEBUG(dbgs() << "LV: The max safe scalable VF is: " << MaxSafeScalableVF
4904                     << ".\n");
4905 
4906   // First analyze the UserVF, fall back if the UserVF should be ignored.
4907   if (UserVF) {
4908     auto MaxSafeUserVF =
4909         UserVF.isScalable() ? MaxSafeScalableVF : MaxSafeFixedVF;
4910 
4911     if (ElementCount::isKnownLE(UserVF, MaxSafeUserVF)) {
4912       // If `VF=vscale x N` is safe, then so is `VF=N`
4913       if (UserVF.isScalable())
4914         return FixedScalableVFPair(
4915             ElementCount::getFixed(UserVF.getKnownMinValue()), UserVF);
4916       else
4917         return UserVF;
4918     }
4919 
4920     assert(ElementCount::isKnownGT(UserVF, MaxSafeUserVF));
4921 
4922     // Only clamp if the UserVF is not scalable. If the UserVF is scalable, it
4923     // is better to ignore the hint and let the compiler choose a suitable VF.
4924     if (!UserVF.isScalable()) {
4925       LLVM_DEBUG(dbgs() << "LV: User VF=" << UserVF
4926                         << " is unsafe, clamping to max safe VF="
4927                         << MaxSafeFixedVF << ".\n");
4928       ORE->emit([&]() {
4929         return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationFactor",
4930                                           TheLoop->getStartLoc(),
4931                                           TheLoop->getHeader())
4932                << "User-specified vectorization factor "
4933                << ore::NV("UserVectorizationFactor", UserVF)
4934                << " is unsafe, clamping to maximum safe vectorization factor "
4935                << ore::NV("VectorizationFactor", MaxSafeFixedVF);
4936       });
4937       return MaxSafeFixedVF;
4938     }
4939 
4940     if (!TTI.supportsScalableVectors() && !ForceTargetSupportsScalableVectors) {
4941       LLVM_DEBUG(dbgs() << "LV: User VF=" << UserVF
4942                         << " is ignored because scalable vectors are not "
4943                            "available.\n");
4944       ORE->emit([&]() {
4945         return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationFactor",
4946                                           TheLoop->getStartLoc(),
4947                                           TheLoop->getHeader())
4948                << "User-specified vectorization factor "
4949                << ore::NV("UserVectorizationFactor", UserVF)
4950                << " is ignored because the target does not support scalable "
4951                   "vectors. The compiler will pick a more suitable value.";
4952       });
4953     } else {
4954       LLVM_DEBUG(dbgs() << "LV: User VF=" << UserVF
4955                         << " is unsafe. Ignoring scalable UserVF.\n");
4956       ORE->emit([&]() {
4957         return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationFactor",
4958                                           TheLoop->getStartLoc(),
4959                                           TheLoop->getHeader())
4960                << "User-specified vectorization factor "
4961                << ore::NV("UserVectorizationFactor", UserVF)
4962                << " is unsafe. Ignoring the hint to let the compiler pick a "
4963                   "more suitable value.";
4964       });
4965     }
4966   }
4967 
4968   LLVM_DEBUG(dbgs() << "LV: The Smallest and Widest types: " << SmallestType
4969                     << " / " << WidestType << " bits.\n");
4970 
4971   FixedScalableVFPair Result(ElementCount::getFixed(1),
4972                              ElementCount::getScalable(0));
4973   if (auto MaxVF =
4974           getMaximizedVFForTarget(ConstTripCount, SmallestType, WidestType,
4975                                   MaxSafeFixedVF, FoldTailByMasking))
4976     Result.FixedVF = MaxVF;
4977 
4978   if (auto MaxVF =
4979           getMaximizedVFForTarget(ConstTripCount, SmallestType, WidestType,
4980                                   MaxSafeScalableVF, FoldTailByMasking))
4981     if (MaxVF.isScalable()) {
4982       Result.ScalableVF = MaxVF;
4983       LLVM_DEBUG(dbgs() << "LV: Found feasible scalable VF = " << MaxVF
4984                         << "\n");
4985     }
4986 
4987   return Result;
4988 }
4989 
4990 FixedScalableVFPair
4991 LoopVectorizationCostModel::computeMaxVF(ElementCount UserVF, unsigned UserIC) {
4992   if (Legal->getRuntimePointerChecking()->Need && TTI.hasBranchDivergence()) {
4993     // TODO: It may by useful to do since it's still likely to be dynamically
4994     // uniform if the target can skip.
4995     reportVectorizationFailure(
4996         "Not inserting runtime ptr check for divergent target",
4997         "runtime pointer checks needed. Not enabled for divergent target",
4998         "CantVersionLoopWithDivergentTarget", ORE, TheLoop);
4999     return FixedScalableVFPair::getNone();
5000   }
5001 
5002   unsigned TC = PSE.getSE()->getSmallConstantTripCount(TheLoop);
5003   LLVM_DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
5004   if (TC == 1) {
5005     reportVectorizationFailure("Single iteration (non) loop",
5006         "loop trip count is one, irrelevant for vectorization",
5007         "SingleIterationLoop", ORE, TheLoop);
5008     return FixedScalableVFPair::getNone();
5009   }
5010 
5011   switch (ScalarEpilogueStatus) {
5012   case CM_ScalarEpilogueAllowed:
5013     return computeFeasibleMaxVF(TC, UserVF, false);
5014   case CM_ScalarEpilogueNotAllowedUsePredicate:
5015     LLVM_FALLTHROUGH;
5016   case CM_ScalarEpilogueNotNeededUsePredicate:
5017     LLVM_DEBUG(
5018         dbgs() << "LV: vector predicate hint/switch found.\n"
5019                << "LV: Not allowing scalar epilogue, creating predicated "
5020                << "vector loop.\n");
5021     break;
5022   case CM_ScalarEpilogueNotAllowedLowTripLoop:
5023     // fallthrough as a special case of OptForSize
5024   case CM_ScalarEpilogueNotAllowedOptSize:
5025     if (ScalarEpilogueStatus == CM_ScalarEpilogueNotAllowedOptSize)
5026       LLVM_DEBUG(
5027           dbgs() << "LV: Not allowing scalar epilogue due to -Os/-Oz.\n");
5028     else
5029       LLVM_DEBUG(dbgs() << "LV: Not allowing scalar epilogue due to low trip "
5030                         << "count.\n");
5031 
5032     // Bail if runtime checks are required, which are not good when optimising
5033     // for size.
5034     if (runtimeChecksRequired())
5035       return FixedScalableVFPair::getNone();
5036 
5037     break;
5038   }
5039 
5040   // The only loops we can vectorize without a scalar epilogue, are loops with
5041   // a bottom-test and a single exiting block. We'd have to handle the fact
5042   // that not every instruction executes on the last iteration.  This will
5043   // require a lane mask which varies through the vector loop body.  (TODO)
5044   if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
5045     // If there was a tail-folding hint/switch, but we can't fold the tail by
5046     // masking, fallback to a vectorization with a scalar epilogue.
5047     if (ScalarEpilogueStatus == CM_ScalarEpilogueNotNeededUsePredicate) {
5048       LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking: vectorize with a "
5049                            "scalar epilogue instead.\n");
5050       ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
5051       return computeFeasibleMaxVF(TC, UserVF, false);
5052     }
5053     return FixedScalableVFPair::getNone();
5054   }
5055 
5056   // Now try the tail folding
5057 
5058   // Invalidate interleave groups that require an epilogue if we can't mask
5059   // the interleave-group.
5060   if (!useMaskedInterleavedAccesses(TTI)) {
5061     assert(WideningDecisions.empty() && Uniforms.empty() && Scalars.empty() &&
5062            "No decisions should have been taken at this point");
5063     // Note: There is no need to invalidate any cost modeling decisions here, as
5064     // non where taken so far.
5065     InterleaveInfo.invalidateGroupsRequiringScalarEpilogue();
5066   }
5067 
5068   FixedScalableVFPair MaxFactors = computeFeasibleMaxVF(TC, UserVF, true);
5069   // Avoid tail folding if the trip count is known to be a multiple of any VF
5070   // we chose.
5071   // FIXME: The condition below pessimises the case for fixed-width vectors,
5072   // when scalable VFs are also candidates for vectorization.
5073   if (MaxFactors.FixedVF.isVector() && !MaxFactors.ScalableVF) {
5074     ElementCount MaxFixedVF = MaxFactors.FixedVF;
5075     assert((UserVF.isNonZero() || isPowerOf2_32(MaxFixedVF.getFixedValue())) &&
5076            "MaxFixedVF must be a power of 2");
5077     unsigned MaxVFtimesIC = UserIC ? MaxFixedVF.getFixedValue() * UserIC
5078                                    : MaxFixedVF.getFixedValue();
5079     ScalarEvolution *SE = PSE.getSE();
5080     const SCEV *BackedgeTakenCount = PSE.getBackedgeTakenCount();
5081     const SCEV *ExitCount = SE->getAddExpr(
5082         BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType()));
5083     const SCEV *Rem = SE->getURemExpr(
5084         SE->applyLoopGuards(ExitCount, TheLoop),
5085         SE->getConstant(BackedgeTakenCount->getType(), MaxVFtimesIC));
5086     if (Rem->isZero()) {
5087       // Accept MaxFixedVF if we do not have a tail.
5088       LLVM_DEBUG(dbgs() << "LV: No tail will remain for any chosen VF.\n");
5089       return MaxFactors;
5090     }
5091   }
5092 
5093   // If we don't know the precise trip count, or if the trip count that we
5094   // found modulo the vectorization factor is not zero, try to fold the tail
5095   // by masking.
5096   // FIXME: look for a smaller MaxVF that does divide TC rather than masking.
5097   if (Legal->prepareToFoldTailByMasking()) {
5098     FoldTailByMasking = true;
5099     return MaxFactors;
5100   }
5101 
5102   // If there was a tail-folding hint/switch, but we can't fold the tail by
5103   // masking, fallback to a vectorization with a scalar epilogue.
5104   if (ScalarEpilogueStatus == CM_ScalarEpilogueNotNeededUsePredicate) {
5105     LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking: vectorize with a "
5106                          "scalar epilogue instead.\n");
5107     ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
5108     return MaxFactors;
5109   }
5110 
5111   if (ScalarEpilogueStatus == CM_ScalarEpilogueNotAllowedUsePredicate) {
5112     LLVM_DEBUG(dbgs() << "LV: Can't fold tail by masking: don't vectorize\n");
5113     return FixedScalableVFPair::getNone();
5114   }
5115 
5116   if (TC == 0) {
5117     reportVectorizationFailure(
5118         "Unable to calculate the loop count due to complex control flow",
5119         "unable to calculate the loop count due to complex control flow",
5120         "UnknownLoopCountComplexCFG", ORE, TheLoop);
5121     return FixedScalableVFPair::getNone();
5122   }
5123 
5124   reportVectorizationFailure(
5125       "Cannot optimize for size and vectorize at the same time.",
5126       "cannot optimize for size and vectorize at the same time. "
5127       "Enable vectorization of this loop with '#pragma clang loop "
5128       "vectorize(enable)' when compiling with -Os/-Oz",
5129       "NoTailLoopWithOptForSize", ORE, TheLoop);
5130   return FixedScalableVFPair::getNone();
5131 }
5132 
5133 ElementCount LoopVectorizationCostModel::getMaximizedVFForTarget(
5134     unsigned ConstTripCount, unsigned SmallestType, unsigned WidestType,
5135     ElementCount MaxSafeVF, bool FoldTailByMasking) {
5136   bool ComputeScalableMaxVF = MaxSafeVF.isScalable();
5137   TypeSize WidestRegister = TTI.getRegisterBitWidth(
5138       ComputeScalableMaxVF ? TargetTransformInfo::RGK_ScalableVector
5139                            : TargetTransformInfo::RGK_FixedWidthVector);
5140 
5141   // Convenience function to return the minimum of two ElementCounts.
5142   auto MinVF = [](const ElementCount &LHS, const ElementCount &RHS) {
5143     assert((LHS.isScalable() == RHS.isScalable()) &&
5144            "Scalable flags must match");
5145     return ElementCount::isKnownLT(LHS, RHS) ? LHS : RHS;
5146   };
5147 
5148   // Ensure MaxVF is a power of 2; the dependence distance bound may not be.
5149   // Note that both WidestRegister and WidestType may not be a powers of 2.
5150   auto MaxVectorElementCount = ElementCount::get(
5151       PowerOf2Floor(WidestRegister.getKnownMinSize() / WidestType),
5152       ComputeScalableMaxVF);
5153   MaxVectorElementCount = MinVF(MaxVectorElementCount, MaxSafeVF);
5154   LLVM_DEBUG(dbgs() << "LV: The Widest register safe to use is: "
5155                     << (MaxVectorElementCount * WidestType) << " bits.\n");
5156 
5157   if (!MaxVectorElementCount) {
5158     LLVM_DEBUG(dbgs() << "LV: The target has no "
5159                       << (ComputeScalableMaxVF ? "scalable" : "fixed")
5160                       << " vector registers.\n");
5161     return ElementCount::getFixed(1);
5162   }
5163 
5164   const auto TripCountEC = ElementCount::getFixed(ConstTripCount);
5165   if (ConstTripCount &&
5166       ElementCount::isKnownLE(TripCountEC, MaxVectorElementCount) &&
5167       (!FoldTailByMasking || isPowerOf2_32(ConstTripCount))) {
5168     // If loop trip count (TC) is known at compile time there is no point in
5169     // choosing VF greater than TC (as done in the loop below). Select maximum
5170     // power of two which doesn't exceed TC.
5171     // If MaxVectorElementCount is scalable, we only fall back on a fixed VF
5172     // when the TC is less than or equal to the known number of lanes.
5173     auto ClampedConstTripCount = PowerOf2Floor(ConstTripCount);
5174     LLVM_DEBUG(dbgs() << "LV: Clamping the MaxVF to maximum power of two not "
5175                          "exceeding the constant trip count: "
5176                       << ClampedConstTripCount << "\n");
5177     return ElementCount::getFixed(ClampedConstTripCount);
5178   }
5179 
5180   TargetTransformInfo::RegisterKind RegKind =
5181       ComputeScalableMaxVF ? TargetTransformInfo::RGK_ScalableVector
5182                            : TargetTransformInfo::RGK_FixedWidthVector;
5183   ElementCount MaxVF = MaxVectorElementCount;
5184   if (MaximizeBandwidth || (MaximizeBandwidth.getNumOccurrences() == 0 &&
5185                             TTI.shouldMaximizeVectorBandwidth(RegKind))) {
5186     auto MaxVectorElementCountMaxBW = ElementCount::get(
5187         PowerOf2Floor(WidestRegister.getKnownMinSize() / SmallestType),
5188         ComputeScalableMaxVF);
5189     MaxVectorElementCountMaxBW = MinVF(MaxVectorElementCountMaxBW, MaxSafeVF);
5190 
5191     // Collect all viable vectorization factors larger than the default MaxVF
5192     // (i.e. MaxVectorElementCount).
5193     SmallVector<ElementCount, 8> VFs;
5194     for (ElementCount VS = MaxVectorElementCount * 2;
5195          ElementCount::isKnownLE(VS, MaxVectorElementCountMaxBW); VS *= 2)
5196       VFs.push_back(VS);
5197 
5198     // For each VF calculate its register usage.
5199     auto RUs = calculateRegisterUsage(VFs);
5200 
5201     // Select the largest VF which doesn't require more registers than existing
5202     // ones.
5203     for (int i = RUs.size() - 1; i >= 0; --i) {
5204       bool Selected = true;
5205       for (auto &pair : RUs[i].MaxLocalUsers) {
5206         unsigned TargetNumRegisters = TTI.getNumberOfRegisters(pair.first);
5207         if (pair.second > TargetNumRegisters)
5208           Selected = false;
5209       }
5210       if (Selected) {
5211         MaxVF = VFs[i];
5212         break;
5213       }
5214     }
5215     if (ElementCount MinVF =
5216             TTI.getMinimumVF(SmallestType, ComputeScalableMaxVF)) {
5217       if (ElementCount::isKnownLT(MaxVF, MinVF)) {
5218         LLVM_DEBUG(dbgs() << "LV: Overriding calculated MaxVF(" << MaxVF
5219                           << ") with target's minimum: " << MinVF << '\n');
5220         MaxVF = MinVF;
5221       }
5222     }
5223 
5224     // Invalidate any widening decisions we might have made, in case the loop
5225     // requires prediction (decided later), but we have already made some
5226     // load/store widening decisions.
5227     invalidateCostModelingDecisions();
5228   }
5229   return MaxVF;
5230 }
5231 
5232 Optional<unsigned> LoopVectorizationCostModel::getVScaleForTuning() const {
5233   if (TheFunction->hasFnAttribute(Attribute::VScaleRange)) {
5234     auto Attr = TheFunction->getFnAttribute(Attribute::VScaleRange);
5235     auto Min = Attr.getVScaleRangeMin();
5236     auto Max = Attr.getVScaleRangeMax();
5237     if (Max && Min == Max)
5238       return Max;
5239   }
5240 
5241   return TTI.getVScaleForTuning();
5242 }
5243 
5244 bool LoopVectorizationCostModel::isMoreProfitable(
5245     const VectorizationFactor &A, const VectorizationFactor &B) const {
5246   InstructionCost CostA = A.Cost;
5247   InstructionCost CostB = B.Cost;
5248 
5249   unsigned MaxTripCount = PSE.getSE()->getSmallConstantMaxTripCount(TheLoop);
5250 
5251   if (!A.Width.isScalable() && !B.Width.isScalable() && FoldTailByMasking &&
5252       MaxTripCount) {
5253     // If we are folding the tail and the trip count is a known (possibly small)
5254     // constant, the trip count will be rounded up to an integer number of
5255     // iterations. The total cost will be PerIterationCost*ceil(TripCount/VF),
5256     // which we compare directly. When not folding the tail, the total cost will
5257     // be PerIterationCost*floor(TC/VF) + Scalar remainder cost, and so is
5258     // approximated with the per-lane cost below instead of using the tripcount
5259     // as here.
5260     auto RTCostA = CostA * divideCeil(MaxTripCount, A.Width.getFixedValue());
5261     auto RTCostB = CostB * divideCeil(MaxTripCount, B.Width.getFixedValue());
5262     return RTCostA < RTCostB;
5263   }
5264 
5265   // Improve estimate for the vector width if it is scalable.
5266   unsigned EstimatedWidthA = A.Width.getKnownMinValue();
5267   unsigned EstimatedWidthB = B.Width.getKnownMinValue();
5268   if (Optional<unsigned> VScale = getVScaleForTuning()) {
5269     if (A.Width.isScalable())
5270       EstimatedWidthA *= VScale.value();
5271     if (B.Width.isScalable())
5272       EstimatedWidthB *= VScale.value();
5273   }
5274 
5275   // Assume vscale may be larger than 1 (or the value being tuned for),
5276   // so that scalable vectorization is slightly favorable over fixed-width
5277   // vectorization.
5278   if (A.Width.isScalable() && !B.Width.isScalable())
5279     return (CostA * B.Width.getFixedValue()) <= (CostB * EstimatedWidthA);
5280 
5281   // To avoid the need for FP division:
5282   //      (CostA / A.Width) < (CostB / B.Width)
5283   // <=>  (CostA * B.Width) < (CostB * A.Width)
5284   return (CostA * EstimatedWidthB) < (CostB * EstimatedWidthA);
5285 }
5286 
5287 VectorizationFactor LoopVectorizationCostModel::selectVectorizationFactor(
5288     const ElementCountSet &VFCandidates) {
5289   InstructionCost ExpectedCost = expectedCost(ElementCount::getFixed(1)).first;
5290   LLVM_DEBUG(dbgs() << "LV: Scalar loop costs: " << ExpectedCost << ".\n");
5291   assert(ExpectedCost.isValid() && "Unexpected invalid cost for scalar loop");
5292   assert(VFCandidates.count(ElementCount::getFixed(1)) &&
5293          "Expected Scalar VF to be a candidate");
5294 
5295   const VectorizationFactor ScalarCost(ElementCount::getFixed(1), ExpectedCost,
5296                                        ExpectedCost);
5297   VectorizationFactor ChosenFactor = ScalarCost;
5298 
5299   bool ForceVectorization = Hints->getForce() == LoopVectorizeHints::FK_Enabled;
5300   if (ForceVectorization && VFCandidates.size() > 1) {
5301     // Ignore scalar width, because the user explicitly wants vectorization.
5302     // Initialize cost to max so that VF = 2 is, at least, chosen during cost
5303     // evaluation.
5304     ChosenFactor.Cost = InstructionCost::getMax();
5305   }
5306 
5307   SmallVector<InstructionVFPair> InvalidCosts;
5308   for (const auto &i : VFCandidates) {
5309     // The cost for scalar VF=1 is already calculated, so ignore it.
5310     if (i.isScalar())
5311       continue;
5312 
5313     VectorizationCostTy C = expectedCost(i, &InvalidCosts);
5314     VectorizationFactor Candidate(i, C.first, ScalarCost.ScalarCost);
5315 
5316 #ifndef NDEBUG
5317     unsigned AssumedMinimumVscale = 1;
5318     if (Optional<unsigned> VScale = getVScaleForTuning())
5319       AssumedMinimumVscale = *VScale;
5320     unsigned Width =
5321         Candidate.Width.isScalable()
5322             ? Candidate.Width.getKnownMinValue() * AssumedMinimumVscale
5323             : Candidate.Width.getFixedValue();
5324     LLVM_DEBUG(dbgs() << "LV: Vector loop of width " << i
5325                       << " costs: " << (Candidate.Cost / Width));
5326     if (i.isScalable())
5327       LLVM_DEBUG(dbgs() << " (assuming a minimum vscale of "
5328                         << AssumedMinimumVscale << ")");
5329     LLVM_DEBUG(dbgs() << ".\n");
5330 #endif
5331 
5332     if (!C.second && !ForceVectorization) {
5333       LLVM_DEBUG(
5334           dbgs() << "LV: Not considering vector loop of width " << i
5335                  << " because it will not generate any vector instructions.\n");
5336       continue;
5337     }
5338 
5339     // If profitable add it to ProfitableVF list.
5340     if (isMoreProfitable(Candidate, ScalarCost))
5341       ProfitableVFs.push_back(Candidate);
5342 
5343     if (isMoreProfitable(Candidate, ChosenFactor))
5344       ChosenFactor = Candidate;
5345   }
5346 
5347   // Emit a report of VFs with invalid costs in the loop.
5348   if (!InvalidCosts.empty()) {
5349     // Group the remarks per instruction, keeping the instruction order from
5350     // InvalidCosts.
5351     std::map<Instruction *, unsigned> Numbering;
5352     unsigned I = 0;
5353     for (auto &Pair : InvalidCosts)
5354       if (!Numbering.count(Pair.first))
5355         Numbering[Pair.first] = I++;
5356 
5357     // Sort the list, first on instruction(number) then on VF.
5358     llvm::sort(InvalidCosts,
5359                [&Numbering](InstructionVFPair &A, InstructionVFPair &B) {
5360                  if (Numbering[A.first] != Numbering[B.first])
5361                    return Numbering[A.first] < Numbering[B.first];
5362                  ElementCountComparator ECC;
5363                  return ECC(A.second, B.second);
5364                });
5365 
5366     // For a list of ordered instruction-vf pairs:
5367     //   [(load, vf1), (load, vf2), (store, vf1)]
5368     // Group the instructions together to emit separate remarks for:
5369     //   load  (vf1, vf2)
5370     //   store (vf1)
5371     auto Tail = ArrayRef<InstructionVFPair>(InvalidCosts);
5372     auto Subset = ArrayRef<InstructionVFPair>();
5373     do {
5374       if (Subset.empty())
5375         Subset = Tail.take_front(1);
5376 
5377       Instruction *I = Subset.front().first;
5378 
5379       // If the next instruction is different, or if there are no other pairs,
5380       // emit a remark for the collated subset. e.g.
5381       //   [(load, vf1), (load, vf2))]
5382       // to emit:
5383       //  remark: invalid costs for 'load' at VF=(vf, vf2)
5384       if (Subset == Tail || Tail[Subset.size()].first != I) {
5385         std::string OutString;
5386         raw_string_ostream OS(OutString);
5387         assert(!Subset.empty() && "Unexpected empty range");
5388         OS << "Instruction with invalid costs prevented vectorization at VF=(";
5389         for (auto &Pair : Subset)
5390           OS << (Pair.second == Subset.front().second ? "" : ", ")
5391              << Pair.second;
5392         OS << "):";
5393         if (auto *CI = dyn_cast<CallInst>(I))
5394           OS << " call to " << CI->getCalledFunction()->getName();
5395         else
5396           OS << " " << I->getOpcodeName();
5397         OS.flush();
5398         reportVectorizationInfo(OutString, "InvalidCost", ORE, TheLoop, I);
5399         Tail = Tail.drop_front(Subset.size());
5400         Subset = {};
5401       } else
5402         // Grow the subset by one element
5403         Subset = Tail.take_front(Subset.size() + 1);
5404     } while (!Tail.empty());
5405   }
5406 
5407   if (!EnableCondStoresVectorization && NumPredStores) {
5408     reportVectorizationFailure("There are conditional stores.",
5409         "store that is conditionally executed prevents vectorization",
5410         "ConditionalStore", ORE, TheLoop);
5411     ChosenFactor = ScalarCost;
5412   }
5413 
5414   LLVM_DEBUG(if (ForceVectorization && !ChosenFactor.Width.isScalar() &&
5415                  !isMoreProfitable(ChosenFactor, ScalarCost)) dbgs()
5416              << "LV: Vectorization seems to be not beneficial, "
5417              << "but was forced by a user.\n");
5418   LLVM_DEBUG(dbgs() << "LV: Selecting VF: " << ChosenFactor.Width << ".\n");
5419   return ChosenFactor;
5420 }
5421 
5422 bool LoopVectorizationCostModel::isCandidateForEpilogueVectorization(
5423     const Loop &L, ElementCount VF) const {
5424   // Cross iteration phis such as reductions need special handling and are
5425   // currently unsupported.
5426   if (any_of(L.getHeader()->phis(),
5427              [&](PHINode &Phi) { return Legal->isFirstOrderRecurrence(&Phi); }))
5428     return false;
5429 
5430   // Phis with uses outside of the loop require special handling and are
5431   // currently unsupported.
5432   for (auto &Entry : Legal->getInductionVars()) {
5433     // Look for uses of the value of the induction at the last iteration.
5434     Value *PostInc = Entry.first->getIncomingValueForBlock(L.getLoopLatch());
5435     for (User *U : PostInc->users())
5436       if (!L.contains(cast<Instruction>(U)))
5437         return false;
5438     // Look for uses of penultimate value of the induction.
5439     for (User *U : Entry.first->users())
5440       if (!L.contains(cast<Instruction>(U)))
5441         return false;
5442   }
5443 
5444   // Induction variables that are widened require special handling that is
5445   // currently not supported.
5446   if (any_of(Legal->getInductionVars(), [&](auto &Entry) {
5447         return !(this->isScalarAfterVectorization(Entry.first, VF) ||
5448                  this->isProfitableToScalarize(Entry.first, VF));
5449       }))
5450     return false;
5451 
5452   // Epilogue vectorization code has not been auditted to ensure it handles
5453   // non-latch exits properly.  It may be fine, but it needs auditted and
5454   // tested.
5455   if (L.getExitingBlock() != L.getLoopLatch())
5456     return false;
5457 
5458   return true;
5459 }
5460 
5461 bool LoopVectorizationCostModel::isEpilogueVectorizationProfitable(
5462     const ElementCount VF) const {
5463   // FIXME: We need a much better cost-model to take different parameters such
5464   // as register pressure, code size increase and cost of extra branches into
5465   // account. For now we apply a very crude heuristic and only consider loops
5466   // with vectorization factors larger than a certain value.
5467   // We also consider epilogue vectorization unprofitable for targets that don't
5468   // consider interleaving beneficial (eg. MVE).
5469   if (TTI.getMaxInterleaveFactor(VF.getKnownMinValue()) <= 1)
5470     return false;
5471   // FIXME: We should consider changing the threshold for scalable
5472   // vectors to take VScaleForTuning into account.
5473   if (VF.getKnownMinValue() >= EpilogueVectorizationMinVF)
5474     return true;
5475   return false;
5476 }
5477 
5478 VectorizationFactor
5479 LoopVectorizationCostModel::selectEpilogueVectorizationFactor(
5480     const ElementCount MainLoopVF, const LoopVectorizationPlanner &LVP) {
5481   VectorizationFactor Result = VectorizationFactor::Disabled();
5482   if (!EnableEpilogueVectorization) {
5483     LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization is disabled.\n";);
5484     return Result;
5485   }
5486 
5487   if (!isScalarEpilogueAllowed()) {
5488     LLVM_DEBUG(
5489         dbgs() << "LEV: Unable to vectorize epilogue because no epilogue is "
5490                   "allowed.\n";);
5491     return Result;
5492   }
5493 
5494   // Not really a cost consideration, but check for unsupported cases here to
5495   // simplify the logic.
5496   if (!isCandidateForEpilogueVectorization(*TheLoop, MainLoopVF)) {
5497     LLVM_DEBUG(
5498         dbgs() << "LEV: Unable to vectorize epilogue because the loop is "
5499                   "not a supported candidate.\n";);
5500     return Result;
5501   }
5502 
5503   if (EpilogueVectorizationForceVF > 1) {
5504     LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization factor is forced.\n";);
5505     ElementCount ForcedEC = ElementCount::getFixed(EpilogueVectorizationForceVF);
5506     if (LVP.hasPlanWithVF(ForcedEC))
5507       return {ForcedEC, 0, 0};
5508     else {
5509       LLVM_DEBUG(
5510           dbgs()
5511               << "LEV: Epilogue vectorization forced factor is not viable.\n";);
5512       return Result;
5513     }
5514   }
5515 
5516   if (TheLoop->getHeader()->getParent()->hasOptSize() ||
5517       TheLoop->getHeader()->getParent()->hasMinSize()) {
5518     LLVM_DEBUG(
5519         dbgs()
5520             << "LEV: Epilogue vectorization skipped due to opt for size.\n";);
5521     return Result;
5522   }
5523 
5524   if (!isEpilogueVectorizationProfitable(MainLoopVF)) {
5525     LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization is not profitable for "
5526                          "this loop\n");
5527     return Result;
5528   }
5529 
5530   // If MainLoopVF = vscale x 2, and vscale is expected to be 4, then we know
5531   // the main loop handles 8 lanes per iteration. We could still benefit from
5532   // vectorizing the epilogue loop with VF=4.
5533   ElementCount EstimatedRuntimeVF = MainLoopVF;
5534   if (MainLoopVF.isScalable()) {
5535     EstimatedRuntimeVF = ElementCount::getFixed(MainLoopVF.getKnownMinValue());
5536     if (Optional<unsigned> VScale = getVScaleForTuning())
5537       EstimatedRuntimeVF *= *VScale;
5538   }
5539 
5540   for (auto &NextVF : ProfitableVFs)
5541     if (((!NextVF.Width.isScalable() && MainLoopVF.isScalable() &&
5542           ElementCount::isKnownLT(NextVF.Width, EstimatedRuntimeVF)) ||
5543          ElementCount::isKnownLT(NextVF.Width, MainLoopVF)) &&
5544         (Result.Width.isScalar() || isMoreProfitable(NextVF, Result)) &&
5545         LVP.hasPlanWithVF(NextVF.Width))
5546       Result = NextVF;
5547 
5548   if (Result != VectorizationFactor::Disabled())
5549     LLVM_DEBUG(dbgs() << "LEV: Vectorizing epilogue loop with VF = "
5550                       << Result.Width << "\n";);
5551   return Result;
5552 }
5553 
5554 std::pair<unsigned, unsigned>
5555 LoopVectorizationCostModel::getSmallestAndWidestTypes() {
5556   unsigned MinWidth = -1U;
5557   unsigned MaxWidth = 8;
5558   const DataLayout &DL = TheFunction->getParent()->getDataLayout();
5559   // For in-loop reductions, no element types are added to ElementTypesInLoop
5560   // if there are no loads/stores in the loop. In this case, check through the
5561   // reduction variables to determine the maximum width.
5562   if (ElementTypesInLoop.empty() && !Legal->getReductionVars().empty()) {
5563     // Reset MaxWidth so that we can find the smallest type used by recurrences
5564     // in the loop.
5565     MaxWidth = -1U;
5566     for (auto &PhiDescriptorPair : Legal->getReductionVars()) {
5567       const RecurrenceDescriptor &RdxDesc = PhiDescriptorPair.second;
5568       // When finding the min width used by the recurrence we need to account
5569       // for casts on the input operands of the recurrence.
5570       MaxWidth = std::min<unsigned>(
5571           MaxWidth, std::min<unsigned>(
5572                         RdxDesc.getMinWidthCastToRecurrenceTypeInBits(),
5573                         RdxDesc.getRecurrenceType()->getScalarSizeInBits()));
5574     }
5575   } else {
5576     for (Type *T : ElementTypesInLoop) {
5577       MinWidth = std::min<unsigned>(
5578           MinWidth, DL.getTypeSizeInBits(T->getScalarType()).getFixedSize());
5579       MaxWidth = std::max<unsigned>(
5580           MaxWidth, DL.getTypeSizeInBits(T->getScalarType()).getFixedSize());
5581     }
5582   }
5583   return {MinWidth, MaxWidth};
5584 }
5585 
5586 void LoopVectorizationCostModel::collectElementTypesForWidening() {
5587   ElementTypesInLoop.clear();
5588   // For each block.
5589   for (BasicBlock *BB : TheLoop->blocks()) {
5590     // For each instruction in the loop.
5591     for (Instruction &I : BB->instructionsWithoutDebug()) {
5592       Type *T = I.getType();
5593 
5594       // Skip ignored values.
5595       if (ValuesToIgnore.count(&I))
5596         continue;
5597 
5598       // Only examine Loads, Stores and PHINodes.
5599       if (!isa<LoadInst>(I) && !isa<StoreInst>(I) && !isa<PHINode>(I))
5600         continue;
5601 
5602       // Examine PHI nodes that are reduction variables. Update the type to
5603       // account for the recurrence type.
5604       if (auto *PN = dyn_cast<PHINode>(&I)) {
5605         if (!Legal->isReductionVariable(PN))
5606           continue;
5607         const RecurrenceDescriptor &RdxDesc =
5608             Legal->getReductionVars().find(PN)->second;
5609         if (PreferInLoopReductions || useOrderedReductions(RdxDesc) ||
5610             TTI.preferInLoopReduction(RdxDesc.getOpcode(),
5611                                       RdxDesc.getRecurrenceType(),
5612                                       TargetTransformInfo::ReductionFlags()))
5613           continue;
5614         T = RdxDesc.getRecurrenceType();
5615       }
5616 
5617       // Examine the stored values.
5618       if (auto *ST = dyn_cast<StoreInst>(&I))
5619         T = ST->getValueOperand()->getType();
5620 
5621       assert(T->isSized() &&
5622              "Expected the load/store/recurrence type to be sized");
5623 
5624       ElementTypesInLoop.insert(T);
5625     }
5626   }
5627 }
5628 
5629 unsigned LoopVectorizationCostModel::selectInterleaveCount(ElementCount VF,
5630                                                            unsigned LoopCost) {
5631   // -- The interleave heuristics --
5632   // We interleave the loop in order to expose ILP and reduce the loop overhead.
5633   // There are many micro-architectural considerations that we can't predict
5634   // at this level. For example, frontend pressure (on decode or fetch) due to
5635   // code size, or the number and capabilities of the execution ports.
5636   //
5637   // We use the following heuristics to select the interleave count:
5638   // 1. If the code has reductions, then we interleave to break the cross
5639   // iteration dependency.
5640   // 2. If the loop is really small, then we interleave to reduce the loop
5641   // overhead.
5642   // 3. We don't interleave if we think that we will spill registers to memory
5643   // due to the increased register pressure.
5644 
5645   if (!isScalarEpilogueAllowed())
5646     return 1;
5647 
5648   // We used the distance for the interleave count.
5649   if (Legal->getMaxSafeDepDistBytes() != -1U)
5650     return 1;
5651 
5652   auto BestKnownTC = getSmallBestKnownTC(*PSE.getSE(), TheLoop);
5653   const bool HasReductions = !Legal->getReductionVars().empty();
5654   // Do not interleave loops with a relatively small known or estimated trip
5655   // count. But we will interleave when InterleaveSmallLoopScalarReduction is
5656   // enabled, and the code has scalar reductions(HasReductions && VF = 1),
5657   // because with the above conditions interleaving can expose ILP and break
5658   // cross iteration dependences for reductions.
5659   if (BestKnownTC && (*BestKnownTC < TinyTripCountInterleaveThreshold) &&
5660       !(InterleaveSmallLoopScalarReduction && HasReductions && VF.isScalar()))
5661     return 1;
5662 
5663   // If we did not calculate the cost for VF (because the user selected the VF)
5664   // then we calculate the cost of VF here.
5665   if (LoopCost == 0) {
5666     InstructionCost C = expectedCost(VF).first;
5667     assert(C.isValid() && "Expected to have chosen a VF with valid cost");
5668     LoopCost = *C.getValue();
5669 
5670     // Loop body is free and there is no need for interleaving.
5671     if (LoopCost == 0)
5672       return 1;
5673   }
5674 
5675   RegisterUsage R = calculateRegisterUsage({VF})[0];
5676   // We divide by these constants so assume that we have at least one
5677   // instruction that uses at least one register.
5678   for (auto& pair : R.MaxLocalUsers) {
5679     pair.second = std::max(pair.second, 1U);
5680   }
5681 
5682   // We calculate the interleave count using the following formula.
5683   // Subtract the number of loop invariants from the number of available
5684   // registers. These registers are used by all of the interleaved instances.
5685   // Next, divide the remaining registers by the number of registers that is
5686   // required by the loop, in order to estimate how many parallel instances
5687   // fit without causing spills. All of this is rounded down if necessary to be
5688   // a power of two. We want power of two interleave count to simplify any
5689   // addressing operations or alignment considerations.
5690   // We also want power of two interleave counts to ensure that the induction
5691   // variable of the vector loop wraps to zero, when tail is folded by masking;
5692   // this currently happens when OptForSize, in which case IC is set to 1 above.
5693   unsigned IC = UINT_MAX;
5694 
5695   for (auto& pair : R.MaxLocalUsers) {
5696     unsigned TargetNumRegisters = TTI.getNumberOfRegisters(pair.first);
5697     LLVM_DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters
5698                       << " registers of "
5699                       << TTI.getRegisterClassName(pair.first) << " register class\n");
5700     if (VF.isScalar()) {
5701       if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
5702         TargetNumRegisters = ForceTargetNumScalarRegs;
5703     } else {
5704       if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
5705         TargetNumRegisters = ForceTargetNumVectorRegs;
5706     }
5707     unsigned MaxLocalUsers = pair.second;
5708     unsigned LoopInvariantRegs = 0;
5709     if (R.LoopInvariantRegs.find(pair.first) != R.LoopInvariantRegs.end())
5710       LoopInvariantRegs = R.LoopInvariantRegs[pair.first];
5711 
5712     unsigned TmpIC = PowerOf2Floor((TargetNumRegisters - LoopInvariantRegs) / MaxLocalUsers);
5713     // Don't count the induction variable as interleaved.
5714     if (EnableIndVarRegisterHeur) {
5715       TmpIC =
5716           PowerOf2Floor((TargetNumRegisters - LoopInvariantRegs - 1) /
5717                         std::max(1U, (MaxLocalUsers - 1)));
5718     }
5719 
5720     IC = std::min(IC, TmpIC);
5721   }
5722 
5723   // Clamp the interleave ranges to reasonable counts.
5724   unsigned MaxInterleaveCount =
5725       TTI.getMaxInterleaveFactor(VF.getKnownMinValue());
5726 
5727   // Check if the user has overridden the max.
5728   if (VF.isScalar()) {
5729     if (ForceTargetMaxScalarInterleaveFactor.getNumOccurrences() > 0)
5730       MaxInterleaveCount = ForceTargetMaxScalarInterleaveFactor;
5731   } else {
5732     if (ForceTargetMaxVectorInterleaveFactor.getNumOccurrences() > 0)
5733       MaxInterleaveCount = ForceTargetMaxVectorInterleaveFactor;
5734   }
5735 
5736   // If trip count is known or estimated compile time constant, limit the
5737   // interleave count to be less than the trip count divided by VF, provided it
5738   // is at least 1.
5739   //
5740   // For scalable vectors we can't know if interleaving is beneficial. It may
5741   // not be beneficial for small loops if none of the lanes in the second vector
5742   // iterations is enabled. However, for larger loops, there is likely to be a
5743   // similar benefit as for fixed-width vectors. For now, we choose to leave
5744   // the InterleaveCount as if vscale is '1', although if some information about
5745   // the vector is known (e.g. min vector size), we can make a better decision.
5746   if (BestKnownTC) {
5747     MaxInterleaveCount =
5748         std::min(*BestKnownTC / VF.getKnownMinValue(), MaxInterleaveCount);
5749     // Make sure MaxInterleaveCount is greater than 0.
5750     MaxInterleaveCount = std::max(1u, MaxInterleaveCount);
5751   }
5752 
5753   assert(MaxInterleaveCount > 0 &&
5754          "Maximum interleave count must be greater than 0");
5755 
5756   // Clamp the calculated IC to be between the 1 and the max interleave count
5757   // that the target and trip count allows.
5758   if (IC > MaxInterleaveCount)
5759     IC = MaxInterleaveCount;
5760   else
5761     // Make sure IC is greater than 0.
5762     IC = std::max(1u, IC);
5763 
5764   assert(IC > 0 && "Interleave count must be greater than 0.");
5765 
5766   // Interleave if we vectorized this loop and there is a reduction that could
5767   // benefit from interleaving.
5768   if (VF.isVector() && HasReductions) {
5769     LLVM_DEBUG(dbgs() << "LV: Interleaving because of reductions.\n");
5770     return IC;
5771   }
5772 
5773   // For any scalar loop that either requires runtime checks or predication we
5774   // are better off leaving this to the unroller. Note that if we've already
5775   // vectorized the loop we will have done the runtime check and so interleaving
5776   // won't require further checks.
5777   bool ScalarInterleavingRequiresPredication =
5778       (VF.isScalar() && any_of(TheLoop->blocks(), [this](BasicBlock *BB) {
5779          return Legal->blockNeedsPredication(BB);
5780        }));
5781   bool ScalarInterleavingRequiresRuntimePointerCheck =
5782       (VF.isScalar() && Legal->getRuntimePointerChecking()->Need);
5783 
5784   // We want to interleave small loops in order to reduce the loop overhead and
5785   // potentially expose ILP opportunities.
5786   LLVM_DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n'
5787                     << "LV: IC is " << IC << '\n'
5788                     << "LV: VF is " << VF << '\n');
5789   const bool AggressivelyInterleaveReductions =
5790       TTI.enableAggressiveInterleaving(HasReductions);
5791   if (!ScalarInterleavingRequiresRuntimePointerCheck &&
5792       !ScalarInterleavingRequiresPredication && LoopCost < SmallLoopCost) {
5793     // We assume that the cost overhead is 1 and we use the cost model
5794     // to estimate the cost of the loop and interleave until the cost of the
5795     // loop overhead is about 5% of the cost of the loop.
5796     unsigned SmallIC =
5797         std::min(IC, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost));
5798 
5799     // Interleave until store/load ports (estimated by max interleave count) are
5800     // saturated.
5801     unsigned NumStores = Legal->getNumStores();
5802     unsigned NumLoads = Legal->getNumLoads();
5803     unsigned StoresIC = IC / (NumStores ? NumStores : 1);
5804     unsigned LoadsIC = IC / (NumLoads ? NumLoads : 1);
5805 
5806     // There is little point in interleaving for reductions containing selects
5807     // and compares when VF=1 since it may just create more overhead than it's
5808     // worth for loops with small trip counts. This is because we still have to
5809     // do the final reduction after the loop.
5810     bool HasSelectCmpReductions =
5811         HasReductions &&
5812         any_of(Legal->getReductionVars(), [&](auto &Reduction) -> bool {
5813           const RecurrenceDescriptor &RdxDesc = Reduction.second;
5814           return RecurrenceDescriptor::isSelectCmpRecurrenceKind(
5815               RdxDesc.getRecurrenceKind());
5816         });
5817     if (HasSelectCmpReductions) {
5818       LLVM_DEBUG(dbgs() << "LV: Not interleaving select-cmp reductions.\n");
5819       return 1;
5820     }
5821 
5822     // If we have a scalar reduction (vector reductions are already dealt with
5823     // by this point), we can increase the critical path length if the loop
5824     // we're interleaving is inside another loop. For tree-wise reductions
5825     // set the limit to 2, and for ordered reductions it's best to disable
5826     // interleaving entirely.
5827     if (HasReductions && TheLoop->getLoopDepth() > 1) {
5828       bool HasOrderedReductions =
5829           any_of(Legal->getReductionVars(), [&](auto &Reduction) -> bool {
5830             const RecurrenceDescriptor &RdxDesc = Reduction.second;
5831             return RdxDesc.isOrdered();
5832           });
5833       if (HasOrderedReductions) {
5834         LLVM_DEBUG(
5835             dbgs() << "LV: Not interleaving scalar ordered reductions.\n");
5836         return 1;
5837       }
5838 
5839       unsigned F = static_cast<unsigned>(MaxNestedScalarReductionIC);
5840       SmallIC = std::min(SmallIC, F);
5841       StoresIC = std::min(StoresIC, F);
5842       LoadsIC = std::min(LoadsIC, F);
5843     }
5844 
5845     if (EnableLoadStoreRuntimeInterleave &&
5846         std::max(StoresIC, LoadsIC) > SmallIC) {
5847       LLVM_DEBUG(
5848           dbgs() << "LV: Interleaving to saturate store or load ports.\n");
5849       return std::max(StoresIC, LoadsIC);
5850     }
5851 
5852     // If there are scalar reductions and TTI has enabled aggressive
5853     // interleaving for reductions, we will interleave to expose ILP.
5854     if (InterleaveSmallLoopScalarReduction && VF.isScalar() &&
5855         AggressivelyInterleaveReductions) {
5856       LLVM_DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
5857       // Interleave no less than SmallIC but not as aggressive as the normal IC
5858       // to satisfy the rare situation when resources are too limited.
5859       return std::max(IC / 2, SmallIC);
5860     } else {
5861       LLVM_DEBUG(dbgs() << "LV: Interleaving to reduce branch cost.\n");
5862       return SmallIC;
5863     }
5864   }
5865 
5866   // Interleave if this is a large loop (small loops are already dealt with by
5867   // this point) that could benefit from interleaving.
5868   if (AggressivelyInterleaveReductions) {
5869     LLVM_DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
5870     return IC;
5871   }
5872 
5873   LLVM_DEBUG(dbgs() << "LV: Not Interleaving.\n");
5874   return 1;
5875 }
5876 
5877 SmallVector<LoopVectorizationCostModel::RegisterUsage, 8>
5878 LoopVectorizationCostModel::calculateRegisterUsage(ArrayRef<ElementCount> VFs) {
5879   // This function calculates the register usage by measuring the highest number
5880   // of values that are alive at a single location. Obviously, this is a very
5881   // rough estimation. We scan the loop in a topological order in order and
5882   // assign a number to each instruction. We use RPO to ensure that defs are
5883   // met before their users. We assume that each instruction that has in-loop
5884   // users starts an interval. We record every time that an in-loop value is
5885   // used, so we have a list of the first and last occurrences of each
5886   // instruction. Next, we transpose this data structure into a multi map that
5887   // holds the list of intervals that *end* at a specific location. This multi
5888   // map allows us to perform a linear search. We scan the instructions linearly
5889   // and record each time that a new interval starts, by placing it in a set.
5890   // If we find this value in the multi-map then we remove it from the set.
5891   // The max register usage is the maximum size of the set.
5892   // We also search for instructions that are defined outside the loop, but are
5893   // used inside the loop. We need this number separately from the max-interval
5894   // usage number because when we unroll, loop-invariant values do not take
5895   // more register.
5896   LoopBlocksDFS DFS(TheLoop);
5897   DFS.perform(LI);
5898 
5899   RegisterUsage RU;
5900 
5901   // Each 'key' in the map opens a new interval. The values
5902   // of the map are the index of the 'last seen' usage of the
5903   // instruction that is the key.
5904   using IntervalMap = DenseMap<Instruction *, unsigned>;
5905 
5906   // Maps instruction to its index.
5907   SmallVector<Instruction *, 64> IdxToInstr;
5908   // Marks the end of each interval.
5909   IntervalMap EndPoint;
5910   // Saves the list of instruction indices that are used in the loop.
5911   SmallPtrSet<Instruction *, 8> Ends;
5912   // Saves the list of values that are used in the loop but are
5913   // defined outside the loop, such as arguments and constants.
5914   SmallPtrSet<Value *, 8> LoopInvariants;
5915 
5916   for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) {
5917     for (Instruction &I : BB->instructionsWithoutDebug()) {
5918       IdxToInstr.push_back(&I);
5919 
5920       // Save the end location of each USE.
5921       for (Value *U : I.operands()) {
5922         auto *Instr = dyn_cast<Instruction>(U);
5923 
5924         // Ignore non-instruction values such as arguments, constants, etc.
5925         if (!Instr)
5926           continue;
5927 
5928         // If this instruction is outside the loop then record it and continue.
5929         if (!TheLoop->contains(Instr)) {
5930           LoopInvariants.insert(Instr);
5931           continue;
5932         }
5933 
5934         // Overwrite previous end points.
5935         EndPoint[Instr] = IdxToInstr.size();
5936         Ends.insert(Instr);
5937       }
5938     }
5939   }
5940 
5941   // Saves the list of intervals that end with the index in 'key'.
5942   using InstrList = SmallVector<Instruction *, 2>;
5943   DenseMap<unsigned, InstrList> TransposeEnds;
5944 
5945   // Transpose the EndPoints to a list of values that end at each index.
5946   for (auto &Interval : EndPoint)
5947     TransposeEnds[Interval.second].push_back(Interval.first);
5948 
5949   SmallPtrSet<Instruction *, 8> OpenIntervals;
5950   SmallVector<RegisterUsage, 8> RUs(VFs.size());
5951   SmallVector<SmallMapVector<unsigned, unsigned, 4>, 8> MaxUsages(VFs.size());
5952 
5953   LLVM_DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
5954 
5955   const auto &TTICapture = TTI;
5956   auto GetRegUsage = [&TTICapture](Type *Ty, ElementCount VF) -> unsigned {
5957     if (Ty->isTokenTy() || !VectorType::isValidElementType(Ty))
5958       return 0;
5959     return TTICapture.getRegUsageForType(VectorType::get(Ty, VF));
5960   };
5961 
5962   for (unsigned int i = 0, s = IdxToInstr.size(); i < s; ++i) {
5963     Instruction *I = IdxToInstr[i];
5964 
5965     // Remove all of the instructions that end at this location.
5966     InstrList &List = TransposeEnds[i];
5967     for (Instruction *ToRemove : List)
5968       OpenIntervals.erase(ToRemove);
5969 
5970     // Ignore instructions that are never used within the loop.
5971     if (!Ends.count(I))
5972       continue;
5973 
5974     // Skip ignored values.
5975     if (ValuesToIgnore.count(I))
5976       continue;
5977 
5978     // For each VF find the maximum usage of registers.
5979     for (unsigned j = 0, e = VFs.size(); j < e; ++j) {
5980       // Count the number of live intervals.
5981       SmallMapVector<unsigned, unsigned, 4> RegUsage;
5982 
5983       if (VFs[j].isScalar()) {
5984         for (auto Inst : OpenIntervals) {
5985           unsigned ClassID = TTI.getRegisterClassForType(false, Inst->getType());
5986           if (RegUsage.find(ClassID) == RegUsage.end())
5987             RegUsage[ClassID] = 1;
5988           else
5989             RegUsage[ClassID] += 1;
5990         }
5991       } else {
5992         collectUniformsAndScalars(VFs[j]);
5993         for (auto Inst : OpenIntervals) {
5994           // Skip ignored values for VF > 1.
5995           if (VecValuesToIgnore.count(Inst))
5996             continue;
5997           if (isScalarAfterVectorization(Inst, VFs[j])) {
5998             unsigned ClassID = TTI.getRegisterClassForType(false, Inst->getType());
5999             if (RegUsage.find(ClassID) == RegUsage.end())
6000               RegUsage[ClassID] = 1;
6001             else
6002               RegUsage[ClassID] += 1;
6003           } else {
6004             unsigned ClassID = TTI.getRegisterClassForType(true, Inst->getType());
6005             if (RegUsage.find(ClassID) == RegUsage.end())
6006               RegUsage[ClassID] = GetRegUsage(Inst->getType(), VFs[j]);
6007             else
6008               RegUsage[ClassID] += GetRegUsage(Inst->getType(), VFs[j]);
6009           }
6010         }
6011       }
6012 
6013       for (auto& pair : RegUsage) {
6014         if (MaxUsages[j].find(pair.first) != MaxUsages[j].end())
6015           MaxUsages[j][pair.first] = std::max(MaxUsages[j][pair.first], pair.second);
6016         else
6017           MaxUsages[j][pair.first] = pair.second;
6018       }
6019     }
6020 
6021     LLVM_DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # "
6022                       << OpenIntervals.size() << '\n');
6023 
6024     // Add the current instruction to the list of open intervals.
6025     OpenIntervals.insert(I);
6026   }
6027 
6028   for (unsigned i = 0, e = VFs.size(); i < e; ++i) {
6029     SmallMapVector<unsigned, unsigned, 4> Invariant;
6030 
6031     for (auto Inst : LoopInvariants) {
6032       unsigned Usage =
6033           VFs[i].isScalar() ? 1 : GetRegUsage(Inst->getType(), VFs[i]);
6034       unsigned ClassID =
6035           TTI.getRegisterClassForType(VFs[i].isVector(), Inst->getType());
6036       if (Invariant.find(ClassID) == Invariant.end())
6037         Invariant[ClassID] = Usage;
6038       else
6039         Invariant[ClassID] += Usage;
6040     }
6041 
6042     LLVM_DEBUG({
6043       dbgs() << "LV(REG): VF = " << VFs[i] << '\n';
6044       dbgs() << "LV(REG): Found max usage: " << MaxUsages[i].size()
6045              << " item\n";
6046       for (const auto &pair : MaxUsages[i]) {
6047         dbgs() << "LV(REG): RegisterClass: "
6048                << TTI.getRegisterClassName(pair.first) << ", " << pair.second
6049                << " registers\n";
6050       }
6051       dbgs() << "LV(REG): Found invariant usage: " << Invariant.size()
6052              << " item\n";
6053       for (const auto &pair : Invariant) {
6054         dbgs() << "LV(REG): RegisterClass: "
6055                << TTI.getRegisterClassName(pair.first) << ", " << pair.second
6056                << " registers\n";
6057       }
6058     });
6059 
6060     RU.LoopInvariantRegs = Invariant;
6061     RU.MaxLocalUsers = MaxUsages[i];
6062     RUs[i] = RU;
6063   }
6064 
6065   return RUs;
6066 }
6067 
6068 bool LoopVectorizationCostModel::useEmulatedMaskMemRefHack(Instruction *I,
6069                                                            ElementCount VF) {
6070   // TODO: Cost model for emulated masked load/store is completely
6071   // broken. This hack guides the cost model to use an artificially
6072   // high enough value to practically disable vectorization with such
6073   // operations, except where previously deployed legality hack allowed
6074   // using very low cost values. This is to avoid regressions coming simply
6075   // from moving "masked load/store" check from legality to cost model.
6076   // Masked Load/Gather emulation was previously never allowed.
6077   // Limited number of Masked Store/Scatter emulation was allowed.
6078   assert(isPredicatedInst(I, VF) && "Expecting a scalar emulated instruction");
6079   return isa<LoadInst>(I) ||
6080          (isa<StoreInst>(I) &&
6081           NumPredStores > NumberOfStoresToPredicate);
6082 }
6083 
6084 void LoopVectorizationCostModel::collectInstsToScalarize(ElementCount VF) {
6085   // If we aren't vectorizing the loop, or if we've already collected the
6086   // instructions to scalarize, there's nothing to do. Collection may already
6087   // have occurred if we have a user-selected VF and are now computing the
6088   // expected cost for interleaving.
6089   if (VF.isScalar() || VF.isZero() ||
6090       InstsToScalarize.find(VF) != InstsToScalarize.end())
6091     return;
6092 
6093   // Initialize a mapping for VF in InstsToScalalarize. If we find that it's
6094   // not profitable to scalarize any instructions, the presence of VF in the
6095   // map will indicate that we've analyzed it already.
6096   ScalarCostsTy &ScalarCostsVF = InstsToScalarize[VF];
6097 
6098   PredicatedBBsAfterVectorization[VF].clear();
6099 
6100   // Find all the instructions that are scalar with predication in the loop and
6101   // determine if it would be better to not if-convert the blocks they are in.
6102   // If so, we also record the instructions to scalarize.
6103   for (BasicBlock *BB : TheLoop->blocks()) {
6104     if (!blockNeedsPredicationForAnyReason(BB))
6105       continue;
6106     for (Instruction &I : *BB)
6107       if (isScalarWithPredication(&I, VF)) {
6108         ScalarCostsTy ScalarCosts;
6109         // Do not apply discount if scalable, because that would lead to
6110         // invalid scalarization costs.
6111         // Do not apply discount logic if hacked cost is needed
6112         // for emulated masked memrefs.
6113         if (!VF.isScalable() && !useEmulatedMaskMemRefHack(&I, VF) &&
6114             computePredInstDiscount(&I, ScalarCosts, VF) >= 0)
6115           ScalarCostsVF.insert(ScalarCosts.begin(), ScalarCosts.end());
6116         // Remember that BB will remain after vectorization.
6117         PredicatedBBsAfterVectorization[VF].insert(BB);
6118       }
6119   }
6120 }
6121 
6122 int LoopVectorizationCostModel::computePredInstDiscount(
6123     Instruction *PredInst, ScalarCostsTy &ScalarCosts, ElementCount VF) {
6124   assert(!isUniformAfterVectorization(PredInst, VF) &&
6125          "Instruction marked uniform-after-vectorization will be predicated");
6126 
6127   // Initialize the discount to zero, meaning that the scalar version and the
6128   // vector version cost the same.
6129   InstructionCost Discount = 0;
6130 
6131   // Holds instructions to analyze. The instructions we visit are mapped in
6132   // ScalarCosts. Those instructions are the ones that would be scalarized if
6133   // we find that the scalar version costs less.
6134   SmallVector<Instruction *, 8> Worklist;
6135 
6136   // Returns true if the given instruction can be scalarized.
6137   auto canBeScalarized = [&](Instruction *I) -> bool {
6138     // We only attempt to scalarize instructions forming a single-use chain
6139     // from the original predicated block that would otherwise be vectorized.
6140     // Although not strictly necessary, we give up on instructions we know will
6141     // already be scalar to avoid traversing chains that are unlikely to be
6142     // beneficial.
6143     if (!I->hasOneUse() || PredInst->getParent() != I->getParent() ||
6144         isScalarAfterVectorization(I, VF))
6145       return false;
6146 
6147     // If the instruction is scalar with predication, it will be analyzed
6148     // separately. We ignore it within the context of PredInst.
6149     if (isScalarWithPredication(I, VF))
6150       return false;
6151 
6152     // If any of the instruction's operands are uniform after vectorization,
6153     // the instruction cannot be scalarized. This prevents, for example, a
6154     // masked load from being scalarized.
6155     //
6156     // We assume we will only emit a value for lane zero of an instruction
6157     // marked uniform after vectorization, rather than VF identical values.
6158     // Thus, if we scalarize an instruction that uses a uniform, we would
6159     // create uses of values corresponding to the lanes we aren't emitting code
6160     // for. This behavior can be changed by allowing getScalarValue to clone
6161     // the lane zero values for uniforms rather than asserting.
6162     for (Use &U : I->operands())
6163       if (auto *J = dyn_cast<Instruction>(U.get()))
6164         if (isUniformAfterVectorization(J, VF))
6165           return false;
6166 
6167     // Otherwise, we can scalarize the instruction.
6168     return true;
6169   };
6170 
6171   // Compute the expected cost discount from scalarizing the entire expression
6172   // feeding the predicated instruction. We currently only consider expressions
6173   // that are single-use instruction chains.
6174   Worklist.push_back(PredInst);
6175   while (!Worklist.empty()) {
6176     Instruction *I = Worklist.pop_back_val();
6177 
6178     // If we've already analyzed the instruction, there's nothing to do.
6179     if (ScalarCosts.find(I) != ScalarCosts.end())
6180       continue;
6181 
6182     // Compute the cost of the vector instruction. Note that this cost already
6183     // includes the scalarization overhead of the predicated instruction.
6184     InstructionCost VectorCost = getInstructionCost(I, VF).first;
6185 
6186     // Compute the cost of the scalarized instruction. This cost is the cost of
6187     // the instruction as if it wasn't if-converted and instead remained in the
6188     // predicated block. We will scale this cost by block probability after
6189     // computing the scalarization overhead.
6190     InstructionCost ScalarCost =
6191         VF.getFixedValue() *
6192         getInstructionCost(I, ElementCount::getFixed(1)).first;
6193 
6194     // Compute the scalarization overhead of needed insertelement instructions
6195     // and phi nodes.
6196     if (isScalarWithPredication(I, VF) && !I->getType()->isVoidTy()) {
6197       ScalarCost += TTI.getScalarizationOverhead(
6198           cast<VectorType>(ToVectorTy(I->getType(), VF)),
6199           APInt::getAllOnes(VF.getFixedValue()), true, false);
6200       ScalarCost +=
6201           VF.getFixedValue() *
6202           TTI.getCFInstrCost(Instruction::PHI, TTI::TCK_RecipThroughput);
6203     }
6204 
6205     // Compute the scalarization overhead of needed extractelement
6206     // instructions. For each of the instruction's operands, if the operand can
6207     // be scalarized, add it to the worklist; otherwise, account for the
6208     // overhead.
6209     for (Use &U : I->operands())
6210       if (auto *J = dyn_cast<Instruction>(U.get())) {
6211         assert(VectorType::isValidElementType(J->getType()) &&
6212                "Instruction has non-scalar type");
6213         if (canBeScalarized(J))
6214           Worklist.push_back(J);
6215         else if (needsExtract(J, VF)) {
6216           ScalarCost += TTI.getScalarizationOverhead(
6217               cast<VectorType>(ToVectorTy(J->getType(), VF)),
6218               APInt::getAllOnes(VF.getFixedValue()), false, true);
6219         }
6220       }
6221 
6222     // Scale the total scalar cost by block probability.
6223     ScalarCost /= getReciprocalPredBlockProb();
6224 
6225     // Compute the discount. A non-negative discount means the vector version
6226     // of the instruction costs more, and scalarizing would be beneficial.
6227     Discount += VectorCost - ScalarCost;
6228     ScalarCosts[I] = ScalarCost;
6229   }
6230 
6231   return *Discount.getValue();
6232 }
6233 
6234 LoopVectorizationCostModel::VectorizationCostTy
6235 LoopVectorizationCostModel::expectedCost(
6236     ElementCount VF, SmallVectorImpl<InstructionVFPair> *Invalid) {
6237   VectorizationCostTy Cost;
6238 
6239   // For each block.
6240   for (BasicBlock *BB : TheLoop->blocks()) {
6241     VectorizationCostTy BlockCost;
6242 
6243     // For each instruction in the old loop.
6244     for (Instruction &I : BB->instructionsWithoutDebug()) {
6245       // Skip ignored values.
6246       if (ValuesToIgnore.count(&I) ||
6247           (VF.isVector() && VecValuesToIgnore.count(&I)))
6248         continue;
6249 
6250       VectorizationCostTy C = getInstructionCost(&I, VF);
6251 
6252       // Check if we should override the cost.
6253       if (C.first.isValid() &&
6254           ForceTargetInstructionCost.getNumOccurrences() > 0)
6255         C.first = InstructionCost(ForceTargetInstructionCost);
6256 
6257       // Keep a list of instructions with invalid costs.
6258       if (Invalid && !C.first.isValid())
6259         Invalid->emplace_back(&I, VF);
6260 
6261       BlockCost.first += C.first;
6262       BlockCost.second |= C.second;
6263       LLVM_DEBUG(dbgs() << "LV: Found an estimated cost of " << C.first
6264                         << " for VF " << VF << " For instruction: " << I
6265                         << '\n');
6266     }
6267 
6268     // If we are vectorizing a predicated block, it will have been
6269     // if-converted. This means that the block's instructions (aside from
6270     // stores and instructions that may divide by zero) will now be
6271     // unconditionally executed. For the scalar case, we may not always execute
6272     // the predicated block, if it is an if-else block. Thus, scale the block's
6273     // cost by the probability of executing it. blockNeedsPredication from
6274     // Legal is used so as to not include all blocks in tail folded loops.
6275     if (VF.isScalar() && Legal->blockNeedsPredication(BB))
6276       BlockCost.first /= getReciprocalPredBlockProb();
6277 
6278     Cost.first += BlockCost.first;
6279     Cost.second |= BlockCost.second;
6280   }
6281 
6282   return Cost;
6283 }
6284 
6285 /// Gets Address Access SCEV after verifying that the access pattern
6286 /// is loop invariant except the induction variable dependence.
6287 ///
6288 /// This SCEV can be sent to the Target in order to estimate the address
6289 /// calculation cost.
6290 static const SCEV *getAddressAccessSCEV(
6291               Value *Ptr,
6292               LoopVectorizationLegality *Legal,
6293               PredicatedScalarEvolution &PSE,
6294               const Loop *TheLoop) {
6295 
6296   auto *Gep = dyn_cast<GetElementPtrInst>(Ptr);
6297   if (!Gep)
6298     return nullptr;
6299 
6300   // We are looking for a gep with all loop invariant indices except for one
6301   // which should be an induction variable.
6302   auto SE = PSE.getSE();
6303   unsigned NumOperands = Gep->getNumOperands();
6304   for (unsigned i = 1; i < NumOperands; ++i) {
6305     Value *Opd = Gep->getOperand(i);
6306     if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
6307         !Legal->isInductionVariable(Opd))
6308       return nullptr;
6309   }
6310 
6311   // Now we know we have a GEP ptr, %inv, %ind, %inv. return the Ptr SCEV.
6312   return PSE.getSCEV(Ptr);
6313 }
6314 
6315 static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
6316   return Legal->hasStride(I->getOperand(0)) ||
6317          Legal->hasStride(I->getOperand(1));
6318 }
6319 
6320 InstructionCost
6321 LoopVectorizationCostModel::getMemInstScalarizationCost(Instruction *I,
6322                                                         ElementCount VF) {
6323   assert(VF.isVector() &&
6324          "Scalarization cost of instruction implies vectorization.");
6325   if (VF.isScalable())
6326     return InstructionCost::getInvalid();
6327 
6328   Type *ValTy = getLoadStoreType(I);
6329   auto SE = PSE.getSE();
6330 
6331   unsigned AS = getLoadStoreAddressSpace(I);
6332   Value *Ptr = getLoadStorePointerOperand(I);
6333   Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
6334   // NOTE: PtrTy is a vector to signal `TTI::getAddressComputationCost`
6335   //       that it is being called from this specific place.
6336 
6337   // Figure out whether the access is strided and get the stride value
6338   // if it's known in compile time
6339   const SCEV *PtrSCEV = getAddressAccessSCEV(Ptr, Legal, PSE, TheLoop);
6340 
6341   // Get the cost of the scalar memory instruction and address computation.
6342   InstructionCost Cost =
6343       VF.getKnownMinValue() * TTI.getAddressComputationCost(PtrTy, SE, PtrSCEV);
6344 
6345   // Don't pass *I here, since it is scalar but will actually be part of a
6346   // vectorized loop where the user of it is a vectorized instruction.
6347   const Align Alignment = getLoadStoreAlignment(I);
6348   Cost += VF.getKnownMinValue() *
6349           TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(), Alignment,
6350                               AS, TTI::TCK_RecipThroughput);
6351 
6352   // Get the overhead of the extractelement and insertelement instructions
6353   // we might create due to scalarization.
6354   Cost += getScalarizationOverhead(I, VF);
6355 
6356   // If we have a predicated load/store, it will need extra i1 extracts and
6357   // conditional branches, but may not be executed for each vector lane. Scale
6358   // the cost by the probability of executing the predicated block.
6359   if (isPredicatedInst(I, VF)) {
6360     Cost /= getReciprocalPredBlockProb();
6361 
6362     // Add the cost of an i1 extract and a branch
6363     auto *Vec_i1Ty =
6364         VectorType::get(IntegerType::getInt1Ty(ValTy->getContext()), VF);
6365     Cost += TTI.getScalarizationOverhead(
6366         Vec_i1Ty, APInt::getAllOnes(VF.getKnownMinValue()),
6367         /*Insert=*/false, /*Extract=*/true);
6368     Cost += TTI.getCFInstrCost(Instruction::Br, TTI::TCK_RecipThroughput);
6369 
6370     if (useEmulatedMaskMemRefHack(I, VF))
6371       // Artificially setting to a high enough value to practically disable
6372       // vectorization with such operations.
6373       Cost = 3000000;
6374   }
6375 
6376   return Cost;
6377 }
6378 
6379 InstructionCost
6380 LoopVectorizationCostModel::getConsecutiveMemOpCost(Instruction *I,
6381                                                     ElementCount VF) {
6382   Type *ValTy = getLoadStoreType(I);
6383   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
6384   Value *Ptr = getLoadStorePointerOperand(I);
6385   unsigned AS = getLoadStoreAddressSpace(I);
6386   int ConsecutiveStride = Legal->isConsecutivePtr(ValTy, Ptr);
6387   enum TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
6388 
6389   assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
6390          "Stride should be 1 or -1 for consecutive memory access");
6391   const Align Alignment = getLoadStoreAlignment(I);
6392   InstructionCost Cost = 0;
6393   if (Legal->isMaskRequired(I))
6394     Cost += TTI.getMaskedMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS,
6395                                       CostKind);
6396   else
6397     Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS,
6398                                 CostKind, I);
6399 
6400   bool Reverse = ConsecutiveStride < 0;
6401   if (Reverse)
6402     Cost +=
6403         TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, None, 0);
6404   return Cost;
6405 }
6406 
6407 InstructionCost
6408 LoopVectorizationCostModel::getUniformMemOpCost(Instruction *I,
6409                                                 ElementCount VF) {
6410   assert(Legal->isUniformMemOp(*I));
6411 
6412   Type *ValTy = getLoadStoreType(I);
6413   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
6414   const Align Alignment = getLoadStoreAlignment(I);
6415   unsigned AS = getLoadStoreAddressSpace(I);
6416   enum TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
6417   if (isa<LoadInst>(I)) {
6418     return TTI.getAddressComputationCost(ValTy) +
6419            TTI.getMemoryOpCost(Instruction::Load, ValTy, Alignment, AS,
6420                                CostKind) +
6421            TTI.getShuffleCost(TargetTransformInfo::SK_Broadcast, VectorTy);
6422   }
6423   StoreInst *SI = cast<StoreInst>(I);
6424 
6425   bool isLoopInvariantStoreValue = Legal->isUniform(SI->getValueOperand());
6426   return TTI.getAddressComputationCost(ValTy) +
6427          TTI.getMemoryOpCost(Instruction::Store, ValTy, Alignment, AS,
6428                              CostKind) +
6429          (isLoopInvariantStoreValue
6430               ? 0
6431               : TTI.getVectorInstrCost(Instruction::ExtractElement, VectorTy,
6432                                        VF.getKnownMinValue() - 1));
6433 }
6434 
6435 InstructionCost
6436 LoopVectorizationCostModel::getGatherScatterCost(Instruction *I,
6437                                                  ElementCount VF) {
6438   Type *ValTy = getLoadStoreType(I);
6439   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
6440   const Align Alignment = getLoadStoreAlignment(I);
6441   const Value *Ptr = getLoadStorePointerOperand(I);
6442 
6443   return TTI.getAddressComputationCost(VectorTy) +
6444          TTI.getGatherScatterOpCost(
6445              I->getOpcode(), VectorTy, Ptr, Legal->isMaskRequired(I), Alignment,
6446              TargetTransformInfo::TCK_RecipThroughput, I);
6447 }
6448 
6449 InstructionCost
6450 LoopVectorizationCostModel::getInterleaveGroupCost(Instruction *I,
6451                                                    ElementCount VF) {
6452   // TODO: Once we have support for interleaving with scalable vectors
6453   // we can calculate the cost properly here.
6454   if (VF.isScalable())
6455     return InstructionCost::getInvalid();
6456 
6457   Type *ValTy = getLoadStoreType(I);
6458   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
6459   unsigned AS = getLoadStoreAddressSpace(I);
6460 
6461   auto Group = getInterleavedAccessGroup(I);
6462   assert(Group && "Fail to get an interleaved access group.");
6463 
6464   unsigned InterleaveFactor = Group->getFactor();
6465   auto *WideVecTy = VectorType::get(ValTy, VF * InterleaveFactor);
6466 
6467   // Holds the indices of existing members in the interleaved group.
6468   SmallVector<unsigned, 4> Indices;
6469   for (unsigned IF = 0; IF < InterleaveFactor; IF++)
6470     if (Group->getMember(IF))
6471       Indices.push_back(IF);
6472 
6473   // Calculate the cost of the whole interleaved group.
6474   bool UseMaskForGaps =
6475       (Group->requiresScalarEpilogue() && !isScalarEpilogueAllowed()) ||
6476       (isa<StoreInst>(I) && (Group->getNumMembers() < Group->getFactor()));
6477   InstructionCost Cost = TTI.getInterleavedMemoryOpCost(
6478       I->getOpcode(), WideVecTy, Group->getFactor(), Indices, Group->getAlign(),
6479       AS, TTI::TCK_RecipThroughput, Legal->isMaskRequired(I), UseMaskForGaps);
6480 
6481   if (Group->isReverse()) {
6482     // TODO: Add support for reversed masked interleaved access.
6483     assert(!Legal->isMaskRequired(I) &&
6484            "Reverse masked interleaved access not supported.");
6485     Cost +=
6486         Group->getNumMembers() *
6487         TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, None, 0);
6488   }
6489   return Cost;
6490 }
6491 
6492 Optional<InstructionCost> LoopVectorizationCostModel::getReductionPatternCost(
6493     Instruction *I, ElementCount VF, Type *Ty, TTI::TargetCostKind CostKind) {
6494   using namespace llvm::PatternMatch;
6495   // Early exit for no inloop reductions
6496   if (InLoopReductionChains.empty() || VF.isScalar() || !isa<VectorType>(Ty))
6497     return None;
6498   auto *VectorTy = cast<VectorType>(Ty);
6499 
6500   // We are looking for a pattern of, and finding the minimal acceptable cost:
6501   //  reduce(mul(ext(A), ext(B))) or
6502   //  reduce(mul(A, B)) or
6503   //  reduce(ext(A)) or
6504   //  reduce(A).
6505   // The basic idea is that we walk down the tree to do that, finding the root
6506   // reduction instruction in InLoopReductionImmediateChains. From there we find
6507   // the pattern of mul/ext and test the cost of the entire pattern vs the cost
6508   // of the components. If the reduction cost is lower then we return it for the
6509   // reduction instruction and 0 for the other instructions in the pattern. If
6510   // it is not we return an invalid cost specifying the orignal cost method
6511   // should be used.
6512   Instruction *RetI = I;
6513   if (match(RetI, m_ZExtOrSExt(m_Value()))) {
6514     if (!RetI->hasOneUser())
6515       return None;
6516     RetI = RetI->user_back();
6517   }
6518   if (match(RetI, m_Mul(m_Value(), m_Value())) &&
6519       RetI->user_back()->getOpcode() == Instruction::Add) {
6520     if (!RetI->hasOneUser())
6521       return None;
6522     RetI = RetI->user_back();
6523   }
6524 
6525   // Test if the found instruction is a reduction, and if not return an invalid
6526   // cost specifying the parent to use the original cost modelling.
6527   if (!InLoopReductionImmediateChains.count(RetI))
6528     return None;
6529 
6530   // Find the reduction this chain is a part of and calculate the basic cost of
6531   // the reduction on its own.
6532   Instruction *LastChain = InLoopReductionImmediateChains[RetI];
6533   Instruction *ReductionPhi = LastChain;
6534   while (!isa<PHINode>(ReductionPhi))
6535     ReductionPhi = InLoopReductionImmediateChains[ReductionPhi];
6536 
6537   const RecurrenceDescriptor &RdxDesc =
6538       Legal->getReductionVars().find(cast<PHINode>(ReductionPhi))->second;
6539 
6540   InstructionCost BaseCost = TTI.getArithmeticReductionCost(
6541       RdxDesc.getOpcode(), VectorTy, RdxDesc.getFastMathFlags(), CostKind);
6542 
6543   // For a call to the llvm.fmuladd intrinsic we need to add the cost of a
6544   // normal fmul instruction to the cost of the fadd reduction.
6545   if (RdxDesc.getRecurrenceKind() == RecurKind::FMulAdd)
6546     BaseCost +=
6547         TTI.getArithmeticInstrCost(Instruction::FMul, VectorTy, CostKind);
6548 
6549   // If we're using ordered reductions then we can just return the base cost
6550   // here, since getArithmeticReductionCost calculates the full ordered
6551   // reduction cost when FP reassociation is not allowed.
6552   if (useOrderedReductions(RdxDesc))
6553     return BaseCost;
6554 
6555   // Get the operand that was not the reduction chain and match it to one of the
6556   // patterns, returning the better cost if it is found.
6557   Instruction *RedOp = RetI->getOperand(1) == LastChain
6558                            ? dyn_cast<Instruction>(RetI->getOperand(0))
6559                            : dyn_cast<Instruction>(RetI->getOperand(1));
6560 
6561   VectorTy = VectorType::get(I->getOperand(0)->getType(), VectorTy);
6562 
6563   Instruction *Op0, *Op1;
6564   if (RedOp &&
6565       match(RedOp,
6566             m_ZExtOrSExt(m_Mul(m_Instruction(Op0), m_Instruction(Op1)))) &&
6567       match(Op0, m_ZExtOrSExt(m_Value())) &&
6568       Op0->getOpcode() == Op1->getOpcode() &&
6569       Op0->getOperand(0)->getType() == Op1->getOperand(0)->getType() &&
6570       !TheLoop->isLoopInvariant(Op0) && !TheLoop->isLoopInvariant(Op1) &&
6571       (Op0->getOpcode() == RedOp->getOpcode() || Op0 == Op1)) {
6572 
6573     // Matched reduce(ext(mul(ext(A), ext(B)))
6574     // Note that the extend opcodes need to all match, or if A==B they will have
6575     // been converted to zext(mul(sext(A), sext(A))) as it is known positive,
6576     // which is equally fine.
6577     bool IsUnsigned = isa<ZExtInst>(Op0);
6578     auto *ExtType = VectorType::get(Op0->getOperand(0)->getType(), VectorTy);
6579     auto *MulType = VectorType::get(Op0->getType(), VectorTy);
6580 
6581     InstructionCost ExtCost =
6582         TTI.getCastInstrCost(Op0->getOpcode(), MulType, ExtType,
6583                              TTI::CastContextHint::None, CostKind, Op0);
6584     InstructionCost MulCost =
6585         TTI.getArithmeticInstrCost(Instruction::Mul, MulType, CostKind);
6586     InstructionCost Ext2Cost =
6587         TTI.getCastInstrCost(RedOp->getOpcode(), VectorTy, MulType,
6588                              TTI::CastContextHint::None, CostKind, RedOp);
6589 
6590     InstructionCost RedCost = TTI.getExtendedAddReductionCost(
6591         /*IsMLA=*/true, IsUnsigned, RdxDesc.getRecurrenceType(), ExtType,
6592         CostKind);
6593 
6594     if (RedCost.isValid() &&
6595         RedCost < ExtCost * 2 + MulCost + Ext2Cost + BaseCost)
6596       return I == RetI ? RedCost : 0;
6597   } else if (RedOp && match(RedOp, m_ZExtOrSExt(m_Value())) &&
6598              !TheLoop->isLoopInvariant(RedOp)) {
6599     // Matched reduce(ext(A))
6600     bool IsUnsigned = isa<ZExtInst>(RedOp);
6601     auto *ExtType = VectorType::get(RedOp->getOperand(0)->getType(), VectorTy);
6602     InstructionCost RedCost = TTI.getExtendedAddReductionCost(
6603         /*IsMLA=*/false, IsUnsigned, RdxDesc.getRecurrenceType(), ExtType,
6604         CostKind);
6605 
6606     InstructionCost ExtCost =
6607         TTI.getCastInstrCost(RedOp->getOpcode(), VectorTy, ExtType,
6608                              TTI::CastContextHint::None, CostKind, RedOp);
6609     if (RedCost.isValid() && RedCost < BaseCost + ExtCost)
6610       return I == RetI ? RedCost : 0;
6611   } else if (RedOp &&
6612              match(RedOp, m_Mul(m_Instruction(Op0), m_Instruction(Op1)))) {
6613     if (match(Op0, m_ZExtOrSExt(m_Value())) &&
6614         Op0->getOpcode() == Op1->getOpcode() &&
6615         !TheLoop->isLoopInvariant(Op0) && !TheLoop->isLoopInvariant(Op1)) {
6616       bool IsUnsigned = isa<ZExtInst>(Op0);
6617       Type *Op0Ty = Op0->getOperand(0)->getType();
6618       Type *Op1Ty = Op1->getOperand(0)->getType();
6619       Type *LargestOpTy =
6620           Op0Ty->getIntegerBitWidth() < Op1Ty->getIntegerBitWidth() ? Op1Ty
6621                                                                     : Op0Ty;
6622       auto *ExtType = VectorType::get(LargestOpTy, VectorTy);
6623 
6624       // Matched reduce(mul(ext(A), ext(B))), where the two ext may be of
6625       // different sizes. We take the largest type as the ext to reduce, and add
6626       // the remaining cost as, for example reduce(mul(ext(ext(A)), ext(B))).
6627       InstructionCost ExtCost0 = TTI.getCastInstrCost(
6628           Op0->getOpcode(), VectorTy, VectorType::get(Op0Ty, VectorTy),
6629           TTI::CastContextHint::None, CostKind, Op0);
6630       InstructionCost ExtCost1 = TTI.getCastInstrCost(
6631           Op1->getOpcode(), VectorTy, VectorType::get(Op1Ty, VectorTy),
6632           TTI::CastContextHint::None, CostKind, Op1);
6633       InstructionCost MulCost =
6634           TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy, CostKind);
6635 
6636       InstructionCost RedCost = TTI.getExtendedAddReductionCost(
6637           /*IsMLA=*/true, IsUnsigned, RdxDesc.getRecurrenceType(), ExtType,
6638           CostKind);
6639       InstructionCost ExtraExtCost = 0;
6640       if (Op0Ty != LargestOpTy || Op1Ty != LargestOpTy) {
6641         Instruction *ExtraExtOp = (Op0Ty != LargestOpTy) ? Op0 : Op1;
6642         ExtraExtCost = TTI.getCastInstrCost(
6643             ExtraExtOp->getOpcode(), ExtType,
6644             VectorType::get(ExtraExtOp->getOperand(0)->getType(), VectorTy),
6645             TTI::CastContextHint::None, CostKind, ExtraExtOp);
6646       }
6647 
6648       if (RedCost.isValid() &&
6649           (RedCost + ExtraExtCost) < (ExtCost0 + ExtCost1 + MulCost + BaseCost))
6650         return I == RetI ? RedCost : 0;
6651     } else if (!match(I, m_ZExtOrSExt(m_Value()))) {
6652       // Matched reduce(mul())
6653       InstructionCost MulCost =
6654           TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy, CostKind);
6655 
6656       InstructionCost RedCost = TTI.getExtendedAddReductionCost(
6657           /*IsMLA=*/true, true, RdxDesc.getRecurrenceType(), VectorTy,
6658           CostKind);
6659 
6660       if (RedCost.isValid() && RedCost < MulCost + BaseCost)
6661         return I == RetI ? RedCost : 0;
6662     }
6663   }
6664 
6665   return I == RetI ? Optional<InstructionCost>(BaseCost) : None;
6666 }
6667 
6668 InstructionCost
6669 LoopVectorizationCostModel::getMemoryInstructionCost(Instruction *I,
6670                                                      ElementCount VF) {
6671   // Calculate scalar cost only. Vectorization cost should be ready at this
6672   // moment.
6673   if (VF.isScalar()) {
6674     Type *ValTy = getLoadStoreType(I);
6675     const Align Alignment = getLoadStoreAlignment(I);
6676     unsigned AS = getLoadStoreAddressSpace(I);
6677 
6678     return TTI.getAddressComputationCost(ValTy) +
6679            TTI.getMemoryOpCost(I->getOpcode(), ValTy, Alignment, AS,
6680                                TTI::TCK_RecipThroughput, I);
6681   }
6682   return getWideningCost(I, VF);
6683 }
6684 
6685 LoopVectorizationCostModel::VectorizationCostTy
6686 LoopVectorizationCostModel::getInstructionCost(Instruction *I,
6687                                                ElementCount VF) {
6688   // If we know that this instruction will remain uniform, check the cost of
6689   // the scalar version.
6690   if (isUniformAfterVectorization(I, VF))
6691     VF = ElementCount::getFixed(1);
6692 
6693   if (VF.isVector() && isProfitableToScalarize(I, VF))
6694     return VectorizationCostTy(InstsToScalarize[VF][I], false);
6695 
6696   // Forced scalars do not have any scalarization overhead.
6697   auto ForcedScalar = ForcedScalars.find(VF);
6698   if (VF.isVector() && ForcedScalar != ForcedScalars.end()) {
6699     auto InstSet = ForcedScalar->second;
6700     if (InstSet.count(I))
6701       return VectorizationCostTy(
6702           (getInstructionCost(I, ElementCount::getFixed(1)).first *
6703            VF.getKnownMinValue()),
6704           false);
6705   }
6706 
6707   Type *VectorTy;
6708   InstructionCost C = getInstructionCost(I, VF, VectorTy);
6709 
6710   bool TypeNotScalarized = false;
6711   if (VF.isVector() && VectorTy->isVectorTy()) {
6712     if (unsigned NumParts = TTI.getNumberOfParts(VectorTy)) {
6713       if (VF.isScalable())
6714         // <vscale x 1 x iN> is assumed to be profitable over iN because
6715         // scalable registers are a distinct register class from scalar ones.
6716         // If we ever find a target which wants to lower scalable vectors
6717         // back to scalars, we'll need to update this code to explicitly
6718         // ask TTI about the register class uses for each part.
6719         TypeNotScalarized = NumParts <= VF.getKnownMinValue();
6720       else
6721         TypeNotScalarized = NumParts < VF.getKnownMinValue();
6722     } else
6723       C = InstructionCost::getInvalid();
6724   }
6725   return VectorizationCostTy(C, TypeNotScalarized);
6726 }
6727 
6728 InstructionCost
6729 LoopVectorizationCostModel::getScalarizationOverhead(Instruction *I,
6730                                                      ElementCount VF) const {
6731 
6732   // There is no mechanism yet to create a scalable scalarization loop,
6733   // so this is currently Invalid.
6734   if (VF.isScalable())
6735     return InstructionCost::getInvalid();
6736 
6737   if (VF.isScalar())
6738     return 0;
6739 
6740   InstructionCost Cost = 0;
6741   Type *RetTy = ToVectorTy(I->getType(), VF);
6742   if (!RetTy->isVoidTy() &&
6743       (!isa<LoadInst>(I) || !TTI.supportsEfficientVectorElementLoadStore()))
6744     Cost += TTI.getScalarizationOverhead(
6745         cast<VectorType>(RetTy), APInt::getAllOnes(VF.getKnownMinValue()), true,
6746         false);
6747 
6748   // Some targets keep addresses scalar.
6749   if (isa<LoadInst>(I) && !TTI.prefersVectorizedAddressing())
6750     return Cost;
6751 
6752   // Some targets support efficient element stores.
6753   if (isa<StoreInst>(I) && TTI.supportsEfficientVectorElementLoadStore())
6754     return Cost;
6755 
6756   // Collect operands to consider.
6757   CallInst *CI = dyn_cast<CallInst>(I);
6758   Instruction::op_range Ops = CI ? CI->args() : I->operands();
6759 
6760   // Skip operands that do not require extraction/scalarization and do not incur
6761   // any overhead.
6762   SmallVector<Type *> Tys;
6763   for (auto *V : filterExtractingOperands(Ops, VF))
6764     Tys.push_back(MaybeVectorizeType(V->getType(), VF));
6765   return Cost + TTI.getOperandsScalarizationOverhead(
6766                     filterExtractingOperands(Ops, VF), Tys);
6767 }
6768 
6769 void LoopVectorizationCostModel::setCostBasedWideningDecision(ElementCount VF) {
6770   if (VF.isScalar())
6771     return;
6772   NumPredStores = 0;
6773   for (BasicBlock *BB : TheLoop->blocks()) {
6774     // For each instruction in the old loop.
6775     for (Instruction &I : *BB) {
6776       Value *Ptr =  getLoadStorePointerOperand(&I);
6777       if (!Ptr)
6778         continue;
6779 
6780       // TODO: We should generate better code and update the cost model for
6781       // predicated uniform stores. Today they are treated as any other
6782       // predicated store (see added test cases in
6783       // invariant-store-vectorization.ll).
6784       if (isa<StoreInst>(&I) && isScalarWithPredication(&I, VF))
6785         NumPredStores++;
6786 
6787       if (Legal->isUniformMemOp(I)) {
6788         // TODO: Avoid replicating loads and stores instead of
6789         // relying on instcombine to remove them.
6790         // Load: Scalar load + broadcast
6791         // Store: Scalar store + isLoopInvariantStoreValue ? 0 : extract
6792         InstructionCost Cost;
6793         if (isa<StoreInst>(&I) && VF.isScalable() &&
6794             isLegalGatherOrScatter(&I, VF)) {
6795           Cost = getGatherScatterCost(&I, VF);
6796           setWideningDecision(&I, VF, CM_GatherScatter, Cost);
6797         } else {
6798           Cost = getUniformMemOpCost(&I, VF);
6799           setWideningDecision(&I, VF, CM_Scalarize, Cost);
6800         }
6801         continue;
6802       }
6803 
6804       // We assume that widening is the best solution when possible.
6805       if (memoryInstructionCanBeWidened(&I, VF)) {
6806         InstructionCost Cost = getConsecutiveMemOpCost(&I, VF);
6807         int ConsecutiveStride = Legal->isConsecutivePtr(
6808             getLoadStoreType(&I), getLoadStorePointerOperand(&I));
6809         assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
6810                "Expected consecutive stride.");
6811         InstWidening Decision =
6812             ConsecutiveStride == 1 ? CM_Widen : CM_Widen_Reverse;
6813         setWideningDecision(&I, VF, Decision, Cost);
6814         continue;
6815       }
6816 
6817       // Choose between Interleaving, Gather/Scatter or Scalarization.
6818       InstructionCost InterleaveCost = InstructionCost::getInvalid();
6819       unsigned NumAccesses = 1;
6820       if (isAccessInterleaved(&I)) {
6821         auto Group = getInterleavedAccessGroup(&I);
6822         assert(Group && "Fail to get an interleaved access group.");
6823 
6824         // Make one decision for the whole group.
6825         if (getWideningDecision(&I, VF) != CM_Unknown)
6826           continue;
6827 
6828         NumAccesses = Group->getNumMembers();
6829         if (interleavedAccessCanBeWidened(&I, VF))
6830           InterleaveCost = getInterleaveGroupCost(&I, VF);
6831       }
6832 
6833       InstructionCost GatherScatterCost =
6834           isLegalGatherOrScatter(&I, VF)
6835               ? getGatherScatterCost(&I, VF) * NumAccesses
6836               : InstructionCost::getInvalid();
6837 
6838       InstructionCost ScalarizationCost =
6839           getMemInstScalarizationCost(&I, VF) * NumAccesses;
6840 
6841       // Choose better solution for the current VF,
6842       // write down this decision and use it during vectorization.
6843       InstructionCost Cost;
6844       InstWidening Decision;
6845       if (InterleaveCost <= GatherScatterCost &&
6846           InterleaveCost < ScalarizationCost) {
6847         Decision = CM_Interleave;
6848         Cost = InterleaveCost;
6849       } else if (GatherScatterCost < ScalarizationCost) {
6850         Decision = CM_GatherScatter;
6851         Cost = GatherScatterCost;
6852       } else {
6853         Decision = CM_Scalarize;
6854         Cost = ScalarizationCost;
6855       }
6856       // If the instructions belongs to an interleave group, the whole group
6857       // receives the same decision. The whole group receives the cost, but
6858       // the cost will actually be assigned to one instruction.
6859       if (auto Group = getInterleavedAccessGroup(&I))
6860         setWideningDecision(Group, VF, Decision, Cost);
6861       else
6862         setWideningDecision(&I, VF, Decision, Cost);
6863     }
6864   }
6865 
6866   // Make sure that any load of address and any other address computation
6867   // remains scalar unless there is gather/scatter support. This avoids
6868   // inevitable extracts into address registers, and also has the benefit of
6869   // activating LSR more, since that pass can't optimize vectorized
6870   // addresses.
6871   if (TTI.prefersVectorizedAddressing())
6872     return;
6873 
6874   // Start with all scalar pointer uses.
6875   SmallPtrSet<Instruction *, 8> AddrDefs;
6876   for (BasicBlock *BB : TheLoop->blocks())
6877     for (Instruction &I : *BB) {
6878       Instruction *PtrDef =
6879         dyn_cast_or_null<Instruction>(getLoadStorePointerOperand(&I));
6880       if (PtrDef && TheLoop->contains(PtrDef) &&
6881           getWideningDecision(&I, VF) != CM_GatherScatter)
6882         AddrDefs.insert(PtrDef);
6883     }
6884 
6885   // Add all instructions used to generate the addresses.
6886   SmallVector<Instruction *, 4> Worklist;
6887   append_range(Worklist, AddrDefs);
6888   while (!Worklist.empty()) {
6889     Instruction *I = Worklist.pop_back_val();
6890     for (auto &Op : I->operands())
6891       if (auto *InstOp = dyn_cast<Instruction>(Op))
6892         if ((InstOp->getParent() == I->getParent()) && !isa<PHINode>(InstOp) &&
6893             AddrDefs.insert(InstOp).second)
6894           Worklist.push_back(InstOp);
6895   }
6896 
6897   for (auto *I : AddrDefs) {
6898     if (isa<LoadInst>(I)) {
6899       // Setting the desired widening decision should ideally be handled in
6900       // by cost functions, but since this involves the task of finding out
6901       // if the loaded register is involved in an address computation, it is
6902       // instead changed here when we know this is the case.
6903       InstWidening Decision = getWideningDecision(I, VF);
6904       if (Decision == CM_Widen || Decision == CM_Widen_Reverse)
6905         // Scalarize a widened load of address.
6906         setWideningDecision(
6907             I, VF, CM_Scalarize,
6908             (VF.getKnownMinValue() *
6909              getMemoryInstructionCost(I, ElementCount::getFixed(1))));
6910       else if (auto Group = getInterleavedAccessGroup(I)) {
6911         // Scalarize an interleave group of address loads.
6912         for (unsigned I = 0; I < Group->getFactor(); ++I) {
6913           if (Instruction *Member = Group->getMember(I))
6914             setWideningDecision(
6915                 Member, VF, CM_Scalarize,
6916                 (VF.getKnownMinValue() *
6917                  getMemoryInstructionCost(Member, ElementCount::getFixed(1))));
6918         }
6919       }
6920     } else
6921       // Make sure I gets scalarized and a cost estimate without
6922       // scalarization overhead.
6923       ForcedScalars[VF].insert(I);
6924   }
6925 }
6926 
6927 InstructionCost
6928 LoopVectorizationCostModel::getInstructionCost(Instruction *I, ElementCount VF,
6929                                                Type *&VectorTy) {
6930   Type *RetTy = I->getType();
6931   if (canTruncateToMinimalBitwidth(I, VF))
6932     RetTy = IntegerType::get(RetTy->getContext(), MinBWs[I]);
6933   auto SE = PSE.getSE();
6934   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
6935 
6936   auto hasSingleCopyAfterVectorization = [this](Instruction *I,
6937                                                 ElementCount VF) -> bool {
6938     if (VF.isScalar())
6939       return true;
6940 
6941     auto Scalarized = InstsToScalarize.find(VF);
6942     assert(Scalarized != InstsToScalarize.end() &&
6943            "VF not yet analyzed for scalarization profitability");
6944     return !Scalarized->second.count(I) &&
6945            llvm::all_of(I->users(), [&](User *U) {
6946              auto *UI = cast<Instruction>(U);
6947              return !Scalarized->second.count(UI);
6948            });
6949   };
6950   (void) hasSingleCopyAfterVectorization;
6951 
6952   if (isScalarAfterVectorization(I, VF)) {
6953     // With the exception of GEPs and PHIs, after scalarization there should
6954     // only be one copy of the instruction generated in the loop. This is
6955     // because the VF is either 1, or any instructions that need scalarizing
6956     // have already been dealt with by the the time we get here. As a result,
6957     // it means we don't have to multiply the instruction cost by VF.
6958     assert(I->getOpcode() == Instruction::GetElementPtr ||
6959            I->getOpcode() == Instruction::PHI ||
6960            (I->getOpcode() == Instruction::BitCast &&
6961             I->getType()->isPointerTy()) ||
6962            hasSingleCopyAfterVectorization(I, VF));
6963     VectorTy = RetTy;
6964   } else
6965     VectorTy = ToVectorTy(RetTy, VF);
6966 
6967   // TODO: We need to estimate the cost of intrinsic calls.
6968   switch (I->getOpcode()) {
6969   case Instruction::GetElementPtr:
6970     // We mark this instruction as zero-cost because the cost of GEPs in
6971     // vectorized code depends on whether the corresponding memory instruction
6972     // is scalarized or not. Therefore, we handle GEPs with the memory
6973     // instruction cost.
6974     return 0;
6975   case Instruction::Br: {
6976     // In cases of scalarized and predicated instructions, there will be VF
6977     // predicated blocks in the vectorized loop. Each branch around these
6978     // blocks requires also an extract of its vector compare i1 element.
6979     bool ScalarPredicatedBB = false;
6980     BranchInst *BI = cast<BranchInst>(I);
6981     if (VF.isVector() && BI->isConditional() &&
6982         (PredicatedBBsAfterVectorization[VF].count(BI->getSuccessor(0)) ||
6983          PredicatedBBsAfterVectorization[VF].count(BI->getSuccessor(1))))
6984       ScalarPredicatedBB = true;
6985 
6986     if (ScalarPredicatedBB) {
6987       // Not possible to scalarize scalable vector with predicated instructions.
6988       if (VF.isScalable())
6989         return InstructionCost::getInvalid();
6990       // Return cost for branches around scalarized and predicated blocks.
6991       auto *Vec_i1Ty =
6992           VectorType::get(IntegerType::getInt1Ty(RetTy->getContext()), VF);
6993       return (
6994           TTI.getScalarizationOverhead(
6995               Vec_i1Ty, APInt::getAllOnes(VF.getFixedValue()), false, true) +
6996           (TTI.getCFInstrCost(Instruction::Br, CostKind) * VF.getFixedValue()));
6997     } else if (I->getParent() == TheLoop->getLoopLatch() || VF.isScalar())
6998       // The back-edge branch will remain, as will all scalar branches.
6999       return TTI.getCFInstrCost(Instruction::Br, CostKind);
7000     else
7001       // This branch will be eliminated by if-conversion.
7002       return 0;
7003     // Note: We currently assume zero cost for an unconditional branch inside
7004     // a predicated block since it will become a fall-through, although we
7005     // may decide in the future to call TTI for all branches.
7006   }
7007   case Instruction::PHI: {
7008     auto *Phi = cast<PHINode>(I);
7009 
7010     // First-order recurrences are replaced by vector shuffles inside the loop.
7011     // NOTE: Don't use ToVectorTy as SK_ExtractSubvector expects a vector type.
7012     if (VF.isVector() && Legal->isFirstOrderRecurrence(Phi))
7013       return TTI.getShuffleCost(
7014           TargetTransformInfo::SK_ExtractSubvector, cast<VectorType>(VectorTy),
7015           None, VF.getKnownMinValue() - 1, FixedVectorType::get(RetTy, 1));
7016 
7017     // Phi nodes in non-header blocks (not inductions, reductions, etc.) are
7018     // converted into select instructions. We require N - 1 selects per phi
7019     // node, where N is the number of incoming values.
7020     if (VF.isVector() && Phi->getParent() != TheLoop->getHeader())
7021       return (Phi->getNumIncomingValues() - 1) *
7022              TTI.getCmpSelInstrCost(
7023                  Instruction::Select, ToVectorTy(Phi->getType(), VF),
7024                  ToVectorTy(Type::getInt1Ty(Phi->getContext()), VF),
7025                  CmpInst::BAD_ICMP_PREDICATE, CostKind);
7026 
7027     return TTI.getCFInstrCost(Instruction::PHI, CostKind);
7028   }
7029   case Instruction::UDiv:
7030   case Instruction::SDiv:
7031   case Instruction::URem:
7032   case Instruction::SRem:
7033     // If we have a predicated instruction, it may not be executed for each
7034     // vector lane. Get the scalarization cost and scale this amount by the
7035     // probability of executing the predicated block. If the instruction is not
7036     // predicated, we fall through to the next case.
7037     if (VF.isVector() && isScalarWithPredication(I, VF)) {
7038       InstructionCost Cost = 0;
7039 
7040       // These instructions have a non-void type, so account for the phi nodes
7041       // that we will create. This cost is likely to be zero. The phi node
7042       // cost, if any, should be scaled by the block probability because it
7043       // models a copy at the end of each predicated block.
7044       Cost += VF.getKnownMinValue() *
7045               TTI.getCFInstrCost(Instruction::PHI, CostKind);
7046 
7047       // The cost of the non-predicated instruction.
7048       Cost += VF.getKnownMinValue() *
7049               TTI.getArithmeticInstrCost(I->getOpcode(), RetTy, CostKind);
7050 
7051       // The cost of insertelement and extractelement instructions needed for
7052       // scalarization.
7053       Cost += getScalarizationOverhead(I, VF);
7054 
7055       // Scale the cost by the probability of executing the predicated blocks.
7056       // This assumes the predicated block for each vector lane is equally
7057       // likely.
7058       return Cost / getReciprocalPredBlockProb();
7059     }
7060     LLVM_FALLTHROUGH;
7061   case Instruction::Add:
7062   case Instruction::FAdd:
7063   case Instruction::Sub:
7064   case Instruction::FSub:
7065   case Instruction::Mul:
7066   case Instruction::FMul:
7067   case Instruction::FDiv:
7068   case Instruction::FRem:
7069   case Instruction::Shl:
7070   case Instruction::LShr:
7071   case Instruction::AShr:
7072   case Instruction::And:
7073   case Instruction::Or:
7074   case Instruction::Xor: {
7075     // Since we will replace the stride by 1 the multiplication should go away.
7076     if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
7077       return 0;
7078 
7079     // Detect reduction patterns
7080     if (auto RedCost = getReductionPatternCost(I, VF, VectorTy, CostKind))
7081       return *RedCost;
7082 
7083     // Certain instructions can be cheaper to vectorize if they have a constant
7084     // second vector operand. One example of this are shifts on x86.
7085     Value *Op2 = I->getOperand(1);
7086     TargetTransformInfo::OperandValueProperties Op2VP;
7087     TargetTransformInfo::OperandValueKind Op2VK =
7088         TTI.getOperandInfo(Op2, Op2VP);
7089     if (Op2VK == TargetTransformInfo::OK_AnyValue && Legal->isUniform(Op2))
7090       Op2VK = TargetTransformInfo::OK_UniformValue;
7091 
7092     SmallVector<const Value *, 4> Operands(I->operand_values());
7093     return TTI.getArithmeticInstrCost(
7094         I->getOpcode(), VectorTy, CostKind, TargetTransformInfo::OK_AnyValue,
7095         Op2VK, TargetTransformInfo::OP_None, Op2VP, Operands, I);
7096   }
7097   case Instruction::FNeg: {
7098     return TTI.getArithmeticInstrCost(
7099         I->getOpcode(), VectorTy, CostKind, TargetTransformInfo::OK_AnyValue,
7100         TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None,
7101         TargetTransformInfo::OP_None, I->getOperand(0), I);
7102   }
7103   case Instruction::Select: {
7104     SelectInst *SI = cast<SelectInst>(I);
7105     const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
7106     bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
7107 
7108     const Value *Op0, *Op1;
7109     using namespace llvm::PatternMatch;
7110     if (!ScalarCond && (match(I, m_LogicalAnd(m_Value(Op0), m_Value(Op1))) ||
7111                         match(I, m_LogicalOr(m_Value(Op0), m_Value(Op1))))) {
7112       // select x, y, false --> x & y
7113       // select x, true, y --> x | y
7114       TTI::OperandValueProperties Op1VP = TTI::OP_None;
7115       TTI::OperandValueProperties Op2VP = TTI::OP_None;
7116       TTI::OperandValueKind Op1VK = TTI::getOperandInfo(Op0, Op1VP);
7117       TTI::OperandValueKind Op2VK = TTI::getOperandInfo(Op1, Op2VP);
7118       assert(Op0->getType()->getScalarSizeInBits() == 1 &&
7119               Op1->getType()->getScalarSizeInBits() == 1);
7120 
7121       SmallVector<const Value *, 2> Operands{Op0, Op1};
7122       return TTI.getArithmeticInstrCost(
7123           match(I, m_LogicalOr()) ? Instruction::Or : Instruction::And, VectorTy,
7124           CostKind, Op1VK, Op2VK, Op1VP, Op2VP, Operands, I);
7125     }
7126 
7127     Type *CondTy = SI->getCondition()->getType();
7128     if (!ScalarCond)
7129       CondTy = VectorType::get(CondTy, VF);
7130 
7131     CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
7132     if (auto *Cmp = dyn_cast<CmpInst>(SI->getCondition()))
7133       Pred = Cmp->getPredicate();
7134     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy, Pred,
7135                                   CostKind, I);
7136   }
7137   case Instruction::ICmp:
7138   case Instruction::FCmp: {
7139     Type *ValTy = I->getOperand(0)->getType();
7140     Instruction *Op0AsInstruction = dyn_cast<Instruction>(I->getOperand(0));
7141     if (canTruncateToMinimalBitwidth(Op0AsInstruction, VF))
7142       ValTy = IntegerType::get(ValTy->getContext(), MinBWs[Op0AsInstruction]);
7143     VectorTy = ToVectorTy(ValTy, VF);
7144     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, nullptr,
7145                                   cast<CmpInst>(I)->getPredicate(), CostKind,
7146                                   I);
7147   }
7148   case Instruction::Store:
7149   case Instruction::Load: {
7150     ElementCount Width = VF;
7151     if (Width.isVector()) {
7152       InstWidening Decision = getWideningDecision(I, Width);
7153       assert(Decision != CM_Unknown &&
7154              "CM decision should be taken at this point");
7155       if (Decision == CM_Scalarize) {
7156         if (VF.isScalable() && isa<StoreInst>(I))
7157           // We can't scalarize a scalable vector store (even a uniform one
7158           // currently), return an invalid cost so as to prevent vectorization.
7159           return InstructionCost::getInvalid();
7160         Width = ElementCount::getFixed(1);
7161       }
7162     }
7163     VectorTy = ToVectorTy(getLoadStoreType(I), Width);
7164     return getMemoryInstructionCost(I, VF);
7165   }
7166   case Instruction::BitCast:
7167     if (I->getType()->isPointerTy())
7168       return 0;
7169     LLVM_FALLTHROUGH;
7170   case Instruction::ZExt:
7171   case Instruction::SExt:
7172   case Instruction::FPToUI:
7173   case Instruction::FPToSI:
7174   case Instruction::FPExt:
7175   case Instruction::PtrToInt:
7176   case Instruction::IntToPtr:
7177   case Instruction::SIToFP:
7178   case Instruction::UIToFP:
7179   case Instruction::Trunc:
7180   case Instruction::FPTrunc: {
7181     // Computes the CastContextHint from a Load/Store instruction.
7182     auto ComputeCCH = [&](Instruction *I) -> TTI::CastContextHint {
7183       assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
7184              "Expected a load or a store!");
7185 
7186       if (VF.isScalar() || !TheLoop->contains(I))
7187         return TTI::CastContextHint::Normal;
7188 
7189       switch (getWideningDecision(I, VF)) {
7190       case LoopVectorizationCostModel::CM_GatherScatter:
7191         return TTI::CastContextHint::GatherScatter;
7192       case LoopVectorizationCostModel::CM_Interleave:
7193         return TTI::CastContextHint::Interleave;
7194       case LoopVectorizationCostModel::CM_Scalarize:
7195       case LoopVectorizationCostModel::CM_Widen:
7196         return Legal->isMaskRequired(I) ? TTI::CastContextHint::Masked
7197                                         : TTI::CastContextHint::Normal;
7198       case LoopVectorizationCostModel::CM_Widen_Reverse:
7199         return TTI::CastContextHint::Reversed;
7200       case LoopVectorizationCostModel::CM_Unknown:
7201         llvm_unreachable("Instr did not go through cost modelling?");
7202       }
7203 
7204       llvm_unreachable("Unhandled case!");
7205     };
7206 
7207     unsigned Opcode = I->getOpcode();
7208     TTI::CastContextHint CCH = TTI::CastContextHint::None;
7209     // For Trunc, the context is the only user, which must be a StoreInst.
7210     if (Opcode == Instruction::Trunc || Opcode == Instruction::FPTrunc) {
7211       if (I->hasOneUse())
7212         if (StoreInst *Store = dyn_cast<StoreInst>(*I->user_begin()))
7213           CCH = ComputeCCH(Store);
7214     }
7215     // For Z/Sext, the context is the operand, which must be a LoadInst.
7216     else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt ||
7217              Opcode == Instruction::FPExt) {
7218       if (LoadInst *Load = dyn_cast<LoadInst>(I->getOperand(0)))
7219         CCH = ComputeCCH(Load);
7220     }
7221 
7222     // We optimize the truncation of induction variables having constant
7223     // integer steps. The cost of these truncations is the same as the scalar
7224     // operation.
7225     if (isOptimizableIVTruncate(I, VF)) {
7226       auto *Trunc = cast<TruncInst>(I);
7227       return TTI.getCastInstrCost(Instruction::Trunc, Trunc->getDestTy(),
7228                                   Trunc->getSrcTy(), CCH, CostKind, Trunc);
7229     }
7230 
7231     // Detect reduction patterns
7232     if (auto RedCost = getReductionPatternCost(I, VF, VectorTy, CostKind))
7233       return *RedCost;
7234 
7235     Type *SrcScalarTy = I->getOperand(0)->getType();
7236     Type *SrcVecTy =
7237         VectorTy->isVectorTy() ? ToVectorTy(SrcScalarTy, VF) : SrcScalarTy;
7238     if (canTruncateToMinimalBitwidth(I, VF)) {
7239       // This cast is going to be shrunk. This may remove the cast or it might
7240       // turn it into slightly different cast. For example, if MinBW == 16,
7241       // "zext i8 %1 to i32" becomes "zext i8 %1 to i16".
7242       //
7243       // Calculate the modified src and dest types.
7244       Type *MinVecTy = VectorTy;
7245       if (Opcode == Instruction::Trunc) {
7246         SrcVecTy = smallestIntegerVectorType(SrcVecTy, MinVecTy);
7247         VectorTy =
7248             largestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy);
7249       } else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
7250         SrcVecTy = largestIntegerVectorType(SrcVecTy, MinVecTy);
7251         VectorTy =
7252             smallestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy);
7253       }
7254     }
7255 
7256     return TTI.getCastInstrCost(Opcode, VectorTy, SrcVecTy, CCH, CostKind, I);
7257   }
7258   case Instruction::Call: {
7259     if (RecurrenceDescriptor::isFMulAddIntrinsic(I))
7260       if (auto RedCost = getReductionPatternCost(I, VF, VectorTy, CostKind))
7261         return *RedCost;
7262     bool NeedToScalarize;
7263     CallInst *CI = cast<CallInst>(I);
7264     InstructionCost CallCost = getVectorCallCost(CI, VF, NeedToScalarize);
7265     if (getVectorIntrinsicIDForCall(CI, TLI)) {
7266       InstructionCost IntrinsicCost = getVectorIntrinsicCost(CI, VF);
7267       return std::min(CallCost, IntrinsicCost);
7268     }
7269     return CallCost;
7270   }
7271   case Instruction::ExtractValue:
7272     return TTI.getInstructionCost(I, TTI::TCK_RecipThroughput);
7273   case Instruction::Alloca:
7274     // We cannot easily widen alloca to a scalable alloca, as
7275     // the result would need to be a vector of pointers.
7276     if (VF.isScalable())
7277       return InstructionCost::getInvalid();
7278     LLVM_FALLTHROUGH;
7279   default:
7280     // This opcode is unknown. Assume that it is the same as 'mul'.
7281     return TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy, CostKind);
7282   } // end of switch.
7283 }
7284 
7285 char LoopVectorize::ID = 0;
7286 
7287 static const char lv_name[] = "Loop Vectorization";
7288 
7289 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
7290 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
7291 INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
7292 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
7293 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
7294 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
7295 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
7296 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
7297 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
7298 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
7299 INITIALIZE_PASS_DEPENDENCY(LoopAccessLegacyAnalysis)
7300 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
7301 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
7302 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
7303 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
7304 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
7305 
7306 namespace llvm {
7307 
7308 Pass *createLoopVectorizePass() { return new LoopVectorize(); }
7309 
7310 Pass *createLoopVectorizePass(bool InterleaveOnlyWhenForced,
7311                               bool VectorizeOnlyWhenForced) {
7312   return new LoopVectorize(InterleaveOnlyWhenForced, VectorizeOnlyWhenForced);
7313 }
7314 
7315 } // end namespace llvm
7316 
7317 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
7318   // Check if the pointer operand of a load or store instruction is
7319   // consecutive.
7320   if (auto *Ptr = getLoadStorePointerOperand(Inst))
7321     return Legal->isConsecutivePtr(getLoadStoreType(Inst), Ptr);
7322   return false;
7323 }
7324 
7325 void LoopVectorizationCostModel::collectValuesToIgnore() {
7326   // Ignore ephemeral values.
7327   CodeMetrics::collectEphemeralValues(TheLoop, AC, ValuesToIgnore);
7328 
7329   // Find all stores to invariant variables. Since they are going to sink
7330   // outside the loop we do not need calculate cost for them.
7331   for (BasicBlock *BB : TheLoop->blocks())
7332     for (Instruction &I : *BB) {
7333       StoreInst *SI;
7334       if ((SI = dyn_cast<StoreInst>(&I)) &&
7335           Legal->isInvariantAddressOfReduction(SI->getPointerOperand()))
7336         ValuesToIgnore.insert(&I);
7337     }
7338 
7339   // Ignore type-promoting instructions we identified during reduction
7340   // detection.
7341   for (auto &Reduction : Legal->getReductionVars()) {
7342     const RecurrenceDescriptor &RedDes = Reduction.second;
7343     const SmallPtrSetImpl<Instruction *> &Casts = RedDes.getCastInsts();
7344     VecValuesToIgnore.insert(Casts.begin(), Casts.end());
7345   }
7346   // Ignore type-casting instructions we identified during induction
7347   // detection.
7348   for (auto &Induction : Legal->getInductionVars()) {
7349     const InductionDescriptor &IndDes = Induction.second;
7350     const SmallVectorImpl<Instruction *> &Casts = IndDes.getCastInsts();
7351     VecValuesToIgnore.insert(Casts.begin(), Casts.end());
7352   }
7353 }
7354 
7355 void LoopVectorizationCostModel::collectInLoopReductions() {
7356   for (auto &Reduction : Legal->getReductionVars()) {
7357     PHINode *Phi = Reduction.first;
7358     const RecurrenceDescriptor &RdxDesc = Reduction.second;
7359 
7360     // We don't collect reductions that are type promoted (yet).
7361     if (RdxDesc.getRecurrenceType() != Phi->getType())
7362       continue;
7363 
7364     // If the target would prefer this reduction to happen "in-loop", then we
7365     // want to record it as such.
7366     unsigned Opcode = RdxDesc.getOpcode();
7367     if (!PreferInLoopReductions && !useOrderedReductions(RdxDesc) &&
7368         !TTI.preferInLoopReduction(Opcode, Phi->getType(),
7369                                    TargetTransformInfo::ReductionFlags()))
7370       continue;
7371 
7372     // Check that we can correctly put the reductions into the loop, by
7373     // finding the chain of operations that leads from the phi to the loop
7374     // exit value.
7375     SmallVector<Instruction *, 4> ReductionOperations =
7376         RdxDesc.getReductionOpChain(Phi, TheLoop);
7377     bool InLoop = !ReductionOperations.empty();
7378     if (InLoop) {
7379       InLoopReductionChains[Phi] = ReductionOperations;
7380       // Add the elements to InLoopReductionImmediateChains for cost modelling.
7381       Instruction *LastChain = Phi;
7382       for (auto *I : ReductionOperations) {
7383         InLoopReductionImmediateChains[I] = LastChain;
7384         LastChain = I;
7385       }
7386     }
7387     LLVM_DEBUG(dbgs() << "LV: Using " << (InLoop ? "inloop" : "out of loop")
7388                       << " reduction for phi: " << *Phi << "\n");
7389   }
7390 }
7391 
7392 // TODO: we could return a pair of values that specify the max VF and
7393 // min VF, to be used in `buildVPlans(MinVF, MaxVF)` instead of
7394 // `buildVPlans(VF, VF)`. We cannot do it because VPLAN at the moment
7395 // doesn't have a cost model that can choose which plan to execute if
7396 // more than one is generated.
7397 static unsigned determineVPlanVF(const unsigned WidestVectorRegBits,
7398                                  LoopVectorizationCostModel &CM) {
7399   unsigned WidestType;
7400   std::tie(std::ignore, WidestType) = CM.getSmallestAndWidestTypes();
7401   return WidestVectorRegBits / WidestType;
7402 }
7403 
7404 VectorizationFactor
7405 LoopVectorizationPlanner::planInVPlanNativePath(ElementCount UserVF) {
7406   assert(!UserVF.isScalable() && "scalable vectors not yet supported");
7407   ElementCount VF = UserVF;
7408   // Outer loop handling: They may require CFG and instruction level
7409   // transformations before even evaluating whether vectorization is profitable.
7410   // Since we cannot modify the incoming IR, we need to build VPlan upfront in
7411   // the vectorization pipeline.
7412   if (!OrigLoop->isInnermost()) {
7413     // If the user doesn't provide a vectorization factor, determine a
7414     // reasonable one.
7415     if (UserVF.isZero()) {
7416       VF = ElementCount::getFixed(determineVPlanVF(
7417           TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector)
7418               .getFixedSize(),
7419           CM));
7420       LLVM_DEBUG(dbgs() << "LV: VPlan computed VF " << VF << ".\n");
7421 
7422       // Make sure we have a VF > 1 for stress testing.
7423       if (VPlanBuildStressTest && (VF.isScalar() || VF.isZero())) {
7424         LLVM_DEBUG(dbgs() << "LV: VPlan stress testing: "
7425                           << "overriding computed VF.\n");
7426         VF = ElementCount::getFixed(4);
7427       }
7428     }
7429     assert(EnableVPlanNativePath && "VPlan-native path is not enabled.");
7430     assert(isPowerOf2_32(VF.getKnownMinValue()) &&
7431            "VF needs to be a power of two");
7432     LLVM_DEBUG(dbgs() << "LV: Using " << (!UserVF.isZero() ? "user " : "")
7433                       << "VF " << VF << " to build VPlans.\n");
7434     buildVPlans(VF, VF);
7435 
7436     // For VPlan build stress testing, we bail out after VPlan construction.
7437     if (VPlanBuildStressTest)
7438       return VectorizationFactor::Disabled();
7439 
7440     return {VF, 0 /*Cost*/, 0 /* ScalarCost */};
7441   }
7442 
7443   LLVM_DEBUG(
7444       dbgs() << "LV: Not vectorizing. Inner loops aren't supported in the "
7445                 "VPlan-native path.\n");
7446   return VectorizationFactor::Disabled();
7447 }
7448 
7449 Optional<VectorizationFactor>
7450 LoopVectorizationPlanner::plan(ElementCount UserVF, unsigned UserIC) {
7451   assert(OrigLoop->isInnermost() && "Inner loop expected.");
7452   FixedScalableVFPair MaxFactors = CM.computeMaxVF(UserVF, UserIC);
7453   if (!MaxFactors) // Cases that should not to be vectorized nor interleaved.
7454     return None;
7455 
7456   // Invalidate interleave groups if all blocks of loop will be predicated.
7457   if (CM.blockNeedsPredicationForAnyReason(OrigLoop->getHeader()) &&
7458       !useMaskedInterleavedAccesses(*TTI)) {
7459     LLVM_DEBUG(
7460         dbgs()
7461         << "LV: Invalidate all interleaved groups due to fold-tail by masking "
7462            "which requires masked-interleaved support.\n");
7463     if (CM.InterleaveInfo.invalidateGroups())
7464       // Invalidating interleave groups also requires invalidating all decisions
7465       // based on them, which includes widening decisions and uniform and scalar
7466       // values.
7467       CM.invalidateCostModelingDecisions();
7468   }
7469 
7470   ElementCount MaxUserVF =
7471       UserVF.isScalable() ? MaxFactors.ScalableVF : MaxFactors.FixedVF;
7472   bool UserVFIsLegal = ElementCount::isKnownLE(UserVF, MaxUserVF);
7473   if (!UserVF.isZero() && UserVFIsLegal) {
7474     assert(isPowerOf2_32(UserVF.getKnownMinValue()) &&
7475            "VF needs to be a power of two");
7476     // Collect the instructions (and their associated costs) that will be more
7477     // profitable to scalarize.
7478     if (CM.selectUserVectorizationFactor(UserVF)) {
7479       LLVM_DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
7480       CM.collectInLoopReductions();
7481       buildVPlansWithVPRecipes(UserVF, UserVF);
7482       LLVM_DEBUG(printPlans(dbgs()));
7483       return {{UserVF, 0, 0}};
7484     } else
7485       reportVectorizationInfo("UserVF ignored because of invalid costs.",
7486                               "InvalidCost", ORE, OrigLoop);
7487   }
7488 
7489   // Populate the set of Vectorization Factor Candidates.
7490   ElementCountSet VFCandidates;
7491   for (auto VF = ElementCount::getFixed(1);
7492        ElementCount::isKnownLE(VF, MaxFactors.FixedVF); VF *= 2)
7493     VFCandidates.insert(VF);
7494   for (auto VF = ElementCount::getScalable(1);
7495        ElementCount::isKnownLE(VF, MaxFactors.ScalableVF); VF *= 2)
7496     VFCandidates.insert(VF);
7497 
7498   for (const auto &VF : VFCandidates) {
7499     // Collect Uniform and Scalar instructions after vectorization with VF.
7500     CM.collectUniformsAndScalars(VF);
7501 
7502     // Collect the instructions (and their associated costs) that will be more
7503     // profitable to scalarize.
7504     if (VF.isVector())
7505       CM.collectInstsToScalarize(VF);
7506   }
7507 
7508   CM.collectInLoopReductions();
7509   buildVPlansWithVPRecipes(ElementCount::getFixed(1), MaxFactors.FixedVF);
7510   buildVPlansWithVPRecipes(ElementCount::getScalable(1), MaxFactors.ScalableVF);
7511 
7512   LLVM_DEBUG(printPlans(dbgs()));
7513   if (!MaxFactors.hasVector())
7514     return VectorizationFactor::Disabled();
7515 
7516   // Select the optimal vectorization factor.
7517   VectorizationFactor VF = CM.selectVectorizationFactor(VFCandidates);
7518   assert((VF.Width.isScalar() || VF.ScalarCost > 0) && "when vectorizing, the scalar cost must be non-zero.");
7519   return VF;
7520 }
7521 
7522 VPlan &LoopVectorizationPlanner::getBestPlanFor(ElementCount VF) const {
7523   assert(count_if(VPlans,
7524                   [VF](const VPlanPtr &Plan) { return Plan->hasVF(VF); }) ==
7525              1 &&
7526          "Best VF has not a single VPlan.");
7527 
7528   for (const VPlanPtr &Plan : VPlans) {
7529     if (Plan->hasVF(VF))
7530       return *Plan.get();
7531   }
7532   llvm_unreachable("No plan found!");
7533 }
7534 
7535 static void AddRuntimeUnrollDisableMetaData(Loop *L) {
7536   SmallVector<Metadata *, 4> MDs;
7537   // Reserve first location for self reference to the LoopID metadata node.
7538   MDs.push_back(nullptr);
7539   bool IsUnrollMetadata = false;
7540   MDNode *LoopID = L->getLoopID();
7541   if (LoopID) {
7542     // First find existing loop unrolling disable metadata.
7543     for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
7544       auto *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
7545       if (MD) {
7546         const auto *S = dyn_cast<MDString>(MD->getOperand(0));
7547         IsUnrollMetadata =
7548             S && S->getString().startswith("llvm.loop.unroll.disable");
7549       }
7550       MDs.push_back(LoopID->getOperand(i));
7551     }
7552   }
7553 
7554   if (!IsUnrollMetadata) {
7555     // Add runtime unroll disable metadata.
7556     LLVMContext &Context = L->getHeader()->getContext();
7557     SmallVector<Metadata *, 1> DisableOperands;
7558     DisableOperands.push_back(
7559         MDString::get(Context, "llvm.loop.unroll.runtime.disable"));
7560     MDNode *DisableNode = MDNode::get(Context, DisableOperands);
7561     MDs.push_back(DisableNode);
7562     MDNode *NewLoopID = MDNode::get(Context, MDs);
7563     // Set operand 0 to refer to the loop id itself.
7564     NewLoopID->replaceOperandWith(0, NewLoopID);
7565     L->setLoopID(NewLoopID);
7566   }
7567 }
7568 
7569 void LoopVectorizationPlanner::executePlan(ElementCount BestVF, unsigned BestUF,
7570                                            VPlan &BestVPlan,
7571                                            InnerLoopVectorizer &ILV,
7572                                            DominatorTree *DT,
7573                                            bool IsEpilogueVectorization) {
7574   LLVM_DEBUG(dbgs() << "Executing best plan with VF=" << BestVF << ", UF=" << BestUF
7575                     << '\n');
7576 
7577   // Perform the actual loop transformation.
7578 
7579   // 1. Set up the skeleton for vectorization, including vector pre-header and
7580   // middle block. The vector loop is created during VPlan execution.
7581   VPTransformState State{BestVF, BestUF, LI, DT, ILV.Builder, &ILV, &BestVPlan};
7582   Value *CanonicalIVStartValue;
7583   std::tie(State.CFG.PrevBB, CanonicalIVStartValue) =
7584       ILV.createVectorizedLoopSkeleton();
7585 
7586   // Only use noalias metadata when using memory checks guaranteeing no overlap
7587   // across all iterations.
7588   const LoopAccessInfo *LAI = ILV.Legal->getLAI();
7589   if (LAI && !LAI->getRuntimePointerChecking()->getChecks().empty() &&
7590       !LAI->getRuntimePointerChecking()->getDiffChecks()) {
7591 
7592     //  We currently don't use LoopVersioning for the actual loop cloning but we
7593     //  still use it to add the noalias metadata.
7594     //  TODO: Find a better way to re-use LoopVersioning functionality to add
7595     //        metadata.
7596     State.LVer = std::make_unique<LoopVersioning>(
7597         *LAI, LAI->getRuntimePointerChecking()->getChecks(), OrigLoop, LI, DT,
7598         PSE.getSE());
7599     State.LVer->prepareNoAliasMetadata();
7600   }
7601 
7602   ILV.collectPoisonGeneratingRecipes(State);
7603 
7604   ILV.printDebugTracesAtStart();
7605 
7606   //===------------------------------------------------===//
7607   //
7608   // Notice: any optimization or new instruction that go
7609   // into the code below should also be implemented in
7610   // the cost-model.
7611   //
7612   //===------------------------------------------------===//
7613 
7614   // 2. Copy and widen instructions from the old loop into the new loop.
7615   BestVPlan.prepareToExecute(ILV.getOrCreateTripCount(nullptr),
7616                              ILV.getOrCreateVectorTripCount(nullptr),
7617                              CanonicalIVStartValue, State,
7618                              IsEpilogueVectorization);
7619 
7620   BestVPlan.execute(&State);
7621 
7622   // Keep all loop hints from the original loop on the vector loop (we'll
7623   // replace the vectorizer-specific hints below).
7624   MDNode *OrigLoopID = OrigLoop->getLoopID();
7625 
7626   Optional<MDNode *> VectorizedLoopID =
7627       makeFollowupLoopID(OrigLoopID, {LLVMLoopVectorizeFollowupAll,
7628                                       LLVMLoopVectorizeFollowupVectorized});
7629 
7630   VPBasicBlock *HeaderVPBB =
7631       BestVPlan.getVectorLoopRegion()->getEntryBasicBlock();
7632   Loop *L = LI->getLoopFor(State.CFG.VPBB2IRBB[HeaderVPBB]);
7633   if (VectorizedLoopID)
7634     L->setLoopID(VectorizedLoopID.value());
7635   else {
7636     // Keep all loop hints from the original loop on the vector loop (we'll
7637     // replace the vectorizer-specific hints below).
7638     if (MDNode *LID = OrigLoop->getLoopID())
7639       L->setLoopID(LID);
7640 
7641     LoopVectorizeHints Hints(L, true, *ORE);
7642     Hints.setAlreadyVectorized();
7643   }
7644   // Disable runtime unrolling when vectorizing the epilogue loop.
7645   if (CanonicalIVStartValue)
7646     AddRuntimeUnrollDisableMetaData(L);
7647 
7648   // 3. Fix the vectorized code: take care of header phi's, live-outs,
7649   //    predication, updating analyses.
7650   ILV.fixVectorizedLoop(State, BestVPlan);
7651 
7652   ILV.printDebugTracesAtEnd();
7653 }
7654 
7655 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
7656 void LoopVectorizationPlanner::printPlans(raw_ostream &O) {
7657   for (const auto &Plan : VPlans)
7658     if (PrintVPlansInDotFormat)
7659       Plan->printDOT(O);
7660     else
7661       Plan->print(O);
7662 }
7663 #endif
7664 
7665 Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) { return V; }
7666 
7667 //===--------------------------------------------------------------------===//
7668 // EpilogueVectorizerMainLoop
7669 //===--------------------------------------------------------------------===//
7670 
7671 /// This function is partially responsible for generating the control flow
7672 /// depicted in https://llvm.org/docs/Vectorizers.html#epilogue-vectorization.
7673 std::pair<BasicBlock *, Value *>
7674 EpilogueVectorizerMainLoop::createEpilogueVectorizedLoopSkeleton() {
7675   MDNode *OrigLoopID = OrigLoop->getLoopID();
7676 
7677   // Workaround!  Compute the trip count of the original loop and cache it
7678   // before we start modifying the CFG.  This code has a systemic problem
7679   // wherein it tries to run analysis over partially constructed IR; this is
7680   // wrong, and not simply for SCEV.  The trip count of the original loop
7681   // simply happens to be prone to hitting this in practice.  In theory, we
7682   // can hit the same issue for any SCEV, or ValueTracking query done during
7683   // mutation.  See PR49900.
7684   getOrCreateTripCount(OrigLoop->getLoopPreheader());
7685   createVectorLoopSkeleton("");
7686 
7687   // Generate the code to check the minimum iteration count of the vector
7688   // epilogue (see below).
7689   EPI.EpilogueIterationCountCheck =
7690       emitIterationCountCheck(LoopScalarPreHeader, true);
7691   EPI.EpilogueIterationCountCheck->setName("iter.check");
7692 
7693   // Generate the code to check any assumptions that we've made for SCEV
7694   // expressions.
7695   EPI.SCEVSafetyCheck = emitSCEVChecks(LoopScalarPreHeader);
7696 
7697   // Generate the code that checks at runtime if arrays overlap. We put the
7698   // checks into a separate block to make the more common case of few elements
7699   // faster.
7700   EPI.MemSafetyCheck = emitMemRuntimeChecks(LoopScalarPreHeader);
7701 
7702   // Generate the iteration count check for the main loop, *after* the check
7703   // for the epilogue loop, so that the path-length is shorter for the case
7704   // that goes directly through the vector epilogue. The longer-path length for
7705   // the main loop is compensated for, by the gain from vectorizing the larger
7706   // trip count. Note: the branch will get updated later on when we vectorize
7707   // the epilogue.
7708   EPI.MainLoopIterationCountCheck =
7709       emitIterationCountCheck(LoopScalarPreHeader, false);
7710 
7711   // Generate the induction variable.
7712   EPI.VectorTripCount = getOrCreateVectorTripCount(LoopVectorPreHeader);
7713 
7714   // Skip induction resume value creation here because they will be created in
7715   // the second pass. If we created them here, they wouldn't be used anyway,
7716   // because the vplan in the second pass still contains the inductions from the
7717   // original loop.
7718 
7719   return {completeLoopSkeleton(OrigLoopID), nullptr};
7720 }
7721 
7722 void EpilogueVectorizerMainLoop::printDebugTracesAtStart() {
7723   LLVM_DEBUG({
7724     dbgs() << "Create Skeleton for epilogue vectorized loop (first pass)\n"
7725            << "Main Loop VF:" << EPI.MainLoopVF
7726            << ", Main Loop UF:" << EPI.MainLoopUF
7727            << ", Epilogue Loop VF:" << EPI.EpilogueVF
7728            << ", Epilogue Loop UF:" << EPI.EpilogueUF << "\n";
7729   });
7730 }
7731 
7732 void EpilogueVectorizerMainLoop::printDebugTracesAtEnd() {
7733   DEBUG_WITH_TYPE(VerboseDebug, {
7734     dbgs() << "intermediate fn:\n"
7735            << *OrigLoop->getHeader()->getParent() << "\n";
7736   });
7737 }
7738 
7739 BasicBlock *
7740 EpilogueVectorizerMainLoop::emitIterationCountCheck(BasicBlock *Bypass,
7741                                                     bool ForEpilogue) {
7742   assert(Bypass && "Expected valid bypass basic block.");
7743   ElementCount VFactor = ForEpilogue ? EPI.EpilogueVF : VF;
7744   unsigned UFactor = ForEpilogue ? EPI.EpilogueUF : UF;
7745   Value *Count = getOrCreateTripCount(LoopVectorPreHeader);
7746   // Reuse existing vector loop preheader for TC checks.
7747   // Note that new preheader block is generated for vector loop.
7748   BasicBlock *const TCCheckBlock = LoopVectorPreHeader;
7749   IRBuilder<> Builder(TCCheckBlock->getTerminator());
7750 
7751   // Generate code to check if the loop's trip count is less than VF * UF of the
7752   // main vector loop.
7753   auto P = Cost->requiresScalarEpilogue(ForEpilogue ? EPI.EpilogueVF : VF) ?
7754       ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT;
7755 
7756   Value *CheckMinIters = Builder.CreateICmp(
7757       P, Count, createStepForVF(Builder, Count->getType(), VFactor, UFactor),
7758       "min.iters.check");
7759 
7760   if (!ForEpilogue)
7761     TCCheckBlock->setName("vector.main.loop.iter.check");
7762 
7763   // Create new preheader for vector loop.
7764   LoopVectorPreHeader = SplitBlock(TCCheckBlock, TCCheckBlock->getTerminator(),
7765                                    DT, LI, nullptr, "vector.ph");
7766 
7767   if (ForEpilogue) {
7768     assert(DT->properlyDominates(DT->getNode(TCCheckBlock),
7769                                  DT->getNode(Bypass)->getIDom()) &&
7770            "TC check is expected to dominate Bypass");
7771 
7772     // Update dominator for Bypass & LoopExit.
7773     DT->changeImmediateDominator(Bypass, TCCheckBlock);
7774     if (!Cost->requiresScalarEpilogue(EPI.EpilogueVF))
7775       // For loops with multiple exits, there's no edge from the middle block
7776       // to exit blocks (as the epilogue must run) and thus no need to update
7777       // the immediate dominator of the exit blocks.
7778       DT->changeImmediateDominator(LoopExitBlock, TCCheckBlock);
7779 
7780     LoopBypassBlocks.push_back(TCCheckBlock);
7781 
7782     // Save the trip count so we don't have to regenerate it in the
7783     // vec.epilog.iter.check. This is safe to do because the trip count
7784     // generated here dominates the vector epilog iter check.
7785     EPI.TripCount = Count;
7786   }
7787 
7788   ReplaceInstWithInst(
7789       TCCheckBlock->getTerminator(),
7790       BranchInst::Create(Bypass, LoopVectorPreHeader, CheckMinIters));
7791 
7792   return TCCheckBlock;
7793 }
7794 
7795 //===--------------------------------------------------------------------===//
7796 // EpilogueVectorizerEpilogueLoop
7797 //===--------------------------------------------------------------------===//
7798 
7799 /// This function is partially responsible for generating the control flow
7800 /// depicted in https://llvm.org/docs/Vectorizers.html#epilogue-vectorization.
7801 std::pair<BasicBlock *, Value *>
7802 EpilogueVectorizerEpilogueLoop::createEpilogueVectorizedLoopSkeleton() {
7803   MDNode *OrigLoopID = OrigLoop->getLoopID();
7804   createVectorLoopSkeleton("vec.epilog.");
7805 
7806   // Now, compare the remaining count and if there aren't enough iterations to
7807   // execute the vectorized epilogue skip to the scalar part.
7808   BasicBlock *VecEpilogueIterationCountCheck = LoopVectorPreHeader;
7809   VecEpilogueIterationCountCheck->setName("vec.epilog.iter.check");
7810   LoopVectorPreHeader =
7811       SplitBlock(LoopVectorPreHeader, LoopVectorPreHeader->getTerminator(), DT,
7812                  LI, nullptr, "vec.epilog.ph");
7813   emitMinimumVectorEpilogueIterCountCheck(LoopScalarPreHeader,
7814                                           VecEpilogueIterationCountCheck);
7815 
7816   // Adjust the control flow taking the state info from the main loop
7817   // vectorization into account.
7818   assert(EPI.MainLoopIterationCountCheck && EPI.EpilogueIterationCountCheck &&
7819          "expected this to be saved from the previous pass.");
7820   EPI.MainLoopIterationCountCheck->getTerminator()->replaceUsesOfWith(
7821       VecEpilogueIterationCountCheck, LoopVectorPreHeader);
7822 
7823   DT->changeImmediateDominator(LoopVectorPreHeader,
7824                                EPI.MainLoopIterationCountCheck);
7825 
7826   EPI.EpilogueIterationCountCheck->getTerminator()->replaceUsesOfWith(
7827       VecEpilogueIterationCountCheck, LoopScalarPreHeader);
7828 
7829   if (EPI.SCEVSafetyCheck)
7830     EPI.SCEVSafetyCheck->getTerminator()->replaceUsesOfWith(
7831         VecEpilogueIterationCountCheck, LoopScalarPreHeader);
7832   if (EPI.MemSafetyCheck)
7833     EPI.MemSafetyCheck->getTerminator()->replaceUsesOfWith(
7834         VecEpilogueIterationCountCheck, LoopScalarPreHeader);
7835 
7836   DT->changeImmediateDominator(
7837       VecEpilogueIterationCountCheck,
7838       VecEpilogueIterationCountCheck->getSinglePredecessor());
7839 
7840   DT->changeImmediateDominator(LoopScalarPreHeader,
7841                                EPI.EpilogueIterationCountCheck);
7842   if (!Cost->requiresScalarEpilogue(EPI.EpilogueVF))
7843     // If there is an epilogue which must run, there's no edge from the
7844     // middle block to exit blocks  and thus no need to update the immediate
7845     // dominator of the exit blocks.
7846     DT->changeImmediateDominator(LoopExitBlock,
7847                                  EPI.EpilogueIterationCountCheck);
7848 
7849   // Keep track of bypass blocks, as they feed start values to the induction
7850   // phis in the scalar loop preheader.
7851   if (EPI.SCEVSafetyCheck)
7852     LoopBypassBlocks.push_back(EPI.SCEVSafetyCheck);
7853   if (EPI.MemSafetyCheck)
7854     LoopBypassBlocks.push_back(EPI.MemSafetyCheck);
7855   LoopBypassBlocks.push_back(EPI.EpilogueIterationCountCheck);
7856 
7857   // The vec.epilog.iter.check block may contain Phi nodes from reductions which
7858   // merge control-flow from the latch block and the middle block. Update the
7859   // incoming values here and move the Phi into the preheader.
7860   SmallVector<PHINode *, 4> PhisInBlock;
7861   for (PHINode &Phi : VecEpilogueIterationCountCheck->phis())
7862     PhisInBlock.push_back(&Phi);
7863 
7864   for (PHINode *Phi : PhisInBlock) {
7865     Phi->replaceIncomingBlockWith(
7866         VecEpilogueIterationCountCheck->getSinglePredecessor(),
7867         VecEpilogueIterationCountCheck);
7868     Phi->removeIncomingValue(EPI.EpilogueIterationCountCheck);
7869     if (EPI.SCEVSafetyCheck)
7870       Phi->removeIncomingValue(EPI.SCEVSafetyCheck);
7871     if (EPI.MemSafetyCheck)
7872       Phi->removeIncomingValue(EPI.MemSafetyCheck);
7873     Phi->moveBefore(LoopVectorPreHeader->getFirstNonPHI());
7874   }
7875 
7876   // Generate a resume induction for the vector epilogue and put it in the
7877   // vector epilogue preheader
7878   Type *IdxTy = Legal->getWidestInductionType();
7879   PHINode *EPResumeVal = PHINode::Create(IdxTy, 2, "vec.epilog.resume.val",
7880                                          LoopVectorPreHeader->getFirstNonPHI());
7881   EPResumeVal->addIncoming(EPI.VectorTripCount, VecEpilogueIterationCountCheck);
7882   EPResumeVal->addIncoming(ConstantInt::get(IdxTy, 0),
7883                            EPI.MainLoopIterationCountCheck);
7884 
7885   // Generate induction resume values. These variables save the new starting
7886   // indexes for the scalar loop. They are used to test if there are any tail
7887   // iterations left once the vector loop has completed.
7888   // Note that when the vectorized epilogue is skipped due to iteration count
7889   // check, then the resume value for the induction variable comes from
7890   // the trip count of the main vector loop, hence passing the AdditionalBypass
7891   // argument.
7892   createInductionResumeValues({VecEpilogueIterationCountCheck,
7893                                EPI.VectorTripCount} /* AdditionalBypass */);
7894 
7895   return {completeLoopSkeleton(OrigLoopID), EPResumeVal};
7896 }
7897 
7898 BasicBlock *
7899 EpilogueVectorizerEpilogueLoop::emitMinimumVectorEpilogueIterCountCheck(
7900     BasicBlock *Bypass, BasicBlock *Insert) {
7901 
7902   assert(EPI.TripCount &&
7903          "Expected trip count to have been safed in the first pass.");
7904   assert(
7905       (!isa<Instruction>(EPI.TripCount) ||
7906        DT->dominates(cast<Instruction>(EPI.TripCount)->getParent(), Insert)) &&
7907       "saved trip count does not dominate insertion point.");
7908   Value *TC = EPI.TripCount;
7909   IRBuilder<> Builder(Insert->getTerminator());
7910   Value *Count = Builder.CreateSub(TC, EPI.VectorTripCount, "n.vec.remaining");
7911 
7912   // Generate code to check if the loop's trip count is less than VF * UF of the
7913   // vector epilogue loop.
7914   auto P = Cost->requiresScalarEpilogue(EPI.EpilogueVF) ?
7915       ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT;
7916 
7917   Value *CheckMinIters =
7918       Builder.CreateICmp(P, Count,
7919                          createStepForVF(Builder, Count->getType(),
7920                                          EPI.EpilogueVF, EPI.EpilogueUF),
7921                          "min.epilog.iters.check");
7922 
7923   ReplaceInstWithInst(
7924       Insert->getTerminator(),
7925       BranchInst::Create(Bypass, LoopVectorPreHeader, CheckMinIters));
7926 
7927   LoopBypassBlocks.push_back(Insert);
7928   return Insert;
7929 }
7930 
7931 void EpilogueVectorizerEpilogueLoop::printDebugTracesAtStart() {
7932   LLVM_DEBUG({
7933     dbgs() << "Create Skeleton for epilogue vectorized loop (second pass)\n"
7934            << "Epilogue Loop VF:" << EPI.EpilogueVF
7935            << ", Epilogue Loop UF:" << EPI.EpilogueUF << "\n";
7936   });
7937 }
7938 
7939 void EpilogueVectorizerEpilogueLoop::printDebugTracesAtEnd() {
7940   DEBUG_WITH_TYPE(VerboseDebug, {
7941     dbgs() << "final fn:\n" << *OrigLoop->getHeader()->getParent() << "\n";
7942   });
7943 }
7944 
7945 bool LoopVectorizationPlanner::getDecisionAndClampRange(
7946     const std::function<bool(ElementCount)> &Predicate, VFRange &Range) {
7947   assert(!Range.isEmpty() && "Trying to test an empty VF range.");
7948   bool PredicateAtRangeStart = Predicate(Range.Start);
7949 
7950   for (ElementCount TmpVF = Range.Start * 2;
7951        ElementCount::isKnownLT(TmpVF, Range.End); TmpVF *= 2)
7952     if (Predicate(TmpVF) != PredicateAtRangeStart) {
7953       Range.End = TmpVF;
7954       break;
7955     }
7956 
7957   return PredicateAtRangeStart;
7958 }
7959 
7960 /// Build VPlans for the full range of feasible VF's = {\p MinVF, 2 * \p MinVF,
7961 /// 4 * \p MinVF, ..., \p MaxVF} by repeatedly building a VPlan for a sub-range
7962 /// of VF's starting at a given VF and extending it as much as possible. Each
7963 /// vectorization decision can potentially shorten this sub-range during
7964 /// buildVPlan().
7965 void LoopVectorizationPlanner::buildVPlans(ElementCount MinVF,
7966                                            ElementCount MaxVF) {
7967   auto MaxVFPlusOne = MaxVF.getWithIncrement(1);
7968   for (ElementCount VF = MinVF; ElementCount::isKnownLT(VF, MaxVFPlusOne);) {
7969     VFRange SubRange = {VF, MaxVFPlusOne};
7970     VPlans.push_back(buildVPlan(SubRange));
7971     VF = SubRange.End;
7972   }
7973 }
7974 
7975 VPValue *VPRecipeBuilder::createEdgeMask(BasicBlock *Src, BasicBlock *Dst,
7976                                          VPlanPtr &Plan) {
7977   assert(is_contained(predecessors(Dst), Src) && "Invalid edge");
7978 
7979   // Look for cached value.
7980   std::pair<BasicBlock *, BasicBlock *> Edge(Src, Dst);
7981   EdgeMaskCacheTy::iterator ECEntryIt = EdgeMaskCache.find(Edge);
7982   if (ECEntryIt != EdgeMaskCache.end())
7983     return ECEntryIt->second;
7984 
7985   VPValue *SrcMask = createBlockInMask(Src, Plan);
7986 
7987   // The terminator has to be a branch inst!
7988   BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
7989   assert(BI && "Unexpected terminator found");
7990 
7991   if (!BI->isConditional() || BI->getSuccessor(0) == BI->getSuccessor(1))
7992     return EdgeMaskCache[Edge] = SrcMask;
7993 
7994   // If source is an exiting block, we know the exit edge is dynamically dead
7995   // in the vector loop, and thus we don't need to restrict the mask.  Avoid
7996   // adding uses of an otherwise potentially dead instruction.
7997   if (OrigLoop->isLoopExiting(Src))
7998     return EdgeMaskCache[Edge] = SrcMask;
7999 
8000   VPValue *EdgeMask = Plan->getOrAddVPValue(BI->getCondition());
8001   assert(EdgeMask && "No Edge Mask found for condition");
8002 
8003   if (BI->getSuccessor(0) != Dst)
8004     EdgeMask = Builder.createNot(EdgeMask, BI->getDebugLoc());
8005 
8006   if (SrcMask) { // Otherwise block in-mask is all-one, no need to AND.
8007     // The condition is 'SrcMask && EdgeMask', which is equivalent to
8008     // 'select i1 SrcMask, i1 EdgeMask, i1 false'.
8009     // The select version does not introduce new UB if SrcMask is false and
8010     // EdgeMask is poison. Using 'and' here introduces undefined behavior.
8011     VPValue *False = Plan->getOrAddVPValue(
8012         ConstantInt::getFalse(BI->getCondition()->getType()));
8013     EdgeMask =
8014         Builder.createSelect(SrcMask, EdgeMask, False, BI->getDebugLoc());
8015   }
8016 
8017   return EdgeMaskCache[Edge] = EdgeMask;
8018 }
8019 
8020 VPValue *VPRecipeBuilder::createBlockInMask(BasicBlock *BB, VPlanPtr &Plan) {
8021   assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
8022 
8023   // Look for cached value.
8024   BlockMaskCacheTy::iterator BCEntryIt = BlockMaskCache.find(BB);
8025   if (BCEntryIt != BlockMaskCache.end())
8026     return BCEntryIt->second;
8027 
8028   // All-one mask is modelled as no-mask following the convention for masked
8029   // load/store/gather/scatter. Initialize BlockMask to no-mask.
8030   VPValue *BlockMask = nullptr;
8031 
8032   if (OrigLoop->getHeader() == BB) {
8033     if (!CM.blockNeedsPredicationForAnyReason(BB))
8034       return BlockMaskCache[BB] = BlockMask; // Loop incoming mask is all-one.
8035 
8036     assert(CM.foldTailByMasking() && "must fold the tail");
8037 
8038     // If we're using the active lane mask for control flow, then we get the
8039     // mask from the active lane mask PHI that is cached in the VPlan.
8040     PredicationStyle EmitGetActiveLaneMask = CM.TTI.emitGetActiveLaneMask();
8041     if (EmitGetActiveLaneMask == PredicationStyle::DataAndControlFlow)
8042       return BlockMaskCache[BB] = Plan->getActiveLaneMaskPhi();
8043 
8044     // Introduce the early-exit compare IV <= BTC to form header block mask.
8045     // This is used instead of IV < TC because TC may wrap, unlike BTC. Start by
8046     // constructing the desired canonical IV in the header block as its first
8047     // non-phi instructions.
8048 
8049     VPBasicBlock *HeaderVPBB =
8050         Plan->getVectorLoopRegion()->getEntryBasicBlock();
8051     auto NewInsertionPoint = HeaderVPBB->getFirstNonPhi();
8052     auto *IV = new VPWidenCanonicalIVRecipe(Plan->getCanonicalIV());
8053     HeaderVPBB->insert(IV, HeaderVPBB->getFirstNonPhi());
8054 
8055     VPBuilder::InsertPointGuard Guard(Builder);
8056     Builder.setInsertPoint(HeaderVPBB, NewInsertionPoint);
8057     if (EmitGetActiveLaneMask != PredicationStyle::None) {
8058       VPValue *TC = Plan->getOrCreateTripCount();
8059       BlockMask = Builder.createNaryOp(VPInstruction::ActiveLaneMask, {IV, TC},
8060                                        nullptr, "active.lane.mask");
8061     } else {
8062       VPValue *BTC = Plan->getOrCreateBackedgeTakenCount();
8063       BlockMask = Builder.createNaryOp(VPInstruction::ICmpULE, {IV, BTC});
8064     }
8065     return BlockMaskCache[BB] = BlockMask;
8066   }
8067 
8068   // This is the block mask. We OR all incoming edges.
8069   for (auto *Predecessor : predecessors(BB)) {
8070     VPValue *EdgeMask = createEdgeMask(Predecessor, BB, Plan);
8071     if (!EdgeMask) // Mask of predecessor is all-one so mask of block is too.
8072       return BlockMaskCache[BB] = EdgeMask;
8073 
8074     if (!BlockMask) { // BlockMask has its initialized nullptr value.
8075       BlockMask = EdgeMask;
8076       continue;
8077     }
8078 
8079     BlockMask = Builder.createOr(BlockMask, EdgeMask, {});
8080   }
8081 
8082   return BlockMaskCache[BB] = BlockMask;
8083 }
8084 
8085 VPRecipeBase *VPRecipeBuilder::tryToWidenMemory(Instruction *I,
8086                                                 ArrayRef<VPValue *> Operands,
8087                                                 VFRange &Range,
8088                                                 VPlanPtr &Plan) {
8089   assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
8090          "Must be called with either a load or store");
8091 
8092   auto willWiden = [&](ElementCount VF) -> bool {
8093     LoopVectorizationCostModel::InstWidening Decision =
8094         CM.getWideningDecision(I, VF);
8095     assert(Decision != LoopVectorizationCostModel::CM_Unknown &&
8096            "CM decision should be taken at this point.");
8097     if (Decision == LoopVectorizationCostModel::CM_Interleave)
8098       return true;
8099     if (CM.isScalarAfterVectorization(I, VF) ||
8100         CM.isProfitableToScalarize(I, VF))
8101       return false;
8102     return Decision != LoopVectorizationCostModel::CM_Scalarize;
8103   };
8104 
8105   if (!LoopVectorizationPlanner::getDecisionAndClampRange(willWiden, Range))
8106     return nullptr;
8107 
8108   VPValue *Mask = nullptr;
8109   if (Legal->isMaskRequired(I))
8110     Mask = createBlockInMask(I->getParent(), Plan);
8111 
8112   // Determine if the pointer operand of the access is either consecutive or
8113   // reverse consecutive.
8114   LoopVectorizationCostModel::InstWidening Decision =
8115       CM.getWideningDecision(I, Range.Start);
8116   bool Reverse = Decision == LoopVectorizationCostModel::CM_Widen_Reverse;
8117   bool Consecutive =
8118       Reverse || Decision == LoopVectorizationCostModel::CM_Widen;
8119 
8120   if (LoadInst *Load = dyn_cast<LoadInst>(I))
8121     return new VPWidenMemoryInstructionRecipe(*Load, Operands[0], Mask,
8122                                               Consecutive, Reverse);
8123 
8124   StoreInst *Store = cast<StoreInst>(I);
8125   return new VPWidenMemoryInstructionRecipe(*Store, Operands[1], Operands[0],
8126                                             Mask, Consecutive, Reverse);
8127 }
8128 
8129 /// Creates a VPWidenIntOrFpInductionRecpipe for \p Phi. If needed, it will also
8130 /// insert a recipe to expand the step for the induction recipe.
8131 static VPWidenIntOrFpInductionRecipe *createWidenInductionRecipes(
8132     PHINode *Phi, Instruction *PhiOrTrunc, VPValue *Start,
8133     const InductionDescriptor &IndDesc, LoopVectorizationCostModel &CM,
8134     VPlan &Plan, ScalarEvolution &SE, Loop &OrigLoop, VFRange &Range) {
8135   // Returns true if an instruction \p I should be scalarized instead of
8136   // vectorized for the chosen vectorization factor.
8137   auto ShouldScalarizeInstruction = [&CM](Instruction *I, ElementCount VF) {
8138     return CM.isScalarAfterVectorization(I, VF) ||
8139            CM.isProfitableToScalarize(I, VF);
8140   };
8141 
8142   bool NeedsScalarIVOnly = LoopVectorizationPlanner::getDecisionAndClampRange(
8143       [&](ElementCount VF) {
8144         return ShouldScalarizeInstruction(PhiOrTrunc, VF);
8145       },
8146       Range);
8147   assert(IndDesc.getStartValue() ==
8148          Phi->getIncomingValueForBlock(OrigLoop.getLoopPreheader()));
8149   assert(SE.isLoopInvariant(IndDesc.getStep(), &OrigLoop) &&
8150          "step must be loop invariant");
8151 
8152   VPValue *Step =
8153       vputils::getOrCreateVPValueForSCEVExpr(Plan, IndDesc.getStep(), SE);
8154   if (auto *TruncI = dyn_cast<TruncInst>(PhiOrTrunc)) {
8155     return new VPWidenIntOrFpInductionRecipe(Phi, Start, Step, IndDesc, TruncI,
8156                                              !NeedsScalarIVOnly);
8157   }
8158   assert(isa<PHINode>(PhiOrTrunc) && "must be a phi node here");
8159   return new VPWidenIntOrFpInductionRecipe(Phi, Start, Step, IndDesc,
8160                                            !NeedsScalarIVOnly);
8161 }
8162 
8163 VPRecipeBase *VPRecipeBuilder::tryToOptimizeInductionPHI(
8164     PHINode *Phi, ArrayRef<VPValue *> Operands, VPlan &Plan, VFRange &Range) {
8165 
8166   // Check if this is an integer or fp induction. If so, build the recipe that
8167   // produces its scalar and vector values.
8168   if (auto *II = Legal->getIntOrFpInductionDescriptor(Phi))
8169     return createWidenInductionRecipes(Phi, Phi, Operands[0], *II, CM, Plan,
8170                                        *PSE.getSE(), *OrigLoop, Range);
8171 
8172   // Check if this is pointer induction. If so, build the recipe for it.
8173   if (auto *II = Legal->getPointerInductionDescriptor(Phi))
8174     return new VPWidenPointerInductionRecipe(Phi, Operands[0], *II,
8175                                              *PSE.getSE());
8176   return nullptr;
8177 }
8178 
8179 VPWidenIntOrFpInductionRecipe *VPRecipeBuilder::tryToOptimizeInductionTruncate(
8180     TruncInst *I, ArrayRef<VPValue *> Operands, VFRange &Range, VPlan &Plan) {
8181   // Optimize the special case where the source is a constant integer
8182   // induction variable. Notice that we can only optimize the 'trunc' case
8183   // because (a) FP conversions lose precision, (b) sext/zext may wrap, and
8184   // (c) other casts depend on pointer size.
8185 
8186   // Determine whether \p K is a truncation based on an induction variable that
8187   // can be optimized.
8188   auto isOptimizableIVTruncate =
8189       [&](Instruction *K) -> std::function<bool(ElementCount)> {
8190     return [=](ElementCount VF) -> bool {
8191       return CM.isOptimizableIVTruncate(K, VF);
8192     };
8193   };
8194 
8195   if (LoopVectorizationPlanner::getDecisionAndClampRange(
8196           isOptimizableIVTruncate(I), Range)) {
8197 
8198     auto *Phi = cast<PHINode>(I->getOperand(0));
8199     const InductionDescriptor &II = *Legal->getIntOrFpInductionDescriptor(Phi);
8200     VPValue *Start = Plan.getOrAddVPValue(II.getStartValue());
8201     return createWidenInductionRecipes(Phi, I, Start, II, CM, Plan,
8202                                        *PSE.getSE(), *OrigLoop, Range);
8203   }
8204   return nullptr;
8205 }
8206 
8207 VPRecipeOrVPValueTy VPRecipeBuilder::tryToBlend(PHINode *Phi,
8208                                                 ArrayRef<VPValue *> Operands,
8209                                                 VPlanPtr &Plan) {
8210   // If all incoming values are equal, the incoming VPValue can be used directly
8211   // instead of creating a new VPBlendRecipe.
8212   VPValue *FirstIncoming = Operands[0];
8213   if (all_of(Operands, [FirstIncoming](const VPValue *Inc) {
8214         return FirstIncoming == Inc;
8215       })) {
8216     return Operands[0];
8217   }
8218 
8219   unsigned NumIncoming = Phi->getNumIncomingValues();
8220   // For in-loop reductions, we do not need to create an additional select.
8221   VPValue *InLoopVal = nullptr;
8222   for (unsigned In = 0; In < NumIncoming; In++) {
8223     PHINode *PhiOp =
8224         dyn_cast_or_null<PHINode>(Operands[In]->getUnderlyingValue());
8225     if (PhiOp && CM.isInLoopReduction(PhiOp)) {
8226       assert(!InLoopVal && "Found more than one in-loop reduction!");
8227       InLoopVal = Operands[In];
8228     }
8229   }
8230 
8231   assert((!InLoopVal || NumIncoming == 2) &&
8232          "Found an in-loop reduction for PHI with unexpected number of "
8233          "incoming values");
8234   if (InLoopVal)
8235     return Operands[Operands[0] == InLoopVal ? 1 : 0];
8236 
8237   // We know that all PHIs in non-header blocks are converted into selects, so
8238   // we don't have to worry about the insertion order and we can just use the
8239   // builder. At this point we generate the predication tree. There may be
8240   // duplications since this is a simple recursive scan, but future
8241   // optimizations will clean it up.
8242   SmallVector<VPValue *, 2> OperandsWithMask;
8243 
8244   for (unsigned In = 0; In < NumIncoming; In++) {
8245     VPValue *EdgeMask =
8246       createEdgeMask(Phi->getIncomingBlock(In), Phi->getParent(), Plan);
8247     assert((EdgeMask || NumIncoming == 1) &&
8248            "Multiple predecessors with one having a full mask");
8249     OperandsWithMask.push_back(Operands[In]);
8250     if (EdgeMask)
8251       OperandsWithMask.push_back(EdgeMask);
8252   }
8253   return toVPRecipeResult(new VPBlendRecipe(Phi, OperandsWithMask));
8254 }
8255 
8256 VPWidenCallRecipe *VPRecipeBuilder::tryToWidenCall(CallInst *CI,
8257                                                    ArrayRef<VPValue *> Operands,
8258                                                    VFRange &Range) const {
8259 
8260   bool IsPredicated = LoopVectorizationPlanner::getDecisionAndClampRange(
8261       [this, CI](ElementCount VF) {
8262         return CM.isScalarWithPredication(CI, VF);
8263       },
8264       Range);
8265 
8266   if (IsPredicated)
8267     return nullptr;
8268 
8269   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
8270   if (ID && (ID == Intrinsic::assume || ID == Intrinsic::lifetime_end ||
8271              ID == Intrinsic::lifetime_start || ID == Intrinsic::sideeffect ||
8272              ID == Intrinsic::pseudoprobe ||
8273              ID == Intrinsic::experimental_noalias_scope_decl))
8274     return nullptr;
8275 
8276   auto willWiden = [&](ElementCount VF) -> bool {
8277     Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
8278     // The following case may be scalarized depending on the VF.
8279     // The flag shows whether we use Intrinsic or a usual Call for vectorized
8280     // version of the instruction.
8281     // Is it beneficial to perform intrinsic call compared to lib call?
8282     bool NeedToScalarize = false;
8283     InstructionCost CallCost = CM.getVectorCallCost(CI, VF, NeedToScalarize);
8284     InstructionCost IntrinsicCost = ID ? CM.getVectorIntrinsicCost(CI, VF) : 0;
8285     bool UseVectorIntrinsic = ID && IntrinsicCost <= CallCost;
8286     return UseVectorIntrinsic || !NeedToScalarize;
8287   };
8288 
8289   if (!LoopVectorizationPlanner::getDecisionAndClampRange(willWiden, Range))
8290     return nullptr;
8291 
8292   ArrayRef<VPValue *> Ops = Operands.take_front(CI->arg_size());
8293   return new VPWidenCallRecipe(*CI, make_range(Ops.begin(), Ops.end()));
8294 }
8295 
8296 bool VPRecipeBuilder::shouldWiden(Instruction *I, VFRange &Range) const {
8297   assert(!isa<BranchInst>(I) && !isa<PHINode>(I) && !isa<LoadInst>(I) &&
8298          !isa<StoreInst>(I) && "Instruction should have been handled earlier");
8299   // Instruction should be widened, unless it is scalar after vectorization,
8300   // scalarization is profitable or it is predicated.
8301   auto WillScalarize = [this, I](ElementCount VF) -> bool {
8302     return CM.isScalarAfterVectorization(I, VF) ||
8303            CM.isProfitableToScalarize(I, VF) ||
8304            CM.isScalarWithPredication(I, VF);
8305   };
8306   return !LoopVectorizationPlanner::getDecisionAndClampRange(WillScalarize,
8307                                                              Range);
8308 }
8309 
8310 VPWidenRecipe *VPRecipeBuilder::tryToWiden(Instruction *I,
8311                                            ArrayRef<VPValue *> Operands) const {
8312   auto IsVectorizableOpcode = [](unsigned Opcode) {
8313     switch (Opcode) {
8314     case Instruction::Add:
8315     case Instruction::And:
8316     case Instruction::AShr:
8317     case Instruction::BitCast:
8318     case Instruction::FAdd:
8319     case Instruction::FCmp:
8320     case Instruction::FDiv:
8321     case Instruction::FMul:
8322     case Instruction::FNeg:
8323     case Instruction::FPExt:
8324     case Instruction::FPToSI:
8325     case Instruction::FPToUI:
8326     case Instruction::FPTrunc:
8327     case Instruction::FRem:
8328     case Instruction::FSub:
8329     case Instruction::ICmp:
8330     case Instruction::IntToPtr:
8331     case Instruction::LShr:
8332     case Instruction::Mul:
8333     case Instruction::Or:
8334     case Instruction::PtrToInt:
8335     case Instruction::SDiv:
8336     case Instruction::Select:
8337     case Instruction::SExt:
8338     case Instruction::Shl:
8339     case Instruction::SIToFP:
8340     case Instruction::SRem:
8341     case Instruction::Sub:
8342     case Instruction::Trunc:
8343     case Instruction::UDiv:
8344     case Instruction::UIToFP:
8345     case Instruction::URem:
8346     case Instruction::Xor:
8347     case Instruction::ZExt:
8348     case Instruction::Freeze:
8349       return true;
8350     }
8351     return false;
8352   };
8353 
8354   if (!IsVectorizableOpcode(I->getOpcode()))
8355     return nullptr;
8356 
8357   // Success: widen this instruction.
8358   return new VPWidenRecipe(*I, make_range(Operands.begin(), Operands.end()));
8359 }
8360 
8361 void VPRecipeBuilder::fixHeaderPhis() {
8362   BasicBlock *OrigLatch = OrigLoop->getLoopLatch();
8363   for (VPHeaderPHIRecipe *R : PhisToFix) {
8364     auto *PN = cast<PHINode>(R->getUnderlyingValue());
8365     VPRecipeBase *IncR =
8366         getRecipe(cast<Instruction>(PN->getIncomingValueForBlock(OrigLatch)));
8367     R->addOperand(IncR->getVPSingleValue());
8368   }
8369 }
8370 
8371 VPBasicBlock *VPRecipeBuilder::handleReplication(
8372     Instruction *I, VFRange &Range, VPBasicBlock *VPBB,
8373     VPlanPtr &Plan) {
8374   bool IsUniform = LoopVectorizationPlanner::getDecisionAndClampRange(
8375       [&](ElementCount VF) { return CM.isUniformAfterVectorization(I, VF); },
8376       Range);
8377 
8378   bool IsPredicated = LoopVectorizationPlanner::getDecisionAndClampRange(
8379       [&](ElementCount VF) { return CM.isPredicatedInst(I, VF, IsUniform); },
8380       Range);
8381 
8382   // Even if the instruction is not marked as uniform, there are certain
8383   // intrinsic calls that can be effectively treated as such, so we check for
8384   // them here. Conservatively, we only do this for scalable vectors, since
8385   // for fixed-width VFs we can always fall back on full scalarization.
8386   if (!IsUniform && Range.Start.isScalable() && isa<IntrinsicInst>(I)) {
8387     switch (cast<IntrinsicInst>(I)->getIntrinsicID()) {
8388     case Intrinsic::assume:
8389     case Intrinsic::lifetime_start:
8390     case Intrinsic::lifetime_end:
8391       // For scalable vectors if one of the operands is variant then we still
8392       // want to mark as uniform, which will generate one instruction for just
8393       // the first lane of the vector. We can't scalarize the call in the same
8394       // way as for fixed-width vectors because we don't know how many lanes
8395       // there are.
8396       //
8397       // The reasons for doing it this way for scalable vectors are:
8398       //   1. For the assume intrinsic generating the instruction for the first
8399       //      lane is still be better than not generating any at all. For
8400       //      example, the input may be a splat across all lanes.
8401       //   2. For the lifetime start/end intrinsics the pointer operand only
8402       //      does anything useful when the input comes from a stack object,
8403       //      which suggests it should always be uniform. For non-stack objects
8404       //      the effect is to poison the object, which still allows us to
8405       //      remove the call.
8406       IsUniform = true;
8407       break;
8408     default:
8409       break;
8410     }
8411   }
8412 
8413   auto *Recipe = new VPReplicateRecipe(I, Plan->mapToVPValues(I->operands()),
8414                                        IsUniform, IsPredicated);
8415   setRecipe(I, Recipe);
8416   Plan->addVPValue(I, Recipe);
8417 
8418   // Find if I uses a predicated instruction. If so, it will use its scalar
8419   // value. Avoid hoisting the insert-element which packs the scalar value into
8420   // a vector value, as that happens iff all users use the vector value.
8421   for (VPValue *Op : Recipe->operands()) {
8422     auto *PredR = dyn_cast_or_null<VPPredInstPHIRecipe>(Op->getDef());
8423     if (!PredR)
8424       continue;
8425     auto *RepR =
8426         cast_or_null<VPReplicateRecipe>(PredR->getOperand(0)->getDef());
8427     assert(RepR->isPredicated() &&
8428            "expected Replicate recipe to be predicated");
8429     RepR->setAlsoPack(false);
8430   }
8431 
8432   // Finalize the recipe for Instr, first if it is not predicated.
8433   if (!IsPredicated) {
8434     LLVM_DEBUG(dbgs() << "LV: Scalarizing:" << *I << "\n");
8435     VPBB->appendRecipe(Recipe);
8436     return VPBB;
8437   }
8438   LLVM_DEBUG(dbgs() << "LV: Scalarizing and predicating:" << *I << "\n");
8439 
8440   VPBlockBase *SingleSucc = VPBB->getSingleSuccessor();
8441   assert(SingleSucc && "VPBB must have a single successor when handling "
8442                        "predicated replication.");
8443   VPBlockUtils::disconnectBlocks(VPBB, SingleSucc);
8444   // Record predicated instructions for above packing optimizations.
8445   VPBlockBase *Region = createReplicateRegion(I, Recipe, Plan);
8446   VPBlockUtils::insertBlockAfter(Region, VPBB);
8447   auto *RegSucc = new VPBasicBlock();
8448   VPBlockUtils::insertBlockAfter(RegSucc, Region);
8449   VPBlockUtils::connectBlocks(RegSucc, SingleSucc);
8450   return RegSucc;
8451 }
8452 
8453 VPRegionBlock *VPRecipeBuilder::createReplicateRegion(
8454     Instruction *Instr, VPReplicateRecipe *PredRecipe, VPlanPtr &Plan) {
8455   // Instructions marked for predication are replicated and placed under an
8456   // if-then construct to prevent side-effects.
8457 
8458   // Generate recipes to compute the block mask for this region.
8459   VPValue *BlockInMask = createBlockInMask(Instr->getParent(), Plan);
8460 
8461   // Build the triangular if-then region.
8462   std::string RegionName = (Twine("pred.") + Instr->getOpcodeName()).str();
8463   assert(Instr->getParent() && "Predicated instruction not in any basic block");
8464   auto *BOMRecipe = new VPBranchOnMaskRecipe(BlockInMask);
8465   auto *Entry = new VPBasicBlock(Twine(RegionName) + ".entry", BOMRecipe);
8466   auto *PHIRecipe = Instr->getType()->isVoidTy()
8467                         ? nullptr
8468                         : new VPPredInstPHIRecipe(PredRecipe);
8469   if (PHIRecipe) {
8470     Plan->removeVPValueFor(Instr);
8471     Plan->addVPValue(Instr, PHIRecipe);
8472   }
8473   auto *Exiting = new VPBasicBlock(Twine(RegionName) + ".continue", PHIRecipe);
8474   auto *Pred = new VPBasicBlock(Twine(RegionName) + ".if", PredRecipe);
8475   VPRegionBlock *Region = new VPRegionBlock(Entry, Exiting, RegionName, true);
8476 
8477   // Note: first set Entry as region entry and then connect successors starting
8478   // from it in order, to propagate the "parent" of each VPBasicBlock.
8479   VPBlockUtils::insertTwoBlocksAfter(Pred, Exiting, Entry);
8480   VPBlockUtils::connectBlocks(Pred, Exiting);
8481 
8482   return Region;
8483 }
8484 
8485 VPRecipeOrVPValueTy
8486 VPRecipeBuilder::tryToCreateWidenRecipe(Instruction *Instr,
8487                                         ArrayRef<VPValue *> Operands,
8488                                         VFRange &Range, VPlanPtr &Plan) {
8489   // First, check for specific widening recipes that deal with inductions, Phi
8490   // nodes, calls and memory operations.
8491   VPRecipeBase *Recipe;
8492   if (auto Phi = dyn_cast<PHINode>(Instr)) {
8493     if (Phi->getParent() != OrigLoop->getHeader())
8494       return tryToBlend(Phi, Operands, Plan);
8495     if ((Recipe = tryToOptimizeInductionPHI(Phi, Operands, *Plan, Range)))
8496       return toVPRecipeResult(Recipe);
8497 
8498     VPHeaderPHIRecipe *PhiRecipe = nullptr;
8499     assert((Legal->isReductionVariable(Phi) ||
8500             Legal->isFirstOrderRecurrence(Phi)) &&
8501            "can only widen reductions and first-order recurrences here");
8502     VPValue *StartV = Operands[0];
8503     if (Legal->isReductionVariable(Phi)) {
8504       const RecurrenceDescriptor &RdxDesc =
8505           Legal->getReductionVars().find(Phi)->second;
8506       assert(RdxDesc.getRecurrenceStartValue() ==
8507              Phi->getIncomingValueForBlock(OrigLoop->getLoopPreheader()));
8508       PhiRecipe = new VPReductionPHIRecipe(Phi, RdxDesc, *StartV,
8509                                            CM.isInLoopReduction(Phi),
8510                                            CM.useOrderedReductions(RdxDesc));
8511     } else {
8512       PhiRecipe = new VPFirstOrderRecurrencePHIRecipe(Phi, *StartV);
8513     }
8514 
8515     // Record the incoming value from the backedge, so we can add the incoming
8516     // value from the backedge after all recipes have been created.
8517     recordRecipeOf(cast<Instruction>(
8518         Phi->getIncomingValueForBlock(OrigLoop->getLoopLatch())));
8519     PhisToFix.push_back(PhiRecipe);
8520     return toVPRecipeResult(PhiRecipe);
8521   }
8522 
8523   if (isa<TruncInst>(Instr) &&
8524       (Recipe = tryToOptimizeInductionTruncate(cast<TruncInst>(Instr), Operands,
8525                                                Range, *Plan)))
8526     return toVPRecipeResult(Recipe);
8527 
8528   // All widen recipes below deal only with VF > 1.
8529   if (LoopVectorizationPlanner::getDecisionAndClampRange(
8530           [&](ElementCount VF) { return VF.isScalar(); }, Range))
8531     return nullptr;
8532 
8533   if (auto *CI = dyn_cast<CallInst>(Instr))
8534     return toVPRecipeResult(tryToWidenCall(CI, Operands, Range));
8535 
8536   if (isa<LoadInst>(Instr) || isa<StoreInst>(Instr))
8537     return toVPRecipeResult(tryToWidenMemory(Instr, Operands, Range, Plan));
8538 
8539   if (!shouldWiden(Instr, Range))
8540     return nullptr;
8541 
8542   if (auto GEP = dyn_cast<GetElementPtrInst>(Instr))
8543     return toVPRecipeResult(new VPWidenGEPRecipe(
8544         GEP, make_range(Operands.begin(), Operands.end()), OrigLoop));
8545 
8546   if (auto *SI = dyn_cast<SelectInst>(Instr)) {
8547     bool InvariantCond =
8548         PSE.getSE()->isLoopInvariant(PSE.getSCEV(SI->getOperand(0)), OrigLoop);
8549     return toVPRecipeResult(new VPWidenSelectRecipe(
8550         *SI, make_range(Operands.begin(), Operands.end()), InvariantCond));
8551   }
8552 
8553   return toVPRecipeResult(tryToWiden(Instr, Operands));
8554 }
8555 
8556 void LoopVectorizationPlanner::buildVPlansWithVPRecipes(ElementCount MinVF,
8557                                                         ElementCount MaxVF) {
8558   assert(OrigLoop->isInnermost() && "Inner loop expected.");
8559 
8560   // Add assume instructions we need to drop to DeadInstructions, to prevent
8561   // them from being added to the VPlan.
8562   // TODO: We only need to drop assumes in blocks that get flattend. If the
8563   // control flow is preserved, we should keep them.
8564   SmallPtrSet<Instruction *, 4> DeadInstructions;
8565   auto &ConditionalAssumes = Legal->getConditionalAssumes();
8566   DeadInstructions.insert(ConditionalAssumes.begin(), ConditionalAssumes.end());
8567 
8568   MapVector<Instruction *, Instruction *> &SinkAfter = Legal->getSinkAfter();
8569   // Dead instructions do not need sinking. Remove them from SinkAfter.
8570   for (Instruction *I : DeadInstructions)
8571     SinkAfter.erase(I);
8572 
8573   // Cannot sink instructions after dead instructions (there won't be any
8574   // recipes for them). Instead, find the first non-dead previous instruction.
8575   for (auto &P : Legal->getSinkAfter()) {
8576     Instruction *SinkTarget = P.second;
8577     Instruction *FirstInst = &*SinkTarget->getParent()->begin();
8578     (void)FirstInst;
8579     while (DeadInstructions.contains(SinkTarget)) {
8580       assert(
8581           SinkTarget != FirstInst &&
8582           "Must find a live instruction (at least the one feeding the "
8583           "first-order recurrence PHI) before reaching beginning of the block");
8584       SinkTarget = SinkTarget->getPrevNode();
8585       assert(SinkTarget != P.first &&
8586              "sink source equals target, no sinking required");
8587     }
8588     P.second = SinkTarget;
8589   }
8590 
8591   auto MaxVFPlusOne = MaxVF.getWithIncrement(1);
8592   for (ElementCount VF = MinVF; ElementCount::isKnownLT(VF, MaxVFPlusOne);) {
8593     VFRange SubRange = {VF, MaxVFPlusOne};
8594     VPlans.push_back(
8595         buildVPlanWithVPRecipes(SubRange, DeadInstructions, SinkAfter));
8596     VF = SubRange.End;
8597   }
8598 }
8599 
8600 // Add the necessary canonical IV and branch recipes required to control the
8601 // loop.
8602 static void addCanonicalIVRecipes(VPlan &Plan, Type *IdxTy, DebugLoc DL,
8603                                   bool HasNUW,
8604                                   bool UseLaneMaskForLoopControlFlow) {
8605   Value *StartIdx = ConstantInt::get(IdxTy, 0);
8606   auto *StartV = Plan.getOrAddVPValue(StartIdx);
8607 
8608   // Add a VPCanonicalIVPHIRecipe starting at 0 to the header.
8609   auto *CanonicalIVPHI = new VPCanonicalIVPHIRecipe(StartV, DL);
8610   VPRegionBlock *TopRegion = Plan.getVectorLoopRegion();
8611   VPBasicBlock *Header = TopRegion->getEntryBasicBlock();
8612   Header->insert(CanonicalIVPHI, Header->begin());
8613 
8614   // Add a CanonicalIVIncrement{NUW} VPInstruction to increment the scalar
8615   // IV by VF * UF.
8616   auto *CanonicalIVIncrement =
8617       new VPInstruction(HasNUW ? VPInstruction::CanonicalIVIncrementNUW
8618                                : VPInstruction::CanonicalIVIncrement,
8619                         {CanonicalIVPHI}, DL, "index.next");
8620   CanonicalIVPHI->addOperand(CanonicalIVIncrement);
8621 
8622   VPBasicBlock *EB = TopRegion->getExitingBasicBlock();
8623   EB->appendRecipe(CanonicalIVIncrement);
8624 
8625   if (UseLaneMaskForLoopControlFlow) {
8626     // Create the active lane mask instruction in the vplan preheader.
8627     VPBasicBlock *Preheader = Plan.getEntry()->getEntryBasicBlock();
8628 
8629     // We can't use StartV directly in the ActiveLaneMask VPInstruction, since
8630     // we have to take unrolling into account. Each part needs to start at
8631     //   Part * VF
8632     auto *CanonicalIVIncrementParts =
8633         new VPInstruction(HasNUW ? VPInstruction::CanonicalIVIncrementForPartNUW
8634                                  : VPInstruction::CanonicalIVIncrementForPart,
8635                           {StartV}, DL, "index.part.next");
8636     Preheader->appendRecipe(CanonicalIVIncrementParts);
8637 
8638     // Create the ActiveLaneMask instruction using the correct start values.
8639     VPValue *TC = Plan.getOrCreateTripCount();
8640     auto *EntryALM = new VPInstruction(VPInstruction::ActiveLaneMask,
8641                                        {CanonicalIVIncrementParts, TC}, DL,
8642                                        "active.lane.mask.entry");
8643     Preheader->appendRecipe(EntryALM);
8644 
8645     // Now create the ActiveLaneMaskPhi recipe in the main loop using the
8646     // preheader ActiveLaneMask instruction.
8647     auto *LaneMaskPhi = new VPActiveLaneMaskPHIRecipe(EntryALM, DebugLoc());
8648     Header->insert(LaneMaskPhi, Header->getFirstNonPhi());
8649 
8650     // Create the active lane mask for the next iteration of the loop.
8651     CanonicalIVIncrementParts =
8652         new VPInstruction(HasNUW ? VPInstruction::CanonicalIVIncrementForPartNUW
8653                                  : VPInstruction::CanonicalIVIncrementForPart,
8654                           {CanonicalIVIncrement}, DL);
8655     EB->appendRecipe(CanonicalIVIncrementParts);
8656 
8657     auto *ALM = new VPInstruction(VPInstruction::ActiveLaneMask,
8658                                   {CanonicalIVIncrementParts, TC}, DL,
8659                                   "active.lane.mask.next");
8660     EB->appendRecipe(ALM);
8661     LaneMaskPhi->addOperand(ALM);
8662 
8663     // We have to invert the mask here because a true condition means jumping
8664     // to the exit block.
8665     auto *NotMask = new VPInstruction(VPInstruction::Not, ALM, DL);
8666     EB->appendRecipe(NotMask);
8667 
8668     VPInstruction *BranchBack =
8669         new VPInstruction(VPInstruction::BranchOnCond, {NotMask}, DL);
8670     EB->appendRecipe(BranchBack);
8671   } else {
8672     // Add the BranchOnCount VPInstruction to the latch.
8673     VPInstruction *BranchBack = new VPInstruction(
8674         VPInstruction::BranchOnCount,
8675         {CanonicalIVIncrement, &Plan.getVectorTripCount()}, DL);
8676     EB->appendRecipe(BranchBack);
8677   }
8678 }
8679 
8680 // Add exit values to \p Plan. VPLiveOuts are added for each LCSSA phi in the
8681 // original exit block.
8682 static void addUsersInExitBlock(VPBasicBlock *HeaderVPBB,
8683                                 VPBasicBlock *MiddleVPBB, Loop *OrigLoop,
8684                                 VPlan &Plan) {
8685   BasicBlock *ExitBB = OrigLoop->getUniqueExitBlock();
8686   BasicBlock *ExitingBB = OrigLoop->getExitingBlock();
8687   // Only handle single-exit loops with unique exit blocks for now.
8688   if (!ExitBB || !ExitBB->getSinglePredecessor() || !ExitingBB)
8689     return;
8690 
8691   // Introduce VPUsers modeling the exit values.
8692   for (PHINode &ExitPhi : ExitBB->phis()) {
8693     Value *IncomingValue =
8694         ExitPhi.getIncomingValueForBlock(ExitingBB);
8695     VPValue *V = Plan.getOrAddVPValue(IncomingValue, true);
8696     Plan.addLiveOut(&ExitPhi, V);
8697   }
8698 }
8699 
8700 VPlanPtr LoopVectorizationPlanner::buildVPlanWithVPRecipes(
8701     VFRange &Range, SmallPtrSetImpl<Instruction *> &DeadInstructions,
8702     const MapVector<Instruction *, Instruction *> &SinkAfter) {
8703 
8704   SmallPtrSet<const InterleaveGroup<Instruction> *, 1> InterleaveGroups;
8705 
8706   VPRecipeBuilder RecipeBuilder(OrigLoop, TLI, Legal, CM, PSE, Builder);
8707 
8708   // ---------------------------------------------------------------------------
8709   // Pre-construction: record ingredients whose recipes we'll need to further
8710   // process after constructing the initial VPlan.
8711   // ---------------------------------------------------------------------------
8712 
8713   // Mark instructions we'll need to sink later and their targets as
8714   // ingredients whose recipe we'll need to record.
8715   for (auto &Entry : SinkAfter) {
8716     RecipeBuilder.recordRecipeOf(Entry.first);
8717     RecipeBuilder.recordRecipeOf(Entry.second);
8718   }
8719   for (auto &Reduction : CM.getInLoopReductionChains()) {
8720     PHINode *Phi = Reduction.first;
8721     RecurKind Kind =
8722         Legal->getReductionVars().find(Phi)->second.getRecurrenceKind();
8723     const SmallVector<Instruction *, 4> &ReductionOperations = Reduction.second;
8724 
8725     RecipeBuilder.recordRecipeOf(Phi);
8726     for (auto &R : ReductionOperations) {
8727       RecipeBuilder.recordRecipeOf(R);
8728       // For min/max reductions, where we have a pair of icmp/select, we also
8729       // need to record the ICmp recipe, so it can be removed later.
8730       assert(!RecurrenceDescriptor::isSelectCmpRecurrenceKind(Kind) &&
8731              "Only min/max recurrences allowed for inloop reductions");
8732       if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind))
8733         RecipeBuilder.recordRecipeOf(cast<Instruction>(R->getOperand(0)));
8734     }
8735   }
8736 
8737   // For each interleave group which is relevant for this (possibly trimmed)
8738   // Range, add it to the set of groups to be later applied to the VPlan and add
8739   // placeholders for its members' Recipes which we'll be replacing with a
8740   // single VPInterleaveRecipe.
8741   for (InterleaveGroup<Instruction> *IG : IAI.getInterleaveGroups()) {
8742     auto applyIG = [IG, this](ElementCount VF) -> bool {
8743       return (VF.isVector() && // Query is illegal for VF == 1
8744               CM.getWideningDecision(IG->getInsertPos(), VF) ==
8745                   LoopVectorizationCostModel::CM_Interleave);
8746     };
8747     if (!getDecisionAndClampRange(applyIG, Range))
8748       continue;
8749     InterleaveGroups.insert(IG);
8750     for (unsigned i = 0; i < IG->getFactor(); i++)
8751       if (Instruction *Member = IG->getMember(i))
8752         RecipeBuilder.recordRecipeOf(Member);
8753   };
8754 
8755   // ---------------------------------------------------------------------------
8756   // Build initial VPlan: Scan the body of the loop in a topological order to
8757   // visit each basic block after having visited its predecessor basic blocks.
8758   // ---------------------------------------------------------------------------
8759 
8760   // Create initial VPlan skeleton, starting with a block for the pre-header,
8761   // followed by a region for the vector loop, followed by the middle block. The
8762   // skeleton vector loop region contains a header and latch block.
8763   VPBasicBlock *Preheader = new VPBasicBlock("vector.ph");
8764   auto Plan = std::make_unique<VPlan>(Preheader);
8765 
8766   VPBasicBlock *HeaderVPBB = new VPBasicBlock("vector.body");
8767   VPBasicBlock *LatchVPBB = new VPBasicBlock("vector.latch");
8768   VPBlockUtils::insertBlockAfter(LatchVPBB, HeaderVPBB);
8769   auto *TopRegion = new VPRegionBlock(HeaderVPBB, LatchVPBB, "vector loop");
8770   VPBlockUtils::insertBlockAfter(TopRegion, Preheader);
8771   VPBasicBlock *MiddleVPBB = new VPBasicBlock("middle.block");
8772   VPBlockUtils::insertBlockAfter(MiddleVPBB, TopRegion);
8773 
8774   Instruction *DLInst =
8775       getDebugLocFromInstOrOperands(Legal->getPrimaryInduction());
8776   addCanonicalIVRecipes(*Plan, Legal->getWidestInductionType(),
8777                         DLInst ? DLInst->getDebugLoc() : DebugLoc(),
8778                         !CM.foldTailByMasking(),
8779                         CM.useActiveLaneMaskForControlFlow());
8780 
8781   // Scan the body of the loop in a topological order to visit each basic block
8782   // after having visited its predecessor basic blocks.
8783   LoopBlocksDFS DFS(OrigLoop);
8784   DFS.perform(LI);
8785 
8786   VPBasicBlock *VPBB = HeaderVPBB;
8787   SmallVector<VPWidenIntOrFpInductionRecipe *> InductionsToMove;
8788   for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) {
8789     // Relevant instructions from basic block BB will be grouped into VPRecipe
8790     // ingredients and fill a new VPBasicBlock.
8791     unsigned VPBBsForBB = 0;
8792     if (VPBB != HeaderVPBB)
8793       VPBB->setName(BB->getName());
8794     Builder.setInsertPoint(VPBB);
8795 
8796     // Introduce each ingredient into VPlan.
8797     // TODO: Model and preserve debug intrinsics in VPlan.
8798     for (Instruction &I : BB->instructionsWithoutDebug()) {
8799       Instruction *Instr = &I;
8800 
8801       // First filter out irrelevant instructions, to ensure no recipes are
8802       // built for them.
8803       if (isa<BranchInst>(Instr) || DeadInstructions.count(Instr))
8804         continue;
8805 
8806       SmallVector<VPValue *, 4> Operands;
8807       auto *Phi = dyn_cast<PHINode>(Instr);
8808       if (Phi && Phi->getParent() == OrigLoop->getHeader()) {
8809         Operands.push_back(Plan->getOrAddVPValue(
8810             Phi->getIncomingValueForBlock(OrigLoop->getLoopPreheader())));
8811       } else {
8812         auto OpRange = Plan->mapToVPValues(Instr->operands());
8813         Operands = {OpRange.begin(), OpRange.end()};
8814       }
8815 
8816       // Invariant stores inside loop will be deleted and a single store
8817       // with the final reduction value will be added to the exit block
8818       StoreInst *SI;
8819       if ((SI = dyn_cast<StoreInst>(&I)) &&
8820           Legal->isInvariantAddressOfReduction(SI->getPointerOperand()))
8821         continue;
8822 
8823       if (auto RecipeOrValue = RecipeBuilder.tryToCreateWidenRecipe(
8824               Instr, Operands, Range, Plan)) {
8825         // If Instr can be simplified to an existing VPValue, use it.
8826         if (RecipeOrValue.is<VPValue *>()) {
8827           auto *VPV = RecipeOrValue.get<VPValue *>();
8828           Plan->addVPValue(Instr, VPV);
8829           // If the re-used value is a recipe, register the recipe for the
8830           // instruction, in case the recipe for Instr needs to be recorded.
8831           if (auto *R = dyn_cast_or_null<VPRecipeBase>(VPV->getDef()))
8832             RecipeBuilder.setRecipe(Instr, R);
8833           continue;
8834         }
8835         // Otherwise, add the new recipe.
8836         VPRecipeBase *Recipe = RecipeOrValue.get<VPRecipeBase *>();
8837         for (auto *Def : Recipe->definedValues()) {
8838           auto *UV = Def->getUnderlyingValue();
8839           Plan->addVPValue(UV, Def);
8840         }
8841 
8842         if (isa<VPWidenIntOrFpInductionRecipe>(Recipe) &&
8843             HeaderVPBB->getFirstNonPhi() != VPBB->end()) {
8844           // Keep track of VPWidenIntOrFpInductionRecipes not in the phi section
8845           // of the header block. That can happen for truncates of induction
8846           // variables. Those recipes are moved to the phi section of the header
8847           // block after applying SinkAfter, which relies on the original
8848           // position of the trunc.
8849           assert(isa<TruncInst>(Instr));
8850           InductionsToMove.push_back(
8851               cast<VPWidenIntOrFpInductionRecipe>(Recipe));
8852         }
8853         RecipeBuilder.setRecipe(Instr, Recipe);
8854         VPBB->appendRecipe(Recipe);
8855         continue;
8856       }
8857 
8858       // Otherwise, if all widening options failed, Instruction is to be
8859       // replicated. This may create a successor for VPBB.
8860       VPBasicBlock *NextVPBB =
8861           RecipeBuilder.handleReplication(Instr, Range, VPBB, Plan);
8862       if (NextVPBB != VPBB) {
8863         VPBB = NextVPBB;
8864         VPBB->setName(BB->hasName() ? BB->getName() + "." + Twine(VPBBsForBB++)
8865                                     : "");
8866       }
8867     }
8868 
8869     VPBlockUtils::insertBlockAfter(new VPBasicBlock(), VPBB);
8870     VPBB = cast<VPBasicBlock>(VPBB->getSingleSuccessor());
8871   }
8872 
8873   HeaderVPBB->setName("vector.body");
8874 
8875   // Fold the last, empty block into its predecessor.
8876   VPBB = VPBlockUtils::tryToMergeBlockIntoPredecessor(VPBB);
8877   assert(VPBB && "expected to fold last (empty) block");
8878   // After here, VPBB should not be used.
8879   VPBB = nullptr;
8880 
8881   addUsersInExitBlock(HeaderVPBB, MiddleVPBB, OrigLoop, *Plan);
8882 
8883   assert(isa<VPRegionBlock>(Plan->getVectorLoopRegion()) &&
8884          !Plan->getVectorLoopRegion()->getEntryBasicBlock()->empty() &&
8885          "entry block must be set to a VPRegionBlock having a non-empty entry "
8886          "VPBasicBlock");
8887   RecipeBuilder.fixHeaderPhis();
8888 
8889   // ---------------------------------------------------------------------------
8890   // Transform initial VPlan: Apply previously taken decisions, in order, to
8891   // bring the VPlan to its final state.
8892   // ---------------------------------------------------------------------------
8893 
8894   // Apply Sink-After legal constraints.
8895   auto GetReplicateRegion = [](VPRecipeBase *R) -> VPRegionBlock * {
8896     auto *Region = dyn_cast_or_null<VPRegionBlock>(R->getParent()->getParent());
8897     if (Region && Region->isReplicator()) {
8898       assert(Region->getNumSuccessors() == 1 &&
8899              Region->getNumPredecessors() == 1 && "Expected SESE region!");
8900       assert(R->getParent()->size() == 1 &&
8901              "A recipe in an original replicator region must be the only "
8902              "recipe in its block");
8903       return Region;
8904     }
8905     return nullptr;
8906   };
8907   for (auto &Entry : SinkAfter) {
8908     VPRecipeBase *Sink = RecipeBuilder.getRecipe(Entry.first);
8909     VPRecipeBase *Target = RecipeBuilder.getRecipe(Entry.second);
8910 
8911     auto *TargetRegion = GetReplicateRegion(Target);
8912     auto *SinkRegion = GetReplicateRegion(Sink);
8913     if (!SinkRegion) {
8914       // If the sink source is not a replicate region, sink the recipe directly.
8915       if (TargetRegion) {
8916         // The target is in a replication region, make sure to move Sink to
8917         // the block after it, not into the replication region itself.
8918         VPBasicBlock *NextBlock =
8919             cast<VPBasicBlock>(TargetRegion->getSuccessors().front());
8920         Sink->moveBefore(*NextBlock, NextBlock->getFirstNonPhi());
8921       } else
8922         Sink->moveAfter(Target);
8923       continue;
8924     }
8925 
8926     // The sink source is in a replicate region. Unhook the region from the CFG.
8927     auto *SinkPred = SinkRegion->getSinglePredecessor();
8928     auto *SinkSucc = SinkRegion->getSingleSuccessor();
8929     VPBlockUtils::disconnectBlocks(SinkPred, SinkRegion);
8930     VPBlockUtils::disconnectBlocks(SinkRegion, SinkSucc);
8931     VPBlockUtils::connectBlocks(SinkPred, SinkSucc);
8932 
8933     if (TargetRegion) {
8934       // The target recipe is also in a replicate region, move the sink region
8935       // after the target region.
8936       auto *TargetSucc = TargetRegion->getSingleSuccessor();
8937       VPBlockUtils::disconnectBlocks(TargetRegion, TargetSucc);
8938       VPBlockUtils::connectBlocks(TargetRegion, SinkRegion);
8939       VPBlockUtils::connectBlocks(SinkRegion, TargetSucc);
8940     } else {
8941       // The sink source is in a replicate region, we need to move the whole
8942       // replicate region, which should only contain a single recipe in the
8943       // main block.
8944       auto *SplitBlock =
8945           Target->getParent()->splitAt(std::next(Target->getIterator()));
8946 
8947       auto *SplitPred = SplitBlock->getSinglePredecessor();
8948 
8949       VPBlockUtils::disconnectBlocks(SplitPred, SplitBlock);
8950       VPBlockUtils::connectBlocks(SplitPred, SinkRegion);
8951       VPBlockUtils::connectBlocks(SinkRegion, SplitBlock);
8952     }
8953   }
8954 
8955   VPlanTransforms::removeRedundantCanonicalIVs(*Plan);
8956   VPlanTransforms::removeRedundantInductionCasts(*Plan);
8957 
8958   // Now that sink-after is done, move induction recipes for optimized truncates
8959   // to the phi section of the header block.
8960   for (VPWidenIntOrFpInductionRecipe *Ind : InductionsToMove)
8961     Ind->moveBefore(*HeaderVPBB, HeaderVPBB->getFirstNonPhi());
8962 
8963   // Adjust the recipes for any inloop reductions.
8964   adjustRecipesForReductions(cast<VPBasicBlock>(TopRegion->getExiting()), Plan,
8965                              RecipeBuilder, Range.Start);
8966 
8967   // Introduce a recipe to combine the incoming and previous values of a
8968   // first-order recurrence.
8969   for (VPRecipeBase &R :
8970        Plan->getVectorLoopRegion()->getEntryBasicBlock()->phis()) {
8971     auto *RecurPhi = dyn_cast<VPFirstOrderRecurrencePHIRecipe>(&R);
8972     if (!RecurPhi)
8973       continue;
8974 
8975     VPRecipeBase *PrevRecipe = RecurPhi->getBackedgeRecipe();
8976     VPBasicBlock *InsertBlock = PrevRecipe->getParent();
8977     auto *Region = GetReplicateRegion(PrevRecipe);
8978     if (Region)
8979       InsertBlock = dyn_cast<VPBasicBlock>(Region->getSingleSuccessor());
8980     if (!InsertBlock) {
8981       InsertBlock = new VPBasicBlock(Region->getName() + ".succ");
8982       VPBlockUtils::insertBlockAfter(InsertBlock, Region);
8983     }
8984     if (Region || PrevRecipe->isPhi())
8985       Builder.setInsertPoint(InsertBlock, InsertBlock->getFirstNonPhi());
8986     else
8987       Builder.setInsertPoint(InsertBlock, std::next(PrevRecipe->getIterator()));
8988 
8989     auto *RecurSplice = cast<VPInstruction>(
8990         Builder.createNaryOp(VPInstruction::FirstOrderRecurrenceSplice,
8991                              {RecurPhi, RecurPhi->getBackedgeValue()}));
8992 
8993     RecurPhi->replaceAllUsesWith(RecurSplice);
8994     // Set the first operand of RecurSplice to RecurPhi again, after replacing
8995     // all users.
8996     RecurSplice->setOperand(0, RecurPhi);
8997   }
8998 
8999   // Interleave memory: for each Interleave Group we marked earlier as relevant
9000   // for this VPlan, replace the Recipes widening its memory instructions with a
9001   // single VPInterleaveRecipe at its insertion point.
9002   for (auto IG : InterleaveGroups) {
9003     auto *Recipe = cast<VPWidenMemoryInstructionRecipe>(
9004         RecipeBuilder.getRecipe(IG->getInsertPos()));
9005     SmallVector<VPValue *, 4> StoredValues;
9006     for (unsigned i = 0; i < IG->getFactor(); ++i)
9007       if (auto *SI = dyn_cast_or_null<StoreInst>(IG->getMember(i))) {
9008         auto *StoreR =
9009             cast<VPWidenMemoryInstructionRecipe>(RecipeBuilder.getRecipe(SI));
9010         StoredValues.push_back(StoreR->getStoredValue());
9011       }
9012 
9013     auto *VPIG = new VPInterleaveRecipe(IG, Recipe->getAddr(), StoredValues,
9014                                         Recipe->getMask());
9015     VPIG->insertBefore(Recipe);
9016     unsigned J = 0;
9017     for (unsigned i = 0; i < IG->getFactor(); ++i)
9018       if (Instruction *Member = IG->getMember(i)) {
9019         if (!Member->getType()->isVoidTy()) {
9020           VPValue *OriginalV = Plan->getVPValue(Member);
9021           Plan->removeVPValueFor(Member);
9022           Plan->addVPValue(Member, VPIG->getVPValue(J));
9023           OriginalV->replaceAllUsesWith(VPIG->getVPValue(J));
9024           J++;
9025         }
9026         RecipeBuilder.getRecipe(Member)->eraseFromParent();
9027       }
9028   }
9029 
9030   std::string PlanName;
9031   raw_string_ostream RSO(PlanName);
9032   ElementCount VF = Range.Start;
9033   Plan->addVF(VF);
9034   RSO << "Initial VPlan for VF={" << VF;
9035   for (VF *= 2; ElementCount::isKnownLT(VF, Range.End); VF *= 2) {
9036     Plan->addVF(VF);
9037     RSO << "," << VF;
9038   }
9039   RSO << "},UF>=1";
9040   RSO.flush();
9041   Plan->setName(PlanName);
9042 
9043   // From this point onwards, VPlan-to-VPlan transformations may change the plan
9044   // in ways that accessing values using original IR values is incorrect.
9045   Plan->disableValue2VPValue();
9046 
9047   VPlanTransforms::optimizeInductions(*Plan, *PSE.getSE());
9048   VPlanTransforms::sinkScalarOperands(*Plan);
9049   VPlanTransforms::removeDeadRecipes(*Plan);
9050   VPlanTransforms::mergeReplicateRegions(*Plan);
9051   VPlanTransforms::removeRedundantExpandSCEVRecipes(*Plan);
9052 
9053   // Fold Exit block into its predecessor if possible.
9054   // TODO: Fold block earlier once all VPlan transforms properly maintain a
9055   // VPBasicBlock as exit.
9056   VPBlockUtils::tryToMergeBlockIntoPredecessor(TopRegion->getExiting());
9057 
9058   assert(VPlanVerifier::verifyPlanIsValid(*Plan) && "VPlan is invalid");
9059   return Plan;
9060 }
9061 
9062 VPlanPtr LoopVectorizationPlanner::buildVPlan(VFRange &Range) {
9063   // Outer loop handling: They may require CFG and instruction level
9064   // transformations before even evaluating whether vectorization is profitable.
9065   // Since we cannot modify the incoming IR, we need to build VPlan upfront in
9066   // the vectorization pipeline.
9067   assert(!OrigLoop->isInnermost());
9068   assert(EnableVPlanNativePath && "VPlan-native path is not enabled.");
9069 
9070   // Create new empty VPlan
9071   auto Plan = std::make_unique<VPlan>();
9072 
9073   // Build hierarchical CFG
9074   VPlanHCFGBuilder HCFGBuilder(OrigLoop, LI, *Plan);
9075   HCFGBuilder.buildHierarchicalCFG();
9076 
9077   for (ElementCount VF = Range.Start; ElementCount::isKnownLT(VF, Range.End);
9078        VF *= 2)
9079     Plan->addVF(VF);
9080 
9081   SmallPtrSet<Instruction *, 1> DeadInstructions;
9082   VPlanTransforms::VPInstructionsToVPRecipes(
9083       OrigLoop, Plan,
9084       [this](PHINode *P) { return Legal->getIntOrFpInductionDescriptor(P); },
9085       DeadInstructions, *PSE.getSE());
9086 
9087   // Remove the existing terminator of the exiting block of the top-most region.
9088   // A BranchOnCount will be added instead when adding the canonical IV recipes.
9089   auto *Term =
9090       Plan->getVectorLoopRegion()->getExitingBasicBlock()->getTerminator();
9091   Term->eraseFromParent();
9092 
9093   addCanonicalIVRecipes(*Plan, Legal->getWidestInductionType(), DebugLoc(),
9094                         true, CM.useActiveLaneMaskForControlFlow());
9095   return Plan;
9096 }
9097 
9098 // Adjust the recipes for reductions. For in-loop reductions the chain of
9099 // instructions leading from the loop exit instr to the phi need to be converted
9100 // to reductions, with one operand being vector and the other being the scalar
9101 // reduction chain. For other reductions, a select is introduced between the phi
9102 // and live-out recipes when folding the tail.
9103 void LoopVectorizationPlanner::adjustRecipesForReductions(
9104     VPBasicBlock *LatchVPBB, VPlanPtr &Plan, VPRecipeBuilder &RecipeBuilder,
9105     ElementCount MinVF) {
9106   for (auto &Reduction : CM.getInLoopReductionChains()) {
9107     PHINode *Phi = Reduction.first;
9108     const RecurrenceDescriptor &RdxDesc =
9109         Legal->getReductionVars().find(Phi)->second;
9110     const SmallVector<Instruction *, 4> &ReductionOperations = Reduction.second;
9111 
9112     if (MinVF.isScalar() && !CM.useOrderedReductions(RdxDesc))
9113       continue;
9114 
9115     // ReductionOperations are orders top-down from the phi's use to the
9116     // LoopExitValue. We keep a track of the previous item (the Chain) to tell
9117     // which of the two operands will remain scalar and which will be reduced.
9118     // For minmax the chain will be the select instructions.
9119     Instruction *Chain = Phi;
9120     for (Instruction *R : ReductionOperations) {
9121       VPRecipeBase *WidenRecipe = RecipeBuilder.getRecipe(R);
9122       RecurKind Kind = RdxDesc.getRecurrenceKind();
9123 
9124       VPValue *ChainOp = Plan->getVPValue(Chain);
9125       unsigned FirstOpId;
9126       assert(!RecurrenceDescriptor::isSelectCmpRecurrenceKind(Kind) &&
9127              "Only min/max recurrences allowed for inloop reductions");
9128       // Recognize a call to the llvm.fmuladd intrinsic.
9129       bool IsFMulAdd = (Kind == RecurKind::FMulAdd);
9130       assert((!IsFMulAdd || RecurrenceDescriptor::isFMulAddIntrinsic(R)) &&
9131              "Expected instruction to be a call to the llvm.fmuladd intrinsic");
9132       if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind)) {
9133         assert(isa<VPWidenSelectRecipe>(WidenRecipe) &&
9134                "Expected to replace a VPWidenSelectSC");
9135         FirstOpId = 1;
9136       } else {
9137         assert((MinVF.isScalar() || isa<VPWidenRecipe>(WidenRecipe) ||
9138                 (IsFMulAdd && isa<VPWidenCallRecipe>(WidenRecipe))) &&
9139                "Expected to replace a VPWidenSC");
9140         FirstOpId = 0;
9141       }
9142       unsigned VecOpId =
9143           R->getOperand(FirstOpId) == Chain ? FirstOpId + 1 : FirstOpId;
9144       VPValue *VecOp = Plan->getVPValue(R->getOperand(VecOpId));
9145 
9146       auto *CondOp = CM.blockNeedsPredicationForAnyReason(R->getParent())
9147                          ? RecipeBuilder.createBlockInMask(R->getParent(), Plan)
9148                          : nullptr;
9149 
9150       if (IsFMulAdd) {
9151         // If the instruction is a call to the llvm.fmuladd intrinsic then we
9152         // need to create an fmul recipe to use as the vector operand for the
9153         // fadd reduction.
9154         VPInstruction *FMulRecipe = new VPInstruction(
9155             Instruction::FMul, {VecOp, Plan->getVPValue(R->getOperand(1))});
9156         FMulRecipe->setFastMathFlags(R->getFastMathFlags());
9157         WidenRecipe->getParent()->insert(FMulRecipe,
9158                                          WidenRecipe->getIterator());
9159         VecOp = FMulRecipe;
9160       }
9161       VPReductionRecipe *RedRecipe =
9162           new VPReductionRecipe(&RdxDesc, R, ChainOp, VecOp, CondOp, TTI);
9163       WidenRecipe->getVPSingleValue()->replaceAllUsesWith(RedRecipe);
9164       Plan->removeVPValueFor(R);
9165       Plan->addVPValue(R, RedRecipe);
9166       // Append the recipe to the end of the VPBasicBlock because we need to
9167       // ensure that it comes after all of it's inputs, including CondOp.
9168       WidenRecipe->getParent()->appendRecipe(RedRecipe);
9169       WidenRecipe->getVPSingleValue()->replaceAllUsesWith(RedRecipe);
9170       WidenRecipe->eraseFromParent();
9171 
9172       if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind)) {
9173         VPRecipeBase *CompareRecipe =
9174             RecipeBuilder.getRecipe(cast<Instruction>(R->getOperand(0)));
9175         assert(isa<VPWidenRecipe>(CompareRecipe) &&
9176                "Expected to replace a VPWidenSC");
9177         assert(cast<VPWidenRecipe>(CompareRecipe)->getNumUsers() == 0 &&
9178                "Expected no remaining users");
9179         CompareRecipe->eraseFromParent();
9180       }
9181       Chain = R;
9182     }
9183   }
9184 
9185   // If tail is folded by masking, introduce selects between the phi
9186   // and the live-out instruction of each reduction, at the beginning of the
9187   // dedicated latch block.
9188   if (CM.foldTailByMasking()) {
9189     Builder.setInsertPoint(LatchVPBB, LatchVPBB->begin());
9190     for (VPRecipeBase &R :
9191          Plan->getVectorLoopRegion()->getEntryBasicBlock()->phis()) {
9192       VPReductionPHIRecipe *PhiR = dyn_cast<VPReductionPHIRecipe>(&R);
9193       if (!PhiR || PhiR->isInLoop())
9194         continue;
9195       VPValue *Cond =
9196           RecipeBuilder.createBlockInMask(OrigLoop->getHeader(), Plan);
9197       VPValue *Red = PhiR->getBackedgeValue();
9198       assert(cast<VPRecipeBase>(Red->getDef())->getParent() != LatchVPBB &&
9199              "reduction recipe must be defined before latch");
9200       Builder.createNaryOp(Instruction::Select, {Cond, Red, PhiR});
9201     }
9202   }
9203 }
9204 
9205 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
9206 void VPInterleaveRecipe::print(raw_ostream &O, const Twine &Indent,
9207                                VPSlotTracker &SlotTracker) const {
9208   O << Indent << "INTERLEAVE-GROUP with factor " << IG->getFactor() << " at ";
9209   IG->getInsertPos()->printAsOperand(O, false);
9210   O << ", ";
9211   getAddr()->printAsOperand(O, SlotTracker);
9212   VPValue *Mask = getMask();
9213   if (Mask) {
9214     O << ", ";
9215     Mask->printAsOperand(O, SlotTracker);
9216   }
9217 
9218   unsigned OpIdx = 0;
9219   for (unsigned i = 0; i < IG->getFactor(); ++i) {
9220     if (!IG->getMember(i))
9221       continue;
9222     if (getNumStoreOperands() > 0) {
9223       O << "\n" << Indent << "  store ";
9224       getOperand(1 + OpIdx)->printAsOperand(O, SlotTracker);
9225       O << " to index " << i;
9226     } else {
9227       O << "\n" << Indent << "  ";
9228       getVPValue(OpIdx)->printAsOperand(O, SlotTracker);
9229       O << " = load from index " << i;
9230     }
9231     ++OpIdx;
9232   }
9233 }
9234 #endif
9235 
9236 void VPWidenCallRecipe::execute(VPTransformState &State) {
9237   State.ILV->widenCallInstruction(*cast<CallInst>(getUnderlyingInstr()), this,
9238                                   *this, State);
9239 }
9240 
9241 void VPWidenIntOrFpInductionRecipe::execute(VPTransformState &State) {
9242   assert(!State.Instance && "Int or FP induction being replicated.");
9243 
9244   Value *Start = getStartValue()->getLiveInIRValue();
9245   const InductionDescriptor &ID = getInductionDescriptor();
9246   TruncInst *Trunc = getTruncInst();
9247   IRBuilderBase &Builder = State.Builder;
9248   assert(IV->getType() == ID.getStartValue()->getType() && "Types must match");
9249   assert(State.VF.isVector() && "must have vector VF");
9250 
9251   // The value from the original loop to which we are mapping the new induction
9252   // variable.
9253   Instruction *EntryVal = Trunc ? cast<Instruction>(Trunc) : IV;
9254 
9255   // Fast-math-flags propagate from the original induction instruction.
9256   IRBuilder<>::FastMathFlagGuard FMFG(Builder);
9257   if (ID.getInductionBinOp() && isa<FPMathOperator>(ID.getInductionBinOp()))
9258     Builder.setFastMathFlags(ID.getInductionBinOp()->getFastMathFlags());
9259 
9260   // Now do the actual transformations, and start with fetching the step value.
9261   Value *Step = State.get(getStepValue(), VPIteration(0, 0));
9262 
9263   assert((isa<PHINode>(EntryVal) || isa<TruncInst>(EntryVal)) &&
9264          "Expected either an induction phi-node or a truncate of it!");
9265 
9266   // Construct the initial value of the vector IV in the vector loop preheader
9267   auto CurrIP = Builder.saveIP();
9268   BasicBlock *VectorPH = State.CFG.getPreheaderBBFor(this);
9269   Builder.SetInsertPoint(VectorPH->getTerminator());
9270   if (isa<TruncInst>(EntryVal)) {
9271     assert(Start->getType()->isIntegerTy() &&
9272            "Truncation requires an integer type");
9273     auto *TruncType = cast<IntegerType>(EntryVal->getType());
9274     Step = Builder.CreateTrunc(Step, TruncType);
9275     Start = Builder.CreateCast(Instruction::Trunc, Start, TruncType);
9276   }
9277 
9278   Value *Zero = getSignedIntOrFpConstant(Start->getType(), 0);
9279   Value *SplatStart = Builder.CreateVectorSplat(State.VF, Start);
9280   Value *SteppedStart = getStepVector(
9281       SplatStart, Zero, Step, ID.getInductionOpcode(), State.VF, State.Builder);
9282 
9283   // We create vector phi nodes for both integer and floating-point induction
9284   // variables. Here, we determine the kind of arithmetic we will perform.
9285   Instruction::BinaryOps AddOp;
9286   Instruction::BinaryOps MulOp;
9287   if (Step->getType()->isIntegerTy()) {
9288     AddOp = Instruction::Add;
9289     MulOp = Instruction::Mul;
9290   } else {
9291     AddOp = ID.getInductionOpcode();
9292     MulOp = Instruction::FMul;
9293   }
9294 
9295   // Multiply the vectorization factor by the step using integer or
9296   // floating-point arithmetic as appropriate.
9297   Type *StepType = Step->getType();
9298   Value *RuntimeVF;
9299   if (Step->getType()->isFloatingPointTy())
9300     RuntimeVF = getRuntimeVFAsFloat(Builder, StepType, State.VF);
9301   else
9302     RuntimeVF = getRuntimeVF(Builder, StepType, State.VF);
9303   Value *Mul = Builder.CreateBinOp(MulOp, Step, RuntimeVF);
9304 
9305   // Create a vector splat to use in the induction update.
9306   //
9307   // FIXME: If the step is non-constant, we create the vector splat with
9308   //        IRBuilder. IRBuilder can constant-fold the multiply, but it doesn't
9309   //        handle a constant vector splat.
9310   Value *SplatVF = isa<Constant>(Mul)
9311                        ? ConstantVector::getSplat(State.VF, cast<Constant>(Mul))
9312                        : Builder.CreateVectorSplat(State.VF, Mul);
9313   Builder.restoreIP(CurrIP);
9314 
9315   // We may need to add the step a number of times, depending on the unroll
9316   // factor. The last of those goes into the PHI.
9317   PHINode *VecInd = PHINode::Create(SteppedStart->getType(), 2, "vec.ind",
9318                                     &*State.CFG.PrevBB->getFirstInsertionPt());
9319   VecInd->setDebugLoc(EntryVal->getDebugLoc());
9320   Instruction *LastInduction = VecInd;
9321   for (unsigned Part = 0; Part < State.UF; ++Part) {
9322     State.set(this, LastInduction, Part);
9323 
9324     if (isa<TruncInst>(EntryVal))
9325       State.addMetadata(LastInduction, EntryVal);
9326 
9327     LastInduction = cast<Instruction>(
9328         Builder.CreateBinOp(AddOp, LastInduction, SplatVF, "step.add"));
9329     LastInduction->setDebugLoc(EntryVal->getDebugLoc());
9330   }
9331 
9332   LastInduction->setName("vec.ind.next");
9333   VecInd->addIncoming(SteppedStart, VectorPH);
9334   // Add induction update using an incorrect block temporarily. The phi node
9335   // will be fixed after VPlan execution. Note that at this point the latch
9336   // block cannot be used, as it does not exist yet.
9337   // TODO: Model increment value in VPlan, by turning the recipe into a
9338   // multi-def and a subclass of VPHeaderPHIRecipe.
9339   VecInd->addIncoming(LastInduction, VectorPH);
9340 }
9341 
9342 void VPWidenPointerInductionRecipe::execute(VPTransformState &State) {
9343   assert(IndDesc.getKind() == InductionDescriptor::IK_PtrInduction &&
9344          "Not a pointer induction according to InductionDescriptor!");
9345   assert(cast<PHINode>(getUnderlyingInstr())->getType()->isPointerTy() &&
9346          "Unexpected type.");
9347 
9348   auto *IVR = getParent()->getPlan()->getCanonicalIV();
9349   PHINode *CanonicalIV = cast<PHINode>(State.get(IVR, 0));
9350 
9351   if (onlyScalarsGenerated(State.VF)) {
9352     // This is the normalized GEP that starts counting at zero.
9353     Value *PtrInd = State.Builder.CreateSExtOrTrunc(
9354         CanonicalIV, IndDesc.getStep()->getType());
9355     // Determine the number of scalars we need to generate for each unroll
9356     // iteration. If the instruction is uniform, we only need to generate the
9357     // first lane. Otherwise, we generate all VF values.
9358     bool IsUniform = vputils::onlyFirstLaneUsed(this);
9359     assert((IsUniform || !State.VF.isScalable()) &&
9360            "Cannot scalarize a scalable VF");
9361     unsigned Lanes = IsUniform ? 1 : State.VF.getFixedValue();
9362 
9363     for (unsigned Part = 0; Part < State.UF; ++Part) {
9364       Value *PartStart =
9365           createStepForVF(State.Builder, PtrInd->getType(), State.VF, Part);
9366 
9367       for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
9368         Value *Idx = State.Builder.CreateAdd(
9369             PartStart, ConstantInt::get(PtrInd->getType(), Lane));
9370         Value *GlobalIdx = State.Builder.CreateAdd(PtrInd, Idx);
9371 
9372         Value *Step = CreateStepValue(IndDesc.getStep(), SE,
9373                                       State.CFG.PrevBB->getTerminator());
9374         Value *SclrGep = emitTransformedIndex(
9375             State.Builder, GlobalIdx, IndDesc.getStartValue(), Step, IndDesc);
9376         SclrGep->setName("next.gep");
9377         State.set(this, SclrGep, VPIteration(Part, Lane));
9378       }
9379     }
9380     return;
9381   }
9382 
9383   assert(isa<SCEVConstant>(IndDesc.getStep()) &&
9384          "Induction step not a SCEV constant!");
9385   Type *PhiType = IndDesc.getStep()->getType();
9386 
9387   // Build a pointer phi
9388   Value *ScalarStartValue = getStartValue()->getLiveInIRValue();
9389   Type *ScStValueType = ScalarStartValue->getType();
9390   PHINode *NewPointerPhi =
9391       PHINode::Create(ScStValueType, 2, "pointer.phi", CanonicalIV);
9392 
9393   BasicBlock *VectorPH = State.CFG.getPreheaderBBFor(this);
9394   NewPointerPhi->addIncoming(ScalarStartValue, VectorPH);
9395 
9396   // A pointer induction, performed by using a gep
9397   const DataLayout &DL = NewPointerPhi->getModule()->getDataLayout();
9398   Instruction *InductionLoc = &*State.Builder.GetInsertPoint();
9399 
9400   const SCEV *ScalarStep = IndDesc.getStep();
9401   SCEVExpander Exp(SE, DL, "induction");
9402   Value *ScalarStepValue = Exp.expandCodeFor(ScalarStep, PhiType, InductionLoc);
9403   Value *RuntimeVF = getRuntimeVF(State.Builder, PhiType, State.VF);
9404   Value *NumUnrolledElems =
9405       State.Builder.CreateMul(RuntimeVF, ConstantInt::get(PhiType, State.UF));
9406   Value *InductionGEP = GetElementPtrInst::Create(
9407       IndDesc.getElementType(), NewPointerPhi,
9408       State.Builder.CreateMul(ScalarStepValue, NumUnrolledElems), "ptr.ind",
9409       InductionLoc);
9410   // Add induction update using an incorrect block temporarily. The phi node
9411   // will be fixed after VPlan execution. Note that at this point the latch
9412   // block cannot be used, as it does not exist yet.
9413   // TODO: Model increment value in VPlan, by turning the recipe into a
9414   // multi-def and a subclass of VPHeaderPHIRecipe.
9415   NewPointerPhi->addIncoming(InductionGEP, VectorPH);
9416 
9417   // Create UF many actual address geps that use the pointer
9418   // phi as base and a vectorized version of the step value
9419   // (<step*0, ..., step*N>) as offset.
9420   for (unsigned Part = 0; Part < State.UF; ++Part) {
9421     Type *VecPhiType = VectorType::get(PhiType, State.VF);
9422     Value *StartOffsetScalar =
9423         State.Builder.CreateMul(RuntimeVF, ConstantInt::get(PhiType, Part));
9424     Value *StartOffset =
9425         State.Builder.CreateVectorSplat(State.VF, StartOffsetScalar);
9426     // Create a vector of consecutive numbers from zero to VF.
9427     StartOffset = State.Builder.CreateAdd(
9428         StartOffset, State.Builder.CreateStepVector(VecPhiType));
9429 
9430     Value *GEP = State.Builder.CreateGEP(
9431         IndDesc.getElementType(), NewPointerPhi,
9432         State.Builder.CreateMul(
9433             StartOffset,
9434             State.Builder.CreateVectorSplat(State.VF, ScalarStepValue),
9435             "vector.gep"));
9436     State.set(this, GEP, Part);
9437   }
9438 }
9439 
9440 void VPScalarIVStepsRecipe::execute(VPTransformState &State) {
9441   assert(!State.Instance && "VPScalarIVStepsRecipe being replicated.");
9442 
9443   // Fast-math-flags propagate from the original induction instruction.
9444   IRBuilder<>::FastMathFlagGuard FMFG(State.Builder);
9445   if (IndDesc.getInductionBinOp() &&
9446       isa<FPMathOperator>(IndDesc.getInductionBinOp()))
9447     State.Builder.setFastMathFlags(
9448         IndDesc.getInductionBinOp()->getFastMathFlags());
9449 
9450   Value *Step = State.get(getStepValue(), VPIteration(0, 0));
9451   auto CreateScalarIV = [&](Value *&Step) -> Value * {
9452     Value *ScalarIV = State.get(getCanonicalIV(), VPIteration(0, 0));
9453     auto *CanonicalIV = State.get(getParent()->getPlan()->getCanonicalIV(), 0);
9454     if (!isCanonical() || CanonicalIV->getType() != Ty) {
9455       ScalarIV =
9456           Ty->isIntegerTy()
9457               ? State.Builder.CreateSExtOrTrunc(ScalarIV, Ty)
9458               : State.Builder.CreateCast(Instruction::SIToFP, ScalarIV, Ty);
9459       ScalarIV = emitTransformedIndex(State.Builder, ScalarIV,
9460                                       getStartValue()->getLiveInIRValue(), Step,
9461                                       IndDesc);
9462       ScalarIV->setName("offset.idx");
9463     }
9464     if (TruncToTy) {
9465       assert(Step->getType()->isIntegerTy() &&
9466              "Truncation requires an integer step");
9467       ScalarIV = State.Builder.CreateTrunc(ScalarIV, TruncToTy);
9468       Step = State.Builder.CreateTrunc(Step, TruncToTy);
9469     }
9470     return ScalarIV;
9471   };
9472 
9473   Value *ScalarIV = CreateScalarIV(Step);
9474   if (State.VF.isVector()) {
9475     buildScalarSteps(ScalarIV, Step, IndDesc, this, State);
9476     return;
9477   }
9478 
9479   for (unsigned Part = 0; Part < State.UF; ++Part) {
9480     assert(!State.VF.isScalable() && "scalable vectors not yet supported.");
9481     Value *EntryPart;
9482     if (Step->getType()->isFloatingPointTy()) {
9483       Value *StartIdx =
9484           getRuntimeVFAsFloat(State.Builder, Step->getType(), State.VF * Part);
9485       // Floating-point operations inherit FMF via the builder's flags.
9486       Value *MulOp = State.Builder.CreateFMul(StartIdx, Step);
9487       EntryPart = State.Builder.CreateBinOp(IndDesc.getInductionOpcode(),
9488                                             ScalarIV, MulOp);
9489     } else {
9490       Value *StartIdx =
9491           getRuntimeVF(State.Builder, Step->getType(), State.VF * Part);
9492       EntryPart = State.Builder.CreateAdd(
9493           ScalarIV, State.Builder.CreateMul(StartIdx, Step), "induction");
9494     }
9495     State.set(this, EntryPart, Part);
9496   }
9497 }
9498 
9499 void VPInterleaveRecipe::execute(VPTransformState &State) {
9500   assert(!State.Instance && "Interleave group being replicated.");
9501   State.ILV->vectorizeInterleaveGroup(IG, definedValues(), State, getAddr(),
9502                                       getStoredValues(), getMask());
9503 }
9504 
9505 void VPReductionRecipe::execute(VPTransformState &State) {
9506   assert(!State.Instance && "Reduction being replicated.");
9507   Value *PrevInChain = State.get(getChainOp(), 0);
9508   RecurKind Kind = RdxDesc->getRecurrenceKind();
9509   bool IsOrdered = State.ILV->useOrderedReductions(*RdxDesc);
9510   // Propagate the fast-math flags carried by the underlying instruction.
9511   IRBuilderBase::FastMathFlagGuard FMFGuard(State.Builder);
9512   State.Builder.setFastMathFlags(RdxDesc->getFastMathFlags());
9513   for (unsigned Part = 0; Part < State.UF; ++Part) {
9514     Value *NewVecOp = State.get(getVecOp(), Part);
9515     if (VPValue *Cond = getCondOp()) {
9516       Value *NewCond = State.get(Cond, Part);
9517       VectorType *VecTy = cast<VectorType>(NewVecOp->getType());
9518       Value *Iden = RdxDesc->getRecurrenceIdentity(
9519           Kind, VecTy->getElementType(), RdxDesc->getFastMathFlags());
9520       Value *IdenVec =
9521           State.Builder.CreateVectorSplat(VecTy->getElementCount(), Iden);
9522       Value *Select = State.Builder.CreateSelect(NewCond, NewVecOp, IdenVec);
9523       NewVecOp = Select;
9524     }
9525     Value *NewRed;
9526     Value *NextInChain;
9527     if (IsOrdered) {
9528       if (State.VF.isVector())
9529         NewRed = createOrderedReduction(State.Builder, *RdxDesc, NewVecOp,
9530                                         PrevInChain);
9531       else
9532         NewRed = State.Builder.CreateBinOp(
9533             (Instruction::BinaryOps)RdxDesc->getOpcode(Kind), PrevInChain,
9534             NewVecOp);
9535       PrevInChain = NewRed;
9536     } else {
9537       PrevInChain = State.get(getChainOp(), Part);
9538       NewRed = createTargetReduction(State.Builder, TTI, *RdxDesc, NewVecOp);
9539     }
9540     if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind)) {
9541       NextInChain =
9542           createMinMaxOp(State.Builder, RdxDesc->getRecurrenceKind(),
9543                          NewRed, PrevInChain);
9544     } else if (IsOrdered)
9545       NextInChain = NewRed;
9546     else
9547       NextInChain = State.Builder.CreateBinOp(
9548           (Instruction::BinaryOps)RdxDesc->getOpcode(Kind), NewRed,
9549           PrevInChain);
9550     State.set(this, NextInChain, Part);
9551   }
9552 }
9553 
9554 void VPReplicateRecipe::execute(VPTransformState &State) {
9555   if (State.Instance) { // Generate a single instance.
9556     assert(!State.VF.isScalable() && "Can't scalarize a scalable vector");
9557     State.ILV->scalarizeInstruction(getUnderlyingInstr(), this, *State.Instance,
9558                                     IsPredicated, State);
9559     // Insert scalar instance packing it into a vector.
9560     if (AlsoPack && State.VF.isVector()) {
9561       // If we're constructing lane 0, initialize to start from poison.
9562       if (State.Instance->Lane.isFirstLane()) {
9563         assert(!State.VF.isScalable() && "VF is assumed to be non scalable.");
9564         Value *Poison = PoisonValue::get(
9565             VectorType::get(getUnderlyingValue()->getType(), State.VF));
9566         State.set(this, Poison, State.Instance->Part);
9567       }
9568       State.ILV->packScalarIntoVectorValue(this, *State.Instance, State);
9569     }
9570     return;
9571   }
9572 
9573   // Generate scalar instances for all VF lanes of all UF parts, unless the
9574   // instruction is uniform inwhich case generate only the first lane for each
9575   // of the UF parts.
9576   unsigned EndLane = IsUniform ? 1 : State.VF.getKnownMinValue();
9577   assert((!State.VF.isScalable() || IsUniform) &&
9578          "Can't scalarize a scalable vector");
9579   for (unsigned Part = 0; Part < State.UF; ++Part)
9580     for (unsigned Lane = 0; Lane < EndLane; ++Lane)
9581       State.ILV->scalarizeInstruction(getUnderlyingInstr(), this,
9582                                       VPIteration(Part, Lane), IsPredicated,
9583                                       State);
9584 }
9585 
9586 void VPPredInstPHIRecipe::execute(VPTransformState &State) {
9587   assert(State.Instance && "Predicated instruction PHI works per instance.");
9588   Instruction *ScalarPredInst =
9589       cast<Instruction>(State.get(getOperand(0), *State.Instance));
9590   BasicBlock *PredicatedBB = ScalarPredInst->getParent();
9591   BasicBlock *PredicatingBB = PredicatedBB->getSinglePredecessor();
9592   assert(PredicatingBB && "Predicated block has no single predecessor.");
9593   assert(isa<VPReplicateRecipe>(getOperand(0)) &&
9594          "operand must be VPReplicateRecipe");
9595 
9596   // By current pack/unpack logic we need to generate only a single phi node: if
9597   // a vector value for the predicated instruction exists at this point it means
9598   // the instruction has vector users only, and a phi for the vector value is
9599   // needed. In this case the recipe of the predicated instruction is marked to
9600   // also do that packing, thereby "hoisting" the insert-element sequence.
9601   // Otherwise, a phi node for the scalar value is needed.
9602   unsigned Part = State.Instance->Part;
9603   if (State.hasVectorValue(getOperand(0), Part)) {
9604     Value *VectorValue = State.get(getOperand(0), Part);
9605     InsertElementInst *IEI = cast<InsertElementInst>(VectorValue);
9606     PHINode *VPhi = State.Builder.CreatePHI(IEI->getType(), 2);
9607     VPhi->addIncoming(IEI->getOperand(0), PredicatingBB); // Unmodified vector.
9608     VPhi->addIncoming(IEI, PredicatedBB); // New vector with inserted element.
9609     if (State.hasVectorValue(this, Part))
9610       State.reset(this, VPhi, Part);
9611     else
9612       State.set(this, VPhi, Part);
9613     // NOTE: Currently we need to update the value of the operand, so the next
9614     // predicated iteration inserts its generated value in the correct vector.
9615     State.reset(getOperand(0), VPhi, Part);
9616   } else {
9617     Type *PredInstType = getOperand(0)->getUnderlyingValue()->getType();
9618     PHINode *Phi = State.Builder.CreatePHI(PredInstType, 2);
9619     Phi->addIncoming(PoisonValue::get(ScalarPredInst->getType()),
9620                      PredicatingBB);
9621     Phi->addIncoming(ScalarPredInst, PredicatedBB);
9622     if (State.hasScalarValue(this, *State.Instance))
9623       State.reset(this, Phi, *State.Instance);
9624     else
9625       State.set(this, Phi, *State.Instance);
9626     // NOTE: Currently we need to update the value of the operand, so the next
9627     // predicated iteration inserts its generated value in the correct vector.
9628     State.reset(getOperand(0), Phi, *State.Instance);
9629   }
9630 }
9631 
9632 void VPWidenMemoryInstructionRecipe::execute(VPTransformState &State) {
9633   VPValue *StoredValue = isStore() ? getStoredValue() : nullptr;
9634 
9635   // Attempt to issue a wide load.
9636   LoadInst *LI = dyn_cast<LoadInst>(&Ingredient);
9637   StoreInst *SI = dyn_cast<StoreInst>(&Ingredient);
9638 
9639   assert((LI || SI) && "Invalid Load/Store instruction");
9640   assert((!SI || StoredValue) && "No stored value provided for widened store");
9641   assert((!LI || !StoredValue) && "Stored value provided for widened load");
9642 
9643   Type *ScalarDataTy = getLoadStoreType(&Ingredient);
9644 
9645   auto *DataTy = VectorType::get(ScalarDataTy, State.VF);
9646   const Align Alignment = getLoadStoreAlignment(&Ingredient);
9647   bool CreateGatherScatter = !Consecutive;
9648 
9649   auto &Builder = State.Builder;
9650   InnerLoopVectorizer::VectorParts BlockInMaskParts(State.UF);
9651   bool isMaskRequired = getMask();
9652   if (isMaskRequired)
9653     for (unsigned Part = 0; Part < State.UF; ++Part)
9654       BlockInMaskParts[Part] = State.get(getMask(), Part);
9655 
9656   const auto CreateVecPtr = [&](unsigned Part, Value *Ptr) -> Value * {
9657     // Calculate the pointer for the specific unroll-part.
9658     GetElementPtrInst *PartPtr = nullptr;
9659 
9660     bool InBounds = false;
9661     if (auto *gep = dyn_cast<GetElementPtrInst>(Ptr->stripPointerCasts()))
9662       InBounds = gep->isInBounds();
9663     if (Reverse) {
9664       // If the address is consecutive but reversed, then the
9665       // wide store needs to start at the last vector element.
9666       // RunTimeVF =  VScale * VF.getKnownMinValue()
9667       // For fixed-width VScale is 1, then RunTimeVF = VF.getKnownMinValue()
9668       Value *RunTimeVF = getRuntimeVF(Builder, Builder.getInt32Ty(), State.VF);
9669       // NumElt = -Part * RunTimeVF
9670       Value *NumElt = Builder.CreateMul(Builder.getInt32(-Part), RunTimeVF);
9671       // LastLane = 1 - RunTimeVF
9672       Value *LastLane = Builder.CreateSub(Builder.getInt32(1), RunTimeVF);
9673       PartPtr =
9674           cast<GetElementPtrInst>(Builder.CreateGEP(ScalarDataTy, Ptr, NumElt));
9675       PartPtr->setIsInBounds(InBounds);
9676       PartPtr = cast<GetElementPtrInst>(
9677           Builder.CreateGEP(ScalarDataTy, PartPtr, LastLane));
9678       PartPtr->setIsInBounds(InBounds);
9679       if (isMaskRequired) // Reverse of a null all-one mask is a null mask.
9680         BlockInMaskParts[Part] =
9681             Builder.CreateVectorReverse(BlockInMaskParts[Part], "reverse");
9682     } else {
9683       Value *Increment =
9684           createStepForVF(Builder, Builder.getInt32Ty(), State.VF, Part);
9685       PartPtr = cast<GetElementPtrInst>(
9686           Builder.CreateGEP(ScalarDataTy, Ptr, Increment));
9687       PartPtr->setIsInBounds(InBounds);
9688     }
9689 
9690     unsigned AddressSpace = Ptr->getType()->getPointerAddressSpace();
9691     return Builder.CreateBitCast(PartPtr, DataTy->getPointerTo(AddressSpace));
9692   };
9693 
9694   // Handle Stores:
9695   if (SI) {
9696     State.setDebugLocFromInst(SI);
9697 
9698     for (unsigned Part = 0; Part < State.UF; ++Part) {
9699       Instruction *NewSI = nullptr;
9700       Value *StoredVal = State.get(StoredValue, Part);
9701       if (CreateGatherScatter) {
9702         Value *MaskPart = isMaskRequired ? BlockInMaskParts[Part] : nullptr;
9703         Value *VectorGep = State.get(getAddr(), Part);
9704         NewSI = Builder.CreateMaskedScatter(StoredVal, VectorGep, Alignment,
9705                                             MaskPart);
9706       } else {
9707         if (Reverse) {
9708           // If we store to reverse consecutive memory locations, then we need
9709           // to reverse the order of elements in the stored value.
9710           StoredVal = Builder.CreateVectorReverse(StoredVal, "reverse");
9711           // We don't want to update the value in the map as it might be used in
9712           // another expression. So don't call resetVectorValue(StoredVal).
9713         }
9714         auto *VecPtr =
9715             CreateVecPtr(Part, State.get(getAddr(), VPIteration(0, 0)));
9716         if (isMaskRequired)
9717           NewSI = Builder.CreateMaskedStore(StoredVal, VecPtr, Alignment,
9718                                             BlockInMaskParts[Part]);
9719         else
9720           NewSI = Builder.CreateAlignedStore(StoredVal, VecPtr, Alignment);
9721       }
9722       State.addMetadata(NewSI, SI);
9723     }
9724     return;
9725   }
9726 
9727   // Handle loads.
9728   assert(LI && "Must have a load instruction");
9729   State.setDebugLocFromInst(LI);
9730   for (unsigned Part = 0; Part < State.UF; ++Part) {
9731     Value *NewLI;
9732     if (CreateGatherScatter) {
9733       Value *MaskPart = isMaskRequired ? BlockInMaskParts[Part] : nullptr;
9734       Value *VectorGep = State.get(getAddr(), Part);
9735       NewLI = Builder.CreateMaskedGather(DataTy, VectorGep, Alignment, MaskPart,
9736                                          nullptr, "wide.masked.gather");
9737       State.addMetadata(NewLI, LI);
9738     } else {
9739       auto *VecPtr =
9740           CreateVecPtr(Part, State.get(getAddr(), VPIteration(0, 0)));
9741       if (isMaskRequired)
9742         NewLI = Builder.CreateMaskedLoad(
9743             DataTy, VecPtr, Alignment, BlockInMaskParts[Part],
9744             PoisonValue::get(DataTy), "wide.masked.load");
9745       else
9746         NewLI =
9747             Builder.CreateAlignedLoad(DataTy, VecPtr, Alignment, "wide.load");
9748 
9749       // Add metadata to the load, but setVectorValue to the reverse shuffle.
9750       State.addMetadata(NewLI, LI);
9751       if (Reverse)
9752         NewLI = Builder.CreateVectorReverse(NewLI, "reverse");
9753     }
9754 
9755     State.set(getVPSingleValue(), NewLI, Part);
9756   }
9757 }
9758 
9759 // Determine how to lower the scalar epilogue, which depends on 1) optimising
9760 // for minimum code-size, 2) predicate compiler options, 3) loop hints forcing
9761 // predication, and 4) a TTI hook that analyses whether the loop is suitable
9762 // for predication.
9763 static ScalarEpilogueLowering getScalarEpilogueLowering(
9764     Function *F, Loop *L, LoopVectorizeHints &Hints, ProfileSummaryInfo *PSI,
9765     BlockFrequencyInfo *BFI, TargetTransformInfo *TTI, TargetLibraryInfo *TLI,
9766     AssumptionCache *AC, LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT,
9767     LoopVectorizationLegality &LVL) {
9768   // 1) OptSize takes precedence over all other options, i.e. if this is set,
9769   // don't look at hints or options, and don't request a scalar epilogue.
9770   // (For PGSO, as shouldOptimizeForSize isn't currently accessible from
9771   // LoopAccessInfo (due to code dependency and not being able to reliably get
9772   // PSI/BFI from a loop analysis under NPM), we cannot suppress the collection
9773   // of strides in LoopAccessInfo::analyzeLoop() and vectorize without
9774   // versioning when the vectorization is forced, unlike hasOptSize. So revert
9775   // back to the old way and vectorize with versioning when forced. See D81345.)
9776   if (F->hasOptSize() || (llvm::shouldOptimizeForSize(L->getHeader(), PSI, BFI,
9777                                                       PGSOQueryType::IRPass) &&
9778                           Hints.getForce() != LoopVectorizeHints::FK_Enabled))
9779     return CM_ScalarEpilogueNotAllowedOptSize;
9780 
9781   // 2) If set, obey the directives
9782   if (PreferPredicateOverEpilogue.getNumOccurrences()) {
9783     switch (PreferPredicateOverEpilogue) {
9784     case PreferPredicateTy::ScalarEpilogue:
9785       return CM_ScalarEpilogueAllowed;
9786     case PreferPredicateTy::PredicateElseScalarEpilogue:
9787       return CM_ScalarEpilogueNotNeededUsePredicate;
9788     case PreferPredicateTy::PredicateOrDontVectorize:
9789       return CM_ScalarEpilogueNotAllowedUsePredicate;
9790     };
9791   }
9792 
9793   // 3) If set, obey the hints
9794   switch (Hints.getPredicate()) {
9795   case LoopVectorizeHints::FK_Enabled:
9796     return CM_ScalarEpilogueNotNeededUsePredicate;
9797   case LoopVectorizeHints::FK_Disabled:
9798     return CM_ScalarEpilogueAllowed;
9799   };
9800 
9801   // 4) if the TTI hook indicates this is profitable, request predication.
9802   if (TTI->preferPredicateOverEpilogue(L, LI, *SE, *AC, TLI, DT,
9803                                        LVL.getLAI()))
9804     return CM_ScalarEpilogueNotNeededUsePredicate;
9805 
9806   return CM_ScalarEpilogueAllowed;
9807 }
9808 
9809 Value *VPTransformState::get(VPValue *Def, unsigned Part) {
9810   // If Values have been set for this Def return the one relevant for \p Part.
9811   if (hasVectorValue(Def, Part))
9812     return Data.PerPartOutput[Def][Part];
9813 
9814   if (!hasScalarValue(Def, {Part, 0})) {
9815     Value *IRV = Def->getLiveInIRValue();
9816     Value *B = ILV->getBroadcastInstrs(IRV);
9817     set(Def, B, Part);
9818     return B;
9819   }
9820 
9821   Value *ScalarValue = get(Def, {Part, 0});
9822   // If we aren't vectorizing, we can just copy the scalar map values over
9823   // to the vector map.
9824   if (VF.isScalar()) {
9825     set(Def, ScalarValue, Part);
9826     return ScalarValue;
9827   }
9828 
9829   auto *RepR = dyn_cast<VPReplicateRecipe>(Def);
9830   bool IsUniform = RepR && RepR->isUniform();
9831 
9832   unsigned LastLane = IsUniform ? 0 : VF.getKnownMinValue() - 1;
9833   // Check if there is a scalar value for the selected lane.
9834   if (!hasScalarValue(Def, {Part, LastLane})) {
9835     // At the moment, VPWidenIntOrFpInductionRecipes can also be uniform.
9836     assert((isa<VPWidenIntOrFpInductionRecipe>(Def->getDef()) ||
9837             isa<VPScalarIVStepsRecipe>(Def->getDef())) &&
9838            "unexpected recipe found to be invariant");
9839     IsUniform = true;
9840     LastLane = 0;
9841   }
9842 
9843   auto *LastInst = cast<Instruction>(get(Def, {Part, LastLane}));
9844   // Set the insert point after the last scalarized instruction or after the
9845   // last PHI, if LastInst is a PHI. This ensures the insertelement sequence
9846   // will directly follow the scalar definitions.
9847   auto OldIP = Builder.saveIP();
9848   auto NewIP =
9849       isa<PHINode>(LastInst)
9850           ? BasicBlock::iterator(LastInst->getParent()->getFirstNonPHI())
9851           : std::next(BasicBlock::iterator(LastInst));
9852   Builder.SetInsertPoint(&*NewIP);
9853 
9854   // However, if we are vectorizing, we need to construct the vector values.
9855   // If the value is known to be uniform after vectorization, we can just
9856   // broadcast the scalar value corresponding to lane zero for each unroll
9857   // iteration. Otherwise, we construct the vector values using
9858   // insertelement instructions. Since the resulting vectors are stored in
9859   // State, we will only generate the insertelements once.
9860   Value *VectorValue = nullptr;
9861   if (IsUniform) {
9862     VectorValue = ILV->getBroadcastInstrs(ScalarValue);
9863     set(Def, VectorValue, Part);
9864   } else {
9865     // Initialize packing with insertelements to start from undef.
9866     assert(!VF.isScalable() && "VF is assumed to be non scalable.");
9867     Value *Undef = PoisonValue::get(VectorType::get(LastInst->getType(), VF));
9868     set(Def, Undef, Part);
9869     for (unsigned Lane = 0; Lane < VF.getKnownMinValue(); ++Lane)
9870       ILV->packScalarIntoVectorValue(Def, {Part, Lane}, *this);
9871     VectorValue = get(Def, Part);
9872   }
9873   Builder.restoreIP(OldIP);
9874   return VectorValue;
9875 }
9876 
9877 // Process the loop in the VPlan-native vectorization path. This path builds
9878 // VPlan upfront in the vectorization pipeline, which allows to apply
9879 // VPlan-to-VPlan transformations from the very beginning without modifying the
9880 // input LLVM IR.
9881 static bool processLoopInVPlanNativePath(
9882     Loop *L, PredicatedScalarEvolution &PSE, LoopInfo *LI, DominatorTree *DT,
9883     LoopVectorizationLegality *LVL, TargetTransformInfo *TTI,
9884     TargetLibraryInfo *TLI, DemandedBits *DB, AssumptionCache *AC,
9885     OptimizationRemarkEmitter *ORE, BlockFrequencyInfo *BFI,
9886     ProfileSummaryInfo *PSI, LoopVectorizeHints &Hints,
9887     LoopVectorizationRequirements &Requirements) {
9888 
9889   if (isa<SCEVCouldNotCompute>(PSE.getBackedgeTakenCount())) {
9890     LLVM_DEBUG(dbgs() << "LV: cannot compute the outer-loop trip count\n");
9891     return false;
9892   }
9893   assert(EnableVPlanNativePath && "VPlan-native path is disabled.");
9894   Function *F = L->getHeader()->getParent();
9895   InterleavedAccessInfo IAI(PSE, L, DT, LI, LVL->getLAI());
9896 
9897   ScalarEpilogueLowering SEL = getScalarEpilogueLowering(
9898       F, L, Hints, PSI, BFI, TTI, TLI, AC, LI, PSE.getSE(), DT, *LVL);
9899 
9900   LoopVectorizationCostModel CM(SEL, L, PSE, LI, LVL, *TTI, TLI, DB, AC, ORE, F,
9901                                 &Hints, IAI);
9902   // Use the planner for outer loop vectorization.
9903   // TODO: CM is not used at this point inside the planner. Turn CM into an
9904   // optional argument if we don't need it in the future.
9905   LoopVectorizationPlanner LVP(L, LI, TLI, TTI, LVL, CM, IAI, PSE, Hints, ORE);
9906 
9907   // Get user vectorization factor.
9908   ElementCount UserVF = Hints.getWidth();
9909 
9910   CM.collectElementTypesForWidening();
9911 
9912   // Plan how to best vectorize, return the best VF and its cost.
9913   const VectorizationFactor VF = LVP.planInVPlanNativePath(UserVF);
9914 
9915   // If we are stress testing VPlan builds, do not attempt to generate vector
9916   // code. Masked vector code generation support will follow soon.
9917   // Also, do not attempt to vectorize if no vector code will be produced.
9918   if (VPlanBuildStressTest || VectorizationFactor::Disabled() == VF)
9919     return false;
9920 
9921   VPlan &BestPlan = LVP.getBestPlanFor(VF.Width);
9922 
9923   {
9924     GeneratedRTChecks Checks(*PSE.getSE(), DT, LI, TTI,
9925                              F->getParent()->getDataLayout());
9926     InnerLoopVectorizer LB(L, PSE, LI, DT, TLI, TTI, AC, ORE, VF.Width,
9927                            VF.Width, 1, LVL, &CM, BFI, PSI, Checks);
9928     LLVM_DEBUG(dbgs() << "Vectorizing outer loop in \""
9929                       << L->getHeader()->getParent()->getName() << "\"\n");
9930     LVP.executePlan(VF.Width, 1, BestPlan, LB, DT, false);
9931   }
9932 
9933   // Mark the loop as already vectorized to avoid vectorizing again.
9934   Hints.setAlreadyVectorized();
9935   assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()));
9936   return true;
9937 }
9938 
9939 // Emit a remark if there are stores to floats that required a floating point
9940 // extension. If the vectorized loop was generated with floating point there
9941 // will be a performance penalty from the conversion overhead and the change in
9942 // the vector width.
9943 static void checkMixedPrecision(Loop *L, OptimizationRemarkEmitter *ORE) {
9944   SmallVector<Instruction *, 4> Worklist;
9945   for (BasicBlock *BB : L->getBlocks()) {
9946     for (Instruction &Inst : *BB) {
9947       if (auto *S = dyn_cast<StoreInst>(&Inst)) {
9948         if (S->getValueOperand()->getType()->isFloatTy())
9949           Worklist.push_back(S);
9950       }
9951     }
9952   }
9953 
9954   // Traverse the floating point stores upwards searching, for floating point
9955   // conversions.
9956   SmallPtrSet<const Instruction *, 4> Visited;
9957   SmallPtrSet<const Instruction *, 4> EmittedRemark;
9958   while (!Worklist.empty()) {
9959     auto *I = Worklist.pop_back_val();
9960     if (!L->contains(I))
9961       continue;
9962     if (!Visited.insert(I).second)
9963       continue;
9964 
9965     // Emit a remark if the floating point store required a floating
9966     // point conversion.
9967     // TODO: More work could be done to identify the root cause such as a
9968     // constant or a function return type and point the user to it.
9969     if (isa<FPExtInst>(I) && EmittedRemark.insert(I).second)
9970       ORE->emit([&]() {
9971         return OptimizationRemarkAnalysis(LV_NAME, "VectorMixedPrecision",
9972                                           I->getDebugLoc(), L->getHeader())
9973                << "floating point conversion changes vector width. "
9974                << "Mixed floating point precision requires an up/down "
9975                << "cast that will negatively impact performance.";
9976       });
9977 
9978     for (Use &Op : I->operands())
9979       if (auto *OpI = dyn_cast<Instruction>(Op))
9980         Worklist.push_back(OpI);
9981   }
9982 }
9983 
9984 static bool areRuntimeChecksProfitable(GeneratedRTChecks &Checks,
9985                                        VectorizationFactor &VF,
9986                                        Optional<unsigned> VScale, Loop *L,
9987                                        ScalarEvolution &SE) {
9988   InstructionCost CheckCost = Checks.getCost();
9989   if (!CheckCost.isValid())
9990     return false;
9991 
9992   // When interleaving only scalar and vector cost will be equal, which in turn
9993   // would lead to a divide by 0. Fall back to hard threshold.
9994   if (VF.Width.isScalar()) {
9995     if (CheckCost > VectorizeMemoryCheckThreshold) {
9996       LLVM_DEBUG(
9997           dbgs()
9998           << "LV: Interleaving only is not profitable due to runtime checks\n");
9999       return false;
10000     }
10001     return true;
10002   }
10003 
10004   // The scalar cost should only be 0 when vectorizing with a user specified VF/IC. In those cases, runtime checks should always be generated.
10005   double ScalarC = *VF.ScalarCost.getValue();
10006   if (ScalarC == 0)
10007     return true;
10008 
10009   // First, compute the minimum iteration count required so that the vector
10010   // loop outperforms the scalar loop.
10011   //  The total cost of the scalar loop is
10012   //   ScalarC * TC
10013   //  where
10014   //  * TC is the actual trip count of the loop.
10015   //  * ScalarC is the cost of a single scalar iteration.
10016   //
10017   //  The total cost of the vector loop is
10018   //    RtC + VecC * (TC / VF) + EpiC
10019   //  where
10020   //  * RtC is the cost of the generated runtime checks
10021   //  * VecC is the cost of a single vector iteration.
10022   //  * TC is the actual trip count of the loop
10023   //  * VF is the vectorization factor
10024   //  * EpiCost is the cost of the generated epilogue, including the cost
10025   //    of the remaining scalar operations.
10026   //
10027   // Vectorization is profitable once the total vector cost is less than the
10028   // total scalar cost:
10029   //   RtC + VecC * (TC / VF) + EpiC <  ScalarC * TC
10030   //
10031   // Now we can compute the minimum required trip count TC as
10032   //   (RtC + EpiC) / (ScalarC - (VecC / VF)) < TC
10033   //
10034   // For now we assume the epilogue cost EpiC = 0 for simplicity. Note that
10035   // the computations are performed on doubles, not integers and the result
10036   // is rounded up, hence we get an upper estimate of the TC.
10037   unsigned IntVF = VF.Width.getKnownMinValue();
10038   if (VF.Width.isScalable()) {
10039     unsigned AssumedMinimumVscale = 1;
10040     if (VScale)
10041       AssumedMinimumVscale = *VScale;
10042     IntVF *= AssumedMinimumVscale;
10043   }
10044   double VecCOverVF = double(*VF.Cost.getValue()) / IntVF;
10045   double RtC = *CheckCost.getValue();
10046   double MinTC1 = RtC / (ScalarC - VecCOverVF);
10047 
10048   // Second, compute a minimum iteration count so that the cost of the
10049   // runtime checks is only a fraction of the total scalar loop cost. This
10050   // adds a loop-dependent bound on the overhead incurred if the runtime
10051   // checks fail. In case the runtime checks fail, the cost is RtC + ScalarC
10052   // * TC. To bound the runtime check to be a fraction 1/X of the scalar
10053   // cost, compute
10054   //   RtC < ScalarC * TC * (1 / X)  ==>  RtC * X / ScalarC < TC
10055   double MinTC2 = RtC * 10 / ScalarC;
10056 
10057   // Now pick the larger minimum. If it is not a multiple of VF, choose the
10058   // next closest multiple of VF. This should partly compensate for ignoring
10059   // the epilogue cost.
10060   uint64_t MinTC = std::ceil(std::max(MinTC1, MinTC2));
10061   VF.MinProfitableTripCount = ElementCount::getFixed(alignTo(MinTC, IntVF));
10062 
10063   LLVM_DEBUG(
10064       dbgs() << "LV: Minimum required TC for runtime checks to be profitable:"
10065              << VF.MinProfitableTripCount << "\n");
10066 
10067   // Skip vectorization if the expected trip count is less than the minimum
10068   // required trip count.
10069   if (auto ExpectedTC = getSmallBestKnownTC(SE, L)) {
10070     if (ElementCount::isKnownLT(ElementCount::getFixed(*ExpectedTC),
10071                                 VF.MinProfitableTripCount)) {
10072       LLVM_DEBUG(dbgs() << "LV: Vectorization is not beneficial: expected "
10073                            "trip count < minimum profitable VF ("
10074                         << *ExpectedTC << " < " << VF.MinProfitableTripCount
10075                         << ")\n");
10076 
10077       return false;
10078     }
10079   }
10080   return true;
10081 }
10082 
10083 LoopVectorizePass::LoopVectorizePass(LoopVectorizeOptions Opts)
10084     : InterleaveOnlyWhenForced(Opts.InterleaveOnlyWhenForced ||
10085                                !EnableLoopInterleaving),
10086       VectorizeOnlyWhenForced(Opts.VectorizeOnlyWhenForced ||
10087                               !EnableLoopVectorization) {}
10088 
10089 bool LoopVectorizePass::processLoop(Loop *L) {
10090   assert((EnableVPlanNativePath || L->isInnermost()) &&
10091          "VPlan-native path is not enabled. Only process inner loops.");
10092 
10093 #ifndef NDEBUG
10094   const std::string DebugLocStr = getDebugLocString(L);
10095 #endif /* NDEBUG */
10096 
10097   LLVM_DEBUG(dbgs() << "\nLV: Checking a loop in '"
10098                     << L->getHeader()->getParent()->getName() << "' from "
10099                     << DebugLocStr << "\n");
10100 
10101   LoopVectorizeHints Hints(L, InterleaveOnlyWhenForced, *ORE, TTI);
10102 
10103   LLVM_DEBUG(
10104       dbgs() << "LV: Loop hints:"
10105              << " force="
10106              << (Hints.getForce() == LoopVectorizeHints::FK_Disabled
10107                      ? "disabled"
10108                      : (Hints.getForce() == LoopVectorizeHints::FK_Enabled
10109                             ? "enabled"
10110                             : "?"))
10111              << " width=" << Hints.getWidth()
10112              << " interleave=" << Hints.getInterleave() << "\n");
10113 
10114   // Function containing loop
10115   Function *F = L->getHeader()->getParent();
10116 
10117   // Looking at the diagnostic output is the only way to determine if a loop
10118   // was vectorized (other than looking at the IR or machine code), so it
10119   // is important to generate an optimization remark for each loop. Most of
10120   // these messages are generated as OptimizationRemarkAnalysis. Remarks
10121   // generated as OptimizationRemark and OptimizationRemarkMissed are
10122   // less verbose reporting vectorized loops and unvectorized loops that may
10123   // benefit from vectorization, respectively.
10124 
10125   if (!Hints.allowVectorization(F, L, VectorizeOnlyWhenForced)) {
10126     LLVM_DEBUG(dbgs() << "LV: Loop hints prevent vectorization.\n");
10127     return false;
10128   }
10129 
10130   PredicatedScalarEvolution PSE(*SE, *L);
10131 
10132   // Check if it is legal to vectorize the loop.
10133   LoopVectorizationRequirements Requirements;
10134   LoopVectorizationLegality LVL(L, PSE, DT, TTI, TLI, AA, F, GetLAA, LI, ORE,
10135                                 &Requirements, &Hints, DB, AC, BFI, PSI);
10136   if (!LVL.canVectorize(EnableVPlanNativePath)) {
10137     LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
10138     Hints.emitRemarkWithHints();
10139     return false;
10140   }
10141 
10142   // Check the function attributes and profiles to find out if this function
10143   // should be optimized for size.
10144   ScalarEpilogueLowering SEL = getScalarEpilogueLowering(
10145       F, L, Hints, PSI, BFI, TTI, TLI, AC, LI, PSE.getSE(), DT, LVL);
10146 
10147   // Entrance to the VPlan-native vectorization path. Outer loops are processed
10148   // here. They may require CFG and instruction level transformations before
10149   // even evaluating whether vectorization is profitable. Since we cannot modify
10150   // the incoming IR, we need to build VPlan upfront in the vectorization
10151   // pipeline.
10152   if (!L->isInnermost())
10153     return processLoopInVPlanNativePath(L, PSE, LI, DT, &LVL, TTI, TLI, DB, AC,
10154                                         ORE, BFI, PSI, Hints, Requirements);
10155 
10156   assert(L->isInnermost() && "Inner loop expected.");
10157 
10158   // Check the loop for a trip count threshold: vectorize loops with a tiny trip
10159   // count by optimizing for size, to minimize overheads.
10160   auto ExpectedTC = getSmallBestKnownTC(*SE, L);
10161   if (ExpectedTC && *ExpectedTC < TinyTripCountVectorThreshold) {
10162     LLVM_DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "
10163                       << "This loop is worth vectorizing only if no scalar "
10164                       << "iteration overheads are incurred.");
10165     if (Hints.getForce() == LoopVectorizeHints::FK_Enabled)
10166       LLVM_DEBUG(dbgs() << " But vectorizing was explicitly forced.\n");
10167     else {
10168       LLVM_DEBUG(dbgs() << "\n");
10169       SEL = CM_ScalarEpilogueNotAllowedLowTripLoop;
10170     }
10171   }
10172 
10173   // Check the function attributes to see if implicit floats are allowed.
10174   // FIXME: This check doesn't seem possibly correct -- what if the loop is
10175   // an integer loop and the vector instructions selected are purely integer
10176   // vector instructions?
10177   if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10178     reportVectorizationFailure(
10179         "Can't vectorize when the NoImplicitFloat attribute is used",
10180         "loop not vectorized due to NoImplicitFloat attribute",
10181         "NoImplicitFloat", ORE, L);
10182     Hints.emitRemarkWithHints();
10183     return false;
10184   }
10185 
10186   // Check if the target supports potentially unsafe FP vectorization.
10187   // FIXME: Add a check for the type of safety issue (denormal, signaling)
10188   // for the target we're vectorizing for, to make sure none of the
10189   // additional fp-math flags can help.
10190   if (Hints.isPotentiallyUnsafe() &&
10191       TTI->isFPVectorizationPotentiallyUnsafe()) {
10192     reportVectorizationFailure(
10193         "Potentially unsafe FP op prevents vectorization",
10194         "loop not vectorized due to unsafe FP support.",
10195         "UnsafeFP", ORE, L);
10196     Hints.emitRemarkWithHints();
10197     return false;
10198   }
10199 
10200   bool AllowOrderedReductions;
10201   // If the flag is set, use that instead and override the TTI behaviour.
10202   if (ForceOrderedReductions.getNumOccurrences() > 0)
10203     AllowOrderedReductions = ForceOrderedReductions;
10204   else
10205     AllowOrderedReductions = TTI->enableOrderedReductions();
10206   if (!LVL.canVectorizeFPMath(AllowOrderedReductions)) {
10207     ORE->emit([&]() {
10208       auto *ExactFPMathInst = Requirements.getExactFPInst();
10209       return OptimizationRemarkAnalysisFPCommute(DEBUG_TYPE, "CantReorderFPOps",
10210                                                  ExactFPMathInst->getDebugLoc(),
10211                                                  ExactFPMathInst->getParent())
10212              << "loop not vectorized: cannot prove it is safe to reorder "
10213                 "floating-point operations";
10214     });
10215     LLVM_DEBUG(dbgs() << "LV: loop not vectorized: cannot prove it is safe to "
10216                          "reorder floating-point operations\n");
10217     Hints.emitRemarkWithHints();
10218     return false;
10219   }
10220 
10221   bool UseInterleaved = TTI->enableInterleavedAccessVectorization();
10222   InterleavedAccessInfo IAI(PSE, L, DT, LI, LVL.getLAI());
10223 
10224   // If an override option has been passed in for interleaved accesses, use it.
10225   if (EnableInterleavedMemAccesses.getNumOccurrences() > 0)
10226     UseInterleaved = EnableInterleavedMemAccesses;
10227 
10228   // Analyze interleaved memory accesses.
10229   if (UseInterleaved) {
10230     IAI.analyzeInterleaving(useMaskedInterleavedAccesses(*TTI));
10231   }
10232 
10233   // Use the cost model.
10234   LoopVectorizationCostModel CM(SEL, L, PSE, LI, &LVL, *TTI, TLI, DB, AC, ORE,
10235                                 F, &Hints, IAI);
10236   CM.collectValuesToIgnore();
10237   CM.collectElementTypesForWidening();
10238 
10239   // Use the planner for vectorization.
10240   LoopVectorizationPlanner LVP(L, LI, TLI, TTI, &LVL, CM, IAI, PSE, Hints, ORE);
10241 
10242   // Get user vectorization factor and interleave count.
10243   ElementCount UserVF = Hints.getWidth();
10244   unsigned UserIC = Hints.getInterleave();
10245 
10246   // Plan how to best vectorize, return the best VF and its cost.
10247   Optional<VectorizationFactor> MaybeVF = LVP.plan(UserVF, UserIC);
10248 
10249   VectorizationFactor VF = VectorizationFactor::Disabled();
10250   unsigned IC = 1;
10251 
10252   GeneratedRTChecks Checks(*PSE.getSE(), DT, LI, TTI,
10253                            F->getParent()->getDataLayout());
10254   if (MaybeVF) {
10255     VF = *MaybeVF;
10256     // Select the interleave count.
10257     IC = CM.selectInterleaveCount(VF.Width, *VF.Cost.getValue());
10258 
10259     unsigned SelectedIC = std::max(IC, UserIC);
10260     //  Optimistically generate runtime checks if they are needed. Drop them if
10261     //  they turn out to not be profitable.
10262     if (VF.Width.isVector() || SelectedIC > 1)
10263       Checks.Create(L, *LVL.getLAI(), PSE.getPredicate(), VF.Width, SelectedIC);
10264 
10265     // Check if it is profitable to vectorize with runtime checks.
10266     bool ForceVectorization =
10267         Hints.getForce() == LoopVectorizeHints::FK_Enabled;
10268     if (!ForceVectorization &&
10269         !areRuntimeChecksProfitable(Checks, VF, CM.getVScaleForTuning(), L,
10270                                     *PSE.getSE())) {
10271       ORE->emit([&]() {
10272         return OptimizationRemarkAnalysisAliasing(
10273                    DEBUG_TYPE, "CantReorderMemOps", L->getStartLoc(),
10274                    L->getHeader())
10275                << "loop not vectorized: cannot prove it is safe to reorder "
10276                   "memory operations";
10277       });
10278       LLVM_DEBUG(dbgs() << "LV: Too many memory checks needed.\n");
10279       Hints.emitRemarkWithHints();
10280       return false;
10281     }
10282   }
10283 
10284   // Identify the diagnostic messages that should be produced.
10285   std::pair<StringRef, std::string> VecDiagMsg, IntDiagMsg;
10286   bool VectorizeLoop = true, InterleaveLoop = true;
10287   if (VF.Width.isScalar()) {
10288     LLVM_DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
10289     VecDiagMsg = std::make_pair(
10290         "VectorizationNotBeneficial",
10291         "the cost-model indicates that vectorization is not beneficial");
10292     VectorizeLoop = false;
10293   }
10294 
10295   if (!MaybeVF && UserIC > 1) {
10296     // Tell the user interleaving was avoided up-front, despite being explicitly
10297     // requested.
10298     LLVM_DEBUG(dbgs() << "LV: Ignoring UserIC, because vectorization and "
10299                          "interleaving should be avoided up front\n");
10300     IntDiagMsg = std::make_pair(
10301         "InterleavingAvoided",
10302         "Ignoring UserIC, because interleaving was avoided up front");
10303     InterleaveLoop = false;
10304   } else if (IC == 1 && UserIC <= 1) {
10305     // Tell the user interleaving is not beneficial.
10306     LLVM_DEBUG(dbgs() << "LV: Interleaving is not beneficial.\n");
10307     IntDiagMsg = std::make_pair(
10308         "InterleavingNotBeneficial",
10309         "the cost-model indicates that interleaving is not beneficial");
10310     InterleaveLoop = false;
10311     if (UserIC == 1) {
10312       IntDiagMsg.first = "InterleavingNotBeneficialAndDisabled";
10313       IntDiagMsg.second +=
10314           " and is explicitly disabled or interleave count is set to 1";
10315     }
10316   } else if (IC > 1 && UserIC == 1) {
10317     // Tell the user interleaving is beneficial, but it explicitly disabled.
10318     LLVM_DEBUG(
10319         dbgs() << "LV: Interleaving is beneficial but is explicitly disabled.");
10320     IntDiagMsg = std::make_pair(
10321         "InterleavingBeneficialButDisabled",
10322         "the cost-model indicates that interleaving is beneficial "
10323         "but is explicitly disabled or interleave count is set to 1");
10324     InterleaveLoop = false;
10325   }
10326 
10327   // Override IC if user provided an interleave count.
10328   IC = UserIC > 0 ? UserIC : IC;
10329 
10330   // Emit diagnostic messages, if any.
10331   const char *VAPassName = Hints.vectorizeAnalysisPassName();
10332   if (!VectorizeLoop && !InterleaveLoop) {
10333     // Do not vectorize or interleaving the loop.
10334     ORE->emit([&]() {
10335       return OptimizationRemarkMissed(VAPassName, VecDiagMsg.first,
10336                                       L->getStartLoc(), L->getHeader())
10337              << VecDiagMsg.second;
10338     });
10339     ORE->emit([&]() {
10340       return OptimizationRemarkMissed(LV_NAME, IntDiagMsg.first,
10341                                       L->getStartLoc(), L->getHeader())
10342              << IntDiagMsg.second;
10343     });
10344     return false;
10345   } else if (!VectorizeLoop && InterleaveLoop) {
10346     LLVM_DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
10347     ORE->emit([&]() {
10348       return OptimizationRemarkAnalysis(VAPassName, VecDiagMsg.first,
10349                                         L->getStartLoc(), L->getHeader())
10350              << VecDiagMsg.second;
10351     });
10352   } else if (VectorizeLoop && !InterleaveLoop) {
10353     LLVM_DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width
10354                       << ") in " << DebugLocStr << '\n');
10355     ORE->emit([&]() {
10356       return OptimizationRemarkAnalysis(LV_NAME, IntDiagMsg.first,
10357                                         L->getStartLoc(), L->getHeader())
10358              << IntDiagMsg.second;
10359     });
10360   } else if (VectorizeLoop && InterleaveLoop) {
10361     LLVM_DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width
10362                       << ") in " << DebugLocStr << '\n');
10363     LLVM_DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
10364   }
10365 
10366   bool DisableRuntimeUnroll = false;
10367   MDNode *OrigLoopID = L->getLoopID();
10368   {
10369     using namespace ore;
10370     if (!VectorizeLoop) {
10371       assert(IC > 1 && "interleave count should not be 1 or 0");
10372       // If we decided that it is not legal to vectorize the loop, then
10373       // interleave it.
10374       InnerLoopUnroller Unroller(L, PSE, LI, DT, TLI, TTI, AC, ORE, IC, &LVL,
10375                                  &CM, BFI, PSI, Checks);
10376 
10377       VPlan &BestPlan = LVP.getBestPlanFor(VF.Width);
10378       LVP.executePlan(VF.Width, IC, BestPlan, Unroller, DT, false);
10379 
10380       ORE->emit([&]() {
10381         return OptimizationRemark(LV_NAME, "Interleaved", L->getStartLoc(),
10382                                   L->getHeader())
10383                << "interleaved loop (interleaved count: "
10384                << NV("InterleaveCount", IC) << ")";
10385       });
10386     } else {
10387       // If we decided that it is *legal* to vectorize the loop, then do it.
10388 
10389       // Consider vectorizing the epilogue too if it's profitable.
10390       VectorizationFactor EpilogueVF =
10391           CM.selectEpilogueVectorizationFactor(VF.Width, LVP);
10392       if (EpilogueVF.Width.isVector()) {
10393 
10394         // The first pass vectorizes the main loop and creates a scalar epilogue
10395         // to be vectorized by executing the plan (potentially with a different
10396         // factor) again shortly afterwards.
10397         EpilogueLoopVectorizationInfo EPI(VF.Width, IC, EpilogueVF.Width, 1);
10398         EpilogueVectorizerMainLoop MainILV(L, PSE, LI, DT, TLI, TTI, AC, ORE,
10399                                            EPI, &LVL, &CM, BFI, PSI, Checks);
10400 
10401         VPlan &BestMainPlan = LVP.getBestPlanFor(EPI.MainLoopVF);
10402         LVP.executePlan(EPI.MainLoopVF, EPI.MainLoopUF, BestMainPlan, MainILV,
10403                         DT, true);
10404         ++LoopsVectorized;
10405 
10406         // Second pass vectorizes the epilogue and adjusts the control flow
10407         // edges from the first pass.
10408         EPI.MainLoopVF = EPI.EpilogueVF;
10409         EPI.MainLoopUF = EPI.EpilogueUF;
10410         EpilogueVectorizerEpilogueLoop EpilogILV(L, PSE, LI, DT, TLI, TTI, AC,
10411                                                  ORE, EPI, &LVL, &CM, BFI, PSI,
10412                                                  Checks);
10413 
10414         VPlan &BestEpiPlan = LVP.getBestPlanFor(EPI.EpilogueVF);
10415         VPRegionBlock *VectorLoop = BestEpiPlan.getVectorLoopRegion();
10416         VPBasicBlock *Header = VectorLoop->getEntryBasicBlock();
10417         Header->setName("vec.epilog.vector.body");
10418 
10419         // Ensure that the start values for any VPReductionPHIRecipes are
10420         // updated before vectorising the epilogue loop.
10421         for (VPRecipeBase &R : Header->phis()) {
10422           if (auto *ReductionPhi = dyn_cast<VPReductionPHIRecipe>(&R)) {
10423             if (auto *Resume = MainILV.getReductionResumeValue(
10424                     ReductionPhi->getRecurrenceDescriptor())) {
10425               VPValue *StartVal = BestEpiPlan.getOrAddExternalDef(Resume);
10426               ReductionPhi->setOperand(0, StartVal);
10427             }
10428           }
10429         }
10430 
10431         LVP.executePlan(EPI.EpilogueVF, EPI.EpilogueUF, BestEpiPlan, EpilogILV,
10432                         DT, true);
10433         ++LoopsEpilogueVectorized;
10434 
10435         if (!MainILV.areSafetyChecksAdded())
10436           DisableRuntimeUnroll = true;
10437       } else {
10438         InnerLoopVectorizer LB(L, PSE, LI, DT, TLI, TTI, AC, ORE, VF.Width,
10439                                VF.MinProfitableTripCount, IC, &LVL, &CM, BFI,
10440                                PSI, Checks);
10441 
10442         VPlan &BestPlan = LVP.getBestPlanFor(VF.Width);
10443         LVP.executePlan(VF.Width, IC, BestPlan, LB, DT, false);
10444         ++LoopsVectorized;
10445 
10446         // Add metadata to disable runtime unrolling a scalar loop when there
10447         // are no runtime checks about strides and memory. A scalar loop that is
10448         // rarely used is not worth unrolling.
10449         if (!LB.areSafetyChecksAdded())
10450           DisableRuntimeUnroll = true;
10451       }
10452       // Report the vectorization decision.
10453       ORE->emit([&]() {
10454         return OptimizationRemark(LV_NAME, "Vectorized", L->getStartLoc(),
10455                                   L->getHeader())
10456                << "vectorized loop (vectorization width: "
10457                << NV("VectorizationFactor", VF.Width)
10458                << ", interleaved count: " << NV("InterleaveCount", IC) << ")";
10459       });
10460     }
10461 
10462     if (ORE->allowExtraAnalysis(LV_NAME))
10463       checkMixedPrecision(L, ORE);
10464   }
10465 
10466   Optional<MDNode *> RemainderLoopID =
10467       makeFollowupLoopID(OrigLoopID, {LLVMLoopVectorizeFollowupAll,
10468                                       LLVMLoopVectorizeFollowupEpilogue});
10469   if (RemainderLoopID) {
10470     L->setLoopID(RemainderLoopID.value());
10471   } else {
10472     if (DisableRuntimeUnroll)
10473       AddRuntimeUnrollDisableMetaData(L);
10474 
10475     // Mark the loop as already vectorized to avoid vectorizing again.
10476     Hints.setAlreadyVectorized();
10477   }
10478 
10479   assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()));
10480   return true;
10481 }
10482 
10483 LoopVectorizeResult LoopVectorizePass::runImpl(
10484     Function &F, ScalarEvolution &SE_, LoopInfo &LI_, TargetTransformInfo &TTI_,
10485     DominatorTree &DT_, BlockFrequencyInfo &BFI_, TargetLibraryInfo *TLI_,
10486     DemandedBits &DB_, AAResults &AA_, AssumptionCache &AC_,
10487     std::function<const LoopAccessInfo &(Loop &)> &GetLAA_,
10488     OptimizationRemarkEmitter &ORE_, ProfileSummaryInfo *PSI_) {
10489   SE = &SE_;
10490   LI = &LI_;
10491   TTI = &TTI_;
10492   DT = &DT_;
10493   BFI = &BFI_;
10494   TLI = TLI_;
10495   AA = &AA_;
10496   AC = &AC_;
10497   GetLAA = &GetLAA_;
10498   DB = &DB_;
10499   ORE = &ORE_;
10500   PSI = PSI_;
10501 
10502   // Don't attempt if
10503   // 1. the target claims to have no vector registers, and
10504   // 2. interleaving won't help ILP.
10505   //
10506   // The second condition is necessary because, even if the target has no
10507   // vector registers, loop vectorization may still enable scalar
10508   // interleaving.
10509   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true)) &&
10510       TTI->getMaxInterleaveFactor(1) < 2)
10511     return LoopVectorizeResult(false, false);
10512 
10513   bool Changed = false, CFGChanged = false;
10514 
10515   // The vectorizer requires loops to be in simplified form.
10516   // Since simplification may add new inner loops, it has to run before the
10517   // legality and profitability checks. This means running the loop vectorizer
10518   // will simplify all loops, regardless of whether anything end up being
10519   // vectorized.
10520   for (auto &L : *LI)
10521     Changed |= CFGChanged |=
10522         simplifyLoop(L, DT, LI, SE, AC, nullptr, false /* PreserveLCSSA */);
10523 
10524   // Build up a worklist of inner-loops to vectorize. This is necessary as
10525   // the act of vectorizing or partially unrolling a loop creates new loops
10526   // and can invalidate iterators across the loops.
10527   SmallVector<Loop *, 8> Worklist;
10528 
10529   for (Loop *L : *LI)
10530     collectSupportedLoops(*L, LI, ORE, Worklist);
10531 
10532   LoopsAnalyzed += Worklist.size();
10533 
10534   // Now walk the identified inner loops.
10535   while (!Worklist.empty()) {
10536     Loop *L = Worklist.pop_back_val();
10537 
10538     // For the inner loops we actually process, form LCSSA to simplify the
10539     // transform.
10540     Changed |= formLCSSARecursively(*L, *DT, LI, SE);
10541 
10542     Changed |= CFGChanged |= processLoop(L);
10543   }
10544 
10545   // Process each loop nest in the function.
10546   return LoopVectorizeResult(Changed, CFGChanged);
10547 }
10548 
10549 PreservedAnalyses LoopVectorizePass::run(Function &F,
10550                                          FunctionAnalysisManager &AM) {
10551     auto &LI = AM.getResult<LoopAnalysis>(F);
10552     // There are no loops in the function. Return before computing other expensive
10553     // analyses.
10554     if (LI.empty())
10555       return PreservedAnalyses::all();
10556     auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
10557     auto &TTI = AM.getResult<TargetIRAnalysis>(F);
10558     auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
10559     auto &BFI = AM.getResult<BlockFrequencyAnalysis>(F);
10560     auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
10561     auto &AA = AM.getResult<AAManager>(F);
10562     auto &AC = AM.getResult<AssumptionAnalysis>(F);
10563     auto &DB = AM.getResult<DemandedBitsAnalysis>(F);
10564     auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
10565 
10566     auto &LAM = AM.getResult<LoopAnalysisManagerFunctionProxy>(F).getManager();
10567     std::function<const LoopAccessInfo &(Loop &)> GetLAA =
10568         [&](Loop &L) -> const LoopAccessInfo & {
10569       LoopStandardAnalysisResults AR = {AA,  AC,  DT,      LI,      SE,
10570                                         TLI, TTI, nullptr, nullptr, nullptr};
10571       return LAM.getResult<LoopAccessAnalysis>(L, AR);
10572     };
10573     auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
10574     ProfileSummaryInfo *PSI =
10575         MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
10576     LoopVectorizeResult Result =
10577         runImpl(F, SE, LI, TTI, DT, BFI, &TLI, DB, AA, AC, GetLAA, ORE, PSI);
10578     if (!Result.MadeAnyChange)
10579       return PreservedAnalyses::all();
10580     PreservedAnalyses PA;
10581 
10582     // We currently do not preserve loopinfo/dominator analyses with outer loop
10583     // vectorization. Until this is addressed, mark these analyses as preserved
10584     // only for non-VPlan-native path.
10585     // TODO: Preserve Loop and Dominator analyses for VPlan-native path.
10586     if (!EnableVPlanNativePath) {
10587       PA.preserve<LoopAnalysis>();
10588       PA.preserve<DominatorTreeAnalysis>();
10589     }
10590 
10591     if (Result.MadeCFGChange) {
10592       // Making CFG changes likely means a loop got vectorized. Indicate that
10593       // extra simplification passes should be run.
10594       // TODO: MadeCFGChanges is not a prefect proxy. Extra passes should only
10595       // be run if runtime checks have been added.
10596       AM.getResult<ShouldRunExtraVectorPasses>(F);
10597       PA.preserve<ShouldRunExtraVectorPasses>();
10598     } else {
10599       PA.preserveSet<CFGAnalyses>();
10600     }
10601     return PA;
10602 }
10603 
10604 void LoopVectorizePass::printPipeline(
10605     raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
10606   static_cast<PassInfoMixin<LoopVectorizePass> *>(this)->printPipeline(
10607       OS, MapClassName2PassName);
10608 
10609   OS << "<";
10610   OS << (InterleaveOnlyWhenForced ? "" : "no-") << "interleave-forced-only;";
10611   OS << (VectorizeOnlyWhenForced ? "" : "no-") << "vectorize-forced-only;";
10612   OS << ">";
10613 }
10614