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