MLIR 23.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
19#include "mlir/IR/Operation.h"
20#include "mlir/IR/SymbolTable.h"
21#include "mlir/IR/Value.h"
26
27#include "llvm/ADT/SetVector.h"
28#include "llvm/IR/FPEnv.h"
29#include "llvm/IR/Module.h"
30
31namespace llvm {
32class BasicBlock;
33class CallBase;
34class CanonicalLoopInfo;
35class Function;
36class IRBuilderBase;
37class OpenMPIRBuilder;
38class Value;
39namespace vfs {
40class FileSystem;
41} // namespace vfs
42} // namespace llvm
43
44namespace mlir {
45class Attribute;
46class Block;
47class Location;
48
49namespace LLVM {
50
51namespace detail {
54} // namespace detail
55
56class AliasScopeAttr;
57class AliasScopeDomainAttr;
58class DINodeAttr;
59class LLVMFuncOp;
60class ComdatSelectorOp;
61
62/// Implementation class for module translation. Holds a reference to the module
63/// being translated, and the mappings between the original and the translated
64/// functions, basic blocks and values. It is practically easier to hold these
65/// mappings in one class since the conversion of control flow operations
66/// needs to look up block and function mappings.
67class ModuleTranslation {
68 friend std::unique_ptr<llvm::Module>
69 mlir::translateModuleToLLVMIR(Operation *, llvm::LLVMContext &, StringRef,
70 bool, llvm::vfs::FileSystem *);
71
72public:
73 /// Stores the mapping between a function name and its LLVM IR representation.
74 void mapFunction(StringRef name, llvm::Function *func) {
75 auto result = functionMapping.try_emplace(name, func);
76 (void)result;
77 assert(result.second &&
78 "attempting to map a function that is already mapped");
79 }
80
81 /// Finds an LLVM IR function by its name.
82 llvm::Function *lookupFunction(StringRef name) const {
83 return functionMapping.lookup(name);
84 }
85
86 /// Stores the mapping between an MLIR value and its LLVM IR counterpart.
87 void mapValue(Value mlir, llvm::Value *llvm) { mapValue(mlir) = llvm; }
88
89 /// Provides write-once access to store the LLVM IR value corresponding to the
90 /// given MLIR value.
91 llvm::Value *&mapValue(Value value) {
92 llvm::Value *&llvm = valueMapping[value];
93 assert(llvm == nullptr &&
94 "attempting to map a value that is already mapped");
95 return llvm;
96 }
97
98 /// Finds an LLVM IR value corresponding to the given MLIR value.
99 llvm::Value *lookupValue(Value value) const {
100 return valueMapping.lookup(value);
101 }
102
103 /// Looks up remapped a list of remapped values.
105
106 /// Stores the mapping between an MLIR block and LLVM IR basic block.
107 void mapBlock(Block *mlir, llvm::BasicBlock *llvm) {
108 auto result = blockMapping.try_emplace(mlir, llvm);
109 (void)result;
110 assert(result.second && "attempting to map a block that is already mapped");
111 }
112
113 /// Finds an LLVM IR basic block that corresponds to the given MLIR block.
114 llvm::BasicBlock *lookupBlock(Block *block) const {
115 return blockMapping.lookup(block);
116 }
117
118 /// Find the LLVM-IR loop that represents an MLIR loop.
119 llvm::CanonicalLoopInfo *lookupOMPLoop(omp::NewCliOp mlir) const {
120 llvm::CanonicalLoopInfo *result = loopMapping.lookup(mlir);
121 assert(result && "attempt to get non-existing loop");
122 return result;
123 }
124
125 /// Find the LLVM-IR loop that represents an MLIR loop.
126 llvm::CanonicalLoopInfo *lookupOMPLoop(Value mlir) const {
127 return lookupOMPLoop(mlir.getDefiningOp<omp::NewCliOp>());
128 }
129
130 /// Mark an OpenMP loop as having been consumed.
131 void invalidateOmpLoop(omp::NewCliOp mlir) { loopMapping.erase(mlir); }
132
133 /// Mark an OpenMP loop as having been consumed.
135 invalidateOmpLoop(mlir.getDefiningOp<omp::NewCliOp>());
136 }
137
138 /// Map an MLIR OpenMP dialect CanonicalLoopInfo to its lowered LLVM-IR
139 /// OpenMPIRBuilder CanonicalLoopInfo
140 void mapOmpLoop(omp::NewCliOp mlir, llvm::CanonicalLoopInfo *llvm) {
141 assert(llvm && "argument must be non-null");
142 llvm::CanonicalLoopInfo *&cur = loopMapping[mlir];
143 assert(cur == nullptr && "attempting to map a loop that is already mapped");
144 cur = llvm;
145 }
146
147 /// Map an MLIR OpenMP dialect CanonicalLoopInfo to its lowered LLVM-IR
148 /// OpenMPIRBuilder CanonicalLoopInfo
149 void mapOmpLoop(Value mlir, llvm::CanonicalLoopInfo *llvm) {
150 mapOmpLoop(mlir.getDefiningOp<omp::NewCliOp>(), llvm);
151 }
152
153 /// Stores the mapping between an MLIR operation with successors and a
154 /// corresponding LLVM IR instruction.
155 void mapBranch(Operation *mlir, llvm::Instruction *llvm) {
156 auto result = branchMapping.try_emplace(mlir, llvm);
157 (void)result;
158 assert(result.second &&
159 "attempting to map a branch that is already mapped");
160 }
161
162 /// Finds an LLVM IR instruction that corresponds to the given MLIR operation
163 /// with successors.
164 llvm::Instruction *lookupBranch(Operation *op) const {
165 return branchMapping.lookup(op);
166 }
167
168 /// Stores a mapping between an MLIR call operation and a corresponding LLVM
169 /// call instruction.
170 void mapCall(Operation *mlir, llvm::CallInst *llvm) {
171 auto result = callMapping.try_emplace(mlir, llvm);
172 (void)result;
173 assert(result.second && "attempting to map a call that is already mapped");
174 }
175
176 /// Finds an LLVM call instruction that corresponds to the given MLIR call
177 /// operation.
178 llvm::CallInst *lookupCall(Operation *op) const {
179 return callMapping.lookup(op);
180 }
181
182 /// Maps a blockaddress operation to its corresponding placeholder LLVM
183 /// value.
184 void mapUnresolvedBlockAddress(BlockAddressOp op, llvm::Value *cst) {
185 auto result = unresolvedBlockAddressMapping.try_emplace(op, cst);
186 (void)result;
187 assert(result.second &&
188 "attempting to map a blockaddress operation that is already mapped");
189 }
190
191 /// Maps a BlockAddressAttr to its corresponding LLVM basic block.
192 void mapBlockAddress(BlockAddressAttr attr, llvm::BasicBlock *block) {
193 auto result = blockAddressToLLVMMapping.try_emplace(attr, block);
194 (void)result;
195 assert(result.second &&
196 "attempting to map a blockaddress attribute that is already mapped");
197 }
198
199 /// Finds the LLVM basic block that corresponds to the given BlockAddressAttr.
200 llvm::BasicBlock *lookupBlockAddress(BlockAddressAttr attr) const {
201 return blockAddressToLLVMMapping.lookup(attr);
202 }
203
204 /// Removes the mapping for blocks contained in the region and values defined
205 /// in these blocks.
206 void forgetMapping(Region &region);
207
208 /// Removes the mapping for the given value.
209 void forgetMapping(Value value) { valueMapping.erase(value); }
210
211 /// Returns the LLVM metadata corresponding to a mlir LLVM dialect alias scope
212 /// attribute. Creates the metadata node if it has not been converted before.
213 llvm::MDNode *getOrCreateAliasScope(AliasScopeAttr aliasScopeAttr);
214
215 /// Returns the LLVM metadata corresponding to an array of mlir LLVM dialect
216 /// alias scope attributes. Creates the metadata nodes if they have not been
217 /// converted before.
218 llvm::MDNode *
220
221 // Sets LLVM metadata for memory operations that are in a parallel loop.
222 void setAccessGroupsMetadata(AccessGroupOpInterface op,
223 llvm::Instruction *inst);
224
225 // Sets LLVM metadata for memory operations that have alias scope information.
226 void setAliasScopeMetadata(AliasAnalysisOpInterface op,
227 llvm::Instruction *inst);
228
229 /// Sets LLVM TBAA metadata for memory operations that have TBAA attributes.
230 void setTBAAMetadata(AliasAnalysisOpInterface op, llvm::Instruction *inst);
231
232 /// Sets LLVM dereferenceable metadata for operations that have
233 /// dereferenceable attributes.
234 void setDereferenceableMetadata(DereferenceableOpInterface op,
235 llvm::Instruction *inst);
236
237 /// Sets LLVM profiling metadata for operations that have branch weights.
238 void setBranchWeightsMetadata(WeightedBranchOpInterface op);
239
240 /// Sets LLVM loop metadata for branch operations that have a loop annotation
241 /// attribute.
242 void setLoopMetadata(Operation *op, llvm::Instruction *inst);
243
244 /// Sets the disjoint flag attribute for the exported instruction `value`
245 /// given the original operation `op`. Asserts if the operation does
246 /// not implement the disjoint flag interface, and asserts if the value
247 /// is an instruction that implements the disjoint flag.
248 void setDisjointFlag(Operation *op, llvm::Value *value);
249
250 /// Converts the type from MLIR LLVM dialect to LLVM.
251 llvm::Type *convertType(Type type);
252
253 /// Returns the MLIR context of the module being translated.
254 MLIRContext &getContext() { return *mlirModule->getContext(); }
255
256 /// Returns the LLVM context in which the IR is being constructed.
257 llvm::LLVMContext &getLLVMContext() const { return llvmModule->getContext(); }
258
259 /// Finds an LLVM IR global value that corresponds to the given MLIR operation
260 /// defining a global value.
261 llvm::GlobalValue *lookupGlobal(Operation *op) {
262 return globalsMapping.lookup(op);
263 }
264
265 /// Finds an LLVM IR global value that corresponds to the given MLIR operation
266 /// defining a global alias value.
267 llvm::GlobalValue *lookupAlias(Operation *op) {
268 return aliasesMapping.lookup(op);
269 }
270
271 /// Finds an LLVM IR global value that corresponds to the given MLIR operation
272 /// defining an IFunc.
273 llvm::GlobalValue *lookupIFunc(Operation *op) {
274 return ifuncMapping.lookup(op);
275 }
276
277 /// Returns the OpenMP IR builder associated with the LLVM IR module being
278 /// constructed.
279 llvm::OpenMPIRBuilder *getOpenMPBuilder();
280
281 /// Returns the virtual filesystem to use for file operations. Falls back to
282 /// the real filesystem if none was provided.
283 llvm::vfs::FileSystem &getFileSystem();
284
285 /// Returns the LLVM module in which the IR is being constructed.
286 llvm::Module *getLLVMModule() { return llvmModule.get(); }
287
288 /// Translates the given location.
289 llvm::DILocation *translateLoc(Location loc, llvm::DILocalScope *scope);
290
291 /// Translates the given LLVM DWARF expression metadata.
292 llvm::DIExpression *translateExpression(LLVM::DIExpressionAttr attr);
293
294 /// Translates the given LLVM global variable expression metadata.
295 llvm::DIGlobalVariableExpression *
296 translateGlobalVariableExpression(LLVM::DIGlobalVariableExpressionAttr attr);
297
298 /// Translates the given LLVM debug info metadata.
299 llvm::Metadata *translateDebugInfo(LLVM::DINodeAttr attr);
300
301 /// Translates the given LLVM rounding mode metadata.
302 llvm::RoundingMode translateRoundingMode(LLVM::RoundingMode rounding);
303
304 /// Translates the given LLVM FP exception behavior metadata.
305 llvm::fp::ExceptionBehavior
306 translateFPExceptionBehavior(LLVM::FPExceptionBehavior exceptionBehavior);
307
308 /// Translates the contents of the given block to LLVM IR using this
309 /// translator. The LLVM IR basic block corresponding to the given block is
310 /// expected to exist in the mapping of this translator. Uses `builder` to
311 /// translate the IR, leaving it at the end of the block. If `ignoreArguments`
312 /// is set, does not produce PHI nodes for the block arguments. Otherwise, the
313 /// PHI nodes are constructed for block arguments but are _not_ connected to
314 /// the predecessors that may not exist yet.
315 LogicalResult convertBlock(Block &bb, bool ignoreArguments,
316 llvm::IRBuilderBase &builder) {
317 return convertBlockImpl(bb, ignoreArguments, builder,
318 /*recordInsertions=*/false);
319 }
320
321 /// Converts the given MLIR operation into LLVM IR using this translator. It
322 /// is up to the caller to ensure that all operands have been mapped before
323 /// calling this function.
324 LogicalResult convertOperation(Operation &op, llvm::IRBuilderBase &builder) {
325 return convertOperationImpl(op, builder, /*recordInsertions=*/false);
326 }
327
328 /// Converts argument and result attributes from `attrsOp` to LLVM IR
329 /// attributes on the `call` instruction. Returns failure if conversion fails.
330 /// The `immArgPositions` parameter is only relevant for intrinsics. It
331 /// specifies the positions of immediate arguments, which do not have
332 /// associated argument attributes in MLIR and should be skipped during
333 /// attribute mapping.
334 LogicalResult
335 convertArgAndResultAttrs(ArgAndResultAttrsOpInterface attrsOp,
336 llvm::CallBase *call,
337 ArrayRef<unsigned> immArgPositions = {});
338
339 /// Gets the named metadata in the LLVM IR module being constructed, creating
340 /// it if it does not exist.
341 llvm::NamedMDNode *getOrInsertNamedModuleMetadata(StringRef name);
342
343 /// Creates a stack frame of type `T` on ModuleTranslation stack. `T` must
344 /// be derived from `StackFrameBase<T>` and constructible from the provided
345 /// arguments. Doing this before entering the region of the op being
346 /// translated makes the frame available when translating ops within that
347 /// region.
348 template <typename T, typename... Args>
349 void stackPush(Args &&...args) {
350 stack.stackPush<T>(std::forward<Args>(args)...);
351 }
352
353 /// Pops the last element from the ModuleTranslation stack.
354 void stackPop() { stack.stackPop(); }
355
356 /// Calls `callback` for every ModuleTranslation stack frame of type `T`
357 /// starting from the top of the stack.
358 template <typename T>
360 return stack.stackWalk(callback);
361 }
362
363 /// RAII object calling stackPush/stackPop on construction/destruction.
364 template <typename T>
366
367 SymbolTableCollection &symbolTable() { return symbolTableCollection; }
368
369 // A helper callback that takes an attribute, and if it is a StringAttr,
370 // properly converts it to the 'no-builtin-VALUE' form.
371 static std::optional<llvm::Attribute> convertNoBuiltin(llvm::LLVMContext &ctx,
373
374 static std::optional<llvm::Attribute>
375 convertDefaultFuncAttr(llvm::LLVMContext &ctx,
376 mlir::NamedAttribute namedAttr);
377
378 /// A template that takes a collection-like attribute, and converts it via a
379 /// user provided callback, then adds each element as function attributes to
380 /// the provided operation.
381 template <typename AttrsTy, typename Operation, typename Converter>
383 const Converter &conv) {
384 if (!attrs)
385 return;
386 for (auto elt : attrs) {
387 std::optional<llvm::Attribute> result = conv(getLLVMContext(), elt);
388 if (result)
389 op->addFnAttr(*result);
390 }
391 }
392
393 llvm::Attribute convertAllocsizeAttr(DenseI32ArrayAttr allocsizeAttr);
394
395private:
396 ModuleTranslation(Operation *module, std::unique_ptr<llvm::Module> llvmModule,
397 llvm::vfs::FileSystem *fs = nullptr);
399
400 /// Converts individual components.
401 LogicalResult convertOperationImpl(Operation &op,
402 llvm::IRBuilderBase &builder,
403 bool recordInsertions = false);
404 LogicalResult convertFunctionSignatures();
405 LogicalResult convertFunctions();
406 LogicalResult convertIFuncs();
407 LogicalResult convertComdats();
408
409 LogicalResult convertUnresolvedBlockAddress();
410
411 /// Handle conversion for both globals and global aliases.
412 ///
413 /// - Create named global variables that correspond to llvm.mlir.global
414 /// definitions, similarly Convert llvm.global_ctors and global_dtors ops.
415 /// - Create global alias that correspond to llvm.mlir.alias.
416 LogicalResult convertGlobalsAndAliases();
417 LogicalResult convertOneFunction(LLVMFuncOp func);
418 LogicalResult convertBlockImpl(Block &bb, bool ignoreArguments,
419 llvm::IRBuilderBase &builder,
420 bool recordInsertions);
421
422 /// Returns the LLVM metadata corresponding to the given mlir LLVM dialect
423 /// TBAATagAttr.
424 llvm::MDNode *getTBAANode(TBAATagAttr tbaaAttr) const;
425
426 /// Process tbaa LLVM Metadata operations and create LLVM
427 /// metadata nodes for them.
428 LogicalResult createTBAAMetadata();
429
430 /// Process the ident LLVM Metadata, if it exists.
431 LogicalResult createIdentMetadata();
432
433 /// Process the llvm.commandline LLVM Metadata, if it exists.
434 LogicalResult createCommandlineMetadata();
435
436 /// Process the llvm.dependent_libraries LLVM Metadata, if it exists.
437 LogicalResult createDependentLibrariesMetadata();
438
439 /// Translates dialect attributes attached to the given operation.
440 LogicalResult
441 convertDialectAttributes(Operation *op,
442 ArrayRef<llvm::Instruction *> instructions);
443
444 /// Translates parameter attributes of a call and adds them to the returned
445 /// AttrBuilder. Returns failure if any of the translations failed.
446 FailureOr<llvm::AttrBuilder> convertParameterAttrs(mlir::Location loc,
447 DictionaryAttr paramAttrs);
448
449 /// Translates parameter attributes of a function and adds them to the
450 /// returned AttrBuilder. Returns failure if any of the translations failed.
451 FailureOr<llvm::AttrBuilder>
452 convertParameterAttrs(LLVMFuncOp func, int argIdx, DictionaryAttr paramAttrs);
453
454 /// Original and translated module.
455 Operation *mlirModule;
456 std::unique_ptr<llvm::Module> llvmModule;
457 /// A converter for translating debug information.
458 std::unique_ptr<detail::DebugTranslation> debugTranslation;
459
460 /// A converter for translating loop annotations.
461 std::unique_ptr<detail::LoopAnnotationTranslation> loopAnnotationTranslation;
462
463 /// Builder for LLVM IR generation of OpenMP constructs.
464 std::unique_ptr<llvm::OpenMPIRBuilder> ompBuilder;
465
466 /// Optional virtual filesystem for file operations. When null, the real
467 /// filesystem is used (via getFileSystem()). Not owned.
468 llvm::vfs::FileSystem *fileSystem = nullptr;
469
470 /// Mappings between llvm.mlir.global definitions and corresponding globals.
472
473 /// Mappings between llvm.mlir.alias definitions and corresponding global
474 /// aliases.
476
477 /// Mappings between llvm.mlir.ifunc definitions and corresponding global
478 /// ifuncs.
480
481 /// A stateful object used to translate types.
482 TypeToLLVMIRTranslator typeTranslator;
483
484 /// A dialect interface collection used for dispatching the translation to
485 /// specific dialects.
487
488 /// Mappings between original and translated values, used for lookups.
489 llvm::StringMap<llvm::Function *> functionMapping;
492
493 /// List of not yet consumed MLIR loop handles (represented by an omp.new_cli
494 /// operation which creates a value of type CanonicalLoopInfoType) and their
495 /// LLVM-IR representation as CanonicalLoopInfo which is managed by the
496 /// OpenMPIRBuilder.
498
499 /// A mapping between MLIR LLVM dialect terminators and LLVM IR terminators
500 /// they are converted to. This allows for connecting PHI nodes to the source
501 /// values after all operations are converted.
503
504 /// A mapping between MLIR LLVM dialect call operations and LLVM IR call
505 /// instructions. This allows for adding branch weights after the operations
506 /// have been converted.
508
509 /// Mapping from an alias scope attribute to its LLVM metadata.
510 /// This map is populated lazily.
511 DenseMap<AliasScopeAttr, llvm::MDNode *> aliasScopeMetadataMapping;
512
513 /// Mapping from an alias scope domain attribute to its LLVM metadata.
514 /// This map is populated lazily.
515 DenseMap<AliasScopeDomainAttr, llvm::MDNode *> aliasDomainMetadataMapping;
516
517 /// Mapping from a tbaa attribute to its LLVM metadata.
518 /// This map is populated on module entry.
519 DenseMap<Attribute, llvm::MDNode *> tbaaMetadataMapping;
520
521 /// Mapping from a comdat selector operation to its LLVM comdat struct.
522 /// This map is populated on module entry.
524
525 /// Mapping from llvm.blockaddress operations to their corresponding LLVM
526 /// constant placeholders. After all basic blocks are translated, this
527 /// mapping is used to replace the placeholders with the LLVM block addresses.
528 DenseMap<BlockAddressOp, llvm::Value *> unresolvedBlockAddressMapping;
529
530 /// Mapping from a BlockAddressAttr attribute to it's matching LLVM basic
531 /// block.
532 DenseMap<BlockAddressAttr, llvm::BasicBlock *> blockAddressToLLVMMapping;
533
534 /// Stack of user-specified state elements, useful when translating operations
535 /// with regions.
536 StateStack stack;
537
538 /// A cache for the symbol tables constructed during symbols lookup.
539 SymbolTableCollection symbolTableCollection;
540};
541
542namespace detail {
543/// For all blocks in the region that were converted to LLVM IR using the given
544/// ModuleTranslation, connect the PHI nodes of the corresponding LLVM IR blocks
545/// to the results of preceding blocks.
546void connectPHINodes(Region &region, const ModuleTranslation &state);
547
548/// Create an LLVM IR constant of `llvmType` from the MLIR attribute `attr`.
549/// This currently supports integer, floating point, splat and dense element
550/// attributes and combinations thereof. Also, an array attribute with two
551/// elements is supported to represent a complex constant. In case of error,
552/// report it to `loc` and return nullptr.
553llvm::Constant *getLLVMConstant(llvm::Type *llvmType, Attribute attr,
554 Location loc,
555 const ModuleTranslation &moduleTranslation);
556
557/// Creates a call to an LLVM IR intrinsic function with the given arguments.
558llvm::CallInst *createIntrinsicCall(llvm::IRBuilderBase &builder,
559 llvm::Intrinsic::ID intrinsic,
560 ArrayRef<llvm::Value *> args = {},
561 ArrayRef<llvm::Type *> tys = {});
562
563/// Creates a call to an LLVM IR intrinsic function with the given return type
564/// and arguments. If the intrinsic is overloaded, the function signature will
565/// be automatically resolved based on the provided return type and argument
566/// types.
567llvm::CallInst *createIntrinsicCall(llvm::IRBuilderBase &builder,
568 llvm::Intrinsic::ID intrinsic,
569 llvm::Type *retTy,
570 ArrayRef<llvm::Value *> args);
571
572/// Creates a call to a LLVM IR intrinsic defined by LLVM_IntrOpBase. This
573/// resolves the overloads, and maps mixed MLIR value and attribute arguments to
574/// LLVM values.
575llvm::CallInst *createIntrinsicCall(
576 llvm::IRBuilderBase &builder, ModuleTranslation &moduleTranslation,
577 Operation *intrOp, llvm::Intrinsic::ID intrinsic, unsigned numResults,
578 ArrayRef<unsigned> overloadedResults, ArrayRef<unsigned> overloadedOperands,
579 ArrayRef<unsigned> immArgPositions,
580 ArrayRef<StringLiteral> immArgAttrNames);
581
582} // namespace detail
583
584} // namespace LLVM
585} // namespace mlir
586
587#endif // MLIR_TARGET_LLVMIR_MODULETRANSLATION_H
static LogicalResult convertOperationImpl(Operation &opInst, llvm::IRBuilderBase &builder, LLVM::ModuleTranslation &moduleTranslation)
Attributes are known-constant values of operations.
Definition Attributes.h:25
Block represents an ordered list of Operations.
Definition Block.h:33
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
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.
void mapOmpLoop(Value mlir, llvm::CanonicalLoopInfo *llvm)
Map an MLIR OpenMP dialect CanonicalLoopInfo to its lowered LLVM-IR OpenMPIRBuilder CanonicalLoopInfo...
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.
llvm::Value * lookupValue(Value value) const
Finds an LLVM IR value corresponding to the given MLIR value.
void invalidateOmpLoop(omp::NewCliOp mlir)
Mark an OpenMP loop as having been consumed.
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.
void invalidateOmpLoop(Value mlir)
Mark an OpenMP loop as having been consumed.
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::OpenMPIRBuilder * getOpenMPBuilder()
Returns the OpenMP IR builder associated with the LLVM IR module being constructed.
llvm::vfs::FileSystem & getFileSystem()
Returns the virtual filesystem to use for file operations.
void mapOmpLoop(omp::NewCliOp mlir, llvm::CanonicalLoopInfo *llvm)
Map an MLIR OpenMP dialect CanonicalLoopInfo to its lowered LLVM-IR OpenMPIRBuilder CanonicalLoopInfo...
llvm::GlobalValue * lookupGlobal(Operation *op)
Finds an LLVM IR global value that corresponds to the given MLIR operation defining a global value.
void forgetMapping(Value value)
Removes the mapping for the given value.
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.
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)
llvm::CanonicalLoopInfo * lookupOMPLoop(Value mlir) const
Find the LLVM-IR loop that represents an MLIR loop.
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::CanonicalLoopInfo * lookupOMPLoop(omp::NewCliOp mlir) const
Find the LLVM-IR loop that represents an MLIR loop.
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:63
NamedAttribute represents a combination of a name and an Attribute value.
Definition Attributes.h:164
Operation is the basic unit of execution within MLIR.
Definition Operation.h:88
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.
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:389
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.
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:120
RAII object calling stackPush/stackPop on construction/destruction.
Definition StateStack.h:106