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