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