MLIR  18.0.0git
ModuleTranslation.h
Go to the documentation of this file.
1 //===- ModuleTranslation.h - MLIR to LLVM conversion ------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the translation between an MLIR LLVM dialect module and
10 // the corresponding LLVMIR module. It only handles core LLVM IR operations.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef MLIR_TARGET_LLVMIR_MODULETRANSLATION_H
15 #define MLIR_TARGET_LLVMIR_MODULETRANSLATION_H
16 
18 #include "mlir/IR/Operation.h"
19 #include "mlir/IR/SymbolTable.h"
20 #include "mlir/IR/Value.h"
24 
25 #include "llvm/ADT/SetVector.h"
26 #include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
27 
28 namespace llvm {
29 class BasicBlock;
30 class IRBuilderBase;
31 class Function;
32 class Value;
33 } // namespace llvm
34 
35 namespace mlir {
36 class Attribute;
37 class Block;
38 class Location;
39 
40 namespace LLVM {
41 
42 namespace detail {
43 class DebugTranslation;
44 class LoopAnnotationTranslation;
45 } // namespace detail
46 
47 class AliasScopeAttr;
48 class AliasScopeDomainAttr;
49 class DINodeAttr;
50 class LLVMFuncOp;
51 class ComdatSelectorOp;
52 
53 /// Implementation class for module translation. Holds a reference to the module
54 /// being translated, and the mappings between the original and the translated
55 /// functions, basic blocks and values. It is practically easier to hold these
56 /// mappings in one class since the conversion of control flow operations
57 /// needs to look up block and function mappings.
59  friend std::unique_ptr<llvm::Module>
60  mlir::translateModuleToLLVMIR(Operation *, llvm::LLVMContext &, StringRef);
61 
62 public:
63  /// Stores the mapping between a function name and its LLVM IR representation.
64  void mapFunction(StringRef name, llvm::Function *func) {
65  auto result = functionMapping.try_emplace(name, func);
66  (void)result;
67  assert(result.second &&
68  "attempting to map a function that is already mapped");
69  }
70 
71  /// Finds an LLVM IR function by its name.
72  llvm::Function *lookupFunction(StringRef name) const {
73  return functionMapping.lookup(name);
74  }
75 
76  /// Stores the mapping between an MLIR value and its LLVM IR counterpart.
77  void mapValue(Value mlir, llvm::Value *llvm) { mapValue(mlir) = llvm; }
78 
79  /// Provides write-once access to store the LLVM IR value corresponding to the
80  /// given MLIR value.
81  llvm::Value *&mapValue(Value value) {
82  llvm::Value *&llvm = valueMapping[value];
83  assert(llvm == nullptr &&
84  "attempting to map a value that is already mapped");
85  return llvm;
86  }
87 
88  /// Finds an LLVM IR value corresponding to the given MLIR value.
89  llvm::Value *lookupValue(Value value) const {
90  return valueMapping.lookup(value);
91  }
92 
93  /// Looks up remapped a list of remapped values.
95 
96  /// Stores the mapping between an MLIR block and LLVM IR basic block.
97  void mapBlock(Block *mlir, llvm::BasicBlock *llvm) {
98  auto result = blockMapping.try_emplace(mlir, llvm);
99  (void)result;
100  assert(result.second && "attempting to map a block that is already mapped");
101  }
102 
103  /// Finds an LLVM IR basic block that corresponds to the given MLIR block.
104  llvm::BasicBlock *lookupBlock(Block *block) const {
105  return blockMapping.lookup(block);
106  }
107 
108  /// Stores the mapping between an MLIR operation with successors and a
109  /// corresponding LLVM IR instruction.
110  void mapBranch(Operation *mlir, llvm::Instruction *llvm) {
111  auto result = branchMapping.try_emplace(mlir, llvm);
112  (void)result;
113  assert(result.second &&
114  "attempting to map a branch that is already mapped");
115  }
116 
117  /// Finds an LLVM IR instruction that corresponds to the given MLIR operation
118  /// with successors.
119  llvm::Instruction *lookupBranch(Operation *op) const {
120  return branchMapping.lookup(op);
121  }
122 
123  /// Stores a mapping between an MLIR call operation and a corresponding LLVM
124  /// call instruction.
125  void mapCall(Operation *mlir, llvm::CallInst *llvm) {
126  auto result = callMapping.try_emplace(mlir, llvm);
127  (void)result;
128  assert(result.second && "attempting to map a call that is already mapped");
129  }
130 
131  /// Finds an LLVM call instruction that corresponds to the given MLIR call
132  /// operation.
133  llvm::CallInst *lookupCall(Operation *op) const {
134  return callMapping.lookup(op);
135  }
136 
137  /// Removes the mapping for blocks contained in the region and values defined
138  /// in these blocks.
139  void forgetMapping(Region &region);
140 
141  /// Returns the LLVM metadata corresponding to a mlir LLVM dialect alias scope
142  /// attribute. Creates the metadata node if it has not been converted before.
143  llvm::MDNode *getOrCreateAliasScope(AliasScopeAttr aliasScopeAttr);
144 
145  /// Returns the LLVM metadata corresponding to an array of mlir LLVM dialect
146  /// alias scope attributes. Creates the metadata nodes if they have not been
147  /// converted before.
148  llvm::MDNode *
150 
151  // Sets LLVM metadata for memory operations that are in a parallel loop.
152  void setAccessGroupsMetadata(AccessGroupOpInterface op,
153  llvm::Instruction *inst);
154 
155  // Sets LLVM metadata for memory operations that have alias scope information.
156  void setAliasScopeMetadata(AliasAnalysisOpInterface op,
157  llvm::Instruction *inst);
158 
159  /// Sets LLVM TBAA metadata for memory operations that have TBAA attributes.
160  void setTBAAMetadata(AliasAnalysisOpInterface op, llvm::Instruction *inst);
161 
162  /// Sets LLVM profiling metadata for operations that have branch weights.
163  void setBranchWeightsMetadata(BranchWeightOpInterface op);
164 
165  /// Sets LLVM loop metadata for branch operations that have a loop annotation
166  /// attribute.
167  void setLoopMetadata(Operation *op, llvm::Instruction *inst);
168 
169  /// Converts the type from MLIR LLVM dialect to LLVM.
170  llvm::Type *convertType(Type type);
171 
172  /// Returns the MLIR context of the module being translated.
173  MLIRContext &getContext() { return *mlirModule->getContext(); }
174 
175  /// Returns the LLVM context in which the IR is being constructed.
176  llvm::LLVMContext &getLLVMContext() const { return llvmModule->getContext(); }
177 
178  /// Finds an LLVM IR global value that corresponds to the given MLIR operation
179  /// defining a global value.
180  llvm::GlobalValue *lookupGlobal(Operation *op) {
181  return globalsMapping.lookup(op);
182  }
183 
184  /// Returns the OpenMP IR builder associated with the LLVM IR module being
185  /// constructed.
186  llvm::OpenMPIRBuilder *getOpenMPBuilder();
187 
188  /// Returns the LLVM module in which the IR is being constructed.
189  llvm::Module *getLLVMModule() { return llvmModule.get(); }
190 
191  /// Translates the given location.
192  llvm::DILocation *translateLoc(Location loc, llvm::DILocalScope *scope);
193 
194  /// Translates the given LLVM debug info metadata.
195  llvm::Metadata *translateDebugInfo(LLVM::DINodeAttr attr);
196 
197  /// Translates the contents of the given block to LLVM IR using this
198  /// translator. The LLVM IR basic block corresponding to the given block is
199  /// expected to exist in the mapping of this translator. Uses `builder` to
200  /// translate the IR, leaving it at the end of the block. If `ignoreArguments`
201  /// is set, does not produce PHI nodes for the block arguments. Otherwise, the
202  /// PHI nodes are constructed for block arguments but are _not_ connected to
203  /// the predecessors that may not exist yet.
204  LogicalResult convertBlock(Block &bb, bool ignoreArguments,
205  llvm::IRBuilderBase &builder);
206 
207  /// Gets the named metadata in the LLVM IR module being constructed, creating
208  /// it if it does not exist.
209  llvm::NamedMDNode *getOrInsertNamedModuleMetadata(StringRef name);
210 
211  /// Common CRTP base class for ModuleTranslation stack frames.
212  class StackFrame {
213  public:
214  virtual ~StackFrame() = default;
215  TypeID getTypeID() const { return typeID; }
216 
217  protected:
218  explicit StackFrame(TypeID typeID) : typeID(typeID) {}
219 
220  private:
221  const TypeID typeID;
222  virtual void anchor();
223  };
224 
225  /// Concrete CRTP base class for ModuleTranslation stack frames. When
226  /// translating operations with regions, users of ModuleTranslation can store
227  /// state on ModuleTranslation stack before entering the region and inspect
228  /// it when converting operations nested within that region. Users are
229  /// expected to derive this class and put any relevant information into fields
230  /// of the derived class. The usual isa/dyn_cast functionality is available
231  /// for instances of derived classes.
232  template <typename Derived>
233  class StackFrameBase : public StackFrame {
234  public:
235  explicit StackFrameBase() : StackFrame(TypeID::get<Derived>()) {}
236  };
237 
238  /// Creates a stack frame of type `T` on ModuleTranslation stack. `T` must
239  /// be derived from `StackFrameBase<T>` and constructible from the provided
240  /// arguments. Doing this before entering the region of the op being
241  /// translated makes the frame available when translating ops within that
242  /// region.
243  template <typename T, typename... Args>
244  void stackPush(Args &&...args) {
245  static_assert(
246  std::is_base_of<StackFrame, T>::value,
247  "can only push instances of StackFrame on ModuleTranslation stack");
248  stack.push_back(std::make_unique<T>(std::forward<Args>(args)...));
249  }
250 
251  /// Pops the last element from the ModuleTranslation stack.
252  void stackPop() { stack.pop_back(); }
253 
254  /// Calls `callback` for every ModuleTranslation stack frame of type `T`
255  /// starting from the top of the stack.
256  template <typename T>
257  WalkResult
258  stackWalk(llvm::function_ref<WalkResult(const T &)> callback) const {
259  static_assert(std::is_base_of<StackFrame, T>::value,
260  "expected T derived from StackFrame");
261  if (!callback)
262  return WalkResult::skip();
263  for (const std::unique_ptr<StackFrame> &frame : llvm::reverse(stack)) {
264  if (T *ptr = dyn_cast_or_null<T>(frame.get())) {
265  WalkResult result = callback(*ptr);
266  if (result.wasInterrupted())
267  return result;
268  }
269  }
270  return WalkResult::advance();
271  }
272 
273  /// RAII object calling stackPush/stackPop on construction/destruction.
274  template <typename T>
275  struct SaveStack {
276  template <typename... Args>
277  explicit SaveStack(ModuleTranslation &m, Args &&...args)
278  : moduleTranslation(m) {
279  moduleTranslation.stackPush<T>(std::forward<Args>(args)...);
280  }
281  ~SaveStack() { moduleTranslation.stackPop(); }
282 
283  private:
284  ModuleTranslation &moduleTranslation;
285  };
286 
287  SymbolTableCollection &symbolTable() { return symbolTableCollection; }
288 
289 private:
291  std::unique_ptr<llvm::Module> llvmModule);
293 
294  /// Converts individual components.
295  LogicalResult convertOperation(Operation &op, llvm::IRBuilderBase &builder);
296  LogicalResult convertFunctionSignatures();
297  LogicalResult convertFunctions();
298  LogicalResult convertComdats();
299  LogicalResult convertGlobals();
300  LogicalResult convertOneFunction(LLVMFuncOp func);
301 
302  /// Returns the LLVM metadata corresponding to the given mlir LLVM dialect
303  /// TBAATagAttr.
304  llvm::MDNode *getTBAANode(TBAATagAttr tbaaAttr) const;
305 
306  /// Process tbaa LLVM Metadata operations and create LLVM
307  /// metadata nodes for them.
308  LogicalResult createTBAAMetadata();
309 
310  /// Translates dialect attributes attached to the given operation.
311  LogicalResult convertDialectAttributes(Operation *op);
312 
313  /// Translates parameter attributes and adds them to the returned AttrBuilder.
314  llvm::AttrBuilder convertParameterAttrs(DictionaryAttr paramAttrs);
315 
316  /// Original and translated module.
317  Operation *mlirModule;
318  std::unique_ptr<llvm::Module> llvmModule;
319  /// A converter for translating debug information.
320  std::unique_ptr<detail::DebugTranslation> debugTranslation;
321 
322  /// A converter for translating loop annotations.
323  std::unique_ptr<detail::LoopAnnotationTranslation> loopAnnotationTranslation;
324 
325  /// Builder for LLVM IR generation of OpenMP constructs.
326  std::unique_ptr<llvm::OpenMPIRBuilder> ompBuilder;
327 
328  /// Mappings between llvm.mlir.global definitions and corresponding globals.
330 
331  /// A stateful object used to translate types.
332  TypeToLLVMIRTranslator typeTranslator;
333 
334  /// A dialect interface collection used for dispatching the translation to
335  /// specific dialects.
337 
338  /// Mappings between original and translated values, used for lookups.
339  llvm::StringMap<llvm::Function *> functionMapping;
340  DenseMap<Value, llvm::Value *> valueMapping;
342 
343  /// A mapping between MLIR LLVM dialect terminators and LLVM IR terminators
344  /// they are converted to. This allows for connecting PHI nodes to the source
345  /// values after all operations are converted.
347 
348  /// A mapping between MLIR LLVM dialect call operations and LLVM IR call
349  /// instructions. This allows for adding branch weights after the operations
350  /// have been converted.
352 
353  /// Mapping from an alias scope attribute to its LLVM metadata.
354  /// This map is populated lazily.
355  DenseMap<AliasScopeAttr, llvm::MDNode *> aliasScopeMetadataMapping;
356 
357  /// Mapping from an alias scope domain attribute to its LLVM metadata.
358  /// This map is populated lazily.
359  DenseMap<AliasScopeDomainAttr, llvm::MDNode *> aliasDomainMetadataMapping;
360 
361  /// Mapping from a tbaa attribute to its LLVM metadata.
362  /// This map is populated on module entry.
363  DenseMap<Attribute, llvm::MDNode *> tbaaMetadataMapping;
364 
365  /// Mapping from a comdat selector operation to its LLVM comdat struct.
366  /// This map is populated on module entry.
368 
369  /// Stack of user-specified state elements, useful when translating operations
370  /// with regions.
372 
373  /// A cache for the symbol tables constructed during symbols lookup.
374  SymbolTableCollection symbolTableCollection;
375 };
376 
377 namespace detail {
378 /// For all blocks in the region that were converted to LLVM IR using the given
379 /// ModuleTranslation, connect the PHI nodes of the corresponding LLVM IR blocks
380 /// to the results of preceding blocks.
381 void connectPHINodes(Region &region, const ModuleTranslation &state);
382 
383 /// Create an LLVM IR constant of `llvmType` from the MLIR attribute `attr`.
384 /// This currently supports integer, floating point, splat and dense element
385 /// attributes and combinations thereof. Also, an array attribute with two
386 /// elements is supported to represent a complex constant. In case of error,
387 /// report it to `loc` and return nullptr.
388 llvm::Constant *getLLVMConstant(llvm::Type *llvmType, Attribute attr,
389  Location loc,
390  const ModuleTranslation &moduleTranslation);
391 
392 /// Creates a call to an LLVM IR intrinsic function with the given arguments.
393 llvm::CallInst *createIntrinsicCall(llvm::IRBuilderBase &builder,
394  llvm::Intrinsic::ID intrinsic,
395  ArrayRef<llvm::Value *> args = {},
396  ArrayRef<llvm::Type *> tys = {});
397 
398 /// Creates a call to a LLVM IR intrinsic defined by LLVM_IntrOpBase. This
399 /// resolves the overloads, and maps mixed MLIR value and attribute arguments to
400 /// LLVM values.
401 llvm::CallInst *createIntrinsicCall(
402  llvm::IRBuilderBase &builder, ModuleTranslation &moduleTranslation,
403  Operation *intrOp, llvm::Intrinsic::ID intrinsic, unsigned numResults,
404  ArrayRef<unsigned> overloadedResults, ArrayRef<unsigned> overloadedOperands,
405  ArrayRef<unsigned> immArgPositions,
406  ArrayRef<StringLiteral> immArgAttrNames);
407 
408 } // namespace detail
409 
410 } // namespace LLVM
411 } // namespace mlir
412 
413 namespace llvm {
414 template <typename T>
416  static inline bool
417  doit(const ::mlir::LLVM::ModuleTranslation::StackFrame &frame) {
418  return frame.getTypeID() == ::mlir::TypeID::get<T>();
419  }
420 };
421 } // namespace llvm
422 
423 #endif // MLIR_TARGET_LLVMIR_MODULETRANSLATION_H
Attributes are known-constant values of operations.
Definition: Attributes.h:25
Block represents an ordered list of Operations.
Definition: Block.h:30
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:27
Concrete CRTP base class for ModuleTranslation stack frames.
Common CRTP base class for ModuleTranslation stack frames.
Implementation class for module translation.
LogicalResult convertBlock(Block &bb, bool ignoreArguments, llvm::IRBuilderBase &builder)
Translates the contents of the given block to LLVM IR using this translator.
llvm::Value * lookupValue(Value value) const
Finds an LLVM IR value corresponding to the given MLIR value.
void mapCall(Operation *mlir, llvm::CallInst *llvm)
Stores a mapping between an MLIR call operation and a corresponding LLVM call instruction.
llvm::Value *& mapValue(Value value)
Provides write-once access to store the LLVM IR value corresponding to the given MLIR value.
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.
void mapBranch(Operation *mlir, llvm::Instruction *llvm)
Stores the mapping between an MLIR operation with successors and a corresponding LLVM IR instruction.
llvm::Instruction * lookupBranch(Operation *op) const
Finds an LLVM IR instruction that corresponds to the given MLIR operation with successors.
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.
llvm::DILocation * translateLoc(Location loc, llvm::DILocalScope *scope)
Translates the given location.
llvm::BasicBlock * lookupBlock(Block *block) const
Finds an LLVM IR basic block that corresponds to the given MLIR block.
SymbolTableCollection & symbolTable()
void setBranchWeightsMetadata(BranchWeightOpInterface op)
Sets LLVM profiling metadata for operations that have branch weights.
llvm::Type * convertType(Type type)
Converts the type from MLIR LLVM dialect to LLVM.
void setTBAAMetadata(AliasAnalysisOpInterface op, llvm::Instruction *inst)
Sets LLVM TBAA metadata for memory operations that have TBAA attributes.
llvm::OpenMPIRBuilder * getOpenMPBuilder()
Returns the OpenMP IR builder associated with the LLVM IR module being constructed.
llvm::CallInst * lookupCall(Operation *op) const
Finds an LLVM call instruction that corresponds to the given MLIR call operation.
llvm::Metadata * translateDebugInfo(LLVM::DINodeAttr attr)
Translates the given LLVM debug info metadata.
llvm::LLVMContext & getLLVMContext() const
Returns the LLVM context in which the IR is being constructed.
llvm::GlobalValue * lookupGlobal(Operation *op)
Finds an LLVM IR global value that corresponds to the given MLIR operation defining a global value.
llvm::Module * getLLVMModule()
Returns the LLVM module in which the IR is being constructed.
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.
WalkResult stackWalk(llvm::function_ref< WalkResult(const T &)> callback) const
Calls callback for every ModuleTranslation stack frame of type T starting from the top of the stack.
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)
MLIRContext & getContext()
Returns the MLIR context of the module being translated.
void mapValue(Value mlir, llvm::Value *llvm)
Stores the mapping between an MLIR value and its LLVM IR counterpart.
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
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition: Location.h:63
MLIRContext is the top-level object for a collection of MLIR operations.
Definition: MLIRContext.h:60
Operation is the basic unit of execution within MLIR.
Definition: Operation.h:88
MLIRContext * getContext()
Return the context this operation is associated with.
Definition: Operation.h:216
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.
Definition: SymbolTable.h:283
This class provides an efficient unique identifier for a specific C++ type.
Definition: TypeID.h:104
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:378
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: Visitors.h:34
static WalkResult skip()
Definition: Visitors.h:53
static WalkResult advance()
Definition: Visitors.h:52
bool wasInterrupted() const
Returns true if the walk was interrupted.
Definition: Visitors.h:56
Include the generated interface declarations.
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.
Include the generated interface declarations.
auto get(MLIRContext *context, Ts &&...params)
Helper method that injects context only if needed, this helps unify some of the attribute constructio...
std::unique_ptr< llvm::Module > translateModuleToLLVMIR(Operation *module, llvm::LLVMContext &llvmContext, llvm::StringRef name="LLVMDialectModule")
Translate operation that satisfies LLVM dialect module requirements into an LLVM IR module living in ...
static bool doit(const ::mlir::LLVM::ModuleTranslation::StackFrame &frame)
RAII object calling stackPush/stackPop on construction/destruction.
SaveStack(ModuleTranslation &m, Args &&...args)
This class represents an efficient way to signal success or failure.
Definition: LogicalResult.h:26