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