/
OpenACCToLLVMIRTranslation.cpp
394 lines (339 loc) · 16 KB
/
OpenACCToLLVMIRTranslation.cpp
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
//===- OpenACCToLLVMIRTranslation.cpp -------------------------------------===//
//
// 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 OpenACC dialect and LLVM
// IR.
//
//===----------------------------------------------------------------------===//
#include "mlir/Target/LLVMIR/Dialect/OpenACC/OpenACCToLLVMIRTranslation.h"
#include "mlir/Conversion/OpenACCToLLVM/ConvertOpenACCToLLVM.h"
#include "mlir/Dialect/LLVMIR/LLVMDialect.h"
#include "mlir/Dialect/OpenACC/OpenACC.h"
#include "mlir/IR/BuiltinOps.h"
#include "mlir/IR/Operation.h"
#include "mlir/Support/LLVM.h"
#include "mlir/Target/LLVMIR/ModuleTranslation.h"
#include "llvm/ADT/TypeSwitch.h"
#include "llvm/Frontend/OpenMP/OMPConstants.h"
#include "llvm/Support/FormatVariadic.h"
using namespace mlir;
using OpenACCIRBuilder = llvm::OpenMPIRBuilder;
//===----------------------------------------------------------------------===//
// Utility functions
//===----------------------------------------------------------------------===//
/// 0 = alloc/create
static constexpr uint64_t kCreateFlag = 0;
/// 1 = to/device/copyin
static constexpr uint64_t kDeviceCopyinFlag = 1;
/// 2 = from/copyout
static constexpr uint64_t kHostCopyoutFlag = 2;
/// 8 = delete
static constexpr uint64_t kDeleteFlag = 8;
/// Default value for the device id
static constexpr int64_t kDefaultDevice = -1;
/// Create a constant string location from the MLIR Location information.
static llvm::Constant *createSourceLocStrFromLocation(Location loc,
OpenACCIRBuilder &builder,
StringRef name) {
if (auto fileLoc = loc.dyn_cast<FileLineColLoc>()) {
StringRef fileName = fileLoc.getFilename();
unsigned lineNo = fileLoc.getLine();
unsigned colNo = fileLoc.getColumn();
return builder.getOrCreateSrcLocStr(name, fileName, lineNo, colNo);
} else {
std::string locStr;
llvm::raw_string_ostream locOS(locStr);
locOS << loc;
return builder.getOrCreateSrcLocStr(locOS.str());
}
}
/// Create the location struct from the operation location information.
static llvm::Value *createSourceLocationInfo(OpenACCIRBuilder &builder,
Operation *op) {
auto loc = op->getLoc();
auto funcOp = op->getParentOfType<LLVM::LLVMFuncOp>();
StringRef funcName = funcOp ? funcOp.getName() : "unknown";
llvm::Constant *locStr =
createSourceLocStrFromLocation(loc, builder, funcName);
return builder.getOrCreateIdent(locStr);
}
/// Create a constant string representing the mapping information extracted from
/// the MLIR location information.
static llvm::Constant *createMappingInformation(Location loc,
OpenACCIRBuilder &builder) {
if (auto nameLoc = loc.dyn_cast<NameLoc>()) {
StringRef name = nameLoc.getName();
return createSourceLocStrFromLocation(nameLoc.getChildLoc(), builder, name);
} else {
return createSourceLocStrFromLocation(loc, builder, "unknown");
}
}
/// Return the runtime function used to lower the given operation.
static llvm::Function *getAssociatedFunction(OpenACCIRBuilder &builder,
Operation *op) {
return llvm::TypeSwitch<Operation *, llvm::Function *>(op)
.Case([&](acc::EnterDataOp) {
return builder.getOrCreateRuntimeFunctionPtr(
llvm::omp::OMPRTL___tgt_target_data_begin_mapper);
})
.Case([&](acc::ExitDataOp) {
return builder.getOrCreateRuntimeFunctionPtr(
llvm::omp::OMPRTL___tgt_target_data_end_mapper);
})
.Case([&](acc::UpdateOp) {
return builder.getOrCreateRuntimeFunctionPtr(
llvm::omp::OMPRTL___tgt_target_data_update_mapper);
});
llvm_unreachable("Unknown OpenACC operation");
}
/// Computes the size of type in bytes.
static llvm::Value *getSizeInBytes(llvm::IRBuilderBase &builder,
llvm::Value *basePtr) {
llvm::LLVMContext &ctx = builder.getContext();
llvm::Value *null =
llvm::Constant::getNullValue(basePtr->getType()->getPointerTo());
llvm::Value *sizeGep =
builder.CreateGEP(basePtr->getType(), null, builder.getInt32(1));
llvm::Value *sizePtrToInt =
builder.CreatePtrToInt(sizeGep, llvm::Type::getInt64Ty(ctx));
return sizePtrToInt;
}
/// Extract pointer, size and mapping information from operands
/// to populate the future functions arguments.
static LogicalResult
processOperands(llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation, Operation *op,
ValueRange operands, unsigned totalNbOperand,
uint64_t operandFlag, SmallVector<uint64_t> &flags,
SmallVector<llvm::Constant *> &names, unsigned &index,
llvm::AllocaInst *argsBase, llvm::AllocaInst *args,
llvm::AllocaInst *argSizes) {
OpenACCIRBuilder *accBuilder = moduleTranslation.getOpenMPBuilder();
llvm::LLVMContext &ctx = builder.getContext();
auto *i8PtrTy = llvm::Type::getInt8PtrTy(ctx);
auto *arrI8PtrTy = llvm::ArrayType::get(i8PtrTy, totalNbOperand);
auto *i64Ty = llvm::Type::getInt64Ty(ctx);
auto *arrI64Ty = llvm::ArrayType::get(i64Ty, totalNbOperand);
for (Value data : operands) {
llvm::Value *dataValue = moduleTranslation.lookupValue(data);
llvm::Value *dataPtrBase;
llvm::Value *dataPtr;
llvm::Value *dataSize;
// Handle operands that were converted to DataDescriptor.
if (DataDescriptor::isValid(data)) {
dataPtrBase =
builder.CreateExtractValue(dataValue, kPtrBasePosInDataDescriptor);
dataPtr = builder.CreateExtractValue(dataValue, kPtrPosInDataDescriptor);
dataSize =
builder.CreateExtractValue(dataValue, kSizePosInDataDescriptor);
} else if (data.getType().isa<LLVM::LLVMPointerType>()) {
dataPtrBase = dataValue;
dataPtr = dataValue;
dataSize = getSizeInBytes(builder, dataValue);
} else {
return op->emitOpError()
<< "Data operand must be legalized before translation."
<< "Unsupported type: " << data.getType();
}
// Store base pointer extracted from operand into the i-th position of
// argBase.
llvm::Value *ptrBaseGEP = builder.CreateInBoundsGEP(
arrI8PtrTy, argsBase, {builder.getInt32(0), builder.getInt32(index)});
llvm::Value *ptrBaseCast = builder.CreateBitCast(
ptrBaseGEP, dataPtrBase->getType()->getPointerTo());
builder.CreateStore(dataPtrBase, ptrBaseCast);
// Store pointer extracted from operand into the i-th position of args.
llvm::Value *ptrGEP = builder.CreateInBoundsGEP(
arrI8PtrTy, args, {builder.getInt32(0), builder.getInt32(index)});
llvm::Value *ptrCast =
builder.CreateBitCast(ptrGEP, dataPtr->getType()->getPointerTo());
builder.CreateStore(dataPtr, ptrCast);
// Store size extracted from operand into the i-th position of argSizes.
llvm::Value *sizeGEP = builder.CreateInBoundsGEP(
arrI64Ty, argSizes, {builder.getInt32(0), builder.getInt32(index)});
builder.CreateStore(dataSize, sizeGEP);
flags.push_back(operandFlag);
llvm::Constant *mapName =
createMappingInformation(data.getLoc(), *accBuilder);
names.push_back(mapName);
++index;
}
return success();
}
/// Process data operands from acc::EnterDataOp
static LogicalResult processDataOperands(
llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation,
acc::EnterDataOp op, SmallVector<uint64_t> &flags,
SmallVector<llvm::Constant *> &names, llvm::AllocaInst *argsBase,
llvm::AllocaInst *args, llvm::AllocaInst *argSizes) {
// TODO add `create_zero` and `attach` operands
unsigned index = 0;
// Create operands are handled as `alloc` call.
if (failed(processOperands(builder, moduleTranslation, op,
op.createOperands(), op.getNumDataOperands(),
kCreateFlag, flags, names, index, argsBase, args,
argSizes)))
return failure();
// Copyin operands are handled as `to` call.
if (failed(processOperands(builder, moduleTranslation, op,
op.copyinOperands(), op.getNumDataOperands(),
kDeviceCopyinFlag, flags, names, index, argsBase,
args, argSizes)))
return failure();
return success();
}
/// Process data operands from acc::ExitDataOp
static LogicalResult processDataOperands(
llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation,
acc::ExitDataOp op, SmallVector<uint64_t> &flags,
SmallVector<llvm::Constant *> &names, llvm::AllocaInst *argsBase,
llvm::AllocaInst *args, llvm::AllocaInst *argSizes) {
// TODO add `detach` operands
unsigned index = 0;
// Delete operands are handled as `delete` call.
if (failed(processOperands(builder, moduleTranslation, op,
op.deleteOperands(), op.getNumDataOperands(),
kDeleteFlag, flags, names, index, argsBase, args,
argSizes)))
return failure();
// Copyout operands are handled as `from` call.
if (failed(processOperands(builder, moduleTranslation, op,
op.copyoutOperands(), op.getNumDataOperands(),
kHostCopyoutFlag, flags, names, index, argsBase,
args, argSizes)))
return failure();
return success();
}
/// Process data operands from acc::UpdateOp
static LogicalResult processDataOperands(
llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation,
acc::UpdateOp op, SmallVector<uint64_t> &flags,
SmallVector<llvm::Constant *> &names, llvm::AllocaInst *argsBase,
llvm::AllocaInst *args, llvm::AllocaInst *argSizes) {
unsigned index = 0;
// Host operands are handled as `from` call.
if (failed(processOperands(builder, moduleTranslation, op, op.hostOperands(),
op.getNumDataOperands(), kHostCopyoutFlag, flags,
names, index, argsBase, args, argSizes)))
return failure();
// Device operands are handled as `to` call.
if (failed(processOperands(builder, moduleTranslation, op,
op.deviceOperands(), op.getNumDataOperands(),
kDeviceCopyinFlag, flags, names, index, argsBase,
args, argSizes)))
return failure();
return success();
}
//===----------------------------------------------------------------------===//
// Conversion functions
//===----------------------------------------------------------------------===//
/// Converts an OpenACC standalone data operation into LLVM IR.
template <typename OpTy>
static LogicalResult
convertStandaloneDataOp(OpTy &op, llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation) {
auto enclosingFuncOp =
op.getOperation()->template getParentOfType<LLVM::LLVMFuncOp>();
llvm::Function *enclosingFunction =
moduleTranslation.lookupFunction(enclosingFuncOp.getName());
OpenACCIRBuilder *accBuilder = moduleTranslation.getOpenMPBuilder();
auto *srcLocInfo = createSourceLocationInfo(*accBuilder, op);
auto *mapperFunc = getAssociatedFunction(*accBuilder, op);
// Number of arguments in the enter_data operation.
unsigned totalNbOperand = op.getNumDataOperands();
// TODO could be moved to OpenXXIRBuilder?
llvm::LLVMContext &ctx = builder.getContext();
auto *i8PtrTy = llvm::Type::getInt8PtrTy(ctx);
auto *arrI8PtrTy = llvm::ArrayType::get(i8PtrTy, totalNbOperand);
auto *i64Ty = llvm::Type::getInt64Ty(ctx);
auto *arrI64Ty = llvm::ArrayType::get(i64Ty, totalNbOperand);
llvm::IRBuilder<>::InsertPoint allocaIP(
&enclosingFunction->getEntryBlock(),
enclosingFunction->getEntryBlock().getFirstInsertionPt());
llvm::IRBuilder<>::InsertPoint currentIP = builder.saveIP();
builder.restoreIP(allocaIP);
llvm::AllocaInst *argsBase = builder.CreateAlloca(arrI8PtrTy);
llvm::AllocaInst *args = builder.CreateAlloca(arrI8PtrTy);
llvm::AllocaInst *argSizes = builder.CreateAlloca(arrI64Ty);
builder.restoreIP(currentIP);
SmallVector<uint64_t> flags;
SmallVector<llvm::Constant *> names;
if (failed(processDataOperands(builder, moduleTranslation, op, flags, names,
argsBase, args, argSizes)))
return failure();
llvm::GlobalVariable *maptypes =
accBuilder->createOffloadMaptypes(flags, ".offload_maptypes");
llvm::Value *maptypesArg = builder.CreateConstInBoundsGEP2_32(
llvm::ArrayType::get(llvm::Type::getInt64Ty(ctx), totalNbOperand),
maptypes, /*Idx0=*/0, /*Idx1=*/0);
llvm::GlobalVariable *mapnames =
accBuilder->createOffloadMapnames(names, ".offload_mapnames");
llvm::Value *mapnamesArg = builder.CreateConstInBoundsGEP2_32(
llvm::ArrayType::get(llvm::Type::getInt8PtrTy(ctx), totalNbOperand),
mapnames, /*Idx0=*/0, /*Idx1=*/0);
llvm::Value *argsBaseGEP = builder.CreateInBoundsGEP(
arrI8PtrTy, argsBase, {builder.getInt32(0), builder.getInt32(0)});
llvm::Value *argsGEP = builder.CreateInBoundsGEP(
arrI8PtrTy, args, {builder.getInt32(0), builder.getInt32(0)});
llvm::Value *argSizesGEP = builder.CreateInBoundsGEP(
arrI64Ty, argSizes, {builder.getInt32(0), builder.getInt32(0)});
llvm::Value *nullPtr = llvm::Constant::getNullValue(
llvm::Type::getInt8PtrTy(ctx)->getPointerTo());
builder.CreateCall(mapperFunc,
{srcLocInfo, builder.getInt64(kDefaultDevice),
builder.getInt32(totalNbOperand), argsBaseGEP, argsGEP,
argSizesGEP, maptypesArg, mapnamesArg, nullPtr});
return success();
}
namespace {
/// Implementation of the dialect interface that converts operations belonging
/// to the OpenACC dialect to LLVM IR.
class OpenACCDialectLLVMIRTranslationInterface
: 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;
};
} // end namespace
/// Given an OpenACC MLIR operation, create the corresponding LLVM IR
/// (including OpenACC runtime calls).
LogicalResult OpenACCDialectLLVMIRTranslationInterface::convertOperation(
Operation *op, llvm::IRBuilderBase &builder,
LLVM::ModuleTranslation &moduleTranslation) const {
return llvm::TypeSwitch<Operation *, LogicalResult>(op)
.Case([&](acc::EnterDataOp enterDataOp) {
return convertStandaloneDataOp<acc::EnterDataOp>(enterDataOp, builder,
moduleTranslation);
})
.Case([&](acc::ExitDataOp exitDataOp) {
return convertStandaloneDataOp<acc::ExitDataOp>(exitDataOp, builder,
moduleTranslation);
})
.Case([&](acc::UpdateOp updateOp) {
return convertStandaloneDataOp<acc::UpdateOp>(updateOp, builder,
moduleTranslation);
})
.Default([&](Operation *op) {
return op->emitError("unsupported OpenACC operation: ")
<< op->getName();
});
}
void mlir::registerOpenACCDialectTranslation(DialectRegistry ®istry) {
registry.insert<acc::OpenACCDialect>();
registry.addDialectInterface<acc::OpenACCDialect,
OpenACCDialectLLVMIRTranslationInterface>();
}
void mlir::registerOpenACCDialectTranslation(MLIRContext &context) {
DialectRegistry registry;
registerOpenACCDialectTranslation(registry);
context.appendDialectRegistry(registry);
}