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 {
1480 if (Opcode == VPInstruction::MaskedCond)
1481 return false;
1482
1483 // For now only VPInstructions with underlying values use masks.
1484 // TODO: provide masks to VPInstructions w/o underlying values.
1485 if (!getUnderlyingValue())
1486 return true;
1487
1488 return Instruction::isCast(Opcode) || Opcode == Instruction::PHI ||
1489 Opcode == Instruction::GetElementPtr ||
1490 Opcode == Instruction::ExtractValue;
1491 }
1492
1493public:
1494 VPInstruction(unsigned Opcode, ArrayRef<VPValue *> Operands,
1495 const VPIRFlags &Flags = {}, const VPIRMetadata &MD = {},
1496 DebugLoc DL = DebugLoc::getUnknown(), const Twine &Name = "",
1497 Type *ResultTy = nullptr, const VPIRAttributes &Attrs = {});
1498
1499 VP_CLASSOF_IMPL(VPRecipeBase::VPInstructionSC)
1500
1501 VPInstruction *clone() override {
1503 }
1504
1506 Type *ResultTy = nullptr) {
1507 auto *New = new VPInstruction(Opcode, NewOperands, *this, *this,
1508 getDebugLoc(), Name, ResultTy, *this);
1509 if (getUnderlyingValue())
1510 New->setUnderlyingValue(getUnderlyingInstr());
1511 return New;
1512 }
1513
1514 unsigned getOpcode() const { return Opcode; }
1515
1516 /// Add \p Op as operand of this VPInstruction. Only supported for AnyOf,
1517 /// ComputeReductionResult, BuildVector, ExtractLane,
1518 /// ExtractLastActive, FirstActiveLane, LastActiveLane.
1519 void addOperand(VPValue *Op);
1520
1521 void execute(VPTransformState &State) override;
1522
1523 /// Return the cost of this VPInstruction.
1524 InstructionCost computeCost(ElementCount VF,
1525 VPCostContext &Ctx) const override;
1526
1527#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1528 /// Print the VPInstruction to dbgs() (for debugging).
1529 LLVM_DUMP_METHOD void dump() const;
1530#endif
1531
1532 bool hasResult() const { return !getScalarType()->isVoidTy(); }
1533
1534 /// Returns true if the VPInstruction has a mask operand.
1535 bool isMasked() const {
1536 unsigned NumOpsForOpcode = getNumOperandsForOpcode();
1537 // VPInstructions without a fixed number of operands cannot be masked.
1538 if (NumOpsForOpcode == -1u)
1539 return false;
1540 return NumOpsForOpcode + 1 == getNumOperands();
1541 }
1542
1543 /// Returns the number of operands, excluding the mask if the VPInstruction is
1544 /// masked.
1545 unsigned getNumOperandsWithoutMask() const {
1546 return getNumOperands() - isMasked();
1547 }
1548
1549 /// Add mask \p Mask to an unmasked VPInstruction, if it needs masking.
1550 void addMask(VPValue *Mask) {
1551 assert(!isMasked() && "recipe is already masked");
1552 if (alwaysUnmasked())
1553 return;
1554 assert(Mask->getScalarType()->isIntegerTy(1) &&
1555 "Mask must be an i1 (vector)");
1556 VPUser::addOperand(Mask);
1557 }
1558
1559 /// Returns the mask for the VPInstruction. Returns nullptr for unmasked
1560 /// VPInstructions.
1561 VPValue *getMask() const { return isMasked() ? getLastOperand() : nullptr; }
1562
1563 /// Returns an iterator range over the operands excluding the mask operand
1564 /// if present.
1571
1572 /// Returns true if the underlying opcode may read from or write to memory.
1573 bool opcodeMayReadOrWriteFromMemory() const;
1574
1575 /// Returns true if the recipe only uses the first lane of operand \p Op.
1576 bool usesFirstLaneOnly(const VPValue *Op) const override;
1577
1578 /// Returns true if the recipe only uses scalars of operand \p Op.
1579 bool usesScalars(const VPValue *Op) const override {
1582 }
1583
1584 /// Returns true if the recipe only uses the first part of operand \p Op.
1585 bool usesFirstPartOnly(const VPValue *Op) const override;
1586
1587 /// Returns true if this VPInstruction produces a scalar value from a vector,
1588 /// e.g. by performing a reduction or extracting a lane.
1589 bool isVectorToScalar() const;
1590
1591 /// Returns true if the recipe produces a single scalar value.
1592 bool isSingleScalar() const;
1593
1594 /// Returns the symbolic name assigned to the VPInstruction.
1595 StringRef getName() const { return Name; }
1596
1597 /// Set the symbolic name for the VPInstruction.
1598 void setName(StringRef NewName) { Name = NewName.str(); }
1599
1600protected:
1601#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1602 /// Print the VPInstruction to \p O.
1603 void printRecipe(raw_ostream &O, const Twine &Indent,
1604 VPSlotTracker &SlotTracker) const override;
1605#endif
1606};
1607
1608/// Helper type to provide functions to access incoming values and blocks for
1609/// phi-like recipes.
1611protected:
1612 /// Return a VPRecipeBase* to the current object.
1613 virtual const VPRecipeBase *getAsRecipe() const = 0;
1614
1615public:
1616 virtual ~VPPhiAccessors() = default;
1617
1618 /// Returns the incoming VPValue with index \p Idx.
1619 VPValue *getIncomingValue(unsigned Idx) const {
1620 return getAsRecipe()->getOperand(Idx);
1621 }
1622
1623 /// Returns the incoming block with index \p Idx.
1624 const VPBasicBlock *getIncomingBlock(unsigned Idx) const;
1625
1626 /// Returns the incoming value for \p VPBB. \p VPBB must be an incoming block.
1628 getIncomingValueForBlock(const VPBasicBlock *VPBB) const;
1629
1630 /// Sets the incoming value for \p VPBB to \p V. \p VPBB must be an incoming
1631 /// block.
1632 void setIncomingValueForBlock(const VPBasicBlock *VPBB, VPValue *V) const;
1633
1634 /// Returns the number of incoming values, also number of incoming blocks.
1635 virtual unsigned getNumIncoming() const {
1636 return getAsRecipe()->getNumOperands();
1637 }
1638
1639 /// Returns an interator range over the incoming values.
1641 return make_range(getAsRecipe()->op_begin(),
1642 getAsRecipe()->op_begin() + getNumIncoming());
1643 }
1644
1646 detail::index_iterator, std::function<const VPBasicBlock *(size_t)>>>;
1647
1648 /// Returns an iterator range over the incoming blocks.
1650 std::function<const VPBasicBlock *(size_t)> GetBlock = [this](size_t Idx) {
1651 return getIncomingBlock(Idx);
1652 };
1653 return map_range(index_range(0, getNumIncoming()), GetBlock);
1654 }
1655
1656 /// Returns an iterator range over pairs of incoming values and corresponding
1657 /// incoming blocks.
1663
1664 /// Removes the incoming value for \p IncomingBlock, which must be a
1665 /// predecessor.
1666 void removeIncomingValueFor(VPBlockBase *IncomingBlock) const;
1667
1668 /// Append \p IncomingV as an incoming value to the phi-like recipe.
1669 void addIncoming(VPValue *IncomingV) {
1670 auto *R = const_cast<VPRecipeBase *>(getAsRecipe());
1671 assert((R->getNumOperands() == 0 ||
1672 IncomingV->getScalarType() == R->getOperand(0)->getScalarType()) &&
1673 "all incoming values must have the same type");
1674 R->addOperand(IncomingV);
1675 }
1676
1677#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1678 /// Print the recipe.
1680#endif
1681};
1682
1685 const Twine &Name = "", Type *ResultTy = nullptr)
1686 : VPInstruction(Instruction::PHI, Operands, Flags, {}, DL, Name,
1687 ResultTy) {}
1688
1689 static inline bool classof(const VPUser *U) {
1690 auto *VPI = dyn_cast<VPInstruction>(U);
1691 return VPI && VPI->getOpcode() == Instruction::PHI;
1692 }
1693
1694 static inline bool classof(const VPValue *V) {
1695 auto *VPI = dyn_cast<VPInstruction>(V);
1696 return VPI && VPI->getOpcode() == Instruction::PHI;
1697 }
1698
1699 static inline bool classof(const VPSingleDefRecipe *SDR) {
1700 auto *VPI = dyn_cast<VPInstruction>(SDR);
1701 return VPI && VPI->getOpcode() == Instruction::PHI;
1702 }
1703
1704 VPPhi *clone() override {
1705 auto *PhiR = new VPPhi(operands(), *this, getDebugLoc(), getName());
1706 PhiR->setUnderlyingValue(getUnderlyingValue());
1707 return PhiR;
1708 }
1709
1710 void execute(VPTransformState &State) override;
1711
1712protected:
1713#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1714 /// Print the recipe.
1715 void printRecipe(raw_ostream &O, const Twine &Indent,
1716 VPSlotTracker &SlotTracker) const override;
1717#endif
1718
1719 const VPRecipeBase *getAsRecipe() const override { return this; }
1720};
1721
1722/// A recipe to wrap on original IR instruction not to be modified during
1723/// execution, except for PHIs. PHIs are modeled via the VPIRPhi subclass.
1724/// Expect PHIs, VPIRInstructions cannot have any operands.
1726 Instruction &I;
1727
1728protected:
1729 /// VPIRInstruction::create() should be used to create VPIRInstructions, as
1730 /// subclasses may need to be created, e.g. VPIRPhi.
1732 : VPRecipeBase(VPRecipeBase::VPIRInstructionSC, {}), I(I) {}
1733
1734public:
1735 ~VPIRInstruction() override = default;
1736
1737 /// Create a new VPIRPhi for \p \I, if it is a PHINode, otherwise create a
1738 /// VPIRInstruction.
1740
1741 VP_CLASSOF_IMPL(VPRecipeBase::VPIRInstructionSC)
1742
1744 auto *R = create(I);
1745 for (auto *Op : operands())
1746 R->addOperand(Op);
1747 return R;
1748 }
1749
1750 void execute(VPTransformState &State) override;
1751
1752 /// Return the cost of this VPIRInstruction.
1754 computeCost(ElementCount VF, VPCostContext &Ctx) const override;
1755
1756 Instruction &getInstruction() const { return I; }
1757
1758 bool usesScalars(const VPValue *Op) const override {
1760 "Op must be an operand of the recipe");
1761 return true;
1762 }
1763
1764 bool usesFirstPartOnly(const VPValue *Op) const override {
1766 "Op must be an operand of the recipe");
1767 return true;
1768 }
1769
1770 bool usesFirstLaneOnly(const VPValue *Op) const override {
1772 "Op must be an operand of the recipe");
1773 return true;
1774 }
1775
1776protected:
1777#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1778 /// Print the recipe.
1779 void printRecipe(raw_ostream &O, const Twine &Indent,
1780 VPSlotTracker &SlotTracker) const override;
1781#endif
1782};
1783
1784/// An overlay for VPIRInstructions wrapping PHI nodes enabling convenient use
1785/// cast/dyn_cast/isa and execute() implementation. A single VPValue operand is
1786/// allowed, and it is used to add a new incoming value for the single
1787/// predecessor VPBB.
1789 public VPPhiAccessors {
1791
1792 static inline bool classof(const VPRecipeBase *U) {
1793 auto *R = dyn_cast<VPIRInstruction>(U);
1794 return R && isa<PHINode>(R->getInstruction());
1795 }
1796
1797 static inline bool classof(const VPUser *U) {
1798 auto *R = dyn_cast<VPRecipeBase>(U);
1799 return R && classof(R);
1800 }
1801
1803
1804 void execute(VPTransformState &State) override;
1805
1806protected:
1807#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1808 /// Print the recipe.
1809 void printRecipe(raw_ostream &O, const Twine &Indent,
1810 VPSlotTracker &SlotTracker) const override;
1811#endif
1812
1813 const VPRecipeBase *getAsRecipe() const override { return this; }
1814};
1815
1816/// VPWidenRecipe is a recipe for producing a widened instruction using the
1817/// opcode and operands of the recipe. This recipe covers most of the
1818/// traditional vectorization cases where each recipe transforms into a
1819/// vectorized version of itself.
1821 public VPIRMetadata {
1822 unsigned Opcode;
1823
1824public:
1826 const VPIRFlags &Flags = {}, const VPIRMetadata &Metadata = {},
1827 DebugLoc DL = {})
1828 : VPWidenRecipe(I.getOpcode(), Operands, Flags, Metadata, DL) {
1829 setUnderlyingValue(&I);
1830 }
1831
1833 const VPIRFlags &Flags = {}, const VPIRMetadata &Metadata = {},
1834 DebugLoc DL = {})
1835 : VPRecipeWithIRFlags(VPRecipeBase::VPWidenSC, Operands,
1837 Flags, DL),
1838 VPIRMetadata(Metadata), Opcode(Opcode) {
1839 assert(flagsValidForOpcode(Opcode) &&
1840 "Set flags not supported for the provided opcode");
1841 assert(hasRequiredFlagsForOpcode(Opcode, getScalarType()) &&
1842 "Opcode requires specific flags to be set");
1843 }
1844
1845 ~VPWidenRecipe() override = default;
1846
1848
1850 if (auto *UV = getUnderlyingValue())
1851 return new VPWidenRecipe(*cast<Instruction>(UV), NewOperands, *this,
1852 *this, getDebugLoc());
1853 return new VPWidenRecipe(Opcode, NewOperands, *this, *this, getDebugLoc());
1854 }
1855
1856 VP_CLASSOF_IMPL(VPRecipeBase::VPWidenSC)
1857
1858 /// Produce a widened instruction using the opcode and operands of the recipe,
1859 /// processing State.VF elements.
1860 void execute(VPTransformState &State) override;
1861
1862 /// Return the cost of this VPWidenRecipe.
1863 InstructionCost computeCost(ElementCount VF,
1864 VPCostContext &Ctx) const override;
1865
1866 unsigned getOpcode() const { return Opcode; }
1867
1868protected:
1869#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1870 /// Print the recipe.
1871 void printRecipe(raw_ostream &O, const Twine &Indent,
1872 VPSlotTracker &SlotTracker) const override;
1873#endif
1874
1875 /// Returns true if the recipe only uses the first lane of operand \p Op.
1876 bool usesFirstLaneOnly(const VPValue *Op) const override {
1878 "Op must be an operand of the recipe");
1879 return Opcode == Instruction::Select && Op == getOperand(0) &&
1881 }
1882};
1883
1884/// VPWidenCastRecipe is a recipe to create vector cast instructions.
1885/// TODO: Merge with VPWidenRecipe now that type is associated to every
1886/// VPRecipeValue.
1888 public VPIRMetadata {
1889 /// Cast instruction opcode.
1890 Instruction::CastOps Opcode;
1891
1892public:
1894 CastInst *CI = nullptr, const VPIRFlags &Flags = {},
1895 const VPIRMetadata &Metadata = {},
1896 DebugLoc DL = DebugLoc::getUnknown())
1897 : VPRecipeWithIRFlags(VPRecipeBase::VPWidenCastSC, Op, ResultTy, Flags,
1898 DL),
1899 VPIRMetadata(Metadata), Opcode(Opcode) {
1900 assert(flagsValidForOpcode(Opcode) &&
1901 "Set flags not supported for the provided opcode");
1902 assert(hasRequiredFlagsForOpcode(Opcode, ResultTy) &&
1903 "Opcode requires specific flags to be set");
1904 setUnderlyingValue(CI);
1905 }
1906
1907 ~VPWidenCastRecipe() override = default;
1908
1910 return new VPWidenCastRecipe(Opcode, getOperand(0), getScalarType(),
1912 *this, *this, getDebugLoc());
1913 }
1914
1915 VP_CLASSOF_IMPL(VPRecipeBase::VPWidenCastSC)
1916
1917 /// Produce widened copies of the cast.
1918 void execute(VPTransformState &State) override;
1919
1920 /// Return the cost of this VPWidenCastRecipe.
1921 InstructionCost computeCost(ElementCount VF,
1922 VPCostContext &Ctx) const override;
1923
1924 Instruction::CastOps getOpcode() const { return Opcode; }
1925
1926protected:
1927#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1928 /// Print the recipe.
1929 void printRecipe(raw_ostream &O, const Twine &Indent,
1930 VPSlotTracker &SlotTracker) const override;
1931#endif
1932};
1933
1934/// A recipe for widening vector intrinsics.
1936 public VPIRMetadata {
1937 /// ID of the vector intrinsic to widen.
1938 Intrinsic::ID VectorIntrinsicID;
1939
1940 /// True if the intrinsic may read from memory.
1941 bool MayReadFromMemory;
1942
1943 /// True if the intrinsic may read write to memory.
1944 bool MayWriteToMemory;
1945
1946 /// True if the intrinsic may have side-effects.
1947 bool MayHaveSideEffects;
1948
1949protected:
1951 ArrayRef<VPValue *> CallArguments, Type *Ty,
1952 const VPIRFlags &Flags = {},
1953 const VPIRMetadata &MD = {},
1954 DebugLoc DL = DebugLoc::getUnknown())
1955 : VPRecipeWithIRFlags(SC, CallArguments, Ty, Flags, DL), VPIRMetadata(MD),
1956 VectorIntrinsicID(VectorIntrinsicID) {
1957 LLVMContext &Ctx = Ty->getContext();
1958 AttributeSet Attrs = Intrinsic::getFnAttributes(Ctx, VectorIntrinsicID);
1959 MemoryEffects ME = Attrs.getMemoryEffects();
1960 MayReadFromMemory = !ME.onlyWritesMemory();
1961 MayWriteToMemory = !ME.onlyReadsMemory();
1962 MayHaveSideEffects = MayWriteToMemory ||
1963 !Attrs.hasAttribute(Attribute::NoUnwind) ||
1964 !Attrs.hasAttribute(Attribute::WillReturn);
1965 }
1966
1967 /// Helper function to produce the widened intrinsic call.
1968 CallInst *createVectorCall(VPTransformState &State);
1969
1970public:
1972 ArrayRef<VPValue *> CallArguments, Type *Ty,
1973 const VPIRFlags &Flags = {},
1974 const VPIRMetadata &MD = {},
1975 DebugLoc DL = DebugLoc::getUnknown())
1976 : VPRecipeWithIRFlags(VPRecipeBase::VPWidenIntrinsicSC, CallArguments, Ty,
1977 Flags, DL),
1978 VPIRMetadata(MD), VectorIntrinsicID(VectorIntrinsicID),
1979 MayReadFromMemory(CI.mayReadFromMemory()),
1980 MayWriteToMemory(CI.mayWriteToMemory()),
1981 MayHaveSideEffects(CI.mayHaveSideEffects()) {
1982 setUnderlyingValue(&CI);
1983 }
1984
1986 ArrayRef<VPValue *> CallArguments, Type *Ty,
1987 const VPIRFlags &Flags = {},
1988 const VPIRMetadata &Metadata = {},
1989 DebugLoc DL = DebugLoc::getUnknown())
1990 : VPWidenIntrinsicRecipe(VPRecipeBase::VPWidenIntrinsicSC,
1991 VectorIntrinsicID, CallArguments, Ty, Flags,
1992 Metadata, DL) {}
1993
1994 ~VPWidenIntrinsicRecipe() override = default;
1995
1997 if (Value *CI = getUnderlyingValue())
1998 return new VPWidenIntrinsicRecipe(*cast<CallInst>(CI), VectorIntrinsicID,
1999 operands(), getScalarType(), *this,
2000 *this, getDebugLoc());
2001 return new VPWidenIntrinsicRecipe(VectorIntrinsicID, operands(),
2002 getScalarType(), *this, *this,
2003 getDebugLoc());
2004 }
2005
2006 static inline bool classof(const VPRecipeBase *R) {
2007 return R->getVPRecipeID() == VPRecipeBase::VPWidenIntrinsicSC ||
2008 R->getVPRecipeID() == VPRecipeBase::VPWidenMemIntrinsicSC;
2009 }
2010
2011 static inline bool classof(const VPUser *U) {
2012 auto *R = dyn_cast<VPRecipeBase>(U);
2013 return R && classof(R);
2014 }
2015
2016 static inline bool classof(const VPValue *V) {
2017 auto *R = V->getDefiningRecipe();
2018 return R && classof(R);
2019 }
2020
2021 static inline bool classof(const VPSingleDefRecipe *R) {
2022 return classof(static_cast<const VPRecipeBase *>(R));
2023 }
2024
2025 /// Produce a widened version of the vector intrinsic.
2026 void execute(VPTransformState &State) override;
2027
2028 /// Compute the cost of a vector intrinsic with \p ID and \p Operands.
2029 static InstructionCost computeCallCost(Intrinsic::ID ID,
2031 const VPRecipeWithIRFlags &R,
2032 ElementCount VF, VPCostContext &Ctx);
2033
2034 /// Return the cost of this vector intrinsic.
2035 InstructionCost computeCost(ElementCount VF,
2036 VPCostContext &Ctx) const override;
2037
2038 /// Return the ID of the intrinsic.
2039 Intrinsic::ID getVectorIntrinsicID() const { return VectorIntrinsicID; }
2040
2041 /// Return to name of the intrinsic as string.
2042 StringRef getIntrinsicName() const;
2043
2044 /// Returns true if the intrinsic may read from memory.
2045 bool mayReadFromMemory() const { return MayReadFromMemory; }
2046
2047 /// Returns true if the intrinsic may write to memory.
2048 bool mayWriteToMemory() const { return MayWriteToMemory; }
2049
2050 /// Returns true if the intrinsic may have side-effects.
2051 bool mayHaveSideEffects() const { return MayHaveSideEffects; }
2052
2053 bool usesFirstLaneOnly(const VPValue *Op) const override;
2054
2055protected:
2056#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2057 /// Print the recipe.
2058 void printRecipe(raw_ostream &O, const Twine &Indent,
2059 VPSlotTracker &SlotTracker) const override;
2060#endif
2061};
2062
2063/// A recipe for widening vector memory intrinsics.
2065 : public VPWidenIntrinsicRecipe {
2066 /// Alignment information for this memory access.
2067 Align Alignment;
2068
2069public:
2071 ArrayRef<VPValue *> CallArguments, Type *Ty,
2072 Align Alignment, const VPIRMetadata &MD = {},
2074 : VPWidenIntrinsicRecipe(VPRecipeBase::VPWidenMemIntrinsicSC,
2075 VectorIntrinsicID, CallArguments, Ty, {}, MD,
2076 DL),
2077 Alignment(Alignment) {
2078 assert(getVectorMemoryIntrinsicPointerArgIdx(VectorIntrinsicID) &&
2079 getVectorIntrinsicMaskArgIdx(VectorIntrinsicID) &&
2080 "Expected a masked vector load/store intrinsic");
2081 assert((!Ty->isVoidTy() ||
2082 getVectorStoreIntrinsicDataArgIdx(VectorIntrinsicID)) &&
2083 "Expected data argument for store intrinsic");
2084 }
2085
2086 ~VPWidenMemIntrinsicRecipe() override = default;
2087
2090 getScalarType(), Alignment, *this,
2091 getDebugLoc());
2092 }
2093
2094 VP_CLASSOF_IMPL(VPRecipeBase::VPWidenMemIntrinsicSC)
2095
2096 /// Produce a widened version of the vector memory intrinsic.
2097 void execute(VPTransformState &State) override;
2098
2099 /// Returns the address operand index of the VPWidenMemIntrinsicRecipe.
2100 unsigned getAddrOpIdx() const;
2101
2102 /// Returns the mask of a predicated VPWidenMemIntrinsicRecipe.
2103 VPValue *getMask() const;
2104
2105 /// Returns the data type of the memory access at \p VF.
2106 Type *getAccessType(ElementCount VF) const;
2107
2108 /// Helper function for computing the cost of vector memory intrinsic.
2109 static InstructionCost computeMemIntrinsicCost(Intrinsic::ID IID, Type *Ty,
2110 bool IsMasked, Align Alignment,
2111 VPCostContext &Ctx);
2112
2113 /// Return the cost of this vector memory intrinsic.
2114 InstructionCost computeCost(ElementCount VF,
2115 VPCostContext &Ctx) const override;
2116};
2117
2118/// A recipe for widening Call instructions using library calls.
2120 public VPIRMetadata,
2121 public VPIRAttributes {
2122 /// Variant stores a pointer to the chosen function. There is a 1:1 mapping
2123 /// between a given VF and the chosen vectorized variant, so there will be a
2124 /// different VPlan for each VF with a valid variant.
2125 Function *Variant;
2126
2127public:
2129 ArrayRef<VPValue *> CallArguments,
2130 const VPIRFlags &Flags = {},
2131 const VPIRMetadata &Metadata = {},
2132 const VPIRAttributes &Attrs = {}, DebugLoc DL = {})
2133 : VPRecipeWithIRFlags(VPRecipeBase::VPWidenCallSC, CallArguments,
2134 toScalarizedTy(Variant->getReturnType()), Flags,
2135 DL),
2136 VPIRMetadata(Metadata), VPIRAttributes(Attrs), Variant(Variant) {
2137 setUnderlyingValue(UV);
2138 assert(isa<Function>(getLastOperand()->getLiveInIRValue()) &&
2139 "last operand must be the called function");
2140 assert(cast<Function>(CallArguments.back()->getLiveInIRValue())
2141 ->getReturnType() == getScalarType() &&
2142 "Scalar type must match return type of called scalar function");
2143 }
2144
2145 ~VPWidenCallRecipe() override = default;
2146
2148 return new VPWidenCallRecipe(getUnderlyingValue(), Variant, operands(),
2149 *this, *this, *this, getDebugLoc());
2150 }
2151
2152 VP_CLASSOF_IMPL(VPRecipeBase::VPWidenCallSC)
2153
2154 /// Produce a widened version of the call instruction.
2155 void execute(VPTransformState &State) override;
2156
2157 /// Return the cost of this VPWidenCallRecipe.
2158 InstructionCost computeCost(ElementCount VF,
2159 VPCostContext &Ctx) const override;
2160
2161 /// Return the cost of widening a call using the vector function \p Variant.
2162 static InstructionCost computeCallCost(Function *Variant, VPCostContext &Ctx);
2163
2167
2170
2171 /// Returns true if the recipe only uses the first lane of operand \p Op.
2172 bool usesFirstLaneOnly(const VPValue *Op) const override;
2173
2174protected:
2175#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2176 /// Print the recipe.
2177 void printRecipe(raw_ostream &O, const Twine &Indent,
2178 VPSlotTracker &SlotTracker) const override;
2179#endif
2180};
2181
2182/// A recipe representing a sequence of load -> update -> store as part of
2183/// a histogram operation. This means there may be aliasing between vector
2184/// lanes, which is handled by the llvm.experimental.vector.histogram family
2185/// of intrinsics. Supported update operations are: add, sub, uadd.sat, umax,
2186/// and umin, where the other term is loop-invariant.
2188 /// The update operation kind for this histogram.
2189 HistogramUpdateKind UpdateKind;
2190
2191public:
2193 ArrayRef<VPValue *> Operands,
2194 const VPIRMetadata &Metadata = {},
2196 : VPRecipeBase(VPRecipeBase::VPHistogramSC, Operands, DL),
2197 VPIRMetadata(Metadata), UpdateKind(UpdateKind) {}
2198
2199 ~VPHistogramRecipe() override = default;
2200
2202 return new VPHistogramRecipe(UpdateKind, operands(), *this, getDebugLoc());
2203 }
2204
2205 VP_CLASSOF_IMPL(VPRecipeBase::VPHistogramSC);
2206
2207 /// Produce a vectorized histogram operation.
2208 void execute(VPTransformState &State) override;
2209
2210 /// Return the cost of this VPHistogramRecipe.
2212 VPCostContext &Ctx) const override;
2213
2214 /// Return the mask operand if one was provided, or a null pointer if all
2215 /// lanes should be executed unconditionally.
2216 VPValue *getMask() const {
2217 return getNumOperands() == 3 ? getOperand(2) : nullptr;
2218 }
2219
2220 /// Returns true if the recipe only uses the first lane of operand \p Op.
2221 bool usesFirstLaneOnly(const VPValue *Op) const override {
2223 "Op must be an operand of the recipe");
2224 return Op == getOperand(1);
2225 }
2226
2227private:
2228 /// Return the histogram intrinsic ID for this recipe's update kind.
2229 Intrinsic::ID getHistogramIntrinsicID() const;
2230
2231 /// Return true if the increment should be negated before passing to the
2232 /// histogram intrinsic (only for Sub).
2233 bool mustNegateIncrement() const {
2234 return UpdateKind == HistogramUpdateKind::Sub;
2235 }
2236
2237protected:
2238#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2239 /// Print the recipe
2240 void printRecipe(raw_ostream &O, const Twine &Indent,
2241 VPSlotTracker &SlotTracker) const override;
2242#endif
2243};
2244
2245/// A recipe for handling GEP instructions.
2247 Type *SourceElementTy;
2248
2249public:
2251 const VPIRFlags &Flags = {},
2253 GetElementPtrInst *UV = nullptr)
2254 : VPRecipeWithIRFlags(VPRecipeBase::VPWidenGEPSC, Operands,
2255 Operands[0]->getScalarType(), Flags, DL),
2256 SourceElementTy(SourceElementTy) {
2257 if (UV) {
2258 setUnderlyingValue(UV);
2261 assert(Metadata.empty() && "unexpected metadata on GEP");
2262 }
2263 }
2264
2265 ~VPWidenGEPRecipe() override = default;
2266
2272
2273 VP_CLASSOF_IMPL(VPRecipeBase::VPWidenGEPSC)
2274
2275 /// This recipe generates a GEP instruction.
2276 unsigned getOpcode() const { return Instruction::GetElementPtr; }
2277
2278 /// Generate the gep nodes.
2279 void execute(VPTransformState &State) override;
2280
2281 Type *getSourceElementType() const { return SourceElementTy; }
2282
2283 /// Return the cost of this VPWidenGEPRecipe.
2285 VPCostContext &Ctx) const override {
2286 // TODO: Compute accurate cost after retiring the legacy cost model.
2287 return 0;
2288 }
2289
2290 /// Returns true if the recipe only uses the first lane of operand \p Op.
2291 bool usesFirstLaneOnly(const VPValue *Op) const override;
2292
2293protected:
2294#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2295 /// Print the recipe.
2296 void printRecipe(raw_ostream &O, const Twine &Indent,
2297 VPSlotTracker &SlotTracker) const override;
2298#endif
2299};
2300
2301/// A recipe to compute a pointer to the last element of each part of a widened
2302/// memory access for widened memory accesses of SourceElementTy. Used for
2303/// VPWidenMemoryRecipes or VPInterleaveRecipes that are reversed. An extra
2304/// Offset operand is added by convertToConcreteRecipes when UF = 1, and by the
2305/// unroller otherwise.
2307 Type *SourceElementTy;
2308
2309 /// The constant stride of the pointer computed by this recipe, expressed in
2310 /// units of SourceElementTy.
2311 int64_t Stride;
2312
2313public:
2314 VPVectorEndPointerRecipe(VPValue *Ptr, VPValue *VF, Type *SourceElementTy,
2315 int64_t Stride, GEPNoWrapFlags GEPFlags, DebugLoc DL)
2316 : VPRecipeWithIRFlags(VPRecipeBase::VPVectorEndPointerSC, {Ptr, VF},
2317 Ptr->getScalarType(), GEPFlags, DL),
2318 SourceElementTy(SourceElementTy), Stride(Stride) {
2319 assert(Stride < 0 && "Stride must be negative");
2320 }
2321
2322 VP_CLASSOF_IMPL(VPRecipeBase::VPVectorEndPointerSC)
2323
2324 Type *getSourceElementType() const { return SourceElementTy; }
2325 int64_t getStride() const { return Stride; }
2326 VPValue *getPointer() const { return getOperand(0); }
2327 VPValue *getVFValue() const { return getOperand(1); }
2329 return getNumOperands() == 3 ? getOperand(2) : nullptr;
2330 }
2331
2332 /// Adds the offset operand to the recipe.
2333 /// Offset = Stride * (VF - 1) + Part * Stride * VF.
2334 void materializeOffset(unsigned Part = 0);
2335
2336 /// Append \p Offset as the offset operand. The offset is an integer index
2337 /// expressed in units of SourceElementTy.
2339 assert(Offset->getScalarType()->isIntegerTy() &&
2340 "offset must be an integer index");
2342 }
2343
2344 void execute(VPTransformState &State) override;
2345
2346 bool usesFirstLaneOnly(const VPValue *Op) const override {
2348 "Op must be an operand of the recipe");
2349 return true;
2350 }
2351
2352 /// Return the cost of this VPVectorPointerRecipe.
2354 VPCostContext &Ctx) const override {
2355 // TODO: Compute accurate cost after retiring the legacy cost model.
2356 return 0;
2357 }
2358
2359 /// Returns true if the recipe only uses the first part of operand \p Op.
2360 bool usesFirstPartOnly(const VPValue *Op) const override {
2362 "Op must be an operand of the recipe");
2363 assert(getNumOperands() <= 2 && "must have at most two operands");
2364 return true;
2365 }
2366
2368 auto *VEPR = new VPVectorEndPointerRecipe(
2371 if (auto *Offset = getOffset())
2372 VEPR->addOffset(Offset);
2373 return VEPR;
2374 }
2375
2376protected:
2377#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2378 /// Print the recipe.
2379 void printRecipe(raw_ostream &O, const Twine &Indent,
2380 VPSlotTracker &SlotTracker) const override;
2381#endif
2382};
2383
2384/// A recipe to compute the pointers for widened memory accesses of \p
2385/// SourceElementTy, with the \p Stride expressed in units of \p
2386/// SourceElementTy. Unrolling adds an extra \p VFxPart operand for unrolled
2387/// parts > 0 and it produces `GEP SourceElementTy Ptr, VFxPart * Stride`.
2389 Type *SourceElementTy;
2390
2391public:
2392 VPVectorPointerRecipe(VPValue *Ptr, Type *SourceElementTy, VPValue *Stride,
2393 GEPNoWrapFlags GEPFlags, DebugLoc DL)
2394 : VPRecipeWithIRFlags(VPRecipeBase::VPVectorPointerSC,
2395 ArrayRef<VPValue *>({Ptr, Stride}),
2396 Ptr->getScalarType(), GEPFlags, DL),
2397 SourceElementTy(SourceElementTy) {}
2398
2399 VP_CLASSOF_IMPL(VPRecipeBase::VPVectorPointerSC)
2400
2401 VPValue *getStride() const { return getOperand(1); }
2402
2404 return getNumOperands() > 2 ? getOperand(2) : nullptr;
2405 }
2406
2407 /// Add the per-part offset (VFxPart) used for unrolled parts > 0.
2408 void addPerPartOffset(VPValue *VFxPart) {
2409 assert(VFxPart->getScalarType()->isIntegerTy() &&
2410 "per-part offset must be an integer index");
2411 VPUser::addOperand(VFxPart);
2412 }
2413
2414 void execute(VPTransformState &State) override;
2415
2416 Type *getSourceElementType() const { return SourceElementTy; }
2417
2418 bool usesFirstLaneOnly(const VPValue *Op) const override {
2420 "Op must be an operand of the recipe");
2421 return true;
2422 }
2423
2424 /// Returns true if the recipe only uses the first part of operand \p Op.
2425 bool usesFirstPartOnly(const VPValue *Op) const override {
2427 "Op must be an operand of the recipe");
2428 assert(getNumOperands() <= 2 && "must have at most two operands");
2429 return true;
2430 }
2431
2433 auto *Clone =
2434 new VPVectorPointerRecipe(getOperand(0), SourceElementTy, getStride(),
2436 if (auto *VFxPart = getVFxPart())
2437 Clone->addPerPartOffset(VFxPart);
2438 return Clone;
2439 }
2440
2441 /// Return the cost of this VPHeaderPHIRecipe.
2443 VPCostContext &Ctx) const override {
2444 // TODO: Compute accurate cost after retiring the legacy cost model.
2445 return 0;
2446 }
2447
2448protected:
2449#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2450 /// Print the recipe.
2451 void printRecipe(raw_ostream &O, const Twine &Indent,
2452 VPSlotTracker &SlotTracker) const override;
2453#endif
2454};
2455
2456/// A pure virtual base class for all recipes modeling header phis, including
2457/// phis for first order recurrences, pointer inductions and reductions. The
2458/// start value is the first operand of the recipe and the incoming value from
2459/// the backedge is the second operand.
2460///
2461/// Inductions are modeled using the following sub-classes:
2462/// * VPWidenIntOrFpInductionRecipe: Generates vector values for integer and
2463/// floating point inductions with arbitrary start and step values. Produces
2464/// a vector PHI per-part.
2465/// * VPWidenPointerInductionRecipe: Generate vector and scalar values for a
2466/// pointer induction. Produces either a vector PHI per-part or scalar values
2467/// per-lane based on the canonical induction.
2468/// * VPFirstOrderRecurrencePHIRecipe
2469/// * VPReductionPHIRecipe
2470/// * VPActiveLaneMaskPHIRecipe
2471/// * VPEVLBasedIVPHIRecipe
2472///
2473/// Note that the canonical IV is modeled as a VPRegionValue associated with
2474/// its loop region.
2476 public VPPhiAccessors {
2477protected:
2478 VPHeaderPHIRecipe(VPRecipeTy VPRecipeID, Instruction *UnderlyingInstr,
2479 VPValue *Start, Type *ResultTy,
2481 : VPSingleDefRecipe(VPRecipeID, Start, ResultTy, UnderlyingInstr, DL) {}
2482
2483 const VPRecipeBase *getAsRecipe() const override { return this; }
2484
2485public:
2486 ~VPHeaderPHIRecipe() override = default;
2487
2488 /// Method to support type inquiry through isa, cast, and dyn_cast.
2489 static inline bool classof(const VPRecipeBase *R) {
2490 return R->getVPRecipeID() >= VPRecipeBase::VPFirstHeaderPHISC &&
2491 R->getVPRecipeID() <= VPRecipeBase::VPLastHeaderPHISC;
2492 }
2493 static inline bool classof(const VPValue *V) {
2494 return isa<VPHeaderPHIRecipe>(V->getDefiningRecipe());
2495 }
2496 static inline bool classof(const VPSingleDefRecipe *R) {
2497 return isa<VPHeaderPHIRecipe>(static_cast<const VPRecipeBase *>(R));
2498 }
2499
2500 /// Generate the phi nodes.
2501 void execute(VPTransformState &State) override = 0;
2502
2503 /// Return the cost of this header phi recipe.
2505 VPCostContext &Ctx) const override;
2506
2507 /// Returns the start value of the phi, if one is set.
2509 return getNumOperands() == 0 ? nullptr : getOperand(0);
2510 }
2512 return getNumOperands() == 0 ? nullptr : getOperand(0);
2513 }
2514
2515 /// Update the start value of the recipe.
2517
2518 /// Returns the incoming value from the loop backedge.
2519 virtual VPValue *getBackedgeValue() { return getOperand(1); }
2520
2521 /// Update the incoming value from the loop backedge.
2523
2524 /// Add \p V as the incoming value from the loop backedge.
2526 assert(getNumOperands() == 1 &&
2527 "backedge value must be appended right after construction");
2528 assert(V->getScalarType() == getScalarType() &&
2529 "backedge value must have the same type as the start value");
2531 }
2532
2533protected:
2534#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2535 /// Print the recipe.
2536 void printRecipe(raw_ostream &O, const Twine &Indent,
2537 VPSlotTracker &SlotTracker) const override = 0;
2538#endif
2539};
2540
2541/// Base class for widened induction (VPWidenIntOrFpInductionRecipe and
2542/// VPWidenPointerInductionRecipe), providing shared functionality, including
2543/// retrieving the step value, induction descriptor and original phi node.
2545 InductionDescriptor IndDesc;
2546
2547public:
2549 VPValue *Step, const InductionDescriptor &IndDesc,
2550 Type *ResultTy, DebugLoc DL)
2551 : VPHeaderPHIRecipe(Kind, IV, Start, ResultTy, DL), IndDesc(IndDesc) {
2552 addOperand(Step);
2553 }
2554
2555 /// After unrolling, append the splat-VF step (`VF * step`) and the value of
2556 /// the induction at the last unrolled part.
2557 void addUnrolledPartOperands(VPValue *SplatVFStep, VPValue *LastPart) {
2558 assert(LastPart->getScalarType() == getScalarType() &&
2559 "last-part value must match the induction recipe's scalar type");
2561 ? SplatVFStep->getScalarType()->isIntegerTy()
2562 : SplatVFStep->getScalarType() == getScalarType()) &&
2563 "splat-step must match the induction type for non-pointer "
2564 "inductions, or be an integer index for pointer inductions");
2565 VPUser::addOperand(SplatVFStep);
2566 VPUser::addOperand(LastPart);
2567 }
2568
2569 static inline bool classof(const VPRecipeBase *R) {
2570 return R->getVPRecipeID() == VPRecipeBase::VPWidenIntOrFpInductionSC ||
2571 R->getVPRecipeID() == VPRecipeBase::VPWidenPointerInductionSC;
2572 }
2573
2574 static inline bool classof(const VPValue *V) {
2575 auto *R = V->getDefiningRecipe();
2576 return R && classof(R);
2577 }
2578
2579 static inline bool classof(const VPSingleDefRecipe *R) {
2580 return classof(static_cast<const VPRecipeBase *>(R));
2581 }
2582
2583 void execute(VPTransformState &State) override = 0;
2584
2585 /// Returns the step value of the induction.
2587 const VPValue *getStepValue() const { return getOperand(1); }
2588
2590 const VPValue *getVFValue() const { return getOperand(2); }
2591
2592 /// Returns the number of incoming values, also number of incoming blocks.
2593 /// Note that at the moment, VPWidenPointerInductionRecipe only has a single
2594 /// incoming value, its start value.
2595 unsigned getNumIncoming() const override { return 1; }
2596
2597 /// Returns the underlying PHINode if one exists, or null otherwise.
2601
2602 /// Returns the induction descriptor for the recipe.
2603 const InductionDescriptor &getInductionDescriptor() const { return IndDesc; }
2604
2605 /// Returns the SCEV predicates associated with this induction.
2607 return IndDesc.getNoWrapPredicates();
2608 }
2609
2611 // TODO: All operands of base recipe must exist and be at same index in
2612 // derived recipe.
2614 "VPWidenIntOrFpInductionRecipe generates its own backedge value");
2615 }
2616
2617 /// Returns true if the recipe only uses the first lane of operand \p Op.
2618 bool usesFirstLaneOnly(const VPValue *Op) const override {
2620 "Op must be an operand of the recipe");
2621 // The recipe creates its own wide start value, so it only requests the
2622 // first lane of the operand.
2623 // TODO: Remove once creating the start value is modeled separately.
2624 return Op == getStartValue() || Op == getStepValue();
2625 }
2626};
2627
2628/// A recipe for handling phi nodes of integer and floating-point inductions,
2629/// producing their vector values. This is an abstract recipe and must be
2630/// converted to concrete recipes before executing.
2632 public VPIRFlags {
2633 // If this recipe is unrolled it will have 2 additional operands.
2634 bool isUnrolled() const { return getNumOperands() == 5; }
2635
2636public:
2638 VPValue *VF, const InductionDescriptor &IndDesc,
2639 const VPIRFlags &Flags, DebugLoc DL)
2640 : VPWidenInductionRecipe(VPRecipeBase::VPWidenIntOrFpInductionSC, IV,
2641 Start, Step, IndDesc, Start->getScalarType(),
2642 DL),
2643 VPIRFlags(Flags) {
2644 addOperand(VF);
2645 }
2646
2648 VPValue *VF, const InductionDescriptor &IndDesc,
2649 Type *ResultTy, const VPIRFlags &Flags,
2650 DebugLoc DL)
2651 : VPWidenInductionRecipe(VPRecipeBase::VPWidenIntOrFpInductionSC, IV,
2652 Start, Step, IndDesc, ResultTy, DL),
2653 VPIRFlags(Flags) {
2654 addOperand(VF);
2655 }
2656
2658
2664
2665 VP_CLASSOF_IMPL(VPRecipeBase::VPWidenIntOrFpInductionSC)
2666
2667 void execute(VPTransformState &State) override {
2668 llvm_unreachable("cannot execute this recipe, should be expanded via "
2669 "expandVPWidenIntOrFpInductionRecipe");
2670 }
2671
2672 /// If the recipe has been unrolled, return the VPValue for the induction
2673 /// increment, otherwise return null.
2675 return isUnrolled() ? getOperand(getNumOperands() - 2) : nullptr;
2676 }
2677
2678 /// Returns the number of incoming values, also number of incoming blocks.
2679 /// Note that at the moment, VPWidenIntOrFpInductionRecipes only have a single
2680 /// incoming value, its start value.
2681 unsigned getNumIncoming() const override { return 1; }
2682
2683 /// Returns true if this induction is evaluated in a narrower type than the
2684 /// start value.
2690
2691 /// Return the cost of this VPWidenIntOrFpInductionRecipe.
2693 VPCostContext &Ctx) const override;
2694
2695 /// Returns true if the induction is canonical, i.e. starting at 0 and
2696 /// incremented by UF * VF (= the original IV is incremented by 1) and has the
2697 /// same type as the canonical induction.
2698 bool isCanonical() const;
2699
2700 /// Returns the VPValue representing the value of this induction at
2701 /// the last unrolled part, if it exists. Returns itself if unrolling did not
2702 /// take place.
2704 return isUnrolled() ? getLastOperand() : this;
2705 }
2706
2707protected:
2708#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2709 /// Print the recipe.
2710 void printRecipe(raw_ostream &O, const Twine &Indent,
2711 VPSlotTracker &SlotTracker) const override;
2712#endif
2713};
2714
2716public:
2717 /// Create a new VPWidenPointerInductionRecipe for \p Phi with start value \p
2718 /// Start and the number of elements unrolled \p NumUnrolledElems, typically
2719 /// VF*UF.
2721 VPValue *NumUnrolledElems,
2722 const InductionDescriptor &IndDesc, DebugLoc DL)
2723 : VPWidenInductionRecipe(VPRecipeBase::VPWidenPointerInductionSC, Phi,
2724 Start, Step, IndDesc, Start->getScalarType(),
2725 DL) {
2726 addOperand(NumUnrolledElems);
2727 }
2728
2730
2736
2737 VP_CLASSOF_IMPL(VPRecipeBase::VPWidenPointerInductionSC)
2738
2739 /// Generate vector values for the pointer induction.
2740 void execute(VPTransformState &State) override {
2741 llvm_unreachable("cannot execute this recipe, should be expanded via "
2742 "expandVPWidenPointerInduction");
2743 };
2744
2745 /// Returns true if only scalar values will be generated.
2747
2748 /// Return the cost of this VPWidenPointerInductionRecipe.
2750 VPCostContext &Ctx) const override;
2751
2752protected:
2753#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2754 /// Print the recipe.
2755 void printRecipe(raw_ostream &O, const Twine &Indent,
2756 VPSlotTracker &SlotTracker) const override;
2757#endif
2758};
2759
2760/// A recipe for widened phis. Incoming values are operands of the recipe and
2761/// their operand index corresponds to the incoming predecessor block. If the
2762/// recipe is placed in an entry block to a (non-replicate) region, it must have
2763/// exactly 2 incoming values, the first from the predecessor of the region and
2764/// the second from the exiting block of the region.
2766 public VPPhiAccessors {
2767 /// Name to use for the generated IR instruction for the widened phi.
2768 std::string Name;
2769
2770public:
2771 /// Create a new VPWidenPHIRecipe with incoming values \p IncomingValues,
2772 /// debug location \p DL and \p Name.
2774 DebugLoc DL = DebugLoc::getUnknown(), const Twine &Name = "")
2775 : VPSingleDefRecipe(VPRecipeBase::VPWidenPHISC, IncomingValues,
2776 IncomingValues[0]->getScalarType(),
2777 /*UV=*/nullptr, DL),
2778 Name(Name.str()) {
2779 assert(all_of(IncomingValues,
2780 [this](VPValue *VPV) {
2781 return VPV->getScalarType() == getScalarType();
2782 }) &&
2783 "all incoming values must have the same type");
2784 }
2785
2787 return new VPWidenPHIRecipe(operands(), getDebugLoc(), Name);
2788 }
2789
2790 ~VPWidenPHIRecipe() override = default;
2791
2792 /// This recipe generates a PHI.
2793 unsigned getOpcode() const { return Instruction::PHI; }
2794
2795 VP_CLASSOF_IMPL(VPRecipeBase::VPWidenPHISC)
2796
2797 /// Generate the phi/select nodes.
2798 void execute(VPTransformState &State) override;
2799
2800 /// Return the cost of this VPWidenPHIRecipe.
2801 InstructionCost computeCost(ElementCount VF,
2802 VPCostContext &Ctx) const override;
2803
2804protected:
2805#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2806 /// Print the recipe.
2807 void printRecipe(raw_ostream &O, const Twine &Indent,
2808 VPSlotTracker &SlotTracker) const override;
2809#endif
2810
2811 const VPRecipeBase *getAsRecipe() const override { return this; }
2812};
2813
2814/// A recipe for handling first-order recurrence phis. The start value is the
2815/// first operand of the recipe and the incoming value from the backedge is the
2816/// second operand.
2819 VPValue &BackedgeValue)
2820 : VPHeaderPHIRecipe(VPRecipeBase::VPFirstOrderRecurrencePHISC, Phi,
2821 &Start, Start.getScalarType()) {
2822 addOperand(&BackedgeValue);
2823 }
2824
2825 VP_CLASSOF_IMPL(VPRecipeBase::VPFirstOrderRecurrencePHISC)
2826
2831
2832 void execute(VPTransformState &State) override;
2833
2834 /// Return the cost of this first-order recurrence phi recipe.
2836 VPCostContext &Ctx) const override;
2837
2838 /// Returns true if the recipe only uses the first lane of operand \p Op.
2839 bool usesFirstLaneOnly(const VPValue *Op) const override {
2841 "Op must be an operand of the recipe");
2842 return Op == getStartValue();
2843 }
2844
2845protected:
2846#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2847 /// Print the recipe.
2848 void printRecipe(raw_ostream &O, const Twine &Indent,
2849 VPSlotTracker &SlotTracker) const override;
2850#endif
2851};
2852
2853/// Possible variants of a reduction.
2854
2855/// This reduction is ordered and in-loop.
2856struct RdxOrdered {};
2857/// This reduction is in-loop.
2858struct RdxInLoop {};
2859/// This reduction is unordered with the partial result scaled down by some
2860/// factor.
2863};
2864using ReductionStyle = std::variant<RdxOrdered, RdxInLoop, RdxUnordered>;
2865
2866inline ReductionStyle getReductionStyle(bool InLoop, bool Ordered,
2867 unsigned ScaleFactor) {
2868 assert((!Ordered || InLoop) && "Ordered implies in-loop");
2869 if (Ordered)
2870 return RdxOrdered{};
2871 if (InLoop)
2872 return RdxInLoop{};
2873 return RdxUnordered{/*VFScaleFactor=*/ScaleFactor};
2874}
2875
2876/// A recipe for handling reduction phis. The start value is the first operand
2877/// of the recipe and the incoming value from the backedge is the second
2878/// operand.
2880 /// The recurrence kind of the reduction.
2881 const RecurKind Kind;
2882
2883 ReductionStyle Style;
2884
2885 /// The phi is part of a multi-use reduction (e.g., used in FindIV
2886 /// patterns for argmin/argmax).
2887 /// TODO: Also support cases where the phi itself has a single use, but its
2888 /// compare has multiple uses.
2889 bool HasUsesOutsideReductionChain;
2890
2891 /// Temporary flag indicating that the FindIV reduction expression has been
2892 /// sunk. While this is true, epilogue vectorization is disabled to avoid
2893 /// applying the sunk expression twice (once in the main vector loop and again
2894 /// in the epilogue), which can produce incorrect results by applying the sunk
2895 /// operation twice.
2896 /// TODO: Remove this flag once epilogue vectorization properly supports
2897 /// sunk FindIV expressions.
2898 bool ExpressionSunk = false;
2899
2900public:
2901 /// Create a new VPReductionPHIRecipe for the reduction \p Phi.
2903 VPValue &BackedgeValue, ReductionStyle Style,
2904 const VPIRFlags &Flags,
2905 bool HasUsesOutsideReductionChain = false)
2906 : VPHeaderPHIRecipe(VPRecipeBase::VPReductionPHISC, Phi, &Start,
2907 Start.getScalarType()),
2908 VPIRFlags(Flags), Kind(Kind), Style(Style),
2909 HasUsesOutsideReductionChain(HasUsesOutsideReductionChain) {
2910 addOperand(&BackedgeValue);
2911 }
2912
2913 ~VPReductionPHIRecipe() override = default;
2914
2916 VPValue *BackedgeValue) {
2917 auto *Clone = new VPReductionPHIRecipe(
2919 *Start, *BackedgeValue, Style, *this, HasUsesOutsideReductionChain);
2920 Clone->ExpressionSunk = ExpressionSunk;
2921 return Clone;
2922 }
2923
2927
2928 VP_CLASSOF_IMPL(VPRecipeBase::VPReductionPHISC)
2929
2930 /// Generate the phi/select nodes.
2931 void execute(VPTransformState &State) override;
2932
2933 /// Get the factor that the VF of this recipe's output should be scaled by, or
2934 /// 1 if it isn't scaled.
2935 unsigned getVFScaleFactor() const {
2936 auto *Partial = std::get_if<RdxUnordered>(&Style);
2937 return Partial ? Partial->VFScaleFactor : 1;
2938 }
2939
2940 /// Set the VFScaleFactor for this reduction phi. Can only be set to a factor
2941 /// > 1.
2942 void setVFScaleFactor(unsigned ScaleFactor) {
2943 assert(ScaleFactor > 1 && "must set to scale factor > 1");
2944 Style = RdxUnordered{ScaleFactor};
2945 }
2946
2947 /// Returns the recurrence kind of the reduction.
2948 RecurKind getRecurrenceKind() const { return Kind; }
2949
2950 /// Returns true, if the phi is part of an ordered reduction.
2951 bool isOrdered() const { return std::holds_alternative<RdxOrdered>(Style); }
2952
2953 /// Returns true if the phi is part of an in-loop reduction.
2954 bool isInLoop() const {
2955 return std::holds_alternative<RdxInLoop>(Style) ||
2956 std::holds_alternative<RdxOrdered>(Style);
2957 }
2958
2959 /// Returns true, if the phi is part of a multi-use reduction.
2961 return HasUsesOutsideReductionChain;
2962 }
2963
2964 void setExpressionSunk() { ExpressionSunk = true; }
2965
2966 bool isExpressionSunk() const { return ExpressionSunk; }
2967
2968 /// Returns true if the recipe only uses the first lane of operand \p Op.
2969 bool usesFirstLaneOnly(const VPValue *Op) const override {
2971 "Op must be an operand of the recipe");
2972 return isOrdered() || isInLoop();
2973 }
2974
2975protected:
2976#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2977 /// Print the recipe.
2978 void printRecipe(raw_ostream &O, const Twine &Indent,
2979 VPSlotTracker &SlotTracker) const override;
2980#endif
2981};
2982
2983/// A recipe for handling scalar conditional induction PHIs. The start value is
2984/// the first operand of the recipe and the incoming value from the backedge is
2985/// the second operand.
2987 const SCEV *StepSCEV = nullptr;
2988
2989public:
2991 VPValue &BackedgeValue, const SCEV *StepSCEV)
2992 : VPHeaderPHIRecipe(VPRecipeBase::VPConditionalInductionPHISC, &Phi,
2993 &Start, Start.getScalarType()),
2994 StepSCEV(StepSCEV) {
2995 addOperand(&BackedgeValue);
2996 }
2997
2999
3000 /// Returns the underlying PHINode.
3002
3003 /// Returns the conditional induction step SCEV expression.
3004 const SCEV *getStepSCEV() const { return StepSCEV; }
3005
3010
3011 VP_CLASSOF_IMPL(VPRecipeBase::VPConditionalInductionPHISC)
3012
3014 return R->getVPRecipeID() == VPRecipeBase::VPConditionalInductionPHISC;
3015 }
3016
3017 void execute(VPTransformState &) override {
3018 llvm_unreachable("must be expanded before final execute");
3019 }
3020
3022 VPCostContext &Ctx) const override;
3023
3024#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3025 /// Print the recipe.
3026 void printRecipe(raw_ostream &O, const Twine &Indent,
3027 VPSlotTracker &SlotTracker) const override;
3028#endif
3029
3030 /// Returns true if the recipe only uses the first lane of operand \p Op.
3031 bool usesFirstLaneOnly(const VPValue *Op) const override {
3033 "Op must be an operand of the recipe");
3034 return true;
3035 }
3036};
3037
3038/// A recipe for vectorizing a phi-node as a sequence of mask-based select
3039/// instructions.
3041public:
3042 /// The blend operation is a User of the incoming values and of their
3043 /// respective masks, ordered [I0, M0, I1, M1, I2, M2, ...]. Note that M0 can
3044 /// be omitted (implied by passing an odd number of operands) in which case
3045 /// all other incoming values are merged into it.
3047 const VPIRFlags &Flags, DebugLoc DL)
3049 Operands[0]->getScalarType(), Flags, DL) {
3050 assert(Operands.size() >= 2 && "Expected at least two operands!");
3052 [this](unsigned I) {
3053 return getIncomingValue(I)->getScalarType() ==
3054 getScalarType();
3055 }) &&
3056 "all incoming values must have the same type");
3058 [this](unsigned I) {
3059 return getMask(I)->getScalarType()->isIntegerTy(1);
3060 }) &&
3061 "masks must be a bool");
3062 assert(hasRequiredFlagsForOpcode(Instruction::PHI, getScalarType()) &&
3063 "blends require the flags of the phi they replace");
3064 setUnderlyingValue(Phi);
3065 }
3066
3068
3071 NewOperands, *this, getDebugLoc());
3072 }
3073
3074 VP_CLASSOF_IMPL(VPRecipeBase::VPBlendSC)
3075
3076 /// A normalized blend is one that has an odd number of operands, whereby the
3077 /// first operand does not have an associated mask.
3078 bool isNormalized() const { return getNumOperands() % 2; }
3079
3080 /// Return the number of incoming values, taking into account when normalized
3081 /// the first incoming value will have no mask.
3082 unsigned getNumIncomingValues() const {
3083 return (getNumOperands() + isNormalized()) / 2;
3084 }
3085
3086 /// Return incoming value number \p Idx.
3087 VPValue *getIncomingValue(unsigned Idx) const {
3088 return Idx == 0 ? getOperand(0) : getOperand(Idx * 2 - isNormalized());
3089 }
3090
3091 /// Return mask number \p Idx.
3092 VPValue *getMask(unsigned Idx) const {
3093 assert((Idx > 0 || !isNormalized()) && "First index has no mask!");
3094 return Idx == 0 ? getOperand(1) : getOperand(Idx * 2 + !isNormalized());
3095 }
3096
3097 /// Set mask number \p Idx to \p V.
3098 void setMask(unsigned Idx, VPValue *V) {
3099 assert((Idx > 0 || !isNormalized()) && "First index has no mask!");
3100 assert(V->getScalarType()->isIntegerTy(1) && "Mask must be an i1 (vector)");
3101 Idx == 0 ? setOperand(1, V) : setOperand(Idx * 2 + !isNormalized(), V);
3102 }
3103
3104 void execute(VPTransformState &State) override {
3105 llvm_unreachable("VPBlendRecipe should be expanded by simplifyBlends");
3106 }
3107
3108 /// Return the cost of this VPWidenMemoryRecipe.
3109 InstructionCost computeCost(ElementCount VF,
3110 VPCostContext &Ctx) const override;
3111
3112 /// Returns true if the recipe only uses the first lane of operand \p Op.
3113 bool usesFirstLaneOnly(const VPValue *Op) const override;
3114
3115protected:
3116#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3117 /// Print the recipe.
3118 void printRecipe(raw_ostream &O, const Twine &Indent,
3119 VPSlotTracker &SlotTracker) const override;
3120#endif
3121};
3122
3123/// A common base class for interleaved memory operations.
3124/// An Interleaved memory operation is a memory access method that combines
3125/// multiple strided loads/stores into a single wide load/store with shuffles.
3126/// The first operand is the start address. The optional operands are, in order,
3127/// the stored values and the mask.
3129 public VPIRMetadata {
3131
3132 /// Indicates if the interleave group is in a conditional block and requires a
3133 /// mask.
3134 bool HasMask = false;
3135
3136 /// Indicates if gaps between members of the group need to be masked out or if
3137 /// unusued gaps can be loaded speculatively.
3138 bool NeedsMaskForGaps = false;
3139
3140protected:
3142 ArrayRef<VPValue *> Operands,
3143 ArrayRef<VPValue *> StoredValues, VPValue *Mask,
3144 bool NeedsMaskForGaps, const VPIRMetadata &MD, DebugLoc DL)
3145 : VPRecipeBase(SC, Operands, DL), VPIRMetadata(MD), IG(IG),
3146 NeedsMaskForGaps(NeedsMaskForGaps) {
3147 // TODO: extend the masked interleaved-group support to reversed access.
3148 assert((!Mask || !IG->isReverse()) &&
3149 "Reversed masked interleave-group not supported.");
3150 if (StoredValues.empty()) {
3151 for (Instruction *Inst : IG->members()) {
3152 assert(!Inst->getType()->isVoidTy() && "must have result");
3153 new VPMultiDefValue(this, Inst, Inst->getType());
3154 }
3155 } else {
3156 for (auto *SV : StoredValues)
3157 addOperand(SV);
3158 }
3159 if (Mask) {
3160 HasMask = true;
3161 addOperand(Mask);
3162 }
3163 }
3164
3165public:
3166 VPInterleaveBase *clone() override = 0;
3167
3168 static inline bool classof(const VPRecipeBase *R) {
3169 return R->getVPRecipeID() == VPRecipeBase::VPInterleaveSC ||
3170 R->getVPRecipeID() == VPRecipeBase::VPInterleaveEVLSC;
3171 }
3172
3173 static inline bool classof(const VPUser *U) {
3174 auto *R = dyn_cast<VPRecipeBase>(U);
3175 return R && classof(R);
3176 }
3177
3178 /// Return the address accessed by this recipe.
3179 VPValue *getAddr() const {
3180 return getOperand(0); // Address is the 1st, mandatory operand.
3181 }
3182
3183 /// Return the mask used by this recipe. Note that a full mask is represented
3184 /// by a nullptr.
3185 VPValue *getMask() const {
3186 // Mask is optional and the last operand.
3187 return HasMask ? getLastOperand() : nullptr;
3188 }
3189
3190 /// Return true if the access needs a mask because of the gaps.
3191 bool needsMaskForGaps() const { return NeedsMaskForGaps; }
3192
3194
3195 Instruction *getInsertPos() const { return IG->getInsertPos(); }
3196
3197 void execute(VPTransformState &State) override {
3198 llvm_unreachable("VPInterleaveBase should not be instantiated.");
3199 }
3200
3201 /// Return the cost of this recipe.
3202 InstructionCost computeCost(ElementCount VF,
3203 VPCostContext &Ctx) const override;
3204
3205 /// Returns true if the recipe only uses the first lane of operand \p Op.
3206 bool usesFirstLaneOnly(const VPValue *Op) const override = 0;
3207
3208 /// Returns the number of stored operands of this interleave group. Returns 0
3209 /// for load interleave groups.
3210 virtual unsigned getNumStoreOperands() const = 0;
3211
3212 /// Return the VPValues stored by this interleave group. If it is a load
3213 /// interleave group, return an empty ArrayRef.
3215 return {op_end() - (getNumStoreOperands() + (HasMask ? 1 : 0)),
3217 }
3218};
3219
3220/// VPInterleaveRecipe is a recipe for transforming an interleave group of load
3221/// or stores into one wide load/store and shuffles. The first operand of a
3222/// VPInterleave recipe is the address, followed by the stored values, followed
3223/// by an optional mask.
3225public:
3227 ArrayRef<VPValue *> StoredValues, VPValue *Mask,
3228 bool NeedsMaskForGaps, const VPIRMetadata &MD, DebugLoc DL)
3229 : VPInterleaveBase(VPRecipeBase::VPInterleaveSC, IG, Addr, StoredValues,
3230 Mask, NeedsMaskForGaps, MD, DL) {}
3231
3232 ~VPInterleaveRecipe() override = default;
3233
3237 needsMaskForGaps(), *this, getDebugLoc());
3238 }
3239
3240 VP_CLASSOF_IMPL(VPRecipeBase::VPInterleaveSC)
3241
3242 /// Generate the wide load or store, and shuffles.
3243 void execute(VPTransformState &State) override;
3244
3245 bool usesFirstLaneOnly(const VPValue *Op) const override {
3247 "Op must be an operand of the recipe");
3248 return Op == getAddr() && !llvm::is_contained(getStoredValues(), Op);
3249 }
3250
3251 unsigned getNumStoreOperands() const override {
3252 return getNumOperands() - (getMask() ? 2 : 1);
3253 }
3254
3255protected:
3256#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3257 /// Print the recipe.
3258 void printRecipe(raw_ostream &O, const Twine &Indent,
3259 VPSlotTracker &SlotTracker) const override;
3260#endif
3261};
3262
3263/// A recipe for interleaved memory operations with vector-predication
3264/// intrinsics. The first operand is the address, the second operand is the
3265/// explicit vector length. Stored values and mask are optional operands.
3267public:
3269 : VPInterleaveBase(VPRecipeBase::VPInterleaveEVLSC,
3270 R.getInterleaveGroup(), {R.getAddr(), &EVL},
3271 R.getStoredValues(), Mask, R.needsMaskForGaps(), R,
3272 R.getDebugLoc()) {
3273 assert(!getInterleaveGroup()->isReverse() &&
3274 "Reversed interleave-group with tail folding is not supported.");
3275 assert(!needsMaskForGaps() && "Interleaved access with gap mask is not "
3276 "supported for scalable vector.");
3277 }
3278
3279 ~VPInterleaveEVLRecipe() override = default;
3280
3282 llvm_unreachable("cloning not implemented yet");
3283 }
3284
3285 VP_CLASSOF_IMPL(VPRecipeBase::VPInterleaveEVLSC)
3286
3287 /// The VPValue of the explicit vector length.
3288 VPValue *getEVL() const { return getOperand(1); }
3289
3290 /// Generate the wide load or store, and shuffles.
3291 void execute(VPTransformState &State) override;
3292
3293 /// The recipe only uses the first lane of the address, and EVL operand.
3294 bool usesFirstLaneOnly(const VPValue *Op) const override {
3296 "Op must be an operand of the recipe");
3297 return (Op == getAddr() && !llvm::is_contained(getStoredValues(), Op)) ||
3298 Op == getEVL();
3299 }
3300
3301 unsigned getNumStoreOperands() const override {
3302 return getNumOperands() - (getMask() ? 3 : 2);
3303 }
3304
3305protected:
3306#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3307 /// Print the recipe.
3308 void printRecipe(raw_ostream &O, const Twine &Indent,
3309 VPSlotTracker &SlotTracker) const override;
3310#endif
3311};
3312
3313/// A recipe to represent inloop, ordered or partial reduction operations. It
3314/// performs a reduction on a vector operand into a scalar (vector in the case
3315/// of a partial reduction) value, and adds the result to a chain. The Operands
3316/// are {ChainOp, VecOp, [Condition]}.
3318
3319 /// The recurrence kind for the reduction in question.
3320 RecurKind RdxKind;
3321 /// Whether the reduction is conditional.
3322 bool IsConditional = false;
3323 ReductionStyle Style;
3324
3325protected:
3328 VPValue *CondOp, ReductionStyle Style, DebugLoc DL)
3330 DL),
3331 RdxKind(RdxKind), Style(Style) {
3333 [this](VPValue *VPV) {
3334 return VPV->getScalarType() == getScalarType() ||
3335 (isa<VPInstruction>(VPV) &&
3336 cast<VPInstruction>(VPV)->getOpcode() ==
3338 }) &&
3339 "all incoming values must have the same type");
3340 if (CondOp) {
3341 assert(CondOp->getScalarType()->isIntegerTy(1) &&
3342 "CondOp must be a bool");
3343 IsConditional = true;
3344 addOperand(CondOp);
3345 }
3347 }
3348
3349public:
3351 VPValue *ChainOp, VPValue *VecOp, VPValue *CondOp,
3353 : VPReductionRecipe(VPRecipeBase::VPReductionSC, RdxKind, FMFs, I,
3354 {ChainOp, VecOp}, CondOp, Style, DL) {}
3355
3357 VPValue *ChainOp, VPValue *VecOp, VPValue *CondOp,
3359 : VPReductionRecipe(VPRecipeBase::VPReductionSC, RdxKind, FMFs, nullptr,
3360 {ChainOp, VecOp}, CondOp, Style, DL) {}
3361
3362 ~VPReductionRecipe() override = default;
3363
3365 return new VPReductionRecipe(RdxKind, getFastMathFlagsOrNone(),
3367 getCondOp(), Style, getDebugLoc());
3368 }
3369
3370 static inline bool classof(const VPRecipeBase *R) {
3371 return R->getVPRecipeID() == VPRecipeBase::VPReductionSC ||
3372 R->getVPRecipeID() == VPRecipeBase::VPReductionEVLSC;
3373 }
3374
3375 static inline bool classof(const VPUser *U) {
3376 auto *R = dyn_cast<VPRecipeBase>(U);
3377 return R && classof(R);
3378 }
3379
3380 static inline bool classof(const VPValue *VPV) {
3381 const VPRecipeBase *R = VPV->getDefiningRecipe();
3382 return R && classof(R);
3383 }
3384
3385 static inline bool classof(const VPSingleDefRecipe *R) {
3386 return classof(static_cast<const VPRecipeBase *>(R));
3387 }
3388
3389 /// Generate the reduction in the loop.
3390 void execute(VPTransformState &State) override;
3391
3392 /// Return the cost of VPReductionRecipe.
3393 InstructionCost computeCost(ElementCount VF,
3394 VPCostContext &Ctx) const override;
3395
3396 /// Return the recurrence kind for the in-loop reduction.
3397 RecurKind getRecurrenceKind() const { return RdxKind; }
3398 /// Return true if the in-loop reduction is ordered.
3399 bool isOrdered() const { return std::holds_alternative<RdxOrdered>(Style); };
3400 /// Return true if the in-loop reduction is conditional.
3401 bool isConditional() const { return IsConditional; };
3402 /// Returns true if the reduction outputs a vector with a scaled down VF.
3403 bool isPartialReduction() const {
3404 return std::holds_alternative<RdxUnordered>(Style);
3405 }
3406 /// Returns true if the reduction is in-loop.
3407 bool isInLoop() const {
3408 return std::holds_alternative<RdxInLoop>(Style) ||
3409 std::holds_alternative<RdxOrdered>(Style);
3410 }
3411 /// The VPValue of the scalar Chain being accumulated.
3412 VPValue *getChainOp() const { return getOperand(0); }
3413 /// The VPValue of the vector value to be reduced.
3414 VPValue *getVecOp() const { return getOperand(1); }
3415 /// The VPValue of the condition for the block.
3417 return isConditional() ? getLastOperand() : nullptr;
3418 }
3419 /// Get the factor that the VF of this recipe's output should be scaled by, or
3420 /// 1 if it isn't scaled.
3421 unsigned getVFScaleFactor() const {
3422 auto *Partial = std::get_if<RdxUnordered>(&Style);
3423 return Partial ? Partial->VFScaleFactor : 1;
3424 }
3425
3426protected:
3427#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3428 /// Print the recipe.
3429 void printRecipe(raw_ostream &O, const Twine &Indent,
3430 VPSlotTracker &SlotTracker) const override;
3431#endif
3432};
3433
3434/// A recipe to represent inloop reduction operations with vector-predication
3435/// intrinsics, performing a reduction on a vector operand with the explicit
3436/// vector length (EVL) into a scalar value, and adding the result to a chain.
3437/// The Operands are {ChainOp, VecOp, EVL, [Condition]}.
3439public:
3442 : VPReductionRecipe(VPRecipeBase::VPReductionEVLSC, R.getRecurrenceKind(),
3445 {R.getChainOp(), R.getVecOp(), &EVL}, CondOp,
3446 getReductionStyle(R.isInLoop(), R.isOrdered(),
3447 R.getVFScaleFactor()),
3448 DL) {}
3449
3450 ~VPReductionEVLRecipe() override = default;
3451
3453 llvm_unreachable("cloning not implemented yet");
3454 }
3455
3456 VP_CLASSOF_IMPL(VPRecipeBase::VPReductionEVLSC)
3457
3458 /// Generate the reduction in the loop
3459 void execute(VPTransformState &State) override;
3460
3461 /// The VPValue of the explicit vector length.
3462 VPValue *getEVL() const { return getOperand(2); }
3463
3464 /// Returns true if the recipe only uses the first lane of operand \p Op.
3465 bool usesFirstLaneOnly(const VPValue *Op) const override {
3467 "Op must be an operand of the recipe");
3468 return Op == getEVL();
3469 }
3470
3471protected:
3472#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3473 /// Print the recipe.
3474 void printRecipe(raw_ostream &O, const Twine &Indent,
3475 VPSlotTracker &SlotTracker) const override;
3476#endif
3477};
3478
3479/// VPReplicateRecipe replicates a given instruction producing multiple scalar
3480/// copies of the original scalar type, one per lane, instead of producing a
3481/// single copy of widened type for all lanes. If the instruction is known to be
3482/// a single scalar, only one copy will be generated.
3484 public VPIRMetadata {
3485 /// Indicator if only a single replica per lane is needed.
3486 bool IsSingleScalar;
3487
3488 /// Indicator if the replicas are also predicated.
3489 bool IsPredicated;
3490
3491public:
3493 bool IsSingleScalar, VPValue *Mask = nullptr,
3494 const VPIRFlags &Flags = {}, VPIRMetadata Metadata = {},
3495 DebugLoc DL = DebugLoc::getUnknown())
3496 : VPRecipeWithIRFlags(VPRecipeBase::VPReplicateSC, Operands,
3497 computeScalarType(I, Operands), Flags, DL),
3498 VPIRMetadata(Metadata), IsSingleScalar(IsSingleScalar),
3499 IsPredicated(Mask) {
3500 assert((!IsSingleScalar || !I->isCast()) &&
3501 "Single-scalar casts should use VPInstruction");
3502 setUnderlyingValue(I);
3503 if (Mask)
3504 addOperand(Mask);
3505 }
3506
3507 ~VPReplicateRecipe() override = default;
3508
3509 /// Compute the scalar result type for a VPReplicateRecipe wrapping \p I with
3510 /// \p Operands (excluding any predicate mask).
3511 static Type *computeScalarType(const Instruction *I,
3513
3515
3517 return new VPReplicateRecipe(
3518 getUnderlyingInstr(), NewOperands, IsSingleScalar,
3519 isPredicated() ? getMask() : nullptr, *this, *this, getDebugLoc());
3520 }
3521
3522 VP_CLASSOF_IMPL(VPRecipeBase::VPReplicateSC)
3523
3524 /// Generate replicas of the desired Ingredient. Replicas will be generated
3525 /// for all parts and lanes unless a specific part and lane are specified in
3526 /// the \p State.
3527 void execute(VPTransformState &State) override;
3528
3529 /// Return the cost of this VPReplicateRecipe.
3530 InstructionCost computeCost(ElementCount VF,
3531 VPCostContext &Ctx) const override;
3532
3533 /// Return the cost of scalarizing a call to \p CalledFn with argument
3534 /// operands \p ArgOps for a given \p VF.
3535 static InstructionCost computeCallCost(Function *CalledFn, Type *ResultTy,
3537 bool IsSingleScalar, ElementCount VF,
3538 VPCostContext &Ctx);
3539
3540 /// Returns true if the recipe produces a single scalar value.
3541 bool isSingleScalar() const { return IsSingleScalar; }
3542
3543 /// Returns true if the recipe produces scalar values for all VF lanes.
3544 bool doesGeneratePerAllLanes() const { return !IsSingleScalar; }
3545
3546 bool isPredicated() const { return IsPredicated; }
3547
3548 /// Returns true if the recipe only uses the first lane of operand \p Op.
3549 bool usesFirstLaneOnly(const VPValue *Op) const override {
3551 "Op must be an operand of the recipe");
3552 return isSingleScalar();
3553 }
3554
3555 /// Returns true if the recipe uses scalars of operand \p Op.
3556 bool usesScalars(const VPValue *Op) const override {
3558 "Op must be an operand of the recipe");
3559 return true;
3560 }
3561
3562 /// Return the mask of a predicated VPReplicateRecipe.
3564 assert(isPredicated() && "Trying to get the mask of a unpredicated recipe");
3565 return getLastOperand();
3566 }
3567
3568 /// Return the recipe's operands, excluding the mask of a predicated recipe.
3572
3573 /// Returns the number of operands, excluding the mask if the recipe is
3574 /// predicated.
3575 unsigned getNumOperandsWithoutMask() const {
3576 return getNumOperands() - isPredicated();
3577 }
3578
3579 unsigned getOpcode() const { return getUnderlyingInstr()->getOpcode(); }
3580
3581protected:
3582#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3583 /// Print the recipe.
3584 void printRecipe(raw_ostream &O, const Twine &Indent,
3585 VPSlotTracker &SlotTracker) const override;
3586#endif
3587};
3588
3589/// A recipe for generating conditional branches on the bits of a mask.
3591 public VPIRMetadata {
3592public:
3594 const VPIRMetadata &Metadata = {})
3595 : VPRecipeBase(VPRecipeBase::VPBranchOnMaskSC, {BlockInMask}, DL),
3596 VPIRMetadata(Metadata) {}
3597
3599 return new VPBranchOnMaskRecipe(getOperand(0), getDebugLoc(), *this);
3600 }
3601
3602 VP_CLASSOF_IMPL(VPRecipeBase::VPBranchOnMaskSC)
3603
3604 /// Generate the extraction of the appropriate bit from the block mask and the
3605 /// conditional branch.
3606 void execute(VPTransformState &State) override;
3607
3608 /// Return the cost of this VPBranchOnMaskRecipe.
3609 InstructionCost computeCost(ElementCount VF,
3610 VPCostContext &Ctx) const override;
3611
3612#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3613 /// Print the recipe.
3614 void printRecipe(raw_ostream &O, const Twine &Indent,
3615 VPSlotTracker &SlotTracker) const override {
3616 O << Indent << "BRANCH-ON-MASK ";
3618 }
3619#endif
3620
3621 /// Returns true if the recipe uses scalars of operand \p Op.
3622 bool usesScalars(const VPValue *Op) const override {
3624 "Op must be an operand of the recipe");
3625 return true;
3626 }
3627};
3628
3629/// A recipe to combine multiple recipes into a single 'expression' recipe,
3630/// which should be considered a single entity for cost-modeling and transforms.
3631/// The recipe needs to be 'decomposed', i.e. replaced by its individual
3632/// expression recipes, before execute. The individual expression recipes are
3633/// completely disconnected from the def-use graph of other recipes not part of
3634/// the expression. Def-use edges between pairs of expression recipes remain
3635/// intact, whereas every edge between an expression recipe and a recipe outside
3636/// the expression is elevated to connect the non-expression recipe with the
3637/// VPExpressionRecipe itself.
3639 /// Recipes included in this VPExpressionRecipe. This could contain
3640 /// duplicates.
3641 SmallVector<VPSingleDefRecipe *> ExpressionRecipes;
3642
3643 /// Temporary VPValues used for external operands of the expression, i.e.
3644 /// operands not defined by recipes in the expression.
3645 SmallVector<VPValue *> LiveInPlaceholders;
3646
3647 enum class ExpressionTypes {
3648 /// Represents an inloop extended reduction operation, performing a
3649 /// reduction on an extended vector operand into a scalar value, and adding
3650 /// the result to a chain.
3651 ExtendedReduction,
3652 /// Represents an inloop extended reduction operation, which is negated,
3653 /// then reduced before adding the result to a chain.
3654 NegatedExtendedReduction,
3655 /// Represent an inloop multiply-accumulate reduction, multiplying the
3656 /// extended vector operands, performing a reduction.add on the result, and
3657 /// adding the scalar result to a chain.
3658 ExtMulAccReduction,
3659 /// Represent an inloop multiply-accumulate reduction, multiplying the
3660 /// vector operands, performing a reduction.add on the result, and adding
3661 /// the scalar result to a chain.
3662 MulAccReduction,
3663 /// Represent an inloop multiply-accumulate reduction, multiplying the
3664 /// extended vector operands, negating the multiplication, performing a
3665 /// reduction.add on the result, and adding the scalar result to a chain.
3666 ExtNegatedMulAccReduction,
3667 };
3668
3669 /// Type of the expression.
3670 ExpressionTypes ExpressionType;
3671
3672public:
3673 /// Construct a new VPExpressionRecipe by internalizing recipes in \p
3674 /// ExpressionRecipes. External operands (i.e. not defined by another recipe
3675 /// in the expression) are replaced by temporary VPValues and the original
3676 /// operands are transferred to the VPExpressionRecipe itself. Clone recipes
3677 /// as needed (excluding last) to ensure they are only used by other recipes
3678 /// in the expression.
3679 VPExpressionRecipe(ExpressionTypes ExpressionType,
3680 ArrayRef<VPSingleDefRecipe *> ExpressionRecipes);
3681
3683 : VPExpressionRecipe(ExpressionTypes::ExtendedReduction, {Ext, Red}) {}
3685 VPReductionRecipe *Red)
3686 : VPExpressionRecipe(ExpressionTypes::NegatedExtendedReduction,
3687 {Ext, Neg, Red}) {
3688 assert((Red->getRecurrenceKind() == RecurKind::Add ||
3689 Red->getRecurrenceKind() == RecurKind::FAdd ||
3690 Red->getRecurrenceKind() == RecurKind::AddChainWithSubs) &&
3691 "Expected an add or add-chain-with-subs reduction");
3692 if (Neg->getOpcode() == Instruction::Sub) {
3693 [[maybe_unused]] auto *SubConst = dyn_cast<VPConstantInt>(getOperand(1));
3694 assert(SubConst && SubConst->isZero() && "Expected a negating sub");
3695 } else
3696 assert(Neg->getOpcode() == Instruction::FNeg && "Unexpected opcode");
3697 }
3699 : VPExpressionRecipe(ExpressionTypes::MulAccReduction, {Mul, Red}) {}
3702 : VPExpressionRecipe(ExpressionTypes::ExtMulAccReduction,
3703 {Ext0, Ext1, Mul, Red}) {}
3706 VPReductionRecipe *Red)
3707 : VPExpressionRecipe(ExpressionTypes::ExtNegatedMulAccReduction,
3708 {Ext0, Ext1, Mul, Neg, Red}) {
3709 assert((Mul->getOpcode() == Instruction::Mul ||
3710 Mul->getOpcode() == Instruction::FMul) &&
3711 "Expected a mul");
3712 assert((Red->getRecurrenceKind() == RecurKind::Add ||
3713 Red->getRecurrenceKind() == RecurKind::FAdd ||
3714 Red->getRecurrenceKind() == RecurKind::AddChainWithSubs) &&
3715 "Expected an add or add-chain-with-subs reduction");
3716 assert(getNumOperands() >= 3 && "Expected at least three operands");
3717 if (Neg->getOpcode() == Instruction::Sub) {
3718 [[maybe_unused]] auto *SubConst = dyn_cast<VPConstantInt>(getOperand(2));
3719 assert(SubConst && SubConst->isZero() &&
3720 Neg->getOpcode() == Instruction::Sub && "Expected a negating sub");
3721 } else
3722 assert(Neg->getOpcode() == Instruction::FNeg && "Unexpected opcode");
3723 }
3724
3726 SmallPtrSet<VPSingleDefRecipe *, 4> ExpressionRecipesSeen;
3727 for (auto *R : reverse(ExpressionRecipes)) {
3728 if (ExpressionRecipesSeen.insert(R).second)
3729 delete R;
3730 }
3731 for (VPValue *T : LiveInPlaceholders)
3732 delete T;
3733 }
3734
3735 VP_CLASSOF_IMPL(VPRecipeBase::VPExpressionSC)
3736
3738 assert(!ExpressionRecipes.empty() && "empty expressions should be removed");
3739 SmallVector<VPSingleDefRecipe *> NewExpressiondRecipes;
3740 for (auto *R : ExpressionRecipes)
3741 NewExpressiondRecipes.push_back(R->clone());
3742 for (auto *New : NewExpressiondRecipes) {
3743 for (const auto &[Idx, Old] : enumerate(ExpressionRecipes))
3744 New->replaceUsesOfWith(Old, NewExpressiondRecipes[Idx]);
3745 // Update placeholder operands in the cloned recipe to use the external
3746 // operands, to be internalized when the cloned expression is constructed.
3747 for (const auto &[Placeholder, OutsideOp] :
3748 zip(LiveInPlaceholders, operands()))
3749 New->replaceUsesOfWith(Placeholder, OutsideOp);
3750 }
3751 return new VPExpressionRecipe(ExpressionType, NewExpressiondRecipes);
3752 }
3753
3754 /// Return and insert the recipes of the expression back into the VPlan,
3755 /// directly before the current recipe. Leaves the expression recipe empty,
3756 /// which must be removed before codegen.
3758
3759 /// Returns the expression type of this recipe.
3760 ExpressionTypes getExpressionType() const { return ExpressionType; }
3761
3762 unsigned getVFScaleFactor() const {
3763 auto *PR = dyn_cast<VPReductionRecipe>(ExpressionRecipes.back());
3764 return PR ? PR->getVFScaleFactor() : 1;
3765 }
3766
3767 /// Method for generating code, must not be called as this recipe is abstract.
3768 void execute(VPTransformState &State) override {
3769 llvm_unreachable("recipe must be removed before execute");
3770 }
3771
3773 VPCostContext &Ctx) const override;
3774
3775 /// Returns true if this expression contains recipes that may read from or
3776 /// write to memory.
3777 bool mayReadOrWriteMemory() const;
3778
3779 /// Returns true if this expression contains recipes that may have side
3780 /// effects.
3781 bool mayHaveSideEffects() const;
3782
3783 /// Returns true if this VPExpressionRecipe produces a single scalar.
3784 bool isVectorToScalar() const;
3785
3786protected:
3787#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3788 /// Print the recipe.
3789 void printRecipe(raw_ostream &O, const Twine &Indent,
3790 VPSlotTracker &SlotTracker) const override;
3791#endif
3792};
3793
3794/// VPPredInstPHIRecipe is a recipe for generating the phi nodes needed when
3795/// control converges back from a Branch-on-Mask. The phi nodes are needed in
3796/// order to merge values that are set under such a branch and feed their uses.
3797/// The phi nodes can be scalar or vector depending on the users of the value.
3798/// This recipe works in concert with VPBranchOnMaskRecipe.
3800public:
3801 /// Construct a VPPredInstPHIRecipe given \p PredInst whose value needs a phi
3802 /// nodes after merging back from a Branch-on-Mask.
3804 : VPSingleDefRecipe(VPRecipeBase::VPPredInstPHISC, PredV,
3805 PredV->getScalarType(), /*UV=*/nullptr, DL) {}
3806 ~VPPredInstPHIRecipe() override = default;
3807
3809 return new VPPredInstPHIRecipe(getOperand(0), getDebugLoc());
3810 }
3811
3812 VP_CLASSOF_IMPL(VPRecipeBase::VPPredInstPHISC)
3813
3814 /// Generates phi nodes for live-outs (from a replicate region) as needed to
3815 /// retain SSA form.
3816 void execute(VPTransformState &State) override;
3817
3818 /// Return the cost of this VPPredInstPHIRecipe.
3820 VPCostContext &Ctx) const override {
3821 // TODO: Compute accurate cost after retiring the legacy cost model.
3822 return 0;
3823 }
3824
3825protected:
3826#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3827 /// Print the recipe.
3828 void printRecipe(raw_ostream &O, const Twine &Indent,
3829 VPSlotTracker &SlotTracker) const override;
3830#endif
3831};
3832
3833/// A common mixin class for widening memory operations. An optional mask can be
3834/// provided as the last operand.
3836protected:
3838
3839 /// Alignment information for this memory access.
3841
3842 /// Whether the accessed addresses are consecutive.
3844
3845 /// Whether the memory access is masked.
3846 bool IsMasked = false;
3847
3848 void setMask(VPValue *Mask) {
3849 assert(!IsMasked && "cannot re-set mask");
3850 if (!Mask)
3851 return;
3852 assert(Mask->getScalarType()->isIntegerTy(1) &&
3853 "Mask must be an i1 (vector)");
3854 getAsRecipe()->addOperand(Mask);
3855 IsMasked = true;
3856 }
3857
3862
3863public:
3864 virtual ~VPWidenMemoryRecipe() = default;
3865
3866 /// Return a VPRecipeBase* to the current object.
3868 virtual const VPRecipeBase *getAsRecipe() const = 0;
3869
3870 /// Return whether the loaded-from / stored-to addresses are consecutive.
3871 bool isConsecutive() const { return Consecutive; }
3872
3873 /// Return the address accessed by this recipe.
3874 VPValue *getAddr() const { return getAsRecipe()->getOperand(0); }
3875
3876 /// Returns true if the recipe is masked.
3877 bool isMasked() const { return IsMasked; }
3878
3879 /// Return the mask used by this recipe. Note that a full mask is represented
3880 /// by a nullptr.
3881 VPValue *getMask() const {
3882 // Mask is optional and therefore the last operand.
3883 const VPRecipeBase *R = getAsRecipe();
3884 return isMasked() ? R->getLastOperand() : nullptr;
3885 }
3886
3887 /// Returns the alignment of the memory access.
3888 Align getAlign() const { return Alignment; }
3889
3890 /// Return the cost of this VPWidenMemoryRecipe.
3891 InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const;
3892
3894};
3895
3896/// A recipe for widening load operations, using the address to load from and an
3897/// optional mask.
3899 public VPWidenMemoryRecipe {
3902 const VPIRMetadata &Metadata, DebugLoc DL)
3903 : VPSingleDefRecipe(VPRecipeBase::VPWidenLoadSC, {Addr}, Load.getType(),
3904 &Load, DL),
3905 VPWidenMemoryRecipe(Load, Alignment, Consecutive, Metadata) {
3906 setMask(Mask);
3907 }
3908
3911 getMask(), Consecutive, getAlign(), *this,
3912 getDebugLoc());
3913 }
3914
3915 VP_CLASSOF_IMPL(VPRecipeBase::VPWidenLoadSC);
3916
3917 /// Returns the opcode of the widened load.
3918 unsigned getOpcode() const { return Instruction::Load; }
3919
3920 /// Generate a wide load or gather.
3921 void execute(VPTransformState &State) override;
3922
3923 /// Return the cost of this VPWidenLoadRecipe.
3925 VPCostContext &Ctx) const override {
3926 return VPWidenMemoryRecipe::computeCost(VF, Ctx);
3927 }
3928
3929 /// Returns true if the recipe only uses the first lane of operand \p Op.
3930 bool usesFirstLaneOnly(const VPValue *Op) const override {
3932 "Op must be an operand of the recipe");
3933 // Widened, consecutive loads operations only demand the first lane of
3934 // their address.
3935 return Op == getAddr() && isConsecutive();
3936 }
3937
3938protected:
3939 VPRecipeBase *getAsRecipe() override;
3940 const VPRecipeBase *getAsRecipe() const override;
3941
3942#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3943 /// Print the recipe.
3944 void printRecipe(raw_ostream &O, const Twine &Indent,
3945 VPSlotTracker &SlotTracker) const override;
3946#endif
3947};
3948
3949/// A recipe for widening load operations with vector-predication intrinsics,
3950/// using the address to load from, the explicit vector length and an optional
3951/// mask.
3953 : public VPSingleDefRecipe,
3954 public VPWidenMemoryRecipe {
3956 VPValue *Mask)
3957 : VPSingleDefRecipe(VPRecipeBase::VPWidenLoadEVLSC, {Addr, &EVL},
3958 L.getIngredient().getType(), &L.getIngredient(),
3959 L.getDebugLoc()),
3960 VPWidenMemoryRecipe(L.getIngredient(), L.getAlign(), L.isConsecutive(),
3961 L) {
3962 setMask(Mask);
3963 }
3964
3966 llvm_unreachable("cloning not supported");
3967 }
3968
3969 VP_CLASSOF_IMPL(VPRecipeBase::VPWidenLoadEVLSC)
3970
3971 /// Returns the opcode of the widened load.
3972 unsigned getOpcode() const { return Instruction::Load; }
3973
3974 /// Return the EVL operand.
3975 VPValue *getEVL() const { return getOperand(1); }
3976
3977 /// Generate the wide load or gather.
3978 void execute(VPTransformState &State) override;
3979
3980 /// Return the cost of this VPWidenLoadEVLRecipe.
3981 InstructionCost computeCost(ElementCount VF,
3982 VPCostContext &Ctx) const override;
3983
3984 /// Returns true if the recipe only uses the first lane of operand \p Op.
3985 bool usesFirstLaneOnly(const VPValue *Op) const override {
3987 "Op must be an operand of the recipe");
3988 // Widened loads only demand the first lane of EVL and consecutive loads
3989 // only demand the first lane of their address.
3990 return Op == getEVL() || (Op == getAddr() && isConsecutive());
3991 }
3992
3993protected:
3994 VPRecipeBase *getAsRecipe() override;
3995 const VPRecipeBase *getAsRecipe() const override;
3996
3997#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3998 /// Print the recipe.
3999 void printRecipe(raw_ostream &O, const Twine &Indent,
4000 VPSlotTracker &SlotTracker) const override;
4001#endif
4002};
4003
4004/// A recipe for widening store operations, using the stored value, the address
4005/// to store to and an optional mask.
4007 public VPWidenMemoryRecipe {
4009 VPValue *Mask, bool Consecutive, Align Alignment,
4010 const VPIRMetadata &Metadata, DebugLoc DL)
4011 : VPRecipeBase(VPRecipeBase::VPWidenStoreSC, {Addr, StoredVal}, DL),
4012 VPWidenMemoryRecipe(Store, Alignment, Consecutive, Metadata) {
4013 setMask(Mask);
4014 }
4015
4021
4022 VP_CLASSOF_IMPL(VPRecipeBase::VPWidenStoreSC);
4023
4024 /// Return the value stored by this recipe.
4025 VPValue *getStoredValue() const { return getOperand(1); }
4026
4027 /// Generate a wide store or scatter.
4028 void execute(VPTransformState &State) override;
4029
4030 /// Return the cost of this VPWidenStoreRecipe.
4032 VPCostContext &Ctx) const override {
4033 return VPWidenMemoryRecipe::computeCost(VF, Ctx);
4034 }
4035
4036 /// Returns true if the recipe only uses the first lane of operand \p Op.
4037 bool usesFirstLaneOnly(const VPValue *Op) const override {
4039 "Op must be an operand of the recipe");
4040 // Widened, consecutive stores only demand the first lane of their address,
4041 // unless the same operand is also stored.
4042 return Op == getAddr() && isConsecutive() && Op != getStoredValue();
4043 }
4044
4045protected:
4046 VPRecipeBase *getAsRecipe() override;
4047 const VPRecipeBase *getAsRecipe() const override;
4048
4049#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4050 /// Print the recipe.
4051 void printRecipe(raw_ostream &O, const Twine &Indent,
4052 VPSlotTracker &SlotTracker) const override;
4053#endif
4054};
4055
4056/// A recipe for widening store operations with vector-predication intrinsics,
4057/// using the value to store, the address to store to, the explicit vector
4058/// length and an optional mask.
4060 : public VPRecipeBase,
4061 public VPWidenMemoryRecipe {
4063 VPValue *StoredVal, VPValue &EVL, VPValue *Mask)
4064 : VPRecipeBase(VPRecipeBase::VPWidenStoreEVLSC, {Addr, StoredVal, &EVL},
4065 S.getDebugLoc()),
4066 VPWidenMemoryRecipe(S.getIngredient(), S.getAlign(), S.isConsecutive(),
4067 S) {
4068 setMask(Mask);
4069 }
4070
4072 llvm_unreachable("cloning not supported");
4073 }
4074
4075 VP_CLASSOF_IMPL(VPRecipeBase::VPWidenStoreEVLSC)
4076
4077 /// Return the address accessed by this recipe.
4078 VPValue *getStoredValue() const { return getOperand(1); }
4079
4080 /// Return the EVL operand.
4081 VPValue *getEVL() const { return getOperand(2); }
4082
4083 /// Generate the wide store or scatter.
4084 void execute(VPTransformState &State) override;
4085
4086 /// Return the cost of this VPWidenStoreEVLRecipe.
4087 InstructionCost computeCost(ElementCount VF,
4088 VPCostContext &Ctx) const override;
4089
4090 /// Returns true if the recipe only uses the first lane of operand \p Op.
4091 bool usesFirstLaneOnly(const VPValue *Op) const override {
4093 "Op must be an operand of the recipe");
4094 if (Op == getEVL()) {
4095 assert(getStoredValue() != Op && "unexpected store of EVL");
4096 return true;
4097 }
4098 // Widened, consecutive memory operations only demand the first lane of
4099 // their address, unless the same operand is also stored. That latter can
4100 // happen with opaque pointers.
4101 return Op == getAddr() && isConsecutive() && Op != getStoredValue();
4102 }
4103
4104protected:
4105 VPRecipeBase *getAsRecipe() override;
4106 const VPRecipeBase *getAsRecipe() const override;
4107
4108#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4109 /// Print the recipe.
4110 void printRecipe(raw_ostream &O, const Twine &Indent,
4111 VPSlotTracker &SlotTracker) const override;
4112#endif
4113};
4114
4115/// Recipe to expand a SCEV expression.
4117 const SCEV *Expr;
4118
4119 /// Whether \p Expr must be expanded in IR, which hoists it out of the loops
4120 /// it is invariant in, instead of as VPInstructions.
4121 bool ExpandInIR;
4122
4123public:
4124 VPExpandSCEVRecipe(const SCEV *Expr, bool ExpandInIR = false);
4125
4126 ~VPExpandSCEVRecipe() override = default;
4127
4129 return new VPExpandSCEVRecipe(Expr, ExpandInIR);
4130 }
4131
4132 VP_CLASSOF_IMPL(VPRecipeBase::VPExpandSCEVSC)
4133
4134 void execute(VPTransformState &State) override {
4135 llvm_unreachable("SCEV expressions must be expanded before final execute");
4136 }
4137
4138 /// Return the cost of this VPExpandSCEVRecipe.
4140 VPCostContext &Ctx) const override {
4141 // TODO: Compute accurate cost after retiring the legacy cost model.
4142 return 0;
4143 }
4144
4145 const SCEV *getSCEV() const { return Expr; }
4146
4147 bool expandInIR() const { return ExpandInIR; }
4148
4149protected:
4150#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4151 /// Print the recipe.
4152 void printRecipe(raw_ostream &O, const Twine &Indent,
4153 VPSlotTracker &SlotTracker) const override;
4154#endif
4155};
4156
4157/// A recipe for generating the active lane mask for the vector loop that is
4158/// used to predicate the vector operations.
4160public:
4162 : VPHeaderPHIRecipe(VPRecipeBase::VPActiveLaneMaskPHISC, nullptr,
4163 StartMask, StartMask->getScalarType(), DL) {}
4164
4165 ~VPActiveLaneMaskPHIRecipe() override = default;
4166
4169 if (getNumOperands() == 2)
4170 R->addBackedgeValue(getOperand(1));
4171 return R;
4172 }
4173
4174 VP_CLASSOF_IMPL(VPRecipeBase::VPActiveLaneMaskPHISC)
4175
4176 /// Generate the active lane mask phi of the vector loop.
4177 void execute(VPTransformState &State) override;
4178
4179protected:
4180#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4181 /// Print the recipe.
4182 void printRecipe(raw_ostream &O, const Twine &Indent,
4183 VPSlotTracker &SlotTracker) const override;
4184#endif
4185};
4186
4187/// A recipe for generating the phi node tracking the current scalar iteration
4188/// index. It starts at the start value of the canonical induction and gets
4189/// incremented by the number of scalar iterations processed by the vector loop
4190/// iteration. The increment does not have to be loop invariant.
4192public:
4194 : VPHeaderPHIRecipe(VPRecipeBase::VPCurrentIterationPHISC, nullptr,
4195 StartIV, StartIV->getScalarType(), DL) {}
4196
4197 ~VPCurrentIterationPHIRecipe() override = default;
4198
4200 llvm_unreachable("cloning not implemented yet");
4201 }
4202
4203 VP_CLASSOF_IMPL(VPRecipeBase::VPCurrentIterationPHISC)
4204
4205 void execute(VPTransformState &State) override {
4206 llvm_unreachable("cannot execute this recipe, should be replaced by a "
4207 "scalar phi recipe");
4208 }
4209
4210 /// Return the cost of this VPCurrentIterationPHIRecipe.
4212 VPCostContext &Ctx) const override {
4213 // For now, match the behavior of the legacy cost model.
4214 return 0;
4215 }
4216
4217 /// Returns true if the recipe only uses the first lane of operand \p Op.
4218 bool usesFirstLaneOnly(const VPValue *Op) const override {
4220 "Op must be an operand of the recipe");
4221 return true;
4222 }
4223
4224protected:
4225#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4226 /// Print the recipe.
4227 void printRecipe(raw_ostream &O, const Twine &Indent,
4228 VPSlotTracker &SlotTracker) const override;
4229#endif
4230};
4231
4232/// A Recipe for widening the canonical induction variable of the vector loop.
4233/// First operand is the canonical IV recipe, a second step operand (VF * Part)
4234/// is added during unrolling.
4236public:
4238 const VPIRFlags::WrapFlagsTy &Flags = {})
4239 : VPRecipeWithIRFlags(VPRecipeBase::VPWidenCanonicalIVSC, CanonicalIV,
4240 CanonicalIV->getType(), Flags) {}
4241
4242 ~VPWidenCanonicalIVRecipe() override = default;
4243
4245 auto *WideCanIV =
4247 if (VPValue *Step = getStepValue())
4248 WideCanIV->addPerPartStep(Step);
4249 return WideCanIV;
4250 }
4251
4252 VP_CLASSOF_IMPL(VPRecipeBase::VPWidenCanonicalIVSC)
4253
4254 void execute(VPTransformState &State) override {
4255 llvm_unreachable("Expected prior expansion of WidenCanonicalIV recipes");
4256 }
4257
4258 /// Return the cost of this VPWidenCanonicalIVPHIRecipe.
4260 VPCostContext &Ctx) const override {
4261 // TODO: Compute accurate cost after retiring the legacy cost model.
4262 return 0;
4263 }
4264
4265 /// Return the canonical IV being widened.
4269
4271 return getNumOperands() == 2 ? getOperand(1) : nullptr;
4272 }
4273
4274 /// Add the per-part step (VF * Part) used for unrolled parts.
4276 assert(Step->getScalarType() == getScalarType() &&
4277 "per-part step must have the same type as the canonical IV");
4278 VPUser::addOperand(Step);
4279 }
4280
4281protected:
4282#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4283 /// Print the recipe.
4284 void printRecipe(raw_ostream &O, const Twine &Indent,
4285 VPSlotTracker &SlotTracker) const override;
4286#endif
4287};
4288
4289/// A recipe for converting \p Current into \p Start + \p Current * \p Step.
4290/// FastMathFlags are derived from the \p FPBinOp in the case of FP inductions,
4291/// and the passed NoWrap \p Flags apply in the case of Ptr and Int inductions.
4293 /// Kind of the induction.
4295 /// If not nullptr, the floating point induction binary operator. Must be set
4296 /// for floating point inductions.
4297 const FPMathOperator *FPBinOp;
4298
4299public:
4301 const FPMathOperator *FPBinOp, VPValue *Start,
4302 VPValue *Current, VPValue *Step,
4303 const VPIRFlags::WrapFlagsTy &Flags = {})
4304 : VPRecipeWithIRFlags(VPRecipeBase::VPDerivedIVSC, {Start, Current, Step},
4305 Start->getScalarType(), Flags),
4306 Kind(Kind), FPBinOp(FPBinOp) {}
4307
4308 ~VPDerivedIVRecipe() override = default;
4309
4311 return new VPDerivedIVRecipe(Kind, FPBinOp, getStartValue(), getOperand(1),
4313 }
4314
4315 VP_CLASSOF_IMPL(VPRecipeBase::VPDerivedIVSC)
4316
4317 void execute(VPTransformState &State) override {
4318 llvm_unreachable("Expected prior expansion of this recipe");
4319 }
4320
4321 /// Return the cost of this VPDerivedIVRecipe.
4322 InstructionCost computeCost(ElementCount VF,
4323 VPCostContext &Ctx) const override;
4324
4325 VPValue *getStartValue() const { return getOperand(0); }
4326 VPValue *getIndex() const { return getOperand(1); }
4327 VPValue *getStepValue() const { return getOperand(2); }
4328 const FPMathOperator *getFPBinOp() const { return FPBinOp; }
4330
4331 /// Returns true if the recipe only uses the first lane of operand \p Op.
4332 bool usesFirstLaneOnly(const VPValue *Op) const override {
4334 "Op must be an operand of the recipe");
4335 return true;
4336 }
4337
4338protected:
4339#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4340 /// Print the recipe.
4341 void printRecipe(raw_ostream &O, const Twine &Indent,
4342 VPSlotTracker &SlotTracker) const override;
4343#endif
4344};
4345
4346/// A recipe for handling phi nodes of integer and floating-point inductions,
4347/// producing their scalar values. Before unrolling by UF the recipe represents
4348/// the VF*UF scalar values to be produced, or UF scalar values if only first
4349/// lane is used, and has 3 operands: IV, step and VF. Unrolling adds one extra
4350/// operand StartIndex to all unroll parts except part 0, as the recipe
4351/// represents the VF scalar values (this number of values is taken from
4352/// State.VF rather than from the VF operand) starting at IV + StartIndex.
4354 Instruction::BinaryOps InductionOpcode;
4355
4356public:
4360 : VPRecipeWithIRFlags(VPRecipeBase::VPScalarIVStepsSC, {IV, Step, VF},
4361 IV->getScalarType(), FMFs, DL),
4362 InductionOpcode(Opcode) {}
4363
4364 ~VPScalarIVStepsRecipe() override = default;
4365
4367 auto *NewR = new VPScalarIVStepsRecipe(
4368 getOperand(0), getOperand(1), getOperand(2), InductionOpcode,
4370 if (VPValue *StartIndex = getStartIndex())
4371 NewR->setStartIndex(StartIndex);
4372 return NewR;
4373 }
4374
4375 VP_CLASSOF_IMPL(VPRecipeBase::VPScalarIVStepsSC)
4376
4377 /// Generate the scalarized versions of the phi node as needed by their users.
4378 void execute(VPTransformState &State) override;
4379
4380 /// Return the cost of this VPScalarIVStepsRecipe.
4381 InstructionCost computeCost(ElementCount VF,
4382 VPCostContext &Ctx) const override;
4383
4384 VPValue *getStepValue() const { return getOperand(1); }
4385
4386 /// Return the number of scalars to produce per unroll part, used to compute
4387 /// StartIndex during unrolling.
4388 VPValue *getVFValue() const { return getOperand(2); }
4389
4390 /// Return the StartIndex, or null if known to be zero, valid only after
4391 /// unrolling.
4393 return getNumOperands() == 4 ? getOperand(3) : nullptr;
4394 }
4395
4396 /// Set or add the StartIndex operand.
4397 void setStartIndex(VPValue *StartIndex) {
4398 if (getNumOperands() == 4)
4399 setOperand(3, StartIndex);
4400 else
4401 addOperand(StartIndex);
4402 }
4403
4404 /// Returns true if this recipe produces scalar values for all VF lanes.
4405 bool doesGeneratePerAllLanes() const;
4406
4407 /// Returns true if the recipe only uses the first lane of operand \p Op.
4408 bool usesFirstLaneOnly(const VPValue *Op) const override {
4410 "Op must be an operand of the recipe");
4411 return true;
4412 }
4413
4414 Instruction::BinaryOps getInductionOpcode() const { return InductionOpcode; }
4415
4416protected:
4417#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4418 /// Print the recipe.
4419 void printRecipe(raw_ostream &O, const Twine &Indent,
4420 VPSlotTracker &SlotTracker) const override;
4421#endif
4422};
4423
4424/// CastInfo helper for casting from VPRecipeBase to a mixin class that is not
4425/// part of the VPRecipeBase class hierarchy (e.g. VPPhiAccessors,
4426/// VPIRMetadata).
4427namespace vpdetail {
4428template <typename VPMixin, typename... RecipeTys>
4430 : public DefaultDoCastIfPossible<VPMixin *, VPRecipeBase *,
4431 CastInfoMixinImpl<VPMixin, RecipeTys...>> {
4432 static_assert((std::is_base_of_v<VPMixin, RecipeTys> && ...),
4433 "Each type in RecipeTys must derive from VPMixin");
4434
4435 /// Used by isa.
4436 static bool isPossible(VPRecipeBase *R) { return isa<RecipeTys...>(R); }
4437
4438 /// Used by cast.
4439 static VPMixin *doCast(VPRecipeBase *R) {
4440 VPMixin *Out = nullptr;
4441 ((Out = dyn_cast<RecipeTys>(R)) || ...);
4442 assert(Out && "Illegal recipe for cast");
4443 return Out;
4444 }
4445 static VPMixin *castFailed() { return nullptr; }
4446};
4447} // namespace vpdetail
4448
4449/// Support casting from VPRecipeBase -> VPPhiAccessors.
4450template <>
4455
4456template <>
4461template <>
4463 : public ForwardToPointerCast<VPPhiAccessors, VPRecipeBase *,
4464 CastInfo<VPPhiAccessors, VPRecipeBase *>> {};
4465
4466/// Support casting from VPRecipeBase / VPUser -> VPWidenMemoryRecipe.
4467template <>
4472template <>
4477
4478/// Support casting from VPSingleDefRecipe -> VPWidenMemoryRecipe (loads only).
4479template <>
4483template <>
4488
4489/// Support casting from VPRecipeBase -> VPIRMetadata.
4490template <>
4497
4498template <>
4503template <>
4505 : public ForwardToPointerCast<VPIRMetadata, VPRecipeBase *,
4506 CastInfo<VPIRMetadata, VPRecipeBase *>> {};
4507
4508/// Support casting from VPSingleDefRecipe -> VPIRMetadata.
4509template <>
4512template <>
4517
4518/// VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph. It
4519/// holds a sequence of zero or more VPRecipe's each representing a sequence of
4520/// output IR instructions. All PHI-like recipes must come before any non-PHI
4521/// recipes.
4522class LLVM_ABI_FOR_TEST VPBasicBlock : public VPBlockBase {
4523 friend class VPlan;
4524
4525 /// Use VPlan::createVPBasicBlock to create VPBasicBlocks.
4526 VPBasicBlock(const Twine &Name = "", VPRecipeBase *Recipe = nullptr)
4527 : VPBasicBlock(VPBasicBlockSC, Name) {
4528 if (Recipe)
4529 appendRecipe(Recipe);
4530 }
4531
4532public:
4534
4535protected:
4536 /// The VPRecipes held in the order of output instructions to generate.
4538
4539 VPBasicBlock(VPBlockTy BlockSC, const Twine &Name = "")
4540 : VPBlockBase(BlockSC, Name.str()) {
4541 // Set the parent of the list's sentinel, so end() iterators know their
4542 // block.
4543 Recipes.end().getNodePtr()->setParent(this);
4544 }
4545
4546public:
4547 ~VPBasicBlock() override {
4548 while (!Recipes.empty())
4549 Recipes.pop_back();
4550 }
4551
4552 /// Instruction iterators...
4557
4558 //===--------------------------------------------------------------------===//
4559 /// Recipe iterator methods
4560 ///
4561 inline iterator begin() { return Recipes.begin(); }
4562 inline const_iterator begin() const { return Recipes.begin(); }
4563 inline iterator end() { return Recipes.end(); }
4564 inline const_iterator end() const { return Recipes.end(); }
4565
4566 inline reverse_iterator rbegin() { return Recipes.rbegin(); }
4567 inline const_reverse_iterator rbegin() const { return Recipes.rbegin(); }
4568 inline reverse_iterator rend() { return Recipes.rend(); }
4569 inline const_reverse_iterator rend() const { return Recipes.rend(); }
4570
4571 inline size_t size() const { return Recipes.size(); }
4572 inline bool empty() const { return Recipes.empty(); }
4573 inline const VPRecipeBase &front() const { return Recipes.front(); }
4574 inline VPRecipeBase &front() { return Recipes.front(); }
4575 inline const VPRecipeBase &back() const { return Recipes.back(); }
4576 inline VPRecipeBase &back() { return Recipes.back(); }
4577
4578 /// Returns a reference to the list of recipes.
4580
4581 /// Returns a pointer to a member of the recipe list.
4582 static RecipeListTy VPBasicBlock::*getSublistAccess(VPRecipeBase *) {
4583 return &VPBasicBlock::Recipes;
4584 }
4585
4586 /// Method to support type inquiry through isa, cast, and dyn_cast.
4587 static inline bool classof(const VPBlockBase *V) {
4588 return V->getVPBlockID() == VPBlockBase::VPBasicBlockSC ||
4589 V->getVPBlockID() == VPBlockBase::VPIRBasicBlockSC;
4590 }
4591
4592 void insert(VPRecipeBase *Recipe, iterator InsertPt) {
4593 assert(Recipe && "No recipe to append.");
4594 assert(!Recipe->getParent() && "Recipe already in VPlan");
4595 assert(InsertPt.getNodeParent() == this &&
4596 "Insertion position not in this VPBasicBlock");
4597 Recipe->setParent(this);
4598 Recipes.insert(InsertPt, Recipe);
4599 }
4600
4601 /// Augment the existing recipes of a VPBasicBlock with an additional
4602 /// \p Recipe as the last recipe.
4603 void appendRecipe(VPRecipeBase *Recipe) { insert(Recipe, end()); }
4604
4605 /// The method which generates the output IR instructions that correspond to
4606 /// this VPBasicBlock, thereby "executing" the VPlan.
4607 void execute(VPTransformState *State) override;
4608
4609 /// Return the cost of this VPBasicBlock.
4610 InstructionCost cost(ElementCount VF, VPCostContext &Ctx) override;
4611
4612 /// Return the position of the first non-phi node recipe in the block.
4613 iterator getFirstNonPhi();
4614
4615 /// Returns an iterator range over the PHI-like recipes in the block.
4619
4620 /// Split current block at \p SplitAt by inserting a new block between the
4621 /// current block and its successors and moving all recipes starting at
4622 /// SplitAt to the new block. Returns the new block.
4623 VPBasicBlock *splitAt(iterator SplitAt);
4624
4625 VPRegionBlock *getEnclosingLoopRegion();
4626 const VPRegionBlock *getEnclosingLoopRegion() const;
4627
4628#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4629 /// Print this VPBsicBlock to \p O, prefixing all lines with \p Indent. \p
4630 /// SlotTracker is used to print unnamed VPValue's using consequtive numbers.
4631 ///
4632 /// Note that the numbering is applied to the whole VPlan, so printing
4633 /// individual blocks is consistent with the whole VPlan printing.
4634 void print(raw_ostream &O, const Twine &Indent,
4635 VPSlotTracker &SlotTracker) const override;
4636 using VPBlockBase::print; // Get the print(raw_stream &O) version.
4637#endif
4638
4639 /// If the block has multiple successors, return the branch recipe terminating
4640 /// the block. If there are no or only a single successor, return nullptr;
4641 VPRecipeBase *getTerminator();
4642 const VPRecipeBase *getTerminator() const;
4643
4644 /// Returns true if the block is exiting it's parent region.
4645 bool isExiting() const;
4646
4647 /// Clone the current block and it's recipes, without updating the operands of
4648 /// the cloned recipes.
4649 VPBasicBlock *clone() override;
4650
4651 /// Returns the predecessor block at index \p Idx with the predecessors as per
4652 /// the corresponding plain CFG. If the block is an entry block to a region,
4653 /// the first predecessor is the single predecessor of a region, and the
4654 /// second predecessor is the exiting block of the region.
4655 const VPBasicBlock *getCFGPredecessor(unsigned Idx) const;
4656
4657protected:
4658 /// Execute the recipes in the IR basic block \p BB.
4659 void executeRecipes(VPTransformState *State, BasicBlock *BB);
4660
4661 /// Connect the VPBBs predecessors' in the VPlan CFG to the IR basic block
4662 /// generated for this VPBB.
4663 void connectToPredecessors(VPTransformState &State);
4664
4665private:
4666 /// Create an IR BasicBlock to hold the output instructions generated by this
4667 /// VPBasicBlock, and return it. Update the CFGState accordingly.
4668 BasicBlock *createEmptyBasicBlock(VPTransformState &State);
4669};
4670
4671inline const VPBasicBlock *
4673 return getAsRecipe()->getParent()->getCFGPredecessor(Idx);
4674}
4675
4676/// A special type of VPBasicBlock that wraps an existing IR basic block.
4677/// Recipes of the block get added before the first non-phi instruction in the
4678/// wrapped block.
4679/// Note: At the moment, VPIRBasicBlock can only be used to wrap VPlan's
4680/// preheader block.
4681class VPIRBasicBlock : public VPBasicBlock {
4682 friend class VPlan;
4683
4684 BasicBlock *IRBB;
4685
4686 /// Use VPlan::createVPIRBasicBlock to create VPIRBasicBlocks.
4687 VPIRBasicBlock(BasicBlock *IRBB)
4688 : VPBasicBlock(VPIRBasicBlockSC,
4689 (Twine("ir-bb<") + IRBB->getName() + Twine(">")).str()),
4690 IRBB(IRBB) {}
4691
4692public:
4693 ~VPIRBasicBlock() override = default;
4694
4695 static inline bool classof(const VPBlockBase *V) {
4696 return V->getVPBlockID() == VPBlockBase::VPIRBasicBlockSC;
4697 }
4698
4699 /// The method which generates the output IR instructions that correspond to
4700 /// this VPBasicBlock, thereby "executing" the VPlan.
4701 void execute(VPTransformState *State) override;
4702
4703 VPIRBasicBlock *clone() override;
4704
4705 BasicBlock *getIRBasicBlock() const { return IRBB; }
4706};
4707
4708/// Track information about the canonical IV and header mask of a loop region.
4709/// TODO: Have it also track the canonical IV increment, subject of NUW flag.
4711 /// VPRegionValue for the canonical IV, whose allocation is managed by
4712 /// VPCanonicalIVInfo.
4713 std::unique_ptr<VPRegionValue> CanIV;
4714
4715 /// Optional VPRegionValue for the header mask, set when tail folding.
4716 std::unique_ptr<VPRegionValue> HeaderMask;
4717
4718 /// Whether the increment of the canonical IV may unsigned wrap or not.
4719 bool HasNUW = true;
4720
4721public:
4723 : CanIV(std::make_unique<VPRegionValue>(Ty, DL, Region)) {}
4724
4725 VPRegionValue *getRegionValue() { return CanIV.get(); }
4726 const VPRegionValue *getRegionValue() const { return CanIV.get(); }
4727
4728 VPRegionValue *getHeaderMask() const { return HeaderMask.get(); }
4729
4730 /// Create the header mask for the region and return it. Must only be called
4731 /// when no header mask exists yet.
4733 assert(!HeaderMask && "Header mask already created");
4734 HeaderMask = std::make_unique<VPRegionValue>(
4735 Type::getInt1Ty(CanIV->getType()->getContext()), DebugLoc::getUnknown(),
4736 CanIV->getDefiningRegion());
4737 return HeaderMask.get();
4738 }
4739
4740 bool hasNUW() const { return HasNUW; }
4741
4742 void clearNUW() { HasNUW = false; }
4743};
4744
4745/// VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks
4746/// which form a Single-Entry-Single-Exiting subgraph of the output IR CFG.
4747/// A VPRegionBlock may indicate that its contents are to be replicated several
4748/// times. This is designed to support predicated scalarization, in which a
4749/// scalar if-then code structure needs to be generated VF * UF times. Having
4750/// this replication indicator helps to keep a single model for multiple
4751/// candidate VF's. The actual replication takes place only once the desired VF
4752/// and UF have been determined.
4753class LLVM_ABI_FOR_TEST VPRegionBlock : public VPBlockBase {
4754 friend class VPlan;
4755
4756 /// Hold the Single Entry of the SESE region modelled by the VPRegionBlock.
4757 VPBlockBase *Entry;
4758
4759 /// Hold the Single Exiting block of the SESE region modelled by the
4760 /// VPRegionBlock.
4761 VPBlockBase *Exiting;
4762
4763 /// Holds the Canonical IV of the loop region along with additional
4764 /// information. If CanIVInfo is nullptr, the region is a replicating region.
4765 /// Loop regions retain their canonical IVs until they are dissolved, even if
4766 /// the canonical IV has no users.
4767 std::unique_ptr<VPCanonicalIVInfo> CanIVInfo;
4768
4769 /// Use VPlan::createLoopRegion() and VPlan::createReplicateRegion() to create
4770 /// VPRegionBlocks.
4771 VPRegionBlock(VPBlockBase *Entry, VPBlockBase *Exiting,
4772 const std::string &Name = "")
4773 : VPBlockBase(VPRegionBlockSC, Name), Entry(Entry), Exiting(Exiting) {
4774 if (Entry) {
4775 assert(!Entry->hasPredecessors() && "Entry block has predecessors.");
4776 assert(Exiting && "Must also pass Exiting if Entry is passed.");
4777 assert(!Exiting->hasSuccessors() && "Exit block has successors.");
4778 Entry->setParent(this);
4779 Exiting->setParent(this);
4780 }
4781 }
4782
4783 VPRegionBlock(Type *CanIVTy, DebugLoc DL, VPBlockBase *Entry,
4784 VPBlockBase *Exiting, const std::string &Name = "")
4785 : VPRegionBlock(Entry, Exiting, Name) {
4786 CanIVInfo = std::make_unique<VPCanonicalIVInfo>(CanIVTy, DL, this);
4787 }
4788
4789public:
4790 ~VPRegionBlock() override = default;
4791
4792 /// Method to support type inquiry through isa, cast, and dyn_cast.
4793 static inline bool classof(const VPBlockBase *V) {
4794 return V->getVPBlockID() == VPBlockBase::VPRegionBlockSC;
4795 }
4796
4797 const VPBlockBase *getEntry() const { return Entry; }
4798 VPBlockBase *getEntry() { return Entry; }
4799
4800 /// Set \p EntryBlock as the entry VPBlockBase of this VPRegionBlock. \p
4801 /// EntryBlock must have no predecessors.
4802 void setEntry(VPBlockBase *EntryBlock) {
4803 assert(!EntryBlock->hasPredecessors() &&
4804 "Entry block cannot have predecessors.");
4805 Entry = EntryBlock;
4806 EntryBlock->setParent(this);
4807 }
4808
4809 const VPBlockBase *getExiting() const { return Exiting; }
4810 VPBlockBase *getExiting() { return Exiting; }
4811
4812 /// Set \p ExitingBlock as the exiting VPBlockBase of this VPRegionBlock. \p
4813 /// ExitingBlock must have no successors.
4814 void setExiting(VPBlockBase *ExitingBlock) {
4815 assert(!ExitingBlock->hasSuccessors() &&
4816 "Exit block cannot have successors.");
4817 Exiting = ExitingBlock;
4818 ExitingBlock->setParent(this);
4819 }
4820
4821 /// Returns the pre-header VPBasicBlock of the loop region.
4823 assert(!isReplicator() && "should only get pre-header of loop regions");
4824 return getSinglePredecessor()->getExitingBasicBlock();
4825 }
4826
4827 /// An indicator whether this region is to generate multiple replicated
4828 /// instances of output IR corresponding to its VPBlockBases.
4829 bool isReplicator() const { return !CanIVInfo; }
4830
4831 /// Return the VPBranchOnMaskRecipe from the entry block of this replicating
4832 /// region.
4833 const VPBranchOnMaskRecipe *getEntryBranchOnMask() const;
4835 return const_cast<VPBranchOnMaskRecipe *>(
4836 static_cast<const VPRegionBlock *>(this)->getEntryBranchOnMask());
4837 }
4838
4839 /// The method which generates the output IR instructions that correspond to
4840 /// this VPRegionBlock, thereby "executing" the VPlan.
4841 void execute(VPTransformState *State) override;
4842
4843 // Return the cost of this region.
4844 InstructionCost cost(ElementCount VF, VPCostContext &Ctx) override;
4845
4846#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4847 /// Print this VPRegionBlock to \p O (recursively), prefixing all lines with
4848 /// \p Indent. \p SlotTracker is used to print unnamed VPValue's using
4849 /// consequtive numbers.
4850 ///
4851 /// Note that the numbering is applied to the whole VPlan, so printing
4852 /// individual regions is consistent with the whole VPlan printing.
4853 void print(raw_ostream &O, const Twine &Indent,
4854 VPSlotTracker &SlotTracker) const override;
4855 using VPBlockBase::print; // Get the print(raw_stream &O) version.
4856#endif
4857
4858 /// Clone all blocks in the single-entry single-exit region of the block and
4859 /// their recipes without updating the operands of the cloned recipes.
4860 VPRegionBlock *clone() override;
4861
4862 /// Remove the current region from its VPlan, connecting its predecessor to
4863 /// its entry, and its exiting block to its successor.
4864 void dissolveToCFGLoop();
4865
4866 /// Get the canonical IV increment instruction if it exists. Otherwise, create
4867 /// a new increment before the terminator and return it. The canonical IV
4868 /// increment is subject to DCE if unused, unlike the canonical IV itself.
4869 VPInstruction *getOrCreateCanonicalIVIncrement();
4870
4871 /// Return the canonical induction variable of the region, null for
4872 /// replicating regions.
4874 return CanIVInfo ? CanIVInfo->getRegionValue() : nullptr;
4875 }
4877 return CanIVInfo ? CanIVInfo->getRegionValue() : nullptr;
4878 }
4879
4880 /// Return the type of the canonical IV for loop regions.
4882 return CanIVInfo->getRegionValue()->getType();
4883 }
4884
4885 /// Return the header mask of the region, or null if not set.
4887 return CanIVInfo ? CanIVInfo->getHeaderMask() : nullptr;
4888 }
4889
4890 /// Return the header mask if it exists and is used, or null otherwise. The
4891 /// mask is materialized into concrete recipes only after costing, so cost and
4892 /// codegen accounting sites use this to skip an unused mask.
4894 VPRegionValue *HeaderMask = getHeaderMask();
4895 return HeaderMask && HeaderMask->getNumUsers() > 0 ? HeaderMask : nullptr;
4896 }
4897
4898 /// Create the header mask for the region and return it. Must only be called
4899 /// on loop regions that don't already have a header mask.
4901 assert(CanIVInfo && "Can only create header mask for loop regions");
4902 return CanIVInfo->createHeaderMask();
4903 }
4904
4905 /// Return the region values of the loop region (canonical IV, header mask)
4906 /// or an empty vector for replicate regions.
4908 if (!CanIVInfo)
4909 return {};
4910 SmallVector<VPRegionValue *, 2> R = {CanIVInfo->getRegionValue()};
4911 if (auto *HM = CanIVInfo->getHeaderMask())
4912 R.push_back(HM);
4913 return R;
4914 }
4915
4916 /// Indicates if NUW is set for the canonical IV increment, for loop regions.
4917 bool hasCanonicalIVNUW() const { return CanIVInfo->hasNUW(); }
4918
4919 /// Unsets NUW for the canonical IV increment \p Increment, for loop regions.
4921 assert(Increment && "Must provide increment to clear");
4922 Increment->dropPoisonGeneratingFlags();
4923 CanIVInfo->clearNUW();
4924 }
4925};
4926
4928 return getParent()->getParent();
4929}
4930
4932 return getParent()->getParent();
4933}
4934
4935/// VPlan models a candidate for vectorization, encoding various decisions take
4936/// to produce efficient output IR, including which branches, basic-blocks and
4937/// output IR instructions to generate, and their cost. VPlan holds a
4938/// Hierarchical-CFG of VPBasicBlocks and VPRegionBlocks rooted at an Entry
4939/// VPBasicBlock.
4940class VPlan {
4941 friend class VPlanPrinter;
4942 friend class VPSlotTracker;
4943
4944 /// VPBasicBlock corresponding to the original preheader. Used to place
4945 /// VPExpandSCEV recipes for expressions used during VPlan execution.
4946 /// When this VPlan is used for the epilogue vector loop, the entry models the
4947 /// main plan's entry and its edges move to the epilogue iteration check (see
4948 /// VPlanTransforms::modelGeneratedMainLoopBlocks).
4949 VPBasicBlock *Entry;
4950
4951 /// VPIRBasicBlock wrapping the header of the original scalar loop.
4952 VPIRBasicBlock *ScalarHeader;
4953
4954 /// Immutable list of VPIRBasicBlocks wrapping the exit blocks of the original
4955 /// scalar loop. Note that some exit blocks may be unreachable at the moment,
4956 /// e.g. if the scalar epilogue always executes.
4958
4959 /// Holds the VFs applicable to this VPlan.
4961
4962 /// Holds the UFs applicable to this VPlan. If empty, the VPlan is valid for
4963 /// any UF.
4965
4966 /// Holds the name of the VPlan, for printing.
4967 std::string Name;
4968
4969 /// Represents the trip count of the original loop, for folding
4970 /// the tail.
4971 VPValue *TripCount = nullptr;
4972
4973 /// Represents the vector trip count.
4974 VPSymbolicValue VectorTripCount;
4975
4976 /// Represents the vectorization factor of the loop.
4977 VPSymbolicValue VF;
4978
4979 /// Represents the unroll factor of the loop.
4980 VPSymbolicValue UF;
4981
4982 /// Represents the loop-invariant VF * UF of the vector loop region.
4983 VPSymbolicValue VFxUF;
4984
4985 /// Contains all the external definitions created for this VPlan, as a mapping
4986 /// from IR Values to VPIRValues.
4988
4989 /// Blocks allocated and owned by the VPlan. They will be deleted once the
4990 /// VPlan is destroyed.
4991 SmallVector<VPBlockBase *> CreatedBlocks;
4992
4993 /// Construct a VPlan with \p Entry to the plan and with \p ScalarHeader
4994 /// wrapping the original header of the scalar loop. The vector loop will have
4995 /// index type \p IdxTy.
4996 VPlan(VPBasicBlock *Entry, VPIRBasicBlock *ScalarHeader, Type *IdxTy)
4997 : Entry(Entry), ScalarHeader(ScalarHeader), VectorTripCount(IdxTy),
4998 VF(IdxTy), UF(IdxTy), VFxUF(IdxTy) {
4999 Entry->setPlan(this);
5000 assert(ScalarHeader->getNumSuccessors() == 0 &&
5001 "scalar header must be a leaf node");
5002 }
5003
5004public:
5005 /// Construct a VPlan for \p L. This will create VPIRBasicBlocks wrapping the
5006 /// original preheader and scalar header of \p L, to be used as entry and
5007 /// scalar header blocks of the new VPlan. The vector loop will have index
5008 /// type \p IdxTy.
5009 VPlan(Loop *L, Type *IdxTy);
5010
5011 /// Construct a VPlan with a new VPBasicBlock as entry, a VPIRBasicBlock
5012 /// wrapping \p ScalarHeaderBB and vector loop index of type \p IdxTy.
5013 VPlan(BasicBlock *ScalarHeaderBB, Type *IdxTy)
5014 : VectorTripCount(IdxTy), VF(IdxTy), UF(IdxTy), VFxUF(IdxTy) {
5015 setEntry(createVPBasicBlock("preheader"));
5016 ScalarHeader = createVPIRBasicBlock(ScalarHeaderBB);
5017 }
5018
5020
5022 Entry = VPBB;
5023 VPBB->setPlan(this);
5024 }
5025
5026 /// Generate the IR code for this VPlan.
5027 void execute(VPTransformState *State);
5028
5029 /// Return the cost of this plan.
5031
5032 VPBasicBlock *getEntry() { return Entry; }
5033 const VPBasicBlock *getEntry() const { return Entry; }
5034
5035 /// Returns the preheader of the vector loop region, if one exists, or null
5036 /// otherwise.
5038 const VPRegionBlock *VectorRegion = getVectorLoopRegion();
5039 return VectorRegion
5040 ? cast<VPBasicBlock>(VectorRegion->getSinglePredecessor())
5041 : nullptr;
5042 }
5043
5044 /// Returns the VPRegionBlock of the vector loop.
5047
5048 /// Returns true if this VPlan is for an outer loop, i.e., its vector
5049 /// loop region contains a nested loop region.
5050 LLVM_ABI_FOR_TEST bool isOuterLoop() const;
5051
5052 /// Returns true if the vector loop region is tail-folded.
5053 bool hasTailFolded() const {
5054 const VPRegionBlock *LoopRegion = getVectorLoopRegion();
5055 return LoopRegion && LoopRegion->getHeaderMask();
5056 }
5057
5058 /// Returns true if the plan requires a scalar epilogue after the vector
5059 /// loop. Must be called before removeBranchOnConst.
5061 const VPBasicBlock *MiddleVPBB = getMiddleBlock();
5062 return MiddleVPBB->getSingleSuccessor() == getScalarPreheader();
5063 }
5064
5065 /// Returns the 'middle' block of the plan, that is the block that selects
5066 /// whether to execute the scalar tail loop or the exit block from the loop
5067 /// latch. If there is an early exit from the vector loop, the middle block
5068 /// conceptully has the early exit block as third successor, split accross 2
5069 /// VPBBs. In that case, the second VPBB selects whether to execute the scalar
5070 /// tail loop or the exit block. If the scalar tail loop or exit block are
5071 /// known to always execute, the middle block may branch directly to that
5072 /// block. This function cannot be called once the vector loop region has been
5073 /// removed.
5075 VPRegionBlock *LoopRegion = getVectorLoopRegion();
5076 assert(
5077 LoopRegion &&
5078 "cannot call the function after vector loop region has been removed");
5079 // The middle block is always the last successor of the region.
5080 return cast<VPBasicBlock>(LoopRegion->getSuccessors().back());
5081 }
5082
5084 return const_cast<VPlan *>(this)->getMiddleBlock();
5085 }
5086
5087 /// Return the VPBasicBlock for the preheader of the scalar loop.
5090 getScalarHeader()->getSinglePredecessor());
5091 }
5092
5093 /// Return the VPIRBasicBlock wrapping the header of the scalar loop.
5094 VPIRBasicBlock *getScalarHeader() const { return ScalarHeader; }
5095
5096 /// Return an ArrayRef containing VPIRBasicBlocks wrapping the exit blocks of
5097 /// the original scalar loop.
5098 ArrayRef<VPIRBasicBlock *> getExitBlocks() const { return ExitBlocks; }
5099
5100 /// Returns true if \p VPBB is an exit block.
5101 bool isExitBlock(VPBlockBase *VPBB);
5102
5103 /// The trip count of the original loop.
5105 assert(TripCount && "trip count needs to be set before accessing it");
5106 return TripCount;
5107 }
5108
5109 /// Set the trip count assuming it is currently null; if it is not - use
5110 /// resetTripCount().
5111 void setTripCount(VPValue *NewTripCount) {
5112 assert(!TripCount && NewTripCount && "TripCount should not be set yet.");
5113 TripCount = NewTripCount;
5114 }
5115
5116 /// Resets the trip count for the VPlan. The caller must make sure all uses of
5117 /// the original trip count have been replaced.
5118 void resetTripCount(VPValue *NewTripCount) {
5119 assert(TripCount && NewTripCount && TripCount->user_empty() &&
5120 "TripCount must be set when resetting");
5121 TripCount = NewTripCount;
5122 }
5123
5124 /// The vector trip count.
5125 VPSymbolicValue &getVectorTripCount() { return VectorTripCount; }
5126
5127 /// Returns the VF of the vector loop region.
5128 VPSymbolicValue &getVF() { return VF; };
5129 const VPSymbolicValue &getVF() const { return VF; };
5130
5131 /// Returns the UF of the vector loop region.
5132 VPSymbolicValue &getUF() { return UF; };
5133
5134 /// Returns VF * UF of the vector loop region.
5135 VPSymbolicValue &getVFxUF() { return VFxUF; }
5136
5139 }
5140
5141 const DataLayout &getDataLayout() const {
5143 }
5144
5147 }
5148
5149 void addVF(ElementCount VF) { VFs.insert(VF); }
5150
5152 assert(hasVF(VF) && "Cannot set VF not already in plan");
5153 VFs.clear();
5154 VFs.insert(VF);
5155 }
5156
5157 /// Remove \p VF from the plan.
5159 assert(hasVF(VF) && "tried to remove VF not present in plan");
5160 VFs.remove(VF);
5161 }
5162
5163 bool hasVF(ElementCount VF) const { return VFs.count(VF); }
5164 bool hasScalableVF() const {
5165 return any_of(VFs, [](ElementCount VF) { return VF.isScalable(); });
5166 }
5167
5168 /// Returns an iterator range over all VFs of the plan.
5171 return VFs;
5172 }
5173
5174 /// Returns the single VF of the plan, asserting that the plan has exactly
5175 /// one VF.
5177 assert(VFs.size() == 1 && "expected plan with single VF");
5178 return VFs[0];
5179 }
5180
5181 bool hasScalarVFOnly() const {
5182 bool HasScalarVFOnly = VFs.size() == 1 && VFs[0].isScalar();
5183 assert(HasScalarVFOnly == hasVF(ElementCount::getFixed(1)) &&
5184 "Plan with scalar VF should only have a single VF");
5185 return HasScalarVFOnly;
5186 }
5187
5188 bool hasUF(unsigned UF) const { return UFs.empty() || UFs.contains(UF); }
5189
5190 /// Returns the concrete UF of the plan, after unrolling.
5191 unsigned getConcreteUF() const {
5192 assert(UFs.size() == 1 && "Expected a single UF");
5193 return UFs[0];
5194 }
5195
5196 void setUF(unsigned UF) {
5197 assert(hasUF(UF) && "Cannot set the UF not already in plan");
5198 UFs.clear();
5199 UFs.insert(UF);
5200 }
5201
5202 /// Returns true if the VPlan already has been unrolled, i.e. it has a single
5203 /// concrete UF.
5204 bool isUnrolled() const { return UFs.size() == 1; }
5205
5206 /// Return a string with the name of the plan and the applicable VFs and UFs.
5207 std::string getName() const;
5208
5209 void setName(const Twine &newName) { Name = newName.str(); }
5210
5211 /// Gets the live-in VPIRValue for \p V or adds a new live-in (if none exists
5212 /// yet) for \p V.
5214 assert(V && "Trying to get or add the VPIRValue of a null Value");
5215 auto [It, Inserted] = LiveIns.try_emplace(V);
5216 if (Inserted) {
5217 if (auto *CI = dyn_cast<ConstantInt>(V))
5218 It->second = new VPConstantInt(CI);
5219 else
5220 It->second = new VPIRValue(V);
5221 }
5222
5223 assert(isa<VPIRValue>(It->second) &&
5224 "Only VPIRValues should be in mapping");
5225 return It->second;
5226 }
5228 assert(V && "Trying to get or add the VPIRValue of a null VPIRValue");
5229 return getOrAddLiveIn(V->getValue());
5230 }
5231
5232 /// Return a VPIRValue wrapping i1 true.
5233 VPIRValue *getTrue() { return getConstantInt(1, 1); }
5234
5235 /// Return a VPIRValue wrapping i1 false.
5236 VPIRValue *getFalse() { return getConstantInt(1, 0); }
5237
5238 /// Return a VPIRValue wrapping the null value of type \p Ty.
5239 VPIRValue *getZero(Type *Ty) { return getConstantInt(Ty, 0); }
5240
5241 /// Return a VPIRValue wrapping the AllOnes value of type \p Ty.
5243 return getConstantInt(APInt::getAllOnes(Ty->getIntegerBitWidth()));
5244 }
5245
5246 /// Return a VPIRValue wrapping a ConstantInt with the given type and value.
5247 VPIRValue *getConstantInt(Type *Ty, uint64_t Val, bool IsSigned = false) {
5248 return getOrAddLiveIn(ConstantInt::get(Ty, Val, IsSigned));
5249 }
5250
5251 /// Return a VPIRValue wrapping a ConstantInt with the given bitwidth and
5252 /// value.
5254 bool IsSigned = false) {
5255 return getConstantInt(APInt(BitWidth, Val, IsSigned));
5256 }
5257
5258 /// Return a VPIRValue wrapping a ConstantInt with the given APInt value.
5260 return getOrAddLiveIn(ConstantInt::get(getContext(), Val));
5261 }
5262
5263 /// Return a VPIRValue wrapping a poison value of type \p Ty.
5265 return getOrAddLiveIn(PoisonValue::get(Ty));
5266 }
5267
5268 /// Return the live-in VPIRValue for \p V, if there is one or nullptr
5269 /// otherwise.
5270 VPIRValue *getLiveIn(Value *V) const { return LiveIns.lookup(V); }
5271
5272 /// Return the list of live-in VPValues available in the VPlan.
5273 auto getLiveIns() const { return LiveIns.values(); }
5274
5275#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5276 /// Print the live-ins of this VPlan to \p O.
5277 void printLiveIns(raw_ostream &O) const;
5278
5279 /// Print this VPlan to \p O.
5280 LLVM_ABI_FOR_TEST void print(raw_ostream &O) const;
5281
5282 /// Print this VPlan in DOT format to \p O.
5283 LLVM_ABI_FOR_TEST void printDOT(raw_ostream &O) const;
5284
5285 /// Dump the plan to stderr (for debugging).
5286 LLVM_DUMP_METHOD void dump() const;
5287#endif
5288
5289 /// Clone the current VPlan, update all VPValues of the new VPlan and cloned
5290 /// recipes to refer to the clones, and return it.
5292
5293 /// Create a new VPBasicBlock with \p Name and containing \p Recipe if
5294 /// present. The returned block is owned by the VPlan and deleted once the
5295 /// VPlan is destroyed.
5297 VPRecipeBase *Recipe = nullptr) {
5298 auto *VPB = new VPBasicBlock(Name, Recipe);
5299 VPB->setPlan(this);
5300 VPB->setNumber(CreatedBlocks.size());
5301 CreatedBlocks.push_back(VPB);
5302 return VPB;
5303 }
5304
5305 /// Create a new loop region with a canonical IV using \p CanIVTy and
5306 /// \p DL. Use \p Name as the region's name and set entry and exiting blocks
5307 /// to \p Entry and \p Exiting respectively, if provided. The returned block
5308 /// is owned by the VPlan and deleted once the VPlan is destroyed.
5310 const std::string &Name = "",
5311 VPBlockBase *Entry = nullptr,
5312 VPBlockBase *Exiting = nullptr) {
5313 auto *VPB = new VPRegionBlock(CanIVTy, DL, Entry, Exiting, Name);
5314 VPB->setPlan(this);
5315 VPB->setNumber(CreatedBlocks.size());
5316 CreatedBlocks.push_back(VPB);
5317 return VPB;
5318 }
5319
5320 /// Create a new replicate region with \p Entry, \p Exiting and \p Name. The
5321 /// returned block is owned by the VPlan and deleted once the VPlan is
5322 /// destroyed.
5324 const std::string &Name = "") {
5325 auto *VPB = new VPRegionBlock(Entry, Exiting, Name);
5326 VPB->setPlan(this);
5327 VPB->setNumber(CreatedBlocks.size());
5328 CreatedBlocks.push_back(VPB);
5329 return VPB;
5330 }
5331
5332 /// Create a VPIRBasicBlock wrapping \p IRBB, but do not create
5333 /// VPIRInstructions wrapping the instructions in t\p IRBB. The returned
5334 /// block is owned by the VPlan and deleted once the VPlan is destroyed.
5336
5337 /// Create a VPIRBasicBlock from \p IRBB containing VPIRInstructions for all
5338 /// instructions in \p IRBB, except its terminator which is managed by the
5339 /// successors of the block in VPlan. The returned block is owned by the VPlan
5340 /// and deleted once the VPlan is destroyed.
5342
5343 unsigned getMaxBlockNumber() const { return CreatedBlocks.size(); }
5344
5345 /// Returns true if the VPlan is based on a loop with an early exit.
5346 bool hasEarlyExit() const {
5347 unsigned NumExitPredecessors =
5348 sum_of(map_range(ExitBlocks, [](VPIRBasicBlock *EB) {
5349 return EB->getNumPredecessors();
5350 }));
5351
5352 // If the scalar preheader executes unconditionally, there's no branch from
5353 // middle block to any exit. If there is any edge to an exit block
5354 // remaining, it must be an early exit.
5355 VPBasicBlock *ScalarPH = getScalarPreheader();
5356 VPBlockBase *ScalarPHPred =
5357 ScalarPH ? ScalarPH->getSinglePredecessor() : nullptr;
5358 if (ScalarPHPred && ScalarPHPred->getNumSuccessors() == 1)
5359 return NumExitPredecessors >= 1;
5360
5361 // Otherwise there must be at least 2 edges to exit blocks (from the middle
5362 // block and the early exiting edge).
5363 return NumExitPredecessors > 1;
5364 }
5365
5366 /// Returns true if the scalar tail may execute after the vector loop, i.e.
5367 /// if the middle block is a predecessor of the scalar preheader. Note that
5368 /// this relies on unneeded branches to the scalar tail loop being removed.
5369 bool hasScalarTail() const {
5370 auto *ScalarPH = getScalarPreheader();
5371 return ScalarPH &&
5372 is_contained(ScalarPH->getPredecessors(), getMiddleBlock());
5373 }
5374
5375 /// The type of the canonical induction variable of the vector loop.
5376 Type *getIndexType() const { return VF.getType(); }
5377};
5378
5379#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5380inline raw_ostream &operator<<(raw_ostream &OS, const VPlan &Plan) {
5381 Plan.print(OS);
5382 return OS;
5383}
5384#endif
5385
5386} // end namespace llvm
5387
5388#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:4167
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPActiveLaneMaskPHIRecipe(VPValue *StartMask, DebugLoc DL)
Definition VPlan.h:4161
~VPActiveLaneMaskPHIRecipe() override=default
VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph.
Definition VPlan.h:4522
VPRecipeBase::RecipeListTy RecipeListTy
Definition VPlan.h:4533
RecipeListTy::const_iterator const_iterator
Definition VPlan.h:4554
void appendRecipe(VPRecipeBase *Recipe)
Augment the existing recipes of a VPBasicBlock with an additional Recipe as the last recipe.
Definition VPlan.h:4603
RecipeListTy::const_reverse_iterator const_reverse_iterator
Definition VPlan.h:4556
RecipeListTy::iterator iterator
Instruction iterators...
Definition VPlan.h:4553
RecipeListTy & getRecipeList()
Returns a reference to the list of recipes.
Definition VPlan.h:4579
iterator end()
Definition VPlan.h:4563
iterator begin()
Recipe iterator methods.
Definition VPlan.h:4561
RecipeListTy::reverse_iterator reverse_iterator
Definition VPlan.h:4555
iterator_range< iterator > phis()
Returns an iterator range over the PHI-like recipes in the block.
Definition VPlan.h:4616
iterator getFirstNonPhi()
Return the position of the first non-phi node recipe in the block.
Definition VPlan.cpp:228
~VPBasicBlock() override
Definition VPlan.h:4547
const_reverse_iterator rbegin() const
Definition VPlan.h:4567
reverse_iterator rend()
Definition VPlan.h:4568
RecipeListTy Recipes
The VPRecipes held in the order of output instructions to generate.
Definition VPlan.h:4537
VPRecipeBase & back()
Definition VPlan.h:4576
const VPRecipeBase & front() const
Definition VPlan.h:4573
const_iterator begin() const
Definition VPlan.h:4562
VPRecipeBase & front()
Definition VPlan.h:4574
const VPRecipeBase & back() const
Definition VPlan.h:4575
void insert(VPRecipeBase *Recipe, iterator InsertPt)
Definition VPlan.h:4592
bool empty() const
Definition VPlan.h:4572
const_iterator end() const
Definition VPlan.h:4564
static bool classof(const VPBlockBase *V)
Method to support type inquiry through isa, cast, and dyn_cast.
Definition VPlan.h:4587
static RecipeListTy VPBasicBlock::* getSublistAccess(VPRecipeBase *)
Returns a pointer to a member of the recipe list.
Definition VPlan.h:4582
reverse_iterator rbegin()
Definition VPlan.h:4566
friend class VPlan
Definition VPlan.h:4523
size_t size() const
Definition VPlan.h:4571
const_reverse_iterator rend() const
Definition VPlan.h:4569
VPBasicBlock(VPBlockTy BlockSC, const Twine &Name="")
Definition VPlan.h:4539
VPValue * getIncomingValue(unsigned Idx) const
Return incoming value number Idx.
Definition VPlan.h:3087
VPValue * getMask(unsigned Idx) const
Return mask number Idx.
Definition VPlan.h:3092
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:3046
unsigned getNumIncomingValues() const
Return the number of incoming values, taking into account when normalized the first incoming value wi...
Definition VPlan.h:3082
void execute(VPTransformState &State) override
The method which generates the output IR instructions that correspond to this VPRecipe,...
Definition VPlan.h:3104
VPBlendRecipe * cloneWithOperands(ArrayRef< VPValue * > NewOperands)
Definition VPlan.h:3069
VPBlendRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:3067
void setMask(unsigned Idx, VPValue *V)
Set mask number Idx to V.
Definition VPlan.h:3098
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:3078
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:3591
VPBranchOnMaskRecipe(VPValue *BlockInMask, DebugLoc DL, const VPIRMetadata &Metadata={})
Definition VPlan.h:3593
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
Definition VPlan.h:3614
VPBranchOnMaskRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:3598
bool usesScalars(const VPValue *Op) const override
Returns true if the recipe uses scalars of operand Op.
Definition VPlan.h:3622
VPlan-based builder utility similar to IRBuilder.
VPRegionValue * createHeaderMask()
Create the header mask for the region and return it.
Definition VPlan.h:4732
VPRegionValue * getHeaderMask() const
Definition VPlan.h:4728
VPRegionValue * getRegionValue()
Definition VPlan.h:4725
VPCanonicalIVInfo(Type *Ty, DebugLoc DL, VPRegionBlock *Region)
Definition VPlan.h:4722
const VPRegionValue * getRegionValue() const
Definition VPlan.h:4726
bool hasNUW() const
Definition VPlan.h:4740
A recipe for handling scalar conditional induction PHIs.
Definition VPlan.h:2986
const SCEV * getStepSCEV() const
Returns the conditional induction step SCEV expression.
Definition VPlan.h:3004
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:3006
PHINode * getPHINode() const
Returns the underlying PHINode.
Definition VPlan.h:3001
VPConditionalInductionPHIRecipe(PHINode &Phi, VPValue &Start, VPValue &BackedgeValue, const SCEV *StepSCEV)
Definition VPlan.h:2990
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:3031
void execute(VPTransformState &) override
Generate the phi nodes.
Definition VPlan.h:3017
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:3013
VPCurrentIterationPHIRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:4199
VPCurrentIterationPHIRecipe(VPValue *StartIV, DebugLoc DL)
Definition VPlan.h:4193
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPCurrentIterationPHIRecipe.
Definition VPlan.h:4211
void execute(VPTransformState &State) override
Generate the phi nodes.
Definition VPlan.h:4205
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:4218
~VPCurrentIterationPHIRecipe() override=default
InductionDescriptor::InductionKind getInductionKind() const
Definition VPlan.h:4329
VPValue * getIndex() const
Definition VPlan.h:4326
const FPMathOperator * getFPBinOp() const
Definition VPlan.h:4328
VPDerivedIVRecipe(InductionDescriptor::InductionKind Kind, const FPMathOperator *FPBinOp, VPValue *Start, VPValue *Current, VPValue *Step, const VPIRFlags::WrapFlagsTy &Flags={})
Definition VPlan.h:4300
VPValue * getStepValue() const
Definition VPlan.h:4327
void execute(VPTransformState &State) override
The method which generates the output IR instructions that correspond to this VPRecipe,...
Definition VPlan.h:4317
VPDerivedIVRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:4310
~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:4332
VPValue * getStartValue() const
Definition VPlan.h:4325
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:4134
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:4139
VPExpandSCEVRecipe(const SCEV *Expr, bool ExpandInIR=false)
bool expandInIR() const
Definition VPlan.h:4147
const SCEV * getSCEV() const
Definition VPlan.h:4145
VPExpandSCEVRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:4128
~VPExpandSCEVRecipe() override=default
void execute(VPTransformState &State) override
Method for generating code, must not be called as this recipe is abstract.
Definition VPlan.h:3768
bool isVectorToScalar() const
Returns true if this VPExpressionRecipe produces a single scalar.
VPExpressionRecipe(VPWidenCastRecipe *Ext, VPWidenRecipe *Neg, VPReductionRecipe *Red)
Definition VPlan.h:3684
VPExpressionRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:3737
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:3725
ExpressionTypes getExpressionType() const
Returns the expression type of this recipe.
Definition VPlan.h:3760
VPExpressionRecipe(VPWidenCastRecipe *Ext, VPReductionRecipe *Red)
Definition VPlan.h:3682
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:3700
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:3704
void printRecipe(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
unsigned getVFScaleFactor() const
Definition VPlan.h:3762
VPExpressionRecipe(VPWidenRecipe *Mul, VPReductionRecipe *Red)
Definition VPlan.h:3698
A pure virtual base class for all recipes modeling header phis, including phis for first order recurr...
Definition VPlan.h:2476
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:2483
void addBackedgeValue(VPValue *V)
Add V as the incoming value from the loop backedge.
Definition VPlan.h:2525
static bool classof(const VPSingleDefRecipe *R)
Definition VPlan.h:2496
static bool classof(const VPValue *V)
Definition VPlan.h:2493
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:2478
virtual VPValue * getBackedgeValue()
Returns the incoming value from the loop backedge.
Definition VPlan.h:2519
void setBackedgeValue(VPValue *V)
Update the incoming value from the loop backedge.
Definition VPlan.h:2522
VPValue * getStartValue()
Returns the start value of the phi, if one is set.
Definition VPlan.h:2508
void setStartValue(VPValue *V)
Update the start value of the recipe.
Definition VPlan.h:2516
static bool classof(const VPRecipeBase *R)
Method to support type inquiry through isa, cast, and dyn_cast.
Definition VPlan.h:2489
VPValue * getStartValue() const
Definition VPlan.h:2511
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:2187
VPHistogramRecipe(HistogramUpdateKind UpdateKind, ArrayRef< VPValue * > Operands, const VPIRMetadata &Metadata={}, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:2192
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:2221
VPHistogramRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:2201
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:2216
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:4681
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:4705
static bool classof(const VPBlockBase *V)
Definition VPlan.h:4695
~VPIRBasicBlock() override=default
friend class VPlan
Definition VPlan.h:4682
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:1756
bool usesFirstPartOnly(const VPValue *Op) const override
Returns true if the VPUser only uses the first part of operand Op.
Definition VPlan.h:1764
~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:1743
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the VPUser only uses the first lane of operand Op.
Definition VPlan.h:1770
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:1758
VPIRInstruction(Instruction &I)
VPIRInstruction::create() should be used to create VPIRInstructions, as subclasses may need to be cre...
Definition VPlan.h:1731
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:1545
iterator_range< operand_iterator > operandsWithoutMask()
Returns an iterator range over the operands excluding the mask operand if present.
Definition VPlan.h:1565
VPInstruction * clone() override
Clone the current recipe.
Definition VPlan.h:1501
@ 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:1532
iterator_range< const_operand_iterator > operandsWithoutMask() const
Definition VPlan.h:1568
void addMask(VPValue *Mask)
Add mask Mask to an unmasked VPInstruction, if it needs masking.
Definition VPlan.h:1550
StringRef getName() const
Returns the symbolic name assigned to the VPInstruction.
Definition VPlan.h:1595
unsigned getOpcode() const
Definition VPlan.h:1514
void setName(StringRef NewName)
Set the symbolic name for the VPInstruction.
Definition VPlan.h:1598
bool usesScalars(const VPValue *Op) const override
Returns true if the recipe only uses scalars of operand Op.
Definition VPlan.h:1579
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:1561
bool isSingleScalar() const
Returns true if the recipe produces a single scalar value.
VPInstruction * cloneWithOperands(ArrayRef< VPValue * > NewOperands, Type *ResultTy=nullptr)
Definition VPlan.h:1505
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:1535
A common base class for interleaved memory operations.
Definition VPlan.h:3129
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:3141
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:3191
void execute(VPTransformState &State) override
The method which generates the output IR instructions that correspond to this VPRecipe,...
Definition VPlan.h:3197
static bool classof(const VPUser *U)
Definition VPlan.h:3173
Instruction * getInsertPos() const
Definition VPlan.h:3195
static bool classof(const VPRecipeBase *R)
Definition VPlan.h:3168
const InterleaveGroup< Instruction > * getInterleaveGroup() const
Definition VPlan.h:3193
VPValue * getMask() const
Return the mask used by this recipe.
Definition VPlan.h:3185
ArrayRef< VPValue * > getStoredValues() const
Return the VPValues stored by this interleave group.
Definition VPlan.h:3214
VPInterleaveBase * clone() override=0
Clone the current recipe.
VPValue * getAddr() const
Return the address accessed by this recipe.
Definition VPlan.h:3179
bool usesFirstLaneOnly(const VPValue *Op) const override
The recipe only uses the first lane of the address, and EVL operand.
Definition VPlan.h:3294
VPValue * getEVL() const
The VPValue of the explicit vector length.
Definition VPlan.h:3288
~VPInterleaveEVLRecipe() override=default
unsigned getNumStoreOperands() const override
Returns the number of stored operands of this interleave group.
Definition VPlan.h:3301
VPInterleaveEVLRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:3281
VPInterleaveEVLRecipe(VPInterleaveRecipe &R, VPValue &EVL, VPValue *Mask)
Definition VPlan.h:3268
VPInterleaveRecipe is a recipe for transforming an interleave group of load or stores into one wide l...
Definition VPlan.h:3224
unsigned getNumStoreOperands() const override
Returns the number of stored operands of this interleave group.
Definition VPlan.h:3251
~VPInterleaveRecipe() override=default
VPInterleaveRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:3234
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:3245
VPInterleaveRecipe(const InterleaveGroup< Instruction > *IG, VPValue *Addr, ArrayRef< VPValue * > StoredValues, VPValue *Mask, bool NeedsMaskForGaps, const VPIRMetadata &MD, DebugLoc DL)
Definition VPlan.h:3226
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:1610
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:1640
void addIncoming(VPValue *IncomingV)
Append IncomingV as an incoming value to the phi-like recipe.
Definition VPlan.h:1669
virtual unsigned getNumIncoming() const
Returns the number of incoming values, also number of incoming blocks.
Definition VPlan.h:1635
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:4672
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:1660
VPValue * getIncomingValue(unsigned Idx) const
Returns the incoming VPValue with index Idx.
Definition VPlan.h:1619
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:1645
const_incoming_blocks_range incoming_blocks() const
Returns an iterator range over the incoming blocks.
Definition VPlan.h:1649
~VPPredInstPHIRecipe() override=default
VPPredInstPHIRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:3808
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPPredInstPHIRecipe.
Definition VPlan.h:3819
VPPredInstPHIRecipe(VPValue *PredV, DebugLoc DL)
Construct a VPPredInstPHIRecipe given PredInst whose value needs a phi nodes after merging back from ...
Definition VPlan.h:3803
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:4927
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:3462
VPReductionEVLRecipe(VPReductionRecipe &R, VPValue &EVL, VPValue *CondOp, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:3440
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:3465
VPReductionEVLRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:3452
~VPReductionEVLRecipe() override=default
bool isOrdered() const
Returns true, if the phi is part of an ordered reduction.
Definition VPlan.h:2951
void setVFScaleFactor(unsigned ScaleFactor)
Set the VFScaleFactor for this reduction phi.
Definition VPlan.h:2942
VPReductionPHIRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:2924
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:2935
~VPReductionPHIRecipe() override=default
bool isExpressionSunk() const
Definition VPlan.h:2966
bool hasUsesOutsideReductionChain() const
Returns true, if the phi is part of a multi-use reduction.
Definition VPlan.h:2960
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:2902
bool isInLoop() const
Returns true if the phi is part of an in-loop reduction.
Definition VPlan.h:2954
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:2969
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:2915
RecurKind getRecurrenceKind() const
Returns the recurrence kind of the reduction.
Definition VPlan.h:2948
A recipe to represent inloop, ordered or partial reduction operations.
Definition VPlan.h:3317
bool isConditional() const
Return true if the in-loop reduction is conditional.
Definition VPlan.h:3401
static bool classof(const VPRecipeBase *R)
Definition VPlan.h:3370
static bool classof(const VPSingleDefRecipe *R)
Definition VPlan.h:3385
VPValue * getVecOp() const
The VPValue of the vector value to be reduced.
Definition VPlan.h:3414
VPValue * getCondOp() const
The VPValue of the condition for the block.
Definition VPlan.h:3416
RecurKind getRecurrenceKind() const
Return the recurrence kind for the in-loop reduction.
Definition VPlan.h:3397
VPReductionRecipe(RecurKind RdxKind, FastMathFlags FMFs, Instruction *I, VPValue *ChainOp, VPValue *VecOp, VPValue *CondOp, ReductionStyle Style, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:3350
bool isOrdered() const
Return true if the in-loop reduction is ordered.
Definition VPlan.h:3399
VPReductionRecipe(const RecurKind RdxKind, FastMathFlags FMFs, VPValue *ChainOp, VPValue *VecOp, VPValue *CondOp, ReductionStyle Style, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:3356
VPReductionRecipe(VPRecipeTy SC, RecurKind RdxKind, FastMathFlags FMFs, Instruction *I, ArrayRef< VPValue * > Operands, VPValue *CondOp, ReductionStyle Style, DebugLoc DL)
Definition VPlan.h:3326
bool isPartialReduction() const
Returns true if the reduction outputs a vector with a scaled down VF.
Definition VPlan.h:3403
~VPReductionRecipe() override=default
VPValue * getChainOp() const
The VPValue of the scalar Chain being accumulated.
Definition VPlan.h:3412
bool isInLoop() const
Returns true if the reduction is in-loop.
Definition VPlan.h:3407
VPReductionRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:3364
static bool classof(const VPUser *U)
Definition VPlan.h:3375
static bool classof(const VPValue *VPV)
Definition VPlan.h:3380
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:3421
VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks which form a Single-Entry-S...
Definition VPlan.h:4753
const VPBlockBase * getEntry() const
Definition VPlan.h:4797
bool isReplicator() const
An indicator whether this region is to generate multiple replicated instances of output IR correspond...
Definition VPlan.h:4829
~VPRegionBlock() override=default
VPRegionValue * createHeaderMask()
Create the header mask for the region and return it.
Definition VPlan.h:4900
VPRegionValue * getUsedHeaderMask() const
Return the header mask if it exists and is used, or null otherwise.
Definition VPlan.h:4893
void setExiting(VPBlockBase *ExitingBlock)
Set ExitingBlock as the exiting VPBlockBase of this VPRegionBlock.
Definition VPlan.h:4814
VPBlockBase * getExiting()
Definition VPlan.h:4810
VPBranchOnMaskRecipe * getEntryBranchOnMask()
Definition VPlan.h:4834
const VPRegionValue * getCanonicalIV() const
Definition VPlan.h:4876
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:4907
void setEntry(VPBlockBase *EntryBlock)
Set EntryBlock as the entry VPBlockBase of this VPRegionBlock.
Definition VPlan.h:4802
Type * getCanonicalIVType() const
Return the type of the canonical IV for loop regions.
Definition VPlan.h:4881
bool hasCanonicalIVNUW() const
Indicates if NUW is set for the canonical IV increment, for loop regions.
Definition VPlan.h:4917
void clearCanonicalIVNUW(VPInstruction *Increment)
Unsets NUW for the canonical IV increment Increment, for loop regions.
Definition VPlan.h:4920
VPRegionValue * getCanonicalIV()
Return the canonical induction variable of the region, null for replicating regions.
Definition VPlan.h:4873
const VPBlockBase * getExiting() const
Definition VPlan.h:4809
VPBlockBase * getEntry()
Definition VPlan.h:4798
VPBasicBlock * getPreheaderVPBB()
Returns the pre-header VPBasicBlock of the loop region.
Definition VPlan.h:4822
VPRegionValue * getHeaderMask() const
Return the header mask of the region, or null if not set.
Definition VPlan.h:4886
friend class VPlan
Definition VPlan.h:4754
static bool classof(const VPBlockBase *V)
Method to support type inquiry through isa, cast, and dyn_cast.
Definition VPlan.h:4793
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:3484
bool isSingleScalar() const
Returns true if the recipe produces a single scalar value.
Definition VPlan.h:3541
unsigned getNumOperandsWithoutMask() const
Returns the number of operands, excluding the mask if the recipe is predicated.
Definition VPlan.h:3575
VPReplicateRecipe(Instruction *I, ArrayRef< VPValue * > Operands, bool IsSingleScalar, VPValue *Mask=nullptr, const VPIRFlags &Flags={}, VPIRMetadata Metadata={}, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:3492
~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:3516
bool usesScalars(const VPValue *Op) const override
Returns true if the recipe uses scalars of operand Op.
Definition VPlan.h:3556
operand_range operandsWithoutMask()
Return the recipe's operands, excluding the mask of a predicated recipe.
Definition VPlan.h:3569
bool isPredicated() const
Definition VPlan.h:3546
VPReplicateRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:3514
bool doesGeneratePerAllLanes() const
Returns true if the recipe produces scalar values for all VF lanes.
Definition VPlan.h:3544
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:3549
unsigned getOpcode() const
Definition VPlan.h:3579
VPValue * getMask()
Return the mask of a predicated VPReplicateRecipe.
Definition VPlan.h:3563
Instruction::BinaryOps getInductionOpcode() const
Definition VPlan.h:4414
VPValue * getStepValue() const
Definition VPlan.h:4384
void setStartIndex(VPValue *StartIndex)
Set or add the StartIndex operand.
Definition VPlan.h:4397
VPScalarIVStepsRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:4366
VPValue * getStartIndex() const
Return the StartIndex, or null if known to be zero, valid only after unrolling.
Definition VPlan.h:4392
VPValue * getVFValue() const
Return the number of scalars to produce per unroll part, used to compute StartIndex during unrolling.
Definition VPlan.h:4388
VPScalarIVStepsRecipe(VPValue *IV, VPValue *Step, VPValue *VF, Instruction::BinaryOps Opcode, FastMathFlags FMFs={}, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:4357
~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:4408
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:2346
VPValue * getVFValue() const
Definition VPlan.h:2327
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:2324
int64_t getStride() const
Definition VPlan.h:2325
VPVectorEndPointerRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:2367
VPValue * getOffset() const
Definition VPlan.h:2328
bool usesFirstPartOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first part of operand Op.
Definition VPlan.h:2360
void addOffset(VPValue *Offset)
Append Offset as the offset operand.
Definition VPlan.h:2338
VPVectorEndPointerRecipe(VPValue *Ptr, VPValue *VF, Type *SourceElementTy, int64_t Stride, GEPNoWrapFlags GEPFlags, DebugLoc DL)
Definition VPlan.h:2314
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPVectorPointerRecipe.
Definition VPlan.h:2353
VPValue * getPointer() const
Definition VPlan.h:2326
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:2408
VPValue * getStride() const
Definition VPlan.h:2401
Type * getSourceElementType() const
Definition VPlan.h:2416
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the VPUser only uses the first lane of operand Op.
Definition VPlan.h:2418
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:2425
VPVectorPointerRecipe(VPValue *Ptr, Type *SourceElementTy, VPValue *Stride, GEPNoWrapFlags GEPFlags, DebugLoc DL)
Definition VPlan.h:2392
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPHeaderPHIRecipe.
Definition VPlan.h:2442
VPVectorPointerRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:2432
VPValue * getVFxPart() const
Definition VPlan.h:2403
A recipe for widening Call instructions using library calls.
Definition VPlan.h:2121
const_operand_range args() const
Definition VPlan.h:2169
VPWidenCallRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:2147
operand_range args()
Definition VPlan.h:2168
Function * getCalledScalarFunction() const
Definition VPlan.h:2164
VPWidenCallRecipe(Value *UV, Function *Variant, ArrayRef< VPValue * > CallArguments, const VPIRFlags &Flags={}, const VPIRMetadata &Metadata={}, const VPIRAttributes &Attrs={}, DebugLoc DL={})
Definition VPlan.h:2128
~VPWidenCallRecipe() override=default
~VPWidenCanonicalIVRecipe() override=default
VPValue * getStepValue() const
Definition VPlan.h:4270
void addPerPartStep(VPValue *Step)
Add the per-part step (VF * Part) used for unrolled parts.
Definition VPlan.h:4275
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:4259
VPRegionValue * getCanonicalIV() const
Return the canonical IV being widened.
Definition VPlan.h:4266
VPWidenCanonicalIVRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:4244
VPWidenCanonicalIVRecipe(VPRegionValue *CanonicalIV, const VPIRFlags::WrapFlagsTy &Flags={})
Definition VPlan.h:4237
void execute(VPTransformState &State) override
The method which generates the output IR instructions that correspond to this VPRecipe,...
Definition VPlan.h:4254
VPWidenCastRecipe is a recipe to create vector cast instructions.
Definition VPlan.h:1888
Instruction::CastOps getOpcode() const
Definition VPlan.h:1924
~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:1893
VPWidenCastRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:1909
unsigned getOpcode() const
This recipe generates a GEP instruction.
Definition VPlan.h:2276
Type * getSourceElementType() const
Definition VPlan.h:2281
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenGEPRecipe.
Definition VPlan.h:2284
VPWidenGEPRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:2267
~VPWidenGEPRecipe() override=default
VPWidenGEPRecipe(Type *SourceElementTy, ArrayRef< VPValue * > Operands, const VPIRFlags &Flags={}, DebugLoc DL=DebugLoc::getUnknown(), GetElementPtrInst *UV=nullptr)
Definition VPlan.h:2250
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:2606
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:2618
static bool classof(const VPValue *V)
Definition VPlan.h:2574
VPValue * getBackedgeValue() override
Returns the incoming value from the loop backedge.
Definition VPlan.h:2610
unsigned getNumIncoming() const override
Returns the number of incoming values, also number of incoming blocks.
Definition VPlan.h:2595
PHINode * getPHINode() const
Returns the underlying PHINode if one exists, or null otherwise.
Definition VPlan.h:2598
VPValue * getStepValue()
Returns the step value of the induction.
Definition VPlan.h:2586
const InductionDescriptor & getInductionDescriptor() const
Returns the induction descriptor for the recipe.
Definition VPlan.h:2603
static bool classof(const VPRecipeBase *R)
Definition VPlan.h:2569
VPWidenInductionRecipe(VPRecipeTy Kind, PHINode *IV, VPValue *Start, VPValue *Step, const InductionDescriptor &IndDesc, Type *ResultTy, DebugLoc DL)
Definition VPlan.h:2548
const VPValue * getVFValue() const
Definition VPlan.h:2590
static bool classof(const VPSingleDefRecipe *R)
Definition VPlan.h:2579
const VPValue * getStepValue() const
Definition VPlan.h:2587
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:2557
void execute(VPTransformState &State) override
Generate the phi nodes.
Definition VPlan.h:2667
~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:2674
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenIntOrFpInductionRecipe.
VPWidenIntOrFpInductionRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:2659
VPWidenIntOrFpInductionRecipe(PHINode *IV, VPValue *Start, VPValue *Step, VPValue *VF, const InductionDescriptor &IndDesc, const VPIRFlags &Flags, DebugLoc DL)
Definition VPlan.h:2637
bool isTruncated() const
Returns true if this induction is evaluated in a narrower type than the start value.
Definition VPlan.h:2685
VPWidenIntOrFpInductionRecipe(PHINode *IV, VPValue *Start, VPValue *Step, VPValue *VF, const InductionDescriptor &IndDesc, Type *ResultTy, const VPIRFlags &Flags, DebugLoc DL)
Definition VPlan.h:2647
VPValue * getLastUnrolledPartOperand()
Returns the VPValue representing the value of this induction at the last unrolled part,...
Definition VPlan.h:2703
unsigned getNumIncoming() const override
Returns the number of incoming values, also number of incoming blocks.
Definition VPlan.h:2681
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:1936
VPWidenIntrinsicRecipe(VPRecipeTy SC, Intrinsic::ID VectorIntrinsicID, ArrayRef< VPValue * > CallArguments, Type *Ty, const VPIRFlags &Flags={}, const VPIRMetadata &MD={}, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:1950
VPWidenIntrinsicRecipe(Intrinsic::ID VectorIntrinsicID, ArrayRef< VPValue * > CallArguments, Type *Ty, const VPIRFlags &Flags={}, const VPIRMetadata &Metadata={}, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:1985
Intrinsic::ID getVectorIntrinsicID() const
Return the ID of the intrinsic.
Definition VPlan.h:2039
bool mayReadFromMemory() const
Returns true if the intrinsic may read from memory.
Definition VPlan.h:2045
VPWidenIntrinsicRecipe(CallInst &CI, Intrinsic::ID VectorIntrinsicID, ArrayRef< VPValue * > CallArguments, Type *Ty, const VPIRFlags &Flags={}, const VPIRMetadata &MD={}, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:1971
bool mayHaveSideEffects() const
Returns true if the intrinsic may have side-effects.
Definition VPlan.h:2051
static bool classof(const VPSingleDefRecipe *R)
Definition VPlan.h:2021
static bool classof(const VPValue *V)
Definition VPlan.h:2016
VPWidenIntrinsicRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:1996
bool mayWriteToMemory() const
Returns true if the intrinsic may write to memory.
Definition VPlan.h:2048
~VPWidenIntrinsicRecipe() override=default
static bool classof(const VPRecipeBase *R)
Definition VPlan.h:2006
static bool classof(const VPUser *U)
Definition VPlan.h:2011
~VPWidenMemIntrinsicRecipe() override=default
VPWidenMemIntrinsicRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:2088
VPWidenMemIntrinsicRecipe(Intrinsic::ID VectorIntrinsicID, ArrayRef< VPValue * > CallArguments, Type *Ty, Align Alignment, const VPIRMetadata &MD={}, DebugLoc DL=DebugLoc::getUnknown())
Definition VPlan.h:2070
A common mixin class for widening memory operations.
Definition VPlan.h:3835
bool IsMasked
Whether the memory access is masked.
Definition VPlan.h:3846
bool isConsecutive() const
Return whether the loaded-from / stored-to addresses are consecutive.
Definition VPlan.h:3871
virtual ~VPWidenMemoryRecipe()=default
Instruction & Ingredient
Definition VPlan.h:3837
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const
Return the cost of this VPWidenMemoryRecipe.
Instruction & getIngredient() const
Definition VPlan.h:3893
bool Consecutive
Whether the accessed addresses are consecutive.
Definition VPlan.h:3843
VPWidenMemoryRecipe(Instruction &I, Align Alignment, bool Consecutive, const VPIRMetadata &Metadata)
Definition VPlan.h:3858
virtual const VPRecipeBase * getAsRecipe() const =0
VPValue * getMask() const
Return the mask used by this recipe.
Definition VPlan.h:3881
Align Alignment
Alignment information for this memory access.
Definition VPlan.h:3840
virtual VPRecipeBase * getAsRecipe()=0
Return a VPRecipeBase* to the current object.
bool isMasked() const
Returns true if the recipe is masked.
Definition VPlan.h:3877
void setMask(VPValue *Mask)
Definition VPlan.h:3848
Align getAlign() const
Returns the alignment of the memory access.
Definition VPlan.h:3888
VPValue * getAddr() const
Return the address accessed by this recipe.
Definition VPlan.h:3874
A recipe for widened phis.
Definition VPlan.h:2766
const VPRecipeBase * getAsRecipe() const override
Return a VPRecipeBase* to the current object.
Definition VPlan.h:2811
unsigned getOpcode() const
This recipe generates a PHI.
Definition VPlan.h:2793
VPWidenPHIRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:2786
~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:2773
VPWidenPointerInductionRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:2731
~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:2740
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:2720
VPWidenRecipe is a recipe for producing a widened instruction using the opcode and operands of the re...
Definition VPlan.h:1821
VPWidenRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:1847
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:1876
VPWidenRecipe(Instruction &I, ArrayRef< VPValue * > Operands, const VPIRFlags &Flags={}, const VPIRMetadata &Metadata={}, DebugLoc DL={})
Definition VPlan.h:1825
VPWidenRecipe(unsigned Opcode, ArrayRef< VPValue * > Operands, const VPIRFlags &Flags={}, const VPIRMetadata &Metadata={}, DebugLoc DL={})
Definition VPlan.h:1832
~VPWidenRecipe() override=default
VPWidenRecipe * cloneWithOperands(ArrayRef< VPValue * > NewOperands)
Definition VPlan.h:1849
unsigned getOpcode() const
Definition VPlan.h:1866
VPlan models a candidate for vectorization, encoding various decisions take to produce efficient outp...
Definition VPlan.h:4940
VPIRValue * getLiveIn(Value *V) const
Return the live-in VPIRValue for V, if there is one or nullptr otherwise.
Definition VPlan.h:5270
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:4942
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:5163
ElementCount getSingleVF() const
Returns the single VF of the plan, asserting that the plan has exactly one VF.
Definition VPlan.h:5176
const DataLayout & getDataLayout() const
Definition VPlan.h:5141
LLVMContext & getContext() const
Definition VPlan.h:5137
VPBasicBlock * getEntry()
Definition VPlan.h:5032
Type * getIndexType() const
The type of the canonical induction variable of the vector loop.
Definition VPlan.h:5376
void setName(const Twine &newName)
Definition VPlan.h:5209
bool hasScalableVF() const
Definition VPlan.h:5164
VPValue * getTripCount() const
The trip count of the original loop.
Definition VPlan.h:5104
iterator_range< SmallSetVector< ElementCount, 2 >::iterator > vectorFactors() const
Returns an iterator range over all VFs of the plan.
Definition VPlan.h:5170
LLVM_ABI_FOR_TEST ~VPlan()
Definition VPlan.cpp:913
VPIRValue * getOrAddLiveIn(VPIRValue *V)
Definition VPlan.h:5227
bool isExitBlock(VPBlockBase *VPBB)
Returns true if VPBB is an exit block.
Definition VPlan.cpp:931
const VPBasicBlock * getEntry() const
Definition VPlan.h:5033
friend class VPlanPrinter
Definition VPlan.h:4941
VPIRValue * getFalse()
Return a VPIRValue wrapping i1 false.
Definition VPlan.h:5236
VPIRValue * getConstantInt(const APInt &Val)
Return a VPIRValue wrapping a ConstantInt with the given APInt value.
Definition VPlan.h:5259
VPSymbolicValue & getVFxUF()
Returns VF * UF of the vector loop region.
Definition VPlan.h:5135
VPIRValue * getAllOnesValue(Type *Ty)
Return a VPIRValue wrapping the AllOnes value of type Ty.
Definition VPlan.h:5242
VPRegionBlock * createReplicateRegion(VPBlockBase *Entry, VPBlockBase *Exiting, const std::string &Name="")
Create a new replicate region with Entry, Exiting and Name.
Definition VPlan.h:5323
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:5273
bool hasUF(unsigned UF) const
Definition VPlan.h:5188
VPIRValue * getPoison(Type *Ty)
Return a VPIRValue wrapping a poison value of type Ty.
Definition VPlan.h:5264
ArrayRef< VPIRBasicBlock * > getExitBlocks() const
Return an ArrayRef containing VPIRBasicBlocks wrapping the exit blocks of the original scalar loop.
Definition VPlan.h:5098
VPlan(BasicBlock *ScalarHeaderBB, Type *IdxTy)
Construct a VPlan with a new VPBasicBlock as entry, a VPIRBasicBlock wrapping ScalarHeaderBB and vect...
Definition VPlan.h:5013
VPSymbolicValue & getVectorTripCount()
The vector trip count.
Definition VPlan.h:5125
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:5213
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:5309
VPIRValue * getZero(Type *Ty)
Return a VPIRValue wrapping the null value of type Ty.
Definition VPlan.h:5239
void setVF(ElementCount VF)
Definition VPlan.h:5151
unsigned getMaxBlockNumber() const
Definition VPlan.h:5343
bool isUnrolled() const
Returns true if the VPlan already has been unrolled, i.e.
Definition VPlan.h:5204
Function * getIRFunction() const
Definition VPlan.h:5145
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:5346
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:5191
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:5253
const VPBasicBlock * getMiddleBlock() const
Definition VPlan.h:5083
void setTripCount(VPValue *NewTripCount)
Set the trip count assuming it is currently null; if it is not - use resetTripCount().
Definition VPlan.h:5111
void resetTripCount(VPValue *NewTripCount)
Resets the trip count for the VPlan.
Definition VPlan.h:5118
VPBasicBlock * getMiddleBlock()
Returns the 'middle' block of the plan, that is the block that selects whether to execute the scalar ...
Definition VPlan.h:5074
void setEntry(VPBasicBlock *VPBB)
Definition VPlan.h:5021
VPBasicBlock * createVPBasicBlock(const Twine &Name, VPRecipeBase *Recipe=nullptr)
Create a new VPBasicBlock with Name and containing Recipe if present.
Definition VPlan.h:5296
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:5158
VPIRValue * getTrue()
Return a VPIRValue wrapping i1 true.
Definition VPlan.h:5233
VPBasicBlock * getVectorPreheader() const
Returns the preheader of the vector loop region, if one exists, or null otherwise.
Definition VPlan.h:5037
bool requiresScalarEpilogue() const
Returns true if the plan requires a scalar epilogue after the vector loop.
Definition VPlan.h:5060
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:5132
bool hasScalarVFOnly() const
Definition VPlan.h:5181
VPBasicBlock * getScalarPreheader() const
Return the VPBasicBlock for the preheader of the scalar loop.
Definition VPlan.h:5088
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:5053
void addVF(ElementCount VF)
Definition VPlan.h:5149
VPIRBasicBlock * getScalarHeader() const
Return the VPIRBasicBlock wrapping the header of the scalar loop.
Definition VPlan.h:5094
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:5128
void setUF(unsigned UF)
Definition VPlan.h:5196
const VPSymbolicValue & getVF() const
Definition VPlan.h:5129
bool hasScalarTail() const
Returns true if the scalar tail may execute after the vector loop, i.e.
Definition VPlan.h:5369
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:5247
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:4427
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:2866
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:2864
@ 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:878
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
#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:2858
Possible variants of a reduction.
Definition VPlan.h:2856
This reduction is unordered with the partial result scaled down by some factor.
Definition VPlan.h:2861
unsigned VFScaleFactor
Definition VPlan.h:2862
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:2827
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:2839
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:2818
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:1789
VPIRPhi(PHINode &PN)
Definition VPlan.h:1790
static bool classof(const VPRecipeBase *U)
Definition VPlan.h:1792
static bool classof(const VPUser *U)
Definition VPlan.h:1797
PHINode & getIRPhi() const
Definition VPlan.h:1802
const VPRecipeBase * getAsRecipe() const override
Return a VPRecipeBase* to the current object.
Definition VPlan.h:1813
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:1689
VPPhi * clone() override
Clone the current recipe.
Definition VPlan.h:1704
const VPRecipeBase * getAsRecipe() const override
Return a VPRecipeBase* to the current object.
Definition VPlan.h:1719
static bool classof(const VPSingleDefRecipe *SDR)
Definition VPlan.h:1699
static bool classof(const VPValue *V)
Definition VPlan.h:1694
VPPhi(ArrayRef< VPValue * > Operands, const VPIRFlags &Flags, DebugLoc DL, const Twine &Name="", Type *ResultTy=nullptr)
Definition VPlan.h:1684
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:3954
VPWidenLoadEVLRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:3965
unsigned getOpcode() const
Returns the opcode of the widened load.
Definition VPlan.h:3972
VPValue * getEVL() const
Return the EVL operand.
Definition VPlan.h:3975
VPWidenLoadEVLRecipe(VPWidenLoadRecipe &L, VPValue *Addr, VPValue &EVL, VPValue *Mask)
Definition VPlan.h:3955
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:3985
A recipe for widening load operations, using the address to load from and an optional mask.
Definition VPlan.h:3899
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:3930
unsigned getOpcode() const
Returns the opcode of the widened load.
Definition VPlan.h:3918
VPWidenLoadRecipe(LoadInst &Load, VPValue *Addr, VPValue *Mask, bool Consecutive, Align Alignment, const VPIRMetadata &Metadata, DebugLoc DL)
Definition VPlan.h:3900
VPWidenLoadRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:3909
VP_CLASSOF_IMPL(VPRecipeBase::VPWidenLoadSC)
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenLoadRecipe.
Definition VPlan.h:3924
A recipe for widening store operations with vector-predication intrinsics, using the value to store,...
Definition VPlan.h:4061
VPValue * getStoredValue() const
Return the address accessed by this recipe.
Definition VPlan.h:4078
VPWidenStoreEVLRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:4071
VPWidenStoreEVLRecipe(VPWidenStoreRecipe &S, VPValue *Addr, VPValue *StoredVal, VPValue &EVL, VPValue *Mask)
Definition VPlan.h:4062
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:4091
VPValue * getEVL() const
Return the EVL operand.
Definition VPlan.h:4081
A recipe for widening store operations, using the stored value, the address to store to and an option...
Definition VPlan.h:4007
VPWidenStoreRecipe(StoreInst &Store, VPValue *Addr, VPValue *StoredVal, VPValue *Mask, bool Consecutive, Align Alignment, const VPIRMetadata &Metadata, DebugLoc DL)
Definition VPlan.h:4008
VP_CLASSOF_IMPL(VPRecipeBase::VPWidenStoreSC)
VPValue * getStoredValue() const
Return the value stored by this recipe.
Definition VPlan.h:4025
VPWidenStoreRecipe * clone() override
Clone the current recipe.
Definition VPlan.h:4016
InstructionCost computeCost(ElementCount VF, VPCostContext &Ctx) const override
Return the cost of this VPWidenStoreRecipe.
Definition VPlan.h:4031
bool usesFirstLaneOnly(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition VPlan.h:4037
static VPMixin * castFailed()
Definition VPlan.h:4445
static bool isPossible(VPRecipeBase *R)
Used by isa.
Definition VPlan.h:4436
static VPMixin * doCast(VPRecipeBase *R)
Used by cast.
Definition VPlan.h:4439