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