LLVM 23.0.0git
Region.h
Go to the documentation of this file.
1//===- Region.h -------------------------------------------------*- 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#ifndef LLVM_SANDBOXIR_REGION_H
10#define LLVM_SANDBOXIR_REGION_H
11
13#include <memory>
14
15#include "llvm/ADT/SetVector.h"
21
22namespace llvm::sandboxir {
23
24/// The main job of the Region is to point to new instructions generated by
25/// vectorization passes. It is the unit that RegionPasses operate on with their
26/// runOnRegion() function.
27///
28/// The region allows us to stack transformations horizontally, meaning that
29/// each transformation operates on a single region and the resulting region is
30/// the input to the next transformation, as opposed to vertically, which is the
31/// common way of applying a transformation across the whole function. This
32/// enables us to check for profitability and decide whether we accept or
33/// rollback at a region granularity, which is much better than doing this at
34/// the function level.
35///
36// Traditional approach: transformations applied vertically for the whole
37// function
38// F
39// +----+
40// | |
41// | |
42// | | -> Transform1 -> ... -> TransformN -> Check Cost
43// | |
44// | |
45// +----+
46//
47// Region-based approach: transformations applied horizontally, for each Region
48// F
49// +----+
50// |Rgn1| -> Transform1 -> ... -> TransformN -> Check Cost
51// | |
52// |Rgn2| -> Transform1 -> ... -> TransformN -> Check Cost
53// | |
54// |Rgn3| -> Transform1 -> ... -> TransformN -> Check Cost
55// +----+
56//
57// The region can also hold an ordered sequence of "auxiliary" instructions.
58// This can be used to pass auxiliary information across region passes, like for
59// example the initial seed slice used by the bottom-up vectorizer.
60
65
66class Region {
67protected:
68 /// All the instructions in the Region. Only new instructions generated during
69 /// vectorization are part of the Region.
71 /// An auxiliary sequence of Instruction-Index pairs.
73
74 /// MDNode that we'll use to mark instructions as being part of the region.
76 static constexpr const char *MDKind = "sandboxvec";
77 static constexpr const char *RegionStr = "sandboxregion";
78 static constexpr const char *AuxMDKind = "sandboxaux";
79
81
83
84 /// ID (for later deregistration) of the "create instruction" callback.
86 /// ID (for later deregistration) of the "erase instruction" callback.
88
89 /// Adds \p I to the set. Only to be used when we want to avoid the additional
90 /// functionality provided by the subclass, e.g., to avoid score counting when
91 /// adding instrs to the aux vector.
92 /// NOTE: When an instruction is added to the region we track it cost in the
93 /// scoreboard, which currently resides in the region class. However, when we
94 /// add an instruction to the auxiliary vector it does get tagged as being a
95 /// member of the region (for ownership reasons), but its cost does not get
96 /// counted because the instruction hasn't been added in the "normal" way.
98 Insts.insert(I);
99 // TODO: Consider tagging instructions lazily.
100 cast<llvm::Instruction>(I->Val)->setMetadata(MDKind, RegionMDN);
101 }
102 /// Adds I to the set. This is the main API for adding an instruction to the
103 /// region.
104 virtual void add(Instruction *I) { addRaw(I); }
105 /// Removes I from the set.
106 LLVM_ABI virtual void remove(Instruction *I);
107 friend class Context; // The callbacks need to call add() and remove().
108 friend class RegionInternalsAttorney; // For unit tests.
109
110 /// Set \p I as the \p Idx'th element in the auxiliary vector.
111 /// NOTE: This is for internal use, it does not set the metadata.
112 void setAux(unsigned Idx, Instruction *I);
113 /// Helper for dropping Aux metadata for \p I.
115 /// Remove instruction \p I from Aux and drop metadata.
117
119
120 template <typename RegionT, typename RegionFactoryT>
122 createRegionsFromMD(Function &F, RegionFactoryT Factory) {
125 for (BasicBlock &BB : F) {
126 for (Instruction &Inst : BB) {
127 auto *LLVMI = cast<llvm::Instruction>(Inst.Val);
128 RegionT *R = nullptr;
129 if (auto *MDN = LLVMI->getMetadata(MDKind)) {
130 auto [It, Inserted] = MDNToRegion.try_emplace(MDN);
131 if (Inserted) {
132 Regions.push_back(Factory());
133 R = Regions.back().get();
134 It->second = R;
135 } else {
136 R = It->second;
137 }
138 R->addRaw(&Inst);
139 }
140 if (auto *AuxMDN = LLVMI->getMetadata(AuxMDKind)) {
141 llvm::Constant *IdxC =
142 dyn_cast<ConstantAsMetadata>(AuxMDN->getOperand(0))->getValue();
143 auto Idx = cast<llvm::ConstantInt>(IdxC)->getSExtValue();
144 if (R == nullptr) {
145 errs() << "No region specified for Aux: '" << *LLVMI << "'\n";
146 reportFatalUsageError("No region specified for Aux!");
147 }
148 R->setAux(Idx, &Inst);
149 }
150 }
151 }
152#ifndef NDEBUG
153 // Check that there are no gaps in the Aux vector.
154 for (auto &RPtr : Regions)
155 for (auto *I : RPtr->getAux())
156 assert(I != nullptr && "Gap in Aux!");
157#endif
158 return Regions;
159 }
160
161public:
163 LLVM_ABI virtual ~Region();
164 // Disable copies to avoid unregistering the callback more than once.
165 Region(const Region &) = delete;
166 // Moves are allowed.
167 Region(Region &&) = default;
168
169 Context &getContext() const { return Ctx; }
170 /// Returns true if I is in the Region.
171 bool contains(Instruction *I) const { return Insts.contains(I); }
172 /// Returns true if the Region has no instructions.
173 bool empty() const { return Insts.empty(); }
174 /// Set the auxiliary vector.
176 /// \Returns the auxiliary vector.
177 const SmallVector<Instruction *> &getAux() const { return Aux; }
178 /// Clears all auxiliary data.
179 LLVM_ABI void clearAux();
180
181 using iterator = decltype(Insts.begin());
182 iterator begin() { return Insts.begin(); }
183 iterator end() { return Insts.end(); }
185
188
189 RegionClassID getSubclassID() const { return ID; }
190
191#ifndef NDEBUG
192 /// This is an expensive check, meant for testing.
193 LLVM_ABI_FOR_TEST bool operator==(const Region &Other) const;
194 bool operator!=(const Region &other) const { return !(*this == other); }
195
196 LLVM_ABI_FOR_TEST void dump(raw_ostream &OS) const;
197 void dump() const;
198 friend raw_ostream &operator<<(raw_ostream &OS, const Region &Rgn) {
199 Rgn.dump(OS);
200 return OS;
201 }
202#endif
203};
204
205/// A helper client-attorney class for unit tests.
207public:
208 static void add(Region &Rgn, Instruction *I) { Rgn.add(I); }
209 static void remove(Region &Rgn, Instruction *I) { Rgn.remove(I); }
210};
211
212} // namespace llvm::sandboxir
213
214#endif // LLVM_SANDBOXIR_REGION_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
#define LLVM_ABI
Definition Compiler.h:213
#define LLVM_ABI_FOR_TEST
Definition Compiler.h:218
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
This file implements a set that has insertion order iteration characteristics.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:39
This is an important base class in LLVM.
Definition Constant.h:43
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:254
Metadata node.
Definition Metadata.h:1080
A vector that has set insertion semantics.
Definition SetVector.h:57
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
A range adaptor for a pair of iterators.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
An ID for a registered callback.
Definition Context.h:49
A sandboxir::User with operands, opcode and linked with previous/next instructions in an instruction ...
Definition Instruction.h:43
A helper client-attorney class for unit tests.
Definition Region.h:206
static void add(Region &Rgn, Instruction *I)
Definition Region.h:208
static void remove(Region &Rgn, Instruction *I)
Definition Region.h:209
static constexpr const char * RegionStr
Definition Region.h:77
Context & getContext() const
Definition Region.h:169
RegionClassID getSubclassID() const
Definition Region.h:189
void addRaw(Instruction *I)
Adds I to the set.
Definition Region.h:97
bool contains(Instruction *I) const
Returns true if I is in the Region.
Definition Region.h:171
void removeFromAux(Instruction *I)
Remove instruction I from Aux and drop metadata.
Definition Region.cpp:67
static constexpr const char * MDKind
Definition Region.h:76
RegionClassID ID
Definition Region.h:82
const SmallVector< Instruction * > & getAux() const
\Returns the auxiliary vector.
Definition Region.h:177
iterator_range< iterator > insts()
Definition Region.h:184
bool operator!=(const Region &other) const
Definition Region.h:194
Context::CallbackID EraseInstCB
ID (for later deregistration) of the "erase instruction" callback.
Definition Region.h:87
Region(const Region &)=delete
LLVM_ABI_FOR_TEST bool operator==(const Region &Other) const
This is an expensive check, meant for testing.
Definition Region.cpp:87
virtual LLVM_ABI void remove(Instruction *I)
Removes I from the set.
Definition Region.cpp:81
static SmallVector< std::unique_ptr< RegionT > > createRegionsFromMD(Function &F, RegionFactoryT Factory)
Definition Region.h:122
Context::CallbackID CreateInstCB
ID (for later deregistration) of the "create instruction" callback.
Definition Region.h:85
void dropAuxMetadata(Instruction *I)
Helper for dropping Aux metadata for I.
Definition Region.cpp:62
SetVector< Instruction * > Insts
All the instructions in the Region.
Definition Region.h:70
static constexpr const char * AuxMDKind
Definition Region.h:78
Region(Region &&)=default
friend class RegionInternalsAttorney
Definition Region.h:108
friend class Context
Definition Region.h:107
friend raw_ostream & operator<<(raw_ostream &OS, const Region &Rgn)
Definition Region.h:198
LLVM_ABI Region(Context &Ctx)
Definition Region.h:162
LLVM_ABI Region(Context &Ctx, RegionClassID ID)
Definition Region.cpp:13
virtual void add(Instruction *I)
Adds I to the set.
Definition Region.h:104
LLVM_ABI void clearAux()
Clears all auxiliary data.
Definition Region.cpp:75
decltype(Insts.begin()) iterator
Definition Region.h:181
virtual LLVM_ABI ~Region()
Definition Region.cpp:26
LLVM_ABI_FOR_TEST void dump(raw_ostream &OS) const
Definition Region.cpp:95
void setAux(unsigned Idx, Instruction *I)
Set I as the Idx'th element in the auxiliary vector.
Definition Region.cpp:46
bool empty() const
Returns true if the Region has no instructions.
Definition Region.h:173
MDNode * RegionMDN
MDNode that we'll use to mark instructions as being part of the region.
Definition Region.h:75
SmallVector< Instruction * > Aux
An auxiliary sequence of Instruction-Index pairs.
Definition Region.h:72
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
RegionClassID
The main job of the Region is to point to new instructions generated by vectorization passes.
Definition Region.h:61
@ RegionWithScoreID
Definition Region.h:63
BasicBlock(llvm::BasicBlock *BB, Context &SBCtx)
Definition BasicBlock.h:75
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
@ Other
Any other memory.
Definition ModRef.h:68
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177