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