LLVM 24.0.0git
VPlan.h
Go to the documentation of this file.
1//===- VPlan.h - Represent A Vectorizer Plan --------------------*- C++ -*-===//
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/// \file
10/// This file contains the declarations of the Vectorization Plan base classes:
11/// 1. VPBasicBlock and VPRegionBlock that inherit from a common pure virtual
12/// VPBlockBase, together implementing a Hierarchical CFG;
13/// 2. Pure virtual VPRecipeBase serving as the base class for recipes contained
14/// within VPBasicBlocks;
15/// 3. Pure virtual VPSingleDefRecipe serving as a base class for recipes that
16/// also inherit from VPValue.
17/// 4. VPInstruction, a concrete Recipe and VPUser modeling a single planned
18/// instruction;
19/// 5. The VPlan class holding a candidate for vectorization;
20/// These are documented in docs/VectorizationPlan.rst.
21//
22//===----------------------------------------------------------------------===//
23
24#ifndef LLVM_TRANSFORMS_VECTORIZE_VPLAN_H
25#define LLVM_TRANSFORMS_VECTORIZE_VPLAN_H
26
27#include "VPlanValue.h"
28#include "llvm/ADT/Bitfields.h"
29#include "llvm/ADT/MapVector.h"
30#include "llvm/ADT/SetVector.h"
33#include "llvm/ADT/Twine.h"
34#include "llvm/ADT/ilist.h"
35#include "llvm/ADT/ilist_node.h"
39#include "llvm/IR/Attributes.h"
40#include "llvm/IR/DebugLoc.h"
41#include "llvm/IR/FMF.h"
42#include "llvm/IR/Operator.h"
46#include <cassert>
47#include <cstddef>
48#include <functional>
49#include <optional>
50#include <string>
51#include <utility>
52#include <variant>
53
54namespace llvm {
55
56class BasicBlock;
57class DominatorTree;
58struct VPTransformState;
59class raw_ostream;
60class SCEV;
61class SCEVPredicate;
62class Type;
63class VPBasicBlock;
65template <typename InserterTy = VPBuilderDefaultInserter> class VPBuilderBase;
67class VPDominatorTree;
68class VPRegionBlock;
69class VPlan;
71class Value;
73
74struct VPCostContext;
75
76using VPlanPtr = std::unique_ptr<VPlan>;
77
78/// \enum UncountableExitStyle
79/// Different methods of handling early exits.
80///
82 /// No side effects to worry about, so we can process any uncountable exits
83 /// in the loop and branch either to the middle block if the trip count was
84 /// reached, or an early exitblock to determine which exit was taken.
86 /// All memory operations other than the load(s) required to determine whether
87 /// an uncountable exit occurre will be masked based on that condition. If an
88 /// uncountable exit is taken, then all lanes before the exiting lane will
89 /// complete, leaving just the final lane to execute in the scalar tail.
91};
92
93/// VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
94/// A VPBlockBase can be either a VPBasicBlock or a VPRegionBlock.
96 friend class VPBlockUtils;
97
98protected:
99 /// An enumeration for keeping track of the concrete subclass of VPBlockBase
100 /// that are actually instantiated. Values of this enumeration are kept in the
101 /// SubclassID field of the VPBlockBase objects. They are used for concrete
102 /// type identification.
103 using VPBlockTy = enum : unsigned char {
104 VPRegionBlockSC,
105 VPBasicBlockSC,
106 VPIRBasicBlockSC
107 };
108
109private:
110 /// An optional name for the block.
111 std::string Name;
112
113 /// The immediate VPRegionBlock which this VPBlockBase belongs to, or null if
114 /// it is a topmost VPBlockBase.
115 VPRegionBlock *Parent = nullptr;
116
117 /// List of predecessor blocks.
119
120 /// List of successor blocks.
122
123 /// VPlan containing the block. Set when the block is created via VPlan
124 /// helpers.
125 VPlan *Plan = nullptr;
126
127 /// Subclass identifier (for isa/dyn_cast).
128 const VPBlockTy SubclassID;
129
130 /// Unique number, used as node number in the dominator tree.
131 unsigned Number;
132
133 /// Add \p Successor as the last successor to this block.
134 void appendSuccessor(VPBlockBase *Successor) {
135 assert(Successor && "Cannot add nullptr successor!");
136 Successors.push_back(Successor);
137 }
138
139 /// Add \p Predecessor as the last predecessor to this block.
140 void appendPredecessor(VPBlockBase *Predecessor) {
141 assert(Predecessor && "Cannot add nullptr predecessor!");
142 Predecessors.push_back(Predecessor);
143 }
144
145 /// Remove \p Predecessor from the predecessors of this block.
146 void removePredecessor(VPBlockBase *Predecessor) {
147 auto Pos = find(Predecessors, Predecessor);
148 assert(Pos && "Predecessor does not exist");
149 Predecessors.erase(Pos);
150 }
151
152 /// Remove \p Successor from the successors of this block.
153 void removeSuccessor(VPBlockBase *Successor) {
154 auto Pos = find(Successors, Successor);
155 assert(Pos && "Successor does not exist");
156 Successors.erase(Pos);
157 }
158
159 /// This function replaces one predecessor with another, useful when
160 /// trying to replace an old block in the CFG with a new one.
161 void replacePredecessor(VPBlockBase *Old, VPBlockBase *New) {
162 auto I = find(Predecessors, Old);
163 assert(I != Predecessors.end());
164 assert(Old->getParent() == New->getParent() &&
165 "replaced predecessor must have the same parent");
166 *I = New;
167 }
168
169 /// This function replaces one successor with another, useful when
170 /// trying to replace an old block in the CFG with a new one.
171 void replaceSuccessor(VPBlockBase *Old, VPBlockBase *New) {
172 auto I = find(Successors, Old);
173 assert(I != Successors.end());
174 assert(Old->getParent() == New->getParent() &&
175 "replaced successor must have the same parent");
176 *I = New;
177 }
178
179public:
181
182 virtual ~VPBlockBase() = default;
183
184 const std::string &getName() const { return Name; }
185
186 void setName(const Twine &newName) { Name = newName.str(); }
187
188 /// \return an ID for the concrete type of this object.
189 /// This is used to implement the classof checks. This should not be used
190 /// for any other purpose, as the values may change as LLVM evolves.
191 unsigned getVPBlockID() const { return SubclassID; }
192
193 VPRegionBlock *getParent() { return Parent; }
194 const VPRegionBlock *getParent() const { return Parent; }
195
196 /// \return A pointer to the plan containing the current block.
197 VPlan *getPlan() { return Plan; }
198 const VPlan *getPlan() const { return Plan; }
199
200 /// Sets the pointer of the plan containing the block.
201 void setPlan(VPlan *ParentPlan) { Plan = ParentPlan; }
202
203 void setParent(VPRegionBlock *P) { Parent = P; }
204
205 /// \return the VPBasicBlock that is the entry of this VPBlockBase,
206 /// recursively, if the latter is a VPRegionBlock. Otherwise, if this
207 /// VPBlockBase is a VPBasicBlock, it is returned.
208 const VPBasicBlock *getEntryBasicBlock() const;
209 VPBasicBlock *getEntryBasicBlock();
210
211 /// \return the VPBasicBlock that is the exiting this VPBlockBase,
212 /// recursively, if the latter is a VPRegionBlock. Otherwise, if this
213 /// VPBlockBase is a VPBasicBlock, it is returned.
214 const VPBasicBlock *getExitingBasicBlock() const;
215 VPBasicBlock *getExitingBasicBlock();
216
217 const VPBlocksTy &getSuccessors() const { return Successors; }
218 VPBlocksTy &getSuccessors() { return Successors; }
219
220 /// Returns true if this block has any successors.
221 bool hasSuccessors() const { return !Successors.empty(); }
222 /// Returns true if this block has any predecessors.
223 bool hasPredecessors() const { return !Predecessors.empty(); }
224
227
228 const VPBlocksTy &getPredecessors() const { return Predecessors; }
229 VPBlocksTy &getPredecessors() { return Predecessors; }
230
231 /// \return the successor of this VPBlockBase if it has a single successor.
232 /// Otherwise return a null pointer.
234 return (Successors.size() == 1 ? *Successors.begin() : nullptr);
235 }
236
237 /// \return the predecessor of this VPBlockBase if it has a single
238 /// predecessor. Otherwise return a null pointer.
240 return (Predecessors.size() == 1 ? *Predecessors.begin() : nullptr);
241 }
242
243 size_t getNumSuccessors() const { return Successors.size(); }
244 size_t getNumPredecessors() const { return Predecessors.size(); }
245
246 /// An Enclosing Block of a block B is any block containing B, including B
247 /// itself. \return the closest enclosing block starting from "this", which
248 /// has successors. \return the root enclosing block if all enclosing blocks
249 /// have no successors.
250 VPBlockBase *getEnclosingBlockWithSuccessors();
251
252 /// \return the closest enclosing block starting from "this", which has
253 /// predecessors. \return the root enclosing block if all enclosing blocks
254 /// have no predecessors.
255 VPBlockBase *getEnclosingBlockWithPredecessors();
256
257 /// \return the successors either attached directly to this VPBlockBase or, if
258 /// this VPBlockBase is the exit block of a VPRegionBlock and has no
259 /// successors of its own, search recursively for the first enclosing
260 /// VPRegionBlock that has successors and return them. If no such
261 /// VPRegionBlock exists, return the (empty) successors of the topmost
262 /// VPBlockBase reached.
264 return getEnclosingBlockWithSuccessors()->getSuccessors();
265 }
266
267 /// \return the hierarchical predecessor of this VPBlockBase if it has a
268 /// single hierarchical predecessor. Otherwise return a null pointer.
272
273 /// Set a given VPBlockBase \p Successor as the single successor of this
274 /// VPBlockBase. This VPBlockBase is not added as predecessor of \p Successor.
275 /// This VPBlockBase must have no successors.
277 assert(Successors.empty() && "Setting one successor when others exist.");
278 assert(Successor->getParent() == getParent() &&
279 "connected blocks must have the same parent");
280 appendSuccessor(Successor);
281 }
282
283 /// Set two given VPBlockBases \p IfTrue and \p IfFalse to be the two
284 /// successors of this VPBlockBase. This VPBlockBase is not added as
285 /// predecessor of \p IfTrue or \p IfFalse. This VPBlockBase must have no
286 /// successors.
287 void setTwoSuccessors(VPBlockBase *IfTrue, VPBlockBase *IfFalse) {
288 assert(Successors.empty() && "Setting two successors when others exist.");
289 appendSuccessor(IfTrue);
290 appendSuccessor(IfFalse);
291 }
292
293 /// Set each VPBasicBlock in \p NewPreds as predecessor of this VPBlockBase.
294 /// This VPBlockBase must have no predecessors. This VPBlockBase is not added
295 /// as successor of any VPBasicBlock in \p NewPreds.
297 assert(Predecessors.empty() && "Block predecessors already set.");
298 for (auto *Pred : NewPreds)
299 appendPredecessor(Pred);
300 }
301
302 /// Set each VPBasicBlock in \p NewSuccss as successor of this VPBlockBase.
303 /// This VPBlockBase must have no successors. This VPBlockBase is not added
304 /// as predecessor of any VPBasicBlock in \p NewSuccs.
306 assert(Successors.empty() && "Block successors already set.");
307 for (auto *Succ : NewSuccs)
308 appendSuccessor(Succ);
309 }
310
311 /// Remove all the predecessor of this block.
312 void clearPredecessors() { Predecessors.clear(); }
313
314 /// Remove all the successors of this block.
315 void clearSuccessors() { Successors.clear(); }
316
317 /// Swap predecessors of the block. The block must have exactly 2
318 /// predecessors.
320 assert(Predecessors.size() == 2 && "must have 2 predecessors to swap");
321 std::swap(Predecessors[0], Predecessors[1]);
322 }
323
324 /// Swap successors of the block. The block must have exactly 2 successors.
325 // TODO: This should be part of introducing conditional branch recipes rather
326 // than being independent.
328 assert(Successors.size() == 2 && "must have 2 successors to swap");
329 std::swap(Successors[0], Successors[1]);
330 }
331
332 /// Returns the index for \p Pred in the blocks predecessors list.
333 unsigned getIndexForPredecessor(const VPBlockBase *Pred) const {
334 assert(count(Predecessors, Pred) == 1 &&
335 "must have Pred exactly once in Predecessors");
336 return std::distance(Predecessors.begin(), find(Predecessors, Pred));
337 }
338
339 /// Returns the index for \p Succ in the blocks successor list.
340 unsigned getIndexForSuccessor(const VPBlockBase *Succ) const {
341 assert(count(Successors, Succ) == 1 &&
342 "must have Succ exactly once in Successors");
343 return std::distance(Successors.begin(), find(Successors, Succ));
344 }
345
346 /// Return the unique number of the block.
347 unsigned getNumber() const { return Number; }
348
349 /// Set the unique number of the block, used for dominator tree.
350 void setNumber(unsigned N) { Number = N; }
351
352 /// The method which generates the output IR that correspond to this
353 /// VPBlockBase, thereby "executing" the VPlan.
354 virtual void execute(VPTransformState *State) = 0;
355
356 /// Return the cost of the block.
358
359 void printAsOperand(raw_ostream &OS, bool PrintType = false) const {
360 OS << getName();
361 }
362
363#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
364 /// Print plain-text dump of this VPBlockBase to \p O, prefixing all lines
365 /// with \p Indent. \p SlotTracker is used to print unnamed VPValue's using
366 /// consequtive numbers.
367 ///
368 /// Note that the numbering is applied to the whole VPlan, so printing
369 /// individual blocks is consistent with the whole VPlan printing.
370 virtual void print(raw_ostream &O, const Twine &Indent,
371 VPSlotTracker &SlotTracker) const = 0;
372
373 /// Print plain-text dump of this VPlan to \p O.
374 void print(raw_ostream &O) const;
375
376 /// Print the successors of this block to \p O, prefixing all lines with \p
377 /// Indent.
378 void printSuccessors(raw_ostream &O, const Twine &Indent) const;
379
380 /// Dump this VPBlockBase to dbgs().
381 LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
382#endif
383
384 /// Clone the current block and it's recipes without updating the operands of
385 /// the cloned recipes, including all blocks in the single-entry single-exit
386 /// region for VPRegionBlocks.
387 virtual VPBlockBase *clone() = 0;
388
389protected:
390 VPBlockBase(VPBlockTy SC, const std::string &N) : Name(N), SubclassID(SC) {}
391};
392
393/// VPRecipeBase is a base class modeling a sequence of one or more output IR
394/// instructions. VPRecipeBase owns the VPValues it defines through VPDef
395/// and is responsible for deleting its defined values. Single-value
396/// recipes must inherit from VPSingleDef instead of inheriting from both
397/// VPRecipeBase and VPValue separately.
399 : public ilist_node_with_parent<VPRecipeBase, VPBasicBlock,
400 ilist_parent<VPBasicBlock>>,
401 public VPDef,
402 public VPUser {
403 friend VPBasicBlock;
404 friend class VPBlockUtils;
405
406 /// The debug location for the recipe.
407 DebugLoc DL;
408
409public:
410 /// An enumeration for keeping track of the concrete subclass of VPRecipeBase
411 /// that is actually instantiated. Values of this enumeration are kept in the
412 /// SubclassID field of the VPRecipeBase objects. They are used for concrete
413 /// type identification.
414 using VPRecipeTy = enum : unsigned char {
415 VPBranchOnMaskSC,
416 VPDerivedIVSC,
417 VPExpandSCEVSC,
418 VPExpressionSC,
419 VPIRInstructionSC,
420 VPInstructionSC,
421 VPInterleaveEVLSC,
422 VPInterleaveSC,
423 VPReductionEVLSC,
424 VPReductionSC,
425 VPReplicateSC,
426 VPScalarIVStepsSC,
427 VPVectorPointerSC,
428 VPVectorEndPointerSC,
429 VPWidenCallSC,
430 VPWidenCanonicalIVSC,
431 VPWidenCastSC,
432 VPWidenGEPSC,
433 VPWidenIntrinsicSC,
434 VPWidenMemIntrinsicSC,
435 VPWidenLoadEVLSC,
436 VPWidenLoadSC,
437 VPWidenStoreEVLSC,
438 VPWidenStoreSC,
439 VPWidenSC,
440 VPBlendSC,
441 VPHistogramSC,
442 // START: Phi-like recipes. Need to be kept together.
443 VPWidenPHISC,
444 VPPredInstPHISC,
445 // START: SubclassID for recipes that inherit VPHeaderPHIRecipe.
446 // VPHeaderPHIRecipe need to be kept together.
447 VPCurrentIterationPHISC,
448 VPActiveLaneMaskPHISC,
449 VPFirstOrderRecurrencePHISC,
450 VPWidenIntOrFpInductionSC,
451 VPWidenPointerInductionSC,
452 VPReductionPHISC,
453 VPConditionalInductionPHISC,
454 // END: SubclassID for recipes that inherit VPHeaderPHIRecipe
455 // END: Phi-like recipes
456 VPFirstPHISC = VPWidenPHISC,
457 VPFirstHeaderPHISC = VPCurrentIterationPHISC,
458 VPLastHeaderPHISC = VPConditionalInductionPHISC,
459 VPLastPHISC = VPConditionalInductionPHISC,
460 };
461
464 : VPDef(), VPUser(Operands), DL(DL), SubclassID(SC) {}
465
466 ~VPRecipeBase() override = default;
467
468 /// Clone the current recipe.
469 virtual VPRecipeBase *clone() = 0;
470
471 /// The list type holding the recipes of a VPBasicBlock. Each node, including
472 /// the sentinel, stores its parent VPBasicBlock.
474
475 /// \return the VPRegionBlock which the recipe belongs to.
477 const VPRegionBlock *getRegion() const;
478
479 /// The method which generates the output IR instructions that correspond to
480 /// this VPRecipe, thereby "executing" the VPlan.
481 virtual void execute(VPTransformState &State) = 0;
482
483 /// Return the cost of this recipe, taking into account if the cost
484 /// computation should be skipped and the ForceTargetInstructionCost flag.
485 /// Also takes care of printing the cost for debugging.
487
488 /// Insert an unlinked recipe into a basic block immediately before
489 /// the specified recipe.
490 void insertBefore(VPRecipeBase *InsertPos);
491 /// Insert an unlinked recipe immediately before the insertion point \p IP.
493
494 /// Insert an unlinked Recipe into a basic block immediately after
495 /// the specified Recipe.
496 void insertAfter(VPRecipeBase *InsertPos);
497
498 /// Unlink this recipe from its current VPBasicBlock and insert it into
499 /// the VPBasicBlock that MovePos lives in, right after MovePos.
500 void moveAfter(VPRecipeBase *MovePos);
501
502 /// Unlink this recipe and insert it before \p I.
504
505 /// This method unlinks 'this' from the containing basic block, but does not
506 /// delete it.
507 void removeFromParent();
508
509 /// This method unlinks 'this' from the containing basic block and deletes it.
510 ///
511 /// \returns an iterator pointing to the element after the erased one
513
514 /// \return an ID for the concrete type of this object.
515 VPRecipeTy getVPRecipeID() const { return SubclassID; }
516
517 /// Method to support type inquiry through isa, cast, and dyn_cast.
518 static inline bool classof(const VPDef *D) {
519 // All VPDefs are also VPRecipeBases.
520 return true;
521 }
522
523 static inline bool classof(const VPUser *U) { return true; }
524
525 /// Returns true if the recipe may have side-effects.
526 bool mayHaveSideEffects() const;
527
528 /// Return true if we can safely execute this recipe unconditionally even if
529 /// it is masked originally.
530 bool isSafeToSpeculativelyExecute() const;
531
532 /// Returns true for PHI-like recipes.
533 bool isPhi() const;
534
535 /// Returns true if the recipe may read from memory.
536 bool mayReadFromMemory() const;
537
538 /// Returns true if the recipe may write to memory.
539 bool mayWriteToMemory() const;
540
541 /// Returns true if the recipe may read from or write to memory.
542 bool mayReadOrWriteMemory() const {
544 }
545
546 /// Returns the debug location of the recipe.
547 DebugLoc getDebugLoc() const { return DL; }
548
549 /// Set the recipe's debug location to \p NewDL.
550 void setDebugLoc(DebugLoc NewDL) { DL = NewDL; }
551
552#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
553 /// Dump the recipe to stderr (for debugging).
554 void dump() const;
555
556 /// Print the recipe, delegating to printRecipe().
557 void print(raw_ostream &O, const Twine &Indent,
559#endif
560
561private:
562 /// Subclass identifier (for isa/dyn_cast).
563 const VPRecipeTy SubclassID;
564
565protected:
566 /// Compute the cost of this recipe either using a recipe's specialized
567 /// implementation or using the legacy cost model and the underlying
568 /// instructions.
569 virtual InstructionCost computeCost(ElementCount VF,
570 VPCostContext &Ctx) const;
571
572#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
573 /// Each concrete VPRecipe prints itself, without printing common information,
574 /// like debug info or metadata.
575 virtual void printRecipe(raw_ostream &O, const Twine &Indent,
576 VPSlotTracker &SlotTracker) const = 0;
577#endif
578};
579
580// Helper macro to define common classof implementations for recipes.
581#define VP_CLASSOF_IMPL(VPRecipeID) \
582 static inline bool classof(const VPRecipeBase *R) { \
583 return R->getVPRecipeID() == VPRecipeID; \
584 } \
585 static inline bool classof(const VPValue *V) { \
586 auto *R = V->getDefiningRecipe(); \
587 return R && R->getVPRecipeID() == VPRecipeID; \
588 } \
589 static inline bool classof(const VPUser *U) { \
590 auto *R = dyn_cast<VPRecipeBase>(U); \
591 return R && R->getVPRecipeID() == VPRecipeID; \
592 } \
593 static inline bool classof(const VPSingleDefRecipe *R) { \
594 return R->getVPRecipeID() == VPRecipeID; \
595 }
596
597/// Compute the scalar result type for an IR \p Opcode given \p Operands.
598LLVM_ABI Type *computeScalarTypeForInstruction(unsigned Opcode,
600
601/// VPSingleDefRecipe is a base class for recipes that model a sequence of one
602/// or more output IR that define a single result VPValue. Note that
603/// VPSingleDefRecipe must inherit from VPRecipeBase before VPSingleDefValue.
605 public VPSingleDefValue {
606public:
608 Value *UV = nullptr, DebugLoc DL = DebugLoc::getUnknown())
609 : VPRecipeBase(SC, Operands, DL), VPSingleDefValue(this, UV, ResultTy) {}
610
611 static inline bool classof(const VPRecipeBase *R) {
612 switch (R->getVPRecipeID()) {
613 case VPRecipeBase::VPDerivedIVSC:
614 case VPRecipeBase::VPExpandSCEVSC:
615 case VPRecipeBase::VPExpressionSC:
616 case VPRecipeBase::VPInstructionSC:
617 case VPRecipeBase::VPReductionEVLSC:
618 case VPRecipeBase::VPReductionSC:
619 case VPRecipeBase::VPReplicateSC:
620 case VPRecipeBase::VPScalarIVStepsSC:
621 case VPRecipeBase::VPVectorPointerSC:
622 case VPRecipeBase::VPVectorEndPointerSC:
623 case VPRecipeBase::VPWidenCallSC:
624 case VPRecipeBase::VPWidenCanonicalIVSC:
625 case VPRecipeBase::VPWidenCastSC:
626 case VPRecipeBase::VPWidenGEPSC:
627 case VPRecipeBase::VPWidenIntrinsicSC:
628 case VPRecipeBase::VPWidenMemIntrinsicSC:
629 case VPRecipeBase::VPWidenSC:
630 case VPRecipeBase::VPBlendSC:
631 case VPRecipeBase::VPPredInstPHISC:
632 case VPRecipeBase::VPCurrentIterationPHISC:
633 case VPRecipeBase::VPActiveLaneMaskPHISC:
634 case VPRecipeBase::VPFirstOrderRecurrencePHISC:
635 case VPRecipeBase::VPWidenPHISC:
636 case VPRecipeBase::VPWidenIntOrFpInductionSC:
637 case VPRecipeBase::VPWidenPointerInductionSC:
638 case VPRecipeBase::VPReductionPHISC:
639 case VPRecipeBase::VPWidenLoadEVLSC:
640 case VPRecipeBase::VPWidenLoadSC:
641 case VPRecipeBase::VPConditionalInductionPHISC:
642 return true;
643 case VPRecipeBase::VPBranchOnMaskSC:
644 case VPRecipeBase::VPInterleaveEVLSC:
645 case VPRecipeBase::VPInterleaveSC:
646 case VPRecipeBase::VPIRInstructionSC:
647 case VPRecipeBase::VPWidenStoreEVLSC:
648 case VPRecipeBase::VPWidenStoreSC:
649 case VPRecipeBase::VPHistogramSC:
650 return false;
651 }
652 llvm_unreachable("Unhandled VPRecipeID");
653 }
654
655 static inline bool classof(const VPValue *V) {
656 auto *R = V->getDefiningRecipe();
657 return R && classof(R);
658 }
659
660 static inline bool classof(const VPUser *U) {
661 auto *R = dyn_cast<VPRecipeBase>(U);
662 return R && classof(R);
663 }
664
665 VPSingleDefRecipe *clone() override = 0;
666
667 /// Returns the underlying instruction.
674
675#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
676 /// Print this VPSingleDefRecipe to dbgs() (for debugging).
677 LLVM_DUMP_METHOD void dump() const;
678#endif
679};
680
681/// Class to record and manage LLVM IR flags.
684 enum class OperationType : unsigned char {
685 Cmp,
686 FCmp,
687 OverflowingBinOp,
688 Trunc,
689 DisjointOp,
690 PossiblyExactOp,
691 GEPOp,
692 FPMathOp,
693 NonNegOp,
694 ReductionOp,
695 Other
696 };
697
698public:
699 struct WrapFlagsTy {
700 char HasNUW : 1;
701 char HasNSW : 1;
702
706 return {static_cast<bool>(HasNUW), false};
707 }
708 };
709
711 char HasNUW : 1;
712 char HasNSW : 1;
713
715 };
716
721
723 char NonNeg : 1;
724 NonNegFlagsTy(bool IsNonNeg) : NonNeg(IsNonNeg) {}
725 };
726
727private:
728 struct ExactFlagsTy {
729 char IsExact : 1;
730 ExactFlagsTy(bool Exact) : IsExact(Exact) {}
731 };
732 struct FastMathFlagsTy {
733 char AllowReassoc : 1;
734 char NoNaNs : 1;
735 char NoInfs : 1;
736 char NoSignedZeros : 1;
737 char AllowReciprocal : 1;
738 char AllowContract : 1;
739 char ApproxFunc : 1;
740
741 LLVM_ABI_FOR_TEST FastMathFlagsTy(const FastMathFlags &FMF);
742 };
743 /// Holds both the predicate and fast-math flags for floating-point
744 /// comparisons.
745 struct FCmpFlagsTy {
746 uint8_t CmpPredStorage;
747 FastMathFlagsTy FMFs;
748 };
749 /// Holds reduction-specific flags: RecurKind, IsOrdered, IsInLoop, and FMFs.
750 struct ReductionFlagsTy {
751 // RecurKind has ~26 values, needs 5 bits but uses 6 bits to account for
752 // additional kinds.
753 unsigned char Kind : 6;
754 // TODO: Derive order/in-loop from plan and remove here.
755 unsigned char IsOrdered : 1;
756 unsigned char IsInLoop : 1;
757 FastMathFlagsTy FMFs;
758
759 ReductionFlagsTy(RecurKind Kind, bool IsOrdered, bool IsInLoop,
760 FastMathFlags FMFs)
761 : Kind(static_cast<unsigned char>(Kind)), IsOrdered(IsOrdered),
762 IsInLoop(IsInLoop), FMFs(FMFs) {}
763 };
764
765 OperationType OpType;
766
767 union {
772 ExactFlagsTy ExactFlags;
775 FastMathFlagsTy FMFs;
776 FCmpFlagsTy FCmpFlags;
777 ReductionFlagsTy ReductionFlags;
779 };
780
781public:
782 VPIRFlags() : OpType(OperationType::Other), AllFlags() {}
783
785 if (auto *FCmp = dyn_cast<FCmpInst>(&I)) {
786 OpType = OperationType::FCmp;
788 FCmp->getPredicate());
789 assert(getPredicate() == FCmp->getPredicate() && "predicate truncated");
790 FCmpFlags.FMFs = FCmp->getFastMathFlags();
791 } else if (auto *Op = dyn_cast<CmpInst>(&I)) {
792 OpType = OperationType::Cmp;
794 Op->getPredicate());
795 assert(getPredicate() == Op->getPredicate() && "predicate truncated");
796 } else if (auto *Op = dyn_cast<PossiblyDisjointInst>(&I)) {
797 OpType = OperationType::DisjointOp;
798 DisjointFlags.IsDisjoint = Op->isDisjoint();
799 } else if (auto *Op = dyn_cast<OverflowingBinaryOperator>(&I)) {
800 OpType = OperationType::OverflowingBinOp;
801 WrapFlags = {Op->hasNoUnsignedWrap(), Op->hasNoSignedWrap()};
802 } else if (auto *Op = dyn_cast<TruncInst>(&I)) {
803 OpType = OperationType::Trunc;
804 TruncFlags = {Op->hasNoUnsignedWrap(), Op->hasNoSignedWrap()};
805 } else if (auto *Op = dyn_cast<PossiblyExactOperator>(&I)) {
806 OpType = OperationType::PossiblyExactOp;
807 ExactFlags.IsExact = Op->isExact();
808 } else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
809 OpType = OperationType::GEPOp;
810 GEPFlagsStorage = GEP->getNoWrapFlags().getRaw();
811 assert(getGEPNoWrapFlags() == GEP->getNoWrapFlags() &&
812 "wrap flags truncated");
813 } else if (auto *PNNI = dyn_cast<PossiblyNonNegInst>(&I)) {
814 OpType = OperationType::NonNegOp;
815 NonNegFlags.NonNeg = PNNI->hasNonNeg();
816 } else if (auto *Op = dyn_cast<FPMathOperator>(&I)) {
817 OpType = OperationType::FPMathOp;
818 FMFs = Op->getFastMathFlags();
819 }
820 }
821
822 VPIRFlags(CmpInst::Predicate Pred) : OpType(OperationType::Cmp), AllFlags() {
824 assert(getPredicate() == Pred && "predicate truncated");
825 }
826
828 : OpType(OperationType::FCmp), AllFlags() {
830 assert(getPredicate() == Pred && "predicate truncated");
831 FCmpFlags.FMFs = FMFs;
832 }
833
835 : OpType(OperationType::OverflowingBinOp), AllFlags() {
836 this->WrapFlags = WrapFlags;
837 }
838
840 : OpType(OperationType::Trunc), AllFlags() {
841 this->TruncFlags = TruncFlags;
842 }
843
844 VPIRFlags(FastMathFlags FMFs) : OpType(OperationType::FPMathOp), AllFlags() {
845 this->FMFs = FMFs;
846 }
847
849 : OpType(OperationType::DisjointOp), AllFlags() {
850 this->DisjointFlags = DisjointFlags;
851 }
852
854 : OpType(OperationType::NonNegOp), AllFlags() {
855 this->NonNegFlags = NonNegFlags;
856 }
857
858 VPIRFlags(ExactFlagsTy ExactFlags)
859 : OpType(OperationType::PossiblyExactOp), AllFlags() {
860 this->ExactFlags = ExactFlags;
861 }
862
864 : OpType(OperationType::GEPOp), AllFlags() {
865 GEPFlagsStorage = GEPFlags.getRaw();
866 }
867
868 VPIRFlags(RecurKind Kind, bool IsOrdered, bool IsInLoop, FastMathFlags FMFs)
869 : OpType(OperationType::ReductionOp), AllFlags() {
870 ReductionFlags = ReductionFlagsTy(Kind, IsOrdered, IsInLoop, FMFs);
871 }
872
873 /// Only keep flags also present in \p Other. \p Other must have the same
874 /// OpType as the current object.
875 void intersectFlags(const VPIRFlags &Other);
876
877 /// Drop all poison-generating flags.
879 // NOTE: This needs to be kept in-sync with
880 // Instruction::dropPoisonGeneratingFlags.
881 switch (OpType) {
882 case OperationType::OverflowingBinOp:
883 WrapFlags.HasNUW = false;
884 WrapFlags.HasNSW = false;
885 break;
886 case OperationType::Trunc:
887 TruncFlags.HasNUW = false;
888 TruncFlags.HasNSW = false;
889 break;
890 case OperationType::DisjointOp:
891 DisjointFlags.IsDisjoint = false;
892 break;
893 case OperationType::PossiblyExactOp:
894 ExactFlags.IsExact = false;
895 break;
896 case OperationType::GEPOp:
897 GEPFlagsStorage = 0;
898 break;
899 case OperationType::FPMathOp:
900 case OperationType::FCmp:
901 case OperationType::ReductionOp:
902 getFMFsRef().NoNaNs = false;
903 getFMFsRef().NoInfs = false;
904 break;
905 case OperationType::NonNegOp:
906 NonNegFlags.NonNeg = false;
907 break;
908 case OperationType::Cmp:
909 case OperationType::Other:
910 break;
911 }
912 }
913
914 /// Apply the IR flags to \p I.
915 void applyFlags(Instruction &I) const {
916 switch (OpType) {
917 case OperationType::OverflowingBinOp:
918 I.setHasNoUnsignedWrap(WrapFlags.HasNUW);
919 I.setHasNoSignedWrap(WrapFlags.HasNSW);
920 break;
921 case OperationType::Trunc:
922 I.setHasNoUnsignedWrap(TruncFlags.HasNUW);
923 I.setHasNoSignedWrap(TruncFlags.HasNSW);
924 break;
925 case OperationType::DisjointOp:
926 cast<PossiblyDisjointInst>(&I)->setIsDisjoint(DisjointFlags.IsDisjoint);
927 break;
928 case OperationType::PossiblyExactOp:
929 I.setIsExact(ExactFlags.IsExact);
930 break;
931 case OperationType::GEPOp:
932 cast<GetElementPtrInst>(&I)->setNoWrapFlags(
934 break;
935 case OperationType::FPMathOp:
936 case OperationType::FCmp:
937 I.copyFastMathFlags(getFastMathFlagsOrNone());
938 break;
939 case OperationType::NonNegOp:
940 I.setNonNeg(NonNegFlags.NonNeg);
941 break;
942 case OperationType::ReductionOp:
943 llvm_unreachable("reduction ops should not use applyFlags");
944 case OperationType::Cmp:
945 case OperationType::Other:
946 break;
947 }
948 }
949
951 assert((OpType == OperationType::Cmp || OpType == OperationType::FCmp) &&
952 "recipe doesn't have a compare predicate");
953 uint8_t Storage = OpType == OperationType::FCmp ? FCmpFlags.CmpPredStorage
956 }
957
959 assert((OpType == OperationType::Cmp || OpType == OperationType::FCmp) &&
960 "recipe doesn't have a compare predicate");
961 if (OpType == OperationType::FCmp)
963 else
965 assert(getPredicate() == Pred && "predicate truncated");
966 }
967
971
972 /// Returns true if the recipe has a comparison predicate.
973 bool hasPredicate() const {
974 return OpType == OperationType::Cmp || OpType == OperationType::FCmp;
975 }
976
977 /// Returns true if the recipe has fast-math flags.
978 bool hasFastMathFlags() const {
979 return OpType == OperationType::FPMathOp || OpType == OperationType::FCmp ||
980 OpType == OperationType::ReductionOp;
981 }
982
984
985 bool hasNoUnsignedWrap() const {
986 switch (OpType) {
987 case OperationType::OverflowingBinOp:
988 return WrapFlags.HasNUW;
989 case OperationType::Trunc:
990 return TruncFlags.HasNUW;
991 default:
992 llvm_unreachable("recipe doesn't have a NUW flag");
993 }
994 }
995
996 bool hasNoSignedWrap() const {
997 switch (OpType) {
998 case OperationType::OverflowingBinOp:
999 return WrapFlags.HasNSW;
1000 case OperationType::Trunc:
1001 return TruncFlags.HasNSW;
1002 default:
1003 llvm_unreachable("recipe doesn't have a NSW flag");
1004 }
1005 }
1006
1008 switch (OpType) {
1009 case OperationType::OverflowingBinOp:
1010 case OperationType::Trunc:
1011 return {hasNoUnsignedWrap(), hasNoSignedWrap()};
1012 default:
1013 return {};
1014 }
1015 }
1016
1018 return {hasNoUnsignedWrap(), hasNoSignedWrap()};
1019 }
1020
1021 bool isDisjoint() const {
1022 assert(OpType == OperationType::DisjointOp &&
1023 "recipe cannot have a disjoing flag");
1024 return DisjointFlags.IsDisjoint;
1025 }
1026
1028 assert(OpType == OperationType::ReductionOp &&
1029 "recipe doesn't have reduction flags");
1030 return static_cast<RecurKind>(ReductionFlags.Kind);
1031 }
1032
1033 bool isReductionOrdered() const {
1034 assert(OpType == OperationType::ReductionOp &&
1035 "recipe doesn't have reduction flags");
1036 return ReductionFlags.IsOrdered;
1037 }
1038
1039 bool isReductionInLoop() const {
1040 assert(OpType == OperationType::ReductionOp &&
1041 "recipe doesn't have reduction flags");
1042 return ReductionFlags.IsInLoop;
1043 }
1044
1045private:
1046 /// Get a reference to the fast-math flags for FPMathOp, FCmp or ReductionOp.
1047 FastMathFlagsTy &getFMFsRef() {
1048 if (OpType == OperationType::FCmp)
1049 return FCmpFlags.FMFs;
1050 if (OpType == OperationType::ReductionOp)
1051 return ReductionFlags.FMFs;
1052 return FMFs;
1053 }
1054 const FastMathFlagsTy &getFMFsRef() const {
1055 if (OpType == OperationType::FCmp)
1056 return FCmpFlags.FMFs;
1057 if (OpType == OperationType::ReductionOp)
1058 return ReductionFlags.FMFs;
1059 return FMFs;
1060 }
1061
1062public:
1063 /// Returns default flags for \p Opcode and scalar \p ResultTy for opcodes
1064 /// that support it, asserts otherwise. Opcodes not supporting default flags
1065 /// include compares and ComputeReductionResult.
1066 LLVM_ABI_FOR_TEST static VPIRFlags getDefaultFlags(unsigned Opcode,
1067 Type *ResultTy = nullptr);
1068
1069#if !defined(NDEBUG)
1070 /// Returns true if the set flags are valid for \p Opcode.
1071 LLVM_ABI_FOR_TEST bool flagsValidForOpcode(unsigned Opcode) const;
1072
1073 /// Returns true if \p Opcode with scalar result type \p ResultTy has its
1074 /// required flags set.
1075 LLVM_ABI_FOR_TEST bool hasRequiredFlagsForOpcode(unsigned Opcode,
1076 Type *ResultTy) const;
1077#endif
1078
1079#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1080 void printFlags(raw_ostream &O) const;
1081#endif
1082};
1084
1085static_assert(sizeof(VPIRFlags) <= 3, "VPIRFlags should not grow");
1086
1087/// A pure-virtual common base class for recipes defining a single VPValue and
1088/// using IR flags.
1091 Type *ResultTy, const VPIRFlags &Flags,
1093 : VPSingleDefRecipe(SC, Operands, ResultTy, /*UV=*/nullptr, DL),
1094 VPIRFlags(Flags) {}
1095
1096 static inline bool classof(const VPRecipeBase *R) {
1097 return R->getVPRecipeID() == VPRecipeBase::VPBlendSC ||
1098 R->getVPRecipeID() == VPRecipeBase::VPInstructionSC ||
1099 R->getVPRecipeID() == VPRecipeBase::VPWidenSC ||
1100 R->getVPRecipeID() == VPRecipeBase::VPWidenGEPSC ||
1101 R->getVPRecipeID() == VPRecipeBase::VPWidenCallSC ||
1102 R->getVPRecipeID() == VPRecipeBase::VPWidenCastSC ||
1103 R->getVPRecipeID() == VPRecipeBase::VPWidenIntrinsicSC ||
1104 R->getVPRecipeID() == VPRecipeBase::VPWidenMemIntrinsicSC ||
1105 R->getVPRecipeID() == VPRecipeBase::VPReductionSC ||
1106 R->getVPRecipeID() == VPRecipeBase::VPReductionEVLSC ||
1107 R->getVPRecipeID() == VPRecipeBase::VPReplicateSC ||
1108 R->getVPRecipeID() == VPRecipeBase::VPVectorEndPointerSC ||
1109 R->getVPRecipeID() == VPRecipeBase::VPVectorPointerSC ||
1110 R->getVPRecipeID() == VPRecipeBase::VPWidenCanonicalIVSC ||
1111 R->getVPRecipeID() == VPRecipeBase::VPDerivedIVSC;
1112 }
1113
1114 static inline bool classof(const VPUser *U) {
1115 auto *R = dyn_cast<VPRecipeBase>(U);
1116 return R && classof(R);
1117 }
1118
1119 static inline bool classof(const VPValue *V) {
1120 auto *R = V->getDefiningRecipe();
1121 return R && classof(R);
1122 }
1123
1125
1126 static inline bool classof(const VPSingleDefRecipe *R) {
1127 return classof(static_cast<const VPRecipeBase *>(R));
1128 }
1129
1130 void execute(VPTransformState &State) override = 0;
1131
1132 /// Compute the cost for this recipe for \p VF, using \p Opcode and \p Ctx.
1134 VPCostContext &Ctx) const;
1135};
1136
1137/// The frequency with which a recipe executes, relative to the entry of the
1138/// loop region. IsEstimated is set if any branch weight it was composed from
1139/// was estimated from static heuristics.
1142 const bool IsEstimated;
1143
1146 assert(Freq > BlockFrequency() && "execution frequency must be non-zero");
1147 }
1148};
1149
1150/// Helper to manage IR metadata for recipes. It filters out metadata that
1151/// cannot be propagated.
1154
1155 /// Name of the VPlan-internal metadata kind holding the execution frequency.
1156 static constexpr StringLiteral ExecutionFrequencyMDName =
1157 "vplan.execution.frequency";
1158
1159 /// Name of the VPlan-internal metadata kind holding estimated branch weights.
1160 static constexpr StringLiteral EstimatedProfileMDName =
1161 "vplan.prof.estimated";
1162
1163 /// Returns the ID of the metadata kind named \p Kind, taking the context from
1164 /// any attached node; all belong to the context of the VPlan's function.
1165 unsigned getMDKindID(StringRef Kind) const {
1166 assert(!Metadata.empty() && "no node to take the context from");
1167 return Metadata.front().second->getContext().getMDKindID(Kind);
1168 }
1169
1170 /// Returns the node attached under the VPlan-internal metadata kind named
1171 /// \p Kind, or nullptr if there is none.
1172 MDNode *getInternalMetadata(StringRef Kind) const {
1173 return Metadata.empty() ? nullptr : getMetadata(getMDKindID(Kind));
1174 }
1175
1176public:
1177 VPIRMetadata() = default;
1178
1179 /// Adds metatadata that can be preserved from the original instruction
1180 /// \p I.
1182 getMetadataToPropagate(&I, Metadata);
1183 // Retain the branch weights of terminators. They are used to compute the
1184 // frequencies with which the blocks of the original loop execute. Also
1185 // retain !prof on selects.
1186 if (I.isTerminator() || isa<SelectInst>(&I))
1187 if (MDNode *BW = I.getMetadata(LLVMContext::MD_prof))
1188 Metadata.emplace_back(LLVMContext::MD_prof, BW);
1189 }
1190
1191 /// Copy constructor for cloning.
1193
1195
1196 /// Add all metadata to \p I.
1197 void applyMetadata(Instruction &I) const;
1198
1199 /// Set metadata with kind \p Kind to \p Node. If metadata with \p Kind
1200 /// already exists, it will be replaced. Otherwise, it will be added.
1201 void setMetadata(unsigned Kind, MDNode *Node) {
1202 auto It =
1203 llvm::find_if(Metadata, [Kind](const std::pair<unsigned, MDNode *> &P) {
1204 return P.first == Kind;
1205 });
1206 if (It != Metadata.end())
1207 It->second = Node;
1208 else
1209 Metadata.emplace_back(Kind, Node);
1210 }
1211
1212 /// Remove the metadata of kind \p Kind, if present.
1213 void eraseMetadata(unsigned Kind) {
1214 erase_if(Metadata, [Kind](const auto &P) { return P.first == Kind; });
1215 }
1216
1217 /// Intersect this VPIRMetadata object with \p MD, keeping only metadata
1218 /// nodes that are common to both.
1219 void intersect(const VPIRMetadata &MD);
1220
1221 /// Get metadata of kind \p Kind. Returns nullptr if not found.
1222 MDNode *getMetadata(unsigned Kind) const {
1223 auto It =
1224 find_if(Metadata, [Kind](const auto &P) { return P.first == Kind; });
1225 return It != Metadata.end() ? It->second : nullptr;
1226 }
1227
1228 /// Record that the recipe executes with frequency \p Freq, relative to the
1229 /// entry of the loop region.
1230 void setExecutionFrequency(std::optional<VPExecutionFrequency> Freq,
1231 LLVMContext &Ctx);
1232
1233 /// Returns the frequency recorded by setExecutionFrequency, if any.
1234 std::optional<VPExecutionFrequency> getExecutionFrequency() const;
1235
1236 /// Drop the frequency recorded by setExecutionFrequency, if any.
1237 void clearExecutionFrequency();
1238
1239 /// Returns the branch weights recorded for this terminator, preferring real
1240 /// profile data over an estimate, or nullptr if there are none.
1242 MDNode *Node = getMetadata(LLVMContext::MD_prof);
1243 return Node ? Node : getInternalMetadata(EstimatedProfileMDName);
1244 }
1245
1246 /// Returns true if the weights returned by getBranchWeights are estimated.
1248 return getInternalMetadata(EstimatedProfileMDName);
1249 }
1250
1251 /// Set estimated branch weights to \p Node.
1253 assert(!getMetadata(LLVMContext::MD_prof) &&
1254 "real profile data takes precedence over an estimate");
1255 setMetadata(Node->getContext().getMDKindID(EstimatedProfileMDName), Node);
1256 }
1257
1258#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1259 /// Print metadata with node IDs.
1260 void print(raw_ostream &O, VPSlotTracker &SlotTracker) const;
1261#endif
1262};
1263
1264class VPInstruction;
1265
1266/// Manage IR attributes for call recipes. Call VPInstructions store all
1267/// call-site attributes. Widened calls only store return and per-argument
1268/// attributes that are valid to propagate to the widened call.
1270 AttributeList CallAttrs;
1271
1272public:
1273 VPIRAttributes() = default;
1274
1275 explicit VPIRAttributes(AttributeList CallAttrs) : CallAttrs(CallAttrs) {}
1276
1277 /// Stores the return and per-arg attributes of the call VPInstruction \p
1278 /// Call that are valid for a widened call with type \p WideTy. If \p Call is
1279 /// masked, the scalar call only executes for some lanes, so argument
1280 /// attributes are only kept for widened arguments passed to a masked variant.
1282
1283 /// Keep only the attributes valid for both this and \p Other.
1285
1286 /// Apply the stored attributes to the widened call \p WideCall.
1287 void applyAttrs(CallInst &WideCall) const {
1288 WideCall.setAttributes(CallAttrs);
1289 }
1290
1291 /// Returns the memory effects of a call with these attributes to a callee
1292 /// with function attributes \p CalleeFnAttrs.
1294 return CallAttrs.getMemoryEffects() & CalleeFnAttrs.getMemoryEffects();
1295 }
1296
1297 /// Returns true if the call site or \p CalleeFnAttrs has \p Kind.
1298 bool hasFnAttr(Attribute::AttrKind Kind, AttributeSet CalleeFnAttrs) const {
1299 return CallAttrs.hasFnAttr(Kind) || CalleeFnAttrs.hasAttribute(Kind);
1300 }
1301
1302#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1303 /// Print return-value attributes carried with this object.
1304 void printRetAttrs(raw_ostream &O) const;
1305
1306 /// Print per-arg attributes for argument \p ArgIdx.
1307 void printParamAttrs(raw_ostream &O, unsigned ArgIdx) const;
1308
1309 /// Print function attributes carried with this object.
1310 void printFnAttrs(raw_ostream &O) const;
1311#endif
1312};
1313
1314/// This is a concrete Recipe that models a single VPlan-level instruction.
1315/// While as any Recipe it may generate a sequence of IR instructions when
1316/// executed, these instructions would always form a single-def expression as
1317/// the VPInstruction is also a single def-use vertex. Most VPInstruction
1318/// opcodes can take an optional mask. Masks may be assigned during
1319/// predication.
1321 public VPIRMetadata,
1322 public VPIRAttributes {
1323public:
1324 /// VPlan opcodes, extending LLVM IR with idiomatics instructions.
1325 enum {
1326 FirstOrderRecurrenceSplice = Instruction::OtherOpsEnd +
1327 1, // Combines the incoming and previous
1328 // values of a first-order recurrence.
1330 // Creates a mask where each lane is active (true) whilst the current
1331 // counter (first operand + index) is less than the second operand. i.e.
1332 // mask[i] = icmpt ult (op0 + i), op1
1333 // ActiveLaneMask is used for early-exit loops with stores, plus tail
1334 // folding for all styles except DataAndControlFlow. The size of the
1335 // mask returned is VF. When unrolled, ActiveLaneMask is duplicated.
1337 // As above, but takes an additional operand (Multiplier). The size of
1338 // the mask returned is VF * Multiplier (UF, op2).
1339 // WideActiveLaneMask is used for control flow and is unrolled by widening,
1340 // with one extract vector created per unroll part.
1342 // Signature: Vectors... -> WideVector
1343 // Concatenates all vector operands to a single wide vector.
1345 // Signature: (Multiplier, Address, Align) -> Vector
1346 // Loads a single wide vector of `Multiplier * VF` elements.
1348 // Signature: (Multiplier, Address, Alignment, Vector)
1349 // Stores a single wide vector of `Multiplier * VF` elements.
1351 // Extracts each unrolled part of a (VF * UF) widened vector/mask.
1354 // Represents the incoming loop-invariant alias-mask. All memory accesses
1355 // in the loop must stay within the active lanes.
1357 // Increment the canonical IV separately for each unrolled part.
1359 // Abstract instruction that compares two values and branches. This is
1360 // lowered to ICmp + BranchOnCond during VPlan to VPlan transformation.
1363 // Branch with 2 boolean condition operands and 3 successors. If condition
1364 // 0 is true, branches to successor 0; if condition 1 is true, branches to
1365 // successor 1; otherwise branches to successor 2. Expanded after region
1366 // dissolution into: (1) an OR of the two conditions branching to
1367 // middle.split or successor 2, and (2) middle.split branching to successor
1368 // 0 or successor 1 based on condition 0.
1371 /// Creates a fixed-width vector containing all operands. The number of
1372 /// operands matches the vector element count.
1374 /// Extracts all lanes from its (non-scalable) vector operand. This is an
1375 /// abstract VPInstruction whose single defined VPValue represents VF
1376 /// scalars extracted from a vector, to be replaced by VF ExtractElement
1377 /// VPInstructions.
1379 /// Reduce the operands to the final reduction result using the operation
1380 /// specified via the operation's VPIRFlags.
1382 // Extracts the last part of its operand. Removed during unrolling.
1384 // Extracts the last lane of its vector operand, per part.
1386 // Extracts the second-to-last lane from its operand or the second-to-last
1387 // part if it is scalar. In the latter case, the recipe will be removed
1388 // during unrolling.
1390 LogicalAnd, // Non-poison propagating logical And.
1391 LogicalOr, // Non-poison propagating logical Or.
1392 NumActiveLanes, // Counts the number of active lanes in a mask.
1393 // Add an offset in bytes (second operand) to a base pointer (first
1394 // operand). Only generates scalar values (either for the first lane only or
1395 // for all lanes, depending on its uses).
1397 // Add a vector offset in bytes (second operand) to a scalar base pointer
1398 // (first operand).
1400 // Returns a scalar boolean value, which is true if any lane of its
1401 // (boolean) vector operands is true. It produces the reduced value across
1402 // all unrolled iterations. Unrolling will add all copies of its original
1403 // operand as additional operands. Note does not block poison propagation.
1405 // Calculates the first active lane index of the vector predicate operands.
1406 // It produces the lane index across all unrolled iterations. Unrolling will
1407 // add all copies of its original operand as additional operands.
1408 // Implemented with @llvm.experimental.cttz.elts, but returns the expected
1409 // result even with operands that are all zeroes.
1411 // Calculates the last active lane index of the vector predicate operands.
1412 // The predicates must be prefix-masks (all 1s before all 0s). Used when
1413 // tail-folding to extract the correct live-out value from the last active
1414 // iteration. It produces the lane index across all unrolled iterations.
1415 // Unrolling will add all copies of its original operand as additional
1416 // operands.
1418 // Returns a reversed vector for the operand.
1420 /// Start vector for reductions with 3 operands: the original start value,
1421 /// the identity value for the reduction and an integer indicating the
1422 /// scaling factor.
1424 /// Extracts a single lane (first operand) from a set of vector operands.
1425 /// The lane specifies an index into a vector formed by combining all vector
1426 /// operands (all operands after the first one).
1428 /// Explicit user for values in the main VPlan, used by the epilogue vector
1429 /// loop. Operands are the resume value from the main vector loop and bypass
1430 /// value.
1432 /// Extracts the last active lane from a set of vectors. The first operand
1433 /// is the default value if no lanes in the masks are active. Conceptually,
1434 /// this concatenates all data vectors (odd operands), concatenates all
1435 /// masks (even operands -- ignoring the default value), and returns the
1436 /// last active value from the combined data vector using the combined mask.
1438 /// Compute the exiting value of a wide induction after vectorization, that
1439 /// is the value of the last lane of the induction increment (i.e. its
1440 /// backedge value). Has the wide induction recipe as operand.
1443 /// Scale the first operand (vector step) by the second operand
1444 /// (scalar-step). Casts both operands to the result type if needed.
1446 // Creates a step vector starting from 0 to VF with a step of 1.
1448 /// Calls a scalar intrinsic. The intrinsic ID is the last operand.
1450
1452 };
1453
1454 /// Returns true if this recipe produces scalar values for all VF lanes.
1455 bool doesGeneratePerAllLanes() const;
1456
1457 /// Return the number of operands determined by the opcode of the
1458 /// VPInstruction, excluding mask. Returns -1u if the number of operands
1459 /// cannot be determined directly by the opcode.
1460 unsigned getNumOperandsForOpcode() const;
1461
1462private:
1463 typedef unsigned char OpcodeTy;
1464 OpcodeTy Opcode;
1465
1466 /// An optional name that can be used for the generated IR instruction.
1467 std::string Name;
1468
1469 /// Returns true if we can generate a scalar for the first lane only if
1470 /// needed.
1471 bool doesGenerateSingleScalar() const;
1472
1473 /// Utility method serving execute: Generates either a single-scalar or vector
1474 /// value. \p GenerateSingleScalar determines whether to generate a
1475 /// single-scalar value.
1476 Value *generate(VPTransformState &State, bool GenerateSingleScalar);
1477
1478 /// Returns true if the VPInstruction does not need masking.
1479 bool alwaysUnmasked() const {
1481 "Should be expanded in VPlanPredicator");
1482
1483 // These VPInstruction can be (optionally) masked.
1484 if (Opcode == VPInstruction::WideVectorLoad ||
1486 return false;
1487
1488 // For now only VPInstructions with underlying values use masks.
1489 // TODO: provide masks to VPInstructions w/o underlying values.
1490 if (!getUnderlyingValue())
1491 return true;
1492
1493 return Instruction::isCast(Opcode) || Opcode == Instruction::PHI ||
1494 Opcode == Instruction::GetElementPtr ||
1495 Opcode == Instruction::ExtractValue;
1496 }
1497
1498 /// Returns true if this is an abstract instruction that can't be executed.
1499 bool isAbstract() const {
1500 return isMasked() && Opcode != VPInstruction::WideVectorLoad &&
1501 Opcode != VPInstruction::WideVectorStore;
1502 }
1503
1504public:
1505 VPInstruction(unsigned Opcode, ArrayRef<VPValue *> Operands,
1506 const VPIRFlags &Flags = {}, const VPIRMetadata &MD = {},
1507 DebugLoc DL = DebugLoc::getUnknown(), const Twine &Name = "",
1508 Type *ResultTy = nullptr, const VPIRAttributes &Attrs = {});
1509
1510 VP_CLASSOF_IMPL(VPRecipeBase::VPInstructionSC)
1511
1512 VPInstruction *clone() override {
1514 }
1515
1517 Type *ResultTy = nullptr) {
1518 auto *New = new VPInstruction(Opcode, NewOperands, *this, *this,
1519 getDebugLoc(), Name, ResultTy, *this);
1520 if (getUnderlyingValue())
1521 New->setUnderlyingValue(getUnderlyingInstr());
1522 return New;
1523 }
1524
1525 unsigned getOpcode() const { return Opcode; }
1526
1527 /// Add \p Op as operand of this VPInstruction. Only supported for AnyOf,
1528 /// ComputeReductionResult, BuildVector, ExtractLane,
1529 /// ExtractLastActive, FirstActiveLane, LastActiveLane.
1530 void addOperand(VPValue *Op);
1531
1532 void execute(VPTransformState &State) override;
1533
1534 /// Return the cost of this VPInstruction.
1535 InstructionCost computeCost(ElementCount VF,
1536 VPCostContext &Ctx) const override;
1537
1538#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1539 /// Print the VPInstruction to dbgs() (for debugging).
1540 LLVM_DUMP_METHOD void dump() const;
1541#endif
1542
1543 bool hasResult() const { return !getScalarType()->isVoidTy(); }
1544
1545 /// Returns true if the VPInstruction has a mask operand.
1546 bool isMasked() const {
1547 unsigned NumOpsForOpcode = getNumOperandsForOpcode();
1548 // VPInstructions without a fixed number of operands cannot be masked.
1549 if (NumOpsForOpcode == -1u)
1550 return false;
1551 return NumOpsForOpcode + 1 == getNumOperands();
1552 }
1553
1554 /// Returns the number of operands, excluding the mask if the VPInstruction is
1555 /// masked.
1556 unsigned getNumOperandsWithoutMask() const {
1557 return getNumOperands() - isMasked();
1558 }
1559
1560 /// Add mask \p Mask to an unmasked VPInstruction, if it needs masking.
1561 void addMask(VPValue *Mask) {
1562 assert(!isMasked() && "recipe is already masked");
1563 if (alwaysUnmasked())
1564 return;
1565 assert(Mask->getScalarType()->isIntegerTy(1) &&
1566 "Mask must be an i1 (vector)");
1567 VPUser::addOperand(Mask);
1568 }
1569
1570 /// Returns the mask for the VPInstruction. Returns nullptr for unmasked
1571 /// VPInstructions.
1572 VPValue *getMask() const { return isMasked() ? getLastOperand() : nullptr; }
1573
1574 /// Returns an iterator range over the operands excluding the mask operand
1575 /// if present.
1582
1583 /// Returns true if the underlying opcode may read from or write to memory.
1584 bool opcodeMayReadOrWriteFromMemory() const;
1585
1586 /// Returns true if the recipe only uses the first lane of operand \p Op.
1587 bool usesFirstLaneOnly(const VPValue *Op) const override;
1588
1589 /// Returns true if the recipe only uses scalars of operand \p Op.
1590 bool usesScalars(const VPValue *Op) const override {
1593 }
1594
1595 /// Returns true if the recipe only uses the first part of operand \p Op.
1596 bool usesFirstPartOnly(const VPValue *Op) const override;
1597
1598 /// Returns true if this VPInstruction produces a scalar value from a vector,
1599 /// e.g. by performing a reduction or extracting a lane.
1600 bool isVectorToScalar() const;
1601
1602 /// Returns true if the recipe produces a single scalar value.
1603 bool isSingleScalar() const;
1604
1605 /// Returns the symbolic name assigned to the VPInstruction.
1606 StringRef getName() const { return Name; }
1607
1608 /// Set the symbolic name for the VPInstruction.
1609 void setName(StringRef NewName) { Name = NewName.str(); }
1610
1611protected:
1612#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1613 /// Print the VPInstruction to \p O.
1614 void printRecipe(raw_ostream &O, const Twine &Indent,
1615 VPSlotTracker &SlotTracker) const override;
1616#endif
1617};
1618
1619/// Helper type to provide functions to access incoming values and blocks for
1620/// phi-like recipes.
1622protected:
1623 /// Return a VPRecipeBase* to the current object.
1624 virtual const VPRecipeBase *getAsRecipe() const = 0;
1625
1626public:
1627 virtual ~VPPhiAccessors() = default;
1628
1629 /// Returns the incoming VPValue with index \p Idx.
1630 VPValue *getIncomingValue(unsigned Idx) const {
1631 return getAsRecipe()->getOperand(Idx);
1632 }
1633
1634 /// Returns the incoming block with index \p Idx.
1635 const VPBasicBlock *getIncomingBlock(unsigned Idx) const;
1636
1637 /// Returns the incoming value for \p VPBB. \p VPBB must be an incoming block.
1639 getIncomingValueForBlock(const VPBasicBlock *VPBB) const;
1640
1641 /// Sets the incoming value for \p VPBB to \p V. \p VPBB must be an incoming
1642 /// block.
1643 void setIncomingValueForBlock(const VPBasicBlock *VPBB, VPValue *V) const;
1644
1645 /// Returns the number of incoming values, also number of incoming blocks.
1646 virtual unsigned getNumIncoming() const {
1647 return getAsRecipe()->getNumOperands();
1648 }
1649
1650 /// Returns an interator range over the incoming values.
1652 return make_range(getAsRecipe()->op_begin(),
1653 getAsRecipe()->op_begin() + getNumIncoming());
1654 }
1655
1657 detail::index_iterator, std::function<const VPBasicBlock *(size_t)>>>;
1658
1659 /// Returns an iterator range over the incoming blocks.
1661 std::function<const VPBasicBlock *(size_t)> GetBlock = [this](size_t Idx) {
1662 return getIncomingBlock(Idx);
1663 };
1664 return map_range(index_range(0, getNumIncoming()), GetBlock);
1665 }
1666
1667 /// Returns an iterator range over pairs of incoming values and corresponding
1668 /// incoming blocks.
1674
1675 /// Removes the incoming value for \p IncomingBlock, which must be a
1676 /// predecessor.
1677 void removeIncomingValueFor(VPBlockBase *IncomingBlock) const;
1678
1679 /// Append \p IncomingV as an incoming value to the phi-like recipe.
1680 void addIncoming(VPValue *IncomingV) {
1681 auto *R = const_cast<VPRecipeBase *>(getAsRecipe());
1682 assert((R->getNumOperands() == 0 ||
1683 IncomingV->getScalarType() == R->getOperand(0)->getScalarType()) &&
1684 "all incoming values must have the same type");
1685 R->addOperand(IncomingV);
1686 }
1687
1688#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1689 /// Print the recipe.
1691#endif
1692};
1693
1696 const Twine &Name = "", Type *ResultTy = nullptr)
1697 : VPInstruction(Instruction::PHI, Operands, Flags, {}, DL, Name,
1698 ResultTy) {}
1699
1700 static inline bool classof(const VPUser *U) {
1701 auto *VPI = dyn_cast<VPInstruction>(U);
1702 return VPI && VPI->getOpcode() == Instruction::PHI;
1703 }
1704
1705 static inline bool classof(const VPValue *V) {
1706 auto *VPI = dyn_cast<VPInstruction>(V);
1707 return VPI && VPI->getOpcode() == Instruction::PHI;
1708 }
1709
1710 static inline bool classof(const VPSingleDefRecipe *SDR) {
1711 auto *VPI = dyn_cast<VPInstruction>(SDR);
1712 return VPI && VPI->getOpcode() == Instruction::PHI;
1713 }
1714
1715 VPPhi *clone() override {
1716 auto *PhiR = new VPPhi(operands(), *this, getDebugLoc(), getName());
1717 PhiR->setUnderlyingValue(getUnderlyingValue());
1718 return PhiR;
1719 }
1720
1721 void execute(VPTransformState &State) override;
1722
1723protected:
1724#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1725 /// Print the recipe.
1726 void printRecipe(raw_ostream &O, const Twine &Indent,
1727 VPSlotTracker &SlotTracker) const override;
1728#endif
1729
1730 const VPRecipeBase *getAsRecipe() const override { return this; }
1731};
1732
1733/// A recipe to wrap on original IR instruction not to be modified during
1734/// execution, except for PHIs. PHIs are modeled via the VPIRPhi subclass.
1735/// Expect PHIs, VPIRInstructions cannot have any operands.
1737 Instruction &I;
1738
1739protected:
1740 /// VPIRInstruction::create() should be used to create VPIRInstructions, as
1741 /// subclasses may need to be created, e.g. VPIRPhi.
1743 : VPRecipeBase(VPRecipeBase::VPIRInstructionSC, {}), I(I) {}
1744
1745public:
1746 ~VPIRInstruction() override = default;
1747
1748 /// Create a new VPIRPhi for \p \I, if it is a PHINode, otherwise create a
1749 /// VPIRInstruction.
1751
1752 VP_CLASSOF_IMPL(VPRecipeBase::VPIRInstructionSC)
1753
1755 auto *R = create(I);
1756 for (auto *Op : operands())
1757 R->addOperand(Op);
1758 return R;
1759 }
1760
1761 void execute(VPTransformState &State) override;
1762
1763 /// Return the cost of this VPIRInstruction.
1765 computeCost(ElementCount VF, VPCostContext &Ctx) const override;
1766
1767 Instruction &getInstruction() const { return I; }
1768
1769 bool usesScalars(const VPValue *Op) const override {
1771 "Op must be an operand of the recipe");
1772 return true;
1773 }
1774
1775 bool usesFirstPartOnly(const VPValue *Op) const override {
1777 "Op must be an operand of the recipe");
1778 return true;
1779 }
1780
1781 bool usesFirstLaneOnly(const VPValue *Op) const override {
1783 "Op must be an operand of the recipe");
1784 return true;
1785 }
1786
1787protected:
1788#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1789 /// Print the recipe.
1790 void printRecipe(raw_ostream &O, const Twine &Indent,
1791 VPSlotTracker &SlotTracker) const override;
1792#endif
1793};
1794
1795/// An overlay for VPIRInstructions wrapping PHI nodes enabling convenient use
1796/// cast/dyn_cast/isa and execute() implementation. A single VPValue operand is
1797/// allowed, and it is used to add a new incoming value for the single
1798/// predecessor VPBB.
1800 public VPPhiAccessors {
1802
1803 static inline bool classof(const VPRecipeBase *U) {
1804 auto *R = dyn_cast<VPIRInstruction>(U);
1805 return R && isa<PHINode>(R->getInstruction());
1806 }
1807
1808 static inline bool classof(const VPUser *U) {
1809 auto *R = dyn_cast<VPRecipeBase>(U);
1810 return R && classof(R);
1811 }
1812
1814
1815 void execute(VPTransformState &State) override;
1816
1817protected:
1818#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1819 /// Print the recipe.
1820 void printRecipe(raw_ostream &O, const Twine &Indent,
1821 VPSlotTracker &SlotTracker) const override;
1822#endif
1823
1824 const VPRecipeBase *getAsRecipe() const override { return this; }
1825};
1826
1827/// VPWidenRecipe is a recipe for producing a widened instruction using the
1828/// opcode and operands of the recipe. This recipe covers most of the
1829/// traditional vectorization cases where each recipe transforms into a
1830/// vectorized version of itself.
1832 public VPIRMetadata {
1833 unsigned Opcode;
1834
1835public:
1837 const VPIRFlags &Flags = {}, const VPIRMetadata &Metadata = {},
1838 DebugLoc DL = {})
1839 : VPWidenRecipe(I.getOpcode(), Operands, Flags, Metadata, DL) {
1840 setUnderlyingValue(&I);
1841 }
1842
1844 const VPIRFlags &Flags = {}, const VPIRMetadata &Metadata = {},
1845 DebugLoc DL = {})
1846 : VPRecipeWithIRFlags(VPRecipeBase::VPWidenSC, Operands,
1848 Flags, DL),
1849 VPIRMetadata(Metadata), Opcode(Opcode) {
1850 assert(flagsValidForOpcode(Opcode) &&
1851 "Set flags not supported for the provided opcode");
1852 assert(hasRequiredFlagsForOpcode(Opcode, getScalarType()) &&
1853 "Opcode requires specific flags to be set");
1854 }
1855
1856 ~VPWidenRecipe() override = default;
1857
1859
1861 if (auto *UV = getUnderlyingValue())
1862 return new VPWidenRecipe(*cast<Instruction>(UV), NewOperands, *this,
1863 *this, getDebugLoc());
1864 return new VPWidenRecipe(Opcode, NewOperands, *this, *this, getDebugLoc());
1865 }
1866
1867 VP_CLASSOF_IMPL(VPRecipeBase::VPWidenSC)
1868
1869 /// Produce a widened instruction using the opcode and operands of the recipe,
1870 /// processing State.VF elements.
1871 void execute(VPTransformState &State) override;
1872
1873 /// Return the cost of this VPWidenRecipe.
1874 InstructionCost computeCost(ElementCount VF,
1875 VPCostContext &Ctx) const override;
1876
1877 unsigned getOpcode() const { return Opcode; }
1878
1879protected:
1880#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1881 /// Print the recipe.
1882 void printRecipe(raw_ostream &O, const Twine &Indent,
1883 VPSlotTracker &SlotTracker) const override;
1884#endif
1885
1886 /// Returns true if the recipe only uses the first lane of operand \p Op.
1887 bool usesFirstLaneOnly(const VPValue *Op) const override {
1889 "Op must be an operand of the recipe");
1890 return Opcode == Instruction::Select && Op == getOperand(0) &&
1892 }
1893};
1894
1895/// VPWidenCastRecipe is a recipe to create vector cast instructions.
1896/// TODO: Merge with VPWidenRecipe now that type is associated to every
1897/// VPRecipeValue.
1899 public VPIRMetadata {
1900 /// Cast instruction opcode.
1901 Instruction::CastOps Opcode;
1902
1903public:
1905 CastInst *CI = nullptr, const VPIRFlags &Flags = {},
1906 const VPIRMetadata &Metadata = {},
1907 DebugLoc DL = DebugLoc::getUnknown())
1908 : VPRecipeWithIRFlags(VPRecipeBase::VPWidenCastSC, Op, ResultTy, Flags,
1909 DL),
1910 VPIRMetadata(Metadata), Opcode(Opcode) {
1911 assert(flagsValidForOpcode(Opcode) &&
1912 "Set flags not supported for the provided opcode");
1913 assert(hasRequiredFlagsForOpcode(Opcode, ResultTy) &&
1914 "Opcode requires specific flags to be set");
1915 setUnderlyingValue(CI);
1916 }
1917
1918 ~VPWidenCastRecipe() override = default;
1919
1921 return new VPWidenCastRecipe(Opcode, getOperand(0), getScalarType(),
1923 *this, *this, getDebugLoc());
1924 }
1925
1926 VP_CLASSOF_IMPL(VPRecipeBase::VPWidenCastSC)
1927
1928 /// Produce widened copies of the cast.
1929 void execute(VPTransformState &State) override;
1930
1931 /// Return the cost of this VPWidenCastRecipe.
1932 InstructionCost computeCost(ElementCount VF,
1933 VPCostContext &Ctx) const override;
1934
1935 Instruction::CastOps getOpcode() const { return Opcode; }
1936
1937protected:
1938#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1939 /// Print the recipe.
1940 void printRecipe(raw_ostream &O, const Twine &Indent,
1941 VPSlotTracker &SlotTracker) const override;
1942#endif
1943};
1944
1945/// A recipe for widening vector intrinsics.
1947 public VPIRMetadata {
1948 /// ID of the vector intrinsic to widen.
1949 Intrinsic::ID VectorIntrinsicID;
1950
1951 /// True if the intrinsic may read from memory.
1952 bool MayReadFromMemory;
1953
1954 /// True if the intrinsic may read write to memory.
1955 bool MayWriteToMemory;
1956
1957 /// True if the intrinsic may have side-effects.
1958 bool MayHaveSideEffects;
1959
1960protected:
1962 ArrayRef<VPValue *> CallArguments, Type *Ty,
1963 const VPIRFlags &Flags = {},
1964 const VPIRMetadata &MD = {},
1965 DebugLoc DL = DebugLoc::getUnknown())
1966 : VPRecipeWithIRFlags(SC, CallArguments, Ty, Flags, DL), VPIRMetadata(MD),
1967 VectorIntrinsicID(VectorIntrinsicID) {
1968 LLVMContext &Ctx = Ty->getContext();
1969 AttributeSet Attrs = Intrinsic::getFnAttributes(Ctx, VectorIntrinsicID);
1970 MemoryEffects ME = Attrs.getMemoryEffects();
1971 MayReadFromMemory = !ME.onlyWritesMemory();
1972 MayWriteToMemory = !ME.onlyReadsMemory();
1973 MayHaveSideEffects = MayWriteToMemory ||
1974 !Attrs.hasAttribute(Attribute::NoUnwind) ||
1975 !Attrs.hasAttribute(Attribute::WillReturn);
1976 }
1977
1978 /// Helper function to produce the widened intrinsic call.
1979 CallInst *createVectorCall(VPTransformState &State);
1980
1981public:
1983 ArrayRef<VPValue *> CallArguments, Type *Ty,
1984 const VPIRFlags &Flags = {},
1985 const VPIRMetadata &MD = {},
1986 DebugLoc DL = DebugLoc::getUnknown())
1987 : VPRecipeWithIRFlags(VPRecipeBase::VPWidenIntrinsicSC, CallArguments, Ty,
1988 Flags, DL),
1989 VPIRMetadata(MD), VectorIntrinsicID(VectorIntrinsicID),
1990 MayReadFromMemory(CI.mayReadFromMemory()),
1991 MayWriteToMemory(CI.mayWriteToMemory()),
1992 MayHaveSideEffects(CI.mayHaveSideEffects()) {
1993 setUnderlyingValue(&CI);
1994 }
1995
1997 ArrayRef<VPValue *> CallArguments, Type *Ty,
1998 const VPIRFlags &Flags = {},
1999 const VPIRMetadata &Metadata = {},
2000 DebugLoc DL = DebugLoc::getUnknown())
2001 : VPWidenIntrinsicRecipe(VPRecipeBase::VPWidenIntrinsicSC,
2002 VectorIntrinsicID, CallArguments, Ty, Flags,
2003 Metadata, DL) {}
2004
2005 ~VPWidenIntrinsicRecipe() override = default;
2006
2008 if (Value *CI = getUnderlyingValue())
2009 return new VPWidenIntrinsicRecipe(*cast<CallInst>(CI), VectorIntrinsicID,
2010 operands(), getScalarType(), *this,
2011 *this, getDebugLoc());
2012 return new VPWidenIntrinsicRecipe(VectorIntrinsicID, operands(),
2013 getScalarType(), *this, *this,
2014 getDebugLoc());
2015 }
2016
2017 static inline bool classof(const VPRecipeBase *R) {
2018 return R->getVPRecipeID() == VPRecipeBase::VPWidenIntrinsicSC ||
2019 R->getVPRecipeID() == VPRecipeBase::VPWidenMemIntrinsicSC;
2020 }
2021
2022 static inline bool classof(const VPUser *U) {
2023 auto *R = dyn_cast<VPRecipeBase>(U);
2024 return R && classof(R);
2025 }
2026
2027 static inline bool classof(const VPValue *V) {
2028 auto *R = V->getDefiningRecipe();
2029 return R && classof(R);
2030 }
2031
2032 static inline bool classof(const VPSingleDefRecipe *R) {
2033 return classof(static_cast<const VPRecipeBase *>(R));
2034 }
2035
2036 /// Produce a widened version of the vector intrinsic.
2037 void execute(VPTransformState &State) override;
2038
2039 /// Compute the cost of a vector intrinsic with \p ID and \p Operands.
2040 static InstructionCost computeCallCost(Intrinsic::ID ID,
2042 const VPRecipeWithIRFlags &R,
2043 ElementCount VF, VPCostContext &Ctx);
2044
2045 /// Return the cost of this vector intrinsic.
2046 InstructionCost computeCost(ElementCount VF,
2047 VPCostContext &Ctx) const override;
2048
2049 /// Return the ID of the intrinsic.
2050 Intrinsic::ID getVectorIntrinsicID() const { return VectorIntrinsicID; }
2051
2052 /// Return to name of the intrinsic as string.
2053 StringRef getIntrinsicName() const;
2054
2055 /// Returns true if the intrinsic may read from memory.
2056 bool mayReadFromMemory() const { return MayReadFromMemory; }
2057
2058 /// Returns true if the intrinsic may write to memory.
2059 bool mayWriteToMemory() const { return MayWriteToMemory; }
2060
2061 /// Returns true if the intrinsic may have side-effects.
2062 bool mayHaveSideEffects() const { return MayHaveSideEffects; }
2063
2064 bool usesFirstLaneOnly(const VPValue *Op) const override;
2065
2066protected:
2067#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2068 /// Print the recipe.
2069 void printRecipe(raw_ostream &O, const Twine &Indent,
2070 VPSlotTracker &SlotTracker) const override;
2071#endif
2072};
2073
2074/// A recipe for widening vector memory intrinsics.
2076 : public VPWidenIntrinsicRecipe {
2077 /// Alignment information for this memory access.
2078 Align Alignment;
2079
2080public:
2082 ArrayRef<VPValue *> CallArguments, Type *Ty,
2083 Align Alignment, const VPIRMetadata &MD = {},
2085 : VPWidenIntrinsicRecipe(VPRecipeBase::VPWidenMemIntrinsicSC,
2086 VectorIntrinsicID, CallArguments, Ty, {}, MD,
2087 DL),
2088 Alignment(Alignment) {
2089 assert(getVectorMemoryIntrinsicPointerArgIdx(VectorIntrinsicID) &&
2090 getVectorIntrinsicMaskArgIdx(VectorIntrinsicID) &&
2091 "Expected a masked vector load/store intrinsic");
2092 assert((!Ty->isVoidTy() ||
2093 getVectorStoreIntrinsicDataArgIdx(VectorIntrinsicID)) &&
2094 "Expected data argument for store intrinsic");
2095 }
2096
2097 ~VPWidenMemIntrinsicRecipe() override = default;
2098
2101 getScalarType(), Alignment, *this,
2102 getDebugLoc());
2103 }
2104
2105 VP_CLASSOF_IMPL(VPRecipeBase::VPWidenMemIntrinsicSC)
2106
2107 /// Produce a widened version of the vector memory intrinsic.
2108 void execute(VPTransformState &State) override;
2109
2110 /// Returns the address operand index of the VPWidenMemIntrinsicRecipe.
2111 unsigned getAddrOpIdx() const;
2112
2113 /// Returns the mask of a predicated VPWidenMemIntrinsicRecipe.
2114 VPValue *getMask() const;
2115
2116 /// Returns the data type of the memory access at \p VF.
2117 Type *getAccessType(ElementCount VF) const;
2118
2119 /// Helper function for computing the cost of vector memory intrinsic.
2120 static InstructionCost computeMemIntrinsicCost(Intrinsic::ID IID, Type *Ty,
2121 bool IsMasked, Align Alignment,
2122 VPCostContext &Ctx);
2123
2124 /// Return the cost of this vector memory intrinsic.
2125 InstructionCost computeCost(ElementCount VF,
2126 VPCostContext &Ctx) const override;
2127};
2128
2129/// A recipe for widening Call instructions using library calls.
2131 public VPIRMetadata,
2132 public VPIRAttributes {
2133 /// Variant stores a pointer to the chosen function. There is a 1:1 mapping
2134 /// between a given VF and the chosen vectorized variant, so there will be a
2135 /// different VPlan for each VF with a valid variant.
2136 Function *Variant;
2137
2138public:
2140 ArrayRef<VPValue *> CallArguments,
2141 const VPIRFlags &Flags = {},
2142 const VPIRMetadata &Metadata = {},
2143 const VPIRAttributes &Attrs = {}, DebugLoc DL = {})
2144 : VPRecipeWithIRFlags(VPRecipeBase::VPWidenCallSC, CallArguments,
2145 toScalarizedTy(Variant->getReturnType()), Flags,
2146 DL),
2147 VPIRMetadata(Metadata), VPIRAttributes(Attrs), Variant(Variant) {
2148 setUnderlyingValue(UV);
2149 assert(isa<Function>(getLastOperand()->getLiveInIRValue()) &&
2150 "last operand must be the called function");
2151 assert(cast<Function>(CallArguments.back()->getLiveInIRValue())
2152 ->getReturnType() == getScalarType() &&
2153 "Scalar type must match return type of called scalar function");
2154 }
2155
2156 ~VPWidenCallRecipe() override = default;
2157
2159 return new VPWidenCallRecipe(getUnderlyingValue(), Variant, operands(),
2160 *this, *this, *this, getDebugLoc());
2161 }
2162
2163 VP_CLASSOF_IMPL(VPRecipeBase::VPWidenCallSC)
2164
2165 /// Produce a widened version of the call instruction.
2166 void execute(VPTransformState &State) override;
2167
2168 /// Return the cost of this VPWidenCallRecipe.
2169 InstructionCost computeCost(ElementCount VF,
2170 VPCostContext &Ctx) const override;
2171
2172 /// Return the cost of widening a call using the vector function \p Variant.
2173 static InstructionCost computeCallCost(Function *Variant, VPCostContext &Ctx);
2174
2178
2181
2182 /// Returns true if the recipe only uses the first lane of operand \p Op.
2183 bool usesFirstLaneOnly(const VPValue *Op) const override;
2184
2185protected:
2186#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2187 /// Print the recipe.
2188 void printRecipe(raw_ostream &O, const Twine &Indent,
2189 VPSlotTracker &SlotTracker) const override;
2190#endif
2191};
2192
2193/// A recipe representing a sequence of load -> update -> store as part of
2194/// a histogram operation. This means there may be aliasing between vector
2195/// lanes, which is handled by the llvm.experimental.vector.histogram family
2196/// of intrinsics. Supported update operations are: add, sub, uadd.sat, umax,
2197/// and umin, where the other term is loop-invariant.
2199 /// The update operation kind for this histogram.
2200 HistogramUpdateKind UpdateKind;
2201
2202public:
2204 ArrayRef<VPValue *> Operands,
2205 const VPIRMetadata &Metadata = {},
2207 : VPRecipeBase(VPRecipeBase::VPHistogramSC, Operands, DL),
2208 VPIRMetadata(Metadata), UpdateKind(UpdateKind) {}
2209
2210 ~VPHistogramRecipe() override = default;
2211
2213 return new VPHistogramRecipe(UpdateKind, operands(), *this, getDebugLoc());
2214 }
2215
2216 VP_CLASSOF_IMPL(VPRecipeBase::VPHistogramSC);
2217
2218 /// Produce a vectorized histogram operation.
2219 void execute(VPTransformState &State) override;
2220
2221 /// Return the cost of this VPHistogramRecipe.
2223 VPCostContext &Ctx) const override;
2224
2225 /// Return the mask operand if one was provided, or a null pointer if all
2226 /// lanes should be executed unconditionally.
2227 VPValue *getMask() const {
2228 return getNumOperands() == 3 ? getOperand(2) : nullptr;
2229 }
2230
2231 /// Returns true if the recipe only uses the first lane of operand \p Op.
2232 bool usesFirstLaneOnly(const VPValue *Op) const override {
2234 "Op must be an operand of the recipe");
2235 return Op == getOperand(1);
2236 }
2237
2238private:
2239 /// Return the histogram intrinsic ID for this recipe's update kind.
2240 Intrinsic::ID getHistogramIntrinsicID() const;
2241
2242 /// Return true if the increment should be negated before passing to the
2243 /// histogram intrinsic (only for Sub).
2244 bool mustNegateIncrement() const {
2245 return UpdateKind == HistogramUpdateKind::Sub;
2246 }
2247
2248protected:
2249#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2250 /// Print the recipe
2251 void printRecipe(raw_ostream &O, const Twine &Indent,
2252 VPSlotTracker &SlotTracker) const override;
2253#endif
2254};
2255
2256/// A recipe for handling GEP instructions.
2258 Type *SourceElementTy;
2259
2260public:
2262 const VPIRFlags &Flags = {},
2264 GetElementPtrInst *UV = nullptr)
2265 : VPRecipeWithIRFlags(VPRecipeBase::VPWidenGEPSC, Operands,
2266 Operands[0]->getScalarType(), Flags, DL),
2267 SourceElementTy(SourceElementTy) {
2268 if (UV) {
2269 setUnderlyingValue(UV);
2272 assert(Metadata.empty() && "unexpected metadata on GEP");
2273 }
2274 }
2275
2276 ~VPWidenGEPRecipe() override = default;
2277
2283
2284 VP_CLASSOF_IMPL(VPRecipeBase::VPWidenGEPSC)
2285
2286 /// This recipe generates a GEP instruction.
2287 unsigned getOpcode() const { return Instruction::GetElementPtr; }
2288
2289 /// Generate the gep nodes.
2290 void execute(VPTransformState &State) override;
2291
2292 Type *getSourceElementType() const { return SourceElementTy; }
2293
2294 /// Return the cost of this VPWidenGEPRecipe.
2296 VPCostContext &Ctx) const override {
2297 // TODO: Compute accurate cost after retiring the legacy cost model.
2298 return 0;
2299 }
2300
2301 /// Returns true if the recipe only uses the first lane of operand \p Op.
2302 bool usesFirstLaneOnly(const VPValue *Op) const override;
2303
2304protected:
2305#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2306 /// Print the recipe.
2307 void printRecipe(raw_ostream &O, const Twine &Indent,
2308 VPSlotTracker &SlotTracker) const override;
2309#endif
2310};
2311
2312/// A recipe to compute a pointer to the last element of each part of a widened
2313/// memory access for widened memory accesses of SourceElementTy. Used for
2314/// VPWidenMemoryRecipes or VPInterleaveRecipes that are reversed. An extra
2315/// Offset operand is added by convertToConcreteRecipes when UF = 1, and by the
2316/// unroller otherwise.
2318 Type *SourceElementTy;
2319
2320 /// The constant stride of the pointer computed by this recipe, expressed in
2321 /// units of SourceElementTy.
2322 int64_t Stride;
2323
2324public:
2325 VPVectorEndPointerRecipe(VPValue *Ptr, VPValue *VF, Type *SourceElementTy,
2326 int64_t Stride, GEPNoWrapFlags GEPFlags, DebugLoc DL)
2327 : VPRecipeWithIRFlags(VPRecipeBase::VPVectorEndPointerSC, {Ptr, VF},
2328 Ptr->getScalarType(), GEPFlags, DL),
2329 SourceElementTy(SourceElementTy), Stride(Stride) {
2330 assert(Stride < 0 && "Stride must be negative");
2331 }
2332
2333 VP_CLASSOF_IMPL(VPRecipeBase::VPVectorEndPointerSC)
2334
2335 Type *getSourceElementType() const { return SourceElementTy; }
2336 int64_t getStride() const { return Stride; }
2337 VPValue *getPointer() const { return getOperand(0); }
2338 VPValue *getVFValue() const { return getOperand(1); }
2340 return getNumOperands() == 3 ? getOperand(2) : nullptr;
2341 }
2342
2343 /// Adds the offset operand to the recipe.
2344 /// Offset = Stride * (VF - 1) + Part * Stride * VF.
2345 void materializeOffset(unsigned Part = 0);
2346
2347 /// Append \p Offset as the offset operand. The offset is an integer index
2348 /// expressed in units of SourceElementTy.
2350 assert(Offset->getScalarType()->isIntegerTy() &&
2351 "offset must be an integer index");
2353 }
2354
2355 void execute(VPTransformState &State) override;
2356
2357 bool usesFirstLaneOnly(const VPValue *Op) const override {
2359 "Op must be an operand of the recipe");
2360 return true;
2361 }
2362
2363 /// Return the cost of this VPVectorPointerRecipe.
2365 VPCostContext &Ctx) const override {
2366 // TODO: Compute accurate cost after retiring the legacy cost model.
2367 return 0;
2368 }
2369
2370 /// Returns true if the recipe only uses the first part of operand \p Op.
2371 bool usesFirstPartOnly(const VPValue *Op) const override {
2373 "Op must be an operand of the recipe");
2374 assert(getNumOperands() <= 2 && "must have at most two operands");
2375 return true;
2376 }
2377
2379 auto *VEPR = new VPVectorEndPointerRecipe(
2382 if (auto *Offset = getOffset())
2383 VEPR->addOffset(Offset);
2384 return VEPR;
2385 }
2386
2387protected:
2388#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2389 /// Print the recipe.
2390 void printRecipe(raw_ostream &O, const Twine &Indent,
2391 VPSlotTracker &SlotTracker) const override;
2392#endif
2393};
2394
2395/// A recipe to compute the pointers for widened memory accesses of \p
2396/// SourceElementTy, with the \p Stride expressed in units of \p
2397/// SourceElementTy. Unrolling adds an extra \p VFxPart operand for unrolled
2398/// parts > 0 and it produces `GEP SourceElementTy Ptr, VFxPart * Stride`.
2400 Type *SourceElementTy;
2401
2402public:
2403 VPVectorPointerRecipe(VPValue *Ptr, Type *SourceElementTy, VPValue *Stride,
2404 GEPNoWrapFlags GEPFlags, DebugLoc DL)
2405 : VPRecipeWithIRFlags(VPRecipeBase::VPVectorPointerSC,
2406 ArrayRef<VPValue *>({Ptr, Stride}),
2407 Ptr->getScalarType(), GEPFlags, DL),
2408 SourceElementTy(SourceElementTy) {}
2409
2410 VP_CLASSOF_IMPL(VPRecipeBase::VPVectorPointerSC)
2411
2412 VPValue *getStride() const { return getOperand(1); }
2413
2415 return getNumOperands() > 2 ? getOperand(2) : nullptr;
2416 }
2417
2418 /// Add the per-part offset (VFxPart) used for unrolled parts > 0.
2419 void addPerPartOffset(VPValue *VFxPart) {
2420 assert(VFxPart->getScalarType()->isIntegerTy() &&
2421 "per-part offset must be an integer index");
2422 VPUser::addOperand(VFxPart);
2423 }
2424
2425 void execute(VPTransformState &State) override;
2426
2427 Type *getSourceElementType() const { return SourceElementTy; }
2428
2429 bool usesFirstLaneOnly(const VPValue *Op) const override {
2431 "Op must be an operand of the recipe");
2432 return true;
2433 }
2434
2435 /// Returns true if the recipe only uses the first part of operand \p Op.
2436 bool usesFirstPartOnly(const VPValue *Op) const override {
2438 "Op must be an operand of the recipe");
2439 assert(getNumOperands() <= 2 && "must have at most two operands");
2440 return true;
2441 }
2442
2444 auto *Clone =
2445 new VPVectorPointerRecipe(getOperand(0), SourceElementTy, getStride(),
2447 if (auto *VFxPart = getVFxPart())
2448 Clone->addPerPartOffset(VFxPart);
2449 return Clone;
2450 }
2451
2452 /// Return the cost of this VPHeaderPHIRecipe.
2454 VPCostContext &Ctx) const override {
2455 // TODO: Compute accurate cost after retiring the legacy cost model.
2456 return 0;
2457 }
2458
2459protected:
2460#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2461 /// Print the recipe.
2462 void printRecipe(raw_ostream &O, const Twine &Indent,
2463 VPSlotTracker &SlotTracker) const override;
2464#endif
2465};
2466
2467/// A pure virtual base class for all recipes modeling header phis, including
2468/// phis for first order recurrences, pointer inductions and reductions. The
2469/// start value is the first operand of the recipe and the incoming value from
2470/// the backedge is the second operand.
2471///
2472/// Inductions are modeled using the following sub-classes:
2473/// * VPWidenIntOrFpInductionRecipe: Generates vector values for integer and
2474/// floating point inductions with arbitrary start and step values. Produces
2475/// a vector PHI per-part.
2476/// * VPWidenPointerInductionRecipe: Generate vector and scalar values for a
2477/// pointer induction. Produces either a vector PHI per-part or scalar values
2478/// per-lane based on the canonical induction.
2479/// * VPFirstOrderRecurrencePHIRecipe
2480/// * VPReductionPHIRecipe
2481/// * VPActiveLaneMaskPHIRecipe
2482/// * VPEVLBasedIVPHIRecipe
2483///
2484/// Note that the canonical IV is modeled as a VPRegionValue associated with
2485/// its loop region.
2487 public VPPhiAccessors {
2488protected:
2489 VPHeaderPHIRecipe(VPRecipeTy VPRecipeID, Instruction *UnderlyingInstr,
2490 VPValue *Start, Type *ResultTy,
2492 : VPSingleDefRecipe(VPRecipeID, Start, ResultTy, UnderlyingInstr, DL) {}
2493
2494 const VPRecipeBase *getAsRecipe() const override { return this; }
2495
2496public:
2497 ~VPHeaderPHIRecipe() override = default;
2498
2499 /// Method to support type inquiry through isa, cast, and dyn_cast.
2500 static inline bool classof(const VPRecipeBase *R) {
2501 return R->getVPRecipeID() >= VPRecipeBase::VPFirstHeaderPHISC &&
2502 R->getVPRecipeID() <= VPRecipeBase::VPLastHeaderPHISC;
2503 }
2504 static inline bool classof(const VPValue *V) {
2505 return isa<VPHeaderPHIRecipe>(V->getDefiningRecipe());
2506 }
2507 static inline bool classof(const VPSingleDefRecipe *R) {
2508 return isa<VPHeaderPHIRecipe>(static_cast<const VPRecipeBase *>(R));
2509 }
2510
2511 /// Generate the phi nodes.
2512 void execute(VPTransformState &State) override = 0;
2513
2514 /// Return the cost of this header phi recipe.
2516 VPCostContext &Ctx) const override;
2517
2518 /// Returns the start value of the phi, if one is set.
2520 return getNumOperands() == 0 ? nullptr : getOperand(0);
2521 }
2523 return getNumOperands() == 0 ? nullptr : getOperand(0);
2524 }
2525
2526 /// Update the start value of the recipe.
2528
2529 /// Returns the incoming value from the loop backedge.
2530 virtual VPValue *getBackedgeValue() { return getOperand(1); }
2531
2532 /// Update the incoming value from the loop backedge.
2534
2535 /// Add \p V as the incoming value from the loop backedge.
2537 assert(getNumOperands() == 1 &&
2538 "backedge value must be appended right after construction");
2539 assert(V->getScalarType() == getScalarType() &&
2540 "backedge value must have the same type as the start value");
2542 }
2543
2544protected:
2545#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2546 /// Print the recipe.
2547 void printRecipe(raw_ostream &O, const Twine &Indent,
2548 VPSlotTracker &SlotTracker) const override = 0;
2549#endif
2550};
2551
2552/// Base class for widened induction (VPWidenIntOrFpInductionRecipe and
2553/// VPWidenPointerInductionRecipe), providing shared functionality, including
2554/// retrieving the step value, induction descriptor and original phi node.
2556 InductionDescriptor IndDesc;
2557
2558public:
2560 VPValue *Step, const InductionDescriptor &IndDesc,
2561 Type *ResultTy, DebugLoc DL)
2562 : VPHeaderPHIRecipe(Kind, IV, Start, ResultTy, DL), IndDesc(IndDesc) {
2563 addOperand(Step);
2564 }
2565
2566 /// After unrolling, append the splat-VF step (`VF * step`) and the value of
2567 /// the induction at the last unrolled part.
2568 void addUnrolledPartOperands(VPValue *SplatVFStep, VPValue *LastPart) {
2569 assert(LastPart->getScalarType() == getScalarType() &&
2570 "last-part value must match the induction recipe's scalar type");
2572 ? SplatVFStep->getScalarType()->isIntegerTy()
2573 : SplatVFStep->getScalarType() == getScalarType()) &&
2574 "splat-step must match the induction type for non-pointer "
2575 "inductions, or be an integer index for pointer inductions");
2576 VPUser::addOperand(SplatVFStep);
2577 VPUser::addOperand(LastPart);
2578 }
2579
2580 static inline bool classof(const VPRecipeBase *R) {
2581 return R->getVPRecipeID() == VPRecipeBase::VPWidenIntOrFpInductionSC ||
2582 R->getVPRecipeID() == VPRecipeBase::VPWidenPointerInductionSC;
2583 }
2584
2585 static inline bool classof(const VPValue *V) {
2586 auto *R = V->getDefiningRecipe();
2587 return R && classof(R);
2588 }
2589
2590 static inline bool classof(const VPSingleDefRecipe *R) {
2591 return classof(static_cast<const VPRecipeBase *>(R));
2592 }
2593
2594 void execute(VPTransformState &State) override = 0;
2595
2596 /// Returns the step value of the induction.
2598 const VPValue *getStepValue() const { return getOperand(1); }
2599
2601 const VPValue *getVFValue() const { return getOperand(2); }
2602
2603 /// Returns the number of incoming values, also number of incoming blocks.
2604 /// Note that at the moment, VPWidenPointerInductionRecipe only has a single
2605 /// incoming value, its start value.
2606 unsigned getNumIncoming() const override { return 1; }
2607
2608 /// Returns the underlying PHINode if one exists, or null otherwise.
2612
2613 /// Returns the induction descriptor for the recipe.
2614 const InductionDescriptor &getInductionDescriptor() const { return IndDesc; }
2615
2616 /// Returns the SCEV predicates associated with this induction.
2618 return IndDesc.getNoWrapPredicates();
2619 }
2620
2622 // TODO: All operands of base recipe must exist and be at same index in
2623 // derived recipe.
2625 "VPWidenIntOrFpInductionRecipe generates its own backedge value");
2626 }
2627
2628 /// Returns true if the recipe only uses the first lane of operand \p Op.
2629 bool usesFirstLaneOnly(const VPValue *Op) const override {
2631 "Op must be an operand of the recipe");
2632 // The recipe creates its own wide start value, so it only requests the
2633 // first lane of the operand.
2634 // TODO: Remove once creating the start value is modeled separately.
2635 return Op == getStartValue() || Op == getStepValue();
2636 }
2637};
2638
2639/// A recipe for handling phi nodes of integer and floating-point inductions,
2640/// producing their vector values. This is an abstract recipe and must be
2641/// converted to concrete recipes before executing.
2643 public VPIRFlags {
2644 // If this recipe is unrolled it will have 2 additional operands.
2645 bool isUnrolled() const { return getNumOperands() == 5; }
2646
2647public:
2649 VPValue *VF, const InductionDescriptor &IndDesc,
2650 const VPIRFlags &Flags, DebugLoc DL)
2651 : VPWidenInductionRecipe(VPRecipeBase::VPWidenIntOrFpInductionSC, IV,
2652 Start, Step, IndDesc, Start->getScalarType(),
2653 DL),
2654 VPIRFlags(Flags) {
2655 addOperand(VF);
2656 }
2657
2659 VPValue *VF, const InductionDescriptor &IndDesc,
2660 Type *ResultTy, const VPIRFlags &Flags,
2661 DebugLoc DL)
2662 : VPWidenInductionRecipe(VPRecipeBase::VPWidenIntOrFpInductionSC, IV,
2663 Start, Step, IndDesc, ResultTy, DL),
2664 VPIRFlags(Flags) {
2665 addOperand(VF);
2666 }
2667
2669
2675
2676 VP_CLASSOF_IMPL(VPRecipeBase::VPWidenIntOrFpInductionSC)
2677
2678 void execute(VPTransformState &State) override {
2679 llvm_unreachable("cannot execute this recipe, should be expanded via "
2680 "expandVPWidenIntOrFpInductionRecipe");
2681 }
2682
2683 /// If the recipe has been unrolled, return the VPValue for the induction
2684 /// increment, otherwise return null.
2686 return isUnrolled() ? getOperand(getNumOperands() - 2) : nullptr;
2687 }
2688
2689 /// Returns the number of incoming values, also number of incoming blocks.
2690 /// Note that at the moment, VPWidenIntOrFpInductionRecipes only have a single
2691 /// incoming value, its start value.
2692 unsigned getNumIncoming() const override { return 1; }
2693
2694 /// Returns true if this induction is evaluated in a narrower type than the
2695 /// start value.
2701
2702 /// Return the cost of this VPWidenIntOrFpInductionRecipe.
2704 VPCostContext &Ctx) const override;
2705
2706 /// Returns true if the induction is canonical, i.e. starting at 0 and
2707 /// incremented by UF * VF (= the original IV is incremented by 1) and has the
2708 /// same type as the canonical induction.
2709 bool isCanonical() const;
2710
2711 /// Returns the VPValue representing the value of this induction at
2712 /// the last unrolled part, if it exists. Returns itself if unrolling did not
2713 /// take place.
2715 return isUnrolled() ? getLastOperand() : this;
2716 }
2717
2718protected:
2719#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2720 /// Print the recipe.
2721 void printRecipe(raw_ostream &O, const Twine &Indent,
2722 VPSlotTracker &SlotTracker) const override;
2723#endif
2724};
2725
2727public:
2728 /// Create a new VPWidenPointerInductionRecipe for \p Phi with start value \p
2729 /// Start and the number of elements unrolled \p NumUnrolledElems, typically
2730 /// VF*UF.
2732 VPValue *NumUnrolledElems,
2733 const InductionDescriptor &IndDesc, DebugLoc DL)
2734 : VPWidenInductionRecipe(VPRecipeBase::VPWidenPointerInductionSC, Phi,
2735 Start, Step, IndDesc, Start->getScalarType(),
2736 DL) {
2737 addOperand(NumUnrolledElems);
2738 }
2739
2741
2747
2748 VP_CLASSOF_IMPL(VPRecipeBase::VPWidenPointerInductionSC)
2749
2750 /// Generate vector values for the pointer induction.
2751 void execute(VPTransformState &State) override {
2752 llvm_unreachable("cannot execute this recipe, should be expanded via "
2753 "expandVPWidenPointerInduction");
2754 };
2755
2756 /// Returns true if only scalar values will be generated.
2758
2759 /// Return the cost of this VPWidenPointerInductionRecipe.
2761 VPCostContext &Ctx) const override;
2762
2763protected:
2764#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2765 /// Print the recipe.
2766 void printRecipe(raw_ostream &O, const Twine &Indent,
2767 VPSlotTracker &SlotTracker) const override;
2768#endif
2769};
2770
2771/// A recipe for widened phis. Incoming values are operands of the recipe and
2772/// their operand index corresponds to the incoming predecessor block. If the
2773/// recipe is placed in an entry block to a (non-replicate) region, it must have
2774/// exactly 2 incoming values, the first from the predecessor of the region and
2775/// the second from the exiting block of the region.
2777 public VPPhiAccessors {
2778 /// Name to use for the generated IR instruction for the widened phi.
2779 std::string Name;
2780
2781public:
2782 /// Create a new VPWidenPHIRecipe with incoming values \p IncomingValues,
2783 /// debug location \p DL and \p Name.
2785 DebugLoc DL = DebugLoc::getUnknown(), const Twine &Name = "")
2786 : VPSingleDefRecipe(VPRecipeBase::VPWidenPHISC, IncomingValues,
2787 IncomingValues[0]->getScalarType(),
2788 /*UV=*/nullptr, DL),
2789 Name(Name.str()) {
2790 assert(all_of(IncomingValues,
2791 [this](VPValue *VPV) {
2792 return VPV->getScalarType() == getScalarType();
2793 }) &&
2794 "all incoming values must have the same type");
2795 }
2796
2798 return new VPWidenPHIRecipe(operands(), getDebugLoc(), Name);
2799 }
2800
2801 ~VPWidenPHIRecipe() override = default;
2802
2803 /// This recipe generates a PHI.
2804 unsigned getOpcode() const { return Instruction::PHI; }
2805
2806 VP_CLASSOF_IMPL(VPRecipeBase::VPWidenPHISC)
2807
2808 /// Generate the phi/select nodes.
2809 void execute(VPTransformState &State) override;
2810
2811 /// Return the cost of this VPWidenPHIRecipe.
2812 InstructionCost computeCost(ElementCount VF,
2813 VPCostContext &Ctx) const override;
2814
2815protected:
2816#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2817 /// Print the recipe.
2818 void printRecipe(raw_ostream &O, const Twine &Indent,
2819 VPSlotTracker &SlotTracker) const override;
2820#endif
2821
2822 const VPRecipeBase *getAsRecipe() const override { return this; }
2823};
2824
2825/// A recipe for handling first-order recurrence phis. The start value is the
2826/// first operand of the recipe and the incoming value from the backedge is the
2827/// second operand.
2830 VPValue &BackedgeValue)
2831 : VPHeaderPHIRecipe(VPRecipeBase::VPFirstOrderRecurrencePHISC, Phi,
2832 &Start, Start.getScalarType()) {
2833 addOperand(&BackedgeValue);
2834 }
2835
2836 VP_CLASSOF_IMPL(VPRecipeBase::VPFirstOrderRecurrencePHISC)
2837
2842
2843 void execute(VPTransformState &State) override;
2844
2845 /// Return the cost of this first-order recurrence phi recipe.
2847 VPCostContext &Ctx) const override;
2848
2849 /// Returns true if the recipe only uses the first lane of operand \p Op.
2850 bool usesFirstLaneOnly(const VPValue *Op) const override {
2852 "Op must be an operand of the recipe");
2853 return Op == getStartValue();
2854 }
2855
2856protected:
2857#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2858 /// Print the recipe.
2859 void printRecipe(raw_ostream &O, const Twine &Indent,
2860 VPSlotTracker &SlotTracker) const override;
2861#endif
2862};
2863
2864/// Possible variants of a reduction.
2865
2866/// This reduction is ordered and in-loop.
2867struct RdxOrdered {};
2868/// This reduction is in-loop.
2869struct RdxInLoop {};
2870/// This reduction is unordered with the partial result scaled down by some
2871/// factor.
2874};
2875using ReductionStyle = std::variant<RdxOrdered, RdxInLoop, RdxUnordered>;
2876
2877inline ReductionStyle getReductionStyle(bool InLoop, bool Ordered,
2878 unsigned ScaleFactor) {
2879 assert((!Ordered || InLoop) && "Ordered implies in-loop");
2880 if (Ordered)
2881 return RdxOrdered{};
2882 if (InLoop)
2883 return RdxInLoop{};
2884 return RdxUnordered{/*VFScaleFactor=*/ScaleFactor};
2885}
2886
2887/// A recipe for handling reduction phis. The start value is the first operand
2888/// of the recipe and the incoming value from the backedge is the second
2889/// operand.
2891 /// The recurrence kind of the reduction.
2892 const RecurKind Kind;
2893
2894 ReductionStyle Style;
2895
2896 /// The phi is part of a multi-use reduction (e.g., used in FindIV
2897 /// patterns for argmin/argmax).
2898 /// TODO: Also support cases where the phi itself has a single use, but its
2899 /// compare has multiple uses.
2900 bool HasUsesOutsideReductionChain;
2901
2902 /// Temporary flag indicating that the FindIV reduction expression has been
2903 /// sunk. While this is true, epilogue vectorization is disabled to avoid
2904 /// applying the sunk expression twice (once in the main vector loop and again
2905 /// in the epilogue), which can produce incorrect results by applying the sunk
2906 /// operation twice.
2907 /// TODO: Remove this flag once epilogue vectorization properly supports
2908 /// sunk FindIV expressions.
2909 bool ExpressionSunk = false;
2910
2911public:
2912 /// Create a new VPReductionPHIRecipe for the reduction \p Phi.
2914 VPValue &BackedgeValue, ReductionStyle Style,
2915 const VPIRFlags &Flags,
2916 bool HasUsesOutsideReductionChain = false)
2917 : VPHeaderPHIRecipe(VPRecipeBase::VPReductionPHISC, Phi, &Start,
2918 Start.getScalarType()),
2919 VPIRFlags(Flags), Kind(Kind), Style(Style),
2920 HasUsesOutsideReductionChain(HasUsesOutsideReductionChain) {
2921 addOperand(&BackedgeValue);
2922 }
2923
2924 ~VPReductionPHIRecipe() override = default;
2925
2927 VPValue *BackedgeValue) {
2928 auto *Clone = new VPReductionPHIRecipe(
2930 *Start, *BackedgeValue, Style, *this, HasUsesOutsideReductionChain);
2931 Clone->ExpressionSunk = ExpressionSunk;
2932 return Clone;
2933 }
2934
2938
2939 VP_CLASSOF_IMPL(VPRecipeBase::VPReductionPHISC)
2940
2941 /// Generate the phi/select nodes.
2942 void execute(VPTransformState &State) override;
2943
2944 /// Get the factor that the VF of this recipe's output should be scaled by, or
2945 /// 1 if it isn't scaled.
2946 unsigned getVFScaleFactor() const {
2947 auto *Partial = std::get_if<RdxUnordered>(&Style);
2948 return Partial ? Partial->VFScaleFactor : 1;
2949 }
2950
2951 /// Set the VFScaleFactor for this reduction phi. Can only be set to a factor
2952 /// > 1.
2953 void setVFScaleFactor(unsigned ScaleFactor) {
2954 assert(ScaleFactor > 1 && "must set to scale factor > 1");
2955 Style = RdxUnordered{ScaleFactor};
2956 }
2957
2958 /// Returns the recurrence kind of the reduction.
2959 RecurKind getRecurrenceKind() const { return Kind; }
2960
2961 /// Returns true, if the phi is part of an ordered reduction.
2962 bool isOrdered() const { return std::holds_alternative<RdxOrdered>(Style); }
2963
2964 /// Returns true if the phi is part of an in-loop reduction.
2965 bool isInLoop() const {
2966 return std::holds_alternative<RdxInLoop>(Style) ||
2967 std::holds_alternative<RdxOrdered>(Style);
2968 }
2969
2970 /// Returns true, if the phi is part of a multi-use reduction.
2972 return HasUsesOutsideReductionChain;
2973 }
2974
2975 void setExpressionSunk() { ExpressionSunk = true; }
2976
2977 bool isExpressionSunk() const { return ExpressionSunk; }
2978
2979 /// Returns true if the recipe only uses the first lane of operand \p Op.
2980 bool usesFirstLaneOnly(const VPValue *Op) const override {
2982 "Op must be an operand of the recipe");
2983 return isOrdered() || isInLoop();
2984 }
2985
2986protected:
2987#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2988 /// Print the recipe.
2989 void printRecipe(raw_ostream &O, const Twine &Indent,
2990 VPSlotTracker &SlotTracker) const override;
2991#endif
2992};
2993
2994/// A recipe for handling scalar conditional induction PHIs. The start value is
2995/// the first operand of the recipe and the incoming value from the backedge is
2996/// the second operand.
2998 const SCEV *StepSCEV = nullptr;
2999
3000public:
3002 VPValue &BackedgeValue, const SCEV *StepSCEV)
3003 : VPHeaderPHIRecipe(VPRecipeBase::VPConditionalInductionPHISC, &Phi,
3004 &Start, Start.getScalarType()),
3005 StepSCEV(StepSCEV) {
3006 addOperand(&BackedgeValue);
3007 }
3008
3010
3011 /// Returns the underlying PHINode.
3013
3014 /// Returns the conditional induction step SCEV expression.
3015 const SCEV *getStepSCEV() const { return StepSCEV; }
3016
3021
3022 VP_CLASSOF_IMPL(VPRecipeBase::VPConditionalInductionPHISC)
3023
3025 return R->getVPRecipeID() == VPRecipeBase::VPConditionalInductionPHISC;
3026 }
3027
3028 void execute(VPTransformState &) override {
3029 llvm_unreachable("must be expanded before final execute");
3030 }
3031
3033 VPCostContext &Ctx) const override;
3034
3035#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3036 /// Print the recipe.
3037 void printRecipe(raw_ostream &O, const Twine &Indent,
3038 VPSlotTracker &SlotTracker) const override;
3039#endif
3040
3041 /// Returns true if the recipe only uses the first lane of operand \p Op.
3042 bool usesFirstLaneOnly(const VPValue *Op) const override {
3044 "Op must be an operand of the recipe");
3045 return true;
3046 }
3047};
3048
3049/// A recipe for vectorizing a phi-node as a sequence of mask-based select
3050/// instructions.
3052public:
3053 /// The blend operation is a User of the incoming values and of their
3054 /// respective masks, ordered [I0, M0, I1, M1, I2, M2, ...]. Note that M0 can
3055 /// be omitted (implied by passing an odd number of operands) in which case
3056 /// all other incoming values are merged into it.
3058 const VPIRFlags &Flags, DebugLoc DL)
3060 Operands[0]->getScalarType(), Flags, DL) {
3061 assert(Operands.size() >= 2 && "Expected at least two operands!");
3063 [this](unsigned I) {
3064 return getIncomingValue(I)->getScalarType() ==
3065 getScalarType();
3066 }) &&
3067 "all incoming values must have the same type");
3069 [this](unsigned I) {
3070 return getMask(I)->getScalarType()->isIntegerTy(1);
3071 }) &&
3072 "masks must be a bool");
3073 assert(hasRequiredFlagsForOpcode(Instruction::PHI, getScalarType()) &&
3074 "blends require the flags of the phi they replace");
3075 setUnderlyingValue(Phi);
3076 }
3077
3079
3082 NewOperands, *this, getDebugLoc());
3083 }
3084
3085 VP_CLASSOF_IMPL(VPRecipeBase::VPBlendSC)
3086
3087 /// A normalized blend is one that has an odd number of operands, whereby the
3088 /// first operand does not have an associated mask.
3089 bool isNormalized() const { return getNumOperands() % 2; }
3090
3091 /// Return the number of incoming values, taking into account when normalized
3092 /// the first incoming value will have no mask.
3093 unsigned getNumIncomingValues() const {
3094 return (getNumOperands() + isNormalized()) / 2;
3095 }
3096
3097 /// Return incoming value number \p Idx.
3098 VPValue *getIncomingValue(unsigned Idx) const {
3099 return Idx == 0 ? getOperand(0) : getOperand(Idx * 2 - isNormalized());
3100 }
3101
3102 /// Return mask number \p Idx.
3103 VPValue *getMask(unsigned Idx) const {
3104 assert((Idx > 0 || !isNormalized()) && "First index has no mask!");
3105 return Idx == 0 ? getOperand(1) : getOperand(Idx * 2 + !isNormalized());
3106 }
3107
3108 /// Set mask number \p Idx to \p V.
3109 void setMask(unsigned Idx, VPValue *V) {
3110 assert((Idx > 0 || !isNormalized()) && "First index has no mask!");
3111 assert(V->getScalarType()->isIntegerTy(1) && "Mask must be an i1 (vector)");
3112 Idx == 0 ? setOperand(1, V) : setOperand(Idx * 2 + !isNormalized(), V);
3113 }
3114
3115 void execute(VPTransformState &State) override {
3116 llvm_unreachable("VPBlendRecipe should be expanded by simplifyBlends");
3117 }
3118
3119 /// Return the cost of this VPWidenMemoryRecipe.
3120 InstructionCost computeCost(ElementCount VF,
3121 VPCostContext &Ctx) const override;
3122
3123 /// Returns true if the recipe only uses the first lane of operand \p Op.
3124 bool usesFirstLaneOnly(const VPValue *Op) const override;
3125
3126protected:
3127#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3128 /// Print the recipe.
3129 void printRecipe(raw_ostream &O, const Twine &Indent,
3130 VPSlotTracker &SlotTracker) const override;
3131#endif
3132};
3133
3134/// A common base class for interleaved memory operations.
3135/// An Interleaved memory operation is a memory access method that combines
3136/// multiple strided loads/stores into a single wide load/store with shuffles.
3137/// The first operand is the start address. The optional operands are, in order,
3138/// the stored values and the mask.
3140 public VPIRMetadata {
3142
3143 /// Indicates if the interleave group is in a conditional block and requires a
3144 /// mask.
3145 bool HasMask = false;
3146
3147 /// Indicates if gaps between members of the group need to be masked out or if
3148 /// unusued gaps can be loaded speculatively.
3149 bool NeedsMaskForGaps = false;
3150
3151protected:
3153 ArrayRef<VPValue *> Operands,
3154 ArrayRef<VPValue *> StoredValues, VPValue *Mask,
3155 bool NeedsMaskForGaps, const VPIRMetadata &MD, DebugLoc DL)
3156 : VPRecipeBase(SC, Operands, DL), VPIRMetadata(MD), IG(IG),
3157 NeedsMaskForGaps(NeedsMaskForGaps) {
3158 // TODO: extend the masked interleaved-group support to reversed access.
3159 assert((!Mask || !IG->isReverse()) &&
3160 "Reversed masked interleave-group not supported.");
3161 if (StoredValues.empty()) {
3162 for (Instruction *Inst : IG->members()) {
3163 assert(!Inst->getType()->isVoidTy() && "must have result");
3164 new VPMultiDefValue(this, Inst, Inst->getType());
3165 }
3166 } else {
3167 for (auto *SV : StoredValues)
3168 addOperand(SV);
3169 }
3170 if (Mask) {
3171 HasMask = true;
3172 addOperand(Mask);
3173 }
3174 }
3175
3176public:
3177 VPInterleaveBase *clone() override = 0;
3178
3179 static inline bool classof(const VPRecipeBase *R) {
3180 return R->getVPRecipeID() == VPRecipeBase::VPInterleaveSC ||
3181 R->getVPRecipeID() == VPRecipeBase::VPInterleaveEVLSC;
3182 }
3183
3184 static inline bool classof(const VPUser *U) {
3185 auto *R = dyn_cast<VPRecipeBase>(U);
3186 return R && classof(R);
3187 }
3188
3189 /// Return the address accessed by this recipe.
3190 VPValue *getAddr() const {
3191 return getOperand(0); // Address is the 1st, mandatory operand.
3192 }
3193
3194 /// Return the mask used by this recipe. Note that a full mask is represented
3195 /// by a nullptr.
3196 VPValue *getMask() const {
3197 // Mask is optional and the last operand.
3198 return HasMask ? getLastOperand() : nullptr;
3199 }
3200
3201 /// Return true if the access needs a mask because of the gaps.
3202 bool needsMaskForGaps() const { return NeedsMaskForGaps; }
3203
3205
3206 Instruction *getInsertPos() const { return IG->getInsertPos(); }
3207
3208 void execute(VPTransformState &State) override {
3209 llvm_unreachable("VPInterleaveBase should not be instantiated.");
3210 }
3211
3212 /// Return the cost of this recipe.
3213 InstructionCost computeCost(ElementCount VF,
3214 VPCostContext &Ctx) const override;
3215
3216 /// Returns true if the recipe only uses the first lane of operand \p Op.
3217 bool usesFirstLaneOnly(const VPValue *Op) const override = 0;
3218
3219 /// Returns the number of stored operands of this interleave group. Returns 0
3220 /// for load interleave groups.
3221 virtual unsigned getNumStoreOperands() const = 0;
3222
3223 /// Return the VPValues stored by this interleave group. If it is a load
3224 /// interleave group, return an empty ArrayRef.
3226 return {op_end() - (getNumStoreOperands() + (HasMask ? 1 : 0)),
3228 }
3229};
3230
3231/// VPInterleaveRecipe is a recipe for transforming an interleave group of load
3232/// or stores into one wide load/store and shuffles. The first operand of a
3233/// VPInterleave recipe is the address, followed by the stored values, followed
3234/// by an optional mask.
3236public:
3238 ArrayRef<VPValue *> StoredValues, VPValue *Mask,
3239 bool NeedsMaskForGaps, const VPIRMetadata &MD, DebugLoc DL)
3240 : VPInterleaveBase(VPRecipeBase::VPInterleaveSC, IG, Addr, StoredValues,
3241 Mask, NeedsMaskForGaps, MD, DL) {}
3242
3243 ~VPInterleaveRecipe() override = default;
3244
3248 needsMaskForGaps(), *this, getDebugLoc());
3249 }
3250
3251 VP_CLASSOF_IMPL(VPRecipeBase::VPInterleaveSC)
3252
3253 /// Generate the wide load or store, and shuffles.
3254 void execute(VPTransformState &State) override;
3255
3256 bool usesFirstLaneOnly(const VPValue *Op) const override {
3258 "Op must be an operand of the recipe");
3259 return Op == getAddr() && !llvm::is_contained(getStoredValues(), Op);
3260 }
3261
3262 unsigned getNumStoreOperands() const override {
3263 return getNumOperands() - (getMask() ? 2 : 1);
3264 }
3265
3266protected:
3267#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3268 /// Print the recipe.
3269 void printRecipe(raw_ostream &O, const Twine &Indent,
3270 VPSlotTracker &SlotTracker) const override;
3271#endif
3272};
3273
3274/// A recipe for interleaved memory operations with vector-predication
3275/// intrinsics. The first operand is the address, the second operand is the
3276/// explicit vector length. Stored values and mask are optional operands.
3278public:
3280 : VPInterleaveBase(VPRecipeBase::VPInterleaveEVLSC,
3281 R.getInterleaveGroup(), {R.getAddr(), &EVL},
3282 R.getStoredValues(), Mask, R.needsMaskForGaps(), R,
3283 R.getDebugLoc()) {
3284 assert(!getInterleaveGroup()->isReverse() &&
3285 "Reversed interleave-group with tail folding is not supported.");
3286 assert(!needsMaskForGaps() && "Interleaved access with gap mask is not "
3287 "supported for scalable vector.");
3288 }
3289
3290 ~VPInterleaveEVLRecipe() override = default;
3291
3293 llvm_unreachable("cloning not implemented yet");
3294 }
3295
3296 VP_CLASSOF_IMPL(VPRecipeBase::VPInterleaveEVLSC)
3297
3298 /// The VPValue of the explicit vector length.
3299 VPValue *getEVL() const { return getOperand(1); }
3300
3301 /// Generate the wide load or store, and shuffles.
3302 void execute(VPTransformState &State) override;
3303
3304 /// The recipe only uses the first lane of the address, and EVL operand.
3305 bool usesFirstLaneOnly(const VPValue *Op) const override {
3307 "Op must be an operand of the recipe");
3308 return (Op == getAddr() && !llvm::is_contained(getStoredValues(), Op)) ||
3309 Op == getEVL();
3310 }
3311
3312 unsigned getNumStoreOperands() const override {
3313 return getNumOperands() - (getMask() ? 3 : 2);
3314 }
3315
3316protected:
3317#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3318 /// Print the recipe.
3319 void printRecipe(raw_ostream &O, const Twine &Indent,
3320 VPSlotTracker &SlotTracker) const override;
3321#endif
3322};
3323
3324/// A recipe to represent inloop, ordered or partial reduction operations. It
3325/// performs a reduction on a vector operand into a scalar (vector in the case
3326/// of a partial reduction) value, and adds the result to a chain. The Operands
3327/// are {ChainOp, VecOp, [Condition]}.
3329
3330 /// The recurrence kind for the reduction in question.
3331 RecurKind RdxKind;
3332 /// Whether the reduction is conditional.
3333 bool IsConditional = false;
3334 ReductionStyle Style;
3335
3336protected:
3339 VPValue *CondOp, ReductionStyle Style, DebugLoc DL)
3341 DL),
3342 RdxKind(RdxKind), Style(Style) {
3344 [this](VPValue *VPV) {
3345 return VPV->getScalarType() == getScalarType() ||
3346 (isa<VPInstruction>(VPV) &&
3347 cast<VPInstruction>(VPV)->getOpcode() ==
3349 }) &&
3350 "all incoming values must have the same type");
3351 if (CondOp) {
3352 assert(CondOp->getScalarType()->isIntegerTy(1) &&
3353 "CondOp must be a bool");
3354 IsConditional = true;
3355 addOperand(CondOp);
3356 }
3358 }
3359
3360public:
3362 VPValue *ChainOp, VPValue *VecOp, VPValue *CondOp,
3364 : VPReductionRecipe(VPRecipeBase::VPReductionSC, RdxKind, FMFs, I,
3365 {ChainOp, VecOp}, CondOp, Style, DL) {}
3366
3368 VPValue *ChainOp, VPValue *VecOp, VPValue *CondOp,
3370 : VPReductionRecipe(VPRecipeBase::VPReductionSC, RdxKind, FMFs, nullptr,
3371 {ChainOp, VecOp}, CondOp, Style, DL) {}
3372
3373 ~VPReductionRecipe() override = default;
3374
3376 return new VPReductionRecipe(RdxKind, getFastMathFlagsOrNone(),
3378 getCondOp(), Style, getDebugLoc());
3379 }
3380
3381 static inline bool classof(const VPRecipeBase *R) {
3382 return R->getVPRecipeID() == VPRecipeBase::VPReductionSC ||
3383 R->getVPRecipeID() == VPRecipeBase::VPReductionEVLSC;
3384 }
3385
3386 static inline bool classof(const VPUser *U) {
3387 auto *R = dyn_cast<VPRecipeBase>(U);
3388 return R && classof(R);
3389 }
3390
3391 static inline bool classof(const VPValue *VPV) {
3392 const VPRecipeBase *R = VPV->getDefiningRecipe();
3393 return R && classof(R);
3394 }
3395
3396 static inline bool classof(const VPSingleDefRecipe *R) {
3397 return classof(static_cast<const VPRecipeBase *>(R));
3398 }
3399
3400 /// Generate the reduction in the loop.
3401 void execute(VPTransformState &State) override;
3402
3403 /// Return the cost of VPReductionRecipe.
3404 InstructionCost computeCost(ElementCount VF,
3405 VPCostContext &Ctx) const override;
3406
3407 /// Return the recurrence kind for the in-loop reduction.
3408 RecurKind getRecurrenceKind() const { return RdxKind; }
3409 /// Return true if the in-loop reduction is ordered.
3410 bool isOrdered() const { return std::holds_alternative<RdxOrdered>(Style); };
3411 /// Return true if the in-loop reduction is conditional.
3412 bool isConditional() const { return IsConditional; };
3413 /// Returns true if the reduction outputs a vector with a scaled down VF.
3414 bool isPartialReduction() const {
3415 return std::holds_alternative<RdxUnordered>(Style);
3416 }
3417 /// Returns true if the reduction is in-loop.
3418 bool isInLoop() const {
3419 return std::holds_alternative<RdxInLoop>(Style) ||
3420 std::holds_alternative<RdxOrdered>(Style);
3421 }
3422 /// The VPValue of the scalar Chain being accumulated.
3423 VPValue *getChainOp() const { return getOperand(0); }
3424 /// The VPValue of the vector value to be reduced.
3425 VPValue *getVecOp() const { return getOperand(1); }
3426 /// The VPValue of the condition for the block.
3428 return isConditional() ? getLastOperand() : nullptr;
3429 }
3430 /// Get the factor that the VF of this recipe's output should be scaled by, or
3431 /// 1 if it isn't scaled.
3432 unsigned getVFScaleFactor() const {
3433 auto *Partial = std::get_if<RdxUnordered>(&Style);
3434 return Partial ? Partial->VFScaleFactor : 1;
3435 }
3436
3437protected:
3438#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3439 /// Print the recipe.
3440 void printRecipe(raw_ostream &O, const Twine &Indent,
3441 VPSlotTracker &SlotTracker) const override;
3442#endif
3443};
3444
3445/// A recipe to represent inloop reduction operations with vector-predication
3446/// intrinsics, performing a reduction on a vector operand with the explicit
3447/// vector length (EVL) into a scalar value, and adding the result to a chain.
3448/// The Operands are {ChainOp, VecOp, EVL, [Condition]}.
3450public:
3453 : VPReductionRecipe(VPRecipeBase::VPReductionEVLSC, R.getRecurrenceKind(),
3456 {R.getChainOp(), R.getVecOp(), &EVL}, CondOp,
3457 getReductionStyle(R.isInLoop(), R.isOrdered(),
3458 R.getVFScaleFactor()),
3459 DL) {}
3460
3461 ~VPReductionEVLRecipe() override = default;
3462
3464 llvm_unreachable("cloning not implemented yet");
3465 }
3466
3467 VP_CLASSOF_IMPL(VPRecipeBase::VPReductionEVLSC)
3468
3469 /// Generate the reduction in the loop
3470 void execute(VPTransformState &State) override;
3471
3472 /// The VPValue of the explicit vector length.
3473 VPValue *getEVL() const { return getOperand(2); }
3474
3475 /// Returns true if the recipe only uses the first lane of operand \p Op.
3476 bool usesFirstLaneOnly(const VPValue *Op) const override {
3478 "Op must be an operand of the recipe");
3479 return Op == getEVL();
3480 }
3481
3482protected:
3483#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3484 /// Print the recipe.
3485 void printRecipe(raw_ostream &O, const Twine &Indent,
3486 VPSlotTracker &SlotTracker) const override;
3487#endif
3488};
3489
3490/// VPReplicateRecipe replicates a given instruction producing multiple scalar
3491/// copies of the original scalar type, one per lane, instead of producing a
3492/// single copy of widened type for all lanes. If the instruction is known to be
3493/// a single scalar, only one copy will be generated.
3495 public VPIRMetadata {
3496 /// Indicator if only a single replica per lane is needed.
3497 bool IsSingleScalar;
3498
3499 /// Indicator if the replicas are also predicated.
3500 bool IsPredicated;
3501
3502public:
3504 bool IsSingleScalar, VPValue *Mask = nullptr,
3505 const VPIRFlags &Flags = {}, VPIRMetadata Metadata = {},
3506 DebugLoc DL = DebugLoc::getUnknown())
3507 : VPRecipeWithIRFlags(VPRecipeBase::VPReplicateSC, Operands,
3508 computeScalarType(I, Operands), Flags, DL),
3509 VPIRMetadata(Metadata), IsSingleScalar(IsSingleScalar),
3510 IsPredicated(Mask) {
3511 assert((!IsSingleScalar || !I->isCast()) &&
3512 "Single-scalar casts should use VPInstruction");
3513 setUnderlyingValue(I);
3514 if (Mask)
3515 addOperand(Mask);
3516 }
3517
3518 ~VPReplicateRecipe() override = default;
3519
3520 /// Compute the scalar result type for a VPReplicateRecipe wrapping \p I with
3521 /// \p Operands (excluding any predicate mask).
3522 static Type *computeScalarType(const Instruction *I,
3524
3526
3528 return new VPReplicateRecipe(
3529 getUnderlyingInstr(), NewOperands, IsSingleScalar,
3530 isPredicated() ? getMask() : nullptr, *this, *this, getDebugLoc());
3531 }
3532
3533 VP_CLASSOF_IMPL(VPRecipeBase::VPReplicateSC)
3534
3535 /// Generate replicas of the desired Ingredient. Replicas will be generated
3536 /// for all parts and lanes unless a specific part and lane are specified in
3537 /// the \p State.
3538 void execute(VPTransformState &State) override;
3539
3540 /// Return the cost of this VPReplicateRecipe.
3541 InstructionCost computeCost(ElementCount VF,
3542 VPCostContext &Ctx) const override;
3543
3544 /// Return the cost of scalarizing a call to \p CalledFn with argument
3545 /// operands \p ArgOps for a given \p VF.
3546 static InstructionCost computeCallCost(Function *CalledFn, Type *ResultTy,
3548 bool IsSingleScalar, ElementCount VF,
3549 VPCostContext &Ctx);
3550
3551 /// Returns true if the recipe produces a single scalar value.
3552 bool isSingleScalar() const { return IsSingleScalar; }
3553
3554 /// Returns true if the recipe produces scalar values for all VF lanes.
3555 bool doesGeneratePerAllLanes() const { return !IsSingleScalar; }
3556
3557 bool isPredicated() const { return IsPredicated; }
3558
3559 /// Returns true if the recipe only uses the first lane of operand \p Op.
3560 bool usesFirstLaneOnly(const VPValue *Op) const override {
3562 "Op must be an operand of the recipe");
3563 return isSingleScalar();
3564 }
3565
3566 /// Returns true if the recipe uses scalars of operand \p Op.
3567 bool usesScalars(const VPValue *Op) const override {
3569 "Op must be an operand of the recipe");
3570 return true;
3571 }
3572
3573 /// Return the mask of a predicated VPReplicateRecipe.
3575 assert(isPredicated() && "Trying to get the mask of a unpredicated recipe");
3576 return getLastOperand();
3577 }
3578
3579 /// Return the recipe's operands, excluding the mask of a predicated recipe.
3583
3584 /// Returns the number of operands, excluding the mask if the recipe is
3585 /// predicated.
3586 unsigned getNumOperandsWithoutMask() const {
3587 return getNumOperands() - isPredicated();
3588 }
3589
3590 unsigned getOpcode() const { return getUnderlyingInstr()->getOpcode(); }
3591
3592protected:
3593#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3594 /// Print the recipe.
3595 void printRecipe(raw_ostream &O, const Twine &Indent,
3596 VPSlotTracker &SlotTracker) const override;
3597#endif
3598};
3599
3600/// A recipe for generating conditional branches on the bits of a mask.
3602 public VPIRMetadata {
3603public:
3605 const VPIRMetadata &Metadata = {})
3606 : VPRecipeBase(VPRecipeBase::VPBranchOnMaskSC, {BlockInMask}, DL),
3607 VPIRMetadata(Metadata) {}
3608
3610 return new VPBranchOnMaskRecipe(getOperand(0), getDebugLoc(), *this);
3611 }
3612
3613 VP_CLASSOF_IMPL(VPRecipeBase::VPBranchOnMaskSC)
3614
3615 /// Generate the extraction of the appropriate bit from the block mask and the
3616 /// conditional branch.
3617 void execute(VPTransformState &State) override;
3618
3619 /// Return the cost of this VPBranchOnMaskRecipe.
3620 InstructionCost computeCost(ElementCount VF,
3621 VPCostContext &Ctx) const override;
3622
3623#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3624 /// Print the recipe.
3625 void printRecipe(raw_ostream &O, const Twine &Indent,
3626 VPSlotTracker &SlotTracker) const override {
3627 O << Indent << "BRANCH-ON-MASK ";
3629 }
3630#endif
3631
3632 /// Returns true if the recipe uses scalars of operand \p Op.
3633 bool usesScalars(const VPValue *Op) const override {
3635 "Op must be an operand of the recipe");
3636 return true;
3637 }
3638};
3639
3640/// A recipe to combine multiple recipes into a single 'expression' recipe,
3641/// which should be considered a single entity for cost-modeling and transforms.
3642/// The recipe needs to be 'decomposed', i.e. replaced by its individual
3643/// expression recipes, before execute. The individual expression recipes are
3644/// completely disconnected from the def-use graph of other recipes not part of
3645/// the expression. Def-use edges between pairs of expression recipes remain
3646/// intact, whereas every edge between an expression recipe and a recipe outside
3647/// the expression is elevated to connect the non-expression recipe with the
3648/// VPExpressionRecipe itself.
3650 /// Recipes included in this VPExpressionRecipe. This could contain
3651 /// duplicates.
3652 SmallVector<VPSingleDefRecipe *> ExpressionRecipes;
3653
3654 /// Temporary VPValues used for external operands of the expression, i.e.
3655 /// operands not defined by recipes in the expression.
3656 SmallVector<VPValue *> LiveInPlaceholders;
3657
3658 enum class ExpressionTypes {
3659 /// Represents an inloop extended reduction operation, performing a
3660 /// reduction on an extended vector operand into a scalar value, and adding
3661 /// the result to a chain.
3662 ExtendedReduction,
3663 /// Represents an inloop extended reduction operation, which is negated,
3664 /// then reduced before adding the result to a chain.
3665 NegatedExtendedReduction,
3666 /// Represent an inloop multiply-accumulate reduction, multiplying the
3667 /// extended vector operands, performing a reduction.add on the result, and
3668 /// adding the scalar result to a chain.
3669 ExtMulAccReduction,
3670 /// Represent an inloop multiply-accumulate reduction, multiplying the
3671 /// vector operands, performing a reduction.add on the result, and adding
3672 /// the scalar result to a chain.
3673 MulAccReduction,
3674 /// Represent an inloop multiply-accumulate reduction, multiplying the
3675 /// extended vector operands, negating the multiplication, performing a
3676 /// reduction.add on the result, and adding the scalar result to a chain.
3677 ExtNegatedMulAccReduction,
3678 };
3679
3680 /// Type of the expression.
3681 ExpressionTypes ExpressionType;
3682
3683public:
3684 /// Construct a new VPExpressionRecipe by internalizing recipes in \p
3685 /// ExpressionRecipes. External operands (i.e. not defined by another recipe
3686 /// in the expression) are replaced by temporary VPValues and the original
3687 /// operands are transferred to the VPExpressionRecipe itself. Clone recipes
3688 /// as needed (excluding last) to ensure they are only used by other recipes
3689 /// in the expression.
3690 VPExpressionRecipe(ExpressionTypes ExpressionType,
3691 ArrayRef<VPSingleDefRecipe *> ExpressionRecipes);
3692
3694 : VPExpressionRecipe(ExpressionTypes::ExtendedReduction, {Ext, Red}) {}
3696 VPReductionRecipe *Red)
3697 : VPExpressionRecipe(ExpressionTypes::NegatedExtendedReduction,
3698 {Ext, Neg, Red}) {
3699 assert((Red->getRecurrenceKind() == RecurKind::Add ||
3700 Red->getRecurrenceKind() == RecurKind::FAdd ||
3701 Red->getRecurrenceKind() == RecurKind::AddChainWithSubs) &&
3702 "Expected an add or add-chain-with-subs reduction");
3703 if (Neg->getOpcode() == Instruction::Sub) {
3704 [[maybe_unused]] auto *SubConst = dyn_cast<VPConstantInt>(getOperand(1));
3705 assert(SubConst && SubConst->isZero() && "Expected a negating sub");
3706 } else
3707 assert(Neg->getOpcode() == Instruction::FNeg && "Unexpected opcode");
3708 }
3710 : VPExpressionRecipe(ExpressionTypes::MulAccReduction, {Mul, Red}) {}
3713 : VPExpressionRecipe(ExpressionTypes::ExtMulAccReduction,
3714 {Ext0, Ext1, Mul, Red}) {}
3717 VPReductionRecipe *Red)
3718 : VPExpressionRecipe(ExpressionTypes::ExtNegatedMulAccReduction,
3719 {Ext0, Ext1, Mul, Neg, Red}) {
3720 assert((Mul->getOpcode() == Instruction::Mul ||
3721 Mul->getOpcode() == Instruction::FMul) &&
3722 "Expected a mul");
3723 assert((Red->getRecurrenceKind() == RecurKind::Add ||
3724 Red->getRecurrenceKind() == RecurKind::FAdd ||
3725 Red->getRecurrenceKind() == RecurKind::AddChainWithSubs) &&
3726 "Expected an add or add-chain-with-subs reduction");
3727 assert(getNumOperands() >= 3 && "Expected at least three operands");
3728 if (Neg->getOpcode() == Instruction::Sub) {
3729 [[maybe_unused]] auto *SubConst = dyn_cast<VPConstantInt>(getOperand(2));
3730 assert(SubConst && SubConst->isZero() &&
3731 Neg->getOpcode() == Instruction::Sub && "Expected a negating sub");
3732 } else
3733 assert(Neg->getOpcode() == Instruction::FNeg && "Unexpected opcode");
3734 }
3735
3737 SmallPtrSet<VPSingleDefRecipe *, 4> ExpressionRecipesSeen;
3738 for (auto *R : reverse(ExpressionRecipes)) {
3739 if (ExpressionRecipesSeen.insert(R).second)
3740 delete R;
3741 }
3742 for (VPValue *T : LiveInPlaceholders)
3743 delete T;
3744 }
3745
3746 VP_CLASSOF_IMPL(VPRecipeBase::VPExpressionSC)
3747
3749 assert(!ExpressionRecipes.empty() && "empty expressions should be removed");
3750 SmallVector<VPSingleDefRecipe *> NewExpressiondRecipes;
3751 for (auto *R : ExpressionRecipes)
3752 NewExpressiondRecipes.push_back(R->clone());
3753 for (auto *New : NewExpressiondRecipes) {
3754 for (const auto &[Idx, Old] : enumerate(ExpressionRecipes))
3755 New->replaceUsesOfWith(Old, NewExpressiondRecipes[Idx]);
3756 // Update placeholder operands in the cloned recipe to use the external
3757 // operands, to be internalized when the cloned expression is constructed.
3758 for (const auto &[Placeholder, OutsideOp] :
3759 zip(LiveInPlaceholders, operands()))
3760 New->replaceUsesOfWith(Placeholder, OutsideOp);
3761 }
3762 return new VPExpressionRecipe(ExpressionType, NewExpressiondRecipes);
3763 }
3764
3765 /// Return and insert the recipes of the expression back into the VPlan,
3766 /// directly before the current recipe. Leaves the expression recipe empty,
3767 /// which must be removed before codegen.
3769
3770 /// Returns the expression type of this recipe.
3771 ExpressionTypes getExpressionType() const { return ExpressionType; }
3772
3773 unsigned getVFScaleFactor() const {
3774 auto *PR = dyn_cast<VPReductionRecipe>(ExpressionRecipes.back());
3775 return PR ? PR->getVFScaleFactor() : 1;
3776 }
3777
3778 /// Method for generating code, must not be called as this recipe is abstract.
3779 void execute(VPTransformState &State) override {
3780 llvm_unreachable("recipe must be removed before execute");
3781 }
3782
3784 VPCostContext &Ctx) const override;
3785
3786 /// Returns true if this expression contains recipes that may read from or
3787 /// write to memory.
3788 bool mayReadOrWriteMemory() const;
3789
3790 /// Returns true if this expression contains recipes that may have side
3791 /// effects.
3792 bool mayHaveSideEffects() const;
3793
3794 /// Returns true if this VPExpressionRecipe produces a single scalar.
3795 bool isVectorToScalar() const;
3796
3797protected:
3798#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3799 /// Print the recipe.
3800 void printRecipe(raw_ostream &O, const Twine &Indent,
3801 VPSlotTracker &SlotTracker) const override;
3802#endif
3803};
3804
3805/// VPPredInstPHIRecipe is a recipe for generating the phi nodes needed when
3806/// control converges back from a Branch-on-Mask. The phi nodes are needed in
3807/// order to merge values that are set under such a branch and feed their uses.
3808/// The phi nodes can be scalar or vector depending on the users of the value.
3809/// This recipe works in concert with VPBranchOnMaskRecipe.
3811public:
3812 /// Construct a VPPredInstPHIRecipe given \p PredInst whose value needs a phi
3813 /// nodes after merging back from a Branch-on-Mask.
3815 : VPSingleDefRecipe(VPRecipeBase::VPPredInstPHISC, PredV,
3816 PredV->getScalarType(), /*UV=*/nullptr, DL) {}
3817 ~VPPredInstPHIRecipe() override = default;
3818
3820 return new VPPredInstPHIRecipe(getOperand(0), getDebugLoc());
3821 }
3822
3823 VP_CLASSOF_IMPL(VPRecipeBase::VPPredInstPHISC)
3824
3825 /// Generates phi nodes for live-outs (from a replicate region) as needed to
3826 /// retain SSA form.
3827 void execute(VPTransformState &State) override;
3828
3829 /// Return the cost of this VPPredInstPHIRecipe.
3831 VPCostContext &Ctx) const override {
3832 // TODO: Compute accurate cost after retiring the legacy cost model.
3833 return 0;
3834 }
3835
3836protected:
3837#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3838 /// Print the recipe.
3839 void printRecipe(raw_ostream &O, const Twine &Indent,
3840 VPSlotTracker &SlotTracker) const override;
3841#endif
3842};
3843
3844/// A common mixin class for widening memory operations. An optional mask can be
3845/// provided as the last operand.
3847protected:
3849
3850 /// Alignment information for this memory access.
3852
3853 /// Whether the accessed addresses are consecutive.
3855
3856 /// Whether the memory access is masked.
3857 bool IsMasked = false;
3858
3859 void setMask(VPValue *Mask) {
3860 assert(!IsMasked && "cannot re-set mask");
3861 if (!Mask)
3862 return;
3863 assert(Mask->getScalarType()->isIntegerTy(1) &&
3864 "Mask must be an i1 (vector)");
3865 getAsRecipe()->addOperand(Mask);
3866 IsMasked = true;
3867 }
3868
3873
3874public:
3875 virtual ~VPWidenMemoryRecipe() = default;
3876
3877 /// Return a VPRecipeBase* to the current object.
3879 virtual const VPRecipeBase *getAsRecipe() const = 0;
3880
3881 /// Return whether the loaded-from / stored-to addresses are consecutive.
3882 bool isConsecutive() const { return Consecutive; }
3883
3884 /// Return the address accessed by this recipe.
3885 VPValue *getAddr() const { return getAsRecipe()->getOperand(0); }
3886
3887 /// Returns true if the recipe is masked.
3888 bool isMasked() const { return IsMasked; }
3889
3890 /// Return the mask used by this recipe. Note that a full mask is represented
3891 /// by a nullptr.
3892 VPValue *getMask() const {
3893 // Mask is optional and therefore the last operand.
3894 const VPRecipeBase *R = getAsRecipe();
3895 return isMasked() ? R->getLastOperand() : nullptr;
3896 }
3897
3898 /// Returns the alignment of the memory access.
3899 Align getAlign() const { return Alignment; }
3900
3901 /// Return the cost of this VPWidenMemoryRecipe.
3902 InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const;
3903
3905};
3906
3907/// A recipe for widening load operations, using the address to load from and an
3908/// optional mask.
3910 public VPWidenMemoryRecipe {
3913 const VPIRMetadata &Metadata, DebugLoc DL)
3914 : VPSingleDefRecipe(VPRecipeBase::VPWidenLoadSC, {Addr}, Load.getType(),
3915 &Load, DL),
3916 VPWidenMemoryRecipe(Load, Alignment, Consecutive, Metadata) {
3917 setMask(Mask);
3918 }
3919
3922 getMask(), Consecutive, getAlign(), *this,
3923 getDebugLoc());
3924 }
3925
3926 VP_CLASSOF_IMPL(VPRecipeBase::VPWidenLoadSC);
3927
3928 /// Returns the opcode of the widened load.
3929 unsigned getOpcode() const { return Instruction::Load; }
3930
3931 /// Generate a wide load or gather.
3932 void execute(VPTransformState &State) override;
3933
3934 /// Return the cost of this VPWidenLoadRecipe.
3936 VPCostContext &Ctx) const override {
3937 return VPWidenMemoryRecipe::computeCost(VF, Ctx);
3938 }
3939
3940 /// Returns true if the recipe only uses the first lane of operand \p Op.
3941 bool usesFirstLaneOnly(const VPValue *Op) const override {
3943 "Op must be an operand of the recipe");
3944 // Widened, consecutive loads operations only demand the first lane of
3945 // their address.
3946 return Op == getAddr() && isConsecutive();
3947 }
3948
3949protected:
3950 VPRecipeBase *getAsRecipe() override;
3951 const VPRecipeBase *getAsRecipe() const override;
3952
3953#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3954 /// Print the recipe.
3955 void printRecipe(raw_ostream &O, const Twine &Indent,
3956 VPSlotTracker &SlotTracker) const override;
3957#endif
3958};
3959
3960/// A recipe for widening load operations with vector-predication intrinsics,
3961/// using the address to load from, the explicit vector length and an optional
3962/// mask.
3964 : public VPSingleDefRecipe,
3965 public VPWidenMemoryRecipe {
3967 VPValue *Mask)
3968 : VPSingleDefRecipe(VPRecipeBase::VPWidenLoadEVLSC, {Addr, &EVL},
3969 L.getIngredient().getType(), &L.getIngredient(),
3970 L.getDebugLoc()),
3971 VPWidenMemoryRecipe(L.getIngredient(), L.getAlign(), L.isConsecutive(),
3972 L) {
3973 setMask(Mask);
3974 }
3975
3977 llvm_unreachable("cloning not supported");
3978 }
3979
3980 VP_CLASSOF_IMPL(VPRecipeBase::VPWidenLoadEVLSC)
3981
3982 /// Returns the opcode of the widened load.
3983 unsigned getOpcode() const { return Instruction::Load; }
3984
3985 /// Return the EVL operand.
3986 VPValue *getEVL() const { return getOperand(1); }
3987
3988 /// Generate the wide load or gather.
3989 void execute(VPTransformState &State) override;
3990
3991 /// Return the cost of this VPWidenLoadEVLRecipe.
3992 InstructionCost computeCost(ElementCount VF,
3993 VPCostContext &Ctx) const override;
3994
3995 /// Returns true if the recipe only uses the first lane of operand \p Op.
3996 bool usesFirstLaneOnly(const VPValue *Op) const override {
3998 "Op must be an operand of the recipe");
3999 // Widened loads only demand the first lane of EVL and consecutive loads
4000 // only demand the first lane of their address.
4001 return Op == getEVL() || (Op == getAddr() && isConsecutive());
4002 }
4003
4004protected:
4005 VPRecipeBase *getAsRecipe() override;
4006 const VPRecipeBase *getAsRecipe() const override;
4007
4008#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4009 /// Print the recipe.
4010 void printRecipe(raw_ostream &O, const Twine &Indent,
4011 VPSlotTracker &SlotTracker) const override;
4012#endif
4013};
4014
4015/// A recipe for widening store operations, using the stored value, the address
4016/// to store to and an optional mask.
4018 public VPWidenMemoryRecipe {
4020 VPValue *Mask, bool Consecutive, Align Alignment,
4021 const VPIRMetadata &Metadata, DebugLoc DL)
4022 : VPRecipeBase(VPRecipeBase::VPWidenStoreSC, {Addr, StoredVal}, DL),
4023 VPWidenMemoryRecipe(Store, Alignment, Consecutive, Metadata) {
4024 setMask(Mask);
4025 }
4026
4032
4033 VP_CLASSOF_IMPL(VPRecipeBase::VPWidenStoreSC);
4034
4035 /// Return the value stored by this recipe.
4036 VPValue *getStoredValue() const { return getOperand(1); }
4037
4038 /// Generate a wide store or scatter.
4039 void execute(VPTransformState &State) override;
4040
4041 /// Return the cost of this VPWidenStoreRecipe.
4043 VPCostContext &Ctx) const override {
4044 return VPWidenMemoryRecipe::computeCost(VF, Ctx);
4045 }
4046
4047 /// Returns true if the recipe only uses the first lane of operand \p Op.
4048 bool usesFirstLaneOnly(const VPValue *Op) const override {
4050 "Op must be an operand of the recipe");
4051 // Widened, consecutive stores only demand the first lane of their address,
4052 // unless the same operand is also stored.
4053 return Op == getAddr() && isConsecutive() && Op != getStoredValue();
4054 }
4055
4056protected:
4057 VPRecipeBase *getAsRecipe() override;
4058 const VPRecipeBase *getAsRecipe() const override;
4059
4060#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4061 /// Print the recipe.
4062 void printRecipe(raw_ostream &O, const Twine &Indent,
4063 VPSlotTracker &SlotTracker) const override;
4064#endif
4065};
4066
4067/// A recipe for widening store operations with vector-predication intrinsics,
4068/// using the value to store, the address to store to, the explicit vector
4069/// length and an optional mask.
4071 : public VPRecipeBase,
4072 public VPWidenMemoryRecipe {
4074 VPValue *StoredVal, VPValue &EVL, VPValue *Mask)
4075 : VPRecipeBase(VPRecipeBase::VPWidenStoreEVLSC, {Addr, StoredVal, &EVL},
4076 S.getDebugLoc()),
4077 VPWidenMemoryRecipe(S.getIngredient(), S.getAlign(), S.isConsecutive(),
4078 S) {
4079 setMask(Mask);
4080 }
4081
4083 llvm_unreachable("cloning not supported");
4084 }
4085
4086 VP_CLASSOF_IMPL(VPRecipeBase::VPWidenStoreEVLSC)
4087
4088 /// Return the address accessed by this recipe.
4089 VPValue *getStoredValue() const { return getOperand(1); }
4090
4091 /// Return the EVL operand.
4092 VPValue *getEVL() const { return getOperand(2); }
4093
4094 /// Generate the wide store or scatter.
4095 void execute(VPTransformState &State) override;
4096
4097 /// Return the cost of this VPWidenStoreEVLRecipe.
4098 InstructionCost computeCost(ElementCount VF,
4099 VPCostContext &Ctx) const override;
4100
4101 /// Returns true if the recipe only uses the first lane of operand \p Op.
4102 bool usesFirstLaneOnly(const VPValue *Op) const override {
4104 "Op must be an operand of the recipe");
4105 if (Op == getEVL()) {
4106 assert(getStoredValue() != Op && "unexpected store of EVL");
4107 return true;
4108 }
4109 // Widened, consecutive memory operations only demand the first lane of
4110 // their address, unless the same operand is also stored. That latter can
4111 // happen with opaque pointers.
4112 return Op == getAddr() && isConsecutive() && Op != getStoredValue();
4113 }
4114
4115protected:
4116 VPRecipeBase *getAsRecipe() override;
4117 const VPRecipeBase *getAsRecipe() const override;
4118
4119#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4120 /// Print the recipe.
4121 void printRecipe(raw_ostream &O, const Twine &Indent,
4122 VPSlotTracker &SlotTracker) const override;
4123#endif
4124};
4125
4126/// Recipe to expand a SCEV expression.
4128 const SCEV *Expr;
4129
4130 /// Whether \p Expr must be expanded in IR, which hoists it out of the loops
4131 /// it is invariant in, instead of as VPInstructions.
4132 bool ExpandInIR;
4133
4134public:
4135 VPExpandSCEVRecipe(const SCEV *Expr, bool ExpandInIR = false);
4136
4137 ~VPExpandSCEVRecipe() override = default;
4138
4140 return new VPExpandSCEVRecipe(Expr, ExpandInIR);
4141 }
4142
4143 VP_CLASSOF_IMPL(VPRecipeBase::VPExpandSCEVSC)
4144
4145 void execute(VPTransformState &State) override {
4146 llvm_unreachable("SCEV expressions must be expanded before final execute");
4147 }
4148
4149 /// Return the cost of this VPExpandSCEVRecipe.
4151 VPCostContext &Ctx) const override {
4152 // TODO: Compute accurate cost after retiring the legacy cost model.
4153 return 0;
4154 }
4155
4156 const SCEV *getSCEV() const { return Expr; }
4157
4158 bool expandInIR() const { return ExpandInIR; }
4159
4160protected:
4161#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4162 /// Print the recipe.
4163 void printRecipe(raw_ostream &O, const Twine &Indent,
4164 VPSlotTracker &SlotTracker) const override;
4165#endif
4166};
4167
4168/// A recipe for generating the active lane mask for the vector loop that is
4169/// used to predicate the vector operations.
4171public:
4173 : VPHeaderPHIRecipe(VPRecipeBase::VPActiveLaneMaskPHISC, nullptr,
4174 StartMask, StartMask->getScalarType(), DL) {}
4175
4176 ~VPActiveLaneMaskPHIRecipe() override = default;
4177
4180 if (getNumOperands() == 2)
4181 R->addBackedgeValue(getOperand(1));
4182 return R;
4183 }
4184
4185 VP_CLASSOF_IMPL(VPRecipeBase::VPActiveLaneMaskPHISC)
4186
4187 /// Generate the active lane mask phi of the vector loop.
4188 void execute(VPTransformState &State) override;
4189
4190protected:
4191#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4192 /// Print the recipe.
4193 void printRecipe(raw_ostream &O, const Twine &Indent,
4194 VPSlotTracker &SlotTracker) const override;
4195#endif
4196};
4197
4198/// A recipe for generating the phi node tracking the current scalar iteration
4199/// index. It starts at the start value of the canonical induction and gets
4200/// incremented by the number of scalar iterations processed by the vector loop
4201/// iteration. The increment does not have to be loop invariant.
4203public:
4205 : VPHeaderPHIRecipe(VPRecipeBase::VPCurrentIterationPHISC, nullptr,
4206 StartIV, StartIV->getScalarType(), DL) {}
4207
4208 ~VPCurrentIterationPHIRecipe() override = default;
4209
4211 llvm_unreachable("cloning not implemented yet");
4212 }
4213
4214 VP_CLASSOF_IMPL(VPRecipeBase::VPCurrentIterationPHISC)
4215
4216 void execute(VPTransformState &State) override {
4217 llvm_unreachable("cannot execute this recipe, should be replaced by a "
4218 "scalar phi recipe");
4219 }
4220
4221 /// Return the cost of this VPCurrentIterationPHIRecipe.
4223 VPCostContext &Ctx) const override {
4224 // For now, match the behavior of the legacy cost model.
4225 return 0;
4226 }
4227
4228 /// Returns true if the recipe only uses the first lane of operand \p Op.
4229 bool usesFirstLaneOnly(const VPValue *Op) const override {
4231 "Op must be an operand of the recipe");
4232 return true;
4233 }
4234
4235protected:
4236#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4237 /// Print the recipe.
4238 void printRecipe(raw_ostream &O, const Twine &Indent,
4239 VPSlotTracker &SlotTracker) const override;
4240#endif
4241};
4242
4243/// A Recipe for widening the canonical induction variable of the vector loop.
4244/// First operand is the canonical IV recipe, a second step operand (VF * Part)
4245/// is added during unrolling.
4247public:
4249 const VPIRFlags::WrapFlagsTy &Flags = {})
4250 : VPRecipeWithIRFlags(VPRecipeBase::VPWidenCanonicalIVSC, CanonicalIV,
4251 CanonicalIV->getType(), Flags) {}
4252
4253 ~VPWidenCanonicalIVRecipe() override = default;
4254
4256 auto *WideCanIV =
4258 if (VPValue *Step = getStepValue())
4259 WideCanIV->addPerPartStep(Step);
4260 return WideCanIV;
4261 }
4262
4263 VP_CLASSOF_IMPL(VPRecipeBase::VPWidenCanonicalIVSC)
4264
4265 void execute(VPTransformState &State) override {
4266 llvm_unreachable("Expected prior expansion of WidenCanonicalIV recipes");
4267 }
4268
4269 /// Return the cost of this VPWidenCanonicalIVPHIRecipe.
4271 VPCostContext &Ctx) const override {
4272 // TODO: Compute accurate cost after retiring the legacy cost model.
4273 return 0;
4274 }
4275
4276 /// Return the canonical IV being widened.
4280
4282 return getNumOperands() == 2 ? getOperand(1) : nullptr;
4283 }
4284
4285 /// Add the per-part step (VF * Part) used for unrolled parts.
4287 assert(Step->getScalarType() == getScalarType() &&
4288 "per-part step must have the same type as the canonical IV");
4289 VPUser::addOperand(Step);
4290 }
4291
4292protected:
4293#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4294 /// Print the recipe.
4295 void printRecipe(raw_ostream &O, const Twine &Indent,
4296 VPSlotTracker &SlotTracker) const override;
4297#endif
4298};
4299
4300/// A recipe for converting \p Current into \p Start + \p Current * \p Step.
4301/// FastMathFlags are derived from the \p FPBinOp in the case of FP inductions,
4302/// and the passed NoWrap \p Flags apply in the case of Ptr and Int inductions.
4304 /// Kind of the induction.
4306 /// If not nullptr, the floating point induction binary operator. Must be set
4307 /// for floating point inductions.
4308 const FPMathOperator *FPBinOp;
4309
4310public:
4312 const FPMathOperator *FPBinOp, VPValue *Start,
4313 VPValue *Current, VPValue *Step,
4314 const VPIRFlags::WrapFlagsTy &Flags = {})
4315 : VPRecipeWithIRFlags(VPRecipeBase::VPDerivedIVSC, {Start, Current, Step},
4316 Start->getScalarType(), Flags),
4317 Kind(Kind), FPBinOp(FPBinOp) {}
4318
4319 ~VPDerivedIVRecipe() override = default;
4320
4322 return new VPDerivedIVRecipe(Kind, FPBinOp, getStartValue(), getOperand(1),
4324 }
4325
4326 VP_CLASSOF_IMPL(VPRecipeBase::VPDerivedIVSC)
4327
4328 void execute(VPTransformState &State) override {
4329 llvm_unreachable("Expected prior expansion of this recipe");
4330 }
4331
4332 /// Return the cost of this VPDerivedIVRecipe.
4333 InstructionCost computeCost(ElementCount VF,
4334 VPCostContext &Ctx) const override;
4335
4336 VPValue *getStartValue() const { return getOperand(0); }
4337 VPValue *getIndex() const { return getOperand(1); }
4338 VPValue *getStepValue() const { return getOperand(2); }
4339 const FPMathOperator *getFPBinOp() const { return FPBinOp; }
4341
4342 /// Returns true if the recipe only uses the first lane of operand \p Op.
4343 bool usesFirstLaneOnly(const VPValue *Op) const override {
4345 "Op must be an operand of the recipe");
4346 return true;
4347 }
4348
4349protected:
4350#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4351 /// Print the recipe.
4352 void printRecipe(raw_ostream &O, const Twine &Indent,
4353 VPSlotTracker &SlotTracker) const override;
4354#endif
4355};
4356
4357/// A recipe for handling phi nodes of integer and floating-point inductions,
4358/// producing their scalar values. Before unrolling by UF the recipe represents
4359/// the VF*UF scalar values to be produced, or UF scalar values if only first
4360/// lane is used, and has 3 operands: IV, step and VF. Unrolling adds one extra
4361/// operand StartIndex to all unroll parts except part 0, as the recipe
4362/// represents the VF scalar values (this number of values is taken from
4363/// State.VF rather than from the VF operand) starting at IV + StartIndex.
4365 Instruction::BinaryOps InductionOpcode;
4366
4367public:
4371 : VPRecipeWithIRFlags(VPRecipeBase::VPScalarIVStepsSC, {IV, Step, VF},
4372 IV->getScalarType(), FMFs, DL),
4373 InductionOpcode(Opcode) {}
4374
4375 ~VPScalarIVStepsRecipe() override = default;
4376
4378 auto *NewR = new VPScalarIVStepsRecipe(
4379 getOperand(0), getOperand(1), getOperand(2), InductionOpcode,
4381 if (VPValue *StartIndex = getStartIndex())
4382 NewR->setStartIndex(StartIndex);
4383 return NewR;
4384 }
4385
4386 VP_CLASSOF_IMPL(VPRecipeBase::VPScalarIVStepsSC)
4387
4388 /// Generate the scalarized versions of the phi node as needed by their users.
4389 void execute(VPTransformState &State) override;
4390
4391 /// Return the cost of this VPScalarIVStepsRecipe.
4392 InstructionCost computeCost(ElementCount VF,
4393 VPCostContext &Ctx) const override;
4394
4395 VPValue *getStepValue() const { return getOperand(1); }
4396
4397 /// Return the number of scalars to produce per unroll part, used to compute
4398 /// StartIndex during unrolling.
4399 VPValue *getVFValue() const { return getOperand(2); }
4400
4401 /// Return the StartIndex, or null if known to be zero, valid only after
4402 /// unrolling.
4404 return getNumOperands() == 4 ? getOperand(3) : nullptr;
4405 }
4406
4407 /// Set or add the StartIndex operand.
4408 void setStartIndex(VPValue *StartIndex) {
4409 if (getNumOperands() == 4)
4410 setOperand(3, StartIndex);
4411 else
4412 addOperand(StartIndex);
4413 }
4414
4415 /// Returns true if this recipe produces scalar values for all VF lanes.
4416 bool doesGeneratePerAllLanes() const;
4417
4418 /// Returns true if the recipe only uses the first lane of operand \p Op.
4419 bool usesFirstLaneOnly(const VPValue *Op) const override {
4421 "Op must be an operand of the recipe");
4422 return true;
4423 }
4424
4425 Instruction::BinaryOps getInductionOpcode() const { return InductionOpcode; }
4426
4427protected:
4428#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4429 /// Print the recipe.
4430 void printRecipe(raw_ostream &O, const Twine &Indent,
4431 VPSlotTracker &SlotTracker) const override;
4432#endif
4433};
4434
4435/// CastInfo helper for casting from VPRecipeBase to a mixin class that is not
4436/// part of the VPRecipeBase class hierarchy (e.g. VPPhiAccessors,
4437/// VPIRMetadata).
4438namespace vpdetail {
4439template <typename VPMixin, typename... RecipeTys>
4441 : public DefaultDoCastIfPossible<VPMixin *, VPRecipeBase *,
4442 CastInfoMixinImpl<VPMixin, RecipeTys...>> {
4443 static_assert((std::is_base_of_v<VPMixin, RecipeTys> && ...),
4444 "Each type in RecipeTys must derive from VPMixin");
4445
4446 /// Used by isa.
4447 static bool isPossible(VPRecipeBase *R) { return isa<RecipeTys...>(R); }
4448
4449 /// Used by cast.
4450 static VPMixin *doCast(VPRecipeBase *R) {
4451 VPMixin *Out = nullptr;
4452 ((Out = dyn_cast<RecipeTys>(R)) || ...);
4453 assert(Out && "Illegal recipe for cast");
4454 return Out;
4455 }
4456 static VPMixin *castFailed() { return nullptr; }
4457};
4458} // namespace vpdetail
4459
4460/// Support casting from VPRecipeBase -> VPPhiAccessors.
4461template <>
4466
4467template <>
4472template <>
4474 : public ForwardToPointerCast<VPPhiAccessors, VPRecipeBase *,
4475 CastInfo<VPPhiAccessors, VPRecipeBase *>> {};
4476
4477/// Support casting from VPRecipeBase / VPUser -> VPWidenMemoryRecipe.
4478template <>
4483template <>
4488
4489/// Support casting from VPSingleDefRecipe -> VPWidenMemoryRecipe (loads only).
4490template <>
4494template <>
4499
4500/// Support casting from VPRecipeBase -> VPIRMetadata.
4501template <>
4508
4509template <>
4514template <>
4516 : public ForwardToPointerCast<VPIRMetadata, VPRecipeBase *,
4517 CastInfo<VPIRMetadata, VPRecipeBase *>> {};
4518
4519/// Support casting from VPSingleDefRecipe -> VPIRMetadata.
4520template <>
4523template <>
4528
4529/// VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph. It
4530/// holds a sequence of zero or more VPRecipe's each representing a sequence of
4531/// output IR instructions. All PHI-like recipes must come before any non-PHI
4532/// recipes.
4533class LLVM_ABI_FOR_TEST VPBasicBlock : public VPBlockBase {
4534 friend class VPlan;
4535
4536 /// Use VPlan::createVPBasicBlock to create VPBasicBlocks.
4537 VPBasicBlock(const Twine &Name = "", VPRecipeBase *Recipe = nullptr)
4538 : VPBasicBlock(VPBasicBlockSC, Name) {
4539 if (Recipe)
4540 appendRecipe(Recipe);
4541 }
4542
4543public:
4545
4546protected:
4547 /// The VPRecipes held in the order of output instructions to generate.
4549
4550 VPBasicBlock(VPBlockTy BlockSC, const Twine &Name = "")
4551 : VPBlockBase(BlockSC, Name.str()) {
4552 // Set the parent of the list's sentinel, so end() iterators know their
4553 // block.
4554 Recipes.end().getNodePtr()->setParent(this);
4555 }
4556
4557public:
4558 ~VPBasicBlock() override {
4559 while (!Recipes.empty())
4560 Recipes.pop_back();
4561 }
4562
4563 /// Instruction iterators...
4568
4569 //===--------------------------------------------------------------------===//
4570 /// Recipe iterator methods
4571 ///
4572 inline iterator begin() { return Recipes.begin(); }
4573 inline const_iterator begin() const { return Recipes.begin(); }
4574 inline iterator end() { return Recipes.end(); }
4575 inline const_iterator end() const { return Recipes.end(); }
4576
4577 inline reverse_iterator rbegin() { return Recipes.rbegin(); }
4578 inline const_reverse_iterator rbegin() const { return Recipes.rbegin(); }
4579 inline reverse_iterator rend() { return Recipes.rend(); }
4580 inline const_reverse_iterator rend() const { return Recipes.rend(); }
4581
4582 inline size_t size() const { return Recipes.size(); }
4583 inline bool empty() const { return Recipes.empty(); }
4584 inline const VPRecipeBase &front() const { return Recipes.front(); }
4585 inline VPRecipeBase &front() { return Recipes.front(); }
4586 inline const VPRecipeBase &back() const { return Recipes.back(); }
4587 inline VPRecipeBase &back() { return Recipes.back(); }
4588
4589 /// Returns a reference to the list of recipes.
4591
4592 /// Returns a pointer to a member of the recipe list.
4593 static RecipeListTy VPBasicBlock::*getSublistAccess(VPRecipeBase *) {
4594 return &VPBasicBlock::Recipes;
4595 }
4596
4597 /// Method to support type inquiry through isa, cast, and dyn_cast.
4598 static inline bool classof(const VPBlockBase *V) {
4599 return V->getVPBlockID() == VPBlockBase::VPBasicBlockSC ||
4600 V->getVPBlockID() == VPBlockBase::VPIRBasicBlockSC;
4601 }
4602
4603 void insert(VPRecipeBase *Recipe, iterator InsertPt) {
4604 assert(Recipe && "No recipe to append.");
4605 assert(!Recipe->getParent() && "Recipe already in VPlan");
4606 assert(InsertPt.getNodeParent() == this &&
4607 "Insertion position not in this VPBasicBlock");
4608 Recipe->setParent(this);
4609 Recipes.insert(InsertPt, Recipe);
4610 }
4611
4612 /// Augment the existing recipes of a VPBasicBlock with an additional
4613 /// \p Recipe as the last recipe.
4614 void appendRecipe(VPRecipeBase *Recipe) { insert(Recipe, end()); }
4615
4616 /// The method which generates the output IR instructions that correspond to
4617 /// this VPBasicBlock, thereby "executing" the VPlan.
4618 void execute(VPTransformState *State) override;
4619
4620 /// Return the cost of this VPBasicBlock.
4621 InstructionCost cost(ElementCount VF, VPCostContext &Ctx) override;
4622
4623 /// Return the position of the first non-phi node recipe in the block.
4624 iterator getFirstNonPhi();
4625
4626 /// Returns an iterator range over the PHI-like recipes in the block.
4630
4631 /// Split current block at \p SplitAt by inserting a new block between the
4632 /// current block and its successors and moving all recipes starting at
4633 /// SplitAt to the new block. Returns the new block.
4634 VPBasicBlock *splitAt(iterator SplitAt);
4635
4636 VPRegionBlock *getEnclosingLoopRegion();
4637 const VPRegionBlock *getEnclosingLoopRegion() const;
4638
4639#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4640 /// Print this VPBsicBlock to \p O, prefixing all lines with \p Indent. \p
4641 /// SlotTracker is used to print unnamed VPValue's using consequtive numbers.
4642 ///
4643 /// Note that the numbering is applied to the whole VPlan, so printing
4644 /// individual blocks is consistent with the whole VPlan printing.
4645 void print(raw_ostream &O, const Twine &Indent,
4646 VPSlotTracker &SlotTracker) const override;
4647 using VPBlockBase::print; // Get the print(raw_stream &O) version.
4648#endif
4649
4650 /// If the block has multiple successors, return the branch recipe terminating
4651 /// the block. If there are no or only a single successor, return nullptr;
4652 VPRecipeBase *getTerminator();
4653 const VPRecipeBase *getTerminator() const;
4654
4655 /// Returns true if the block is exiting it's parent region.
4656 bool isExiting() const;
4657
4658 /// Clone the current block and it's recipes, without updating the operands of
4659 /// the cloned recipes.
4660 VPBasicBlock *clone() override;
4661
4662 /// Returns the predecessor block at index \p Idx with the predecessors as per
4663 /// the corresponding plain CFG. If the block is an entry block to a region,
4664 /// the first predecessor is the single predecessor of a region, and the
4665 /// second predecessor is the exiting block of the region.
4666 const VPBasicBlock *getCFGPredecessor(unsigned Idx) const;
4667
4668protected:
4669 /// Execute the recipes in the IR basic block \p BB.
4670 void executeRecipes(VPTransformState *State, BasicBlock *BB);
4671
4672 /// Connect the VPBBs predecessors' in the VPlan CFG to the IR basic block
4673 /// generated for this VPBB.
4674 void connectToPredecessors(VPTransformState &State);
4675
4676private:
4677 /// Create an IR BasicBlock to hold the output instructions generated by this
4678 /// VPBasicBlock, and return it. Update the CFGState accordingly.
4679 BasicBlock *createEmptyBasicBlock(VPTransformState &State);
4680};
4681
4682inline const VPBasicBlock *
4684 return getAsRecipe()->getParent()->getCFGPredecessor(Idx);
4685}
4686
4687/// A special type of VPBasicBlock that wraps an existing IR basic block.
4688/// Recipes of the block get added before the first non-phi instruction in the
4689/// wrapped block.
4690/// Note: At the moment, VPIRBasicBlock can only be used to wrap VPlan's
4691/// preheader block.
4692class VPIRBasicBlock : public VPBasicBlock {
4693 friend class VPlan;
4694
4695 BasicBlock *IRBB;
4696
4697 /// Use VPlan::createVPIRBasicBlock to create VPIRBasicBlocks.
4698 VPIRBasicBlock(BasicBlock *IRBB)
4699 : VPBasicBlock(VPIRBasicBlockSC,
4700 (Twine("ir-bb<") + IRBB->getName() + Twine(">")).str()),
4701 IRBB(IRBB) {}
4702
4703public:
4704 ~VPIRBasicBlock() override = default;
4705
4706 static inline bool classof(const VPBlockBase *V) {
4707 return V->getVPBlockID() == VPBlockBase::VPIRBasicBlockSC;
4708 }
4709
4710 /// The method which generates the output IR instructions that correspond to
4711 /// this VPBasicBlock, thereby "executing" the VPlan.
4712 void execute(VPTransformState *State) override;
4713
4714 VPIRBasicBlock *clone() override;
4715
4716 BasicBlock *getIRBasicBlock() const { return IRBB; }
4717};
4718
4719/// Track information about the canonical IV and header mask of a loop region.
4720/// TODO: Have it also track the canonical IV increment, subject of NUW flag.
4722 /// VPRegionValue for the canonical IV, whose allocation is managed by
4723 /// VPCanonicalIVInfo.
4724 std::unique_ptr<VPRegionValue> CanIV;
4725
4726 /// Optional VPRegionValue for the header mask, set when tail folding.
4727 std::unique_ptr<VPRegionValue> HeaderMask;
4728
4729 /// Whether the increment of the canonical IV may unsigned wrap or not.
4730 bool HasNUW = true;
4731
4732public:
4734 : CanIV(std::make_unique<VPRegionValue>(Ty, DL, Region)) {}
4735
4736 VPRegionValue *getRegionValue() { return CanIV.get(); }
4737 const VPRegionValue *getRegionValue() const { return CanIV.get(); }
4738
4739 VPRegionValue *getHeaderMask() const { return HeaderMask.get(); }
4740
4741 /// Create the header mask for the region and return it. Must only be called
4742 /// when no header mask exists yet.
4744 assert(!HeaderMask && "Header mask already created");
4745 HeaderMask = std::make_unique<VPRegionValue>(
4746 Type::getInt1Ty(CanIV->getType()->getContext()), DebugLoc::getUnknown(),
4747 CanIV->getDefiningRegion());
4748 return HeaderMask.get();
4749 }
4750
4751 bool hasNUW() const { return HasNUW; }
4752
4753 void clearNUW() { HasNUW = false; }
4754};
4755
4756/// VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks
4757/// which form a Single-Entry-Single-Exiting subgraph of the output IR CFG.
4758/// A VPRegionBlock may indicate that its contents are to be replicated several
4759/// times. This is designed to support predicated scalarization, in which a
4760/// scalar if-then code structure needs to be generated VF * UF times. Having
4761/// this replication indicator helps to keep a single model for multiple
4762/// candidate VF's. The actual replication takes place only once the desired VF
4763/// and UF have been determined.
4764class LLVM_ABI_FOR_TEST VPRegionBlock : public VPBlockBase {
4765 friend class VPlan;
4766
4767 /// Hold the Single Entry of the SESE region modelled by the VPRegionBlock.
4768 VPBlockBase *Entry;
4769
4770 /// Hold the Single Exiting block of the SESE region modelled by the
4771 /// VPRegionBlock.
4772 VPBlockBase *Exiting;
4773
4774 /// Holds the Canonical IV of the loop region along with additional
4775 /// information. If CanIVInfo is nullptr, the region is a replicating region.
4776 /// Loop regions retain their canonical IVs until they are dissolved, even if
4777 /// the canonical IV has no users.
4778 std::unique_ptr<VPCanonicalIVInfo> CanIVInfo;
4779
4780 /// Use VPlan::createLoopRegion() and VPlan::createReplicateRegion() to create
4781 /// VPRegionBlocks.
4782 VPRegionBlock(VPBlockBase *Entry, VPBlockBase *Exiting,
4783 const std::string &Name = "")
4784 : VPBlockBase(VPRegionBlockSC, Name), Entry(Entry), Exiting(Exiting) {
4785 if (Entry) {
4786 assert(!Entry->hasPredecessors() && "Entry block has predecessors.");
4787 assert(Exiting && "Must also pass Exiting if Entry is passed.");
4788 assert(!Exiting->hasSuccessors() && "Exit block has successors.");
4789 Entry->setParent(this);
4790 Exiting->setParent(this);
4791 }
4792 }
4793
4794 VPRegionBlock(Type *CanIVTy, DebugLoc DL, VPBlockBase *Entry,
4795 VPBlockBase *Exiting, const std::string &Name = "")
4796 : VPRegionBlock(Entry, Exiting, Name) {
4797 CanIVInfo = std::make_unique<VPCanonicalIVInfo>(CanIVTy, DL, this);
4798 }
4799
4800public:
4801 ~VPRegionBlock() override = default;
4802
4803 /// Method to support type inquiry through isa, cast, and dyn_cast.
4804 static inline bool classof(const VPBlockBase *V) {
4805 return V->getVPBlockID() == VPBlockBase::VPRegionBlockSC;
4806 }
4807
4808 const VPBlockBase *getEntry() const { return Entry; }
4809 VPBlockBase *getEntry() { return Entry; }
4810
4811 /// Set \p EntryBlock as the entry VPBlockBase of this VPRegionBlock. \p
4812 /// EntryBlock must have no predecessors.
4813 void setEntry(VPBlockBase *EntryBlock) {
4814 assert(!EntryBlock->hasPredecessors() &&
4815 "Entry block cannot have predecessors.");
4816 Entry = EntryBlock;
4817 EntryBlock->setParent(this);
4818 }
4819
4820 const VPBlockBase *getExiting() const { return Exiting; }
4821 VPBlockBase *getExiting() { return Exiting; }
4822
4823 /// Set \p ExitingBlock as the exiting VPBlockBase of this VPRegionBlock. \p
4824 /// ExitingBlock must have no successors.
4825 void setExiting(VPBlockBase *ExitingBlock) {
4826 assert(!ExitingBlock->hasSuccessors() &&
4827 "Exit block cannot have successors.");
4828 Exiting = ExitingBlock;
4829 ExitingBlock->setParent(this);
4830 }
4831
4832 /// Returns the pre-header VPBasicBlock of the loop region.
4834 assert(!isReplicator() && "should only get pre-header of loop regions");
4835 return getSinglePredecessor()->getExitingBasicBlock();
4836 }
4837
4838 /// An indicator whether this region is to generate multiple replicated
4839 /// instances of output IR corresponding to its VPBlockBases.
4840 bool isReplicator() const { return !CanIVInfo; }
4841
4842 /// Return the VPBranchOnMaskRecipe from the entry block of this replicating
4843 /// region.
4844 const VPBranchOnMaskRecipe *getEntryBranchOnMask() const;
4846 return const_cast<VPBranchOnMaskRecipe *>(
4847 static_cast<const VPRegionBlock *>(this)->getEntryBranchOnMask());
4848 }
4849
4850 /// The method which generates the output IR instructions that correspond to
4851 /// this VPRegionBlock, thereby "executing" the VPlan.
4852 void execute(VPTransformState *State) override;
4853
4854 // Return the cost of this region.
4855 InstructionCost cost(ElementCount VF, VPCostContext &Ctx) override;
4856
4857#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4858 /// Print this VPRegionBlock to \p O (recursively), prefixing all lines with
4859 /// \p Indent. \p SlotTracker is used to print unnamed VPValue's using
4860 /// consequtive numbers.
4861 ///
4862 /// Note that the numbering is applied to the whole VPlan, so printing
4863 /// individual regions is consistent with the whole VPlan printing.
4864 void print(raw_ostream &O, const Twine &Indent,
4865 VPSlotTracker &SlotTracker) const override;
4866 using VPBlockBase::print; // Get the print(raw_stream &O) version.
4867#endif
4868
4869 /// Clone all blocks in the single-entry single-exit region of the block and
4870 /// their recipes without updating the operands of the cloned recipes.
4871 VPRegionBlock *clone() override;
4872
4873 /// Remove the current region from its VPlan, connecting its predecessor to
4874 /// its entry, and its exiting block to its successor.
4875 void dissolveToCFGLoop();
4876
4877 /// Get the canonical IV increment instruction if it exists. Otherwise, create
4878 /// a new increment before the terminator and return it. The canonical IV
4879 /// increment is subject to DCE if unused, unlike the canonical IV itself.
4880 VPInstruction *getOrCreateCanonicalIVIncrement();
4881
4882 /// Return the canonical induction variable of the region, null for
4883 /// replicating regions.
4885 return CanIVInfo ? CanIVInfo->getRegionValue() : nullptr;
4886 }
4888 return CanIVInfo ? CanIVInfo->getRegionValue() : nullptr;
4889 }
4890
4891 /// Return the type of the canonical IV for loop regions.
4893 return CanIVInfo->getRegionValue()->getType();
4894 }
4895
4896 /// Return the header mask of the region, or null if not set.
4898 return CanIVInfo ? CanIVInfo->getHeaderMask() : nullptr;
4899 }
4900
4901 /// Return the header mask if it exists and is used, or null otherwise. The
4902 /// mask is materialized into concrete recipes only after costing, so cost and
4903 /// codegen accounting sites use this to skip an unused mask.
4905 VPRegionValue *HeaderMask = getHeaderMask();
4906 return HeaderMask && HeaderMask->getNumUsers() > 0 ? HeaderMask : nullptr;
4907 }
4908
4909 /// Create the header mask for the region and return it. Must only be called
4910 /// on loop regions that don't already have a header mask.
4912 assert(CanIVInfo && "Can only create header mask for loop regions");
4913 return CanIVInfo->createHeaderMask();
4914 }
4915
4916 /// Return the region values of the loop region (canonical IV, header mask)
4917 /// or an empty vector for replicate regions.
4919 if (!CanIVInfo)
4920 return {};
4921 SmallVector<VPRegionValue *, 2> R = {CanIVInfo->getRegionValue()};
4922 if (auto *HM = CanIVInfo->getHeaderMask())
4923 R.push_back(HM);
4924 return R;
4925 }
4926
4927 /// Indicates if NUW is set for the canonical IV increment, for loop regions.
4928 bool hasCanonicalIVNUW() const { return CanIVInfo->hasNUW(); }
4929
4930 /// Unsets NUW for the canonical IV increment \p Increment, for loop regions.
4932 assert(Increment && "Must provide increment to clear");
4933 Increment->dropPoisonGeneratingFlags();
4934 CanIVInfo->clearNUW();
4935 }
4936};
4937
4939 return getParent()->getParent();
4940}
4941
4943 return getParent()->getParent();
4944}
4945
4946/// VPlan models a candidate for vectorization, encoding various decisions take
4947/// to produce efficient output IR, including which branches, basic-blocks and
4948/// output IR instructions to generate, and their cost. VPlan holds a
4949/// Hierarchical-CFG of VPBasicBlocks and VPRegionBlocks rooted at an Entry
4950/// VPBasicBlock.
4951class VPlan {
4952 friend class VPlanPrinter;
4953 friend class VPSlotTracker;
4954
4955 /// VPBasicBlock corresponding to the original preheader. Used to place
4956 /// VPExpandSCEV recipes for expressions used during VPlan execution.
4957 /// When this VPlan is used for the epilogue vector loop, the entry models the
4958 /// main plan's entry and its edges move to the epilogue iteration check (see
4959 /// VPlanTransforms::modelGeneratedMainLoopBlocks).
4960 VPBasicBlock *Entry;
4961
4962 /// VPIRBasicBlock wrapping the header of the original scalar loop.
4963 VPIRBasicBlock *ScalarHeader;
4964
4965 /// Immutable list of VPIRBasicBlocks wrapping the exit blocks of the original
4966 /// scalar loop. Note that some exit blocks may be unreachable at the moment,
4967 /// e.g. if the scalar epilogue always executes.
4969
4970 /// Holds the VFs applicable to this VPlan.
4972
4973 /// Holds the UFs applicable to this VPlan. If empty, the VPlan is valid for
4974 /// any UF.
4976
4977 /// Holds the name of the VPlan, for printing.
4978 std::string Name;
4979
4980 /// Represents the trip count of the original loop, for folding
4981 /// the tail.
4982 VPValue *TripCount = nullptr;
4983
4984 /// Represents the vector trip count.
4985 VPSymbolicValue VectorTripCount;
4986
4987 /// Represents the vectorization factor of the loop.
4988 VPSymbolicValue VF;
4989
4990 /// Represents the unroll factor of the loop.
4991 VPSymbolicValue UF;
4992
4993 /// Represents the loop-invariant VF * UF of the vector loop region.
4994 VPSymbolicValue VFxUF;
4995
4996 /// Contains all the external definitions created for this VPlan, as a mapping
4997 /// from IR Values to VPIRValues.
4999
5000 /// Blocks allocated and owned by the VPlan. They will be deleted once the
5001 /// VPlan is destroyed.
5002 SmallVector<VPBlockBase *> CreatedBlocks;
5003
5004 /// Construct a VPlan with \p Entry to the plan and with \p ScalarHeader
5005 /// wrapping the original header of the scalar loop. The vector loop will have
5006 /// index type \p IdxTy.
5007 VPlan(VPBasicBlock *Entry, VPIRBasicBlock *ScalarHeader, Type *IdxTy)
5008 : Entry(Entry), ScalarHeader(ScalarHeader), VectorTripCount(IdxTy),
5009 VF(IdxTy), UF(IdxTy), VFxUF(IdxTy) {
5010 Entry->setPlan(this);
5011 assert(ScalarHeader->getNumSuccessors() == 0 &&
5012 "scalar header must be a leaf node");
5013 }
5014
5015public:
5016 /// Construct a VPlan for \p L. This will create VPIRBasicBlocks wrapping the
5017 /// original preheader and scalar header of \p L, to be used as entry and
5018 /// scalar header blocks of the new VPlan. The vector loop will have index
5019 /// type \p IdxTy.
5020 VPlan(Loop *L, Type *IdxTy);
5021
5022 /// Construct a VPlan with a new VPBasicBlock as entry, a VPIRBasicBlock
5023 /// wrapping \p ScalarHeaderBB and vector loop index of type \p IdxTy.
5024 VPlan(BasicBlock *ScalarHeaderBB, Type *IdxTy)
5025 : VectorTripCount(IdxTy), VF(IdxTy), UF(IdxTy), VFxUF(IdxTy) {
5026 setEntry(createVPBasicBlock("preheader"));
5027 ScalarHeader = createVPIRBasicBlock(ScalarHeaderBB);
5028 }
5029
5031
5033 Entry = VPBB;
5034 VPBB->setPlan(this);
5035 }
5036
5037 /// Generate the IR code for this VPlan.
5038 void execute(VPTransformState *State);
5039
5040 /// Return the cost of this plan.
5042
5043 VPBasicBlock *getEntry() { return Entry; }
5044 const VPBasicBlock *getEntry() const { return Entry; }
5045
5046 /// Returns the preheader of the vector loop region, if one exists, or null
5047 /// otherwise.
5049 const VPRegionBlock *VectorRegion = getVectorLoopRegion();
5050 return VectorRegion
5051 ? cast<VPBasicBlock>(VectorRegion->getSinglePredecessor())
5052 : nullptr;
5053 }
5054
5055 /// Returns the VPRegionBlock of the vector loop.
5058
5059 /// Returns true if this VPlan is for an outer loop, i.e., its vector
5060 /// loop region contains a nested loop region.
5061 LLVM_ABI_FOR_TEST bool isOuterLoop() const;
5062
5063 /// Returns true if the vector loop region is tail-folded.
5064 bool hasTailFolded() const {
5065 const VPRegionBlock *LoopRegion = getVectorLoopRegion();
5066 return LoopRegion && LoopRegion->getHeaderMask();
5067 }
5068
5069 /// Returns true if the plan requires a scalar epilogue after the vector
5070 /// loop. Must be called before removeBranchOnConst.
5072 const VPBasicBlock *MiddleVPBB = getMiddleBlock();
5073 return MiddleVPBB->getSingleSuccessor() == getScalarPreheader();
5074 }
5075
5076 /// Returns the 'middle' block of the plan, that is the block that selects
5077 /// whether to execute the scalar tail loop or the exit block from the loop
5078 /// latch. If there is an early exit from the vector loop, the middle block
5079 /// conceptully has the early exit block as third successor, split accross 2
5080 /// VPBBs. In that case, the second VPBB selects whether to execute the scalar
5081 /// tail loop or the exit block. If the scalar tail loop or exit block are
5082 /// known to always execute, the middle block may branch directly to that
5083 /// block. This function cannot be called once the vector loop region has been
5084 /// removed.
5086 VPRegionBlock *LoopRegion = getVectorLoopRegion();
5087 assert(
5088 LoopRegion &&
5089 "cannot call the function after vector loop region has been removed");
5090 // The middle block is always the last successor of the region.
5091 return cast<VPBasicBlock>(LoopRegion->getSuccessors().back());
5092 }
5093
5095 return const_cast<VPlan *>(this)->getMiddleBlock();
5096 }
5097
5098 /// Return the VPBasicBlock for the preheader of the scalar loop.
5101 getScalarHeader()->getSinglePredecessor());
5102 }
5103
5104 /// Return the VPIRBasicBlock wrapping the header of the scalar loop.
5105 VPIRBasicBlock *getScalarHeader() const { return ScalarHeader; }
5106
5107 /// Return an ArrayRef containing VPIRBasicBlocks wrapping the exit blocks of
5108 /// the original scalar loop.
5109 ArrayRef<VPIRBasicBlock *> getExitBlocks() const { return ExitBlocks; }
5110
5111 /// Returns true if \p VPBB is an exit block.
5112 bool isExitBlock(VPBlockBase *VPBB);
5113
5114 /// The trip count of the original loop.
5116 assert(TripCount && "trip count needs to be set before accessing it");
5117 return TripCount;
5118 }
5119
5120 /// Set the trip count assuming it is currently null; if it is not - use
5121 /// resetTripCount().
5122 void setTripCount(VPValue *NewTripCount) {
5123 assert(!TripCount && NewTripCount && "TripCount should not be set yet.");
5124 TripCount = NewTripCount;
5125 }
5126
5127 /// Resets the trip count for the VPlan. The caller must make sure all uses of
5128 /// the original trip count have been replaced.
5129 void resetTripCount(VPValue *NewTripCount) {
5130 assert(TripCount && NewTripCount && TripCount->user_empty() &&
5131 "TripCount must be set when resetting");
5132 TripCount = NewTripCount;
5133 }
5134
5135 /// The vector trip count.
5136 VPSymbolicValue &getVectorTripCount() { return VectorTripCount; }
5137
5138 /// Returns the VF of the vector loop region.
5139 VPSymbolicValue &getVF() { return VF; };
5140 const VPSymbolicValue &getVF() const { return VF; };
5141
5142 /// Returns the UF of the vector loop region.
5143 VPSymbolicValue &getUF() { return UF; };
5144
5145 /// Returns VF * UF of the vector loop region.
5146 VPSymbolicValue &getVFxUF() { return VFxUF; }
5147
5150 }
5151
5152 const DataLayout &getDataLayout() const {
5154 }
5155
5158 }
5159
5160 void addVF(ElementCount VF) { VFs.insert(VF); }
5161
5163 assert(hasVF(VF) && "Cannot set VF not already in plan");
5164 VFs.clear();
5165 VFs.insert(VF);
5166 }
5167
5168 /// Remove \p VF from the plan.
5170 assert(hasVF(VF) && "tried to remove VF not present in plan");
5171 VFs.remove(VF);
5172 }
5173
5174 bool hasVF(ElementCount VF) const { return VFs.count(VF); }
5175 bool hasScalableVF() const {
5176 return any_of(VFs, [](ElementCount VF) { return VF.isScalable(); });
5177 }
5178
5179 /// Returns an iterator range over all VFs of the plan.
5182 return VFs;
5183 }
5184
5185 /// Returns the single VF of the plan, asserting that the plan has exactly
5186 /// one VF.
5188 assert(VFs.size() == 1 && "expected plan with single VF");
5189 return VFs[0];
5190 }
5191
5192 bool hasScalarVFOnly() const {
5193 bool HasScalarVFOnly = VFs.size() == 1 && VFs[0].isScalar();
5194 assert(HasScalarVFOnly == hasVF(ElementCount::getFixed(1)) &&
5195 "Plan with scalar VF should only have a single VF");
5196 return HasScalarVFOnly;
5197 }
5198
5199 bool hasUF(unsigned UF) const { return UFs.empty() || UFs.contains(UF); }
5200
5201 /// Returns the concrete UF of the plan, after unrolling.
5202 unsigned getConcreteUF() const {
5203 assert(UFs.size() == 1 && "Expected a single UF");
5204 return UFs[0];
5205 }
5206
5207 void setUF(unsigned UF) {
5208 assert(hasUF(UF) && "Cannot set the UF not already in plan");
5209 UFs.clear();
5210 UFs.insert(UF);
5211 }
5212
5213 /// Returns true if the VPlan already has been unrolled, i.e. it has a single
5214 /// concrete UF.
5215 bool isUnrolled() const { return UFs.size() == 1; }
5216
5217 /// Return a string with the name of the plan and the applicable VFs and UFs.
5218 std::string getName() const;
5219
5220 void setName(const Twine &newName) { Name = newName.str(); }
5221
5222 /// Gets the live-in VPIRValue for \p V or adds a new live-in (if none exists
5223 /// yet) for \p V.
5225 assert(V && "Trying to get or add the VPIRValue of a null Value");
5226 auto [It, Inserted] = LiveIns.try_emplace(V);
5227 if (Inserted) {
5228 if (auto *CI = dyn_cast<ConstantInt>(V))
5229 It->second = new VPConstantInt(CI);
5230 else
5231 It->second = new VPIRValue(V);
5232 }
5233
5234 assert(isa<VPIRValue>(It->second) &&
5235 "Only VPIRValues should be in mapping");
5236 return It->second;
5237 }
5239 assert(V && "Trying to get or add the VPIRValue of a null VPIRValue");
5240 return getOrAddLiveIn(V->getValue());
5241 }
5242
5243 /// Return a VPIRValue wrapping i1 true.
5244 VPIRValue *getTrue() { return getConstantInt(1, 1); }
5245
5246 /// Return a VPIRValue wrapping i1 false.
5247 VPIRValue *getFalse() { return getConstantInt(1, 0); }
5248
5249 /// Return a VPIRValue wrapping the null value of type \p Ty.
5250 VPIRValue *getZero(Type *Ty) { return getConstantInt(Ty, 0); }
5251
5252 /// Return a VPIRValue wrapping the AllOnes value of type \p Ty.
5254 return getConstantInt(APInt::getAllOnes(Ty->getIntegerBitWidth()));
5255 }
5256
5257 /// Return a VPIRValue wrapping a ConstantInt with the given type and value.
5258 VPIRValue *getConstantInt(Type *Ty, uint64_t Val, bool IsSigned = false) {
5259 return getOrAddLiveIn(ConstantInt::get(Ty, Val, IsSigned));
5260 }
5261
5262 /// Return a VPIRValue wrapping a ConstantInt with the given bitwidth and
5263 /// value.
5265 bool IsSigned = false) {
5266 return getConstantInt(APInt(BitWidth, Val, IsSigned));
5267 }
5268
5269 /// Return a VPIRValue wrapping a ConstantInt with the given APInt value.
5271 return getOrAddLiveIn(ConstantInt::get(getContext(), Val));
5272 }
5273
5274 /// Return a VPIRValue wrapping a poison value of type \p Ty.
5276 return getOrAddLiveIn(PoisonValue::get(Ty));
5277 }
5278
5279 /// Return the live-in VPIRValue for \p V, if there is one or nullptr
5280 /// otherwise.
5281 VPIRValue *getLiveIn(Value *V) const { return LiveIns.lookup(V); }
5282
5283 /// Return the list of live-in VPValues available in the VPlan.
5284 auto getLiveIns() const { return LiveIns.values(); }
5285
5286#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5287 /// Print the live-ins of this VPlan to \p O.
5288 void printLiveIns(raw_ostream &O) const;
5289
5290 /// Print this VPlan to \p O.
5291 LLVM_ABI_FOR_TEST void print(raw_ostream &O) const;
5292
5293 /// Print this VPlan in DOT format to \p O.
5294 LLVM_ABI_FOR_TEST void printDOT(raw_ostream &O) const;
5295
5296 /// Dump the plan to stderr (for debugging).
5297 LLVM_DUMP_METHOD void dump() const;
5298#endif
5299
5300 /// Clone the current VPlan, update all VPValues of the new VPlan and cloned
5301 /// recipes to refer to the clones, and return it.
5303
5304 /// Create a new VPBasicBlock with \p Name and containing \p Recipe if
5305 /// present. The returned block is owned by the VPlan and deleted once the
5306 /// VPlan is destroyed.
5308 VPRecipeBase *Recipe = nullptr) {
5309 auto *VPB = new VPBasicBlock(Name, Recipe);
5310 VPB->setPlan(this);
5311 VPB->setNumber(CreatedBlocks.size());
5312 CreatedBlocks.push_back(VPB);
5313 return VPB;
5314 }
5315
5316 /// Create a new loop region with a canonical IV using \p CanIVTy and
5317 /// \p DL. Use \p Name as the region's name and set entry and exiting blocks
5318 /// to \p Entry and \p Exiting respectively, if provided. The returned block
5319 /// is owned by the VPlan and deleted once the VPlan is destroyed.
5321 const std::string &Name = "",
5322 VPBlockBase *Entry = nullptr,
5323 VPBlockBase *Exiting = nullptr) {
5324 auto *VPB = new VPRegionBlock(CanIVTy, DL, Entry, Exiting, Name);
5325 VPB->setPlan(this);
5326 VPB->setNumber(CreatedBlocks.size());
5327 CreatedBlocks.push_back(VPB);
5328 return VPB;
5329 }
5330
5331 /// Create a new replicate region with \p Entry, \p Exiting and \p Name. The
5332 /// returned block is owned by the VPlan and deleted once the VPlan is
5333 /// destroyed.
5335 const std::string &Name = "") {
5336 auto *VPB = new VPRegionBlock(Entry, Exiting, Name);
5337 VPB->setPlan(this);
5338 VPB->setNumber(CreatedBlocks.size());
5339 CreatedBlocks.push_back(VPB);
5340 return VPB;
5341 }
5342
5343 /// Create a VPIRBasicBlock wrapping \p IRBB, but do not create
5344 /// VPIRInstructions wrapping the instructions in t\p IRBB. The returned
5345 /// block is owned by the VPlan and deleted once the VPlan is destroyed.
5347
5348 /// Create a VPIRBasicBlock from \p IRBB containing VPIRInstructions for all
5349 /// instructions in \p IRBB, except its terminator which is managed by the
5350 /// successors of the block in VPlan. The returned block is owned by the VPlan
5351 /// and deleted once the VPlan is destroyed.
5353
5354 unsigned getMaxBlockNumber() const { return CreatedBlocks.size(); }
5355
5356 /// Returns true if the VPlan is based on a loop with an early exit.
5357 bool hasEarlyExit() const {
5358 unsigned NumExitPredecessors =
5359 sum_of(map_range(ExitBlocks, [](VPIRBasicBlock *EB) {
5360 return EB->getNumPredecessors();
5361 }));
5362
5363 // If the scalar preheader executes unconditionally, there's no branch from
5364 // middle block to any exit. If there is any edge to an exit block
5365 // remaining, it must be an early exit.
5366 VPBasicBlock *ScalarPH = getScalarPreheader();
5367 VPBlockBase *ScalarPHPred =
5368 ScalarPH ? ScalarPH->getSinglePredecessor() : nullptr;
5369 if (ScalarPHPred && ScalarPHPred->getNumSuccessors() == 1)
5370 return NumExitPredecessors >= 1;
5371
5372 // Otherwise there must be at least 2 edges to exit blocks (from the middle
5373 // block and the early exiting edge).
5374 return NumExitPredecessors > 1;
5375 }
5376
5377 /// Returns true if the scalar tail may execute after the vector loop, i.e.
5378 /// if the middle block is a predecessor of the scalar preheader. Note that
5379 /// this relies on unneeded branches to the scalar tail loop being removed.
5380 bool hasScalarTail() const {
5381 auto *ScalarPH = getScalarPreheader();
5382 return ScalarPH &&
5383 is_contained(ScalarPH->getPredecessors(), getMiddleBlock());
5384 }
5385
5386 /// The type of the canonical induction variable of the vector loop.
5387 Type *getIndexType() const { return VF.getType(); }
5388};
5389
5390#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5391inline raw_ostream &operator<<(raw_ostream &OS, const VPlan &Plan) {
5392 Plan.print(OS);
5393 return OS;
5394}
5395#endif
5396
5397} // end namespace llvm
5398
5399#endif // LLVM_TRANSFORMS_VECTORIZE_VPLAN_H
bool IsScalable
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
uint64_t uint64_t
static MCDisassembler::DecodeStatus addOperand(MCInst &Inst, const MCOperand &Opnd)
Rewrite undef for PHI
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
always inline
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
This file contains the simple types necessary to represent the attributes associated with functions a...
This file implements methods to test, set and extract typed bits from packed unsigned integers.
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
#define LLVM_ABI
Definition Compiler.h:211
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:690
#define LLVM_ABI_FOR_TEST
Definition Compiler.h:216
#define LLVM_PACKED_START
Definition Compiler.h:583
dxil translate DXIL Translate Metadata
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
Hexagon Common GEP
static MaybeAlign getAlign(Value *Ptr)
This file defines an InstructionCost class that is used when calculating the cost of an instruction,...
static std::pair< Value *, APInt > getMask(Value *WideMask, unsigned Factor, ElementCount LeafValueEC)
static MemAccessTy getAccessType(const TargetTransformInfo &TTI, Instruction *Inst, Value *OperandVal)
Return the type of the memory being accessed.
#define I(x, y, z)
Definition MD5.cpp:57
This file implements a map that provides insertion order iteration.
static Interval intersect(const Interval &I1, const Interval &I2)
This file provides utility analysis objects describing memory locations.
#define T
#define P(N)
static StringRef getName(Value *V)
static bool mayHaveSideEffects(MachineInstr &MI)
SI Fold Operands
Func MI getDebugLoc()))
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
static const BasicSubtargetSubTypeKV * find(StringRef S, ArrayRef< BasicSubtargetSubTypeKV > A)
Find KV in array using binary search.
This file contains the declarations of the entities induced by Vectorization Plans,...
#define VP_CLASSOF_IMPL(VPRecipeID)
Definition VPlan.h:581
static const uint32_t IV[8]
Definition blake3_impl.h:83
Class for arbitrary precision integers.
Definition APInt.h:78
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:230
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
const T & back() const
Get the last element.
Definition ArrayRef.h:150
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
This class holds the attributes for a particular argument, parameter, function, or return value.
Definition Attributes.h:406
LLVM_ABI MemoryEffects getMemoryEffects() const
LLVM_ABI bool hasAttribute(Attribute::AttrKind Kind) const
Return true if the attribute exists in this set.
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
Definition Attributes.h:125
LLVM Basic Block Representation.
Definition BasicBlock.h:62
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this basic block belongs to.
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
void setAttributes(AttributeList A)
Set the attributes for this call.
This class represents a function call, abstracting a target machine's calling convention.
This is the base class for all instructions that perform data casts.
Definition InstrTypes.h:512
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
A debug info location.
Definition DebugLoc.h:126
static DebugLoc getUnknown()
Definition DebugLoc.h:153
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:306
Utility class for floating point operations which can have information about relaxed accuracy require...
Definition Operator.h:202
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:23
Class to represent function types.
Represents flags for the getelementptr instruction/expression.
static GEPNoWrapFlags fromRaw(unsigned Flags)
unsigned getRaw() const
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
A struct for saving information about induction variables.
InductionKind
This enum represents the kinds of inductions that we support.
bool isCast() const
The group of interleaved loads/stores sharing the same stride and close to each other.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
An instruction for reading from memory.
LoopVectorizationCostModel - estimates the expected speedups due to vectorization.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
Metadata node.
Definition Metadata.h:1081
Root of the metadata hierarchy.
Definition Metadata.h:64
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
This class represents an assumption made using SCEV expressions which can be checked at run-time.
This class represents an analyzed expression in the program.
This class provides computation of slot numbers for LLVM Assembly writing.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:346
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
iterator erase(const_iterator CI)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
A wrapper around a string literal that serves as a proxy for constructing global tables of StringRefs...
Definition StringRef.h:888
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
std::string str() const
Get the contents as an std::string.
Definition StringRef.h:222
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
LLVM_ABI std::string str() const
Return the twine contents as a std::string.
Definition Twine.cpp:17
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:296
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
void execute(VPTransformState &State) override
Generate the active lane mask phi of the vector loop.
VPActiveLaneMaskPHIRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:4178
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPActiveLaneMaskPHIRecipe(VPValue *StartMask, DebugLoc DL)
Definition VPlan.h:4172
~VPActiveLaneMaskPHIRecipe() override=default
VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph.
Definition VPlan.h:4533
VPRecipeBase::RecipeListTy RecipeListTy
Definition VPlan.h:4544
RecipeListTy::const_iterator const_iterator
Definition VPlan.h:4565
void appendRecipe(VPRecipeBase *Recipe)
Augment the existing recipes of a VPBasicBlock with an additional Recipe as the last recipe.
Definition VPlan.h:4614
RecipeListTy::const_reverse_iterator const_reverse_iterator
Definition VPlan.h:4567
RecipeListTy::iterator iterator
Instruction iterators...
Definition VPlan.h:4564
RecipeListTy & getRecipeList()
Returns a reference to the list of recipes.
Definition VPlan.h:4590
iterator end()
Definition VPlan.h:4574
iterator begin()
Recipe iterator methods.
Definition VPlan.h:4572
RecipeListTy::reverse_iterator reverse_iterator
Definition VPlan.h:4566
iterator_range< iterator > phis()
Returns an iterator range over the PHI-like recipes in the block.
Definition VPlan.h:4627
iterator getFirstNonPhi()
Return the position of the first non-phi node recipe in the block.
Definition VPlan.cpp:228
~VPBasicBlock() override
Definition VPlan.h:4558
const_reverse_iterator rbegin() const
Definition VPlan.h:4578
reverse_iterator rend()
Definition VPlan.h:4579
RecipeListTy Recipes
The VPRecipes held in the order of output instructions to generate.
Definition VPlan.h:4548
VPRecipeBase & back()
Definition VPlan.h:4587
const VPRecipeBase & front() const
Definition VPlan.h:4584
const_iterator begin() const
Definition VPlan.h:4573
VPRecipeBase & front()
Definition VPlan.h:4585
const VPRecipeBase & back() const
Definition VPlan.h:4586
void insert(VPRecipeBase *Recipe, iterator InsertPt)
Definition VPlan.h:4603
bool empty() const
Definition VPlan.h:4583
const_iterator end() const
Definition VPlan.h:4575
static bool classof(const VPBlockBase *V)
Method to support type inquiry through isa, cast, and dyn_cast.
Definition VPlan.h:4598
static RecipeListTy VPBasicBlock::* getSublistAccess(VPRecipeBase *)
Returns a pointer to a member of the recipe list.
Definition VPlan.h:4593
reverse_iterator rbegin()
Definition VPlan.h:4577
friend class VPlan
Definition VPlan.h:4534
size_t size() const
Definition VPlan.h:4582
const_reverse_iterator rend() const
Definition VPlan.h:4580
VPBasicBlock(VPBlockTy BlockSC, const Twine &Name="")
Definition VPlan.h:4550
VPValue * getIncomingValue(unsigned Idx) const
Return incoming value number Idx.
Definition VPlan.h:3098
VPValue * getMask(unsigned Idx) const
Return mask number Idx.
Definition VPlan.h:3103
VPBlendRecipe(PHINode *Phi, ArrayRef< VPValue * > Operands, const VPIRFlags &Flags, DebugLoc DL)
The blend operation is a User of the incoming values and of their respective masks,...
Definition VPlan.h:3057
unsigned getNumIncomingValues() const
Return the number of incoming values, taking into account when normalized the first incoming value wi...
Definition VPlan.h:3093
void execute(VPTransformState &State) override
The method which generates the output IR instructions that correspond to this VPRecipe,...
Definition VPlan.h:3115
VPBlendRecipe * cloneWithOperands(ArrayRef< VPValue * > NewOperands)
Definition VPlan.h:3080
VPBlendRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:3078
void setMask(unsigned Idx, VPValue *V)
Set mask number Idx to V.
Definition VPlan.h:3109
bool isNormalized() const
A normalized blend is one that has an odd number of operands, whereby the first operand does not have...
Definition VPlan.h:3089
VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
Definition VPlan.h:95
void setSuccessors(ArrayRef< VPBlockBase * > NewSuccs)
Set each VPBasicBlock in NewSuccss as successor of this VPBlockBase.
Definition VPlan.h:305
VPRegionBlock * getParent()
Definition VPlan.h:193
const VPlan * getPlan() const
Definition VPlan.h:198
void setPlan(VPlan *ParentPlan)
Sets the pointer of the plan containing the block.
Definition VPlan.h:201
VPBlocksTy & getPredecessors()
Definition VPlan.h:229
iterator_range< VPBlockBase ** > predecessors()
Definition VPlan.h:226
LLVM_DUMP_METHOD void dump() const
Dump this VPBlockBase to dbgs().
Definition VPlan.h:381
void setName(const Twine &newName)
Definition VPlan.h:186
size_t getNumSuccessors() const
Definition VPlan.h:243
iterator_range< VPBlockBase ** > successors()
Definition VPlan.h:225
virtual void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const =0
Print plain-text dump of this VPBlockBase to O, prefixing all lines with Indent.
bool hasPredecessors() const
Returns true if this block has any predecessors.
Definition VPlan.h:223
void swapSuccessors()
Swap successors of the block. The block must have exactly 2 successors.
Definition VPlan.h:327
void printSuccessors(raw_ostream &O, const Twine &Indent) const
Print the successors of this block to O, prefixing all lines with Indent.
Definition VPlan.cpp:630
SmallVectorImpl< VPBlockBase * > VPBlocksTy
Definition VPlan.h:180
virtual ~VPBlockBase()=default
unsigned getNumber() const
Return the unique number of the block.
Definition VPlan.h:347
void setNumber(unsigned N)
Set the unique number of the block, used for dominator tree.
Definition VPlan.h:350
unsigned getIndexForSuccessor(const VPBlockBase *Succ) const
Returns the index for Succ in the blocks successor list.
Definition VPlan.h:340
size_t getNumPredecessors() const
Definition VPlan.h:244
void setPredecessors(ArrayRef< VPBlockBase * > NewPreds)
Set each VPBasicBlock in NewPreds as predecessor of this VPBlockBase.
Definition VPlan.h:296
VPBlockBase * getEnclosingBlockWithPredecessors()
Definition VPlan.cpp:220
unsigned getIndexForPredecessor(const VPBlockBase *Pred) const
Returns the index for Pred in the blocks predecessors list.
Definition VPlan.h:333
enum :unsigned char { VPRegionBlockSC, VPBasicBlockSC, VPIRBasicBlockSC } VPBlockTy
An enumeration for keeping track of the concrete subclass of VPBlockBase that are actually instantiat...
Definition VPlan.h:103
bool hasSuccessors() const
Returns true if this block has any successors.
Definition VPlan.h:221
const VPBlocksTy & getPredecessors() const
Definition VPlan.h:228
virtual VPBlockBase * clone()=0
Clone the current block and it's recipes without updating the operands of the cloned recipes,...
virtual InstructionCost cost(ElementCount VF, VPCostContext &Ctx)=0
Return the cost of the block.
VPlan * getPlan()
Definition VPlan.h:197
const VPRegionBlock * getParent() const
Definition VPlan.h:194
const std::string & getName() const
Definition VPlan.h:184
void clearSuccessors()
Remove all the successors of this block.
Definition VPlan.h:315
void setTwoSuccessors(VPBlockBase *IfTrue, VPBlockBase *IfFalse)
Set two given VPBlockBases IfTrue and IfFalse to be the two successors of this VPBlockBase.
Definition VPlan.h:287
VPBlockBase * getSinglePredecessor() const
Definition VPlan.h:239
virtual void execute(VPTransformState *State)=0
The method which generates the output IR that correspond to this VPBlockBase, thereby "executing" the...
const VPBlocksTy & getHierarchicalSuccessors()
Definition VPlan.h:263
void clearPredecessors()
Remove all the predecessor of this block.
Definition VPlan.h:312
friend class VPBlockUtils
Definition VPlan.h:96
unsigned getVPBlockID() const
Definition VPlan.h:191
void printAsOperand(raw_ostream &OS, bool PrintType=false) const
Definition VPlan.h:359
void swapPredecessors()
Swap predecessors of the block.
Definition VPlan.h:319
VPBlocksTy & getSuccessors()
Definition VPlan.h:218
VPBlockBase * getEnclosingBlockWithSuccessors()
An Enclosing Block of a block B is any block containing B, including B itself.
Definition VPlan.cpp:212
void setOneSuccessor(VPBlockBase *Successor)
Set a given VPBlockBase Successor as the single successor of this VPBlockBase.
Definition VPlan.h:276
void setParent(VPRegionBlock *P)
Definition VPlan.h:203
VPBlockBase * getSingleHierarchicalPredecessor()
Definition VPlan.h:269
VPBlockBase * getSingleSuccessor() const
Definition VPlan.h:233
const VPBlocksTy & getSuccessors() const
Definition VPlan.h:217
VPBlockBase(VPBlockTy SC, const std::string &N)
Definition VPlan.h:390
A recipe for generating conditional branches on the bits of a mask.
Definition VPlan.h:3602
VPBranchOnMaskRecipe(VPValue *BlockInMask, DebugLoc DL, const VPIRMetadata &Metadata={})
Definition VPlan.h:3604
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
Definition VPlan.h:3625
VPBranchOnMaskRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:3609
bool usesScalars(const VPValue *Op) const override
Returns true if the recipe uses scalars of operand Op.
Definition VPlan.h:3633
VPlan-based builder utility similar to IRBuilder.
VPRegionValue * createHeaderMask()
Create the header mask for the region and return it.
Definition VPlan.h:4743
VPRegionValue * getHeaderMask() const
Definition VPlan.h:4739
VPRegionValue * getRegionValue()
Definition VPlan.h:4736
VPCanonicalIVInfo(Type *Ty, DebugLoc DL, VPRegionBlock *Region)
Definition VPlan.h:4733
const VPRegionValue * getRegionValue() const
Definition VPlan.h:4737
bool hasNUW() const
Definition VPlan.h:4751
A recipe for handling scalar conditional induction PHIs.
Definition VPlan.h:2997
const SCEV * getStepSCEV() const
Returns the conditional induction step SCEV expression.
Definition VPlan.h:3015
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Compute the cost of this recipe either using a recipe's specialized implementation or using the legac...
VPConditionalInductionPHIRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:3017
PHINode * getPHINode() const
Returns the underlying PHINode.
Definition VPlan.h:3012
VPConditionalInductionPHIRecipe(PHINode &Phi, VPValue &Start, VPValue &BackedgeValue, const SCEV *StepSCEV)
Definition VPlan.h:3001
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:3042
void execute(VPTransformState &) override
Generate the phi nodes.
Definition VPlan.h:3028
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
~VPConditionalInductionPHIRecipe() override=default
static bool classof(const VPHeaderPHIRecipe *R)
Definition VPlan.h:3024
VPCurrentIterationPHIRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:4210
VPCurrentIterationPHIRecipe(VPValue *StartIV, DebugLoc DL)
Definition VPlan.h:4204
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPCurrentIterationPHIRecipe.
Definition VPlan.h:4222
void execute(VPTransformState &State) override
Generate the phi nodes.
Definition VPlan.h:4216
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:4229
~VPCurrentIterationPHIRecipe() override=default
InductionDescriptor::InductionKind getInductionKind() const
Definition VPlan.h:4340
VPValue * getIndex() const
Definition VPlan.h:4337
const FPMathOperator * getFPBinOp() const
Definition VPlan.h:4339
VPDerivedIVRecipe(InductionDescriptor::InductionKind Kind, const FPMathOperator *FPBinOp, VPValue *Start, VPValue *Current, VPValue *Step, const VPIRFlags::WrapFlagsTy &Flags={})
Definition VPlan.h:4311
VPValue * getStepValue() const
Definition VPlan.h:4338
void execute(VPTransformState &State) override
The method which generates the output IR instructions that correspond to this VPRecipe,...
Definition VPlan.h:4328
VPDerivedIVRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:4321
~VPDerivedIVRecipe() override=default
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:4343
VPValue * getStartValue() const
Definition VPlan.h:4336
Template specialization of the standard LLVM dominator tree utility for VPBlockBases.
void execute(VPTransformState &State) override
The method which generates the output IR instructions that correspond to this VPRecipe,...
Definition VPlan.h:4145
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPExpandSCEVRecipe.
Definition VPlan.h:4150
VPExpandSCEVRecipe(const SCEV *Expr, bool ExpandInIR=false)
bool expandInIR() const
Definition VPlan.h:4158
const SCEV * getSCEV() const
Definition VPlan.h:4156
VPExpandSCEVRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:4139
~VPExpandSCEVRecipe() override=default
void execute(VPTransformState &State) override
Method for generating code, must not be called as this recipe is abstract.
Definition VPlan.h:3779
bool isVectorToScalar() const
Returns true if this VPExpressionRecipe produces a single scalar.
VPExpressionRecipe(VPWidenCastRecipe *Ext, VPWidenRecipe *Neg, VPReductionRecipe *Red)
Definition VPlan.h:3695
VPExpressionRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:3748
SmallVector< VPSingleDefRecipe * > decompose()
Return and insert the recipes of the expression back into the VPlan, directly before the current reci...
~VPExpressionRecipe() override
Definition VPlan.h:3736
ExpressionTypes getExpressionType() const
Returns the expression type of this recipe.
Definition VPlan.h:3771
VPExpressionRecipe(VPWidenCastRecipe *Ext, VPReductionRecipe *Red)
Definition VPlan.h:3693
bool mayHaveSideEffects() const
Returns true if this expression contains recipes that may have side effects.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Compute the cost of this recipe either using a recipe's specialized implementation or using the legac...
bool mayReadOrWriteMemory() const
Returns true if this expression contains recipes that may read from or write to memory.
VPExpressionRecipe(VPWidenCastRecipe *Ext0, VPWidenCastRecipe *Ext1, VPWidenRecipe *Mul, VPReductionRecipe *Red)
Definition VPlan.h:3711
VPExpressionRecipe(ExpressionTypes ExpressionType, ArrayRef< VPSingleDefRecipe * > ExpressionRecipes)
Construct a new VPExpressionRecipe by internalizing recipes in ExpressionRecipes.
VPExpressionRecipe(VPWidenCastRecipe *Ext0, VPWidenCastRecipe *Ext1, VPWidenRecipe *Mul, VPWidenRecipe *Neg, VPReductionRecipe *Red)
Definition VPlan.h:3715
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
unsigned getVFScaleFactor() const
Definition VPlan.h:3773
VPExpressionRecipe(VPWidenRecipe *Mul, VPReductionRecipe *Red)
Definition VPlan.h:3709
A pure virtual base class for all recipes modeling header phis, including phis for first order recurr...
Definition VPlan.h:2487
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this header phi recipe.
const VPRecipeBase * getAsRecipe() const override
Return a VPRecipeBase* to the current object.
Definition VPlan.h:2494
void addBackedgeValue(VPValue *V)
Add V as the incoming value from the loop backedge.
Definition VPlan.h:2536
static bool classof(const VPSingleDefRecipe *R)
Definition VPlan.h:2507
static bool classof(const VPValue *V)
Definition VPlan.h:2504
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override=0
Print the recipe.
VPHeaderPHIRecipe(VPRecipeTy VPRecipeID, Instruction *UnderlyingInstr, VPValue *Start, Type *ResultTy, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:2489
virtual VPValue * getBackedgeValue()
Returns the incoming value from the loop backedge.
Definition VPlan.h:2530
void setBackedgeValue(VPValue *V)
Update the incoming value from the loop backedge.
Definition VPlan.h:2533
VPValue * getStartValue()
Returns the start value of the phi, if one is set.
Definition VPlan.h:2519
void setStartValue(VPValue *V)
Update the start value of the recipe.
Definition VPlan.h:2527
static bool classof(const VPRecipeBase *R)
Method to support type inquiry through isa, cast, and dyn_cast.
Definition VPlan.h:2500
VPValue * getStartValue() const
Definition VPlan.h:2522
void execute(VPTransformState &State) override=0
Generate the phi nodes.
~VPHeaderPHIRecipe() override=default
A recipe representing a sequence of load -> update -> store as part of a histogram operation.
Definition VPlan.h:2198
VPHistogramRecipe(HistogramUpdateKind UpdateKind, ArrayRef< VPValue * > Operands, const VPIRMetadata &Metadata={}, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:2203
void execute(VPTransformState &State) override
Produce a vectorized histogram operation.
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:2232
VPHistogramRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:2212
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPHistogramRecipe.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPValue * getMask() const
Return the mask operand if one was provided, or a null pointer if all lanes should be executed uncond...
Definition VPlan.h:2227
VP_CLASSOF_IMPL(VPRecipeBase::VPHistogramSC)
~VPHistogramRecipe() override=default
Manage IR attributes for call recipes.
Definition VPlan.h:1269
void printFnAttrs(raw_ostream &O) const
Print function attributes carried with this object.
void printRetAttrs(raw_ostream &O) const
Print return-value attributes carried with this object.
MemoryEffects getMemoryEffects(AttributeSet CalleeFnAttrs) const
Returns the memory effects of a call with these attributes to a callee with function attributes Calle...
Definition VPlan.h:1293
VPIRAttributes()=default
VPIRAttributes(AttributeList CallAttrs)
Definition VPlan.h:1275
bool hasFnAttr(Attribute::AttrKind Kind, AttributeSet CalleeFnAttrs) const
Returns true if the call site or CalleeFnAttrs has Kind.
Definition VPlan.h:1298
void intersectAttrs(const VPIRAttributes &Other, LLVMContext &Ctx)
Keep only the attributes valid for both this and Other.
void printParamAttrs(raw_ostream &O, unsigned ArgIdx) const
Print per-arg attributes for argument ArgIdx.
void applyAttrs(CallInst &WideCall) const
Apply the stored attributes to the widened call WideCall.
Definition VPlan.h:1287
A special type of VPBasicBlock that wraps an existing IR basic block.
Definition VPlan.h:4692
void execute(VPTransformState *State) override
The method which generates the output IR instructions that correspond to this VPBasicBlock,...
Definition VPlan.cpp:442
BasicBlock * getIRBasicBlock() const
Definition VPlan.h:4716
static bool classof(const VPBlockBase *V)
Definition VPlan.h:4706
~VPIRBasicBlock() override=default
friend class VPlan
Definition VPlan.h:4693
VPIRBasicBlock * clone() override
Clone the current block and it's recipes, without updating the operands of the cloned recipes.
Definition VPlan.cpp:467
Class to record and manage LLVM IR flags.
Definition VPlan.h:683
WrapFlagsTy getNoWrapFlagsOrNone() const
Definition VPlan.h:1007
FastMathFlagsTy FMFs
Definition VPlan.h:775
ReductionFlagsTy ReductionFlags
Definition VPlan.h:777
VPIRFlags(RecurKind Kind, bool IsOrdered, bool IsInLoop, FastMathFlags FMFs)
Definition VPlan.h:868
LLVM_ABI_FOR_TEST bool flagsValidForOpcode(unsigned Opcode) const
Returns true if the set flags are valid for Opcode.
VPIRFlags(DisjointFlagsTy DisjointFlags)
Definition VPlan.h:848
VPIRFlags(WrapFlagsTy WrapFlags)
Definition VPlan.h:834
WrapFlagsTy WrapFlags
Definition VPlan.h:769
void printFlags(raw_ostream &O) const
VPIRFlags(CmpInst::Predicate Pred, FastMathFlags FMFs)
Definition VPlan.h:827
bool hasFastMathFlags() const
Returns true if the recipe has fast-math flags.
Definition VPlan.h:978
static LLVM_ABI_FOR_TEST VPIRFlags getDefaultFlags(unsigned Opcode, Type *ResultTy=nullptr)
Returns default flags for Opcode and scalar ResultTy for opcodes that support it, asserts otherwise.
bool isReductionOrdered() const
Definition VPlan.h:1033
TruncFlagsTy TruncFlags
Definition VPlan.h:770
CmpInst::Predicate getPredicate() const
Definition VPlan.h:950
WrapFlagsTy getNoWrapFlags() const
Definition VPlan.h:1017
LLVM_ABI_FOR_TEST FastMathFlags getFastMathFlagsOrNone() const
uint8_t AllFlags[2]
Definition VPlan.h:778
ExactFlagsTy ExactFlags
Definition VPlan.h:772
bool hasNoSignedWrap() const
Definition VPlan.h:996
void intersectFlags(const VPIRFlags &Other)
Only keep flags also present in Other.
bool isDisjoint() const
Definition VPlan.h:1021
VPIRFlags(TruncFlagsTy TruncFlags)
Definition VPlan.h:839
VPIRFlags(FastMathFlags FMFs)
Definition VPlan.h:844
VPIRFlags(NonNegFlagsTy NonNegFlags)
Definition VPlan.h:853
VPIRFlags(CmpInst::Predicate Pred)
Definition VPlan.h:822
uint8_t GEPFlagsStorage
Definition VPlan.h:773
VPIRFlags(ExactFlagsTy ExactFlags)
Definition VPlan.h:858
GEPNoWrapFlags getGEPNoWrapFlags() const
Definition VPlan.h:968
bool hasPredicate() const
Returns true if the recipe has a comparison predicate.
Definition VPlan.h:973
LLVM_ABI_FOR_TEST bool hasRequiredFlagsForOpcode(unsigned Opcode, Type *ResultTy) const
Returns true if Opcode with scalar result type ResultTy has its required flags set.
DisjointFlagsTy DisjointFlags
Definition VPlan.h:771
void setPredicate(CmpInst::Predicate Pred)
Definition VPlan.h:958
bool hasNoUnsignedWrap() const
Definition VPlan.h:985
FCmpFlagsTy FCmpFlags
Definition VPlan.h:776
NonNegFlagsTy NonNegFlags
Definition VPlan.h:774
bool isReductionInLoop() const
Definition VPlan.h:1039
void dropPoisonGeneratingFlags()
Drop all poison-generating flags.
Definition VPlan.h:878
void applyFlags(Instruction &I) const
Apply the IR flags to I.
Definition VPlan.h:915
VPIRFlags(GEPNoWrapFlags GEPFlags)
Definition VPlan.h:863
uint8_t CmpPredStorage
Definition VPlan.h:768
RecurKind getRecurKind() const
Definition VPlan.h:1027
VPIRFlags(Instruction &I)
Definition VPlan.h:784
Instruction & getInstruction() const
Definition VPlan.h:1767
bool usesFirstPartOnly(const VPValue *Op) const override
Returns true if the VPUser only uses the first part of operand Op.
Definition VPlan.h:1775
~VPIRInstruction() override=default
void execute(VPTransformState &State) override
The method which generates the output IR instructions that correspond to this VPRecipe,...
VPIRInstruction * clone() override
Clone the current recipe.
Definition VPlan.h:1754
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the VPUser only uses the first lane of operand Op.
Definition VPlan.h:1781
static LLVM_ABI_FOR_TEST VPIRInstruction * create(Instruction &I)
Create a new VPIRPhi for \I , if it is a PHINode, otherwise create a VPIRInstruction.
LLVM_ABI_FOR_TEST InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPIRInstruction.
bool usesScalars(const VPValue *Op) const override
Returns true if the VPUser uses scalars of operand Op.
Definition VPlan.h:1769
VPIRInstruction(Instruction &I)
VPIRInstruction::create() should be used to create VPIRInstructions, as subclasses may need to be cre...
Definition VPlan.h:1742
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
Helper to manage IR metadata for recipes.
Definition VPlan.h:1152
MDNode * getBranchWeights() const
Returns the branch weights recorded for this terminator, preferring real profile data over an estimat...
Definition VPlan.h:1241
VPIRMetadata & operator=(const VPIRMetadata &Other)=default
MDNode * getMetadata(unsigned Kind) const
Get metadata of kind Kind. Returns nullptr if not found.
Definition VPlan.h:1222
VPIRMetadata(Instruction &I)
Adds metatadata that can be preserved from the original instruction I.
Definition VPlan.h:1181
VPIRMetadata(const VPIRMetadata &Other)=default
Copy constructor for cloning.
VPIRMetadata()=default
void setEstimatedBranchWeights(MDNode *Node)
Set estimated branch weights to Node.
Definition VPlan.h:1252
void applyMetadata(Instruction &I) const
Add all metadata to I.
void setMetadata(unsigned Kind, MDNode *Node)
Set metadata with kind Kind to Node.
Definition VPlan.h:1201
void eraseMetadata(unsigned Kind)
Remove the metadata of kind Kind, if present.
Definition VPlan.h:1213
bool hasEstimatedBranchWeights() const
Returns true if the weights returned by getBranchWeights are estimated.
Definition VPlan.h:1247
This is a concrete Recipe that models a single VPlan-level instruction.
Definition VPlan.h:1322
unsigned getNumOperandsWithoutMask() const
Returns the number of operands, excluding the mask if the VPInstruction is masked.
Definition VPlan.h:1556
iterator_range< operand_iterator > operandsWithoutMask()
Returns an iterator range over the operands excluding the mask operand if present.
Definition VPlan.h:1576
VPInstruction * clone() override
Clone the current recipe.
Definition VPlan.h:1512
@ ExtractLastActive
Extracts the last active lane from a set of vectors.
Definition VPlan.h:1437
@ Intrinsic
Calls a scalar intrinsic. The intrinsic ID is the last operand.
Definition VPlan.h:1449
@ ExtractLane
Extracts a single lane (first operand) from a set of vector operands.
Definition VPlan.h:1427
@ ExitingIVValue
Compute the exiting value of a wide induction after vectorization, that is the value of the last lane...
Definition VPlan.h:1441
@ WideIVStep
Scale the first operand (vector step) by the second operand (scalar-step).
Definition VPlan.h:1445
@ ResumeForEpilogue
Explicit user for values in the main VPlan, used by the epilogue vector loop.
Definition VPlan.h:1431
@ Unpack
Extracts all lanes from its (non-scalable) vector operand.
Definition VPlan.h:1378
@ ReductionStartVector
Start vector for reductions with 3 operands: the original start value, the identity value for the red...
Definition VPlan.h:1423
@ BuildVector
Creates a fixed-width vector containing all operands.
Definition VPlan.h:1373
@ CanonicalIVIncrementForPart
Definition VPlan.h:1358
@ ComputeReductionResult
Reduce the operands to the final reduction result using the operation specified via the operation's V...
Definition VPlan.h:1381
bool hasResult() const
Definition VPlan.h:1543
iterator_range< const_operand_iterator > operandsWithoutMask() const
Definition VPlan.h:1579
void addMask(VPValue *Mask)
Add mask Mask to an unmasked VPInstruction, if it needs masking.
Definition VPlan.h:1561
StringRef getName() const
Returns the symbolic name assigned to the VPInstruction.
Definition VPlan.h:1606
unsigned getOpcode() const
Definition VPlan.h:1525
void setName(StringRef NewName)
Set the symbolic name for the VPInstruction.
Definition VPlan.h:1609
bool usesScalars(const VPValue *Op) const override
Returns true if the recipe only uses scalars of operand Op.
Definition VPlan.h:1590
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
VPInstruction(unsigned Opcode, ArrayRef< VPValue * > Operands, const VPIRFlags &Flags={}, const VPIRMetadata &MD={}, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="", Type *ResultTy=nullptr, const VPIRAttributes &Attrs={})
VPValue * getMask() const
Returns the mask for the VPInstruction.
Definition VPlan.h:1572
bool isSingleScalar() const
Returns true if the recipe produces a single scalar value.
VPInstruction * cloneWithOperands(ArrayRef< VPValue * > NewOperands, Type *ResultTy=nullptr)
Definition VPlan.h:1516
unsigned getNumOperandsForOpcode() const
Return the number of operands determined by the opcode of the VPInstruction, excluding mask.
bool isMasked() const
Returns true if the VPInstruction has a mask operand.
Definition VPlan.h:1546
A common base class for interleaved memory operations.
Definition VPlan.h:3140
virtual unsigned getNumStoreOperands() const =0
Returns the number of stored operands of this interleave group.
VPInterleaveBase(VPRecipeTy SC, const InterleaveGroup< Instruction > *IG, ArrayRef< VPValue * > Operands, ArrayRef< VPValue * > StoredValues, VPValue *Mask, bool NeedsMaskForGaps, const VPIRMetadata &MD, DebugLoc DL)
Definition VPlan.h:3152
bool usesFirstLaneOnly(const VPValue *Op) const override=0
Returns true if the recipe only uses the first lane of operand Op.
bool needsMaskForGaps() const
Return true if the access needs a mask because of the gaps.
Definition VPlan.h:3202
void execute(VPTransformState &State) override
The method which generates the output IR instructions that correspond to this VPRecipe,...
Definition VPlan.h:3208
static bool classof(const VPUser *U)
Definition VPlan.h:3184
Instruction * getInsertPos() const
Definition VPlan.h:3206
static bool classof(const VPRecipeBase *R)
Definition VPlan.h:3179
const InterleaveGroup< Instruction > * getInterleaveGroup() const
Definition VPlan.h:3204
VPValue * getMask() const
Return the mask used by this recipe.
Definition VPlan.h:3196
ArrayRef< VPValue * > getStoredValues() const
Return the VPValues stored by this interleave group.
Definition VPlan.h:3225
VPInterleaveBase * clone() override=0
Clone the current recipe.
VPValue * getAddr() const
Return the address accessed by this recipe.
Definition VPlan.h:3190
bool usesFirstLaneOnly(const VPValue *Op) const override
The recipe only uses the first lane of the address, and EVL operand.
Definition VPlan.h:3305
VPValue * getEVL() const
The VPValue of the explicit vector length.
Definition VPlan.h:3299
~VPInterleaveEVLRecipe() override=default
unsigned getNumStoreOperands() const override
Returns the number of stored operands of this interleave group.
Definition VPlan.h:3312
VPInterleaveEVLRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:3292
VPInterleaveEVLRecipe(VPInterleaveRecipe &R, VPValue &EVL, VPValue *Mask)
Definition VPlan.h:3279
VPInterleaveRecipe is a recipe for transforming an interleave group of load or stores into one wide l...
Definition VPlan.h:3235
unsigned getNumStoreOperands() const override
Returns the number of stored operands of this interleave group.
Definition VPlan.h:3262
~VPInterleaveRecipe() override=default
VPInterleaveRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:3245
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:3256
VPInterleaveRecipe(const InterleaveGroup< Instruction > *IG, VPValue *Addr, ArrayRef< VPValue * > StoredValues, VPValue *Mask, bool NeedsMaskForGaps, const VPIRMetadata &MD, DebugLoc DL)
Definition VPlan.h:3237
A VPRecipeValue defined by a multi-def recipe, stores a pointer to it.
Definition VPlanValue.h:376
Helper type to provide functions to access incoming values and blocks for phi-like recipes.
Definition VPlan.h:1621
virtual const VPRecipeBase * getAsRecipe() const =0
Return a VPRecipeBase* to the current object.
LLVM_ABI_FOR_TEST VPValue * getIncomingValueForBlock(const VPBasicBlock *VPBB) const
Returns the incoming value for VPBB. VPBB must be an incoming block.
VPUser::const_operand_range incoming_values() const
Returns an interator range over the incoming values.
Definition VPlan.h:1651
void addIncoming(VPValue *IncomingV)
Append IncomingV as an incoming value to the phi-like recipe.
Definition VPlan.h:1680
virtual unsigned getNumIncoming() const
Returns the number of incoming values, also number of incoming blocks.
Definition VPlan.h:1646
void removeIncomingValueFor(VPBlockBase *IncomingBlock) const
Removes the incoming value for IncomingBlock, which must be a predecessor.
const VPBasicBlock * getIncomingBlock(unsigned Idx) const
Returns the incoming block with index Idx.
Definition VPlan.h:4683
detail::zippy< llvm::detail::zip_first, VPUser::const_operand_range, const_incoming_blocks_range > incoming_values_and_blocks() const
Returns an iterator range over pairs of incoming values and corresponding incoming blocks.
Definition VPlan.h:1671
VPValue * getIncomingValue(unsigned Idx) const
Returns the incoming VPValue with index Idx.
Definition VPlan.h:1630
virtual ~VPPhiAccessors()=default
void printPhiOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const
Print the recipe.
void setIncomingValueForBlock(const VPBasicBlock *VPBB, VPValue *V) const
Sets the incoming value for VPBB to V.
iterator_range< mapped_iterator< detail::index_iterator, std::function< const VPBasicBlock *(size_t)> > > const_incoming_blocks_range
Definition VPlan.h:1656
const_incoming_blocks_range incoming_blocks() const
Returns an iterator range over the incoming blocks.
Definition VPlan.h:1660
~VPPredInstPHIRecipe() override=default
VPPredInstPHIRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:3819
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPPredInstPHIRecipe.
Definition VPlan.h:3830
VPPredInstPHIRecipe(VPValue *PredV, DebugLoc DL)
Construct a VPPredInstPHIRecipe given PredInst whose value needs a phi nodes after merging back from ...
Definition VPlan.h:3814
VPRecipeBase is a base class modeling a sequence of one or more output IR instructions.
Definition VPlan.h:402
bool mayReadFromMemory() const
Returns true if the recipe may read from memory.
void moveBefore(RecipeListTy::iterator I)
Unlink this recipe and insert it before I.
bool mayReadOrWriteMemory() const
Returns true if the recipe may read from or write to memory.
Definition VPlan.h:542
virtual void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const =0
Each concrete VPRecipe prints itself, without printing common information, like debug info or metadat...
VPRegionBlock * getRegion()
Definition VPlan.h:4938
RecipeListTy::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
void setDebugLoc(DebugLoc NewDL)
Set the recipe's debug location to NewDL.
Definition VPlan.h:550
bool mayWriteToMemory() const
Returns true if the recipe may write to memory.
VPRecipeTy getVPRecipeID() const
Definition VPlan.h:515
~VPRecipeBase() override=default
DebugLoc getDebugLoc() const
Returns the debug location of the recipe.
Definition VPlan.h:547
virtual void execute(VPTransformState &State)=0
The method which generates the output IR instructions that correspond to this VPRecipe,...
iplist< VPRecipeBase, ilist_parent< VPBasicBlock > > RecipeListTy
The list type holding the recipes of a VPBasicBlock.
Definition VPlan.h:473
void insertBefore(VPRecipeBase *InsertPos)
Insert an unlinked recipe into a basic block immediately before the specified recipe.
void insertAfter(VPRecipeBase *InsertPos)
Insert an unlinked Recipe into a basic block immediately after the specified Recipe.
static bool classof(const VPDef *D)
Method to support type inquiry through isa, cast, and dyn_cast.
Definition VPlan.h:518
virtual VPRecipeBase * clone()=0
Clone the current recipe.
friend class VPBlockUtils
Definition VPlan.h:404
VPRecipeBase(VPRecipeTy SC, ArrayRef< VPValue * > Operands, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:462
InstructionCost cost(ElementCount VF, VPCostContext &Ctx)
Return the cost of this recipe, taking into account if the cost computation should be skipped and the...
static bool classof(const VPUser *U)
Definition VPlan.h:523
void removeFromParent()
This method unlinks 'this' from the containing basic block, but does not delete it.
enum :unsigned char { VPBranchOnMaskSC, VPDerivedIVSC, VPExpandSCEVSC, VPExpressionSC, VPIRInstructionSC, VPInstructionSC, VPInterleaveEVLSC, VPInterleaveSC, VPReductionEVLSC, VPReductionSC, VPReplicateSC, VPScalarIVStepsSC, VPVectorPointerSC, VPVectorEndPointerSC, VPWidenCallSC, VPWidenCanonicalIVSC, VPWidenCastSC, VPWidenGEPSC, VPWidenIntrinsicSC, VPWidenMemIntrinsicSC, VPWidenLoadEVLSC, VPWidenLoadSC, VPWidenStoreEVLSC, VPWidenStoreSC, VPWidenSC, VPBlendSC, VPHistogramSC, VPWidenPHISC, VPPredInstPHISC, VPCurrentIterationPHISC, VPActiveLaneMaskPHISC, VPFirstOrderRecurrencePHISC, VPWidenIntOrFpInductionSC, VPWidenPointerInductionSC, VPReductionPHISC, VPConditionalInductionPHISC, VPFirstPHISC=VPWidenPHISC, VPFirstHeaderPHISC=VPCurrentIterationPHISC, VPLastHeaderPHISC=VPConditionalInductionPHISC, VPLastPHISC=VPConditionalInductionPHISC, } VPRecipeTy
An enumeration for keeping track of the concrete subclass of VPRecipeBase that is actually instantiat...
Definition VPlan.h:414
void moveAfter(VPRecipeBase *MovePos)
Unlink this recipe from its current VPBasicBlock and insert it into the VPBasicBlock that MovePos liv...
Type * getScalarType() const
Returns the scalar type of this VPRecipeValue.
Definition VPlanValue.h:349
VPValue * getEVL() const
The VPValue of the explicit vector length.
Definition VPlan.h:3473
VPReductionEVLRecipe(VPReductionRecipe &R, VPValue &EVL, VPValue *CondOp, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:3451
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:3476
VPReductionEVLRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:3463
~VPReductionEVLRecipe() override=default
bool isOrdered() const
Returns true, if the phi is part of an ordered reduction.
Definition VPlan.h:2962
void setVFScaleFactor(unsigned ScaleFactor)
Set the VFScaleFactor for this reduction phi.
Definition VPlan.h:2953
VPReductionPHIRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:2935
unsigned getVFScaleFactor() const
Get the factor that the VF of this recipe's output should be scaled by, or 1 if it isn't scaled.
Definition VPlan.h:2946
~VPReductionPHIRecipe() override=default
bool isExpressionSunk() const
Definition VPlan.h:2977
bool hasUsesOutsideReductionChain() const
Returns true, if the phi is part of a multi-use reduction.
Definition VPlan.h:2971
VPReductionPHIRecipe(PHINode *Phi, RecurKind Kind, VPValue &Start, VPValue &BackedgeValue, ReductionStyle Style, const VPIRFlags &Flags, bool HasUsesOutsideReductionChain=false)
Create a new VPReductionPHIRecipe for the reduction Phi.
Definition VPlan.h:2913
bool isInLoop() const
Returns true if the phi is part of an in-loop reduction.
Definition VPlan.h:2965
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:2980
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
Generate the phi/select nodes.
VPReductionPHIRecipe * cloneWithOperands(VPValue *Start, VPValue *BackedgeValue)
Definition VPlan.h:2926
RecurKind getRecurrenceKind() const
Returns the recurrence kind of the reduction.
Definition VPlan.h:2959
A recipe to represent inloop, ordered or partial reduction operations.
Definition VPlan.h:3328
bool isConditional() const
Return true if the in-loop reduction is conditional.
Definition VPlan.h:3412
static bool classof(const VPRecipeBase *R)
Definition VPlan.h:3381
static bool classof(const VPSingleDefRecipe *R)
Definition VPlan.h:3396
VPValue * getVecOp() const
The VPValue of the vector value to be reduced.
Definition VPlan.h:3425
VPValue * getCondOp() const
The VPValue of the condition for the block.
Definition VPlan.h:3427
RecurKind getRecurrenceKind() const
Return the recurrence kind for the in-loop reduction.
Definition VPlan.h:3408
VPReductionRecipe(RecurKind RdxKind, FastMathFlags FMFs, Instruction *I, VPValue *ChainOp, VPValue *VecOp, VPValue *CondOp, ReductionStyle Style, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:3361
bool isOrdered() const
Return true if the in-loop reduction is ordered.
Definition VPlan.h:3410
VPReductionRecipe(const RecurKind RdxKind, FastMathFlags FMFs, VPValue *ChainOp, VPValue *VecOp, VPValue *CondOp, ReductionStyle Style, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:3367
VPReductionRecipe(VPRecipeTy SC, RecurKind RdxKind, FastMathFlags FMFs, Instruction *I, ArrayRef< VPValue * > Operands, VPValue *CondOp, ReductionStyle Style, DebugLoc DL)
Definition VPlan.h:3337
bool isPartialReduction() const
Returns true if the reduction outputs a vector with a scaled down VF.
Definition VPlan.h:3414
~VPReductionRecipe() override=default
VPValue * getChainOp() const
The VPValue of the scalar Chain being accumulated.
Definition VPlan.h:3423
bool isInLoop() const
Returns true if the reduction is in-loop.
Definition VPlan.h:3418
VPReductionRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:3375
static bool classof(const VPUser *U)
Definition VPlan.h:3386
static bool classof(const VPValue *VPV)
Definition VPlan.h:3391
unsigned getVFScaleFactor() const
Get the factor that the VF of this recipe's output should be scaled by, or 1 if it isn't scaled.
Definition VPlan.h:3432
VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks which form a Single-Entry-S...
Definition VPlan.h:4764
const VPBlockBase * getEntry() const
Definition VPlan.h:4808
bool isReplicator() const
An indicator whether this region is to generate multiple replicated instances of output IR correspond...
Definition VPlan.h:4840
~VPRegionBlock() override=default
VPRegionValue * createHeaderMask()
Create the header mask for the region and return it.
Definition VPlan.h:4911
VPRegionValue * getUsedHeaderMask() const
Return the header mask if it exists and is used, or null otherwise.
Definition VPlan.h:4904
void setExiting(VPBlockBase *ExitingBlock)
Set ExitingBlock as the exiting VPBlockBase of this VPRegionBlock.
Definition VPlan.h:4825
VPBlockBase * getExiting()
Definition VPlan.h:4821
VPBranchOnMaskRecipe * getEntryBranchOnMask()
Definition VPlan.h:4845
const VPRegionValue * getCanonicalIV() const
Definition VPlan.h:4887
SmallVector< VPRegionValue *, 2 > getRegionValues() const
Return the region values of the loop region (canonical IV, header mask) or an empty vector for replic...
Definition VPlan.h:4918
void setEntry(VPBlockBase *EntryBlock)
Set EntryBlock as the entry VPBlockBase of this VPRegionBlock.
Definition VPlan.h:4813
Type * getCanonicalIVType() const
Return the type of the canonical IV for loop regions.
Definition VPlan.h:4892
bool hasCanonicalIVNUW() const
Indicates if NUW is set for the canonical IV increment, for loop regions.
Definition VPlan.h:4928
void clearCanonicalIVNUW(VPInstruction *Increment)
Unsets NUW for the canonical IV increment Increment, for loop regions.
Definition VPlan.h:4931
VPRegionValue * getCanonicalIV()
Return the canonical induction variable of the region, null for replicating regions.
Definition VPlan.h:4884
const VPBlockBase * getExiting() const
Definition VPlan.h:4820
VPBlockBase * getEntry()
Definition VPlan.h:4809
VPBasicBlock * getPreheaderVPBB()
Returns the pre-header VPBasicBlock of the loop region.
Definition VPlan.h:4833
VPRegionValue * getHeaderMask() const
Return the header mask of the region, or null if not set.
Definition VPlan.h:4897
friend class VPlan
Definition VPlan.h:4765
static bool classof(const VPBlockBase *V)
Method to support type inquiry through isa, cast, and dyn_cast.
Definition VPlan.h:4804
VPValues are defined by a VPRegionBlock, like the canonical IV.
Definition VPlanValue.h:247
VPReplicateRecipe replicates a given instruction producing multiple scalar copies of the original sca...
Definition VPlan.h:3495
bool isSingleScalar() const
Returns true if the recipe produces a single scalar value.
Definition VPlan.h:3552
unsigned getNumOperandsWithoutMask() const
Returns the number of operands, excluding the mask if the recipe is predicated.
Definition VPlan.h:3586
VPReplicateRecipe(Instruction *I, ArrayRef< VPValue * > Operands, bool IsSingleScalar, VPValue *Mask=nullptr, const VPIRFlags &Flags={}, VPIRMetadata Metadata={}, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:3503
~VPReplicateRecipe() override=default
static Type * computeScalarType(const Instruction *I, ArrayRef< VPValue * > Operands)
Compute the scalar result type for a VPReplicateRecipe wrapping I with Operands (excluding any predic...
VPReplicateRecipe * cloneWithOperands(ArrayRef< VPValue * > NewOperands)
Definition VPlan.h:3527
bool usesScalars(const VPValue *Op) const override
Returns true if the recipe uses scalars of operand Op.
Definition VPlan.h:3567
operand_range operandsWithoutMask()
Return the recipe's operands, excluding the mask of a predicated recipe.
Definition VPlan.h:3580
bool isPredicated() const
Definition VPlan.h:3557
VPReplicateRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:3525
bool doesGeneratePerAllLanes() const
Returns true if the recipe produces scalar values for all VF lanes.
Definition VPlan.h:3555
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:3560
unsigned getOpcode() const
Definition VPlan.h:3590
VPValue * getMask()
Return the mask of a predicated VPReplicateRecipe.
Definition VPlan.h:3574
Instruction::BinaryOps getInductionOpcode() const
Definition VPlan.h:4425
VPValue * getStepValue() const
Definition VPlan.h:4395
void setStartIndex(VPValue *StartIndex)
Set or add the StartIndex operand.
Definition VPlan.h:4408
VPScalarIVStepsRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:4377
VPValue * getStartIndex() const
Return the StartIndex, or null if known to be zero, valid only after unrolling.
Definition VPlan.h:4403
VPValue * getVFValue() const
Return the number of scalars to produce per unroll part, used to compute StartIndex during unrolling.
Definition VPlan.h:4399
VPScalarIVStepsRecipe(VPValue *IV, VPValue *Step, VPValue *VF, Instruction::BinaryOps Opcode, FastMathFlags FMFs={}, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:4368
~VPScalarIVStepsRecipe() override=default
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:4419
VPSingleDefRecipe is a base class for recipes that model a sequence of one or more output IR that def...
Definition VPlan.h:605
static bool classof(const VPValue *V)
Definition VPlan.h:655
Instruction * getUnderlyingInstr()
Returns the underlying instruction.
Definition VPlan.h:668
static bool classof(const VPRecipeBase *R)
Definition VPlan.h:611
const Instruction * getUnderlyingInstr() const
Definition VPlan.h:671
VPSingleDefRecipe(VPRecipeTy SC, ArrayRef< VPValue * > Operands, Type *ResultTy, Value *UV=nullptr, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:607
static bool classof(const VPUser *U)
Definition VPlan.h:660
VPSingleDefRecipe * clone() override=0
Clone the current recipe.
VPSingleDefValue(VPSingleDefRecipe *Def, Value *UV=nullptr, Type *Ty=nullptr)
Construct a VPSingleDefValue. Must only be used by VPSingleDefRecipe.
Definition VPlan.cpp:162
This class can be used to assign names to VPValues.
A symbolic live-in VPValue, used for values like vector trip count, VF, and VFxUF.
Definition VPlanValue.h:212
This class augments VPValue with operands which provide the inverse def-use edges from VPValue's user...
Definition VPlanValue.h:396
void printOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const
Print the operands to O.
Definition VPlan.cpp:1521
operand_range operands()
Definition VPlanValue.h:472
void setOperand(unsigned I, VPValue *New)
Definition VPlanValue.h:445
unsigned getNumOperands() const
Definition VPlanValue.h:436
operand_iterator op_end()
Definition VPlanValue.h:470
operand_iterator op_begin()
Definition VPlanValue.h:468
VPValue * getOperand(unsigned N) const
Definition VPlanValue.h:437
VPUser(ArrayRef< VPValue * > Operands)
Definition VPlanValue.h:417
iterator_range< const_operand_iterator > const_operand_range
Definition VPlanValue.h:466
VPValue * getLastOperand() const
Returns the last operand.
Definition VPlanValue.h:443
iterator_range< operand_iterator > operand_range
Definition VPlanValue.h:465
void addOperand(VPValue *Operand)
Definition VPlanValue.h:422
This is the base class of the VPlan Def/Use graph, used for modeling the data flow into,...
Definition VPlanValue.h:50
Type * getScalarType() const
Returns the scalar type of this VPValue, dispatching based on the concrete subclass.
Definition VPlan.cpp:142
Value * getLiveInIRValue() const
Return the underlying IR value for a VPIRValue.
Definition VPlan.cpp:136
VPRecipeBase * getDefiningRecipe()
Returns the recipe defining this VPValue or nullptr if it is not defined by a recipe,...
Definition VPlan.cpp:123
Value * getUnderlyingValue() const
Return the underlying Value attached to this VPValue.
Definition VPlanValue.h:75
bool user_empty() const
Definition VPlanValue.h:161
void setUnderlyingValue(Value *Val)
Definition VPlanValue.h:204
unsigned getNumUsers() const
Definition VPlanValue.h:115
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the VPUser only uses the first lane of operand Op.
Definition VPlan.h:2357
VPValue * getVFValue() const
Definition VPlan.h:2338
void execute(VPTransformState &State) override
The method which generates the output IR instructions that correspond to this VPRecipe,...
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
Type * getSourceElementType() const
Definition VPlan.h:2335
int64_t getStride() const
Definition VPlan.h:2336
VPVectorEndPointerRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:2378
VPValue * getOffset() const
Definition VPlan.h:2339
bool usesFirstPartOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first part of operand Op.
Definition VPlan.h:2371
void addOffset(VPValue *Offset)
Append Offset as the offset operand.
Definition VPlan.h:2349
VPVectorEndPointerRecipe(VPValue *Ptr, VPValue *VF, Type *SourceElementTy, int64_t Stride, GEPNoWrapFlags GEPFlags, DebugLoc DL)
Definition VPlan.h:2325
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPVectorPointerRecipe.
Definition VPlan.h:2364
VPValue * getPointer() const
Definition VPlan.h:2337
void materializeOffset(unsigned Part=0)
Adds the offset operand to the recipe.
void addPerPartOffset(VPValue *VFxPart)
Add the per-part offset (VFxPart) used for unrolled parts > 0.
Definition VPlan.h:2419
VPValue * getStride() const
Definition VPlan.h:2412
Type * getSourceElementType() const
Definition VPlan.h:2427
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the VPUser only uses the first lane of operand Op.
Definition VPlan.h:2429
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
The method which generates the output IR instructions that correspond to this VPRecipe,...
bool usesFirstPartOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first part of operand Op.
Definition VPlan.h:2436
VPVectorPointerRecipe(VPValue *Ptr, Type *SourceElementTy, VPValue *Stride, GEPNoWrapFlags GEPFlags, DebugLoc DL)
Definition VPlan.h:2403
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPHeaderPHIRecipe.
Definition VPlan.h:2453
VPVectorPointerRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:2443
VPValue * getVFxPart() const
Definition VPlan.h:2414
A recipe for widening Call instructions using library calls.
Definition VPlan.h:2132
const_operand_range args() const
Definition VPlan.h:2180
VPWidenCallRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:2158
operand_range args()
Definition VPlan.h:2179
Function * getCalledScalarFunction() const
Definition VPlan.h:2175
VPWidenCallRecipe(Value *UV, Function *Variant, ArrayRef< VPValue * > CallArguments, const VPIRFlags &Flags={}, const VPIRMetadata &Metadata={}, const VPIRAttributes &Attrs={}, DebugLoc DL={})
Definition VPlan.h:2139
~VPWidenCallRecipe() override=default
~VPWidenCanonicalIVRecipe() override=default
VPValue * getStepValue() const
Definition VPlan.h:4281
void addPerPartStep(VPValue *Step)
Add the per-part step (VF * Part) used for unrolled parts.
Definition VPlan.h:4286
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenCanonicalIVPHIRecipe.
Definition VPlan.h:4270
VPRegionValue * getCanonicalIV() const
Return the canonical IV being widened.
Definition VPlan.h:4277
VPWidenCanonicalIVRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:4255
VPWidenCanonicalIVRecipe(VPRegionValue *CanonicalIV, const VPIRFlags::WrapFlagsTy &Flags={})
Definition VPlan.h:4248
void execute(VPTransformState &State) override
The method which generates the output IR instructions that correspond to this VPRecipe,...
Definition VPlan.h:4265
VPWidenCastRecipe is a recipe to create vector cast instructions.
Definition VPlan.h:1899
Instruction::CastOps getOpcode() const
Definition VPlan.h:1935
~VPWidenCastRecipe() override=default
VPWidenCastRecipe(Instruction::CastOps Opcode, VPValue *Op, Type *ResultTy, CastInst *CI=nullptr, const VPIRFlags &Flags={}, const VPIRMetadata &Metadata={}, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:1904
VPWidenCastRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:1920
unsigned getOpcode() const
This recipe generates a GEP instruction.
Definition VPlan.h:2287
Type * getSourceElementType() const
Definition VPlan.h:2292
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenGEPRecipe.
Definition VPlan.h:2295
VPWidenGEPRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:2278
~VPWidenGEPRecipe() override=default
VPWidenGEPRecipe(Type *SourceElementTy, ArrayRef< VPValue * > Operands, const VPIRFlags &Flags={}, DebugLoc DL=DebugLoc::getUnknown(), GetElementPtrInst *UV=nullptr)
Definition VPlan.h:2261
void execute(VPTransformState &State) override=0
Generate the phi nodes.
ArrayRef< const SCEVPredicate * > getNoWrapPredicates() const
Returns the SCEV predicates associated with this induction.
Definition VPlan.h:2617
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:2629
static bool classof(const VPValue *V)
Definition VPlan.h:2585
VPValue * getBackedgeValue() override
Returns the incoming value from the loop backedge.
Definition VPlan.h:2621
unsigned getNumIncoming() const override
Returns the number of incoming values, also number of incoming blocks.
Definition VPlan.h:2606
PHINode * getPHINode() const
Returns the underlying PHINode if one exists, or null otherwise.
Definition VPlan.h:2609
VPValue * getStepValue()
Returns the step value of the induction.
Definition VPlan.h:2597
const InductionDescriptor & getInductionDescriptor() const
Returns the induction descriptor for the recipe.
Definition VPlan.h:2614
static bool classof(const VPRecipeBase *R)
Definition VPlan.h:2580
VPWidenInductionRecipe(VPRecipeTy Kind, PHINode *IV, VPValue *Start, VPValue *Step, const InductionDescriptor &IndDesc, Type *ResultTy, DebugLoc DL)
Definition VPlan.h:2559
const VPValue * getVFValue() const
Definition VPlan.h:2601
static bool classof(const VPSingleDefRecipe *R)
Definition VPlan.h:2590
const VPValue * getStepValue() const
Definition VPlan.h:2598
void addUnrolledPartOperands(VPValue *SplatVFStep, VPValue *LastPart)
After unrolling, append the splat-VF step (VF * step) and the value of the induction at the last unro...
Definition VPlan.h:2568
void execute(VPTransformState &State) override
Generate the phi nodes.
Definition VPlan.h:2678
~VPWidenIntOrFpInductionRecipe() override=default
VPValue * getSplatVFValue() const
If the recipe has been unrolled, return the VPValue for the induction increment, otherwise return nul...
Definition VPlan.h:2685
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenIntOrFpInductionRecipe.
VPWidenIntOrFpInductionRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:2670
VPWidenIntOrFpInductionRecipe(PHINode *IV, VPValue *Start, VPValue *Step, VPValue *VF, const InductionDescriptor &IndDesc, const VPIRFlags &Flags, DebugLoc DL)
Definition VPlan.h:2648
bool isTruncated() const
Returns true if this induction is evaluated in a narrower type than the start value.
Definition VPlan.h:2696
VPWidenIntOrFpInductionRecipe(PHINode *IV, VPValue *Start, VPValue *Step, VPValue *VF, const InductionDescriptor &IndDesc, Type *ResultTy, const VPIRFlags &Flags, DebugLoc DL)
Definition VPlan.h:2658
VPValue * getLastUnrolledPartOperand()
Returns the VPValue representing the value of this induction at the last unrolled part,...
Definition VPlan.h:2714
unsigned getNumIncoming() const override
Returns the number of incoming values, also number of incoming blocks.
Definition VPlan.h:2692
bool isCanonical() const
Returns true if the induction is canonical, i.e.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
A recipe for widening vector intrinsics.
Definition VPlan.h:1947
VPWidenIntrinsicRecipe(VPRecipeTy SC, Intrinsic::ID VectorIntrinsicID, ArrayRef< VPValue * > CallArguments, Type *Ty, const VPIRFlags &Flags={}, const VPIRMetadata &MD={}, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:1961
VPWidenIntrinsicRecipe(Intrinsic::ID VectorIntrinsicID, ArrayRef< VPValue * > CallArguments, Type *Ty, const VPIRFlags &Flags={}, const VPIRMetadata &Metadata={}, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:1996
Intrinsic::ID getVectorIntrinsicID() const
Return the ID of the intrinsic.
Definition VPlan.h:2050
bool mayReadFromMemory() const
Returns true if the intrinsic may read from memory.
Definition VPlan.h:2056
VPWidenIntrinsicRecipe(CallInst &CI, Intrinsic::ID VectorIntrinsicID, ArrayRef< VPValue * > CallArguments, Type *Ty, const VPIRFlags &Flags={}, const VPIRMetadata &MD={}, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:1982
bool mayHaveSideEffects() const
Returns true if the intrinsic may have side-effects.
Definition VPlan.h:2062
static bool classof(const VPSingleDefRecipe *R)
Definition VPlan.h:2032
static bool classof(const VPValue *V)
Definition VPlan.h:2027
VPWidenIntrinsicRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:2007
bool mayWriteToMemory() const
Returns true if the intrinsic may write to memory.
Definition VPlan.h:2059
~VPWidenIntrinsicRecipe() override=default
static bool classof(const VPRecipeBase *R)
Definition VPlan.h:2017
static bool classof(const VPUser *U)
Definition VPlan.h:2022
~VPWidenMemIntrinsicRecipe() override=default
VPWidenMemIntrinsicRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:2099
VPWidenMemIntrinsicRecipe(Intrinsic::ID VectorIntrinsicID, ArrayRef< VPValue * > CallArguments, Type *Ty, Align Alignment, const VPIRMetadata &MD={}, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:2081
A common mixin class for widening memory operations.
Definition VPlan.h:3846
bool IsMasked
Whether the memory access is masked.
Definition VPlan.h:3857
bool isConsecutive() const
Return whether the loaded-from / stored-to addresses are consecutive.
Definition VPlan.h:3882
virtual ~VPWidenMemoryRecipe()=default
Instruction & Ingredient
Definition VPlan.h:3848
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const
Return the cost of this VPWidenMemoryRecipe.
Instruction & getIngredient() const
Definition VPlan.h:3904
bool Consecutive
Whether the accessed addresses are consecutive.
Definition VPlan.h:3854
VPWidenMemoryRecipe(Instruction &I, Align Alignment, bool Consecutive, const VPIRMetadata &Metadata)
Definition VPlan.h:3869
virtual const VPRecipeBase * getAsRecipe() const =0
VPValue * getMask() const
Return the mask used by this recipe.
Definition VPlan.h:3892
Align Alignment
Alignment information for this memory access.
Definition VPlan.h:3851
virtual VPRecipeBase * getAsRecipe()=0
Return a VPRecipeBase* to the current object.
bool isMasked() const
Returns true if the recipe is masked.
Definition VPlan.h:3888
void setMask(VPValue *Mask)
Definition VPlan.h:3859
Align getAlign() const
Returns the alignment of the memory access.
Definition VPlan.h:3899
VPValue * getAddr() const
Return the address accessed by this recipe.
Definition VPlan.h:3885
A recipe for widened phis.
Definition VPlan.h:2777
const VPRecipeBase * getAsRecipe() const override
Return a VPRecipeBase* to the current object.
Definition VPlan.h:2822
unsigned getOpcode() const
This recipe generates a PHI.
Definition VPlan.h:2804
VPWidenPHIRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:2797
~VPWidenPHIRecipe() override=default
VPWidenPHIRecipe(ArrayRef< VPValue * > IncomingValues, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
Create a new VPWidenPHIRecipe with incoming values IncomingValues, debug location DL and Name.
Definition VPlan.h:2784
VPWidenPointerInductionRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:2742
~VPWidenPointerInductionRecipe() override=default
bool onlyScalarsGenerated(bool IsScalable)
Returns true if only scalar values will be generated.
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
Generate vector values for the pointer induction.
Definition VPlan.h:2751
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenPointerInductionRecipe.
VPWidenPointerInductionRecipe(PHINode *Phi, VPValue *Start, VPValue *Step, VPValue *NumUnrolledElems, const InductionDescriptor &IndDesc, DebugLoc DL)
Create a new VPWidenPointerInductionRecipe for Phi with start value Start and the number of elements ...
Definition VPlan.h:2731
VPWidenRecipe is a recipe for producing a widened instruction using the opcode and operands of the re...
Definition VPlan.h:1832
VPWidenRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:1858
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:1887
VPWidenRecipe(Instruction &I, ArrayRef< VPValue * > Operands, const VPIRFlags &Flags={}, const VPIRMetadata &Metadata={}, DebugLoc DL={})
Definition VPlan.h:1836
VPWidenRecipe(unsigned Opcode, ArrayRef< VPValue * > Operands, const VPIRFlags &Flags={}, const VPIRMetadata &Metadata={}, DebugLoc DL={})
Definition VPlan.h:1843
~VPWidenRecipe() override=default
VPWidenRecipe * cloneWithOperands(ArrayRef< VPValue * > NewOperands)
Definition VPlan.h:1860
unsigned getOpcode() const
Definition VPlan.h:1877
VPlan models a candidate for vectorization, encoding various decisions take to produce efficient outp...
Definition VPlan.h:4951
VPIRValue * getLiveIn(Value *V) const
Return the live-in VPIRValue for V, if there is one or nullptr otherwise.
Definition VPlan.h:5281
LLVM_ABI_FOR_TEST void printDOT(raw_ostream &O) const
Print this VPlan in DOT format to O.
Definition VPlan.cpp:1179
friend class VPSlotTracker
Definition VPlan.h:4953
std::string getName() const
Return a string with the name of the plan and the applicable VFs and UFs.
Definition VPlan.cpp:1155
bool hasVF(ElementCount VF) const
Definition VPlan.h:5174
ElementCount getSingleVF() const
Returns the single VF of the plan, asserting that the plan has exactly one VF.
Definition VPlan.h:5187
const DataLayout & getDataLayout() const
Definition VPlan.h:5152
LLVMContext & getContext() const
Definition VPlan.h:5148
VPBasicBlock * getEntry()
Definition VPlan.h:5043
Type * getIndexType() const
The type of the canonical induction variable of the vector loop.
Definition VPlan.h:5387
void setName(const Twine &newName)
Definition VPlan.h:5220
bool hasScalableVF() const
Definition VPlan.h:5175
VPValue * getTripCount() const
The trip count of the original loop.
Definition VPlan.h:5115
iterator_range< SmallSetVector< ElementCount, 2 >::iterator > vectorFactors() const
Returns an iterator range over all VFs of the plan.
Definition VPlan.h:5181
LLVM_ABI_FOR_TEST ~VPlan()
Definition VPlan.cpp:913
VPIRValue * getOrAddLiveIn(VPIRValue *V)
Definition VPlan.h:5238
bool isExitBlock(VPBlockBase *VPBB)
Returns true if VPBB is an exit block.
Definition VPlan.cpp:931
const VPBasicBlock * getEntry() const
Definition VPlan.h:5044
friend class VPlanPrinter
Definition VPlan.h:4952
VPIRValue * getFalse()
Return a VPIRValue wrapping i1 false.
Definition VPlan.h:5247
VPIRValue * getConstantInt(const APInt &Val)
Return a VPIRValue wrapping a ConstantInt with the given APInt value.
Definition VPlan.h:5270
VPSymbolicValue & getVFxUF()
Returns VF * UF of the vector loop region.
Definition VPlan.h:5146
VPIRValue * getAllOnesValue(Type *Ty)
Return a VPIRValue wrapping the AllOnes value of type Ty.
Definition VPlan.h:5253
VPRegionBlock * createReplicateRegion(VPBlockBase *Entry, VPBlockBase *Exiting, const std::string &Name="")
Create a new replicate region with Entry, Exiting and Name.
Definition VPlan.h:5334
VPIRBasicBlock * createEmptyVPIRBasicBlock(BasicBlock *IRBB)
Create a VPIRBasicBlock wrapping IRBB, but do not create VPIRInstructions wrapping the instructions i...
Definition VPlan.cpp:1312
auto getLiveIns() const
Return the list of live-in VPValues available in the VPlan.
Definition VPlan.h:5284
bool hasUF(unsigned UF) const
Definition VPlan.h:5199
VPIRValue * getPoison(Type *Ty)
Return a VPIRValue wrapping a poison value of type Ty.
Definition VPlan.h:5275
ArrayRef< VPIRBasicBlock * > getExitBlocks() const
Return an ArrayRef containing VPIRBasicBlocks wrapping the exit blocks of the original scalar loop.
Definition VPlan.h:5109
VPlan(BasicBlock *ScalarHeaderBB, Type *IdxTy)
Construct a VPlan with a new VPBasicBlock as entry, a VPIRBasicBlock wrapping ScalarHeaderBB and vect...
Definition VPlan.h:5024
VPSymbolicValue & getVectorTripCount()
The vector trip count.
Definition VPlan.h:5136
VPIRValue * getOrAddLiveIn(Value *V)
Gets the live-in VPIRValue for V or adds a new live-in (if none exists yet) for V.
Definition VPlan.h:5224
VPRegionBlock * createLoopRegion(Type *CanIVTy, DebugLoc DL, const std::string &Name="", VPBlockBase *Entry=nullptr, VPBlockBase *Exiting=nullptr)
Create a new loop region with a canonical IV using CanIVTy and DL.
Definition VPlan.h:5320
VPIRValue * getZero(Type *Ty)
Return a VPIRValue wrapping the null value of type Ty.
Definition VPlan.h:5250
void setVF(ElementCount VF)
Definition VPlan.h:5162
unsigned getMaxBlockNumber() const
Definition VPlan.h:5354
bool isUnrolled() const
Returns true if the VPlan already has been unrolled, i.e.
Definition VPlan.h:5215
Function * getIRFunction() const
Definition VPlan.h:5156
LLVM_ABI_FOR_TEST VPRegionBlock * getVectorLoopRegion()
Returns the VPRegionBlock of the vector loop.
Definition VPlan.cpp:1066
bool hasEarlyExit() const
Returns true if the VPlan is based on a loop with an early exit.
Definition VPlan.h:5357
InstructionCost cost(ElementCount VF, VPCostContext &Ctx)
Return the cost of this plan.
Definition VPlan.cpp:1048
LLVM_ABI_FOR_TEST bool isOuterLoop() const
Returns true if this VPlan is for an outer loop, i.e., its vector loop region contains a nested loop ...
Definition VPlan.cpp:1091
unsigned getConcreteUF() const
Returns the concrete UF of the plan, after unrolling.
Definition VPlan.h:5202
VPIRValue * getConstantInt(unsigned BitWidth, uint64_t Val, bool IsSigned=false)
Return a VPIRValue wrapping a ConstantInt with the given bitwidth and value.
Definition VPlan.h:5264
const VPBasicBlock * getMiddleBlock() const
Definition VPlan.h:5094
void setTripCount(VPValue *NewTripCount)
Set the trip count assuming it is currently null; if it is not - use resetTripCount().
Definition VPlan.h:5122
void resetTripCount(VPValue *NewTripCount)
Resets the trip count for the VPlan.
Definition VPlan.h:5129
VPBasicBlock * getMiddleBlock()
Returns the 'middle' block of the plan, that is the block that selects whether to execute the scalar ...
Definition VPlan.h:5085
void setEntry(VPBasicBlock *VPBB)
Definition VPlan.h:5032
VPBasicBlock * createVPBasicBlock(const Twine &Name, VPRecipeBase *Recipe=nullptr)
Create a new VPBasicBlock with Name and containing Recipe if present.
Definition VPlan.h:5307
LLVM_ABI_FOR_TEST VPIRBasicBlock * createVPIRBasicBlock(BasicBlock *IRBB)
Create a VPIRBasicBlock from IRBB containing VPIRInstructions for all instructions in IRBB,...
Definition VPlan.cpp:1320
void removeVF(ElementCount VF)
Remove VF from the plan.
Definition VPlan.h:5169
VPIRValue * getTrue()
Return a VPIRValue wrapping i1 true.
Definition VPlan.h:5244
VPBasicBlock * getVectorPreheader() const
Returns the preheader of the vector loop region, if one exists, or null otherwise.
Definition VPlan.h:5048
bool requiresScalarEpilogue() const
Returns true if the plan requires a scalar epilogue after the vector loop.
Definition VPlan.h:5071
LLVM_DUMP_METHOD void dump() const
Dump the plan to stderr (for debugging).
Definition VPlan.cpp:1185
VPSymbolicValue & getUF()
Returns the UF of the vector loop region.
Definition VPlan.h:5143
bool hasScalarVFOnly() const
Definition VPlan.h:5192
VPBasicBlock * getScalarPreheader() const
Return the VPBasicBlock for the preheader of the scalar loop.
Definition VPlan.h:5099
void execute(VPTransformState *State)
Generate the IR code for this VPlan.
Definition VPlan.cpp:941
LLVM_ABI_FOR_TEST void print(raw_ostream &O) const
Print this VPlan to O.
Definition VPlan.cpp:1138
bool hasTailFolded() const
Returns true if the vector loop region is tail-folded.
Definition VPlan.h:5064
void addVF(ElementCount VF)
Definition VPlan.h:5160
VPIRBasicBlock * getScalarHeader() const
Return the VPIRBasicBlock wrapping the header of the scalar loop.
Definition VPlan.h:5105
void printLiveIns(raw_ostream &O) const
Print the live-ins of this VPlan to O.
Definition VPlan.cpp:1100
VPSymbolicValue & getVF()
Returns the VF of the vector loop region.
Definition VPlan.h:5139
void setUF(unsigned UF)
Definition VPlan.h:5207
const VPSymbolicValue & getVF() const
Definition VPlan.h:5140
bool hasScalarTail() const
Returns true if the scalar tail may execute after the vector loop, i.e.
Definition VPlan.h:5380
LLVM_ABI_FOR_TEST VPlan * duplicate()
Clone the current VPlan, update all VPValues of the new VPlan and cloned recipes to refer to the clon...
Definition VPlan.cpp:1226
VPIRValue * getConstantInt(Type *Ty, uint64_t Val, bool IsSigned=false)
Return a VPIRValue wrapping a ConstantInt with the given type and value.
Definition VPlan.h:5258
LLVM Value Representation.
Definition Value.h:75
const ParentTy * getParent() const
Definition ilist_node.h:34
void setParent(ParentTy *Parent)
Definition ilist_node.h:40
Increasing range of size_t indices.
Definition STLExtras.h:2523
typename base_list_type::const_reverse_iterator const_reverse_iterator
Definition ilist.h:124
typename base_list_type::reverse_iterator reverse_iterator
Definition ilist.h:123
typename base_list_type::iterator iterator
Definition ilist.h:121
typename base_list_type::const_iterator const_iterator
Definition ilist.h:122
An intrusive list with ownership and callbacks specified/controlled by ilist_traits,...
Definition ilist.h:328
A range adaptor for a pair of iterators.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
CallInst * Call
This file defines classes to implement an intrusive doubly linked list class (i.e.
This file defines the ilist_node class template, which is a convenient base class for creating classe...
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
std::variant< std::monostate, Loc::Single, Loc::Multi, Loc::MMI, Loc::EntryValue > Variant
Alias for the std::variant specialization base class of DbgVariable.
Definition DwarfDebug.h:190
CastInfo helper for casting from VPRecipeBase to a mixin class that is not part of the VPRecipeBase c...
Definition VPlan.h:4438
unsigned getOpcode(const VPValue *V)
Return the instruction opcode for the recipe defining V or 0 for unsupported recipes and VPValues not...
This is an optimization pass for GlobalISel generic memory operations.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
@ Offset
Definition DWP.cpp:577
detail::zippy< detail::zip_shortest, T, U, Args... > zip(T &&t, U &&u, Args &&...args)
zip iterator for two or more iteratable types.
Definition STLExtras.h:846
LLVM_PACKED_END
Definition VPlan.h:1085
auto cast_if_present(const Y &Val)
cast_if_present<X> - Functionally identical to cast, except that a null value is accepted.
Definition Casting.h:683
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1781
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
detail::zippy< detail::zip_first, T, U, Args... > zip_equal(T &&t, U &&u, Args &&...args)
zip iterator that assumes that all iteratees have the same length.
Definition STLExtras.h:856
ReductionStyle getReductionStyle(bool InLoop, bool Ordered, unsigned ScaleFactor)
Definition VPlan.h:2877
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2570
Type * toScalarizedTy(Type *Ty)
A helper for converting vectorized types to scalarized (non-vector) types.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
@ Load
The value being inserted comes from a load (InsertElement only).
@ Store
The extracted value is stored (ExtractElement only).
VPBuilderBase<> VPBuilder
Definition VPlan.h:66
LLVM_ABI void getMetadataToPropagate(Instruction *Inst, SmallVectorImpl< std::pair< unsigned, MDNode * > > &Metadata)
Add metadata from Inst to Metadata, if it can be preserved after vectorization.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
HistogramUpdateKind
The kind of update operation performed on the buckets of a histogram, i.e.
auto cast_or_null(const Y &Val)
Definition Casting.h:714
MemoryEffectsBase< IRMemLocation > MemoryEffects
Summary of how a function affects memory in the program.
Definition ModRef.h:356
LLVM_ABI bool isSafeToSpeculativelyExecute(const Instruction *I, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr, bool UseVariableInfo=true, bool IgnoreUBImplyingAttrs=true)
Return true if the instruction does not have any effects besides calculating the result and does not ...
auto map_range(ContainerTy &&C, FuncTy F)
Return a range that applies F to the elements of C.
Definition STLExtras.h:366
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
UncountableExitStyle
Different methods of handling early exits.
Definition VPlan.h:81
@ MaskedHandleExitInScalarLoop
All memory operations other than the load(s) required to determine whether an uncountable exit occurr...
Definition VPlan.h:90
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool isPointerTy(const Type *T)
Definition SPIRVUtils.h:373
LLVM_ABI Type * computeScalarTypeForInstruction(unsigned Opcode, ArrayRef< VPValue * > Operands)
Compute the scalar result type for an IR Opcode given Operands.
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
auto drop_end(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the last N elements excluded.
Definition STLExtras.h:323
@ Other
Any other memory.
Definition ModRef.h:68
RecurKind
These are the kinds of recurrences that we support.
@ Mul
Product of integers.
@ Add
Sum of integers.
@ AddChainWithSubs
A chain of adds and subs.
@ FAdd
Sum of floats.
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition STLExtras.h:2028
DWARFExpression::Operation Op
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
ArrayRef(const T &OneElt) -> ArrayRef< T >
constexpr unsigned BitWidth
auto sum_of(R &&Range, E Init=E{0})
Returns the sum of all values in Range with Init initial value.
Definition STLExtras.h:1733
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1788
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:341
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2208
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
std::variant< RdxOrdered, RdxInLoop, RdxUnordered > ReductionStyle
Definition VPlan.h:2875
@ Increment
Incrementally increasing token ID.
Definition AllocToken.h:26
std::unique_ptr< VPlan > VPlanPtr
Definition VPlan.h:76
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:879
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
#define N
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
static Bitfield::Type get(StorageType Packed)
Unpacks the field from the Packed value.
Definition Bitfields.h:207
static void set(StorageType &Packed, typename Bitfield::Type Value)
Sets the typed value in the provided Packed value.
Definition Bitfields.h:223
This struct provides a method for customizing the way a cast is performed.
Definition Casting.h:476
Provides a cast trait that strips const from types to make it easier to implement a const-version of ...
Definition Casting.h:388
This cast trait just provides the default implementation of doCastIfPossible to make CastInfo special...
Definition Casting.h:309
Provides a cast trait that uses a defined pointer to pointer cast as a base for reference-to-referenc...
Definition Casting.h:423
This reduction is in-loop.
Definition VPlan.h:2869
Possible variants of a reduction.
Definition VPlan.h:2867
This reduction is unordered with the partial result scaled down by some factor.
Definition VPlan.h:2872
unsigned VFScaleFactor
Definition VPlan.h:2873
A MapVector that performs no allocations if smaller than a certain size.
Definition MapVector.h:344
Default inserter for VPBuilderBase, inserting R before It.
An overlay on VPConstant for VPValues that wrap a ConstantInt.
Definition VPlanValue.h:305
Struct to hold various analysis needed for cost computations.
const BlockFrequency Freq
Definition VPlan.h:1141
VPExecutionFrequency(BlockFrequency Freq, bool IsEstimated)
Definition VPlan.h:1144
void execute(VPTransformState &State) override
Generate the phi nodes.
VPFirstOrderRecurrencePHIRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:2838
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this first-order recurrence phi recipe.
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:2850
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPFirstOrderRecurrencePHIRecipe(PHINode *Phi, VPValue &Start, VPValue &BackedgeValue)
Definition VPlan.h:2829
DisjointFlagsTy(bool IsDisjoint)
Definition VPlan.h:719
NonNegFlagsTy(bool IsNonNeg)
Definition VPlan.h:724
TruncFlagsTy(bool HasNUW, bool HasNSW)
Definition VPlan.h:714
WrapFlagsTy(bool HasNUW, bool HasNSW)
Definition VPlan.h:703
WrapFlagsTy withoutNoSignedWrap()
Definition VPlan.h:705
An overlay for VPIRInstructions wrapping PHI nodes enabling convenient use cast/dyn_cast/isa and exec...
Definition VPlan.h:1800
VPIRPhi(PHINode &PN)
Definition VPlan.h:1801
static bool classof(const VPRecipeBase *U)
Definition VPlan.h:1803
static bool classof(const VPUser *U)
Definition VPlan.h:1808
PHINode & getIRPhi() const
Definition VPlan.h:1813
const VPRecipeBase * getAsRecipe() const override
Return a VPRecipeBase* to the current object.
Definition VPlan.h:1824
A VPValue representing a live-in from the input IR or a constant.
Definition VPlanValue.h:274
static bool classof(const VPUser *U)
Definition VPlan.h:1700
VPPhi * clone() override
Clone the current recipe.
Definition VPlan.h:1715
const VPRecipeBase * getAsRecipe() const override
Return a VPRecipeBase* to the current object.
Definition VPlan.h:1730
static bool classof(const VPSingleDefRecipe *SDR)
Definition VPlan.h:1710
static bool classof(const VPValue *V)
Definition VPlan.h:1705
VPPhi(ArrayRef< VPValue * > Operands, const VPIRFlags &Flags, DebugLoc DL, const Twine &Name="", Type *ResultTy=nullptr)
Definition VPlan.h:1695
A pure-virtual common base class for recipes defining a single VPValue and using IR flags.
Definition VPlan.h:1089
static bool classof(const VPSingleDefRecipe *R)
Definition VPlan.h:1126
static bool classof(const VPRecipeBase *R)
Definition VPlan.h:1096
InstructionCost getCostForRecipeWithOpcode(unsigned Opcode, ElementCount VF, VPCostContext &Ctx) const
Compute the cost for this recipe for VF, using Opcode and Ctx.
static bool classof(const VPValue *V)
Definition VPlan.h:1119
VPRecipeWithIRFlags(VPRecipeTy SC, ArrayRef< VPValue * > Operands, Type *ResultTy, const VPIRFlags &Flags, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:1090
void execute(VPTransformState &State) override=0
The method which generates the output IR instructions that correspond to this VPRecipe,...
VPRecipeWithIRFlags * clone() override=0
Clone the current recipe.
static bool classof(const VPUser *U)
Definition VPlan.h:1114
VPTransformState holds information passed down when "executing" a VPlan, needed for generating the ou...
A recipe for widening load operations with vector-predication intrinsics, using the address to load f...
Definition VPlan.h:3965
VPWidenLoadEVLRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:3976
unsigned getOpcode() const
Returns the opcode of the widened load.
Definition VPlan.h:3983
VPValue * getEVL() const
Return the EVL operand.
Definition VPlan.h:3986
VPWidenLoadEVLRecipe(VPWidenLoadRecipe &L, VPValue *Addr, VPValue &EVL, VPValue *Mask)
Definition VPlan.h:3966
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:3996
A recipe for widening load operations, using the address to load from and an optional mask.
Definition VPlan.h:3910
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:3941
unsigned getOpcode() const
Returns the opcode of the widened load.
Definition VPlan.h:3929
VPWidenLoadRecipe(LoadInst &Load, VPValue *Addr, VPValue *Mask, bool Consecutive, Align Alignment, const VPIRMetadata &Metadata, DebugLoc DL)
Definition VPlan.h:3911
VPWidenLoadRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:3920
VP_CLASSOF_IMPL(VPRecipeBase::VPWidenLoadSC)
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenLoadRecipe.
Definition VPlan.h:3935
A recipe for widening store operations with vector-predication intrinsics, using the value to store,...
Definition VPlan.h:4072
VPValue * getStoredValue() const
Return the address accessed by this recipe.
Definition VPlan.h:4089
VPWidenStoreEVLRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:4082
VPWidenStoreEVLRecipe(VPWidenStoreRecipe &S, VPValue *Addr, VPValue *StoredVal, VPValue &EVL, VPValue *Mask)
Definition VPlan.h:4073
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:4102
VPValue * getEVL() const
Return the EVL operand.
Definition VPlan.h:4092
A recipe for widening store operations, using the stored value, the address to store to and an option...
Definition VPlan.h:4018
VPWidenStoreRecipe(StoreInst &Store, VPValue *Addr, VPValue *StoredVal, VPValue *Mask, bool Consecutive, Align Alignment, const VPIRMetadata &Metadata, DebugLoc DL)
Definition VPlan.h:4019
VP_CLASSOF_IMPL(VPRecipeBase::VPWidenStoreSC)
VPValue * getStoredValue() const
Return the value stored by this recipe.
Definition VPlan.h:4036
VPWidenStoreRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:4027
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenStoreRecipe.
Definition VPlan.h:4042
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:4048
static VPMixin * castFailed()
Definition VPlan.h:4456
static bool isPossible(VPRecipeBase *R)
Used by isa.
Definition VPlan.h:4447
static VPMixin * doCast(VPRecipeBase *R)
Used by cast.
Definition VPlan.h:4450