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