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