MLIR 24.0.0git
ModuleImport.h
Go to the documentation of this file.
1//===- ModuleImport.h - 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
14#ifndef MLIR_TARGET_LLVMIR_MODULEIMPORT_H
15#define MLIR_TARGET_LLVMIR_MODULEIMPORT_H
16
18#include "mlir/IR/BuiltinOps.h"
22#include "llvm/ADT/SmallPtrSet.h"
23#include "llvm/IR/Module.h"
24
25namespace llvm {
26class BasicBlock;
27class ModuleSlotTracker;
28class CallBase;
29class DbgVariableIntrinsic;
30class Function;
31class Instruction;
32class Value;
33} // namespace llvm
34
35namespace mlir {
36namespace LLVM {
37class CallOp;
38class InvokeOp;
39
40namespace detail {
42class DebugImporter;
44} // namespace detail
45
46/// Module import implementation class that provides methods to import globals
47/// and functions from an LLVM module into an MLIR module. It holds mappings
48/// between the original and translated globals, basic blocks, and values used
49/// during the translation. Additionally, it keeps track of the current constant
50/// insertion point since LLVM immediate values translate to MLIR operations
51/// that are introduced at the beginning of the region.
53public:
54 ModuleImport(ModuleOp mlirModule, std::unique_ptr<llvm::Module> llvmModule,
55 bool emitExpensiveWarnings, bool importEmptyDICompositeTypes,
56 bool preferUnregisteredIntrinsics, bool importStructsAsLiterals);
58
59 /// Calls the LLVMImportInterface initialization that queries the registered
60 /// dialect interfaces for the supported LLVM IR intrinsics and metadata kinds
61 /// and builds the dispatch tables. Returns failure if multiple dialect
62 /// interfaces translate the same LLVM IR intrinsic.
63 LogicalResult initializeImportInterface() {
64 return iface.initializeImport(llvmModule->getContext());
65 }
66
67 /// Converts all functions of the LLVM module to MLIR functions.
68 LogicalResult convertFunctions();
69
70 /// Converts all comdat selectors of the LLVM module to MLIR comdat
71 /// operations.
72 LogicalResult convertComdats();
73
74 /// Converts all global variables of the LLVM module to MLIR global variables.
75 LogicalResult convertGlobals();
76
77 /// Converts all aliases of the LLVM module to MLIR variables.
78 LogicalResult convertAliases();
79
80 /// Converts all ifuncs of the LLVM module to MLIR variables.
81 LogicalResult convertIFuncs();
82
83 /// Converts the data layout of the LLVM module to an MLIR data layout
84 /// specification.
85 LogicalResult convertDataLayout();
86
87 /// Converts target triple of the LLVM module to an MLIR target triple
88 /// specification.
90
91 /// Converts the module level asm of the LLVM module to an MLIR module
92 /// level asm specification.
94
95 /// Stores the mapping between an LLVM value and its MLIR counterpart.
96 void mapValue(llvm::Value *llvm, Value mlir) { mapValue(llvm) = mlir; }
97
98 /// Provides write-once access to store the MLIR value corresponding to the
99 /// given LLVM value.
100 Value &mapValue(llvm::Value *value) {
101 Value &mlir = valueMapping[value];
102 assert(mlir == nullptr &&
103 "attempting to map a value that is already mapped");
104 return mlir;
105 }
106
107 /// Returns the MLIR value mapped to the given LLVM value.
108 Value lookupValue(llvm::Value *value) { return valueMapping.lookup(value); }
109
110 /// Stores a mapping between an LLVM instruction and the imported MLIR
111 /// operation if the operation returns no result. Asserts if the operation
112 /// returns a result and should be added to valueMapping instead.
113 void mapNoResultOp(llvm::Instruction *llvm, Operation *mlir) {
115 }
116
117 /// Provides write-once access to store the MLIR operation corresponding to
118 /// the given LLVM instruction if the operation returns no result. Asserts if
119 /// the operation returns a result and should be added to valueMapping
120 /// instead.
121 Operation *&mapNoResultOp(llvm::Instruction *inst) {
122 Operation *&mlir = noResultOpMapping[inst];
123 assert(inst->getType()->isVoidTy() &&
124 "attempting to map an operation that returns a result");
125 assert(mlir == nullptr &&
126 "attempting to map an operation that is already mapped");
127 return mlir;
128 }
129
130 /// Returns the MLIR operation mapped to the given LLVM instruction. Queries
131 /// valueMapping and noResultOpMapping to support operations with and without
132 /// result.
133 Operation *lookupOperation(llvm::Instruction *inst) {
134 if (Value value = lookupValue(inst))
135 return value.getDefiningOp();
136 return noResultOpMapping.lookup(inst);
137 }
138
139 /// Stores the mapping between an LLVM block and its MLIR counterpart.
140 void mapBlock(llvm::BasicBlock *llvm, Block *mlir) {
141 auto result = blockMapping.try_emplace(llvm, mlir);
142 (void)result;
143 assert(result.second && "attempting to map a block that is already mapped");
144 }
145
146 /// Returns the MLIR block mapped to the given LLVM block.
147 Block *lookupBlock(llvm::BasicBlock *block) const {
148 return blockMapping.lookup(block);
149 }
150
151 /// Converts an LLVM value to an MLIR value, or returns failure if the
152 /// conversion fails. Uses the `convertConstant` method to translate constant
153 /// LLVM values.
154 FailureOr<Value> convertValue(llvm::Value *value);
155
156 /// Converts an LLVM metadata value to an MLIR value, or returns failure if
157 /// the conversion fails. Uses the `convertConstant` method to translate
158 /// constant LLVM values.
159 FailureOr<Value> convertMetadataValue(llvm::Value *value);
160
161 /// Converts a range of LLVM values to a range of MLIR values using the
162 /// `convertValue` method, or returns failure if the conversion fails.
163 FailureOr<SmallVector<Value>> convertValues(ArrayRef<llvm::Value *> values);
164
165 /// Converts `value` to an integer attribute. Asserts if the matching fails.
166 IntegerAttr matchIntegerAttr(llvm::Value *value);
167
168 /// Converts `value` to a float attribute. Asserts if the matching fails.
169 FloatAttr matchFloatAttr(llvm::Value *value);
170
171 /// Converts `valOrVariable` to a local variable attribute. Asserts if the
172 /// matching fails.
173 DILocalVariableAttr matchLocalVariableAttr(
175
176 /// Converts `value` to a label attribute. Asserts if the matching fails.
177 DILabelAttr matchLabelAttr(llvm::Value *value);
178
179 /// Converts `value` to a FP exception behavior attribute. Asserts if the
180 /// matching fails.
181 FPExceptionBehaviorAttr matchFPExceptionBehaviorAttr(llvm::Value *value);
182
183 /// Converts `value` to a rounding mode attribute. Asserts if the matching
184 /// fails.
185 RoundingModeAttr matchRoundingModeAttr(llvm::Value *value);
186
187 /// Converts `value` to an array of alias scopes or returns failure if the
188 /// conversion fails.
189 FailureOr<SmallVector<AliasScopeAttr>>
190 matchAliasScopeAttrs(llvm::Value *value);
191
192 /// Translates the debug location.
193 Location translateLoc(llvm::DILocation *loc);
194
195 /// Converts the type from LLVM to MLIR LLVM dialect.
196 Type convertType(llvm::Type *type) {
197 return typeTranslator.translateType(type);
198 }
199
200 /// Imports `func` into the current module.
201 LogicalResult processFunction(llvm::Function *func);
202
203 /// Converts function attributes of LLVM Function `func` into LLVM dialect
204 /// attributes of LLVMFuncOp `funcOp`.
205 void processFunctionAttributes(llvm::Function *func, LLVMFuncOp funcOp);
206
207 /// Sets the integer overflow flags (nsw/nuw) attribute for the imported
208 /// operation `op` given the original instruction `inst`. Asserts if the
209 /// operation does not implement the integer overflow flag interface.
210 void setIntegerOverflowFlags(llvm::Instruction *inst, Operation *op) const;
211
212 /// Sets the exact flag attribute for the imported operation `op` given
213 /// the original instruction `inst`. Asserts if the operation does not
214 /// implement the exact flag interface.
215 void setExactFlag(llvm::Instruction *inst, Operation *op) const;
216
217 /// Sets the disjoint flag attribute for the imported operation `op`
218 /// given the original instruction `inst`. Asserts if the operation does
219 /// not implement the disjoint flag interface.
220 void setDisjointFlag(llvm::Instruction *inst, Operation *op) const;
221
222 /// Sets the nneg flag attribute for the imported operation `op` given
223 /// the original instruction `inst`. Asserts if the operation does not
224 /// implement the nneg flag interface.
225 void setNonNegFlag(llvm::Instruction *inst, Operation *op) const;
226
227 /// Sets the fastmath flags attribute for the imported operation `op` given
228 /// the original instruction `inst`. Asserts if the operation does not
229 /// implement the fastmath interface.
230 void setFastmathFlagsAttr(llvm::Instruction *inst, Operation *op) const;
231
232 /// Converts !llvm.linker.options metadata to the llvm.linker.options
233 /// LLVM dialect operation.
234 LogicalResult convertLinkerOptionsMetadata();
235
236 /// Converts !llvm.module.flags metadata.
237 LogicalResult convertModuleFlagsMetadata();
238
239 /// Converts !llvm.ident metadata to the llvm.ident LLVM ModuleOp attribute.
240 LogicalResult convertIdentMetadata();
241
242 /// Converts !llvm.commandline metadata to the llvm.commandline LLVM ModuleOp
243 /// attribute.
244 LogicalResult convertCommandlineMetadata();
245
246 /// Converts !llvm.dependent-libraries metadata to llvm.dependent_libraries
247 /// LLVM ModuleOp attribute.
248 LogicalResult convertDependentLibrariesMetadata();
249
250 /// Converts all LLVM metadata nodes that translate to attributes such as
251 /// alias analysis or access group metadata, and builds a map from the
252 /// metadata nodes to the converted attributes.
253 /// Returns success if all conversions succeed and failure otherwise.
254 LogicalResult convertMetadata();
255
256 /// Returns the MLIR attribute mapped to the given LLVM TBAA
257 /// metadata `node`.
258 Attribute lookupTBAAAttr(const llvm::MDNode *node) const {
259 return tbaaMapping.lookup(node);
260 }
261
262 /// Looks up a converted `!tbaa.struct` node. Returns null when the
263 /// node was never converted or could not be modeled.
264 Attribute lookupTBAAStructAttr(const llvm::MDNode *node) const {
265 return tbaaStructMapping.lookup(node);
266 }
267
268 /// Returns the access group attributes that map to the access group nodes
269 /// starting from the access group metadata `node`. Returns failure, if any of
270 /// the attributes cannot be found.
271 FailureOr<SmallVector<AccessGroupAttr>>
272 lookupAccessGroupAttrs(const llvm::MDNode *node) const;
273
274 /// Returns the loop annotation attribute that corresponds to the given LLVM
275 /// loop metadata `node`.
276 LoopAnnotationAttr translateLoopAnnotationAttr(const llvm::MDNode *node,
277 Location loc) const;
278
279 /// Returns the dereferenceable attribute that corresponds to the given LLVM
280 /// dereferenceable or dereferenceable_or_null metadata `node`. `kindID`
281 /// specifies the kind of the metadata node (dereferenceable or
282 /// dereferenceable_or_null).
283 FailureOr<DereferenceableAttr>
284 translateDereferenceableAttr(const llvm::MDNode *node, unsigned kindID);
285
286 /// Returns the alias scope attributes that map to the alias scope nodes
287 /// starting from the metadata `node`. Returns failure, if any of the
288 /// attributes cannot be found.
289 FailureOr<SmallVector<AliasScopeAttr>>
290 lookupAliasScopeAttrs(const llvm::MDNode *node) const;
291
292 /// Adds a debug intrinsics to the list of intrinsics that should be converted
293 /// after the function conversion has finished.
294 void addDebugIntrinsic(llvm::CallInst *intrinsic);
295
296 /// Adds a debug record to the list of debug records that need to be imported
297 /// after the function conversion has finished.
298 void addDebugRecord(llvm::DbgVariableRecord *dbgRecord);
299
300 /// Converts the LLVM values for an intrinsic to mixed MLIR values and
301 /// attributes for LLVM_IntrOpBase. Attributes correspond to LLVM immargs. The
302 /// list `immArgPositions` contains the positions of immargs on the LLVM
303 /// intrinsic, and `immArgAttrNames` list (of the same length) contains the
304 /// corresponding MLIR attribute names.
305 LogicalResult
308 bool requiresOpBundles,
309 ArrayRef<unsigned> immArgPositions,
310 ArrayRef<StringLiteral> immArgAttrNames,
311 SmallVectorImpl<Value> &valuesOut,
313
314 /// Converts the argument and result attributes attached to `call` and adds
315 /// them to `attrsOp`. For intrinsic calls, filters out attributes
316 /// corresponding to immediate arguments specified by `immArgPositions`.
317 void convertArgAndResultAttrs(llvm::CallBase *call,
318 ArgAndResultAttrsOpInterface attrsOp,
319 ArrayRef<unsigned> immArgPositions = {});
320
321 /// Whether the importer should try to convert all intrinsics to
322 /// llvm.call_intrinsic instead of dialect supported operations.
324 return preferUnregisteredIntrinsics;
325 }
326
327private:
328 /// Renders `value` into a bounded string for a diagnostic.
329 std::string renderValue(const llvm::Value &value);
330 /// Renders `node` into a bounded string for a diagnostic.
331 std::string renderMetadata(const llvm::Metadata *node);
332 /// Shared slot tracker for diagnostics, created on first use.
333 llvm::ModuleSlotTracker &getDiagSlotTracker();
334
335 /// Clears the accumulated state before processing a new region.
336 void clearRegionState() {
337 valueMapping.clear();
338 noResultOpMapping.clear();
339 blockMapping.clear();
340 debugIntrinsics.clear();
341 }
342 /// Sets the constant insertion point to the start of the given block.
343 void setConstantInsertionPointToStart(Block *block) {
344 constantInsertionBlock = block;
345 constantInsertionOp = nullptr;
346 }
347
348 /// Converts an LLVM global variable into an MLIR LLVM dialect global
349 /// operation if a conversion exists. Otherwise, returns failure.
350 LogicalResult convertGlobal(llvm::GlobalVariable *globalVar);
351 /// Imports the magic globals "global_ctors" and "global_dtors".
352 LogicalResult convertGlobalCtorsAndDtors(llvm::GlobalVariable *globalVar);
353 /// Converts an LLVM global alias variable into an MLIR LLVM dialect alias
354 /// operation if a conversion exists. Otherwise, returns failure.
355 LogicalResult convertAlias(llvm::GlobalAlias *alias);
356 // Converts an LLVM global ifunc into an MLIR LLVM dialect ifunc operation.
357 LogicalResult convertIFunc(llvm::GlobalIFunc *ifunc);
358 /// Returns personality of `func` as a FlatSymbolRefAttr.
359 FlatSymbolRefAttr getPersonalityAsAttr(llvm::Function *func);
360 /// Imports `bb` into `block`, which must be initially empty.
361 LogicalResult processBasicBlock(llvm::BasicBlock *bb, Block *block);
362 /// Converts all debug intrinsics in `debugIntrinsics`. Assumes that the
363 /// function containing the intrinsics has been fully converted to MLIR.
364 LogicalResult processDebugIntrinsics();
365 /// Converts all debug records in `dbgRecords`. Assumes that the
366 /// function containing the record has been fully converted to MLIR.
367 LogicalResult processDebugRecords();
368 /// Converts a single debug intrinsic.
369 LogicalResult processDebugIntrinsic(llvm::DbgVariableIntrinsic *dbgIntr,
370 DominanceInfo &domInfo);
371 /// Converts a single debug record.
372 LogicalResult processDebugRecord(llvm::DbgVariableRecord &dbgRecord,
373 DominanceInfo &domInfo);
374 /// Process arguments for declare/value operation insertion. `localVarAttr`
375 /// and `localExprAttr` are the attained attributes after importing the debug
376 /// variable and expressions. This also sets the builder insertion point to be
377 /// used by these operations.
378 std::tuple<DILocalVariableAttr, DIExpressionAttr, Value>
379 processDebugOpArgumentsAndInsertionPt(
380 Location loc,
381 llvm::function_ref<FailureOr<Value>()> convertArgOperandToValue,
382 llvm::Value *address,
384 llvm::DIExpression *expression, DominanceInfo &domInfo);
385 /// Converts LLMV IR asm inline call operand's attributes into an array of
386 /// MLIR attributes to be utilized in `llvm.inline_asm`.
387 ArrayAttr convertAsmInlineOperandAttrs(const llvm::CallBase &llvmCall);
388 /// Converts an LLVM intrinsic to an MLIR LLVM dialect operation if an MLIR
389 /// counterpart exists. Otherwise, returns failure.
390 LogicalResult convertIntrinsic(llvm::CallInst *inst);
391 /// Converts an LLVM instruction to an MLIR LLVM dialect operation if an MLIR
392 /// counterpart exists. Otherwise, returns failure.
393 LogicalResult convertInstruction(llvm::Instruction *inst);
394 /// Converts the metadata attached to the original instruction `inst` if
395 /// a dialect interfaces supports the specific kind of metadata and attaches
396 /// the resulting dialect attributes to the converted operation `op`. Emits a
397 /// warning if the conversion of a supported metadata kind fails.
398 void setNonDebugMetadataAttrs(llvm::Instruction *inst, Operation *op);
399 /// Returns the symbol reference for a global value that has a corresponding
400 /// imported MLIR symbol, or a null attribute otherwise.
401 FlatSymbolRefAttr getMetadataGlobalValueSymbolRef(llvm::GlobalValue *global);
402 /// Returns a symbol ref if `md` refers to an imported global value.
403 FlatSymbolRefAttr getMetadataOperandSymbolRef(const llvm::Metadata *md);
404 /// Converts `md` to the matching LLVM dialect metadata attribute, or returns
405 /// a null attribute if the metadata cannot be represented.
406 Attribute convertMetadataToAttr(const llvm::Metadata *md);
407 /// Recursively converts `md` and tracks the current path and previously
408 /// converted nodes to reject cycles and preserve shared subgraphs.
409 Attribute convertMetadataToAttrImpl(
410 const llvm::Metadata *md, SmallPtrSetImpl<const llvm::Metadata *> &path,
412 /// Imports `inst` and populates valueMapping[inst] with the result of the
413 /// imported operation or noResultOpMapping[inst] with the imported operation
414 /// if it has no result.
415 LogicalResult processInstruction(llvm::Instruction *inst);
416 /// Converts the `branch` arguments in the order of the phi's found in
417 /// `target` and appends them to the `blockArguments` to attach to the
418 /// generated branch operation. The `blockArguments` thus have the same order
419 /// as the phi's in `target`.
420 LogicalResult convertBranchArgs(llvm::Instruction *branch,
421 llvm::BasicBlock *target,
422 SmallVectorImpl<Value> &blockArguments);
423 /// Converted operand bundles, with flattened operands and one size and tag
424 /// per bundle.
425 struct OperandBundles {
426 SmallVector<Value> operands;
427 DenseI32ArrayAttr sizes;
428 ArrayAttr tags;
429 };
430
431 /// Converts operand bundles, preserving their order and empty bundles.
432 FailureOr<OperandBundles>
433 convertOperandBundles(ArrayRef<llvm::OperandBundleUse> bundles);
434
435 /// Convert `callInst` operands. For indirect calls, the method additionally
436 /// inserts the called function at the beginning of the returned `operands`
437 /// array. If `allowInlineAsm` is set to false (the default), it will return
438 /// failure if the called operand is an inline asm which isn't convertible to
439 /// MLIR as a value.
440 FailureOr<SmallVector<Value>>
441 convertCallOperands(llvm::CallBase *callInst, bool allowInlineAsm = false);
442 /// Converts the callee's function type. For direct calls, it converts the
443 /// actual function type, which may differ from the called operand type in
444 /// variadic functions. For indirect calls, it converts the function type
445 /// associated with the call instruction. When the call and the callee are not
446 /// compatible (or when nested type conversions failed), emit a warning and
447 /// update `isIncompatibleCall` to indicate it.
448 FailureOr<LLVMFunctionType> convertFunctionType(llvm::CallBase *callInst,
449 bool &isIncompatibleCall);
450 /// Returns the callee name, or an empty symbol if the call is not direct.
451 FlatSymbolRefAttr convertCalleeName(llvm::CallBase *callInst);
452 /// Converts the argument and result attributes attached to `func` and adds
453 /// them to the `funcOp`.
454 void convertArgAndResultAttrs(llvm::Function *func, LLVMFuncOp funcOp);
455 /// Converts the argument or result attributes in `llvmAttrSet` to a
456 /// corresponding MLIR LLVM dialect attribute dictionary.
457 DictionaryAttr convertArgOrResultAttrSet(llvm::AttributeSet llvmAttrSet);
458 /// Converts the attributes attached to `inst` and adds them to the `op`.
459 LogicalResult convertCallAttributes(llvm::CallInst *inst, CallOp op);
460 /// Converts the attributes attached to `inst` and adds them to the `op`.
461 LogicalResult convertInvokeAttributes(llvm::InvokeInst *inst, InvokeOp op);
462 /// Returns the builtin type equivalent to the given LLVM dialect type or
463 /// nullptr if there is no equivalent. The returned type can be used to create
464 /// an attribute for a GlobalOp or a ConstantOp.
465 Type getBuiltinTypeForAttr(Type type);
466 /// Returns `constant` as an attribute to attach to a GlobalOp or ConstantOp
467 /// or nullptr if the constant is not convertible. It supports scalar integer
468 /// and float constants as well as shaped types thereof including strings.
469 Attribute getConstantAsAttr(llvm::Constant *constant);
470 /// Returns the topologically sorted set of transitive dependencies needed to
471 /// convert the given constant.
472 SetVector<llvm::Constant *> getConstantsToConvert(llvm::Constant *constant);
473 /// Converts an LLVM constant to an MLIR value, or returns failure if the
474 /// conversion fails. The MLIR value may be produced by a ConstantOp,
475 /// AddressOfOp, NullOp, or a side-effect free operation (for ConstantExprs or
476 /// ConstantGEPs).
477 FailureOr<Value> convertConstant(llvm::Constant *constant);
478 /// Converts an LLVM constant and its transitive constant dependencies to MLIR
479 /// operations by converting them in topological order using the
480 /// `convertConstant` method, or returns failure if the conversion of any of
481 /// them fails. All operations are inserted at the start of the current
482 /// function entry block.
483 FailureOr<Value> convertConstantExpr(llvm::Constant *constant);
484 /// Returns a global comdat operation that serves as a container for LLVM
485 /// comdat selectors. Creates the global comdat operation on the first
486 /// invocation.
487 ComdatOp getGlobalComdatOp();
488 /// Performs conversion of LLVM TBAA metadata starting from
489 /// `node`. On exit from this function all nodes reachable
490 /// from `node` are converted, and tbaaMapping map is updated
491 /// (unless all dependencies have been converted by a previous
492 /// invocation of this function).
493 LogicalResult processTBAAMetadata(const llvm::MDNode *node);
494 /// Converts a `!tbaa.struct` node to the `tbaa_struct` attribute. The
495 /// node's tags must already be converted (see the pre-walk in
496 /// convertMetadata). Returns null for nodes that cannot be modeled;
497 /// callers record the null in tbaaStructMapping so the node is
498 /// declined at attach time.
499 Attribute convertTBAAStructMetadata(const llvm::MDNode *node);
500 /// Converts all LLVM access groups starting from `node` to MLIR access group
501 /// operations and stores a mapping from every nested access group node to the
502 /// translated attribute. Returns success if all conversions succeed and
503 /// failure otherwise.
504 LogicalResult processAccessGroupMetadata(const llvm::MDNode *node);
505 /// Converts all LLVM alias scopes and domains starting from `node` to MLIR
506 /// alias scope and domain attributes and stores a mapping from every nested
507 /// alias scope or alias domain node to the translated attribute. Returns
508 /// success if all conversions succeed and failure otherwise.
509 LogicalResult processAliasScopeMetadata(const llvm::MDNode *node);
510 /// Converts the given LLVM comdat struct to an MLIR comdat selector operation
511 /// and stores a mapping from the struct to the symbol pointing to the
512 /// translated operation.
513 void processComdat(const llvm::Comdat *comdat);
514 /// Returns a symbol name for a nameless global. MLIR, in contrast to LLVM,
515 /// always requires a symbol name.
516 FlatSymbolRefAttr
517 getOrCreateNamelessSymbolName(llvm::GlobalVariable *globalVar);
518 /// Returns the global insertion point for the next global operation. If the
519 /// `globalInsertionOp` is set, the insertion point is placed after the
520 /// specified operation. Otherwise, it defaults to the start of the module.
521 OpBuilder::InsertionGuard setGlobalInsertionPoint();
522
523 /// Builder pointing at where the next instruction should be generated.
524 OpBuilder builder;
525 /// Block to insert the next constant into.
526 Block *constantInsertionBlock = nullptr;
527 /// Operation to insert the next constant after.
528 Operation *constantInsertionOp = nullptr;
529 /// Operation to insert the next global after.
530 Operation *globalInsertionOp = nullptr;
531 /// Operation to insert comdat selector operations into.
532 ComdatOp globalComdatOp = nullptr;
533 /// The current context.
534 MLIRContext *context;
535 /// The MLIR module being created.
536 ModuleOp mlirModule;
537 /// The LLVM module being imported.
538 std::unique_ptr<llvm::Module> llvmModule;
539 /// Nameless globals.
541 /// Counter used to assign a unique ID to each nameless global.
542 unsigned namelessGlobalId = 0;
543
544 /// A dialect interface collection used for dispatching the import to specific
545 /// dialects.
546 LLVMImportInterface iface;
547
548 /// Function-local mapping between original and imported block.
550 /// Function-local mapping between original and imported values.
552 /// Function-local mapping between original instructions and imported
553 /// operations for all operations that return no result. All operations that
554 /// return a result have a valueMapping entry instead.
556 /// Function-local list of debug intrinsics that need to be imported after the
557 /// function conversion has finished.
558 SetVector<llvm::Instruction *> debugIntrinsics;
559 /// Function-local list of debug records that need to be imported after the
560 /// function conversion has finished.
561 SetVector<llvm::DbgVariableRecord *> dbgRecords;
562 /// Mapping between LLVM alias scope and domain metadata nodes and
563 /// attributes in the LLVM dialect corresponding to these nodes.
565 /// Mapping between LLVM TBAA metadata nodes and LLVM dialect TBAA attributes
566 /// corresponding to these nodes.
568 /// Mapping between LLVM `!tbaa.struct` nodes and the converted
569 /// `tbaa_struct` attributes. Kept separate from tbaaMapping so a struct
570 /// node can never be mistaken for a TBAA tag or type descriptor node,
571 /// which processTBAAMetadata casts to those attribute kinds. A null
572 /// value records that the node was converted and could not be modeled.
574 /// Mapping between LLVM comdat structs and symbol references to LLVM dialect
575 /// comdat selector operations corresponding to these structs.
576 DenseMap<const llvm::Comdat *, SymbolRefAttr> comdatMapping;
577 /// The stateful type translator (contains named structs).
578 LLVM::TypeFromLLVMIRTranslator typeTranslator;
579 /// Stateful debug information importer.
580 std::unique_ptr<detail::DebugImporter> debugImporter;
581 /// Loop annotation importer.
582 std::unique_ptr<detail::LoopAnnotationImporter> loopAnnotationImporter;
583 /// Slot tracker shared by every diagnostic that renders an LLVM entity.
584 /// Metadata::print and Value::print each construct their own tracker when
585 /// not given one, and building one walks the module, so a per-call tracker
586 /// makes a per-instruction diagnostic quadratic in module size. Sharing one
587 /// makes that walk a per-import cost instead. Created lazily, so an import
588 /// that renders nothing never pays for it at all.
589 std::unique_ptr<llvm::ModuleSlotTracker> diagSlotTracker;
590
591 /// An option to control if expensive but uncritical diagnostics should be
592 /// emitted. Avoids generating warnings for unhandled debug intrinsics and
593 /// metadata that otherwise dominate the translation time for large inputs.
594 bool emitExpensiveWarnings;
595
596 /// An option to control whether the importer should try to convert all
597 /// intrinsics to llvm.call_intrinsic instead of dialect supported operations.
598 bool preferUnregisteredIntrinsics;
599};
600
601} // namespace LLVM
602} // namespace mlir
603
604#endif // MLIR_TARGET_LLVMIR_MODULEIMPORT_H
ArrayAttr()
Attributes are known-constant values of operations.
Definition Attributes.h:25
Block represents an ordered list of Operations.
Definition Block.h:34
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.
bool useUnregisteredIntrinsicsOnly() const
Whether the importer should try to convert all intrinsics to llvm.call_intrinsic instead of dialect s...
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.
Attribute lookupTBAAStructAttr(const llvm::MDNode *node) const
Looks up a converted !tbaa.struct node.
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.
Value & mapValue(llvm::Value *value)
Provides write-once access to store the MLIR value corresponding to the given LLVM value.
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.
Operation *& mapNoResultOp(llvm::Instruction *inst)
Provides write-once access to store the MLIR operation corresponding to the given LLVM instruction if...
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.
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
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
The OpAsmOpInterface, see OpAsmInterface.td for more details.
Definition CallGraph.h:229
Include the generated interface declarations.
llvm::SetVector< T, Vector, Set, N > SetVector
Definition LLVM.h:128
detail::DenseArrayAttrImpl< int32_t > DenseI32ArrayAttr
llvm::DenseMap< KeyT, ValueT, KeyInfoT, BucketT > DenseMap
Definition LLVM.h:123