MLIR 24.0.0git
ModuleTranslation.h
Go to the documentation of this file.
1//===- ModuleTranslation.h - MLIR to LLVM 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 translation between an MLIR LLVM dialect module and
10// the corresponding LLVMIR module. It only handles core LLVM IR operations.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef MLIR_TARGET_LLVMIR_MODULETRANSLATION_H
15#define MLIR_TARGET_LLVMIR_MODULETRANSLATION_H
16
18#include "mlir/IR/Operation.h"
19#include "mlir/IR/SymbolTable.h"
20#include "mlir/IR/Value.h"
21#include "mlir/Support/LLVM.h"
23#include "mlir/Support/TypeID.h"
27
28#include "llvm/ADT/MapVector.h"
29#include "llvm/ADT/SetVector.h"
30#include "llvm/IR/FPEnv.h"
31#include "llvm/IR/Module.h"
32#include "llvm/Support/VirtualFileSystemFwd.h"
33
34namespace llvm {
35class BasicBlock;
36class CallBase;
37class Function;
38class IRBuilderBase;
39class Metadata;
40class Value;
41} // namespace llvm
42
43namespace mlir {
44class Attribute;
45class Block;
46class Location;
47
48namespace LLVM {
49
50namespace detail {
53} // namespace detail
54
55class AliasScopeAttr;
56class AliasScopeDomainAttr;
57class DINodeAttr;
58class LLVMFuncOp;
59class ComdatSelectorOp;
60
61/// Implementation class for module translation. Holds a reference to the module
62/// being translated, and the mappings between the original and the translated
63/// functions, basic blocks and values. It is practically easier to hold these
64/// mappings in one class since the conversion of control flow operations
65/// needs to look up block and function mappings.
66class ModuleTranslation {
67 friend std::unique_ptr<llvm::Module>
68 mlir::translateModuleToLLVMIR(Operation *, llvm::LLVMContext &, StringRef,
69 bool, llvm::vfs::FileSystem *);
70
71public:
72 /// Stores the mapping between a function name and its LLVM IR representation.
73 void mapFunction(StringRef name, llvm::Function *func) {
74 auto result = functionMapping.try_emplace(name, func);
75 (void)result;
76 assert(result.second &&
77 "attempting to map a function that is already mapped");
78 }
79
80 /// Finds an LLVM IR function by its name.
81 llvm::Function *lookupFunction(StringRef name) const {
82 return functionMapping.lookup(name);
83 }
84
85 /// Stores the mapping between an MLIR value and its LLVM IR counterpart.
86 void mapValue(Value mlir, llvm::Value *llvm) { mapValue(mlir) = llvm; }
87
88 /// Provides write-once access to store the LLVM IR value corresponding to the
89 /// given MLIR value.
90 llvm::Value *&mapValue(Value value) {
91 llvm::Value *&llvm = valueMapping[value];
92 assert(llvm == nullptr &&
93 "attempting to map a value that is already mapped");
94 return llvm;
95 }
96
97 /// Finds an LLVM IR value corresponding to the given MLIR value.
98 llvm::Value *lookupValue(Value value) const {
99 return valueMapping.lookup(value);
100 }
101
102 /// Remap old value with new value in the MLIR-to-LLVM value map so later
103 /// translations use the replacement. Existing LLVM instructions are not
104 /// rewritten.
105 void remapAllValuesWith(llvm::Value *oldValue, llvm::Value *newValue);
106
107 /// Looks up remapped a list of remapped values.
109
110 /// Stores the mapping between an MLIR block and LLVM IR basic block.
111 void mapBlock(Block *mlir, llvm::BasicBlock *llvm) {
112 auto result = blockMapping.try_emplace(mlir, llvm);
113 (void)result;
114 assert(result.second && "attempting to map a block that is already mapped");
115 }
116
117 /// Finds an LLVM IR basic block that corresponds to the given MLIR block.
118 llvm::BasicBlock *lookupBlock(Block *block) const {
119 return blockMapping.lookup(block);
120 }
121
122 /// Stores the mapping between an MLIR operation with successors and a
123 /// corresponding LLVM IR instruction.
124 void mapBranch(Operation *mlir, llvm::Instruction *llvm) {
125 auto result = branchMapping.try_emplace(mlir, llvm);
126 (void)result;
127 assert(result.second &&
128 "attempting to map a branch that is already mapped");
129 }
130
131 /// Finds an LLVM IR instruction that corresponds to the given MLIR operation
132 /// with successors.
133 llvm::Instruction *lookupBranch(Operation *op) const {
134 return branchMapping.lookup(op);
135 }
136
137 /// Stores a mapping between an MLIR call operation and a corresponding LLVM
138 /// call instruction.
139 void mapCall(Operation *mlir, llvm::CallInst *llvm) {
140 auto result = callMapping.try_emplace(mlir, llvm);
141 (void)result;
142 assert(result.second && "attempting to map a call that is already mapped");
143 }
144
145 /// Finds an LLVM call instruction that corresponds to the given MLIR call
146 /// operation.
147 llvm::CallInst *lookupCall(Operation *op) const {
148 return callMapping.lookup(op);
149 }
150
151 /// Maps a blockaddress operation to its corresponding placeholder LLVM
152 /// value.
153 void mapUnresolvedBlockAddress(BlockAddressOp op, llvm::Value *cst) {
154 auto result = unresolvedBlockAddressMapping.try_emplace(op, cst);
155 (void)result;
156 assert(result.second &&
157 "attempting to map a blockaddress operation that is already mapped");
158 }
159
160 /// Maps a BlockAddressAttr to its corresponding LLVM basic block.
161 void mapBlockAddress(BlockAddressAttr attr, llvm::BasicBlock *block) {
162 auto result = blockAddressToLLVMMapping.try_emplace(attr, block);
163 (void)result;
164 assert(result.second &&
165 "attempting to map a blockaddress attribute that is already mapped");
166 }
167
168 /// Finds the LLVM basic block that corresponds to the given BlockAddressAttr.
169 llvm::BasicBlock *lookupBlockAddress(BlockAddressAttr attr) const {
170 return blockAddressToLLVMMapping.lookup(attr);
171 }
172
173 /// Removes the mapping for blocks contained in the region and values defined
174 /// in these blocks.
175 void forgetMapping(Region &region);
176
177 /// Removes the mapping for the given value.
178 void forgetMapping(Value value) { valueMapping.erase(value); }
179
180 /// Returns the LLVM metadata corresponding to a mlir LLVM dialect alias scope
181 /// attribute. Creates the metadata node if it has not been converted before.
182 llvm::MDNode *getOrCreateAliasScope(AliasScopeAttr aliasScopeAttr);
183
184 /// Returns the LLVM metadata corresponding to an array of mlir LLVM dialect
185 /// alias scope attributes. Creates the metadata nodes if they have not been
186 /// converted before.
187 llvm::MDNode *
189
190 // Sets LLVM metadata for memory operations that are in a parallel loop.
191 void setAccessGroupsMetadata(AccessGroupOpInterface op,
192 llvm::Instruction *inst);
193
194 // Sets LLVM metadata for memory operations that have alias scope information.
195 void setAliasScopeMetadata(AliasAnalysisOpInterface op,
196 llvm::Instruction *inst);
197
198 /// Sets LLVM TBAA metadata for memory operations that have TBAA attributes.
199 void setTBAAMetadata(AliasAnalysisOpInterface op, llvm::Instruction *inst);
200
201 /// Sets LLVM tbaa.struct metadata on an aggregate copy, describing which
202 /// fields of the aggregate the copy touches.
203 void setTBAAStructMetadata(ArrayAttr fields, llvm::Instruction *inst);
204
205 /// Sets LLVM dereferenceable metadata for operations that have
206 /// dereferenceable attributes.
207 void setDereferenceableMetadata(DereferenceableOpInterface op,
208 llvm::Instruction *inst);
209
210 /// Sets LLVM profiling metadata for operations that have branch weights.
211 void setBranchWeightsMetadata(WeightedBranchOpInterface op);
212
213 /// Sets LLVM loop metadata for branch operations that have a loop annotation
214 /// attribute.
215 void setLoopMetadata(Operation *op, llvm::Instruction *inst);
216
217 /// Sets the disjoint flag attribute for the exported instruction `value`
218 /// given the original operation `op`. Asserts if the operation does
219 /// not implement the disjoint flag interface, and asserts if the value
220 /// is an instruction that implements the disjoint flag.
221 void setDisjointFlag(Operation *op, llvm::Value *value);
222
223 /// Converts the type from MLIR LLVM dialect to LLVM.
224 llvm::Type *convertType(Type type);
225
226 /// Returns the MLIR context of the module being translated.
227 MLIRContext &getContext() { return *mlirModule->getContext(); }
228
229 /// Returns the LLVM context in which the IR is being constructed.
230 llvm::LLVMContext &getLLVMContext() const { return llvmModule->getContext(); }
231
232 /// Finds an LLVM IR global value that corresponds to the given MLIR operation
233 /// defining a global value.
234 llvm::GlobalValue *lookupGlobal(Operation *op) {
235 return globalsMapping.lookup(op);
236 }
237
238 /// Finds an LLVM IR global value by the mlir.global symbol name.
239 llvm::GlobalValue *lookupGlobal(StringRef name) const {
240 return globalsByNameMapping.lookup(name);
241 }
242
243 /// Finds an LLVM IR global value that corresponds to the given MLIR operation
244 /// defining a global alias value.
245 llvm::GlobalValue *lookupAlias(Operation *op) {
246 return aliasesMapping.lookup(op);
247 }
248
249 /// Finds an LLVM IR global value that corresponds to the given MLIR operation
250 /// defining an IFunc.
251 llvm::GlobalValue *lookupIFunc(Operation *op) {
252 return ifuncMapping.lookup(op);
253 }
254
255 /// Returns the virtual filesystem to use for file operations. Falls back to
256 /// the real filesystem if none was provided.
257 llvm::vfs::FileSystem &getFileSystem();
258
259 /// Returns the LLVM module in which the IR is being constructed.
260 llvm::Module *getLLVMModule() { return llvmModule.get(); }
261
262 /// Translates the given location.
263 llvm::DILocation *translateLoc(Location loc, llvm::DILocalScope *scope);
264
265 /// Translates the given LLVM DWARF expression metadata.
266 llvm::DIExpression *translateExpression(LLVM::DIExpressionAttr attr);
267
268 /// Translates the given LLVM global variable expression metadata.
269 llvm::DIGlobalVariableExpression *
270 translateGlobalVariableExpression(LLVM::DIGlobalVariableExpressionAttr attr);
271
272 /// Translates the given LLVM debug info metadata.
273 llvm::Metadata *translateDebugInfo(LLVM::DINodeAttr attr);
274
275 /// Translates the given LLVM rounding mode metadata.
276 llvm::RoundingMode translateRoundingMode(LLVM::RoundingMode rounding);
277
278 /// Translates the given LLVM FP exception behavior metadata.
279 llvm::fp::ExceptionBehavior
280 translateFPExceptionBehavior(LLVM::FPExceptionBehavior exceptionBehavior);
281
282 /// Translates the contents of the given block to LLVM IR using this
283 /// translator. The LLVM IR basic block corresponding to the given block is
284 /// expected to exist in the mapping of this translator. Uses `builder` to
285 /// translate the IR, leaving it at the end of the block. If `ignoreArguments`
286 /// is set, does not produce PHI nodes for the block arguments. Otherwise, the
287 /// PHI nodes are constructed for block arguments but are _not_ connected to
288 /// the predecessors that may not exist yet.
289 LogicalResult convertBlock(Block &bb, bool ignoreArguments,
290 llvm::IRBuilderBase &builder) {
291 return convertBlockImpl(bb, ignoreArguments, builder,
292 /*recordInsertions=*/false);
293 }
294
295 /// Converts the given MLIR operation into LLVM IR using this translator. It
296 /// is up to the caller to ensure that all operands have been mapped before
297 /// calling this function.
298 LogicalResult convertOperation(Operation &op, llvm::IRBuilderBase &builder) {
299 return convertOperationImpl(op, builder, /*recordInsertions=*/false);
300 }
301
302 /// Converts argument and result attributes from `attrsOp` to LLVM IR
303 /// attributes on the `call` instruction. Returns failure if conversion fails.
304 /// The `immArgPositions` parameter is only relevant for intrinsics. It
305 /// specifies the positions of immediate arguments, which do not have
306 /// associated argument attributes in MLIR and should be skipped during
307 /// attribute mapping.
308 LogicalResult
309 convertArgAndResultAttrs(ArgAndResultAttrsOpInterface attrsOp,
310 llvm::CallBase *call,
311 ArrayRef<unsigned> immArgPositions = {});
312
313 /// Gets the named metadata in the LLVM IR module being constructed, creating
314 /// it if it does not exist.
315 llvm::NamedMDNode *getOrInsertNamedModuleMetadata(StringRef name);
316
317 /// Converts an LLVM dialect metadata attribute to LLVM IR metadata.
318 /// Returns failure and emits a diagnostic using `emitError` if the attribute
319 /// cannot be converted.
320 FailureOr<llvm::Metadata *>
323
324 /// Creates a stack frame of type `T` on ModuleTranslation stack. `T` must
325 /// be derived from `StackFrameBase<T>` and constructible from the provided
326 /// arguments. Doing this before entering the region of the op being
327 /// translated makes the frame available when translating ops within that
328 /// region.
329 template <typename T, typename... Args>
330 void stackPush(Args &&...args) {
331 stack.stackPush<T>(std::forward<Args>(args)...);
332 }
333
334 /// Pops the last element from the ModuleTranslation stack.
335 void stackPop() { stack.stackPop(); }
336
337 /// Calls `callback` for every ModuleTranslation stack frame of type `T`
338 /// starting from the top of the stack.
339 template <typename T>
341 return stack.stackWalk(callback);
342 }
343
344 /// RAII object calling stackPush/stackPop on construction/destruction.
345 template <typename T>
347
348 /// Base class for state that lives as long as the module translation.
349 /// Dialect translations use extensions to keep state shared across the
350 /// translation of several operations (e.g. IR builders or handle mappings)
351 /// without the core translation depending on those dialects. Derived classes
352 /// must provide an explicit TypeID.
353 class Extension {
354 public:
355 virtual ~Extension();
356
357 /// Called once after all operations have been translated and before the
358 /// LLVM module is verified. Extensions are finalized in creation order.
359 virtual LogicalResult finalize() { return success(); }
360 };
361
362 /// Returns the extension of type `T`, constructing it from `args` on first
363 /// use. `T` must derive from `Extension`.
364 template <typename T, typename... Args>
365 T &getOrCreateExtension(Args &&...args) {
366 static_assert(std::is_base_of<Extension, T>::value,
367 "expected T derived from ModuleTranslation::Extension");
368 TypeID id = TypeID::get<T>();
369 auto it = extensions.find(id);
370 if (it != extensions.end())
371 return static_cast<T &>(*it->second);
372 // Construct before inserting: the constructor may create other extensions.
373 auto extension = std::make_unique<T>(std::forward<Args>(args)...);
374 T &result = *extension;
375 extensions.insert({id, std::move(extension)});
376 return result;
377 }
378
379 SymbolTableCollection &symbolTable() { return symbolTableCollection; }
380
381 // A helper callback that takes an attribute, and if it is a StringAttr,
382 // properly converts it to the 'no-builtin-VALUE' form.
383 static std::optional<llvm::Attribute> convertNoBuiltin(llvm::LLVMContext &ctx,
385
386 static std::optional<llvm::Attribute>
387 convertDefaultFuncAttr(llvm::LLVMContext &ctx,
388 mlir::NamedAttribute namedAttr);
389
390 /// A template that takes a collection-like attribute, and converts it via a
391 /// user provided callback, then adds each element as function attributes to
392 /// the provided operation.
393 template <typename AttrsTy, typename Operation, typename Converter>
395 const Converter &conv) {
396 if (!attrs)
397 return;
398 for (auto elt : attrs) {
399 std::optional<llvm::Attribute> result = conv(getLLVMContext(), elt);
400 if (result)
401 op->addFnAttr(*result);
402 }
403 }
404
405 llvm::Attribute convertAllocsizeAttr(DenseI32ArrayAttr allocsizeAttr);
406
407private:
408 ModuleTranslation(Operation *module, std::unique_ptr<llvm::Module> llvmModule,
409 llvm::vfs::FileSystem *fs = nullptr);
411
412 /// Converts individual components.
413 LogicalResult convertOperationImpl(Operation &op,
414 llvm::IRBuilderBase &builder,
415 bool recordInsertions = false);
416 LogicalResult convertFunctionSignatures();
417 LogicalResult convertFunctionMetadata();
418 LogicalResult convertFunctions();
419 LogicalResult convertIFuncs();
420 LogicalResult convertComdats();
421
422 LogicalResult convertUnresolvedBlockAddress();
423
424 /// Handle conversion for both globals and global aliases.
425 ///
426 /// - Create named global variables that correspond to llvm.mlir.global
427 /// definitions, similarly Convert llvm.global_ctors and global_dtors ops.
428 /// - Create global alias that correspond to llvm.mlir.alias.
429 /// Global metadata that can reference other global objects (including
430 /// ifuncs) is converted later by `convertGlobalMetadata`.
431 LogicalResult convertGlobalsAndAliases();
432
433 /// Attach metadata on LLVM globals after all global objects exist so that
434 /// symbol references (globals, aliases, functions, and ifuncs) can be
435 /// resolved.
436 LogicalResult convertGlobalMetadata();
437 /// Converts a symbol ref to LLVM IR metadata, or fails if unresolved.
438 FailureOr<llvm::Metadata *>
439 convertSymbolRefToMetadata(FlatSymbolRefAttr name,
441 LogicalResult convertOneFunction(LLVMFuncOp func);
442 LogicalResult convertBlockImpl(Block &bb, bool ignoreArguments,
443 llvm::IRBuilderBase &builder,
444 bool recordInsertions);
445
446 /// Returns the LLVM metadata corresponding to the given mlir LLVM dialect
447 /// TBAATagAttr.
448 llvm::MDNode *getTBAANode(TBAATagAttr tbaaAttr) const;
449
450 /// Process tbaa LLVM Metadata operations and create LLVM
451 /// metadata nodes for them.
452 LogicalResult createTBAAMetadata();
453
454 /// Process the ident LLVM Metadata, if it exists.
455 LogicalResult createIdentMetadata();
456
457 /// Process the llvm.commandline LLVM Metadata, if it exists.
458 LogicalResult createCommandlineMetadata();
459
460 /// Process the llvm.dependent_libraries LLVM Metadata, if it exists.
461 LogicalResult createDependentLibrariesMetadata();
462
463 /// Translates dialect attributes attached to the given operation.
464 LogicalResult
465 convertDialectAttributes(Operation *op,
466 ArrayRef<llvm::Instruction *> instructions);
467
468 /// Translates parameter attributes of a call and adds them to the returned
469 /// AttrBuilder. Returns failure if any of the translations failed.
470 FailureOr<llvm::AttrBuilder> convertParameterAttrs(mlir::Location loc,
471 DictionaryAttr paramAttrs);
472
473 /// Translates parameter attributes of a function and adds them to the
474 /// returned AttrBuilder. Returns failure if any of the translations failed.
475 FailureOr<llvm::AttrBuilder>
476 convertParameterAttrs(LLVMFuncOp func, int argIdx, DictionaryAttr paramAttrs);
477
478 /// Original and translated module.
479 Operation *mlirModule;
480 std::unique_ptr<llvm::Module> llvmModule;
481 /// A converter for translating debug information.
482 std::unique_ptr<detail::DebugTranslation> debugTranslation;
483
484 /// A converter for translating loop annotations.
485 std::unique_ptr<detail::LoopAnnotationTranslation> loopAnnotationTranslation;
486
487 /// Translation-scoped state owned by dialect translations.
489
490 /// Optional virtual filesystem for file operations. When null, the real
491 /// filesystem is used (via getFileSystem()). Not owned.
492 llvm::vfs::FileSystem *fileSystem = nullptr;
493
494 /// Mappings between llvm.mlir.global definitions and corresponding globals.
496
497 /// Name-keyed mirror of `globalsMapping`, populated alongside it during
498 /// `convertGlobalsAndAliases`. Lets `getLLVMConstant` resolve
499 /// `FlatSymbolRefAttr` leaves of aggregate constants that name a global
500 /// (mirroring how `functionMapping` resolves function names).
501 llvm::StringMap<llvm::GlobalValue *> globalsByNameMapping;
502
503 /// Mappings between llvm.mlir.alias definitions and corresponding global
504 /// aliases.
506
507 /// Mappings between llvm.mlir.ifunc definitions and corresponding global
508 /// ifuncs.
510
511 /// A stateful object used to translate types.
512 TypeToLLVMIRTranslator typeTranslator;
513
514 /// A dialect interface collection used for dispatching the translation to
515 /// specific dialects.
517
518 /// Mappings between original and translated values, used for lookups.
519 llvm::StringMap<llvm::Function *> functionMapping;
522
523 /// A mapping between MLIR LLVM dialect terminators and LLVM IR terminators
524 /// they are converted to. This allows for connecting PHI nodes to the source
525 /// values after all operations are converted.
527
528 /// A mapping between MLIR LLVM dialect call operations and LLVM IR call
529 /// instructions. This allows for adding branch weights after the operations
530 /// have been converted.
532
533 /// Mapping from an alias scope attribute to its LLVM metadata.
534 /// This map is populated lazily.
535 DenseMap<AliasScopeAttr, llvm::MDNode *> aliasScopeMetadataMapping;
536
537 /// Mapping from an alias scope domain attribute to its LLVM metadata.
538 /// This map is populated lazily.
539 DenseMap<AliasScopeDomainAttr, llvm::MDNode *> aliasDomainMetadataMapping;
540
541 /// Mapping from a tbaa attribute to its LLVM metadata.
542 /// This map is populated on module entry.
543 DenseMap<Attribute, llvm::MDNode *> tbaaMetadataMapping;
544
545 /// Mapping from a comdat selector operation to its LLVM comdat struct.
546 /// This map is populated on module entry.
548
549 /// Mapping from llvm.blockaddress operations to their corresponding LLVM
550 /// constant placeholders. After all basic blocks are translated, this
551 /// mapping is used to replace the placeholders with the LLVM block addresses.
552 DenseMap<BlockAddressOp, llvm::Value *> unresolvedBlockAddressMapping;
553
554 /// Mapping from a BlockAddressAttr attribute to it's matching LLVM basic
555 /// block.
556 DenseMap<BlockAddressAttr, llvm::BasicBlock *> blockAddressToLLVMMapping;
557
558 /// Stack of user-specified state elements, useful when translating operations
559 /// with regions.
560 StateStack stack;
561
562 /// A cache for the symbol tables constructed during symbols lookup.
563 SymbolTableCollection symbolTableCollection;
564};
565
566namespace detail {
567/// For all blocks in the region that were converted to LLVM IR using the given
568/// ModuleTranslation, connect the PHI nodes of the corresponding LLVM IR blocks
569/// to the results of preceding blocks.
570void connectPHINodes(Region &region, const ModuleTranslation &state);
571
572/// Create an LLVM IR constant of `llvmType` from the MLIR attribute `attr`.
573/// This currently supports integer, floating point, splat and dense element
574/// attributes and combinations thereof. Also, an array attribute with two
575/// elements is supported to represent a complex constant. In case of error,
576/// report it to `loc` and return nullptr.
577llvm::Constant *getLLVMConstant(llvm::Type *llvmType, Attribute attr,
578 Location loc,
579 const ModuleTranslation &moduleTranslation);
580
581/// Creates a call to an LLVM IR intrinsic function with the given arguments.
582llvm::CallInst *createIntrinsicCall(llvm::IRBuilderBase &builder,
583 llvm::Intrinsic::ID intrinsic,
584 ArrayRef<llvm::Value *> args = {},
585 ArrayRef<llvm::Type *> tys = {});
586
587/// Creates a call to an LLVM IR intrinsic function with the given return type
588/// and arguments. If the intrinsic is overloaded, the function signature will
589/// be automatically resolved based on the provided return type and argument
590/// types.
591llvm::CallInst *createIntrinsicCall(llvm::IRBuilderBase &builder,
592 llvm::Intrinsic::ID intrinsic,
593 llvm::Type *retTy,
594 ArrayRef<llvm::Value *> args);
595
596/// Creates a call to a LLVM IR intrinsic defined by LLVM_IntrOpBase. This
597/// resolves the overloads, and maps mixed MLIR value and attribute arguments to
598/// LLVM values.
599llvm::CallInst *createIntrinsicCall(
600 llvm::IRBuilderBase &builder, ModuleTranslation &moduleTranslation,
601 Operation *intrOp, llvm::Intrinsic::ID intrinsic, unsigned numResults,
602 ArrayRef<unsigned> overloadedResults, ArrayRef<unsigned> overloadedOperands,
603 ArrayRef<unsigned> immArgPositions,
604 ArrayRef<StringLiteral> immArgAttrNames);
605
606} // namespace detail
607
608} // namespace LLVM
609} // namespace mlir
610
611#endif // MLIR_TARGET_LLVMIR_MODULETRANSLATION_H
return success()
static LogicalResult convertOperationImpl(Operation &opInst, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
ArrayAttr()
Attributes are known-constant values of operations.
Definition Attributes.h:25
Block represents an ordered list of Operations.
Definition Block.h:34
A symbol reference with a reference path containing a single element.
This class represents a diagnostic that is inflight and set to be reported.
Interface collection for translation to LLVM IR, dispatches to a concrete interface implementation ba...
This class represents the base attribute for all debug info attributes.
Definition LLVMAttrs.h:29
Base class for state that lives as long as the module translation.
virtual LogicalResult finalize()
Called once after all operations have been translated and before the LLVM module is verified.
Implementation class for module translation.
void mapUnresolvedBlockAddress(BlockAddressOp op, llvm::Value *cst)
Maps a blockaddress operation to its corresponding placeholder LLVM value.
llvm::fp::ExceptionBehavior translateFPExceptionBehavior(LLVM::FPExceptionBehavior exceptionBehavior)
Translates the given LLVM FP exception behavior metadata.
llvm::CallInst * lookupCall(Operation *op) const
Finds an LLVM call instruction that corresponds to the given MLIR call operation.
void mapCall(Operation *mlir, llvm::CallInst *llvm)
Stores a mapping between an MLIR call operation and a corresponding LLVM call instruction.
llvm::BasicBlock * lookupBlock(Block *block) const
Finds an LLVM IR basic block that corresponds to the given MLIR block.
llvm::DIGlobalVariableExpression * translateGlobalVariableExpression(LLVM::DIGlobalVariableExpressionAttr attr)
Translates the given LLVM global variable expression metadata.
llvm::Attribute convertAllocsizeAttr(DenseI32ArrayAttr allocsizeAttr)
MLIRContext & getContext()
Returns the MLIR context of the module being translated.
WalkResult stackWalk(llvm::function_ref< WalkResult(T &)> callback)
Calls callback for every ModuleTranslation stack frame of type T starting from the top of the stack.
void stackPush(Args &&...args)
Creates a stack frame of type T on ModuleTranslation stack.
llvm::NamedMDNode * getOrInsertNamedModuleMetadata(StringRef name)
Gets the named metadata in the LLVM IR module being constructed, creating it if it does not exist.
LogicalResult convertBlock(Block &bb, bool ignoreArguments, llvm::IRBuilderBase &builder)
Translates the contents of the given block to LLVM IR using this translator.
void mapBranch(Operation *mlir, llvm::Instruction *llvm)
Stores the mapping between an MLIR operation with successors and a corresponding LLVM IR instruction.
SmallVector< llvm::Value * > lookupValues(ValueRange values)
Looks up remapped a list of remapped values.
void mapFunction(StringRef name, llvm::Function *func)
Stores the mapping between a function name and its LLVM IR representation.
void convertFunctionAttrCollection(AttrsTy attrs, Operation *op, const Converter &conv)
A template that takes a collection-like attribute, and converts it via a user provided callback,...
llvm::DILocation * translateLoc(Location loc, llvm::DILocalScope *scope)
Translates the given location.
void setDereferenceableMetadata(DereferenceableOpInterface op, llvm::Instruction *inst)
Sets LLVM dereferenceable metadata for operations that have dereferenceable attributes.
void setBranchWeightsMetadata(WeightedBranchOpInterface op)
Sets LLVM profiling metadata for operations that have branch weights.
llvm::Instruction * lookupBranch(Operation *op) const
Finds an LLVM IR instruction that corresponds to the given MLIR operation with successors.
T & getOrCreateExtension(Args &&...args)
Returns the extension of type T, constructing it from args on first use.
llvm::Value * lookupValue(Value value) const
Finds an LLVM IR value corresponding to the given MLIR value.
LogicalResult convertArgAndResultAttrs(ArgAndResultAttrsOpInterface attrsOp, llvm::CallBase *call, ArrayRef< unsigned > immArgPositions={})
Converts argument and result attributes from attrsOp to LLVM IR attributes on the call instruction.
static std::optional< llvm::Attribute > convertNoBuiltin(llvm::LLVMContext &ctx, mlir::Attribute a)
SymbolTableCollection & symbolTable()
llvm::Type * convertType(Type type)
Converts the type from MLIR LLVM dialect to LLVM.
llvm::Value *& mapValue(Value value)
Provides write-once access to store the LLVM IR value corresponding to the given MLIR value.
llvm::RoundingMode translateRoundingMode(LLVM::RoundingMode rounding)
Translates the given LLVM rounding mode metadata.
void setTBAAMetadata(AliasAnalysisOpInterface op, llvm::Instruction *inst)
Sets LLVM TBAA metadata for memory operations that have TBAA attributes.
llvm::DIExpression * translateExpression(LLVM::DIExpressionAttr attr)
Translates the given LLVM DWARF expression metadata.
llvm::vfs::FileSystem & getFileSystem()
Returns the virtual filesystem to use for file operations.
llvm::GlobalValue * lookupGlobal(Operation *op)
Finds an LLVM IR global value that corresponds to the given MLIR operation defining a global value.
llvm::GlobalValue * lookupGlobal(StringRef name) const
Finds an LLVM IR global value by the mlir.global symbol name.
void forgetMapping(Value value)
Removes the mapping for the given value.
FailureOr< llvm::Metadata * > convertMetadataAttr(Attribute attr, function_ref< InFlightDiagnostic()> emitError)
Converts an LLVM dialect metadata attribute to LLVM IR metadata.
SaveStateStack< T, ModuleTranslation > SaveStack
RAII object calling stackPush/stackPop on construction/destruction.
llvm::BasicBlock * lookupBlockAddress(BlockAddressAttr attr) const
Finds the LLVM basic block that corresponds to the given BlockAddressAttr.
void remapAllValuesWith(llvm::Value *oldValue, llvm::Value *newValue)
Remap old value with new value in the MLIR-to-LLVM value map so later translations use the replacemen...
void setTBAAStructMetadata(ArrayAttr fields, llvm::Instruction *inst)
Sets LLVM tbaa.struct metadata on an aggregate copy, describing which fields of the aggregate the cop...
llvm::GlobalValue * lookupIFunc(Operation *op)
Finds an LLVM IR global value that corresponds to the given MLIR operation defining an IFunc.
llvm::Metadata * translateDebugInfo(LLVM::DINodeAttr attr)
Translates the given LLVM debug info metadata.
void setDisjointFlag(Operation *op, llvm::Value *value)
Sets the disjoint flag attribute for the exported instruction value given the original operation op.
llvm::GlobalValue * lookupAlias(Operation *op)
Finds an LLVM IR global value that corresponds to the given MLIR operation defining a global alias va...
LogicalResult convertOperation(Operation &op, llvm::IRBuilderBase &builder)
Converts the given MLIR operation into LLVM IR using this translator.
llvm::Function * lookupFunction(StringRef name) const
Finds an LLVM IR function by its name.
llvm::MDNode * getOrCreateAliasScopes(ArrayRef< AliasScopeAttr > aliasScopeAttrs)
Returns the LLVM metadata corresponding to an array of mlir LLVM dialect alias scope attributes.
void mapBlock(Block *mlir, llvm::BasicBlock *llvm)
Stores the mapping between an MLIR block and LLVM IR basic block.
llvm::MDNode * getOrCreateAliasScope(AliasScopeAttr aliasScopeAttr)
Returns the LLVM metadata corresponding to a mlir LLVM dialect alias scope attribute.
llvm::Module * getLLVMModule()
Returns the LLVM module in which the IR is being constructed.
static std::optional< llvm::Attribute > convertDefaultFuncAttr(llvm::LLVMContext &ctx, mlir::NamedAttribute namedAttr)
void stackPop()
Pops the last element from the ModuleTranslation stack.
void forgetMapping(Region &region)
Removes the mapping for blocks contained in the region and values defined in these blocks.
void setAliasScopeMetadata(AliasAnalysisOpInterface op, llvm::Instruction *inst)
void setAccessGroupsMetadata(AccessGroupOpInterface op, llvm::Instruction *inst)
void mapValue(Value mlir, llvm::Value *llvm)
Stores the mapping between an MLIR value and its LLVM IR counterpart.
llvm::LLVMContext & getLLVMContext() const
Returns the LLVM context in which the IR is being constructed.
void mapBlockAddress(BlockAddressAttr attr, llvm::BasicBlock *block)
Maps a BlockAddressAttr to its corresponding LLVM basic block.
void setLoopMetadata(Operation *op, llvm::Instruction *inst)
Sets LLVM loop metadata for branch operations that have a loop annotation attribute.
Utility class to translate MLIR LLVM dialect types to LLVM IR.
Definition TypeToLLVM.h:39
A helper class that converts LoopAnnotationAttrs and AccessGroupAttrs into corresponding llvm::MDNode...
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
NamedAttribute represents a combination of a name and an Attribute value.
Definition Attributes.h:166
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
This class contains a list of basic blocks and a link to the parent operation it is attached to.
Definition Region.h:26
This class represents a collection of SymbolTables.
This class provides an efficient unique identifier for a specific C++ type.
Definition TypeID.h:107
static TypeID get()
Construct a type info object for the given type T.
Definition TypeID.h:245
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
This class provides an abstraction over the different types of ranges over Values.
Definition ValueRange.h:392
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
A utility result that is used to signal how to proceed with an ongoing walk:
Definition WalkResult.h:29
The OpAsmOpInterface, see OpAsmInterface.td for more details.
Definition CallGraph.h:229
void connectPHINodes(Region &region, const ModuleTranslation &state)
For all blocks in the region that were converted to LLVM IR using the given ModuleTranslation,...
llvm::CallInst * createIntrinsicCall(llvm::IRBuilderBase &builder, llvm::Intrinsic::ID intrinsic, ArrayRef< llvm::Value * > args={}, ArrayRef< llvm::Type * > tys={})
Creates a call to an LLVM IR intrinsic function with the given arguments.
llvm::Constant * getLLVMConstant(llvm::Type *llvmType, Attribute attr, Location loc, const ModuleTranslation &moduleTranslation)
Create an LLVM IR constant of llvmType from the MLIR attribute attr.
AttrTypeReplacer.
Include the generated interface declarations.
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
detail::DenseArrayAttrImpl< int32_t > DenseI32ArrayAttr
std::unique_ptr< llvm::Module > translateModuleToLLVMIR(Operation *module, llvm::LLVMContext &llvmContext, llvm::StringRef name="LLVMDialectModule", bool disableVerification=false, llvm::vfs::FileSystem *fs=nullptr)
Translates a given LLVM dialect module into an LLVM IR module living in the given context.
llvm::DenseMap< KeyT, ValueT, KeyInfoT, BucketT > DenseMap
Definition LLVM.h:123
llvm::function_ref< Fn > function_ref
Definition LLVM.h:155
RAII object calling stackPush/stackPop on construction/destruction.
Definition StateStack.h:106