xref: /netbsd-src/external/apache2/llvm/dist/llvm/lib/Transforms/Vectorize/LoopVectorize.cpp (revision 82d56013d7b633d116a93943de88e08335357a7c)
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/SmallVector.h"
74 #include "llvm/ADT/Statistic.h"
75 #include "llvm/ADT/StringRef.h"
76 #include "llvm/ADT/Twine.h"
77 #include "llvm/ADT/iterator_range.h"
78 #include "llvm/Analysis/AssumptionCache.h"
79 #include "llvm/Analysis/BasicAliasAnalysis.h"
80 #include "llvm/Analysis/BlockFrequencyInfo.h"
81 #include "llvm/Analysis/CFG.h"
82 #include "llvm/Analysis/CodeMetrics.h"
83 #include "llvm/Analysis/DemandedBits.h"
84 #include "llvm/Analysis/GlobalsModRef.h"
85 #include "llvm/Analysis/LoopAccessAnalysis.h"
86 #include "llvm/Analysis/LoopAnalysisManager.h"
87 #include "llvm/Analysis/LoopInfo.h"
88 #include "llvm/Analysis/LoopIterator.h"
89 #include "llvm/Analysis/MemorySSA.h"
90 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
91 #include "llvm/Analysis/ProfileSummaryInfo.h"
92 #include "llvm/Analysis/ScalarEvolution.h"
93 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
94 #include "llvm/Analysis/TargetLibraryInfo.h"
95 #include "llvm/Analysis/TargetTransformInfo.h"
96 #include "llvm/Analysis/VectorUtils.h"
97 #include "llvm/IR/Attributes.h"
98 #include "llvm/IR/BasicBlock.h"
99 #include "llvm/IR/CFG.h"
100 #include "llvm/IR/Constant.h"
101 #include "llvm/IR/Constants.h"
102 #include "llvm/IR/DataLayout.h"
103 #include "llvm/IR/DebugInfoMetadata.h"
104 #include "llvm/IR/DebugLoc.h"
105 #include "llvm/IR/DerivedTypes.h"
106 #include "llvm/IR/DiagnosticInfo.h"
107 #include "llvm/IR/Dominators.h"
108 #include "llvm/IR/Function.h"
109 #include "llvm/IR/IRBuilder.h"
110 #include "llvm/IR/InstrTypes.h"
111 #include "llvm/IR/Instruction.h"
112 #include "llvm/IR/Instructions.h"
113 #include "llvm/IR/IntrinsicInst.h"
114 #include "llvm/IR/Intrinsics.h"
115 #include "llvm/IR/LLVMContext.h"
116 #include "llvm/IR/Metadata.h"
117 #include "llvm/IR/Module.h"
118 #include "llvm/IR/Operator.h"
119 #include "llvm/IR/PatternMatch.h"
120 #include "llvm/IR/Type.h"
121 #include "llvm/IR/Use.h"
122 #include "llvm/IR/User.h"
123 #include "llvm/IR/Value.h"
124 #include "llvm/IR/ValueHandle.h"
125 #include "llvm/IR/Verifier.h"
126 #include "llvm/InitializePasses.h"
127 #include "llvm/Pass.h"
128 #include "llvm/Support/Casting.h"
129 #include "llvm/Support/CommandLine.h"
130 #include "llvm/Support/Compiler.h"
131 #include "llvm/Support/Debug.h"
132 #include "llvm/Support/ErrorHandling.h"
133 #include "llvm/Support/InstructionCost.h"
134 #include "llvm/Support/MathExtras.h"
135 #include "llvm/Support/raw_ostream.h"
136 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
137 #include "llvm/Transforms/Utils/InjectTLIMappings.h"
138 #include "llvm/Transforms/Utils/LoopSimplify.h"
139 #include "llvm/Transforms/Utils/LoopUtils.h"
140 #include "llvm/Transforms/Utils/LoopVersioning.h"
141 #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
142 #include "llvm/Transforms/Utils/SizeOpts.h"
143 #include "llvm/Transforms/Vectorize/LoopVectorizationLegality.h"
144 #include <algorithm>
145 #include <cassert>
146 #include <cstdint>
147 #include <cstdlib>
148 #include <functional>
149 #include <iterator>
150 #include <limits>
151 #include <memory>
152 #include <string>
153 #include <tuple>
154 #include <utility>
155 
156 using namespace llvm;
157 
158 #define LV_NAME "loop-vectorize"
159 #define DEBUG_TYPE LV_NAME
160 
161 #ifndef NDEBUG
162 const char VerboseDebug[] = DEBUG_TYPE "-verbose";
163 #endif
164 
165 /// @{
166 /// Metadata attribute names
167 const char LLVMLoopVectorizeFollowupAll[] = "llvm.loop.vectorize.followup_all";
168 const char LLVMLoopVectorizeFollowupVectorized[] =
169     "llvm.loop.vectorize.followup_vectorized";
170 const char LLVMLoopVectorizeFollowupEpilogue[] =
171     "llvm.loop.vectorize.followup_epilogue";
172 /// @}
173 
174 STATISTIC(LoopsVectorized, "Number of loops vectorized");
175 STATISTIC(LoopsAnalyzed, "Number of loops analyzed for vectorization");
176 STATISTIC(LoopsEpilogueVectorized, "Number of epilogues vectorized");
177 
178 static cl::opt<bool> EnableEpilogueVectorization(
179     "enable-epilogue-vectorization", cl::init(true), cl::Hidden,
180     cl::desc("Enable vectorization of epilogue loops."));
181 
182 static cl::opt<unsigned> EpilogueVectorizationForceVF(
183     "epilogue-vectorization-force-VF", cl::init(1), cl::Hidden,
184     cl::desc("When epilogue vectorization is enabled, and a value greater than "
185              "1 is specified, forces the given VF for all applicable epilogue "
186              "loops."));
187 
188 static cl::opt<unsigned> EpilogueVectorizationMinVF(
189     "epilogue-vectorization-minimum-VF", cl::init(16), cl::Hidden,
190     cl::desc("Only loops with vectorization factor equal to or larger than "
191              "the specified value are considered for epilogue vectorization."));
192 
193 /// Loops with a known constant trip count below this number are vectorized only
194 /// if no scalar iteration overheads are incurred.
195 static cl::opt<unsigned> TinyTripCountVectorThreshold(
196     "vectorizer-min-trip-count", cl::init(16), cl::Hidden,
197     cl::desc("Loops with a constant trip count that is smaller than this "
198              "value are vectorized only if no scalar iteration overheads "
199              "are incurred."));
200 
201 static cl::opt<unsigned> PragmaVectorizeMemoryCheckThreshold(
202     "pragma-vectorize-memory-check-threshold", cl::init(128), cl::Hidden,
203     cl::desc("The maximum allowed number of runtime memory checks with a "
204              "vectorize(enable) pragma."));
205 
206 // Option prefer-predicate-over-epilogue indicates that an epilogue is undesired,
207 // that predication is preferred, and this lists all options. I.e., the
208 // vectorizer will try to fold the tail-loop (epilogue) into the vector body
209 // and predicate the instructions accordingly. If tail-folding fails, there are
210 // different fallback strategies depending on these values:
211 namespace PreferPredicateTy {
212   enum Option {
213     ScalarEpilogue = 0,
214     PredicateElseScalarEpilogue,
215     PredicateOrDontVectorize
216   };
217 } // namespace PreferPredicateTy
218 
219 static cl::opt<PreferPredicateTy::Option> PreferPredicateOverEpilogue(
220     "prefer-predicate-over-epilogue",
221     cl::init(PreferPredicateTy::ScalarEpilogue),
222     cl::Hidden,
223     cl::desc("Tail-folding and predication preferences over creating a scalar "
224              "epilogue loop."),
225     cl::values(clEnumValN(PreferPredicateTy::ScalarEpilogue,
226                          "scalar-epilogue",
227                          "Don't tail-predicate loops, create scalar epilogue"),
228               clEnumValN(PreferPredicateTy::PredicateElseScalarEpilogue,
229                          "predicate-else-scalar-epilogue",
230                          "prefer tail-folding, create scalar epilogue if tail "
231                          "folding fails."),
232               clEnumValN(PreferPredicateTy::PredicateOrDontVectorize,
233                          "predicate-dont-vectorize",
234                          "prefers tail-folding, don't attempt vectorization if "
235                          "tail-folding fails.")));
236 
237 static cl::opt<bool> MaximizeBandwidth(
238     "vectorizer-maximize-bandwidth", cl::init(false), cl::Hidden,
239     cl::desc("Maximize bandwidth when selecting vectorization factor which "
240              "will be determined by the smallest type in loop."));
241 
242 static cl::opt<bool> EnableInterleavedMemAccesses(
243     "enable-interleaved-mem-accesses", cl::init(false), cl::Hidden,
244     cl::desc("Enable vectorization on interleaved memory accesses in a loop"));
245 
246 /// An interleave-group may need masking if it resides in a block that needs
247 /// predication, or in order to mask away gaps.
248 static cl::opt<bool> EnableMaskedInterleavedMemAccesses(
249     "enable-masked-interleaved-mem-accesses", cl::init(false), cl::Hidden,
250     cl::desc("Enable vectorization on masked interleaved memory accesses in a loop"));
251 
252 static cl::opt<unsigned> TinyTripCountInterleaveThreshold(
253     "tiny-trip-count-interleave-threshold", cl::init(128), cl::Hidden,
254     cl::desc("We don't interleave loops with a estimated constant trip count "
255              "below this number"));
256 
257 static cl::opt<unsigned> ForceTargetNumScalarRegs(
258     "force-target-num-scalar-regs", cl::init(0), cl::Hidden,
259     cl::desc("A flag that overrides the target's number of scalar registers."));
260 
261 static cl::opt<unsigned> ForceTargetNumVectorRegs(
262     "force-target-num-vector-regs", cl::init(0), cl::Hidden,
263     cl::desc("A flag that overrides the target's number of vector registers."));
264 
265 static cl::opt<unsigned> ForceTargetMaxScalarInterleaveFactor(
266     "force-target-max-scalar-interleave", cl::init(0), cl::Hidden,
267     cl::desc("A flag that overrides the target's max interleave factor for "
268              "scalar loops."));
269 
270 static cl::opt<unsigned> ForceTargetMaxVectorInterleaveFactor(
271     "force-target-max-vector-interleave", cl::init(0), cl::Hidden,
272     cl::desc("A flag that overrides the target's max interleave factor for "
273              "vectorized loops."));
274 
275 static cl::opt<unsigned> ForceTargetInstructionCost(
276     "force-target-instruction-cost", cl::init(0), cl::Hidden,
277     cl::desc("A flag that overrides the target's expected cost for "
278              "an instruction to a single constant value. Mostly "
279              "useful for getting consistent testing."));
280 
281 static cl::opt<bool> ForceTargetSupportsScalableVectors(
282     "force-target-supports-scalable-vectors", cl::init(false), cl::Hidden,
283     cl::desc(
284         "Pretend that scalable vectors are supported, even if the target does "
285         "not support them. This flag should only be used for testing."));
286 
287 static cl::opt<unsigned> SmallLoopCost(
288     "small-loop-cost", cl::init(20), cl::Hidden,
289     cl::desc(
290         "The cost of a loop that is considered 'small' by the interleaver."));
291 
292 static cl::opt<bool> LoopVectorizeWithBlockFrequency(
293     "loop-vectorize-with-block-frequency", cl::init(true), cl::Hidden,
294     cl::desc("Enable the use of the block frequency analysis to access PGO "
295              "heuristics minimizing code growth in cold regions and being more "
296              "aggressive in hot regions."));
297 
298 // Runtime interleave loops for load/store throughput.
299 static cl::opt<bool> EnableLoadStoreRuntimeInterleave(
300     "enable-loadstore-runtime-interleave", cl::init(true), cl::Hidden,
301     cl::desc(
302         "Enable runtime interleaving until load/store ports are saturated"));
303 
304 /// Interleave small loops with scalar reductions.
305 static cl::opt<bool> InterleaveSmallLoopScalarReduction(
306     "interleave-small-loop-scalar-reduction", cl::init(false), cl::Hidden,
307     cl::desc("Enable interleaving for loops with small iteration counts that "
308              "contain scalar reductions to expose ILP."));
309 
310 /// The number of stores in a loop that are allowed to need predication.
311 static cl::opt<unsigned> NumberOfStoresToPredicate(
312     "vectorize-num-stores-pred", cl::init(1), cl::Hidden,
313     cl::desc("Max number of stores to be predicated behind an if."));
314 
315 static cl::opt<bool> EnableIndVarRegisterHeur(
316     "enable-ind-var-reg-heur", cl::init(true), cl::Hidden,
317     cl::desc("Count the induction variable only once when interleaving"));
318 
319 static cl::opt<bool> EnableCondStoresVectorization(
320     "enable-cond-stores-vec", cl::init(true), cl::Hidden,
321     cl::desc("Enable if predication of stores during vectorization."));
322 
323 static cl::opt<unsigned> MaxNestedScalarReductionIC(
324     "max-nested-scalar-reduction-interleave", cl::init(2), cl::Hidden,
325     cl::desc("The maximum interleave count to use when interleaving a scalar "
326              "reduction in a nested loop."));
327 
328 static cl::opt<bool>
329     PreferInLoopReductions("prefer-inloop-reductions", cl::init(false),
330                            cl::Hidden,
331                            cl::desc("Prefer in-loop vector reductions, "
332                                     "overriding the targets preference."));
333 
334 cl::opt<bool> EnableStrictReductions(
335     "enable-strict-reductions", cl::init(false), cl::Hidden,
336     cl::desc("Enable the vectorisation of loops with in-order (strict) "
337              "FP reductions"));
338 
339 static cl::opt<bool> PreferPredicatedReductionSelect(
340     "prefer-predicated-reduction-select", cl::init(false), cl::Hidden,
341     cl::desc(
342         "Prefer predicating a reduction operation over an after loop select."));
343 
344 cl::opt<bool> EnableVPlanNativePath(
345     "enable-vplan-native-path", cl::init(false), cl::Hidden,
346     cl::desc("Enable VPlan-native vectorization path with "
347              "support for outer loop vectorization."));
348 
349 // FIXME: Remove this switch once we have divergence analysis. Currently we
350 // assume divergent non-backedge branches when this switch is true.
351 cl::opt<bool> EnableVPlanPredication(
352     "enable-vplan-predication", cl::init(false), cl::Hidden,
353     cl::desc("Enable VPlan-native vectorization path predicator with "
354              "support for outer loop vectorization."));
355 
356 // This flag enables the stress testing of the VPlan H-CFG construction in the
357 // VPlan-native vectorization path. It must be used in conjuction with
358 // -enable-vplan-native-path. -vplan-verify-hcfg can also be used to enable the
359 // verification of the H-CFGs built.
360 static cl::opt<bool> VPlanBuildStressTest(
361     "vplan-build-stress-test", cl::init(false), cl::Hidden,
362     cl::desc(
363         "Build VPlan for every supported loop nest in the function and bail "
364         "out right after the build (stress test the VPlan H-CFG construction "
365         "in the VPlan-native vectorization path)."));
366 
367 cl::opt<bool> llvm::EnableLoopInterleaving(
368     "interleave-loops", cl::init(true), cl::Hidden,
369     cl::desc("Enable loop interleaving in Loop vectorization passes"));
370 cl::opt<bool> llvm::EnableLoopVectorization(
371     "vectorize-loops", cl::init(true), cl::Hidden,
372     cl::desc("Run the Loop vectorization passes"));
373 
374 cl::opt<bool> PrintVPlansInDotFormat(
375     "vplan-print-in-dot-format", cl::init(false), cl::Hidden,
376     cl::desc("Use dot format instead of plain text when dumping VPlans"));
377 
378 /// A helper function that returns the type of loaded or stored value.
getMemInstValueType(Value * I)379 static Type *getMemInstValueType(Value *I) {
380   assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
381          "Expected Load or Store instruction");
382   if (auto *LI = dyn_cast<LoadInst>(I))
383     return LI->getType();
384   return cast<StoreInst>(I)->getValueOperand()->getType();
385 }
386 
387 /// A helper function that returns true if the given type is irregular. The
388 /// type is irregular if its allocated size doesn't equal the store size of an
389 /// element of the corresponding vector type.
hasIrregularType(Type * Ty,const DataLayout & DL)390 static bool hasIrregularType(Type *Ty, const DataLayout &DL) {
391   // Determine if an array of N elements of type Ty is "bitcast compatible"
392   // with a <N x Ty> vector.
393   // This is only true if there is no padding between the array elements.
394   return DL.getTypeAllocSizeInBits(Ty) != DL.getTypeSizeInBits(Ty);
395 }
396 
397 /// A helper function that returns the reciprocal of the block probability of
398 /// predicated blocks. If we return X, we are assuming the predicated block
399 /// will execute once for every X iterations of the loop header.
400 ///
401 /// TODO: We should use actual block probability here, if available. Currently,
402 ///       we always assume predicated blocks have a 50% chance of executing.
getReciprocalPredBlockProb()403 static unsigned getReciprocalPredBlockProb() { return 2; }
404 
405 /// A helper function that returns an integer or floating-point constant with
406 /// value C.
getSignedIntOrFpConstant(Type * Ty,int64_t C)407 static Constant *getSignedIntOrFpConstant(Type *Ty, int64_t C) {
408   return Ty->isIntegerTy() ? ConstantInt::getSigned(Ty, C)
409                            : ConstantFP::get(Ty, C);
410 }
411 
412 /// Returns "best known" trip count for the specified loop \p L as defined by
413 /// the following procedure:
414 ///   1) Returns exact trip count if it is known.
415 ///   2) Returns expected trip count according to profile data if any.
416 ///   3) Returns upper bound estimate if it is known.
417 ///   4) Returns None if all of the above failed.
getSmallBestKnownTC(ScalarEvolution & SE,Loop * L)418 static Optional<unsigned> getSmallBestKnownTC(ScalarEvolution &SE, Loop *L) {
419   // Check if exact trip count is known.
420   if (unsigned ExpectedTC = SE.getSmallConstantTripCount(L))
421     return ExpectedTC;
422 
423   // Check if there is an expected trip count available from profile data.
424   if (LoopVectorizeWithBlockFrequency)
425     if (auto EstimatedTC = getLoopEstimatedTripCount(L))
426       return EstimatedTC;
427 
428   // Check if upper bound estimate is known.
429   if (unsigned ExpectedTC = SE.getSmallConstantMaxTripCount(L))
430     return ExpectedTC;
431 
432   return None;
433 }
434 
435 // Forward declare GeneratedRTChecks.
436 class GeneratedRTChecks;
437 
438 namespace llvm {
439 
440 /// InnerLoopVectorizer vectorizes loops which contain only one basic
441 /// block to a specified vectorization factor (VF).
442 /// This class performs the widening of scalars into vectors, or multiple
443 /// scalars. This class also implements the following features:
444 /// * It inserts an epilogue loop for handling loops that don't have iteration
445 ///   counts that are known to be a multiple of the vectorization factor.
446 /// * It handles the code generation for reduction variables.
447 /// * Scalarization (implementation using scalars) of un-vectorizable
448 ///   instructions.
449 /// InnerLoopVectorizer does not perform any vectorization-legality
450 /// checks, and relies on the caller to check for the different legality
451 /// aspects. The InnerLoopVectorizer relies on the
452 /// LoopVectorizationLegality class to provide information about the induction
453 /// and reduction variables that were found to a given vectorization factor.
454 class InnerLoopVectorizer {
455 public:
InnerLoopVectorizer(Loop * OrigLoop,PredicatedScalarEvolution & PSE,LoopInfo * LI,DominatorTree * DT,const TargetLibraryInfo * TLI,const TargetTransformInfo * TTI,AssumptionCache * AC,OptimizationRemarkEmitter * ORE,ElementCount VecWidth,unsigned UnrollFactor,LoopVectorizationLegality * LVL,LoopVectorizationCostModel * CM,BlockFrequencyInfo * BFI,ProfileSummaryInfo * PSI,GeneratedRTChecks & RTChecks)456   InnerLoopVectorizer(Loop *OrigLoop, PredicatedScalarEvolution &PSE,
457                       LoopInfo *LI, DominatorTree *DT,
458                       const TargetLibraryInfo *TLI,
459                       const TargetTransformInfo *TTI, AssumptionCache *AC,
460                       OptimizationRemarkEmitter *ORE, ElementCount VecWidth,
461                       unsigned UnrollFactor, LoopVectorizationLegality *LVL,
462                       LoopVectorizationCostModel *CM, BlockFrequencyInfo *BFI,
463                       ProfileSummaryInfo *PSI, GeneratedRTChecks &RTChecks)
464       : OrigLoop(OrigLoop), PSE(PSE), LI(LI), DT(DT), TLI(TLI), TTI(TTI),
465         AC(AC), ORE(ORE), VF(VecWidth), UF(UnrollFactor),
466         Builder(PSE.getSE()->getContext()), Legal(LVL), Cost(CM), BFI(BFI),
467         PSI(PSI), RTChecks(RTChecks) {
468     // Query this against the original loop and save it here because the profile
469     // of the original loop header may change as the transformation happens.
470     OptForSizeBasedOnProfile = llvm::shouldOptimizeForSize(
471         OrigLoop->getHeader(), PSI, BFI, PGSOQueryType::IRPass);
472   }
473 
474   virtual ~InnerLoopVectorizer() = default;
475 
476   /// Create a new empty loop that will contain vectorized instructions later
477   /// on, while the old loop will be used as the scalar remainder. Control flow
478   /// is generated around the vectorized (and scalar epilogue) loops consisting
479   /// of various checks and bypasses. Return the pre-header block of the new
480   /// loop.
481   /// In the case of epilogue vectorization, this function is overriden to
482   /// handle the more complex control flow around the loops.
483   virtual BasicBlock *createVectorizedLoopSkeleton();
484 
485   /// Widen a single instruction within the innermost loop.
486   void widenInstruction(Instruction &I, VPValue *Def, VPUser &Operands,
487                         VPTransformState &State);
488 
489   /// Widen a single call instruction within the innermost loop.
490   void widenCallInstruction(CallInst &I, VPValue *Def, VPUser &ArgOperands,
491                             VPTransformState &State);
492 
493   /// Widen a single select instruction within the innermost loop.
494   void widenSelectInstruction(SelectInst &I, VPValue *VPDef, VPUser &Operands,
495                               bool InvariantCond, VPTransformState &State);
496 
497   /// Fix the vectorized code, taking care of header phi's, live-outs, and more.
498   void fixVectorizedLoop(VPTransformState &State);
499 
500   // Return true if any runtime check is added.
areSafetyChecksAdded()501   bool areSafetyChecksAdded() { return AddedSafetyChecks; }
502 
503   /// A type for vectorized values in the new loop. Each value from the
504   /// original loop, when vectorized, is represented by UF vector values in the
505   /// new unrolled loop, where UF is the unroll factor.
506   using VectorParts = SmallVector<Value *, 2>;
507 
508   /// Vectorize a single GetElementPtrInst based on information gathered and
509   /// decisions taken during planning.
510   void widenGEP(GetElementPtrInst *GEP, VPValue *VPDef, VPUser &Indices,
511                 unsigned UF, ElementCount VF, bool IsPtrLoopInvariant,
512                 SmallBitVector &IsIndexLoopInvariant, VPTransformState &State);
513 
514   /// Vectorize a single PHINode in a block. This method handles the induction
515   /// variable canonicalization. It supports both VF = 1 for unrolled loops and
516   /// arbitrary length vectors.
517   void widenPHIInstruction(Instruction *PN, RecurrenceDescriptor *RdxDesc,
518                            VPWidenPHIRecipe *PhiR, VPTransformState &State);
519 
520   /// A helper function to scalarize a single Instruction in the innermost loop.
521   /// Generates a sequence of scalar instances for each lane between \p MinLane
522   /// and \p MaxLane, times each part between \p MinPart and \p MaxPart,
523   /// inclusive. Uses the VPValue operands from \p Operands instead of \p
524   /// Instr's operands.
525   void scalarizeInstruction(Instruction *Instr, VPValue *Def, VPUser &Operands,
526                             const VPIteration &Instance, bool IfPredicateInstr,
527                             VPTransformState &State);
528 
529   /// Widen an integer or floating-point induction variable \p IV. If \p Trunc
530   /// is provided, the integer induction variable will first be truncated to
531   /// the corresponding type.
532   void widenIntOrFpInduction(PHINode *IV, Value *Start, TruncInst *Trunc,
533                              VPValue *Def, VPValue *CastDef,
534                              VPTransformState &State);
535 
536   /// Construct the vector value of a scalarized value \p V one lane at a time.
537   void packScalarIntoVectorValue(VPValue *Def, const VPIteration &Instance,
538                                  VPTransformState &State);
539 
540   /// Try to vectorize interleaved access group \p Group with the base address
541   /// given in \p Addr, optionally masking the vector operations if \p
542   /// BlockInMask is non-null. Use \p State to translate given VPValues to IR
543   /// values in the vectorized loop.
544   void vectorizeInterleaveGroup(const InterleaveGroup<Instruction> *Group,
545                                 ArrayRef<VPValue *> VPDefs,
546                                 VPTransformState &State, VPValue *Addr,
547                                 ArrayRef<VPValue *> StoredValues,
548                                 VPValue *BlockInMask = nullptr);
549 
550   /// Vectorize Load and Store instructions with the base address given in \p
551   /// Addr, optionally masking the vector operations if \p BlockInMask is
552   /// non-null. Use \p State to translate given VPValues to IR values in the
553   /// vectorized loop.
554   void vectorizeMemoryInstruction(Instruction *Instr, VPTransformState &State,
555                                   VPValue *Def, VPValue *Addr,
556                                   VPValue *StoredValue, VPValue *BlockInMask);
557 
558   /// Set the debug location in the builder using the debug location in
559   /// the instruction.
560   void setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr);
561 
562   /// Fix the non-induction PHIs in the OrigPHIsToFix vector.
563   void fixNonInductionPHIs(VPTransformState &State);
564 
565   /// Create a broadcast instruction. This method generates a broadcast
566   /// instruction (shuffle) for loop invariant values and for the induction
567   /// value. If this is the induction variable then we extend it to N, N+1, ...
568   /// this is needed because each iteration in the loop corresponds to a SIMD
569   /// element.
570   virtual Value *getBroadcastInstrs(Value *V);
571 
572 protected:
573   friend class LoopVectorizationPlanner;
574 
575   /// A small list of PHINodes.
576   using PhiVector = SmallVector<PHINode *, 4>;
577 
578   /// A type for scalarized values in the new loop. Each value from the
579   /// original loop, when scalarized, is represented by UF x VF scalar values
580   /// in the new unrolled loop, where UF is the unroll factor and VF is the
581   /// vectorization factor.
582   using ScalarParts = SmallVector<SmallVector<Value *, 4>, 2>;
583 
584   /// Set up the values of the IVs correctly when exiting the vector loop.
585   void fixupIVUsers(PHINode *OrigPhi, const InductionDescriptor &II,
586                     Value *CountRoundDown, Value *EndValue,
587                     BasicBlock *MiddleBlock);
588 
589   /// Create a new induction variable inside L.
590   PHINode *createInductionVariable(Loop *L, Value *Start, Value *End,
591                                    Value *Step, Instruction *DL);
592 
593   /// Handle all cross-iteration phis in the header.
594   void fixCrossIterationPHIs(VPTransformState &State);
595 
596   /// Fix a first-order recurrence. This is the second phase of vectorizing
597   /// this phi node.
598   void fixFirstOrderRecurrence(PHINode *Phi, VPTransformState &State);
599 
600   /// Fix a reduction cross-iteration phi. This is the second phase of
601   /// vectorizing this phi node.
602   void fixReduction(VPWidenPHIRecipe *Phi, VPTransformState &State);
603 
604   /// Clear NSW/NUW flags from reduction instructions if necessary.
605   void clearReductionWrapFlags(RecurrenceDescriptor &RdxDesc,
606                                VPTransformState &State);
607 
608   /// Fixup the LCSSA phi nodes in the unique exit block.  This simply
609   /// means we need to add the appropriate incoming value from the middle
610   /// block as exiting edges from the scalar epilogue loop (if present) are
611   /// already in place, and we exit the vector loop exclusively to the middle
612   /// block.
613   void fixLCSSAPHIs(VPTransformState &State);
614 
615   /// Iteratively sink the scalarized operands of a predicated instruction into
616   /// the block that was created for it.
617   void sinkScalarOperands(Instruction *PredInst);
618 
619   /// Shrinks vector element sizes to the smallest bitwidth they can be legally
620   /// represented as.
621   void truncateToMinimalBitwidths(VPTransformState &State);
622 
623   /// This function adds
624   /// (StartIdx * Step, (StartIdx + 1) * Step, (StartIdx + 2) * Step, ...)
625   /// to each vector element of Val. The sequence starts at StartIndex.
626   /// \p Opcode is relevant for FP induction variable.
627   virtual Value *getStepVector(Value *Val, int StartIdx, Value *Step,
628                                Instruction::BinaryOps Opcode =
629                                Instruction::BinaryOpsEnd);
630 
631   /// Compute scalar induction steps. \p ScalarIV is the scalar induction
632   /// variable on which to base the steps, \p Step is the size of the step, and
633   /// \p EntryVal is the value from the original loop that maps to the steps.
634   /// Note that \p EntryVal doesn't have to be an induction variable - it
635   /// can also be a truncate instruction.
636   void buildScalarSteps(Value *ScalarIV, Value *Step, Instruction *EntryVal,
637                         const InductionDescriptor &ID, VPValue *Def,
638                         VPValue *CastDef, VPTransformState &State);
639 
640   /// Create a vector induction phi node based on an existing scalar one. \p
641   /// EntryVal is the value from the original loop that maps to the vector phi
642   /// node, and \p Step is the loop-invariant step. If \p EntryVal is a
643   /// truncate instruction, instead of widening the original IV, we widen a
644   /// version of the IV truncated to \p EntryVal's type.
645   void createVectorIntOrFpInductionPHI(const InductionDescriptor &II,
646                                        Value *Step, Value *Start,
647                                        Instruction *EntryVal, VPValue *Def,
648                                        VPValue *CastDef,
649                                        VPTransformState &State);
650 
651   /// Returns true if an instruction \p I should be scalarized instead of
652   /// vectorized for the chosen vectorization factor.
653   bool shouldScalarizeInstruction(Instruction *I) const;
654 
655   /// Returns true if we should generate a scalar version of \p IV.
656   bool needsScalarInduction(Instruction *IV) const;
657 
658   /// If there is a cast involved in the induction variable \p ID, which should
659   /// be ignored in the vectorized loop body, this function records the
660   /// VectorLoopValue of the respective Phi also as the VectorLoopValue of the
661   /// cast. We had already proved that the casted Phi is equal to the uncasted
662   /// Phi in the vectorized loop (under a runtime guard), and therefore
663   /// there is no need to vectorize the cast - the same value can be used in the
664   /// vector loop for both the Phi and the cast.
665   /// If \p VectorLoopValue is a scalarized value, \p Lane is also specified,
666   /// Otherwise, \p VectorLoopValue is a widened/vectorized value.
667   ///
668   /// \p EntryVal is the value from the original loop that maps to the vector
669   /// phi node and is used to distinguish what is the IV currently being
670   /// processed - original one (if \p EntryVal is a phi corresponding to the
671   /// original IV) or the "newly-created" one based on the proof mentioned above
672   /// (see also buildScalarSteps() and createVectorIntOrFPInductionPHI()). In the
673   /// latter case \p EntryVal is a TruncInst and we must not record anything for
674   /// that IV, but it's error-prone to expect callers of this routine to care
675   /// about that, hence this explicit parameter.
676   void recordVectorLoopValueForInductionCast(
677       const InductionDescriptor &ID, const Instruction *EntryVal,
678       Value *VectorLoopValue, VPValue *CastDef, VPTransformState &State,
679       unsigned Part, unsigned Lane = UINT_MAX);
680 
681   /// Generate a shuffle sequence that will reverse the vector Vec.
682   virtual Value *reverseVector(Value *Vec);
683 
684   /// Returns (and creates if needed) the original loop trip count.
685   Value *getOrCreateTripCount(Loop *NewLoop);
686 
687   /// Returns (and creates if needed) the trip count of the widened loop.
688   Value *getOrCreateVectorTripCount(Loop *NewLoop);
689 
690   /// Returns a bitcasted value to the requested vector type.
691   /// Also handles bitcasts of vector<float> <-> vector<pointer> types.
692   Value *createBitOrPointerCast(Value *V, VectorType *DstVTy,
693                                 const DataLayout &DL);
694 
695   /// Emit a bypass check to see if the vector trip count is zero, including if
696   /// it overflows.
697   void emitMinimumIterationCountCheck(Loop *L, BasicBlock *Bypass);
698 
699   /// Emit a bypass check to see if all of the SCEV assumptions we've
700   /// had to make are correct. Returns the block containing the checks or
701   /// nullptr if no checks have been added.
702   BasicBlock *emitSCEVChecks(Loop *L, BasicBlock *Bypass);
703 
704   /// Emit bypass checks to check any memory assumptions we may have made.
705   /// Returns the block containing the checks or nullptr if no checks have been
706   /// added.
707   BasicBlock *emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass);
708 
709   /// Compute the transformed value of Index at offset StartValue using step
710   /// StepValue.
711   /// For integer induction, returns StartValue + Index * StepValue.
712   /// For pointer induction, returns StartValue[Index * StepValue].
713   /// FIXME: The newly created binary instructions should contain nsw/nuw
714   /// flags, which can be found from the original scalar operations.
715   Value *emitTransformedIndex(IRBuilder<> &B, Value *Index, ScalarEvolution *SE,
716                               const DataLayout &DL,
717                               const InductionDescriptor &ID) const;
718 
719   /// Emit basic blocks (prefixed with \p Prefix) for the iteration check,
720   /// vector loop preheader, middle block and scalar preheader. Also
721   /// allocate a loop object for the new vector loop and return it.
722   Loop *createVectorLoopSkeleton(StringRef Prefix);
723 
724   /// Create new phi nodes for the induction variables to resume iteration count
725   /// in the scalar epilogue, from where the vectorized loop left off (given by
726   /// \p VectorTripCount).
727   /// In cases where the loop skeleton is more complicated (eg. epilogue
728   /// vectorization) and the resume values can come from an additional bypass
729   /// block, the \p AdditionalBypass pair provides information about the bypass
730   /// block and the end value on the edge from bypass to this loop.
731   void createInductionResumeValues(
732       Loop *L, Value *VectorTripCount,
733       std::pair<BasicBlock *, Value *> AdditionalBypass = {nullptr, nullptr});
734 
735   /// Complete the loop skeleton by adding debug MDs, creating appropriate
736   /// conditional branches in the middle block, preparing the builder and
737   /// running the verifier. Take in the vector loop \p L as argument, and return
738   /// the preheader of the completed vector loop.
739   BasicBlock *completeLoopSkeleton(Loop *L, MDNode *OrigLoopID);
740 
741   /// Add additional metadata to \p To that was not present on \p Orig.
742   ///
743   /// Currently this is used to add the noalias annotations based on the
744   /// inserted memchecks.  Use this for instructions that are *cloned* into the
745   /// vector loop.
746   void addNewMetadata(Instruction *To, const Instruction *Orig);
747 
748   /// Add metadata from one instruction to another.
749   ///
750   /// This includes both the original MDs from \p From and additional ones (\see
751   /// addNewMetadata).  Use this for *newly created* instructions in the vector
752   /// loop.
753   void addMetadata(Instruction *To, Instruction *From);
754 
755   /// Similar to the previous function but it adds the metadata to a
756   /// vector of instructions.
757   void addMetadata(ArrayRef<Value *> To, Instruction *From);
758 
759   /// Allow subclasses to override and print debug traces before/after vplan
760   /// execution, when trace information is requested.
printDebugTracesAtStart()761   virtual void printDebugTracesAtStart(){};
printDebugTracesAtEnd()762   virtual void printDebugTracesAtEnd(){};
763 
764   /// The original loop.
765   Loop *OrigLoop;
766 
767   /// A wrapper around ScalarEvolution used to add runtime SCEV checks. Applies
768   /// dynamic knowledge to simplify SCEV expressions and converts them to a
769   /// more usable form.
770   PredicatedScalarEvolution &PSE;
771 
772   /// Loop Info.
773   LoopInfo *LI;
774 
775   /// Dominator Tree.
776   DominatorTree *DT;
777 
778   /// Alias Analysis.
779   AAResults *AA;
780 
781   /// Target Library Info.
782   const TargetLibraryInfo *TLI;
783 
784   /// Target Transform Info.
785   const TargetTransformInfo *TTI;
786 
787   /// Assumption Cache.
788   AssumptionCache *AC;
789 
790   /// Interface to emit optimization remarks.
791   OptimizationRemarkEmitter *ORE;
792 
793   /// LoopVersioning.  It's only set up (non-null) if memchecks were
794   /// used.
795   ///
796   /// This is currently only used to add no-alias metadata based on the
797   /// memchecks.  The actually versioning is performed manually.
798   std::unique_ptr<LoopVersioning> LVer;
799 
800   /// The vectorization SIMD factor to use. Each vector will have this many
801   /// vector elements.
802   ElementCount VF;
803 
804   /// The vectorization unroll factor to use. Each scalar is vectorized to this
805   /// many different vector instructions.
806   unsigned UF;
807 
808   /// The builder that we use
809   IRBuilder<> Builder;
810 
811   // --- Vectorization state ---
812 
813   /// The vector-loop preheader.
814   BasicBlock *LoopVectorPreHeader;
815 
816   /// The scalar-loop preheader.
817   BasicBlock *LoopScalarPreHeader;
818 
819   /// Middle Block between the vector and the scalar.
820   BasicBlock *LoopMiddleBlock;
821 
822   /// The (unique) ExitBlock of the scalar loop.  Note that
823   /// there can be multiple exiting edges reaching this block.
824   BasicBlock *LoopExitBlock;
825 
826   /// The vector loop body.
827   BasicBlock *LoopVectorBody;
828 
829   /// The scalar loop body.
830   BasicBlock *LoopScalarBody;
831 
832   /// A list of all bypass blocks. The first block is the entry of the loop.
833   SmallVector<BasicBlock *, 4> LoopBypassBlocks;
834 
835   /// The new Induction variable which was added to the new block.
836   PHINode *Induction = nullptr;
837 
838   /// The induction variable of the old basic block.
839   PHINode *OldInduction = nullptr;
840 
841   /// Store instructions that were predicated.
842   SmallVector<Instruction *, 4> PredicatedInstructions;
843 
844   /// Trip count of the original loop.
845   Value *TripCount = nullptr;
846 
847   /// Trip count of the widened loop (TripCount - TripCount % (VF*UF))
848   Value *VectorTripCount = nullptr;
849 
850   /// The legality analysis.
851   LoopVectorizationLegality *Legal;
852 
853   /// The profitablity analysis.
854   LoopVectorizationCostModel *Cost;
855 
856   // Record whether runtime checks are added.
857   bool AddedSafetyChecks = false;
858 
859   // Holds the end values for each induction variable. We save the end values
860   // so we can later fix-up the external users of the induction variables.
861   DenseMap<PHINode *, Value *> IVEndValues;
862 
863   // Vector of original scalar PHIs whose corresponding widened PHIs need to be
864   // fixed up at the end of vector code generation.
865   SmallVector<PHINode *, 8> OrigPHIsToFix;
866 
867   /// BFI and PSI are used to check for profile guided size optimizations.
868   BlockFrequencyInfo *BFI;
869   ProfileSummaryInfo *PSI;
870 
871   // Whether this loop should be optimized for size based on profile guided size
872   // optimizatios.
873   bool OptForSizeBasedOnProfile;
874 
875   /// Structure to hold information about generated runtime checks, responsible
876   /// for cleaning the checks, if vectorization turns out unprofitable.
877   GeneratedRTChecks &RTChecks;
878 };
879 
880 class InnerLoopUnroller : public InnerLoopVectorizer {
881 public:
InnerLoopUnroller(Loop * OrigLoop,PredicatedScalarEvolution & PSE,LoopInfo * LI,DominatorTree * DT,const TargetLibraryInfo * TLI,const TargetTransformInfo * TTI,AssumptionCache * AC,OptimizationRemarkEmitter * ORE,unsigned UnrollFactor,LoopVectorizationLegality * LVL,LoopVectorizationCostModel * CM,BlockFrequencyInfo * BFI,ProfileSummaryInfo * PSI,GeneratedRTChecks & Check)882   InnerLoopUnroller(Loop *OrigLoop, PredicatedScalarEvolution &PSE,
883                     LoopInfo *LI, DominatorTree *DT,
884                     const TargetLibraryInfo *TLI,
885                     const TargetTransformInfo *TTI, AssumptionCache *AC,
886                     OptimizationRemarkEmitter *ORE, unsigned UnrollFactor,
887                     LoopVectorizationLegality *LVL,
888                     LoopVectorizationCostModel *CM, BlockFrequencyInfo *BFI,
889                     ProfileSummaryInfo *PSI, GeneratedRTChecks &Check)
890       : InnerLoopVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
891                             ElementCount::getFixed(1), UnrollFactor, LVL, CM,
892                             BFI, PSI, Check) {}
893 
894 private:
895   Value *getBroadcastInstrs(Value *V) override;
896   Value *getStepVector(Value *Val, int StartIdx, Value *Step,
897                        Instruction::BinaryOps Opcode =
898                        Instruction::BinaryOpsEnd) override;
899   Value *reverseVector(Value *Vec) override;
900 };
901 
902 /// Encapsulate information regarding vectorization of a loop and its epilogue.
903 /// This information is meant to be updated and used across two stages of
904 /// epilogue vectorization.
905 struct EpilogueLoopVectorizationInfo {
906   ElementCount MainLoopVF = ElementCount::getFixed(0);
907   unsigned MainLoopUF = 0;
908   ElementCount EpilogueVF = ElementCount::getFixed(0);
909   unsigned EpilogueUF = 0;
910   BasicBlock *MainLoopIterationCountCheck = nullptr;
911   BasicBlock *EpilogueIterationCountCheck = nullptr;
912   BasicBlock *SCEVSafetyCheck = nullptr;
913   BasicBlock *MemSafetyCheck = nullptr;
914   Value *TripCount = nullptr;
915   Value *VectorTripCount = nullptr;
916 
EpilogueLoopVectorizationInfollvm::EpilogueLoopVectorizationInfo917   EpilogueLoopVectorizationInfo(unsigned MVF, unsigned MUF, unsigned EVF,
918                                 unsigned EUF)
919       : MainLoopVF(ElementCount::getFixed(MVF)), MainLoopUF(MUF),
920         EpilogueVF(ElementCount::getFixed(EVF)), EpilogueUF(EUF) {
921     assert(EUF == 1 &&
922            "A high UF for the epilogue loop is likely not beneficial.");
923   }
924 };
925 
926 /// An extension of the inner loop vectorizer that creates a skeleton for a
927 /// vectorized loop that has its epilogue (residual) also vectorized.
928 /// The idea is to run the vplan on a given loop twice, firstly to setup the
929 /// skeleton and vectorize the main loop, and secondly to complete the skeleton
930 /// from the first step and vectorize the epilogue.  This is achieved by
931 /// deriving two concrete strategy classes from this base class and invoking
932 /// them in succession from the loop vectorizer planner.
933 class InnerLoopAndEpilogueVectorizer : public InnerLoopVectorizer {
934 public:
InnerLoopAndEpilogueVectorizer(Loop * OrigLoop,PredicatedScalarEvolution & PSE,LoopInfo * LI,DominatorTree * DT,const TargetLibraryInfo * TLI,const TargetTransformInfo * TTI,AssumptionCache * AC,OptimizationRemarkEmitter * ORE,EpilogueLoopVectorizationInfo & EPI,LoopVectorizationLegality * LVL,llvm::LoopVectorizationCostModel * CM,BlockFrequencyInfo * BFI,ProfileSummaryInfo * PSI,GeneratedRTChecks & Checks)935   InnerLoopAndEpilogueVectorizer(
936       Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI,
937       DominatorTree *DT, const TargetLibraryInfo *TLI,
938       const TargetTransformInfo *TTI, AssumptionCache *AC,
939       OptimizationRemarkEmitter *ORE, EpilogueLoopVectorizationInfo &EPI,
940       LoopVectorizationLegality *LVL, llvm::LoopVectorizationCostModel *CM,
941       BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI,
942       GeneratedRTChecks &Checks)
943       : InnerLoopVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
944                             EPI.MainLoopVF, EPI.MainLoopUF, LVL, CM, BFI, PSI,
945                             Checks),
946         EPI(EPI) {}
947 
948   // Override this function to handle the more complex control flow around the
949   // three loops.
createVectorizedLoopSkeleton()950   BasicBlock *createVectorizedLoopSkeleton() final override {
951     return createEpilogueVectorizedLoopSkeleton();
952   }
953 
954   /// The interface for creating a vectorized skeleton using one of two
955   /// different strategies, each corresponding to one execution of the vplan
956   /// as described above.
957   virtual BasicBlock *createEpilogueVectorizedLoopSkeleton() = 0;
958 
959   /// Holds and updates state information required to vectorize the main loop
960   /// and its epilogue in two separate passes. This setup helps us avoid
961   /// regenerating and recomputing runtime safety checks. It also helps us to
962   /// shorten the iteration-count-check path length for the cases where the
963   /// iteration count of the loop is so small that the main vector loop is
964   /// completely skipped.
965   EpilogueLoopVectorizationInfo &EPI;
966 };
967 
968 /// A specialized derived class of inner loop vectorizer that performs
969 /// vectorization of *main* loops in the process of vectorizing loops and their
970 /// epilogues.
971 class EpilogueVectorizerMainLoop : public InnerLoopAndEpilogueVectorizer {
972 public:
EpilogueVectorizerMainLoop(Loop * OrigLoop,PredicatedScalarEvolution & PSE,LoopInfo * LI,DominatorTree * DT,const TargetLibraryInfo * TLI,const TargetTransformInfo * TTI,AssumptionCache * AC,OptimizationRemarkEmitter * ORE,EpilogueLoopVectorizationInfo & EPI,LoopVectorizationLegality * LVL,llvm::LoopVectorizationCostModel * CM,BlockFrequencyInfo * BFI,ProfileSummaryInfo * PSI,GeneratedRTChecks & Check)973   EpilogueVectorizerMainLoop(
974       Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI,
975       DominatorTree *DT, const TargetLibraryInfo *TLI,
976       const TargetTransformInfo *TTI, AssumptionCache *AC,
977       OptimizationRemarkEmitter *ORE, EpilogueLoopVectorizationInfo &EPI,
978       LoopVectorizationLegality *LVL, llvm::LoopVectorizationCostModel *CM,
979       BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI,
980       GeneratedRTChecks &Check)
981       : InnerLoopAndEpilogueVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
982                                        EPI, LVL, CM, BFI, PSI, Check) {}
983   /// Implements the interface for creating a vectorized skeleton using the
984   /// *main loop* strategy (ie the first pass of vplan execution).
985   BasicBlock *createEpilogueVectorizedLoopSkeleton() final override;
986 
987 protected:
988   /// Emits an iteration count bypass check once for the main loop (when \p
989   /// ForEpilogue is false) and once for the epilogue loop (when \p
990   /// ForEpilogue is true).
991   BasicBlock *emitMinimumIterationCountCheck(Loop *L, BasicBlock *Bypass,
992                                              bool ForEpilogue);
993   void printDebugTracesAtStart() override;
994   void printDebugTracesAtEnd() override;
995 };
996 
997 // A specialized derived class of inner loop vectorizer that performs
998 // vectorization of *epilogue* loops in the process of vectorizing loops and
999 // their epilogues.
1000 class EpilogueVectorizerEpilogueLoop : public InnerLoopAndEpilogueVectorizer {
1001 public:
EpilogueVectorizerEpilogueLoop(Loop * OrigLoop,PredicatedScalarEvolution & PSE,LoopInfo * LI,DominatorTree * DT,const TargetLibraryInfo * TLI,const TargetTransformInfo * TTI,AssumptionCache * AC,OptimizationRemarkEmitter * ORE,EpilogueLoopVectorizationInfo & EPI,LoopVectorizationLegality * LVL,llvm::LoopVectorizationCostModel * CM,BlockFrequencyInfo * BFI,ProfileSummaryInfo * PSI,GeneratedRTChecks & Checks)1002   EpilogueVectorizerEpilogueLoop(
1003       Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI,
1004       DominatorTree *DT, const TargetLibraryInfo *TLI,
1005       const TargetTransformInfo *TTI, AssumptionCache *AC,
1006       OptimizationRemarkEmitter *ORE, EpilogueLoopVectorizationInfo &EPI,
1007       LoopVectorizationLegality *LVL, llvm::LoopVectorizationCostModel *CM,
1008       BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI,
1009       GeneratedRTChecks &Checks)
1010       : InnerLoopAndEpilogueVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
1011                                        EPI, LVL, CM, BFI, PSI, Checks) {}
1012   /// Implements the interface for creating a vectorized skeleton using the
1013   /// *epilogue loop* strategy (ie the second pass of vplan execution).
1014   BasicBlock *createEpilogueVectorizedLoopSkeleton() final override;
1015 
1016 protected:
1017   /// Emits an iteration count bypass check after the main vector loop has
1018   /// finished to see if there are any iterations left to execute by either
1019   /// the vector epilogue or the scalar epilogue.
1020   BasicBlock *emitMinimumVectorEpilogueIterCountCheck(Loop *L,
1021                                                       BasicBlock *Bypass,
1022                                                       BasicBlock *Insert);
1023   void printDebugTracesAtStart() override;
1024   void printDebugTracesAtEnd() override;
1025 };
1026 } // end namespace llvm
1027 
1028 /// Look for a meaningful debug location on the instruction or it's
1029 /// operands.
getDebugLocFromInstOrOperands(Instruction * I)1030 static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
1031   if (!I)
1032     return I;
1033 
1034   DebugLoc Empty;
1035   if (I->getDebugLoc() != Empty)
1036     return I;
1037 
1038   for (Use &Op : I->operands()) {
1039     if (Instruction *OpInst = dyn_cast<Instruction>(Op))
1040       if (OpInst->getDebugLoc() != Empty)
1041         return OpInst;
1042   }
1043 
1044   return I;
1045 }
1046 
setDebugLocFromInst(IRBuilder<> & B,const Value * Ptr)1047 void InnerLoopVectorizer::setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr) {
1048   if (const Instruction *Inst = dyn_cast_or_null<Instruction>(Ptr)) {
1049     const DILocation *DIL = Inst->getDebugLoc();
1050 
1051     // When a FSDiscriminator is enabled, we don't need to add the multiply
1052     // factors to the discriminators.
1053     if (DIL && Inst->getFunction()->isDebugInfoForProfiling() &&
1054         !isa<DbgInfoIntrinsic>(Inst) && !EnableFSDiscriminator) {
1055       // FIXME: For scalable vectors, assume vscale=1.
1056       auto NewDIL =
1057           DIL->cloneByMultiplyingDuplicationFactor(UF * VF.getKnownMinValue());
1058       if (NewDIL)
1059         B.SetCurrentDebugLocation(NewDIL.getValue());
1060       else
1061         LLVM_DEBUG(dbgs()
1062                    << "Failed to create new discriminator: "
1063                    << DIL->getFilename() << " Line: " << DIL->getLine());
1064     } else
1065       B.SetCurrentDebugLocation(DIL);
1066   } else
1067     B.SetCurrentDebugLocation(DebugLoc());
1068 }
1069 
1070 /// Write a \p DebugMsg about vectorization to the debug output stream. If \p I
1071 /// is passed, the message relates to that particular instruction.
1072 #ifndef NDEBUG
debugVectorizationMessage(const StringRef Prefix,const StringRef DebugMsg,Instruction * I)1073 static void debugVectorizationMessage(const StringRef Prefix,
1074                                       const StringRef DebugMsg,
1075                                       Instruction *I) {
1076   dbgs() << "LV: " << Prefix << DebugMsg;
1077   if (I != nullptr)
1078     dbgs() << " " << *I;
1079   else
1080     dbgs() << '.';
1081   dbgs() << '\n';
1082 }
1083 #endif
1084 
1085 /// Create an analysis remark that explains why vectorization failed
1086 ///
1087 /// \p PassName is the name of the pass (e.g. can be AlwaysPrint).  \p
1088 /// RemarkName is the identifier for the remark.  If \p I is passed it is an
1089 /// instruction that prevents vectorization.  Otherwise \p TheLoop is used for
1090 /// the location of the remark.  \return the remark object that can be
1091 /// streamed to.
createLVAnalysis(const char * PassName,StringRef RemarkName,Loop * TheLoop,Instruction * I)1092 static OptimizationRemarkAnalysis createLVAnalysis(const char *PassName,
1093     StringRef RemarkName, Loop *TheLoop, Instruction *I) {
1094   Value *CodeRegion = TheLoop->getHeader();
1095   DebugLoc DL = TheLoop->getStartLoc();
1096 
1097   if (I) {
1098     CodeRegion = I->getParent();
1099     // If there is no debug location attached to the instruction, revert back to
1100     // using the loop's.
1101     if (I->getDebugLoc())
1102       DL = I->getDebugLoc();
1103   }
1104 
1105   return OptimizationRemarkAnalysis(PassName, RemarkName, DL, CodeRegion);
1106 }
1107 
1108 /// Return a value for Step multiplied by VF.
createStepForVF(IRBuilder<> & B,Constant * Step,ElementCount VF)1109 static Value *createStepForVF(IRBuilder<> &B, Constant *Step, ElementCount VF) {
1110   assert(isa<ConstantInt>(Step) && "Expected an integer step");
1111   Constant *StepVal = ConstantInt::get(
1112       Step->getType(),
1113       cast<ConstantInt>(Step)->getSExtValue() * VF.getKnownMinValue());
1114   return VF.isScalable() ? B.CreateVScale(StepVal) : StepVal;
1115 }
1116 
1117 namespace llvm {
1118 
1119 /// Return the runtime value for VF.
getRuntimeVF(IRBuilder<> & B,Type * Ty,ElementCount VF)1120 Value *getRuntimeVF(IRBuilder<> &B, Type *Ty, ElementCount VF) {
1121   Constant *EC = ConstantInt::get(Ty, VF.getKnownMinValue());
1122   return VF.isScalable() ? B.CreateVScale(EC) : EC;
1123 }
1124 
reportVectorizationFailure(const StringRef DebugMsg,const StringRef OREMsg,const StringRef ORETag,OptimizationRemarkEmitter * ORE,Loop * TheLoop,Instruction * I)1125 void reportVectorizationFailure(const StringRef DebugMsg,
1126                                 const StringRef OREMsg, const StringRef ORETag,
1127                                 OptimizationRemarkEmitter *ORE, Loop *TheLoop,
1128                                 Instruction *I) {
1129   LLVM_DEBUG(debugVectorizationMessage("Not vectorizing: ", DebugMsg, I));
1130   LoopVectorizeHints Hints(TheLoop, true /* doesn't matter */, *ORE);
1131   ORE->emit(
1132       createLVAnalysis(Hints.vectorizeAnalysisPassName(), ORETag, TheLoop, I)
1133       << "loop not vectorized: " << OREMsg);
1134 }
1135 
reportVectorizationInfo(const StringRef Msg,const StringRef ORETag,OptimizationRemarkEmitter * ORE,Loop * TheLoop,Instruction * I)1136 void reportVectorizationInfo(const StringRef Msg, const StringRef ORETag,
1137                              OptimizationRemarkEmitter *ORE, Loop *TheLoop,
1138                              Instruction *I) {
1139   LLVM_DEBUG(debugVectorizationMessage("", Msg, I));
1140   LoopVectorizeHints Hints(TheLoop, true /* doesn't matter */, *ORE);
1141   ORE->emit(
1142       createLVAnalysis(Hints.vectorizeAnalysisPassName(), ORETag, TheLoop, I)
1143       << Msg);
1144 }
1145 
1146 } // end namespace llvm
1147 
1148 #ifndef NDEBUG
1149 /// \return string containing a file name and a line # for the given loop.
getDebugLocString(const Loop * L)1150 static std::string getDebugLocString(const Loop *L) {
1151   std::string Result;
1152   if (L) {
1153     raw_string_ostream OS(Result);
1154     if (const DebugLoc LoopDbgLoc = L->getStartLoc())
1155       LoopDbgLoc.print(OS);
1156     else
1157       // Just print the module name.
1158       OS << L->getHeader()->getParent()->getParent()->getModuleIdentifier();
1159     OS.flush();
1160   }
1161   return Result;
1162 }
1163 #endif
1164 
addNewMetadata(Instruction * To,const Instruction * Orig)1165 void InnerLoopVectorizer::addNewMetadata(Instruction *To,
1166                                          const Instruction *Orig) {
1167   // If the loop was versioned with memchecks, add the corresponding no-alias
1168   // metadata.
1169   if (LVer && (isa<LoadInst>(Orig) || isa<StoreInst>(Orig)))
1170     LVer->annotateInstWithNoAlias(To, Orig);
1171 }
1172 
addMetadata(Instruction * To,Instruction * From)1173 void InnerLoopVectorizer::addMetadata(Instruction *To,
1174                                       Instruction *From) {
1175   propagateMetadata(To, From);
1176   addNewMetadata(To, From);
1177 }
1178 
addMetadata(ArrayRef<Value * > To,Instruction * From)1179 void InnerLoopVectorizer::addMetadata(ArrayRef<Value *> To,
1180                                       Instruction *From) {
1181   for (Value *V : To) {
1182     if (Instruction *I = dyn_cast<Instruction>(V))
1183       addMetadata(I, From);
1184   }
1185 }
1186 
1187 namespace llvm {
1188 
1189 // Loop vectorization cost-model hints how the scalar epilogue loop should be
1190 // lowered.
1191 enum ScalarEpilogueLowering {
1192 
1193   // The default: allowing scalar epilogues.
1194   CM_ScalarEpilogueAllowed,
1195 
1196   // Vectorization with OptForSize: don't allow epilogues.
1197   CM_ScalarEpilogueNotAllowedOptSize,
1198 
1199   // A special case of vectorisation with OptForSize: loops with a very small
1200   // trip count are considered for vectorization under OptForSize, thereby
1201   // making sure the cost of their loop body is dominant, free of runtime
1202   // guards and scalar iteration overheads.
1203   CM_ScalarEpilogueNotAllowedLowTripLoop,
1204 
1205   // Loop hint predicate indicating an epilogue is undesired.
1206   CM_ScalarEpilogueNotNeededUsePredicate,
1207 
1208   // Directive indicating we must either tail fold or not vectorize
1209   CM_ScalarEpilogueNotAllowedUsePredicate
1210 };
1211 
1212 /// LoopVectorizationCostModel - estimates the expected speedups due to
1213 /// vectorization.
1214 /// In many cases vectorization is not profitable. This can happen because of
1215 /// a number of reasons. In this class we mainly attempt to predict the
1216 /// expected speedup/slowdowns due to the supported instruction set. We use the
1217 /// TargetTransformInfo to query the different backends for the cost of
1218 /// different operations.
1219 class LoopVectorizationCostModel {
1220 public:
LoopVectorizationCostModel(ScalarEpilogueLowering SEL,Loop * L,PredicatedScalarEvolution & PSE,LoopInfo * LI,LoopVectorizationLegality * Legal,const TargetTransformInfo & TTI,const TargetLibraryInfo * TLI,DemandedBits * DB,AssumptionCache * AC,OptimizationRemarkEmitter * ORE,const Function * F,const LoopVectorizeHints * Hints,InterleavedAccessInfo & IAI)1221   LoopVectorizationCostModel(ScalarEpilogueLowering SEL, Loop *L,
1222                              PredicatedScalarEvolution &PSE, LoopInfo *LI,
1223                              LoopVectorizationLegality *Legal,
1224                              const TargetTransformInfo &TTI,
1225                              const TargetLibraryInfo *TLI, DemandedBits *DB,
1226                              AssumptionCache *AC,
1227                              OptimizationRemarkEmitter *ORE, const Function *F,
1228                              const LoopVectorizeHints *Hints,
1229                              InterleavedAccessInfo &IAI)
1230       : ScalarEpilogueStatus(SEL), TheLoop(L), PSE(PSE), LI(LI), Legal(Legal),
1231         TTI(TTI), TLI(TLI), DB(DB), AC(AC), ORE(ORE), TheFunction(F),
1232         Hints(Hints), InterleaveInfo(IAI) {}
1233 
1234   /// \return An upper bound for the vectorization factors (both fixed and
1235   /// scalable). If the factors are 0, vectorization and interleaving should be
1236   /// avoided up front.
1237   FixedScalableVFPair computeMaxVF(ElementCount UserVF, unsigned UserIC);
1238 
1239   /// \return True if runtime checks are required for vectorization, and false
1240   /// otherwise.
1241   bool runtimeChecksRequired();
1242 
1243   /// \return The most profitable vectorization factor and the cost of that VF.
1244   /// This method checks every power of two up to MaxVF. If UserVF is not ZERO
1245   /// then this vectorization factor will be selected if vectorization is
1246   /// possible.
1247   VectorizationFactor selectVectorizationFactor(ElementCount MaxVF);
1248   VectorizationFactor
1249   selectEpilogueVectorizationFactor(const ElementCount MaxVF,
1250                                     const LoopVectorizationPlanner &LVP);
1251 
1252   /// Setup cost-based decisions for user vectorization factor.
selectUserVectorizationFactor(ElementCount UserVF)1253   void selectUserVectorizationFactor(ElementCount UserVF) {
1254     collectUniformsAndScalars(UserVF);
1255     collectInstsToScalarize(UserVF);
1256   }
1257 
1258   /// \return The size (in bits) of the smallest and widest types in the code
1259   /// that needs to be vectorized. We ignore values that remain scalar such as
1260   /// 64 bit loop indices.
1261   std::pair<unsigned, unsigned> getSmallestAndWidestTypes();
1262 
1263   /// \return The desired interleave count.
1264   /// If interleave count has been specified by metadata it will be returned.
1265   /// Otherwise, the interleave count is computed and returned. VF and LoopCost
1266   /// are the selected vectorization factor and the cost of the selected VF.
1267   unsigned selectInterleaveCount(ElementCount VF, unsigned LoopCost);
1268 
1269   /// Memory access instruction may be vectorized in more than one way.
1270   /// Form of instruction after vectorization depends on cost.
1271   /// This function takes cost-based decisions for Load/Store instructions
1272   /// and collects them in a map. This decisions map is used for building
1273   /// the lists of loop-uniform and loop-scalar instructions.
1274   /// The calculated cost is saved with widening decision in order to
1275   /// avoid redundant calculations.
1276   void setCostBasedWideningDecision(ElementCount VF);
1277 
1278   /// A struct that represents some properties of the register usage
1279   /// of a loop.
1280   struct RegisterUsage {
1281     /// Holds the number of loop invariant values that are used in the loop.
1282     /// The key is ClassID of target-provided register class.
1283     SmallMapVector<unsigned, unsigned, 4> LoopInvariantRegs;
1284     /// Holds the maximum number of concurrent live intervals in the loop.
1285     /// The key is ClassID of target-provided register class.
1286     SmallMapVector<unsigned, unsigned, 4> MaxLocalUsers;
1287   };
1288 
1289   /// \return Returns information about the register usages of the loop for the
1290   /// given vectorization factors.
1291   SmallVector<RegisterUsage, 8>
1292   calculateRegisterUsage(ArrayRef<ElementCount> VFs);
1293 
1294   /// Collect values we want to ignore in the cost model.
1295   void collectValuesToIgnore();
1296 
1297   /// Split reductions into those that happen in the loop, and those that happen
1298   /// outside. In loop reductions are collected into InLoopReductionChains.
1299   void collectInLoopReductions();
1300 
1301   /// \returns The smallest bitwidth each instruction can be represented with.
1302   /// The vector equivalents of these instructions should be truncated to this
1303   /// type.
getMinimalBitwidths() const1304   const MapVector<Instruction *, uint64_t> &getMinimalBitwidths() const {
1305     return MinBWs;
1306   }
1307 
1308   /// \returns True if it is more profitable to scalarize instruction \p I for
1309   /// vectorization factor \p VF.
isProfitableToScalarize(Instruction * I,ElementCount VF) const1310   bool isProfitableToScalarize(Instruction *I, ElementCount VF) const {
1311     assert(VF.isVector() &&
1312            "Profitable to scalarize relevant only for VF > 1.");
1313 
1314     // Cost model is not run in the VPlan-native path - return conservative
1315     // result until this changes.
1316     if (EnableVPlanNativePath)
1317       return false;
1318 
1319     auto Scalars = InstsToScalarize.find(VF);
1320     assert(Scalars != InstsToScalarize.end() &&
1321            "VF not yet analyzed for scalarization profitability");
1322     return Scalars->second.find(I) != Scalars->second.end();
1323   }
1324 
1325   /// Returns true if \p I is known to be uniform after vectorization.
isUniformAfterVectorization(Instruction * I,ElementCount VF) const1326   bool isUniformAfterVectorization(Instruction *I, ElementCount VF) const {
1327     if (VF.isScalar())
1328       return true;
1329 
1330     // Cost model is not run in the VPlan-native path - return conservative
1331     // result until this changes.
1332     if (EnableVPlanNativePath)
1333       return false;
1334 
1335     auto UniformsPerVF = Uniforms.find(VF);
1336     assert(UniformsPerVF != Uniforms.end() &&
1337            "VF not yet analyzed for uniformity");
1338     return UniformsPerVF->second.count(I);
1339   }
1340 
1341   /// Returns true if \p I is known to be scalar after vectorization.
isScalarAfterVectorization(Instruction * I,ElementCount VF) const1342   bool isScalarAfterVectorization(Instruction *I, ElementCount VF) const {
1343     if (VF.isScalar())
1344       return true;
1345 
1346     // Cost model is not run in the VPlan-native path - return conservative
1347     // result until this changes.
1348     if (EnableVPlanNativePath)
1349       return false;
1350 
1351     auto ScalarsPerVF = Scalars.find(VF);
1352     assert(ScalarsPerVF != Scalars.end() &&
1353            "Scalar values are not calculated for VF");
1354     return ScalarsPerVF->second.count(I);
1355   }
1356 
1357   /// \returns True if instruction \p I can be truncated to a smaller bitwidth
1358   /// for vectorization factor \p VF.
canTruncateToMinimalBitwidth(Instruction * I,ElementCount VF) const1359   bool canTruncateToMinimalBitwidth(Instruction *I, ElementCount VF) const {
1360     return VF.isVector() && MinBWs.find(I) != MinBWs.end() &&
1361            !isProfitableToScalarize(I, VF) &&
1362            !isScalarAfterVectorization(I, VF);
1363   }
1364 
1365   /// Decision that was taken during cost calculation for memory instruction.
1366   enum InstWidening {
1367     CM_Unknown,
1368     CM_Widen,         // For consecutive accesses with stride +1.
1369     CM_Widen_Reverse, // For consecutive accesses with stride -1.
1370     CM_Interleave,
1371     CM_GatherScatter,
1372     CM_Scalarize
1373   };
1374 
1375   /// Save vectorization decision \p W and \p Cost taken by the cost model for
1376   /// instruction \p I and vector width \p VF.
setWideningDecision(Instruction * I,ElementCount VF,InstWidening W,InstructionCost Cost)1377   void setWideningDecision(Instruction *I, ElementCount VF, InstWidening W,
1378                            InstructionCost Cost) {
1379     assert(VF.isVector() && "Expected VF >=2");
1380     WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
1381   }
1382 
1383   /// Save vectorization decision \p W and \p Cost taken by the cost model for
1384   /// interleaving group \p Grp and vector width \p VF.
setWideningDecision(const InterleaveGroup<Instruction> * Grp,ElementCount VF,InstWidening W,InstructionCost Cost)1385   void setWideningDecision(const InterleaveGroup<Instruction> *Grp,
1386                            ElementCount VF, InstWidening W,
1387                            InstructionCost Cost) {
1388     assert(VF.isVector() && "Expected VF >=2");
1389     /// Broadcast this decicion to all instructions inside the group.
1390     /// But the cost will be assigned to one instruction only.
1391     for (unsigned i = 0; i < Grp->getFactor(); ++i) {
1392       if (auto *I = Grp->getMember(i)) {
1393         if (Grp->getInsertPos() == I)
1394           WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
1395         else
1396           WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, 0);
1397       }
1398     }
1399   }
1400 
1401   /// Return the cost model decision for the given instruction \p I and vector
1402   /// width \p VF. Return CM_Unknown if this instruction did not pass
1403   /// through the cost modeling.
getWideningDecision(Instruction * I,ElementCount VF) const1404   InstWidening getWideningDecision(Instruction *I, ElementCount VF) const {
1405     assert(VF.isVector() && "Expected VF to be a vector VF");
1406     // Cost model is not run in the VPlan-native path - return conservative
1407     // result until this changes.
1408     if (EnableVPlanNativePath)
1409       return CM_GatherScatter;
1410 
1411     std::pair<Instruction *, ElementCount> InstOnVF = std::make_pair(I, VF);
1412     auto Itr = WideningDecisions.find(InstOnVF);
1413     if (Itr == WideningDecisions.end())
1414       return CM_Unknown;
1415     return Itr->second.first;
1416   }
1417 
1418   /// Return the vectorization cost for the given instruction \p I and vector
1419   /// width \p VF.
getWideningCost(Instruction * I,ElementCount VF)1420   InstructionCost getWideningCost(Instruction *I, ElementCount VF) {
1421     assert(VF.isVector() && "Expected VF >=2");
1422     std::pair<Instruction *, ElementCount> InstOnVF = std::make_pair(I, VF);
1423     assert(WideningDecisions.find(InstOnVF) != WideningDecisions.end() &&
1424            "The cost is not calculated");
1425     return WideningDecisions[InstOnVF].second;
1426   }
1427 
1428   /// Return True if instruction \p I is an optimizable truncate whose operand
1429   /// is an induction variable. Such a truncate will be removed by adding a new
1430   /// induction variable with the destination type.
isOptimizableIVTruncate(Instruction * I,ElementCount VF)1431   bool isOptimizableIVTruncate(Instruction *I, ElementCount VF) {
1432     // If the instruction is not a truncate, return false.
1433     auto *Trunc = dyn_cast<TruncInst>(I);
1434     if (!Trunc)
1435       return false;
1436 
1437     // Get the source and destination types of the truncate.
1438     Type *SrcTy = ToVectorTy(cast<CastInst>(I)->getSrcTy(), VF);
1439     Type *DestTy = ToVectorTy(cast<CastInst>(I)->getDestTy(), VF);
1440 
1441     // If the truncate is free for the given types, return false. Replacing a
1442     // free truncate with an induction variable would add an induction variable
1443     // update instruction to each iteration of the loop. We exclude from this
1444     // check the primary induction variable since it will need an update
1445     // instruction regardless.
1446     Value *Op = Trunc->getOperand(0);
1447     if (Op != Legal->getPrimaryInduction() && TTI.isTruncateFree(SrcTy, DestTy))
1448       return false;
1449 
1450     // If the truncated value is not an induction variable, return false.
1451     return Legal->isInductionPhi(Op);
1452   }
1453 
1454   /// Collects the instructions to scalarize for each predicated instruction in
1455   /// the loop.
1456   void collectInstsToScalarize(ElementCount VF);
1457 
1458   /// Collect Uniform and Scalar values for the given \p VF.
1459   /// The sets depend on CM decision for Load/Store instructions
1460   /// that may be vectorized as interleave, gather-scatter or scalarized.
collectUniformsAndScalars(ElementCount VF)1461   void collectUniformsAndScalars(ElementCount VF) {
1462     // Do the analysis once.
1463     if (VF.isScalar() || Uniforms.find(VF) != Uniforms.end())
1464       return;
1465     setCostBasedWideningDecision(VF);
1466     collectLoopUniforms(VF);
1467     collectLoopScalars(VF);
1468   }
1469 
1470   /// Returns true if the target machine supports masked store operation
1471   /// for the given \p DataType and kind of access to \p Ptr.
isLegalMaskedStore(Type * DataType,Value * Ptr,Align Alignment) const1472   bool isLegalMaskedStore(Type *DataType, Value *Ptr, Align Alignment) const {
1473     return Legal->isConsecutivePtr(Ptr) &&
1474            TTI.isLegalMaskedStore(DataType, Alignment);
1475   }
1476 
1477   /// Returns true if the target machine supports masked load operation
1478   /// for the given \p DataType and kind of access to \p Ptr.
isLegalMaskedLoad(Type * DataType,Value * Ptr,Align Alignment) const1479   bool isLegalMaskedLoad(Type *DataType, Value *Ptr, Align Alignment) const {
1480     return Legal->isConsecutivePtr(Ptr) &&
1481            TTI.isLegalMaskedLoad(DataType, Alignment);
1482   }
1483 
1484   /// Returns true if the target machine supports masked scatter operation
1485   /// for the given \p DataType.
isLegalMaskedScatter(Type * DataType,Align Alignment) const1486   bool isLegalMaskedScatter(Type *DataType, Align Alignment) const {
1487     return TTI.isLegalMaskedScatter(DataType, Alignment);
1488   }
1489 
1490   /// Returns true if the target machine supports masked gather operation
1491   /// for the given \p DataType.
isLegalMaskedGather(Type * DataType,Align Alignment) const1492   bool isLegalMaskedGather(Type *DataType, Align Alignment) const {
1493     return TTI.isLegalMaskedGather(DataType, Alignment);
1494   }
1495 
1496   /// Returns true if the target machine can represent \p V as a masked gather
1497   /// or scatter operation.
isLegalGatherOrScatter(Value * V)1498   bool isLegalGatherOrScatter(Value *V) {
1499     bool LI = isa<LoadInst>(V);
1500     bool SI = isa<StoreInst>(V);
1501     if (!LI && !SI)
1502       return false;
1503     auto *Ty = getMemInstValueType(V);
1504     Align Align = getLoadStoreAlignment(V);
1505     return (LI && isLegalMaskedGather(Ty, Align)) ||
1506            (SI && isLegalMaskedScatter(Ty, Align));
1507   }
1508 
1509   /// Returns true if the target machine supports all of the reduction
1510   /// variables found for the given VF.
canVectorizeReductions(ElementCount VF)1511   bool canVectorizeReductions(ElementCount VF) {
1512     return (all_of(Legal->getReductionVars(), [&](auto &Reduction) -> bool {
1513       RecurrenceDescriptor RdxDesc = Reduction.second;
1514       return TTI.isLegalToVectorizeReduction(RdxDesc, VF);
1515     }));
1516   }
1517 
1518   /// Returns true if \p I is an instruction that will be scalarized with
1519   /// predication. Such instructions include conditional stores and
1520   /// instructions that may divide by zero.
1521   /// If a non-zero VF has been calculated, we check if I will be scalarized
1522   /// predication for that VF.
1523   bool isScalarWithPredication(Instruction *I) const;
1524 
1525   // Returns true if \p I is an instruction that will be predicated either
1526   // through scalar predication or masked load/store or masked gather/scatter.
1527   // Superset of instructions that return true for isScalarWithPredication.
isPredicatedInst(Instruction * I)1528   bool isPredicatedInst(Instruction *I) {
1529     if (!blockNeedsPredication(I->getParent()))
1530       return false;
1531     // Loads and stores that need some form of masked operation are predicated
1532     // instructions.
1533     if (isa<LoadInst>(I) || isa<StoreInst>(I))
1534       return Legal->isMaskRequired(I);
1535     return isScalarWithPredication(I);
1536   }
1537 
1538   /// Returns true if \p I is a memory instruction with consecutive memory
1539   /// access that can be widened.
1540   bool
1541   memoryInstructionCanBeWidened(Instruction *I,
1542                                 ElementCount VF = ElementCount::getFixed(1));
1543 
1544   /// Returns true if \p I is a memory instruction in an interleaved-group
1545   /// of memory accesses that can be vectorized with wide vector loads/stores
1546   /// and shuffles.
1547   bool
1548   interleavedAccessCanBeWidened(Instruction *I,
1549                                 ElementCount VF = ElementCount::getFixed(1));
1550 
1551   /// Check if \p Instr belongs to any interleaved access group.
isAccessInterleaved(Instruction * Instr)1552   bool isAccessInterleaved(Instruction *Instr) {
1553     return InterleaveInfo.isInterleaved(Instr);
1554   }
1555 
1556   /// Get the interleaved access group that \p Instr belongs to.
1557   const InterleaveGroup<Instruction> *
getInterleavedAccessGroup(Instruction * Instr)1558   getInterleavedAccessGroup(Instruction *Instr) {
1559     return InterleaveInfo.getInterleaveGroup(Instr);
1560   }
1561 
1562   /// Returns true if we're required to use a scalar epilogue for at least
1563   /// the final iteration of the original loop.
requiresScalarEpilogue() const1564   bool requiresScalarEpilogue() const {
1565     if (!isScalarEpilogueAllowed())
1566       return false;
1567     // If we might exit from anywhere but the latch, must run the exiting
1568     // iteration in scalar form.
1569     if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch())
1570       return true;
1571     return InterleaveInfo.requiresScalarEpilogue();
1572   }
1573 
1574   /// Returns true if a scalar epilogue is not allowed due to optsize or a
1575   /// loop hint annotation.
isScalarEpilogueAllowed() const1576   bool isScalarEpilogueAllowed() const {
1577     return ScalarEpilogueStatus == CM_ScalarEpilogueAllowed;
1578   }
1579 
1580   /// Returns true if all loop blocks should be masked to fold tail loop.
foldTailByMasking() const1581   bool foldTailByMasking() const { return FoldTailByMasking; }
1582 
blockNeedsPredication(BasicBlock * BB) const1583   bool blockNeedsPredication(BasicBlock *BB) const {
1584     return foldTailByMasking() || Legal->blockNeedsPredication(BB);
1585   }
1586 
1587   /// A SmallMapVector to store the InLoop reduction op chains, mapping phi
1588   /// nodes to the chain of instructions representing the reductions. Uses a
1589   /// MapVector to ensure deterministic iteration order.
1590   using ReductionChainMap =
1591       SmallMapVector<PHINode *, SmallVector<Instruction *, 4>, 4>;
1592 
1593   /// Return the chain of instructions representing an inloop reduction.
getInLoopReductionChains() const1594   const ReductionChainMap &getInLoopReductionChains() const {
1595     return InLoopReductionChains;
1596   }
1597 
1598   /// Returns true if the Phi is part of an inloop reduction.
isInLoopReduction(PHINode * Phi) const1599   bool isInLoopReduction(PHINode *Phi) const {
1600     return InLoopReductionChains.count(Phi);
1601   }
1602 
1603   /// Estimate cost of an intrinsic call instruction CI if it were vectorized
1604   /// with factor VF.  Return the cost of the instruction, including
1605   /// scalarization overhead if it's needed.
1606   InstructionCost getVectorIntrinsicCost(CallInst *CI, ElementCount VF) const;
1607 
1608   /// Estimate cost of a call instruction CI if it were vectorized with factor
1609   /// VF. Return the cost of the instruction, including scalarization overhead
1610   /// if it's needed. The flag NeedToScalarize shows if the call needs to be
1611   /// scalarized -
1612   /// i.e. either vector version isn't available, or is too expensive.
1613   InstructionCost getVectorCallCost(CallInst *CI, ElementCount VF,
1614                                     bool &NeedToScalarize) const;
1615 
1616   /// Returns true if the per-lane cost of VectorizationFactor A is lower than
1617   /// that of B.
1618   bool isMoreProfitable(const VectorizationFactor &A,
1619                         const VectorizationFactor &B) const;
1620 
1621   /// Invalidates decisions already taken by the cost model.
invalidateCostModelingDecisions()1622   void invalidateCostModelingDecisions() {
1623     WideningDecisions.clear();
1624     Uniforms.clear();
1625     Scalars.clear();
1626   }
1627 
1628 private:
1629   unsigned NumPredStores = 0;
1630 
1631   /// \return An upper bound for the vectorization factors for both
1632   /// fixed and scalable vectorization, where the minimum-known number of
1633   /// elements is a power-of-2 larger than zero. If scalable vectorization is
1634   /// disabled or unsupported, then the scalable part will be equal to
1635   /// ElementCount::getScalable(0).
1636   FixedScalableVFPair computeFeasibleMaxVF(unsigned ConstTripCount,
1637                                            ElementCount UserVF);
1638 
1639   /// \return the maximized element count based on the targets vector
1640   /// registers and the loop trip-count, but limited to a maximum safe VF.
1641   /// This is a helper function of computeFeasibleMaxVF.
1642   /// FIXME: MaxSafeVF is currently passed by reference to avoid some obscure
1643   /// issue that occurred on one of the buildbots which cannot be reproduced
1644   /// without having access to the properietary compiler (see comments on
1645   /// D98509). The issue is currently under investigation and this workaround
1646   /// will be removed as soon as possible.
1647   ElementCount getMaximizedVFForTarget(unsigned ConstTripCount,
1648                                        unsigned SmallestType,
1649                                        unsigned WidestType,
1650                                        const ElementCount &MaxSafeVF);
1651 
1652   /// \return the maximum legal scalable VF, based on the safe max number
1653   /// of elements.
1654   ElementCount getMaxLegalScalableVF(unsigned MaxSafeElements);
1655 
1656   /// The vectorization cost is a combination of the cost itself and a boolean
1657   /// indicating whether any of the contributing operations will actually
1658   /// operate on
1659   /// vector values after type legalization in the backend. If this latter value
1660   /// is
1661   /// false, then all operations will be scalarized (i.e. no vectorization has
1662   /// actually taken place).
1663   using VectorizationCostTy = std::pair<InstructionCost, bool>;
1664 
1665   /// Returns the expected execution cost. The unit of the cost does
1666   /// not matter because we use the 'cost' units to compare different
1667   /// vector widths. The cost that is returned is *not* normalized by
1668   /// the factor width.
1669   VectorizationCostTy expectedCost(ElementCount VF);
1670 
1671   /// Returns the execution time cost of an instruction for a given vector
1672   /// width. Vector width of one means scalar.
1673   VectorizationCostTy getInstructionCost(Instruction *I, ElementCount VF);
1674 
1675   /// The cost-computation logic from getInstructionCost which provides
1676   /// the vector type as an output parameter.
1677   InstructionCost getInstructionCost(Instruction *I, ElementCount VF,
1678                                      Type *&VectorTy);
1679 
1680   /// Return the cost of instructions in an inloop reduction pattern, if I is
1681   /// part of that pattern.
1682   InstructionCost getReductionPatternCost(Instruction *I, ElementCount VF,
1683                                           Type *VectorTy,
1684                                           TTI::TargetCostKind CostKind);
1685 
1686   /// Calculate vectorization cost of memory instruction \p I.
1687   InstructionCost getMemoryInstructionCost(Instruction *I, ElementCount VF);
1688 
1689   /// The cost computation for scalarized memory instruction.
1690   InstructionCost getMemInstScalarizationCost(Instruction *I, ElementCount VF);
1691 
1692   /// The cost computation for interleaving group of memory instructions.
1693   InstructionCost getInterleaveGroupCost(Instruction *I, ElementCount VF);
1694 
1695   /// The cost computation for Gather/Scatter instruction.
1696   InstructionCost getGatherScatterCost(Instruction *I, ElementCount VF);
1697 
1698   /// The cost computation for widening instruction \p I with consecutive
1699   /// memory access.
1700   InstructionCost getConsecutiveMemOpCost(Instruction *I, ElementCount VF);
1701 
1702   /// The cost calculation for Load/Store instruction \p I with uniform pointer -
1703   /// Load: scalar load + broadcast.
1704   /// Store: scalar store + (loop invariant value stored? 0 : extract of last
1705   /// element)
1706   InstructionCost getUniformMemOpCost(Instruction *I, ElementCount VF);
1707 
1708   /// Estimate the overhead of scalarizing an instruction. This is a
1709   /// convenience wrapper for the type-based getScalarizationOverhead API.
1710   InstructionCost getScalarizationOverhead(Instruction *I,
1711                                            ElementCount VF) const;
1712 
1713   /// Returns whether the instruction is a load or store and will be a emitted
1714   /// as a vector operation.
1715   bool isConsecutiveLoadOrStore(Instruction *I);
1716 
1717   /// Returns true if an artificially high cost for emulated masked memrefs
1718   /// should be used.
1719   bool useEmulatedMaskMemRefHack(Instruction *I);
1720 
1721   /// Map of scalar integer values to the smallest bitwidth they can be legally
1722   /// represented as. The vector equivalents of these values should be truncated
1723   /// to this type.
1724   MapVector<Instruction *, uint64_t> MinBWs;
1725 
1726   /// A type representing the costs for instructions if they were to be
1727   /// scalarized rather than vectorized. The entries are Instruction-Cost
1728   /// pairs.
1729   using ScalarCostsTy = DenseMap<Instruction *, InstructionCost>;
1730 
1731   /// A set containing all BasicBlocks that are known to present after
1732   /// vectorization as a predicated block.
1733   SmallPtrSet<BasicBlock *, 4> PredicatedBBsAfterVectorization;
1734 
1735   /// Records whether it is allowed to have the original scalar loop execute at
1736   /// least once. This may be needed as a fallback loop in case runtime
1737   /// aliasing/dependence checks fail, or to handle the tail/remainder
1738   /// iterations when the trip count is unknown or doesn't divide by the VF,
1739   /// or as a peel-loop to handle gaps in interleave-groups.
1740   /// Under optsize and when the trip count is very small we don't allow any
1741   /// iterations to execute in the scalar loop.
1742   ScalarEpilogueLowering ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
1743 
1744   /// All blocks of loop are to be masked to fold tail of scalar iterations.
1745   bool FoldTailByMasking = false;
1746 
1747   /// A map holding scalar costs for different vectorization factors. The
1748   /// presence of a cost for an instruction in the mapping indicates that the
1749   /// instruction will be scalarized when vectorizing with the associated
1750   /// vectorization factor. The entries are VF-ScalarCostTy pairs.
1751   DenseMap<ElementCount, ScalarCostsTy> InstsToScalarize;
1752 
1753   /// Holds the instructions known to be uniform after vectorization.
1754   /// The data is collected per VF.
1755   DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> Uniforms;
1756 
1757   /// Holds the instructions known to be scalar after vectorization.
1758   /// The data is collected per VF.
1759   DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> Scalars;
1760 
1761   /// Holds the instructions (address computations) that are forced to be
1762   /// scalarized.
1763   DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> ForcedScalars;
1764 
1765   /// PHINodes of the reductions that should be expanded in-loop along with
1766   /// their associated chains of reduction operations, in program order from top
1767   /// (PHI) to bottom
1768   ReductionChainMap InLoopReductionChains;
1769 
1770   /// A Map of inloop reduction operations and their immediate chain operand.
1771   /// FIXME: This can be removed once reductions can be costed correctly in
1772   /// vplan. This was added to allow quick lookup to the inloop operations,
1773   /// without having to loop through InLoopReductionChains.
1774   DenseMap<Instruction *, Instruction *> InLoopReductionImmediateChains;
1775 
1776   /// Returns the expected difference in cost from scalarizing the expression
1777   /// feeding a predicated instruction \p PredInst. The instructions to
1778   /// scalarize and their scalar costs are collected in \p ScalarCosts. A
1779   /// non-negative return value implies the expression will be scalarized.
1780   /// Currently, only single-use chains are considered for scalarization.
1781   int computePredInstDiscount(Instruction *PredInst, ScalarCostsTy &ScalarCosts,
1782                               ElementCount VF);
1783 
1784   /// Collect the instructions that are uniform after vectorization. An
1785   /// instruction is uniform if we represent it with a single scalar value in
1786   /// the vectorized loop corresponding to each vector iteration. Examples of
1787   /// uniform instructions include pointer operands of consecutive or
1788   /// interleaved memory accesses. Note that although uniformity implies an
1789   /// instruction will be scalar, the reverse is not true. In general, a
1790   /// scalarized instruction will be represented by VF scalar values in the
1791   /// vectorized loop, each corresponding to an iteration of the original
1792   /// scalar loop.
1793   void collectLoopUniforms(ElementCount VF);
1794 
1795   /// Collect the instructions that are scalar after vectorization. An
1796   /// instruction is scalar if it is known to be uniform or will be scalarized
1797   /// during vectorization. Non-uniform scalarized instructions will be
1798   /// represented by VF values in the vectorized loop, each corresponding to an
1799   /// iteration of the original scalar loop.
1800   void collectLoopScalars(ElementCount VF);
1801 
1802   /// Keeps cost model vectorization decision and cost for instructions.
1803   /// Right now it is used for memory instructions only.
1804   using DecisionList = DenseMap<std::pair<Instruction *, ElementCount>,
1805                                 std::pair<InstWidening, InstructionCost>>;
1806 
1807   DecisionList WideningDecisions;
1808 
1809   /// Returns true if \p V is expected to be vectorized and it needs to be
1810   /// extracted.
needsExtract(Value * V,ElementCount VF) const1811   bool needsExtract(Value *V, ElementCount VF) const {
1812     Instruction *I = dyn_cast<Instruction>(V);
1813     if (VF.isScalar() || !I || !TheLoop->contains(I) ||
1814         TheLoop->isLoopInvariant(I))
1815       return false;
1816 
1817     // Assume we can vectorize V (and hence we need extraction) if the
1818     // scalars are not computed yet. This can happen, because it is called
1819     // via getScalarizationOverhead from setCostBasedWideningDecision, before
1820     // the scalars are collected. That should be a safe assumption in most
1821     // cases, because we check if the operands have vectorizable types
1822     // beforehand in LoopVectorizationLegality.
1823     return Scalars.find(VF) == Scalars.end() ||
1824            !isScalarAfterVectorization(I, VF);
1825   };
1826 
1827   /// Returns a range containing only operands needing to be extracted.
filterExtractingOperands(Instruction::op_range Ops,ElementCount VF) const1828   SmallVector<Value *, 4> filterExtractingOperands(Instruction::op_range Ops,
1829                                                    ElementCount VF) const {
1830     return SmallVector<Value *, 4>(make_filter_range(
1831         Ops, [this, VF](Value *V) { return this->needsExtract(V, VF); }));
1832   }
1833 
1834   /// Determines if we have the infrastructure to vectorize loop \p L and its
1835   /// epilogue, assuming the main loop is vectorized by \p VF.
1836   bool isCandidateForEpilogueVectorization(const Loop &L,
1837                                            const ElementCount VF) const;
1838 
1839   /// Returns true if epilogue vectorization is considered profitable, and
1840   /// false otherwise.
1841   /// \p VF is the vectorization factor chosen for the original loop.
1842   bool isEpilogueVectorizationProfitable(const ElementCount VF) const;
1843 
1844 public:
1845   /// The loop that we evaluate.
1846   Loop *TheLoop;
1847 
1848   /// Predicated scalar evolution analysis.
1849   PredicatedScalarEvolution &PSE;
1850 
1851   /// Loop Info analysis.
1852   LoopInfo *LI;
1853 
1854   /// Vectorization legality.
1855   LoopVectorizationLegality *Legal;
1856 
1857   /// Vector target information.
1858   const TargetTransformInfo &TTI;
1859 
1860   /// Target Library Info.
1861   const TargetLibraryInfo *TLI;
1862 
1863   /// Demanded bits analysis.
1864   DemandedBits *DB;
1865 
1866   /// Assumption cache.
1867   AssumptionCache *AC;
1868 
1869   /// Interface to emit optimization remarks.
1870   OptimizationRemarkEmitter *ORE;
1871 
1872   const Function *TheFunction;
1873 
1874   /// Loop Vectorize Hint.
1875   const LoopVectorizeHints *Hints;
1876 
1877   /// The interleave access information contains groups of interleaved accesses
1878   /// with the same stride and close to each other.
1879   InterleavedAccessInfo &InterleaveInfo;
1880 
1881   /// Values to ignore in the cost model.
1882   SmallPtrSet<const Value *, 16> ValuesToIgnore;
1883 
1884   /// Values to ignore in the cost model when VF > 1.
1885   SmallPtrSet<const Value *, 16> VecValuesToIgnore;
1886 
1887   /// Profitable vector factors.
1888   SmallVector<VectorizationFactor, 8> ProfitableVFs;
1889 };
1890 } // end namespace llvm
1891 
1892 /// Helper struct to manage generating runtime checks for vectorization.
1893 ///
1894 /// The runtime checks are created up-front in temporary blocks to allow better
1895 /// estimating the cost and un-linked from the existing IR. After deciding to
1896 /// vectorize, the checks are moved back. If deciding not to vectorize, the
1897 /// temporary blocks are completely removed.
1898 class GeneratedRTChecks {
1899   /// Basic block which contains the generated SCEV checks, if any.
1900   BasicBlock *SCEVCheckBlock = nullptr;
1901 
1902   /// The value representing the result of the generated SCEV checks. If it is
1903   /// nullptr, either no SCEV checks have been generated or they have been used.
1904   Value *SCEVCheckCond = nullptr;
1905 
1906   /// Basic block which contains the generated memory runtime checks, if any.
1907   BasicBlock *MemCheckBlock = nullptr;
1908 
1909   /// The value representing the result of the generated memory runtime checks.
1910   /// If it is nullptr, either no memory runtime checks have been generated or
1911   /// they have been used.
1912   Instruction *MemRuntimeCheckCond = nullptr;
1913 
1914   DominatorTree *DT;
1915   LoopInfo *LI;
1916 
1917   SCEVExpander SCEVExp;
1918   SCEVExpander MemCheckExp;
1919 
1920 public:
GeneratedRTChecks(ScalarEvolution & SE,DominatorTree * DT,LoopInfo * LI,const DataLayout & DL)1921   GeneratedRTChecks(ScalarEvolution &SE, DominatorTree *DT, LoopInfo *LI,
1922                     const DataLayout &DL)
1923       : DT(DT), LI(LI), SCEVExp(SE, DL, "scev.check"),
1924         MemCheckExp(SE, DL, "scev.check") {}
1925 
1926   /// Generate runtime checks in SCEVCheckBlock and MemCheckBlock, so we can
1927   /// accurately estimate the cost of the runtime checks. The blocks are
1928   /// un-linked from the IR and is added back during vector code generation. If
1929   /// there is no vector code generation, the check blocks are removed
1930   /// completely.
Create(Loop * L,const LoopAccessInfo & LAI,const SCEVUnionPredicate & UnionPred)1931   void Create(Loop *L, const LoopAccessInfo &LAI,
1932               const SCEVUnionPredicate &UnionPred) {
1933 
1934     BasicBlock *LoopHeader = L->getHeader();
1935     BasicBlock *Preheader = L->getLoopPreheader();
1936 
1937     // Use SplitBlock to create blocks for SCEV & memory runtime checks to
1938     // ensure the blocks are properly added to LoopInfo & DominatorTree. Those
1939     // may be used by SCEVExpander. The blocks will be un-linked from their
1940     // predecessors and removed from LI & DT at the end of the function.
1941     if (!UnionPred.isAlwaysTrue()) {
1942       SCEVCheckBlock = SplitBlock(Preheader, Preheader->getTerminator(), DT, LI,
1943                                   nullptr, "vector.scevcheck");
1944 
1945       SCEVCheckCond = SCEVExp.expandCodeForPredicate(
1946           &UnionPred, SCEVCheckBlock->getTerminator());
1947     }
1948 
1949     const auto &RtPtrChecking = *LAI.getRuntimePointerChecking();
1950     if (RtPtrChecking.Need) {
1951       auto *Pred = SCEVCheckBlock ? SCEVCheckBlock : Preheader;
1952       MemCheckBlock = SplitBlock(Pred, Pred->getTerminator(), DT, LI, nullptr,
1953                                  "vector.memcheck");
1954 
1955       std::tie(std::ignore, MemRuntimeCheckCond) =
1956           addRuntimeChecks(MemCheckBlock->getTerminator(), L,
1957                            RtPtrChecking.getChecks(), MemCheckExp);
1958       assert(MemRuntimeCheckCond &&
1959              "no RT checks generated although RtPtrChecking "
1960              "claimed checks are required");
1961     }
1962 
1963     if (!MemCheckBlock && !SCEVCheckBlock)
1964       return;
1965 
1966     // Unhook the temporary block with the checks, update various places
1967     // accordingly.
1968     if (SCEVCheckBlock)
1969       SCEVCheckBlock->replaceAllUsesWith(Preheader);
1970     if (MemCheckBlock)
1971       MemCheckBlock->replaceAllUsesWith(Preheader);
1972 
1973     if (SCEVCheckBlock) {
1974       SCEVCheckBlock->getTerminator()->moveBefore(Preheader->getTerminator());
1975       new UnreachableInst(Preheader->getContext(), SCEVCheckBlock);
1976       Preheader->getTerminator()->eraseFromParent();
1977     }
1978     if (MemCheckBlock) {
1979       MemCheckBlock->getTerminator()->moveBefore(Preheader->getTerminator());
1980       new UnreachableInst(Preheader->getContext(), MemCheckBlock);
1981       Preheader->getTerminator()->eraseFromParent();
1982     }
1983 
1984     DT->changeImmediateDominator(LoopHeader, Preheader);
1985     if (MemCheckBlock) {
1986       DT->eraseNode(MemCheckBlock);
1987       LI->removeBlock(MemCheckBlock);
1988     }
1989     if (SCEVCheckBlock) {
1990       DT->eraseNode(SCEVCheckBlock);
1991       LI->removeBlock(SCEVCheckBlock);
1992     }
1993   }
1994 
1995   /// Remove the created SCEV & memory runtime check blocks & instructions, if
1996   /// unused.
~GeneratedRTChecks()1997   ~GeneratedRTChecks() {
1998     SCEVExpanderCleaner SCEVCleaner(SCEVExp, *DT);
1999     SCEVExpanderCleaner MemCheckCleaner(MemCheckExp, *DT);
2000     if (!SCEVCheckCond)
2001       SCEVCleaner.markResultUsed();
2002 
2003     if (!MemRuntimeCheckCond)
2004       MemCheckCleaner.markResultUsed();
2005 
2006     if (MemRuntimeCheckCond) {
2007       auto &SE = *MemCheckExp.getSE();
2008       // Memory runtime check generation creates compares that use expanded
2009       // values. Remove them before running the SCEVExpanderCleaners.
2010       for (auto &I : make_early_inc_range(reverse(*MemCheckBlock))) {
2011         if (MemCheckExp.isInsertedInstruction(&I))
2012           continue;
2013         SE.forgetValue(&I);
2014         SE.eraseValueFromMap(&I);
2015         I.eraseFromParent();
2016       }
2017     }
2018     MemCheckCleaner.cleanup();
2019     SCEVCleaner.cleanup();
2020 
2021     if (SCEVCheckCond)
2022       SCEVCheckBlock->eraseFromParent();
2023     if (MemRuntimeCheckCond)
2024       MemCheckBlock->eraseFromParent();
2025   }
2026 
2027   /// Adds the generated SCEVCheckBlock before \p LoopVectorPreHeader and
2028   /// adjusts the branches to branch to the vector preheader or \p Bypass,
2029   /// depending on the generated condition.
emitSCEVChecks(Loop * L,BasicBlock * Bypass,BasicBlock * LoopVectorPreHeader,BasicBlock * LoopExitBlock)2030   BasicBlock *emitSCEVChecks(Loop *L, BasicBlock *Bypass,
2031                              BasicBlock *LoopVectorPreHeader,
2032                              BasicBlock *LoopExitBlock) {
2033     if (!SCEVCheckCond)
2034       return nullptr;
2035     if (auto *C = dyn_cast<ConstantInt>(SCEVCheckCond))
2036       if (C->isZero())
2037         return nullptr;
2038 
2039     auto *Pred = LoopVectorPreHeader->getSinglePredecessor();
2040 
2041     BranchInst::Create(LoopVectorPreHeader, SCEVCheckBlock);
2042     // Create new preheader for vector loop.
2043     if (auto *PL = LI->getLoopFor(LoopVectorPreHeader))
2044       PL->addBasicBlockToLoop(SCEVCheckBlock, *LI);
2045 
2046     SCEVCheckBlock->getTerminator()->eraseFromParent();
2047     SCEVCheckBlock->moveBefore(LoopVectorPreHeader);
2048     Pred->getTerminator()->replaceSuccessorWith(LoopVectorPreHeader,
2049                                                 SCEVCheckBlock);
2050 
2051     DT->addNewBlock(SCEVCheckBlock, Pred);
2052     DT->changeImmediateDominator(LoopVectorPreHeader, SCEVCheckBlock);
2053 
2054     ReplaceInstWithInst(
2055         SCEVCheckBlock->getTerminator(),
2056         BranchInst::Create(Bypass, LoopVectorPreHeader, SCEVCheckCond));
2057     // Mark the check as used, to prevent it from being removed during cleanup.
2058     SCEVCheckCond = nullptr;
2059     return SCEVCheckBlock;
2060   }
2061 
2062   /// Adds the generated MemCheckBlock before \p LoopVectorPreHeader and adjusts
2063   /// the branches to branch to the vector preheader or \p Bypass, depending on
2064   /// the generated condition.
emitMemRuntimeChecks(Loop * L,BasicBlock * Bypass,BasicBlock * LoopVectorPreHeader)2065   BasicBlock *emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass,
2066                                    BasicBlock *LoopVectorPreHeader) {
2067     // Check if we generated code that checks in runtime if arrays overlap.
2068     if (!MemRuntimeCheckCond)
2069       return nullptr;
2070 
2071     auto *Pred = LoopVectorPreHeader->getSinglePredecessor();
2072     Pred->getTerminator()->replaceSuccessorWith(LoopVectorPreHeader,
2073                                                 MemCheckBlock);
2074 
2075     DT->addNewBlock(MemCheckBlock, Pred);
2076     DT->changeImmediateDominator(LoopVectorPreHeader, MemCheckBlock);
2077     MemCheckBlock->moveBefore(LoopVectorPreHeader);
2078 
2079     if (auto *PL = LI->getLoopFor(LoopVectorPreHeader))
2080       PL->addBasicBlockToLoop(MemCheckBlock, *LI);
2081 
2082     ReplaceInstWithInst(
2083         MemCheckBlock->getTerminator(),
2084         BranchInst::Create(Bypass, LoopVectorPreHeader, MemRuntimeCheckCond));
2085     MemCheckBlock->getTerminator()->setDebugLoc(
2086         Pred->getTerminator()->getDebugLoc());
2087 
2088     // Mark the check as used, to prevent it from being removed during cleanup.
2089     MemRuntimeCheckCond = nullptr;
2090     return MemCheckBlock;
2091   }
2092 };
2093 
2094 // Return true if \p OuterLp is an outer loop annotated with hints for explicit
2095 // vectorization. The loop needs to be annotated with #pragma omp simd
2096 // simdlen(#) or #pragma clang vectorize(enable) vectorize_width(#). If the
2097 // vector length information is not provided, vectorization is not considered
2098 // explicit. Interleave hints are not allowed either. These limitations will be
2099 // relaxed in the future.
2100 // Please, note that we are currently forced to abuse the pragma 'clang
2101 // vectorize' semantics. This pragma provides *auto-vectorization hints*
2102 // (i.e., LV must check that vectorization is legal) whereas pragma 'omp simd'
2103 // provides *explicit vectorization hints* (LV can bypass legal checks and
2104 // assume that vectorization is legal). However, both hints are implemented
2105 // using the same metadata (llvm.loop.vectorize, processed by
2106 // LoopVectorizeHints). This will be fixed in the future when the native IR
2107 // representation for pragma 'omp simd' is introduced.
isExplicitVecOuterLoop(Loop * OuterLp,OptimizationRemarkEmitter * ORE)2108 static bool isExplicitVecOuterLoop(Loop *OuterLp,
2109                                    OptimizationRemarkEmitter *ORE) {
2110   assert(!OuterLp->isInnermost() && "This is not an outer loop");
2111   LoopVectorizeHints Hints(OuterLp, true /*DisableInterleaving*/, *ORE);
2112 
2113   // Only outer loops with an explicit vectorization hint are supported.
2114   // Unannotated outer loops are ignored.
2115   if (Hints.getForce() == LoopVectorizeHints::FK_Undefined)
2116     return false;
2117 
2118   Function *Fn = OuterLp->getHeader()->getParent();
2119   if (!Hints.allowVectorization(Fn, OuterLp,
2120                                 true /*VectorizeOnlyWhenForced*/)) {
2121     LLVM_DEBUG(dbgs() << "LV: Loop hints prevent outer loop vectorization.\n");
2122     return false;
2123   }
2124 
2125   if (Hints.getInterleave() > 1) {
2126     // TODO: Interleave support is future work.
2127     LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Interleave is not supported for "
2128                          "outer loops.\n");
2129     Hints.emitRemarkWithHints();
2130     return false;
2131   }
2132 
2133   return true;
2134 }
2135 
collectSupportedLoops(Loop & L,LoopInfo * LI,OptimizationRemarkEmitter * ORE,SmallVectorImpl<Loop * > & V)2136 static void collectSupportedLoops(Loop &L, LoopInfo *LI,
2137                                   OptimizationRemarkEmitter *ORE,
2138                                   SmallVectorImpl<Loop *> &V) {
2139   // Collect inner loops and outer loops without irreducible control flow. For
2140   // now, only collect outer loops that have explicit vectorization hints. If we
2141   // are stress testing the VPlan H-CFG construction, we collect the outermost
2142   // loop of every loop nest.
2143   if (L.isInnermost() || VPlanBuildStressTest ||
2144       (EnableVPlanNativePath && isExplicitVecOuterLoop(&L, ORE))) {
2145     LoopBlocksRPO RPOT(&L);
2146     RPOT.perform(LI);
2147     if (!containsIrreducibleCFG<const BasicBlock *>(RPOT, *LI)) {
2148       V.push_back(&L);
2149       // TODO: Collect inner loops inside marked outer loops in case
2150       // vectorization fails for the outer loop. Do not invoke
2151       // 'containsIrreducibleCFG' again for inner loops when the outer loop is
2152       // already known to be reducible. We can use an inherited attribute for
2153       // that.
2154       return;
2155     }
2156   }
2157   for (Loop *InnerL : L)
2158     collectSupportedLoops(*InnerL, LI, ORE, V);
2159 }
2160 
2161 namespace {
2162 
2163 /// The LoopVectorize Pass.
2164 struct LoopVectorize : public FunctionPass {
2165   /// Pass identification, replacement for typeid
2166   static char ID;
2167 
2168   LoopVectorizePass Impl;
2169 
LoopVectorize__anone42b58380311::LoopVectorize2170   explicit LoopVectorize(bool InterleaveOnlyWhenForced = false,
2171                          bool VectorizeOnlyWhenForced = false)
2172       : FunctionPass(ID),
2173         Impl({InterleaveOnlyWhenForced, VectorizeOnlyWhenForced}) {
2174     initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
2175   }
2176 
runOnFunction__anone42b58380311::LoopVectorize2177   bool runOnFunction(Function &F) override {
2178     if (skipFunction(F))
2179       return false;
2180 
2181     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
2182     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2183     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
2184     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2185     auto *BFI = &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI();
2186     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
2187     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
2188     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
2189     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
2190     auto *LAA = &getAnalysis<LoopAccessLegacyAnalysis>();
2191     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
2192     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
2193     auto *PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
2194 
2195     std::function<const LoopAccessInfo &(Loop &)> GetLAA =
2196         [&](Loop &L) -> const LoopAccessInfo & { return LAA->getInfo(&L); };
2197 
2198     return Impl.runImpl(F, *SE, *LI, *TTI, *DT, *BFI, TLI, *DB, *AA, *AC,
2199                         GetLAA, *ORE, PSI).MadeAnyChange;
2200   }
2201 
getAnalysisUsage__anone42b58380311::LoopVectorize2202   void getAnalysisUsage(AnalysisUsage &AU) const override {
2203     AU.addRequired<AssumptionCacheTracker>();
2204     AU.addRequired<BlockFrequencyInfoWrapperPass>();
2205     AU.addRequired<DominatorTreeWrapperPass>();
2206     AU.addRequired<LoopInfoWrapperPass>();
2207     AU.addRequired<ScalarEvolutionWrapperPass>();
2208     AU.addRequired<TargetTransformInfoWrapperPass>();
2209     AU.addRequired<AAResultsWrapperPass>();
2210     AU.addRequired<LoopAccessLegacyAnalysis>();
2211     AU.addRequired<DemandedBitsWrapperPass>();
2212     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
2213     AU.addRequired<InjectTLIMappingsLegacy>();
2214 
2215     // We currently do not preserve loopinfo/dominator analyses with outer loop
2216     // vectorization. Until this is addressed, mark these analyses as preserved
2217     // only for non-VPlan-native path.
2218     // TODO: Preserve Loop and Dominator analyses for VPlan-native path.
2219     if (!EnableVPlanNativePath) {
2220       AU.addPreserved<LoopInfoWrapperPass>();
2221       AU.addPreserved<DominatorTreeWrapperPass>();
2222     }
2223 
2224     AU.addPreserved<BasicAAWrapperPass>();
2225     AU.addPreserved<GlobalsAAWrapperPass>();
2226     AU.addRequired<ProfileSummaryInfoWrapperPass>();
2227   }
2228 };
2229 
2230 } // end anonymous namespace
2231 
2232 //===----------------------------------------------------------------------===//
2233 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
2234 // LoopVectorizationCostModel and LoopVectorizationPlanner.
2235 //===----------------------------------------------------------------------===//
2236 
getBroadcastInstrs(Value * V)2237 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
2238   // We need to place the broadcast of invariant variables outside the loop,
2239   // but only if it's proven safe to do so. Else, broadcast will be inside
2240   // vector loop body.
2241   Instruction *Instr = dyn_cast<Instruction>(V);
2242   bool SafeToHoist = OrigLoop->isLoopInvariant(V) &&
2243                      (!Instr ||
2244                       DT->dominates(Instr->getParent(), LoopVectorPreHeader));
2245   // Place the code for broadcasting invariant variables in the new preheader.
2246   IRBuilder<>::InsertPointGuard Guard(Builder);
2247   if (SafeToHoist)
2248     Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
2249 
2250   // Broadcast the scalar into all locations in the vector.
2251   Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
2252 
2253   return Shuf;
2254 }
2255 
createVectorIntOrFpInductionPHI(const InductionDescriptor & II,Value * Step,Value * Start,Instruction * EntryVal,VPValue * Def,VPValue * CastDef,VPTransformState & State)2256 void InnerLoopVectorizer::createVectorIntOrFpInductionPHI(
2257     const InductionDescriptor &II, Value *Step, Value *Start,
2258     Instruction *EntryVal, VPValue *Def, VPValue *CastDef,
2259     VPTransformState &State) {
2260   assert((isa<PHINode>(EntryVal) || isa<TruncInst>(EntryVal)) &&
2261          "Expected either an induction phi-node or a truncate of it!");
2262 
2263   // Construct the initial value of the vector IV in the vector loop preheader
2264   auto CurrIP = Builder.saveIP();
2265   Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
2266   if (isa<TruncInst>(EntryVal)) {
2267     assert(Start->getType()->isIntegerTy() &&
2268            "Truncation requires an integer type");
2269     auto *TruncType = cast<IntegerType>(EntryVal->getType());
2270     Step = Builder.CreateTrunc(Step, TruncType);
2271     Start = Builder.CreateCast(Instruction::Trunc, Start, TruncType);
2272   }
2273   Value *SplatStart = Builder.CreateVectorSplat(VF, Start);
2274   Value *SteppedStart =
2275       getStepVector(SplatStart, 0, Step, II.getInductionOpcode());
2276 
2277   // We create vector phi nodes for both integer and floating-point induction
2278   // variables. Here, we determine the kind of arithmetic we will perform.
2279   Instruction::BinaryOps AddOp;
2280   Instruction::BinaryOps MulOp;
2281   if (Step->getType()->isIntegerTy()) {
2282     AddOp = Instruction::Add;
2283     MulOp = Instruction::Mul;
2284   } else {
2285     AddOp = II.getInductionOpcode();
2286     MulOp = Instruction::FMul;
2287   }
2288 
2289   // Multiply the vectorization factor by the step using integer or
2290   // floating-point arithmetic as appropriate.
2291   Type *StepType = Step->getType();
2292   if (Step->getType()->isFloatingPointTy())
2293     StepType = IntegerType::get(StepType->getContext(),
2294                                 StepType->getScalarSizeInBits());
2295   Value *RuntimeVF = getRuntimeVF(Builder, StepType, VF);
2296   if (Step->getType()->isFloatingPointTy())
2297     RuntimeVF = Builder.CreateSIToFP(RuntimeVF, Step->getType());
2298   Value *Mul = Builder.CreateBinOp(MulOp, Step, RuntimeVF);
2299 
2300   // Create a vector splat to use in the induction update.
2301   //
2302   // FIXME: If the step is non-constant, we create the vector splat with
2303   //        IRBuilder. IRBuilder can constant-fold the multiply, but it doesn't
2304   //        handle a constant vector splat.
2305   Value *SplatVF = isa<Constant>(Mul)
2306                        ? ConstantVector::getSplat(VF, cast<Constant>(Mul))
2307                        : Builder.CreateVectorSplat(VF, Mul);
2308   Builder.restoreIP(CurrIP);
2309 
2310   // We may need to add the step a number of times, depending on the unroll
2311   // factor. The last of those goes into the PHI.
2312   PHINode *VecInd = PHINode::Create(SteppedStart->getType(), 2, "vec.ind",
2313                                     &*LoopVectorBody->getFirstInsertionPt());
2314   VecInd->setDebugLoc(EntryVal->getDebugLoc());
2315   Instruction *LastInduction = VecInd;
2316   for (unsigned Part = 0; Part < UF; ++Part) {
2317     State.set(Def, LastInduction, Part);
2318 
2319     if (isa<TruncInst>(EntryVal))
2320       addMetadata(LastInduction, EntryVal);
2321     recordVectorLoopValueForInductionCast(II, EntryVal, LastInduction, CastDef,
2322                                           State, Part);
2323 
2324     LastInduction = cast<Instruction>(
2325         Builder.CreateBinOp(AddOp, LastInduction, SplatVF, "step.add"));
2326     LastInduction->setDebugLoc(EntryVal->getDebugLoc());
2327   }
2328 
2329   // Move the last step to the end of the latch block. This ensures consistent
2330   // placement of all induction updates.
2331   auto *LoopVectorLatch = LI->getLoopFor(LoopVectorBody)->getLoopLatch();
2332   auto *Br = cast<BranchInst>(LoopVectorLatch->getTerminator());
2333   auto *ICmp = cast<Instruction>(Br->getCondition());
2334   LastInduction->moveBefore(ICmp);
2335   LastInduction->setName("vec.ind.next");
2336 
2337   VecInd->addIncoming(SteppedStart, LoopVectorPreHeader);
2338   VecInd->addIncoming(LastInduction, LoopVectorLatch);
2339 }
2340 
shouldScalarizeInstruction(Instruction * I) const2341 bool InnerLoopVectorizer::shouldScalarizeInstruction(Instruction *I) const {
2342   return Cost->isScalarAfterVectorization(I, VF) ||
2343          Cost->isProfitableToScalarize(I, VF);
2344 }
2345 
needsScalarInduction(Instruction * IV) const2346 bool InnerLoopVectorizer::needsScalarInduction(Instruction *IV) const {
2347   if (shouldScalarizeInstruction(IV))
2348     return true;
2349   auto isScalarInst = [&](User *U) -> bool {
2350     auto *I = cast<Instruction>(U);
2351     return (OrigLoop->contains(I) && shouldScalarizeInstruction(I));
2352   };
2353   return llvm::any_of(IV->users(), isScalarInst);
2354 }
2355 
recordVectorLoopValueForInductionCast(const InductionDescriptor & ID,const Instruction * EntryVal,Value * VectorLoopVal,VPValue * CastDef,VPTransformState & State,unsigned Part,unsigned Lane)2356 void InnerLoopVectorizer::recordVectorLoopValueForInductionCast(
2357     const InductionDescriptor &ID, const Instruction *EntryVal,
2358     Value *VectorLoopVal, VPValue *CastDef, VPTransformState &State,
2359     unsigned Part, unsigned Lane) {
2360   assert((isa<PHINode>(EntryVal) || isa<TruncInst>(EntryVal)) &&
2361          "Expected either an induction phi-node or a truncate of it!");
2362 
2363   // This induction variable is not the phi from the original loop but the
2364   // newly-created IV based on the proof that casted Phi is equal to the
2365   // uncasted Phi in the vectorized loop (under a runtime guard possibly). It
2366   // re-uses the same InductionDescriptor that original IV uses but we don't
2367   // have to do any recording in this case - that is done when original IV is
2368   // processed.
2369   if (isa<TruncInst>(EntryVal))
2370     return;
2371 
2372   const SmallVectorImpl<Instruction *> &Casts = ID.getCastInsts();
2373   if (Casts.empty())
2374     return;
2375   // Only the first Cast instruction in the Casts vector is of interest.
2376   // The rest of the Casts (if exist) have no uses outside the
2377   // induction update chain itself.
2378   if (Lane < UINT_MAX)
2379     State.set(CastDef, VectorLoopVal, VPIteration(Part, Lane));
2380   else
2381     State.set(CastDef, VectorLoopVal, Part);
2382 }
2383 
widenIntOrFpInduction(PHINode * IV,Value * Start,TruncInst * Trunc,VPValue * Def,VPValue * CastDef,VPTransformState & State)2384 void InnerLoopVectorizer::widenIntOrFpInduction(PHINode *IV, Value *Start,
2385                                                 TruncInst *Trunc, VPValue *Def,
2386                                                 VPValue *CastDef,
2387                                                 VPTransformState &State) {
2388   assert((IV->getType()->isIntegerTy() || IV != OldInduction) &&
2389          "Primary induction variable must have an integer type");
2390 
2391   auto II = Legal->getInductionVars().find(IV);
2392   assert(II != Legal->getInductionVars().end() && "IV is not an induction");
2393 
2394   auto ID = II->second;
2395   assert(IV->getType() == ID.getStartValue()->getType() && "Types must match");
2396 
2397   // The value from the original loop to which we are mapping the new induction
2398   // variable.
2399   Instruction *EntryVal = Trunc ? cast<Instruction>(Trunc) : IV;
2400 
2401   auto &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
2402 
2403   // Generate code for the induction step. Note that induction steps are
2404   // required to be loop-invariant
2405   auto CreateStepValue = [&](const SCEV *Step) -> Value * {
2406     assert(PSE.getSE()->isLoopInvariant(Step, OrigLoop) &&
2407            "Induction step should be loop invariant");
2408     if (PSE.getSE()->isSCEVable(IV->getType())) {
2409       SCEVExpander Exp(*PSE.getSE(), DL, "induction");
2410       return Exp.expandCodeFor(Step, Step->getType(),
2411                                LoopVectorPreHeader->getTerminator());
2412     }
2413     return cast<SCEVUnknown>(Step)->getValue();
2414   };
2415 
2416   // The scalar value to broadcast. This is derived from the canonical
2417   // induction variable. If a truncation type is given, truncate the canonical
2418   // induction variable and step. Otherwise, derive these values from the
2419   // induction descriptor.
2420   auto CreateScalarIV = [&](Value *&Step) -> Value * {
2421     Value *ScalarIV = Induction;
2422     if (IV != OldInduction) {
2423       ScalarIV = IV->getType()->isIntegerTy()
2424                      ? Builder.CreateSExtOrTrunc(Induction, IV->getType())
2425                      : Builder.CreateCast(Instruction::SIToFP, Induction,
2426                                           IV->getType());
2427       ScalarIV = emitTransformedIndex(Builder, ScalarIV, PSE.getSE(), DL, ID);
2428       ScalarIV->setName("offset.idx");
2429     }
2430     if (Trunc) {
2431       auto *TruncType = cast<IntegerType>(Trunc->getType());
2432       assert(Step->getType()->isIntegerTy() &&
2433              "Truncation requires an integer step");
2434       ScalarIV = Builder.CreateTrunc(ScalarIV, TruncType);
2435       Step = Builder.CreateTrunc(Step, TruncType);
2436     }
2437     return ScalarIV;
2438   };
2439 
2440   // Create the vector values from the scalar IV, in the absence of creating a
2441   // vector IV.
2442   auto CreateSplatIV = [&](Value *ScalarIV, Value *Step) {
2443     Value *Broadcasted = getBroadcastInstrs(ScalarIV);
2444     for (unsigned Part = 0; Part < UF; ++Part) {
2445       assert(!VF.isScalable() && "scalable vectors not yet supported.");
2446       Value *EntryPart =
2447           getStepVector(Broadcasted, VF.getKnownMinValue() * Part, Step,
2448                         ID.getInductionOpcode());
2449       State.set(Def, EntryPart, Part);
2450       if (Trunc)
2451         addMetadata(EntryPart, Trunc);
2452       recordVectorLoopValueForInductionCast(ID, EntryVal, EntryPart, CastDef,
2453                                             State, Part);
2454     }
2455   };
2456 
2457   // Fast-math-flags propagate from the original induction instruction.
2458   IRBuilder<>::FastMathFlagGuard FMFG(Builder);
2459   if (ID.getInductionBinOp() && isa<FPMathOperator>(ID.getInductionBinOp()))
2460     Builder.setFastMathFlags(ID.getInductionBinOp()->getFastMathFlags());
2461 
2462   // Now do the actual transformations, and start with creating the step value.
2463   Value *Step = CreateStepValue(ID.getStep());
2464   if (VF.isZero() || VF.isScalar()) {
2465     Value *ScalarIV = CreateScalarIV(Step);
2466     CreateSplatIV(ScalarIV, Step);
2467     return;
2468   }
2469 
2470   // Determine if we want a scalar version of the induction variable. This is
2471   // true if the induction variable itself is not widened, or if it has at
2472   // least one user in the loop that is not widened.
2473   auto NeedsScalarIV = needsScalarInduction(EntryVal);
2474   if (!NeedsScalarIV) {
2475     createVectorIntOrFpInductionPHI(ID, Step, Start, EntryVal, Def, CastDef,
2476                                     State);
2477     return;
2478   }
2479 
2480   // Try to create a new independent vector induction variable. If we can't
2481   // create the phi node, we will splat the scalar induction variable in each
2482   // loop iteration.
2483   if (!shouldScalarizeInstruction(EntryVal)) {
2484     createVectorIntOrFpInductionPHI(ID, Step, Start, EntryVal, Def, CastDef,
2485                                     State);
2486     Value *ScalarIV = CreateScalarIV(Step);
2487     // Create scalar steps that can be used by instructions we will later
2488     // scalarize. Note that the addition of the scalar steps will not increase
2489     // the number of instructions in the loop in the common case prior to
2490     // InstCombine. We will be trading one vector extract for each scalar step.
2491     buildScalarSteps(ScalarIV, Step, EntryVal, ID, Def, CastDef, State);
2492     return;
2493   }
2494 
2495   // All IV users are scalar instructions, so only emit a scalar IV, not a
2496   // vectorised IV. Except when we tail-fold, then the splat IV feeds the
2497   // predicate used by the masked loads/stores.
2498   Value *ScalarIV = CreateScalarIV(Step);
2499   if (!Cost->isScalarEpilogueAllowed())
2500     CreateSplatIV(ScalarIV, Step);
2501   buildScalarSteps(ScalarIV, Step, EntryVal, ID, Def, CastDef, State);
2502 }
2503 
getStepVector(Value * Val,int StartIdx,Value * Step,Instruction::BinaryOps BinOp)2504 Value *InnerLoopVectorizer::getStepVector(Value *Val, int StartIdx, Value *Step,
2505                                           Instruction::BinaryOps BinOp) {
2506   // Create and check the types.
2507   auto *ValVTy = cast<VectorType>(Val->getType());
2508   ElementCount VLen = ValVTy->getElementCount();
2509 
2510   Type *STy = Val->getType()->getScalarType();
2511   assert((STy->isIntegerTy() || STy->isFloatingPointTy()) &&
2512          "Induction Step must be an integer or FP");
2513   assert(Step->getType() == STy && "Step has wrong type");
2514 
2515   SmallVector<Constant *, 8> Indices;
2516 
2517   // Create a vector of consecutive numbers from zero to VF.
2518   VectorType *InitVecValVTy = ValVTy;
2519   Type *InitVecValSTy = STy;
2520   if (STy->isFloatingPointTy()) {
2521     InitVecValSTy =
2522         IntegerType::get(STy->getContext(), STy->getScalarSizeInBits());
2523     InitVecValVTy = VectorType::get(InitVecValSTy, VLen);
2524   }
2525   Value *InitVec = Builder.CreateStepVector(InitVecValVTy);
2526 
2527   // Add on StartIdx
2528   Value *StartIdxSplat = Builder.CreateVectorSplat(
2529       VLen, ConstantInt::get(InitVecValSTy, StartIdx));
2530   InitVec = Builder.CreateAdd(InitVec, StartIdxSplat);
2531 
2532   if (STy->isIntegerTy()) {
2533     Step = Builder.CreateVectorSplat(VLen, Step);
2534     assert(Step->getType() == Val->getType() && "Invalid step vec");
2535     // FIXME: The newly created binary instructions should contain nsw/nuw flags,
2536     // which can be found from the original scalar operations.
2537     Step = Builder.CreateMul(InitVec, Step);
2538     return Builder.CreateAdd(Val, Step, "induction");
2539   }
2540 
2541   // Floating point induction.
2542   assert((BinOp == Instruction::FAdd || BinOp == Instruction::FSub) &&
2543          "Binary Opcode should be specified for FP induction");
2544   InitVec = Builder.CreateUIToFP(InitVec, ValVTy);
2545   Step = Builder.CreateVectorSplat(VLen, Step);
2546   Value *MulOp = Builder.CreateFMul(InitVec, Step);
2547   return Builder.CreateBinOp(BinOp, Val, MulOp, "induction");
2548 }
2549 
buildScalarSteps(Value * ScalarIV,Value * Step,Instruction * EntryVal,const InductionDescriptor & ID,VPValue * Def,VPValue * CastDef,VPTransformState & State)2550 void InnerLoopVectorizer::buildScalarSteps(Value *ScalarIV, Value *Step,
2551                                            Instruction *EntryVal,
2552                                            const InductionDescriptor &ID,
2553                                            VPValue *Def, VPValue *CastDef,
2554                                            VPTransformState &State) {
2555   // We shouldn't have to build scalar steps if we aren't vectorizing.
2556   assert(VF.isVector() && "VF should be greater than one");
2557   // Get the value type and ensure it and the step have the same integer type.
2558   Type *ScalarIVTy = ScalarIV->getType()->getScalarType();
2559   assert(ScalarIVTy == Step->getType() &&
2560          "Val and Step should have the same type");
2561 
2562   // We build scalar steps for both integer and floating-point induction
2563   // variables. Here, we determine the kind of arithmetic we will perform.
2564   Instruction::BinaryOps AddOp;
2565   Instruction::BinaryOps MulOp;
2566   if (ScalarIVTy->isIntegerTy()) {
2567     AddOp = Instruction::Add;
2568     MulOp = Instruction::Mul;
2569   } else {
2570     AddOp = ID.getInductionOpcode();
2571     MulOp = Instruction::FMul;
2572   }
2573 
2574   // Determine the number of scalars we need to generate for each unroll
2575   // iteration. If EntryVal is uniform, we only need to generate the first
2576   // lane. Otherwise, we generate all VF values.
2577   bool IsUniform =
2578       Cost->isUniformAfterVectorization(cast<Instruction>(EntryVal), VF);
2579   unsigned Lanes = IsUniform ? 1 : VF.getKnownMinValue();
2580   // Compute the scalar steps and save the results in State.
2581   Type *IntStepTy = IntegerType::get(ScalarIVTy->getContext(),
2582                                      ScalarIVTy->getScalarSizeInBits());
2583   Type *VecIVTy = nullptr;
2584   Value *UnitStepVec = nullptr, *SplatStep = nullptr, *SplatIV = nullptr;
2585   if (!IsUniform && VF.isScalable()) {
2586     VecIVTy = VectorType::get(ScalarIVTy, VF);
2587     UnitStepVec = Builder.CreateStepVector(VectorType::get(IntStepTy, VF));
2588     SplatStep = Builder.CreateVectorSplat(VF, Step);
2589     SplatIV = Builder.CreateVectorSplat(VF, ScalarIV);
2590   }
2591 
2592   for (unsigned Part = 0; Part < UF; ++Part) {
2593     Value *StartIdx0 =
2594         createStepForVF(Builder, ConstantInt::get(IntStepTy, Part), VF);
2595 
2596     if (!IsUniform && VF.isScalable()) {
2597       auto *SplatStartIdx = Builder.CreateVectorSplat(VF, StartIdx0);
2598       auto *InitVec = Builder.CreateAdd(SplatStartIdx, UnitStepVec);
2599       if (ScalarIVTy->isFloatingPointTy())
2600         InitVec = Builder.CreateSIToFP(InitVec, VecIVTy);
2601       auto *Mul = Builder.CreateBinOp(MulOp, InitVec, SplatStep);
2602       auto *Add = Builder.CreateBinOp(AddOp, SplatIV, Mul);
2603       State.set(Def, Add, Part);
2604       recordVectorLoopValueForInductionCast(ID, EntryVal, Add, CastDef, State,
2605                                             Part);
2606       // It's useful to record the lane values too for the known minimum number
2607       // of elements so we do those below. This improves the code quality when
2608       // trying to extract the first element, for example.
2609     }
2610 
2611     if (ScalarIVTy->isFloatingPointTy())
2612       StartIdx0 = Builder.CreateSIToFP(StartIdx0, ScalarIVTy);
2613 
2614     for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
2615       Value *StartIdx = Builder.CreateBinOp(
2616           AddOp, StartIdx0, getSignedIntOrFpConstant(ScalarIVTy, Lane));
2617       // The step returned by `createStepForVF` is a runtime-evaluated value
2618       // when VF is scalable. Otherwise, it should be folded into a Constant.
2619       assert((VF.isScalable() || isa<Constant>(StartIdx)) &&
2620              "Expected StartIdx to be folded to a constant when VF is not "
2621              "scalable");
2622       auto *Mul = Builder.CreateBinOp(MulOp, StartIdx, Step);
2623       auto *Add = Builder.CreateBinOp(AddOp, ScalarIV, Mul);
2624       State.set(Def, Add, VPIteration(Part, Lane));
2625       recordVectorLoopValueForInductionCast(ID, EntryVal, Add, CastDef, State,
2626                                             Part, Lane);
2627     }
2628   }
2629 }
2630 
packScalarIntoVectorValue(VPValue * Def,const VPIteration & Instance,VPTransformState & State)2631 void InnerLoopVectorizer::packScalarIntoVectorValue(VPValue *Def,
2632                                                     const VPIteration &Instance,
2633                                                     VPTransformState &State) {
2634   Value *ScalarInst = State.get(Def, Instance);
2635   Value *VectorValue = State.get(Def, Instance.Part);
2636   VectorValue = Builder.CreateInsertElement(
2637       VectorValue, ScalarInst,
2638       Instance.Lane.getAsRuntimeExpr(State.Builder, VF));
2639   State.set(Def, VectorValue, Instance.Part);
2640 }
2641 
reverseVector(Value * Vec)2642 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
2643   assert(Vec->getType()->isVectorTy() && "Invalid type");
2644   return Builder.CreateVectorReverse(Vec, "reverse");
2645 }
2646 
2647 // Return whether we allow using masked interleave-groups (for dealing with
2648 // strided loads/stores that reside in predicated blocks, or for dealing
2649 // with gaps).
useMaskedInterleavedAccesses(const TargetTransformInfo & TTI)2650 static bool useMaskedInterleavedAccesses(const TargetTransformInfo &TTI) {
2651   // If an override option has been passed in for interleaved accesses, use it.
2652   if (EnableMaskedInterleavedMemAccesses.getNumOccurrences() > 0)
2653     return EnableMaskedInterleavedMemAccesses;
2654 
2655   return TTI.enableMaskedInterleavedAccessVectorization();
2656 }
2657 
2658 // Try to vectorize the interleave group that \p Instr belongs to.
2659 //
2660 // E.g. Translate following interleaved load group (factor = 3):
2661 //   for (i = 0; i < N; i+=3) {
2662 //     R = Pic[i];             // Member of index 0
2663 //     G = Pic[i+1];           // Member of index 1
2664 //     B = Pic[i+2];           // Member of index 2
2665 //     ... // do something to R, G, B
2666 //   }
2667 // To:
2668 //   %wide.vec = load <12 x i32>                       ; Read 4 tuples of R,G,B
2669 //   %R.vec = shuffle %wide.vec, poison, <0, 3, 6, 9>   ; R elements
2670 //   %G.vec = shuffle %wide.vec, poison, <1, 4, 7, 10>  ; G elements
2671 //   %B.vec = shuffle %wide.vec, poison, <2, 5, 8, 11>  ; B elements
2672 //
2673 // Or translate following interleaved store group (factor = 3):
2674 //   for (i = 0; i < N; i+=3) {
2675 //     ... do something to R, G, B
2676 //     Pic[i]   = R;           // Member of index 0
2677 //     Pic[i+1] = G;           // Member of index 1
2678 //     Pic[i+2] = B;           // Member of index 2
2679 //   }
2680 // To:
2681 //   %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
2682 //   %B_U.vec = shuffle %B.vec, poison, <0, 1, 2, 3, u, u, u, u>
2683 //   %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
2684 //        <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>    ; Interleave R,G,B elements
2685 //   store <12 x i32> %interleaved.vec              ; Write 4 tuples of R,G,B
vectorizeInterleaveGroup(const InterleaveGroup<Instruction> * Group,ArrayRef<VPValue * > VPDefs,VPTransformState & State,VPValue * Addr,ArrayRef<VPValue * > StoredValues,VPValue * BlockInMask)2686 void InnerLoopVectorizer::vectorizeInterleaveGroup(
2687     const InterleaveGroup<Instruction> *Group, ArrayRef<VPValue *> VPDefs,
2688     VPTransformState &State, VPValue *Addr, ArrayRef<VPValue *> StoredValues,
2689     VPValue *BlockInMask) {
2690   Instruction *Instr = Group->getInsertPos();
2691   const DataLayout &DL = Instr->getModule()->getDataLayout();
2692 
2693   // Prepare for the vector type of the interleaved load/store.
2694   Type *ScalarTy = getMemInstValueType(Instr);
2695   unsigned InterleaveFactor = Group->getFactor();
2696   assert(!VF.isScalable() && "scalable vectors not yet supported.");
2697   auto *VecTy = VectorType::get(ScalarTy, VF * InterleaveFactor);
2698 
2699   // Prepare for the new pointers.
2700   SmallVector<Value *, 2> AddrParts;
2701   unsigned Index = Group->getIndex(Instr);
2702 
2703   // TODO: extend the masked interleaved-group support to reversed access.
2704   assert((!BlockInMask || !Group->isReverse()) &&
2705          "Reversed masked interleave-group not supported.");
2706 
2707   // If the group is reverse, adjust the index to refer to the last vector lane
2708   // instead of the first. We adjust the index from the first vector lane,
2709   // rather than directly getting the pointer for lane VF - 1, because the
2710   // pointer operand of the interleaved access is supposed to be uniform. For
2711   // uniform instructions, we're only required to generate a value for the
2712   // first vector lane in each unroll iteration.
2713   if (Group->isReverse())
2714     Index += (VF.getKnownMinValue() - 1) * Group->getFactor();
2715 
2716   for (unsigned Part = 0; Part < UF; Part++) {
2717     Value *AddrPart = State.get(Addr, VPIteration(Part, 0));
2718     setDebugLocFromInst(Builder, AddrPart);
2719 
2720     // Notice current instruction could be any index. Need to adjust the address
2721     // to the member of index 0.
2722     //
2723     // E.g.  a = A[i+1];     // Member of index 1 (Current instruction)
2724     //       b = A[i];       // Member of index 0
2725     // Current pointer is pointed to A[i+1], adjust it to A[i].
2726     //
2727     // E.g.  A[i+1] = a;     // Member of index 1
2728     //       A[i]   = b;     // Member of index 0
2729     //       A[i+2] = c;     // Member of index 2 (Current instruction)
2730     // Current pointer is pointed to A[i+2], adjust it to A[i].
2731 
2732     bool InBounds = false;
2733     if (auto *gep = dyn_cast<GetElementPtrInst>(AddrPart->stripPointerCasts()))
2734       InBounds = gep->isInBounds();
2735     AddrPart = Builder.CreateGEP(ScalarTy, AddrPart, Builder.getInt32(-Index));
2736     cast<GetElementPtrInst>(AddrPart)->setIsInBounds(InBounds);
2737 
2738     // Cast to the vector pointer type.
2739     unsigned AddressSpace = AddrPart->getType()->getPointerAddressSpace();
2740     Type *PtrTy = VecTy->getPointerTo(AddressSpace);
2741     AddrParts.push_back(Builder.CreateBitCast(AddrPart, PtrTy));
2742   }
2743 
2744   setDebugLocFromInst(Builder, Instr);
2745   Value *PoisonVec = PoisonValue::get(VecTy);
2746 
2747   Value *MaskForGaps = nullptr;
2748   if (Group->requiresScalarEpilogue() && !Cost->isScalarEpilogueAllowed()) {
2749     MaskForGaps = createBitMaskForGaps(Builder, VF.getKnownMinValue(), *Group);
2750     assert(MaskForGaps && "Mask for Gaps is required but it is null");
2751   }
2752 
2753   // Vectorize the interleaved load group.
2754   if (isa<LoadInst>(Instr)) {
2755     // For each unroll part, create a wide load for the group.
2756     SmallVector<Value *, 2> NewLoads;
2757     for (unsigned Part = 0; Part < UF; Part++) {
2758       Instruction *NewLoad;
2759       if (BlockInMask || MaskForGaps) {
2760         assert(useMaskedInterleavedAccesses(*TTI) &&
2761                "masked interleaved groups are not allowed.");
2762         Value *GroupMask = MaskForGaps;
2763         if (BlockInMask) {
2764           Value *BlockInMaskPart = State.get(BlockInMask, Part);
2765           Value *ShuffledMask = Builder.CreateShuffleVector(
2766               BlockInMaskPart,
2767               createReplicatedMask(InterleaveFactor, VF.getKnownMinValue()),
2768               "interleaved.mask");
2769           GroupMask = MaskForGaps
2770                           ? Builder.CreateBinOp(Instruction::And, ShuffledMask,
2771                                                 MaskForGaps)
2772                           : ShuffledMask;
2773         }
2774         NewLoad =
2775             Builder.CreateMaskedLoad(AddrParts[Part], Group->getAlign(),
2776                                      GroupMask, PoisonVec, "wide.masked.vec");
2777       }
2778       else
2779         NewLoad = Builder.CreateAlignedLoad(VecTy, AddrParts[Part],
2780                                             Group->getAlign(), "wide.vec");
2781       Group->addMetadata(NewLoad);
2782       NewLoads.push_back(NewLoad);
2783     }
2784 
2785     // For each member in the group, shuffle out the appropriate data from the
2786     // wide loads.
2787     unsigned J = 0;
2788     for (unsigned I = 0; I < InterleaveFactor; ++I) {
2789       Instruction *Member = Group->getMember(I);
2790 
2791       // Skip the gaps in the group.
2792       if (!Member)
2793         continue;
2794 
2795       auto StrideMask =
2796           createStrideMask(I, InterleaveFactor, VF.getKnownMinValue());
2797       for (unsigned Part = 0; Part < UF; Part++) {
2798         Value *StridedVec = Builder.CreateShuffleVector(
2799             NewLoads[Part], StrideMask, "strided.vec");
2800 
2801         // If this member has different type, cast the result type.
2802         if (Member->getType() != ScalarTy) {
2803           assert(!VF.isScalable() && "VF is assumed to be non scalable.");
2804           VectorType *OtherVTy = VectorType::get(Member->getType(), VF);
2805           StridedVec = createBitOrPointerCast(StridedVec, OtherVTy, DL);
2806         }
2807 
2808         if (Group->isReverse())
2809           StridedVec = reverseVector(StridedVec);
2810 
2811         State.set(VPDefs[J], StridedVec, Part);
2812       }
2813       ++J;
2814     }
2815     return;
2816   }
2817 
2818   // The sub vector type for current instruction.
2819   auto *SubVT = VectorType::get(ScalarTy, VF);
2820 
2821   // Vectorize the interleaved store group.
2822   for (unsigned Part = 0; Part < UF; Part++) {
2823     // Collect the stored vector from each member.
2824     SmallVector<Value *, 4> StoredVecs;
2825     for (unsigned i = 0; i < InterleaveFactor; i++) {
2826       // Interleaved store group doesn't allow a gap, so each index has a member
2827       assert(Group->getMember(i) && "Fail to get a member from an interleaved store group");
2828 
2829       Value *StoredVec = State.get(StoredValues[i], Part);
2830 
2831       if (Group->isReverse())
2832         StoredVec = reverseVector(StoredVec);
2833 
2834       // If this member has different type, cast it to a unified type.
2835 
2836       if (StoredVec->getType() != SubVT)
2837         StoredVec = createBitOrPointerCast(StoredVec, SubVT, DL);
2838 
2839       StoredVecs.push_back(StoredVec);
2840     }
2841 
2842     // Concatenate all vectors into a wide vector.
2843     Value *WideVec = concatenateVectors(Builder, StoredVecs);
2844 
2845     // Interleave the elements in the wide vector.
2846     Value *IVec = Builder.CreateShuffleVector(
2847         WideVec, createInterleaveMask(VF.getKnownMinValue(), InterleaveFactor),
2848         "interleaved.vec");
2849 
2850     Instruction *NewStoreInstr;
2851     if (BlockInMask) {
2852       Value *BlockInMaskPart = State.get(BlockInMask, Part);
2853       Value *ShuffledMask = Builder.CreateShuffleVector(
2854           BlockInMaskPart,
2855           createReplicatedMask(InterleaveFactor, VF.getKnownMinValue()),
2856           "interleaved.mask");
2857       NewStoreInstr = Builder.CreateMaskedStore(
2858           IVec, AddrParts[Part], Group->getAlign(), ShuffledMask);
2859     }
2860     else
2861       NewStoreInstr =
2862           Builder.CreateAlignedStore(IVec, AddrParts[Part], Group->getAlign());
2863 
2864     Group->addMetadata(NewStoreInstr);
2865   }
2866 }
2867 
vectorizeMemoryInstruction(Instruction * Instr,VPTransformState & State,VPValue * Def,VPValue * Addr,VPValue * StoredValue,VPValue * BlockInMask)2868 void InnerLoopVectorizer::vectorizeMemoryInstruction(
2869     Instruction *Instr, VPTransformState &State, VPValue *Def, VPValue *Addr,
2870     VPValue *StoredValue, VPValue *BlockInMask) {
2871   // Attempt to issue a wide load.
2872   LoadInst *LI = dyn_cast<LoadInst>(Instr);
2873   StoreInst *SI = dyn_cast<StoreInst>(Instr);
2874 
2875   assert((LI || SI) && "Invalid Load/Store instruction");
2876   assert((!SI || StoredValue) && "No stored value provided for widened store");
2877   assert((!LI || !StoredValue) && "Stored value provided for widened load");
2878 
2879   LoopVectorizationCostModel::InstWidening Decision =
2880       Cost->getWideningDecision(Instr, VF);
2881   assert((Decision == LoopVectorizationCostModel::CM_Widen ||
2882           Decision == LoopVectorizationCostModel::CM_Widen_Reverse ||
2883           Decision == LoopVectorizationCostModel::CM_GatherScatter) &&
2884          "CM decision is not to widen the memory instruction");
2885 
2886   Type *ScalarDataTy = getMemInstValueType(Instr);
2887 
2888   auto *DataTy = VectorType::get(ScalarDataTy, VF);
2889   const Align Alignment = getLoadStoreAlignment(Instr);
2890 
2891   // Determine if the pointer operand of the access is either consecutive or
2892   // reverse consecutive.
2893   bool Reverse = (Decision == LoopVectorizationCostModel::CM_Widen_Reverse);
2894   bool ConsecutiveStride =
2895       Reverse || (Decision == LoopVectorizationCostModel::CM_Widen);
2896   bool CreateGatherScatter =
2897       (Decision == LoopVectorizationCostModel::CM_GatherScatter);
2898 
2899   // Either Ptr feeds a vector load/store, or a vector GEP should feed a vector
2900   // gather/scatter. Otherwise Decision should have been to Scalarize.
2901   assert((ConsecutiveStride || CreateGatherScatter) &&
2902          "The instruction should be scalarized");
2903   (void)ConsecutiveStride;
2904 
2905   VectorParts BlockInMaskParts(UF);
2906   bool isMaskRequired = BlockInMask;
2907   if (isMaskRequired)
2908     for (unsigned Part = 0; Part < UF; ++Part)
2909       BlockInMaskParts[Part] = State.get(BlockInMask, Part);
2910 
2911   const auto CreateVecPtr = [&](unsigned Part, Value *Ptr) -> Value * {
2912     // Calculate the pointer for the specific unroll-part.
2913     GetElementPtrInst *PartPtr = nullptr;
2914 
2915     bool InBounds = false;
2916     if (auto *gep = dyn_cast<GetElementPtrInst>(Ptr->stripPointerCasts()))
2917       InBounds = gep->isInBounds();
2918     if (Reverse) {
2919       // If the address is consecutive but reversed, then the
2920       // wide store needs to start at the last vector element.
2921       // RunTimeVF =  VScale * VF.getKnownMinValue()
2922       // For fixed-width VScale is 1, then RunTimeVF = VF.getKnownMinValue()
2923       Value *RunTimeVF = getRuntimeVF(Builder, Builder.getInt32Ty(), VF);
2924       // NumElt = -Part * RunTimeVF
2925       Value *NumElt = Builder.CreateMul(Builder.getInt32(-Part), RunTimeVF);
2926       // LastLane = 1 - RunTimeVF
2927       Value *LastLane = Builder.CreateSub(Builder.getInt32(1), RunTimeVF);
2928       PartPtr =
2929           cast<GetElementPtrInst>(Builder.CreateGEP(ScalarDataTy, Ptr, NumElt));
2930       PartPtr->setIsInBounds(InBounds);
2931       PartPtr = cast<GetElementPtrInst>(
2932           Builder.CreateGEP(ScalarDataTy, PartPtr, LastLane));
2933       PartPtr->setIsInBounds(InBounds);
2934       if (isMaskRequired) // Reverse of a null all-one mask is a null mask.
2935         BlockInMaskParts[Part] = reverseVector(BlockInMaskParts[Part]);
2936     } else {
2937       Value *Increment = createStepForVF(Builder, Builder.getInt32(Part), VF);
2938       PartPtr = cast<GetElementPtrInst>(
2939           Builder.CreateGEP(ScalarDataTy, Ptr, Increment));
2940       PartPtr->setIsInBounds(InBounds);
2941     }
2942 
2943     unsigned AddressSpace = Ptr->getType()->getPointerAddressSpace();
2944     return Builder.CreateBitCast(PartPtr, DataTy->getPointerTo(AddressSpace));
2945   };
2946 
2947   // Handle Stores:
2948   if (SI) {
2949     setDebugLocFromInst(Builder, SI);
2950 
2951     for (unsigned Part = 0; Part < UF; ++Part) {
2952       Instruction *NewSI = nullptr;
2953       Value *StoredVal = State.get(StoredValue, Part);
2954       if (CreateGatherScatter) {
2955         Value *MaskPart = isMaskRequired ? BlockInMaskParts[Part] : nullptr;
2956         Value *VectorGep = State.get(Addr, Part);
2957         NewSI = Builder.CreateMaskedScatter(StoredVal, VectorGep, Alignment,
2958                                             MaskPart);
2959       } else {
2960         if (Reverse) {
2961           // If we store to reverse consecutive memory locations, then we need
2962           // to reverse the order of elements in the stored value.
2963           StoredVal = reverseVector(StoredVal);
2964           // We don't want to update the value in the map as it might be used in
2965           // another expression. So don't call resetVectorValue(StoredVal).
2966         }
2967         auto *VecPtr = CreateVecPtr(Part, State.get(Addr, VPIteration(0, 0)));
2968         if (isMaskRequired)
2969           NewSI = Builder.CreateMaskedStore(StoredVal, VecPtr, Alignment,
2970                                             BlockInMaskParts[Part]);
2971         else
2972           NewSI = Builder.CreateAlignedStore(StoredVal, VecPtr, Alignment);
2973       }
2974       addMetadata(NewSI, SI);
2975     }
2976     return;
2977   }
2978 
2979   // Handle loads.
2980   assert(LI && "Must have a load instruction");
2981   setDebugLocFromInst(Builder, LI);
2982   for (unsigned Part = 0; Part < UF; ++Part) {
2983     Value *NewLI;
2984     if (CreateGatherScatter) {
2985       Value *MaskPart = isMaskRequired ? BlockInMaskParts[Part] : nullptr;
2986       Value *VectorGep = State.get(Addr, Part);
2987       NewLI = Builder.CreateMaskedGather(VectorGep, Alignment, MaskPart,
2988                                          nullptr, "wide.masked.gather");
2989       addMetadata(NewLI, LI);
2990     } else {
2991       auto *VecPtr = CreateVecPtr(Part, State.get(Addr, VPIteration(0, 0)));
2992       if (isMaskRequired)
2993         NewLI = Builder.CreateMaskedLoad(
2994             VecPtr, Alignment, BlockInMaskParts[Part], PoisonValue::get(DataTy),
2995             "wide.masked.load");
2996       else
2997         NewLI =
2998             Builder.CreateAlignedLoad(DataTy, VecPtr, Alignment, "wide.load");
2999 
3000       // Add metadata to the load, but setVectorValue to the reverse shuffle.
3001       addMetadata(NewLI, LI);
3002       if (Reverse)
3003         NewLI = reverseVector(NewLI);
3004     }
3005 
3006     State.set(Def, NewLI, Part);
3007   }
3008 }
3009 
scalarizeInstruction(Instruction * Instr,VPValue * Def,VPUser & User,const VPIteration & Instance,bool IfPredicateInstr,VPTransformState & State)3010 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr, VPValue *Def,
3011                                                VPUser &User,
3012                                                const VPIteration &Instance,
3013                                                bool IfPredicateInstr,
3014                                                VPTransformState &State) {
3015   assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
3016 
3017   // llvm.experimental.noalias.scope.decl intrinsics must only be duplicated for
3018   // the first lane and part.
3019   if (isa<NoAliasScopeDeclInst>(Instr))
3020     if (!Instance.isFirstIteration())
3021       return;
3022 
3023   setDebugLocFromInst(Builder, Instr);
3024 
3025   // Does this instruction return a value ?
3026   bool IsVoidRetTy = Instr->getType()->isVoidTy();
3027 
3028   Instruction *Cloned = Instr->clone();
3029   if (!IsVoidRetTy)
3030     Cloned->setName(Instr->getName() + ".cloned");
3031 
3032   State.Builder.SetInsertPoint(Builder.GetInsertBlock(),
3033                                Builder.GetInsertPoint());
3034   // Replace the operands of the cloned instructions with their scalar
3035   // equivalents in the new loop.
3036   for (unsigned op = 0, e = User.getNumOperands(); op != e; ++op) {
3037     auto *Operand = dyn_cast<Instruction>(Instr->getOperand(op));
3038     auto InputInstance = Instance;
3039     if (!Operand || !OrigLoop->contains(Operand) ||
3040         (Cost->isUniformAfterVectorization(Operand, State.VF)))
3041       InputInstance.Lane = VPLane::getFirstLane();
3042     auto *NewOp = State.get(User.getOperand(op), InputInstance);
3043     Cloned->setOperand(op, NewOp);
3044   }
3045   addNewMetadata(Cloned, Instr);
3046 
3047   // Place the cloned scalar in the new loop.
3048   Builder.Insert(Cloned);
3049 
3050   State.set(Def, Cloned, Instance);
3051 
3052   // If we just cloned a new assumption, add it the assumption cache.
3053   if (auto *II = dyn_cast<AssumeInst>(Cloned))
3054     AC->registerAssumption(II);
3055 
3056   // End if-block.
3057   if (IfPredicateInstr)
3058     PredicatedInstructions.push_back(Cloned);
3059 }
3060 
createInductionVariable(Loop * L,Value * Start,Value * End,Value * Step,Instruction * DL)3061 PHINode *InnerLoopVectorizer::createInductionVariable(Loop *L, Value *Start,
3062                                                       Value *End, Value *Step,
3063                                                       Instruction *DL) {
3064   BasicBlock *Header = L->getHeader();
3065   BasicBlock *Latch = L->getLoopLatch();
3066   // As we're just creating this loop, it's possible no latch exists
3067   // yet. If so, use the header as this will be a single block loop.
3068   if (!Latch)
3069     Latch = Header;
3070 
3071   IRBuilder<> Builder(&*Header->getFirstInsertionPt());
3072   Instruction *OldInst = getDebugLocFromInstOrOperands(OldInduction);
3073   setDebugLocFromInst(Builder, OldInst);
3074   auto *Induction = Builder.CreatePHI(Start->getType(), 2, "index");
3075 
3076   Builder.SetInsertPoint(Latch->getTerminator());
3077   setDebugLocFromInst(Builder, OldInst);
3078 
3079   // Create i+1 and fill the PHINode.
3080   Value *Next = Builder.CreateAdd(Induction, Step, "index.next");
3081   Induction->addIncoming(Start, L->getLoopPreheader());
3082   Induction->addIncoming(Next, Latch);
3083   // Create the compare.
3084   Value *ICmp = Builder.CreateICmpEQ(Next, End);
3085   Builder.CreateCondBr(ICmp, L->getUniqueExitBlock(), Header);
3086 
3087   // Now we have two terminators. Remove the old one from the block.
3088   Latch->getTerminator()->eraseFromParent();
3089 
3090   return Induction;
3091 }
3092 
getOrCreateTripCount(Loop * L)3093 Value *InnerLoopVectorizer::getOrCreateTripCount(Loop *L) {
3094   if (TripCount)
3095     return TripCount;
3096 
3097   assert(L && "Create Trip Count for null loop.");
3098   IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
3099   // Find the loop boundaries.
3100   ScalarEvolution *SE = PSE.getSE();
3101   const SCEV *BackedgeTakenCount = PSE.getBackedgeTakenCount();
3102   assert(!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
3103          "Invalid loop count");
3104 
3105   Type *IdxTy = Legal->getWidestInductionType();
3106   assert(IdxTy && "No type for induction");
3107 
3108   // The exit count might have the type of i64 while the phi is i32. This can
3109   // happen if we have an induction variable that is sign extended before the
3110   // compare. The only way that we get a backedge taken count is that the
3111   // induction variable was signed and as such will not overflow. In such a case
3112   // truncation is legal.
3113   if (SE->getTypeSizeInBits(BackedgeTakenCount->getType()) >
3114       IdxTy->getPrimitiveSizeInBits())
3115     BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount, IdxTy);
3116   BackedgeTakenCount = SE->getNoopOrZeroExtend(BackedgeTakenCount, IdxTy);
3117 
3118   // Get the total trip count from the count by adding 1.
3119   const SCEV *ExitCount = SE->getAddExpr(
3120       BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType()));
3121 
3122   const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
3123 
3124   // Expand the trip count and place the new instructions in the preheader.
3125   // Notice that the pre-header does not change, only the loop body.
3126   SCEVExpander Exp(*SE, DL, "induction");
3127 
3128   // Count holds the overall loop count (N).
3129   TripCount = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
3130                                 L->getLoopPreheader()->getTerminator());
3131 
3132   if (TripCount->getType()->isPointerTy())
3133     TripCount =
3134         CastInst::CreatePointerCast(TripCount, IdxTy, "exitcount.ptrcnt.to.int",
3135                                     L->getLoopPreheader()->getTerminator());
3136 
3137   return TripCount;
3138 }
3139 
getOrCreateVectorTripCount(Loop * L)3140 Value *InnerLoopVectorizer::getOrCreateVectorTripCount(Loop *L) {
3141   if (VectorTripCount)
3142     return VectorTripCount;
3143 
3144   Value *TC = getOrCreateTripCount(L);
3145   IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
3146 
3147   Type *Ty = TC->getType();
3148   // This is where we can make the step a runtime constant.
3149   Value *Step = createStepForVF(Builder, ConstantInt::get(Ty, UF), VF);
3150 
3151   // If the tail is to be folded by masking, round the number of iterations N
3152   // up to a multiple of Step instead of rounding down. This is done by first
3153   // adding Step-1 and then rounding down. Note that it's ok if this addition
3154   // overflows: the vector induction variable will eventually wrap to zero given
3155   // that it starts at zero and its Step is a power of two; the loop will then
3156   // exit, with the last early-exit vector comparison also producing all-true.
3157   if (Cost->foldTailByMasking()) {
3158     assert(isPowerOf2_32(VF.getKnownMinValue() * UF) &&
3159            "VF*UF must be a power of 2 when folding tail by masking");
3160     assert(!VF.isScalable() &&
3161            "Tail folding not yet supported for scalable vectors");
3162     TC = Builder.CreateAdd(
3163         TC, ConstantInt::get(Ty, VF.getKnownMinValue() * UF - 1), "n.rnd.up");
3164   }
3165 
3166   // Now we need to generate the expression for the part of the loop that the
3167   // vectorized body will execute. This is equal to N - (N % Step) if scalar
3168   // iterations are not required for correctness, or N - Step, otherwise. Step
3169   // is equal to the vectorization factor (number of SIMD elements) times the
3170   // unroll factor (number of SIMD instructions).
3171   Value *R = Builder.CreateURem(TC, Step, "n.mod.vf");
3172 
3173   // There are two cases where we need to ensure (at least) the last iteration
3174   // runs in the scalar remainder loop. Thus, if the step evenly divides
3175   // the trip count, we set the remainder to be equal to the step. If the step
3176   // does not evenly divide the trip count, no adjustment is necessary since
3177   // there will already be scalar iterations. Note that the minimum iterations
3178   // check ensures that N >= Step. The cases are:
3179   // 1) If there is a non-reversed interleaved group that may speculatively
3180   //    access memory out-of-bounds.
3181   // 2) If any instruction may follow a conditionally taken exit. That is, if
3182   //    the loop contains multiple exiting blocks, or a single exiting block
3183   //    which is not the latch.
3184   if (VF.isVector() && Cost->requiresScalarEpilogue()) {
3185     auto *IsZero = Builder.CreateICmpEQ(R, ConstantInt::get(R->getType(), 0));
3186     R = Builder.CreateSelect(IsZero, Step, R);
3187   }
3188 
3189   VectorTripCount = Builder.CreateSub(TC, R, "n.vec");
3190 
3191   return VectorTripCount;
3192 }
3193 
createBitOrPointerCast(Value * V,VectorType * DstVTy,const DataLayout & DL)3194 Value *InnerLoopVectorizer::createBitOrPointerCast(Value *V, VectorType *DstVTy,
3195                                                    const DataLayout &DL) {
3196   // Verify that V is a vector type with same number of elements as DstVTy.
3197   auto *DstFVTy = cast<FixedVectorType>(DstVTy);
3198   unsigned VF = DstFVTy->getNumElements();
3199   auto *SrcVecTy = cast<FixedVectorType>(V->getType());
3200   assert((VF == SrcVecTy->getNumElements()) && "Vector dimensions do not match");
3201   Type *SrcElemTy = SrcVecTy->getElementType();
3202   Type *DstElemTy = DstFVTy->getElementType();
3203   assert((DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy)) &&
3204          "Vector elements must have same size");
3205 
3206   // Do a direct cast if element types are castable.
3207   if (CastInst::isBitOrNoopPointerCastable(SrcElemTy, DstElemTy, DL)) {
3208     return Builder.CreateBitOrPointerCast(V, DstFVTy);
3209   }
3210   // V cannot be directly casted to desired vector type.
3211   // May happen when V is a floating point vector but DstVTy is a vector of
3212   // pointers or vice-versa. Handle this using a two-step bitcast using an
3213   // intermediate Integer type for the bitcast i.e. Ptr <-> Int <-> Float.
3214   assert((DstElemTy->isPointerTy() != SrcElemTy->isPointerTy()) &&
3215          "Only one type should be a pointer type");
3216   assert((DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy()) &&
3217          "Only one type should be a floating point type");
3218   Type *IntTy =
3219       IntegerType::getIntNTy(V->getContext(), DL.getTypeSizeInBits(SrcElemTy));
3220   auto *VecIntTy = FixedVectorType::get(IntTy, VF);
3221   Value *CastVal = Builder.CreateBitOrPointerCast(V, VecIntTy);
3222   return Builder.CreateBitOrPointerCast(CastVal, DstFVTy);
3223 }
3224 
emitMinimumIterationCountCheck(Loop * L,BasicBlock * Bypass)3225 void InnerLoopVectorizer::emitMinimumIterationCountCheck(Loop *L,
3226                                                          BasicBlock *Bypass) {
3227   Value *Count = getOrCreateTripCount(L);
3228   // Reuse existing vector loop preheader for TC checks.
3229   // Note that new preheader block is generated for vector loop.
3230   BasicBlock *const TCCheckBlock = LoopVectorPreHeader;
3231   IRBuilder<> Builder(TCCheckBlock->getTerminator());
3232 
3233   // Generate code to check if the loop's trip count is less than VF * UF, or
3234   // equal to it in case a scalar epilogue is required; this implies that the
3235   // vector trip count is zero. This check also covers the case where adding one
3236   // to the backedge-taken count overflowed leading to an incorrect trip count
3237   // of zero. In this case we will also jump to the scalar loop.
3238   auto P = Cost->requiresScalarEpilogue() ? ICmpInst::ICMP_ULE
3239                                           : ICmpInst::ICMP_ULT;
3240 
3241   // If tail is to be folded, vector loop takes care of all iterations.
3242   Value *CheckMinIters = Builder.getFalse();
3243   if (!Cost->foldTailByMasking()) {
3244     Value *Step =
3245         createStepForVF(Builder, ConstantInt::get(Count->getType(), UF), VF);
3246     CheckMinIters = Builder.CreateICmp(P, Count, Step, "min.iters.check");
3247   }
3248   // Create new preheader for vector loop.
3249   LoopVectorPreHeader =
3250       SplitBlock(TCCheckBlock, TCCheckBlock->getTerminator(), DT, LI, nullptr,
3251                  "vector.ph");
3252 
3253   assert(DT->properlyDominates(DT->getNode(TCCheckBlock),
3254                                DT->getNode(Bypass)->getIDom()) &&
3255          "TC check is expected to dominate Bypass");
3256 
3257   // Update dominator for Bypass & LoopExit.
3258   DT->changeImmediateDominator(Bypass, TCCheckBlock);
3259   DT->changeImmediateDominator(LoopExitBlock, TCCheckBlock);
3260 
3261   ReplaceInstWithInst(
3262       TCCheckBlock->getTerminator(),
3263       BranchInst::Create(Bypass, LoopVectorPreHeader, CheckMinIters));
3264   LoopBypassBlocks.push_back(TCCheckBlock);
3265 }
3266 
emitSCEVChecks(Loop * L,BasicBlock * Bypass)3267 BasicBlock *InnerLoopVectorizer::emitSCEVChecks(Loop *L, BasicBlock *Bypass) {
3268 
3269   BasicBlock *const SCEVCheckBlock =
3270       RTChecks.emitSCEVChecks(L, Bypass, LoopVectorPreHeader, LoopExitBlock);
3271   if (!SCEVCheckBlock)
3272     return nullptr;
3273 
3274   assert(!(SCEVCheckBlock->getParent()->hasOptSize() ||
3275            (OptForSizeBasedOnProfile &&
3276             Cost->Hints->getForce() != LoopVectorizeHints::FK_Enabled)) &&
3277          "Cannot SCEV check stride or overflow when optimizing for size");
3278 
3279 
3280   // Update dominator only if this is first RT check.
3281   if (LoopBypassBlocks.empty()) {
3282     DT->changeImmediateDominator(Bypass, SCEVCheckBlock);
3283     DT->changeImmediateDominator(LoopExitBlock, SCEVCheckBlock);
3284   }
3285 
3286   LoopBypassBlocks.push_back(SCEVCheckBlock);
3287   AddedSafetyChecks = true;
3288   return SCEVCheckBlock;
3289 }
3290 
emitMemRuntimeChecks(Loop * L,BasicBlock * Bypass)3291 BasicBlock *InnerLoopVectorizer::emitMemRuntimeChecks(Loop *L,
3292                                                       BasicBlock *Bypass) {
3293   // VPlan-native path does not do any analysis for runtime checks currently.
3294   if (EnableVPlanNativePath)
3295     return nullptr;
3296 
3297   BasicBlock *const MemCheckBlock =
3298       RTChecks.emitMemRuntimeChecks(L, Bypass, LoopVectorPreHeader);
3299 
3300   // Check if we generated code that checks in runtime if arrays overlap. We put
3301   // the checks into a separate block to make the more common case of few
3302   // elements faster.
3303   if (!MemCheckBlock)
3304     return nullptr;
3305 
3306   if (MemCheckBlock->getParent()->hasOptSize() || OptForSizeBasedOnProfile) {
3307     assert(Cost->Hints->getForce() == LoopVectorizeHints::FK_Enabled &&
3308            "Cannot emit memory checks when optimizing for size, unless forced "
3309            "to vectorize.");
3310     ORE->emit([&]() {
3311       return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationCodeSize",
3312                                         L->getStartLoc(), L->getHeader())
3313              << "Code-size may be reduced by not forcing "
3314                 "vectorization, or by source-code modifications "
3315                 "eliminating the need for runtime checks "
3316                 "(e.g., adding 'restrict').";
3317     });
3318   }
3319 
3320   LoopBypassBlocks.push_back(MemCheckBlock);
3321 
3322   AddedSafetyChecks = true;
3323 
3324   // We currently don't use LoopVersioning for the actual loop cloning but we
3325   // still use it to add the noalias metadata.
3326   LVer = std::make_unique<LoopVersioning>(
3327       *Legal->getLAI(),
3328       Legal->getLAI()->getRuntimePointerChecking()->getChecks(), OrigLoop, LI,
3329       DT, PSE.getSE());
3330   LVer->prepareNoAliasMetadata();
3331   return MemCheckBlock;
3332 }
3333 
emitTransformedIndex(IRBuilder<> & B,Value * Index,ScalarEvolution * SE,const DataLayout & DL,const InductionDescriptor & ID) const3334 Value *InnerLoopVectorizer::emitTransformedIndex(
3335     IRBuilder<> &B, Value *Index, ScalarEvolution *SE, const DataLayout &DL,
3336     const InductionDescriptor &ID) const {
3337 
3338   SCEVExpander Exp(*SE, DL, "induction");
3339   auto Step = ID.getStep();
3340   auto StartValue = ID.getStartValue();
3341   assert(Index->getType()->getScalarType() == Step->getType() &&
3342          "Index scalar type does not match StepValue type");
3343 
3344   // Note: the IR at this point is broken. We cannot use SE to create any new
3345   // SCEV and then expand it, hoping that SCEV's simplification will give us
3346   // a more optimal code. Unfortunately, attempt of doing so on invalid IR may
3347   // lead to various SCEV crashes. So all we can do is to use builder and rely
3348   // on InstCombine for future simplifications. Here we handle some trivial
3349   // cases only.
3350   auto CreateAdd = [&B](Value *X, Value *Y) {
3351     assert(X->getType() == Y->getType() && "Types don't match!");
3352     if (auto *CX = dyn_cast<ConstantInt>(X))
3353       if (CX->isZero())
3354         return Y;
3355     if (auto *CY = dyn_cast<ConstantInt>(Y))
3356       if (CY->isZero())
3357         return X;
3358     return B.CreateAdd(X, Y);
3359   };
3360 
3361   // We allow X to be a vector type, in which case Y will potentially be
3362   // splatted into a vector with the same element count.
3363   auto CreateMul = [&B](Value *X, Value *Y) {
3364     assert(X->getType()->getScalarType() == Y->getType() &&
3365            "Types don't match!");
3366     if (auto *CX = dyn_cast<ConstantInt>(X))
3367       if (CX->isOne())
3368         return Y;
3369     if (auto *CY = dyn_cast<ConstantInt>(Y))
3370       if (CY->isOne())
3371         return X;
3372     VectorType *XVTy = dyn_cast<VectorType>(X->getType());
3373     if (XVTy && !isa<VectorType>(Y->getType()))
3374       Y = B.CreateVectorSplat(XVTy->getElementCount(), Y);
3375     return B.CreateMul(X, Y);
3376   };
3377 
3378   // Get a suitable insert point for SCEV expansion. For blocks in the vector
3379   // loop, choose the end of the vector loop header (=LoopVectorBody), because
3380   // the DomTree is not kept up-to-date for additional blocks generated in the
3381   // vector loop. By using the header as insertion point, we guarantee that the
3382   // expanded instructions dominate all their uses.
3383   auto GetInsertPoint = [this, &B]() {
3384     BasicBlock *InsertBB = B.GetInsertPoint()->getParent();
3385     if (InsertBB != LoopVectorBody &&
3386         LI->getLoopFor(LoopVectorBody) == LI->getLoopFor(InsertBB))
3387       return LoopVectorBody->getTerminator();
3388     return &*B.GetInsertPoint();
3389   };
3390 
3391   switch (ID.getKind()) {
3392   case InductionDescriptor::IK_IntInduction: {
3393     assert(!isa<VectorType>(Index->getType()) &&
3394            "Vector indices not supported for integer inductions yet");
3395     assert(Index->getType() == StartValue->getType() &&
3396            "Index type does not match StartValue type");
3397     if (ID.getConstIntStepValue() && ID.getConstIntStepValue()->isMinusOne())
3398       return B.CreateSub(StartValue, Index);
3399     auto *Offset = CreateMul(
3400         Index, Exp.expandCodeFor(Step, Index->getType(), GetInsertPoint()));
3401     return CreateAdd(StartValue, Offset);
3402   }
3403   case InductionDescriptor::IK_PtrInduction: {
3404     assert(isa<SCEVConstant>(Step) &&
3405            "Expected constant step for pointer induction");
3406     return B.CreateGEP(
3407         StartValue->getType()->getPointerElementType(), StartValue,
3408         CreateMul(Index,
3409                   Exp.expandCodeFor(Step, Index->getType()->getScalarType(),
3410                                     GetInsertPoint())));
3411   }
3412   case InductionDescriptor::IK_FpInduction: {
3413     assert(!isa<VectorType>(Index->getType()) &&
3414            "Vector indices not supported for FP inductions yet");
3415     assert(Step->getType()->isFloatingPointTy() && "Expected FP Step value");
3416     auto InductionBinOp = ID.getInductionBinOp();
3417     assert(InductionBinOp &&
3418            (InductionBinOp->getOpcode() == Instruction::FAdd ||
3419             InductionBinOp->getOpcode() == Instruction::FSub) &&
3420            "Original bin op should be defined for FP induction");
3421 
3422     Value *StepValue = cast<SCEVUnknown>(Step)->getValue();
3423     Value *MulExp = B.CreateFMul(StepValue, Index);
3424     return B.CreateBinOp(InductionBinOp->getOpcode(), StartValue, MulExp,
3425                          "induction");
3426   }
3427   case InductionDescriptor::IK_NoInduction:
3428     return nullptr;
3429   }
3430   llvm_unreachable("invalid enum");
3431 }
3432 
createVectorLoopSkeleton(StringRef Prefix)3433 Loop *InnerLoopVectorizer::createVectorLoopSkeleton(StringRef Prefix) {
3434   LoopScalarBody = OrigLoop->getHeader();
3435   LoopVectorPreHeader = OrigLoop->getLoopPreheader();
3436   LoopExitBlock = OrigLoop->getUniqueExitBlock();
3437   assert(LoopExitBlock && "Must have an exit block");
3438   assert(LoopVectorPreHeader && "Invalid loop structure");
3439 
3440   LoopMiddleBlock =
3441       SplitBlock(LoopVectorPreHeader, LoopVectorPreHeader->getTerminator(), DT,
3442                  LI, nullptr, Twine(Prefix) + "middle.block");
3443   LoopScalarPreHeader =
3444       SplitBlock(LoopMiddleBlock, LoopMiddleBlock->getTerminator(), DT, LI,
3445                  nullptr, Twine(Prefix) + "scalar.ph");
3446 
3447   // Set up branch from middle block to the exit and scalar preheader blocks.
3448   // completeLoopSkeleton will update the condition to use an iteration check,
3449   // if required to decide whether to execute the remainder.
3450   BranchInst *BrInst =
3451       BranchInst::Create(LoopExitBlock, LoopScalarPreHeader, Builder.getTrue());
3452   auto *ScalarLatchTerm = OrigLoop->getLoopLatch()->getTerminator();
3453   BrInst->setDebugLoc(ScalarLatchTerm->getDebugLoc());
3454   ReplaceInstWithInst(LoopMiddleBlock->getTerminator(), BrInst);
3455 
3456   // We intentionally don't let SplitBlock to update LoopInfo since
3457   // LoopVectorBody should belong to another loop than LoopVectorPreHeader.
3458   // LoopVectorBody is explicitly added to the correct place few lines later.
3459   LoopVectorBody =
3460       SplitBlock(LoopVectorPreHeader, LoopVectorPreHeader->getTerminator(), DT,
3461                  nullptr, nullptr, Twine(Prefix) + "vector.body");
3462 
3463   // Update dominator for loop exit.
3464   DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
3465 
3466   // Create and register the new vector loop.
3467   Loop *Lp = LI->AllocateLoop();
3468   Loop *ParentLoop = OrigLoop->getParentLoop();
3469 
3470   // Insert the new loop into the loop nest and register the new basic blocks
3471   // before calling any utilities such as SCEV that require valid LoopInfo.
3472   if (ParentLoop) {
3473     ParentLoop->addChildLoop(Lp);
3474   } else {
3475     LI->addTopLevelLoop(Lp);
3476   }
3477   Lp->addBasicBlockToLoop(LoopVectorBody, *LI);
3478   return Lp;
3479 }
3480 
createInductionResumeValues(Loop * L,Value * VectorTripCount,std::pair<BasicBlock *,Value * > AdditionalBypass)3481 void InnerLoopVectorizer::createInductionResumeValues(
3482     Loop *L, Value *VectorTripCount,
3483     std::pair<BasicBlock *, Value *> AdditionalBypass) {
3484   assert(VectorTripCount && L && "Expected valid arguments");
3485   assert(((AdditionalBypass.first && AdditionalBypass.second) ||
3486           (!AdditionalBypass.first && !AdditionalBypass.second)) &&
3487          "Inconsistent information about additional bypass.");
3488   // We are going to resume the execution of the scalar loop.
3489   // Go over all of the induction variables that we found and fix the
3490   // PHIs that are left in the scalar version of the loop.
3491   // The starting values of PHI nodes depend on the counter of the last
3492   // iteration in the vectorized loop.
3493   // If we come from a bypass edge then we need to start from the original
3494   // start value.
3495   for (auto &InductionEntry : Legal->getInductionVars()) {
3496     PHINode *OrigPhi = InductionEntry.first;
3497     InductionDescriptor II = InductionEntry.second;
3498 
3499     // Create phi nodes to merge from the  backedge-taken check block.
3500     PHINode *BCResumeVal =
3501         PHINode::Create(OrigPhi->getType(), 3, "bc.resume.val",
3502                         LoopScalarPreHeader->getTerminator());
3503     // Copy original phi DL over to the new one.
3504     BCResumeVal->setDebugLoc(OrigPhi->getDebugLoc());
3505     Value *&EndValue = IVEndValues[OrigPhi];
3506     Value *EndValueFromAdditionalBypass = AdditionalBypass.second;
3507     if (OrigPhi == OldInduction) {
3508       // We know what the end value is.
3509       EndValue = VectorTripCount;
3510     } else {
3511       IRBuilder<> B(L->getLoopPreheader()->getTerminator());
3512 
3513       // Fast-math-flags propagate from the original induction instruction.
3514       if (II.getInductionBinOp() && isa<FPMathOperator>(II.getInductionBinOp()))
3515         B.setFastMathFlags(II.getInductionBinOp()->getFastMathFlags());
3516 
3517       Type *StepType = II.getStep()->getType();
3518       Instruction::CastOps CastOp =
3519           CastInst::getCastOpcode(VectorTripCount, true, StepType, true);
3520       Value *CRD = B.CreateCast(CastOp, VectorTripCount, StepType, "cast.crd");
3521       const DataLayout &DL = LoopScalarBody->getModule()->getDataLayout();
3522       EndValue = emitTransformedIndex(B, CRD, PSE.getSE(), DL, II);
3523       EndValue->setName("ind.end");
3524 
3525       // Compute the end value for the additional bypass (if applicable).
3526       if (AdditionalBypass.first) {
3527         B.SetInsertPoint(&(*AdditionalBypass.first->getFirstInsertionPt()));
3528         CastOp = CastInst::getCastOpcode(AdditionalBypass.second, true,
3529                                          StepType, true);
3530         CRD =
3531             B.CreateCast(CastOp, AdditionalBypass.second, StepType, "cast.crd");
3532         EndValueFromAdditionalBypass =
3533             emitTransformedIndex(B, CRD, PSE.getSE(), DL, II);
3534         EndValueFromAdditionalBypass->setName("ind.end");
3535       }
3536     }
3537     // The new PHI merges the original incoming value, in case of a bypass,
3538     // or the value at the end of the vectorized loop.
3539     BCResumeVal->addIncoming(EndValue, LoopMiddleBlock);
3540 
3541     // Fix the scalar body counter (PHI node).
3542     // The old induction's phi node in the scalar body needs the truncated
3543     // value.
3544     for (BasicBlock *BB : LoopBypassBlocks)
3545       BCResumeVal->addIncoming(II.getStartValue(), BB);
3546 
3547     if (AdditionalBypass.first)
3548       BCResumeVal->setIncomingValueForBlock(AdditionalBypass.first,
3549                                             EndValueFromAdditionalBypass);
3550 
3551     OrigPhi->setIncomingValueForBlock(LoopScalarPreHeader, BCResumeVal);
3552   }
3553 }
3554 
completeLoopSkeleton(Loop * L,MDNode * OrigLoopID)3555 BasicBlock *InnerLoopVectorizer::completeLoopSkeleton(Loop *L,
3556                                                       MDNode *OrigLoopID) {
3557   assert(L && "Expected valid loop.");
3558 
3559   // The trip counts should be cached by now.
3560   Value *Count = getOrCreateTripCount(L);
3561   Value *VectorTripCount = getOrCreateVectorTripCount(L);
3562 
3563   auto *ScalarLatchTerm = OrigLoop->getLoopLatch()->getTerminator();
3564 
3565   // Add a check in the middle block to see if we have completed
3566   // all of the iterations in the first vector loop.
3567   // If (N - N%VF) == N, then we *don't* need to run the remainder.
3568   // If tail is to be folded, we know we don't need to run the remainder.
3569   if (!Cost->foldTailByMasking()) {
3570     Instruction *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
3571                                         Count, VectorTripCount, "cmp.n",
3572                                         LoopMiddleBlock->getTerminator());
3573 
3574     // Here we use the same DebugLoc as the scalar loop latch terminator instead
3575     // of the corresponding compare because they may have ended up with
3576     // different line numbers and we want to avoid awkward line stepping while
3577     // debugging. Eg. if the compare has got a line number inside the loop.
3578     CmpN->setDebugLoc(ScalarLatchTerm->getDebugLoc());
3579     cast<BranchInst>(LoopMiddleBlock->getTerminator())->setCondition(CmpN);
3580   }
3581 
3582   // Get ready to start creating new instructions into the vectorized body.
3583   assert(LoopVectorPreHeader == L->getLoopPreheader() &&
3584          "Inconsistent vector loop preheader");
3585   Builder.SetInsertPoint(&*LoopVectorBody->getFirstInsertionPt());
3586 
3587   Optional<MDNode *> VectorizedLoopID =
3588       makeFollowupLoopID(OrigLoopID, {LLVMLoopVectorizeFollowupAll,
3589                                       LLVMLoopVectorizeFollowupVectorized});
3590   if (VectorizedLoopID.hasValue()) {
3591     L->setLoopID(VectorizedLoopID.getValue());
3592 
3593     // Do not setAlreadyVectorized if loop attributes have been defined
3594     // explicitly.
3595     return LoopVectorPreHeader;
3596   }
3597 
3598   // Keep all loop hints from the original loop on the vector loop (we'll
3599   // replace the vectorizer-specific hints below).
3600   if (MDNode *LID = OrigLoop->getLoopID())
3601     L->setLoopID(LID);
3602 
3603   LoopVectorizeHints Hints(L, true, *ORE);
3604   Hints.setAlreadyVectorized();
3605 
3606 #ifdef EXPENSIVE_CHECKS
3607   assert(DT->verify(DominatorTree::VerificationLevel::Fast));
3608   LI->verify(*DT);
3609 #endif
3610 
3611   return LoopVectorPreHeader;
3612 }
3613 
createVectorizedLoopSkeleton()3614 BasicBlock *InnerLoopVectorizer::createVectorizedLoopSkeleton() {
3615   /*
3616    In this function we generate a new loop. The new loop will contain
3617    the vectorized instructions while the old loop will continue to run the
3618    scalar remainder.
3619 
3620        [ ] <-- loop iteration number check.
3621     /   |
3622    /    v
3623   |    [ ] <-- vector loop bypass (may consist of multiple blocks).
3624   |  /  |
3625   | /   v
3626   ||   [ ]     <-- vector pre header.
3627   |/    |
3628   |     v
3629   |    [  ] \
3630   |    [  ]_|   <-- vector loop.
3631   |     |
3632   |     v
3633   |   -[ ]   <--- middle-block.
3634   |  /  |
3635   | /   v
3636   -|- >[ ]     <--- new preheader.
3637    |    |
3638    |    v
3639    |   [ ] \
3640    |   [ ]_|   <-- old scalar loop to handle remainder.
3641     \   |
3642      \  v
3643       >[ ]     <-- exit block.
3644    ...
3645    */
3646 
3647   // Get the metadata of the original loop before it gets modified.
3648   MDNode *OrigLoopID = OrigLoop->getLoopID();
3649 
3650   // Workaround!  Compute the trip count of the original loop and cache it
3651   // before we start modifying the CFG.  This code has a systemic problem
3652   // wherein it tries to run analysis over partially constructed IR; this is
3653   // wrong, and not simply for SCEV.  The trip count of the original loop
3654   // simply happens to be prone to hitting this in practice.  In theory, we
3655   // can hit the same issue for any SCEV, or ValueTracking query done during
3656   // mutation.  See PR49900.
3657   getOrCreateTripCount(OrigLoop);
3658 
3659   // Create an empty vector loop, and prepare basic blocks for the runtime
3660   // checks.
3661   Loop *Lp = createVectorLoopSkeleton("");
3662 
3663   // Now, compare the new count to zero. If it is zero skip the vector loop and
3664   // jump to the scalar loop. This check also covers the case where the
3665   // backedge-taken count is uint##_max: adding one to it will overflow leading
3666   // to an incorrect trip count of zero. In this (rare) case we will also jump
3667   // to the scalar loop.
3668   emitMinimumIterationCountCheck(Lp, LoopScalarPreHeader);
3669 
3670   // Generate the code to check any assumptions that we've made for SCEV
3671   // expressions.
3672   emitSCEVChecks(Lp, LoopScalarPreHeader);
3673 
3674   // Generate the code that checks in runtime if arrays overlap. We put the
3675   // checks into a separate block to make the more common case of few elements
3676   // faster.
3677   emitMemRuntimeChecks(Lp, LoopScalarPreHeader);
3678 
3679   // Some loops have a single integer induction variable, while other loops
3680   // don't. One example is c++ iterators that often have multiple pointer
3681   // induction variables. In the code below we also support a case where we
3682   // don't have a single induction variable.
3683   //
3684   // We try to obtain an induction variable from the original loop as hard
3685   // as possible. However if we don't find one that:
3686   //   - is an integer
3687   //   - counts from zero, stepping by one
3688   //   - is the size of the widest induction variable type
3689   // then we create a new one.
3690   OldInduction = Legal->getPrimaryInduction();
3691   Type *IdxTy = Legal->getWidestInductionType();
3692   Value *StartIdx = ConstantInt::get(IdxTy, 0);
3693   // The loop step is equal to the vectorization factor (num of SIMD elements)
3694   // times the unroll factor (num of SIMD instructions).
3695   Builder.SetInsertPoint(&*Lp->getHeader()->getFirstInsertionPt());
3696   Value *Step = createStepForVF(Builder, ConstantInt::get(IdxTy, UF), VF);
3697   Value *CountRoundDown = getOrCreateVectorTripCount(Lp);
3698   Induction =
3699       createInductionVariable(Lp, StartIdx, CountRoundDown, Step,
3700                               getDebugLocFromInstOrOperands(OldInduction));
3701 
3702   // Emit phis for the new starting index of the scalar loop.
3703   createInductionResumeValues(Lp, CountRoundDown);
3704 
3705   return completeLoopSkeleton(Lp, OrigLoopID);
3706 }
3707 
3708 // Fix up external users of the induction variable. At this point, we are
3709 // in LCSSA form, with all external PHIs that use the IV having one input value,
3710 // coming from the remainder loop. We need those PHIs to also have a correct
3711 // value for the IV when arriving directly from the middle block.
fixupIVUsers(PHINode * OrigPhi,const InductionDescriptor & II,Value * CountRoundDown,Value * EndValue,BasicBlock * MiddleBlock)3712 void InnerLoopVectorizer::fixupIVUsers(PHINode *OrigPhi,
3713                                        const InductionDescriptor &II,
3714                                        Value *CountRoundDown, Value *EndValue,
3715                                        BasicBlock *MiddleBlock) {
3716   // There are two kinds of external IV usages - those that use the value
3717   // computed in the last iteration (the PHI) and those that use the penultimate
3718   // value (the value that feeds into the phi from the loop latch).
3719   // We allow both, but they, obviously, have different values.
3720 
3721   assert(OrigLoop->getUniqueExitBlock() && "Expected a single exit block");
3722 
3723   DenseMap<Value *, Value *> MissingVals;
3724 
3725   // An external user of the last iteration's value should see the value that
3726   // the remainder loop uses to initialize its own IV.
3727   Value *PostInc = OrigPhi->getIncomingValueForBlock(OrigLoop->getLoopLatch());
3728   for (User *U : PostInc->users()) {
3729     Instruction *UI = cast<Instruction>(U);
3730     if (!OrigLoop->contains(UI)) {
3731       assert(isa<PHINode>(UI) && "Expected LCSSA form");
3732       MissingVals[UI] = EndValue;
3733     }
3734   }
3735 
3736   // An external user of the penultimate value need to see EndValue - Step.
3737   // The simplest way to get this is to recompute it from the constituent SCEVs,
3738   // that is Start + (Step * (CRD - 1)).
3739   for (User *U : OrigPhi->users()) {
3740     auto *UI = cast<Instruction>(U);
3741     if (!OrigLoop->contains(UI)) {
3742       const DataLayout &DL =
3743           OrigLoop->getHeader()->getModule()->getDataLayout();
3744       assert(isa<PHINode>(UI) && "Expected LCSSA form");
3745 
3746       IRBuilder<> B(MiddleBlock->getTerminator());
3747 
3748       // Fast-math-flags propagate from the original induction instruction.
3749       if (II.getInductionBinOp() && isa<FPMathOperator>(II.getInductionBinOp()))
3750         B.setFastMathFlags(II.getInductionBinOp()->getFastMathFlags());
3751 
3752       Value *CountMinusOne = B.CreateSub(
3753           CountRoundDown, ConstantInt::get(CountRoundDown->getType(), 1));
3754       Value *CMO =
3755           !II.getStep()->getType()->isIntegerTy()
3756               ? B.CreateCast(Instruction::SIToFP, CountMinusOne,
3757                              II.getStep()->getType())
3758               : B.CreateSExtOrTrunc(CountMinusOne, II.getStep()->getType());
3759       CMO->setName("cast.cmo");
3760       Value *Escape = emitTransformedIndex(B, CMO, PSE.getSE(), DL, II);
3761       Escape->setName("ind.escape");
3762       MissingVals[UI] = Escape;
3763     }
3764   }
3765 
3766   for (auto &I : MissingVals) {
3767     PHINode *PHI = cast<PHINode>(I.first);
3768     // One corner case we have to handle is two IVs "chasing" each-other,
3769     // that is %IV2 = phi [...], [ %IV1, %latch ]
3770     // In this case, if IV1 has an external use, we need to avoid adding both
3771     // "last value of IV1" and "penultimate value of IV2". So, verify that we
3772     // don't already have an incoming value for the middle block.
3773     if (PHI->getBasicBlockIndex(MiddleBlock) == -1)
3774       PHI->addIncoming(I.second, MiddleBlock);
3775   }
3776 }
3777 
3778 namespace {
3779 
3780 struct CSEDenseMapInfo {
canHandle__anone42b58380e11::CSEDenseMapInfo3781   static bool canHandle(const Instruction *I) {
3782     return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
3783            isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
3784   }
3785 
getEmptyKey__anone42b58380e11::CSEDenseMapInfo3786   static inline Instruction *getEmptyKey() {
3787     return DenseMapInfo<Instruction *>::getEmptyKey();
3788   }
3789 
getTombstoneKey__anone42b58380e11::CSEDenseMapInfo3790   static inline Instruction *getTombstoneKey() {
3791     return DenseMapInfo<Instruction *>::getTombstoneKey();
3792   }
3793 
getHashValue__anone42b58380e11::CSEDenseMapInfo3794   static unsigned getHashValue(const Instruction *I) {
3795     assert(canHandle(I) && "Unknown instruction!");
3796     return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
3797                                                            I->value_op_end()));
3798   }
3799 
isEqual__anone42b58380e11::CSEDenseMapInfo3800   static bool isEqual(const Instruction *LHS, const Instruction *RHS) {
3801     if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
3802         LHS == getTombstoneKey() || RHS == getTombstoneKey())
3803       return LHS == RHS;
3804     return LHS->isIdenticalTo(RHS);
3805   }
3806 };
3807 
3808 } // end anonymous namespace
3809 
3810 ///Perform cse of induction variable instructions.
cse(BasicBlock * BB)3811 static void cse(BasicBlock *BB) {
3812   // Perform simple cse.
3813   SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
3814   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
3815     Instruction *In = &*I++;
3816 
3817     if (!CSEDenseMapInfo::canHandle(In))
3818       continue;
3819 
3820     // Check if we can replace this instruction with any of the
3821     // visited instructions.
3822     if (Instruction *V = CSEMap.lookup(In)) {
3823       In->replaceAllUsesWith(V);
3824       In->eraseFromParent();
3825       continue;
3826     }
3827 
3828     CSEMap[In] = In;
3829   }
3830 }
3831 
3832 InstructionCost
getVectorCallCost(CallInst * CI,ElementCount VF,bool & NeedToScalarize) const3833 LoopVectorizationCostModel::getVectorCallCost(CallInst *CI, ElementCount VF,
3834                                               bool &NeedToScalarize) const {
3835   Function *F = CI->getCalledFunction();
3836   Type *ScalarRetTy = CI->getType();
3837   SmallVector<Type *, 4> Tys, ScalarTys;
3838   for (auto &ArgOp : CI->arg_operands())
3839     ScalarTys.push_back(ArgOp->getType());
3840 
3841   // Estimate cost of scalarized vector call. The source operands are assumed
3842   // to be vectors, so we need to extract individual elements from there,
3843   // execute VF scalar calls, and then gather the result into the vector return
3844   // value.
3845   InstructionCost ScalarCallCost =
3846       TTI.getCallInstrCost(F, ScalarRetTy, ScalarTys, TTI::TCK_RecipThroughput);
3847   if (VF.isScalar())
3848     return ScalarCallCost;
3849 
3850   // Compute corresponding vector type for return value and arguments.
3851   Type *RetTy = ToVectorTy(ScalarRetTy, VF);
3852   for (Type *ScalarTy : ScalarTys)
3853     Tys.push_back(ToVectorTy(ScalarTy, VF));
3854 
3855   // Compute costs of unpacking argument values for the scalar calls and
3856   // packing the return values to a vector.
3857   InstructionCost ScalarizationCost = getScalarizationOverhead(CI, VF);
3858 
3859   InstructionCost Cost =
3860       ScalarCallCost * VF.getKnownMinValue() + ScalarizationCost;
3861 
3862   // If we can't emit a vector call for this function, then the currently found
3863   // cost is the cost we need to return.
3864   NeedToScalarize = true;
3865   VFShape Shape = VFShape::get(*CI, VF, false /*HasGlobalPred*/);
3866   Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
3867 
3868   if (!TLI || CI->isNoBuiltin() || !VecFunc)
3869     return Cost;
3870 
3871   // If the corresponding vector cost is cheaper, return its cost.
3872   InstructionCost VectorCallCost =
3873       TTI.getCallInstrCost(nullptr, RetTy, Tys, TTI::TCK_RecipThroughput);
3874   if (VectorCallCost < Cost) {
3875     NeedToScalarize = false;
3876     Cost = VectorCallCost;
3877   }
3878   return Cost;
3879 }
3880 
MaybeVectorizeType(Type * Elt,ElementCount VF)3881 static Type *MaybeVectorizeType(Type *Elt, ElementCount VF) {
3882   if (VF.isScalar() || (!Elt->isIntOrPtrTy() && !Elt->isFloatingPointTy()))
3883     return Elt;
3884   return VectorType::get(Elt, VF);
3885 }
3886 
3887 InstructionCost
getVectorIntrinsicCost(CallInst * CI,ElementCount VF) const3888 LoopVectorizationCostModel::getVectorIntrinsicCost(CallInst *CI,
3889                                                    ElementCount VF) const {
3890   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
3891   assert(ID && "Expected intrinsic call!");
3892   Type *RetTy = MaybeVectorizeType(CI->getType(), VF);
3893   FastMathFlags FMF;
3894   if (auto *FPMO = dyn_cast<FPMathOperator>(CI))
3895     FMF = FPMO->getFastMathFlags();
3896 
3897   SmallVector<const Value *> Arguments(CI->arg_begin(), CI->arg_end());
3898   FunctionType *FTy = CI->getCalledFunction()->getFunctionType();
3899   SmallVector<Type *> ParamTys;
3900   std::transform(FTy->param_begin(), FTy->param_end(),
3901                  std::back_inserter(ParamTys),
3902                  [&](Type *Ty) { return MaybeVectorizeType(Ty, VF); });
3903 
3904   IntrinsicCostAttributes CostAttrs(ID, RetTy, Arguments, ParamTys, FMF,
3905                                     dyn_cast<IntrinsicInst>(CI));
3906   return TTI.getIntrinsicInstrCost(CostAttrs,
3907                                    TargetTransformInfo::TCK_RecipThroughput);
3908 }
3909 
smallestIntegerVectorType(Type * T1,Type * T2)3910 static Type *smallestIntegerVectorType(Type *T1, Type *T2) {
3911   auto *I1 = cast<IntegerType>(cast<VectorType>(T1)->getElementType());
3912   auto *I2 = cast<IntegerType>(cast<VectorType>(T2)->getElementType());
3913   return I1->getBitWidth() < I2->getBitWidth() ? T1 : T2;
3914 }
3915 
largestIntegerVectorType(Type * T1,Type * T2)3916 static Type *largestIntegerVectorType(Type *T1, Type *T2) {
3917   auto *I1 = cast<IntegerType>(cast<VectorType>(T1)->getElementType());
3918   auto *I2 = cast<IntegerType>(cast<VectorType>(T2)->getElementType());
3919   return I1->getBitWidth() > I2->getBitWidth() ? T1 : T2;
3920 }
3921 
truncateToMinimalBitwidths(VPTransformState & State)3922 void InnerLoopVectorizer::truncateToMinimalBitwidths(VPTransformState &State) {
3923   // For every instruction `I` in MinBWs, truncate the operands, create a
3924   // truncated version of `I` and reextend its result. InstCombine runs
3925   // later and will remove any ext/trunc pairs.
3926   SmallPtrSet<Value *, 4> Erased;
3927   for (const auto &KV : Cost->getMinimalBitwidths()) {
3928     // If the value wasn't vectorized, we must maintain the original scalar
3929     // type. The absence of the value from State indicates that it
3930     // wasn't vectorized.
3931     VPValue *Def = State.Plan->getVPValue(KV.first);
3932     if (!State.hasAnyVectorValue(Def))
3933       continue;
3934     for (unsigned Part = 0; Part < UF; ++Part) {
3935       Value *I = State.get(Def, Part);
3936       if (Erased.count(I) || I->use_empty() || !isa<Instruction>(I))
3937         continue;
3938       Type *OriginalTy = I->getType();
3939       Type *ScalarTruncatedTy =
3940           IntegerType::get(OriginalTy->getContext(), KV.second);
3941       auto *TruncatedTy = FixedVectorType::get(
3942           ScalarTruncatedTy,
3943           cast<FixedVectorType>(OriginalTy)->getNumElements());
3944       if (TruncatedTy == OriginalTy)
3945         continue;
3946 
3947       IRBuilder<> B(cast<Instruction>(I));
3948       auto ShrinkOperand = [&](Value *V) -> Value * {
3949         if (auto *ZI = dyn_cast<ZExtInst>(V))
3950           if (ZI->getSrcTy() == TruncatedTy)
3951             return ZI->getOperand(0);
3952         return B.CreateZExtOrTrunc(V, TruncatedTy);
3953       };
3954 
3955       // The actual instruction modification depends on the instruction type,
3956       // unfortunately.
3957       Value *NewI = nullptr;
3958       if (auto *BO = dyn_cast<BinaryOperator>(I)) {
3959         NewI = B.CreateBinOp(BO->getOpcode(), ShrinkOperand(BO->getOperand(0)),
3960                              ShrinkOperand(BO->getOperand(1)));
3961 
3962         // Any wrapping introduced by shrinking this operation shouldn't be
3963         // considered undefined behavior. So, we can't unconditionally copy
3964         // arithmetic wrapping flags to NewI.
3965         cast<BinaryOperator>(NewI)->copyIRFlags(I, /*IncludeWrapFlags=*/false);
3966       } else if (auto *CI = dyn_cast<ICmpInst>(I)) {
3967         NewI =
3968             B.CreateICmp(CI->getPredicate(), ShrinkOperand(CI->getOperand(0)),
3969                          ShrinkOperand(CI->getOperand(1)));
3970       } else if (auto *SI = dyn_cast<SelectInst>(I)) {
3971         NewI = B.CreateSelect(SI->getCondition(),
3972                               ShrinkOperand(SI->getTrueValue()),
3973                               ShrinkOperand(SI->getFalseValue()));
3974       } else if (auto *CI = dyn_cast<CastInst>(I)) {
3975         switch (CI->getOpcode()) {
3976         default:
3977           llvm_unreachable("Unhandled cast!");
3978         case Instruction::Trunc:
3979           NewI = ShrinkOperand(CI->getOperand(0));
3980           break;
3981         case Instruction::SExt:
3982           NewI = B.CreateSExtOrTrunc(
3983               CI->getOperand(0),
3984               smallestIntegerVectorType(OriginalTy, TruncatedTy));
3985           break;
3986         case Instruction::ZExt:
3987           NewI = B.CreateZExtOrTrunc(
3988               CI->getOperand(0),
3989               smallestIntegerVectorType(OriginalTy, TruncatedTy));
3990           break;
3991         }
3992       } else if (auto *SI = dyn_cast<ShuffleVectorInst>(I)) {
3993         auto Elements0 = cast<FixedVectorType>(SI->getOperand(0)->getType())
3994                              ->getNumElements();
3995         auto *O0 = B.CreateZExtOrTrunc(
3996             SI->getOperand(0),
3997             FixedVectorType::get(ScalarTruncatedTy, Elements0));
3998         auto Elements1 = cast<FixedVectorType>(SI->getOperand(1)->getType())
3999                              ->getNumElements();
4000         auto *O1 = B.CreateZExtOrTrunc(
4001             SI->getOperand(1),
4002             FixedVectorType::get(ScalarTruncatedTy, Elements1));
4003 
4004         NewI = B.CreateShuffleVector(O0, O1, SI->getShuffleMask());
4005       } else if (isa<LoadInst>(I) || isa<PHINode>(I)) {
4006         // Don't do anything with the operands, just extend the result.
4007         continue;
4008       } else if (auto *IE = dyn_cast<InsertElementInst>(I)) {
4009         auto Elements = cast<FixedVectorType>(IE->getOperand(0)->getType())
4010                             ->getNumElements();
4011         auto *O0 = B.CreateZExtOrTrunc(
4012             IE->getOperand(0),
4013             FixedVectorType::get(ScalarTruncatedTy, Elements));
4014         auto *O1 = B.CreateZExtOrTrunc(IE->getOperand(1), ScalarTruncatedTy);
4015         NewI = B.CreateInsertElement(O0, O1, IE->getOperand(2));
4016       } else if (auto *EE = dyn_cast<ExtractElementInst>(I)) {
4017         auto Elements = cast<FixedVectorType>(EE->getOperand(0)->getType())
4018                             ->getNumElements();
4019         auto *O0 = B.CreateZExtOrTrunc(
4020             EE->getOperand(0),
4021             FixedVectorType::get(ScalarTruncatedTy, Elements));
4022         NewI = B.CreateExtractElement(O0, EE->getOperand(2));
4023       } else {
4024         // If we don't know what to do, be conservative and don't do anything.
4025         continue;
4026       }
4027 
4028       // Lastly, extend the result.
4029       NewI->takeName(cast<Instruction>(I));
4030       Value *Res = B.CreateZExtOrTrunc(NewI, OriginalTy);
4031       I->replaceAllUsesWith(Res);
4032       cast<Instruction>(I)->eraseFromParent();
4033       Erased.insert(I);
4034       State.reset(Def, Res, Part);
4035     }
4036   }
4037 
4038   // We'll have created a bunch of ZExts that are now parentless. Clean up.
4039   for (const auto &KV : Cost->getMinimalBitwidths()) {
4040     // If the value wasn't vectorized, we must maintain the original scalar
4041     // type. The absence of the value from State indicates that it
4042     // wasn't vectorized.
4043     VPValue *Def = State.Plan->getVPValue(KV.first);
4044     if (!State.hasAnyVectorValue(Def))
4045       continue;
4046     for (unsigned Part = 0; Part < UF; ++Part) {
4047       Value *I = State.get(Def, Part);
4048       ZExtInst *Inst = dyn_cast<ZExtInst>(I);
4049       if (Inst && Inst->use_empty()) {
4050         Value *NewI = Inst->getOperand(0);
4051         Inst->eraseFromParent();
4052         State.reset(Def, NewI, Part);
4053       }
4054     }
4055   }
4056 }
4057 
fixVectorizedLoop(VPTransformState & State)4058 void InnerLoopVectorizer::fixVectorizedLoop(VPTransformState &State) {
4059   // Insert truncates and extends for any truncated instructions as hints to
4060   // InstCombine.
4061   if (VF.isVector())
4062     truncateToMinimalBitwidths(State);
4063 
4064   // Fix widened non-induction PHIs by setting up the PHI operands.
4065   if (OrigPHIsToFix.size()) {
4066     assert(EnableVPlanNativePath &&
4067            "Unexpected non-induction PHIs for fixup in non VPlan-native path");
4068     fixNonInductionPHIs(State);
4069   }
4070 
4071   // At this point every instruction in the original loop is widened to a
4072   // vector form. Now we need to fix the recurrences in the loop. These PHI
4073   // nodes are currently empty because we did not want to introduce cycles.
4074   // This is the second stage of vectorizing recurrences.
4075   fixCrossIterationPHIs(State);
4076 
4077   // Forget the original basic block.
4078   PSE.getSE()->forgetLoop(OrigLoop);
4079 
4080   // Fix-up external users of the induction variables.
4081   for (auto &Entry : Legal->getInductionVars())
4082     fixupIVUsers(Entry.first, Entry.second,
4083                  getOrCreateVectorTripCount(LI->getLoopFor(LoopVectorBody)),
4084                  IVEndValues[Entry.first], LoopMiddleBlock);
4085 
4086   fixLCSSAPHIs(State);
4087   for (Instruction *PI : PredicatedInstructions)
4088     sinkScalarOperands(&*PI);
4089 
4090   // Remove redundant induction instructions.
4091   cse(LoopVectorBody);
4092 
4093   // Set/update profile weights for the vector and remainder loops as original
4094   // loop iterations are now distributed among them. Note that original loop
4095   // represented by LoopScalarBody becomes remainder loop after vectorization.
4096   //
4097   // For cases like foldTailByMasking() and requiresScalarEpiloque() we may
4098   // end up getting slightly roughened result but that should be OK since
4099   // profile is not inherently precise anyway. Note also possible bypass of
4100   // vector code caused by legality checks is ignored, assigning all the weight
4101   // to the vector loop, optimistically.
4102   //
4103   // For scalable vectorization we can't know at compile time how many iterations
4104   // of the loop are handled in one vector iteration, so instead assume a pessimistic
4105   // vscale of '1'.
4106   setProfileInfoAfterUnrolling(
4107       LI->getLoopFor(LoopScalarBody), LI->getLoopFor(LoopVectorBody),
4108       LI->getLoopFor(LoopScalarBody), VF.getKnownMinValue() * UF);
4109 }
4110 
fixCrossIterationPHIs(VPTransformState & State)4111 void InnerLoopVectorizer::fixCrossIterationPHIs(VPTransformState &State) {
4112   // In order to support recurrences we need to be able to vectorize Phi nodes.
4113   // Phi nodes have cycles, so we need to vectorize them in two stages. This is
4114   // stage #2: We now need to fix the recurrences by adding incoming edges to
4115   // the currently empty PHI nodes. At this point every instruction in the
4116   // original loop is widened to a vector form so we can use them to construct
4117   // the incoming edges.
4118   VPBasicBlock *Header = State.Plan->getEntry()->getEntryBasicBlock();
4119   for (VPRecipeBase &R : Header->phis()) {
4120     auto *PhiR = dyn_cast<VPWidenPHIRecipe>(&R);
4121     if (!PhiR)
4122       continue;
4123     auto *OrigPhi = cast<PHINode>(PhiR->getUnderlyingValue());
4124     if (PhiR->getRecurrenceDescriptor()) {
4125       fixReduction(PhiR, State);
4126     } else if (Legal->isFirstOrderRecurrence(OrigPhi))
4127       fixFirstOrderRecurrence(OrigPhi, State);
4128   }
4129 }
4130 
fixFirstOrderRecurrence(PHINode * Phi,VPTransformState & State)4131 void InnerLoopVectorizer::fixFirstOrderRecurrence(PHINode *Phi,
4132                                                   VPTransformState &State) {
4133   // This is the second phase of vectorizing first-order recurrences. An
4134   // overview of the transformation is described below. Suppose we have the
4135   // following loop.
4136   //
4137   //   for (int i = 0; i < n; ++i)
4138   //     b[i] = a[i] - a[i - 1];
4139   //
4140   // There is a first-order recurrence on "a". For this loop, the shorthand
4141   // scalar IR looks like:
4142   //
4143   //   scalar.ph:
4144   //     s_init = a[-1]
4145   //     br scalar.body
4146   //
4147   //   scalar.body:
4148   //     i = phi [0, scalar.ph], [i+1, scalar.body]
4149   //     s1 = phi [s_init, scalar.ph], [s2, scalar.body]
4150   //     s2 = a[i]
4151   //     b[i] = s2 - s1
4152   //     br cond, scalar.body, ...
4153   //
4154   // In this example, s1 is a recurrence because it's value depends on the
4155   // previous iteration. In the first phase of vectorization, we created a
4156   // temporary value for s1. We now complete the vectorization and produce the
4157   // shorthand vector IR shown below (for VF = 4, UF = 1).
4158   //
4159   //   vector.ph:
4160   //     v_init = vector(..., ..., ..., a[-1])
4161   //     br vector.body
4162   //
4163   //   vector.body
4164   //     i = phi [0, vector.ph], [i+4, vector.body]
4165   //     v1 = phi [v_init, vector.ph], [v2, vector.body]
4166   //     v2 = a[i, i+1, i+2, i+3];
4167   //     v3 = vector(v1(3), v2(0, 1, 2))
4168   //     b[i, i+1, i+2, i+3] = v2 - v3
4169   //     br cond, vector.body, middle.block
4170   //
4171   //   middle.block:
4172   //     x = v2(3)
4173   //     br scalar.ph
4174   //
4175   //   scalar.ph:
4176   //     s_init = phi [x, middle.block], [a[-1], otherwise]
4177   //     br scalar.body
4178   //
4179   // After execution completes the vector loop, we extract the next value of
4180   // the recurrence (x) to use as the initial value in the scalar loop.
4181 
4182   // Get the original loop preheader and single loop latch.
4183   auto *Preheader = OrigLoop->getLoopPreheader();
4184   auto *Latch = OrigLoop->getLoopLatch();
4185 
4186   // Get the initial and previous values of the scalar recurrence.
4187   auto *ScalarInit = Phi->getIncomingValueForBlock(Preheader);
4188   auto *Previous = Phi->getIncomingValueForBlock(Latch);
4189 
4190   auto *IdxTy = Builder.getInt32Ty();
4191   auto *One = ConstantInt::get(IdxTy, 1);
4192 
4193   // Create a vector from the initial value.
4194   auto *VectorInit = ScalarInit;
4195   if (VF.isVector()) {
4196     Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
4197     auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, VF);
4198     auto *LastIdx = Builder.CreateSub(RuntimeVF, One);
4199     VectorInit = Builder.CreateInsertElement(
4200         PoisonValue::get(VectorType::get(VectorInit->getType(), VF)),
4201         VectorInit, LastIdx, "vector.recur.init");
4202   }
4203 
4204   VPValue *PhiDef = State.Plan->getVPValue(Phi);
4205   VPValue *PreviousDef = State.Plan->getVPValue(Previous);
4206   // We constructed a temporary phi node in the first phase of vectorization.
4207   // This phi node will eventually be deleted.
4208   Builder.SetInsertPoint(cast<Instruction>(State.get(PhiDef, 0)));
4209 
4210   // Create a phi node for the new recurrence. The current value will either be
4211   // the initial value inserted into a vector or loop-varying vector value.
4212   auto *VecPhi = Builder.CreatePHI(VectorInit->getType(), 2, "vector.recur");
4213   VecPhi->addIncoming(VectorInit, LoopVectorPreHeader);
4214 
4215   // Get the vectorized previous value of the last part UF - 1. It appears last
4216   // among all unrolled iterations, due to the order of their construction.
4217   Value *PreviousLastPart = State.get(PreviousDef, UF - 1);
4218 
4219   // Find and set the insertion point after the previous value if it is an
4220   // instruction.
4221   BasicBlock::iterator InsertPt;
4222   // Note that the previous value may have been constant-folded so it is not
4223   // guaranteed to be an instruction in the vector loop.
4224   // FIXME: Loop invariant values do not form recurrences. We should deal with
4225   //        them earlier.
4226   if (LI->getLoopFor(LoopVectorBody)->isLoopInvariant(PreviousLastPart))
4227     InsertPt = LoopVectorBody->getFirstInsertionPt();
4228   else {
4229     Instruction *PreviousInst = cast<Instruction>(PreviousLastPart);
4230     if (isa<PHINode>(PreviousLastPart))
4231       // If the previous value is a phi node, we should insert after all the phi
4232       // nodes in the block containing the PHI to avoid breaking basic block
4233       // verification. Note that the basic block may be different to
4234       // LoopVectorBody, in case we predicate the loop.
4235       InsertPt = PreviousInst->getParent()->getFirstInsertionPt();
4236     else
4237       InsertPt = ++PreviousInst->getIterator();
4238   }
4239   Builder.SetInsertPoint(&*InsertPt);
4240 
4241   // The vector from which to take the initial value for the current iteration
4242   // (actual or unrolled). Initially, this is the vector phi node.
4243   Value *Incoming = VecPhi;
4244 
4245   // Shuffle the current and previous vector and update the vector parts.
4246   for (unsigned Part = 0; Part < UF; ++Part) {
4247     Value *PreviousPart = State.get(PreviousDef, Part);
4248     Value *PhiPart = State.get(PhiDef, Part);
4249     auto *Shuffle = VF.isVector()
4250                         ? Builder.CreateVectorSplice(Incoming, PreviousPart, -1)
4251                         : Incoming;
4252     PhiPart->replaceAllUsesWith(Shuffle);
4253     cast<Instruction>(PhiPart)->eraseFromParent();
4254     State.reset(PhiDef, Shuffle, Part);
4255     Incoming = PreviousPart;
4256   }
4257 
4258   // Fix the latch value of the new recurrence in the vector loop.
4259   VecPhi->addIncoming(Incoming, LI->getLoopFor(LoopVectorBody)->getLoopLatch());
4260 
4261   // Extract the last vector element in the middle block. This will be the
4262   // initial value for the recurrence when jumping to the scalar loop.
4263   auto *ExtractForScalar = Incoming;
4264   if (VF.isVector()) {
4265     Builder.SetInsertPoint(LoopMiddleBlock->getTerminator());
4266     auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, VF);
4267     auto *LastIdx = Builder.CreateSub(RuntimeVF, One);
4268     ExtractForScalar = Builder.CreateExtractElement(ExtractForScalar, LastIdx,
4269                                                     "vector.recur.extract");
4270   }
4271   // Extract the second last element in the middle block if the
4272   // Phi is used outside the loop. We need to extract the phi itself
4273   // and not the last element (the phi update in the current iteration). This
4274   // will be the value when jumping to the exit block from the LoopMiddleBlock,
4275   // when the scalar loop is not run at all.
4276   Value *ExtractForPhiUsedOutsideLoop = nullptr;
4277   if (VF.isVector()) {
4278     auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, VF);
4279     auto *Idx = Builder.CreateSub(RuntimeVF, ConstantInt::get(IdxTy, 2));
4280     ExtractForPhiUsedOutsideLoop = Builder.CreateExtractElement(
4281         Incoming, Idx, "vector.recur.extract.for.phi");
4282   } else if (UF > 1)
4283     // When loop is unrolled without vectorizing, initialize
4284     // ExtractForPhiUsedOutsideLoop with the value just prior to unrolled value
4285     // of `Incoming`. This is analogous to the vectorized case above: extracting
4286     // the second last element when VF > 1.
4287     ExtractForPhiUsedOutsideLoop = State.get(PreviousDef, UF - 2);
4288 
4289   // Fix the initial value of the original recurrence in the scalar loop.
4290   Builder.SetInsertPoint(&*LoopScalarPreHeader->begin());
4291   auto *Start = Builder.CreatePHI(Phi->getType(), 2, "scalar.recur.init");
4292   for (auto *BB : predecessors(LoopScalarPreHeader)) {
4293     auto *Incoming = BB == LoopMiddleBlock ? ExtractForScalar : ScalarInit;
4294     Start->addIncoming(Incoming, BB);
4295   }
4296 
4297   Phi->setIncomingValueForBlock(LoopScalarPreHeader, Start);
4298   Phi->setName("scalar.recur");
4299 
4300   // Finally, fix users of the recurrence outside the loop. The users will need
4301   // either the last value of the scalar recurrence or the last value of the
4302   // vector recurrence we extracted in the middle block. Since the loop is in
4303   // LCSSA form, we just need to find all the phi nodes for the original scalar
4304   // recurrence in the exit block, and then add an edge for the middle block.
4305   // Note that LCSSA does not imply single entry when the original scalar loop
4306   // had multiple exiting edges (as we always run the last iteration in the
4307   // scalar epilogue); in that case, the exiting path through middle will be
4308   // dynamically dead and the value picked for the phi doesn't matter.
4309   for (PHINode &LCSSAPhi : LoopExitBlock->phis())
4310     if (any_of(LCSSAPhi.incoming_values(),
4311                [Phi](Value *V) { return V == Phi; }))
4312       LCSSAPhi.addIncoming(ExtractForPhiUsedOutsideLoop, LoopMiddleBlock);
4313 }
4314 
useOrderedReductions(RecurrenceDescriptor & RdxDesc)4315 static bool useOrderedReductions(RecurrenceDescriptor &RdxDesc) {
4316   return EnableStrictReductions && RdxDesc.isOrdered();
4317 }
4318 
fixReduction(VPWidenPHIRecipe * PhiR,VPTransformState & State)4319 void InnerLoopVectorizer::fixReduction(VPWidenPHIRecipe *PhiR,
4320                                        VPTransformState &State) {
4321   PHINode *OrigPhi = cast<PHINode>(PhiR->getUnderlyingValue());
4322   // Get it's reduction variable descriptor.
4323   assert(Legal->isReductionVariable(OrigPhi) &&
4324          "Unable to find the reduction variable");
4325   RecurrenceDescriptor RdxDesc = *PhiR->getRecurrenceDescriptor();
4326 
4327   RecurKind RK = RdxDesc.getRecurrenceKind();
4328   TrackingVH<Value> ReductionStartValue = RdxDesc.getRecurrenceStartValue();
4329   Instruction *LoopExitInst = RdxDesc.getLoopExitInstr();
4330   setDebugLocFromInst(Builder, ReductionStartValue);
4331   bool IsInLoopReductionPhi = Cost->isInLoopReduction(OrigPhi);
4332 
4333   VPValue *LoopExitInstDef = State.Plan->getVPValue(LoopExitInst);
4334   // This is the vector-clone of the value that leaves the loop.
4335   Type *VecTy = State.get(LoopExitInstDef, 0)->getType();
4336 
4337   // Wrap flags are in general invalid after vectorization, clear them.
4338   clearReductionWrapFlags(RdxDesc, State);
4339 
4340   // Fix the vector-loop phi.
4341 
4342   // Reductions do not have to start at zero. They can start with
4343   // any loop invariant values.
4344   BasicBlock *VectorLoopLatch = LI->getLoopFor(LoopVectorBody)->getLoopLatch();
4345 
4346   bool IsOrdered = State.VF.isVector() && IsInLoopReductionPhi &&
4347                    useOrderedReductions(RdxDesc);
4348 
4349   for (unsigned Part = 0; Part < UF; ++Part) {
4350     if (IsOrdered && Part > 0)
4351       break;
4352     Value *VecRdxPhi = State.get(PhiR->getVPSingleValue(), Part);
4353     Value *Val = State.get(PhiR->getBackedgeValue(), Part);
4354     if (IsOrdered)
4355       Val = State.get(PhiR->getBackedgeValue(), UF - 1);
4356 
4357     cast<PHINode>(VecRdxPhi)->addIncoming(Val, VectorLoopLatch);
4358   }
4359 
4360   // Before each round, move the insertion point right between
4361   // the PHIs and the values we are going to write.
4362   // This allows us to write both PHINodes and the extractelement
4363   // instructions.
4364   Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
4365 
4366   setDebugLocFromInst(Builder, LoopExitInst);
4367 
4368   Type *PhiTy = OrigPhi->getType();
4369   // If tail is folded by masking, the vector value to leave the loop should be
4370   // a Select choosing between the vectorized LoopExitInst and vectorized Phi,
4371   // instead of the former. For an inloop reduction the reduction will already
4372   // be predicated, and does not need to be handled here.
4373   if (Cost->foldTailByMasking() && !IsInLoopReductionPhi) {
4374     for (unsigned Part = 0; Part < UF; ++Part) {
4375       Value *VecLoopExitInst = State.get(LoopExitInstDef, Part);
4376       Value *Sel = nullptr;
4377       for (User *U : VecLoopExitInst->users()) {
4378         if (isa<SelectInst>(U)) {
4379           assert(!Sel && "Reduction exit feeding two selects");
4380           Sel = U;
4381         } else
4382           assert(isa<PHINode>(U) && "Reduction exit must feed Phi's or select");
4383       }
4384       assert(Sel && "Reduction exit feeds no select");
4385       State.reset(LoopExitInstDef, Sel, Part);
4386 
4387       // If the target can create a predicated operator for the reduction at no
4388       // extra cost in the loop (for example a predicated vadd), it can be
4389       // cheaper for the select to remain in the loop than be sunk out of it,
4390       // and so use the select value for the phi instead of the old
4391       // LoopExitValue.
4392       if (PreferPredicatedReductionSelect ||
4393           TTI->preferPredicatedReductionSelect(
4394               RdxDesc.getOpcode(), PhiTy,
4395               TargetTransformInfo::ReductionFlags())) {
4396         auto *VecRdxPhi =
4397             cast<PHINode>(State.get(PhiR->getVPSingleValue(), Part));
4398         VecRdxPhi->setIncomingValueForBlock(
4399             LI->getLoopFor(LoopVectorBody)->getLoopLatch(), Sel);
4400       }
4401     }
4402   }
4403 
4404   // If the vector reduction can be performed in a smaller type, we truncate
4405   // then extend the loop exit value to enable InstCombine to evaluate the
4406   // entire expression in the smaller type.
4407   if (VF.isVector() && PhiTy != RdxDesc.getRecurrenceType()) {
4408     assert(!IsInLoopReductionPhi && "Unexpected truncated inloop reduction!");
4409     Type *RdxVecTy = VectorType::get(RdxDesc.getRecurrenceType(), VF);
4410     Builder.SetInsertPoint(
4411         LI->getLoopFor(LoopVectorBody)->getLoopLatch()->getTerminator());
4412     VectorParts RdxParts(UF);
4413     for (unsigned Part = 0; Part < UF; ++Part) {
4414       RdxParts[Part] = State.get(LoopExitInstDef, Part);
4415       Value *Trunc = Builder.CreateTrunc(RdxParts[Part], RdxVecTy);
4416       Value *Extnd = RdxDesc.isSigned() ? Builder.CreateSExt(Trunc, VecTy)
4417                                         : Builder.CreateZExt(Trunc, VecTy);
4418       for (Value::user_iterator UI = RdxParts[Part]->user_begin();
4419            UI != RdxParts[Part]->user_end();)
4420         if (*UI != Trunc) {
4421           (*UI++)->replaceUsesOfWith(RdxParts[Part], Extnd);
4422           RdxParts[Part] = Extnd;
4423         } else {
4424           ++UI;
4425         }
4426     }
4427     Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
4428     for (unsigned Part = 0; Part < UF; ++Part) {
4429       RdxParts[Part] = Builder.CreateTrunc(RdxParts[Part], RdxVecTy);
4430       State.reset(LoopExitInstDef, RdxParts[Part], Part);
4431     }
4432   }
4433 
4434   // Reduce all of the unrolled parts into a single vector.
4435   Value *ReducedPartRdx = State.get(LoopExitInstDef, 0);
4436   unsigned Op = RecurrenceDescriptor::getOpcode(RK);
4437 
4438   // The middle block terminator has already been assigned a DebugLoc here (the
4439   // OrigLoop's single latch terminator). We want the whole middle block to
4440   // appear to execute on this line because: (a) it is all compiler generated,
4441   // (b) these instructions are always executed after evaluating the latch
4442   // conditional branch, and (c) other passes may add new predecessors which
4443   // terminate on this line. This is the easiest way to ensure we don't
4444   // accidentally cause an extra step back into the loop while debugging.
4445   setDebugLocFromInst(Builder, LoopMiddleBlock->getTerminator());
4446   if (IsOrdered)
4447     ReducedPartRdx = State.get(LoopExitInstDef, UF - 1);
4448   else {
4449     // Floating-point operations should have some FMF to enable the reduction.
4450     IRBuilderBase::FastMathFlagGuard FMFG(Builder);
4451     Builder.setFastMathFlags(RdxDesc.getFastMathFlags());
4452     for (unsigned Part = 1; Part < UF; ++Part) {
4453       Value *RdxPart = State.get(LoopExitInstDef, Part);
4454       if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
4455         ReducedPartRdx = Builder.CreateBinOp(
4456             (Instruction::BinaryOps)Op, RdxPart, ReducedPartRdx, "bin.rdx");
4457       } else {
4458         ReducedPartRdx = createMinMaxOp(Builder, RK, ReducedPartRdx, RdxPart);
4459       }
4460     }
4461   }
4462 
4463   // Create the reduction after the loop. Note that inloop reductions create the
4464   // target reduction in the loop using a Reduction recipe.
4465   if (VF.isVector() && !IsInLoopReductionPhi) {
4466     ReducedPartRdx =
4467         createTargetReduction(Builder, TTI, RdxDesc, ReducedPartRdx);
4468     // If the reduction can be performed in a smaller type, we need to extend
4469     // the reduction to the wider type before we branch to the original loop.
4470     if (PhiTy != RdxDesc.getRecurrenceType())
4471       ReducedPartRdx = RdxDesc.isSigned()
4472                            ? Builder.CreateSExt(ReducedPartRdx, PhiTy)
4473                            : Builder.CreateZExt(ReducedPartRdx, PhiTy);
4474   }
4475 
4476   // Create a phi node that merges control-flow from the backedge-taken check
4477   // block and the middle block.
4478   PHINode *BCBlockPhi = PHINode::Create(PhiTy, 2, "bc.merge.rdx",
4479                                         LoopScalarPreHeader->getTerminator());
4480   for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
4481     BCBlockPhi->addIncoming(ReductionStartValue, LoopBypassBlocks[I]);
4482   BCBlockPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
4483 
4484   // Now, we need to fix the users of the reduction variable
4485   // inside and outside of the scalar remainder loop.
4486 
4487   // We know that the loop is in LCSSA form. We need to update the PHI nodes
4488   // in the exit blocks.  See comment on analogous loop in
4489   // fixFirstOrderRecurrence for a more complete explaination of the logic.
4490   for (PHINode &LCSSAPhi : LoopExitBlock->phis())
4491     if (any_of(LCSSAPhi.incoming_values(),
4492                [LoopExitInst](Value *V) { return V == LoopExitInst; }))
4493       LCSSAPhi.addIncoming(ReducedPartRdx, LoopMiddleBlock);
4494 
4495   // Fix the scalar loop reduction variable with the incoming reduction sum
4496   // from the vector body and from the backedge value.
4497   int IncomingEdgeBlockIdx =
4498       OrigPhi->getBasicBlockIndex(OrigLoop->getLoopLatch());
4499   assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
4500   // Pick the other block.
4501   int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
4502   OrigPhi->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi);
4503   OrigPhi->setIncomingValue(IncomingEdgeBlockIdx, LoopExitInst);
4504 }
4505 
clearReductionWrapFlags(RecurrenceDescriptor & RdxDesc,VPTransformState & State)4506 void InnerLoopVectorizer::clearReductionWrapFlags(RecurrenceDescriptor &RdxDesc,
4507                                                   VPTransformState &State) {
4508   RecurKind RK = RdxDesc.getRecurrenceKind();
4509   if (RK != RecurKind::Add && RK != RecurKind::Mul)
4510     return;
4511 
4512   Instruction *LoopExitInstr = RdxDesc.getLoopExitInstr();
4513   assert(LoopExitInstr && "null loop exit instruction");
4514   SmallVector<Instruction *, 8> Worklist;
4515   SmallPtrSet<Instruction *, 8> Visited;
4516   Worklist.push_back(LoopExitInstr);
4517   Visited.insert(LoopExitInstr);
4518 
4519   while (!Worklist.empty()) {
4520     Instruction *Cur = Worklist.pop_back_val();
4521     if (isa<OverflowingBinaryOperator>(Cur))
4522       for (unsigned Part = 0; Part < UF; ++Part) {
4523         Value *V = State.get(State.Plan->getVPValue(Cur), Part);
4524         cast<Instruction>(V)->dropPoisonGeneratingFlags();
4525       }
4526 
4527     for (User *U : Cur->users()) {
4528       Instruction *UI = cast<Instruction>(U);
4529       if ((Cur != LoopExitInstr || OrigLoop->contains(UI->getParent())) &&
4530           Visited.insert(UI).second)
4531         Worklist.push_back(UI);
4532     }
4533   }
4534 }
4535 
fixLCSSAPHIs(VPTransformState & State)4536 void InnerLoopVectorizer::fixLCSSAPHIs(VPTransformState &State) {
4537   for (PHINode &LCSSAPhi : LoopExitBlock->phis()) {
4538     if (LCSSAPhi.getBasicBlockIndex(LoopMiddleBlock) != -1)
4539       // Some phis were already hand updated by the reduction and recurrence
4540       // code above, leave them alone.
4541       continue;
4542 
4543     auto *IncomingValue = LCSSAPhi.getIncomingValue(0);
4544     // Non-instruction incoming values will have only one value.
4545 
4546     VPLane Lane = VPLane::getFirstLane();
4547     if (isa<Instruction>(IncomingValue) &&
4548         !Cost->isUniformAfterVectorization(cast<Instruction>(IncomingValue),
4549                                            VF))
4550       Lane = VPLane::getLastLaneForVF(VF);
4551 
4552     // Can be a loop invariant incoming value or the last scalar value to be
4553     // extracted from the vectorized loop.
4554     Builder.SetInsertPoint(LoopMiddleBlock->getTerminator());
4555     Value *lastIncomingValue =
4556         OrigLoop->isLoopInvariant(IncomingValue)
4557             ? IncomingValue
4558             : State.get(State.Plan->getVPValue(IncomingValue),
4559                         VPIteration(UF - 1, Lane));
4560     LCSSAPhi.addIncoming(lastIncomingValue, LoopMiddleBlock);
4561   }
4562 }
4563 
sinkScalarOperands(Instruction * PredInst)4564 void InnerLoopVectorizer::sinkScalarOperands(Instruction *PredInst) {
4565   // The basic block and loop containing the predicated instruction.
4566   auto *PredBB = PredInst->getParent();
4567   auto *VectorLoop = LI->getLoopFor(PredBB);
4568 
4569   // Initialize a worklist with the operands of the predicated instruction.
4570   SetVector<Value *> Worklist(PredInst->op_begin(), PredInst->op_end());
4571 
4572   // Holds instructions that we need to analyze again. An instruction may be
4573   // reanalyzed if we don't yet know if we can sink it or not.
4574   SmallVector<Instruction *, 8> InstsToReanalyze;
4575 
4576   // Returns true if a given use occurs in the predicated block. Phi nodes use
4577   // their operands in their corresponding predecessor blocks.
4578   auto isBlockOfUsePredicated = [&](Use &U) -> bool {
4579     auto *I = cast<Instruction>(U.getUser());
4580     BasicBlock *BB = I->getParent();
4581     if (auto *Phi = dyn_cast<PHINode>(I))
4582       BB = Phi->getIncomingBlock(
4583           PHINode::getIncomingValueNumForOperand(U.getOperandNo()));
4584     return BB == PredBB;
4585   };
4586 
4587   // Iteratively sink the scalarized operands of the predicated instruction
4588   // into the block we created for it. When an instruction is sunk, it's
4589   // operands are then added to the worklist. The algorithm ends after one pass
4590   // through the worklist doesn't sink a single instruction.
4591   bool Changed;
4592   do {
4593     // Add the instructions that need to be reanalyzed to the worklist, and
4594     // reset the changed indicator.
4595     Worklist.insert(InstsToReanalyze.begin(), InstsToReanalyze.end());
4596     InstsToReanalyze.clear();
4597     Changed = false;
4598 
4599     while (!Worklist.empty()) {
4600       auto *I = dyn_cast<Instruction>(Worklist.pop_back_val());
4601 
4602       // We can't sink an instruction if it is a phi node, is already in the
4603       // predicated block, is not in the loop, or may have side effects.
4604       if (!I || isa<PHINode>(I) || I->getParent() == PredBB ||
4605           !VectorLoop->contains(I) || I->mayHaveSideEffects())
4606         continue;
4607 
4608       // It's legal to sink the instruction if all its uses occur in the
4609       // predicated block. Otherwise, there's nothing to do yet, and we may
4610       // need to reanalyze the instruction.
4611       if (!llvm::all_of(I->uses(), isBlockOfUsePredicated)) {
4612         InstsToReanalyze.push_back(I);
4613         continue;
4614       }
4615 
4616       // Move the instruction to the beginning of the predicated block, and add
4617       // it's operands to the worklist.
4618       I->moveBefore(&*PredBB->getFirstInsertionPt());
4619       Worklist.insert(I->op_begin(), I->op_end());
4620 
4621       // The sinking may have enabled other instructions to be sunk, so we will
4622       // need to iterate.
4623       Changed = true;
4624     }
4625   } while (Changed);
4626 }
4627 
fixNonInductionPHIs(VPTransformState & State)4628 void InnerLoopVectorizer::fixNonInductionPHIs(VPTransformState &State) {
4629   for (PHINode *OrigPhi : OrigPHIsToFix) {
4630     VPWidenPHIRecipe *VPPhi =
4631         cast<VPWidenPHIRecipe>(State.Plan->getVPValue(OrigPhi));
4632     PHINode *NewPhi = cast<PHINode>(State.get(VPPhi, 0));
4633     // Make sure the builder has a valid insert point.
4634     Builder.SetInsertPoint(NewPhi);
4635     for (unsigned i = 0; i < VPPhi->getNumOperands(); ++i) {
4636       VPValue *Inc = VPPhi->getIncomingValue(i);
4637       VPBasicBlock *VPBB = VPPhi->getIncomingBlock(i);
4638       NewPhi->addIncoming(State.get(Inc, 0), State.CFG.VPBB2IRBB[VPBB]);
4639     }
4640   }
4641 }
4642 
widenGEP(GetElementPtrInst * GEP,VPValue * VPDef,VPUser & Operands,unsigned UF,ElementCount VF,bool IsPtrLoopInvariant,SmallBitVector & IsIndexLoopInvariant,VPTransformState & State)4643 void InnerLoopVectorizer::widenGEP(GetElementPtrInst *GEP, VPValue *VPDef,
4644                                    VPUser &Operands, unsigned UF,
4645                                    ElementCount VF, bool IsPtrLoopInvariant,
4646                                    SmallBitVector &IsIndexLoopInvariant,
4647                                    VPTransformState &State) {
4648   // Construct a vector GEP by widening the operands of the scalar GEP as
4649   // necessary. We mark the vector GEP 'inbounds' if appropriate. A GEP
4650   // results in a vector of pointers when at least one operand of the GEP
4651   // is vector-typed. Thus, to keep the representation compact, we only use
4652   // vector-typed operands for loop-varying values.
4653 
4654   if (VF.isVector() && IsPtrLoopInvariant && IsIndexLoopInvariant.all()) {
4655     // If we are vectorizing, but the GEP has only loop-invariant operands,
4656     // the GEP we build (by only using vector-typed operands for
4657     // loop-varying values) would be a scalar pointer. Thus, to ensure we
4658     // produce a vector of pointers, we need to either arbitrarily pick an
4659     // operand to broadcast, or broadcast a clone of the original GEP.
4660     // Here, we broadcast a clone of the original.
4661     //
4662     // TODO: If at some point we decide to scalarize instructions having
4663     //       loop-invariant operands, this special case will no longer be
4664     //       required. We would add the scalarization decision to
4665     //       collectLoopScalars() and teach getVectorValue() to broadcast
4666     //       the lane-zero scalar value.
4667     auto *Clone = Builder.Insert(GEP->clone());
4668     for (unsigned Part = 0; Part < UF; ++Part) {
4669       Value *EntryPart = Builder.CreateVectorSplat(VF, Clone);
4670       State.set(VPDef, EntryPart, Part);
4671       addMetadata(EntryPart, GEP);
4672     }
4673   } else {
4674     // If the GEP has at least one loop-varying operand, we are sure to
4675     // produce a vector of pointers. But if we are only unrolling, we want
4676     // to produce a scalar GEP for each unroll part. Thus, the GEP we
4677     // produce with the code below will be scalar (if VF == 1) or vector
4678     // (otherwise). Note that for the unroll-only case, we still maintain
4679     // values in the vector mapping with initVector, as we do for other
4680     // instructions.
4681     for (unsigned Part = 0; Part < UF; ++Part) {
4682       // The pointer operand of the new GEP. If it's loop-invariant, we
4683       // won't broadcast it.
4684       auto *Ptr = IsPtrLoopInvariant
4685                       ? State.get(Operands.getOperand(0), VPIteration(0, 0))
4686                       : State.get(Operands.getOperand(0), Part);
4687 
4688       // Collect all the indices for the new GEP. If any index is
4689       // loop-invariant, we won't broadcast it.
4690       SmallVector<Value *, 4> Indices;
4691       for (unsigned I = 1, E = Operands.getNumOperands(); I < E; I++) {
4692         VPValue *Operand = Operands.getOperand(I);
4693         if (IsIndexLoopInvariant[I - 1])
4694           Indices.push_back(State.get(Operand, VPIteration(0, 0)));
4695         else
4696           Indices.push_back(State.get(Operand, Part));
4697       }
4698 
4699       // Create the new GEP. Note that this GEP may be a scalar if VF == 1,
4700       // but it should be a vector, otherwise.
4701       auto *NewGEP =
4702           GEP->isInBounds()
4703               ? Builder.CreateInBoundsGEP(GEP->getSourceElementType(), Ptr,
4704                                           Indices)
4705               : Builder.CreateGEP(GEP->getSourceElementType(), Ptr, Indices);
4706       assert((VF.isScalar() || NewGEP->getType()->isVectorTy()) &&
4707              "NewGEP is not a pointer vector");
4708       State.set(VPDef, NewGEP, Part);
4709       addMetadata(NewGEP, GEP);
4710     }
4711   }
4712 }
4713 
widenPHIInstruction(Instruction * PN,RecurrenceDescriptor * RdxDesc,VPWidenPHIRecipe * PhiR,VPTransformState & State)4714 void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN,
4715                                               RecurrenceDescriptor *RdxDesc,
4716                                               VPWidenPHIRecipe *PhiR,
4717                                               VPTransformState &State) {
4718   PHINode *P = cast<PHINode>(PN);
4719   if (EnableVPlanNativePath) {
4720     // Currently we enter here in the VPlan-native path for non-induction
4721     // PHIs where all control flow is uniform. We simply widen these PHIs.
4722     // Create a vector phi with no operands - the vector phi operands will be
4723     // set at the end of vector code generation.
4724     Type *VecTy = (State.VF.isScalar())
4725                       ? PN->getType()
4726                       : VectorType::get(PN->getType(), State.VF);
4727     Value *VecPhi = Builder.CreatePHI(VecTy, PN->getNumOperands(), "vec.phi");
4728     State.set(PhiR, VecPhi, 0);
4729     OrigPHIsToFix.push_back(P);
4730 
4731     return;
4732   }
4733 
4734   assert(PN->getParent() == OrigLoop->getHeader() &&
4735          "Non-header phis should have been handled elsewhere");
4736 
4737   VPValue *StartVPV = PhiR->getStartValue();
4738   Value *StartV = StartVPV ? StartVPV->getLiveInIRValue() : nullptr;
4739   // In order to support recurrences we need to be able to vectorize Phi nodes.
4740   // Phi nodes have cycles, so we need to vectorize them in two stages. This is
4741   // stage #1: We create a new vector PHI node with no incoming edges. We'll use
4742   // this value when we vectorize all of the instructions that use the PHI.
4743   if (RdxDesc || Legal->isFirstOrderRecurrence(P)) {
4744     Value *Iden = nullptr;
4745     bool ScalarPHI =
4746         (State.VF.isScalar()) || Cost->isInLoopReduction(cast<PHINode>(PN));
4747     Type *VecTy =
4748         ScalarPHI ? PN->getType() : VectorType::get(PN->getType(), State.VF);
4749 
4750     if (RdxDesc) {
4751       assert(Legal->isReductionVariable(P) && StartV &&
4752              "RdxDesc should only be set for reduction variables; in that case "
4753              "a StartV is also required");
4754       RecurKind RK = RdxDesc->getRecurrenceKind();
4755       if (RecurrenceDescriptor::isMinMaxRecurrenceKind(RK)) {
4756         // MinMax reduction have the start value as their identify.
4757         if (ScalarPHI) {
4758           Iden = StartV;
4759         } else {
4760           IRBuilderBase::InsertPointGuard IPBuilder(Builder);
4761           Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
4762           StartV = Iden =
4763               Builder.CreateVectorSplat(State.VF, StartV, "minmax.ident");
4764         }
4765       } else {
4766         Constant *IdenC = RecurrenceDescriptor::getRecurrenceIdentity(
4767             RK, VecTy->getScalarType(), RdxDesc->getFastMathFlags());
4768         Iden = IdenC;
4769 
4770         if (!ScalarPHI) {
4771           Iden = ConstantVector::getSplat(State.VF, IdenC);
4772           IRBuilderBase::InsertPointGuard IPBuilder(Builder);
4773           Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
4774           Constant *Zero = Builder.getInt32(0);
4775           StartV = Builder.CreateInsertElement(Iden, StartV, Zero);
4776         }
4777       }
4778     }
4779 
4780     bool IsOrdered = State.VF.isVector() &&
4781                      Cost->isInLoopReduction(cast<PHINode>(PN)) &&
4782                      useOrderedReductions(*RdxDesc);
4783 
4784     for (unsigned Part = 0; Part < State.UF; ++Part) {
4785       // This is phase one of vectorizing PHIs.
4786       if (Part > 0 && IsOrdered)
4787         return;
4788       Value *EntryPart = PHINode::Create(
4789           VecTy, 2, "vec.phi", &*LoopVectorBody->getFirstInsertionPt());
4790       State.set(PhiR, EntryPart, Part);
4791       if (StartV) {
4792         // Make sure to add the reduction start value only to the
4793         // first unroll part.
4794         Value *StartVal = (Part == 0) ? StartV : Iden;
4795         cast<PHINode>(EntryPart)->addIncoming(StartVal, LoopVectorPreHeader);
4796       }
4797     }
4798     return;
4799   }
4800 
4801   assert(!Legal->isReductionVariable(P) &&
4802          "reductions should be handled above");
4803 
4804   setDebugLocFromInst(Builder, P);
4805 
4806   // This PHINode must be an induction variable.
4807   // Make sure that we know about it.
4808   assert(Legal->getInductionVars().count(P) && "Not an induction variable");
4809 
4810   InductionDescriptor II = Legal->getInductionVars().lookup(P);
4811   const DataLayout &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
4812 
4813   // FIXME: The newly created binary instructions should contain nsw/nuw flags,
4814   // which can be found from the original scalar operations.
4815   switch (II.getKind()) {
4816   case InductionDescriptor::IK_NoInduction:
4817     llvm_unreachable("Unknown induction");
4818   case InductionDescriptor::IK_IntInduction:
4819   case InductionDescriptor::IK_FpInduction:
4820     llvm_unreachable("Integer/fp induction is handled elsewhere.");
4821   case InductionDescriptor::IK_PtrInduction: {
4822     // Handle the pointer induction variable case.
4823     assert(P->getType()->isPointerTy() && "Unexpected type.");
4824 
4825     if (Cost->isScalarAfterVectorization(P, State.VF)) {
4826       // This is the normalized GEP that starts counting at zero.
4827       Value *PtrInd =
4828           Builder.CreateSExtOrTrunc(Induction, II.getStep()->getType());
4829       // Determine the number of scalars we need to generate for each unroll
4830       // iteration. If the instruction is uniform, we only need to generate the
4831       // first lane. Otherwise, we generate all VF values.
4832       bool IsUniform = Cost->isUniformAfterVectorization(P, State.VF);
4833       unsigned Lanes = IsUniform ? 1 : State.VF.getKnownMinValue();
4834 
4835       bool NeedsVectorIndex = !IsUniform && VF.isScalable();
4836       Value *UnitStepVec = nullptr, *PtrIndSplat = nullptr;
4837       if (NeedsVectorIndex) {
4838         Type *VecIVTy = VectorType::get(PtrInd->getType(), VF);
4839         UnitStepVec = Builder.CreateStepVector(VecIVTy);
4840         PtrIndSplat = Builder.CreateVectorSplat(VF, PtrInd);
4841       }
4842 
4843       for (unsigned Part = 0; Part < UF; ++Part) {
4844         Value *PartStart = createStepForVF(
4845             Builder, ConstantInt::get(PtrInd->getType(), Part), VF);
4846 
4847         if (NeedsVectorIndex) {
4848           Value *PartStartSplat = Builder.CreateVectorSplat(VF, PartStart);
4849           Value *Indices = Builder.CreateAdd(PartStartSplat, UnitStepVec);
4850           Value *GlobalIndices = Builder.CreateAdd(PtrIndSplat, Indices);
4851           Value *SclrGep =
4852               emitTransformedIndex(Builder, GlobalIndices, PSE.getSE(), DL, II);
4853           SclrGep->setName("next.gep");
4854           State.set(PhiR, SclrGep, Part);
4855           // We've cached the whole vector, which means we can support the
4856           // extraction of any lane.
4857           continue;
4858         }
4859 
4860         for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
4861           Value *Idx = Builder.CreateAdd(
4862               PartStart, ConstantInt::get(PtrInd->getType(), Lane));
4863           Value *GlobalIdx = Builder.CreateAdd(PtrInd, Idx);
4864           Value *SclrGep =
4865               emitTransformedIndex(Builder, GlobalIdx, PSE.getSE(), DL, II);
4866           SclrGep->setName("next.gep");
4867           State.set(PhiR, SclrGep, VPIteration(Part, Lane));
4868         }
4869       }
4870       return;
4871     }
4872     assert(isa<SCEVConstant>(II.getStep()) &&
4873            "Induction step not a SCEV constant!");
4874     Type *PhiType = II.getStep()->getType();
4875 
4876     // Build a pointer phi
4877     Value *ScalarStartValue = II.getStartValue();
4878     Type *ScStValueType = ScalarStartValue->getType();
4879     PHINode *NewPointerPhi =
4880         PHINode::Create(ScStValueType, 2, "pointer.phi", Induction);
4881     NewPointerPhi->addIncoming(ScalarStartValue, LoopVectorPreHeader);
4882 
4883     // A pointer induction, performed by using a gep
4884     BasicBlock *LoopLatch = LI->getLoopFor(LoopVectorBody)->getLoopLatch();
4885     Instruction *InductionLoc = LoopLatch->getTerminator();
4886     const SCEV *ScalarStep = II.getStep();
4887     SCEVExpander Exp(*PSE.getSE(), DL, "induction");
4888     Value *ScalarStepValue =
4889         Exp.expandCodeFor(ScalarStep, PhiType, InductionLoc);
4890     Value *RuntimeVF = getRuntimeVF(Builder, PhiType, VF);
4891     Value *NumUnrolledElems =
4892         Builder.CreateMul(RuntimeVF, ConstantInt::get(PhiType, State.UF));
4893     Value *InductionGEP = GetElementPtrInst::Create(
4894         ScStValueType->getPointerElementType(), NewPointerPhi,
4895         Builder.CreateMul(ScalarStepValue, NumUnrolledElems), "ptr.ind",
4896         InductionLoc);
4897     NewPointerPhi->addIncoming(InductionGEP, LoopLatch);
4898 
4899     // Create UF many actual address geps that use the pointer
4900     // phi as base and a vectorized version of the step value
4901     // (<step*0, ..., step*N>) as offset.
4902     for (unsigned Part = 0; Part < State.UF; ++Part) {
4903       Type *VecPhiType = VectorType::get(PhiType, State.VF);
4904       Value *StartOffsetScalar =
4905           Builder.CreateMul(RuntimeVF, ConstantInt::get(PhiType, Part));
4906       Value *StartOffset =
4907           Builder.CreateVectorSplat(State.VF, StartOffsetScalar);
4908       // Create a vector of consecutive numbers from zero to VF.
4909       StartOffset =
4910           Builder.CreateAdd(StartOffset, Builder.CreateStepVector(VecPhiType));
4911 
4912       Value *GEP = Builder.CreateGEP(
4913           ScStValueType->getPointerElementType(), NewPointerPhi,
4914           Builder.CreateMul(
4915               StartOffset, Builder.CreateVectorSplat(State.VF, ScalarStepValue),
4916               "vector.gep"));
4917       State.set(PhiR, GEP, Part);
4918     }
4919   }
4920   }
4921 }
4922 
4923 /// A helper function for checking whether an integer division-related
4924 /// instruction may divide by zero (in which case it must be predicated if
4925 /// executed conditionally in the scalar code).
4926 /// TODO: It may be worthwhile to generalize and check isKnownNonZero().
4927 /// Non-zero divisors that are non compile-time constants will not be
4928 /// converted into multiplication, so we will still end up scalarizing
4929 /// the division, but can do so w/o predication.
mayDivideByZero(Instruction & I)4930 static bool mayDivideByZero(Instruction &I) {
4931   assert((I.getOpcode() == Instruction::UDiv ||
4932           I.getOpcode() == Instruction::SDiv ||
4933           I.getOpcode() == Instruction::URem ||
4934           I.getOpcode() == Instruction::SRem) &&
4935          "Unexpected instruction");
4936   Value *Divisor = I.getOperand(1);
4937   auto *CInt = dyn_cast<ConstantInt>(Divisor);
4938   return !CInt || CInt->isZero();
4939 }
4940 
widenInstruction(Instruction & I,VPValue * Def,VPUser & User,VPTransformState & State)4941 void InnerLoopVectorizer::widenInstruction(Instruction &I, VPValue *Def,
4942                                            VPUser &User,
4943                                            VPTransformState &State) {
4944   switch (I.getOpcode()) {
4945   case Instruction::Call:
4946   case Instruction::Br:
4947   case Instruction::PHI:
4948   case Instruction::GetElementPtr:
4949   case Instruction::Select:
4950     llvm_unreachable("This instruction is handled by a different recipe.");
4951   case Instruction::UDiv:
4952   case Instruction::SDiv:
4953   case Instruction::SRem:
4954   case Instruction::URem:
4955   case Instruction::Add:
4956   case Instruction::FAdd:
4957   case Instruction::Sub:
4958   case Instruction::FSub:
4959   case Instruction::FNeg:
4960   case Instruction::Mul:
4961   case Instruction::FMul:
4962   case Instruction::FDiv:
4963   case Instruction::FRem:
4964   case Instruction::Shl:
4965   case Instruction::LShr:
4966   case Instruction::AShr:
4967   case Instruction::And:
4968   case Instruction::Or:
4969   case Instruction::Xor: {
4970     // Just widen unops and binops.
4971     setDebugLocFromInst(Builder, &I);
4972 
4973     for (unsigned Part = 0; Part < UF; ++Part) {
4974       SmallVector<Value *, 2> Ops;
4975       for (VPValue *VPOp : User.operands())
4976         Ops.push_back(State.get(VPOp, Part));
4977 
4978       Value *V = Builder.CreateNAryOp(I.getOpcode(), Ops);
4979 
4980       if (auto *VecOp = dyn_cast<Instruction>(V))
4981         VecOp->copyIRFlags(&I);
4982 
4983       // Use this vector value for all users of the original instruction.
4984       State.set(Def, V, Part);
4985       addMetadata(V, &I);
4986     }
4987 
4988     break;
4989   }
4990   case Instruction::ICmp:
4991   case Instruction::FCmp: {
4992     // Widen compares. Generate vector compares.
4993     bool FCmp = (I.getOpcode() == Instruction::FCmp);
4994     auto *Cmp = cast<CmpInst>(&I);
4995     setDebugLocFromInst(Builder, Cmp);
4996     for (unsigned Part = 0; Part < UF; ++Part) {
4997       Value *A = State.get(User.getOperand(0), Part);
4998       Value *B = State.get(User.getOperand(1), Part);
4999       Value *C = nullptr;
5000       if (FCmp) {
5001         // Propagate fast math flags.
5002         IRBuilder<>::FastMathFlagGuard FMFG(Builder);
5003         Builder.setFastMathFlags(Cmp->getFastMathFlags());
5004         C = Builder.CreateFCmp(Cmp->getPredicate(), A, B);
5005       } else {
5006         C = Builder.CreateICmp(Cmp->getPredicate(), A, B);
5007       }
5008       State.set(Def, C, Part);
5009       addMetadata(C, &I);
5010     }
5011 
5012     break;
5013   }
5014 
5015   case Instruction::ZExt:
5016   case Instruction::SExt:
5017   case Instruction::FPToUI:
5018   case Instruction::FPToSI:
5019   case Instruction::FPExt:
5020   case Instruction::PtrToInt:
5021   case Instruction::IntToPtr:
5022   case Instruction::SIToFP:
5023   case Instruction::UIToFP:
5024   case Instruction::Trunc:
5025   case Instruction::FPTrunc:
5026   case Instruction::BitCast: {
5027     auto *CI = cast<CastInst>(&I);
5028     setDebugLocFromInst(Builder, CI);
5029 
5030     /// Vectorize casts.
5031     Type *DestTy =
5032         (VF.isScalar()) ? CI->getType() : VectorType::get(CI->getType(), VF);
5033 
5034     for (unsigned Part = 0; Part < UF; ++Part) {
5035       Value *A = State.get(User.getOperand(0), Part);
5036       Value *Cast = Builder.CreateCast(CI->getOpcode(), A, DestTy);
5037       State.set(Def, Cast, Part);
5038       addMetadata(Cast, &I);
5039     }
5040     break;
5041   }
5042   default:
5043     // This instruction is not vectorized by simple widening.
5044     LLVM_DEBUG(dbgs() << "LV: Found an unhandled instruction: " << I);
5045     llvm_unreachable("Unhandled instruction!");
5046   } // end of switch.
5047 }
5048 
widenCallInstruction(CallInst & I,VPValue * Def,VPUser & ArgOperands,VPTransformState & State)5049 void InnerLoopVectorizer::widenCallInstruction(CallInst &I, VPValue *Def,
5050                                                VPUser &ArgOperands,
5051                                                VPTransformState &State) {
5052   assert(!isa<DbgInfoIntrinsic>(I) &&
5053          "DbgInfoIntrinsic should have been dropped during VPlan construction");
5054   setDebugLocFromInst(Builder, &I);
5055 
5056   Module *M = I.getParent()->getParent()->getParent();
5057   auto *CI = cast<CallInst>(&I);
5058 
5059   SmallVector<Type *, 4> Tys;
5060   for (Value *ArgOperand : CI->arg_operands())
5061     Tys.push_back(ToVectorTy(ArgOperand->getType(), VF.getKnownMinValue()));
5062 
5063   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
5064 
5065   // The flag shows whether we use Intrinsic or a usual Call for vectorized
5066   // version of the instruction.
5067   // Is it beneficial to perform intrinsic call compared to lib call?
5068   bool NeedToScalarize = false;
5069   InstructionCost CallCost = Cost->getVectorCallCost(CI, VF, NeedToScalarize);
5070   InstructionCost IntrinsicCost = ID ? Cost->getVectorIntrinsicCost(CI, VF) : 0;
5071   bool UseVectorIntrinsic = ID && IntrinsicCost <= CallCost;
5072   assert((UseVectorIntrinsic || !NeedToScalarize) &&
5073          "Instruction should be scalarized elsewhere.");
5074   assert((IntrinsicCost.isValid() || CallCost.isValid()) &&
5075          "Either the intrinsic cost or vector call cost must be valid");
5076 
5077   for (unsigned Part = 0; Part < UF; ++Part) {
5078     SmallVector<Value *, 4> Args;
5079     for (auto &I : enumerate(ArgOperands.operands())) {
5080       // Some intrinsics have a scalar argument - don't replace it with a
5081       // vector.
5082       Value *Arg;
5083       if (!UseVectorIntrinsic || !hasVectorInstrinsicScalarOpd(ID, I.index()))
5084         Arg = State.get(I.value(), Part);
5085       else
5086         Arg = State.get(I.value(), VPIteration(0, 0));
5087       Args.push_back(Arg);
5088     }
5089 
5090     Function *VectorF;
5091     if (UseVectorIntrinsic) {
5092       // Use vector version of the intrinsic.
5093       Type *TysForDecl[] = {CI->getType()};
5094       if (VF.isVector())
5095         TysForDecl[0] = VectorType::get(CI->getType()->getScalarType(), VF);
5096       VectorF = Intrinsic::getDeclaration(M, ID, TysForDecl);
5097       assert(VectorF && "Can't retrieve vector intrinsic.");
5098     } else {
5099       // Use vector version of the function call.
5100       const VFShape Shape = VFShape::get(*CI, VF, false /*HasGlobalPred*/);
5101 #ifndef NDEBUG
5102       assert(VFDatabase(*CI).getVectorizedFunction(Shape) != nullptr &&
5103              "Can't create vector function.");
5104 #endif
5105         VectorF = VFDatabase(*CI).getVectorizedFunction(Shape);
5106     }
5107       SmallVector<OperandBundleDef, 1> OpBundles;
5108       CI->getOperandBundlesAsDefs(OpBundles);
5109       CallInst *V = Builder.CreateCall(VectorF, Args, OpBundles);
5110 
5111       if (isa<FPMathOperator>(V))
5112         V->copyFastMathFlags(CI);
5113 
5114       State.set(Def, V, Part);
5115       addMetadata(V, &I);
5116   }
5117 }
5118 
widenSelectInstruction(SelectInst & I,VPValue * VPDef,VPUser & Operands,bool InvariantCond,VPTransformState & State)5119 void InnerLoopVectorizer::widenSelectInstruction(SelectInst &I, VPValue *VPDef,
5120                                                  VPUser &Operands,
5121                                                  bool InvariantCond,
5122                                                  VPTransformState &State) {
5123   setDebugLocFromInst(Builder, &I);
5124 
5125   // The condition can be loop invariant  but still defined inside the
5126   // loop. This means that we can't just use the original 'cond' value.
5127   // We have to take the 'vectorized' value and pick the first lane.
5128   // Instcombine will make this a no-op.
5129   auto *InvarCond = InvariantCond
5130                         ? State.get(Operands.getOperand(0), VPIteration(0, 0))
5131                         : nullptr;
5132 
5133   for (unsigned Part = 0; Part < UF; ++Part) {
5134     Value *Cond =
5135         InvarCond ? InvarCond : State.get(Operands.getOperand(0), Part);
5136     Value *Op0 = State.get(Operands.getOperand(1), Part);
5137     Value *Op1 = State.get(Operands.getOperand(2), Part);
5138     Value *Sel = Builder.CreateSelect(Cond, Op0, Op1);
5139     State.set(VPDef, Sel, Part);
5140     addMetadata(Sel, &I);
5141   }
5142 }
5143 
collectLoopScalars(ElementCount VF)5144 void LoopVectorizationCostModel::collectLoopScalars(ElementCount VF) {
5145   // We should not collect Scalars more than once per VF. Right now, this
5146   // function is called from collectUniformsAndScalars(), which already does
5147   // this check. Collecting Scalars for VF=1 does not make any sense.
5148   assert(VF.isVector() && Scalars.find(VF) == Scalars.end() &&
5149          "This function should not be visited twice for the same VF");
5150 
5151   SmallSetVector<Instruction *, 8> Worklist;
5152 
5153   // These sets are used to seed the analysis with pointers used by memory
5154   // accesses that will remain scalar.
5155   SmallSetVector<Instruction *, 8> ScalarPtrs;
5156   SmallPtrSet<Instruction *, 8> PossibleNonScalarPtrs;
5157   auto *Latch = TheLoop->getLoopLatch();
5158 
5159   // A helper that returns true if the use of Ptr by MemAccess will be scalar.
5160   // The pointer operands of loads and stores will be scalar as long as the
5161   // memory access is not a gather or scatter operation. The value operand of a
5162   // store will remain scalar if the store is scalarized.
5163   auto isScalarUse = [&](Instruction *MemAccess, Value *Ptr) {
5164     InstWidening WideningDecision = getWideningDecision(MemAccess, VF);
5165     assert(WideningDecision != CM_Unknown &&
5166            "Widening decision should be ready at this moment");
5167     if (auto *Store = dyn_cast<StoreInst>(MemAccess))
5168       if (Ptr == Store->getValueOperand())
5169         return WideningDecision == CM_Scalarize;
5170     assert(Ptr == getLoadStorePointerOperand(MemAccess) &&
5171            "Ptr is neither a value or pointer operand");
5172     return WideningDecision != CM_GatherScatter;
5173   };
5174 
5175   // A helper that returns true if the given value is a bitcast or
5176   // getelementptr instruction contained in the loop.
5177   auto isLoopVaryingBitCastOrGEP = [&](Value *V) {
5178     return ((isa<BitCastInst>(V) && V->getType()->isPointerTy()) ||
5179             isa<GetElementPtrInst>(V)) &&
5180            !TheLoop->isLoopInvariant(V);
5181   };
5182 
5183   auto isScalarPtrInduction = [&](Instruction *MemAccess, Value *Ptr) {
5184     if (!isa<PHINode>(Ptr) ||
5185         !Legal->getInductionVars().count(cast<PHINode>(Ptr)))
5186       return false;
5187     auto &Induction = Legal->getInductionVars()[cast<PHINode>(Ptr)];
5188     if (Induction.getKind() != InductionDescriptor::IK_PtrInduction)
5189       return false;
5190     return isScalarUse(MemAccess, Ptr);
5191   };
5192 
5193   // A helper that evaluates a memory access's use of a pointer. If the
5194   // pointer is actually the pointer induction of a loop, it is being
5195   // inserted into Worklist. If the use will be a scalar use, and the
5196   // pointer is only used by memory accesses, we place the pointer in
5197   // ScalarPtrs. Otherwise, the pointer is placed in PossibleNonScalarPtrs.
5198   auto evaluatePtrUse = [&](Instruction *MemAccess, Value *Ptr) {
5199     if (isScalarPtrInduction(MemAccess, Ptr)) {
5200       Worklist.insert(cast<Instruction>(Ptr));
5201       Instruction *Update = cast<Instruction>(
5202           cast<PHINode>(Ptr)->getIncomingValueForBlock(Latch));
5203       Worklist.insert(Update);
5204       LLVM_DEBUG(dbgs() << "LV: Found new scalar instruction: " << *Ptr
5205                         << "\n");
5206       LLVM_DEBUG(dbgs() << "LV: Found new scalar instruction: " << *Update
5207                         << "\n");
5208       return;
5209     }
5210     // We only care about bitcast and getelementptr instructions contained in
5211     // the loop.
5212     if (!isLoopVaryingBitCastOrGEP(Ptr))
5213       return;
5214 
5215     // If the pointer has already been identified as scalar (e.g., if it was
5216     // also identified as uniform), there's nothing to do.
5217     auto *I = cast<Instruction>(Ptr);
5218     if (Worklist.count(I))
5219       return;
5220 
5221     // If the use of the pointer will be a scalar use, and all users of the
5222     // pointer are memory accesses, place the pointer in ScalarPtrs. Otherwise,
5223     // place the pointer in PossibleNonScalarPtrs.
5224     if (isScalarUse(MemAccess, Ptr) && llvm::all_of(I->users(), [&](User *U) {
5225           return isa<LoadInst>(U) || isa<StoreInst>(U);
5226         }))
5227       ScalarPtrs.insert(I);
5228     else
5229       PossibleNonScalarPtrs.insert(I);
5230   };
5231 
5232   // We seed the scalars analysis with three classes of instructions: (1)
5233   // instructions marked uniform-after-vectorization and (2) bitcast,
5234   // getelementptr and (pointer) phi instructions used by memory accesses
5235   // requiring a scalar use.
5236   //
5237   // (1) Add to the worklist all instructions that have been identified as
5238   // uniform-after-vectorization.
5239   Worklist.insert(Uniforms[VF].begin(), Uniforms[VF].end());
5240 
5241   // (2) Add to the worklist all bitcast and getelementptr instructions used by
5242   // memory accesses requiring a scalar use. The pointer operands of loads and
5243   // stores will be scalar as long as the memory accesses is not a gather or
5244   // scatter operation. The value operand of a store will remain scalar if the
5245   // store is scalarized.
5246   for (auto *BB : TheLoop->blocks())
5247     for (auto &I : *BB) {
5248       if (auto *Load = dyn_cast<LoadInst>(&I)) {
5249         evaluatePtrUse(Load, Load->getPointerOperand());
5250       } else if (auto *Store = dyn_cast<StoreInst>(&I)) {
5251         evaluatePtrUse(Store, Store->getPointerOperand());
5252         evaluatePtrUse(Store, Store->getValueOperand());
5253       }
5254     }
5255   for (auto *I : ScalarPtrs)
5256     if (!PossibleNonScalarPtrs.count(I)) {
5257       LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *I << "\n");
5258       Worklist.insert(I);
5259     }
5260 
5261   // Insert the forced scalars.
5262   // FIXME: Currently widenPHIInstruction() often creates a dead vector
5263   // induction variable when the PHI user is scalarized.
5264   auto ForcedScalar = ForcedScalars.find(VF);
5265   if (ForcedScalar != ForcedScalars.end())
5266     for (auto *I : ForcedScalar->second)
5267       Worklist.insert(I);
5268 
5269   // Expand the worklist by looking through any bitcasts and getelementptr
5270   // instructions we've already identified as scalar. This is similar to the
5271   // expansion step in collectLoopUniforms(); however, here we're only
5272   // expanding to include additional bitcasts and getelementptr instructions.
5273   unsigned Idx = 0;
5274   while (Idx != Worklist.size()) {
5275     Instruction *Dst = Worklist[Idx++];
5276     if (!isLoopVaryingBitCastOrGEP(Dst->getOperand(0)))
5277       continue;
5278     auto *Src = cast<Instruction>(Dst->getOperand(0));
5279     if (llvm::all_of(Src->users(), [&](User *U) -> bool {
5280           auto *J = cast<Instruction>(U);
5281           return !TheLoop->contains(J) || Worklist.count(J) ||
5282                  ((isa<LoadInst>(J) || isa<StoreInst>(J)) &&
5283                   isScalarUse(J, Src));
5284         })) {
5285       Worklist.insert(Src);
5286       LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Src << "\n");
5287     }
5288   }
5289 
5290   // An induction variable will remain scalar if all users of the induction
5291   // variable and induction variable update remain scalar.
5292   for (auto &Induction : Legal->getInductionVars()) {
5293     auto *Ind = Induction.first;
5294     auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
5295 
5296     // If tail-folding is applied, the primary induction variable will be used
5297     // to feed a vector compare.
5298     if (Ind == Legal->getPrimaryInduction() && foldTailByMasking())
5299       continue;
5300 
5301     // Determine if all users of the induction variable are scalar after
5302     // vectorization.
5303     auto ScalarInd = llvm::all_of(Ind->users(), [&](User *U) -> bool {
5304       auto *I = cast<Instruction>(U);
5305       return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I);
5306     });
5307     if (!ScalarInd)
5308       continue;
5309 
5310     // Determine if all users of the induction variable update instruction are
5311     // scalar after vectorization.
5312     auto ScalarIndUpdate =
5313         llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
5314           auto *I = cast<Instruction>(U);
5315           return I == Ind || !TheLoop->contains(I) || Worklist.count(I);
5316         });
5317     if (!ScalarIndUpdate)
5318       continue;
5319 
5320     // The induction variable and its update instruction will remain scalar.
5321     Worklist.insert(Ind);
5322     Worklist.insert(IndUpdate);
5323     LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Ind << "\n");
5324     LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *IndUpdate
5325                       << "\n");
5326   }
5327 
5328   Scalars[VF].insert(Worklist.begin(), Worklist.end());
5329 }
5330 
isScalarWithPredication(Instruction * I) const5331 bool LoopVectorizationCostModel::isScalarWithPredication(Instruction *I) const {
5332   if (!blockNeedsPredication(I->getParent()))
5333     return false;
5334   switch(I->getOpcode()) {
5335   default:
5336     break;
5337   case Instruction::Load:
5338   case Instruction::Store: {
5339     if (!Legal->isMaskRequired(I))
5340       return false;
5341     auto *Ptr = getLoadStorePointerOperand(I);
5342     auto *Ty = getMemInstValueType(I);
5343     const Align Alignment = getLoadStoreAlignment(I);
5344     return isa<LoadInst>(I) ? !(isLegalMaskedLoad(Ty, Ptr, Alignment) ||
5345                                 isLegalMaskedGather(Ty, Alignment))
5346                             : !(isLegalMaskedStore(Ty, Ptr, Alignment) ||
5347                                 isLegalMaskedScatter(Ty, Alignment));
5348   }
5349   case Instruction::UDiv:
5350   case Instruction::SDiv:
5351   case Instruction::SRem:
5352   case Instruction::URem:
5353     return mayDivideByZero(*I);
5354   }
5355   return false;
5356 }
5357 
interleavedAccessCanBeWidened(Instruction * I,ElementCount VF)5358 bool LoopVectorizationCostModel::interleavedAccessCanBeWidened(
5359     Instruction *I, ElementCount VF) {
5360   assert(isAccessInterleaved(I) && "Expecting interleaved access.");
5361   assert(getWideningDecision(I, VF) == CM_Unknown &&
5362          "Decision should not be set yet.");
5363   auto *Group = getInterleavedAccessGroup(I);
5364   assert(Group && "Must have a group.");
5365 
5366   // If the instruction's allocated size doesn't equal it's type size, it
5367   // requires padding and will be scalarized.
5368   auto &DL = I->getModule()->getDataLayout();
5369   auto *ScalarTy = getMemInstValueType(I);
5370   if (hasIrregularType(ScalarTy, DL))
5371     return false;
5372 
5373   // Check if masking is required.
5374   // A Group may need masking for one of two reasons: it resides in a block that
5375   // needs predication, or it was decided to use masking to deal with gaps.
5376   bool PredicatedAccessRequiresMasking =
5377       Legal->blockNeedsPredication(I->getParent()) && Legal->isMaskRequired(I);
5378   bool AccessWithGapsRequiresMasking =
5379       Group->requiresScalarEpilogue() && !isScalarEpilogueAllowed();
5380   if (!PredicatedAccessRequiresMasking && !AccessWithGapsRequiresMasking)
5381     return true;
5382 
5383   // If masked interleaving is required, we expect that the user/target had
5384   // enabled it, because otherwise it either wouldn't have been created or
5385   // it should have been invalidated by the CostModel.
5386   assert(useMaskedInterleavedAccesses(TTI) &&
5387          "Masked interleave-groups for predicated accesses are not enabled.");
5388 
5389   auto *Ty = getMemInstValueType(I);
5390   const Align Alignment = getLoadStoreAlignment(I);
5391   return isa<LoadInst>(I) ? TTI.isLegalMaskedLoad(Ty, Alignment)
5392                           : TTI.isLegalMaskedStore(Ty, Alignment);
5393 }
5394 
memoryInstructionCanBeWidened(Instruction * I,ElementCount VF)5395 bool LoopVectorizationCostModel::memoryInstructionCanBeWidened(
5396     Instruction *I, ElementCount VF) {
5397   // Get and ensure we have a valid memory instruction.
5398   LoadInst *LI = dyn_cast<LoadInst>(I);
5399   StoreInst *SI = dyn_cast<StoreInst>(I);
5400   assert((LI || SI) && "Invalid memory instruction");
5401 
5402   auto *Ptr = getLoadStorePointerOperand(I);
5403 
5404   // In order to be widened, the pointer should be consecutive, first of all.
5405   if (!Legal->isConsecutivePtr(Ptr))
5406     return false;
5407 
5408   // If the instruction is a store located in a predicated block, it will be
5409   // scalarized.
5410   if (isScalarWithPredication(I))
5411     return false;
5412 
5413   // If the instruction's allocated size doesn't equal it's type size, it
5414   // requires padding and will be scalarized.
5415   auto &DL = I->getModule()->getDataLayout();
5416   auto *ScalarTy = LI ? LI->getType() : SI->getValueOperand()->getType();
5417   if (hasIrregularType(ScalarTy, DL))
5418     return false;
5419 
5420   return true;
5421 }
5422 
collectLoopUniforms(ElementCount VF)5423 void LoopVectorizationCostModel::collectLoopUniforms(ElementCount VF) {
5424   // We should not collect Uniforms more than once per VF. Right now,
5425   // this function is called from collectUniformsAndScalars(), which
5426   // already does this check. Collecting Uniforms for VF=1 does not make any
5427   // sense.
5428 
5429   assert(VF.isVector() && Uniforms.find(VF) == Uniforms.end() &&
5430          "This function should not be visited twice for the same VF");
5431 
5432   // Visit the list of Uniforms. If we'll not find any uniform value, we'll
5433   // not analyze again.  Uniforms.count(VF) will return 1.
5434   Uniforms[VF].clear();
5435 
5436   // We now know that the loop is vectorizable!
5437   // Collect instructions inside the loop that will remain uniform after
5438   // vectorization.
5439 
5440   // Global values, params and instructions outside of current loop are out of
5441   // scope.
5442   auto isOutOfScope = [&](Value *V) -> bool {
5443     Instruction *I = dyn_cast<Instruction>(V);
5444     return (!I || !TheLoop->contains(I));
5445   };
5446 
5447   SetVector<Instruction *> Worklist;
5448   BasicBlock *Latch = TheLoop->getLoopLatch();
5449 
5450   // Instructions that are scalar with predication must not be considered
5451   // uniform after vectorization, because that would create an erroneous
5452   // replicating region where only a single instance out of VF should be formed.
5453   // TODO: optimize such seldom cases if found important, see PR40816.
5454   auto addToWorklistIfAllowed = [&](Instruction *I) -> void {
5455     if (isOutOfScope(I)) {
5456       LLVM_DEBUG(dbgs() << "LV: Found not uniform due to scope: "
5457                         << *I << "\n");
5458       return;
5459     }
5460     if (isScalarWithPredication(I)) {
5461       LLVM_DEBUG(dbgs() << "LV: Found not uniform being ScalarWithPredication: "
5462                         << *I << "\n");
5463       return;
5464     }
5465     LLVM_DEBUG(dbgs() << "LV: Found uniform instruction: " << *I << "\n");
5466     Worklist.insert(I);
5467   };
5468 
5469   // Start with the conditional branch. If the branch condition is an
5470   // instruction contained in the loop that is only used by the branch, it is
5471   // uniform.
5472   auto *Cmp = dyn_cast<Instruction>(Latch->getTerminator()->getOperand(0));
5473   if (Cmp && TheLoop->contains(Cmp) && Cmp->hasOneUse())
5474     addToWorklistIfAllowed(Cmp);
5475 
5476   auto isUniformDecision = [&](Instruction *I, ElementCount VF) {
5477     InstWidening WideningDecision = getWideningDecision(I, VF);
5478     assert(WideningDecision != CM_Unknown &&
5479            "Widening decision should be ready at this moment");
5480 
5481     // A uniform memory op is itself uniform.  We exclude uniform stores
5482     // here as they demand the last lane, not the first one.
5483     if (isa<LoadInst>(I) && Legal->isUniformMemOp(*I)) {
5484       assert(WideningDecision == CM_Scalarize);
5485       return true;
5486     }
5487 
5488     return (WideningDecision == CM_Widen ||
5489             WideningDecision == CM_Widen_Reverse ||
5490             WideningDecision == CM_Interleave);
5491   };
5492 
5493 
5494   // Returns true if Ptr is the pointer operand of a memory access instruction
5495   // I, and I is known to not require scalarization.
5496   auto isVectorizedMemAccessUse = [&](Instruction *I, Value *Ptr) -> bool {
5497     return getLoadStorePointerOperand(I) == Ptr && isUniformDecision(I, VF);
5498   };
5499 
5500   // Holds a list of values which are known to have at least one uniform use.
5501   // Note that there may be other uses which aren't uniform.  A "uniform use"
5502   // here is something which only demands lane 0 of the unrolled iterations;
5503   // it does not imply that all lanes produce the same value (e.g. this is not
5504   // the usual meaning of uniform)
5505   SetVector<Value *> HasUniformUse;
5506 
5507   // Scan the loop for instructions which are either a) known to have only
5508   // lane 0 demanded or b) are uses which demand only lane 0 of their operand.
5509   for (auto *BB : TheLoop->blocks())
5510     for (auto &I : *BB) {
5511       // If there's no pointer operand, there's nothing to do.
5512       auto *Ptr = getLoadStorePointerOperand(&I);
5513       if (!Ptr)
5514         continue;
5515 
5516       // A uniform memory op is itself uniform.  We exclude uniform stores
5517       // here as they demand the last lane, not the first one.
5518       if (isa<LoadInst>(I) && Legal->isUniformMemOp(I))
5519         addToWorklistIfAllowed(&I);
5520 
5521       if (isUniformDecision(&I, VF)) {
5522         assert(isVectorizedMemAccessUse(&I, Ptr) && "consistency check");
5523         HasUniformUse.insert(Ptr);
5524       }
5525     }
5526 
5527   // Add to the worklist any operands which have *only* uniform (e.g. lane 0
5528   // demanding) users.  Since loops are assumed to be in LCSSA form, this
5529   // disallows uses outside the loop as well.
5530   for (auto *V : HasUniformUse) {
5531     if (isOutOfScope(V))
5532       continue;
5533     auto *I = cast<Instruction>(V);
5534     auto UsersAreMemAccesses =
5535       llvm::all_of(I->users(), [&](User *U) -> bool {
5536         return isVectorizedMemAccessUse(cast<Instruction>(U), V);
5537       });
5538     if (UsersAreMemAccesses)
5539       addToWorklistIfAllowed(I);
5540   }
5541 
5542   // Expand Worklist in topological order: whenever a new instruction
5543   // is added , its users should be already inside Worklist.  It ensures
5544   // a uniform instruction will only be used by uniform instructions.
5545   unsigned idx = 0;
5546   while (idx != Worklist.size()) {
5547     Instruction *I = Worklist[idx++];
5548 
5549     for (auto OV : I->operand_values()) {
5550       // isOutOfScope operands cannot be uniform instructions.
5551       if (isOutOfScope(OV))
5552         continue;
5553       // First order recurrence Phi's should typically be considered
5554       // non-uniform.
5555       auto *OP = dyn_cast<PHINode>(OV);
5556       if (OP && Legal->isFirstOrderRecurrence(OP))
5557         continue;
5558       // If all the users of the operand are uniform, then add the
5559       // operand into the uniform worklist.
5560       auto *OI = cast<Instruction>(OV);
5561       if (llvm::all_of(OI->users(), [&](User *U) -> bool {
5562             auto *J = cast<Instruction>(U);
5563             return Worklist.count(J) || isVectorizedMemAccessUse(J, OI);
5564           }))
5565         addToWorklistIfAllowed(OI);
5566     }
5567   }
5568 
5569   // For an instruction to be added into Worklist above, all its users inside
5570   // the loop should also be in Worklist. However, this condition cannot be
5571   // true for phi nodes that form a cyclic dependence. We must process phi
5572   // nodes separately. An induction variable will remain uniform if all users
5573   // of the induction variable and induction variable update remain uniform.
5574   // The code below handles both pointer and non-pointer induction variables.
5575   for (auto &Induction : Legal->getInductionVars()) {
5576     auto *Ind = Induction.first;
5577     auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
5578 
5579     // Determine if all users of the induction variable are uniform after
5580     // vectorization.
5581     auto UniformInd = llvm::all_of(Ind->users(), [&](User *U) -> bool {
5582       auto *I = cast<Instruction>(U);
5583       return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) ||
5584              isVectorizedMemAccessUse(I, Ind);
5585     });
5586     if (!UniformInd)
5587       continue;
5588 
5589     // Determine if all users of the induction variable update instruction are
5590     // uniform after vectorization.
5591     auto UniformIndUpdate =
5592         llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
5593           auto *I = cast<Instruction>(U);
5594           return I == Ind || !TheLoop->contains(I) || Worklist.count(I) ||
5595                  isVectorizedMemAccessUse(I, IndUpdate);
5596         });
5597     if (!UniformIndUpdate)
5598       continue;
5599 
5600     // The induction variable and its update instruction will remain uniform.
5601     addToWorklistIfAllowed(Ind);
5602     addToWorklistIfAllowed(IndUpdate);
5603   }
5604 
5605   Uniforms[VF].insert(Worklist.begin(), Worklist.end());
5606 }
5607 
runtimeChecksRequired()5608 bool LoopVectorizationCostModel::runtimeChecksRequired() {
5609   LLVM_DEBUG(dbgs() << "LV: Performing code size checks.\n");
5610 
5611   if (Legal->getRuntimePointerChecking()->Need) {
5612     reportVectorizationFailure("Runtime ptr check is required with -Os/-Oz",
5613         "runtime pointer checks needed. Enable vectorization of this "
5614         "loop with '#pragma clang loop vectorize(enable)' when "
5615         "compiling with -Os/-Oz",
5616         "CantVersionLoopWithOptForSize", ORE, TheLoop);
5617     return true;
5618   }
5619 
5620   if (!PSE.getUnionPredicate().getPredicates().empty()) {
5621     reportVectorizationFailure("Runtime SCEV check is required with -Os/-Oz",
5622         "runtime SCEV checks needed. Enable vectorization of this "
5623         "loop with '#pragma clang loop vectorize(enable)' when "
5624         "compiling with -Os/-Oz",
5625         "CantVersionLoopWithOptForSize", ORE, TheLoop);
5626     return true;
5627   }
5628 
5629   // FIXME: Avoid specializing for stride==1 instead of bailing out.
5630   if (!Legal->getLAI()->getSymbolicStrides().empty()) {
5631     reportVectorizationFailure("Runtime stride check for small trip count",
5632         "runtime stride == 1 checks needed. Enable vectorization of "
5633         "this loop without such check by compiling with -Os/-Oz",
5634         "CantVersionLoopWithOptForSize", ORE, TheLoop);
5635     return true;
5636   }
5637 
5638   return false;
5639 }
5640 
5641 ElementCount
getMaxLegalScalableVF(unsigned MaxSafeElements)5642 LoopVectorizationCostModel::getMaxLegalScalableVF(unsigned MaxSafeElements) {
5643   if (!TTI.supportsScalableVectors() && !ForceTargetSupportsScalableVectors) {
5644     reportVectorizationInfo(
5645         "Disabling scalable vectorization, because target does not "
5646         "support scalable vectors.",
5647         "ScalableVectorsUnsupported", ORE, TheLoop);
5648     return ElementCount::getScalable(0);
5649   }
5650 
5651   if (Hints->isScalableVectorizationDisabled()) {
5652     reportVectorizationInfo("Scalable vectorization is explicitly disabled",
5653                             "ScalableVectorizationDisabled", ORE, TheLoop);
5654     return ElementCount::getScalable(0);
5655   }
5656 
5657   auto MaxScalableVF = ElementCount::getScalable(
5658       std::numeric_limits<ElementCount::ScalarTy>::max());
5659 
5660   // Disable scalable vectorization if the loop contains unsupported reductions.
5661   // Test that the loop-vectorizer can legalize all operations for this MaxVF.
5662   // FIXME: While for scalable vectors this is currently sufficient, this should
5663   // be replaced by a more detailed mechanism that filters out specific VFs,
5664   // instead of invalidating vectorization for a whole set of VFs based on the
5665   // MaxVF.
5666   if (!canVectorizeReductions(MaxScalableVF)) {
5667     reportVectorizationInfo(
5668         "Scalable vectorization not supported for the reduction "
5669         "operations found in this loop.",
5670         "ScalableVFUnfeasible", ORE, TheLoop);
5671     return ElementCount::getScalable(0);
5672   }
5673 
5674   if (Legal->isSafeForAnyVectorWidth())
5675     return MaxScalableVF;
5676 
5677   // Limit MaxScalableVF by the maximum safe dependence distance.
5678   Optional<unsigned> MaxVScale = TTI.getMaxVScale();
5679   MaxScalableVF = ElementCount::getScalable(
5680       MaxVScale ? (MaxSafeElements / MaxVScale.getValue()) : 0);
5681   if (!MaxScalableVF)
5682     reportVectorizationInfo(
5683         "Max legal vector width too small, scalable vectorization "
5684         "unfeasible.",
5685         "ScalableVFUnfeasible", ORE, TheLoop);
5686 
5687   return MaxScalableVF;
5688 }
5689 
5690 FixedScalableVFPair
computeFeasibleMaxVF(unsigned ConstTripCount,ElementCount UserVF)5691 LoopVectorizationCostModel::computeFeasibleMaxVF(unsigned ConstTripCount,
5692                                                  ElementCount UserVF) {
5693   MinBWs = computeMinimumValueSizes(TheLoop->getBlocks(), *DB, &TTI);
5694   unsigned SmallestType, WidestType;
5695   std::tie(SmallestType, WidestType) = getSmallestAndWidestTypes();
5696 
5697   // Get the maximum safe dependence distance in bits computed by LAA.
5698   // It is computed by MaxVF * sizeOf(type) * 8, where type is taken from
5699   // the memory accesses that is most restrictive (involved in the smallest
5700   // dependence distance).
5701   unsigned MaxSafeElements =
5702       PowerOf2Floor(Legal->getMaxSafeVectorWidthInBits() / WidestType);
5703 
5704   auto MaxSafeFixedVF = ElementCount::getFixed(MaxSafeElements);
5705   auto MaxSafeScalableVF = getMaxLegalScalableVF(MaxSafeElements);
5706 
5707   LLVM_DEBUG(dbgs() << "LV: The max safe fixed VF is: " << MaxSafeFixedVF
5708                     << ".\n");
5709   LLVM_DEBUG(dbgs() << "LV: The max safe scalable VF is: " << MaxSafeScalableVF
5710                     << ".\n");
5711 
5712   // First analyze the UserVF, fall back if the UserVF should be ignored.
5713   if (UserVF) {
5714     auto MaxSafeUserVF =
5715         UserVF.isScalable() ? MaxSafeScalableVF : MaxSafeFixedVF;
5716 
5717     if (ElementCount::isKnownLE(UserVF, MaxSafeUserVF))
5718       return UserVF;
5719 
5720     assert(ElementCount::isKnownGT(UserVF, MaxSafeUserVF));
5721 
5722     // Only clamp if the UserVF is not scalable. If the UserVF is scalable, it
5723     // is better to ignore the hint and let the compiler choose a suitable VF.
5724     if (!UserVF.isScalable()) {
5725       LLVM_DEBUG(dbgs() << "LV: User VF=" << UserVF
5726                         << " is unsafe, clamping to max safe VF="
5727                         << MaxSafeFixedVF << ".\n");
5728       ORE->emit([&]() {
5729         return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationFactor",
5730                                           TheLoop->getStartLoc(),
5731                                           TheLoop->getHeader())
5732                << "User-specified vectorization factor "
5733                << ore::NV("UserVectorizationFactor", UserVF)
5734                << " is unsafe, clamping to maximum safe vectorization factor "
5735                << ore::NV("VectorizationFactor", MaxSafeFixedVF);
5736       });
5737       return MaxSafeFixedVF;
5738     }
5739 
5740     LLVM_DEBUG(dbgs() << "LV: User VF=" << UserVF
5741                       << " is unsafe. Ignoring scalable UserVF.\n");
5742     ORE->emit([&]() {
5743       return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationFactor",
5744                                         TheLoop->getStartLoc(),
5745                                         TheLoop->getHeader())
5746              << "User-specified vectorization factor "
5747              << ore::NV("UserVectorizationFactor", UserVF)
5748              << " is unsafe. Ignoring the hint to let the compiler pick a "
5749                 "suitable VF.";
5750     });
5751   }
5752 
5753   LLVM_DEBUG(dbgs() << "LV: The Smallest and Widest types: " << SmallestType
5754                     << " / " << WidestType << " bits.\n");
5755 
5756   FixedScalableVFPair Result(ElementCount::getFixed(1),
5757                              ElementCount::getScalable(0));
5758   if (auto MaxVF = getMaximizedVFForTarget(ConstTripCount, SmallestType,
5759                                            WidestType, MaxSafeFixedVF))
5760     Result.FixedVF = MaxVF;
5761 
5762   if (auto MaxVF = getMaximizedVFForTarget(ConstTripCount, SmallestType,
5763                                            WidestType, MaxSafeScalableVF))
5764     if (MaxVF.isScalable()) {
5765       Result.ScalableVF = MaxVF;
5766       LLVM_DEBUG(dbgs() << "LV: Found feasible scalable VF = " << MaxVF
5767                         << "\n");
5768     }
5769 
5770   return Result;
5771 }
5772 
5773 FixedScalableVFPair
computeMaxVF(ElementCount UserVF,unsigned UserIC)5774 LoopVectorizationCostModel::computeMaxVF(ElementCount UserVF, unsigned UserIC) {
5775   if (Legal->getRuntimePointerChecking()->Need && TTI.hasBranchDivergence()) {
5776     // TODO: It may by useful to do since it's still likely to be dynamically
5777     // uniform if the target can skip.
5778     reportVectorizationFailure(
5779         "Not inserting runtime ptr check for divergent target",
5780         "runtime pointer checks needed. Not enabled for divergent target",
5781         "CantVersionLoopWithDivergentTarget", ORE, TheLoop);
5782     return FixedScalableVFPair::getNone();
5783   }
5784 
5785   unsigned TC = PSE.getSE()->getSmallConstantTripCount(TheLoop);
5786   LLVM_DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
5787   if (TC == 1) {
5788     reportVectorizationFailure("Single iteration (non) loop",
5789         "loop trip count is one, irrelevant for vectorization",
5790         "SingleIterationLoop", ORE, TheLoop);
5791     return FixedScalableVFPair::getNone();
5792   }
5793 
5794   switch (ScalarEpilogueStatus) {
5795   case CM_ScalarEpilogueAllowed:
5796     return computeFeasibleMaxVF(TC, UserVF);
5797   case CM_ScalarEpilogueNotAllowedUsePredicate:
5798     LLVM_FALLTHROUGH;
5799   case CM_ScalarEpilogueNotNeededUsePredicate:
5800     LLVM_DEBUG(
5801         dbgs() << "LV: vector predicate hint/switch found.\n"
5802                << "LV: Not allowing scalar epilogue, creating predicated "
5803                << "vector loop.\n");
5804     break;
5805   case CM_ScalarEpilogueNotAllowedLowTripLoop:
5806     // fallthrough as a special case of OptForSize
5807   case CM_ScalarEpilogueNotAllowedOptSize:
5808     if (ScalarEpilogueStatus == CM_ScalarEpilogueNotAllowedOptSize)
5809       LLVM_DEBUG(
5810           dbgs() << "LV: Not allowing scalar epilogue due to -Os/-Oz.\n");
5811     else
5812       LLVM_DEBUG(dbgs() << "LV: Not allowing scalar epilogue due to low trip "
5813                         << "count.\n");
5814 
5815     // Bail if runtime checks are required, which are not good when optimising
5816     // for size.
5817     if (runtimeChecksRequired())
5818       return FixedScalableVFPair::getNone();
5819 
5820     break;
5821   }
5822 
5823   // The only loops we can vectorize without a scalar epilogue, are loops with
5824   // a bottom-test and a single exiting block. We'd have to handle the fact
5825   // that not every instruction executes on the last iteration.  This will
5826   // require a lane mask which varies through the vector loop body.  (TODO)
5827   if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
5828     // If there was a tail-folding hint/switch, but we can't fold the tail by
5829     // masking, fallback to a vectorization with a scalar epilogue.
5830     if (ScalarEpilogueStatus == CM_ScalarEpilogueNotNeededUsePredicate) {
5831       LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking: vectorize with a "
5832                            "scalar epilogue instead.\n");
5833       ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
5834       return computeFeasibleMaxVF(TC, UserVF);
5835     }
5836     return FixedScalableVFPair::getNone();
5837   }
5838 
5839   // Now try the tail folding
5840 
5841   // Invalidate interleave groups that require an epilogue if we can't mask
5842   // the interleave-group.
5843   if (!useMaskedInterleavedAccesses(TTI)) {
5844     assert(WideningDecisions.empty() && Uniforms.empty() && Scalars.empty() &&
5845            "No decisions should have been taken at this point");
5846     // Note: There is no need to invalidate any cost modeling decisions here, as
5847     // non where taken so far.
5848     InterleaveInfo.invalidateGroupsRequiringScalarEpilogue();
5849   }
5850 
5851   FixedScalableVFPair MaxFactors = computeFeasibleMaxVF(TC, UserVF);
5852   // Avoid tail folding if the trip count is known to be a multiple of any VF
5853   // we chose.
5854   // FIXME: The condition below pessimises the case for fixed-width vectors,
5855   // when scalable VFs are also candidates for vectorization.
5856   if (MaxFactors.FixedVF.isVector() && !MaxFactors.ScalableVF) {
5857     ElementCount MaxFixedVF = MaxFactors.FixedVF;
5858     assert((UserVF.isNonZero() || isPowerOf2_32(MaxFixedVF.getFixedValue())) &&
5859            "MaxFixedVF must be a power of 2");
5860     unsigned MaxVFtimesIC = UserIC ? MaxFixedVF.getFixedValue() * UserIC
5861                                    : MaxFixedVF.getFixedValue();
5862     ScalarEvolution *SE = PSE.getSE();
5863     const SCEV *BackedgeTakenCount = PSE.getBackedgeTakenCount();
5864     const SCEV *ExitCount = SE->getAddExpr(
5865         BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType()));
5866     const SCEV *Rem = SE->getURemExpr(
5867         SE->applyLoopGuards(ExitCount, TheLoop),
5868         SE->getConstant(BackedgeTakenCount->getType(), MaxVFtimesIC));
5869     if (Rem->isZero()) {
5870       // Accept MaxFixedVF if we do not have a tail.
5871       LLVM_DEBUG(dbgs() << "LV: No tail will remain for any chosen VF.\n");
5872       return MaxFactors;
5873     }
5874   }
5875 
5876   // If we don't know the precise trip count, or if the trip count that we
5877   // found modulo the vectorization factor is not zero, try to fold the tail
5878   // by masking.
5879   // FIXME: look for a smaller MaxVF that does divide TC rather than masking.
5880   if (Legal->prepareToFoldTailByMasking()) {
5881     FoldTailByMasking = true;
5882     return MaxFactors;
5883   }
5884 
5885   // If there was a tail-folding hint/switch, but we can't fold the tail by
5886   // masking, fallback to a vectorization with a scalar epilogue.
5887   if (ScalarEpilogueStatus == CM_ScalarEpilogueNotNeededUsePredicate) {
5888     LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking: vectorize with a "
5889                          "scalar epilogue instead.\n");
5890     ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
5891     return MaxFactors;
5892   }
5893 
5894   if (ScalarEpilogueStatus == CM_ScalarEpilogueNotAllowedUsePredicate) {
5895     LLVM_DEBUG(dbgs() << "LV: Can't fold tail by masking: don't vectorize\n");
5896     return FixedScalableVFPair::getNone();
5897   }
5898 
5899   if (TC == 0) {
5900     reportVectorizationFailure(
5901         "Unable to calculate the loop count due to complex control flow",
5902         "unable to calculate the loop count due to complex control flow",
5903         "UnknownLoopCountComplexCFG", ORE, TheLoop);
5904     return FixedScalableVFPair::getNone();
5905   }
5906 
5907   reportVectorizationFailure(
5908       "Cannot optimize for size and vectorize at the same time.",
5909       "cannot optimize for size and vectorize at the same time. "
5910       "Enable vectorization of this loop with '#pragma clang loop "
5911       "vectorize(enable)' when compiling with -Os/-Oz",
5912       "NoTailLoopWithOptForSize", ORE, TheLoop);
5913   return FixedScalableVFPair::getNone();
5914 }
5915 
getMaximizedVFForTarget(unsigned ConstTripCount,unsigned SmallestType,unsigned WidestType,const ElementCount & MaxSafeVF)5916 ElementCount LoopVectorizationCostModel::getMaximizedVFForTarget(
5917     unsigned ConstTripCount, unsigned SmallestType, unsigned WidestType,
5918     const ElementCount &MaxSafeVF) {
5919   bool ComputeScalableMaxVF = MaxSafeVF.isScalable();
5920   TypeSize WidestRegister = TTI.getRegisterBitWidth(
5921       ComputeScalableMaxVF ? TargetTransformInfo::RGK_ScalableVector
5922                            : TargetTransformInfo::RGK_FixedWidthVector);
5923 
5924   // Convenience function to return the minimum of two ElementCounts.
5925   auto MinVF = [](const ElementCount &LHS, const ElementCount &RHS) {
5926     assert((LHS.isScalable() == RHS.isScalable()) &&
5927            "Scalable flags must match");
5928     return ElementCount::isKnownLT(LHS, RHS) ? LHS : RHS;
5929   };
5930 
5931   // Ensure MaxVF is a power of 2; the dependence distance bound may not be.
5932   // Note that both WidestRegister and WidestType may not be a powers of 2.
5933   auto MaxVectorElementCount = ElementCount::get(
5934       PowerOf2Floor(WidestRegister.getKnownMinSize() / WidestType),
5935       ComputeScalableMaxVF);
5936   MaxVectorElementCount = MinVF(MaxVectorElementCount, MaxSafeVF);
5937   LLVM_DEBUG(dbgs() << "LV: The Widest register safe to use is: "
5938                     << (MaxVectorElementCount * WidestType) << " bits.\n");
5939 
5940   if (!MaxVectorElementCount) {
5941     LLVM_DEBUG(dbgs() << "LV: The target has no vector registers.\n");
5942     return ElementCount::getFixed(1);
5943   }
5944 
5945   const auto TripCountEC = ElementCount::getFixed(ConstTripCount);
5946   if (ConstTripCount &&
5947       ElementCount::isKnownLE(TripCountEC, MaxVectorElementCount) &&
5948       isPowerOf2_32(ConstTripCount)) {
5949     // We need to clamp the VF to be the ConstTripCount. There is no point in
5950     // choosing a higher viable VF as done in the loop below. If
5951     // MaxVectorElementCount is scalable, we only fall back on a fixed VF when
5952     // the TC is less than or equal to the known number of lanes.
5953     LLVM_DEBUG(dbgs() << "LV: Clamping the MaxVF to the constant trip count: "
5954                       << ConstTripCount << "\n");
5955     return TripCountEC;
5956   }
5957 
5958   ElementCount MaxVF = MaxVectorElementCount;
5959   if (TTI.shouldMaximizeVectorBandwidth() ||
5960       (MaximizeBandwidth && isScalarEpilogueAllowed())) {
5961     auto MaxVectorElementCountMaxBW = ElementCount::get(
5962         PowerOf2Floor(WidestRegister.getKnownMinSize() / SmallestType),
5963         ComputeScalableMaxVF);
5964     MaxVectorElementCountMaxBW = MinVF(MaxVectorElementCountMaxBW, MaxSafeVF);
5965 
5966     // Collect all viable vectorization factors larger than the default MaxVF
5967     // (i.e. MaxVectorElementCount).
5968     SmallVector<ElementCount, 8> VFs;
5969     for (ElementCount VS = MaxVectorElementCount * 2;
5970          ElementCount::isKnownLE(VS, MaxVectorElementCountMaxBW); VS *= 2)
5971       VFs.push_back(VS);
5972 
5973     // For each VF calculate its register usage.
5974     auto RUs = calculateRegisterUsage(VFs);
5975 
5976     // Select the largest VF which doesn't require more registers than existing
5977     // ones.
5978     for (int i = RUs.size() - 1; i >= 0; --i) {
5979       bool Selected = true;
5980       for (auto &pair : RUs[i].MaxLocalUsers) {
5981         unsigned TargetNumRegisters = TTI.getNumberOfRegisters(pair.first);
5982         if (pair.second > TargetNumRegisters)
5983           Selected = false;
5984       }
5985       if (Selected) {
5986         MaxVF = VFs[i];
5987         break;
5988       }
5989     }
5990     if (ElementCount MinVF =
5991             TTI.getMinimumVF(SmallestType, ComputeScalableMaxVF)) {
5992       if (ElementCount::isKnownLT(MaxVF, MinVF)) {
5993         LLVM_DEBUG(dbgs() << "LV: Overriding calculated MaxVF(" << MaxVF
5994                           << ") with target's minimum: " << MinVF << '\n');
5995         MaxVF = MinVF;
5996       }
5997     }
5998   }
5999   return MaxVF;
6000 }
6001 
isMoreProfitable(const VectorizationFactor & A,const VectorizationFactor & B) const6002 bool LoopVectorizationCostModel::isMoreProfitable(
6003     const VectorizationFactor &A, const VectorizationFactor &B) const {
6004   InstructionCost::CostType CostA = *A.Cost.getValue();
6005   InstructionCost::CostType CostB = *B.Cost.getValue();
6006 
6007   unsigned MaxTripCount = PSE.getSE()->getSmallConstantMaxTripCount(TheLoop);
6008 
6009   if (!A.Width.isScalable() && !B.Width.isScalable() && FoldTailByMasking &&
6010       MaxTripCount) {
6011     // If we are folding the tail and the trip count is a known (possibly small)
6012     // constant, the trip count will be rounded up to an integer number of
6013     // iterations. The total cost will be PerIterationCost*ceil(TripCount/VF),
6014     // which we compare directly. When not folding the tail, the total cost will
6015     // be PerIterationCost*floor(TC/VF) + Scalar remainder cost, and so is
6016     // approximated with the per-lane cost below instead of using the tripcount
6017     // as here.
6018     int64_t RTCostA = CostA * divideCeil(MaxTripCount, A.Width.getFixedValue());
6019     int64_t RTCostB = CostB * divideCeil(MaxTripCount, B.Width.getFixedValue());
6020     return RTCostA < RTCostB;
6021   }
6022 
6023   // To avoid the need for FP division:
6024   //      (CostA / A.Width) < (CostB / B.Width)
6025   // <=>  (CostA * B.Width) < (CostB * A.Width)
6026   return (CostA * B.Width.getKnownMinValue()) <
6027          (CostB * A.Width.getKnownMinValue());
6028 }
6029 
6030 VectorizationFactor
selectVectorizationFactor(ElementCount MaxVF)6031 LoopVectorizationCostModel::selectVectorizationFactor(ElementCount MaxVF) {
6032   // FIXME: This can be fixed for scalable vectors later, because at this stage
6033   // the LoopVectorizer will only consider vectorizing a loop with scalable
6034   // vectors when the loop has a hint to enable vectorization for a given VF.
6035   assert(!MaxVF.isScalable() && "scalable vectors not yet supported");
6036 
6037   InstructionCost ExpectedCost = expectedCost(ElementCount::getFixed(1)).first;
6038   LLVM_DEBUG(dbgs() << "LV: Scalar loop costs: " << ExpectedCost << ".\n");
6039   assert(ExpectedCost.isValid() && "Unexpected invalid cost for scalar loop");
6040 
6041   const VectorizationFactor ScalarCost(ElementCount::getFixed(1), ExpectedCost);
6042   VectorizationFactor ChosenFactor = ScalarCost;
6043 
6044   bool ForceVectorization = Hints->getForce() == LoopVectorizeHints::FK_Enabled;
6045   if (ForceVectorization && MaxVF.isVector()) {
6046     // Ignore scalar width, because the user explicitly wants vectorization.
6047     // Initialize cost to max so that VF = 2 is, at least, chosen during cost
6048     // evaluation.
6049     ChosenFactor.Cost = std::numeric_limits<InstructionCost::CostType>::max();
6050   }
6051 
6052   for (auto i = ElementCount::getFixed(2); ElementCount::isKnownLE(i, MaxVF);
6053        i *= 2) {
6054     // Notice that the vector loop needs to be executed less times, so
6055     // we need to divide the cost of the vector loops by the width of
6056     // the vector elements.
6057     VectorizationCostTy C = expectedCost(i);
6058 
6059     assert(C.first.isValid() && "Unexpected invalid cost for vector loop");
6060     VectorizationFactor Candidate(i, C.first);
6061     LLVM_DEBUG(
6062         dbgs() << "LV: Vector loop of width " << i << " costs: "
6063                << (*Candidate.Cost.getValue() / Candidate.Width.getFixedValue())
6064                << ".\n");
6065 
6066     if (!C.second && !ForceVectorization) {
6067       LLVM_DEBUG(
6068           dbgs() << "LV: Not considering vector loop of width " << i
6069                  << " because it will not generate any vector instructions.\n");
6070       continue;
6071     }
6072 
6073     // If profitable add it to ProfitableVF list.
6074     if (isMoreProfitable(Candidate, ScalarCost))
6075       ProfitableVFs.push_back(Candidate);
6076 
6077     if (isMoreProfitable(Candidate, ChosenFactor))
6078       ChosenFactor = Candidate;
6079   }
6080 
6081   if (!EnableCondStoresVectorization && NumPredStores) {
6082     reportVectorizationFailure("There are conditional stores.",
6083         "store that is conditionally executed prevents vectorization",
6084         "ConditionalStore", ORE, TheLoop);
6085     ChosenFactor = ScalarCost;
6086   }
6087 
6088   LLVM_DEBUG(if (ForceVectorization && !ChosenFactor.Width.isScalar() &&
6089                  *ChosenFactor.Cost.getValue() >= *ScalarCost.Cost.getValue())
6090                  dbgs()
6091              << "LV: Vectorization seems to be not beneficial, "
6092              << "but was forced by a user.\n");
6093   LLVM_DEBUG(dbgs() << "LV: Selecting VF: " << ChosenFactor.Width << ".\n");
6094   return ChosenFactor;
6095 }
6096 
isCandidateForEpilogueVectorization(const Loop & L,ElementCount VF) const6097 bool LoopVectorizationCostModel::isCandidateForEpilogueVectorization(
6098     const Loop &L, ElementCount VF) const {
6099   // Cross iteration phis such as reductions need special handling and are
6100   // currently unsupported.
6101   if (any_of(L.getHeader()->phis(), [&](PHINode &Phi) {
6102         return Legal->isFirstOrderRecurrence(&Phi) ||
6103                Legal->isReductionVariable(&Phi);
6104       }))
6105     return false;
6106 
6107   // Phis with uses outside of the loop require special handling and are
6108   // currently unsupported.
6109   for (auto &Entry : Legal->getInductionVars()) {
6110     // Look for uses of the value of the induction at the last iteration.
6111     Value *PostInc = Entry.first->getIncomingValueForBlock(L.getLoopLatch());
6112     for (User *U : PostInc->users())
6113       if (!L.contains(cast<Instruction>(U)))
6114         return false;
6115     // Look for uses of penultimate value of the induction.
6116     for (User *U : Entry.first->users())
6117       if (!L.contains(cast<Instruction>(U)))
6118         return false;
6119   }
6120 
6121   // Induction variables that are widened require special handling that is
6122   // currently not supported.
6123   if (any_of(Legal->getInductionVars(), [&](auto &Entry) {
6124         return !(this->isScalarAfterVectorization(Entry.first, VF) ||
6125                  this->isProfitableToScalarize(Entry.first, VF));
6126       }))
6127     return false;
6128 
6129   return true;
6130 }
6131 
isEpilogueVectorizationProfitable(const ElementCount VF) const6132 bool LoopVectorizationCostModel::isEpilogueVectorizationProfitable(
6133     const ElementCount VF) const {
6134   // FIXME: We need a much better cost-model to take different parameters such
6135   // as register pressure, code size increase and cost of extra branches into
6136   // account. For now we apply a very crude heuristic and only consider loops
6137   // with vectorization factors larger than a certain value.
6138   // We also consider epilogue vectorization unprofitable for targets that don't
6139   // consider interleaving beneficial (eg. MVE).
6140   if (TTI.getMaxInterleaveFactor(VF.getKnownMinValue()) <= 1)
6141     return false;
6142   if (VF.getFixedValue() >= EpilogueVectorizationMinVF)
6143     return true;
6144   return false;
6145 }
6146 
6147 VectorizationFactor
selectEpilogueVectorizationFactor(const ElementCount MainLoopVF,const LoopVectorizationPlanner & LVP)6148 LoopVectorizationCostModel::selectEpilogueVectorizationFactor(
6149     const ElementCount MainLoopVF, const LoopVectorizationPlanner &LVP) {
6150   VectorizationFactor Result = VectorizationFactor::Disabled();
6151   if (!EnableEpilogueVectorization) {
6152     LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization is disabled.\n";);
6153     return Result;
6154   }
6155 
6156   if (!isScalarEpilogueAllowed()) {
6157     LLVM_DEBUG(
6158         dbgs() << "LEV: Unable to vectorize epilogue because no epilogue is "
6159                   "allowed.\n";);
6160     return Result;
6161   }
6162 
6163   // FIXME: This can be fixed for scalable vectors later, because at this stage
6164   // the LoopVectorizer will only consider vectorizing a loop with scalable
6165   // vectors when the loop has a hint to enable vectorization for a given VF.
6166   if (MainLoopVF.isScalable()) {
6167     LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization for scalable vectors not "
6168                          "yet supported.\n");
6169     return Result;
6170   }
6171 
6172   // Not really a cost consideration, but check for unsupported cases here to
6173   // simplify the logic.
6174   if (!isCandidateForEpilogueVectorization(*TheLoop, MainLoopVF)) {
6175     LLVM_DEBUG(
6176         dbgs() << "LEV: Unable to vectorize epilogue because the loop is "
6177                   "not a supported candidate.\n";);
6178     return Result;
6179   }
6180 
6181   if (EpilogueVectorizationForceVF > 1) {
6182     LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization factor is forced.\n";);
6183     if (LVP.hasPlanWithVFs(
6184             {MainLoopVF, ElementCount::getFixed(EpilogueVectorizationForceVF)}))
6185       return {ElementCount::getFixed(EpilogueVectorizationForceVF), 0};
6186     else {
6187       LLVM_DEBUG(
6188           dbgs()
6189               << "LEV: Epilogue vectorization forced factor is not viable.\n";);
6190       return Result;
6191     }
6192   }
6193 
6194   if (TheLoop->getHeader()->getParent()->hasOptSize() ||
6195       TheLoop->getHeader()->getParent()->hasMinSize()) {
6196     LLVM_DEBUG(
6197         dbgs()
6198             << "LEV: Epilogue vectorization skipped due to opt for size.\n";);
6199     return Result;
6200   }
6201 
6202   if (!isEpilogueVectorizationProfitable(MainLoopVF))
6203     return Result;
6204 
6205   for (auto &NextVF : ProfitableVFs)
6206     if (ElementCount::isKnownLT(NextVF.Width, MainLoopVF) &&
6207         (Result.Width.getFixedValue() == 1 ||
6208          isMoreProfitable(NextVF, Result)) &&
6209         LVP.hasPlanWithVFs({MainLoopVF, NextVF.Width}))
6210       Result = NextVF;
6211 
6212   if (Result != VectorizationFactor::Disabled())
6213     LLVM_DEBUG(dbgs() << "LEV: Vectorizing epilogue loop with VF = "
6214                       << Result.Width.getFixedValue() << "\n";);
6215   return Result;
6216 }
6217 
6218 std::pair<unsigned, unsigned>
getSmallestAndWidestTypes()6219 LoopVectorizationCostModel::getSmallestAndWidestTypes() {
6220   unsigned MinWidth = -1U;
6221   unsigned MaxWidth = 8;
6222   const DataLayout &DL = TheFunction->getParent()->getDataLayout();
6223 
6224   // For each block.
6225   for (BasicBlock *BB : TheLoop->blocks()) {
6226     // For each instruction in the loop.
6227     for (Instruction &I : BB->instructionsWithoutDebug()) {
6228       Type *T = I.getType();
6229 
6230       // Skip ignored values.
6231       if (ValuesToIgnore.count(&I))
6232         continue;
6233 
6234       // Only examine Loads, Stores and PHINodes.
6235       if (!isa<LoadInst>(I) && !isa<StoreInst>(I) && !isa<PHINode>(I))
6236         continue;
6237 
6238       // Examine PHI nodes that are reduction variables. Update the type to
6239       // account for the recurrence type.
6240       if (auto *PN = dyn_cast<PHINode>(&I)) {
6241         if (!Legal->isReductionVariable(PN))
6242           continue;
6243         RecurrenceDescriptor RdxDesc = Legal->getReductionVars()[PN];
6244         if (PreferInLoopReductions || useOrderedReductions(RdxDesc) ||
6245             TTI.preferInLoopReduction(RdxDesc.getOpcode(),
6246                                       RdxDesc.getRecurrenceType(),
6247                                       TargetTransformInfo::ReductionFlags()))
6248           continue;
6249         T = RdxDesc.getRecurrenceType();
6250       }
6251 
6252       // Examine the stored values.
6253       if (auto *ST = dyn_cast<StoreInst>(&I))
6254         T = ST->getValueOperand()->getType();
6255 
6256       // Ignore loaded pointer types and stored pointer types that are not
6257       // vectorizable.
6258       //
6259       // FIXME: The check here attempts to predict whether a load or store will
6260       //        be vectorized. We only know this for certain after a VF has
6261       //        been selected. Here, we assume that if an access can be
6262       //        vectorized, it will be. We should also look at extending this
6263       //        optimization to non-pointer types.
6264       //
6265       if (T->isPointerTy() && !isConsecutiveLoadOrStore(&I) &&
6266           !isAccessInterleaved(&I) && !isLegalGatherOrScatter(&I))
6267         continue;
6268 
6269       MinWidth = std::min(MinWidth,
6270                           (unsigned)DL.getTypeSizeInBits(T->getScalarType()));
6271       MaxWidth = std::max(MaxWidth,
6272                           (unsigned)DL.getTypeSizeInBits(T->getScalarType()));
6273     }
6274   }
6275 
6276   return {MinWidth, MaxWidth};
6277 }
6278 
selectInterleaveCount(ElementCount VF,unsigned LoopCost)6279 unsigned LoopVectorizationCostModel::selectInterleaveCount(ElementCount VF,
6280                                                            unsigned LoopCost) {
6281   // -- The interleave heuristics --
6282   // We interleave the loop in order to expose ILP and reduce the loop overhead.
6283   // There are many micro-architectural considerations that we can't predict
6284   // at this level. For example, frontend pressure (on decode or fetch) due to
6285   // code size, or the number and capabilities of the execution ports.
6286   //
6287   // We use the following heuristics to select the interleave count:
6288   // 1. If the code has reductions, then we interleave to break the cross
6289   // iteration dependency.
6290   // 2. If the loop is really small, then we interleave to reduce the loop
6291   // overhead.
6292   // 3. We don't interleave if we think that we will spill registers to memory
6293   // due to the increased register pressure.
6294 
6295   if (!isScalarEpilogueAllowed())
6296     return 1;
6297 
6298   // We used the distance for the interleave count.
6299   if (Legal->getMaxSafeDepDistBytes() != -1U)
6300     return 1;
6301 
6302   auto BestKnownTC = getSmallBestKnownTC(*PSE.getSE(), TheLoop);
6303   const bool HasReductions = !Legal->getReductionVars().empty();
6304   // Do not interleave loops with a relatively small known or estimated trip
6305   // count. But we will interleave when InterleaveSmallLoopScalarReduction is
6306   // enabled, and the code has scalar reductions(HasReductions && VF = 1),
6307   // because with the above conditions interleaving can expose ILP and break
6308   // cross iteration dependences for reductions.
6309   if (BestKnownTC && (*BestKnownTC < TinyTripCountInterleaveThreshold) &&
6310       !(InterleaveSmallLoopScalarReduction && HasReductions && VF.isScalar()))
6311     return 1;
6312 
6313   RegisterUsage R = calculateRegisterUsage({VF})[0];
6314   // We divide by these constants so assume that we have at least one
6315   // instruction that uses at least one register.
6316   for (auto& pair : R.MaxLocalUsers) {
6317     pair.second = std::max(pair.second, 1U);
6318   }
6319 
6320   // We calculate the interleave count using the following formula.
6321   // Subtract the number of loop invariants from the number of available
6322   // registers. These registers are used by all of the interleaved instances.
6323   // Next, divide the remaining registers by the number of registers that is
6324   // required by the loop, in order to estimate how many parallel instances
6325   // fit without causing spills. All of this is rounded down if necessary to be
6326   // a power of two. We want power of two interleave count to simplify any
6327   // addressing operations or alignment considerations.
6328   // We also want power of two interleave counts to ensure that the induction
6329   // variable of the vector loop wraps to zero, when tail is folded by masking;
6330   // this currently happens when OptForSize, in which case IC is set to 1 above.
6331   unsigned IC = UINT_MAX;
6332 
6333   for (auto& pair : R.MaxLocalUsers) {
6334     unsigned TargetNumRegisters = TTI.getNumberOfRegisters(pair.first);
6335     LLVM_DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters
6336                       << " registers of "
6337                       << TTI.getRegisterClassName(pair.first) << " register class\n");
6338     if (VF.isScalar()) {
6339       if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
6340         TargetNumRegisters = ForceTargetNumScalarRegs;
6341     } else {
6342       if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
6343         TargetNumRegisters = ForceTargetNumVectorRegs;
6344     }
6345     unsigned MaxLocalUsers = pair.second;
6346     unsigned LoopInvariantRegs = 0;
6347     if (R.LoopInvariantRegs.find(pair.first) != R.LoopInvariantRegs.end())
6348       LoopInvariantRegs = R.LoopInvariantRegs[pair.first];
6349 
6350     unsigned TmpIC = PowerOf2Floor((TargetNumRegisters - LoopInvariantRegs) / MaxLocalUsers);
6351     // Don't count the induction variable as interleaved.
6352     if (EnableIndVarRegisterHeur) {
6353       TmpIC =
6354           PowerOf2Floor((TargetNumRegisters - LoopInvariantRegs - 1) /
6355                         std::max(1U, (MaxLocalUsers - 1)));
6356     }
6357 
6358     IC = std::min(IC, TmpIC);
6359   }
6360 
6361   // Clamp the interleave ranges to reasonable counts.
6362   unsigned MaxInterleaveCount =
6363       TTI.getMaxInterleaveFactor(VF.getKnownMinValue());
6364 
6365   // Check if the user has overridden the max.
6366   if (VF.isScalar()) {
6367     if (ForceTargetMaxScalarInterleaveFactor.getNumOccurrences() > 0)
6368       MaxInterleaveCount = ForceTargetMaxScalarInterleaveFactor;
6369   } else {
6370     if (ForceTargetMaxVectorInterleaveFactor.getNumOccurrences() > 0)
6371       MaxInterleaveCount = ForceTargetMaxVectorInterleaveFactor;
6372   }
6373 
6374   // If trip count is known or estimated compile time constant, limit the
6375   // interleave count to be less than the trip count divided by VF, provided it
6376   // is at least 1.
6377   //
6378   // For scalable vectors we can't know if interleaving is beneficial. It may
6379   // not be beneficial for small loops if none of the lanes in the second vector
6380   // iterations is enabled. However, for larger loops, there is likely to be a
6381   // similar benefit as for fixed-width vectors. For now, we choose to leave
6382   // the InterleaveCount as if vscale is '1', although if some information about
6383   // the vector is known (e.g. min vector size), we can make a better decision.
6384   if (BestKnownTC) {
6385     MaxInterleaveCount =
6386         std::min(*BestKnownTC / VF.getKnownMinValue(), MaxInterleaveCount);
6387     // Make sure MaxInterleaveCount is greater than 0.
6388     MaxInterleaveCount = std::max(1u, MaxInterleaveCount);
6389   }
6390 
6391   assert(MaxInterleaveCount > 0 &&
6392          "Maximum interleave count must be greater than 0");
6393 
6394   // Clamp the calculated IC to be between the 1 and the max interleave count
6395   // that the target and trip count allows.
6396   if (IC > MaxInterleaveCount)
6397     IC = MaxInterleaveCount;
6398   else
6399     // Make sure IC is greater than 0.
6400     IC = std::max(1u, IC);
6401 
6402   assert(IC > 0 && "Interleave count must be greater than 0.");
6403 
6404   // If we did not calculate the cost for VF (because the user selected the VF)
6405   // then we calculate the cost of VF here.
6406   if (LoopCost == 0) {
6407     assert(expectedCost(VF).first.isValid() && "Expected a valid cost");
6408     LoopCost = *expectedCost(VF).first.getValue();
6409   }
6410 
6411   assert(LoopCost && "Non-zero loop cost expected");
6412 
6413   // Interleave if we vectorized this loop and there is a reduction that could
6414   // benefit from interleaving.
6415   if (VF.isVector() && HasReductions) {
6416     LLVM_DEBUG(dbgs() << "LV: Interleaving because of reductions.\n");
6417     return IC;
6418   }
6419 
6420   // Note that if we've already vectorized the loop we will have done the
6421   // runtime check and so interleaving won't require further checks.
6422   bool InterleavingRequiresRuntimePointerCheck =
6423       (VF.isScalar() && Legal->getRuntimePointerChecking()->Need);
6424 
6425   // We want to interleave small loops in order to reduce the loop overhead and
6426   // potentially expose ILP opportunities.
6427   LLVM_DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n'
6428                     << "LV: IC is " << IC << '\n'
6429                     << "LV: VF is " << VF << '\n');
6430   const bool AggressivelyInterleaveReductions =
6431       TTI.enableAggressiveInterleaving(HasReductions);
6432   if (!InterleavingRequiresRuntimePointerCheck && LoopCost < SmallLoopCost) {
6433     // We assume that the cost overhead is 1 and we use the cost model
6434     // to estimate the cost of the loop and interleave until the cost of the
6435     // loop overhead is about 5% of the cost of the loop.
6436     unsigned SmallIC =
6437         std::min(IC, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost));
6438 
6439     // Interleave until store/load ports (estimated by max interleave count) are
6440     // saturated.
6441     unsigned NumStores = Legal->getNumStores();
6442     unsigned NumLoads = Legal->getNumLoads();
6443     unsigned StoresIC = IC / (NumStores ? NumStores : 1);
6444     unsigned LoadsIC = IC / (NumLoads ? NumLoads : 1);
6445 
6446     // If we have a scalar reduction (vector reductions are already dealt with
6447     // by this point), we can increase the critical path length if the loop
6448     // we're interleaving is inside another loop. Limit, by default to 2, so the
6449     // critical path only gets increased by one reduction operation.
6450     if (HasReductions && TheLoop->getLoopDepth() > 1) {
6451       unsigned F = static_cast<unsigned>(MaxNestedScalarReductionIC);
6452       SmallIC = std::min(SmallIC, F);
6453       StoresIC = std::min(StoresIC, F);
6454       LoadsIC = std::min(LoadsIC, F);
6455     }
6456 
6457     if (EnableLoadStoreRuntimeInterleave &&
6458         std::max(StoresIC, LoadsIC) > SmallIC) {
6459       LLVM_DEBUG(
6460           dbgs() << "LV: Interleaving to saturate store or load ports.\n");
6461       return std::max(StoresIC, LoadsIC);
6462     }
6463 
6464     // If there are scalar reductions and TTI has enabled aggressive
6465     // interleaving for reductions, we will interleave to expose ILP.
6466     if (InterleaveSmallLoopScalarReduction && VF.isScalar() &&
6467         AggressivelyInterleaveReductions) {
6468       LLVM_DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
6469       // Interleave no less than SmallIC but not as aggressive as the normal IC
6470       // to satisfy the rare situation when resources are too limited.
6471       return std::max(IC / 2, SmallIC);
6472     } else {
6473       LLVM_DEBUG(dbgs() << "LV: Interleaving to reduce branch cost.\n");
6474       return SmallIC;
6475     }
6476   }
6477 
6478   // Interleave if this is a large loop (small loops are already dealt with by
6479   // this point) that could benefit from interleaving.
6480   if (AggressivelyInterleaveReductions) {
6481     LLVM_DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
6482     return IC;
6483   }
6484 
6485   LLVM_DEBUG(dbgs() << "LV: Not Interleaving.\n");
6486   return 1;
6487 }
6488 
6489 SmallVector<LoopVectorizationCostModel::RegisterUsage, 8>
calculateRegisterUsage(ArrayRef<ElementCount> VFs)6490 LoopVectorizationCostModel::calculateRegisterUsage(ArrayRef<ElementCount> VFs) {
6491   // This function calculates the register usage by measuring the highest number
6492   // of values that are alive at a single location. Obviously, this is a very
6493   // rough estimation. We scan the loop in a topological order in order and
6494   // assign a number to each instruction. We use RPO to ensure that defs are
6495   // met before their users. We assume that each instruction that has in-loop
6496   // users starts an interval. We record every time that an in-loop value is
6497   // used, so we have a list of the first and last occurrences of each
6498   // instruction. Next, we transpose this data structure into a multi map that
6499   // holds the list of intervals that *end* at a specific location. This multi
6500   // map allows us to perform a linear search. We scan the instructions linearly
6501   // and record each time that a new interval starts, by placing it in a set.
6502   // If we find this value in the multi-map then we remove it from the set.
6503   // The max register usage is the maximum size of the set.
6504   // We also search for instructions that are defined outside the loop, but are
6505   // used inside the loop. We need this number separately from the max-interval
6506   // usage number because when we unroll, loop-invariant values do not take
6507   // more register.
6508   LoopBlocksDFS DFS(TheLoop);
6509   DFS.perform(LI);
6510 
6511   RegisterUsage RU;
6512 
6513   // Each 'key' in the map opens a new interval. The values
6514   // of the map are the index of the 'last seen' usage of the
6515   // instruction that is the key.
6516   using IntervalMap = DenseMap<Instruction *, unsigned>;
6517 
6518   // Maps instruction to its index.
6519   SmallVector<Instruction *, 64> IdxToInstr;
6520   // Marks the end of each interval.
6521   IntervalMap EndPoint;
6522   // Saves the list of instruction indices that are used in the loop.
6523   SmallPtrSet<Instruction *, 8> Ends;
6524   // Saves the list of values that are used in the loop but are
6525   // defined outside the loop, such as arguments and constants.
6526   SmallPtrSet<Value *, 8> LoopInvariants;
6527 
6528   for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) {
6529     for (Instruction &I : BB->instructionsWithoutDebug()) {
6530       IdxToInstr.push_back(&I);
6531 
6532       // Save the end location of each USE.
6533       for (Value *U : I.operands()) {
6534         auto *Instr = dyn_cast<Instruction>(U);
6535 
6536         // Ignore non-instruction values such as arguments, constants, etc.
6537         if (!Instr)
6538           continue;
6539 
6540         // If this instruction is outside the loop then record it and continue.
6541         if (!TheLoop->contains(Instr)) {
6542           LoopInvariants.insert(Instr);
6543           continue;
6544         }
6545 
6546         // Overwrite previous end points.
6547         EndPoint[Instr] = IdxToInstr.size();
6548         Ends.insert(Instr);
6549       }
6550     }
6551   }
6552 
6553   // Saves the list of intervals that end with the index in 'key'.
6554   using InstrList = SmallVector<Instruction *, 2>;
6555   DenseMap<unsigned, InstrList> TransposeEnds;
6556 
6557   // Transpose the EndPoints to a list of values that end at each index.
6558   for (auto &Interval : EndPoint)
6559     TransposeEnds[Interval.second].push_back(Interval.first);
6560 
6561   SmallPtrSet<Instruction *, 8> OpenIntervals;
6562   SmallVector<RegisterUsage, 8> RUs(VFs.size());
6563   SmallVector<SmallMapVector<unsigned, unsigned, 4>, 8> MaxUsages(VFs.size());
6564 
6565   LLVM_DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
6566 
6567   // A lambda that gets the register usage for the given type and VF.
6568   const auto &TTICapture = TTI;
6569   auto GetRegUsage = [&TTICapture](Type *Ty, ElementCount VF) {
6570     if (Ty->isTokenTy() || !VectorType::isValidElementType(Ty))
6571       return 0;
6572     return *TTICapture.getRegUsageForType(VectorType::get(Ty, VF)).getValue();
6573   };
6574 
6575   for (unsigned int i = 0, s = IdxToInstr.size(); i < s; ++i) {
6576     Instruction *I = IdxToInstr[i];
6577 
6578     // Remove all of the instructions that end at this location.
6579     InstrList &List = TransposeEnds[i];
6580     for (Instruction *ToRemove : List)
6581       OpenIntervals.erase(ToRemove);
6582 
6583     // Ignore instructions that are never used within the loop.
6584     if (!Ends.count(I))
6585       continue;
6586 
6587     // Skip ignored values.
6588     if (ValuesToIgnore.count(I))
6589       continue;
6590 
6591     // For each VF find the maximum usage of registers.
6592     for (unsigned j = 0, e = VFs.size(); j < e; ++j) {
6593       // Count the number of live intervals.
6594       SmallMapVector<unsigned, unsigned, 4> RegUsage;
6595 
6596       if (VFs[j].isScalar()) {
6597         for (auto Inst : OpenIntervals) {
6598           unsigned ClassID = TTI.getRegisterClassForType(false, Inst->getType());
6599           if (RegUsage.find(ClassID) == RegUsage.end())
6600             RegUsage[ClassID] = 1;
6601           else
6602             RegUsage[ClassID] += 1;
6603         }
6604       } else {
6605         collectUniformsAndScalars(VFs[j]);
6606         for (auto Inst : OpenIntervals) {
6607           // Skip ignored values for VF > 1.
6608           if (VecValuesToIgnore.count(Inst))
6609             continue;
6610           if (isScalarAfterVectorization(Inst, VFs[j])) {
6611             unsigned ClassID = TTI.getRegisterClassForType(false, Inst->getType());
6612             if (RegUsage.find(ClassID) == RegUsage.end())
6613               RegUsage[ClassID] = 1;
6614             else
6615               RegUsage[ClassID] += 1;
6616           } else {
6617             unsigned ClassID = TTI.getRegisterClassForType(true, Inst->getType());
6618             if (RegUsage.find(ClassID) == RegUsage.end())
6619               RegUsage[ClassID] = GetRegUsage(Inst->getType(), VFs[j]);
6620             else
6621               RegUsage[ClassID] += GetRegUsage(Inst->getType(), VFs[j]);
6622           }
6623         }
6624       }
6625 
6626       for (auto& pair : RegUsage) {
6627         if (MaxUsages[j].find(pair.first) != MaxUsages[j].end())
6628           MaxUsages[j][pair.first] = std::max(MaxUsages[j][pair.first], pair.second);
6629         else
6630           MaxUsages[j][pair.first] = pair.second;
6631       }
6632     }
6633 
6634     LLVM_DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # "
6635                       << OpenIntervals.size() << '\n');
6636 
6637     // Add the current instruction to the list of open intervals.
6638     OpenIntervals.insert(I);
6639   }
6640 
6641   for (unsigned i = 0, e = VFs.size(); i < e; ++i) {
6642     SmallMapVector<unsigned, unsigned, 4> Invariant;
6643 
6644     for (auto Inst : LoopInvariants) {
6645       unsigned Usage =
6646           VFs[i].isScalar() ? 1 : GetRegUsage(Inst->getType(), VFs[i]);
6647       unsigned ClassID =
6648           TTI.getRegisterClassForType(VFs[i].isVector(), Inst->getType());
6649       if (Invariant.find(ClassID) == Invariant.end())
6650         Invariant[ClassID] = Usage;
6651       else
6652         Invariant[ClassID] += Usage;
6653     }
6654 
6655     LLVM_DEBUG({
6656       dbgs() << "LV(REG): VF = " << VFs[i] << '\n';
6657       dbgs() << "LV(REG): Found max usage: " << MaxUsages[i].size()
6658              << " item\n";
6659       for (const auto &pair : MaxUsages[i]) {
6660         dbgs() << "LV(REG): RegisterClass: "
6661                << TTI.getRegisterClassName(pair.first) << ", " << pair.second
6662                << " registers\n";
6663       }
6664       dbgs() << "LV(REG): Found invariant usage: " << Invariant.size()
6665              << " item\n";
6666       for (const auto &pair : Invariant) {
6667         dbgs() << "LV(REG): RegisterClass: "
6668                << TTI.getRegisterClassName(pair.first) << ", " << pair.second
6669                << " registers\n";
6670       }
6671     });
6672 
6673     RU.LoopInvariantRegs = Invariant;
6674     RU.MaxLocalUsers = MaxUsages[i];
6675     RUs[i] = RU;
6676   }
6677 
6678   return RUs;
6679 }
6680 
useEmulatedMaskMemRefHack(Instruction * I)6681 bool LoopVectorizationCostModel::useEmulatedMaskMemRefHack(Instruction *I){
6682   // TODO: Cost model for emulated masked load/store is completely
6683   // broken. This hack guides the cost model to use an artificially
6684   // high enough value to practically disable vectorization with such
6685   // operations, except where previously deployed legality hack allowed
6686   // using very low cost values. This is to avoid regressions coming simply
6687   // from moving "masked load/store" check from legality to cost model.
6688   // Masked Load/Gather emulation was previously never allowed.
6689   // Limited number of Masked Store/Scatter emulation was allowed.
6690   assert(isPredicatedInst(I) &&
6691          "Expecting a scalar emulated instruction");
6692   return isa<LoadInst>(I) ||
6693          (isa<StoreInst>(I) &&
6694           NumPredStores > NumberOfStoresToPredicate);
6695 }
6696 
collectInstsToScalarize(ElementCount VF)6697 void LoopVectorizationCostModel::collectInstsToScalarize(ElementCount VF) {
6698   // If we aren't vectorizing the loop, or if we've already collected the
6699   // instructions to scalarize, there's nothing to do. Collection may already
6700   // have occurred if we have a user-selected VF and are now computing the
6701   // expected cost for interleaving.
6702   if (VF.isScalar() || VF.isZero() ||
6703       InstsToScalarize.find(VF) != InstsToScalarize.end())
6704     return;
6705 
6706   // Initialize a mapping for VF in InstsToScalalarize. If we find that it's
6707   // not profitable to scalarize any instructions, the presence of VF in the
6708   // map will indicate that we've analyzed it already.
6709   ScalarCostsTy &ScalarCostsVF = InstsToScalarize[VF];
6710 
6711   // Find all the instructions that are scalar with predication in the loop and
6712   // determine if it would be better to not if-convert the blocks they are in.
6713   // If so, we also record the instructions to scalarize.
6714   for (BasicBlock *BB : TheLoop->blocks()) {
6715     if (!blockNeedsPredication(BB))
6716       continue;
6717     for (Instruction &I : *BB)
6718       if (isScalarWithPredication(&I)) {
6719         ScalarCostsTy ScalarCosts;
6720         // Do not apply discount logic if hacked cost is needed
6721         // for emulated masked memrefs.
6722         if (!useEmulatedMaskMemRefHack(&I) &&
6723             computePredInstDiscount(&I, ScalarCosts, VF) >= 0)
6724           ScalarCostsVF.insert(ScalarCosts.begin(), ScalarCosts.end());
6725         // Remember that BB will remain after vectorization.
6726         PredicatedBBsAfterVectorization.insert(BB);
6727       }
6728   }
6729 }
6730 
computePredInstDiscount(Instruction * PredInst,ScalarCostsTy & ScalarCosts,ElementCount VF)6731 int LoopVectorizationCostModel::computePredInstDiscount(
6732     Instruction *PredInst, ScalarCostsTy &ScalarCosts, ElementCount VF) {
6733   assert(!isUniformAfterVectorization(PredInst, VF) &&
6734          "Instruction marked uniform-after-vectorization will be predicated");
6735 
6736   // Initialize the discount to zero, meaning that the scalar version and the
6737   // vector version cost the same.
6738   InstructionCost Discount = 0;
6739 
6740   // Holds instructions to analyze. The instructions we visit are mapped in
6741   // ScalarCosts. Those instructions are the ones that would be scalarized if
6742   // we find that the scalar version costs less.
6743   SmallVector<Instruction *, 8> Worklist;
6744 
6745   // Returns true if the given instruction can be scalarized.
6746   auto canBeScalarized = [&](Instruction *I) -> bool {
6747     // We only attempt to scalarize instructions forming a single-use chain
6748     // from the original predicated block that would otherwise be vectorized.
6749     // Although not strictly necessary, we give up on instructions we know will
6750     // already be scalar to avoid traversing chains that are unlikely to be
6751     // beneficial.
6752     if (!I->hasOneUse() || PredInst->getParent() != I->getParent() ||
6753         isScalarAfterVectorization(I, VF))
6754       return false;
6755 
6756     // If the instruction is scalar with predication, it will be analyzed
6757     // separately. We ignore it within the context of PredInst.
6758     if (isScalarWithPredication(I))
6759       return false;
6760 
6761     // If any of the instruction's operands are uniform after vectorization,
6762     // the instruction cannot be scalarized. This prevents, for example, a
6763     // masked load from being scalarized.
6764     //
6765     // We assume we will only emit a value for lane zero of an instruction
6766     // marked uniform after vectorization, rather than VF identical values.
6767     // Thus, if we scalarize an instruction that uses a uniform, we would
6768     // create uses of values corresponding to the lanes we aren't emitting code
6769     // for. This behavior can be changed by allowing getScalarValue to clone
6770     // the lane zero values for uniforms rather than asserting.
6771     for (Use &U : I->operands())
6772       if (auto *J = dyn_cast<Instruction>(U.get()))
6773         if (isUniformAfterVectorization(J, VF))
6774           return false;
6775 
6776     // Otherwise, we can scalarize the instruction.
6777     return true;
6778   };
6779 
6780   // Compute the expected cost discount from scalarizing the entire expression
6781   // feeding the predicated instruction. We currently only consider expressions
6782   // that are single-use instruction chains.
6783   Worklist.push_back(PredInst);
6784   while (!Worklist.empty()) {
6785     Instruction *I = Worklist.pop_back_val();
6786 
6787     // If we've already analyzed the instruction, there's nothing to do.
6788     if (ScalarCosts.find(I) != ScalarCosts.end())
6789       continue;
6790 
6791     // Compute the cost of the vector instruction. Note that this cost already
6792     // includes the scalarization overhead of the predicated instruction.
6793     InstructionCost VectorCost = getInstructionCost(I, VF).first;
6794 
6795     // Compute the cost of the scalarized instruction. This cost is the cost of
6796     // the instruction as if it wasn't if-converted and instead remained in the
6797     // predicated block. We will scale this cost by block probability after
6798     // computing the scalarization overhead.
6799     assert(!VF.isScalable() && "scalable vectors not yet supported.");
6800     InstructionCost ScalarCost =
6801         VF.getKnownMinValue() *
6802         getInstructionCost(I, ElementCount::getFixed(1)).first;
6803 
6804     // Compute the scalarization overhead of needed insertelement instructions
6805     // and phi nodes.
6806     if (isScalarWithPredication(I) && !I->getType()->isVoidTy()) {
6807       ScalarCost += TTI.getScalarizationOverhead(
6808           cast<VectorType>(ToVectorTy(I->getType(), VF)),
6809           APInt::getAllOnesValue(VF.getKnownMinValue()), true, false);
6810       assert(!VF.isScalable() && "scalable vectors not yet supported.");
6811       ScalarCost +=
6812           VF.getKnownMinValue() *
6813           TTI.getCFInstrCost(Instruction::PHI, TTI::TCK_RecipThroughput);
6814     }
6815 
6816     // Compute the scalarization overhead of needed extractelement
6817     // instructions. For each of the instruction's operands, if the operand can
6818     // be scalarized, add it to the worklist; otherwise, account for the
6819     // overhead.
6820     for (Use &U : I->operands())
6821       if (auto *J = dyn_cast<Instruction>(U.get())) {
6822         assert(VectorType::isValidElementType(J->getType()) &&
6823                "Instruction has non-scalar type");
6824         if (canBeScalarized(J))
6825           Worklist.push_back(J);
6826         else if (needsExtract(J, VF)) {
6827           assert(!VF.isScalable() && "scalable vectors not yet supported.");
6828           ScalarCost += TTI.getScalarizationOverhead(
6829               cast<VectorType>(ToVectorTy(J->getType(), VF)),
6830               APInt::getAllOnesValue(VF.getKnownMinValue()), false, true);
6831         }
6832       }
6833 
6834     // Scale the total scalar cost by block probability.
6835     ScalarCost /= getReciprocalPredBlockProb();
6836 
6837     // Compute the discount. A non-negative discount means the vector version
6838     // of the instruction costs more, and scalarizing would be beneficial.
6839     Discount += VectorCost - ScalarCost;
6840     ScalarCosts[I] = ScalarCost;
6841   }
6842 
6843   return *Discount.getValue();
6844 }
6845 
6846 LoopVectorizationCostModel::VectorizationCostTy
expectedCost(ElementCount VF)6847 LoopVectorizationCostModel::expectedCost(ElementCount VF) {
6848   VectorizationCostTy Cost;
6849 
6850   // For each block.
6851   for (BasicBlock *BB : TheLoop->blocks()) {
6852     VectorizationCostTy BlockCost;
6853 
6854     // For each instruction in the old loop.
6855     for (Instruction &I : BB->instructionsWithoutDebug()) {
6856       // Skip ignored values.
6857       if (ValuesToIgnore.count(&I) ||
6858           (VF.isVector() && VecValuesToIgnore.count(&I)))
6859         continue;
6860 
6861       VectorizationCostTy C = getInstructionCost(&I, VF);
6862 
6863       // Check if we should override the cost.
6864       if (ForceTargetInstructionCost.getNumOccurrences() > 0)
6865         C.first = InstructionCost(ForceTargetInstructionCost);
6866 
6867       BlockCost.first += C.first;
6868       BlockCost.second |= C.second;
6869       LLVM_DEBUG(dbgs() << "LV: Found an estimated cost of " << C.first
6870                         << " for VF " << VF << " For instruction: " << I
6871                         << '\n');
6872     }
6873 
6874     // If we are vectorizing a predicated block, it will have been
6875     // if-converted. This means that the block's instructions (aside from
6876     // stores and instructions that may divide by zero) will now be
6877     // unconditionally executed. For the scalar case, we may not always execute
6878     // the predicated block, if it is an if-else block. Thus, scale the block's
6879     // cost by the probability of executing it. blockNeedsPredication from
6880     // Legal is used so as to not include all blocks in tail folded loops.
6881     if (VF.isScalar() && Legal->blockNeedsPredication(BB))
6882       BlockCost.first /= getReciprocalPredBlockProb();
6883 
6884     Cost.first += BlockCost.first;
6885     Cost.second |= BlockCost.second;
6886   }
6887 
6888   return Cost;
6889 }
6890 
6891 /// Gets Address Access SCEV after verifying that the access pattern
6892 /// is loop invariant except the induction variable dependence.
6893 ///
6894 /// This SCEV can be sent to the Target in order to estimate the address
6895 /// calculation cost.
getAddressAccessSCEV(Value * Ptr,LoopVectorizationLegality * Legal,PredicatedScalarEvolution & PSE,const Loop * TheLoop)6896 static const SCEV *getAddressAccessSCEV(
6897               Value *Ptr,
6898               LoopVectorizationLegality *Legal,
6899               PredicatedScalarEvolution &PSE,
6900               const Loop *TheLoop) {
6901 
6902   auto *Gep = dyn_cast<GetElementPtrInst>(Ptr);
6903   if (!Gep)
6904     return nullptr;
6905 
6906   // We are looking for a gep with all loop invariant indices except for one
6907   // which should be an induction variable.
6908   auto SE = PSE.getSE();
6909   unsigned NumOperands = Gep->getNumOperands();
6910   for (unsigned i = 1; i < NumOperands; ++i) {
6911     Value *Opd = Gep->getOperand(i);
6912     if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
6913         !Legal->isInductionVariable(Opd))
6914       return nullptr;
6915   }
6916 
6917   // Now we know we have a GEP ptr, %inv, %ind, %inv. return the Ptr SCEV.
6918   return PSE.getSCEV(Ptr);
6919 }
6920 
isStrideMul(Instruction * I,LoopVectorizationLegality * Legal)6921 static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
6922   return Legal->hasStride(I->getOperand(0)) ||
6923          Legal->hasStride(I->getOperand(1));
6924 }
6925 
6926 InstructionCost
getMemInstScalarizationCost(Instruction * I,ElementCount VF)6927 LoopVectorizationCostModel::getMemInstScalarizationCost(Instruction *I,
6928                                                         ElementCount VF) {
6929   assert(VF.isVector() &&
6930          "Scalarization cost of instruction implies vectorization.");
6931   if (VF.isScalable())
6932     return InstructionCost::getInvalid();
6933 
6934   Type *ValTy = getMemInstValueType(I);
6935   auto SE = PSE.getSE();
6936 
6937   unsigned AS = getLoadStoreAddressSpace(I);
6938   Value *Ptr = getLoadStorePointerOperand(I);
6939   Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
6940 
6941   // Figure out whether the access is strided and get the stride value
6942   // if it's known in compile time
6943   const SCEV *PtrSCEV = getAddressAccessSCEV(Ptr, Legal, PSE, TheLoop);
6944 
6945   // Get the cost of the scalar memory instruction and address computation.
6946   InstructionCost Cost =
6947       VF.getKnownMinValue() * TTI.getAddressComputationCost(PtrTy, SE, PtrSCEV);
6948 
6949   // Don't pass *I here, since it is scalar but will actually be part of a
6950   // vectorized loop where the user of it is a vectorized instruction.
6951   const Align Alignment = getLoadStoreAlignment(I);
6952   Cost += VF.getKnownMinValue() *
6953           TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(), Alignment,
6954                               AS, TTI::TCK_RecipThroughput);
6955 
6956   // Get the overhead of the extractelement and insertelement instructions
6957   // we might create due to scalarization.
6958   Cost += getScalarizationOverhead(I, VF);
6959 
6960   // If we have a predicated load/store, it will need extra i1 extracts and
6961   // conditional branches, but may not be executed for each vector lane. Scale
6962   // the cost by the probability of executing the predicated block.
6963   if (isPredicatedInst(I)) {
6964     Cost /= getReciprocalPredBlockProb();
6965 
6966     // Add the cost of an i1 extract and a branch
6967     auto *Vec_i1Ty =
6968         VectorType::get(IntegerType::getInt1Ty(ValTy->getContext()), VF);
6969     Cost += TTI.getScalarizationOverhead(
6970         Vec_i1Ty, APInt::getAllOnesValue(VF.getKnownMinValue()),
6971         /*Insert=*/false, /*Extract=*/true);
6972     Cost += TTI.getCFInstrCost(Instruction::Br, TTI::TCK_RecipThroughput);
6973 
6974     if (useEmulatedMaskMemRefHack(I))
6975       // Artificially setting to a high enough value to practically disable
6976       // vectorization with such operations.
6977       Cost = 3000000;
6978   }
6979 
6980   return Cost;
6981 }
6982 
6983 InstructionCost
getConsecutiveMemOpCost(Instruction * I,ElementCount VF)6984 LoopVectorizationCostModel::getConsecutiveMemOpCost(Instruction *I,
6985                                                     ElementCount VF) {
6986   Type *ValTy = getMemInstValueType(I);
6987   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
6988   Value *Ptr = getLoadStorePointerOperand(I);
6989   unsigned AS = getLoadStoreAddressSpace(I);
6990   int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
6991   enum TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
6992 
6993   assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
6994          "Stride should be 1 or -1 for consecutive memory access");
6995   const Align Alignment = getLoadStoreAlignment(I);
6996   InstructionCost Cost = 0;
6997   if (Legal->isMaskRequired(I))
6998     Cost += TTI.getMaskedMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS,
6999                                       CostKind);
7000   else
7001     Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS,
7002                                 CostKind, I);
7003 
7004   bool Reverse = ConsecutiveStride < 0;
7005   if (Reverse)
7006     Cost +=
7007         TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, None, 0);
7008   return Cost;
7009 }
7010 
7011 InstructionCost
getUniformMemOpCost(Instruction * I,ElementCount VF)7012 LoopVectorizationCostModel::getUniformMemOpCost(Instruction *I,
7013                                                 ElementCount VF) {
7014   assert(Legal->isUniformMemOp(*I));
7015 
7016   Type *ValTy = getMemInstValueType(I);
7017   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
7018   const Align Alignment = getLoadStoreAlignment(I);
7019   unsigned AS = getLoadStoreAddressSpace(I);
7020   enum TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
7021   if (isa<LoadInst>(I)) {
7022     return TTI.getAddressComputationCost(ValTy) +
7023            TTI.getMemoryOpCost(Instruction::Load, ValTy, Alignment, AS,
7024                                CostKind) +
7025            TTI.getShuffleCost(TargetTransformInfo::SK_Broadcast, VectorTy);
7026   }
7027   StoreInst *SI = cast<StoreInst>(I);
7028 
7029   bool isLoopInvariantStoreValue = Legal->isUniform(SI->getValueOperand());
7030   return TTI.getAddressComputationCost(ValTy) +
7031          TTI.getMemoryOpCost(Instruction::Store, ValTy, Alignment, AS,
7032                              CostKind) +
7033          (isLoopInvariantStoreValue
7034               ? 0
7035               : TTI.getVectorInstrCost(Instruction::ExtractElement, VectorTy,
7036                                        VF.getKnownMinValue() - 1));
7037 }
7038 
7039 InstructionCost
getGatherScatterCost(Instruction * I,ElementCount VF)7040 LoopVectorizationCostModel::getGatherScatterCost(Instruction *I,
7041                                                  ElementCount VF) {
7042   Type *ValTy = getMemInstValueType(I);
7043   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
7044   const Align Alignment = getLoadStoreAlignment(I);
7045   const Value *Ptr = getLoadStorePointerOperand(I);
7046 
7047   return TTI.getAddressComputationCost(VectorTy) +
7048          TTI.getGatherScatterOpCost(
7049              I->getOpcode(), VectorTy, Ptr, Legal->isMaskRequired(I), Alignment,
7050              TargetTransformInfo::TCK_RecipThroughput, I);
7051 }
7052 
7053 InstructionCost
getInterleaveGroupCost(Instruction * I,ElementCount VF)7054 LoopVectorizationCostModel::getInterleaveGroupCost(Instruction *I,
7055                                                    ElementCount VF) {
7056   // TODO: Once we have support for interleaving with scalable vectors
7057   // we can calculate the cost properly here.
7058   if (VF.isScalable())
7059     return InstructionCost::getInvalid();
7060 
7061   Type *ValTy = getMemInstValueType(I);
7062   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
7063   unsigned AS = getLoadStoreAddressSpace(I);
7064 
7065   auto Group = getInterleavedAccessGroup(I);
7066   assert(Group && "Fail to get an interleaved access group.");
7067 
7068   unsigned InterleaveFactor = Group->getFactor();
7069   auto *WideVecTy = VectorType::get(ValTy, VF * InterleaveFactor);
7070 
7071   // Holds the indices of existing members in an interleaved load group.
7072   // An interleaved store group doesn't need this as it doesn't allow gaps.
7073   SmallVector<unsigned, 4> Indices;
7074   if (isa<LoadInst>(I)) {
7075     for (unsigned i = 0; i < InterleaveFactor; i++)
7076       if (Group->getMember(i))
7077         Indices.push_back(i);
7078   }
7079 
7080   // Calculate the cost of the whole interleaved group.
7081   bool UseMaskForGaps =
7082       Group->requiresScalarEpilogue() && !isScalarEpilogueAllowed();
7083   InstructionCost Cost = TTI.getInterleavedMemoryOpCost(
7084       I->getOpcode(), WideVecTy, Group->getFactor(), Indices, Group->getAlign(),
7085       AS, TTI::TCK_RecipThroughput, Legal->isMaskRequired(I), UseMaskForGaps);
7086 
7087   if (Group->isReverse()) {
7088     // TODO: Add support for reversed masked interleaved access.
7089     assert(!Legal->isMaskRequired(I) &&
7090            "Reverse masked interleaved access not supported.");
7091     Cost +=
7092         Group->getNumMembers() *
7093         TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, None, 0);
7094   }
7095   return Cost;
7096 }
7097 
getReductionPatternCost(Instruction * I,ElementCount VF,Type * Ty,TTI::TargetCostKind CostKind)7098 InstructionCost LoopVectorizationCostModel::getReductionPatternCost(
7099     Instruction *I, ElementCount VF, Type *Ty, TTI::TargetCostKind CostKind) {
7100   // Early exit for no inloop reductions
7101   if (InLoopReductionChains.empty() || VF.isScalar() || !isa<VectorType>(Ty))
7102     return InstructionCost::getInvalid();
7103   auto *VectorTy = cast<VectorType>(Ty);
7104 
7105   // We are looking for a pattern of, and finding the minimal acceptable cost:
7106   //  reduce(mul(ext(A), ext(B))) or
7107   //  reduce(mul(A, B)) or
7108   //  reduce(ext(A)) or
7109   //  reduce(A).
7110   // The basic idea is that we walk down the tree to do that, finding the root
7111   // reduction instruction in InLoopReductionImmediateChains. From there we find
7112   // the pattern of mul/ext and test the cost of the entire pattern vs the cost
7113   // of the components. If the reduction cost is lower then we return it for the
7114   // reduction instruction and 0 for the other instructions in the pattern. If
7115   // it is not we return an invalid cost specifying the orignal cost method
7116   // should be used.
7117   Instruction *RetI = I;
7118   if ((RetI->getOpcode() == Instruction::SExt ||
7119        RetI->getOpcode() == Instruction::ZExt)) {
7120     if (!RetI->hasOneUser())
7121       return InstructionCost::getInvalid();
7122     RetI = RetI->user_back();
7123   }
7124   if (RetI->getOpcode() == Instruction::Mul &&
7125       RetI->user_back()->getOpcode() == Instruction::Add) {
7126     if (!RetI->hasOneUser())
7127       return InstructionCost::getInvalid();
7128     RetI = RetI->user_back();
7129   }
7130 
7131   // Test if the found instruction is a reduction, and if not return an invalid
7132   // cost specifying the parent to use the original cost modelling.
7133   if (!InLoopReductionImmediateChains.count(RetI))
7134     return InstructionCost::getInvalid();
7135 
7136   // Find the reduction this chain is a part of and calculate the basic cost of
7137   // the reduction on its own.
7138   Instruction *LastChain = InLoopReductionImmediateChains[RetI];
7139   Instruction *ReductionPhi = LastChain;
7140   while (!isa<PHINode>(ReductionPhi))
7141     ReductionPhi = InLoopReductionImmediateChains[ReductionPhi];
7142 
7143   RecurrenceDescriptor RdxDesc =
7144       Legal->getReductionVars()[cast<PHINode>(ReductionPhi)];
7145   InstructionCost BaseCost = TTI.getArithmeticReductionCost(
7146       RdxDesc.getOpcode(), VectorTy, false, CostKind);
7147 
7148   // Get the operand that was not the reduction chain and match it to one of the
7149   // patterns, returning the better cost if it is found.
7150   Instruction *RedOp = RetI->getOperand(1) == LastChain
7151                            ? dyn_cast<Instruction>(RetI->getOperand(0))
7152                            : dyn_cast<Instruction>(RetI->getOperand(1));
7153 
7154   VectorTy = VectorType::get(I->getOperand(0)->getType(), VectorTy);
7155 
7156   if (RedOp && (isa<SExtInst>(RedOp) || isa<ZExtInst>(RedOp)) &&
7157       !TheLoop->isLoopInvariant(RedOp)) {
7158     bool IsUnsigned = isa<ZExtInst>(RedOp);
7159     auto *ExtType = VectorType::get(RedOp->getOperand(0)->getType(), VectorTy);
7160     InstructionCost RedCost = TTI.getExtendedAddReductionCost(
7161         /*IsMLA=*/false, IsUnsigned, RdxDesc.getRecurrenceType(), ExtType,
7162         CostKind);
7163 
7164     InstructionCost ExtCost =
7165         TTI.getCastInstrCost(RedOp->getOpcode(), VectorTy, ExtType,
7166                              TTI::CastContextHint::None, CostKind, RedOp);
7167     if (RedCost.isValid() && RedCost < BaseCost + ExtCost)
7168       return I == RetI ? *RedCost.getValue() : 0;
7169   } else if (RedOp && RedOp->getOpcode() == Instruction::Mul) {
7170     Instruction *Mul = RedOp;
7171     Instruction *Op0 = dyn_cast<Instruction>(Mul->getOperand(0));
7172     Instruction *Op1 = dyn_cast<Instruction>(Mul->getOperand(1));
7173     if (Op0 && Op1 && (isa<SExtInst>(Op0) || isa<ZExtInst>(Op0)) &&
7174         Op0->getOpcode() == Op1->getOpcode() &&
7175         Op0->getOperand(0)->getType() == Op1->getOperand(0)->getType() &&
7176         !TheLoop->isLoopInvariant(Op0) && !TheLoop->isLoopInvariant(Op1)) {
7177       bool IsUnsigned = isa<ZExtInst>(Op0);
7178       auto *ExtType = VectorType::get(Op0->getOperand(0)->getType(), VectorTy);
7179       // reduce(mul(ext, ext))
7180       InstructionCost ExtCost =
7181           TTI.getCastInstrCost(Op0->getOpcode(), VectorTy, ExtType,
7182                                TTI::CastContextHint::None, CostKind, Op0);
7183       InstructionCost MulCost =
7184           TTI.getArithmeticInstrCost(Mul->getOpcode(), VectorTy, CostKind);
7185 
7186       InstructionCost RedCost = TTI.getExtendedAddReductionCost(
7187           /*IsMLA=*/true, IsUnsigned, RdxDesc.getRecurrenceType(), ExtType,
7188           CostKind);
7189 
7190       if (RedCost.isValid() && RedCost < ExtCost * 2 + MulCost + BaseCost)
7191         return I == RetI ? *RedCost.getValue() : 0;
7192     } else {
7193       InstructionCost MulCost =
7194           TTI.getArithmeticInstrCost(Mul->getOpcode(), VectorTy, CostKind);
7195 
7196       InstructionCost RedCost = TTI.getExtendedAddReductionCost(
7197           /*IsMLA=*/true, true, RdxDesc.getRecurrenceType(), VectorTy,
7198           CostKind);
7199 
7200       if (RedCost.isValid() && RedCost < MulCost + BaseCost)
7201         return I == RetI ? *RedCost.getValue() : 0;
7202     }
7203   }
7204 
7205   return I == RetI ? BaseCost : InstructionCost::getInvalid();
7206 }
7207 
7208 InstructionCost
getMemoryInstructionCost(Instruction * I,ElementCount VF)7209 LoopVectorizationCostModel::getMemoryInstructionCost(Instruction *I,
7210                                                      ElementCount VF) {
7211   // Calculate scalar cost only. Vectorization cost should be ready at this
7212   // moment.
7213   if (VF.isScalar()) {
7214     Type *ValTy = getMemInstValueType(I);
7215     const Align Alignment = getLoadStoreAlignment(I);
7216     unsigned AS = getLoadStoreAddressSpace(I);
7217 
7218     return TTI.getAddressComputationCost(ValTy) +
7219            TTI.getMemoryOpCost(I->getOpcode(), ValTy, Alignment, AS,
7220                                TTI::TCK_RecipThroughput, I);
7221   }
7222   return getWideningCost(I, VF);
7223 }
7224 
7225 LoopVectorizationCostModel::VectorizationCostTy
getInstructionCost(Instruction * I,ElementCount VF)7226 LoopVectorizationCostModel::getInstructionCost(Instruction *I,
7227                                                ElementCount VF) {
7228   // If we know that this instruction will remain uniform, check the cost of
7229   // the scalar version.
7230   if (isUniformAfterVectorization(I, VF))
7231     VF = ElementCount::getFixed(1);
7232 
7233   if (VF.isVector() && isProfitableToScalarize(I, VF))
7234     return VectorizationCostTy(InstsToScalarize[VF][I], false);
7235 
7236   // Forced scalars do not have any scalarization overhead.
7237   auto ForcedScalar = ForcedScalars.find(VF);
7238   if (VF.isVector() && ForcedScalar != ForcedScalars.end()) {
7239     auto InstSet = ForcedScalar->second;
7240     if (InstSet.count(I))
7241       return VectorizationCostTy(
7242           (getInstructionCost(I, ElementCount::getFixed(1)).first *
7243            VF.getKnownMinValue()),
7244           false);
7245   }
7246 
7247   Type *VectorTy;
7248   InstructionCost C = getInstructionCost(I, VF, VectorTy);
7249 
7250   bool TypeNotScalarized =
7251       VF.isVector() && VectorTy->isVectorTy() &&
7252       TTI.getNumberOfParts(VectorTy) < VF.getKnownMinValue();
7253   return VectorizationCostTy(C, TypeNotScalarized);
7254 }
7255 
7256 InstructionCost
getScalarizationOverhead(Instruction * I,ElementCount VF) const7257 LoopVectorizationCostModel::getScalarizationOverhead(Instruction *I,
7258                                                      ElementCount VF) const {
7259 
7260   if (VF.isScalable())
7261     return InstructionCost::getInvalid();
7262 
7263   if (VF.isScalar())
7264     return 0;
7265 
7266   InstructionCost Cost = 0;
7267   Type *RetTy = ToVectorTy(I->getType(), VF);
7268   if (!RetTy->isVoidTy() &&
7269       (!isa<LoadInst>(I) || !TTI.supportsEfficientVectorElementLoadStore()))
7270     Cost += TTI.getScalarizationOverhead(
7271         cast<VectorType>(RetTy), APInt::getAllOnesValue(VF.getKnownMinValue()),
7272         true, false);
7273 
7274   // Some targets keep addresses scalar.
7275   if (isa<LoadInst>(I) && !TTI.prefersVectorizedAddressing())
7276     return Cost;
7277 
7278   // Some targets support efficient element stores.
7279   if (isa<StoreInst>(I) && TTI.supportsEfficientVectorElementLoadStore())
7280     return Cost;
7281 
7282   // Collect operands to consider.
7283   CallInst *CI = dyn_cast<CallInst>(I);
7284   Instruction::op_range Ops = CI ? CI->arg_operands() : I->operands();
7285 
7286   // Skip operands that do not require extraction/scalarization and do not incur
7287   // any overhead.
7288   SmallVector<Type *> Tys;
7289   for (auto *V : filterExtractingOperands(Ops, VF))
7290     Tys.push_back(MaybeVectorizeType(V->getType(), VF));
7291   return Cost + TTI.getOperandsScalarizationOverhead(
7292                     filterExtractingOperands(Ops, VF), Tys);
7293 }
7294 
setCostBasedWideningDecision(ElementCount VF)7295 void LoopVectorizationCostModel::setCostBasedWideningDecision(ElementCount VF) {
7296   if (VF.isScalar())
7297     return;
7298   NumPredStores = 0;
7299   for (BasicBlock *BB : TheLoop->blocks()) {
7300     // For each instruction in the old loop.
7301     for (Instruction &I : *BB) {
7302       Value *Ptr =  getLoadStorePointerOperand(&I);
7303       if (!Ptr)
7304         continue;
7305 
7306       // TODO: We should generate better code and update the cost model for
7307       // predicated uniform stores. Today they are treated as any other
7308       // predicated store (see added test cases in
7309       // invariant-store-vectorization.ll).
7310       if (isa<StoreInst>(&I) && isScalarWithPredication(&I))
7311         NumPredStores++;
7312 
7313       if (Legal->isUniformMemOp(I)) {
7314         // TODO: Avoid replicating loads and stores instead of
7315         // relying on instcombine to remove them.
7316         // Load: Scalar load + broadcast
7317         // Store: Scalar store + isLoopInvariantStoreValue ? 0 : extract
7318         InstructionCost Cost = getUniformMemOpCost(&I, VF);
7319         setWideningDecision(&I, VF, CM_Scalarize, Cost);
7320         continue;
7321       }
7322 
7323       // We assume that widening is the best solution when possible.
7324       if (memoryInstructionCanBeWidened(&I, VF)) {
7325         InstructionCost Cost = getConsecutiveMemOpCost(&I, VF);
7326         int ConsecutiveStride =
7327                Legal->isConsecutivePtr(getLoadStorePointerOperand(&I));
7328         assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
7329                "Expected consecutive stride.");
7330         InstWidening Decision =
7331             ConsecutiveStride == 1 ? CM_Widen : CM_Widen_Reverse;
7332         setWideningDecision(&I, VF, Decision, Cost);
7333         continue;
7334       }
7335 
7336       // Choose between Interleaving, Gather/Scatter or Scalarization.
7337       InstructionCost InterleaveCost = InstructionCost::getInvalid();
7338       unsigned NumAccesses = 1;
7339       if (isAccessInterleaved(&I)) {
7340         auto Group = getInterleavedAccessGroup(&I);
7341         assert(Group && "Fail to get an interleaved access group.");
7342 
7343         // Make one decision for the whole group.
7344         if (getWideningDecision(&I, VF) != CM_Unknown)
7345           continue;
7346 
7347         NumAccesses = Group->getNumMembers();
7348         if (interleavedAccessCanBeWidened(&I, VF))
7349           InterleaveCost = getInterleaveGroupCost(&I, VF);
7350       }
7351 
7352       InstructionCost GatherScatterCost =
7353           isLegalGatherOrScatter(&I)
7354               ? getGatherScatterCost(&I, VF) * NumAccesses
7355               : InstructionCost::getInvalid();
7356 
7357       InstructionCost ScalarizationCost =
7358           getMemInstScalarizationCost(&I, VF) * NumAccesses;
7359 
7360       // Choose better solution for the current VF,
7361       // write down this decision and use it during vectorization.
7362       InstructionCost Cost;
7363       InstWidening Decision;
7364       if (InterleaveCost <= GatherScatterCost &&
7365           InterleaveCost < ScalarizationCost) {
7366         Decision = CM_Interleave;
7367         Cost = InterleaveCost;
7368       } else if (GatherScatterCost < ScalarizationCost) {
7369         Decision = CM_GatherScatter;
7370         Cost = GatherScatterCost;
7371       } else {
7372         assert(!VF.isScalable() &&
7373                "We cannot yet scalarise for scalable vectors");
7374         Decision = CM_Scalarize;
7375         Cost = ScalarizationCost;
7376       }
7377       // If the instructions belongs to an interleave group, the whole group
7378       // receives the same decision. The whole group receives the cost, but
7379       // the cost will actually be assigned to one instruction.
7380       if (auto Group = getInterleavedAccessGroup(&I))
7381         setWideningDecision(Group, VF, Decision, Cost);
7382       else
7383         setWideningDecision(&I, VF, Decision, Cost);
7384     }
7385   }
7386 
7387   // Make sure that any load of address and any other address computation
7388   // remains scalar unless there is gather/scatter support. This avoids
7389   // inevitable extracts into address registers, and also has the benefit of
7390   // activating LSR more, since that pass can't optimize vectorized
7391   // addresses.
7392   if (TTI.prefersVectorizedAddressing())
7393     return;
7394 
7395   // Start with all scalar pointer uses.
7396   SmallPtrSet<Instruction *, 8> AddrDefs;
7397   for (BasicBlock *BB : TheLoop->blocks())
7398     for (Instruction &I : *BB) {
7399       Instruction *PtrDef =
7400         dyn_cast_or_null<Instruction>(getLoadStorePointerOperand(&I));
7401       if (PtrDef && TheLoop->contains(PtrDef) &&
7402           getWideningDecision(&I, VF) != CM_GatherScatter)
7403         AddrDefs.insert(PtrDef);
7404     }
7405 
7406   // Add all instructions used to generate the addresses.
7407   SmallVector<Instruction *, 4> Worklist;
7408   append_range(Worklist, AddrDefs);
7409   while (!Worklist.empty()) {
7410     Instruction *I = Worklist.pop_back_val();
7411     for (auto &Op : I->operands())
7412       if (auto *InstOp = dyn_cast<Instruction>(Op))
7413         if ((InstOp->getParent() == I->getParent()) && !isa<PHINode>(InstOp) &&
7414             AddrDefs.insert(InstOp).second)
7415           Worklist.push_back(InstOp);
7416   }
7417 
7418   for (auto *I : AddrDefs) {
7419     if (isa<LoadInst>(I)) {
7420       // Setting the desired widening decision should ideally be handled in
7421       // by cost functions, but since this involves the task of finding out
7422       // if the loaded register is involved in an address computation, it is
7423       // instead changed here when we know this is the case.
7424       InstWidening Decision = getWideningDecision(I, VF);
7425       if (Decision == CM_Widen || Decision == CM_Widen_Reverse)
7426         // Scalarize a widened load of address.
7427         setWideningDecision(
7428             I, VF, CM_Scalarize,
7429             (VF.getKnownMinValue() *
7430              getMemoryInstructionCost(I, ElementCount::getFixed(1))));
7431       else if (auto Group = getInterleavedAccessGroup(I)) {
7432         // Scalarize an interleave group of address loads.
7433         for (unsigned I = 0; I < Group->getFactor(); ++I) {
7434           if (Instruction *Member = Group->getMember(I))
7435             setWideningDecision(
7436                 Member, VF, CM_Scalarize,
7437                 (VF.getKnownMinValue() *
7438                  getMemoryInstructionCost(Member, ElementCount::getFixed(1))));
7439         }
7440       }
7441     } else
7442       // Make sure I gets scalarized and a cost estimate without
7443       // scalarization overhead.
7444       ForcedScalars[VF].insert(I);
7445   }
7446 }
7447 
7448 InstructionCost
getInstructionCost(Instruction * I,ElementCount VF,Type * & VectorTy)7449 LoopVectorizationCostModel::getInstructionCost(Instruction *I, ElementCount VF,
7450                                                Type *&VectorTy) {
7451   Type *RetTy = I->getType();
7452   if (canTruncateToMinimalBitwidth(I, VF))
7453     RetTy = IntegerType::get(RetTy->getContext(), MinBWs[I]);
7454   auto SE = PSE.getSE();
7455   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
7456 
7457   auto hasSingleCopyAfterVectorization = [this](Instruction *I,
7458                                                 ElementCount VF) -> bool {
7459     if (VF.isScalar())
7460       return true;
7461 
7462     auto Scalarized = InstsToScalarize.find(VF);
7463     assert(Scalarized != InstsToScalarize.end() &&
7464            "VF not yet analyzed for scalarization profitability");
7465     return !Scalarized->second.count(I) &&
7466            llvm::all_of(I->users(), [&](User *U) {
7467              auto *UI = cast<Instruction>(U);
7468              return !Scalarized->second.count(UI);
7469            });
7470   };
7471   (void) hasSingleCopyAfterVectorization;
7472 
7473   if (isScalarAfterVectorization(I, VF)) {
7474     // With the exception of GEPs and PHIs, after scalarization there should
7475     // only be one copy of the instruction generated in the loop. This is
7476     // because the VF is either 1, or any instructions that need scalarizing
7477     // have already been dealt with by the the time we get here. As a result,
7478     // it means we don't have to multiply the instruction cost by VF.
7479     assert(I->getOpcode() == Instruction::GetElementPtr ||
7480            I->getOpcode() == Instruction::PHI ||
7481            (I->getOpcode() == Instruction::BitCast &&
7482             I->getType()->isPointerTy()) ||
7483            hasSingleCopyAfterVectorization(I, VF));
7484     VectorTy = RetTy;
7485   } else
7486     VectorTy = ToVectorTy(RetTy, VF);
7487 
7488   // TODO: We need to estimate the cost of intrinsic calls.
7489   switch (I->getOpcode()) {
7490   case Instruction::GetElementPtr:
7491     // We mark this instruction as zero-cost because the cost of GEPs in
7492     // vectorized code depends on whether the corresponding memory instruction
7493     // is scalarized or not. Therefore, we handle GEPs with the memory
7494     // instruction cost.
7495     return 0;
7496   case Instruction::Br: {
7497     // In cases of scalarized and predicated instructions, there will be VF
7498     // predicated blocks in the vectorized loop. Each branch around these
7499     // blocks requires also an extract of its vector compare i1 element.
7500     bool ScalarPredicatedBB = false;
7501     BranchInst *BI = cast<BranchInst>(I);
7502     if (VF.isVector() && BI->isConditional() &&
7503         (PredicatedBBsAfterVectorization.count(BI->getSuccessor(0)) ||
7504          PredicatedBBsAfterVectorization.count(BI->getSuccessor(1))))
7505       ScalarPredicatedBB = true;
7506 
7507     if (ScalarPredicatedBB) {
7508       // Return cost for branches around scalarized and predicated blocks.
7509       assert(!VF.isScalable() && "scalable vectors not yet supported.");
7510       auto *Vec_i1Ty =
7511           VectorType::get(IntegerType::getInt1Ty(RetTy->getContext()), VF);
7512       return (TTI.getScalarizationOverhead(
7513                   Vec_i1Ty, APInt::getAllOnesValue(VF.getKnownMinValue()),
7514                   false, true) +
7515               (TTI.getCFInstrCost(Instruction::Br, CostKind) *
7516                VF.getKnownMinValue()));
7517     } else if (I->getParent() == TheLoop->getLoopLatch() || VF.isScalar())
7518       // The back-edge branch will remain, as will all scalar branches.
7519       return TTI.getCFInstrCost(Instruction::Br, CostKind);
7520     else
7521       // This branch will be eliminated by if-conversion.
7522       return 0;
7523     // Note: We currently assume zero cost for an unconditional branch inside
7524     // a predicated block since it will become a fall-through, although we
7525     // may decide in the future to call TTI for all branches.
7526   }
7527   case Instruction::PHI: {
7528     auto *Phi = cast<PHINode>(I);
7529 
7530     // First-order recurrences are replaced by vector shuffles inside the loop.
7531     // NOTE: Don't use ToVectorTy as SK_ExtractSubvector expects a vector type.
7532     if (VF.isVector() && Legal->isFirstOrderRecurrence(Phi))
7533       return TTI.getShuffleCost(
7534           TargetTransformInfo::SK_ExtractSubvector, cast<VectorType>(VectorTy),
7535           None, VF.getKnownMinValue() - 1, FixedVectorType::get(RetTy, 1));
7536 
7537     // Phi nodes in non-header blocks (not inductions, reductions, etc.) are
7538     // converted into select instructions. We require N - 1 selects per phi
7539     // node, where N is the number of incoming values.
7540     if (VF.isVector() && Phi->getParent() != TheLoop->getHeader())
7541       return (Phi->getNumIncomingValues() - 1) *
7542              TTI.getCmpSelInstrCost(
7543                  Instruction::Select, ToVectorTy(Phi->getType(), VF),
7544                  ToVectorTy(Type::getInt1Ty(Phi->getContext()), VF),
7545                  CmpInst::BAD_ICMP_PREDICATE, CostKind);
7546 
7547     return TTI.getCFInstrCost(Instruction::PHI, CostKind);
7548   }
7549   case Instruction::UDiv:
7550   case Instruction::SDiv:
7551   case Instruction::URem:
7552   case Instruction::SRem:
7553     // If we have a predicated instruction, it may not be executed for each
7554     // vector lane. Get the scalarization cost and scale this amount by the
7555     // probability of executing the predicated block. If the instruction is not
7556     // predicated, we fall through to the next case.
7557     if (VF.isVector() && isScalarWithPredication(I)) {
7558       InstructionCost Cost = 0;
7559 
7560       // These instructions have a non-void type, so account for the phi nodes
7561       // that we will create. This cost is likely to be zero. The phi node
7562       // cost, if any, should be scaled by the block probability because it
7563       // models a copy at the end of each predicated block.
7564       Cost += VF.getKnownMinValue() *
7565               TTI.getCFInstrCost(Instruction::PHI, CostKind);
7566 
7567       // The cost of the non-predicated instruction.
7568       Cost += VF.getKnownMinValue() *
7569               TTI.getArithmeticInstrCost(I->getOpcode(), RetTy, CostKind);
7570 
7571       // The cost of insertelement and extractelement instructions needed for
7572       // scalarization.
7573       Cost += getScalarizationOverhead(I, VF);
7574 
7575       // Scale the cost by the probability of executing the predicated blocks.
7576       // This assumes the predicated block for each vector lane is equally
7577       // likely.
7578       return Cost / getReciprocalPredBlockProb();
7579     }
7580     LLVM_FALLTHROUGH;
7581   case Instruction::Add:
7582   case Instruction::FAdd:
7583   case Instruction::Sub:
7584   case Instruction::FSub:
7585   case Instruction::Mul:
7586   case Instruction::FMul:
7587   case Instruction::FDiv:
7588   case Instruction::FRem:
7589   case Instruction::Shl:
7590   case Instruction::LShr:
7591   case Instruction::AShr:
7592   case Instruction::And:
7593   case Instruction::Or:
7594   case Instruction::Xor: {
7595     // Since we will replace the stride by 1 the multiplication should go away.
7596     if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
7597       return 0;
7598 
7599     // Detect reduction patterns
7600     InstructionCost RedCost;
7601     if ((RedCost = getReductionPatternCost(I, VF, VectorTy, CostKind))
7602             .isValid())
7603       return RedCost;
7604 
7605     // Certain instructions can be cheaper to vectorize if they have a constant
7606     // second vector operand. One example of this are shifts on x86.
7607     Value *Op2 = I->getOperand(1);
7608     TargetTransformInfo::OperandValueProperties Op2VP;
7609     TargetTransformInfo::OperandValueKind Op2VK =
7610         TTI.getOperandInfo(Op2, Op2VP);
7611     if (Op2VK == TargetTransformInfo::OK_AnyValue && Legal->isUniform(Op2))
7612       Op2VK = TargetTransformInfo::OK_UniformValue;
7613 
7614     SmallVector<const Value *, 4> Operands(I->operand_values());
7615     return TTI.getArithmeticInstrCost(
7616         I->getOpcode(), VectorTy, CostKind, TargetTransformInfo::OK_AnyValue,
7617         Op2VK, TargetTransformInfo::OP_None, Op2VP, Operands, I);
7618   }
7619   case Instruction::FNeg: {
7620     return TTI.getArithmeticInstrCost(
7621         I->getOpcode(), VectorTy, CostKind, TargetTransformInfo::OK_AnyValue,
7622         TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None,
7623         TargetTransformInfo::OP_None, I->getOperand(0), I);
7624   }
7625   case Instruction::Select: {
7626     SelectInst *SI = cast<SelectInst>(I);
7627     const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
7628     bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
7629 
7630     const Value *Op0, *Op1;
7631     using namespace llvm::PatternMatch;
7632     if (!ScalarCond && (match(I, m_LogicalAnd(m_Value(Op0), m_Value(Op1))) ||
7633                         match(I, m_LogicalOr(m_Value(Op0), m_Value(Op1))))) {
7634       // select x, y, false --> x & y
7635       // select x, true, y --> x | y
7636       TTI::OperandValueProperties Op1VP = TTI::OP_None;
7637       TTI::OperandValueProperties Op2VP = TTI::OP_None;
7638       TTI::OperandValueKind Op1VK = TTI::getOperandInfo(Op0, Op1VP);
7639       TTI::OperandValueKind Op2VK = TTI::getOperandInfo(Op1, Op2VP);
7640       assert(Op0->getType()->getScalarSizeInBits() == 1 &&
7641               Op1->getType()->getScalarSizeInBits() == 1);
7642 
7643       SmallVector<const Value *, 2> Operands{Op0, Op1};
7644       return TTI.getArithmeticInstrCost(
7645           match(I, m_LogicalOr()) ? Instruction::Or : Instruction::And, VectorTy,
7646           CostKind, Op1VK, Op2VK, Op1VP, Op2VP, Operands, I);
7647     }
7648 
7649     Type *CondTy = SI->getCondition()->getType();
7650     if (!ScalarCond)
7651       CondTy = VectorType::get(CondTy, VF);
7652     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy,
7653                                   CmpInst::BAD_ICMP_PREDICATE, CostKind, I);
7654   }
7655   case Instruction::ICmp:
7656   case Instruction::FCmp: {
7657     Type *ValTy = I->getOperand(0)->getType();
7658     Instruction *Op0AsInstruction = dyn_cast<Instruction>(I->getOperand(0));
7659     if (canTruncateToMinimalBitwidth(Op0AsInstruction, VF))
7660       ValTy = IntegerType::get(ValTy->getContext(), MinBWs[Op0AsInstruction]);
7661     VectorTy = ToVectorTy(ValTy, VF);
7662     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, nullptr,
7663                                   CmpInst::BAD_ICMP_PREDICATE, CostKind, I);
7664   }
7665   case Instruction::Store:
7666   case Instruction::Load: {
7667     ElementCount Width = VF;
7668     if (Width.isVector()) {
7669       InstWidening Decision = getWideningDecision(I, Width);
7670       assert(Decision != CM_Unknown &&
7671              "CM decision should be taken at this point");
7672       if (Decision == CM_Scalarize)
7673         Width = ElementCount::getFixed(1);
7674     }
7675     VectorTy = ToVectorTy(getMemInstValueType(I), Width);
7676     return getMemoryInstructionCost(I, VF);
7677   }
7678   case Instruction::BitCast:
7679     if (I->getType()->isPointerTy())
7680       return 0;
7681     LLVM_FALLTHROUGH;
7682   case Instruction::ZExt:
7683   case Instruction::SExt:
7684   case Instruction::FPToUI:
7685   case Instruction::FPToSI:
7686   case Instruction::FPExt:
7687   case Instruction::PtrToInt:
7688   case Instruction::IntToPtr:
7689   case Instruction::SIToFP:
7690   case Instruction::UIToFP:
7691   case Instruction::Trunc:
7692   case Instruction::FPTrunc: {
7693     // Computes the CastContextHint from a Load/Store instruction.
7694     auto ComputeCCH = [&](Instruction *I) -> TTI::CastContextHint {
7695       assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
7696              "Expected a load or a store!");
7697 
7698       if (VF.isScalar() || !TheLoop->contains(I))
7699         return TTI::CastContextHint::Normal;
7700 
7701       switch (getWideningDecision(I, VF)) {
7702       case LoopVectorizationCostModel::CM_GatherScatter:
7703         return TTI::CastContextHint::GatherScatter;
7704       case LoopVectorizationCostModel::CM_Interleave:
7705         return TTI::CastContextHint::Interleave;
7706       case LoopVectorizationCostModel::CM_Scalarize:
7707       case LoopVectorizationCostModel::CM_Widen:
7708         return Legal->isMaskRequired(I) ? TTI::CastContextHint::Masked
7709                                         : TTI::CastContextHint::Normal;
7710       case LoopVectorizationCostModel::CM_Widen_Reverse:
7711         return TTI::CastContextHint::Reversed;
7712       case LoopVectorizationCostModel::CM_Unknown:
7713         llvm_unreachable("Instr did not go through cost modelling?");
7714       }
7715 
7716       llvm_unreachable("Unhandled case!");
7717     };
7718 
7719     unsigned Opcode = I->getOpcode();
7720     TTI::CastContextHint CCH = TTI::CastContextHint::None;
7721     // For Trunc, the context is the only user, which must be a StoreInst.
7722     if (Opcode == Instruction::Trunc || Opcode == Instruction::FPTrunc) {
7723       if (I->hasOneUse())
7724         if (StoreInst *Store = dyn_cast<StoreInst>(*I->user_begin()))
7725           CCH = ComputeCCH(Store);
7726     }
7727     // For Z/Sext, the context is the operand, which must be a LoadInst.
7728     else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt ||
7729              Opcode == Instruction::FPExt) {
7730       if (LoadInst *Load = dyn_cast<LoadInst>(I->getOperand(0)))
7731         CCH = ComputeCCH(Load);
7732     }
7733 
7734     // We optimize the truncation of induction variables having constant
7735     // integer steps. The cost of these truncations is the same as the scalar
7736     // operation.
7737     if (isOptimizableIVTruncate(I, VF)) {
7738       auto *Trunc = cast<TruncInst>(I);
7739       return TTI.getCastInstrCost(Instruction::Trunc, Trunc->getDestTy(),
7740                                   Trunc->getSrcTy(), CCH, CostKind, Trunc);
7741     }
7742 
7743     // Detect reduction patterns
7744     InstructionCost RedCost;
7745     if ((RedCost = getReductionPatternCost(I, VF, VectorTy, CostKind))
7746             .isValid())
7747       return RedCost;
7748 
7749     Type *SrcScalarTy = I->getOperand(0)->getType();
7750     Type *SrcVecTy =
7751         VectorTy->isVectorTy() ? ToVectorTy(SrcScalarTy, VF) : SrcScalarTy;
7752     if (canTruncateToMinimalBitwidth(I, VF)) {
7753       // This cast is going to be shrunk. This may remove the cast or it might
7754       // turn it into slightly different cast. For example, if MinBW == 16,
7755       // "zext i8 %1 to i32" becomes "zext i8 %1 to i16".
7756       //
7757       // Calculate the modified src and dest types.
7758       Type *MinVecTy = VectorTy;
7759       if (Opcode == Instruction::Trunc) {
7760         SrcVecTy = smallestIntegerVectorType(SrcVecTy, MinVecTy);
7761         VectorTy =
7762             largestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy);
7763       } else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
7764         SrcVecTy = largestIntegerVectorType(SrcVecTy, MinVecTy);
7765         VectorTy =
7766             smallestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy);
7767       }
7768     }
7769 
7770     return TTI.getCastInstrCost(Opcode, VectorTy, SrcVecTy, CCH, CostKind, I);
7771   }
7772   case Instruction::Call: {
7773     bool NeedToScalarize;
7774     CallInst *CI = cast<CallInst>(I);
7775     InstructionCost CallCost = getVectorCallCost(CI, VF, NeedToScalarize);
7776     if (getVectorIntrinsicIDForCall(CI, TLI)) {
7777       InstructionCost IntrinsicCost = getVectorIntrinsicCost(CI, VF);
7778       return std::min(CallCost, IntrinsicCost);
7779     }
7780     return CallCost;
7781   }
7782   case Instruction::ExtractValue:
7783     return TTI.getInstructionCost(I, TTI::TCK_RecipThroughput);
7784   default:
7785     // This opcode is unknown. Assume that it is the same as 'mul'.
7786     return TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy, CostKind);
7787   } // end of switch.
7788 }
7789 
7790 char LoopVectorize::ID = 0;
7791 
7792 static const char lv_name[] = "Loop Vectorization";
7793 
7794 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
7795 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
7796 INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
7797 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
7798 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
7799 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
7800 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
7801 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
7802 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
7803 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
7804 INITIALIZE_PASS_DEPENDENCY(LoopAccessLegacyAnalysis)
7805 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
7806 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
7807 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
7808 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
7809 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
7810 
7811 namespace llvm {
7812 
createLoopVectorizePass()7813 Pass *createLoopVectorizePass() { return new LoopVectorize(); }
7814 
createLoopVectorizePass(bool InterleaveOnlyWhenForced,bool VectorizeOnlyWhenForced)7815 Pass *createLoopVectorizePass(bool InterleaveOnlyWhenForced,
7816                               bool VectorizeOnlyWhenForced) {
7817   return new LoopVectorize(InterleaveOnlyWhenForced, VectorizeOnlyWhenForced);
7818 }
7819 
7820 } // end namespace llvm
7821 
isConsecutiveLoadOrStore(Instruction * Inst)7822 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
7823   // Check if the pointer operand of a load or store instruction is
7824   // consecutive.
7825   if (auto *Ptr = getLoadStorePointerOperand(Inst))
7826     return Legal->isConsecutivePtr(Ptr);
7827   return false;
7828 }
7829 
collectValuesToIgnore()7830 void LoopVectorizationCostModel::collectValuesToIgnore() {
7831   // Ignore ephemeral values.
7832   CodeMetrics::collectEphemeralValues(TheLoop, AC, ValuesToIgnore);
7833 
7834   // Ignore type-promoting instructions we identified during reduction
7835   // detection.
7836   for (auto &Reduction : Legal->getReductionVars()) {
7837     RecurrenceDescriptor &RedDes = Reduction.second;
7838     const SmallPtrSetImpl<Instruction *> &Casts = RedDes.getCastInsts();
7839     VecValuesToIgnore.insert(Casts.begin(), Casts.end());
7840   }
7841   // Ignore type-casting instructions we identified during induction
7842   // detection.
7843   for (auto &Induction : Legal->getInductionVars()) {
7844     InductionDescriptor &IndDes = Induction.second;
7845     const SmallVectorImpl<Instruction *> &Casts = IndDes.getCastInsts();
7846     VecValuesToIgnore.insert(Casts.begin(), Casts.end());
7847   }
7848 }
7849 
collectInLoopReductions()7850 void LoopVectorizationCostModel::collectInLoopReductions() {
7851   for (auto &Reduction : Legal->getReductionVars()) {
7852     PHINode *Phi = Reduction.first;
7853     RecurrenceDescriptor &RdxDesc = Reduction.second;
7854 
7855     // We don't collect reductions that are type promoted (yet).
7856     if (RdxDesc.getRecurrenceType() != Phi->getType())
7857       continue;
7858 
7859     // If the target would prefer this reduction to happen "in-loop", then we
7860     // want to record it as such.
7861     unsigned Opcode = RdxDesc.getOpcode();
7862     if (!PreferInLoopReductions && !useOrderedReductions(RdxDesc) &&
7863         !TTI.preferInLoopReduction(Opcode, Phi->getType(),
7864                                    TargetTransformInfo::ReductionFlags()))
7865       continue;
7866 
7867     // Check that we can correctly put the reductions into the loop, by
7868     // finding the chain of operations that leads from the phi to the loop
7869     // exit value.
7870     SmallVector<Instruction *, 4> ReductionOperations =
7871         RdxDesc.getReductionOpChain(Phi, TheLoop);
7872     bool InLoop = !ReductionOperations.empty();
7873     if (InLoop) {
7874       InLoopReductionChains[Phi] = ReductionOperations;
7875       // Add the elements to InLoopReductionImmediateChains for cost modelling.
7876       Instruction *LastChain = Phi;
7877       for (auto *I : ReductionOperations) {
7878         InLoopReductionImmediateChains[I] = LastChain;
7879         LastChain = I;
7880       }
7881     }
7882     LLVM_DEBUG(dbgs() << "LV: Using " << (InLoop ? "inloop" : "out of loop")
7883                       << " reduction for phi: " << *Phi << "\n");
7884   }
7885 }
7886 
7887 // TODO: we could return a pair of values that specify the max VF and
7888 // min VF, to be used in `buildVPlans(MinVF, MaxVF)` instead of
7889 // `buildVPlans(VF, VF)`. We cannot do it because VPLAN at the moment
7890 // doesn't have a cost model that can choose which plan to execute if
7891 // more than one is generated.
determineVPlanVF(const unsigned WidestVectorRegBits,LoopVectorizationCostModel & CM)7892 static unsigned determineVPlanVF(const unsigned WidestVectorRegBits,
7893                                  LoopVectorizationCostModel &CM) {
7894   unsigned WidestType;
7895   std::tie(std::ignore, WidestType) = CM.getSmallestAndWidestTypes();
7896   return WidestVectorRegBits / WidestType;
7897 }
7898 
7899 VectorizationFactor
planInVPlanNativePath(ElementCount UserVF)7900 LoopVectorizationPlanner::planInVPlanNativePath(ElementCount UserVF) {
7901   assert(!UserVF.isScalable() && "scalable vectors not yet supported");
7902   ElementCount VF = UserVF;
7903   // Outer loop handling: They may require CFG and instruction level
7904   // transformations before even evaluating whether vectorization is profitable.
7905   // Since we cannot modify the incoming IR, we need to build VPlan upfront in
7906   // the vectorization pipeline.
7907   if (!OrigLoop->isInnermost()) {
7908     // If the user doesn't provide a vectorization factor, determine a
7909     // reasonable one.
7910     if (UserVF.isZero()) {
7911       VF = ElementCount::getFixed(determineVPlanVF(
7912           TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector)
7913               .getFixedSize(),
7914           CM));
7915       LLVM_DEBUG(dbgs() << "LV: VPlan computed VF " << VF << ".\n");
7916 
7917       // Make sure we have a VF > 1 for stress testing.
7918       if (VPlanBuildStressTest && (VF.isScalar() || VF.isZero())) {
7919         LLVM_DEBUG(dbgs() << "LV: VPlan stress testing: "
7920                           << "overriding computed VF.\n");
7921         VF = ElementCount::getFixed(4);
7922       }
7923     }
7924     assert(EnableVPlanNativePath && "VPlan-native path is not enabled.");
7925     assert(isPowerOf2_32(VF.getKnownMinValue()) &&
7926            "VF needs to be a power of two");
7927     LLVM_DEBUG(dbgs() << "LV: Using " << (!UserVF.isZero() ? "user " : "")
7928                       << "VF " << VF << " to build VPlans.\n");
7929     buildVPlans(VF, VF);
7930 
7931     // For VPlan build stress testing, we bail out after VPlan construction.
7932     if (VPlanBuildStressTest)
7933       return VectorizationFactor::Disabled();
7934 
7935     return {VF, 0 /*Cost*/};
7936   }
7937 
7938   LLVM_DEBUG(
7939       dbgs() << "LV: Not vectorizing. Inner loops aren't supported in the "
7940                 "VPlan-native path.\n");
7941   return VectorizationFactor::Disabled();
7942 }
7943 
7944 Optional<VectorizationFactor>
plan(ElementCount UserVF,unsigned UserIC)7945 LoopVectorizationPlanner::plan(ElementCount UserVF, unsigned UserIC) {
7946   assert(OrigLoop->isInnermost() && "Inner loop expected.");
7947   FixedScalableVFPair MaxFactors = CM.computeMaxVF(UserVF, UserIC);
7948   if (!MaxFactors) // Cases that should not to be vectorized nor interleaved.
7949     return None;
7950 
7951   // Invalidate interleave groups if all blocks of loop will be predicated.
7952   if (CM.blockNeedsPredication(OrigLoop->getHeader()) &&
7953       !useMaskedInterleavedAccesses(*TTI)) {
7954     LLVM_DEBUG(
7955         dbgs()
7956         << "LV: Invalidate all interleaved groups due to fold-tail by masking "
7957            "which requires masked-interleaved support.\n");
7958     if (CM.InterleaveInfo.invalidateGroups())
7959       // Invalidating interleave groups also requires invalidating all decisions
7960       // based on them, which includes widening decisions and uniform and scalar
7961       // values.
7962       CM.invalidateCostModelingDecisions();
7963   }
7964 
7965   ElementCount MaxUserVF =
7966       UserVF.isScalable() ? MaxFactors.ScalableVF : MaxFactors.FixedVF;
7967   bool UserVFIsLegal = ElementCount::isKnownLE(UserVF, MaxUserVF);
7968   if (!UserVF.isZero() && UserVFIsLegal) {
7969     LLVM_DEBUG(dbgs() << "LV: Using " << (UserVFIsLegal ? "user" : "max")
7970                       << " VF " << UserVF << ".\n");
7971     assert(isPowerOf2_32(UserVF.getKnownMinValue()) &&
7972            "VF needs to be a power of two");
7973     // Collect the instructions (and their associated costs) that will be more
7974     // profitable to scalarize.
7975     CM.selectUserVectorizationFactor(UserVF);
7976     CM.collectInLoopReductions();
7977     buildVPlansWithVPRecipes({UserVF}, {UserVF});
7978     LLVM_DEBUG(printPlans(dbgs()));
7979     return {{UserVF, 0}};
7980   }
7981 
7982   ElementCount MaxVF = MaxFactors.FixedVF;
7983   assert(!MaxVF.isScalable() &&
7984          "Scalable vectors not yet supported beyond this point");
7985 
7986   for (ElementCount VF = ElementCount::getFixed(1);
7987        ElementCount::isKnownLE(VF, MaxVF); VF *= 2) {
7988     // Collect Uniform and Scalar instructions after vectorization with VF.
7989     CM.collectUniformsAndScalars(VF);
7990 
7991     // Collect the instructions (and their associated costs) that will be more
7992     // profitable to scalarize.
7993     if (VF.isVector())
7994       CM.collectInstsToScalarize(VF);
7995   }
7996 
7997   CM.collectInLoopReductions();
7998 
7999   buildVPlansWithVPRecipes(ElementCount::getFixed(1), MaxVF);
8000   LLVM_DEBUG(printPlans(dbgs()));
8001   if (!MaxFactors.hasVector())
8002     return VectorizationFactor::Disabled();
8003 
8004   // Select the optimal vectorization factor.
8005   auto SelectedVF = CM.selectVectorizationFactor(MaxVF);
8006 
8007   // Check if it is profitable to vectorize with runtime checks.
8008   unsigned NumRuntimePointerChecks = Requirements.getNumRuntimePointerChecks();
8009   if (SelectedVF.Width.getKnownMinValue() > 1 && NumRuntimePointerChecks) {
8010     bool PragmaThresholdReached =
8011         NumRuntimePointerChecks > PragmaVectorizeMemoryCheckThreshold;
8012     bool ThresholdReached =
8013         NumRuntimePointerChecks > VectorizerParams::RuntimeMemoryCheckThreshold;
8014     if ((ThresholdReached && !Hints.allowReordering()) ||
8015         PragmaThresholdReached) {
8016       ORE->emit([&]() {
8017         return OptimizationRemarkAnalysisAliasing(
8018                    DEBUG_TYPE, "CantReorderMemOps", OrigLoop->getStartLoc(),
8019                    OrigLoop->getHeader())
8020                << "loop not vectorized: cannot prove it is safe to reorder "
8021                   "memory operations";
8022       });
8023       LLVM_DEBUG(dbgs() << "LV: Too many memory checks needed.\n");
8024       Hints.emitRemarkWithHints();
8025       return VectorizationFactor::Disabled();
8026     }
8027   }
8028   return SelectedVF;
8029 }
8030 
setBestPlan(ElementCount VF,unsigned UF)8031 void LoopVectorizationPlanner::setBestPlan(ElementCount VF, unsigned UF) {
8032   LLVM_DEBUG(dbgs() << "Setting best plan to VF=" << VF << ", UF=" << UF
8033                     << '\n');
8034   BestVF = VF;
8035   BestUF = UF;
8036 
8037   erase_if(VPlans, [VF](const VPlanPtr &Plan) {
8038     return !Plan->hasVF(VF);
8039   });
8040   assert(VPlans.size() == 1 && "Best VF has not a single VPlan.");
8041 }
8042 
executePlan(InnerLoopVectorizer & ILV,DominatorTree * DT)8043 void LoopVectorizationPlanner::executePlan(InnerLoopVectorizer &ILV,
8044                                            DominatorTree *DT) {
8045   // Perform the actual loop transformation.
8046 
8047   // 1. Create a new empty loop. Unlink the old loop and connect the new one.
8048   assert(BestVF.hasValue() && "Vectorization Factor is missing");
8049   assert(VPlans.size() == 1 && "Not a single VPlan to execute.");
8050 
8051   VPTransformState State{
8052       *BestVF, BestUF, LI, DT, ILV.Builder, &ILV, VPlans.front().get()};
8053   State.CFG.PrevBB = ILV.createVectorizedLoopSkeleton();
8054   State.TripCount = ILV.getOrCreateTripCount(nullptr);
8055   State.CanonicalIV = ILV.Induction;
8056 
8057   ILV.printDebugTracesAtStart();
8058 
8059   //===------------------------------------------------===//
8060   //
8061   // Notice: any optimization or new instruction that go
8062   // into the code below should also be implemented in
8063   // the cost-model.
8064   //
8065   //===------------------------------------------------===//
8066 
8067   // 2. Copy and widen instructions from the old loop into the new loop.
8068   VPlans.front()->execute(&State);
8069 
8070   // 3. Fix the vectorized code: take care of header phi's, live-outs,
8071   //    predication, updating analyses.
8072   ILV.fixVectorizedLoop(State);
8073 
8074   ILV.printDebugTracesAtEnd();
8075 }
8076 
8077 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
printPlans(raw_ostream & O)8078 void LoopVectorizationPlanner::printPlans(raw_ostream &O) {
8079   for (const auto &Plan : VPlans)
8080     if (PrintVPlansInDotFormat)
8081       Plan->printDOT(O);
8082     else
8083       Plan->print(O);
8084 }
8085 #endif
8086 
collectTriviallyDeadInstructions(SmallPtrSetImpl<Instruction * > & DeadInstructions)8087 void LoopVectorizationPlanner::collectTriviallyDeadInstructions(
8088     SmallPtrSetImpl<Instruction *> &DeadInstructions) {
8089 
8090   // We create new control-flow for the vectorized loop, so the original exit
8091   // conditions will be dead after vectorization if it's only used by the
8092   // terminator
8093   SmallVector<BasicBlock*> ExitingBlocks;
8094   OrigLoop->getExitingBlocks(ExitingBlocks);
8095   for (auto *BB : ExitingBlocks) {
8096     auto *Cmp = dyn_cast<Instruction>(BB->getTerminator()->getOperand(0));
8097     if (!Cmp || !Cmp->hasOneUse())
8098       continue;
8099 
8100     // TODO: we should introduce a getUniqueExitingBlocks on Loop
8101     if (!DeadInstructions.insert(Cmp).second)
8102       continue;
8103 
8104     // The operands of the icmp is often a dead trunc, used by IndUpdate.
8105     // TODO: can recurse through operands in general
8106     for (Value *Op : Cmp->operands()) {
8107       if (isa<TruncInst>(Op) && Op->hasOneUse())
8108           DeadInstructions.insert(cast<Instruction>(Op));
8109     }
8110   }
8111 
8112   // We create new "steps" for induction variable updates to which the original
8113   // induction variables map. An original update instruction will be dead if
8114   // all its users except the induction variable are dead.
8115   auto *Latch = OrigLoop->getLoopLatch();
8116   for (auto &Induction : Legal->getInductionVars()) {
8117     PHINode *Ind = Induction.first;
8118     auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
8119 
8120     // If the tail is to be folded by masking, the primary induction variable,
8121     // if exists, isn't dead: it will be used for masking. Don't kill it.
8122     if (CM.foldTailByMasking() && IndUpdate == Legal->getPrimaryInduction())
8123       continue;
8124 
8125     if (llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
8126           return U == Ind || DeadInstructions.count(cast<Instruction>(U));
8127         }))
8128       DeadInstructions.insert(IndUpdate);
8129 
8130     // We record as "Dead" also the type-casting instructions we had identified
8131     // during induction analysis. We don't need any handling for them in the
8132     // vectorized loop because we have proven that, under a proper runtime
8133     // test guarding the vectorized loop, the value of the phi, and the casted
8134     // value of the phi, are the same. The last instruction in this casting chain
8135     // will get its scalar/vector/widened def from the scalar/vector/widened def
8136     // of the respective phi node. Any other casts in the induction def-use chain
8137     // have no other uses outside the phi update chain, and will be ignored.
8138     InductionDescriptor &IndDes = Induction.second;
8139     const SmallVectorImpl<Instruction *> &Casts = IndDes.getCastInsts();
8140     DeadInstructions.insert(Casts.begin(), Casts.end());
8141   }
8142 }
8143 
reverseVector(Value * Vec)8144 Value *InnerLoopUnroller::reverseVector(Value *Vec) { return Vec; }
8145 
getBroadcastInstrs(Value * V)8146 Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) { return V; }
8147 
getStepVector(Value * Val,int StartIdx,Value * Step,Instruction::BinaryOps BinOp)8148 Value *InnerLoopUnroller::getStepVector(Value *Val, int StartIdx, Value *Step,
8149                                         Instruction::BinaryOps BinOp) {
8150   // When unrolling and the VF is 1, we only need to add a simple scalar.
8151   Type *Ty = Val->getType();
8152   assert(!Ty->isVectorTy() && "Val must be a scalar");
8153 
8154   if (Ty->isFloatingPointTy()) {
8155     Constant *C = ConstantFP::get(Ty, (double)StartIdx);
8156 
8157     // Floating-point operations inherit FMF via the builder's flags.
8158     Value *MulOp = Builder.CreateFMul(C, Step);
8159     return Builder.CreateBinOp(BinOp, Val, MulOp);
8160   }
8161   Constant *C = ConstantInt::get(Ty, StartIdx);
8162   return Builder.CreateAdd(Val, Builder.CreateMul(C, Step), "induction");
8163 }
8164 
AddRuntimeUnrollDisableMetaData(Loop * L)8165 static void AddRuntimeUnrollDisableMetaData(Loop *L) {
8166   SmallVector<Metadata *, 4> MDs;
8167   // Reserve first location for self reference to the LoopID metadata node.
8168   MDs.push_back(nullptr);
8169   bool IsUnrollMetadata = false;
8170   MDNode *LoopID = L->getLoopID();
8171   if (LoopID) {
8172     // First find existing loop unrolling disable metadata.
8173     for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
8174       auto *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
8175       if (MD) {
8176         const auto *S = dyn_cast<MDString>(MD->getOperand(0));
8177         IsUnrollMetadata =
8178             S && S->getString().startswith("llvm.loop.unroll.disable");
8179       }
8180       MDs.push_back(LoopID->getOperand(i));
8181     }
8182   }
8183 
8184   if (!IsUnrollMetadata) {
8185     // Add runtime unroll disable metadata.
8186     LLVMContext &Context = L->getHeader()->getContext();
8187     SmallVector<Metadata *, 1> DisableOperands;
8188     DisableOperands.push_back(
8189         MDString::get(Context, "llvm.loop.unroll.runtime.disable"));
8190     MDNode *DisableNode = MDNode::get(Context, DisableOperands);
8191     MDs.push_back(DisableNode);
8192     MDNode *NewLoopID = MDNode::get(Context, MDs);
8193     // Set operand 0 to refer to the loop id itself.
8194     NewLoopID->replaceOperandWith(0, NewLoopID);
8195     L->setLoopID(NewLoopID);
8196   }
8197 }
8198 
8199 //===--------------------------------------------------------------------===//
8200 // EpilogueVectorizerMainLoop
8201 //===--------------------------------------------------------------------===//
8202 
8203 /// This function is partially responsible for generating the control flow
8204 /// depicted in https://llvm.org/docs/Vectorizers.html#epilogue-vectorization.
createEpilogueVectorizedLoopSkeleton()8205 BasicBlock *EpilogueVectorizerMainLoop::createEpilogueVectorizedLoopSkeleton() {
8206   MDNode *OrigLoopID = OrigLoop->getLoopID();
8207   Loop *Lp = createVectorLoopSkeleton("");
8208 
8209   // Generate the code to check the minimum iteration count of the vector
8210   // epilogue (see below).
8211   EPI.EpilogueIterationCountCheck =
8212       emitMinimumIterationCountCheck(Lp, LoopScalarPreHeader, true);
8213   EPI.EpilogueIterationCountCheck->setName("iter.check");
8214 
8215   // Generate the code to check any assumptions that we've made for SCEV
8216   // expressions.
8217   EPI.SCEVSafetyCheck = emitSCEVChecks(Lp, LoopScalarPreHeader);
8218 
8219   // Generate the code that checks at runtime if arrays overlap. We put the
8220   // checks into a separate block to make the more common case of few elements
8221   // faster.
8222   EPI.MemSafetyCheck = emitMemRuntimeChecks(Lp, LoopScalarPreHeader);
8223 
8224   // Generate the iteration count check for the main loop, *after* the check
8225   // for the epilogue loop, so that the path-length is shorter for the case
8226   // that goes directly through the vector epilogue. The longer-path length for
8227   // the main loop is compensated for, by the gain from vectorizing the larger
8228   // trip count. Note: the branch will get updated later on when we vectorize
8229   // the epilogue.
8230   EPI.MainLoopIterationCountCheck =
8231       emitMinimumIterationCountCheck(Lp, LoopScalarPreHeader, false);
8232 
8233   // Generate the induction variable.
8234   OldInduction = Legal->getPrimaryInduction();
8235   Type *IdxTy = Legal->getWidestInductionType();
8236   Value *StartIdx = ConstantInt::get(IdxTy, 0);
8237   Constant *Step = ConstantInt::get(IdxTy, VF.getKnownMinValue() * UF);
8238   Value *CountRoundDown = getOrCreateVectorTripCount(Lp);
8239   EPI.VectorTripCount = CountRoundDown;
8240   Induction =
8241       createInductionVariable(Lp, StartIdx, CountRoundDown, Step,
8242                               getDebugLocFromInstOrOperands(OldInduction));
8243 
8244   // Skip induction resume value creation here because they will be created in
8245   // the second pass. If we created them here, they wouldn't be used anyway,
8246   // because the vplan in the second pass still contains the inductions from the
8247   // original loop.
8248 
8249   return completeLoopSkeleton(Lp, OrigLoopID);
8250 }
8251 
printDebugTracesAtStart()8252 void EpilogueVectorizerMainLoop::printDebugTracesAtStart() {
8253   LLVM_DEBUG({
8254     dbgs() << "Create Skeleton for epilogue vectorized loop (first pass)\n"
8255            << "Main Loop VF:" << EPI.MainLoopVF.getKnownMinValue()
8256            << ", Main Loop UF:" << EPI.MainLoopUF
8257            << ", Epilogue Loop VF:" << EPI.EpilogueVF.getKnownMinValue()
8258            << ", Epilogue Loop UF:" << EPI.EpilogueUF << "\n";
8259   });
8260 }
8261 
printDebugTracesAtEnd()8262 void EpilogueVectorizerMainLoop::printDebugTracesAtEnd() {
8263   DEBUG_WITH_TYPE(VerboseDebug, {
8264     dbgs() << "intermediate fn:\n" << *Induction->getFunction() << "\n";
8265   });
8266 }
8267 
emitMinimumIterationCountCheck(Loop * L,BasicBlock * Bypass,bool ForEpilogue)8268 BasicBlock *EpilogueVectorizerMainLoop::emitMinimumIterationCountCheck(
8269     Loop *L, BasicBlock *Bypass, bool ForEpilogue) {
8270   assert(L && "Expected valid Loop.");
8271   assert(Bypass && "Expected valid bypass basic block.");
8272   unsigned VFactor =
8273       ForEpilogue ? EPI.EpilogueVF.getKnownMinValue() : VF.getKnownMinValue();
8274   unsigned UFactor = ForEpilogue ? EPI.EpilogueUF : UF;
8275   Value *Count = getOrCreateTripCount(L);
8276   // Reuse existing vector loop preheader for TC checks.
8277   // Note that new preheader block is generated for vector loop.
8278   BasicBlock *const TCCheckBlock = LoopVectorPreHeader;
8279   IRBuilder<> Builder(TCCheckBlock->getTerminator());
8280 
8281   // Generate code to check if the loop's trip count is less than VF * UF of the
8282   // main vector loop.
8283   auto P =
8284       Cost->requiresScalarEpilogue() ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT;
8285 
8286   Value *CheckMinIters = Builder.CreateICmp(
8287       P, Count, ConstantInt::get(Count->getType(), VFactor * UFactor),
8288       "min.iters.check");
8289 
8290   if (!ForEpilogue)
8291     TCCheckBlock->setName("vector.main.loop.iter.check");
8292 
8293   // Create new preheader for vector loop.
8294   LoopVectorPreHeader = SplitBlock(TCCheckBlock, TCCheckBlock->getTerminator(),
8295                                    DT, LI, nullptr, "vector.ph");
8296 
8297   if (ForEpilogue) {
8298     assert(DT->properlyDominates(DT->getNode(TCCheckBlock),
8299                                  DT->getNode(Bypass)->getIDom()) &&
8300            "TC check is expected to dominate Bypass");
8301 
8302     // Update dominator for Bypass & LoopExit.
8303     DT->changeImmediateDominator(Bypass, TCCheckBlock);
8304     DT->changeImmediateDominator(LoopExitBlock, TCCheckBlock);
8305 
8306     LoopBypassBlocks.push_back(TCCheckBlock);
8307 
8308     // Save the trip count so we don't have to regenerate it in the
8309     // vec.epilog.iter.check. This is safe to do because the trip count
8310     // generated here dominates the vector epilog iter check.
8311     EPI.TripCount = Count;
8312   }
8313 
8314   ReplaceInstWithInst(
8315       TCCheckBlock->getTerminator(),
8316       BranchInst::Create(Bypass, LoopVectorPreHeader, CheckMinIters));
8317 
8318   return TCCheckBlock;
8319 }
8320 
8321 //===--------------------------------------------------------------------===//
8322 // EpilogueVectorizerEpilogueLoop
8323 //===--------------------------------------------------------------------===//
8324 
8325 /// This function is partially responsible for generating the control flow
8326 /// depicted in https://llvm.org/docs/Vectorizers.html#epilogue-vectorization.
8327 BasicBlock *
createEpilogueVectorizedLoopSkeleton()8328 EpilogueVectorizerEpilogueLoop::createEpilogueVectorizedLoopSkeleton() {
8329   MDNode *OrigLoopID = OrigLoop->getLoopID();
8330   Loop *Lp = createVectorLoopSkeleton("vec.epilog.");
8331 
8332   // Now, compare the remaining count and if there aren't enough iterations to
8333   // execute the vectorized epilogue skip to the scalar part.
8334   BasicBlock *VecEpilogueIterationCountCheck = LoopVectorPreHeader;
8335   VecEpilogueIterationCountCheck->setName("vec.epilog.iter.check");
8336   LoopVectorPreHeader =
8337       SplitBlock(LoopVectorPreHeader, LoopVectorPreHeader->getTerminator(), DT,
8338                  LI, nullptr, "vec.epilog.ph");
8339   emitMinimumVectorEpilogueIterCountCheck(Lp, LoopScalarPreHeader,
8340                                           VecEpilogueIterationCountCheck);
8341 
8342   // Adjust the control flow taking the state info from the main loop
8343   // vectorization into account.
8344   assert(EPI.MainLoopIterationCountCheck && EPI.EpilogueIterationCountCheck &&
8345          "expected this to be saved from the previous pass.");
8346   EPI.MainLoopIterationCountCheck->getTerminator()->replaceUsesOfWith(
8347       VecEpilogueIterationCountCheck, LoopVectorPreHeader);
8348 
8349   DT->changeImmediateDominator(LoopVectorPreHeader,
8350                                EPI.MainLoopIterationCountCheck);
8351 
8352   EPI.EpilogueIterationCountCheck->getTerminator()->replaceUsesOfWith(
8353       VecEpilogueIterationCountCheck, LoopScalarPreHeader);
8354 
8355   if (EPI.SCEVSafetyCheck)
8356     EPI.SCEVSafetyCheck->getTerminator()->replaceUsesOfWith(
8357         VecEpilogueIterationCountCheck, LoopScalarPreHeader);
8358   if (EPI.MemSafetyCheck)
8359     EPI.MemSafetyCheck->getTerminator()->replaceUsesOfWith(
8360         VecEpilogueIterationCountCheck, LoopScalarPreHeader);
8361 
8362   DT->changeImmediateDominator(
8363       VecEpilogueIterationCountCheck,
8364       VecEpilogueIterationCountCheck->getSinglePredecessor());
8365 
8366   DT->changeImmediateDominator(LoopScalarPreHeader,
8367                                EPI.EpilogueIterationCountCheck);
8368   DT->changeImmediateDominator(LoopExitBlock, EPI.EpilogueIterationCountCheck);
8369 
8370   // Keep track of bypass blocks, as they feed start values to the induction
8371   // phis in the scalar loop preheader.
8372   if (EPI.SCEVSafetyCheck)
8373     LoopBypassBlocks.push_back(EPI.SCEVSafetyCheck);
8374   if (EPI.MemSafetyCheck)
8375     LoopBypassBlocks.push_back(EPI.MemSafetyCheck);
8376   LoopBypassBlocks.push_back(EPI.EpilogueIterationCountCheck);
8377 
8378   // Generate a resume induction for the vector epilogue and put it in the
8379   // vector epilogue preheader
8380   Type *IdxTy = Legal->getWidestInductionType();
8381   PHINode *EPResumeVal = PHINode::Create(IdxTy, 2, "vec.epilog.resume.val",
8382                                          LoopVectorPreHeader->getFirstNonPHI());
8383   EPResumeVal->addIncoming(EPI.VectorTripCount, VecEpilogueIterationCountCheck);
8384   EPResumeVal->addIncoming(ConstantInt::get(IdxTy, 0),
8385                            EPI.MainLoopIterationCountCheck);
8386 
8387   // Generate the induction variable.
8388   OldInduction = Legal->getPrimaryInduction();
8389   Value *CountRoundDown = getOrCreateVectorTripCount(Lp);
8390   Constant *Step = ConstantInt::get(IdxTy, VF.getKnownMinValue() * UF);
8391   Value *StartIdx = EPResumeVal;
8392   Induction =
8393       createInductionVariable(Lp, StartIdx, CountRoundDown, Step,
8394                               getDebugLocFromInstOrOperands(OldInduction));
8395 
8396   // Generate induction resume values. These variables save the new starting
8397   // indexes for the scalar loop. They are used to test if there are any tail
8398   // iterations left once the vector loop has completed.
8399   // Note that when the vectorized epilogue is skipped due to iteration count
8400   // check, then the resume value for the induction variable comes from
8401   // the trip count of the main vector loop, hence passing the AdditionalBypass
8402   // argument.
8403   createInductionResumeValues(Lp, CountRoundDown,
8404                               {VecEpilogueIterationCountCheck,
8405                                EPI.VectorTripCount} /* AdditionalBypass */);
8406 
8407   AddRuntimeUnrollDisableMetaData(Lp);
8408   return completeLoopSkeleton(Lp, OrigLoopID);
8409 }
8410 
8411 BasicBlock *
emitMinimumVectorEpilogueIterCountCheck(Loop * L,BasicBlock * Bypass,BasicBlock * Insert)8412 EpilogueVectorizerEpilogueLoop::emitMinimumVectorEpilogueIterCountCheck(
8413     Loop *L, BasicBlock *Bypass, BasicBlock *Insert) {
8414 
8415   assert(EPI.TripCount &&
8416          "Expected trip count to have been safed in the first pass.");
8417   assert(
8418       (!isa<Instruction>(EPI.TripCount) ||
8419        DT->dominates(cast<Instruction>(EPI.TripCount)->getParent(), Insert)) &&
8420       "saved trip count does not dominate insertion point.");
8421   Value *TC = EPI.TripCount;
8422   IRBuilder<> Builder(Insert->getTerminator());
8423   Value *Count = Builder.CreateSub(TC, EPI.VectorTripCount, "n.vec.remaining");
8424 
8425   // Generate code to check if the loop's trip count is less than VF * UF of the
8426   // vector epilogue loop.
8427   auto P =
8428       Cost->requiresScalarEpilogue() ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT;
8429 
8430   Value *CheckMinIters = Builder.CreateICmp(
8431       P, Count,
8432       ConstantInt::get(Count->getType(),
8433                        EPI.EpilogueVF.getKnownMinValue() * EPI.EpilogueUF),
8434       "min.epilog.iters.check");
8435 
8436   ReplaceInstWithInst(
8437       Insert->getTerminator(),
8438       BranchInst::Create(Bypass, LoopVectorPreHeader, CheckMinIters));
8439 
8440   LoopBypassBlocks.push_back(Insert);
8441   return Insert;
8442 }
8443 
printDebugTracesAtStart()8444 void EpilogueVectorizerEpilogueLoop::printDebugTracesAtStart() {
8445   LLVM_DEBUG({
8446     dbgs() << "Create Skeleton for epilogue vectorized loop (second pass)\n"
8447            << "Main Loop VF:" << EPI.MainLoopVF.getKnownMinValue()
8448            << ", Main Loop UF:" << EPI.MainLoopUF
8449            << ", Epilogue Loop VF:" << EPI.EpilogueVF.getKnownMinValue()
8450            << ", Epilogue Loop UF:" << EPI.EpilogueUF << "\n";
8451   });
8452 }
8453 
printDebugTracesAtEnd()8454 void EpilogueVectorizerEpilogueLoop::printDebugTracesAtEnd() {
8455   DEBUG_WITH_TYPE(VerboseDebug, {
8456     dbgs() << "final fn:\n" << *Induction->getFunction() << "\n";
8457   });
8458 }
8459 
getDecisionAndClampRange(const std::function<bool (ElementCount)> & Predicate,VFRange & Range)8460 bool LoopVectorizationPlanner::getDecisionAndClampRange(
8461     const std::function<bool(ElementCount)> &Predicate, VFRange &Range) {
8462   assert(!Range.isEmpty() && "Trying to test an empty VF range.");
8463   bool PredicateAtRangeStart = Predicate(Range.Start);
8464 
8465   for (ElementCount TmpVF = Range.Start * 2;
8466        ElementCount::isKnownLT(TmpVF, Range.End); TmpVF *= 2)
8467     if (Predicate(TmpVF) != PredicateAtRangeStart) {
8468       Range.End = TmpVF;
8469       break;
8470     }
8471 
8472   return PredicateAtRangeStart;
8473 }
8474 
8475 /// Build VPlans for the full range of feasible VF's = {\p MinVF, 2 * \p MinVF,
8476 /// 4 * \p MinVF, ..., \p MaxVF} by repeatedly building a VPlan for a sub-range
8477 /// of VF's starting at a given VF and extending it as much as possible. Each
8478 /// vectorization decision can potentially shorten this sub-range during
8479 /// buildVPlan().
buildVPlans(ElementCount MinVF,ElementCount MaxVF)8480 void LoopVectorizationPlanner::buildVPlans(ElementCount MinVF,
8481                                            ElementCount MaxVF) {
8482   auto MaxVFPlusOne = MaxVF.getWithIncrement(1);
8483   for (ElementCount VF = MinVF; ElementCount::isKnownLT(VF, MaxVFPlusOne);) {
8484     VFRange SubRange = {VF, MaxVFPlusOne};
8485     VPlans.push_back(buildVPlan(SubRange));
8486     VF = SubRange.End;
8487   }
8488 }
8489 
createEdgeMask(BasicBlock * Src,BasicBlock * Dst,VPlanPtr & Plan)8490 VPValue *VPRecipeBuilder::createEdgeMask(BasicBlock *Src, BasicBlock *Dst,
8491                                          VPlanPtr &Plan) {
8492   assert(is_contained(predecessors(Dst), Src) && "Invalid edge");
8493 
8494   // Look for cached value.
8495   std::pair<BasicBlock *, BasicBlock *> Edge(Src, Dst);
8496   EdgeMaskCacheTy::iterator ECEntryIt = EdgeMaskCache.find(Edge);
8497   if (ECEntryIt != EdgeMaskCache.end())
8498     return ECEntryIt->second;
8499 
8500   VPValue *SrcMask = createBlockInMask(Src, Plan);
8501 
8502   // The terminator has to be a branch inst!
8503   BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
8504   assert(BI && "Unexpected terminator found");
8505 
8506   if (!BI->isConditional() || BI->getSuccessor(0) == BI->getSuccessor(1))
8507     return EdgeMaskCache[Edge] = SrcMask;
8508 
8509   // If source is an exiting block, we know the exit edge is dynamically dead
8510   // in the vector loop, and thus we don't need to restrict the mask.  Avoid
8511   // adding uses of an otherwise potentially dead instruction.
8512   if (OrigLoop->isLoopExiting(Src))
8513     return EdgeMaskCache[Edge] = SrcMask;
8514 
8515   VPValue *EdgeMask = Plan->getOrAddVPValue(BI->getCondition());
8516   assert(EdgeMask && "No Edge Mask found for condition");
8517 
8518   if (BI->getSuccessor(0) != Dst)
8519     EdgeMask = Builder.createNot(EdgeMask);
8520 
8521   if (SrcMask) { // Otherwise block in-mask is all-one, no need to AND.
8522     // The condition is 'SrcMask && EdgeMask', which is equivalent to
8523     // 'select i1 SrcMask, i1 EdgeMask, i1 false'.
8524     // The select version does not introduce new UB if SrcMask is false and
8525     // EdgeMask is poison. Using 'and' here introduces undefined behavior.
8526     VPValue *False = Plan->getOrAddVPValue(
8527         ConstantInt::getFalse(BI->getCondition()->getType()));
8528     EdgeMask = Builder.createSelect(SrcMask, EdgeMask, False);
8529   }
8530 
8531   return EdgeMaskCache[Edge] = EdgeMask;
8532 }
8533 
createBlockInMask(BasicBlock * BB,VPlanPtr & Plan)8534 VPValue *VPRecipeBuilder::createBlockInMask(BasicBlock *BB, VPlanPtr &Plan) {
8535   assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
8536 
8537   // Look for cached value.
8538   BlockMaskCacheTy::iterator BCEntryIt = BlockMaskCache.find(BB);
8539   if (BCEntryIt != BlockMaskCache.end())
8540     return BCEntryIt->second;
8541 
8542   // All-one mask is modelled as no-mask following the convention for masked
8543   // load/store/gather/scatter. Initialize BlockMask to no-mask.
8544   VPValue *BlockMask = nullptr;
8545 
8546   if (OrigLoop->getHeader() == BB) {
8547     if (!CM.blockNeedsPredication(BB))
8548       return BlockMaskCache[BB] = BlockMask; // Loop incoming mask is all-one.
8549 
8550     // Create the block in mask as the first non-phi instruction in the block.
8551     VPBuilder::InsertPointGuard Guard(Builder);
8552     auto NewInsertionPoint = Builder.getInsertBlock()->getFirstNonPhi();
8553     Builder.setInsertPoint(Builder.getInsertBlock(), NewInsertionPoint);
8554 
8555     // Introduce the early-exit compare IV <= BTC to form header block mask.
8556     // This is used instead of IV < TC because TC may wrap, unlike BTC.
8557     // Start by constructing the desired canonical IV.
8558     VPValue *IV = nullptr;
8559     if (Legal->getPrimaryInduction())
8560       IV = Plan->getOrAddVPValue(Legal->getPrimaryInduction());
8561     else {
8562       auto IVRecipe = new VPWidenCanonicalIVRecipe();
8563       Builder.getInsertBlock()->insert(IVRecipe, NewInsertionPoint);
8564       IV = IVRecipe->getVPSingleValue();
8565     }
8566     VPValue *BTC = Plan->getOrCreateBackedgeTakenCount();
8567     bool TailFolded = !CM.isScalarEpilogueAllowed();
8568 
8569     if (TailFolded && CM.TTI.emitGetActiveLaneMask()) {
8570       // While ActiveLaneMask is a binary op that consumes the loop tripcount
8571       // as a second argument, we only pass the IV here and extract the
8572       // tripcount from the transform state where codegen of the VP instructions
8573       // happen.
8574       BlockMask = Builder.createNaryOp(VPInstruction::ActiveLaneMask, {IV});
8575     } else {
8576       BlockMask = Builder.createNaryOp(VPInstruction::ICmpULE, {IV, BTC});
8577     }
8578     return BlockMaskCache[BB] = BlockMask;
8579   }
8580 
8581   // This is the block mask. We OR all incoming edges.
8582   for (auto *Predecessor : predecessors(BB)) {
8583     VPValue *EdgeMask = createEdgeMask(Predecessor, BB, Plan);
8584     if (!EdgeMask) // Mask of predecessor is all-one so mask of block is too.
8585       return BlockMaskCache[BB] = EdgeMask;
8586 
8587     if (!BlockMask) { // BlockMask has its initialized nullptr value.
8588       BlockMask = EdgeMask;
8589       continue;
8590     }
8591 
8592     BlockMask = Builder.createOr(BlockMask, EdgeMask);
8593   }
8594 
8595   return BlockMaskCache[BB] = BlockMask;
8596 }
8597 
tryToWidenMemory(Instruction * I,ArrayRef<VPValue * > Operands,VFRange & Range,VPlanPtr & Plan)8598 VPRecipeBase *VPRecipeBuilder::tryToWidenMemory(Instruction *I,
8599                                                 ArrayRef<VPValue *> Operands,
8600                                                 VFRange &Range,
8601                                                 VPlanPtr &Plan) {
8602   assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
8603          "Must be called with either a load or store");
8604 
8605   auto willWiden = [&](ElementCount VF) -> bool {
8606     if (VF.isScalar())
8607       return false;
8608     LoopVectorizationCostModel::InstWidening Decision =
8609         CM.getWideningDecision(I, VF);
8610     assert(Decision != LoopVectorizationCostModel::CM_Unknown &&
8611            "CM decision should be taken at this point.");
8612     if (Decision == LoopVectorizationCostModel::CM_Interleave)
8613       return true;
8614     if (CM.isScalarAfterVectorization(I, VF) ||
8615         CM.isProfitableToScalarize(I, VF))
8616       return false;
8617     return Decision != LoopVectorizationCostModel::CM_Scalarize;
8618   };
8619 
8620   if (!LoopVectorizationPlanner::getDecisionAndClampRange(willWiden, Range))
8621     return nullptr;
8622 
8623   VPValue *Mask = nullptr;
8624   if (Legal->isMaskRequired(I))
8625     Mask = createBlockInMask(I->getParent(), Plan);
8626 
8627   if (LoadInst *Load = dyn_cast<LoadInst>(I))
8628     return new VPWidenMemoryInstructionRecipe(*Load, Operands[0], Mask);
8629 
8630   StoreInst *Store = cast<StoreInst>(I);
8631   return new VPWidenMemoryInstructionRecipe(*Store, Operands[1], Operands[0],
8632                                             Mask);
8633 }
8634 
8635 VPWidenIntOrFpInductionRecipe *
tryToOptimizeInductionPHI(PHINode * Phi,ArrayRef<VPValue * > Operands) const8636 VPRecipeBuilder::tryToOptimizeInductionPHI(PHINode *Phi,
8637                                            ArrayRef<VPValue *> Operands) const {
8638   // Check if this is an integer or fp induction. If so, build the recipe that
8639   // produces its scalar and vector values.
8640   InductionDescriptor II = Legal->getInductionVars().lookup(Phi);
8641   if (II.getKind() == InductionDescriptor::IK_IntInduction ||
8642       II.getKind() == InductionDescriptor::IK_FpInduction) {
8643     assert(II.getStartValue() ==
8644            Phi->getIncomingValueForBlock(OrigLoop->getLoopPreheader()));
8645     const SmallVectorImpl<Instruction *> &Casts = II.getCastInsts();
8646     return new VPWidenIntOrFpInductionRecipe(
8647         Phi, Operands[0], Casts.empty() ? nullptr : Casts.front());
8648   }
8649 
8650   return nullptr;
8651 }
8652 
tryToOptimizeInductionTruncate(TruncInst * I,ArrayRef<VPValue * > Operands,VFRange & Range,VPlan & Plan) const8653 VPWidenIntOrFpInductionRecipe *VPRecipeBuilder::tryToOptimizeInductionTruncate(
8654     TruncInst *I, ArrayRef<VPValue *> Operands, VFRange &Range,
8655     VPlan &Plan) const {
8656   // Optimize the special case where the source is a constant integer
8657   // induction variable. Notice that we can only optimize the 'trunc' case
8658   // because (a) FP conversions lose precision, (b) sext/zext may wrap, and
8659   // (c) other casts depend on pointer size.
8660 
8661   // Determine whether \p K is a truncation based on an induction variable that
8662   // can be optimized.
8663   auto isOptimizableIVTruncate =
8664       [&](Instruction *K) -> std::function<bool(ElementCount)> {
8665     return [=](ElementCount VF) -> bool {
8666       return CM.isOptimizableIVTruncate(K, VF);
8667     };
8668   };
8669 
8670   if (LoopVectorizationPlanner::getDecisionAndClampRange(
8671           isOptimizableIVTruncate(I), Range)) {
8672 
8673     InductionDescriptor II =
8674         Legal->getInductionVars().lookup(cast<PHINode>(I->getOperand(0)));
8675     VPValue *Start = Plan.getOrAddVPValue(II.getStartValue());
8676     return new VPWidenIntOrFpInductionRecipe(cast<PHINode>(I->getOperand(0)),
8677                                              Start, nullptr, I);
8678   }
8679   return nullptr;
8680 }
8681 
tryToBlend(PHINode * Phi,ArrayRef<VPValue * > Operands,VPlanPtr & Plan)8682 VPRecipeOrVPValueTy VPRecipeBuilder::tryToBlend(PHINode *Phi,
8683                                                 ArrayRef<VPValue *> Operands,
8684                                                 VPlanPtr &Plan) {
8685   // If all incoming values are equal, the incoming VPValue can be used directly
8686   // instead of creating a new VPBlendRecipe.
8687   VPValue *FirstIncoming = Operands[0];
8688   if (all_of(Operands, [FirstIncoming](const VPValue *Inc) {
8689         return FirstIncoming == Inc;
8690       })) {
8691     return Operands[0];
8692   }
8693 
8694   // We know that all PHIs in non-header blocks are converted into selects, so
8695   // we don't have to worry about the insertion order and we can just use the
8696   // builder. At this point we generate the predication tree. There may be
8697   // duplications since this is a simple recursive scan, but future
8698   // optimizations will clean it up.
8699   SmallVector<VPValue *, 2> OperandsWithMask;
8700   unsigned NumIncoming = Phi->getNumIncomingValues();
8701 
8702   for (unsigned In = 0; In < NumIncoming; In++) {
8703     VPValue *EdgeMask =
8704       createEdgeMask(Phi->getIncomingBlock(In), Phi->getParent(), Plan);
8705     assert((EdgeMask || NumIncoming == 1) &&
8706            "Multiple predecessors with one having a full mask");
8707     OperandsWithMask.push_back(Operands[In]);
8708     if (EdgeMask)
8709       OperandsWithMask.push_back(EdgeMask);
8710   }
8711   return toVPRecipeResult(new VPBlendRecipe(Phi, OperandsWithMask));
8712 }
8713 
tryToWidenCall(CallInst * CI,ArrayRef<VPValue * > Operands,VFRange & Range) const8714 VPWidenCallRecipe *VPRecipeBuilder::tryToWidenCall(CallInst *CI,
8715                                                    ArrayRef<VPValue *> Operands,
8716                                                    VFRange &Range) const {
8717 
8718   bool IsPredicated = LoopVectorizationPlanner::getDecisionAndClampRange(
8719       [this, CI](ElementCount VF) { return CM.isScalarWithPredication(CI); },
8720       Range);
8721 
8722   if (IsPredicated)
8723     return nullptr;
8724 
8725   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
8726   if (ID && (ID == Intrinsic::assume || ID == Intrinsic::lifetime_end ||
8727              ID == Intrinsic::lifetime_start || ID == Intrinsic::sideeffect ||
8728              ID == Intrinsic::pseudoprobe ||
8729              ID == Intrinsic::experimental_noalias_scope_decl))
8730     return nullptr;
8731 
8732   auto willWiden = [&](ElementCount VF) -> bool {
8733     Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
8734     // The following case may be scalarized depending on the VF.
8735     // The flag shows whether we use Intrinsic or a usual Call for vectorized
8736     // version of the instruction.
8737     // Is it beneficial to perform intrinsic call compared to lib call?
8738     bool NeedToScalarize = false;
8739     InstructionCost CallCost = CM.getVectorCallCost(CI, VF, NeedToScalarize);
8740     InstructionCost IntrinsicCost = ID ? CM.getVectorIntrinsicCost(CI, VF) : 0;
8741     bool UseVectorIntrinsic = ID && IntrinsicCost <= CallCost;
8742     assert((IntrinsicCost.isValid() || CallCost.isValid()) &&
8743            "Either the intrinsic cost or vector call cost must be valid");
8744     return UseVectorIntrinsic || !NeedToScalarize;
8745   };
8746 
8747   if (!LoopVectorizationPlanner::getDecisionAndClampRange(willWiden, Range))
8748     return nullptr;
8749 
8750   ArrayRef<VPValue *> Ops = Operands.take_front(CI->getNumArgOperands());
8751   return new VPWidenCallRecipe(*CI, make_range(Ops.begin(), Ops.end()));
8752 }
8753 
shouldWiden(Instruction * I,VFRange & Range) const8754 bool VPRecipeBuilder::shouldWiden(Instruction *I, VFRange &Range) const {
8755   assert(!isa<BranchInst>(I) && !isa<PHINode>(I) && !isa<LoadInst>(I) &&
8756          !isa<StoreInst>(I) && "Instruction should have been handled earlier");
8757   // Instruction should be widened, unless it is scalar after vectorization,
8758   // scalarization is profitable or it is predicated.
8759   auto WillScalarize = [this, I](ElementCount VF) -> bool {
8760     return CM.isScalarAfterVectorization(I, VF) ||
8761            CM.isProfitableToScalarize(I, VF) || CM.isScalarWithPredication(I);
8762   };
8763   return !LoopVectorizationPlanner::getDecisionAndClampRange(WillScalarize,
8764                                                              Range);
8765 }
8766 
tryToWiden(Instruction * I,ArrayRef<VPValue * > Operands) const8767 VPWidenRecipe *VPRecipeBuilder::tryToWiden(Instruction *I,
8768                                            ArrayRef<VPValue *> Operands) const {
8769   auto IsVectorizableOpcode = [](unsigned Opcode) {
8770     switch (Opcode) {
8771     case Instruction::Add:
8772     case Instruction::And:
8773     case Instruction::AShr:
8774     case Instruction::BitCast:
8775     case Instruction::FAdd:
8776     case Instruction::FCmp:
8777     case Instruction::FDiv:
8778     case Instruction::FMul:
8779     case Instruction::FNeg:
8780     case Instruction::FPExt:
8781     case Instruction::FPToSI:
8782     case Instruction::FPToUI:
8783     case Instruction::FPTrunc:
8784     case Instruction::FRem:
8785     case Instruction::FSub:
8786     case Instruction::ICmp:
8787     case Instruction::IntToPtr:
8788     case Instruction::LShr:
8789     case Instruction::Mul:
8790     case Instruction::Or:
8791     case Instruction::PtrToInt:
8792     case Instruction::SDiv:
8793     case Instruction::Select:
8794     case Instruction::SExt:
8795     case Instruction::Shl:
8796     case Instruction::SIToFP:
8797     case Instruction::SRem:
8798     case Instruction::Sub:
8799     case Instruction::Trunc:
8800     case Instruction::UDiv:
8801     case Instruction::UIToFP:
8802     case Instruction::URem:
8803     case Instruction::Xor:
8804     case Instruction::ZExt:
8805       return true;
8806     }
8807     return false;
8808   };
8809 
8810   if (!IsVectorizableOpcode(I->getOpcode()))
8811     return nullptr;
8812 
8813   // Success: widen this instruction.
8814   return new VPWidenRecipe(*I, make_range(Operands.begin(), Operands.end()));
8815 }
8816 
fixHeaderPhis()8817 void VPRecipeBuilder::fixHeaderPhis() {
8818   BasicBlock *OrigLatch = OrigLoop->getLoopLatch();
8819   for (VPWidenPHIRecipe *R : PhisToFix) {
8820     auto *PN = cast<PHINode>(R->getUnderlyingValue());
8821     VPRecipeBase *IncR =
8822         getRecipe(cast<Instruction>(PN->getIncomingValueForBlock(OrigLatch)));
8823     R->addOperand(IncR->getVPSingleValue());
8824   }
8825 }
8826 
handleReplication(Instruction * I,VFRange & Range,VPBasicBlock * VPBB,VPlanPtr & Plan)8827 VPBasicBlock *VPRecipeBuilder::handleReplication(
8828     Instruction *I, VFRange &Range, VPBasicBlock *VPBB,
8829     VPlanPtr &Plan) {
8830   bool IsUniform = LoopVectorizationPlanner::getDecisionAndClampRange(
8831       [&](ElementCount VF) { return CM.isUniformAfterVectorization(I, VF); },
8832       Range);
8833 
8834   bool IsPredicated = LoopVectorizationPlanner::getDecisionAndClampRange(
8835       [&](ElementCount VF) { return CM.isPredicatedInst(I); }, Range);
8836 
8837   auto *Recipe = new VPReplicateRecipe(I, Plan->mapToVPValues(I->operands()),
8838                                        IsUniform, IsPredicated);
8839   setRecipe(I, Recipe);
8840   Plan->addVPValue(I, Recipe);
8841 
8842   // Find if I uses a predicated instruction. If so, it will use its scalar
8843   // value. Avoid hoisting the insert-element which packs the scalar value into
8844   // a vector value, as that happens iff all users use the vector value.
8845   for (VPValue *Op : Recipe->operands()) {
8846     auto *PredR = dyn_cast_or_null<VPPredInstPHIRecipe>(Op->getDef());
8847     if (!PredR)
8848       continue;
8849     auto *RepR =
8850         cast_or_null<VPReplicateRecipe>(PredR->getOperand(0)->getDef());
8851     assert(RepR->isPredicated() &&
8852            "expected Replicate recipe to be predicated");
8853     RepR->setAlsoPack(false);
8854   }
8855 
8856   // Finalize the recipe for Instr, first if it is not predicated.
8857   if (!IsPredicated) {
8858     LLVM_DEBUG(dbgs() << "LV: Scalarizing:" << *I << "\n");
8859     VPBB->appendRecipe(Recipe);
8860     return VPBB;
8861   }
8862   LLVM_DEBUG(dbgs() << "LV: Scalarizing and predicating:" << *I << "\n");
8863   assert(VPBB->getSuccessors().empty() &&
8864          "VPBB has successors when handling predicated replication.");
8865   // Record predicated instructions for above packing optimizations.
8866   VPBlockBase *Region = createReplicateRegion(I, Recipe, Plan);
8867   VPBlockUtils::insertBlockAfter(Region, VPBB);
8868   auto *RegSucc = new VPBasicBlock();
8869   VPBlockUtils::insertBlockAfter(RegSucc, Region);
8870   return RegSucc;
8871 }
8872 
createReplicateRegion(Instruction * Instr,VPRecipeBase * PredRecipe,VPlanPtr & Plan)8873 VPRegionBlock *VPRecipeBuilder::createReplicateRegion(Instruction *Instr,
8874                                                       VPRecipeBase *PredRecipe,
8875                                                       VPlanPtr &Plan) {
8876   // Instructions marked for predication are replicated and placed under an
8877   // if-then construct to prevent side-effects.
8878 
8879   // Generate recipes to compute the block mask for this region.
8880   VPValue *BlockInMask = createBlockInMask(Instr->getParent(), Plan);
8881 
8882   // Build the triangular if-then region.
8883   std::string RegionName = (Twine("pred.") + Instr->getOpcodeName()).str();
8884   assert(Instr->getParent() && "Predicated instruction not in any basic block");
8885   auto *BOMRecipe = new VPBranchOnMaskRecipe(BlockInMask);
8886   auto *Entry = new VPBasicBlock(Twine(RegionName) + ".entry", BOMRecipe);
8887   auto *PHIRecipe = Instr->getType()->isVoidTy()
8888                         ? nullptr
8889                         : new VPPredInstPHIRecipe(Plan->getOrAddVPValue(Instr));
8890   if (PHIRecipe) {
8891     Plan->removeVPValueFor(Instr);
8892     Plan->addVPValue(Instr, PHIRecipe);
8893   }
8894   auto *Exit = new VPBasicBlock(Twine(RegionName) + ".continue", PHIRecipe);
8895   auto *Pred = new VPBasicBlock(Twine(RegionName) + ".if", PredRecipe);
8896   VPRegionBlock *Region = new VPRegionBlock(Entry, Exit, RegionName, true);
8897 
8898   // Note: first set Entry as region entry and then connect successors starting
8899   // from it in order, to propagate the "parent" of each VPBasicBlock.
8900   VPBlockUtils::insertTwoBlocksAfter(Pred, Exit, BlockInMask, Entry);
8901   VPBlockUtils::connectBlocks(Pred, Exit);
8902 
8903   return Region;
8904 }
8905 
8906 VPRecipeOrVPValueTy
tryToCreateWidenRecipe(Instruction * Instr,ArrayRef<VPValue * > Operands,VFRange & Range,VPlanPtr & Plan)8907 VPRecipeBuilder::tryToCreateWidenRecipe(Instruction *Instr,
8908                                         ArrayRef<VPValue *> Operands,
8909                                         VFRange &Range, VPlanPtr &Plan) {
8910   // First, check for specific widening recipes that deal with calls, memory
8911   // operations, inductions and Phi nodes.
8912   if (auto *CI = dyn_cast<CallInst>(Instr))
8913     return toVPRecipeResult(tryToWidenCall(CI, Operands, Range));
8914 
8915   if (isa<LoadInst>(Instr) || isa<StoreInst>(Instr))
8916     return toVPRecipeResult(tryToWidenMemory(Instr, Operands, Range, Plan));
8917 
8918   VPRecipeBase *Recipe;
8919   if (auto Phi = dyn_cast<PHINode>(Instr)) {
8920     if (Phi->getParent() != OrigLoop->getHeader())
8921       return tryToBlend(Phi, Operands, Plan);
8922     if ((Recipe = tryToOptimizeInductionPHI(Phi, Operands)))
8923       return toVPRecipeResult(Recipe);
8924 
8925     if (Legal->isReductionVariable(Phi)) {
8926       RecurrenceDescriptor &RdxDesc = Legal->getReductionVars()[Phi];
8927       assert(RdxDesc.getRecurrenceStartValue() ==
8928              Phi->getIncomingValueForBlock(OrigLoop->getLoopPreheader()));
8929       VPValue *StartV = Operands[0];
8930 
8931       auto *PhiRecipe = new VPWidenPHIRecipe(Phi, RdxDesc, *StartV);
8932       PhisToFix.push_back(PhiRecipe);
8933       // Record the incoming value from the backedge, so we can add the incoming
8934       // value from the backedge after all recipes have been created.
8935       recordRecipeOf(cast<Instruction>(
8936           Phi->getIncomingValueForBlock(OrigLoop->getLoopLatch())));
8937       return toVPRecipeResult(PhiRecipe);
8938     }
8939 
8940     return toVPRecipeResult(new VPWidenPHIRecipe(Phi));
8941   }
8942 
8943   if (isa<TruncInst>(Instr) &&
8944       (Recipe = tryToOptimizeInductionTruncate(cast<TruncInst>(Instr), Operands,
8945                                                Range, *Plan)))
8946     return toVPRecipeResult(Recipe);
8947 
8948   if (!shouldWiden(Instr, Range))
8949     return nullptr;
8950 
8951   if (auto GEP = dyn_cast<GetElementPtrInst>(Instr))
8952     return toVPRecipeResult(new VPWidenGEPRecipe(
8953         GEP, make_range(Operands.begin(), Operands.end()), OrigLoop));
8954 
8955   if (auto *SI = dyn_cast<SelectInst>(Instr)) {
8956     bool InvariantCond =
8957         PSE.getSE()->isLoopInvariant(PSE.getSCEV(SI->getOperand(0)), OrigLoop);
8958     return toVPRecipeResult(new VPWidenSelectRecipe(
8959         *SI, make_range(Operands.begin(), Operands.end()), InvariantCond));
8960   }
8961 
8962   return toVPRecipeResult(tryToWiden(Instr, Operands));
8963 }
8964 
buildVPlansWithVPRecipes(ElementCount MinVF,ElementCount MaxVF)8965 void LoopVectorizationPlanner::buildVPlansWithVPRecipes(ElementCount MinVF,
8966                                                         ElementCount MaxVF) {
8967   assert(OrigLoop->isInnermost() && "Inner loop expected.");
8968 
8969   // Collect instructions from the original loop that will become trivially dead
8970   // in the vectorized loop. We don't need to vectorize these instructions. For
8971   // example, original induction update instructions can become dead because we
8972   // separately emit induction "steps" when generating code for the new loop.
8973   // Similarly, we create a new latch condition when setting up the structure
8974   // of the new loop, so the old one can become dead.
8975   SmallPtrSet<Instruction *, 4> DeadInstructions;
8976   collectTriviallyDeadInstructions(DeadInstructions);
8977 
8978   // Add assume instructions we need to drop to DeadInstructions, to prevent
8979   // them from being added to the VPlan.
8980   // TODO: We only need to drop assumes in blocks that get flattend. If the
8981   // control flow is preserved, we should keep them.
8982   auto &ConditionalAssumes = Legal->getConditionalAssumes();
8983   DeadInstructions.insert(ConditionalAssumes.begin(), ConditionalAssumes.end());
8984 
8985   DenseMap<Instruction *, Instruction *> &SinkAfter = Legal->getSinkAfter();
8986   // Dead instructions do not need sinking. Remove them from SinkAfter.
8987   for (Instruction *I : DeadInstructions)
8988     SinkAfter.erase(I);
8989 
8990   auto MaxVFPlusOne = MaxVF.getWithIncrement(1);
8991   for (ElementCount VF = MinVF; ElementCount::isKnownLT(VF, MaxVFPlusOne);) {
8992     VFRange SubRange = {VF, MaxVFPlusOne};
8993     VPlans.push_back(
8994         buildVPlanWithVPRecipes(SubRange, DeadInstructions, SinkAfter));
8995     VF = SubRange.End;
8996   }
8997 }
8998 
buildVPlanWithVPRecipes(VFRange & Range,SmallPtrSetImpl<Instruction * > & DeadInstructions,const DenseMap<Instruction *,Instruction * > & SinkAfter)8999 VPlanPtr LoopVectorizationPlanner::buildVPlanWithVPRecipes(
9000     VFRange &Range, SmallPtrSetImpl<Instruction *> &DeadInstructions,
9001     const DenseMap<Instruction *, Instruction *> &SinkAfter) {
9002 
9003   SmallPtrSet<const InterleaveGroup<Instruction> *, 1> InterleaveGroups;
9004 
9005   VPRecipeBuilder RecipeBuilder(OrigLoop, TLI, Legal, CM, PSE, Builder);
9006 
9007   // ---------------------------------------------------------------------------
9008   // Pre-construction: record ingredients whose recipes we'll need to further
9009   // process after constructing the initial VPlan.
9010   // ---------------------------------------------------------------------------
9011 
9012   // Mark instructions we'll need to sink later and their targets as
9013   // ingredients whose recipe we'll need to record.
9014   for (auto &Entry : SinkAfter) {
9015     RecipeBuilder.recordRecipeOf(Entry.first);
9016     RecipeBuilder.recordRecipeOf(Entry.second);
9017   }
9018   for (auto &Reduction : CM.getInLoopReductionChains()) {
9019     PHINode *Phi = Reduction.first;
9020     RecurKind Kind = Legal->getReductionVars()[Phi].getRecurrenceKind();
9021     const SmallVector<Instruction *, 4> &ReductionOperations = Reduction.second;
9022 
9023     RecipeBuilder.recordRecipeOf(Phi);
9024     for (auto &R : ReductionOperations) {
9025       RecipeBuilder.recordRecipeOf(R);
9026       // For min/max reducitons, where we have a pair of icmp/select, we also
9027       // need to record the ICmp recipe, so it can be removed later.
9028       if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind))
9029         RecipeBuilder.recordRecipeOf(cast<Instruction>(R->getOperand(0)));
9030     }
9031   }
9032 
9033   // For each interleave group which is relevant for this (possibly trimmed)
9034   // Range, add it to the set of groups to be later applied to the VPlan and add
9035   // placeholders for its members' Recipes which we'll be replacing with a
9036   // single VPInterleaveRecipe.
9037   for (InterleaveGroup<Instruction> *IG : IAI.getInterleaveGroups()) {
9038     auto applyIG = [IG, this](ElementCount VF) -> bool {
9039       return (VF.isVector() && // Query is illegal for VF == 1
9040               CM.getWideningDecision(IG->getInsertPos(), VF) ==
9041                   LoopVectorizationCostModel::CM_Interleave);
9042     };
9043     if (!getDecisionAndClampRange(applyIG, Range))
9044       continue;
9045     InterleaveGroups.insert(IG);
9046     for (unsigned i = 0; i < IG->getFactor(); i++)
9047       if (Instruction *Member = IG->getMember(i))
9048         RecipeBuilder.recordRecipeOf(Member);
9049   };
9050 
9051   // ---------------------------------------------------------------------------
9052   // Build initial VPlan: Scan the body of the loop in a topological order to
9053   // visit each basic block after having visited its predecessor basic blocks.
9054   // ---------------------------------------------------------------------------
9055 
9056   // Create a dummy pre-entry VPBasicBlock to start building the VPlan.
9057   auto Plan = std::make_unique<VPlan>();
9058   VPBasicBlock *VPBB = new VPBasicBlock("Pre-Entry");
9059   Plan->setEntry(VPBB);
9060 
9061   // Scan the body of the loop in a topological order to visit each basic block
9062   // after having visited its predecessor basic blocks.
9063   LoopBlocksDFS DFS(OrigLoop);
9064   DFS.perform(LI);
9065 
9066   for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) {
9067     // Relevant instructions from basic block BB will be grouped into VPRecipe
9068     // ingredients and fill a new VPBasicBlock.
9069     unsigned VPBBsForBB = 0;
9070     auto *FirstVPBBForBB = new VPBasicBlock(BB->getName());
9071     VPBlockUtils::insertBlockAfter(FirstVPBBForBB, VPBB);
9072     VPBB = FirstVPBBForBB;
9073     Builder.setInsertPoint(VPBB);
9074 
9075     // Introduce each ingredient into VPlan.
9076     // TODO: Model and preserve debug instrinsics in VPlan.
9077     for (Instruction &I : BB->instructionsWithoutDebug()) {
9078       Instruction *Instr = &I;
9079 
9080       // First filter out irrelevant instructions, to ensure no recipes are
9081       // built for them.
9082       if (isa<BranchInst>(Instr) || DeadInstructions.count(Instr))
9083         continue;
9084 
9085       SmallVector<VPValue *, 4> Operands;
9086       auto *Phi = dyn_cast<PHINode>(Instr);
9087       if (Phi && Phi->getParent() == OrigLoop->getHeader()) {
9088         Operands.push_back(Plan->getOrAddVPValue(
9089             Phi->getIncomingValueForBlock(OrigLoop->getLoopPreheader())));
9090       } else {
9091         auto OpRange = Plan->mapToVPValues(Instr->operands());
9092         Operands = {OpRange.begin(), OpRange.end()};
9093       }
9094       if (auto RecipeOrValue = RecipeBuilder.tryToCreateWidenRecipe(
9095               Instr, Operands, Range, Plan)) {
9096         // If Instr can be simplified to an existing VPValue, use it.
9097         if (RecipeOrValue.is<VPValue *>()) {
9098           auto *VPV = RecipeOrValue.get<VPValue *>();
9099           Plan->addVPValue(Instr, VPV);
9100           // If the re-used value is a recipe, register the recipe for the
9101           // instruction, in case the recipe for Instr needs to be recorded.
9102           if (auto *R = dyn_cast_or_null<VPRecipeBase>(VPV->getDef()))
9103             RecipeBuilder.setRecipe(Instr, R);
9104           continue;
9105         }
9106         // Otherwise, add the new recipe.
9107         VPRecipeBase *Recipe = RecipeOrValue.get<VPRecipeBase *>();
9108         for (auto *Def : Recipe->definedValues()) {
9109           auto *UV = Def->getUnderlyingValue();
9110           Plan->addVPValue(UV, Def);
9111         }
9112 
9113         RecipeBuilder.setRecipe(Instr, Recipe);
9114         VPBB->appendRecipe(Recipe);
9115         continue;
9116       }
9117 
9118       // Otherwise, if all widening options failed, Instruction is to be
9119       // replicated. This may create a successor for VPBB.
9120       VPBasicBlock *NextVPBB =
9121           RecipeBuilder.handleReplication(Instr, Range, VPBB, Plan);
9122       if (NextVPBB != VPBB) {
9123         VPBB = NextVPBB;
9124         VPBB->setName(BB->hasName() ? BB->getName() + "." + Twine(VPBBsForBB++)
9125                                     : "");
9126       }
9127     }
9128   }
9129 
9130   RecipeBuilder.fixHeaderPhis();
9131 
9132   // Discard empty dummy pre-entry VPBasicBlock. Note that other VPBasicBlocks
9133   // may also be empty, such as the last one VPBB, reflecting original
9134   // basic-blocks with no recipes.
9135   VPBasicBlock *PreEntry = cast<VPBasicBlock>(Plan->getEntry());
9136   assert(PreEntry->empty() && "Expecting empty pre-entry block.");
9137   VPBlockBase *Entry = Plan->setEntry(PreEntry->getSingleSuccessor());
9138   VPBlockUtils::disconnectBlocks(PreEntry, Entry);
9139   delete PreEntry;
9140 
9141   // ---------------------------------------------------------------------------
9142   // Transform initial VPlan: Apply previously taken decisions, in order, to
9143   // bring the VPlan to its final state.
9144   // ---------------------------------------------------------------------------
9145 
9146   // Apply Sink-After legal constraints.
9147   for (auto &Entry : SinkAfter) {
9148     VPRecipeBase *Sink = RecipeBuilder.getRecipe(Entry.first);
9149     VPRecipeBase *Target = RecipeBuilder.getRecipe(Entry.second);
9150 
9151     auto GetReplicateRegion = [](VPRecipeBase *R) -> VPRegionBlock * {
9152       auto *Region =
9153           dyn_cast_or_null<VPRegionBlock>(R->getParent()->getParent());
9154       if (Region && Region->isReplicator())
9155         return Region;
9156       return nullptr;
9157     };
9158 
9159     // If the target is in a replication region, make sure to move Sink to the
9160     // block after it, not into the replication region itself.
9161     if (auto *TargetRegion = GetReplicateRegion(Target)) {
9162       assert(TargetRegion->getNumSuccessors() == 1 && "Expected SESE region!");
9163       assert(!GetReplicateRegion(Sink) &&
9164              "cannot sink a region into another region yet");
9165       VPBasicBlock *NextBlock =
9166           cast<VPBasicBlock>(TargetRegion->getSuccessors().front());
9167       Sink->moveBefore(*NextBlock, NextBlock->getFirstNonPhi());
9168       continue;
9169     }
9170 
9171     auto *SinkRegion = GetReplicateRegion(Sink);
9172     // Unless the sink source is in a replicate region, sink the recipe
9173     // directly.
9174     if (!SinkRegion) {
9175       Sink->moveAfter(Target);
9176       continue;
9177     }
9178 
9179     // If the sink source is in a replicate region, we need to move the whole
9180     // replicate region, which should only contain a single recipe in the main
9181     // block.
9182     assert(Sink->getParent()->size() == 1 &&
9183            "parent must be a replicator with a single recipe");
9184     auto *SplitBlock =
9185         Target->getParent()->splitAt(std::next(Target->getIterator()));
9186 
9187     auto *Pred = SinkRegion->getSinglePredecessor();
9188     auto *Succ = SinkRegion->getSingleSuccessor();
9189     VPBlockUtils::disconnectBlocks(Pred, SinkRegion);
9190     VPBlockUtils::disconnectBlocks(SinkRegion, Succ);
9191     VPBlockUtils::connectBlocks(Pred, Succ);
9192 
9193     auto *SplitPred = SplitBlock->getSinglePredecessor();
9194 
9195     VPBlockUtils::disconnectBlocks(SplitPred, SplitBlock);
9196     VPBlockUtils::connectBlocks(SplitPred, SinkRegion);
9197     VPBlockUtils::connectBlocks(SinkRegion, SplitBlock);
9198     if (VPBB == SplitPred)
9199       VPBB = SplitBlock;
9200   }
9201 
9202   // Interleave memory: for each Interleave Group we marked earlier as relevant
9203   // for this VPlan, replace the Recipes widening its memory instructions with a
9204   // single VPInterleaveRecipe at its insertion point.
9205   for (auto IG : InterleaveGroups) {
9206     auto *Recipe = cast<VPWidenMemoryInstructionRecipe>(
9207         RecipeBuilder.getRecipe(IG->getInsertPos()));
9208     SmallVector<VPValue *, 4> StoredValues;
9209     for (unsigned i = 0; i < IG->getFactor(); ++i)
9210       if (auto *SI = dyn_cast_or_null<StoreInst>(IG->getMember(i)))
9211         StoredValues.push_back(Plan->getOrAddVPValue(SI->getOperand(0)));
9212 
9213     auto *VPIG = new VPInterleaveRecipe(IG, Recipe->getAddr(), StoredValues,
9214                                         Recipe->getMask());
9215     VPIG->insertBefore(Recipe);
9216     unsigned J = 0;
9217     for (unsigned i = 0; i < IG->getFactor(); ++i)
9218       if (Instruction *Member = IG->getMember(i)) {
9219         if (!Member->getType()->isVoidTy()) {
9220           VPValue *OriginalV = Plan->getVPValue(Member);
9221           Plan->removeVPValueFor(Member);
9222           Plan->addVPValue(Member, VPIG->getVPValue(J));
9223           OriginalV->replaceAllUsesWith(VPIG->getVPValue(J));
9224           J++;
9225         }
9226         RecipeBuilder.getRecipe(Member)->eraseFromParent();
9227       }
9228   }
9229 
9230   // Adjust the recipes for any inloop reductions.
9231   if (Range.Start.isVector())
9232     adjustRecipesForInLoopReductions(Plan, RecipeBuilder);
9233 
9234   // Finally, if tail is folded by masking, introduce selects between the phi
9235   // and the live-out instruction of each reduction, at the end of the latch.
9236   if (CM.foldTailByMasking() && !Legal->getReductionVars().empty()) {
9237     Builder.setInsertPoint(VPBB);
9238     auto *Cond = RecipeBuilder.createBlockInMask(OrigLoop->getHeader(), Plan);
9239     for (auto &Reduction : Legal->getReductionVars()) {
9240       if (CM.isInLoopReduction(Reduction.first))
9241         continue;
9242       VPValue *Phi = Plan->getOrAddVPValue(Reduction.first);
9243       VPValue *Red = Plan->getOrAddVPValue(Reduction.second.getLoopExitInstr());
9244       Builder.createNaryOp(Instruction::Select, {Cond, Red, Phi});
9245     }
9246   }
9247 
9248   std::string PlanName;
9249   raw_string_ostream RSO(PlanName);
9250   ElementCount VF = Range.Start;
9251   Plan->addVF(VF);
9252   RSO << "Initial VPlan for VF={" << VF;
9253   for (VF *= 2; ElementCount::isKnownLT(VF, Range.End); VF *= 2) {
9254     Plan->addVF(VF);
9255     RSO << "," << VF;
9256   }
9257   RSO << "},UF>=1";
9258   RSO.flush();
9259   Plan->setName(PlanName);
9260 
9261   return Plan;
9262 }
9263 
buildVPlan(VFRange & Range)9264 VPlanPtr LoopVectorizationPlanner::buildVPlan(VFRange &Range) {
9265   // Outer loop handling: They may require CFG and instruction level
9266   // transformations before even evaluating whether vectorization is profitable.
9267   // Since we cannot modify the incoming IR, we need to build VPlan upfront in
9268   // the vectorization pipeline.
9269   assert(!OrigLoop->isInnermost());
9270   assert(EnableVPlanNativePath && "VPlan-native path is not enabled.");
9271 
9272   // Create new empty VPlan
9273   auto Plan = std::make_unique<VPlan>();
9274 
9275   // Build hierarchical CFG
9276   VPlanHCFGBuilder HCFGBuilder(OrigLoop, LI, *Plan);
9277   HCFGBuilder.buildHierarchicalCFG();
9278 
9279   for (ElementCount VF = Range.Start; ElementCount::isKnownLT(VF, Range.End);
9280        VF *= 2)
9281     Plan->addVF(VF);
9282 
9283   if (EnableVPlanPredication) {
9284     VPlanPredicator VPP(*Plan);
9285     VPP.predicate();
9286 
9287     // Avoid running transformation to recipes until masked code generation in
9288     // VPlan-native path is in place.
9289     return Plan;
9290   }
9291 
9292   SmallPtrSet<Instruction *, 1> DeadInstructions;
9293   VPlanTransforms::VPInstructionsToVPRecipes(OrigLoop, Plan,
9294                                              Legal->getInductionVars(),
9295                                              DeadInstructions, *PSE.getSE());
9296   return Plan;
9297 }
9298 
9299 // Adjust the recipes for any inloop reductions. The chain of instructions
9300 // leading from the loop exit instr to the phi need to be converted to
9301 // reductions, with one operand being vector and the other being the scalar
9302 // reduction chain.
adjustRecipesForInLoopReductions(VPlanPtr & Plan,VPRecipeBuilder & RecipeBuilder)9303 void LoopVectorizationPlanner::adjustRecipesForInLoopReductions(
9304     VPlanPtr &Plan, VPRecipeBuilder &RecipeBuilder) {
9305   for (auto &Reduction : CM.getInLoopReductionChains()) {
9306     PHINode *Phi = Reduction.first;
9307     RecurrenceDescriptor &RdxDesc = Legal->getReductionVars()[Phi];
9308     const SmallVector<Instruction *, 4> &ReductionOperations = Reduction.second;
9309 
9310     // ReductionOperations are orders top-down from the phi's use to the
9311     // LoopExitValue. We keep a track of the previous item (the Chain) to tell
9312     // which of the two operands will remain scalar and which will be reduced.
9313     // For minmax the chain will be the select instructions.
9314     Instruction *Chain = Phi;
9315     for (Instruction *R : ReductionOperations) {
9316       VPRecipeBase *WidenRecipe = RecipeBuilder.getRecipe(R);
9317       RecurKind Kind = RdxDesc.getRecurrenceKind();
9318 
9319       VPValue *ChainOp = Plan->getVPValue(Chain);
9320       unsigned FirstOpId;
9321       if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind)) {
9322         assert(isa<VPWidenSelectRecipe>(WidenRecipe) &&
9323                "Expected to replace a VPWidenSelectSC");
9324         FirstOpId = 1;
9325       } else {
9326         assert(isa<VPWidenRecipe>(WidenRecipe) &&
9327                "Expected to replace a VPWidenSC");
9328         FirstOpId = 0;
9329       }
9330       unsigned VecOpId =
9331           R->getOperand(FirstOpId) == Chain ? FirstOpId + 1 : FirstOpId;
9332       VPValue *VecOp = Plan->getVPValue(R->getOperand(VecOpId));
9333 
9334       auto *CondOp = CM.foldTailByMasking()
9335                          ? RecipeBuilder.createBlockInMask(R->getParent(), Plan)
9336                          : nullptr;
9337       VPReductionRecipe *RedRecipe = new VPReductionRecipe(
9338           &RdxDesc, R, ChainOp, VecOp, CondOp, TTI);
9339       WidenRecipe->getVPSingleValue()->replaceAllUsesWith(RedRecipe);
9340       Plan->removeVPValueFor(R);
9341       Plan->addVPValue(R, RedRecipe);
9342       WidenRecipe->getParent()->insert(RedRecipe, WidenRecipe->getIterator());
9343       WidenRecipe->getVPSingleValue()->replaceAllUsesWith(RedRecipe);
9344       WidenRecipe->eraseFromParent();
9345 
9346       if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind)) {
9347         VPRecipeBase *CompareRecipe =
9348             RecipeBuilder.getRecipe(cast<Instruction>(R->getOperand(0)));
9349         assert(isa<VPWidenRecipe>(CompareRecipe) &&
9350                "Expected to replace a VPWidenSC");
9351         assert(cast<VPWidenRecipe>(CompareRecipe)->getNumUsers() == 0 &&
9352                "Expected no remaining users");
9353         CompareRecipe->eraseFromParent();
9354       }
9355       Chain = R;
9356     }
9357   }
9358 }
9359 
9360 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
print(raw_ostream & O,const Twine & Indent,VPSlotTracker & SlotTracker) const9361 void VPInterleaveRecipe::print(raw_ostream &O, const Twine &Indent,
9362                                VPSlotTracker &SlotTracker) const {
9363   O << Indent << "INTERLEAVE-GROUP with factor " << IG->getFactor() << " at ";
9364   IG->getInsertPos()->printAsOperand(O, false);
9365   O << ", ";
9366   getAddr()->printAsOperand(O, SlotTracker);
9367   VPValue *Mask = getMask();
9368   if (Mask) {
9369     O << ", ";
9370     Mask->printAsOperand(O, SlotTracker);
9371   }
9372   for (unsigned i = 0; i < IG->getFactor(); ++i)
9373     if (Instruction *I = IG->getMember(i))
9374       O << "\n" << Indent << "  " << VPlanIngredient(I) << " " << i;
9375 }
9376 #endif
9377 
execute(VPTransformState & State)9378 void VPWidenCallRecipe::execute(VPTransformState &State) {
9379   State.ILV->widenCallInstruction(*cast<CallInst>(getUnderlyingInstr()), this,
9380                                   *this, State);
9381 }
9382 
execute(VPTransformState & State)9383 void VPWidenSelectRecipe::execute(VPTransformState &State) {
9384   State.ILV->widenSelectInstruction(*cast<SelectInst>(getUnderlyingInstr()),
9385                                     this, *this, InvariantCond, State);
9386 }
9387 
execute(VPTransformState & State)9388 void VPWidenRecipe::execute(VPTransformState &State) {
9389   State.ILV->widenInstruction(*getUnderlyingInstr(), this, *this, State);
9390 }
9391 
execute(VPTransformState & State)9392 void VPWidenGEPRecipe::execute(VPTransformState &State) {
9393   State.ILV->widenGEP(cast<GetElementPtrInst>(getUnderlyingInstr()), this,
9394                       *this, State.UF, State.VF, IsPtrLoopInvariant,
9395                       IsIndexLoopInvariant, State);
9396 }
9397 
execute(VPTransformState & State)9398 void VPWidenIntOrFpInductionRecipe::execute(VPTransformState &State) {
9399   assert(!State.Instance && "Int or FP induction being replicated.");
9400   State.ILV->widenIntOrFpInduction(IV, getStartValue()->getLiveInIRValue(),
9401                                    getTruncInst(), getVPValue(0),
9402                                    getCastValue(), State);
9403 }
9404 
execute(VPTransformState & State)9405 void VPWidenPHIRecipe::execute(VPTransformState &State) {
9406   State.ILV->widenPHIInstruction(cast<PHINode>(getUnderlyingValue()), RdxDesc,
9407                                  this, State);
9408 }
9409 
execute(VPTransformState & State)9410 void VPBlendRecipe::execute(VPTransformState &State) {
9411   State.ILV->setDebugLocFromInst(State.Builder, Phi);
9412   // We know that all PHIs in non-header blocks are converted into
9413   // selects, so we don't have to worry about the insertion order and we
9414   // can just use the builder.
9415   // At this point we generate the predication tree. There may be
9416   // duplications since this is a simple recursive scan, but future
9417   // optimizations will clean it up.
9418 
9419   unsigned NumIncoming = getNumIncomingValues();
9420 
9421   // Generate a sequence of selects of the form:
9422   // SELECT(Mask3, In3,
9423   //        SELECT(Mask2, In2,
9424   //               SELECT(Mask1, In1,
9425   //                      In0)))
9426   // Note that Mask0 is never used: lanes for which no path reaches this phi and
9427   // are essentially undef are taken from In0.
9428   InnerLoopVectorizer::VectorParts Entry(State.UF);
9429   for (unsigned In = 0; In < NumIncoming; ++In) {
9430     for (unsigned Part = 0; Part < State.UF; ++Part) {
9431       // We might have single edge PHIs (blocks) - use an identity
9432       // 'select' for the first PHI operand.
9433       Value *In0 = State.get(getIncomingValue(In), Part);
9434       if (In == 0)
9435         Entry[Part] = In0; // Initialize with the first incoming value.
9436       else {
9437         // Select between the current value and the previous incoming edge
9438         // based on the incoming mask.
9439         Value *Cond = State.get(getMask(In), Part);
9440         Entry[Part] =
9441             State.Builder.CreateSelect(Cond, In0, Entry[Part], "predphi");
9442       }
9443     }
9444   }
9445   for (unsigned Part = 0; Part < State.UF; ++Part)
9446     State.set(this, Entry[Part], Part);
9447 }
9448 
execute(VPTransformState & State)9449 void VPInterleaveRecipe::execute(VPTransformState &State) {
9450   assert(!State.Instance && "Interleave group being replicated.");
9451   State.ILV->vectorizeInterleaveGroup(IG, definedValues(), State, getAddr(),
9452                                       getStoredValues(), getMask());
9453 }
9454 
execute(VPTransformState & State)9455 void VPReductionRecipe::execute(VPTransformState &State) {
9456   assert(!State.Instance && "Reduction being replicated.");
9457   Value *PrevInChain = State.get(getChainOp(), 0);
9458   for (unsigned Part = 0; Part < State.UF; ++Part) {
9459     RecurKind Kind = RdxDesc->getRecurrenceKind();
9460     bool IsOrdered = useOrderedReductions(*RdxDesc);
9461     Value *NewVecOp = State.get(getVecOp(), Part);
9462     if (VPValue *Cond = getCondOp()) {
9463       Value *NewCond = State.get(Cond, Part);
9464       VectorType *VecTy = cast<VectorType>(NewVecOp->getType());
9465       Constant *Iden = RecurrenceDescriptor::getRecurrenceIdentity(
9466           Kind, VecTy->getElementType(), RdxDesc->getFastMathFlags());
9467       Constant *IdenVec =
9468           ConstantVector::getSplat(VecTy->getElementCount(), Iden);
9469       Value *Select = State.Builder.CreateSelect(NewCond, NewVecOp, IdenVec);
9470       NewVecOp = Select;
9471     }
9472     Value *NewRed;
9473     Value *NextInChain;
9474     if (IsOrdered) {
9475       NewRed = createOrderedReduction(State.Builder, *RdxDesc, NewVecOp,
9476                                       PrevInChain);
9477       PrevInChain = NewRed;
9478     } else {
9479       PrevInChain = State.get(getChainOp(), Part);
9480       NewRed = createTargetReduction(State.Builder, TTI, *RdxDesc, NewVecOp);
9481     }
9482     if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind)) {
9483       NextInChain =
9484           createMinMaxOp(State.Builder, RdxDesc->getRecurrenceKind(),
9485                          NewRed, PrevInChain);
9486     } else if (IsOrdered)
9487       NextInChain = NewRed;
9488     else {
9489       NextInChain = State.Builder.CreateBinOp(
9490           (Instruction::BinaryOps)getUnderlyingInstr()->getOpcode(), NewRed,
9491           PrevInChain);
9492     }
9493     State.set(this, NextInChain, Part);
9494   }
9495 }
9496 
execute(VPTransformState & State)9497 void VPReplicateRecipe::execute(VPTransformState &State) {
9498   if (State.Instance) { // Generate a single instance.
9499     assert(!State.VF.isScalable() && "Can't scalarize a scalable vector");
9500     State.ILV->scalarizeInstruction(getUnderlyingInstr(), this, *this,
9501                                     *State.Instance, IsPredicated, State);
9502     // Insert scalar instance packing it into a vector.
9503     if (AlsoPack && State.VF.isVector()) {
9504       // If we're constructing lane 0, initialize to start from poison.
9505       if (State.Instance->Lane.isFirstLane()) {
9506         assert(!State.VF.isScalable() && "VF is assumed to be non scalable.");
9507         Value *Poison = PoisonValue::get(
9508             VectorType::get(getUnderlyingValue()->getType(), State.VF));
9509         State.set(this, Poison, State.Instance->Part);
9510       }
9511       State.ILV->packScalarIntoVectorValue(this, *State.Instance, State);
9512     }
9513     return;
9514   }
9515 
9516   // Generate scalar instances for all VF lanes of all UF parts, unless the
9517   // instruction is uniform inwhich case generate only the first lane for each
9518   // of the UF parts.
9519   unsigned EndLane = IsUniform ? 1 : State.VF.getKnownMinValue();
9520   assert((!State.VF.isScalable() || IsUniform) &&
9521          "Can't scalarize a scalable vector");
9522   for (unsigned Part = 0; Part < State.UF; ++Part)
9523     for (unsigned Lane = 0; Lane < EndLane; ++Lane)
9524       State.ILV->scalarizeInstruction(getUnderlyingInstr(), this, *this,
9525                                       VPIteration(Part, Lane), IsPredicated,
9526                                       State);
9527 }
9528 
execute(VPTransformState & State)9529 void VPBranchOnMaskRecipe::execute(VPTransformState &State) {
9530   assert(State.Instance && "Branch on Mask works only on single instance.");
9531 
9532   unsigned Part = State.Instance->Part;
9533   unsigned Lane = State.Instance->Lane.getKnownLane();
9534 
9535   Value *ConditionBit = nullptr;
9536   VPValue *BlockInMask = getMask();
9537   if (BlockInMask) {
9538     ConditionBit = State.get(BlockInMask, Part);
9539     if (ConditionBit->getType()->isVectorTy())
9540       ConditionBit = State.Builder.CreateExtractElement(
9541           ConditionBit, State.Builder.getInt32(Lane));
9542   } else // Block in mask is all-one.
9543     ConditionBit = State.Builder.getTrue();
9544 
9545   // Replace the temporary unreachable terminator with a new conditional branch,
9546   // whose two destinations will be set later when they are created.
9547   auto *CurrentTerminator = State.CFG.PrevBB->getTerminator();
9548   assert(isa<UnreachableInst>(CurrentTerminator) &&
9549          "Expected to replace unreachable terminator with conditional branch.");
9550   auto *CondBr = BranchInst::Create(State.CFG.PrevBB, nullptr, ConditionBit);
9551   CondBr->setSuccessor(0, nullptr);
9552   ReplaceInstWithInst(CurrentTerminator, CondBr);
9553 }
9554 
execute(VPTransformState & State)9555 void VPPredInstPHIRecipe::execute(VPTransformState &State) {
9556   assert(State.Instance && "Predicated instruction PHI works per instance.");
9557   Instruction *ScalarPredInst =
9558       cast<Instruction>(State.get(getOperand(0), *State.Instance));
9559   BasicBlock *PredicatedBB = ScalarPredInst->getParent();
9560   BasicBlock *PredicatingBB = PredicatedBB->getSinglePredecessor();
9561   assert(PredicatingBB && "Predicated block has no single predecessor.");
9562   assert(isa<VPReplicateRecipe>(getOperand(0)) &&
9563          "operand must be VPReplicateRecipe");
9564 
9565   // By current pack/unpack logic we need to generate only a single phi node: if
9566   // a vector value for the predicated instruction exists at this point it means
9567   // the instruction has vector users only, and a phi for the vector value is
9568   // needed. In this case the recipe of the predicated instruction is marked to
9569   // also do that packing, thereby "hoisting" the insert-element sequence.
9570   // Otherwise, a phi node for the scalar value is needed.
9571   unsigned Part = State.Instance->Part;
9572   if (State.hasVectorValue(getOperand(0), Part)) {
9573     Value *VectorValue = State.get(getOperand(0), Part);
9574     InsertElementInst *IEI = cast<InsertElementInst>(VectorValue);
9575     PHINode *VPhi = State.Builder.CreatePHI(IEI->getType(), 2);
9576     VPhi->addIncoming(IEI->getOperand(0), PredicatingBB); // Unmodified vector.
9577     VPhi->addIncoming(IEI, PredicatedBB); // New vector with inserted element.
9578     if (State.hasVectorValue(this, Part))
9579       State.reset(this, VPhi, Part);
9580     else
9581       State.set(this, VPhi, Part);
9582     // NOTE: Currently we need to update the value of the operand, so the next
9583     // predicated iteration inserts its generated value in the correct vector.
9584     State.reset(getOperand(0), VPhi, Part);
9585   } else {
9586     Type *PredInstType = getOperand(0)->getUnderlyingValue()->getType();
9587     PHINode *Phi = State.Builder.CreatePHI(PredInstType, 2);
9588     Phi->addIncoming(PoisonValue::get(ScalarPredInst->getType()),
9589                      PredicatingBB);
9590     Phi->addIncoming(ScalarPredInst, PredicatedBB);
9591     if (State.hasScalarValue(this, *State.Instance))
9592       State.reset(this, Phi, *State.Instance);
9593     else
9594       State.set(this, Phi, *State.Instance);
9595     // NOTE: Currently we need to update the value of the operand, so the next
9596     // predicated iteration inserts its generated value in the correct vector.
9597     State.reset(getOperand(0), Phi, *State.Instance);
9598   }
9599 }
9600 
execute(VPTransformState & State)9601 void VPWidenMemoryInstructionRecipe::execute(VPTransformState &State) {
9602   VPValue *StoredValue = isStore() ? getStoredValue() : nullptr;
9603   State.ILV->vectorizeMemoryInstruction(
9604       &Ingredient, State, StoredValue ? nullptr : getVPSingleValue(), getAddr(),
9605       StoredValue, getMask());
9606 }
9607 
9608 // Determine how to lower the scalar epilogue, which depends on 1) optimising
9609 // for minimum code-size, 2) predicate compiler options, 3) loop hints forcing
9610 // predication, and 4) a TTI hook that analyses whether the loop is suitable
9611 // for predication.
getScalarEpilogueLowering(Function * F,Loop * L,LoopVectorizeHints & Hints,ProfileSummaryInfo * PSI,BlockFrequencyInfo * BFI,TargetTransformInfo * TTI,TargetLibraryInfo * TLI,AssumptionCache * AC,LoopInfo * LI,ScalarEvolution * SE,DominatorTree * DT,LoopVectorizationLegality & LVL)9612 static ScalarEpilogueLowering getScalarEpilogueLowering(
9613     Function *F, Loop *L, LoopVectorizeHints &Hints, ProfileSummaryInfo *PSI,
9614     BlockFrequencyInfo *BFI, TargetTransformInfo *TTI, TargetLibraryInfo *TLI,
9615     AssumptionCache *AC, LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT,
9616     LoopVectorizationLegality &LVL) {
9617   // 1) OptSize takes precedence over all other options, i.e. if this is set,
9618   // don't look at hints or options, and don't request a scalar epilogue.
9619   // (For PGSO, as shouldOptimizeForSize isn't currently accessible from
9620   // LoopAccessInfo (due to code dependency and not being able to reliably get
9621   // PSI/BFI from a loop analysis under NPM), we cannot suppress the collection
9622   // of strides in LoopAccessInfo::analyzeLoop() and vectorize without
9623   // versioning when the vectorization is forced, unlike hasOptSize. So revert
9624   // back to the old way and vectorize with versioning when forced. See D81345.)
9625   if (F->hasOptSize() || (llvm::shouldOptimizeForSize(L->getHeader(), PSI, BFI,
9626                                                       PGSOQueryType::IRPass) &&
9627                           Hints.getForce() != LoopVectorizeHints::FK_Enabled))
9628     return CM_ScalarEpilogueNotAllowedOptSize;
9629 
9630   // 2) If set, obey the directives
9631   if (PreferPredicateOverEpilogue.getNumOccurrences()) {
9632     switch (PreferPredicateOverEpilogue) {
9633     case PreferPredicateTy::ScalarEpilogue:
9634       return CM_ScalarEpilogueAllowed;
9635     case PreferPredicateTy::PredicateElseScalarEpilogue:
9636       return CM_ScalarEpilogueNotNeededUsePredicate;
9637     case PreferPredicateTy::PredicateOrDontVectorize:
9638       return CM_ScalarEpilogueNotAllowedUsePredicate;
9639     };
9640   }
9641 
9642   // 3) If set, obey the hints
9643   switch (Hints.getPredicate()) {
9644   case LoopVectorizeHints::FK_Enabled:
9645     return CM_ScalarEpilogueNotNeededUsePredicate;
9646   case LoopVectorizeHints::FK_Disabled:
9647     return CM_ScalarEpilogueAllowed;
9648   };
9649 
9650   // 4) if the TTI hook indicates this is profitable, request predication.
9651   if (TTI->preferPredicateOverEpilogue(L, LI, *SE, *AC, TLI, DT,
9652                                        LVL.getLAI()))
9653     return CM_ScalarEpilogueNotNeededUsePredicate;
9654 
9655   return CM_ScalarEpilogueAllowed;
9656 }
9657 
get(VPValue * Def,unsigned Part)9658 Value *VPTransformState::get(VPValue *Def, unsigned Part) {
9659   // If Values have been set for this Def return the one relevant for \p Part.
9660   if (hasVectorValue(Def, Part))
9661     return Data.PerPartOutput[Def][Part];
9662 
9663   if (!hasScalarValue(Def, {Part, 0})) {
9664     Value *IRV = Def->getLiveInIRValue();
9665     Value *B = ILV->getBroadcastInstrs(IRV);
9666     set(Def, B, Part);
9667     return B;
9668   }
9669 
9670   Value *ScalarValue = get(Def, {Part, 0});
9671   // If we aren't vectorizing, we can just copy the scalar map values over
9672   // to the vector map.
9673   if (VF.isScalar()) {
9674     set(Def, ScalarValue, Part);
9675     return ScalarValue;
9676   }
9677 
9678   auto *RepR = dyn_cast<VPReplicateRecipe>(Def);
9679   bool IsUniform = RepR && RepR->isUniform();
9680 
9681   unsigned LastLane = IsUniform ? 0 : VF.getKnownMinValue() - 1;
9682   // Check if there is a scalar value for the selected lane.
9683   if (!hasScalarValue(Def, {Part, LastLane})) {
9684     // At the moment, VPWidenIntOrFpInductionRecipes can also be uniform.
9685     assert(isa<VPWidenIntOrFpInductionRecipe>(Def->getDef()) &&
9686            "unexpected recipe found to be invariant");
9687     IsUniform = true;
9688     LastLane = 0;
9689   }
9690 
9691   auto *LastInst = cast<Instruction>(get(Def, {Part, LastLane}));
9692 
9693   // Set the insert point after the last scalarized instruction. This
9694   // ensures the insertelement sequence will directly follow the scalar
9695   // definitions.
9696   auto OldIP = Builder.saveIP();
9697   auto NewIP = std::next(BasicBlock::iterator(LastInst));
9698   Builder.SetInsertPoint(&*NewIP);
9699 
9700   // However, if we are vectorizing, we need to construct the vector values.
9701   // If the value is known to be uniform after vectorization, we can just
9702   // broadcast the scalar value corresponding to lane zero for each unroll
9703   // iteration. Otherwise, we construct the vector values using
9704   // insertelement instructions. Since the resulting vectors are stored in
9705   // State, we will only generate the insertelements once.
9706   Value *VectorValue = nullptr;
9707   if (IsUniform) {
9708     VectorValue = ILV->getBroadcastInstrs(ScalarValue);
9709     set(Def, VectorValue, Part);
9710   } else {
9711     // Initialize packing with insertelements to start from undef.
9712     assert(!VF.isScalable() && "VF is assumed to be non scalable.");
9713     Value *Undef = PoisonValue::get(VectorType::get(LastInst->getType(), VF));
9714     set(Def, Undef, Part);
9715     for (unsigned Lane = 0; Lane < VF.getKnownMinValue(); ++Lane)
9716       ILV->packScalarIntoVectorValue(Def, {Part, Lane}, *this);
9717     VectorValue = get(Def, Part);
9718   }
9719   Builder.restoreIP(OldIP);
9720   return VectorValue;
9721 }
9722 
9723 // Process the loop in the VPlan-native vectorization path. This path builds
9724 // VPlan upfront in the vectorization pipeline, which allows to apply
9725 // VPlan-to-VPlan transformations from the very beginning without modifying the
9726 // input LLVM IR.
processLoopInVPlanNativePath(Loop * L,PredicatedScalarEvolution & PSE,LoopInfo * LI,DominatorTree * DT,LoopVectorizationLegality * LVL,TargetTransformInfo * TTI,TargetLibraryInfo * TLI,DemandedBits * DB,AssumptionCache * AC,OptimizationRemarkEmitter * ORE,BlockFrequencyInfo * BFI,ProfileSummaryInfo * PSI,LoopVectorizeHints & Hints,LoopVectorizationRequirements & Requirements)9727 static bool processLoopInVPlanNativePath(
9728     Loop *L, PredicatedScalarEvolution &PSE, LoopInfo *LI, DominatorTree *DT,
9729     LoopVectorizationLegality *LVL, TargetTransformInfo *TTI,
9730     TargetLibraryInfo *TLI, DemandedBits *DB, AssumptionCache *AC,
9731     OptimizationRemarkEmitter *ORE, BlockFrequencyInfo *BFI,
9732     ProfileSummaryInfo *PSI, LoopVectorizeHints &Hints,
9733     LoopVectorizationRequirements &Requirements) {
9734 
9735   if (isa<SCEVCouldNotCompute>(PSE.getBackedgeTakenCount())) {
9736     LLVM_DEBUG(dbgs() << "LV: cannot compute the outer-loop trip count\n");
9737     return false;
9738   }
9739   assert(EnableVPlanNativePath && "VPlan-native path is disabled.");
9740   Function *F = L->getHeader()->getParent();
9741   InterleavedAccessInfo IAI(PSE, L, DT, LI, LVL->getLAI());
9742 
9743   ScalarEpilogueLowering SEL = getScalarEpilogueLowering(
9744       F, L, Hints, PSI, BFI, TTI, TLI, AC, LI, PSE.getSE(), DT, *LVL);
9745 
9746   LoopVectorizationCostModel CM(SEL, L, PSE, LI, LVL, *TTI, TLI, DB, AC, ORE, F,
9747                                 &Hints, IAI);
9748   // Use the planner for outer loop vectorization.
9749   // TODO: CM is not used at this point inside the planner. Turn CM into an
9750   // optional argument if we don't need it in the future.
9751   LoopVectorizationPlanner LVP(L, LI, TLI, TTI, LVL, CM, IAI, PSE, Hints,
9752                                Requirements, ORE);
9753 
9754   // Get user vectorization factor.
9755   ElementCount UserVF = Hints.getWidth();
9756 
9757   // Plan how to best vectorize, return the best VF and its cost.
9758   const VectorizationFactor VF = LVP.planInVPlanNativePath(UserVF);
9759 
9760   // If we are stress testing VPlan builds, do not attempt to generate vector
9761   // code. Masked vector code generation support will follow soon.
9762   // Also, do not attempt to vectorize if no vector code will be produced.
9763   if (VPlanBuildStressTest || EnableVPlanPredication ||
9764       VectorizationFactor::Disabled() == VF)
9765     return false;
9766 
9767   LVP.setBestPlan(VF.Width, 1);
9768 
9769   {
9770     GeneratedRTChecks Checks(*PSE.getSE(), DT, LI,
9771                              F->getParent()->getDataLayout());
9772     InnerLoopVectorizer LB(L, PSE, LI, DT, TLI, TTI, AC, ORE, VF.Width, 1, LVL,
9773                            &CM, BFI, PSI, Checks);
9774     LLVM_DEBUG(dbgs() << "Vectorizing outer loop in \""
9775                       << L->getHeader()->getParent()->getName() << "\"\n");
9776     LVP.executePlan(LB, DT);
9777   }
9778 
9779   // Mark the loop as already vectorized to avoid vectorizing again.
9780   Hints.setAlreadyVectorized();
9781   assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()));
9782   return true;
9783 }
9784 
9785 // Emit a remark if there are stores to floats that required a floating point
9786 // extension. If the vectorized loop was generated with floating point there
9787 // will be a performance penalty from the conversion overhead and the change in
9788 // the vector width.
checkMixedPrecision(Loop * L,OptimizationRemarkEmitter * ORE)9789 static void checkMixedPrecision(Loop *L, OptimizationRemarkEmitter *ORE) {
9790   SmallVector<Instruction *, 4> Worklist;
9791   for (BasicBlock *BB : L->getBlocks()) {
9792     for (Instruction &Inst : *BB) {
9793       if (auto *S = dyn_cast<StoreInst>(&Inst)) {
9794         if (S->getValueOperand()->getType()->isFloatTy())
9795           Worklist.push_back(S);
9796       }
9797     }
9798   }
9799 
9800   // Traverse the floating point stores upwards searching, for floating point
9801   // conversions.
9802   SmallPtrSet<const Instruction *, 4> Visited;
9803   SmallPtrSet<const Instruction *, 4> EmittedRemark;
9804   while (!Worklist.empty()) {
9805     auto *I = Worklist.pop_back_val();
9806     if (!L->contains(I))
9807       continue;
9808     if (!Visited.insert(I).second)
9809       continue;
9810 
9811     // Emit a remark if the floating point store required a floating
9812     // point conversion.
9813     // TODO: More work could be done to identify the root cause such as a
9814     // constant or a function return type and point the user to it.
9815     if (isa<FPExtInst>(I) && EmittedRemark.insert(I).second)
9816       ORE->emit([&]() {
9817         return OptimizationRemarkAnalysis(LV_NAME, "VectorMixedPrecision",
9818                                           I->getDebugLoc(), L->getHeader())
9819                << "floating point conversion changes vector width. "
9820                << "Mixed floating point precision requires an up/down "
9821                << "cast that will negatively impact performance.";
9822       });
9823 
9824     for (Use &Op : I->operands())
9825       if (auto *OpI = dyn_cast<Instruction>(Op))
9826         Worklist.push_back(OpI);
9827   }
9828 }
9829 
LoopVectorizePass(LoopVectorizeOptions Opts)9830 LoopVectorizePass::LoopVectorizePass(LoopVectorizeOptions Opts)
9831     : InterleaveOnlyWhenForced(Opts.InterleaveOnlyWhenForced ||
9832                                !EnableLoopInterleaving),
9833       VectorizeOnlyWhenForced(Opts.VectorizeOnlyWhenForced ||
9834                               !EnableLoopVectorization) {}
9835 
processLoop(Loop * L)9836 bool LoopVectorizePass::processLoop(Loop *L) {
9837   assert((EnableVPlanNativePath || L->isInnermost()) &&
9838          "VPlan-native path is not enabled. Only process inner loops.");
9839 
9840 #ifndef NDEBUG
9841   const std::string DebugLocStr = getDebugLocString(L);
9842 #endif /* NDEBUG */
9843 
9844   LLVM_DEBUG(dbgs() << "\nLV: Checking a loop in \""
9845                     << L->getHeader()->getParent()->getName() << "\" from "
9846                     << DebugLocStr << "\n");
9847 
9848   LoopVectorizeHints Hints(L, InterleaveOnlyWhenForced, *ORE);
9849 
9850   LLVM_DEBUG(
9851       dbgs() << "LV: Loop hints:"
9852              << " force="
9853              << (Hints.getForce() == LoopVectorizeHints::FK_Disabled
9854                      ? "disabled"
9855                      : (Hints.getForce() == LoopVectorizeHints::FK_Enabled
9856                             ? "enabled"
9857                             : "?"))
9858              << " width=" << Hints.getWidth()
9859              << " interleave=" << Hints.getInterleave() << "\n");
9860 
9861   // Function containing loop
9862   Function *F = L->getHeader()->getParent();
9863 
9864   // Looking at the diagnostic output is the only way to determine if a loop
9865   // was vectorized (other than looking at the IR or machine code), so it
9866   // is important to generate an optimization remark for each loop. Most of
9867   // these messages are generated as OptimizationRemarkAnalysis. Remarks
9868   // generated as OptimizationRemark and OptimizationRemarkMissed are
9869   // less verbose reporting vectorized loops and unvectorized loops that may
9870   // benefit from vectorization, respectively.
9871 
9872   if (!Hints.allowVectorization(F, L, VectorizeOnlyWhenForced)) {
9873     LLVM_DEBUG(dbgs() << "LV: Loop hints prevent vectorization.\n");
9874     return false;
9875   }
9876 
9877   PredicatedScalarEvolution PSE(*SE, *L);
9878 
9879   // Check if it is legal to vectorize the loop.
9880   LoopVectorizationRequirements Requirements;
9881   LoopVectorizationLegality LVL(L, PSE, DT, TTI, TLI, AA, F, GetLAA, LI, ORE,
9882                                 &Requirements, &Hints, DB, AC, BFI, PSI);
9883   if (!LVL.canVectorize(EnableVPlanNativePath)) {
9884     LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
9885     Hints.emitRemarkWithHints();
9886     return false;
9887   }
9888 
9889   // Check the function attributes and profiles to find out if this function
9890   // should be optimized for size.
9891   ScalarEpilogueLowering SEL = getScalarEpilogueLowering(
9892       F, L, Hints, PSI, BFI, TTI, TLI, AC, LI, PSE.getSE(), DT, LVL);
9893 
9894   // Entrance to the VPlan-native vectorization path. Outer loops are processed
9895   // here. They may require CFG and instruction level transformations before
9896   // even evaluating whether vectorization is profitable. Since we cannot modify
9897   // the incoming IR, we need to build VPlan upfront in the vectorization
9898   // pipeline.
9899   if (!L->isInnermost())
9900     return processLoopInVPlanNativePath(L, PSE, LI, DT, &LVL, TTI, TLI, DB, AC,
9901                                         ORE, BFI, PSI, Hints, Requirements);
9902 
9903   assert(L->isInnermost() && "Inner loop expected.");
9904 
9905   // Check the loop for a trip count threshold: vectorize loops with a tiny trip
9906   // count by optimizing for size, to minimize overheads.
9907   auto ExpectedTC = getSmallBestKnownTC(*SE, L);
9908   if (ExpectedTC && *ExpectedTC < TinyTripCountVectorThreshold) {
9909     LLVM_DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "
9910                       << "This loop is worth vectorizing only if no scalar "
9911                       << "iteration overheads are incurred.");
9912     if (Hints.getForce() == LoopVectorizeHints::FK_Enabled)
9913       LLVM_DEBUG(dbgs() << " But vectorizing was explicitly forced.\n");
9914     else {
9915       LLVM_DEBUG(dbgs() << "\n");
9916       SEL = CM_ScalarEpilogueNotAllowedLowTripLoop;
9917     }
9918   }
9919 
9920   // Check the function attributes to see if implicit floats are allowed.
9921   // FIXME: This check doesn't seem possibly correct -- what if the loop is
9922   // an integer loop and the vector instructions selected are purely integer
9923   // vector instructions?
9924   if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
9925     reportVectorizationFailure(
9926         "Can't vectorize when the NoImplicitFloat attribute is used",
9927         "loop not vectorized due to NoImplicitFloat attribute",
9928         "NoImplicitFloat", ORE, L);
9929     Hints.emitRemarkWithHints();
9930     return false;
9931   }
9932 
9933   // Check if the target supports potentially unsafe FP vectorization.
9934   // FIXME: Add a check for the type of safety issue (denormal, signaling)
9935   // for the target we're vectorizing for, to make sure none of the
9936   // additional fp-math flags can help.
9937   if (Hints.isPotentiallyUnsafe() &&
9938       TTI->isFPVectorizationPotentiallyUnsafe()) {
9939     reportVectorizationFailure(
9940         "Potentially unsafe FP op prevents vectorization",
9941         "loop not vectorized due to unsafe FP support.",
9942         "UnsafeFP", ORE, L);
9943     Hints.emitRemarkWithHints();
9944     return false;
9945   }
9946 
9947   if (!Requirements.canVectorizeFPMath(Hints)) {
9948     ORE->emit([&]() {
9949       auto *ExactFPMathInst = Requirements.getExactFPInst();
9950       return OptimizationRemarkAnalysisFPCommute(DEBUG_TYPE, "CantReorderFPOps",
9951                                                  ExactFPMathInst->getDebugLoc(),
9952                                                  ExactFPMathInst->getParent())
9953              << "loop not vectorized: cannot prove it is safe to reorder "
9954                 "floating-point operations";
9955     });
9956     LLVM_DEBUG(dbgs() << "LV: loop not vectorized: cannot prove it is safe to "
9957                          "reorder floating-point operations\n");
9958     Hints.emitRemarkWithHints();
9959     return false;
9960   }
9961 
9962   bool UseInterleaved = TTI->enableInterleavedAccessVectorization();
9963   InterleavedAccessInfo IAI(PSE, L, DT, LI, LVL.getLAI());
9964 
9965   // If an override option has been passed in for interleaved accesses, use it.
9966   if (EnableInterleavedMemAccesses.getNumOccurrences() > 0)
9967     UseInterleaved = EnableInterleavedMemAccesses;
9968 
9969   // Analyze interleaved memory accesses.
9970   if (UseInterleaved) {
9971     IAI.analyzeInterleaving(useMaskedInterleavedAccesses(*TTI));
9972   }
9973 
9974   // Use the cost model.
9975   LoopVectorizationCostModel CM(SEL, L, PSE, LI, &LVL, *TTI, TLI, DB, AC, ORE,
9976                                 F, &Hints, IAI);
9977   CM.collectValuesToIgnore();
9978 
9979   // Use the planner for vectorization.
9980   LoopVectorizationPlanner LVP(L, LI, TLI, TTI, &LVL, CM, IAI, PSE, Hints,
9981                                Requirements, ORE);
9982 
9983   // Get user vectorization factor and interleave count.
9984   ElementCount UserVF = Hints.getWidth();
9985   unsigned UserIC = Hints.getInterleave();
9986 
9987   // Plan how to best vectorize, return the best VF and its cost.
9988   Optional<VectorizationFactor> MaybeVF = LVP.plan(UserVF, UserIC);
9989 
9990   VectorizationFactor VF = VectorizationFactor::Disabled();
9991   unsigned IC = 1;
9992 
9993   if (MaybeVF) {
9994     VF = *MaybeVF;
9995     // Select the interleave count.
9996     IC = CM.selectInterleaveCount(VF.Width, *VF.Cost.getValue());
9997   }
9998 
9999   // Identify the diagnostic messages that should be produced.
10000   std::pair<StringRef, std::string> VecDiagMsg, IntDiagMsg;
10001   bool VectorizeLoop = true, InterleaveLoop = true;
10002   if (VF.Width.isScalar()) {
10003     LLVM_DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
10004     VecDiagMsg = std::make_pair(
10005         "VectorizationNotBeneficial",
10006         "the cost-model indicates that vectorization is not beneficial");
10007     VectorizeLoop = false;
10008   }
10009 
10010   if (!MaybeVF && UserIC > 1) {
10011     // Tell the user interleaving was avoided up-front, despite being explicitly
10012     // requested.
10013     LLVM_DEBUG(dbgs() << "LV: Ignoring UserIC, because vectorization and "
10014                          "interleaving should be avoided up front\n");
10015     IntDiagMsg = std::make_pair(
10016         "InterleavingAvoided",
10017         "Ignoring UserIC, because interleaving was avoided up front");
10018     InterleaveLoop = false;
10019   } else if (IC == 1 && UserIC <= 1) {
10020     // Tell the user interleaving is not beneficial.
10021     LLVM_DEBUG(dbgs() << "LV: Interleaving is not beneficial.\n");
10022     IntDiagMsg = std::make_pair(
10023         "InterleavingNotBeneficial",
10024         "the cost-model indicates that interleaving is not beneficial");
10025     InterleaveLoop = false;
10026     if (UserIC == 1) {
10027       IntDiagMsg.first = "InterleavingNotBeneficialAndDisabled";
10028       IntDiagMsg.second +=
10029           " and is explicitly disabled or interleave count is set to 1";
10030     }
10031   } else if (IC > 1 && UserIC == 1) {
10032     // Tell the user interleaving is beneficial, but it explicitly disabled.
10033     LLVM_DEBUG(
10034         dbgs() << "LV: Interleaving is beneficial but is explicitly disabled.");
10035     IntDiagMsg = std::make_pair(
10036         "InterleavingBeneficialButDisabled",
10037         "the cost-model indicates that interleaving is beneficial "
10038         "but is explicitly disabled or interleave count is set to 1");
10039     InterleaveLoop = false;
10040   }
10041 
10042   // Override IC if user provided an interleave count.
10043   IC = UserIC > 0 ? UserIC : IC;
10044 
10045   // Emit diagnostic messages, if any.
10046   const char *VAPassName = Hints.vectorizeAnalysisPassName();
10047   if (!VectorizeLoop && !InterleaveLoop) {
10048     // Do not vectorize or interleaving the loop.
10049     ORE->emit([&]() {
10050       return OptimizationRemarkMissed(VAPassName, VecDiagMsg.first,
10051                                       L->getStartLoc(), L->getHeader())
10052              << VecDiagMsg.second;
10053     });
10054     ORE->emit([&]() {
10055       return OptimizationRemarkMissed(LV_NAME, IntDiagMsg.first,
10056                                       L->getStartLoc(), L->getHeader())
10057              << IntDiagMsg.second;
10058     });
10059     return false;
10060   } else if (!VectorizeLoop && InterleaveLoop) {
10061     LLVM_DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
10062     ORE->emit([&]() {
10063       return OptimizationRemarkAnalysis(VAPassName, VecDiagMsg.first,
10064                                         L->getStartLoc(), L->getHeader())
10065              << VecDiagMsg.second;
10066     });
10067   } else if (VectorizeLoop && !InterleaveLoop) {
10068     LLVM_DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width
10069                       << ") in " << DebugLocStr << '\n');
10070     ORE->emit([&]() {
10071       return OptimizationRemarkAnalysis(LV_NAME, IntDiagMsg.first,
10072                                         L->getStartLoc(), L->getHeader())
10073              << IntDiagMsg.second;
10074     });
10075   } else if (VectorizeLoop && InterleaveLoop) {
10076     LLVM_DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width
10077                       << ") in " << DebugLocStr << '\n');
10078     LLVM_DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
10079   }
10080 
10081   bool DisableRuntimeUnroll = false;
10082   MDNode *OrigLoopID = L->getLoopID();
10083   {
10084     // Optimistically generate runtime checks. Drop them if they turn out to not
10085     // be profitable. Limit the scope of Checks, so the cleanup happens
10086     // immediately after vector codegeneration is done.
10087     GeneratedRTChecks Checks(*PSE.getSE(), DT, LI,
10088                              F->getParent()->getDataLayout());
10089     if (!VF.Width.isScalar() || IC > 1)
10090       Checks.Create(L, *LVL.getLAI(), PSE.getUnionPredicate());
10091     LVP.setBestPlan(VF.Width, IC);
10092 
10093     using namespace ore;
10094     if (!VectorizeLoop) {
10095       assert(IC > 1 && "interleave count should not be 1 or 0");
10096       // If we decided that it is not legal to vectorize the loop, then
10097       // interleave it.
10098       InnerLoopUnroller Unroller(L, PSE, LI, DT, TLI, TTI, AC, ORE, IC, &LVL,
10099                                  &CM, BFI, PSI, Checks);
10100       LVP.executePlan(Unroller, DT);
10101 
10102       ORE->emit([&]() {
10103         return OptimizationRemark(LV_NAME, "Interleaved", L->getStartLoc(),
10104                                   L->getHeader())
10105                << "interleaved loop (interleaved count: "
10106                << NV("InterleaveCount", IC) << ")";
10107       });
10108     } else {
10109       // If we decided that it is *legal* to vectorize the loop, then do it.
10110 
10111       // Consider vectorizing the epilogue too if it's profitable.
10112       VectorizationFactor EpilogueVF =
10113           CM.selectEpilogueVectorizationFactor(VF.Width, LVP);
10114       if (EpilogueVF.Width.isVector()) {
10115 
10116         // The first pass vectorizes the main loop and creates a scalar epilogue
10117         // to be vectorized by executing the plan (potentially with a different
10118         // factor) again shortly afterwards.
10119         EpilogueLoopVectorizationInfo EPI(VF.Width.getKnownMinValue(), IC,
10120                                           EpilogueVF.Width.getKnownMinValue(),
10121                                           1);
10122         EpilogueVectorizerMainLoop MainILV(L, PSE, LI, DT, TLI, TTI, AC, ORE,
10123                                            EPI, &LVL, &CM, BFI, PSI, Checks);
10124 
10125         LVP.setBestPlan(EPI.MainLoopVF, EPI.MainLoopUF);
10126         LVP.executePlan(MainILV, DT);
10127         ++LoopsVectorized;
10128 
10129         simplifyLoop(L, DT, LI, SE, AC, nullptr, false /* PreserveLCSSA */);
10130         formLCSSARecursively(*L, *DT, LI, SE);
10131 
10132         // Second pass vectorizes the epilogue and adjusts the control flow
10133         // edges from the first pass.
10134         LVP.setBestPlan(EPI.EpilogueVF, EPI.EpilogueUF);
10135         EPI.MainLoopVF = EPI.EpilogueVF;
10136         EPI.MainLoopUF = EPI.EpilogueUF;
10137         EpilogueVectorizerEpilogueLoop EpilogILV(L, PSE, LI, DT, TLI, TTI, AC,
10138                                                  ORE, EPI, &LVL, &CM, BFI, PSI,
10139                                                  Checks);
10140         LVP.executePlan(EpilogILV, DT);
10141         ++LoopsEpilogueVectorized;
10142 
10143         if (!MainILV.areSafetyChecksAdded())
10144           DisableRuntimeUnroll = true;
10145       } else {
10146         InnerLoopVectorizer LB(L, PSE, LI, DT, TLI, TTI, AC, ORE, VF.Width, IC,
10147                                &LVL, &CM, BFI, PSI, Checks);
10148         LVP.executePlan(LB, DT);
10149         ++LoopsVectorized;
10150 
10151         // Add metadata to disable runtime unrolling a scalar loop when there
10152         // are no runtime checks about strides and memory. A scalar loop that is
10153         // rarely used is not worth unrolling.
10154         if (!LB.areSafetyChecksAdded())
10155           DisableRuntimeUnroll = true;
10156       }
10157       // Report the vectorization decision.
10158       ORE->emit([&]() {
10159         return OptimizationRemark(LV_NAME, "Vectorized", L->getStartLoc(),
10160                                   L->getHeader())
10161                << "vectorized loop (vectorization width: "
10162                << NV("VectorizationFactor", VF.Width)
10163                << ", interleaved count: " << NV("InterleaveCount", IC) << ")";
10164       });
10165     }
10166 
10167     if (ORE->allowExtraAnalysis(LV_NAME))
10168       checkMixedPrecision(L, ORE);
10169   }
10170 
10171   Optional<MDNode *> RemainderLoopID =
10172       makeFollowupLoopID(OrigLoopID, {LLVMLoopVectorizeFollowupAll,
10173                                       LLVMLoopVectorizeFollowupEpilogue});
10174   if (RemainderLoopID.hasValue()) {
10175     L->setLoopID(RemainderLoopID.getValue());
10176   } else {
10177     if (DisableRuntimeUnroll)
10178       AddRuntimeUnrollDisableMetaData(L);
10179 
10180     // Mark the loop as already vectorized to avoid vectorizing again.
10181     Hints.setAlreadyVectorized();
10182   }
10183 
10184   assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()));
10185   return true;
10186 }
10187 
runImpl(Function & F,ScalarEvolution & SE_,LoopInfo & LI_,TargetTransformInfo & TTI_,DominatorTree & DT_,BlockFrequencyInfo & BFI_,TargetLibraryInfo * TLI_,DemandedBits & DB_,AAResults & AA_,AssumptionCache & AC_,std::function<const LoopAccessInfo & (Loop &)> & GetLAA_,OptimizationRemarkEmitter & ORE_,ProfileSummaryInfo * PSI_)10188 LoopVectorizeResult LoopVectorizePass::runImpl(
10189     Function &F, ScalarEvolution &SE_, LoopInfo &LI_, TargetTransformInfo &TTI_,
10190     DominatorTree &DT_, BlockFrequencyInfo &BFI_, TargetLibraryInfo *TLI_,
10191     DemandedBits &DB_, AAResults &AA_, AssumptionCache &AC_,
10192     std::function<const LoopAccessInfo &(Loop &)> &GetLAA_,
10193     OptimizationRemarkEmitter &ORE_, ProfileSummaryInfo *PSI_) {
10194   SE = &SE_;
10195   LI = &LI_;
10196   TTI = &TTI_;
10197   DT = &DT_;
10198   BFI = &BFI_;
10199   TLI = TLI_;
10200   AA = &AA_;
10201   AC = &AC_;
10202   GetLAA = &GetLAA_;
10203   DB = &DB_;
10204   ORE = &ORE_;
10205   PSI = PSI_;
10206 
10207   // Don't attempt if
10208   // 1. the target claims to have no vector registers, and
10209   // 2. interleaving won't help ILP.
10210   //
10211   // The second condition is necessary because, even if the target has no
10212   // vector registers, loop vectorization may still enable scalar
10213   // interleaving.
10214   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true)) &&
10215       TTI->getMaxInterleaveFactor(1) < 2)
10216     return LoopVectorizeResult(false, false);
10217 
10218   bool Changed = false, CFGChanged = false;
10219 
10220   // The vectorizer requires loops to be in simplified form.
10221   // Since simplification may add new inner loops, it has to run before the
10222   // legality and profitability checks. This means running the loop vectorizer
10223   // will simplify all loops, regardless of whether anything end up being
10224   // vectorized.
10225   for (auto &L : *LI)
10226     Changed |= CFGChanged |=
10227         simplifyLoop(L, DT, LI, SE, AC, nullptr, false /* PreserveLCSSA */);
10228 
10229   // Build up a worklist of inner-loops to vectorize. This is necessary as
10230   // the act of vectorizing or partially unrolling a loop creates new loops
10231   // and can invalidate iterators across the loops.
10232   SmallVector<Loop *, 8> Worklist;
10233 
10234   for (Loop *L : *LI)
10235     collectSupportedLoops(*L, LI, ORE, Worklist);
10236 
10237   LoopsAnalyzed += Worklist.size();
10238 
10239   // Now walk the identified inner loops.
10240   while (!Worklist.empty()) {
10241     Loop *L = Worklist.pop_back_val();
10242 
10243     // For the inner loops we actually process, form LCSSA to simplify the
10244     // transform.
10245     Changed |= formLCSSARecursively(*L, *DT, LI, SE);
10246 
10247     Changed |= CFGChanged |= processLoop(L);
10248   }
10249 
10250   // Process each loop nest in the function.
10251   return LoopVectorizeResult(Changed, CFGChanged);
10252 }
10253 
run(Function & F,FunctionAnalysisManager & AM)10254 PreservedAnalyses LoopVectorizePass::run(Function &F,
10255                                          FunctionAnalysisManager &AM) {
10256     auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
10257     auto &LI = AM.getResult<LoopAnalysis>(F);
10258     auto &TTI = AM.getResult<TargetIRAnalysis>(F);
10259     auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
10260     auto &BFI = AM.getResult<BlockFrequencyAnalysis>(F);
10261     auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
10262     auto &AA = AM.getResult<AAManager>(F);
10263     auto &AC = AM.getResult<AssumptionAnalysis>(F);
10264     auto &DB = AM.getResult<DemandedBitsAnalysis>(F);
10265     auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
10266     MemorySSA *MSSA = EnableMSSALoopDependency
10267                           ? &AM.getResult<MemorySSAAnalysis>(F).getMSSA()
10268                           : nullptr;
10269 
10270     auto &LAM = AM.getResult<LoopAnalysisManagerFunctionProxy>(F).getManager();
10271     std::function<const LoopAccessInfo &(Loop &)> GetLAA =
10272         [&](Loop &L) -> const LoopAccessInfo & {
10273       LoopStandardAnalysisResults AR = {AA,  AC,  DT,      LI,  SE,
10274                                         TLI, TTI, nullptr, MSSA};
10275       return LAM.getResult<LoopAccessAnalysis>(L, AR);
10276     };
10277     auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
10278     ProfileSummaryInfo *PSI =
10279         MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
10280     LoopVectorizeResult Result =
10281         runImpl(F, SE, LI, TTI, DT, BFI, &TLI, DB, AA, AC, GetLAA, ORE, PSI);
10282     if (!Result.MadeAnyChange)
10283       return PreservedAnalyses::all();
10284     PreservedAnalyses PA;
10285 
10286     // We currently do not preserve loopinfo/dominator analyses with outer loop
10287     // vectorization. Until this is addressed, mark these analyses as preserved
10288     // only for non-VPlan-native path.
10289     // TODO: Preserve Loop and Dominator analyses for VPlan-native path.
10290     if (!EnableVPlanNativePath) {
10291       PA.preserve<LoopAnalysis>();
10292       PA.preserve<DominatorTreeAnalysis>();
10293     }
10294     if (!Result.MadeCFGChange)
10295       PA.preserveSet<CFGAnalyses>();
10296     return PA;
10297 }
10298