1 //===- LoopVectorize.cpp - A Loop Vectorizer ------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This is the LLVM loop vectorizer. This pass modifies 'vectorizable' loops
10 // and generates target-independent LLVM-IR.
11 // The vectorizer uses the TargetTransformInfo analysis to estimate the costs
12 // of instructions in order to estimate the profitability of vectorization.
13 //
14 // The loop vectorizer combines consecutive loop iterations into a single
15 // 'wide' iteration. After this transformation the index is incremented
16 // by the SIMD vector width, and not by one.
17 //
18 // This pass has three parts:
19 // 1. The main loop pass that drives the different parts.
20 // 2. LoopVectorizationLegality - A unit that checks for the legality
21 //    of the vectorization.
22 // 3. InnerLoopVectorizer - A unit that performs the actual
23 //    widening of instructions.
24 // 4. LoopVectorizationCostModel - A unit that checks for the profitability
25 //    of vectorization. It decides on the optimal vector width, which
26 //    can be one, if vectorization is not profitable.
27 //
28 // There is a development effort going on to migrate loop vectorizer to the
29 // VPlan infrastructure and to introduce outer loop vectorization support (see
30 // docs/Proposal/VectorizationPlan.rst and
31 // http://lists.llvm.org/pipermail/llvm-dev/2017-December/119523.html). For this
32 // purpose, we temporarily introduced the VPlan-native vectorization path: an
33 // alternative vectorization path that is natively implemented on top of the
34 // VPlan infrastructure. See EnableVPlanNativePath for enabling.
35 //
36 //===----------------------------------------------------------------------===//
37 //
38 // The reduction-variable vectorization is based on the paper:
39 //  D. Nuzman and R. Henderson. Multi-platform Auto-vectorization.
40 //
41 // Variable uniformity checks are inspired by:
42 //  Karrenberg, R. and Hack, S. Whole Function Vectorization.
43 //
44 // The interleaved access vectorization is based on the paper:
45 //  Dorit Nuzman, Ira Rosen and Ayal Zaks.  Auto-Vectorization of Interleaved
46 //  Data for SIMD
47 //
48 // Other ideas/concepts are from:
49 //  A. Zaks and D. Nuzman. Autovectorization in GCC-two years later.
50 //
51 //  S. Maleki, Y. Gao, M. Garzaran, T. Wong and D. Padua.  An Evaluation of
52 //  Vectorizing Compilers.
53 //
54 //===----------------------------------------------------------------------===//
55 
56 #include "llvm/Transforms/Vectorize/LoopVectorize.h"
57 #include "LoopVectorizationPlanner.h"
58 #include "VPRecipeBuilder.h"
59 #include "VPlan.h"
60 #include "VPlanHCFGBuilder.h"
61 #include "VPlanPredicator.h"
62 #include "VPlanTransforms.h"
63 #include "llvm/ADT/APInt.h"
64 #include "llvm/ADT/ArrayRef.h"
65 #include "llvm/ADT/DenseMap.h"
66 #include "llvm/ADT/DenseMapInfo.h"
67 #include "llvm/ADT/Hashing.h"
68 #include "llvm/ADT/MapVector.h"
69 #include "llvm/ADT/None.h"
70 #include "llvm/ADT/Optional.h"
71 #include "llvm/ADT/STLExtras.h"
72 #include "llvm/ADT/SmallPtrSet.h"
73 #include "llvm/ADT/SmallSet.h"
74 #include "llvm/ADT/SmallVector.h"
75 #include "llvm/ADT/Statistic.h"
76 #include "llvm/ADT/StringRef.h"
77 #include "llvm/ADT/Twine.h"
78 #include "llvm/ADT/iterator_range.h"
79 #include "llvm/Analysis/AssumptionCache.h"
80 #include "llvm/Analysis/BasicAliasAnalysis.h"
81 #include "llvm/Analysis/BlockFrequencyInfo.h"
82 #include "llvm/Analysis/CFG.h"
83 #include "llvm/Analysis/CodeMetrics.h"
84 #include "llvm/Analysis/DemandedBits.h"
85 #include "llvm/Analysis/GlobalsModRef.h"
86 #include "llvm/Analysis/LoopAccessAnalysis.h"
87 #include "llvm/Analysis/LoopAnalysisManager.h"
88 #include "llvm/Analysis/LoopInfo.h"
89 #include "llvm/Analysis/LoopIterator.h"
90 #include "llvm/Analysis/MemorySSA.h"
91 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
92 #include "llvm/Analysis/ProfileSummaryInfo.h"
93 #include "llvm/Analysis/ScalarEvolution.h"
94 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
95 #include "llvm/Analysis/TargetLibraryInfo.h"
96 #include "llvm/Analysis/TargetTransformInfo.h"
97 #include "llvm/Analysis/VectorUtils.h"
98 #include "llvm/IR/Attributes.h"
99 #include "llvm/IR/BasicBlock.h"
100 #include "llvm/IR/CFG.h"
101 #include "llvm/IR/Constant.h"
102 #include "llvm/IR/Constants.h"
103 #include "llvm/IR/DataLayout.h"
104 #include "llvm/IR/DebugInfoMetadata.h"
105 #include "llvm/IR/DebugLoc.h"
106 #include "llvm/IR/DerivedTypes.h"
107 #include "llvm/IR/DiagnosticInfo.h"
108 #include "llvm/IR/Dominators.h"
109 #include "llvm/IR/Function.h"
110 #include "llvm/IR/IRBuilder.h"
111 #include "llvm/IR/InstrTypes.h"
112 #include "llvm/IR/Instruction.h"
113 #include "llvm/IR/Instructions.h"
114 #include "llvm/IR/IntrinsicInst.h"
115 #include "llvm/IR/Intrinsics.h"
116 #include "llvm/IR/LLVMContext.h"
117 #include "llvm/IR/Metadata.h"
118 #include "llvm/IR/Module.h"
119 #include "llvm/IR/Operator.h"
120 #include "llvm/IR/PatternMatch.h"
121 #include "llvm/IR/Type.h"
122 #include "llvm/IR/Use.h"
123 #include "llvm/IR/User.h"
124 #include "llvm/IR/Value.h"
125 #include "llvm/IR/ValueHandle.h"
126 #include "llvm/IR/Verifier.h"
127 #include "llvm/InitializePasses.h"
128 #include "llvm/Pass.h"
129 #include "llvm/Support/Casting.h"
130 #include "llvm/Support/CommandLine.h"
131 #include "llvm/Support/Compiler.h"
132 #include "llvm/Support/Debug.h"
133 #include "llvm/Support/ErrorHandling.h"
134 #include "llvm/Support/InstructionCost.h"
135 #include "llvm/Support/MathExtras.h"
136 #include "llvm/Support/raw_ostream.h"
137 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
138 #include "llvm/Transforms/Utils/InjectTLIMappings.h"
139 #include "llvm/Transforms/Utils/LoopSimplify.h"
140 #include "llvm/Transforms/Utils/LoopUtils.h"
141 #include "llvm/Transforms/Utils/LoopVersioning.h"
142 #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
143 #include "llvm/Transforms/Utils/SizeOpts.h"
144 #include "llvm/Transforms/Vectorize/LoopVectorizationLegality.h"
145 #include <algorithm>
146 #include <cassert>
147 #include <cstdint>
148 #include <cstdlib>
149 #include <functional>
150 #include <iterator>
151 #include <limits>
152 #include <memory>
153 #include <string>
154 #include <tuple>
155 #include <utility>
156 
157 using namespace llvm;
158 
159 #define LV_NAME "loop-vectorize"
160 #define DEBUG_TYPE LV_NAME
161 
162 #ifndef NDEBUG
163 const char VerboseDebug[] = DEBUG_TYPE "-verbose";
164 #endif
165 
166 /// @{
167 /// Metadata attribute names
168 const char LLVMLoopVectorizeFollowupAll[] = "llvm.loop.vectorize.followup_all";
169 const char LLVMLoopVectorizeFollowupVectorized[] =
170     "llvm.loop.vectorize.followup_vectorized";
171 const char LLVMLoopVectorizeFollowupEpilogue[] =
172     "llvm.loop.vectorize.followup_epilogue";
173 /// @}
174 
175 STATISTIC(LoopsVectorized, "Number of loops vectorized");
176 STATISTIC(LoopsAnalyzed, "Number of loops analyzed for vectorization");
177 STATISTIC(LoopsEpilogueVectorized, "Number of epilogues vectorized");
178 
179 static cl::opt<bool> EnableEpilogueVectorization(
180     "enable-epilogue-vectorization", cl::init(true), cl::Hidden,
181     cl::desc("Enable vectorization of epilogue loops."));
182 
183 static cl::opt<unsigned> EpilogueVectorizationForceVF(
184     "epilogue-vectorization-force-VF", cl::init(1), cl::Hidden,
185     cl::desc("When epilogue vectorization is enabled, and a value greater than "
186              "1 is specified, forces the given VF for all applicable epilogue "
187              "loops."));
188 
189 static cl::opt<unsigned> EpilogueVectorizationMinVF(
190     "epilogue-vectorization-minimum-VF", cl::init(16), cl::Hidden,
191     cl::desc("Only loops with vectorization factor equal to or larger than "
192              "the specified value are considered for epilogue vectorization."));
193 
194 /// Loops with a known constant trip count below this number are vectorized only
195 /// if no scalar iteration overheads are incurred.
196 static cl::opt<unsigned> TinyTripCountVectorThreshold(
197     "vectorizer-min-trip-count", cl::init(16), cl::Hidden,
198     cl::desc("Loops with a constant trip count that is smaller than this "
199              "value are vectorized only if no scalar iteration overheads "
200              "are incurred."));
201 
202 static cl::opt<unsigned> PragmaVectorizeMemoryCheckThreshold(
203     "pragma-vectorize-memory-check-threshold", cl::init(128), cl::Hidden,
204     cl::desc("The maximum allowed number of runtime memory checks with a "
205              "vectorize(enable) pragma."));
206 
207 // Option prefer-predicate-over-epilogue indicates that an epilogue is undesired,
208 // that predication is preferred, and this lists all options. I.e., the
209 // vectorizer will try to fold the tail-loop (epilogue) into the vector body
210 // and predicate the instructions accordingly. If tail-folding fails, there are
211 // different fallback strategies depending on these values:
212 namespace PreferPredicateTy {
213   enum Option {
214     ScalarEpilogue = 0,
215     PredicateElseScalarEpilogue,
216     PredicateOrDontVectorize
217   };
218 } // namespace PreferPredicateTy
219 
220 static cl::opt<PreferPredicateTy::Option> PreferPredicateOverEpilogue(
221     "prefer-predicate-over-epilogue",
222     cl::init(PreferPredicateTy::ScalarEpilogue),
223     cl::Hidden,
224     cl::desc("Tail-folding and predication preferences over creating a scalar "
225              "epilogue loop."),
226     cl::values(clEnumValN(PreferPredicateTy::ScalarEpilogue,
227                          "scalar-epilogue",
228                          "Don't tail-predicate loops, create scalar epilogue"),
229               clEnumValN(PreferPredicateTy::PredicateElseScalarEpilogue,
230                          "predicate-else-scalar-epilogue",
231                          "prefer tail-folding, create scalar epilogue if tail "
232                          "folding fails."),
233               clEnumValN(PreferPredicateTy::PredicateOrDontVectorize,
234                          "predicate-dont-vectorize",
235                          "prefers tail-folding, don't attempt vectorization if "
236                          "tail-folding fails.")));
237 
238 static cl::opt<bool> MaximizeBandwidth(
239     "vectorizer-maximize-bandwidth", cl::init(false), cl::Hidden,
240     cl::desc("Maximize bandwidth when selecting vectorization factor which "
241              "will be determined by the smallest type in loop."));
242 
243 static cl::opt<bool> EnableInterleavedMemAccesses(
244     "enable-interleaved-mem-accesses", cl::init(false), cl::Hidden,
245     cl::desc("Enable vectorization on interleaved memory accesses in a loop"));
246 
247 /// An interleave-group may need masking if it resides in a block that needs
248 /// predication, or in order to mask away gaps.
249 static cl::opt<bool> EnableMaskedInterleavedMemAccesses(
250     "enable-masked-interleaved-mem-accesses", cl::init(false), cl::Hidden,
251     cl::desc("Enable vectorization on masked interleaved memory accesses in a loop"));
252 
253 static cl::opt<unsigned> TinyTripCountInterleaveThreshold(
254     "tiny-trip-count-interleave-threshold", cl::init(128), cl::Hidden,
255     cl::desc("We don't interleave loops with a estimated constant trip count "
256              "below this number"));
257 
258 static cl::opt<unsigned> ForceTargetNumScalarRegs(
259     "force-target-num-scalar-regs", cl::init(0), cl::Hidden,
260     cl::desc("A flag that overrides the target's number of scalar registers."));
261 
262 static cl::opt<unsigned> ForceTargetNumVectorRegs(
263     "force-target-num-vector-regs", cl::init(0), cl::Hidden,
264     cl::desc("A flag that overrides the target's number of vector registers."));
265 
266 static cl::opt<unsigned> ForceTargetMaxScalarInterleaveFactor(
267     "force-target-max-scalar-interleave", cl::init(0), cl::Hidden,
268     cl::desc("A flag that overrides the target's max interleave factor for "
269              "scalar loops."));
270 
271 static cl::opt<unsigned> ForceTargetMaxVectorInterleaveFactor(
272     "force-target-max-vector-interleave", cl::init(0), cl::Hidden,
273     cl::desc("A flag that overrides the target's max interleave factor for "
274              "vectorized loops."));
275 
276 static cl::opt<unsigned> ForceTargetInstructionCost(
277     "force-target-instruction-cost", cl::init(0), cl::Hidden,
278     cl::desc("A flag that overrides the target's expected cost for "
279              "an instruction to a single constant value. Mostly "
280              "useful for getting consistent testing."));
281 
282 static cl::opt<bool> ForceTargetSupportsScalableVectors(
283     "force-target-supports-scalable-vectors", cl::init(false), cl::Hidden,
284     cl::desc(
285         "Pretend that scalable vectors are supported, even if the target does "
286         "not support them. This flag should only be used for testing."));
287 
288 static cl::opt<unsigned> SmallLoopCost(
289     "small-loop-cost", cl::init(20), cl::Hidden,
290     cl::desc(
291         "The cost of a loop that is considered 'small' by the interleaver."));
292 
293 static cl::opt<bool> LoopVectorizeWithBlockFrequency(
294     "loop-vectorize-with-block-frequency", cl::init(true), cl::Hidden,
295     cl::desc("Enable the use of the block frequency analysis to access PGO "
296              "heuristics minimizing code growth in cold regions and being more "
297              "aggressive in hot regions."));
298 
299 // Runtime interleave loops for load/store throughput.
300 static cl::opt<bool> EnableLoadStoreRuntimeInterleave(
301     "enable-loadstore-runtime-interleave", cl::init(true), cl::Hidden,
302     cl::desc(
303         "Enable runtime interleaving until load/store ports are saturated"));
304 
305 /// Interleave small loops with scalar reductions.
306 static cl::opt<bool> InterleaveSmallLoopScalarReduction(
307     "interleave-small-loop-scalar-reduction", cl::init(false), cl::Hidden,
308     cl::desc("Enable interleaving for loops with small iteration counts that "
309              "contain scalar reductions to expose ILP."));
310 
311 /// The number of stores in a loop that are allowed to need predication.
312 static cl::opt<unsigned> NumberOfStoresToPredicate(
313     "vectorize-num-stores-pred", cl::init(1), cl::Hidden,
314     cl::desc("Max number of stores to be predicated behind an if."));
315 
316 static cl::opt<bool> EnableIndVarRegisterHeur(
317     "enable-ind-var-reg-heur", cl::init(true), cl::Hidden,
318     cl::desc("Count the induction variable only once when interleaving"));
319 
320 static cl::opt<bool> EnableCondStoresVectorization(
321     "enable-cond-stores-vec", cl::init(true), cl::Hidden,
322     cl::desc("Enable if predication of stores during vectorization."));
323 
324 static cl::opt<unsigned> MaxNestedScalarReductionIC(
325     "max-nested-scalar-reduction-interleave", cl::init(2), cl::Hidden,
326     cl::desc("The maximum interleave count to use when interleaving a scalar "
327              "reduction in a nested loop."));
328 
329 static cl::opt<bool>
330     PreferInLoopReductions("prefer-inloop-reductions", cl::init(false),
331                            cl::Hidden,
332                            cl::desc("Prefer in-loop vector reductions, "
333                                     "overriding the targets preference."));
334 
335 cl::opt<bool> EnableStrictReductions(
336     "enable-strict-reductions", cl::init(false), cl::Hidden,
337     cl::desc("Enable the vectorisation of loops with in-order (strict) "
338              "FP reductions"));
339 
340 static cl::opt<bool> PreferPredicatedReductionSelect(
341     "prefer-predicated-reduction-select", cl::init(false), cl::Hidden,
342     cl::desc(
343         "Prefer predicating a reduction operation over an after loop select."));
344 
345 cl::opt<bool> EnableVPlanNativePath(
346     "enable-vplan-native-path", cl::init(false), cl::Hidden,
347     cl::desc("Enable VPlan-native vectorization path with "
348              "support for outer loop vectorization."));
349 
350 // FIXME: Remove this switch once we have divergence analysis. Currently we
351 // assume divergent non-backedge branches when this switch is true.
352 cl::opt<bool> EnableVPlanPredication(
353     "enable-vplan-predication", cl::init(false), cl::Hidden,
354     cl::desc("Enable VPlan-native vectorization path predicator with "
355              "support for outer loop vectorization."));
356 
357 // This flag enables the stress testing of the VPlan H-CFG construction in the
358 // VPlan-native vectorization path. It must be used in conjuction with
359 // -enable-vplan-native-path. -vplan-verify-hcfg can also be used to enable the
360 // verification of the H-CFGs built.
361 static cl::opt<bool> VPlanBuildStressTest(
362     "vplan-build-stress-test", cl::init(false), cl::Hidden,
363     cl::desc(
364         "Build VPlan for every supported loop nest in the function and bail "
365         "out right after the build (stress test the VPlan H-CFG construction "
366         "in the VPlan-native vectorization path)."));
367 
368 cl::opt<bool> llvm::EnableLoopInterleaving(
369     "interleave-loops", cl::init(true), cl::Hidden,
370     cl::desc("Enable loop interleaving in Loop vectorization passes"));
371 cl::opt<bool> llvm::EnableLoopVectorization(
372     "vectorize-loops", cl::init(true), cl::Hidden,
373     cl::desc("Run the Loop vectorization passes"));
374 
375 cl::opt<bool> PrintVPlansInDotFormat(
376     "vplan-print-in-dot-format", cl::init(false), cl::Hidden,
377     cl::desc("Use dot format instead of plain text when dumping VPlans"));
378 
379 /// A helper function that returns true if the given type is irregular. The
380 /// type is irregular if its allocated size doesn't equal the store size of an
381 /// element of the corresponding vector type.
382 static bool hasIrregularType(Type *Ty, const DataLayout &DL) {
383   // Determine if an array of N elements of type Ty is "bitcast compatible"
384   // with a <N x Ty> vector.
385   // This is only true if there is no padding between the array elements.
386   return DL.getTypeAllocSizeInBits(Ty) != DL.getTypeSizeInBits(Ty);
387 }
388 
389 /// A helper function that returns the reciprocal of the block probability of
390 /// predicated blocks. If we return X, we are assuming the predicated block
391 /// will execute once for every X iterations of the loop header.
392 ///
393 /// TODO: We should use actual block probability here, if available. Currently,
394 ///       we always assume predicated blocks have a 50% chance of executing.
395 static unsigned getReciprocalPredBlockProb() { return 2; }
396 
397 /// A helper function that returns an integer or floating-point constant with
398 /// value C.
399 static Constant *getSignedIntOrFpConstant(Type *Ty, int64_t C) {
400   return Ty->isIntegerTy() ? ConstantInt::getSigned(Ty, C)
401                            : ConstantFP::get(Ty, C);
402 }
403 
404 /// Returns "best known" trip count for the specified loop \p L as defined by
405 /// the following procedure:
406 ///   1) Returns exact trip count if it is known.
407 ///   2) Returns expected trip count according to profile data if any.
408 ///   3) Returns upper bound estimate if it is known.
409 ///   4) Returns None if all of the above failed.
410 static Optional<unsigned> getSmallBestKnownTC(ScalarEvolution &SE, Loop *L) {
411   // Check if exact trip count is known.
412   if (unsigned ExpectedTC = SE.getSmallConstantTripCount(L))
413     return ExpectedTC;
414 
415   // Check if there is an expected trip count available from profile data.
416   if (LoopVectorizeWithBlockFrequency)
417     if (auto EstimatedTC = getLoopEstimatedTripCount(L))
418       return EstimatedTC;
419 
420   // Check if upper bound estimate is known.
421   if (unsigned ExpectedTC = SE.getSmallConstantMaxTripCount(L))
422     return ExpectedTC;
423 
424   return None;
425 }
426 
427 // Forward declare GeneratedRTChecks.
428 class GeneratedRTChecks;
429 
430 namespace llvm {
431 
432 /// InnerLoopVectorizer vectorizes loops which contain only one basic
433 /// block to a specified vectorization factor (VF).
434 /// This class performs the widening of scalars into vectors, or multiple
435 /// scalars. This class also implements the following features:
436 /// * It inserts an epilogue loop for handling loops that don't have iteration
437 ///   counts that are known to be a multiple of the vectorization factor.
438 /// * It handles the code generation for reduction variables.
439 /// * Scalarization (implementation using scalars) of un-vectorizable
440 ///   instructions.
441 /// InnerLoopVectorizer does not perform any vectorization-legality
442 /// checks, and relies on the caller to check for the different legality
443 /// aspects. The InnerLoopVectorizer relies on the
444 /// LoopVectorizationLegality class to provide information about the induction
445 /// and reduction variables that were found to a given vectorization factor.
446 class InnerLoopVectorizer {
447 public:
448   InnerLoopVectorizer(Loop *OrigLoop, PredicatedScalarEvolution &PSE,
449                       LoopInfo *LI, DominatorTree *DT,
450                       const TargetLibraryInfo *TLI,
451                       const TargetTransformInfo *TTI, AssumptionCache *AC,
452                       OptimizationRemarkEmitter *ORE, ElementCount VecWidth,
453                       unsigned UnrollFactor, LoopVectorizationLegality *LVL,
454                       LoopVectorizationCostModel *CM, BlockFrequencyInfo *BFI,
455                       ProfileSummaryInfo *PSI, GeneratedRTChecks &RTChecks)
456       : OrigLoop(OrigLoop), PSE(PSE), LI(LI), DT(DT), TLI(TLI), TTI(TTI),
457         AC(AC), ORE(ORE), VF(VecWidth), UF(UnrollFactor),
458         Builder(PSE.getSE()->getContext()), Legal(LVL), Cost(CM), BFI(BFI),
459         PSI(PSI), RTChecks(RTChecks) {
460     // Query this against the original loop and save it here because the profile
461     // of the original loop header may change as the transformation happens.
462     OptForSizeBasedOnProfile = llvm::shouldOptimizeForSize(
463         OrigLoop->getHeader(), PSI, BFI, PGSOQueryType::IRPass);
464   }
465 
466   virtual ~InnerLoopVectorizer() = default;
467 
468   /// Create a new empty loop that will contain vectorized instructions later
469   /// on, while the old loop will be used as the scalar remainder. Control flow
470   /// is generated around the vectorized (and scalar epilogue) loops consisting
471   /// of various checks and bypasses. Return the pre-header block of the new
472   /// loop.
473   /// In the case of epilogue vectorization, this function is overriden to
474   /// handle the more complex control flow around the loops.
475   virtual BasicBlock *createVectorizedLoopSkeleton();
476 
477   /// Widen a single instruction within the innermost loop.
478   void widenInstruction(Instruction &I, VPValue *Def, VPUser &Operands,
479                         VPTransformState &State);
480 
481   /// Widen a single call instruction within the innermost loop.
482   void widenCallInstruction(CallInst &I, VPValue *Def, VPUser &ArgOperands,
483                             VPTransformState &State);
484 
485   /// Widen a single select instruction within the innermost loop.
486   void widenSelectInstruction(SelectInst &I, VPValue *VPDef, VPUser &Operands,
487                               bool InvariantCond, VPTransformState &State);
488 
489   /// Fix the vectorized code, taking care of header phi's, live-outs, and more.
490   void fixVectorizedLoop(VPTransformState &State);
491 
492   // Return true if any runtime check is added.
493   bool areSafetyChecksAdded() { return AddedSafetyChecks; }
494 
495   /// A type for vectorized values in the new loop. Each value from the
496   /// original loop, when vectorized, is represented by UF vector values in the
497   /// new unrolled loop, where UF is the unroll factor.
498   using VectorParts = SmallVector<Value *, 2>;
499 
500   /// Vectorize a single GetElementPtrInst based on information gathered and
501   /// decisions taken during planning.
502   void widenGEP(GetElementPtrInst *GEP, VPValue *VPDef, VPUser &Indices,
503                 unsigned UF, ElementCount VF, bool IsPtrLoopInvariant,
504                 SmallBitVector &IsIndexLoopInvariant, VPTransformState &State);
505 
506   /// Vectorize a single first-order recurrence or pointer induction PHINode in
507   /// a block. This method handles the induction variable canonicalization. It
508   /// supports both VF = 1 for unrolled loops and arbitrary length vectors.
509   void widenPHIInstruction(Instruction *PN, VPWidenPHIRecipe *PhiR,
510                            VPTransformState &State);
511 
512   /// A helper function to scalarize a single Instruction in the innermost loop.
513   /// Generates a sequence of scalar instances for each lane between \p MinLane
514   /// and \p MaxLane, times each part between \p MinPart and \p MaxPart,
515   /// inclusive. Uses the VPValue operands from \p Operands instead of \p
516   /// Instr's operands.
517   void scalarizeInstruction(Instruction *Instr, VPValue *Def, VPUser &Operands,
518                             const VPIteration &Instance, bool IfPredicateInstr,
519                             VPTransformState &State);
520 
521   /// Widen an integer or floating-point induction variable \p IV. If \p Trunc
522   /// is provided, the integer induction variable will first be truncated to
523   /// the corresponding type.
524   void widenIntOrFpInduction(PHINode *IV, Value *Start, TruncInst *Trunc,
525                              VPValue *Def, VPValue *CastDef,
526                              VPTransformState &State);
527 
528   /// Construct the vector value of a scalarized value \p V one lane at a time.
529   void packScalarIntoVectorValue(VPValue *Def, const VPIteration &Instance,
530                                  VPTransformState &State);
531 
532   /// Try to vectorize interleaved access group \p Group with the base address
533   /// given in \p Addr, optionally masking the vector operations if \p
534   /// BlockInMask is non-null. Use \p State to translate given VPValues to IR
535   /// values in the vectorized loop.
536   void vectorizeInterleaveGroup(const InterleaveGroup<Instruction> *Group,
537                                 ArrayRef<VPValue *> VPDefs,
538                                 VPTransformState &State, VPValue *Addr,
539                                 ArrayRef<VPValue *> StoredValues,
540                                 VPValue *BlockInMask = nullptr);
541 
542   /// Vectorize Load and Store instructions with the base address given in \p
543   /// Addr, optionally masking the vector operations if \p BlockInMask is
544   /// non-null. Use \p State to translate given VPValues to IR values in the
545   /// vectorized loop.
546   void vectorizeMemoryInstruction(Instruction *Instr, VPTransformState &State,
547                                   VPValue *Def, VPValue *Addr,
548                                   VPValue *StoredValue, VPValue *BlockInMask);
549 
550   /// Set the debug location in the builder \p Ptr using the debug location in
551   /// \p V. If \p Ptr is None then it uses the class member's Builder.
552   void setDebugLocFromInst(const Value *V,
553                            Optional<IRBuilder<> *> CustomBuilder = None);
554 
555   /// Fix the non-induction PHIs in the OrigPHIsToFix vector.
556   void fixNonInductionPHIs(VPTransformState &State);
557 
558   /// Returns true if the reordering of FP operations is not allowed, but we are
559   /// able to vectorize with strict in-order reductions for the given RdxDesc.
560   bool useOrderedReductions(RecurrenceDescriptor &RdxDesc);
561 
562   /// Create a broadcast instruction. This method generates a broadcast
563   /// instruction (shuffle) for loop invariant values and for the induction
564   /// value. If this is the induction variable then we extend it to N, N+1, ...
565   /// this is needed because each iteration in the loop corresponds to a SIMD
566   /// element.
567   virtual Value *getBroadcastInstrs(Value *V);
568 
569 protected:
570   friend class LoopVectorizationPlanner;
571 
572   /// A small list of PHINodes.
573   using PhiVector = SmallVector<PHINode *, 4>;
574 
575   /// A type for scalarized values in the new loop. Each value from the
576   /// original loop, when scalarized, is represented by UF x VF scalar values
577   /// in the new unrolled loop, where UF is the unroll factor and VF is the
578   /// vectorization factor.
579   using ScalarParts = SmallVector<SmallVector<Value *, 4>, 2>;
580 
581   /// Set up the values of the IVs correctly when exiting the vector loop.
582   void fixupIVUsers(PHINode *OrigPhi, const InductionDescriptor &II,
583                     Value *CountRoundDown, Value *EndValue,
584                     BasicBlock *MiddleBlock);
585 
586   /// Create a new induction variable inside L.
587   PHINode *createInductionVariable(Loop *L, Value *Start, Value *End,
588                                    Value *Step, Instruction *DL);
589 
590   /// Handle all cross-iteration phis in the header.
591   void fixCrossIterationPHIs(VPTransformState &State);
592 
593   /// Fix a first-order recurrence. This is the second phase of vectorizing
594   /// this phi node.
595   void fixFirstOrderRecurrence(VPWidenPHIRecipe *PhiR, VPTransformState &State);
596 
597   /// Fix a reduction cross-iteration phi. This is the second phase of
598   /// vectorizing this phi node.
599   void fixReduction(VPReductionPHIRecipe *Phi, VPTransformState &State);
600 
601   /// Clear NSW/NUW flags from reduction instructions if necessary.
602   void clearReductionWrapFlags(const RecurrenceDescriptor &RdxDesc,
603                                VPTransformState &State);
604 
605   /// Fixup the LCSSA phi nodes in the unique exit block.  This simply
606   /// means we need to add the appropriate incoming value from the middle
607   /// block as exiting edges from the scalar epilogue loop (if present) are
608   /// already in place, and we exit the vector loop exclusively to the middle
609   /// block.
610   void fixLCSSAPHIs(VPTransformState &State);
611 
612   /// Iteratively sink the scalarized operands of a predicated instruction into
613   /// the block that was created for it.
614   void sinkScalarOperands(Instruction *PredInst);
615 
616   /// Shrinks vector element sizes to the smallest bitwidth they can be legally
617   /// represented as.
618   void truncateToMinimalBitwidths(VPTransformState &State);
619 
620   /// This function adds
621   /// (StartIdx * Step, (StartIdx + 1) * Step, (StartIdx + 2) * Step, ...)
622   /// to each vector element of Val. The sequence starts at StartIndex.
623   /// \p Opcode is relevant for FP induction variable.
624   virtual Value *getStepVector(Value *Val, int StartIdx, Value *Step,
625                                Instruction::BinaryOps Opcode =
626                                Instruction::BinaryOpsEnd);
627 
628   /// Compute scalar induction steps. \p ScalarIV is the scalar induction
629   /// variable on which to base the steps, \p Step is the size of the step, and
630   /// \p EntryVal is the value from the original loop that maps to the steps.
631   /// Note that \p EntryVal doesn't have to be an induction variable - it
632   /// can also be a truncate instruction.
633   void buildScalarSteps(Value *ScalarIV, Value *Step, Instruction *EntryVal,
634                         const InductionDescriptor &ID, VPValue *Def,
635                         VPValue *CastDef, VPTransformState &State);
636 
637   /// Create a vector induction phi node based on an existing scalar one. \p
638   /// EntryVal is the value from the original loop that maps to the vector phi
639   /// node, and \p Step is the loop-invariant step. If \p EntryVal is a
640   /// truncate instruction, instead of widening the original IV, we widen a
641   /// version of the IV truncated to \p EntryVal's type.
642   void createVectorIntOrFpInductionPHI(const InductionDescriptor &II,
643                                        Value *Step, Value *Start,
644                                        Instruction *EntryVal, VPValue *Def,
645                                        VPValue *CastDef,
646                                        VPTransformState &State);
647 
648   /// Returns true if an instruction \p I should be scalarized instead of
649   /// vectorized for the chosen vectorization factor.
650   bool shouldScalarizeInstruction(Instruction *I) const;
651 
652   /// Returns true if we should generate a scalar version of \p IV.
653   bool needsScalarInduction(Instruction *IV) const;
654 
655   /// If there is a cast involved in the induction variable \p ID, which should
656   /// be ignored in the vectorized loop body, this function records the
657   /// VectorLoopValue of the respective Phi also as the VectorLoopValue of the
658   /// cast. We had already proved that the casted Phi is equal to the uncasted
659   /// Phi in the vectorized loop (under a runtime guard), and therefore
660   /// there is no need to vectorize the cast - the same value can be used in the
661   /// vector loop for both the Phi and the cast.
662   /// If \p VectorLoopValue is a scalarized value, \p Lane is also specified,
663   /// Otherwise, \p VectorLoopValue is a widened/vectorized value.
664   ///
665   /// \p EntryVal is the value from the original loop that maps to the vector
666   /// phi node and is used to distinguish what is the IV currently being
667   /// processed - original one (if \p EntryVal is a phi corresponding to the
668   /// original IV) or the "newly-created" one based on the proof mentioned above
669   /// (see also buildScalarSteps() and createVectorIntOrFPInductionPHI()). In the
670   /// latter case \p EntryVal is a TruncInst and we must not record anything for
671   /// that IV, but it's error-prone to expect callers of this routine to care
672   /// about that, hence this explicit parameter.
673   void recordVectorLoopValueForInductionCast(
674       const InductionDescriptor &ID, const Instruction *EntryVal,
675       Value *VectorLoopValue, VPValue *CastDef, VPTransformState &State,
676       unsigned Part, unsigned Lane = UINT_MAX);
677 
678   /// Generate a shuffle sequence that will reverse the vector Vec.
679   virtual Value *reverseVector(Value *Vec);
680 
681   /// Returns (and creates if needed) the original loop trip count.
682   Value *getOrCreateTripCount(Loop *NewLoop);
683 
684   /// Returns (and creates if needed) the trip count of the widened loop.
685   Value *getOrCreateVectorTripCount(Loop *NewLoop);
686 
687   /// Returns a bitcasted value to the requested vector type.
688   /// Also handles bitcasts of vector<float> <-> vector<pointer> types.
689   Value *createBitOrPointerCast(Value *V, VectorType *DstVTy,
690                                 const DataLayout &DL);
691 
692   /// Emit a bypass check to see if the vector trip count is zero, including if
693   /// it overflows.
694   void emitMinimumIterationCountCheck(Loop *L, BasicBlock *Bypass);
695 
696   /// Emit a bypass check to see if all of the SCEV assumptions we've
697   /// had to make are correct. Returns the block containing the checks or
698   /// nullptr if no checks have been added.
699   BasicBlock *emitSCEVChecks(Loop *L, BasicBlock *Bypass);
700 
701   /// Emit bypass checks to check any memory assumptions we may have made.
702   /// Returns the block containing the checks or nullptr if no checks have been
703   /// added.
704   BasicBlock *emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass);
705 
706   /// Compute the transformed value of Index at offset StartValue using step
707   /// StepValue.
708   /// For integer induction, returns StartValue + Index * StepValue.
709   /// For pointer induction, returns StartValue[Index * StepValue].
710   /// FIXME: The newly created binary instructions should contain nsw/nuw
711   /// flags, which can be found from the original scalar operations.
712   Value *emitTransformedIndex(IRBuilder<> &B, Value *Index, ScalarEvolution *SE,
713                               const DataLayout &DL,
714                               const InductionDescriptor &ID) const;
715 
716   /// Emit basic blocks (prefixed with \p Prefix) for the iteration check,
717   /// vector loop preheader, middle block and scalar preheader. Also
718   /// allocate a loop object for the new vector loop and return it.
719   Loop *createVectorLoopSkeleton(StringRef Prefix);
720 
721   /// Create new phi nodes for the induction variables to resume iteration count
722   /// in the scalar epilogue, from where the vectorized loop left off (given by
723   /// \p VectorTripCount).
724   /// In cases where the loop skeleton is more complicated (eg. epilogue
725   /// vectorization) and the resume values can come from an additional bypass
726   /// block, the \p AdditionalBypass pair provides information about the bypass
727   /// block and the end value on the edge from bypass to this loop.
728   void createInductionResumeValues(
729       Loop *L, Value *VectorTripCount,
730       std::pair<BasicBlock *, Value *> AdditionalBypass = {nullptr, nullptr});
731 
732   /// Complete the loop skeleton by adding debug MDs, creating appropriate
733   /// conditional branches in the middle block, preparing the builder and
734   /// running the verifier. Take in the vector loop \p L as argument, and return
735   /// the preheader of the completed vector loop.
736   BasicBlock *completeLoopSkeleton(Loop *L, MDNode *OrigLoopID);
737 
738   /// Add additional metadata to \p To that was not present on \p Orig.
739   ///
740   /// Currently this is used to add the noalias annotations based on the
741   /// inserted memchecks.  Use this for instructions that are *cloned* into the
742   /// vector loop.
743   void addNewMetadata(Instruction *To, const Instruction *Orig);
744 
745   /// Add metadata from one instruction to another.
746   ///
747   /// This includes both the original MDs from \p From and additional ones (\see
748   /// addNewMetadata).  Use this for *newly created* instructions in the vector
749   /// loop.
750   void addMetadata(Instruction *To, Instruction *From);
751 
752   /// Similar to the previous function but it adds the metadata to a
753   /// vector of instructions.
754   void addMetadata(ArrayRef<Value *> To, Instruction *From);
755 
756   /// Allow subclasses to override and print debug traces before/after vplan
757   /// execution, when trace information is requested.
758   virtual void printDebugTracesAtStart(){};
759   virtual void printDebugTracesAtEnd(){};
760 
761   /// The original loop.
762   Loop *OrigLoop;
763 
764   /// A wrapper around ScalarEvolution used to add runtime SCEV checks. Applies
765   /// dynamic knowledge to simplify SCEV expressions and converts them to a
766   /// more usable form.
767   PredicatedScalarEvolution &PSE;
768 
769   /// Loop Info.
770   LoopInfo *LI;
771 
772   /// Dominator Tree.
773   DominatorTree *DT;
774 
775   /// Alias Analysis.
776   AAResults *AA;
777 
778   /// Target Library Info.
779   const TargetLibraryInfo *TLI;
780 
781   /// Target Transform Info.
782   const TargetTransformInfo *TTI;
783 
784   /// Assumption Cache.
785   AssumptionCache *AC;
786 
787   /// Interface to emit optimization remarks.
788   OptimizationRemarkEmitter *ORE;
789 
790   /// LoopVersioning.  It's only set up (non-null) if memchecks were
791   /// used.
792   ///
793   /// This is currently only used to add no-alias metadata based on the
794   /// memchecks.  The actually versioning is performed manually.
795   std::unique_ptr<LoopVersioning> LVer;
796 
797   /// The vectorization SIMD factor to use. Each vector will have this many
798   /// vector elements.
799   ElementCount VF;
800 
801   /// The vectorization unroll factor to use. Each scalar is vectorized to this
802   /// many different vector instructions.
803   unsigned UF;
804 
805   /// The builder that we use
806   IRBuilder<> Builder;
807 
808   // --- Vectorization state ---
809 
810   /// The vector-loop preheader.
811   BasicBlock *LoopVectorPreHeader;
812 
813   /// The scalar-loop preheader.
814   BasicBlock *LoopScalarPreHeader;
815 
816   /// Middle Block between the vector and the scalar.
817   BasicBlock *LoopMiddleBlock;
818 
819   /// The unique ExitBlock of the scalar loop if one exists.  Note that
820   /// there can be multiple exiting edges reaching this block.
821   BasicBlock *LoopExitBlock;
822 
823   /// The vector loop body.
824   BasicBlock *LoopVectorBody;
825 
826   /// The scalar loop body.
827   BasicBlock *LoopScalarBody;
828 
829   /// A list of all bypass blocks. The first block is the entry of the loop.
830   SmallVector<BasicBlock *, 4> LoopBypassBlocks;
831 
832   /// The new Induction variable which was added to the new block.
833   PHINode *Induction = nullptr;
834 
835   /// The induction variable of the old basic block.
836   PHINode *OldInduction = nullptr;
837 
838   /// Store instructions that were predicated.
839   SmallVector<Instruction *, 4> PredicatedInstructions;
840 
841   /// Trip count of the original loop.
842   Value *TripCount = nullptr;
843 
844   /// Trip count of the widened loop (TripCount - TripCount % (VF*UF))
845   Value *VectorTripCount = nullptr;
846 
847   /// The legality analysis.
848   LoopVectorizationLegality *Legal;
849 
850   /// The profitablity analysis.
851   LoopVectorizationCostModel *Cost;
852 
853   // Record whether runtime checks are added.
854   bool AddedSafetyChecks = false;
855 
856   // Holds the end values for each induction variable. We save the end values
857   // so we can later fix-up the external users of the induction variables.
858   DenseMap<PHINode *, Value *> IVEndValues;
859 
860   // Vector of original scalar PHIs whose corresponding widened PHIs need to be
861   // fixed up at the end of vector code generation.
862   SmallVector<PHINode *, 8> OrigPHIsToFix;
863 
864   /// BFI and PSI are used to check for profile guided size optimizations.
865   BlockFrequencyInfo *BFI;
866   ProfileSummaryInfo *PSI;
867 
868   // Whether this loop should be optimized for size based on profile guided size
869   // optimizatios.
870   bool OptForSizeBasedOnProfile;
871 
872   /// Structure to hold information about generated runtime checks, responsible
873   /// for cleaning the checks, if vectorization turns out unprofitable.
874   GeneratedRTChecks &RTChecks;
875 };
876 
877 class InnerLoopUnroller : public InnerLoopVectorizer {
878 public:
879   InnerLoopUnroller(Loop *OrigLoop, PredicatedScalarEvolution &PSE,
880                     LoopInfo *LI, DominatorTree *DT,
881                     const TargetLibraryInfo *TLI,
882                     const TargetTransformInfo *TTI, AssumptionCache *AC,
883                     OptimizationRemarkEmitter *ORE, unsigned UnrollFactor,
884                     LoopVectorizationLegality *LVL,
885                     LoopVectorizationCostModel *CM, BlockFrequencyInfo *BFI,
886                     ProfileSummaryInfo *PSI, GeneratedRTChecks &Check)
887       : InnerLoopVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
888                             ElementCount::getFixed(1), UnrollFactor, LVL, CM,
889                             BFI, PSI, Check) {}
890 
891 private:
892   Value *getBroadcastInstrs(Value *V) override;
893   Value *getStepVector(Value *Val, int StartIdx, Value *Step,
894                        Instruction::BinaryOps Opcode =
895                        Instruction::BinaryOpsEnd) override;
896   Value *reverseVector(Value *Vec) override;
897 };
898 
899 /// Encapsulate information regarding vectorization of a loop and its epilogue.
900 /// This information is meant to be updated and used across two stages of
901 /// epilogue vectorization.
902 struct EpilogueLoopVectorizationInfo {
903   ElementCount MainLoopVF = ElementCount::getFixed(0);
904   unsigned MainLoopUF = 0;
905   ElementCount EpilogueVF = ElementCount::getFixed(0);
906   unsigned EpilogueUF = 0;
907   BasicBlock *MainLoopIterationCountCheck = nullptr;
908   BasicBlock *EpilogueIterationCountCheck = nullptr;
909   BasicBlock *SCEVSafetyCheck = nullptr;
910   BasicBlock *MemSafetyCheck = nullptr;
911   Value *TripCount = nullptr;
912   Value *VectorTripCount = nullptr;
913 
914   EpilogueLoopVectorizationInfo(unsigned MVF, unsigned MUF, unsigned EVF,
915                                 unsigned EUF)
916       : MainLoopVF(ElementCount::getFixed(MVF)), MainLoopUF(MUF),
917         EpilogueVF(ElementCount::getFixed(EVF)), EpilogueUF(EUF) {
918     assert(EUF == 1 &&
919            "A high UF for the epilogue loop is likely not beneficial.");
920   }
921 };
922 
923 /// An extension of the inner loop vectorizer that creates a skeleton for a
924 /// vectorized loop that has its epilogue (residual) also vectorized.
925 /// The idea is to run the vplan on a given loop twice, firstly to setup the
926 /// skeleton and vectorize the main loop, and secondly to complete the skeleton
927 /// from the first step and vectorize the epilogue.  This is achieved by
928 /// deriving two concrete strategy classes from this base class and invoking
929 /// them in succession from the loop vectorizer planner.
930 class InnerLoopAndEpilogueVectorizer : public InnerLoopVectorizer {
931 public:
932   InnerLoopAndEpilogueVectorizer(
933       Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI,
934       DominatorTree *DT, const TargetLibraryInfo *TLI,
935       const TargetTransformInfo *TTI, AssumptionCache *AC,
936       OptimizationRemarkEmitter *ORE, EpilogueLoopVectorizationInfo &EPI,
937       LoopVectorizationLegality *LVL, llvm::LoopVectorizationCostModel *CM,
938       BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI,
939       GeneratedRTChecks &Checks)
940       : InnerLoopVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
941                             EPI.MainLoopVF, EPI.MainLoopUF, LVL, CM, BFI, PSI,
942                             Checks),
943         EPI(EPI) {}
944 
945   // Override this function to handle the more complex control flow around the
946   // three loops.
947   BasicBlock *createVectorizedLoopSkeleton() final override {
948     return createEpilogueVectorizedLoopSkeleton();
949   }
950 
951   /// The interface for creating a vectorized skeleton using one of two
952   /// different strategies, each corresponding to one execution of the vplan
953   /// as described above.
954   virtual BasicBlock *createEpilogueVectorizedLoopSkeleton() = 0;
955 
956   /// Holds and updates state information required to vectorize the main loop
957   /// and its epilogue in two separate passes. This setup helps us avoid
958   /// regenerating and recomputing runtime safety checks. It also helps us to
959   /// shorten the iteration-count-check path length for the cases where the
960   /// iteration count of the loop is so small that the main vector loop is
961   /// completely skipped.
962   EpilogueLoopVectorizationInfo &EPI;
963 };
964 
965 /// A specialized derived class of inner loop vectorizer that performs
966 /// vectorization of *main* loops in the process of vectorizing loops and their
967 /// epilogues.
968 class EpilogueVectorizerMainLoop : public InnerLoopAndEpilogueVectorizer {
969 public:
970   EpilogueVectorizerMainLoop(
971       Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI,
972       DominatorTree *DT, const TargetLibraryInfo *TLI,
973       const TargetTransformInfo *TTI, AssumptionCache *AC,
974       OptimizationRemarkEmitter *ORE, EpilogueLoopVectorizationInfo &EPI,
975       LoopVectorizationLegality *LVL, llvm::LoopVectorizationCostModel *CM,
976       BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI,
977       GeneratedRTChecks &Check)
978       : InnerLoopAndEpilogueVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
979                                        EPI, LVL, CM, BFI, PSI, Check) {}
980   /// Implements the interface for creating a vectorized skeleton using the
981   /// *main loop* strategy (ie the first pass of vplan execution).
982   BasicBlock *createEpilogueVectorizedLoopSkeleton() final override;
983 
984 protected:
985   /// Emits an iteration count bypass check once for the main loop (when \p
986   /// ForEpilogue is false) and once for the epilogue loop (when \p
987   /// ForEpilogue is true).
988   BasicBlock *emitMinimumIterationCountCheck(Loop *L, BasicBlock *Bypass,
989                                              bool ForEpilogue);
990   void printDebugTracesAtStart() override;
991   void printDebugTracesAtEnd() override;
992 };
993 
994 // A specialized derived class of inner loop vectorizer that performs
995 // vectorization of *epilogue* loops in the process of vectorizing loops and
996 // their epilogues.
997 class EpilogueVectorizerEpilogueLoop : public InnerLoopAndEpilogueVectorizer {
998 public:
999   EpilogueVectorizerEpilogueLoop(
1000       Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI,
1001       DominatorTree *DT, const TargetLibraryInfo *TLI,
1002       const TargetTransformInfo *TTI, AssumptionCache *AC,
1003       OptimizationRemarkEmitter *ORE, EpilogueLoopVectorizationInfo &EPI,
1004       LoopVectorizationLegality *LVL, llvm::LoopVectorizationCostModel *CM,
1005       BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI,
1006       GeneratedRTChecks &Checks)
1007       : InnerLoopAndEpilogueVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
1008                                        EPI, LVL, CM, BFI, PSI, Checks) {}
1009   /// Implements the interface for creating a vectorized skeleton using the
1010   /// *epilogue loop* strategy (ie the second pass of vplan execution).
1011   BasicBlock *createEpilogueVectorizedLoopSkeleton() final override;
1012 
1013 protected:
1014   /// Emits an iteration count bypass check after the main vector loop has
1015   /// finished to see if there are any iterations left to execute by either
1016   /// the vector epilogue or the scalar epilogue.
1017   BasicBlock *emitMinimumVectorEpilogueIterCountCheck(Loop *L,
1018                                                       BasicBlock *Bypass,
1019                                                       BasicBlock *Insert);
1020   void printDebugTracesAtStart() override;
1021   void printDebugTracesAtEnd() override;
1022 };
1023 } // end namespace llvm
1024 
1025 /// Look for a meaningful debug location on the instruction or it's
1026 /// operands.
1027 static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
1028   if (!I)
1029     return I;
1030 
1031   DebugLoc Empty;
1032   if (I->getDebugLoc() != Empty)
1033     return I;
1034 
1035   for (Use &Op : I->operands()) {
1036     if (Instruction *OpInst = dyn_cast<Instruction>(Op))
1037       if (OpInst->getDebugLoc() != Empty)
1038         return OpInst;
1039   }
1040 
1041   return I;
1042 }
1043 
1044 void InnerLoopVectorizer::setDebugLocFromInst(
1045     const Value *V, Optional<IRBuilder<> *> CustomBuilder) {
1046   IRBuilder<> *B = (CustomBuilder == None) ? &Builder : *CustomBuilder;
1047   if (const Instruction *Inst = dyn_cast_or_null<Instruction>(V)) {
1048     const DILocation *DIL = Inst->getDebugLoc();
1049 
1050     // When a FSDiscriminator is enabled, we don't need to add the multiply
1051     // factors to the discriminators.
1052     if (DIL && Inst->getFunction()->isDebugInfoForProfiling() &&
1053         !isa<DbgInfoIntrinsic>(Inst) && !EnableFSDiscriminator) {
1054       // FIXME: For scalable vectors, assume vscale=1.
1055       auto NewDIL =
1056           DIL->cloneByMultiplyingDuplicationFactor(UF * VF.getKnownMinValue());
1057       if (NewDIL)
1058         B->SetCurrentDebugLocation(NewDIL.getValue());
1059       else
1060         LLVM_DEBUG(dbgs()
1061                    << "Failed to create new discriminator: "
1062                    << DIL->getFilename() << " Line: " << DIL->getLine());
1063     } else
1064       B->SetCurrentDebugLocation(DIL);
1065   } else
1066     B->SetCurrentDebugLocation(DebugLoc());
1067 }
1068 
1069 /// Write a \p DebugMsg about vectorization to the debug output stream. If \p I
1070 /// is passed, the message relates to that particular instruction.
1071 #ifndef NDEBUG
1072 static void debugVectorizationMessage(const StringRef Prefix,
1073                                       const StringRef DebugMsg,
1074                                       Instruction *I) {
1075   dbgs() << "LV: " << Prefix << DebugMsg;
1076   if (I != nullptr)
1077     dbgs() << " " << *I;
1078   else
1079     dbgs() << '.';
1080   dbgs() << '\n';
1081 }
1082 #endif
1083 
1084 /// Create an analysis remark that explains why vectorization failed
1085 ///
1086 /// \p PassName is the name of the pass (e.g. can be AlwaysPrint).  \p
1087 /// RemarkName is the identifier for the remark.  If \p I is passed it is an
1088 /// instruction that prevents vectorization.  Otherwise \p TheLoop is used for
1089 /// the location of the remark.  \return the remark object that can be
1090 /// streamed to.
1091 static OptimizationRemarkAnalysis createLVAnalysis(const char *PassName,
1092     StringRef RemarkName, Loop *TheLoop, Instruction *I) {
1093   Value *CodeRegion = TheLoop->getHeader();
1094   DebugLoc DL = TheLoop->getStartLoc();
1095 
1096   if (I) {
1097     CodeRegion = I->getParent();
1098     // If there is no debug location attached to the instruction, revert back to
1099     // using the loop's.
1100     if (I->getDebugLoc())
1101       DL = I->getDebugLoc();
1102   }
1103 
1104   return OptimizationRemarkAnalysis(PassName, RemarkName, DL, CodeRegion);
1105 }
1106 
1107 /// Return a value for Step multiplied by VF.
1108 static Value *createStepForVF(IRBuilder<> &B, Constant *Step, ElementCount VF) {
1109   assert(isa<ConstantInt>(Step) && "Expected an integer step");
1110   Constant *StepVal = ConstantInt::get(
1111       Step->getType(),
1112       cast<ConstantInt>(Step)->getSExtValue() * VF.getKnownMinValue());
1113   return VF.isScalable() ? B.CreateVScale(StepVal) : StepVal;
1114 }
1115 
1116 namespace llvm {
1117 
1118 /// Return the runtime value for VF.
1119 Value *getRuntimeVF(IRBuilder<> &B, Type *Ty, ElementCount VF) {
1120   Constant *EC = ConstantInt::get(Ty, VF.getKnownMinValue());
1121   return VF.isScalable() ? B.CreateVScale(EC) : EC;
1122 }
1123 
1124 void reportVectorizationFailure(const StringRef DebugMsg,
1125                                 const StringRef OREMsg, const StringRef ORETag,
1126                                 OptimizationRemarkEmitter *ORE, Loop *TheLoop,
1127                                 Instruction *I) {
1128   LLVM_DEBUG(debugVectorizationMessage("Not vectorizing: ", DebugMsg, I));
1129   LoopVectorizeHints Hints(TheLoop, true /* doesn't matter */, *ORE);
1130   ORE->emit(
1131       createLVAnalysis(Hints.vectorizeAnalysisPassName(), ORETag, TheLoop, I)
1132       << "loop not vectorized: " << OREMsg);
1133 }
1134 
1135 void reportVectorizationInfo(const StringRef Msg, const StringRef ORETag,
1136                              OptimizationRemarkEmitter *ORE, Loop *TheLoop,
1137                              Instruction *I) {
1138   LLVM_DEBUG(debugVectorizationMessage("", Msg, I));
1139   LoopVectorizeHints Hints(TheLoop, true /* doesn't matter */, *ORE);
1140   ORE->emit(
1141       createLVAnalysis(Hints.vectorizeAnalysisPassName(), ORETag, TheLoop, I)
1142       << Msg);
1143 }
1144 
1145 } // end namespace llvm
1146 
1147 #ifndef NDEBUG
1148 /// \return string containing a file name and a line # for the given loop.
1149 static std::string getDebugLocString(const Loop *L) {
1150   std::string Result;
1151   if (L) {
1152     raw_string_ostream OS(Result);
1153     if (const DebugLoc LoopDbgLoc = L->getStartLoc())
1154       LoopDbgLoc.print(OS);
1155     else
1156       // Just print the module name.
1157       OS << L->getHeader()->getParent()->getParent()->getModuleIdentifier();
1158     OS.flush();
1159   }
1160   return Result;
1161 }
1162 #endif
1163 
1164 void InnerLoopVectorizer::addNewMetadata(Instruction *To,
1165                                          const Instruction *Orig) {
1166   // If the loop was versioned with memchecks, add the corresponding no-alias
1167   // metadata.
1168   if (LVer && (isa<LoadInst>(Orig) || isa<StoreInst>(Orig)))
1169     LVer->annotateInstWithNoAlias(To, Orig);
1170 }
1171 
1172 void InnerLoopVectorizer::addMetadata(Instruction *To,
1173                                       Instruction *From) {
1174   propagateMetadata(To, From);
1175   addNewMetadata(To, From);
1176 }
1177 
1178 void InnerLoopVectorizer::addMetadata(ArrayRef<Value *> To,
1179                                       Instruction *From) {
1180   for (Value *V : To) {
1181     if (Instruction *I = dyn_cast<Instruction>(V))
1182       addMetadata(I, From);
1183   }
1184 }
1185 
1186 namespace llvm {
1187 
1188 // Loop vectorization cost-model hints how the scalar epilogue loop should be
1189 // lowered.
1190 enum ScalarEpilogueLowering {
1191 
1192   // The default: allowing scalar epilogues.
1193   CM_ScalarEpilogueAllowed,
1194 
1195   // Vectorization with OptForSize: don't allow epilogues.
1196   CM_ScalarEpilogueNotAllowedOptSize,
1197 
1198   // A special case of vectorisation with OptForSize: loops with a very small
1199   // trip count are considered for vectorization under OptForSize, thereby
1200   // making sure the cost of their loop body is dominant, free of runtime
1201   // guards and scalar iteration overheads.
1202   CM_ScalarEpilogueNotAllowedLowTripLoop,
1203 
1204   // Loop hint predicate indicating an epilogue is undesired.
1205   CM_ScalarEpilogueNotNeededUsePredicate,
1206 
1207   // Directive indicating we must either tail fold or not vectorize
1208   CM_ScalarEpilogueNotAllowedUsePredicate
1209 };
1210 
1211 /// ElementCountComparator creates a total ordering for ElementCount
1212 /// for the purposes of using it in a set structure.
1213 struct ElementCountComparator {
1214   bool operator()(const ElementCount &LHS, const ElementCount &RHS) const {
1215     return std::make_tuple(LHS.isScalable(), LHS.getKnownMinValue()) <
1216            std::make_tuple(RHS.isScalable(), RHS.getKnownMinValue());
1217   }
1218 };
1219 using ElementCountSet = SmallSet<ElementCount, 16, ElementCountComparator>;
1220 
1221 /// LoopVectorizationCostModel - estimates the expected speedups due to
1222 /// vectorization.
1223 /// In many cases vectorization is not profitable. This can happen because of
1224 /// a number of reasons. In this class we mainly attempt to predict the
1225 /// expected speedup/slowdowns due to the supported instruction set. We use the
1226 /// TargetTransformInfo to query the different backends for the cost of
1227 /// different operations.
1228 class LoopVectorizationCostModel {
1229 public:
1230   LoopVectorizationCostModel(ScalarEpilogueLowering SEL, Loop *L,
1231                              PredicatedScalarEvolution &PSE, LoopInfo *LI,
1232                              LoopVectorizationLegality *Legal,
1233                              const TargetTransformInfo &TTI,
1234                              const TargetLibraryInfo *TLI, DemandedBits *DB,
1235                              AssumptionCache *AC,
1236                              OptimizationRemarkEmitter *ORE, const Function *F,
1237                              const LoopVectorizeHints *Hints,
1238                              InterleavedAccessInfo &IAI)
1239       : ScalarEpilogueStatus(SEL), TheLoop(L), PSE(PSE), LI(LI), Legal(Legal),
1240         TTI(TTI), TLI(TLI), DB(DB), AC(AC), ORE(ORE), TheFunction(F),
1241         Hints(Hints), InterleaveInfo(IAI) {}
1242 
1243   /// \return An upper bound for the vectorization factors (both fixed and
1244   /// scalable). If the factors are 0, vectorization and interleaving should be
1245   /// avoided up front.
1246   FixedScalableVFPair computeMaxVF(ElementCount UserVF, unsigned UserIC);
1247 
1248   /// \return True if runtime checks are required for vectorization, and false
1249   /// otherwise.
1250   bool runtimeChecksRequired();
1251 
1252   /// \return The most profitable vectorization factor and the cost of that VF.
1253   /// This method checks every VF in \p CandidateVFs. If UserVF is not ZERO
1254   /// then this vectorization factor will be selected if vectorization is
1255   /// possible.
1256   VectorizationFactor
1257   selectVectorizationFactor(const ElementCountSet &CandidateVFs);
1258 
1259   VectorizationFactor
1260   selectEpilogueVectorizationFactor(const ElementCount MaxVF,
1261                                     const LoopVectorizationPlanner &LVP);
1262 
1263   /// Setup cost-based decisions for user vectorization factor.
1264   /// \return true if the UserVF is a feasible VF to be chosen.
1265   bool selectUserVectorizationFactor(ElementCount UserVF) {
1266     collectUniformsAndScalars(UserVF);
1267     collectInstsToScalarize(UserVF);
1268     return expectedCost(UserVF).first.isValid();
1269   }
1270 
1271   /// \return The size (in bits) of the smallest and widest types in the code
1272   /// that needs to be vectorized. We ignore values that remain scalar such as
1273   /// 64 bit loop indices.
1274   std::pair<unsigned, unsigned> getSmallestAndWidestTypes();
1275 
1276   /// \return The desired interleave count.
1277   /// If interleave count has been specified by metadata it will be returned.
1278   /// Otherwise, the interleave count is computed and returned. VF and LoopCost
1279   /// are the selected vectorization factor and the cost of the selected VF.
1280   unsigned selectInterleaveCount(ElementCount VF, unsigned LoopCost);
1281 
1282   /// Memory access instruction may be vectorized in more than one way.
1283   /// Form of instruction after vectorization depends on cost.
1284   /// This function takes cost-based decisions for Load/Store instructions
1285   /// and collects them in a map. This decisions map is used for building
1286   /// the lists of loop-uniform and loop-scalar instructions.
1287   /// The calculated cost is saved with widening decision in order to
1288   /// avoid redundant calculations.
1289   void setCostBasedWideningDecision(ElementCount VF);
1290 
1291   /// A struct that represents some properties of the register usage
1292   /// of a loop.
1293   struct RegisterUsage {
1294     /// Holds the number of loop invariant values that are used in the loop.
1295     /// The key is ClassID of target-provided register class.
1296     SmallMapVector<unsigned, unsigned, 4> LoopInvariantRegs;
1297     /// Holds the maximum number of concurrent live intervals in the loop.
1298     /// The key is ClassID of target-provided register class.
1299     SmallMapVector<unsigned, unsigned, 4> MaxLocalUsers;
1300   };
1301 
1302   /// \return Returns information about the register usages of the loop for the
1303   /// given vectorization factors.
1304   SmallVector<RegisterUsage, 8>
1305   calculateRegisterUsage(ArrayRef<ElementCount> VFs);
1306 
1307   /// Collect values we want to ignore in the cost model.
1308   void collectValuesToIgnore();
1309 
1310   /// Collect all element types in the loop for which widening is needed.
1311   void collectElementTypesForWidening();
1312 
1313   /// Split reductions into those that happen in the loop, and those that happen
1314   /// outside. In loop reductions are collected into InLoopReductionChains.
1315   void collectInLoopReductions();
1316 
1317   /// Returns true if we should use strict in-order reductions for the given
1318   /// RdxDesc. This is true if the -enable-strict-reductions flag is passed,
1319   /// the IsOrdered flag of RdxDesc is set and we do not allow reordering
1320   /// of FP operations.
1321   bool useOrderedReductions(const RecurrenceDescriptor &RdxDesc) {
1322     return EnableStrictReductions && !Hints->allowReordering() &&
1323            RdxDesc.isOrdered();
1324   }
1325 
1326   /// \returns The smallest bitwidth each instruction can be represented with.
1327   /// The vector equivalents of these instructions should be truncated to this
1328   /// type.
1329   const MapVector<Instruction *, uint64_t> &getMinimalBitwidths() const {
1330     return MinBWs;
1331   }
1332 
1333   /// \returns True if it is more profitable to scalarize instruction \p I for
1334   /// vectorization factor \p VF.
1335   bool isProfitableToScalarize(Instruction *I, ElementCount VF) const {
1336     assert(VF.isVector() &&
1337            "Profitable to scalarize relevant only for VF > 1.");
1338 
1339     // Cost model is not run in the VPlan-native path - return conservative
1340     // result until this changes.
1341     if (EnableVPlanNativePath)
1342       return false;
1343 
1344     auto Scalars = InstsToScalarize.find(VF);
1345     assert(Scalars != InstsToScalarize.end() &&
1346            "VF not yet analyzed for scalarization profitability");
1347     return Scalars->second.find(I) != Scalars->second.end();
1348   }
1349 
1350   /// Returns true if \p I is known to be uniform after vectorization.
1351   bool isUniformAfterVectorization(Instruction *I, ElementCount VF) const {
1352     if (VF.isScalar())
1353       return true;
1354 
1355     // Cost model is not run in the VPlan-native path - return conservative
1356     // result until this changes.
1357     if (EnableVPlanNativePath)
1358       return false;
1359 
1360     auto UniformsPerVF = Uniforms.find(VF);
1361     assert(UniformsPerVF != Uniforms.end() &&
1362            "VF not yet analyzed for uniformity");
1363     return UniformsPerVF->second.count(I);
1364   }
1365 
1366   /// Returns true if \p I is known to be scalar after vectorization.
1367   bool isScalarAfterVectorization(Instruction *I, ElementCount VF) const {
1368     if (VF.isScalar())
1369       return true;
1370 
1371     // Cost model is not run in the VPlan-native path - return conservative
1372     // result until this changes.
1373     if (EnableVPlanNativePath)
1374       return false;
1375 
1376     auto ScalarsPerVF = Scalars.find(VF);
1377     assert(ScalarsPerVF != Scalars.end() &&
1378            "Scalar values are not calculated for VF");
1379     return ScalarsPerVF->second.count(I);
1380   }
1381 
1382   /// \returns True if instruction \p I can be truncated to a smaller bitwidth
1383   /// for vectorization factor \p VF.
1384   bool canTruncateToMinimalBitwidth(Instruction *I, ElementCount VF) const {
1385     return VF.isVector() && MinBWs.find(I) != MinBWs.end() &&
1386            !isProfitableToScalarize(I, VF) &&
1387            !isScalarAfterVectorization(I, VF);
1388   }
1389 
1390   /// Decision that was taken during cost calculation for memory instruction.
1391   enum InstWidening {
1392     CM_Unknown,
1393     CM_Widen,         // For consecutive accesses with stride +1.
1394     CM_Widen_Reverse, // For consecutive accesses with stride -1.
1395     CM_Interleave,
1396     CM_GatherScatter,
1397     CM_Scalarize
1398   };
1399 
1400   /// Save vectorization decision \p W and \p Cost taken by the cost model for
1401   /// instruction \p I and vector width \p VF.
1402   void setWideningDecision(Instruction *I, ElementCount VF, InstWidening W,
1403                            InstructionCost Cost) {
1404     assert(VF.isVector() && "Expected VF >=2");
1405     WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
1406   }
1407 
1408   /// Save vectorization decision \p W and \p Cost taken by the cost model for
1409   /// interleaving group \p Grp and vector width \p VF.
1410   void setWideningDecision(const InterleaveGroup<Instruction> *Grp,
1411                            ElementCount VF, InstWidening W,
1412                            InstructionCost Cost) {
1413     assert(VF.isVector() && "Expected VF >=2");
1414     /// Broadcast this decicion to all instructions inside the group.
1415     /// But the cost will be assigned to one instruction only.
1416     for (unsigned i = 0; i < Grp->getFactor(); ++i) {
1417       if (auto *I = Grp->getMember(i)) {
1418         if (Grp->getInsertPos() == I)
1419           WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
1420         else
1421           WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, 0);
1422       }
1423     }
1424   }
1425 
1426   /// Return the cost model decision for the given instruction \p I and vector
1427   /// width \p VF. Return CM_Unknown if this instruction did not pass
1428   /// through the cost modeling.
1429   InstWidening getWideningDecision(Instruction *I, ElementCount VF) const {
1430     assert(VF.isVector() && "Expected VF to be a vector VF");
1431     // Cost model is not run in the VPlan-native path - return conservative
1432     // result until this changes.
1433     if (EnableVPlanNativePath)
1434       return CM_GatherScatter;
1435 
1436     std::pair<Instruction *, ElementCount> InstOnVF = std::make_pair(I, VF);
1437     auto Itr = WideningDecisions.find(InstOnVF);
1438     if (Itr == WideningDecisions.end())
1439       return CM_Unknown;
1440     return Itr->second.first;
1441   }
1442 
1443   /// Return the vectorization cost for the given instruction \p I and vector
1444   /// width \p VF.
1445   InstructionCost getWideningCost(Instruction *I, ElementCount VF) {
1446     assert(VF.isVector() && "Expected VF >=2");
1447     std::pair<Instruction *, ElementCount> InstOnVF = std::make_pair(I, VF);
1448     assert(WideningDecisions.find(InstOnVF) != WideningDecisions.end() &&
1449            "The cost is not calculated");
1450     return WideningDecisions[InstOnVF].second;
1451   }
1452 
1453   /// Return True if instruction \p I is an optimizable truncate whose operand
1454   /// is an induction variable. Such a truncate will be removed by adding a new
1455   /// induction variable with the destination type.
1456   bool isOptimizableIVTruncate(Instruction *I, ElementCount VF) {
1457     // If the instruction is not a truncate, return false.
1458     auto *Trunc = dyn_cast<TruncInst>(I);
1459     if (!Trunc)
1460       return false;
1461 
1462     // Get the source and destination types of the truncate.
1463     Type *SrcTy = ToVectorTy(cast<CastInst>(I)->getSrcTy(), VF);
1464     Type *DestTy = ToVectorTy(cast<CastInst>(I)->getDestTy(), VF);
1465 
1466     // If the truncate is free for the given types, return false. Replacing a
1467     // free truncate with an induction variable would add an induction variable
1468     // update instruction to each iteration of the loop. We exclude from this
1469     // check the primary induction variable since it will need an update
1470     // instruction regardless.
1471     Value *Op = Trunc->getOperand(0);
1472     if (Op != Legal->getPrimaryInduction() && TTI.isTruncateFree(SrcTy, DestTy))
1473       return false;
1474 
1475     // If the truncated value is not an induction variable, return false.
1476     return Legal->isInductionPhi(Op);
1477   }
1478 
1479   /// Collects the instructions to scalarize for each predicated instruction in
1480   /// the loop.
1481   void collectInstsToScalarize(ElementCount VF);
1482 
1483   /// Collect Uniform and Scalar values for the given \p VF.
1484   /// The sets depend on CM decision for Load/Store instructions
1485   /// that may be vectorized as interleave, gather-scatter or scalarized.
1486   void collectUniformsAndScalars(ElementCount VF) {
1487     // Do the analysis once.
1488     if (VF.isScalar() || Uniforms.find(VF) != Uniforms.end())
1489       return;
1490     setCostBasedWideningDecision(VF);
1491     collectLoopUniforms(VF);
1492     collectLoopScalars(VF);
1493   }
1494 
1495   /// Returns true if the target machine supports masked store operation
1496   /// for the given \p DataType and kind of access to \p Ptr.
1497   bool isLegalMaskedStore(Type *DataType, Value *Ptr, Align Alignment) const {
1498     return Legal->isConsecutivePtr(Ptr) &&
1499            TTI.isLegalMaskedStore(DataType, Alignment);
1500   }
1501 
1502   /// Returns true if the target machine supports masked load operation
1503   /// for the given \p DataType and kind of access to \p Ptr.
1504   bool isLegalMaskedLoad(Type *DataType, Value *Ptr, Align Alignment) const {
1505     return Legal->isConsecutivePtr(Ptr) &&
1506            TTI.isLegalMaskedLoad(DataType, Alignment);
1507   }
1508 
1509   /// Returns true if the target machine can represent \p V as a masked gather
1510   /// or scatter operation.
1511   bool isLegalGatherOrScatter(Value *V) {
1512     bool LI = isa<LoadInst>(V);
1513     bool SI = isa<StoreInst>(V);
1514     if (!LI && !SI)
1515       return false;
1516     auto *Ty = getLoadStoreType(V);
1517     Align Align = getLoadStoreAlignment(V);
1518     return (LI && TTI.isLegalMaskedGather(Ty, Align)) ||
1519            (SI && TTI.isLegalMaskedScatter(Ty, Align));
1520   }
1521 
1522   /// Returns true if the target machine supports all of the reduction
1523   /// variables found for the given VF.
1524   bool canVectorizeReductions(ElementCount VF) const {
1525     return (all_of(Legal->getReductionVars(), [&](auto &Reduction) -> bool {
1526       const RecurrenceDescriptor &RdxDesc = Reduction.second;
1527       return TTI.isLegalToVectorizeReduction(RdxDesc, VF);
1528     }));
1529   }
1530 
1531   /// Returns true if \p I is an instruction that will be scalarized with
1532   /// predication. Such instructions include conditional stores and
1533   /// instructions that may divide by zero.
1534   /// If a non-zero VF has been calculated, we check if I will be scalarized
1535   /// predication for that VF.
1536   bool isScalarWithPredication(Instruction *I) const;
1537 
1538   // Returns true if \p I is an instruction that will be predicated either
1539   // through scalar predication or masked load/store or masked gather/scatter.
1540   // Superset of instructions that return true for isScalarWithPredication.
1541   bool isPredicatedInst(Instruction *I) {
1542     if (!blockNeedsPredication(I->getParent()))
1543       return false;
1544     // Loads and stores that need some form of masked operation are predicated
1545     // instructions.
1546     if (isa<LoadInst>(I) || isa<StoreInst>(I))
1547       return Legal->isMaskRequired(I);
1548     return isScalarWithPredication(I);
1549   }
1550 
1551   /// Returns true if \p I is a memory instruction with consecutive memory
1552   /// access that can be widened.
1553   bool
1554   memoryInstructionCanBeWidened(Instruction *I,
1555                                 ElementCount VF = ElementCount::getFixed(1));
1556 
1557   /// Returns true if \p I is a memory instruction in an interleaved-group
1558   /// of memory accesses that can be vectorized with wide vector loads/stores
1559   /// and shuffles.
1560   bool
1561   interleavedAccessCanBeWidened(Instruction *I,
1562                                 ElementCount VF = ElementCount::getFixed(1));
1563 
1564   /// Check if \p Instr belongs to any interleaved access group.
1565   bool isAccessInterleaved(Instruction *Instr) {
1566     return InterleaveInfo.isInterleaved(Instr);
1567   }
1568 
1569   /// Get the interleaved access group that \p Instr belongs to.
1570   const InterleaveGroup<Instruction> *
1571   getInterleavedAccessGroup(Instruction *Instr) {
1572     return InterleaveInfo.getInterleaveGroup(Instr);
1573   }
1574 
1575   /// Returns true if we're required to use a scalar epilogue for at least
1576   /// the final iteration of the original loop.
1577   bool requiresScalarEpilogue(ElementCount VF) const {
1578     if (!isScalarEpilogueAllowed())
1579       return false;
1580     // If we might exit from anywhere but the latch, must run the exiting
1581     // iteration in scalar form.
1582     if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch())
1583       return true;
1584     return VF.isVector() && InterleaveInfo.requiresScalarEpilogue();
1585   }
1586 
1587   /// Returns true if a scalar epilogue is not allowed due to optsize or a
1588   /// loop hint annotation.
1589   bool isScalarEpilogueAllowed() const {
1590     return ScalarEpilogueStatus == CM_ScalarEpilogueAllowed;
1591   }
1592 
1593   /// Returns true if all loop blocks should be masked to fold tail loop.
1594   bool foldTailByMasking() const { return FoldTailByMasking; }
1595 
1596   bool blockNeedsPredication(BasicBlock *BB) const {
1597     return foldTailByMasking() || Legal->blockNeedsPredication(BB);
1598   }
1599 
1600   /// A SmallMapVector to store the InLoop reduction op chains, mapping phi
1601   /// nodes to the chain of instructions representing the reductions. Uses a
1602   /// MapVector to ensure deterministic iteration order.
1603   using ReductionChainMap =
1604       SmallMapVector<PHINode *, SmallVector<Instruction *, 4>, 4>;
1605 
1606   /// Return the chain of instructions representing an inloop reduction.
1607   const ReductionChainMap &getInLoopReductionChains() const {
1608     return InLoopReductionChains;
1609   }
1610 
1611   /// Returns true if the Phi is part of an inloop reduction.
1612   bool isInLoopReduction(PHINode *Phi) const {
1613     return InLoopReductionChains.count(Phi);
1614   }
1615 
1616   /// Estimate cost of an intrinsic call instruction CI if it were vectorized
1617   /// with factor VF.  Return the cost of the instruction, including
1618   /// scalarization overhead if it's needed.
1619   InstructionCost getVectorIntrinsicCost(CallInst *CI, ElementCount VF) const;
1620 
1621   /// Estimate cost of a call instruction CI if it were vectorized with factor
1622   /// VF. Return the cost of the instruction, including scalarization overhead
1623   /// if it's needed. The flag NeedToScalarize shows if the call needs to be
1624   /// scalarized -
1625   /// i.e. either vector version isn't available, or is too expensive.
1626   InstructionCost getVectorCallCost(CallInst *CI, ElementCount VF,
1627                                     bool &NeedToScalarize) const;
1628 
1629   /// Returns true if the per-lane cost of VectorizationFactor A is lower than
1630   /// that of B.
1631   bool isMoreProfitable(const VectorizationFactor &A,
1632                         const VectorizationFactor &B) const;
1633 
1634   /// Invalidates decisions already taken by the cost model.
1635   void invalidateCostModelingDecisions() {
1636     WideningDecisions.clear();
1637     Uniforms.clear();
1638     Scalars.clear();
1639   }
1640 
1641 private:
1642   unsigned NumPredStores = 0;
1643 
1644   /// \return An upper bound for the vectorization factors for both
1645   /// fixed and scalable vectorization, where the minimum-known number of
1646   /// elements is a power-of-2 larger than zero. If scalable vectorization is
1647   /// disabled or unsupported, then the scalable part will be equal to
1648   /// ElementCount::getScalable(0).
1649   FixedScalableVFPair computeFeasibleMaxVF(unsigned ConstTripCount,
1650                                            ElementCount UserVF);
1651 
1652   /// \return the maximized element count based on the targets vector
1653   /// registers and the loop trip-count, but limited to a maximum safe VF.
1654   /// This is a helper function of computeFeasibleMaxVF.
1655   /// FIXME: MaxSafeVF is currently passed by reference to avoid some obscure
1656   /// issue that occurred on one of the buildbots which cannot be reproduced
1657   /// without having access to the properietary compiler (see comments on
1658   /// D98509). The issue is currently under investigation and this workaround
1659   /// will be removed as soon as possible.
1660   ElementCount getMaximizedVFForTarget(unsigned ConstTripCount,
1661                                        unsigned SmallestType,
1662                                        unsigned WidestType,
1663                                        const ElementCount &MaxSafeVF);
1664 
1665   /// \return the maximum legal scalable VF, based on the safe max number
1666   /// of elements.
1667   ElementCount getMaxLegalScalableVF(unsigned MaxSafeElements);
1668 
1669   /// The vectorization cost is a combination of the cost itself and a boolean
1670   /// indicating whether any of the contributing operations will actually
1671   /// operate on vector values after type legalization in the backend. If this
1672   /// latter value is false, then all operations will be scalarized (i.e. no
1673   /// vectorization has actually taken place).
1674   using VectorizationCostTy = std::pair<InstructionCost, bool>;
1675 
1676   /// Returns the expected execution cost. The unit of the cost does
1677   /// not matter because we use the 'cost' units to compare different
1678   /// vector widths. The cost that is returned is *not* normalized by
1679   /// the factor width.
1680   VectorizationCostTy expectedCost(ElementCount VF);
1681 
1682   /// Returns the execution time cost of an instruction for a given vector
1683   /// width. Vector width of one means scalar.
1684   VectorizationCostTy getInstructionCost(Instruction *I, ElementCount VF);
1685 
1686   /// The cost-computation logic from getInstructionCost which provides
1687   /// the vector type as an output parameter.
1688   InstructionCost getInstructionCost(Instruction *I, ElementCount VF,
1689                                      Type *&VectorTy);
1690 
1691   /// Return the cost of instructions in an inloop reduction pattern, if I is
1692   /// part of that pattern.
1693   InstructionCost getReductionPatternCost(Instruction *I, ElementCount VF,
1694                                           Type *VectorTy,
1695                                           TTI::TargetCostKind CostKind);
1696 
1697   /// Calculate vectorization cost of memory instruction \p I.
1698   InstructionCost getMemoryInstructionCost(Instruction *I, ElementCount VF);
1699 
1700   /// The cost computation for scalarized memory instruction.
1701   InstructionCost getMemInstScalarizationCost(Instruction *I, ElementCount VF);
1702 
1703   /// The cost computation for interleaving group of memory instructions.
1704   InstructionCost getInterleaveGroupCost(Instruction *I, ElementCount VF);
1705 
1706   /// The cost computation for Gather/Scatter instruction.
1707   InstructionCost getGatherScatterCost(Instruction *I, ElementCount VF);
1708 
1709   /// The cost computation for widening instruction \p I with consecutive
1710   /// memory access.
1711   InstructionCost getConsecutiveMemOpCost(Instruction *I, ElementCount VF);
1712 
1713   /// The cost calculation for Load/Store instruction \p I with uniform pointer -
1714   /// Load: scalar load + broadcast.
1715   /// Store: scalar store + (loop invariant value stored? 0 : extract of last
1716   /// element)
1717   InstructionCost getUniformMemOpCost(Instruction *I, ElementCount VF);
1718 
1719   /// Estimate the overhead of scalarizing an instruction. This is a
1720   /// convenience wrapper for the type-based getScalarizationOverhead API.
1721   InstructionCost getScalarizationOverhead(Instruction *I,
1722                                            ElementCount VF) const;
1723 
1724   /// Returns whether the instruction is a load or store and will be a emitted
1725   /// as a vector operation.
1726   bool isConsecutiveLoadOrStore(Instruction *I);
1727 
1728   /// Returns true if an artificially high cost for emulated masked memrefs
1729   /// should be used.
1730   bool useEmulatedMaskMemRefHack(Instruction *I);
1731 
1732   /// Map of scalar integer values to the smallest bitwidth they can be legally
1733   /// represented as. The vector equivalents of these values should be truncated
1734   /// to this type.
1735   MapVector<Instruction *, uint64_t> MinBWs;
1736 
1737   /// A type representing the costs for instructions if they were to be
1738   /// scalarized rather than vectorized. The entries are Instruction-Cost
1739   /// pairs.
1740   using ScalarCostsTy = DenseMap<Instruction *, InstructionCost>;
1741 
1742   /// A set containing all BasicBlocks that are known to present after
1743   /// vectorization as a predicated block.
1744   SmallPtrSet<BasicBlock *, 4> PredicatedBBsAfterVectorization;
1745 
1746   /// Records whether it is allowed to have the original scalar loop execute at
1747   /// least once. This may be needed as a fallback loop in case runtime
1748   /// aliasing/dependence checks fail, or to handle the tail/remainder
1749   /// iterations when the trip count is unknown or doesn't divide by the VF,
1750   /// or as a peel-loop to handle gaps in interleave-groups.
1751   /// Under optsize and when the trip count is very small we don't allow any
1752   /// iterations to execute in the scalar loop.
1753   ScalarEpilogueLowering ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
1754 
1755   /// All blocks of loop are to be masked to fold tail of scalar iterations.
1756   bool FoldTailByMasking = false;
1757 
1758   /// A map holding scalar costs for different vectorization factors. The
1759   /// presence of a cost for an instruction in the mapping indicates that the
1760   /// instruction will be scalarized when vectorizing with the associated
1761   /// vectorization factor. The entries are VF-ScalarCostTy pairs.
1762   DenseMap<ElementCount, ScalarCostsTy> InstsToScalarize;
1763 
1764   /// Holds the instructions known to be uniform after vectorization.
1765   /// The data is collected per VF.
1766   DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> Uniforms;
1767 
1768   /// Holds the instructions known to be scalar after vectorization.
1769   /// The data is collected per VF.
1770   DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> Scalars;
1771 
1772   /// Holds the instructions (address computations) that are forced to be
1773   /// scalarized.
1774   DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> ForcedScalars;
1775 
1776   /// PHINodes of the reductions that should be expanded in-loop along with
1777   /// their associated chains of reduction operations, in program order from top
1778   /// (PHI) to bottom
1779   ReductionChainMap InLoopReductionChains;
1780 
1781   /// A Map of inloop reduction operations and their immediate chain operand.
1782   /// FIXME: This can be removed once reductions can be costed correctly in
1783   /// vplan. This was added to allow quick lookup to the inloop operations,
1784   /// without having to loop through InLoopReductionChains.
1785   DenseMap<Instruction *, Instruction *> InLoopReductionImmediateChains;
1786 
1787   /// Returns the expected difference in cost from scalarizing the expression
1788   /// feeding a predicated instruction \p PredInst. The instructions to
1789   /// scalarize and their scalar costs are collected in \p ScalarCosts. A
1790   /// non-negative return value implies the expression will be scalarized.
1791   /// Currently, only single-use chains are considered for scalarization.
1792   int computePredInstDiscount(Instruction *PredInst, ScalarCostsTy &ScalarCosts,
1793                               ElementCount VF);
1794 
1795   /// Collect the instructions that are uniform after vectorization. An
1796   /// instruction is uniform if we represent it with a single scalar value in
1797   /// the vectorized loop corresponding to each vector iteration. Examples of
1798   /// uniform instructions include pointer operands of consecutive or
1799   /// interleaved memory accesses. Note that although uniformity implies an
1800   /// instruction will be scalar, the reverse is not true. In general, a
1801   /// scalarized instruction will be represented by VF scalar values in the
1802   /// vectorized loop, each corresponding to an iteration of the original
1803   /// scalar loop.
1804   void collectLoopUniforms(ElementCount VF);
1805 
1806   /// Collect the instructions that are scalar after vectorization. An
1807   /// instruction is scalar if it is known to be uniform or will be scalarized
1808   /// during vectorization. Non-uniform scalarized instructions will be
1809   /// represented by VF values in the vectorized loop, each corresponding to an
1810   /// iteration of the original scalar loop.
1811   void collectLoopScalars(ElementCount VF);
1812 
1813   /// Keeps cost model vectorization decision and cost for instructions.
1814   /// Right now it is used for memory instructions only.
1815   using DecisionList = DenseMap<std::pair<Instruction *, ElementCount>,
1816                                 std::pair<InstWidening, InstructionCost>>;
1817 
1818   DecisionList WideningDecisions;
1819 
1820   /// Returns true if \p V is expected to be vectorized and it needs to be
1821   /// extracted.
1822   bool needsExtract(Value *V, ElementCount VF) const {
1823     Instruction *I = dyn_cast<Instruction>(V);
1824     if (VF.isScalar() || !I || !TheLoop->contains(I) ||
1825         TheLoop->isLoopInvariant(I))
1826       return false;
1827 
1828     // Assume we can vectorize V (and hence we need extraction) if the
1829     // scalars are not computed yet. This can happen, because it is called
1830     // via getScalarizationOverhead from setCostBasedWideningDecision, before
1831     // the scalars are collected. That should be a safe assumption in most
1832     // cases, because we check if the operands have vectorizable types
1833     // beforehand in LoopVectorizationLegality.
1834     return Scalars.find(VF) == Scalars.end() ||
1835            !isScalarAfterVectorization(I, VF);
1836   };
1837 
1838   /// Returns a range containing only operands needing to be extracted.
1839   SmallVector<Value *, 4> filterExtractingOperands(Instruction::op_range Ops,
1840                                                    ElementCount VF) const {
1841     return SmallVector<Value *, 4>(make_filter_range(
1842         Ops, [this, VF](Value *V) { return this->needsExtract(V, VF); }));
1843   }
1844 
1845   /// Determines if we have the infrastructure to vectorize loop \p L and its
1846   /// epilogue, assuming the main loop is vectorized by \p VF.
1847   bool isCandidateForEpilogueVectorization(const Loop &L,
1848                                            const ElementCount VF) const;
1849 
1850   /// Returns true if epilogue vectorization is considered profitable, and
1851   /// false otherwise.
1852   /// \p VF is the vectorization factor chosen for the original loop.
1853   bool isEpilogueVectorizationProfitable(const ElementCount VF) const;
1854 
1855 public:
1856   /// The loop that we evaluate.
1857   Loop *TheLoop;
1858 
1859   /// Predicated scalar evolution analysis.
1860   PredicatedScalarEvolution &PSE;
1861 
1862   /// Loop Info analysis.
1863   LoopInfo *LI;
1864 
1865   /// Vectorization legality.
1866   LoopVectorizationLegality *Legal;
1867 
1868   /// Vector target information.
1869   const TargetTransformInfo &TTI;
1870 
1871   /// Target Library Info.
1872   const TargetLibraryInfo *TLI;
1873 
1874   /// Demanded bits analysis.
1875   DemandedBits *DB;
1876 
1877   /// Assumption cache.
1878   AssumptionCache *AC;
1879 
1880   /// Interface to emit optimization remarks.
1881   OptimizationRemarkEmitter *ORE;
1882 
1883   const Function *TheFunction;
1884 
1885   /// Loop Vectorize Hint.
1886   const LoopVectorizeHints *Hints;
1887 
1888   /// The interleave access information contains groups of interleaved accesses
1889   /// with the same stride and close to each other.
1890   InterleavedAccessInfo &InterleaveInfo;
1891 
1892   /// Values to ignore in the cost model.
1893   SmallPtrSet<const Value *, 16> ValuesToIgnore;
1894 
1895   /// Values to ignore in the cost model when VF > 1.
1896   SmallPtrSet<const Value *, 16> VecValuesToIgnore;
1897 
1898   /// All element types found in the loop.
1899   SmallPtrSet<Type *, 16> ElementTypesInLoop;
1900 
1901   /// Profitable vector factors.
1902   SmallVector<VectorizationFactor, 8> ProfitableVFs;
1903 };
1904 } // end namespace llvm
1905 
1906 /// Helper struct to manage generating runtime checks for vectorization.
1907 ///
1908 /// The runtime checks are created up-front in temporary blocks to allow better
1909 /// estimating the cost and un-linked from the existing IR. After deciding to
1910 /// vectorize, the checks are moved back. If deciding not to vectorize, the
1911 /// temporary blocks are completely removed.
1912 class GeneratedRTChecks {
1913   /// Basic block which contains the generated SCEV checks, if any.
1914   BasicBlock *SCEVCheckBlock = nullptr;
1915 
1916   /// The value representing the result of the generated SCEV checks. If it is
1917   /// nullptr, either no SCEV checks have been generated or they have been used.
1918   Value *SCEVCheckCond = nullptr;
1919 
1920   /// Basic block which contains the generated memory runtime checks, if any.
1921   BasicBlock *MemCheckBlock = nullptr;
1922 
1923   /// The value representing the result of the generated memory runtime checks.
1924   /// If it is nullptr, either no memory runtime checks have been generated or
1925   /// they have been used.
1926   Instruction *MemRuntimeCheckCond = nullptr;
1927 
1928   DominatorTree *DT;
1929   LoopInfo *LI;
1930 
1931   SCEVExpander SCEVExp;
1932   SCEVExpander MemCheckExp;
1933 
1934 public:
1935   GeneratedRTChecks(ScalarEvolution &SE, DominatorTree *DT, LoopInfo *LI,
1936                     const DataLayout &DL)
1937       : DT(DT), LI(LI), SCEVExp(SE, DL, "scev.check"),
1938         MemCheckExp(SE, DL, "scev.check") {}
1939 
1940   /// Generate runtime checks in SCEVCheckBlock and MemCheckBlock, so we can
1941   /// accurately estimate the cost of the runtime checks. The blocks are
1942   /// un-linked from the IR and is added back during vector code generation. If
1943   /// there is no vector code generation, the check blocks are removed
1944   /// completely.
1945   void Create(Loop *L, const LoopAccessInfo &LAI,
1946               const SCEVUnionPredicate &UnionPred) {
1947 
1948     BasicBlock *LoopHeader = L->getHeader();
1949     BasicBlock *Preheader = L->getLoopPreheader();
1950 
1951     // Use SplitBlock to create blocks for SCEV & memory runtime checks to
1952     // ensure the blocks are properly added to LoopInfo & DominatorTree. Those
1953     // may be used by SCEVExpander. The blocks will be un-linked from their
1954     // predecessors and removed from LI & DT at the end of the function.
1955     if (!UnionPred.isAlwaysTrue()) {
1956       SCEVCheckBlock = SplitBlock(Preheader, Preheader->getTerminator(), DT, LI,
1957                                   nullptr, "vector.scevcheck");
1958 
1959       SCEVCheckCond = SCEVExp.expandCodeForPredicate(
1960           &UnionPred, SCEVCheckBlock->getTerminator());
1961     }
1962 
1963     const auto &RtPtrChecking = *LAI.getRuntimePointerChecking();
1964     if (RtPtrChecking.Need) {
1965       auto *Pred = SCEVCheckBlock ? SCEVCheckBlock : Preheader;
1966       MemCheckBlock = SplitBlock(Pred, Pred->getTerminator(), DT, LI, nullptr,
1967                                  "vector.memcheck");
1968 
1969       std::tie(std::ignore, MemRuntimeCheckCond) =
1970           addRuntimeChecks(MemCheckBlock->getTerminator(), L,
1971                            RtPtrChecking.getChecks(), MemCheckExp);
1972       assert(MemRuntimeCheckCond &&
1973              "no RT checks generated although RtPtrChecking "
1974              "claimed checks are required");
1975     }
1976 
1977     if (!MemCheckBlock && !SCEVCheckBlock)
1978       return;
1979 
1980     // Unhook the temporary block with the checks, update various places
1981     // accordingly.
1982     if (SCEVCheckBlock)
1983       SCEVCheckBlock->replaceAllUsesWith(Preheader);
1984     if (MemCheckBlock)
1985       MemCheckBlock->replaceAllUsesWith(Preheader);
1986 
1987     if (SCEVCheckBlock) {
1988       SCEVCheckBlock->getTerminator()->moveBefore(Preheader->getTerminator());
1989       new UnreachableInst(Preheader->getContext(), SCEVCheckBlock);
1990       Preheader->getTerminator()->eraseFromParent();
1991     }
1992     if (MemCheckBlock) {
1993       MemCheckBlock->getTerminator()->moveBefore(Preheader->getTerminator());
1994       new UnreachableInst(Preheader->getContext(), MemCheckBlock);
1995       Preheader->getTerminator()->eraseFromParent();
1996     }
1997 
1998     DT->changeImmediateDominator(LoopHeader, Preheader);
1999     if (MemCheckBlock) {
2000       DT->eraseNode(MemCheckBlock);
2001       LI->removeBlock(MemCheckBlock);
2002     }
2003     if (SCEVCheckBlock) {
2004       DT->eraseNode(SCEVCheckBlock);
2005       LI->removeBlock(SCEVCheckBlock);
2006     }
2007   }
2008 
2009   /// Remove the created SCEV & memory runtime check blocks & instructions, if
2010   /// unused.
2011   ~GeneratedRTChecks() {
2012     SCEVExpanderCleaner SCEVCleaner(SCEVExp, *DT);
2013     SCEVExpanderCleaner MemCheckCleaner(MemCheckExp, *DT);
2014     if (!SCEVCheckCond)
2015       SCEVCleaner.markResultUsed();
2016 
2017     if (!MemRuntimeCheckCond)
2018       MemCheckCleaner.markResultUsed();
2019 
2020     if (MemRuntimeCheckCond) {
2021       auto &SE = *MemCheckExp.getSE();
2022       // Memory runtime check generation creates compares that use expanded
2023       // values. Remove them before running the SCEVExpanderCleaners.
2024       for (auto &I : make_early_inc_range(reverse(*MemCheckBlock))) {
2025         if (MemCheckExp.isInsertedInstruction(&I))
2026           continue;
2027         SE.forgetValue(&I);
2028         SE.eraseValueFromMap(&I);
2029         I.eraseFromParent();
2030       }
2031     }
2032     MemCheckCleaner.cleanup();
2033     SCEVCleaner.cleanup();
2034 
2035     if (SCEVCheckCond)
2036       SCEVCheckBlock->eraseFromParent();
2037     if (MemRuntimeCheckCond)
2038       MemCheckBlock->eraseFromParent();
2039   }
2040 
2041   /// Adds the generated SCEVCheckBlock before \p LoopVectorPreHeader and
2042   /// adjusts the branches to branch to the vector preheader or \p Bypass,
2043   /// depending on the generated condition.
2044   BasicBlock *emitSCEVChecks(Loop *L, BasicBlock *Bypass,
2045                              BasicBlock *LoopVectorPreHeader,
2046                              BasicBlock *LoopExitBlock) {
2047     if (!SCEVCheckCond)
2048       return nullptr;
2049     if (auto *C = dyn_cast<ConstantInt>(SCEVCheckCond))
2050       if (C->isZero())
2051         return nullptr;
2052 
2053     auto *Pred = LoopVectorPreHeader->getSinglePredecessor();
2054 
2055     BranchInst::Create(LoopVectorPreHeader, SCEVCheckBlock);
2056     // Create new preheader for vector loop.
2057     if (auto *PL = LI->getLoopFor(LoopVectorPreHeader))
2058       PL->addBasicBlockToLoop(SCEVCheckBlock, *LI);
2059 
2060     SCEVCheckBlock->getTerminator()->eraseFromParent();
2061     SCEVCheckBlock->moveBefore(LoopVectorPreHeader);
2062     Pred->getTerminator()->replaceSuccessorWith(LoopVectorPreHeader,
2063                                                 SCEVCheckBlock);
2064 
2065     DT->addNewBlock(SCEVCheckBlock, Pred);
2066     DT->changeImmediateDominator(LoopVectorPreHeader, SCEVCheckBlock);
2067 
2068     ReplaceInstWithInst(
2069         SCEVCheckBlock->getTerminator(),
2070         BranchInst::Create(Bypass, LoopVectorPreHeader, SCEVCheckCond));
2071     // Mark the check as used, to prevent it from being removed during cleanup.
2072     SCEVCheckCond = nullptr;
2073     return SCEVCheckBlock;
2074   }
2075 
2076   /// Adds the generated MemCheckBlock before \p LoopVectorPreHeader and adjusts
2077   /// the branches to branch to the vector preheader or \p Bypass, depending on
2078   /// the generated condition.
2079   BasicBlock *emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass,
2080                                    BasicBlock *LoopVectorPreHeader) {
2081     // Check if we generated code that checks in runtime if arrays overlap.
2082     if (!MemRuntimeCheckCond)
2083       return nullptr;
2084 
2085     auto *Pred = LoopVectorPreHeader->getSinglePredecessor();
2086     Pred->getTerminator()->replaceSuccessorWith(LoopVectorPreHeader,
2087                                                 MemCheckBlock);
2088 
2089     DT->addNewBlock(MemCheckBlock, Pred);
2090     DT->changeImmediateDominator(LoopVectorPreHeader, MemCheckBlock);
2091     MemCheckBlock->moveBefore(LoopVectorPreHeader);
2092 
2093     if (auto *PL = LI->getLoopFor(LoopVectorPreHeader))
2094       PL->addBasicBlockToLoop(MemCheckBlock, *LI);
2095 
2096     ReplaceInstWithInst(
2097         MemCheckBlock->getTerminator(),
2098         BranchInst::Create(Bypass, LoopVectorPreHeader, MemRuntimeCheckCond));
2099     MemCheckBlock->getTerminator()->setDebugLoc(
2100         Pred->getTerminator()->getDebugLoc());
2101 
2102     // Mark the check as used, to prevent it from being removed during cleanup.
2103     MemRuntimeCheckCond = nullptr;
2104     return MemCheckBlock;
2105   }
2106 };
2107 
2108 // Return true if \p OuterLp is an outer loop annotated with hints for explicit
2109 // vectorization. The loop needs to be annotated with #pragma omp simd
2110 // simdlen(#) or #pragma clang vectorize(enable) vectorize_width(#). If the
2111 // vector length information is not provided, vectorization is not considered
2112 // explicit. Interleave hints are not allowed either. These limitations will be
2113 // relaxed in the future.
2114 // Please, note that we are currently forced to abuse the pragma 'clang
2115 // vectorize' semantics. This pragma provides *auto-vectorization hints*
2116 // (i.e., LV must check that vectorization is legal) whereas pragma 'omp simd'
2117 // provides *explicit vectorization hints* (LV can bypass legal checks and
2118 // assume that vectorization is legal). However, both hints are implemented
2119 // using the same metadata (llvm.loop.vectorize, processed by
2120 // LoopVectorizeHints). This will be fixed in the future when the native IR
2121 // representation for pragma 'omp simd' is introduced.
2122 static bool isExplicitVecOuterLoop(Loop *OuterLp,
2123                                    OptimizationRemarkEmitter *ORE) {
2124   assert(!OuterLp->isInnermost() && "This is not an outer loop");
2125   LoopVectorizeHints Hints(OuterLp, true /*DisableInterleaving*/, *ORE);
2126 
2127   // Only outer loops with an explicit vectorization hint are supported.
2128   // Unannotated outer loops are ignored.
2129   if (Hints.getForce() == LoopVectorizeHints::FK_Undefined)
2130     return false;
2131 
2132   Function *Fn = OuterLp->getHeader()->getParent();
2133   if (!Hints.allowVectorization(Fn, OuterLp,
2134                                 true /*VectorizeOnlyWhenForced*/)) {
2135     LLVM_DEBUG(dbgs() << "LV: Loop hints prevent outer loop vectorization.\n");
2136     return false;
2137   }
2138 
2139   if (Hints.getInterleave() > 1) {
2140     // TODO: Interleave support is future work.
2141     LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Interleave is not supported for "
2142                          "outer loops.\n");
2143     Hints.emitRemarkWithHints();
2144     return false;
2145   }
2146 
2147   return true;
2148 }
2149 
2150 static void collectSupportedLoops(Loop &L, LoopInfo *LI,
2151                                   OptimizationRemarkEmitter *ORE,
2152                                   SmallVectorImpl<Loop *> &V) {
2153   // Collect inner loops and outer loops without irreducible control flow. For
2154   // now, only collect outer loops that have explicit vectorization hints. If we
2155   // are stress testing the VPlan H-CFG construction, we collect the outermost
2156   // loop of every loop nest.
2157   if (L.isInnermost() || VPlanBuildStressTest ||
2158       (EnableVPlanNativePath && isExplicitVecOuterLoop(&L, ORE))) {
2159     LoopBlocksRPO RPOT(&L);
2160     RPOT.perform(LI);
2161     if (!containsIrreducibleCFG<const BasicBlock *>(RPOT, *LI)) {
2162       V.push_back(&L);
2163       // TODO: Collect inner loops inside marked outer loops in case
2164       // vectorization fails for the outer loop. Do not invoke
2165       // 'containsIrreducibleCFG' again for inner loops when the outer loop is
2166       // already known to be reducible. We can use an inherited attribute for
2167       // that.
2168       return;
2169     }
2170   }
2171   for (Loop *InnerL : L)
2172     collectSupportedLoops(*InnerL, LI, ORE, V);
2173 }
2174 
2175 namespace {
2176 
2177 /// The LoopVectorize Pass.
2178 struct LoopVectorize : public FunctionPass {
2179   /// Pass identification, replacement for typeid
2180   static char ID;
2181 
2182   LoopVectorizePass Impl;
2183 
2184   explicit LoopVectorize(bool InterleaveOnlyWhenForced = false,
2185                          bool VectorizeOnlyWhenForced = false)
2186       : FunctionPass(ID),
2187         Impl({InterleaveOnlyWhenForced, VectorizeOnlyWhenForced}) {
2188     initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
2189   }
2190 
2191   bool runOnFunction(Function &F) override {
2192     if (skipFunction(F))
2193       return false;
2194 
2195     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
2196     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2197     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
2198     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2199     auto *BFI = &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI();
2200     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
2201     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
2202     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
2203     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
2204     auto *LAA = &getAnalysis<LoopAccessLegacyAnalysis>();
2205     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
2206     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
2207     auto *PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
2208 
2209     std::function<const LoopAccessInfo &(Loop &)> GetLAA =
2210         [&](Loop &L) -> const LoopAccessInfo & { return LAA->getInfo(&L); };
2211 
2212     return Impl.runImpl(F, *SE, *LI, *TTI, *DT, *BFI, TLI, *DB, *AA, *AC,
2213                         GetLAA, *ORE, PSI).MadeAnyChange;
2214   }
2215 
2216   void getAnalysisUsage(AnalysisUsage &AU) const override {
2217     AU.addRequired<AssumptionCacheTracker>();
2218     AU.addRequired<BlockFrequencyInfoWrapperPass>();
2219     AU.addRequired<DominatorTreeWrapperPass>();
2220     AU.addRequired<LoopInfoWrapperPass>();
2221     AU.addRequired<ScalarEvolutionWrapperPass>();
2222     AU.addRequired<TargetTransformInfoWrapperPass>();
2223     AU.addRequired<AAResultsWrapperPass>();
2224     AU.addRequired<LoopAccessLegacyAnalysis>();
2225     AU.addRequired<DemandedBitsWrapperPass>();
2226     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
2227     AU.addRequired<InjectTLIMappingsLegacy>();
2228 
2229     // We currently do not preserve loopinfo/dominator analyses with outer loop
2230     // vectorization. Until this is addressed, mark these analyses as preserved
2231     // only for non-VPlan-native path.
2232     // TODO: Preserve Loop and Dominator analyses for VPlan-native path.
2233     if (!EnableVPlanNativePath) {
2234       AU.addPreserved<LoopInfoWrapperPass>();
2235       AU.addPreserved<DominatorTreeWrapperPass>();
2236     }
2237 
2238     AU.addPreserved<BasicAAWrapperPass>();
2239     AU.addPreserved<GlobalsAAWrapperPass>();
2240     AU.addRequired<ProfileSummaryInfoWrapperPass>();
2241   }
2242 };
2243 
2244 } // end anonymous namespace
2245 
2246 //===----------------------------------------------------------------------===//
2247 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
2248 // LoopVectorizationCostModel and LoopVectorizationPlanner.
2249 //===----------------------------------------------------------------------===//
2250 
2251 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
2252   // We need to place the broadcast of invariant variables outside the loop,
2253   // but only if it's proven safe to do so. Else, broadcast will be inside
2254   // vector loop body.
2255   Instruction *Instr = dyn_cast<Instruction>(V);
2256   bool SafeToHoist = OrigLoop->isLoopInvariant(V) &&
2257                      (!Instr ||
2258                       DT->dominates(Instr->getParent(), LoopVectorPreHeader));
2259   // Place the code for broadcasting invariant variables in the new preheader.
2260   IRBuilder<>::InsertPointGuard Guard(Builder);
2261   if (SafeToHoist)
2262     Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
2263 
2264   // Broadcast the scalar into all locations in the vector.
2265   Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
2266 
2267   return Shuf;
2268 }
2269 
2270 void InnerLoopVectorizer::createVectorIntOrFpInductionPHI(
2271     const InductionDescriptor &II, Value *Step, Value *Start,
2272     Instruction *EntryVal, VPValue *Def, VPValue *CastDef,
2273     VPTransformState &State) {
2274   assert((isa<PHINode>(EntryVal) || isa<TruncInst>(EntryVal)) &&
2275          "Expected either an induction phi-node or a truncate of it!");
2276 
2277   // Construct the initial value of the vector IV in the vector loop preheader
2278   auto CurrIP = Builder.saveIP();
2279   Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
2280   if (isa<TruncInst>(EntryVal)) {
2281     assert(Start->getType()->isIntegerTy() &&
2282            "Truncation requires an integer type");
2283     auto *TruncType = cast<IntegerType>(EntryVal->getType());
2284     Step = Builder.CreateTrunc(Step, TruncType);
2285     Start = Builder.CreateCast(Instruction::Trunc, Start, TruncType);
2286   }
2287   Value *SplatStart = Builder.CreateVectorSplat(VF, Start);
2288   Value *SteppedStart =
2289       getStepVector(SplatStart, 0, Step, II.getInductionOpcode());
2290 
2291   // We create vector phi nodes for both integer and floating-point induction
2292   // variables. Here, we determine the kind of arithmetic we will perform.
2293   Instruction::BinaryOps AddOp;
2294   Instruction::BinaryOps MulOp;
2295   if (Step->getType()->isIntegerTy()) {
2296     AddOp = Instruction::Add;
2297     MulOp = Instruction::Mul;
2298   } else {
2299     AddOp = II.getInductionOpcode();
2300     MulOp = Instruction::FMul;
2301   }
2302 
2303   // Multiply the vectorization factor by the step using integer or
2304   // floating-point arithmetic as appropriate.
2305   Type *StepType = Step->getType();
2306   if (Step->getType()->isFloatingPointTy())
2307     StepType = IntegerType::get(StepType->getContext(),
2308                                 StepType->getScalarSizeInBits());
2309   Value *RuntimeVF = getRuntimeVF(Builder, StepType, VF);
2310   if (Step->getType()->isFloatingPointTy())
2311     RuntimeVF = Builder.CreateSIToFP(RuntimeVF, Step->getType());
2312   Value *Mul = Builder.CreateBinOp(MulOp, Step, RuntimeVF);
2313 
2314   // Create a vector splat to use in the induction update.
2315   //
2316   // FIXME: If the step is non-constant, we create the vector splat with
2317   //        IRBuilder. IRBuilder can constant-fold the multiply, but it doesn't
2318   //        handle a constant vector splat.
2319   Value *SplatVF = isa<Constant>(Mul)
2320                        ? ConstantVector::getSplat(VF, cast<Constant>(Mul))
2321                        : Builder.CreateVectorSplat(VF, Mul);
2322   Builder.restoreIP(CurrIP);
2323 
2324   // We may need to add the step a number of times, depending on the unroll
2325   // factor. The last of those goes into the PHI.
2326   PHINode *VecInd = PHINode::Create(SteppedStart->getType(), 2, "vec.ind",
2327                                     &*LoopVectorBody->getFirstInsertionPt());
2328   VecInd->setDebugLoc(EntryVal->getDebugLoc());
2329   Instruction *LastInduction = VecInd;
2330   for (unsigned Part = 0; Part < UF; ++Part) {
2331     State.set(Def, LastInduction, Part);
2332 
2333     if (isa<TruncInst>(EntryVal))
2334       addMetadata(LastInduction, EntryVal);
2335     recordVectorLoopValueForInductionCast(II, EntryVal, LastInduction, CastDef,
2336                                           State, Part);
2337 
2338     LastInduction = cast<Instruction>(
2339         Builder.CreateBinOp(AddOp, LastInduction, SplatVF, "step.add"));
2340     LastInduction->setDebugLoc(EntryVal->getDebugLoc());
2341   }
2342 
2343   // Move the last step to the end of the latch block. This ensures consistent
2344   // placement of all induction updates.
2345   auto *LoopVectorLatch = LI->getLoopFor(LoopVectorBody)->getLoopLatch();
2346   auto *Br = cast<BranchInst>(LoopVectorLatch->getTerminator());
2347   auto *ICmp = cast<Instruction>(Br->getCondition());
2348   LastInduction->moveBefore(ICmp);
2349   LastInduction->setName("vec.ind.next");
2350 
2351   VecInd->addIncoming(SteppedStart, LoopVectorPreHeader);
2352   VecInd->addIncoming(LastInduction, LoopVectorLatch);
2353 }
2354 
2355 bool InnerLoopVectorizer::shouldScalarizeInstruction(Instruction *I) const {
2356   return Cost->isScalarAfterVectorization(I, VF) ||
2357          Cost->isProfitableToScalarize(I, VF);
2358 }
2359 
2360 bool InnerLoopVectorizer::needsScalarInduction(Instruction *IV) const {
2361   if (shouldScalarizeInstruction(IV))
2362     return true;
2363   auto isScalarInst = [&](User *U) -> bool {
2364     auto *I = cast<Instruction>(U);
2365     return (OrigLoop->contains(I) && shouldScalarizeInstruction(I));
2366   };
2367   return llvm::any_of(IV->users(), isScalarInst);
2368 }
2369 
2370 void InnerLoopVectorizer::recordVectorLoopValueForInductionCast(
2371     const InductionDescriptor &ID, const Instruction *EntryVal,
2372     Value *VectorLoopVal, VPValue *CastDef, VPTransformState &State,
2373     unsigned Part, unsigned Lane) {
2374   assert((isa<PHINode>(EntryVal) || isa<TruncInst>(EntryVal)) &&
2375          "Expected either an induction phi-node or a truncate of it!");
2376 
2377   // This induction variable is not the phi from the original loop but the
2378   // newly-created IV based on the proof that casted Phi is equal to the
2379   // uncasted Phi in the vectorized loop (under a runtime guard possibly). It
2380   // re-uses the same InductionDescriptor that original IV uses but we don't
2381   // have to do any recording in this case - that is done when original IV is
2382   // processed.
2383   if (isa<TruncInst>(EntryVal))
2384     return;
2385 
2386   const SmallVectorImpl<Instruction *> &Casts = ID.getCastInsts();
2387   if (Casts.empty())
2388     return;
2389   // Only the first Cast instruction in the Casts vector is of interest.
2390   // The rest of the Casts (if exist) have no uses outside the
2391   // induction update chain itself.
2392   if (Lane < UINT_MAX)
2393     State.set(CastDef, VectorLoopVal, VPIteration(Part, Lane));
2394   else
2395     State.set(CastDef, VectorLoopVal, Part);
2396 }
2397 
2398 void InnerLoopVectorizer::widenIntOrFpInduction(PHINode *IV, Value *Start,
2399                                                 TruncInst *Trunc, VPValue *Def,
2400                                                 VPValue *CastDef,
2401                                                 VPTransformState &State) {
2402   assert((IV->getType()->isIntegerTy() || IV != OldInduction) &&
2403          "Primary induction variable must have an integer type");
2404 
2405   auto II = Legal->getInductionVars().find(IV);
2406   assert(II != Legal->getInductionVars().end() && "IV is not an induction");
2407 
2408   auto ID = II->second;
2409   assert(IV->getType() == ID.getStartValue()->getType() && "Types must match");
2410 
2411   // The value from the original loop to which we are mapping the new induction
2412   // variable.
2413   Instruction *EntryVal = Trunc ? cast<Instruction>(Trunc) : IV;
2414 
2415   auto &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
2416 
2417   // Generate code for the induction step. Note that induction steps are
2418   // required to be loop-invariant
2419   auto CreateStepValue = [&](const SCEV *Step) -> Value * {
2420     assert(PSE.getSE()->isLoopInvariant(Step, OrigLoop) &&
2421            "Induction step should be loop invariant");
2422     if (PSE.getSE()->isSCEVable(IV->getType())) {
2423       SCEVExpander Exp(*PSE.getSE(), DL, "induction");
2424       return Exp.expandCodeFor(Step, Step->getType(),
2425                                LoopVectorPreHeader->getTerminator());
2426     }
2427     return cast<SCEVUnknown>(Step)->getValue();
2428   };
2429 
2430   // The scalar value to broadcast. This is derived from the canonical
2431   // induction variable. If a truncation type is given, truncate the canonical
2432   // induction variable and step. Otherwise, derive these values from the
2433   // induction descriptor.
2434   auto CreateScalarIV = [&](Value *&Step) -> Value * {
2435     Value *ScalarIV = Induction;
2436     if (IV != OldInduction) {
2437       ScalarIV = IV->getType()->isIntegerTy()
2438                      ? Builder.CreateSExtOrTrunc(Induction, IV->getType())
2439                      : Builder.CreateCast(Instruction::SIToFP, Induction,
2440                                           IV->getType());
2441       ScalarIV = emitTransformedIndex(Builder, ScalarIV, PSE.getSE(), DL, ID);
2442       ScalarIV->setName("offset.idx");
2443     }
2444     if (Trunc) {
2445       auto *TruncType = cast<IntegerType>(Trunc->getType());
2446       assert(Step->getType()->isIntegerTy() &&
2447              "Truncation requires an integer step");
2448       ScalarIV = Builder.CreateTrunc(ScalarIV, TruncType);
2449       Step = Builder.CreateTrunc(Step, TruncType);
2450     }
2451     return ScalarIV;
2452   };
2453 
2454   // Create the vector values from the scalar IV, in the absence of creating a
2455   // vector IV.
2456   auto CreateSplatIV = [&](Value *ScalarIV, Value *Step) {
2457     Value *Broadcasted = getBroadcastInstrs(ScalarIV);
2458     for (unsigned Part = 0; Part < UF; ++Part) {
2459       assert(!VF.isScalable() && "scalable vectors not yet supported.");
2460       Value *EntryPart =
2461           getStepVector(Broadcasted, VF.getKnownMinValue() * Part, Step,
2462                         ID.getInductionOpcode());
2463       State.set(Def, EntryPart, Part);
2464       if (Trunc)
2465         addMetadata(EntryPart, Trunc);
2466       recordVectorLoopValueForInductionCast(ID, EntryVal, EntryPart, CastDef,
2467                                             State, Part);
2468     }
2469   };
2470 
2471   // Fast-math-flags propagate from the original induction instruction.
2472   IRBuilder<>::FastMathFlagGuard FMFG(Builder);
2473   if (ID.getInductionBinOp() && isa<FPMathOperator>(ID.getInductionBinOp()))
2474     Builder.setFastMathFlags(ID.getInductionBinOp()->getFastMathFlags());
2475 
2476   // Now do the actual transformations, and start with creating the step value.
2477   Value *Step = CreateStepValue(ID.getStep());
2478   if (VF.isZero() || VF.isScalar()) {
2479     Value *ScalarIV = CreateScalarIV(Step);
2480     CreateSplatIV(ScalarIV, Step);
2481     return;
2482   }
2483 
2484   // Determine if we want a scalar version of the induction variable. This is
2485   // true if the induction variable itself is not widened, or if it has at
2486   // least one user in the loop that is not widened.
2487   auto NeedsScalarIV = needsScalarInduction(EntryVal);
2488   if (!NeedsScalarIV) {
2489     createVectorIntOrFpInductionPHI(ID, Step, Start, EntryVal, Def, CastDef,
2490                                     State);
2491     return;
2492   }
2493 
2494   // Try to create a new independent vector induction variable. If we can't
2495   // create the phi node, we will splat the scalar induction variable in each
2496   // loop iteration.
2497   if (!shouldScalarizeInstruction(EntryVal)) {
2498     createVectorIntOrFpInductionPHI(ID, Step, Start, EntryVal, Def, CastDef,
2499                                     State);
2500     Value *ScalarIV = CreateScalarIV(Step);
2501     // Create scalar steps that can be used by instructions we will later
2502     // scalarize. Note that the addition of the scalar steps will not increase
2503     // the number of instructions in the loop in the common case prior to
2504     // InstCombine. We will be trading one vector extract for each scalar step.
2505     buildScalarSteps(ScalarIV, Step, EntryVal, ID, Def, CastDef, State);
2506     return;
2507   }
2508 
2509   // All IV users are scalar instructions, so only emit a scalar IV, not a
2510   // vectorised IV. Except when we tail-fold, then the splat IV feeds the
2511   // predicate used by the masked loads/stores.
2512   Value *ScalarIV = CreateScalarIV(Step);
2513   if (!Cost->isScalarEpilogueAllowed())
2514     CreateSplatIV(ScalarIV, Step);
2515   buildScalarSteps(ScalarIV, Step, EntryVal, ID, Def, CastDef, State);
2516 }
2517 
2518 Value *InnerLoopVectorizer::getStepVector(Value *Val, int StartIdx, Value *Step,
2519                                           Instruction::BinaryOps BinOp) {
2520   // Create and check the types.
2521   auto *ValVTy = cast<VectorType>(Val->getType());
2522   ElementCount VLen = ValVTy->getElementCount();
2523 
2524   Type *STy = Val->getType()->getScalarType();
2525   assert((STy->isIntegerTy() || STy->isFloatingPointTy()) &&
2526          "Induction Step must be an integer or FP");
2527   assert(Step->getType() == STy && "Step has wrong type");
2528 
2529   SmallVector<Constant *, 8> Indices;
2530 
2531   // Create a vector of consecutive numbers from zero to VF.
2532   VectorType *InitVecValVTy = ValVTy;
2533   Type *InitVecValSTy = STy;
2534   if (STy->isFloatingPointTy()) {
2535     InitVecValSTy =
2536         IntegerType::get(STy->getContext(), STy->getScalarSizeInBits());
2537     InitVecValVTy = VectorType::get(InitVecValSTy, VLen);
2538   }
2539   Value *InitVec = Builder.CreateStepVector(InitVecValVTy);
2540 
2541   // Add on StartIdx
2542   Value *StartIdxSplat = Builder.CreateVectorSplat(
2543       VLen, ConstantInt::get(InitVecValSTy, StartIdx));
2544   InitVec = Builder.CreateAdd(InitVec, StartIdxSplat);
2545 
2546   if (STy->isIntegerTy()) {
2547     Step = Builder.CreateVectorSplat(VLen, Step);
2548     assert(Step->getType() == Val->getType() && "Invalid step vec");
2549     // FIXME: The newly created binary instructions should contain nsw/nuw flags,
2550     // which can be found from the original scalar operations.
2551     Step = Builder.CreateMul(InitVec, Step);
2552     return Builder.CreateAdd(Val, Step, "induction");
2553   }
2554 
2555   // Floating point induction.
2556   assert((BinOp == Instruction::FAdd || BinOp == Instruction::FSub) &&
2557          "Binary Opcode should be specified for FP induction");
2558   InitVec = Builder.CreateUIToFP(InitVec, ValVTy);
2559   Step = Builder.CreateVectorSplat(VLen, Step);
2560   Value *MulOp = Builder.CreateFMul(InitVec, Step);
2561   return Builder.CreateBinOp(BinOp, Val, MulOp, "induction");
2562 }
2563 
2564 void InnerLoopVectorizer::buildScalarSteps(Value *ScalarIV, Value *Step,
2565                                            Instruction *EntryVal,
2566                                            const InductionDescriptor &ID,
2567                                            VPValue *Def, VPValue *CastDef,
2568                                            VPTransformState &State) {
2569   // We shouldn't have to build scalar steps if we aren't vectorizing.
2570   assert(VF.isVector() && "VF should be greater than one");
2571   // Get the value type and ensure it and the step have the same integer type.
2572   Type *ScalarIVTy = ScalarIV->getType()->getScalarType();
2573   assert(ScalarIVTy == Step->getType() &&
2574          "Val and Step should have the same type");
2575 
2576   // We build scalar steps for both integer and floating-point induction
2577   // variables. Here, we determine the kind of arithmetic we will perform.
2578   Instruction::BinaryOps AddOp;
2579   Instruction::BinaryOps MulOp;
2580   if (ScalarIVTy->isIntegerTy()) {
2581     AddOp = Instruction::Add;
2582     MulOp = Instruction::Mul;
2583   } else {
2584     AddOp = ID.getInductionOpcode();
2585     MulOp = Instruction::FMul;
2586   }
2587 
2588   // Determine the number of scalars we need to generate for each unroll
2589   // iteration. If EntryVal is uniform, we only need to generate the first
2590   // lane. Otherwise, we generate all VF values.
2591   bool IsUniform =
2592       Cost->isUniformAfterVectorization(cast<Instruction>(EntryVal), VF);
2593   unsigned Lanes = IsUniform ? 1 : VF.getKnownMinValue();
2594   // Compute the scalar steps and save the results in State.
2595   Type *IntStepTy = IntegerType::get(ScalarIVTy->getContext(),
2596                                      ScalarIVTy->getScalarSizeInBits());
2597   Type *VecIVTy = nullptr;
2598   Value *UnitStepVec = nullptr, *SplatStep = nullptr, *SplatIV = nullptr;
2599   if (!IsUniform && VF.isScalable()) {
2600     VecIVTy = VectorType::get(ScalarIVTy, VF);
2601     UnitStepVec = Builder.CreateStepVector(VectorType::get(IntStepTy, VF));
2602     SplatStep = Builder.CreateVectorSplat(VF, Step);
2603     SplatIV = Builder.CreateVectorSplat(VF, ScalarIV);
2604   }
2605 
2606   for (unsigned Part = 0; Part < UF; ++Part) {
2607     Value *StartIdx0 =
2608         createStepForVF(Builder, ConstantInt::get(IntStepTy, Part), VF);
2609 
2610     if (!IsUniform && VF.isScalable()) {
2611       auto *SplatStartIdx = Builder.CreateVectorSplat(VF, StartIdx0);
2612       auto *InitVec = Builder.CreateAdd(SplatStartIdx, UnitStepVec);
2613       if (ScalarIVTy->isFloatingPointTy())
2614         InitVec = Builder.CreateSIToFP(InitVec, VecIVTy);
2615       auto *Mul = Builder.CreateBinOp(MulOp, InitVec, SplatStep);
2616       auto *Add = Builder.CreateBinOp(AddOp, SplatIV, Mul);
2617       State.set(Def, Add, Part);
2618       recordVectorLoopValueForInductionCast(ID, EntryVal, Add, CastDef, State,
2619                                             Part);
2620       // It's useful to record the lane values too for the known minimum number
2621       // of elements so we do those below. This improves the code quality when
2622       // trying to extract the first element, for example.
2623     }
2624 
2625     if (ScalarIVTy->isFloatingPointTy())
2626       StartIdx0 = Builder.CreateSIToFP(StartIdx0, ScalarIVTy);
2627 
2628     for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
2629       Value *StartIdx = Builder.CreateBinOp(
2630           AddOp, StartIdx0, getSignedIntOrFpConstant(ScalarIVTy, Lane));
2631       // The step returned by `createStepForVF` is a runtime-evaluated value
2632       // when VF is scalable. Otherwise, it should be folded into a Constant.
2633       assert((VF.isScalable() || isa<Constant>(StartIdx)) &&
2634              "Expected StartIdx to be folded to a constant when VF is not "
2635              "scalable");
2636       auto *Mul = Builder.CreateBinOp(MulOp, StartIdx, Step);
2637       auto *Add = Builder.CreateBinOp(AddOp, ScalarIV, Mul);
2638       State.set(Def, Add, VPIteration(Part, Lane));
2639       recordVectorLoopValueForInductionCast(ID, EntryVal, Add, CastDef, State,
2640                                             Part, Lane);
2641     }
2642   }
2643 }
2644 
2645 void InnerLoopVectorizer::packScalarIntoVectorValue(VPValue *Def,
2646                                                     const VPIteration &Instance,
2647                                                     VPTransformState &State) {
2648   Value *ScalarInst = State.get(Def, Instance);
2649   Value *VectorValue = State.get(Def, Instance.Part);
2650   VectorValue = Builder.CreateInsertElement(
2651       VectorValue, ScalarInst,
2652       Instance.Lane.getAsRuntimeExpr(State.Builder, VF));
2653   State.set(Def, VectorValue, Instance.Part);
2654 }
2655 
2656 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
2657   assert(Vec->getType()->isVectorTy() && "Invalid type");
2658   return Builder.CreateVectorReverse(Vec, "reverse");
2659 }
2660 
2661 // Return whether we allow using masked interleave-groups (for dealing with
2662 // strided loads/stores that reside in predicated blocks, or for dealing
2663 // with gaps).
2664 static bool useMaskedInterleavedAccesses(const TargetTransformInfo &TTI) {
2665   // If an override option has been passed in for interleaved accesses, use it.
2666   if (EnableMaskedInterleavedMemAccesses.getNumOccurrences() > 0)
2667     return EnableMaskedInterleavedMemAccesses;
2668 
2669   return TTI.enableMaskedInterleavedAccessVectorization();
2670 }
2671 
2672 // Try to vectorize the interleave group that \p Instr belongs to.
2673 //
2674 // E.g. Translate following interleaved load group (factor = 3):
2675 //   for (i = 0; i < N; i+=3) {
2676 //     R = Pic[i];             // Member of index 0
2677 //     G = Pic[i+1];           // Member of index 1
2678 //     B = Pic[i+2];           // Member of index 2
2679 //     ... // do something to R, G, B
2680 //   }
2681 // To:
2682 //   %wide.vec = load <12 x i32>                       ; Read 4 tuples of R,G,B
2683 //   %R.vec = shuffle %wide.vec, poison, <0, 3, 6, 9>   ; R elements
2684 //   %G.vec = shuffle %wide.vec, poison, <1, 4, 7, 10>  ; G elements
2685 //   %B.vec = shuffle %wide.vec, poison, <2, 5, 8, 11>  ; B elements
2686 //
2687 // Or translate following interleaved store group (factor = 3):
2688 //   for (i = 0; i < N; i+=3) {
2689 //     ... do something to R, G, B
2690 //     Pic[i]   = R;           // Member of index 0
2691 //     Pic[i+1] = G;           // Member of index 1
2692 //     Pic[i+2] = B;           // Member of index 2
2693 //   }
2694 // To:
2695 //   %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
2696 //   %B_U.vec = shuffle %B.vec, poison, <0, 1, 2, 3, u, u, u, u>
2697 //   %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
2698 //        <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>    ; Interleave R,G,B elements
2699 //   store <12 x i32> %interleaved.vec              ; Write 4 tuples of R,G,B
2700 void InnerLoopVectorizer::vectorizeInterleaveGroup(
2701     const InterleaveGroup<Instruction> *Group, ArrayRef<VPValue *> VPDefs,
2702     VPTransformState &State, VPValue *Addr, ArrayRef<VPValue *> StoredValues,
2703     VPValue *BlockInMask) {
2704   Instruction *Instr = Group->getInsertPos();
2705   const DataLayout &DL = Instr->getModule()->getDataLayout();
2706 
2707   // Prepare for the vector type of the interleaved load/store.
2708   Type *ScalarTy = getLoadStoreType(Instr);
2709   unsigned InterleaveFactor = Group->getFactor();
2710   assert(!VF.isScalable() && "scalable vectors not yet supported.");
2711   auto *VecTy = VectorType::get(ScalarTy, VF * InterleaveFactor);
2712 
2713   // Prepare for the new pointers.
2714   SmallVector<Value *, 2> AddrParts;
2715   unsigned Index = Group->getIndex(Instr);
2716 
2717   // TODO: extend the masked interleaved-group support to reversed access.
2718   assert((!BlockInMask || !Group->isReverse()) &&
2719          "Reversed masked interleave-group not supported.");
2720 
2721   // If the group is reverse, adjust the index to refer to the last vector lane
2722   // instead of the first. We adjust the index from the first vector lane,
2723   // rather than directly getting the pointer for lane VF - 1, because the
2724   // pointer operand of the interleaved access is supposed to be uniform. For
2725   // uniform instructions, we're only required to generate a value for the
2726   // first vector lane in each unroll iteration.
2727   if (Group->isReverse())
2728     Index += (VF.getKnownMinValue() - 1) * Group->getFactor();
2729 
2730   for (unsigned Part = 0; Part < UF; Part++) {
2731     Value *AddrPart = State.get(Addr, VPIteration(Part, 0));
2732     setDebugLocFromInst(AddrPart);
2733 
2734     // Notice current instruction could be any index. Need to adjust the address
2735     // to the member of index 0.
2736     //
2737     // E.g.  a = A[i+1];     // Member of index 1 (Current instruction)
2738     //       b = A[i];       // Member of index 0
2739     // Current pointer is pointed to A[i+1], adjust it to A[i].
2740     //
2741     // E.g.  A[i+1] = a;     // Member of index 1
2742     //       A[i]   = b;     // Member of index 0
2743     //       A[i+2] = c;     // Member of index 2 (Current instruction)
2744     // Current pointer is pointed to A[i+2], adjust it to A[i].
2745 
2746     bool InBounds = false;
2747     if (auto *gep = dyn_cast<GetElementPtrInst>(AddrPart->stripPointerCasts()))
2748       InBounds = gep->isInBounds();
2749     AddrPart = Builder.CreateGEP(ScalarTy, AddrPart, Builder.getInt32(-Index));
2750     cast<GetElementPtrInst>(AddrPart)->setIsInBounds(InBounds);
2751 
2752     // Cast to the vector pointer type.
2753     unsigned AddressSpace = AddrPart->getType()->getPointerAddressSpace();
2754     Type *PtrTy = VecTy->getPointerTo(AddressSpace);
2755     AddrParts.push_back(Builder.CreateBitCast(AddrPart, PtrTy));
2756   }
2757 
2758   setDebugLocFromInst(Instr);
2759   Value *PoisonVec = PoisonValue::get(VecTy);
2760 
2761   Value *MaskForGaps = nullptr;
2762   if (Group->requiresScalarEpilogue() && !Cost->isScalarEpilogueAllowed()) {
2763     MaskForGaps = createBitMaskForGaps(Builder, VF.getKnownMinValue(), *Group);
2764     assert(MaskForGaps && "Mask for Gaps is required but it is null");
2765   }
2766 
2767   // Vectorize the interleaved load group.
2768   if (isa<LoadInst>(Instr)) {
2769     // For each unroll part, create a wide load for the group.
2770     SmallVector<Value *, 2> NewLoads;
2771     for (unsigned Part = 0; Part < UF; Part++) {
2772       Instruction *NewLoad;
2773       if (BlockInMask || MaskForGaps) {
2774         assert(useMaskedInterleavedAccesses(*TTI) &&
2775                "masked interleaved groups are not allowed.");
2776         Value *GroupMask = MaskForGaps;
2777         if (BlockInMask) {
2778           Value *BlockInMaskPart = State.get(BlockInMask, Part);
2779           Value *ShuffledMask = Builder.CreateShuffleVector(
2780               BlockInMaskPart,
2781               createReplicatedMask(InterleaveFactor, VF.getKnownMinValue()),
2782               "interleaved.mask");
2783           GroupMask = MaskForGaps
2784                           ? Builder.CreateBinOp(Instruction::And, ShuffledMask,
2785                                                 MaskForGaps)
2786                           : ShuffledMask;
2787         }
2788         NewLoad =
2789             Builder.CreateMaskedLoad(VecTy, AddrParts[Part], Group->getAlign(),
2790                                      GroupMask, PoisonVec, "wide.masked.vec");
2791       }
2792       else
2793         NewLoad = Builder.CreateAlignedLoad(VecTy, AddrParts[Part],
2794                                             Group->getAlign(), "wide.vec");
2795       Group->addMetadata(NewLoad);
2796       NewLoads.push_back(NewLoad);
2797     }
2798 
2799     // For each member in the group, shuffle out the appropriate data from the
2800     // wide loads.
2801     unsigned J = 0;
2802     for (unsigned I = 0; I < InterleaveFactor; ++I) {
2803       Instruction *Member = Group->getMember(I);
2804 
2805       // Skip the gaps in the group.
2806       if (!Member)
2807         continue;
2808 
2809       auto StrideMask =
2810           createStrideMask(I, InterleaveFactor, VF.getKnownMinValue());
2811       for (unsigned Part = 0; Part < UF; Part++) {
2812         Value *StridedVec = Builder.CreateShuffleVector(
2813             NewLoads[Part], StrideMask, "strided.vec");
2814 
2815         // If this member has different type, cast the result type.
2816         if (Member->getType() != ScalarTy) {
2817           assert(!VF.isScalable() && "VF is assumed to be non scalable.");
2818           VectorType *OtherVTy = VectorType::get(Member->getType(), VF);
2819           StridedVec = createBitOrPointerCast(StridedVec, OtherVTy, DL);
2820         }
2821 
2822         if (Group->isReverse())
2823           StridedVec = reverseVector(StridedVec);
2824 
2825         State.set(VPDefs[J], StridedVec, Part);
2826       }
2827       ++J;
2828     }
2829     return;
2830   }
2831 
2832   // The sub vector type for current instruction.
2833   auto *SubVT = VectorType::get(ScalarTy, VF);
2834 
2835   // Vectorize the interleaved store group.
2836   for (unsigned Part = 0; Part < UF; Part++) {
2837     // Collect the stored vector from each member.
2838     SmallVector<Value *, 4> StoredVecs;
2839     for (unsigned i = 0; i < InterleaveFactor; i++) {
2840       // Interleaved store group doesn't allow a gap, so each index has a member
2841       assert(Group->getMember(i) && "Fail to get a member from an interleaved store group");
2842 
2843       Value *StoredVec = State.get(StoredValues[i], Part);
2844 
2845       if (Group->isReverse())
2846         StoredVec = reverseVector(StoredVec);
2847 
2848       // If this member has different type, cast it to a unified type.
2849 
2850       if (StoredVec->getType() != SubVT)
2851         StoredVec = createBitOrPointerCast(StoredVec, SubVT, DL);
2852 
2853       StoredVecs.push_back(StoredVec);
2854     }
2855 
2856     // Concatenate all vectors into a wide vector.
2857     Value *WideVec = concatenateVectors(Builder, StoredVecs);
2858 
2859     // Interleave the elements in the wide vector.
2860     Value *IVec = Builder.CreateShuffleVector(
2861         WideVec, createInterleaveMask(VF.getKnownMinValue(), InterleaveFactor),
2862         "interleaved.vec");
2863 
2864     Instruction *NewStoreInstr;
2865     if (BlockInMask) {
2866       Value *BlockInMaskPart = State.get(BlockInMask, Part);
2867       Value *ShuffledMask = Builder.CreateShuffleVector(
2868           BlockInMaskPart,
2869           createReplicatedMask(InterleaveFactor, VF.getKnownMinValue()),
2870           "interleaved.mask");
2871       NewStoreInstr = Builder.CreateMaskedStore(
2872           IVec, AddrParts[Part], Group->getAlign(), ShuffledMask);
2873     }
2874     else
2875       NewStoreInstr =
2876           Builder.CreateAlignedStore(IVec, AddrParts[Part], Group->getAlign());
2877 
2878     Group->addMetadata(NewStoreInstr);
2879   }
2880 }
2881 
2882 void InnerLoopVectorizer::vectorizeMemoryInstruction(
2883     Instruction *Instr, VPTransformState &State, VPValue *Def, VPValue *Addr,
2884     VPValue *StoredValue, VPValue *BlockInMask) {
2885   // Attempt to issue a wide load.
2886   LoadInst *LI = dyn_cast<LoadInst>(Instr);
2887   StoreInst *SI = dyn_cast<StoreInst>(Instr);
2888 
2889   assert((LI || SI) && "Invalid Load/Store instruction");
2890   assert((!SI || StoredValue) && "No stored value provided for widened store");
2891   assert((!LI || !StoredValue) && "Stored value provided for widened load");
2892 
2893   LoopVectorizationCostModel::InstWidening Decision =
2894       Cost->getWideningDecision(Instr, VF);
2895   assert((Decision == LoopVectorizationCostModel::CM_Widen ||
2896           Decision == LoopVectorizationCostModel::CM_Widen_Reverse ||
2897           Decision == LoopVectorizationCostModel::CM_GatherScatter) &&
2898          "CM decision is not to widen the memory instruction");
2899 
2900   Type *ScalarDataTy = getLoadStoreType(Instr);
2901 
2902   auto *DataTy = VectorType::get(ScalarDataTy, VF);
2903   const Align Alignment = getLoadStoreAlignment(Instr);
2904 
2905   // Determine if the pointer operand of the access is either consecutive or
2906   // reverse consecutive.
2907   bool Reverse = (Decision == LoopVectorizationCostModel::CM_Widen_Reverse);
2908   bool ConsecutiveStride =
2909       Reverse || (Decision == LoopVectorizationCostModel::CM_Widen);
2910   bool CreateGatherScatter =
2911       (Decision == LoopVectorizationCostModel::CM_GatherScatter);
2912 
2913   // Either Ptr feeds a vector load/store, or a vector GEP should feed a vector
2914   // gather/scatter. Otherwise Decision should have been to Scalarize.
2915   assert((ConsecutiveStride || CreateGatherScatter) &&
2916          "The instruction should be scalarized");
2917   (void)ConsecutiveStride;
2918 
2919   VectorParts BlockInMaskParts(UF);
2920   bool isMaskRequired = BlockInMask;
2921   if (isMaskRequired)
2922     for (unsigned Part = 0; Part < UF; ++Part)
2923       BlockInMaskParts[Part] = State.get(BlockInMask, Part);
2924 
2925   const auto CreateVecPtr = [&](unsigned Part, Value *Ptr) -> Value * {
2926     // Calculate the pointer for the specific unroll-part.
2927     GetElementPtrInst *PartPtr = nullptr;
2928 
2929     bool InBounds = false;
2930     if (auto *gep = dyn_cast<GetElementPtrInst>(Ptr->stripPointerCasts()))
2931       InBounds = gep->isInBounds();
2932     if (Reverse) {
2933       // If the address is consecutive but reversed, then the
2934       // wide store needs to start at the last vector element.
2935       // RunTimeVF =  VScale * VF.getKnownMinValue()
2936       // For fixed-width VScale is 1, then RunTimeVF = VF.getKnownMinValue()
2937       Value *RunTimeVF = getRuntimeVF(Builder, Builder.getInt32Ty(), VF);
2938       // NumElt = -Part * RunTimeVF
2939       Value *NumElt = Builder.CreateMul(Builder.getInt32(-Part), RunTimeVF);
2940       // LastLane = 1 - RunTimeVF
2941       Value *LastLane = Builder.CreateSub(Builder.getInt32(1), RunTimeVF);
2942       PartPtr =
2943           cast<GetElementPtrInst>(Builder.CreateGEP(ScalarDataTy, Ptr, NumElt));
2944       PartPtr->setIsInBounds(InBounds);
2945       PartPtr = cast<GetElementPtrInst>(
2946           Builder.CreateGEP(ScalarDataTy, PartPtr, LastLane));
2947       PartPtr->setIsInBounds(InBounds);
2948       if (isMaskRequired) // Reverse of a null all-one mask is a null mask.
2949         BlockInMaskParts[Part] = reverseVector(BlockInMaskParts[Part]);
2950     } else {
2951       Value *Increment = createStepForVF(Builder, Builder.getInt32(Part), VF);
2952       PartPtr = cast<GetElementPtrInst>(
2953           Builder.CreateGEP(ScalarDataTy, Ptr, Increment));
2954       PartPtr->setIsInBounds(InBounds);
2955     }
2956 
2957     unsigned AddressSpace = Ptr->getType()->getPointerAddressSpace();
2958     return Builder.CreateBitCast(PartPtr, DataTy->getPointerTo(AddressSpace));
2959   };
2960 
2961   // Handle Stores:
2962   if (SI) {
2963     setDebugLocFromInst(SI);
2964 
2965     for (unsigned Part = 0; Part < UF; ++Part) {
2966       Instruction *NewSI = nullptr;
2967       Value *StoredVal = State.get(StoredValue, Part);
2968       if (CreateGatherScatter) {
2969         Value *MaskPart = isMaskRequired ? BlockInMaskParts[Part] : nullptr;
2970         Value *VectorGep = State.get(Addr, Part);
2971         NewSI = Builder.CreateMaskedScatter(StoredVal, VectorGep, Alignment,
2972                                             MaskPart);
2973       } else {
2974         if (Reverse) {
2975           // If we store to reverse consecutive memory locations, then we need
2976           // to reverse the order of elements in the stored value.
2977           StoredVal = reverseVector(StoredVal);
2978           // We don't want to update the value in the map as it might be used in
2979           // another expression. So don't call resetVectorValue(StoredVal).
2980         }
2981         auto *VecPtr = CreateVecPtr(Part, State.get(Addr, VPIteration(0, 0)));
2982         if (isMaskRequired)
2983           NewSI = Builder.CreateMaskedStore(StoredVal, VecPtr, Alignment,
2984                                             BlockInMaskParts[Part]);
2985         else
2986           NewSI = Builder.CreateAlignedStore(StoredVal, VecPtr, Alignment);
2987       }
2988       addMetadata(NewSI, SI);
2989     }
2990     return;
2991   }
2992 
2993   // Handle loads.
2994   assert(LI && "Must have a load instruction");
2995   setDebugLocFromInst(LI);
2996   for (unsigned Part = 0; Part < UF; ++Part) {
2997     Value *NewLI;
2998     if (CreateGatherScatter) {
2999       Value *MaskPart = isMaskRequired ? BlockInMaskParts[Part] : nullptr;
3000       Value *VectorGep = State.get(Addr, Part);
3001       NewLI = Builder.CreateMaskedGather(DataTy, VectorGep, Alignment, MaskPart,
3002                                          nullptr, "wide.masked.gather");
3003       addMetadata(NewLI, LI);
3004     } else {
3005       auto *VecPtr = CreateVecPtr(Part, State.get(Addr, VPIteration(0, 0)));
3006       if (isMaskRequired)
3007         NewLI = Builder.CreateMaskedLoad(
3008             DataTy, VecPtr, Alignment, BlockInMaskParts[Part],
3009             PoisonValue::get(DataTy), "wide.masked.load");
3010       else
3011         NewLI =
3012             Builder.CreateAlignedLoad(DataTy, VecPtr, Alignment, "wide.load");
3013 
3014       // Add metadata to the load, but setVectorValue to the reverse shuffle.
3015       addMetadata(NewLI, LI);
3016       if (Reverse)
3017         NewLI = reverseVector(NewLI);
3018     }
3019 
3020     State.set(Def, NewLI, Part);
3021   }
3022 }
3023 
3024 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr, VPValue *Def,
3025                                                VPUser &User,
3026                                                const VPIteration &Instance,
3027                                                bool IfPredicateInstr,
3028                                                VPTransformState &State) {
3029   assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
3030 
3031   // llvm.experimental.noalias.scope.decl intrinsics must only be duplicated for
3032   // the first lane and part.
3033   if (isa<NoAliasScopeDeclInst>(Instr))
3034     if (!Instance.isFirstIteration())
3035       return;
3036 
3037   setDebugLocFromInst(Instr);
3038 
3039   // Does this instruction return a value ?
3040   bool IsVoidRetTy = Instr->getType()->isVoidTy();
3041 
3042   Instruction *Cloned = Instr->clone();
3043   if (!IsVoidRetTy)
3044     Cloned->setName(Instr->getName() + ".cloned");
3045 
3046   State.Builder.SetInsertPoint(Builder.GetInsertBlock(),
3047                                Builder.GetInsertPoint());
3048   // Replace the operands of the cloned instructions with their scalar
3049   // equivalents in the new loop.
3050   for (unsigned op = 0, e = User.getNumOperands(); op != e; ++op) {
3051     auto *Operand = dyn_cast<Instruction>(Instr->getOperand(op));
3052     auto InputInstance = Instance;
3053     if (!Operand || !OrigLoop->contains(Operand) ||
3054         (Cost->isUniformAfterVectorization(Operand, State.VF)))
3055       InputInstance.Lane = VPLane::getFirstLane();
3056     auto *NewOp = State.get(User.getOperand(op), InputInstance);
3057     Cloned->setOperand(op, NewOp);
3058   }
3059   addNewMetadata(Cloned, Instr);
3060 
3061   // Place the cloned scalar in the new loop.
3062   Builder.Insert(Cloned);
3063 
3064   State.set(Def, Cloned, Instance);
3065 
3066   // If we just cloned a new assumption, add it the assumption cache.
3067   if (auto *II = dyn_cast<AssumeInst>(Cloned))
3068     AC->registerAssumption(II);
3069 
3070   // End if-block.
3071   if (IfPredicateInstr)
3072     PredicatedInstructions.push_back(Cloned);
3073 }
3074 
3075 PHINode *InnerLoopVectorizer::createInductionVariable(Loop *L, Value *Start,
3076                                                       Value *End, Value *Step,
3077                                                       Instruction *DL) {
3078   BasicBlock *Header = L->getHeader();
3079   BasicBlock *Latch = L->getLoopLatch();
3080   // As we're just creating this loop, it's possible no latch exists
3081   // yet. If so, use the header as this will be a single block loop.
3082   if (!Latch)
3083     Latch = Header;
3084 
3085   IRBuilder<> B(&*Header->getFirstInsertionPt());
3086   Instruction *OldInst = getDebugLocFromInstOrOperands(OldInduction);
3087   setDebugLocFromInst(OldInst, &B);
3088   auto *Induction = B.CreatePHI(Start->getType(), 2, "index");
3089 
3090   B.SetInsertPoint(Latch->getTerminator());
3091   setDebugLocFromInst(OldInst, &B);
3092 
3093   // Create i+1 and fill the PHINode.
3094   //
3095   // If the tail is not folded, we know that End - Start >= Step (either
3096   // statically or through the minimum iteration checks). We also know that both
3097   // Start % Step == 0 and End % Step == 0. We exit the vector loop if %IV +
3098   // %Step == %End. Hence we must exit the loop before %IV + %Step unsigned
3099   // overflows and we can mark the induction increment as NUW.
3100   Value *Next = B.CreateAdd(Induction, Step, "index.next",
3101                             /*NUW=*/!Cost->foldTailByMasking(), /*NSW=*/false);
3102   Induction->addIncoming(Start, L->getLoopPreheader());
3103   Induction->addIncoming(Next, Latch);
3104   // Create the compare.
3105   Value *ICmp = B.CreateICmpEQ(Next, End);
3106   B.CreateCondBr(ICmp, L->getUniqueExitBlock(), Header);
3107 
3108   // Now we have two terminators. Remove the old one from the block.
3109   Latch->getTerminator()->eraseFromParent();
3110 
3111   return Induction;
3112 }
3113 
3114 Value *InnerLoopVectorizer::getOrCreateTripCount(Loop *L) {
3115   if (TripCount)
3116     return TripCount;
3117 
3118   assert(L && "Create Trip Count for null loop.");
3119   IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
3120   // Find the loop boundaries.
3121   ScalarEvolution *SE = PSE.getSE();
3122   const SCEV *BackedgeTakenCount = PSE.getBackedgeTakenCount();
3123   assert(!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
3124          "Invalid loop count");
3125 
3126   Type *IdxTy = Legal->getWidestInductionType();
3127   assert(IdxTy && "No type for induction");
3128 
3129   // The exit count might have the type of i64 while the phi is i32. This can
3130   // happen if we have an induction variable that is sign extended before the
3131   // compare. The only way that we get a backedge taken count is that the
3132   // induction variable was signed and as such will not overflow. In such a case
3133   // truncation is legal.
3134   if (SE->getTypeSizeInBits(BackedgeTakenCount->getType()) >
3135       IdxTy->getPrimitiveSizeInBits())
3136     BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount, IdxTy);
3137   BackedgeTakenCount = SE->getNoopOrZeroExtend(BackedgeTakenCount, IdxTy);
3138 
3139   // Get the total trip count from the count by adding 1.
3140   const SCEV *ExitCount = SE->getAddExpr(
3141       BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType()));
3142 
3143   const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
3144 
3145   // Expand the trip count and place the new instructions in the preheader.
3146   // Notice that the pre-header does not change, only the loop body.
3147   SCEVExpander Exp(*SE, DL, "induction");
3148 
3149   // Count holds the overall loop count (N).
3150   TripCount = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
3151                                 L->getLoopPreheader()->getTerminator());
3152 
3153   if (TripCount->getType()->isPointerTy())
3154     TripCount =
3155         CastInst::CreatePointerCast(TripCount, IdxTy, "exitcount.ptrcnt.to.int",
3156                                     L->getLoopPreheader()->getTerminator());
3157 
3158   return TripCount;
3159 }
3160 
3161 Value *InnerLoopVectorizer::getOrCreateVectorTripCount(Loop *L) {
3162   if (VectorTripCount)
3163     return VectorTripCount;
3164 
3165   Value *TC = getOrCreateTripCount(L);
3166   IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
3167 
3168   Type *Ty = TC->getType();
3169   // This is where we can make the step a runtime constant.
3170   Value *Step = createStepForVF(Builder, ConstantInt::get(Ty, UF), VF);
3171 
3172   // If the tail is to be folded by masking, round the number of iterations N
3173   // up to a multiple of Step instead of rounding down. This is done by first
3174   // adding Step-1 and then rounding down. Note that it's ok if this addition
3175   // overflows: the vector induction variable will eventually wrap to zero given
3176   // that it starts at zero and its Step is a power of two; the loop will then
3177   // exit, with the last early-exit vector comparison also producing all-true.
3178   if (Cost->foldTailByMasking()) {
3179     assert(isPowerOf2_32(VF.getKnownMinValue() * UF) &&
3180            "VF*UF must be a power of 2 when folding tail by masking");
3181     assert(!VF.isScalable() &&
3182            "Tail folding not yet supported for scalable vectors");
3183     TC = Builder.CreateAdd(
3184         TC, ConstantInt::get(Ty, VF.getKnownMinValue() * UF - 1), "n.rnd.up");
3185   }
3186 
3187   // Now we need to generate the expression for the part of the loop that the
3188   // vectorized body will execute. This is equal to N - (N % Step) if scalar
3189   // iterations are not required for correctness, or N - Step, otherwise. Step
3190   // is equal to the vectorization factor (number of SIMD elements) times the
3191   // unroll factor (number of SIMD instructions).
3192   Value *R = Builder.CreateURem(TC, Step, "n.mod.vf");
3193 
3194   // There are cases where we *must* run at least one iteration in the remainder
3195   // loop.  See the cost model for when this can happen.  If the step evenly
3196   // divides the trip count, we set the remainder to be equal to the step. If
3197   // the step does not evenly divide the trip count, no adjustment is necessary
3198   // since there will already be scalar iterations. Note that the minimum
3199   // iterations check ensures that N >= Step.
3200   if (Cost->requiresScalarEpilogue(VF)) {
3201     auto *IsZero = Builder.CreateICmpEQ(R, ConstantInt::get(R->getType(), 0));
3202     R = Builder.CreateSelect(IsZero, Step, R);
3203   }
3204 
3205   VectorTripCount = Builder.CreateSub(TC, R, "n.vec");
3206 
3207   return VectorTripCount;
3208 }
3209 
3210 Value *InnerLoopVectorizer::createBitOrPointerCast(Value *V, VectorType *DstVTy,
3211                                                    const DataLayout &DL) {
3212   // Verify that V is a vector type with same number of elements as DstVTy.
3213   auto *DstFVTy = cast<FixedVectorType>(DstVTy);
3214   unsigned VF = DstFVTy->getNumElements();
3215   auto *SrcVecTy = cast<FixedVectorType>(V->getType());
3216   assert((VF == SrcVecTy->getNumElements()) && "Vector dimensions do not match");
3217   Type *SrcElemTy = SrcVecTy->getElementType();
3218   Type *DstElemTy = DstFVTy->getElementType();
3219   assert((DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy)) &&
3220          "Vector elements must have same size");
3221 
3222   // Do a direct cast if element types are castable.
3223   if (CastInst::isBitOrNoopPointerCastable(SrcElemTy, DstElemTy, DL)) {
3224     return Builder.CreateBitOrPointerCast(V, DstFVTy);
3225   }
3226   // V cannot be directly casted to desired vector type.
3227   // May happen when V is a floating point vector but DstVTy is a vector of
3228   // pointers or vice-versa. Handle this using a two-step bitcast using an
3229   // intermediate Integer type for the bitcast i.e. Ptr <-> Int <-> Float.
3230   assert((DstElemTy->isPointerTy() != SrcElemTy->isPointerTy()) &&
3231          "Only one type should be a pointer type");
3232   assert((DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy()) &&
3233          "Only one type should be a floating point type");
3234   Type *IntTy =
3235       IntegerType::getIntNTy(V->getContext(), DL.getTypeSizeInBits(SrcElemTy));
3236   auto *VecIntTy = FixedVectorType::get(IntTy, VF);
3237   Value *CastVal = Builder.CreateBitOrPointerCast(V, VecIntTy);
3238   return Builder.CreateBitOrPointerCast(CastVal, DstFVTy);
3239 }
3240 
3241 void InnerLoopVectorizer::emitMinimumIterationCountCheck(Loop *L,
3242                                                          BasicBlock *Bypass) {
3243   Value *Count = getOrCreateTripCount(L);
3244   // Reuse existing vector loop preheader for TC checks.
3245   // Note that new preheader block is generated for vector loop.
3246   BasicBlock *const TCCheckBlock = LoopVectorPreHeader;
3247   IRBuilder<> Builder(TCCheckBlock->getTerminator());
3248 
3249   // Generate code to check if the loop's trip count is less than VF * UF, or
3250   // equal to it in case a scalar epilogue is required; this implies that the
3251   // vector trip count is zero. This check also covers the case where adding one
3252   // to the backedge-taken count overflowed leading to an incorrect trip count
3253   // of zero. In this case we will also jump to the scalar loop.
3254   auto P = Cost->requiresScalarEpilogue(VF) ? ICmpInst::ICMP_ULE
3255                                             : ICmpInst::ICMP_ULT;
3256 
3257   // If tail is to be folded, vector loop takes care of all iterations.
3258   Value *CheckMinIters = Builder.getFalse();
3259   if (!Cost->foldTailByMasking()) {
3260     Value *Step =
3261         createStepForVF(Builder, ConstantInt::get(Count->getType(), UF), VF);
3262     CheckMinIters = Builder.CreateICmp(P, Count, Step, "min.iters.check");
3263   }
3264   // Create new preheader for vector loop.
3265   LoopVectorPreHeader =
3266       SplitBlock(TCCheckBlock, TCCheckBlock->getTerminator(), DT, LI, nullptr,
3267                  "vector.ph");
3268 
3269   assert(DT->properlyDominates(DT->getNode(TCCheckBlock),
3270                                DT->getNode(Bypass)->getIDom()) &&
3271          "TC check is expected to dominate Bypass");
3272 
3273   // Update dominator for Bypass & LoopExit (if needed).
3274   DT->changeImmediateDominator(Bypass, TCCheckBlock);
3275   if (!Cost->requiresScalarEpilogue(VF))
3276     // If there is an epilogue which must run, there's no edge from the
3277     // middle block to exit blocks  and thus no need to update the immediate
3278     // dominator of the exit blocks.
3279     DT->changeImmediateDominator(LoopExitBlock, TCCheckBlock);
3280 
3281   ReplaceInstWithInst(
3282       TCCheckBlock->getTerminator(),
3283       BranchInst::Create(Bypass, LoopVectorPreHeader, CheckMinIters));
3284   LoopBypassBlocks.push_back(TCCheckBlock);
3285 }
3286 
3287 BasicBlock *InnerLoopVectorizer::emitSCEVChecks(Loop *L, BasicBlock *Bypass) {
3288 
3289   BasicBlock *const SCEVCheckBlock =
3290       RTChecks.emitSCEVChecks(L, Bypass, LoopVectorPreHeader, LoopExitBlock);
3291   if (!SCEVCheckBlock)
3292     return nullptr;
3293 
3294   assert(!(SCEVCheckBlock->getParent()->hasOptSize() ||
3295            (OptForSizeBasedOnProfile &&
3296             Cost->Hints->getForce() != LoopVectorizeHints::FK_Enabled)) &&
3297          "Cannot SCEV check stride or overflow when optimizing for size");
3298 
3299 
3300   // Update dominator only if this is first RT check.
3301   if (LoopBypassBlocks.empty()) {
3302     DT->changeImmediateDominator(Bypass, SCEVCheckBlock);
3303     if (!Cost->requiresScalarEpilogue(VF))
3304       // If there is an epilogue which must run, there's no edge from the
3305       // middle block to exit blocks  and thus no need to update the immediate
3306       // dominator of the exit blocks.
3307       DT->changeImmediateDominator(LoopExitBlock, SCEVCheckBlock);
3308   }
3309 
3310   LoopBypassBlocks.push_back(SCEVCheckBlock);
3311   AddedSafetyChecks = true;
3312   return SCEVCheckBlock;
3313 }
3314 
3315 BasicBlock *InnerLoopVectorizer::emitMemRuntimeChecks(Loop *L,
3316                                                       BasicBlock *Bypass) {
3317   // VPlan-native path does not do any analysis for runtime checks currently.
3318   if (EnableVPlanNativePath)
3319     return nullptr;
3320 
3321   BasicBlock *const MemCheckBlock =
3322       RTChecks.emitMemRuntimeChecks(L, Bypass, LoopVectorPreHeader);
3323 
3324   // Check if we generated code that checks in runtime if arrays overlap. We put
3325   // the checks into a separate block to make the more common case of few
3326   // elements faster.
3327   if (!MemCheckBlock)
3328     return nullptr;
3329 
3330   if (MemCheckBlock->getParent()->hasOptSize() || OptForSizeBasedOnProfile) {
3331     assert(Cost->Hints->getForce() == LoopVectorizeHints::FK_Enabled &&
3332            "Cannot emit memory checks when optimizing for size, unless forced "
3333            "to vectorize.");
3334     ORE->emit([&]() {
3335       return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationCodeSize",
3336                                         L->getStartLoc(), L->getHeader())
3337              << "Code-size may be reduced by not forcing "
3338                 "vectorization, or by source-code modifications "
3339                 "eliminating the need for runtime checks "
3340                 "(e.g., adding 'restrict').";
3341     });
3342   }
3343 
3344   LoopBypassBlocks.push_back(MemCheckBlock);
3345 
3346   AddedSafetyChecks = true;
3347 
3348   // We currently don't use LoopVersioning for the actual loop cloning but we
3349   // still use it to add the noalias metadata.
3350   LVer = std::make_unique<LoopVersioning>(
3351       *Legal->getLAI(),
3352       Legal->getLAI()->getRuntimePointerChecking()->getChecks(), OrigLoop, LI,
3353       DT, PSE.getSE());
3354   LVer->prepareNoAliasMetadata();
3355   return MemCheckBlock;
3356 }
3357 
3358 Value *InnerLoopVectorizer::emitTransformedIndex(
3359     IRBuilder<> &B, Value *Index, ScalarEvolution *SE, const DataLayout &DL,
3360     const InductionDescriptor &ID) const {
3361 
3362   SCEVExpander Exp(*SE, DL, "induction");
3363   auto Step = ID.getStep();
3364   auto StartValue = ID.getStartValue();
3365   assert(Index->getType()->getScalarType() == Step->getType() &&
3366          "Index scalar type does not match StepValue type");
3367 
3368   // Note: the IR at this point is broken. We cannot use SE to create any new
3369   // SCEV and then expand it, hoping that SCEV's simplification will give us
3370   // a more optimal code. Unfortunately, attempt of doing so on invalid IR may
3371   // lead to various SCEV crashes. So all we can do is to use builder and rely
3372   // on InstCombine for future simplifications. Here we handle some trivial
3373   // cases only.
3374   auto CreateAdd = [&B](Value *X, Value *Y) {
3375     assert(X->getType() == Y->getType() && "Types don't match!");
3376     if (auto *CX = dyn_cast<ConstantInt>(X))
3377       if (CX->isZero())
3378         return Y;
3379     if (auto *CY = dyn_cast<ConstantInt>(Y))
3380       if (CY->isZero())
3381         return X;
3382     return B.CreateAdd(X, Y);
3383   };
3384 
3385   // We allow X to be a vector type, in which case Y will potentially be
3386   // splatted into a vector with the same element count.
3387   auto CreateMul = [&B](Value *X, Value *Y) {
3388     assert(X->getType()->getScalarType() == Y->getType() &&
3389            "Types don't match!");
3390     if (auto *CX = dyn_cast<ConstantInt>(X))
3391       if (CX->isOne())
3392         return Y;
3393     if (auto *CY = dyn_cast<ConstantInt>(Y))
3394       if (CY->isOne())
3395         return X;
3396     VectorType *XVTy = dyn_cast<VectorType>(X->getType());
3397     if (XVTy && !isa<VectorType>(Y->getType()))
3398       Y = B.CreateVectorSplat(XVTy->getElementCount(), Y);
3399     return B.CreateMul(X, Y);
3400   };
3401 
3402   // Get a suitable insert point for SCEV expansion. For blocks in the vector
3403   // loop, choose the end of the vector loop header (=LoopVectorBody), because
3404   // the DomTree is not kept up-to-date for additional blocks generated in the
3405   // vector loop. By using the header as insertion point, we guarantee that the
3406   // expanded instructions dominate all their uses.
3407   auto GetInsertPoint = [this, &B]() {
3408     BasicBlock *InsertBB = B.GetInsertPoint()->getParent();
3409     if (InsertBB != LoopVectorBody &&
3410         LI->getLoopFor(LoopVectorBody) == LI->getLoopFor(InsertBB))
3411       return LoopVectorBody->getTerminator();
3412     return &*B.GetInsertPoint();
3413   };
3414 
3415   switch (ID.getKind()) {
3416   case InductionDescriptor::IK_IntInduction: {
3417     assert(!isa<VectorType>(Index->getType()) &&
3418            "Vector indices not supported for integer inductions yet");
3419     assert(Index->getType() == StartValue->getType() &&
3420            "Index type does not match StartValue type");
3421     if (ID.getConstIntStepValue() && ID.getConstIntStepValue()->isMinusOne())
3422       return B.CreateSub(StartValue, Index);
3423     auto *Offset = CreateMul(
3424         Index, Exp.expandCodeFor(Step, Index->getType(), GetInsertPoint()));
3425     return CreateAdd(StartValue, Offset);
3426   }
3427   case InductionDescriptor::IK_PtrInduction: {
3428     assert(isa<SCEVConstant>(Step) &&
3429            "Expected constant step for pointer induction");
3430     return B.CreateGEP(
3431         StartValue->getType()->getPointerElementType(), StartValue,
3432         CreateMul(Index,
3433                   Exp.expandCodeFor(Step, Index->getType()->getScalarType(),
3434                                     GetInsertPoint())));
3435   }
3436   case InductionDescriptor::IK_FpInduction: {
3437     assert(!isa<VectorType>(Index->getType()) &&
3438            "Vector indices not supported for FP inductions yet");
3439     assert(Step->getType()->isFloatingPointTy() && "Expected FP Step value");
3440     auto InductionBinOp = ID.getInductionBinOp();
3441     assert(InductionBinOp &&
3442            (InductionBinOp->getOpcode() == Instruction::FAdd ||
3443             InductionBinOp->getOpcode() == Instruction::FSub) &&
3444            "Original bin op should be defined for FP induction");
3445 
3446     Value *StepValue = cast<SCEVUnknown>(Step)->getValue();
3447     Value *MulExp = B.CreateFMul(StepValue, Index);
3448     return B.CreateBinOp(InductionBinOp->getOpcode(), StartValue, MulExp,
3449                          "induction");
3450   }
3451   case InductionDescriptor::IK_NoInduction:
3452     return nullptr;
3453   }
3454   llvm_unreachable("invalid enum");
3455 }
3456 
3457 Loop *InnerLoopVectorizer::createVectorLoopSkeleton(StringRef Prefix) {
3458   LoopScalarBody = OrigLoop->getHeader();
3459   LoopVectorPreHeader = OrigLoop->getLoopPreheader();
3460   assert(LoopVectorPreHeader && "Invalid loop structure");
3461   LoopExitBlock = OrigLoop->getUniqueExitBlock(); // may be nullptr
3462   assert((LoopExitBlock || Cost->requiresScalarEpilogue(VF)) &&
3463          "multiple exit loop without required epilogue?");
3464 
3465   LoopMiddleBlock =
3466       SplitBlock(LoopVectorPreHeader, LoopVectorPreHeader->getTerminator(), DT,
3467                  LI, nullptr, Twine(Prefix) + "middle.block");
3468   LoopScalarPreHeader =
3469       SplitBlock(LoopMiddleBlock, LoopMiddleBlock->getTerminator(), DT, LI,
3470                  nullptr, Twine(Prefix) + "scalar.ph");
3471 
3472   auto *ScalarLatchTerm = OrigLoop->getLoopLatch()->getTerminator();
3473 
3474   // Set up the middle block terminator.  Two cases:
3475   // 1) If we know that we must execute the scalar epilogue, emit an
3476   //    unconditional branch.
3477   // 2) Otherwise, we must have a single unique exit block (due to how we
3478   //    implement the multiple exit case).  In this case, set up a conditonal
3479   //    branch from the middle block to the loop scalar preheader, and the
3480   //    exit block.  completeLoopSkeleton will update the condition to use an
3481   //    iteration check, if required to decide whether to execute the remainder.
3482   BranchInst *BrInst = Cost->requiresScalarEpilogue(VF) ?
3483     BranchInst::Create(LoopScalarPreHeader) :
3484     BranchInst::Create(LoopExitBlock, LoopScalarPreHeader,
3485                        Builder.getTrue());
3486   BrInst->setDebugLoc(ScalarLatchTerm->getDebugLoc());
3487   ReplaceInstWithInst(LoopMiddleBlock->getTerminator(), BrInst);
3488 
3489   // We intentionally don't let SplitBlock to update LoopInfo since
3490   // LoopVectorBody should belong to another loop than LoopVectorPreHeader.
3491   // LoopVectorBody is explicitly added to the correct place few lines later.
3492   LoopVectorBody =
3493       SplitBlock(LoopVectorPreHeader, LoopVectorPreHeader->getTerminator(), DT,
3494                  nullptr, nullptr, Twine(Prefix) + "vector.body");
3495 
3496   // Update dominator for loop exit.
3497   if (!Cost->requiresScalarEpilogue(VF))
3498     // If there is an epilogue which must run, there's no edge from the
3499     // middle block to exit blocks  and thus no need to update the immediate
3500     // dominator of the exit blocks.
3501     DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
3502 
3503   // Create and register the new vector loop.
3504   Loop *Lp = LI->AllocateLoop();
3505   Loop *ParentLoop = OrigLoop->getParentLoop();
3506 
3507   // Insert the new loop into the loop nest and register the new basic blocks
3508   // before calling any utilities such as SCEV that require valid LoopInfo.
3509   if (ParentLoop) {
3510     ParentLoop->addChildLoop(Lp);
3511   } else {
3512     LI->addTopLevelLoop(Lp);
3513   }
3514   Lp->addBasicBlockToLoop(LoopVectorBody, *LI);
3515   return Lp;
3516 }
3517 
3518 void InnerLoopVectorizer::createInductionResumeValues(
3519     Loop *L, Value *VectorTripCount,
3520     std::pair<BasicBlock *, Value *> AdditionalBypass) {
3521   assert(VectorTripCount && L && "Expected valid arguments");
3522   assert(((AdditionalBypass.first && AdditionalBypass.second) ||
3523           (!AdditionalBypass.first && !AdditionalBypass.second)) &&
3524          "Inconsistent information about additional bypass.");
3525   // We are going to resume the execution of the scalar loop.
3526   // Go over all of the induction variables that we found and fix the
3527   // PHIs that are left in the scalar version of the loop.
3528   // The starting values of PHI nodes depend on the counter of the last
3529   // iteration in the vectorized loop.
3530   // If we come from a bypass edge then we need to start from the original
3531   // start value.
3532   for (auto &InductionEntry : Legal->getInductionVars()) {
3533     PHINode *OrigPhi = InductionEntry.first;
3534     InductionDescriptor II = InductionEntry.second;
3535 
3536     // Create phi nodes to merge from the  backedge-taken check block.
3537     PHINode *BCResumeVal =
3538         PHINode::Create(OrigPhi->getType(), 3, "bc.resume.val",
3539                         LoopScalarPreHeader->getTerminator());
3540     // Copy original phi DL over to the new one.
3541     BCResumeVal->setDebugLoc(OrigPhi->getDebugLoc());
3542     Value *&EndValue = IVEndValues[OrigPhi];
3543     Value *EndValueFromAdditionalBypass = AdditionalBypass.second;
3544     if (OrigPhi == OldInduction) {
3545       // We know what the end value is.
3546       EndValue = VectorTripCount;
3547     } else {
3548       IRBuilder<> B(L->getLoopPreheader()->getTerminator());
3549 
3550       // Fast-math-flags propagate from the original induction instruction.
3551       if (II.getInductionBinOp() && isa<FPMathOperator>(II.getInductionBinOp()))
3552         B.setFastMathFlags(II.getInductionBinOp()->getFastMathFlags());
3553 
3554       Type *StepType = II.getStep()->getType();
3555       Instruction::CastOps CastOp =
3556           CastInst::getCastOpcode(VectorTripCount, true, StepType, true);
3557       Value *CRD = B.CreateCast(CastOp, VectorTripCount, StepType, "cast.crd");
3558       const DataLayout &DL = LoopScalarBody->getModule()->getDataLayout();
3559       EndValue = emitTransformedIndex(B, CRD, PSE.getSE(), DL, II);
3560       EndValue->setName("ind.end");
3561 
3562       // Compute the end value for the additional bypass (if applicable).
3563       if (AdditionalBypass.first) {
3564         B.SetInsertPoint(&(*AdditionalBypass.first->getFirstInsertionPt()));
3565         CastOp = CastInst::getCastOpcode(AdditionalBypass.second, true,
3566                                          StepType, true);
3567         CRD =
3568             B.CreateCast(CastOp, AdditionalBypass.second, StepType, "cast.crd");
3569         EndValueFromAdditionalBypass =
3570             emitTransformedIndex(B, CRD, PSE.getSE(), DL, II);
3571         EndValueFromAdditionalBypass->setName("ind.end");
3572       }
3573     }
3574     // The new PHI merges the original incoming value, in case of a bypass,
3575     // or the value at the end of the vectorized loop.
3576     BCResumeVal->addIncoming(EndValue, LoopMiddleBlock);
3577 
3578     // Fix the scalar body counter (PHI node).
3579     // The old induction's phi node in the scalar body needs the truncated
3580     // value.
3581     for (BasicBlock *BB : LoopBypassBlocks)
3582       BCResumeVal->addIncoming(II.getStartValue(), BB);
3583 
3584     if (AdditionalBypass.first)
3585       BCResumeVal->setIncomingValueForBlock(AdditionalBypass.first,
3586                                             EndValueFromAdditionalBypass);
3587 
3588     OrigPhi->setIncomingValueForBlock(LoopScalarPreHeader, BCResumeVal);
3589   }
3590 }
3591 
3592 BasicBlock *InnerLoopVectorizer::completeLoopSkeleton(Loop *L,
3593                                                       MDNode *OrigLoopID) {
3594   assert(L && "Expected valid loop.");
3595 
3596   // The trip counts should be cached by now.
3597   Value *Count = getOrCreateTripCount(L);
3598   Value *VectorTripCount = getOrCreateVectorTripCount(L);
3599 
3600   auto *ScalarLatchTerm = OrigLoop->getLoopLatch()->getTerminator();
3601 
3602   // Add a check in the middle block to see if we have completed
3603   // all of the iterations in the first vector loop.  Three cases:
3604   // 1) If we require a scalar epilogue, there is no conditional branch as
3605   //    we unconditionally branch to the scalar preheader.  Do nothing.
3606   // 2) If (N - N%VF) == N, then we *don't* need to run the remainder.
3607   //    Thus if tail is to be folded, we know we don't need to run the
3608   //    remainder and we can use the previous value for the condition (true).
3609   // 3) Otherwise, construct a runtime check.
3610   if (!Cost->requiresScalarEpilogue(VF) && !Cost->foldTailByMasking()) {
3611     Instruction *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
3612                                         Count, VectorTripCount, "cmp.n",
3613                                         LoopMiddleBlock->getTerminator());
3614 
3615     // Here we use the same DebugLoc as the scalar loop latch terminator instead
3616     // of the corresponding compare because they may have ended up with
3617     // different line numbers and we want to avoid awkward line stepping while
3618     // debugging. Eg. if the compare has got a line number inside the loop.
3619     CmpN->setDebugLoc(ScalarLatchTerm->getDebugLoc());
3620     cast<BranchInst>(LoopMiddleBlock->getTerminator())->setCondition(CmpN);
3621   }
3622 
3623   // Get ready to start creating new instructions into the vectorized body.
3624   assert(LoopVectorPreHeader == L->getLoopPreheader() &&
3625          "Inconsistent vector loop preheader");
3626   Builder.SetInsertPoint(&*LoopVectorBody->getFirstInsertionPt());
3627 
3628   Optional<MDNode *> VectorizedLoopID =
3629       makeFollowupLoopID(OrigLoopID, {LLVMLoopVectorizeFollowupAll,
3630                                       LLVMLoopVectorizeFollowupVectorized});
3631   if (VectorizedLoopID.hasValue()) {
3632     L->setLoopID(VectorizedLoopID.getValue());
3633 
3634     // Do not setAlreadyVectorized if loop attributes have been defined
3635     // explicitly.
3636     return LoopVectorPreHeader;
3637   }
3638 
3639   // Keep all loop hints from the original loop on the vector loop (we'll
3640   // replace the vectorizer-specific hints below).
3641   if (MDNode *LID = OrigLoop->getLoopID())
3642     L->setLoopID(LID);
3643 
3644   LoopVectorizeHints Hints(L, true, *ORE);
3645   Hints.setAlreadyVectorized();
3646 
3647 #ifdef EXPENSIVE_CHECKS
3648   assert(DT->verify(DominatorTree::VerificationLevel::Fast));
3649   LI->verify(*DT);
3650 #endif
3651 
3652   return LoopVectorPreHeader;
3653 }
3654 
3655 BasicBlock *InnerLoopVectorizer::createVectorizedLoopSkeleton() {
3656   /*
3657    In this function we generate a new loop. The new loop will contain
3658    the vectorized instructions while the old loop will continue to run the
3659    scalar remainder.
3660 
3661        [ ] <-- loop iteration number check.
3662     /   |
3663    /    v
3664   |    [ ] <-- vector loop bypass (may consist of multiple blocks).
3665   |  /  |
3666   | /   v
3667   ||   [ ]     <-- vector pre header.
3668   |/    |
3669   |     v
3670   |    [  ] \
3671   |    [  ]_|   <-- vector loop.
3672   |     |
3673   |     v
3674   \   -[ ]   <--- middle-block.
3675    \/   |
3676    /\   v
3677    | ->[ ]     <--- new preheader.
3678    |    |
3679  (opt)  v      <-- edge from middle to exit iff epilogue is not required.
3680    |   [ ] \
3681    |   [ ]_|   <-- old scalar loop to handle remainder (scalar epilogue).
3682     \   |
3683      \  v
3684       >[ ]     <-- exit block(s).
3685    ...
3686    */
3687 
3688   // Get the metadata of the original loop before it gets modified.
3689   MDNode *OrigLoopID = OrigLoop->getLoopID();
3690 
3691   // Workaround!  Compute the trip count of the original loop and cache it
3692   // before we start modifying the CFG.  This code has a systemic problem
3693   // wherein it tries to run analysis over partially constructed IR; this is
3694   // wrong, and not simply for SCEV.  The trip count of the original loop
3695   // simply happens to be prone to hitting this in practice.  In theory, we
3696   // can hit the same issue for any SCEV, or ValueTracking query done during
3697   // mutation.  See PR49900.
3698   getOrCreateTripCount(OrigLoop);
3699 
3700   // Create an empty vector loop, and prepare basic blocks for the runtime
3701   // checks.
3702   Loop *Lp = createVectorLoopSkeleton("");
3703 
3704   // Now, compare the new count to zero. If it is zero skip the vector loop and
3705   // jump to the scalar loop. This check also covers the case where the
3706   // backedge-taken count is uint##_max: adding one to it will overflow leading
3707   // to an incorrect trip count of zero. In this (rare) case we will also jump
3708   // to the scalar loop.
3709   emitMinimumIterationCountCheck(Lp, LoopScalarPreHeader);
3710 
3711   // Generate the code to check any assumptions that we've made for SCEV
3712   // expressions.
3713   emitSCEVChecks(Lp, LoopScalarPreHeader);
3714 
3715   // Generate the code that checks in runtime if arrays overlap. We put the
3716   // checks into a separate block to make the more common case of few elements
3717   // faster.
3718   emitMemRuntimeChecks(Lp, LoopScalarPreHeader);
3719 
3720   // Some loops have a single integer induction variable, while other loops
3721   // don't. One example is c++ iterators that often have multiple pointer
3722   // induction variables. In the code below we also support a case where we
3723   // don't have a single induction variable.
3724   //
3725   // We try to obtain an induction variable from the original loop as hard
3726   // as possible. However if we don't find one that:
3727   //   - is an integer
3728   //   - counts from zero, stepping by one
3729   //   - is the size of the widest induction variable type
3730   // then we create a new one.
3731   OldInduction = Legal->getPrimaryInduction();
3732   Type *IdxTy = Legal->getWidestInductionType();
3733   Value *StartIdx = ConstantInt::get(IdxTy, 0);
3734   // The loop step is equal to the vectorization factor (num of SIMD elements)
3735   // times the unroll factor (num of SIMD instructions).
3736   Builder.SetInsertPoint(&*Lp->getHeader()->getFirstInsertionPt());
3737   Value *Step = createStepForVF(Builder, ConstantInt::get(IdxTy, UF), VF);
3738   Value *CountRoundDown = getOrCreateVectorTripCount(Lp);
3739   Induction =
3740       createInductionVariable(Lp, StartIdx, CountRoundDown, Step,
3741                               getDebugLocFromInstOrOperands(OldInduction));
3742 
3743   // Emit phis for the new starting index of the scalar loop.
3744   createInductionResumeValues(Lp, CountRoundDown);
3745 
3746   return completeLoopSkeleton(Lp, OrigLoopID);
3747 }
3748 
3749 // Fix up external users of the induction variable. At this point, we are
3750 // in LCSSA form, with all external PHIs that use the IV having one input value,
3751 // coming from the remainder loop. We need those PHIs to also have a correct
3752 // value for the IV when arriving directly from the middle block.
3753 void InnerLoopVectorizer::fixupIVUsers(PHINode *OrigPhi,
3754                                        const InductionDescriptor &II,
3755                                        Value *CountRoundDown, Value *EndValue,
3756                                        BasicBlock *MiddleBlock) {
3757   // There are two kinds of external IV usages - those that use the value
3758   // computed in the last iteration (the PHI) and those that use the penultimate
3759   // value (the value that feeds into the phi from the loop latch).
3760   // We allow both, but they, obviously, have different values.
3761 
3762   assert(OrigLoop->getUniqueExitBlock() && "Expected a single exit block");
3763 
3764   DenseMap<Value *, Value *> MissingVals;
3765 
3766   // An external user of the last iteration's value should see the value that
3767   // the remainder loop uses to initialize its own IV.
3768   Value *PostInc = OrigPhi->getIncomingValueForBlock(OrigLoop->getLoopLatch());
3769   for (User *U : PostInc->users()) {
3770     Instruction *UI = cast<Instruction>(U);
3771     if (!OrigLoop->contains(UI)) {
3772       assert(isa<PHINode>(UI) && "Expected LCSSA form");
3773       MissingVals[UI] = EndValue;
3774     }
3775   }
3776 
3777   // An external user of the penultimate value need to see EndValue - Step.
3778   // The simplest way to get this is to recompute it from the constituent SCEVs,
3779   // that is Start + (Step * (CRD - 1)).
3780   for (User *U : OrigPhi->users()) {
3781     auto *UI = cast<Instruction>(U);
3782     if (!OrigLoop->contains(UI)) {
3783       const DataLayout &DL =
3784           OrigLoop->getHeader()->getModule()->getDataLayout();
3785       assert(isa<PHINode>(UI) && "Expected LCSSA form");
3786 
3787       IRBuilder<> B(MiddleBlock->getTerminator());
3788 
3789       // Fast-math-flags propagate from the original induction instruction.
3790       if (II.getInductionBinOp() && isa<FPMathOperator>(II.getInductionBinOp()))
3791         B.setFastMathFlags(II.getInductionBinOp()->getFastMathFlags());
3792 
3793       Value *CountMinusOne = B.CreateSub(
3794           CountRoundDown, ConstantInt::get(CountRoundDown->getType(), 1));
3795       Value *CMO =
3796           !II.getStep()->getType()->isIntegerTy()
3797               ? B.CreateCast(Instruction::SIToFP, CountMinusOne,
3798                              II.getStep()->getType())
3799               : B.CreateSExtOrTrunc(CountMinusOne, II.getStep()->getType());
3800       CMO->setName("cast.cmo");
3801       Value *Escape = emitTransformedIndex(B, CMO, PSE.getSE(), DL, II);
3802       Escape->setName("ind.escape");
3803       MissingVals[UI] = Escape;
3804     }
3805   }
3806 
3807   for (auto &I : MissingVals) {
3808     PHINode *PHI = cast<PHINode>(I.first);
3809     // One corner case we have to handle is two IVs "chasing" each-other,
3810     // that is %IV2 = phi [...], [ %IV1, %latch ]
3811     // In this case, if IV1 has an external use, we need to avoid adding both
3812     // "last value of IV1" and "penultimate value of IV2". So, verify that we
3813     // don't already have an incoming value for the middle block.
3814     if (PHI->getBasicBlockIndex(MiddleBlock) == -1)
3815       PHI->addIncoming(I.second, MiddleBlock);
3816   }
3817 }
3818 
3819 namespace {
3820 
3821 struct CSEDenseMapInfo {
3822   static bool canHandle(const Instruction *I) {
3823     return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
3824            isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
3825   }
3826 
3827   static inline Instruction *getEmptyKey() {
3828     return DenseMapInfo<Instruction *>::getEmptyKey();
3829   }
3830 
3831   static inline Instruction *getTombstoneKey() {
3832     return DenseMapInfo<Instruction *>::getTombstoneKey();
3833   }
3834 
3835   static unsigned getHashValue(const Instruction *I) {
3836     assert(canHandle(I) && "Unknown instruction!");
3837     return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
3838                                                            I->value_op_end()));
3839   }
3840 
3841   static bool isEqual(const Instruction *LHS, const Instruction *RHS) {
3842     if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
3843         LHS == getTombstoneKey() || RHS == getTombstoneKey())
3844       return LHS == RHS;
3845     return LHS->isIdenticalTo(RHS);
3846   }
3847 };
3848 
3849 } // end anonymous namespace
3850 
3851 ///Perform cse of induction variable instructions.
3852 static void cse(BasicBlock *BB) {
3853   // Perform simple cse.
3854   SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
3855   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
3856     Instruction *In = &*I++;
3857 
3858     if (!CSEDenseMapInfo::canHandle(In))
3859       continue;
3860 
3861     // Check if we can replace this instruction with any of the
3862     // visited instructions.
3863     if (Instruction *V = CSEMap.lookup(In)) {
3864       In->replaceAllUsesWith(V);
3865       In->eraseFromParent();
3866       continue;
3867     }
3868 
3869     CSEMap[In] = In;
3870   }
3871 }
3872 
3873 InstructionCost
3874 LoopVectorizationCostModel::getVectorCallCost(CallInst *CI, ElementCount VF,
3875                                               bool &NeedToScalarize) const {
3876   Function *F = CI->getCalledFunction();
3877   Type *ScalarRetTy = CI->getType();
3878   SmallVector<Type *, 4> Tys, ScalarTys;
3879   for (auto &ArgOp : CI->arg_operands())
3880     ScalarTys.push_back(ArgOp->getType());
3881 
3882   // Estimate cost of scalarized vector call. The source operands are assumed
3883   // to be vectors, so we need to extract individual elements from there,
3884   // execute VF scalar calls, and then gather the result into the vector return
3885   // value.
3886   InstructionCost ScalarCallCost =
3887       TTI.getCallInstrCost(F, ScalarRetTy, ScalarTys, TTI::TCK_RecipThroughput);
3888   if (VF.isScalar())
3889     return ScalarCallCost;
3890 
3891   // Compute corresponding vector type for return value and arguments.
3892   Type *RetTy = ToVectorTy(ScalarRetTy, VF);
3893   for (Type *ScalarTy : ScalarTys)
3894     Tys.push_back(ToVectorTy(ScalarTy, VF));
3895 
3896   // Compute costs of unpacking argument values for the scalar calls and
3897   // packing the return values to a vector.
3898   InstructionCost ScalarizationCost = getScalarizationOverhead(CI, VF);
3899 
3900   InstructionCost Cost =
3901       ScalarCallCost * VF.getKnownMinValue() + ScalarizationCost;
3902 
3903   // If we can't emit a vector call for this function, then the currently found
3904   // cost is the cost we need to return.
3905   NeedToScalarize = true;
3906   VFShape Shape = VFShape::get(*CI, VF, false /*HasGlobalPred*/);
3907   Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
3908 
3909   if (!TLI || CI->isNoBuiltin() || !VecFunc)
3910     return Cost;
3911 
3912   // If the corresponding vector cost is cheaper, return its cost.
3913   InstructionCost VectorCallCost =
3914       TTI.getCallInstrCost(nullptr, RetTy, Tys, TTI::TCK_RecipThroughput);
3915   if (VectorCallCost < Cost) {
3916     NeedToScalarize = false;
3917     Cost = VectorCallCost;
3918   }
3919   return Cost;
3920 }
3921 
3922 static Type *MaybeVectorizeType(Type *Elt, ElementCount VF) {
3923   if (VF.isScalar() || (!Elt->isIntOrPtrTy() && !Elt->isFloatingPointTy()))
3924     return Elt;
3925   return VectorType::get(Elt, VF);
3926 }
3927 
3928 InstructionCost
3929 LoopVectorizationCostModel::getVectorIntrinsicCost(CallInst *CI,
3930                                                    ElementCount VF) const {
3931   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
3932   assert(ID && "Expected intrinsic call!");
3933   Type *RetTy = MaybeVectorizeType(CI->getType(), VF);
3934   FastMathFlags FMF;
3935   if (auto *FPMO = dyn_cast<FPMathOperator>(CI))
3936     FMF = FPMO->getFastMathFlags();
3937 
3938   SmallVector<const Value *> Arguments(CI->arg_begin(), CI->arg_end());
3939   FunctionType *FTy = CI->getCalledFunction()->getFunctionType();
3940   SmallVector<Type *> ParamTys;
3941   std::transform(FTy->param_begin(), FTy->param_end(),
3942                  std::back_inserter(ParamTys),
3943                  [&](Type *Ty) { return MaybeVectorizeType(Ty, VF); });
3944 
3945   IntrinsicCostAttributes CostAttrs(ID, RetTy, Arguments, ParamTys, FMF,
3946                                     dyn_cast<IntrinsicInst>(CI));
3947   return TTI.getIntrinsicInstrCost(CostAttrs,
3948                                    TargetTransformInfo::TCK_RecipThroughput);
3949 }
3950 
3951 static Type *smallestIntegerVectorType(Type *T1, Type *T2) {
3952   auto *I1 = cast<IntegerType>(cast<VectorType>(T1)->getElementType());
3953   auto *I2 = cast<IntegerType>(cast<VectorType>(T2)->getElementType());
3954   return I1->getBitWidth() < I2->getBitWidth() ? T1 : T2;
3955 }
3956 
3957 static Type *largestIntegerVectorType(Type *T1, Type *T2) {
3958   auto *I1 = cast<IntegerType>(cast<VectorType>(T1)->getElementType());
3959   auto *I2 = cast<IntegerType>(cast<VectorType>(T2)->getElementType());
3960   return I1->getBitWidth() > I2->getBitWidth() ? T1 : T2;
3961 }
3962 
3963 void InnerLoopVectorizer::truncateToMinimalBitwidths(VPTransformState &State) {
3964   // For every instruction `I` in MinBWs, truncate the operands, create a
3965   // truncated version of `I` and reextend its result. InstCombine runs
3966   // later and will remove any ext/trunc pairs.
3967   SmallPtrSet<Value *, 4> Erased;
3968   for (const auto &KV : Cost->getMinimalBitwidths()) {
3969     // If the value wasn't vectorized, we must maintain the original scalar
3970     // type. The absence of the value from State indicates that it
3971     // wasn't vectorized.
3972     VPValue *Def = State.Plan->getVPValue(KV.first);
3973     if (!State.hasAnyVectorValue(Def))
3974       continue;
3975     for (unsigned Part = 0; Part < UF; ++Part) {
3976       Value *I = State.get(Def, Part);
3977       if (Erased.count(I) || I->use_empty() || !isa<Instruction>(I))
3978         continue;
3979       Type *OriginalTy = I->getType();
3980       Type *ScalarTruncatedTy =
3981           IntegerType::get(OriginalTy->getContext(), KV.second);
3982       auto *TruncatedTy = VectorType::get(
3983           ScalarTruncatedTy, cast<VectorType>(OriginalTy)->getElementCount());
3984       if (TruncatedTy == OriginalTy)
3985         continue;
3986 
3987       IRBuilder<> B(cast<Instruction>(I));
3988       auto ShrinkOperand = [&](Value *V) -> Value * {
3989         if (auto *ZI = dyn_cast<ZExtInst>(V))
3990           if (ZI->getSrcTy() == TruncatedTy)
3991             return ZI->getOperand(0);
3992         return B.CreateZExtOrTrunc(V, TruncatedTy);
3993       };
3994 
3995       // The actual instruction modification depends on the instruction type,
3996       // unfortunately.
3997       Value *NewI = nullptr;
3998       if (auto *BO = dyn_cast<BinaryOperator>(I)) {
3999         NewI = B.CreateBinOp(BO->getOpcode(), ShrinkOperand(BO->getOperand(0)),
4000                              ShrinkOperand(BO->getOperand(1)));
4001 
4002         // Any wrapping introduced by shrinking this operation shouldn't be
4003         // considered undefined behavior. So, we can't unconditionally copy
4004         // arithmetic wrapping flags to NewI.
4005         cast<BinaryOperator>(NewI)->copyIRFlags(I, /*IncludeWrapFlags=*/false);
4006       } else if (auto *CI = dyn_cast<ICmpInst>(I)) {
4007         NewI =
4008             B.CreateICmp(CI->getPredicate(), ShrinkOperand(CI->getOperand(0)),
4009                          ShrinkOperand(CI->getOperand(1)));
4010       } else if (auto *SI = dyn_cast<SelectInst>(I)) {
4011         NewI = B.CreateSelect(SI->getCondition(),
4012                               ShrinkOperand(SI->getTrueValue()),
4013                               ShrinkOperand(SI->getFalseValue()));
4014       } else if (auto *CI = dyn_cast<CastInst>(I)) {
4015         switch (CI->getOpcode()) {
4016         default:
4017           llvm_unreachable("Unhandled cast!");
4018         case Instruction::Trunc:
4019           NewI = ShrinkOperand(CI->getOperand(0));
4020           break;
4021         case Instruction::SExt:
4022           NewI = B.CreateSExtOrTrunc(
4023               CI->getOperand(0),
4024               smallestIntegerVectorType(OriginalTy, TruncatedTy));
4025           break;
4026         case Instruction::ZExt:
4027           NewI = B.CreateZExtOrTrunc(
4028               CI->getOperand(0),
4029               smallestIntegerVectorType(OriginalTy, TruncatedTy));
4030           break;
4031         }
4032       } else if (auto *SI = dyn_cast<ShuffleVectorInst>(I)) {
4033         auto Elements0 =
4034             cast<VectorType>(SI->getOperand(0)->getType())->getElementCount();
4035         auto *O0 = B.CreateZExtOrTrunc(
4036             SI->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements0));
4037         auto Elements1 =
4038             cast<VectorType>(SI->getOperand(1)->getType())->getElementCount();
4039         auto *O1 = B.CreateZExtOrTrunc(
4040             SI->getOperand(1), VectorType::get(ScalarTruncatedTy, Elements1));
4041 
4042         NewI = B.CreateShuffleVector(O0, O1, SI->getShuffleMask());
4043       } else if (isa<LoadInst>(I) || isa<PHINode>(I)) {
4044         // Don't do anything with the operands, just extend the result.
4045         continue;
4046       } else if (auto *IE = dyn_cast<InsertElementInst>(I)) {
4047         auto Elements = cast<FixedVectorType>(IE->getOperand(0)->getType())
4048                             ->getNumElements();
4049         auto *O0 = B.CreateZExtOrTrunc(
4050             IE->getOperand(0),
4051             FixedVectorType::get(ScalarTruncatedTy, Elements));
4052         auto *O1 = B.CreateZExtOrTrunc(IE->getOperand(1), ScalarTruncatedTy);
4053         NewI = B.CreateInsertElement(O0, O1, IE->getOperand(2));
4054       } else if (auto *EE = dyn_cast<ExtractElementInst>(I)) {
4055         auto Elements = cast<FixedVectorType>(EE->getOperand(0)->getType())
4056                             ->getNumElements();
4057         auto *O0 = B.CreateZExtOrTrunc(
4058             EE->getOperand(0),
4059             FixedVectorType::get(ScalarTruncatedTy, Elements));
4060         NewI = B.CreateExtractElement(O0, EE->getOperand(2));
4061       } else {
4062         // If we don't know what to do, be conservative and don't do anything.
4063         continue;
4064       }
4065 
4066       // Lastly, extend the result.
4067       NewI->takeName(cast<Instruction>(I));
4068       Value *Res = B.CreateZExtOrTrunc(NewI, OriginalTy);
4069       I->replaceAllUsesWith(Res);
4070       cast<Instruction>(I)->eraseFromParent();
4071       Erased.insert(I);
4072       State.reset(Def, Res, Part);
4073     }
4074   }
4075 
4076   // We'll have created a bunch of ZExts that are now parentless. Clean up.
4077   for (const auto &KV : Cost->getMinimalBitwidths()) {
4078     // If the value wasn't vectorized, we must maintain the original scalar
4079     // type. The absence of the value from State indicates that it
4080     // wasn't vectorized.
4081     VPValue *Def = State.Plan->getVPValue(KV.first);
4082     if (!State.hasAnyVectorValue(Def))
4083       continue;
4084     for (unsigned Part = 0; Part < UF; ++Part) {
4085       Value *I = State.get(Def, Part);
4086       ZExtInst *Inst = dyn_cast<ZExtInst>(I);
4087       if (Inst && Inst->use_empty()) {
4088         Value *NewI = Inst->getOperand(0);
4089         Inst->eraseFromParent();
4090         State.reset(Def, NewI, Part);
4091       }
4092     }
4093   }
4094 }
4095 
4096 void InnerLoopVectorizer::fixVectorizedLoop(VPTransformState &State) {
4097   // Insert truncates and extends for any truncated instructions as hints to
4098   // InstCombine.
4099   if (VF.isVector())
4100     truncateToMinimalBitwidths(State);
4101 
4102   // Fix widened non-induction PHIs by setting up the PHI operands.
4103   if (OrigPHIsToFix.size()) {
4104     assert(EnableVPlanNativePath &&
4105            "Unexpected non-induction PHIs for fixup in non VPlan-native path");
4106     fixNonInductionPHIs(State);
4107   }
4108 
4109   // At this point every instruction in the original loop is widened to a
4110   // vector form. Now we need to fix the recurrences in the loop. These PHI
4111   // nodes are currently empty because we did not want to introduce cycles.
4112   // This is the second stage of vectorizing recurrences.
4113   fixCrossIterationPHIs(State);
4114 
4115   // Forget the original basic block.
4116   PSE.getSE()->forgetLoop(OrigLoop);
4117 
4118   // If we inserted an edge from the middle block to the unique exit block,
4119   // update uses outside the loop (phis) to account for the newly inserted
4120   // edge.
4121   if (!Cost->requiresScalarEpilogue(VF)) {
4122     // Fix-up external users of the induction variables.
4123     for (auto &Entry : Legal->getInductionVars())
4124       fixupIVUsers(Entry.first, Entry.second,
4125                    getOrCreateVectorTripCount(LI->getLoopFor(LoopVectorBody)),
4126                    IVEndValues[Entry.first], LoopMiddleBlock);
4127 
4128     fixLCSSAPHIs(State);
4129   }
4130 
4131   for (Instruction *PI : PredicatedInstructions)
4132     sinkScalarOperands(&*PI);
4133 
4134   // Remove redundant induction instructions.
4135   cse(LoopVectorBody);
4136 
4137   // Set/update profile weights for the vector and remainder loops as original
4138   // loop iterations are now distributed among them. Note that original loop
4139   // represented by LoopScalarBody becomes remainder loop after vectorization.
4140   //
4141   // For cases like foldTailByMasking() and requiresScalarEpiloque() we may
4142   // end up getting slightly roughened result but that should be OK since
4143   // profile is not inherently precise anyway. Note also possible bypass of
4144   // vector code caused by legality checks is ignored, assigning all the weight
4145   // to the vector loop, optimistically.
4146   //
4147   // For scalable vectorization we can't know at compile time how many iterations
4148   // of the loop are handled in one vector iteration, so instead assume a pessimistic
4149   // vscale of '1'.
4150   setProfileInfoAfterUnrolling(
4151       LI->getLoopFor(LoopScalarBody), LI->getLoopFor(LoopVectorBody),
4152       LI->getLoopFor(LoopScalarBody), VF.getKnownMinValue() * UF);
4153 }
4154 
4155 void InnerLoopVectorizer::fixCrossIterationPHIs(VPTransformState &State) {
4156   // In order to support recurrences we need to be able to vectorize Phi nodes.
4157   // Phi nodes have cycles, so we need to vectorize them in two stages. This is
4158   // stage #2: We now need to fix the recurrences by adding incoming edges to
4159   // the currently empty PHI nodes. At this point every instruction in the
4160   // original loop is widened to a vector form so we can use them to construct
4161   // the incoming edges.
4162   VPBasicBlock *Header = State.Plan->getEntry()->getEntryBasicBlock();
4163   for (VPRecipeBase &R : Header->phis()) {
4164     auto *PhiR = dyn_cast<VPWidenPHIRecipe>(&R);
4165     if (!PhiR)
4166       continue;
4167     auto *OrigPhi = cast<PHINode>(PhiR->getUnderlyingValue());
4168     if (auto *ReductionPhi = dyn_cast<VPReductionPHIRecipe>(PhiR)) {
4169       fixReduction(ReductionPhi, State);
4170     } else if (Legal->isFirstOrderRecurrence(OrigPhi))
4171       fixFirstOrderRecurrence(PhiR, State);
4172   }
4173 }
4174 
4175 void InnerLoopVectorizer::fixFirstOrderRecurrence(VPWidenPHIRecipe *PhiR,
4176                                                   VPTransformState &State) {
4177   // This is the second phase of vectorizing first-order recurrences. An
4178   // overview of the transformation is described below. Suppose we have the
4179   // following loop.
4180   //
4181   //   for (int i = 0; i < n; ++i)
4182   //     b[i] = a[i] - a[i - 1];
4183   //
4184   // There is a first-order recurrence on "a". For this loop, the shorthand
4185   // scalar IR looks like:
4186   //
4187   //   scalar.ph:
4188   //     s_init = a[-1]
4189   //     br scalar.body
4190   //
4191   //   scalar.body:
4192   //     i = phi [0, scalar.ph], [i+1, scalar.body]
4193   //     s1 = phi [s_init, scalar.ph], [s2, scalar.body]
4194   //     s2 = a[i]
4195   //     b[i] = s2 - s1
4196   //     br cond, scalar.body, ...
4197   //
4198   // In this example, s1 is a recurrence because it's value depends on the
4199   // previous iteration. In the first phase of vectorization, we created a
4200   // temporary value for s1. We now complete the vectorization and produce the
4201   // shorthand vector IR shown below (for VF = 4, UF = 1).
4202   //
4203   //   vector.ph:
4204   //     v_init = vector(..., ..., ..., a[-1])
4205   //     br vector.body
4206   //
4207   //   vector.body
4208   //     i = phi [0, vector.ph], [i+4, vector.body]
4209   //     v1 = phi [v_init, vector.ph], [v2, vector.body]
4210   //     v2 = a[i, i+1, i+2, i+3];
4211   //     v3 = vector(v1(3), v2(0, 1, 2))
4212   //     b[i, i+1, i+2, i+3] = v2 - v3
4213   //     br cond, vector.body, middle.block
4214   //
4215   //   middle.block:
4216   //     x = v2(3)
4217   //     br scalar.ph
4218   //
4219   //   scalar.ph:
4220   //     s_init = phi [x, middle.block], [a[-1], otherwise]
4221   //     br scalar.body
4222   //
4223   // After execution completes the vector loop, we extract the next value of
4224   // the recurrence (x) to use as the initial value in the scalar loop.
4225 
4226   auto *ScalarInit = PhiR->getStartValue()->getLiveInIRValue();
4227 
4228   auto *IdxTy = Builder.getInt32Ty();
4229   auto *One = ConstantInt::get(IdxTy, 1);
4230 
4231   // Create a vector from the initial value.
4232   auto *VectorInit = ScalarInit;
4233   if (VF.isVector()) {
4234     Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
4235     auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, VF);
4236     auto *LastIdx = Builder.CreateSub(RuntimeVF, One);
4237     VectorInit = Builder.CreateInsertElement(
4238         PoisonValue::get(VectorType::get(VectorInit->getType(), VF)),
4239         VectorInit, LastIdx, "vector.recur.init");
4240   }
4241 
4242   VPValue *PreviousDef = PhiR->getBackedgeValue();
4243   // We constructed a temporary phi node in the first phase of vectorization.
4244   // This phi node will eventually be deleted.
4245   Builder.SetInsertPoint(cast<Instruction>(State.get(PhiR, 0)));
4246 
4247   // Create a phi node for the new recurrence. The current value will either be
4248   // the initial value inserted into a vector or loop-varying vector value.
4249   auto *VecPhi = Builder.CreatePHI(VectorInit->getType(), 2, "vector.recur");
4250   VecPhi->addIncoming(VectorInit, LoopVectorPreHeader);
4251 
4252   // Get the vectorized previous value of the last part UF - 1. It appears last
4253   // among all unrolled iterations, due to the order of their construction.
4254   Value *PreviousLastPart = State.get(PreviousDef, UF - 1);
4255 
4256   // Find and set the insertion point after the previous value if it is an
4257   // instruction.
4258   BasicBlock::iterator InsertPt;
4259   // Note that the previous value may have been constant-folded so it is not
4260   // guaranteed to be an instruction in the vector loop.
4261   // FIXME: Loop invariant values do not form recurrences. We should deal with
4262   //        them earlier.
4263   if (LI->getLoopFor(LoopVectorBody)->isLoopInvariant(PreviousLastPart))
4264     InsertPt = LoopVectorBody->getFirstInsertionPt();
4265   else {
4266     Instruction *PreviousInst = cast<Instruction>(PreviousLastPart);
4267     if (isa<PHINode>(PreviousLastPart))
4268       // If the previous value is a phi node, we should insert after all the phi
4269       // nodes in the block containing the PHI to avoid breaking basic block
4270       // verification. Note that the basic block may be different to
4271       // LoopVectorBody, in case we predicate the loop.
4272       InsertPt = PreviousInst->getParent()->getFirstInsertionPt();
4273     else
4274       InsertPt = ++PreviousInst->getIterator();
4275   }
4276   Builder.SetInsertPoint(&*InsertPt);
4277 
4278   // The vector from which to take the initial value for the current iteration
4279   // (actual or unrolled). Initially, this is the vector phi node.
4280   Value *Incoming = VecPhi;
4281 
4282   // Shuffle the current and previous vector and update the vector parts.
4283   for (unsigned Part = 0; Part < UF; ++Part) {
4284     Value *PreviousPart = State.get(PreviousDef, Part);
4285     Value *PhiPart = State.get(PhiR, Part);
4286     auto *Shuffle = VF.isVector()
4287                         ? Builder.CreateVectorSplice(Incoming, PreviousPart, -1)
4288                         : Incoming;
4289     PhiPart->replaceAllUsesWith(Shuffle);
4290     cast<Instruction>(PhiPart)->eraseFromParent();
4291     State.reset(PhiR, Shuffle, Part);
4292     Incoming = PreviousPart;
4293   }
4294 
4295   // Fix the latch value of the new recurrence in the vector loop.
4296   VecPhi->addIncoming(Incoming, LI->getLoopFor(LoopVectorBody)->getLoopLatch());
4297 
4298   // Extract the last vector element in the middle block. This will be the
4299   // initial value for the recurrence when jumping to the scalar loop.
4300   auto *ExtractForScalar = Incoming;
4301   if (VF.isVector()) {
4302     Builder.SetInsertPoint(LoopMiddleBlock->getTerminator());
4303     auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, VF);
4304     auto *LastIdx = Builder.CreateSub(RuntimeVF, One);
4305     ExtractForScalar = Builder.CreateExtractElement(ExtractForScalar, LastIdx,
4306                                                     "vector.recur.extract");
4307   }
4308   // Extract the second last element in the middle block if the
4309   // Phi is used outside the loop. We need to extract the phi itself
4310   // and not the last element (the phi update in the current iteration). This
4311   // will be the value when jumping to the exit block from the LoopMiddleBlock,
4312   // when the scalar loop is not run at all.
4313   Value *ExtractForPhiUsedOutsideLoop = nullptr;
4314   if (VF.isVector()) {
4315     auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, VF);
4316     auto *Idx = Builder.CreateSub(RuntimeVF, ConstantInt::get(IdxTy, 2));
4317     ExtractForPhiUsedOutsideLoop = Builder.CreateExtractElement(
4318         Incoming, Idx, "vector.recur.extract.for.phi");
4319   } else if (UF > 1)
4320     // When loop is unrolled without vectorizing, initialize
4321     // ExtractForPhiUsedOutsideLoop with the value just prior to unrolled value
4322     // of `Incoming`. This is analogous to the vectorized case above: extracting
4323     // the second last element when VF > 1.
4324     ExtractForPhiUsedOutsideLoop = State.get(PreviousDef, UF - 2);
4325 
4326   // Fix the initial value of the original recurrence in the scalar loop.
4327   Builder.SetInsertPoint(&*LoopScalarPreHeader->begin());
4328   PHINode *Phi = cast<PHINode>(PhiR->getUnderlyingValue());
4329   auto *Start = Builder.CreatePHI(Phi->getType(), 2, "scalar.recur.init");
4330   for (auto *BB : predecessors(LoopScalarPreHeader)) {
4331     auto *Incoming = BB == LoopMiddleBlock ? ExtractForScalar : ScalarInit;
4332     Start->addIncoming(Incoming, BB);
4333   }
4334 
4335   Phi->setIncomingValueForBlock(LoopScalarPreHeader, Start);
4336   Phi->setName("scalar.recur");
4337 
4338   // Finally, fix users of the recurrence outside the loop. The users will need
4339   // either the last value of the scalar recurrence or the last value of the
4340   // vector recurrence we extracted in the middle block. Since the loop is in
4341   // LCSSA form, we just need to find all the phi nodes for the original scalar
4342   // recurrence in the exit block, and then add an edge for the middle block.
4343   // Note that LCSSA does not imply single entry when the original scalar loop
4344   // had multiple exiting edges (as we always run the last iteration in the
4345   // scalar epilogue); in that case, there is no edge from middle to exit and
4346   // and thus no phis which needed updated.
4347   if (!Cost->requiresScalarEpilogue(VF))
4348     for (PHINode &LCSSAPhi : LoopExitBlock->phis())
4349       if (any_of(LCSSAPhi.incoming_values(),
4350                  [Phi](Value *V) { return V == Phi; }))
4351         LCSSAPhi.addIncoming(ExtractForPhiUsedOutsideLoop, LoopMiddleBlock);
4352 }
4353 
4354 void InnerLoopVectorizer::fixReduction(VPReductionPHIRecipe *PhiR,
4355                                        VPTransformState &State) {
4356   PHINode *OrigPhi = cast<PHINode>(PhiR->getUnderlyingValue());
4357   // Get it's reduction variable descriptor.
4358   assert(Legal->isReductionVariable(OrigPhi) &&
4359          "Unable to find the reduction variable");
4360   const RecurrenceDescriptor &RdxDesc = PhiR->getRecurrenceDescriptor();
4361 
4362   RecurKind RK = RdxDesc.getRecurrenceKind();
4363   TrackingVH<Value> ReductionStartValue = RdxDesc.getRecurrenceStartValue();
4364   Instruction *LoopExitInst = RdxDesc.getLoopExitInstr();
4365   setDebugLocFromInst(ReductionStartValue);
4366 
4367   VPValue *LoopExitInstDef = State.Plan->getVPValue(LoopExitInst);
4368   // This is the vector-clone of the value that leaves the loop.
4369   Type *VecTy = State.get(LoopExitInstDef, 0)->getType();
4370 
4371   // Wrap flags are in general invalid after vectorization, clear them.
4372   clearReductionWrapFlags(RdxDesc, State);
4373 
4374   // Fix the vector-loop phi.
4375 
4376   // Reductions do not have to start at zero. They can start with
4377   // any loop invariant values.
4378   BasicBlock *VectorLoopLatch = LI->getLoopFor(LoopVectorBody)->getLoopLatch();
4379 
4380   unsigned LastPartForNewPhi = PhiR->isOrdered() ? 1 : UF;
4381   for (unsigned Part = 0; Part < LastPartForNewPhi; ++Part) {
4382     Value *VecRdxPhi = State.get(PhiR->getVPSingleValue(), Part);
4383     Value *Val = State.get(PhiR->getBackedgeValue(), Part);
4384     if (PhiR->isOrdered())
4385       Val = State.get(PhiR->getBackedgeValue(), UF - 1);
4386 
4387     cast<PHINode>(VecRdxPhi)->addIncoming(Val, VectorLoopLatch);
4388   }
4389 
4390   // Before each round, move the insertion point right between
4391   // the PHIs and the values we are going to write.
4392   // This allows us to write both PHINodes and the extractelement
4393   // instructions.
4394   Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
4395 
4396   setDebugLocFromInst(LoopExitInst);
4397 
4398   Type *PhiTy = OrigPhi->getType();
4399   // If tail is folded by masking, the vector value to leave the loop should be
4400   // a Select choosing between the vectorized LoopExitInst and vectorized Phi,
4401   // instead of the former. For an inloop reduction the reduction will already
4402   // be predicated, and does not need to be handled here.
4403   if (Cost->foldTailByMasking() && !PhiR->isInLoop()) {
4404     for (unsigned Part = 0; Part < UF; ++Part) {
4405       Value *VecLoopExitInst = State.get(LoopExitInstDef, Part);
4406       Value *Sel = nullptr;
4407       for (User *U : VecLoopExitInst->users()) {
4408         if (isa<SelectInst>(U)) {
4409           assert(!Sel && "Reduction exit feeding two selects");
4410           Sel = U;
4411         } else
4412           assert(isa<PHINode>(U) && "Reduction exit must feed Phi's or select");
4413       }
4414       assert(Sel && "Reduction exit feeds no select");
4415       State.reset(LoopExitInstDef, Sel, Part);
4416 
4417       // If the target can create a predicated operator for the reduction at no
4418       // extra cost in the loop (for example a predicated vadd), it can be
4419       // cheaper for the select to remain in the loop than be sunk out of it,
4420       // and so use the select value for the phi instead of the old
4421       // LoopExitValue.
4422       if (PreferPredicatedReductionSelect ||
4423           TTI->preferPredicatedReductionSelect(
4424               RdxDesc.getOpcode(), PhiTy,
4425               TargetTransformInfo::ReductionFlags())) {
4426         auto *VecRdxPhi =
4427             cast<PHINode>(State.get(PhiR->getVPSingleValue(), Part));
4428         VecRdxPhi->setIncomingValueForBlock(
4429             LI->getLoopFor(LoopVectorBody)->getLoopLatch(), Sel);
4430       }
4431     }
4432   }
4433 
4434   // If the vector reduction can be performed in a smaller type, we truncate
4435   // then extend the loop exit value to enable InstCombine to evaluate the
4436   // entire expression in the smaller type.
4437   if (VF.isVector() && PhiTy != RdxDesc.getRecurrenceType()) {
4438     assert(!PhiR->isInLoop() && "Unexpected truncated inloop reduction!");
4439     Type *RdxVecTy = VectorType::get(RdxDesc.getRecurrenceType(), VF);
4440     Builder.SetInsertPoint(
4441         LI->getLoopFor(LoopVectorBody)->getLoopLatch()->getTerminator());
4442     VectorParts RdxParts(UF);
4443     for (unsigned Part = 0; Part < UF; ++Part) {
4444       RdxParts[Part] = State.get(LoopExitInstDef, Part);
4445       Value *Trunc = Builder.CreateTrunc(RdxParts[Part], RdxVecTy);
4446       Value *Extnd = RdxDesc.isSigned() ? Builder.CreateSExt(Trunc, VecTy)
4447                                         : Builder.CreateZExt(Trunc, VecTy);
4448       for (Value::user_iterator UI = RdxParts[Part]->user_begin();
4449            UI != RdxParts[Part]->user_end();)
4450         if (*UI != Trunc) {
4451           (*UI++)->replaceUsesOfWith(RdxParts[Part], Extnd);
4452           RdxParts[Part] = Extnd;
4453         } else {
4454           ++UI;
4455         }
4456     }
4457     Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
4458     for (unsigned Part = 0; Part < UF; ++Part) {
4459       RdxParts[Part] = Builder.CreateTrunc(RdxParts[Part], RdxVecTy);
4460       State.reset(LoopExitInstDef, RdxParts[Part], Part);
4461     }
4462   }
4463 
4464   // Reduce all of the unrolled parts into a single vector.
4465   Value *ReducedPartRdx = State.get(LoopExitInstDef, 0);
4466   unsigned Op = RecurrenceDescriptor::getOpcode(RK);
4467 
4468   // The middle block terminator has already been assigned a DebugLoc here (the
4469   // OrigLoop's single latch terminator). We want the whole middle block to
4470   // appear to execute on this line because: (a) it is all compiler generated,
4471   // (b) these instructions are always executed after evaluating the latch
4472   // conditional branch, and (c) other passes may add new predecessors which
4473   // terminate on this line. This is the easiest way to ensure we don't
4474   // accidentally cause an extra step back into the loop while debugging.
4475   setDebugLocFromInst(LoopMiddleBlock->getTerminator());
4476   if (PhiR->isOrdered())
4477     ReducedPartRdx = State.get(LoopExitInstDef, UF - 1);
4478   else {
4479     // Floating-point operations should have some FMF to enable the reduction.
4480     IRBuilderBase::FastMathFlagGuard FMFG(Builder);
4481     Builder.setFastMathFlags(RdxDesc.getFastMathFlags());
4482     for (unsigned Part = 1; Part < UF; ++Part) {
4483       Value *RdxPart = State.get(LoopExitInstDef, Part);
4484       if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
4485         ReducedPartRdx = Builder.CreateBinOp(
4486             (Instruction::BinaryOps)Op, RdxPart, ReducedPartRdx, "bin.rdx");
4487       } else {
4488         ReducedPartRdx = createMinMaxOp(Builder, RK, ReducedPartRdx, RdxPart);
4489       }
4490     }
4491   }
4492 
4493   // Create the reduction after the loop. Note that inloop reductions create the
4494   // target reduction in the loop using a Reduction recipe.
4495   if (VF.isVector() && !PhiR->isInLoop()) {
4496     ReducedPartRdx =
4497         createTargetReduction(Builder, TTI, RdxDesc, ReducedPartRdx);
4498     // If the reduction can be performed in a smaller type, we need to extend
4499     // the reduction to the wider type before we branch to the original loop.
4500     if (PhiTy != RdxDesc.getRecurrenceType())
4501       ReducedPartRdx = RdxDesc.isSigned()
4502                            ? Builder.CreateSExt(ReducedPartRdx, PhiTy)
4503                            : Builder.CreateZExt(ReducedPartRdx, PhiTy);
4504   }
4505 
4506   // Create a phi node that merges control-flow from the backedge-taken check
4507   // block and the middle block.
4508   PHINode *BCBlockPhi = PHINode::Create(PhiTy, 2, "bc.merge.rdx",
4509                                         LoopScalarPreHeader->getTerminator());
4510   for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
4511     BCBlockPhi->addIncoming(ReductionStartValue, LoopBypassBlocks[I]);
4512   BCBlockPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
4513 
4514   // Now, we need to fix the users of the reduction variable
4515   // inside and outside of the scalar remainder loop.
4516 
4517   // We know that the loop is in LCSSA form. We need to update the PHI nodes
4518   // in the exit blocks.  See comment on analogous loop in
4519   // fixFirstOrderRecurrence for a more complete explaination of the logic.
4520   if (!Cost->requiresScalarEpilogue(VF))
4521     for (PHINode &LCSSAPhi : LoopExitBlock->phis())
4522       if (any_of(LCSSAPhi.incoming_values(),
4523                  [LoopExitInst](Value *V) { return V == LoopExitInst; }))
4524         LCSSAPhi.addIncoming(ReducedPartRdx, LoopMiddleBlock);
4525 
4526   // Fix the scalar loop reduction variable with the incoming reduction sum
4527   // from the vector body and from the backedge value.
4528   int IncomingEdgeBlockIdx =
4529       OrigPhi->getBasicBlockIndex(OrigLoop->getLoopLatch());
4530   assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
4531   // Pick the other block.
4532   int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
4533   OrigPhi->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi);
4534   OrigPhi->setIncomingValue(IncomingEdgeBlockIdx, LoopExitInst);
4535 }
4536 
4537 void InnerLoopVectorizer::clearReductionWrapFlags(const RecurrenceDescriptor &RdxDesc,
4538                                                   VPTransformState &State) {
4539   RecurKind RK = RdxDesc.getRecurrenceKind();
4540   if (RK != RecurKind::Add && RK != RecurKind::Mul)
4541     return;
4542 
4543   Instruction *LoopExitInstr = RdxDesc.getLoopExitInstr();
4544   assert(LoopExitInstr && "null loop exit instruction");
4545   SmallVector<Instruction *, 8> Worklist;
4546   SmallPtrSet<Instruction *, 8> Visited;
4547   Worklist.push_back(LoopExitInstr);
4548   Visited.insert(LoopExitInstr);
4549 
4550   while (!Worklist.empty()) {
4551     Instruction *Cur = Worklist.pop_back_val();
4552     if (isa<OverflowingBinaryOperator>(Cur))
4553       for (unsigned Part = 0; Part < UF; ++Part) {
4554         Value *V = State.get(State.Plan->getVPValue(Cur), Part);
4555         cast<Instruction>(V)->dropPoisonGeneratingFlags();
4556       }
4557 
4558     for (User *U : Cur->users()) {
4559       Instruction *UI = cast<Instruction>(U);
4560       if ((Cur != LoopExitInstr || OrigLoop->contains(UI->getParent())) &&
4561           Visited.insert(UI).second)
4562         Worklist.push_back(UI);
4563     }
4564   }
4565 }
4566 
4567 void InnerLoopVectorizer::fixLCSSAPHIs(VPTransformState &State) {
4568   for (PHINode &LCSSAPhi : LoopExitBlock->phis()) {
4569     if (LCSSAPhi.getBasicBlockIndex(LoopMiddleBlock) != -1)
4570       // Some phis were already hand updated by the reduction and recurrence
4571       // code above, leave them alone.
4572       continue;
4573 
4574     auto *IncomingValue = LCSSAPhi.getIncomingValue(0);
4575     // Non-instruction incoming values will have only one value.
4576 
4577     VPLane Lane = VPLane::getFirstLane();
4578     if (isa<Instruction>(IncomingValue) &&
4579         !Cost->isUniformAfterVectorization(cast<Instruction>(IncomingValue),
4580                                            VF))
4581       Lane = VPLane::getLastLaneForVF(VF);
4582 
4583     // Can be a loop invariant incoming value or the last scalar value to be
4584     // extracted from the vectorized loop.
4585     Builder.SetInsertPoint(LoopMiddleBlock->getTerminator());
4586     Value *lastIncomingValue =
4587         OrigLoop->isLoopInvariant(IncomingValue)
4588             ? IncomingValue
4589             : State.get(State.Plan->getVPValue(IncomingValue),
4590                         VPIteration(UF - 1, Lane));
4591     LCSSAPhi.addIncoming(lastIncomingValue, LoopMiddleBlock);
4592   }
4593 }
4594 
4595 void InnerLoopVectorizer::sinkScalarOperands(Instruction *PredInst) {
4596   // The basic block and loop containing the predicated instruction.
4597   auto *PredBB = PredInst->getParent();
4598   auto *VectorLoop = LI->getLoopFor(PredBB);
4599 
4600   // Initialize a worklist with the operands of the predicated instruction.
4601   SetVector<Value *> Worklist(PredInst->op_begin(), PredInst->op_end());
4602 
4603   // Holds instructions that we need to analyze again. An instruction may be
4604   // reanalyzed if we don't yet know if we can sink it or not.
4605   SmallVector<Instruction *, 8> InstsToReanalyze;
4606 
4607   // Returns true if a given use occurs in the predicated block. Phi nodes use
4608   // their operands in their corresponding predecessor blocks.
4609   auto isBlockOfUsePredicated = [&](Use &U) -> bool {
4610     auto *I = cast<Instruction>(U.getUser());
4611     BasicBlock *BB = I->getParent();
4612     if (auto *Phi = dyn_cast<PHINode>(I))
4613       BB = Phi->getIncomingBlock(
4614           PHINode::getIncomingValueNumForOperand(U.getOperandNo()));
4615     return BB == PredBB;
4616   };
4617 
4618   // Iteratively sink the scalarized operands of the predicated instruction
4619   // into the block we created for it. When an instruction is sunk, it's
4620   // operands are then added to the worklist. The algorithm ends after one pass
4621   // through the worklist doesn't sink a single instruction.
4622   bool Changed;
4623   do {
4624     // Add the instructions that need to be reanalyzed to the worklist, and
4625     // reset the changed indicator.
4626     Worklist.insert(InstsToReanalyze.begin(), InstsToReanalyze.end());
4627     InstsToReanalyze.clear();
4628     Changed = false;
4629 
4630     while (!Worklist.empty()) {
4631       auto *I = dyn_cast<Instruction>(Worklist.pop_back_val());
4632 
4633       // We can't sink an instruction if it is a phi node, is not in the loop,
4634       // or may have side effects.
4635       if (!I || isa<PHINode>(I) || !VectorLoop->contains(I) ||
4636           I->mayHaveSideEffects())
4637         continue;
4638 
4639       // If the instruction is already in PredBB, check if we can sink its
4640       // operands. In that case, VPlan's sinkScalarOperands() succeeded in
4641       // sinking the scalar instruction I, hence it appears in PredBB; but it
4642       // may have failed to sink I's operands (recursively), which we try
4643       // (again) here.
4644       if (I->getParent() == PredBB) {
4645         Worklist.insert(I->op_begin(), I->op_end());
4646         continue;
4647       }
4648 
4649       // It's legal to sink the instruction if all its uses occur in the
4650       // predicated block. Otherwise, there's nothing to do yet, and we may
4651       // need to reanalyze the instruction.
4652       if (!llvm::all_of(I->uses(), isBlockOfUsePredicated)) {
4653         InstsToReanalyze.push_back(I);
4654         continue;
4655       }
4656 
4657       // Move the instruction to the beginning of the predicated block, and add
4658       // it's operands to the worklist.
4659       I->moveBefore(&*PredBB->getFirstInsertionPt());
4660       Worklist.insert(I->op_begin(), I->op_end());
4661 
4662       // The sinking may have enabled other instructions to be sunk, so we will
4663       // need to iterate.
4664       Changed = true;
4665     }
4666   } while (Changed);
4667 }
4668 
4669 void InnerLoopVectorizer::fixNonInductionPHIs(VPTransformState &State) {
4670   for (PHINode *OrigPhi : OrigPHIsToFix) {
4671     VPWidenPHIRecipe *VPPhi =
4672         cast<VPWidenPHIRecipe>(State.Plan->getVPValue(OrigPhi));
4673     PHINode *NewPhi = cast<PHINode>(State.get(VPPhi, 0));
4674     // Make sure the builder has a valid insert point.
4675     Builder.SetInsertPoint(NewPhi);
4676     for (unsigned i = 0; i < VPPhi->getNumOperands(); ++i) {
4677       VPValue *Inc = VPPhi->getIncomingValue(i);
4678       VPBasicBlock *VPBB = VPPhi->getIncomingBlock(i);
4679       NewPhi->addIncoming(State.get(Inc, 0), State.CFG.VPBB2IRBB[VPBB]);
4680     }
4681   }
4682 }
4683 
4684 bool InnerLoopVectorizer::useOrderedReductions(RecurrenceDescriptor &RdxDesc) {
4685   return Cost->useOrderedReductions(RdxDesc);
4686 }
4687 
4688 void InnerLoopVectorizer::widenGEP(GetElementPtrInst *GEP, VPValue *VPDef,
4689                                    VPUser &Operands, unsigned UF,
4690                                    ElementCount VF, bool IsPtrLoopInvariant,
4691                                    SmallBitVector &IsIndexLoopInvariant,
4692                                    VPTransformState &State) {
4693   // Construct a vector GEP by widening the operands of the scalar GEP as
4694   // necessary. We mark the vector GEP 'inbounds' if appropriate. A GEP
4695   // results in a vector of pointers when at least one operand of the GEP
4696   // is vector-typed. Thus, to keep the representation compact, we only use
4697   // vector-typed operands for loop-varying values.
4698 
4699   if (VF.isVector() && IsPtrLoopInvariant && IsIndexLoopInvariant.all()) {
4700     // If we are vectorizing, but the GEP has only loop-invariant operands,
4701     // the GEP we build (by only using vector-typed operands for
4702     // loop-varying values) would be a scalar pointer. Thus, to ensure we
4703     // produce a vector of pointers, we need to either arbitrarily pick an
4704     // operand to broadcast, or broadcast a clone of the original GEP.
4705     // Here, we broadcast a clone of the original.
4706     //
4707     // TODO: If at some point we decide to scalarize instructions having
4708     //       loop-invariant operands, this special case will no longer be
4709     //       required. We would add the scalarization decision to
4710     //       collectLoopScalars() and teach getVectorValue() to broadcast
4711     //       the lane-zero scalar value.
4712     auto *Clone = Builder.Insert(GEP->clone());
4713     for (unsigned Part = 0; Part < UF; ++Part) {
4714       Value *EntryPart = Builder.CreateVectorSplat(VF, Clone);
4715       State.set(VPDef, EntryPart, Part);
4716       addMetadata(EntryPart, GEP);
4717     }
4718   } else {
4719     // If the GEP has at least one loop-varying operand, we are sure to
4720     // produce a vector of pointers. But if we are only unrolling, we want
4721     // to produce a scalar GEP for each unroll part. Thus, the GEP we
4722     // produce with the code below will be scalar (if VF == 1) or vector
4723     // (otherwise). Note that for the unroll-only case, we still maintain
4724     // values in the vector mapping with initVector, as we do for other
4725     // instructions.
4726     for (unsigned Part = 0; Part < UF; ++Part) {
4727       // The pointer operand of the new GEP. If it's loop-invariant, we
4728       // won't broadcast it.
4729       auto *Ptr = IsPtrLoopInvariant
4730                       ? State.get(Operands.getOperand(0), VPIteration(0, 0))
4731                       : State.get(Operands.getOperand(0), Part);
4732 
4733       // Collect all the indices for the new GEP. If any index is
4734       // loop-invariant, we won't broadcast it.
4735       SmallVector<Value *, 4> Indices;
4736       for (unsigned I = 1, E = Operands.getNumOperands(); I < E; I++) {
4737         VPValue *Operand = Operands.getOperand(I);
4738         if (IsIndexLoopInvariant[I - 1])
4739           Indices.push_back(State.get(Operand, VPIteration(0, 0)));
4740         else
4741           Indices.push_back(State.get(Operand, Part));
4742       }
4743 
4744       // Create the new GEP. Note that this GEP may be a scalar if VF == 1,
4745       // but it should be a vector, otherwise.
4746       auto *NewGEP =
4747           GEP->isInBounds()
4748               ? Builder.CreateInBoundsGEP(GEP->getSourceElementType(), Ptr,
4749                                           Indices)
4750               : Builder.CreateGEP(GEP->getSourceElementType(), Ptr, Indices);
4751       assert((VF.isScalar() || NewGEP->getType()->isVectorTy()) &&
4752              "NewGEP is not a pointer vector");
4753       State.set(VPDef, NewGEP, Part);
4754       addMetadata(NewGEP, GEP);
4755     }
4756   }
4757 }
4758 
4759 void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN,
4760                                               VPWidenPHIRecipe *PhiR,
4761                                               VPTransformState &State) {
4762   PHINode *P = cast<PHINode>(PN);
4763   if (EnableVPlanNativePath) {
4764     // Currently we enter here in the VPlan-native path for non-induction
4765     // PHIs where all control flow is uniform. We simply widen these PHIs.
4766     // Create a vector phi with no operands - the vector phi operands will be
4767     // set at the end of vector code generation.
4768     Type *VecTy = (State.VF.isScalar())
4769                       ? PN->getType()
4770                       : VectorType::get(PN->getType(), State.VF);
4771     Value *VecPhi = Builder.CreatePHI(VecTy, PN->getNumOperands(), "vec.phi");
4772     State.set(PhiR, VecPhi, 0);
4773     OrigPHIsToFix.push_back(P);
4774 
4775     return;
4776   }
4777 
4778   assert(PN->getParent() == OrigLoop->getHeader() &&
4779          "Non-header phis should have been handled elsewhere");
4780 
4781   // In order to support recurrences we need to be able to vectorize Phi nodes.
4782   // Phi nodes have cycles, so we need to vectorize them in two stages. This is
4783   // stage #1: We create a new vector PHI node with no incoming edges. We'll use
4784   // this value when we vectorize all of the instructions that use the PHI.
4785   if (Legal->isFirstOrderRecurrence(P)) {
4786     Type *VecTy = State.VF.isScalar()
4787                       ? PN->getType()
4788                       : VectorType::get(PN->getType(), State.VF);
4789 
4790     for (unsigned Part = 0; Part < State.UF; ++Part) {
4791       Value *EntryPart = PHINode::Create(
4792           VecTy, 2, "vec.phi", &*LoopVectorBody->getFirstInsertionPt());
4793       State.set(PhiR, EntryPart, Part);
4794     }
4795       return;
4796   }
4797 
4798   assert(!Legal->isReductionVariable(P) &&
4799          "reductions should be handled elsewhere");
4800 
4801   setDebugLocFromInst(P);
4802 
4803   // This PHINode must be an induction variable.
4804   // Make sure that we know about it.
4805   assert(Legal->getInductionVars().count(P) && "Not an induction variable");
4806 
4807   InductionDescriptor II = Legal->getInductionVars().lookup(P);
4808   const DataLayout &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
4809 
4810   // FIXME: The newly created binary instructions should contain nsw/nuw flags,
4811   // which can be found from the original scalar operations.
4812   switch (II.getKind()) {
4813   case InductionDescriptor::IK_NoInduction:
4814     llvm_unreachable("Unknown induction");
4815   case InductionDescriptor::IK_IntInduction:
4816   case InductionDescriptor::IK_FpInduction:
4817     llvm_unreachable("Integer/fp induction is handled elsewhere.");
4818   case InductionDescriptor::IK_PtrInduction: {
4819     // Handle the pointer induction variable case.
4820     assert(P->getType()->isPointerTy() && "Unexpected type.");
4821 
4822     if (Cost->isScalarAfterVectorization(P, State.VF)) {
4823       // This is the normalized GEP that starts counting at zero.
4824       Value *PtrInd =
4825           Builder.CreateSExtOrTrunc(Induction, II.getStep()->getType());
4826       // Determine the number of scalars we need to generate for each unroll
4827       // iteration. If the instruction is uniform, we only need to generate the
4828       // first lane. Otherwise, we generate all VF values.
4829       bool IsUniform = Cost->isUniformAfterVectorization(P, State.VF);
4830       unsigned Lanes = IsUniform ? 1 : State.VF.getKnownMinValue();
4831 
4832       bool NeedsVectorIndex = !IsUniform && VF.isScalable();
4833       Value *UnitStepVec = nullptr, *PtrIndSplat = nullptr;
4834       if (NeedsVectorIndex) {
4835         Type *VecIVTy = VectorType::get(PtrInd->getType(), VF);
4836         UnitStepVec = Builder.CreateStepVector(VecIVTy);
4837         PtrIndSplat = Builder.CreateVectorSplat(VF, PtrInd);
4838       }
4839 
4840       for (unsigned Part = 0; Part < UF; ++Part) {
4841         Value *PartStart = createStepForVF(
4842             Builder, ConstantInt::get(PtrInd->getType(), Part), VF);
4843 
4844         if (NeedsVectorIndex) {
4845           Value *PartStartSplat = Builder.CreateVectorSplat(VF, PartStart);
4846           Value *Indices = Builder.CreateAdd(PartStartSplat, UnitStepVec);
4847           Value *GlobalIndices = Builder.CreateAdd(PtrIndSplat, Indices);
4848           Value *SclrGep =
4849               emitTransformedIndex(Builder, GlobalIndices, PSE.getSE(), DL, II);
4850           SclrGep->setName("next.gep");
4851           State.set(PhiR, SclrGep, Part);
4852           // We've cached the whole vector, which means we can support the
4853           // extraction of any lane.
4854           continue;
4855         }
4856 
4857         for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
4858           Value *Idx = Builder.CreateAdd(
4859               PartStart, ConstantInt::get(PtrInd->getType(), Lane));
4860           Value *GlobalIdx = Builder.CreateAdd(PtrInd, Idx);
4861           Value *SclrGep =
4862               emitTransformedIndex(Builder, GlobalIdx, PSE.getSE(), DL, II);
4863           SclrGep->setName("next.gep");
4864           State.set(PhiR, SclrGep, VPIteration(Part, Lane));
4865         }
4866       }
4867       return;
4868     }
4869     assert(isa<SCEVConstant>(II.getStep()) &&
4870            "Induction step not a SCEV constant!");
4871     Type *PhiType = II.getStep()->getType();
4872 
4873     // Build a pointer phi
4874     Value *ScalarStartValue = II.getStartValue();
4875     Type *ScStValueType = ScalarStartValue->getType();
4876     PHINode *NewPointerPhi =
4877         PHINode::Create(ScStValueType, 2, "pointer.phi", Induction);
4878     NewPointerPhi->addIncoming(ScalarStartValue, LoopVectorPreHeader);
4879 
4880     // A pointer induction, performed by using a gep
4881     BasicBlock *LoopLatch = LI->getLoopFor(LoopVectorBody)->getLoopLatch();
4882     Instruction *InductionLoc = LoopLatch->getTerminator();
4883     const SCEV *ScalarStep = II.getStep();
4884     SCEVExpander Exp(*PSE.getSE(), DL, "induction");
4885     Value *ScalarStepValue =
4886         Exp.expandCodeFor(ScalarStep, PhiType, InductionLoc);
4887     Value *RuntimeVF = getRuntimeVF(Builder, PhiType, VF);
4888     Value *NumUnrolledElems =
4889         Builder.CreateMul(RuntimeVF, ConstantInt::get(PhiType, State.UF));
4890     Value *InductionGEP = GetElementPtrInst::Create(
4891         ScStValueType->getPointerElementType(), NewPointerPhi,
4892         Builder.CreateMul(ScalarStepValue, NumUnrolledElems), "ptr.ind",
4893         InductionLoc);
4894     NewPointerPhi->addIncoming(InductionGEP, LoopLatch);
4895 
4896     // Create UF many actual address geps that use the pointer
4897     // phi as base and a vectorized version of the step value
4898     // (<step*0, ..., step*N>) as offset.
4899     for (unsigned Part = 0; Part < State.UF; ++Part) {
4900       Type *VecPhiType = VectorType::get(PhiType, State.VF);
4901       Value *StartOffsetScalar =
4902           Builder.CreateMul(RuntimeVF, ConstantInt::get(PhiType, Part));
4903       Value *StartOffset =
4904           Builder.CreateVectorSplat(State.VF, StartOffsetScalar);
4905       // Create a vector of consecutive numbers from zero to VF.
4906       StartOffset =
4907           Builder.CreateAdd(StartOffset, Builder.CreateStepVector(VecPhiType));
4908 
4909       Value *GEP = Builder.CreateGEP(
4910           ScStValueType->getPointerElementType(), NewPointerPhi,
4911           Builder.CreateMul(
4912               StartOffset, Builder.CreateVectorSplat(State.VF, ScalarStepValue),
4913               "vector.gep"));
4914       State.set(PhiR, GEP, Part);
4915     }
4916   }
4917   }
4918 }
4919 
4920 /// A helper function for checking whether an integer division-related
4921 /// instruction may divide by zero (in which case it must be predicated if
4922 /// executed conditionally in the scalar code).
4923 /// TODO: It may be worthwhile to generalize and check isKnownNonZero().
4924 /// Non-zero divisors that are non compile-time constants will not be
4925 /// converted into multiplication, so we will still end up scalarizing
4926 /// the division, but can do so w/o predication.
4927 static bool mayDivideByZero(Instruction &I) {
4928   assert((I.getOpcode() == Instruction::UDiv ||
4929           I.getOpcode() == Instruction::SDiv ||
4930           I.getOpcode() == Instruction::URem ||
4931           I.getOpcode() == Instruction::SRem) &&
4932          "Unexpected instruction");
4933   Value *Divisor = I.getOperand(1);
4934   auto *CInt = dyn_cast<ConstantInt>(Divisor);
4935   return !CInt || CInt->isZero();
4936 }
4937 
4938 void InnerLoopVectorizer::widenInstruction(Instruction &I, VPValue *Def,
4939                                            VPUser &User,
4940                                            VPTransformState &State) {
4941   switch (I.getOpcode()) {
4942   case Instruction::Call:
4943   case Instruction::Br:
4944   case Instruction::PHI:
4945   case Instruction::GetElementPtr:
4946   case Instruction::Select:
4947     llvm_unreachable("This instruction is handled by a different recipe.");
4948   case Instruction::UDiv:
4949   case Instruction::SDiv:
4950   case Instruction::SRem:
4951   case Instruction::URem:
4952   case Instruction::Add:
4953   case Instruction::FAdd:
4954   case Instruction::Sub:
4955   case Instruction::FSub:
4956   case Instruction::FNeg:
4957   case Instruction::Mul:
4958   case Instruction::FMul:
4959   case Instruction::FDiv:
4960   case Instruction::FRem:
4961   case Instruction::Shl:
4962   case Instruction::LShr:
4963   case Instruction::AShr:
4964   case Instruction::And:
4965   case Instruction::Or:
4966   case Instruction::Xor: {
4967     // Just widen unops and binops.
4968     setDebugLocFromInst(&I);
4969 
4970     for (unsigned Part = 0; Part < UF; ++Part) {
4971       SmallVector<Value *, 2> Ops;
4972       for (VPValue *VPOp : User.operands())
4973         Ops.push_back(State.get(VPOp, Part));
4974 
4975       Value *V = Builder.CreateNAryOp(I.getOpcode(), Ops);
4976 
4977       if (auto *VecOp = dyn_cast<Instruction>(V))
4978         VecOp->copyIRFlags(&I);
4979 
4980       // Use this vector value for all users of the original instruction.
4981       State.set(Def, V, Part);
4982       addMetadata(V, &I);
4983     }
4984 
4985     break;
4986   }
4987   case Instruction::ICmp:
4988   case Instruction::FCmp: {
4989     // Widen compares. Generate vector compares.
4990     bool FCmp = (I.getOpcode() == Instruction::FCmp);
4991     auto *Cmp = cast<CmpInst>(&I);
4992     setDebugLocFromInst(Cmp);
4993     for (unsigned Part = 0; Part < UF; ++Part) {
4994       Value *A = State.get(User.getOperand(0), Part);
4995       Value *B = State.get(User.getOperand(1), Part);
4996       Value *C = nullptr;
4997       if (FCmp) {
4998         // Propagate fast math flags.
4999         IRBuilder<>::FastMathFlagGuard FMFG(Builder);
5000         Builder.setFastMathFlags(Cmp->getFastMathFlags());
5001         C = Builder.CreateFCmp(Cmp->getPredicate(), A, B);
5002       } else {
5003         C = Builder.CreateICmp(Cmp->getPredicate(), A, B);
5004       }
5005       State.set(Def, C, Part);
5006       addMetadata(C, &I);
5007     }
5008 
5009     break;
5010   }
5011 
5012   case Instruction::ZExt:
5013   case Instruction::SExt:
5014   case Instruction::FPToUI:
5015   case Instruction::FPToSI:
5016   case Instruction::FPExt:
5017   case Instruction::PtrToInt:
5018   case Instruction::IntToPtr:
5019   case Instruction::SIToFP:
5020   case Instruction::UIToFP:
5021   case Instruction::Trunc:
5022   case Instruction::FPTrunc:
5023   case Instruction::BitCast: {
5024     auto *CI = cast<CastInst>(&I);
5025     setDebugLocFromInst(CI);
5026 
5027     /// Vectorize casts.
5028     Type *DestTy =
5029         (VF.isScalar()) ? CI->getType() : VectorType::get(CI->getType(), VF);
5030 
5031     for (unsigned Part = 0; Part < UF; ++Part) {
5032       Value *A = State.get(User.getOperand(0), Part);
5033       Value *Cast = Builder.CreateCast(CI->getOpcode(), A, DestTy);
5034       State.set(Def, Cast, Part);
5035       addMetadata(Cast, &I);
5036     }
5037     break;
5038   }
5039   default:
5040     // This instruction is not vectorized by simple widening.
5041     LLVM_DEBUG(dbgs() << "LV: Found an unhandled instruction: " << I);
5042     llvm_unreachable("Unhandled instruction!");
5043   } // end of switch.
5044 }
5045 
5046 void InnerLoopVectorizer::widenCallInstruction(CallInst &I, VPValue *Def,
5047                                                VPUser &ArgOperands,
5048                                                VPTransformState &State) {
5049   assert(!isa<DbgInfoIntrinsic>(I) &&
5050          "DbgInfoIntrinsic should have been dropped during VPlan construction");
5051   setDebugLocFromInst(&I);
5052 
5053   Module *M = I.getParent()->getParent()->getParent();
5054   auto *CI = cast<CallInst>(&I);
5055 
5056   SmallVector<Type *, 4> Tys;
5057   for (Value *ArgOperand : CI->arg_operands())
5058     Tys.push_back(ToVectorTy(ArgOperand->getType(), VF.getKnownMinValue()));
5059 
5060   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
5061 
5062   // The flag shows whether we use Intrinsic or a usual Call for vectorized
5063   // version of the instruction.
5064   // Is it beneficial to perform intrinsic call compared to lib call?
5065   bool NeedToScalarize = false;
5066   InstructionCost CallCost = Cost->getVectorCallCost(CI, VF, NeedToScalarize);
5067   InstructionCost IntrinsicCost = ID ? Cost->getVectorIntrinsicCost(CI, VF) : 0;
5068   bool UseVectorIntrinsic = ID && IntrinsicCost <= CallCost;
5069   assert((UseVectorIntrinsic || !NeedToScalarize) &&
5070          "Instruction should be scalarized elsewhere.");
5071   assert((IntrinsicCost.isValid() || CallCost.isValid()) &&
5072          "Either the intrinsic cost or vector call cost must be valid");
5073 
5074   for (unsigned Part = 0; Part < UF; ++Part) {
5075     SmallVector<Type *, 2> TysForDecl = {CI->getType()};
5076     SmallVector<Value *, 4> Args;
5077     for (auto &I : enumerate(ArgOperands.operands())) {
5078       // Some intrinsics have a scalar argument - don't replace it with a
5079       // vector.
5080       Value *Arg;
5081       if (!UseVectorIntrinsic || !hasVectorInstrinsicScalarOpd(ID, I.index()))
5082         Arg = State.get(I.value(), Part);
5083       else {
5084         Arg = State.get(I.value(), VPIteration(0, 0));
5085         if (hasVectorInstrinsicOverloadedScalarOpd(ID, I.index()))
5086           TysForDecl.push_back(Arg->getType());
5087       }
5088       Args.push_back(Arg);
5089     }
5090 
5091     Function *VectorF;
5092     if (UseVectorIntrinsic) {
5093       // Use vector version of the intrinsic.
5094       if (VF.isVector())
5095         TysForDecl[0] = VectorType::get(CI->getType()->getScalarType(), VF);
5096       VectorF = Intrinsic::getDeclaration(M, ID, TysForDecl);
5097       assert(VectorF && "Can't retrieve vector intrinsic.");
5098     } else {
5099       // Use vector version of the function call.
5100       const VFShape Shape = VFShape::get(*CI, VF, false /*HasGlobalPred*/);
5101 #ifndef NDEBUG
5102       assert(VFDatabase(*CI).getVectorizedFunction(Shape) != nullptr &&
5103              "Can't create vector function.");
5104 #endif
5105         VectorF = VFDatabase(*CI).getVectorizedFunction(Shape);
5106     }
5107       SmallVector<OperandBundleDef, 1> OpBundles;
5108       CI->getOperandBundlesAsDefs(OpBundles);
5109       CallInst *V = Builder.CreateCall(VectorF, Args, OpBundles);
5110 
5111       if (isa<FPMathOperator>(V))
5112         V->copyFastMathFlags(CI);
5113 
5114       State.set(Def, V, Part);
5115       addMetadata(V, &I);
5116   }
5117 }
5118 
5119 void InnerLoopVectorizer::widenSelectInstruction(SelectInst &I, VPValue *VPDef,
5120                                                  VPUser &Operands,
5121                                                  bool InvariantCond,
5122                                                  VPTransformState &State) {
5123   setDebugLocFromInst(&I);
5124 
5125   // The condition can be loop invariant  but still defined inside the
5126   // loop. This means that we can't just use the original 'cond' value.
5127   // We have to take the 'vectorized' value and pick the first lane.
5128   // Instcombine will make this a no-op.
5129   auto *InvarCond = InvariantCond
5130                         ? State.get(Operands.getOperand(0), VPIteration(0, 0))
5131                         : nullptr;
5132 
5133   for (unsigned Part = 0; Part < UF; ++Part) {
5134     Value *Cond =
5135         InvarCond ? InvarCond : State.get(Operands.getOperand(0), Part);
5136     Value *Op0 = State.get(Operands.getOperand(1), Part);
5137     Value *Op1 = State.get(Operands.getOperand(2), Part);
5138     Value *Sel = Builder.CreateSelect(Cond, Op0, Op1);
5139     State.set(VPDef, Sel, Part);
5140     addMetadata(Sel, &I);
5141   }
5142 }
5143 
5144 void LoopVectorizationCostModel::collectLoopScalars(ElementCount VF) {
5145   // We should not collect Scalars more than once per VF. Right now, this
5146   // function is called from collectUniformsAndScalars(), which already does
5147   // this check. Collecting Scalars for VF=1 does not make any sense.
5148   assert(VF.isVector() && Scalars.find(VF) == Scalars.end() &&
5149          "This function should not be visited twice for the same VF");
5150 
5151   SmallSetVector<Instruction *, 8> Worklist;
5152 
5153   // These sets are used to seed the analysis with pointers used by memory
5154   // accesses that will remain scalar.
5155   SmallSetVector<Instruction *, 8> ScalarPtrs;
5156   SmallPtrSet<Instruction *, 8> PossibleNonScalarPtrs;
5157   auto *Latch = TheLoop->getLoopLatch();
5158 
5159   // A helper that returns true if the use of Ptr by MemAccess will be scalar.
5160   // The pointer operands of loads and stores will be scalar as long as the
5161   // memory access is not a gather or scatter operation. The value operand of a
5162   // store will remain scalar if the store is scalarized.
5163   auto isScalarUse = [&](Instruction *MemAccess, Value *Ptr) {
5164     InstWidening WideningDecision = getWideningDecision(MemAccess, VF);
5165     assert(WideningDecision != CM_Unknown &&
5166            "Widening decision should be ready at this moment");
5167     if (auto *Store = dyn_cast<StoreInst>(MemAccess))
5168       if (Ptr == Store->getValueOperand())
5169         return WideningDecision == CM_Scalarize;
5170     assert(Ptr == getLoadStorePointerOperand(MemAccess) &&
5171            "Ptr is neither a value or pointer operand");
5172     return WideningDecision != CM_GatherScatter;
5173   };
5174 
5175   // A helper that returns true if the given value is a bitcast or
5176   // getelementptr instruction contained in the loop.
5177   auto isLoopVaryingBitCastOrGEP = [&](Value *V) {
5178     return ((isa<BitCastInst>(V) && V->getType()->isPointerTy()) ||
5179             isa<GetElementPtrInst>(V)) &&
5180            !TheLoop->isLoopInvariant(V);
5181   };
5182 
5183   auto isScalarPtrInduction = [&](Instruction *MemAccess, Value *Ptr) {
5184     if (!isa<PHINode>(Ptr) ||
5185         !Legal->getInductionVars().count(cast<PHINode>(Ptr)))
5186       return false;
5187     auto &Induction = Legal->getInductionVars()[cast<PHINode>(Ptr)];
5188     if (Induction.getKind() != InductionDescriptor::IK_PtrInduction)
5189       return false;
5190     return isScalarUse(MemAccess, Ptr);
5191   };
5192 
5193   // A helper that evaluates a memory access's use of a pointer. If the
5194   // pointer is actually the pointer induction of a loop, it is being
5195   // inserted into Worklist. If the use will be a scalar use, and the
5196   // pointer is only used by memory accesses, we place the pointer in
5197   // ScalarPtrs. Otherwise, the pointer is placed in PossibleNonScalarPtrs.
5198   auto evaluatePtrUse = [&](Instruction *MemAccess, Value *Ptr) {
5199     if (isScalarPtrInduction(MemAccess, Ptr)) {
5200       Worklist.insert(cast<Instruction>(Ptr));
5201       Instruction *Update = cast<Instruction>(
5202           cast<PHINode>(Ptr)->getIncomingValueForBlock(Latch));
5203       Worklist.insert(Update);
5204       LLVM_DEBUG(dbgs() << "LV: Found new scalar instruction: " << *Ptr
5205                         << "\n");
5206       LLVM_DEBUG(dbgs() << "LV: Found new scalar instruction: " << *Update
5207                         << "\n");
5208       return;
5209     }
5210     // We only care about bitcast and getelementptr instructions contained in
5211     // the loop.
5212     if (!isLoopVaryingBitCastOrGEP(Ptr))
5213       return;
5214 
5215     // If the pointer has already been identified as scalar (e.g., if it was
5216     // also identified as uniform), there's nothing to do.
5217     auto *I = cast<Instruction>(Ptr);
5218     if (Worklist.count(I))
5219       return;
5220 
5221     // If the use of the pointer will be a scalar use, and all users of the
5222     // pointer are memory accesses, place the pointer in ScalarPtrs. Otherwise,
5223     // place the pointer in PossibleNonScalarPtrs.
5224     if (isScalarUse(MemAccess, Ptr) && llvm::all_of(I->users(), [&](User *U) {
5225           return isa<LoadInst>(U) || isa<StoreInst>(U);
5226         }))
5227       ScalarPtrs.insert(I);
5228     else
5229       PossibleNonScalarPtrs.insert(I);
5230   };
5231 
5232   // We seed the scalars analysis with three classes of instructions: (1)
5233   // instructions marked uniform-after-vectorization and (2) bitcast,
5234   // getelementptr and (pointer) phi instructions used by memory accesses
5235   // requiring a scalar use.
5236   //
5237   // (1) Add to the worklist all instructions that have been identified as
5238   // uniform-after-vectorization.
5239   Worklist.insert(Uniforms[VF].begin(), Uniforms[VF].end());
5240 
5241   // (2) Add to the worklist all bitcast and getelementptr instructions used by
5242   // memory accesses requiring a scalar use. The pointer operands of loads and
5243   // stores will be scalar as long as the memory accesses is not a gather or
5244   // scatter operation. The value operand of a store will remain scalar if the
5245   // store is scalarized.
5246   for (auto *BB : TheLoop->blocks())
5247     for (auto &I : *BB) {
5248       if (auto *Load = dyn_cast<LoadInst>(&I)) {
5249         evaluatePtrUse(Load, Load->getPointerOperand());
5250       } else if (auto *Store = dyn_cast<StoreInst>(&I)) {
5251         evaluatePtrUse(Store, Store->getPointerOperand());
5252         evaluatePtrUse(Store, Store->getValueOperand());
5253       }
5254     }
5255   for (auto *I : ScalarPtrs)
5256     if (!PossibleNonScalarPtrs.count(I)) {
5257       LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *I << "\n");
5258       Worklist.insert(I);
5259     }
5260 
5261   // Insert the forced scalars.
5262   // FIXME: Currently widenPHIInstruction() often creates a dead vector
5263   // induction variable when the PHI user is scalarized.
5264   auto ForcedScalar = ForcedScalars.find(VF);
5265   if (ForcedScalar != ForcedScalars.end())
5266     for (auto *I : ForcedScalar->second)
5267       Worklist.insert(I);
5268 
5269   // Expand the worklist by looking through any bitcasts and getelementptr
5270   // instructions we've already identified as scalar. This is similar to the
5271   // expansion step in collectLoopUniforms(); however, here we're only
5272   // expanding to include additional bitcasts and getelementptr instructions.
5273   unsigned Idx = 0;
5274   while (Idx != Worklist.size()) {
5275     Instruction *Dst = Worklist[Idx++];
5276     if (!isLoopVaryingBitCastOrGEP(Dst->getOperand(0)))
5277       continue;
5278     auto *Src = cast<Instruction>(Dst->getOperand(0));
5279     if (llvm::all_of(Src->users(), [&](User *U) -> bool {
5280           auto *J = cast<Instruction>(U);
5281           return !TheLoop->contains(J) || Worklist.count(J) ||
5282                  ((isa<LoadInst>(J) || isa<StoreInst>(J)) &&
5283                   isScalarUse(J, Src));
5284         })) {
5285       Worklist.insert(Src);
5286       LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Src << "\n");
5287     }
5288   }
5289 
5290   // An induction variable will remain scalar if all users of the induction
5291   // variable and induction variable update remain scalar.
5292   for (auto &Induction : Legal->getInductionVars()) {
5293     auto *Ind = Induction.first;
5294     auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
5295 
5296     // If tail-folding is applied, the primary induction variable will be used
5297     // to feed a vector compare.
5298     if (Ind == Legal->getPrimaryInduction() && foldTailByMasking())
5299       continue;
5300 
5301     // Determine if all users of the induction variable are scalar after
5302     // vectorization.
5303     auto ScalarInd = llvm::all_of(Ind->users(), [&](User *U) -> bool {
5304       auto *I = cast<Instruction>(U);
5305       return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I);
5306     });
5307     if (!ScalarInd)
5308       continue;
5309 
5310     // Determine if all users of the induction variable update instruction are
5311     // scalar after vectorization.
5312     auto ScalarIndUpdate =
5313         llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
5314           auto *I = cast<Instruction>(U);
5315           return I == Ind || !TheLoop->contains(I) || Worklist.count(I);
5316         });
5317     if (!ScalarIndUpdate)
5318       continue;
5319 
5320     // The induction variable and its update instruction will remain scalar.
5321     Worklist.insert(Ind);
5322     Worklist.insert(IndUpdate);
5323     LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Ind << "\n");
5324     LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *IndUpdate
5325                       << "\n");
5326   }
5327 
5328   Scalars[VF].insert(Worklist.begin(), Worklist.end());
5329 }
5330 
5331 bool LoopVectorizationCostModel::isScalarWithPredication(Instruction *I) const {
5332   if (!blockNeedsPredication(I->getParent()))
5333     return false;
5334   switch(I->getOpcode()) {
5335   default:
5336     break;
5337   case Instruction::Load:
5338   case Instruction::Store: {
5339     if (!Legal->isMaskRequired(I))
5340       return false;
5341     auto *Ptr = getLoadStorePointerOperand(I);
5342     auto *Ty = getLoadStoreType(I);
5343     const Align Alignment = getLoadStoreAlignment(I);
5344     return isa<LoadInst>(I) ? !(isLegalMaskedLoad(Ty, Ptr, Alignment) ||
5345                                 TTI.isLegalMaskedGather(Ty, Alignment))
5346                             : !(isLegalMaskedStore(Ty, Ptr, Alignment) ||
5347                                 TTI.isLegalMaskedScatter(Ty, Alignment));
5348   }
5349   case Instruction::UDiv:
5350   case Instruction::SDiv:
5351   case Instruction::SRem:
5352   case Instruction::URem:
5353     return mayDivideByZero(*I);
5354   }
5355   return false;
5356 }
5357 
5358 bool LoopVectorizationCostModel::interleavedAccessCanBeWidened(
5359     Instruction *I, ElementCount VF) {
5360   assert(isAccessInterleaved(I) && "Expecting interleaved access.");
5361   assert(getWideningDecision(I, VF) == CM_Unknown &&
5362          "Decision should not be set yet.");
5363   auto *Group = getInterleavedAccessGroup(I);
5364   assert(Group && "Must have a group.");
5365 
5366   // If the instruction's allocated size doesn't equal it's type size, it
5367   // requires padding and will be scalarized.
5368   auto &DL = I->getModule()->getDataLayout();
5369   auto *ScalarTy = getLoadStoreType(I);
5370   if (hasIrregularType(ScalarTy, DL))
5371     return false;
5372 
5373   // Check if masking is required.
5374   // A Group may need masking for one of two reasons: it resides in a block that
5375   // needs predication, or it was decided to use masking to deal with gaps.
5376   bool PredicatedAccessRequiresMasking =
5377       Legal->blockNeedsPredication(I->getParent()) && Legal->isMaskRequired(I);
5378   bool AccessWithGapsRequiresMasking =
5379       Group->requiresScalarEpilogue() && !isScalarEpilogueAllowed();
5380   if (!PredicatedAccessRequiresMasking && !AccessWithGapsRequiresMasking)
5381     return true;
5382 
5383   // If masked interleaving is required, we expect that the user/target had
5384   // enabled it, because otherwise it either wouldn't have been created or
5385   // it should have been invalidated by the CostModel.
5386   assert(useMaskedInterleavedAccesses(TTI) &&
5387          "Masked interleave-groups for predicated accesses are not enabled.");
5388 
5389   auto *Ty = getLoadStoreType(I);
5390   const Align Alignment = getLoadStoreAlignment(I);
5391   return isa<LoadInst>(I) ? TTI.isLegalMaskedLoad(Ty, Alignment)
5392                           : TTI.isLegalMaskedStore(Ty, Alignment);
5393 }
5394 
5395 bool LoopVectorizationCostModel::memoryInstructionCanBeWidened(
5396     Instruction *I, ElementCount VF) {
5397   // Get and ensure we have a valid memory instruction.
5398   LoadInst *LI = dyn_cast<LoadInst>(I);
5399   StoreInst *SI = dyn_cast<StoreInst>(I);
5400   assert((LI || SI) && "Invalid memory instruction");
5401 
5402   auto *Ptr = getLoadStorePointerOperand(I);
5403 
5404   // In order to be widened, the pointer should be consecutive, first of all.
5405   if (!Legal->isConsecutivePtr(Ptr))
5406     return false;
5407 
5408   // If the instruction is a store located in a predicated block, it will be
5409   // scalarized.
5410   if (isScalarWithPredication(I))
5411     return false;
5412 
5413   // If the instruction's allocated size doesn't equal it's type size, it
5414   // requires padding and will be scalarized.
5415   auto &DL = I->getModule()->getDataLayout();
5416   auto *ScalarTy = LI ? LI->getType() : SI->getValueOperand()->getType();
5417   if (hasIrregularType(ScalarTy, DL))
5418     return false;
5419 
5420   return true;
5421 }
5422 
5423 void LoopVectorizationCostModel::collectLoopUniforms(ElementCount VF) {
5424   // We should not collect Uniforms more than once per VF. Right now,
5425   // this function is called from collectUniformsAndScalars(), which
5426   // already does this check. Collecting Uniforms for VF=1 does not make any
5427   // sense.
5428 
5429   assert(VF.isVector() && Uniforms.find(VF) == Uniforms.end() &&
5430          "This function should not be visited twice for the same VF");
5431 
5432   // Visit the list of Uniforms. If we'll not find any uniform value, we'll
5433   // not analyze again.  Uniforms.count(VF) will return 1.
5434   Uniforms[VF].clear();
5435 
5436   // We now know that the loop is vectorizable!
5437   // Collect instructions inside the loop that will remain uniform after
5438   // vectorization.
5439 
5440   // Global values, params and instructions outside of current loop are out of
5441   // scope.
5442   auto isOutOfScope = [&](Value *V) -> bool {
5443     Instruction *I = dyn_cast<Instruction>(V);
5444     return (!I || !TheLoop->contains(I));
5445   };
5446 
5447   SetVector<Instruction *> Worklist;
5448   BasicBlock *Latch = TheLoop->getLoopLatch();
5449 
5450   // Instructions that are scalar with predication must not be considered
5451   // uniform after vectorization, because that would create an erroneous
5452   // replicating region where only a single instance out of VF should be formed.
5453   // TODO: optimize such seldom cases if found important, see PR40816.
5454   auto addToWorklistIfAllowed = [&](Instruction *I) -> void {
5455     if (isOutOfScope(I)) {
5456       LLVM_DEBUG(dbgs() << "LV: Found not uniform due to scope: "
5457                         << *I << "\n");
5458       return;
5459     }
5460     if (isScalarWithPredication(I)) {
5461       LLVM_DEBUG(dbgs() << "LV: Found not uniform being ScalarWithPredication: "
5462                         << *I << "\n");
5463       return;
5464     }
5465     LLVM_DEBUG(dbgs() << "LV: Found uniform instruction: " << *I << "\n");
5466     Worklist.insert(I);
5467   };
5468 
5469   // Start with the conditional branch. If the branch condition is an
5470   // instruction contained in the loop that is only used by the branch, it is
5471   // uniform.
5472   auto *Cmp = dyn_cast<Instruction>(Latch->getTerminator()->getOperand(0));
5473   if (Cmp && TheLoop->contains(Cmp) && Cmp->hasOneUse())
5474     addToWorklistIfAllowed(Cmp);
5475 
5476   auto isUniformDecision = [&](Instruction *I, ElementCount VF) {
5477     InstWidening WideningDecision = getWideningDecision(I, VF);
5478     assert(WideningDecision != CM_Unknown &&
5479            "Widening decision should be ready at this moment");
5480 
5481     // A uniform memory op is itself uniform.  We exclude uniform stores
5482     // here as they demand the last lane, not the first one.
5483     if (isa<LoadInst>(I) && Legal->isUniformMemOp(*I)) {
5484       assert(WideningDecision == CM_Scalarize);
5485       return true;
5486     }
5487 
5488     return (WideningDecision == CM_Widen ||
5489             WideningDecision == CM_Widen_Reverse ||
5490             WideningDecision == CM_Interleave);
5491   };
5492 
5493 
5494   // Returns true if Ptr is the pointer operand of a memory access instruction
5495   // I, and I is known to not require scalarization.
5496   auto isVectorizedMemAccessUse = [&](Instruction *I, Value *Ptr) -> bool {
5497     return getLoadStorePointerOperand(I) == Ptr && isUniformDecision(I, VF);
5498   };
5499 
5500   // Holds a list of values which are known to have at least one uniform use.
5501   // Note that there may be other uses which aren't uniform.  A "uniform use"
5502   // here is something which only demands lane 0 of the unrolled iterations;
5503   // it does not imply that all lanes produce the same value (e.g. this is not
5504   // the usual meaning of uniform)
5505   SetVector<Value *> HasUniformUse;
5506 
5507   // Scan the loop for instructions which are either a) known to have only
5508   // lane 0 demanded or b) are uses which demand only lane 0 of their operand.
5509   for (auto *BB : TheLoop->blocks())
5510     for (auto &I : *BB) {
5511       // If there's no pointer operand, there's nothing to do.
5512       auto *Ptr = getLoadStorePointerOperand(&I);
5513       if (!Ptr)
5514         continue;
5515 
5516       // A uniform memory op is itself uniform.  We exclude uniform stores
5517       // here as they demand the last lane, not the first one.
5518       if (isa<LoadInst>(I) && Legal->isUniformMemOp(I))
5519         addToWorklistIfAllowed(&I);
5520 
5521       if (isUniformDecision(&I, VF)) {
5522         assert(isVectorizedMemAccessUse(&I, Ptr) && "consistency check");
5523         HasUniformUse.insert(Ptr);
5524       }
5525     }
5526 
5527   // Add to the worklist any operands which have *only* uniform (e.g. lane 0
5528   // demanding) users.  Since loops are assumed to be in LCSSA form, this
5529   // disallows uses outside the loop as well.
5530   for (auto *V : HasUniformUse) {
5531     if (isOutOfScope(V))
5532       continue;
5533     auto *I = cast<Instruction>(V);
5534     auto UsersAreMemAccesses =
5535       llvm::all_of(I->users(), [&](User *U) -> bool {
5536         return isVectorizedMemAccessUse(cast<Instruction>(U), V);
5537       });
5538     if (UsersAreMemAccesses)
5539       addToWorklistIfAllowed(I);
5540   }
5541 
5542   // Expand Worklist in topological order: whenever a new instruction
5543   // is added , its users should be already inside Worklist.  It ensures
5544   // a uniform instruction will only be used by uniform instructions.
5545   unsigned idx = 0;
5546   while (idx != Worklist.size()) {
5547     Instruction *I = Worklist[idx++];
5548 
5549     for (auto OV : I->operand_values()) {
5550       // isOutOfScope operands cannot be uniform instructions.
5551       if (isOutOfScope(OV))
5552         continue;
5553       // First order recurrence Phi's should typically be considered
5554       // non-uniform.
5555       auto *OP = dyn_cast<PHINode>(OV);
5556       if (OP && Legal->isFirstOrderRecurrence(OP))
5557         continue;
5558       // If all the users of the operand are uniform, then add the
5559       // operand into the uniform worklist.
5560       auto *OI = cast<Instruction>(OV);
5561       if (llvm::all_of(OI->users(), [&](User *U) -> bool {
5562             auto *J = cast<Instruction>(U);
5563             return Worklist.count(J) || isVectorizedMemAccessUse(J, OI);
5564           }))
5565         addToWorklistIfAllowed(OI);
5566     }
5567   }
5568 
5569   // For an instruction to be added into Worklist above, all its users inside
5570   // the loop should also be in Worklist. However, this condition cannot be
5571   // true for phi nodes that form a cyclic dependence. We must process phi
5572   // nodes separately. An induction variable will remain uniform if all users
5573   // of the induction variable and induction variable update remain uniform.
5574   // The code below handles both pointer and non-pointer induction variables.
5575   for (auto &Induction : Legal->getInductionVars()) {
5576     auto *Ind = Induction.first;
5577     auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
5578 
5579     // Determine if all users of the induction variable are uniform after
5580     // vectorization.
5581     auto UniformInd = llvm::all_of(Ind->users(), [&](User *U) -> bool {
5582       auto *I = cast<Instruction>(U);
5583       return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) ||
5584              isVectorizedMemAccessUse(I, Ind);
5585     });
5586     if (!UniformInd)
5587       continue;
5588 
5589     // Determine if all users of the induction variable update instruction are
5590     // uniform after vectorization.
5591     auto UniformIndUpdate =
5592         llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
5593           auto *I = cast<Instruction>(U);
5594           return I == Ind || !TheLoop->contains(I) || Worklist.count(I) ||
5595                  isVectorizedMemAccessUse(I, IndUpdate);
5596         });
5597     if (!UniformIndUpdate)
5598       continue;
5599 
5600     // The induction variable and its update instruction will remain uniform.
5601     addToWorklistIfAllowed(Ind);
5602     addToWorklistIfAllowed(IndUpdate);
5603   }
5604 
5605   Uniforms[VF].insert(Worklist.begin(), Worklist.end());
5606 }
5607 
5608 bool LoopVectorizationCostModel::runtimeChecksRequired() {
5609   LLVM_DEBUG(dbgs() << "LV: Performing code size checks.\n");
5610 
5611   if (Legal->getRuntimePointerChecking()->Need) {
5612     reportVectorizationFailure("Runtime ptr check is required with -Os/-Oz",
5613         "runtime pointer checks needed. Enable vectorization of this "
5614         "loop with '#pragma clang loop vectorize(enable)' when "
5615         "compiling with -Os/-Oz",
5616         "CantVersionLoopWithOptForSize", ORE, TheLoop);
5617     return true;
5618   }
5619 
5620   if (!PSE.getUnionPredicate().getPredicates().empty()) {
5621     reportVectorizationFailure("Runtime SCEV check is required with -Os/-Oz",
5622         "runtime SCEV checks needed. Enable vectorization of this "
5623         "loop with '#pragma clang loop vectorize(enable)' when "
5624         "compiling with -Os/-Oz",
5625         "CantVersionLoopWithOptForSize", ORE, TheLoop);
5626     return true;
5627   }
5628 
5629   // FIXME: Avoid specializing for stride==1 instead of bailing out.
5630   if (!Legal->getLAI()->getSymbolicStrides().empty()) {
5631     reportVectorizationFailure("Runtime stride check for small trip count",
5632         "runtime stride == 1 checks needed. Enable vectorization of "
5633         "this loop without such check by compiling with -Os/-Oz",
5634         "CantVersionLoopWithOptForSize", ORE, TheLoop);
5635     return true;
5636   }
5637 
5638   return false;
5639 }
5640 
5641 ElementCount
5642 LoopVectorizationCostModel::getMaxLegalScalableVF(unsigned MaxSafeElements) {
5643   if (!TTI.supportsScalableVectors() && !ForceTargetSupportsScalableVectors) {
5644     reportVectorizationInfo(
5645         "Disabling scalable vectorization, because target does not "
5646         "support scalable vectors.",
5647         "ScalableVectorsUnsupported", ORE, TheLoop);
5648     return ElementCount::getScalable(0);
5649   }
5650 
5651   if (Hints->isScalableVectorizationDisabled()) {
5652     reportVectorizationInfo("Scalable vectorization is explicitly disabled",
5653                             "ScalableVectorizationDisabled", ORE, TheLoop);
5654     return ElementCount::getScalable(0);
5655   }
5656 
5657   auto MaxScalableVF = ElementCount::getScalable(
5658       std::numeric_limits<ElementCount::ScalarTy>::max());
5659 
5660   // Test that the loop-vectorizer can legalize all operations for this MaxVF.
5661   // FIXME: While for scalable vectors this is currently sufficient, this should
5662   // be replaced by a more detailed mechanism that filters out specific VFs,
5663   // instead of invalidating vectorization for a whole set of VFs based on the
5664   // MaxVF.
5665 
5666   // Disable scalable vectorization if the loop contains unsupported reductions.
5667   if (!canVectorizeReductions(MaxScalableVF)) {
5668     reportVectorizationInfo(
5669         "Scalable vectorization not supported for the reduction "
5670         "operations found in this loop.",
5671         "ScalableVFUnfeasible", ORE, TheLoop);
5672     return ElementCount::getScalable(0);
5673   }
5674 
5675   // Disable scalable vectorization if the loop contains any instructions
5676   // with element types not supported for scalable vectors.
5677   if (any_of(ElementTypesInLoop, [&](Type *Ty) {
5678         return !Ty->isVoidTy() &&
5679                !this->TTI.isElementTypeLegalForScalableVector(Ty);
5680       })) {
5681     reportVectorizationInfo("Scalable vectorization is not supported "
5682                             "for all element types found in this loop.",
5683                             "ScalableVFUnfeasible", ORE, TheLoop);
5684     return ElementCount::getScalable(0);
5685   }
5686 
5687   if (Legal->isSafeForAnyVectorWidth())
5688     return MaxScalableVF;
5689 
5690   // Limit MaxScalableVF by the maximum safe dependence distance.
5691   Optional<unsigned> MaxVScale = TTI.getMaxVScale();
5692   MaxScalableVF = ElementCount::getScalable(
5693       MaxVScale ? (MaxSafeElements / MaxVScale.getValue()) : 0);
5694   if (!MaxScalableVF)
5695     reportVectorizationInfo(
5696         "Max legal vector width too small, scalable vectorization "
5697         "unfeasible.",
5698         "ScalableVFUnfeasible", ORE, TheLoop);
5699 
5700   return MaxScalableVF;
5701 }
5702 
5703 FixedScalableVFPair
5704 LoopVectorizationCostModel::computeFeasibleMaxVF(unsigned ConstTripCount,
5705                                                  ElementCount UserVF) {
5706   MinBWs = computeMinimumValueSizes(TheLoop->getBlocks(), *DB, &TTI);
5707   unsigned SmallestType, WidestType;
5708   std::tie(SmallestType, WidestType) = getSmallestAndWidestTypes();
5709 
5710   // Get the maximum safe dependence distance in bits computed by LAA.
5711   // It is computed by MaxVF * sizeOf(type) * 8, where type is taken from
5712   // the memory accesses that is most restrictive (involved in the smallest
5713   // dependence distance).
5714   unsigned MaxSafeElements =
5715       PowerOf2Floor(Legal->getMaxSafeVectorWidthInBits() / WidestType);
5716 
5717   auto MaxSafeFixedVF = ElementCount::getFixed(MaxSafeElements);
5718   auto MaxSafeScalableVF = getMaxLegalScalableVF(MaxSafeElements);
5719 
5720   LLVM_DEBUG(dbgs() << "LV: The max safe fixed VF is: " << MaxSafeFixedVF
5721                     << ".\n");
5722   LLVM_DEBUG(dbgs() << "LV: The max safe scalable VF is: " << MaxSafeScalableVF
5723                     << ".\n");
5724 
5725   // First analyze the UserVF, fall back if the UserVF should be ignored.
5726   if (UserVF) {
5727     auto MaxSafeUserVF =
5728         UserVF.isScalable() ? MaxSafeScalableVF : MaxSafeFixedVF;
5729 
5730     if (ElementCount::isKnownLE(UserVF, MaxSafeUserVF)) {
5731       // If `VF=vscale x N` is safe, then so is `VF=N`
5732       if (UserVF.isScalable())
5733         return FixedScalableVFPair(
5734             ElementCount::getFixed(UserVF.getKnownMinValue()), UserVF);
5735       else
5736         return UserVF;
5737     }
5738 
5739     assert(ElementCount::isKnownGT(UserVF, MaxSafeUserVF));
5740 
5741     // Only clamp if the UserVF is not scalable. If the UserVF is scalable, it
5742     // is better to ignore the hint and let the compiler choose a suitable VF.
5743     if (!UserVF.isScalable()) {
5744       LLVM_DEBUG(dbgs() << "LV: User VF=" << UserVF
5745                         << " is unsafe, clamping to max safe VF="
5746                         << MaxSafeFixedVF << ".\n");
5747       ORE->emit([&]() {
5748         return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationFactor",
5749                                           TheLoop->getStartLoc(),
5750                                           TheLoop->getHeader())
5751                << "User-specified vectorization factor "
5752                << ore::NV("UserVectorizationFactor", UserVF)
5753                << " is unsafe, clamping to maximum safe vectorization factor "
5754                << ore::NV("VectorizationFactor", MaxSafeFixedVF);
5755       });
5756       return MaxSafeFixedVF;
5757     }
5758 
5759     LLVM_DEBUG(dbgs() << "LV: User VF=" << UserVF
5760                       << " is unsafe. Ignoring scalable UserVF.\n");
5761     ORE->emit([&]() {
5762       return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationFactor",
5763                                         TheLoop->getStartLoc(),
5764                                         TheLoop->getHeader())
5765              << "User-specified vectorization factor "
5766              << ore::NV("UserVectorizationFactor", UserVF)
5767              << " is unsafe. Ignoring the hint to let the compiler pick a "
5768                 "suitable VF.";
5769     });
5770   }
5771 
5772   LLVM_DEBUG(dbgs() << "LV: The Smallest and Widest types: " << SmallestType
5773                     << " / " << WidestType << " bits.\n");
5774 
5775   FixedScalableVFPair Result(ElementCount::getFixed(1),
5776                              ElementCount::getScalable(0));
5777   if (auto MaxVF = getMaximizedVFForTarget(ConstTripCount, SmallestType,
5778                                            WidestType, MaxSafeFixedVF))
5779     Result.FixedVF = MaxVF;
5780 
5781   if (auto MaxVF = getMaximizedVFForTarget(ConstTripCount, SmallestType,
5782                                            WidestType, MaxSafeScalableVF))
5783     if (MaxVF.isScalable()) {
5784       Result.ScalableVF = MaxVF;
5785       LLVM_DEBUG(dbgs() << "LV: Found feasible scalable VF = " << MaxVF
5786                         << "\n");
5787     }
5788 
5789   return Result;
5790 }
5791 
5792 FixedScalableVFPair
5793 LoopVectorizationCostModel::computeMaxVF(ElementCount UserVF, unsigned UserIC) {
5794   if (Legal->getRuntimePointerChecking()->Need && TTI.hasBranchDivergence()) {
5795     // TODO: It may by useful to do since it's still likely to be dynamically
5796     // uniform if the target can skip.
5797     reportVectorizationFailure(
5798         "Not inserting runtime ptr check for divergent target",
5799         "runtime pointer checks needed. Not enabled for divergent target",
5800         "CantVersionLoopWithDivergentTarget", ORE, TheLoop);
5801     return FixedScalableVFPair::getNone();
5802   }
5803 
5804   unsigned TC = PSE.getSE()->getSmallConstantTripCount(TheLoop);
5805   LLVM_DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
5806   if (TC == 1) {
5807     reportVectorizationFailure("Single iteration (non) loop",
5808         "loop trip count is one, irrelevant for vectorization",
5809         "SingleIterationLoop", ORE, TheLoop);
5810     return FixedScalableVFPair::getNone();
5811   }
5812 
5813   switch (ScalarEpilogueStatus) {
5814   case CM_ScalarEpilogueAllowed:
5815     return computeFeasibleMaxVF(TC, UserVF);
5816   case CM_ScalarEpilogueNotAllowedUsePredicate:
5817     LLVM_FALLTHROUGH;
5818   case CM_ScalarEpilogueNotNeededUsePredicate:
5819     LLVM_DEBUG(
5820         dbgs() << "LV: vector predicate hint/switch found.\n"
5821                << "LV: Not allowing scalar epilogue, creating predicated "
5822                << "vector loop.\n");
5823     break;
5824   case CM_ScalarEpilogueNotAllowedLowTripLoop:
5825     // fallthrough as a special case of OptForSize
5826   case CM_ScalarEpilogueNotAllowedOptSize:
5827     if (ScalarEpilogueStatus == CM_ScalarEpilogueNotAllowedOptSize)
5828       LLVM_DEBUG(
5829           dbgs() << "LV: Not allowing scalar epilogue due to -Os/-Oz.\n");
5830     else
5831       LLVM_DEBUG(dbgs() << "LV: Not allowing scalar epilogue due to low trip "
5832                         << "count.\n");
5833 
5834     // Bail if runtime checks are required, which are not good when optimising
5835     // for size.
5836     if (runtimeChecksRequired())
5837       return FixedScalableVFPair::getNone();
5838 
5839     break;
5840   }
5841 
5842   // The only loops we can vectorize without a scalar epilogue, are loops with
5843   // a bottom-test and a single exiting block. We'd have to handle the fact
5844   // that not every instruction executes on the last iteration.  This will
5845   // require a lane mask which varies through the vector loop body.  (TODO)
5846   if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
5847     // If there was a tail-folding hint/switch, but we can't fold the tail by
5848     // masking, fallback to a vectorization with a scalar epilogue.
5849     if (ScalarEpilogueStatus == CM_ScalarEpilogueNotNeededUsePredicate) {
5850       LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking: vectorize with a "
5851                            "scalar epilogue instead.\n");
5852       ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
5853       return computeFeasibleMaxVF(TC, UserVF);
5854     }
5855     return FixedScalableVFPair::getNone();
5856   }
5857 
5858   // Now try the tail folding
5859 
5860   // Invalidate interleave groups that require an epilogue if we can't mask
5861   // the interleave-group.
5862   if (!useMaskedInterleavedAccesses(TTI)) {
5863     assert(WideningDecisions.empty() && Uniforms.empty() && Scalars.empty() &&
5864            "No decisions should have been taken at this point");
5865     // Note: There is no need to invalidate any cost modeling decisions here, as
5866     // non where taken so far.
5867     InterleaveInfo.invalidateGroupsRequiringScalarEpilogue();
5868   }
5869 
5870   FixedScalableVFPair MaxFactors = computeFeasibleMaxVF(TC, UserVF);
5871   // Avoid tail folding if the trip count is known to be a multiple of any VF
5872   // we chose.
5873   // FIXME: The condition below pessimises the case for fixed-width vectors,
5874   // when scalable VFs are also candidates for vectorization.
5875   if (MaxFactors.FixedVF.isVector() && !MaxFactors.ScalableVF) {
5876     ElementCount MaxFixedVF = MaxFactors.FixedVF;
5877     assert((UserVF.isNonZero() || isPowerOf2_32(MaxFixedVF.getFixedValue())) &&
5878            "MaxFixedVF must be a power of 2");
5879     unsigned MaxVFtimesIC = UserIC ? MaxFixedVF.getFixedValue() * UserIC
5880                                    : MaxFixedVF.getFixedValue();
5881     ScalarEvolution *SE = PSE.getSE();
5882     const SCEV *BackedgeTakenCount = PSE.getBackedgeTakenCount();
5883     const SCEV *ExitCount = SE->getAddExpr(
5884         BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType()));
5885     const SCEV *Rem = SE->getURemExpr(
5886         SE->applyLoopGuards(ExitCount, TheLoop),
5887         SE->getConstant(BackedgeTakenCount->getType(), MaxVFtimesIC));
5888     if (Rem->isZero()) {
5889       // Accept MaxFixedVF if we do not have a tail.
5890       LLVM_DEBUG(dbgs() << "LV: No tail will remain for any chosen VF.\n");
5891       return MaxFactors;
5892     }
5893   }
5894 
5895   // If we don't know the precise trip count, or if the trip count that we
5896   // found modulo the vectorization factor is not zero, try to fold the tail
5897   // by masking.
5898   // FIXME: look for a smaller MaxVF that does divide TC rather than masking.
5899   if (Legal->prepareToFoldTailByMasking()) {
5900     FoldTailByMasking = true;
5901     return MaxFactors;
5902   }
5903 
5904   // If there was a tail-folding hint/switch, but we can't fold the tail by
5905   // masking, fallback to a vectorization with a scalar epilogue.
5906   if (ScalarEpilogueStatus == CM_ScalarEpilogueNotNeededUsePredicate) {
5907     LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking: vectorize with a "
5908                          "scalar epilogue instead.\n");
5909     ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
5910     return MaxFactors;
5911   }
5912 
5913   if (ScalarEpilogueStatus == CM_ScalarEpilogueNotAllowedUsePredicate) {
5914     LLVM_DEBUG(dbgs() << "LV: Can't fold tail by masking: don't vectorize\n");
5915     return FixedScalableVFPair::getNone();
5916   }
5917 
5918   if (TC == 0) {
5919     reportVectorizationFailure(
5920         "Unable to calculate the loop count due to complex control flow",
5921         "unable to calculate the loop count due to complex control flow",
5922         "UnknownLoopCountComplexCFG", ORE, TheLoop);
5923     return FixedScalableVFPair::getNone();
5924   }
5925 
5926   reportVectorizationFailure(
5927       "Cannot optimize for size and vectorize at the same time.",
5928       "cannot optimize for size and vectorize at the same time. "
5929       "Enable vectorization of this loop with '#pragma clang loop "
5930       "vectorize(enable)' when compiling with -Os/-Oz",
5931       "NoTailLoopWithOptForSize", ORE, TheLoop);
5932   return FixedScalableVFPair::getNone();
5933 }
5934 
5935 ElementCount LoopVectorizationCostModel::getMaximizedVFForTarget(
5936     unsigned ConstTripCount, unsigned SmallestType, unsigned WidestType,
5937     const ElementCount &MaxSafeVF) {
5938   bool ComputeScalableMaxVF = MaxSafeVF.isScalable();
5939   TypeSize WidestRegister = TTI.getRegisterBitWidth(
5940       ComputeScalableMaxVF ? TargetTransformInfo::RGK_ScalableVector
5941                            : TargetTransformInfo::RGK_FixedWidthVector);
5942 
5943   // Convenience function to return the minimum of two ElementCounts.
5944   auto MinVF = [](const ElementCount &LHS, const ElementCount &RHS) {
5945     assert((LHS.isScalable() == RHS.isScalable()) &&
5946            "Scalable flags must match");
5947     return ElementCount::isKnownLT(LHS, RHS) ? LHS : RHS;
5948   };
5949 
5950   // Ensure MaxVF is a power of 2; the dependence distance bound may not be.
5951   // Note that both WidestRegister and WidestType may not be a powers of 2.
5952   auto MaxVectorElementCount = ElementCount::get(
5953       PowerOf2Floor(WidestRegister.getKnownMinSize() / WidestType),
5954       ComputeScalableMaxVF);
5955   MaxVectorElementCount = MinVF(MaxVectorElementCount, MaxSafeVF);
5956   LLVM_DEBUG(dbgs() << "LV: The Widest register safe to use is: "
5957                     << (MaxVectorElementCount * WidestType) << " bits.\n");
5958 
5959   if (!MaxVectorElementCount) {
5960     LLVM_DEBUG(dbgs() << "LV: The target has no "
5961                       << (ComputeScalableMaxVF ? "scalable" : "fixed")
5962                       << " vector registers.\n");
5963     return ElementCount::getFixed(1);
5964   }
5965 
5966   const auto TripCountEC = ElementCount::getFixed(ConstTripCount);
5967   if (ConstTripCount &&
5968       ElementCount::isKnownLE(TripCountEC, MaxVectorElementCount) &&
5969       isPowerOf2_32(ConstTripCount)) {
5970     // We need to clamp the VF to be the ConstTripCount. There is no point in
5971     // choosing a higher viable VF as done in the loop below. If
5972     // MaxVectorElementCount is scalable, we only fall back on a fixed VF when
5973     // the TC is less than or equal to the known number of lanes.
5974     LLVM_DEBUG(dbgs() << "LV: Clamping the MaxVF to the constant trip count: "
5975                       << ConstTripCount << "\n");
5976     return TripCountEC;
5977   }
5978 
5979   ElementCount MaxVF = MaxVectorElementCount;
5980   if (TTI.shouldMaximizeVectorBandwidth() ||
5981       (MaximizeBandwidth && isScalarEpilogueAllowed())) {
5982     auto MaxVectorElementCountMaxBW = ElementCount::get(
5983         PowerOf2Floor(WidestRegister.getKnownMinSize() / SmallestType),
5984         ComputeScalableMaxVF);
5985     MaxVectorElementCountMaxBW = MinVF(MaxVectorElementCountMaxBW, MaxSafeVF);
5986 
5987     // Collect all viable vectorization factors larger than the default MaxVF
5988     // (i.e. MaxVectorElementCount).
5989     SmallVector<ElementCount, 8> VFs;
5990     for (ElementCount VS = MaxVectorElementCount * 2;
5991          ElementCount::isKnownLE(VS, MaxVectorElementCountMaxBW); VS *= 2)
5992       VFs.push_back(VS);
5993 
5994     // For each VF calculate its register usage.
5995     auto RUs = calculateRegisterUsage(VFs);
5996 
5997     // Select the largest VF which doesn't require more registers than existing
5998     // ones.
5999     for (int i = RUs.size() - 1; i >= 0; --i) {
6000       bool Selected = true;
6001       for (auto &pair : RUs[i].MaxLocalUsers) {
6002         unsigned TargetNumRegisters = TTI.getNumberOfRegisters(pair.first);
6003         if (pair.second > TargetNumRegisters)
6004           Selected = false;
6005       }
6006       if (Selected) {
6007         MaxVF = VFs[i];
6008         break;
6009       }
6010     }
6011     if (ElementCount MinVF =
6012             TTI.getMinimumVF(SmallestType, ComputeScalableMaxVF)) {
6013       if (ElementCount::isKnownLT(MaxVF, MinVF)) {
6014         LLVM_DEBUG(dbgs() << "LV: Overriding calculated MaxVF(" << MaxVF
6015                           << ") with target's minimum: " << MinVF << '\n');
6016         MaxVF = MinVF;
6017       }
6018     }
6019   }
6020   return MaxVF;
6021 }
6022 
6023 bool LoopVectorizationCostModel::isMoreProfitable(
6024     const VectorizationFactor &A, const VectorizationFactor &B) const {
6025   InstructionCost CostA = A.Cost;
6026   InstructionCost CostB = B.Cost;
6027 
6028   unsigned MaxTripCount = PSE.getSE()->getSmallConstantMaxTripCount(TheLoop);
6029 
6030   if (!A.Width.isScalable() && !B.Width.isScalable() && FoldTailByMasking &&
6031       MaxTripCount) {
6032     // If we are folding the tail and the trip count is a known (possibly small)
6033     // constant, the trip count will be rounded up to an integer number of
6034     // iterations. The total cost will be PerIterationCost*ceil(TripCount/VF),
6035     // which we compare directly. When not folding the tail, the total cost will
6036     // be PerIterationCost*floor(TC/VF) + Scalar remainder cost, and so is
6037     // approximated with the per-lane cost below instead of using the tripcount
6038     // as here.
6039     auto RTCostA = CostA * divideCeil(MaxTripCount, A.Width.getFixedValue());
6040     auto RTCostB = CostB * divideCeil(MaxTripCount, B.Width.getFixedValue());
6041     return RTCostA < RTCostB;
6042   }
6043 
6044   // When set to preferred, for now assume vscale may be larger than 1, so
6045   // that scalable vectorization is slightly favorable over fixed-width
6046   // vectorization.
6047   if (Hints->isScalableVectorizationPreferred())
6048     if (A.Width.isScalable() && !B.Width.isScalable())
6049       return (CostA * B.Width.getKnownMinValue()) <=
6050              (CostB * A.Width.getKnownMinValue());
6051 
6052   // To avoid the need for FP division:
6053   //      (CostA / A.Width) < (CostB / B.Width)
6054   // <=>  (CostA * B.Width) < (CostB * A.Width)
6055   return (CostA * B.Width.getKnownMinValue()) <
6056          (CostB * A.Width.getKnownMinValue());
6057 }
6058 
6059 VectorizationFactor LoopVectorizationCostModel::selectVectorizationFactor(
6060     const ElementCountSet &VFCandidates) {
6061   InstructionCost ExpectedCost = expectedCost(ElementCount::getFixed(1)).first;
6062   LLVM_DEBUG(dbgs() << "LV: Scalar loop costs: " << ExpectedCost << ".\n");
6063   assert(ExpectedCost.isValid() && "Unexpected invalid cost for scalar loop");
6064   assert(VFCandidates.count(ElementCount::getFixed(1)) &&
6065          "Expected Scalar VF to be a candidate");
6066 
6067   const VectorizationFactor ScalarCost(ElementCount::getFixed(1), ExpectedCost);
6068   VectorizationFactor ChosenFactor = ScalarCost;
6069 
6070   bool ForceVectorization = Hints->getForce() == LoopVectorizeHints::FK_Enabled;
6071   if (ForceVectorization && VFCandidates.size() > 1) {
6072     // Ignore scalar width, because the user explicitly wants vectorization.
6073     // Initialize cost to max so that VF = 2 is, at least, chosen during cost
6074     // evaluation.
6075     ChosenFactor.Cost = InstructionCost::getMax();
6076   }
6077 
6078   for (const auto &i : VFCandidates) {
6079     // The cost for scalar VF=1 is already calculated, so ignore it.
6080     if (i.isScalar())
6081       continue;
6082 
6083     VectorizationCostTy C = expectedCost(i);
6084     VectorizationFactor Candidate(i, C.first);
6085     LLVM_DEBUG(
6086         dbgs() << "LV: Vector loop of width " << i << " costs: "
6087                << (Candidate.Cost / Candidate.Width.getKnownMinValue())
6088                << (i.isScalable() ? " (assuming a minimum vscale of 1)" : "")
6089                << ".\n");
6090 
6091     if (!C.second && !ForceVectorization) {
6092       LLVM_DEBUG(
6093           dbgs() << "LV: Not considering vector loop of width " << i
6094                  << " because it will not generate any vector instructions.\n");
6095       continue;
6096     }
6097 
6098     // If profitable add it to ProfitableVF list.
6099     if (isMoreProfitable(Candidate, ScalarCost))
6100       ProfitableVFs.push_back(Candidate);
6101 
6102     if (isMoreProfitable(Candidate, ChosenFactor))
6103       ChosenFactor = Candidate;
6104   }
6105 
6106   if (!EnableCondStoresVectorization && NumPredStores) {
6107     reportVectorizationFailure("There are conditional stores.",
6108         "store that is conditionally executed prevents vectorization",
6109         "ConditionalStore", ORE, TheLoop);
6110     ChosenFactor = ScalarCost;
6111   }
6112 
6113   LLVM_DEBUG(if (ForceVectorization && !ChosenFactor.Width.isScalar() &&
6114                  ChosenFactor.Cost >= ScalarCost.Cost) dbgs()
6115              << "LV: Vectorization seems to be not beneficial, "
6116              << "but was forced by a user.\n");
6117   LLVM_DEBUG(dbgs() << "LV: Selecting VF: " << ChosenFactor.Width << ".\n");
6118   return ChosenFactor;
6119 }
6120 
6121 bool LoopVectorizationCostModel::isCandidateForEpilogueVectorization(
6122     const Loop &L, ElementCount VF) const {
6123   // Cross iteration phis such as reductions need special handling and are
6124   // currently unsupported.
6125   if (any_of(L.getHeader()->phis(), [&](PHINode &Phi) {
6126         return Legal->isFirstOrderRecurrence(&Phi) ||
6127                Legal->isReductionVariable(&Phi);
6128       }))
6129     return false;
6130 
6131   // Phis with uses outside of the loop require special handling and are
6132   // currently unsupported.
6133   for (auto &Entry : Legal->getInductionVars()) {
6134     // Look for uses of the value of the induction at the last iteration.
6135     Value *PostInc = Entry.first->getIncomingValueForBlock(L.getLoopLatch());
6136     for (User *U : PostInc->users())
6137       if (!L.contains(cast<Instruction>(U)))
6138         return false;
6139     // Look for uses of penultimate value of the induction.
6140     for (User *U : Entry.first->users())
6141       if (!L.contains(cast<Instruction>(U)))
6142         return false;
6143   }
6144 
6145   // Induction variables that are widened require special handling that is
6146   // currently not supported.
6147   if (any_of(Legal->getInductionVars(), [&](auto &Entry) {
6148         return !(this->isScalarAfterVectorization(Entry.first, VF) ||
6149                  this->isProfitableToScalarize(Entry.first, VF));
6150       }))
6151     return false;
6152 
6153   // Epilogue vectorization code has not been auditted to ensure it handles
6154   // non-latch exits properly.  It may be fine, but it needs auditted and
6155   // tested.
6156   if (L.getExitingBlock() != L.getLoopLatch())
6157     return false;
6158 
6159   return true;
6160 }
6161 
6162 bool LoopVectorizationCostModel::isEpilogueVectorizationProfitable(
6163     const ElementCount VF) const {
6164   // FIXME: We need a much better cost-model to take different parameters such
6165   // as register pressure, code size increase and cost of extra branches into
6166   // account. For now we apply a very crude heuristic and only consider loops
6167   // with vectorization factors larger than a certain value.
6168   // We also consider epilogue vectorization unprofitable for targets that don't
6169   // consider interleaving beneficial (eg. MVE).
6170   if (TTI.getMaxInterleaveFactor(VF.getKnownMinValue()) <= 1)
6171     return false;
6172   if (VF.getFixedValue() >= EpilogueVectorizationMinVF)
6173     return true;
6174   return false;
6175 }
6176 
6177 VectorizationFactor
6178 LoopVectorizationCostModel::selectEpilogueVectorizationFactor(
6179     const ElementCount MainLoopVF, const LoopVectorizationPlanner &LVP) {
6180   VectorizationFactor Result = VectorizationFactor::Disabled();
6181   if (!EnableEpilogueVectorization) {
6182     LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization is disabled.\n";);
6183     return Result;
6184   }
6185 
6186   if (!isScalarEpilogueAllowed()) {
6187     LLVM_DEBUG(
6188         dbgs() << "LEV: Unable to vectorize epilogue because no epilogue is "
6189                   "allowed.\n";);
6190     return Result;
6191   }
6192 
6193   // FIXME: This can be fixed for scalable vectors later, because at this stage
6194   // the LoopVectorizer will only consider vectorizing a loop with scalable
6195   // vectors when the loop has a hint to enable vectorization for a given VF.
6196   if (MainLoopVF.isScalable()) {
6197     LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization for scalable vectors not "
6198                          "yet supported.\n");
6199     return Result;
6200   }
6201 
6202   // Not really a cost consideration, but check for unsupported cases here to
6203   // simplify the logic.
6204   if (!isCandidateForEpilogueVectorization(*TheLoop, MainLoopVF)) {
6205     LLVM_DEBUG(
6206         dbgs() << "LEV: Unable to vectorize epilogue because the loop is "
6207                   "not a supported candidate.\n";);
6208     return Result;
6209   }
6210 
6211   if (EpilogueVectorizationForceVF > 1) {
6212     LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization factor is forced.\n";);
6213     if (LVP.hasPlanWithVFs(
6214             {MainLoopVF, ElementCount::getFixed(EpilogueVectorizationForceVF)}))
6215       return {ElementCount::getFixed(EpilogueVectorizationForceVF), 0};
6216     else {
6217       LLVM_DEBUG(
6218           dbgs()
6219               << "LEV: Epilogue vectorization forced factor is not viable.\n";);
6220       return Result;
6221     }
6222   }
6223 
6224   if (TheLoop->getHeader()->getParent()->hasOptSize() ||
6225       TheLoop->getHeader()->getParent()->hasMinSize()) {
6226     LLVM_DEBUG(
6227         dbgs()
6228             << "LEV: Epilogue vectorization skipped due to opt for size.\n";);
6229     return Result;
6230   }
6231 
6232   if (!isEpilogueVectorizationProfitable(MainLoopVF))
6233     return Result;
6234 
6235   for (auto &NextVF : ProfitableVFs)
6236     if (ElementCount::isKnownLT(NextVF.Width, MainLoopVF) &&
6237         (Result.Width.getFixedValue() == 1 ||
6238          isMoreProfitable(NextVF, Result)) &&
6239         LVP.hasPlanWithVFs({MainLoopVF, NextVF.Width}))
6240       Result = NextVF;
6241 
6242   if (Result != VectorizationFactor::Disabled())
6243     LLVM_DEBUG(dbgs() << "LEV: Vectorizing epilogue loop with VF = "
6244                       << Result.Width.getFixedValue() << "\n";);
6245   return Result;
6246 }
6247 
6248 std::pair<unsigned, unsigned>
6249 LoopVectorizationCostModel::getSmallestAndWidestTypes() {
6250   unsigned MinWidth = -1U;
6251   unsigned MaxWidth = 8;
6252   const DataLayout &DL = TheFunction->getParent()->getDataLayout();
6253   for (Type *T : ElementTypesInLoop) {
6254     MinWidth = std::min<unsigned>(
6255         MinWidth, DL.getTypeSizeInBits(T->getScalarType()).getFixedSize());
6256     MaxWidth = std::max<unsigned>(
6257         MaxWidth, DL.getTypeSizeInBits(T->getScalarType()).getFixedSize());
6258   }
6259   return {MinWidth, MaxWidth};
6260 }
6261 
6262 void LoopVectorizationCostModel::collectElementTypesForWidening() {
6263   ElementTypesInLoop.clear();
6264   // For each block.
6265   for (BasicBlock *BB : TheLoop->blocks()) {
6266     // For each instruction in the loop.
6267     for (Instruction &I : BB->instructionsWithoutDebug()) {
6268       Type *T = I.getType();
6269 
6270       // Skip ignored values.
6271       if (ValuesToIgnore.count(&I))
6272         continue;
6273 
6274       // Only examine Loads, Stores and PHINodes.
6275       if (!isa<LoadInst>(I) && !isa<StoreInst>(I) && !isa<PHINode>(I))
6276         continue;
6277 
6278       // Examine PHI nodes that are reduction variables. Update the type to
6279       // account for the recurrence type.
6280       if (auto *PN = dyn_cast<PHINode>(&I)) {
6281         if (!Legal->isReductionVariable(PN))
6282           continue;
6283         const RecurrenceDescriptor &RdxDesc = Legal->getReductionVars()[PN];
6284         if (PreferInLoopReductions || useOrderedReductions(RdxDesc) ||
6285             TTI.preferInLoopReduction(RdxDesc.getOpcode(),
6286                                       RdxDesc.getRecurrenceType(),
6287                                       TargetTransformInfo::ReductionFlags()))
6288           continue;
6289         T = RdxDesc.getRecurrenceType();
6290       }
6291 
6292       // Examine the stored values.
6293       if (auto *ST = dyn_cast<StoreInst>(&I))
6294         T = ST->getValueOperand()->getType();
6295 
6296       // Ignore loaded pointer types and stored pointer types that are not
6297       // vectorizable.
6298       //
6299       // FIXME: The check here attempts to predict whether a load or store will
6300       //        be vectorized. We only know this for certain after a VF has
6301       //        been selected. Here, we assume that if an access can be
6302       //        vectorized, it will be. We should also look at extending this
6303       //        optimization to non-pointer types.
6304       //
6305       if (T->isPointerTy() && !isConsecutiveLoadOrStore(&I) &&
6306           !isAccessInterleaved(&I) && !isLegalGatherOrScatter(&I))
6307         continue;
6308 
6309       ElementTypesInLoop.insert(T);
6310     }
6311   }
6312 }
6313 
6314 unsigned LoopVectorizationCostModel::selectInterleaveCount(ElementCount VF,
6315                                                            unsigned LoopCost) {
6316   // -- The interleave heuristics --
6317   // We interleave the loop in order to expose ILP and reduce the loop overhead.
6318   // There are many micro-architectural considerations that we can't predict
6319   // at this level. For example, frontend pressure (on decode or fetch) due to
6320   // code size, or the number and capabilities of the execution ports.
6321   //
6322   // We use the following heuristics to select the interleave count:
6323   // 1. If the code has reductions, then we interleave to break the cross
6324   // iteration dependency.
6325   // 2. If the loop is really small, then we interleave to reduce the loop
6326   // overhead.
6327   // 3. We don't interleave if we think that we will spill registers to memory
6328   // due to the increased register pressure.
6329 
6330   if (!isScalarEpilogueAllowed())
6331     return 1;
6332 
6333   // We used the distance for the interleave count.
6334   if (Legal->getMaxSafeDepDistBytes() != -1U)
6335     return 1;
6336 
6337   auto BestKnownTC = getSmallBestKnownTC(*PSE.getSE(), TheLoop);
6338   const bool HasReductions = !Legal->getReductionVars().empty();
6339   // Do not interleave loops with a relatively small known or estimated trip
6340   // count. But we will interleave when InterleaveSmallLoopScalarReduction is
6341   // enabled, and the code has scalar reductions(HasReductions && VF = 1),
6342   // because with the above conditions interleaving can expose ILP and break
6343   // cross iteration dependences for reductions.
6344   if (BestKnownTC && (*BestKnownTC < TinyTripCountInterleaveThreshold) &&
6345       !(InterleaveSmallLoopScalarReduction && HasReductions && VF.isScalar()))
6346     return 1;
6347 
6348   RegisterUsage R = calculateRegisterUsage({VF})[0];
6349   // We divide by these constants so assume that we have at least one
6350   // instruction that uses at least one register.
6351   for (auto& pair : R.MaxLocalUsers) {
6352     pair.second = std::max(pair.second, 1U);
6353   }
6354 
6355   // We calculate the interleave count using the following formula.
6356   // Subtract the number of loop invariants from the number of available
6357   // registers. These registers are used by all of the interleaved instances.
6358   // Next, divide the remaining registers by the number of registers that is
6359   // required by the loop, in order to estimate how many parallel instances
6360   // fit without causing spills. All of this is rounded down if necessary to be
6361   // a power of two. We want power of two interleave count to simplify any
6362   // addressing operations or alignment considerations.
6363   // We also want power of two interleave counts to ensure that the induction
6364   // variable of the vector loop wraps to zero, when tail is folded by masking;
6365   // this currently happens when OptForSize, in which case IC is set to 1 above.
6366   unsigned IC = UINT_MAX;
6367 
6368   for (auto& pair : R.MaxLocalUsers) {
6369     unsigned TargetNumRegisters = TTI.getNumberOfRegisters(pair.first);
6370     LLVM_DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters
6371                       << " registers of "
6372                       << TTI.getRegisterClassName(pair.first) << " register class\n");
6373     if (VF.isScalar()) {
6374       if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
6375         TargetNumRegisters = ForceTargetNumScalarRegs;
6376     } else {
6377       if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
6378         TargetNumRegisters = ForceTargetNumVectorRegs;
6379     }
6380     unsigned MaxLocalUsers = pair.second;
6381     unsigned LoopInvariantRegs = 0;
6382     if (R.LoopInvariantRegs.find(pair.first) != R.LoopInvariantRegs.end())
6383       LoopInvariantRegs = R.LoopInvariantRegs[pair.first];
6384 
6385     unsigned TmpIC = PowerOf2Floor((TargetNumRegisters - LoopInvariantRegs) / MaxLocalUsers);
6386     // Don't count the induction variable as interleaved.
6387     if (EnableIndVarRegisterHeur) {
6388       TmpIC =
6389           PowerOf2Floor((TargetNumRegisters - LoopInvariantRegs - 1) /
6390                         std::max(1U, (MaxLocalUsers - 1)));
6391     }
6392 
6393     IC = std::min(IC, TmpIC);
6394   }
6395 
6396   // Clamp the interleave ranges to reasonable counts.
6397   unsigned MaxInterleaveCount =
6398       TTI.getMaxInterleaveFactor(VF.getKnownMinValue());
6399 
6400   // Check if the user has overridden the max.
6401   if (VF.isScalar()) {
6402     if (ForceTargetMaxScalarInterleaveFactor.getNumOccurrences() > 0)
6403       MaxInterleaveCount = ForceTargetMaxScalarInterleaveFactor;
6404   } else {
6405     if (ForceTargetMaxVectorInterleaveFactor.getNumOccurrences() > 0)
6406       MaxInterleaveCount = ForceTargetMaxVectorInterleaveFactor;
6407   }
6408 
6409   // If trip count is known or estimated compile time constant, limit the
6410   // interleave count to be less than the trip count divided by VF, provided it
6411   // is at least 1.
6412   //
6413   // For scalable vectors we can't know if interleaving is beneficial. It may
6414   // not be beneficial for small loops if none of the lanes in the second vector
6415   // iterations is enabled. However, for larger loops, there is likely to be a
6416   // similar benefit as for fixed-width vectors. For now, we choose to leave
6417   // the InterleaveCount as if vscale is '1', although if some information about
6418   // the vector is known (e.g. min vector size), we can make a better decision.
6419   if (BestKnownTC) {
6420     MaxInterleaveCount =
6421         std::min(*BestKnownTC / VF.getKnownMinValue(), MaxInterleaveCount);
6422     // Make sure MaxInterleaveCount is greater than 0.
6423     MaxInterleaveCount = std::max(1u, MaxInterleaveCount);
6424   }
6425 
6426   assert(MaxInterleaveCount > 0 &&
6427          "Maximum interleave count must be greater than 0");
6428 
6429   // Clamp the calculated IC to be between the 1 and the max interleave count
6430   // that the target and trip count allows.
6431   if (IC > MaxInterleaveCount)
6432     IC = MaxInterleaveCount;
6433   else
6434     // Make sure IC is greater than 0.
6435     IC = std::max(1u, IC);
6436 
6437   assert(IC > 0 && "Interleave count must be greater than 0.");
6438 
6439   // If we did not calculate the cost for VF (because the user selected the VF)
6440   // then we calculate the cost of VF here.
6441   if (LoopCost == 0) {
6442     InstructionCost C = expectedCost(VF).first;
6443     assert(C.isValid() && "Expected to have chosen a VF with valid cost");
6444     LoopCost = *C.getValue();
6445   }
6446 
6447   assert(LoopCost && "Non-zero loop cost expected");
6448 
6449   // Interleave if we vectorized this loop and there is a reduction that could
6450   // benefit from interleaving.
6451   if (VF.isVector() && HasReductions) {
6452     LLVM_DEBUG(dbgs() << "LV: Interleaving because of reductions.\n");
6453     return IC;
6454   }
6455 
6456   // Note that if we've already vectorized the loop we will have done the
6457   // runtime check and so interleaving won't require further checks.
6458   bool InterleavingRequiresRuntimePointerCheck =
6459       (VF.isScalar() && Legal->getRuntimePointerChecking()->Need);
6460 
6461   // We want to interleave small loops in order to reduce the loop overhead and
6462   // potentially expose ILP opportunities.
6463   LLVM_DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n'
6464                     << "LV: IC is " << IC << '\n'
6465                     << "LV: VF is " << VF << '\n');
6466   const bool AggressivelyInterleaveReductions =
6467       TTI.enableAggressiveInterleaving(HasReductions);
6468   if (!InterleavingRequiresRuntimePointerCheck && LoopCost < SmallLoopCost) {
6469     // We assume that the cost overhead is 1 and we use the cost model
6470     // to estimate the cost of the loop and interleave until the cost of the
6471     // loop overhead is about 5% of the cost of the loop.
6472     unsigned SmallIC =
6473         std::min(IC, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost));
6474 
6475     // Interleave until store/load ports (estimated by max interleave count) are
6476     // saturated.
6477     unsigned NumStores = Legal->getNumStores();
6478     unsigned NumLoads = Legal->getNumLoads();
6479     unsigned StoresIC = IC / (NumStores ? NumStores : 1);
6480     unsigned LoadsIC = IC / (NumLoads ? NumLoads : 1);
6481 
6482     // If we have a scalar reduction (vector reductions are already dealt with
6483     // by this point), we can increase the critical path length if the loop
6484     // we're interleaving is inside another loop. Limit, by default to 2, so the
6485     // critical path only gets increased by one reduction operation.
6486     if (HasReductions && TheLoop->getLoopDepth() > 1) {
6487       unsigned F = static_cast<unsigned>(MaxNestedScalarReductionIC);
6488       SmallIC = std::min(SmallIC, F);
6489       StoresIC = std::min(StoresIC, F);
6490       LoadsIC = std::min(LoadsIC, F);
6491     }
6492 
6493     if (EnableLoadStoreRuntimeInterleave &&
6494         std::max(StoresIC, LoadsIC) > SmallIC) {
6495       LLVM_DEBUG(
6496           dbgs() << "LV: Interleaving to saturate store or load ports.\n");
6497       return std::max(StoresIC, LoadsIC);
6498     }
6499 
6500     // If there are scalar reductions and TTI has enabled aggressive
6501     // interleaving for reductions, we will interleave to expose ILP.
6502     if (InterleaveSmallLoopScalarReduction && VF.isScalar() &&
6503         AggressivelyInterleaveReductions) {
6504       LLVM_DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
6505       // Interleave no less than SmallIC but not as aggressive as the normal IC
6506       // to satisfy the rare situation when resources are too limited.
6507       return std::max(IC / 2, SmallIC);
6508     } else {
6509       LLVM_DEBUG(dbgs() << "LV: Interleaving to reduce branch cost.\n");
6510       return SmallIC;
6511     }
6512   }
6513 
6514   // Interleave if this is a large loop (small loops are already dealt with by
6515   // this point) that could benefit from interleaving.
6516   if (AggressivelyInterleaveReductions) {
6517     LLVM_DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
6518     return IC;
6519   }
6520 
6521   LLVM_DEBUG(dbgs() << "LV: Not Interleaving.\n");
6522   return 1;
6523 }
6524 
6525 SmallVector<LoopVectorizationCostModel::RegisterUsage, 8>
6526 LoopVectorizationCostModel::calculateRegisterUsage(ArrayRef<ElementCount> VFs) {
6527   // This function calculates the register usage by measuring the highest number
6528   // of values that are alive at a single location. Obviously, this is a very
6529   // rough estimation. We scan the loop in a topological order in order and
6530   // assign a number to each instruction. We use RPO to ensure that defs are
6531   // met before their users. We assume that each instruction that has in-loop
6532   // users starts an interval. We record every time that an in-loop value is
6533   // used, so we have a list of the first and last occurrences of each
6534   // instruction. Next, we transpose this data structure into a multi map that
6535   // holds the list of intervals that *end* at a specific location. This multi
6536   // map allows us to perform a linear search. We scan the instructions linearly
6537   // and record each time that a new interval starts, by placing it in a set.
6538   // If we find this value in the multi-map then we remove it from the set.
6539   // The max register usage is the maximum size of the set.
6540   // We also search for instructions that are defined outside the loop, but are
6541   // used inside the loop. We need this number separately from the max-interval
6542   // usage number because when we unroll, loop-invariant values do not take
6543   // more register.
6544   LoopBlocksDFS DFS(TheLoop);
6545   DFS.perform(LI);
6546 
6547   RegisterUsage RU;
6548 
6549   // Each 'key' in the map opens a new interval. The values
6550   // of the map are the index of the 'last seen' usage of the
6551   // instruction that is the key.
6552   using IntervalMap = DenseMap<Instruction *, unsigned>;
6553 
6554   // Maps instruction to its index.
6555   SmallVector<Instruction *, 64> IdxToInstr;
6556   // Marks the end of each interval.
6557   IntervalMap EndPoint;
6558   // Saves the list of instruction indices that are used in the loop.
6559   SmallPtrSet<Instruction *, 8> Ends;
6560   // Saves the list of values that are used in the loop but are
6561   // defined outside the loop, such as arguments and constants.
6562   SmallPtrSet<Value *, 8> LoopInvariants;
6563 
6564   for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) {
6565     for (Instruction &I : BB->instructionsWithoutDebug()) {
6566       IdxToInstr.push_back(&I);
6567 
6568       // Save the end location of each USE.
6569       for (Value *U : I.operands()) {
6570         auto *Instr = dyn_cast<Instruction>(U);
6571 
6572         // Ignore non-instruction values such as arguments, constants, etc.
6573         if (!Instr)
6574           continue;
6575 
6576         // If this instruction is outside the loop then record it and continue.
6577         if (!TheLoop->contains(Instr)) {
6578           LoopInvariants.insert(Instr);
6579           continue;
6580         }
6581 
6582         // Overwrite previous end points.
6583         EndPoint[Instr] = IdxToInstr.size();
6584         Ends.insert(Instr);
6585       }
6586     }
6587   }
6588 
6589   // Saves the list of intervals that end with the index in 'key'.
6590   using InstrList = SmallVector<Instruction *, 2>;
6591   DenseMap<unsigned, InstrList> TransposeEnds;
6592 
6593   // Transpose the EndPoints to a list of values that end at each index.
6594   for (auto &Interval : EndPoint)
6595     TransposeEnds[Interval.second].push_back(Interval.first);
6596 
6597   SmallPtrSet<Instruction *, 8> OpenIntervals;
6598   SmallVector<RegisterUsage, 8> RUs(VFs.size());
6599   SmallVector<SmallMapVector<unsigned, unsigned, 4>, 8> MaxUsages(VFs.size());
6600 
6601   LLVM_DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
6602 
6603   // A lambda that gets the register usage for the given type and VF.
6604   const auto &TTICapture = TTI;
6605   auto GetRegUsage = [&TTICapture](Type *Ty, ElementCount VF) -> unsigned {
6606     if (Ty->isTokenTy() || !VectorType::isValidElementType(Ty))
6607       return 0;
6608     InstructionCost::CostType RegUsage =
6609         *TTICapture.getRegUsageForType(VectorType::get(Ty, VF)).getValue();
6610     assert(RegUsage >= 0 && RegUsage <= std::numeric_limits<unsigned>::max() &&
6611            "Nonsensical values for register usage.");
6612     return RegUsage;
6613   };
6614 
6615   for (unsigned int i = 0, s = IdxToInstr.size(); i < s; ++i) {
6616     Instruction *I = IdxToInstr[i];
6617 
6618     // Remove all of the instructions that end at this location.
6619     InstrList &List = TransposeEnds[i];
6620     for (Instruction *ToRemove : List)
6621       OpenIntervals.erase(ToRemove);
6622 
6623     // Ignore instructions that are never used within the loop.
6624     if (!Ends.count(I))
6625       continue;
6626 
6627     // Skip ignored values.
6628     if (ValuesToIgnore.count(I))
6629       continue;
6630 
6631     // For each VF find the maximum usage of registers.
6632     for (unsigned j = 0, e = VFs.size(); j < e; ++j) {
6633       // Count the number of live intervals.
6634       SmallMapVector<unsigned, unsigned, 4> RegUsage;
6635 
6636       if (VFs[j].isScalar()) {
6637         for (auto Inst : OpenIntervals) {
6638           unsigned ClassID = TTI.getRegisterClassForType(false, Inst->getType());
6639           if (RegUsage.find(ClassID) == RegUsage.end())
6640             RegUsage[ClassID] = 1;
6641           else
6642             RegUsage[ClassID] += 1;
6643         }
6644       } else {
6645         collectUniformsAndScalars(VFs[j]);
6646         for (auto Inst : OpenIntervals) {
6647           // Skip ignored values for VF > 1.
6648           if (VecValuesToIgnore.count(Inst))
6649             continue;
6650           if (isScalarAfterVectorization(Inst, VFs[j])) {
6651             unsigned ClassID = TTI.getRegisterClassForType(false, Inst->getType());
6652             if (RegUsage.find(ClassID) == RegUsage.end())
6653               RegUsage[ClassID] = 1;
6654             else
6655               RegUsage[ClassID] += 1;
6656           } else {
6657             unsigned ClassID = TTI.getRegisterClassForType(true, Inst->getType());
6658             if (RegUsage.find(ClassID) == RegUsage.end())
6659               RegUsage[ClassID] = GetRegUsage(Inst->getType(), VFs[j]);
6660             else
6661               RegUsage[ClassID] += GetRegUsage(Inst->getType(), VFs[j]);
6662           }
6663         }
6664       }
6665 
6666       for (auto& pair : RegUsage) {
6667         if (MaxUsages[j].find(pair.first) != MaxUsages[j].end())
6668           MaxUsages[j][pair.first] = std::max(MaxUsages[j][pair.first], pair.second);
6669         else
6670           MaxUsages[j][pair.first] = pair.second;
6671       }
6672     }
6673 
6674     LLVM_DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # "
6675                       << OpenIntervals.size() << '\n');
6676 
6677     // Add the current instruction to the list of open intervals.
6678     OpenIntervals.insert(I);
6679   }
6680 
6681   for (unsigned i = 0, e = VFs.size(); i < e; ++i) {
6682     SmallMapVector<unsigned, unsigned, 4> Invariant;
6683 
6684     for (auto Inst : LoopInvariants) {
6685       unsigned Usage =
6686           VFs[i].isScalar() ? 1 : GetRegUsage(Inst->getType(), VFs[i]);
6687       unsigned ClassID =
6688           TTI.getRegisterClassForType(VFs[i].isVector(), Inst->getType());
6689       if (Invariant.find(ClassID) == Invariant.end())
6690         Invariant[ClassID] = Usage;
6691       else
6692         Invariant[ClassID] += Usage;
6693     }
6694 
6695     LLVM_DEBUG({
6696       dbgs() << "LV(REG): VF = " << VFs[i] << '\n';
6697       dbgs() << "LV(REG): Found max usage: " << MaxUsages[i].size()
6698              << " item\n";
6699       for (const auto &pair : MaxUsages[i]) {
6700         dbgs() << "LV(REG): RegisterClass: "
6701                << TTI.getRegisterClassName(pair.first) << ", " << pair.second
6702                << " registers\n";
6703       }
6704       dbgs() << "LV(REG): Found invariant usage: " << Invariant.size()
6705              << " item\n";
6706       for (const auto &pair : Invariant) {
6707         dbgs() << "LV(REG): RegisterClass: "
6708                << TTI.getRegisterClassName(pair.first) << ", " << pair.second
6709                << " registers\n";
6710       }
6711     });
6712 
6713     RU.LoopInvariantRegs = Invariant;
6714     RU.MaxLocalUsers = MaxUsages[i];
6715     RUs[i] = RU;
6716   }
6717 
6718   return RUs;
6719 }
6720 
6721 bool LoopVectorizationCostModel::useEmulatedMaskMemRefHack(Instruction *I){
6722   // TODO: Cost model for emulated masked load/store is completely
6723   // broken. This hack guides the cost model to use an artificially
6724   // high enough value to practically disable vectorization with such
6725   // operations, except where previously deployed legality hack allowed
6726   // using very low cost values. This is to avoid regressions coming simply
6727   // from moving "masked load/store" check from legality to cost model.
6728   // Masked Load/Gather emulation was previously never allowed.
6729   // Limited number of Masked Store/Scatter emulation was allowed.
6730   assert(isPredicatedInst(I) &&
6731          "Expecting a scalar emulated instruction");
6732   return isa<LoadInst>(I) ||
6733          (isa<StoreInst>(I) &&
6734           NumPredStores > NumberOfStoresToPredicate);
6735 }
6736 
6737 void LoopVectorizationCostModel::collectInstsToScalarize(ElementCount VF) {
6738   // If we aren't vectorizing the loop, or if we've already collected the
6739   // instructions to scalarize, there's nothing to do. Collection may already
6740   // have occurred if we have a user-selected VF and are now computing the
6741   // expected cost for interleaving.
6742   if (VF.isScalar() || VF.isZero() ||
6743       InstsToScalarize.find(VF) != InstsToScalarize.end())
6744     return;
6745 
6746   // Initialize a mapping for VF in InstsToScalalarize. If we find that it's
6747   // not profitable to scalarize any instructions, the presence of VF in the
6748   // map will indicate that we've analyzed it already.
6749   ScalarCostsTy &ScalarCostsVF = InstsToScalarize[VF];
6750 
6751   // Find all the instructions that are scalar with predication in the loop and
6752   // determine if it would be better to not if-convert the blocks they are in.
6753   // If so, we also record the instructions to scalarize.
6754   for (BasicBlock *BB : TheLoop->blocks()) {
6755     if (!blockNeedsPredication(BB))
6756       continue;
6757     for (Instruction &I : *BB)
6758       if (isScalarWithPredication(&I)) {
6759         ScalarCostsTy ScalarCosts;
6760         // Do not apply discount logic if hacked cost is needed
6761         // for emulated masked memrefs.
6762         if (!useEmulatedMaskMemRefHack(&I) &&
6763             computePredInstDiscount(&I, ScalarCosts, VF) >= 0)
6764           ScalarCostsVF.insert(ScalarCosts.begin(), ScalarCosts.end());
6765         // Remember that BB will remain after vectorization.
6766         PredicatedBBsAfterVectorization.insert(BB);
6767       }
6768   }
6769 }
6770 
6771 int LoopVectorizationCostModel::computePredInstDiscount(
6772     Instruction *PredInst, ScalarCostsTy &ScalarCosts, ElementCount VF) {
6773   assert(!isUniformAfterVectorization(PredInst, VF) &&
6774          "Instruction marked uniform-after-vectorization will be predicated");
6775 
6776   // Initialize the discount to zero, meaning that the scalar version and the
6777   // vector version cost the same.
6778   InstructionCost Discount = 0;
6779 
6780   // Holds instructions to analyze. The instructions we visit are mapped in
6781   // ScalarCosts. Those instructions are the ones that would be scalarized if
6782   // we find that the scalar version costs less.
6783   SmallVector<Instruction *, 8> Worklist;
6784 
6785   // Returns true if the given instruction can be scalarized.
6786   auto canBeScalarized = [&](Instruction *I) -> bool {
6787     // We only attempt to scalarize instructions forming a single-use chain
6788     // from the original predicated block that would otherwise be vectorized.
6789     // Although not strictly necessary, we give up on instructions we know will
6790     // already be scalar to avoid traversing chains that are unlikely to be
6791     // beneficial.
6792     if (!I->hasOneUse() || PredInst->getParent() != I->getParent() ||
6793         isScalarAfterVectorization(I, VF))
6794       return false;
6795 
6796     // If the instruction is scalar with predication, it will be analyzed
6797     // separately. We ignore it within the context of PredInst.
6798     if (isScalarWithPredication(I))
6799       return false;
6800 
6801     // If any of the instruction's operands are uniform after vectorization,
6802     // the instruction cannot be scalarized. This prevents, for example, a
6803     // masked load from being scalarized.
6804     //
6805     // We assume we will only emit a value for lane zero of an instruction
6806     // marked uniform after vectorization, rather than VF identical values.
6807     // Thus, if we scalarize an instruction that uses a uniform, we would
6808     // create uses of values corresponding to the lanes we aren't emitting code
6809     // for. This behavior can be changed by allowing getScalarValue to clone
6810     // the lane zero values for uniforms rather than asserting.
6811     for (Use &U : I->operands())
6812       if (auto *J = dyn_cast<Instruction>(U.get()))
6813         if (isUniformAfterVectorization(J, VF))
6814           return false;
6815 
6816     // Otherwise, we can scalarize the instruction.
6817     return true;
6818   };
6819 
6820   // Compute the expected cost discount from scalarizing the entire expression
6821   // feeding the predicated instruction. We currently only consider expressions
6822   // that are single-use instruction chains.
6823   Worklist.push_back(PredInst);
6824   while (!Worklist.empty()) {
6825     Instruction *I = Worklist.pop_back_val();
6826 
6827     // If we've already analyzed the instruction, there's nothing to do.
6828     if (ScalarCosts.find(I) != ScalarCosts.end())
6829       continue;
6830 
6831     // Compute the cost of the vector instruction. Note that this cost already
6832     // includes the scalarization overhead of the predicated instruction.
6833     InstructionCost VectorCost = getInstructionCost(I, VF).first;
6834 
6835     // Compute the cost of the scalarized instruction. This cost is the cost of
6836     // the instruction as if it wasn't if-converted and instead remained in the
6837     // predicated block. We will scale this cost by block probability after
6838     // computing the scalarization overhead.
6839     assert(!VF.isScalable() && "scalable vectors not yet supported.");
6840     InstructionCost ScalarCost =
6841         VF.getKnownMinValue() *
6842         getInstructionCost(I, ElementCount::getFixed(1)).first;
6843 
6844     // Compute the scalarization overhead of needed insertelement instructions
6845     // and phi nodes.
6846     if (isScalarWithPredication(I) && !I->getType()->isVoidTy()) {
6847       ScalarCost += TTI.getScalarizationOverhead(
6848           cast<VectorType>(ToVectorTy(I->getType(), VF)),
6849           APInt::getAllOnesValue(VF.getKnownMinValue()), true, false);
6850       assert(!VF.isScalable() && "scalable vectors not yet supported.");
6851       ScalarCost +=
6852           VF.getKnownMinValue() *
6853           TTI.getCFInstrCost(Instruction::PHI, TTI::TCK_RecipThroughput);
6854     }
6855 
6856     // Compute the scalarization overhead of needed extractelement
6857     // instructions. For each of the instruction's operands, if the operand can
6858     // be scalarized, add it to the worklist; otherwise, account for the
6859     // overhead.
6860     for (Use &U : I->operands())
6861       if (auto *J = dyn_cast<Instruction>(U.get())) {
6862         assert(VectorType::isValidElementType(J->getType()) &&
6863                "Instruction has non-scalar type");
6864         if (canBeScalarized(J))
6865           Worklist.push_back(J);
6866         else if (needsExtract(J, VF)) {
6867           assert(!VF.isScalable() && "scalable vectors not yet supported.");
6868           ScalarCost += TTI.getScalarizationOverhead(
6869               cast<VectorType>(ToVectorTy(J->getType(), VF)),
6870               APInt::getAllOnesValue(VF.getKnownMinValue()), false, true);
6871         }
6872       }
6873 
6874     // Scale the total scalar cost by block probability.
6875     ScalarCost /= getReciprocalPredBlockProb();
6876 
6877     // Compute the discount. A non-negative discount means the vector version
6878     // of the instruction costs more, and scalarizing would be beneficial.
6879     Discount += VectorCost - ScalarCost;
6880     ScalarCosts[I] = ScalarCost;
6881   }
6882 
6883   return *Discount.getValue();
6884 }
6885 
6886 LoopVectorizationCostModel::VectorizationCostTy
6887 LoopVectorizationCostModel::expectedCost(ElementCount VF) {
6888   VectorizationCostTy Cost;
6889 
6890   // For each block.
6891   for (BasicBlock *BB : TheLoop->blocks()) {
6892     VectorizationCostTy BlockCost;
6893 
6894     // For each instruction in the old loop.
6895     for (Instruction &I : BB->instructionsWithoutDebug()) {
6896       // Skip ignored values.
6897       if (ValuesToIgnore.count(&I) ||
6898           (VF.isVector() && VecValuesToIgnore.count(&I)))
6899         continue;
6900 
6901       VectorizationCostTy C = getInstructionCost(&I, VF);
6902 
6903       // Check if we should override the cost.
6904       if (ForceTargetInstructionCost.getNumOccurrences() > 0)
6905         C.first = InstructionCost(ForceTargetInstructionCost);
6906 
6907       BlockCost.first += C.first;
6908       BlockCost.second |= C.second;
6909       LLVM_DEBUG(dbgs() << "LV: Found an estimated cost of " << C.first
6910                         << " for VF " << VF << " For instruction: " << I
6911                         << '\n');
6912     }
6913 
6914     // If we are vectorizing a predicated block, it will have been
6915     // if-converted. This means that the block's instructions (aside from
6916     // stores and instructions that may divide by zero) will now be
6917     // unconditionally executed. For the scalar case, we may not always execute
6918     // the predicated block, if it is an if-else block. Thus, scale the block's
6919     // cost by the probability of executing it. blockNeedsPredication from
6920     // Legal is used so as to not include all blocks in tail folded loops.
6921     if (VF.isScalar() && Legal->blockNeedsPredication(BB))
6922       BlockCost.first /= getReciprocalPredBlockProb();
6923 
6924     Cost.first += BlockCost.first;
6925     Cost.second |= BlockCost.second;
6926   }
6927 
6928   return Cost;
6929 }
6930 
6931 /// Gets Address Access SCEV after verifying that the access pattern
6932 /// is loop invariant except the induction variable dependence.
6933 ///
6934 /// This SCEV can be sent to the Target in order to estimate the address
6935 /// calculation cost.
6936 static const SCEV *getAddressAccessSCEV(
6937               Value *Ptr,
6938               LoopVectorizationLegality *Legal,
6939               PredicatedScalarEvolution &PSE,
6940               const Loop *TheLoop) {
6941 
6942   auto *Gep = dyn_cast<GetElementPtrInst>(Ptr);
6943   if (!Gep)
6944     return nullptr;
6945 
6946   // We are looking for a gep with all loop invariant indices except for one
6947   // which should be an induction variable.
6948   auto SE = PSE.getSE();
6949   unsigned NumOperands = Gep->getNumOperands();
6950   for (unsigned i = 1; i < NumOperands; ++i) {
6951     Value *Opd = Gep->getOperand(i);
6952     if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
6953         !Legal->isInductionVariable(Opd))
6954       return nullptr;
6955   }
6956 
6957   // Now we know we have a GEP ptr, %inv, %ind, %inv. return the Ptr SCEV.
6958   return PSE.getSCEV(Ptr);
6959 }
6960 
6961 static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
6962   return Legal->hasStride(I->getOperand(0)) ||
6963          Legal->hasStride(I->getOperand(1));
6964 }
6965 
6966 InstructionCost
6967 LoopVectorizationCostModel::getMemInstScalarizationCost(Instruction *I,
6968                                                         ElementCount VF) {
6969   assert(VF.isVector() &&
6970          "Scalarization cost of instruction implies vectorization.");
6971   if (VF.isScalable())
6972     return InstructionCost::getInvalid();
6973 
6974   Type *ValTy = getLoadStoreType(I);
6975   auto SE = PSE.getSE();
6976 
6977   unsigned AS = getLoadStoreAddressSpace(I);
6978   Value *Ptr = getLoadStorePointerOperand(I);
6979   Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
6980 
6981   // Figure out whether the access is strided and get the stride value
6982   // if it's known in compile time
6983   const SCEV *PtrSCEV = getAddressAccessSCEV(Ptr, Legal, PSE, TheLoop);
6984 
6985   // Get the cost of the scalar memory instruction and address computation.
6986   InstructionCost Cost =
6987       VF.getKnownMinValue() * TTI.getAddressComputationCost(PtrTy, SE, PtrSCEV);
6988 
6989   // Don't pass *I here, since it is scalar but will actually be part of a
6990   // vectorized loop where the user of it is a vectorized instruction.
6991   const Align Alignment = getLoadStoreAlignment(I);
6992   Cost += VF.getKnownMinValue() *
6993           TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(), Alignment,
6994                               AS, TTI::TCK_RecipThroughput);
6995 
6996   // Get the overhead of the extractelement and insertelement instructions
6997   // we might create due to scalarization.
6998   Cost += getScalarizationOverhead(I, VF);
6999 
7000   // If we have a predicated load/store, it will need extra i1 extracts and
7001   // conditional branches, but may not be executed for each vector lane. Scale
7002   // the cost by the probability of executing the predicated block.
7003   if (isPredicatedInst(I)) {
7004     Cost /= getReciprocalPredBlockProb();
7005 
7006     // Add the cost of an i1 extract and a branch
7007     auto *Vec_i1Ty =
7008         VectorType::get(IntegerType::getInt1Ty(ValTy->getContext()), VF);
7009     Cost += TTI.getScalarizationOverhead(
7010         Vec_i1Ty, APInt::getAllOnesValue(VF.getKnownMinValue()),
7011         /*Insert=*/false, /*Extract=*/true);
7012     Cost += TTI.getCFInstrCost(Instruction::Br, TTI::TCK_RecipThroughput);
7013 
7014     if (useEmulatedMaskMemRefHack(I))
7015       // Artificially setting to a high enough value to practically disable
7016       // vectorization with such operations.
7017       Cost = 3000000;
7018   }
7019 
7020   return Cost;
7021 }
7022 
7023 InstructionCost
7024 LoopVectorizationCostModel::getConsecutiveMemOpCost(Instruction *I,
7025                                                     ElementCount VF) {
7026   Type *ValTy = getLoadStoreType(I);
7027   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
7028   Value *Ptr = getLoadStorePointerOperand(I);
7029   unsigned AS = getLoadStoreAddressSpace(I);
7030   int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
7031   enum TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
7032 
7033   assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
7034          "Stride should be 1 or -1 for consecutive memory access");
7035   const Align Alignment = getLoadStoreAlignment(I);
7036   InstructionCost Cost = 0;
7037   if (Legal->isMaskRequired(I))
7038     Cost += TTI.getMaskedMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS,
7039                                       CostKind);
7040   else
7041     Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS,
7042                                 CostKind, I);
7043 
7044   bool Reverse = ConsecutiveStride < 0;
7045   if (Reverse)
7046     Cost +=
7047         TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, None, 0);
7048   return Cost;
7049 }
7050 
7051 InstructionCost
7052 LoopVectorizationCostModel::getUniformMemOpCost(Instruction *I,
7053                                                 ElementCount VF) {
7054   assert(Legal->isUniformMemOp(*I));
7055 
7056   Type *ValTy = getLoadStoreType(I);
7057   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
7058   const Align Alignment = getLoadStoreAlignment(I);
7059   unsigned AS = getLoadStoreAddressSpace(I);
7060   enum TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
7061   if (isa<LoadInst>(I)) {
7062     return TTI.getAddressComputationCost(ValTy) +
7063            TTI.getMemoryOpCost(Instruction::Load, ValTy, Alignment, AS,
7064                                CostKind) +
7065            TTI.getShuffleCost(TargetTransformInfo::SK_Broadcast, VectorTy);
7066   }
7067   StoreInst *SI = cast<StoreInst>(I);
7068 
7069   bool isLoopInvariantStoreValue = Legal->isUniform(SI->getValueOperand());
7070   return TTI.getAddressComputationCost(ValTy) +
7071          TTI.getMemoryOpCost(Instruction::Store, ValTy, Alignment, AS,
7072                              CostKind) +
7073          (isLoopInvariantStoreValue
7074               ? 0
7075               : TTI.getVectorInstrCost(Instruction::ExtractElement, VectorTy,
7076                                        VF.getKnownMinValue() - 1));
7077 }
7078 
7079 InstructionCost
7080 LoopVectorizationCostModel::getGatherScatterCost(Instruction *I,
7081                                                  ElementCount VF) {
7082   Type *ValTy = getLoadStoreType(I);
7083   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
7084   const Align Alignment = getLoadStoreAlignment(I);
7085   const Value *Ptr = getLoadStorePointerOperand(I);
7086 
7087   return TTI.getAddressComputationCost(VectorTy) +
7088          TTI.getGatherScatterOpCost(
7089              I->getOpcode(), VectorTy, Ptr, Legal->isMaskRequired(I), Alignment,
7090              TargetTransformInfo::TCK_RecipThroughput, I);
7091 }
7092 
7093 InstructionCost
7094 LoopVectorizationCostModel::getInterleaveGroupCost(Instruction *I,
7095                                                    ElementCount VF) {
7096   // TODO: Once we have support for interleaving with scalable vectors
7097   // we can calculate the cost properly here.
7098   if (VF.isScalable())
7099     return InstructionCost::getInvalid();
7100 
7101   Type *ValTy = getLoadStoreType(I);
7102   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
7103   unsigned AS = getLoadStoreAddressSpace(I);
7104 
7105   auto Group = getInterleavedAccessGroup(I);
7106   assert(Group && "Fail to get an interleaved access group.");
7107 
7108   unsigned InterleaveFactor = Group->getFactor();
7109   auto *WideVecTy = VectorType::get(ValTy, VF * InterleaveFactor);
7110 
7111   // Holds the indices of existing members in an interleaved load group.
7112   // An interleaved store group doesn't need this as it doesn't allow gaps.
7113   SmallVector<unsigned, 4> Indices;
7114   if (isa<LoadInst>(I)) {
7115     for (unsigned i = 0; i < InterleaveFactor; i++)
7116       if (Group->getMember(i))
7117         Indices.push_back(i);
7118   }
7119 
7120   // Calculate the cost of the whole interleaved group.
7121   bool UseMaskForGaps =
7122       Group->requiresScalarEpilogue() && !isScalarEpilogueAllowed();
7123   InstructionCost Cost = TTI.getInterleavedMemoryOpCost(
7124       I->getOpcode(), WideVecTy, Group->getFactor(), Indices, Group->getAlign(),
7125       AS, TTI::TCK_RecipThroughput, Legal->isMaskRequired(I), UseMaskForGaps);
7126 
7127   if (Group->isReverse()) {
7128     // TODO: Add support for reversed masked interleaved access.
7129     assert(!Legal->isMaskRequired(I) &&
7130            "Reverse masked interleaved access not supported.");
7131     Cost +=
7132         Group->getNumMembers() *
7133         TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, None, 0);
7134   }
7135   return Cost;
7136 }
7137 
7138 InstructionCost LoopVectorizationCostModel::getReductionPatternCost(
7139     Instruction *I, ElementCount VF, Type *Ty, TTI::TargetCostKind CostKind) {
7140   // Early exit for no inloop reductions
7141   if (InLoopReductionChains.empty() || VF.isScalar() || !isa<VectorType>(Ty))
7142     return InstructionCost::getInvalid();
7143   auto *VectorTy = cast<VectorType>(Ty);
7144 
7145   // We are looking for a pattern of, and finding the minimal acceptable cost:
7146   //  reduce(mul(ext(A), ext(B))) or
7147   //  reduce(mul(A, B)) or
7148   //  reduce(ext(A)) or
7149   //  reduce(A).
7150   // The basic idea is that we walk down the tree to do that, finding the root
7151   // reduction instruction in InLoopReductionImmediateChains. From there we find
7152   // the pattern of mul/ext and test the cost of the entire pattern vs the cost
7153   // of the components. If the reduction cost is lower then we return it for the
7154   // reduction instruction and 0 for the other instructions in the pattern. If
7155   // it is not we return an invalid cost specifying the orignal cost method
7156   // should be used.
7157   Instruction *RetI = I;
7158   if ((RetI->getOpcode() == Instruction::SExt ||
7159        RetI->getOpcode() == Instruction::ZExt)) {
7160     if (!RetI->hasOneUser())
7161       return InstructionCost::getInvalid();
7162     RetI = RetI->user_back();
7163   }
7164   if (RetI->getOpcode() == Instruction::Mul &&
7165       RetI->user_back()->getOpcode() == Instruction::Add) {
7166     if (!RetI->hasOneUser())
7167       return InstructionCost::getInvalid();
7168     RetI = RetI->user_back();
7169   }
7170 
7171   // Test if the found instruction is a reduction, and if not return an invalid
7172   // cost specifying the parent to use the original cost modelling.
7173   if (!InLoopReductionImmediateChains.count(RetI))
7174     return InstructionCost::getInvalid();
7175 
7176   // Find the reduction this chain is a part of and calculate the basic cost of
7177   // the reduction on its own.
7178   Instruction *LastChain = InLoopReductionImmediateChains[RetI];
7179   Instruction *ReductionPhi = LastChain;
7180   while (!isa<PHINode>(ReductionPhi))
7181     ReductionPhi = InLoopReductionImmediateChains[ReductionPhi];
7182 
7183   const RecurrenceDescriptor &RdxDesc =
7184       Legal->getReductionVars()[cast<PHINode>(ReductionPhi)];
7185   InstructionCost BaseCost =
7186       TTI.getArithmeticReductionCost(RdxDesc.getOpcode(), VectorTy, CostKind);
7187 
7188   // Get the operand that was not the reduction chain and match it to one of the
7189   // patterns, returning the better cost if it is found.
7190   Instruction *RedOp = RetI->getOperand(1) == LastChain
7191                            ? dyn_cast<Instruction>(RetI->getOperand(0))
7192                            : dyn_cast<Instruction>(RetI->getOperand(1));
7193 
7194   VectorTy = VectorType::get(I->getOperand(0)->getType(), VectorTy);
7195 
7196   if (RedOp && (isa<SExtInst>(RedOp) || isa<ZExtInst>(RedOp)) &&
7197       !TheLoop->isLoopInvariant(RedOp)) {
7198     bool IsUnsigned = isa<ZExtInst>(RedOp);
7199     auto *ExtType = VectorType::get(RedOp->getOperand(0)->getType(), VectorTy);
7200     InstructionCost RedCost = TTI.getExtendedAddReductionCost(
7201         /*IsMLA=*/false, IsUnsigned, RdxDesc.getRecurrenceType(), ExtType,
7202         CostKind);
7203 
7204     InstructionCost ExtCost =
7205         TTI.getCastInstrCost(RedOp->getOpcode(), VectorTy, ExtType,
7206                              TTI::CastContextHint::None, CostKind, RedOp);
7207     if (RedCost.isValid() && RedCost < BaseCost + ExtCost)
7208       return I == RetI ? *RedCost.getValue() : 0;
7209   } else if (RedOp && RedOp->getOpcode() == Instruction::Mul) {
7210     Instruction *Mul = RedOp;
7211     Instruction *Op0 = dyn_cast<Instruction>(Mul->getOperand(0));
7212     Instruction *Op1 = dyn_cast<Instruction>(Mul->getOperand(1));
7213     if (Op0 && Op1 && (isa<SExtInst>(Op0) || isa<ZExtInst>(Op0)) &&
7214         Op0->getOpcode() == Op1->getOpcode() &&
7215         Op0->getOperand(0)->getType() == Op1->getOperand(0)->getType() &&
7216         !TheLoop->isLoopInvariant(Op0) && !TheLoop->isLoopInvariant(Op1)) {
7217       bool IsUnsigned = isa<ZExtInst>(Op0);
7218       auto *ExtType = VectorType::get(Op0->getOperand(0)->getType(), VectorTy);
7219       // reduce(mul(ext, ext))
7220       InstructionCost ExtCost =
7221           TTI.getCastInstrCost(Op0->getOpcode(), VectorTy, ExtType,
7222                                TTI::CastContextHint::None, CostKind, Op0);
7223       InstructionCost MulCost =
7224           TTI.getArithmeticInstrCost(Mul->getOpcode(), VectorTy, CostKind);
7225 
7226       InstructionCost RedCost = TTI.getExtendedAddReductionCost(
7227           /*IsMLA=*/true, IsUnsigned, RdxDesc.getRecurrenceType(), ExtType,
7228           CostKind);
7229 
7230       if (RedCost.isValid() && RedCost < ExtCost * 2 + MulCost + BaseCost)
7231         return I == RetI ? *RedCost.getValue() : 0;
7232     } else {
7233       InstructionCost MulCost =
7234           TTI.getArithmeticInstrCost(Mul->getOpcode(), VectorTy, CostKind);
7235 
7236       InstructionCost RedCost = TTI.getExtendedAddReductionCost(
7237           /*IsMLA=*/true, true, RdxDesc.getRecurrenceType(), VectorTy,
7238           CostKind);
7239 
7240       if (RedCost.isValid() && RedCost < MulCost + BaseCost)
7241         return I == RetI ? *RedCost.getValue() : 0;
7242     }
7243   }
7244 
7245   return I == RetI ? BaseCost : InstructionCost::getInvalid();
7246 }
7247 
7248 InstructionCost
7249 LoopVectorizationCostModel::getMemoryInstructionCost(Instruction *I,
7250                                                      ElementCount VF) {
7251   // Calculate scalar cost only. Vectorization cost should be ready at this
7252   // moment.
7253   if (VF.isScalar()) {
7254     Type *ValTy = getLoadStoreType(I);
7255     const Align Alignment = getLoadStoreAlignment(I);
7256     unsigned AS = getLoadStoreAddressSpace(I);
7257 
7258     return TTI.getAddressComputationCost(ValTy) +
7259            TTI.getMemoryOpCost(I->getOpcode(), ValTy, Alignment, AS,
7260                                TTI::TCK_RecipThroughput, I);
7261   }
7262   return getWideningCost(I, VF);
7263 }
7264 
7265 LoopVectorizationCostModel::VectorizationCostTy
7266 LoopVectorizationCostModel::getInstructionCost(Instruction *I,
7267                                                ElementCount VF) {
7268   // If we know that this instruction will remain uniform, check the cost of
7269   // the scalar version.
7270   if (isUniformAfterVectorization(I, VF))
7271     VF = ElementCount::getFixed(1);
7272 
7273   if (VF.isVector() && isProfitableToScalarize(I, VF))
7274     return VectorizationCostTy(InstsToScalarize[VF][I], false);
7275 
7276   // Forced scalars do not have any scalarization overhead.
7277   auto ForcedScalar = ForcedScalars.find(VF);
7278   if (VF.isVector() && ForcedScalar != ForcedScalars.end()) {
7279     auto InstSet = ForcedScalar->second;
7280     if (InstSet.count(I))
7281       return VectorizationCostTy(
7282           (getInstructionCost(I, ElementCount::getFixed(1)).first *
7283            VF.getKnownMinValue()),
7284           false);
7285   }
7286 
7287   Type *VectorTy;
7288   InstructionCost C = getInstructionCost(I, VF, VectorTy);
7289 
7290   bool TypeNotScalarized =
7291       VF.isVector() && VectorTy->isVectorTy() &&
7292       TTI.getNumberOfParts(VectorTy) < VF.getKnownMinValue();
7293   return VectorizationCostTy(C, TypeNotScalarized);
7294 }
7295 
7296 InstructionCost
7297 LoopVectorizationCostModel::getScalarizationOverhead(Instruction *I,
7298                                                      ElementCount VF) const {
7299 
7300   // There is no mechanism yet to create a scalable scalarization loop,
7301   // so this is currently Invalid.
7302   if (VF.isScalable())
7303     return InstructionCost::getInvalid();
7304 
7305   if (VF.isScalar())
7306     return 0;
7307 
7308   InstructionCost Cost = 0;
7309   Type *RetTy = ToVectorTy(I->getType(), VF);
7310   if (!RetTy->isVoidTy() &&
7311       (!isa<LoadInst>(I) || !TTI.supportsEfficientVectorElementLoadStore()))
7312     Cost += TTI.getScalarizationOverhead(
7313         cast<VectorType>(RetTy), APInt::getAllOnesValue(VF.getKnownMinValue()),
7314         true, false);
7315 
7316   // Some targets keep addresses scalar.
7317   if (isa<LoadInst>(I) && !TTI.prefersVectorizedAddressing())
7318     return Cost;
7319 
7320   // Some targets support efficient element stores.
7321   if (isa<StoreInst>(I) && TTI.supportsEfficientVectorElementLoadStore())
7322     return Cost;
7323 
7324   // Collect operands to consider.
7325   CallInst *CI = dyn_cast<CallInst>(I);
7326   Instruction::op_range Ops = CI ? CI->arg_operands() : I->operands();
7327 
7328   // Skip operands that do not require extraction/scalarization and do not incur
7329   // any overhead.
7330   SmallVector<Type *> Tys;
7331   for (auto *V : filterExtractingOperands(Ops, VF))
7332     Tys.push_back(MaybeVectorizeType(V->getType(), VF));
7333   return Cost + TTI.getOperandsScalarizationOverhead(
7334                     filterExtractingOperands(Ops, VF), Tys);
7335 }
7336 
7337 void LoopVectorizationCostModel::setCostBasedWideningDecision(ElementCount VF) {
7338   if (VF.isScalar())
7339     return;
7340   NumPredStores = 0;
7341   for (BasicBlock *BB : TheLoop->blocks()) {
7342     // For each instruction in the old loop.
7343     for (Instruction &I : *BB) {
7344       Value *Ptr =  getLoadStorePointerOperand(&I);
7345       if (!Ptr)
7346         continue;
7347 
7348       // TODO: We should generate better code and update the cost model for
7349       // predicated uniform stores. Today they are treated as any other
7350       // predicated store (see added test cases in
7351       // invariant-store-vectorization.ll).
7352       if (isa<StoreInst>(&I) && isScalarWithPredication(&I))
7353         NumPredStores++;
7354 
7355       if (Legal->isUniformMemOp(I)) {
7356         // TODO: Avoid replicating loads and stores instead of
7357         // relying on instcombine to remove them.
7358         // Load: Scalar load + broadcast
7359         // Store: Scalar store + isLoopInvariantStoreValue ? 0 : extract
7360         InstructionCost Cost;
7361         if (isa<StoreInst>(&I) && VF.isScalable() &&
7362             isLegalGatherOrScatter(&I)) {
7363           Cost = getGatherScatterCost(&I, VF);
7364           setWideningDecision(&I, VF, CM_GatherScatter, Cost);
7365         } else {
7366           assert((isa<LoadInst>(&I) || !VF.isScalable()) &&
7367                  "Cannot yet scalarize uniform stores");
7368           Cost = getUniformMemOpCost(&I, VF);
7369           setWideningDecision(&I, VF, CM_Scalarize, Cost);
7370         }
7371         continue;
7372       }
7373 
7374       // We assume that widening is the best solution when possible.
7375       if (memoryInstructionCanBeWidened(&I, VF)) {
7376         InstructionCost Cost = getConsecutiveMemOpCost(&I, VF);
7377         int ConsecutiveStride =
7378                Legal->isConsecutivePtr(getLoadStorePointerOperand(&I));
7379         assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
7380                "Expected consecutive stride.");
7381         InstWidening Decision =
7382             ConsecutiveStride == 1 ? CM_Widen : CM_Widen_Reverse;
7383         setWideningDecision(&I, VF, Decision, Cost);
7384         continue;
7385       }
7386 
7387       // Choose between Interleaving, Gather/Scatter or Scalarization.
7388       InstructionCost InterleaveCost = InstructionCost::getInvalid();
7389       unsigned NumAccesses = 1;
7390       if (isAccessInterleaved(&I)) {
7391         auto Group = getInterleavedAccessGroup(&I);
7392         assert(Group && "Fail to get an interleaved access group.");
7393 
7394         // Make one decision for the whole group.
7395         if (getWideningDecision(&I, VF) != CM_Unknown)
7396           continue;
7397 
7398         NumAccesses = Group->getNumMembers();
7399         if (interleavedAccessCanBeWidened(&I, VF))
7400           InterleaveCost = getInterleaveGroupCost(&I, VF);
7401       }
7402 
7403       InstructionCost GatherScatterCost =
7404           isLegalGatherOrScatter(&I)
7405               ? getGatherScatterCost(&I, VF) * NumAccesses
7406               : InstructionCost::getInvalid();
7407 
7408       InstructionCost ScalarizationCost =
7409           getMemInstScalarizationCost(&I, VF) * NumAccesses;
7410 
7411       // Choose better solution for the current VF,
7412       // write down this decision and use it during vectorization.
7413       InstructionCost Cost;
7414       InstWidening Decision;
7415       if (InterleaveCost <= GatherScatterCost &&
7416           InterleaveCost < ScalarizationCost) {
7417         Decision = CM_Interleave;
7418         Cost = InterleaveCost;
7419       } else if (GatherScatterCost < ScalarizationCost) {
7420         Decision = CM_GatherScatter;
7421         Cost = GatherScatterCost;
7422       } else {
7423         assert(!VF.isScalable() &&
7424                "We cannot yet scalarise for scalable vectors");
7425         Decision = CM_Scalarize;
7426         Cost = ScalarizationCost;
7427       }
7428       // If the instructions belongs to an interleave group, the whole group
7429       // receives the same decision. The whole group receives the cost, but
7430       // the cost will actually be assigned to one instruction.
7431       if (auto Group = getInterleavedAccessGroup(&I))
7432         setWideningDecision(Group, VF, Decision, Cost);
7433       else
7434         setWideningDecision(&I, VF, Decision, Cost);
7435     }
7436   }
7437 
7438   // Make sure that any load of address and any other address computation
7439   // remains scalar unless there is gather/scatter support. This avoids
7440   // inevitable extracts into address registers, and also has the benefit of
7441   // activating LSR more, since that pass can't optimize vectorized
7442   // addresses.
7443   if (TTI.prefersVectorizedAddressing())
7444     return;
7445 
7446   // Start with all scalar pointer uses.
7447   SmallPtrSet<Instruction *, 8> AddrDefs;
7448   for (BasicBlock *BB : TheLoop->blocks())
7449     for (Instruction &I : *BB) {
7450       Instruction *PtrDef =
7451         dyn_cast_or_null<Instruction>(getLoadStorePointerOperand(&I));
7452       if (PtrDef && TheLoop->contains(PtrDef) &&
7453           getWideningDecision(&I, VF) != CM_GatherScatter)
7454         AddrDefs.insert(PtrDef);
7455     }
7456 
7457   // Add all instructions used to generate the addresses.
7458   SmallVector<Instruction *, 4> Worklist;
7459   append_range(Worklist, AddrDefs);
7460   while (!Worklist.empty()) {
7461     Instruction *I = Worklist.pop_back_val();
7462     for (auto &Op : I->operands())
7463       if (auto *InstOp = dyn_cast<Instruction>(Op))
7464         if ((InstOp->getParent() == I->getParent()) && !isa<PHINode>(InstOp) &&
7465             AddrDefs.insert(InstOp).second)
7466           Worklist.push_back(InstOp);
7467   }
7468 
7469   for (auto *I : AddrDefs) {
7470     if (isa<LoadInst>(I)) {
7471       // Setting the desired widening decision should ideally be handled in
7472       // by cost functions, but since this involves the task of finding out
7473       // if the loaded register is involved in an address computation, it is
7474       // instead changed here when we know this is the case.
7475       InstWidening Decision = getWideningDecision(I, VF);
7476       if (Decision == CM_Widen || Decision == CM_Widen_Reverse)
7477         // Scalarize a widened load of address.
7478         setWideningDecision(
7479             I, VF, CM_Scalarize,
7480             (VF.getKnownMinValue() *
7481              getMemoryInstructionCost(I, ElementCount::getFixed(1))));
7482       else if (auto Group = getInterleavedAccessGroup(I)) {
7483         // Scalarize an interleave group of address loads.
7484         for (unsigned I = 0; I < Group->getFactor(); ++I) {
7485           if (Instruction *Member = Group->getMember(I))
7486             setWideningDecision(
7487                 Member, VF, CM_Scalarize,
7488                 (VF.getKnownMinValue() *
7489                  getMemoryInstructionCost(Member, ElementCount::getFixed(1))));
7490         }
7491       }
7492     } else
7493       // Make sure I gets scalarized and a cost estimate without
7494       // scalarization overhead.
7495       ForcedScalars[VF].insert(I);
7496   }
7497 }
7498 
7499 InstructionCost
7500 LoopVectorizationCostModel::getInstructionCost(Instruction *I, ElementCount VF,
7501                                                Type *&VectorTy) {
7502   Type *RetTy = I->getType();
7503   if (canTruncateToMinimalBitwidth(I, VF))
7504     RetTy = IntegerType::get(RetTy->getContext(), MinBWs[I]);
7505   auto SE = PSE.getSE();
7506   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
7507 
7508   auto hasSingleCopyAfterVectorization = [this](Instruction *I,
7509                                                 ElementCount VF) -> bool {
7510     if (VF.isScalar())
7511       return true;
7512 
7513     auto Scalarized = InstsToScalarize.find(VF);
7514     assert(Scalarized != InstsToScalarize.end() &&
7515            "VF not yet analyzed for scalarization profitability");
7516     return !Scalarized->second.count(I) &&
7517            llvm::all_of(I->users(), [&](User *U) {
7518              auto *UI = cast<Instruction>(U);
7519              return !Scalarized->second.count(UI);
7520            });
7521   };
7522   (void) hasSingleCopyAfterVectorization;
7523 
7524   if (isScalarAfterVectorization(I, VF)) {
7525     // With the exception of GEPs and PHIs, after scalarization there should
7526     // only be one copy of the instruction generated in the loop. This is
7527     // because the VF is either 1, or any instructions that need scalarizing
7528     // have already been dealt with by the the time we get here. As a result,
7529     // it means we don't have to multiply the instruction cost by VF.
7530     assert(I->getOpcode() == Instruction::GetElementPtr ||
7531            I->getOpcode() == Instruction::PHI ||
7532            (I->getOpcode() == Instruction::BitCast &&
7533             I->getType()->isPointerTy()) ||
7534            hasSingleCopyAfterVectorization(I, VF));
7535     VectorTy = RetTy;
7536   } else
7537     VectorTy = ToVectorTy(RetTy, VF);
7538 
7539   // TODO: We need to estimate the cost of intrinsic calls.
7540   switch (I->getOpcode()) {
7541   case Instruction::GetElementPtr:
7542     // We mark this instruction as zero-cost because the cost of GEPs in
7543     // vectorized code depends on whether the corresponding memory instruction
7544     // is scalarized or not. Therefore, we handle GEPs with the memory
7545     // instruction cost.
7546     return 0;
7547   case Instruction::Br: {
7548     // In cases of scalarized and predicated instructions, there will be VF
7549     // predicated blocks in the vectorized loop. Each branch around these
7550     // blocks requires also an extract of its vector compare i1 element.
7551     bool ScalarPredicatedBB = false;
7552     BranchInst *BI = cast<BranchInst>(I);
7553     if (VF.isVector() && BI->isConditional() &&
7554         (PredicatedBBsAfterVectorization.count(BI->getSuccessor(0)) ||
7555          PredicatedBBsAfterVectorization.count(BI->getSuccessor(1))))
7556       ScalarPredicatedBB = true;
7557 
7558     if (ScalarPredicatedBB) {
7559       // Return cost for branches around scalarized and predicated blocks.
7560       assert(!VF.isScalable() && "scalable vectors not yet supported.");
7561       auto *Vec_i1Ty =
7562           VectorType::get(IntegerType::getInt1Ty(RetTy->getContext()), VF);
7563       return (TTI.getScalarizationOverhead(
7564                   Vec_i1Ty, APInt::getAllOnesValue(VF.getKnownMinValue()),
7565                   false, true) +
7566               (TTI.getCFInstrCost(Instruction::Br, CostKind) *
7567                VF.getKnownMinValue()));
7568     } else if (I->getParent() == TheLoop->getLoopLatch() || VF.isScalar())
7569       // The back-edge branch will remain, as will all scalar branches.
7570       return TTI.getCFInstrCost(Instruction::Br, CostKind);
7571     else
7572       // This branch will be eliminated by if-conversion.
7573       return 0;
7574     // Note: We currently assume zero cost for an unconditional branch inside
7575     // a predicated block since it will become a fall-through, although we
7576     // may decide in the future to call TTI for all branches.
7577   }
7578   case Instruction::PHI: {
7579     auto *Phi = cast<PHINode>(I);
7580 
7581     // First-order recurrences are replaced by vector shuffles inside the loop.
7582     // NOTE: Don't use ToVectorTy as SK_ExtractSubvector expects a vector type.
7583     if (VF.isVector() && Legal->isFirstOrderRecurrence(Phi))
7584       return TTI.getShuffleCost(
7585           TargetTransformInfo::SK_ExtractSubvector, cast<VectorType>(VectorTy),
7586           None, VF.getKnownMinValue() - 1, FixedVectorType::get(RetTy, 1));
7587 
7588     // Phi nodes in non-header blocks (not inductions, reductions, etc.) are
7589     // converted into select instructions. We require N - 1 selects per phi
7590     // node, where N is the number of incoming values.
7591     if (VF.isVector() && Phi->getParent() != TheLoop->getHeader())
7592       return (Phi->getNumIncomingValues() - 1) *
7593              TTI.getCmpSelInstrCost(
7594                  Instruction::Select, ToVectorTy(Phi->getType(), VF),
7595                  ToVectorTy(Type::getInt1Ty(Phi->getContext()), VF),
7596                  CmpInst::BAD_ICMP_PREDICATE, CostKind);
7597 
7598     return TTI.getCFInstrCost(Instruction::PHI, CostKind);
7599   }
7600   case Instruction::UDiv:
7601   case Instruction::SDiv:
7602   case Instruction::URem:
7603   case Instruction::SRem:
7604     // If we have a predicated instruction, it may not be executed for each
7605     // vector lane. Get the scalarization cost and scale this amount by the
7606     // probability of executing the predicated block. If the instruction is not
7607     // predicated, we fall through to the next case.
7608     if (VF.isVector() && isScalarWithPredication(I)) {
7609       InstructionCost Cost = 0;
7610 
7611       // These instructions have a non-void type, so account for the phi nodes
7612       // that we will create. This cost is likely to be zero. The phi node
7613       // cost, if any, should be scaled by the block probability because it
7614       // models a copy at the end of each predicated block.
7615       Cost += VF.getKnownMinValue() *
7616               TTI.getCFInstrCost(Instruction::PHI, CostKind);
7617 
7618       // The cost of the non-predicated instruction.
7619       Cost += VF.getKnownMinValue() *
7620               TTI.getArithmeticInstrCost(I->getOpcode(), RetTy, CostKind);
7621 
7622       // The cost of insertelement and extractelement instructions needed for
7623       // scalarization.
7624       Cost += getScalarizationOverhead(I, VF);
7625 
7626       // Scale the cost by the probability of executing the predicated blocks.
7627       // This assumes the predicated block for each vector lane is equally
7628       // likely.
7629       return Cost / getReciprocalPredBlockProb();
7630     }
7631     LLVM_FALLTHROUGH;
7632   case Instruction::Add:
7633   case Instruction::FAdd:
7634   case Instruction::Sub:
7635   case Instruction::FSub:
7636   case Instruction::Mul:
7637   case Instruction::FMul:
7638   case Instruction::FDiv:
7639   case Instruction::FRem:
7640   case Instruction::Shl:
7641   case Instruction::LShr:
7642   case Instruction::AShr:
7643   case Instruction::And:
7644   case Instruction::Or:
7645   case Instruction::Xor: {
7646     // Since we will replace the stride by 1 the multiplication should go away.
7647     if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
7648       return 0;
7649 
7650     // Detect reduction patterns
7651     InstructionCost RedCost;
7652     if ((RedCost = getReductionPatternCost(I, VF, VectorTy, CostKind))
7653             .isValid())
7654       return RedCost;
7655 
7656     // Certain instructions can be cheaper to vectorize if they have a constant
7657     // second vector operand. One example of this are shifts on x86.
7658     Value *Op2 = I->getOperand(1);
7659     TargetTransformInfo::OperandValueProperties Op2VP;
7660     TargetTransformInfo::OperandValueKind Op2VK =
7661         TTI.getOperandInfo(Op2, Op2VP);
7662     if (Op2VK == TargetTransformInfo::OK_AnyValue && Legal->isUniform(Op2))
7663       Op2VK = TargetTransformInfo::OK_UniformValue;
7664 
7665     SmallVector<const Value *, 4> Operands(I->operand_values());
7666     return TTI.getArithmeticInstrCost(
7667         I->getOpcode(), VectorTy, CostKind, TargetTransformInfo::OK_AnyValue,
7668         Op2VK, TargetTransformInfo::OP_None, Op2VP, Operands, I);
7669   }
7670   case Instruction::FNeg: {
7671     return TTI.getArithmeticInstrCost(
7672         I->getOpcode(), VectorTy, CostKind, TargetTransformInfo::OK_AnyValue,
7673         TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None,
7674         TargetTransformInfo::OP_None, I->getOperand(0), I);
7675   }
7676   case Instruction::Select: {
7677     SelectInst *SI = cast<SelectInst>(I);
7678     const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
7679     bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
7680 
7681     const Value *Op0, *Op1;
7682     using namespace llvm::PatternMatch;
7683     if (!ScalarCond && (match(I, m_LogicalAnd(m_Value(Op0), m_Value(Op1))) ||
7684                         match(I, m_LogicalOr(m_Value(Op0), m_Value(Op1))))) {
7685       // select x, y, false --> x & y
7686       // select x, true, y --> x | y
7687       TTI::OperandValueProperties Op1VP = TTI::OP_None;
7688       TTI::OperandValueProperties Op2VP = TTI::OP_None;
7689       TTI::OperandValueKind Op1VK = TTI::getOperandInfo(Op0, Op1VP);
7690       TTI::OperandValueKind Op2VK = TTI::getOperandInfo(Op1, Op2VP);
7691       assert(Op0->getType()->getScalarSizeInBits() == 1 &&
7692               Op1->getType()->getScalarSizeInBits() == 1);
7693 
7694       SmallVector<const Value *, 2> Operands{Op0, Op1};
7695       return TTI.getArithmeticInstrCost(
7696           match(I, m_LogicalOr()) ? Instruction::Or : Instruction::And, VectorTy,
7697           CostKind, Op1VK, Op2VK, Op1VP, Op2VP, Operands, I);
7698     }
7699 
7700     Type *CondTy = SI->getCondition()->getType();
7701     if (!ScalarCond)
7702       CondTy = VectorType::get(CondTy, VF);
7703     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy,
7704                                   CmpInst::BAD_ICMP_PREDICATE, CostKind, I);
7705   }
7706   case Instruction::ICmp:
7707   case Instruction::FCmp: {
7708     Type *ValTy = I->getOperand(0)->getType();
7709     Instruction *Op0AsInstruction = dyn_cast<Instruction>(I->getOperand(0));
7710     if (canTruncateToMinimalBitwidth(Op0AsInstruction, VF))
7711       ValTy = IntegerType::get(ValTy->getContext(), MinBWs[Op0AsInstruction]);
7712     VectorTy = ToVectorTy(ValTy, VF);
7713     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, nullptr,
7714                                   CmpInst::BAD_ICMP_PREDICATE, CostKind, I);
7715   }
7716   case Instruction::Store:
7717   case Instruction::Load: {
7718     ElementCount Width = VF;
7719     if (Width.isVector()) {
7720       InstWidening Decision = getWideningDecision(I, Width);
7721       assert(Decision != CM_Unknown &&
7722              "CM decision should be taken at this point");
7723       if (Decision == CM_Scalarize)
7724         Width = ElementCount::getFixed(1);
7725     }
7726     VectorTy = ToVectorTy(getLoadStoreType(I), Width);
7727     return getMemoryInstructionCost(I, VF);
7728   }
7729   case Instruction::BitCast:
7730     if (I->getType()->isPointerTy())
7731       return 0;
7732     LLVM_FALLTHROUGH;
7733   case Instruction::ZExt:
7734   case Instruction::SExt:
7735   case Instruction::FPToUI:
7736   case Instruction::FPToSI:
7737   case Instruction::FPExt:
7738   case Instruction::PtrToInt:
7739   case Instruction::IntToPtr:
7740   case Instruction::SIToFP:
7741   case Instruction::UIToFP:
7742   case Instruction::Trunc:
7743   case Instruction::FPTrunc: {
7744     // Computes the CastContextHint from a Load/Store instruction.
7745     auto ComputeCCH = [&](Instruction *I) -> TTI::CastContextHint {
7746       assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
7747              "Expected a load or a store!");
7748 
7749       if (VF.isScalar() || !TheLoop->contains(I))
7750         return TTI::CastContextHint::Normal;
7751 
7752       switch (getWideningDecision(I, VF)) {
7753       case LoopVectorizationCostModel::CM_GatherScatter:
7754         return TTI::CastContextHint::GatherScatter;
7755       case LoopVectorizationCostModel::CM_Interleave:
7756         return TTI::CastContextHint::Interleave;
7757       case LoopVectorizationCostModel::CM_Scalarize:
7758       case LoopVectorizationCostModel::CM_Widen:
7759         return Legal->isMaskRequired(I) ? TTI::CastContextHint::Masked
7760                                         : TTI::CastContextHint::Normal;
7761       case LoopVectorizationCostModel::CM_Widen_Reverse:
7762         return TTI::CastContextHint::Reversed;
7763       case LoopVectorizationCostModel::CM_Unknown:
7764         llvm_unreachable("Instr did not go through cost modelling?");
7765       }
7766 
7767       llvm_unreachable("Unhandled case!");
7768     };
7769 
7770     unsigned Opcode = I->getOpcode();
7771     TTI::CastContextHint CCH = TTI::CastContextHint::None;
7772     // For Trunc, the context is the only user, which must be a StoreInst.
7773     if (Opcode == Instruction::Trunc || Opcode == Instruction::FPTrunc) {
7774       if (I->hasOneUse())
7775         if (StoreInst *Store = dyn_cast<StoreInst>(*I->user_begin()))
7776           CCH = ComputeCCH(Store);
7777     }
7778     // For Z/Sext, the context is the operand, which must be a LoadInst.
7779     else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt ||
7780              Opcode == Instruction::FPExt) {
7781       if (LoadInst *Load = dyn_cast<LoadInst>(I->getOperand(0)))
7782         CCH = ComputeCCH(Load);
7783     }
7784 
7785     // We optimize the truncation of induction variables having constant
7786     // integer steps. The cost of these truncations is the same as the scalar
7787     // operation.
7788     if (isOptimizableIVTruncate(I, VF)) {
7789       auto *Trunc = cast<TruncInst>(I);
7790       return TTI.getCastInstrCost(Instruction::Trunc, Trunc->getDestTy(),
7791                                   Trunc->getSrcTy(), CCH, CostKind, Trunc);
7792     }
7793 
7794     // Detect reduction patterns
7795     InstructionCost RedCost;
7796     if ((RedCost = getReductionPatternCost(I, VF, VectorTy, CostKind))
7797             .isValid())
7798       return RedCost;
7799 
7800     Type *SrcScalarTy = I->getOperand(0)->getType();
7801     Type *SrcVecTy =
7802         VectorTy->isVectorTy() ? ToVectorTy(SrcScalarTy, VF) : SrcScalarTy;
7803     if (canTruncateToMinimalBitwidth(I, VF)) {
7804       // This cast is going to be shrunk. This may remove the cast or it might
7805       // turn it into slightly different cast. For example, if MinBW == 16,
7806       // "zext i8 %1 to i32" becomes "zext i8 %1 to i16".
7807       //
7808       // Calculate the modified src and dest types.
7809       Type *MinVecTy = VectorTy;
7810       if (Opcode == Instruction::Trunc) {
7811         SrcVecTy = smallestIntegerVectorType(SrcVecTy, MinVecTy);
7812         VectorTy =
7813             largestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy);
7814       } else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
7815         SrcVecTy = largestIntegerVectorType(SrcVecTy, MinVecTy);
7816         VectorTy =
7817             smallestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy);
7818       }
7819     }
7820 
7821     return TTI.getCastInstrCost(Opcode, VectorTy, SrcVecTy, CCH, CostKind, I);
7822   }
7823   case Instruction::Call: {
7824     bool NeedToScalarize;
7825     CallInst *CI = cast<CallInst>(I);
7826     InstructionCost CallCost = getVectorCallCost(CI, VF, NeedToScalarize);
7827     if (getVectorIntrinsicIDForCall(CI, TLI)) {
7828       InstructionCost IntrinsicCost = getVectorIntrinsicCost(CI, VF);
7829       return std::min(CallCost, IntrinsicCost);
7830     }
7831     return CallCost;
7832   }
7833   case Instruction::ExtractValue:
7834     return TTI.getInstructionCost(I, TTI::TCK_RecipThroughput);
7835   default:
7836     // This opcode is unknown. Assume that it is the same as 'mul'.
7837     return TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy, CostKind);
7838   } // end of switch.
7839 }
7840 
7841 char LoopVectorize::ID = 0;
7842 
7843 static const char lv_name[] = "Loop Vectorization";
7844 
7845 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
7846 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
7847 INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
7848 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
7849 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
7850 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
7851 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
7852 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
7853 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
7854 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
7855 INITIALIZE_PASS_DEPENDENCY(LoopAccessLegacyAnalysis)
7856 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
7857 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
7858 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
7859 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
7860 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
7861 
7862 namespace llvm {
7863 
7864 Pass *createLoopVectorizePass() { return new LoopVectorize(); }
7865 
7866 Pass *createLoopVectorizePass(bool InterleaveOnlyWhenForced,
7867                               bool VectorizeOnlyWhenForced) {
7868   return new LoopVectorize(InterleaveOnlyWhenForced, VectorizeOnlyWhenForced);
7869 }
7870 
7871 } // end namespace llvm
7872 
7873 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
7874   // Check if the pointer operand of a load or store instruction is
7875   // consecutive.
7876   if (auto *Ptr = getLoadStorePointerOperand(Inst))
7877     return Legal->isConsecutivePtr(Ptr);
7878   return false;
7879 }
7880 
7881 void LoopVectorizationCostModel::collectValuesToIgnore() {
7882   // Ignore ephemeral values.
7883   CodeMetrics::collectEphemeralValues(TheLoop, AC, ValuesToIgnore);
7884 
7885   // Ignore type-promoting instructions we identified during reduction
7886   // detection.
7887   for (auto &Reduction : Legal->getReductionVars()) {
7888     RecurrenceDescriptor &RedDes = Reduction.second;
7889     const SmallPtrSetImpl<Instruction *> &Casts = RedDes.getCastInsts();
7890     VecValuesToIgnore.insert(Casts.begin(), Casts.end());
7891   }
7892   // Ignore type-casting instructions we identified during induction
7893   // detection.
7894   for (auto &Induction : Legal->getInductionVars()) {
7895     InductionDescriptor &IndDes = Induction.second;
7896     const SmallVectorImpl<Instruction *> &Casts = IndDes.getCastInsts();
7897     VecValuesToIgnore.insert(Casts.begin(), Casts.end());
7898   }
7899 }
7900 
7901 void LoopVectorizationCostModel::collectInLoopReductions() {
7902   for (auto &Reduction : Legal->getReductionVars()) {
7903     PHINode *Phi = Reduction.first;
7904     RecurrenceDescriptor &RdxDesc = Reduction.second;
7905 
7906     // We don't collect reductions that are type promoted (yet).
7907     if (RdxDesc.getRecurrenceType() != Phi->getType())
7908       continue;
7909 
7910     // If the target would prefer this reduction to happen "in-loop", then we
7911     // want to record it as such.
7912     unsigned Opcode = RdxDesc.getOpcode();
7913     if (!PreferInLoopReductions && !useOrderedReductions(RdxDesc) &&
7914         !TTI.preferInLoopReduction(Opcode, Phi->getType(),
7915                                    TargetTransformInfo::ReductionFlags()))
7916       continue;
7917 
7918     // Check that we can correctly put the reductions into the loop, by
7919     // finding the chain of operations that leads from the phi to the loop
7920     // exit value.
7921     SmallVector<Instruction *, 4> ReductionOperations =
7922         RdxDesc.getReductionOpChain(Phi, TheLoop);
7923     bool InLoop = !ReductionOperations.empty();
7924     if (InLoop) {
7925       InLoopReductionChains[Phi] = ReductionOperations;
7926       // Add the elements to InLoopReductionImmediateChains for cost modelling.
7927       Instruction *LastChain = Phi;
7928       for (auto *I : ReductionOperations) {
7929         InLoopReductionImmediateChains[I] = LastChain;
7930         LastChain = I;
7931       }
7932     }
7933     LLVM_DEBUG(dbgs() << "LV: Using " << (InLoop ? "inloop" : "out of loop")
7934                       << " reduction for phi: " << *Phi << "\n");
7935   }
7936 }
7937 
7938 // TODO: we could return a pair of values that specify the max VF and
7939 // min VF, to be used in `buildVPlans(MinVF, MaxVF)` instead of
7940 // `buildVPlans(VF, VF)`. We cannot do it because VPLAN at the moment
7941 // doesn't have a cost model that can choose which plan to execute if
7942 // more than one is generated.
7943 static unsigned determineVPlanVF(const unsigned WidestVectorRegBits,
7944                                  LoopVectorizationCostModel &CM) {
7945   unsigned WidestType;
7946   std::tie(std::ignore, WidestType) = CM.getSmallestAndWidestTypes();
7947   return WidestVectorRegBits / WidestType;
7948 }
7949 
7950 VectorizationFactor
7951 LoopVectorizationPlanner::planInVPlanNativePath(ElementCount UserVF) {
7952   assert(!UserVF.isScalable() && "scalable vectors not yet supported");
7953   ElementCount VF = UserVF;
7954   // Outer loop handling: They may require CFG and instruction level
7955   // transformations before even evaluating whether vectorization is profitable.
7956   // Since we cannot modify the incoming IR, we need to build VPlan upfront in
7957   // the vectorization pipeline.
7958   if (!OrigLoop->isInnermost()) {
7959     // If the user doesn't provide a vectorization factor, determine a
7960     // reasonable one.
7961     if (UserVF.isZero()) {
7962       VF = ElementCount::getFixed(determineVPlanVF(
7963           TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector)
7964               .getFixedSize(),
7965           CM));
7966       LLVM_DEBUG(dbgs() << "LV: VPlan computed VF " << VF << ".\n");
7967 
7968       // Make sure we have a VF > 1 for stress testing.
7969       if (VPlanBuildStressTest && (VF.isScalar() || VF.isZero())) {
7970         LLVM_DEBUG(dbgs() << "LV: VPlan stress testing: "
7971                           << "overriding computed VF.\n");
7972         VF = ElementCount::getFixed(4);
7973       }
7974     }
7975     assert(EnableVPlanNativePath && "VPlan-native path is not enabled.");
7976     assert(isPowerOf2_32(VF.getKnownMinValue()) &&
7977            "VF needs to be a power of two");
7978     LLVM_DEBUG(dbgs() << "LV: Using " << (!UserVF.isZero() ? "user " : "")
7979                       << "VF " << VF << " to build VPlans.\n");
7980     buildVPlans(VF, VF);
7981 
7982     // For VPlan build stress testing, we bail out after VPlan construction.
7983     if (VPlanBuildStressTest)
7984       return VectorizationFactor::Disabled();
7985 
7986     return {VF, 0 /*Cost*/};
7987   }
7988 
7989   LLVM_DEBUG(
7990       dbgs() << "LV: Not vectorizing. Inner loops aren't supported in the "
7991                 "VPlan-native path.\n");
7992   return VectorizationFactor::Disabled();
7993 }
7994 
7995 Optional<VectorizationFactor>
7996 LoopVectorizationPlanner::plan(ElementCount UserVF, unsigned UserIC) {
7997   assert(OrigLoop->isInnermost() && "Inner loop expected.");
7998   FixedScalableVFPair MaxFactors = CM.computeMaxVF(UserVF, UserIC);
7999   if (!MaxFactors) // Cases that should not to be vectorized nor interleaved.
8000     return None;
8001 
8002   // Invalidate interleave groups if all blocks of loop will be predicated.
8003   if (CM.blockNeedsPredication(OrigLoop->getHeader()) &&
8004       !useMaskedInterleavedAccesses(*TTI)) {
8005     LLVM_DEBUG(
8006         dbgs()
8007         << "LV: Invalidate all interleaved groups due to fold-tail by masking "
8008            "which requires masked-interleaved support.\n");
8009     if (CM.InterleaveInfo.invalidateGroups())
8010       // Invalidating interleave groups also requires invalidating all decisions
8011       // based on them, which includes widening decisions and uniform and scalar
8012       // values.
8013       CM.invalidateCostModelingDecisions();
8014   }
8015 
8016   ElementCount MaxUserVF =
8017       UserVF.isScalable() ? MaxFactors.ScalableVF : MaxFactors.FixedVF;
8018   bool UserVFIsLegal = ElementCount::isKnownLE(UserVF, MaxUserVF);
8019   if (!UserVF.isZero() && UserVFIsLegal) {
8020     assert(isPowerOf2_32(UserVF.getKnownMinValue()) &&
8021            "VF needs to be a power of two");
8022     // Collect the instructions (and their associated costs) that will be more
8023     // profitable to scalarize.
8024     if (CM.selectUserVectorizationFactor(UserVF)) {
8025       LLVM_DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
8026       CM.collectInLoopReductions();
8027       buildVPlansWithVPRecipes(UserVF, UserVF);
8028       LLVM_DEBUG(printPlans(dbgs()));
8029       return {{UserVF, 0}};
8030     } else
8031       reportVectorizationInfo("UserVF ignored because of invalid costs.",
8032                               "InvalidCost", ORE, OrigLoop);
8033   }
8034 
8035   // Populate the set of Vectorization Factor Candidates.
8036   ElementCountSet VFCandidates;
8037   for (auto VF = ElementCount::getFixed(1);
8038        ElementCount::isKnownLE(VF, MaxFactors.FixedVF); VF *= 2)
8039     VFCandidates.insert(VF);
8040   for (auto VF = ElementCount::getScalable(1);
8041        ElementCount::isKnownLE(VF, MaxFactors.ScalableVF); VF *= 2)
8042     VFCandidates.insert(VF);
8043 
8044   for (const auto &VF : VFCandidates) {
8045     // Collect Uniform and Scalar instructions after vectorization with VF.
8046     CM.collectUniformsAndScalars(VF);
8047 
8048     // Collect the instructions (and their associated costs) that will be more
8049     // profitable to scalarize.
8050     if (VF.isVector())
8051       CM.collectInstsToScalarize(VF);
8052   }
8053 
8054   CM.collectInLoopReductions();
8055   buildVPlansWithVPRecipes(ElementCount::getFixed(1), MaxFactors.FixedVF);
8056   buildVPlansWithVPRecipes(ElementCount::getScalable(1), MaxFactors.ScalableVF);
8057 
8058   LLVM_DEBUG(printPlans(dbgs()));
8059   if (!MaxFactors.hasVector())
8060     return VectorizationFactor::Disabled();
8061 
8062   // Select the optimal vectorization factor.
8063   auto SelectedVF = CM.selectVectorizationFactor(VFCandidates);
8064 
8065   // Check if it is profitable to vectorize with runtime checks.
8066   unsigned NumRuntimePointerChecks = Requirements.getNumRuntimePointerChecks();
8067   if (SelectedVF.Width.getKnownMinValue() > 1 && NumRuntimePointerChecks) {
8068     bool PragmaThresholdReached =
8069         NumRuntimePointerChecks > PragmaVectorizeMemoryCheckThreshold;
8070     bool ThresholdReached =
8071         NumRuntimePointerChecks > VectorizerParams::RuntimeMemoryCheckThreshold;
8072     if ((ThresholdReached && !Hints.allowReordering()) ||
8073         PragmaThresholdReached) {
8074       ORE->emit([&]() {
8075         return OptimizationRemarkAnalysisAliasing(
8076                    DEBUG_TYPE, "CantReorderMemOps", OrigLoop->getStartLoc(),
8077                    OrigLoop->getHeader())
8078                << "loop not vectorized: cannot prove it is safe to reorder "
8079                   "memory operations";
8080       });
8081       LLVM_DEBUG(dbgs() << "LV: Too many memory checks needed.\n");
8082       Hints.emitRemarkWithHints();
8083       return VectorizationFactor::Disabled();
8084     }
8085   }
8086   return SelectedVF;
8087 }
8088 
8089 void LoopVectorizationPlanner::setBestPlan(ElementCount VF, unsigned UF) {
8090   LLVM_DEBUG(dbgs() << "Setting best plan to VF=" << VF << ", UF=" << UF
8091                     << '\n');
8092   BestVF = VF;
8093   BestUF = UF;
8094 
8095   erase_if(VPlans, [VF](const VPlanPtr &Plan) {
8096     return !Plan->hasVF(VF);
8097   });
8098   assert(VPlans.size() == 1 && "Best VF has not a single VPlan.");
8099 }
8100 
8101 void LoopVectorizationPlanner::executePlan(InnerLoopVectorizer &ILV,
8102                                            DominatorTree *DT) {
8103   // Perform the actual loop transformation.
8104 
8105   // 1. Create a new empty loop. Unlink the old loop and connect the new one.
8106   assert(BestVF.hasValue() && "Vectorization Factor is missing");
8107   assert(VPlans.size() == 1 && "Not a single VPlan to execute.");
8108 
8109   VPTransformState State{
8110       *BestVF, BestUF, LI, DT, ILV.Builder, &ILV, VPlans.front().get()};
8111   State.CFG.PrevBB = ILV.createVectorizedLoopSkeleton();
8112   State.TripCount = ILV.getOrCreateTripCount(nullptr);
8113   State.CanonicalIV = ILV.Induction;
8114 
8115   ILV.printDebugTracesAtStart();
8116 
8117   //===------------------------------------------------===//
8118   //
8119   // Notice: any optimization or new instruction that go
8120   // into the code below should also be implemented in
8121   // the cost-model.
8122   //
8123   //===------------------------------------------------===//
8124 
8125   // 2. Copy and widen instructions from the old loop into the new loop.
8126   VPlans.front()->execute(&State);
8127 
8128   // 3. Fix the vectorized code: take care of header phi's, live-outs,
8129   //    predication, updating analyses.
8130   ILV.fixVectorizedLoop(State);
8131 
8132   ILV.printDebugTracesAtEnd();
8133 }
8134 
8135 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
8136 void LoopVectorizationPlanner::printPlans(raw_ostream &O) {
8137   for (const auto &Plan : VPlans)
8138     if (PrintVPlansInDotFormat)
8139       Plan->printDOT(O);
8140     else
8141       Plan->print(O);
8142 }
8143 #endif
8144 
8145 void LoopVectorizationPlanner::collectTriviallyDeadInstructions(
8146     SmallPtrSetImpl<Instruction *> &DeadInstructions) {
8147 
8148   // We create new control-flow for the vectorized loop, so the original exit
8149   // conditions will be dead after vectorization if it's only used by the
8150   // terminator
8151   SmallVector<BasicBlock*> ExitingBlocks;
8152   OrigLoop->getExitingBlocks(ExitingBlocks);
8153   for (auto *BB : ExitingBlocks) {
8154     auto *Cmp = dyn_cast<Instruction>(BB->getTerminator()->getOperand(0));
8155     if (!Cmp || !Cmp->hasOneUse())
8156       continue;
8157 
8158     // TODO: we should introduce a getUniqueExitingBlocks on Loop
8159     if (!DeadInstructions.insert(Cmp).second)
8160       continue;
8161 
8162     // The operands of the icmp is often a dead trunc, used by IndUpdate.
8163     // TODO: can recurse through operands in general
8164     for (Value *Op : Cmp->operands()) {
8165       if (isa<TruncInst>(Op) && Op->hasOneUse())
8166           DeadInstructions.insert(cast<Instruction>(Op));
8167     }
8168   }
8169 
8170   // We create new "steps" for induction variable updates to which the original
8171   // induction variables map. An original update instruction will be dead if
8172   // all its users except the induction variable are dead.
8173   auto *Latch = OrigLoop->getLoopLatch();
8174   for (auto &Induction : Legal->getInductionVars()) {
8175     PHINode *Ind = Induction.first;
8176     auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
8177 
8178     // If the tail is to be folded by masking, the primary induction variable,
8179     // if exists, isn't dead: it will be used for masking. Don't kill it.
8180     if (CM.foldTailByMasking() && IndUpdate == Legal->getPrimaryInduction())
8181       continue;
8182 
8183     if (llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
8184           return U == Ind || DeadInstructions.count(cast<Instruction>(U));
8185         }))
8186       DeadInstructions.insert(IndUpdate);
8187 
8188     // We record as "Dead" also the type-casting instructions we had identified
8189     // during induction analysis. We don't need any handling for them in the
8190     // vectorized loop because we have proven that, under a proper runtime
8191     // test guarding the vectorized loop, the value of the phi, and the casted
8192     // value of the phi, are the same. The last instruction in this casting chain
8193     // will get its scalar/vector/widened def from the scalar/vector/widened def
8194     // of the respective phi node. Any other casts in the induction def-use chain
8195     // have no other uses outside the phi update chain, and will be ignored.
8196     InductionDescriptor &IndDes = Induction.second;
8197     const SmallVectorImpl<Instruction *> &Casts = IndDes.getCastInsts();
8198     DeadInstructions.insert(Casts.begin(), Casts.end());
8199   }
8200 }
8201 
8202 Value *InnerLoopUnroller::reverseVector(Value *Vec) { return Vec; }
8203 
8204 Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) { return V; }
8205 
8206 Value *InnerLoopUnroller::getStepVector(Value *Val, int StartIdx, Value *Step,
8207                                         Instruction::BinaryOps BinOp) {
8208   // When unrolling and the VF is 1, we only need to add a simple scalar.
8209   Type *Ty = Val->getType();
8210   assert(!Ty->isVectorTy() && "Val must be a scalar");
8211 
8212   if (Ty->isFloatingPointTy()) {
8213     Constant *C = ConstantFP::get(Ty, (double)StartIdx);
8214 
8215     // Floating-point operations inherit FMF via the builder's flags.
8216     Value *MulOp = Builder.CreateFMul(C, Step);
8217     return Builder.CreateBinOp(BinOp, Val, MulOp);
8218   }
8219   Constant *C = ConstantInt::get(Ty, StartIdx);
8220   return Builder.CreateAdd(Val, Builder.CreateMul(C, Step), "induction");
8221 }
8222 
8223 static void AddRuntimeUnrollDisableMetaData(Loop *L) {
8224   SmallVector<Metadata *, 4> MDs;
8225   // Reserve first location for self reference to the LoopID metadata node.
8226   MDs.push_back(nullptr);
8227   bool IsUnrollMetadata = false;
8228   MDNode *LoopID = L->getLoopID();
8229   if (LoopID) {
8230     // First find existing loop unrolling disable metadata.
8231     for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
8232       auto *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
8233       if (MD) {
8234         const auto *S = dyn_cast<MDString>(MD->getOperand(0));
8235         IsUnrollMetadata =
8236             S && S->getString().startswith("llvm.loop.unroll.disable");
8237       }
8238       MDs.push_back(LoopID->getOperand(i));
8239     }
8240   }
8241 
8242   if (!IsUnrollMetadata) {
8243     // Add runtime unroll disable metadata.
8244     LLVMContext &Context = L->getHeader()->getContext();
8245     SmallVector<Metadata *, 1> DisableOperands;
8246     DisableOperands.push_back(
8247         MDString::get(Context, "llvm.loop.unroll.runtime.disable"));
8248     MDNode *DisableNode = MDNode::get(Context, DisableOperands);
8249     MDs.push_back(DisableNode);
8250     MDNode *NewLoopID = MDNode::get(Context, MDs);
8251     // Set operand 0 to refer to the loop id itself.
8252     NewLoopID->replaceOperandWith(0, NewLoopID);
8253     L->setLoopID(NewLoopID);
8254   }
8255 }
8256 
8257 //===--------------------------------------------------------------------===//
8258 // EpilogueVectorizerMainLoop
8259 //===--------------------------------------------------------------------===//
8260 
8261 /// This function is partially responsible for generating the control flow
8262 /// depicted in https://llvm.org/docs/Vectorizers.html#epilogue-vectorization.
8263 BasicBlock *EpilogueVectorizerMainLoop::createEpilogueVectorizedLoopSkeleton() {
8264   MDNode *OrigLoopID = OrigLoop->getLoopID();
8265   Loop *Lp = createVectorLoopSkeleton("");
8266 
8267   // Generate the code to check the minimum iteration count of the vector
8268   // epilogue (see below).
8269   EPI.EpilogueIterationCountCheck =
8270       emitMinimumIterationCountCheck(Lp, LoopScalarPreHeader, true);
8271   EPI.EpilogueIterationCountCheck->setName("iter.check");
8272 
8273   // Generate the code to check any assumptions that we've made for SCEV
8274   // expressions.
8275   EPI.SCEVSafetyCheck = emitSCEVChecks(Lp, LoopScalarPreHeader);
8276 
8277   // Generate the code that checks at runtime if arrays overlap. We put the
8278   // checks into a separate block to make the more common case of few elements
8279   // faster.
8280   EPI.MemSafetyCheck = emitMemRuntimeChecks(Lp, LoopScalarPreHeader);
8281 
8282   // Generate the iteration count check for the main loop, *after* the check
8283   // for the epilogue loop, so that the path-length is shorter for the case
8284   // that goes directly through the vector epilogue. The longer-path length for
8285   // the main loop is compensated for, by the gain from vectorizing the larger
8286   // trip count. Note: the branch will get updated later on when we vectorize
8287   // the epilogue.
8288   EPI.MainLoopIterationCountCheck =
8289       emitMinimumIterationCountCheck(Lp, LoopScalarPreHeader, false);
8290 
8291   // Generate the induction variable.
8292   OldInduction = Legal->getPrimaryInduction();
8293   Type *IdxTy = Legal->getWidestInductionType();
8294   Value *StartIdx = ConstantInt::get(IdxTy, 0);
8295   Constant *Step = ConstantInt::get(IdxTy, VF.getKnownMinValue() * UF);
8296   Value *CountRoundDown = getOrCreateVectorTripCount(Lp);
8297   EPI.VectorTripCount = CountRoundDown;
8298   Induction =
8299       createInductionVariable(Lp, StartIdx, CountRoundDown, Step,
8300                               getDebugLocFromInstOrOperands(OldInduction));
8301 
8302   // Skip induction resume value creation here because they will be created in
8303   // the second pass. If we created them here, they wouldn't be used anyway,
8304   // because the vplan in the second pass still contains the inductions from the
8305   // original loop.
8306 
8307   return completeLoopSkeleton(Lp, OrigLoopID);
8308 }
8309 
8310 void EpilogueVectorizerMainLoop::printDebugTracesAtStart() {
8311   LLVM_DEBUG({
8312     dbgs() << "Create Skeleton for epilogue vectorized loop (first pass)\n"
8313            << "Main Loop VF:" << EPI.MainLoopVF.getKnownMinValue()
8314            << ", Main Loop UF:" << EPI.MainLoopUF
8315            << ", Epilogue Loop VF:" << EPI.EpilogueVF.getKnownMinValue()
8316            << ", Epilogue Loop UF:" << EPI.EpilogueUF << "\n";
8317   });
8318 }
8319 
8320 void EpilogueVectorizerMainLoop::printDebugTracesAtEnd() {
8321   DEBUG_WITH_TYPE(VerboseDebug, {
8322     dbgs() << "intermediate fn:\n" << *Induction->getFunction() << "\n";
8323   });
8324 }
8325 
8326 BasicBlock *EpilogueVectorizerMainLoop::emitMinimumIterationCountCheck(
8327     Loop *L, BasicBlock *Bypass, bool ForEpilogue) {
8328   assert(L && "Expected valid Loop.");
8329   assert(Bypass && "Expected valid bypass basic block.");
8330   unsigned VFactor =
8331       ForEpilogue ? EPI.EpilogueVF.getKnownMinValue() : VF.getKnownMinValue();
8332   unsigned UFactor = ForEpilogue ? EPI.EpilogueUF : UF;
8333   Value *Count = getOrCreateTripCount(L);
8334   // Reuse existing vector loop preheader for TC checks.
8335   // Note that new preheader block is generated for vector loop.
8336   BasicBlock *const TCCheckBlock = LoopVectorPreHeader;
8337   IRBuilder<> Builder(TCCheckBlock->getTerminator());
8338 
8339   // Generate code to check if the loop's trip count is less than VF * UF of the
8340   // main vector loop.
8341   auto P = Cost->requiresScalarEpilogue(ForEpilogue ? EPI.EpilogueVF : VF) ?
8342       ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT;
8343 
8344   Value *CheckMinIters = Builder.CreateICmp(
8345       P, Count, ConstantInt::get(Count->getType(), VFactor * UFactor),
8346       "min.iters.check");
8347 
8348   if (!ForEpilogue)
8349     TCCheckBlock->setName("vector.main.loop.iter.check");
8350 
8351   // Create new preheader for vector loop.
8352   LoopVectorPreHeader = SplitBlock(TCCheckBlock, TCCheckBlock->getTerminator(),
8353                                    DT, LI, nullptr, "vector.ph");
8354 
8355   if (ForEpilogue) {
8356     assert(DT->properlyDominates(DT->getNode(TCCheckBlock),
8357                                  DT->getNode(Bypass)->getIDom()) &&
8358            "TC check is expected to dominate Bypass");
8359 
8360     // Update dominator for Bypass & LoopExit.
8361     DT->changeImmediateDominator(Bypass, TCCheckBlock);
8362     if (!Cost->requiresScalarEpilogue(EPI.EpilogueVF))
8363       // For loops with multiple exits, there's no edge from the middle block
8364       // to exit blocks (as the epilogue must run) and thus no need to update
8365       // the immediate dominator of the exit blocks.
8366       DT->changeImmediateDominator(LoopExitBlock, TCCheckBlock);
8367 
8368     LoopBypassBlocks.push_back(TCCheckBlock);
8369 
8370     // Save the trip count so we don't have to regenerate it in the
8371     // vec.epilog.iter.check. This is safe to do because the trip count
8372     // generated here dominates the vector epilog iter check.
8373     EPI.TripCount = Count;
8374   }
8375 
8376   ReplaceInstWithInst(
8377       TCCheckBlock->getTerminator(),
8378       BranchInst::Create(Bypass, LoopVectorPreHeader, CheckMinIters));
8379 
8380   return TCCheckBlock;
8381 }
8382 
8383 //===--------------------------------------------------------------------===//
8384 // EpilogueVectorizerEpilogueLoop
8385 //===--------------------------------------------------------------------===//
8386 
8387 /// This function is partially responsible for generating the control flow
8388 /// depicted in https://llvm.org/docs/Vectorizers.html#epilogue-vectorization.
8389 BasicBlock *
8390 EpilogueVectorizerEpilogueLoop::createEpilogueVectorizedLoopSkeleton() {
8391   MDNode *OrigLoopID = OrigLoop->getLoopID();
8392   Loop *Lp = createVectorLoopSkeleton("vec.epilog.");
8393 
8394   // Now, compare the remaining count and if there aren't enough iterations to
8395   // execute the vectorized epilogue skip to the scalar part.
8396   BasicBlock *VecEpilogueIterationCountCheck = LoopVectorPreHeader;
8397   VecEpilogueIterationCountCheck->setName("vec.epilog.iter.check");
8398   LoopVectorPreHeader =
8399       SplitBlock(LoopVectorPreHeader, LoopVectorPreHeader->getTerminator(), DT,
8400                  LI, nullptr, "vec.epilog.ph");
8401   emitMinimumVectorEpilogueIterCountCheck(Lp, LoopScalarPreHeader,
8402                                           VecEpilogueIterationCountCheck);
8403 
8404   // Adjust the control flow taking the state info from the main loop
8405   // vectorization into account.
8406   assert(EPI.MainLoopIterationCountCheck && EPI.EpilogueIterationCountCheck &&
8407          "expected this to be saved from the previous pass.");
8408   EPI.MainLoopIterationCountCheck->getTerminator()->replaceUsesOfWith(
8409       VecEpilogueIterationCountCheck, LoopVectorPreHeader);
8410 
8411   DT->changeImmediateDominator(LoopVectorPreHeader,
8412                                EPI.MainLoopIterationCountCheck);
8413 
8414   EPI.EpilogueIterationCountCheck->getTerminator()->replaceUsesOfWith(
8415       VecEpilogueIterationCountCheck, LoopScalarPreHeader);
8416 
8417   if (EPI.SCEVSafetyCheck)
8418     EPI.SCEVSafetyCheck->getTerminator()->replaceUsesOfWith(
8419         VecEpilogueIterationCountCheck, LoopScalarPreHeader);
8420   if (EPI.MemSafetyCheck)
8421     EPI.MemSafetyCheck->getTerminator()->replaceUsesOfWith(
8422         VecEpilogueIterationCountCheck, LoopScalarPreHeader);
8423 
8424   DT->changeImmediateDominator(
8425       VecEpilogueIterationCountCheck,
8426       VecEpilogueIterationCountCheck->getSinglePredecessor());
8427 
8428   DT->changeImmediateDominator(LoopScalarPreHeader,
8429                                EPI.EpilogueIterationCountCheck);
8430   if (!Cost->requiresScalarEpilogue(EPI.EpilogueVF))
8431     // If there is an epilogue which must run, there's no edge from the
8432     // middle block to exit blocks  and thus no need to update the immediate
8433     // dominator of the exit blocks.
8434     DT->changeImmediateDominator(LoopExitBlock,
8435                                  EPI.EpilogueIterationCountCheck);
8436 
8437   // Keep track of bypass blocks, as they feed start values to the induction
8438   // phis in the scalar loop preheader.
8439   if (EPI.SCEVSafetyCheck)
8440     LoopBypassBlocks.push_back(EPI.SCEVSafetyCheck);
8441   if (EPI.MemSafetyCheck)
8442     LoopBypassBlocks.push_back(EPI.MemSafetyCheck);
8443   LoopBypassBlocks.push_back(EPI.EpilogueIterationCountCheck);
8444 
8445   // Generate a resume induction for the vector epilogue and put it in the
8446   // vector epilogue preheader
8447   Type *IdxTy = Legal->getWidestInductionType();
8448   PHINode *EPResumeVal = PHINode::Create(IdxTy, 2, "vec.epilog.resume.val",
8449                                          LoopVectorPreHeader->getFirstNonPHI());
8450   EPResumeVal->addIncoming(EPI.VectorTripCount, VecEpilogueIterationCountCheck);
8451   EPResumeVal->addIncoming(ConstantInt::get(IdxTy, 0),
8452                            EPI.MainLoopIterationCountCheck);
8453 
8454   // Generate the induction variable.
8455   OldInduction = Legal->getPrimaryInduction();
8456   Value *CountRoundDown = getOrCreateVectorTripCount(Lp);
8457   Constant *Step = ConstantInt::get(IdxTy, VF.getKnownMinValue() * UF);
8458   Value *StartIdx = EPResumeVal;
8459   Induction =
8460       createInductionVariable(Lp, StartIdx, CountRoundDown, Step,
8461                               getDebugLocFromInstOrOperands(OldInduction));
8462 
8463   // Generate induction resume values. These variables save the new starting
8464   // indexes for the scalar loop. They are used to test if there are any tail
8465   // iterations left once the vector loop has completed.
8466   // Note that when the vectorized epilogue is skipped due to iteration count
8467   // check, then the resume value for the induction variable comes from
8468   // the trip count of the main vector loop, hence passing the AdditionalBypass
8469   // argument.
8470   createInductionResumeValues(Lp, CountRoundDown,
8471                               {VecEpilogueIterationCountCheck,
8472                                EPI.VectorTripCount} /* AdditionalBypass */);
8473 
8474   AddRuntimeUnrollDisableMetaData(Lp);
8475   return completeLoopSkeleton(Lp, OrigLoopID);
8476 }
8477 
8478 BasicBlock *
8479 EpilogueVectorizerEpilogueLoop::emitMinimumVectorEpilogueIterCountCheck(
8480     Loop *L, BasicBlock *Bypass, BasicBlock *Insert) {
8481 
8482   assert(EPI.TripCount &&
8483          "Expected trip count to have been safed in the first pass.");
8484   assert(
8485       (!isa<Instruction>(EPI.TripCount) ||
8486        DT->dominates(cast<Instruction>(EPI.TripCount)->getParent(), Insert)) &&
8487       "saved trip count does not dominate insertion point.");
8488   Value *TC = EPI.TripCount;
8489   IRBuilder<> Builder(Insert->getTerminator());
8490   Value *Count = Builder.CreateSub(TC, EPI.VectorTripCount, "n.vec.remaining");
8491 
8492   // Generate code to check if the loop's trip count is less than VF * UF of the
8493   // vector epilogue loop.
8494   auto P = Cost->requiresScalarEpilogue(EPI.EpilogueVF) ?
8495       ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT;
8496 
8497   Value *CheckMinIters = Builder.CreateICmp(
8498       P, Count,
8499       ConstantInt::get(Count->getType(),
8500                        EPI.EpilogueVF.getKnownMinValue() * EPI.EpilogueUF),
8501       "min.epilog.iters.check");
8502 
8503   ReplaceInstWithInst(
8504       Insert->getTerminator(),
8505       BranchInst::Create(Bypass, LoopVectorPreHeader, CheckMinIters));
8506 
8507   LoopBypassBlocks.push_back(Insert);
8508   return Insert;
8509 }
8510 
8511 void EpilogueVectorizerEpilogueLoop::printDebugTracesAtStart() {
8512   LLVM_DEBUG({
8513     dbgs() << "Create Skeleton for epilogue vectorized loop (second pass)\n"
8514            << "Epilogue Loop VF:" << EPI.EpilogueVF.getKnownMinValue()
8515            << ", Epilogue Loop UF:" << EPI.EpilogueUF << "\n";
8516   });
8517 }
8518 
8519 void EpilogueVectorizerEpilogueLoop::printDebugTracesAtEnd() {
8520   DEBUG_WITH_TYPE(VerboseDebug, {
8521     dbgs() << "final fn:\n" << *Induction->getFunction() << "\n";
8522   });
8523 }
8524 
8525 bool LoopVectorizationPlanner::getDecisionAndClampRange(
8526     const std::function<bool(ElementCount)> &Predicate, VFRange &Range) {
8527   assert(!Range.isEmpty() && "Trying to test an empty VF range.");
8528   bool PredicateAtRangeStart = Predicate(Range.Start);
8529 
8530   for (ElementCount TmpVF = Range.Start * 2;
8531        ElementCount::isKnownLT(TmpVF, Range.End); TmpVF *= 2)
8532     if (Predicate(TmpVF) != PredicateAtRangeStart) {
8533       Range.End = TmpVF;
8534       break;
8535     }
8536 
8537   return PredicateAtRangeStart;
8538 }
8539 
8540 /// Build VPlans for the full range of feasible VF's = {\p MinVF, 2 * \p MinVF,
8541 /// 4 * \p MinVF, ..., \p MaxVF} by repeatedly building a VPlan for a sub-range
8542 /// of VF's starting at a given VF and extending it as much as possible. Each
8543 /// vectorization decision can potentially shorten this sub-range during
8544 /// buildVPlan().
8545 void LoopVectorizationPlanner::buildVPlans(ElementCount MinVF,
8546                                            ElementCount MaxVF) {
8547   auto MaxVFPlusOne = MaxVF.getWithIncrement(1);
8548   for (ElementCount VF = MinVF; ElementCount::isKnownLT(VF, MaxVFPlusOne);) {
8549     VFRange SubRange = {VF, MaxVFPlusOne};
8550     VPlans.push_back(buildVPlan(SubRange));
8551     VF = SubRange.End;
8552   }
8553 }
8554 
8555 VPValue *VPRecipeBuilder::createEdgeMask(BasicBlock *Src, BasicBlock *Dst,
8556                                          VPlanPtr &Plan) {
8557   assert(is_contained(predecessors(Dst), Src) && "Invalid edge");
8558 
8559   // Look for cached value.
8560   std::pair<BasicBlock *, BasicBlock *> Edge(Src, Dst);
8561   EdgeMaskCacheTy::iterator ECEntryIt = EdgeMaskCache.find(Edge);
8562   if (ECEntryIt != EdgeMaskCache.end())
8563     return ECEntryIt->second;
8564 
8565   VPValue *SrcMask = createBlockInMask(Src, Plan);
8566 
8567   // The terminator has to be a branch inst!
8568   BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
8569   assert(BI && "Unexpected terminator found");
8570 
8571   if (!BI->isConditional() || BI->getSuccessor(0) == BI->getSuccessor(1))
8572     return EdgeMaskCache[Edge] = SrcMask;
8573 
8574   // If source is an exiting block, we know the exit edge is dynamically dead
8575   // in the vector loop, and thus we don't need to restrict the mask.  Avoid
8576   // adding uses of an otherwise potentially dead instruction.
8577   if (OrigLoop->isLoopExiting(Src))
8578     return EdgeMaskCache[Edge] = SrcMask;
8579 
8580   VPValue *EdgeMask = Plan->getOrAddVPValue(BI->getCondition());
8581   assert(EdgeMask && "No Edge Mask found for condition");
8582 
8583   if (BI->getSuccessor(0) != Dst)
8584     EdgeMask = Builder.createNot(EdgeMask);
8585 
8586   if (SrcMask) { // Otherwise block in-mask is all-one, no need to AND.
8587     // The condition is 'SrcMask && EdgeMask', which is equivalent to
8588     // 'select i1 SrcMask, i1 EdgeMask, i1 false'.
8589     // The select version does not introduce new UB if SrcMask is false and
8590     // EdgeMask is poison. Using 'and' here introduces undefined behavior.
8591     VPValue *False = Plan->getOrAddVPValue(
8592         ConstantInt::getFalse(BI->getCondition()->getType()));
8593     EdgeMask = Builder.createSelect(SrcMask, EdgeMask, False);
8594   }
8595 
8596   return EdgeMaskCache[Edge] = EdgeMask;
8597 }
8598 
8599 VPValue *VPRecipeBuilder::createBlockInMask(BasicBlock *BB, VPlanPtr &Plan) {
8600   assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
8601 
8602   // Look for cached value.
8603   BlockMaskCacheTy::iterator BCEntryIt = BlockMaskCache.find(BB);
8604   if (BCEntryIt != BlockMaskCache.end())
8605     return BCEntryIt->second;
8606 
8607   // All-one mask is modelled as no-mask following the convention for masked
8608   // load/store/gather/scatter. Initialize BlockMask to no-mask.
8609   VPValue *BlockMask = nullptr;
8610 
8611   if (OrigLoop->getHeader() == BB) {
8612     if (!CM.blockNeedsPredication(BB))
8613       return BlockMaskCache[BB] = BlockMask; // Loop incoming mask is all-one.
8614 
8615     // Create the block in mask as the first non-phi instruction in the block.
8616     VPBuilder::InsertPointGuard Guard(Builder);
8617     auto NewInsertionPoint = Builder.getInsertBlock()->getFirstNonPhi();
8618     Builder.setInsertPoint(Builder.getInsertBlock(), NewInsertionPoint);
8619 
8620     // Introduce the early-exit compare IV <= BTC to form header block mask.
8621     // This is used instead of IV < TC because TC may wrap, unlike BTC.
8622     // Start by constructing the desired canonical IV.
8623     VPValue *IV = nullptr;
8624     if (Legal->getPrimaryInduction())
8625       IV = Plan->getOrAddVPValue(Legal->getPrimaryInduction());
8626     else {
8627       auto IVRecipe = new VPWidenCanonicalIVRecipe();
8628       Builder.getInsertBlock()->insert(IVRecipe, NewInsertionPoint);
8629       IV = IVRecipe->getVPSingleValue();
8630     }
8631     VPValue *BTC = Plan->getOrCreateBackedgeTakenCount();
8632     bool TailFolded = !CM.isScalarEpilogueAllowed();
8633 
8634     if (TailFolded && CM.TTI.emitGetActiveLaneMask()) {
8635       // While ActiveLaneMask is a binary op that consumes the loop tripcount
8636       // as a second argument, we only pass the IV here and extract the
8637       // tripcount from the transform state where codegen of the VP instructions
8638       // happen.
8639       BlockMask = Builder.createNaryOp(VPInstruction::ActiveLaneMask, {IV});
8640     } else {
8641       BlockMask = Builder.createNaryOp(VPInstruction::ICmpULE, {IV, BTC});
8642     }
8643     return BlockMaskCache[BB] = BlockMask;
8644   }
8645 
8646   // This is the block mask. We OR all incoming edges.
8647   for (auto *Predecessor : predecessors(BB)) {
8648     VPValue *EdgeMask = createEdgeMask(Predecessor, BB, Plan);
8649     if (!EdgeMask) // Mask of predecessor is all-one so mask of block is too.
8650       return BlockMaskCache[BB] = EdgeMask;
8651 
8652     if (!BlockMask) { // BlockMask has its initialized nullptr value.
8653       BlockMask = EdgeMask;
8654       continue;
8655     }
8656 
8657     BlockMask = Builder.createOr(BlockMask, EdgeMask);
8658   }
8659 
8660   return BlockMaskCache[BB] = BlockMask;
8661 }
8662 
8663 VPRecipeBase *VPRecipeBuilder::tryToWidenMemory(Instruction *I,
8664                                                 ArrayRef<VPValue *> Operands,
8665                                                 VFRange &Range,
8666                                                 VPlanPtr &Plan) {
8667   assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
8668          "Must be called with either a load or store");
8669 
8670   auto willWiden = [&](ElementCount VF) -> bool {
8671     if (VF.isScalar())
8672       return false;
8673     LoopVectorizationCostModel::InstWidening Decision =
8674         CM.getWideningDecision(I, VF);
8675     assert(Decision != LoopVectorizationCostModel::CM_Unknown &&
8676            "CM decision should be taken at this point.");
8677     if (Decision == LoopVectorizationCostModel::CM_Interleave)
8678       return true;
8679     if (CM.isScalarAfterVectorization(I, VF) ||
8680         CM.isProfitableToScalarize(I, VF))
8681       return false;
8682     return Decision != LoopVectorizationCostModel::CM_Scalarize;
8683   };
8684 
8685   if (!LoopVectorizationPlanner::getDecisionAndClampRange(willWiden, Range))
8686     return nullptr;
8687 
8688   VPValue *Mask = nullptr;
8689   if (Legal->isMaskRequired(I))
8690     Mask = createBlockInMask(I->getParent(), Plan);
8691 
8692   if (LoadInst *Load = dyn_cast<LoadInst>(I))
8693     return new VPWidenMemoryInstructionRecipe(*Load, Operands[0], Mask);
8694 
8695   StoreInst *Store = cast<StoreInst>(I);
8696   return new VPWidenMemoryInstructionRecipe(*Store, Operands[1], Operands[0],
8697                                             Mask);
8698 }
8699 
8700 VPWidenIntOrFpInductionRecipe *
8701 VPRecipeBuilder::tryToOptimizeInductionPHI(PHINode *Phi,
8702                                            ArrayRef<VPValue *> Operands) const {
8703   // Check if this is an integer or fp induction. If so, build the recipe that
8704   // produces its scalar and vector values.
8705   InductionDescriptor II = Legal->getInductionVars().lookup(Phi);
8706   if (II.getKind() == InductionDescriptor::IK_IntInduction ||
8707       II.getKind() == InductionDescriptor::IK_FpInduction) {
8708     assert(II.getStartValue() ==
8709            Phi->getIncomingValueForBlock(OrigLoop->getLoopPreheader()));
8710     const SmallVectorImpl<Instruction *> &Casts = II.getCastInsts();
8711     return new VPWidenIntOrFpInductionRecipe(
8712         Phi, Operands[0], Casts.empty() ? nullptr : Casts.front());
8713   }
8714 
8715   return nullptr;
8716 }
8717 
8718 VPWidenIntOrFpInductionRecipe *VPRecipeBuilder::tryToOptimizeInductionTruncate(
8719     TruncInst *I, ArrayRef<VPValue *> Operands, VFRange &Range,
8720     VPlan &Plan) const {
8721   // Optimize the special case where the source is a constant integer
8722   // induction variable. Notice that we can only optimize the 'trunc' case
8723   // because (a) FP conversions lose precision, (b) sext/zext may wrap, and
8724   // (c) other casts depend on pointer size.
8725 
8726   // Determine whether \p K is a truncation based on an induction variable that
8727   // can be optimized.
8728   auto isOptimizableIVTruncate =
8729       [&](Instruction *K) -> std::function<bool(ElementCount)> {
8730     return [=](ElementCount VF) -> bool {
8731       return CM.isOptimizableIVTruncate(K, VF);
8732     };
8733   };
8734 
8735   if (LoopVectorizationPlanner::getDecisionAndClampRange(
8736           isOptimizableIVTruncate(I), Range)) {
8737 
8738     InductionDescriptor II =
8739         Legal->getInductionVars().lookup(cast<PHINode>(I->getOperand(0)));
8740     VPValue *Start = Plan.getOrAddVPValue(II.getStartValue());
8741     return new VPWidenIntOrFpInductionRecipe(cast<PHINode>(I->getOperand(0)),
8742                                              Start, nullptr, I);
8743   }
8744   return nullptr;
8745 }
8746 
8747 VPRecipeOrVPValueTy VPRecipeBuilder::tryToBlend(PHINode *Phi,
8748                                                 ArrayRef<VPValue *> Operands,
8749                                                 VPlanPtr &Plan) {
8750   // If all incoming values are equal, the incoming VPValue can be used directly
8751   // instead of creating a new VPBlendRecipe.
8752   VPValue *FirstIncoming = Operands[0];
8753   if (all_of(Operands, [FirstIncoming](const VPValue *Inc) {
8754         return FirstIncoming == Inc;
8755       })) {
8756     return Operands[0];
8757   }
8758 
8759   // We know that all PHIs in non-header blocks are converted into selects, so
8760   // we don't have to worry about the insertion order and we can just use the
8761   // builder. At this point we generate the predication tree. There may be
8762   // duplications since this is a simple recursive scan, but future
8763   // optimizations will clean it up.
8764   SmallVector<VPValue *, 2> OperandsWithMask;
8765   unsigned NumIncoming = Phi->getNumIncomingValues();
8766 
8767   for (unsigned In = 0; In < NumIncoming; In++) {
8768     VPValue *EdgeMask =
8769       createEdgeMask(Phi->getIncomingBlock(In), Phi->getParent(), Plan);
8770     assert((EdgeMask || NumIncoming == 1) &&
8771            "Multiple predecessors with one having a full mask");
8772     OperandsWithMask.push_back(Operands[In]);
8773     if (EdgeMask)
8774       OperandsWithMask.push_back(EdgeMask);
8775   }
8776   return toVPRecipeResult(new VPBlendRecipe(Phi, OperandsWithMask));
8777 }
8778 
8779 VPWidenCallRecipe *VPRecipeBuilder::tryToWidenCall(CallInst *CI,
8780                                                    ArrayRef<VPValue *> Operands,
8781                                                    VFRange &Range) const {
8782 
8783   bool IsPredicated = LoopVectorizationPlanner::getDecisionAndClampRange(
8784       [this, CI](ElementCount VF) { return CM.isScalarWithPredication(CI); },
8785       Range);
8786 
8787   if (IsPredicated)
8788     return nullptr;
8789 
8790   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
8791   if (ID && (ID == Intrinsic::assume || ID == Intrinsic::lifetime_end ||
8792              ID == Intrinsic::lifetime_start || ID == Intrinsic::sideeffect ||
8793              ID == Intrinsic::pseudoprobe ||
8794              ID == Intrinsic::experimental_noalias_scope_decl))
8795     return nullptr;
8796 
8797   auto willWiden = [&](ElementCount VF) -> bool {
8798     Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
8799     // The following case may be scalarized depending on the VF.
8800     // The flag shows whether we use Intrinsic or a usual Call for vectorized
8801     // version of the instruction.
8802     // Is it beneficial to perform intrinsic call compared to lib call?
8803     bool NeedToScalarize = false;
8804     InstructionCost CallCost = CM.getVectorCallCost(CI, VF, NeedToScalarize);
8805     InstructionCost IntrinsicCost = ID ? CM.getVectorIntrinsicCost(CI, VF) : 0;
8806     bool UseVectorIntrinsic = ID && IntrinsicCost <= CallCost;
8807     return UseVectorIntrinsic || !NeedToScalarize;
8808   };
8809 
8810   if (!LoopVectorizationPlanner::getDecisionAndClampRange(willWiden, Range))
8811     return nullptr;
8812 
8813   ArrayRef<VPValue *> Ops = Operands.take_front(CI->getNumArgOperands());
8814   return new VPWidenCallRecipe(*CI, make_range(Ops.begin(), Ops.end()));
8815 }
8816 
8817 bool VPRecipeBuilder::shouldWiden(Instruction *I, VFRange &Range) const {
8818   assert(!isa<BranchInst>(I) && !isa<PHINode>(I) && !isa<LoadInst>(I) &&
8819          !isa<StoreInst>(I) && "Instruction should have been handled earlier");
8820   // Instruction should be widened, unless it is scalar after vectorization,
8821   // scalarization is profitable or it is predicated.
8822   auto WillScalarize = [this, I](ElementCount VF) -> bool {
8823     return CM.isScalarAfterVectorization(I, VF) ||
8824            CM.isProfitableToScalarize(I, VF) || CM.isScalarWithPredication(I);
8825   };
8826   return !LoopVectorizationPlanner::getDecisionAndClampRange(WillScalarize,
8827                                                              Range);
8828 }
8829 
8830 VPWidenRecipe *VPRecipeBuilder::tryToWiden(Instruction *I,
8831                                            ArrayRef<VPValue *> Operands) const {
8832   auto IsVectorizableOpcode = [](unsigned Opcode) {
8833     switch (Opcode) {
8834     case Instruction::Add:
8835     case Instruction::And:
8836     case Instruction::AShr:
8837     case Instruction::BitCast:
8838     case Instruction::FAdd:
8839     case Instruction::FCmp:
8840     case Instruction::FDiv:
8841     case Instruction::FMul:
8842     case Instruction::FNeg:
8843     case Instruction::FPExt:
8844     case Instruction::FPToSI:
8845     case Instruction::FPToUI:
8846     case Instruction::FPTrunc:
8847     case Instruction::FRem:
8848     case Instruction::FSub:
8849     case Instruction::ICmp:
8850     case Instruction::IntToPtr:
8851     case Instruction::LShr:
8852     case Instruction::Mul:
8853     case Instruction::Or:
8854     case Instruction::PtrToInt:
8855     case Instruction::SDiv:
8856     case Instruction::Select:
8857     case Instruction::SExt:
8858     case Instruction::Shl:
8859     case Instruction::SIToFP:
8860     case Instruction::SRem:
8861     case Instruction::Sub:
8862     case Instruction::Trunc:
8863     case Instruction::UDiv:
8864     case Instruction::UIToFP:
8865     case Instruction::URem:
8866     case Instruction::Xor:
8867     case Instruction::ZExt:
8868       return true;
8869     }
8870     return false;
8871   };
8872 
8873   if (!IsVectorizableOpcode(I->getOpcode()))
8874     return nullptr;
8875 
8876   // Success: widen this instruction.
8877   return new VPWidenRecipe(*I, make_range(Operands.begin(), Operands.end()));
8878 }
8879 
8880 void VPRecipeBuilder::fixHeaderPhis() {
8881   BasicBlock *OrigLatch = OrigLoop->getLoopLatch();
8882   for (VPWidenPHIRecipe *R : PhisToFix) {
8883     auto *PN = cast<PHINode>(R->getUnderlyingValue());
8884     VPRecipeBase *IncR =
8885         getRecipe(cast<Instruction>(PN->getIncomingValueForBlock(OrigLatch)));
8886     R->addOperand(IncR->getVPSingleValue());
8887   }
8888 }
8889 
8890 VPBasicBlock *VPRecipeBuilder::handleReplication(
8891     Instruction *I, VFRange &Range, VPBasicBlock *VPBB,
8892     VPlanPtr &Plan) {
8893   bool IsUniform = LoopVectorizationPlanner::getDecisionAndClampRange(
8894       [&](ElementCount VF) { return CM.isUniformAfterVectorization(I, VF); },
8895       Range);
8896 
8897   bool IsPredicated = LoopVectorizationPlanner::getDecisionAndClampRange(
8898       [&](ElementCount VF) { return CM.isPredicatedInst(I); }, Range);
8899 
8900   auto *Recipe = new VPReplicateRecipe(I, Plan->mapToVPValues(I->operands()),
8901                                        IsUniform, IsPredicated);
8902   setRecipe(I, Recipe);
8903   Plan->addVPValue(I, Recipe);
8904 
8905   // Find if I uses a predicated instruction. If so, it will use its scalar
8906   // value. Avoid hoisting the insert-element which packs the scalar value into
8907   // a vector value, as that happens iff all users use the vector value.
8908   for (VPValue *Op : Recipe->operands()) {
8909     auto *PredR = dyn_cast_or_null<VPPredInstPHIRecipe>(Op->getDef());
8910     if (!PredR)
8911       continue;
8912     auto *RepR =
8913         cast_or_null<VPReplicateRecipe>(PredR->getOperand(0)->getDef());
8914     assert(RepR->isPredicated() &&
8915            "expected Replicate recipe to be predicated");
8916     RepR->setAlsoPack(false);
8917   }
8918 
8919   // Finalize the recipe for Instr, first if it is not predicated.
8920   if (!IsPredicated) {
8921     LLVM_DEBUG(dbgs() << "LV: Scalarizing:" << *I << "\n");
8922     VPBB->appendRecipe(Recipe);
8923     return VPBB;
8924   }
8925   LLVM_DEBUG(dbgs() << "LV: Scalarizing and predicating:" << *I << "\n");
8926   assert(VPBB->getSuccessors().empty() &&
8927          "VPBB has successors when handling predicated replication.");
8928   // Record predicated instructions for above packing optimizations.
8929   VPBlockBase *Region = createReplicateRegion(I, Recipe, Plan);
8930   VPBlockUtils::insertBlockAfter(Region, VPBB);
8931   auto *RegSucc = new VPBasicBlock();
8932   VPBlockUtils::insertBlockAfter(RegSucc, Region);
8933   return RegSucc;
8934 }
8935 
8936 VPRegionBlock *VPRecipeBuilder::createReplicateRegion(Instruction *Instr,
8937                                                       VPRecipeBase *PredRecipe,
8938                                                       VPlanPtr &Plan) {
8939   // Instructions marked for predication are replicated and placed under an
8940   // if-then construct to prevent side-effects.
8941 
8942   // Generate recipes to compute the block mask for this region.
8943   VPValue *BlockInMask = createBlockInMask(Instr->getParent(), Plan);
8944 
8945   // Build the triangular if-then region.
8946   std::string RegionName = (Twine("pred.") + Instr->getOpcodeName()).str();
8947   assert(Instr->getParent() && "Predicated instruction not in any basic block");
8948   auto *BOMRecipe = new VPBranchOnMaskRecipe(BlockInMask);
8949   auto *Entry = new VPBasicBlock(Twine(RegionName) + ".entry", BOMRecipe);
8950   auto *PHIRecipe = Instr->getType()->isVoidTy()
8951                         ? nullptr
8952                         : new VPPredInstPHIRecipe(Plan->getOrAddVPValue(Instr));
8953   if (PHIRecipe) {
8954     Plan->removeVPValueFor(Instr);
8955     Plan->addVPValue(Instr, PHIRecipe);
8956   }
8957   auto *Exit = new VPBasicBlock(Twine(RegionName) + ".continue", PHIRecipe);
8958   auto *Pred = new VPBasicBlock(Twine(RegionName) + ".if", PredRecipe);
8959   VPRegionBlock *Region = new VPRegionBlock(Entry, Exit, RegionName, true);
8960 
8961   // Note: first set Entry as region entry and then connect successors starting
8962   // from it in order, to propagate the "parent" of each VPBasicBlock.
8963   VPBlockUtils::insertTwoBlocksAfter(Pred, Exit, BlockInMask, Entry);
8964   VPBlockUtils::connectBlocks(Pred, Exit);
8965 
8966   return Region;
8967 }
8968 
8969 VPRecipeOrVPValueTy
8970 VPRecipeBuilder::tryToCreateWidenRecipe(Instruction *Instr,
8971                                         ArrayRef<VPValue *> Operands,
8972                                         VFRange &Range, VPlanPtr &Plan) {
8973   // First, check for specific widening recipes that deal with calls, memory
8974   // operations, inductions and Phi nodes.
8975   if (auto *CI = dyn_cast<CallInst>(Instr))
8976     return toVPRecipeResult(tryToWidenCall(CI, Operands, Range));
8977 
8978   if (isa<LoadInst>(Instr) || isa<StoreInst>(Instr))
8979     return toVPRecipeResult(tryToWidenMemory(Instr, Operands, Range, Plan));
8980 
8981   VPRecipeBase *Recipe;
8982   if (auto Phi = dyn_cast<PHINode>(Instr)) {
8983     if (Phi->getParent() != OrigLoop->getHeader())
8984       return tryToBlend(Phi, Operands, Plan);
8985     if ((Recipe = tryToOptimizeInductionPHI(Phi, Operands)))
8986       return toVPRecipeResult(Recipe);
8987 
8988     VPWidenPHIRecipe *PhiRecipe = nullptr;
8989     if (Legal->isReductionVariable(Phi) || Legal->isFirstOrderRecurrence(Phi)) {
8990       VPValue *StartV = Operands[0];
8991       if (Legal->isReductionVariable(Phi)) {
8992         RecurrenceDescriptor &RdxDesc = Legal->getReductionVars()[Phi];
8993         assert(RdxDesc.getRecurrenceStartValue() ==
8994                Phi->getIncomingValueForBlock(OrigLoop->getLoopPreheader()));
8995         PhiRecipe = new VPReductionPHIRecipe(Phi, RdxDesc, *StartV,
8996                                              CM.isInLoopReduction(Phi),
8997                                              CM.useOrderedReductions(RdxDesc));
8998       } else {
8999         PhiRecipe = new VPWidenPHIRecipe(Phi, *StartV);
9000       }
9001 
9002       // Record the incoming value from the backedge, so we can add the incoming
9003       // value from the backedge after all recipes have been created.
9004       recordRecipeOf(cast<Instruction>(
9005           Phi->getIncomingValueForBlock(OrigLoop->getLoopLatch())));
9006       PhisToFix.push_back(PhiRecipe);
9007     } else {
9008       // TODO: record start and backedge value for remaining pointer induction
9009       // phis.
9010       assert(Phi->getType()->isPointerTy() &&
9011              "only pointer phis should be handled here");
9012       PhiRecipe = new VPWidenPHIRecipe(Phi);
9013     }
9014 
9015     return toVPRecipeResult(PhiRecipe);
9016   }
9017 
9018   if (isa<TruncInst>(Instr) &&
9019       (Recipe = tryToOptimizeInductionTruncate(cast<TruncInst>(Instr), Operands,
9020                                                Range, *Plan)))
9021     return toVPRecipeResult(Recipe);
9022 
9023   if (!shouldWiden(Instr, Range))
9024     return nullptr;
9025 
9026   if (auto GEP = dyn_cast<GetElementPtrInst>(Instr))
9027     return toVPRecipeResult(new VPWidenGEPRecipe(
9028         GEP, make_range(Operands.begin(), Operands.end()), OrigLoop));
9029 
9030   if (auto *SI = dyn_cast<SelectInst>(Instr)) {
9031     bool InvariantCond =
9032         PSE.getSE()->isLoopInvariant(PSE.getSCEV(SI->getOperand(0)), OrigLoop);
9033     return toVPRecipeResult(new VPWidenSelectRecipe(
9034         *SI, make_range(Operands.begin(), Operands.end()), InvariantCond));
9035   }
9036 
9037   return toVPRecipeResult(tryToWiden(Instr, Operands));
9038 }
9039 
9040 void LoopVectorizationPlanner::buildVPlansWithVPRecipes(ElementCount MinVF,
9041                                                         ElementCount MaxVF) {
9042   assert(OrigLoop->isInnermost() && "Inner loop expected.");
9043 
9044   // Collect instructions from the original loop that will become trivially dead
9045   // in the vectorized loop. We don't need to vectorize these instructions. For
9046   // example, original induction update instructions can become dead because we
9047   // separately emit induction "steps" when generating code for the new loop.
9048   // Similarly, we create a new latch condition when setting up the structure
9049   // of the new loop, so the old one can become dead.
9050   SmallPtrSet<Instruction *, 4> DeadInstructions;
9051   collectTriviallyDeadInstructions(DeadInstructions);
9052 
9053   // Add assume instructions we need to drop to DeadInstructions, to prevent
9054   // them from being added to the VPlan.
9055   // TODO: We only need to drop assumes in blocks that get flattend. If the
9056   // control flow is preserved, we should keep them.
9057   auto &ConditionalAssumes = Legal->getConditionalAssumes();
9058   DeadInstructions.insert(ConditionalAssumes.begin(), ConditionalAssumes.end());
9059 
9060   MapVector<Instruction *, Instruction *> &SinkAfter = Legal->getSinkAfter();
9061   // Dead instructions do not need sinking. Remove them from SinkAfter.
9062   for (Instruction *I : DeadInstructions)
9063     SinkAfter.erase(I);
9064 
9065   // Cannot sink instructions after dead instructions (there won't be any
9066   // recipes for them). Instead, find the first non-dead previous instruction.
9067   for (auto &P : Legal->getSinkAfter()) {
9068     Instruction *SinkTarget = P.second;
9069     Instruction *FirstInst = &*SinkTarget->getParent()->begin();
9070     (void)FirstInst;
9071     while (DeadInstructions.contains(SinkTarget)) {
9072       assert(
9073           SinkTarget != FirstInst &&
9074           "Must find a live instruction (at least the one feeding the "
9075           "first-order recurrence PHI) before reaching beginning of the block");
9076       SinkTarget = SinkTarget->getPrevNode();
9077       assert(SinkTarget != P.first &&
9078              "sink source equals target, no sinking required");
9079     }
9080     P.second = SinkTarget;
9081   }
9082 
9083   auto MaxVFPlusOne = MaxVF.getWithIncrement(1);
9084   for (ElementCount VF = MinVF; ElementCount::isKnownLT(VF, MaxVFPlusOne);) {
9085     VFRange SubRange = {VF, MaxVFPlusOne};
9086     VPlans.push_back(
9087         buildVPlanWithVPRecipes(SubRange, DeadInstructions, SinkAfter));
9088     VF = SubRange.End;
9089   }
9090 }
9091 
9092 VPlanPtr LoopVectorizationPlanner::buildVPlanWithVPRecipes(
9093     VFRange &Range, SmallPtrSetImpl<Instruction *> &DeadInstructions,
9094     const MapVector<Instruction *, Instruction *> &SinkAfter) {
9095 
9096   SmallPtrSet<const InterleaveGroup<Instruction> *, 1> InterleaveGroups;
9097 
9098   VPRecipeBuilder RecipeBuilder(OrigLoop, TLI, Legal, CM, PSE, Builder);
9099 
9100   // ---------------------------------------------------------------------------
9101   // Pre-construction: record ingredients whose recipes we'll need to further
9102   // process after constructing the initial VPlan.
9103   // ---------------------------------------------------------------------------
9104 
9105   // Mark instructions we'll need to sink later and their targets as
9106   // ingredients whose recipe we'll need to record.
9107   for (auto &Entry : SinkAfter) {
9108     RecipeBuilder.recordRecipeOf(Entry.first);
9109     RecipeBuilder.recordRecipeOf(Entry.second);
9110   }
9111   for (auto &Reduction : CM.getInLoopReductionChains()) {
9112     PHINode *Phi = Reduction.first;
9113     RecurKind Kind = Legal->getReductionVars()[Phi].getRecurrenceKind();
9114     const SmallVector<Instruction *, 4> &ReductionOperations = Reduction.second;
9115 
9116     RecipeBuilder.recordRecipeOf(Phi);
9117     for (auto &R : ReductionOperations) {
9118       RecipeBuilder.recordRecipeOf(R);
9119       // For min/max reducitons, where we have a pair of icmp/select, we also
9120       // need to record the ICmp recipe, so it can be removed later.
9121       if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind))
9122         RecipeBuilder.recordRecipeOf(cast<Instruction>(R->getOperand(0)));
9123     }
9124   }
9125 
9126   // For each interleave group which is relevant for this (possibly trimmed)
9127   // Range, add it to the set of groups to be later applied to the VPlan and add
9128   // placeholders for its members' Recipes which we'll be replacing with a
9129   // single VPInterleaveRecipe.
9130   for (InterleaveGroup<Instruction> *IG : IAI.getInterleaveGroups()) {
9131     auto applyIG = [IG, this](ElementCount VF) -> bool {
9132       return (VF.isVector() && // Query is illegal for VF == 1
9133               CM.getWideningDecision(IG->getInsertPos(), VF) ==
9134                   LoopVectorizationCostModel::CM_Interleave);
9135     };
9136     if (!getDecisionAndClampRange(applyIG, Range))
9137       continue;
9138     InterleaveGroups.insert(IG);
9139     for (unsigned i = 0; i < IG->getFactor(); i++)
9140       if (Instruction *Member = IG->getMember(i))
9141         RecipeBuilder.recordRecipeOf(Member);
9142   };
9143 
9144   // ---------------------------------------------------------------------------
9145   // Build initial VPlan: Scan the body of the loop in a topological order to
9146   // visit each basic block after having visited its predecessor basic blocks.
9147   // ---------------------------------------------------------------------------
9148 
9149   // Create a dummy pre-entry VPBasicBlock to start building the VPlan.
9150   auto Plan = std::make_unique<VPlan>();
9151   VPBasicBlock *VPBB = new VPBasicBlock("Pre-Entry");
9152   Plan->setEntry(VPBB);
9153 
9154   // Scan the body of the loop in a topological order to visit each basic block
9155   // after having visited its predecessor basic blocks.
9156   LoopBlocksDFS DFS(OrigLoop);
9157   DFS.perform(LI);
9158 
9159   for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) {
9160     // Relevant instructions from basic block BB will be grouped into VPRecipe
9161     // ingredients and fill a new VPBasicBlock.
9162     unsigned VPBBsForBB = 0;
9163     auto *FirstVPBBForBB = new VPBasicBlock(BB->getName());
9164     VPBlockUtils::insertBlockAfter(FirstVPBBForBB, VPBB);
9165     VPBB = FirstVPBBForBB;
9166     Builder.setInsertPoint(VPBB);
9167 
9168     // Introduce each ingredient into VPlan.
9169     // TODO: Model and preserve debug instrinsics in VPlan.
9170     for (Instruction &I : BB->instructionsWithoutDebug()) {
9171       Instruction *Instr = &I;
9172 
9173       // First filter out irrelevant instructions, to ensure no recipes are
9174       // built for them.
9175       if (isa<BranchInst>(Instr) || DeadInstructions.count(Instr))
9176         continue;
9177 
9178       SmallVector<VPValue *, 4> Operands;
9179       auto *Phi = dyn_cast<PHINode>(Instr);
9180       if (Phi && Phi->getParent() == OrigLoop->getHeader()) {
9181         Operands.push_back(Plan->getOrAddVPValue(
9182             Phi->getIncomingValueForBlock(OrigLoop->getLoopPreheader())));
9183       } else {
9184         auto OpRange = Plan->mapToVPValues(Instr->operands());
9185         Operands = {OpRange.begin(), OpRange.end()};
9186       }
9187       if (auto RecipeOrValue = RecipeBuilder.tryToCreateWidenRecipe(
9188               Instr, Operands, Range, Plan)) {
9189         // If Instr can be simplified to an existing VPValue, use it.
9190         if (RecipeOrValue.is<VPValue *>()) {
9191           auto *VPV = RecipeOrValue.get<VPValue *>();
9192           Plan->addVPValue(Instr, VPV);
9193           // If the re-used value is a recipe, register the recipe for the
9194           // instruction, in case the recipe for Instr needs to be recorded.
9195           if (auto *R = dyn_cast_or_null<VPRecipeBase>(VPV->getDef()))
9196             RecipeBuilder.setRecipe(Instr, R);
9197           continue;
9198         }
9199         // Otherwise, add the new recipe.
9200         VPRecipeBase *Recipe = RecipeOrValue.get<VPRecipeBase *>();
9201         for (auto *Def : Recipe->definedValues()) {
9202           auto *UV = Def->getUnderlyingValue();
9203           Plan->addVPValue(UV, Def);
9204         }
9205 
9206         RecipeBuilder.setRecipe(Instr, Recipe);
9207         VPBB->appendRecipe(Recipe);
9208         continue;
9209       }
9210 
9211       // Otherwise, if all widening options failed, Instruction is to be
9212       // replicated. This may create a successor for VPBB.
9213       VPBasicBlock *NextVPBB =
9214           RecipeBuilder.handleReplication(Instr, Range, VPBB, Plan);
9215       if (NextVPBB != VPBB) {
9216         VPBB = NextVPBB;
9217         VPBB->setName(BB->hasName() ? BB->getName() + "." + Twine(VPBBsForBB++)
9218                                     : "");
9219       }
9220     }
9221   }
9222 
9223   RecipeBuilder.fixHeaderPhis();
9224 
9225   // Discard empty dummy pre-entry VPBasicBlock. Note that other VPBasicBlocks
9226   // may also be empty, such as the last one VPBB, reflecting original
9227   // basic-blocks with no recipes.
9228   VPBasicBlock *PreEntry = cast<VPBasicBlock>(Plan->getEntry());
9229   assert(PreEntry->empty() && "Expecting empty pre-entry block.");
9230   VPBlockBase *Entry = Plan->setEntry(PreEntry->getSingleSuccessor());
9231   VPBlockUtils::disconnectBlocks(PreEntry, Entry);
9232   delete PreEntry;
9233 
9234   // ---------------------------------------------------------------------------
9235   // Transform initial VPlan: Apply previously taken decisions, in order, to
9236   // bring the VPlan to its final state.
9237   // ---------------------------------------------------------------------------
9238 
9239   // Apply Sink-After legal constraints.
9240   for (auto &Entry : SinkAfter) {
9241     VPRecipeBase *Sink = RecipeBuilder.getRecipe(Entry.first);
9242     VPRecipeBase *Target = RecipeBuilder.getRecipe(Entry.second);
9243 
9244     auto GetReplicateRegion = [](VPRecipeBase *R) -> VPRegionBlock * {
9245       auto *Region =
9246           dyn_cast_or_null<VPRegionBlock>(R->getParent()->getParent());
9247       if (Region && Region->isReplicator()) {
9248         assert(Region->getNumSuccessors() == 1 &&
9249                Region->getNumPredecessors() == 1 && "Expected SESE region!");
9250         assert(R->getParent()->size() == 1 &&
9251                "A recipe in an original replicator region must be the only "
9252                "recipe in its block");
9253         return Region;
9254       }
9255       return nullptr;
9256     };
9257     auto *TargetRegion = GetReplicateRegion(Target);
9258     auto *SinkRegion = GetReplicateRegion(Sink);
9259     if (!SinkRegion) {
9260       // If the sink source is not a replicate region, sink the recipe directly.
9261       if (TargetRegion) {
9262         // The target is in a replication region, make sure to move Sink to
9263         // the block after it, not into the replication region itself.
9264         VPBasicBlock *NextBlock =
9265             cast<VPBasicBlock>(TargetRegion->getSuccessors().front());
9266         Sink->moveBefore(*NextBlock, NextBlock->getFirstNonPhi());
9267       } else
9268         Sink->moveAfter(Target);
9269       continue;
9270     }
9271 
9272     // The sink source is in a replicate region. Unhook the region from the CFG.
9273     auto *SinkPred = SinkRegion->getSinglePredecessor();
9274     auto *SinkSucc = SinkRegion->getSingleSuccessor();
9275     VPBlockUtils::disconnectBlocks(SinkPred, SinkRegion);
9276     VPBlockUtils::disconnectBlocks(SinkRegion, SinkSucc);
9277     VPBlockUtils::connectBlocks(SinkPred, SinkSucc);
9278 
9279     if (TargetRegion) {
9280       // The target recipe is also in a replicate region, move the sink region
9281       // after the target region.
9282       auto *TargetSucc = TargetRegion->getSingleSuccessor();
9283       VPBlockUtils::disconnectBlocks(TargetRegion, TargetSucc);
9284       VPBlockUtils::connectBlocks(TargetRegion, SinkRegion);
9285       VPBlockUtils::connectBlocks(SinkRegion, TargetSucc);
9286     } else {
9287       // The sink source is in a replicate region, we need to move the whole
9288       // replicate region, which should only contain a single recipe in the main
9289       // block.
9290       auto *SplitBlock =
9291           Target->getParent()->splitAt(std::next(Target->getIterator()));
9292 
9293       auto *SplitPred = SplitBlock->getSinglePredecessor();
9294 
9295       VPBlockUtils::disconnectBlocks(SplitPred, SplitBlock);
9296       VPBlockUtils::connectBlocks(SplitPred, SinkRegion);
9297       VPBlockUtils::connectBlocks(SinkRegion, SplitBlock);
9298       if (VPBB == SplitPred)
9299         VPBB = SplitBlock;
9300     }
9301   }
9302 
9303   // Interleave memory: for each Interleave Group we marked earlier as relevant
9304   // for this VPlan, replace the Recipes widening its memory instructions with a
9305   // single VPInterleaveRecipe at its insertion point.
9306   for (auto IG : InterleaveGroups) {
9307     auto *Recipe = cast<VPWidenMemoryInstructionRecipe>(
9308         RecipeBuilder.getRecipe(IG->getInsertPos()));
9309     SmallVector<VPValue *, 4> StoredValues;
9310     for (unsigned i = 0; i < IG->getFactor(); ++i)
9311       if (auto *SI = dyn_cast_or_null<StoreInst>(IG->getMember(i)))
9312         StoredValues.push_back(Plan->getOrAddVPValue(SI->getOperand(0)));
9313 
9314     auto *VPIG = new VPInterleaveRecipe(IG, Recipe->getAddr(), StoredValues,
9315                                         Recipe->getMask());
9316     VPIG->insertBefore(Recipe);
9317     unsigned J = 0;
9318     for (unsigned i = 0; i < IG->getFactor(); ++i)
9319       if (Instruction *Member = IG->getMember(i)) {
9320         if (!Member->getType()->isVoidTy()) {
9321           VPValue *OriginalV = Plan->getVPValue(Member);
9322           Plan->removeVPValueFor(Member);
9323           Plan->addVPValue(Member, VPIG->getVPValue(J));
9324           OriginalV->replaceAllUsesWith(VPIG->getVPValue(J));
9325           J++;
9326         }
9327         RecipeBuilder.getRecipe(Member)->eraseFromParent();
9328       }
9329   }
9330 
9331   // Adjust the recipes for any inloop reductions.
9332   adjustRecipesForInLoopReductions(Plan, RecipeBuilder, Range.Start);
9333 
9334   // Finally, if tail is folded by masking, introduce selects between the phi
9335   // and the live-out instruction of each reduction, at the end of the latch.
9336   if (CM.foldTailByMasking() && !Legal->getReductionVars().empty()) {
9337     Builder.setInsertPoint(VPBB);
9338     auto *Cond = RecipeBuilder.createBlockInMask(OrigLoop->getHeader(), Plan);
9339     for (auto &Reduction : Legal->getReductionVars()) {
9340       if (CM.isInLoopReduction(Reduction.first))
9341         continue;
9342       VPValue *Phi = Plan->getOrAddVPValue(Reduction.first);
9343       VPValue *Red = Plan->getOrAddVPValue(Reduction.second.getLoopExitInstr());
9344       Builder.createNaryOp(Instruction::Select, {Cond, Red, Phi});
9345     }
9346   }
9347 
9348   VPlanTransforms::sinkScalarOperands(*Plan);
9349   VPlanTransforms::mergeReplicateRegions(*Plan);
9350 
9351   std::string PlanName;
9352   raw_string_ostream RSO(PlanName);
9353   ElementCount VF = Range.Start;
9354   Plan->addVF(VF);
9355   RSO << "Initial VPlan for VF={" << VF;
9356   for (VF *= 2; ElementCount::isKnownLT(VF, Range.End); VF *= 2) {
9357     Plan->addVF(VF);
9358     RSO << "," << VF;
9359   }
9360   RSO << "},UF>=1";
9361   RSO.flush();
9362   Plan->setName(PlanName);
9363 
9364   return Plan;
9365 }
9366 
9367 VPlanPtr LoopVectorizationPlanner::buildVPlan(VFRange &Range) {
9368   // Outer loop handling: They may require CFG and instruction level
9369   // transformations before even evaluating whether vectorization is profitable.
9370   // Since we cannot modify the incoming IR, we need to build VPlan upfront in
9371   // the vectorization pipeline.
9372   assert(!OrigLoop->isInnermost());
9373   assert(EnableVPlanNativePath && "VPlan-native path is not enabled.");
9374 
9375   // Create new empty VPlan
9376   auto Plan = std::make_unique<VPlan>();
9377 
9378   // Build hierarchical CFG
9379   VPlanHCFGBuilder HCFGBuilder(OrigLoop, LI, *Plan);
9380   HCFGBuilder.buildHierarchicalCFG();
9381 
9382   for (ElementCount VF = Range.Start; ElementCount::isKnownLT(VF, Range.End);
9383        VF *= 2)
9384     Plan->addVF(VF);
9385 
9386   if (EnableVPlanPredication) {
9387     VPlanPredicator VPP(*Plan);
9388     VPP.predicate();
9389 
9390     // Avoid running transformation to recipes until masked code generation in
9391     // VPlan-native path is in place.
9392     return Plan;
9393   }
9394 
9395   SmallPtrSet<Instruction *, 1> DeadInstructions;
9396   VPlanTransforms::VPInstructionsToVPRecipes(OrigLoop, Plan,
9397                                              Legal->getInductionVars(),
9398                                              DeadInstructions, *PSE.getSE());
9399   return Plan;
9400 }
9401 
9402 // Adjust the recipes for any inloop reductions. The chain of instructions
9403 // leading from the loop exit instr to the phi need to be converted to
9404 // reductions, with one operand being vector and the other being the scalar
9405 // reduction chain.
9406 void LoopVectorizationPlanner::adjustRecipesForInLoopReductions(
9407     VPlanPtr &Plan, VPRecipeBuilder &RecipeBuilder, ElementCount MinVF) {
9408   for (auto &Reduction : CM.getInLoopReductionChains()) {
9409     PHINode *Phi = Reduction.first;
9410     RecurrenceDescriptor &RdxDesc = Legal->getReductionVars()[Phi];
9411     const SmallVector<Instruction *, 4> &ReductionOperations = Reduction.second;
9412 
9413     if (MinVF.isScalar() && !CM.useOrderedReductions(RdxDesc))
9414       continue;
9415 
9416     // ReductionOperations are orders top-down from the phi's use to the
9417     // LoopExitValue. We keep a track of the previous item (the Chain) to tell
9418     // which of the two operands will remain scalar and which will be reduced.
9419     // For minmax the chain will be the select instructions.
9420     Instruction *Chain = Phi;
9421     for (Instruction *R : ReductionOperations) {
9422       VPRecipeBase *WidenRecipe = RecipeBuilder.getRecipe(R);
9423       RecurKind Kind = RdxDesc.getRecurrenceKind();
9424 
9425       VPValue *ChainOp = Plan->getVPValue(Chain);
9426       unsigned FirstOpId;
9427       if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind)) {
9428         assert(isa<VPWidenSelectRecipe>(WidenRecipe) &&
9429                "Expected to replace a VPWidenSelectSC");
9430         FirstOpId = 1;
9431       } else {
9432         assert((MinVF.isScalar() || isa<VPWidenRecipe>(WidenRecipe)) &&
9433                "Expected to replace a VPWidenSC");
9434         FirstOpId = 0;
9435       }
9436       unsigned VecOpId =
9437           R->getOperand(FirstOpId) == Chain ? FirstOpId + 1 : FirstOpId;
9438       VPValue *VecOp = Plan->getVPValue(R->getOperand(VecOpId));
9439 
9440       auto *CondOp = CM.foldTailByMasking()
9441                          ? RecipeBuilder.createBlockInMask(R->getParent(), Plan)
9442                          : nullptr;
9443       VPReductionRecipe *RedRecipe = new VPReductionRecipe(
9444           &RdxDesc, R, ChainOp, VecOp, CondOp, TTI);
9445       WidenRecipe->getVPSingleValue()->replaceAllUsesWith(RedRecipe);
9446       Plan->removeVPValueFor(R);
9447       Plan->addVPValue(R, RedRecipe);
9448       WidenRecipe->getParent()->insert(RedRecipe, WidenRecipe->getIterator());
9449       WidenRecipe->getVPSingleValue()->replaceAllUsesWith(RedRecipe);
9450       WidenRecipe->eraseFromParent();
9451 
9452       if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind)) {
9453         VPRecipeBase *CompareRecipe =
9454             RecipeBuilder.getRecipe(cast<Instruction>(R->getOperand(0)));
9455         assert(isa<VPWidenRecipe>(CompareRecipe) &&
9456                "Expected to replace a VPWidenSC");
9457         assert(cast<VPWidenRecipe>(CompareRecipe)->getNumUsers() == 0 &&
9458                "Expected no remaining users");
9459         CompareRecipe->eraseFromParent();
9460       }
9461       Chain = R;
9462     }
9463   }
9464 }
9465 
9466 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
9467 void VPInterleaveRecipe::print(raw_ostream &O, const Twine &Indent,
9468                                VPSlotTracker &SlotTracker) const {
9469   O << Indent << "INTERLEAVE-GROUP with factor " << IG->getFactor() << " at ";
9470   IG->getInsertPos()->printAsOperand(O, false);
9471   O << ", ";
9472   getAddr()->printAsOperand(O, SlotTracker);
9473   VPValue *Mask = getMask();
9474   if (Mask) {
9475     O << ", ";
9476     Mask->printAsOperand(O, SlotTracker);
9477   }
9478   for (unsigned i = 0; i < IG->getFactor(); ++i)
9479     if (Instruction *I = IG->getMember(i))
9480       O << "\n" << Indent << "  " << VPlanIngredient(I) << " " << i;
9481 }
9482 #endif
9483 
9484 void VPWidenCallRecipe::execute(VPTransformState &State) {
9485   State.ILV->widenCallInstruction(*cast<CallInst>(getUnderlyingInstr()), this,
9486                                   *this, State);
9487 }
9488 
9489 void VPWidenSelectRecipe::execute(VPTransformState &State) {
9490   State.ILV->widenSelectInstruction(*cast<SelectInst>(getUnderlyingInstr()),
9491                                     this, *this, InvariantCond, State);
9492 }
9493 
9494 void VPWidenRecipe::execute(VPTransformState &State) {
9495   State.ILV->widenInstruction(*getUnderlyingInstr(), this, *this, State);
9496 }
9497 
9498 void VPWidenGEPRecipe::execute(VPTransformState &State) {
9499   State.ILV->widenGEP(cast<GetElementPtrInst>(getUnderlyingInstr()), this,
9500                       *this, State.UF, State.VF, IsPtrLoopInvariant,
9501                       IsIndexLoopInvariant, State);
9502 }
9503 
9504 void VPWidenIntOrFpInductionRecipe::execute(VPTransformState &State) {
9505   assert(!State.Instance && "Int or FP induction being replicated.");
9506   State.ILV->widenIntOrFpInduction(IV, getStartValue()->getLiveInIRValue(),
9507                                    getTruncInst(), getVPValue(0),
9508                                    getCastValue(), State);
9509 }
9510 
9511 void VPWidenPHIRecipe::execute(VPTransformState &State) {
9512   State.ILV->widenPHIInstruction(cast<PHINode>(getUnderlyingValue()), this,
9513                                  State);
9514 }
9515 
9516 void VPBlendRecipe::execute(VPTransformState &State) {
9517   State.ILV->setDebugLocFromInst(Phi, &State.Builder);
9518   // We know that all PHIs in non-header blocks are converted into
9519   // selects, so we don't have to worry about the insertion order and we
9520   // can just use the builder.
9521   // At this point we generate the predication tree. There may be
9522   // duplications since this is a simple recursive scan, but future
9523   // optimizations will clean it up.
9524 
9525   unsigned NumIncoming = getNumIncomingValues();
9526 
9527   // Generate a sequence of selects of the form:
9528   // SELECT(Mask3, In3,
9529   //        SELECT(Mask2, In2,
9530   //               SELECT(Mask1, In1,
9531   //                      In0)))
9532   // Note that Mask0 is never used: lanes for which no path reaches this phi and
9533   // are essentially undef are taken from In0.
9534   InnerLoopVectorizer::VectorParts Entry(State.UF);
9535   for (unsigned In = 0; In < NumIncoming; ++In) {
9536     for (unsigned Part = 0; Part < State.UF; ++Part) {
9537       // We might have single edge PHIs (blocks) - use an identity
9538       // 'select' for the first PHI operand.
9539       Value *In0 = State.get(getIncomingValue(In), Part);
9540       if (In == 0)
9541         Entry[Part] = In0; // Initialize with the first incoming value.
9542       else {
9543         // Select between the current value and the previous incoming edge
9544         // based on the incoming mask.
9545         Value *Cond = State.get(getMask(In), Part);
9546         Entry[Part] =
9547             State.Builder.CreateSelect(Cond, In0, Entry[Part], "predphi");
9548       }
9549     }
9550   }
9551   for (unsigned Part = 0; Part < State.UF; ++Part)
9552     State.set(this, Entry[Part], Part);
9553 }
9554 
9555 void VPInterleaveRecipe::execute(VPTransformState &State) {
9556   assert(!State.Instance && "Interleave group being replicated.");
9557   State.ILV->vectorizeInterleaveGroup(IG, definedValues(), State, getAddr(),
9558                                       getStoredValues(), getMask());
9559 }
9560 
9561 void VPReductionRecipe::execute(VPTransformState &State) {
9562   assert(!State.Instance && "Reduction being replicated.");
9563   Value *PrevInChain = State.get(getChainOp(), 0);
9564   for (unsigned Part = 0; Part < State.UF; ++Part) {
9565     RecurKind Kind = RdxDesc->getRecurrenceKind();
9566     bool IsOrdered = State.ILV->useOrderedReductions(*RdxDesc);
9567     Value *NewVecOp = State.get(getVecOp(), Part);
9568     if (VPValue *Cond = getCondOp()) {
9569       Value *NewCond = State.get(Cond, Part);
9570       VectorType *VecTy = cast<VectorType>(NewVecOp->getType());
9571       Constant *Iden = RecurrenceDescriptor::getRecurrenceIdentity(
9572           Kind, VecTy->getElementType(), RdxDesc->getFastMathFlags());
9573       Constant *IdenVec =
9574           ConstantVector::getSplat(VecTy->getElementCount(), Iden);
9575       Value *Select = State.Builder.CreateSelect(NewCond, NewVecOp, IdenVec);
9576       NewVecOp = Select;
9577     }
9578     Value *NewRed;
9579     Value *NextInChain;
9580     if (IsOrdered) {
9581       if (State.VF.isVector())
9582         NewRed = createOrderedReduction(State.Builder, *RdxDesc, NewVecOp,
9583                                         PrevInChain);
9584       else
9585         NewRed = State.Builder.CreateBinOp(
9586             (Instruction::BinaryOps)getUnderlyingInstr()->getOpcode(),
9587             PrevInChain, NewVecOp);
9588       PrevInChain = NewRed;
9589     } else {
9590       PrevInChain = State.get(getChainOp(), Part);
9591       NewRed = createTargetReduction(State.Builder, TTI, *RdxDesc, NewVecOp);
9592     }
9593     if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind)) {
9594       NextInChain =
9595           createMinMaxOp(State.Builder, RdxDesc->getRecurrenceKind(),
9596                          NewRed, PrevInChain);
9597     } else if (IsOrdered)
9598       NextInChain = NewRed;
9599     else {
9600       NextInChain = State.Builder.CreateBinOp(
9601           (Instruction::BinaryOps)getUnderlyingInstr()->getOpcode(), NewRed,
9602           PrevInChain);
9603     }
9604     State.set(this, NextInChain, Part);
9605   }
9606 }
9607 
9608 void VPReplicateRecipe::execute(VPTransformState &State) {
9609   if (State.Instance) { // Generate a single instance.
9610     assert(!State.VF.isScalable() && "Can't scalarize a scalable vector");
9611     State.ILV->scalarizeInstruction(getUnderlyingInstr(), this, *this,
9612                                     *State.Instance, IsPredicated, State);
9613     // Insert scalar instance packing it into a vector.
9614     if (AlsoPack && State.VF.isVector()) {
9615       // If we're constructing lane 0, initialize to start from poison.
9616       if (State.Instance->Lane.isFirstLane()) {
9617         assert(!State.VF.isScalable() && "VF is assumed to be non scalable.");
9618         Value *Poison = PoisonValue::get(
9619             VectorType::get(getUnderlyingValue()->getType(), State.VF));
9620         State.set(this, Poison, State.Instance->Part);
9621       }
9622       State.ILV->packScalarIntoVectorValue(this, *State.Instance, State);
9623     }
9624     return;
9625   }
9626 
9627   // Generate scalar instances for all VF lanes of all UF parts, unless the
9628   // instruction is uniform inwhich case generate only the first lane for each
9629   // of the UF parts.
9630   unsigned EndLane = IsUniform ? 1 : State.VF.getKnownMinValue();
9631   assert((!State.VF.isScalable() || IsUniform) &&
9632          "Can't scalarize a scalable vector");
9633   for (unsigned Part = 0; Part < State.UF; ++Part)
9634     for (unsigned Lane = 0; Lane < EndLane; ++Lane)
9635       State.ILV->scalarizeInstruction(getUnderlyingInstr(), this, *this,
9636                                       VPIteration(Part, Lane), IsPredicated,
9637                                       State);
9638 }
9639 
9640 void VPBranchOnMaskRecipe::execute(VPTransformState &State) {
9641   assert(State.Instance && "Branch on Mask works only on single instance.");
9642 
9643   unsigned Part = State.Instance->Part;
9644   unsigned Lane = State.Instance->Lane.getKnownLane();
9645 
9646   Value *ConditionBit = nullptr;
9647   VPValue *BlockInMask = getMask();
9648   if (BlockInMask) {
9649     ConditionBit = State.get(BlockInMask, Part);
9650     if (ConditionBit->getType()->isVectorTy())
9651       ConditionBit = State.Builder.CreateExtractElement(
9652           ConditionBit, State.Builder.getInt32(Lane));
9653   } else // Block in mask is all-one.
9654     ConditionBit = State.Builder.getTrue();
9655 
9656   // Replace the temporary unreachable terminator with a new conditional branch,
9657   // whose two destinations will be set later when they are created.
9658   auto *CurrentTerminator = State.CFG.PrevBB->getTerminator();
9659   assert(isa<UnreachableInst>(CurrentTerminator) &&
9660          "Expected to replace unreachable terminator with conditional branch.");
9661   auto *CondBr = BranchInst::Create(State.CFG.PrevBB, nullptr, ConditionBit);
9662   CondBr->setSuccessor(0, nullptr);
9663   ReplaceInstWithInst(CurrentTerminator, CondBr);
9664 }
9665 
9666 void VPPredInstPHIRecipe::execute(VPTransformState &State) {
9667   assert(State.Instance && "Predicated instruction PHI works per instance.");
9668   Instruction *ScalarPredInst =
9669       cast<Instruction>(State.get(getOperand(0), *State.Instance));
9670   BasicBlock *PredicatedBB = ScalarPredInst->getParent();
9671   BasicBlock *PredicatingBB = PredicatedBB->getSinglePredecessor();
9672   assert(PredicatingBB && "Predicated block has no single predecessor.");
9673   assert(isa<VPReplicateRecipe>(getOperand(0)) &&
9674          "operand must be VPReplicateRecipe");
9675 
9676   // By current pack/unpack logic we need to generate only a single phi node: if
9677   // a vector value for the predicated instruction exists at this point it means
9678   // the instruction has vector users only, and a phi for the vector value is
9679   // needed. In this case the recipe of the predicated instruction is marked to
9680   // also do that packing, thereby "hoisting" the insert-element sequence.
9681   // Otherwise, a phi node for the scalar value is needed.
9682   unsigned Part = State.Instance->Part;
9683   if (State.hasVectorValue(getOperand(0), Part)) {
9684     Value *VectorValue = State.get(getOperand(0), Part);
9685     InsertElementInst *IEI = cast<InsertElementInst>(VectorValue);
9686     PHINode *VPhi = State.Builder.CreatePHI(IEI->getType(), 2);
9687     VPhi->addIncoming(IEI->getOperand(0), PredicatingBB); // Unmodified vector.
9688     VPhi->addIncoming(IEI, PredicatedBB); // New vector with inserted element.
9689     if (State.hasVectorValue(this, Part))
9690       State.reset(this, VPhi, Part);
9691     else
9692       State.set(this, VPhi, Part);
9693     // NOTE: Currently we need to update the value of the operand, so the next
9694     // predicated iteration inserts its generated value in the correct vector.
9695     State.reset(getOperand(0), VPhi, Part);
9696   } else {
9697     Type *PredInstType = getOperand(0)->getUnderlyingValue()->getType();
9698     PHINode *Phi = State.Builder.CreatePHI(PredInstType, 2);
9699     Phi->addIncoming(PoisonValue::get(ScalarPredInst->getType()),
9700                      PredicatingBB);
9701     Phi->addIncoming(ScalarPredInst, PredicatedBB);
9702     if (State.hasScalarValue(this, *State.Instance))
9703       State.reset(this, Phi, *State.Instance);
9704     else
9705       State.set(this, Phi, *State.Instance);
9706     // NOTE: Currently we need to update the value of the operand, so the next
9707     // predicated iteration inserts its generated value in the correct vector.
9708     State.reset(getOperand(0), Phi, *State.Instance);
9709   }
9710 }
9711 
9712 void VPWidenMemoryInstructionRecipe::execute(VPTransformState &State) {
9713   VPValue *StoredValue = isStore() ? getStoredValue() : nullptr;
9714   State.ILV->vectorizeMemoryInstruction(
9715       &Ingredient, State, StoredValue ? nullptr : getVPSingleValue(), getAddr(),
9716       StoredValue, getMask());
9717 }
9718 
9719 // Determine how to lower the scalar epilogue, which depends on 1) optimising
9720 // for minimum code-size, 2) predicate compiler options, 3) loop hints forcing
9721 // predication, and 4) a TTI hook that analyses whether the loop is suitable
9722 // for predication.
9723 static ScalarEpilogueLowering getScalarEpilogueLowering(
9724     Function *F, Loop *L, LoopVectorizeHints &Hints, ProfileSummaryInfo *PSI,
9725     BlockFrequencyInfo *BFI, TargetTransformInfo *TTI, TargetLibraryInfo *TLI,
9726     AssumptionCache *AC, LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT,
9727     LoopVectorizationLegality &LVL) {
9728   // 1) OptSize takes precedence over all other options, i.e. if this is set,
9729   // don't look at hints or options, and don't request a scalar epilogue.
9730   // (For PGSO, as shouldOptimizeForSize isn't currently accessible from
9731   // LoopAccessInfo (due to code dependency and not being able to reliably get
9732   // PSI/BFI from a loop analysis under NPM), we cannot suppress the collection
9733   // of strides in LoopAccessInfo::analyzeLoop() and vectorize without
9734   // versioning when the vectorization is forced, unlike hasOptSize. So revert
9735   // back to the old way and vectorize with versioning when forced. See D81345.)
9736   if (F->hasOptSize() || (llvm::shouldOptimizeForSize(L->getHeader(), PSI, BFI,
9737                                                       PGSOQueryType::IRPass) &&
9738                           Hints.getForce() != LoopVectorizeHints::FK_Enabled))
9739     return CM_ScalarEpilogueNotAllowedOptSize;
9740 
9741   // 2) If set, obey the directives
9742   if (PreferPredicateOverEpilogue.getNumOccurrences()) {
9743     switch (PreferPredicateOverEpilogue) {
9744     case PreferPredicateTy::ScalarEpilogue:
9745       return CM_ScalarEpilogueAllowed;
9746     case PreferPredicateTy::PredicateElseScalarEpilogue:
9747       return CM_ScalarEpilogueNotNeededUsePredicate;
9748     case PreferPredicateTy::PredicateOrDontVectorize:
9749       return CM_ScalarEpilogueNotAllowedUsePredicate;
9750     };
9751   }
9752 
9753   // 3) If set, obey the hints
9754   switch (Hints.getPredicate()) {
9755   case LoopVectorizeHints::FK_Enabled:
9756     return CM_ScalarEpilogueNotNeededUsePredicate;
9757   case LoopVectorizeHints::FK_Disabled:
9758     return CM_ScalarEpilogueAllowed;
9759   };
9760 
9761   // 4) if the TTI hook indicates this is profitable, request predication.
9762   if (TTI->preferPredicateOverEpilogue(L, LI, *SE, *AC, TLI, DT,
9763                                        LVL.getLAI()))
9764     return CM_ScalarEpilogueNotNeededUsePredicate;
9765 
9766   return CM_ScalarEpilogueAllowed;
9767 }
9768 
9769 Value *VPTransformState::get(VPValue *Def, unsigned Part) {
9770   // If Values have been set for this Def return the one relevant for \p Part.
9771   if (hasVectorValue(Def, Part))
9772     return Data.PerPartOutput[Def][Part];
9773 
9774   if (!hasScalarValue(Def, {Part, 0})) {
9775     Value *IRV = Def->getLiveInIRValue();
9776     Value *B = ILV->getBroadcastInstrs(IRV);
9777     set(Def, B, Part);
9778     return B;
9779   }
9780 
9781   Value *ScalarValue = get(Def, {Part, 0});
9782   // If we aren't vectorizing, we can just copy the scalar map values over
9783   // to the vector map.
9784   if (VF.isScalar()) {
9785     set(Def, ScalarValue, Part);
9786     return ScalarValue;
9787   }
9788 
9789   auto *RepR = dyn_cast<VPReplicateRecipe>(Def);
9790   bool IsUniform = RepR && RepR->isUniform();
9791 
9792   unsigned LastLane = IsUniform ? 0 : VF.getKnownMinValue() - 1;
9793   // Check if there is a scalar value for the selected lane.
9794   if (!hasScalarValue(Def, {Part, LastLane})) {
9795     // At the moment, VPWidenIntOrFpInductionRecipes can also be uniform.
9796     assert(isa<VPWidenIntOrFpInductionRecipe>(Def->getDef()) &&
9797            "unexpected recipe found to be invariant");
9798     IsUniform = true;
9799     LastLane = 0;
9800   }
9801 
9802   auto *LastInst = cast<Instruction>(get(Def, {Part, LastLane}));
9803   // Set the insert point after the last scalarized instruction or after the
9804   // last PHI, if LastInst is a PHI. This ensures the insertelement sequence
9805   // will directly follow the scalar definitions.
9806   auto OldIP = Builder.saveIP();
9807   auto NewIP =
9808       isa<PHINode>(LastInst)
9809           ? BasicBlock::iterator(LastInst->getParent()->getFirstNonPHI())
9810           : std::next(BasicBlock::iterator(LastInst));
9811   Builder.SetInsertPoint(&*NewIP);
9812 
9813   // However, if we are vectorizing, we need to construct the vector values.
9814   // If the value is known to be uniform after vectorization, we can just
9815   // broadcast the scalar value corresponding to lane zero for each unroll
9816   // iteration. Otherwise, we construct the vector values using
9817   // insertelement instructions. Since the resulting vectors are stored in
9818   // State, we will only generate the insertelements once.
9819   Value *VectorValue = nullptr;
9820   if (IsUniform) {
9821     VectorValue = ILV->getBroadcastInstrs(ScalarValue);
9822     set(Def, VectorValue, Part);
9823   } else {
9824     // Initialize packing with insertelements to start from undef.
9825     assert(!VF.isScalable() && "VF is assumed to be non scalable.");
9826     Value *Undef = PoisonValue::get(VectorType::get(LastInst->getType(), VF));
9827     set(Def, Undef, Part);
9828     for (unsigned Lane = 0; Lane < VF.getKnownMinValue(); ++Lane)
9829       ILV->packScalarIntoVectorValue(Def, {Part, Lane}, *this);
9830     VectorValue = get(Def, Part);
9831   }
9832   Builder.restoreIP(OldIP);
9833   return VectorValue;
9834 }
9835 
9836 // Process the loop in the VPlan-native vectorization path. This path builds
9837 // VPlan upfront in the vectorization pipeline, which allows to apply
9838 // VPlan-to-VPlan transformations from the very beginning without modifying the
9839 // input LLVM IR.
9840 static bool processLoopInVPlanNativePath(
9841     Loop *L, PredicatedScalarEvolution &PSE, LoopInfo *LI, DominatorTree *DT,
9842     LoopVectorizationLegality *LVL, TargetTransformInfo *TTI,
9843     TargetLibraryInfo *TLI, DemandedBits *DB, AssumptionCache *AC,
9844     OptimizationRemarkEmitter *ORE, BlockFrequencyInfo *BFI,
9845     ProfileSummaryInfo *PSI, LoopVectorizeHints &Hints,
9846     LoopVectorizationRequirements &Requirements) {
9847 
9848   if (isa<SCEVCouldNotCompute>(PSE.getBackedgeTakenCount())) {
9849     LLVM_DEBUG(dbgs() << "LV: cannot compute the outer-loop trip count\n");
9850     return false;
9851   }
9852   assert(EnableVPlanNativePath && "VPlan-native path is disabled.");
9853   Function *F = L->getHeader()->getParent();
9854   InterleavedAccessInfo IAI(PSE, L, DT, LI, LVL->getLAI());
9855 
9856   ScalarEpilogueLowering SEL = getScalarEpilogueLowering(
9857       F, L, Hints, PSI, BFI, TTI, TLI, AC, LI, PSE.getSE(), DT, *LVL);
9858 
9859   LoopVectorizationCostModel CM(SEL, L, PSE, LI, LVL, *TTI, TLI, DB, AC, ORE, F,
9860                                 &Hints, IAI);
9861   // Use the planner for outer loop vectorization.
9862   // TODO: CM is not used at this point inside the planner. Turn CM into an
9863   // optional argument if we don't need it in the future.
9864   LoopVectorizationPlanner LVP(L, LI, TLI, TTI, LVL, CM, IAI, PSE, Hints,
9865                                Requirements, ORE);
9866 
9867   // Get user vectorization factor.
9868   ElementCount UserVF = Hints.getWidth();
9869 
9870   CM.collectElementTypesForWidening();
9871 
9872   // Plan how to best vectorize, return the best VF and its cost.
9873   const VectorizationFactor VF = LVP.planInVPlanNativePath(UserVF);
9874 
9875   // If we are stress testing VPlan builds, do not attempt to generate vector
9876   // code. Masked vector code generation support will follow soon.
9877   // Also, do not attempt to vectorize if no vector code will be produced.
9878   if (VPlanBuildStressTest || EnableVPlanPredication ||
9879       VectorizationFactor::Disabled() == VF)
9880     return false;
9881 
9882   LVP.setBestPlan(VF.Width, 1);
9883 
9884   {
9885     GeneratedRTChecks Checks(*PSE.getSE(), DT, LI,
9886                              F->getParent()->getDataLayout());
9887     InnerLoopVectorizer LB(L, PSE, LI, DT, TLI, TTI, AC, ORE, VF.Width, 1, LVL,
9888                            &CM, BFI, PSI, Checks);
9889     LLVM_DEBUG(dbgs() << "Vectorizing outer loop in \""
9890                       << L->getHeader()->getParent()->getName() << "\"\n");
9891     LVP.executePlan(LB, DT);
9892   }
9893 
9894   // Mark the loop as already vectorized to avoid vectorizing again.
9895   Hints.setAlreadyVectorized();
9896   assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()));
9897   return true;
9898 }
9899 
9900 // Emit a remark if there are stores to floats that required a floating point
9901 // extension. If the vectorized loop was generated with floating point there
9902 // will be a performance penalty from the conversion overhead and the change in
9903 // the vector width.
9904 static void checkMixedPrecision(Loop *L, OptimizationRemarkEmitter *ORE) {
9905   SmallVector<Instruction *, 4> Worklist;
9906   for (BasicBlock *BB : L->getBlocks()) {
9907     for (Instruction &Inst : *BB) {
9908       if (auto *S = dyn_cast<StoreInst>(&Inst)) {
9909         if (S->getValueOperand()->getType()->isFloatTy())
9910           Worklist.push_back(S);
9911       }
9912     }
9913   }
9914 
9915   // Traverse the floating point stores upwards searching, for floating point
9916   // conversions.
9917   SmallPtrSet<const Instruction *, 4> Visited;
9918   SmallPtrSet<const Instruction *, 4> EmittedRemark;
9919   while (!Worklist.empty()) {
9920     auto *I = Worklist.pop_back_val();
9921     if (!L->contains(I))
9922       continue;
9923     if (!Visited.insert(I).second)
9924       continue;
9925 
9926     // Emit a remark if the floating point store required a floating
9927     // point conversion.
9928     // TODO: More work could be done to identify the root cause such as a
9929     // constant or a function return type and point the user to it.
9930     if (isa<FPExtInst>(I) && EmittedRemark.insert(I).second)
9931       ORE->emit([&]() {
9932         return OptimizationRemarkAnalysis(LV_NAME, "VectorMixedPrecision",
9933                                           I->getDebugLoc(), L->getHeader())
9934                << "floating point conversion changes vector width. "
9935                << "Mixed floating point precision requires an up/down "
9936                << "cast that will negatively impact performance.";
9937       });
9938 
9939     for (Use &Op : I->operands())
9940       if (auto *OpI = dyn_cast<Instruction>(Op))
9941         Worklist.push_back(OpI);
9942   }
9943 }
9944 
9945 LoopVectorizePass::LoopVectorizePass(LoopVectorizeOptions Opts)
9946     : InterleaveOnlyWhenForced(Opts.InterleaveOnlyWhenForced ||
9947                                !EnableLoopInterleaving),
9948       VectorizeOnlyWhenForced(Opts.VectorizeOnlyWhenForced ||
9949                               !EnableLoopVectorization) {}
9950 
9951 bool LoopVectorizePass::processLoop(Loop *L) {
9952   assert((EnableVPlanNativePath || L->isInnermost()) &&
9953          "VPlan-native path is not enabled. Only process inner loops.");
9954 
9955 #ifndef NDEBUG
9956   const std::string DebugLocStr = getDebugLocString(L);
9957 #endif /* NDEBUG */
9958 
9959   LLVM_DEBUG(dbgs() << "\nLV: Checking a loop in \""
9960                     << L->getHeader()->getParent()->getName() << "\" from "
9961                     << DebugLocStr << "\n");
9962 
9963   LoopVectorizeHints Hints(L, InterleaveOnlyWhenForced, *ORE);
9964 
9965   LLVM_DEBUG(
9966       dbgs() << "LV: Loop hints:"
9967              << " force="
9968              << (Hints.getForce() == LoopVectorizeHints::FK_Disabled
9969                      ? "disabled"
9970                      : (Hints.getForce() == LoopVectorizeHints::FK_Enabled
9971                             ? "enabled"
9972                             : "?"))
9973              << " width=" << Hints.getWidth()
9974              << " interleave=" << Hints.getInterleave() << "\n");
9975 
9976   // Function containing loop
9977   Function *F = L->getHeader()->getParent();
9978 
9979   // Looking at the diagnostic output is the only way to determine if a loop
9980   // was vectorized (other than looking at the IR or machine code), so it
9981   // is important to generate an optimization remark for each loop. Most of
9982   // these messages are generated as OptimizationRemarkAnalysis. Remarks
9983   // generated as OptimizationRemark and OptimizationRemarkMissed are
9984   // less verbose reporting vectorized loops and unvectorized loops that may
9985   // benefit from vectorization, respectively.
9986 
9987   if (!Hints.allowVectorization(F, L, VectorizeOnlyWhenForced)) {
9988     LLVM_DEBUG(dbgs() << "LV: Loop hints prevent vectorization.\n");
9989     return false;
9990   }
9991 
9992   PredicatedScalarEvolution PSE(*SE, *L);
9993 
9994   // Check if it is legal to vectorize the loop.
9995   LoopVectorizationRequirements Requirements;
9996   LoopVectorizationLegality LVL(L, PSE, DT, TTI, TLI, AA, F, GetLAA, LI, ORE,
9997                                 &Requirements, &Hints, DB, AC, BFI, PSI);
9998   if (!LVL.canVectorize(EnableVPlanNativePath)) {
9999     LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
10000     Hints.emitRemarkWithHints();
10001     return false;
10002   }
10003 
10004   // Check the function attributes and profiles to find out if this function
10005   // should be optimized for size.
10006   ScalarEpilogueLowering SEL = getScalarEpilogueLowering(
10007       F, L, Hints, PSI, BFI, TTI, TLI, AC, LI, PSE.getSE(), DT, LVL);
10008 
10009   // Entrance to the VPlan-native vectorization path. Outer loops are processed
10010   // here. They may require CFG and instruction level transformations before
10011   // even evaluating whether vectorization is profitable. Since we cannot modify
10012   // the incoming IR, we need to build VPlan upfront in the vectorization
10013   // pipeline.
10014   if (!L->isInnermost())
10015     return processLoopInVPlanNativePath(L, PSE, LI, DT, &LVL, TTI, TLI, DB, AC,
10016                                         ORE, BFI, PSI, Hints, Requirements);
10017 
10018   assert(L->isInnermost() && "Inner loop expected.");
10019 
10020   // Check the loop for a trip count threshold: vectorize loops with a tiny trip
10021   // count by optimizing for size, to minimize overheads.
10022   auto ExpectedTC = getSmallBestKnownTC(*SE, L);
10023   if (ExpectedTC && *ExpectedTC < TinyTripCountVectorThreshold) {
10024     LLVM_DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "
10025                       << "This loop is worth vectorizing only if no scalar "
10026                       << "iteration overheads are incurred.");
10027     if (Hints.getForce() == LoopVectorizeHints::FK_Enabled)
10028       LLVM_DEBUG(dbgs() << " But vectorizing was explicitly forced.\n");
10029     else {
10030       LLVM_DEBUG(dbgs() << "\n");
10031       SEL = CM_ScalarEpilogueNotAllowedLowTripLoop;
10032     }
10033   }
10034 
10035   // Check the function attributes to see if implicit floats are allowed.
10036   // FIXME: This check doesn't seem possibly correct -- what if the loop is
10037   // an integer loop and the vector instructions selected are purely integer
10038   // vector instructions?
10039   if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10040     reportVectorizationFailure(
10041         "Can't vectorize when the NoImplicitFloat attribute is used",
10042         "loop not vectorized due to NoImplicitFloat attribute",
10043         "NoImplicitFloat", ORE, L);
10044     Hints.emitRemarkWithHints();
10045     return false;
10046   }
10047 
10048   // Check if the target supports potentially unsafe FP vectorization.
10049   // FIXME: Add a check for the type of safety issue (denormal, signaling)
10050   // for the target we're vectorizing for, to make sure none of the
10051   // additional fp-math flags can help.
10052   if (Hints.isPotentiallyUnsafe() &&
10053       TTI->isFPVectorizationPotentiallyUnsafe()) {
10054     reportVectorizationFailure(
10055         "Potentially unsafe FP op prevents vectorization",
10056         "loop not vectorized due to unsafe FP support.",
10057         "UnsafeFP", ORE, L);
10058     Hints.emitRemarkWithHints();
10059     return false;
10060   }
10061 
10062   if (!LVL.canVectorizeFPMath(EnableStrictReductions)) {
10063     ORE->emit([&]() {
10064       auto *ExactFPMathInst = Requirements.getExactFPInst();
10065       return OptimizationRemarkAnalysisFPCommute(DEBUG_TYPE, "CantReorderFPOps",
10066                                                  ExactFPMathInst->getDebugLoc(),
10067                                                  ExactFPMathInst->getParent())
10068              << "loop not vectorized: cannot prove it is safe to reorder "
10069                 "floating-point operations";
10070     });
10071     LLVM_DEBUG(dbgs() << "LV: loop not vectorized: cannot prove it is safe to "
10072                          "reorder floating-point operations\n");
10073     Hints.emitRemarkWithHints();
10074     return false;
10075   }
10076 
10077   bool UseInterleaved = TTI->enableInterleavedAccessVectorization();
10078   InterleavedAccessInfo IAI(PSE, L, DT, LI, LVL.getLAI());
10079 
10080   // If an override option has been passed in for interleaved accesses, use it.
10081   if (EnableInterleavedMemAccesses.getNumOccurrences() > 0)
10082     UseInterleaved = EnableInterleavedMemAccesses;
10083 
10084   // Analyze interleaved memory accesses.
10085   if (UseInterleaved) {
10086     IAI.analyzeInterleaving(useMaskedInterleavedAccesses(*TTI));
10087   }
10088 
10089   // Use the cost model.
10090   LoopVectorizationCostModel CM(SEL, L, PSE, LI, &LVL, *TTI, TLI, DB, AC, ORE,
10091                                 F, &Hints, IAI);
10092   CM.collectValuesToIgnore();
10093   CM.collectElementTypesForWidening();
10094 
10095   // Use the planner for vectorization.
10096   LoopVectorizationPlanner LVP(L, LI, TLI, TTI, &LVL, CM, IAI, PSE, Hints,
10097                                Requirements, ORE);
10098 
10099   // Get user vectorization factor and interleave count.
10100   ElementCount UserVF = Hints.getWidth();
10101   unsigned UserIC = Hints.getInterleave();
10102 
10103   // Plan how to best vectorize, return the best VF and its cost.
10104   Optional<VectorizationFactor> MaybeVF = LVP.plan(UserVF, UserIC);
10105 
10106   VectorizationFactor VF = VectorizationFactor::Disabled();
10107   unsigned IC = 1;
10108 
10109   if (MaybeVF) {
10110     VF = *MaybeVF;
10111     // Select the interleave count.
10112     IC = CM.selectInterleaveCount(VF.Width, *VF.Cost.getValue());
10113   }
10114 
10115   // Identify the diagnostic messages that should be produced.
10116   std::pair<StringRef, std::string> VecDiagMsg, IntDiagMsg;
10117   bool VectorizeLoop = true, InterleaveLoop = true;
10118   if (VF.Width.isScalar()) {
10119     LLVM_DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
10120     VecDiagMsg = std::make_pair(
10121         "VectorizationNotBeneficial",
10122         "the cost-model indicates that vectorization is not beneficial");
10123     VectorizeLoop = false;
10124   }
10125 
10126   if (!MaybeVF && UserIC > 1) {
10127     // Tell the user interleaving was avoided up-front, despite being explicitly
10128     // requested.
10129     LLVM_DEBUG(dbgs() << "LV: Ignoring UserIC, because vectorization and "
10130                          "interleaving should be avoided up front\n");
10131     IntDiagMsg = std::make_pair(
10132         "InterleavingAvoided",
10133         "Ignoring UserIC, because interleaving was avoided up front");
10134     InterleaveLoop = false;
10135   } else if (IC == 1 && UserIC <= 1) {
10136     // Tell the user interleaving is not beneficial.
10137     LLVM_DEBUG(dbgs() << "LV: Interleaving is not beneficial.\n");
10138     IntDiagMsg = std::make_pair(
10139         "InterleavingNotBeneficial",
10140         "the cost-model indicates that interleaving is not beneficial");
10141     InterleaveLoop = false;
10142     if (UserIC == 1) {
10143       IntDiagMsg.first = "InterleavingNotBeneficialAndDisabled";
10144       IntDiagMsg.second +=
10145           " and is explicitly disabled or interleave count is set to 1";
10146     }
10147   } else if (IC > 1 && UserIC == 1) {
10148     // Tell the user interleaving is beneficial, but it explicitly disabled.
10149     LLVM_DEBUG(
10150         dbgs() << "LV: Interleaving is beneficial but is explicitly disabled.");
10151     IntDiagMsg = std::make_pair(
10152         "InterleavingBeneficialButDisabled",
10153         "the cost-model indicates that interleaving is beneficial "
10154         "but is explicitly disabled or interleave count is set to 1");
10155     InterleaveLoop = false;
10156   }
10157 
10158   // Override IC if user provided an interleave count.
10159   IC = UserIC > 0 ? UserIC : IC;
10160 
10161   // Emit diagnostic messages, if any.
10162   const char *VAPassName = Hints.vectorizeAnalysisPassName();
10163   if (!VectorizeLoop && !InterleaveLoop) {
10164     // Do not vectorize or interleaving the loop.
10165     ORE->emit([&]() {
10166       return OptimizationRemarkMissed(VAPassName, VecDiagMsg.first,
10167                                       L->getStartLoc(), L->getHeader())
10168              << VecDiagMsg.second;
10169     });
10170     ORE->emit([&]() {
10171       return OptimizationRemarkMissed(LV_NAME, IntDiagMsg.first,
10172                                       L->getStartLoc(), L->getHeader())
10173              << IntDiagMsg.second;
10174     });
10175     return false;
10176   } else if (!VectorizeLoop && InterleaveLoop) {
10177     LLVM_DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
10178     ORE->emit([&]() {
10179       return OptimizationRemarkAnalysis(VAPassName, VecDiagMsg.first,
10180                                         L->getStartLoc(), L->getHeader())
10181              << VecDiagMsg.second;
10182     });
10183   } else if (VectorizeLoop && !InterleaveLoop) {
10184     LLVM_DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width
10185                       << ") in " << DebugLocStr << '\n');
10186     ORE->emit([&]() {
10187       return OptimizationRemarkAnalysis(LV_NAME, IntDiagMsg.first,
10188                                         L->getStartLoc(), L->getHeader())
10189              << IntDiagMsg.second;
10190     });
10191   } else if (VectorizeLoop && InterleaveLoop) {
10192     LLVM_DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width
10193                       << ") in " << DebugLocStr << '\n');
10194     LLVM_DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
10195   }
10196 
10197   bool DisableRuntimeUnroll = false;
10198   MDNode *OrigLoopID = L->getLoopID();
10199   {
10200     // Optimistically generate runtime checks. Drop them if they turn out to not
10201     // be profitable. Limit the scope of Checks, so the cleanup happens
10202     // immediately after vector codegeneration is done.
10203     GeneratedRTChecks Checks(*PSE.getSE(), DT, LI,
10204                              F->getParent()->getDataLayout());
10205     if (!VF.Width.isScalar() || IC > 1)
10206       Checks.Create(L, *LVL.getLAI(), PSE.getUnionPredicate());
10207     LVP.setBestPlan(VF.Width, IC);
10208 
10209     using namespace ore;
10210     if (!VectorizeLoop) {
10211       assert(IC > 1 && "interleave count should not be 1 or 0");
10212       // If we decided that it is not legal to vectorize the loop, then
10213       // interleave it.
10214       InnerLoopUnroller Unroller(L, PSE, LI, DT, TLI, TTI, AC, ORE, IC, &LVL,
10215                                  &CM, BFI, PSI, Checks);
10216       LVP.executePlan(Unroller, DT);
10217 
10218       ORE->emit([&]() {
10219         return OptimizationRemark(LV_NAME, "Interleaved", L->getStartLoc(),
10220                                   L->getHeader())
10221                << "interleaved loop (interleaved count: "
10222                << NV("InterleaveCount", IC) << ")";
10223       });
10224     } else {
10225       // If we decided that it is *legal* to vectorize the loop, then do it.
10226 
10227       // Consider vectorizing the epilogue too if it's profitable.
10228       VectorizationFactor EpilogueVF =
10229           CM.selectEpilogueVectorizationFactor(VF.Width, LVP);
10230       if (EpilogueVF.Width.isVector()) {
10231 
10232         // The first pass vectorizes the main loop and creates a scalar epilogue
10233         // to be vectorized by executing the plan (potentially with a different
10234         // factor) again shortly afterwards.
10235         EpilogueLoopVectorizationInfo EPI(VF.Width.getKnownMinValue(), IC,
10236                                           EpilogueVF.Width.getKnownMinValue(),
10237                                           1);
10238         EpilogueVectorizerMainLoop MainILV(L, PSE, LI, DT, TLI, TTI, AC, ORE,
10239                                            EPI, &LVL, &CM, BFI, PSI, Checks);
10240 
10241         LVP.setBestPlan(EPI.MainLoopVF, EPI.MainLoopUF);
10242         LVP.executePlan(MainILV, DT);
10243         ++LoopsVectorized;
10244 
10245         simplifyLoop(L, DT, LI, SE, AC, nullptr, false /* PreserveLCSSA */);
10246         formLCSSARecursively(*L, *DT, LI, SE);
10247 
10248         // Second pass vectorizes the epilogue and adjusts the control flow
10249         // edges from the first pass.
10250         LVP.setBestPlan(EPI.EpilogueVF, EPI.EpilogueUF);
10251         EPI.MainLoopVF = EPI.EpilogueVF;
10252         EPI.MainLoopUF = EPI.EpilogueUF;
10253         EpilogueVectorizerEpilogueLoop EpilogILV(L, PSE, LI, DT, TLI, TTI, AC,
10254                                                  ORE, EPI, &LVL, &CM, BFI, PSI,
10255                                                  Checks);
10256         LVP.executePlan(EpilogILV, DT);
10257         ++LoopsEpilogueVectorized;
10258 
10259         if (!MainILV.areSafetyChecksAdded())
10260           DisableRuntimeUnroll = true;
10261       } else {
10262         InnerLoopVectorizer LB(L, PSE, LI, DT, TLI, TTI, AC, ORE, VF.Width, IC,
10263                                &LVL, &CM, BFI, PSI, Checks);
10264         LVP.executePlan(LB, DT);
10265         ++LoopsVectorized;
10266 
10267         // Add metadata to disable runtime unrolling a scalar loop when there
10268         // are no runtime checks about strides and memory. A scalar loop that is
10269         // rarely used is not worth unrolling.
10270         if (!LB.areSafetyChecksAdded())
10271           DisableRuntimeUnroll = true;
10272       }
10273       // Report the vectorization decision.
10274       ORE->emit([&]() {
10275         return OptimizationRemark(LV_NAME, "Vectorized", L->getStartLoc(),
10276                                   L->getHeader())
10277                << "vectorized loop (vectorization width: "
10278                << NV("VectorizationFactor", VF.Width)
10279                << ", interleaved count: " << NV("InterleaveCount", IC) << ")";
10280       });
10281     }
10282 
10283     if (ORE->allowExtraAnalysis(LV_NAME))
10284       checkMixedPrecision(L, ORE);
10285   }
10286 
10287   Optional<MDNode *> RemainderLoopID =
10288       makeFollowupLoopID(OrigLoopID, {LLVMLoopVectorizeFollowupAll,
10289                                       LLVMLoopVectorizeFollowupEpilogue});
10290   if (RemainderLoopID.hasValue()) {
10291     L->setLoopID(RemainderLoopID.getValue());
10292   } else {
10293     if (DisableRuntimeUnroll)
10294       AddRuntimeUnrollDisableMetaData(L);
10295 
10296     // Mark the loop as already vectorized to avoid vectorizing again.
10297     Hints.setAlreadyVectorized();
10298   }
10299 
10300   assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()));
10301   return true;
10302 }
10303 
10304 LoopVectorizeResult LoopVectorizePass::runImpl(
10305     Function &F, ScalarEvolution &SE_, LoopInfo &LI_, TargetTransformInfo &TTI_,
10306     DominatorTree &DT_, BlockFrequencyInfo &BFI_, TargetLibraryInfo *TLI_,
10307     DemandedBits &DB_, AAResults &AA_, AssumptionCache &AC_,
10308     std::function<const LoopAccessInfo &(Loop &)> &GetLAA_,
10309     OptimizationRemarkEmitter &ORE_, ProfileSummaryInfo *PSI_) {
10310   SE = &SE_;
10311   LI = &LI_;
10312   TTI = &TTI_;
10313   DT = &DT_;
10314   BFI = &BFI_;
10315   TLI = TLI_;
10316   AA = &AA_;
10317   AC = &AC_;
10318   GetLAA = &GetLAA_;
10319   DB = &DB_;
10320   ORE = &ORE_;
10321   PSI = PSI_;
10322 
10323   // Don't attempt if
10324   // 1. the target claims to have no vector registers, and
10325   // 2. interleaving won't help ILP.
10326   //
10327   // The second condition is necessary because, even if the target has no
10328   // vector registers, loop vectorization may still enable scalar
10329   // interleaving.
10330   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true)) &&
10331       TTI->getMaxInterleaveFactor(1) < 2)
10332     return LoopVectorizeResult(false, false);
10333 
10334   bool Changed = false, CFGChanged = false;
10335 
10336   // The vectorizer requires loops to be in simplified form.
10337   // Since simplification may add new inner loops, it has to run before the
10338   // legality and profitability checks. This means running the loop vectorizer
10339   // will simplify all loops, regardless of whether anything end up being
10340   // vectorized.
10341   for (auto &L : *LI)
10342     Changed |= CFGChanged |=
10343         simplifyLoop(L, DT, LI, SE, AC, nullptr, false /* PreserveLCSSA */);
10344 
10345   // Build up a worklist of inner-loops to vectorize. This is necessary as
10346   // the act of vectorizing or partially unrolling a loop creates new loops
10347   // and can invalidate iterators across the loops.
10348   SmallVector<Loop *, 8> Worklist;
10349 
10350   for (Loop *L : *LI)
10351     collectSupportedLoops(*L, LI, ORE, Worklist);
10352 
10353   LoopsAnalyzed += Worklist.size();
10354 
10355   // Now walk the identified inner loops.
10356   while (!Worklist.empty()) {
10357     Loop *L = Worklist.pop_back_val();
10358 
10359     // For the inner loops we actually process, form LCSSA to simplify the
10360     // transform.
10361     Changed |= formLCSSARecursively(*L, *DT, LI, SE);
10362 
10363     Changed |= CFGChanged |= processLoop(L);
10364   }
10365 
10366   // Process each loop nest in the function.
10367   return LoopVectorizeResult(Changed, CFGChanged);
10368 }
10369 
10370 PreservedAnalyses LoopVectorizePass::run(Function &F,
10371                                          FunctionAnalysisManager &AM) {
10372     auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
10373     auto &LI = AM.getResult<LoopAnalysis>(F);
10374     auto &TTI = AM.getResult<TargetIRAnalysis>(F);
10375     auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
10376     auto &BFI = AM.getResult<BlockFrequencyAnalysis>(F);
10377     auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
10378     auto &AA = AM.getResult<AAManager>(F);
10379     auto &AC = AM.getResult<AssumptionAnalysis>(F);
10380     auto &DB = AM.getResult<DemandedBitsAnalysis>(F);
10381     auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
10382     MemorySSA *MSSA = EnableMSSALoopDependency
10383                           ? &AM.getResult<MemorySSAAnalysis>(F).getMSSA()
10384                           : nullptr;
10385 
10386     auto &LAM = AM.getResult<LoopAnalysisManagerFunctionProxy>(F).getManager();
10387     std::function<const LoopAccessInfo &(Loop &)> GetLAA =
10388         [&](Loop &L) -> const LoopAccessInfo & {
10389       LoopStandardAnalysisResults AR = {AA,  AC,  DT,      LI,  SE,
10390                                         TLI, TTI, nullptr, MSSA};
10391       return LAM.getResult<LoopAccessAnalysis>(L, AR);
10392     };
10393     auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
10394     ProfileSummaryInfo *PSI =
10395         MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
10396     LoopVectorizeResult Result =
10397         runImpl(F, SE, LI, TTI, DT, BFI, &TLI, DB, AA, AC, GetLAA, ORE, PSI);
10398     if (!Result.MadeAnyChange)
10399       return PreservedAnalyses::all();
10400     PreservedAnalyses PA;
10401 
10402     // We currently do not preserve loopinfo/dominator analyses with outer loop
10403     // vectorization. Until this is addressed, mark these analyses as preserved
10404     // only for non-VPlan-native path.
10405     // TODO: Preserve Loop and Dominator analyses for VPlan-native path.
10406     if (!EnableVPlanNativePath) {
10407       PA.preserve<LoopAnalysis>();
10408       PA.preserve<DominatorTreeAnalysis>();
10409     }
10410     if (!Result.MadeCFGChange)
10411       PA.preserveSet<CFGAnalyses>();
10412     return PA;
10413 }
10414