1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
|
//===- PtrToLLVMIRTranslation.cpp - Translate `ptr` to LLVM IR ------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file implements a translation between the MLIR `ptr` dialect and
// LLVM IR.
//
//===----------------------------------------------------------------------===//
#include "mlir/Target/LLVMIR/Dialect/Ptr/PtrToLLVMIRTranslation.h"
#include "mlir/Dialect/Ptr/IR/PtrOps.h"
#include "mlir/IR/BuiltinAttributes.h"
#include "mlir/IR/Operation.h"
#include "mlir/Target/LLVMIR/ModuleTranslation.h"
#include "llvm/ADT/TypeSwitch.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/Value.h"
using namespace mlir;
using namespace mlir::ptr;
namespace {
/// Converts ptr::AtomicOrdering to llvm::AtomicOrdering
static llvm::AtomicOrdering
translateAtomicOrdering(ptr::AtomicOrdering ordering) {
switch (ordering) {
case ptr::AtomicOrdering::not_atomic:
return llvm::AtomicOrdering::NotAtomic;
case ptr::AtomicOrdering::unordered:
return llvm::AtomicOrdering::Unordered;
case ptr::AtomicOrdering::monotonic:
return llvm::AtomicOrdering::Monotonic;
case ptr::AtomicOrdering::acquire:
return llvm::AtomicOrdering::Acquire;
case ptr::AtomicOrdering::release:
return llvm::AtomicOrdering::Release;
case ptr::AtomicOrdering::acq_rel:
return llvm::AtomicOrdering::AcquireRelease;
case ptr::AtomicOrdering::seq_cst:
return llvm::AtomicOrdering::SequentiallyConsistent;
}
llvm_unreachable("Unknown atomic ordering");
}
/// Translate ptr.ptr_add operation to LLVM IR.
static LogicalResult
translatePtrAddOp(PtrAddOp ptrAddOp, llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation) {
llvm::Value *basePtr = moduleTranslation.lookupValue(ptrAddOp.getBase());
llvm::Value *offset = moduleTranslation.lookupValue(ptrAddOp.getOffset());
if (!basePtr || !offset)
return ptrAddOp.emitError("Failed to lookup operands");
// Create the GEP flags
llvm::GEPNoWrapFlags gepFlags;
switch (ptrAddOp.getFlags()) {
case ptr::PtrAddFlags::none:
break;
case ptr::PtrAddFlags::nusw:
gepFlags = llvm::GEPNoWrapFlags::noUnsignedSignedWrap();
break;
case ptr::PtrAddFlags::nuw:
gepFlags = llvm::GEPNoWrapFlags::noUnsignedWrap();
break;
case ptr::PtrAddFlags::inbounds:
gepFlags = llvm::GEPNoWrapFlags::inBounds();
break;
}
// Create GEP instruction for pointer arithmetic
llvm::Value *gep =
builder.CreateGEP(builder.getInt8Ty(), basePtr, {offset}, "", gepFlags);
moduleTranslation.mapValue(ptrAddOp.getResult(), gep);
return success();
}
/// Translate ptr.load operation to LLVM IR.
static LogicalResult
translateLoadOp(LoadOp loadOp, llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation) {
llvm::Value *ptr = moduleTranslation.lookupValue(loadOp.getPtr());
if (!ptr)
return loadOp.emitError("Failed to lookup pointer operand");
// Translate result type to LLVM type
llvm::Type *resultType =
moduleTranslation.convertType(loadOp.getValue().getType());
if (!resultType)
return loadOp.emitError("Failed to translate result type");
// Create the load instruction.
llvm::MaybeAlign alignment(loadOp.getAlignment().value_or(0));
llvm::LoadInst *loadInst = builder.CreateAlignedLoad(
resultType, ptr, alignment, loadOp.getVolatile_());
// Set op flags and metadata.
loadInst->setAtomic(translateAtomicOrdering(loadOp.getOrdering()));
// Set sync scope if specified
if (loadOp.getSyncscope().has_value()) {
llvm::LLVMContext &ctx = builder.getContext();
llvm::SyncScope::ID syncScope =
ctx.getOrInsertSyncScopeID(loadOp.getSyncscope().value());
loadInst->setSyncScopeID(syncScope);
}
// Set metadata for nontemporal, invariant, and invariant_group
if (loadOp.getNontemporal()) {
llvm::MDNode *nontemporalMD =
llvm::MDNode::get(builder.getContext(),
llvm::ConstantAsMetadata::get(builder.getInt32(1)));
loadInst->setMetadata(llvm::LLVMContext::MD_nontemporal, nontemporalMD);
}
if (loadOp.getInvariant()) {
llvm::MDNode *invariantMD = llvm::MDNode::get(builder.getContext(), {});
loadInst->setMetadata(llvm::LLVMContext::MD_invariant_load, invariantMD);
}
if (loadOp.getInvariantGroup()) {
llvm::MDNode *invariantGroupMD =
llvm::MDNode::get(builder.getContext(), {});
loadInst->setMetadata(llvm::LLVMContext::MD_invariant_group,
invariantGroupMD);
}
moduleTranslation.mapValue(loadOp.getResult(), loadInst);
return success();
}
/// Translate ptr.store operation to LLVM IR.
static LogicalResult
translateStoreOp(StoreOp storeOp, llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation) {
llvm::Value *value = moduleTranslation.lookupValue(storeOp.getValue());
llvm::Value *ptr = moduleTranslation.lookupValue(storeOp.getPtr());
if (!value || !ptr)
return storeOp.emitError("Failed to lookup operands");
// Create the store instruction.
llvm::MaybeAlign alignment(storeOp.getAlignment().value_or(0));
llvm::StoreInst *storeInst =
builder.CreateAlignedStore(value, ptr, alignment, storeOp.getVolatile_());
// Set op flags and metadata.
storeInst->setAtomic(translateAtomicOrdering(storeOp.getOrdering()));
// Set sync scope if specified
if (storeOp.getSyncscope().has_value()) {
llvm::LLVMContext &ctx = builder.getContext();
llvm::SyncScope::ID syncScope =
ctx.getOrInsertSyncScopeID(storeOp.getSyncscope().value());
storeInst->setSyncScopeID(syncScope);
}
// Set metadata for nontemporal and invariant_group
if (storeOp.getNontemporal()) {
llvm::MDNode *nontemporalMD =
llvm::MDNode::get(builder.getContext(),
llvm::ConstantAsMetadata::get(builder.getInt32(1)));
storeInst->setMetadata(llvm::LLVMContext::MD_nontemporal, nontemporalMD);
}
if (storeOp.getInvariantGroup()) {
llvm::MDNode *invariantGroupMD =
llvm::MDNode::get(builder.getContext(), {});
storeInst->setMetadata(llvm::LLVMContext::MD_invariant_group,
invariantGroupMD);
}
return success();
}
/// Translate ptr.type_offset operation to LLVM IR.
static LogicalResult
translateTypeOffsetOp(TypeOffsetOp typeOffsetOp, llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation) {
// Translate the element type to LLVM type
llvm::Type *elementType =
moduleTranslation.convertType(typeOffsetOp.getElementType());
if (!elementType)
return typeOffsetOp.emitError("Failed to translate the element type");
// Translate result type
llvm::Type *resultType =
moduleTranslation.convertType(typeOffsetOp.getResult().getType());
if (!resultType)
return typeOffsetOp.emitError("Failed to translate the result type");
// Use GEP with null pointer to compute type size/offset.
llvm::Value *nullPtr = llvm::Constant::getNullValue(builder.getPtrTy(0));
llvm::Value *offsetPtr =
builder.CreateGEP(elementType, nullPtr, {builder.getInt32(1)});
llvm::Value *offset = builder.CreatePtrToInt(offsetPtr, resultType);
moduleTranslation.mapValue(typeOffsetOp.getResult(), offset);
return success();
}
/// Translate ptr.gather operation to LLVM IR.
static LogicalResult
translateGatherOp(GatherOp gatherOp, llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation) {
llvm::Value *ptrs = moduleTranslation.lookupValue(gatherOp.getPtrs());
llvm::Value *mask = moduleTranslation.lookupValue(gatherOp.getMask());
llvm::Value *passthrough =
moduleTranslation.lookupValue(gatherOp.getPassthrough());
if (!ptrs || !mask || !passthrough)
return gatherOp.emitError("Failed to lookup operands");
// Translate result type to LLVM type.
llvm::Type *resultType =
moduleTranslation.convertType(gatherOp.getResult().getType());
if (!resultType)
return gatherOp.emitError("Failed to translate result type");
// Get the alignment.
llvm::MaybeAlign alignment(gatherOp.getAlignment().value_or(0));
// Create the masked gather intrinsic call.
llvm::Value *result = builder.CreateMaskedGather(
resultType, ptrs, alignment.valueOrOne(), mask, passthrough);
moduleTranslation.mapValue(gatherOp.getResult(), result);
return success();
}
/// Translate ptr.masked_load operation to LLVM IR.
static LogicalResult
translateMaskedLoadOp(MaskedLoadOp maskedLoadOp, llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation) {
llvm::Value *ptr = moduleTranslation.lookupValue(maskedLoadOp.getPtr());
llvm::Value *mask = moduleTranslation.lookupValue(maskedLoadOp.getMask());
llvm::Value *passthrough =
moduleTranslation.lookupValue(maskedLoadOp.getPassthrough());
if (!ptr || !mask || !passthrough)
return maskedLoadOp.emitError("Failed to lookup operands");
// Translate result type to LLVM type.
llvm::Type *resultType =
moduleTranslation.convertType(maskedLoadOp.getResult().getType());
if (!resultType)
return maskedLoadOp.emitError("Failed to translate result type");
// Get the alignment.
llvm::MaybeAlign alignment(maskedLoadOp.getAlignment().value_or(0));
// Create the masked load intrinsic call.
llvm::Value *result = builder.CreateMaskedLoad(
resultType, ptr, alignment.valueOrOne(), mask, passthrough);
moduleTranslation.mapValue(maskedLoadOp.getResult(), result);
return success();
}
/// Translate ptr.masked_store operation to LLVM IR.
static LogicalResult
translateMaskedStoreOp(MaskedStoreOp maskedStoreOp,
llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation) {
llvm::Value *value = moduleTranslation.lookupValue(maskedStoreOp.getValue());
llvm::Value *ptr = moduleTranslation.lookupValue(maskedStoreOp.getPtr());
llvm::Value *mask = moduleTranslation.lookupValue(maskedStoreOp.getMask());
if (!value || !ptr || !mask)
return maskedStoreOp.emitError("Failed to lookup operands");
// Get the alignment.
llvm::MaybeAlign alignment(maskedStoreOp.getAlignment().value_or(0));
// Create the masked store intrinsic call.
builder.CreateMaskedStore(value, ptr, alignment.valueOrOne(), mask);
return success();
}
/// Translate ptr.scatter operation to LLVM IR.
static LogicalResult
translateScatterOp(ScatterOp scatterOp, llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation) {
llvm::Value *value = moduleTranslation.lookupValue(scatterOp.getValue());
llvm::Value *ptrs = moduleTranslation.lookupValue(scatterOp.getPtrs());
llvm::Value *mask = moduleTranslation.lookupValue(scatterOp.getMask());
if (!value || !ptrs || !mask)
return scatterOp.emitError("Failed to lookup operands");
// Get the alignment.
llvm::MaybeAlign alignment(scatterOp.getAlignment().value_or(0));
// Create the masked scatter intrinsic call.
builder.CreateMaskedScatter(value, ptrs, alignment.valueOrOne(), mask);
return success();
}
/// Translate ptr.constant operation to LLVM IR.
static LogicalResult
translateConstantOp(ConstantOp constantOp, llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation) {
// Translate result type to LLVM type
llvm::PointerType *resultType = dyn_cast_or_null<llvm::PointerType>(
moduleTranslation.convertType(constantOp.getResult().getType()));
if (!resultType)
return constantOp.emitError("Expected a valid pointer type");
llvm::Value *result = nullptr;
TypedAttr value = constantOp.getValue();
if (auto nullAttr = dyn_cast<ptr::NullAttr>(value)) {
// Create a null pointer constant
result = llvm::ConstantPointerNull::get(resultType);
} else if (auto addressAttr = dyn_cast<ptr::AddressAttr>(value)) {
// Create an integer constant and translate it to pointer
llvm::APInt addressValue = addressAttr.getValue();
// Determine the integer type width based on the target's pointer size
llvm::DataLayout dataLayout =
moduleTranslation.getLLVMModule()->getDataLayout();
unsigned pointerSizeInBits =
dataLayout.getPointerSizeInBits(resultType->getAddressSpace());
// Extend or truncate the address value to match pointer size if needed
if (addressValue.getBitWidth() != pointerSizeInBits) {
if (addressValue.getBitWidth() > pointerSizeInBits) {
constantOp.emitWarning()
<< "Truncating address value to fit pointer size";
}
addressValue = addressValue.getBitWidth() < pointerSizeInBits
? addressValue.zext(pointerSizeInBits)
: addressValue.trunc(pointerSizeInBits);
}
// Create integer constant and translate to pointer
llvm::Type *intType = builder.getIntNTy(pointerSizeInBits);
llvm::Value *intValue = llvm::ConstantInt::get(intType, addressValue);
result = builder.CreateIntToPtr(intValue, resultType);
} else {
return constantOp.emitError("Unsupported constant attribute type");
}
moduleTranslation.mapValue(constantOp.getResult(), result);
return success();
}
/// Translate ptr.ptr_diff operation operation to LLVM IR.
static LogicalResult
translatePtrDiffOp(PtrDiffOp ptrDiffOp, llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation) {
llvm::Value *lhs = moduleTranslation.lookupValue(ptrDiffOp.getLhs());
llvm::Value *rhs = moduleTranslation.lookupValue(ptrDiffOp.getRhs());
if (!lhs || !rhs)
return ptrDiffOp.emitError("Failed to lookup operands");
// Translate result type to LLVM type
llvm::Type *resultType =
moduleTranslation.convertType(ptrDiffOp.getResult().getType());
if (!resultType)
return ptrDiffOp.emitError("Failed to translate result type");
PtrDiffFlags flags = ptrDiffOp.getFlags();
// Convert both pointers to integers using ptrtoaddr, and compute the
// difference: lhs - rhs
llvm::Value *llLhs = builder.CreatePtrToAddr(lhs);
llvm::Value *llRhs = builder.CreatePtrToAddr(rhs);
llvm::Value *result = builder.CreateSub(
llLhs, llRhs, /*Name=*/"",
/*HasNUW=*/(flags & PtrDiffFlags::nuw) == PtrDiffFlags::nuw,
/*HasNSW=*/(flags & PtrDiffFlags::nsw) == PtrDiffFlags::nsw);
// Convert the difference to the expected result type by truncating or
// extending.
if (result->getType() != resultType)
result = builder.CreateIntCast(result, resultType, /*isSigned=*/true);
moduleTranslation.mapValue(ptrDiffOp.getResult(), result);
return success();
}
/// Implementation of the dialect interface that translates operations belonging
/// to the `ptr` dialect to LLVM IR.
class PtrDialectLLVMIRTranslationInterface
: public LLVMTranslationDialectInterface {
public:
using LLVMTranslationDialectInterface::LLVMTranslationDialectInterface;
/// Translates the given operation to LLVM IR using the provided IR builder
/// and saving the state in `moduleTranslation`.
LogicalResult
convertOperation(Operation *op, llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation) const final {
return llvm::TypeSwitch<Operation *, LogicalResult>(op)
.Case([&](ConstantOp constantOp) {
return translateConstantOp(constantOp, builder, moduleTranslation);
})
.Case([&](PtrAddOp ptrAddOp) {
return translatePtrAddOp(ptrAddOp, builder, moduleTranslation);
})
.Case([&](PtrDiffOp ptrDiffOp) {
return translatePtrDiffOp(ptrDiffOp, builder, moduleTranslation);
})
.Case([&](LoadOp loadOp) {
return translateLoadOp(loadOp, builder, moduleTranslation);
})
.Case([&](StoreOp storeOp) {
return translateStoreOp(storeOp, builder, moduleTranslation);
})
.Case([&](TypeOffsetOp typeOffsetOp) {
return translateTypeOffsetOp(typeOffsetOp, builder,
moduleTranslation);
})
.Case([&](GatherOp gatherOp) {
return translateGatherOp(gatherOp, builder, moduleTranslation);
})
.Case([&](MaskedLoadOp maskedLoadOp) {
return translateMaskedLoadOp(maskedLoadOp, builder,
moduleTranslation);
})
.Case([&](MaskedStoreOp maskedStoreOp) {
return translateMaskedStoreOp(maskedStoreOp, builder,
moduleTranslation);
})
.Case([&](ScatterOp scatterOp) {
return translateScatterOp(scatterOp, builder, moduleTranslation);
})
.Default([&](Operation *op) {
return op->emitError("Translation for operation '")
<< op->getName() << "' is not implemented.";
});
}
/// Attaches module-level metadata for functions marked as kernels.
LogicalResult
amendOperation(Operation *op, ArrayRef<llvm::Instruction *> instructions,
NamedAttribute attribute,
LLVM::ModuleTranslation &moduleTranslation) const final {
// No special amendments needed for ptr dialect operations
return success();
}
};
} // namespace
void mlir::registerPtrDialectTranslation(DialectRegistry ®istry) {
registry.insert<ptr::PtrDialect>();
registry.addExtension(+[](MLIRContext *ctx, ptr::PtrDialect *dialect) {
dialect->addInterfaces<PtrDialectLLVMIRTranslationInterface>();
});
}
void mlir::registerPtrDialectTranslation(MLIRContext &context) {
DialectRegistry registry;
registerPtrDialectTranslation(registry);
context.appendDialectRegistry(registry);
}
|