LLVM 19.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/// 6. The VPlanPrinter class providing a way to print a plan in dot format;
21/// These are documented in docs/VectorizationPlan.rst.
22//
23//===----------------------------------------------------------------------===//
24
25#ifndef LLVM_TRANSFORMS_VECTORIZE_VPLAN_H
26#define LLVM_TRANSFORMS_VECTORIZE_VPLAN_H
27
28#include "VPlanAnalysis.h"
29#include "VPlanValue.h"
30#include "llvm/ADT/DenseMap.h"
31#include "llvm/ADT/MapVector.h"
35#include "llvm/ADT/Twine.h"
36#include "llvm/ADT/ilist.h"
37#include "llvm/ADT/ilist_node.h"
41#include "llvm/IR/DebugLoc.h"
42#include "llvm/IR/FMF.h"
43#include "llvm/IR/Operator.h"
44#include <algorithm>
45#include <cassert>
46#include <cstddef>
47#include <string>
48
49namespace llvm {
50
51class BasicBlock;
52class DominatorTree;
53class InnerLoopVectorizer;
54class IRBuilderBase;
55class LoopInfo;
56class raw_ostream;
57class RecurrenceDescriptor;
58class SCEV;
59class Type;
60class VPBasicBlock;
61class VPRegionBlock;
62class VPlan;
63class VPReplicateRecipe;
64class VPlanSlp;
65class Value;
66class LoopVersioning;
67
68namespace Intrinsic {
69typedef unsigned ID;
70}
71
72/// Returns a calculation for the total number of elements for a given \p VF.
73/// For fixed width vectors this value is a constant, whereas for scalable
74/// vectors it is an expression determined at runtime.
75Value *getRuntimeVF(IRBuilderBase &B, Type *Ty, ElementCount VF);
76
77/// Return a value for Step multiplied by VF.
78Value *createStepForVF(IRBuilderBase &B, Type *Ty, ElementCount VF,
79 int64_t Step);
80
81const SCEV *createTripCountSCEV(Type *IdxTy, PredicatedScalarEvolution &PSE,
82 Loop *CurLoop = nullptr);
83
84/// A range of powers-of-2 vectorization factors with fixed start and
85/// adjustable end. The range includes start and excludes end, e.g.,:
86/// [1, 16) = {1, 2, 4, 8}
87struct VFRange {
88 // A power of 2.
90
91 // A power of 2. If End <= Start range is empty.
93
94 bool isEmpty() const {
96 }
97
99 : Start(Start), End(End) {
101 "Both Start and End should have the same scalable flag");
103 "Expected Start to be a power of 2");
105 "Expected End to be a power of 2");
106 }
107
108 /// Iterator to iterate over vectorization factors in a VFRange.
110 : public iterator_facade_base<iterator, std::forward_iterator_tag,
111 ElementCount> {
112 ElementCount VF;
113
114 public:
115 iterator(ElementCount VF) : VF(VF) {}
116
117 bool operator==(const iterator &Other) const { return VF == Other.VF; }
118
119 ElementCount operator*() const { return VF; }
120
122 VF *= 2;
123 return *this;
124 }
125 };
126
130 return iterator(End);
131 }
132};
133
134using VPlanPtr = std::unique_ptr<VPlan>;
135
136/// In what follows, the term "input IR" refers to code that is fed into the
137/// vectorizer whereas the term "output IR" refers to code that is generated by
138/// the vectorizer.
139
140/// VPLane provides a way to access lanes in both fixed width and scalable
141/// vectors, where for the latter the lane index sometimes needs calculating
142/// as a runtime expression.
143class VPLane {
144public:
145 /// Kind describes how to interpret Lane.
146 enum class Kind : uint8_t {
147 /// For First, Lane is the index into the first N elements of a
148 /// fixed-vector <N x <ElTy>> or a scalable vector <vscale x N x <ElTy>>.
149 First,
150 /// For ScalableLast, Lane is the offset from the start of the last
151 /// N-element subvector in a scalable vector <vscale x N x <ElTy>>. For
152 /// example, a Lane of 0 corresponds to lane `(vscale - 1) * N`, a Lane of
153 /// 1 corresponds to `((vscale - 1) * N) + 1`, etc.
155 };
156
157private:
158 /// in [0..VF)
159 unsigned Lane;
160
161 /// Indicates how the Lane should be interpreted, as described above.
162 Kind LaneKind;
163
164public:
165 VPLane(unsigned Lane, Kind LaneKind) : Lane(Lane), LaneKind(LaneKind) {}
166
168
170 unsigned LaneOffset = VF.getKnownMinValue() - 1;
171 Kind LaneKind;
172 if (VF.isScalable())
173 // In this case 'LaneOffset' refers to the offset from the start of the
174 // last subvector with VF.getKnownMinValue() elements.
176 else
177 LaneKind = VPLane::Kind::First;
178 return VPLane(LaneOffset, LaneKind);
179 }
180
181 /// Returns a compile-time known value for the lane index and asserts if the
182 /// lane can only be calculated at runtime.
183 unsigned getKnownLane() const {
184 assert(LaneKind == Kind::First);
185 return Lane;
186 }
187
188 /// Returns an expression describing the lane index that can be used at
189 /// runtime.
190 Value *getAsRuntimeExpr(IRBuilderBase &Builder, const ElementCount &VF) const;
191
192 /// Returns the Kind of lane offset.
193 Kind getKind() const { return LaneKind; }
194
195 /// Returns true if this is the first lane of the whole vector.
196 bool isFirstLane() const { return Lane == 0 && LaneKind == Kind::First; }
197
198 /// Maps the lane to a cache index based on \p VF.
199 unsigned mapToCacheIndex(const ElementCount &VF) const {
200 switch (LaneKind) {
202 assert(VF.isScalable() && Lane < VF.getKnownMinValue());
203 return VF.getKnownMinValue() + Lane;
204 default:
205 assert(Lane < VF.getKnownMinValue());
206 return Lane;
207 }
208 }
209
210 /// Returns the maxmimum number of lanes that we are able to consider
211 /// caching for \p VF.
212 static unsigned getNumCachedLanes(const ElementCount &VF) {
213 return VF.getKnownMinValue() * (VF.isScalable() ? 2 : 1);
214 }
215};
216
217/// VPIteration represents a single point in the iteration space of the output
218/// (vectorized and/or unrolled) IR loop.
220 /// in [0..UF)
221 unsigned Part;
222
224
225 VPIteration(unsigned Part, unsigned Lane,
227 : Part(Part), Lane(Lane, Kind) {}
228
229 VPIteration(unsigned Part, const VPLane &Lane) : Part(Part), Lane(Lane) {}
230
231 bool isFirstIteration() const { return Part == 0 && Lane.isFirstLane(); }
232};
233
234/// VPTransformState holds information passed down when "executing" a VPlan,
235/// needed for generating the output IR.
240
241 /// The chosen Vectorization and Unroll Factors of the loop being vectorized.
243 unsigned UF;
244
245 /// Hold the indices to generate specific scalar instructions. Null indicates
246 /// that all instances are to be generated, using either scalar or vector
247 /// instructions.
248 std::optional<VPIteration> Instance;
249
250 struct DataState {
251 /// A type for vectorized values in the new loop. Each value from the
252 /// original loop, when vectorized, is represented by UF vector values in
253 /// the new unrolled loop, where UF is the unroll factor.
255
257
261
262 /// Get the generated vector Value for a given VPValue \p Def and a given \p
263 /// Part if \p IsScalar is false, otherwise return the generated scalar
264 /// for \p Part. \See set.
265 Value *get(VPValue *Def, unsigned Part, bool IsScalar = false);
266
267 /// Get the generated Value for a given VPValue and given Part and Lane.
268 Value *get(VPValue *Def, const VPIteration &Instance);
269
270 bool hasVectorValue(VPValue *Def, unsigned Part) {
271 auto I = Data.PerPartOutput.find(Def);
272 return I != Data.PerPartOutput.end() && Part < I->second.size() &&
273 I->second[Part];
274 }
275
277 auto I = Data.PerPartScalars.find(Def);
278 if (I == Data.PerPartScalars.end())
279 return false;
280 unsigned CacheIdx = Instance.Lane.mapToCacheIndex(VF);
281 return Instance.Part < I->second.size() &&
282 CacheIdx < I->second[Instance.Part].size() &&
283 I->second[Instance.Part][CacheIdx];
284 }
285
286 /// Set the generated vector Value for a given VPValue and a given Part, if \p
287 /// IsScalar is false. If \p IsScalar is true, set the scalar in (Part, 0).
288 void set(VPValue *Def, Value *V, unsigned Part, bool IsScalar = false) {
289 if (IsScalar) {
290 set(Def, V, VPIteration(Part, 0));
291 return;
292 }
293 assert((VF.isScalar() || V->getType()->isVectorTy()) &&
294 "scalar values must be stored as (Part, 0)");
295 if (!Data.PerPartOutput.count(Def)) {
297 Data.PerPartOutput[Def] = Entry;
298 }
299 Data.PerPartOutput[Def][Part] = V;
300 }
301
302 /// Reset an existing vector value for \p Def and a given \p Part.
303 void reset(VPValue *Def, Value *V, unsigned Part) {
304 auto Iter = Data.PerPartOutput.find(Def);
305 assert(Iter != Data.PerPartOutput.end() &&
306 "need to overwrite existing value");
307 Iter->second[Part] = V;
308 }
309
310 /// Set the generated scalar \p V for \p Def and the given \p Instance.
311 void set(VPValue *Def, Value *V, const VPIteration &Instance) {
312 auto Iter = Data.PerPartScalars.insert({Def, {}});
313 auto &PerPartVec = Iter.first->second;
314 if (PerPartVec.size() <= Instance.Part)
315 PerPartVec.resize(Instance.Part + 1);
316 auto &Scalars = PerPartVec[Instance.Part];
317 unsigned CacheIdx = Instance.Lane.mapToCacheIndex(VF);
318 if (Scalars.size() <= CacheIdx)
319 Scalars.resize(CacheIdx + 1);
320 assert(!Scalars[CacheIdx] && "should overwrite existing value");
321 Scalars[CacheIdx] = V;
322 }
323
324 /// Reset an existing scalar value for \p Def and a given \p Instance.
325 void reset(VPValue *Def, Value *V, const VPIteration &Instance) {
326 auto Iter = Data.PerPartScalars.find(Def);
327 assert(Iter != Data.PerPartScalars.end() &&
328 "need to overwrite existing value");
329 assert(Instance.Part < Iter->second.size() &&
330 "need to overwrite existing value");
331 unsigned CacheIdx = Instance.Lane.mapToCacheIndex(VF);
332 assert(CacheIdx < Iter->second[Instance.Part].size() &&
333 "need to overwrite existing value");
334 Iter->second[Instance.Part][CacheIdx] = V;
335 }
336
337 /// Add additional metadata to \p To that was not present on \p Orig.
338 ///
339 /// Currently this is used to add the noalias annotations based on the
340 /// inserted memchecks. Use this for instructions that are *cloned* into the
341 /// vector loop.
342 void addNewMetadata(Instruction *To, const Instruction *Orig);
343
344 /// Add metadata from one instruction to another.
345 ///
346 /// This includes both the original MDs from \p From and additional ones (\see
347 /// addNewMetadata). Use this for *newly created* instructions in the vector
348 /// loop.
349 void addMetadata(Value *To, Instruction *From);
350
351 /// Set the debug location in the builder using the debug location \p DL.
353
354 /// Construct the vector value of a scalarized value \p V one lane at a time.
356
357 /// Hold state information used when constructing the CFG of the output IR,
358 /// traversing the VPBasicBlocks and generating corresponding IR BasicBlocks.
359 struct CFGState {
360 /// The previous VPBasicBlock visited. Initially set to null.
362
363 /// The previous IR BasicBlock created or used. Initially set to the new
364 /// header BasicBlock.
365 BasicBlock *PrevBB = nullptr;
366
367 /// The last IR BasicBlock in the output IR. Set to the exit block of the
368 /// vector loop.
369 BasicBlock *ExitBB = nullptr;
370
371 /// A mapping of each VPBasicBlock to the corresponding BasicBlock. In case
372 /// of replication, maps the BasicBlock of the last replica created.
374
375 CFGState() = default;
376
377 /// Returns the BasicBlock* mapped to the pre-header of the loop region
378 /// containing \p R.
381
382 /// Hold a pointer to LoopInfo to register new basic blocks in the loop.
384
385 /// Hold a pointer to Dominator Tree to register new basic blocks in the loop.
387
388 /// Hold a reference to the IRBuilder used to generate output IR code.
390
391 /// Hold a pointer to InnerLoopVectorizer to reuse its IR generation methods.
393
394 /// Pointer to the VPlan code is generated for.
396
397 /// The loop object for the current parent region, or nullptr.
399
400 /// LoopVersioning. It's only set up (non-null) if memchecks were
401 /// used.
402 ///
403 /// This is currently only used to add no-alias metadata based on the
404 /// memchecks. The actually versioning is performed manually.
406
407 /// Map SCEVs to their expanded values. Populated when executing
408 /// VPExpandSCEVRecipes.
410
411 /// VPlan-based type analysis.
413};
414
415/// VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
416/// A VPBlockBase can be either a VPBasicBlock or a VPRegionBlock.
418 friend class VPBlockUtils;
419
420 const unsigned char SubclassID; ///< Subclass identifier (for isa/dyn_cast).
421
422 /// An optional name for the block.
423 std::string Name;
424
425 /// The immediate VPRegionBlock which this VPBlockBase belongs to, or null if
426 /// it is a topmost VPBlockBase.
427 VPRegionBlock *Parent = nullptr;
428
429 /// List of predecessor blocks.
431
432 /// List of successor blocks.
434
435 /// VPlan containing the block. Can only be set on the entry block of the
436 /// plan.
437 VPlan *Plan = nullptr;
438
439 /// Add \p Successor as the last successor to this block.
440 void appendSuccessor(VPBlockBase *Successor) {
441 assert(Successor && "Cannot add nullptr successor!");
442 Successors.push_back(Successor);
443 }
444
445 /// Add \p Predecessor as the last predecessor to this block.
446 void appendPredecessor(VPBlockBase *Predecessor) {
447 assert(Predecessor && "Cannot add nullptr predecessor!");
448 Predecessors.push_back(Predecessor);
449 }
450
451 /// Remove \p Predecessor from the predecessors of this block.
452 void removePredecessor(VPBlockBase *Predecessor) {
453 auto Pos = find(Predecessors, Predecessor);
454 assert(Pos && "Predecessor does not exist");
455 Predecessors.erase(Pos);
456 }
457
458 /// Remove \p Successor from the successors of this block.
459 void removeSuccessor(VPBlockBase *Successor) {
460 auto Pos = find(Successors, Successor);
461 assert(Pos && "Successor does not exist");
462 Successors.erase(Pos);
463 }
464
465protected:
466 VPBlockBase(const unsigned char SC, const std::string &N)
467 : SubclassID(SC), Name(N) {}
468
469public:
470 /// An enumeration for keeping track of the concrete subclass of VPBlockBase
471 /// that are actually instantiated. Values of this enumeration are kept in the
472 /// SubclassID field of the VPBlockBase objects. They are used for concrete
473 /// type identification.
474 using VPBlockTy = enum { VPBasicBlockSC, VPRegionBlockSC };
475
477
478 virtual ~VPBlockBase() = default;
479
480 const std::string &getName() const { return Name; }
481
482 void setName(const Twine &newName) { Name = newName.str(); }
483
484 /// \return an ID for the concrete type of this object.
485 /// This is used to implement the classof checks. This should not be used
486 /// for any other purpose, as the values may change as LLVM evolves.
487 unsigned getVPBlockID() const { return SubclassID; }
488
489 VPRegionBlock *getParent() { return Parent; }
490 const VPRegionBlock *getParent() const { return Parent; }
491
492 /// \return A pointer to the plan containing the current block.
493 VPlan *getPlan();
494 const VPlan *getPlan() const;
495
496 /// Sets the pointer of the plan containing the block. The block must be the
497 /// entry block into the VPlan.
498 void setPlan(VPlan *ParentPlan);
499
500 void setParent(VPRegionBlock *P) { Parent = P; }
501
502 /// \return the VPBasicBlock that is the entry of this VPBlockBase,
503 /// recursively, if the latter is a VPRegionBlock. Otherwise, if this
504 /// VPBlockBase is a VPBasicBlock, it is returned.
505 const VPBasicBlock *getEntryBasicBlock() const;
507
508 /// \return the VPBasicBlock that is the exiting this VPBlockBase,
509 /// recursively, if the latter is a VPRegionBlock. Otherwise, if this
510 /// VPBlockBase is a VPBasicBlock, it is returned.
511 const VPBasicBlock *getExitingBasicBlock() const;
513
514 const VPBlocksTy &getSuccessors() const { return Successors; }
515 VPBlocksTy &getSuccessors() { return Successors; }
516
518
519 const VPBlocksTy &getPredecessors() const { return Predecessors; }
520 VPBlocksTy &getPredecessors() { return Predecessors; }
521
522 /// \return the successor of this VPBlockBase if it has a single successor.
523 /// Otherwise return a null pointer.
525 return (Successors.size() == 1 ? *Successors.begin() : nullptr);
526 }
527
528 /// \return the predecessor of this VPBlockBase if it has a single
529 /// predecessor. Otherwise return a null pointer.
531 return (Predecessors.size() == 1 ? *Predecessors.begin() : nullptr);
532 }
533
534 size_t getNumSuccessors() const { return Successors.size(); }
535 size_t getNumPredecessors() const { return Predecessors.size(); }
536
537 /// An Enclosing Block of a block B is any block containing B, including B
538 /// itself. \return the closest enclosing block starting from "this", which
539 /// has successors. \return the root enclosing block if all enclosing blocks
540 /// have no successors.
542
543 /// \return the closest enclosing block starting from "this", which has
544 /// predecessors. \return the root enclosing block if all enclosing blocks
545 /// have no predecessors.
547
548 /// \return the successors either attached directly to this VPBlockBase or, if
549 /// this VPBlockBase is the exit block of a VPRegionBlock and has no
550 /// successors of its own, search recursively for the first enclosing
551 /// VPRegionBlock that has successors and return them. If no such
552 /// VPRegionBlock exists, return the (empty) successors of the topmost
553 /// VPBlockBase reached.
556 }
557
558 /// \return the hierarchical successor of this VPBlockBase if it has a single
559 /// hierarchical successor. Otherwise return a null pointer.
562 }
563
564 /// \return the predecessors either attached directly to this VPBlockBase or,
565 /// if this VPBlockBase is the entry block of a VPRegionBlock and has no
566 /// predecessors of its own, search recursively for the first enclosing
567 /// VPRegionBlock that has predecessors and return them. If no such
568 /// VPRegionBlock exists, return the (empty) predecessors of the topmost
569 /// VPBlockBase reached.
572 }
573
574 /// \return the hierarchical predecessor of this VPBlockBase if it has a
575 /// single hierarchical predecessor. Otherwise return a null pointer.
578 }
579
580 /// Set a given VPBlockBase \p Successor as the single successor of this
581 /// VPBlockBase. This VPBlockBase is not added as predecessor of \p Successor.
582 /// This VPBlockBase must have no successors.
584 assert(Successors.empty() && "Setting one successor when others exist.");
585 assert(Successor->getParent() == getParent() &&
586 "connected blocks must have the same parent");
587 appendSuccessor(Successor);
588 }
589
590 /// Set two given VPBlockBases \p IfTrue and \p IfFalse to be the two
591 /// successors of this VPBlockBase. This VPBlockBase is not added as
592 /// predecessor of \p IfTrue or \p IfFalse. This VPBlockBase must have no
593 /// successors.
594 void setTwoSuccessors(VPBlockBase *IfTrue, VPBlockBase *IfFalse) {
595 assert(Successors.empty() && "Setting two successors when others exist.");
596 appendSuccessor(IfTrue);
597 appendSuccessor(IfFalse);
598 }
599
600 /// Set each VPBasicBlock in \p NewPreds as predecessor of this VPBlockBase.
601 /// This VPBlockBase must have no predecessors. This VPBlockBase is not added
602 /// as successor of any VPBasicBlock in \p NewPreds.
604 assert(Predecessors.empty() && "Block predecessors already set.");
605 for (auto *Pred : NewPreds)
606 appendPredecessor(Pred);
607 }
608
609 /// Remove all the predecessor of this block.
610 void clearPredecessors() { Predecessors.clear(); }
611
612 /// Remove all the successors of this block.
613 void clearSuccessors() { Successors.clear(); }
614
615 /// The method which generates the output IR that correspond to this
616 /// VPBlockBase, thereby "executing" the VPlan.
617 virtual void execute(VPTransformState *State) = 0;
618
619 /// Delete all blocks reachable from a given VPBlockBase, inclusive.
620 static void deleteCFG(VPBlockBase *Entry);
621
622 /// Return true if it is legal to hoist instructions into this block.
624 // There are currently no constraints that prevent an instruction to be
625 // hoisted into a VPBlockBase.
626 return true;
627 }
628
629 /// Replace all operands of VPUsers in the block with \p NewValue and also
630 /// replaces all uses of VPValues defined in the block with NewValue.
631 virtual void dropAllReferences(VPValue *NewValue) = 0;
632
633#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
634 void printAsOperand(raw_ostream &OS, bool PrintType) const {
635 OS << getName();
636 }
637
638 /// Print plain-text dump of this VPBlockBase to \p O, prefixing all lines
639 /// with \p Indent. \p SlotTracker is used to print unnamed VPValue's using
640 /// consequtive numbers.
641 ///
642 /// Note that the numbering is applied to the whole VPlan, so printing
643 /// individual blocks is consistent with the whole VPlan printing.
644 virtual void print(raw_ostream &O, const Twine &Indent,
645 VPSlotTracker &SlotTracker) const = 0;
646
647 /// Print plain-text dump of this VPlan to \p O.
648 void print(raw_ostream &O) const {
650 print(O, "", SlotTracker);
651 }
652
653 /// Print the successors of this block to \p O, prefixing all lines with \p
654 /// Indent.
655 void printSuccessors(raw_ostream &O, const Twine &Indent) const;
656
657 /// Dump this VPBlockBase to dbgs().
658 LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
659#endif
660
661 /// Clone the current block and it's recipes without updating the operands of
662 /// the cloned recipes, including all blocks in the single-entry single-exit
663 /// region for VPRegionBlocks.
664 virtual VPBlockBase *clone() = 0;
665};
666
667/// A value that is used outside the VPlan. The operand of the user needs to be
668/// added to the associated LCSSA phi node.
669class VPLiveOut : public VPUser {
670 PHINode *Phi;
671
672public:
674 : VPUser({Op}, VPUser::VPUserID::LiveOut), Phi(Phi) {}
675
676 static inline bool classof(const VPUser *U) {
677 return U->getVPUserID() == VPUser::VPUserID::LiveOut;
678 }
679
680 /// Fixup the wrapped LCSSA phi node in the unique exit block. This simply
681 /// means we need to add the appropriate incoming value from the middle
682 /// block as exiting edges from the scalar epilogue loop (if present) are
683 /// already in place, and we exit the vector loop exclusively to the middle
684 /// block.
685 void fixPhi(VPlan &Plan, VPTransformState &State);
686
687 /// Returns true if the VPLiveOut uses scalars of operand \p Op.
688 bool usesScalars(const VPValue *Op) const override {
690 "Op must be an operand of the recipe");
691 return true;
692 }
693
694 PHINode *getPhi() const { return Phi; }
695
696#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
697 /// Print the VPLiveOut to \p O.
699#endif
700};
701
702/// VPRecipeBase is a base class modeling a sequence of one or more output IR
703/// instructions. VPRecipeBase owns the VPValues it defines through VPDef
704/// and is responsible for deleting its defined values. Single-value
705/// recipes must inherit from VPSingleDef instead of inheriting from both
706/// VPRecipeBase and VPValue separately.
707class VPRecipeBase : public ilist_node_with_parent<VPRecipeBase, VPBasicBlock>,
708 public VPDef,
709 public VPUser {
710 friend VPBasicBlock;
711 friend class VPBlockUtils;
712
713 /// Each VPRecipe belongs to a single VPBasicBlock.
714 VPBasicBlock *Parent = nullptr;
715
716 /// The debug location for the recipe.
717 DebugLoc DL;
718
719public:
721 DebugLoc DL = {})
723
724 template <typename IterT>
726 DebugLoc DL = {})
728 virtual ~VPRecipeBase() = default;
729
730 /// Clone the current recipe.
731 virtual VPRecipeBase *clone() = 0;
732
733 /// \return the VPBasicBlock which this VPRecipe belongs to.
734 VPBasicBlock *getParent() { return Parent; }
735 const VPBasicBlock *getParent() const { return Parent; }
736
737 /// The method which generates the output IR instructions that correspond to
738 /// this VPRecipe, thereby "executing" the VPlan.
739 virtual void execute(VPTransformState &State) = 0;
740
741 /// Insert an unlinked recipe into a basic block immediately before
742 /// the specified recipe.
743 void insertBefore(VPRecipeBase *InsertPos);
744 /// Insert an unlinked recipe into \p BB immediately before the insertion
745 /// point \p IP;
747
748 /// Insert an unlinked Recipe into a basic block immediately after
749 /// the specified Recipe.
750 void insertAfter(VPRecipeBase *InsertPos);
751
752 /// Unlink this recipe from its current VPBasicBlock and insert it into
753 /// the VPBasicBlock that MovePos lives in, right after MovePos.
754 void moveAfter(VPRecipeBase *MovePos);
755
756 /// Unlink this recipe and insert into BB before I.
757 ///
758 /// \pre I is a valid iterator into BB.
760
761 /// This method unlinks 'this' from the containing basic block, but does not
762 /// delete it.
763 void removeFromParent();
764
765 /// This method unlinks 'this' from the containing basic block and deletes it.
766 ///
767 /// \returns an iterator pointing to the element after the erased one
769
770 /// Method to support type inquiry through isa, cast, and dyn_cast.
771 static inline bool classof(const VPDef *D) {
772 // All VPDefs are also VPRecipeBases.
773 return true;
774 }
775
776 static inline bool classof(const VPUser *U) {
777 return U->getVPUserID() == VPUser::VPUserID::Recipe;
778 }
779
780 /// Returns true if the recipe may have side-effects.
781 bool mayHaveSideEffects() const;
782
783 /// Returns true for PHI-like recipes.
784 bool isPhi() const {
785 return getVPDefID() >= VPFirstPHISC && getVPDefID() <= VPLastPHISC;
786 }
787
788 /// Returns true if the recipe may read from memory.
789 bool mayReadFromMemory() const;
790
791 /// Returns true if the recipe may write to memory.
792 bool mayWriteToMemory() const;
793
794 /// Returns true if the recipe may read from or write to memory.
795 bool mayReadOrWriteMemory() const {
797 }
798
799 /// Returns the debug location of the recipe.
800 DebugLoc getDebugLoc() const { return DL; }
801};
802
803// Helper macro to define common classof implementations for recipes.
804#define VP_CLASSOF_IMPL(VPDefID) \
805 static inline bool classof(const VPDef *D) { \
806 return D->getVPDefID() == VPDefID; \
807 } \
808 static inline bool classof(const VPValue *V) { \
809 auto *R = V->getDefiningRecipe(); \
810 return R && R->getVPDefID() == VPDefID; \
811 } \
812 static inline bool classof(const VPUser *U) { \
813 auto *R = dyn_cast<VPRecipeBase>(U); \
814 return R && R->getVPDefID() == VPDefID; \
815 } \
816 static inline bool classof(const VPRecipeBase *R) { \
817 return R->getVPDefID() == VPDefID; \
818 } \
819 static inline bool classof(const VPSingleDefRecipe *R) { \
820 return R->getVPDefID() == VPDefID; \
821 }
822
823/// VPSingleDef is a base class for recipes for modeling a sequence of one or
824/// more output IR that define a single result VPValue.
825/// Note that VPRecipeBase must be inherited from before VPValue.
826class VPSingleDefRecipe : public VPRecipeBase, public VPValue {
827public:
828 template <typename IterT>
829 VPSingleDefRecipe(const unsigned char SC, IterT Operands, DebugLoc DL = {})
830 : VPRecipeBase(SC, Operands, DL), VPValue(this) {}
831
832 VPSingleDefRecipe(const unsigned char SC, ArrayRef<VPValue *> Operands,
833 DebugLoc DL = {})
834 : VPRecipeBase(SC, Operands, DL), VPValue(this) {}
835
836 template <typename IterT>
837 VPSingleDefRecipe(const unsigned char SC, IterT Operands, Value *UV,
838 DebugLoc DL = {})
839 : VPRecipeBase(SC, Operands, DL), VPValue(this, UV) {}
840
841 static inline bool classof(const VPRecipeBase *R) {
842 switch (R->getVPDefID()) {
843 case VPRecipeBase::VPDerivedIVSC:
844 case VPRecipeBase::VPEVLBasedIVPHISC:
845 case VPRecipeBase::VPExpandSCEVSC:
846 case VPRecipeBase::VPInstructionSC:
847 case VPRecipeBase::VPReductionSC:
848 case VPRecipeBase::VPReplicateSC:
849 case VPRecipeBase::VPScalarIVStepsSC:
850 case VPRecipeBase::VPVectorPointerSC:
851 case VPRecipeBase::VPWidenCallSC:
852 case VPRecipeBase::VPWidenCanonicalIVSC:
853 case VPRecipeBase::VPWidenCastSC:
854 case VPRecipeBase::VPWidenGEPSC:
855 case VPRecipeBase::VPWidenSC:
856 case VPRecipeBase::VPWidenSelectSC:
857 case VPRecipeBase::VPBlendSC:
858 case VPRecipeBase::VPPredInstPHISC:
859 case VPRecipeBase::VPCanonicalIVPHISC:
860 case VPRecipeBase::VPActiveLaneMaskPHISC:
861 case VPRecipeBase::VPFirstOrderRecurrencePHISC:
862 case VPRecipeBase::VPWidenPHISC:
863 case VPRecipeBase::VPWidenIntOrFpInductionSC:
864 case VPRecipeBase::VPWidenPointerInductionSC:
865 case VPRecipeBase::VPReductionPHISC:
866 case VPRecipeBase::VPScalarCastSC:
867 return true;
868 case VPRecipeBase::VPInterleaveSC:
869 case VPRecipeBase::VPBranchOnMaskSC:
870 case VPRecipeBase::VPWidenLoadEVLSC:
871 case VPRecipeBase::VPWidenLoadSC:
872 case VPRecipeBase::VPWidenStoreEVLSC:
873 case VPRecipeBase::VPWidenStoreSC:
874 // TODO: Widened stores don't define a value, but widened loads do. Split
875 // the recipes to be able to make widened loads VPSingleDefRecipes.
876 return false;
877 }
878 llvm_unreachable("Unhandled VPDefID");
879 }
880
881 static inline bool classof(const VPUser *U) {
882 auto *R = dyn_cast<VPRecipeBase>(U);
883 return R && classof(R);
884 }
885
886 virtual VPSingleDefRecipe *clone() override = 0;
887
888 /// Returns the underlying instruction.
890 return cast<Instruction>(getUnderlyingValue());
891 }
893 return cast<Instruction>(getUnderlyingValue());
894 }
895};
896
897/// Class to record LLVM IR flag for a recipe along with it.
899 enum class OperationType : unsigned char {
900 Cmp,
901 OverflowingBinOp,
902 DisjointOp,
903 PossiblyExactOp,
904 GEPOp,
905 FPMathOp,
906 NonNegOp,
907 Other
908 };
909
910public:
911 struct WrapFlagsTy {
912 char HasNUW : 1;
913 char HasNSW : 1;
914
916 };
917
919 char IsDisjoint : 1;
921 };
922
923protected:
924 struct GEPFlagsTy {
925 char IsInBounds : 1;
927 };
928
929private:
930 struct ExactFlagsTy {
931 char IsExact : 1;
932 };
933 struct NonNegFlagsTy {
934 char NonNeg : 1;
935 };
936 struct FastMathFlagsTy {
937 char AllowReassoc : 1;
938 char NoNaNs : 1;
939 char NoInfs : 1;
940 char NoSignedZeros : 1;
941 char AllowReciprocal : 1;
942 char AllowContract : 1;
943 char ApproxFunc : 1;
944
945 FastMathFlagsTy(const FastMathFlags &FMF);
946 };
947
948 OperationType OpType;
949
950 union {
954 ExactFlagsTy ExactFlags;
956 NonNegFlagsTy NonNegFlags;
957 FastMathFlagsTy FMFs;
958 unsigned AllFlags;
959 };
960
961protected:
963 OpType = Other.OpType;
964 AllFlags = Other.AllFlags;
965 }
966
967public:
968 template <typename IterT>
969 VPRecipeWithIRFlags(const unsigned char SC, IterT Operands, DebugLoc DL = {})
970 : VPSingleDefRecipe(SC, Operands, DL) {
971 OpType = OperationType::Other;
972 AllFlags = 0;
973 }
974
975 template <typename IterT>
976 VPRecipeWithIRFlags(const unsigned char SC, IterT Operands, Instruction &I)
978 if (auto *Op = dyn_cast<CmpInst>(&I)) {
979 OpType = OperationType::Cmp;
980 CmpPredicate = Op->getPredicate();
981 } else if (auto *Op = dyn_cast<PossiblyDisjointInst>(&I)) {
982 OpType = OperationType::DisjointOp;
983 DisjointFlags.IsDisjoint = Op->isDisjoint();
984 } else if (auto *Op = dyn_cast<OverflowingBinaryOperator>(&I)) {
985 OpType = OperationType::OverflowingBinOp;
986 WrapFlags = {Op->hasNoUnsignedWrap(), Op->hasNoSignedWrap()};
987 } else if (auto *Op = dyn_cast<PossiblyExactOperator>(&I)) {
988 OpType = OperationType::PossiblyExactOp;
989 ExactFlags.IsExact = Op->isExact();
990 } else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
991 OpType = OperationType::GEPOp;
992 GEPFlags.IsInBounds = GEP->isInBounds();
993 } else if (auto *PNNI = dyn_cast<PossiblyNonNegInst>(&I)) {
994 OpType = OperationType::NonNegOp;
995 NonNegFlags.NonNeg = PNNI->hasNonNeg();
996 } else if (auto *Op = dyn_cast<FPMathOperator>(&I)) {
997 OpType = OperationType::FPMathOp;
998 FMFs = Op->getFastMathFlags();
999 } else {
1000 OpType = OperationType::Other;
1001 AllFlags = 0;
1002 }
1003 }
1004
1005 template <typename IterT>
1006 VPRecipeWithIRFlags(const unsigned char SC, IterT Operands,
1007 CmpInst::Predicate Pred, DebugLoc DL = {})
1008 : VPSingleDefRecipe(SC, Operands, DL), OpType(OperationType::Cmp),
1009 CmpPredicate(Pred) {}
1010
1011 template <typename IterT>
1012 VPRecipeWithIRFlags(const unsigned char SC, IterT Operands,
1014 : VPSingleDefRecipe(SC, Operands, DL),
1015 OpType(OperationType::OverflowingBinOp), WrapFlags(WrapFlags) {}
1016
1017 template <typename IterT>
1018 VPRecipeWithIRFlags(const unsigned char SC, IterT Operands,
1019 FastMathFlags FMFs, DebugLoc DL = {})
1020 : VPSingleDefRecipe(SC, Operands, DL), OpType(OperationType::FPMathOp),
1021 FMFs(FMFs) {}
1022
1023 template <typename IterT>
1024 VPRecipeWithIRFlags(const unsigned char SC, IterT Operands,
1026 : VPSingleDefRecipe(SC, Operands, DL), OpType(OperationType::DisjointOp),
1028
1029protected:
1030 template <typename IterT>
1031 VPRecipeWithIRFlags(const unsigned char SC, IterT Operands,
1032 GEPFlagsTy GEPFlags, DebugLoc DL = {})
1033 : VPSingleDefRecipe(SC, Operands, DL), OpType(OperationType::GEPOp),
1034 GEPFlags(GEPFlags) {}
1035
1036public:
1037 static inline bool classof(const VPRecipeBase *R) {
1038 return R->getVPDefID() == VPRecipeBase::VPInstructionSC ||
1039 R->getVPDefID() == VPRecipeBase::VPWidenSC ||
1040 R->getVPDefID() == VPRecipeBase::VPWidenGEPSC ||
1041 R->getVPDefID() == VPRecipeBase::VPWidenCastSC ||
1042 R->getVPDefID() == VPRecipeBase::VPReplicateSC ||
1043 R->getVPDefID() == VPRecipeBase::VPVectorPointerSC;
1044 }
1045
1046 static inline bool classof(const VPUser *U) {
1047 auto *R = dyn_cast<VPRecipeBase>(U);
1048 return R && classof(R);
1049 }
1050
1051 /// Drop all poison-generating flags.
1053 // NOTE: This needs to be kept in-sync with
1054 // Instruction::dropPoisonGeneratingFlags.
1055 switch (OpType) {
1056 case OperationType::OverflowingBinOp:
1057 WrapFlags.HasNUW = false;
1058 WrapFlags.HasNSW = false;
1059 break;
1060 case OperationType::DisjointOp:
1061 DisjointFlags.IsDisjoint = false;
1062 break;
1063 case OperationType::PossiblyExactOp:
1064 ExactFlags.IsExact = false;
1065 break;
1066 case OperationType::GEPOp:
1067 GEPFlags.IsInBounds = false;
1068 break;
1069 case OperationType::FPMathOp:
1070 FMFs.NoNaNs = false;
1071 FMFs.NoInfs = false;
1072 break;
1073 case OperationType::NonNegOp:
1074 NonNegFlags.NonNeg = false;
1075 break;
1076 case OperationType::Cmp:
1077 case OperationType::Other:
1078 break;
1079 }
1080 }
1081
1082 /// Set the IR flags for \p I.
1083 void setFlags(Instruction *I) const {
1084 switch (OpType) {
1085 case OperationType::OverflowingBinOp:
1086 I->setHasNoUnsignedWrap(WrapFlags.HasNUW);
1087 I->setHasNoSignedWrap(WrapFlags.HasNSW);
1088 break;
1089 case OperationType::DisjointOp:
1090 cast<PossiblyDisjointInst>(I)->setIsDisjoint(DisjointFlags.IsDisjoint);
1091 break;
1092 case OperationType::PossiblyExactOp:
1093 I->setIsExact(ExactFlags.IsExact);
1094 break;
1095 case OperationType::GEPOp:
1096 cast<GetElementPtrInst>(I)->setIsInBounds(GEPFlags.IsInBounds);
1097 break;
1098 case OperationType::FPMathOp:
1099 I->setHasAllowReassoc(FMFs.AllowReassoc);
1100 I->setHasNoNaNs(FMFs.NoNaNs);
1101 I->setHasNoInfs(FMFs.NoInfs);
1102 I->setHasNoSignedZeros(FMFs.NoSignedZeros);
1103 I->setHasAllowReciprocal(FMFs.AllowReciprocal);
1104 I->setHasAllowContract(FMFs.AllowContract);
1105 I->setHasApproxFunc(FMFs.ApproxFunc);
1106 break;
1107 case OperationType::NonNegOp:
1108 I->setNonNeg(NonNegFlags.NonNeg);
1109 break;
1110 case OperationType::Cmp:
1111 case OperationType::Other:
1112 break;
1113 }
1114 }
1115
1117 assert(OpType == OperationType::Cmp &&
1118 "recipe doesn't have a compare predicate");
1119 return CmpPredicate;
1120 }
1121
1122 bool isInBounds() const {
1123 assert(OpType == OperationType::GEPOp &&
1124 "recipe doesn't have inbounds flag");
1125 return GEPFlags.IsInBounds;
1126 }
1127
1128 /// Returns true if the recipe has fast-math flags.
1129 bool hasFastMathFlags() const { return OpType == OperationType::FPMathOp; }
1130
1132
1133 bool hasNoUnsignedWrap() const {
1134 assert(OpType == OperationType::OverflowingBinOp &&
1135 "recipe doesn't have a NUW flag");
1136 return WrapFlags.HasNUW;
1137 }
1138
1139 bool hasNoSignedWrap() const {
1140 assert(OpType == OperationType::OverflowingBinOp &&
1141 "recipe doesn't have a NSW flag");
1142 return WrapFlags.HasNSW;
1143 }
1144
1145 bool isDisjoint() const {
1146 assert(OpType == OperationType::DisjointOp &&
1147 "recipe cannot have a disjoing flag");
1149 }
1150
1151#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1152 void printFlags(raw_ostream &O) const;
1153#endif
1154};
1155
1156/// This is a concrete Recipe that models a single VPlan-level instruction.
1157/// While as any Recipe it may generate a sequence of IR instructions when
1158/// executed, these instructions would always form a single-def expression as
1159/// the VPInstruction is also a single def-use vertex.
1161 friend class VPlanSlp;
1162
1163public:
1164 /// VPlan opcodes, extending LLVM IR with idiomatics instructions.
1165 enum {
1167 Instruction::OtherOpsEnd + 1, // Combines the incoming and previous
1168 // values of a first-order recurrence.
1175 // Increment the canonical IV separately for each unrolled part.
1180 // Add an offset in bytes (second operand) to a base pointer (first
1181 // operand). Only generates scalar values (either for the first lane only or
1182 // for all lanes, depending on its uses).
1184 };
1185
1186private:
1187 typedef unsigned char OpcodeTy;
1188 OpcodeTy Opcode;
1189
1190 /// An optional name that can be used for the generated IR instruction.
1191 const std::string Name;
1192
1193 /// Returns true if this VPInstruction generates scalar values for all lanes.
1194 /// Most VPInstructions generate a single value per part, either vector or
1195 /// scalar. VPReplicateRecipe takes care of generating multiple (scalar)
1196 /// values per all lanes, stemming from an original ingredient. This method
1197 /// identifies the (rare) cases of VPInstructions that do so as well, w/o an
1198 /// underlying ingredient.
1199 bool doesGeneratePerAllLanes() const;
1200
1201 /// Returns true if we can generate a scalar for the first lane only if
1202 /// needed.
1203 bool canGenerateScalarForFirstLane() const;
1204
1205 /// Utility methods serving execute(): generates a single instance of the
1206 /// modeled instruction for a given part. \returns the generated value for \p
1207 /// Part. In some cases an existing value is returned rather than a generated
1208 /// one.
1209 Value *generatePerPart(VPTransformState &State, unsigned Part);
1210
1211 /// Utility methods serving execute(): generates a scalar single instance of
1212 /// the modeled instruction for a given lane. \returns the scalar generated
1213 /// value for lane \p Lane.
1214 Value *generatePerLane(VPTransformState &State, const VPIteration &Lane);
1215
1216#if !defined(NDEBUG)
1217 /// Return true if the VPInstruction is a floating point math operation, i.e.
1218 /// has fast-math flags.
1219 bool isFPMathOp() const;
1220#endif
1221
1222public:
1224 const Twine &Name = "")
1225 : VPRecipeWithIRFlags(VPDef::VPInstructionSC, Operands, DL),
1226 Opcode(Opcode), Name(Name.str()) {}
1227
1228 VPInstruction(unsigned Opcode, std::initializer_list<VPValue *> Operands,
1229 DebugLoc DL = {}, const Twine &Name = "")
1231
1232 VPInstruction(unsigned Opcode, CmpInst::Predicate Pred, VPValue *A,
1233 VPValue *B, DebugLoc DL = {}, const Twine &Name = "");
1234
1235 VPInstruction(unsigned Opcode, std::initializer_list<VPValue *> Operands,
1236 WrapFlagsTy WrapFlags, DebugLoc DL = {}, const Twine &Name = "")
1237 : VPRecipeWithIRFlags(VPDef::VPInstructionSC, Operands, WrapFlags, DL),
1238 Opcode(Opcode), Name(Name.str()) {}
1239
1240 VPInstruction(unsigned Opcode, std::initializer_list<VPValue *> Operands,
1241 DisjointFlagsTy DisjointFlag, DebugLoc DL = {},
1242 const Twine &Name = "")
1243 : VPRecipeWithIRFlags(VPDef::VPInstructionSC, Operands, DisjointFlag, DL),
1244 Opcode(Opcode), Name(Name.str()) {
1245 assert(Opcode == Instruction::Or && "only OR opcodes can be disjoint");
1246 }
1247
1248 VPInstruction(unsigned Opcode, std::initializer_list<VPValue *> Operands,
1249 FastMathFlags FMFs, DebugLoc DL = {}, const Twine &Name = "");
1250
1251 VP_CLASSOF_IMPL(VPDef::VPInstructionSC)
1252
1253 VPInstruction *clone() override {
1255 auto *New = new VPInstruction(Opcode, Operands, getDebugLoc(), Name);
1256 New->transferFlags(*this);
1257 return New;
1258 }
1259
1260 unsigned getOpcode() const { return Opcode; }
1261
1262 /// Generate the instruction.
1263 /// TODO: We currently execute only per-part unless a specific instance is
1264 /// provided.
1265 void execute(VPTransformState &State) override;
1266
1267#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1268 /// Print the VPInstruction to \p O.
1269 void print(raw_ostream &O, const Twine &Indent,
1270 VPSlotTracker &SlotTracker) const override;
1271
1272 /// Print the VPInstruction to dbgs() (for debugging).
1273 LLVM_DUMP_METHOD void dump() const;
1274#endif
1275
1276 /// Return true if this instruction may modify memory.
1277 bool mayWriteToMemory() const {
1278 // TODO: we can use attributes of the called function to rule out memory
1279 // modifications.
1280 return Opcode == Instruction::Store || Opcode == Instruction::Call ||
1281 Opcode == Instruction::Invoke || Opcode == SLPStore;
1282 }
1283
1284 bool hasResult() const {
1285 // CallInst may or may not have a result, depending on the called function.
1286 // Conservatively return calls have results for now.
1287 switch (getOpcode()) {
1288 case Instruction::Ret:
1289 case Instruction::Br:
1290 case Instruction::Store:
1291 case Instruction::Switch:
1292 case Instruction::IndirectBr:
1293 case Instruction::Resume:
1294 case Instruction::CatchRet:
1295 case Instruction::Unreachable:
1296 case Instruction::Fence:
1297 case Instruction::AtomicRMW:
1300 return false;
1301 default:
1302 return true;
1303 }
1304 }
1305
1306 /// Returns true if the recipe only uses the first lane of operand \p Op.
1307 bool onlyFirstLaneUsed(const VPValue *Op) const override;
1308
1309 /// Returns true if the recipe only uses the first part of operand \p Op.
1310 bool onlyFirstPartUsed(const VPValue *Op) const override {
1312 "Op must be an operand of the recipe");
1313 if (getOperand(0) != Op)
1314 return false;
1315 switch (getOpcode()) {
1316 default:
1317 return false;
1320 return true;
1321 };
1322 llvm_unreachable("switch should return");
1323 }
1324};
1325
1326/// VPWidenRecipe is a recipe for producing a copy of vector type its
1327/// ingredient. This recipe covers most of the traditional vectorization cases
1328/// where each ingredient transforms into a vectorized version of itself.
1330 unsigned Opcode;
1331
1332public:
1333 template <typename IterT>
1335 : VPRecipeWithIRFlags(VPDef::VPWidenSC, Operands, I),
1336 Opcode(I.getOpcode()) {}
1337
1338 ~VPWidenRecipe() override = default;
1339
1340 VPWidenRecipe *clone() override {
1341 auto *R = new VPWidenRecipe(*getUnderlyingInstr(), operands());
1342 R->transferFlags(*this);
1343 return R;
1344 }
1345
1346 VP_CLASSOF_IMPL(VPDef::VPWidenSC)
1347
1348 /// Produce widened copies of all Ingredients.
1349 void execute(VPTransformState &State) override;
1350
1351 unsigned getOpcode() const { return Opcode; }
1352
1353#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1354 /// Print the recipe.
1355 void print(raw_ostream &O, const Twine &Indent,
1356 VPSlotTracker &SlotTracker) const override;
1357#endif
1358};
1359
1360/// VPWidenCastRecipe is a recipe to create vector cast instructions.
1362 /// Cast instruction opcode.
1363 Instruction::CastOps Opcode;
1364
1365 /// Result type for the cast.
1366 Type *ResultTy;
1367
1368public:
1370 CastInst &UI)
1371 : VPRecipeWithIRFlags(VPDef::VPWidenCastSC, Op, UI), Opcode(Opcode),
1372 ResultTy(ResultTy) {
1373 assert(UI.getOpcode() == Opcode &&
1374 "opcode of underlying cast doesn't match");
1375 assert(UI.getType() == ResultTy &&
1376 "result type of underlying cast doesn't match");
1377 }
1378
1380 : VPRecipeWithIRFlags(VPDef::VPWidenCastSC, Op), Opcode(Opcode),
1381 ResultTy(ResultTy) {}
1382
1383 ~VPWidenCastRecipe() override = default;
1384
1386 if (auto *UV = getUnderlyingValue())
1387 return new VPWidenCastRecipe(Opcode, getOperand(0), ResultTy,
1388 *cast<CastInst>(UV));
1389
1390 return new VPWidenCastRecipe(Opcode, getOperand(0), ResultTy);
1391 }
1392
1393 VP_CLASSOF_IMPL(VPDef::VPWidenCastSC)
1394
1395 /// Produce widened copies of the cast.
1396 void execute(VPTransformState &State) override;
1397
1398#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1399 /// Print the recipe.
1400 void print(raw_ostream &O, const Twine &Indent,
1401 VPSlotTracker &SlotTracker) const override;
1402#endif
1403
1404 Instruction::CastOps getOpcode() const { return Opcode; }
1405
1406 /// Returns the result type of the cast.
1407 Type *getResultType() const { return ResultTy; }
1408};
1409
1410/// VPScalarCastRecipe is a recipe to create scalar cast instructions.
1412 Instruction::CastOps Opcode;
1413
1414 Type *ResultTy;
1415
1416 Value *generate(VPTransformState &State, unsigned Part);
1417
1418public:
1420 : VPSingleDefRecipe(VPDef::VPScalarCastSC, {Op}), Opcode(Opcode),
1421 ResultTy(ResultTy) {}
1422
1423 ~VPScalarCastRecipe() override = default;
1424
1426 return new VPScalarCastRecipe(Opcode, getOperand(0), ResultTy);
1427 }
1428
1429 VP_CLASSOF_IMPL(VPDef::VPScalarCastSC)
1430
1431 void execute(VPTransformState &State) override;
1432
1433#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1434 void print(raw_ostream &O, const Twine &Indent,
1435 VPSlotTracker &SlotTracker) const override;
1436#endif
1437
1438 /// Returns the result type of the cast.
1439 Type *getResultType() const { return ResultTy; }
1440
1441 bool onlyFirstLaneUsed(const VPValue *Op) const override {
1442 // At the moment, only uniform codegen is implemented.
1444 "Op must be an operand of the recipe");
1445 return true;
1446 }
1447};
1448
1449/// A recipe for widening Call instructions.
1451 /// ID of the vector intrinsic to call when widening the call. If set the
1452 /// Intrinsic::not_intrinsic, a library call will be used instead.
1453 Intrinsic::ID VectorIntrinsicID;
1454 /// If this recipe represents a library call, Variant stores a pointer to
1455 /// the chosen function. There is a 1:1 mapping between a given VF and the
1456 /// chosen vectorized variant, so there will be a different vplan for each
1457 /// VF with a valid variant.
1458 Function *Variant;
1459
1460public:
1461 template <typename IterT>
1463 Intrinsic::ID VectorIntrinsicID, DebugLoc DL = {},
1464 Function *Variant = nullptr)
1465 : VPSingleDefRecipe(VPDef::VPWidenCallSC, CallArguments, UV, DL),
1466 VectorIntrinsicID(VectorIntrinsicID), Variant(Variant) {
1467 assert(
1468 isa<Function>(getOperand(getNumOperands() - 1)->getLiveInIRValue()) &&
1469 "last operand must be the called function");
1470 }
1471
1472 ~VPWidenCallRecipe() override = default;
1473
1476 VectorIntrinsicID, getDebugLoc(), Variant);
1477 }
1478
1479 VP_CLASSOF_IMPL(VPDef::VPWidenCallSC)
1480
1481 /// Produce a widened version of the call instruction.
1482 void execute(VPTransformState &State) override;
1483
1485 return cast<Function>(getOperand(getNumOperands() - 1)->getLiveInIRValue());
1486 }
1487
1489 return make_range(op_begin(), op_begin() + getNumOperands() - 1);
1490 }
1492 return make_range(op_begin(), op_begin() + getNumOperands() - 1);
1493 }
1494
1495#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1496 /// Print the recipe.
1497 void print(raw_ostream &O, const Twine &Indent,
1498 VPSlotTracker &SlotTracker) const override;
1499#endif
1500};
1501
1502/// A recipe for widening select instructions.
1504 template <typename IterT>
1506 : VPSingleDefRecipe(VPDef::VPWidenSelectSC, Operands, &I,
1507 I.getDebugLoc()) {}
1508
1509 ~VPWidenSelectRecipe() override = default;
1510
1512 return new VPWidenSelectRecipe(*cast<SelectInst>(getUnderlyingInstr()),
1513 operands());
1514 }
1515
1516 VP_CLASSOF_IMPL(VPDef::VPWidenSelectSC)
1517
1518 /// Produce a widened version of the select instruction.
1519 void execute(VPTransformState &State) override;
1520
1521#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1522 /// Print the recipe.
1523 void print(raw_ostream &O, const Twine &Indent,
1524 VPSlotTracker &SlotTracker) const override;
1525#endif
1526
1527 VPValue *getCond() const {
1528 return getOperand(0);
1529 }
1530
1531 bool isInvariantCond() const {
1533 }
1534};
1535
1536/// A recipe for handling GEP instructions.
1538 bool isPointerLoopInvariant() const {
1540 }
1541
1542 bool isIndexLoopInvariant(unsigned I) const {
1544 }
1545
1546 bool areAllOperandsInvariant() const {
1547 return all_of(operands(), [](VPValue *Op) {
1548 return Op->isDefinedOutsideVectorRegions();
1549 });
1550 }
1551
1552public:
1553 template <typename IterT>
1555 : VPRecipeWithIRFlags(VPDef::VPWidenGEPSC, Operands, *GEP) {}
1556
1557 ~VPWidenGEPRecipe() override = default;
1558
1560 return new VPWidenGEPRecipe(cast<GetElementPtrInst>(getUnderlyingInstr()),
1561 operands());
1562 }
1563
1564 VP_CLASSOF_IMPL(VPDef::VPWidenGEPSC)
1565
1566 /// Generate the gep nodes.
1567 void execute(VPTransformState &State) override;
1568
1569#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1570 /// Print the recipe.
1571 void print(raw_ostream &O, const Twine &Indent,
1572 VPSlotTracker &SlotTracker) const override;
1573#endif
1574};
1575
1576/// A recipe to compute the pointers for widened memory accesses of IndexTy for
1577/// all parts. If IsReverse is true, compute pointers for accessing the input in
1578/// reverse order per part.
1580 Type *IndexedTy;
1581 bool IsReverse;
1582
1583public:
1584 VPVectorPointerRecipe(VPValue *Ptr, Type *IndexedTy, bool IsReverse,
1585 bool IsInBounds, DebugLoc DL)
1586 : VPRecipeWithIRFlags(VPDef::VPVectorPointerSC, ArrayRef<VPValue *>(Ptr),
1587 GEPFlagsTy(IsInBounds), DL),
1588 IndexedTy(IndexedTy), IsReverse(IsReverse) {}
1589
1590 VP_CLASSOF_IMPL(VPDef::VPVectorPointerSC)
1591
1592 void execute(VPTransformState &State) override;
1593
1594 bool onlyFirstLaneUsed(const VPValue *Op) const override {
1596 "Op must be an operand of the recipe");
1597 return true;
1598 }
1599
1601 return new VPVectorPointerRecipe(getOperand(0), IndexedTy, IsReverse,
1602 isInBounds(), getDebugLoc());
1603 }
1604
1605#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1606 /// Print the recipe.
1607 void print(raw_ostream &O, const Twine &Indent,
1608 VPSlotTracker &SlotTracker) const override;
1609#endif
1610};
1611
1612/// A pure virtual base class for all recipes modeling header phis, including
1613/// phis for first order recurrences, pointer inductions and reductions. The
1614/// start value is the first operand of the recipe and the incoming value from
1615/// the backedge is the second operand.
1616///
1617/// Inductions are modeled using the following sub-classes:
1618/// * VPCanonicalIVPHIRecipe: Canonical scalar induction of the vector loop,
1619/// starting at a specified value (zero for the main vector loop, the resume
1620/// value for the epilogue vector loop) and stepping by 1. The induction
1621/// controls exiting of the vector loop by comparing against the vector trip
1622/// count. Produces a single scalar PHI for the induction value per
1623/// iteration.
1624/// * VPWidenIntOrFpInductionRecipe: Generates vector values for integer and
1625/// floating point inductions with arbitrary start and step values. Produces
1626/// a vector PHI per-part.
1627/// * VPDerivedIVRecipe: Converts the canonical IV value to the corresponding
1628/// value of an IV with different start and step values. Produces a single
1629/// scalar value per iteration
1630/// * VPScalarIVStepsRecipe: Generates scalar values per-lane based on a
1631/// canonical or derived induction.
1632/// * VPWidenPointerInductionRecipe: Generate vector and scalar values for a
1633/// pointer induction. Produces either a vector PHI per-part or scalar values
1634/// per-lane based on the canonical induction.
1636protected:
1637 VPHeaderPHIRecipe(unsigned char VPDefID, Instruction *UnderlyingInstr,
1638 VPValue *Start = nullptr, DebugLoc DL = {})
1639 : VPSingleDefRecipe(VPDefID, ArrayRef<VPValue *>(), UnderlyingInstr, DL) {
1640 if (Start)
1641 addOperand(Start);
1642 }
1643
1644public:
1645 ~VPHeaderPHIRecipe() override = default;
1646
1647 /// Method to support type inquiry through isa, cast, and dyn_cast.
1648 static inline bool classof(const VPRecipeBase *B) {
1649 return B->getVPDefID() >= VPDef::VPFirstHeaderPHISC &&
1650 B->getVPDefID() <= VPDef::VPLastHeaderPHISC;
1651 }
1652 static inline bool classof(const VPValue *V) {
1653 auto *B = V->getDefiningRecipe();
1654 return B && B->getVPDefID() >= VPRecipeBase::VPFirstHeaderPHISC &&
1655 B->getVPDefID() <= VPRecipeBase::VPLastHeaderPHISC;
1656 }
1657
1658 /// Generate the phi nodes.
1659 void execute(VPTransformState &State) override = 0;
1660
1661#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1662 /// Print the recipe.
1663 void print(raw_ostream &O, const Twine &Indent,
1664 VPSlotTracker &SlotTracker) const override = 0;
1665#endif
1666
1667 /// Returns the start value of the phi, if one is set.
1669 return getNumOperands() == 0 ? nullptr : getOperand(0);
1670 }
1672 return getNumOperands() == 0 ? nullptr : getOperand(0);
1673 }
1674
1675 /// Update the start value of the recipe.
1677
1678 /// Returns the incoming value from the loop backedge.
1680 return getOperand(1);
1681 }
1682
1683 /// Returns the backedge value as a recipe. The backedge value is guaranteed
1684 /// to be a recipe.
1687 }
1688};
1689
1690/// A recipe for handling phi nodes of integer and floating-point inductions,
1691/// producing their vector values.
1693 PHINode *IV;
1694 TruncInst *Trunc;
1695 const InductionDescriptor &IndDesc;
1696
1697public:
1699 const InductionDescriptor &IndDesc)
1700 : VPHeaderPHIRecipe(VPDef::VPWidenIntOrFpInductionSC, IV, Start), IV(IV),
1701 Trunc(nullptr), IndDesc(IndDesc) {
1702 addOperand(Step);
1703 }
1704
1706 const InductionDescriptor &IndDesc,
1707 TruncInst *Trunc)
1708 : VPHeaderPHIRecipe(VPDef::VPWidenIntOrFpInductionSC, Trunc, Start),
1709 IV(IV), Trunc(Trunc), IndDesc(IndDesc) {
1710 addOperand(Step);
1711 }
1712
1714
1717 getStepValue(), IndDesc, Trunc);
1718 }
1719
1720 VP_CLASSOF_IMPL(VPDef::VPWidenIntOrFpInductionSC)
1721
1722 /// Generate the vectorized and scalarized versions of the phi node as
1723 /// needed by their users.
1724 void execute(VPTransformState &State) override;
1725
1726#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1727 /// Print the recipe.
1728 void print(raw_ostream &O, const Twine &Indent,
1729 VPSlotTracker &SlotTracker) const override;
1730#endif
1731
1733 // TODO: All operands of base recipe must exist and be at same index in
1734 // derived recipe.
1736 "VPWidenIntOrFpInductionRecipe generates its own backedge value");
1737 }
1738
1740 // TODO: All operands of base recipe must exist and be at same index in
1741 // derived recipe.
1743 "VPWidenIntOrFpInductionRecipe generates its own backedge value");
1744 }
1745
1746 /// Returns the step value of the induction.
1748 const VPValue *getStepValue() const { return getOperand(1); }
1749
1750 /// Returns the first defined value as TruncInst, if it is one or nullptr
1751 /// otherwise.
1752 TruncInst *getTruncInst() { return Trunc; }
1753 const TruncInst *getTruncInst() const { return Trunc; }
1754
1755 PHINode *getPHINode() { return IV; }
1756
1757 /// Returns the induction descriptor for the recipe.
1758 const InductionDescriptor &getInductionDescriptor() const { return IndDesc; }
1759
1760 /// Returns true if the induction is canonical, i.e. starting at 0 and
1761 /// incremented by UF * VF (= the original IV is incremented by 1) and has the
1762 /// same type as the canonical induction.
1763 bool isCanonical() const;
1764
1765 /// Returns the scalar type of the induction.
1767 return Trunc ? Trunc->getType() : IV->getType();
1768 }
1769};
1770
1772 const InductionDescriptor &IndDesc;
1773
1774 bool IsScalarAfterVectorization;
1775
1776public:
1777 /// Create a new VPWidenPointerInductionRecipe for \p Phi with start value \p
1778 /// Start.
1780 const InductionDescriptor &IndDesc,
1781 bool IsScalarAfterVectorization)
1782 : VPHeaderPHIRecipe(VPDef::VPWidenPointerInductionSC, Phi),
1783 IndDesc(IndDesc),
1784 IsScalarAfterVectorization(IsScalarAfterVectorization) {
1785 addOperand(Start);
1786 addOperand(Step);
1787 }
1788
1790
1793 cast<PHINode>(getUnderlyingInstr()), getOperand(0), getOperand(1),
1794 IndDesc, IsScalarAfterVectorization);
1795 }
1796
1797 VP_CLASSOF_IMPL(VPDef::VPWidenPointerInductionSC)
1798
1799 /// Generate vector values for the pointer induction.
1800 void execute(VPTransformState &State) override;
1801
1802 /// Returns true if only scalar values will be generated.
1803 bool onlyScalarsGenerated(bool IsScalable);
1804
1805 /// Returns the induction descriptor for the recipe.
1806 const InductionDescriptor &getInductionDescriptor() const { return IndDesc; }
1807
1808#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1809 /// Print the recipe.
1810 void print(raw_ostream &O, const Twine &Indent,
1811 VPSlotTracker &SlotTracker) const override;
1812#endif
1813};
1814
1815/// A recipe for handling phis that are widened in the vector loop.
1816/// In the VPlan native path, all incoming VPValues & VPBasicBlock pairs are
1817/// managed in the recipe directly.
1819 /// List of incoming blocks. Only used in the VPlan native path.
1820 SmallVector<VPBasicBlock *, 2> IncomingBlocks;
1821
1822public:
1823 /// Create a new VPWidenPHIRecipe for \p Phi with start value \p Start.
1824 VPWidenPHIRecipe(PHINode *Phi, VPValue *Start = nullptr)
1825 : VPSingleDefRecipe(VPDef::VPWidenPHISC, ArrayRef<VPValue *>(), Phi) {
1826 if (Start)
1827 addOperand(Start);
1828 }
1829
1831 llvm_unreachable("cloning not implemented yet");
1832 }
1833
1834 ~VPWidenPHIRecipe() override = default;
1835
1836 VP_CLASSOF_IMPL(VPDef::VPWidenPHISC)
1837
1838 /// Generate the phi/select nodes.
1839 void execute(VPTransformState &State) override;
1840
1841#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1842 /// Print the recipe.
1843 void print(raw_ostream &O, const Twine &Indent,
1844 VPSlotTracker &SlotTracker) const override;
1845#endif
1846
1847 /// Adds a pair (\p IncomingV, \p IncomingBlock) to the phi.
1848 void addIncoming(VPValue *IncomingV, VPBasicBlock *IncomingBlock) {
1849 addOperand(IncomingV);
1850 IncomingBlocks.push_back(IncomingBlock);
1851 }
1852
1853 /// Returns the \p I th incoming VPBasicBlock.
1854 VPBasicBlock *getIncomingBlock(unsigned I) { return IncomingBlocks[I]; }
1855
1856 /// Returns the \p I th incoming VPValue.
1857 VPValue *getIncomingValue(unsigned I) { return getOperand(I); }
1858};
1859
1860/// A recipe for handling first-order recurrence phis. The start value is the
1861/// first operand of the recipe and the incoming value from the backedge is the
1862/// second operand.
1865 : VPHeaderPHIRecipe(VPDef::VPFirstOrderRecurrencePHISC, Phi, &Start) {}
1866
1867 VP_CLASSOF_IMPL(VPDef::VPFirstOrderRecurrencePHISC)
1868
1870 return R->getVPDefID() == VPDef::VPFirstOrderRecurrencePHISC;
1871 }
1872
1875 cast<PHINode>(getUnderlyingInstr()), *getOperand(0));
1876 }
1877
1878 void execute(VPTransformState &State) override;
1879
1880#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1881 /// Print the recipe.
1882 void print(raw_ostream &O, const Twine &Indent,
1883 VPSlotTracker &SlotTracker) const override;
1884#endif
1885};
1886
1887/// A recipe for handling reduction phis. The start value is the first operand
1888/// of the recipe and the incoming value from the backedge is the second
1889/// operand.
1891 /// Descriptor for the reduction.
1892 const RecurrenceDescriptor &RdxDesc;
1893
1894 /// The phi is part of an in-loop reduction.
1895 bool IsInLoop;
1896
1897 /// The phi is part of an ordered reduction. Requires IsInLoop to be true.
1898 bool IsOrdered;
1899
1900public:
1901 /// Create a new VPReductionPHIRecipe for the reduction \p Phi described by \p
1902 /// RdxDesc.
1904 VPValue &Start, bool IsInLoop = false,
1905 bool IsOrdered = false)
1906 : VPHeaderPHIRecipe(VPDef::VPReductionPHISC, Phi, &Start),
1907 RdxDesc(RdxDesc), IsInLoop(IsInLoop), IsOrdered(IsOrdered) {
1908 assert((!IsOrdered || IsInLoop) && "IsOrdered requires IsInLoop");
1909 }
1910
1911 ~VPReductionPHIRecipe() override = default;
1912
1914 auto *R =
1915 new VPReductionPHIRecipe(cast<PHINode>(getUnderlyingInstr()), RdxDesc,
1916 *getOperand(0), IsInLoop, IsOrdered);
1917 R->addOperand(getBackedgeValue());
1918 return R;
1919 }
1920
1921 VP_CLASSOF_IMPL(VPDef::VPReductionPHISC)
1922
1924 return R->getVPDefID() == VPDef::VPReductionPHISC;
1925 }
1926
1927 /// Generate the phi/select nodes.
1928 void execute(VPTransformState &State) override;
1929
1930#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1931 /// Print the recipe.
1932 void print(raw_ostream &O, const Twine &Indent,
1933 VPSlotTracker &SlotTracker) const override;
1934#endif
1935
1937 return RdxDesc;
1938 }
1939
1940 /// Returns true, if the phi is part of an ordered reduction.
1941 bool isOrdered() const { return IsOrdered; }
1942
1943 /// Returns true, if the phi is part of an in-loop reduction.
1944 bool isInLoop() const { return IsInLoop; }
1945};
1946
1947/// A recipe for vectorizing a phi-node as a sequence of mask-based select
1948/// instructions.
1950public:
1951 /// The blend operation is a User of the incoming values and of their
1952 /// respective masks, ordered [I0, I1, M1, I2, M2, ...]. Note that the first
1953 /// incoming value does not have a mask associated.
1955 : VPSingleDefRecipe(VPDef::VPBlendSC, Operands, Phi, Phi->getDebugLoc()) {
1956 assert((Operands.size() + 1) % 2 == 0 &&
1957 "Expected an odd number of operands");
1958 }
1959
1960 VPBlendRecipe *clone() override {
1962 return new VPBlendRecipe(cast<PHINode>(getUnderlyingValue()), Ops);
1963 }
1964
1965 VP_CLASSOF_IMPL(VPDef::VPBlendSC)
1966
1967 /// Return the number of incoming values, taking into account that the first
1968 /// incoming value has no mask.
1969 unsigned getNumIncomingValues() const { return (getNumOperands() + 1) / 2; }
1970
1971 /// Return incoming value number \p Idx.
1972 VPValue *getIncomingValue(unsigned Idx) const {
1973 return Idx == 0 ? getOperand(0) : getOperand(Idx * 2 - 1);
1974 }
1975
1976 /// Return mask number \p Idx.
1977 VPValue *getMask(unsigned Idx) const {
1978 assert(Idx > 0 && "First index has no mask associated.");
1979 return getOperand(Idx * 2);
1980 }
1981
1982 /// Generate the phi/select nodes.
1983 void execute(VPTransformState &State) override;
1984
1985#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1986 /// Print the recipe.
1987 void print(raw_ostream &O, const Twine &Indent,
1988 VPSlotTracker &SlotTracker) const override;
1989#endif
1990
1991 /// Returns true if the recipe only uses the first lane of operand \p Op.
1992 bool onlyFirstLaneUsed(const VPValue *Op) const override {
1994 "Op must be an operand of the recipe");
1995 // Recursing through Blend recipes only, must terminate at header phi's the
1996 // latest.
1997 return all_of(users(),
1998 [this](VPUser *U) { return U->onlyFirstLaneUsed(this); });
1999 }
2000};
2001
2002/// VPInterleaveRecipe is a recipe for transforming an interleave group of load
2003/// or stores into one wide load/store and shuffles. The first operand of a
2004/// VPInterleave recipe is the address, followed by the stored values, followed
2005/// by an optional mask.
2008
2009 /// Indicates if the interleave group is in a conditional block and requires a
2010 /// mask.
2011 bool HasMask = false;
2012
2013 /// Indicates if gaps between members of the group need to be masked out or if
2014 /// unusued gaps can be loaded speculatively.
2015 bool NeedsMaskForGaps = false;
2016
2017public:
2019 ArrayRef<VPValue *> StoredValues, VPValue *Mask,
2020 bool NeedsMaskForGaps)
2021 : VPRecipeBase(VPDef::VPInterleaveSC, {Addr}), IG(IG),
2022 NeedsMaskForGaps(NeedsMaskForGaps) {
2023 for (unsigned i = 0; i < IG->getFactor(); ++i)
2024 if (Instruction *I = IG->getMember(i)) {
2025 if (I->getType()->isVoidTy())
2026 continue;
2027 new VPValue(I, this);
2028 }
2029
2030 for (auto *SV : StoredValues)
2031 addOperand(SV);
2032 if (Mask) {
2033 HasMask = true;
2034 addOperand(Mask);
2035 }
2036 }
2037 ~VPInterleaveRecipe() override = default;
2038
2040 return new VPInterleaveRecipe(IG, getAddr(), getStoredValues(), getMask(),
2041 NeedsMaskForGaps);
2042 }
2043
2044 VP_CLASSOF_IMPL(VPDef::VPInterleaveSC)
2045
2046 /// Return the address accessed by this recipe.
2047 VPValue *getAddr() const {
2048 return getOperand(0); // Address is the 1st, mandatory operand.
2049 }
2050
2051 /// Return the mask used by this recipe. Note that a full mask is represented
2052 /// by a nullptr.
2053 VPValue *getMask() const {
2054 // Mask is optional and therefore the last, currently 2nd operand.
2055 return HasMask ? getOperand(getNumOperands() - 1) : nullptr;
2056 }
2057
2058 /// Return the VPValues stored by this interleave group. If it is a load
2059 /// interleave group, return an empty ArrayRef.
2061 // The first operand is the address, followed by the stored values, followed
2062 // by an optional mask.
2065 }
2066
2067 /// Generate the wide load or store, and shuffles.
2068 void execute(VPTransformState &State) override;
2069
2070#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2071 /// Print the recipe.
2072 void print(raw_ostream &O, const Twine &Indent,
2073 VPSlotTracker &SlotTracker) const override;
2074#endif
2075
2077
2078 /// Returns the number of stored operands of this interleave group. Returns 0
2079 /// for load interleave groups.
2080 unsigned getNumStoreOperands() const {
2081 return getNumOperands() - (HasMask ? 2 : 1);
2082 }
2083
2084 /// The recipe only uses the first lane of the address.
2085 bool onlyFirstLaneUsed(const VPValue *Op) const override {
2087 "Op must be an operand of the recipe");
2088 return Op == getAddr() && !llvm::is_contained(getStoredValues(), Op);
2089 }
2090};
2091
2092/// A recipe to represent inloop reduction operations, performing a reduction on
2093/// a vector operand into a scalar value, and adding the result to a chain.
2094/// The Operands are {ChainOp, VecOp, [Condition]}.
2096 /// The recurrence decriptor for the reduction in question.
2097 const RecurrenceDescriptor &RdxDesc;
2098 bool IsOrdered;
2099
2100public:
2102 VPValue *ChainOp, VPValue *VecOp, VPValue *CondOp,
2103 bool IsOrdered)
2104 : VPSingleDefRecipe(VPDef::VPReductionSC,
2105 ArrayRef<VPValue *>({ChainOp, VecOp}), I),
2106 RdxDesc(R), IsOrdered(IsOrdered) {
2107 if (CondOp)
2108 addOperand(CondOp);
2109 }
2110
2111 ~VPReductionRecipe() override = default;
2112
2114 return new VPReductionRecipe(RdxDesc, getUnderlyingInstr(), getChainOp(),
2115 getVecOp(), getCondOp(), IsOrdered);
2116 }
2117
2118 VP_CLASSOF_IMPL(VPDef::VPReductionSC)
2119
2120 /// Generate the reduction in the loop
2121 void execute(VPTransformState &State) override;
2122
2123#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2124 /// Print the recipe.
2125 void print(raw_ostream &O, const Twine &Indent,
2126 VPSlotTracker &SlotTracker) const override;
2127#endif
2128
2129 /// The VPValue of the scalar Chain being accumulated.
2130 VPValue *getChainOp() const { return getOperand(0); }
2131 /// The VPValue of the vector value to be reduced.
2132 VPValue *getVecOp() const { return getOperand(1); }
2133 /// The VPValue of the condition for the block.
2135 return getNumOperands() > 2 ? getOperand(2) : nullptr;
2136 }
2137};
2138
2139/// VPReplicateRecipe replicates a given instruction producing multiple scalar
2140/// copies of the original scalar type, one per lane, instead of producing a
2141/// single copy of widened type for all lanes. If the instruction is known to be
2142/// uniform only one copy, per lane zero, will be generated.
2144 /// Indicator if only a single replica per lane is needed.
2145 bool IsUniform;
2146
2147 /// Indicator if the replicas are also predicated.
2148 bool IsPredicated;
2149
2150public:
2151 template <typename IterT>
2153 bool IsUniform, VPValue *Mask = nullptr)
2154 : VPRecipeWithIRFlags(VPDef::VPReplicateSC, Operands, *I),
2155 IsUniform(IsUniform), IsPredicated(Mask) {
2156 if (Mask)
2157 addOperand(Mask);
2158 }
2159
2160 ~VPReplicateRecipe() override = default;
2161
2163 auto *Copy =
2164 new VPReplicateRecipe(getUnderlyingInstr(), operands(), IsUniform,
2165 isPredicated() ? getMask() : nullptr);
2166 Copy->transferFlags(*this);
2167 return Copy;
2168 }
2169
2170 VP_CLASSOF_IMPL(VPDef::VPReplicateSC)
2171
2172 /// Generate replicas of the desired Ingredient. Replicas will be generated
2173 /// for all parts and lanes unless a specific part and lane are specified in
2174 /// the \p State.
2175 void execute(VPTransformState &State) override;
2176
2177#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2178 /// Print the recipe.
2179 void print(raw_ostream &O, const Twine &Indent,
2180 VPSlotTracker &SlotTracker) const override;
2181#endif
2182
2183 bool isUniform() const { return IsUniform; }
2184
2185 bool isPredicated() const { return IsPredicated; }
2186
2187 /// Returns true if the recipe only uses the first lane of operand \p Op.
2188 bool onlyFirstLaneUsed(const VPValue *Op) const override {
2190 "Op must be an operand of the recipe");
2191 return isUniform();
2192 }
2193
2194 /// Returns true if the recipe uses scalars of operand \p Op.
2195 bool usesScalars(const VPValue *Op) const override {
2197 "Op must be an operand of the recipe");
2198 return true;
2199 }
2200
2201 /// Returns true if the recipe is used by a widened recipe via an intervening
2202 /// VPPredInstPHIRecipe. In this case, the scalar values should also be packed
2203 /// in a vector.
2204 bool shouldPack() const;
2205
2206 /// Return the mask of a predicated VPReplicateRecipe.
2208 assert(isPredicated() && "Trying to get the mask of a unpredicated recipe");
2209 return getOperand(getNumOperands() - 1);
2210 }
2211
2212 unsigned getOpcode() const { return getUnderlyingInstr()->getOpcode(); }
2213};
2214
2215/// A recipe for generating conditional branches on the bits of a mask.
2217public:
2219 : VPRecipeBase(VPDef::VPBranchOnMaskSC, {}) {
2220 if (BlockInMask) // nullptr means all-one mask.
2221 addOperand(BlockInMask);
2222 }
2223
2225 return new VPBranchOnMaskRecipe(getOperand(0));
2226 }
2227
2228 VP_CLASSOF_IMPL(VPDef::VPBranchOnMaskSC)
2229
2230 /// Generate the extraction of the appropriate bit from the block mask and the
2231 /// conditional branch.
2232 void execute(VPTransformState &State) override;
2233
2234#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2235 /// Print the recipe.
2236 void print(raw_ostream &O, const Twine &Indent,
2237 VPSlotTracker &SlotTracker) const override {
2238 O << Indent << "BRANCH-ON-MASK ";
2239 if (VPValue *Mask = getMask())
2240 Mask->printAsOperand(O, SlotTracker);
2241 else
2242 O << " All-One";
2243 }
2244#endif
2245
2246 /// Return the mask used by this recipe. Note that a full mask is represented
2247 /// by a nullptr.
2248 VPValue *getMask() const {
2249 assert(getNumOperands() <= 1 && "should have either 0 or 1 operands");
2250 // Mask is optional.
2251 return getNumOperands() == 1 ? getOperand(0) : nullptr;
2252 }
2253
2254 /// Returns true if the recipe uses scalars of operand \p Op.
2255 bool usesScalars(const VPValue *Op) const override {
2257 "Op must be an operand of the recipe");
2258 return true;
2259 }
2260};
2261
2262/// VPPredInstPHIRecipe is a recipe for generating the phi nodes needed when
2263/// control converges back from a Branch-on-Mask. The phi nodes are needed in
2264/// order to merge values that are set under such a branch and feed their uses.
2265/// The phi nodes can be scalar or vector depending on the users of the value.
2266/// This recipe works in concert with VPBranchOnMaskRecipe.
2268public:
2269 /// Construct a VPPredInstPHIRecipe given \p PredInst whose value needs a phi
2270 /// nodes after merging back from a Branch-on-Mask.
2272 : VPSingleDefRecipe(VPDef::VPPredInstPHISC, PredV) {}
2273 ~VPPredInstPHIRecipe() override = default;
2274
2276 return new VPPredInstPHIRecipe(getOperand(0));
2277 }
2278
2279 VP_CLASSOF_IMPL(VPDef::VPPredInstPHISC)
2280
2281 /// Generates phi nodes for live-outs as needed to retain SSA form.
2282 void execute(VPTransformState &State) override;
2283
2284#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2285 /// Print the recipe.
2286 void print(raw_ostream &O, const Twine &Indent,
2287 VPSlotTracker &SlotTracker) const override;
2288#endif
2289
2290 /// Returns true if the recipe uses scalars of operand \p Op.
2291 bool usesScalars(const VPValue *Op) const override {
2293 "Op must be an operand of the recipe");
2294 return true;
2295 }
2296};
2297
2298/// A common base class for widening memory operations. An optional mask can be
2299/// provided as the last operand.
2301protected:
2303
2304 /// Whether the accessed addresses are consecutive.
2306
2307 /// Whether the consecutive accessed addresses are in reverse order.
2309
2310 /// Whether the memory access is masked.
2311 bool IsMasked = false;
2312
2313 void setMask(VPValue *Mask) {
2314 assert(!IsMasked && "cannot re-set mask");
2315 if (!Mask)
2316 return;
2317 addOperand(Mask);
2318 IsMasked = true;
2319 }
2320
2321 VPWidenMemoryRecipe(const char unsigned SC, Instruction &I,
2322 std::initializer_list<VPValue *> Operands,
2323 bool Consecutive, bool Reverse, DebugLoc DL)
2325 Reverse(Reverse) {
2326 assert((Consecutive || !Reverse) && "Reverse implies consecutive");
2327 }
2328
2329public:
2331 llvm_unreachable("cloning not supported");
2332 }
2333
2334 static inline bool classof(const VPRecipeBase *R) {
2335 return R->getVPDefID() == VPRecipeBase::VPWidenLoadSC ||
2336 R->getVPDefID() == VPRecipeBase::VPWidenStoreSC ||
2337 R->getVPDefID() == VPRecipeBase::VPWidenLoadEVLSC ||
2338 R->getVPDefID() == VPRecipeBase::VPWidenStoreEVLSC;
2339 }
2340
2341 static inline bool classof(const VPUser *U) {
2342 auto *R = dyn_cast<VPRecipeBase>(U);
2343 return R && classof(R);
2344 }
2345
2346 /// Return whether the loaded-from / stored-to addresses are consecutive.
2347 bool isConsecutive() const { return Consecutive; }
2348
2349 /// Return whether the consecutive loaded/stored addresses are in reverse
2350 /// order.
2351 bool isReverse() const { return Reverse; }
2352
2353 /// Return the address accessed by this recipe.
2354 VPValue *getAddr() const { return getOperand(0); }
2355
2356 /// Returns true if the recipe is masked.
2357 bool isMasked() const { return IsMasked; }
2358
2359 /// Return the mask used by this recipe. Note that a full mask is represented
2360 /// by a nullptr.
2361 VPValue *getMask() const {
2362 // Mask is optional and therefore the last operand.
2363 return isMasked() ? getOperand(getNumOperands() - 1) : nullptr;
2364 }
2365
2366 /// Generate the wide load/store.
2367 void execute(VPTransformState &State) override {
2368 llvm_unreachable("VPWidenMemoryRecipe should not be instantiated.");
2369 }
2370
2372};
2373
2374/// A recipe for widening load operations, using the address to load from and an
2375/// optional mask.
2376struct VPWidenLoadRecipe final : public VPWidenMemoryRecipe, public VPValue {
2378 bool Consecutive, bool Reverse, DebugLoc DL)
2379 : VPWidenMemoryRecipe(VPDef::VPWidenLoadSC, Load, {Addr}, Consecutive,
2380 Reverse, DL),
2381 VPValue(this, &Load) {
2382 setMask(Mask);
2383 }
2384
2386 return new VPWidenLoadRecipe(cast<LoadInst>(Ingredient), getAddr(),
2388 getDebugLoc());
2389 }
2390
2391 VP_CLASSOF_IMPL(VPDef::VPWidenLoadSC);
2392
2393 /// Generate a wide load or gather.
2394 void execute(VPTransformState &State) override;
2395
2396#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2397 /// Print the recipe.
2398 void print(raw_ostream &O, const Twine &Indent,
2399 VPSlotTracker &SlotTracker) const override;
2400#endif
2401
2402 /// Returns true if the recipe only uses the first lane of operand \p Op.
2403 bool onlyFirstLaneUsed(const VPValue *Op) const override {
2405 "Op must be an operand of the recipe");
2406 // Widened, consecutive loads operations only demand the first lane of
2407 // their address.
2408 return Op == getAddr() && isConsecutive();
2409 }
2410};
2411
2412/// A recipe for widening load operations with vector-predication intrinsics,
2413/// using the address to load from, the explicit vector length and an optional
2414/// mask.
2415struct VPWidenLoadEVLRecipe final : public VPWidenMemoryRecipe, public VPValue {
2417 : VPWidenMemoryRecipe(VPDef::VPWidenLoadEVLSC, L->getIngredient(),
2418 {L->getAddr(), EVL}, L->isConsecutive(),
2419 L->isReverse(), L->getDebugLoc()),
2420 VPValue(this, &getIngredient()) {
2421 setMask(Mask);
2422 }
2423
2424 VP_CLASSOF_IMPL(VPDef::VPWidenLoadEVLSC)
2425
2426 /// Return the EVL operand.
2427 VPValue *getEVL() const { return getOperand(1); }
2428
2429 /// Generate the wide load or gather.
2430 void execute(VPTransformState &State) override;
2431
2432#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2433 /// Print the recipe.
2434 void print(raw_ostream &O, const Twine &Indent,
2435 VPSlotTracker &SlotTracker) const override;
2436#endif
2437
2438 /// Returns true if the recipe only uses the first lane of operand \p Op.
2439 bool onlyFirstLaneUsed(const VPValue *Op) const override {
2441 "Op must be an operand of the recipe");
2442 // Widened loads only demand the first lane of EVL and consecutive loads
2443 // only demand the first lane of their address.
2444 return Op == getEVL() || (Op == getAddr() && isConsecutive());
2445 }
2446};
2447
2448/// A recipe for widening store operations, using the stored value, the address
2449/// to store to and an optional mask.
2452 VPValue *Mask, bool Consecutive, bool Reverse, DebugLoc DL)
2453 : VPWidenMemoryRecipe(VPDef::VPWidenStoreSC, Store, {Addr, StoredVal},
2455 setMask(Mask);
2456 }
2457
2459 return new VPWidenStoreRecipe(cast<StoreInst>(Ingredient), getAddr(),
2461 Reverse, getDebugLoc());
2462 }
2463
2464 VP_CLASSOF_IMPL(VPDef::VPWidenStoreSC);
2465
2466 /// Return the value stored by this recipe.
2467 VPValue *getStoredValue() const { return getOperand(1); }
2468
2469 /// Generate a wide store or scatter.
2470 void execute(VPTransformState &State) override;
2471
2472#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2473 /// Print the recipe.
2474 void print(raw_ostream &O, const Twine &Indent,
2475 VPSlotTracker &SlotTracker) const override;
2476#endif
2477
2478 /// Returns true if the recipe only uses the first lane of operand \p Op.
2479 bool onlyFirstLaneUsed(const VPValue *Op) const override {
2481 "Op must be an operand of the recipe");
2482 // Widened, consecutive stores only demand the first lane of their address,
2483 // unless the same operand is also stored.
2484 return Op == getAddr() && isConsecutive() && Op != getStoredValue();
2485 }
2486};
2487
2488/// A recipe for widening store operations with vector-predication intrinsics,
2489/// using the value to store, the address to store to, the explicit vector
2490/// length and an optional mask.
2493 : VPWidenMemoryRecipe(VPDef::VPWidenStoreEVLSC, S->getIngredient(),
2494 {S->getAddr(), S->getStoredValue(), EVL},
2495 S->isConsecutive(), S->isReverse(),
2496 S->getDebugLoc()) {
2497 setMask(Mask);
2498 }
2499
2500 VP_CLASSOF_IMPL(VPDef::VPWidenStoreEVLSC)
2501
2502 /// Return the address accessed by this recipe.
2503 VPValue *getStoredValue() const { return getOperand(1); }
2504
2505 /// Return the EVL operand.
2506 VPValue *getEVL() const { return getOperand(2); }
2507
2508 /// Generate the wide store or scatter.
2509 void execute(VPTransformState &State) override;
2510
2511#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2512 /// Print the recipe.
2513 void print(raw_ostream &O, const Twine &Indent,
2514 VPSlotTracker &SlotTracker) const override;
2515#endif
2516
2517 /// Returns true if the recipe only uses the first lane of operand \p Op.
2518 bool onlyFirstLaneUsed(const VPValue *Op) const override {
2520 "Op must be an operand of the recipe");
2521 if (Op == getEVL()) {
2522 assert(getStoredValue() != Op && "unexpected store of EVL");
2523 return true;
2524 }
2525 // Widened, consecutive memory operations only demand the first lane of
2526 // their address, unless the same operand is also stored. That latter can
2527 // happen with opaque pointers.
2528 return Op == getAddr() && isConsecutive() && Op != getStoredValue();
2529 }
2530};
2531
2532/// Recipe to expand a SCEV expression.
2534 const SCEV *Expr;
2535 ScalarEvolution &SE;
2536
2537public:
2539 : VPSingleDefRecipe(VPDef::VPExpandSCEVSC, {}), Expr(Expr), SE(SE) {}
2540
2541 ~VPExpandSCEVRecipe() override = default;
2542
2544 return new VPExpandSCEVRecipe(Expr, SE);
2545 }
2546
2547 VP_CLASSOF_IMPL(VPDef::VPExpandSCEVSC)
2548
2549 /// Generate a canonical vector induction variable of the vector loop, with
2550 void execute(VPTransformState &State) override;
2551
2552#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2553 /// Print the recipe.
2554 void print(raw_ostream &O, const Twine &Indent,
2555 VPSlotTracker &SlotTracker) const override;
2556#endif
2557
2558 const SCEV *getSCEV() const { return Expr; }
2559};
2560
2561/// Canonical scalar induction phi of the vector loop. Starting at the specified
2562/// start value (either 0 or the resume value when vectorizing the epilogue
2563/// loop). VPWidenCanonicalIVRecipe represents the vector version of the
2564/// canonical induction variable.
2566public:
2568 : VPHeaderPHIRecipe(VPDef::VPCanonicalIVPHISC, nullptr, StartV, DL) {}
2569
2570 ~VPCanonicalIVPHIRecipe() override = default;
2571
2573 auto *R = new VPCanonicalIVPHIRecipe(getOperand(0), getDebugLoc());
2574 R->addOperand(getBackedgeValue());
2575 return R;
2576 }
2577
2578 VP_CLASSOF_IMPL(VPDef::VPCanonicalIVPHISC)
2579
2581 return D->getVPDefID() == VPDef::VPCanonicalIVPHISC;
2582 }
2583
2584 /// Generate the canonical scalar induction phi of the vector loop.
2585 void execute(VPTransformState &State) override;
2586
2587#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2588 /// Print the recipe.
2589 void print(raw_ostream &O, const Twine &Indent,
2590 VPSlotTracker &SlotTracker) const override;
2591#endif
2592
2593 /// Returns the scalar type of the induction.
2595 return getStartValue()->getLiveInIRValue()->getType();
2596 }
2597
2598 /// Returns true if the recipe only uses the first lane of operand \p Op.
2599 bool onlyFirstLaneUsed(const VPValue *Op) const override {
2601 "Op must be an operand of the recipe");
2602 return true;
2603 }
2604
2605 /// Returns true if the recipe only uses the first part of operand \p Op.
2606 bool onlyFirstPartUsed(const VPValue *Op) const override {
2608 "Op must be an operand of the recipe");
2609 return true;
2610 }
2611
2612 /// Check if the induction described by \p Kind, /p Start and \p Step is
2613 /// canonical, i.e. has the same start and step (of 1) as the canonical IV.
2615 VPValue *Step) const;
2616};
2617
2618/// A recipe for generating the active lane mask for the vector loop that is
2619/// used to predicate the vector operations.
2620/// TODO: It would be good to use the existing VPWidenPHIRecipe instead and
2621/// remove VPActiveLaneMaskPHIRecipe.
2623public:
2625 : VPHeaderPHIRecipe(VPDef::VPActiveLaneMaskPHISC, nullptr, StartMask,
2626 DL) {}
2627
2628 ~VPActiveLaneMaskPHIRecipe() override = default;
2629
2632 }
2633
2634 VP_CLASSOF_IMPL(VPDef::VPActiveLaneMaskPHISC)
2635
2637 return D->getVPDefID() == VPDef::VPActiveLaneMaskPHISC;
2638 }
2639
2640 /// Generate the active lane mask phi of the vector loop.
2641 void execute(VPTransformState &State) override;
2642
2643#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2644 /// Print the recipe.
2645 void print(raw_ostream &O, const Twine &Indent,
2646 VPSlotTracker &SlotTracker) const override;
2647#endif
2648};
2649
2650/// A recipe for generating the phi node for the current index of elements,
2651/// adjusted in accordance with EVL value. It starts at the start value of the
2652/// canonical induction and gets incremented by EVL in each iteration of the
2653/// vector loop.
2655public:
2657 : VPHeaderPHIRecipe(VPDef::VPEVLBasedIVPHISC, nullptr, StartIV, DL) {}
2658
2659 ~VPEVLBasedIVPHIRecipe() override = default;
2660
2662 llvm_unreachable("cloning not implemented yet");
2663 }
2664
2665 VP_CLASSOF_IMPL(VPDef::VPEVLBasedIVPHISC)
2666
2668 return D->getVPDefID() == VPDef::VPEVLBasedIVPHISC;
2669 }
2670
2671 /// Generate phi for handling IV based on EVL over iterations correctly.
2672 /// TODO: investigate if it can share the code with VPCanonicalIVPHIRecipe.
2673 void execute(VPTransformState &State) override;
2674
2675 /// Returns true if the recipe only uses the first lane of operand \p Op.
2676 bool onlyFirstLaneUsed(const VPValue *Op) const override {
2678 "Op must be an operand of the recipe");
2679 return true;
2680 }
2681
2682#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2683 /// Print the recipe.
2684 void print(raw_ostream &O, const Twine &Indent,
2685 VPSlotTracker &SlotTracker) const override;
2686#endif
2687};
2688
2689/// A Recipe for widening the canonical induction variable of the vector loop.
2691public:
2693 : VPSingleDefRecipe(VPDef::VPWidenCanonicalIVSC, {CanonicalIV}) {}
2694
2695 ~VPWidenCanonicalIVRecipe() override = default;
2696
2698 return new VPWidenCanonicalIVRecipe(
2699 cast<VPCanonicalIVPHIRecipe>(getOperand(0)));
2700 }
2701
2702 VP_CLASSOF_IMPL(VPDef::VPWidenCanonicalIVSC)
2703
2704 /// Generate a canonical vector induction variable of the vector loop, with
2705 /// start = {<Part*VF, Part*VF+1, ..., Part*VF+VF-1> for 0 <= Part < UF}, and
2706 /// step = <VF*UF, VF*UF, ..., VF*UF>.
2707 void execute(VPTransformState &State) override;
2708
2709#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2710 /// Print the recipe.
2711 void print(raw_ostream &O, const Twine &Indent,
2712 VPSlotTracker &SlotTracker) const override;
2713#endif
2714};
2715
2716/// A recipe for converting the input value \p IV value to the corresponding
2717/// value of an IV with different start and step values, using Start + IV *
2718/// Step.
2720 /// Kind of the induction.
2722 /// If not nullptr, the floating point induction binary operator. Must be set
2723 /// for floating point inductions.
2724 const FPMathOperator *FPBinOp;
2725
2726public:
2728 VPCanonicalIVPHIRecipe *CanonicalIV, VPValue *Step)
2730 IndDesc.getKind(),
2731 dyn_cast_or_null<FPMathOperator>(IndDesc.getInductionBinOp()),
2732 Start, CanonicalIV, Step) {}
2733
2735 const FPMathOperator *FPBinOp, VPValue *Start, VPValue *IV,
2736 VPValue *Step)
2737 : VPSingleDefRecipe(VPDef::VPDerivedIVSC, {Start, IV, Step}), Kind(Kind),
2738 FPBinOp(FPBinOp) {}
2739
2740 ~VPDerivedIVRecipe() override = default;
2741
2743 return new VPDerivedIVRecipe(Kind, FPBinOp, getStartValue(), getOperand(1),
2744 getStepValue());
2745 }
2746
2747 VP_CLASSOF_IMPL(VPDef::VPDerivedIVSC)
2748
2749 /// Generate the transformed value of the induction at offset StartValue (1.
2750 /// operand) + IV (2. operand) * StepValue (3, operand).
2751 void execute(VPTransformState &State) override;
2752
2753#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2754 /// Print the recipe.
2755 void print(raw_ostream &O, const Twine &Indent,
2756 VPSlotTracker &SlotTracker) const override;
2757#endif
2758
2760 return getStartValue()->getLiveInIRValue()->getType();
2761 }
2762
2763 VPValue *getStartValue() const { return getOperand(0); }
2764 VPValue *getStepValue() const { return getOperand(2); }
2765
2766 /// Returns true if the recipe only uses the first lane of operand \p Op.
2767 bool onlyFirstLaneUsed(const VPValue *Op) const override {
2769 "Op must be an operand of the recipe");
2770 return true;
2771 }
2772};
2773
2774/// A recipe for handling phi nodes of integer and floating-point inductions,
2775/// producing their scalar values.
2777 Instruction::BinaryOps InductionOpcode;
2778
2779public:
2782 : VPRecipeWithIRFlags(VPDef::VPScalarIVStepsSC,
2783 ArrayRef<VPValue *>({IV, Step}), FMFs),
2784 InductionOpcode(Opcode) {}
2785
2787 VPValue *Step)
2789 IV, Step, IndDesc.getInductionOpcode(),
2790 dyn_cast_or_null<FPMathOperator>(IndDesc.getInductionBinOp())
2791 ? IndDesc.getInductionBinOp()->getFastMathFlags()
2792 : FastMathFlags()) {}
2793
2794 ~VPScalarIVStepsRecipe() override = default;
2795
2797 return new VPScalarIVStepsRecipe(
2798 getOperand(0), getOperand(1), InductionOpcode,
2800 }
2801
2802 VP_CLASSOF_IMPL(VPDef::VPScalarIVStepsSC)
2803
2804 /// Generate the scalarized versions of the phi node as needed by their users.
2805 void execute(VPTransformState &State) override;
2806
2807#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2808 /// Print the recipe.
2809 void print(raw_ostream &O, const Twine &Indent,
2810 VPSlotTracker &SlotTracker) const override;
2811#endif
2812
2813 VPValue *getStepValue() const { return getOperand(1); }
2814
2815 /// Returns true if the recipe only uses the first lane of operand \p Op.
2816 bool onlyFirstLaneUsed(const VPValue *Op) const override {
2818 "Op must be an operand of the recipe");
2819 return true;
2820 }
2821};
2822
2823/// VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph. It
2824/// holds a sequence of zero or more VPRecipe's each representing a sequence of
2825/// output IR instructions. All PHI-like recipes must come before any non-PHI recipes.
2827public:
2829
2830private:
2831 /// The VPRecipes held in the order of output instructions to generate.
2832 RecipeListTy Recipes;
2833
2834public:
2835 VPBasicBlock(const Twine &Name = "", VPRecipeBase *Recipe = nullptr)
2836 : VPBlockBase(VPBasicBlockSC, Name.str()) {
2837 if (Recipe)
2838 appendRecipe(Recipe);
2839 }
2840
2841 ~VPBasicBlock() override {
2842 while (!Recipes.empty())
2843 Recipes.pop_back();
2844 }
2845
2846 /// Instruction iterators...
2851
2852 //===--------------------------------------------------------------------===//
2853 /// Recipe iterator methods
2854 ///
2855 inline iterator begin() { return Recipes.begin(); }
2856 inline const_iterator begin() const { return Recipes.begin(); }
2857 inline iterator end() { return Recipes.end(); }
2858 inline const_iterator end() const { return Recipes.end(); }
2859
2860 inline reverse_iterator rbegin() { return Recipes.rbegin(); }
2861 inline const_reverse_iterator rbegin() const { return Recipes.rbegin(); }
2862 inline reverse_iterator rend() { return Recipes.rend(); }
2863 inline const_reverse_iterator rend() const { return Recipes.rend(); }
2864
2865 inline size_t size() const { return Recipes.size(); }
2866 inline bool empty() const { return Recipes.empty(); }
2867 inline const VPRecipeBase &front() const { return Recipes.front(); }
2868 inline VPRecipeBase &front() { return Recipes.front(); }
2869 inline const VPRecipeBase &back() const { return Recipes.back(); }
2870 inline VPRecipeBase &back() { return Recipes.back(); }
2871
2872 /// Returns a reference to the list of recipes.
2873 RecipeListTy &getRecipeList() { return Recipes; }
2874
2875 /// Returns a pointer to a member of the recipe list.
2877 return &VPBasicBlock::Recipes;
2878 }
2879
2880 /// Method to support type inquiry through isa, cast, and dyn_cast.
2881 static inline bool classof(const VPBlockBase *V) {
2882 return V->getVPBlockID() == VPBlockBase::VPBasicBlockSC;
2883 }
2884
2885 void insert(VPRecipeBase *Recipe, iterator InsertPt) {
2886 assert(Recipe && "No recipe to append.");
2887 assert(!Recipe->Parent && "Recipe already in VPlan");
2888 Recipe->Parent = this;
2889 Recipes.insert(InsertPt, Recipe);
2890 }
2891
2892 /// Augment the existing recipes of a VPBasicBlock with an additional
2893 /// \p Recipe as the last recipe.
2894 void appendRecipe(VPRecipeBase *Recipe) { insert(Recipe, end()); }
2895
2896 /// The method which generates the output IR instructions that correspond to
2897 /// this VPBasicBlock, thereby "executing" the VPlan.
2898 void execute(VPTransformState *State) override;
2899
2900 /// Return the position of the first non-phi node recipe in the block.
2902
2903 /// Returns an iterator range over the PHI-like recipes in the block.
2905 return make_range(begin(), getFirstNonPhi());
2906 }
2907
2908 void dropAllReferences(VPValue *NewValue) override;
2909
2910 /// Split current block at \p SplitAt by inserting a new block between the
2911 /// current block and its successors and moving all recipes starting at
2912 /// SplitAt to the new block. Returns the new block.
2913 VPBasicBlock *splitAt(iterator SplitAt);
2914
2916
2917#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2918 /// Print this VPBsicBlock to \p O, prefixing all lines with \p Indent. \p
2919 /// SlotTracker is used to print unnamed VPValue's using consequtive numbers.
2920 ///
2921 /// Note that the numbering is applied to the whole VPlan, so printing
2922 /// individual blocks is consistent with the whole VPlan printing.
2923 void print(raw_ostream &O, const Twine &Indent,
2924 VPSlotTracker &SlotTracker) const override;
2925 using VPBlockBase::print; // Get the print(raw_stream &O) version.
2926#endif
2927
2928 /// If the block has multiple successors, return the branch recipe terminating
2929 /// the block. If there are no or only a single successor, return nullptr;
2931 const VPRecipeBase *getTerminator() const;
2932
2933 /// Returns true if the block is exiting it's parent region.
2934 bool isExiting() const;
2935
2936 /// Clone the current block and it's recipes, without updating the operands of
2937 /// the cloned recipes.
2938 VPBasicBlock *clone() override {
2939 auto *NewBlock = new VPBasicBlock(getName());
2940 for (VPRecipeBase &R : *this)
2941 NewBlock->appendRecipe(R.clone());
2942 return NewBlock;
2943 }
2944
2945private:
2946 /// Create an IR BasicBlock to hold the output instructions generated by this
2947 /// VPBasicBlock, and return it. Update the CFGState accordingly.
2948 BasicBlock *createEmptyBasicBlock(VPTransformState::CFGState &CFG);
2949};
2950
2951/// VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks
2952/// which form a Single-Entry-Single-Exiting subgraph of the output IR CFG.
2953/// A VPRegionBlock may indicate that its contents are to be replicated several
2954/// times. This is designed to support predicated scalarization, in which a
2955/// scalar if-then code structure needs to be generated VF * UF times. Having
2956/// this replication indicator helps to keep a single model for multiple
2957/// candidate VF's. The actual replication takes place only once the desired VF
2958/// and UF have been determined.
2960 /// Hold the Single Entry of the SESE region modelled by the VPRegionBlock.
2961 VPBlockBase *Entry;
2962
2963 /// Hold the Single Exiting block of the SESE region modelled by the
2964 /// VPRegionBlock.
2965 VPBlockBase *Exiting;
2966
2967 /// An indicator whether this region is to generate multiple replicated
2968 /// instances of output IR corresponding to its VPBlockBases.
2969 bool IsReplicator;
2970
2971public:
2973 const std::string &Name = "", bool IsReplicator = false)
2974 : VPBlockBase(VPRegionBlockSC, Name), Entry(Entry), Exiting(Exiting),
2975 IsReplicator(IsReplicator) {
2976 assert(Entry->getPredecessors().empty() && "Entry block has predecessors.");
2977 assert(Exiting->getSuccessors().empty() && "Exit block has successors.");
2978 Entry->setParent(this);
2979 Exiting->setParent(this);
2980 }
2981 VPRegionBlock(const std::string &Name = "", bool IsReplicator = false)
2982 : VPBlockBase(VPRegionBlockSC, Name), Entry(nullptr), Exiting(nullptr),
2983 IsReplicator(IsReplicator) {}
2984
2985 ~VPRegionBlock() override {
2986 if (Entry) {
2987 VPValue DummyValue;
2988 Entry->dropAllReferences(&DummyValue);
2989 deleteCFG(Entry);
2990 }
2991 }
2992
2993 /// Method to support type inquiry through isa, cast, and dyn_cast.
2994 static inline bool classof(const VPBlockBase *V) {
2995 return V->getVPBlockID() == VPBlockBase::VPRegionBlockSC;
2996 }
2997
2998 const VPBlockBase *getEntry() const { return Entry; }
2999 VPBlockBase *getEntry() { return Entry; }
3000
3001 /// Set \p EntryBlock as the entry VPBlockBase of this VPRegionBlock. \p
3002 /// EntryBlock must have no predecessors.
3003 void setEntry(VPBlockBase *EntryBlock) {
3004 assert(EntryBlock->getPredecessors().empty() &&
3005 "Entry block cannot have predecessors.");
3006 Entry = EntryBlock;
3007 EntryBlock->setParent(this);
3008 }
3009
3010 const VPBlockBase *getExiting() const { return Exiting; }
3011 VPBlockBase *getExiting() { return Exiting; }
3012
3013 /// Set \p ExitingBlock as the exiting VPBlockBase of this VPRegionBlock. \p
3014 /// ExitingBlock must have no successors.
3015 void setExiting(VPBlockBase *ExitingBlock) {
3016 assert(ExitingBlock->getSuccessors().empty() &&
3017 "Exit block cannot have successors.");
3018 Exiting = ExitingBlock;
3019 ExitingBlock->setParent(this);
3020 }
3021
3022 /// Returns the pre-header VPBasicBlock of the loop region.
3024 assert(!isReplicator() && "should only get pre-header of loop regions");
3026 }
3027
3028 /// An indicator whether this region is to generate multiple replicated
3029 /// instances of output IR corresponding to its VPBlockBases.
3030 bool isReplicator() const { return IsReplicator; }
3031
3032 /// The method which generates the output IR instructions that correspond to
3033 /// this VPRegionBlock, thereby "executing" the VPlan.
3034 void execute(VPTransformState *State) override;
3035
3036 void dropAllReferences(VPValue *NewValue) override;
3037
3038#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3039 /// Print this VPRegionBlock to \p O (recursively), prefixing all lines with
3040 /// \p Indent. \p SlotTracker is used to print unnamed VPValue's using
3041 /// consequtive numbers.
3042 ///
3043 /// Note that the numbering is applied to the whole VPlan, so printing
3044 /// individual regions is consistent with the whole VPlan printing.
3045 void print(raw_ostream &O, const Twine &Indent,
3046 VPSlotTracker &SlotTracker) const override;
3047 using VPBlockBase::print; // Get the print(raw_stream &O) version.
3048#endif
3049
3050 /// Clone all blocks in the single-entry single-exit region of the block and
3051 /// their recipes without updating the operands of the cloned recipes.
3052 VPRegionBlock *clone() override;
3053};
3054
3055/// VPlan models a candidate for vectorization, encoding various decisions take
3056/// to produce efficient output IR, including which branches, basic-blocks and
3057/// output IR instructions to generate, and their cost. VPlan holds a
3058/// Hierarchical-CFG of VPBasicBlocks and VPRegionBlocks rooted at an Entry
3059/// VPBasicBlock.
3060class VPlan {
3061 friend class VPlanPrinter;
3062 friend class VPSlotTracker;
3063
3064 /// Hold the single entry to the Hierarchical CFG of the VPlan, i.e. the
3065 /// preheader of the vector loop.
3066 VPBasicBlock *Entry;
3067
3068 /// VPBasicBlock corresponding to the original preheader. Used to place
3069 /// VPExpandSCEV recipes for expressions used during skeleton creation and the
3070 /// rest of VPlan execution.
3071 VPBasicBlock *Preheader;
3072
3073 /// Holds the VFs applicable to this VPlan.
3075
3076 /// Holds the UFs applicable to this VPlan. If empty, the VPlan is valid for
3077 /// any UF.
3079
3080 /// Holds the name of the VPlan, for printing.
3081 std::string Name;
3082
3083 /// Represents the trip count of the original loop, for folding
3084 /// the tail.
3085 VPValue *TripCount = nullptr;
3086
3087 /// Represents the backedge taken count of the original loop, for folding
3088 /// the tail. It equals TripCount - 1.
3089 VPValue *BackedgeTakenCount = nullptr;
3090
3091 /// Represents the vector trip count.
3092 VPValue VectorTripCount;
3093
3094 /// Represents the loop-invariant VF * UF of the vector loop region.
3095 VPValue VFxUF;
3096
3097 /// Holds a mapping between Values and their corresponding VPValue inside
3098 /// VPlan.
3099 Value2VPValueTy Value2VPValue;
3100
3101 /// Contains all the external definitions created for this VPlan. External
3102 /// definitions are VPValues that hold a pointer to their underlying IR.
3103 SmallVector<VPValue *, 16> VPLiveInsToFree;
3104
3105 /// Values used outside the plan.
3107
3108 /// Mapping from SCEVs to the VPValues representing their expansions.
3109 /// NOTE: This mapping is temporary and will be removed once all users have
3110 /// been modeled in VPlan directly.
3111 DenseMap<const SCEV *, VPValue *> SCEVToExpansion;
3112
3113public:
3114 /// Construct a VPlan with original preheader \p Preheader, trip count \p TC
3115 /// and \p Entry to the plan. At the moment, \p Preheader and \p Entry need to
3116 /// be disconnected, as the bypass blocks between them are not yet modeled in
3117 /// VPlan.
3118 VPlan(VPBasicBlock *Preheader, VPValue *TC, VPBasicBlock *Entry)
3119 : VPlan(Preheader, Entry) {
3120 TripCount = TC;
3121 }
3122
3123 /// Construct a VPlan with original preheader \p Preheader and \p Entry to
3124 /// the plan. At the moment, \p Preheader and \p Entry need to be
3125 /// disconnected, as the bypass blocks between them are not yet modeled in
3126 /// VPlan.
3127 VPlan(VPBasicBlock *Preheader, VPBasicBlock *Entry)
3128 : Entry(Entry), Preheader(Preheader) {
3129 Entry->setPlan(this);
3130 Preheader->setPlan(this);
3131 assert(Preheader->getNumSuccessors() == 0 &&
3132 Preheader->getNumPredecessors() == 0 &&
3133 "preheader must be disconnected");
3134 }
3135
3136 ~VPlan();
3137
3138 /// Create initial VPlan skeleton, having an "entry" VPBasicBlock (wrapping
3139 /// original scalar pre-header) which contains SCEV expansions that need to
3140 /// happen before the CFG is modified; a VPBasicBlock for the vector
3141 /// pre-header, followed by a region for the vector loop, followed by the
3142 /// middle VPBasicBlock.
3143 static VPlanPtr createInitialVPlan(const SCEV *TripCount,
3144 ScalarEvolution &PSE);
3145
3146 /// Prepare the plan for execution, setting up the required live-in values.
3147 void prepareToExecute(Value *TripCount, Value *VectorTripCount,
3148 Value *CanonicalIVStartValue, VPTransformState &State);
3149
3150 /// Generate the IR code for this VPlan.
3151 void execute(VPTransformState *State);
3152
3153 VPBasicBlock *getEntry() { return Entry; }
3154 const VPBasicBlock *getEntry() const { return Entry; }
3155
3156 /// The trip count of the original loop.
3158 assert(TripCount && "trip count needs to be set before accessing it");
3159 return TripCount;
3160 }
3161
3162 /// Resets the trip count for the VPlan. The caller must make sure all uses of
3163 /// the original trip count have been replaced.
3164 void resetTripCount(VPValue *NewTripCount) {
3165 assert(TripCount && NewTripCount && TripCount->getNumUsers() == 0 &&
3166 "TripCount always must be set");
3167 TripCount = NewTripCount;
3168 }
3169
3170 /// The backedge taken count of the original loop.
3172 if (!BackedgeTakenCount)
3173 BackedgeTakenCount = new VPValue();
3174 return BackedgeTakenCount;
3175 }
3176
3177 /// The vector trip count.
3178 VPValue &getVectorTripCount() { return VectorTripCount; }
3179
3180 /// Returns VF * UF of the vector loop region.
3181 VPValue &getVFxUF() { return VFxUF; }
3182
3183 void addVF(ElementCount VF) { VFs.insert(VF); }
3184
3186 assert(hasVF(VF) && "Cannot set VF not already in plan");
3187 VFs.clear();
3188 VFs.insert(VF);
3189 }
3190
3191 bool hasVF(ElementCount VF) { return VFs.count(VF); }
3193 return any_of(VFs, [](ElementCount VF) { return VF.isScalable(); });
3194 }
3195
3196 bool hasScalarVFOnly() const { return VFs.size() == 1 && VFs[0].isScalar(); }
3197
3198 bool hasUF(unsigned UF) const { return UFs.empty() || UFs.contains(UF); }
3199
3200 void setUF(unsigned UF) {
3201 assert(hasUF(UF) && "Cannot set the UF not already in plan");
3202 UFs.clear();
3203 UFs.insert(UF);
3204 }
3205
3206 /// Return a string with the name of the plan and the applicable VFs and UFs.
3207 std::string getName() const;
3208
3209 void setName(const Twine &newName) { Name = newName.str(); }
3210
3211 /// Gets the live-in VPValue for \p V or adds a new live-in (if none exists
3212 /// yet) for \p V.
3214 assert(V && "Trying to get or add the VPValue of a null Value");
3215 if (!Value2VPValue.count(V)) {
3216 VPValue *VPV = new VPValue(V);
3217 VPLiveInsToFree.push_back(VPV);
3218 assert(VPV->isLiveIn() && "VPV must be a live-in.");
3219 assert(!Value2VPValue.count(V) && "Value already exists in VPlan");
3220 Value2VPValue[V] = VPV;
3221 }
3222
3223 assert(Value2VPValue.count(V) && "Value does not exist in VPlan");
3224 assert(Value2VPValue[V]->isLiveIn() &&
3225 "Only live-ins should be in mapping");
3226 return Value2VPValue[V];
3227 }
3228
3229 /// Return the live-in VPValue for \p V, if there is one or nullptr otherwise.
3230 VPValue *getLiveIn(Value *V) const { return Value2VPValue.lookup(V); }
3231
3232#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3233 /// Print the live-ins of this VPlan to \p O.
3234 void printLiveIns(raw_ostream &O) const;
3235
3236 /// Print this VPlan to \p O.
3237 void print(raw_ostream &O) const;
3238
3239 /// Print this VPlan in DOT format to \p O.
3240 void printDOT(raw_ostream &O) const;
3241
3242 /// Dump the plan to stderr (for debugging).
3243 LLVM_DUMP_METHOD void dump() const;
3244#endif
3245
3246 /// Returns the VPRegionBlock of the vector loop.
3248 return cast<VPRegionBlock>(getEntry()->getSingleSuccessor());
3249 }
3251 return cast<VPRegionBlock>(getEntry()->getSingleSuccessor());
3252 }
3253
3254 /// Returns the canonical induction recipe of the vector loop.
3257 if (EntryVPBB->empty()) {
3258 // VPlan native path.
3259 EntryVPBB = cast<VPBasicBlock>(EntryVPBB->getSingleSuccessor());
3260 }
3261 return cast<VPCanonicalIVPHIRecipe>(&*EntryVPBB->begin());
3262 }
3263
3264 void addLiveOut(PHINode *PN, VPValue *V);
3265
3267 delete LiveOuts[PN];
3268 LiveOuts.erase(PN);
3269 }
3270
3272 return LiveOuts;
3273 }
3274
3275 VPValue *getSCEVExpansion(const SCEV *S) const {
3276 return SCEVToExpansion.lookup(S);
3277 }
3278
3279 void addSCEVExpansion(const SCEV *S, VPValue *V) {
3280 assert(!SCEVToExpansion.contains(S) && "SCEV already expanded");
3281 SCEVToExpansion[S] = V;
3282 }
3283
3284 /// \return The block corresponding to the original preheader.
3285 VPBasicBlock *getPreheader() { return Preheader; }
3286 const VPBasicBlock *getPreheader() const { return Preheader; }
3287
3288 /// Clone the current VPlan, update all VPValues of the new VPlan and cloned
3289 /// recipes to refer to the clones, and return it.
3290 VPlan *duplicate();
3291
3292private:
3293 /// Add to the given dominator tree the header block and every new basic block
3294 /// that was created between it and the latch block, inclusive.
3295 static void updateDominatorTree(DominatorTree *DT, BasicBlock *LoopHeaderBB,
3296 BasicBlock *LoopLatchBB,
3297 BasicBlock *LoopExitBB);
3298};
3299
3300#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3301/// VPlanPrinter prints a given VPlan to a given output stream. The printing is
3302/// indented and follows the dot format.
3304 raw_ostream &OS;
3305 const VPlan &Plan;
3306 unsigned Depth = 0;
3307 unsigned TabWidth = 2;
3308 std::string Indent;
3309 unsigned BID = 0;
3311
3313
3314 /// Handle indentation.
3315 void bumpIndent(int b) { Indent = std::string((Depth += b) * TabWidth, ' '); }
3316
3317 /// Print a given \p Block of the Plan.
3318 void dumpBlock(const VPBlockBase *Block);
3319
3320 /// Print the information related to the CFG edges going out of a given
3321 /// \p Block, followed by printing the successor blocks themselves.
3322 void dumpEdges(const VPBlockBase *Block);
3323
3324 /// Print a given \p BasicBlock, including its VPRecipes, followed by printing
3325 /// its successor blocks.
3326 void dumpBasicBlock(const VPBasicBlock *BasicBlock);
3327
3328 /// Print a given \p Region of the Plan.
3329 void dumpRegion(const VPRegionBlock *Region);
3330
3331 unsigned getOrCreateBID(const VPBlockBase *Block) {
3332 return BlockID.count(Block) ? BlockID[Block] : BlockID[Block] = BID++;
3333 }
3334
3335 Twine getOrCreateName(const VPBlockBase *Block);
3336
3337 Twine getUID(const VPBlockBase *Block);
3338
3339 /// Print the information related to a CFG edge between two VPBlockBases.
3340 void drawEdge(const VPBlockBase *From, const VPBlockBase *To, bool Hidden,
3341 const Twine &Label);
3342
3343public:
3345 : OS(O), Plan(P), SlotTracker(&P) {}
3346
3347 LLVM_DUMP_METHOD void dump();
3348};
3349
3351 const Value *V;
3352
3353 VPlanIngredient(const Value *V) : V(V) {}
3354
3355 void print(raw_ostream &O) const;
3356};
3357
3359 I.print(OS);
3360 return OS;
3361}
3362
3364 Plan.print(OS);
3365 return OS;
3366}
3367#endif
3368
3369//===----------------------------------------------------------------------===//
3370// VPlan Utilities
3371//===----------------------------------------------------------------------===//
3372
3373/// Class that provides utilities for VPBlockBases in VPlan.
3375public:
3376 VPBlockUtils() = delete;
3377
3378 /// Insert disconnected VPBlockBase \p NewBlock after \p BlockPtr. Add \p
3379 /// NewBlock as successor of \p BlockPtr and \p BlockPtr as predecessor of \p
3380 /// NewBlock, and propagate \p BlockPtr parent to \p NewBlock. \p BlockPtr's
3381 /// successors are moved from \p BlockPtr to \p NewBlock. \p NewBlock must
3382 /// have neither successors nor predecessors.
3383 static void insertBlockAfter(VPBlockBase *NewBlock, VPBlockBase *BlockPtr) {
3384 assert(NewBlock->getSuccessors().empty() &&
3385 NewBlock->getPredecessors().empty() &&
3386 "Can't insert new block with predecessors or successors.");
3387 NewBlock->setParent(BlockPtr->getParent());
3388 SmallVector<VPBlockBase *> Succs(BlockPtr->successors());
3389 for (VPBlockBase *Succ : Succs) {
3390 disconnectBlocks(BlockPtr, Succ);
3391 connectBlocks(NewBlock, Succ);
3392 }
3393 connectBlocks(BlockPtr, NewBlock);
3394 }
3395
3396 /// Insert disconnected VPBlockBases \p IfTrue and \p IfFalse after \p
3397 /// BlockPtr. Add \p IfTrue and \p IfFalse as succesors of \p BlockPtr and \p
3398 /// BlockPtr as predecessor of \p IfTrue and \p IfFalse. Propagate \p BlockPtr
3399 /// parent to \p IfTrue and \p IfFalse. \p BlockPtr must have no successors
3400 /// and \p IfTrue and \p IfFalse must have neither successors nor
3401 /// predecessors.
3402 static void insertTwoBlocksAfter(VPBlockBase *IfTrue, VPBlockBase *IfFalse,
3403 VPBlockBase *BlockPtr) {
3404 assert(IfTrue->getSuccessors().empty() &&
3405 "Can't insert IfTrue with successors.");
3406 assert(IfFalse->getSuccessors().empty() &&
3407 "Can't insert IfFalse with successors.");
3408 BlockPtr->setTwoSuccessors(IfTrue, IfFalse);
3409 IfTrue->setPredecessors({BlockPtr});
3410 IfFalse->setPredecessors({BlockPtr});
3411 IfTrue->setParent(BlockPtr->getParent());
3412 IfFalse->setParent(BlockPtr->getParent());
3413 }
3414
3415 /// Connect VPBlockBases \p From and \p To bi-directionally. Append \p To to
3416 /// the successors of \p From and \p From to the predecessors of \p To. Both
3417 /// VPBlockBases must have the same parent, which can be null. Both
3418 /// VPBlockBases can be already connected to other VPBlockBases.
3420 assert((From->getParent() == To->getParent()) &&
3421 "Can't connect two block with different parents");
3422 assert(From->getNumSuccessors() < 2 &&
3423 "Blocks can't have more than two successors.");
3424 From->appendSuccessor(To);
3425 To->appendPredecessor(From);
3426 }
3427
3428 /// Disconnect VPBlockBases \p From and \p To bi-directionally. Remove \p To
3429 /// from the successors of \p From and \p From from the predecessors of \p To.
3431 assert(To && "Successor to disconnect is null.");
3432 From->removeSuccessor(To);
3433 To->removePredecessor(From);
3434 }
3435
3436 /// Return an iterator range over \p Range which only includes \p BlockTy
3437 /// blocks. The accesses are casted to \p BlockTy.
3438 template <typename BlockTy, typename T>
3439 static auto blocksOnly(const T &Range) {
3440 // Create BaseTy with correct const-ness based on BlockTy.
3441 using BaseTy = std::conditional_t<std::is_const<BlockTy>::value,
3442 const VPBlockBase, VPBlockBase>;
3443
3444 // We need to first create an iterator range over (const) BlocktTy & instead
3445 // of (const) BlockTy * for filter_range to work properly.
3446 auto Mapped =
3447 map_range(Range, [](BaseTy *Block) -> BaseTy & { return *Block; });
3449 Mapped, [](BaseTy &Block) { return isa<BlockTy>(&Block); });
3450 return map_range(Filter, [](BaseTy &Block) -> BlockTy * {
3451 return cast<BlockTy>(&Block);
3452 });
3453 }
3454};
3455
3458 InterleaveGroupMap;
3459
3460 /// Type for mapping of instruction based interleave groups to VPInstruction
3461 /// interleave groups
3464
3465 /// Recursively \p Region and populate VPlan based interleave groups based on
3466 /// \p IAI.
3467 void visitRegion(VPRegionBlock *Region, Old2NewTy &Old2New,
3469 /// Recursively traverse \p Block and populate VPlan based interleave groups
3470 /// based on \p IAI.
3471 void visitBlock(VPBlockBase *Block, Old2NewTy &Old2New,
3473
3474public:
3476
3479 // Avoid releasing a pointer twice.
3480 for (auto &I : InterleaveGroupMap)
3481 DelSet.insert(I.second);
3482 for (auto *Ptr : DelSet)
3483 delete Ptr;
3484 }
3485
3486 /// Get the interleave group that \p Instr belongs to.
3487 ///
3488 /// \returns nullptr if doesn't have such group.
3491 return InterleaveGroupMap.lookup(Instr);
3492 }
3493};
3494
3495/// Class that maps (parts of) an existing VPlan to trees of combined
3496/// VPInstructions.
3498 enum class OpMode { Failed, Load, Opcode };
3499
3500 /// A DenseMapInfo implementation for using SmallVector<VPValue *, 4> as
3501 /// DenseMap keys.
3502 struct BundleDenseMapInfo {
3503 static SmallVector<VPValue *, 4> getEmptyKey() {
3504 return {reinterpret_cast<VPValue *>(-1)};
3505 }
3506
3507 static SmallVector<VPValue *, 4> getTombstoneKey() {
3508 return {reinterpret_cast<VPValue *>(-2)};
3509 }
3510
3511 static unsigned getHashValue(const SmallVector<VPValue *, 4> &V) {
3512 return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
3513 }
3514
3515 static bool isEqual(const SmallVector<VPValue *, 4> &LHS,
3517 return LHS == RHS;
3518 }
3519 };
3520
3521 /// Mapping of values in the original VPlan to a combined VPInstruction.
3523 BundleToCombined;
3524
3526
3527 /// Basic block to operate on. For now, only instructions in a single BB are
3528 /// considered.
3529 const VPBasicBlock &BB;
3530
3531 /// Indicates whether we managed to combine all visited instructions or not.
3532 bool CompletelySLP = true;
3533
3534 /// Width of the widest combined bundle in bits.
3535 unsigned WidestBundleBits = 0;
3536
3537 using MultiNodeOpTy =
3538 typename std::pair<VPInstruction *, SmallVector<VPValue *, 4>>;
3539
3540 // Input operand bundles for the current multi node. Each multi node operand
3541 // bundle contains values not matching the multi node's opcode. They will
3542 // be reordered in reorderMultiNodeOps, once we completed building a
3543 // multi node.
3544 SmallVector<MultiNodeOpTy, 4> MultiNodeOps;
3545
3546 /// Indicates whether we are building a multi node currently.
3547 bool MultiNodeActive = false;
3548
3549 /// Check if we can vectorize Operands together.
3550 bool areVectorizable(ArrayRef<VPValue *> Operands) const;
3551
3552 /// Add combined instruction \p New for the bundle \p Operands.
3553 void addCombined(ArrayRef<VPValue *> Operands, VPInstruction *New);
3554
3555 /// Indicate we hit a bundle we failed to combine. Returns nullptr for now.
3556 VPInstruction *markFailed();
3557
3558 /// Reorder operands in the multi node to maximize sequential memory access
3559 /// and commutative operations.
3560 SmallVector<MultiNodeOpTy, 4> reorderMultiNodeOps();
3561
3562 /// Choose the best candidate to use for the lane after \p Last. The set of
3563 /// candidates to choose from are values with an opcode matching \p Last's
3564 /// or loads consecutive to \p Last.
3565 std::pair<OpMode, VPValue *> getBest(OpMode Mode, VPValue *Last,
3566 SmallPtrSetImpl<VPValue *> &Candidates,
3568
3569#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3570 /// Print bundle \p Values to dbgs().
3571 void dumpBundle(ArrayRef<VPValue *> Values);
3572#endif
3573
3574public:
3575 VPlanSlp(VPInterleavedAccessInfo &IAI, VPBasicBlock &BB) : IAI(IAI), BB(BB) {}
3576
3577 ~VPlanSlp() = default;
3578
3579 /// Tries to build an SLP tree rooted at \p Operands and returns a
3580 /// VPInstruction combining \p Operands, if they can be combined.
3582
3583 /// Return the width of the widest combined bundle in bits.
3584 unsigned getWidestBundleBits() const { return WidestBundleBits; }
3585
3586 /// Return true if all visited instruction can be combined.
3587 bool isCompletelySLP() const { return CompletelySLP; }
3588};
3589
3590namespace vputils {
3591
3592/// Returns true if only the first lane of \p Def is used.
3593bool onlyFirstLaneUsed(const VPValue *Def);
3594
3595/// Returns true if only the first part of \p Def is used.
3596bool onlyFirstPartUsed(const VPValue *Def);
3597
3598/// Get or create a VPValue that corresponds to the expansion of \p Expr. If \p
3599/// Expr is a SCEVConstant or SCEVUnknown, return a VPValue wrapping the live-in
3600/// value. Otherwise return a VPExpandSCEVRecipe to expand \p Expr. If \p Plan's
3601/// pre-header already contains a recipe expanding \p Expr, return it. If not,
3602/// create a new one.
3604 ScalarEvolution &SE);
3605
3606/// Returns true if \p VPV is uniform after vectorization.
3608 // A value defined outside the vector region must be uniform after
3609 // vectorization inside a vector region.
3611 return true;
3612 VPRecipeBase *Def = VPV->getDefiningRecipe();
3613 assert(Def && "Must have definition for value defined inside vector region");
3614 if (auto Rep = dyn_cast<VPReplicateRecipe>(Def))
3615 return Rep->isUniform();
3616 if (auto *GEP = dyn_cast<VPWidenGEPRecipe>(Def))
3617 return all_of(GEP->operands(), isUniformAfterVectorization);
3618 if (auto *VPI = dyn_cast<VPInstruction>(Def))
3619 return VPI->getOpcode() == VPInstruction::ComputeReductionResult;
3620 return false;
3621}
3622} // end namespace vputils
3623
3624} // end namespace llvm
3625
3626#endif // LLVM_TRANSFORMS_VECTORIZE_VPLAN_H
aarch64 promote const
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static MCDisassembler::DecodeStatus addOperand(MCInst &Inst, const MCOperand &Opnd)
always inline
BlockVerifier::State From
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
RelocType Type
Definition: COFFYAML.cpp:391
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition: Compiler.h:537
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
This file defines the DenseMap class.
uint64_t Addr
std::string Name
std::optional< std::vector< StOtherPiece > > Other
Definition: ELFYAML.cpp:1291
Flatten the CFG
Hexagon Common GEP
std::pair< BasicBlock *, unsigned > BlockTy
A pair of (basic block, score).
#define I(x, y, z)
Definition: MD5.cpp:58
mir Rename Register Operands
This file implements a map that provides insertion order iteration.
#define P(N)
static cl::opt< RegAllocEvictionAdvisorAnalysis::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysis::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysis::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysis::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysis::AdvisorMode::Development, "development", "for training")))
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
raw_pwrite_stream & OS
This file implements the SmallBitVector class.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file contains the declarations of the entities induced by Vectorization Plans,...
#define VP_CLASSOF_IMPL(VPDefID)
Definition: VPlan.h:804
Value * RHS
Value * LHS
static const uint32_t IV[8]
Definition: blake3_impl.h:78
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
ArrayRef< T > slice(size_t N, size_t M) const
slice(n, m) - Chop off the first N elements of the array, and keep M elements in the array.
Definition: ArrayRef.h:195
LLVM Basic Block Representation.
Definition: BasicBlock.h:60
This is the base class for all instructions that perform data casts.
Definition: InstrTypes.h:601
Instruction::CastOps getOpcode() const
Return the opcode of this CastInst.
Definition: InstrTypes.h:930
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition: InstrTypes.h:993
This class represents an Operation in the Expression.
A debug info location.
Definition: DebugLoc.h:33
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition: DenseMap.h:202
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition: DenseMap.h:151
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition: DenseMap.h:145
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition: Dominators.h:162
constexpr bool isScalar() const
Exactly one element.
Definition: TypeSize.h:319
Utility class for floating point operations which can have information about relaxed accuracy require...
Definition: Operator.h:201
Convenience struct for specifying and reasoning about fast-math flags.
Definition: FMF.h:20
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
Definition: Instructions.h:973
Common base class shared among various IRBuilders.
Definition: IRBuilder.h:94
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 ...
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
Definition: Instruction.h:252
The group of interleaved loads/stores sharing the same stride and close to each other.
Definition: VectorUtils.h:444
uint32_t getFactor() const
Definition: VectorUtils.h:460
InstTy * getMember(uint32_t Index) const
Get the member with the given index Index.
Definition: VectorUtils.h:514
Drive the analysis of interleaved memory accesses in the loop.
Definition: VectorUtils.h:586
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
An instruction for reading from memory.
Definition: Instructions.h:184
This class emits a version of the loop where run-time checks ensure that may-alias pointers can't ove...
Represents a single loop in the control flow graph.
Definition: LoopInfo.h:44
This class implements a map that also provides access to all stored values in a deterministic order.
Definition: MapVector.h:36
VectorType::iterator erase(typename VectorType::iterator Iterator)
Remove the element given by Iterator.
Definition: MapVector.h:193
The RecurrenceDescriptor is used to identify recurrences variables in a loop.
Definition: IVDescriptors.h:71
This class represents an analyzed expression in the program.
The main scalar evolution driver.
This class represents the LLVM 'select' instruction.
size_type size() const
Determine the number of elements in the SetVector.
Definition: SetVector.h:98
void clear()
Completely clear the SetVector.
Definition: SetVector.h:273
size_type count(const key_type &key) const
Count the number of elements of a given key in the SetVector.
Definition: SetVector.h:264
bool empty() const
Determine if the SetVector is empty or not.
Definition: SetVector.h:93
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition: SetVector.h:162
bool contains(const key_type &key) const
Check if the SetVector contains the given key.
Definition: SetVector.h:254
This class provides computation of slot numbers for LLVM Assembly writing.
Definition: AsmWriter.cpp:693
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
Definition: SmallPtrSet.h:321
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:342
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:427
A SetVector that performs no allocations if smaller than a certain size.
Definition: SetVector.h:370
bool empty() const
Definition: SmallVector.h:94
size_t size() const
Definition: SmallVector.h:91
iterator erase(const_iterator CI)
Definition: SmallVector.h:750
void push_back(const T &Elt)
Definition: SmallVector.h:426
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
An instruction for storing to memory.
Definition: Instructions.h:317
This class represents a truncation of integer types.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
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:45
Iterator to iterate over vectorization factors in a VFRange.
Definition: VPlan.h:111
ElementCount operator*() const
Definition: VPlan.h:119
iterator & operator++()
Definition: VPlan.h:121
iterator(ElementCount VF)
Definition: VPlan.h:115
bool operator==(const iterator &Other) const
Definition: VPlan.h:117
A recipe for generating the active lane mask for the vector loop that is used to predicate the vector...
Definition: VPlan.h:2622
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:2630
static bool classof(const VPHeaderPHIRecipe *D)
Definition: VPlan.h:2636
VPActiveLaneMaskPHIRecipe(VPValue *StartMask, DebugLoc DL)
Definition: VPlan.h:2624
~VPActiveLaneMaskPHIRecipe() override=default
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph.
Definition: VPlan.h:2826
RecipeListTy::const_iterator const_iterator
Definition: VPlan.h:2848
void appendRecipe(VPRecipeBase *Recipe)
Augment the existing recipes of a VPBasicBlock with an additional Recipe as the last recipe.
Definition: VPlan.h:2894
VPBasicBlock * clone() override
Clone the current block and it's recipes, without updating the operands of the cloned recipes.
Definition: VPlan.h:2938
RecipeListTy::const_reverse_iterator const_reverse_iterator
Definition: VPlan.h:2850
RecipeListTy::iterator iterator
Instruction iterators...
Definition: VPlan.h:2847
void execute(VPTransformState *State) override
The method which generates the output IR instructions that correspond to this VPBasicBlock,...
Definition: VPlan.cpp:443
RecipeListTy & getRecipeList()
Returns a reference to the list of recipes.
Definition: VPlan.h:2873
iterator end()
Definition: VPlan.h:2857
VPBasicBlock(const Twine &Name="", VPRecipeBase *Recipe=nullptr)
Definition: VPlan.h:2835
iterator begin()
Recipe iterator methods.
Definition: VPlan.h:2855
RecipeListTy::reverse_iterator reverse_iterator
Definition: VPlan.h:2849
iterator_range< iterator > phis()
Returns an iterator range over the PHI-like recipes in the block.
Definition: VPlan.h:2904
iterator getFirstNonPhi()
Return the position of the first non-phi node recipe in the block.
Definition: VPlan.cpp:210
~VPBasicBlock() override
Definition: VPlan.h:2841
VPRegionBlock * getEnclosingLoopRegion()
Definition: VPlan.cpp:546
void dropAllReferences(VPValue *NewValue) override
Replace all operands of VPUsers in the block with NewValue and also replaces all uses of VPValues def...
Definition: VPlan.cpp:511
const_reverse_iterator rbegin() const
Definition: VPlan.h:2861
reverse_iterator rend()
Definition: VPlan.h:2862
VPBasicBlock * splitAt(iterator SplitAt)
Split current block at SplitAt by inserting a new block between the current block and its successors ...
Definition: VPlan.cpp:521
VPRecipeBase & back()
Definition: VPlan.h:2870
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print this VPBsicBlock to O, prefixing all lines with Indent.
Definition: VPlan.cpp:613
const VPRecipeBase & front() const
Definition: VPlan.h:2867
const_iterator begin() const
Definition: VPlan.h:2856
VPRecipeBase & front()
Definition: VPlan.h:2868
bool isExiting() const
Returns true if the block is exiting it's parent region.
Definition: VPlan.cpp:596
VPRecipeBase * getTerminator()
If the block has multiple successors, return the branch recipe terminating the block.
Definition: VPlan.cpp:584
const VPRecipeBase & back() const
Definition: VPlan.h:2869
void insert(VPRecipeBase *Recipe, iterator InsertPt)
Definition: VPlan.h:2885
bool empty() const
Definition: VPlan.h:2866
const_iterator end() const
Definition: VPlan.h:2858
static bool classof(const VPBlockBase *V)
Method to support type inquiry through isa, cast, and dyn_cast.
Definition: VPlan.h:2881
static RecipeListTy VPBasicBlock::* getSublistAccess(VPRecipeBase *)
Returns a pointer to a member of the recipe list.
Definition: VPlan.h:2876
reverse_iterator rbegin()
Definition: VPlan.h:2860
size_t size() const
Definition: VPlan.h:2865
const_reverse_iterator rend() const
Definition: VPlan.h:2863
A recipe for vectorizing a phi-node as a sequence of mask-based select instructions.
Definition: VPlan.h:1949
VPBlendRecipe(PHINode *Phi, ArrayRef< VPValue * > Operands)
The blend operation is a User of the incoming values and of their respective masks,...
Definition: VPlan.h:1954
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
bool onlyFirstLaneUsed(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition: VPlan.h:1992
VPValue * getIncomingValue(unsigned Idx) const
Return incoming value number Idx.
Definition: VPlan.h:1972
VPValue * getMask(unsigned Idx) const
Return mask number Idx.
Definition: VPlan.h:1977
unsigned getNumIncomingValues() const
Return the number of incoming values, taking into account that the first incoming value has no mask.
Definition: VPlan.h:1969
VPBlendRecipe * clone() override
Clone the current recipe.
Definition: VPlan.h:1960
void execute(VPTransformState &State) override
Generate the phi/select nodes.
VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
Definition: VPlan.h:417
VPRegionBlock * getParent()
Definition: VPlan.h:489
VPBlocksTy & getPredecessors()
Definition: VPlan.h:520
const VPBasicBlock * getExitingBasicBlock() const
Definition: VPlan.cpp:175
LLVM_DUMP_METHOD void dump() const
Dump this VPBlockBase to dbgs().
Definition: VPlan.h:658
void setName(const Twine &newName)
Definition: VPlan.h:482
size_t getNumSuccessors() const
Definition: VPlan.h:534
iterator_range< VPBlockBase ** > successors()
Definition: VPlan.h:517
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.
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:601
bool isLegalToHoistInto()
Return true if it is legal to hoist instructions into this block.
Definition: VPlan.h:623
virtual ~VPBlockBase()=default
void print(raw_ostream &O) const
Print plain-text dump of this VPlan to O.
Definition: VPlan.h:648
const VPBlocksTy & getHierarchicalPredecessors()
Definition: VPlan.h:570
size_t getNumPredecessors() const
Definition: VPlan.h:535
void setPredecessors(ArrayRef< VPBlockBase * > NewPreds)
Set each VPBasicBlock in NewPreds as predecessor of this VPBlockBase.
Definition: VPlan.h:603
VPBlockBase * getEnclosingBlockWithPredecessors()
Definition: VPlan.cpp:197
const VPBlocksTy & getPredecessors() const
Definition: VPlan.h:519
virtual VPBlockBase * clone()=0
Clone the current block and it's recipes without updating the operands of the cloned recipes,...
static void deleteCFG(VPBlockBase *Entry)
Delete all blocks reachable from a given VPBlockBase, inclusive.
Definition: VPlan.cpp:205
VPlan * getPlan()
Definition: VPlan.cpp:148
void setPlan(VPlan *ParentPlan)
Sets the pointer of the plan containing the block.
Definition: VPlan.cpp:167
const VPRegionBlock * getParent() const
Definition: VPlan.h:490
void printAsOperand(raw_ostream &OS, bool PrintType) const
Definition: VPlan.h:634
const std::string & getName() const
Definition: VPlan.h:480
void clearSuccessors()
Remove all the successors of this block.
Definition: VPlan.h:613
VPBlockBase * getSingleHierarchicalSuccessor()
Definition: VPlan.h:560
void setTwoSuccessors(VPBlockBase *IfTrue, VPBlockBase *IfFalse)
Set two given VPBlockBases IfTrue and IfFalse to be the two successors of this VPBlockBase.
Definition: VPlan.h:594
VPBlockBase * getSinglePredecessor() const
Definition: VPlan.h:530
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:554
void clearPredecessors()
Remove all the predecessor of this block.
Definition: VPlan.h:610
enum { VPBasicBlockSC, VPRegionBlockSC } VPBlockTy
An enumeration for keeping track of the concrete subclass of VPBlockBase that are actually instantiat...
Definition: VPlan.h:474
unsigned getVPBlockID() const
Definition: VPlan.h:487
VPBlockBase(const unsigned char SC, const std::string &N)
Definition: VPlan.h:466
VPBlocksTy & getSuccessors()
Definition: VPlan.h:515
VPBlockBase * getEnclosingBlockWithSuccessors()
An Enclosing Block of a block B is any block containing B, including B itself.
Definition: VPlan.cpp:189
const VPBasicBlock * getEntryBasicBlock() const
Definition: VPlan.cpp:153
void setOneSuccessor(VPBlockBase *Successor)
Set a given VPBlockBase Successor as the single successor of this VPBlockBase.
Definition: VPlan.h:583
void setParent(VPRegionBlock *P)
Definition: VPlan.h:500
virtual void dropAllReferences(VPValue *NewValue)=0
Replace all operands of VPUsers in the block with NewValue and also replaces all uses of VPValues def...
VPBlockBase * getSingleHierarchicalPredecessor()
Definition: VPlan.h:576
VPBlockBase * getSingleSuccessor() const
Definition: VPlan.h:524
const VPBlocksTy & getSuccessors() const
Definition: VPlan.h:514
Class that provides utilities for VPBlockBases in VPlan.
Definition: VPlan.h:3374
static auto blocksOnly(const T &Range)
Return an iterator range over Range which only includes BlockTy blocks.
Definition: VPlan.h:3439
static void insertBlockAfter(VPBlockBase *NewBlock, VPBlockBase *BlockPtr)
Insert disconnected VPBlockBase NewBlock after BlockPtr.
Definition: VPlan.h:3383
static void insertTwoBlocksAfter(VPBlockBase *IfTrue, VPBlockBase *IfFalse, VPBlockBase *BlockPtr)
Insert disconnected VPBlockBases IfTrue and IfFalse after BlockPtr.
Definition: VPlan.h:3402
static void disconnectBlocks(VPBlockBase *From, VPBlockBase *To)
Disconnect VPBlockBases From and To bi-directionally.
Definition: VPlan.h:3430
static void connectBlocks(VPBlockBase *From, VPBlockBase *To)
Connect VPBlockBases From and To bi-directionally.
Definition: VPlan.h:3419
A recipe for generating conditional branches on the bits of a mask.
Definition: VPlan.h:2216
VPValue * getMask() const
Return the mask used by this recipe.
Definition: VPlan.h:2248
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
Definition: VPlan.h:2236
VPBranchOnMaskRecipe(VPValue *BlockInMask)
Definition: VPlan.h:2218
VPBranchOnMaskRecipe * clone() override
Clone the current recipe.
Definition: VPlan.h:2224
bool usesScalars(const VPValue *Op) const override
Returns true if the recipe uses scalars of operand Op.
Definition: VPlan.h:2255
void execute(VPTransformState &State) override
Generate the extraction of the appropriate bit from the block mask and the conditional branch.
Canonical scalar induction phi of the vector loop.
Definition: VPlan.h:2565
bool onlyFirstPartUsed(const VPValue *Op) const override
Returns true if the recipe only uses the first part of operand Op.
Definition: VPlan.h:2606
~VPCanonicalIVPHIRecipe() override=default
static bool classof(const VPHeaderPHIRecipe *D)
Definition: VPlan.h:2580
VPCanonicalIVPHIRecipe * clone() override
Clone the current recipe.
Definition: VPlan.h:2572
VPCanonicalIVPHIRecipe(VPValue *StartV, DebugLoc DL)
Definition: VPlan.h:2567
bool onlyFirstLaneUsed(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition: VPlan.h:2599
void execute(VPTransformState &State) override
Generate the canonical scalar induction phi of the vector loop.
Type * getScalarType() const
Returns the scalar type of the induction.
Definition: VPlan.h:2594
bool isCanonical(InductionDescriptor::InductionKind Kind, VPValue *Start, VPValue *Step) const
Check if the induction described by Kind, /p Start and Step is canonical, i.e.
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
This class augments a recipe with a set of VPValues defined by the recipe.
Definition: VPlanValue.h:313
unsigned getVPDefID() const
Definition: VPlanValue.h:433
A recipe for converting the input value IV value to the corresponding value of an IV with different s...
Definition: VPlan.h:2719
void execute(VPTransformState &State) override
Generate the transformed value of the induction at offset StartValue (1.
VPDerivedIVRecipe(InductionDescriptor::InductionKind Kind, const FPMathOperator *FPBinOp, VPValue *Start, VPValue *IV, VPValue *Step)
Definition: VPlan.h:2734
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPValue * getStepValue() const
Definition: VPlan.h:2764
VPDerivedIVRecipe(const InductionDescriptor &IndDesc, VPValue *Start, VPCanonicalIVPHIRecipe *CanonicalIV, VPValue *Step)
Definition: VPlan.h:2727
Type * getScalarType() const
Definition: VPlan.h:2759
VPDerivedIVRecipe * clone() override
Clone the current recipe.
Definition: VPlan.h:2742
~VPDerivedIVRecipe() override=default
bool onlyFirstLaneUsed(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition: VPlan.h:2767
VPValue * getStartValue() const
Definition: VPlan.h:2763
A recipe for generating the phi node for the current index of elements, adjusted in accordance with E...
Definition: VPlan.h:2654
static bool classof(const VPHeaderPHIRecipe *D)
Definition: VPlan.h:2667
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPEVLBasedIVPHIRecipe * clone() override
Clone the current recipe.
Definition: VPlan.h:2661
~VPEVLBasedIVPHIRecipe() override=default
void execute(VPTransformState &State) override
Generate phi for handling IV based on EVL over iterations correctly.
VPEVLBasedIVPHIRecipe(VPValue *StartIV, DebugLoc DL)
Definition: VPlan.h:2656
bool onlyFirstLaneUsed(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition: VPlan.h:2676
Recipe to expand a SCEV expression.
Definition: VPlan.h:2533
VPExpandSCEVRecipe(const SCEV *Expr, ScalarEvolution &SE)
Definition: VPlan.h:2538
const SCEV * getSCEV() const
Definition: VPlan.h:2558
void execute(VPTransformState &State) override
Generate a canonical vector induction variable of the vector loop, with.
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPExpandSCEVRecipe * clone() override
Clone the current recipe.
Definition: VPlan.h:2543
~VPExpandSCEVRecipe() override=default
A pure virtual base class for all recipes modeling header phis, including phis for first order recurr...
Definition: VPlan.h:1635
static bool classof(const VPValue *V)
Definition: VPlan.h:1652
VPHeaderPHIRecipe(unsigned char VPDefID, Instruction *UnderlyingInstr, VPValue *Start=nullptr, DebugLoc DL={})
Definition: VPlan.h:1637
void print(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:1679
VPValue * getStartValue()
Returns the start value of the phi, if one is set.
Definition: VPlan.h:1668
void setStartValue(VPValue *V)
Update the start value of the recipe.
Definition: VPlan.h:1676
VPValue * getStartValue() const
Definition: VPlan.h:1671
static bool classof(const VPRecipeBase *B)
Method to support type inquiry through isa, cast, and dyn_cast.
Definition: VPlan.h:1648
void execute(VPTransformState &State) override=0
Generate the phi nodes.
virtual VPRecipeBase & getBackedgeRecipe()
Returns the backedge value as a recipe.
Definition: VPlan.h:1685
~VPHeaderPHIRecipe() override=default
This is a concrete Recipe that models a single VPlan-level instruction.
Definition: VPlan.h:1160
bool onlyFirstPartUsed(const VPValue *Op) const override
Returns true if the recipe only uses the first part of operand Op.
Definition: VPlan.h:1310
VPInstruction(unsigned Opcode, ArrayRef< VPValue * > Operands, DebugLoc DL, const Twine &Name="")
Definition: VPlan.h:1223
VPInstruction * clone() override
Clone the current recipe.
Definition: VPlan.h:1253
@ FirstOrderRecurrenceSplice
Definition: VPlan.h:1166
@ CanonicalIVIncrementForPart
Definition: VPlan.h:1176
@ CalculateTripCountMinusVF
Definition: VPlan.h:1174
bool hasResult() const
Definition: VPlan.h:1284
LLVM_DUMP_METHOD void dump() const
Print the VPInstruction to dbgs() (for debugging).
unsigned getOpcode() const
Definition: VPlan.h:1260
VPInstruction(unsigned Opcode, std::initializer_list< VPValue * > Operands, WrapFlagsTy WrapFlags, DebugLoc DL={}, const Twine &Name="")
Definition: VPlan.h:1235
VPInstruction(unsigned Opcode, std::initializer_list< VPValue * > Operands, DebugLoc DL={}, const Twine &Name="")
Definition: VPlan.h:1228
VPInstruction(unsigned Opcode, std::initializer_list< VPValue * > Operands, DisjointFlagsTy DisjointFlag, DebugLoc DL={}, const Twine &Name="")
Definition: VPlan.h:1240
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the VPInstruction to O.
bool onlyFirstLaneUsed(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
bool mayWriteToMemory() const
Return true if this instruction may modify memory.
Definition: VPlan.h:1277
void execute(VPTransformState &State) override
Generate the instruction.
VPInterleaveRecipe is a recipe for transforming an interleave group of load or stores into one wide l...
Definition: VPlan.h:2006
bool onlyFirstLaneUsed(const VPValue *Op) const override
The recipe only uses the first lane of the address.
Definition: VPlan.h:2085
~VPInterleaveRecipe() override=default
VPValue * getAddr() const
Return the address accessed by this recipe.
Definition: VPlan.h:2047
VPInterleaveRecipe(const InterleaveGroup< Instruction > *IG, VPValue *Addr, ArrayRef< VPValue * > StoredValues, VPValue *Mask, bool NeedsMaskForGaps)
Definition: VPlan.h:2018
VPValue * getMask() const
Return the mask used by this recipe.
Definition: VPlan.h:2053
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPInterleaveRecipe * clone() override
Clone the current recipe.
Definition: VPlan.h:2039
void execute(VPTransformState &State) override
Generate the wide load or store, and shuffles.
ArrayRef< VPValue * > getStoredValues() const
Return the VPValues stored by this interleave group.
Definition: VPlan.h:2060
const InterleaveGroup< Instruction > * getInterleaveGroup()
Definition: VPlan.h:2076
unsigned getNumStoreOperands() const
Returns the number of stored operands of this interleave group.
Definition: VPlan.h:2080
InterleaveGroup< VPInstruction > * getInterleaveGroup(VPInstruction *Instr) const
Get the interleave group that Instr belongs to.
Definition: VPlan.h:3490
In what follows, the term "input IR" refers to code that is fed into the vectorizer whereas the term ...
Definition: VPlan.h:143
static VPLane getLastLaneForVF(const ElementCount &VF)
Definition: VPlan.h:169
static unsigned getNumCachedLanes(const ElementCount &VF)
Returns the maxmimum number of lanes that we are able to consider caching for VF.
Definition: VPlan.h:212
Value * getAsRuntimeExpr(IRBuilderBase &Builder, const ElementCount &VF) const
Returns an expression describing the lane index that can be used at runtime.
Definition: VPlan.cpp:68
VPLane(unsigned Lane, Kind LaneKind)
Definition: VPlan.h:165
Kind getKind() const
Returns the Kind of lane offset.
Definition: VPlan.h:193
bool isFirstLane() const
Returns true if this is the first lane of the whole vector.
Definition: VPlan.h:196
unsigned getKnownLane() const
Returns a compile-time known value for the lane index and asserts if the lane can only be calculated ...
Definition: VPlan.h:183
static VPLane getFirstLane()
Definition: VPlan.h:167
Kind
Kind describes how to interpret Lane.
Definition: VPlan.h:146
@ ScalableLast
For ScalableLast, Lane is the offset from the start of the last N-element subvector in a scalable vec...
@ First
For First, Lane is the index into the first N elements of a fixed-vector <N x <ElTy>> or a scalable v...
unsigned mapToCacheIndex(const ElementCount &VF) const
Maps the lane to a cache index based on VF.
Definition: VPlan.h:199
A value that is used outside the VPlan.
Definition: VPlan.h:669
VPLiveOut(PHINode *Phi, VPValue *Op)
Definition: VPlan.h:673
static bool classof(const VPUser *U)
Definition: VPlan.h:676
bool usesScalars(const VPValue *Op) const override
Returns true if the VPLiveOut uses scalars of operand Op.
Definition: VPlan.h:688
void print(raw_ostream &O, VPSlotTracker &SlotTracker) const
Print the VPLiveOut to O.
PHINode * getPhi() const
Definition: VPlan.h:694
void fixPhi(VPlan &Plan, VPTransformState &State)
Fixup the wrapped LCSSA phi node in the unique exit block.
VPPredInstPHIRecipe is a recipe for generating the phi nodes needed when control converges back from ...
Definition: VPlan.h:2267
~VPPredInstPHIRecipe() override=default
bool usesScalars(const VPValue *Op) const override
Returns true if the recipe uses scalars of operand Op.
Definition: VPlan.h:2291
VPPredInstPHIRecipe(VPValue *PredV)
Construct a VPPredInstPHIRecipe given PredInst whose value needs a phi nodes after merging back from ...
Definition: VPlan.h:2271
void execute(VPTransformState &State) override
Generates phi nodes for live-outs as needed to retain SSA form.
VPPredInstPHIRecipe * clone() override
Clone the current recipe.
Definition: VPlan.h:2275
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPRecipeBase is a base class modeling a sequence of one or more output IR instructions.
Definition: VPlan.h:709
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:795
bool mayHaveSideEffects() const
Returns true if the recipe may have side-effects.
bool mayWriteToMemory() const
Returns true if the recipe may write to memory.
virtual ~VPRecipeBase()=default
VPBasicBlock * getParent()
Definition: VPlan.h:734
DebugLoc getDebugLoc() const
Returns the debug location of the recipe.
Definition: VPlan.h:800
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:771
iplist< VPRecipeBase >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
VPRecipeBase(const unsigned char SC, ArrayRef< VPValue * > Operands, DebugLoc DL={})
Definition: VPlan.h:720
virtual VPRecipeBase * clone()=0
Clone the current recipe.
const VPBasicBlock * getParent() const
Definition: VPlan.h:735
static bool classof(const VPUser *U)
Definition: VPlan.h:776
VPRecipeBase(const unsigned char SC, iterator_range< IterT > Operands, DebugLoc DL={})
Definition: VPlan.h:725
void removeFromParent()
This method unlinks 'this' from the containing basic block, but does not delete it.
bool isPhi() const
Returns true for PHI-like recipes.
Definition: VPlan.h:784
void moveAfter(VPRecipeBase *MovePos)
Unlink this recipe from its current VPBasicBlock and insert it into the VPBasicBlock that MovePos liv...
Class to record LLVM IR flag for a recipe along with it.
Definition: VPlan.h:898
ExactFlagsTy ExactFlags
Definition: VPlan.h:954
FastMathFlagsTy FMFs
Definition: VPlan.h:957
VPRecipeWithIRFlags(const unsigned char SC, IterT Operands, GEPFlagsTy GEPFlags, DebugLoc DL={})
Definition: VPlan.h:1031
NonNegFlagsTy NonNegFlags
Definition: VPlan.h:956
CmpInst::Predicate CmpPredicate
Definition: VPlan.h:951
VPRecipeWithIRFlags(const unsigned char SC, IterT Operands, CmpInst::Predicate Pred, DebugLoc DL={})
Definition: VPlan.h:1006
void setFlags(Instruction *I) const
Set the IR flags for I.
Definition: VPlan.h:1083
bool isInBounds() const
Definition: VPlan.h:1122
GEPFlagsTy GEPFlags
Definition: VPlan.h:955
static bool classof(const VPRecipeBase *R)
Definition: VPlan.h:1037
VPRecipeWithIRFlags(const unsigned char SC, IterT Operands, FastMathFlags FMFs, DebugLoc DL={})
Definition: VPlan.h:1018
void dropPoisonGeneratingFlags()
Drop all poison-generating flags.
Definition: VPlan.h:1052
bool hasFastMathFlags() const
Returns true if the recipe has fast-math flags.
Definition: VPlan.h:1129
VPRecipeWithIRFlags(const unsigned char SC, IterT Operands, Instruction &I)
Definition: VPlan.h:976
DisjointFlagsTy DisjointFlags
Definition: VPlan.h:953
VPRecipeWithIRFlags(const unsigned char SC, IterT Operands, WrapFlagsTy WrapFlags, DebugLoc DL={})
Definition: VPlan.h:1012
VPRecipeWithIRFlags(const unsigned char SC, IterT Operands, DisjointFlagsTy DisjointFlags, DebugLoc DL={})
Definition: VPlan.h:1024
void transferFlags(VPRecipeWithIRFlags &Other)
Definition: VPlan.h:962
WrapFlagsTy WrapFlags
Definition: VPlan.h:952
bool hasNoUnsignedWrap() const
Definition: VPlan.h:1133
bool isDisjoint() const
Definition: VPlan.h:1145
void printFlags(raw_ostream &O) const
CmpInst::Predicate getPredicate() const
Definition: VPlan.h:1116
bool hasNoSignedWrap() const
Definition: VPlan.h:1139
static bool classof(const VPUser *U)
Definition: VPlan.h:1046
FastMathFlags getFastMathFlags() const
VPRecipeWithIRFlags(const unsigned char SC, IterT Operands, DebugLoc DL={})
Definition: VPlan.h:969
A recipe for handling reduction phis.
Definition: VPlan.h:1890
VPReductionPHIRecipe(PHINode *Phi, const RecurrenceDescriptor &RdxDesc, VPValue &Start, bool IsInLoop=false, bool IsOrdered=false)
Create a new VPReductionPHIRecipe for the reduction Phi described by RdxDesc.
Definition: VPlan.h:1903
bool isOrdered() const
Returns true, if the phi is part of an ordered reduction.
Definition: VPlan.h:1941
VPReductionPHIRecipe * clone() override
Clone the current recipe.
Definition: VPlan.h:1913
~VPReductionPHIRecipe() override=default
bool isInLoop() const
Returns true, if the phi is part of an in-loop reduction.
Definition: VPlan.h:1944
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
Generate the phi/select nodes.
static bool classof(const VPHeaderPHIRecipe *R)
Definition: VPlan.h:1923
const RecurrenceDescriptor & getRecurrenceDescriptor() const
Definition: VPlan.h:1936
A recipe to represent inloop reduction operations, performing a reduction on a vector operand into a ...
Definition: VPlan.h:2095
VPValue * getVecOp() const
The VPValue of the vector value to be reduced.
Definition: VPlan.h:2132
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPReductionRecipe(const RecurrenceDescriptor &R, Instruction *I, VPValue *ChainOp, VPValue *VecOp, VPValue *CondOp, bool IsOrdered)
Definition: VPlan.h:2101
VPValue * getCondOp() const
The VPValue of the condition for the block.
Definition: VPlan.h:2134
~VPReductionRecipe() override=default
VPValue * getChainOp() const
The VPValue of the scalar Chain being accumulated.
Definition: VPlan.h:2130
VPReductionRecipe * clone() override
Clone the current recipe.
Definition: VPlan.h:2113
void execute(VPTransformState &State) override
Generate the reduction in the loop.
VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks which form a Single-Entry-S...
Definition: VPlan.h:2959
VPRegionBlock * clone() override
Clone all blocks in the single-entry single-exit region of the block and their recipes without updati...
Definition: VPlan.cpp:666
const VPBlockBase * getEntry() const
Definition: VPlan.h:2998
bool isReplicator() const
An indicator whether this region is to generate multiple replicated instances of output IR correspond...
Definition: VPlan.h:3030
void dropAllReferences(VPValue *NewValue) override
Replace all operands of VPUsers in the block with NewValue and also replaces all uses of VPValues def...
Definition: VPlan.cpp:675
void setExiting(VPBlockBase *ExitingBlock)
Set ExitingBlock as the exiting VPBlockBase of this VPRegionBlock.
Definition: VPlan.h:3015
VPBlockBase * getExiting()
Definition: VPlan.h:3011
void setEntry(VPBlockBase *EntryBlock)
Set EntryBlock as the entry VPBlockBase of this VPRegionBlock.
Definition: VPlan.h:3003
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print this VPRegionBlock to O (recursively), prefixing all lines with Indent.
Definition: VPlan.cpp:734
VPRegionBlock(const std::string &Name="", bool IsReplicator=false)
Definition: VPlan.h:2981
VPRegionBlock(VPBlockBase *Entry, VPBlockBase *Exiting, const std::string &Name="", bool IsReplicator=false)
Definition: VPlan.h:2972
void execute(VPTransformState *State) override
The method which generates the output IR instructions that correspond to this VPRegionBlock,...
Definition: VPlan.cpp:682
const VPBlockBase * getExiting() const
Definition: VPlan.h:3010
VPBlockBase * getEntry()
Definition: VPlan.h:2999
VPBasicBlock * getPreheaderVPBB()
Returns the pre-header VPBasicBlock of the loop region.
Definition: VPlan.h:3023
~VPRegionBlock() override
Definition: VPlan.h:2985
static bool classof(const VPBlockBase *V)
Method to support type inquiry through isa, cast, and dyn_cast.
Definition: VPlan.h:2994
VPReplicateRecipe replicates a given instruction producing multiple scalar copies of the original sca...
Definition: VPlan.h:2143
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
Generate replicas of the desired Ingredient.
~VPReplicateRecipe() override=default
bool onlyFirstLaneUsed(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition: VPlan.h:2188
bool usesScalars(const VPValue *Op) const override
Returns true if the recipe uses scalars of operand Op.
Definition: VPlan.h:2195
bool isUniform() const
Definition: VPlan.h:2183
bool isPredicated() const
Definition: VPlan.h:2185
VPReplicateRecipe * clone() override
Clone the current recipe.
Definition: VPlan.h:2162
VPReplicateRecipe(Instruction *I, iterator_range< IterT > Operands, bool IsUniform, VPValue *Mask=nullptr)
Definition: VPlan.h:2152
unsigned getOpcode() const
Definition: VPlan.h:2212
VPValue * getMask()
Return the mask of a predicated VPReplicateRecipe.
Definition: VPlan.h:2207
bool shouldPack() const
Returns true if the recipe is used by a widened recipe via an intervening VPPredInstPHIRecipe.
VPScalarCastRecipe is a recipe to create scalar cast instructions.
Definition: VPlan.h:1411
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Each concrete VPDef prints itself.
~VPScalarCastRecipe() override=default
VPScalarCastRecipe * clone() override
Clone the current recipe.
Definition: VPlan.h:1425
bool onlyFirstLaneUsed(const VPValue *Op) const override
Returns true if the VPUser only uses the first lane of operand Op.
Definition: VPlan.h:1441
void execute(VPTransformState &State) override
The method which generates the output IR instructions that correspond to this VPRecipe,...
Type * getResultType() const
Returns the result type of the cast.
Definition: VPlan.h:1439
VPScalarCastRecipe(Instruction::CastOps Opcode, VPValue *Op, Type *ResultTy)
Definition: VPlan.h:1419
A recipe for handling phi nodes of integer and floating-point inductions, producing their scalar valu...
Definition: VPlan.h:2776
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
bool onlyFirstLaneUsed(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition: VPlan.h:2816
VPValue * getStepValue() const
Definition: VPlan.h:2813
VPScalarIVStepsRecipe(const InductionDescriptor &IndDesc, VPValue *IV, VPValue *Step)
Definition: VPlan.h:2786
VPScalarIVStepsRecipe * clone() override
Clone the current recipe.
Definition: VPlan.h:2796
VPScalarIVStepsRecipe(VPValue *IV, VPValue *Step, Instruction::BinaryOps Opcode, FastMathFlags FMFs)
Definition: VPlan.h:2780
~VPScalarIVStepsRecipe() override=default
void execute(VPTransformState &State) override
Generate the scalarized versions of the phi node as needed by their users.
VPSingleDef is a base class for recipes for modeling a sequence of one or more output IR that define ...
Definition: VPlan.h:826
VPSingleDefRecipe(const unsigned char SC, ArrayRef< VPValue * > Operands, DebugLoc DL={})
Definition: VPlan.h:832
Instruction * getUnderlyingInstr()
Returns the underlying instruction.
Definition: VPlan.h:889
static bool classof(const VPRecipeBase *R)
Definition: VPlan.h:841
const Instruction * getUnderlyingInstr() const
Definition: VPlan.h:892
VPSingleDefRecipe(const unsigned char SC, IterT Operands, DebugLoc DL={})
Definition: VPlan.h:829
static bool classof(const VPUser *U)
Definition: VPlan.h:881
VPSingleDefRecipe(const unsigned char SC, IterT Operands, Value *UV, DebugLoc DL={})
Definition: VPlan.h:837
virtual VPSingleDefRecipe * clone() override=0
Clone the current recipe.
This class can be used to assign names to VPValues.
Definition: VPlanValue.h:454
An analysis for type-inference for VPValues.
Definition: VPlanAnalysis.h:36
This class augments VPValue with operands which provide the inverse def-use edges from VPValue's user...
Definition: VPlanValue.h:203
operand_range operands()
Definition: VPlanValue.h:278
void setOperand(unsigned I, VPValue *New)
Definition: VPlanValue.h:258
unsigned getNumOperands() const
Definition: VPlanValue.h:252
operand_iterator op_begin()
Definition: VPlanValue.h:274
VPValue * getOperand(unsigned N) const
Definition: VPlanValue.h:253
VPUser()=delete
void addOperand(VPValue *Operand)
Definition: VPlanValue.h:247
Value * getUnderlyingValue()
Return the underlying Value attached to this VPValue.
Definition: VPlanValue.h:77
VPRecipeBase * getDefiningRecipe()
Returns the recipe defining this VPValue or nullptr if it is not defined by a recipe,...
Definition: VPlan.cpp:118
unsigned getNumUsers() const
Definition: VPlanValue.h:112
Value * getLiveInIRValue()
Returns the underlying IR value, if this VPValue is defined outside the scope of VPlan.
Definition: VPlanValue.h:173
bool isLiveIn() const
Returns true if this VPValue is a live-in, i.e. defined outside the VPlan.
Definition: VPlanValue.h:168
friend class VPRecipeBase
Definition: VPlanValue.h:52
user_range users()
Definition: VPlanValue.h:133
bool isDefinedOutsideVectorRegions() const
Returns true if the VPValue is defined outside any vector regions, i.e.
Definition: VPlanValue.h:187
A recipe to compute the pointers for widened memory accesses of IndexTy for all parts.
Definition: VPlan.h:1579
void print(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,...
VPVectorPointerRecipe(VPValue *Ptr, Type *IndexedTy, bool IsReverse, bool IsInBounds, DebugLoc DL)
Definition: VPlan.h:1584
bool onlyFirstLaneUsed(const VPValue *Op) const override
Returns true if the VPUser only uses the first lane of operand Op.
Definition: VPlan.h:1594
VPVectorPointerRecipe * clone() override
Clone the current recipe.
Definition: VPlan.h:1600
A recipe for widening Call instructions.
Definition: VPlan.h:1450
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
const_operand_range arg_operands() const
Definition: VPlan.h:1491
VPWidenCallRecipe * clone() override
Clone the current recipe.
Definition: VPlan.h:1474
VPWidenCallRecipe(Value *UV, iterator_range< IterT > CallArguments, Intrinsic::ID VectorIntrinsicID, DebugLoc DL={}, Function *Variant=nullptr)
Definition: VPlan.h:1462
Function * getCalledScalarFunction() const
Definition: VPlan.h:1484
void execute(VPTransformState &State) override
Produce a widened version of the call instruction.
operand_range arg_operands()
Definition: VPlan.h:1488
~VPWidenCallRecipe() override=default
A Recipe for widening the canonical induction variable of the vector loop.
Definition: VPlan.h:2690
void execute(VPTransformState &State) override
Generate a canonical vector induction variable of the vector loop, with start = {<Part*VF,...
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
~VPWidenCanonicalIVRecipe() override=default
VPWidenCanonicalIVRecipe * clone() override
Clone the current recipe.
Definition: VPlan.h:2697
VPWidenCanonicalIVRecipe(VPCanonicalIVPHIRecipe *CanonicalIV)
Definition: VPlan.h:2692
VPWidenCastRecipe is a recipe to create vector cast instructions.
Definition: VPlan.h:1361
VPWidenCastRecipe(Instruction::CastOps Opcode, VPValue *Op, Type *ResultTy, CastInst &UI)
Definition: VPlan.h:1369
Instruction::CastOps getOpcode() const
Definition: VPlan.h:1404
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
Type * getResultType() const
Returns the result type of the cast.
Definition: VPlan.h:1407
VPWidenCastRecipe(Instruction::CastOps Opcode, VPValue *Op, Type *ResultTy)
Definition: VPlan.h:1379
void execute(VPTransformState &State) override
Produce widened copies of the cast.
~VPWidenCastRecipe() override=default
VPWidenCastRecipe * clone() override
Clone the current recipe.
Definition: VPlan.h:1385
A recipe for handling GEP instructions.
Definition: VPlan.h:1537
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
Generate the gep nodes.
VPWidenGEPRecipe * clone() override
Clone the current recipe.
Definition: VPlan.h:1559
~VPWidenGEPRecipe() override=default
VPWidenGEPRecipe(GetElementPtrInst *GEP, iterator_range< IterT > Operands)
Definition: VPlan.h:1554
A recipe for handling phi nodes of integer and floating-point inductions, producing their vector valu...
Definition: VPlan.h:1692
VPWidenIntOrFpInductionRecipe(PHINode *IV, VPValue *Start, VPValue *Step, const InductionDescriptor &IndDesc, TruncInst *Trunc)
Definition: VPlan.h:1705
const TruncInst * getTruncInst() const
Definition: VPlan.h:1753
VPRecipeBase & getBackedgeRecipe() override
Returns the backedge value as a recipe.
Definition: VPlan.h:1739
~VPWidenIntOrFpInductionRecipe() override=default
VPWidenIntOrFpInductionRecipe * clone() override
Clone the current recipe.
Definition: VPlan.h:1715
TruncInst * getTruncInst()
Returns the first defined value as TruncInst, if it is one or nullptr otherwise.
Definition: VPlan.h:1752
void execute(VPTransformState &State) override
Generate the vectorized and scalarized versions of the phi node as needed by their users.
VPValue * getStepValue()
Returns the step value of the induction.
Definition: VPlan.h:1747
VPWidenIntOrFpInductionRecipe(PHINode *IV, VPValue *Start, VPValue *Step, const InductionDescriptor &IndDesc)
Definition: VPlan.h:1698
const VPValue * getStepValue() const
Definition: VPlan.h:1748
Type * getScalarType() const
Returns the scalar type of the induction.
Definition: VPlan.h:1766
VPValue * getBackedgeValue() override
Returns the incoming value from the loop backedge.
Definition: VPlan.h:1732
bool isCanonical() const
Returns true if the induction is canonical, i.e.
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
const InductionDescriptor & getInductionDescriptor() const
Returns the induction descriptor for the recipe.
Definition: VPlan.h:1758
A common base class for widening memory operations.
Definition: VPlan.h:2300
bool IsMasked
Whether the memory access is masked.
Definition: VPlan.h:2311
bool Reverse
Whether the consecutive accessed addresses are in reverse order.
Definition: VPlan.h:2308
bool isConsecutive() const
Return whether the loaded-from / stored-to addresses are consecutive.
Definition: VPlan.h:2347
static bool classof(const VPUser *U)
Definition: VPlan.h:2341
void execute(VPTransformState &State) override
Generate the wide load/store.
Definition: VPlan.h:2367
Instruction & Ingredient
Definition: VPlan.h:2302
VPWidenMemoryRecipe * clone() override
Clone the current recipe.
Definition: VPlan.h:2330
Instruction & getIngredient() const
Definition: VPlan.h:2371
bool Consecutive
Whether the accessed addresses are consecutive.
Definition: VPlan.h:2305
static bool classof(const VPRecipeBase *R)
Definition: VPlan.h:2334
VPWidenMemoryRecipe(const char unsigned SC, Instruction &I, std::initializer_list< VPValue * > Operands, bool Consecutive, bool Reverse, DebugLoc DL)
Definition: VPlan.h:2321
VPValue * getMask() const
Return the mask used by this recipe.
Definition: VPlan.h:2361
bool isMasked() const
Returns true if the recipe is masked.
Definition: VPlan.h:2357
void setMask(VPValue *Mask)
Definition: VPlan.h:2313
VPValue * getAddr() const
Return the address accessed by this recipe.
Definition: VPlan.h:2354
bool isReverse() const
Return whether the consecutive loaded/stored addresses are in reverse order.
Definition: VPlan.h:2351
A recipe for handling phis that are widened in the vector loop.
Definition: VPlan.h:1818
void addIncoming(VPValue *IncomingV, VPBasicBlock *IncomingBlock)
Adds a pair (IncomingV, IncomingBlock) to the phi.
Definition: VPlan.h:1848
VPValue * getIncomingValue(unsigned I)
Returns the I th incoming VPValue.
Definition: VPlan.h:1857
VPWidenPHIRecipe(PHINode *Phi, VPValue *Start=nullptr)
Create a new VPWidenPHIRecipe for Phi with start value Start.
Definition: VPlan.h:1824
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPWidenPHIRecipe * clone() override
Clone the current recipe.
Definition: VPlan.h:1830
~VPWidenPHIRecipe() override=default
VPBasicBlock * getIncomingBlock(unsigned I)
Returns the I th incoming VPBasicBlock.
Definition: VPlan.h:1854
void execute(VPTransformState &State) override
Generate the phi/select nodes.
VPWidenPointerInductionRecipe * clone() override
Clone the current recipe.
Definition: VPlan.h:1791
const InductionDescriptor & getInductionDescriptor() const
Returns the induction descriptor for the recipe.
Definition: VPlan.h:1806
~VPWidenPointerInductionRecipe() override=default
bool onlyScalarsGenerated(bool IsScalable)
Returns true if only scalar values will be generated.
void execute(VPTransformState &State) override
Generate vector values for the pointer induction.
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPWidenPointerInductionRecipe(PHINode *Phi, VPValue *Start, VPValue *Step, const InductionDescriptor &IndDesc, bool IsScalarAfterVectorization)
Create a new VPWidenPointerInductionRecipe for Phi with start value Start.
Definition: VPlan.h:1779
VPWidenRecipe is a recipe for producing a copy of vector type its ingredient.
Definition: VPlan.h:1329
void execute(VPTransformState &State) override
Produce widened copies of all Ingredients.
VPWidenRecipe * clone() override
Clone the current recipe.
Definition: VPlan.h:1340
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
~VPWidenRecipe() override=default
VPWidenRecipe(Instruction &I, iterator_range< IterT > Operands)
Definition: VPlan.h:1334
unsigned getOpcode() const
Definition: VPlan.h:1351
VPlanPrinter prints a given VPlan to a given output stream.
Definition: VPlan.h:3303
VPlanPrinter(raw_ostream &O, const VPlan &P)
Definition: VPlan.h:3344
LLVM_DUMP_METHOD void dump()
Definition: VPlan.cpp:1131
Class that maps (parts of) an existing VPlan to trees of combined VPInstructions.
Definition: VPlan.h:3497
VPInstruction * buildGraph(ArrayRef< VPValue * > Operands)
Tries to build an SLP tree rooted at Operands and returns a VPInstruction combining Operands,...
Definition: VPlanSLP.cpp:359
bool isCompletelySLP() const
Return true if all visited instruction can be combined.
Definition: VPlan.h:3587
~VPlanSlp()=default
VPlanSlp(VPInterleavedAccessInfo &IAI, VPBasicBlock &BB)
Definition: VPlan.h:3575
unsigned getWidestBundleBits() const
Return the width of the widest combined bundle in bits.
Definition: VPlan.h:3584
VPlan models a candidate for vectorization, encoding various decisions take to produce efficient outp...
Definition: VPlan.h:3060
void printDOT(raw_ostream &O) const
Print this VPlan in DOT format to O.
Definition: VPlan.cpp:984
std::string getName() const
Return a string with the name of the plan and the applicable VFs and UFs.
Definition: VPlan.cpp:960
void prepareToExecute(Value *TripCount, Value *VectorTripCount, Value *CanonicalIVStartValue, VPTransformState &State)
Prepare the plan for execution, setting up the required live-in values.
Definition: VPlan.cpp:783
bool hasScalableVF()
Definition: VPlan.h:3192
VPBasicBlock * getEntry()
Definition: VPlan.h:3153
VPValue & getVectorTripCount()
The vector trip count.
Definition: VPlan.h:3178
void setName(const Twine &newName)
Definition: VPlan.h:3209
VPValue & getVFxUF()
Returns VF * UF of the vector loop region.
Definition: VPlan.h:3181
VPValue * getTripCount() const
The trip count of the original loop.
Definition: VPlan.h:3157
VPValue * getOrCreateBackedgeTakenCount()
The backedge taken count of the original loop.
Definition: VPlan.h:3171
void removeLiveOut(PHINode *PN)
Definition: VPlan.h:3266
void addLiveOut(PHINode *PN, VPValue *V)
Definition: VPlan.cpp:993
const VPBasicBlock * getEntry() const
Definition: VPlan.h:3154
VPlan(VPBasicBlock *Preheader, VPValue *TC, VPBasicBlock *Entry)
Construct a VPlan with original preheader Preheader, trip count TC and Entry to the plan.
Definition: VPlan.h:3118
VPBasicBlock * getPreheader()
Definition: VPlan.h:3285
VPRegionBlock * getVectorLoopRegion()
Returns the VPRegionBlock of the vector loop.
Definition: VPlan.h:3247
const VPRegionBlock * getVectorLoopRegion() const
Definition: VPlan.h:3250
static VPlanPtr createInitialVPlan(const SCEV *TripCount, ScalarEvolution &PSE)
Create initial VPlan skeleton, having an "entry" VPBasicBlock (wrapping original scalar pre-header) w...
Definition: VPlan.cpp:769
bool hasVF(ElementCount VF)
Definition: VPlan.h:3191
void addSCEVExpansion(const SCEV *S, VPValue *V)
Definition: VPlan.h:3279
bool hasUF(unsigned UF) const
Definition: VPlan.h:3198
void setVF(ElementCount VF)
Definition: VPlan.h:3185
void resetTripCount(VPValue *NewTripCount)
Resets the trip count for the VPlan.
Definition: VPlan.h:3164
VPlan(VPBasicBlock *Preheader, VPBasicBlock *Entry)
Construct a VPlan with original preheader Preheader and Entry to the plan.
Definition: VPlan.h:3127
const VPBasicBlock * getPreheader() const
Definition: VPlan.h:3286
VPValue * getOrAddLiveIn(Value *V)
Gets the live-in VPValue for V or adds a new live-in (if none exists yet) for V.
Definition: VPlan.h:3213
LLVM_DUMP_METHOD void dump() const
Dump the plan to stderr (for debugging).
Definition: VPlan.cpp:990
bool hasScalarVFOnly() const
Definition: VPlan.h:3196
void execute(VPTransformState *State)
Generate the IR code for this VPlan.
Definition: VPlan.cpp:825
VPCanonicalIVPHIRecipe * getCanonicalIV()
Returns the canonical induction recipe of the vector loop.
Definition: VPlan.h:3255
const MapVector< PHINode *, VPLiveOut * > & getLiveOuts() const
Definition: VPlan.h:3271
void print(raw_ostream &O) const
Print this VPlan to O.
Definition: VPlan.cpp:934
void addVF(ElementCount VF)
Definition: VPlan.h:3183
VPValue * getLiveIn(Value *V) const
Return the live-in VPValue for V, if there is one or nullptr otherwise.
Definition: VPlan.h:3230
VPValue * getSCEVExpansion(const SCEV *S) const
Definition: VPlan.h:3275
void printLiveIns(raw_ostream &O) const
Print the live-ins of this VPlan to O.
Definition: VPlan.cpp:904
void setUF(unsigned UF)
Definition: VPlan.h:3200
VPlan * duplicate()
Clone the current VPlan, update all VPValues of the new VPlan and cloned recipes to refer to the clon...
Definition: VPlan.cpp:1074
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition: TypeSize.h:171
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition: TypeSize.h:168
An ilist node that can access its parent list.
Definition: ilist_node.h:284
base_list_type::const_reverse_iterator const_reverse_iterator
Definition: ilist.h:125
void pop_back()
Definition: ilist.h:255
base_list_type::reverse_iterator reverse_iterator
Definition: ilist.h:123
base_list_type::const_iterator const_iterator
Definition: ilist.h:122
iterator insert(iterator where, pointer New)
Definition: ilist.h:165
CRTP base class which implements the entire standard iterator facade in terms of a minimal subset of ...
Definition: iterator.h:80
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:52
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.
@ BasicBlock
Various leaf nodes.
Definition: ISDOpcodes.h:71
VPValue * getOrCreateVPValueForSCEVExpr(VPlan &Plan, const SCEV *Expr, ScalarEvolution &SE)
Get or create a VPValue that corresponds to the expansion of Expr.
Definition: VPlan.cpp:1459
bool isUniformAfterVectorization(VPValue *VPV)
Returns true if VPV is uniform after vectorization.
Definition: VPlan.h:3607
bool onlyFirstPartUsed(const VPValue *Def)
Returns true if only the first part of Def is used.
Definition: VPlan.cpp:1454
bool onlyFirstLaneUsed(const VPValue *Def)
Returns true if only the first lane of Def is used.
Definition: VPlan.cpp:1449
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
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:1742
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:1722
bool isEqual(const GCNRPTracker::LiveRegSet &S1, const GCNRPTracker::LiveRegSet &S2)
const SCEV * createTripCountSCEV(Type *IdxTy, PredicatedScalarEvolution &PSE, Loop *OrigLoop)
testing::Matcher< const detail::ErrorHolder & > Failed()
Definition: Error.h:198
Value * getRuntimeVF(IRBuilderBase &B, Type *Ty, ElementCount VF)
Return the runtime value for VF.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
auto map_range(ContainerTy &&C, FuncTy F)
Definition: STLExtras.h:377
auto dyn_cast_or_null(const Y &Val)
Definition: Casting.h:759
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:1729
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition: MathExtras.h:275
std::unique_ptr< VPlan > VPlanPtr
Definition: VPlan.h:134
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
iterator_range< filter_iterator< detail::IterOfRange< RangeT >, PredicateT > > make_filter_range(RangeT &&Range, PredicateT Pred)
Convenience function that takes a range of elements and a predicate, and return a new filter_iterator...
Definition: STLExtras.h:572
@ Other
Any other memory.
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
Definition: APFixedPoint.h:293
Value * createStepForVF(IRBuilderBase &B, Type *Ty, ElementCount VF, int64_t Step)
Return a value for Step multiplied by VF.
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition: STLExtras.h:1879
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
Definition: Hashing.h:491
#define N
A range of powers-of-2 vectorization factors with fixed start and adjustable end.
Definition: VPlan.h:87
iterator end()
Definition: VPlan.h:128
const ElementCount Start
Definition: VPlan.h:89
ElementCount End
Definition: VPlan.h:92
iterator begin()
Definition: VPlan.h:127
bool isEmpty() const
Definition: VPlan.h:94
VFRange(const ElementCount &Start, const ElementCount &End)
Definition: VPlan.h:98
A recipe for handling first-order recurrence phis.
Definition: VPlan.h:1863
void execute(VPTransformState &State) override
Generate the phi nodes.
VPFirstOrderRecurrencePHIRecipe * clone() override
Clone the current recipe.
Definition: VPlan.h:1873
VPFirstOrderRecurrencePHIRecipe(PHINode *Phi, VPValue &Start)
Definition: VPlan.h:1864
static bool classof(const VPHeaderPHIRecipe *R)
Definition: VPlan.h:1869
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPIteration represents a single point in the iteration space of the output (vectorized and/or unrolle...
Definition: VPlan.h:219
VPIteration(unsigned Part, const VPLane &Lane)
Definition: VPlan.h:229
unsigned Part
in [0..UF)
Definition: VPlan.h:221
VPLane Lane
Definition: VPlan.h:223
VPIteration(unsigned Part, unsigned Lane, VPLane::Kind Kind=VPLane::Kind::First)
Definition: VPlan.h:225
bool isFirstIteration() const
Definition: VPlan.h:231
WrapFlagsTy(bool HasNUW, bool HasNSW)
Definition: VPlan.h:915
Hold state information used when constructing the CFG of the output IR, traversing the VPBasicBlocks ...
Definition: VPlan.h:359
BasicBlock * PrevBB
The previous IR BasicBlock created or used.
Definition: VPlan.h:365
SmallDenseMap< VPBasicBlock *, BasicBlock * > VPBB2IRBB
A mapping of each VPBasicBlock to the corresponding BasicBlock.
Definition: VPlan.h:373
VPBasicBlock * PrevVPBB
The previous VPBasicBlock visited. Initially set to null.
Definition: VPlan.h:361
BasicBlock * ExitBB
The last IR BasicBlock in the output IR.
Definition: VPlan.h:369
BasicBlock * getPreheaderBBFor(VPRecipeBase *R)
Returns the BasicBlock* mapped to the pre-header of the loop region containing R.
Definition: VPlan.cpp:348
SmallVector< Value *, 2 > PerPartValuesTy
A type for vectorized values in the new loop.
Definition: VPlan.h:254
DenseMap< VPValue *, ScalarsPerPartValuesTy > PerPartScalars
Definition: VPlan.h:259
DenseMap< VPValue *, PerPartValuesTy > PerPartOutput
Definition: VPlan.h:256
VPTransformState holds information passed down when "executing" a VPlan, needed for generating the ou...
Definition: VPlan.h:236
Value * get(VPValue *Def, unsigned Part, bool IsScalar=false)
Get the generated vector Value for a given VPValue Def and a given Part if IsScalar is false,...
Definition: VPlan.cpp:247
LoopInfo * LI
Hold a pointer to LoopInfo to register new basic blocks in the loop.
Definition: VPlan.h:383
DenseMap< const SCEV *, Value * > ExpandedSCEVs
Map SCEVs to their expanded values.
Definition: VPlan.h:409
VPTypeAnalysis TypeAnalysis
VPlan-based type analysis.
Definition: VPlan.h:412
struct llvm::VPTransformState::DataState Data
void addMetadata(Value *To, Instruction *From)
Add metadata from one instruction to another.
Definition: VPlan.cpp:361
void reset(VPValue *Def, Value *V, unsigned Part)
Reset an existing vector value for Def and a given Part.
Definition: VPlan.h:303
struct llvm::VPTransformState::CFGState CFG
void reset(VPValue *Def, Value *V, const VPIteration &Instance)
Reset an existing scalar value for Def and a given Instance.
Definition: VPlan.h:325
LoopVersioning * LVer
LoopVersioning.
Definition: VPlan.h:405
void addNewMetadata(Instruction *To, const Instruction *Orig)
Add additional metadata to To that was not present on Orig.
Definition: VPlan.cpp:353
void packScalarIntoVectorValue(VPValue *Def, const VPIteration &Instance)
Construct the vector value of a scalarized value V one lane at a time.
Definition: VPlan.cpp:393
void set(VPValue *Def, Value *V, const VPIteration &Instance)
Set the generated scalar V for Def and the given Instance.
Definition: VPlan.h:311
void set(VPValue *Def, Value *V, unsigned Part, bool IsScalar=false)
Set the generated vector Value for a given VPValue and a given Part, if IsScalar is false.
Definition: VPlan.h:288
std::optional< VPIteration > Instance
Hold the indices to generate specific scalar instructions.
Definition: VPlan.h:248
IRBuilderBase & Builder
Hold a reference to the IRBuilder used to generate output IR code.
Definition: VPlan.h:389
DominatorTree * DT
Hold a pointer to Dominator Tree to register new basic blocks in the loop.
Definition: VPlan.h:386
bool hasScalarValue(VPValue *Def, VPIteration Instance)
Definition: VPlan.h:276
VPlan * Plan
Pointer to the VPlan code is generated for.
Definition: VPlan.h:395
InnerLoopVectorizer * ILV
Hold a pointer to InnerLoopVectorizer to reuse its IR generation methods.
Definition: VPlan.h:392
bool hasVectorValue(VPValue *Def, unsigned Part)
Definition: VPlan.h:270
ElementCount VF
The chosen Vectorization and Unroll Factors of the loop being vectorized.
Definition: VPlan.h:242
Loop * CurrentVectorLoop
The loop object for the current parent region, or nullptr.
Definition: VPlan.h:398
void setDebugLocFrom(DebugLoc DL)
Set the debug location in the builder using the debug location DL.
Definition: VPlan.cpp:372
A recipe for widening load operations with vector-predication intrinsics, using the address to load f...
Definition: VPlan.h:2415
void execute(VPTransformState &State) override
Generate the wide load or gather.
VPValue * getEVL() const
Return the EVL operand.
Definition: VPlan.h:2427
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPWidenLoadEVLRecipe(VPWidenLoadRecipe *L, VPValue *EVL, VPValue *Mask)
Definition: VPlan.h:2416
bool onlyFirstLaneUsed(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition: VPlan.h:2439
A recipe for widening load operations, using the address to load from and an optional mask.
Definition: VPlan.h:2376
VP_CLASSOF_IMPL(VPDef::VPWidenLoadSC)
VPWidenLoadRecipe(LoadInst &Load, VPValue *Addr, VPValue *Mask, bool Consecutive, bool Reverse, DebugLoc DL)
Definition: VPlan.h:2377
bool onlyFirstLaneUsed(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition: VPlan.h:2403
void execute(VPTransformState &State) override
Generate a wide load or gather.
VPWidenLoadRecipe * clone() override
Clone the current recipe.
Definition: VPlan.h:2385
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
A recipe for widening select instructions.
Definition: VPlan.h:1503
bool isInvariantCond() const
Definition: VPlan.h:1531
VPWidenSelectRecipe * clone() override
Clone the current recipe.
Definition: VPlan.h:1511
VPWidenSelectRecipe(SelectInst &I, iterator_range< IterT > Operands)
Definition: VPlan.h:1505
VPValue * getCond() const
Definition: VPlan.h:1527
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
void execute(VPTransformState &State) override
Produce a widened version of the select instruction.
~VPWidenSelectRecipe() override=default
A recipe for widening store operations with vector-predication intrinsics, using the value to store,...
Definition: VPlan.h:2491
VPValue * getStoredValue() const
Return the address accessed by this recipe.
Definition: VPlan.h:2503
void execute(VPTransformState &State) override
Generate the wide store or scatter.
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPWidenStoreEVLRecipe(VPWidenStoreRecipe *S, VPValue *EVL, VPValue *Mask)
Definition: VPlan.h:2492
bool onlyFirstLaneUsed(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition: VPlan.h:2518
VPValue * getEVL() const
Return the EVL operand.
Definition: VPlan.h:2506
A recipe for widening store operations, using the stored value, the address to store to and an option...
Definition: VPlan.h:2450
void execute(VPTransformState &State) override
Generate a wide store or scatter.
bool onlyFirstLaneUsed(const VPValue *Op) const override
Returns true if the recipe only uses the first lane of operand Op.
Definition: VPlan.h:2479
VPWidenStoreRecipe(StoreInst &Store, VPValue *Addr, VPValue *StoredVal, VPValue *Mask, bool Consecutive, bool Reverse, DebugLoc DL)
Definition: VPlan.h:2451
VP_CLASSOF_IMPL(VPDef::VPWidenStoreSC)
VPValue * getStoredValue() const
Return the value stored by this recipe.
Definition: VPlan.h:2467
VPWidenStoreRecipe * clone() override
Clone the current recipe.
Definition: VPlan.h:2458
void print(raw_ostream &O, const Twine &Indent, VPSlotTracker &SlotTracker) const override
Print the recipe.
VPlanIngredient(const Value *V)
Definition: VPlan.h:3353
const Value * V
Definition: VPlan.h:3351
void print(raw_ostream &O) const
Definition: VPlan.cpp:1249