clang 24.0.0git
LowerToLLVMIR.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
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// This file implements lowering of CIR attributes and operations directly to
10// LLVMIR.
11//
12//===----------------------------------------------------------------------===//
13
14#include "mlir/Dialect/LLVMIR/LLVMConstantOps.h"
15#include "mlir/Dialect/LLVMIR/LLVMModuleOps.h"
16#include "mlir/IR/DialectRegistry.h"
17#include "mlir/Target/LLVMIR/LLVMTranslationInterface.h"
18#include "mlir/Target/LLVMIR/ModuleTranslation.h"
20#include "llvm/ADT/ArrayRef.h"
21#include "llvm/Frontend/Offloading/Utility.h"
22#include "llvm/IR/Constant.h"
23#include "llvm/IR/Constants.h"
24#include "llvm/IR/GlobalVariable.h"
25#include "llvm/IR/MDBuilder.h"
26#include "llvm/IR/Metadata.h"
27#include "llvm/Support/AMDGPUAddrSpace.h"
28
29using namespace llvm;
30
31namespace cir {
32namespace direct {
33
34namespace {
35/// Emits the -fgpu-rdc offloading entries once the globals they refer to have
36/// been translated.
37class CUDAOffloadEntries : public mlir::LLVM::ModuleTranslation::Extension {
38public:
39 MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(CUDAOffloadEntries)
40
41 CUDAOffloadEntries(mlir::ModuleOp mod, mlir::ArrayAttr entries,
42 llvm::Module &llvmModule)
43 : mod(mod), entries(entries), llvmModule(llvmModule) {}
44
45 mlir::LogicalResult finalize() override {
46 for (auto entry : entries.getAsRange<cir::CUDAOffloadEntryAttr>()) {
47 mlir::FlatSymbolRefAttr aux = entry.getAuxAddr();
48 llvm::GlobalValue *addr =
49 llvmModule.getNamedValue(entry.getAddr().getValue());
50 llvm::GlobalValue *auxAddr =
51 aux ? llvmModule.getNamedValue(aux.getValue()) : nullptr;
52 if (!addr || (aux && !auxAddr))
53 return mod.emitError("offloading entry refers to undefined symbol ")
54 << (addr ? aux : entry.getAddr());
55 llvm::offloading::emitOffloadingEntry(
56 llvmModule, static_cast<llvm::object::OffloadKind>(entry.getKind()),
57 addr, entry.getName(), entry.getSize(), entry.getFlags(),
58 entry.getData(), auxAddr);
59 }
60 return mlir::success();
61 }
62
63private:
64 mlir::ModuleOp mod;
65 mlir::ArrayAttr entries;
66 llvm::Module &llvmModule;
67};
68} // namespace
69
70/// Implementation of the dialect interface that converts CIR attributes to LLVM
71/// IR metadata.
73 : public mlir::LLVMTranslationDialectInterface {
74public:
75 using LLVMTranslationDialectInterface::LLVMTranslationDialectInterface;
76
77 /// Translates the given operation to LLVM IR using the provided IR builder
78 /// and saving the state in `moduleTranslation`.
79 mlir::LogicalResult convertOperation(
80 mlir::Operation *op, llvm::IRBuilderBase &builder,
81 mlir::LLVM::ModuleTranslation &moduleTranslation) const final {
82
83 if (auto cirOp = llvm::dyn_cast<mlir::LLVM::ZeroOp>(op))
84 moduleTranslation.mapValue(cirOp.getResult()) =
85 llvm::Constant::getNullValue(
86 moduleTranslation.convertType(cirOp.getType()));
87
88 return mlir::success();
89 }
90
91 /// Any named attribute in the CIR dialect, i.e, with name started with
92 /// "cir.", will be handled here.
93 virtual mlir::LogicalResult amendOperation(
94 mlir::Operation *op, llvm::ArrayRef<llvm::Instruction *> instructions,
95 mlir::NamedAttribute attribute,
96 mlir::LLVM::ModuleTranslation &moduleTranslation) const override {
97 if (auto func = dyn_cast<mlir::LLVM::LLVMFuncOp>(op)) {
98 if (mlir::failed(
99 amendFunction(func, instructions, attribute, moduleTranslation)))
100 return mlir::failure();
101 } else if (auto mod = dyn_cast<mlir::ModuleOp>(op)) {
102 if (mlir::failed(amendModule(mod, attribute, moduleTranslation)))
103 return mlir::failure();
104 } else if (attribute.getName() == "cir.riscv_nontemporal_domain") {
105 if (mlir::failed(amendRISCVNontemporalDomain(op, instructions, attribute,
106 moduleTranslation)))
107 return mlir::failure();
108 } else if (attribute.getName() == cir::CIRDialect::getSrcLocAttrName()) {
109 if (mlir::failed(amendSrcLoc(instructions, attribute, moduleTranslation)))
110 return mlir::failure();
111 } else if (attribute.getName() ==
112 cir::CIRDialect::getAMDGPUNoFineGrainedMemoryAttrName() ||
113 attribute.getName() ==
114 cir::CIRDialect::getAMDGPUNoRemoteMemoryAttrName() ||
115 attribute.getName() ==
116 cir::CIRDialect::getAMDGPUIgnoreDenormalModeAttrName() ||
117 attribute.getName() ==
118 cir::CIRDialect::getAMDGPUNoPrivateAddrSpaceAttrName()) {
119 amendAMDGPUAtomicMetadata(instructions, attribute, moduleTranslation);
120 }
121 return mlir::success();
122 }
123
124private:
125 // Convert the raw-encoded clang::SourceLocation into !srcloc, so that
126 // dontcall-error/warn works.
127 mlir::LogicalResult
128 amendSrcLoc(llvm::ArrayRef<llvm::Instruction *> instructions,
129 mlir::NamedAttribute attribute,
130 mlir::LLVM::ModuleTranslation &moduleTranslation) const {
131 auto srcLoc = mlir::dyn_cast<mlir::IntegerAttr>(attribute.getValue());
132 if (!srcLoc)
133 return mlir::failure();
134
135 llvm::LLVMContext &llvmContext = moduleTranslation.getLLVMContext();
136 llvm::MDNode *node = llvm::MDNode::get(
137 llvmContext, llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
138 llvm::Type::getInt64Ty(llvmContext),
139 srcLoc.getValue().getZExtValue())));
140 for (llvm::Instruction *inst : instructions)
141 inst->setMetadata("srcloc", node);
142 return mlir::success();
143 }
144
145 /// Attach the AMDGPU atomic metadata that lets the backend select a native
146 /// atomic instruction instead of expanding to a cmpxchg loop.
147 void amendAMDGPUAtomicMetadata(
149 mlir::NamedAttribute attribute,
150 mlir::LLVM::ModuleTranslation &moduleTranslation) const {
151 if (attribute.getName() ==
152 cir::CIRDialect::getAMDGPUNoPrivateAddrSpaceAttrName()) {
153 llvm::MDBuilder mdHelper(moduleTranslation.getLLVMContext());
154 llvm::MDNode *asRange = mdHelper.createRange(
155 llvm::APInt(32, llvm::AMDGPUAS::PRIVATE_ADDRESS),
156 llvm::APInt(32, llvm::AMDGPUAS::PRIVATE_ADDRESS + 1));
157 for (llvm::Instruction *inst : instructions)
158 inst->setMetadata(llvm::LLVMContext::MD_noalias_addrspace, asRange);
159 return;
160 }
161 llvm::MDNode *empty =
162 llvm::MDNode::get(moduleTranslation.getLLVMContext(), {});
163 // !atomic.ignore.denormal.mode is a fixed metadata kind so it has to be
164 // attached via its enum rather than by name.
165 if (attribute.getName() ==
166 cir::CIRDialect::getAMDGPUIgnoreDenormalModeAttrName()) {
167 for (llvm::Instruction *inst : instructions)
168 inst->setMetadata(llvm::LLVMContext::MD_atomic_ignore_denormal_mode,
169 empty);
170 return;
171 }
172 llvm::StringRef mdName;
173 if (attribute.getName() ==
174 cir::CIRDialect::getAMDGPUNoFineGrainedMemoryAttrName())
175 mdName = "amdgpu.no.fine.grained.memory";
176 else if (attribute.getName() ==
177 cir::CIRDialect::getAMDGPUNoRemoteMemoryAttrName())
178 mdName = "amdgpu.no.remote.memory";
179 for (llvm::Instruction *inst : instructions)
180 inst->setMetadata(mdName, empty);
181 }
182
183 mlir::LogicalResult amendRISCVNontemporalDomain(
184 mlir::Operation *op, llvm::ArrayRef<llvm::Instruction *> instructions,
185 mlir::NamedAttribute attribute,
186 mlir::LLVM::ModuleTranslation &moduleTranslation) const {
187 auto domain = mlir::dyn_cast<mlir::IntegerAttr>(attribute.getValue());
188 if (!domain)
189 return op->emitError()
190 << "expected cir.riscv_nontemporal_domain to be an integer";
191
192 llvm::LLVMContext &llvmContext = moduleTranslation.getLLVMContext();
193 llvm::MDNode *node = llvm::MDNode::get(
194 llvmContext, llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
195 llvm::Type::getInt32Ty(llvmContext),
196 domain.getValue().getZExtValue())));
197 for (llvm::Instruction *inst : instructions)
198 inst->setMetadata("riscv-nontemporal-domain", node);
199 return mlir::success();
200 }
201
202 // Translate CIR function attributes to LLVM function attributes.
203 mlir::LogicalResult
204 amendFunction(mlir::LLVM::LLVMFuncOp func,
205 llvm::ArrayRef<llvm::Instruction *> instructions,
206 mlir::NamedAttribute attribute,
207 mlir::LLVM::ModuleTranslation &moduleTranslation) const {
208 llvm::Function *llvmFunc = moduleTranslation.lookupFunction(func.getName());
209 llvm::StringRef attrName = attribute.getName().strref();
210
211 // Strip the "cir." prefix to get the LLVM attribute name.
212 llvm::StringRef llvmAttrName = attrName.substr(strlen("cir."));
213 if (auto strAttr = mlir::dyn_cast<mlir::StringAttr>(attribute.getValue()))
214 llvmFunc->addFnAttr(llvmAttrName, strAttr.getValue());
215 return mlir::success();
216 }
217
218 // Translate CIR's module attributes to LLVM's module metadata
219 mlir::LogicalResult
220 amendModule(mlir::ModuleOp mod, mlir::NamedAttribute attribute,
221 mlir::LLVM::ModuleTranslation &moduleTranslation) const {
222 llvm::Module *llvmModule = moduleTranslation.getLLVMModule();
223 llvm::LLVMContext &llvmContext = llvmModule->getContext();
224
225 if (attribute.getName() ==
226 cir::CIRDialect::getAMDGPUCodeObjectVersionAttrName()) {
227 if (auto intAttr =
228 mlir::dyn_cast<mlir::IntegerAttr>(attribute.getValue())) {
229 llvmModule->addModuleFlag(llvm::Module::Error,
230 "amdhsa_code_object_version",
231 static_cast<uint32_t>(intAttr.getInt()));
232 }
233 }
234
235 if (attribute.getName() == cir::CIRDialect::getAMDGPUPrintfKindAttrName()) {
236 if (auto strAttr =
237 mlir::dyn_cast<mlir::StringAttr>(attribute.getValue())) {
238 llvm::MDString *mdStr =
239 llvm::MDString::get(llvmContext, strAttr.getValue());
240 llvmModule->addModuleFlag(llvm::Module::Error, "amdgpu_printf_kind",
241 mdStr);
242 }
243 }
244
245 if (attribute.getName() == cir::CIRDialect::getAMDGPUXnackAttrName()) {
246 if (auto intAttr =
247 mlir::dyn_cast<mlir::IntegerAttr>(attribute.getValue())) {
248 llvmModule->addModuleFlag(llvm::Module::Error, "amdgpu.xnack",
249 static_cast<uint32_t>(intAttr.getInt()));
250 }
251 }
252
253 if (attribute.getName() ==
254 cir::CIRDialect::getCUDAOffloadEntriesAttrName()) {
255 if (auto entries = mlir::dyn_cast<mlir::ArrayAttr>(attribute.getValue()))
256 moduleTranslation.getOrCreateExtension<CUDAOffloadEntries>(mod, entries,
257 *llvmModule);
258 }
259
260 if (attribute.getName() == cir::CIRDialect::getAMDGPUSramEccAttrName()) {
261 if (auto intAttr =
262 mlir::dyn_cast<mlir::IntegerAttr>(attribute.getValue())) {
263 llvmModule->addModuleFlag(llvm::Module::Error, "amdgpu.sramecc",
264 static_cast<uint32_t>(intAttr.getInt()));
265 }
266 }
267
268 return mlir::success();
269 }
270};
271
272void registerCIRDialectTranslation(mlir::DialectRegistry &registry) {
273 registry.insert<cir::CIRDialect>();
274 registry.addExtension(+[](mlir::MLIRContext *ctx, cir::CIRDialect *dialect) {
275 dialect->addInterfaces<CIRDialectLLVMIRTranslationInterface>();
276 });
277}
278
279} // namespace direct
280} // namespace cir
281
282namespace mlir {
283void registerCIRDialectTranslation(mlir::MLIRContext &context) {
284 mlir::DialectRegistry registry;
286 context.appendDialectRegistry(registry);
287}
288} // namespace mlir
Implementation of the dialect interface that converts CIR attributes to LLVM IR metadata.
mlir::LogicalResult convertOperation(mlir::Operation *op, llvm::IRBuilderBase &builder, mlir::LLVM::ModuleTranslation &moduleTranslation) const final
Translates the given operation to LLVM IR using the provided IR builder and saving the state in modul...
virtual mlir::LogicalResult amendOperation(mlir::Operation *op, llvm::ArrayRef< llvm::Instruction * > instructions, mlir::NamedAttribute attribute, mlir::LLVM::ModuleTranslation &moduleTranslation) const override
Any named attribute in the CIR dialect, i.e, with name started with "cir.", will be handled here.
void registerCIRDialectTranslation(mlir::DialectRegistry &registry)
RangeSelector node(std::string ID)
Selects a node, including trailing semicolon, if any (for declarations and non-expression statements)...
Diagnostic wrappers for TextAPI types for error reporting.
Definition Dominators.h:30
void registerCIRDialectTranslation(mlir::MLIRContext &context)