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