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   void selectUserVectorizationFactor(ElementCount UserVF) {
1265     collectUniformsAndScalars(UserVF);
1266     collectInstsToScalarize(UserVF);
1267   }
1268 
1269   /// \return The size (in bits) of the smallest and widest types in the code
1270   /// that needs to be vectorized. We ignore values that remain scalar such as
1271   /// 64 bit loop indices.
1272   std::pair<unsigned, unsigned> getSmallestAndWidestTypes();
1273 
1274   /// \return The desired interleave count.
1275   /// If interleave count has been specified by metadata it will be returned.
1276   /// Otherwise, the interleave count is computed and returned. VF and LoopCost
1277   /// are the selected vectorization factor and the cost of the selected VF.
1278   unsigned selectInterleaveCount(ElementCount VF, unsigned LoopCost);
1279 
1280   /// Memory access instruction may be vectorized in more than one way.
1281   /// Form of instruction after vectorization depends on cost.
1282   /// This function takes cost-based decisions for Load/Store instructions
1283   /// and collects them in a map. This decisions map is used for building
1284   /// the lists of loop-uniform and loop-scalar instructions.
1285   /// The calculated cost is saved with widening decision in order to
1286   /// avoid redundant calculations.
1287   void setCostBasedWideningDecision(ElementCount VF);
1288 
1289   /// A struct that represents some properties of the register usage
1290   /// of a loop.
1291   struct RegisterUsage {
1292     /// Holds the number of loop invariant values that are used in the loop.
1293     /// The key is ClassID of target-provided register class.
1294     SmallMapVector<unsigned, unsigned, 4> LoopInvariantRegs;
1295     /// Holds the maximum number of concurrent live intervals in the loop.
1296     /// The key is ClassID of target-provided register class.
1297     SmallMapVector<unsigned, unsigned, 4> MaxLocalUsers;
1298   };
1299 
1300   /// \return Returns information about the register usages of the loop for the
1301   /// given vectorization factors.
1302   SmallVector<RegisterUsage, 8>
1303   calculateRegisterUsage(ArrayRef<ElementCount> VFs);
1304 
1305   /// Collect values we want to ignore in the cost model.
1306   void collectValuesToIgnore();
1307 
1308   /// Collect all element types in the loop for which widening is needed.
1309   void collectElementTypesForWidening();
1310 
1311   /// Split reductions into those that happen in the loop, and those that happen
1312   /// outside. In loop reductions are collected into InLoopReductionChains.
1313   void collectInLoopReductions();
1314 
1315   /// Returns true if we should use strict in-order reductions for the given
1316   /// RdxDesc. This is true if the -enable-strict-reductions flag is passed,
1317   /// the IsOrdered flag of RdxDesc is set and we do not allow reordering
1318   /// of FP operations.
1319   bool useOrderedReductions(const RecurrenceDescriptor &RdxDesc) {
1320     return EnableStrictReductions && !Hints->allowReordering() &&
1321            RdxDesc.isOrdered();
1322   }
1323 
1324   /// \returns The smallest bitwidth each instruction can be represented with.
1325   /// The vector equivalents of these instructions should be truncated to this
1326   /// type.
1327   const MapVector<Instruction *, uint64_t> &getMinimalBitwidths() const {
1328     return MinBWs;
1329   }
1330 
1331   /// \returns True if it is more profitable to scalarize instruction \p I for
1332   /// vectorization factor \p VF.
1333   bool isProfitableToScalarize(Instruction *I, ElementCount VF) const {
1334     assert(VF.isVector() &&
1335            "Profitable to scalarize relevant only for VF > 1.");
1336 
1337     // Cost model is not run in the VPlan-native path - return conservative
1338     // result until this changes.
1339     if (EnableVPlanNativePath)
1340       return false;
1341 
1342     auto Scalars = InstsToScalarize.find(VF);
1343     assert(Scalars != InstsToScalarize.end() &&
1344            "VF not yet analyzed for scalarization profitability");
1345     return Scalars->second.find(I) != Scalars->second.end();
1346   }
1347 
1348   /// Returns true if \p I is known to be uniform after vectorization.
1349   bool isUniformAfterVectorization(Instruction *I, ElementCount VF) const {
1350     if (VF.isScalar())
1351       return true;
1352 
1353     // Cost model is not run in the VPlan-native path - return conservative
1354     // result until this changes.
1355     if (EnableVPlanNativePath)
1356       return false;
1357 
1358     auto UniformsPerVF = Uniforms.find(VF);
1359     assert(UniformsPerVF != Uniforms.end() &&
1360            "VF not yet analyzed for uniformity");
1361     return UniformsPerVF->second.count(I);
1362   }
1363 
1364   /// Returns true if \p I is known to be scalar after vectorization.
1365   bool isScalarAfterVectorization(Instruction *I, ElementCount VF) const {
1366     if (VF.isScalar())
1367       return true;
1368 
1369     // Cost model is not run in the VPlan-native path - return conservative
1370     // result until this changes.
1371     if (EnableVPlanNativePath)
1372       return false;
1373 
1374     auto ScalarsPerVF = Scalars.find(VF);
1375     assert(ScalarsPerVF != Scalars.end() &&
1376            "Scalar values are not calculated for VF");
1377     return ScalarsPerVF->second.count(I);
1378   }
1379 
1380   /// \returns True if instruction \p I can be truncated to a smaller bitwidth
1381   /// for vectorization factor \p VF.
1382   bool canTruncateToMinimalBitwidth(Instruction *I, ElementCount VF) const {
1383     return VF.isVector() && MinBWs.find(I) != MinBWs.end() &&
1384            !isProfitableToScalarize(I, VF) &&
1385            !isScalarAfterVectorization(I, VF);
1386   }
1387 
1388   /// Decision that was taken during cost calculation for memory instruction.
1389   enum InstWidening {
1390     CM_Unknown,
1391     CM_Widen,         // For consecutive accesses with stride +1.
1392     CM_Widen_Reverse, // For consecutive accesses with stride -1.
1393     CM_Interleave,
1394     CM_GatherScatter,
1395     CM_Scalarize
1396   };
1397 
1398   /// Save vectorization decision \p W and \p Cost taken by the cost model for
1399   /// instruction \p I and vector width \p VF.
1400   void setWideningDecision(Instruction *I, ElementCount VF, InstWidening W,
1401                            InstructionCost Cost) {
1402     assert(VF.isVector() && "Expected VF >=2");
1403     WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
1404   }
1405 
1406   /// Save vectorization decision \p W and \p Cost taken by the cost model for
1407   /// interleaving group \p Grp and vector width \p VF.
1408   void setWideningDecision(const InterleaveGroup<Instruction> *Grp,
1409                            ElementCount VF, InstWidening W,
1410                            InstructionCost Cost) {
1411     assert(VF.isVector() && "Expected VF >=2");
1412     /// Broadcast this decicion to all instructions inside the group.
1413     /// But the cost will be assigned to one instruction only.
1414     for (unsigned i = 0; i < Grp->getFactor(); ++i) {
1415       if (auto *I = Grp->getMember(i)) {
1416         if (Grp->getInsertPos() == I)
1417           WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
1418         else
1419           WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, 0);
1420       }
1421     }
1422   }
1423 
1424   /// Return the cost model decision for the given instruction \p I and vector
1425   /// width \p VF. Return CM_Unknown if this instruction did not pass
1426   /// through the cost modeling.
1427   InstWidening getWideningDecision(Instruction *I, ElementCount VF) const {
1428     assert(VF.isVector() && "Expected VF to be a vector VF");
1429     // Cost model is not run in the VPlan-native path - return conservative
1430     // result until this changes.
1431     if (EnableVPlanNativePath)
1432       return CM_GatherScatter;
1433 
1434     std::pair<Instruction *, ElementCount> InstOnVF = std::make_pair(I, VF);
1435     auto Itr = WideningDecisions.find(InstOnVF);
1436     if (Itr == WideningDecisions.end())
1437       return CM_Unknown;
1438     return Itr->second.first;
1439   }
1440 
1441   /// Return the vectorization cost for the given instruction \p I and vector
1442   /// width \p VF.
1443   InstructionCost getWideningCost(Instruction *I, ElementCount VF) {
1444     assert(VF.isVector() && "Expected VF >=2");
1445     std::pair<Instruction *, ElementCount> InstOnVF = std::make_pair(I, VF);
1446     assert(WideningDecisions.find(InstOnVF) != WideningDecisions.end() &&
1447            "The cost is not calculated");
1448     return WideningDecisions[InstOnVF].second;
1449   }
1450 
1451   /// Return True if instruction \p I is an optimizable truncate whose operand
1452   /// is an induction variable. Such a truncate will be removed by adding a new
1453   /// induction variable with the destination type.
1454   bool isOptimizableIVTruncate(Instruction *I, ElementCount VF) {
1455     // If the instruction is not a truncate, return false.
1456     auto *Trunc = dyn_cast<TruncInst>(I);
1457     if (!Trunc)
1458       return false;
1459 
1460     // Get the source and destination types of the truncate.
1461     Type *SrcTy = ToVectorTy(cast<CastInst>(I)->getSrcTy(), VF);
1462     Type *DestTy = ToVectorTy(cast<CastInst>(I)->getDestTy(), VF);
1463 
1464     // If the truncate is free for the given types, return false. Replacing a
1465     // free truncate with an induction variable would add an induction variable
1466     // update instruction to each iteration of the loop. We exclude from this
1467     // check the primary induction variable since it will need an update
1468     // instruction regardless.
1469     Value *Op = Trunc->getOperand(0);
1470     if (Op != Legal->getPrimaryInduction() && TTI.isTruncateFree(SrcTy, DestTy))
1471       return false;
1472 
1473     // If the truncated value is not an induction variable, return false.
1474     return Legal->isInductionPhi(Op);
1475   }
1476 
1477   /// Collects the instructions to scalarize for each predicated instruction in
1478   /// the loop.
1479   void collectInstsToScalarize(ElementCount VF);
1480 
1481   /// Collect Uniform and Scalar values for the given \p VF.
1482   /// The sets depend on CM decision for Load/Store instructions
1483   /// that may be vectorized as interleave, gather-scatter or scalarized.
1484   void collectUniformsAndScalars(ElementCount VF) {
1485     // Do the analysis once.
1486     if (VF.isScalar() || Uniforms.find(VF) != Uniforms.end())
1487       return;
1488     setCostBasedWideningDecision(VF);
1489     collectLoopUniforms(VF);
1490     collectLoopScalars(VF);
1491   }
1492 
1493   /// Returns true if the target machine supports masked store operation
1494   /// for the given \p DataType and kind of access to \p Ptr.
1495   bool isLegalMaskedStore(Type *DataType, Value *Ptr, Align Alignment) const {
1496     return Legal->isConsecutivePtr(Ptr) &&
1497            TTI.isLegalMaskedStore(DataType, Alignment);
1498   }
1499 
1500   /// Returns true if the target machine supports masked load operation
1501   /// for the given \p DataType and kind of access to \p Ptr.
1502   bool isLegalMaskedLoad(Type *DataType, Value *Ptr, Align Alignment) const {
1503     return Legal->isConsecutivePtr(Ptr) &&
1504            TTI.isLegalMaskedLoad(DataType, Alignment);
1505   }
1506 
1507   /// Returns true if the target machine can represent \p V as a masked gather
1508   /// or scatter operation.
1509   bool isLegalGatherOrScatter(Value *V) {
1510     bool LI = isa<LoadInst>(V);
1511     bool SI = isa<StoreInst>(V);
1512     if (!LI && !SI)
1513       return false;
1514     auto *Ty = getLoadStoreType(V);
1515     Align Align = getLoadStoreAlignment(V);
1516     return (LI && TTI.isLegalMaskedGather(Ty, Align)) ||
1517            (SI && TTI.isLegalMaskedScatter(Ty, Align));
1518   }
1519 
1520   /// Returns true if the target machine supports all of the reduction
1521   /// variables found for the given VF.
1522   bool canVectorizeReductions(ElementCount VF) const {
1523     return (all_of(Legal->getReductionVars(), [&](auto &Reduction) -> bool {
1524       const RecurrenceDescriptor &RdxDesc = Reduction.second;
1525       return TTI.isLegalToVectorizeReduction(RdxDesc, VF);
1526     }));
1527   }
1528 
1529   /// Returns true if \p I is an instruction that will be scalarized with
1530   /// predication. Such instructions include conditional stores and
1531   /// instructions that may divide by zero.
1532   /// If a non-zero VF has been calculated, we check if I will be scalarized
1533   /// predication for that VF.
1534   bool isScalarWithPredication(Instruction *I) const;
1535 
1536   // Returns true if \p I is an instruction that will be predicated either
1537   // through scalar predication or masked load/store or masked gather/scatter.
1538   // Superset of instructions that return true for isScalarWithPredication.
1539   bool isPredicatedInst(Instruction *I) {
1540     if (!blockNeedsPredication(I->getParent()))
1541       return false;
1542     // Loads and stores that need some form of masked operation are predicated
1543     // instructions.
1544     if (isa<LoadInst>(I) || isa<StoreInst>(I))
1545       return Legal->isMaskRequired(I);
1546     return isScalarWithPredication(I);
1547   }
1548 
1549   /// Returns true if \p I is a memory instruction with consecutive memory
1550   /// access that can be widened.
1551   bool
1552   memoryInstructionCanBeWidened(Instruction *I,
1553                                 ElementCount VF = ElementCount::getFixed(1));
1554 
1555   /// Returns true if \p I is a memory instruction in an interleaved-group
1556   /// of memory accesses that can be vectorized with wide vector loads/stores
1557   /// and shuffles.
1558   bool
1559   interleavedAccessCanBeWidened(Instruction *I,
1560                                 ElementCount VF = ElementCount::getFixed(1));
1561 
1562   /// Check if \p Instr belongs to any interleaved access group.
1563   bool isAccessInterleaved(Instruction *Instr) {
1564     return InterleaveInfo.isInterleaved(Instr);
1565   }
1566 
1567   /// Get the interleaved access group that \p Instr belongs to.
1568   const InterleaveGroup<Instruction> *
1569   getInterleavedAccessGroup(Instruction *Instr) {
1570     return InterleaveInfo.getInterleaveGroup(Instr);
1571   }
1572 
1573   /// Returns true if we're required to use a scalar epilogue for at least
1574   /// the final iteration of the original loop.
1575   bool requiresScalarEpilogue(ElementCount VF) const {
1576     if (!isScalarEpilogueAllowed())
1577       return false;
1578     // If we might exit from anywhere but the latch, must run the exiting
1579     // iteration in scalar form.
1580     if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch())
1581       return true;
1582     return VF.isVector() && InterleaveInfo.requiresScalarEpilogue();
1583   }
1584 
1585   /// Returns true if a scalar epilogue is not allowed due to optsize or a
1586   /// loop hint annotation.
1587   bool isScalarEpilogueAllowed() const {
1588     return ScalarEpilogueStatus == CM_ScalarEpilogueAllowed;
1589   }
1590 
1591   /// Returns true if all loop blocks should be masked to fold tail loop.
1592   bool foldTailByMasking() const { return FoldTailByMasking; }
1593 
1594   bool blockNeedsPredication(BasicBlock *BB) const {
1595     return foldTailByMasking() || Legal->blockNeedsPredication(BB);
1596   }
1597 
1598   /// A SmallMapVector to store the InLoop reduction op chains, mapping phi
1599   /// nodes to the chain of instructions representing the reductions. Uses a
1600   /// MapVector to ensure deterministic iteration order.
1601   using ReductionChainMap =
1602       SmallMapVector<PHINode *, SmallVector<Instruction *, 4>, 4>;
1603 
1604   /// Return the chain of instructions representing an inloop reduction.
1605   const ReductionChainMap &getInLoopReductionChains() const {
1606     return InLoopReductionChains;
1607   }
1608 
1609   /// Returns true if the Phi is part of an inloop reduction.
1610   bool isInLoopReduction(PHINode *Phi) const {
1611     return InLoopReductionChains.count(Phi);
1612   }
1613 
1614   /// Estimate cost of an intrinsic call instruction CI if it were vectorized
1615   /// with factor VF.  Return the cost of the instruction, including
1616   /// scalarization overhead if it's needed.
1617   InstructionCost getVectorIntrinsicCost(CallInst *CI, ElementCount VF) const;
1618 
1619   /// Estimate cost of a call instruction CI if it were vectorized with factor
1620   /// VF. Return the cost of the instruction, including scalarization overhead
1621   /// if it's needed. The flag NeedToScalarize shows if the call needs to be
1622   /// scalarized -
1623   /// i.e. either vector version isn't available, or is too expensive.
1624   InstructionCost getVectorCallCost(CallInst *CI, ElementCount VF,
1625                                     bool &NeedToScalarize) const;
1626 
1627   /// Returns true if the per-lane cost of VectorizationFactor A is lower than
1628   /// that of B.
1629   bool isMoreProfitable(const VectorizationFactor &A,
1630                         const VectorizationFactor &B) const;
1631 
1632   /// Invalidates decisions already taken by the cost model.
1633   void invalidateCostModelingDecisions() {
1634     WideningDecisions.clear();
1635     Uniforms.clear();
1636     Scalars.clear();
1637   }
1638 
1639 private:
1640   unsigned NumPredStores = 0;
1641 
1642   /// \return An upper bound for the vectorization factors for both
1643   /// fixed and scalable vectorization, where the minimum-known number of
1644   /// elements is a power-of-2 larger than zero. If scalable vectorization is
1645   /// disabled or unsupported, then the scalable part will be equal to
1646   /// ElementCount::getScalable(0).
1647   FixedScalableVFPair computeFeasibleMaxVF(unsigned ConstTripCount,
1648                                            ElementCount UserVF);
1649 
1650   /// \return the maximized element count based on the targets vector
1651   /// registers and the loop trip-count, but limited to a maximum safe VF.
1652   /// This is a helper function of computeFeasibleMaxVF.
1653   /// FIXME: MaxSafeVF is currently passed by reference to avoid some obscure
1654   /// issue that occurred on one of the buildbots which cannot be reproduced
1655   /// without having access to the properietary compiler (see comments on
1656   /// D98509). The issue is currently under investigation and this workaround
1657   /// will be removed as soon as possible.
1658   ElementCount getMaximizedVFForTarget(unsigned ConstTripCount,
1659                                        unsigned SmallestType,
1660                                        unsigned WidestType,
1661                                        const ElementCount &MaxSafeVF);
1662 
1663   /// \return the maximum legal scalable VF, based on the safe max number
1664   /// of elements.
1665   ElementCount getMaxLegalScalableVF(unsigned MaxSafeElements);
1666 
1667   /// The vectorization cost is a combination of the cost itself and a boolean
1668   /// indicating whether any of the contributing operations will actually
1669   /// operate on vector values after type legalization in the backend. If this
1670   /// latter value is false, then all operations will be scalarized (i.e. no
1671   /// vectorization has actually taken place).
1672   using VectorizationCostTy = std::pair<InstructionCost, bool>;
1673 
1674   /// Returns the expected execution cost. The unit of the cost does
1675   /// not matter because we use the 'cost' units to compare different
1676   /// vector widths. The cost that is returned is *not* normalized by
1677   /// the factor width.
1678   VectorizationCostTy expectedCost(ElementCount VF);
1679 
1680   /// Returns the execution time cost of an instruction for a given vector
1681   /// width. Vector width of one means scalar.
1682   VectorizationCostTy getInstructionCost(Instruction *I, ElementCount VF);
1683 
1684   /// The cost-computation logic from getInstructionCost which provides
1685   /// the vector type as an output parameter.
1686   InstructionCost getInstructionCost(Instruction *I, ElementCount VF,
1687                                      Type *&VectorTy);
1688 
1689   /// Return the cost of instructions in an inloop reduction pattern, if I is
1690   /// part of that pattern.
1691   InstructionCost getReductionPatternCost(Instruction *I, ElementCount VF,
1692                                           Type *VectorTy,
1693                                           TTI::TargetCostKind CostKind);
1694 
1695   /// Calculate vectorization cost of memory instruction \p I.
1696   InstructionCost getMemoryInstructionCost(Instruction *I, ElementCount VF);
1697 
1698   /// The cost computation for scalarized memory instruction.
1699   InstructionCost getMemInstScalarizationCost(Instruction *I, ElementCount VF);
1700 
1701   /// The cost computation for interleaving group of memory instructions.
1702   InstructionCost getInterleaveGroupCost(Instruction *I, ElementCount VF);
1703 
1704   /// The cost computation for Gather/Scatter instruction.
1705   InstructionCost getGatherScatterCost(Instruction *I, ElementCount VF);
1706 
1707   /// The cost computation for widening instruction \p I with consecutive
1708   /// memory access.
1709   InstructionCost getConsecutiveMemOpCost(Instruction *I, ElementCount VF);
1710 
1711   /// The cost calculation for Load/Store instruction \p I with uniform pointer -
1712   /// Load: scalar load + broadcast.
1713   /// Store: scalar store + (loop invariant value stored? 0 : extract of last
1714   /// element)
1715   InstructionCost getUniformMemOpCost(Instruction *I, ElementCount VF);
1716 
1717   /// Estimate the overhead of scalarizing an instruction. This is a
1718   /// convenience wrapper for the type-based getScalarizationOverhead API.
1719   InstructionCost getScalarizationOverhead(Instruction *I,
1720                                            ElementCount VF) const;
1721 
1722   /// Returns whether the instruction is a load or store and will be a emitted
1723   /// as a vector operation.
1724   bool isConsecutiveLoadOrStore(Instruction *I);
1725 
1726   /// Returns true if an artificially high cost for emulated masked memrefs
1727   /// should be used.
1728   bool useEmulatedMaskMemRefHack(Instruction *I);
1729 
1730   /// Map of scalar integer values to the smallest bitwidth they can be legally
1731   /// represented as. The vector equivalents of these values should be truncated
1732   /// to this type.
1733   MapVector<Instruction *, uint64_t> MinBWs;
1734 
1735   /// A type representing the costs for instructions if they were to be
1736   /// scalarized rather than vectorized. The entries are Instruction-Cost
1737   /// pairs.
1738   using ScalarCostsTy = DenseMap<Instruction *, InstructionCost>;
1739 
1740   /// A set containing all BasicBlocks that are known to present after
1741   /// vectorization as a predicated block.
1742   SmallPtrSet<BasicBlock *, 4> PredicatedBBsAfterVectorization;
1743 
1744   /// Records whether it is allowed to have the original scalar loop execute at
1745   /// least once. This may be needed as a fallback loop in case runtime
1746   /// aliasing/dependence checks fail, or to handle the tail/remainder
1747   /// iterations when the trip count is unknown or doesn't divide by the VF,
1748   /// or as a peel-loop to handle gaps in interleave-groups.
1749   /// Under optsize and when the trip count is very small we don't allow any
1750   /// iterations to execute in the scalar loop.
1751   ScalarEpilogueLowering ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
1752 
1753   /// All blocks of loop are to be masked to fold tail of scalar iterations.
1754   bool FoldTailByMasking = false;
1755 
1756   /// A map holding scalar costs for different vectorization factors. The
1757   /// presence of a cost for an instruction in the mapping indicates that the
1758   /// instruction will be scalarized when vectorizing with the associated
1759   /// vectorization factor. The entries are VF-ScalarCostTy pairs.
1760   DenseMap<ElementCount, ScalarCostsTy> InstsToScalarize;
1761 
1762   /// Holds the instructions known to be uniform after vectorization.
1763   /// The data is collected per VF.
1764   DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> Uniforms;
1765 
1766   /// Holds the instructions known to be scalar after vectorization.
1767   /// The data is collected per VF.
1768   DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> Scalars;
1769 
1770   /// Holds the instructions (address computations) that are forced to be
1771   /// scalarized.
1772   DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> ForcedScalars;
1773 
1774   /// PHINodes of the reductions that should be expanded in-loop along with
1775   /// their associated chains of reduction operations, in program order from top
1776   /// (PHI) to bottom
1777   ReductionChainMap InLoopReductionChains;
1778 
1779   /// A Map of inloop reduction operations and their immediate chain operand.
1780   /// FIXME: This can be removed once reductions can be costed correctly in
1781   /// vplan. This was added to allow quick lookup to the inloop operations,
1782   /// without having to loop through InLoopReductionChains.
1783   DenseMap<Instruction *, Instruction *> InLoopReductionImmediateChains;
1784 
1785   /// Returns the expected difference in cost from scalarizing the expression
1786   /// feeding a predicated instruction \p PredInst. The instructions to
1787   /// scalarize and their scalar costs are collected in \p ScalarCosts. A
1788   /// non-negative return value implies the expression will be scalarized.
1789   /// Currently, only single-use chains are considered for scalarization.
1790   int computePredInstDiscount(Instruction *PredInst, ScalarCostsTy &ScalarCosts,
1791                               ElementCount VF);
1792 
1793   /// Collect the instructions that are uniform after vectorization. An
1794   /// instruction is uniform if we represent it with a single scalar value in
1795   /// the vectorized loop corresponding to each vector iteration. Examples of
1796   /// uniform instructions include pointer operands of consecutive or
1797   /// interleaved memory accesses. Note that although uniformity implies an
1798   /// instruction will be scalar, the reverse is not true. In general, a
1799   /// scalarized instruction will be represented by VF scalar values in the
1800   /// vectorized loop, each corresponding to an iteration of the original
1801   /// scalar loop.
1802   void collectLoopUniforms(ElementCount VF);
1803 
1804   /// Collect the instructions that are scalar after vectorization. An
1805   /// instruction is scalar if it is known to be uniform or will be scalarized
1806   /// during vectorization. Non-uniform scalarized instructions will be
1807   /// represented by VF values in the vectorized loop, each corresponding to an
1808   /// iteration of the original scalar loop.
1809   void collectLoopScalars(ElementCount VF);
1810 
1811   /// Keeps cost model vectorization decision and cost for instructions.
1812   /// Right now it is used for memory instructions only.
1813   using DecisionList = DenseMap<std::pair<Instruction *, ElementCount>,
1814                                 std::pair<InstWidening, InstructionCost>>;
1815 
1816   DecisionList WideningDecisions;
1817 
1818   /// Returns true if \p V is expected to be vectorized and it needs to be
1819   /// extracted.
1820   bool needsExtract(Value *V, ElementCount VF) const {
1821     Instruction *I = dyn_cast<Instruction>(V);
1822     if (VF.isScalar() || !I || !TheLoop->contains(I) ||
1823         TheLoop->isLoopInvariant(I))
1824       return false;
1825 
1826     // Assume we can vectorize V (and hence we need extraction) if the
1827     // scalars are not computed yet. This can happen, because it is called
1828     // via getScalarizationOverhead from setCostBasedWideningDecision, before
1829     // the scalars are collected. That should be a safe assumption in most
1830     // cases, because we check if the operands have vectorizable types
1831     // beforehand in LoopVectorizationLegality.
1832     return Scalars.find(VF) == Scalars.end() ||
1833            !isScalarAfterVectorization(I, VF);
1834   };
1835 
1836   /// Returns a range containing only operands needing to be extracted.
1837   SmallVector<Value *, 4> filterExtractingOperands(Instruction::op_range Ops,
1838                                                    ElementCount VF) const {
1839     return SmallVector<Value *, 4>(make_filter_range(
1840         Ops, [this, VF](Value *V) { return this->needsExtract(V, VF); }));
1841   }
1842 
1843   /// Determines if we have the infrastructure to vectorize loop \p L and its
1844   /// epilogue, assuming the main loop is vectorized by \p VF.
1845   bool isCandidateForEpilogueVectorization(const Loop &L,
1846                                            const ElementCount VF) const;
1847 
1848   /// Returns true if epilogue vectorization is considered profitable, and
1849   /// false otherwise.
1850   /// \p VF is the vectorization factor chosen for the original loop.
1851   bool isEpilogueVectorizationProfitable(const ElementCount VF) const;
1852 
1853 public:
1854   /// The loop that we evaluate.
1855   Loop *TheLoop;
1856 
1857   /// Predicated scalar evolution analysis.
1858   PredicatedScalarEvolution &PSE;
1859 
1860   /// Loop Info analysis.
1861   LoopInfo *LI;
1862 
1863   /// Vectorization legality.
1864   LoopVectorizationLegality *Legal;
1865 
1866   /// Vector target information.
1867   const TargetTransformInfo &TTI;
1868 
1869   /// Target Library Info.
1870   const TargetLibraryInfo *TLI;
1871 
1872   /// Demanded bits analysis.
1873   DemandedBits *DB;
1874 
1875   /// Assumption cache.
1876   AssumptionCache *AC;
1877 
1878   /// Interface to emit optimization remarks.
1879   OptimizationRemarkEmitter *ORE;
1880 
1881   const Function *TheFunction;
1882 
1883   /// Loop Vectorize Hint.
1884   const LoopVectorizeHints *Hints;
1885 
1886   /// The interleave access information contains groups of interleaved accesses
1887   /// with the same stride and close to each other.
1888   InterleavedAccessInfo &InterleaveInfo;
1889 
1890   /// Values to ignore in the cost model.
1891   SmallPtrSet<const Value *, 16> ValuesToIgnore;
1892 
1893   /// Values to ignore in the cost model when VF > 1.
1894   SmallPtrSet<const Value *, 16> VecValuesToIgnore;
1895 
1896   /// All element types found in the loop.
1897   SmallPtrSet<Type *, 16> ElementTypesInLoop;
1898 
1899   /// Profitable vector factors.
1900   SmallVector<VectorizationFactor, 8> ProfitableVFs;
1901 };
1902 } // end namespace llvm
1903 
1904 /// Helper struct to manage generating runtime checks for vectorization.
1905 ///
1906 /// The runtime checks are created up-front in temporary blocks to allow better
1907 /// estimating the cost and un-linked from the existing IR. After deciding to
1908 /// vectorize, the checks are moved back. If deciding not to vectorize, the
1909 /// temporary blocks are completely removed.
1910 class GeneratedRTChecks {
1911   /// Basic block which contains the generated SCEV checks, if any.
1912   BasicBlock *SCEVCheckBlock = nullptr;
1913 
1914   /// The value representing the result of the generated SCEV checks. If it is
1915   /// nullptr, either no SCEV checks have been generated or they have been used.
1916   Value *SCEVCheckCond = nullptr;
1917 
1918   /// Basic block which contains the generated memory runtime checks, if any.
1919   BasicBlock *MemCheckBlock = nullptr;
1920 
1921   /// The value representing the result of the generated memory runtime checks.
1922   /// If it is nullptr, either no memory runtime checks have been generated or
1923   /// they have been used.
1924   Instruction *MemRuntimeCheckCond = nullptr;
1925 
1926   DominatorTree *DT;
1927   LoopInfo *LI;
1928 
1929   SCEVExpander SCEVExp;
1930   SCEVExpander MemCheckExp;
1931 
1932 public:
1933   GeneratedRTChecks(ScalarEvolution &SE, DominatorTree *DT, LoopInfo *LI,
1934                     const DataLayout &DL)
1935       : DT(DT), LI(LI), SCEVExp(SE, DL, "scev.check"),
1936         MemCheckExp(SE, DL, "scev.check") {}
1937 
1938   /// Generate runtime checks in SCEVCheckBlock and MemCheckBlock, so we can
1939   /// accurately estimate the cost of the runtime checks. The blocks are
1940   /// un-linked from the IR and is added back during vector code generation. If
1941   /// there is no vector code generation, the check blocks are removed
1942   /// completely.
1943   void Create(Loop *L, const LoopAccessInfo &LAI,
1944               const SCEVUnionPredicate &UnionPred) {
1945 
1946     BasicBlock *LoopHeader = L->getHeader();
1947     BasicBlock *Preheader = L->getLoopPreheader();
1948 
1949     // Use SplitBlock to create blocks for SCEV & memory runtime checks to
1950     // ensure the blocks are properly added to LoopInfo & DominatorTree. Those
1951     // may be used by SCEVExpander. The blocks will be un-linked from their
1952     // predecessors and removed from LI & DT at the end of the function.
1953     if (!UnionPred.isAlwaysTrue()) {
1954       SCEVCheckBlock = SplitBlock(Preheader, Preheader->getTerminator(), DT, LI,
1955                                   nullptr, "vector.scevcheck");
1956 
1957       SCEVCheckCond = SCEVExp.expandCodeForPredicate(
1958           &UnionPred, SCEVCheckBlock->getTerminator());
1959     }
1960 
1961     const auto &RtPtrChecking = *LAI.getRuntimePointerChecking();
1962     if (RtPtrChecking.Need) {
1963       auto *Pred = SCEVCheckBlock ? SCEVCheckBlock : Preheader;
1964       MemCheckBlock = SplitBlock(Pred, Pred->getTerminator(), DT, LI, nullptr,
1965                                  "vector.memcheck");
1966 
1967       std::tie(std::ignore, MemRuntimeCheckCond) =
1968           addRuntimeChecks(MemCheckBlock->getTerminator(), L,
1969                            RtPtrChecking.getChecks(), MemCheckExp);
1970       assert(MemRuntimeCheckCond &&
1971              "no RT checks generated although RtPtrChecking "
1972              "claimed checks are required");
1973     }
1974 
1975     if (!MemCheckBlock && !SCEVCheckBlock)
1976       return;
1977 
1978     // Unhook the temporary block with the checks, update various places
1979     // accordingly.
1980     if (SCEVCheckBlock)
1981       SCEVCheckBlock->replaceAllUsesWith(Preheader);
1982     if (MemCheckBlock)
1983       MemCheckBlock->replaceAllUsesWith(Preheader);
1984 
1985     if (SCEVCheckBlock) {
1986       SCEVCheckBlock->getTerminator()->moveBefore(Preheader->getTerminator());
1987       new UnreachableInst(Preheader->getContext(), SCEVCheckBlock);
1988       Preheader->getTerminator()->eraseFromParent();
1989     }
1990     if (MemCheckBlock) {
1991       MemCheckBlock->getTerminator()->moveBefore(Preheader->getTerminator());
1992       new UnreachableInst(Preheader->getContext(), MemCheckBlock);
1993       Preheader->getTerminator()->eraseFromParent();
1994     }
1995 
1996     DT->changeImmediateDominator(LoopHeader, Preheader);
1997     if (MemCheckBlock) {
1998       DT->eraseNode(MemCheckBlock);
1999       LI->removeBlock(MemCheckBlock);
2000     }
2001     if (SCEVCheckBlock) {
2002       DT->eraseNode(SCEVCheckBlock);
2003       LI->removeBlock(SCEVCheckBlock);
2004     }
2005   }
2006 
2007   /// Remove the created SCEV & memory runtime check blocks & instructions, if
2008   /// unused.
2009   ~GeneratedRTChecks() {
2010     SCEVExpanderCleaner SCEVCleaner(SCEVExp, *DT);
2011     SCEVExpanderCleaner MemCheckCleaner(MemCheckExp, *DT);
2012     if (!SCEVCheckCond)
2013       SCEVCleaner.markResultUsed();
2014 
2015     if (!MemRuntimeCheckCond)
2016       MemCheckCleaner.markResultUsed();
2017 
2018     if (MemRuntimeCheckCond) {
2019       auto &SE = *MemCheckExp.getSE();
2020       // Memory runtime check generation creates compares that use expanded
2021       // values. Remove them before running the SCEVExpanderCleaners.
2022       for (auto &I : make_early_inc_range(reverse(*MemCheckBlock))) {
2023         if (MemCheckExp.isInsertedInstruction(&I))
2024           continue;
2025         SE.forgetValue(&I);
2026         SE.eraseValueFromMap(&I);
2027         I.eraseFromParent();
2028       }
2029     }
2030     MemCheckCleaner.cleanup();
2031     SCEVCleaner.cleanup();
2032 
2033     if (SCEVCheckCond)
2034       SCEVCheckBlock->eraseFromParent();
2035     if (MemRuntimeCheckCond)
2036       MemCheckBlock->eraseFromParent();
2037   }
2038 
2039   /// Adds the generated SCEVCheckBlock before \p LoopVectorPreHeader and
2040   /// adjusts the branches to branch to the vector preheader or \p Bypass,
2041   /// depending on the generated condition.
2042   BasicBlock *emitSCEVChecks(Loop *L, BasicBlock *Bypass,
2043                              BasicBlock *LoopVectorPreHeader,
2044                              BasicBlock *LoopExitBlock) {
2045     if (!SCEVCheckCond)
2046       return nullptr;
2047     if (auto *C = dyn_cast<ConstantInt>(SCEVCheckCond))
2048       if (C->isZero())
2049         return nullptr;
2050 
2051     auto *Pred = LoopVectorPreHeader->getSinglePredecessor();
2052 
2053     BranchInst::Create(LoopVectorPreHeader, SCEVCheckBlock);
2054     // Create new preheader for vector loop.
2055     if (auto *PL = LI->getLoopFor(LoopVectorPreHeader))
2056       PL->addBasicBlockToLoop(SCEVCheckBlock, *LI);
2057 
2058     SCEVCheckBlock->getTerminator()->eraseFromParent();
2059     SCEVCheckBlock->moveBefore(LoopVectorPreHeader);
2060     Pred->getTerminator()->replaceSuccessorWith(LoopVectorPreHeader,
2061                                                 SCEVCheckBlock);
2062 
2063     DT->addNewBlock(SCEVCheckBlock, Pred);
2064     DT->changeImmediateDominator(LoopVectorPreHeader, SCEVCheckBlock);
2065 
2066     ReplaceInstWithInst(
2067         SCEVCheckBlock->getTerminator(),
2068         BranchInst::Create(Bypass, LoopVectorPreHeader, SCEVCheckCond));
2069     // Mark the check as used, to prevent it from being removed during cleanup.
2070     SCEVCheckCond = nullptr;
2071     return SCEVCheckBlock;
2072   }
2073 
2074   /// Adds the generated MemCheckBlock before \p LoopVectorPreHeader and adjusts
2075   /// the branches to branch to the vector preheader or \p Bypass, depending on
2076   /// the generated condition.
2077   BasicBlock *emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass,
2078                                    BasicBlock *LoopVectorPreHeader) {
2079     // Check if we generated code that checks in runtime if arrays overlap.
2080     if (!MemRuntimeCheckCond)
2081       return nullptr;
2082 
2083     auto *Pred = LoopVectorPreHeader->getSinglePredecessor();
2084     Pred->getTerminator()->replaceSuccessorWith(LoopVectorPreHeader,
2085                                                 MemCheckBlock);
2086 
2087     DT->addNewBlock(MemCheckBlock, Pred);
2088     DT->changeImmediateDominator(LoopVectorPreHeader, MemCheckBlock);
2089     MemCheckBlock->moveBefore(LoopVectorPreHeader);
2090 
2091     if (auto *PL = LI->getLoopFor(LoopVectorPreHeader))
2092       PL->addBasicBlockToLoop(MemCheckBlock, *LI);
2093 
2094     ReplaceInstWithInst(
2095         MemCheckBlock->getTerminator(),
2096         BranchInst::Create(Bypass, LoopVectorPreHeader, MemRuntimeCheckCond));
2097     MemCheckBlock->getTerminator()->setDebugLoc(
2098         Pred->getTerminator()->getDebugLoc());
2099 
2100     // Mark the check as used, to prevent it from being removed during cleanup.
2101     MemRuntimeCheckCond = nullptr;
2102     return MemCheckBlock;
2103   }
2104 };
2105 
2106 // Return true if \p OuterLp is an outer loop annotated with hints for explicit
2107 // vectorization. The loop needs to be annotated with #pragma omp simd
2108 // simdlen(#) or #pragma clang vectorize(enable) vectorize_width(#). If the
2109 // vector length information is not provided, vectorization is not considered
2110 // explicit. Interleave hints are not allowed either. These limitations will be
2111 // relaxed in the future.
2112 // Please, note that we are currently forced to abuse the pragma 'clang
2113 // vectorize' semantics. This pragma provides *auto-vectorization hints*
2114 // (i.e., LV must check that vectorization is legal) whereas pragma 'omp simd'
2115 // provides *explicit vectorization hints* (LV can bypass legal checks and
2116 // assume that vectorization is legal). However, both hints are implemented
2117 // using the same metadata (llvm.loop.vectorize, processed by
2118 // LoopVectorizeHints). This will be fixed in the future when the native IR
2119 // representation for pragma 'omp simd' is introduced.
2120 static bool isExplicitVecOuterLoop(Loop *OuterLp,
2121                                    OptimizationRemarkEmitter *ORE) {
2122   assert(!OuterLp->isInnermost() && "This is not an outer loop");
2123   LoopVectorizeHints Hints(OuterLp, true /*DisableInterleaving*/, *ORE);
2124 
2125   // Only outer loops with an explicit vectorization hint are supported.
2126   // Unannotated outer loops are ignored.
2127   if (Hints.getForce() == LoopVectorizeHints::FK_Undefined)
2128     return false;
2129 
2130   Function *Fn = OuterLp->getHeader()->getParent();
2131   if (!Hints.allowVectorization(Fn, OuterLp,
2132                                 true /*VectorizeOnlyWhenForced*/)) {
2133     LLVM_DEBUG(dbgs() << "LV: Loop hints prevent outer loop vectorization.\n");
2134     return false;
2135   }
2136 
2137   if (Hints.getInterleave() > 1) {
2138     // TODO: Interleave support is future work.
2139     LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Interleave is not supported for "
2140                          "outer loops.\n");
2141     Hints.emitRemarkWithHints();
2142     return false;
2143   }
2144 
2145   return true;
2146 }
2147 
2148 static void collectSupportedLoops(Loop &L, LoopInfo *LI,
2149                                   OptimizationRemarkEmitter *ORE,
2150                                   SmallVectorImpl<Loop *> &V) {
2151   // Collect inner loops and outer loops without irreducible control flow. For
2152   // now, only collect outer loops that have explicit vectorization hints. If we
2153   // are stress testing the VPlan H-CFG construction, we collect the outermost
2154   // loop of every loop nest.
2155   if (L.isInnermost() || VPlanBuildStressTest ||
2156       (EnableVPlanNativePath && isExplicitVecOuterLoop(&L, ORE))) {
2157     LoopBlocksRPO RPOT(&L);
2158     RPOT.perform(LI);
2159     if (!containsIrreducibleCFG<const BasicBlock *>(RPOT, *LI)) {
2160       V.push_back(&L);
2161       // TODO: Collect inner loops inside marked outer loops in case
2162       // vectorization fails for the outer loop. Do not invoke
2163       // 'containsIrreducibleCFG' again for inner loops when the outer loop is
2164       // already known to be reducible. We can use an inherited attribute for
2165       // that.
2166       return;
2167     }
2168   }
2169   for (Loop *InnerL : L)
2170     collectSupportedLoops(*InnerL, LI, ORE, V);
2171 }
2172 
2173 namespace {
2174 
2175 /// The LoopVectorize Pass.
2176 struct LoopVectorize : public FunctionPass {
2177   /// Pass identification, replacement for typeid
2178   static char ID;
2179 
2180   LoopVectorizePass Impl;
2181 
2182   explicit LoopVectorize(bool InterleaveOnlyWhenForced = false,
2183                          bool VectorizeOnlyWhenForced = false)
2184       : FunctionPass(ID),
2185         Impl({InterleaveOnlyWhenForced, VectorizeOnlyWhenForced}) {
2186     initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
2187   }
2188 
2189   bool runOnFunction(Function &F) override {
2190     if (skipFunction(F))
2191       return false;
2192 
2193     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
2194     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2195     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
2196     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2197     auto *BFI = &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI();
2198     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
2199     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
2200     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
2201     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
2202     auto *LAA = &getAnalysis<LoopAccessLegacyAnalysis>();
2203     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
2204     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
2205     auto *PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
2206 
2207     std::function<const LoopAccessInfo &(Loop &)> GetLAA =
2208         [&](Loop &L) -> const LoopAccessInfo & { return LAA->getInfo(&L); };
2209 
2210     return Impl.runImpl(F, *SE, *LI, *TTI, *DT, *BFI, TLI, *DB, *AA, *AC,
2211                         GetLAA, *ORE, PSI).MadeAnyChange;
2212   }
2213 
2214   void getAnalysisUsage(AnalysisUsage &AU) const override {
2215     AU.addRequired<AssumptionCacheTracker>();
2216     AU.addRequired<BlockFrequencyInfoWrapperPass>();
2217     AU.addRequired<DominatorTreeWrapperPass>();
2218     AU.addRequired<LoopInfoWrapperPass>();
2219     AU.addRequired<ScalarEvolutionWrapperPass>();
2220     AU.addRequired<TargetTransformInfoWrapperPass>();
2221     AU.addRequired<AAResultsWrapperPass>();
2222     AU.addRequired<LoopAccessLegacyAnalysis>();
2223     AU.addRequired<DemandedBitsWrapperPass>();
2224     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
2225     AU.addRequired<InjectTLIMappingsLegacy>();
2226 
2227     // We currently do not preserve loopinfo/dominator analyses with outer loop
2228     // vectorization. Until this is addressed, mark these analyses as preserved
2229     // only for non-VPlan-native path.
2230     // TODO: Preserve Loop and Dominator analyses for VPlan-native path.
2231     if (!EnableVPlanNativePath) {
2232       AU.addPreserved<LoopInfoWrapperPass>();
2233       AU.addPreserved<DominatorTreeWrapperPass>();
2234     }
2235 
2236     AU.addPreserved<BasicAAWrapperPass>();
2237     AU.addPreserved<GlobalsAAWrapperPass>();
2238     AU.addRequired<ProfileSummaryInfoWrapperPass>();
2239   }
2240 };
2241 
2242 } // end anonymous namespace
2243 
2244 //===----------------------------------------------------------------------===//
2245 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
2246 // LoopVectorizationCostModel and LoopVectorizationPlanner.
2247 //===----------------------------------------------------------------------===//
2248 
2249 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
2250   // We need to place the broadcast of invariant variables outside the loop,
2251   // but only if it's proven safe to do so. Else, broadcast will be inside
2252   // vector loop body.
2253   Instruction *Instr = dyn_cast<Instruction>(V);
2254   bool SafeToHoist = OrigLoop->isLoopInvariant(V) &&
2255                      (!Instr ||
2256                       DT->dominates(Instr->getParent(), LoopVectorPreHeader));
2257   // Place the code for broadcasting invariant variables in the new preheader.
2258   IRBuilder<>::InsertPointGuard Guard(Builder);
2259   if (SafeToHoist)
2260     Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
2261 
2262   // Broadcast the scalar into all locations in the vector.
2263   Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
2264 
2265   return Shuf;
2266 }
2267 
2268 void InnerLoopVectorizer::createVectorIntOrFpInductionPHI(
2269     const InductionDescriptor &II, Value *Step, Value *Start,
2270     Instruction *EntryVal, VPValue *Def, VPValue *CastDef,
2271     VPTransformState &State) {
2272   assert((isa<PHINode>(EntryVal) || isa<TruncInst>(EntryVal)) &&
2273          "Expected either an induction phi-node or a truncate of it!");
2274 
2275   // Construct the initial value of the vector IV in the vector loop preheader
2276   auto CurrIP = Builder.saveIP();
2277   Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
2278   if (isa<TruncInst>(EntryVal)) {
2279     assert(Start->getType()->isIntegerTy() &&
2280            "Truncation requires an integer type");
2281     auto *TruncType = cast<IntegerType>(EntryVal->getType());
2282     Step = Builder.CreateTrunc(Step, TruncType);
2283     Start = Builder.CreateCast(Instruction::Trunc, Start, TruncType);
2284   }
2285   Value *SplatStart = Builder.CreateVectorSplat(VF, Start);
2286   Value *SteppedStart =
2287       getStepVector(SplatStart, 0, Step, II.getInductionOpcode());
2288 
2289   // We create vector phi nodes for both integer and floating-point induction
2290   // variables. Here, we determine the kind of arithmetic we will perform.
2291   Instruction::BinaryOps AddOp;
2292   Instruction::BinaryOps MulOp;
2293   if (Step->getType()->isIntegerTy()) {
2294     AddOp = Instruction::Add;
2295     MulOp = Instruction::Mul;
2296   } else {
2297     AddOp = II.getInductionOpcode();
2298     MulOp = Instruction::FMul;
2299   }
2300 
2301   // Multiply the vectorization factor by the step using integer or
2302   // floating-point arithmetic as appropriate.
2303   Type *StepType = Step->getType();
2304   if (Step->getType()->isFloatingPointTy())
2305     StepType = IntegerType::get(StepType->getContext(),
2306                                 StepType->getScalarSizeInBits());
2307   Value *RuntimeVF = getRuntimeVF(Builder, StepType, VF);
2308   if (Step->getType()->isFloatingPointTy())
2309     RuntimeVF = Builder.CreateSIToFP(RuntimeVF, Step->getType());
2310   Value *Mul = Builder.CreateBinOp(MulOp, Step, RuntimeVF);
2311 
2312   // Create a vector splat to use in the induction update.
2313   //
2314   // FIXME: If the step is non-constant, we create the vector splat with
2315   //        IRBuilder. IRBuilder can constant-fold the multiply, but it doesn't
2316   //        handle a constant vector splat.
2317   Value *SplatVF = isa<Constant>(Mul)
2318                        ? ConstantVector::getSplat(VF, cast<Constant>(Mul))
2319                        : Builder.CreateVectorSplat(VF, Mul);
2320   Builder.restoreIP(CurrIP);
2321 
2322   // We may need to add the step a number of times, depending on the unroll
2323   // factor. The last of those goes into the PHI.
2324   PHINode *VecInd = PHINode::Create(SteppedStart->getType(), 2, "vec.ind",
2325                                     &*LoopVectorBody->getFirstInsertionPt());
2326   VecInd->setDebugLoc(EntryVal->getDebugLoc());
2327   Instruction *LastInduction = VecInd;
2328   for (unsigned Part = 0; Part < UF; ++Part) {
2329     State.set(Def, LastInduction, Part);
2330 
2331     if (isa<TruncInst>(EntryVal))
2332       addMetadata(LastInduction, EntryVal);
2333     recordVectorLoopValueForInductionCast(II, EntryVal, LastInduction, CastDef,
2334                                           State, Part);
2335 
2336     LastInduction = cast<Instruction>(
2337         Builder.CreateBinOp(AddOp, LastInduction, SplatVF, "step.add"));
2338     LastInduction->setDebugLoc(EntryVal->getDebugLoc());
2339   }
2340 
2341   // Move the last step to the end of the latch block. This ensures consistent
2342   // placement of all induction updates.
2343   auto *LoopVectorLatch = LI->getLoopFor(LoopVectorBody)->getLoopLatch();
2344   auto *Br = cast<BranchInst>(LoopVectorLatch->getTerminator());
2345   auto *ICmp = cast<Instruction>(Br->getCondition());
2346   LastInduction->moveBefore(ICmp);
2347   LastInduction->setName("vec.ind.next");
2348 
2349   VecInd->addIncoming(SteppedStart, LoopVectorPreHeader);
2350   VecInd->addIncoming(LastInduction, LoopVectorLatch);
2351 }
2352 
2353 bool InnerLoopVectorizer::shouldScalarizeInstruction(Instruction *I) const {
2354   return Cost->isScalarAfterVectorization(I, VF) ||
2355          Cost->isProfitableToScalarize(I, VF);
2356 }
2357 
2358 bool InnerLoopVectorizer::needsScalarInduction(Instruction *IV) const {
2359   if (shouldScalarizeInstruction(IV))
2360     return true;
2361   auto isScalarInst = [&](User *U) -> bool {
2362     auto *I = cast<Instruction>(U);
2363     return (OrigLoop->contains(I) && shouldScalarizeInstruction(I));
2364   };
2365   return llvm::any_of(IV->users(), isScalarInst);
2366 }
2367 
2368 void InnerLoopVectorizer::recordVectorLoopValueForInductionCast(
2369     const InductionDescriptor &ID, const Instruction *EntryVal,
2370     Value *VectorLoopVal, VPValue *CastDef, VPTransformState &State,
2371     unsigned Part, unsigned Lane) {
2372   assert((isa<PHINode>(EntryVal) || isa<TruncInst>(EntryVal)) &&
2373          "Expected either an induction phi-node or a truncate of it!");
2374 
2375   // This induction variable is not the phi from the original loop but the
2376   // newly-created IV based on the proof that casted Phi is equal to the
2377   // uncasted Phi in the vectorized loop (under a runtime guard possibly). It
2378   // re-uses the same InductionDescriptor that original IV uses but we don't
2379   // have to do any recording in this case - that is done when original IV is
2380   // processed.
2381   if (isa<TruncInst>(EntryVal))
2382     return;
2383 
2384   const SmallVectorImpl<Instruction *> &Casts = ID.getCastInsts();
2385   if (Casts.empty())
2386     return;
2387   // Only the first Cast instruction in the Casts vector is of interest.
2388   // The rest of the Casts (if exist) have no uses outside the
2389   // induction update chain itself.
2390   if (Lane < UINT_MAX)
2391     State.set(CastDef, VectorLoopVal, VPIteration(Part, Lane));
2392   else
2393     State.set(CastDef, VectorLoopVal, Part);
2394 }
2395 
2396 void InnerLoopVectorizer::widenIntOrFpInduction(PHINode *IV, Value *Start,
2397                                                 TruncInst *Trunc, VPValue *Def,
2398                                                 VPValue *CastDef,
2399                                                 VPTransformState &State) {
2400   assert((IV->getType()->isIntegerTy() || IV != OldInduction) &&
2401          "Primary induction variable must have an integer type");
2402 
2403   auto II = Legal->getInductionVars().find(IV);
2404   assert(II != Legal->getInductionVars().end() && "IV is not an induction");
2405 
2406   auto ID = II->second;
2407   assert(IV->getType() == ID.getStartValue()->getType() && "Types must match");
2408 
2409   // The value from the original loop to which we are mapping the new induction
2410   // variable.
2411   Instruction *EntryVal = Trunc ? cast<Instruction>(Trunc) : IV;
2412 
2413   auto &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
2414 
2415   // Generate code for the induction step. Note that induction steps are
2416   // required to be loop-invariant
2417   auto CreateStepValue = [&](const SCEV *Step) -> Value * {
2418     assert(PSE.getSE()->isLoopInvariant(Step, OrigLoop) &&
2419            "Induction step should be loop invariant");
2420     if (PSE.getSE()->isSCEVable(IV->getType())) {
2421       SCEVExpander Exp(*PSE.getSE(), DL, "induction");
2422       return Exp.expandCodeFor(Step, Step->getType(),
2423                                LoopVectorPreHeader->getTerminator());
2424     }
2425     return cast<SCEVUnknown>(Step)->getValue();
2426   };
2427 
2428   // The scalar value to broadcast. This is derived from the canonical
2429   // induction variable. If a truncation type is given, truncate the canonical
2430   // induction variable and step. Otherwise, derive these values from the
2431   // induction descriptor.
2432   auto CreateScalarIV = [&](Value *&Step) -> Value * {
2433     Value *ScalarIV = Induction;
2434     if (IV != OldInduction) {
2435       ScalarIV = IV->getType()->isIntegerTy()
2436                      ? Builder.CreateSExtOrTrunc(Induction, IV->getType())
2437                      : Builder.CreateCast(Instruction::SIToFP, Induction,
2438                                           IV->getType());
2439       ScalarIV = emitTransformedIndex(Builder, ScalarIV, PSE.getSE(), DL, ID);
2440       ScalarIV->setName("offset.idx");
2441     }
2442     if (Trunc) {
2443       auto *TruncType = cast<IntegerType>(Trunc->getType());
2444       assert(Step->getType()->isIntegerTy() &&
2445              "Truncation requires an integer step");
2446       ScalarIV = Builder.CreateTrunc(ScalarIV, TruncType);
2447       Step = Builder.CreateTrunc(Step, TruncType);
2448     }
2449     return ScalarIV;
2450   };
2451 
2452   // Create the vector values from the scalar IV, in the absence of creating a
2453   // vector IV.
2454   auto CreateSplatIV = [&](Value *ScalarIV, Value *Step) {
2455     Value *Broadcasted = getBroadcastInstrs(ScalarIV);
2456     for (unsigned Part = 0; Part < UF; ++Part) {
2457       assert(!VF.isScalable() && "scalable vectors not yet supported.");
2458       Value *EntryPart =
2459           getStepVector(Broadcasted, VF.getKnownMinValue() * Part, Step,
2460                         ID.getInductionOpcode());
2461       State.set(Def, EntryPart, Part);
2462       if (Trunc)
2463         addMetadata(EntryPart, Trunc);
2464       recordVectorLoopValueForInductionCast(ID, EntryVal, EntryPart, CastDef,
2465                                             State, Part);
2466     }
2467   };
2468 
2469   // Fast-math-flags propagate from the original induction instruction.
2470   IRBuilder<>::FastMathFlagGuard FMFG(Builder);
2471   if (ID.getInductionBinOp() && isa<FPMathOperator>(ID.getInductionBinOp()))
2472     Builder.setFastMathFlags(ID.getInductionBinOp()->getFastMathFlags());
2473 
2474   // Now do the actual transformations, and start with creating the step value.
2475   Value *Step = CreateStepValue(ID.getStep());
2476   if (VF.isZero() || VF.isScalar()) {
2477     Value *ScalarIV = CreateScalarIV(Step);
2478     CreateSplatIV(ScalarIV, Step);
2479     return;
2480   }
2481 
2482   // Determine if we want a scalar version of the induction variable. This is
2483   // true if the induction variable itself is not widened, or if it has at
2484   // least one user in the loop that is not widened.
2485   auto NeedsScalarIV = needsScalarInduction(EntryVal);
2486   if (!NeedsScalarIV) {
2487     createVectorIntOrFpInductionPHI(ID, Step, Start, EntryVal, Def, CastDef,
2488                                     State);
2489     return;
2490   }
2491 
2492   // Try to create a new independent vector induction variable. If we can't
2493   // create the phi node, we will splat the scalar induction variable in each
2494   // loop iteration.
2495   if (!shouldScalarizeInstruction(EntryVal)) {
2496     createVectorIntOrFpInductionPHI(ID, Step, Start, EntryVal, Def, CastDef,
2497                                     State);
2498     Value *ScalarIV = CreateScalarIV(Step);
2499     // Create scalar steps that can be used by instructions we will later
2500     // scalarize. Note that the addition of the scalar steps will not increase
2501     // the number of instructions in the loop in the common case prior to
2502     // InstCombine. We will be trading one vector extract for each scalar step.
2503     buildScalarSteps(ScalarIV, Step, EntryVal, ID, Def, CastDef, State);
2504     return;
2505   }
2506 
2507   // All IV users are scalar instructions, so only emit a scalar IV, not a
2508   // vectorised IV. Except when we tail-fold, then the splat IV feeds the
2509   // predicate used by the masked loads/stores.
2510   Value *ScalarIV = CreateScalarIV(Step);
2511   if (!Cost->isScalarEpilogueAllowed())
2512     CreateSplatIV(ScalarIV, Step);
2513   buildScalarSteps(ScalarIV, Step, EntryVal, ID, Def, CastDef, State);
2514 }
2515 
2516 Value *InnerLoopVectorizer::getStepVector(Value *Val, int StartIdx, Value *Step,
2517                                           Instruction::BinaryOps BinOp) {
2518   // Create and check the types.
2519   auto *ValVTy = cast<VectorType>(Val->getType());
2520   ElementCount VLen = ValVTy->getElementCount();
2521 
2522   Type *STy = Val->getType()->getScalarType();
2523   assert((STy->isIntegerTy() || STy->isFloatingPointTy()) &&
2524          "Induction Step must be an integer or FP");
2525   assert(Step->getType() == STy && "Step has wrong type");
2526 
2527   SmallVector<Constant *, 8> Indices;
2528 
2529   // Create a vector of consecutive numbers from zero to VF.
2530   VectorType *InitVecValVTy = ValVTy;
2531   Type *InitVecValSTy = STy;
2532   if (STy->isFloatingPointTy()) {
2533     InitVecValSTy =
2534         IntegerType::get(STy->getContext(), STy->getScalarSizeInBits());
2535     InitVecValVTy = VectorType::get(InitVecValSTy, VLen);
2536   }
2537   Value *InitVec = Builder.CreateStepVector(InitVecValVTy);
2538 
2539   // Add on StartIdx
2540   Value *StartIdxSplat = Builder.CreateVectorSplat(
2541       VLen, ConstantInt::get(InitVecValSTy, StartIdx));
2542   InitVec = Builder.CreateAdd(InitVec, StartIdxSplat);
2543 
2544   if (STy->isIntegerTy()) {
2545     Step = Builder.CreateVectorSplat(VLen, Step);
2546     assert(Step->getType() == Val->getType() && "Invalid step vec");
2547     // FIXME: The newly created binary instructions should contain nsw/nuw flags,
2548     // which can be found from the original scalar operations.
2549     Step = Builder.CreateMul(InitVec, Step);
2550     return Builder.CreateAdd(Val, Step, "induction");
2551   }
2552 
2553   // Floating point induction.
2554   assert((BinOp == Instruction::FAdd || BinOp == Instruction::FSub) &&
2555          "Binary Opcode should be specified for FP induction");
2556   InitVec = Builder.CreateUIToFP(InitVec, ValVTy);
2557   Step = Builder.CreateVectorSplat(VLen, Step);
2558   Value *MulOp = Builder.CreateFMul(InitVec, Step);
2559   return Builder.CreateBinOp(BinOp, Val, MulOp, "induction");
2560 }
2561 
2562 void InnerLoopVectorizer::buildScalarSteps(Value *ScalarIV, Value *Step,
2563                                            Instruction *EntryVal,
2564                                            const InductionDescriptor &ID,
2565                                            VPValue *Def, VPValue *CastDef,
2566                                            VPTransformState &State) {
2567   // We shouldn't have to build scalar steps if we aren't vectorizing.
2568   assert(VF.isVector() && "VF should be greater than one");
2569   // Get the value type and ensure it and the step have the same integer type.
2570   Type *ScalarIVTy = ScalarIV->getType()->getScalarType();
2571   assert(ScalarIVTy == Step->getType() &&
2572          "Val and Step should have the same type");
2573 
2574   // We build scalar steps for both integer and floating-point induction
2575   // variables. Here, we determine the kind of arithmetic we will perform.
2576   Instruction::BinaryOps AddOp;
2577   Instruction::BinaryOps MulOp;
2578   if (ScalarIVTy->isIntegerTy()) {
2579     AddOp = Instruction::Add;
2580     MulOp = Instruction::Mul;
2581   } else {
2582     AddOp = ID.getInductionOpcode();
2583     MulOp = Instruction::FMul;
2584   }
2585 
2586   // Determine the number of scalars we need to generate for each unroll
2587   // iteration. If EntryVal is uniform, we only need to generate the first
2588   // lane. Otherwise, we generate all VF values.
2589   bool IsUniform =
2590       Cost->isUniformAfterVectorization(cast<Instruction>(EntryVal), VF);
2591   unsigned Lanes = IsUniform ? 1 : VF.getKnownMinValue();
2592   // Compute the scalar steps and save the results in State.
2593   Type *IntStepTy = IntegerType::get(ScalarIVTy->getContext(),
2594                                      ScalarIVTy->getScalarSizeInBits());
2595   Type *VecIVTy = nullptr;
2596   Value *UnitStepVec = nullptr, *SplatStep = nullptr, *SplatIV = nullptr;
2597   if (!IsUniform && VF.isScalable()) {
2598     VecIVTy = VectorType::get(ScalarIVTy, VF);
2599     UnitStepVec = Builder.CreateStepVector(VectorType::get(IntStepTy, VF));
2600     SplatStep = Builder.CreateVectorSplat(VF, Step);
2601     SplatIV = Builder.CreateVectorSplat(VF, ScalarIV);
2602   }
2603 
2604   for (unsigned Part = 0; Part < UF; ++Part) {
2605     Value *StartIdx0 =
2606         createStepForVF(Builder, ConstantInt::get(IntStepTy, Part), VF);
2607 
2608     if (!IsUniform && VF.isScalable()) {
2609       auto *SplatStartIdx = Builder.CreateVectorSplat(VF, StartIdx0);
2610       auto *InitVec = Builder.CreateAdd(SplatStartIdx, UnitStepVec);
2611       if (ScalarIVTy->isFloatingPointTy())
2612         InitVec = Builder.CreateSIToFP(InitVec, VecIVTy);
2613       auto *Mul = Builder.CreateBinOp(MulOp, InitVec, SplatStep);
2614       auto *Add = Builder.CreateBinOp(AddOp, SplatIV, Mul);
2615       State.set(Def, Add, Part);
2616       recordVectorLoopValueForInductionCast(ID, EntryVal, Add, CastDef, State,
2617                                             Part);
2618       // It's useful to record the lane values too for the known minimum number
2619       // of elements so we do those below. This improves the code quality when
2620       // trying to extract the first element, for example.
2621     }
2622 
2623     if (ScalarIVTy->isFloatingPointTy())
2624       StartIdx0 = Builder.CreateSIToFP(StartIdx0, ScalarIVTy);
2625 
2626     for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
2627       Value *StartIdx = Builder.CreateBinOp(
2628           AddOp, StartIdx0, getSignedIntOrFpConstant(ScalarIVTy, Lane));
2629       // The step returned by `createStepForVF` is a runtime-evaluated value
2630       // when VF is scalable. Otherwise, it should be folded into a Constant.
2631       assert((VF.isScalable() || isa<Constant>(StartIdx)) &&
2632              "Expected StartIdx to be folded to a constant when VF is not "
2633              "scalable");
2634       auto *Mul = Builder.CreateBinOp(MulOp, StartIdx, Step);
2635       auto *Add = Builder.CreateBinOp(AddOp, ScalarIV, Mul);
2636       State.set(Def, Add, VPIteration(Part, Lane));
2637       recordVectorLoopValueForInductionCast(ID, EntryVal, Add, CastDef, State,
2638                                             Part, Lane);
2639     }
2640   }
2641 }
2642 
2643 void InnerLoopVectorizer::packScalarIntoVectorValue(VPValue *Def,
2644                                                     const VPIteration &Instance,
2645                                                     VPTransformState &State) {
2646   Value *ScalarInst = State.get(Def, Instance);
2647   Value *VectorValue = State.get(Def, Instance.Part);
2648   VectorValue = Builder.CreateInsertElement(
2649       VectorValue, ScalarInst,
2650       Instance.Lane.getAsRuntimeExpr(State.Builder, VF));
2651   State.set(Def, VectorValue, Instance.Part);
2652 }
2653 
2654 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
2655   assert(Vec->getType()->isVectorTy() && "Invalid type");
2656   return Builder.CreateVectorReverse(Vec, "reverse");
2657 }
2658 
2659 // Return whether we allow using masked interleave-groups (for dealing with
2660 // strided loads/stores that reside in predicated blocks, or for dealing
2661 // with gaps).
2662 static bool useMaskedInterleavedAccesses(const TargetTransformInfo &TTI) {
2663   // If an override option has been passed in for interleaved accesses, use it.
2664   if (EnableMaskedInterleavedMemAccesses.getNumOccurrences() > 0)
2665     return EnableMaskedInterleavedMemAccesses;
2666 
2667   return TTI.enableMaskedInterleavedAccessVectorization();
2668 }
2669 
2670 // Try to vectorize the interleave group that \p Instr belongs to.
2671 //
2672 // E.g. Translate following interleaved load group (factor = 3):
2673 //   for (i = 0; i < N; i+=3) {
2674 //     R = Pic[i];             // Member of index 0
2675 //     G = Pic[i+1];           // Member of index 1
2676 //     B = Pic[i+2];           // Member of index 2
2677 //     ... // do something to R, G, B
2678 //   }
2679 // To:
2680 //   %wide.vec = load <12 x i32>                       ; Read 4 tuples of R,G,B
2681 //   %R.vec = shuffle %wide.vec, poison, <0, 3, 6, 9>   ; R elements
2682 //   %G.vec = shuffle %wide.vec, poison, <1, 4, 7, 10>  ; G elements
2683 //   %B.vec = shuffle %wide.vec, poison, <2, 5, 8, 11>  ; B elements
2684 //
2685 // Or translate following interleaved store group (factor = 3):
2686 //   for (i = 0; i < N; i+=3) {
2687 //     ... do something to R, G, B
2688 //     Pic[i]   = R;           // Member of index 0
2689 //     Pic[i+1] = G;           // Member of index 1
2690 //     Pic[i+2] = B;           // Member of index 2
2691 //   }
2692 // To:
2693 //   %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
2694 //   %B_U.vec = shuffle %B.vec, poison, <0, 1, 2, 3, u, u, u, u>
2695 //   %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
2696 //        <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>    ; Interleave R,G,B elements
2697 //   store <12 x i32> %interleaved.vec              ; Write 4 tuples of R,G,B
2698 void InnerLoopVectorizer::vectorizeInterleaveGroup(
2699     const InterleaveGroup<Instruction> *Group, ArrayRef<VPValue *> VPDefs,
2700     VPTransformState &State, VPValue *Addr, ArrayRef<VPValue *> StoredValues,
2701     VPValue *BlockInMask) {
2702   Instruction *Instr = Group->getInsertPos();
2703   const DataLayout &DL = Instr->getModule()->getDataLayout();
2704 
2705   // Prepare for the vector type of the interleaved load/store.
2706   Type *ScalarTy = getLoadStoreType(Instr);
2707   unsigned InterleaveFactor = Group->getFactor();
2708   assert(!VF.isScalable() && "scalable vectors not yet supported.");
2709   auto *VecTy = VectorType::get(ScalarTy, VF * InterleaveFactor);
2710 
2711   // Prepare for the new pointers.
2712   SmallVector<Value *, 2> AddrParts;
2713   unsigned Index = Group->getIndex(Instr);
2714 
2715   // TODO: extend the masked interleaved-group support to reversed access.
2716   assert((!BlockInMask || !Group->isReverse()) &&
2717          "Reversed masked interleave-group not supported.");
2718 
2719   // If the group is reverse, adjust the index to refer to the last vector lane
2720   // instead of the first. We adjust the index from the first vector lane,
2721   // rather than directly getting the pointer for lane VF - 1, because the
2722   // pointer operand of the interleaved access is supposed to be uniform. For
2723   // uniform instructions, we're only required to generate a value for the
2724   // first vector lane in each unroll iteration.
2725   if (Group->isReverse())
2726     Index += (VF.getKnownMinValue() - 1) * Group->getFactor();
2727 
2728   for (unsigned Part = 0; Part < UF; Part++) {
2729     Value *AddrPart = State.get(Addr, VPIteration(Part, 0));
2730     setDebugLocFromInst(AddrPart);
2731 
2732     // Notice current instruction could be any index. Need to adjust the address
2733     // to the member of index 0.
2734     //
2735     // E.g.  a = A[i+1];     // Member of index 1 (Current instruction)
2736     //       b = A[i];       // Member of index 0
2737     // Current pointer is pointed to A[i+1], adjust it to A[i].
2738     //
2739     // E.g.  A[i+1] = a;     // Member of index 1
2740     //       A[i]   = b;     // Member of index 0
2741     //       A[i+2] = c;     // Member of index 2 (Current instruction)
2742     // Current pointer is pointed to A[i+2], adjust it to A[i].
2743 
2744     bool InBounds = false;
2745     if (auto *gep = dyn_cast<GetElementPtrInst>(AddrPart->stripPointerCasts()))
2746       InBounds = gep->isInBounds();
2747     AddrPart = Builder.CreateGEP(ScalarTy, AddrPart, Builder.getInt32(-Index));
2748     cast<GetElementPtrInst>(AddrPart)->setIsInBounds(InBounds);
2749 
2750     // Cast to the vector pointer type.
2751     unsigned AddressSpace = AddrPart->getType()->getPointerAddressSpace();
2752     Type *PtrTy = VecTy->getPointerTo(AddressSpace);
2753     AddrParts.push_back(Builder.CreateBitCast(AddrPart, PtrTy));
2754   }
2755 
2756   setDebugLocFromInst(Instr);
2757   Value *PoisonVec = PoisonValue::get(VecTy);
2758 
2759   Value *MaskForGaps = nullptr;
2760   if (Group->requiresScalarEpilogue() && !Cost->isScalarEpilogueAllowed()) {
2761     MaskForGaps = createBitMaskForGaps(Builder, VF.getKnownMinValue(), *Group);
2762     assert(MaskForGaps && "Mask for Gaps is required but it is null");
2763   }
2764 
2765   // Vectorize the interleaved load group.
2766   if (isa<LoadInst>(Instr)) {
2767     // For each unroll part, create a wide load for the group.
2768     SmallVector<Value *, 2> NewLoads;
2769     for (unsigned Part = 0; Part < UF; Part++) {
2770       Instruction *NewLoad;
2771       if (BlockInMask || MaskForGaps) {
2772         assert(useMaskedInterleavedAccesses(*TTI) &&
2773                "masked interleaved groups are not allowed.");
2774         Value *GroupMask = MaskForGaps;
2775         if (BlockInMask) {
2776           Value *BlockInMaskPart = State.get(BlockInMask, Part);
2777           Value *ShuffledMask = Builder.CreateShuffleVector(
2778               BlockInMaskPart,
2779               createReplicatedMask(InterleaveFactor, VF.getKnownMinValue()),
2780               "interleaved.mask");
2781           GroupMask = MaskForGaps
2782                           ? Builder.CreateBinOp(Instruction::And, ShuffledMask,
2783                                                 MaskForGaps)
2784                           : ShuffledMask;
2785         }
2786         NewLoad =
2787             Builder.CreateMaskedLoad(VecTy, AddrParts[Part], Group->getAlign(),
2788                                      GroupMask, PoisonVec, "wide.masked.vec");
2789       }
2790       else
2791         NewLoad = Builder.CreateAlignedLoad(VecTy, AddrParts[Part],
2792                                             Group->getAlign(), "wide.vec");
2793       Group->addMetadata(NewLoad);
2794       NewLoads.push_back(NewLoad);
2795     }
2796 
2797     // For each member in the group, shuffle out the appropriate data from the
2798     // wide loads.
2799     unsigned J = 0;
2800     for (unsigned I = 0; I < InterleaveFactor; ++I) {
2801       Instruction *Member = Group->getMember(I);
2802 
2803       // Skip the gaps in the group.
2804       if (!Member)
2805         continue;
2806 
2807       auto StrideMask =
2808           createStrideMask(I, InterleaveFactor, VF.getKnownMinValue());
2809       for (unsigned Part = 0; Part < UF; Part++) {
2810         Value *StridedVec = Builder.CreateShuffleVector(
2811             NewLoads[Part], StrideMask, "strided.vec");
2812 
2813         // If this member has different type, cast the result type.
2814         if (Member->getType() != ScalarTy) {
2815           assert(!VF.isScalable() && "VF is assumed to be non scalable.");
2816           VectorType *OtherVTy = VectorType::get(Member->getType(), VF);
2817           StridedVec = createBitOrPointerCast(StridedVec, OtherVTy, DL);
2818         }
2819 
2820         if (Group->isReverse())
2821           StridedVec = reverseVector(StridedVec);
2822 
2823         State.set(VPDefs[J], StridedVec, Part);
2824       }
2825       ++J;
2826     }
2827     return;
2828   }
2829 
2830   // The sub vector type for current instruction.
2831   auto *SubVT = VectorType::get(ScalarTy, VF);
2832 
2833   // Vectorize the interleaved store group.
2834   for (unsigned Part = 0; Part < UF; Part++) {
2835     // Collect the stored vector from each member.
2836     SmallVector<Value *, 4> StoredVecs;
2837     for (unsigned i = 0; i < InterleaveFactor; i++) {
2838       // Interleaved store group doesn't allow a gap, so each index has a member
2839       assert(Group->getMember(i) && "Fail to get a member from an interleaved store group");
2840 
2841       Value *StoredVec = State.get(StoredValues[i], Part);
2842 
2843       if (Group->isReverse())
2844         StoredVec = reverseVector(StoredVec);
2845 
2846       // If this member has different type, cast it to a unified type.
2847 
2848       if (StoredVec->getType() != SubVT)
2849         StoredVec = createBitOrPointerCast(StoredVec, SubVT, DL);
2850 
2851       StoredVecs.push_back(StoredVec);
2852     }
2853 
2854     // Concatenate all vectors into a wide vector.
2855     Value *WideVec = concatenateVectors(Builder, StoredVecs);
2856 
2857     // Interleave the elements in the wide vector.
2858     Value *IVec = Builder.CreateShuffleVector(
2859         WideVec, createInterleaveMask(VF.getKnownMinValue(), InterleaveFactor),
2860         "interleaved.vec");
2861 
2862     Instruction *NewStoreInstr;
2863     if (BlockInMask) {
2864       Value *BlockInMaskPart = State.get(BlockInMask, Part);
2865       Value *ShuffledMask = Builder.CreateShuffleVector(
2866           BlockInMaskPart,
2867           createReplicatedMask(InterleaveFactor, VF.getKnownMinValue()),
2868           "interleaved.mask");
2869       NewStoreInstr = Builder.CreateMaskedStore(
2870           IVec, AddrParts[Part], Group->getAlign(), ShuffledMask);
2871     }
2872     else
2873       NewStoreInstr =
2874           Builder.CreateAlignedStore(IVec, AddrParts[Part], Group->getAlign());
2875 
2876     Group->addMetadata(NewStoreInstr);
2877   }
2878 }
2879 
2880 void InnerLoopVectorizer::vectorizeMemoryInstruction(
2881     Instruction *Instr, VPTransformState &State, VPValue *Def, VPValue *Addr,
2882     VPValue *StoredValue, VPValue *BlockInMask) {
2883   // Attempt to issue a wide load.
2884   LoadInst *LI = dyn_cast<LoadInst>(Instr);
2885   StoreInst *SI = dyn_cast<StoreInst>(Instr);
2886 
2887   assert((LI || SI) && "Invalid Load/Store instruction");
2888   assert((!SI || StoredValue) && "No stored value provided for widened store");
2889   assert((!LI || !StoredValue) && "Stored value provided for widened load");
2890 
2891   LoopVectorizationCostModel::InstWidening Decision =
2892       Cost->getWideningDecision(Instr, VF);
2893   assert((Decision == LoopVectorizationCostModel::CM_Widen ||
2894           Decision == LoopVectorizationCostModel::CM_Widen_Reverse ||
2895           Decision == LoopVectorizationCostModel::CM_GatherScatter) &&
2896          "CM decision is not to widen the memory instruction");
2897 
2898   Type *ScalarDataTy = getLoadStoreType(Instr);
2899 
2900   auto *DataTy = VectorType::get(ScalarDataTy, VF);
2901   const Align Alignment = getLoadStoreAlignment(Instr);
2902 
2903   // Determine if the pointer operand of the access is either consecutive or
2904   // reverse consecutive.
2905   bool Reverse = (Decision == LoopVectorizationCostModel::CM_Widen_Reverse);
2906   bool ConsecutiveStride =
2907       Reverse || (Decision == LoopVectorizationCostModel::CM_Widen);
2908   bool CreateGatherScatter =
2909       (Decision == LoopVectorizationCostModel::CM_GatherScatter);
2910 
2911   // Either Ptr feeds a vector load/store, or a vector GEP should feed a vector
2912   // gather/scatter. Otherwise Decision should have been to Scalarize.
2913   assert((ConsecutiveStride || CreateGatherScatter) &&
2914          "The instruction should be scalarized");
2915   (void)ConsecutiveStride;
2916 
2917   VectorParts BlockInMaskParts(UF);
2918   bool isMaskRequired = BlockInMask;
2919   if (isMaskRequired)
2920     for (unsigned Part = 0; Part < UF; ++Part)
2921       BlockInMaskParts[Part] = State.get(BlockInMask, Part);
2922 
2923   const auto CreateVecPtr = [&](unsigned Part, Value *Ptr) -> Value * {
2924     // Calculate the pointer for the specific unroll-part.
2925     GetElementPtrInst *PartPtr = nullptr;
2926 
2927     bool InBounds = false;
2928     if (auto *gep = dyn_cast<GetElementPtrInst>(Ptr->stripPointerCasts()))
2929       InBounds = gep->isInBounds();
2930     if (Reverse) {
2931       // If the address is consecutive but reversed, then the
2932       // wide store needs to start at the last vector element.
2933       // RunTimeVF =  VScale * VF.getKnownMinValue()
2934       // For fixed-width VScale is 1, then RunTimeVF = VF.getKnownMinValue()
2935       Value *RunTimeVF = getRuntimeVF(Builder, Builder.getInt32Ty(), VF);
2936       // NumElt = -Part * RunTimeVF
2937       Value *NumElt = Builder.CreateMul(Builder.getInt32(-Part), RunTimeVF);
2938       // LastLane = 1 - RunTimeVF
2939       Value *LastLane = Builder.CreateSub(Builder.getInt32(1), RunTimeVF);
2940       PartPtr =
2941           cast<GetElementPtrInst>(Builder.CreateGEP(ScalarDataTy, Ptr, NumElt));
2942       PartPtr->setIsInBounds(InBounds);
2943       PartPtr = cast<GetElementPtrInst>(
2944           Builder.CreateGEP(ScalarDataTy, PartPtr, LastLane));
2945       PartPtr->setIsInBounds(InBounds);
2946       if (isMaskRequired) // Reverse of a null all-one mask is a null mask.
2947         BlockInMaskParts[Part] = reverseVector(BlockInMaskParts[Part]);
2948     } else {
2949       Value *Increment = createStepForVF(Builder, Builder.getInt32(Part), VF);
2950       PartPtr = cast<GetElementPtrInst>(
2951           Builder.CreateGEP(ScalarDataTy, Ptr, Increment));
2952       PartPtr->setIsInBounds(InBounds);
2953     }
2954 
2955     unsigned AddressSpace = Ptr->getType()->getPointerAddressSpace();
2956     return Builder.CreateBitCast(PartPtr, DataTy->getPointerTo(AddressSpace));
2957   };
2958 
2959   // Handle Stores:
2960   if (SI) {
2961     setDebugLocFromInst(SI);
2962 
2963     for (unsigned Part = 0; Part < UF; ++Part) {
2964       Instruction *NewSI = nullptr;
2965       Value *StoredVal = State.get(StoredValue, Part);
2966       if (CreateGatherScatter) {
2967         Value *MaskPart = isMaskRequired ? BlockInMaskParts[Part] : nullptr;
2968         Value *VectorGep = State.get(Addr, Part);
2969         NewSI = Builder.CreateMaskedScatter(StoredVal, VectorGep, Alignment,
2970                                             MaskPart);
2971       } else {
2972         if (Reverse) {
2973           // If we store to reverse consecutive memory locations, then we need
2974           // to reverse the order of elements in the stored value.
2975           StoredVal = reverseVector(StoredVal);
2976           // We don't want to update the value in the map as it might be used in
2977           // another expression. So don't call resetVectorValue(StoredVal).
2978         }
2979         auto *VecPtr = CreateVecPtr(Part, State.get(Addr, VPIteration(0, 0)));
2980         if (isMaskRequired)
2981           NewSI = Builder.CreateMaskedStore(StoredVal, VecPtr, Alignment,
2982                                             BlockInMaskParts[Part]);
2983         else
2984           NewSI = Builder.CreateAlignedStore(StoredVal, VecPtr, Alignment);
2985       }
2986       addMetadata(NewSI, SI);
2987     }
2988     return;
2989   }
2990 
2991   // Handle loads.
2992   assert(LI && "Must have a load instruction");
2993   setDebugLocFromInst(LI);
2994   for (unsigned Part = 0; Part < UF; ++Part) {
2995     Value *NewLI;
2996     if (CreateGatherScatter) {
2997       Value *MaskPart = isMaskRequired ? BlockInMaskParts[Part] : nullptr;
2998       Value *VectorGep = State.get(Addr, Part);
2999       NewLI = Builder.CreateMaskedGather(DataTy, VectorGep, Alignment, MaskPart,
3000                                          nullptr, "wide.masked.gather");
3001       addMetadata(NewLI, LI);
3002     } else {
3003       auto *VecPtr = CreateVecPtr(Part, State.get(Addr, VPIteration(0, 0)));
3004       if (isMaskRequired)
3005         NewLI = Builder.CreateMaskedLoad(
3006             DataTy, VecPtr, Alignment, BlockInMaskParts[Part],
3007             PoisonValue::get(DataTy), "wide.masked.load");
3008       else
3009         NewLI =
3010             Builder.CreateAlignedLoad(DataTy, VecPtr, Alignment, "wide.load");
3011 
3012       // Add metadata to the load, but setVectorValue to the reverse shuffle.
3013       addMetadata(NewLI, LI);
3014       if (Reverse)
3015         NewLI = reverseVector(NewLI);
3016     }
3017 
3018     State.set(Def, NewLI, Part);
3019   }
3020 }
3021 
3022 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr, VPValue *Def,
3023                                                VPUser &User,
3024                                                const VPIteration &Instance,
3025                                                bool IfPredicateInstr,
3026                                                VPTransformState &State) {
3027   assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
3028 
3029   // llvm.experimental.noalias.scope.decl intrinsics must only be duplicated for
3030   // the first lane and part.
3031   if (isa<NoAliasScopeDeclInst>(Instr))
3032     if (!Instance.isFirstIteration())
3033       return;
3034 
3035   setDebugLocFromInst(Instr);
3036 
3037   // Does this instruction return a value ?
3038   bool IsVoidRetTy = Instr->getType()->isVoidTy();
3039 
3040   Instruction *Cloned = Instr->clone();
3041   if (!IsVoidRetTy)
3042     Cloned->setName(Instr->getName() + ".cloned");
3043 
3044   State.Builder.SetInsertPoint(Builder.GetInsertBlock(),
3045                                Builder.GetInsertPoint());
3046   // Replace the operands of the cloned instructions with their scalar
3047   // equivalents in the new loop.
3048   for (unsigned op = 0, e = User.getNumOperands(); op != e; ++op) {
3049     auto *Operand = dyn_cast<Instruction>(Instr->getOperand(op));
3050     auto InputInstance = Instance;
3051     if (!Operand || !OrigLoop->contains(Operand) ||
3052         (Cost->isUniformAfterVectorization(Operand, State.VF)))
3053       InputInstance.Lane = VPLane::getFirstLane();
3054     auto *NewOp = State.get(User.getOperand(op), InputInstance);
3055     Cloned->setOperand(op, NewOp);
3056   }
3057   addNewMetadata(Cloned, Instr);
3058 
3059   // Place the cloned scalar in the new loop.
3060   Builder.Insert(Cloned);
3061 
3062   State.set(Def, Cloned, Instance);
3063 
3064   // If we just cloned a new assumption, add it the assumption cache.
3065   if (auto *II = dyn_cast<AssumeInst>(Cloned))
3066     AC->registerAssumption(II);
3067 
3068   // End if-block.
3069   if (IfPredicateInstr)
3070     PredicatedInstructions.push_back(Cloned);
3071 }
3072 
3073 PHINode *InnerLoopVectorizer::createInductionVariable(Loop *L, Value *Start,
3074                                                       Value *End, Value *Step,
3075                                                       Instruction *DL) {
3076   BasicBlock *Header = L->getHeader();
3077   BasicBlock *Latch = L->getLoopLatch();
3078   // As we're just creating this loop, it's possible no latch exists
3079   // yet. If so, use the header as this will be a single block loop.
3080   if (!Latch)
3081     Latch = Header;
3082 
3083   IRBuilder<> B(&*Header->getFirstInsertionPt());
3084   Instruction *OldInst = getDebugLocFromInstOrOperands(OldInduction);
3085   setDebugLocFromInst(OldInst, &B);
3086   auto *Induction = B.CreatePHI(Start->getType(), 2, "index");
3087 
3088   B.SetInsertPoint(Latch->getTerminator());
3089   setDebugLocFromInst(OldInst, &B);
3090 
3091   // Create i+1 and fill the PHINode.
3092   //
3093   // If the tail is not folded, we know that End - Start >= Step (either
3094   // statically or through the minimum iteration checks). We also know that both
3095   // Start % Step == 0 and End % Step == 0. We exit the vector loop if %IV +
3096   // %Step == %End. Hence we must exit the loop before %IV + %Step unsigned
3097   // overflows and we can mark the induction increment as NUW.
3098   Value *Next = B.CreateAdd(Induction, Step, "index.next",
3099                             /*NUW=*/!Cost->foldTailByMasking(), /*NSW=*/false);
3100   Induction->addIncoming(Start, L->getLoopPreheader());
3101   Induction->addIncoming(Next, Latch);
3102   // Create the compare.
3103   Value *ICmp = B.CreateICmpEQ(Next, End);
3104   B.CreateCondBr(ICmp, L->getUniqueExitBlock(), Header);
3105 
3106   // Now we have two terminators. Remove the old one from the block.
3107   Latch->getTerminator()->eraseFromParent();
3108 
3109   return Induction;
3110 }
3111 
3112 Value *InnerLoopVectorizer::getOrCreateTripCount(Loop *L) {
3113   if (TripCount)
3114     return TripCount;
3115 
3116   assert(L && "Create Trip Count for null loop.");
3117   IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
3118   // Find the loop boundaries.
3119   ScalarEvolution *SE = PSE.getSE();
3120   const SCEV *BackedgeTakenCount = PSE.getBackedgeTakenCount();
3121   assert(!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
3122          "Invalid loop count");
3123 
3124   Type *IdxTy = Legal->getWidestInductionType();
3125   assert(IdxTy && "No type for induction");
3126 
3127   // The exit count might have the type of i64 while the phi is i32. This can
3128   // happen if we have an induction variable that is sign extended before the
3129   // compare. The only way that we get a backedge taken count is that the
3130   // induction variable was signed and as such will not overflow. In such a case
3131   // truncation is legal.
3132   if (SE->getTypeSizeInBits(BackedgeTakenCount->getType()) >
3133       IdxTy->getPrimitiveSizeInBits())
3134     BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount, IdxTy);
3135   BackedgeTakenCount = SE->getNoopOrZeroExtend(BackedgeTakenCount, IdxTy);
3136 
3137   // Get the total trip count from the count by adding 1.
3138   const SCEV *ExitCount = SE->getAddExpr(
3139       BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType()));
3140 
3141   const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
3142 
3143   // Expand the trip count and place the new instructions in the preheader.
3144   // Notice that the pre-header does not change, only the loop body.
3145   SCEVExpander Exp(*SE, DL, "induction");
3146 
3147   // Count holds the overall loop count (N).
3148   TripCount = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
3149                                 L->getLoopPreheader()->getTerminator());
3150 
3151   if (TripCount->getType()->isPointerTy())
3152     TripCount =
3153         CastInst::CreatePointerCast(TripCount, IdxTy, "exitcount.ptrcnt.to.int",
3154                                     L->getLoopPreheader()->getTerminator());
3155 
3156   return TripCount;
3157 }
3158 
3159 Value *InnerLoopVectorizer::getOrCreateVectorTripCount(Loop *L) {
3160   if (VectorTripCount)
3161     return VectorTripCount;
3162 
3163   Value *TC = getOrCreateTripCount(L);
3164   IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
3165 
3166   Type *Ty = TC->getType();
3167   // This is where we can make the step a runtime constant.
3168   Value *Step = createStepForVF(Builder, ConstantInt::get(Ty, UF), VF);
3169 
3170   // If the tail is to be folded by masking, round the number of iterations N
3171   // up to a multiple of Step instead of rounding down. This is done by first
3172   // adding Step-1 and then rounding down. Note that it's ok if this addition
3173   // overflows: the vector induction variable will eventually wrap to zero given
3174   // that it starts at zero and its Step is a power of two; the loop will then
3175   // exit, with the last early-exit vector comparison also producing all-true.
3176   if (Cost->foldTailByMasking()) {
3177     assert(isPowerOf2_32(VF.getKnownMinValue() * UF) &&
3178            "VF*UF must be a power of 2 when folding tail by masking");
3179     assert(!VF.isScalable() &&
3180            "Tail folding not yet supported for scalable vectors");
3181     TC = Builder.CreateAdd(
3182         TC, ConstantInt::get(Ty, VF.getKnownMinValue() * UF - 1), "n.rnd.up");
3183   }
3184 
3185   // Now we need to generate the expression for the part of the loop that the
3186   // vectorized body will execute. This is equal to N - (N % Step) if scalar
3187   // iterations are not required for correctness, or N - Step, otherwise. Step
3188   // is equal to the vectorization factor (number of SIMD elements) times the
3189   // unroll factor (number of SIMD instructions).
3190   Value *R = Builder.CreateURem(TC, Step, "n.mod.vf");
3191 
3192   // There are cases where we *must* run at least one iteration in the remainder
3193   // loop.  See the cost model for when this can happen.  If the step evenly
3194   // divides the trip count, we set the remainder to be equal to the step. If
3195   // the step does not evenly divide the trip count, no adjustment is necessary
3196   // since there will already be scalar iterations. Note that the minimum
3197   // iterations check ensures that N >= Step.
3198   if (Cost->requiresScalarEpilogue(VF)) {
3199     auto *IsZero = Builder.CreateICmpEQ(R, ConstantInt::get(R->getType(), 0));
3200     R = Builder.CreateSelect(IsZero, Step, R);
3201   }
3202 
3203   VectorTripCount = Builder.CreateSub(TC, R, "n.vec");
3204 
3205   return VectorTripCount;
3206 }
3207 
3208 Value *InnerLoopVectorizer::createBitOrPointerCast(Value *V, VectorType *DstVTy,
3209                                                    const DataLayout &DL) {
3210   // Verify that V is a vector type with same number of elements as DstVTy.
3211   auto *DstFVTy = cast<FixedVectorType>(DstVTy);
3212   unsigned VF = DstFVTy->getNumElements();
3213   auto *SrcVecTy = cast<FixedVectorType>(V->getType());
3214   assert((VF == SrcVecTy->getNumElements()) && "Vector dimensions do not match");
3215   Type *SrcElemTy = SrcVecTy->getElementType();
3216   Type *DstElemTy = DstFVTy->getElementType();
3217   assert((DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy)) &&
3218          "Vector elements must have same size");
3219 
3220   // Do a direct cast if element types are castable.
3221   if (CastInst::isBitOrNoopPointerCastable(SrcElemTy, DstElemTy, DL)) {
3222     return Builder.CreateBitOrPointerCast(V, DstFVTy);
3223   }
3224   // V cannot be directly casted to desired vector type.
3225   // May happen when V is a floating point vector but DstVTy is a vector of
3226   // pointers or vice-versa. Handle this using a two-step bitcast using an
3227   // intermediate Integer type for the bitcast i.e. Ptr <-> Int <-> Float.
3228   assert((DstElemTy->isPointerTy() != SrcElemTy->isPointerTy()) &&
3229          "Only one type should be a pointer type");
3230   assert((DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy()) &&
3231          "Only one type should be a floating point type");
3232   Type *IntTy =
3233       IntegerType::getIntNTy(V->getContext(), DL.getTypeSizeInBits(SrcElemTy));
3234   auto *VecIntTy = FixedVectorType::get(IntTy, VF);
3235   Value *CastVal = Builder.CreateBitOrPointerCast(V, VecIntTy);
3236   return Builder.CreateBitOrPointerCast(CastVal, DstFVTy);
3237 }
3238 
3239 void InnerLoopVectorizer::emitMinimumIterationCountCheck(Loop *L,
3240                                                          BasicBlock *Bypass) {
3241   Value *Count = getOrCreateTripCount(L);
3242   // Reuse existing vector loop preheader for TC checks.
3243   // Note that new preheader block is generated for vector loop.
3244   BasicBlock *const TCCheckBlock = LoopVectorPreHeader;
3245   IRBuilder<> Builder(TCCheckBlock->getTerminator());
3246 
3247   // Generate code to check if the loop's trip count is less than VF * UF, or
3248   // equal to it in case a scalar epilogue is required; this implies that the
3249   // vector trip count is zero. This check also covers the case where adding one
3250   // to the backedge-taken count overflowed leading to an incorrect trip count
3251   // of zero. In this case we will also jump to the scalar loop.
3252   auto P = Cost->requiresScalarEpilogue(VF) ? ICmpInst::ICMP_ULE
3253                                             : ICmpInst::ICMP_ULT;
3254 
3255   // If tail is to be folded, vector loop takes care of all iterations.
3256   Value *CheckMinIters = Builder.getFalse();
3257   if (!Cost->foldTailByMasking()) {
3258     Value *Step =
3259         createStepForVF(Builder, ConstantInt::get(Count->getType(), UF), VF);
3260     CheckMinIters = Builder.CreateICmp(P, Count, Step, "min.iters.check");
3261   }
3262   // Create new preheader for vector loop.
3263   LoopVectorPreHeader =
3264       SplitBlock(TCCheckBlock, TCCheckBlock->getTerminator(), DT, LI, nullptr,
3265                  "vector.ph");
3266 
3267   assert(DT->properlyDominates(DT->getNode(TCCheckBlock),
3268                                DT->getNode(Bypass)->getIDom()) &&
3269          "TC check is expected to dominate Bypass");
3270 
3271   // Update dominator for Bypass & LoopExit (if needed).
3272   DT->changeImmediateDominator(Bypass, TCCheckBlock);
3273   if (!Cost->requiresScalarEpilogue(VF))
3274     // If there is an epilogue which must run, there's no edge from the
3275     // middle block to exit blocks  and thus no need to update the immediate
3276     // dominator of the exit blocks.
3277     DT->changeImmediateDominator(LoopExitBlock, TCCheckBlock);
3278 
3279   ReplaceInstWithInst(
3280       TCCheckBlock->getTerminator(),
3281       BranchInst::Create(Bypass, LoopVectorPreHeader, CheckMinIters));
3282   LoopBypassBlocks.push_back(TCCheckBlock);
3283 }
3284 
3285 BasicBlock *InnerLoopVectorizer::emitSCEVChecks(Loop *L, BasicBlock *Bypass) {
3286 
3287   BasicBlock *const SCEVCheckBlock =
3288       RTChecks.emitSCEVChecks(L, Bypass, LoopVectorPreHeader, LoopExitBlock);
3289   if (!SCEVCheckBlock)
3290     return nullptr;
3291 
3292   assert(!(SCEVCheckBlock->getParent()->hasOptSize() ||
3293            (OptForSizeBasedOnProfile &&
3294             Cost->Hints->getForce() != LoopVectorizeHints::FK_Enabled)) &&
3295          "Cannot SCEV check stride or overflow when optimizing for size");
3296 
3297 
3298   // Update dominator only if this is first RT check.
3299   if (LoopBypassBlocks.empty()) {
3300     DT->changeImmediateDominator(Bypass, SCEVCheckBlock);
3301     if (!Cost->requiresScalarEpilogue(VF))
3302       // If there is an epilogue which must run, there's no edge from the
3303       // middle block to exit blocks  and thus no need to update the immediate
3304       // dominator of the exit blocks.
3305       DT->changeImmediateDominator(LoopExitBlock, SCEVCheckBlock);
3306   }
3307 
3308   LoopBypassBlocks.push_back(SCEVCheckBlock);
3309   AddedSafetyChecks = true;
3310   return SCEVCheckBlock;
3311 }
3312 
3313 BasicBlock *InnerLoopVectorizer::emitMemRuntimeChecks(Loop *L,
3314                                                       BasicBlock *Bypass) {
3315   // VPlan-native path does not do any analysis for runtime checks currently.
3316   if (EnableVPlanNativePath)
3317     return nullptr;
3318 
3319   BasicBlock *const MemCheckBlock =
3320       RTChecks.emitMemRuntimeChecks(L, Bypass, LoopVectorPreHeader);
3321 
3322   // Check if we generated code that checks in runtime if arrays overlap. We put
3323   // the checks into a separate block to make the more common case of few
3324   // elements faster.
3325   if (!MemCheckBlock)
3326     return nullptr;
3327 
3328   if (MemCheckBlock->getParent()->hasOptSize() || OptForSizeBasedOnProfile) {
3329     assert(Cost->Hints->getForce() == LoopVectorizeHints::FK_Enabled &&
3330            "Cannot emit memory checks when optimizing for size, unless forced "
3331            "to vectorize.");
3332     ORE->emit([&]() {
3333       return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationCodeSize",
3334                                         L->getStartLoc(), L->getHeader())
3335              << "Code-size may be reduced by not forcing "
3336                 "vectorization, or by source-code modifications "
3337                 "eliminating the need for runtime checks "
3338                 "(e.g., adding 'restrict').";
3339     });
3340   }
3341 
3342   LoopBypassBlocks.push_back(MemCheckBlock);
3343 
3344   AddedSafetyChecks = true;
3345 
3346   // We currently don't use LoopVersioning for the actual loop cloning but we
3347   // still use it to add the noalias metadata.
3348   LVer = std::make_unique<LoopVersioning>(
3349       *Legal->getLAI(),
3350       Legal->getLAI()->getRuntimePointerChecking()->getChecks(), OrigLoop, LI,
3351       DT, PSE.getSE());
3352   LVer->prepareNoAliasMetadata();
3353   return MemCheckBlock;
3354 }
3355 
3356 Value *InnerLoopVectorizer::emitTransformedIndex(
3357     IRBuilder<> &B, Value *Index, ScalarEvolution *SE, const DataLayout &DL,
3358     const InductionDescriptor &ID) const {
3359 
3360   SCEVExpander Exp(*SE, DL, "induction");
3361   auto Step = ID.getStep();
3362   auto StartValue = ID.getStartValue();
3363   assert(Index->getType()->getScalarType() == Step->getType() &&
3364          "Index scalar type does not match StepValue type");
3365 
3366   // Note: the IR at this point is broken. We cannot use SE to create any new
3367   // SCEV and then expand it, hoping that SCEV's simplification will give us
3368   // a more optimal code. Unfortunately, attempt of doing so on invalid IR may
3369   // lead to various SCEV crashes. So all we can do is to use builder and rely
3370   // on InstCombine for future simplifications. Here we handle some trivial
3371   // cases only.
3372   auto CreateAdd = [&B](Value *X, Value *Y) {
3373     assert(X->getType() == Y->getType() && "Types don't match!");
3374     if (auto *CX = dyn_cast<ConstantInt>(X))
3375       if (CX->isZero())
3376         return Y;
3377     if (auto *CY = dyn_cast<ConstantInt>(Y))
3378       if (CY->isZero())
3379         return X;
3380     return B.CreateAdd(X, Y);
3381   };
3382 
3383   // We allow X to be a vector type, in which case Y will potentially be
3384   // splatted into a vector with the same element count.
3385   auto CreateMul = [&B](Value *X, Value *Y) {
3386     assert(X->getType()->getScalarType() == Y->getType() &&
3387            "Types don't match!");
3388     if (auto *CX = dyn_cast<ConstantInt>(X))
3389       if (CX->isOne())
3390         return Y;
3391     if (auto *CY = dyn_cast<ConstantInt>(Y))
3392       if (CY->isOne())
3393         return X;
3394     VectorType *XVTy = dyn_cast<VectorType>(X->getType());
3395     if (XVTy && !isa<VectorType>(Y->getType()))
3396       Y = B.CreateVectorSplat(XVTy->getElementCount(), Y);
3397     return B.CreateMul(X, Y);
3398   };
3399 
3400   // Get a suitable insert point for SCEV expansion. For blocks in the vector
3401   // loop, choose the end of the vector loop header (=LoopVectorBody), because
3402   // the DomTree is not kept up-to-date for additional blocks generated in the
3403   // vector loop. By using the header as insertion point, we guarantee that the
3404   // expanded instructions dominate all their uses.
3405   auto GetInsertPoint = [this, &B]() {
3406     BasicBlock *InsertBB = B.GetInsertPoint()->getParent();
3407     if (InsertBB != LoopVectorBody &&
3408         LI->getLoopFor(LoopVectorBody) == LI->getLoopFor(InsertBB))
3409       return LoopVectorBody->getTerminator();
3410     return &*B.GetInsertPoint();
3411   };
3412 
3413   switch (ID.getKind()) {
3414   case InductionDescriptor::IK_IntInduction: {
3415     assert(!isa<VectorType>(Index->getType()) &&
3416            "Vector indices not supported for integer inductions yet");
3417     assert(Index->getType() == StartValue->getType() &&
3418            "Index type does not match StartValue type");
3419     if (ID.getConstIntStepValue() && ID.getConstIntStepValue()->isMinusOne())
3420       return B.CreateSub(StartValue, Index);
3421     auto *Offset = CreateMul(
3422         Index, Exp.expandCodeFor(Step, Index->getType(), GetInsertPoint()));
3423     return CreateAdd(StartValue, Offset);
3424   }
3425   case InductionDescriptor::IK_PtrInduction: {
3426     assert(isa<SCEVConstant>(Step) &&
3427            "Expected constant step for pointer induction");
3428     return B.CreateGEP(
3429         StartValue->getType()->getPointerElementType(), StartValue,
3430         CreateMul(Index,
3431                   Exp.expandCodeFor(Step, Index->getType()->getScalarType(),
3432                                     GetInsertPoint())));
3433   }
3434   case InductionDescriptor::IK_FpInduction: {
3435     assert(!isa<VectorType>(Index->getType()) &&
3436            "Vector indices not supported for FP inductions yet");
3437     assert(Step->getType()->isFloatingPointTy() && "Expected FP Step value");
3438     auto InductionBinOp = ID.getInductionBinOp();
3439     assert(InductionBinOp &&
3440            (InductionBinOp->getOpcode() == Instruction::FAdd ||
3441             InductionBinOp->getOpcode() == Instruction::FSub) &&
3442            "Original bin op should be defined for FP induction");
3443 
3444     Value *StepValue = cast<SCEVUnknown>(Step)->getValue();
3445     Value *MulExp = B.CreateFMul(StepValue, Index);
3446     return B.CreateBinOp(InductionBinOp->getOpcode(), StartValue, MulExp,
3447                          "induction");
3448   }
3449   case InductionDescriptor::IK_NoInduction:
3450     return nullptr;
3451   }
3452   llvm_unreachable("invalid enum");
3453 }
3454 
3455 Loop *InnerLoopVectorizer::createVectorLoopSkeleton(StringRef Prefix) {
3456   LoopScalarBody = OrigLoop->getHeader();
3457   LoopVectorPreHeader = OrigLoop->getLoopPreheader();
3458   assert(LoopVectorPreHeader && "Invalid loop structure");
3459   LoopExitBlock = OrigLoop->getUniqueExitBlock(); // may be nullptr
3460   assert((LoopExitBlock || Cost->requiresScalarEpilogue(VF)) &&
3461          "multiple exit loop without required epilogue?");
3462 
3463   LoopMiddleBlock =
3464       SplitBlock(LoopVectorPreHeader, LoopVectorPreHeader->getTerminator(), DT,
3465                  LI, nullptr, Twine(Prefix) + "middle.block");
3466   LoopScalarPreHeader =
3467       SplitBlock(LoopMiddleBlock, LoopMiddleBlock->getTerminator(), DT, LI,
3468                  nullptr, Twine(Prefix) + "scalar.ph");
3469 
3470   auto *ScalarLatchTerm = OrigLoop->getLoopLatch()->getTerminator();
3471 
3472   // Set up the middle block terminator.  Two cases:
3473   // 1) If we know that we must execute the scalar epilogue, emit an
3474   //    unconditional branch.
3475   // 2) Otherwise, we must have a single unique exit block (due to how we
3476   //    implement the multiple exit case).  In this case, set up a conditonal
3477   //    branch from the middle block to the loop scalar preheader, and the
3478   //    exit block.  completeLoopSkeleton will update the condition to use an
3479   //    iteration check, if required to decide whether to execute the remainder.
3480   BranchInst *BrInst = Cost->requiresScalarEpilogue(VF) ?
3481     BranchInst::Create(LoopScalarPreHeader) :
3482     BranchInst::Create(LoopExitBlock, LoopScalarPreHeader,
3483                        Builder.getTrue());
3484   BrInst->setDebugLoc(ScalarLatchTerm->getDebugLoc());
3485   ReplaceInstWithInst(LoopMiddleBlock->getTerminator(), BrInst);
3486 
3487   // We intentionally don't let SplitBlock to update LoopInfo since
3488   // LoopVectorBody should belong to another loop than LoopVectorPreHeader.
3489   // LoopVectorBody is explicitly added to the correct place few lines later.
3490   LoopVectorBody =
3491       SplitBlock(LoopVectorPreHeader, LoopVectorPreHeader->getTerminator(), DT,
3492                  nullptr, nullptr, Twine(Prefix) + "vector.body");
3493 
3494   // Update dominator for loop exit.
3495   if (!Cost->requiresScalarEpilogue(VF))
3496     // If there is an epilogue which must run, there's no edge from the
3497     // middle block to exit blocks  and thus no need to update the immediate
3498     // dominator of the exit blocks.
3499     DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
3500 
3501   // Create and register the new vector loop.
3502   Loop *Lp = LI->AllocateLoop();
3503   Loop *ParentLoop = OrigLoop->getParentLoop();
3504 
3505   // Insert the new loop into the loop nest and register the new basic blocks
3506   // before calling any utilities such as SCEV that require valid LoopInfo.
3507   if (ParentLoop) {
3508     ParentLoop->addChildLoop(Lp);
3509   } else {
3510     LI->addTopLevelLoop(Lp);
3511   }
3512   Lp->addBasicBlockToLoop(LoopVectorBody, *LI);
3513   return Lp;
3514 }
3515 
3516 void InnerLoopVectorizer::createInductionResumeValues(
3517     Loop *L, Value *VectorTripCount,
3518     std::pair<BasicBlock *, Value *> AdditionalBypass) {
3519   assert(VectorTripCount && L && "Expected valid arguments");
3520   assert(((AdditionalBypass.first && AdditionalBypass.second) ||
3521           (!AdditionalBypass.first && !AdditionalBypass.second)) &&
3522          "Inconsistent information about additional bypass.");
3523   // We are going to resume the execution of the scalar loop.
3524   // Go over all of the induction variables that we found and fix the
3525   // PHIs that are left in the scalar version of the loop.
3526   // The starting values of PHI nodes depend on the counter of the last
3527   // iteration in the vectorized loop.
3528   // If we come from a bypass edge then we need to start from the original
3529   // start value.
3530   for (auto &InductionEntry : Legal->getInductionVars()) {
3531     PHINode *OrigPhi = InductionEntry.first;
3532     InductionDescriptor II = InductionEntry.second;
3533 
3534     // Create phi nodes to merge from the  backedge-taken check block.
3535     PHINode *BCResumeVal =
3536         PHINode::Create(OrigPhi->getType(), 3, "bc.resume.val",
3537                         LoopScalarPreHeader->getTerminator());
3538     // Copy original phi DL over to the new one.
3539     BCResumeVal->setDebugLoc(OrigPhi->getDebugLoc());
3540     Value *&EndValue = IVEndValues[OrigPhi];
3541     Value *EndValueFromAdditionalBypass = AdditionalBypass.second;
3542     if (OrigPhi == OldInduction) {
3543       // We know what the end value is.
3544       EndValue = VectorTripCount;
3545     } else {
3546       IRBuilder<> B(L->getLoopPreheader()->getTerminator());
3547 
3548       // Fast-math-flags propagate from the original induction instruction.
3549       if (II.getInductionBinOp() && isa<FPMathOperator>(II.getInductionBinOp()))
3550         B.setFastMathFlags(II.getInductionBinOp()->getFastMathFlags());
3551 
3552       Type *StepType = II.getStep()->getType();
3553       Instruction::CastOps CastOp =
3554           CastInst::getCastOpcode(VectorTripCount, true, StepType, true);
3555       Value *CRD = B.CreateCast(CastOp, VectorTripCount, StepType, "cast.crd");
3556       const DataLayout &DL = LoopScalarBody->getModule()->getDataLayout();
3557       EndValue = emitTransformedIndex(B, CRD, PSE.getSE(), DL, II);
3558       EndValue->setName("ind.end");
3559 
3560       // Compute the end value for the additional bypass (if applicable).
3561       if (AdditionalBypass.first) {
3562         B.SetInsertPoint(&(*AdditionalBypass.first->getFirstInsertionPt()));
3563         CastOp = CastInst::getCastOpcode(AdditionalBypass.second, true,
3564                                          StepType, true);
3565         CRD =
3566             B.CreateCast(CastOp, AdditionalBypass.second, StepType, "cast.crd");
3567         EndValueFromAdditionalBypass =
3568             emitTransformedIndex(B, CRD, PSE.getSE(), DL, II);
3569         EndValueFromAdditionalBypass->setName("ind.end");
3570       }
3571     }
3572     // The new PHI merges the original incoming value, in case of a bypass,
3573     // or the value at the end of the vectorized loop.
3574     BCResumeVal->addIncoming(EndValue, LoopMiddleBlock);
3575 
3576     // Fix the scalar body counter (PHI node).
3577     // The old induction's phi node in the scalar body needs the truncated
3578     // value.
3579     for (BasicBlock *BB : LoopBypassBlocks)
3580       BCResumeVal->addIncoming(II.getStartValue(), BB);
3581 
3582     if (AdditionalBypass.first)
3583       BCResumeVal->setIncomingValueForBlock(AdditionalBypass.first,
3584                                             EndValueFromAdditionalBypass);
3585 
3586     OrigPhi->setIncomingValueForBlock(LoopScalarPreHeader, BCResumeVal);
3587   }
3588 }
3589 
3590 BasicBlock *InnerLoopVectorizer::completeLoopSkeleton(Loop *L,
3591                                                       MDNode *OrigLoopID) {
3592   assert(L && "Expected valid loop.");
3593 
3594   // The trip counts should be cached by now.
3595   Value *Count = getOrCreateTripCount(L);
3596   Value *VectorTripCount = getOrCreateVectorTripCount(L);
3597 
3598   auto *ScalarLatchTerm = OrigLoop->getLoopLatch()->getTerminator();
3599 
3600   // Add a check in the middle block to see if we have completed
3601   // all of the iterations in the first vector loop.  Three cases:
3602   // 1) If we require a scalar epilogue, there is no conditional branch as
3603   //    we unconditionally branch to the scalar preheader.  Do nothing.
3604   // 2) If (N - N%VF) == N, then we *don't* need to run the remainder.
3605   //    Thus if tail is to be folded, we know we don't need to run the
3606   //    remainder and we can use the previous value for the condition (true).
3607   // 3) Otherwise, construct a runtime check.
3608   if (!Cost->requiresScalarEpilogue(VF) && !Cost->foldTailByMasking()) {
3609     Instruction *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
3610                                         Count, VectorTripCount, "cmp.n",
3611                                         LoopMiddleBlock->getTerminator());
3612 
3613     // Here we use the same DebugLoc as the scalar loop latch terminator instead
3614     // of the corresponding compare because they may have ended up with
3615     // different line numbers and we want to avoid awkward line stepping while
3616     // debugging. Eg. if the compare has got a line number inside the loop.
3617     CmpN->setDebugLoc(ScalarLatchTerm->getDebugLoc());
3618     cast<BranchInst>(LoopMiddleBlock->getTerminator())->setCondition(CmpN);
3619   }
3620 
3621   // Get ready to start creating new instructions into the vectorized body.
3622   assert(LoopVectorPreHeader == L->getLoopPreheader() &&
3623          "Inconsistent vector loop preheader");
3624   Builder.SetInsertPoint(&*LoopVectorBody->getFirstInsertionPt());
3625 
3626   Optional<MDNode *> VectorizedLoopID =
3627       makeFollowupLoopID(OrigLoopID, {LLVMLoopVectorizeFollowupAll,
3628                                       LLVMLoopVectorizeFollowupVectorized});
3629   if (VectorizedLoopID.hasValue()) {
3630     L->setLoopID(VectorizedLoopID.getValue());
3631 
3632     // Do not setAlreadyVectorized if loop attributes have been defined
3633     // explicitly.
3634     return LoopVectorPreHeader;
3635   }
3636 
3637   // Keep all loop hints from the original loop on the vector loop (we'll
3638   // replace the vectorizer-specific hints below).
3639   if (MDNode *LID = OrigLoop->getLoopID())
3640     L->setLoopID(LID);
3641 
3642   LoopVectorizeHints Hints(L, true, *ORE);
3643   Hints.setAlreadyVectorized();
3644 
3645 #ifdef EXPENSIVE_CHECKS
3646   assert(DT->verify(DominatorTree::VerificationLevel::Fast));
3647   LI->verify(*DT);
3648 #endif
3649 
3650   return LoopVectorPreHeader;
3651 }
3652 
3653 BasicBlock *InnerLoopVectorizer::createVectorizedLoopSkeleton() {
3654   /*
3655    In this function we generate a new loop. The new loop will contain
3656    the vectorized instructions while the old loop will continue to run the
3657    scalar remainder.
3658 
3659        [ ] <-- loop iteration number check.
3660     /   |
3661    /    v
3662   |    [ ] <-- vector loop bypass (may consist of multiple blocks).
3663   |  /  |
3664   | /   v
3665   ||   [ ]     <-- vector pre header.
3666   |/    |
3667   |     v
3668   |    [  ] \
3669   |    [  ]_|   <-- vector loop.
3670   |     |
3671   |     v
3672   \   -[ ]   <--- middle-block.
3673    \/   |
3674    /\   v
3675    | ->[ ]     <--- new preheader.
3676    |    |
3677  (opt)  v      <-- edge from middle to exit iff epilogue is not required.
3678    |   [ ] \
3679    |   [ ]_|   <-- old scalar loop to handle remainder (scalar epilogue).
3680     \   |
3681      \  v
3682       >[ ]     <-- exit block(s).
3683    ...
3684    */
3685 
3686   // Get the metadata of the original loop before it gets modified.
3687   MDNode *OrigLoopID = OrigLoop->getLoopID();
3688 
3689   // Workaround!  Compute the trip count of the original loop and cache it
3690   // before we start modifying the CFG.  This code has a systemic problem
3691   // wherein it tries to run analysis over partially constructed IR; this is
3692   // wrong, and not simply for SCEV.  The trip count of the original loop
3693   // simply happens to be prone to hitting this in practice.  In theory, we
3694   // can hit the same issue for any SCEV, or ValueTracking query done during
3695   // mutation.  See PR49900.
3696   getOrCreateTripCount(OrigLoop);
3697 
3698   // Create an empty vector loop, and prepare basic blocks for the runtime
3699   // checks.
3700   Loop *Lp = createVectorLoopSkeleton("");
3701 
3702   // Now, compare the new count to zero. If it is zero skip the vector loop and
3703   // jump to the scalar loop. This check also covers the case where the
3704   // backedge-taken count is uint##_max: adding one to it will overflow leading
3705   // to an incorrect trip count of zero. In this (rare) case we will also jump
3706   // to the scalar loop.
3707   emitMinimumIterationCountCheck(Lp, LoopScalarPreHeader);
3708 
3709   // Generate the code to check any assumptions that we've made for SCEV
3710   // expressions.
3711   emitSCEVChecks(Lp, LoopScalarPreHeader);
3712 
3713   // Generate the code that checks in runtime if arrays overlap. We put the
3714   // checks into a separate block to make the more common case of few elements
3715   // faster.
3716   emitMemRuntimeChecks(Lp, LoopScalarPreHeader);
3717 
3718   // Some loops have a single integer induction variable, while other loops
3719   // don't. One example is c++ iterators that often have multiple pointer
3720   // induction variables. In the code below we also support a case where we
3721   // don't have a single induction variable.
3722   //
3723   // We try to obtain an induction variable from the original loop as hard
3724   // as possible. However if we don't find one that:
3725   //   - is an integer
3726   //   - counts from zero, stepping by one
3727   //   - is the size of the widest induction variable type
3728   // then we create a new one.
3729   OldInduction = Legal->getPrimaryInduction();
3730   Type *IdxTy = Legal->getWidestInductionType();
3731   Value *StartIdx = ConstantInt::get(IdxTy, 0);
3732   // The loop step is equal to the vectorization factor (num of SIMD elements)
3733   // times the unroll factor (num of SIMD instructions).
3734   Builder.SetInsertPoint(&*Lp->getHeader()->getFirstInsertionPt());
3735   Value *Step = createStepForVF(Builder, ConstantInt::get(IdxTy, UF), VF);
3736   Value *CountRoundDown = getOrCreateVectorTripCount(Lp);
3737   Induction =
3738       createInductionVariable(Lp, StartIdx, CountRoundDown, Step,
3739                               getDebugLocFromInstOrOperands(OldInduction));
3740 
3741   // Emit phis for the new starting index of the scalar loop.
3742   createInductionResumeValues(Lp, CountRoundDown);
3743 
3744   return completeLoopSkeleton(Lp, OrigLoopID);
3745 }
3746 
3747 // Fix up external users of the induction variable. At this point, we are
3748 // in LCSSA form, with all external PHIs that use the IV having one input value,
3749 // coming from the remainder loop. We need those PHIs to also have a correct
3750 // value for the IV when arriving directly from the middle block.
3751 void InnerLoopVectorizer::fixupIVUsers(PHINode *OrigPhi,
3752                                        const InductionDescriptor &II,
3753                                        Value *CountRoundDown, Value *EndValue,
3754                                        BasicBlock *MiddleBlock) {
3755   // There are two kinds of external IV usages - those that use the value
3756   // computed in the last iteration (the PHI) and those that use the penultimate
3757   // value (the value that feeds into the phi from the loop latch).
3758   // We allow both, but they, obviously, have different values.
3759 
3760   assert(OrigLoop->getUniqueExitBlock() && "Expected a single exit block");
3761 
3762   DenseMap<Value *, Value *> MissingVals;
3763 
3764   // An external user of the last iteration's value should see the value that
3765   // the remainder loop uses to initialize its own IV.
3766   Value *PostInc = OrigPhi->getIncomingValueForBlock(OrigLoop->getLoopLatch());
3767   for (User *U : PostInc->users()) {
3768     Instruction *UI = cast<Instruction>(U);
3769     if (!OrigLoop->contains(UI)) {
3770       assert(isa<PHINode>(UI) && "Expected LCSSA form");
3771       MissingVals[UI] = EndValue;
3772     }
3773   }
3774 
3775   // An external user of the penultimate value need to see EndValue - Step.
3776   // The simplest way to get this is to recompute it from the constituent SCEVs,
3777   // that is Start + (Step * (CRD - 1)).
3778   for (User *U : OrigPhi->users()) {
3779     auto *UI = cast<Instruction>(U);
3780     if (!OrigLoop->contains(UI)) {
3781       const DataLayout &DL =
3782           OrigLoop->getHeader()->getModule()->getDataLayout();
3783       assert(isa<PHINode>(UI) && "Expected LCSSA form");
3784 
3785       IRBuilder<> B(MiddleBlock->getTerminator());
3786 
3787       // Fast-math-flags propagate from the original induction instruction.
3788       if (II.getInductionBinOp() && isa<FPMathOperator>(II.getInductionBinOp()))
3789         B.setFastMathFlags(II.getInductionBinOp()->getFastMathFlags());
3790 
3791       Value *CountMinusOne = B.CreateSub(
3792           CountRoundDown, ConstantInt::get(CountRoundDown->getType(), 1));
3793       Value *CMO =
3794           !II.getStep()->getType()->isIntegerTy()
3795               ? B.CreateCast(Instruction::SIToFP, CountMinusOne,
3796                              II.getStep()->getType())
3797               : B.CreateSExtOrTrunc(CountMinusOne, II.getStep()->getType());
3798       CMO->setName("cast.cmo");
3799       Value *Escape = emitTransformedIndex(B, CMO, PSE.getSE(), DL, II);
3800       Escape->setName("ind.escape");
3801       MissingVals[UI] = Escape;
3802     }
3803   }
3804 
3805   for (auto &I : MissingVals) {
3806     PHINode *PHI = cast<PHINode>(I.first);
3807     // One corner case we have to handle is two IVs "chasing" each-other,
3808     // that is %IV2 = phi [...], [ %IV1, %latch ]
3809     // In this case, if IV1 has an external use, we need to avoid adding both
3810     // "last value of IV1" and "penultimate value of IV2". So, verify that we
3811     // don't already have an incoming value for the middle block.
3812     if (PHI->getBasicBlockIndex(MiddleBlock) == -1)
3813       PHI->addIncoming(I.second, MiddleBlock);
3814   }
3815 }
3816 
3817 namespace {
3818 
3819 struct CSEDenseMapInfo {
3820   static bool canHandle(const Instruction *I) {
3821     return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
3822            isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
3823   }
3824 
3825   static inline Instruction *getEmptyKey() {
3826     return DenseMapInfo<Instruction *>::getEmptyKey();
3827   }
3828 
3829   static inline Instruction *getTombstoneKey() {
3830     return DenseMapInfo<Instruction *>::getTombstoneKey();
3831   }
3832 
3833   static unsigned getHashValue(const Instruction *I) {
3834     assert(canHandle(I) && "Unknown instruction!");
3835     return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
3836                                                            I->value_op_end()));
3837   }
3838 
3839   static bool isEqual(const Instruction *LHS, const Instruction *RHS) {
3840     if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
3841         LHS == getTombstoneKey() || RHS == getTombstoneKey())
3842       return LHS == RHS;
3843     return LHS->isIdenticalTo(RHS);
3844   }
3845 };
3846 
3847 } // end anonymous namespace
3848 
3849 ///Perform cse of induction variable instructions.
3850 static void cse(BasicBlock *BB) {
3851   // Perform simple cse.
3852   SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
3853   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
3854     Instruction *In = &*I++;
3855 
3856     if (!CSEDenseMapInfo::canHandle(In))
3857       continue;
3858 
3859     // Check if we can replace this instruction with any of the
3860     // visited instructions.
3861     if (Instruction *V = CSEMap.lookup(In)) {
3862       In->replaceAllUsesWith(V);
3863       In->eraseFromParent();
3864       continue;
3865     }
3866 
3867     CSEMap[In] = In;
3868   }
3869 }
3870 
3871 InstructionCost
3872 LoopVectorizationCostModel::getVectorCallCost(CallInst *CI, ElementCount VF,
3873                                               bool &NeedToScalarize) const {
3874   Function *F = CI->getCalledFunction();
3875   Type *ScalarRetTy = CI->getType();
3876   SmallVector<Type *, 4> Tys, ScalarTys;
3877   for (auto &ArgOp : CI->arg_operands())
3878     ScalarTys.push_back(ArgOp->getType());
3879 
3880   // Estimate cost of scalarized vector call. The source operands are assumed
3881   // to be vectors, so we need to extract individual elements from there,
3882   // execute VF scalar calls, and then gather the result into the vector return
3883   // value.
3884   InstructionCost ScalarCallCost =
3885       TTI.getCallInstrCost(F, ScalarRetTy, ScalarTys, TTI::TCK_RecipThroughput);
3886   if (VF.isScalar())
3887     return ScalarCallCost;
3888 
3889   // Compute corresponding vector type for return value and arguments.
3890   Type *RetTy = ToVectorTy(ScalarRetTy, VF);
3891   for (Type *ScalarTy : ScalarTys)
3892     Tys.push_back(ToVectorTy(ScalarTy, VF));
3893 
3894   // Compute costs of unpacking argument values for the scalar calls and
3895   // packing the return values to a vector.
3896   InstructionCost ScalarizationCost = getScalarizationOverhead(CI, VF);
3897 
3898   InstructionCost Cost =
3899       ScalarCallCost * VF.getKnownMinValue() + ScalarizationCost;
3900 
3901   // If we can't emit a vector call for this function, then the currently found
3902   // cost is the cost we need to return.
3903   NeedToScalarize = true;
3904   VFShape Shape = VFShape::get(*CI, VF, false /*HasGlobalPred*/);
3905   Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
3906 
3907   if (!TLI || CI->isNoBuiltin() || !VecFunc)
3908     return Cost;
3909 
3910   // If the corresponding vector cost is cheaper, return its cost.
3911   InstructionCost VectorCallCost =
3912       TTI.getCallInstrCost(nullptr, RetTy, Tys, TTI::TCK_RecipThroughput);
3913   if (VectorCallCost < Cost) {
3914     NeedToScalarize = false;
3915     Cost = VectorCallCost;
3916   }
3917   return Cost;
3918 }
3919 
3920 static Type *MaybeVectorizeType(Type *Elt, ElementCount VF) {
3921   if (VF.isScalar() || (!Elt->isIntOrPtrTy() && !Elt->isFloatingPointTy()))
3922     return Elt;
3923   return VectorType::get(Elt, VF);
3924 }
3925 
3926 InstructionCost
3927 LoopVectorizationCostModel::getVectorIntrinsicCost(CallInst *CI,
3928                                                    ElementCount VF) const {
3929   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
3930   assert(ID && "Expected intrinsic call!");
3931   Type *RetTy = MaybeVectorizeType(CI->getType(), VF);
3932   FastMathFlags FMF;
3933   if (auto *FPMO = dyn_cast<FPMathOperator>(CI))
3934     FMF = FPMO->getFastMathFlags();
3935 
3936   SmallVector<const Value *> Arguments(CI->arg_begin(), CI->arg_end());
3937   FunctionType *FTy = CI->getCalledFunction()->getFunctionType();
3938   SmallVector<Type *> ParamTys;
3939   std::transform(FTy->param_begin(), FTy->param_end(),
3940                  std::back_inserter(ParamTys),
3941                  [&](Type *Ty) { return MaybeVectorizeType(Ty, VF); });
3942 
3943   IntrinsicCostAttributes CostAttrs(ID, RetTy, Arguments, ParamTys, FMF,
3944                                     dyn_cast<IntrinsicInst>(CI));
3945   return TTI.getIntrinsicInstrCost(CostAttrs,
3946                                    TargetTransformInfo::TCK_RecipThroughput);
3947 }
3948 
3949 static Type *smallestIntegerVectorType(Type *T1, Type *T2) {
3950   auto *I1 = cast<IntegerType>(cast<VectorType>(T1)->getElementType());
3951   auto *I2 = cast<IntegerType>(cast<VectorType>(T2)->getElementType());
3952   return I1->getBitWidth() < I2->getBitWidth() ? T1 : T2;
3953 }
3954 
3955 static Type *largestIntegerVectorType(Type *T1, Type *T2) {
3956   auto *I1 = cast<IntegerType>(cast<VectorType>(T1)->getElementType());
3957   auto *I2 = cast<IntegerType>(cast<VectorType>(T2)->getElementType());
3958   return I1->getBitWidth() > I2->getBitWidth() ? T1 : T2;
3959 }
3960 
3961 void InnerLoopVectorizer::truncateToMinimalBitwidths(VPTransformState &State) {
3962   // For every instruction `I` in MinBWs, truncate the operands, create a
3963   // truncated version of `I` and reextend its result. InstCombine runs
3964   // later and will remove any ext/trunc pairs.
3965   SmallPtrSet<Value *, 4> Erased;
3966   for (const auto &KV : Cost->getMinimalBitwidths()) {
3967     // If the value wasn't vectorized, we must maintain the original scalar
3968     // type. The absence of the value from State indicates that it
3969     // wasn't vectorized.
3970     VPValue *Def = State.Plan->getVPValue(KV.first);
3971     if (!State.hasAnyVectorValue(Def))
3972       continue;
3973     for (unsigned Part = 0; Part < UF; ++Part) {
3974       Value *I = State.get(Def, Part);
3975       if (Erased.count(I) || I->use_empty() || !isa<Instruction>(I))
3976         continue;
3977       Type *OriginalTy = I->getType();
3978       Type *ScalarTruncatedTy =
3979           IntegerType::get(OriginalTy->getContext(), KV.second);
3980       auto *TruncatedTy = VectorType::get(
3981           ScalarTruncatedTy, cast<VectorType>(OriginalTy)->getElementCount());
3982       if (TruncatedTy == OriginalTy)
3983         continue;
3984 
3985       IRBuilder<> B(cast<Instruction>(I));
3986       auto ShrinkOperand = [&](Value *V) -> Value * {
3987         if (auto *ZI = dyn_cast<ZExtInst>(V))
3988           if (ZI->getSrcTy() == TruncatedTy)
3989             return ZI->getOperand(0);
3990         return B.CreateZExtOrTrunc(V, TruncatedTy);
3991       };
3992 
3993       // The actual instruction modification depends on the instruction type,
3994       // unfortunately.
3995       Value *NewI = nullptr;
3996       if (auto *BO = dyn_cast<BinaryOperator>(I)) {
3997         NewI = B.CreateBinOp(BO->getOpcode(), ShrinkOperand(BO->getOperand(0)),
3998                              ShrinkOperand(BO->getOperand(1)));
3999 
4000         // Any wrapping introduced by shrinking this operation shouldn't be
4001         // considered undefined behavior. So, we can't unconditionally copy
4002         // arithmetic wrapping flags to NewI.
4003         cast<BinaryOperator>(NewI)->copyIRFlags(I, /*IncludeWrapFlags=*/false);
4004       } else if (auto *CI = dyn_cast<ICmpInst>(I)) {
4005         NewI =
4006             B.CreateICmp(CI->getPredicate(), ShrinkOperand(CI->getOperand(0)),
4007                          ShrinkOperand(CI->getOperand(1)));
4008       } else if (auto *SI = dyn_cast<SelectInst>(I)) {
4009         NewI = B.CreateSelect(SI->getCondition(),
4010                               ShrinkOperand(SI->getTrueValue()),
4011                               ShrinkOperand(SI->getFalseValue()));
4012       } else if (auto *CI = dyn_cast<CastInst>(I)) {
4013         switch (CI->getOpcode()) {
4014         default:
4015           llvm_unreachable("Unhandled cast!");
4016         case Instruction::Trunc:
4017           NewI = ShrinkOperand(CI->getOperand(0));
4018           break;
4019         case Instruction::SExt:
4020           NewI = B.CreateSExtOrTrunc(
4021               CI->getOperand(0),
4022               smallestIntegerVectorType(OriginalTy, TruncatedTy));
4023           break;
4024         case Instruction::ZExt:
4025           NewI = B.CreateZExtOrTrunc(
4026               CI->getOperand(0),
4027               smallestIntegerVectorType(OriginalTy, TruncatedTy));
4028           break;
4029         }
4030       } else if (auto *SI = dyn_cast<ShuffleVectorInst>(I)) {
4031         auto Elements0 =
4032             cast<VectorType>(SI->getOperand(0)->getType())->getElementCount();
4033         auto *O0 = B.CreateZExtOrTrunc(
4034             SI->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements0));
4035         auto Elements1 =
4036             cast<VectorType>(SI->getOperand(1)->getType())->getElementCount();
4037         auto *O1 = B.CreateZExtOrTrunc(
4038             SI->getOperand(1), VectorType::get(ScalarTruncatedTy, Elements1));
4039 
4040         NewI = B.CreateShuffleVector(O0, O1, SI->getShuffleMask());
4041       } else if (isa<LoadInst>(I) || isa<PHINode>(I)) {
4042         // Don't do anything with the operands, just extend the result.
4043         continue;
4044       } else if (auto *IE = dyn_cast<InsertElementInst>(I)) {
4045         auto Elements = cast<FixedVectorType>(IE->getOperand(0)->getType())
4046                             ->getNumElements();
4047         auto *O0 = B.CreateZExtOrTrunc(
4048             IE->getOperand(0),
4049             FixedVectorType::get(ScalarTruncatedTy, Elements));
4050         auto *O1 = B.CreateZExtOrTrunc(IE->getOperand(1), ScalarTruncatedTy);
4051         NewI = B.CreateInsertElement(O0, O1, IE->getOperand(2));
4052       } else if (auto *EE = dyn_cast<ExtractElementInst>(I)) {
4053         auto Elements = cast<FixedVectorType>(EE->getOperand(0)->getType())
4054                             ->getNumElements();
4055         auto *O0 = B.CreateZExtOrTrunc(
4056             EE->getOperand(0),
4057             FixedVectorType::get(ScalarTruncatedTy, Elements));
4058         NewI = B.CreateExtractElement(O0, EE->getOperand(2));
4059       } else {
4060         // If we don't know what to do, be conservative and don't do anything.
4061         continue;
4062       }
4063 
4064       // Lastly, extend the result.
4065       NewI->takeName(cast<Instruction>(I));
4066       Value *Res = B.CreateZExtOrTrunc(NewI, OriginalTy);
4067       I->replaceAllUsesWith(Res);
4068       cast<Instruction>(I)->eraseFromParent();
4069       Erased.insert(I);
4070       State.reset(Def, Res, Part);
4071     }
4072   }
4073 
4074   // We'll have created a bunch of ZExts that are now parentless. Clean up.
4075   for (const auto &KV : Cost->getMinimalBitwidths()) {
4076     // If the value wasn't vectorized, we must maintain the original scalar
4077     // type. The absence of the value from State indicates that it
4078     // wasn't vectorized.
4079     VPValue *Def = State.Plan->getVPValue(KV.first);
4080     if (!State.hasAnyVectorValue(Def))
4081       continue;
4082     for (unsigned Part = 0; Part < UF; ++Part) {
4083       Value *I = State.get(Def, Part);
4084       ZExtInst *Inst = dyn_cast<ZExtInst>(I);
4085       if (Inst && Inst->use_empty()) {
4086         Value *NewI = Inst->getOperand(0);
4087         Inst->eraseFromParent();
4088         State.reset(Def, NewI, Part);
4089       }
4090     }
4091   }
4092 }
4093 
4094 void InnerLoopVectorizer::fixVectorizedLoop(VPTransformState &State) {
4095   // Insert truncates and extends for any truncated instructions as hints to
4096   // InstCombine.
4097   if (VF.isVector())
4098     truncateToMinimalBitwidths(State);
4099 
4100   // Fix widened non-induction PHIs by setting up the PHI operands.
4101   if (OrigPHIsToFix.size()) {
4102     assert(EnableVPlanNativePath &&
4103            "Unexpected non-induction PHIs for fixup in non VPlan-native path");
4104     fixNonInductionPHIs(State);
4105   }
4106 
4107   // At this point every instruction in the original loop is widened to a
4108   // vector form. Now we need to fix the recurrences in the loop. These PHI
4109   // nodes are currently empty because we did not want to introduce cycles.
4110   // This is the second stage of vectorizing recurrences.
4111   fixCrossIterationPHIs(State);
4112 
4113   // Forget the original basic block.
4114   PSE.getSE()->forgetLoop(OrigLoop);
4115 
4116   // If we inserted an edge from the middle block to the unique exit block,
4117   // update uses outside the loop (phis) to account for the newly inserted
4118   // edge.
4119   if (!Cost->requiresScalarEpilogue(VF)) {
4120     // Fix-up external users of the induction variables.
4121     for (auto &Entry : Legal->getInductionVars())
4122       fixupIVUsers(Entry.first, Entry.second,
4123                    getOrCreateVectorTripCount(LI->getLoopFor(LoopVectorBody)),
4124                    IVEndValues[Entry.first], LoopMiddleBlock);
4125 
4126     fixLCSSAPHIs(State);
4127   }
4128 
4129   for (Instruction *PI : PredicatedInstructions)
4130     sinkScalarOperands(&*PI);
4131 
4132   // Remove redundant induction instructions.
4133   cse(LoopVectorBody);
4134 
4135   // Set/update profile weights for the vector and remainder loops as original
4136   // loop iterations are now distributed among them. Note that original loop
4137   // represented by LoopScalarBody becomes remainder loop after vectorization.
4138   //
4139   // For cases like foldTailByMasking() and requiresScalarEpiloque() we may
4140   // end up getting slightly roughened result but that should be OK since
4141   // profile is not inherently precise anyway. Note also possible bypass of
4142   // vector code caused by legality checks is ignored, assigning all the weight
4143   // to the vector loop, optimistically.
4144   //
4145   // For scalable vectorization we can't know at compile time how many iterations
4146   // of the loop are handled in one vector iteration, so instead assume a pessimistic
4147   // vscale of '1'.
4148   setProfileInfoAfterUnrolling(
4149       LI->getLoopFor(LoopScalarBody), LI->getLoopFor(LoopVectorBody),
4150       LI->getLoopFor(LoopScalarBody), VF.getKnownMinValue() * UF);
4151 }
4152 
4153 void InnerLoopVectorizer::fixCrossIterationPHIs(VPTransformState &State) {
4154   // In order to support recurrences we need to be able to vectorize Phi nodes.
4155   // Phi nodes have cycles, so we need to vectorize them in two stages. This is
4156   // stage #2: We now need to fix the recurrences by adding incoming edges to
4157   // the currently empty PHI nodes. At this point every instruction in the
4158   // original loop is widened to a vector form so we can use them to construct
4159   // the incoming edges.
4160   VPBasicBlock *Header = State.Plan->getEntry()->getEntryBasicBlock();
4161   for (VPRecipeBase &R : Header->phis()) {
4162     auto *PhiR = dyn_cast<VPWidenPHIRecipe>(&R);
4163     if (!PhiR)
4164       continue;
4165     auto *OrigPhi = cast<PHINode>(PhiR->getUnderlyingValue());
4166     if (auto *ReductionPhi = dyn_cast<VPReductionPHIRecipe>(PhiR)) {
4167       fixReduction(ReductionPhi, State);
4168     } else if (Legal->isFirstOrderRecurrence(OrigPhi))
4169       fixFirstOrderRecurrence(PhiR, State);
4170   }
4171 }
4172 
4173 void InnerLoopVectorizer::fixFirstOrderRecurrence(VPWidenPHIRecipe *PhiR,
4174                                                   VPTransformState &State) {
4175   // This is the second phase of vectorizing first-order recurrences. An
4176   // overview of the transformation is described below. Suppose we have the
4177   // following loop.
4178   //
4179   //   for (int i = 0; i < n; ++i)
4180   //     b[i] = a[i] - a[i - 1];
4181   //
4182   // There is a first-order recurrence on "a". For this loop, the shorthand
4183   // scalar IR looks like:
4184   //
4185   //   scalar.ph:
4186   //     s_init = a[-1]
4187   //     br scalar.body
4188   //
4189   //   scalar.body:
4190   //     i = phi [0, scalar.ph], [i+1, scalar.body]
4191   //     s1 = phi [s_init, scalar.ph], [s2, scalar.body]
4192   //     s2 = a[i]
4193   //     b[i] = s2 - s1
4194   //     br cond, scalar.body, ...
4195   //
4196   // In this example, s1 is a recurrence because it's value depends on the
4197   // previous iteration. In the first phase of vectorization, we created a
4198   // temporary value for s1. We now complete the vectorization and produce the
4199   // shorthand vector IR shown below (for VF = 4, UF = 1).
4200   //
4201   //   vector.ph:
4202   //     v_init = vector(..., ..., ..., a[-1])
4203   //     br vector.body
4204   //
4205   //   vector.body
4206   //     i = phi [0, vector.ph], [i+4, vector.body]
4207   //     v1 = phi [v_init, vector.ph], [v2, vector.body]
4208   //     v2 = a[i, i+1, i+2, i+3];
4209   //     v3 = vector(v1(3), v2(0, 1, 2))
4210   //     b[i, i+1, i+2, i+3] = v2 - v3
4211   //     br cond, vector.body, middle.block
4212   //
4213   //   middle.block:
4214   //     x = v2(3)
4215   //     br scalar.ph
4216   //
4217   //   scalar.ph:
4218   //     s_init = phi [x, middle.block], [a[-1], otherwise]
4219   //     br scalar.body
4220   //
4221   // After execution completes the vector loop, we extract the next value of
4222   // the recurrence (x) to use as the initial value in the scalar loop.
4223 
4224   auto *ScalarInit = PhiR->getStartValue()->getLiveInIRValue();
4225 
4226   auto *IdxTy = Builder.getInt32Ty();
4227   auto *One = ConstantInt::get(IdxTy, 1);
4228 
4229   // Create a vector from the initial value.
4230   auto *VectorInit = ScalarInit;
4231   if (VF.isVector()) {
4232     Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
4233     auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, VF);
4234     auto *LastIdx = Builder.CreateSub(RuntimeVF, One);
4235     VectorInit = Builder.CreateInsertElement(
4236         PoisonValue::get(VectorType::get(VectorInit->getType(), VF)),
4237         VectorInit, LastIdx, "vector.recur.init");
4238   }
4239 
4240   VPValue *PreviousDef = PhiR->getBackedgeValue();
4241   // We constructed a temporary phi node in the first phase of vectorization.
4242   // This phi node will eventually be deleted.
4243   Builder.SetInsertPoint(cast<Instruction>(State.get(PhiR, 0)));
4244 
4245   // Create a phi node for the new recurrence. The current value will either be
4246   // the initial value inserted into a vector or loop-varying vector value.
4247   auto *VecPhi = Builder.CreatePHI(VectorInit->getType(), 2, "vector.recur");
4248   VecPhi->addIncoming(VectorInit, LoopVectorPreHeader);
4249 
4250   // Get the vectorized previous value of the last part UF - 1. It appears last
4251   // among all unrolled iterations, due to the order of their construction.
4252   Value *PreviousLastPart = State.get(PreviousDef, UF - 1);
4253 
4254   // Find and set the insertion point after the previous value if it is an
4255   // instruction.
4256   BasicBlock::iterator InsertPt;
4257   // Note that the previous value may have been constant-folded so it is not
4258   // guaranteed to be an instruction in the vector loop.
4259   // FIXME: Loop invariant values do not form recurrences. We should deal with
4260   //        them earlier.
4261   if (LI->getLoopFor(LoopVectorBody)->isLoopInvariant(PreviousLastPart))
4262     InsertPt = LoopVectorBody->getFirstInsertionPt();
4263   else {
4264     Instruction *PreviousInst = cast<Instruction>(PreviousLastPart);
4265     if (isa<PHINode>(PreviousLastPart))
4266       // If the previous value is a phi node, we should insert after all the phi
4267       // nodes in the block containing the PHI to avoid breaking basic block
4268       // verification. Note that the basic block may be different to
4269       // LoopVectorBody, in case we predicate the loop.
4270       InsertPt = PreviousInst->getParent()->getFirstInsertionPt();
4271     else
4272       InsertPt = ++PreviousInst->getIterator();
4273   }
4274   Builder.SetInsertPoint(&*InsertPt);
4275 
4276   // The vector from which to take the initial value for the current iteration
4277   // (actual or unrolled). Initially, this is the vector phi node.
4278   Value *Incoming = VecPhi;
4279 
4280   // Shuffle the current and previous vector and update the vector parts.
4281   for (unsigned Part = 0; Part < UF; ++Part) {
4282     Value *PreviousPart = State.get(PreviousDef, Part);
4283     Value *PhiPart = State.get(PhiR, Part);
4284     auto *Shuffle = VF.isVector()
4285                         ? Builder.CreateVectorSplice(Incoming, PreviousPart, -1)
4286                         : Incoming;
4287     PhiPart->replaceAllUsesWith(Shuffle);
4288     cast<Instruction>(PhiPart)->eraseFromParent();
4289     State.reset(PhiR, Shuffle, Part);
4290     Incoming = PreviousPart;
4291   }
4292 
4293   // Fix the latch value of the new recurrence in the vector loop.
4294   VecPhi->addIncoming(Incoming, LI->getLoopFor(LoopVectorBody)->getLoopLatch());
4295 
4296   // Extract the last vector element in the middle block. This will be the
4297   // initial value for the recurrence when jumping to the scalar loop.
4298   auto *ExtractForScalar = Incoming;
4299   if (VF.isVector()) {
4300     Builder.SetInsertPoint(LoopMiddleBlock->getTerminator());
4301     auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, VF);
4302     auto *LastIdx = Builder.CreateSub(RuntimeVF, One);
4303     ExtractForScalar = Builder.CreateExtractElement(ExtractForScalar, LastIdx,
4304                                                     "vector.recur.extract");
4305   }
4306   // Extract the second last element in the middle block if the
4307   // Phi is used outside the loop. We need to extract the phi itself
4308   // and not the last element (the phi update in the current iteration). This
4309   // will be the value when jumping to the exit block from the LoopMiddleBlock,
4310   // when the scalar loop is not run at all.
4311   Value *ExtractForPhiUsedOutsideLoop = nullptr;
4312   if (VF.isVector()) {
4313     auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, VF);
4314     auto *Idx = Builder.CreateSub(RuntimeVF, ConstantInt::get(IdxTy, 2));
4315     ExtractForPhiUsedOutsideLoop = Builder.CreateExtractElement(
4316         Incoming, Idx, "vector.recur.extract.for.phi");
4317   } else if (UF > 1)
4318     // When loop is unrolled without vectorizing, initialize
4319     // ExtractForPhiUsedOutsideLoop with the value just prior to unrolled value
4320     // of `Incoming`. This is analogous to the vectorized case above: extracting
4321     // the second last element when VF > 1.
4322     ExtractForPhiUsedOutsideLoop = State.get(PreviousDef, UF - 2);
4323 
4324   // Fix the initial value of the original recurrence in the scalar loop.
4325   Builder.SetInsertPoint(&*LoopScalarPreHeader->begin());
4326   PHINode *Phi = cast<PHINode>(PhiR->getUnderlyingValue());
4327   auto *Start = Builder.CreatePHI(Phi->getType(), 2, "scalar.recur.init");
4328   for (auto *BB : predecessors(LoopScalarPreHeader)) {
4329     auto *Incoming = BB == LoopMiddleBlock ? ExtractForScalar : ScalarInit;
4330     Start->addIncoming(Incoming, BB);
4331   }
4332 
4333   Phi->setIncomingValueForBlock(LoopScalarPreHeader, Start);
4334   Phi->setName("scalar.recur");
4335 
4336   // Finally, fix users of the recurrence outside the loop. The users will need
4337   // either the last value of the scalar recurrence or the last value of the
4338   // vector recurrence we extracted in the middle block. Since the loop is in
4339   // LCSSA form, we just need to find all the phi nodes for the original scalar
4340   // recurrence in the exit block, and then add an edge for the middle block.
4341   // Note that LCSSA does not imply single entry when the original scalar loop
4342   // had multiple exiting edges (as we always run the last iteration in the
4343   // scalar epilogue); in that case, there is no edge from middle to exit and
4344   // and thus no phis which needed updated.
4345   if (!Cost->requiresScalarEpilogue(VF))
4346     for (PHINode &LCSSAPhi : LoopExitBlock->phis())
4347       if (any_of(LCSSAPhi.incoming_values(),
4348                  [Phi](Value *V) { return V == Phi; }))
4349         LCSSAPhi.addIncoming(ExtractForPhiUsedOutsideLoop, LoopMiddleBlock);
4350 }
4351 
4352 void InnerLoopVectorizer::fixReduction(VPReductionPHIRecipe *PhiR,
4353                                        VPTransformState &State) {
4354   PHINode *OrigPhi = cast<PHINode>(PhiR->getUnderlyingValue());
4355   // Get it's reduction variable descriptor.
4356   assert(Legal->isReductionVariable(OrigPhi) &&
4357          "Unable to find the reduction variable");
4358   const RecurrenceDescriptor &RdxDesc = PhiR->getRecurrenceDescriptor();
4359 
4360   RecurKind RK = RdxDesc.getRecurrenceKind();
4361   TrackingVH<Value> ReductionStartValue = RdxDesc.getRecurrenceStartValue();
4362   Instruction *LoopExitInst = RdxDesc.getLoopExitInstr();
4363   setDebugLocFromInst(ReductionStartValue);
4364 
4365   VPValue *LoopExitInstDef = State.Plan->getVPValue(LoopExitInst);
4366   // This is the vector-clone of the value that leaves the loop.
4367   Type *VecTy = State.get(LoopExitInstDef, 0)->getType();
4368 
4369   // Wrap flags are in general invalid after vectorization, clear them.
4370   clearReductionWrapFlags(RdxDesc, State);
4371 
4372   // Fix the vector-loop phi.
4373 
4374   // Reductions do not have to start at zero. They can start with
4375   // any loop invariant values.
4376   BasicBlock *VectorLoopLatch = LI->getLoopFor(LoopVectorBody)->getLoopLatch();
4377 
4378   unsigned LastPartForNewPhi = PhiR->isOrdered() ? 1 : UF;
4379   for (unsigned Part = 0; Part < LastPartForNewPhi; ++Part) {
4380     Value *VecRdxPhi = State.get(PhiR->getVPSingleValue(), Part);
4381     Value *Val = State.get(PhiR->getBackedgeValue(), Part);
4382     if (PhiR->isOrdered())
4383       Val = State.get(PhiR->getBackedgeValue(), UF - 1);
4384 
4385     cast<PHINode>(VecRdxPhi)->addIncoming(Val, VectorLoopLatch);
4386   }
4387 
4388   // Before each round, move the insertion point right between
4389   // the PHIs and the values we are going to write.
4390   // This allows us to write both PHINodes and the extractelement
4391   // instructions.
4392   Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
4393 
4394   setDebugLocFromInst(LoopExitInst);
4395 
4396   Type *PhiTy = OrigPhi->getType();
4397   // If tail is folded by masking, the vector value to leave the loop should be
4398   // a Select choosing between the vectorized LoopExitInst and vectorized Phi,
4399   // instead of the former. For an inloop reduction the reduction will already
4400   // be predicated, and does not need to be handled here.
4401   if (Cost->foldTailByMasking() && !PhiR->isInLoop()) {
4402     for (unsigned Part = 0; Part < UF; ++Part) {
4403       Value *VecLoopExitInst = State.get(LoopExitInstDef, Part);
4404       Value *Sel = nullptr;
4405       for (User *U : VecLoopExitInst->users()) {
4406         if (isa<SelectInst>(U)) {
4407           assert(!Sel && "Reduction exit feeding two selects");
4408           Sel = U;
4409         } else
4410           assert(isa<PHINode>(U) && "Reduction exit must feed Phi's or select");
4411       }
4412       assert(Sel && "Reduction exit feeds no select");
4413       State.reset(LoopExitInstDef, Sel, Part);
4414 
4415       // If the target can create a predicated operator for the reduction at no
4416       // extra cost in the loop (for example a predicated vadd), it can be
4417       // cheaper for the select to remain in the loop than be sunk out of it,
4418       // and so use the select value for the phi instead of the old
4419       // LoopExitValue.
4420       if (PreferPredicatedReductionSelect ||
4421           TTI->preferPredicatedReductionSelect(
4422               RdxDesc.getOpcode(), PhiTy,
4423               TargetTransformInfo::ReductionFlags())) {
4424         auto *VecRdxPhi =
4425             cast<PHINode>(State.get(PhiR->getVPSingleValue(), Part));
4426         VecRdxPhi->setIncomingValueForBlock(
4427             LI->getLoopFor(LoopVectorBody)->getLoopLatch(), Sel);
4428       }
4429     }
4430   }
4431 
4432   // If the vector reduction can be performed in a smaller type, we truncate
4433   // then extend the loop exit value to enable InstCombine to evaluate the
4434   // entire expression in the smaller type.
4435   if (VF.isVector() && PhiTy != RdxDesc.getRecurrenceType()) {
4436     assert(!PhiR->isInLoop() && "Unexpected truncated inloop reduction!");
4437     Type *RdxVecTy = VectorType::get(RdxDesc.getRecurrenceType(), VF);
4438     Builder.SetInsertPoint(
4439         LI->getLoopFor(LoopVectorBody)->getLoopLatch()->getTerminator());
4440     VectorParts RdxParts(UF);
4441     for (unsigned Part = 0; Part < UF; ++Part) {
4442       RdxParts[Part] = State.get(LoopExitInstDef, Part);
4443       Value *Trunc = Builder.CreateTrunc(RdxParts[Part], RdxVecTy);
4444       Value *Extnd = RdxDesc.isSigned() ? Builder.CreateSExt(Trunc, VecTy)
4445                                         : Builder.CreateZExt(Trunc, VecTy);
4446       for (Value::user_iterator UI = RdxParts[Part]->user_begin();
4447            UI != RdxParts[Part]->user_end();)
4448         if (*UI != Trunc) {
4449           (*UI++)->replaceUsesOfWith(RdxParts[Part], Extnd);
4450           RdxParts[Part] = Extnd;
4451         } else {
4452           ++UI;
4453         }
4454     }
4455     Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
4456     for (unsigned Part = 0; Part < UF; ++Part) {
4457       RdxParts[Part] = Builder.CreateTrunc(RdxParts[Part], RdxVecTy);
4458       State.reset(LoopExitInstDef, RdxParts[Part], Part);
4459     }
4460   }
4461 
4462   // Reduce all of the unrolled parts into a single vector.
4463   Value *ReducedPartRdx = State.get(LoopExitInstDef, 0);
4464   unsigned Op = RecurrenceDescriptor::getOpcode(RK);
4465 
4466   // The middle block terminator has already been assigned a DebugLoc here (the
4467   // OrigLoop's single latch terminator). We want the whole middle block to
4468   // appear to execute on this line because: (a) it is all compiler generated,
4469   // (b) these instructions are always executed after evaluating the latch
4470   // conditional branch, and (c) other passes may add new predecessors which
4471   // terminate on this line. This is the easiest way to ensure we don't
4472   // accidentally cause an extra step back into the loop while debugging.
4473   setDebugLocFromInst(LoopMiddleBlock->getTerminator());
4474   if (PhiR->isOrdered())
4475     ReducedPartRdx = State.get(LoopExitInstDef, UF - 1);
4476   else {
4477     // Floating-point operations should have some FMF to enable the reduction.
4478     IRBuilderBase::FastMathFlagGuard FMFG(Builder);
4479     Builder.setFastMathFlags(RdxDesc.getFastMathFlags());
4480     for (unsigned Part = 1; Part < UF; ++Part) {
4481       Value *RdxPart = State.get(LoopExitInstDef, Part);
4482       if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
4483         ReducedPartRdx = Builder.CreateBinOp(
4484             (Instruction::BinaryOps)Op, RdxPart, ReducedPartRdx, "bin.rdx");
4485       } else {
4486         ReducedPartRdx = createMinMaxOp(Builder, RK, ReducedPartRdx, RdxPart);
4487       }
4488     }
4489   }
4490 
4491   // Create the reduction after the loop. Note that inloop reductions create the
4492   // target reduction in the loop using a Reduction recipe.
4493   if (VF.isVector() && !PhiR->isInLoop()) {
4494     ReducedPartRdx =
4495         createTargetReduction(Builder, TTI, RdxDesc, ReducedPartRdx);
4496     // If the reduction can be performed in a smaller type, we need to extend
4497     // the reduction to the wider type before we branch to the original loop.
4498     if (PhiTy != RdxDesc.getRecurrenceType())
4499       ReducedPartRdx = RdxDesc.isSigned()
4500                            ? Builder.CreateSExt(ReducedPartRdx, PhiTy)
4501                            : Builder.CreateZExt(ReducedPartRdx, PhiTy);
4502   }
4503 
4504   // Create a phi node that merges control-flow from the backedge-taken check
4505   // block and the middle block.
4506   PHINode *BCBlockPhi = PHINode::Create(PhiTy, 2, "bc.merge.rdx",
4507                                         LoopScalarPreHeader->getTerminator());
4508   for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
4509     BCBlockPhi->addIncoming(ReductionStartValue, LoopBypassBlocks[I]);
4510   BCBlockPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
4511 
4512   // Now, we need to fix the users of the reduction variable
4513   // inside and outside of the scalar remainder loop.
4514 
4515   // We know that the loop is in LCSSA form. We need to update the PHI nodes
4516   // in the exit blocks.  See comment on analogous loop in
4517   // fixFirstOrderRecurrence for a more complete explaination of the logic.
4518   if (!Cost->requiresScalarEpilogue(VF))
4519     for (PHINode &LCSSAPhi : LoopExitBlock->phis())
4520       if (any_of(LCSSAPhi.incoming_values(),
4521                  [LoopExitInst](Value *V) { return V == LoopExitInst; }))
4522         LCSSAPhi.addIncoming(ReducedPartRdx, LoopMiddleBlock);
4523 
4524   // Fix the scalar loop reduction variable with the incoming reduction sum
4525   // from the vector body and from the backedge value.
4526   int IncomingEdgeBlockIdx =
4527       OrigPhi->getBasicBlockIndex(OrigLoop->getLoopLatch());
4528   assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
4529   // Pick the other block.
4530   int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
4531   OrigPhi->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi);
4532   OrigPhi->setIncomingValue(IncomingEdgeBlockIdx, LoopExitInst);
4533 }
4534 
4535 void InnerLoopVectorizer::clearReductionWrapFlags(const RecurrenceDescriptor &RdxDesc,
4536                                                   VPTransformState &State) {
4537   RecurKind RK = RdxDesc.getRecurrenceKind();
4538   if (RK != RecurKind::Add && RK != RecurKind::Mul)
4539     return;
4540 
4541   Instruction *LoopExitInstr = RdxDesc.getLoopExitInstr();
4542   assert(LoopExitInstr && "null loop exit instruction");
4543   SmallVector<Instruction *, 8> Worklist;
4544   SmallPtrSet<Instruction *, 8> Visited;
4545   Worklist.push_back(LoopExitInstr);
4546   Visited.insert(LoopExitInstr);
4547 
4548   while (!Worklist.empty()) {
4549     Instruction *Cur = Worklist.pop_back_val();
4550     if (isa<OverflowingBinaryOperator>(Cur))
4551       for (unsigned Part = 0; Part < UF; ++Part) {
4552         Value *V = State.get(State.Plan->getVPValue(Cur), Part);
4553         cast<Instruction>(V)->dropPoisonGeneratingFlags();
4554       }
4555 
4556     for (User *U : Cur->users()) {
4557       Instruction *UI = cast<Instruction>(U);
4558       if ((Cur != LoopExitInstr || OrigLoop->contains(UI->getParent())) &&
4559           Visited.insert(UI).second)
4560         Worklist.push_back(UI);
4561     }
4562   }
4563 }
4564 
4565 void InnerLoopVectorizer::fixLCSSAPHIs(VPTransformState &State) {
4566   for (PHINode &LCSSAPhi : LoopExitBlock->phis()) {
4567     if (LCSSAPhi.getBasicBlockIndex(LoopMiddleBlock) != -1)
4568       // Some phis were already hand updated by the reduction and recurrence
4569       // code above, leave them alone.
4570       continue;
4571 
4572     auto *IncomingValue = LCSSAPhi.getIncomingValue(0);
4573     // Non-instruction incoming values will have only one value.
4574 
4575     VPLane Lane = VPLane::getFirstLane();
4576     if (isa<Instruction>(IncomingValue) &&
4577         !Cost->isUniformAfterVectorization(cast<Instruction>(IncomingValue),
4578                                            VF))
4579       Lane = VPLane::getLastLaneForVF(VF);
4580 
4581     // Can be a loop invariant incoming value or the last scalar value to be
4582     // extracted from the vectorized loop.
4583     Builder.SetInsertPoint(LoopMiddleBlock->getTerminator());
4584     Value *lastIncomingValue =
4585         OrigLoop->isLoopInvariant(IncomingValue)
4586             ? IncomingValue
4587             : State.get(State.Plan->getVPValue(IncomingValue),
4588                         VPIteration(UF - 1, Lane));
4589     LCSSAPhi.addIncoming(lastIncomingValue, LoopMiddleBlock);
4590   }
4591 }
4592 
4593 void InnerLoopVectorizer::sinkScalarOperands(Instruction *PredInst) {
4594   // The basic block and loop containing the predicated instruction.
4595   auto *PredBB = PredInst->getParent();
4596   auto *VectorLoop = LI->getLoopFor(PredBB);
4597 
4598   // Initialize a worklist with the operands of the predicated instruction.
4599   SetVector<Value *> Worklist(PredInst->op_begin(), PredInst->op_end());
4600 
4601   // Holds instructions that we need to analyze again. An instruction may be
4602   // reanalyzed if we don't yet know if we can sink it or not.
4603   SmallVector<Instruction *, 8> InstsToReanalyze;
4604 
4605   // Returns true if a given use occurs in the predicated block. Phi nodes use
4606   // their operands in their corresponding predecessor blocks.
4607   auto isBlockOfUsePredicated = [&](Use &U) -> bool {
4608     auto *I = cast<Instruction>(U.getUser());
4609     BasicBlock *BB = I->getParent();
4610     if (auto *Phi = dyn_cast<PHINode>(I))
4611       BB = Phi->getIncomingBlock(
4612           PHINode::getIncomingValueNumForOperand(U.getOperandNo()));
4613     return BB == PredBB;
4614   };
4615 
4616   // Iteratively sink the scalarized operands of the predicated instruction
4617   // into the block we created for it. When an instruction is sunk, it's
4618   // operands are then added to the worklist. The algorithm ends after one pass
4619   // through the worklist doesn't sink a single instruction.
4620   bool Changed;
4621   do {
4622     // Add the instructions that need to be reanalyzed to the worklist, and
4623     // reset the changed indicator.
4624     Worklist.insert(InstsToReanalyze.begin(), InstsToReanalyze.end());
4625     InstsToReanalyze.clear();
4626     Changed = false;
4627 
4628     while (!Worklist.empty()) {
4629       auto *I = dyn_cast<Instruction>(Worklist.pop_back_val());
4630 
4631       // We can't sink an instruction if it is a phi node, is not in the loop,
4632       // or may have side effects.
4633       if (!I || isa<PHINode>(I) || !VectorLoop->contains(I) ||
4634           I->mayHaveSideEffects())
4635         continue;
4636 
4637       // If the instruction is already in PredBB, check if we can sink its
4638       // operands. In that case, VPlan's sinkScalarOperands() succeeded in
4639       // sinking the scalar instruction I, hence it appears in PredBB; but it
4640       // may have failed to sink I's operands (recursively), which we try
4641       // (again) here.
4642       if (I->getParent() == PredBB) {
4643         Worklist.insert(I->op_begin(), I->op_end());
4644         continue;
4645       }
4646 
4647       // It's legal to sink the instruction if all its uses occur in the
4648       // predicated block. Otherwise, there's nothing to do yet, and we may
4649       // need to reanalyze the instruction.
4650       if (!llvm::all_of(I->uses(), isBlockOfUsePredicated)) {
4651         InstsToReanalyze.push_back(I);
4652         continue;
4653       }
4654 
4655       // Move the instruction to the beginning of the predicated block, and add
4656       // it's operands to the worklist.
4657       I->moveBefore(&*PredBB->getFirstInsertionPt());
4658       Worklist.insert(I->op_begin(), I->op_end());
4659 
4660       // The sinking may have enabled other instructions to be sunk, so we will
4661       // need to iterate.
4662       Changed = true;
4663     }
4664   } while (Changed);
4665 }
4666 
4667 void InnerLoopVectorizer::fixNonInductionPHIs(VPTransformState &State) {
4668   for (PHINode *OrigPhi : OrigPHIsToFix) {
4669     VPWidenPHIRecipe *VPPhi =
4670         cast<VPWidenPHIRecipe>(State.Plan->getVPValue(OrigPhi));
4671     PHINode *NewPhi = cast<PHINode>(State.get(VPPhi, 0));
4672     // Make sure the builder has a valid insert point.
4673     Builder.SetInsertPoint(NewPhi);
4674     for (unsigned i = 0; i < VPPhi->getNumOperands(); ++i) {
4675       VPValue *Inc = VPPhi->getIncomingValue(i);
4676       VPBasicBlock *VPBB = VPPhi->getIncomingBlock(i);
4677       NewPhi->addIncoming(State.get(Inc, 0), State.CFG.VPBB2IRBB[VPBB]);
4678     }
4679   }
4680 }
4681 
4682 bool InnerLoopVectorizer::useOrderedReductions(RecurrenceDescriptor &RdxDesc) {
4683   return Cost->useOrderedReductions(RdxDesc);
4684 }
4685 
4686 void InnerLoopVectorizer::widenGEP(GetElementPtrInst *GEP, VPValue *VPDef,
4687                                    VPUser &Operands, unsigned UF,
4688                                    ElementCount VF, bool IsPtrLoopInvariant,
4689                                    SmallBitVector &IsIndexLoopInvariant,
4690                                    VPTransformState &State) {
4691   // Construct a vector GEP by widening the operands of the scalar GEP as
4692   // necessary. We mark the vector GEP 'inbounds' if appropriate. A GEP
4693   // results in a vector of pointers when at least one operand of the GEP
4694   // is vector-typed. Thus, to keep the representation compact, we only use
4695   // vector-typed operands for loop-varying values.
4696 
4697   if (VF.isVector() && IsPtrLoopInvariant && IsIndexLoopInvariant.all()) {
4698     // If we are vectorizing, but the GEP has only loop-invariant operands,
4699     // the GEP we build (by only using vector-typed operands for
4700     // loop-varying values) would be a scalar pointer. Thus, to ensure we
4701     // produce a vector of pointers, we need to either arbitrarily pick an
4702     // operand to broadcast, or broadcast a clone of the original GEP.
4703     // Here, we broadcast a clone of the original.
4704     //
4705     // TODO: If at some point we decide to scalarize instructions having
4706     //       loop-invariant operands, this special case will no longer be
4707     //       required. We would add the scalarization decision to
4708     //       collectLoopScalars() and teach getVectorValue() to broadcast
4709     //       the lane-zero scalar value.
4710     auto *Clone = Builder.Insert(GEP->clone());
4711     for (unsigned Part = 0; Part < UF; ++Part) {
4712       Value *EntryPart = Builder.CreateVectorSplat(VF, Clone);
4713       State.set(VPDef, EntryPart, Part);
4714       addMetadata(EntryPart, GEP);
4715     }
4716   } else {
4717     // If the GEP has at least one loop-varying operand, we are sure to
4718     // produce a vector of pointers. But if we are only unrolling, we want
4719     // to produce a scalar GEP for each unroll part. Thus, the GEP we
4720     // produce with the code below will be scalar (if VF == 1) or vector
4721     // (otherwise). Note that for the unroll-only case, we still maintain
4722     // values in the vector mapping with initVector, as we do for other
4723     // instructions.
4724     for (unsigned Part = 0; Part < UF; ++Part) {
4725       // The pointer operand of the new GEP. If it's loop-invariant, we
4726       // won't broadcast it.
4727       auto *Ptr = IsPtrLoopInvariant
4728                       ? State.get(Operands.getOperand(0), VPIteration(0, 0))
4729                       : State.get(Operands.getOperand(0), Part);
4730 
4731       // Collect all the indices for the new GEP. If any index is
4732       // loop-invariant, we won't broadcast it.
4733       SmallVector<Value *, 4> Indices;
4734       for (unsigned I = 1, E = Operands.getNumOperands(); I < E; I++) {
4735         VPValue *Operand = Operands.getOperand(I);
4736         if (IsIndexLoopInvariant[I - 1])
4737           Indices.push_back(State.get(Operand, VPIteration(0, 0)));
4738         else
4739           Indices.push_back(State.get(Operand, Part));
4740       }
4741 
4742       // Create the new GEP. Note that this GEP may be a scalar if VF == 1,
4743       // but it should be a vector, otherwise.
4744       auto *NewGEP =
4745           GEP->isInBounds()
4746               ? Builder.CreateInBoundsGEP(GEP->getSourceElementType(), Ptr,
4747                                           Indices)
4748               : Builder.CreateGEP(GEP->getSourceElementType(), Ptr, Indices);
4749       assert((VF.isScalar() || NewGEP->getType()->isVectorTy()) &&
4750              "NewGEP is not a pointer vector");
4751       State.set(VPDef, NewGEP, Part);
4752       addMetadata(NewGEP, GEP);
4753     }
4754   }
4755 }
4756 
4757 void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN,
4758                                               VPWidenPHIRecipe *PhiR,
4759                                               VPTransformState &State) {
4760   PHINode *P = cast<PHINode>(PN);
4761   if (EnableVPlanNativePath) {
4762     // Currently we enter here in the VPlan-native path for non-induction
4763     // PHIs where all control flow is uniform. We simply widen these PHIs.
4764     // Create a vector phi with no operands - the vector phi operands will be
4765     // set at the end of vector code generation.
4766     Type *VecTy = (State.VF.isScalar())
4767                       ? PN->getType()
4768                       : VectorType::get(PN->getType(), State.VF);
4769     Value *VecPhi = Builder.CreatePHI(VecTy, PN->getNumOperands(), "vec.phi");
4770     State.set(PhiR, VecPhi, 0);
4771     OrigPHIsToFix.push_back(P);
4772 
4773     return;
4774   }
4775 
4776   assert(PN->getParent() == OrigLoop->getHeader() &&
4777          "Non-header phis should have been handled elsewhere");
4778 
4779   // In order to support recurrences we need to be able to vectorize Phi nodes.
4780   // Phi nodes have cycles, so we need to vectorize them in two stages. This is
4781   // stage #1: We create a new vector PHI node with no incoming edges. We'll use
4782   // this value when we vectorize all of the instructions that use the PHI.
4783   if (Legal->isFirstOrderRecurrence(P)) {
4784     Type *VecTy = State.VF.isScalar()
4785                       ? PN->getType()
4786                       : VectorType::get(PN->getType(), State.VF);
4787 
4788     for (unsigned Part = 0; Part < State.UF; ++Part) {
4789       Value *EntryPart = PHINode::Create(
4790           VecTy, 2, "vec.phi", &*LoopVectorBody->getFirstInsertionPt());
4791       State.set(PhiR, EntryPart, Part);
4792     }
4793       return;
4794   }
4795 
4796   assert(!Legal->isReductionVariable(P) &&
4797          "reductions should be handled elsewhere");
4798 
4799   setDebugLocFromInst(P);
4800 
4801   // This PHINode must be an induction variable.
4802   // Make sure that we know about it.
4803   assert(Legal->getInductionVars().count(P) && "Not an induction variable");
4804 
4805   InductionDescriptor II = Legal->getInductionVars().lookup(P);
4806   const DataLayout &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
4807 
4808   // FIXME: The newly created binary instructions should contain nsw/nuw flags,
4809   // which can be found from the original scalar operations.
4810   switch (II.getKind()) {
4811   case InductionDescriptor::IK_NoInduction:
4812     llvm_unreachable("Unknown induction");
4813   case InductionDescriptor::IK_IntInduction:
4814   case InductionDescriptor::IK_FpInduction:
4815     llvm_unreachable("Integer/fp induction is handled elsewhere.");
4816   case InductionDescriptor::IK_PtrInduction: {
4817     // Handle the pointer induction variable case.
4818     assert(P->getType()->isPointerTy() && "Unexpected type.");
4819 
4820     if (Cost->isScalarAfterVectorization(P, State.VF)) {
4821       // This is the normalized GEP that starts counting at zero.
4822       Value *PtrInd =
4823           Builder.CreateSExtOrTrunc(Induction, II.getStep()->getType());
4824       // Determine the number of scalars we need to generate for each unroll
4825       // iteration. If the instruction is uniform, we only need to generate the
4826       // first lane. Otherwise, we generate all VF values.
4827       bool IsUniform = Cost->isUniformAfterVectorization(P, State.VF);
4828       unsigned Lanes = IsUniform ? 1 : State.VF.getKnownMinValue();
4829 
4830       bool NeedsVectorIndex = !IsUniform && VF.isScalable();
4831       Value *UnitStepVec = nullptr, *PtrIndSplat = nullptr;
4832       if (NeedsVectorIndex) {
4833         Type *VecIVTy = VectorType::get(PtrInd->getType(), VF);
4834         UnitStepVec = Builder.CreateStepVector(VecIVTy);
4835         PtrIndSplat = Builder.CreateVectorSplat(VF, PtrInd);
4836       }
4837 
4838       for (unsigned Part = 0; Part < UF; ++Part) {
4839         Value *PartStart = createStepForVF(
4840             Builder, ConstantInt::get(PtrInd->getType(), Part), VF);
4841 
4842         if (NeedsVectorIndex) {
4843           Value *PartStartSplat = Builder.CreateVectorSplat(VF, PartStart);
4844           Value *Indices = Builder.CreateAdd(PartStartSplat, UnitStepVec);
4845           Value *GlobalIndices = Builder.CreateAdd(PtrIndSplat, Indices);
4846           Value *SclrGep =
4847               emitTransformedIndex(Builder, GlobalIndices, PSE.getSE(), DL, II);
4848           SclrGep->setName("next.gep");
4849           State.set(PhiR, SclrGep, Part);
4850           // We've cached the whole vector, which means we can support the
4851           // extraction of any lane.
4852           continue;
4853         }
4854 
4855         for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
4856           Value *Idx = Builder.CreateAdd(
4857               PartStart, ConstantInt::get(PtrInd->getType(), Lane));
4858           Value *GlobalIdx = Builder.CreateAdd(PtrInd, Idx);
4859           Value *SclrGep =
4860               emitTransformedIndex(Builder, GlobalIdx, PSE.getSE(), DL, II);
4861           SclrGep->setName("next.gep");
4862           State.set(PhiR, SclrGep, VPIteration(Part, Lane));
4863         }
4864       }
4865       return;
4866     }
4867     assert(isa<SCEVConstant>(II.getStep()) &&
4868            "Induction step not a SCEV constant!");
4869     Type *PhiType = II.getStep()->getType();
4870 
4871     // Build a pointer phi
4872     Value *ScalarStartValue = II.getStartValue();
4873     Type *ScStValueType = ScalarStartValue->getType();
4874     PHINode *NewPointerPhi =
4875         PHINode::Create(ScStValueType, 2, "pointer.phi", Induction);
4876     NewPointerPhi->addIncoming(ScalarStartValue, LoopVectorPreHeader);
4877 
4878     // A pointer induction, performed by using a gep
4879     BasicBlock *LoopLatch = LI->getLoopFor(LoopVectorBody)->getLoopLatch();
4880     Instruction *InductionLoc = LoopLatch->getTerminator();
4881     const SCEV *ScalarStep = II.getStep();
4882     SCEVExpander Exp(*PSE.getSE(), DL, "induction");
4883     Value *ScalarStepValue =
4884         Exp.expandCodeFor(ScalarStep, PhiType, InductionLoc);
4885     Value *RuntimeVF = getRuntimeVF(Builder, PhiType, VF);
4886     Value *NumUnrolledElems =
4887         Builder.CreateMul(RuntimeVF, ConstantInt::get(PhiType, State.UF));
4888     Value *InductionGEP = GetElementPtrInst::Create(
4889         ScStValueType->getPointerElementType(), NewPointerPhi,
4890         Builder.CreateMul(ScalarStepValue, NumUnrolledElems), "ptr.ind",
4891         InductionLoc);
4892     NewPointerPhi->addIncoming(InductionGEP, LoopLatch);
4893 
4894     // Create UF many actual address geps that use the pointer
4895     // phi as base and a vectorized version of the step value
4896     // (<step*0, ..., step*N>) as offset.
4897     for (unsigned Part = 0; Part < State.UF; ++Part) {
4898       Type *VecPhiType = VectorType::get(PhiType, State.VF);
4899       Value *StartOffsetScalar =
4900           Builder.CreateMul(RuntimeVF, ConstantInt::get(PhiType, Part));
4901       Value *StartOffset =
4902           Builder.CreateVectorSplat(State.VF, StartOffsetScalar);
4903       // Create a vector of consecutive numbers from zero to VF.
4904       StartOffset =
4905           Builder.CreateAdd(StartOffset, Builder.CreateStepVector(VecPhiType));
4906 
4907       Value *GEP = Builder.CreateGEP(
4908           ScStValueType->getPointerElementType(), NewPointerPhi,
4909           Builder.CreateMul(
4910               StartOffset, Builder.CreateVectorSplat(State.VF, ScalarStepValue),
4911               "vector.gep"));
4912       State.set(PhiR, GEP, Part);
4913     }
4914   }
4915   }
4916 }
4917 
4918 /// A helper function for checking whether an integer division-related
4919 /// instruction may divide by zero (in which case it must be predicated if
4920 /// executed conditionally in the scalar code).
4921 /// TODO: It may be worthwhile to generalize and check isKnownNonZero().
4922 /// Non-zero divisors that are non compile-time constants will not be
4923 /// converted into multiplication, so we will still end up scalarizing
4924 /// the division, but can do so w/o predication.
4925 static bool mayDivideByZero(Instruction &I) {
4926   assert((I.getOpcode() == Instruction::UDiv ||
4927           I.getOpcode() == Instruction::SDiv ||
4928           I.getOpcode() == Instruction::URem ||
4929           I.getOpcode() == Instruction::SRem) &&
4930          "Unexpected instruction");
4931   Value *Divisor = I.getOperand(1);
4932   auto *CInt = dyn_cast<ConstantInt>(Divisor);
4933   return !CInt || CInt->isZero();
4934 }
4935 
4936 void InnerLoopVectorizer::widenInstruction(Instruction &I, VPValue *Def,
4937                                            VPUser &User,
4938                                            VPTransformState &State) {
4939   switch (I.getOpcode()) {
4940   case Instruction::Call:
4941   case Instruction::Br:
4942   case Instruction::PHI:
4943   case Instruction::GetElementPtr:
4944   case Instruction::Select:
4945     llvm_unreachable("This instruction is handled by a different recipe.");
4946   case Instruction::UDiv:
4947   case Instruction::SDiv:
4948   case Instruction::SRem:
4949   case Instruction::URem:
4950   case Instruction::Add:
4951   case Instruction::FAdd:
4952   case Instruction::Sub:
4953   case Instruction::FSub:
4954   case Instruction::FNeg:
4955   case Instruction::Mul:
4956   case Instruction::FMul:
4957   case Instruction::FDiv:
4958   case Instruction::FRem:
4959   case Instruction::Shl:
4960   case Instruction::LShr:
4961   case Instruction::AShr:
4962   case Instruction::And:
4963   case Instruction::Or:
4964   case Instruction::Xor: {
4965     // Just widen unops and binops.
4966     setDebugLocFromInst(&I);
4967 
4968     for (unsigned Part = 0; Part < UF; ++Part) {
4969       SmallVector<Value *, 2> Ops;
4970       for (VPValue *VPOp : User.operands())
4971         Ops.push_back(State.get(VPOp, Part));
4972 
4973       Value *V = Builder.CreateNAryOp(I.getOpcode(), Ops);
4974 
4975       if (auto *VecOp = dyn_cast<Instruction>(V))
4976         VecOp->copyIRFlags(&I);
4977 
4978       // Use this vector value for all users of the original instruction.
4979       State.set(Def, V, Part);
4980       addMetadata(V, &I);
4981     }
4982 
4983     break;
4984   }
4985   case Instruction::ICmp:
4986   case Instruction::FCmp: {
4987     // Widen compares. Generate vector compares.
4988     bool FCmp = (I.getOpcode() == Instruction::FCmp);
4989     auto *Cmp = cast<CmpInst>(&I);
4990     setDebugLocFromInst(Cmp);
4991     for (unsigned Part = 0; Part < UF; ++Part) {
4992       Value *A = State.get(User.getOperand(0), Part);
4993       Value *B = State.get(User.getOperand(1), Part);
4994       Value *C = nullptr;
4995       if (FCmp) {
4996         // Propagate fast math flags.
4997         IRBuilder<>::FastMathFlagGuard FMFG(Builder);
4998         Builder.setFastMathFlags(Cmp->getFastMathFlags());
4999         C = Builder.CreateFCmp(Cmp->getPredicate(), A, B);
5000       } else {
5001         C = Builder.CreateICmp(Cmp->getPredicate(), A, B);
5002       }
5003       State.set(Def, C, Part);
5004       addMetadata(C, &I);
5005     }
5006 
5007     break;
5008   }
5009 
5010   case Instruction::ZExt:
5011   case Instruction::SExt:
5012   case Instruction::FPToUI:
5013   case Instruction::FPToSI:
5014   case Instruction::FPExt:
5015   case Instruction::PtrToInt:
5016   case Instruction::IntToPtr:
5017   case Instruction::SIToFP:
5018   case Instruction::UIToFP:
5019   case Instruction::Trunc:
5020   case Instruction::FPTrunc:
5021   case Instruction::BitCast: {
5022     auto *CI = cast<CastInst>(&I);
5023     setDebugLocFromInst(CI);
5024 
5025     /// Vectorize casts.
5026     Type *DestTy =
5027         (VF.isScalar()) ? CI->getType() : VectorType::get(CI->getType(), VF);
5028 
5029     for (unsigned Part = 0; Part < UF; ++Part) {
5030       Value *A = State.get(User.getOperand(0), Part);
5031       Value *Cast = Builder.CreateCast(CI->getOpcode(), A, DestTy);
5032       State.set(Def, Cast, Part);
5033       addMetadata(Cast, &I);
5034     }
5035     break;
5036   }
5037   default:
5038     // This instruction is not vectorized by simple widening.
5039     LLVM_DEBUG(dbgs() << "LV: Found an unhandled instruction: " << I);
5040     llvm_unreachable("Unhandled instruction!");
5041   } // end of switch.
5042 }
5043 
5044 void InnerLoopVectorizer::widenCallInstruction(CallInst &I, VPValue *Def,
5045                                                VPUser &ArgOperands,
5046                                                VPTransformState &State) {
5047   assert(!isa<DbgInfoIntrinsic>(I) &&
5048          "DbgInfoIntrinsic should have been dropped during VPlan construction");
5049   setDebugLocFromInst(&I);
5050 
5051   Module *M = I.getParent()->getParent()->getParent();
5052   auto *CI = cast<CallInst>(&I);
5053 
5054   SmallVector<Type *, 4> Tys;
5055   for (Value *ArgOperand : CI->arg_operands())
5056     Tys.push_back(ToVectorTy(ArgOperand->getType(), VF.getKnownMinValue()));
5057 
5058   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
5059 
5060   // The flag shows whether we use Intrinsic or a usual Call for vectorized
5061   // version of the instruction.
5062   // Is it beneficial to perform intrinsic call compared to lib call?
5063   bool NeedToScalarize = false;
5064   InstructionCost CallCost = Cost->getVectorCallCost(CI, VF, NeedToScalarize);
5065   InstructionCost IntrinsicCost = ID ? Cost->getVectorIntrinsicCost(CI, VF) : 0;
5066   bool UseVectorIntrinsic = ID && IntrinsicCost <= CallCost;
5067   assert((UseVectorIntrinsic || !NeedToScalarize) &&
5068          "Instruction should be scalarized elsewhere.");
5069   assert((IntrinsicCost.isValid() || CallCost.isValid()) &&
5070          "Either the intrinsic cost or vector call cost must be valid");
5071 
5072   for (unsigned Part = 0; Part < UF; ++Part) {
5073     SmallVector<Type *, 2> TysForDecl = {CI->getType()};
5074     SmallVector<Value *, 4> Args;
5075     for (auto &I : enumerate(ArgOperands.operands())) {
5076       // Some intrinsics have a scalar argument - don't replace it with a
5077       // vector.
5078       Value *Arg;
5079       if (!UseVectorIntrinsic || !hasVectorInstrinsicScalarOpd(ID, I.index()))
5080         Arg = State.get(I.value(), Part);
5081       else {
5082         Arg = State.get(I.value(), VPIteration(0, 0));
5083         if (hasVectorInstrinsicOverloadedScalarOpd(ID, I.index()))
5084           TysForDecl.push_back(Arg->getType());
5085       }
5086       Args.push_back(Arg);
5087     }
5088 
5089     Function *VectorF;
5090     if (UseVectorIntrinsic) {
5091       // Use vector version of the intrinsic.
5092       if (VF.isVector())
5093         TysForDecl[0] = VectorType::get(CI->getType()->getScalarType(), VF);
5094       VectorF = Intrinsic::getDeclaration(M, ID, TysForDecl);
5095       assert(VectorF && "Can't retrieve vector intrinsic.");
5096     } else {
5097       // Use vector version of the function call.
5098       const VFShape Shape = VFShape::get(*CI, VF, false /*HasGlobalPred*/);
5099 #ifndef NDEBUG
5100       assert(VFDatabase(*CI).getVectorizedFunction(Shape) != nullptr &&
5101              "Can't create vector function.");
5102 #endif
5103         VectorF = VFDatabase(*CI).getVectorizedFunction(Shape);
5104     }
5105       SmallVector<OperandBundleDef, 1> OpBundles;
5106       CI->getOperandBundlesAsDefs(OpBundles);
5107       CallInst *V = Builder.CreateCall(VectorF, Args, OpBundles);
5108 
5109       if (isa<FPMathOperator>(V))
5110         V->copyFastMathFlags(CI);
5111 
5112       State.set(Def, V, Part);
5113       addMetadata(V, &I);
5114   }
5115 }
5116 
5117 void InnerLoopVectorizer::widenSelectInstruction(SelectInst &I, VPValue *VPDef,
5118                                                  VPUser &Operands,
5119                                                  bool InvariantCond,
5120                                                  VPTransformState &State) {
5121   setDebugLocFromInst(&I);
5122 
5123   // The condition can be loop invariant  but still defined inside the
5124   // loop. This means that we can't just use the original 'cond' value.
5125   // We have to take the 'vectorized' value and pick the first lane.
5126   // Instcombine will make this a no-op.
5127   auto *InvarCond = InvariantCond
5128                         ? State.get(Operands.getOperand(0), VPIteration(0, 0))
5129                         : nullptr;
5130 
5131   for (unsigned Part = 0; Part < UF; ++Part) {
5132     Value *Cond =
5133         InvarCond ? InvarCond : State.get(Operands.getOperand(0), Part);
5134     Value *Op0 = State.get(Operands.getOperand(1), Part);
5135     Value *Op1 = State.get(Operands.getOperand(2), Part);
5136     Value *Sel = Builder.CreateSelect(Cond, Op0, Op1);
5137     State.set(VPDef, Sel, Part);
5138     addMetadata(Sel, &I);
5139   }
5140 }
5141 
5142 void LoopVectorizationCostModel::collectLoopScalars(ElementCount VF) {
5143   // We should not collect Scalars more than once per VF. Right now, this
5144   // function is called from collectUniformsAndScalars(), which already does
5145   // this check. Collecting Scalars for VF=1 does not make any sense.
5146   assert(VF.isVector() && Scalars.find(VF) == Scalars.end() &&
5147          "This function should not be visited twice for the same VF");
5148 
5149   SmallSetVector<Instruction *, 8> Worklist;
5150 
5151   // These sets are used to seed the analysis with pointers used by memory
5152   // accesses that will remain scalar.
5153   SmallSetVector<Instruction *, 8> ScalarPtrs;
5154   SmallPtrSet<Instruction *, 8> PossibleNonScalarPtrs;
5155   auto *Latch = TheLoop->getLoopLatch();
5156 
5157   // A helper that returns true if the use of Ptr by MemAccess will be scalar.
5158   // The pointer operands of loads and stores will be scalar as long as the
5159   // memory access is not a gather or scatter operation. The value operand of a
5160   // store will remain scalar if the store is scalarized.
5161   auto isScalarUse = [&](Instruction *MemAccess, Value *Ptr) {
5162     InstWidening WideningDecision = getWideningDecision(MemAccess, VF);
5163     assert(WideningDecision != CM_Unknown &&
5164            "Widening decision should be ready at this moment");
5165     if (auto *Store = dyn_cast<StoreInst>(MemAccess))
5166       if (Ptr == Store->getValueOperand())
5167         return WideningDecision == CM_Scalarize;
5168     assert(Ptr == getLoadStorePointerOperand(MemAccess) &&
5169            "Ptr is neither a value or pointer operand");
5170     return WideningDecision != CM_GatherScatter;
5171   };
5172 
5173   // A helper that returns true if the given value is a bitcast or
5174   // getelementptr instruction contained in the loop.
5175   auto isLoopVaryingBitCastOrGEP = [&](Value *V) {
5176     return ((isa<BitCastInst>(V) && V->getType()->isPointerTy()) ||
5177             isa<GetElementPtrInst>(V)) &&
5178            !TheLoop->isLoopInvariant(V);
5179   };
5180 
5181   auto isScalarPtrInduction = [&](Instruction *MemAccess, Value *Ptr) {
5182     if (!isa<PHINode>(Ptr) ||
5183         !Legal->getInductionVars().count(cast<PHINode>(Ptr)))
5184       return false;
5185     auto &Induction = Legal->getInductionVars()[cast<PHINode>(Ptr)];
5186     if (Induction.getKind() != InductionDescriptor::IK_PtrInduction)
5187       return false;
5188     return isScalarUse(MemAccess, Ptr);
5189   };
5190 
5191   // A helper that evaluates a memory access's use of a pointer. If the
5192   // pointer is actually the pointer induction of a loop, it is being
5193   // inserted into Worklist. If the use will be a scalar use, and the
5194   // pointer is only used by memory accesses, we place the pointer in
5195   // ScalarPtrs. Otherwise, the pointer is placed in PossibleNonScalarPtrs.
5196   auto evaluatePtrUse = [&](Instruction *MemAccess, Value *Ptr) {
5197     if (isScalarPtrInduction(MemAccess, Ptr)) {
5198       Worklist.insert(cast<Instruction>(Ptr));
5199       Instruction *Update = cast<Instruction>(
5200           cast<PHINode>(Ptr)->getIncomingValueForBlock(Latch));
5201       Worklist.insert(Update);
5202       LLVM_DEBUG(dbgs() << "LV: Found new scalar instruction: " << *Ptr
5203                         << "\n");
5204       LLVM_DEBUG(dbgs() << "LV: Found new scalar instruction: " << *Update
5205                         << "\n");
5206       return;
5207     }
5208     // We only care about bitcast and getelementptr instructions contained in
5209     // the loop.
5210     if (!isLoopVaryingBitCastOrGEP(Ptr))
5211       return;
5212 
5213     // If the pointer has already been identified as scalar (e.g., if it was
5214     // also identified as uniform), there's nothing to do.
5215     auto *I = cast<Instruction>(Ptr);
5216     if (Worklist.count(I))
5217       return;
5218 
5219     // If the use of the pointer will be a scalar use, and all users of the
5220     // pointer are memory accesses, place the pointer in ScalarPtrs. Otherwise,
5221     // place the pointer in PossibleNonScalarPtrs.
5222     if (isScalarUse(MemAccess, Ptr) && llvm::all_of(I->users(), [&](User *U) {
5223           return isa<LoadInst>(U) || isa<StoreInst>(U);
5224         }))
5225       ScalarPtrs.insert(I);
5226     else
5227       PossibleNonScalarPtrs.insert(I);
5228   };
5229 
5230   // We seed the scalars analysis with three classes of instructions: (1)
5231   // instructions marked uniform-after-vectorization and (2) bitcast,
5232   // getelementptr and (pointer) phi instructions used by memory accesses
5233   // requiring a scalar use.
5234   //
5235   // (1) Add to the worklist all instructions that have been identified as
5236   // uniform-after-vectorization.
5237   Worklist.insert(Uniforms[VF].begin(), Uniforms[VF].end());
5238 
5239   // (2) Add to the worklist all bitcast and getelementptr instructions used by
5240   // memory accesses requiring a scalar use. The pointer operands of loads and
5241   // stores will be scalar as long as the memory accesses is not a gather or
5242   // scatter operation. The value operand of a store will remain scalar if the
5243   // store is scalarized.
5244   for (auto *BB : TheLoop->blocks())
5245     for (auto &I : *BB) {
5246       if (auto *Load = dyn_cast<LoadInst>(&I)) {
5247         evaluatePtrUse(Load, Load->getPointerOperand());
5248       } else if (auto *Store = dyn_cast<StoreInst>(&I)) {
5249         evaluatePtrUse(Store, Store->getPointerOperand());
5250         evaluatePtrUse(Store, Store->getValueOperand());
5251       }
5252     }
5253   for (auto *I : ScalarPtrs)
5254     if (!PossibleNonScalarPtrs.count(I)) {
5255       LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *I << "\n");
5256       Worklist.insert(I);
5257     }
5258 
5259   // Insert the forced scalars.
5260   // FIXME: Currently widenPHIInstruction() often creates a dead vector
5261   // induction variable when the PHI user is scalarized.
5262   auto ForcedScalar = ForcedScalars.find(VF);
5263   if (ForcedScalar != ForcedScalars.end())
5264     for (auto *I : ForcedScalar->second)
5265       Worklist.insert(I);
5266 
5267   // Expand the worklist by looking through any bitcasts and getelementptr
5268   // instructions we've already identified as scalar. This is similar to the
5269   // expansion step in collectLoopUniforms(); however, here we're only
5270   // expanding to include additional bitcasts and getelementptr instructions.
5271   unsigned Idx = 0;
5272   while (Idx != Worklist.size()) {
5273     Instruction *Dst = Worklist[Idx++];
5274     if (!isLoopVaryingBitCastOrGEP(Dst->getOperand(0)))
5275       continue;
5276     auto *Src = cast<Instruction>(Dst->getOperand(0));
5277     if (llvm::all_of(Src->users(), [&](User *U) -> bool {
5278           auto *J = cast<Instruction>(U);
5279           return !TheLoop->contains(J) || Worklist.count(J) ||
5280                  ((isa<LoadInst>(J) || isa<StoreInst>(J)) &&
5281                   isScalarUse(J, Src));
5282         })) {
5283       Worklist.insert(Src);
5284       LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Src << "\n");
5285     }
5286   }
5287 
5288   // An induction variable will remain scalar if all users of the induction
5289   // variable and induction variable update remain scalar.
5290   for (auto &Induction : Legal->getInductionVars()) {
5291     auto *Ind = Induction.first;
5292     auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
5293 
5294     // If tail-folding is applied, the primary induction variable will be used
5295     // to feed a vector compare.
5296     if (Ind == Legal->getPrimaryInduction() && foldTailByMasking())
5297       continue;
5298 
5299     // Determine if all users of the induction variable are scalar after
5300     // vectorization.
5301     auto ScalarInd = llvm::all_of(Ind->users(), [&](User *U) -> bool {
5302       auto *I = cast<Instruction>(U);
5303       return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I);
5304     });
5305     if (!ScalarInd)
5306       continue;
5307 
5308     // Determine if all users of the induction variable update instruction are
5309     // scalar after vectorization.
5310     auto ScalarIndUpdate =
5311         llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
5312           auto *I = cast<Instruction>(U);
5313           return I == Ind || !TheLoop->contains(I) || Worklist.count(I);
5314         });
5315     if (!ScalarIndUpdate)
5316       continue;
5317 
5318     // The induction variable and its update instruction will remain scalar.
5319     Worklist.insert(Ind);
5320     Worklist.insert(IndUpdate);
5321     LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Ind << "\n");
5322     LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *IndUpdate
5323                       << "\n");
5324   }
5325 
5326   Scalars[VF].insert(Worklist.begin(), Worklist.end());
5327 }
5328 
5329 bool LoopVectorizationCostModel::isScalarWithPredication(Instruction *I) const {
5330   if (!blockNeedsPredication(I->getParent()))
5331     return false;
5332   switch(I->getOpcode()) {
5333   default:
5334     break;
5335   case Instruction::Load:
5336   case Instruction::Store: {
5337     if (!Legal->isMaskRequired(I))
5338       return false;
5339     auto *Ptr = getLoadStorePointerOperand(I);
5340     auto *Ty = getLoadStoreType(I);
5341     const Align Alignment = getLoadStoreAlignment(I);
5342     return isa<LoadInst>(I) ? !(isLegalMaskedLoad(Ty, Ptr, Alignment) ||
5343                                 TTI.isLegalMaskedGather(Ty, Alignment))
5344                             : !(isLegalMaskedStore(Ty, Ptr, Alignment) ||
5345                                 TTI.isLegalMaskedScatter(Ty, Alignment));
5346   }
5347   case Instruction::UDiv:
5348   case Instruction::SDiv:
5349   case Instruction::SRem:
5350   case Instruction::URem:
5351     return mayDivideByZero(*I);
5352   }
5353   return false;
5354 }
5355 
5356 bool LoopVectorizationCostModel::interleavedAccessCanBeWidened(
5357     Instruction *I, ElementCount VF) {
5358   assert(isAccessInterleaved(I) && "Expecting interleaved access.");
5359   assert(getWideningDecision(I, VF) == CM_Unknown &&
5360          "Decision should not be set yet.");
5361   auto *Group = getInterleavedAccessGroup(I);
5362   assert(Group && "Must have a group.");
5363 
5364   // If the instruction's allocated size doesn't equal it's type size, it
5365   // requires padding and will be scalarized.
5366   auto &DL = I->getModule()->getDataLayout();
5367   auto *ScalarTy = getLoadStoreType(I);
5368   if (hasIrregularType(ScalarTy, DL))
5369     return false;
5370 
5371   // Check if masking is required.
5372   // A Group may need masking for one of two reasons: it resides in a block that
5373   // needs predication, or it was decided to use masking to deal with gaps.
5374   bool PredicatedAccessRequiresMasking =
5375       Legal->blockNeedsPredication(I->getParent()) && Legal->isMaskRequired(I);
5376   bool AccessWithGapsRequiresMasking =
5377       Group->requiresScalarEpilogue() && !isScalarEpilogueAllowed();
5378   if (!PredicatedAccessRequiresMasking && !AccessWithGapsRequiresMasking)
5379     return true;
5380 
5381   // If masked interleaving is required, we expect that the user/target had
5382   // enabled it, because otherwise it either wouldn't have been created or
5383   // it should have been invalidated by the CostModel.
5384   assert(useMaskedInterleavedAccesses(TTI) &&
5385          "Masked interleave-groups for predicated accesses are not enabled.");
5386 
5387   auto *Ty = getLoadStoreType(I);
5388   const Align Alignment = getLoadStoreAlignment(I);
5389   return isa<LoadInst>(I) ? TTI.isLegalMaskedLoad(Ty, Alignment)
5390                           : TTI.isLegalMaskedStore(Ty, Alignment);
5391 }
5392 
5393 bool LoopVectorizationCostModel::memoryInstructionCanBeWidened(
5394     Instruction *I, ElementCount VF) {
5395   // Get and ensure we have a valid memory instruction.
5396   LoadInst *LI = dyn_cast<LoadInst>(I);
5397   StoreInst *SI = dyn_cast<StoreInst>(I);
5398   assert((LI || SI) && "Invalid memory instruction");
5399 
5400   auto *Ptr = getLoadStorePointerOperand(I);
5401 
5402   // In order to be widened, the pointer should be consecutive, first of all.
5403   if (!Legal->isConsecutivePtr(Ptr))
5404     return false;
5405 
5406   // If the instruction is a store located in a predicated block, it will be
5407   // scalarized.
5408   if (isScalarWithPredication(I))
5409     return false;
5410 
5411   // If the instruction's allocated size doesn't equal it's type size, it
5412   // requires padding and will be scalarized.
5413   auto &DL = I->getModule()->getDataLayout();
5414   auto *ScalarTy = LI ? LI->getType() : SI->getValueOperand()->getType();
5415   if (hasIrregularType(ScalarTy, DL))
5416     return false;
5417 
5418   return true;
5419 }
5420 
5421 void LoopVectorizationCostModel::collectLoopUniforms(ElementCount VF) {
5422   // We should not collect Uniforms more than once per VF. Right now,
5423   // this function is called from collectUniformsAndScalars(), which
5424   // already does this check. Collecting Uniforms for VF=1 does not make any
5425   // sense.
5426 
5427   assert(VF.isVector() && Uniforms.find(VF) == Uniforms.end() &&
5428          "This function should not be visited twice for the same VF");
5429 
5430   // Visit the list of Uniforms. If we'll not find any uniform value, we'll
5431   // not analyze again.  Uniforms.count(VF) will return 1.
5432   Uniforms[VF].clear();
5433 
5434   // We now know that the loop is vectorizable!
5435   // Collect instructions inside the loop that will remain uniform after
5436   // vectorization.
5437 
5438   // Global values, params and instructions outside of current loop are out of
5439   // scope.
5440   auto isOutOfScope = [&](Value *V) -> bool {
5441     Instruction *I = dyn_cast<Instruction>(V);
5442     return (!I || !TheLoop->contains(I));
5443   };
5444 
5445   SetVector<Instruction *> Worklist;
5446   BasicBlock *Latch = TheLoop->getLoopLatch();
5447 
5448   // Instructions that are scalar with predication must not be considered
5449   // uniform after vectorization, because that would create an erroneous
5450   // replicating region where only a single instance out of VF should be formed.
5451   // TODO: optimize such seldom cases if found important, see PR40816.
5452   auto addToWorklistIfAllowed = [&](Instruction *I) -> void {
5453     if (isOutOfScope(I)) {
5454       LLVM_DEBUG(dbgs() << "LV: Found not uniform due to scope: "
5455                         << *I << "\n");
5456       return;
5457     }
5458     if (isScalarWithPredication(I)) {
5459       LLVM_DEBUG(dbgs() << "LV: Found not uniform being ScalarWithPredication: "
5460                         << *I << "\n");
5461       return;
5462     }
5463     LLVM_DEBUG(dbgs() << "LV: Found uniform instruction: " << *I << "\n");
5464     Worklist.insert(I);
5465   };
5466 
5467   // Start with the conditional branch. If the branch condition is an
5468   // instruction contained in the loop that is only used by the branch, it is
5469   // uniform.
5470   auto *Cmp = dyn_cast<Instruction>(Latch->getTerminator()->getOperand(0));
5471   if (Cmp && TheLoop->contains(Cmp) && Cmp->hasOneUse())
5472     addToWorklistIfAllowed(Cmp);
5473 
5474   auto isUniformDecision = [&](Instruction *I, ElementCount VF) {
5475     InstWidening WideningDecision = getWideningDecision(I, VF);
5476     assert(WideningDecision != CM_Unknown &&
5477            "Widening decision should be ready at this moment");
5478 
5479     // A uniform memory op is itself uniform.  We exclude uniform stores
5480     // here as they demand the last lane, not the first one.
5481     if (isa<LoadInst>(I) && Legal->isUniformMemOp(*I)) {
5482       assert(WideningDecision == CM_Scalarize);
5483       return true;
5484     }
5485 
5486     return (WideningDecision == CM_Widen ||
5487             WideningDecision == CM_Widen_Reverse ||
5488             WideningDecision == CM_Interleave);
5489   };
5490 
5491 
5492   // Returns true if Ptr is the pointer operand of a memory access instruction
5493   // I, and I is known to not require scalarization.
5494   auto isVectorizedMemAccessUse = [&](Instruction *I, Value *Ptr) -> bool {
5495     return getLoadStorePointerOperand(I) == Ptr && isUniformDecision(I, VF);
5496   };
5497 
5498   // Holds a list of values which are known to have at least one uniform use.
5499   // Note that there may be other uses which aren't uniform.  A "uniform use"
5500   // here is something which only demands lane 0 of the unrolled iterations;
5501   // it does not imply that all lanes produce the same value (e.g. this is not
5502   // the usual meaning of uniform)
5503   SetVector<Value *> HasUniformUse;
5504 
5505   // Scan the loop for instructions which are either a) known to have only
5506   // lane 0 demanded or b) are uses which demand only lane 0 of their operand.
5507   for (auto *BB : TheLoop->blocks())
5508     for (auto &I : *BB) {
5509       // If there's no pointer operand, there's nothing to do.
5510       auto *Ptr = getLoadStorePointerOperand(&I);
5511       if (!Ptr)
5512         continue;
5513 
5514       // A uniform memory op is itself uniform.  We exclude uniform stores
5515       // here as they demand the last lane, not the first one.
5516       if (isa<LoadInst>(I) && Legal->isUniformMemOp(I))
5517         addToWorklistIfAllowed(&I);
5518 
5519       if (isUniformDecision(&I, VF)) {
5520         assert(isVectorizedMemAccessUse(&I, Ptr) && "consistency check");
5521         HasUniformUse.insert(Ptr);
5522       }
5523     }
5524 
5525   // Add to the worklist any operands which have *only* uniform (e.g. lane 0
5526   // demanding) users.  Since loops are assumed to be in LCSSA form, this
5527   // disallows uses outside the loop as well.
5528   for (auto *V : HasUniformUse) {
5529     if (isOutOfScope(V))
5530       continue;
5531     auto *I = cast<Instruction>(V);
5532     auto UsersAreMemAccesses =
5533       llvm::all_of(I->users(), [&](User *U) -> bool {
5534         return isVectorizedMemAccessUse(cast<Instruction>(U), V);
5535       });
5536     if (UsersAreMemAccesses)
5537       addToWorklistIfAllowed(I);
5538   }
5539 
5540   // Expand Worklist in topological order: whenever a new instruction
5541   // is added , its users should be already inside Worklist.  It ensures
5542   // a uniform instruction will only be used by uniform instructions.
5543   unsigned idx = 0;
5544   while (idx != Worklist.size()) {
5545     Instruction *I = Worklist[idx++];
5546 
5547     for (auto OV : I->operand_values()) {
5548       // isOutOfScope operands cannot be uniform instructions.
5549       if (isOutOfScope(OV))
5550         continue;
5551       // First order recurrence Phi's should typically be considered
5552       // non-uniform.
5553       auto *OP = dyn_cast<PHINode>(OV);
5554       if (OP && Legal->isFirstOrderRecurrence(OP))
5555         continue;
5556       // If all the users of the operand are uniform, then add the
5557       // operand into the uniform worklist.
5558       auto *OI = cast<Instruction>(OV);
5559       if (llvm::all_of(OI->users(), [&](User *U) -> bool {
5560             auto *J = cast<Instruction>(U);
5561             return Worklist.count(J) || isVectorizedMemAccessUse(J, OI);
5562           }))
5563         addToWorklistIfAllowed(OI);
5564     }
5565   }
5566 
5567   // For an instruction to be added into Worklist above, all its users inside
5568   // the loop should also be in Worklist. However, this condition cannot be
5569   // true for phi nodes that form a cyclic dependence. We must process phi
5570   // nodes separately. An induction variable will remain uniform if all users
5571   // of the induction variable and induction variable update remain uniform.
5572   // The code below handles both pointer and non-pointer induction variables.
5573   for (auto &Induction : Legal->getInductionVars()) {
5574     auto *Ind = Induction.first;
5575     auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
5576 
5577     // Determine if all users of the induction variable are uniform after
5578     // vectorization.
5579     auto UniformInd = llvm::all_of(Ind->users(), [&](User *U) -> bool {
5580       auto *I = cast<Instruction>(U);
5581       return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) ||
5582              isVectorizedMemAccessUse(I, Ind);
5583     });
5584     if (!UniformInd)
5585       continue;
5586 
5587     // Determine if all users of the induction variable update instruction are
5588     // uniform after vectorization.
5589     auto UniformIndUpdate =
5590         llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
5591           auto *I = cast<Instruction>(U);
5592           return I == Ind || !TheLoop->contains(I) || Worklist.count(I) ||
5593                  isVectorizedMemAccessUse(I, IndUpdate);
5594         });
5595     if (!UniformIndUpdate)
5596       continue;
5597 
5598     // The induction variable and its update instruction will remain uniform.
5599     addToWorklistIfAllowed(Ind);
5600     addToWorklistIfAllowed(IndUpdate);
5601   }
5602 
5603   Uniforms[VF].insert(Worklist.begin(), Worklist.end());
5604 }
5605 
5606 bool LoopVectorizationCostModel::runtimeChecksRequired() {
5607   LLVM_DEBUG(dbgs() << "LV: Performing code size checks.\n");
5608 
5609   if (Legal->getRuntimePointerChecking()->Need) {
5610     reportVectorizationFailure("Runtime ptr check is required with -Os/-Oz",
5611         "runtime pointer checks needed. Enable vectorization of this "
5612         "loop with '#pragma clang loop vectorize(enable)' when "
5613         "compiling with -Os/-Oz",
5614         "CantVersionLoopWithOptForSize", ORE, TheLoop);
5615     return true;
5616   }
5617 
5618   if (!PSE.getUnionPredicate().getPredicates().empty()) {
5619     reportVectorizationFailure("Runtime SCEV check is required with -Os/-Oz",
5620         "runtime SCEV checks needed. Enable vectorization of this "
5621         "loop with '#pragma clang loop vectorize(enable)' when "
5622         "compiling with -Os/-Oz",
5623         "CantVersionLoopWithOptForSize", ORE, TheLoop);
5624     return true;
5625   }
5626 
5627   // FIXME: Avoid specializing for stride==1 instead of bailing out.
5628   if (!Legal->getLAI()->getSymbolicStrides().empty()) {
5629     reportVectorizationFailure("Runtime stride check for small trip count",
5630         "runtime stride == 1 checks needed. Enable vectorization of "
5631         "this loop without such check by compiling with -Os/-Oz",
5632         "CantVersionLoopWithOptForSize", ORE, TheLoop);
5633     return true;
5634   }
5635 
5636   return false;
5637 }
5638 
5639 ElementCount
5640 LoopVectorizationCostModel::getMaxLegalScalableVF(unsigned MaxSafeElements) {
5641   if (!TTI.supportsScalableVectors() && !ForceTargetSupportsScalableVectors) {
5642     reportVectorizationInfo(
5643         "Disabling scalable vectorization, because target does not "
5644         "support scalable vectors.",
5645         "ScalableVectorsUnsupported", ORE, TheLoop);
5646     return ElementCount::getScalable(0);
5647   }
5648 
5649   if (Hints->isScalableVectorizationDisabled()) {
5650     reportVectorizationInfo("Scalable vectorization is explicitly disabled",
5651                             "ScalableVectorizationDisabled", ORE, TheLoop);
5652     return ElementCount::getScalable(0);
5653   }
5654 
5655   auto MaxScalableVF = ElementCount::getScalable(
5656       std::numeric_limits<ElementCount::ScalarTy>::max());
5657 
5658   // Test that the loop-vectorizer can legalize all operations for this MaxVF.
5659   // FIXME: While for scalable vectors this is currently sufficient, this should
5660   // be replaced by a more detailed mechanism that filters out specific VFs,
5661   // instead of invalidating vectorization for a whole set of VFs based on the
5662   // MaxVF.
5663 
5664   // Disable scalable vectorization if the loop contains unsupported reductions.
5665   if (!canVectorizeReductions(MaxScalableVF)) {
5666     reportVectorizationInfo(
5667         "Scalable vectorization not supported for the reduction "
5668         "operations found in this loop.",
5669         "ScalableVFUnfeasible", ORE, TheLoop);
5670     return ElementCount::getScalable(0);
5671   }
5672 
5673   // Disable scalable vectorization if the loop contains any instructions
5674   // with element types not supported for scalable vectors.
5675   if (any_of(ElementTypesInLoop, [&](Type *Ty) {
5676         return !Ty->isVoidTy() &&
5677                !this->TTI.isElementTypeLegalForScalableVector(Ty);
5678       })) {
5679     reportVectorizationInfo("Scalable vectorization is not supported "
5680                             "for all element types found in this loop.",
5681                             "ScalableVFUnfeasible", ORE, TheLoop);
5682     return ElementCount::getScalable(0);
5683   }
5684 
5685   if (Legal->isSafeForAnyVectorWidth())
5686     return MaxScalableVF;
5687 
5688   // Limit MaxScalableVF by the maximum safe dependence distance.
5689   Optional<unsigned> MaxVScale = TTI.getMaxVScale();
5690   MaxScalableVF = ElementCount::getScalable(
5691       MaxVScale ? (MaxSafeElements / MaxVScale.getValue()) : 0);
5692   if (!MaxScalableVF)
5693     reportVectorizationInfo(
5694         "Max legal vector width too small, scalable vectorization "
5695         "unfeasible.",
5696         "ScalableVFUnfeasible", ORE, TheLoop);
5697 
5698   return MaxScalableVF;
5699 }
5700 
5701 FixedScalableVFPair
5702 LoopVectorizationCostModel::computeFeasibleMaxVF(unsigned ConstTripCount,
5703                                                  ElementCount UserVF) {
5704   MinBWs = computeMinimumValueSizes(TheLoop->getBlocks(), *DB, &TTI);
5705   unsigned SmallestType, WidestType;
5706   std::tie(SmallestType, WidestType) = getSmallestAndWidestTypes();
5707 
5708   // Get the maximum safe dependence distance in bits computed by LAA.
5709   // It is computed by MaxVF * sizeOf(type) * 8, where type is taken from
5710   // the memory accesses that is most restrictive (involved in the smallest
5711   // dependence distance).
5712   unsigned MaxSafeElements =
5713       PowerOf2Floor(Legal->getMaxSafeVectorWidthInBits() / WidestType);
5714 
5715   auto MaxSafeFixedVF = ElementCount::getFixed(MaxSafeElements);
5716   auto MaxSafeScalableVF = getMaxLegalScalableVF(MaxSafeElements);
5717 
5718   LLVM_DEBUG(dbgs() << "LV: The max safe fixed VF is: " << MaxSafeFixedVF
5719                     << ".\n");
5720   LLVM_DEBUG(dbgs() << "LV: The max safe scalable VF is: " << MaxSafeScalableVF
5721                     << ".\n");
5722 
5723   // First analyze the UserVF, fall back if the UserVF should be ignored.
5724   if (UserVF) {
5725     auto MaxSafeUserVF =
5726         UserVF.isScalable() ? MaxSafeScalableVF : MaxSafeFixedVF;
5727 
5728     if (ElementCount::isKnownLE(UserVF, MaxSafeUserVF))
5729       return UserVF;
5730 
5731     assert(ElementCount::isKnownGT(UserVF, MaxSafeUserVF));
5732 
5733     // Only clamp if the UserVF is not scalable. If the UserVF is scalable, it
5734     // is better to ignore the hint and let the compiler choose a suitable VF.
5735     if (!UserVF.isScalable()) {
5736       LLVM_DEBUG(dbgs() << "LV: User VF=" << UserVF
5737                         << " is unsafe, clamping to max safe VF="
5738                         << MaxSafeFixedVF << ".\n");
5739       ORE->emit([&]() {
5740         return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationFactor",
5741                                           TheLoop->getStartLoc(),
5742                                           TheLoop->getHeader())
5743                << "User-specified vectorization factor "
5744                << ore::NV("UserVectorizationFactor", UserVF)
5745                << " is unsafe, clamping to maximum safe vectorization factor "
5746                << ore::NV("VectorizationFactor", MaxSafeFixedVF);
5747       });
5748       return MaxSafeFixedVF;
5749     }
5750 
5751     LLVM_DEBUG(dbgs() << "LV: User VF=" << UserVF
5752                       << " is unsafe. Ignoring scalable UserVF.\n");
5753     ORE->emit([&]() {
5754       return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationFactor",
5755                                         TheLoop->getStartLoc(),
5756                                         TheLoop->getHeader())
5757              << "User-specified vectorization factor "
5758              << ore::NV("UserVectorizationFactor", UserVF)
5759              << " is unsafe. Ignoring the hint to let the compiler pick a "
5760                 "suitable VF.";
5761     });
5762   }
5763 
5764   LLVM_DEBUG(dbgs() << "LV: The Smallest and Widest types: " << SmallestType
5765                     << " / " << WidestType << " bits.\n");
5766 
5767   FixedScalableVFPair Result(ElementCount::getFixed(1),
5768                              ElementCount::getScalable(0));
5769   if (auto MaxVF = getMaximizedVFForTarget(ConstTripCount, SmallestType,
5770                                            WidestType, MaxSafeFixedVF))
5771     Result.FixedVF = MaxVF;
5772 
5773   if (auto MaxVF = getMaximizedVFForTarget(ConstTripCount, SmallestType,
5774                                            WidestType, MaxSafeScalableVF))
5775     if (MaxVF.isScalable()) {
5776       Result.ScalableVF = MaxVF;
5777       LLVM_DEBUG(dbgs() << "LV: Found feasible scalable VF = " << MaxVF
5778                         << "\n");
5779     }
5780 
5781   return Result;
5782 }
5783 
5784 FixedScalableVFPair
5785 LoopVectorizationCostModel::computeMaxVF(ElementCount UserVF, unsigned UserIC) {
5786   if (Legal->getRuntimePointerChecking()->Need && TTI.hasBranchDivergence()) {
5787     // TODO: It may by useful to do since it's still likely to be dynamically
5788     // uniform if the target can skip.
5789     reportVectorizationFailure(
5790         "Not inserting runtime ptr check for divergent target",
5791         "runtime pointer checks needed. Not enabled for divergent target",
5792         "CantVersionLoopWithDivergentTarget", ORE, TheLoop);
5793     return FixedScalableVFPair::getNone();
5794   }
5795 
5796   unsigned TC = PSE.getSE()->getSmallConstantTripCount(TheLoop);
5797   LLVM_DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
5798   if (TC == 1) {
5799     reportVectorizationFailure("Single iteration (non) loop",
5800         "loop trip count is one, irrelevant for vectorization",
5801         "SingleIterationLoop", ORE, TheLoop);
5802     return FixedScalableVFPair::getNone();
5803   }
5804 
5805   switch (ScalarEpilogueStatus) {
5806   case CM_ScalarEpilogueAllowed:
5807     return computeFeasibleMaxVF(TC, UserVF);
5808   case CM_ScalarEpilogueNotAllowedUsePredicate:
5809     LLVM_FALLTHROUGH;
5810   case CM_ScalarEpilogueNotNeededUsePredicate:
5811     LLVM_DEBUG(
5812         dbgs() << "LV: vector predicate hint/switch found.\n"
5813                << "LV: Not allowing scalar epilogue, creating predicated "
5814                << "vector loop.\n");
5815     break;
5816   case CM_ScalarEpilogueNotAllowedLowTripLoop:
5817     // fallthrough as a special case of OptForSize
5818   case CM_ScalarEpilogueNotAllowedOptSize:
5819     if (ScalarEpilogueStatus == CM_ScalarEpilogueNotAllowedOptSize)
5820       LLVM_DEBUG(
5821           dbgs() << "LV: Not allowing scalar epilogue due to -Os/-Oz.\n");
5822     else
5823       LLVM_DEBUG(dbgs() << "LV: Not allowing scalar epilogue due to low trip "
5824                         << "count.\n");
5825 
5826     // Bail if runtime checks are required, which are not good when optimising
5827     // for size.
5828     if (runtimeChecksRequired())
5829       return FixedScalableVFPair::getNone();
5830 
5831     break;
5832   }
5833 
5834   // The only loops we can vectorize without a scalar epilogue, are loops with
5835   // a bottom-test and a single exiting block. We'd have to handle the fact
5836   // that not every instruction executes on the last iteration.  This will
5837   // require a lane mask which varies through the vector loop body.  (TODO)
5838   if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
5839     // If there was a tail-folding hint/switch, but we can't fold the tail by
5840     // masking, fallback to a vectorization with a scalar epilogue.
5841     if (ScalarEpilogueStatus == CM_ScalarEpilogueNotNeededUsePredicate) {
5842       LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking: vectorize with a "
5843                            "scalar epilogue instead.\n");
5844       ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
5845       return computeFeasibleMaxVF(TC, UserVF);
5846     }
5847     return FixedScalableVFPair::getNone();
5848   }
5849 
5850   // Now try the tail folding
5851 
5852   // Invalidate interleave groups that require an epilogue if we can't mask
5853   // the interleave-group.
5854   if (!useMaskedInterleavedAccesses(TTI)) {
5855     assert(WideningDecisions.empty() && Uniforms.empty() && Scalars.empty() &&
5856            "No decisions should have been taken at this point");
5857     // Note: There is no need to invalidate any cost modeling decisions here, as
5858     // non where taken so far.
5859     InterleaveInfo.invalidateGroupsRequiringScalarEpilogue();
5860   }
5861 
5862   FixedScalableVFPair MaxFactors = computeFeasibleMaxVF(TC, UserVF);
5863   // Avoid tail folding if the trip count is known to be a multiple of any VF
5864   // we chose.
5865   // FIXME: The condition below pessimises the case for fixed-width vectors,
5866   // when scalable VFs are also candidates for vectorization.
5867   if (MaxFactors.FixedVF.isVector() && !MaxFactors.ScalableVF) {
5868     ElementCount MaxFixedVF = MaxFactors.FixedVF;
5869     assert((UserVF.isNonZero() || isPowerOf2_32(MaxFixedVF.getFixedValue())) &&
5870            "MaxFixedVF must be a power of 2");
5871     unsigned MaxVFtimesIC = UserIC ? MaxFixedVF.getFixedValue() * UserIC
5872                                    : MaxFixedVF.getFixedValue();
5873     ScalarEvolution *SE = PSE.getSE();
5874     const SCEV *BackedgeTakenCount = PSE.getBackedgeTakenCount();
5875     const SCEV *ExitCount = SE->getAddExpr(
5876         BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType()));
5877     const SCEV *Rem = SE->getURemExpr(
5878         SE->applyLoopGuards(ExitCount, TheLoop),
5879         SE->getConstant(BackedgeTakenCount->getType(), MaxVFtimesIC));
5880     if (Rem->isZero()) {
5881       // Accept MaxFixedVF if we do not have a tail.
5882       LLVM_DEBUG(dbgs() << "LV: No tail will remain for any chosen VF.\n");
5883       return MaxFactors;
5884     }
5885   }
5886 
5887   // If we don't know the precise trip count, or if the trip count that we
5888   // found modulo the vectorization factor is not zero, try to fold the tail
5889   // by masking.
5890   // FIXME: look for a smaller MaxVF that does divide TC rather than masking.
5891   if (Legal->prepareToFoldTailByMasking()) {
5892     FoldTailByMasking = true;
5893     return MaxFactors;
5894   }
5895 
5896   // If there was a tail-folding hint/switch, but we can't fold the tail by
5897   // masking, fallback to a vectorization with a scalar epilogue.
5898   if (ScalarEpilogueStatus == CM_ScalarEpilogueNotNeededUsePredicate) {
5899     LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking: vectorize with a "
5900                          "scalar epilogue instead.\n");
5901     ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
5902     return MaxFactors;
5903   }
5904 
5905   if (ScalarEpilogueStatus == CM_ScalarEpilogueNotAllowedUsePredicate) {
5906     LLVM_DEBUG(dbgs() << "LV: Can't fold tail by masking: don't vectorize\n");
5907     return FixedScalableVFPair::getNone();
5908   }
5909 
5910   if (TC == 0) {
5911     reportVectorizationFailure(
5912         "Unable to calculate the loop count due to complex control flow",
5913         "unable to calculate the loop count due to complex control flow",
5914         "UnknownLoopCountComplexCFG", ORE, TheLoop);
5915     return FixedScalableVFPair::getNone();
5916   }
5917 
5918   reportVectorizationFailure(
5919       "Cannot optimize for size and vectorize at the same time.",
5920       "cannot optimize for size and vectorize at the same time. "
5921       "Enable vectorization of this loop with '#pragma clang loop "
5922       "vectorize(enable)' when compiling with -Os/-Oz",
5923       "NoTailLoopWithOptForSize", ORE, TheLoop);
5924   return FixedScalableVFPair::getNone();
5925 }
5926 
5927 ElementCount LoopVectorizationCostModel::getMaximizedVFForTarget(
5928     unsigned ConstTripCount, unsigned SmallestType, unsigned WidestType,
5929     const ElementCount &MaxSafeVF) {
5930   bool ComputeScalableMaxVF = MaxSafeVF.isScalable();
5931   TypeSize WidestRegister = TTI.getRegisterBitWidth(
5932       ComputeScalableMaxVF ? TargetTransformInfo::RGK_ScalableVector
5933                            : TargetTransformInfo::RGK_FixedWidthVector);
5934 
5935   // Convenience function to return the minimum of two ElementCounts.
5936   auto MinVF = [](const ElementCount &LHS, const ElementCount &RHS) {
5937     assert((LHS.isScalable() == RHS.isScalable()) &&
5938            "Scalable flags must match");
5939     return ElementCount::isKnownLT(LHS, RHS) ? LHS : RHS;
5940   };
5941 
5942   // Ensure MaxVF is a power of 2; the dependence distance bound may not be.
5943   // Note that both WidestRegister and WidestType may not be a powers of 2.
5944   auto MaxVectorElementCount = ElementCount::get(
5945       PowerOf2Floor(WidestRegister.getKnownMinSize() / WidestType),
5946       ComputeScalableMaxVF);
5947   MaxVectorElementCount = MinVF(MaxVectorElementCount, MaxSafeVF);
5948   LLVM_DEBUG(dbgs() << "LV: The Widest register safe to use is: "
5949                     << (MaxVectorElementCount * WidestType) << " bits.\n");
5950 
5951   if (!MaxVectorElementCount) {
5952     LLVM_DEBUG(dbgs() << "LV: The target has no "
5953                       << (ComputeScalableMaxVF ? "scalable" : "fixed")
5954                       << " vector registers.\n");
5955     return ElementCount::getFixed(1);
5956   }
5957 
5958   const auto TripCountEC = ElementCount::getFixed(ConstTripCount);
5959   if (ConstTripCount &&
5960       ElementCount::isKnownLE(TripCountEC, MaxVectorElementCount) &&
5961       isPowerOf2_32(ConstTripCount)) {
5962     // We need to clamp the VF to be the ConstTripCount. There is no point in
5963     // choosing a higher viable VF as done in the loop below. If
5964     // MaxVectorElementCount is scalable, we only fall back on a fixed VF when
5965     // the TC is less than or equal to the known number of lanes.
5966     LLVM_DEBUG(dbgs() << "LV: Clamping the MaxVF to the constant trip count: "
5967                       << ConstTripCount << "\n");
5968     return TripCountEC;
5969   }
5970 
5971   ElementCount MaxVF = MaxVectorElementCount;
5972   if (TTI.shouldMaximizeVectorBandwidth() ||
5973       (MaximizeBandwidth && isScalarEpilogueAllowed())) {
5974     auto MaxVectorElementCountMaxBW = ElementCount::get(
5975         PowerOf2Floor(WidestRegister.getKnownMinSize() / SmallestType),
5976         ComputeScalableMaxVF);
5977     MaxVectorElementCountMaxBW = MinVF(MaxVectorElementCountMaxBW, MaxSafeVF);
5978 
5979     // Collect all viable vectorization factors larger than the default MaxVF
5980     // (i.e. MaxVectorElementCount).
5981     SmallVector<ElementCount, 8> VFs;
5982     for (ElementCount VS = MaxVectorElementCount * 2;
5983          ElementCount::isKnownLE(VS, MaxVectorElementCountMaxBW); VS *= 2)
5984       VFs.push_back(VS);
5985 
5986     // For each VF calculate its register usage.
5987     auto RUs = calculateRegisterUsage(VFs);
5988 
5989     // Select the largest VF which doesn't require more registers than existing
5990     // ones.
5991     for (int i = RUs.size() - 1; i >= 0; --i) {
5992       bool Selected = true;
5993       for (auto &pair : RUs[i].MaxLocalUsers) {
5994         unsigned TargetNumRegisters = TTI.getNumberOfRegisters(pair.first);
5995         if (pair.second > TargetNumRegisters)
5996           Selected = false;
5997       }
5998       if (Selected) {
5999         MaxVF = VFs[i];
6000         break;
6001       }
6002     }
6003     if (ElementCount MinVF =
6004             TTI.getMinimumVF(SmallestType, ComputeScalableMaxVF)) {
6005       if (ElementCount::isKnownLT(MaxVF, MinVF)) {
6006         LLVM_DEBUG(dbgs() << "LV: Overriding calculated MaxVF(" << MaxVF
6007                           << ") with target's minimum: " << MinVF << '\n');
6008         MaxVF = MinVF;
6009       }
6010     }
6011   }
6012   return MaxVF;
6013 }
6014 
6015 bool LoopVectorizationCostModel::isMoreProfitable(
6016     const VectorizationFactor &A, const VectorizationFactor &B) const {
6017   InstructionCost::CostType CostA = *A.Cost.getValue();
6018   InstructionCost::CostType CostB = *B.Cost.getValue();
6019 
6020   unsigned MaxTripCount = PSE.getSE()->getSmallConstantMaxTripCount(TheLoop);
6021 
6022   if (!A.Width.isScalable() && !B.Width.isScalable() && FoldTailByMasking &&
6023       MaxTripCount) {
6024     // If we are folding the tail and the trip count is a known (possibly small)
6025     // constant, the trip count will be rounded up to an integer number of
6026     // iterations. The total cost will be PerIterationCost*ceil(TripCount/VF),
6027     // which we compare directly. When not folding the tail, the total cost will
6028     // be PerIterationCost*floor(TC/VF) + Scalar remainder cost, and so is
6029     // approximated with the per-lane cost below instead of using the tripcount
6030     // as here.
6031     int64_t RTCostA = CostA * divideCeil(MaxTripCount, A.Width.getFixedValue());
6032     int64_t RTCostB = CostB * divideCeil(MaxTripCount, B.Width.getFixedValue());
6033     return RTCostA < RTCostB;
6034   }
6035 
6036   // When set to preferred, for now assume vscale may be larger than 1, so
6037   // that scalable vectorization is slightly favorable over fixed-width
6038   // vectorization.
6039   if (Hints->isScalableVectorizationPreferred())
6040     if (A.Width.isScalable() && !B.Width.isScalable())
6041       return (CostA * B.Width.getKnownMinValue()) <=
6042              (CostB * A.Width.getKnownMinValue());
6043 
6044   // To avoid the need for FP division:
6045   //      (CostA / A.Width) < (CostB / B.Width)
6046   // <=>  (CostA * B.Width) < (CostB * A.Width)
6047   return (CostA * B.Width.getKnownMinValue()) <
6048          (CostB * A.Width.getKnownMinValue());
6049 }
6050 
6051 VectorizationFactor LoopVectorizationCostModel::selectVectorizationFactor(
6052     const ElementCountSet &VFCandidates) {
6053   InstructionCost ExpectedCost = expectedCost(ElementCount::getFixed(1)).first;
6054   LLVM_DEBUG(dbgs() << "LV: Scalar loop costs: " << ExpectedCost << ".\n");
6055   assert(ExpectedCost.isValid() && "Unexpected invalid cost for scalar loop");
6056   assert(VFCandidates.count(ElementCount::getFixed(1)) &&
6057          "Expected Scalar VF to be a candidate");
6058 
6059   const VectorizationFactor ScalarCost(ElementCount::getFixed(1), ExpectedCost);
6060   VectorizationFactor ChosenFactor = ScalarCost;
6061 
6062   bool ForceVectorization = Hints->getForce() == LoopVectorizeHints::FK_Enabled;
6063   if (ForceVectorization && VFCandidates.size() > 1) {
6064     // Ignore scalar width, because the user explicitly wants vectorization.
6065     // Initialize cost to max so that VF = 2 is, at least, chosen during cost
6066     // evaluation.
6067     ChosenFactor.Cost = std::numeric_limits<InstructionCost::CostType>::max();
6068   }
6069 
6070   for (const auto &i : VFCandidates) {
6071     // The cost for scalar VF=1 is already calculated, so ignore it.
6072     if (i.isScalar())
6073       continue;
6074 
6075     // Notice that the vector loop needs to be executed less times, so
6076     // we need to divide the cost of the vector loops by the width of
6077     // the vector elements.
6078     VectorizationCostTy C = expectedCost(i);
6079 
6080     assert(C.first.isValid() && "Unexpected invalid cost for vector loop");
6081     VectorizationFactor Candidate(i, C.first);
6082     LLVM_DEBUG(
6083         dbgs() << "LV: Vector loop of width " << i << " costs: "
6084                << (*Candidate.Cost.getValue() /
6085                    Candidate.Width.getKnownMinValue())
6086                << (i.isScalable() ? " (assuming a minimum vscale of 1)" : "")
6087                << ".\n");
6088 
6089     if (!C.second && !ForceVectorization) {
6090       LLVM_DEBUG(
6091           dbgs() << "LV: Not considering vector loop of width " << i
6092                  << " because it will not generate any vector instructions.\n");
6093       continue;
6094     }
6095 
6096     // If profitable add it to ProfitableVF list.
6097     if (isMoreProfitable(Candidate, ScalarCost))
6098       ProfitableVFs.push_back(Candidate);
6099 
6100     if (isMoreProfitable(Candidate, ChosenFactor))
6101       ChosenFactor = Candidate;
6102   }
6103 
6104   if (!EnableCondStoresVectorization && NumPredStores) {
6105     reportVectorizationFailure("There are conditional stores.",
6106         "store that is conditionally executed prevents vectorization",
6107         "ConditionalStore", ORE, TheLoop);
6108     ChosenFactor = ScalarCost;
6109   }
6110 
6111   LLVM_DEBUG(if (ForceVectorization && !ChosenFactor.Width.isScalar() &&
6112                  *ChosenFactor.Cost.getValue() >= *ScalarCost.Cost.getValue())
6113                  dbgs()
6114              << "LV: Vectorization seems to be not beneficial, "
6115              << "but was forced by a user.\n");
6116   LLVM_DEBUG(dbgs() << "LV: Selecting VF: " << ChosenFactor.Width << ".\n");
6117   return ChosenFactor;
6118 }
6119 
6120 bool LoopVectorizationCostModel::isCandidateForEpilogueVectorization(
6121     const Loop &L, ElementCount VF) const {
6122   // Cross iteration phis such as reductions need special handling and are
6123   // currently unsupported.
6124   if (any_of(L.getHeader()->phis(), [&](PHINode &Phi) {
6125         return Legal->isFirstOrderRecurrence(&Phi) ||
6126                Legal->isReductionVariable(&Phi);
6127       }))
6128     return false;
6129 
6130   // Phis with uses outside of the loop require special handling and are
6131   // currently unsupported.
6132   for (auto &Entry : Legal->getInductionVars()) {
6133     // Look for uses of the value of the induction at the last iteration.
6134     Value *PostInc = Entry.first->getIncomingValueForBlock(L.getLoopLatch());
6135     for (User *U : PostInc->users())
6136       if (!L.contains(cast<Instruction>(U)))
6137         return false;
6138     // Look for uses of penultimate value of the induction.
6139     for (User *U : Entry.first->users())
6140       if (!L.contains(cast<Instruction>(U)))
6141         return false;
6142   }
6143 
6144   // Induction variables that are widened require special handling that is
6145   // currently not supported.
6146   if (any_of(Legal->getInductionVars(), [&](auto &Entry) {
6147         return !(this->isScalarAfterVectorization(Entry.first, VF) ||
6148                  this->isProfitableToScalarize(Entry.first, VF));
6149       }))
6150     return false;
6151 
6152   // Epilogue vectorization code has not been auditted to ensure it handles
6153   // non-latch exits properly.  It may be fine, but it needs auditted and
6154   // tested.
6155   if (L.getExitingBlock() != L.getLoopLatch())
6156     return false;
6157 
6158   return true;
6159 }
6160 
6161 bool LoopVectorizationCostModel::isEpilogueVectorizationProfitable(
6162     const ElementCount VF) const {
6163   // FIXME: We need a much better cost-model to take different parameters such
6164   // as register pressure, code size increase and cost of extra branches into
6165   // account. For now we apply a very crude heuristic and only consider loops
6166   // with vectorization factors larger than a certain value.
6167   // We also consider epilogue vectorization unprofitable for targets that don't
6168   // consider interleaving beneficial (eg. MVE).
6169   if (TTI.getMaxInterleaveFactor(VF.getKnownMinValue()) <= 1)
6170     return false;
6171   if (VF.getFixedValue() >= EpilogueVectorizationMinVF)
6172     return true;
6173   return false;
6174 }
6175 
6176 VectorizationFactor
6177 LoopVectorizationCostModel::selectEpilogueVectorizationFactor(
6178     const ElementCount MainLoopVF, const LoopVectorizationPlanner &LVP) {
6179   VectorizationFactor Result = VectorizationFactor::Disabled();
6180   if (!EnableEpilogueVectorization) {
6181     LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization is disabled.\n";);
6182     return Result;
6183   }
6184 
6185   if (!isScalarEpilogueAllowed()) {
6186     LLVM_DEBUG(
6187         dbgs() << "LEV: Unable to vectorize epilogue because no epilogue is "
6188                   "allowed.\n";);
6189     return Result;
6190   }
6191 
6192   // FIXME: This can be fixed for scalable vectors later, because at this stage
6193   // the LoopVectorizer will only consider vectorizing a loop with scalable
6194   // vectors when the loop has a hint to enable vectorization for a given VF.
6195   if (MainLoopVF.isScalable()) {
6196     LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization for scalable vectors not "
6197                          "yet supported.\n");
6198     return Result;
6199   }
6200 
6201   // Not really a cost consideration, but check for unsupported cases here to
6202   // simplify the logic.
6203   if (!isCandidateForEpilogueVectorization(*TheLoop, MainLoopVF)) {
6204     LLVM_DEBUG(
6205         dbgs() << "LEV: Unable to vectorize epilogue because the loop is "
6206                   "not a supported candidate.\n";);
6207     return Result;
6208   }
6209 
6210   if (EpilogueVectorizationForceVF > 1) {
6211     LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization factor is forced.\n";);
6212     if (LVP.hasPlanWithVFs(
6213             {MainLoopVF, ElementCount::getFixed(EpilogueVectorizationForceVF)}))
6214       return {ElementCount::getFixed(EpilogueVectorizationForceVF), 0};
6215     else {
6216       LLVM_DEBUG(
6217           dbgs()
6218               << "LEV: Epilogue vectorization forced factor is not viable.\n";);
6219       return Result;
6220     }
6221   }
6222 
6223   if (TheLoop->getHeader()->getParent()->hasOptSize() ||
6224       TheLoop->getHeader()->getParent()->hasMinSize()) {
6225     LLVM_DEBUG(
6226         dbgs()
6227             << "LEV: Epilogue vectorization skipped due to opt for size.\n";);
6228     return Result;
6229   }
6230 
6231   if (!isEpilogueVectorizationProfitable(MainLoopVF))
6232     return Result;
6233 
6234   for (auto &NextVF : ProfitableVFs)
6235     if (ElementCount::isKnownLT(NextVF.Width, MainLoopVF) &&
6236         (Result.Width.getFixedValue() == 1 ||
6237          isMoreProfitable(NextVF, Result)) &&
6238         LVP.hasPlanWithVFs({MainLoopVF, NextVF.Width}))
6239       Result = NextVF;
6240 
6241   if (Result != VectorizationFactor::Disabled())
6242     LLVM_DEBUG(dbgs() << "LEV: Vectorizing epilogue loop with VF = "
6243                       << Result.Width.getFixedValue() << "\n";);
6244   return Result;
6245 }
6246 
6247 std::pair<unsigned, unsigned>
6248 LoopVectorizationCostModel::getSmallestAndWidestTypes() {
6249   unsigned MinWidth = -1U;
6250   unsigned MaxWidth = 8;
6251   const DataLayout &DL = TheFunction->getParent()->getDataLayout();
6252   for (Type *T : ElementTypesInLoop) {
6253     MinWidth = std::min<unsigned>(
6254         MinWidth, DL.getTypeSizeInBits(T->getScalarType()).getFixedSize());
6255     MaxWidth = std::max<unsigned>(
6256         MaxWidth, DL.getTypeSizeInBits(T->getScalarType()).getFixedSize());
6257   }
6258   return {MinWidth, MaxWidth};
6259 }
6260 
6261 void LoopVectorizationCostModel::collectElementTypesForWidening() {
6262   ElementTypesInLoop.clear();
6263   // For each block.
6264   for (BasicBlock *BB : TheLoop->blocks()) {
6265     // For each instruction in the loop.
6266     for (Instruction &I : BB->instructionsWithoutDebug()) {
6267       Type *T = I.getType();
6268 
6269       // Skip ignored values.
6270       if (ValuesToIgnore.count(&I))
6271         continue;
6272 
6273       // Only examine Loads, Stores and PHINodes.
6274       if (!isa<LoadInst>(I) && !isa<StoreInst>(I) && !isa<PHINode>(I))
6275         continue;
6276 
6277       // Examine PHI nodes that are reduction variables. Update the type to
6278       // account for the recurrence type.
6279       if (auto *PN = dyn_cast<PHINode>(&I)) {
6280         if (!Legal->isReductionVariable(PN))
6281           continue;
6282         const RecurrenceDescriptor &RdxDesc = Legal->getReductionVars()[PN];
6283         if (PreferInLoopReductions || useOrderedReductions(RdxDesc) ||
6284             TTI.preferInLoopReduction(RdxDesc.getOpcode(),
6285                                       RdxDesc.getRecurrenceType(),
6286                                       TargetTransformInfo::ReductionFlags()))
6287           continue;
6288         T = RdxDesc.getRecurrenceType();
6289       }
6290 
6291       // Examine the stored values.
6292       if (auto *ST = dyn_cast<StoreInst>(&I))
6293         T = ST->getValueOperand()->getType();
6294 
6295       // Ignore loaded pointer types and stored pointer types that are not
6296       // vectorizable.
6297       //
6298       // FIXME: The check here attempts to predict whether a load or store will
6299       //        be vectorized. We only know this for certain after a VF has
6300       //        been selected. Here, we assume that if an access can be
6301       //        vectorized, it will be. We should also look at extending this
6302       //        optimization to non-pointer types.
6303       //
6304       if (T->isPointerTy() && !isConsecutiveLoadOrStore(&I) &&
6305           !isAccessInterleaved(&I) && !isLegalGatherOrScatter(&I))
6306         continue;
6307 
6308       ElementTypesInLoop.insert(T);
6309     }
6310   }
6311 }
6312 
6313 unsigned LoopVectorizationCostModel::selectInterleaveCount(ElementCount VF,
6314                                                            unsigned LoopCost) {
6315   // -- The interleave heuristics --
6316   // We interleave the loop in order to expose ILP and reduce the loop overhead.
6317   // There are many micro-architectural considerations that we can't predict
6318   // at this level. For example, frontend pressure (on decode or fetch) due to
6319   // code size, or the number and capabilities of the execution ports.
6320   //
6321   // We use the following heuristics to select the interleave count:
6322   // 1. If the code has reductions, then we interleave to break the cross
6323   // iteration dependency.
6324   // 2. If the loop is really small, then we interleave to reduce the loop
6325   // overhead.
6326   // 3. We don't interleave if we think that we will spill registers to memory
6327   // due to the increased register pressure.
6328 
6329   if (!isScalarEpilogueAllowed())
6330     return 1;
6331 
6332   // We used the distance for the interleave count.
6333   if (Legal->getMaxSafeDepDistBytes() != -1U)
6334     return 1;
6335 
6336   auto BestKnownTC = getSmallBestKnownTC(*PSE.getSE(), TheLoop);
6337   const bool HasReductions = !Legal->getReductionVars().empty();
6338   // Do not interleave loops with a relatively small known or estimated trip
6339   // count. But we will interleave when InterleaveSmallLoopScalarReduction is
6340   // enabled, and the code has scalar reductions(HasReductions && VF = 1),
6341   // because with the above conditions interleaving can expose ILP and break
6342   // cross iteration dependences for reductions.
6343   if (BestKnownTC && (*BestKnownTC < TinyTripCountInterleaveThreshold) &&
6344       !(InterleaveSmallLoopScalarReduction && HasReductions && VF.isScalar()))
6345     return 1;
6346 
6347   RegisterUsage R = calculateRegisterUsage({VF})[0];
6348   // We divide by these constants so assume that we have at least one
6349   // instruction that uses at least one register.
6350   for (auto& pair : R.MaxLocalUsers) {
6351     pair.second = std::max(pair.second, 1U);
6352   }
6353 
6354   // We calculate the interleave count using the following formula.
6355   // Subtract the number of loop invariants from the number of available
6356   // registers. These registers are used by all of the interleaved instances.
6357   // Next, divide the remaining registers by the number of registers that is
6358   // required by the loop, in order to estimate how many parallel instances
6359   // fit without causing spills. All of this is rounded down if necessary to be
6360   // a power of two. We want power of two interleave count to simplify any
6361   // addressing operations or alignment considerations.
6362   // We also want power of two interleave counts to ensure that the induction
6363   // variable of the vector loop wraps to zero, when tail is folded by masking;
6364   // this currently happens when OptForSize, in which case IC is set to 1 above.
6365   unsigned IC = UINT_MAX;
6366 
6367   for (auto& pair : R.MaxLocalUsers) {
6368     unsigned TargetNumRegisters = TTI.getNumberOfRegisters(pair.first);
6369     LLVM_DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters
6370                       << " registers of "
6371                       << TTI.getRegisterClassName(pair.first) << " register class\n");
6372     if (VF.isScalar()) {
6373       if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
6374         TargetNumRegisters = ForceTargetNumScalarRegs;
6375     } else {
6376       if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
6377         TargetNumRegisters = ForceTargetNumVectorRegs;
6378     }
6379     unsigned MaxLocalUsers = pair.second;
6380     unsigned LoopInvariantRegs = 0;
6381     if (R.LoopInvariantRegs.find(pair.first) != R.LoopInvariantRegs.end())
6382       LoopInvariantRegs = R.LoopInvariantRegs[pair.first];
6383 
6384     unsigned TmpIC = PowerOf2Floor((TargetNumRegisters - LoopInvariantRegs) / MaxLocalUsers);
6385     // Don't count the induction variable as interleaved.
6386     if (EnableIndVarRegisterHeur) {
6387       TmpIC =
6388           PowerOf2Floor((TargetNumRegisters - LoopInvariantRegs - 1) /
6389                         std::max(1U, (MaxLocalUsers - 1)));
6390     }
6391 
6392     IC = std::min(IC, TmpIC);
6393   }
6394 
6395   // Clamp the interleave ranges to reasonable counts.
6396   unsigned MaxInterleaveCount =
6397       TTI.getMaxInterleaveFactor(VF.getKnownMinValue());
6398 
6399   // Check if the user has overridden the max.
6400   if (VF.isScalar()) {
6401     if (ForceTargetMaxScalarInterleaveFactor.getNumOccurrences() > 0)
6402       MaxInterleaveCount = ForceTargetMaxScalarInterleaveFactor;
6403   } else {
6404     if (ForceTargetMaxVectorInterleaveFactor.getNumOccurrences() > 0)
6405       MaxInterleaveCount = ForceTargetMaxVectorInterleaveFactor;
6406   }
6407 
6408   // If trip count is known or estimated compile time constant, limit the
6409   // interleave count to be less than the trip count divided by VF, provided it
6410   // is at least 1.
6411   //
6412   // For scalable vectors we can't know if interleaving is beneficial. It may
6413   // not be beneficial for small loops if none of the lanes in the second vector
6414   // iterations is enabled. However, for larger loops, there is likely to be a
6415   // similar benefit as for fixed-width vectors. For now, we choose to leave
6416   // the InterleaveCount as if vscale is '1', although if some information about
6417   // the vector is known (e.g. min vector size), we can make a better decision.
6418   if (BestKnownTC) {
6419     MaxInterleaveCount =
6420         std::min(*BestKnownTC / VF.getKnownMinValue(), MaxInterleaveCount);
6421     // Make sure MaxInterleaveCount is greater than 0.
6422     MaxInterleaveCount = std::max(1u, MaxInterleaveCount);
6423   }
6424 
6425   assert(MaxInterleaveCount > 0 &&
6426          "Maximum interleave count must be greater than 0");
6427 
6428   // Clamp the calculated IC to be between the 1 and the max interleave count
6429   // that the target and trip count allows.
6430   if (IC > MaxInterleaveCount)
6431     IC = MaxInterleaveCount;
6432   else
6433     // Make sure IC is greater than 0.
6434     IC = std::max(1u, IC);
6435 
6436   assert(IC > 0 && "Interleave count must be greater than 0.");
6437 
6438   // If we did not calculate the cost for VF (because the user selected the VF)
6439   // then we calculate the cost of VF here.
6440   if (LoopCost == 0) {
6441     assert(expectedCost(VF).first.isValid() && "Expected a valid cost");
6442     LoopCost = *expectedCost(VF).first.getValue();
6443   }
6444 
6445   assert(LoopCost && "Non-zero loop cost expected");
6446 
6447   // Interleave if we vectorized this loop and there is a reduction that could
6448   // benefit from interleaving.
6449   if (VF.isVector() && HasReductions) {
6450     LLVM_DEBUG(dbgs() << "LV: Interleaving because of reductions.\n");
6451     return IC;
6452   }
6453 
6454   // Note that if we've already vectorized the loop we will have done the
6455   // runtime check and so interleaving won't require further checks.
6456   bool InterleavingRequiresRuntimePointerCheck =
6457       (VF.isScalar() && Legal->getRuntimePointerChecking()->Need);
6458 
6459   // We want to interleave small loops in order to reduce the loop overhead and
6460   // potentially expose ILP opportunities.
6461   LLVM_DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n'
6462                     << "LV: IC is " << IC << '\n'
6463                     << "LV: VF is " << VF << '\n');
6464   const bool AggressivelyInterleaveReductions =
6465       TTI.enableAggressiveInterleaving(HasReductions);
6466   if (!InterleavingRequiresRuntimePointerCheck && LoopCost < SmallLoopCost) {
6467     // We assume that the cost overhead is 1 and we use the cost model
6468     // to estimate the cost of the loop and interleave until the cost of the
6469     // loop overhead is about 5% of the cost of the loop.
6470     unsigned SmallIC =
6471         std::min(IC, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost));
6472 
6473     // Interleave until store/load ports (estimated by max interleave count) are
6474     // saturated.
6475     unsigned NumStores = Legal->getNumStores();
6476     unsigned NumLoads = Legal->getNumLoads();
6477     unsigned StoresIC = IC / (NumStores ? NumStores : 1);
6478     unsigned LoadsIC = IC / (NumLoads ? NumLoads : 1);
6479 
6480     // If we have a scalar reduction (vector reductions are already dealt with
6481     // by this point), we can increase the critical path length if the loop
6482     // we're interleaving is inside another loop. Limit, by default to 2, so the
6483     // critical path only gets increased by one reduction operation.
6484     if (HasReductions && TheLoop->getLoopDepth() > 1) {
6485       unsigned F = static_cast<unsigned>(MaxNestedScalarReductionIC);
6486       SmallIC = std::min(SmallIC, F);
6487       StoresIC = std::min(StoresIC, F);
6488       LoadsIC = std::min(LoadsIC, F);
6489     }
6490 
6491     if (EnableLoadStoreRuntimeInterleave &&
6492         std::max(StoresIC, LoadsIC) > SmallIC) {
6493       LLVM_DEBUG(
6494           dbgs() << "LV: Interleaving to saturate store or load ports.\n");
6495       return std::max(StoresIC, LoadsIC);
6496     }
6497 
6498     // If there are scalar reductions and TTI has enabled aggressive
6499     // interleaving for reductions, we will interleave to expose ILP.
6500     if (InterleaveSmallLoopScalarReduction && VF.isScalar() &&
6501         AggressivelyInterleaveReductions) {
6502       LLVM_DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
6503       // Interleave no less than SmallIC but not as aggressive as the normal IC
6504       // to satisfy the rare situation when resources are too limited.
6505       return std::max(IC / 2, SmallIC);
6506     } else {
6507       LLVM_DEBUG(dbgs() << "LV: Interleaving to reduce branch cost.\n");
6508       return SmallIC;
6509     }
6510   }
6511 
6512   // Interleave if this is a large loop (small loops are already dealt with by
6513   // this point) that could benefit from interleaving.
6514   if (AggressivelyInterleaveReductions) {
6515     LLVM_DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
6516     return IC;
6517   }
6518 
6519   LLVM_DEBUG(dbgs() << "LV: Not Interleaving.\n");
6520   return 1;
6521 }
6522 
6523 SmallVector<LoopVectorizationCostModel::RegisterUsage, 8>
6524 LoopVectorizationCostModel::calculateRegisterUsage(ArrayRef<ElementCount> VFs) {
6525   // This function calculates the register usage by measuring the highest number
6526   // of values that are alive at a single location. Obviously, this is a very
6527   // rough estimation. We scan the loop in a topological order in order and
6528   // assign a number to each instruction. We use RPO to ensure that defs are
6529   // met before their users. We assume that each instruction that has in-loop
6530   // users starts an interval. We record every time that an in-loop value is
6531   // used, so we have a list of the first and last occurrences of each
6532   // instruction. Next, we transpose this data structure into a multi map that
6533   // holds the list of intervals that *end* at a specific location. This multi
6534   // map allows us to perform a linear search. We scan the instructions linearly
6535   // and record each time that a new interval starts, by placing it in a set.
6536   // If we find this value in the multi-map then we remove it from the set.
6537   // The max register usage is the maximum size of the set.
6538   // We also search for instructions that are defined outside the loop, but are
6539   // used inside the loop. We need this number separately from the max-interval
6540   // usage number because when we unroll, loop-invariant values do not take
6541   // more register.
6542   LoopBlocksDFS DFS(TheLoop);
6543   DFS.perform(LI);
6544 
6545   RegisterUsage RU;
6546 
6547   // Each 'key' in the map opens a new interval. The values
6548   // of the map are the index of the 'last seen' usage of the
6549   // instruction that is the key.
6550   using IntervalMap = DenseMap<Instruction *, unsigned>;
6551 
6552   // Maps instruction to its index.
6553   SmallVector<Instruction *, 64> IdxToInstr;
6554   // Marks the end of each interval.
6555   IntervalMap EndPoint;
6556   // Saves the list of instruction indices that are used in the loop.
6557   SmallPtrSet<Instruction *, 8> Ends;
6558   // Saves the list of values that are used in the loop but are
6559   // defined outside the loop, such as arguments and constants.
6560   SmallPtrSet<Value *, 8> LoopInvariants;
6561 
6562   for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) {
6563     for (Instruction &I : BB->instructionsWithoutDebug()) {
6564       IdxToInstr.push_back(&I);
6565 
6566       // Save the end location of each USE.
6567       for (Value *U : I.operands()) {
6568         auto *Instr = dyn_cast<Instruction>(U);
6569 
6570         // Ignore non-instruction values such as arguments, constants, etc.
6571         if (!Instr)
6572           continue;
6573 
6574         // If this instruction is outside the loop then record it and continue.
6575         if (!TheLoop->contains(Instr)) {
6576           LoopInvariants.insert(Instr);
6577           continue;
6578         }
6579 
6580         // Overwrite previous end points.
6581         EndPoint[Instr] = IdxToInstr.size();
6582         Ends.insert(Instr);
6583       }
6584     }
6585   }
6586 
6587   // Saves the list of intervals that end with the index in 'key'.
6588   using InstrList = SmallVector<Instruction *, 2>;
6589   DenseMap<unsigned, InstrList> TransposeEnds;
6590 
6591   // Transpose the EndPoints to a list of values that end at each index.
6592   for (auto &Interval : EndPoint)
6593     TransposeEnds[Interval.second].push_back(Interval.first);
6594 
6595   SmallPtrSet<Instruction *, 8> OpenIntervals;
6596   SmallVector<RegisterUsage, 8> RUs(VFs.size());
6597   SmallVector<SmallMapVector<unsigned, unsigned, 4>, 8> MaxUsages(VFs.size());
6598 
6599   LLVM_DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
6600 
6601   // A lambda that gets the register usage for the given type and VF.
6602   const auto &TTICapture = TTI;
6603   auto GetRegUsage = [&TTICapture](Type *Ty, ElementCount VF) {
6604     if (Ty->isTokenTy() || !VectorType::isValidElementType(Ty))
6605       return 0;
6606     return *TTICapture.getRegUsageForType(VectorType::get(Ty, VF)).getValue();
6607   };
6608 
6609   for (unsigned int i = 0, s = IdxToInstr.size(); i < s; ++i) {
6610     Instruction *I = IdxToInstr[i];
6611 
6612     // Remove all of the instructions that end at this location.
6613     InstrList &List = TransposeEnds[i];
6614     for (Instruction *ToRemove : List)
6615       OpenIntervals.erase(ToRemove);
6616 
6617     // Ignore instructions that are never used within the loop.
6618     if (!Ends.count(I))
6619       continue;
6620 
6621     // Skip ignored values.
6622     if (ValuesToIgnore.count(I))
6623       continue;
6624 
6625     // For each VF find the maximum usage of registers.
6626     for (unsigned j = 0, e = VFs.size(); j < e; ++j) {
6627       // Count the number of live intervals.
6628       SmallMapVector<unsigned, unsigned, 4> RegUsage;
6629 
6630       if (VFs[j].isScalar()) {
6631         for (auto Inst : OpenIntervals) {
6632           unsigned ClassID = TTI.getRegisterClassForType(false, Inst->getType());
6633           if (RegUsage.find(ClassID) == RegUsage.end())
6634             RegUsage[ClassID] = 1;
6635           else
6636             RegUsage[ClassID] += 1;
6637         }
6638       } else {
6639         collectUniformsAndScalars(VFs[j]);
6640         for (auto Inst : OpenIntervals) {
6641           // Skip ignored values for VF > 1.
6642           if (VecValuesToIgnore.count(Inst))
6643             continue;
6644           if (isScalarAfterVectorization(Inst, VFs[j])) {
6645             unsigned ClassID = TTI.getRegisterClassForType(false, Inst->getType());
6646             if (RegUsage.find(ClassID) == RegUsage.end())
6647               RegUsage[ClassID] = 1;
6648             else
6649               RegUsage[ClassID] += 1;
6650           } else {
6651             unsigned ClassID = TTI.getRegisterClassForType(true, Inst->getType());
6652             if (RegUsage.find(ClassID) == RegUsage.end())
6653               RegUsage[ClassID] = GetRegUsage(Inst->getType(), VFs[j]);
6654             else
6655               RegUsage[ClassID] += GetRegUsage(Inst->getType(), VFs[j]);
6656           }
6657         }
6658       }
6659 
6660       for (auto& pair : RegUsage) {
6661         if (MaxUsages[j].find(pair.first) != MaxUsages[j].end())
6662           MaxUsages[j][pair.first] = std::max(MaxUsages[j][pair.first], pair.second);
6663         else
6664           MaxUsages[j][pair.first] = pair.second;
6665       }
6666     }
6667 
6668     LLVM_DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # "
6669                       << OpenIntervals.size() << '\n');
6670 
6671     // Add the current instruction to the list of open intervals.
6672     OpenIntervals.insert(I);
6673   }
6674 
6675   for (unsigned i = 0, e = VFs.size(); i < e; ++i) {
6676     SmallMapVector<unsigned, unsigned, 4> Invariant;
6677 
6678     for (auto Inst : LoopInvariants) {
6679       unsigned Usage =
6680           VFs[i].isScalar() ? 1 : GetRegUsage(Inst->getType(), VFs[i]);
6681       unsigned ClassID =
6682           TTI.getRegisterClassForType(VFs[i].isVector(), Inst->getType());
6683       if (Invariant.find(ClassID) == Invariant.end())
6684         Invariant[ClassID] = Usage;
6685       else
6686         Invariant[ClassID] += Usage;
6687     }
6688 
6689     LLVM_DEBUG({
6690       dbgs() << "LV(REG): VF = " << VFs[i] << '\n';
6691       dbgs() << "LV(REG): Found max usage: " << MaxUsages[i].size()
6692              << " item\n";
6693       for (const auto &pair : MaxUsages[i]) {
6694         dbgs() << "LV(REG): RegisterClass: "
6695                << TTI.getRegisterClassName(pair.first) << ", " << pair.second
6696                << " registers\n";
6697       }
6698       dbgs() << "LV(REG): Found invariant usage: " << Invariant.size()
6699              << " item\n";
6700       for (const auto &pair : Invariant) {
6701         dbgs() << "LV(REG): RegisterClass: "
6702                << TTI.getRegisterClassName(pair.first) << ", " << pair.second
6703                << " registers\n";
6704       }
6705     });
6706 
6707     RU.LoopInvariantRegs = Invariant;
6708     RU.MaxLocalUsers = MaxUsages[i];
6709     RUs[i] = RU;
6710   }
6711 
6712   return RUs;
6713 }
6714 
6715 bool LoopVectorizationCostModel::useEmulatedMaskMemRefHack(Instruction *I){
6716   // TODO: Cost model for emulated masked load/store is completely
6717   // broken. This hack guides the cost model to use an artificially
6718   // high enough value to practically disable vectorization with such
6719   // operations, except where previously deployed legality hack allowed
6720   // using very low cost values. This is to avoid regressions coming simply
6721   // from moving "masked load/store" check from legality to cost model.
6722   // Masked Load/Gather emulation was previously never allowed.
6723   // Limited number of Masked Store/Scatter emulation was allowed.
6724   assert(isPredicatedInst(I) &&
6725          "Expecting a scalar emulated instruction");
6726   return isa<LoadInst>(I) ||
6727          (isa<StoreInst>(I) &&
6728           NumPredStores > NumberOfStoresToPredicate);
6729 }
6730 
6731 void LoopVectorizationCostModel::collectInstsToScalarize(ElementCount VF) {
6732   // If we aren't vectorizing the loop, or if we've already collected the
6733   // instructions to scalarize, there's nothing to do. Collection may already
6734   // have occurred if we have a user-selected VF and are now computing the
6735   // expected cost for interleaving.
6736   if (VF.isScalar() || VF.isZero() ||
6737       InstsToScalarize.find(VF) != InstsToScalarize.end())
6738     return;
6739 
6740   // Initialize a mapping for VF in InstsToScalalarize. If we find that it's
6741   // not profitable to scalarize any instructions, the presence of VF in the
6742   // map will indicate that we've analyzed it already.
6743   ScalarCostsTy &ScalarCostsVF = InstsToScalarize[VF];
6744 
6745   // Find all the instructions that are scalar with predication in the loop and
6746   // determine if it would be better to not if-convert the blocks they are in.
6747   // If so, we also record the instructions to scalarize.
6748   for (BasicBlock *BB : TheLoop->blocks()) {
6749     if (!blockNeedsPredication(BB))
6750       continue;
6751     for (Instruction &I : *BB)
6752       if (isScalarWithPredication(&I)) {
6753         ScalarCostsTy ScalarCosts;
6754         // Do not apply discount logic if hacked cost is needed
6755         // for emulated masked memrefs.
6756         if (!useEmulatedMaskMemRefHack(&I) &&
6757             computePredInstDiscount(&I, ScalarCosts, VF) >= 0)
6758           ScalarCostsVF.insert(ScalarCosts.begin(), ScalarCosts.end());
6759         // Remember that BB will remain after vectorization.
6760         PredicatedBBsAfterVectorization.insert(BB);
6761       }
6762   }
6763 }
6764 
6765 int LoopVectorizationCostModel::computePredInstDiscount(
6766     Instruction *PredInst, ScalarCostsTy &ScalarCosts, ElementCount VF) {
6767   assert(!isUniformAfterVectorization(PredInst, VF) &&
6768          "Instruction marked uniform-after-vectorization will be predicated");
6769 
6770   // Initialize the discount to zero, meaning that the scalar version and the
6771   // vector version cost the same.
6772   InstructionCost Discount = 0;
6773 
6774   // Holds instructions to analyze. The instructions we visit are mapped in
6775   // ScalarCosts. Those instructions are the ones that would be scalarized if
6776   // we find that the scalar version costs less.
6777   SmallVector<Instruction *, 8> Worklist;
6778 
6779   // Returns true if the given instruction can be scalarized.
6780   auto canBeScalarized = [&](Instruction *I) -> bool {
6781     // We only attempt to scalarize instructions forming a single-use chain
6782     // from the original predicated block that would otherwise be vectorized.
6783     // Although not strictly necessary, we give up on instructions we know will
6784     // already be scalar to avoid traversing chains that are unlikely to be
6785     // beneficial.
6786     if (!I->hasOneUse() || PredInst->getParent() != I->getParent() ||
6787         isScalarAfterVectorization(I, VF))
6788       return false;
6789 
6790     // If the instruction is scalar with predication, it will be analyzed
6791     // separately. We ignore it within the context of PredInst.
6792     if (isScalarWithPredication(I))
6793       return false;
6794 
6795     // If any of the instruction's operands are uniform after vectorization,
6796     // the instruction cannot be scalarized. This prevents, for example, a
6797     // masked load from being scalarized.
6798     //
6799     // We assume we will only emit a value for lane zero of an instruction
6800     // marked uniform after vectorization, rather than VF identical values.
6801     // Thus, if we scalarize an instruction that uses a uniform, we would
6802     // create uses of values corresponding to the lanes we aren't emitting code
6803     // for. This behavior can be changed by allowing getScalarValue to clone
6804     // the lane zero values for uniforms rather than asserting.
6805     for (Use &U : I->operands())
6806       if (auto *J = dyn_cast<Instruction>(U.get()))
6807         if (isUniformAfterVectorization(J, VF))
6808           return false;
6809 
6810     // Otherwise, we can scalarize the instruction.
6811     return true;
6812   };
6813 
6814   // Compute the expected cost discount from scalarizing the entire expression
6815   // feeding the predicated instruction. We currently only consider expressions
6816   // that are single-use instruction chains.
6817   Worklist.push_back(PredInst);
6818   while (!Worklist.empty()) {
6819     Instruction *I = Worklist.pop_back_val();
6820 
6821     // If we've already analyzed the instruction, there's nothing to do.
6822     if (ScalarCosts.find(I) != ScalarCosts.end())
6823       continue;
6824 
6825     // Compute the cost of the vector instruction. Note that this cost already
6826     // includes the scalarization overhead of the predicated instruction.
6827     InstructionCost VectorCost = getInstructionCost(I, VF).first;
6828 
6829     // Compute the cost of the scalarized instruction. This cost is the cost of
6830     // the instruction as if it wasn't if-converted and instead remained in the
6831     // predicated block. We will scale this cost by block probability after
6832     // computing the scalarization overhead.
6833     assert(!VF.isScalable() && "scalable vectors not yet supported.");
6834     InstructionCost ScalarCost =
6835         VF.getKnownMinValue() *
6836         getInstructionCost(I, ElementCount::getFixed(1)).first;
6837 
6838     // Compute the scalarization overhead of needed insertelement instructions
6839     // and phi nodes.
6840     if (isScalarWithPredication(I) && !I->getType()->isVoidTy()) {
6841       ScalarCost += TTI.getScalarizationOverhead(
6842           cast<VectorType>(ToVectorTy(I->getType(), VF)),
6843           APInt::getAllOnesValue(VF.getKnownMinValue()), true, false);
6844       assert(!VF.isScalable() && "scalable vectors not yet supported.");
6845       ScalarCost +=
6846           VF.getKnownMinValue() *
6847           TTI.getCFInstrCost(Instruction::PHI, TTI::TCK_RecipThroughput);
6848     }
6849 
6850     // Compute the scalarization overhead of needed extractelement
6851     // instructions. For each of the instruction's operands, if the operand can
6852     // be scalarized, add it to the worklist; otherwise, account for the
6853     // overhead.
6854     for (Use &U : I->operands())
6855       if (auto *J = dyn_cast<Instruction>(U.get())) {
6856         assert(VectorType::isValidElementType(J->getType()) &&
6857                "Instruction has non-scalar type");
6858         if (canBeScalarized(J))
6859           Worklist.push_back(J);
6860         else if (needsExtract(J, VF)) {
6861           assert(!VF.isScalable() && "scalable vectors not yet supported.");
6862           ScalarCost += TTI.getScalarizationOverhead(
6863               cast<VectorType>(ToVectorTy(J->getType(), VF)),
6864               APInt::getAllOnesValue(VF.getKnownMinValue()), false, true);
6865         }
6866       }
6867 
6868     // Scale the total scalar cost by block probability.
6869     ScalarCost /= getReciprocalPredBlockProb();
6870 
6871     // Compute the discount. A non-negative discount means the vector version
6872     // of the instruction costs more, and scalarizing would be beneficial.
6873     Discount += VectorCost - ScalarCost;
6874     ScalarCosts[I] = ScalarCost;
6875   }
6876 
6877   return *Discount.getValue();
6878 }
6879 
6880 LoopVectorizationCostModel::VectorizationCostTy
6881 LoopVectorizationCostModel::expectedCost(ElementCount VF) {
6882   VectorizationCostTy Cost;
6883 
6884   // For each block.
6885   for (BasicBlock *BB : TheLoop->blocks()) {
6886     VectorizationCostTy BlockCost;
6887 
6888     // For each instruction in the old loop.
6889     for (Instruction &I : BB->instructionsWithoutDebug()) {
6890       // Skip ignored values.
6891       if (ValuesToIgnore.count(&I) ||
6892           (VF.isVector() && VecValuesToIgnore.count(&I)))
6893         continue;
6894 
6895       VectorizationCostTy C = getInstructionCost(&I, VF);
6896 
6897       // Check if we should override the cost.
6898       if (ForceTargetInstructionCost.getNumOccurrences() > 0)
6899         C.first = InstructionCost(ForceTargetInstructionCost);
6900 
6901       BlockCost.first += C.first;
6902       BlockCost.second |= C.second;
6903       LLVM_DEBUG(dbgs() << "LV: Found an estimated cost of " << C.first
6904                         << " for VF " << VF << " For instruction: " << I
6905                         << '\n');
6906     }
6907 
6908     // If we are vectorizing a predicated block, it will have been
6909     // if-converted. This means that the block's instructions (aside from
6910     // stores and instructions that may divide by zero) will now be
6911     // unconditionally executed. For the scalar case, we may not always execute
6912     // the predicated block, if it is an if-else block. Thus, scale the block's
6913     // cost by the probability of executing it. blockNeedsPredication from
6914     // Legal is used so as to not include all blocks in tail folded loops.
6915     if (VF.isScalar() && Legal->blockNeedsPredication(BB))
6916       BlockCost.first /= getReciprocalPredBlockProb();
6917 
6918     Cost.first += BlockCost.first;
6919     Cost.second |= BlockCost.second;
6920   }
6921 
6922   return Cost;
6923 }
6924 
6925 /// Gets Address Access SCEV after verifying that the access pattern
6926 /// is loop invariant except the induction variable dependence.
6927 ///
6928 /// This SCEV can be sent to the Target in order to estimate the address
6929 /// calculation cost.
6930 static const SCEV *getAddressAccessSCEV(
6931               Value *Ptr,
6932               LoopVectorizationLegality *Legal,
6933               PredicatedScalarEvolution &PSE,
6934               const Loop *TheLoop) {
6935 
6936   auto *Gep = dyn_cast<GetElementPtrInst>(Ptr);
6937   if (!Gep)
6938     return nullptr;
6939 
6940   // We are looking for a gep with all loop invariant indices except for one
6941   // which should be an induction variable.
6942   auto SE = PSE.getSE();
6943   unsigned NumOperands = Gep->getNumOperands();
6944   for (unsigned i = 1; i < NumOperands; ++i) {
6945     Value *Opd = Gep->getOperand(i);
6946     if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
6947         !Legal->isInductionVariable(Opd))
6948       return nullptr;
6949   }
6950 
6951   // Now we know we have a GEP ptr, %inv, %ind, %inv. return the Ptr SCEV.
6952   return PSE.getSCEV(Ptr);
6953 }
6954 
6955 static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
6956   return Legal->hasStride(I->getOperand(0)) ||
6957          Legal->hasStride(I->getOperand(1));
6958 }
6959 
6960 InstructionCost
6961 LoopVectorizationCostModel::getMemInstScalarizationCost(Instruction *I,
6962                                                         ElementCount VF) {
6963   assert(VF.isVector() &&
6964          "Scalarization cost of instruction implies vectorization.");
6965   if (VF.isScalable())
6966     return InstructionCost::getInvalid();
6967 
6968   Type *ValTy = getLoadStoreType(I);
6969   auto SE = PSE.getSE();
6970 
6971   unsigned AS = getLoadStoreAddressSpace(I);
6972   Value *Ptr = getLoadStorePointerOperand(I);
6973   Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
6974 
6975   // Figure out whether the access is strided and get the stride value
6976   // if it's known in compile time
6977   const SCEV *PtrSCEV = getAddressAccessSCEV(Ptr, Legal, PSE, TheLoop);
6978 
6979   // Get the cost of the scalar memory instruction and address computation.
6980   InstructionCost Cost =
6981       VF.getKnownMinValue() * TTI.getAddressComputationCost(PtrTy, SE, PtrSCEV);
6982 
6983   // Don't pass *I here, since it is scalar but will actually be part of a
6984   // vectorized loop where the user of it is a vectorized instruction.
6985   const Align Alignment = getLoadStoreAlignment(I);
6986   Cost += VF.getKnownMinValue() *
6987           TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(), Alignment,
6988                               AS, TTI::TCK_RecipThroughput);
6989 
6990   // Get the overhead of the extractelement and insertelement instructions
6991   // we might create due to scalarization.
6992   Cost += getScalarizationOverhead(I, VF);
6993 
6994   // If we have a predicated load/store, it will need extra i1 extracts and
6995   // conditional branches, but may not be executed for each vector lane. Scale
6996   // the cost by the probability of executing the predicated block.
6997   if (isPredicatedInst(I)) {
6998     Cost /= getReciprocalPredBlockProb();
6999 
7000     // Add the cost of an i1 extract and a branch
7001     auto *Vec_i1Ty =
7002         VectorType::get(IntegerType::getInt1Ty(ValTy->getContext()), VF);
7003     Cost += TTI.getScalarizationOverhead(
7004         Vec_i1Ty, APInt::getAllOnesValue(VF.getKnownMinValue()),
7005         /*Insert=*/false, /*Extract=*/true);
7006     Cost += TTI.getCFInstrCost(Instruction::Br, TTI::TCK_RecipThroughput);
7007 
7008     if (useEmulatedMaskMemRefHack(I))
7009       // Artificially setting to a high enough value to practically disable
7010       // vectorization with such operations.
7011       Cost = 3000000;
7012   }
7013 
7014   return Cost;
7015 }
7016 
7017 InstructionCost
7018 LoopVectorizationCostModel::getConsecutiveMemOpCost(Instruction *I,
7019                                                     ElementCount VF) {
7020   Type *ValTy = getLoadStoreType(I);
7021   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
7022   Value *Ptr = getLoadStorePointerOperand(I);
7023   unsigned AS = getLoadStoreAddressSpace(I);
7024   int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
7025   enum TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
7026 
7027   assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
7028          "Stride should be 1 or -1 for consecutive memory access");
7029   const Align Alignment = getLoadStoreAlignment(I);
7030   InstructionCost Cost = 0;
7031   if (Legal->isMaskRequired(I))
7032     Cost += TTI.getMaskedMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS,
7033                                       CostKind);
7034   else
7035     Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS,
7036                                 CostKind, I);
7037 
7038   bool Reverse = ConsecutiveStride < 0;
7039   if (Reverse)
7040     Cost +=
7041         TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, None, 0);
7042   return Cost;
7043 }
7044 
7045 InstructionCost
7046 LoopVectorizationCostModel::getUniformMemOpCost(Instruction *I,
7047                                                 ElementCount VF) {
7048   assert(Legal->isUniformMemOp(*I));
7049 
7050   Type *ValTy = getLoadStoreType(I);
7051   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
7052   const Align Alignment = getLoadStoreAlignment(I);
7053   unsigned AS = getLoadStoreAddressSpace(I);
7054   enum TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
7055   if (isa<LoadInst>(I)) {
7056     return TTI.getAddressComputationCost(ValTy) +
7057            TTI.getMemoryOpCost(Instruction::Load, ValTy, Alignment, AS,
7058                                CostKind) +
7059            TTI.getShuffleCost(TargetTransformInfo::SK_Broadcast, VectorTy);
7060   }
7061   StoreInst *SI = cast<StoreInst>(I);
7062 
7063   bool isLoopInvariantStoreValue = Legal->isUniform(SI->getValueOperand());
7064   return TTI.getAddressComputationCost(ValTy) +
7065          TTI.getMemoryOpCost(Instruction::Store, ValTy, Alignment, AS,
7066                              CostKind) +
7067          (isLoopInvariantStoreValue
7068               ? 0
7069               : TTI.getVectorInstrCost(Instruction::ExtractElement, VectorTy,
7070                                        VF.getKnownMinValue() - 1));
7071 }
7072 
7073 InstructionCost
7074 LoopVectorizationCostModel::getGatherScatterCost(Instruction *I,
7075                                                  ElementCount VF) {
7076   Type *ValTy = getLoadStoreType(I);
7077   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
7078   const Align Alignment = getLoadStoreAlignment(I);
7079   const Value *Ptr = getLoadStorePointerOperand(I);
7080 
7081   return TTI.getAddressComputationCost(VectorTy) +
7082          TTI.getGatherScatterOpCost(
7083              I->getOpcode(), VectorTy, Ptr, Legal->isMaskRequired(I), Alignment,
7084              TargetTransformInfo::TCK_RecipThroughput, I);
7085 }
7086 
7087 InstructionCost
7088 LoopVectorizationCostModel::getInterleaveGroupCost(Instruction *I,
7089                                                    ElementCount VF) {
7090   // TODO: Once we have support for interleaving with scalable vectors
7091   // we can calculate the cost properly here.
7092   if (VF.isScalable())
7093     return InstructionCost::getInvalid();
7094 
7095   Type *ValTy = getLoadStoreType(I);
7096   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
7097   unsigned AS = getLoadStoreAddressSpace(I);
7098 
7099   auto Group = getInterleavedAccessGroup(I);
7100   assert(Group && "Fail to get an interleaved access group.");
7101 
7102   unsigned InterleaveFactor = Group->getFactor();
7103   auto *WideVecTy = VectorType::get(ValTy, VF * InterleaveFactor);
7104 
7105   // Holds the indices of existing members in an interleaved load group.
7106   // An interleaved store group doesn't need this as it doesn't allow gaps.
7107   SmallVector<unsigned, 4> Indices;
7108   if (isa<LoadInst>(I)) {
7109     for (unsigned i = 0; i < InterleaveFactor; i++)
7110       if (Group->getMember(i))
7111         Indices.push_back(i);
7112   }
7113 
7114   // Calculate the cost of the whole interleaved group.
7115   bool UseMaskForGaps =
7116       Group->requiresScalarEpilogue() && !isScalarEpilogueAllowed();
7117   InstructionCost Cost = TTI.getInterleavedMemoryOpCost(
7118       I->getOpcode(), WideVecTy, Group->getFactor(), Indices, Group->getAlign(),
7119       AS, TTI::TCK_RecipThroughput, Legal->isMaskRequired(I), UseMaskForGaps);
7120 
7121   if (Group->isReverse()) {
7122     // TODO: Add support for reversed masked interleaved access.
7123     assert(!Legal->isMaskRequired(I) &&
7124            "Reverse masked interleaved access not supported.");
7125     Cost +=
7126         Group->getNumMembers() *
7127         TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, None, 0);
7128   }
7129   return Cost;
7130 }
7131 
7132 InstructionCost LoopVectorizationCostModel::getReductionPatternCost(
7133     Instruction *I, ElementCount VF, Type *Ty, TTI::TargetCostKind CostKind) {
7134   // Early exit for no inloop reductions
7135   if (InLoopReductionChains.empty() || VF.isScalar() || !isa<VectorType>(Ty))
7136     return InstructionCost::getInvalid();
7137   auto *VectorTy = cast<VectorType>(Ty);
7138 
7139   // We are looking for a pattern of, and finding the minimal acceptable cost:
7140   //  reduce(mul(ext(A), ext(B))) or
7141   //  reduce(mul(A, B)) or
7142   //  reduce(ext(A)) or
7143   //  reduce(A).
7144   // The basic idea is that we walk down the tree to do that, finding the root
7145   // reduction instruction in InLoopReductionImmediateChains. From there we find
7146   // the pattern of mul/ext and test the cost of the entire pattern vs the cost
7147   // of the components. If the reduction cost is lower then we return it for the
7148   // reduction instruction and 0 for the other instructions in the pattern. If
7149   // it is not we return an invalid cost specifying the orignal cost method
7150   // should be used.
7151   Instruction *RetI = I;
7152   if ((RetI->getOpcode() == Instruction::SExt ||
7153        RetI->getOpcode() == Instruction::ZExt)) {
7154     if (!RetI->hasOneUser())
7155       return InstructionCost::getInvalid();
7156     RetI = RetI->user_back();
7157   }
7158   if (RetI->getOpcode() == Instruction::Mul &&
7159       RetI->user_back()->getOpcode() == Instruction::Add) {
7160     if (!RetI->hasOneUser())
7161       return InstructionCost::getInvalid();
7162     RetI = RetI->user_back();
7163   }
7164 
7165   // Test if the found instruction is a reduction, and if not return an invalid
7166   // cost specifying the parent to use the original cost modelling.
7167   if (!InLoopReductionImmediateChains.count(RetI))
7168     return InstructionCost::getInvalid();
7169 
7170   // Find the reduction this chain is a part of and calculate the basic cost of
7171   // the reduction on its own.
7172   Instruction *LastChain = InLoopReductionImmediateChains[RetI];
7173   Instruction *ReductionPhi = LastChain;
7174   while (!isa<PHINode>(ReductionPhi))
7175     ReductionPhi = InLoopReductionImmediateChains[ReductionPhi];
7176 
7177   const RecurrenceDescriptor &RdxDesc =
7178       Legal->getReductionVars()[cast<PHINode>(ReductionPhi)];
7179   InstructionCost BaseCost =
7180       TTI.getArithmeticReductionCost(RdxDesc.getOpcode(), VectorTy, CostKind);
7181 
7182   // Get the operand that was not the reduction chain and match it to one of the
7183   // patterns, returning the better cost if it is found.
7184   Instruction *RedOp = RetI->getOperand(1) == LastChain
7185                            ? dyn_cast<Instruction>(RetI->getOperand(0))
7186                            : dyn_cast<Instruction>(RetI->getOperand(1));
7187 
7188   VectorTy = VectorType::get(I->getOperand(0)->getType(), VectorTy);
7189 
7190   if (RedOp && (isa<SExtInst>(RedOp) || isa<ZExtInst>(RedOp)) &&
7191       !TheLoop->isLoopInvariant(RedOp)) {
7192     bool IsUnsigned = isa<ZExtInst>(RedOp);
7193     auto *ExtType = VectorType::get(RedOp->getOperand(0)->getType(), VectorTy);
7194     InstructionCost RedCost = TTI.getExtendedAddReductionCost(
7195         /*IsMLA=*/false, IsUnsigned, RdxDesc.getRecurrenceType(), ExtType,
7196         CostKind);
7197 
7198     InstructionCost ExtCost =
7199         TTI.getCastInstrCost(RedOp->getOpcode(), VectorTy, ExtType,
7200                              TTI::CastContextHint::None, CostKind, RedOp);
7201     if (RedCost.isValid() && RedCost < BaseCost + ExtCost)
7202       return I == RetI ? *RedCost.getValue() : 0;
7203   } else if (RedOp && RedOp->getOpcode() == Instruction::Mul) {
7204     Instruction *Mul = RedOp;
7205     Instruction *Op0 = dyn_cast<Instruction>(Mul->getOperand(0));
7206     Instruction *Op1 = dyn_cast<Instruction>(Mul->getOperand(1));
7207     if (Op0 && Op1 && (isa<SExtInst>(Op0) || isa<ZExtInst>(Op0)) &&
7208         Op0->getOpcode() == Op1->getOpcode() &&
7209         Op0->getOperand(0)->getType() == Op1->getOperand(0)->getType() &&
7210         !TheLoop->isLoopInvariant(Op0) && !TheLoop->isLoopInvariant(Op1)) {
7211       bool IsUnsigned = isa<ZExtInst>(Op0);
7212       auto *ExtType = VectorType::get(Op0->getOperand(0)->getType(), VectorTy);
7213       // reduce(mul(ext, ext))
7214       InstructionCost ExtCost =
7215           TTI.getCastInstrCost(Op0->getOpcode(), VectorTy, ExtType,
7216                                TTI::CastContextHint::None, CostKind, Op0);
7217       InstructionCost MulCost =
7218           TTI.getArithmeticInstrCost(Mul->getOpcode(), VectorTy, CostKind);
7219 
7220       InstructionCost RedCost = TTI.getExtendedAddReductionCost(
7221           /*IsMLA=*/true, IsUnsigned, RdxDesc.getRecurrenceType(), ExtType,
7222           CostKind);
7223 
7224       if (RedCost.isValid() && RedCost < ExtCost * 2 + MulCost + BaseCost)
7225         return I == RetI ? *RedCost.getValue() : 0;
7226     } else {
7227       InstructionCost MulCost =
7228           TTI.getArithmeticInstrCost(Mul->getOpcode(), VectorTy, CostKind);
7229 
7230       InstructionCost RedCost = TTI.getExtendedAddReductionCost(
7231           /*IsMLA=*/true, true, RdxDesc.getRecurrenceType(), VectorTy,
7232           CostKind);
7233 
7234       if (RedCost.isValid() && RedCost < MulCost + BaseCost)
7235         return I == RetI ? *RedCost.getValue() : 0;
7236     }
7237   }
7238 
7239   return I == RetI ? BaseCost : InstructionCost::getInvalid();
7240 }
7241 
7242 InstructionCost
7243 LoopVectorizationCostModel::getMemoryInstructionCost(Instruction *I,
7244                                                      ElementCount VF) {
7245   // Calculate scalar cost only. Vectorization cost should be ready at this
7246   // moment.
7247   if (VF.isScalar()) {
7248     Type *ValTy = getLoadStoreType(I);
7249     const Align Alignment = getLoadStoreAlignment(I);
7250     unsigned AS = getLoadStoreAddressSpace(I);
7251 
7252     return TTI.getAddressComputationCost(ValTy) +
7253            TTI.getMemoryOpCost(I->getOpcode(), ValTy, Alignment, AS,
7254                                TTI::TCK_RecipThroughput, I);
7255   }
7256   return getWideningCost(I, VF);
7257 }
7258 
7259 LoopVectorizationCostModel::VectorizationCostTy
7260 LoopVectorizationCostModel::getInstructionCost(Instruction *I,
7261                                                ElementCount VF) {
7262   // If we know that this instruction will remain uniform, check the cost of
7263   // the scalar version.
7264   if (isUniformAfterVectorization(I, VF))
7265     VF = ElementCount::getFixed(1);
7266 
7267   if (VF.isVector() && isProfitableToScalarize(I, VF))
7268     return VectorizationCostTy(InstsToScalarize[VF][I], false);
7269 
7270   // Forced scalars do not have any scalarization overhead.
7271   auto ForcedScalar = ForcedScalars.find(VF);
7272   if (VF.isVector() && ForcedScalar != ForcedScalars.end()) {
7273     auto InstSet = ForcedScalar->second;
7274     if (InstSet.count(I))
7275       return VectorizationCostTy(
7276           (getInstructionCost(I, ElementCount::getFixed(1)).first *
7277            VF.getKnownMinValue()),
7278           false);
7279   }
7280 
7281   Type *VectorTy;
7282   InstructionCost C = getInstructionCost(I, VF, VectorTy);
7283 
7284   bool TypeNotScalarized =
7285       VF.isVector() && VectorTy->isVectorTy() &&
7286       TTI.getNumberOfParts(VectorTy) < VF.getKnownMinValue();
7287   return VectorizationCostTy(C, TypeNotScalarized);
7288 }
7289 
7290 InstructionCost
7291 LoopVectorizationCostModel::getScalarizationOverhead(Instruction *I,
7292                                                      ElementCount VF) const {
7293 
7294   if (VF.isScalable())
7295     return InstructionCost::getInvalid();
7296 
7297   if (VF.isScalar())
7298     return 0;
7299 
7300   InstructionCost Cost = 0;
7301   Type *RetTy = ToVectorTy(I->getType(), VF);
7302   if (!RetTy->isVoidTy() &&
7303       (!isa<LoadInst>(I) || !TTI.supportsEfficientVectorElementLoadStore()))
7304     Cost += TTI.getScalarizationOverhead(
7305         cast<VectorType>(RetTy), APInt::getAllOnesValue(VF.getKnownMinValue()),
7306         true, false);
7307 
7308   // Some targets keep addresses scalar.
7309   if (isa<LoadInst>(I) && !TTI.prefersVectorizedAddressing())
7310     return Cost;
7311 
7312   // Some targets support efficient element stores.
7313   if (isa<StoreInst>(I) && TTI.supportsEfficientVectorElementLoadStore())
7314     return Cost;
7315 
7316   // Collect operands to consider.
7317   CallInst *CI = dyn_cast<CallInst>(I);
7318   Instruction::op_range Ops = CI ? CI->arg_operands() : I->operands();
7319 
7320   // Skip operands that do not require extraction/scalarization and do not incur
7321   // any overhead.
7322   SmallVector<Type *> Tys;
7323   for (auto *V : filterExtractingOperands(Ops, VF))
7324     Tys.push_back(MaybeVectorizeType(V->getType(), VF));
7325   return Cost + TTI.getOperandsScalarizationOverhead(
7326                     filterExtractingOperands(Ops, VF), Tys);
7327 }
7328 
7329 void LoopVectorizationCostModel::setCostBasedWideningDecision(ElementCount VF) {
7330   if (VF.isScalar())
7331     return;
7332   NumPredStores = 0;
7333   for (BasicBlock *BB : TheLoop->blocks()) {
7334     // For each instruction in the old loop.
7335     for (Instruction &I : *BB) {
7336       Value *Ptr =  getLoadStorePointerOperand(&I);
7337       if (!Ptr)
7338         continue;
7339 
7340       // TODO: We should generate better code and update the cost model for
7341       // predicated uniform stores. Today they are treated as any other
7342       // predicated store (see added test cases in
7343       // invariant-store-vectorization.ll).
7344       if (isa<StoreInst>(&I) && isScalarWithPredication(&I))
7345         NumPredStores++;
7346 
7347       if (Legal->isUniformMemOp(I)) {
7348         // TODO: Avoid replicating loads and stores instead of
7349         // relying on instcombine to remove them.
7350         // Load: Scalar load + broadcast
7351         // Store: Scalar store + isLoopInvariantStoreValue ? 0 : extract
7352         InstructionCost Cost;
7353         if (isa<StoreInst>(&I) && VF.isScalable() &&
7354             isLegalGatherOrScatter(&I)) {
7355           Cost = getGatherScatterCost(&I, VF);
7356           setWideningDecision(&I, VF, CM_GatherScatter, Cost);
7357         } else {
7358           assert((isa<LoadInst>(&I) || !VF.isScalable()) &&
7359                  "Cannot yet scalarize uniform stores");
7360           Cost = getUniformMemOpCost(&I, VF);
7361           setWideningDecision(&I, VF, CM_Scalarize, Cost);
7362         }
7363         continue;
7364       }
7365 
7366       // We assume that widening is the best solution when possible.
7367       if (memoryInstructionCanBeWidened(&I, VF)) {
7368         InstructionCost Cost = getConsecutiveMemOpCost(&I, VF);
7369         int ConsecutiveStride =
7370                Legal->isConsecutivePtr(getLoadStorePointerOperand(&I));
7371         assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
7372                "Expected consecutive stride.");
7373         InstWidening Decision =
7374             ConsecutiveStride == 1 ? CM_Widen : CM_Widen_Reverse;
7375         setWideningDecision(&I, VF, Decision, Cost);
7376         continue;
7377       }
7378 
7379       // Choose between Interleaving, Gather/Scatter or Scalarization.
7380       InstructionCost InterleaveCost = InstructionCost::getInvalid();
7381       unsigned NumAccesses = 1;
7382       if (isAccessInterleaved(&I)) {
7383         auto Group = getInterleavedAccessGroup(&I);
7384         assert(Group && "Fail to get an interleaved access group.");
7385 
7386         // Make one decision for the whole group.
7387         if (getWideningDecision(&I, VF) != CM_Unknown)
7388           continue;
7389 
7390         NumAccesses = Group->getNumMembers();
7391         if (interleavedAccessCanBeWidened(&I, VF))
7392           InterleaveCost = getInterleaveGroupCost(&I, VF);
7393       }
7394 
7395       InstructionCost GatherScatterCost =
7396           isLegalGatherOrScatter(&I)
7397               ? getGatherScatterCost(&I, VF) * NumAccesses
7398               : InstructionCost::getInvalid();
7399 
7400       InstructionCost ScalarizationCost =
7401           getMemInstScalarizationCost(&I, VF) * NumAccesses;
7402 
7403       // Choose better solution for the current VF,
7404       // write down this decision and use it during vectorization.
7405       InstructionCost Cost;
7406       InstWidening Decision;
7407       if (InterleaveCost <= GatherScatterCost &&
7408           InterleaveCost < ScalarizationCost) {
7409         Decision = CM_Interleave;
7410         Cost = InterleaveCost;
7411       } else if (GatherScatterCost < ScalarizationCost) {
7412         Decision = CM_GatherScatter;
7413         Cost = GatherScatterCost;
7414       } else {
7415         assert(!VF.isScalable() &&
7416                "We cannot yet scalarise for scalable vectors");
7417         Decision = CM_Scalarize;
7418         Cost = ScalarizationCost;
7419       }
7420       // If the instructions belongs to an interleave group, the whole group
7421       // receives the same decision. The whole group receives the cost, but
7422       // the cost will actually be assigned to one instruction.
7423       if (auto Group = getInterleavedAccessGroup(&I))
7424         setWideningDecision(Group, VF, Decision, Cost);
7425       else
7426         setWideningDecision(&I, VF, Decision, Cost);
7427     }
7428   }
7429 
7430   // Make sure that any load of address and any other address computation
7431   // remains scalar unless there is gather/scatter support. This avoids
7432   // inevitable extracts into address registers, and also has the benefit of
7433   // activating LSR more, since that pass can't optimize vectorized
7434   // addresses.
7435   if (TTI.prefersVectorizedAddressing())
7436     return;
7437 
7438   // Start with all scalar pointer uses.
7439   SmallPtrSet<Instruction *, 8> AddrDefs;
7440   for (BasicBlock *BB : TheLoop->blocks())
7441     for (Instruction &I : *BB) {
7442       Instruction *PtrDef =
7443         dyn_cast_or_null<Instruction>(getLoadStorePointerOperand(&I));
7444       if (PtrDef && TheLoop->contains(PtrDef) &&
7445           getWideningDecision(&I, VF) != CM_GatherScatter)
7446         AddrDefs.insert(PtrDef);
7447     }
7448 
7449   // Add all instructions used to generate the addresses.
7450   SmallVector<Instruction *, 4> Worklist;
7451   append_range(Worklist, AddrDefs);
7452   while (!Worklist.empty()) {
7453     Instruction *I = Worklist.pop_back_val();
7454     for (auto &Op : I->operands())
7455       if (auto *InstOp = dyn_cast<Instruction>(Op))
7456         if ((InstOp->getParent() == I->getParent()) && !isa<PHINode>(InstOp) &&
7457             AddrDefs.insert(InstOp).second)
7458           Worklist.push_back(InstOp);
7459   }
7460 
7461   for (auto *I : AddrDefs) {
7462     if (isa<LoadInst>(I)) {
7463       // Setting the desired widening decision should ideally be handled in
7464       // by cost functions, but since this involves the task of finding out
7465       // if the loaded register is involved in an address computation, it is
7466       // instead changed here when we know this is the case.
7467       InstWidening Decision = getWideningDecision(I, VF);
7468       if (Decision == CM_Widen || Decision == CM_Widen_Reverse)
7469         // Scalarize a widened load of address.
7470         setWideningDecision(
7471             I, VF, CM_Scalarize,
7472             (VF.getKnownMinValue() *
7473              getMemoryInstructionCost(I, ElementCount::getFixed(1))));
7474       else if (auto Group = getInterleavedAccessGroup(I)) {
7475         // Scalarize an interleave group of address loads.
7476         for (unsigned I = 0; I < Group->getFactor(); ++I) {
7477           if (Instruction *Member = Group->getMember(I))
7478             setWideningDecision(
7479                 Member, VF, CM_Scalarize,
7480                 (VF.getKnownMinValue() *
7481                  getMemoryInstructionCost(Member, ElementCount::getFixed(1))));
7482         }
7483       }
7484     } else
7485       // Make sure I gets scalarized and a cost estimate without
7486       // scalarization overhead.
7487       ForcedScalars[VF].insert(I);
7488   }
7489 }
7490 
7491 InstructionCost
7492 LoopVectorizationCostModel::getInstructionCost(Instruction *I, ElementCount VF,
7493                                                Type *&VectorTy) {
7494   Type *RetTy = I->getType();
7495   if (canTruncateToMinimalBitwidth(I, VF))
7496     RetTy = IntegerType::get(RetTy->getContext(), MinBWs[I]);
7497   auto SE = PSE.getSE();
7498   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
7499 
7500   auto hasSingleCopyAfterVectorization = [this](Instruction *I,
7501                                                 ElementCount VF) -> bool {
7502     if (VF.isScalar())
7503       return true;
7504 
7505     auto Scalarized = InstsToScalarize.find(VF);
7506     assert(Scalarized != InstsToScalarize.end() &&
7507            "VF not yet analyzed for scalarization profitability");
7508     return !Scalarized->second.count(I) &&
7509            llvm::all_of(I->users(), [&](User *U) {
7510              auto *UI = cast<Instruction>(U);
7511              return !Scalarized->second.count(UI);
7512            });
7513   };
7514   (void) hasSingleCopyAfterVectorization;
7515 
7516   if (isScalarAfterVectorization(I, VF)) {
7517     // With the exception of GEPs and PHIs, after scalarization there should
7518     // only be one copy of the instruction generated in the loop. This is
7519     // because the VF is either 1, or any instructions that need scalarizing
7520     // have already been dealt with by the the time we get here. As a result,
7521     // it means we don't have to multiply the instruction cost by VF.
7522     assert(I->getOpcode() == Instruction::GetElementPtr ||
7523            I->getOpcode() == Instruction::PHI ||
7524            (I->getOpcode() == Instruction::BitCast &&
7525             I->getType()->isPointerTy()) ||
7526            hasSingleCopyAfterVectorization(I, VF));
7527     VectorTy = RetTy;
7528   } else
7529     VectorTy = ToVectorTy(RetTy, VF);
7530 
7531   // TODO: We need to estimate the cost of intrinsic calls.
7532   switch (I->getOpcode()) {
7533   case Instruction::GetElementPtr:
7534     // We mark this instruction as zero-cost because the cost of GEPs in
7535     // vectorized code depends on whether the corresponding memory instruction
7536     // is scalarized or not. Therefore, we handle GEPs with the memory
7537     // instruction cost.
7538     return 0;
7539   case Instruction::Br: {
7540     // In cases of scalarized and predicated instructions, there will be VF
7541     // predicated blocks in the vectorized loop. Each branch around these
7542     // blocks requires also an extract of its vector compare i1 element.
7543     bool ScalarPredicatedBB = false;
7544     BranchInst *BI = cast<BranchInst>(I);
7545     if (VF.isVector() && BI->isConditional() &&
7546         (PredicatedBBsAfterVectorization.count(BI->getSuccessor(0)) ||
7547          PredicatedBBsAfterVectorization.count(BI->getSuccessor(1))))
7548       ScalarPredicatedBB = true;
7549 
7550     if (ScalarPredicatedBB) {
7551       // Return cost for branches around scalarized and predicated blocks.
7552       assert(!VF.isScalable() && "scalable vectors not yet supported.");
7553       auto *Vec_i1Ty =
7554           VectorType::get(IntegerType::getInt1Ty(RetTy->getContext()), VF);
7555       return (TTI.getScalarizationOverhead(
7556                   Vec_i1Ty, APInt::getAllOnesValue(VF.getKnownMinValue()),
7557                   false, true) +
7558               (TTI.getCFInstrCost(Instruction::Br, CostKind) *
7559                VF.getKnownMinValue()));
7560     } else if (I->getParent() == TheLoop->getLoopLatch() || VF.isScalar())
7561       // The back-edge branch will remain, as will all scalar branches.
7562       return TTI.getCFInstrCost(Instruction::Br, CostKind);
7563     else
7564       // This branch will be eliminated by if-conversion.
7565       return 0;
7566     // Note: We currently assume zero cost for an unconditional branch inside
7567     // a predicated block since it will become a fall-through, although we
7568     // may decide in the future to call TTI for all branches.
7569   }
7570   case Instruction::PHI: {
7571     auto *Phi = cast<PHINode>(I);
7572 
7573     // First-order recurrences are replaced by vector shuffles inside the loop.
7574     // NOTE: Don't use ToVectorTy as SK_ExtractSubvector expects a vector type.
7575     if (VF.isVector() && Legal->isFirstOrderRecurrence(Phi))
7576       return TTI.getShuffleCost(
7577           TargetTransformInfo::SK_ExtractSubvector, cast<VectorType>(VectorTy),
7578           None, VF.getKnownMinValue() - 1, FixedVectorType::get(RetTy, 1));
7579 
7580     // Phi nodes in non-header blocks (not inductions, reductions, etc.) are
7581     // converted into select instructions. We require N - 1 selects per phi
7582     // node, where N is the number of incoming values.
7583     if (VF.isVector() && Phi->getParent() != TheLoop->getHeader())
7584       return (Phi->getNumIncomingValues() - 1) *
7585              TTI.getCmpSelInstrCost(
7586                  Instruction::Select, ToVectorTy(Phi->getType(), VF),
7587                  ToVectorTy(Type::getInt1Ty(Phi->getContext()), VF),
7588                  CmpInst::BAD_ICMP_PREDICATE, CostKind);
7589 
7590     return TTI.getCFInstrCost(Instruction::PHI, CostKind);
7591   }
7592   case Instruction::UDiv:
7593   case Instruction::SDiv:
7594   case Instruction::URem:
7595   case Instruction::SRem:
7596     // If we have a predicated instruction, it may not be executed for each
7597     // vector lane. Get the scalarization cost and scale this amount by the
7598     // probability of executing the predicated block. If the instruction is not
7599     // predicated, we fall through to the next case.
7600     if (VF.isVector() && isScalarWithPredication(I)) {
7601       InstructionCost Cost = 0;
7602 
7603       // These instructions have a non-void type, so account for the phi nodes
7604       // that we will create. This cost is likely to be zero. The phi node
7605       // cost, if any, should be scaled by the block probability because it
7606       // models a copy at the end of each predicated block.
7607       Cost += VF.getKnownMinValue() *
7608               TTI.getCFInstrCost(Instruction::PHI, CostKind);
7609 
7610       // The cost of the non-predicated instruction.
7611       Cost += VF.getKnownMinValue() *
7612               TTI.getArithmeticInstrCost(I->getOpcode(), RetTy, CostKind);
7613 
7614       // The cost of insertelement and extractelement instructions needed for
7615       // scalarization.
7616       Cost += getScalarizationOverhead(I, VF);
7617 
7618       // Scale the cost by the probability of executing the predicated blocks.
7619       // This assumes the predicated block for each vector lane is equally
7620       // likely.
7621       return Cost / getReciprocalPredBlockProb();
7622     }
7623     LLVM_FALLTHROUGH;
7624   case Instruction::Add:
7625   case Instruction::FAdd:
7626   case Instruction::Sub:
7627   case Instruction::FSub:
7628   case Instruction::Mul:
7629   case Instruction::FMul:
7630   case Instruction::FDiv:
7631   case Instruction::FRem:
7632   case Instruction::Shl:
7633   case Instruction::LShr:
7634   case Instruction::AShr:
7635   case Instruction::And:
7636   case Instruction::Or:
7637   case Instruction::Xor: {
7638     // Since we will replace the stride by 1 the multiplication should go away.
7639     if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
7640       return 0;
7641 
7642     // Detect reduction patterns
7643     InstructionCost RedCost;
7644     if ((RedCost = getReductionPatternCost(I, VF, VectorTy, CostKind))
7645             .isValid())
7646       return RedCost;
7647 
7648     // Certain instructions can be cheaper to vectorize if they have a constant
7649     // second vector operand. One example of this are shifts on x86.
7650     Value *Op2 = I->getOperand(1);
7651     TargetTransformInfo::OperandValueProperties Op2VP;
7652     TargetTransformInfo::OperandValueKind Op2VK =
7653         TTI.getOperandInfo(Op2, Op2VP);
7654     if (Op2VK == TargetTransformInfo::OK_AnyValue && Legal->isUniform(Op2))
7655       Op2VK = TargetTransformInfo::OK_UniformValue;
7656 
7657     SmallVector<const Value *, 4> Operands(I->operand_values());
7658     return TTI.getArithmeticInstrCost(
7659         I->getOpcode(), VectorTy, CostKind, TargetTransformInfo::OK_AnyValue,
7660         Op2VK, TargetTransformInfo::OP_None, Op2VP, Operands, I);
7661   }
7662   case Instruction::FNeg: {
7663     return TTI.getArithmeticInstrCost(
7664         I->getOpcode(), VectorTy, CostKind, TargetTransformInfo::OK_AnyValue,
7665         TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None,
7666         TargetTransformInfo::OP_None, I->getOperand(0), I);
7667   }
7668   case Instruction::Select: {
7669     SelectInst *SI = cast<SelectInst>(I);
7670     const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
7671     bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
7672 
7673     const Value *Op0, *Op1;
7674     using namespace llvm::PatternMatch;
7675     if (!ScalarCond && (match(I, m_LogicalAnd(m_Value(Op0), m_Value(Op1))) ||
7676                         match(I, m_LogicalOr(m_Value(Op0), m_Value(Op1))))) {
7677       // select x, y, false --> x & y
7678       // select x, true, y --> x | y
7679       TTI::OperandValueProperties Op1VP = TTI::OP_None;
7680       TTI::OperandValueProperties Op2VP = TTI::OP_None;
7681       TTI::OperandValueKind Op1VK = TTI::getOperandInfo(Op0, Op1VP);
7682       TTI::OperandValueKind Op2VK = TTI::getOperandInfo(Op1, Op2VP);
7683       assert(Op0->getType()->getScalarSizeInBits() == 1 &&
7684               Op1->getType()->getScalarSizeInBits() == 1);
7685 
7686       SmallVector<const Value *, 2> Operands{Op0, Op1};
7687       return TTI.getArithmeticInstrCost(
7688           match(I, m_LogicalOr()) ? Instruction::Or : Instruction::And, VectorTy,
7689           CostKind, Op1VK, Op2VK, Op1VP, Op2VP, Operands, I);
7690     }
7691 
7692     Type *CondTy = SI->getCondition()->getType();
7693     if (!ScalarCond)
7694       CondTy = VectorType::get(CondTy, VF);
7695     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy,
7696                                   CmpInst::BAD_ICMP_PREDICATE, CostKind, I);
7697   }
7698   case Instruction::ICmp:
7699   case Instruction::FCmp: {
7700     Type *ValTy = I->getOperand(0)->getType();
7701     Instruction *Op0AsInstruction = dyn_cast<Instruction>(I->getOperand(0));
7702     if (canTruncateToMinimalBitwidth(Op0AsInstruction, VF))
7703       ValTy = IntegerType::get(ValTy->getContext(), MinBWs[Op0AsInstruction]);
7704     VectorTy = ToVectorTy(ValTy, VF);
7705     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, nullptr,
7706                                   CmpInst::BAD_ICMP_PREDICATE, CostKind, I);
7707   }
7708   case Instruction::Store:
7709   case Instruction::Load: {
7710     ElementCount Width = VF;
7711     if (Width.isVector()) {
7712       InstWidening Decision = getWideningDecision(I, Width);
7713       assert(Decision != CM_Unknown &&
7714              "CM decision should be taken at this point");
7715       if (Decision == CM_Scalarize)
7716         Width = ElementCount::getFixed(1);
7717     }
7718     VectorTy = ToVectorTy(getLoadStoreType(I), Width);
7719     return getMemoryInstructionCost(I, VF);
7720   }
7721   case Instruction::BitCast:
7722     if (I->getType()->isPointerTy())
7723       return 0;
7724     LLVM_FALLTHROUGH;
7725   case Instruction::ZExt:
7726   case Instruction::SExt:
7727   case Instruction::FPToUI:
7728   case Instruction::FPToSI:
7729   case Instruction::FPExt:
7730   case Instruction::PtrToInt:
7731   case Instruction::IntToPtr:
7732   case Instruction::SIToFP:
7733   case Instruction::UIToFP:
7734   case Instruction::Trunc:
7735   case Instruction::FPTrunc: {
7736     // Computes the CastContextHint from a Load/Store instruction.
7737     auto ComputeCCH = [&](Instruction *I) -> TTI::CastContextHint {
7738       assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
7739              "Expected a load or a store!");
7740 
7741       if (VF.isScalar() || !TheLoop->contains(I))
7742         return TTI::CastContextHint::Normal;
7743 
7744       switch (getWideningDecision(I, VF)) {
7745       case LoopVectorizationCostModel::CM_GatherScatter:
7746         return TTI::CastContextHint::GatherScatter;
7747       case LoopVectorizationCostModel::CM_Interleave:
7748         return TTI::CastContextHint::Interleave;
7749       case LoopVectorizationCostModel::CM_Scalarize:
7750       case LoopVectorizationCostModel::CM_Widen:
7751         return Legal->isMaskRequired(I) ? TTI::CastContextHint::Masked
7752                                         : TTI::CastContextHint::Normal;
7753       case LoopVectorizationCostModel::CM_Widen_Reverse:
7754         return TTI::CastContextHint::Reversed;
7755       case LoopVectorizationCostModel::CM_Unknown:
7756         llvm_unreachable("Instr did not go through cost modelling?");
7757       }
7758 
7759       llvm_unreachable("Unhandled case!");
7760     };
7761 
7762     unsigned Opcode = I->getOpcode();
7763     TTI::CastContextHint CCH = TTI::CastContextHint::None;
7764     // For Trunc, the context is the only user, which must be a StoreInst.
7765     if (Opcode == Instruction::Trunc || Opcode == Instruction::FPTrunc) {
7766       if (I->hasOneUse())
7767         if (StoreInst *Store = dyn_cast<StoreInst>(*I->user_begin()))
7768           CCH = ComputeCCH(Store);
7769     }
7770     // For Z/Sext, the context is the operand, which must be a LoadInst.
7771     else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt ||
7772              Opcode == Instruction::FPExt) {
7773       if (LoadInst *Load = dyn_cast<LoadInst>(I->getOperand(0)))
7774         CCH = ComputeCCH(Load);
7775     }
7776 
7777     // We optimize the truncation of induction variables having constant
7778     // integer steps. The cost of these truncations is the same as the scalar
7779     // operation.
7780     if (isOptimizableIVTruncate(I, VF)) {
7781       auto *Trunc = cast<TruncInst>(I);
7782       return TTI.getCastInstrCost(Instruction::Trunc, Trunc->getDestTy(),
7783                                   Trunc->getSrcTy(), CCH, CostKind, Trunc);
7784     }
7785 
7786     // Detect reduction patterns
7787     InstructionCost RedCost;
7788     if ((RedCost = getReductionPatternCost(I, VF, VectorTy, CostKind))
7789             .isValid())
7790       return RedCost;
7791 
7792     Type *SrcScalarTy = I->getOperand(0)->getType();
7793     Type *SrcVecTy =
7794         VectorTy->isVectorTy() ? ToVectorTy(SrcScalarTy, VF) : SrcScalarTy;
7795     if (canTruncateToMinimalBitwidth(I, VF)) {
7796       // This cast is going to be shrunk. This may remove the cast or it might
7797       // turn it into slightly different cast. For example, if MinBW == 16,
7798       // "zext i8 %1 to i32" becomes "zext i8 %1 to i16".
7799       //
7800       // Calculate the modified src and dest types.
7801       Type *MinVecTy = VectorTy;
7802       if (Opcode == Instruction::Trunc) {
7803         SrcVecTy = smallestIntegerVectorType(SrcVecTy, MinVecTy);
7804         VectorTy =
7805             largestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy);
7806       } else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
7807         SrcVecTy = largestIntegerVectorType(SrcVecTy, MinVecTy);
7808         VectorTy =
7809             smallestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy);
7810       }
7811     }
7812 
7813     return TTI.getCastInstrCost(Opcode, VectorTy, SrcVecTy, CCH, CostKind, I);
7814   }
7815   case Instruction::Call: {
7816     bool NeedToScalarize;
7817     CallInst *CI = cast<CallInst>(I);
7818     InstructionCost CallCost = getVectorCallCost(CI, VF, NeedToScalarize);
7819     if (getVectorIntrinsicIDForCall(CI, TLI)) {
7820       InstructionCost IntrinsicCost = getVectorIntrinsicCost(CI, VF);
7821       return std::min(CallCost, IntrinsicCost);
7822     }
7823     return CallCost;
7824   }
7825   case Instruction::ExtractValue:
7826     return TTI.getInstructionCost(I, TTI::TCK_RecipThroughput);
7827   default:
7828     // This opcode is unknown. Assume that it is the same as 'mul'.
7829     return TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy, CostKind);
7830   } // end of switch.
7831 }
7832 
7833 char LoopVectorize::ID = 0;
7834 
7835 static const char lv_name[] = "Loop Vectorization";
7836 
7837 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
7838 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
7839 INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
7840 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
7841 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
7842 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
7843 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
7844 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
7845 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
7846 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
7847 INITIALIZE_PASS_DEPENDENCY(LoopAccessLegacyAnalysis)
7848 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
7849 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
7850 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
7851 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
7852 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
7853 
7854 namespace llvm {
7855 
7856 Pass *createLoopVectorizePass() { return new LoopVectorize(); }
7857 
7858 Pass *createLoopVectorizePass(bool InterleaveOnlyWhenForced,
7859                               bool VectorizeOnlyWhenForced) {
7860   return new LoopVectorize(InterleaveOnlyWhenForced, VectorizeOnlyWhenForced);
7861 }
7862 
7863 } // end namespace llvm
7864 
7865 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
7866   // Check if the pointer operand of a load or store instruction is
7867   // consecutive.
7868   if (auto *Ptr = getLoadStorePointerOperand(Inst))
7869     return Legal->isConsecutivePtr(Ptr);
7870   return false;
7871 }
7872 
7873 void LoopVectorizationCostModel::collectValuesToIgnore() {
7874   // Ignore ephemeral values.
7875   CodeMetrics::collectEphemeralValues(TheLoop, AC, ValuesToIgnore);
7876 
7877   // Ignore type-promoting instructions we identified during reduction
7878   // detection.
7879   for (auto &Reduction : Legal->getReductionVars()) {
7880     RecurrenceDescriptor &RedDes = Reduction.second;
7881     const SmallPtrSetImpl<Instruction *> &Casts = RedDes.getCastInsts();
7882     VecValuesToIgnore.insert(Casts.begin(), Casts.end());
7883   }
7884   // Ignore type-casting instructions we identified during induction
7885   // detection.
7886   for (auto &Induction : Legal->getInductionVars()) {
7887     InductionDescriptor &IndDes = Induction.second;
7888     const SmallVectorImpl<Instruction *> &Casts = IndDes.getCastInsts();
7889     VecValuesToIgnore.insert(Casts.begin(), Casts.end());
7890   }
7891 }
7892 
7893 void LoopVectorizationCostModel::collectInLoopReductions() {
7894   for (auto &Reduction : Legal->getReductionVars()) {
7895     PHINode *Phi = Reduction.first;
7896     RecurrenceDescriptor &RdxDesc = Reduction.second;
7897 
7898     // We don't collect reductions that are type promoted (yet).
7899     if (RdxDesc.getRecurrenceType() != Phi->getType())
7900       continue;
7901 
7902     // If the target would prefer this reduction to happen "in-loop", then we
7903     // want to record it as such.
7904     unsigned Opcode = RdxDesc.getOpcode();
7905     if (!PreferInLoopReductions && !useOrderedReductions(RdxDesc) &&
7906         !TTI.preferInLoopReduction(Opcode, Phi->getType(),
7907                                    TargetTransformInfo::ReductionFlags()))
7908       continue;
7909 
7910     // Check that we can correctly put the reductions into the loop, by
7911     // finding the chain of operations that leads from the phi to the loop
7912     // exit value.
7913     SmallVector<Instruction *, 4> ReductionOperations =
7914         RdxDesc.getReductionOpChain(Phi, TheLoop);
7915     bool InLoop = !ReductionOperations.empty();
7916     if (InLoop) {
7917       InLoopReductionChains[Phi] = ReductionOperations;
7918       // Add the elements to InLoopReductionImmediateChains for cost modelling.
7919       Instruction *LastChain = Phi;
7920       for (auto *I : ReductionOperations) {
7921         InLoopReductionImmediateChains[I] = LastChain;
7922         LastChain = I;
7923       }
7924     }
7925     LLVM_DEBUG(dbgs() << "LV: Using " << (InLoop ? "inloop" : "out of loop")
7926                       << " reduction for phi: " << *Phi << "\n");
7927   }
7928 }
7929 
7930 // TODO: we could return a pair of values that specify the max VF and
7931 // min VF, to be used in `buildVPlans(MinVF, MaxVF)` instead of
7932 // `buildVPlans(VF, VF)`. We cannot do it because VPLAN at the moment
7933 // doesn't have a cost model that can choose which plan to execute if
7934 // more than one is generated.
7935 static unsigned determineVPlanVF(const unsigned WidestVectorRegBits,
7936                                  LoopVectorizationCostModel &CM) {
7937   unsigned WidestType;
7938   std::tie(std::ignore, WidestType) = CM.getSmallestAndWidestTypes();
7939   return WidestVectorRegBits / WidestType;
7940 }
7941 
7942 VectorizationFactor
7943 LoopVectorizationPlanner::planInVPlanNativePath(ElementCount UserVF) {
7944   assert(!UserVF.isScalable() && "scalable vectors not yet supported");
7945   ElementCount VF = UserVF;
7946   // Outer loop handling: They may require CFG and instruction level
7947   // transformations before even evaluating whether vectorization is profitable.
7948   // Since we cannot modify the incoming IR, we need to build VPlan upfront in
7949   // the vectorization pipeline.
7950   if (!OrigLoop->isInnermost()) {
7951     // If the user doesn't provide a vectorization factor, determine a
7952     // reasonable one.
7953     if (UserVF.isZero()) {
7954       VF = ElementCount::getFixed(determineVPlanVF(
7955           TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector)
7956               .getFixedSize(),
7957           CM));
7958       LLVM_DEBUG(dbgs() << "LV: VPlan computed VF " << VF << ".\n");
7959 
7960       // Make sure we have a VF > 1 for stress testing.
7961       if (VPlanBuildStressTest && (VF.isScalar() || VF.isZero())) {
7962         LLVM_DEBUG(dbgs() << "LV: VPlan stress testing: "
7963                           << "overriding computed VF.\n");
7964         VF = ElementCount::getFixed(4);
7965       }
7966     }
7967     assert(EnableVPlanNativePath && "VPlan-native path is not enabled.");
7968     assert(isPowerOf2_32(VF.getKnownMinValue()) &&
7969            "VF needs to be a power of two");
7970     LLVM_DEBUG(dbgs() << "LV: Using " << (!UserVF.isZero() ? "user " : "")
7971                       << "VF " << VF << " to build VPlans.\n");
7972     buildVPlans(VF, VF);
7973 
7974     // For VPlan build stress testing, we bail out after VPlan construction.
7975     if (VPlanBuildStressTest)
7976       return VectorizationFactor::Disabled();
7977 
7978     return {VF, 0 /*Cost*/};
7979   }
7980 
7981   LLVM_DEBUG(
7982       dbgs() << "LV: Not vectorizing. Inner loops aren't supported in the "
7983                 "VPlan-native path.\n");
7984   return VectorizationFactor::Disabled();
7985 }
7986 
7987 Optional<VectorizationFactor>
7988 LoopVectorizationPlanner::plan(ElementCount UserVF, unsigned UserIC) {
7989   assert(OrigLoop->isInnermost() && "Inner loop expected.");
7990   FixedScalableVFPair MaxFactors = CM.computeMaxVF(UserVF, UserIC);
7991   if (!MaxFactors) // Cases that should not to be vectorized nor interleaved.
7992     return None;
7993 
7994   // Invalidate interleave groups if all blocks of loop will be predicated.
7995   if (CM.blockNeedsPredication(OrigLoop->getHeader()) &&
7996       !useMaskedInterleavedAccesses(*TTI)) {
7997     LLVM_DEBUG(
7998         dbgs()
7999         << "LV: Invalidate all interleaved groups due to fold-tail by masking "
8000            "which requires masked-interleaved support.\n");
8001     if (CM.InterleaveInfo.invalidateGroups())
8002       // Invalidating interleave groups also requires invalidating all decisions
8003       // based on them, which includes widening decisions and uniform and scalar
8004       // values.
8005       CM.invalidateCostModelingDecisions();
8006   }
8007 
8008   ElementCount MaxUserVF =
8009       UserVF.isScalable() ? MaxFactors.ScalableVF : MaxFactors.FixedVF;
8010   bool UserVFIsLegal = ElementCount::isKnownLE(UserVF, MaxUserVF);
8011   if (!UserVF.isZero() && UserVFIsLegal) {
8012     LLVM_DEBUG(dbgs() << "LV: Using " << (UserVFIsLegal ? "user" : "max")
8013                       << " VF " << UserVF << ".\n");
8014     assert(isPowerOf2_32(UserVF.getKnownMinValue()) &&
8015            "VF needs to be a power of two");
8016     // Collect the instructions (and their associated costs) that will be more
8017     // profitable to scalarize.
8018     CM.selectUserVectorizationFactor(UserVF);
8019     CM.collectInLoopReductions();
8020     buildVPlansWithVPRecipes(UserVF, UserVF);
8021     LLVM_DEBUG(printPlans(dbgs()));
8022     return {{UserVF, 0}};
8023   }
8024 
8025   // Populate the set of Vectorization Factor Candidates.
8026   ElementCountSet VFCandidates;
8027   for (auto VF = ElementCount::getFixed(1);
8028        ElementCount::isKnownLE(VF, MaxFactors.FixedVF); VF *= 2)
8029     VFCandidates.insert(VF);
8030   for (auto VF = ElementCount::getScalable(1);
8031        ElementCount::isKnownLE(VF, MaxFactors.ScalableVF); VF *= 2)
8032     VFCandidates.insert(VF);
8033 
8034   for (const auto &VF : VFCandidates) {
8035     // Collect Uniform and Scalar instructions after vectorization with VF.
8036     CM.collectUniformsAndScalars(VF);
8037 
8038     // Collect the instructions (and their associated costs) that will be more
8039     // profitable to scalarize.
8040     if (VF.isVector())
8041       CM.collectInstsToScalarize(VF);
8042   }
8043 
8044   CM.collectInLoopReductions();
8045   buildVPlansWithVPRecipes(ElementCount::getFixed(1), MaxFactors.FixedVF);
8046   buildVPlansWithVPRecipes(ElementCount::getScalable(1), MaxFactors.ScalableVF);
8047 
8048   LLVM_DEBUG(printPlans(dbgs()));
8049   if (!MaxFactors.hasVector())
8050     return VectorizationFactor::Disabled();
8051 
8052   // Select the optimal vectorization factor.
8053   auto SelectedVF = CM.selectVectorizationFactor(VFCandidates);
8054 
8055   // Check if it is profitable to vectorize with runtime checks.
8056   unsigned NumRuntimePointerChecks = Requirements.getNumRuntimePointerChecks();
8057   if (SelectedVF.Width.getKnownMinValue() > 1 && NumRuntimePointerChecks) {
8058     bool PragmaThresholdReached =
8059         NumRuntimePointerChecks > PragmaVectorizeMemoryCheckThreshold;
8060     bool ThresholdReached =
8061         NumRuntimePointerChecks > VectorizerParams::RuntimeMemoryCheckThreshold;
8062     if ((ThresholdReached && !Hints.allowReordering()) ||
8063         PragmaThresholdReached) {
8064       ORE->emit([&]() {
8065         return OptimizationRemarkAnalysisAliasing(
8066                    DEBUG_TYPE, "CantReorderMemOps", OrigLoop->getStartLoc(),
8067                    OrigLoop->getHeader())
8068                << "loop not vectorized: cannot prove it is safe to reorder "
8069                   "memory operations";
8070       });
8071       LLVM_DEBUG(dbgs() << "LV: Too many memory checks needed.\n");
8072       Hints.emitRemarkWithHints();
8073       return VectorizationFactor::Disabled();
8074     }
8075   }
8076   return SelectedVF;
8077 }
8078 
8079 void LoopVectorizationPlanner::setBestPlan(ElementCount VF, unsigned UF) {
8080   LLVM_DEBUG(dbgs() << "Setting best plan to VF=" << VF << ", UF=" << UF
8081                     << '\n');
8082   BestVF = VF;
8083   BestUF = UF;
8084 
8085   erase_if(VPlans, [VF](const VPlanPtr &Plan) {
8086     return !Plan->hasVF(VF);
8087   });
8088   assert(VPlans.size() == 1 && "Best VF has not a single VPlan.");
8089 }
8090 
8091 void LoopVectorizationPlanner::executePlan(InnerLoopVectorizer &ILV,
8092                                            DominatorTree *DT) {
8093   // Perform the actual loop transformation.
8094 
8095   // 1. Create a new empty loop. Unlink the old loop and connect the new one.
8096   assert(BestVF.hasValue() && "Vectorization Factor is missing");
8097   assert(VPlans.size() == 1 && "Not a single VPlan to execute.");
8098 
8099   VPTransformState State{
8100       *BestVF, BestUF, LI, DT, ILV.Builder, &ILV, VPlans.front().get()};
8101   State.CFG.PrevBB = ILV.createVectorizedLoopSkeleton();
8102   State.TripCount = ILV.getOrCreateTripCount(nullptr);
8103   State.CanonicalIV = ILV.Induction;
8104 
8105   ILV.printDebugTracesAtStart();
8106 
8107   //===------------------------------------------------===//
8108   //
8109   // Notice: any optimization or new instruction that go
8110   // into the code below should also be implemented in
8111   // the cost-model.
8112   //
8113   //===------------------------------------------------===//
8114 
8115   // 2. Copy and widen instructions from the old loop into the new loop.
8116   VPlans.front()->execute(&State);
8117 
8118   // 3. Fix the vectorized code: take care of header phi's, live-outs,
8119   //    predication, updating analyses.
8120   ILV.fixVectorizedLoop(State);
8121 
8122   ILV.printDebugTracesAtEnd();
8123 }
8124 
8125 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
8126 void LoopVectorizationPlanner::printPlans(raw_ostream &O) {
8127   for (const auto &Plan : VPlans)
8128     if (PrintVPlansInDotFormat)
8129       Plan->printDOT(O);
8130     else
8131       Plan->print(O);
8132 }
8133 #endif
8134 
8135 void LoopVectorizationPlanner::collectTriviallyDeadInstructions(
8136     SmallPtrSetImpl<Instruction *> &DeadInstructions) {
8137 
8138   // We create new control-flow for the vectorized loop, so the original exit
8139   // conditions will be dead after vectorization if it's only used by the
8140   // terminator
8141   SmallVector<BasicBlock*> ExitingBlocks;
8142   OrigLoop->getExitingBlocks(ExitingBlocks);
8143   for (auto *BB : ExitingBlocks) {
8144     auto *Cmp = dyn_cast<Instruction>(BB->getTerminator()->getOperand(0));
8145     if (!Cmp || !Cmp->hasOneUse())
8146       continue;
8147 
8148     // TODO: we should introduce a getUniqueExitingBlocks on Loop
8149     if (!DeadInstructions.insert(Cmp).second)
8150       continue;
8151 
8152     // The operands of the icmp is often a dead trunc, used by IndUpdate.
8153     // TODO: can recurse through operands in general
8154     for (Value *Op : Cmp->operands()) {
8155       if (isa<TruncInst>(Op) && Op->hasOneUse())
8156           DeadInstructions.insert(cast<Instruction>(Op));
8157     }
8158   }
8159 
8160   // We create new "steps" for induction variable updates to which the original
8161   // induction variables map. An original update instruction will be dead if
8162   // all its users except the induction variable are dead.
8163   auto *Latch = OrigLoop->getLoopLatch();
8164   for (auto &Induction : Legal->getInductionVars()) {
8165     PHINode *Ind = Induction.first;
8166     auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
8167 
8168     // If the tail is to be folded by masking, the primary induction variable,
8169     // if exists, isn't dead: it will be used for masking. Don't kill it.
8170     if (CM.foldTailByMasking() && IndUpdate == Legal->getPrimaryInduction())
8171       continue;
8172 
8173     if (llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
8174           return U == Ind || DeadInstructions.count(cast<Instruction>(U));
8175         }))
8176       DeadInstructions.insert(IndUpdate);
8177 
8178     // We record as "Dead" also the type-casting instructions we had identified
8179     // during induction analysis. We don't need any handling for them in the
8180     // vectorized loop because we have proven that, under a proper runtime
8181     // test guarding the vectorized loop, the value of the phi, and the casted
8182     // value of the phi, are the same. The last instruction in this casting chain
8183     // will get its scalar/vector/widened def from the scalar/vector/widened def
8184     // of the respective phi node. Any other casts in the induction def-use chain
8185     // have no other uses outside the phi update chain, and will be ignored.
8186     InductionDescriptor &IndDes = Induction.second;
8187     const SmallVectorImpl<Instruction *> &Casts = IndDes.getCastInsts();
8188     DeadInstructions.insert(Casts.begin(), Casts.end());
8189   }
8190 }
8191 
8192 Value *InnerLoopUnroller::reverseVector(Value *Vec) { return Vec; }
8193 
8194 Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) { return V; }
8195 
8196 Value *InnerLoopUnroller::getStepVector(Value *Val, int StartIdx, Value *Step,
8197                                         Instruction::BinaryOps BinOp) {
8198   // When unrolling and the VF is 1, we only need to add a simple scalar.
8199   Type *Ty = Val->getType();
8200   assert(!Ty->isVectorTy() && "Val must be a scalar");
8201 
8202   if (Ty->isFloatingPointTy()) {
8203     Constant *C = ConstantFP::get(Ty, (double)StartIdx);
8204 
8205     // Floating-point operations inherit FMF via the builder's flags.
8206     Value *MulOp = Builder.CreateFMul(C, Step);
8207     return Builder.CreateBinOp(BinOp, Val, MulOp);
8208   }
8209   Constant *C = ConstantInt::get(Ty, StartIdx);
8210   return Builder.CreateAdd(Val, Builder.CreateMul(C, Step), "induction");
8211 }
8212 
8213 static void AddRuntimeUnrollDisableMetaData(Loop *L) {
8214   SmallVector<Metadata *, 4> MDs;
8215   // Reserve first location for self reference to the LoopID metadata node.
8216   MDs.push_back(nullptr);
8217   bool IsUnrollMetadata = false;
8218   MDNode *LoopID = L->getLoopID();
8219   if (LoopID) {
8220     // First find existing loop unrolling disable metadata.
8221     for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
8222       auto *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
8223       if (MD) {
8224         const auto *S = dyn_cast<MDString>(MD->getOperand(0));
8225         IsUnrollMetadata =
8226             S && S->getString().startswith("llvm.loop.unroll.disable");
8227       }
8228       MDs.push_back(LoopID->getOperand(i));
8229     }
8230   }
8231 
8232   if (!IsUnrollMetadata) {
8233     // Add runtime unroll disable metadata.
8234     LLVMContext &Context = L->getHeader()->getContext();
8235     SmallVector<Metadata *, 1> DisableOperands;
8236     DisableOperands.push_back(
8237         MDString::get(Context, "llvm.loop.unroll.runtime.disable"));
8238     MDNode *DisableNode = MDNode::get(Context, DisableOperands);
8239     MDs.push_back(DisableNode);
8240     MDNode *NewLoopID = MDNode::get(Context, MDs);
8241     // Set operand 0 to refer to the loop id itself.
8242     NewLoopID->replaceOperandWith(0, NewLoopID);
8243     L->setLoopID(NewLoopID);
8244   }
8245 }
8246 
8247 //===--------------------------------------------------------------------===//
8248 // EpilogueVectorizerMainLoop
8249 //===--------------------------------------------------------------------===//
8250 
8251 /// This function is partially responsible for generating the control flow
8252 /// depicted in https://llvm.org/docs/Vectorizers.html#epilogue-vectorization.
8253 BasicBlock *EpilogueVectorizerMainLoop::createEpilogueVectorizedLoopSkeleton() {
8254   MDNode *OrigLoopID = OrigLoop->getLoopID();
8255   Loop *Lp = createVectorLoopSkeleton("");
8256 
8257   // Generate the code to check the minimum iteration count of the vector
8258   // epilogue (see below).
8259   EPI.EpilogueIterationCountCheck =
8260       emitMinimumIterationCountCheck(Lp, LoopScalarPreHeader, true);
8261   EPI.EpilogueIterationCountCheck->setName("iter.check");
8262 
8263   // Generate the code to check any assumptions that we've made for SCEV
8264   // expressions.
8265   EPI.SCEVSafetyCheck = emitSCEVChecks(Lp, LoopScalarPreHeader);
8266 
8267   // Generate the code that checks at runtime if arrays overlap. We put the
8268   // checks into a separate block to make the more common case of few elements
8269   // faster.
8270   EPI.MemSafetyCheck = emitMemRuntimeChecks(Lp, LoopScalarPreHeader);
8271 
8272   // Generate the iteration count check for the main loop, *after* the check
8273   // for the epilogue loop, so that the path-length is shorter for the case
8274   // that goes directly through the vector epilogue. The longer-path length for
8275   // the main loop is compensated for, by the gain from vectorizing the larger
8276   // trip count. Note: the branch will get updated later on when we vectorize
8277   // the epilogue.
8278   EPI.MainLoopIterationCountCheck =
8279       emitMinimumIterationCountCheck(Lp, LoopScalarPreHeader, false);
8280 
8281   // Generate the induction variable.
8282   OldInduction = Legal->getPrimaryInduction();
8283   Type *IdxTy = Legal->getWidestInductionType();
8284   Value *StartIdx = ConstantInt::get(IdxTy, 0);
8285   Constant *Step = ConstantInt::get(IdxTy, VF.getKnownMinValue() * UF);
8286   Value *CountRoundDown = getOrCreateVectorTripCount(Lp);
8287   EPI.VectorTripCount = CountRoundDown;
8288   Induction =
8289       createInductionVariable(Lp, StartIdx, CountRoundDown, Step,
8290                               getDebugLocFromInstOrOperands(OldInduction));
8291 
8292   // Skip induction resume value creation here because they will be created in
8293   // the second pass. If we created them here, they wouldn't be used anyway,
8294   // because the vplan in the second pass still contains the inductions from the
8295   // original loop.
8296 
8297   return completeLoopSkeleton(Lp, OrigLoopID);
8298 }
8299 
8300 void EpilogueVectorizerMainLoop::printDebugTracesAtStart() {
8301   LLVM_DEBUG({
8302     dbgs() << "Create Skeleton for epilogue vectorized loop (first pass)\n"
8303            << "Main Loop VF:" << EPI.MainLoopVF.getKnownMinValue()
8304            << ", Main Loop UF:" << EPI.MainLoopUF
8305            << ", Epilogue Loop VF:" << EPI.EpilogueVF.getKnownMinValue()
8306            << ", Epilogue Loop UF:" << EPI.EpilogueUF << "\n";
8307   });
8308 }
8309 
8310 void EpilogueVectorizerMainLoop::printDebugTracesAtEnd() {
8311   DEBUG_WITH_TYPE(VerboseDebug, {
8312     dbgs() << "intermediate fn:\n" << *Induction->getFunction() << "\n";
8313   });
8314 }
8315 
8316 BasicBlock *EpilogueVectorizerMainLoop::emitMinimumIterationCountCheck(
8317     Loop *L, BasicBlock *Bypass, bool ForEpilogue) {
8318   assert(L && "Expected valid Loop.");
8319   assert(Bypass && "Expected valid bypass basic block.");
8320   unsigned VFactor =
8321       ForEpilogue ? EPI.EpilogueVF.getKnownMinValue() : VF.getKnownMinValue();
8322   unsigned UFactor = ForEpilogue ? EPI.EpilogueUF : UF;
8323   Value *Count = getOrCreateTripCount(L);
8324   // Reuse existing vector loop preheader for TC checks.
8325   // Note that new preheader block is generated for vector loop.
8326   BasicBlock *const TCCheckBlock = LoopVectorPreHeader;
8327   IRBuilder<> Builder(TCCheckBlock->getTerminator());
8328 
8329   // Generate code to check if the loop's trip count is less than VF * UF of the
8330   // main vector loop.
8331   auto P = Cost->requiresScalarEpilogue(ForEpilogue ? EPI.EpilogueVF : VF) ?
8332       ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT;
8333 
8334   Value *CheckMinIters = Builder.CreateICmp(
8335       P, Count, ConstantInt::get(Count->getType(), VFactor * UFactor),
8336       "min.iters.check");
8337 
8338   if (!ForEpilogue)
8339     TCCheckBlock->setName("vector.main.loop.iter.check");
8340 
8341   // Create new preheader for vector loop.
8342   LoopVectorPreHeader = SplitBlock(TCCheckBlock, TCCheckBlock->getTerminator(),
8343                                    DT, LI, nullptr, "vector.ph");
8344 
8345   if (ForEpilogue) {
8346     assert(DT->properlyDominates(DT->getNode(TCCheckBlock),
8347                                  DT->getNode(Bypass)->getIDom()) &&
8348            "TC check is expected to dominate Bypass");
8349 
8350     // Update dominator for Bypass & LoopExit.
8351     DT->changeImmediateDominator(Bypass, TCCheckBlock);
8352     if (!Cost->requiresScalarEpilogue(EPI.EpilogueVF))
8353       // For loops with multiple exits, there's no edge from the middle block
8354       // to exit blocks (as the epilogue must run) and thus no need to update
8355       // the immediate dominator of the exit blocks.
8356       DT->changeImmediateDominator(LoopExitBlock, TCCheckBlock);
8357 
8358     LoopBypassBlocks.push_back(TCCheckBlock);
8359 
8360     // Save the trip count so we don't have to regenerate it in the
8361     // vec.epilog.iter.check. This is safe to do because the trip count
8362     // generated here dominates the vector epilog iter check.
8363     EPI.TripCount = Count;
8364   }
8365 
8366   ReplaceInstWithInst(
8367       TCCheckBlock->getTerminator(),
8368       BranchInst::Create(Bypass, LoopVectorPreHeader, CheckMinIters));
8369 
8370   return TCCheckBlock;
8371 }
8372 
8373 //===--------------------------------------------------------------------===//
8374 // EpilogueVectorizerEpilogueLoop
8375 //===--------------------------------------------------------------------===//
8376 
8377 /// This function is partially responsible for generating the control flow
8378 /// depicted in https://llvm.org/docs/Vectorizers.html#epilogue-vectorization.
8379 BasicBlock *
8380 EpilogueVectorizerEpilogueLoop::createEpilogueVectorizedLoopSkeleton() {
8381   MDNode *OrigLoopID = OrigLoop->getLoopID();
8382   Loop *Lp = createVectorLoopSkeleton("vec.epilog.");
8383 
8384   // Now, compare the remaining count and if there aren't enough iterations to
8385   // execute the vectorized epilogue skip to the scalar part.
8386   BasicBlock *VecEpilogueIterationCountCheck = LoopVectorPreHeader;
8387   VecEpilogueIterationCountCheck->setName("vec.epilog.iter.check");
8388   LoopVectorPreHeader =
8389       SplitBlock(LoopVectorPreHeader, LoopVectorPreHeader->getTerminator(), DT,
8390                  LI, nullptr, "vec.epilog.ph");
8391   emitMinimumVectorEpilogueIterCountCheck(Lp, LoopScalarPreHeader,
8392                                           VecEpilogueIterationCountCheck);
8393 
8394   // Adjust the control flow taking the state info from the main loop
8395   // vectorization into account.
8396   assert(EPI.MainLoopIterationCountCheck && EPI.EpilogueIterationCountCheck &&
8397          "expected this to be saved from the previous pass.");
8398   EPI.MainLoopIterationCountCheck->getTerminator()->replaceUsesOfWith(
8399       VecEpilogueIterationCountCheck, LoopVectorPreHeader);
8400 
8401   DT->changeImmediateDominator(LoopVectorPreHeader,
8402                                EPI.MainLoopIterationCountCheck);
8403 
8404   EPI.EpilogueIterationCountCheck->getTerminator()->replaceUsesOfWith(
8405       VecEpilogueIterationCountCheck, LoopScalarPreHeader);
8406 
8407   if (EPI.SCEVSafetyCheck)
8408     EPI.SCEVSafetyCheck->getTerminator()->replaceUsesOfWith(
8409         VecEpilogueIterationCountCheck, LoopScalarPreHeader);
8410   if (EPI.MemSafetyCheck)
8411     EPI.MemSafetyCheck->getTerminator()->replaceUsesOfWith(
8412         VecEpilogueIterationCountCheck, LoopScalarPreHeader);
8413 
8414   DT->changeImmediateDominator(
8415       VecEpilogueIterationCountCheck,
8416       VecEpilogueIterationCountCheck->getSinglePredecessor());
8417 
8418   DT->changeImmediateDominator(LoopScalarPreHeader,
8419                                EPI.EpilogueIterationCountCheck);
8420   if (!Cost->requiresScalarEpilogue(EPI.EpilogueVF))
8421     // If there is an epilogue which must run, there's no edge from the
8422     // middle block to exit blocks  and thus no need to update the immediate
8423     // dominator of the exit blocks.
8424     DT->changeImmediateDominator(LoopExitBlock,
8425                                  EPI.EpilogueIterationCountCheck);
8426 
8427   // Keep track of bypass blocks, as they feed start values to the induction
8428   // phis in the scalar loop preheader.
8429   if (EPI.SCEVSafetyCheck)
8430     LoopBypassBlocks.push_back(EPI.SCEVSafetyCheck);
8431   if (EPI.MemSafetyCheck)
8432     LoopBypassBlocks.push_back(EPI.MemSafetyCheck);
8433   LoopBypassBlocks.push_back(EPI.EpilogueIterationCountCheck);
8434 
8435   // Generate a resume induction for the vector epilogue and put it in the
8436   // vector epilogue preheader
8437   Type *IdxTy = Legal->getWidestInductionType();
8438   PHINode *EPResumeVal = PHINode::Create(IdxTy, 2, "vec.epilog.resume.val",
8439                                          LoopVectorPreHeader->getFirstNonPHI());
8440   EPResumeVal->addIncoming(EPI.VectorTripCount, VecEpilogueIterationCountCheck);
8441   EPResumeVal->addIncoming(ConstantInt::get(IdxTy, 0),
8442                            EPI.MainLoopIterationCountCheck);
8443 
8444   // Generate the induction variable.
8445   OldInduction = Legal->getPrimaryInduction();
8446   Value *CountRoundDown = getOrCreateVectorTripCount(Lp);
8447   Constant *Step = ConstantInt::get(IdxTy, VF.getKnownMinValue() * UF);
8448   Value *StartIdx = EPResumeVal;
8449   Induction =
8450       createInductionVariable(Lp, StartIdx, CountRoundDown, Step,
8451                               getDebugLocFromInstOrOperands(OldInduction));
8452 
8453   // Generate induction resume values. These variables save the new starting
8454   // indexes for the scalar loop. They are used to test if there are any tail
8455   // iterations left once the vector loop has completed.
8456   // Note that when the vectorized epilogue is skipped due to iteration count
8457   // check, then the resume value for the induction variable comes from
8458   // the trip count of the main vector loop, hence passing the AdditionalBypass
8459   // argument.
8460   createInductionResumeValues(Lp, CountRoundDown,
8461                               {VecEpilogueIterationCountCheck,
8462                                EPI.VectorTripCount} /* AdditionalBypass */);
8463 
8464   AddRuntimeUnrollDisableMetaData(Lp);
8465   return completeLoopSkeleton(Lp, OrigLoopID);
8466 }
8467 
8468 BasicBlock *
8469 EpilogueVectorizerEpilogueLoop::emitMinimumVectorEpilogueIterCountCheck(
8470     Loop *L, BasicBlock *Bypass, BasicBlock *Insert) {
8471 
8472   assert(EPI.TripCount &&
8473          "Expected trip count to have been safed in the first pass.");
8474   assert(
8475       (!isa<Instruction>(EPI.TripCount) ||
8476        DT->dominates(cast<Instruction>(EPI.TripCount)->getParent(), Insert)) &&
8477       "saved trip count does not dominate insertion point.");
8478   Value *TC = EPI.TripCount;
8479   IRBuilder<> Builder(Insert->getTerminator());
8480   Value *Count = Builder.CreateSub(TC, EPI.VectorTripCount, "n.vec.remaining");
8481 
8482   // Generate code to check if the loop's trip count is less than VF * UF of the
8483   // vector epilogue loop.
8484   auto P = Cost->requiresScalarEpilogue(EPI.EpilogueVF) ?
8485       ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT;
8486 
8487   Value *CheckMinIters = Builder.CreateICmp(
8488       P, Count,
8489       ConstantInt::get(Count->getType(),
8490                        EPI.EpilogueVF.getKnownMinValue() * EPI.EpilogueUF),
8491       "min.epilog.iters.check");
8492 
8493   ReplaceInstWithInst(
8494       Insert->getTerminator(),
8495       BranchInst::Create(Bypass, LoopVectorPreHeader, CheckMinIters));
8496 
8497   LoopBypassBlocks.push_back(Insert);
8498   return Insert;
8499 }
8500 
8501 void EpilogueVectorizerEpilogueLoop::printDebugTracesAtStart() {
8502   LLVM_DEBUG({
8503     dbgs() << "Create Skeleton for epilogue vectorized loop (second pass)\n"
8504            << "Epilogue Loop VF:" << EPI.EpilogueVF.getKnownMinValue()
8505            << ", Epilogue Loop UF:" << EPI.EpilogueUF << "\n";
8506   });
8507 }
8508 
8509 void EpilogueVectorizerEpilogueLoop::printDebugTracesAtEnd() {
8510   DEBUG_WITH_TYPE(VerboseDebug, {
8511     dbgs() << "final fn:\n" << *Induction->getFunction() << "\n";
8512   });
8513 }
8514 
8515 bool LoopVectorizationPlanner::getDecisionAndClampRange(
8516     const std::function<bool(ElementCount)> &Predicate, VFRange &Range) {
8517   assert(!Range.isEmpty() && "Trying to test an empty VF range.");
8518   bool PredicateAtRangeStart = Predicate(Range.Start);
8519 
8520   for (ElementCount TmpVF = Range.Start * 2;
8521        ElementCount::isKnownLT(TmpVF, Range.End); TmpVF *= 2)
8522     if (Predicate(TmpVF) != PredicateAtRangeStart) {
8523       Range.End = TmpVF;
8524       break;
8525     }
8526 
8527   return PredicateAtRangeStart;
8528 }
8529 
8530 /// Build VPlans for the full range of feasible VF's = {\p MinVF, 2 * \p MinVF,
8531 /// 4 * \p MinVF, ..., \p MaxVF} by repeatedly building a VPlan for a sub-range
8532 /// of VF's starting at a given VF and extending it as much as possible. Each
8533 /// vectorization decision can potentially shorten this sub-range during
8534 /// buildVPlan().
8535 void LoopVectorizationPlanner::buildVPlans(ElementCount MinVF,
8536                                            ElementCount MaxVF) {
8537   auto MaxVFPlusOne = MaxVF.getWithIncrement(1);
8538   for (ElementCount VF = MinVF; ElementCount::isKnownLT(VF, MaxVFPlusOne);) {
8539     VFRange SubRange = {VF, MaxVFPlusOne};
8540     VPlans.push_back(buildVPlan(SubRange));
8541     VF = SubRange.End;
8542   }
8543 }
8544 
8545 VPValue *VPRecipeBuilder::createEdgeMask(BasicBlock *Src, BasicBlock *Dst,
8546                                          VPlanPtr &Plan) {
8547   assert(is_contained(predecessors(Dst), Src) && "Invalid edge");
8548 
8549   // Look for cached value.
8550   std::pair<BasicBlock *, BasicBlock *> Edge(Src, Dst);
8551   EdgeMaskCacheTy::iterator ECEntryIt = EdgeMaskCache.find(Edge);
8552   if (ECEntryIt != EdgeMaskCache.end())
8553     return ECEntryIt->second;
8554 
8555   VPValue *SrcMask = createBlockInMask(Src, Plan);
8556 
8557   // The terminator has to be a branch inst!
8558   BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
8559   assert(BI && "Unexpected terminator found");
8560 
8561   if (!BI->isConditional() || BI->getSuccessor(0) == BI->getSuccessor(1))
8562     return EdgeMaskCache[Edge] = SrcMask;
8563 
8564   // If source is an exiting block, we know the exit edge is dynamically dead
8565   // in the vector loop, and thus we don't need to restrict the mask.  Avoid
8566   // adding uses of an otherwise potentially dead instruction.
8567   if (OrigLoop->isLoopExiting(Src))
8568     return EdgeMaskCache[Edge] = SrcMask;
8569 
8570   VPValue *EdgeMask = Plan->getOrAddVPValue(BI->getCondition());
8571   assert(EdgeMask && "No Edge Mask found for condition");
8572 
8573   if (BI->getSuccessor(0) != Dst)
8574     EdgeMask = Builder.createNot(EdgeMask);
8575 
8576   if (SrcMask) { // Otherwise block in-mask is all-one, no need to AND.
8577     // The condition is 'SrcMask && EdgeMask', which is equivalent to
8578     // 'select i1 SrcMask, i1 EdgeMask, i1 false'.
8579     // The select version does not introduce new UB if SrcMask is false and
8580     // EdgeMask is poison. Using 'and' here introduces undefined behavior.
8581     VPValue *False = Plan->getOrAddVPValue(
8582         ConstantInt::getFalse(BI->getCondition()->getType()));
8583     EdgeMask = Builder.createSelect(SrcMask, EdgeMask, False);
8584   }
8585 
8586   return EdgeMaskCache[Edge] = EdgeMask;
8587 }
8588 
8589 VPValue *VPRecipeBuilder::createBlockInMask(BasicBlock *BB, VPlanPtr &Plan) {
8590   assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
8591 
8592   // Look for cached value.
8593   BlockMaskCacheTy::iterator BCEntryIt = BlockMaskCache.find(BB);
8594   if (BCEntryIt != BlockMaskCache.end())
8595     return BCEntryIt->second;
8596 
8597   // All-one mask is modelled as no-mask following the convention for masked
8598   // load/store/gather/scatter. Initialize BlockMask to no-mask.
8599   VPValue *BlockMask = nullptr;
8600 
8601   if (OrigLoop->getHeader() == BB) {
8602     if (!CM.blockNeedsPredication(BB))
8603       return BlockMaskCache[BB] = BlockMask; // Loop incoming mask is all-one.
8604 
8605     // Create the block in mask as the first non-phi instruction in the block.
8606     VPBuilder::InsertPointGuard Guard(Builder);
8607     auto NewInsertionPoint = Builder.getInsertBlock()->getFirstNonPhi();
8608     Builder.setInsertPoint(Builder.getInsertBlock(), NewInsertionPoint);
8609 
8610     // Introduce the early-exit compare IV <= BTC to form header block mask.
8611     // This is used instead of IV < TC because TC may wrap, unlike BTC.
8612     // Start by constructing the desired canonical IV.
8613     VPValue *IV = nullptr;
8614     if (Legal->getPrimaryInduction())
8615       IV = Plan->getOrAddVPValue(Legal->getPrimaryInduction());
8616     else {
8617       auto IVRecipe = new VPWidenCanonicalIVRecipe();
8618       Builder.getInsertBlock()->insert(IVRecipe, NewInsertionPoint);
8619       IV = IVRecipe->getVPSingleValue();
8620     }
8621     VPValue *BTC = Plan->getOrCreateBackedgeTakenCount();
8622     bool TailFolded = !CM.isScalarEpilogueAllowed();
8623 
8624     if (TailFolded && CM.TTI.emitGetActiveLaneMask()) {
8625       // While ActiveLaneMask is a binary op that consumes the loop tripcount
8626       // as a second argument, we only pass the IV here and extract the
8627       // tripcount from the transform state where codegen of the VP instructions
8628       // happen.
8629       BlockMask = Builder.createNaryOp(VPInstruction::ActiveLaneMask, {IV});
8630     } else {
8631       BlockMask = Builder.createNaryOp(VPInstruction::ICmpULE, {IV, BTC});
8632     }
8633     return BlockMaskCache[BB] = BlockMask;
8634   }
8635 
8636   // This is the block mask. We OR all incoming edges.
8637   for (auto *Predecessor : predecessors(BB)) {
8638     VPValue *EdgeMask = createEdgeMask(Predecessor, BB, Plan);
8639     if (!EdgeMask) // Mask of predecessor is all-one so mask of block is too.
8640       return BlockMaskCache[BB] = EdgeMask;
8641 
8642     if (!BlockMask) { // BlockMask has its initialized nullptr value.
8643       BlockMask = EdgeMask;
8644       continue;
8645     }
8646 
8647     BlockMask = Builder.createOr(BlockMask, EdgeMask);
8648   }
8649 
8650   return BlockMaskCache[BB] = BlockMask;
8651 }
8652 
8653 VPRecipeBase *VPRecipeBuilder::tryToWidenMemory(Instruction *I,
8654                                                 ArrayRef<VPValue *> Operands,
8655                                                 VFRange &Range,
8656                                                 VPlanPtr &Plan) {
8657   assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
8658          "Must be called with either a load or store");
8659 
8660   auto willWiden = [&](ElementCount VF) -> bool {
8661     if (VF.isScalar())
8662       return false;
8663     LoopVectorizationCostModel::InstWidening Decision =
8664         CM.getWideningDecision(I, VF);
8665     assert(Decision != LoopVectorizationCostModel::CM_Unknown &&
8666            "CM decision should be taken at this point.");
8667     if (Decision == LoopVectorizationCostModel::CM_Interleave)
8668       return true;
8669     if (CM.isScalarAfterVectorization(I, VF) ||
8670         CM.isProfitableToScalarize(I, VF))
8671       return false;
8672     return Decision != LoopVectorizationCostModel::CM_Scalarize;
8673   };
8674 
8675   if (!LoopVectorizationPlanner::getDecisionAndClampRange(willWiden, Range))
8676     return nullptr;
8677 
8678   VPValue *Mask = nullptr;
8679   if (Legal->isMaskRequired(I))
8680     Mask = createBlockInMask(I->getParent(), Plan);
8681 
8682   if (LoadInst *Load = dyn_cast<LoadInst>(I))
8683     return new VPWidenMemoryInstructionRecipe(*Load, Operands[0], Mask);
8684 
8685   StoreInst *Store = cast<StoreInst>(I);
8686   return new VPWidenMemoryInstructionRecipe(*Store, Operands[1], Operands[0],
8687                                             Mask);
8688 }
8689 
8690 VPWidenIntOrFpInductionRecipe *
8691 VPRecipeBuilder::tryToOptimizeInductionPHI(PHINode *Phi,
8692                                            ArrayRef<VPValue *> Operands) const {
8693   // Check if this is an integer or fp induction. If so, build the recipe that
8694   // produces its scalar and vector values.
8695   InductionDescriptor II = Legal->getInductionVars().lookup(Phi);
8696   if (II.getKind() == InductionDescriptor::IK_IntInduction ||
8697       II.getKind() == InductionDescriptor::IK_FpInduction) {
8698     assert(II.getStartValue() ==
8699            Phi->getIncomingValueForBlock(OrigLoop->getLoopPreheader()));
8700     const SmallVectorImpl<Instruction *> &Casts = II.getCastInsts();
8701     return new VPWidenIntOrFpInductionRecipe(
8702         Phi, Operands[0], Casts.empty() ? nullptr : Casts.front());
8703   }
8704 
8705   return nullptr;
8706 }
8707 
8708 VPWidenIntOrFpInductionRecipe *VPRecipeBuilder::tryToOptimizeInductionTruncate(
8709     TruncInst *I, ArrayRef<VPValue *> Operands, VFRange &Range,
8710     VPlan &Plan) const {
8711   // Optimize the special case where the source is a constant integer
8712   // induction variable. Notice that we can only optimize the 'trunc' case
8713   // because (a) FP conversions lose precision, (b) sext/zext may wrap, and
8714   // (c) other casts depend on pointer size.
8715 
8716   // Determine whether \p K is a truncation based on an induction variable that
8717   // can be optimized.
8718   auto isOptimizableIVTruncate =
8719       [&](Instruction *K) -> std::function<bool(ElementCount)> {
8720     return [=](ElementCount VF) -> bool {
8721       return CM.isOptimizableIVTruncate(K, VF);
8722     };
8723   };
8724 
8725   if (LoopVectorizationPlanner::getDecisionAndClampRange(
8726           isOptimizableIVTruncate(I), Range)) {
8727 
8728     InductionDescriptor II =
8729         Legal->getInductionVars().lookup(cast<PHINode>(I->getOperand(0)));
8730     VPValue *Start = Plan.getOrAddVPValue(II.getStartValue());
8731     return new VPWidenIntOrFpInductionRecipe(cast<PHINode>(I->getOperand(0)),
8732                                              Start, nullptr, I);
8733   }
8734   return nullptr;
8735 }
8736 
8737 VPRecipeOrVPValueTy VPRecipeBuilder::tryToBlend(PHINode *Phi,
8738                                                 ArrayRef<VPValue *> Operands,
8739                                                 VPlanPtr &Plan) {
8740   // If all incoming values are equal, the incoming VPValue can be used directly
8741   // instead of creating a new VPBlendRecipe.
8742   VPValue *FirstIncoming = Operands[0];
8743   if (all_of(Operands, [FirstIncoming](const VPValue *Inc) {
8744         return FirstIncoming == Inc;
8745       })) {
8746     return Operands[0];
8747   }
8748 
8749   // We know that all PHIs in non-header blocks are converted into selects, so
8750   // we don't have to worry about the insertion order and we can just use the
8751   // builder. At this point we generate the predication tree. There may be
8752   // duplications since this is a simple recursive scan, but future
8753   // optimizations will clean it up.
8754   SmallVector<VPValue *, 2> OperandsWithMask;
8755   unsigned NumIncoming = Phi->getNumIncomingValues();
8756 
8757   for (unsigned In = 0; In < NumIncoming; In++) {
8758     VPValue *EdgeMask =
8759       createEdgeMask(Phi->getIncomingBlock(In), Phi->getParent(), Plan);
8760     assert((EdgeMask || NumIncoming == 1) &&
8761            "Multiple predecessors with one having a full mask");
8762     OperandsWithMask.push_back(Operands[In]);
8763     if (EdgeMask)
8764       OperandsWithMask.push_back(EdgeMask);
8765   }
8766   return toVPRecipeResult(new VPBlendRecipe(Phi, OperandsWithMask));
8767 }
8768 
8769 VPWidenCallRecipe *VPRecipeBuilder::tryToWidenCall(CallInst *CI,
8770                                                    ArrayRef<VPValue *> Operands,
8771                                                    VFRange &Range) const {
8772 
8773   bool IsPredicated = LoopVectorizationPlanner::getDecisionAndClampRange(
8774       [this, CI](ElementCount VF) { return CM.isScalarWithPredication(CI); },
8775       Range);
8776 
8777   if (IsPredicated)
8778     return nullptr;
8779 
8780   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
8781   if (ID && (ID == Intrinsic::assume || ID == Intrinsic::lifetime_end ||
8782              ID == Intrinsic::lifetime_start || ID == Intrinsic::sideeffect ||
8783              ID == Intrinsic::pseudoprobe ||
8784              ID == Intrinsic::experimental_noalias_scope_decl))
8785     return nullptr;
8786 
8787   auto willWiden = [&](ElementCount VF) -> bool {
8788     Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
8789     // The following case may be scalarized depending on the VF.
8790     // The flag shows whether we use Intrinsic or a usual Call for vectorized
8791     // version of the instruction.
8792     // Is it beneficial to perform intrinsic call compared to lib call?
8793     bool NeedToScalarize = false;
8794     InstructionCost CallCost = CM.getVectorCallCost(CI, VF, NeedToScalarize);
8795     InstructionCost IntrinsicCost = ID ? CM.getVectorIntrinsicCost(CI, VF) : 0;
8796     bool UseVectorIntrinsic = ID && IntrinsicCost <= CallCost;
8797     assert((IntrinsicCost.isValid() || CallCost.isValid()) &&
8798            "Either the intrinsic cost or vector call cost must be valid");
8799     return UseVectorIntrinsic || !NeedToScalarize;
8800   };
8801 
8802   if (!LoopVectorizationPlanner::getDecisionAndClampRange(willWiden, Range))
8803     return nullptr;
8804 
8805   ArrayRef<VPValue *> Ops = Operands.take_front(CI->getNumArgOperands());
8806   return new VPWidenCallRecipe(*CI, make_range(Ops.begin(), Ops.end()));
8807 }
8808 
8809 bool VPRecipeBuilder::shouldWiden(Instruction *I, VFRange &Range) const {
8810   assert(!isa<BranchInst>(I) && !isa<PHINode>(I) && !isa<LoadInst>(I) &&
8811          !isa<StoreInst>(I) && "Instruction should have been handled earlier");
8812   // Instruction should be widened, unless it is scalar after vectorization,
8813   // scalarization is profitable or it is predicated.
8814   auto WillScalarize = [this, I](ElementCount VF) -> bool {
8815     return CM.isScalarAfterVectorization(I, VF) ||
8816            CM.isProfitableToScalarize(I, VF) || CM.isScalarWithPredication(I);
8817   };
8818   return !LoopVectorizationPlanner::getDecisionAndClampRange(WillScalarize,
8819                                                              Range);
8820 }
8821 
8822 VPWidenRecipe *VPRecipeBuilder::tryToWiden(Instruction *I,
8823                                            ArrayRef<VPValue *> Operands) const {
8824   auto IsVectorizableOpcode = [](unsigned Opcode) {
8825     switch (Opcode) {
8826     case Instruction::Add:
8827     case Instruction::And:
8828     case Instruction::AShr:
8829     case Instruction::BitCast:
8830     case Instruction::FAdd:
8831     case Instruction::FCmp:
8832     case Instruction::FDiv:
8833     case Instruction::FMul:
8834     case Instruction::FNeg:
8835     case Instruction::FPExt:
8836     case Instruction::FPToSI:
8837     case Instruction::FPToUI:
8838     case Instruction::FPTrunc:
8839     case Instruction::FRem:
8840     case Instruction::FSub:
8841     case Instruction::ICmp:
8842     case Instruction::IntToPtr:
8843     case Instruction::LShr:
8844     case Instruction::Mul:
8845     case Instruction::Or:
8846     case Instruction::PtrToInt:
8847     case Instruction::SDiv:
8848     case Instruction::Select:
8849     case Instruction::SExt:
8850     case Instruction::Shl:
8851     case Instruction::SIToFP:
8852     case Instruction::SRem:
8853     case Instruction::Sub:
8854     case Instruction::Trunc:
8855     case Instruction::UDiv:
8856     case Instruction::UIToFP:
8857     case Instruction::URem:
8858     case Instruction::Xor:
8859     case Instruction::ZExt:
8860       return true;
8861     }
8862     return false;
8863   };
8864 
8865   if (!IsVectorizableOpcode(I->getOpcode()))
8866     return nullptr;
8867 
8868   // Success: widen this instruction.
8869   return new VPWidenRecipe(*I, make_range(Operands.begin(), Operands.end()));
8870 }
8871 
8872 void VPRecipeBuilder::fixHeaderPhis() {
8873   BasicBlock *OrigLatch = OrigLoop->getLoopLatch();
8874   for (VPWidenPHIRecipe *R : PhisToFix) {
8875     auto *PN = cast<PHINode>(R->getUnderlyingValue());
8876     VPRecipeBase *IncR =
8877         getRecipe(cast<Instruction>(PN->getIncomingValueForBlock(OrigLatch)));
8878     R->addOperand(IncR->getVPSingleValue());
8879   }
8880 }
8881 
8882 VPBasicBlock *VPRecipeBuilder::handleReplication(
8883     Instruction *I, VFRange &Range, VPBasicBlock *VPBB,
8884     VPlanPtr &Plan) {
8885   bool IsUniform = LoopVectorizationPlanner::getDecisionAndClampRange(
8886       [&](ElementCount VF) { return CM.isUniformAfterVectorization(I, VF); },
8887       Range);
8888 
8889   bool IsPredicated = LoopVectorizationPlanner::getDecisionAndClampRange(
8890       [&](ElementCount VF) { return CM.isPredicatedInst(I); }, Range);
8891 
8892   auto *Recipe = new VPReplicateRecipe(I, Plan->mapToVPValues(I->operands()),
8893                                        IsUniform, IsPredicated);
8894   setRecipe(I, Recipe);
8895   Plan->addVPValue(I, Recipe);
8896 
8897   // Find if I uses a predicated instruction. If so, it will use its scalar
8898   // value. Avoid hoisting the insert-element which packs the scalar value into
8899   // a vector value, as that happens iff all users use the vector value.
8900   for (VPValue *Op : Recipe->operands()) {
8901     auto *PredR = dyn_cast_or_null<VPPredInstPHIRecipe>(Op->getDef());
8902     if (!PredR)
8903       continue;
8904     auto *RepR =
8905         cast_or_null<VPReplicateRecipe>(PredR->getOperand(0)->getDef());
8906     assert(RepR->isPredicated() &&
8907            "expected Replicate recipe to be predicated");
8908     RepR->setAlsoPack(false);
8909   }
8910 
8911   // Finalize the recipe for Instr, first if it is not predicated.
8912   if (!IsPredicated) {
8913     LLVM_DEBUG(dbgs() << "LV: Scalarizing:" << *I << "\n");
8914     VPBB->appendRecipe(Recipe);
8915     return VPBB;
8916   }
8917   LLVM_DEBUG(dbgs() << "LV: Scalarizing and predicating:" << *I << "\n");
8918   assert(VPBB->getSuccessors().empty() &&
8919          "VPBB has successors when handling predicated replication.");
8920   // Record predicated instructions for above packing optimizations.
8921   VPBlockBase *Region = createReplicateRegion(I, Recipe, Plan);
8922   VPBlockUtils::insertBlockAfter(Region, VPBB);
8923   auto *RegSucc = new VPBasicBlock();
8924   VPBlockUtils::insertBlockAfter(RegSucc, Region);
8925   return RegSucc;
8926 }
8927 
8928 VPRegionBlock *VPRecipeBuilder::createReplicateRegion(Instruction *Instr,
8929                                                       VPRecipeBase *PredRecipe,
8930                                                       VPlanPtr &Plan) {
8931   // Instructions marked for predication are replicated and placed under an
8932   // if-then construct to prevent side-effects.
8933 
8934   // Generate recipes to compute the block mask for this region.
8935   VPValue *BlockInMask = createBlockInMask(Instr->getParent(), Plan);
8936 
8937   // Build the triangular if-then region.
8938   std::string RegionName = (Twine("pred.") + Instr->getOpcodeName()).str();
8939   assert(Instr->getParent() && "Predicated instruction not in any basic block");
8940   auto *BOMRecipe = new VPBranchOnMaskRecipe(BlockInMask);
8941   auto *Entry = new VPBasicBlock(Twine(RegionName) + ".entry", BOMRecipe);
8942   auto *PHIRecipe = Instr->getType()->isVoidTy()
8943                         ? nullptr
8944                         : new VPPredInstPHIRecipe(Plan->getOrAddVPValue(Instr));
8945   if (PHIRecipe) {
8946     Plan->removeVPValueFor(Instr);
8947     Plan->addVPValue(Instr, PHIRecipe);
8948   }
8949   auto *Exit = new VPBasicBlock(Twine(RegionName) + ".continue", PHIRecipe);
8950   auto *Pred = new VPBasicBlock(Twine(RegionName) + ".if", PredRecipe);
8951   VPRegionBlock *Region = new VPRegionBlock(Entry, Exit, RegionName, true);
8952 
8953   // Note: first set Entry as region entry and then connect successors starting
8954   // from it in order, to propagate the "parent" of each VPBasicBlock.
8955   VPBlockUtils::insertTwoBlocksAfter(Pred, Exit, BlockInMask, Entry);
8956   VPBlockUtils::connectBlocks(Pred, Exit);
8957 
8958   return Region;
8959 }
8960 
8961 VPRecipeOrVPValueTy
8962 VPRecipeBuilder::tryToCreateWidenRecipe(Instruction *Instr,
8963                                         ArrayRef<VPValue *> Operands,
8964                                         VFRange &Range, VPlanPtr &Plan) {
8965   // First, check for specific widening recipes that deal with calls, memory
8966   // operations, inductions and Phi nodes.
8967   if (auto *CI = dyn_cast<CallInst>(Instr))
8968     return toVPRecipeResult(tryToWidenCall(CI, Operands, Range));
8969 
8970   if (isa<LoadInst>(Instr) || isa<StoreInst>(Instr))
8971     return toVPRecipeResult(tryToWidenMemory(Instr, Operands, Range, Plan));
8972 
8973   VPRecipeBase *Recipe;
8974   if (auto Phi = dyn_cast<PHINode>(Instr)) {
8975     if (Phi->getParent() != OrigLoop->getHeader())
8976       return tryToBlend(Phi, Operands, Plan);
8977     if ((Recipe = tryToOptimizeInductionPHI(Phi, Operands)))
8978       return toVPRecipeResult(Recipe);
8979 
8980     VPWidenPHIRecipe *PhiRecipe = nullptr;
8981     if (Legal->isReductionVariable(Phi) || Legal->isFirstOrderRecurrence(Phi)) {
8982       VPValue *StartV = Operands[0];
8983       if (Legal->isReductionVariable(Phi)) {
8984         RecurrenceDescriptor &RdxDesc = Legal->getReductionVars()[Phi];
8985         assert(RdxDesc.getRecurrenceStartValue() ==
8986                Phi->getIncomingValueForBlock(OrigLoop->getLoopPreheader()));
8987         PhiRecipe = new VPReductionPHIRecipe(Phi, RdxDesc, *StartV,
8988                                              CM.isInLoopReduction(Phi),
8989                                              CM.useOrderedReductions(RdxDesc));
8990       } else {
8991         PhiRecipe = new VPWidenPHIRecipe(Phi, *StartV);
8992       }
8993 
8994       // Record the incoming value from the backedge, so we can add the incoming
8995       // value from the backedge after all recipes have been created.
8996       recordRecipeOf(cast<Instruction>(
8997           Phi->getIncomingValueForBlock(OrigLoop->getLoopLatch())));
8998       PhisToFix.push_back(PhiRecipe);
8999     } else {
9000       // TODO: record start and backedge value for remaining pointer induction
9001       // phis.
9002       assert(Phi->getType()->isPointerTy() &&
9003              "only pointer phis should be handled here");
9004       PhiRecipe = new VPWidenPHIRecipe(Phi);
9005     }
9006 
9007     return toVPRecipeResult(PhiRecipe);
9008   }
9009 
9010   if (isa<TruncInst>(Instr) &&
9011       (Recipe = tryToOptimizeInductionTruncate(cast<TruncInst>(Instr), Operands,
9012                                                Range, *Plan)))
9013     return toVPRecipeResult(Recipe);
9014 
9015   if (!shouldWiden(Instr, Range))
9016     return nullptr;
9017 
9018   if (auto GEP = dyn_cast<GetElementPtrInst>(Instr))
9019     return toVPRecipeResult(new VPWidenGEPRecipe(
9020         GEP, make_range(Operands.begin(), Operands.end()), OrigLoop));
9021 
9022   if (auto *SI = dyn_cast<SelectInst>(Instr)) {
9023     bool InvariantCond =
9024         PSE.getSE()->isLoopInvariant(PSE.getSCEV(SI->getOperand(0)), OrigLoop);
9025     return toVPRecipeResult(new VPWidenSelectRecipe(
9026         *SI, make_range(Operands.begin(), Operands.end()), InvariantCond));
9027   }
9028 
9029   return toVPRecipeResult(tryToWiden(Instr, Operands));
9030 }
9031 
9032 void LoopVectorizationPlanner::buildVPlansWithVPRecipes(ElementCount MinVF,
9033                                                         ElementCount MaxVF) {
9034   assert(OrigLoop->isInnermost() && "Inner loop expected.");
9035 
9036   // Collect instructions from the original loop that will become trivially dead
9037   // in the vectorized loop. We don't need to vectorize these instructions. For
9038   // example, original induction update instructions can become dead because we
9039   // separately emit induction "steps" when generating code for the new loop.
9040   // Similarly, we create a new latch condition when setting up the structure
9041   // of the new loop, so the old one can become dead.
9042   SmallPtrSet<Instruction *, 4> DeadInstructions;
9043   collectTriviallyDeadInstructions(DeadInstructions);
9044 
9045   // Add assume instructions we need to drop to DeadInstructions, to prevent
9046   // them from being added to the VPlan.
9047   // TODO: We only need to drop assumes in blocks that get flattend. If the
9048   // control flow is preserved, we should keep them.
9049   auto &ConditionalAssumes = Legal->getConditionalAssumes();
9050   DeadInstructions.insert(ConditionalAssumes.begin(), ConditionalAssumes.end());
9051 
9052   MapVector<Instruction *, Instruction *> &SinkAfter = Legal->getSinkAfter();
9053   // Dead instructions do not need sinking. Remove them from SinkAfter.
9054   for (Instruction *I : DeadInstructions)
9055     SinkAfter.erase(I);
9056 
9057   // Cannot sink instructions after dead instructions (there won't be any
9058   // recipes for them). Instead, find the first non-dead previous instruction.
9059   for (auto &P : Legal->getSinkAfter()) {
9060     Instruction *SinkTarget = P.second;
9061     Instruction *FirstInst = &*SinkTarget->getParent()->begin();
9062     (void)FirstInst;
9063     while (DeadInstructions.contains(SinkTarget)) {
9064       assert(
9065           SinkTarget != FirstInst &&
9066           "Must find a live instruction (at least the one feeding the "
9067           "first-order recurrence PHI) before reaching beginning of the block");
9068       SinkTarget = SinkTarget->getPrevNode();
9069       assert(SinkTarget != P.first &&
9070              "sink source equals target, no sinking required");
9071     }
9072     P.second = SinkTarget;
9073   }
9074 
9075   auto MaxVFPlusOne = MaxVF.getWithIncrement(1);
9076   for (ElementCount VF = MinVF; ElementCount::isKnownLT(VF, MaxVFPlusOne);) {
9077     VFRange SubRange = {VF, MaxVFPlusOne};
9078     VPlans.push_back(
9079         buildVPlanWithVPRecipes(SubRange, DeadInstructions, SinkAfter));
9080     VF = SubRange.End;
9081   }
9082 }
9083 
9084 VPlanPtr LoopVectorizationPlanner::buildVPlanWithVPRecipes(
9085     VFRange &Range, SmallPtrSetImpl<Instruction *> &DeadInstructions,
9086     const MapVector<Instruction *, Instruction *> &SinkAfter) {
9087 
9088   SmallPtrSet<const InterleaveGroup<Instruction> *, 1> InterleaveGroups;
9089 
9090   VPRecipeBuilder RecipeBuilder(OrigLoop, TLI, Legal, CM, PSE, Builder);
9091 
9092   // ---------------------------------------------------------------------------
9093   // Pre-construction: record ingredients whose recipes we'll need to further
9094   // process after constructing the initial VPlan.
9095   // ---------------------------------------------------------------------------
9096 
9097   // Mark instructions we'll need to sink later and their targets as
9098   // ingredients whose recipe we'll need to record.
9099   for (auto &Entry : SinkAfter) {
9100     RecipeBuilder.recordRecipeOf(Entry.first);
9101     RecipeBuilder.recordRecipeOf(Entry.second);
9102   }
9103   for (auto &Reduction : CM.getInLoopReductionChains()) {
9104     PHINode *Phi = Reduction.first;
9105     RecurKind Kind = Legal->getReductionVars()[Phi].getRecurrenceKind();
9106     const SmallVector<Instruction *, 4> &ReductionOperations = Reduction.second;
9107 
9108     RecipeBuilder.recordRecipeOf(Phi);
9109     for (auto &R : ReductionOperations) {
9110       RecipeBuilder.recordRecipeOf(R);
9111       // For min/max reducitons, where we have a pair of icmp/select, we also
9112       // need to record the ICmp recipe, so it can be removed later.
9113       if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind))
9114         RecipeBuilder.recordRecipeOf(cast<Instruction>(R->getOperand(0)));
9115     }
9116   }
9117 
9118   // For each interleave group which is relevant for this (possibly trimmed)
9119   // Range, add it to the set of groups to be later applied to the VPlan and add
9120   // placeholders for its members' Recipes which we'll be replacing with a
9121   // single VPInterleaveRecipe.
9122   for (InterleaveGroup<Instruction> *IG : IAI.getInterleaveGroups()) {
9123     auto applyIG = [IG, this](ElementCount VF) -> bool {
9124       return (VF.isVector() && // Query is illegal for VF == 1
9125               CM.getWideningDecision(IG->getInsertPos(), VF) ==
9126                   LoopVectorizationCostModel::CM_Interleave);
9127     };
9128     if (!getDecisionAndClampRange(applyIG, Range))
9129       continue;
9130     InterleaveGroups.insert(IG);
9131     for (unsigned i = 0; i < IG->getFactor(); i++)
9132       if (Instruction *Member = IG->getMember(i))
9133         RecipeBuilder.recordRecipeOf(Member);
9134   };
9135 
9136   // ---------------------------------------------------------------------------
9137   // Build initial VPlan: Scan the body of the loop in a topological order to
9138   // visit each basic block after having visited its predecessor basic blocks.
9139   // ---------------------------------------------------------------------------
9140 
9141   // Create a dummy pre-entry VPBasicBlock to start building the VPlan.
9142   auto Plan = std::make_unique<VPlan>();
9143   VPBasicBlock *VPBB = new VPBasicBlock("Pre-Entry");
9144   Plan->setEntry(VPBB);
9145 
9146   // Scan the body of the loop in a topological order to visit each basic block
9147   // after having visited its predecessor basic blocks.
9148   LoopBlocksDFS DFS(OrigLoop);
9149   DFS.perform(LI);
9150 
9151   for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) {
9152     // Relevant instructions from basic block BB will be grouped into VPRecipe
9153     // ingredients and fill a new VPBasicBlock.
9154     unsigned VPBBsForBB = 0;
9155     auto *FirstVPBBForBB = new VPBasicBlock(BB->getName());
9156     VPBlockUtils::insertBlockAfter(FirstVPBBForBB, VPBB);
9157     VPBB = FirstVPBBForBB;
9158     Builder.setInsertPoint(VPBB);
9159 
9160     // Introduce each ingredient into VPlan.
9161     // TODO: Model and preserve debug instrinsics in VPlan.
9162     for (Instruction &I : BB->instructionsWithoutDebug()) {
9163       Instruction *Instr = &I;
9164 
9165       // First filter out irrelevant instructions, to ensure no recipes are
9166       // built for them.
9167       if (isa<BranchInst>(Instr) || DeadInstructions.count(Instr))
9168         continue;
9169 
9170       SmallVector<VPValue *, 4> Operands;
9171       auto *Phi = dyn_cast<PHINode>(Instr);
9172       if (Phi && Phi->getParent() == OrigLoop->getHeader()) {
9173         Operands.push_back(Plan->getOrAddVPValue(
9174             Phi->getIncomingValueForBlock(OrigLoop->getLoopPreheader())));
9175       } else {
9176         auto OpRange = Plan->mapToVPValues(Instr->operands());
9177         Operands = {OpRange.begin(), OpRange.end()};
9178       }
9179       if (auto RecipeOrValue = RecipeBuilder.tryToCreateWidenRecipe(
9180               Instr, Operands, Range, Plan)) {
9181         // If Instr can be simplified to an existing VPValue, use it.
9182         if (RecipeOrValue.is<VPValue *>()) {
9183           auto *VPV = RecipeOrValue.get<VPValue *>();
9184           Plan->addVPValue(Instr, VPV);
9185           // If the re-used value is a recipe, register the recipe for the
9186           // instruction, in case the recipe for Instr needs to be recorded.
9187           if (auto *R = dyn_cast_or_null<VPRecipeBase>(VPV->getDef()))
9188             RecipeBuilder.setRecipe(Instr, R);
9189           continue;
9190         }
9191         // Otherwise, add the new recipe.
9192         VPRecipeBase *Recipe = RecipeOrValue.get<VPRecipeBase *>();
9193         for (auto *Def : Recipe->definedValues()) {
9194           auto *UV = Def->getUnderlyingValue();
9195           Plan->addVPValue(UV, Def);
9196         }
9197 
9198         RecipeBuilder.setRecipe(Instr, Recipe);
9199         VPBB->appendRecipe(Recipe);
9200         continue;
9201       }
9202 
9203       // Otherwise, if all widening options failed, Instruction is to be
9204       // replicated. This may create a successor for VPBB.
9205       VPBasicBlock *NextVPBB =
9206           RecipeBuilder.handleReplication(Instr, Range, VPBB, Plan);
9207       if (NextVPBB != VPBB) {
9208         VPBB = NextVPBB;
9209         VPBB->setName(BB->hasName() ? BB->getName() + "." + Twine(VPBBsForBB++)
9210                                     : "");
9211       }
9212     }
9213   }
9214 
9215   RecipeBuilder.fixHeaderPhis();
9216 
9217   // Discard empty dummy pre-entry VPBasicBlock. Note that other VPBasicBlocks
9218   // may also be empty, such as the last one VPBB, reflecting original
9219   // basic-blocks with no recipes.
9220   VPBasicBlock *PreEntry = cast<VPBasicBlock>(Plan->getEntry());
9221   assert(PreEntry->empty() && "Expecting empty pre-entry block.");
9222   VPBlockBase *Entry = Plan->setEntry(PreEntry->getSingleSuccessor());
9223   VPBlockUtils::disconnectBlocks(PreEntry, Entry);
9224   delete PreEntry;
9225 
9226   // ---------------------------------------------------------------------------
9227   // Transform initial VPlan: Apply previously taken decisions, in order, to
9228   // bring the VPlan to its final state.
9229   // ---------------------------------------------------------------------------
9230 
9231   // Apply Sink-After legal constraints.
9232   for (auto &Entry : SinkAfter) {
9233     VPRecipeBase *Sink = RecipeBuilder.getRecipe(Entry.first);
9234     VPRecipeBase *Target = RecipeBuilder.getRecipe(Entry.second);
9235 
9236     auto GetReplicateRegion = [](VPRecipeBase *R) -> VPRegionBlock * {
9237       auto *Region =
9238           dyn_cast_or_null<VPRegionBlock>(R->getParent()->getParent());
9239       if (Region && Region->isReplicator()) {
9240         assert(Region->getNumSuccessors() == 1 &&
9241                Region->getNumPredecessors() == 1 && "Expected SESE region!");
9242         assert(R->getParent()->size() == 1 &&
9243                "A recipe in an original replicator region must be the only "
9244                "recipe in its block");
9245         return Region;
9246       }
9247       return nullptr;
9248     };
9249     auto *TargetRegion = GetReplicateRegion(Target);
9250     auto *SinkRegion = GetReplicateRegion(Sink);
9251     if (!SinkRegion) {
9252       // If the sink source is not a replicate region, sink the recipe directly.
9253       if (TargetRegion) {
9254         // The target is in a replication region, make sure to move Sink to
9255         // the block after it, not into the replication region itself.
9256         VPBasicBlock *NextBlock =
9257             cast<VPBasicBlock>(TargetRegion->getSuccessors().front());
9258         Sink->moveBefore(*NextBlock, NextBlock->getFirstNonPhi());
9259       } else
9260         Sink->moveAfter(Target);
9261       continue;
9262     }
9263 
9264     // The sink source is in a replicate region. Unhook the region from the CFG.
9265     auto *SinkPred = SinkRegion->getSinglePredecessor();
9266     auto *SinkSucc = SinkRegion->getSingleSuccessor();
9267     VPBlockUtils::disconnectBlocks(SinkPred, SinkRegion);
9268     VPBlockUtils::disconnectBlocks(SinkRegion, SinkSucc);
9269     VPBlockUtils::connectBlocks(SinkPred, SinkSucc);
9270 
9271     if (TargetRegion) {
9272       // The target recipe is also in a replicate region, move the sink region
9273       // after the target region.
9274       auto *TargetSucc = TargetRegion->getSingleSuccessor();
9275       VPBlockUtils::disconnectBlocks(TargetRegion, TargetSucc);
9276       VPBlockUtils::connectBlocks(TargetRegion, SinkRegion);
9277       VPBlockUtils::connectBlocks(SinkRegion, TargetSucc);
9278     } else {
9279       // The sink source is in a replicate region, we need to move the whole
9280       // replicate region, which should only contain a single recipe in the main
9281       // block.
9282       auto *SplitBlock =
9283           Target->getParent()->splitAt(std::next(Target->getIterator()));
9284 
9285       auto *SplitPred = SplitBlock->getSinglePredecessor();
9286 
9287       VPBlockUtils::disconnectBlocks(SplitPred, SplitBlock);
9288       VPBlockUtils::connectBlocks(SplitPred, SinkRegion);
9289       VPBlockUtils::connectBlocks(SinkRegion, SplitBlock);
9290       if (VPBB == SplitPred)
9291         VPBB = SplitBlock;
9292     }
9293   }
9294 
9295   // Interleave memory: for each Interleave Group we marked earlier as relevant
9296   // for this VPlan, replace the Recipes widening its memory instructions with a
9297   // single VPInterleaveRecipe at its insertion point.
9298   for (auto IG : InterleaveGroups) {
9299     auto *Recipe = cast<VPWidenMemoryInstructionRecipe>(
9300         RecipeBuilder.getRecipe(IG->getInsertPos()));
9301     SmallVector<VPValue *, 4> StoredValues;
9302     for (unsigned i = 0; i < IG->getFactor(); ++i)
9303       if (auto *SI = dyn_cast_or_null<StoreInst>(IG->getMember(i)))
9304         StoredValues.push_back(Plan->getOrAddVPValue(SI->getOperand(0)));
9305 
9306     auto *VPIG = new VPInterleaveRecipe(IG, Recipe->getAddr(), StoredValues,
9307                                         Recipe->getMask());
9308     VPIG->insertBefore(Recipe);
9309     unsigned J = 0;
9310     for (unsigned i = 0; i < IG->getFactor(); ++i)
9311       if (Instruction *Member = IG->getMember(i)) {
9312         if (!Member->getType()->isVoidTy()) {
9313           VPValue *OriginalV = Plan->getVPValue(Member);
9314           Plan->removeVPValueFor(Member);
9315           Plan->addVPValue(Member, VPIG->getVPValue(J));
9316           OriginalV->replaceAllUsesWith(VPIG->getVPValue(J));
9317           J++;
9318         }
9319         RecipeBuilder.getRecipe(Member)->eraseFromParent();
9320       }
9321   }
9322 
9323   // Adjust the recipes for any inloop reductions.
9324   adjustRecipesForInLoopReductions(Plan, RecipeBuilder, Range.Start);
9325 
9326   // Finally, if tail is folded by masking, introduce selects between the phi
9327   // and the live-out instruction of each reduction, at the end of the latch.
9328   if (CM.foldTailByMasking() && !Legal->getReductionVars().empty()) {
9329     Builder.setInsertPoint(VPBB);
9330     auto *Cond = RecipeBuilder.createBlockInMask(OrigLoop->getHeader(), Plan);
9331     for (auto &Reduction : Legal->getReductionVars()) {
9332       if (CM.isInLoopReduction(Reduction.first))
9333         continue;
9334       VPValue *Phi = Plan->getOrAddVPValue(Reduction.first);
9335       VPValue *Red = Plan->getOrAddVPValue(Reduction.second.getLoopExitInstr());
9336       Builder.createNaryOp(Instruction::Select, {Cond, Red, Phi});
9337     }
9338   }
9339 
9340   VPlanTransforms::sinkScalarOperands(*Plan);
9341   VPlanTransforms::mergeReplicateRegions(*Plan);
9342 
9343   std::string PlanName;
9344   raw_string_ostream RSO(PlanName);
9345   ElementCount VF = Range.Start;
9346   Plan->addVF(VF);
9347   RSO << "Initial VPlan for VF={" << VF;
9348   for (VF *= 2; ElementCount::isKnownLT(VF, Range.End); VF *= 2) {
9349     Plan->addVF(VF);
9350     RSO << "," << VF;
9351   }
9352   RSO << "},UF>=1";
9353   RSO.flush();
9354   Plan->setName(PlanName);
9355 
9356   return Plan;
9357 }
9358 
9359 VPlanPtr LoopVectorizationPlanner::buildVPlan(VFRange &Range) {
9360   // Outer loop handling: They may require CFG and instruction level
9361   // transformations before even evaluating whether vectorization is profitable.
9362   // Since we cannot modify the incoming IR, we need to build VPlan upfront in
9363   // the vectorization pipeline.
9364   assert(!OrigLoop->isInnermost());
9365   assert(EnableVPlanNativePath && "VPlan-native path is not enabled.");
9366 
9367   // Create new empty VPlan
9368   auto Plan = std::make_unique<VPlan>();
9369 
9370   // Build hierarchical CFG
9371   VPlanHCFGBuilder HCFGBuilder(OrigLoop, LI, *Plan);
9372   HCFGBuilder.buildHierarchicalCFG();
9373 
9374   for (ElementCount VF = Range.Start; ElementCount::isKnownLT(VF, Range.End);
9375        VF *= 2)
9376     Plan->addVF(VF);
9377 
9378   if (EnableVPlanPredication) {
9379     VPlanPredicator VPP(*Plan);
9380     VPP.predicate();
9381 
9382     // Avoid running transformation to recipes until masked code generation in
9383     // VPlan-native path is in place.
9384     return Plan;
9385   }
9386 
9387   SmallPtrSet<Instruction *, 1> DeadInstructions;
9388   VPlanTransforms::VPInstructionsToVPRecipes(OrigLoop, Plan,
9389                                              Legal->getInductionVars(),
9390                                              DeadInstructions, *PSE.getSE());
9391   return Plan;
9392 }
9393 
9394 // Adjust the recipes for any inloop reductions. The chain of instructions
9395 // leading from the loop exit instr to the phi need to be converted to
9396 // reductions, with one operand being vector and the other being the scalar
9397 // reduction chain.
9398 void LoopVectorizationPlanner::adjustRecipesForInLoopReductions(
9399     VPlanPtr &Plan, VPRecipeBuilder &RecipeBuilder, ElementCount MinVF) {
9400   for (auto &Reduction : CM.getInLoopReductionChains()) {
9401     PHINode *Phi = Reduction.first;
9402     RecurrenceDescriptor &RdxDesc = Legal->getReductionVars()[Phi];
9403     const SmallVector<Instruction *, 4> &ReductionOperations = Reduction.second;
9404 
9405     if (MinVF.isScalar() && !CM.useOrderedReductions(RdxDesc))
9406       continue;
9407 
9408     // ReductionOperations are orders top-down from the phi's use to the
9409     // LoopExitValue. We keep a track of the previous item (the Chain) to tell
9410     // which of the two operands will remain scalar and which will be reduced.
9411     // For minmax the chain will be the select instructions.
9412     Instruction *Chain = Phi;
9413     for (Instruction *R : ReductionOperations) {
9414       VPRecipeBase *WidenRecipe = RecipeBuilder.getRecipe(R);
9415       RecurKind Kind = RdxDesc.getRecurrenceKind();
9416 
9417       VPValue *ChainOp = Plan->getVPValue(Chain);
9418       unsigned FirstOpId;
9419       if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind)) {
9420         assert(isa<VPWidenSelectRecipe>(WidenRecipe) &&
9421                "Expected to replace a VPWidenSelectSC");
9422         FirstOpId = 1;
9423       } else {
9424         assert((MinVF.isScalar() || isa<VPWidenRecipe>(WidenRecipe)) &&
9425                "Expected to replace a VPWidenSC");
9426         FirstOpId = 0;
9427       }
9428       unsigned VecOpId =
9429           R->getOperand(FirstOpId) == Chain ? FirstOpId + 1 : FirstOpId;
9430       VPValue *VecOp = Plan->getVPValue(R->getOperand(VecOpId));
9431 
9432       auto *CondOp = CM.foldTailByMasking()
9433                          ? RecipeBuilder.createBlockInMask(R->getParent(), Plan)
9434                          : nullptr;
9435       VPReductionRecipe *RedRecipe = new VPReductionRecipe(
9436           &RdxDesc, R, ChainOp, VecOp, CondOp, TTI);
9437       WidenRecipe->getVPSingleValue()->replaceAllUsesWith(RedRecipe);
9438       Plan->removeVPValueFor(R);
9439       Plan->addVPValue(R, RedRecipe);
9440       WidenRecipe->getParent()->insert(RedRecipe, WidenRecipe->getIterator());
9441       WidenRecipe->getVPSingleValue()->replaceAllUsesWith(RedRecipe);
9442       WidenRecipe->eraseFromParent();
9443 
9444       if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind)) {
9445         VPRecipeBase *CompareRecipe =
9446             RecipeBuilder.getRecipe(cast<Instruction>(R->getOperand(0)));
9447         assert(isa<VPWidenRecipe>(CompareRecipe) &&
9448                "Expected to replace a VPWidenSC");
9449         assert(cast<VPWidenRecipe>(CompareRecipe)->getNumUsers() == 0 &&
9450                "Expected no remaining users");
9451         CompareRecipe->eraseFromParent();
9452       }
9453       Chain = R;
9454     }
9455   }
9456 }
9457 
9458 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
9459 void VPInterleaveRecipe::print(raw_ostream &O, const Twine &Indent,
9460                                VPSlotTracker &SlotTracker) const {
9461   O << Indent << "INTERLEAVE-GROUP with factor " << IG->getFactor() << " at ";
9462   IG->getInsertPos()->printAsOperand(O, false);
9463   O << ", ";
9464   getAddr()->printAsOperand(O, SlotTracker);
9465   VPValue *Mask = getMask();
9466   if (Mask) {
9467     O << ", ";
9468     Mask->printAsOperand(O, SlotTracker);
9469   }
9470   for (unsigned i = 0; i < IG->getFactor(); ++i)
9471     if (Instruction *I = IG->getMember(i))
9472       O << "\n" << Indent << "  " << VPlanIngredient(I) << " " << i;
9473 }
9474 #endif
9475 
9476 void VPWidenCallRecipe::execute(VPTransformState &State) {
9477   State.ILV->widenCallInstruction(*cast<CallInst>(getUnderlyingInstr()), this,
9478                                   *this, State);
9479 }
9480 
9481 void VPWidenSelectRecipe::execute(VPTransformState &State) {
9482   State.ILV->widenSelectInstruction(*cast<SelectInst>(getUnderlyingInstr()),
9483                                     this, *this, InvariantCond, State);
9484 }
9485 
9486 void VPWidenRecipe::execute(VPTransformState &State) {
9487   State.ILV->widenInstruction(*getUnderlyingInstr(), this, *this, State);
9488 }
9489 
9490 void VPWidenGEPRecipe::execute(VPTransformState &State) {
9491   State.ILV->widenGEP(cast<GetElementPtrInst>(getUnderlyingInstr()), this,
9492                       *this, State.UF, State.VF, IsPtrLoopInvariant,
9493                       IsIndexLoopInvariant, State);
9494 }
9495 
9496 void VPWidenIntOrFpInductionRecipe::execute(VPTransformState &State) {
9497   assert(!State.Instance && "Int or FP induction being replicated.");
9498   State.ILV->widenIntOrFpInduction(IV, getStartValue()->getLiveInIRValue(),
9499                                    getTruncInst(), getVPValue(0),
9500                                    getCastValue(), State);
9501 }
9502 
9503 void VPWidenPHIRecipe::execute(VPTransformState &State) {
9504   State.ILV->widenPHIInstruction(cast<PHINode>(getUnderlyingValue()), this,
9505                                  State);
9506 }
9507 
9508 void VPBlendRecipe::execute(VPTransformState &State) {
9509   State.ILV->setDebugLocFromInst(Phi, &State.Builder);
9510   // We know that all PHIs in non-header blocks are converted into
9511   // selects, so we don't have to worry about the insertion order and we
9512   // can just use the builder.
9513   // At this point we generate the predication tree. There may be
9514   // duplications since this is a simple recursive scan, but future
9515   // optimizations will clean it up.
9516 
9517   unsigned NumIncoming = getNumIncomingValues();
9518 
9519   // Generate a sequence of selects of the form:
9520   // SELECT(Mask3, In3,
9521   //        SELECT(Mask2, In2,
9522   //               SELECT(Mask1, In1,
9523   //                      In0)))
9524   // Note that Mask0 is never used: lanes for which no path reaches this phi and
9525   // are essentially undef are taken from In0.
9526   InnerLoopVectorizer::VectorParts Entry(State.UF);
9527   for (unsigned In = 0; In < NumIncoming; ++In) {
9528     for (unsigned Part = 0; Part < State.UF; ++Part) {
9529       // We might have single edge PHIs (blocks) - use an identity
9530       // 'select' for the first PHI operand.
9531       Value *In0 = State.get(getIncomingValue(In), Part);
9532       if (In == 0)
9533         Entry[Part] = In0; // Initialize with the first incoming value.
9534       else {
9535         // Select between the current value and the previous incoming edge
9536         // based on the incoming mask.
9537         Value *Cond = State.get(getMask(In), Part);
9538         Entry[Part] =
9539             State.Builder.CreateSelect(Cond, In0, Entry[Part], "predphi");
9540       }
9541     }
9542   }
9543   for (unsigned Part = 0; Part < State.UF; ++Part)
9544     State.set(this, Entry[Part], Part);
9545 }
9546 
9547 void VPInterleaveRecipe::execute(VPTransformState &State) {
9548   assert(!State.Instance && "Interleave group being replicated.");
9549   State.ILV->vectorizeInterleaveGroup(IG, definedValues(), State, getAddr(),
9550                                       getStoredValues(), getMask());
9551 }
9552 
9553 void VPReductionRecipe::execute(VPTransformState &State) {
9554   assert(!State.Instance && "Reduction being replicated.");
9555   Value *PrevInChain = State.get(getChainOp(), 0);
9556   for (unsigned Part = 0; Part < State.UF; ++Part) {
9557     RecurKind Kind = RdxDesc->getRecurrenceKind();
9558     bool IsOrdered = State.ILV->useOrderedReductions(*RdxDesc);
9559     Value *NewVecOp = State.get(getVecOp(), Part);
9560     if (VPValue *Cond = getCondOp()) {
9561       Value *NewCond = State.get(Cond, Part);
9562       VectorType *VecTy = cast<VectorType>(NewVecOp->getType());
9563       Constant *Iden = RecurrenceDescriptor::getRecurrenceIdentity(
9564           Kind, VecTy->getElementType(), RdxDesc->getFastMathFlags());
9565       Constant *IdenVec =
9566           ConstantVector::getSplat(VecTy->getElementCount(), Iden);
9567       Value *Select = State.Builder.CreateSelect(NewCond, NewVecOp, IdenVec);
9568       NewVecOp = Select;
9569     }
9570     Value *NewRed;
9571     Value *NextInChain;
9572     if (IsOrdered) {
9573       if (State.VF.isVector())
9574         NewRed = createOrderedReduction(State.Builder, *RdxDesc, NewVecOp,
9575                                         PrevInChain);
9576       else
9577         NewRed = State.Builder.CreateBinOp(
9578             (Instruction::BinaryOps)getUnderlyingInstr()->getOpcode(),
9579             PrevInChain, NewVecOp);
9580       PrevInChain = NewRed;
9581     } else {
9582       PrevInChain = State.get(getChainOp(), Part);
9583       NewRed = createTargetReduction(State.Builder, TTI, *RdxDesc, NewVecOp);
9584     }
9585     if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind)) {
9586       NextInChain =
9587           createMinMaxOp(State.Builder, RdxDesc->getRecurrenceKind(),
9588                          NewRed, PrevInChain);
9589     } else if (IsOrdered)
9590       NextInChain = NewRed;
9591     else {
9592       NextInChain = State.Builder.CreateBinOp(
9593           (Instruction::BinaryOps)getUnderlyingInstr()->getOpcode(), NewRed,
9594           PrevInChain);
9595     }
9596     State.set(this, NextInChain, Part);
9597   }
9598 }
9599 
9600 void VPReplicateRecipe::execute(VPTransformState &State) {
9601   if (State.Instance) { // Generate a single instance.
9602     assert(!State.VF.isScalable() && "Can't scalarize a scalable vector");
9603     State.ILV->scalarizeInstruction(getUnderlyingInstr(), this, *this,
9604                                     *State.Instance, IsPredicated, State);
9605     // Insert scalar instance packing it into a vector.
9606     if (AlsoPack && State.VF.isVector()) {
9607       // If we're constructing lane 0, initialize to start from poison.
9608       if (State.Instance->Lane.isFirstLane()) {
9609         assert(!State.VF.isScalable() && "VF is assumed to be non scalable.");
9610         Value *Poison = PoisonValue::get(
9611             VectorType::get(getUnderlyingValue()->getType(), State.VF));
9612         State.set(this, Poison, State.Instance->Part);
9613       }
9614       State.ILV->packScalarIntoVectorValue(this, *State.Instance, State);
9615     }
9616     return;
9617   }
9618 
9619   // Generate scalar instances for all VF lanes of all UF parts, unless the
9620   // instruction is uniform inwhich case generate only the first lane for each
9621   // of the UF parts.
9622   unsigned EndLane = IsUniform ? 1 : State.VF.getKnownMinValue();
9623   assert((!State.VF.isScalable() || IsUniform) &&
9624          "Can't scalarize a scalable vector");
9625   for (unsigned Part = 0; Part < State.UF; ++Part)
9626     for (unsigned Lane = 0; Lane < EndLane; ++Lane)
9627       State.ILV->scalarizeInstruction(getUnderlyingInstr(), this, *this,
9628                                       VPIteration(Part, Lane), IsPredicated,
9629                                       State);
9630 }
9631 
9632 void VPBranchOnMaskRecipe::execute(VPTransformState &State) {
9633   assert(State.Instance && "Branch on Mask works only on single instance.");
9634 
9635   unsigned Part = State.Instance->Part;
9636   unsigned Lane = State.Instance->Lane.getKnownLane();
9637 
9638   Value *ConditionBit = nullptr;
9639   VPValue *BlockInMask = getMask();
9640   if (BlockInMask) {
9641     ConditionBit = State.get(BlockInMask, Part);
9642     if (ConditionBit->getType()->isVectorTy())
9643       ConditionBit = State.Builder.CreateExtractElement(
9644           ConditionBit, State.Builder.getInt32(Lane));
9645   } else // Block in mask is all-one.
9646     ConditionBit = State.Builder.getTrue();
9647 
9648   // Replace the temporary unreachable terminator with a new conditional branch,
9649   // whose two destinations will be set later when they are created.
9650   auto *CurrentTerminator = State.CFG.PrevBB->getTerminator();
9651   assert(isa<UnreachableInst>(CurrentTerminator) &&
9652          "Expected to replace unreachable terminator with conditional branch.");
9653   auto *CondBr = BranchInst::Create(State.CFG.PrevBB, nullptr, ConditionBit);
9654   CondBr->setSuccessor(0, nullptr);
9655   ReplaceInstWithInst(CurrentTerminator, CondBr);
9656 }
9657 
9658 void VPPredInstPHIRecipe::execute(VPTransformState &State) {
9659   assert(State.Instance && "Predicated instruction PHI works per instance.");
9660   Instruction *ScalarPredInst =
9661       cast<Instruction>(State.get(getOperand(0), *State.Instance));
9662   BasicBlock *PredicatedBB = ScalarPredInst->getParent();
9663   BasicBlock *PredicatingBB = PredicatedBB->getSinglePredecessor();
9664   assert(PredicatingBB && "Predicated block has no single predecessor.");
9665   assert(isa<VPReplicateRecipe>(getOperand(0)) &&
9666          "operand must be VPReplicateRecipe");
9667 
9668   // By current pack/unpack logic we need to generate only a single phi node: if
9669   // a vector value for the predicated instruction exists at this point it means
9670   // the instruction has vector users only, and a phi for the vector value is
9671   // needed. In this case the recipe of the predicated instruction is marked to
9672   // also do that packing, thereby "hoisting" the insert-element sequence.
9673   // Otherwise, a phi node for the scalar value is needed.
9674   unsigned Part = State.Instance->Part;
9675   if (State.hasVectorValue(getOperand(0), Part)) {
9676     Value *VectorValue = State.get(getOperand(0), Part);
9677     InsertElementInst *IEI = cast<InsertElementInst>(VectorValue);
9678     PHINode *VPhi = State.Builder.CreatePHI(IEI->getType(), 2);
9679     VPhi->addIncoming(IEI->getOperand(0), PredicatingBB); // Unmodified vector.
9680     VPhi->addIncoming(IEI, PredicatedBB); // New vector with inserted element.
9681     if (State.hasVectorValue(this, Part))
9682       State.reset(this, VPhi, Part);
9683     else
9684       State.set(this, VPhi, Part);
9685     // NOTE: Currently we need to update the value of the operand, so the next
9686     // predicated iteration inserts its generated value in the correct vector.
9687     State.reset(getOperand(0), VPhi, Part);
9688   } else {
9689     Type *PredInstType = getOperand(0)->getUnderlyingValue()->getType();
9690     PHINode *Phi = State.Builder.CreatePHI(PredInstType, 2);
9691     Phi->addIncoming(PoisonValue::get(ScalarPredInst->getType()),
9692                      PredicatingBB);
9693     Phi->addIncoming(ScalarPredInst, PredicatedBB);
9694     if (State.hasScalarValue(this, *State.Instance))
9695       State.reset(this, Phi, *State.Instance);
9696     else
9697       State.set(this, Phi, *State.Instance);
9698     // NOTE: Currently we need to update the value of the operand, so the next
9699     // predicated iteration inserts its generated value in the correct vector.
9700     State.reset(getOperand(0), Phi, *State.Instance);
9701   }
9702 }
9703 
9704 void VPWidenMemoryInstructionRecipe::execute(VPTransformState &State) {
9705   VPValue *StoredValue = isStore() ? getStoredValue() : nullptr;
9706   State.ILV->vectorizeMemoryInstruction(
9707       &Ingredient, State, StoredValue ? nullptr : getVPSingleValue(), getAddr(),
9708       StoredValue, getMask());
9709 }
9710 
9711 // Determine how to lower the scalar epilogue, which depends on 1) optimising
9712 // for minimum code-size, 2) predicate compiler options, 3) loop hints forcing
9713 // predication, and 4) a TTI hook that analyses whether the loop is suitable
9714 // for predication.
9715 static ScalarEpilogueLowering getScalarEpilogueLowering(
9716     Function *F, Loop *L, LoopVectorizeHints &Hints, ProfileSummaryInfo *PSI,
9717     BlockFrequencyInfo *BFI, TargetTransformInfo *TTI, TargetLibraryInfo *TLI,
9718     AssumptionCache *AC, LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT,
9719     LoopVectorizationLegality &LVL) {
9720   // 1) OptSize takes precedence over all other options, i.e. if this is set,
9721   // don't look at hints or options, and don't request a scalar epilogue.
9722   // (For PGSO, as shouldOptimizeForSize isn't currently accessible from
9723   // LoopAccessInfo (due to code dependency and not being able to reliably get
9724   // PSI/BFI from a loop analysis under NPM), we cannot suppress the collection
9725   // of strides in LoopAccessInfo::analyzeLoop() and vectorize without
9726   // versioning when the vectorization is forced, unlike hasOptSize. So revert
9727   // back to the old way and vectorize with versioning when forced. See D81345.)
9728   if (F->hasOptSize() || (llvm::shouldOptimizeForSize(L->getHeader(), PSI, BFI,
9729                                                       PGSOQueryType::IRPass) &&
9730                           Hints.getForce() != LoopVectorizeHints::FK_Enabled))
9731     return CM_ScalarEpilogueNotAllowedOptSize;
9732 
9733   // 2) If set, obey the directives
9734   if (PreferPredicateOverEpilogue.getNumOccurrences()) {
9735     switch (PreferPredicateOverEpilogue) {
9736     case PreferPredicateTy::ScalarEpilogue:
9737       return CM_ScalarEpilogueAllowed;
9738     case PreferPredicateTy::PredicateElseScalarEpilogue:
9739       return CM_ScalarEpilogueNotNeededUsePredicate;
9740     case PreferPredicateTy::PredicateOrDontVectorize:
9741       return CM_ScalarEpilogueNotAllowedUsePredicate;
9742     };
9743   }
9744 
9745   // 3) If set, obey the hints
9746   switch (Hints.getPredicate()) {
9747   case LoopVectorizeHints::FK_Enabled:
9748     return CM_ScalarEpilogueNotNeededUsePredicate;
9749   case LoopVectorizeHints::FK_Disabled:
9750     return CM_ScalarEpilogueAllowed;
9751   };
9752 
9753   // 4) if the TTI hook indicates this is profitable, request predication.
9754   if (TTI->preferPredicateOverEpilogue(L, LI, *SE, *AC, TLI, DT,
9755                                        LVL.getLAI()))
9756     return CM_ScalarEpilogueNotNeededUsePredicate;
9757 
9758   return CM_ScalarEpilogueAllowed;
9759 }
9760 
9761 Value *VPTransformState::get(VPValue *Def, unsigned Part) {
9762   // If Values have been set for this Def return the one relevant for \p Part.
9763   if (hasVectorValue(Def, Part))
9764     return Data.PerPartOutput[Def][Part];
9765 
9766   if (!hasScalarValue(Def, {Part, 0})) {
9767     Value *IRV = Def->getLiveInIRValue();
9768     Value *B = ILV->getBroadcastInstrs(IRV);
9769     set(Def, B, Part);
9770     return B;
9771   }
9772 
9773   Value *ScalarValue = get(Def, {Part, 0});
9774   // If we aren't vectorizing, we can just copy the scalar map values over
9775   // to the vector map.
9776   if (VF.isScalar()) {
9777     set(Def, ScalarValue, Part);
9778     return ScalarValue;
9779   }
9780 
9781   auto *RepR = dyn_cast<VPReplicateRecipe>(Def);
9782   bool IsUniform = RepR && RepR->isUniform();
9783 
9784   unsigned LastLane = IsUniform ? 0 : VF.getKnownMinValue() - 1;
9785   // Check if there is a scalar value for the selected lane.
9786   if (!hasScalarValue(Def, {Part, LastLane})) {
9787     // At the moment, VPWidenIntOrFpInductionRecipes can also be uniform.
9788     assert(isa<VPWidenIntOrFpInductionRecipe>(Def->getDef()) &&
9789            "unexpected recipe found to be invariant");
9790     IsUniform = true;
9791     LastLane = 0;
9792   }
9793 
9794   auto *LastInst = cast<Instruction>(get(Def, {Part, LastLane}));
9795   // Set the insert point after the last scalarized instruction or after the
9796   // last PHI, if LastInst is a PHI. This ensures the insertelement sequence
9797   // will directly follow the scalar definitions.
9798   auto OldIP = Builder.saveIP();
9799   auto NewIP =
9800       isa<PHINode>(LastInst)
9801           ? BasicBlock::iterator(LastInst->getParent()->getFirstNonPHI())
9802           : std::next(BasicBlock::iterator(LastInst));
9803   Builder.SetInsertPoint(&*NewIP);
9804 
9805   // However, if we are vectorizing, we need to construct the vector values.
9806   // If the value is known to be uniform after vectorization, we can just
9807   // broadcast the scalar value corresponding to lane zero for each unroll
9808   // iteration. Otherwise, we construct the vector values using
9809   // insertelement instructions. Since the resulting vectors are stored in
9810   // State, we will only generate the insertelements once.
9811   Value *VectorValue = nullptr;
9812   if (IsUniform) {
9813     VectorValue = ILV->getBroadcastInstrs(ScalarValue);
9814     set(Def, VectorValue, Part);
9815   } else {
9816     // Initialize packing with insertelements to start from undef.
9817     assert(!VF.isScalable() && "VF is assumed to be non scalable.");
9818     Value *Undef = PoisonValue::get(VectorType::get(LastInst->getType(), VF));
9819     set(Def, Undef, Part);
9820     for (unsigned Lane = 0; Lane < VF.getKnownMinValue(); ++Lane)
9821       ILV->packScalarIntoVectorValue(Def, {Part, Lane}, *this);
9822     VectorValue = get(Def, Part);
9823   }
9824   Builder.restoreIP(OldIP);
9825   return VectorValue;
9826 }
9827 
9828 // Process the loop in the VPlan-native vectorization path. This path builds
9829 // VPlan upfront in the vectorization pipeline, which allows to apply
9830 // VPlan-to-VPlan transformations from the very beginning without modifying the
9831 // input LLVM IR.
9832 static bool processLoopInVPlanNativePath(
9833     Loop *L, PredicatedScalarEvolution &PSE, LoopInfo *LI, DominatorTree *DT,
9834     LoopVectorizationLegality *LVL, TargetTransformInfo *TTI,
9835     TargetLibraryInfo *TLI, DemandedBits *DB, AssumptionCache *AC,
9836     OptimizationRemarkEmitter *ORE, BlockFrequencyInfo *BFI,
9837     ProfileSummaryInfo *PSI, LoopVectorizeHints &Hints,
9838     LoopVectorizationRequirements &Requirements) {
9839 
9840   if (isa<SCEVCouldNotCompute>(PSE.getBackedgeTakenCount())) {
9841     LLVM_DEBUG(dbgs() << "LV: cannot compute the outer-loop trip count\n");
9842     return false;
9843   }
9844   assert(EnableVPlanNativePath && "VPlan-native path is disabled.");
9845   Function *F = L->getHeader()->getParent();
9846   InterleavedAccessInfo IAI(PSE, L, DT, LI, LVL->getLAI());
9847 
9848   ScalarEpilogueLowering SEL = getScalarEpilogueLowering(
9849       F, L, Hints, PSI, BFI, TTI, TLI, AC, LI, PSE.getSE(), DT, *LVL);
9850 
9851   LoopVectorizationCostModel CM(SEL, L, PSE, LI, LVL, *TTI, TLI, DB, AC, ORE, F,
9852                                 &Hints, IAI);
9853   // Use the planner for outer loop vectorization.
9854   // TODO: CM is not used at this point inside the planner. Turn CM into an
9855   // optional argument if we don't need it in the future.
9856   LoopVectorizationPlanner LVP(L, LI, TLI, TTI, LVL, CM, IAI, PSE, Hints,
9857                                Requirements, ORE);
9858 
9859   // Get user vectorization factor.
9860   ElementCount UserVF = Hints.getWidth();
9861 
9862   CM.collectElementTypesForWidening();
9863 
9864   // Plan how to best vectorize, return the best VF and its cost.
9865   const VectorizationFactor VF = LVP.planInVPlanNativePath(UserVF);
9866 
9867   // If we are stress testing VPlan builds, do not attempt to generate vector
9868   // code. Masked vector code generation support will follow soon.
9869   // Also, do not attempt to vectorize if no vector code will be produced.
9870   if (VPlanBuildStressTest || EnableVPlanPredication ||
9871       VectorizationFactor::Disabled() == VF)
9872     return false;
9873 
9874   LVP.setBestPlan(VF.Width, 1);
9875 
9876   {
9877     GeneratedRTChecks Checks(*PSE.getSE(), DT, LI,
9878                              F->getParent()->getDataLayout());
9879     InnerLoopVectorizer LB(L, PSE, LI, DT, TLI, TTI, AC, ORE, VF.Width, 1, LVL,
9880                            &CM, BFI, PSI, Checks);
9881     LLVM_DEBUG(dbgs() << "Vectorizing outer loop in \""
9882                       << L->getHeader()->getParent()->getName() << "\"\n");
9883     LVP.executePlan(LB, DT);
9884   }
9885 
9886   // Mark the loop as already vectorized to avoid vectorizing again.
9887   Hints.setAlreadyVectorized();
9888   assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()));
9889   return true;
9890 }
9891 
9892 // Emit a remark if there are stores to floats that required a floating point
9893 // extension. If the vectorized loop was generated with floating point there
9894 // will be a performance penalty from the conversion overhead and the change in
9895 // the vector width.
9896 static void checkMixedPrecision(Loop *L, OptimizationRemarkEmitter *ORE) {
9897   SmallVector<Instruction *, 4> Worklist;
9898   for (BasicBlock *BB : L->getBlocks()) {
9899     for (Instruction &Inst : *BB) {
9900       if (auto *S = dyn_cast<StoreInst>(&Inst)) {
9901         if (S->getValueOperand()->getType()->isFloatTy())
9902           Worklist.push_back(S);
9903       }
9904     }
9905   }
9906 
9907   // Traverse the floating point stores upwards searching, for floating point
9908   // conversions.
9909   SmallPtrSet<const Instruction *, 4> Visited;
9910   SmallPtrSet<const Instruction *, 4> EmittedRemark;
9911   while (!Worklist.empty()) {
9912     auto *I = Worklist.pop_back_val();
9913     if (!L->contains(I))
9914       continue;
9915     if (!Visited.insert(I).second)
9916       continue;
9917 
9918     // Emit a remark if the floating point store required a floating
9919     // point conversion.
9920     // TODO: More work could be done to identify the root cause such as a
9921     // constant or a function return type and point the user to it.
9922     if (isa<FPExtInst>(I) && EmittedRemark.insert(I).second)
9923       ORE->emit([&]() {
9924         return OptimizationRemarkAnalysis(LV_NAME, "VectorMixedPrecision",
9925                                           I->getDebugLoc(), L->getHeader())
9926                << "floating point conversion changes vector width. "
9927                << "Mixed floating point precision requires an up/down "
9928                << "cast that will negatively impact performance.";
9929       });
9930 
9931     for (Use &Op : I->operands())
9932       if (auto *OpI = dyn_cast<Instruction>(Op))
9933         Worklist.push_back(OpI);
9934   }
9935 }
9936 
9937 LoopVectorizePass::LoopVectorizePass(LoopVectorizeOptions Opts)
9938     : InterleaveOnlyWhenForced(Opts.InterleaveOnlyWhenForced ||
9939                                !EnableLoopInterleaving),
9940       VectorizeOnlyWhenForced(Opts.VectorizeOnlyWhenForced ||
9941                               !EnableLoopVectorization) {}
9942 
9943 bool LoopVectorizePass::processLoop(Loop *L) {
9944   assert((EnableVPlanNativePath || L->isInnermost()) &&
9945          "VPlan-native path is not enabled. Only process inner loops.");
9946 
9947 #ifndef NDEBUG
9948   const std::string DebugLocStr = getDebugLocString(L);
9949 #endif /* NDEBUG */
9950 
9951   LLVM_DEBUG(dbgs() << "\nLV: Checking a loop in \""
9952                     << L->getHeader()->getParent()->getName() << "\" from "
9953                     << DebugLocStr << "\n");
9954 
9955   LoopVectorizeHints Hints(L, InterleaveOnlyWhenForced, *ORE);
9956 
9957   LLVM_DEBUG(
9958       dbgs() << "LV: Loop hints:"
9959              << " force="
9960              << (Hints.getForce() == LoopVectorizeHints::FK_Disabled
9961                      ? "disabled"
9962                      : (Hints.getForce() == LoopVectorizeHints::FK_Enabled
9963                             ? "enabled"
9964                             : "?"))
9965              << " width=" << Hints.getWidth()
9966              << " interleave=" << Hints.getInterleave() << "\n");
9967 
9968   // Function containing loop
9969   Function *F = L->getHeader()->getParent();
9970 
9971   // Looking at the diagnostic output is the only way to determine if a loop
9972   // was vectorized (other than looking at the IR or machine code), so it
9973   // is important to generate an optimization remark for each loop. Most of
9974   // these messages are generated as OptimizationRemarkAnalysis. Remarks
9975   // generated as OptimizationRemark and OptimizationRemarkMissed are
9976   // less verbose reporting vectorized loops and unvectorized loops that may
9977   // benefit from vectorization, respectively.
9978 
9979   if (!Hints.allowVectorization(F, L, VectorizeOnlyWhenForced)) {
9980     LLVM_DEBUG(dbgs() << "LV: Loop hints prevent vectorization.\n");
9981     return false;
9982   }
9983 
9984   PredicatedScalarEvolution PSE(*SE, *L);
9985 
9986   // Check if it is legal to vectorize the loop.
9987   LoopVectorizationRequirements Requirements;
9988   LoopVectorizationLegality LVL(L, PSE, DT, TTI, TLI, AA, F, GetLAA, LI, ORE,
9989                                 &Requirements, &Hints, DB, AC, BFI, PSI);
9990   if (!LVL.canVectorize(EnableVPlanNativePath)) {
9991     LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
9992     Hints.emitRemarkWithHints();
9993     return false;
9994   }
9995 
9996   // Check the function attributes and profiles to find out if this function
9997   // should be optimized for size.
9998   ScalarEpilogueLowering SEL = getScalarEpilogueLowering(
9999       F, L, Hints, PSI, BFI, TTI, TLI, AC, LI, PSE.getSE(), DT, LVL);
10000 
10001   // Entrance to the VPlan-native vectorization path. Outer loops are processed
10002   // here. They may require CFG and instruction level transformations before
10003   // even evaluating whether vectorization is profitable. Since we cannot modify
10004   // the incoming IR, we need to build VPlan upfront in the vectorization
10005   // pipeline.
10006   if (!L->isInnermost())
10007     return processLoopInVPlanNativePath(L, PSE, LI, DT, &LVL, TTI, TLI, DB, AC,
10008                                         ORE, BFI, PSI, Hints, Requirements);
10009 
10010   assert(L->isInnermost() && "Inner loop expected.");
10011 
10012   // Check the loop for a trip count threshold: vectorize loops with a tiny trip
10013   // count by optimizing for size, to minimize overheads.
10014   auto ExpectedTC = getSmallBestKnownTC(*SE, L);
10015   if (ExpectedTC && *ExpectedTC < TinyTripCountVectorThreshold) {
10016     LLVM_DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "
10017                       << "This loop is worth vectorizing only if no scalar "
10018                       << "iteration overheads are incurred.");
10019     if (Hints.getForce() == LoopVectorizeHints::FK_Enabled)
10020       LLVM_DEBUG(dbgs() << " But vectorizing was explicitly forced.\n");
10021     else {
10022       LLVM_DEBUG(dbgs() << "\n");
10023       SEL = CM_ScalarEpilogueNotAllowedLowTripLoop;
10024     }
10025   }
10026 
10027   // Check the function attributes to see if implicit floats are allowed.
10028   // FIXME: This check doesn't seem possibly correct -- what if the loop is
10029   // an integer loop and the vector instructions selected are purely integer
10030   // vector instructions?
10031   if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10032     reportVectorizationFailure(
10033         "Can't vectorize when the NoImplicitFloat attribute is used",
10034         "loop not vectorized due to NoImplicitFloat attribute",
10035         "NoImplicitFloat", ORE, L);
10036     Hints.emitRemarkWithHints();
10037     return false;
10038   }
10039 
10040   // Check if the target supports potentially unsafe FP vectorization.
10041   // FIXME: Add a check for the type of safety issue (denormal, signaling)
10042   // for the target we're vectorizing for, to make sure none of the
10043   // additional fp-math flags can help.
10044   if (Hints.isPotentiallyUnsafe() &&
10045       TTI->isFPVectorizationPotentiallyUnsafe()) {
10046     reportVectorizationFailure(
10047         "Potentially unsafe FP op prevents vectorization",
10048         "loop not vectorized due to unsafe FP support.",
10049         "UnsafeFP", ORE, L);
10050     Hints.emitRemarkWithHints();
10051     return false;
10052   }
10053 
10054   if (!LVL.canVectorizeFPMath(EnableStrictReductions)) {
10055     ORE->emit([&]() {
10056       auto *ExactFPMathInst = Requirements.getExactFPInst();
10057       return OptimizationRemarkAnalysisFPCommute(DEBUG_TYPE, "CantReorderFPOps",
10058                                                  ExactFPMathInst->getDebugLoc(),
10059                                                  ExactFPMathInst->getParent())
10060              << "loop not vectorized: cannot prove it is safe to reorder "
10061                 "floating-point operations";
10062     });
10063     LLVM_DEBUG(dbgs() << "LV: loop not vectorized: cannot prove it is safe to "
10064                          "reorder floating-point operations\n");
10065     Hints.emitRemarkWithHints();
10066     return false;
10067   }
10068 
10069   bool UseInterleaved = TTI->enableInterleavedAccessVectorization();
10070   InterleavedAccessInfo IAI(PSE, L, DT, LI, LVL.getLAI());
10071 
10072   // If an override option has been passed in for interleaved accesses, use it.
10073   if (EnableInterleavedMemAccesses.getNumOccurrences() > 0)
10074     UseInterleaved = EnableInterleavedMemAccesses;
10075 
10076   // Analyze interleaved memory accesses.
10077   if (UseInterleaved) {
10078     IAI.analyzeInterleaving(useMaskedInterleavedAccesses(*TTI));
10079   }
10080 
10081   // Use the cost model.
10082   LoopVectorizationCostModel CM(SEL, L, PSE, LI, &LVL, *TTI, TLI, DB, AC, ORE,
10083                                 F, &Hints, IAI);
10084   CM.collectValuesToIgnore();
10085   CM.collectElementTypesForWidening();
10086 
10087   // Use the planner for vectorization.
10088   LoopVectorizationPlanner LVP(L, LI, TLI, TTI, &LVL, CM, IAI, PSE, Hints,
10089                                Requirements, ORE);
10090 
10091   // Get user vectorization factor and interleave count.
10092   ElementCount UserVF = Hints.getWidth();
10093   unsigned UserIC = Hints.getInterleave();
10094 
10095   // Plan how to best vectorize, return the best VF and its cost.
10096   Optional<VectorizationFactor> MaybeVF = LVP.plan(UserVF, UserIC);
10097 
10098   VectorizationFactor VF = VectorizationFactor::Disabled();
10099   unsigned IC = 1;
10100 
10101   if (MaybeVF) {
10102     VF = *MaybeVF;
10103     // Select the interleave count.
10104     IC = CM.selectInterleaveCount(VF.Width, *VF.Cost.getValue());
10105   }
10106 
10107   // Identify the diagnostic messages that should be produced.
10108   std::pair<StringRef, std::string> VecDiagMsg, IntDiagMsg;
10109   bool VectorizeLoop = true, InterleaveLoop = true;
10110   if (VF.Width.isScalar()) {
10111     LLVM_DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
10112     VecDiagMsg = std::make_pair(
10113         "VectorizationNotBeneficial",
10114         "the cost-model indicates that vectorization is not beneficial");
10115     VectorizeLoop = false;
10116   }
10117 
10118   if (!MaybeVF && UserIC > 1) {
10119     // Tell the user interleaving was avoided up-front, despite being explicitly
10120     // requested.
10121     LLVM_DEBUG(dbgs() << "LV: Ignoring UserIC, because vectorization and "
10122                          "interleaving should be avoided up front\n");
10123     IntDiagMsg = std::make_pair(
10124         "InterleavingAvoided",
10125         "Ignoring UserIC, because interleaving was avoided up front");
10126     InterleaveLoop = false;
10127   } else if (IC == 1 && UserIC <= 1) {
10128     // Tell the user interleaving is not beneficial.
10129     LLVM_DEBUG(dbgs() << "LV: Interleaving is not beneficial.\n");
10130     IntDiagMsg = std::make_pair(
10131         "InterleavingNotBeneficial",
10132         "the cost-model indicates that interleaving is not beneficial");
10133     InterleaveLoop = false;
10134     if (UserIC == 1) {
10135       IntDiagMsg.first = "InterleavingNotBeneficialAndDisabled";
10136       IntDiagMsg.second +=
10137           " and is explicitly disabled or interleave count is set to 1";
10138     }
10139   } else if (IC > 1 && UserIC == 1) {
10140     // Tell the user interleaving is beneficial, but it explicitly disabled.
10141     LLVM_DEBUG(
10142         dbgs() << "LV: Interleaving is beneficial but is explicitly disabled.");
10143     IntDiagMsg = std::make_pair(
10144         "InterleavingBeneficialButDisabled",
10145         "the cost-model indicates that interleaving is beneficial "
10146         "but is explicitly disabled or interleave count is set to 1");
10147     InterleaveLoop = false;
10148   }
10149 
10150   // Override IC if user provided an interleave count.
10151   IC = UserIC > 0 ? UserIC : IC;
10152 
10153   // Emit diagnostic messages, if any.
10154   const char *VAPassName = Hints.vectorizeAnalysisPassName();
10155   if (!VectorizeLoop && !InterleaveLoop) {
10156     // Do not vectorize or interleaving the loop.
10157     ORE->emit([&]() {
10158       return OptimizationRemarkMissed(VAPassName, VecDiagMsg.first,
10159                                       L->getStartLoc(), L->getHeader())
10160              << VecDiagMsg.second;
10161     });
10162     ORE->emit([&]() {
10163       return OptimizationRemarkMissed(LV_NAME, IntDiagMsg.first,
10164                                       L->getStartLoc(), L->getHeader())
10165              << IntDiagMsg.second;
10166     });
10167     return false;
10168   } else if (!VectorizeLoop && InterleaveLoop) {
10169     LLVM_DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
10170     ORE->emit([&]() {
10171       return OptimizationRemarkAnalysis(VAPassName, VecDiagMsg.first,
10172                                         L->getStartLoc(), L->getHeader())
10173              << VecDiagMsg.second;
10174     });
10175   } else if (VectorizeLoop && !InterleaveLoop) {
10176     LLVM_DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width
10177                       << ") in " << DebugLocStr << '\n');
10178     ORE->emit([&]() {
10179       return OptimizationRemarkAnalysis(LV_NAME, IntDiagMsg.first,
10180                                         L->getStartLoc(), L->getHeader())
10181              << IntDiagMsg.second;
10182     });
10183   } else if (VectorizeLoop && InterleaveLoop) {
10184     LLVM_DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width
10185                       << ") in " << DebugLocStr << '\n');
10186     LLVM_DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
10187   }
10188 
10189   bool DisableRuntimeUnroll = false;
10190   MDNode *OrigLoopID = L->getLoopID();
10191   {
10192     // Optimistically generate runtime checks. Drop them if they turn out to not
10193     // be profitable. Limit the scope of Checks, so the cleanup happens
10194     // immediately after vector codegeneration is done.
10195     GeneratedRTChecks Checks(*PSE.getSE(), DT, LI,
10196                              F->getParent()->getDataLayout());
10197     if (!VF.Width.isScalar() || IC > 1)
10198       Checks.Create(L, *LVL.getLAI(), PSE.getUnionPredicate());
10199     LVP.setBestPlan(VF.Width, IC);
10200 
10201     using namespace ore;
10202     if (!VectorizeLoop) {
10203       assert(IC > 1 && "interleave count should not be 1 or 0");
10204       // If we decided that it is not legal to vectorize the loop, then
10205       // interleave it.
10206       InnerLoopUnroller Unroller(L, PSE, LI, DT, TLI, TTI, AC, ORE, IC, &LVL,
10207                                  &CM, BFI, PSI, Checks);
10208       LVP.executePlan(Unroller, DT);
10209 
10210       ORE->emit([&]() {
10211         return OptimizationRemark(LV_NAME, "Interleaved", L->getStartLoc(),
10212                                   L->getHeader())
10213                << "interleaved loop (interleaved count: "
10214                << NV("InterleaveCount", IC) << ")";
10215       });
10216     } else {
10217       // If we decided that it is *legal* to vectorize the loop, then do it.
10218 
10219       // Consider vectorizing the epilogue too if it's profitable.
10220       VectorizationFactor EpilogueVF =
10221           CM.selectEpilogueVectorizationFactor(VF.Width, LVP);
10222       if (EpilogueVF.Width.isVector()) {
10223 
10224         // The first pass vectorizes the main loop and creates a scalar epilogue
10225         // to be vectorized by executing the plan (potentially with a different
10226         // factor) again shortly afterwards.
10227         EpilogueLoopVectorizationInfo EPI(VF.Width.getKnownMinValue(), IC,
10228                                           EpilogueVF.Width.getKnownMinValue(),
10229                                           1);
10230         EpilogueVectorizerMainLoop MainILV(L, PSE, LI, DT, TLI, TTI, AC, ORE,
10231                                            EPI, &LVL, &CM, BFI, PSI, Checks);
10232 
10233         LVP.setBestPlan(EPI.MainLoopVF, EPI.MainLoopUF);
10234         LVP.executePlan(MainILV, DT);
10235         ++LoopsVectorized;
10236 
10237         simplifyLoop(L, DT, LI, SE, AC, nullptr, false /* PreserveLCSSA */);
10238         formLCSSARecursively(*L, *DT, LI, SE);
10239 
10240         // Second pass vectorizes the epilogue and adjusts the control flow
10241         // edges from the first pass.
10242         LVP.setBestPlan(EPI.EpilogueVF, EPI.EpilogueUF);
10243         EPI.MainLoopVF = EPI.EpilogueVF;
10244         EPI.MainLoopUF = EPI.EpilogueUF;
10245         EpilogueVectorizerEpilogueLoop EpilogILV(L, PSE, LI, DT, TLI, TTI, AC,
10246                                                  ORE, EPI, &LVL, &CM, BFI, PSI,
10247                                                  Checks);
10248         LVP.executePlan(EpilogILV, DT);
10249         ++LoopsEpilogueVectorized;
10250 
10251         if (!MainILV.areSafetyChecksAdded())
10252           DisableRuntimeUnroll = true;
10253       } else {
10254         InnerLoopVectorizer LB(L, PSE, LI, DT, TLI, TTI, AC, ORE, VF.Width, IC,
10255                                &LVL, &CM, BFI, PSI, Checks);
10256         LVP.executePlan(LB, DT);
10257         ++LoopsVectorized;
10258 
10259         // Add metadata to disable runtime unrolling a scalar loop when there
10260         // are no runtime checks about strides and memory. A scalar loop that is
10261         // rarely used is not worth unrolling.
10262         if (!LB.areSafetyChecksAdded())
10263           DisableRuntimeUnroll = true;
10264       }
10265       // Report the vectorization decision.
10266       ORE->emit([&]() {
10267         return OptimizationRemark(LV_NAME, "Vectorized", L->getStartLoc(),
10268                                   L->getHeader())
10269                << "vectorized loop (vectorization width: "
10270                << NV("VectorizationFactor", VF.Width)
10271                << ", interleaved count: " << NV("InterleaveCount", IC) << ")";
10272       });
10273     }
10274 
10275     if (ORE->allowExtraAnalysis(LV_NAME))
10276       checkMixedPrecision(L, ORE);
10277   }
10278 
10279   Optional<MDNode *> RemainderLoopID =
10280       makeFollowupLoopID(OrigLoopID, {LLVMLoopVectorizeFollowupAll,
10281                                       LLVMLoopVectorizeFollowupEpilogue});
10282   if (RemainderLoopID.hasValue()) {
10283     L->setLoopID(RemainderLoopID.getValue());
10284   } else {
10285     if (DisableRuntimeUnroll)
10286       AddRuntimeUnrollDisableMetaData(L);
10287 
10288     // Mark the loop as already vectorized to avoid vectorizing again.
10289     Hints.setAlreadyVectorized();
10290   }
10291 
10292   assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()));
10293   return true;
10294 }
10295 
10296 LoopVectorizeResult LoopVectorizePass::runImpl(
10297     Function &F, ScalarEvolution &SE_, LoopInfo &LI_, TargetTransformInfo &TTI_,
10298     DominatorTree &DT_, BlockFrequencyInfo &BFI_, TargetLibraryInfo *TLI_,
10299     DemandedBits &DB_, AAResults &AA_, AssumptionCache &AC_,
10300     std::function<const LoopAccessInfo &(Loop &)> &GetLAA_,
10301     OptimizationRemarkEmitter &ORE_, ProfileSummaryInfo *PSI_) {
10302   SE = &SE_;
10303   LI = &LI_;
10304   TTI = &TTI_;
10305   DT = &DT_;
10306   BFI = &BFI_;
10307   TLI = TLI_;
10308   AA = &AA_;
10309   AC = &AC_;
10310   GetLAA = &GetLAA_;
10311   DB = &DB_;
10312   ORE = &ORE_;
10313   PSI = PSI_;
10314 
10315   // Don't attempt if
10316   // 1. the target claims to have no vector registers, and
10317   // 2. interleaving won't help ILP.
10318   //
10319   // The second condition is necessary because, even if the target has no
10320   // vector registers, loop vectorization may still enable scalar
10321   // interleaving.
10322   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true)) &&
10323       TTI->getMaxInterleaveFactor(1) < 2)
10324     return LoopVectorizeResult(false, false);
10325 
10326   bool Changed = false, CFGChanged = false;
10327 
10328   // The vectorizer requires loops to be in simplified form.
10329   // Since simplification may add new inner loops, it has to run before the
10330   // legality and profitability checks. This means running the loop vectorizer
10331   // will simplify all loops, regardless of whether anything end up being
10332   // vectorized.
10333   for (auto &L : *LI)
10334     Changed |= CFGChanged |=
10335         simplifyLoop(L, DT, LI, SE, AC, nullptr, false /* PreserveLCSSA */);
10336 
10337   // Build up a worklist of inner-loops to vectorize. This is necessary as
10338   // the act of vectorizing or partially unrolling a loop creates new loops
10339   // and can invalidate iterators across the loops.
10340   SmallVector<Loop *, 8> Worklist;
10341 
10342   for (Loop *L : *LI)
10343     collectSupportedLoops(*L, LI, ORE, Worklist);
10344 
10345   LoopsAnalyzed += Worklist.size();
10346 
10347   // Now walk the identified inner loops.
10348   while (!Worklist.empty()) {
10349     Loop *L = Worklist.pop_back_val();
10350 
10351     // For the inner loops we actually process, form LCSSA to simplify the
10352     // transform.
10353     Changed |= formLCSSARecursively(*L, *DT, LI, SE);
10354 
10355     Changed |= CFGChanged |= processLoop(L);
10356   }
10357 
10358   // Process each loop nest in the function.
10359   return LoopVectorizeResult(Changed, CFGChanged);
10360 }
10361 
10362 PreservedAnalyses LoopVectorizePass::run(Function &F,
10363                                          FunctionAnalysisManager &AM) {
10364     auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
10365     auto &LI = AM.getResult<LoopAnalysis>(F);
10366     auto &TTI = AM.getResult<TargetIRAnalysis>(F);
10367     auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
10368     auto &BFI = AM.getResult<BlockFrequencyAnalysis>(F);
10369     auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
10370     auto &AA = AM.getResult<AAManager>(F);
10371     auto &AC = AM.getResult<AssumptionAnalysis>(F);
10372     auto &DB = AM.getResult<DemandedBitsAnalysis>(F);
10373     auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
10374     MemorySSA *MSSA = EnableMSSALoopDependency
10375                           ? &AM.getResult<MemorySSAAnalysis>(F).getMSSA()
10376                           : nullptr;
10377 
10378     auto &LAM = AM.getResult<LoopAnalysisManagerFunctionProxy>(F).getManager();
10379     std::function<const LoopAccessInfo &(Loop &)> GetLAA =
10380         [&](Loop &L) -> const LoopAccessInfo & {
10381       LoopStandardAnalysisResults AR = {AA,  AC,  DT,      LI,  SE,
10382                                         TLI, TTI, nullptr, MSSA};
10383       return LAM.getResult<LoopAccessAnalysis>(L, AR);
10384     };
10385     auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
10386     ProfileSummaryInfo *PSI =
10387         MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
10388     LoopVectorizeResult Result =
10389         runImpl(F, SE, LI, TTI, DT, BFI, &TLI, DB, AA, AC, GetLAA, ORE, PSI);
10390     if (!Result.MadeAnyChange)
10391       return PreservedAnalyses::all();
10392     PreservedAnalyses PA;
10393 
10394     // We currently do not preserve loopinfo/dominator analyses with outer loop
10395     // vectorization. Until this is addressed, mark these analyses as preserved
10396     // only for non-VPlan-native path.
10397     // TODO: Preserve Loop and Dominator analyses for VPlan-native path.
10398     if (!EnableVPlanNativePath) {
10399       PA.preserve<LoopAnalysis>();
10400       PA.preserve<DominatorTreeAnalysis>();
10401     }
10402     if (!Result.MadeCFGChange)
10403       PA.preserveSet<CFGAnalyses>();
10404     return PA;
10405 }
10406