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