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