LLVM  16.0.0git
LoopVectorize.cpp
Go to the documentation of this file.
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 
58 #include "VPRecipeBuilder.h"
59 #include "VPlan.h"
60 #include "VPlanHCFGBuilder.h"
61 #include "VPlanTransforms.h"
62 #include "llvm/ADT/APInt.h"
63 #include "llvm/ADT/ArrayRef.h"
64 #include "llvm/ADT/DenseMap.h"
65 #include "llvm/ADT/DenseMapInfo.h"
66 #include "llvm/ADT/Hashing.h"
67 #include "llvm/ADT/MapVector.h"
68 #include "llvm/ADT/None.h"
69 #include "llvm/ADT/Optional.h"
70 #include "llvm/ADT/STLExtras.h"
71 #include "llvm/ADT/SmallPtrSet.h"
72 #include "llvm/ADT/SmallSet.h"
73 #include "llvm/ADT/SmallVector.h"
74 #include "llvm/ADT/Statistic.h"
75 #include "llvm/ADT/StringRef.h"
76 #include "llvm/ADT/Twine.h"
81 #include "llvm/Analysis/CFG.h"
87 #include "llvm/Analysis/LoopInfo.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"
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/Metadata.h"
116 #include "llvm/IR/Module.h"
117 #include "llvm/IR/Operator.h"
118 #include "llvm/IR/PatternMatch.h"
119 #include "llvm/IR/Type.h"
120 #include "llvm/IR/Use.h"
121 #include "llvm/IR/User.h"
122 #include "llvm/IR/Value.h"
123 #include "llvm/IR/ValueHandle.h"
124 #include "llvm/IR/Verifier.h"
125 #include "llvm/InitializePasses.h"
126 #include "llvm/Pass.h"
127 #include "llvm/Support/Casting.h"
129 #include "llvm/Support/Compiler.h"
130 #include "llvm/Support/Debug.h"
133 #include "llvm/Support/MathExtras.h"
143 #include <algorithm>
144 #include <cassert>
145 #include <cmath>
146 #include <cstdint>
147 #include <functional>
148 #include <iterator>
149 #include <limits>
150 #include <map>
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";
169  "llvm.loop.vectorize.followup_vectorized";
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 
179  "enable-epilogue-vectorization", cl::init(true), cl::Hidden,
180  cl::desc("Enable vectorization of epilogue loops."));
181 
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 
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.
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 
202  "vectorize-memory-check-threshold", cl::init(128), cl::Hidden,
203  cl::desc("The maximum allowed number of runtime memory checks"));
204 
205 // Option prefer-predicate-over-epilogue indicates that an epilogue is undesired,
206 // that predication is preferred, and this lists all options. I.e., the
207 // vectorizer will try to fold the tail-loop (epilogue) into the vector body
208 // and predicate the instructions accordingly. If tail-folding fails, there are
209 // different fallback strategies depending on these values:
210 namespace PreferPredicateTy {
211  enum Option {
215  };
216 } // namespace PreferPredicateTy
217 
219  "prefer-predicate-over-epilogue",
221  cl::Hidden,
222  cl::desc("Tail-folding and predication preferences over creating a scalar "
223  "epilogue loop."),
225  "scalar-epilogue",
226  "Don't tail-predicate loops, create scalar epilogue"),
228  "predicate-else-scalar-epilogue",
229  "prefer tail-folding, create scalar epilogue if tail "
230  "folding fails."),
232  "predicate-dont-vectorize",
233  "prefers tail-folding, don't attempt vectorization if "
234  "tail-folding fails.")));
235 
237  "vectorizer-maximize-bandwidth", cl::init(false), cl::Hidden,
238  cl::desc("Maximize bandwidth when selecting vectorization factor which "
239  "will be determined by the smallest type in loop."));
240 
242  "enable-interleaved-mem-accesses", cl::init(false), cl::Hidden,
243  cl::desc("Enable vectorization on interleaved memory accesses in a loop"));
244 
245 /// An interleave-group may need masking if it resides in a block that needs
246 /// predication, or in order to mask away gaps.
248  "enable-masked-interleaved-mem-accesses", cl::init(false), cl::Hidden,
249  cl::desc("Enable vectorization on masked interleaved memory accesses in a loop"));
250 
252  "tiny-trip-count-interleave-threshold", cl::init(128), cl::Hidden,
253  cl::desc("We don't interleave loops with a estimated constant trip count "
254  "below this number"));
255 
257  "force-target-num-scalar-regs", cl::init(0), cl::Hidden,
258  cl::desc("A flag that overrides the target's number of scalar registers."));
259 
261  "force-target-num-vector-regs", cl::init(0), cl::Hidden,
262  cl::desc("A flag that overrides the target's number of vector registers."));
263 
265  "force-target-max-scalar-interleave", cl::init(0), cl::Hidden,
266  cl::desc("A flag that overrides the target's max interleave factor for "
267  "scalar loops."));
268 
270  "force-target-max-vector-interleave", cl::init(0), cl::Hidden,
271  cl::desc("A flag that overrides the target's max interleave factor for "
272  "vectorized loops."));
273 
275  "force-target-instruction-cost", cl::init(0), cl::Hidden,
276  cl::desc("A flag that overrides the target's expected cost for "
277  "an instruction to a single constant value. Mostly "
278  "useful for getting consistent testing."));
279 
281  "force-target-supports-scalable-vectors", cl::init(false), cl::Hidden,
282  cl::desc(
283  "Pretend that scalable vectors are supported, even if the target does "
284  "not support them. This flag should only be used for testing."));
285 
287  "small-loop-cost", cl::init(20), cl::Hidden,
288  cl::desc(
289  "The cost of a loop that is considered 'small' by the interleaver."));
290 
292  "loop-vectorize-with-block-frequency", cl::init(true), cl::Hidden,
293  cl::desc("Enable the use of the block frequency analysis to access PGO "
294  "heuristics minimizing code growth in cold regions and being more "
295  "aggressive in hot regions."));
296 
297 // Runtime interleave loops for load/store throughput.
299  "enable-loadstore-runtime-interleave", cl::init(true), cl::Hidden,
300  cl::desc(
301  "Enable runtime interleaving until load/store ports are saturated"));
302 
303 /// Interleave small loops with scalar reductions.
305  "interleave-small-loop-scalar-reduction", cl::init(false), cl::Hidden,
306  cl::desc("Enable interleaving for loops with small iteration counts that "
307  "contain scalar reductions to expose ILP."));
308 
309 /// The number of stores in a loop that are allowed to need predication.
311  "vectorize-num-stores-pred", cl::init(1), cl::Hidden,
312  cl::desc("Max number of stores to be predicated behind an if."));
313 
315  "enable-ind-var-reg-heur", cl::init(true), cl::Hidden,
316  cl::desc("Count the induction variable only once when interleaving"));
317 
319  "enable-cond-stores-vec", cl::init(true), cl::Hidden,
320  cl::desc("Enable if predication of stores during vectorization."));
321 
323  "max-nested-scalar-reduction-interleave", cl::init(2), cl::Hidden,
324  cl::desc("The maximum interleave count to use when interleaving a scalar "
325  "reduction in a nested loop."));
326 
327 static cl::opt<bool>
328  PreferInLoopReductions("prefer-inloop-reductions", cl::init(false),
329  cl::Hidden,
330  cl::desc("Prefer in-loop vector reductions, "
331  "overriding the targets preference."));
332 
334  "force-ordered-reductions", cl::init(false), cl::Hidden,
335  cl::desc("Enable the vectorisation of loops with in-order (strict) "
336  "FP reductions"));
337 
339  "prefer-predicated-reduction-select", cl::init(false), cl::Hidden,
340  cl::desc(
341  "Prefer predicating a reduction operation over an after loop select."));
342 
344  "enable-vplan-native-path", cl::init(false), cl::Hidden,
345  cl::desc("Enable VPlan-native vectorization path with "
346  "support for outer loop vectorization."));
347 
348 // This flag enables the stress testing of the VPlan H-CFG construction in the
349 // VPlan-native vectorization path. It must be used in conjuction with
350 // -enable-vplan-native-path. -vplan-verify-hcfg can also be used to enable the
351 // verification of the H-CFGs built.
353  "vplan-build-stress-test", cl::init(false), cl::Hidden,
354  cl::desc(
355  "Build VPlan for every supported loop nest in the function and bail "
356  "out right after the build (stress test the VPlan H-CFG construction "
357  "in the VPlan-native vectorization path)."));
358 
360  "interleave-loops", cl::init(true), cl::Hidden,
361  cl::desc("Enable loop interleaving in Loop vectorization passes"));
363  "vectorize-loops", cl::init(true), cl::Hidden,
364  cl::desc("Run the Loop vectorization passes"));
365 
367  "vplan-print-in-dot-format", cl::init(false), cl::Hidden,
368  cl::desc("Use dot format instead of plain text when dumping VPlans"));
369 
371  "force-widen-divrem-via-safe-divisor", cl::Hidden,
372  cl::desc("Override cost based safe divisor widening for div/rem instructions"));
373 
374 /// A helper function that returns true if the given type is irregular. The
375 /// type is irregular if its allocated size doesn't equal the store size of an
376 /// element of the corresponding vector type.
377 static bool hasIrregularType(Type *Ty, const DataLayout &DL) {
378  // Determine if an array of N elements of type Ty is "bitcast compatible"
379  // with a <N x Ty> vector.
380  // This is only true if there is no padding between the array elements.
381  return DL.getTypeAllocSizeInBits(Ty) != DL.getTypeSizeInBits(Ty);
382 }
383 
384 /// A helper function that returns the reciprocal of the block probability of
385 /// predicated blocks. If we return X, we are assuming the predicated block
386 /// will execute once for every X iterations of the loop header.
387 ///
388 /// TODO: We should use actual block probability here, if available. Currently,
389 /// we always assume predicated blocks have a 50% chance of executing.
390 static unsigned getReciprocalPredBlockProb() { return 2; }
391 
392 /// A helper function that returns an integer or floating-point constant with
393 /// value C.
394 static Constant *getSignedIntOrFpConstant(Type *Ty, int64_t C) {
395  return Ty->isIntegerTy() ? ConstantInt::getSigned(Ty, C)
396  : ConstantFP::get(Ty, C);
397 }
398 
399 /// Returns "best known" trip count for the specified loop \p L as defined by
400 /// the following procedure:
401 /// 1) Returns exact trip count if it is known.
402 /// 2) Returns expected trip count according to profile data if any.
403 /// 3) Returns upper bound estimate if it is known.
404 /// 4) Returns None if all of the above failed.
406  // Check if exact trip count is known.
407  if (unsigned ExpectedTC = SE.getSmallConstantTripCount(L))
408  return ExpectedTC;
409 
410  // Check if there is an expected trip count available from profile data.
412  if (auto EstimatedTC = getLoopEstimatedTripCount(L))
413  return EstimatedTC;
414 
415  // Check if upper bound estimate is known.
416  if (unsigned ExpectedTC = SE.getSmallConstantMaxTripCount(L))
417  return ExpectedTC;
418 
419  return None;
420 }
421 
422 // Forward declare GeneratedRTChecks.
423 class GeneratedRTChecks;
424 
425 namespace llvm {
426 
428 
429 /// InnerLoopVectorizer vectorizes loops which contain only one basic
430 /// block to a specified vectorization factor (VF).
431 /// This class performs the widening of scalars into vectors, or multiple
432 /// scalars. This class also implements the following features:
433 /// * It inserts an epilogue loop for handling loops that don't have iteration
434 /// counts that are known to be a multiple of the vectorization factor.
435 /// * It handles the code generation for reduction variables.
436 /// * Scalarization (implementation using scalars) of un-vectorizable
437 /// instructions.
438 /// InnerLoopVectorizer does not perform any vectorization-legality
439 /// checks, and relies on the caller to check for the different legality
440 /// aspects. The InnerLoopVectorizer relies on the
441 /// LoopVectorizationLegality class to provide information about the induction
442 /// and reduction variables that were found to a given vectorization factor.
444 public:
447  const TargetLibraryInfo *TLI,
451  unsigned UnrollFactor, LoopVectorizationLegality *LVL,
454  : OrigLoop(OrigLoop), PSE(PSE), LI(LI), DT(DT), TLI(TLI), TTI(TTI),
455  AC(AC), ORE(ORE), VF(VecWidth), UF(UnrollFactor),
456  Builder(PSE.getSE()->getContext()), Legal(LVL), Cost(CM), BFI(BFI),
457  PSI(PSI), RTChecks(RTChecks) {
458  // Query this against the original loop and save it here because the profile
459  // of the original loop header may change as the transformation happens.
462 
464  this->MinProfitableTripCount = VecWidth;
465  else
466  this->MinProfitableTripCount = MinProfitableTripCount;
467  }
468 
469  virtual ~InnerLoopVectorizer() = default;
470 
471  /// Create a new empty loop that will contain vectorized instructions later
472  /// on, while the old loop will be used as the scalar remainder. Control flow
473  /// is generated around the vectorized (and scalar epilogue) loops consisting
474  /// of various checks and bypasses. Return the pre-header block of the new
475  /// loop and the start value for the canonical induction, if it is != 0. The
476  /// latter is the case when vectorizing the epilogue loop. In the case of
477  /// epilogue vectorization, this function is overriden to handle the more
478  /// complex control flow around the loops.
479  virtual std::pair<BasicBlock *, Value *> createVectorizedLoopSkeleton();
480 
481  /// Fix the vectorized code, taking care of header phi's, live-outs, and more.
482  void fixVectorizedLoop(VPTransformState &State, VPlan &Plan);
483 
484  // Return true if any runtime check is added.
486 
487  /// A type for vectorized values in the new loop. Each value from the
488  /// original loop, when vectorized, is represented by UF vector values in the
489  /// new unrolled loop, where UF is the unroll factor.
491 
492  /// A helper function to scalarize a single Instruction in the innermost loop.
493  /// Generates a sequence of scalar instances for each lane between \p MinLane
494  /// and \p MaxLane, times each part between \p MinPart and \p MaxPart,
495  /// inclusive. Uses the VPValue operands from \p RepRecipe instead of \p
496  /// Instr's operands.
497  void scalarizeInstruction(const Instruction *Instr,
498  VPReplicateRecipe *RepRecipe,
499  const VPIteration &Instance, bool IfPredicateInstr,
500  VPTransformState &State);
501 
502  /// Construct the vector value of a scalarized value \p V one lane at a time.
503  void packScalarIntoVectorValue(VPValue *Def, const VPIteration &Instance,
504  VPTransformState &State);
505 
506  /// Try to vectorize interleaved access group \p Group with the base address
507  /// given in \p Addr, optionally masking the vector operations if \p
508  /// BlockInMask is non-null. Use \p State to translate given VPValues to IR
509  /// values in the vectorized loop.
511  ArrayRef<VPValue *> VPDefs,
512  VPTransformState &State, VPValue *Addr,
513  ArrayRef<VPValue *> StoredValues,
514  VPValue *BlockInMask = nullptr);
515 
516  /// Fix the non-induction PHIs in \p Plan.
517  void fixNonInductionPHIs(VPlan &Plan, VPTransformState &State);
518 
519  /// Returns true if the reordering of FP operations is not allowed, but we are
520  /// able to vectorize with strict in-order reductions for the given RdxDesc.
521  bool useOrderedReductions(const RecurrenceDescriptor &RdxDesc);
522 
523  /// Create a broadcast instruction. This method generates a broadcast
524  /// instruction (shuffle) for loop invariant values and for the induction
525  /// value. If this is the induction variable then we extend it to N, N+1, ...
526  /// this is needed because each iteration in the loop corresponds to a SIMD
527  /// element.
528  virtual Value *getBroadcastInstrs(Value *V);
529 
530  // Returns the resume value (bc.merge.rdx) for a reduction as
531  // generated by fixReduction.
533 
534  /// Create a new phi node for the induction variable \p OrigPhi to resume
535  /// iteration count in the scalar epilogue, from where the vectorized loop
536  /// left off. In cases where the loop skeleton is more complicated (eg.
537  /// epilogue vectorization) and the resume values can come from an additional
538  /// bypass block, the \p AdditionalBypass pair provides information about the
539  /// bypass block and the end value on the edge from bypass to this loop.
541  PHINode *OrigPhi, const InductionDescriptor &ID,
542  ArrayRef<BasicBlock *> BypassBlocks,
543  std::pair<BasicBlock *, Value *> AdditionalBypass = {nullptr, nullptr});
544 
545 protected:
547 
548  /// A small list of PHINodes.
550 
551  /// A type for scalarized values in the new loop. Each value from the
552  /// original loop, when scalarized, is represented by UF x VF scalar values
553  /// in the new unrolled loop, where UF is the unroll factor and VF is the
554  /// vectorization factor.
556 
557  /// Set up the values of the IVs correctly when exiting the vector loop.
558  void fixupIVUsers(PHINode *OrigPhi, const InductionDescriptor &II,
559  Value *VectorTripCount, Value *EndValue,
560  BasicBlock *MiddleBlock, BasicBlock *VectorHeader,
561  VPlan &Plan);
562 
563  /// Handle all cross-iteration phis in the header.
565 
566  /// Create the exit value of first order recurrences in the middle block and
567  /// update their users.
569  VPTransformState &State);
570 
571  /// Create code for the loop exit value of the reduction.
573 
574  /// Clear NSW/NUW flags from reduction instructions if necessary.
576  VPTransformState &State);
577 
578  /// Iteratively sink the scalarized operands of a predicated instruction into
579  /// the block that was created for it.
580  void sinkScalarOperands(Instruction *PredInst);
581 
582  /// Shrinks vector element sizes to the smallest bitwidth they can be legally
583  /// represented as.
585 
586  /// Returns (and creates if needed) the original loop trip count.
587  Value *getOrCreateTripCount(BasicBlock *InsertBlock);
588 
589  /// Returns (and creates if needed) the trip count of the widened loop.
591 
592  /// Returns a bitcasted value to the requested vector type.
593  /// Also handles bitcasts of vector<float> <-> vector<pointer> types.
595  const DataLayout &DL);
596 
597  /// Emit a bypass check to see if the vector trip count is zero, including if
598  /// it overflows.
599  void emitIterationCountCheck(BasicBlock *Bypass);
600 
601  /// Emit a bypass check to see if all of the SCEV assumptions we've
602  /// had to make are correct. Returns the block containing the checks or
603  /// nullptr if no checks have been added.
605 
606  /// Emit bypass checks to check any memory assumptions we may have made.
607  /// Returns the block containing the checks or nullptr if no checks have been
608  /// added.
610 
611  /// Emit basic blocks (prefixed with \p Prefix) for the iteration check,
612  /// vector loop preheader, middle block and scalar preheader.
614 
615  /// Create new phi nodes for the induction variables to resume iteration count
616  /// in the scalar epilogue, from where the vectorized loop left off.
617  /// In cases where the loop skeleton is more complicated (eg. epilogue
618  /// vectorization) and the resume values can come from an additional bypass
619  /// block, the \p AdditionalBypass pair provides information about the bypass
620  /// block and the end value on the edge from bypass to this loop.
622  std::pair<BasicBlock *, Value *> AdditionalBypass = {nullptr, nullptr});
623 
624  /// Complete the loop skeleton by adding debug MDs, creating appropriate
625  /// conditional branches in the middle block, preparing the builder and
626  /// running the verifier. Return the preheader of the completed vector loop.
627  BasicBlock *completeLoopSkeleton(MDNode *OrigLoopID);
628 
629  /// Collect poison-generating recipes that may generate a poison value that is
630  /// used after vectorization, even when their operands are not poison. Those
631  /// recipes meet the following conditions:
632  /// * Contribute to the address computation of a recipe generating a widen
633  /// memory load/store (VPWidenMemoryInstructionRecipe or
634  /// VPInterleaveRecipe).
635  /// * Such a widen memory load/store has at least one underlying Instruction
636  /// that is in a basic block that needs predication and after vectorization
637  /// the generated instruction won't be predicated.
639 
640  /// Allow subclasses to override and print debug traces before/after vplan
641  /// execution, when trace information is requested.
642  virtual void printDebugTracesAtStart(){};
643  virtual void printDebugTracesAtEnd(){};
644 
645  /// The original loop.
646  Loop *OrigLoop;
647 
648  /// A wrapper around ScalarEvolution used to add runtime SCEV checks. Applies
649  /// dynamic knowledge to simplify SCEV expressions and converts them to a
650  /// more usable form.
652 
653  /// Loop Info.
655 
656  /// Dominator Tree.
658 
659  /// Alias Analysis.
661 
662  /// Target Library Info.
664 
665  /// Target Transform Info.
667 
668  /// Assumption Cache.
670 
671  /// Interface to emit optimization remarks.
673 
674  /// The vectorization SIMD factor to use. Each vector will have this many
675  /// vector elements.
677 
679 
680  /// The vectorization unroll factor to use. Each scalar is vectorized to this
681  /// many different vector instructions.
682  unsigned UF;
683 
684  /// The builder that we use
686 
687  // --- Vectorization state ---
688 
689  /// The vector-loop preheader.
691 
692  /// The scalar-loop preheader.
694 
695  /// Middle Block between the vector and the scalar.
697 
698  /// The unique ExitBlock of the scalar loop if one exists. Note that
699  /// there can be multiple exiting edges reaching this block.
701 
702  /// The scalar loop body.
704 
705  /// A list of all bypass blocks. The first block is the entry of the loop.
707 
708  /// Store instructions that were predicated.
710 
711  /// Trip count of the original loop.
712  Value *TripCount = nullptr;
713 
714  /// Trip count of the widened loop (TripCount - TripCount % (VF*UF))
715  Value *VectorTripCount = nullptr;
716 
717  /// The legality analysis.
719 
720  /// The profitablity analysis.
722 
723  // Record whether runtime checks are added.
724  bool AddedSafetyChecks = false;
725 
726  // Holds the end values for each induction variable. We save the end values
727  // so we can later fix-up the external users of the induction variables.
729 
730  /// BFI and PSI are used to check for profile guided size optimizations.
733 
734  // Whether this loop should be optimized for size based on profile guided size
735  // optimizatios.
737 
738  /// Structure to hold information about generated runtime checks, responsible
739  /// for cleaning the checks, if vectorization turns out unprofitable.
741 
742  // Holds the resume values for reductions in the loops, used to set the
743  // correct start value of reduction PHIs when vectorizing the epilogue.
746 };
747 
749 public:
752  const TargetLibraryInfo *TLI,
754  OptimizationRemarkEmitter *ORE, unsigned UnrollFactor,
759  ElementCount::getFixed(1),
760  ElementCount::getFixed(1), UnrollFactor, LVL, CM,
761  BFI, PSI, Check) {}
762 
763 private:
764  Value *getBroadcastInstrs(Value *V) override;
765 };
766 
767 /// Encapsulate information regarding vectorization of a loop and its epilogue.
768 /// This information is meant to be updated and used across two stages of
769 /// epilogue vectorization.
772  unsigned MainLoopUF = 0;
774  unsigned EpilogueUF = 0;
779  Value *TripCount = nullptr;
780  Value *VectorTripCount = nullptr;
781 
783  ElementCount EVF, unsigned EUF)
784  : MainLoopVF(MVF), MainLoopUF(MUF), EpilogueVF(EVF), EpilogueUF(EUF) {
785  assert(EUF == 1 &&
786  "A high UF for the epilogue loop is likely not beneficial.");
787  }
788 };
789 
790 /// An extension of the inner loop vectorizer that creates a skeleton for a
791 /// vectorized loop that has its epilogue (residual) also vectorized.
792 /// The idea is to run the vplan on a given loop twice, firstly to setup the
793 /// skeleton and vectorize the main loop, and secondly to complete the skeleton
794 /// from the first step and vectorize the epilogue. This is achieved by
795 /// deriving two concrete strategy classes from this base class and invoking
796 /// them in succession from the loop vectorizer planner.
798 public:
806  GeneratedRTChecks &Checks)
808  EPI.MainLoopVF, EPI.MainLoopVF, EPI.MainLoopUF, LVL,
809  CM, BFI, PSI, Checks),
810  EPI(EPI) {}
811 
812  // Override this function to handle the more complex control flow around the
813  // three loops.
814  std::pair<BasicBlock *, Value *> createVectorizedLoopSkeleton() final {
816  }
817 
818  /// The interface for creating a vectorized skeleton using one of two
819  /// different strategies, each corresponding to one execution of the vplan
820  /// as described above.
821  virtual std::pair<BasicBlock *, Value *>
823 
824  /// Holds and updates state information required to vectorize the main loop
825  /// and its epilogue in two separate passes. This setup helps us avoid
826  /// regenerating and recomputing runtime safety checks. It also helps us to
827  /// shorten the iteration-count-check path length for the cases where the
828  /// iteration count of the loop is so small that the main vector loop is
829  /// completely skipped.
831 };
832 
833 /// A specialized derived class of inner loop vectorizer that performs
834 /// vectorization of *main* loops in the process of vectorizing loops and their
835 /// epilogues.
837 public:
847  EPI, LVL, CM, BFI, PSI, Check) {}
848  /// Implements the interface for creating a vectorized skeleton using the
849  /// *main loop* strategy (ie the first pass of vplan execution).
850  std::pair<BasicBlock *, Value *> createEpilogueVectorizedLoopSkeleton() final;
851 
852 protected:
853  /// Emits an iteration count bypass check once for the main loop (when \p
854  /// ForEpilogue is false) and once for the epilogue loop (when \p
855  /// ForEpilogue is true).
856  BasicBlock *emitIterationCountCheck(BasicBlock *Bypass, bool ForEpilogue);
857  void printDebugTracesAtStart() override;
858  void printDebugTracesAtEnd() override;
859 };
860 
861 // A specialized derived class of inner loop vectorizer that performs
862 // vectorization of *epilogue* loops in the process of vectorizing loops and
863 // their epilogues.
865 public:
873  GeneratedRTChecks &Checks)
875  EPI, LVL, CM, BFI, PSI, Checks) {
877  }
878  /// Implements the interface for creating a vectorized skeleton using the
879  /// *epilogue loop* strategy (ie the second pass of vplan execution).
880  std::pair<BasicBlock *, Value *> createEpilogueVectorizedLoopSkeleton() final;
881 
882 protected:
883  /// Emits an iteration count bypass check after the main vector loop has
884  /// finished to see if there are any iterations left to execute by either
885  /// the vector epilogue or the scalar epilogue.
886  BasicBlock *emitMinimumVectorEpilogueIterCountCheck(
887  BasicBlock *Bypass,
888  BasicBlock *Insert);
889  void printDebugTracesAtStart() override;
890  void printDebugTracesAtEnd() override;
891 };
892 } // end namespace llvm
893 
894 /// Look for a meaningful debug location on the instruction or it's
895 /// operands.
897  if (!I)
898  return I;
899 
900  DebugLoc Empty;
901  if (I->getDebugLoc() != Empty)
902  return I;
903 
904  for (Use &Op : I->operands()) {
905  if (Instruction *OpInst = dyn_cast<Instruction>(Op))
906  if (OpInst->getDebugLoc() != Empty)
907  return OpInst;
908  }
909 
910  return I;
911 }
912 
913 /// Write a \p DebugMsg about vectorization to the debug output stream. If \p I
914 /// is passed, the message relates to that particular instruction.
915 #ifndef NDEBUG
917  const StringRef DebugMsg,
918  Instruction *I) {
919  dbgs() << "LV: " << Prefix << DebugMsg;
920  if (I != nullptr)
921  dbgs() << " " << *I;
922  else
923  dbgs() << '.';
924  dbgs() << '\n';
925 }
926 #endif
927 
928 /// Create an analysis remark that explains why vectorization failed
929 ///
930 /// \p PassName is the name of the pass (e.g. can be AlwaysPrint). \p
931 /// RemarkName is the identifier for the remark. If \p I is passed it is an
932 /// instruction that prevents vectorization. Otherwise \p TheLoop is used for
933 /// the location of the remark. \return the remark object that can be
934 /// streamed to.
936  StringRef RemarkName, Loop *TheLoop, Instruction *I) {
937  Value *CodeRegion = TheLoop->getHeader();
938  DebugLoc DL = TheLoop->getStartLoc();
939 
940  if (I) {
941  CodeRegion = I->getParent();
942  // If there is no debug location attached to the instruction, revert back to
943  // using the loop's.
944  if (I->getDebugLoc())
945  DL = I->getDebugLoc();
946  }
947 
948  return OptimizationRemarkAnalysis(PassName, RemarkName, DL, CodeRegion);
949 }
950 
951 namespace llvm {
952 
953 /// Return a value for Step multiplied by VF.
955  int64_t Step) {
956  assert(Ty->isIntegerTy() && "Expected an integer step");
957  Constant *StepVal = ConstantInt::get(Ty, Step * VF.getKnownMinValue());
958  return VF.isScalable() ? B.CreateVScale(StepVal) : StepVal;
959 }
960 
961 /// Return the runtime value for VF.
964  return VF.isScalable() ? B.CreateVScale(EC) : EC;
965 }
966 
968  ElementCount VF) {
969  assert(FTy->isFloatingPointTy() && "Expected floating point type!");
970  Type *IntTy = IntegerType::get(FTy->getContext(), FTy->getScalarSizeInBits());
971  Value *RuntimeVF = getRuntimeVF(B, IntTy, VF);
972  return B.CreateUIToFP(RuntimeVF, FTy);
973 }
974 
976  const StringRef OREMsg, const StringRef ORETag,
978  Instruction *I) {
979  LLVM_DEBUG(debugVectorizationMessage("Not vectorizing: ", DebugMsg, I));
980  LoopVectorizeHints Hints(TheLoop, true /* doesn't matter */, *ORE);
981  ORE->emit(
982  createLVAnalysis(Hints.vectorizeAnalysisPassName(), ORETag, TheLoop, I)
983  << "loop not vectorized: " << OREMsg);
984 }
985 
988  Instruction *I) {
990  LoopVectorizeHints Hints(TheLoop, true /* doesn't matter */, *ORE);
991  ORE->emit(
992  createLVAnalysis(Hints.vectorizeAnalysisPassName(), ORETag, TheLoop, I)
993  << Msg);
994 }
995 
996 } // end namespace llvm
997 
998 #ifndef NDEBUG
999 /// \return string containing a file name and a line # for the given loop.
1000 static std::string getDebugLocString(const Loop *L) {
1001  std::string Result;
1002  if (L) {
1003  raw_string_ostream OS(Result);
1004  if (const DebugLoc LoopDbgLoc = L->getStartLoc())
1005  LoopDbgLoc.print(OS);
1006  else
1007  // Just print the module name.
1008  OS << L->getHeader()->getParent()->getParent()->getModuleIdentifier();
1009  OS.flush();
1010  }
1011  return Result;
1012 }
1013 #endif
1014 
1016  VPTransformState &State) {
1017 
1018  // Collect recipes in the backward slice of `Root` that may generate a poison
1019  // value that is used after vectorization.
1021  auto collectPoisonGeneratingInstrsInBackwardSlice([&](VPRecipeBase *Root) {
1023  Worklist.push_back(Root);
1024 
1025  // Traverse the backward slice of Root through its use-def chain.
1026  while (!Worklist.empty()) {
1027  VPRecipeBase *CurRec = Worklist.back();
1028  Worklist.pop_back();
1029 
1030  if (!Visited.insert(CurRec).second)
1031  continue;
1032 
1033  // Prune search if we find another recipe generating a widen memory
1034  // instruction. Widen memory instructions involved in address computation
1035  // will lead to gather/scatter instructions, which don't need to be
1036  // handled.
1037  if (isa<VPWidenMemoryInstructionRecipe>(CurRec) ||
1038  isa<VPInterleaveRecipe>(CurRec) ||
1039  isa<VPScalarIVStepsRecipe>(CurRec) ||
1040  isa<VPCanonicalIVPHIRecipe>(CurRec) ||
1041  isa<VPActiveLaneMaskPHIRecipe>(CurRec))
1042  continue;
1043 
1044  // This recipe contributes to the address computation of a widen
1045  // load/store. Collect recipe if its underlying instruction has
1046  // poison-generating flags.
1047  Instruction *Instr = CurRec->getUnderlyingInstr();
1048  if (Instr && Instr->hasPoisonGeneratingFlags())
1049  State.MayGeneratePoisonRecipes.insert(CurRec);
1050 
1051  // Add new definitions to the worklist.
1052  for (VPValue *operand : CurRec->operands())
1053  if (VPDef *OpDef = operand->getDef())
1054  Worklist.push_back(cast<VPRecipeBase>(OpDef));
1055  }
1056  });
1057 
1058  // Traverse all the recipes in the VPlan and collect the poison-generating
1059  // recipes in the backward slice starting at the address of a VPWidenRecipe or
1060  // VPInterleaveRecipe.
1061  auto Iter = depth_first(
1063  for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(Iter)) {
1064  for (VPRecipeBase &Recipe : *VPBB) {
1065  if (auto *WidenRec = dyn_cast<VPWidenMemoryInstructionRecipe>(&Recipe)) {
1066  Instruction &UnderlyingInstr = WidenRec->getIngredient();
1067  VPDef *AddrDef = WidenRec->getAddr()->getDef();
1068  if (AddrDef && WidenRec->isConsecutive() &&
1069  Legal->blockNeedsPredication(UnderlyingInstr.getParent()))
1070  collectPoisonGeneratingInstrsInBackwardSlice(
1071  cast<VPRecipeBase>(AddrDef));
1072  } else if (auto *InterleaveRec = dyn_cast<VPInterleaveRecipe>(&Recipe)) {
1073  VPDef *AddrDef = InterleaveRec->getAddr()->getDef();
1074  if (AddrDef) {
1075  // Check if any member of the interleave group needs predication.
1076  const InterleaveGroup<Instruction> *InterGroup =
1077  InterleaveRec->getInterleaveGroup();
1078  bool NeedPredication = false;
1079  for (int I = 0, NumMembers = InterGroup->getNumMembers();
1080  I < NumMembers; ++I) {
1081  Instruction *Member = InterGroup->getMember(I);
1082  if (Member)
1083  NeedPredication |=
1084  Legal->blockNeedsPredication(Member->getParent());
1085  }
1086 
1087  if (NeedPredication)
1088  collectPoisonGeneratingInstrsInBackwardSlice(
1089  cast<VPRecipeBase>(AddrDef));
1090  }
1091  }
1092  }
1093  }
1094 }
1095 
1097  const RecurrenceDescriptor &RdxDesc) {
1098  auto It = ReductionResumeValues.find(&RdxDesc);
1099  assert(It != ReductionResumeValues.end() &&
1100  "Expected to find a resume value for the reduction.");
1101  return It->second;
1102 }
1103 
1104 namespace llvm {
1105 
1106 // Loop vectorization cost-model hints how the scalar epilogue loop should be
1107 // lowered.
1109 
1110  // The default: allowing scalar epilogues.
1112 
1113  // Vectorization with OptForSize: don't allow epilogues.
1115 
1116  // A special case of vectorisation with OptForSize: loops with a very small
1117  // trip count are considered for vectorization under OptForSize, thereby
1118  // making sure the cost of their loop body is dominant, free of runtime
1119  // guards and scalar iteration overheads.
1121 
1122  // Loop hint predicate indicating an epilogue is undesired.
1124 
1125  // Directive indicating we must either tail fold or not vectorize
1127 };
1128 
1129 /// ElementCountComparator creates a total ordering for ElementCount
1130 /// for the purposes of using it in a set structure.
1132  bool operator()(const ElementCount &LHS, const ElementCount &RHS) const {
1133  return std::make_tuple(LHS.isScalable(), LHS.getKnownMinValue()) <
1134  std::make_tuple(RHS.isScalable(), RHS.getKnownMinValue());
1135  }
1136 };
1138 
1139 /// LoopVectorizationCostModel - estimates the expected speedups due to
1140 /// vectorization.
1141 /// In many cases vectorization is not profitable. This can happen because of
1142 /// a number of reasons. In this class we mainly attempt to predict the
1143 /// expected speedup/slowdowns due to the supported instruction set. We use the
1144 /// TargetTransformInfo to query the different backends for the cost of
1145 /// different operations.
1147 public:
1151  const TargetTransformInfo &TTI,
1152  const TargetLibraryInfo *TLI, DemandedBits *DB,
1155  const LoopVectorizeHints *Hints,
1156  InterleavedAccessInfo &IAI)
1157  : ScalarEpilogueStatus(SEL), TheLoop(L), PSE(PSE), LI(LI), Legal(Legal),
1158  TTI(TTI), TLI(TLI), DB(DB), AC(AC), ORE(ORE), TheFunction(F),
1159  Hints(Hints), InterleaveInfo(IAI) {}
1160 
1161  /// \return An upper bound for the vectorization factors (both fixed and
1162  /// scalable). If the factors are 0, vectorization and interleaving should be
1163  /// avoided up front.
1164  FixedScalableVFPair computeMaxVF(ElementCount UserVF, unsigned UserIC);
1165 
1166  /// \return True if runtime checks are required for vectorization, and false
1167  /// otherwise.
1168  bool runtimeChecksRequired();
1169 
1170  /// \return The most profitable vectorization factor and the cost of that VF.
1171  /// This method checks every VF in \p CandidateVFs. If UserVF is not ZERO
1172  /// then this vectorization factor will be selected if vectorization is
1173  /// possible.
1175  selectVectorizationFactor(const ElementCountSet &CandidateVFs);
1176 
1178  selectEpilogueVectorizationFactor(const ElementCount MaxVF,
1179  const LoopVectorizationPlanner &LVP);
1180 
1181  /// Setup cost-based decisions for user vectorization factor.
1182  /// \return true if the UserVF is a feasible VF to be chosen.
1184  collectUniformsAndScalars(UserVF);
1185  collectInstsToScalarize(UserVF);
1186  return expectedCost(UserVF).first.isValid();
1187  }
1188 
1189  /// \return The size (in bits) of the smallest and widest types in the code
1190  /// that needs to be vectorized. We ignore values that remain scalar such as
1191  /// 64 bit loop indices.
1192  std::pair<unsigned, unsigned> getSmallestAndWidestTypes();
1193 
1194  /// \return The desired interleave count.
1195  /// If interleave count has been specified by metadata it will be returned.
1196  /// Otherwise, the interleave count is computed and returned. VF and LoopCost
1197  /// are the selected vectorization factor and the cost of the selected VF.
1198  unsigned selectInterleaveCount(ElementCount VF, InstructionCost LoopCost);
1199 
1200  /// Memory access instruction may be vectorized in more than one way.
1201  /// Form of instruction after vectorization depends on cost.
1202  /// This function takes cost-based decisions for Load/Store instructions
1203  /// and collects them in a map. This decisions map is used for building
1204  /// the lists of loop-uniform and loop-scalar instructions.
1205  /// The calculated cost is saved with widening decision in order to
1206  /// avoid redundant calculations.
1207  void setCostBasedWideningDecision(ElementCount VF);
1208 
1209  /// A struct that represents some properties of the register usage
1210  /// of a loop.
1211  struct RegisterUsage {
1212  /// Holds the number of loop invariant values that are used in the loop.
1213  /// The key is ClassID of target-provided register class.
1215  /// Holds the maximum number of concurrent live intervals in the loop.
1216  /// The key is ClassID of target-provided register class.
1218  };
1219 
1220  /// \return Returns information about the register usages of the loop for the
1221  /// given vectorization factors.
1223  calculateRegisterUsage(ArrayRef<ElementCount> VFs);
1224 
1225  /// Collect values we want to ignore in the cost model.
1226  void collectValuesToIgnore();
1227 
1228  /// Collect all element types in the loop for which widening is needed.
1229  void collectElementTypesForWidening();
1230 
1231  /// Split reductions into those that happen in the loop, and those that happen
1232  /// outside. In loop reductions are collected into InLoopReductionChains.
1233  void collectInLoopReductions();
1234 
1235  /// Returns true if we should use strict in-order reductions for the given
1236  /// RdxDesc. This is true if the -enable-strict-reductions flag is passed,
1237  /// the IsOrdered flag of RdxDesc is set and we do not allow reordering
1238  /// of FP operations.
1239  bool useOrderedReductions(const RecurrenceDescriptor &RdxDesc) const {
1240  return !Hints->allowReordering() && RdxDesc.isOrdered();
1241  }
1242 
1243  /// \returns The smallest bitwidth each instruction can be represented with.
1244  /// The vector equivalents of these instructions should be truncated to this
1245  /// type.
1247  return MinBWs;
1248  }
1249 
1250  /// \returns True if it is more profitable to scalarize instruction \p I for
1251  /// vectorization factor \p VF.
1253  assert(VF.isVector() &&
1254  "Profitable to scalarize relevant only for VF > 1.");
1255 
1256  // Cost model is not run in the VPlan-native path - return conservative
1257  // result until this changes.
1259  return false;
1260 
1261  auto Scalars = InstsToScalarize.find(VF);
1262  assert(Scalars != InstsToScalarize.end() &&
1263  "VF not yet analyzed for scalarization profitability");
1264  return Scalars->second.find(I) != Scalars->second.end();
1265  }
1266 
1267  /// Returns true if \p I is known to be uniform after vectorization.
1269  if (VF.isScalar())
1270  return true;
1271 
1272  // Cost model is not run in the VPlan-native path - return conservative
1273  // result until this changes.
1275  return false;
1276 
1277  auto UniformsPerVF = Uniforms.find(VF);
1278  assert(UniformsPerVF != Uniforms.end() &&
1279  "VF not yet analyzed for uniformity");
1280  return UniformsPerVF->second.count(I);
1281  }
1282 
1283  /// Returns true if \p I is known to be scalar after vectorization.
1285  if (VF.isScalar())
1286  return true;
1287 
1288  // Cost model is not run in the VPlan-native path - return conservative
1289  // result until this changes.
1291  return false;
1292 
1293  auto ScalarsPerVF = Scalars.find(VF);
1294  assert(ScalarsPerVF != Scalars.end() &&
1295  "Scalar values are not calculated for VF");
1296  return ScalarsPerVF->second.count(I);
1297  }
1298 
1299  /// \returns True if instruction \p I can be truncated to a smaller bitwidth
1300  /// for vectorization factor \p VF.
1302  return VF.isVector() && MinBWs.find(I) != MinBWs.end() &&
1303  !isProfitableToScalarize(I, VF) &&
1304  !isScalarAfterVectorization(I, VF);
1305  }
1306 
1307  /// Decision that was taken during cost calculation for memory instruction.
1310  CM_Widen, // For consecutive accesses with stride +1.
1311  CM_Widen_Reverse, // For consecutive accesses with stride -1.
1314  CM_Scalarize
1315  };
1316 
1317  /// Save vectorization decision \p W and \p Cost taken by the cost model for
1318  /// instruction \p I and vector width \p VF.
1321  assert(VF.isVector() && "Expected VF >=2");
1322  WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
1323  }
1324 
1325  /// Save vectorization decision \p W and \p Cost taken by the cost model for
1326  /// interleaving group \p Grp and vector width \p VF.
1330  assert(VF.isVector() && "Expected VF >=2");
1331  /// Broadcast this decicion to all instructions inside the group.
1332  /// But the cost will be assigned to one instruction only.
1333  for (unsigned i = 0; i < Grp->getFactor(); ++i) {
1334  if (auto *I = Grp->getMember(i)) {
1335  if (Grp->getInsertPos() == I)
1336  WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
1337  else
1338  WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, 0);
1339  }
1340  }
1341  }
1342 
1343  /// Return the cost model decision for the given instruction \p I and vector
1344  /// width \p VF. Return CM_Unknown if this instruction did not pass
1345  /// through the cost modeling.
1347  assert(VF.isVector() && "Expected VF to be a vector VF");
1348  // Cost model is not run in the VPlan-native path - return conservative
1349  // result until this changes.
1351  return CM_GatherScatter;
1352 
1353  std::pair<Instruction *, ElementCount> InstOnVF = std::make_pair(I, VF);
1354  auto Itr = WideningDecisions.find(InstOnVF);
1355  if (Itr == WideningDecisions.end())
1356  return CM_Unknown;
1357  return Itr->second.first;
1358  }
1359 
1360  /// Return the vectorization cost for the given instruction \p I and vector
1361  /// width \p VF.
1363  assert(VF.isVector() && "Expected VF >=2");
1364  std::pair<Instruction *, ElementCount> InstOnVF = std::make_pair(I, VF);
1365  assert(WideningDecisions.find(InstOnVF) != WideningDecisions.end() &&
1366  "The cost is not calculated");
1367  return WideningDecisions[InstOnVF].second;
1368  }
1369 
1370  /// Return True if instruction \p I is an optimizable truncate whose operand
1371  /// is an induction variable. Such a truncate will be removed by adding a new
1372  /// induction variable with the destination type.
1374  // If the instruction is not a truncate, return false.
1375  auto *Trunc = dyn_cast<TruncInst>(I);
1376  if (!Trunc)
1377  return false;
1378 
1379  // Get the source and destination types of the truncate.
1380  Type *SrcTy = ToVectorTy(cast<CastInst>(I)->getSrcTy(), VF);
1381  Type *DestTy = ToVectorTy(cast<CastInst>(I)->getDestTy(), VF);
1382 
1383  // If the truncate is free for the given types, return false. Replacing a
1384  // free truncate with an induction variable would add an induction variable
1385  // update instruction to each iteration of the loop. We exclude from this
1386  // check the primary induction variable since it will need an update
1387  // instruction regardless.
1388  Value *Op = Trunc->getOperand(0);
1389  if (Op != Legal->getPrimaryInduction() && TTI.isTruncateFree(SrcTy, DestTy))
1390  return false;
1391 
1392  // If the truncated value is not an induction variable, return false.
1393  return Legal->isInductionPhi(Op);
1394  }
1395 
1396  /// Collects the instructions to scalarize for each predicated instruction in
1397  /// the loop.
1398  void collectInstsToScalarize(ElementCount VF);
1399 
1400  /// Collect Uniform and Scalar values for the given \p VF.
1401  /// The sets depend on CM decision for Load/Store instructions
1402  /// that may be vectorized as interleave, gather-scatter or scalarized.
1404  // Do the analysis once.
1405  if (VF.isScalar() || Uniforms.find(VF) != Uniforms.end())
1406  return;
1407  setCostBasedWideningDecision(VF);
1408  collectLoopUniforms(VF);
1409  collectLoopScalars(VF);
1410  }
1411 
1412  /// Returns true if the target machine supports masked store operation
1413  /// for the given \p DataType and kind of access to \p Ptr.
1414  bool isLegalMaskedStore(Type *DataType, Value *Ptr, Align Alignment) const {
1415  return Legal->isConsecutivePtr(DataType, Ptr) &&
1416  TTI.isLegalMaskedStore(DataType, Alignment);
1417  }
1418 
1419  /// Returns true if the target machine supports masked load operation
1420  /// for the given \p DataType and kind of access to \p Ptr.
1421  bool isLegalMaskedLoad(Type *DataType, Value *Ptr, Align Alignment) const {
1422  return Legal->isConsecutivePtr(DataType, Ptr) &&
1423  TTI.isLegalMaskedLoad(DataType, Alignment);
1424  }
1425 
1426  /// Returns true if the target machine can represent \p V as a masked gather
1427  /// or scatter operation.
1430  bool LI = isa<LoadInst>(V);
1431  bool SI = isa<StoreInst>(V);
1432  if (!LI && !SI)
1433  return false;
1434  auto *Ty = getLoadStoreType(V);
1436  if (VF.isVector())
1437  Ty = VectorType::get(Ty, VF);
1438  return (LI && TTI.isLegalMaskedGather(Ty, Align)) ||
1439  (SI && TTI.isLegalMaskedScatter(Ty, Align));
1440  }
1441 
1442  /// Returns true if the target machine supports all of the reduction
1443  /// variables found for the given VF.
1445  return (all_of(Legal->getReductionVars(), [&](auto &Reduction) -> bool {
1446  const RecurrenceDescriptor &RdxDesc = Reduction.second;
1447  return TTI.isLegalToVectorizeReduction(RdxDesc, VF);
1448  }));
1449  }
1450 
1451  /// Given costs for both strategies, return true if the scalar predication
1452  /// lowering should be used for div/rem. This incorporates an override
1453  /// option so it is not simply a cost comparison.
1455  InstructionCost SafeDivisorCost) const {
1456  switch (ForceSafeDivisor) {
1457  case cl::BOU_UNSET:
1458  return ScalarCost < SafeDivisorCost;
1459  case cl::BOU_TRUE:
1460  return false;
1461  case cl::BOU_FALSE:
1462  return true;
1463  };
1464  llvm_unreachable("impossible case value");
1465  }
1466 
1467  /// Returns true if \p I is an instruction which requires predication and
1468  /// for which our chosen predication strategy is scalarization (i.e. we
1469  /// don't have an alternate strategy such as masking available).
1470  /// \p VF is the vectorization factor that will be used to vectorize \p I.
1471  bool isScalarWithPredication(Instruction *I, ElementCount VF) const;
1472 
1473  /// Returns true if \p I is an instruction that needs to be predicated
1474  /// at runtime. The result is independent of the predication mechanism.
1475  /// Superset of instructions that return true for isScalarWithPredication.
1476  bool isPredicatedInst(Instruction *I) const;
1477 
1478  /// Return the costs for our two available strategies for lowering a
1479  /// div/rem operation which requires speculating at least one lane.
1480  /// First result is for scalarization (will be invalid for scalable
1481  /// vectors); second is for the safe-divisor strategy.
1482  std::pair<InstructionCost, InstructionCost>
1483  getDivRemSpeculationCost(Instruction *I,
1484  ElementCount VF) const;
1485 
1486  /// Returns true if \p I is a memory instruction with consecutive memory
1487  /// access that can be widened.
1488  bool memoryInstructionCanBeWidened(Instruction *I, ElementCount VF);
1489 
1490  /// Returns true if \p I is a memory instruction in an interleaved-group
1491  /// of memory accesses that can be vectorized with wide vector loads/stores
1492  /// and shuffles.
1493  bool interleavedAccessCanBeWidened(Instruction *I, ElementCount VF);
1494 
1495  /// Check if \p Instr belongs to any interleaved access group.
1497  return InterleaveInfo.isInterleaved(Instr);
1498  }
1499 
1500  /// Get the interleaved access group that \p Instr belongs to.
1503  return InterleaveInfo.getInterleaveGroup(Instr);
1504  }
1505 
1506  /// Returns true if we're required to use a scalar epilogue for at least
1507  /// the final iteration of the original loop.
1509  if (!isScalarEpilogueAllowed())
1510  return false;
1511  // If we might exit from anywhere but the latch, must run the exiting
1512  // iteration in scalar form.
1513  if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch())
1514  return true;
1515  return VF.isVector() && InterleaveInfo.requiresScalarEpilogue();
1516  }
1517 
1518  /// Returns true if a scalar epilogue is not allowed due to optsize or a
1519  /// loop hint annotation.
1521  return ScalarEpilogueStatus == CM_ScalarEpilogueAllowed;
1522  }
1523 
1524  /// Returns true if all loop blocks should be masked to fold tail loop.
1525  bool foldTailByMasking() const { return FoldTailByMasking; }
1526 
1527  /// Returns true if were tail-folding and want to use the active lane mask
1528  /// for vector loop control flow.
1530  return FoldTailByMasking &&
1532  }
1533 
1534  /// Returns true if the instructions in this block requires predication
1535  /// for any reason, e.g. because tail folding now requires a predicate
1536  /// or because the block in the original loop was predicated.
1538  return foldTailByMasking() || Legal->blockNeedsPredication(BB);
1539  }
1540 
1541  /// A SmallMapVector to store the InLoop reduction op chains, mapping phi
1542  /// nodes to the chain of instructions representing the reductions. Uses a
1543  /// MapVector to ensure deterministic iteration order.
1544  using ReductionChainMap =
1546 
1547  /// Return the chain of instructions representing an inloop reduction.
1549  return InLoopReductionChains;
1550  }
1551 
1552  /// Returns true if the Phi is part of an inloop reduction.
1553  bool isInLoopReduction(PHINode *Phi) const {
1554  return InLoopReductionChains.count(Phi);
1555  }
1556 
1557  /// Estimate cost of an intrinsic call instruction CI if it were vectorized
1558  /// with factor VF. Return the cost of the instruction, including
1559  /// scalarization overhead if it's needed.
1560  InstructionCost getVectorIntrinsicCost(CallInst *CI, ElementCount VF) const;
1561 
1562  /// Estimate cost of a call instruction CI if it were vectorized with factor
1563  /// VF. Return the cost of the instruction, including scalarization overhead
1564  /// if it's needed. The flag NeedToScalarize shows if the call needs to be
1565  /// scalarized -
1566  /// i.e. either vector version isn't available, or is too expensive.
1567  InstructionCost getVectorCallCost(CallInst *CI, ElementCount VF,
1568  bool &NeedToScalarize) const;
1569 
1570  /// Returns true if the per-lane cost of VectorizationFactor A is lower than
1571  /// that of B.
1572  bool isMoreProfitable(const VectorizationFactor &A,
1573  const VectorizationFactor &B) const;
1574 
1575  /// Invalidates decisions already taken by the cost model.
1577  WideningDecisions.clear();
1578  Uniforms.clear();
1579  Scalars.clear();
1580  }
1581 
1582  /// Convenience function that returns the value of vscale_range iff
1583  /// vscale_range.min == vscale_range.max or otherwise returns the value
1584  /// returned by the corresponding TLI method.
1585  Optional<unsigned> getVScaleForTuning() const;
1586 
1587 private:
1588  unsigned NumPredStores = 0;
1589 
1590  /// \return An upper bound for the vectorization factors for both
1591  /// fixed and scalable vectorization, where the minimum-known number of
1592  /// elements is a power-of-2 larger than zero. If scalable vectorization is
1593  /// disabled or unsupported, then the scalable part will be equal to
1594  /// ElementCount::getScalable(0).
1595  FixedScalableVFPair computeFeasibleMaxVF(unsigned ConstTripCount,
1596  ElementCount UserVF,
1597  bool FoldTailByMasking);
1598 
1599  /// \return the maximized element count based on the targets vector
1600  /// registers and the loop trip-count, but limited to a maximum safe VF.
1601  /// This is a helper function of computeFeasibleMaxVF.
1602  ElementCount getMaximizedVFForTarget(unsigned ConstTripCount,
1603  unsigned SmallestType,
1604  unsigned WidestType,
1605  ElementCount MaxSafeVF,
1606  bool FoldTailByMasking);
1607 
1608  /// \return the maximum legal scalable VF, based on the safe max number
1609  /// of elements.
1610  ElementCount getMaxLegalScalableVF(unsigned MaxSafeElements);
1611 
1612  /// The vectorization cost is a combination of the cost itself and a boolean
1613  /// indicating whether any of the contributing operations will actually
1614  /// operate on vector values after type legalization in the backend. If this
1615  /// latter value is false, then all operations will be scalarized (i.e. no
1616  /// vectorization has actually taken place).
1617  using VectorizationCostTy = std::pair<InstructionCost, bool>;
1618 
1619  /// Returns the expected execution cost. The unit of the cost does
1620  /// not matter because we use the 'cost' units to compare different
1621  /// vector widths. The cost that is returned is *not* normalized by
1622  /// the factor width. If \p Invalid is not nullptr, this function
1623  /// will add a pair(Instruction*, ElementCount) to \p Invalid for
1624  /// each instruction that has an Invalid cost for the given VF.
1625  using InstructionVFPair = std::pair<Instruction *, ElementCount>;
1626  VectorizationCostTy
1627  expectedCost(ElementCount VF,
1628  SmallVectorImpl<InstructionVFPair> *Invalid = nullptr);
1629 
1630  /// Returns the execution time cost of an instruction for a given vector
1631  /// width. Vector width of one means scalar.
1632  VectorizationCostTy getInstructionCost(Instruction *I, ElementCount VF);
1633 
1634  /// The cost-computation logic from getInstructionCost which provides
1635  /// the vector type as an output parameter.
1636  InstructionCost getInstructionCost(Instruction *I, ElementCount VF,
1637  Type *&VectorTy);
1638 
1639  /// Return the cost of instructions in an inloop reduction pattern, if I is
1640  /// part of that pattern.
1642  getReductionPatternCost(Instruction *I, ElementCount VF, Type *VectorTy,
1644 
1645  /// Calculate vectorization cost of memory instruction \p I.
1646  InstructionCost getMemoryInstructionCost(Instruction *I, ElementCount VF);
1647 
1648  /// The cost computation for scalarized memory instruction.
1649  InstructionCost getMemInstScalarizationCost(Instruction *I, ElementCount VF);
1650 
1651  /// The cost computation for interleaving group of memory instructions.
1652  InstructionCost getInterleaveGroupCost(Instruction *I, ElementCount VF);
1653 
1654  /// The cost computation for Gather/Scatter instruction.
1655  InstructionCost getGatherScatterCost(Instruction *I, ElementCount VF);
1656 
1657  /// The cost computation for widening instruction \p I with consecutive
1658  /// memory access.
1659  InstructionCost getConsecutiveMemOpCost(Instruction *I, ElementCount VF);
1660 
1661  /// The cost calculation for Load/Store instruction \p I with uniform pointer -
1662  /// Load: scalar load + broadcast.
1663  /// Store: scalar store + (loop invariant value stored? 0 : extract of last
1664  /// element)
1665  InstructionCost getUniformMemOpCost(Instruction *I, ElementCount VF);
1666 
1667  /// Estimate the overhead of scalarizing an instruction. This is a
1668  /// convenience wrapper for the type-based getScalarizationOverhead API.
1669  InstructionCost getScalarizationOverhead(Instruction *I,
1670  ElementCount VF) const;
1671 
1672  /// Returns true if an artificially high cost for emulated masked memrefs
1673  /// should be used.
1674  bool useEmulatedMaskMemRefHack(Instruction *I, ElementCount VF);
1675 
1676  /// Map of scalar integer values to the smallest bitwidth they can be legally
1677  /// represented as. The vector equivalents of these values should be truncated
1678  /// to this type.
1680 
1681  /// A type representing the costs for instructions if they were to be
1682  /// scalarized rather than vectorized. The entries are Instruction-Cost
1683  /// pairs.
1684  using ScalarCostsTy = DenseMap<Instruction *, InstructionCost>;
1685 
1686  /// A set containing all BasicBlocks that are known to present after
1687  /// vectorization as a predicated block.
1689  PredicatedBBsAfterVectorization;
1690 
1691  /// Records whether it is allowed to have the original scalar loop execute at
1692  /// least once. This may be needed as a fallback loop in case runtime
1693  /// aliasing/dependence checks fail, or to handle the tail/remainder
1694  /// iterations when the trip count is unknown or doesn't divide by the VF,
1695  /// or as a peel-loop to handle gaps in interleave-groups.
1696  /// Under optsize and when the trip count is very small we don't allow any
1697  /// iterations to execute in the scalar loop.
1698  ScalarEpilogueLowering ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
1699 
1700  /// All blocks of loop are to be masked to fold tail of scalar iterations.
1701  bool FoldTailByMasking = false;
1702 
1703  /// A map holding scalar costs for different vectorization factors. The
1704  /// presence of a cost for an instruction in the mapping indicates that the
1705  /// instruction will be scalarized when vectorizing with the associated
1706  /// vectorization factor. The entries are VF-ScalarCostTy pairs.
1707  DenseMap<ElementCount, ScalarCostsTy> InstsToScalarize;
1708 
1709  /// Holds the instructions known to be uniform after vectorization.
1710  /// The data is collected per VF.
1712 
1713  /// Holds the instructions known to be scalar after vectorization.
1714  /// The data is collected per VF.
1716 
1717  /// Holds the instructions (address computations) that are forced to be
1718  /// scalarized.
1720 
1721  /// PHINodes of the reductions that should be expanded in-loop along with
1722  /// their associated chains of reduction operations, in program order from top
1723  /// (PHI) to bottom
1724  ReductionChainMap InLoopReductionChains;
1725 
1726  /// A Map of inloop reduction operations and their immediate chain operand.
1727  /// FIXME: This can be removed once reductions can be costed correctly in
1728  /// vplan. This was added to allow quick lookup to the inloop operations,
1729  /// without having to loop through InLoopReductionChains.
1730  DenseMap<Instruction *, Instruction *> InLoopReductionImmediateChains;
1731 
1732  /// Returns the expected difference in cost from scalarizing the expression
1733  /// feeding a predicated instruction \p PredInst. The instructions to
1734  /// scalarize and their scalar costs are collected in \p ScalarCosts. A
1735  /// non-negative return value implies the expression will be scalarized.
1736  /// Currently, only single-use chains are considered for scalarization.
1737  InstructionCost computePredInstDiscount(Instruction *PredInst,
1738  ScalarCostsTy &ScalarCosts,
1739  ElementCount VF);
1740 
1741  /// Collect the instructions that are uniform after vectorization. An
1742  /// instruction is uniform if we represent it with a single scalar value in
1743  /// the vectorized loop corresponding to each vector iteration. Examples of
1744  /// uniform instructions include pointer operands of consecutive or
1745  /// interleaved memory accesses. Note that although uniformity implies an
1746  /// instruction will be scalar, the reverse is not true. In general, a
1747  /// scalarized instruction will be represented by VF scalar values in the
1748  /// vectorized loop, each corresponding to an iteration of the original
1749  /// scalar loop.
1750  void collectLoopUniforms(ElementCount VF);
1751 
1752  /// Collect the instructions that are scalar after vectorization. An
1753  /// instruction is scalar if it is known to be uniform or will be scalarized
1754  /// during vectorization. collectLoopScalars should only add non-uniform nodes
1755  /// to the list if they are used by a load/store instruction that is marked as
1756  /// CM_Scalarize. Non-uniform scalarized instructions will be represented by
1757  /// VF values in the vectorized loop, each corresponding to an iteration of
1758  /// the original scalar loop.
1759  void collectLoopScalars(ElementCount VF);
1760 
1761  /// Keeps cost model vectorization decision and cost for instructions.
1762  /// Right now it is used for memory instructions only.
1764  std::pair<InstWidening, InstructionCost>>;
1765 
1766  DecisionList WideningDecisions;
1767 
1768  /// Returns true if \p V is expected to be vectorized and it needs to be
1769  /// extracted.
1770  bool needsExtract(Value *V, ElementCount VF) const {
1771  Instruction *I = dyn_cast<Instruction>(V);
1772  if (VF.isScalar() || !I || !TheLoop->contains(I) ||
1773  TheLoop->isLoopInvariant(I))
1774  return false;
1775 
1776  // Assume we can vectorize V (and hence we need extraction) if the
1777  // scalars are not computed yet. This can happen, because it is called
1778  // via getScalarizationOverhead from setCostBasedWideningDecision, before
1779  // the scalars are collected. That should be a safe assumption in most
1780  // cases, because we check if the operands have vectorizable types
1781  // beforehand in LoopVectorizationLegality.
1782  return Scalars.find(VF) == Scalars.end() ||
1783  !isScalarAfterVectorization(I, VF);
1784  };
1785 
1786  /// Returns a range containing only operands needing to be extracted.
1787  SmallVector<Value *, 4> filterExtractingOperands(Instruction::op_range Ops,
1788  ElementCount VF) const {
1790  Ops, [this, VF](Value *V) { return this->needsExtract(V, VF); }));
1791  }
1792 
1793  /// Determines if we have the infrastructure to vectorize loop \p L and its
1794  /// epilogue, assuming the main loop is vectorized by \p VF.
1795  bool isCandidateForEpilogueVectorization(const Loop &L,
1796  const ElementCount VF) const;
1797 
1798  /// Returns true if epilogue vectorization is considered profitable, and
1799  /// false otherwise.
1800  /// \p VF is the vectorization factor chosen for the original loop.
1801  bool isEpilogueVectorizationProfitable(const ElementCount VF) const;
1802 
1803 public:
1804  /// The loop that we evaluate.
1806 
1807  /// Predicated scalar evolution analysis.
1809 
1810  /// Loop Info analysis.
1812 
1813  /// Vectorization legality.
1815 
1816  /// Vector target information.
1818 
1819  /// Target Library Info.
1821 
1822  /// Demanded bits analysis.
1824 
1825  /// Assumption cache.
1827 
1828  /// Interface to emit optimization remarks.
1830 
1832 
1833  /// Loop Vectorize Hint.
1835 
1836  /// The interleave access information contains groups of interleaved accesses
1837  /// with the same stride and close to each other.
1839 
1840  /// Values to ignore in the cost model.
1842 
1843  /// Values to ignore in the cost model when VF > 1.
1845 
1846  /// All element types found in the loop.
1848 
1849  /// Profitable vector factors.
1851 };
1852 } // end namespace llvm
1853 
1854 /// Helper struct to manage generating runtime checks for vectorization.
1855 ///
1856 /// The runtime checks are created up-front in temporary blocks to allow better
1857 /// estimating the cost and un-linked from the existing IR. After deciding to
1858 /// vectorize, the checks are moved back. If deciding not to vectorize, the
1859 /// temporary blocks are completely removed.
1861  /// Basic block which contains the generated SCEV checks, if any.
1862  BasicBlock *SCEVCheckBlock = nullptr;
1863 
1864  /// The value representing the result of the generated SCEV checks. If it is
1865  /// nullptr, either no SCEV checks have been generated or they have been used.
1866  Value *SCEVCheckCond = nullptr;
1867 
1868  /// Basic block which contains the generated memory runtime checks, if any.
1869  BasicBlock *MemCheckBlock = nullptr;
1870 
1871  /// The value representing the result of the generated memory runtime checks.
1872  /// If it is nullptr, either no memory runtime checks have been generated or
1873  /// they have been used.
1874  Value *MemRuntimeCheckCond = nullptr;
1875 
1876  DominatorTree *DT;
1877  LoopInfo *LI;
1879 
1880  SCEVExpander SCEVExp;
1881  SCEVExpander MemCheckExp;
1882 
1883  bool CostTooHigh = false;
1884 
1885 public:
1888  : DT(DT), LI(LI), TTI(TTI), SCEVExp(SE, DL, "scev.check"),
1889  MemCheckExp(SE, DL, "scev.check") {}
1890 
1891  /// Generate runtime checks in SCEVCheckBlock and MemCheckBlock, so we can
1892  /// accurately estimate the cost of the runtime checks. The blocks are
1893  /// un-linked from the IR and is added back during vector code generation. If
1894  /// there is no vector code generation, the check blocks are removed
1895  /// completely.
1896  void Create(Loop *L, const LoopAccessInfo &LAI,
1897  const SCEVPredicate &UnionPred, ElementCount VF, unsigned IC) {
1898 
1899  // Hard cutoff to limit compile-time increase in case a very large number of
1900  // runtime checks needs to be generated.
1901  // TODO: Skip cutoff if the loop is guaranteed to execute, e.g. due to
1902  // profile info.
1903  CostTooHigh =
1905  if (CostTooHigh)
1906  return;
1907 
1908  BasicBlock *LoopHeader = L->getHeader();
1909  BasicBlock *Preheader = L->getLoopPreheader();
1910 
1911  // Use SplitBlock to create blocks for SCEV & memory runtime checks to
1912  // ensure the blocks are properly added to LoopInfo & DominatorTree. Those
1913  // may be used by SCEVExpander. The blocks will be un-linked from their
1914  // predecessors and removed from LI & DT at the end of the function.
1915  if (!UnionPred.isAlwaysTrue()) {
1916  SCEVCheckBlock = SplitBlock(Preheader, Preheader->getTerminator(), DT, LI,
1917  nullptr, "vector.scevcheck");
1918 
1919  SCEVCheckCond = SCEVExp.expandCodeForPredicate(
1920  &UnionPred, SCEVCheckBlock->getTerminator());
1921  }
1922 
1923  const auto &RtPtrChecking = *LAI.getRuntimePointerChecking();
1924  if (RtPtrChecking.Need) {
1925  auto *Pred = SCEVCheckBlock ? SCEVCheckBlock : Preheader;
1926  MemCheckBlock = SplitBlock(Pred, Pred->getTerminator(), DT, LI, nullptr,
1927  "vector.memcheck");
1928 
1929  auto DiffChecks = RtPtrChecking.getDiffChecks();
1930  if (DiffChecks) {
1931  Value *RuntimeVF = nullptr;
1932  MemRuntimeCheckCond = addDiffRuntimeChecks(
1933  MemCheckBlock->getTerminator(), *DiffChecks, MemCheckExp,
1934  [VF, &RuntimeVF](IRBuilderBase &B, unsigned Bits) {
1935  if (!RuntimeVF)
1936  RuntimeVF = getRuntimeVF(B, B.getIntNTy(Bits), VF);
1937  return RuntimeVF;
1938  },
1939  IC);
1940  } else {
1941  MemRuntimeCheckCond =
1942  addRuntimeChecks(MemCheckBlock->getTerminator(), L,
1943  RtPtrChecking.getChecks(), MemCheckExp);
1944  }
1945  assert(MemRuntimeCheckCond &&
1946  "no RT checks generated although RtPtrChecking "
1947  "claimed checks are required");
1948  }
1949 
1950  if (!MemCheckBlock && !SCEVCheckBlock)
1951  return;
1952 
1953  // Unhook the temporary block with the checks, update various places
1954  // accordingly.
1955  if (SCEVCheckBlock)
1956  SCEVCheckBlock->replaceAllUsesWith(Preheader);
1957  if (MemCheckBlock)
1958  MemCheckBlock->replaceAllUsesWith(Preheader);
1959 
1960  if (SCEVCheckBlock) {
1961  SCEVCheckBlock->getTerminator()->moveBefore(Preheader->getTerminator());
1962  new UnreachableInst(Preheader->getContext(), SCEVCheckBlock);
1963  Preheader->getTerminator()->eraseFromParent();
1964  }
1965  if (MemCheckBlock) {
1966  MemCheckBlock->getTerminator()->moveBefore(Preheader->getTerminator());
1967  new UnreachableInst(Preheader->getContext(), MemCheckBlock);
1968  Preheader->getTerminator()->eraseFromParent();
1969  }
1970 
1971  DT->changeImmediateDominator(LoopHeader, Preheader);
1972  if (MemCheckBlock) {
1973  DT->eraseNode(MemCheckBlock);
1974  LI->removeBlock(MemCheckBlock);
1975  }
1976  if (SCEVCheckBlock) {
1977  DT->eraseNode(SCEVCheckBlock);
1978  LI->removeBlock(SCEVCheckBlock);
1979  }
1980  }
1981 
1983  if (SCEVCheckBlock || MemCheckBlock)
1984  LLVM_DEBUG(dbgs() << "Calculating cost of runtime checks:\n");
1985 
1986  if (CostTooHigh) {
1988  Cost.setInvalid();
1989  LLVM_DEBUG(dbgs() << " number of checks exceeded threshold\n");
1990  return Cost;
1991  }
1992 
1993  InstructionCost RTCheckCost = 0;
1994  if (SCEVCheckBlock)
1995  for (Instruction &I : *SCEVCheckBlock) {
1996  if (SCEVCheckBlock->getTerminator() == &I)
1997  continue;
1998  InstructionCost C =
2000  LLVM_DEBUG(dbgs() << " " << C << " for " << I << "\n");
2001  RTCheckCost += C;
2002  }
2003  if (MemCheckBlock)
2004  for (Instruction &I : *MemCheckBlock) {
2005  if (MemCheckBlock->getTerminator() == &I)
2006  continue;
2007  InstructionCost C =
2009  LLVM_DEBUG(dbgs() << " " << C << " for " << I << "\n");
2010  RTCheckCost += C;
2011  }
2012 
2013  if (SCEVCheckBlock || MemCheckBlock)
2014  LLVM_DEBUG(dbgs() << "Total cost of runtime checks: " << RTCheckCost
2015  << "\n");
2016 
2017  return RTCheckCost;
2018  }
2019 
2020  /// Remove the created SCEV & memory runtime check blocks & instructions, if
2021  /// unused.
2023  SCEVExpanderCleaner SCEVCleaner(SCEVExp);
2024  SCEVExpanderCleaner MemCheckCleaner(MemCheckExp);
2025  if (!SCEVCheckCond)
2026  SCEVCleaner.markResultUsed();
2027 
2028  if (!MemRuntimeCheckCond)
2029  MemCheckCleaner.markResultUsed();
2030 
2031  if (MemRuntimeCheckCond) {
2032  auto &SE = *MemCheckExp.getSE();
2033  // Memory runtime check generation creates compares that use expanded
2034  // values. Remove them before running the SCEVExpanderCleaners.
2035  for (auto &I : make_early_inc_range(reverse(*MemCheckBlock))) {
2036  if (MemCheckExp.isInsertedInstruction(&I))
2037  continue;
2038  SE.forgetValue(&I);
2039  I.eraseFromParent();
2040  }
2041  }
2042  MemCheckCleaner.cleanup();
2043  SCEVCleaner.cleanup();
2044 
2045  if (SCEVCheckCond)
2046  SCEVCheckBlock->eraseFromParent();
2047  if (MemRuntimeCheckCond)
2048  MemCheckBlock->eraseFromParent();
2049  }
2050 
2051  /// Adds the generated SCEVCheckBlock before \p LoopVectorPreHeader and
2052  /// adjusts the branches to branch to the vector preheader or \p Bypass,
2053  /// depending on the generated condition.
2057  if (!SCEVCheckCond)
2058  return nullptr;
2059 
2060  Value *Cond = SCEVCheckCond;
2061  // Mark the check as used, to prevent it from being removed during cleanup.
2062  SCEVCheckCond = nullptr;
2063  if (auto *C = dyn_cast<ConstantInt>(Cond))
2064  if (C->isZero())
2065  return nullptr;
2066 
2067  auto *Pred = LoopVectorPreHeader->getSinglePredecessor();
2068 
2069  BranchInst::Create(LoopVectorPreHeader, SCEVCheckBlock);
2070  // Create new preheader for vector loop.
2071  if (auto *PL = LI->getLoopFor(LoopVectorPreHeader))
2072  PL->addBasicBlockToLoop(SCEVCheckBlock, *LI);
2073 
2074  SCEVCheckBlock->getTerminator()->eraseFromParent();
2075  SCEVCheckBlock->moveBefore(LoopVectorPreHeader);
2076  Pred->getTerminator()->replaceSuccessorWith(LoopVectorPreHeader,
2077  SCEVCheckBlock);
2078 
2079  DT->addNewBlock(SCEVCheckBlock, Pred);
2081 
2082  ReplaceInstWithInst(SCEVCheckBlock->getTerminator(),
2084  return SCEVCheckBlock;
2085  }
2086 
2087  /// Adds the generated MemCheckBlock before \p LoopVectorPreHeader and adjusts
2088  /// the branches to branch to the vector preheader or \p Bypass, depending on
2089  /// the generated condition.
2092  // Check if we generated code that checks in runtime if arrays overlap.
2093  if (!MemRuntimeCheckCond)
2094  return nullptr;
2095 
2096  auto *Pred = LoopVectorPreHeader->getSinglePredecessor();
2098  MemCheckBlock);
2099 
2100  DT->addNewBlock(MemCheckBlock, Pred);
2102  MemCheckBlock->moveBefore(LoopVectorPreHeader);
2103 
2104  if (auto *PL = LI->getLoopFor(LoopVectorPreHeader))
2105  PL->addBasicBlockToLoop(MemCheckBlock, *LI);
2106 
2108  MemCheckBlock->getTerminator(),
2109  BranchInst::Create(Bypass, LoopVectorPreHeader, MemRuntimeCheckCond));
2110  MemCheckBlock->getTerminator()->setDebugLoc(
2111  Pred->getTerminator()->getDebugLoc());
2112 
2113  // Mark the check as used, to prevent it from being removed during cleanup.
2114  MemRuntimeCheckCond = nullptr;
2115  return MemCheckBlock;
2116  }
2117 };
2118 
2119 // Return true if \p OuterLp is an outer loop annotated with hints for explicit
2120 // vectorization. The loop needs to be annotated with #pragma omp simd
2121 // simdlen(#) or #pragma clang vectorize(enable) vectorize_width(#). If the
2122 // vector length information is not provided, vectorization is not considered
2123 // explicit. Interleave hints are not allowed either. These limitations will be
2124 // relaxed in the future.
2125 // Please, note that we are currently forced to abuse the pragma 'clang
2126 // vectorize' semantics. This pragma provides *auto-vectorization hints*
2127 // (i.e., LV must check that vectorization is legal) whereas pragma 'omp simd'
2128 // provides *explicit vectorization hints* (LV can bypass legal checks and
2129 // assume that vectorization is legal). However, both hints are implemented
2130 // using the same metadata (llvm.loop.vectorize, processed by
2131 // LoopVectorizeHints). This will be fixed in the future when the native IR
2132 // representation for pragma 'omp simd' is introduced.
2133 static bool isExplicitVecOuterLoop(Loop *OuterLp,
2135  assert(!OuterLp->isInnermost() && "This is not an outer loop");
2136  LoopVectorizeHints Hints(OuterLp, true /*DisableInterleaving*/, *ORE);
2137 
2138  // Only outer loops with an explicit vectorization hint are supported.
2139  // Unannotated outer loops are ignored.
2141  return false;
2142 
2143  Function *Fn = OuterLp->getHeader()->getParent();
2144  if (!Hints.allowVectorization(Fn, OuterLp,
2145  true /*VectorizeOnlyWhenForced*/)) {
2146  LLVM_DEBUG(dbgs() << "LV: Loop hints prevent outer loop vectorization.\n");
2147  return false;
2148  }
2149 
2150  if (Hints.getInterleave() > 1) {
2151  // TODO: Interleave support is future work.
2152  LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Interleave is not supported for "
2153  "outer loops.\n");
2154  Hints.emitRemarkWithHints();
2155  return false;
2156  }
2157 
2158  return true;
2159 }
2160 
2164  // Collect inner loops and outer loops without irreducible control flow. For
2165  // now, only collect outer loops that have explicit vectorization hints. If we
2166  // are stress testing the VPlan H-CFG construction, we collect the outermost
2167  // loop of every loop nest.
2168  if (L.isInnermost() || VPlanBuildStressTest ||
2170  LoopBlocksRPO RPOT(&L);
2171  RPOT.perform(LI);
2172  if (!containsIrreducibleCFG<const BasicBlock *>(RPOT, *LI)) {
2173  V.push_back(&L);
2174  // TODO: Collect inner loops inside marked outer loops in case
2175  // vectorization fails for the outer loop. Do not invoke
2176  // 'containsIrreducibleCFG' again for inner loops when the outer loop is
2177  // already known to be reducible. We can use an inherited attribute for
2178  // that.
2179  return;
2180  }
2181  }
2182  for (Loop *InnerL : L)
2183  collectSupportedLoops(*InnerL, LI, ORE, V);
2184 }
2185 
2186 namespace {
2187 
2188 /// The LoopVectorize Pass.
2189 struct LoopVectorize : public FunctionPass {
2190  /// Pass identification, replacement for typeid
2191  static char ID;
2192 
2193  LoopVectorizePass Impl;
2194 
2195  explicit LoopVectorize(bool InterleaveOnlyWhenForced = false,
2196  bool VectorizeOnlyWhenForced = false)
2197  : FunctionPass(ID),
2198  Impl({InterleaveOnlyWhenForced, VectorizeOnlyWhenForced}) {
2200  }
2201 
2202  bool runOnFunction(Function &F) override {
2203  if (skipFunction(F))
2204  return false;
2205 
2206  auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
2207  auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2208  auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
2209  auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2210  auto *BFI = &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI();
2211  auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
2212  auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
2213  auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
2214  auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
2215  auto *LAA = &getAnalysis<LoopAccessLegacyAnalysis>();
2216  auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
2217  auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
2218  auto *PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
2219 
2220  std::function<const LoopAccessInfo &(Loop &)> GetLAA =
2221  [&](Loop &L) -> const LoopAccessInfo & { return LAA->getInfo(&L); };
2222 
2223  return Impl.runImpl(F, *SE, *LI, *TTI, *DT, *BFI, TLI, *DB, *AA, *AC,
2224  GetLAA, *ORE, PSI).MadeAnyChange;
2225  }
2226 
2227  void getAnalysisUsage(AnalysisUsage &AU) const override {
2239 
2240  // We currently do not preserve loopinfo/dominator analyses with outer loop
2241  // vectorization. Until this is addressed, mark these analyses as preserved
2242  // only for non-VPlan-native path.
2243  // TODO: Preserve Loop and Dominator analyses for VPlan-native path.
2244  if (!EnableVPlanNativePath) {
2247  }
2248 
2252  }
2253 };
2254 
2255 } // end anonymous namespace
2256 
2257 //===----------------------------------------------------------------------===//
2258 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
2259 // LoopVectorizationCostModel and LoopVectorizationPlanner.
2260 //===----------------------------------------------------------------------===//
2261 
2263  // We need to place the broadcast of invariant variables outside the loop,
2264  // but only if it's proven safe to do so. Else, broadcast will be inside
2265  // vector loop body.
2266  Instruction *Instr = dyn_cast<Instruction>(V);
2267  bool SafeToHoist = OrigLoop->isLoopInvariant(V) &&
2268  (!Instr ||
2270  // Place the code for broadcasting invariant variables in the new preheader.
2272  if (SafeToHoist)
2274 
2275  // Broadcast the scalar into all locations in the vector.
2276  Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
2277 
2278  return Shuf;
2279 }
2280 
2281 /// This function adds
2282 /// (StartIdx * Step, (StartIdx + 1) * Step, (StartIdx + 2) * Step, ...)
2283 /// to each vector element of Val. The sequence starts at StartIndex.
2284 /// \p Opcode is relevant for FP induction variable.
2285 static Value *getStepVector(Value *Val, Value *StartIdx, Value *Step,
2288  assert(VF.isVector() && "only vector VFs are supported");
2289 
2290  // Create and check the types.
2291  auto *ValVTy = cast<VectorType>(Val->getType());
2292  ElementCount VLen = ValVTy->getElementCount();
2293 
2294  Type *STy = Val->getType()->getScalarType();
2295  assert((STy->isIntegerTy() || STy->isFloatingPointTy()) &&
2296  "Induction Step must be an integer or FP");
2297  assert(Step->getType() == STy && "Step has wrong type");
2298 
2300 
2301  // Create a vector of consecutive numbers from zero to VF.
2302  VectorType *InitVecValVTy = ValVTy;
2303  if (STy->isFloatingPointTy()) {
2304  Type *InitVecValSTy =
2306  InitVecValVTy = VectorType::get(InitVecValSTy, VLen);
2307  }
2308  Value *InitVec = Builder.CreateStepVector(InitVecValVTy);
2309 
2310  // Splat the StartIdx
2311  Value *StartIdxSplat = Builder.CreateVectorSplat(VLen, StartIdx);
2312 
2313  if (STy->isIntegerTy()) {
2314  InitVec = Builder.CreateAdd(InitVec, StartIdxSplat);
2315  Step = Builder.CreateVectorSplat(VLen, Step);
2316  assert(Step->getType() == Val->getType() && "Invalid step vec");
2317  // FIXME: The newly created binary instructions should contain nsw/nuw
2318  // flags, which can be found from the original scalar operations.
2319  Step = Builder.CreateMul(InitVec, Step);
2320  return Builder.CreateAdd(Val, Step, "induction");
2321  }
2322 
2323  // Floating point induction.
2324  assert((BinOp == Instruction::FAdd || BinOp == Instruction::FSub) &&
2325  "Binary Opcode should be specified for FP induction");
2326  InitVec = Builder.CreateUIToFP(InitVec, ValVTy);
2327  InitVec = Builder.CreateFAdd(InitVec, StartIdxSplat);
2328 
2329  Step = Builder.CreateVectorSplat(VLen, Step);
2330  Value *MulOp = Builder.CreateFMul(InitVec, Step);
2331  return Builder.CreateBinOp(BinOp, Val, MulOp, "induction");
2332 }
2333 
2334 /// Compute scalar induction steps. \p ScalarIV is the scalar induction
2335 /// variable on which to base the steps, \p Step is the size of the step.
2336 static void buildScalarSteps(Value *ScalarIV, Value *Step,
2337  const InductionDescriptor &ID, VPValue *Def,
2338  VPTransformState &State) {
2339  IRBuilderBase &Builder = State.Builder;
2340  // We shouldn't have to build scalar steps if we aren't vectorizing.
2341  assert(State.VF.isVector() && "VF should be greater than one");
2342  // Get the value type and ensure it and the step have the same integer type.
2343  Type *ScalarIVTy = ScalarIV->getType()->getScalarType();
2344  assert(ScalarIVTy == Step->getType() &&
2345  "Val and Step should have the same type");
2346 
2347  // We build scalar steps for both integer and floating-point induction
2348  // variables. Here, we determine the kind of arithmetic we will perform.
2349  Instruction::BinaryOps AddOp;
2350  Instruction::BinaryOps MulOp;
2351  if (ScalarIVTy->isIntegerTy()) {
2352  AddOp = Instruction::Add;
2353  MulOp = Instruction::Mul;
2354  } else {
2355  AddOp = ID.getInductionOpcode();
2356  MulOp = Instruction::FMul;
2357  }
2358 
2359  // Determine the number of scalars we need to generate for each unroll
2360  // iteration.
2361  bool FirstLaneOnly = vputils::onlyFirstLaneUsed(Def);
2362  unsigned Lanes = FirstLaneOnly ? 1 : State.VF.getKnownMinValue();
2363  // Compute the scalar steps and save the results in State.
2364  Type *IntStepTy = IntegerType::get(ScalarIVTy->getContext(),
2365  ScalarIVTy->getScalarSizeInBits());
2366  Type *VecIVTy = nullptr;
2367  Value *UnitStepVec = nullptr, *SplatStep = nullptr, *SplatIV = nullptr;
2368  if (!FirstLaneOnly && State.VF.isScalable()) {
2369  VecIVTy = VectorType::get(ScalarIVTy, State.VF);
2370  UnitStepVec =
2371  Builder.CreateStepVector(VectorType::get(IntStepTy, State.VF));
2372  SplatStep = Builder.CreateVectorSplat(State.VF, Step);
2373  SplatIV = Builder.CreateVectorSplat(State.VF, ScalarIV);
2374  }
2375 
2376  for (unsigned Part = 0; Part < State.UF; ++Part) {
2377  Value *StartIdx0 = createStepForVF(Builder, IntStepTy, State.VF, Part);
2378 
2379  if (!FirstLaneOnly && State.VF.isScalable()) {
2380  auto *SplatStartIdx = Builder.CreateVectorSplat(State.VF, StartIdx0);
2381  auto *InitVec = Builder.CreateAdd(SplatStartIdx, UnitStepVec);
2382  if (ScalarIVTy->isFloatingPointTy())
2383  InitVec = Builder.CreateSIToFP(InitVec, VecIVTy);
2384  auto *Mul = Builder.CreateBinOp(MulOp, InitVec, SplatStep);
2385  auto *Add = Builder.CreateBinOp(AddOp, SplatIV, Mul);
2386  State.set(Def, Add, Part);
2387  // It's useful to record the lane values too for the known minimum number
2388  // of elements so we do those below. This improves the code quality when
2389  // trying to extract the first element, for example.
2390  }
2391 
2392  if (ScalarIVTy->isFloatingPointTy())
2393  StartIdx0 = Builder.CreateSIToFP(StartIdx0, ScalarIVTy);
2394 
2395  for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
2396  Value *StartIdx = Builder.CreateBinOp(
2397  AddOp, StartIdx0, getSignedIntOrFpConstant(ScalarIVTy, Lane));
2398  // The step returned by `createStepForVF` is a runtime-evaluated value
2399  // when VF is scalable. Otherwise, it should be folded into a Constant.
2400  assert((State.VF.isScalable() || isa<Constant>(StartIdx)) &&
2401  "Expected StartIdx to be folded to a constant when VF is not "
2402  "scalable");
2403  auto *Mul = Builder.CreateBinOp(MulOp, StartIdx, Step);
2404  auto *Add = Builder.CreateBinOp(AddOp, ScalarIV, Mul);
2405  State.set(Def, Add, VPIteration(Part, Lane));
2406  }
2407  }
2408 }
2409 
2410 // Generate code for the induction step. Note that induction steps are
2411 // required to be loop-invariant
2412 static Value *CreateStepValue(const SCEV *Step, ScalarEvolution &SE,
2413  Instruction *InsertBefore,
2414  Loop *OrigLoop = nullptr) {
2415  const DataLayout &DL = SE.getDataLayout();
2416  assert((!OrigLoop || SE.isLoopInvariant(Step, OrigLoop)) &&
2417  "Induction step should be loop invariant");
2418  if (auto *E = dyn_cast<SCEVUnknown>(Step))
2419  return E->getValue();
2420 
2421  SCEVExpander Exp(SE, DL, "induction");
2422  return Exp.expandCodeFor(Step, Step->getType(), InsertBefore);
2423 }
2424 
2425 /// Compute the transformed value of Index at offset StartValue using step
2426 /// StepValue.
2427 /// For integer induction, returns StartValue + Index * StepValue.
2428 /// For pointer induction, returns StartValue[Index * StepValue].
2429 /// FIXME: The newly created binary instructions should contain nsw/nuw
2430 /// flags, which can be found from the original scalar operations.
2432  Value *StartValue, Value *Step,
2433  const InductionDescriptor &ID) {
2434  assert(Index->getType()->getScalarType() == Step->getType() &&
2435  "Index scalar type does not match StepValue type");
2436 
2437  // Note: the IR at this point is broken. We cannot use SE to create any new
2438  // SCEV and then expand it, hoping that SCEV's simplification will give us
2439  // a more optimal code. Unfortunately, attempt of doing so on invalid IR may
2440  // lead to various SCEV crashes. So all we can do is to use builder and rely
2441  // on InstCombine for future simplifications. Here we handle some trivial
2442  // cases only.
2443  auto CreateAdd = [&B](Value *X, Value *Y) {
2444  assert(X->getType() == Y->getType() && "Types don't match!");
2445  if (auto *CX = dyn_cast<ConstantInt>(X))
2446  if (CX->isZero())
2447  return Y;
2448  if (auto *CY = dyn_cast<ConstantInt>(Y))
2449  if (CY->isZero())
2450  return X;
2451  return B.CreateAdd(X, Y);
2452  };
2453 
2454  // We allow X to be a vector type, in which case Y will potentially be
2455  // splatted into a vector with the same element count.
2456  auto CreateMul = [&B](Value *X, Value *Y) {
2457  assert(X->getType()->getScalarType() == Y->getType() &&
2458  "Types don't match!");
2459  if (auto *CX = dyn_cast<ConstantInt>(X))
2460  if (CX->isOne())
2461  return Y;
2462  if (auto *CY = dyn_cast<ConstantInt>(Y))
2463  if (CY->isOne())
2464  return X;
2465  VectorType *XVTy = dyn_cast<VectorType>(X->getType());
2466  if (XVTy && !isa<VectorType>(Y->getType()))
2467  Y = B.CreateVectorSplat(XVTy->getElementCount(), Y);
2468  return B.CreateMul(X, Y);
2469  };
2470 
2471  switch (ID.getKind()) {
2473  assert(!isa<VectorType>(Index->getType()) &&
2474  "Vector indices not supported for integer inductions yet");
2475  assert(Index->getType() == StartValue->getType() &&
2476  "Index type does not match StartValue type");
2477  if (isa<ConstantInt>(Step) && cast<ConstantInt>(Step)->isMinusOne())
2478  return B.CreateSub(StartValue, Index);
2479  auto *Offset = CreateMul(Index, Step);
2480  return CreateAdd(StartValue, Offset);
2481  }
2483  assert(isa<Constant>(Step) &&
2484  "Expected constant step for pointer induction");
2485  return B.CreateGEP(ID.getElementType(), StartValue, CreateMul(Index, Step));
2486  }
2488  assert(!isa<VectorType>(Index->getType()) &&
2489  "Vector indices not supported for FP inductions yet");
2490  assert(Step->getType()->isFloatingPointTy() && "Expected FP Step value");
2491  auto InductionBinOp = ID.getInductionBinOp();
2492  assert(InductionBinOp &&
2493  (InductionBinOp->getOpcode() == Instruction::FAdd ||
2494  InductionBinOp->getOpcode() == Instruction::FSub) &&
2495  "Original bin op should be defined for FP induction");
2496 
2497  Value *MulExp = B.CreateFMul(Step, Index);
2498  return B.CreateBinOp(InductionBinOp->getOpcode(), StartValue, MulExp,
2499  "induction");
2500  }
2502  return nullptr;
2503  }
2504  llvm_unreachable("invalid enum");
2505 }
2506 
2508  const VPIteration &Instance,
2509  VPTransformState &State) {
2510  Value *ScalarInst = State.get(Def, Instance);
2511  Value *VectorValue = State.get(Def, Instance.Part);
2512  VectorValue = Builder.CreateInsertElement(
2513  VectorValue, ScalarInst,
2514  Instance.Lane.getAsRuntimeExpr(State.Builder, VF));
2515  State.set(Def, VectorValue, Instance.Part);
2516 }
2517 
2518 // Return whether we allow using masked interleave-groups (for dealing with
2519 // strided loads/stores that reside in predicated blocks, or for dealing
2520 // with gaps).
2522  // If an override option has been passed in for interleaved accesses, use it.
2525 
2527 }
2528 
2529 // Try to vectorize the interleave group that \p Instr belongs to.
2530 //
2531 // E.g. Translate following interleaved load group (factor = 3):
2532 // for (i = 0; i < N; i+=3) {
2533 // R = Pic[i]; // Member of index 0
2534 // G = Pic[i+1]; // Member of index 1
2535 // B = Pic[i+2]; // Member of index 2
2536 // ... // do something to R, G, B
2537 // }
2538 // To:
2539 // %wide.vec = load <12 x i32> ; Read 4 tuples of R,G,B
2540 // %R.vec = shuffle %wide.vec, poison, <0, 3, 6, 9> ; R elements
2541 // %G.vec = shuffle %wide.vec, poison, <1, 4, 7, 10> ; G elements
2542 // %B.vec = shuffle %wide.vec, poison, <2, 5, 8, 11> ; B elements
2543 //
2544 // Or translate following interleaved store group (factor = 3):
2545 // for (i = 0; i < N; i+=3) {
2546 // ... do something to R, G, B
2547 // Pic[i] = R; // Member of index 0
2548 // Pic[i+1] = G; // Member of index 1
2549 // Pic[i+2] = B; // Member of index 2
2550 // }
2551 // To:
2552 // %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
2553 // %B_U.vec = shuffle %B.vec, poison, <0, 1, 2, 3, u, u, u, u>
2554 // %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
2555 // <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> ; Interleave R,G,B elements
2556 // store <12 x i32> %interleaved.vec ; Write 4 tuples of R,G,B
2559  VPTransformState &State, VPValue *Addr, ArrayRef<VPValue *> StoredValues,
2560  VPValue *BlockInMask) {
2561  Instruction *Instr = Group->getInsertPos();
2562  const DataLayout &DL = Instr->getModule()->getDataLayout();
2563 
2564  // Prepare for the vector type of the interleaved load/store.
2565  Type *ScalarTy = getLoadStoreType(Instr);
2566  unsigned InterleaveFactor = Group->getFactor();
2567  assert(!VF.isScalable() && "scalable vectors not yet supported.");
2568  auto *VecTy = VectorType::get(ScalarTy, VF * InterleaveFactor);
2569 
2570  // Prepare for the new pointers.
2571  SmallVector<Value *, 2> AddrParts;
2572  unsigned Index = Group->getIndex(Instr);
2573 
2574  // TODO: extend the masked interleaved-group support to reversed access.
2575  assert((!BlockInMask || !Group->isReverse()) &&
2576  "Reversed masked interleave-group not supported.");
2577 
2578  // If the group is reverse, adjust the index to refer to the last vector lane
2579  // instead of the first. We adjust the index from the first vector lane,
2580  // rather than directly getting the pointer for lane VF - 1, because the
2581  // pointer operand of the interleaved access is supposed to be uniform. For
2582  // uniform instructions, we're only required to generate a value for the
2583  // first vector lane in each unroll iteration.
2584  if (Group->isReverse())
2585  Index += (VF.getKnownMinValue() - 1) * Group->getFactor();
2586 
2587  for (unsigned Part = 0; Part < UF; Part++) {
2588  Value *AddrPart = State.get(Addr, VPIteration(Part, 0));
2589  State.setDebugLocFromInst(AddrPart);
2590 
2591  // Notice current instruction could be any index. Need to adjust the address
2592  // to the member of index 0.
2593  //
2594  // E.g. a = A[i+1]; // Member of index 1 (Current instruction)
2595  // b = A[i]; // Member of index 0
2596  // Current pointer is pointed to A[i+1], adjust it to A[i].
2597  //
2598  // E.g. A[i+1] = a; // Member of index 1
2599  // A[i] = b; // Member of index 0
2600  // A[i+2] = c; // Member of index 2 (Current instruction)
2601  // Current pointer is pointed to A[i+2], adjust it to A[i].
2602 
2603  bool InBounds = false;
2604  if (auto *gep = dyn_cast<GetElementPtrInst>(AddrPart->stripPointerCasts()))
2605  InBounds = gep->isInBounds();
2606  AddrPart = Builder.CreateGEP(ScalarTy, AddrPart, Builder.getInt32(-Index));
2607  cast<GetElementPtrInst>(AddrPart)->setIsInBounds(InBounds);
2608 
2609  // Cast to the vector pointer type.
2610  unsigned AddressSpace = AddrPart->getType()->getPointerAddressSpace();
2611  Type *PtrTy = VecTy->getPointerTo(AddressSpace);
2612  AddrParts.push_back(Builder.CreateBitCast(AddrPart, PtrTy));
2613  }
2614 
2615  State.setDebugLocFromInst(Instr);
2616  Value *PoisonVec = PoisonValue::get(VecTy);
2617 
2618  Value *MaskForGaps = nullptr;
2619  if (Group->requiresScalarEpilogue() && !Cost->isScalarEpilogueAllowed()) {
2620  MaskForGaps = createBitMaskForGaps(Builder, VF.getKnownMinValue(), *Group);
2621  assert(MaskForGaps && "Mask for Gaps is required but it is null");
2622  }
2623 
2624  // Vectorize the interleaved load group.
2625  if (isa<LoadInst>(Instr)) {
2626  // For each unroll part, create a wide load for the group.
2627  SmallVector<Value *, 2> NewLoads;
2628  for (unsigned Part = 0; Part < UF; Part++) {
2629  Instruction *NewLoad;
2630  if (BlockInMask || MaskForGaps) {
2632  "masked interleaved groups are not allowed.");
2633  Value *GroupMask = MaskForGaps;
2634  if (BlockInMask) {
2635  Value *BlockInMaskPart = State.get(BlockInMask, Part);
2636  Value *ShuffledMask = Builder.CreateShuffleVector(
2637  BlockInMaskPart,
2638  createReplicatedMask(InterleaveFactor, VF.getKnownMinValue()),
2639  "interleaved.mask");
2640  GroupMask = MaskForGaps
2641  ? Builder.CreateBinOp(Instruction::And, ShuffledMask,
2642  MaskForGaps)
2643  : ShuffledMask;
2644  }
2645  NewLoad =
2646  Builder.CreateMaskedLoad(VecTy, AddrParts[Part], Group->getAlign(),
2647  GroupMask, PoisonVec, "wide.masked.vec");
2648  }
2649  else
2650  NewLoad = Builder.CreateAlignedLoad(VecTy, AddrParts[Part],
2651  Group->getAlign(), "wide.vec");
2652  Group->addMetadata(NewLoad);
2653  NewLoads.push_back(NewLoad);
2654  }
2655 
2656  // For each member in the group, shuffle out the appropriate data from the
2657  // wide loads.
2658  unsigned J = 0;
2659  for (unsigned I = 0; I < InterleaveFactor; ++I) {
2660  Instruction *Member = Group->getMember(I);
2661 
2662  // Skip the gaps in the group.
2663  if (!Member)
2664  continue;
2665 
2666  auto StrideMask =
2667  createStrideMask(I, InterleaveFactor, VF.getKnownMinValue());
2668  for (unsigned Part = 0; Part < UF; Part++) {
2669  Value *StridedVec = Builder.CreateShuffleVector(
2670  NewLoads[Part], StrideMask, "strided.vec");
2671 
2672  // If this member has different type, cast the result type.
2673  if (Member->getType() != ScalarTy) {
2674  assert(!VF.isScalable() && "VF is assumed to be non scalable.");
2675  VectorType *OtherVTy = VectorType::get(Member->getType(), VF);
2676  StridedVec = createBitOrPointerCast(StridedVec, OtherVTy, DL);
2677  }
2678 
2679  if (Group->isReverse())
2680  StridedVec = Builder.CreateVectorReverse(StridedVec, "reverse");
2681 
2682  State.set(VPDefs[J], StridedVec, Part);
2683  }
2684  ++J;
2685  }
2686  return;
2687  }
2688 
2689  // The sub vector type for current instruction.
2690  auto *SubVT = VectorType::get(ScalarTy, VF);
2691 
2692  // Vectorize the interleaved store group.
2693  MaskForGaps = createBitMaskForGaps(Builder, VF.getKnownMinValue(), *Group);
2694  assert((!MaskForGaps || useMaskedInterleavedAccesses(*TTI)) &&
2695  "masked interleaved groups are not allowed.");
2696  assert((!MaskForGaps || !VF.isScalable()) &&
2697  "masking gaps for scalable vectors is not yet supported.");
2698  for (unsigned Part = 0; Part < UF; Part++) {
2699  // Collect the stored vector from each member.
2700  SmallVector<Value *, 4> StoredVecs;
2701  for (unsigned i = 0; i < InterleaveFactor; i++) {
2702  assert((Group->getMember(i) || MaskForGaps) &&
2703  "Fail to get a member from an interleaved store group");
2704  Instruction *Member = Group->getMember(i);
2705 
2706  // Skip the gaps in the group.
2707  if (!Member) {
2708  Value *Undef = PoisonValue::get(SubVT);
2709  StoredVecs.push_back(Undef);
2710  continue;
2711  }
2712 
2713  Value *StoredVec = State.get(StoredValues[i], Part);
2714 
2715  if (Group->isReverse())
2716  StoredVec = Builder.CreateVectorReverse(StoredVec, "reverse");
2717 
2718  // If this member has different type, cast it to a unified type.
2719 
2720  if (StoredVec->getType() != SubVT)
2721  StoredVec = createBitOrPointerCast(StoredVec, SubVT, DL);
2722 
2723  StoredVecs.push_back(StoredVec);
2724  }
2725 
2726  // Concatenate all vectors into a wide vector.
2727  Value *WideVec = concatenateVectors(Builder, StoredVecs);
2728 
2729  // Interleave the elements in the wide vector.
2731  WideVec, createInterleaveMask(VF.getKnownMinValue(), InterleaveFactor),
2732  "interleaved.vec");
2733 
2734  Instruction *NewStoreInstr;
2735  if (BlockInMask || MaskForGaps) {
2736  Value *GroupMask = MaskForGaps;
2737  if (BlockInMask) {
2738  Value *BlockInMaskPart = State.get(BlockInMask, Part);
2739  Value *ShuffledMask = Builder.CreateShuffleVector(
2740  BlockInMaskPart,
2741  createReplicatedMask(InterleaveFactor, VF.getKnownMinValue()),
2742  "interleaved.mask");
2743  GroupMask = MaskForGaps ? Builder.CreateBinOp(Instruction::And,
2744  ShuffledMask, MaskForGaps)
2745  : ShuffledMask;
2746  }
2747  NewStoreInstr = Builder.CreateMaskedStore(IVec, AddrParts[Part],
2748  Group->getAlign(), GroupMask);
2749  } else
2750  NewStoreInstr =
2751  Builder.CreateAlignedStore(IVec, AddrParts[Part], Group->getAlign());
2752 
2753  Group->addMetadata(NewStoreInstr);
2754  }
2755 }
2756 
2758  VPReplicateRecipe *RepRecipe,
2759  const VPIteration &Instance,
2760  bool IfPredicateInstr,
2761  VPTransformState &State) {
2762  assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
2763 
2764  // llvm.experimental.noalias.scope.decl intrinsics must only be duplicated for
2765  // the first lane and part.
2766  if (isa<NoAliasScopeDeclInst>(Instr))
2767  if (!Instance.isFirstIteration())
2768  return;
2769 
2770  // Does this instruction return a value ?
2771  bool IsVoidRetTy = Instr->getType()->isVoidTy();
2772 
2773  Instruction *Cloned = Instr->clone();
2774  if (!IsVoidRetTy)
2775  Cloned->setName(Instr->getName() + ".cloned");
2776 
2777  // If the scalarized instruction contributes to the address computation of a
2778  // widen masked load/store which was in a basic block that needed predication
2779  // and is not predicated after vectorization, we can't propagate
2780  // poison-generating flags (nuw/nsw, exact, inbounds, etc.). The scalarized
2781  // instruction could feed a poison value to the base address of the widen
2782  // load/store.
2783  if (State.MayGeneratePoisonRecipes.contains(RepRecipe))
2784  Cloned->dropPoisonGeneratingFlags();
2785 
2786  if (Instr->getDebugLoc())
2787  State.setDebugLocFromInst(Instr);
2788 
2789  // Replace the operands of the cloned instructions with their scalar
2790  // equivalents in the new loop.
2791  for (const auto &I : enumerate(RepRecipe->operands())) {
2792  auto InputInstance = Instance;
2793  VPValue *Operand = I.value();
2795  InputInstance.Lane = VPLane::getFirstLane();
2796  Cloned->setOperand(I.index(), State.get(Operand, InputInstance));
2797  }
2798  State.addNewMetadata(Cloned, Instr);
2799 
2800  // Place the cloned scalar in the new loop.
2801  State.Builder.Insert(Cloned);
2802 
2803  State.set(RepRecipe, Cloned, Instance);
2804 
2805  // If we just cloned a new assumption, add it the assumption cache.
2806  if (auto *II = dyn_cast<AssumeInst>(Cloned))
2807  AC->registerAssumption(II);
2808 
2809  // End if-block.
2810  if (IfPredicateInstr)
2811  PredicatedInstructions.push_back(Cloned);
2812 }
2813 
2815  if (TripCount)
2816  return TripCount;
2817 
2818  assert(InsertBlock);
2819  IRBuilder<> Builder(InsertBlock->getTerminator());
2820  // Find the loop boundaries.
2821  ScalarEvolution *SE = PSE.getSE();
2822  const SCEV *BackedgeTakenCount = PSE.getBackedgeTakenCount();
2823  assert(!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
2824  "Invalid loop count");
2825 
2826  Type *IdxTy = Legal->getWidestInductionType();
2827  assert(IdxTy && "No type for induction");
2828 
2829  // The exit count might have the type of i64 while the phi is i32. This can
2830  // happen if we have an induction variable that is sign extended before the
2831  // compare. The only way that we get a backedge taken count is that the
2832  // induction variable was signed and as such will not overflow. In such a case
2833  // truncation is legal.
2834  if (SE->getTypeSizeInBits(BackedgeTakenCount->getType()) >
2835  IdxTy->getPrimitiveSizeInBits())
2836  BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount, IdxTy);
2837  BackedgeTakenCount = SE->getNoopOrZeroExtend(BackedgeTakenCount, IdxTy);
2838 
2839  // Get the total trip count from the count by adding 1.
2840  const SCEV *ExitCount = SE->getAddExpr(
2841  BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType()));
2842 
2843  const DataLayout &DL = InsertBlock->getModule()->getDataLayout();
2844 
2845  // Expand the trip count and place the new instructions in the preheader.
2846  // Notice that the pre-header does not change, only the loop body.
2847  SCEVExpander Exp(*SE, DL, "induction");
2848 
2849  // Count holds the overall loop count (N).
2850  TripCount = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
2851  InsertBlock->getTerminator());
2852 
2853  if (TripCount->getType()->isPointerTy())
2854  TripCount =
2855  CastInst::CreatePointerCast(TripCount, IdxTy, "exitcount.ptrcnt.to.int",
2856  InsertBlock->getTerminator());
2857 
2858  return TripCount;
2859 }
2860 
2861 Value *
2863  if (VectorTripCount)
2864  return VectorTripCount;
2865 
2866  Value *TC = getOrCreateTripCount(InsertBlock);
2867  IRBuilder<> Builder(InsertBlock->getTerminator());
2868 
2869  Type *Ty = TC->getType();
2870  // This is where we can make the step a runtime constant.
2871  Value *Step = createStepForVF(Builder, Ty, VF, UF);
2872 
2873  // If the tail is to be folded by masking, round the number of iterations N
2874  // up to a multiple of Step instead of rounding down. This is done by first
2875  // adding Step-1 and then rounding down. Note that it's ok if this addition
2876  // overflows: the vector induction variable will eventually wrap to zero given
2877  // that it starts at zero and its Step is a power of two; the loop will then
2878  // exit, with the last early-exit vector comparison also producing all-true.
2879  // For scalable vectors the VF is not guaranteed to be a power of 2, but this
2880  // is accounted for in emitIterationCountCheck that adds an overflow check.
2881  if (Cost->foldTailByMasking()) {
2883  "VF*UF must be a power of 2 when folding tail by masking");
2884  Value *NumLanes = getRuntimeVF(Builder, Ty, VF * UF);
2885  TC = Builder.CreateAdd(
2886  TC, Builder.CreateSub(NumLanes, ConstantInt::get(Ty, 1)), "n.rnd.up");
2887  }
2888 
2889  // Now we need to generate the expression for the part of the loop that the
2890  // vectorized body will execute. This is equal to N - (N % Step) if scalar
2891  // iterations are not required for correctness, or N - Step, otherwise. Step
2892  // is equal to the vectorization factor (number of SIMD elements) times the
2893  // unroll factor (number of SIMD instructions).
2894  Value *R = Builder.CreateURem(TC, Step, "n.mod.vf");
2895 
2896  // There are cases where we *must* run at least one iteration in the remainder
2897  // loop. See the cost model for when this can happen. If the step evenly
2898  // divides the trip count, we set the remainder to be equal to the step. If
2899  // the step does not evenly divide the trip count, no adjustment is necessary
2900  // since there will already be scalar iterations. Note that the minimum
2901  // iterations check ensures that N >= Step.
2902  if (Cost->requiresScalarEpilogue(VF)) {
2903  auto *IsZero = Builder.CreateICmpEQ(R, ConstantInt::get(R->getType(), 0));
2904  R = Builder.CreateSelect(IsZero, Step, R);
2905  }
2906 
2907  VectorTripCount = Builder.CreateSub(TC, R, "n.vec");
2908 
2909  return VectorTripCount;
2910 }
2911 
2913  const DataLayout &DL) {
2914  // Verify that V is a vector type with same number of elements as DstVTy.
2915  auto *DstFVTy = cast<FixedVectorType>(DstVTy);
2916  unsigned VF = DstFVTy->getNumElements();
2917  auto *SrcVecTy = cast<FixedVectorType>(V->getType());
2918  assert((VF == SrcVecTy->getNumElements()) && "Vector dimensions do not match");
2919  Type *SrcElemTy = SrcVecTy->getElementType();
2920  Type *DstElemTy = DstFVTy->getElementType();
2921  assert((DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy)) &&
2922  "Vector elements must have same size");
2923 
2924  // Do a direct cast if element types are castable.
2925  if (CastInst::isBitOrNoopPointerCastable(SrcElemTy, DstElemTy, DL)) {
2926  return Builder.CreateBitOrPointerCast(V, DstFVTy);
2927  }
2928  // V cannot be directly casted to desired vector type.
2929  // May happen when V is a floating point vector but DstVTy is a vector of
2930  // pointers or vice-versa. Handle this using a two-step bitcast using an
2931  // intermediate Integer type for the bitcast i.e. Ptr <-> Int <-> Float.
2932  assert((DstElemTy->isPointerTy() != SrcElemTy->isPointerTy()) &&
2933  "Only one type should be a pointer type");
2934  assert((DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy()) &&
2935  "Only one type should be a floating point type");
2936  Type *IntTy =
2937  IntegerType::getIntNTy(V->getContext(), DL.getTypeSizeInBits(SrcElemTy));
2938  auto *VecIntTy = FixedVectorType::get(IntTy, VF);
2939  Value *CastVal = Builder.CreateBitOrPointerCast(V, VecIntTy);
2940  return Builder.CreateBitOrPointerCast(CastVal, DstFVTy);
2941 }
2942 
2945  // Reuse existing vector loop preheader for TC checks.
2946  // Note that new preheader block is generated for vector loop.
2947  BasicBlock *const TCCheckBlock = LoopVectorPreHeader;
2948  IRBuilder<> Builder(TCCheckBlock->getTerminator());
2949 
2950  // Generate code to check if the loop's trip count is less than VF * UF, or
2951  // equal to it in case a scalar epilogue is required; this implies that the
2952  // vector trip count is zero. This check also covers the case where adding one
2953  // to the backedge-taken count overflowed leading to an incorrect trip count
2954  // of zero. In this case we will also jump to the scalar loop.
2957 
2958  // If tail is to be folded, vector loop takes care of all iterations.
2959  Type *CountTy = Count->getType();
2960  Value *CheckMinIters = Builder.getFalse();
2961  auto CreateStep = [&]() -> Value * {
2962  // Create step with max(MinProTripCount, UF * VF).
2964  return createStepForVF(Builder, CountTy, VF, UF);
2965 
2966  Value *MinProfTC =
2968  if (!VF.isScalable())
2969  return MinProfTC;
2971  Intrinsic::umax, MinProfTC, createStepForVF(Builder, CountTy, VF, UF));
2972  };
2973 
2974  if (!Cost->foldTailByMasking())
2975  CheckMinIters =
2976  Builder.CreateICmp(P, Count, CreateStep(), "min.iters.check");
2977  else if (VF.isScalable()) {
2978  // vscale is not necessarily a power-of-2, which means we cannot guarantee
2979  // an overflow to zero when updating induction variables and so an
2980  // additional overflow check is required before entering the vector loop.
2981 
2982  // Get the maximum unsigned value for the type.
2983  Value *MaxUIntTripCount =
2984  ConstantInt::get(CountTy, cast<IntegerType>(CountTy)->getMask());
2985  Value *LHS = Builder.CreateSub(MaxUIntTripCount, Count);
2986 
2987  // Don't execute the vector loop if (UMax - n) < (VF * UF).
2988  CheckMinIters = Builder.CreateICmp(ICmpInst::ICMP_ULT, LHS, CreateStep());
2989  }
2990 
2991  // Create new preheader for vector loop.
2993  SplitBlock(TCCheckBlock, TCCheckBlock->getTerminator(), DT, LI, nullptr,
2994  "vector.ph");
2995 
2996  assert(DT->properlyDominates(DT->getNode(TCCheckBlock),
2997  DT->getNode(Bypass)->getIDom()) &&
2998  "TC check is expected to dominate Bypass");
2999 
3000  // Update dominator for Bypass & LoopExit (if needed).
3001  DT->changeImmediateDominator(Bypass, TCCheckBlock);
3003  // If there is an epilogue which must run, there's no edge from the
3004  // middle block to exit blocks and thus no need to update the immediate
3005  // dominator of the exit blocks.
3006  DT->changeImmediateDominator(LoopExitBlock, TCCheckBlock);
3007 
3009  TCCheckBlock->getTerminator(),
3010  BranchInst::Create(Bypass, LoopVectorPreHeader, CheckMinIters));
3011  LoopBypassBlocks.push_back(TCCheckBlock);
3012 }
3013 
3015  BasicBlock *const SCEVCheckBlock =
3017  if (!SCEVCheckBlock)
3018  return nullptr;
3019 
3020  assert(!(SCEVCheckBlock->getParent()->hasOptSize() ||
3023  "Cannot SCEV check stride or overflow when optimizing for size");
3024 
3025 
3026  // Update dominator only if this is first RT check.
3027  if (LoopBypassBlocks.empty()) {
3028  DT->changeImmediateDominator(Bypass, SCEVCheckBlock);
3030  // If there is an epilogue which must run, there's no edge from the
3031  // middle block to exit blocks and thus no need to update the immediate
3032  // dominator of the exit blocks.
3033  DT->changeImmediateDominator(LoopExitBlock, SCEVCheckBlock);
3034  }
3035 
3036  LoopBypassBlocks.push_back(SCEVCheckBlock);
3037  AddedSafetyChecks = true;
3038  return SCEVCheckBlock;
3039 }
3040 
3042  // VPlan-native path does not do any analysis for runtime checks currently.
3044  return nullptr;
3045 
3046  BasicBlock *const MemCheckBlock =
3048 
3049  // Check if we generated code that checks in runtime if arrays overlap. We put
3050  // the checks into a separate block to make the more common case of few
3051  // elements faster.
3052  if (!MemCheckBlock)
3053  return nullptr;
3054 
3055  if (MemCheckBlock->getParent()->hasOptSize() || OptForSizeBasedOnProfile) {
3057  "Cannot emit memory checks when optimizing for size, unless forced "
3058  "to vectorize.");
3059  ORE->emit([&]() {
3060  return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationCodeSize",
3061  OrigLoop->getStartLoc(),
3062  OrigLoop->getHeader())
3063  << "Code-size may be reduced by not forcing "
3064  "vectorization, or by source-code modifications "
3065  "eliminating the need for runtime checks "
3066  "(e.g., adding 'restrict').";
3067  });
3068  }
3069 
3070  LoopBypassBlocks.push_back(MemCheckBlock);
3071 
3072  AddedSafetyChecks = true;
3073 
3074  return MemCheckBlock;
3075 }
3076 
3080  assert(LoopVectorPreHeader && "Invalid loop structure");
3081  LoopExitBlock = OrigLoop->getUniqueExitBlock(); // may be nullptr
3083  "multiple exit loop without required epilogue?");
3084 
3085  LoopMiddleBlock =
3087  LI, nullptr, Twine(Prefix) + "middle.block");
3090  nullptr, Twine(Prefix) + "scalar.ph");
3091 
3092  auto *ScalarLatchTerm = OrigLoop->getLoopLatch()->getTerminator();
3093 
3094  // Set up the middle block terminator. Two cases:
3095  // 1) If we know that we must execute the scalar epilogue, emit an
3096  // unconditional branch.
3097  // 2) Otherwise, we must have a single unique exit block (due to how we
3098  // implement the multiple exit case). In this case, set up a conditional
3099  // branch from the middle block to the loop scalar preheader, and the
3100  // exit block. completeLoopSkeleton will update the condition to use an
3101  // iteration check, if required to decide whether to execute the remainder.
3105  Builder.getTrue());
3106  BrInst->setDebugLoc(ScalarLatchTerm->getDebugLoc());
3108 
3109  // Update dominator for loop exit. During skeleton creation, only the vector
3110  // pre-header and the middle block are created. The vector loop is entirely
3111  // created during VPlan exection.
3113  // If there is an epilogue which must run, there's no edge from the
3114  // middle block to exit blocks and thus no need to update the immediate
3115  // dominator of the exit blocks.
3117 }
3118 
3120  PHINode *OrigPhi, const InductionDescriptor &II,
3121  ArrayRef<BasicBlock *> BypassBlocks,
3122  std::pair<BasicBlock *, Value *> AdditionalBypass) {
3124  assert(VectorTripCount && "Expected valid arguments");
3125 
3126  Instruction *OldInduction = Legal->getPrimaryInduction();
3127  Value *&EndValue = IVEndValues[OrigPhi];
3128  Value *EndValueFromAdditionalBypass = AdditionalBypass.second;
3129  if (OrigPhi == OldInduction) {
3130  // We know what the end value is.
3131  EndValue = VectorTripCount;
3132  } else {
3134 
3135  // Fast-math-flags propagate from the original induction instruction.
3136  if (II.getInductionBinOp() && isa<FPMathOperator>(II.getInductionBinOp()))
3137  B.setFastMathFlags(II.getInductionBinOp()->getFastMathFlags());
3138 
3139  Type *StepType = II.getStep()->getType();
3140  Instruction::CastOps CastOp =
3141  CastInst::getCastOpcode(VectorTripCount, true, StepType, true);
3142  Value *VTC = B.CreateCast(CastOp, VectorTripCount, StepType, "cast.vtc");
3143  Value *Step =
3144  CreateStepValue(II.getStep(), *PSE.getSE(), &*B.GetInsertPoint());
3145  EndValue = emitTransformedIndex(B, VTC, II.getStartValue(), Step, II);
3146  EndValue->setName("ind.end");
3147 
3148  // Compute the end value for the additional bypass (if applicable).
3149  if (AdditionalBypass.first) {
3150  B.SetInsertPoint(&(*AdditionalBypass.first->getFirstInsertionPt()));
3151  CastOp = CastInst::getCastOpcode(AdditionalBypass.second, true, StepType,
3152  true);
3153  Value *Step =
3154  CreateStepValue(II.getStep(), *PSE.getSE(), &*B.GetInsertPoint());
3155  VTC = B.CreateCast(CastOp, AdditionalBypass.second, StepType, "cast.vtc");
3156  EndValueFromAdditionalBypass =
3157  emitTransformedIndex(B, VTC, II.getStartValue(), Step, II);
3158  EndValueFromAdditionalBypass->setName("ind.end");
3159  }
3160  }
3161 
3162  // Create phi nodes to merge from the backedge-taken check block.
3163  PHINode *BCResumeVal = PHINode::Create(OrigPhi->getType(), 3, "bc.resume.val",
3165  // Copy original phi DL over to the new one.
3166  BCResumeVal->setDebugLoc(OrigPhi->getDebugLoc());
3167 
3168  // The new PHI merges the original incoming value, in case of a bypass,
3169  // or the value at the end of the vectorized loop.
3170  BCResumeVal->addIncoming(EndValue, LoopMiddleBlock);
3171 
3172  // Fix the scalar body counter (PHI node).
3173  // The old induction's phi node in the scalar body needs the truncated
3174  // value.
3175  for (BasicBlock *BB : BypassBlocks)
3176  BCResumeVal->addIncoming(II.getStartValue(), BB);
3177 
3178  if (AdditionalBypass.first)
3179  BCResumeVal->setIncomingValueForBlock(AdditionalBypass.first,
3180  EndValueFromAdditionalBypass);
3181  return BCResumeVal;
3182 }
3183 
3185  std::pair<BasicBlock *, Value *> AdditionalBypass) {
3186  assert(((AdditionalBypass.first && AdditionalBypass.second) ||
3187  (!AdditionalBypass.first && !AdditionalBypass.second)) &&
3188  "Inconsistent information about additional bypass.");
3189  // We are going to resume the execution of the scalar loop.
3190  // Go over all of the induction variables that we found and fix the
3191  // PHIs that are left in the scalar version of the loop.
3192  // The starting values of PHI nodes depend on the counter of the last
3193  // iteration in the vectorized loop.
3194  // If we come from a bypass edge then we need to start from the original
3195  // start value.
3196  for (const auto &InductionEntry : Legal->getInductionVars()) {
3197  PHINode *OrigPhi = InductionEntry.first;
3198  const InductionDescriptor &II = InductionEntry.second;
3199  PHINode *BCResumeVal = createInductionResumeValue(
3200  OrigPhi, II, LoopBypassBlocks, AdditionalBypass);
3201  OrigPhi->setIncomingValueForBlock(LoopScalarPreHeader, BCResumeVal);
3202  }
3203 }
3204 
3206  // The trip counts should be cached by now.
3209 
3210  auto *ScalarLatchTerm = OrigLoop->getLoopLatch()->getTerminator();
3211 
3212  // Add a check in the middle block to see if we have completed
3213  // all of the iterations in the first vector loop. Three cases:
3214  // 1) If we require a scalar epilogue, there is no conditional branch as
3215  // we unconditionally branch to the scalar preheader. Do nothing.
3216  // 2) If (N - N%VF) == N, then we *don't* need to run the remainder.
3217  // Thus if tail is to be folded, we know we don't need to run the
3218  // remainder and we can use the previous value for the condition (true).
3219  // 3) Otherwise, construct a runtime check.
3221  Instruction *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
3222  Count, VectorTripCount, "cmp.n",
3224 
3225  // Here we use the same DebugLoc as the scalar loop latch terminator instead
3226  // of the corresponding compare because they may have ended up with
3227  // different line numbers and we want to avoid awkward line stepping while
3228  // debugging. Eg. if the compare has got a line number inside the loop.
3229  CmpN->setDebugLoc(ScalarLatchTerm->getDebugLoc());
3230  cast<BranchInst>(LoopMiddleBlock->getTerminator())->setCondition(CmpN);
3231  }
3232 
3233 #ifdef EXPENSIVE_CHECKS
3235 #endif
3236 
3237  return LoopVectorPreHeader;
3238 }
3239 
3240 std::pair<BasicBlock *, Value *>
3242  /*
3243  In this function we generate a new loop. The new loop will contain
3244  the vectorized instructions while the old loop will continue to run the
3245  scalar remainder.
3246 
3247  [ ] <-- loop iteration number check.
3248  / |
3249  / v
3250  | [ ] <-- vector loop bypass (may consist of multiple blocks).
3251  | / |
3252  | / v
3253  || [ ] <-- vector pre header.
3254  |/ |
3255  | v
3256  | [ ] \
3257  | [ ]_| <-- vector loop (created during VPlan execution).
3258  | |
3259  | v
3260  \ -[ ] <--- middle-block.
3261  \/ |
3262  /\ v
3263  | ->[ ] <--- new preheader.
3264  | |
3265  (opt) v <-- edge from middle to exit iff epilogue is not required.
3266  | [ ] \
3267  | [ ]_| <-- old scalar loop to handle remainder (scalar epilogue).
3268  \ |
3269  \ v
3270  >[ ] <-- exit block(s).
3271  ...
3272  */
3273 
3274  // Get the metadata of the original loop before it gets modified.
3275  MDNode *OrigLoopID = OrigLoop->getLoopID();
3276 
3277  // Workaround! Compute the trip count of the original loop and cache it
3278  // before we start modifying the CFG. This code has a systemic problem
3279  // wherein it tries to run analysis over partially constructed IR; this is
3280  // wrong, and not simply for SCEV. The trip count of the original loop
3281  // simply happens to be prone to hitting this in practice. In theory, we
3282  // can hit the same issue for any SCEV, or ValueTracking query done during
3283  // mutation. See PR49900.
3285 
3286  // Create an empty vector loop, and prepare basic blocks for the runtime
3287  // checks.
3289 
3290  // Now, compare the new count to zero. If it is zero skip the vector loop and
3291  // jump to the scalar loop. This check also covers the case where the
3292  // backedge-taken count is uint##_max: adding one to it will overflow leading
3293  // to an incorrect trip count of zero. In this (rare) case we will also jump
3294  // to the scalar loop.
3296 
3297  // Generate the code to check any assumptions that we've made for SCEV
3298  // expressions.
3300 
3301  // Generate the code that checks in runtime if arrays overlap. We put the
3302  // checks into a separate block to make the more common case of few elements
3303  // faster.
3305 
3306  // Emit phis for the new starting index of the scalar loop.
3308 
3309  return {completeLoopSkeleton(OrigLoopID), nullptr};
3310 }
3311 
3312 // Fix up external users of the induction variable. At this point, we are
3313 // in LCSSA form, with all external PHIs that use the IV having one input value,
3314 // coming from the remainder loop. We need those PHIs to also have a correct
3315 // value for the IV when arriving directly from the middle block.
3317  const InductionDescriptor &II,
3318  Value *VectorTripCount, Value *EndValue,
3319  BasicBlock *MiddleBlock,
3320  BasicBlock *VectorHeader, VPlan &Plan) {
3321  // There are two kinds of external IV usages - those that use the value
3322  // computed in the last iteration (the PHI) and those that use the penultimate
3323  // value (the value that feeds into the phi from the loop latch).
3324  // We allow both, but they, obviously, have different values.
3325 
3326  assert(OrigLoop->getUniqueExitBlock() && "Expected a single exit block");
3327 
3328  DenseMap<Value *, Value *> MissingVals;
3329 
3330  // An external user of the last iteration's value should see the value that
3331  // the remainder loop uses to initialize its own IV.
3333  for (User *U : PostInc->users()) {
3334  Instruction *UI = cast<Instruction>(U);
3335  if (!OrigLoop->contains(UI)) {
3336  assert(isa<PHINode>(UI) && "Expected LCSSA form");
3337  MissingVals[UI] = EndValue;
3338  }
3339  }
3340 
3341  // An external user of the penultimate value need to see EndValue - Step.
3342  // The simplest way to get this is to recompute it from the constituent SCEVs,
3343  // that is Start + (Step * (CRD - 1)).
3344  for (User *U : OrigPhi->users()) {
3345  auto *UI = cast<Instruction>(U);
3346  if (!OrigLoop->contains(UI)) {
3347  assert(isa<PHINode>(UI) && "Expected LCSSA form");
3348 
3349  IRBuilder<> B(MiddleBlock->getTerminator());
3350 
3351  // Fast-math-flags propagate from the original induction instruction.
3352  if (II.getInductionBinOp() && isa<FPMathOperator>(II.getInductionBinOp()))
3353  B.setFastMathFlags(II.getInductionBinOp()->getFastMathFlags());
3354 
3355  Value *CountMinusOne = B.CreateSub(
3357  Value *CMO =
3358  !II.getStep()->getType()->isIntegerTy()
3359  ? B.CreateCast(Instruction::SIToFP, CountMinusOne,
3360  II.getStep()->getType())
3361  : B.CreateSExtOrTrunc(CountMinusOne, II.getStep()->getType());
3362  CMO->setName("cast.cmo");
3363 
3364  Value *Step = CreateStepValue(II.getStep(), *PSE.getSE(),
3365  VectorHeader->getTerminator());
3366  Value *Escape =
3367  emitTransformedIndex(B, CMO, II.getStartValue(), Step, II);
3368  Escape->setName("ind.escape");
3369  MissingVals[UI] = Escape;
3370  }
3371  }
3372 
3373  for (auto &I : MissingVals) {
3374  PHINode *PHI = cast<PHINode>(I.first);
3375  // One corner case we have to handle is two IVs "chasing" each-other,
3376  // that is %IV2 = phi [...], [ %IV1, %latch ]
3377  // In this case, if IV1 has an external use, we need to avoid adding both
3378  // "last value of IV1" and "penultimate value of IV2". So, verify that we
3379  // don't already have an incoming value for the middle block.
3380  if (PHI->getBasicBlockIndex(MiddleBlock) == -1) {
3381  PHI->addIncoming(I.second, MiddleBlock);
3382  Plan.removeLiveOut(PHI);
3383  }
3384  }
3385 }
3386 
3387 namespace {
3388 
3389 struct CSEDenseMapInfo {
3390  static bool canHandle(const Instruction *I) {
3391  return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
3392  isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
3393  }
3394 
3395  static inline Instruction *getEmptyKey() {
3397  }
3398 
3399  static inline Instruction *getTombstoneKey() {
3401  }
3402 
3403  static unsigned getHashValue(const Instruction *I) {
3404  assert(canHandle(I) && "Unknown instruction!");
3405  return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
3406  I->value_op_end()));
3407  }
3408 
3409  static bool isEqual(const Instruction *LHS, const Instruction *RHS) {
3410  if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
3411  LHS == getTombstoneKey() || RHS == getTombstoneKey())
3412  return LHS == RHS;
3413  return LHS->isIdenticalTo(RHS);
3414  }
3415 };
3416 
3417 } // end anonymous namespace
3418 
3419 ///Perform cse of induction variable instructions.
3420 static void cse(BasicBlock *BB) {
3421  // Perform simple cse.
3424  if (!CSEDenseMapInfo::canHandle(&In))
3425  continue;
3426 
3427  // Check if we can replace this instruction with any of the
3428  // visited instructions.
3429  if (Instruction *V = CSEMap.lookup(&In)) {
3430  In.replaceAllUsesWith(V);
3431  In.eraseFromParent();
3432  continue;
3433  }
3434 
3435  CSEMap[&In] = &In;
3436  }
3437 }
3438 
3441  bool &NeedToScalarize) const {
3442  Function *F = CI->getCalledFunction();
3443  Type *ScalarRetTy = CI->getType();
3444  SmallVector<Type *, 4> Tys, ScalarTys;
3445  for (auto &ArgOp : CI->args())
3446  ScalarTys.push_back(ArgOp->getType());
3447 
3448  // Estimate cost of scalarized vector call. The source operands are assumed
3449  // to be vectors, so we need to extract individual elements from there,
3450  // execute VF scalar calls, and then gather the result into the vector return
3451  // value.
3452  InstructionCost ScalarCallCost =
3453  TTI.getCallInstrCost(F, ScalarRetTy, ScalarTys, TTI::TCK_RecipThroughput);
3454  if (VF.isScalar())
3455  return ScalarCallCost;
3456 
3457  // Compute corresponding vector type for return value and arguments.
3458  Type *RetTy = ToVectorTy(ScalarRetTy, VF);
3459  for (Type *ScalarTy : ScalarTys)
3460  Tys.push_back(ToVectorTy(ScalarTy, VF));
3461 
3462  // Compute costs of unpacking argument values for the scalar calls and
3463  // packing the return values to a vector.
3464  InstructionCost ScalarizationCost = getScalarizationOverhead(CI, VF);
3465 
3467  ScalarCallCost * VF.getKnownMinValue() + ScalarizationCost;
3468 
3469  // If we can't emit a vector call for this function, then the currently found
3470  // cost is the cost we need to return.
3471  NeedToScalarize = true;
3472  VFShape Shape = VFShape::get(*CI, VF, false /*HasGlobalPred*/);
3473  Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
3474 
3475  if (!TLI || CI->isNoBuiltin() || !VecFunc)
3476  return Cost;
3477 
3478  // If the corresponding vector cost is cheaper, return its cost.
3479  InstructionCost VectorCallCost =
3480  TTI.getCallInstrCost(nullptr, RetTy, Tys, TTI::TCK_RecipThroughput);
3481  if (VectorCallCost < Cost) {
3482  NeedToScalarize = false;
3483  Cost = VectorCallCost;
3484  }
3485  return Cost;
3486 }
3487 
3489  if (VF.isScalar() || (!Elt->isIntOrPtrTy() && !Elt->isFloatingPointTy()))
3490  return Elt;
3491  return VectorType::get(Elt, VF);
3492 }
3493 
3496  ElementCount VF) const {
3498  assert(ID && "Expected intrinsic call!");
3499  Type *RetTy = MaybeVectorizeType(CI->getType(), VF);
3500  FastMathFlags FMF;
3501  if (auto *FPMO = dyn_cast<FPMathOperator>(CI))
3502  FMF = FPMO->getFastMathFlags();
3503 
3506  SmallVector<Type *> ParamTys;
3507  std::transform(FTy->param_begin(), FTy->param_end(),
3508  std::back_inserter(ParamTys),
3509  [&](Type *Ty) { return MaybeVectorizeType(Ty, VF); });
3510 
3511  IntrinsicCostAttributes CostAttrs(ID, RetTy, Arguments, ParamTys, FMF,
3512  dyn_cast<IntrinsicInst>(CI));
3513  return TTI.getIntrinsicInstrCost(CostAttrs,
3515 }
3516 
3518  auto *I1 = cast<IntegerType>(cast<VectorType>(T1)->getElementType());
3519  auto *I2 = cast<IntegerType>(cast<VectorType>(T2)->getElementType());
3520  return I1->getBitWidth() < I2->getBitWidth() ? T1 : T2;
3521 }
3522 
3524  auto *I1 = cast<IntegerType>(cast<VectorType>(T1)->getElementType());
3525  auto *I2 = cast<IntegerType>(cast<VectorType>(T2)->getElementType());
3526  return I1->getBitWidth() > I2->getBitWidth() ? T1 : T2;
3527 }
3528 
3530  // For every instruction `I` in MinBWs, truncate the operands, create a
3531  // truncated version of `I` and reextend its result. InstCombine runs
3532  // later and will remove any ext/trunc pairs.
3533  SmallPtrSet<Value *, 4> Erased;
3534  for (const auto &KV : Cost->getMinimalBitwidths()) {
3535  // If the value wasn't vectorized, we must maintain the original scalar
3536  // type. The absence of the value from State indicates that it
3537  // wasn't vectorized.
3538  // FIXME: Should not rely on getVPValue at this point.
3539  VPValue *Def = State.Plan->getVPValue(KV.first, true);
3540  if (!State.hasAnyVectorValue(Def))
3541  continue;
3542  for (unsigned Part = 0; Part < UF; ++Part) {
3543  Value *I = State.get(Def, Part);
3544  if (Erased.count(I) || I->use_empty() || !isa<Instruction>(I))
3545  continue;
3546  Type *OriginalTy = I->getType();
3547  Type *ScalarTruncatedTy =
3548  IntegerType::get(OriginalTy->getContext(), KV.second);
3549  auto *TruncatedTy = VectorType::get(
3550  ScalarTruncatedTy, cast<VectorType>(OriginalTy)->getElementCount());
3551  if (TruncatedTy == OriginalTy)
3552  continue;
3553 
3554  IRBuilder<> B(cast<Instruction>(I));
3555  auto ShrinkOperand = [&](Value *V) -> Value * {
3556  if (auto *ZI = dyn_cast<ZExtInst>(V))
3557  if (ZI->getSrcTy() == TruncatedTy)
3558  return ZI->getOperand(0);
3559  return B.CreateZExtOrTrunc(V, TruncatedTy);
3560  };
3561 
3562  // The actual instruction modification depends on the instruction type,
3563  // unfortunately.
3564  Value *NewI = nullptr;
3565  if (auto *BO = dyn_cast<BinaryOperator>(I)) {
3566  NewI = B.CreateBinOp(BO->getOpcode(), ShrinkOperand(BO->getOperand(0)),
3567  ShrinkOperand(BO->getOperand(1)));
3568 
3569  // Any wrapping introduced by shrinking this operation shouldn't be
3570  // considered undefined behavior. So, we can't unconditionally copy
3571  // arithmetic wrapping flags to NewI.
3572  cast<BinaryOperator>(NewI)->copyIRFlags(I, /*IncludeWrapFlags=*/false);
3573  } else if (auto *CI = dyn_cast<ICmpInst>(I)) {
3574  NewI =
3575  B.CreateICmp(CI->getPredicate(), ShrinkOperand(CI->getOperand(0)),
3576  ShrinkOperand(CI->getOperand(1)));
3577  } else if (auto *SI = dyn_cast<SelectInst>(I)) {
3578  NewI = B.CreateSelect(SI->getCondition(),
3579  ShrinkOperand(SI->getTrueValue()),
3580  ShrinkOperand(SI->getFalseValue()));
3581  } else if (auto *CI = dyn_cast<CastInst>(I)) {
3582  switch (CI->getOpcode()) {
3583  default:
3584  llvm_unreachable("Unhandled cast!");
3585  case Instruction::Trunc:
3586  NewI = ShrinkOperand(CI->getOperand(0));
3587  break;
3588  case Instruction::SExt:
3589  NewI = B.CreateSExtOrTrunc(
3590  CI->getOperand(0),
3591  smallestIntegerVectorType(OriginalTy, TruncatedTy));
3592  break;
3593  case Instruction::ZExt:
3594  NewI = B.CreateZExtOrTrunc(
3595  CI->getOperand(0),
3596  smallestIntegerVectorType(OriginalTy, TruncatedTy));
3597  break;
3598  }
3599  } else if (auto *SI = dyn_cast<ShuffleVectorInst>(I)) {
3600  auto Elements0 =
3601  cast<VectorType>(SI->getOperand(0)->getType())->getElementCount();
3602  auto *O0 = B.CreateZExtOrTrunc(
3603  SI->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements0));
3604  auto Elements1 =
3605  cast<VectorType>(SI->getOperand(1)->getType())->getElementCount();
3606  auto *O1 = B.CreateZExtOrTrunc(
3607  SI->getOperand(1), VectorType::get(ScalarTruncatedTy, Elements1));
3608 
3609  NewI = B.CreateShuffleVector(O0, O1, SI->getShuffleMask());
3610  } else if (isa<LoadInst>(I) || isa<PHINode>(I)) {
3611  // Don't do anything with the operands, just extend the result.
3612  continue;
3613  } else if (auto *IE = dyn_cast<InsertElementInst>(I)) {
3614  auto Elements =
3615  cast<VectorType>(IE->getOperand(0)->getType())->getElementCount();
3616  auto *O0 = B.CreateZExtOrTrunc(
3617  IE->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements));
3618  auto *O1 = B.CreateZExtOrTrunc(IE->getOperand(1), ScalarTruncatedTy);
3619  NewI = B.CreateInsertElement(O0, O1, IE->getOperand(2));
3620  } else if (auto *EE = dyn_cast<ExtractElementInst>(I)) {
3621  auto Elements =
3622  cast<VectorType>(EE->getOperand(0)->getType())->getElementCount();
3623  auto *O0 = B.CreateZExtOrTrunc(
3624  EE->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements));
3625  NewI = B.CreateExtractElement(O0, EE->getOperand(2));
3626  } else {
3627  // If we don't know what to do, be conservative and don't do anything.
3628  continue;
3629  }
3630 
3631  // Lastly, extend the result.
3632  NewI->takeName(cast<Instruction>(I));
3633  Value *Res = B.CreateZExtOrTrunc(NewI, OriginalTy);
3634  I->replaceAllUsesWith(Res);
3635  cast<Instruction>(I)->eraseFromParent();
3636  Erased.insert(I);
3637  State.reset(Def, Res, Part);
3638  }
3639  }
3640 
3641  // We'll have created a bunch of ZExts that are now parentless. Clean up.
3642  for (const auto &KV : Cost->getMinimalBitwidths()) {
3643  // If the value wasn't vectorized, we must maintain the original scalar
3644  // type. The absence of the value from State indicates that it
3645  // wasn't vectorized.
3646  // FIXME: Should not rely on getVPValue at this point.
3647  VPValue *Def = State.Plan->getVPValue(KV.first, true);
3648  if (!State.hasAnyVectorValue(Def))
3649  continue;
3650  for (unsigned Part = 0; Part < UF; ++Part) {
3651  Value *I = State.get(Def, Part);
3652  ZExtInst *Inst = dyn_cast<ZExtInst>(I);
3653  if (Inst && Inst->use_empty()) {
3654  Value *NewI = Inst->getOperand(0);
3655  Inst->eraseFromParent();
3656  State.reset(Def, NewI, Part);
3657  }
3658  }
3659  }
3660 }
3661 
3663  VPlan &Plan) {
3664  // Insert truncates and extends for any truncated instructions as hints to
3665  // InstCombine.
3666  if (VF.isVector())
3668 
3669  // Fix widened non-induction PHIs by setting up the PHI operands.
3671  fixNonInductionPHIs(Plan, State);
3672 
3673  // At this point every instruction in the original loop is widened to a
3674  // vector form. Now we need to fix the recurrences in the loop. These PHI
3675  // nodes are currently empty because we did not want to introduce cycles.
3676  // This is the second stage of vectorizing recurrences.
3677  fixCrossIterationPHIs(State);
3678 
3679  // Forget the original basic block.
3681 
3682  VPBasicBlock *LatchVPBB = Plan.getVectorLoopRegion()->getExitingBasicBlock();
3683  Loop *VectorLoop = LI->getLoopFor(State.CFG.VPBB2IRBB[LatchVPBB]);
3684  if (Cost->requiresScalarEpilogue(VF)) {
3685  // No edge from the middle block to the unique exit block has been inserted
3686  // and there is nothing to fix from vector loop; phis should have incoming
3687  // from scalar loop only.
3688  Plan.clearLiveOuts();
3689  } else {
3690  // If we inserted an edge from the middle block to the unique exit block,
3691  // update uses outside the loop (phis) to account for the newly inserted
3692  // edge.
3693 
3694  // Fix-up external users of the induction variables.
3695  for (const auto &Entry : Legal->getInductionVars())
3696  fixupIVUsers(Entry.first, Entry.second,
3698  IVEndValues[Entry.first], LoopMiddleBlock,
3699  VectorLoop->getHeader(), Plan);
3700  }
3701 
3702  // Fix LCSSA phis not already fixed earlier. Extracts may need to be generated
3703  // in the exit block, so update the builder.
3705  for (const auto &KV : Plan.getLiveOuts())
3706  KV.second->fixPhi(Plan, State);
3707 
3709  sinkScalarOperands(&*PI);
3710 
3711  // Remove redundant induction instructions.
3712  cse(VectorLoop->getHeader());
3713 
3714  // Set/update profile weights for the vector and remainder loops as original
3715  // loop iterations are now distributed among them. Note that original loop
3716  // represented by LoopScalarBody becomes remainder loop after vectorization.
3717  //
3718  // For cases like foldTailByMasking() and requiresScalarEpiloque() we may
3719  // end up getting slightly roughened result but that should be OK since
3720  // profile is not inherently precise anyway. Note also possible bypass of
3721  // vector code caused by legality checks is ignored, assigning all the weight
3722  // to the vector loop, optimistically.
3723  //
3724  // For scalable vectorization we can't know at compile time how many iterations
3725  // of the loop are handled in one vector iteration, so instead assume a pessimistic
3726  // vscale of '1'.
3729  VF.getKnownMinValue() * UF);
3730 }
3731 
3733  // In order to support recurrences we need to be able to vectorize Phi nodes.
3734  // Phi nodes have cycles, so we need to vectorize them in two stages. This is
3735  // stage #2: We now need to fix the recurrences by adding incoming edges to
3736  // the currently empty PHI nodes. At this point every instruction in the
3737  // original loop is widened to a vector form so we can use them to construct
3738  // the incoming edges.
3739  VPBasicBlock *Header =
3741  for (VPRecipeBase &R : Header->phis()) {
3742  if (auto *ReductionPhi = dyn_cast<VPReductionPHIRecipe>(&R))
3743  fixReduction(ReductionPhi, State);
3744  else if (auto *FOR = dyn_cast<VPFirstOrderRecurrencePHIRecipe>(&R))
3745  fixFixedOrderRecurrence(FOR, State);
3746  }
3747 }
3748 
3751  // This is the second phase of vectorizing first-order recurrences. An
3752  // overview of the transformation is described below. Suppose we have the
3753  // following loop.
3754  //
3755  // for (int i = 0; i < n; ++i)
3756  // b[i] = a[i] - a[i - 1];
3757  //
3758  // There is a first-order recurrence on "a". For this loop, the shorthand
3759  // scalar IR looks like:
3760  //
3761  // scalar.ph:
3762  // s_init = a[-1]
3763  // br scalar.body
3764  //
3765  // scalar.body:
3766  // i = phi [0, scalar.ph], [i+1, scalar.body]
3767  // s1 = phi [s_init, scalar.ph], [s2, scalar.body]
3768  // s2 = a[i]
3769  // b[i] = s2 - s1
3770  // br cond, scalar.body, ...
3771  //
3772  // In this example, s1 is a recurrence because it's value depends on the
3773  // previous iteration. In the first phase of vectorization, we created a
3774  // vector phi v1 for s1. We now complete the vectorization and produce the
3775  // shorthand vector IR shown below (for VF = 4, UF = 1).
3776  //
3777  // vector.ph:
3778  // v_init = vector(..., ..., ..., a[-1])
3779  // br vector.body
3780  //
3781  // vector.body
3782  // i = phi [0, vector.ph], [i+4, vector.body]
3783  // v1 = phi [v_init, vector.ph], [v2, vector.body]
3784  // v2 = a[i, i+1, i+2, i+3];
3785  // v3 = vector(v1(3), v2(0, 1, 2))
3786  // b[i, i+1, i+2, i+3] = v2 - v3
3787  // br cond, vector.body, middle.block
3788  //
3789  // middle.block:
3790  // x = v2(3)
3791  // br scalar.ph
3792  //
3793  // scalar.ph:
3794  // s_init = phi [x, middle.block], [a[-1], otherwise]
3795  // br scalar.body
3796  //
3797  // After execution completes the vector loop, we extract the next value of
3798  // the recurrence (x) to use as the initial value in the scalar loop.
3799 
3800  // Extract the last vector element in the middle block. This will be the
3801  // initial value for the recurrence when jumping to the scalar loop.
3802  VPValue *PreviousDef = PhiR->getBackedgeValue();
3803  Value *Incoming = State.get(PreviousDef, UF - 1);
3804  auto *ExtractForScalar = Incoming;
3805  auto *IdxTy = Builder.getInt32Ty();
3806  if (VF.isVector()) {
3807  auto *One = ConstantInt::get(IdxTy, 1);
3809  auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, VF);
3810  auto *LastIdx = Builder.CreateSub(RuntimeVF, One);
3811  ExtractForScalar = Builder.CreateExtractElement(ExtractForScalar, LastIdx,
3812  "vector.recur.extract");
3813  }
3814  // Extract the second last element in the middle block if the
3815  // Phi is used outside the loop. We need to extract the phi itself
3816  // and not the last element (the phi update in the current iteration). This
3817  // will be the value when jumping to the exit block from the LoopMiddleBlock,
3818  // when the scalar loop is not run at all.
3819  Value *ExtractForPhiUsedOutsideLoop = nullptr;
3820  if (VF.isVector()) {
3821  auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, VF);
3822  auto *Idx = Builder.CreateSub(RuntimeVF, ConstantInt::get(IdxTy, 2));
3823  ExtractForPhiUsedOutsideLoop = Builder.CreateExtractElement(
3824  Incoming, Idx, "vector.recur.extract.for.phi");
3825  } else if (UF > 1)
3826  // When loop is unrolled without vectorizing, initialize
3827  // ExtractForPhiUsedOutsideLoop with the value just prior to unrolled value
3828  // of `Incoming`. This is analogous to the vectorized case above: extracting
3829  // the second last element when VF > 1.
3830  ExtractForPhiUsedOutsideLoop = State.get(PreviousDef, UF - 2);
3831 
3832  // Fix the initial value of the original recurrence in the scalar loop.
3834  PHINode *Phi = cast<PHINode>(PhiR->getUnderlyingValue());
3835  auto *Start = Builder.CreatePHI(Phi->getType(), 2, "scalar.recur.init");
3836  auto *ScalarInit = PhiR->getStartValue()->getLiveInIRValue();
3837  for (auto *BB : predecessors(LoopScalarPreHeader)) {
3838  auto *Incoming = BB == LoopMiddleBlock ? ExtractForScalar : ScalarInit;
3839  Start->addIncoming(Incoming, BB);
3840  }
3841 
3843  Phi->setName("scalar.recur");
3844 
3845  // Finally, fix users of the recurrence outside the loop. The users will need
3846  // either the last value of the scalar recurrence or the last value of the
3847  // vector recurrence we extracted in the middle block. Since the loop is in
3848  // LCSSA form, we just need to find all the phi nodes for the original scalar
3849  // recurrence in the exit block, and then add an edge for the middle block.
3850  // Note that LCSSA does not imply single entry when the original scalar loop
3851  // had multiple exiting edges (as we always run the last iteration in the
3852  // scalar epilogue); in that case, there is no edge from middle to exit and
3853  // and thus no phis which needed updated.
3855  for (PHINode &LCSSAPhi : LoopExitBlock->phis())
3856  if (llvm::is_contained(LCSSAPhi.incoming_values(), Phi)) {
3857  LCSSAPhi.addIncoming(ExtractForPhiUsedOutsideLoop, LoopMiddleBlock);
3858  State.Plan->removeLiveOut(&LCSSAPhi);
3859  }
3860 }
3861 
3863  VPTransformState &State) {
3864  PHINode *OrigPhi = cast<PHINode>(PhiR->getUnderlyingValue());
3865  // Get it's reduction variable descriptor.
3866  assert(Legal->isReductionVariable(OrigPhi) &&
3867  "Unable to find the reduction variable");
3868  const RecurrenceDescriptor &RdxDesc = PhiR->getRecurrenceDescriptor();
3869 
3870  RecurKind RK = RdxDesc.getRecurrenceKind();
3871  TrackingVH<Value> ReductionStartValue = RdxDesc.getRecurrenceStartValue();
3872  Instruction *LoopExitInst = RdxDesc.getLoopExitInstr();
3873  State.setDebugLocFromInst(ReductionStartValue);
3874 
3875  VPValue *LoopExitInstDef = PhiR->getBackedgeValue();
3876  // This is the vector-clone of the value that leaves the loop.
3877  Type *VecTy = State.get(LoopExitInstDef, 0)->getType();
3878 
3879  // Wrap flags are in general invalid after vectorization, clear them.
3880  clearReductionWrapFlags(PhiR, State);
3881 
3882  // Before each round, move the insertion point right between
3883  // the PHIs and the values we are going to write.
3884  // This allows us to write both PHINodes and the extractelement
3885  // instructions.
3887 
3888  State.setDebugLocFromInst(LoopExitInst);
3889 
3890  Type *PhiTy = OrigPhi->getType();
3891 
3892  VPBasicBlock *LatchVPBB =
3894  BasicBlock *VectorLoopLatch = State.CFG.VPBB2IRBB[LatchVPBB];
3895  // If tail is folded by masking, the vector value to leave the loop should be
3896  // a Select choosing between the vectorized LoopExitInst and vectorized Phi,
3897  // instead of the former. For an inloop reduction the reduction will already
3898  // be predicated, and does not need to be handled here.
3899  if (Cost->foldTailByMasking() && !PhiR->isInLoop()) {
3900  for (unsigned Part = 0; Part < UF; ++Part) {
3901  Value *VecLoopExitInst = State.get(LoopExitInstDef, Part);
3902  SelectInst *Sel = nullptr;
3903  for (User *U : VecLoopExitInst->users()) {
3904  if (isa<SelectInst>(U)) {
3905  assert(!Sel && "Reduction exit feeding two selects");
3906  Sel = cast<SelectInst>(U);
3907  } else
3908  assert(isa<PHINode>(U) && "Reduction exit must feed Phi's or select");
3909  }
3910  assert(Sel && "Reduction exit feeds no select");
3911  State.reset(LoopExitInstDef, Sel, Part);
3912 
3913  if (isa<FPMathOperator>(Sel))
3914  Sel->setFastMathFlags(RdxDesc.getFastMathFlags());
3915 
3916  // If the target can create a predicated operator for the reduction at no
3917  // extra cost in the loop (for example a predicated vadd), it can be
3918  // cheaper for the select to remain in the loop than be sunk out of it,
3919  // and so use the select value for the phi instead of the old
3920  // LoopExitValue.
3923  RdxDesc.getOpcode(), PhiTy,
3925  auto *VecRdxPhi =
3926  cast<PHINode>(State.get(PhiR, Part));
3927  VecRdxPhi->setIncomingValueForBlock(VectorLoopLatch, Sel);
3928  }
3929  }
3930  }
3931 
3932  // If the vector reduction can be performed in a smaller type, we truncate
3933  // then extend the loop exit value to enable InstCombine to evaluate the
3934  // entire expression in the smaller type.
3935  if (VF.isVector() && PhiTy != RdxDesc.getRecurrenceType()) {
3936  assert(!PhiR->isInLoop() && "Unexpected truncated inloop reduction!");
3937  Type *RdxVecTy = VectorType::get(RdxDesc.getRecurrenceType(), VF);
3938  Builder.SetInsertPoint(VectorLoopLatch->getTerminator());
3939  VectorParts RdxParts(UF);
3940  for (unsigned Part = 0; Part < UF; ++Part) {
3941  RdxParts[Part] = State.get(LoopExitInstDef, Part);
3942  Value *Trunc = Builder.CreateTrunc(RdxParts[Part], RdxVecTy);
3943  Value *Extnd = RdxDesc.isSigned() ? Builder.CreateSExt(Trunc, VecTy)
3944  : Builder.CreateZExt(Trunc, VecTy);
3945  for (User *U : llvm::make_early_inc_range(RdxParts[Part]->users()))
3946  if (U != Trunc) {
3947  U->replaceUsesOfWith(RdxParts[Part], Extnd);
3948  RdxParts[Part] = Extnd;
3949  }
3950  }
3952  for (unsigned Part = 0; Part < UF; ++Part) {
3953  RdxParts[Part] = Builder.CreateTrunc(RdxParts[Part], RdxVecTy);
3954  State.reset(LoopExitInstDef, RdxParts[Part], Part);
3955  }
3956  }
3957 
3958  // Reduce all of the unrolled parts into a single vector.
3959  Value *ReducedPartRdx = State.get(LoopExitInstDef, 0);
3960  unsigned Op = RecurrenceDescriptor::getOpcode(RK);
3961 
3962  // The middle block terminator has already been assigned a DebugLoc here (the
3963  // OrigLoop's single latch terminator). We want the whole middle block to
3964  // appear to execute on this line because: (a) it is all compiler generated,
3965  // (b) these instructions are always executed after evaluating the latch
3966  // conditional branch, and (c) other passes may add new predecessors which
3967  // terminate on this line. This is the easiest way to ensure we don't
3968  // accidentally cause an extra step back into the loop while debugging.
3970  if (PhiR->isOrdered())
3971  ReducedPartRdx = State.get(LoopExitInstDef, UF - 1);
3972  else {
3973  // Floating-point operations should have some FMF to enable the reduction.
3976  for (unsigned Part = 1; Part < UF; ++Part) {
3977  Value *RdxPart = State.get(LoopExitInstDef, Part);
3978  if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
3979  ReducedPartRdx = Builder.CreateBinOp(
3980  (Instruction::BinaryOps)Op, RdxPart, ReducedPartRdx, "bin.rdx");
3982  ReducedPartRdx = createSelectCmpOp(Builder, ReductionStartValue, RK,
3983  ReducedPartRdx, RdxPart);
3984  else
3985  ReducedPartRdx = createMinMaxOp(Builder, RK, ReducedPartRdx, RdxPart);
3986  }
3987  }
3988 
3989  // Create the reduction after the loop. Note that inloop reductions create the
3990  // target reduction in the loop using a Reduction recipe.
3991  if (VF.isVector() && !PhiR->isInLoop()) {
3992  ReducedPartRdx =
3993  createTargetReduction(Builder, TTI, RdxDesc, ReducedPartRdx, OrigPhi);
3994  // If the reduction can be performed in a smaller type, we need to extend
3995  // the reduction to the wider type before we branch to the original loop.
3996  if (PhiTy != RdxDesc.getRecurrenceType())
3997  ReducedPartRdx = RdxDesc.isSigned()
3998  ? Builder.CreateSExt(ReducedPartRdx, PhiTy)
3999  : Builder.CreateZExt(ReducedPartRdx, PhiTy);
4000  }
4001 
4002  PHINode *ResumePhi =
4003  dyn_cast<PHINode>(PhiR->getStartValue()->getUnderlyingValue());
4004 
4005  // Create a phi node that merges control-flow from the backedge-taken check
4006  // block and the middle block.
4007  PHINode *BCBlockPhi = PHINode::Create(PhiTy, 2, "bc.merge.rdx",
4009 
4010  // If we are fixing reductions in the epilogue loop then we should already
4011  // have created a bc.merge.rdx Phi after the main vector body. Ensure that
4012  // we carry over the incoming values correctly.
4013  for (auto *Incoming : predecessors(LoopScalarPreHeader)) {
4014  if (Incoming == LoopMiddleBlock)
4015  BCBlockPhi->addIncoming(ReducedPartRdx, Incoming);
4016  else if (ResumePhi && llvm::is_contained(ResumePhi->blocks(), Incoming))
4017  BCBlockPhi->addIncoming(ResumePhi->getIncomingValueForBlock(Incoming),
4018  Incoming);
4019  else
4020  BCBlockPhi->addIncoming(ReductionStartValue, Incoming);
4021  }
4022 
4023  // Set the resume value for this reduction
4024  ReductionResumeValues.insert({&RdxDesc, BCBlockPhi});
4025 
4026  // If there were stores of the reduction value to a uniform memory address
4027  // inside the loop, create the final store here.
4028  if (StoreInst *SI = RdxDesc.IntermediateStore) {
4029  StoreInst *NewSI =
4030  Builder.CreateStore(ReducedPartRdx, SI->getPointerOperand());
4031  propagateMetadata(NewSI, SI);
4032 
4033  // If the reduction value is used in other places,
4034  // then let the code below create PHI's for that.
4035  }
4036 
4037  // Now, we need to fix the users of the reduction variable
4038  // inside and outside of the scalar remainder loop.
4039 
4040  // We know that the loop is in LCSSA form. We need to update the PHI nodes
4041  // in the exit blocks. See comment on analogous loop in
4042  // fixFixedOrderRecurrence for a more complete explaination of the logic.
4044  for (PHINode &LCSSAPhi : LoopExitBlock->phis())
4045  if (llvm::is_contained(LCSSAPhi.incoming_values(), LoopExitInst)) {
4046  LCSSAPhi.addIncoming(ReducedPartRdx, LoopMiddleBlock);
4047  State.Plan->removeLiveOut(&LCSSAPhi);
4048  }
4049 
4050  // Fix the scalar loop reduction variable with the incoming reduction sum
4051  // from the vector body and from the backedge value.
4052  int IncomingEdgeBlockIdx =
4054  assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
4055  // Pick the other block.
4056  int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
4057  OrigPhi->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi);
4058  OrigPhi->setIncomingValue(IncomingEdgeBlockIdx, LoopExitInst);
4059 }
4060 
4062  VPTransformState &State) {
4063  const RecurrenceDescriptor &RdxDesc = PhiR->getRecurrenceDescriptor();
4064  RecurKind RK = RdxDesc.getRecurrenceKind();
4065  if (RK != RecurKind::Add && RK != RecurKind::Mul)
4066  return;
4067 
4068  SmallVector<VPValue *, 8> Worklist;
4069  SmallPtrSet<VPValue *, 8> Visited;
4070  Worklist.push_back(PhiR);
4071  Visited.insert(PhiR);
4072 
4073  while (!Worklist.empty()) {
4074  VPValue *Cur = Worklist.pop_back_val();
4075  for (unsigned Part = 0; Part < UF; ++Part) {
4076  Value *V = State.get(Cur, Part);
4077  if (!isa<OverflowingBinaryOperator>(V))
4078  break;
4079  cast<Instruction>(V)->dropPoisonGeneratingFlags();
4080  }
4081 
4082  for (VPUser *U : Cur->users()) {
4083  auto *UserRecipe = dyn_cast<VPRecipeBase>(U);
4084  if (!UserRecipe)
4085  continue;
4086  for (VPValue *V : UserRecipe->definedValues())
4087  if (Visited.insert(V).second)
4088  Worklist.push_back(V);
4089  }
4090  }
4091 }
4092 
4094  // The basic block and loop containing the predicated instruction.
4095  auto *PredBB = PredInst->getParent();
4096  auto *VectorLoop = LI->getLoopFor(PredBB);
4097 
4098  // Initialize a worklist with the operands of the predicated instruction.
4099  SetVector<Value *> Worklist(PredInst->op_begin(), PredInst->op_end());
4100 
4101  // Holds instructions that we need to analyze again. An instruction may be
4102  // reanalyzed if we don't yet know if we can sink it or not.
4103  SmallVector<Instruction *, 8> InstsToReanalyze;
4104 
4105  // Returns true if a given use occurs in the predicated block. Phi nodes use
4106  // their operands in their corresponding predecessor blocks.
4107  auto isBlockOfUsePredicated = [&](Use &U) -> bool {
4108  auto *I = cast<Instruction>(U.getUser());
4109  BasicBlock *BB = I->getParent();
4110  if (auto *Phi = dyn_cast<PHINode>(I))
4111  BB = Phi->getIncomingBlock(
4112  PHINode::getIncomingValueNumForOperand(U.getOperandNo()));
4113  return BB == PredBB;
4114  };
4115 
4116  // Iteratively sink the scalarized operands of the predicated instruction
4117  // into the block we created for it. When an instruction is sunk, it's
4118  // operands are then added to the worklist. The algorithm ends after one pass
4119  // through the worklist doesn't sink a single instruction.
4120  bool Changed;
4121  do {
4122  // Add the instructions that need to be reanalyzed to the worklist, and
4123  // reset the changed indicator.
4124  Worklist.insert(InstsToReanalyze.begin(), InstsToReanalyze.end());
4125  InstsToReanalyze.clear();
4126  Changed = false;
4127 
4128  while (!Worklist.empty()) {
4129  auto *I = dyn_cast<Instruction>(Worklist.pop_back_val());
4130 
4131  // We can't sink an instruction if it is a phi node, is not in the loop,
4132  // or may have side effects.
4133  if (!I || isa<PHINode>(I) || !VectorLoop->contains(I) ||
4134  I->mayHaveSideEffects())
4135  continue;
4136 
4137  // If the instruction is already in PredBB, check if we can sink its
4138  // operands. In that case, VPlan's sinkScalarOperands() succeeded in
4139  // sinking the scalar instruction I, hence it appears in PredBB; but it
4140  // may have failed to sink I's operands (recursively), which we try
4141  // (again) here.
4142  if (I->getParent() == PredBB) {
4143  Worklist.insert(I->op_begin(), I->op_end());
4144  continue;
4145  }
4146 
4147  // It's legal to sink the instruction if all its uses occur in the
4148  // predicated block. Otherwise, there's nothing to do yet, and we may
4149  // need to reanalyze the instruction.
4150  if (!llvm::all_of(I->uses(), isBlockOfUsePredicated)) {
4151  InstsToReanalyze.push_back(I);
4152  continue;
4153  }
4154 
4155  // Move the instruction to the beginning of the predicated block, and add
4156  // it's operands to the worklist.
4157  I->moveBefore(&*PredBB->getFirstInsertionPt());
4158  Worklist.insert(I->op_begin(), I->op_end());
4159 
4160  // The sinking may have enabled other instructions to be sunk, so we will
4161  // need to iterate.
4162  Changed = true;
4163  }
4164  } while (Changed);
4165 }
4166 
4168  VPTransformState &State) {
4169  auto Iter = depth_first(
4171  for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(Iter)) {
4172  for (VPRecipeBase &P : VPBB->phis()) {
4173  VPWidenPHIRecipe *VPPhi = dyn_cast<VPWidenPHIRecipe>(&P);
4174  if (!VPPhi)
4175  continue;
4176  PHINode *NewPhi = cast<PHINode>(State.get(VPPhi, 0));
4177  // Make sure the builder has a valid insert point.
4178  Builder.SetInsertPoint(NewPhi);
4179  for (unsigned i = 0; i < VPPhi->getNumOperands(); ++i) {
4180  VPValue *Inc = VPPhi->getIncomingValue(i);
4181  VPBasicBlock *VPBB = VPPhi->getIncomingBlock(i);
4182  NewPhi->addIncoming(State.get(Inc, 0), State.CFG.VPBB2IRBB[VPBB]);
4183  }
4184  }
4185  }
4186 }
4187 
4189  const RecurrenceDescriptor &RdxDesc) {
4190  return Cost->useOrderedReductions(RdxDesc);
4191 }
4192 
4193 void LoopVectorizationCostModel::collectLoopScalars(ElementCount VF) {
4194  // We should not collect Scalars more than once per VF. Right now, this
4195  // function is called from collectUniformsAndScalars(), which already does
4196  // this check. Collecting Scalars for VF=1 does not make any sense.
4197  assert(VF.isVector() && Scalars.find(VF) == Scalars.end() &&
4198  "This function should not be visited twice for the same VF");
4199 
4200  // This avoids any chances of creating a REPLICATE recipe during planning
4201  // since that would result in generation of scalarized code during execution,
4202  // which is not supported for scalable vectors.
4203  if (VF.isScalable()) {
4204  Scalars[VF].insert(Uniforms[VF].begin(), Uniforms[VF].end());
4205  return;
4206  }
4207 
4209 
4210  // These sets are used to seed the analysis with pointers used by memory
4211  // accesses that will remain scalar.
4213  SmallPtrSet<Instruction *, 8> PossibleNonScalarPtrs;
4214  auto *Latch = TheLoop->getLoopLatch();
4215 
4216  // A helper that returns true if the use of Ptr by MemAccess will be scalar.
4217  // The pointer operands of loads and stores will be scalar as long as the
4218  // memory access is not a gather or scatter operation. The value operand of a
4219  // store will remain scalar if the store is scalarized.
4220  auto isScalarUse = [&](Instruction *MemAccess, Value *Ptr) {
4221  InstWidening WideningDecision = getWideningDecision(MemAccess, VF);
4222  assert(WideningDecision != CM_Unknown &&
4223  "Widening decision should be ready at this moment");
4224  if (auto *Store = dyn_cast<StoreInst>(MemAccess))
4225  if (Ptr == Store->getValueOperand())
4226  return WideningDecision == CM_Scalarize;
4227  assert(Ptr == getLoadStorePointerOperand(MemAccess) &&
4228  "Ptr is neither a value or pointer operand");
4229  return WideningDecision != CM_GatherScatter;
4230  };
4231 
4232  // A helper that returns true if the given value is a bitcast or
4233  // getelementptr instruction contained in the loop.
4234  auto isLoopVaryingBitCastOrGEP = [&](Value *V) {
4235  return ((isa<BitCastInst>(V) && V->getType()->isPointerTy()) ||
4236  isa<GetElementPtrInst>(V)) &&
4237  !TheLoop->isLoopInvariant(V);
4238  };
4239 
4240  // A helper that evaluates a memory access's use of a pointer. If the use will
4241  // be a scalar use and the pointer is only used by memory accesses, we place
4242  // the pointer in ScalarPtrs. Otherwise, the pointer is placed in
4243  // PossibleNonScalarPtrs.
4244  auto evaluatePtrUse = [&](Instruction *MemAccess, Value *Ptr) {
4245  // We only care about bitcast and getelementptr instructions contained in
4246  // the loop.
4247  if (!isLoopVaryingBitCastOrGEP(Ptr))
4248  return;
4249 
4250  // If the pointer has already been identified as scalar (e.g., if it was
4251  // also identified as uniform), there's nothing to do.
4252  auto *I = cast<Instruction>(Ptr);
4253  if (Worklist.count(I))
4254  return;
4255 
4256  // If the use of the pointer will be a scalar use, and all users of the
4257  // pointer are memory accesses, place the pointer in ScalarPtrs. Otherwise,
4258  // place the pointer in PossibleNonScalarPtrs.
4259  if (isScalarUse(MemAccess, Ptr) && llvm::all_of(I->users(), [&](User *U) {
4260  return isa<LoadInst>(U) || isa<StoreInst>(U);
4261  }))
4262  ScalarPtrs.insert(I);
4263  else
4264  PossibleNonScalarPtrs.insert(I);
4265  };
4266 
4267  // We seed the scalars analysis with three classes of instructions: (1)
4268  // instructions marked uniform-after-vectorization and (2) bitcast,
4269  // getelementptr and (pointer) phi instructions used by memory accesses
4270  // requiring a scalar use.
4271  //
4272  // (1) Add to the worklist all instructions that have been identified as
4273  // uniform-after-vectorization.
4274  Worklist.insert(Uniforms[VF].begin(), Uniforms[VF].end());
4275 
4276  // (2) Add to the worklist all bitcast and getelementptr instructions used by
4277  // memory accesses requiring a scalar use. The pointer operands of loads and
4278  // stores will be scalar as long as the memory accesses is not a gather or
4279  // scatter operation. The value operand of a store will remain scalar if the
4280  // store is scalarized.
4281  for (auto *BB : TheLoop->blocks())
4282  for (auto &I : *BB) {
4283  if (auto *Load = dyn_cast<LoadInst>(&I)) {
4284  evaluatePtrUse(Load, Load->getPointerOperand());
4285  } else if (auto *Store = dyn_cast<StoreInst>(&I)) {
4286  evaluatePtrUse(Store, Store->getPointerOperand());
4287  evaluatePtrUse(Store, Store->getValueOperand());
4288  }
4289  }
4290  for (auto *I : ScalarPtrs)
4291  if (!PossibleNonScalarPtrs.count(I)) {
4292  LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *I << "\n");
4293  Worklist.insert(I);
4294  }
4295 
4296  // Insert the forced scalars.
4297  // FIXME: Currently VPWidenPHIRecipe() often creates a dead vector
4298  // induction variable when the PHI user is scalarized.
4299  auto ForcedScalar = ForcedScalars.find(VF);
4300  if (ForcedScalar != ForcedScalars.end())
4301  for (auto *I : ForcedScalar->second) {
4302  LLVM_DEBUG(dbgs() << "LV: Found (forced) scalar instruction: " << *I << "\n");
4303  Worklist.insert(I);
4304  }
4305 
4306  // Expand the worklist by looking through any bitcasts and getelementptr
4307  // instructions we've already identified as scalar. This is similar to the
4308  // expansion step in collectLoopUniforms(); however, here we're only
4309  // expanding to include additional bitcasts and getelementptr instructions.
4310  unsigned Idx = 0;
4311  while (Idx != Worklist.size()) {
4312  Instruction *Dst = Worklist[Idx++];
4313  if (!isLoopVaryingBitCastOrGEP(Dst->getOperand(0)))
4314  continue;
4315  auto *Src = cast<Instruction>(Dst->getOperand(0));
4316  if (llvm::all_of(Src->users(), [&](User *U) -> bool {
4317  auto *J = cast<Instruction>(U);
4318  return !TheLoop->contains(J) || Worklist.count(J) ||
4319  ((isa<LoadInst>(J) || isa<StoreInst>(J)) &&
4320  isScalarUse(J, Src));
4321  })) {
4322  Worklist.insert(Src);
4323  LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Src << "\n");
4324  }
4325  }
4326 
4327  // An induction variable will remain scalar if all users of the induction
4328  // variable and induction variable update remain scalar.
4329  for (const auto &Induction : Legal->getInductionVars()) {
4330  auto *Ind = Induction.first;
4331  auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
4332 
4333  // If tail-folding is applied, the primary induction variable will be used
4334  // to feed a vector compare.
4335  if (Ind == Legal->getPrimaryInduction() && foldTailByMasking())
4336  continue;
4337 
4338  // Returns true if \p Indvar is a pointer induction that is used directly by
4339  // load/store instruction \p I.
4340  auto IsDirectLoadStoreFromPtrIndvar = [&](Instruction *Indvar,
4341  Instruction *I) {
4342  return Induction.second.getKind() ==
4344  (isa<LoadInst>(I) || isa<StoreInst>(I)) &&
4345  Indvar == getLoadStorePointerOperand(I) && isScalarUse(I, Indvar);
4346  };
4347 
4348  // Determine if all users of the induction variable are scalar after
4349  // vectorization.
4350  auto ScalarInd = llvm::all_of(Ind->users(), [&](User *U) -> bool {
4351  auto *I = cast<Instruction>(U);
4352  return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) ||
4353  IsDirectLoadStoreFromPtrIndvar(Ind, I);
4354  });
4355  if (!ScalarInd)
4356  continue;
4357 
4358  // Determine if all users of the induction variable update instruction are
4359  // scalar after vectorization.
4360  auto ScalarIndUpdate =
4361  llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
4362  auto *I = cast<Instruction>(U);
4363  return I == Ind || !TheLoop->contains(I) || Worklist.count(I) ||
4364  IsDirectLoadStoreFromPtrIndvar(IndUpdate, I);
4365  });
4366  if (!ScalarIndUpdate)
4367  continue;
4368 
4369  // The induction variable and its update instruction will remain scalar.
4370  Worklist.insert(Ind);
4371  Worklist.insert(IndUpdate);
4372  LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Ind << "\n");
4373  LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *IndUpdate
4374  << "\n");
4375  }
4376 
4377  Scalars[VF].insert(Worklist.begin(), Worklist.end());
4378 }
4379 
4381  Instruction *I, ElementCount VF) const {
4382  if (!isPredicatedInst(I))
4383  return false;
4384 
4385  // Do we have a non-scalar lowering for this predicated
4386  // instruction? No - it is scalar with predication.
4387  switch(I->getOpcode()) {
4388  default:
4389  return true;
4390  case Instruction::Load:
4391  case Instruction::Store: {
4392  auto *Ptr = getLoadStorePointerOperand(I);
4393  auto *Ty = getLoadStoreType(I);
4394  Type *VTy = Ty;
4395  if (VF.isVector())
4396  VTy = VectorType::get(Ty, VF);
4397  const Align Alignment = getLoadStoreAlignment(I);
4398  return isa<LoadInst>(I) ? !(isLegalMaskedLoad(Ty, Ptr, Alignment) ||
4399  TTI.isLegalMaskedGather(VTy, Alignment))
4400  : !(isLegalMaskedStore(Ty, Ptr, Alignment) ||
4401  TTI.isLegalMaskedScatter(VTy, Alignment));
4402  }
4403  case Instruction::UDiv:
4404  case Instruction::SDiv:
4405  case Instruction::SRem:
4406  case Instruction::URem: {
4407  // We have the option to use the safe-divisor idiom to avoid predication.
4408  // The cost based decision here will always select safe-divisor for
4409  // scalable vectors as scalarization isn't legal.
4410  const auto [ScalarCost, SafeDivisorCost] = getDivRemSpeculationCost(I, VF);
4411  return isDivRemScalarWithPredication(ScalarCost, SafeDivisorCost);
4412  }
4413  }
4414 }
4415 
4417  if (!blockNeedsPredicationForAnyReason(I->getParent()))
4418  return false;
4419 
4420  // Can we prove this instruction is safe to unconditionally execute?
4421  // If not, we must use some form of predication.
4422  switch(I->getOpcode()) {
4423  default:
4424  return false;
4425  case Instruction::Load:
4426  case Instruction::Store: {
4427  if (!Legal->isMaskRequired(I))
4428  return false;
4429  // When we know the load's address is loop invariant and the instruction
4430  // in the original scalar loop was unconditionally executed then we
4431  // don't need to mark it as a predicated instruction. Tail folding may
4432  // introduce additional predication, but we're guaranteed to always have
4433  // at least one active lane. We call Legal->blockNeedsPredication here
4434  // because it doesn't query tail-folding. For stores, we need to prove
4435  // both speculation safety (which follows from the same argument as loads),
4436  // but also must prove the value being stored is correct. The easiest
4437  // form of the later is to require that all values stored are the same.
4438  if (Legal->isUniformMemOp(*I) &&
4439  (isa<LoadInst>(I) ||
4440  (isa<StoreInst>(I) &&
4441  TheLoop->isLoopInvariant(cast<StoreInst>(I)->getValueOperand()))) &&
4442  !Legal->blockNeedsPredication(I->getParent()))
4443  return false;
4444  return true;
4445  }
4446  case Instruction::UDiv:
4447  case Instruction::SDiv:
4448  case Instruction::SRem:
4449  case Instruction::URem:
4450  // TODO: We can use the loop-preheader as context point here and get
4451  // context sensitive reasoning
4453  }
4454 }
4455 
4456 std::pair<InstructionCost, InstructionCost>
4458  ElementCount VF) const {
4459  assert(I->getOpcode() == Instruction::UDiv ||
4460  I->getOpcode() == Instruction::SDiv ||
4461  I->getOpcode() == Instruction::SRem ||
4462  I->getOpcode() == Instruction::URem);
4464 
4466 
4467  // Scalarization isn't legal for scalable vector types
4468  InstructionCost ScalarizationCost = InstructionCost::getInvalid();
4469  if (!VF.isScalable()) {
4470  // Get the scalarization cost and scale this amount by the probability of
4471  // executing the predicated block. If the instruction is not predicated,
4472  // we fall through to the next case.
4473  ScalarizationCost = 0;
4474 
4475  // These instructions have a non-void type, so account for the phi nodes
4476  // that we will create. This cost is likely to be zero. The phi node
4477  // cost, if any, should be scaled by the block probability because it
4478  // models a copy at the end of each predicated block.
4479  ScalarizationCost += VF.getKnownMinValue() *
4481 
4482  // The cost of the non-predicated instruction.
4483  ScalarizationCost += VF.getKnownMinValue() *
4484  TTI.getArithmeticInstrCost(I->getOpcode(), I->getType(), CostKind);
4485 
4486  // The cost of insertelement and extractelement instructions needed for
4487  // scalarization.
4488  ScalarizationCost += getScalarizationOverhead(I, VF);
4489 
4490  // Scale the cost by the probability of executing the predicated blocks.
4491  // This assumes the predicated block for each vector lane is equally
4492  // likely.
4493  ScalarizationCost = ScalarizationCost / getReciprocalPredBlockProb();
4494  }
4495  InstructionCost SafeDivisorCost = 0;
4496 
4497  auto *VecTy = ToVectorTy(I->getType(), VF);
4498 
4499  // The cost of the select guard to ensure all lanes are well defined
4500  // after we speculate above any internal control flow.
4501  SafeDivisorCost += TTI.getCmpSelInstrCost(
4502  Instruction::Select, VecTy,
4503  ToVectorTy(Type::getInt1Ty(I->getContext()), VF),
4505 
4506  // Certain instructions can be cheaper to vectorize if they have a constant
4507  // second vector operand. One example of this are shifts on x86.
4508  Value *Op2 = I->getOperand(1);
4509  auto Op2Info = TTI.getOperandInfo(Op2);
4510  if (Op2Info.Kind == TargetTransformInfo::OK_AnyValue && Legal->isUniform(Op2))
4512 
4513  SmallVector<const Value *, 4> Operands(I->operand_values());
4514  SafeDivisorCost += TTI.getArithmeticInstrCost(
4515  I->getOpcode(), VecTy, CostKind,
4516  {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
4517  Op2Info, Operands, I);
4518  return {ScalarizationCost, SafeDivisorCost};
4519 }
4520 
4523  assert(isAccessInterleaved(I) && "Expecting interleaved access.");
4524  assert(getWideningDecision(I, VF) == CM_Unknown &&
4525  "Decision should not be set yet.");
4526  auto *Group = getInterleavedAccessGroup(I);
4527  assert(Group && "Must have a group.");
4528 
4529  // If the instruction's allocated size doesn't equal it's type size, it
4530  // requires padding and will be scalarized.
4531  auto &DL = I->getModule()->getDataLayout();
4532  auto *ScalarTy = getLoadStoreType(I);
4533  if (hasIrregularType(ScalarTy, DL))
4534  return false;
4535 
4536  // If the group involves a non-integral pointer, we may not be able to
4537  // losslessly cast all values to a common type.
4538  unsigned InterleaveFactor = Group->getFactor();
4539  bool ScalarNI = DL.isNonIntegralPointerType(ScalarTy);
4540  for (unsigned i = 0; i < InterleaveFactor; i++) {
4541  Instruction *Member = Group->getMember(i);
4542  if (!Member)
4543  continue;
4544  auto *MemberTy = getLoadStoreType(Member);
4545  bool MemberNI = DL.isNonIntegralPointerType(MemberTy);
4546  // Don't coerce non-integral pointers to integers or vice versa.
4547  if (MemberNI != ScalarNI) {
4548  // TODO: Consider adding special nullptr value case here
4549  return false;
4550  } else if (MemberNI && ScalarNI &&
4551  ScalarTy->getPointerAddressSpace() !=
4552  MemberTy->getPointerAddressSpace()) {
4553  return false;
4554  }
4555  }
4556 
4557  // Check if masking is required.
4558  // A Group may need masking for one of two reasons: it resides in a block that
4559  // needs predication, or it was decided to use masking to deal with gaps
4560  // (either a gap at the end of a load-access that may result in a speculative
4561  // load, or any gaps in a store-access).
4562  bool PredicatedAccessRequiresMasking =
4563  blockNeedsPredicationForAnyReason(I->getParent()) &&
4565  bool LoadAccessWithGapsRequiresEpilogMasking =
4566  isa<LoadInst>(I) && Group->requiresScalarEpilogue() &&
4567  !isScalarEpilogueAllowed();
4568  bool StoreAccessWithGapsRequiresMasking =
4569  isa<StoreInst>(I) && (Group->getNumMembers() < Group->getFactor());
4570  if (!PredicatedAccessRequiresMasking &&
4571  !LoadAccessWithGapsRequiresEpilogMasking &&
4572  !StoreAccessWithGapsRequiresMasking)
4573  return true;
4574 
4575  // If masked interleaving is required, we expect that the user/target had
4576  // enabled it, because otherwise it either wouldn't have been created or
4577  // it should have been invalidated by the CostModel.
4579  "Masked interleave-groups for predicated accesses are not enabled.");
4580 
4581  if (Group->isReverse())
4582  return false;
4583 
4584  auto *Ty = getLoadStoreType(I);
4585  const Align Alignment = getLoadStoreAlignment(I);
4586  return isa<LoadInst>(I) ? TTI.isLegalMaskedLoad(Ty, Alignment)
4587  : TTI.isLegalMaskedStore(Ty, Alignment);
4588 }
4589 
4592  // Get and ensure we have a valid memory instruction.
4593  assert((isa<LoadInst, StoreInst>(I)) && "Invalid memory instruction");
4594 
4595  auto *Ptr = getLoadStorePointerOperand(I);
4596  auto *ScalarTy = getLoadStoreType(I);
4597 
4598  // In order to be widened, the pointer should be consecutive, first of all.
4599  if (!Legal->isConsecutivePtr(ScalarTy, Ptr))
4600  return false;
4601 
4602  // If the instruction is a store located in a predicated block, it will be
4603  // scalarized.
4604  if (isScalarWithPredication(I, VF))
4605  return false;
4606 
4607  // If the instruction's allocated size doesn't equal it's type size, it
4608  // requires padding and will be scalarized.
4609  auto &DL = I->getModule()->getDataLayout();
4610  if (hasIrregularType(ScalarTy, DL))
4611  return false;
4612 
4613  return true;
4614 }
4615 
4616 void LoopVectorizationCostModel::collectLoopUniforms(ElementCount VF) {
4617  // We should not collect Uniforms more than once per VF. Right now,
4618  // this function is called from collectUniformsAndScalars(), which
4619  // already does this check. Collecting Uniforms for VF=1 does not make any
4620  // sense.
4621 
4622  assert(VF.isVector() && Uniforms.find(VF) == Uniforms.end() &&
4623  "This function should not be visited twice for the same VF");
4624 
4625  // Visit the list of Uniforms. If we'll not find any uniform value, we'll
4626  // not analyze again. Uniforms.count(VF) will return 1.
4627  Uniforms[VF].clear();
4628 
4629  // We now know that the loop is vectorizable!
4630  // Collect instructions inside the loop that will remain uniform after
4631  // vectorization.
4632 
4633  // Global values, params and instructions outside of current loop are out of
4634  // scope.
4635  auto isOutOfScope = [&](Value *V) -> bool {
4636  Instruction *I = dyn_cast<Instruction>(V);
4637  return (!I || !TheLoop->contains(I));
4638  };
4639 
4640  // Worklist containing uniform instructions demanding lane 0.
4641  SetVector<Instruction *> Worklist;
4642  BasicBlock *Latch = TheLoop->getLoopLatch();
4643 
4644  // Add uniform instructions demanding lane 0 to the worklist. Instructions
4645  // that are scalar with predication must not be considered uniform after
4646  // vectorization, because that would create an erroneous replicating region
4647  // where only a single instance out of VF should be formed.
4648  // TODO: optimize such seldom cases if found important, see PR40816.
4649  auto addToWorklistIfAllowed = [&](Instruction *I) -> void {
4650  if (isOutOfScope(I)) {
4651  LLVM_DEBUG(dbgs() << "LV: Found not uniform due to scope: "
4652  << *I << "\n");
4653  return;
4654  }
4655  if (isScalarWithPredication(I, VF)) {
4656  LLVM_DEBUG(dbgs() << "LV: Found not uniform being ScalarWithPredication: "
4657  << *I << "\n");
4658  return;
4659  }
4660  LLVM_DEBUG(dbgs() << "LV: Found uniform instruction: " << *I << "\n");
4661  Worklist.insert(