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