MLIR 24.0.0git
MemRefInterfaces.cpp
Go to the documentation of this file.
1//===- MemRefInterfaces.cpp - OpenACC external models ---------------------===//
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
14#include "mlir/IR/BuiltinOps.h"
16#include "mlir/IR/SymbolTable.h"
17
18using namespace mlir;
19using namespace mlir::acc;
20
21namespace {
22static bool isScalarLikeType(Type type) {
23 return type.isIntOrIndexOrFloat() || isa<ComplexType>(type);
24}
25
26/// Helper function to attach the `VarName` attribute to an operation
27/// if a variable name is provided.
28static void attachVarNameAttr(Operation *op, OpBuilder &builder,
29 StringRef varName) {
30 if (!varName.empty()) {
31 auto varNameAttr = acc::VarNameAttr::get(builder.getContext(), varName);
33 }
34}
35
36template <typename T>
37struct MemRefPointerLikeModel
38 : public PointerLikeType::ExternalModel<MemRefPointerLikeModel<T>, T> {
39 Type getElementType(Type pointer) const {
40 return cast<T>(pointer).getElementType();
41 }
42
43 mlir::acc::VariableTypeCategory
44 getPointeeTypeCategory(Type pointer, TypedValue<PointerLikeType> varPtr,
45 Type varType) const {
46 if (auto mappableTy = dyn_cast<MappableType>(varType)) {
47 return mappableTy.getTypeCategory(varPtr);
48 }
49 auto memrefTy = cast<T>(pointer);
50 if (!memrefTy.hasRank()) {
51 // This memref is unranked - aka it could have any rank, including a
52 // rank of 0 which could mean scalar. For now, return uncategorized.
53 return mlir::acc::VariableTypeCategory::uncategorized;
54 }
55
56 if (memrefTy.getRank() == 0) {
57 if (isScalarLikeType(memrefTy.getElementType())) {
58 return mlir::acc::VariableTypeCategory::scalar;
59 }
60 // Zero-rank non-scalar - need further analysis to determine the type
61 // category. For now, return uncategorized.
62 return mlir::acc::VariableTypeCategory::uncategorized;
63 }
64
65 // It has a rank - must be an array.
66 assert(memrefTy.getRank() > 0 && "rank expected to be positive");
67 return mlir::acc::VariableTypeCategory::array;
68 }
69
70 mlir::Value genAllocate(Type pointer, OpBuilder &builder, Location loc,
71 StringRef varName, Type varType, Value originalVar,
72 bool &needsFree) const {
73 auto memrefTy = cast<MemRefType>(pointer);
74
75 // Check if this is a static memref (all dimensions are known) - if yes
76 // then we can generate an alloca operation.
77 if (memrefTy.hasStaticShape()) {
78 needsFree = false; // alloca doesn't need deallocation
79 auto allocaOp = memref::AllocaOp::create(builder, loc, memrefTy);
80 attachVarNameAttr(allocaOp, builder, varName);
81 return allocaOp.getResult();
82 }
83
84 // For dynamic memrefs, extract sizes from the original variable if
85 // provided. Otherwise they cannot be handled.
86 if (originalVar && originalVar.getType() == memrefTy &&
87 memrefTy.hasRank()) {
88 SmallVector<Value> dynamicSizes;
89 for (int64_t i = 0; i < memrefTy.getRank(); ++i) {
90 if (memrefTy.isDynamicDim(i)) {
91 // Extract the size of dimension i from the original variable
92 auto indexValue = arith::ConstantIndexOp::create(builder, loc, i);
93 auto dimSize =
94 memref::DimOp::create(builder, loc, originalVar, indexValue);
95 dynamicSizes.push_back(dimSize);
96 }
97 // Note: We only add dynamic sizes to the dynamicSizes array
98 // Static dimensions are handled automatically by AllocOp
99 }
100 needsFree = true; // alloc needs deallocation
101 auto allocOp =
102 memref::AllocOp::create(builder, loc, memrefTy, dynamicSizes);
103 attachVarNameAttr(allocOp, builder, varName);
104 return allocOp.getResult();
105 }
106
107 // TODO: Unranked not yet supported.
108 return {};
109 }
110
111 bool genFree(Type pointer, OpBuilder &builder, Location loc,
112 TypedValue<PointerLikeType> varToFree, Value allocRes,
113 Type varType) const {
114 if (auto memrefValue = dyn_cast<TypedValue<MemRefType>>(varToFree)) {
115 // Use allocRes if provided to determine the allocation type
116 Value valueToInspect = allocRes ? allocRes : memrefValue;
117
118 // Walk through casts to find the original allocation
119 Value currentValue = valueToInspect;
120 Operation *originalAlloc = nullptr;
121
122 // Follow the chain of operations to find the original allocation
123 // even if a casted result is provided.
124 while (currentValue) {
125 if (auto *definingOp = currentValue.getDefiningOp()) {
126 // Check if this is an allocation operation
127 if (isa<memref::AllocOp, memref::AllocaOp>(definingOp)) {
128 originalAlloc = definingOp;
129 break;
130 }
131
132 // Check if this is a cast operation we can look through
133 if (auto castOp = dyn_cast<memref::CastOp>(definingOp)) {
134 currentValue = castOp.getSource();
135 continue;
136 }
137
138 // Check for other cast-like operations
139 if (auto reinterpretCastOp =
140 dyn_cast<memref::ReinterpretCastOp>(definingOp)) {
141 currentValue = reinterpretCastOp.getSource();
142 continue;
143 }
144
145 // If we can't look through this operation, stop
146 break;
147 }
148 // This is a block argument or similar - can't trace further.
149 break;
150 }
151
152 if (originalAlloc) {
153 if (isa<memref::AllocaOp>(originalAlloc)) {
154 // This is an alloca - no dealloc needed, but return true (success)
155 return true;
156 }
157 if (isa<memref::AllocOp>(originalAlloc)) {
158 // This is an alloc - generate dealloc on varToFree
159 memref::DeallocOp::create(builder, loc, memrefValue);
160 return true;
161 }
162 }
163 }
164
165 return false;
166 }
167
168 bool genCopy(Type pointer, OpBuilder &builder, Location loc,
169 TypedValue<PointerLikeType> destination,
170 TypedValue<PointerLikeType> source, Type varType) const {
171 // Generate a copy operation between two memrefs
172 auto destMemref = dyn_cast_if_present<TypedValue<MemRefType>>(destination);
173 auto srcMemref = dyn_cast_if_present<TypedValue<MemRefType>>(source);
174
175 // As per memref documentation, source and destination must have same
176 // element type and shape in order to be compatible. We do not want to fail
177 // with an IR verification error - thus check that before generating the
178 // copy operation.
179 if (destMemref && srcMemref &&
180 destMemref.getType().getElementType() ==
181 srcMemref.getType().getElementType() &&
182 destMemref.getType().getShape() == srcMemref.getType().getShape()) {
183 memref::CopyOp::create(builder, loc, srcMemref, destMemref);
184 return true;
185 }
186
187 return false;
188 }
189
190 mlir::Value genLoad(Type pointer, OpBuilder &builder, Location loc,
192 Type valueType) const {
193 // Load from a memref - only valid for scalar memrefs (rank 0).
194 // This is because the address computation for memrefs is part of the load
195 // (and not computed separately), but the API does not have arguments for
196 // indexing.
197 auto memrefValue = dyn_cast_if_present<TypedValue<MemRefType>>(srcPtr);
198 if (!memrefValue)
199 return {};
200
201 auto memrefTy = memrefValue.getType();
202
203 // Only load from scalar memrefs (rank 0)
204 if (memrefTy.getRank() != 0)
205 return {};
206
207 return memref::LoadOp::create(builder, loc, memrefValue, ValueRange{});
208 }
209
210 bool genStore(Type pointer, OpBuilder &builder, Location loc,
211 Value valueToStore, TypedValue<PointerLikeType> destPtr) const {
212 // Store to a memref - only valid for scalar memrefs (rank 0)
213 // This is because the address computation for memrefs is part of the store
214 // (and not computed separately), but the API does not have arguments for
215 // indexing.
216 auto memrefValue = dyn_cast_if_present<TypedValue<MemRefType>>(destPtr);
217 if (!memrefValue)
218 return false;
219
220 auto memrefTy = memrefValue.getType();
221
222 // Only store to scalar memrefs (rank 0)
223 if (memrefTy.getRank() != 0)
224 return false;
225
226 memref::StoreOp::create(builder, loc, valueToStore, memrefValue);
227 return true;
228 }
229
230 Value genCast(Type, OpBuilder &builder, Location loc, Value value,
231 Type resultType) const {
232 if (value.getType() == resultType)
233 return value;
234
235 if (isa<BaseMemRefType>(value.getType()) &&
236 isa<BaseMemRefType>(resultType)) {
237 if (memref::CastOp::areCastCompatible(TypeRange(value.getType()),
238 TypeRange(resultType)))
239 return memref::CastOp::create(builder, loc, resultType, value);
240 if (memref::MemorySpaceCastOp::areCastCompatible(
241 TypeRange(value.getType()), TypeRange(resultType)))
242 return memref::MemorySpaceCastOp::create(builder, loc, resultType,
243 value);
244 }
245
246 // If one side is not a memref, try the other type's `PointerLikeType`
247 // implementation (since it may be an out-of-tree reference type that
248 // we cannot generate here).
249 if (auto resPtrLike = dyn_cast<PointerLikeType>(resultType))
250 if (!isa<BaseMemRefType>(resPtrLike))
251 if (Value v = resPtrLike.genCast(builder, loc, value, resultType))
252 return v;
253 if (auto valPtrLike = dyn_cast<PointerLikeType>(value.getType()))
254 if (!isa<BaseMemRefType>(valPtrLike))
255 if (Value v = valPtrLike.genCast(builder, loc, value, resultType))
256 return v;
257
258 return {};
259 }
260
261 bool isDeviceAccessible(Type pointer, Value var,
262 SymbolTableCollection *symbolTables) const {
263 auto memrefTy = cast<T>(pointer);
264 Attribute memSpace = memrefTy.getMemorySpace();
265 return isa_and_nonnull<gpu::AddressSpaceAttr>(memSpace);
266 }
267
268 MemRefType getAsMemRefType(Type pointer, ModuleOp module) const {
269 (void)module;
270 return dyn_cast<MemRefType>(pointer);
271 }
272};
273
274struct MemrefAddressOfGlobalModel
275 : public AddressOfGlobalOpInterface::ExternalModel<
276 MemrefAddressOfGlobalModel, memref::GetGlobalOp> {
277 SymbolRefAttr getSymbol(Operation *op) const {
278 auto getGlobalOp = cast<memref::GetGlobalOp>(op);
279 return getGlobalOp.getNameAttr();
280 }
281};
282
283struct MemrefGlobalVariableModel
284 : public GlobalVariableOpInterface::ExternalModel<MemrefGlobalVariableModel,
285 memref::GlobalOp> {
286 bool isConstant(Operation *op) const {
287 auto globalOp = cast<memref::GlobalOp>(op);
288 return globalOp.getConstant();
289 }
290
291 bool hasInitializer(Operation *op) const {
292 auto globalOp = cast<memref::GlobalOp>(op);
293 return globalOp.getInitialValue().has_value();
294 }
295
296 Region *getInitRegion(Operation *op) const {
297 // GlobalOp uses attributes for initialization, not regions
298 return nullptr;
299 }
300
301 bool isDeviceAccessible(Operation *op) const {
302 auto globalOp = cast<memref::GlobalOp>(op);
303 Attribute memSpace = globalOp.getType().getMemorySpace();
304 return isa_and_nonnull<gpu::AddressSpaceAttr>(memSpace);
305 }
306
307 bool isInDeviceMemory(Operation *op) const {
308 // A memref address space models storage that is physically resident on the
309 // device, so a device-accessible global is also in device memory. (There
310 // is no host-shared/migratable address space to exclude here.)
311 return isDeviceAccessible(op);
312 }
313
314 bool isCompilerGenerated(Operation *op) const { return false; }
315
316 // memref.global has no linkage attribute. MemRefToLLVM lowers a non-public
317 // symbol to LLVM private linkage and a public symbol to external linkage.
318 // LLVM hasLocalLinkage is true for private linkage.
319 bool hasLocalLinkage(Operation *op) const {
320 return cast<memref::GlobalOp>(op).getVisibility() !=
321 SymbolTable::Visibility::Public;
322 }
323};
324} // namespace
325
327 // MemRef types belong to BuiltinDialect, so IR can use them without any
328 // memref operations. Install their models as soon as OpenACC is loaded.
329 registry.addExtension(+[](MLIRContext *ctx, OpenACCDialect *) {
330 ctx->getOrLoadDialect<memref::MemRefDialect>();
331 ctx->getOrLoadDialect<arith::ArithDialect>();
332 MemRefType::attachInterface<MemRefPointerLikeModel<MemRefType>>(*ctx);
333 UnrankedMemRefType::attachInterface<
334 MemRefPointerLikeModel<UnrankedMemRefType>>(*ctx);
335 memref::GetGlobalOp::attachInterface<MemrefAddressOfGlobalModel>(*ctx);
336 memref::GlobalOp::attachInterface<MemrefGlobalVariableModel>(*ctx);
337 });
338}
static Type getElementType(Type type, ArrayRef< int32_t > indices, function_ref< InFlightDiagnostic(StringRef)> emitErrorFn)
Walks the given type hierarchy with the given indices, potentially down to component granularity,...
Definition SPIRVOps.cpp:230
static void genStore(OpBuilder &builder, Location loc, Value val, Value mem, Value idx)
Generates a store with proper index typing and proper value.
static Value genLoad(OpBuilder &builder, Location loc, Value mem, Value idx)
Generates a load with proper index typing.
MLIRContext * getContext() const
Definition Builders.h:56
The DialectRegistry maps a dialect namespace to a constructor for the matching dialect.
bool addExtension(TypeID extensionID, std::unique_ptr< DialectExtensionBase > extension)
Add the given extension to the registry.
MLIRContext is the top-level object for a collection of MLIR operations.
Definition MLIRContext.h:71
T * getOrLoadDialect()
Get (or create) a dialect for the given derived dialect type.
This class helps build Operations.
Definition Builders.h:210
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
void setDiscardableAttr(StringAttr name, Attribute value)
Set a discardable attribute by name.
Definition Operation.h:514
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
bool isIntOrIndexOrFloat() const
Return true if this is an integer (of any signedness), index, or float type.
Definition Types.cpp:122
Type getType() const
Return the type of this value.
Definition Value.h:105
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Definition Value.cpp:18
static ConstantIndexOp create(OpBuilder &builder, Location location, int64_t value)
Definition ArithOps.cpp:453
void registerMemRefInterfaces(DialectRegistry &registry)
Register OpenACC interfaces for MemRef IR.
static constexpr StringLiteral getVarNameAttrName()
Definition OpenACC.h:250
Value genCast(OpBuilder &builder, Location loc, Value value, Type dstTy)
Add type casting between arith and index types when needed.
Include the generated interface declarations.
std::conditional_t< std::is_same_v< Ty, mlir::Type >, mlir::Value, detail::TypedValue< Ty > > TypedValue
If Ty is mlir::Type this will select Value instead of having a wrapper around it.
Definition Value.h:496