MLIR 24.0.0git
ModuleImport.cpp
Go to the documentation of this file.
1//===- ModuleImport.cpp - LLVM to MLIR conversion ---------------*- 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// This file implements the import of an LLVM IR module into an LLVM dialect
10// module.
11//
12//===----------------------------------------------------------------------===//
13
17
18#include "AttrKindDetail.h"
19#include "DebugImporter.h"
21
35#include "mlir/IR/Builders.h"
36#include "mlir/IR/Matchers.h"
40
41#include "llvm/ADT/DepthFirstIterator.h"
42#include "llvm/ADT/PostOrderIterator.h"
43#include "llvm/ADT/STLExtras.h"
44#include "llvm/ADT/ScopeExit.h"
45#include "llvm/ADT/SmallPtrSet.h"
46#include "llvm/ADT/StringExtras.h"
47#include "llvm/ADT/TypeSwitch.h"
48#include "llvm/IR/Comdat.h"
49#include "llvm/IR/Constants.h"
50#include "llvm/IR/DebugProgramInstruction.h"
51#include "llvm/IR/InlineAsm.h"
52#include "llvm/IR/InstIterator.h"
53#include "llvm/IR/Instructions.h"
54#include "llvm/IR/IntrinsicInst.h"
55#include "llvm/IR/Metadata.h"
56#include "llvm/IR/ModuleSlotTracker.h"
57#include "llvm/IR/Operator.h"
58#include "llvm/Support/LogicalResult.h"
59#include "llvm/Support/ModRef.h"
60#include <optional>
61
62using namespace mlir;
63using namespace mlir::LLVM;
64using namespace mlir::LLVM::detail;
65
66#include "mlir/Dialect/LLVMIR/LLVMConversionEnumsFromLLVM.inc"
67
68/// Upper bound on the characters a diagnostic renders for an LLVM entity.
69/// One rendering is unbounded by nature: a GlobalVariable prints its entire
70/// initializer, and a node with long MDStrings or large inline constants
71/// prints them whole. On a merged library a single unbounded diagnostic
72/// reaches tens of megabytes, so every rendering path below truncates its
73/// output. Diagnostics only need to identify the entity; the full form is
74/// in the input being imported.
75static constexpr size_t kMaxDiagLength = 256;
76
77static std::string truncateDiag(std::string str) {
78 if (str.size() <= kMaxDiagLength)
79 return str;
80 str.resize(kMaxDiagLength);
81 str += "... <truncated>";
82 return str;
83}
84
85/// Prints a metadata node through a caller-provided tracker so module-flag
86/// conversion shares the importer's tracker instead of building one per call.
87static std::string renderMetadataWithTracker(const llvm::Metadata *node,
88 llvm::ModuleSlotTracker &tracker,
89 const llvm::Module *module) {
90 std::string str;
91 llvm::raw_string_ostream os(str);
92 node->print(os, tracker, module, /*IsForDebug=*/true);
93 return truncateDiag(std::move(str));
94}
95
96llvm::ModuleSlotTracker &ModuleImport::getDiagSlotTracker() {
97 // Printing through a caller-provided tracker numbers exactly like the
98 // per-call tracker Metadata::print and Value::print would construct, but
99 // the tracker's lazy module pre-pass is paid once per import instead of
100 // once per rendering.
101 if (!diagSlotTracker)
102 diagSlotTracker =
103 std::make_unique<llvm::ModuleSlotTracker>(llvmModule.get());
104 return *diagSlotTracker;
105}
106
107std::string ModuleImport::renderValue(const llvm::Value &value) {
108 std::string str;
109 llvm::raw_string_ostream os(str);
110 // A GlobalValue renders its full definition. For a merged vtable or string
111 // table that is megabytes, so print globals by name only.
112 if (const auto *global = llvm::dyn_cast<llvm::GlobalValue>(&value)) {
113 global->printAsOperand(os, /*PrintType=*/false, getDiagSlotTracker());
114 return truncateDiag(std::move(str));
115 }
116 value.print(os, getDiagSlotTracker());
117 return truncateDiag(std::move(str));
118}
119
120std::string ModuleImport::renderMetadata(const llvm::Metadata *node) {
121 return renderMetadataWithTracker(node, getDiagSlotTracker(),
122 llvmModule.get());
123}
124
125/// Returns the name of the global_ctors global variables.
126static constexpr StringRef getGlobalCtorsVarName() {
127 return "llvm.global_ctors";
128}
129
130/// Prefix used for symbols of nameless llvm globals.
131static constexpr StringRef getNamelessGlobalPrefix() {
132 return "mlir.llvm.nameless_global";
133}
134
135/// Returns the name of the global_dtors global variables.
136static constexpr StringRef getGlobalDtorsVarName() {
137 return "llvm.global_dtors";
138}
139
140/// Returns the symbol name for the module-level comdat operation. It must not
141/// conflict with the user namespace.
142static constexpr StringRef getGlobalComdatOpName() {
143 return "__llvm_global_comdat";
144}
145
146/// Converts the sync scope identifier of `inst` to the string representation
147/// necessary to build an atomic LLVM dialect operation. Returns the empty
148/// string if the operation has either no sync scope or the default system-level
149/// sync scope attached. The atomic operations only set their sync scope
150/// attribute if they have a non-default sync scope attached.
151static StringRef getLLVMSyncScope(llvm::Instruction *inst) {
152 std::optional<llvm::SyncScope::ID> syncScopeID =
153 llvm::getAtomicSyncScopeID(inst);
154 if (!syncScopeID)
155 return "";
156
157 // Search the sync scope name for the given identifier. The default
158 // system-level sync scope thereby maps to the empty string.
159 SmallVector<StringRef> syncScopeName;
160 llvm::LLVMContext &llvmContext = inst->getContext();
161 llvmContext.getSyncScopeNames(syncScopeName);
162 auto *it = llvm::find_if(syncScopeName, [&](StringRef name) {
163 return *syncScopeID == llvmContext.getOrInsertSyncScopeID(name);
164 });
165 if (it != syncScopeName.end())
166 return *it;
167 llvm_unreachable("incorrect sync scope identifier");
168}
169
170/// Converts an array of unsigned indices to a signed integer position array.
172 SmallVector<int64_t> position;
173 llvm::append_range(position, indices);
174 return position;
175}
176
177/// Converts the LLVM instructions that have a generated MLIR builder. Using a
178/// static implementation method called from the module import ensures the
179/// builders have to use the `moduleImport` argument and cannot directly call
180/// import methods. As a result, both the intrinsic and the instruction MLIR
181/// builders have to use the `moduleImport` argument and none of them has direct
182/// access to the private module import methods.
183static LogicalResult convertInstructionImpl(OpBuilder &odsBuilder,
184 llvm::Instruction *inst,
185 ModuleImport &moduleImport,
186 LLVMImportInterface &iface) {
187 // Copy the operands to an LLVM operands array reference for conversion.
188 SmallVector<llvm::Value *> operands(inst->operands());
189 ArrayRef<llvm::Value *> llvmOperands(operands);
190
191 // Convert all instructions that provide an MLIR builder.
192 if (iface.isConvertibleInstruction(inst->getOpcode()))
193 return iface.convertInstruction(odsBuilder, inst, llvmOperands,
194 moduleImport);
195 // TODO: Implement the `convertInstruction` hooks in the
196 // `LLVMDialectLLVMIRImportInterface` and move the following include there.
197#include "mlir/Dialect/LLVMIR/LLVMOpFromLLVMIRConversions.inc"
198
199 return failure();
200}
201
202FlatSymbolRefAttr
203ModuleImport::getMetadataGlobalValueSymbolRef(llvm::GlobalValue *global) {
204 if (auto *globalVar = dyn_cast<llvm::GlobalVariable>(global)) {
205 StringRef name = globalVar->getName();
206 if (name.empty())
207 return getOrCreateNamelessSymbolName(globalVar);
208 if (name == getGlobalCtorsVarName() || name == getGlobalDtorsVarName())
209 return {};
210 }
211
212 if (auto *func = dyn_cast<llvm::Function>(global)) {
213 // Intrinsics with a dedicated import conversion do not have an imported
214 // function declaration that a metadata symbol reference could resolve to.
215 if (func->isIntrinsic() &&
216 iface.isConvertibleIntrinsic(func->getIntrinsicID()))
217 return {};
218 }
219
220 if (global->getName().empty())
221 return {};
222 return FlatSymbolRefAttr::get(context, global->getName());
223}
224
225FlatSymbolRefAttr
226ModuleImport::getMetadataOperandSymbolRef(const llvm::Metadata *md) {
227 auto *valueAsMD = dyn_cast_or_null<llvm::ValueAsMetadata>(md);
228 if (!valueAsMD)
229 return {};
230 llvm::Value *value = valueAsMD->getValue();
231 llvm::GlobalValue *gv = dyn_cast<llvm::GlobalValue>(value);
232 if (!gv)
233 gv = dyn_cast<llvm::GlobalValue>(value->stripPointerCastsAndAliases());
234 if (!gv)
235 return {};
236 return getMetadataGlobalValueSymbolRef(gv);
237}
238
239/// Depth-first conversion of the metadata node `md` to the matching LLVM
240/// dialect metadata attribute. Returns a null attribute for shapes that the
241/// dialect's metadata-attribute hierarchy does not currently model. `path`
242/// holds the metadata nodes on the current depth-first search path. Cyclic
243/// metadata graphs are valid in LLVM IR, but they cannot be expressed by the
244/// immutable, structurally-uniqued metadata attributes built here. The `path`
245/// set lets the traversal recognize such a back-edge and bail out. `attrMap`
246/// caches the attributes of fully converted nodes so that shared subgraphs
247/// are visited only once.
248Attribute ModuleImport::convertMetadataToAttrImpl(
249 const llvm::Metadata *md, SmallPtrSetImpl<const llvm::Metadata *> &path,
251 if (!md)
252 return {};
253 if (auto *mdStr = dyn_cast<llvm::MDString>(md))
254 return MDStringAttr::get(context,
255 StringAttr::get(context, mdStr->getString()));
256 if (auto *cam = dyn_cast<llvm::ConstantAsMetadata>(md)) {
257 llvm::Constant *constant = cam->getValue();
258 if (auto *global = dyn_cast<llvm::GlobalValue>(constant)) {
259 if (FlatSymbolRefAttr symbolRef = getMetadataGlobalValueSymbolRef(global))
260 return MDGlobalValueAttr::get(context, symbolRef);
261 }
262 if (auto *ci = dyn_cast<llvm::ConstantInt>(constant)) {
263 auto intType = IntegerType::get(context, ci->getBitWidth());
264 return MDConstantAttr::get(context,
265 IntegerAttr::get(intType, ci->getValue()));
266 }
267 if (auto *nullPtr = dyn_cast<llvm::ConstantPointerNull>(constant))
268 return MDNullAttr::get(context,
269 nullPtr->getType()->getPointerAddressSpace());
270 if (auto *constExpr = dyn_cast<llvm::ConstantExpr>(constant)) {
271 // Only `addrspacecast` is modelled; other constant expressions have no
272 // metadata-attribute counterpart.
273 if (constExpr->getOpcode() != llvm::Instruction::AddrSpaceCast)
274 return {};
275 Attribute argAttr = convertMetadataToAttrImpl(
276 llvm::ConstantAsMetadata::get(constExpr->getOperand(0)), path,
277 attrMap);
278 if (!argAttr)
279 return {};
280 return MDAddrSpaceCastAttr::get(
281 context, argAttr, constExpr->getType()->getPointerAddressSpace());
282 }
283 return {};
284 }
285 if (auto *node = dyn_cast<llvm::MDNode>(md)) {
286 // Metadata attributes cannot preserve distinctness, so bail out.
287 if (node->isDistinct())
288 return {};
289 if (Attribute cached = attrMap.lookup(node))
290 return cached;
291 // If `node` is already on the current search path, this is a back-edge into
292 // a cyclic graph. While that's valid it isn't implemented yet, so bail out.
293 if (!path.insert(node).second)
294 return {};
295 SmallVector<Attribute> operands;
296 operands.reserve(node->getNumOperands());
297 for (const llvm::MDOperand &op : node->operands()) {
298 Attribute opAttr = convertMetadataToAttrImpl(op.get(), path, attrMap);
299 if (!opAttr)
300 return {};
301 operands.push_back(opAttr);
302 }
303 path.erase(node);
304 Attribute nodeAttr = MDNodeAttr::get(context, operands);
305 attrMap.try_emplace(node, nodeAttr);
306 return nodeAttr;
307 }
308 return {};
309}
310
311/// Converts the metadata node `md` to the matching LLVM dialect metadata
312/// attribute. Returns a null attribute for shapes that the dialect's
313/// metadata-attribute hierarchy does not currently model, including distinct
314/// nodes and cyclic metadata graphs that the immutable metadata attributes
315/// cannot express.
316Attribute ModuleImport::convertMetadataToAttr(const llvm::Metadata *md) {
317 SmallPtrSet<const llvm::Metadata *, 8> path;
319 return convertMetadataToAttrImpl(md, path, attrMap);
320}
321
322/// Get a topologically sorted list of blocks for the given basic blocks.
326 for (llvm::BasicBlock *basicBlock : basicBlocks) {
327 if (!blocks.contains(basicBlock)) {
328 llvm::ReversePostOrderTraversal<llvm::BasicBlock *> traversal(basicBlock);
329 blocks.insert_range(traversal);
330 }
331 }
332 assert(blocks.size() == basicBlocks.size() && "some blocks are not sorted");
333 return blocks;
334}
335
337
338ModuleImport::ModuleImport(ModuleOp mlirModule,
339 std::unique_ptr<llvm::Module> llvmModule,
340 bool emitExpensiveWarnings,
341 bool importEmptyDICompositeTypes,
342 bool preferUnregisteredIntrinsics,
343 bool importStructsAsLiterals)
344 : builder(mlirModule->getContext()), context(mlirModule->getContext()),
345 mlirModule(mlirModule), llvmModule(std::move(llvmModule)),
346 iface(mlirModule->getContext()),
347 typeTranslator(*mlirModule->getContext(), importStructsAsLiterals),
348 debugImporter(std::make_unique<DebugImporter>(
349 mlirModule, importEmptyDICompositeTypes)),
350 loopAnnotationImporter(
351 std::make_unique<LoopAnnotationImporter>(*this, builder)),
352 emitExpensiveWarnings(emitExpensiveWarnings),
353 preferUnregisteredIntrinsics(preferUnregisteredIntrinsics) {
354 builder.setInsertionPointToStart(mlirModule.getBody());
355}
356
357ComdatOp ModuleImport::getGlobalComdatOp() {
358 if (globalComdatOp)
359 return globalComdatOp;
360
361 OpBuilder::InsertionGuard guard(builder);
362 builder.setInsertionPointToEnd(mlirModule.getBody());
363 globalComdatOp =
364 ComdatOp::create(builder, mlirModule.getLoc(), getGlobalComdatOpName());
365 globalInsertionOp = globalComdatOp;
366 return globalComdatOp;
367}
368
369LogicalResult ModuleImport::processTBAAMetadata(const llvm::MDNode *node) {
370 Location loc = mlirModule.getLoc();
371
372 // If `node` is a valid TBAA root node, then return its optional identity
373 // string, otherwise return failure.
374 auto getIdentityIfRootNode =
375 [&](const llvm::MDNode *node) -> FailureOr<std::optional<StringRef>> {
376 // Root node, e.g.:
377 // !0 = !{!"Simple C/C++ TBAA"}
378 // !1 = !{}
379 if (node->getNumOperands() > 1)
380 return failure();
381 // If the operand is MDString, then assume that this is a root node.
382 if (node->getNumOperands() == 1)
383 if (const auto *op0 = dyn_cast<const llvm::MDString>(node->getOperand(0)))
384 return std::optional<StringRef>{op0->getString()};
385 return std::optional<StringRef>{};
386 };
387
388 // If `node` looks like a TBAA type descriptor metadata,
389 // then return true, if it is a valid node, and false otherwise.
390 // If it does not look like a TBAA type descriptor metadata, then
391 // return std::nullopt.
392 // If `identity` and `memberTypes/Offsets` are non-null, then they will
393 // contain the converted metadata operands for a valid TBAA node (i.e. when
394 // true is returned).
395 auto isTypeDescriptorNode = [&](const llvm::MDNode *node,
396 StringRef *identity = nullptr,
397 SmallVectorImpl<TBAAMemberAttr> *members =
398 nullptr) -> std::optional<bool> {
399 unsigned numOperands = node->getNumOperands();
400 // Type descriptor, e.g.:
401 // !1 = !{!"int", !0, /*optional*/i64 0} /* scalar int type */
402 // !2 = !{!"agg_t", !1, i64 0} /* struct agg_t { int x; } */
403 if (numOperands < 2)
404 return std::nullopt;
405
406 // TODO: support "new" format (D41501) for type descriptors,
407 // where the first operand is an MDNode.
408 const auto *identityNode =
409 dyn_cast<const llvm::MDString>(node->getOperand(0));
410 if (!identityNode)
411 return std::nullopt;
412
413 // This should be a type descriptor node.
414 if (identity)
415 *identity = identityNode->getString();
416
417 for (unsigned pairNum = 0, e = numOperands / 2; pairNum < e; ++pairNum) {
418 const auto *memberNode =
419 dyn_cast<const llvm::MDNode>(node->getOperand(2 * pairNum + 1));
420 if (!memberNode) {
421 emitError(loc) << "operand '" << 2 * pairNum + 1
422 << "' must be MDNode: " << renderMetadata(node);
423 return false;
424 }
425 int64_t offset = 0;
426 if (2 * pairNum + 2 >= numOperands) {
427 // Allow for optional 0 offset in 2-operand nodes.
428 if (numOperands != 2) {
429 emitError(loc) << "missing member offset: " << renderMetadata(node);
430 return false;
431 }
432 } else {
433 auto *offsetCI = llvm::mdconst::dyn_extract<llvm::ConstantInt>(
434 node->getOperand(2 * pairNum + 2));
435 if (!offsetCI) {
436 emitError(loc) << "operand '" << 2 * pairNum + 2
437 << "' must be ConstantInt: " << renderMetadata(node);
438 return false;
439 }
440 offset = offsetCI->getZExtValue();
441 }
442
443 if (members)
444 members->push_back(TBAAMemberAttr::get(
445 cast<TBAANodeAttr>(tbaaMapping.lookup(memberNode)), offset));
446 }
447
448 return true;
449 };
450
451 // If `node` looks like a TBAA access tag metadata,
452 // then return true, if it is a valid node, and false otherwise.
453 // If it does not look like a TBAA access tag metadata, then
454 // return std::nullopt.
455 // If the other arguments are non-null, then they will contain
456 // the converted metadata operands for a valid TBAA node (i.e. when true is
457 // returned).
458 auto isTagNode = [&](const llvm::MDNode *node,
459 TBAATypeDescriptorAttr *baseAttr = nullptr,
460 TBAATypeDescriptorAttr *accessAttr = nullptr,
461 int64_t *offset = nullptr,
462 bool *isConstant = nullptr) -> std::optional<bool> {
463 // Access tag, e.g.:
464 // !3 = !{!1, !1, i64 0} /* scalar int access */
465 // !4 = !{!2, !1, i64 0} /* agg_t::x access */
466 //
467 // Optional 4th argument is ConstantInt 0/1 identifying whether
468 // the location being accessed is "constant" (see for details:
469 // https://llvm.org/docs/LangRef.html#representation).
470 unsigned numOperands = node->getNumOperands();
471 if (numOperands != 3 && numOperands != 4)
472 return std::nullopt;
473 const auto *baseMD = dyn_cast<const llvm::MDNode>(node->getOperand(0));
474 const auto *accessMD = dyn_cast<const llvm::MDNode>(node->getOperand(1));
475 auto *offsetCI =
476 llvm::mdconst::dyn_extract<llvm::ConstantInt>(node->getOperand(2));
477 if (!baseMD || !accessMD || !offsetCI)
478 return std::nullopt;
479 // TODO: support "new" TBAA format, if needed (see D41501).
480 // In the "old" format the first operand of the access type
481 // metadata is MDString. We have to distinguish the formats,
482 // because access tags have the same structure, but different
483 // meaning for the operands.
484 if (accessMD->getNumOperands() < 1 ||
485 !isa<llvm::MDString>(accessMD->getOperand(0)))
486 return std::nullopt;
487 bool isConst = false;
488 if (numOperands == 4) {
489 auto *isConstantCI =
490 llvm::mdconst::dyn_extract<llvm::ConstantInt>(node->getOperand(3));
491 if (!isConstantCI) {
492 emitError(loc) << "operand '3' must be ConstantInt: "
493 << renderMetadata(node);
494 return false;
495 }
496 isConst = isConstantCI->getValue()[0];
497 }
498 if (baseAttr)
499 *baseAttr = cast<TBAATypeDescriptorAttr>(tbaaMapping.lookup(baseMD));
500 if (accessAttr)
501 *accessAttr = cast<TBAATypeDescriptorAttr>(tbaaMapping.lookup(accessMD));
502 if (offset)
503 *offset = offsetCI->getZExtValue();
504 if (isConstant)
505 *isConstant = isConst;
506 return true;
507 };
508
509 // Do a post-order walk over the TBAA Graph. Since a correct TBAA Graph is a
510 // DAG, a post-order walk guarantees that we convert any metadata node we
511 // depend on, prior to converting the current node.
513 SmallVector<const llvm::MDNode *> workList;
514 workList.push_back(node);
515 while (!workList.empty()) {
516 const llvm::MDNode *current = workList.back();
517 if (tbaaMapping.contains(current)) {
518 // Already converted. Just pop from the worklist.
519 workList.pop_back();
520 continue;
521 }
522
523 // If any child of this node is not yet converted, don't pop the current
524 // node from the worklist but push the not-yet-converted children in the
525 // front of the worklist.
526 bool anyChildNotConverted = false;
527 for (const llvm::MDOperand &operand : current->operands())
528 if (auto *childNode = dyn_cast_or_null<const llvm::MDNode>(operand.get()))
529 if (!tbaaMapping.contains(childNode)) {
530 workList.push_back(childNode);
531 anyChildNotConverted = true;
532 }
533
534 if (anyChildNotConverted) {
535 // If this is the second time we failed to convert an element in the
536 // worklist it must be because a child is dependent on it being converted
537 // and we have a cycle in the graph. Cycles are not allowed in TBAA
538 // graphs.
539 if (!seen.insert(current).second)
540 return emitError(loc)
541 << "has cycle in TBAA graph: " << renderMetadata(current);
542
543 continue;
544 }
545
546 // Otherwise simply import the current node.
547 workList.pop_back();
548
549 FailureOr<std::optional<StringRef>> rootNodeIdentity =
550 getIdentityIfRootNode(current);
551 if (succeeded(rootNodeIdentity)) {
552 StringAttr stringAttr = *rootNodeIdentity
553 ? builder.getStringAttr(**rootNodeIdentity)
554 : nullptr;
555 // The root nodes do not have operands, so we can create
556 // the TBAARootAttr on the first walk.
557 tbaaMapping.insert({current, builder.getAttr<TBAARootAttr>(stringAttr)});
558 continue;
559 }
560
561 StringRef identity;
562 SmallVector<TBAAMemberAttr> members;
563 if (std::optional<bool> isValid =
564 isTypeDescriptorNode(current, &identity, &members)) {
565 assert(isValid.value() && "type descriptor node must be valid");
566
567 tbaaMapping.insert({current, builder.getAttr<TBAATypeDescriptorAttr>(
568 identity, members)});
569 continue;
570 }
571
572 TBAATypeDescriptorAttr baseAttr, accessAttr;
573 int64_t offset;
574 bool isConstant;
575 if (std::optional<bool> isValid =
576 isTagNode(current, &baseAttr, &accessAttr, &offset, &isConstant)) {
577 assert(isValid.value() && "access tag node must be valid");
578 tbaaMapping.insert(
579 {current, builder.getAttr<TBAATagAttr>(baseAttr, accessAttr, offset,
580 isConstant)});
581 continue;
582 }
583
584 return emitError(loc) << "unsupported TBAA node format: "
585 << renderMetadata(current);
586 }
587 return success();
588}
589
590Attribute ModuleImport::convertTBAAStructMetadata(const llvm::MDNode *node) {
591 // Operands come in conceptual groups of three; anything else is malformed.
592 if (node->getNumOperands() == 0 || node->getNumOperands() % 3 != 0)
593 return {};
594
595 SmallVector<Attribute> fields;
596 fields.reserve(node->getNumOperands() / 3);
597 for (unsigned i = 0, e = node->getNumOperands(); i != e; i += 3) {
598 auto *offset = llvm::mdconst::dyn_extract_or_null<llvm::ConstantInt>(
599 node->getOperand(i));
600 auto *size = llvm::mdconst::dyn_extract_or_null<llvm::ConstantInt>(
601 node->getOperand(i + 1));
602 if (!offset || !size)
603 return {};
604 // Offsets and sizes are uint64_t in the attribute. Read them as APInts:
605 // LLVM compares offsets zero-extended, so a narrow constant with its
606 // high bit set (e.g. i32 0x80000000) must keep its unsigned value
607 // rather than sign-extending. Values using more than 64 bits cannot
608 // be represented and are declined.
609 const APInt &offsetAP = offset->getValue();
610 const APInt &sizeAP = size->getValue();
611 if (offsetAP.getActiveBits() > 64 || sizeAP.getActiveBits() > 64)
612 return {};
613 auto *tagNode = dyn_cast_if_present<llvm::MDNode>(node->getOperand(i + 2));
614 if (!tagNode)
615 return {};
616 auto tag = dyn_cast_if_present<TBAATagAttr>(lookupTBAAAttr(tagNode));
617 if (!tag)
618 return {};
619 fields.push_back(builder.getAttr<TBAAStructFieldAttr>(
620 offsetAP.getZExtValue(), sizeAP.getZExtValue(), tag));
621 }
622
623 return builder.getArrayAttr(fields);
624}
625
626LogicalResult
627ModuleImport::processAccessGroupMetadata(const llvm::MDNode *node) {
628 Location loc = mlirModule.getLoc();
629 if (failed(loopAnnotationImporter->translateAccessGroup(node, loc)))
630 return emitError(loc) << "unsupported access group node: "
631 << renderMetadata(node);
632 return success();
633}
634
635LogicalResult
636ModuleImport::processAliasScopeMetadata(const llvm::MDNode *node) {
637 Location loc = mlirModule.getLoc();
638 // Helper that verifies the node has a self reference operand.
639 auto verifySelfRef = [](const llvm::MDNode *node) {
640 return node->getNumOperands() != 0 &&
641 node == dyn_cast<llvm::MDNode>(node->getOperand(0));
642 };
643 auto verifySelfRefOrString = [](const llvm::MDNode *node) {
644 return node->getNumOperands() != 0 &&
645 (node == dyn_cast<llvm::MDNode>(node->getOperand(0)) ||
646 isa<llvm::MDString>(node->getOperand(0)));
647 };
648 // Helper that verifies the given operand is a string or does not exist.
649 auto verifyDescription = [](const llvm::MDNode *node, unsigned idx) {
650 return idx >= node->getNumOperands() ||
651 isa<llvm::MDString>(node->getOperand(idx));
652 };
653
654 auto getIdAttr = [&](const llvm::MDNode *node) -> Attribute {
655 if (verifySelfRef(node))
656 return DistinctAttr::create(builder.getUnitAttr());
657
658 auto *name = cast<llvm::MDString>(node->getOperand(0));
659 return builder.getStringAttr(name->getString());
660 };
661
662 // Helper that creates an alias scope domain attribute.
663 auto createAliasScopeDomainOp = [&](const llvm::MDNode *aliasDomain) {
664 StringAttr description = nullptr;
665 StringRef descriptionStr =
666 llvm::AliasScopeDomainNode(aliasDomain).getDescription();
667 if (!descriptionStr.empty())
668 description = builder.getStringAttr(descriptionStr);
669 Attribute idAttr = getIdAttr(aliasDomain);
670 return builder.getAttr<AliasScopeDomainAttr>(idAttr, description);
671 };
672
673 // Collect the alias scopes and domains to translate them.
674 for (const llvm::MDOperand &operand : node->operands()) {
675 if (const auto *scope = dyn_cast<llvm::MDNode>(operand)) {
676 llvm::AliasScopeNode aliasScope(scope);
677 const llvm::MDNode *domain = aliasScope.getDomain();
678
679 // Verify the scope node points to valid scope metadata which includes
680 // verifying its domain. Perform the verification before looking it up in
681 // the alias scope mapping since it could have been inserted as a domain
682 // node before.
683 if (!verifySelfRefOrString(scope) || !domain ||
684 !verifyDescription(scope, 2))
685 return emitError(loc)
686 << "unsupported alias scope node: " << renderMetadata(scope);
687 if (!verifySelfRefOrString(domain) || !verifyDescription(domain, 2))
688 return emitError(loc)
689 << "unsupported alias domain node: " << renderMetadata(domain);
690
691 if (aliasScopeMapping.contains(scope))
692 continue;
693
694 // Convert the domain metadata node if it has not been translated before.
695 auto it = aliasScopeMapping.find(aliasScope.getDomain());
696 if (it == aliasScopeMapping.end()) {
697 auto aliasScopeDomainOp = createAliasScopeDomainOp(domain);
698 it = aliasScopeMapping.try_emplace(domain, aliasScopeDomainOp).first;
699 }
700
701 // Convert the scope metadata node if it has not been converted before.
702 StringAttr description = nullptr;
703 if (!aliasScope.getName().empty())
704 description = builder.getStringAttr(aliasScope.getName());
705 Attribute idAttr = getIdAttr(scope);
706 auto aliasScopeOp = builder.getAttr<AliasScopeAttr>(
707 idAttr, cast<AliasScopeDomainAttr>(it->second), description);
708
709 aliasScopeMapping.try_emplace(aliasScope.getNode(), aliasScopeOp);
710 }
711 }
712 return success();
713}
714
715FailureOr<SmallVector<AliasScopeAttr>>
716ModuleImport::lookupAliasScopeAttrs(const llvm::MDNode *node) const {
717 SmallVector<AliasScopeAttr> aliasScopes;
718 aliasScopes.reserve(node->getNumOperands());
719 for (const llvm::MDOperand &operand : node->operands()) {
720 auto *node = cast<llvm::MDNode>(operand.get());
721 aliasScopes.push_back(
722 dyn_cast_or_null<AliasScopeAttr>(aliasScopeMapping.lookup(node)));
723 }
724 // Return failure if one of the alias scope lookups failed.
725 if (llvm::is_contained(aliasScopes, nullptr))
726 return failure();
727 return aliasScopes;
728}
729
730void ModuleImport::addDebugIntrinsic(llvm::CallInst *intrinsic) {
731 debugIntrinsics.insert(intrinsic);
732}
733
734void ModuleImport::addDebugRecord(llvm::DbgVariableRecord *dbgRecord) {
735 if (!dbgRecords.contains(dbgRecord))
736 dbgRecords.insert(dbgRecord);
737}
738
740 llvm::MDTuple *mdTuple) {
741 auto getLLVMFunction =
742 [&](const llvm::MDOperand &funcMDO) -> llvm::Function * {
743 auto *f = cast_or_null<llvm::ValueAsMetadata>(funcMDO);
744 // nullptr is a valid value for the function pointer.
745 if (!f)
746 return nullptr;
747 auto *llvmFn = cast<llvm::Function>(f->getValue()->stripPointerCasts());
748 return llvmFn;
749 };
750
751 // Each tuple element becomes one ModuleFlagCGProfileEntryAttr.
752 SmallVector<Attribute> cgProfile;
753 for (unsigned i = 0; i < mdTuple->getNumOperands(); i++) {
754 const llvm::MDOperand &mdo = mdTuple->getOperand(i);
755 auto *cgEntry = cast<llvm::MDNode>(mdo);
756 llvm::Constant *llvmConstant =
757 cast<llvm::ConstantAsMetadata>(cgEntry->getOperand(2))->getValue();
758 uint64_t count = cast<llvm::ConstantInt>(llvmConstant)->getZExtValue();
759 auto *fromFn = getLLVMFunction(cgEntry->getOperand(0));
760 auto *toFn = getLLVMFunction(cgEntry->getOperand(1));
761 // FlatSymbolRefAttr::get(mlirModule->getContext(), llvmFn->getName());
762 cgProfile.push_back(ModuleFlagCGProfileEntryAttr::get(
763 mlirModule->getContext(),
764 fromFn ? FlatSymbolRefAttr::get(mlirModule->getContext(),
765 fromFn->getName())
766 : nullptr,
767 toFn ? FlatSymbolRefAttr::get(mlirModule->getContext(), toFn->getName())
768 : nullptr,
769 count));
770 }
771 return ArrayAttr::get(mlirModule->getContext(), cgProfile);
772}
773
774/// Extract a two element `MDTuple` from a `MDOperand`. Emit a warning in case
775/// something else is found.
776static llvm::MDTuple *getTwoElementMDTuple(ModuleOp mlirModule,
777 const llvm::Module *llvmModule,
778 const llvm::MDOperand &md,
779 llvm::ModuleSlotTracker &tracker) {
780 auto *tupleEntry = dyn_cast_or_null<llvm::MDTuple>(md);
781 if (!tupleEntry || tupleEntry->getNumOperands() != 2)
782 emitWarning(mlirModule.getLoc())
783 << "expected 2-element tuple metadata: "
784 << renderMetadataWithTracker(md, tracker, llvmModule);
785 return tupleEntry;
786}
787
788/// Extract a constant metadata value from a two element tuple (<key, value>).
789/// Return nullptr if requirements are not met. A warning is emitted if the
790/// `matchKey` is different from the tuple's key.
791static llvm::ConstantAsMetadata *getConstantMDFromKeyValueTuple(
792 ModuleOp mlirModule, const llvm::Module *llvmModule,
793 const llvm::MDOperand &md, StringRef matchKey,
794 llvm::ModuleSlotTracker &tracker, bool optional = false) {
795 llvm::MDTuple *tupleEntry =
796 getTwoElementMDTuple(mlirModule, llvmModule, md, tracker);
797 if (!tupleEntry)
798 return nullptr;
799 auto *keyMD = dyn_cast<llvm::MDString>(tupleEntry->getOperand(0));
800 if (!keyMD || keyMD->getString() != matchKey) {
801 if (!optional)
802 emitWarning(mlirModule.getLoc())
803 << "expected '" << matchKey << "' key, but found: "
804 << renderMetadataWithTracker(tupleEntry->getOperand(0), tracker,
805 llvmModule);
806 return nullptr;
807 }
808
809 return dyn_cast<llvm::ConstantAsMetadata>(tupleEntry->getOperand(1));
810}
811
812/// Extract an integer value from a two element tuple (<key, value>).
813/// Fail if requirements are not met. A warning is emitted if the
814/// found value isn't a LLVM constant integer.
815static FailureOr<uint64_t>
817 const llvm::Module *llvmModule,
818 const llvm::MDOperand &md, StringRef matchKey,
819 llvm::ModuleSlotTracker &tracker) {
820 llvm::ConstantAsMetadata *valMD = getConstantMDFromKeyValueTuple(
821 mlirModule, llvmModule, md, matchKey, tracker);
822 if (!valMD)
823 return failure();
824
825 if (auto *cstInt = dyn_cast<llvm::ConstantInt>(valMD->getValue()))
826 return cstInt->getZExtValue();
827
828 emitWarning(mlirModule.getLoc())
829 << "expected integer metadata value for key '" << matchKey
830 << "': " << renderMetadataWithTracker(md, tracker, llvmModule);
831 return failure();
832}
833
834static std::optional<ProfileSummaryFormatKind>
835convertProfileSummaryFormat(ModuleOp mlirModule, const llvm::Module *llvmModule,
836 const llvm::MDOperand &formatMD,
837 llvm::ModuleSlotTracker &tracker) {
838 auto *tupleEntry =
839 getTwoElementMDTuple(mlirModule, llvmModule, formatMD, tracker);
840 if (!tupleEntry)
841 return std::nullopt;
842
843 llvm::MDString *keyMD = dyn_cast<llvm::MDString>(tupleEntry->getOperand(0));
844 if (!keyMD || keyMD->getString() != "ProfileFormat") {
845 emitWarning(mlirModule.getLoc())
846 << "expected 'ProfileFormat' key: "
847 << renderMetadataWithTracker(tupleEntry->getOperand(0), tracker,
848 llvmModule);
849 return std::nullopt;
850 }
851
852 llvm::Metadata *valueMD = tupleEntry->getOperand(1).get();
853 if (!valueMD) {
854 emitWarning(mlirModule.getLoc())
855 << "expected string metadata value for key 'ProfileFormat': null";
856 return std::nullopt;
857 }
858
859 llvm::MDString *valMD = dyn_cast<llvm::MDString>(valueMD);
860 if (!valMD) {
861 emitWarning(mlirModule.getLoc())
862 << "expected string metadata value for key 'ProfileFormat': "
863 << renderMetadataWithTracker(valueMD, tracker, llvmModule);
864 return std::nullopt;
865 }
866 std::optional<ProfileSummaryFormatKind> fmtKind =
867 symbolizeProfileSummaryFormatKind(valMD->getString());
868 if (!fmtKind) {
869 emitWarning(mlirModule.getLoc())
870 << "expected 'SampleProfile', 'InstrProf' or 'CSInstrProf' values, "
871 "but found: "
872 << renderMetadataWithTracker(valMD, tracker, llvmModule);
873 return std::nullopt;
874 }
875
876 return fmtKind;
877}
878
879static FailureOr<SmallVector<ModuleFlagProfileSummaryDetailedAttr>>
881 const llvm::Module *llvmModule,
882 const llvm::MDOperand &summaryMD,
883 llvm::ModuleSlotTracker &tracker) {
884 auto *tupleEntry =
885 getTwoElementMDTuple(mlirModule, llvmModule, summaryMD, tracker);
886 if (!tupleEntry)
887 return failure();
888
889 llvm::MDString *keyMD = dyn_cast<llvm::MDString>(tupleEntry->getOperand(0));
890 if (!keyMD || keyMD->getString() != "DetailedSummary") {
891 emitWarning(mlirModule.getLoc())
892 << "expected 'DetailedSummary' key: "
893 << renderMetadataWithTracker(tupleEntry->getOperand(0), tracker,
894 llvmModule);
895 return failure();
896 }
897
898 llvm::MDTuple *entriesMD = dyn_cast<llvm::MDTuple>(tupleEntry->getOperand(1));
899 if (!entriesMD) {
900 emitWarning(mlirModule.getLoc())
901 << "expected tuple value for 'DetailedSummary' key: "
902 << renderMetadataWithTracker(tupleEntry->getOperand(1), tracker,
903 llvmModule);
904 return failure();
905 }
906
908 for (auto &&entry : entriesMD->operands()) {
909 llvm::MDTuple *entryMD = dyn_cast<llvm::MDTuple>(entry);
910 if (!entryMD || entryMD->getNumOperands() != 3) {
911 emitWarning(mlirModule.getLoc())
912 << "'DetailedSummary' entry expects 3 operands: "
913 << renderMetadataWithTracker(entry, tracker, llvmModule);
914 return failure();
915 }
916
917 auto *op0 = dyn_cast<llvm::ConstantAsMetadata>(entryMD->getOperand(0));
918 auto *op1 = dyn_cast<llvm::ConstantAsMetadata>(entryMD->getOperand(1));
919 auto *op2 = dyn_cast<llvm::ConstantAsMetadata>(entryMD->getOperand(2));
920 if (!op0 || !op1 || !op2) {
921 emitWarning(mlirModule.getLoc())
922 << "expected only integer entries in 'DetailedSummary': "
923 << renderMetadataWithTracker(entry, tracker, llvmModule);
924 return failure();
925 }
926
927 auto detaildSummaryEntry = ModuleFlagProfileSummaryDetailedAttr::get(
928 mlirModule->getContext(),
929 cast<llvm::ConstantInt>(op0->getValue())->getZExtValue(),
930 cast<llvm::ConstantInt>(op1->getValue())->getZExtValue(),
931 cast<llvm::ConstantInt>(op2->getValue())->getZExtValue());
932 detailedSummary.push_back(detaildSummaryEntry);
933 }
934 return detailedSummary;
935}
936
938 ModuleOp mlirModule, const llvm::Module *llvmModule, llvm::MDTuple *mdTuple,
939 llvm::ModuleSlotTracker &tracker) {
940 unsigned profileNumEntries = mdTuple->getNumOperands();
941 if (profileNumEntries < 8) {
942 emitWarning(mlirModule.getLoc())
943 << "expected at 8 entries in 'ProfileSummary': "
944 << renderMetadataWithTracker(mdTuple, tracker, llvmModule);
945 return nullptr;
946 }
947
948 unsigned summayIdx = 0;
949 auto checkOptionalPosition = [&](const llvm::MDOperand &md,
950 StringRef matchKey) -> LogicalResult {
951 // Make sure we won't step over the bound of the array of summary entries.
952 // Since (non-optional) DetailedSummary always comes last, the next entry in
953 // the tuple operand array must exist.
954 if (summayIdx + 1 >= profileNumEntries) {
955 emitWarning(mlirModule.getLoc())
956 << "the last summary entry is '" << matchKey
957 << "', expected 'DetailedSummary': "
958 << renderMetadataWithTracker(md, tracker, llvmModule);
959 return failure();
960 }
961
962 return success();
963 };
964
965 auto getOptIntValue =
966 [&](const llvm::MDOperand &md,
967 StringRef matchKey) -> FailureOr<std::optional<uint64_t>> {
968 if (!getConstantMDFromKeyValueTuple(mlirModule, llvmModule, md, matchKey,
969 tracker,
970 /*optional=*/true))
971 return FailureOr<std::optional<uint64_t>>(std::nullopt);
972 if (checkOptionalPosition(md, matchKey).failed())
973 return failure();
974 FailureOr<uint64_t> val = convertInt64FromKeyValueTuple(
975 mlirModule, llvmModule, md, matchKey, tracker);
976 if (failed(val))
977 return failure();
978 return val;
979 };
980
981 auto getOptDoubleValue = [&](const llvm::MDOperand &md,
982 StringRef matchKey) -> FailureOr<FloatAttr> {
983 auto *valMD = getConstantMDFromKeyValueTuple(mlirModule, llvmModule, md,
984 matchKey, tracker,
985 /*optional=*/true);
986 if (!valMD)
987 return FloatAttr{};
988 if (auto *cstFP = dyn_cast<llvm::ConstantFP>(valMD->getValue())) {
989 if (checkOptionalPosition(md, matchKey).failed())
990 return failure();
991 return FloatAttr::get(Float64Type::get(mlirModule.getContext()),
992 cstFP->getValueAPF());
993 }
994 emitWarning(mlirModule.getLoc())
995 << "expected double metadata value for key '" << matchKey
996 << "': " << renderMetadataWithTracker(md, tracker, llvmModule);
997 return failure();
998 };
999
1000 // Build ModuleFlagProfileSummaryAttr by sequentially fetching elements in
1001 // a fixed order: format, total count, etc.
1002 std::optional<ProfileSummaryFormatKind> format = convertProfileSummaryFormat(
1003 mlirModule, llvmModule, mdTuple->getOperand(summayIdx++), tracker);
1004 if (!format.has_value())
1005 return nullptr;
1006
1007 FailureOr<uint64_t> totalCount = convertInt64FromKeyValueTuple(
1008 mlirModule, llvmModule, mdTuple->getOperand(summayIdx++), "TotalCount",
1009 tracker);
1010 if (failed(totalCount))
1011 return nullptr;
1012
1013 FailureOr<uint64_t> maxCount = convertInt64FromKeyValueTuple(
1014 mlirModule, llvmModule, mdTuple->getOperand(summayIdx++), "MaxCount",
1015 tracker);
1016 if (failed(maxCount))
1017 return nullptr;
1018
1019 FailureOr<uint64_t> maxInternalCount = convertInt64FromKeyValueTuple(
1020 mlirModule, llvmModule, mdTuple->getOperand(summayIdx++),
1021 "MaxInternalCount", tracker);
1022 if (failed(maxInternalCount))
1023 return nullptr;
1024
1025 FailureOr<uint64_t> maxFunctionCount = convertInt64FromKeyValueTuple(
1026 mlirModule, llvmModule, mdTuple->getOperand(summayIdx++),
1027 "MaxFunctionCount", tracker);
1028 if (failed(maxFunctionCount))
1029 return nullptr;
1030
1031 FailureOr<uint64_t> numCounts = convertInt64FromKeyValueTuple(
1032 mlirModule, llvmModule, mdTuple->getOperand(summayIdx++), "NumCounts",
1033 tracker);
1034 if (failed(numCounts))
1035 return nullptr;
1036
1037 FailureOr<uint64_t> numFunctions = convertInt64FromKeyValueTuple(
1038 mlirModule, llvmModule, mdTuple->getOperand(summayIdx++), "NumFunctions",
1039 tracker);
1040 if (failed(numFunctions))
1041 return nullptr;
1042
1043 // Handle optional keys.
1044 FailureOr<std::optional<uint64_t>> isPartialProfile =
1045 getOptIntValue(mdTuple->getOperand(summayIdx), "IsPartialProfile");
1046 if (failed(isPartialProfile))
1047 return nullptr;
1048 if (isPartialProfile->has_value())
1049 summayIdx++;
1050
1051 FailureOr<FloatAttr> partialProfileRatio =
1052 getOptDoubleValue(mdTuple->getOperand(summayIdx), "PartialProfileRatio");
1053 if (failed(partialProfileRatio))
1054 return nullptr;
1055 if (*partialProfileRatio)
1056 summayIdx++;
1057
1058 // Handle detailed summary.
1059 FailureOr<SmallVector<ModuleFlagProfileSummaryDetailedAttr>> detailed =
1060 convertProfileSummaryDetailed(mlirModule, llvmModule,
1061 mdTuple->getOperand(summayIdx), tracker);
1062 if (failed(detailed))
1063 return nullptr;
1064
1065 // Build the final profile summary attribute.
1066 return ModuleFlagProfileSummaryAttr::get(
1067 mlirModule->getContext(), *format, *totalCount, *maxCount,
1068 *maxInternalCount, *maxFunctionCount, *numCounts, *numFunctions,
1069 *isPartialProfile, *partialProfileRatio, *detailed);
1070}
1071
1072/// Invoke specific handlers for each known module flag value, returns nullptr
1073/// if the key is unknown or unimplemented.
1075 ModuleOp mlirModule, const llvm::Module *llvmModule, StringRef key,
1076 llvm::MDTuple *mdTuple, llvm::ModuleSlotTracker &tracker) {
1077 if (key == LLVMDialect::getModuleFlagKeyCGProfileName())
1078 return convertCGProfileModuleFlagValue(mlirModule, mdTuple);
1079 if (key == LLVMDialect::getModuleFlagKeyProfileSummaryName())
1080 return convertProfileSummaryModuleFlagValue(mlirModule, llvmModule, mdTuple,
1081 tracker);
1082 // Handle MDTuples whose operands are all MDStrings (e.g. "riscv-isa").
1083 // Convert them to ArrayAttr of StringAttrs for a lossless round-trip.
1084 Builder builder(mlirModule->getContext());
1085 SmallVector<Attribute> strings;
1086 strings.reserve(mdTuple->getNumOperands());
1087 for (const llvm::MDOperand &operand : mdTuple->operands()) {
1088 auto *mdString = dyn_cast_if_present<llvm::MDString>(operand.get());
1089 if (!mdString)
1090 return nullptr;
1091 strings.push_back(builder.getStringAttr(mdString->getString()));
1092 }
1093 return builder.getArrayAttr(strings);
1094}
1095
1098 llvmModule->getModuleFlagsMetadata(llvmModuleFlags);
1099
1100 SmallVector<Attribute> moduleFlags;
1101 for (const auto [behavior, key, val] : llvmModuleFlags) {
1102 Attribute valAttr = nullptr;
1103 if (auto *constInt = llvm::mdconst::dyn_extract<llvm::ConstantInt>(val)) {
1104 valAttr = builder.getI32IntegerAttr(constInt->getZExtValue());
1105 } else if (auto *mdString = dyn_cast<llvm::MDString>(val)) {
1106 valAttr = builder.getStringAttr(mdString->getString());
1107 } else if (auto *mdTuple = dyn_cast<llvm::MDTuple>(val)) {
1108 valAttr = convertModuleFlagValueFromMDTuple(mlirModule, llvmModule.get(),
1109 key->getString(), mdTuple,
1110 getDiagSlotTracker());
1111 }
1112
1113 if (!valAttr) {
1114 emitWarning(mlirModule.getLoc())
1115 << "unsupported module flag value for key '" << key->getString()
1116 << "' : " << renderMetadata(val);
1117 continue;
1118 }
1119
1120 moduleFlags.push_back(builder.getAttr<ModuleFlagAttr>(
1121 convertModFlagBehaviorFromLLVM(behavior),
1122 builder.getStringAttr(key->getString()), valAttr));
1123 }
1124
1125 if (!moduleFlags.empty())
1126 LLVM::ModuleFlagsOp::create(builder, mlirModule.getLoc(),
1127 builder.getArrayAttr(moduleFlags));
1128
1129 return success();
1130}
1131
1133 for (const llvm::NamedMDNode &named : llvmModule->named_metadata()) {
1134 if (named.getName() != "llvm.linker.options")
1135 continue;
1136 // llvm.linker.options operands are lists of strings.
1137 for (const llvm::MDNode *node : named.operands()) {
1139 options.reserve(node->getNumOperands());
1140 for (const llvm::MDOperand &option : node->operands())
1141 options.push_back(cast<llvm::MDString>(option)->getString());
1142 LLVM::LinkerOptionsOp::create(builder, mlirModule.getLoc(),
1143 builder.getStrArrayAttr(options));
1144 }
1145 }
1146 return success();
1147}
1148
1150 for (const llvm::NamedMDNode &named : llvmModule->named_metadata()) {
1151 if (named.getName() != "llvm.dependent-libraries")
1152 continue;
1153 SmallVector<StringRef> libraries;
1154 for (const llvm::MDNode *node : named.operands()) {
1155 if (node->getNumOperands() == 1)
1156 if (auto *mdString = dyn_cast<llvm::MDString>(node->getOperand(0)))
1157 libraries.push_back(mdString->getString());
1158 }
1159 if (!libraries.empty())
1160 mlirModule->setDiscardableAttr(
1161 LLVM::LLVMDialect::getDependentLibrariesAttrName(),
1162 builder.getStrArrayAttr(libraries));
1163 }
1164 return success();
1165}
1166
1168 for (const llvm::NamedMDNode &named : llvmModule->named_metadata()) {
1169 // llvm.ident should have a single operand. That operand is itself an
1170 // MDNode with a single string operand.
1171 if (named.getName() != LLVMDialect::getIdentAttrName())
1172 continue;
1173
1174 if (named.getNumOperands() == 1)
1175 if (auto *md = dyn_cast<llvm::MDNode>(named.getOperand(0)))
1176 if (md->getNumOperands() == 1)
1177 if (auto *mdStr = dyn_cast<llvm::MDString>(md->getOperand(0)))
1178 mlirModule->setDiscardableAttr(
1179 LLVMDialect::getIdentAttrName(),
1180 builder.getStringAttr(mdStr->getString()));
1181 }
1182 return success();
1183}
1184
1186 for (const llvm::NamedMDNode &nmd : llvmModule->named_metadata()) {
1187 // llvm.commandline should have a single operand. That operand is itself an
1188 // MDNode with a single string operand.
1189 if (nmd.getName() != LLVMDialect::getCommandlineAttrName())
1190 continue;
1191
1192 if (nmd.getNumOperands() == 1)
1193 if (auto *md = dyn_cast<llvm::MDNode>(nmd.getOperand(0)))
1194 if (md->getNumOperands() == 1)
1195 if (auto *mdStr = dyn_cast<llvm::MDString>(md->getOperand(0)))
1196 mlirModule->setDiscardableAttr(
1197 LLVMDialect::getCommandlineAttrName(),
1198 builder.getStringAttr(mdStr->getString()));
1199 }
1200 return success();
1201}
1202
1204 OpBuilder::InsertionGuard guard(builder);
1205 builder.setInsertionPointToEnd(mlirModule.getBody());
1206 for (const llvm::Function &func : llvmModule->functions()) {
1207 for (const llvm::Instruction &inst : llvm::instructions(func)) {
1208 // Convert access group metadata nodes.
1209 if (llvm::MDNode *node =
1210 inst.getMetadata(llvm::LLVMContext::MD_access_group))
1211 if (failed(processAccessGroupMetadata(node)))
1212 return failure();
1213
1214 // Convert alias analysis metadata nodes.
1215 llvm::AAMDNodes aliasAnalysisNodes = inst.getAAMetadata();
1216 if (!aliasAnalysisNodes)
1217 continue;
1218 if (aliasAnalysisNodes.TBAA)
1219 if (failed(processTBAAMetadata(aliasAnalysisNodes.TBAA)))
1220 return failure();
1221 // A `!tbaa.struct` node reaches its own tags, and those tags may appear
1222 // nowhere else in the module. Without walking them here the struct
1223 // conversion below finds nothing and the node is declined.
1224 if (aliasAnalysisNodes.TBAAStruct) {
1225 const llvm::MDNode *structNode = aliasAnalysisNodes.TBAAStruct;
1226 // Operands come in groups of three: check the count before
1227 // walking the tags. The verifier rejects malformed nodes
1228 // before CLI import, so this guards direct API use.
1229 bool wellFormed = structNode->getNumOperands() % 3 == 0;
1230 if (wellFormed) {
1231 for (unsigned i = 2, e = structNode->getNumOperands(); i < e; i += 3)
1232 if (auto *tag = dyn_cast_if_present<llvm::MDNode>(
1233 structNode->getOperand(i)))
1234 if (failed(processTBAAMetadata(tag)))
1235 return failure();
1236 }
1237 // Convert the struct node itself once its tags are in the map. A
1238 // node that cannot be modeled is recorded with a null value so it
1239 // is not converted again for every instruction carrying it, and is
1240 // declined at attach time.
1241 if (!tbaaStructMapping.contains(structNode))
1242 tbaaStructMapping.insert(
1243 {structNode, convertTBAAStructMetadata(structNode)});
1244 }
1245 if (aliasAnalysisNodes.Scope)
1246 if (failed(processAliasScopeMetadata(aliasAnalysisNodes.Scope)))
1247 return failure();
1248 if (aliasAnalysisNodes.NoAlias)
1249 if (failed(processAliasScopeMetadata(aliasAnalysisNodes.NoAlias)))
1250 return failure();
1251 }
1252 }
1253 if (failed(convertLinkerOptionsMetadata()))
1254 return failure();
1256 return failure();
1257 if (failed(convertModuleFlagsMetadata()))
1258 return failure();
1259 if (failed(convertIdentMetadata()))
1260 return failure();
1261 if (failed(convertCommandlineMetadata()))
1262 return failure();
1263 return success();
1264}
1265
1266void ModuleImport::processComdat(const llvm::Comdat *comdat) {
1267 if (comdatMapping.contains(comdat))
1268 return;
1269
1270 ComdatOp comdatOp = getGlobalComdatOp();
1271 OpBuilder::InsertionGuard guard(builder);
1272 builder.setInsertionPointToEnd(&comdatOp.getBody().back());
1273 auto selectorOp = ComdatSelectorOp::create(
1274 builder, mlirModule.getLoc(), comdat->getName(),
1275 convertComdatFromLLVM(comdat->getSelectionKind()),
1276 /*sym_visibility=*/nullptr);
1277 auto symbolRef =
1278 SymbolRefAttr::get(builder.getContext(), getGlobalComdatOpName(),
1279 FlatSymbolRefAttr::get(selectorOp.getSymNameAttr()));
1280 comdatMapping.try_emplace(comdat, symbolRef);
1281}
1282
1284 for (llvm::GlobalVariable &globalVar : llvmModule->globals())
1285 if (globalVar.hasComdat())
1286 processComdat(globalVar.getComdat());
1287 for (llvm::Function &func : llvmModule->functions())
1288 if (func.hasComdat())
1289 processComdat(func.getComdat());
1290 return success();
1291}
1292
1294 for (llvm::GlobalVariable &globalVar : llvmModule->globals()) {
1295 if (globalVar.getName() == getGlobalCtorsVarName() ||
1296 globalVar.getName() == getGlobalDtorsVarName()) {
1297 if (failed(convertGlobalCtorsAndDtors(&globalVar))) {
1298 return emitError(UnknownLoc::get(context))
1299 << "unhandled global variable: " << renderValue(globalVar);
1300 }
1301 continue;
1302 }
1303 if (failed(convertGlobal(&globalVar))) {
1304 return emitError(UnknownLoc::get(context))
1305 << "unhandled global variable: " << renderValue(globalVar);
1306 }
1307 }
1308 return success();
1309}
1310
1312 for (llvm::GlobalAlias &alias : llvmModule->aliases()) {
1313 if (failed(convertAlias(&alias))) {
1314 return emitError(UnknownLoc::get(context))
1315 << "unhandled global alias: " << renderValue(alias);
1316 }
1317 }
1318 return success();
1319}
1320
1322 for (llvm::GlobalIFunc &ifunc : llvmModule->ifuncs()) {
1323 if (failed(convertIFunc(&ifunc))) {
1324 return emitError(UnknownLoc::get(context))
1325 << "unhandled global ifunc: " << renderValue(ifunc);
1326 }
1327 }
1328 return success();
1329}
1330
1332 Location loc = mlirModule.getLoc();
1333 DataLayoutImporter dataLayoutImporter(
1334 context, llvmModule->getDataLayout().getStringRepresentation());
1335 if (!dataLayoutImporter.getDataLayoutSpec())
1336 return emitError(loc, "cannot translate data layout: ")
1337 << dataLayoutImporter.getLastToken();
1338
1339 for (StringRef token : dataLayoutImporter.getUnhandledTokens())
1340 emitWarning(loc, "unhandled data layout token: ") << token;
1341
1342 mlirModule->setDiscardableAttr(DLTIDialect::kDataLayoutAttrName,
1343 dataLayoutImporter.getDataLayoutSpec());
1344 return success();
1345}
1346
1348 mlirModule->setDiscardableAttr(
1349 LLVM::LLVMDialect::getTargetTripleAttrName(),
1350 builder.getStringAttr(llvmModule->getTargetTriple().str()));
1351}
1352
1355
1356 for (const llvm::Module::GlobalAsmFragment &Frag :
1357 llvmModule->getModuleInlineAsm()) {
1358 // TODO: Preserve module asm properties.
1359 for (llvm::StringRef line : llvm::split(Frag.Asm, '\n'))
1360 if (!line.empty())
1361 asmArrayAttr.push_back(builder.getStringAttr(line));
1362 }
1363
1364 mlirModule->setDiscardableAttr(LLVM::LLVMDialect::getModuleLevelAsmAttrName(),
1365 builder.getArrayAttr(asmArrayAttr));
1366}
1367
1369 for (llvm::Function &func : llvmModule->functions())
1370 if (failed(processFunction(&func)))
1371 return failure();
1372 return success();
1373}
1374
1375void ModuleImport::setNonDebugMetadataAttrs(llvm::Instruction *inst,
1376 Operation *op) {
1378 inst->getAllMetadataOtherThanDebugLoc(allMetadata);
1379 for (auto &[kind, node] : allMetadata) {
1380 if (!iface.isConvertibleMetadata(kind))
1381 continue;
1382 if (failed(iface.setMetadataAttrs(builder, kind, node, op, *this))) {
1383 if (emitExpensiveWarnings) {
1384 Location loc = debugImporter->translateLoc(inst->getDebugLoc());
1385 emitWarning(loc) << "unhandled metadata: " << renderMetadata(node)
1386 << " on " << renderValue(*inst);
1387 }
1388 }
1389 }
1390}
1391
1392void ModuleImport::setIntegerOverflowFlags(llvm::Instruction *inst,
1393 Operation *op) const {
1394 auto iface = cast<IntegerOverflowFlagsInterface>(op);
1395
1396 IntegerOverflowFlags value = {};
1397 value = bitEnumSet(value, IntegerOverflowFlags::nsw, inst->hasNoSignedWrap());
1398 value =
1399 bitEnumSet(value, IntegerOverflowFlags::nuw, inst->hasNoUnsignedWrap());
1400
1401 iface.setOverflowFlags(value);
1402}
1403
1404void ModuleImport::setExactFlag(llvm::Instruction *inst, Operation *op) const {
1405 auto iface = cast<ExactFlagInterface>(op);
1406
1407 iface.setIsExact(inst->isExact());
1408}
1409
1410void ModuleImport::setDisjointFlag(llvm::Instruction *inst,
1411 Operation *op) const {
1412 auto iface = cast<DisjointFlagInterface>(op);
1413 auto *instDisjoint = cast<llvm::PossiblyDisjointInst>(inst);
1414
1415 iface.setIsDisjoint(instDisjoint->isDisjoint());
1416}
1417
1418void ModuleImport::setNonNegFlag(llvm::Instruction *inst, Operation *op) const {
1419 auto iface = cast<NonNegFlagInterface>(op);
1420
1421 iface.setNonNeg(inst->hasNonNeg());
1422}
1423
1424void ModuleImport::setFastmathFlagsAttr(llvm::Instruction *inst,
1425 Operation *op) const {
1426 auto iface = cast<FastmathFlagsInterface>(op);
1427
1428 // Even if the imported operation implements the fastmath interface, the
1429 // original instruction may not have fastmath flags set. Exit if an
1430 // instruction, such as a non floating-point function call, does not have
1431 // fastmath flags.
1432 if (!isa<llvm::FPMathOperator>(inst))
1433 return;
1434 llvm::FastMathFlags flags = inst->getFastMathFlags();
1435
1436 // Set the fastmath bits flag-by-flag.
1437 FastmathFlags value = {};
1438 value = bitEnumSet(value, FastmathFlags::nnan, flags.noNaNs());
1439 value = bitEnumSet(value, FastmathFlags::ninf, flags.noInfs());
1440 value = bitEnumSet(value, FastmathFlags::nsz, flags.noSignedZeros());
1441 value = bitEnumSet(value, FastmathFlags::arcp, flags.allowReciprocal());
1442 value = bitEnumSet(value, FastmathFlags::contract, flags.allowContract());
1443 value = bitEnumSet(value, FastmathFlags::afn, flags.approxFunc());
1444 value = bitEnumSet(value, FastmathFlags::reassoc, flags.allowReassoc());
1445 FastmathFlagsAttr attr = FastmathFlagsAttr::get(builder.getContext(), value);
1446 iface.setFastmathAttr(attr);
1447}
1448
1449/// Returns `type` if it is a builtin integer or floating-point vector type that
1450/// can be used to create an attribute or nullptr otherwise. If provided,
1451/// `arrayShape` is added to the shape of the vector to create an attribute that
1452/// matches an array of vectors.
1453static Type getVectorTypeForAttr(Type type, ArrayRef<int64_t> arrayShape = {}) {
1455 return {};
1456
1457 llvm::ElementCount numElements = LLVM::getVectorNumElements(type);
1458 if (numElements.isScalable()) {
1459 emitError(UnknownLoc::get(type.getContext()))
1460 << "scalable vectors not supported";
1461 return {};
1462 }
1463
1464 // An LLVM dialect vector can only contain scalars.
1465 Type elementType = cast<VectorType>(type).getElementType();
1466 if (!elementType.isIntOrFloat())
1467 return {};
1468
1469 SmallVector<int64_t> shape(arrayShape);
1470 shape.push_back(numElements.getKnownMinValue());
1471 return VectorType::get(shape, elementType);
1472}
1473
1474Type ModuleImport::getBuiltinTypeForAttr(Type type) {
1475 if (!type)
1476 return {};
1477
1478 // Return builtin integer and floating-point types as is.
1479 if (type.isIntOrFloat())
1480 return type;
1481
1482 // Return builtin vectors of integer and floating-point types as is.
1483 if (Type vectorType = getVectorTypeForAttr(type))
1484 return vectorType;
1485
1486 // Multi-dimensional array types are converted to tensors or vectors,
1487 // depending on the innermost type being a scalar or a vector.
1488 SmallVector<int64_t> arrayShape;
1489 while (auto arrayType = dyn_cast<LLVMArrayType>(type)) {
1490 arrayShape.push_back(arrayType.getNumElements());
1491 type = arrayType.getElementType();
1492 }
1493 if (type.isIntOrFloat())
1494 return RankedTensorType::get(arrayShape, type);
1495 return getVectorTypeForAttr(type, arrayShape);
1496}
1497
1498/// Returns an integer or float attribute for the provided scalar constant
1499/// `constScalar` or nullptr if the conversion fails.
1500static TypedAttr getScalarConstantAsAttr(OpBuilder &builder,
1501 llvm::Constant *constScalar) {
1502 MLIRContext *context = builder.getContext();
1503
1504 if (constScalar->getType()->isVectorTy())
1505 return {};
1506
1507 // Convert scalar integers.
1508 if (auto *constInt = dyn_cast<llvm::ConstantInt>(constScalar)) {
1509 return builder.getIntegerAttr(
1510 IntegerType::get(context, constInt->getBitWidth()),
1511 constInt->getValue());
1512 }
1513
1514 // Convert scalar floats.
1515 if (auto *constFloat = dyn_cast<llvm::ConstantFP>(constScalar)) {
1516 llvm::Type *type = constFloat->getType();
1517 FloatType floatType =
1518 type->isBFloatTy()
1519 ? BFloat16Type::get(context)
1520 : LLVM::detail::getFloatType(context, type->getScalarSizeInBits());
1521 if (!floatType) {
1522 emitError(UnknownLoc::get(builder.getContext()))
1523 << "unexpected floating-point type";
1524 return {};
1525 }
1526 return builder.getFloatAttr(floatType, constFloat->getValueAPF());
1527 }
1528 return {};
1529}
1530
1531/// Returns an integer or float attribute array for the provided constant
1532/// sequence `constSequence` or nullptr if the conversion fails.
1533static SmallVector<Attribute>
1535 llvm::ConstantDataSequential *constSequence) {
1536 SmallVector<Attribute> elementAttrs;
1537 elementAttrs.reserve(constSequence->getNumElements());
1538 for (auto idx : llvm::seq<int64_t>(0, constSequence->getNumElements())) {
1539 llvm::Constant *constElement = constSequence->getElementAsConstant(idx);
1540 elementAttrs.push_back(getScalarConstantAsAttr(builder, constElement));
1541 }
1542 return elementAttrs;
1543}
1544
1545Attribute ModuleImport::getConstantAsAttr(llvm::Constant *constant) {
1546 // Convert scalar constants.
1547 if (Attribute scalarAttr = getScalarConstantAsAttr(builder, constant))
1548 return scalarAttr;
1549
1550 // Returns the static shape of the provided type if possible.
1551 auto getConstantShape = [&](llvm::Type *type) {
1552 return llvm::dyn_cast_if_present<ShapedType>(
1553 getBuiltinTypeForAttr(convertType(type)));
1554 };
1555
1556 // Convert constant vector splat values.
1557 if (isa<llvm::ConstantInt, llvm::ConstantFP>(constant)) {
1558 assert(constant->getType()->isVectorTy() && "expected a vector splat");
1559 auto shape = getConstantShape(constant->getType());
1560 if (!shape)
1561 return {};
1562 Attribute splatAttr =
1563 getScalarConstantAsAttr(builder, constant->getSplatValue());
1564 return SplatElementsAttr::get(shape, splatAttr);
1565 }
1566
1567 // Convert one-dimensional constant arrays or vectors that store 1/2/4/8-byte
1568 // integer or half/bfloat/float/double values.
1569 if (auto *constArray = dyn_cast<llvm::ConstantDataSequential>(constant)) {
1570 if (constArray->isString())
1571 return builder.getStringAttr(constArray->getAsString());
1572 auto shape = getConstantShape(constArray->getType());
1573 if (!shape)
1574 return {};
1575 // Convert splat constants to splat elements attributes.
1576 auto *constVector = dyn_cast<llvm::ConstantDataVector>(constant);
1577 if (constVector && constVector->isSplat()) {
1578 // A vector is guaranteed to have at least size one.
1579 Attribute splatAttr = getScalarConstantAsAttr(
1580 builder, constVector->getElementAsConstant(0));
1581 return SplatElementsAttr::get(shape, splatAttr);
1582 }
1583 // Convert non-splat constants to dense elements attributes.
1584 SmallVector<Attribute> elementAttrs =
1585 getSequenceConstantAsAttrs(builder, constArray);
1586 return DenseElementsAttr::get(shape, elementAttrs);
1587 }
1588
1589 // Convert multi-dimensional constant aggregates that store all kinds of
1590 // integer and floating-point types.
1591 if (auto *constAggregate = dyn_cast<llvm::ConstantAggregate>(constant)) {
1592 auto shape = getConstantShape(constAggregate->getType());
1593 if (!shape)
1594 return {};
1595 // Collect the aggregate elements in depths first order.
1596 SmallVector<Attribute> elementAttrs;
1597 SmallVector<llvm::Constant *> workList = {constAggregate};
1598 while (!workList.empty()) {
1599 llvm::Constant *current = workList.pop_back_val();
1600 // Append any nested aggregates in reverse order to ensure the head
1601 // element of the nested aggregates is at the back of the work list.
1602 if (auto *constAggregate = dyn_cast<llvm::ConstantAggregate>(current)) {
1603 for (auto idx :
1604 reverse(llvm::seq<int64_t>(0, constAggregate->getNumOperands())))
1605 workList.push_back(constAggregate->getAggregateElement(idx));
1606 continue;
1607 }
1608 // Append the elements of nested constant arrays or vectors that store
1609 // 1/2/4/8-byte integer or half/bfloat/float/double values.
1610 if (auto *constArray = dyn_cast<llvm::ConstantDataSequential>(current)) {
1611 SmallVector<Attribute> attrs =
1612 getSequenceConstantAsAttrs(builder, constArray);
1613 elementAttrs.append(attrs.begin(), attrs.end());
1614 continue;
1615 }
1616 // Append nested scalar constants that store all kinds of integer and
1617 // floating-point types.
1618 if (Attribute scalarAttr = getScalarConstantAsAttr(builder, current)) {
1619 elementAttrs.push_back(scalarAttr);
1620 continue;
1621 }
1622 // Bail if the aggregate contains a unsupported constant type such as a
1623 // constant expression.
1624 return {};
1625 }
1626 return DenseElementsAttr::get(shape, elementAttrs);
1627 }
1628
1629 // Convert zero aggregates.
1630 if (auto *constZero = dyn_cast<llvm::ConstantAggregateZero>(constant)) {
1631 auto shape = llvm::dyn_cast_if_present<ShapedType>(
1632 getBuiltinTypeForAttr(convertType(constZero->getType())));
1633 if (!shape)
1634 return {};
1635 // Convert zero aggregates with a static shape to splat elements attributes.
1636 Attribute splatAttr = builder.getZeroAttr(shape.getElementType());
1637 assert(splatAttr && "expected non-null zero attribute for scalar types");
1638 return SplatElementsAttr::get(shape, splatAttr);
1639 }
1640 return {};
1641}
1642
1643FlatSymbolRefAttr
1644ModuleImport::getOrCreateNamelessSymbolName(llvm::GlobalVariable *globalVar) {
1645 assert(globalVar->getName().empty() &&
1646 "expected to work with a nameless global");
1647 auto [it, success] = namelessGlobals.try_emplace(globalVar);
1648 if (!success)
1649 return it->second;
1650
1651 // Make sure the symbol name does not clash with an existing symbol.
1652 SmallString<128> globalName = SymbolTable::generateSymbolName<128>(
1654 [this](StringRef newName) { return llvmModule->getNamedValue(newName); },
1655 namelessGlobalId);
1656 auto symbolRef = FlatSymbolRefAttr::get(context, globalName);
1657 it->getSecond() = symbolRef;
1658 return symbolRef;
1659}
1660
1661OpBuilder::InsertionGuard ModuleImport::setGlobalInsertionPoint() {
1662 OpBuilder::InsertionGuard guard(builder);
1663 if (globalInsertionOp)
1664 builder.setInsertionPointAfter(globalInsertionOp);
1665 else
1666 builder.setInsertionPointToStart(mlirModule.getBody());
1667 return guard;
1668}
1669
1670LogicalResult ModuleImport::convertAlias(llvm::GlobalAlias *alias) {
1671 // Insert the alias after the last one or at the start of the module.
1672 OpBuilder::InsertionGuard guard = setGlobalInsertionPoint();
1673
1674 Type type = convertType(alias->getValueType());
1675 AliasOp aliasOp = AliasOp::create(
1676 builder, mlirModule.getLoc(), type,
1677 convertLinkageFromLLVM(alias->getLinkage()), alias->getName(),
1678 /*dsoLocal=*/alias->isDSOLocal(),
1679 convertThreadLocalModeFromLLVM(alias->getThreadLocalMode()),
1680 /*attrs=*/ArrayRef<NamedAttribute>());
1681 globalInsertionOp = aliasOp;
1682
1683 clearRegionState();
1684 Block *block = builder.createBlock(&aliasOp.getInitializerRegion());
1685 setConstantInsertionPointToStart(block);
1686 FailureOr<Value> initializer = convertConstantExpr(alias->getAliasee());
1687 if (failed(initializer))
1688 return failure();
1689 ReturnOp::create(builder, aliasOp.getLoc(), *initializer);
1690
1691 if (alias->hasAtLeastLocalUnnamedAddr())
1692 aliasOp.setUnnamedAddr(convertUnnamedAddrFromLLVM(alias->getUnnamedAddr()));
1693 aliasOp.setVisibility_(convertVisibilityFromLLVM(alias->getVisibility()));
1694
1695 return success();
1696}
1697
1698LogicalResult ModuleImport::convertIFunc(llvm::GlobalIFunc *ifunc) {
1699 OpBuilder::InsertionGuard guard = setGlobalInsertionPoint();
1700
1701 Type type = convertType(ifunc->getValueType());
1702 llvm::Constant *resolver = ifunc->getResolver();
1703 Type resolverType = convertType(resolver->getType());
1704 IFuncOp::create(builder, mlirModule.getLoc(), ifunc->getName(), type,
1705 resolver->getName(), resolverType,
1706 convertLinkageFromLLVM(ifunc->getLinkage()),
1707 ifunc->isDSOLocal(), ifunc->getAddressSpace(),
1708 convertUnnamedAddrFromLLVM(ifunc->getUnnamedAddr()),
1709 convertVisibilityFromLLVM(ifunc->getVisibility()),
1710 /*sym_visibility=*/nullptr);
1711 return success();
1712}
1713
1714/// Converts LLVM string, integer, and enum attributes into MLIR attributes,
1715/// skipping those in `attributesToSkip` and emitting a warning at `loc` for
1716/// any other unsupported attributes.
1718 Location loc, MLIRContext *context, llvm::AttributeSet attributes,
1719 ArrayRef<StringLiteral> attributesToSkip = {},
1720 ArrayRef<StringLiteral> attributePrefixesToSkip = {}) {
1721 SmallVector<Attribute> mlirAttributes;
1722 for (llvm::Attribute attr : attributes) {
1723 StringRef attrName;
1724 if (attr.isStringAttribute())
1725 attrName = attr.getKindAsString();
1726 else
1727 attrName = llvm::Attribute::getNameFromAttrKind(attr.getKindAsEnum());
1728 if (llvm::is_contained(attributesToSkip, attrName))
1729 continue;
1730
1731 auto attrNameStartsWith = [attrName](StringLiteral sl) {
1732 return attrName.starts_with(sl);
1733 };
1734 if (attributePrefixesToSkip.end() !=
1735 llvm::find_if(attributePrefixesToSkip, attrNameStartsWith))
1736 continue;
1737
1738 auto keyAttr = StringAttr::get(context, attrName);
1739 if (attr.isStringAttribute()) {
1740 StringRef val = attr.getValueAsString();
1741 if (val.empty()) {
1742 // For string attributes without values, add only the attribute name.
1743 mlirAttributes.push_back(keyAttr);
1744 continue;
1745 }
1746 // For string attributes with a value, create a [name, value] pair.
1747 mlirAttributes.push_back(
1748 ArrayAttr::get(context, {keyAttr, StringAttr::get(context, val)}));
1749 continue;
1750 }
1751 if (attr.isIntAttribute()) {
1752 // For integer attributes, convert the value to a string and create a
1753 // [name, value] pair.
1754 auto val = std::to_string(attr.getValueAsInt());
1755 mlirAttributes.push_back(
1756 ArrayAttr::get(context, {keyAttr, StringAttr::get(context, val)}));
1757 continue;
1758 }
1759 if (attr.isEnumAttribute()) {
1760 // For enum attributes, add only the attribute name.
1761 mlirAttributes.push_back(keyAttr);
1762 continue;
1763 }
1764
1765 emitWarning(loc)
1766 << "'" << attrName
1767 << "' attribute is invalid on current operation, skipping it";
1768 }
1769 return ArrayAttr::get(context, mlirAttributes);
1770}
1771
1772/// Converts LLVM attributes from `globalVar` into MLIR attributes and adds them
1773/// to `globalOp` as target-specific attributes.
1774static void processTargetSpecificAttrs(llvm::GlobalVariable *globalVar,
1775 GlobalOp globalOp) {
1776 ArrayAttr targetSpecificAttrs = convertLLVMAttributesToMLIR(
1777 globalOp.getLoc(), globalOp.getContext(), globalVar->getAttributes());
1778 if (!targetSpecificAttrs.empty())
1779 globalOp.setTargetSpecificAttrsAttr(targetSpecificAttrs);
1780}
1781
1782LogicalResult ModuleImport::convertGlobal(llvm::GlobalVariable *globalVar) {
1783 // Insert the global after the last one or at the start of the module.
1784 OpBuilder::InsertionGuard guard = setGlobalInsertionPoint();
1785
1786 Attribute valueAttr;
1787 if (globalVar->hasInitializer())
1788 valueAttr = getConstantAsAttr(globalVar->getInitializer());
1789 Type type = convertType(globalVar->getValueType());
1790
1791 uint64_t alignment = 0;
1792 llvm::MaybeAlign maybeAlign = globalVar->getAlign();
1793 if (maybeAlign.has_value()) {
1794 llvm::Align align = *maybeAlign;
1795 alignment = align.value();
1796 }
1797
1798 // Get the global expression associated with this global variable and convert
1799 // it.
1800 SmallVector<Attribute> globalExpressionAttrs;
1801 SmallVector<llvm::DIGlobalVariableExpression *> globalExpressions;
1802 globalVar->getDebugInfo(globalExpressions);
1803
1804 for (llvm::DIGlobalVariableExpression *expr : globalExpressions) {
1805 DIGlobalVariableExpressionAttr globalExpressionAttr =
1806 debugImporter->translateGlobalVariableExpression(expr);
1807 globalExpressionAttrs.push_back(globalExpressionAttr);
1808 }
1809
1810 // Workaround to support LLVM's nameless globals. MLIR, in contrast to LLVM,
1811 // always requires a symbol name.
1812 StringRef globalName = globalVar->getName();
1813 if (globalName.empty())
1814 globalName = getOrCreateNamelessSymbolName(globalVar).getValue();
1815
1816 GlobalOp globalOp = GlobalOp::create(
1817 builder, mlirModule.getLoc(), type, globalVar->isConstant(),
1818 convertLinkageFromLLVM(globalVar->getLinkage()), StringRef(globalName),
1819 valueAttr, alignment, /*addrSpace=*/globalVar->getAddressSpace(),
1820 /*dsoLocal=*/globalVar->isDSOLocal(),
1821 convertThreadLocalModeFromLLVM(globalVar->getThreadLocalMode()),
1822 /*comdat=*/SymbolRefAttr(),
1823 /*attrs=*/ArrayRef<NamedAttribute>(), /*dbgExprs=*/globalExpressionAttrs);
1824 globalInsertionOp = globalOp;
1825
1826 if (globalVar->hasInitializer() && !valueAttr) {
1827 clearRegionState();
1828 Block *block = builder.createBlock(&globalOp.getInitializerRegion());
1829 setConstantInsertionPointToStart(block);
1830 FailureOr<Value> initializer =
1831 convertConstantExpr(globalVar->getInitializer());
1832 if (failed(initializer))
1833 return failure();
1834 ReturnOp::create(builder, globalOp.getLoc(), *initializer);
1835 }
1836 if (globalVar->hasAtLeastLocalUnnamedAddr()) {
1837 globalOp.setUnnamedAddr(
1838 convertUnnamedAddrFromLLVM(globalVar->getUnnamedAddr()));
1839 }
1840 if (globalVar->hasSection())
1841 globalOp.setSection(globalVar->getSection());
1842 globalOp.setVisibility_(
1843 convertVisibilityFromLLVM(globalVar->getVisibility()));
1844
1845 if (globalVar->hasComdat())
1846 globalOp.setComdatAttr(comdatMapping.lookup(globalVar->getComdat()));
1847
1848 if (llvm::MDNode *associatedMD =
1849 globalVar->getMetadata(llvm::LLVMContext::MD_associated)) {
1850 FlatSymbolRefAttr symbolRef;
1851 if (associatedMD->getNumOperands() == 1)
1852 symbolRef =
1853 getMetadataOperandSymbolRef(associatedMD->getOperand(0).get());
1854 if (!symbolRef) {
1855 emitWarning(globalOp.getLoc())
1856 << "unhandled associated metadata: " << renderMetadata(associatedMD)
1857 << " on " << renderValue(*globalVar);
1858 } else {
1859 globalOp.setAssociatedAttr(symbolRef);
1860 }
1861 }
1862
1863 if (llvm::MDNode *absSymMD =
1864 globalVar->getMetadata(llvm::LLVMContext::MD_absolute_symbol)) {
1865 unsigned numOps = absSymMD->getNumOperands();
1866 if (numOps >= 2 && numOps % 2 == 0) {
1867 SmallVector<Attribute> rangeAttrs;
1868 rangeAttrs.reserve(numOps);
1869
1870 for (const llvm::MDOperand &op : absSymMD->operands()) {
1871 auto *constInt = llvm::mdconst::dyn_extract<llvm::ConstantInt>(op);
1872 if (!constInt)
1873 break;
1874
1875 auto intType = IntegerType::get(context, constInt->getBitWidth());
1876 rangeAttrs.push_back(IntegerAttr::get(intType, constInt->getValue()));
1877 }
1878
1879 if (rangeAttrs.size() == numOps)
1880 globalOp.setAbsoluteSymbolAttr(ArrayAttr::get(context, rangeAttrs));
1881 }
1882 }
1883
1884 processTargetSpecificAttrs(globalVar, globalOp);
1885
1886 return success();
1887}
1888
1889LogicalResult
1890ModuleImport::convertGlobalCtorsAndDtors(llvm::GlobalVariable *globalVar) {
1891 if (!globalVar->hasInitializer() || !globalVar->hasAppendingLinkage())
1892 return failure();
1893 llvm::Constant *initializer = globalVar->getInitializer();
1894
1895 bool knownInit = isa<llvm::ConstantArray>(initializer) ||
1896 isa<llvm::ConstantAggregateZero>(initializer);
1897 if (!knownInit)
1898 return failure();
1899
1900 // ConstantAggregateZero does not engage with the operand initialization
1901 // in the loop that follows - there should be no operands. This implies
1902 // empty ctor/dtor lists.
1903 if (auto *caz = dyn_cast<llvm::ConstantAggregateZero>(initializer)) {
1904 if (caz->getElementCount().getFixedValue() != 0)
1905 return failure();
1906 }
1907
1908 SmallVector<Attribute> funcs;
1909 SmallVector<int32_t> priorities;
1910 SmallVector<Attribute> dataList;
1911 for (llvm::Value *operand : initializer->operands()) {
1912 auto *aggregate = dyn_cast<llvm::ConstantAggregate>(operand);
1913 if (!aggregate || aggregate->getNumOperands() != 3)
1914 return failure();
1915
1916 auto *priority = dyn_cast<llvm::ConstantInt>(aggregate->getOperand(0));
1917 auto *func = dyn_cast<llvm::Function>(aggregate->getOperand(1));
1918 auto *data = dyn_cast<llvm::Constant>(aggregate->getOperand(2));
1919 if (!priority || !func || !data)
1920 return failure();
1921
1922 auto *gv = dyn_cast_or_null<llvm::GlobalValue>(data);
1923 Attribute dataAttr;
1924 if (gv)
1925 dataAttr = FlatSymbolRefAttr::get(context, gv->getName());
1926 else if (data->isNullValue())
1927 dataAttr = ZeroAttr::get(context);
1928 else
1929 return failure();
1930
1931 funcs.push_back(FlatSymbolRefAttr::get(context, func->getName()));
1932 priorities.push_back(priority->getValue().getZExtValue());
1933 dataList.push_back(dataAttr);
1934 }
1935
1936 // Insert the global after the last one or at the start of the module.
1937 OpBuilder::InsertionGuard guard = setGlobalInsertionPoint();
1938
1939 if (globalVar->getName() == getGlobalCtorsVarName()) {
1940 globalInsertionOp = LLVM::GlobalCtorsOp::create(
1941 builder, mlirModule.getLoc(), builder.getArrayAttr(funcs),
1942 builder.getI32ArrayAttr(priorities), builder.getArrayAttr(dataList));
1943 return success();
1944 }
1945 globalInsertionOp = LLVM::GlobalDtorsOp::create(
1946 builder, mlirModule.getLoc(), builder.getArrayAttr(funcs),
1947 builder.getI32ArrayAttr(priorities), builder.getArrayAttr(dataList));
1948 return success();
1949}
1950
1952ModuleImport::getConstantsToConvert(llvm::Constant *constant) {
1953 // Return the empty set if the constant has been translated before.
1954 if (valueMapping.contains(constant))
1955 return {};
1956
1957 // Traverse the constants in post-order and stop the traversal if a constant
1958 // already has a `valueMapping` from an earlier constant translation or if the
1959 // constant is traversed a second time.
1960 SetVector<llvm::Constant *> orderedSet;
1963 workList.insert(constant);
1964 while (!workList.empty()) {
1965 llvm::Constant *current = workList.back();
1966 // References of global objects are just pointers to the object. Avoid
1967 // walking the elements of these here.
1968 if (isa<llvm::GlobalObject>(current) || isa<llvm::GlobalAlias>(current)) {
1969 orderedSet.insert(current);
1970 workList.pop_back();
1971 continue;
1972 }
1973
1974 // Collect all dependencies of the current constant and add them to the
1975 // adjacency list if none has been computed before.
1976 auto [adjacencyIt, inserted] = adjacencyLists.try_emplace(current);
1977 if (inserted) {
1978 // Add all constant operands to the adjacency list and skip any other
1979 // values such as basic block addresses.
1980 for (llvm::Value *operand : current->operands())
1981 if (auto *constDependency = dyn_cast<llvm::Constant>(operand))
1982 adjacencyIt->getSecond().push_back(constDependency);
1983 // Use the getElementValue method to add the dependencies of zero
1984 // initialized aggregate constants since they do not take any operands.
1985 if (auto *constAgg = dyn_cast<llvm::ConstantAggregateZero>(current)) {
1986 unsigned numElements = constAgg->getElementCount().getFixedValue();
1987 for (unsigned i = 0, e = numElements; i != e; ++i)
1988 adjacencyIt->getSecond().push_back(constAgg->getElementValue(i));
1989 }
1990 }
1991 // Add the current constant to the `orderedSet` of the traversed nodes if
1992 // all its dependencies have been traversed before. Additionally, remove the
1993 // constant from the `workList` and continue the traversal.
1994 if (adjacencyIt->getSecond().empty()) {
1995 orderedSet.insert(current);
1996 workList.pop_back();
1997 continue;
1998 }
1999 // Add the next dependency from the adjacency list to the `workList` and
2000 // continue the traversal. Remove the dependency from the adjacency list to
2001 // mark that it has been processed. Only enqueue the dependency if it has no
2002 // `valueMapping` from an earlier translation and if it has not been
2003 // enqueued before.
2004 llvm::Constant *dependency = adjacencyIt->getSecond().pop_back_val();
2005 if (valueMapping.contains(dependency) || workList.contains(dependency) ||
2006 orderedSet.contains(dependency))
2007 continue;
2008 workList.insert(dependency);
2009 }
2010
2011 return orderedSet;
2012}
2013
2014FailureOr<Value> ModuleImport::convertConstant(llvm::Constant *constant) {
2015 Location loc = UnknownLoc::get(context);
2016
2017 // Convert constants that can be represented as attributes.
2018 if (Attribute attr = getConstantAsAttr(constant)) {
2019 Type type = convertType(constant->getType());
2020 if (auto symbolRef = dyn_cast<FlatSymbolRefAttr>(attr)) {
2021 return AddressOfOp::create(builder, loc, type, symbolRef.getValue())
2022 .getResult();
2023 }
2024 return ConstantOp::create(builder, loc, type, attr).getResult();
2025 }
2026
2027 // Convert null pointer constants.
2028 if (auto *nullPtr = dyn_cast<llvm::ConstantPointerNull>(constant)) {
2029 Type type = convertType(nullPtr->getType());
2030 return ZeroOp::create(builder, loc, type).getResult();
2031 }
2032
2033 // Convert none token constants.
2034 if (isa<llvm::ConstantTokenNone>(constant)) {
2035 return NoneTokenOp::create(builder, loc).getResult();
2036 }
2037
2038 // Convert poison.
2039 if (auto *poisonVal = dyn_cast<llvm::PoisonValue>(constant)) {
2040 Type type = convertType(poisonVal->getType());
2041 return PoisonOp::create(builder, loc, type).getResult();
2042 }
2043
2044 // Convert undef.
2045 if (auto *undefVal = dyn_cast<llvm::UndefValue>(constant)) {
2046 Type type = convertType(undefVal->getType());
2047 return UndefOp::create(builder, loc, type).getResult();
2048 }
2049
2050 // Convert dso_local_equivalent.
2051 if (auto *dsoLocalEquivalent = dyn_cast<llvm::DSOLocalEquivalent>(constant)) {
2052 Type type = convertType(dsoLocalEquivalent->getType());
2053 return DSOLocalEquivalentOp::create(
2054 builder, loc, type,
2056 builder.getContext(),
2057 dsoLocalEquivalent->getGlobalValue()->getName()))
2058 .getResult();
2059 }
2060
2061 // Convert global variable accesses.
2062 if (auto *globalObj = dyn_cast<llvm::GlobalObject>(constant)) {
2063 Type type = convertType(globalObj->getType());
2064 StringRef globalName = globalObj->getName();
2065 FlatSymbolRefAttr symbolRef;
2066 // Empty names are only allowed for global variables.
2067 if (globalName.empty())
2068 symbolRef =
2069 getOrCreateNamelessSymbolName(cast<llvm::GlobalVariable>(globalObj));
2070 else
2071 symbolRef = FlatSymbolRefAttr::get(context, globalName);
2072 return AddressOfOp::create(builder, loc, type, symbolRef).getResult();
2073 }
2074
2075 // Convert global alias accesses.
2076 if (auto *globalAliasObj = dyn_cast<llvm::GlobalAlias>(constant)) {
2077 Type type = convertType(globalAliasObj->getType());
2078 StringRef aliaseeName = globalAliasObj->getName();
2079 FlatSymbolRefAttr symbolRef = FlatSymbolRefAttr::get(context, aliaseeName);
2080 return AddressOfOp::create(builder, loc, type, symbolRef).getResult();
2081 }
2082
2083 // Convert constant expressions.
2084 if (auto *constExpr = dyn_cast<llvm::ConstantExpr>(constant)) {
2085 // Convert the constant expression to a temporary LLVM instruction and
2086 // translate it using the `processInstruction` method. Delete the
2087 // instruction after the translation and remove it from `valueMapping`,
2088 // since later calls to `getAsInstruction` may return the same address
2089 // resulting in a conflicting `valueMapping` entry.
2090 llvm::Instruction *inst = constExpr->getAsInstruction();
2091 llvm::scope_exit guard([&]() {
2092 assert(!noResultOpMapping.contains(inst) &&
2093 "expected constant expression to return a result");
2094 valueMapping.erase(inst);
2095 inst->deleteValue();
2096 });
2097 // Note: `processInstruction` does not call `convertConstant` recursively
2098 // since all constant dependencies have been converted before.
2099 assert(llvm::all_of(inst->operands(), [&](llvm::Value *value) {
2100 return valueMapping.contains(value);
2101 }));
2102 if (failed(processInstruction(inst)))
2103 return failure();
2104 Value result = lookupValue(inst);
2105 // getAsInstruction() does not preserve GEP `inrange`, which exists only on
2106 // constant expressions. Reattach it to the imported GEPOp.
2107 if (constExpr->getOpcode() == llvm::Instruction::GetElementPtr) {
2108 auto *gepOperator = llvm::cast<llvm::GEPOperator>(constExpr);
2109 if (std::optional<llvm::ConstantRange> inRange =
2110 gepOperator->getInRange()) {
2111 auto gepOp = result.getDefiningOp<GEPOp>();
2112 assert(gepOp && "expected GEPOp for getelementptr constexpr");
2113 // The range is not always built at the index width of the base
2114 // pointer (clang uses 32 bits for vtable address points); bring it to
2115 // that width, as the textual IR parser does.
2116 unsigned indexWidth =
2117 llvmModule->getDataLayout().getIndexTypeSizeInBits(
2118 gepOperator->getPointerOperandType());
2119 gepOp.setInrangeAttr(LLVM::ConstantRangeAttr::get(
2120 context, inRange->getLower().sextOrTrunc(indexWidth),
2121 inRange->getUpper().sextOrTrunc(indexWidth)));
2122 }
2123 }
2124 return result;
2125 }
2126
2127 // Convert zero-initialized aggregates to ZeroOp.
2128 if (auto *aggregateZero = dyn_cast<llvm::ConstantAggregateZero>(constant)) {
2129 Type type = convertType(aggregateZero->getType());
2130 return ZeroOp::create(builder, loc, type).getResult();
2131 }
2132
2133 // Convert aggregate constants.
2134 if (auto *constAgg = dyn_cast<llvm::ConstantAggregate>(constant)) {
2135 // Lookup the aggregate elements that have been converted before.
2136 SmallVector<Value> elementValues;
2137
2138 elementValues.reserve(constAgg->getNumOperands());
2139 for (llvm::Value *operand : constAgg->operands())
2140 elementValues.push_back(lookupValue(operand));
2141
2142 assert(llvm::count(elementValues, nullptr) == 0 &&
2143 "expected all elements have been converted before");
2144
2145 // Generate an UndefOp as root value and insert the aggregate elements.
2146 Type rootType = convertType(constant->getType());
2147 bool isArrayOrStruct = isa<LLVMArrayType, LLVMStructType>(rootType);
2148 assert((isArrayOrStruct || LLVM::isCompatibleVectorType(rootType)) &&
2149 "unrecognized aggregate type");
2150 Value root = UndefOp::create(builder, loc, rootType);
2151 for (const auto &it : llvm::enumerate(elementValues)) {
2152 if (isArrayOrStruct) {
2153 root =
2154 InsertValueOp::create(builder, loc, root, it.value(), it.index());
2155 } else {
2156 Attribute indexAttr = builder.getI32IntegerAttr(it.index());
2157 Value indexValue =
2158 ConstantOp::create(builder, loc, builder.getI32Type(), indexAttr);
2159 root = InsertElementOp::create(builder, loc, rootType, root, it.value(),
2160 indexValue);
2161 }
2162 }
2163 return root;
2164 }
2165
2166 if (auto *constTargetNone = dyn_cast<llvm::ConstantTargetNone>(constant)) {
2167 LLVMTargetExtType targetExtType =
2168 cast<LLVMTargetExtType>(convertType(constTargetNone->getType()));
2169 assert(targetExtType.hasProperty(LLVMTargetExtType::HasZeroInit) &&
2170 "target extension type does not support zero-initialization");
2171 // Create llvm.mlir.zero operation to represent zero-initialization of
2172 // target extension type.
2173 return LLVM::ZeroOp::create(builder, loc, targetExtType).getRes();
2174 }
2175
2176 if (auto *blockAddr = dyn_cast<llvm::BlockAddress>(constant)) {
2177 auto fnSym =
2178 FlatSymbolRefAttr::get(context, blockAddr->getFunction()->getName());
2179 auto blockTag =
2180 BlockTagAttr::get(context, blockAddr->getBasicBlock()->getNumber());
2181 return BlockAddressOp::create(
2182 builder, loc, convertType(blockAddr->getType()),
2183 BlockAddressAttr::get(context, fnSym, blockTag))
2184 .getRes();
2185 }
2186
2187 StringRef error = "";
2188
2189 if (isa<llvm::ConstantPtrAuth>(constant))
2190 error = " since ptrauth(...) is unsupported";
2191
2192 if (isa<llvm::NoCFIValue>(constant))
2193 error = " since no_cfi is unsupported";
2194
2195 if (isa<llvm::GlobalValue>(constant))
2196 error = " since global value is unsupported";
2197
2198 return emitError(loc) << "unhandled constant: " << renderValue(*constant)
2199 << error;
2200}
2201
2202FailureOr<Value> ModuleImport::convertConstantExpr(llvm::Constant *constant) {
2203 // Only call the function for constants that have not been translated before
2204 // since it updates the constant insertion point assuming the converted
2205 // constant has been introduced at the end of the constant section.
2206 assert(!valueMapping.contains(constant) &&
2207 "expected constant has not been converted before");
2208 assert(constantInsertionBlock &&
2209 "expected the constant insertion block to be non-null");
2210
2211 // Insert the constant after the last one or at the start of the entry block.
2212 OpBuilder::InsertionGuard guard(builder);
2213 if (!constantInsertionOp)
2214 builder.setInsertionPointToStart(constantInsertionBlock);
2215 else
2216 builder.setInsertionPointAfter(constantInsertionOp);
2217
2218 // Convert all constants of the expression and add them to `valueMapping`.
2219 SetVector<llvm::Constant *> constantsToConvert =
2220 getConstantsToConvert(constant);
2221 for (llvm::Constant *constantToConvert : constantsToConvert) {
2222 FailureOr<Value> converted = convertConstant(constantToConvert);
2223 if (failed(converted))
2224 return failure();
2225 mapValue(constantToConvert, *converted);
2226 }
2227
2228 // Update the constant insertion point and return the converted constant.
2229 Value result = lookupValue(constant);
2230 constantInsertionOp = result.getDefiningOp();
2231 return result;
2232}
2233
2234FailureOr<Value> ModuleImport::convertValue(llvm::Value *value) {
2235 // Return the mapped value if it has been converted before.
2236 auto it = valueMapping.find(value);
2237 if (it != valueMapping.end())
2238 return it->getSecond();
2239
2240 // `llvm::MetadataAsValue` operands (e.g. the rounding-mode / FP-exception
2241 // MDString arguments used by the constrained floating-point intrinsics, or
2242 // the named-register MDNode used by `llvm.read_register`) are lifted into a
2243 // `llvm.mlir.metadata_as_value` SSA op carrying the corresponding metadata
2244 // attribute.
2245 if (auto *mdAsVal = dyn_cast<llvm::MetadataAsValue>(value)) {
2246 llvm::Metadata *md = mdAsVal->getMetadata();
2247 Attribute mdAttr = convertMetadataToAttr(md);
2248 if (!mdAttr)
2249 return emitError(mlirModule.getLoc())
2250 << "unsupported metadata: " << renderMetadata(md);
2251 // The mapped metadata value may also be used in a sibling block.
2252 OpBuilder::InsertionGuard guard(builder);
2253 builder.setInsertionPointToStart(constantInsertionBlock);
2254 Value result =
2255 MetadataAsValueOp::create(builder, UnknownLoc::get(context), mdAttr)
2256 .getRes();
2257 mapValue(value, result);
2258 return result;
2259 }
2260
2261 // Convert constants such as immediate values that have no mapping yet.
2262 if (auto *constant = dyn_cast<llvm::Constant>(value))
2263 return convertConstantExpr(constant);
2264
2265 Location loc = UnknownLoc::get(context);
2266 if (auto *inst = dyn_cast<llvm::Instruction>(value))
2267 loc = translateLoc(inst->getDebugLoc());
2268 return emitError(loc) << "unhandled value: " << renderValue(*value);
2269}
2270
2271FailureOr<Value> ModuleImport::convertMetadataValue(llvm::Value *value) {
2272 // A value may be wrapped as metadata, for example, when passed to a debug
2273 // intrinsic. Unwrap these values before the conversion.
2274 auto *nodeAsVal = dyn_cast<llvm::MetadataAsValue>(value);
2275 if (!nodeAsVal)
2276 return failure();
2277 auto *node = dyn_cast<llvm::ValueAsMetadata>(nodeAsVal->getMetadata());
2278 if (!node)
2279 return failure();
2280 value = node->getValue();
2281
2282 // Return the mapped value if it has been converted before.
2283 auto it = valueMapping.find(value);
2284 if (it != valueMapping.end())
2285 return it->getSecond();
2286
2287 // Convert constants such as immediate values that have no mapping yet.
2288 if (auto *constant = dyn_cast<llvm::Constant>(value))
2289 return convertConstantExpr(constant);
2290 return failure();
2291}
2292
2293FailureOr<SmallVector<Value>>
2295 SmallVector<Value> remapped;
2296 remapped.reserve(values.size());
2297 for (llvm::Value *value : values) {
2298 FailureOr<Value> converted = convertValue(value);
2299 if (failed(converted))
2300 return failure();
2301 remapped.push_back(*converted);
2302 }
2303 return remapped;
2304}
2305
2306FailureOr<ModuleImport::OperandBundles>
2307ModuleImport::convertOperandBundles(ArrayRef<llvm::OperandBundleUse> bundles) {
2308 SmallVector<Value> operands;
2311 sizes.reserve(bundles.size());
2312 tags.reserve(bundles.size());
2313 for (const llvm::OperandBundleUse &bundle : bundles) {
2314 auto converted =
2315 convertValues(llvm::to_vector_of<llvm::Value *>(bundle.Inputs));
2316 if (failed(converted))
2317 return failure();
2318 llvm::append_range(operands, *converted);
2319 sizes.push_back(converted->size());
2320 tags.push_back(builder.getStringAttr(bundle.getTagName()));
2321 }
2322 return OperandBundles{std::move(operands),
2323 builder.getDenseI32ArrayAttr(sizes),
2324 builder.getArrayAttr(tags)};
2325}
2326
2329 bool requiresOpBundles, ArrayRef<unsigned> immArgPositions,
2330 ArrayRef<StringLiteral> immArgAttrNames, SmallVectorImpl<Value> &valuesOut,
2332 assert(immArgPositions.size() == immArgAttrNames.size() &&
2333 "LLVM `immArgPositions` and MLIR `immArgAttrNames` should have equal "
2334 "length");
2335
2336 SmallVector<llvm::Value *> operands(values);
2337 for (auto [immArgPos, immArgName] :
2338 llvm::zip(immArgPositions, immArgAttrNames)) {
2339 auto &value = operands[immArgPos];
2340 auto *constant = llvm::cast<llvm::Constant>(value);
2341 auto attr = getScalarConstantAsAttr(builder, constant);
2342 assert(attr && attr.getType().isIntOrFloat() &&
2343 "expected immarg to be float or integer constant");
2344 auto nameAttr = StringAttr::get(attr.getContext(), immArgName);
2345 attrsOut.push_back({nameAttr, attr});
2346 // Mark matched attribute values as null (so they can be removed below).
2347 value = nullptr;
2348 }
2349
2350 for (llvm::Value *value : operands) {
2351 if (!value)
2352 continue;
2353 auto mlirValue = convertValue(value);
2354 if (failed(mlirValue))
2355 return failure();
2356 valuesOut.push_back(*mlirValue);
2357 }
2358
2359 if (requiresOpBundles) {
2360 FailureOr<OperandBundles> bundles = convertOperandBundles(opBundles);
2361 if (failed(bundles))
2362 return failure();
2363 llvm::append_range(valuesOut, bundles->operands);
2364 attrsOut.push_back(builder.getNamedAttr(
2365 LLVMDialect::getOpBundleSizesAttrName(), bundles->sizes));
2366 attrsOut.push_back(builder.getNamedAttr(
2367 LLVMDialect::getOpBundleTagsAttrName(), bundles->tags));
2368 }
2369
2370 return success();
2371}
2372
2373IntegerAttr ModuleImport::matchIntegerAttr(llvm::Value *value) {
2374 IntegerAttr integerAttr;
2375 FailureOr<Value> converted = convertValue(value);
2376 bool success = succeeded(converted) &&
2377 matchPattern(*converted, m_Constant(&integerAttr));
2378 assert(success && "expected a constant integer value");
2379 (void)success;
2380 return integerAttr;
2381}
2382
2383FloatAttr ModuleImport::matchFloatAttr(llvm::Value *value) {
2384 FloatAttr floatAttr;
2385 FailureOr<Value> converted = convertValue(value);
2386 bool success =
2387 succeeded(converted) && matchPattern(*converted, m_Constant(&floatAttr));
2388 assert(success && "expected a constant float value");
2389 (void)success;
2390 return floatAttr;
2391}
2392
2395 llvm::DILocalVariable *node = nullptr;
2396 if (auto *value = dyn_cast<llvm::Value *>(valOrVariable)) {
2397 auto *nodeAsVal = cast<llvm::MetadataAsValue>(value);
2398 node = cast<llvm::DILocalVariable>(nodeAsVal->getMetadata());
2399 } else {
2400 node = cast<llvm::DILocalVariable *>(valOrVariable);
2401 }
2402 return debugImporter->translate(node);
2403}
2404
2405DILabelAttr ModuleImport::matchLabelAttr(llvm::Value *value) {
2406 auto *nodeAsVal = cast<llvm::MetadataAsValue>(value);
2407 auto *node = cast<llvm::DILabel>(nodeAsVal->getMetadata());
2408 return debugImporter->translate(node);
2409}
2410
2411FPExceptionBehaviorAttr
2413 auto *metadata = cast<llvm::MetadataAsValue>(value);
2414 auto *mdstr = cast<llvm::MDString>(metadata->getMetadata());
2415 std::optional<llvm::fp::ExceptionBehavior> optLLVM =
2416 llvm::convertStrToExceptionBehavior(mdstr->getString());
2417 assert(optLLVM && "Expecting FP exception behavior");
2418 return builder.getAttr<FPExceptionBehaviorAttr>(
2419 convertFPExceptionBehaviorFromLLVM(*optLLVM));
2420}
2421
2422RoundingModeAttr ModuleImport::matchRoundingModeAttr(llvm::Value *value) {
2423 auto *metadata = cast<llvm::MetadataAsValue>(value);
2424 auto *mdstr = cast<llvm::MDString>(metadata->getMetadata());
2425 std::optional<llvm::RoundingMode> optLLVM =
2426 llvm::convertStrToRoundingMode(mdstr->getString());
2427 assert(optLLVM && "Expecting rounding mode");
2428 return builder.getAttr<RoundingModeAttr>(
2429 convertRoundingModeFromLLVM(*optLLVM));
2430}
2431
2432FailureOr<SmallVector<AliasScopeAttr>>
2434 auto *nodeAsVal = cast<llvm::MetadataAsValue>(value);
2435 auto *node = cast<llvm::MDNode>(nodeAsVal->getMetadata());
2436 return lookupAliasScopeAttrs(node);
2437}
2438
2439Location ModuleImport::translateLoc(llvm::DILocation *loc) {
2440 return debugImporter->translateLoc(loc);
2441}
2442
2443LogicalResult
2444ModuleImport::convertBranchArgs(llvm::Instruction *branch,
2445 llvm::BasicBlock *target,
2446 SmallVectorImpl<Value> &blockArguments) {
2447 for (auto inst = target->begin(); isa<llvm::PHINode>(inst); ++inst) {
2448 auto *phiInst = cast<llvm::PHINode>(&*inst);
2449 llvm::Value *value = phiInst->getIncomingValueForBlock(branch->getParent());
2450 FailureOr<Value> converted = convertValue(value);
2451 if (failed(converted))
2452 return failure();
2453 blockArguments.push_back(*converted);
2454 }
2455 return success();
2456}
2457
2458FailureOr<SmallVector<Value>>
2459ModuleImport::convertCallOperands(llvm::CallBase *callInst,
2460 bool allowInlineAsm) {
2461 bool isInlineAsm = callInst->isInlineAsm();
2462 if (isInlineAsm && !allowInlineAsm)
2463 return failure();
2464
2465 SmallVector<Value> operands;
2466
2467 // Cannot use isIndirectCall() here because we need to handle Constant callees
2468 // that are not considered indirect calls by LLVM. However, in MLIR, they are
2469 // treated as indirect calls to constant operands that need to be converted.
2470 // Skip the callee operand if it's inline assembly, as it's handled separately
2471 // in InlineAsmOp.
2472 llvm::Value *calleeOperand = callInst->getCalledOperand();
2473 if (!isa<llvm::Function, llvm::GlobalIFunc>(calleeOperand) && !isInlineAsm) {
2474 FailureOr<Value> called = convertValue(calleeOperand);
2475 if (failed(called))
2476 return failure();
2477 operands.push_back(*called);
2478 }
2479
2480 SmallVector<llvm::Value *> args(callInst->args());
2481 FailureOr<SmallVector<Value>> arguments = convertValues(args);
2482 if (failed(arguments))
2483 return failure();
2484
2485 llvm::append_range(operands, *arguments);
2486 return operands;
2487}
2488
2489/// Checks if `callType` and `calleeType` are compatible and can be represented
2490/// in MLIR.
2491static LogicalResult
2492checkFunctionTypeCompatibility(LLVMFunctionType callType,
2493 LLVMFunctionType calleeType) {
2494 if (callType.getReturnType() != calleeType.getReturnType())
2495 return failure();
2496
2497 if (calleeType.isVarArg()) {
2498 // For variadic functions, the call can have more types than the callee
2499 // specifies.
2500 if (callType.getNumParams() < calleeType.getNumParams())
2501 return failure();
2502 } else {
2503 // For non-variadic functions, the number of parameters needs to be the
2504 // same.
2505 if (callType.getNumParams() != calleeType.getNumParams())
2506 return failure();
2507 }
2508
2509 // Check that all operands match.
2510 for (auto [operandType, argumentType] :
2511 llvm::zip(callType.getParams(), calleeType.getParams()))
2512 if (operandType != argumentType)
2513 return failure();
2514
2515 return success();
2516}
2517
2518FailureOr<LLVMFunctionType>
2519ModuleImport::convertFunctionType(llvm::CallBase *callInst,
2520 bool &isIncompatibleCall) {
2521 isIncompatibleCall = false;
2522 auto castOrFailure = [](Type convertedType) -> FailureOr<LLVMFunctionType> {
2523 auto funcTy = dyn_cast_or_null<LLVMFunctionType>(convertedType);
2524 if (!funcTy)
2525 return failure();
2526 return funcTy;
2527 };
2528
2529 llvm::Value *calledOperand = callInst->getCalledOperand();
2530 FailureOr<LLVMFunctionType> callType =
2531 castOrFailure(convertType(callInst->getFunctionType()));
2532 if (failed(callType))
2533 return failure();
2534 auto *callee = dyn_cast<llvm::Function>(calledOperand);
2535
2536 llvm::FunctionType *origCalleeType = nullptr;
2537 if (callee) {
2538 origCalleeType = callee->getFunctionType();
2539 } else if (auto *ifunc = dyn_cast<llvm::GlobalIFunc>(calledOperand)) {
2540 origCalleeType = cast<llvm::FunctionType>(ifunc->getValueType());
2541 }
2542
2543 // For indirect calls, return the type of the call itself.
2544 if (!origCalleeType)
2545 return callType;
2546
2547 FailureOr<LLVMFunctionType> calleeType =
2548 castOrFailure(convertType(origCalleeType));
2549 if (failed(calleeType))
2550 return failure();
2551
2552 // Compare the types and notify users via `isIncompatibleCall` if they are not
2553 // compatible.
2554 if (failed(checkFunctionTypeCompatibility(*callType, *calleeType))) {
2555 isIncompatibleCall = true;
2556 Location loc = translateLoc(callInst->getDebugLoc());
2557 emitWarning(loc) << "incompatible call and callee types: " << *callType
2558 << " and " << *calleeType;
2559 return callType;
2560 }
2561
2562 return calleeType;
2563}
2564
2565FlatSymbolRefAttr ModuleImport::convertCalleeName(llvm::CallBase *callInst) {
2566 llvm::Value *calledOperand = callInst->getCalledOperand();
2567 if (isa<llvm::Function, llvm::GlobalIFunc>(calledOperand))
2568 return SymbolRefAttr::get(context, calledOperand->getName());
2569 return {};
2570}
2571
2572LogicalResult ModuleImport::convertIntrinsic(llvm::CallInst *inst) {
2573 if (succeeded(iface.convertIntrinsic(builder, inst, *this)))
2574 return success();
2575
2576 Location loc = translateLoc(inst->getDebugLoc());
2577 return emitError(loc) << "unhandled intrinsic: " << renderValue(*inst);
2578}
2579
2581ModuleImport::convertAsmInlineOperandAttrs(const llvm::CallBase &llvmCall) {
2582 const auto *ia = cast<llvm::InlineAsm>(llvmCall.getCalledOperand());
2583 unsigned argIdx = 0;
2584 SmallVector<mlir::Attribute> opAttrs;
2585 bool hasIndirect = false;
2586
2587 for (const llvm::InlineAsm::ConstraintInfo &ci : ia->ParseConstraints()) {
2588 // Only deal with constraints that correspond to call arguments.
2589 if (ci.Type == llvm::InlineAsm::isLabel || !ci.hasArg())
2590 continue;
2591
2592 // Only increment `argIdx` in terms of constraints containing arguments,
2593 // which are guaranteed to happen in the same order of the call arguments.
2594 if (ci.isIndirect) {
2595 if (llvm::Type *paramEltType = llvmCall.getParamElementType(argIdx)) {
2596 SmallVector<mlir::NamedAttribute> attrs;
2597 attrs.push_back(builder.getNamedAttr(
2598 mlir::LLVM::InlineAsmOp::getElementTypeAttrName(),
2599 mlir::TypeAttr::get(convertType(paramEltType))));
2600 opAttrs.push_back(builder.getDictionaryAttr(attrs));
2601 hasIndirect = true;
2602 }
2603 } else {
2604 opAttrs.push_back(builder.getDictionaryAttr({}));
2605 }
2606 argIdx++;
2607 }
2608
2609 // Avoid emitting an array where all entries are empty dictionaries.
2610 return hasIndirect ? ArrayAttr::get(mlirModule->getContext(), opAttrs)
2611 : nullptr;
2612}
2613
2614LogicalResult ModuleImport::convertInstruction(llvm::Instruction *inst) {
2615 // Convert all instructions that do not provide an MLIR builder.
2616 Location loc = translateLoc(inst->getDebugLoc());
2617 if (auto *brInst = dyn_cast<llvm::UncondBrInst>(inst)) {
2618 llvm::BasicBlock *succ = brInst->getSuccessor();
2619 SmallVector<Value> blockArgs;
2620 if (failed(convertBranchArgs(brInst, succ, blockArgs)))
2621 return failure();
2622
2623 auto brOp = LLVM::BrOp::create(builder, loc, blockArgs, lookupBlock(succ));
2624 mapNoResultOp(inst, brOp);
2625 return success();
2626 }
2627 if (auto *brInst = dyn_cast<llvm::CondBrInst>(inst)) {
2628 SmallVector<Block *> succBlocks;
2629 SmallVector<SmallVector<Value>> succBlockArgs;
2630 for (auto i : llvm::seq<unsigned>(0, brInst->getNumSuccessors())) {
2631 llvm::BasicBlock *succ = brInst->getSuccessor(i);
2632 SmallVector<Value> blockArgs;
2633 if (failed(convertBranchArgs(brInst, succ, blockArgs)))
2634 return failure();
2635 succBlocks.push_back(lookupBlock(succ));
2636 succBlockArgs.push_back(blockArgs);
2637 }
2638
2639 FailureOr<Value> condition = convertValue(brInst->getCondition());
2640 if (failed(condition))
2641 return failure();
2642 auto condBrOp = LLVM::CondBrOp::create(
2643 builder, loc, *condition, succBlocks.front(), succBlockArgs.front(),
2644 succBlocks.back(), succBlockArgs.back());
2645 mapNoResultOp(inst, condBrOp);
2646 return success();
2647 }
2648 if (inst->getOpcode() == llvm::Instruction::Switch) {
2649 auto *swInst = cast<llvm::SwitchInst>(inst);
2650 // Process the condition value.
2651 FailureOr<Value> condition = convertValue(swInst->getCondition());
2652 if (failed(condition))
2653 return failure();
2654 SmallVector<Value> defaultBlockArgs;
2655 // Process the default case.
2656 llvm::BasicBlock *defaultBB = swInst->getDefaultDest();
2657 if (failed(convertBranchArgs(swInst, defaultBB, defaultBlockArgs)))
2658 return failure();
2659
2660 // Process the cases.
2661 unsigned numCases = swInst->getNumCases();
2662 SmallVector<SmallVector<Value>> caseOperands(numCases);
2663 SmallVector<ValueRange> caseOperandRefs(numCases);
2664 SmallVector<APInt> caseValues(numCases);
2665 SmallVector<Block *> caseBlocks(numCases);
2666 for (const auto &it : llvm::enumerate(swInst->cases())) {
2667 const llvm::SwitchInst::CaseHandle &caseHandle = it.value();
2668 llvm::BasicBlock *succBB = caseHandle.getCaseSuccessor();
2669 if (failed(convertBranchArgs(swInst, succBB, caseOperands[it.index()])))
2670 return failure();
2671 caseOperandRefs[it.index()] = caseOperands[it.index()];
2672 caseValues[it.index()] = caseHandle.getCaseValue()->getValue();
2673 caseBlocks[it.index()] = lookupBlock(succBB);
2674 }
2675
2676 auto switchOp = SwitchOp::create(builder, loc, *condition,
2677 lookupBlock(defaultBB), defaultBlockArgs,
2678 caseValues, caseBlocks, caseOperandRefs);
2679 mapNoResultOp(inst, switchOp);
2680 return success();
2681 }
2682 if (inst->getOpcode() == llvm::Instruction::PHI) {
2683 Type type = convertType(inst->getType());
2684 mapValue(inst, builder.getInsertionBlock()->addArgument(
2685 type, translateLoc(inst->getDebugLoc())));
2686 return success();
2687 }
2688 if (inst->getOpcode() == llvm::Instruction::Call) {
2689 auto *callInst = cast<llvm::CallInst>(inst);
2690 llvm::Value *calledOperand = callInst->getCalledOperand();
2691
2692 FailureOr<SmallVector<Value>> operands =
2693 convertCallOperands(callInst, /*allowInlineAsm=*/true);
2694 if (failed(operands))
2695 return failure();
2696
2697 auto callOp = [&]() -> FailureOr<Operation *> {
2698 if (auto *asmI = dyn_cast<llvm::InlineAsm>(calledOperand)) {
2699 if (callInst->hasOperandBundles())
2700 emitWarning(loc, "dropping operand bundles on inline assembly");
2701 Type resultTy = convertType(callInst->getType());
2702 if (!resultTy)
2703 return failure();
2704 ArrayAttr operandAttrs = convertAsmInlineOperandAttrs(*callInst);
2705 return InlineAsmOp::create(
2706 builder, loc, resultTy, *operands,
2707 builder.getStringAttr(asmI->getAsmString()),
2708 builder.getStringAttr(asmI->getConstraintString()),
2709 asmI->hasSideEffects(), asmI->isAlignStack(),
2710 convertTailCallKindFromLLVM(callInst->getTailCallKind()),
2711 callInst->hasFnAttr(llvm::Attribute::Convergent),
2712 AsmDialectAttr::get(
2713 mlirModule.getContext(),
2714 convertAsmDialectFromLLVM(asmI->getDialect())),
2715 operandAttrs,
2716 callInst->getAttributes().hasFnAttr(
2717 llvm::Attribute::StrictFP))
2718 .getOperation();
2719 }
2720 bool isIncompatibleCall;
2721 FailureOr<LLVMFunctionType> funcTy =
2722 convertFunctionType(callInst, isIncompatibleCall);
2723 if (failed(funcTy))
2724 return failure();
2725
2726 FlatSymbolRefAttr callee = nullptr;
2727 if (isIncompatibleCall) {
2728 // Use an indirect call (in order to represent valid and verifiable LLVM
2729 // IR). Build the indirect call by passing an empty `callee` operand and
2730 // insert into `operands` to include the indirect call target.
2731 FlatSymbolRefAttr calleeSym = convertCalleeName(callInst);
2732 Value indirectCallVal = LLVM::AddressOfOp::create(
2733 builder, loc, LLVM::LLVMPointerType::get(context), calleeSym);
2734 operands->insert(operands->begin(), indirectCallVal);
2735 } else {
2736 // Regular direct call using callee name.
2737 callee = convertCalleeName(callInst);
2738 }
2739 CallOp callOp = CallOp::create(builder, loc, *funcTy, callee, *operands);
2740 if (callInst->hasOperandBundles()) {
2741 FailureOr<OperandBundles> bundles =
2742 convertOperandBundles(llvm::to_vector(callInst->operand_bundles()));
2743 if (failed(bundles))
2744 return failure();
2745 callOp.getOpBundleOperandsMutable().join().assign(bundles->operands);
2746 callOp.setOpBundleSizesAttr(bundles->sizes);
2747 callOp.setOpBundleTagsAttr(bundles->tags);
2748 }
2749
2750 if (failed(convertCallAttributes(callInst, callOp)))
2751 return failure();
2752
2753 // Handle parameter and result attributes unless it's an incompatible
2754 // call.
2755 if (!isIncompatibleCall)
2756 convertArgAndResultAttrs(callInst, callOp);
2757 return callOp.getOperation();
2758 }();
2759
2760 if (failed(callOp))
2761 return failure();
2762
2763 if (!callInst->getType()->isVoidTy())
2764 mapValue(inst, (*callOp)->getResult(0));
2765 else
2766 mapNoResultOp(inst, *callOp);
2767 return success();
2768 }
2769 if (inst->getOpcode() == llvm::Instruction::LandingPad) {
2770 auto *lpInst = cast<llvm::LandingPadInst>(inst);
2771
2772 SmallVector<Value> operands;
2773 operands.reserve(lpInst->getNumClauses());
2774 for (auto i : llvm::seq<unsigned>(0, lpInst->getNumClauses())) {
2775 FailureOr<Value> operand = convertValue(lpInst->getClause(i));
2776 if (failed(operand))
2777 return failure();
2778 operands.push_back(*operand);
2779 }
2780
2781 Type type = convertType(lpInst->getType());
2782 auto lpOp =
2783 LandingpadOp::create(builder, loc, type, lpInst->isCleanup(), operands);
2784 mapValue(inst, lpOp);
2785 return success();
2786 }
2787 if (inst->getOpcode() == llvm::Instruction::Invoke) {
2788 auto *invokeInst = cast<llvm::InvokeInst>(inst);
2789
2790 if (invokeInst->isInlineAsm())
2791 return emitError(loc) << "invoke of inline assembly is not supported";
2792
2793 FailureOr<SmallVector<Value>> operands = convertCallOperands(invokeInst);
2794 if (failed(operands))
2795 return failure();
2796
2797 // Check whether the invoke result is an argument to the normal destination
2798 // block.
2799 bool invokeResultUsedInPhi = llvm::any_of(
2800 invokeInst->getNormalDest()->phis(), [&](const llvm::PHINode &phi) {
2801 return phi.getIncomingValueForBlock(invokeInst->getParent()) ==
2802 invokeInst;
2803 });
2804
2805 Block *normalDest = lookupBlock(invokeInst->getNormalDest());
2806 Block *directNormalDest = normalDest;
2807 if (invokeResultUsedInPhi) {
2808 // The invoke result cannot be an argument to the normal destination
2809 // block, as that would imply using the invoke operation result in its
2810 // definition, so we need to create a dummy block to serve as an
2811 // intermediate destination.
2812 OpBuilder::InsertionGuard g(builder);
2813 directNormalDest = builder.createBlock(normalDest);
2814 }
2815
2816 SmallVector<Value> unwindArgs;
2817 if (failed(convertBranchArgs(invokeInst, invokeInst->getUnwindDest(),
2818 unwindArgs)))
2819 return failure();
2820
2821 bool isIncompatibleInvoke;
2822 FailureOr<LLVMFunctionType> funcTy =
2823 convertFunctionType(invokeInst, isIncompatibleInvoke);
2824 if (failed(funcTy))
2825 return failure();
2826
2827 FlatSymbolRefAttr calleeName = nullptr;
2828 if (isIncompatibleInvoke) {
2829 // Use an indirect invoke (in order to represent valid and verifiable LLVM
2830 // IR). Build the indirect invoke by passing an empty `callee` operand and
2831 // insert into `operands` to include the indirect invoke target.
2832 FlatSymbolRefAttr calleeSym = convertCalleeName(invokeInst);
2833 Value indirectInvokeVal = LLVM::AddressOfOp::create(
2834 builder, loc, LLVM::LLVMPointerType::get(context), calleeSym);
2835 operands->insert(operands->begin(), indirectInvokeVal);
2836 } else {
2837 // Regular direct invoke using callee name.
2838 calleeName = convertCalleeName(invokeInst);
2839 }
2840 // Create the invoke operation. Normal destination block arguments will be
2841 // added later on to handle the case in which the operation result is
2842 // included in this list.
2843 auto invokeOp = InvokeOp::create(
2844 builder, loc, *funcTy, calleeName, *operands, directNormalDest,
2845 ValueRange(), lookupBlock(invokeInst->getUnwindDest()), unwindArgs);
2846 if (invokeInst->hasOperandBundles()) {
2847 FailureOr<OperandBundles> bundles =
2848 convertOperandBundles(llvm::to_vector(invokeInst->operand_bundles()));
2849 if (failed(bundles))
2850 return failure();
2851 invokeOp.getOpBundleOperandsMutable().join().assign(bundles->operands);
2852 invokeOp.setOpBundleSizesAttr(bundles->sizes);
2853 invokeOp.setOpBundleTagsAttr(bundles->tags);
2854 }
2855
2856 if (failed(convertInvokeAttributes(invokeInst, invokeOp)))
2857 return failure();
2858
2859 // Handle parameter and result attributes unless it's an incompatible
2860 // invoke.
2861 if (!isIncompatibleInvoke)
2862 convertArgAndResultAttrs(invokeInst, invokeOp);
2863
2864 if (!invokeInst->getType()->isVoidTy())
2865 mapValue(inst, invokeOp.getResults().front());
2866 else
2867 mapNoResultOp(inst, invokeOp);
2868
2869 SmallVector<Value> normalArgs;
2870 if (failed(convertBranchArgs(invokeInst, invokeInst->getNormalDest(),
2871 normalArgs)))
2872 return failure();
2873
2874 if (invokeResultUsedInPhi) {
2875 // The dummy normal dest block will just host an unconditional branch
2876 // instruction to the normal destination block passing the required block
2877 // arguments (including the invoke operation's result).
2878 OpBuilder::InsertionGuard g(builder);
2879 builder.setInsertionPointToStart(directNormalDest);
2880 LLVM::BrOp::create(builder, loc, normalArgs, normalDest);
2881 } else {
2882 // If the invoke operation's result is not a block argument to the normal
2883 // destination block, just add the block arguments as usual.
2884 assert(llvm::none_of(
2885 normalArgs,
2886 [&](Value val) { return val.getDefiningOp() == invokeOp; }) &&
2887 "An llvm.invoke operation cannot pass its result as a block "
2888 "argument.");
2889 invokeOp.getNormalDestOperandsMutable().append(normalArgs);
2890 }
2891
2892 return success();
2893 }
2894 if (inst->getOpcode() == llvm::Instruction::GetElementPtr) {
2895 auto *gepInst = cast<llvm::GetElementPtrInst>(inst);
2896 Type sourceElementType = convertType(gepInst->getSourceElementType());
2897 FailureOr<Value> basePtr = convertValue(gepInst->getOperand(0));
2898 if (failed(basePtr))
2899 return failure();
2900
2901 // Treat every indices as dynamic since GEPOp::build will refine those
2902 // indices into static attributes later. One small downside of this
2903 // approach is that many unused `llvm.mlir.constant` would be emitted
2904 // at first place.
2905 SmallVector<GEPArg> indices;
2906 for (llvm::Value *operand : llvm::drop_begin(gepInst->operand_values())) {
2907 FailureOr<Value> index = convertValue(operand);
2908 if (failed(index))
2909 return failure();
2910 indices.push_back(*index);
2911 }
2912
2913 Type type = convertType(inst->getType());
2914 auto gepOp = GEPOp::create(
2915 builder, loc, type, sourceElementType, *basePtr, indices,
2916 static_cast<GEPNoWrapFlags>(gepInst->getNoWrapFlags().getRaw()));
2917 mapValue(inst, gepOp);
2918 return success();
2919 }
2920
2921 if (inst->getOpcode() == llvm::Instruction::IndirectBr) {
2922 auto *indBrInst = cast<llvm::IndirectBrInst>(inst);
2923
2924 FailureOr<Value> basePtr = convertValue(indBrInst->getAddress());
2925 if (failed(basePtr))
2926 return failure();
2927
2928 SmallVector<Block *> succBlocks;
2929 SmallVector<SmallVector<Value>> succBlockArgs;
2930 for (auto i : llvm::seq<unsigned>(0, indBrInst->getNumSuccessors())) {
2931 llvm::BasicBlock *succ = indBrInst->getSuccessor(i);
2932 SmallVector<Value> blockArgs;
2933 if (failed(convertBranchArgs(indBrInst, succ, blockArgs)))
2934 return failure();
2935 succBlocks.push_back(lookupBlock(succ));
2936 succBlockArgs.push_back(blockArgs);
2937 }
2938 SmallVector<ValueRange> succBlockArgsRange =
2939 llvm::to_vector_of<ValueRange>(succBlockArgs);
2940 Location loc = translateLoc(inst->getDebugLoc());
2941 auto indBrOp = LLVM::IndirectBrOp::create(builder, loc, *basePtr,
2942 succBlockArgsRange, succBlocks);
2943
2944 mapNoResultOp(inst, indBrOp);
2945 return success();
2946 }
2947
2948 // Convert all instructions that have an mlirBuilder.
2949 if (succeeded(convertInstructionImpl(builder, inst, *this, iface)))
2950 return success();
2951
2952 return emitError(loc) << "unhandled instruction: " << renderValue(*inst);
2953}
2954
2955LogicalResult ModuleImport::processInstruction(llvm::Instruction *inst) {
2956 // FIXME: Support uses of SubtargetData.
2957 // FIXME: Add support for call / operand attributes.
2958 // FIXME: Add support for the cleanupret, catchret, catchswitch, callbr,
2959 // vaarg, catchpad, cleanuppad instructions.
2960
2961 // Convert LLVM intrinsics calls to MLIR intrinsics.
2962 if (auto *intrinsic = dyn_cast<llvm::IntrinsicInst>(inst))
2963 return convertIntrinsic(intrinsic);
2964
2965 // Process debug records attached to this instruction. Debug variable records
2966 // are stored for later processing after all SSA values are converted, while
2967 // debug label records can be converted immediately.
2968 if (inst->getDbgMarker()) {
2969 for (llvm::DbgRecord &dbgRecord :
2970 inst->getDbgMarker()->getDbgRecordRange()) {
2971 // Store debug variable records for later processing.
2972 if (auto *dbgVariableRecord =
2973 dyn_cast<llvm::DbgVariableRecord>(&dbgRecord)) {
2974 addDebugRecord(dbgVariableRecord);
2975 continue;
2976 }
2977 Location loc = translateLoc(dbgRecord.getDebugLoc());
2978 auto emitUnsupportedWarning = [&]() -> LogicalResult {
2979 if (!emitExpensiveWarnings)
2980 return success();
2981 std::string options;
2982 llvm::raw_string_ostream optionsStream(options);
2983 dbgRecord.print(optionsStream);
2984 emitWarning(loc) << "unhandled debug record " << optionsStream.str();
2985 return success();
2986 };
2987 // Convert the debug label records in-place.
2988 if (auto *dbgLabelRecord = dyn_cast<llvm::DbgLabelRecord>(&dbgRecord)) {
2989 DILabelAttr labelAttr =
2990 debugImporter->translate(dbgLabelRecord->getLabel());
2991 if (!labelAttr)
2992 return emitUnsupportedWarning();
2993 LLVM::DbgLabelOp::create(builder, loc, labelAttr);
2994 continue;
2995 }
2996 // Warn if an unsupported debug record is encountered.
2997 return emitUnsupportedWarning();
2998 }
2999 }
3000
3001 // Convert all remaining LLVM instructions to MLIR operations.
3002 return convertInstruction(inst);
3003}
3004
3005FlatSymbolRefAttr ModuleImport::getPersonalityAsAttr(llvm::Function *f) {
3006 if (!f->hasPersonalityFn())
3007 return nullptr;
3008
3009 llvm::Constant *pf = f->getPersonalityFn();
3010
3011 // If it directly has a name, we can use it.
3012 if (pf->hasName())
3013 return SymbolRefAttr::get(builder.getContext(), pf->getName());
3014
3015 // If it doesn't have a name, currently, only function pointers that are
3016 // bitcast to i8* are parsed.
3017 if (auto *ce = dyn_cast<llvm::ConstantExpr>(pf)) {
3018 if (ce->getOpcode() == llvm::Instruction::BitCast &&
3019 ce->getType() == llvm::PointerType::getUnqual(f->getContext())) {
3020 if (auto *func = dyn_cast<llvm::Function>(ce->getOperand(0)))
3021 return SymbolRefAttr::get(builder.getContext(), func->getName());
3022 }
3023 }
3024 return FlatSymbolRefAttr();
3025}
3026
3027static void processMemoryEffects(llvm::Function *func, LLVMFuncOp funcOp) {
3028 llvm::MemoryEffects memEffects = func->getMemoryEffects();
3029
3030 auto othermem = convertModRefInfoFromLLVM(
3031 memEffects.getModRef(llvm::MemoryEffects::Location::Other));
3032 auto argMem = convertModRefInfoFromLLVM(
3033 memEffects.getModRef(llvm::MemoryEffects::Location::ArgMem));
3034 auto inaccessibleMem = convertModRefInfoFromLLVM(
3035 memEffects.getModRef(llvm::MemoryEffects::Location::InaccessibleMem));
3036 auto errnoMem = convertModRefInfoFromLLVM(
3037 memEffects.getModRef(llvm::MemoryEffects::Location::ErrnoMem));
3038 auto targetMem0 = convertModRefInfoFromLLVM(
3039 memEffects.getModRef(llvm::MemoryEffects::Location::TargetMem0));
3040 auto targetMem1 = convertModRefInfoFromLLVM(
3041 memEffects.getModRef(llvm::MemoryEffects::Location::TargetMem1));
3042 auto memAttr =
3043 MemoryEffectsAttr::get(funcOp.getContext(), othermem, argMem,
3044 inaccessibleMem, errnoMem, targetMem0, targetMem1);
3045 // Only set the attr when it does not match the default value.
3046 if (memAttr.isReadWrite())
3047 return;
3048 funcOp.setMemoryEffectsAttr(memAttr);
3049}
3050
3051static void processDenormalFPEnv(llvm::Function *func, LLVMFuncOp funcOp) {
3052 llvm::DenormalFPEnv denormalFpEnv = func->getDenormalFPEnv();
3053 // Only set the attr when it does not match the default value.
3054 if (denormalFpEnv == llvm::DenormalFPEnv::getDefault())
3055 return;
3056
3057 llvm::DenormalMode defaultMode = denormalFpEnv.DefaultMode;
3058 llvm::DenormalMode floatMode = denormalFpEnv.F32Mode;
3059
3060 auto denormalFpEnvAttr = DenormalFPEnvAttr::get(
3061 funcOp.getContext(), convertDenormalModeKindFromLLVM(defaultMode.Output),
3062 convertDenormalModeKindFromLLVM(defaultMode.Input),
3063 convertDenormalModeKindFromLLVM(floatMode.Output),
3064 convertDenormalModeKindFromLLVM(floatMode.Input));
3065 funcOp.setDenormalFpenvAttr(denormalFpEnvAttr);
3066}
3067
3068// List of LLVM IR attributes that map to an explicit attribute on the MLIR
3069// LLVMFuncOp.
3070static constexpr std::array kExplicitLLVMFuncOpAttributes{
3071 StringLiteral("aarch64_in_za"),
3072 StringLiteral("aarch64_inout_za"),
3073 StringLiteral("aarch64_new_za"),
3074 StringLiteral("aarch64_out_za"),
3075 StringLiteral("aarch64_preserves_za"),
3076 StringLiteral("aarch64_pstate_sm_body"),
3077 StringLiteral("aarch64_pstate_sm_compatible"),
3078 StringLiteral("aarch64_pstate_sm_enabled"),
3079 StringLiteral("allocsize"),
3080 StringLiteral("alwaysinline"),
3081 StringLiteral("cold"),
3082 StringLiteral("convergent"),
3083 StringLiteral("disable-tail-calls"),
3084 StringLiteral("fp-contract"),
3085 StringLiteral("frame-pointer"),
3086 StringLiteral("hot"),
3087 StringLiteral("inlinehint"),
3088 StringLiteral("instrument-function-entry"),
3089 StringLiteral("instrument-function-exit"),
3090 StringLiteral("modular-format"),
3091 StringLiteral("memory"),
3092 StringLiteral("minsize"),
3093 StringLiteral("no_caller_saved_registers"),
3094 StringLiteral("no-signed-zeros-fp-math"),
3095 StringLiteral("no-builtins"),
3096 StringLiteral("nocallback"),
3097 StringLiteral("noduplicate"),
3098 StringLiteral("noinline"),
3099 StringLiteral("noreturn"),
3100 StringLiteral("nounwind"),
3101 StringLiteral("optnone"),
3102 StringLiteral("optsize"),
3103 StringLiteral("returns_twice"),
3104 StringLiteral("save-reg-params"),
3105 StringLiteral("strictfp"),
3106 StringLiteral("target-features"),
3107 StringLiteral("trap-func-name"),
3108 StringLiteral("sample-profile-suffix-elision-policy"),
3109 StringLiteral("tune-cpu"),
3110 StringLiteral("uniform-work-group-size"),
3111 StringLiteral("uwtable"),
3112 StringLiteral("vscale_range"),
3113 StringLiteral("willreturn"),
3114 StringLiteral("zero-call-used-regs"),
3115 StringLiteral("denormal_fpenv"),
3116};
3117
3118// List of LLVM IR attributes that are handled by prefix to map onto an MLIR
3119// LLVMFuncOp.
3120static constexpr std::array kExplicitLLVMFuncOpAttributePrefixes{
3121 StringLiteral("no-builtin-"),
3122};
3123
3124template <typename OpTy>
3126 const llvm::AttributeSet &attrs,
3127 OpTy target) {
3128 // 'no-builtins' is the complete collection, and overrides all the rest.
3129 if (attrs.hasAttribute("no-builtins")) {
3130 target.setNobuiltinsAttr(ArrayAttr::get(ctx, {}));
3131 return;
3132 }
3133
3135 for (llvm::Attribute attr : attrs) {
3136 // Attributes that are part of llvm directly (that is, have an AttributeKind
3137 // in the enum) shouldn't be checked.
3138 if (attr.hasKindAsEnum())
3139 continue;
3140
3141 StringRef val = attr.getKindAsString();
3142
3143 if (val.starts_with("no-builtin-"))
3144 nbAttrs.insert(
3145 StringAttr::get(ctx, val.drop_front(sizeof("no-builtin-") - 1)));
3146 }
3147
3148 if (!nbAttrs.empty())
3149 target.setNobuiltinsAttr(ArrayAttr::get(ctx, nbAttrs.getArrayRef()));
3150}
3151
3152template <typename OpTy>
3154 const llvm::AttributeSet &attrs, OpTy target) {
3155 llvm::Attribute attr = attrs.getAttribute(llvm::Attribute::AllocSize);
3156 if (!attr.isValid())
3157 return;
3158
3159 auto [elemSize, numElems] = attr.getAllocSizeArgs();
3160 if (numElems) {
3161 target.setAllocsizeAttr(
3162 DenseI32ArrayAttr::get(ctx, {static_cast<int32_t>(elemSize),
3163 static_cast<int32_t>(*numElems)}));
3164 } else {
3165 target.setAllocsizeAttr(
3166 DenseI32ArrayAttr::get(ctx, {static_cast<int32_t>(elemSize)}));
3167 }
3168}
3169
3170/// Converts LLVM attributes from `func` into MLIR attributes and adds them
3171/// to `funcOp` as passthrough attributes, skipping those listed in
3172/// `kExplicitLLVMFuncAttributes`.
3173static void processPassthroughAttrs(llvm::Function *func, LLVMFuncOp funcOp) {
3174 llvm::AttributeSet funcAttrs = func->getAttributes().getAttributes(
3175 llvm::AttributeList::AttrIndex::FunctionIndex);
3176 ArrayAttr passthroughAttr = convertLLVMAttributesToMLIR(
3177 funcOp.getLoc(), funcOp.getContext(), funcAttrs,
3179 if (!passthroughAttr.empty())
3180 funcOp.setPassthroughAttr(passthroughAttr);
3181}
3182
3184 LLVMFuncOp funcOp) {
3185 processMemoryEffects(func, funcOp);
3186 processDenormalFPEnv(func, funcOp);
3188
3189 if (func->hasFnAttribute(llvm::Attribute::NoInline))
3190 funcOp.setNoInline(true);
3191 if (func->hasFnAttribute(llvm::Attribute::AlwaysInline))
3192 funcOp.setAlwaysInline(true);
3193 if (func->hasFnAttribute(llvm::Attribute::InlineHint))
3194 funcOp.setInlineHint(true);
3195 if (func->hasFnAttribute(llvm::Attribute::OptimizeNone))
3196 funcOp.setOptimizeNone(true);
3197 if (func->hasFnAttribute(llvm::Attribute::Convergent))
3198 funcOp.setConvergent(true);
3199 if (func->hasFnAttribute(llvm::Attribute::NoUnwind))
3200 funcOp.setNoUnwind(true);
3201 if (func->hasFnAttribute(llvm::Attribute::WillReturn))
3202 funcOp.setWillReturn(true);
3203 if (func->hasFnAttribute(llvm::Attribute::StrictFP))
3204 funcOp.setStrictfp(true);
3205 if (func->hasFnAttribute(llvm::Attribute::NoReturn))
3206 funcOp.setNoreturn(true);
3207 if (func->hasFnAttribute(llvm::Attribute::OptimizeForSize))
3208 funcOp.setOptsize(true);
3209 if (func->hasFnAttribute("save-reg-params"))
3210 funcOp.setSaveRegParams(true);
3211 if (func->hasFnAttribute("uniform-work-group-size"))
3212 funcOp.setUniformWorkGroupSize(true);
3213 if (func->hasFnAttribute(llvm::Attribute::MinSize))
3214 funcOp.setMinsize(true);
3215 if (func->hasFnAttribute(llvm::Attribute::ReturnsTwice))
3216 funcOp.setReturnsTwice(true);
3217 if (func->hasFnAttribute(llvm::Attribute::Cold))
3218 funcOp.setCold(true);
3219 if (func->hasFnAttribute(llvm::Attribute::Hot))
3220 funcOp.setHot(true);
3221 if (func->hasFnAttribute(llvm::Attribute::NoDuplicate))
3222 funcOp.setNoduplicate(true);
3223 if (func->hasFnAttribute("no_caller_saved_registers"))
3224 funcOp.setNoCallerSavedRegisters(true);
3225 if (func->hasFnAttribute(llvm::Attribute::NoCallback))
3226 funcOp.setNocallback(true);
3227 if (llvm::Attribute attr = func->getFnAttribute("modular-format");
3228 attr.isStringAttribute())
3229 funcOp.setModularFormat(StringAttr::get(context, attr.getValueAsString()));
3230 if (llvm::Attribute attr = func->getFnAttribute("zero-call-used-regs");
3231 attr.isStringAttribute())
3232 funcOp.setZeroCallUsedRegsAttr(
3233 StringAttr::get(context, attr.getValueAsString()));
3234
3235 if (func->hasFnAttribute("aarch64_pstate_sm_enabled"))
3236 funcOp.setArmStreaming(true);
3237 else if (func->hasFnAttribute("aarch64_pstate_sm_body"))
3238 funcOp.setArmLocallyStreaming(true);
3239 else if (func->hasFnAttribute("aarch64_pstate_sm_compatible"))
3240 funcOp.setArmStreamingCompatible(true);
3241
3242 if (func->hasFnAttribute("aarch64_new_za"))
3243 funcOp.setArmNewZa(true);
3244 else if (func->hasFnAttribute("aarch64_in_za"))
3245 funcOp.setArmInZa(true);
3246 else if (func->hasFnAttribute("aarch64_out_za"))
3247 funcOp.setArmOutZa(true);
3248 else if (func->hasFnAttribute("aarch64_inout_za"))
3249 funcOp.setArmInoutZa(true);
3250 else if (func->hasFnAttribute("aarch64_preserves_za"))
3251 funcOp.setArmPreservesZa(true);
3252
3253 convertNoBuiltinAttrs(context, func->getAttributes().getFnAttrs(), funcOp);
3254 convertAllocsizeAttr(context, func->getAttributes().getFnAttrs(), funcOp);
3255
3256 llvm::Attribute attr = func->getFnAttribute(llvm::Attribute::VScaleRange);
3257 if (attr.isValid()) {
3258 MLIRContext *context = funcOp.getContext();
3259 auto intTy = IntegerType::get(context, 32);
3260 funcOp.setVscaleRangeAttr(LLVM::VScaleRangeAttr::get(
3261 context, IntegerAttr::get(intTy, attr.getVScaleRangeMin()),
3262 IntegerAttr::get(intTy, attr.getVScaleRangeMax().value_or(0))));
3263 }
3264
3265 // Process frame-pointer attribute.
3266 if (func->hasFnAttribute("frame-pointer")) {
3267 StringRef stringRefFramePointerKind =
3268 func->getFnAttribute("frame-pointer").getValueAsString();
3269 funcOp.setFramePointerAttr(LLVM::FramePointerKindAttr::get(
3270 funcOp.getContext(), LLVM::framePointerKind::symbolizeFramePointerKind(
3271 stringRefFramePointerKind)
3272 .value()));
3273 }
3274
3275 if (func->hasFnAttribute("use-sample-profile"))
3276 funcOp.setUseSampleProfile(true);
3277
3278 if (llvm::Attribute attr = func->getFnAttribute("disable-tail-calls");
3279 attr.isStringAttribute()) {
3280 StringRef val = attr.getValueAsString();
3281 if (val == "true")
3282 funcOp.setDisableTailCalls(true);
3283 else if (val != "false")
3284 emitError(funcOp.getLoc())
3285 << "unknown value '" << val << "' for 'disable-tail-calls' attribute";
3286 }
3287
3288 if (llvm::Attribute attr =
3289 func->getFnAttribute("sample-profile-suffix-elision-policy");
3290 attr.isStringAttribute())
3291 funcOp.setSampleProfileSuffixElisionPolicy(
3292 StringAttr::get(context, attr.getValueAsString()));
3293
3294 if (llvm::Attribute attr = func->getFnAttribute("target-cpu");
3295 attr.isStringAttribute())
3296 funcOp.setTargetCpuAttr(StringAttr::get(context, attr.getValueAsString()));
3297
3298 if (llvm::Attribute attr = func->getFnAttribute("tune-cpu");
3299 attr.isStringAttribute())
3300 funcOp.setTuneCpuAttr(StringAttr::get(context, attr.getValueAsString()));
3301
3302 if (llvm::Attribute attr = func->getFnAttribute("target-features");
3303 attr.isStringAttribute())
3304 funcOp.setTargetFeaturesAttr(
3305 LLVM::TargetFeaturesAttr::get(context, attr.getValueAsString()));
3306
3307 if (llvm::Attribute attr = func->getFnAttribute("reciprocal-estimates");
3308 attr.isStringAttribute())
3309 funcOp.setReciprocalEstimatesAttr(
3310 StringAttr::get(context, attr.getValueAsString()));
3311
3312 if (llvm::Attribute attr = func->getFnAttribute("prefer-vector-width");
3313 attr.isStringAttribute())
3314 funcOp.setPreferVectorWidth(attr.getValueAsString());
3315
3316 if (llvm::Attribute attr = func->getFnAttribute("instrument-function-entry");
3317 attr.isStringAttribute())
3318 funcOp.setInstrumentFunctionEntry(
3319 StringAttr::get(context, attr.getValueAsString()));
3320
3321 if (llvm::Attribute attr = func->getFnAttribute("instrument-function-exit");
3322 attr.isStringAttribute())
3323 funcOp.setInstrumentFunctionExit(
3324 StringAttr::get(context, attr.getValueAsString()));
3325
3326 if (llvm::Attribute attr = func->getFnAttribute("no-signed-zeros-fp-math");
3327 attr.isStringAttribute())
3328 funcOp.setNoSignedZerosFpMath(attr.getValueAsBool());
3329
3330 if (llvm::Attribute attr = func->getFnAttribute("fp-contract");
3331 attr.isStringAttribute())
3332 funcOp.setFpContractAttr(StringAttr::get(context, attr.getValueAsString()));
3333
3334 if (func->hasUWTable()) {
3335 ::llvm::UWTableKind uwtableKind = func->getUWTableKind();
3336 funcOp.setUwtableKindAttr(LLVM::UWTableKindAttr::get(
3337 funcOp.getContext(), convertUWTableKindFromLLVM(uwtableKind)));
3338 }
3339}
3340
3341DictionaryAttr
3342ModuleImport::convertArgOrResultAttrSet(llvm::AttributeSet llvmAttrSet) {
3343 SmallVector<NamedAttribute> paramAttrs;
3344 for (auto [llvmKind, mlirName] : getAttrKindToNameMapping()) {
3345 auto llvmAttr = llvmAttrSet.getAttribute(llvmKind);
3346 // Skip attributes that are not attached.
3347 if (!llvmAttr.isValid())
3348 continue;
3349
3350 // TODO: Import captures(none) as a nocapture unit attribute until the
3351 // LLVM dialect switches to the captures representation.
3352 if (llvmAttr.hasKindAsEnum() &&
3353 llvmAttr.getKindAsEnum() == llvm::Attribute::Captures) {
3354 if (llvm::capturesNothing(llvmAttr.getCaptureInfo()))
3355 paramAttrs.push_back(
3356 builder.getNamedAttr(mlirName, builder.getUnitAttr()));
3357 continue;
3358 }
3359
3360 Attribute mlirAttr;
3361 if (llvmAttr.isTypeAttribute())
3362 mlirAttr = TypeAttr::get(convertType(llvmAttr.getValueAsType()));
3363 else if (llvmAttr.isIntAttribute())
3364 mlirAttr = builder.getI64IntegerAttr(llvmAttr.getValueAsInt());
3365 else if (llvmAttr.isEnumAttribute())
3366 mlirAttr = builder.getUnitAttr();
3367 else if (llvmAttr.isConstantRangeAttribute()) {
3368 const llvm::ConstantRange &value = llvmAttr.getValueAsConstantRange();
3369 mlirAttr = builder.getAttr<LLVM::ConstantRangeAttr>(value.getLower(),
3370 value.getUpper());
3371 } else {
3372 llvm_unreachable("unexpected parameter attribute kind");
3373 }
3374 paramAttrs.push_back(builder.getNamedAttr(mlirName, mlirAttr));
3375 }
3376
3377 return builder.getDictionaryAttr(paramAttrs);
3378}
3379
3380void ModuleImport::convertArgAndResultAttrs(llvm::Function *func,
3381 LLVMFuncOp funcOp) {
3382 auto llvmAttrs = func->getAttributes();
3383 for (size_t i = 0, e = funcOp.getNumArguments(); i < e; ++i) {
3384 llvm::AttributeSet llvmArgAttrs = llvmAttrs.getParamAttrs(i);
3385 funcOp.setArgAttrs(i, convertArgOrResultAttrSet(llvmArgAttrs));
3386 }
3387 // Convert the result attributes and attach them wrapped in an ArrayAttribute
3388 // to the funcOp.
3389 llvm::AttributeSet llvmResAttr = llvmAttrs.getRetAttrs();
3390 if (!llvmResAttr.hasAttributes())
3391 return;
3392 funcOp.setResAttrsAttr(
3393 builder.getArrayAttr({convertArgOrResultAttrSet(llvmResAttr)}));
3394}
3395
3397 llvm::CallBase *call, ArgAndResultAttrsOpInterface attrsOp,
3398 ArrayRef<unsigned> immArgPositions) {
3399 // Compute the set of immediate argument positions.
3400 llvm::SmallDenseSet<unsigned> immArgPositionsSet(immArgPositions.begin(),
3401 immArgPositions.end());
3402 // Convert the argument attributes and filter out immediate arguments.
3403 llvm::AttributeList llvmAttrs = call->getAttributes();
3404 SmallVector<llvm::AttributeSet> llvmArgAttrsSet;
3405 bool anyArgAttrs = false;
3406 for (size_t i = 0, e = call->arg_size(); i < e; ++i) {
3407 // Skip immediate arguments.
3408 if (immArgPositionsSet.contains(i))
3409 continue;
3410 llvmArgAttrsSet.emplace_back(llvmAttrs.getParamAttrs(i));
3411 if (llvmArgAttrsSet.back().hasAttributes())
3412 anyArgAttrs = true;
3413 }
3414 auto getArrayAttr = [&](ArrayRef<DictionaryAttr> dictAttrs) {
3416 for (auto &dict : dictAttrs)
3417 attrs.push_back(dict ? dict : builder.getDictionaryAttr({}));
3418 return builder.getArrayAttr(attrs);
3419 };
3420 if (anyArgAttrs) {
3422 for (auto &llvmArgAttrs : llvmArgAttrsSet)
3423 argAttrs.emplace_back(convertArgOrResultAttrSet(llvmArgAttrs));
3424 attrsOp.setArgAttrsAttr(getArrayAttr(argAttrs));
3425 }
3426
3427 // Convert the result attributes.
3428 llvm::AttributeSet llvmResAttr = llvmAttrs.getRetAttrs();
3429 if (!llvmResAttr.hasAttributes())
3430 return;
3431 DictionaryAttr resAttrs = convertArgOrResultAttrSet(llvmResAttr);
3432 attrsOp.setResAttrsAttr(getArrayAttr({resAttrs}));
3433}
3434
3435template <typename Op>
3436static LogicalResult convertCallBaseAttributes(llvm::CallBase *inst, Op op) {
3437 op.setCConv(convertCConvFromLLVM(inst->getCallingConv()));
3438 op.setStrictfp(inst->getAttributes().hasFnAttr(llvm::Attribute::StrictFP));
3439 return success();
3440}
3441
3442LogicalResult ModuleImport::convertInvokeAttributes(llvm::InvokeInst *inst,
3443 InvokeOp op) {
3444 llvm::AttributeList invokeAttrs = inst->getAttributes();
3445 op.setUniformWorkGroupSize(
3446 invokeAttrs.getFnAttr("uniform-work-group-size").isValid());
3447 return convertCallBaseAttributes(inst, op);
3448}
3449
3450LogicalResult ModuleImport::convertCallAttributes(llvm::CallInst *inst,
3451 CallOp op) {
3452 setFastmathFlagsAttr(inst, op.getOperation());
3453 // Query the attributes directly instead of using `inst->getFnAttr(Kind)`, the
3454 // latter does additional lookup to the parent and inherits, changing the
3455 // semantics too early.
3456 llvm::AttributeList callAttrs = inst->getAttributes();
3457
3458 op.setTailCallKind(convertTailCallKindFromLLVM(inst->getTailCallKind()));
3459 op.setConvergent(callAttrs.getFnAttr(llvm::Attribute::Convergent).isValid());
3460 op.setNoUnwind(callAttrs.getFnAttr(llvm::Attribute::NoUnwind).isValid());
3461 op.setWillReturn(callAttrs.getFnAttr(llvm::Attribute::WillReturn).isValid());
3462 op.setNoreturn(callAttrs.getFnAttr(llvm::Attribute::NoReturn).isValid());
3463 op.setOptsize(
3464 callAttrs.getFnAttr(llvm::Attribute::OptimizeForSize).isValid());
3465 op.setSaveRegParams(callAttrs.getFnAttr("save-reg-params").isValid());
3466 op.setUniformWorkGroupSize(
3467 callAttrs.getFnAttr("uniform-work-group-size").isValid());
3468 op.setBuiltin(callAttrs.getFnAttr(llvm::Attribute::Builtin).isValid());
3469 op.setNobuiltin(callAttrs.getFnAttr(llvm::Attribute::NoBuiltin).isValid());
3470 op.setMinsize(callAttrs.getFnAttr(llvm::Attribute::MinSize).isValid());
3471
3472 op.setReturnsTwice(
3473 callAttrs.getFnAttr(llvm::Attribute::ReturnsTwice).isValid());
3474 op.setHot(callAttrs.getFnAttr(llvm::Attribute::Hot).isValid());
3475 op.setCold(callAttrs.getFnAttr(llvm::Attribute::Cold).isValid());
3476 op.setNoduplicate(
3477 callAttrs.getFnAttr(llvm::Attribute::NoDuplicate).isValid());
3478 op.setNoCallerSavedRegisters(
3479 callAttrs.getFnAttr("no_caller_saved_registers").isValid());
3480 op.setNocallback(callAttrs.getFnAttr(llvm::Attribute::NoCallback).isValid());
3481
3482 if (llvm::Attribute attr = callAttrs.getFnAttr("modular-format");
3483 attr.isStringAttribute())
3484 op.setModularFormat(StringAttr::get(context, attr.getValueAsString()));
3485 if (llvm::Attribute attr = callAttrs.getFnAttr("zero-call-used-regs");
3486 attr.isStringAttribute())
3487 op.setZeroCallUsedRegsAttr(
3488 StringAttr::get(context, attr.getValueAsString()));
3489 if (llvm::Attribute attr = callAttrs.getFnAttr("trap-func-name");
3490 attr.isStringAttribute())
3491 op.setTrapFuncNameAttr(StringAttr::get(context, attr.getValueAsString()));
3492 op.setNoInline(callAttrs.getFnAttr(llvm::Attribute::NoInline).isValid());
3493 op.setAlwaysInline(
3494 callAttrs.getFnAttr(llvm::Attribute::AlwaysInline).isValid());
3495 op.setInlineHint(callAttrs.getFnAttr(llvm::Attribute::InlineHint).isValid());
3496
3497 llvm::MemoryEffects memEffects = inst->getMemoryEffects();
3498 ModRefInfo othermem = convertModRefInfoFromLLVM(
3499 memEffects.getModRef(llvm::MemoryEffects::Location::Other));
3500 ModRefInfo argMem = convertModRefInfoFromLLVM(
3501 memEffects.getModRef(llvm::MemoryEffects::Location::ArgMem));
3502 ModRefInfo inaccessibleMem = convertModRefInfoFromLLVM(
3503 memEffects.getModRef(llvm::MemoryEffects::Location::InaccessibleMem));
3504 ModRefInfo errnoMem = convertModRefInfoFromLLVM(
3505 memEffects.getModRef(llvm::MemoryEffects::Location::ErrnoMem));
3506 ModRefInfo targetMem0 = convertModRefInfoFromLLVM(
3507 memEffects.getModRef(llvm::MemoryEffects::Location::TargetMem0));
3508 ModRefInfo targetMem1 = convertModRefInfoFromLLVM(
3509 memEffects.getModRef(llvm::MemoryEffects::Location::TargetMem1));
3510 auto memAttr =
3511 MemoryEffectsAttr::get(op.getContext(), othermem, argMem, inaccessibleMem,
3512 errnoMem, targetMem0, targetMem1);
3513 // Only set the attribute when it does not match the default value.
3514 if (!memAttr.isReadWrite())
3515 op.setMemoryEffectsAttr(memAttr);
3516
3517 convertNoBuiltinAttrs(op.getContext(), callAttrs.getFnAttrs(), op);
3518 convertAllocsizeAttr(op.getContext(), callAttrs.getFnAttrs(), op);
3519
3520 return convertCallBaseAttributes(inst, op);
3521}
3522
3523LogicalResult ModuleImport::processFunction(llvm::Function *func) {
3524 clearRegionState();
3525
3526 auto functionType =
3527 dyn_cast<LLVMFunctionType>(convertType(func->getFunctionType()));
3528 if (func->isIntrinsic() &&
3529 iface.isConvertibleIntrinsic(func->getIntrinsicID()))
3530 return success();
3531
3532 bool dsoLocal = func->isDSOLocal();
3533 CConv cconv = convertCConvFromLLVM(func->getCallingConv());
3534
3535 // Insert the function at the end of the module.
3536 OpBuilder::InsertionGuard guard(builder);
3537 builder.setInsertionPointToEnd(mlirModule.getBody());
3538
3539 Location loc = debugImporter->translateFuncLocation(func);
3540 LLVMFuncOp funcOp = LLVMFuncOp::create(
3541 builder, loc, func->getName(), functionType,
3542 convertLinkageFromLLVM(func->getLinkage()), dsoLocal, cconv);
3543
3545
3546 if (FlatSymbolRefAttr personality = getPersonalityAsAttr(func))
3547 funcOp.setPersonalityAttr(personality);
3548 else if (func->hasPersonalityFn())
3549 emitWarning(funcOp.getLoc(), "could not deduce personality, skipping it");
3550
3551 if (func->hasGC())
3552 funcOp.setGarbageCollector(StringRef(func->getGC()));
3553
3554 if (func->hasAtLeastLocalUnnamedAddr())
3555 funcOp.setUnnamedAddr(convertUnnamedAddrFromLLVM(func->getUnnamedAddr()));
3556
3557 if (func->hasSection())
3558 funcOp.setSection(StringRef(func->getSection()));
3559
3560 funcOp.setVisibility_(convertVisibilityFromLLVM(func->getVisibility()));
3561
3562 if (func->hasComdat())
3563 funcOp.setComdatAttr(comdatMapping.lookup(func->getComdat()));
3564
3565 if (llvm::MaybeAlign maybeAlign = func->getAlign())
3566 funcOp.setAlignment(maybeAlign->value());
3567
3568 // Handle Function attributes.
3570
3571 // Convert non-debug metadata by using the dialect interface. Metadata without
3572 // a kind-specific conversion is preserved in the generic function metadata
3573 // carrier.
3575 func->getAllMetadata(allMetadata);
3576 SmallVector<StringRef> metadataNames;
3577 llvmModule->getMDKindNames(metadataNames);
3578 SmallVector<Attribute> functionMetadata;
3579 for (auto &[kind, node] : allMetadata) {
3580 if (kind == llvm::LLVMContext::MD_dbg)
3581 continue;
3582
3583 llvm::MDNode *metadataNode = node;
3584 auto emitUnhandledFunctionMetadataWarning = [&]() {
3585 if (!emitExpensiveWarnings)
3586 return;
3587 emitWarning(funcOp.getLoc())
3588 << "unhandled function metadata: " << renderMetadata(metadataNode)
3589 << " on " << renderValue(*func);
3590 };
3591
3592 if (iface.isConvertibleMetadata(kind)) {
3593 if (succeeded(iface.setMetadataAttrs(builder, kind, metadataNode, funcOp,
3594 *this)))
3595 continue;
3596 emitUnhandledFunctionMetadataWarning();
3597 continue;
3598 }
3599
3600 Attribute nodeAttr = convertMetadataToAttr(metadataNode);
3601 auto mdNodeAttr = dyn_cast_if_present<LLVM::MDNodeAttr>(nodeAttr);
3602 if (!mdNodeAttr || kind >= metadataNames.size()) {
3603 emitUnhandledFunctionMetadataWarning();
3604 continue;
3605 }
3606
3607 functionMetadata.push_back(LLVM::FunctionMetadataAttr::get(
3608 context, builder.getStringAttr(metadataNames[kind]), mdNodeAttr));
3609 }
3610 if (!functionMetadata.empty())
3611 funcOp.setFunctionMetadataAttr(builder.getArrayAttr(functionMetadata));
3612
3613 if (func->isDeclaration())
3614 return success();
3615
3616 // Collect the set of basic blocks reachable from the function's entry block.
3617 // This step is crucial as LLVM IR can contain unreachable blocks that
3618 // self-dominate. As a result, an operation might utilize a variable it
3619 // defines, which the import does not support. Given that MLIR lacks block
3620 // label support, we can safely remove unreachable blocks, as there are no
3621 // indirect branch instructions that could potentially target these blocks.
3622 llvm::df_iterator_default_set<llvm::BasicBlock *> reachable;
3623 for (llvm::BasicBlock *basicBlock : llvm::depth_first_ext(func, reachable))
3624 (void)basicBlock;
3625
3626 // Eagerly create all reachable blocks.
3627 SmallVector<llvm::BasicBlock *> reachableBasicBlocks;
3628 for (llvm::BasicBlock &basicBlock : *func) {
3629 // Skip unreachable blocks.
3630 if (!reachable.contains(&basicBlock)) {
3631 if (basicBlock.hasAddressTaken())
3632 return emitError(funcOp.getLoc())
3633 << "unreachable block '" << basicBlock.getName()
3634 << "' with address taken";
3635 continue;
3636 }
3637 Region &body = funcOp.getBody();
3638 Block *block = builder.createBlock(&body, body.end());
3639 mapBlock(&basicBlock, block);
3640 reachableBasicBlocks.push_back(&basicBlock);
3641 }
3642
3643 // Add function arguments to the entry block.
3644 for (const auto &it : llvm::enumerate(func->args())) {
3645 BlockArgument blockArg = funcOp.getFunctionBody().addArgument(
3646 functionType.getParamType(it.index()), funcOp.getLoc());
3647 mapValue(&it.value(), blockArg);
3648 }
3649
3650 // Process the blocks in topological order. The ordered traversal ensures
3651 // operands defined in a dominating block have a valid mapping to an MLIR
3652 // value once a block is translated.
3654 getTopologicallySortedBlocks(reachableBasicBlocks);
3655 setConstantInsertionPointToStart(lookupBlock(blocks.front()));
3656 for (llvm::BasicBlock *basicBlock : blocks)
3657 if (failed(processBasicBlock(basicBlock, lookupBlock(basicBlock))))
3658 return failure();
3659
3660 // Process the debug intrinsics that require a delayed conversion after
3661 // everything else was converted.
3662 if (failed(processDebugIntrinsics()))
3663 return failure();
3664
3665 // Process the debug records that require a delayed conversion after
3666 // everything else was converted.
3667 if (failed(processDebugRecords()))
3668 return failure();
3669
3670 return success();
3671}
3672
3673/// Checks if `dbgIntr` is a kill location that holds metadata instead of an SSA
3674/// value.
3675static bool isMetadataKillLocation(llvm::DbgVariableIntrinsic *dbgIntr) {
3676 if (!dbgIntr->isKillLocation())
3677 return false;
3678 llvm::Value *value = dbgIntr->getArgOperand(0);
3679 auto *nodeAsVal = dyn_cast<llvm::MetadataAsValue>(value);
3680 if (!nodeAsVal)
3681 return false;
3682 return !isa<llvm::ValueAsMetadata>(nodeAsVal->getMetadata());
3683}
3684
3685/// Ensure that the debug intrinsic is inserted right after the operand
3686/// definition. Otherwise, the operand might not necessarily dominate the
3687/// intrinsic. If the defining operation is a terminator, insert the intrinsic
3688/// into a dominated block.
3690 mlir::OpBuilder &builder, DominanceInfo &domInfo, Value argOperand) {
3691 if (Operation *op = argOperand.getDefiningOp();
3692 op && op->hasTrait<OpTrait::IsTerminator>()) {
3693 // Find a dominated block that can hold the debug intrinsic.
3694 auto dominatedBlocks = domInfo.getNode(op->getBlock())->children();
3695 // If no block is dominated by the terminator, this intrinisc cannot be
3696 // converted.
3697 if (dominatedBlocks.empty())
3698 return failure();
3699 // Set insertion point before the terminator, to avoid inserting something
3700 // before landingpads.
3701 Block *dominatedBlock = (*dominatedBlocks.begin())->getBlock();
3702 builder.setInsertionPoint(dominatedBlock->getTerminator());
3703 } else {
3704 Value insertPt = argOperand;
3705 if (auto blockArg = dyn_cast<BlockArgument>(argOperand)) {
3706 // The value might be coming from a phi node and is now a block argument,
3707 // which means the insertion point is set to the start of the block. If
3708 // this block is a target destination of an invoke, the insertion point
3709 // must happen after the landing pad operation.
3710 Block *insertionBlock = argOperand.getParentBlock();
3711 if (!insertionBlock->empty() &&
3712 isa<LandingpadOp>(insertionBlock->front()))
3713 insertPt = cast<LandingpadOp>(insertionBlock->front()).getRes();
3714 }
3715
3716 builder.setInsertionPointAfterValue(insertPt);
3717 }
3718 return success();
3719}
3720
3721std::tuple<DILocalVariableAttr, DIExpressionAttr, Value>
3722ModuleImport::processDebugOpArgumentsAndInsertionPt(
3723 Location loc,
3724 llvm::function_ref<FailureOr<Value>()> convertArgOperandToValue,
3725 llvm::Value *address,
3726 llvm::PointerUnion<llvm::Value *, llvm::DILocalVariable *> variable,
3727 llvm::DIExpression *expression, DominanceInfo &domInfo) {
3728 // Drop debug intrinsics if the associated debug information cannot be
3729 // translated due to an unsupported construct.
3730 DILocalVariableAttr localVarAttr = matchLocalVariableAttr(variable);
3731 if (!localVarAttr)
3732 return {};
3733 FailureOr<Value> argOperand = convertArgOperandToValue();
3734 if (failed(argOperand)) {
3735 emitError(loc) << "failed to convert a debug operand: "
3736 << renderValue(*address);
3737 return {};
3738 }
3739
3740 if (setDebugIntrinsicBuilderInsertionPoint(builder, domInfo, *argOperand)
3741 .failed())
3742 return {};
3743
3744 return {localVarAttr, debugImporter->translateExpression(expression),
3745 *argOperand};
3746}
3747
3748LogicalResult
3749ModuleImport::processDebugIntrinsic(llvm::DbgVariableIntrinsic *dbgIntr,
3750 DominanceInfo &domInfo) {
3751 Location loc = translateLoc(dbgIntr->getDebugLoc());
3752 auto emitUnsupportedWarning = [&]() {
3753 if (emitExpensiveWarnings)
3754 emitWarning(loc) << "dropped intrinsic: " << renderValue(*dbgIntr);
3755 return success();
3756 };
3757
3758 OpBuilder::InsertionGuard guard(builder);
3759 auto convertArgOperandToValue = [&]() {
3760 return convertMetadataValue(dbgIntr->getArgOperand(0));
3761 };
3762
3763 // Drop debug intrinsics with an argument list.
3764 // TODO: Support this case.
3765 if (dbgIntr->hasArgList())
3766 return emitUnsupportedWarning();
3767
3768 // Drop debug intrinsics with kill locations that have metadata nodes as
3769 // location operand, which cannot be converted to poison as the type cannot be
3770 // reconstructed.
3771 // TODO: Support this case.
3772 if (isMetadataKillLocation(dbgIntr))
3773 return emitUnsupportedWarning();
3774
3775 auto [localVariableAttr, locationExprAttr, locVal] =
3776 processDebugOpArgumentsAndInsertionPt(
3777 loc, convertArgOperandToValue, dbgIntr->getArgOperand(0),
3778 dbgIntr->getArgOperand(1), dbgIntr->getExpression(), domInfo);
3779
3780 if (!localVariableAttr)
3781 return emitUnsupportedWarning();
3782
3783 if (!locVal) // Expected if localVariableAttr is present.
3784 return failure();
3785
3786 Operation *op = nullptr;
3787 if (isa<llvm::DbgDeclareInst>(dbgIntr))
3788 op = LLVM::DbgDeclareOp::create(builder, loc, locVal, localVariableAttr,
3789 locationExprAttr);
3790 else if (isa<llvm::DbgValueInst>(dbgIntr))
3791 op = LLVM::DbgValueOp::create(builder, loc, locVal, localVariableAttr,
3792 locationExprAttr);
3793 else
3794 return emitUnsupportedWarning();
3795
3796 mapNoResultOp(dbgIntr, op);
3797 setNonDebugMetadataAttrs(dbgIntr, op);
3798 return success();
3799}
3800
3801LogicalResult
3802ModuleImport::processDebugRecord(llvm::DbgVariableRecord &dbgRecord,
3803 DominanceInfo &domInfo) {
3804 OpBuilder::InsertionGuard guard(builder);
3805 Location loc = translateLoc(dbgRecord.getDebugLoc());
3806 auto emitUnsupportedWarning = [&]() -> LogicalResult {
3807 if (!emitExpensiveWarnings)
3808 return success();
3809 std::string options;
3810 llvm::raw_string_ostream optionsStream(options);
3811 dbgRecord.print(optionsStream);
3812 emitWarning(loc) << "unhandled debug variable record "
3813 << optionsStream.str();
3814 return success();
3815 };
3816
3817 // Drop debug records with an argument list.
3818 // TODO: Support this case.
3819 if (dbgRecord.hasArgList())
3820 return emitUnsupportedWarning();
3821
3822 // Drop all other debug records with a address operand that cannot be
3823 // converted to an SSA value such as an empty metadata node.
3824 // TODO: Support this case.
3825 if (!dbgRecord.getAddress())
3826 return emitUnsupportedWarning();
3827
3828 auto convertArgOperandToValue = [&]() -> FailureOr<Value> {
3829 llvm::Value *value = dbgRecord.getAddress();
3830
3831 // Return the mapped value if it has been converted before.
3832 auto it = valueMapping.find(value);
3833 if (it != valueMapping.end())
3834 return it->getSecond();
3835
3836 // Convert constants such as immediate values that have no mapping yet.
3837 if (auto *constant = dyn_cast<llvm::Constant>(value))
3838 return convertConstantExpr(constant);
3839 return failure();
3840 };
3841
3842 auto [localVariableAttr, locationExprAttr, locVal] =
3843 processDebugOpArgumentsAndInsertionPt(
3844 loc, convertArgOperandToValue, dbgRecord.getAddress(),
3845 dbgRecord.getVariable(), dbgRecord.getExpression(), domInfo);
3846
3847 if (!localVariableAttr)
3848 return emitUnsupportedWarning();
3849
3850 if (!locVal) // Expected if localVariableAttr is present.
3851 return failure();
3852
3853 if (dbgRecord.isDbgDeclare())
3854 LLVM::DbgDeclareOp::create(builder, loc, locVal, localVariableAttr,
3855 locationExprAttr);
3856 else if (dbgRecord.isDbgValue())
3857 LLVM::DbgValueOp::create(builder, loc, locVal, localVariableAttr,
3858 locationExprAttr);
3859 else // isDbgAssign
3860 return emitUnsupportedWarning();
3861
3862 return success();
3863}
3864
3865LogicalResult ModuleImport::processDebugIntrinsics() {
3866 DominanceInfo domInfo;
3867 for (llvm::Instruction *inst : debugIntrinsics) {
3868 auto *intrCall = cast<llvm::DbgVariableIntrinsic>(inst);
3869 if (failed(processDebugIntrinsic(intrCall, domInfo)))
3870 return failure();
3871 }
3872 return success();
3873}
3874
3875LogicalResult ModuleImport::processDebugRecords() {
3876 DominanceInfo domInfo;
3877 for (llvm::DbgVariableRecord *dbgRecord : dbgRecords)
3878 if (failed(processDebugRecord(*dbgRecord, domInfo)))
3879 return failure();
3880 dbgRecords.clear();
3881 return success();
3882}
3883
3884LogicalResult ModuleImport::processBasicBlock(llvm::BasicBlock *bb,
3885 Block *block) {
3886 builder.setInsertionPointToStart(block);
3887 for (llvm::Instruction &inst : *bb) {
3888 if (failed(processInstruction(&inst)))
3889 return failure();
3890
3891 // Skip additional processing when the instructions is a debug intrinsics
3892 // that was not yet converted.
3893 if (debugIntrinsics.contains(&inst))
3894 continue;
3895
3896 // Set the non-debug metadata attributes on the imported operation and emit
3897 // a warning if an instruction other than a phi instruction is dropped
3898 // during the import.
3899 if (Operation *op = lookupOperation(&inst)) {
3900 setNonDebugMetadataAttrs(&inst, op);
3901 } else if (inst.getOpcode() != llvm::Instruction::PHI) {
3902 if (emitExpensiveWarnings) {
3903 Location loc = debugImporter->translateLoc(inst.getDebugLoc());
3904 emitWarning(loc) << "dropped instruction: " << renderValue(inst);
3905 }
3906 }
3907 }
3908
3909 if (bb->hasAddressTaken()) {
3910 OpBuilder::InsertionGuard guard(builder);
3911 builder.setInsertionPointToStart(block);
3912 BlockTagOp::create(builder, block->getParentOp()->getLoc(),
3913 BlockTagAttr::get(context, bb->getNumber()));
3914 }
3915 return success();
3916}
3917
3918FailureOr<SmallVector<AccessGroupAttr>>
3919ModuleImport::lookupAccessGroupAttrs(const llvm::MDNode *node) const {
3920 return loopAnnotationImporter->lookupAccessGroupAttrs(node);
3921}
3922
3923LoopAnnotationAttr
3925 Location loc) const {
3926 return loopAnnotationImporter->translateLoopAnnotation(node, loc);
3927}
3928
3929FailureOr<DereferenceableAttr>
3931 unsigned kindID) {
3932 Location loc = mlirModule.getLoc();
3933
3934 // The only operand should be a constant integer representing the number of
3935 // dereferenceable bytes.
3936 if (node->getNumOperands() != 1)
3937 return emitError(loc) << "dereferenceable metadata must have one operand: "
3938 << renderMetadata(node);
3939
3940 auto *numBytesMD = dyn_cast<llvm::ConstantAsMetadata>(node->getOperand(0));
3941 auto *numBytesCst = dyn_cast<llvm::ConstantInt>(numBytesMD->getValue());
3942 if (!numBytesCst || !numBytesCst->getValue().isNonNegative())
3943 return emitError(loc) << "dereferenceable metadata operand must be a "
3944 "non-negative constant integer: "
3945 << renderMetadata(node);
3946
3947 bool mayBeNull = kindID == llvm::LLVMContext::MD_dereferenceable_or_null;
3948 auto derefAttr = builder.getAttr<DereferenceableAttr>(
3949 numBytesCst->getZExtValue(), mayBeNull);
3950
3951 return derefAttr;
3952}
3953
3955 std::unique_ptr<llvm::Module> llvmModule, MLIRContext *context,
3956 bool emitExpensiveWarnings, bool dropDICompositeTypeElements,
3957 bool loadAllDialects, bool preferUnregisteredIntrinsics,
3958 bool importStructsAsLiterals) {
3959 // Preload all registered dialects to allow the import to iterate the
3960 // registered LLVMImportDialectInterface implementations and query the
3961 // supported LLVM IR constructs before starting the translation. Assumes the
3962 // LLVM and DLTI dialects that convert the core LLVM IR constructs have been
3963 // registered before.
3964 assert(llvm::is_contained(context->getAvailableDialects(),
3965 LLVMDialect::getDialectNamespace()));
3966 assert(llvm::is_contained(context->getAvailableDialects(),
3967 DLTIDialect::getDialectNamespace()));
3968 if (loadAllDialects)
3969 context->loadAllAvailableDialects();
3970 OwningOpRef<ModuleOp> module(ModuleOp::create(FileLineColLoc::get(
3971 StringAttr::get(context, llvmModule->getSourceFileName()), /*line=*/0,
3972 /*column=*/0)));
3973
3974 ModuleImport moduleImport(module.get(), std::move(llvmModule),
3975 emitExpensiveWarnings, dropDICompositeTypeElements,
3976 preferUnregisteredIntrinsics,
3977 importStructsAsLiterals);
3978 if (failed(moduleImport.initializeImportInterface()))
3979 return {};
3980 if (failed(moduleImport.convertDataLayout()))
3981 return {};
3982 if (failed(moduleImport.convertComdats()))
3983 return {};
3984 if (failed(moduleImport.convertMetadata()))
3985 return {};
3986 if (failed(moduleImport.convertGlobals()))
3987 return {};
3988 if (failed(moduleImport.convertFunctions()))
3989 return {};
3990 if (failed(moduleImport.convertAliases()))
3991 return {};
3992 if (failed(moduleImport.convertIFuncs()))
3993 return {};
3994 moduleImport.convertTargetTriple();
3995 moduleImport.convertModuleLevelAsm();
3996 return module;
3997}
return success()
return MutableOperandRange * this
ArrayAttr()
b getContext())
*if copies could not be generated due to yet unimplemented cases *copyInPlacementStart and copyOutPlacementStart in copyPlacementBlock *specify the insertion points where the incoming copies and outgoing should be inserted(the insertion happens right before the *insertion point). Since `begin` can itself be invalidated due to the memref *rewriting done from this method
static ArrayAttr convertLLVMAttributesToMLIR(Location loc, MLIRContext *context, llvm::AttributeSet attributes, ArrayRef< StringLiteral > attributesToSkip={}, ArrayRef< StringLiteral > attributePrefixesToSkip={})
Converts LLVM string, integer, and enum attributes into MLIR attributes, skipping those in attributes...
static StringRef getLLVMSyncScope(llvm::Instruction *inst)
Converts the sync scope identifier of inst to the string representation necessary to build an atomic ...
static void processPassthroughAttrs(llvm::Function *func, LLVMFuncOp funcOp)
Converts LLVM attributes from func into MLIR attributes and adds them to funcOp as passthrough attrib...
static constexpr size_t kMaxDiagLength
Upper bound on the characters a diagnostic renders for an LLVM entity.
static SmallVector< Attribute > getSequenceConstantAsAttrs(OpBuilder &builder, llvm::ConstantDataSequential *constSequence)
Returns an integer or float attribute array for the provided constant sequence constSequence or nullp...
static LogicalResult convertCallBaseAttributes(llvm::CallBase *inst, Op op)
static void processMemoryEffects(llvm::Function *func, LLVMFuncOp funcOp)
static Attribute convertCGProfileModuleFlagValue(ModuleOp mlirModule, llvm::MDTuple *mdTuple)
static FailureOr< uint64_t > convertInt64FromKeyValueTuple(ModuleOp mlirModule, const llvm::Module *llvmModule, const llvm::MDOperand &md, StringRef matchKey, llvm::ModuleSlotTracker &tracker)
Extract an integer value from a two element tuple (<key, value>).
static constexpr std::array kExplicitLLVMFuncOpAttributePrefixes
static llvm::ConstantAsMetadata * getConstantMDFromKeyValueTuple(ModuleOp mlirModule, const llvm::Module *llvmModule, const llvm::MDOperand &md, StringRef matchKey, llvm::ModuleSlotTracker &tracker, bool optional=false)
Extract a constant metadata value from a two element tuple (<key, value>).
static constexpr StringRef getGlobalDtorsVarName()
Returns the name of the global_dtors global variables.
static Type getVectorTypeForAttr(Type type, ArrayRef< int64_t > arrayShape={})
Returns type if it is a builtin integer or floating-point vector type that can be used to create an a...
static LogicalResult convertInstructionImpl(OpBuilder &odsBuilder, llvm::Instruction *inst, ModuleImport &moduleImport, LLVMImportInterface &iface)
Converts the LLVM instructions that have a generated MLIR builder.
static constexpr StringRef getNamelessGlobalPrefix()
Prefix used for symbols of nameless llvm globals.
static constexpr std::array kExplicitLLVMFuncOpAttributes
static constexpr StringRef getGlobalComdatOpName()
Returns the symbol name for the module-level comdat operation.
static std::optional< ProfileSummaryFormatKind > convertProfileSummaryFormat(ModuleOp mlirModule, const llvm::Module *llvmModule, const llvm::MDOperand &formatMD, llvm::ModuleSlotTracker &tracker)
static void convertNoBuiltinAttrs(MLIRContext *ctx, const llvm::AttributeSet &attrs, OpTy target)
static SmallVector< int64_t > getPositionFromIndices(ArrayRef< unsigned > indices)
Converts an array of unsigned indices to a signed integer position array.
static LogicalResult setDebugIntrinsicBuilderInsertionPoint(mlir::OpBuilder &builder, DominanceInfo &domInfo, Value argOperand)
Ensure that the debug intrinsic is inserted right after the operand definition.
static LogicalResult checkFunctionTypeCompatibility(LLVMFunctionType callType, LLVMFunctionType calleeType)
Checks if callType and calleeType are compatible and can be represented in MLIR.
static void processDenormalFPEnv(llvm::Function *func, LLVMFuncOp funcOp)
static constexpr StringRef getGlobalCtorsVarName()
Returns the name of the global_ctors global variables.
static void processTargetSpecificAttrs(llvm::GlobalVariable *globalVar, GlobalOp globalOp)
Converts LLVM attributes from globalVar into MLIR attributes and adds them to globalOp as target-spec...
static llvm::MDTuple * getTwoElementMDTuple(ModuleOp mlirModule, const llvm::Module *llvmModule, const llvm::MDOperand &md, llvm::ModuleSlotTracker &tracker)
Extract a two element MDTuple from a MDOperand.
static bool isMetadataKillLocation(llvm::DbgVariableIntrinsic *dbgIntr)
Checks if dbgIntr is a kill location that holds metadata instead of an SSA value.
static TypedAttr getScalarConstantAsAttr(OpBuilder &builder, llvm::Constant *constScalar)
Returns an integer or float attribute for the provided scalar constant constScalar or nullptr if the ...
static void convertAllocsizeAttr(MLIRContext *ctx, const llvm::AttributeSet &attrs, OpTy target)
static Attribute convertProfileSummaryModuleFlagValue(ModuleOp mlirModule, const llvm::Module *llvmModule, llvm::MDTuple *mdTuple, llvm::ModuleSlotTracker &tracker)
static std::string truncateDiag(std::string str)
static Attribute convertModuleFlagValueFromMDTuple(ModuleOp mlirModule, const llvm::Module *llvmModule, StringRef key, llvm::MDTuple *mdTuple, llvm::ModuleSlotTracker &tracker)
Invoke specific handlers for each known module flag value, returns nullptr if the key is unknown or u...
static std::string renderMetadataWithTracker(const llvm::Metadata *node, llvm::ModuleSlotTracker &tracker, const llvm::Module *module)
Prints a metadata node through a caller-provided tracker so module-flag conversion shares the importe...
static FailureOr< SmallVector< ModuleFlagProfileSummaryDetailedAttr > > convertProfileSummaryDetailed(ModuleOp mlirModule, const llvm::Module *llvmModule, const llvm::MDOperand &summaryMD, llvm::ModuleSlotTracker &tracker)
static SetVector< llvm::BasicBlock * > getTopologicallySortedBlocks(ArrayRef< llvm::BasicBlock * > basicBlocks)
Get a topologically sorted list of blocks for the given basic blocks.
static llvm::ManagedStatic< PassManagerOptions > options
Attributes are known-constant values of operations.
Definition Attributes.h:25
This class represents an argument of a Block.
Definition Value.h:308
Block represents an ordered list of Operations.
Definition Block.h:34
bool empty()
Definition Block.h:173
Operation & front()
Definition Block.h:178
Operation * getTerminator()
Get the terminator operation of this block.
Definition Block.cpp:249
Operation * getParentOp()
Returns the closest surrounding operation that contains this block.
Definition Block.cpp:31
This class is a general helper class for creating context-global objects like types,...
Definition Builders.h:51
UnitAttr getUnitAttr()
Definition Builders.cpp:106
DenseI32ArrayAttr getDenseI32ArrayAttr(ArrayRef< int32_t > values)
Definition Builders.cpp:171
IntegerAttr getIntegerAttr(Type type, int64_t value)
Definition Builders.cpp:237
FloatAttr getFloatAttr(Type type, double value)
Definition Builders.cpp:263
IntegerAttr getI64IntegerAttr(int64_t value)
Definition Builders.cpp:120
StringAttr getStringAttr(const Twine &bytes)
Definition Builders.cpp:271
ArrayAttr getArrayAttr(ArrayRef< Attribute > value)
Definition Builders.cpp:275
MLIRContext * getContext() const
Definition Builders.h:56
NamedAttribute getNamedAttr(StringRef name, Attribute val)
Definition Builders.cpp:102
Attr getAttr(Args &&...args)
Get or construct an instance of the attribute Attr with provided arguments.
Definition Builders.h:101
static DenseElementsAttr get(ShapedType type, ArrayRef< Attribute > values)
Constructs a dense elements attribute from an array of element values.
static DistinctAttr create(Attribute referencedAttr)
Creates a distinct attribute that associates a referenced attribute with a unique identifier.
A class for computing basic dominance information.
Definition Dominance.h:143
static FileLineColLoc get(StringAttr filename, unsigned line, unsigned column)
Definition Location.cpp:161
A symbol reference with a reference path containing a single element.
static FlatSymbolRefAttr get(StringAttr value)
Construct a symbol reference for the given value name.
StringRef getValue() const
Returns the name of the held symbol reference.
Interface collection for the import of LLVM IR that dispatches to a concrete dialect interface implem...
LogicalResult convertInstruction(OpBuilder &builder, llvm::Instruction *inst, ArrayRef< llvm::Value * > llvmOperands, LLVM::ModuleImport &moduleImport) const
Converts the LLVM instruction to an MLIR operation if a conversion exists.
LogicalResult setMetadataAttrs(OpBuilder &builder, unsigned kind, llvm::MDNode *node, Operation *op, LLVM::ModuleImport &moduleImport) const
Attaches the given LLVM metadata to the imported operation if a conversion to one or more MLIR dialec...
bool isConvertibleMetadata(unsigned kind)
Returns true if the given LLVM IR metadata is convertible to an MLIR attribute.
bool isConvertibleInstruction(unsigned id)
Returns true if the given LLVM IR instruction is convertible to an MLIR operation.
Module import implementation class that provides methods to import globals and functions from an LLVM...
LogicalResult convertIFuncs()
Converts all ifuncs of the LLVM module to MLIR variables.
LogicalResult convertIntrinsicArguments(ArrayRef< llvm::Value * > values, ArrayRef< llvm::OperandBundleUse > opBundles, bool requiresOpBundles, ArrayRef< unsigned > immArgPositions, ArrayRef< StringLiteral > immArgAttrNames, SmallVectorImpl< Value > &valuesOut, SmallVectorImpl< NamedAttribute > &attrsOut)
Converts the LLVM values for an intrinsic to mixed MLIR values and attributes for LLVM_IntrOpBase.
Location translateLoc(llvm::DILocation *loc)
Translates the debug location.
LogicalResult convertComdats()
Converts all comdat selectors of the LLVM module to MLIR comdat operations.
LogicalResult convertAliases()
Converts all aliases of the LLVM module to MLIR variables.
LogicalResult convertFunctions()
Converts all functions of the LLVM module to MLIR functions.
FailureOr< SmallVector< Value > > convertValues(ArrayRef< llvm::Value * > values)
Converts a range of LLVM values to a range of MLIR values using the convertValue method,...
Attribute lookupTBAAAttr(const llvm::MDNode *node) const
Returns the MLIR attribute mapped to the given LLVM TBAA metadata node.
LogicalResult convertLinkerOptionsMetadata()
Converts !llvm.linker.options metadata to the llvm.linker.options LLVM dialect operation.
Block * lookupBlock(llvm::BasicBlock *block) const
Returns the MLIR block mapped to the given LLVM block.
void mapBlock(llvm::BasicBlock *llvm, Block *mlir)
Stores the mapping between an LLVM block and its MLIR counterpart.
DILocalVariableAttr matchLocalVariableAttr(llvm::PointerUnion< llvm::Value *, llvm::DILocalVariable * > valOrVariable)
Converts valOrVariable to a local variable attribute.
void processFunctionAttributes(llvm::Function *func, LLVMFuncOp funcOp)
Converts function attributes of LLVM Function func into LLVM dialect attributes of LLVMFuncOp funcOp.
LogicalResult convertMetadata()
Converts all LLVM metadata nodes that translate to attributes such as alias analysis or access group ...
FailureOr< Value > convertValue(llvm::Value *value)
Converts an LLVM value to an MLIR value, or returns failure if the conversion fails.
LogicalResult initializeImportInterface()
Calls the LLVMImportInterface initialization that queries the registered dialect interfaces for the s...
void addDebugIntrinsic(llvm::CallInst *intrinsic)
Adds a debug intrinsics to the list of intrinsics that should be converted after the function convers...
LogicalResult convertIdentMetadata()
Converts !llvm.ident metadata to the llvm.ident LLVM ModuleOp attribute.
FailureOr< Value > convertMetadataValue(llvm::Value *value)
Converts an LLVM metadata value to an MLIR value, or returns failure if the conversion fails.
FailureOr< SmallVector< AliasScopeAttr > > lookupAliasScopeAttrs(const llvm::MDNode *node) const
Returns the alias scope attributes that map to the alias scope nodes starting from the metadata node.
void setDisjointFlag(llvm::Instruction *inst, Operation *op) const
Sets the disjoint flag attribute for the imported operation op given the original instruction inst.
void mapNoResultOp(llvm::Instruction *llvm, Operation *mlir)
Stores a mapping between an LLVM instruction and the imported MLIR operation if the operation returns...
void convertModuleLevelAsm()
Converts the module level asm of the LLVM module to an MLIR module level asm specification.
void setExactFlag(llvm::Instruction *inst, Operation *op) const
Sets the exact flag attribute for the imported operation op given the original instruction inst.
Type convertType(llvm::Type *type)
Converts the type from LLVM to MLIR LLVM dialect.
ModuleImport(ModuleOp mlirModule, std::unique_ptr< llvm::Module > llvmModule, bool emitExpensiveWarnings, bool importEmptyDICompositeTypes, bool preferUnregisteredIntrinsics, bool importStructsAsLiterals)
DILabelAttr matchLabelAttr(llvm::Value *value)
Converts value to a label attribute. Asserts if the matching fails.
FloatAttr matchFloatAttr(llvm::Value *value)
Converts value to a float attribute. Asserts if the matching fails.
LoopAnnotationAttr translateLoopAnnotationAttr(const llvm::MDNode *node, Location loc) const
Returns the loop annotation attribute that corresponds to the given LLVM loop metadata node.
void setFastmathFlagsAttr(llvm::Instruction *inst, Operation *op) const
Sets the fastmath flags attribute for the imported operation op given the original instruction inst.
FailureOr< SmallVector< AliasScopeAttr > > matchAliasScopeAttrs(llvm::Value *value)
Converts value to an array of alias scopes or returns failure if the conversion fails.
Value lookupValue(llvm::Value *value)
Returns the MLIR value mapped to the given LLVM value.
Operation * lookupOperation(llvm::Instruction *inst)
Returns the MLIR operation mapped to the given LLVM instruction.
LogicalResult processFunction(llvm::Function *func)
Imports func into the current module.
LogicalResult convertDependentLibrariesMetadata()
Converts !llvm.dependent-libraries metadata to llvm.dependent_libraries LLVM ModuleOp attribute.
RoundingModeAttr matchRoundingModeAttr(llvm::Value *value)
Converts value to a rounding mode attribute.
void convertTargetTriple()
Converts target triple of the LLVM module to an MLIR target triple specification.
void addDebugRecord(llvm::DbgVariableRecord *dbgRecord)
Adds a debug record to the list of debug records that need to be imported after the function conversi...
void convertArgAndResultAttrs(llvm::CallBase *call, ArgAndResultAttrsOpInterface attrsOp, ArrayRef< unsigned > immArgPositions={})
Converts the argument and result attributes attached to call and adds them to attrsOp.
LogicalResult convertModuleFlagsMetadata()
Converts !llvm.module.flags metadata.
void mapValue(llvm::Value *llvm, Value mlir)
Stores the mapping between an LLVM value and its MLIR counterpart.
FailureOr< SmallVector< AccessGroupAttr > > lookupAccessGroupAttrs(const llvm::MDNode *node) const
Returns the access group attributes that map to the access group nodes starting from the access group...
LogicalResult convertGlobals()
Converts all global variables of the LLVM module to MLIR global variables.
void setIntegerOverflowFlags(llvm::Instruction *inst, Operation *op) const
Sets the integer overflow flags (nsw/nuw) attribute for the imported operation op given the original ...
LogicalResult convertCommandlineMetadata()
Converts !llvm.commandline metadata to the llvm.commandline LLVM ModuleOp attribute.
FPExceptionBehaviorAttr matchFPExceptionBehaviorAttr(llvm::Value *value)
Converts value to a FP exception behavior attribute.
void setNonNegFlag(llvm::Instruction *inst, Operation *op) const
Sets the nneg flag attribute for the imported operation op given the original instruction inst.
FailureOr< DereferenceableAttr > translateDereferenceableAttr(const llvm::MDNode *node, unsigned kindID)
Returns the dereferenceable attribute that corresponds to the given LLVM dereferenceable or dereferen...
LogicalResult convertDataLayout()
Converts the data layout of the LLVM module to an MLIR data layout specification.
IntegerAttr matchIntegerAttr(llvm::Value *value)
Converts value to an integer attribute. Asserts if the matching fails.
Helper class that translates an LLVM data layout string to an MLIR data layout specification.
StringRef getLastToken() const
Returns the last data layout token that has been processed before the data layout translation failed.
ArrayRef< StringRef > getUnhandledTokens() const
Returns the data layout tokens that have not been handled during the data layout translation.
DataLayoutSpecInterface getDataLayoutSpec() const
Returns the MLIR data layout specification translated from the LLVM data layout.
A helper class that converts llvm.loop metadata nodes into corresponding LoopAnnotationAttrs and llvm...
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition Location.h:76
MLIRContext is the top-level object for a collection of MLIR operations.
Definition MLIRContext.h:71
std::vector< StringRef > getAvailableDialects()
Return information about all available dialects in the registry in this context.
void loadAllAvailableDialects()
Load all dialects available in the registry in this context.
RAII guard to reset the insertion point of the builder when destroyed.
Definition Builders.h:351
This class helps build Operations.
Definition Builders.h:210
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
Definition Builders.h:401
void setInsertionPointToEnd(Block *block)
Sets the insertion point to the end of the specified block.
Definition Builders.h:439
void setInsertionPointAfterValue(Value val)
Sets the insertion point to the node after the specified value.
Definition Builders.h:424
This class provides the API for ops that are known to be terminators.
This provides public APIs that all operations should have.
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
bool hasTrait()
Returns true if the operation was registered with a particular trait, e.g.
Definition Operation.h:803
Location getLoc()
The source location the operation was defined or derived from.
Definition Operation.h:240
This class acts as an owning reference to an op, and will automatically destroy the held op on destru...
Definition OwningOpRef.h:29
OpTy get() const
Allow accessing the internal op.
Definition OwningOpRef.h:51
This class contains a list of basic blocks and a link to the parent operation it is attached to.
Definition Region.h:26
iterator end()
Definition Region.h:56
static SmallString< N > generateSymbolName(StringRef name, UniqueChecker uniqueChecker, unsigned &uniquingCounter)
Generate a unique symbol name.
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
MLIRContext * getContext() const
Return the MLIRContext in which this type was uniqued.
Definition Types.cpp:35
bool isIntOrFloat() const
Return true if this is an integer (of any signedness) or a float type.
Definition Types.cpp:118
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
Block * getParentBlock()
Return the Block in which this Value is defined.
Definition Value.cpp:46
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Definition Value.cpp:18
static DenseArrayAttrImpl get(MLIRContext *context, ArrayRef< int32_t > content)
DominanceInfoNode * getNode(Block *a)
Return the dominance node from the Region containing block A.
Definition Dominance.h:85
static llvm::ArrayRef< std::pair< llvm::Attribute::AttrKind, llvm::StringRef > > getAttrKindToNameMapping()
Returns a list of pairs that each hold a mapping from LLVM attribute kinds to their corresponding str...
FloatType getFloatType(MLIRContext *context, unsigned width)
Returns a supported MLIR floating point type of the given bit width or null if the bit width is not s...
bool isCompatibleVectorType(Type type)
Returns true if the given type is a vector type compatible with the LLVM dialect.
llvm::ElementCount getVectorNumElements(Type type)
Returns the element count of any LLVM-compatible vector type.
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:886
Include the generated interface declarations.
bool matchPattern(Value value, const Pattern &pattern)
Entry point for matching a pattern over a Value.
Definition Matchers.h:490
InFlightDiagnostic emitWarning(Location loc)
Utility method to emit a warning message using this location.
llvm::DenseSet< ValueT, ValueInfoT > DenseSet
Definition LLVM.h:125
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
llvm::SetVector< T, Vector, Set, N > SetVector
Definition LLVM.h:128
llvm::DenseMap< KeyT, ValueT, KeyInfoT, BucketT > DenseMap
Definition LLVM.h:123
detail::constant_op_matcher m_Constant()
Matches a constant foldable operation.
Definition Matchers.h:369
OwningOpRef< ModuleOp > translateLLVMIRToModule(std::unique_ptr< llvm::Module > llvmModule, MLIRContext *context, bool emitExpensiveWarnings=true, bool dropDICompositeTypeElements=false, bool loadAllDialects=true, bool preferUnregisteredIntrinsics=false, bool importStructsAsLiterals=false)
Translates the LLVM module into an MLIR module living in the given context.