1cde4d5a6SJacques Pienaar //===- ModuleTranslation.cpp - MLIR to LLVM conversion --------------------===//
25d7231d8SStephan Herhut //
330857107SMehdi Amini // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
456222a06SMehdi Amini // See https://llvm.org/LICENSE.txt for license information.
556222a06SMehdi Amini // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
65d7231d8SStephan Herhut //
756222a06SMehdi Amini //===----------------------------------------------------------------------===//
85d7231d8SStephan Herhut //
95d7231d8SStephan Herhut // This file implements the translation between an MLIR LLVM dialect module and
105d7231d8SStephan Herhut // the corresponding LLVMIR module. It only handles core LLVM IR operations.
115d7231d8SStephan Herhut //
125d7231d8SStephan Herhut //===----------------------------------------------------------------------===//
135d7231d8SStephan Herhut 
145d7231d8SStephan Herhut #include "mlir/Target/LLVMIR/ModuleTranslation.h"
155d7231d8SStephan Herhut 
16c33d6970SRiver Riddle #include "DebugTranslation.h"
17ba0fa925SRiver Riddle #include "mlir/Dialect/LLVMIR/LLVMDialect.h"
18ce8f10d6SAlex Zinenko #include "mlir/Dialect/LLVMIR/Transforms/LegalizeForExport.h"
1992a295ebSKiran Chandramohan #include "mlir/Dialect/OpenMP/OpenMPDialect.h"
205d7231d8SStephan Herhut #include "mlir/IR/Attributes.h"
2165fcddffSRiver Riddle #include "mlir/IR/BuiltinOps.h"
2209f7a55fSRiver Riddle #include "mlir/IR/BuiltinTypes.h"
23d4568ed7SGeorge Mitenkov #include "mlir/IR/RegionGraphTraits.h"
245d7231d8SStephan Herhut #include "mlir/Support/LLVM.h"
25b77bac05SAlex Zinenko #include "mlir/Target/LLVMIR/LLVMTranslationInterface.h"
26ec1f4e7cSAlex Zinenko #include "mlir/Target/LLVMIR/TypeTranslation.h"
27ebf190fcSRiver Riddle #include "llvm/ADT/TypeSwitch.h"
285d7231d8SStephan Herhut 
29d4568ed7SGeorge Mitenkov #include "llvm/ADT/PostOrderIterator.h"
305d7231d8SStephan Herhut #include "llvm/ADT/SetVector.h"
3192a295ebSKiran Chandramohan #include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
325d7231d8SStephan Herhut #include "llvm/IR/BasicBlock.h"
33d9067dcaSKiran Chandramohan #include "llvm/IR/CFG.h"
345d7231d8SStephan Herhut #include "llvm/IR/Constants.h"
355d7231d8SStephan Herhut #include "llvm/IR/DerivedTypes.h"
365d7231d8SStephan Herhut #include "llvm/IR/IRBuilder.h"
37047400edSNicolas Vasilache #include "llvm/IR/InlineAsm.h"
385d7231d8SStephan Herhut #include "llvm/IR/LLVMContext.h"
3999d03f03SGeorge Mitenkov #include "llvm/IR/MDBuilder.h"
405d7231d8SStephan Herhut #include "llvm/IR/Module.h"
41ce8f10d6SAlex Zinenko #include "llvm/IR/Verifier.h"
42d9067dcaSKiran Chandramohan #include "llvm/Transforms/Utils/BasicBlockUtils.h"
435d7231d8SStephan Herhut #include "llvm/Transforms/Utils/Cloning.h"
445d7231d8SStephan Herhut 
452666b973SRiver Riddle using namespace mlir;
462666b973SRiver Riddle using namespace mlir::LLVM;
47c33d6970SRiver Riddle using namespace mlir::LLVM::detail;
485d7231d8SStephan Herhut 
49eb67bd78SAlex Zinenko #include "mlir/Dialect/LLVMIR/LLVMConversionEnumsToLLVM.inc"
50eb67bd78SAlex Zinenko 
51a922e231SAlex Zinenko /// Builds a constant of a sequential LLVM type `type`, potentially containing
52a922e231SAlex Zinenko /// other sequential types recursively, from the individual constant values
53a922e231SAlex Zinenko /// provided in `constants`. `shape` contains the number of elements in nested
54a922e231SAlex Zinenko /// sequential types. Reports errors at `loc` and returns nullptr on error.
55a4a42160SAlex Zinenko static llvm::Constant *
56a4a42160SAlex Zinenko buildSequentialConstant(ArrayRef<llvm::Constant *> &constants,
57a4a42160SAlex Zinenko                         ArrayRef<int64_t> shape, llvm::Type *type,
58a4a42160SAlex Zinenko                         Location loc) {
59a4a42160SAlex Zinenko   if (shape.empty()) {
60a4a42160SAlex Zinenko     llvm::Constant *result = constants.front();
61a4a42160SAlex Zinenko     constants = constants.drop_front();
62a4a42160SAlex Zinenko     return result;
63a4a42160SAlex Zinenko   }
64a4a42160SAlex Zinenko 
6568b03aeeSEli Friedman   llvm::Type *elementType;
6668b03aeeSEli Friedman   if (auto *arrayTy = dyn_cast<llvm::ArrayType>(type)) {
6768b03aeeSEli Friedman     elementType = arrayTy->getElementType();
6868b03aeeSEli Friedman   } else if (auto *vectorTy = dyn_cast<llvm::VectorType>(type)) {
6968b03aeeSEli Friedman     elementType = vectorTy->getElementType();
7068b03aeeSEli Friedman   } else {
71a4a42160SAlex Zinenko     emitError(loc) << "expected sequential LLVM types wrapping a scalar";
72a4a42160SAlex Zinenko     return nullptr;
73a4a42160SAlex Zinenko   }
74a4a42160SAlex Zinenko 
75a4a42160SAlex Zinenko   SmallVector<llvm::Constant *, 8> nested;
76a4a42160SAlex Zinenko   nested.reserve(shape.front());
77a4a42160SAlex Zinenko   for (int64_t i = 0; i < shape.front(); ++i) {
78a4a42160SAlex Zinenko     nested.push_back(buildSequentialConstant(constants, shape.drop_front(),
79a4a42160SAlex Zinenko                                              elementType, loc));
80a4a42160SAlex Zinenko     if (!nested.back())
81a4a42160SAlex Zinenko       return nullptr;
82a4a42160SAlex Zinenko   }
83a4a42160SAlex Zinenko 
84a4a42160SAlex Zinenko   if (shape.size() == 1 && type->isVectorTy())
85a4a42160SAlex Zinenko     return llvm::ConstantVector::get(nested);
86a4a42160SAlex Zinenko   return llvm::ConstantArray::get(
87a4a42160SAlex Zinenko       llvm::ArrayType::get(elementType, shape.front()), nested);
88a4a42160SAlex Zinenko }
89a4a42160SAlex Zinenko 
90fc817b09SKazuaki Ishizaki /// Returns the first non-sequential type nested in sequential types.
91a4a42160SAlex Zinenko static llvm::Type *getInnermostElementType(llvm::Type *type) {
9268b03aeeSEli Friedman   do {
9368b03aeeSEli Friedman     if (auto *arrayTy = dyn_cast<llvm::ArrayType>(type)) {
9468b03aeeSEli Friedman       type = arrayTy->getElementType();
9568b03aeeSEli Friedman     } else if (auto *vectorTy = dyn_cast<llvm::VectorType>(type)) {
9668b03aeeSEli Friedman       type = vectorTy->getElementType();
9768b03aeeSEli Friedman     } else {
98a4a42160SAlex Zinenko       return type;
99a4a42160SAlex Zinenko     }
1000881a4f1SAlex Zinenko   } while (true);
10168b03aeeSEli Friedman }
102a4a42160SAlex Zinenko 
1032666b973SRiver Riddle /// Create an LLVM IR constant of `llvmType` from the MLIR attribute `attr`.
1042666b973SRiver Riddle /// This currently supports integer, floating point, splat and dense element
1052666b973SRiver Riddle /// attributes and combinations thereof.  In case of error, report it to `loc`
1062666b973SRiver Riddle /// and return nullptr.
107176379e0SAlex Zinenko llvm::Constant *mlir::LLVM::detail::getLLVMConstant(
108176379e0SAlex Zinenko     llvm::Type *llvmType, Attribute attr, Location loc,
109176379e0SAlex Zinenko     const ModuleTranslation &moduleTranslation) {
11033a3a91bSChristian Sigg   if (!attr)
11133a3a91bSChristian Sigg     return llvm::UndefValue::get(llvmType);
112a4a42160SAlex Zinenko   if (llvmType->isStructTy()) {
113a4a42160SAlex Zinenko     emitError(loc, "struct types are not supported in constants");
114a4a42160SAlex Zinenko     return nullptr;
115a4a42160SAlex Zinenko   }
116ac9d742bSStephan Herhut   // For integer types, we allow a mismatch in sizes as the index type in
117ac9d742bSStephan Herhut   // MLIR might have a different size than the index type in the LLVM module.
1185d7231d8SStephan Herhut   if (auto intAttr = attr.dyn_cast<IntegerAttr>())
119ac9d742bSStephan Herhut     return llvm::ConstantInt::get(
120ac9d742bSStephan Herhut         llvmType,
121ac9d742bSStephan Herhut         intAttr.getValue().sextOrTrunc(llvmType->getIntegerBitWidth()));
1225d7231d8SStephan Herhut   if (auto floatAttr = attr.dyn_cast<FloatAttr>())
1235d7231d8SStephan Herhut     return llvm::ConstantFP::get(llvmType, floatAttr.getValue());
1249b9c647cSRiver Riddle   if (auto funcAttr = attr.dyn_cast<FlatSymbolRefAttr>())
125176379e0SAlex Zinenko     return llvm::ConstantExpr::getBitCast(
126176379e0SAlex Zinenko         moduleTranslation.lookupFunction(funcAttr.getValue()), llvmType);
1275d7231d8SStephan Herhut   if (auto splatAttr = attr.dyn_cast<SplatElementsAttr>()) {
12868b03aeeSEli Friedman     llvm::Type *elementType;
12968b03aeeSEli Friedman     uint64_t numElements;
13068b03aeeSEli Friedman     if (auto *arrayTy = dyn_cast<llvm::ArrayType>(llvmType)) {
13168b03aeeSEli Friedman       elementType = arrayTy->getElementType();
13268b03aeeSEli Friedman       numElements = arrayTy->getNumElements();
13368b03aeeSEli Friedman     } else {
1345cba1c63SChristopher Tetreault       auto *vectorTy = cast<llvm::FixedVectorType>(llvmType);
13568b03aeeSEli Friedman       elementType = vectorTy->getElementType();
13668b03aeeSEli Friedman       numElements = vectorTy->getNumElements();
13768b03aeeSEli Friedman     }
138d6ea8ff0SAlex Zinenko     // Splat value is a scalar. Extract it only if the element type is not
139d6ea8ff0SAlex Zinenko     // another sequence type. The recursion terminates because each step removes
140d6ea8ff0SAlex Zinenko     // one outer sequential type.
14168b03aeeSEli Friedman     bool elementTypeSequential =
142d891d738SRahul Joshi         isa<llvm::ArrayType, llvm::VectorType>(elementType);
143d6ea8ff0SAlex Zinenko     llvm::Constant *child = getLLVMConstant(
144d6ea8ff0SAlex Zinenko         elementType,
145176379e0SAlex Zinenko         elementTypeSequential ? splatAttr : splatAttr.getSplatValue(), loc,
146176379e0SAlex Zinenko         moduleTranslation);
147a4a42160SAlex Zinenko     if (!child)
148a4a42160SAlex Zinenko       return nullptr;
1492f13df13SMLIR Team     if (llvmType->isVectorTy())
150396a42d9SRiver Riddle       return llvm::ConstantVector::getSplat(
1510f95e731SAlex Zinenko           llvm::ElementCount::get(numElements, /*Scalable=*/false), child);
1522f13df13SMLIR Team     if (llvmType->isArrayTy()) {
153ac9d742bSStephan Herhut       auto *arrayType = llvm::ArrayType::get(elementType, numElements);
1542f13df13SMLIR Team       SmallVector<llvm::Constant *, 8> constants(numElements, child);
1552f13df13SMLIR Team       return llvm::ConstantArray::get(arrayType, constants);
1562f13df13SMLIR Team     }
1575d7231d8SStephan Herhut   }
158a4a42160SAlex Zinenko 
159d906f84bSRiver Riddle   if (auto elementsAttr = attr.dyn_cast<ElementsAttr>()) {
160a4a42160SAlex Zinenko     assert(elementsAttr.getType().hasStaticShape());
161a4a42160SAlex Zinenko     assert(elementsAttr.getNumElements() != 0 &&
162a4a42160SAlex Zinenko            "unexpected empty elements attribute");
163a4a42160SAlex Zinenko     assert(!elementsAttr.getType().getShape().empty() &&
164a4a42160SAlex Zinenko            "unexpected empty elements attribute shape");
165a4a42160SAlex Zinenko 
1665d7231d8SStephan Herhut     SmallVector<llvm::Constant *, 8> constants;
167a4a42160SAlex Zinenko     constants.reserve(elementsAttr.getNumElements());
168a4a42160SAlex Zinenko     llvm::Type *innermostType = getInnermostElementType(llvmType);
169d906f84bSRiver Riddle     for (auto n : elementsAttr.getValues<Attribute>()) {
170176379e0SAlex Zinenko       constants.push_back(
171176379e0SAlex Zinenko           getLLVMConstant(innermostType, n, loc, moduleTranslation));
1725d7231d8SStephan Herhut       if (!constants.back())
1735d7231d8SStephan Herhut         return nullptr;
1745d7231d8SStephan Herhut     }
175a4a42160SAlex Zinenko     ArrayRef<llvm::Constant *> constantsRef = constants;
176a4a42160SAlex Zinenko     llvm::Constant *result = buildSequentialConstant(
177a4a42160SAlex Zinenko         constantsRef, elementsAttr.getType().getShape(), llvmType, loc);
178a4a42160SAlex Zinenko     assert(constantsRef.empty() && "did not consume all elemental constants");
179a4a42160SAlex Zinenko     return result;
1802f13df13SMLIR Team   }
181a4a42160SAlex Zinenko 
182cb348dffSStephan Herhut   if (auto stringAttr = attr.dyn_cast<StringAttr>()) {
183cb348dffSStephan Herhut     return llvm::ConstantDataArray::get(
184176379e0SAlex Zinenko         moduleTranslation.getLLVMContext(),
185176379e0SAlex Zinenko         ArrayRef<char>{stringAttr.getValue().data(),
186cb348dffSStephan Herhut                        stringAttr.getValue().size()});
187cb348dffSStephan Herhut   }
188a4c3a645SRiver Riddle   emitError(loc, "unsupported constant value");
1895d7231d8SStephan Herhut   return nullptr;
1905d7231d8SStephan Herhut }
1915d7231d8SStephan Herhut 
192c33d6970SRiver Riddle ModuleTranslation::ModuleTranslation(Operation *module,
193c33d6970SRiver Riddle                                      std::unique_ptr<llvm::Module> llvmModule)
194c33d6970SRiver Riddle     : mlirModule(module), llvmModule(std::move(llvmModule)),
195c33d6970SRiver Riddle       debugTranslation(
19692a295ebSKiran Chandramohan           std::make_unique<DebugTranslation>(module, *this->llvmModule)),
197b77bac05SAlex Zinenko       typeTranslator(this->llvmModule->getContext()),
198b77bac05SAlex Zinenko       iface(module->getContext()) {
199c33d6970SRiver Riddle   assert(satisfiesLLVMModule(mlirModule) &&
200c33d6970SRiver Riddle          "mlirModule should honor LLVM's module semantics.");
201c33d6970SRiver Riddle }
202d9067dcaSKiran Chandramohan ModuleTranslation::~ModuleTranslation() {
203d9067dcaSKiran Chandramohan   if (ompBuilder)
204d9067dcaSKiran Chandramohan     ompBuilder->finalize();
205d9067dcaSKiran Chandramohan }
206d9067dcaSKiran Chandramohan 
207d9067dcaSKiran Chandramohan /// Get the SSA value passed to the current block from the terminator operation
208d9067dcaSKiran Chandramohan /// of its predecessor.
209d9067dcaSKiran Chandramohan static Value getPHISourceValue(Block *current, Block *pred,
210d9067dcaSKiran Chandramohan                                unsigned numArguments, unsigned index) {
211d9067dcaSKiran Chandramohan   Operation &terminator = *pred->getTerminator();
212d9067dcaSKiran Chandramohan   if (isa<LLVM::BrOp>(terminator))
213d9067dcaSKiran Chandramohan     return terminator.getOperand(index);
214d9067dcaSKiran Chandramohan 
21514f24155SBrian Gesiak   SuccessorRange successors = terminator.getSuccessors();
21614f24155SBrian Gesiak   assert(std::adjacent_find(successors.begin(), successors.end()) ==
21714f24155SBrian Gesiak              successors.end() &&
21814f24155SBrian Gesiak          "successors with arguments in LLVM branches must be different blocks");
21958f2b765SChristian Sigg   (void)successors;
220d9067dcaSKiran Chandramohan 
22114f24155SBrian Gesiak   // For instructions that branch based on a condition value, we need to take
22214f24155SBrian Gesiak   // the operands for the branch that was taken.
22314f24155SBrian Gesiak   if (auto condBranchOp = dyn_cast<LLVM::CondBrOp>(terminator)) {
22414f24155SBrian Gesiak     // For conditional branches, we take the operands from either the "true" or
22514f24155SBrian Gesiak     // the "false" branch.
226d9067dcaSKiran Chandramohan     return condBranchOp.getSuccessor(0) == current
227d9067dcaSKiran Chandramohan                ? condBranchOp.trueDestOperands()[index]
228d9067dcaSKiran Chandramohan                : condBranchOp.falseDestOperands()[index];
2290881a4f1SAlex Zinenko   }
2300881a4f1SAlex Zinenko 
2310881a4f1SAlex Zinenko   if (auto switchOp = dyn_cast<LLVM::SwitchOp>(terminator)) {
23214f24155SBrian Gesiak     // For switches, we take the operands from either the default case, or from
23314f24155SBrian Gesiak     // the case branch that was taken.
23414f24155SBrian Gesiak     if (switchOp.defaultDestination() == current)
23514f24155SBrian Gesiak       return switchOp.defaultOperands()[index];
23614f24155SBrian Gesiak     for (auto i : llvm::enumerate(switchOp.caseDestinations()))
23714f24155SBrian Gesiak       if (i.value() == current)
23814f24155SBrian Gesiak         return switchOp.getCaseOperands(i.index())[index];
23914f24155SBrian Gesiak   }
24014f24155SBrian Gesiak 
24114f24155SBrian Gesiak   llvm_unreachable("only branch or switch operations can be terminators of a "
24214f24155SBrian Gesiak                    "block that has successors");
243d9067dcaSKiran Chandramohan }
244d9067dcaSKiran Chandramohan 
245d9067dcaSKiran Chandramohan /// Connect the PHI nodes to the results of preceding blocks.
24666900b3eSAlex Zinenko void mlir::LLVM::detail::connectPHINodes(Region &region,
24766900b3eSAlex Zinenko                                          const ModuleTranslation &state) {
248d9067dcaSKiran Chandramohan   // Skip the first block, it cannot be branched to and its arguments correspond
249d9067dcaSKiran Chandramohan   // to the arguments of the LLVM function.
25066900b3eSAlex Zinenko   for (auto it = std::next(region.begin()), eit = region.end(); it != eit;
25166900b3eSAlex Zinenko        ++it) {
252d9067dcaSKiran Chandramohan     Block *bb = &*it;
2530881a4f1SAlex Zinenko     llvm::BasicBlock *llvmBB = state.lookupBlock(bb);
254d9067dcaSKiran Chandramohan     auto phis = llvmBB->phis();
255d9067dcaSKiran Chandramohan     auto numArguments = bb->getNumArguments();
256d9067dcaSKiran Chandramohan     assert(numArguments == std::distance(phis.begin(), phis.end()));
257d9067dcaSKiran Chandramohan     for (auto &numberedPhiNode : llvm::enumerate(phis)) {
258d9067dcaSKiran Chandramohan       auto &phiNode = numberedPhiNode.value();
259d9067dcaSKiran Chandramohan       unsigned index = numberedPhiNode.index();
260d9067dcaSKiran Chandramohan       for (auto *pred : bb->getPredecessors()) {
261db884dafSAlex Zinenko         // Find the LLVM IR block that contains the converted terminator
262db884dafSAlex Zinenko         // instruction and use it in the PHI node. Note that this block is not
2630881a4f1SAlex Zinenko         // necessarily the same as state.lookupBlock(pred), some operations
264db884dafSAlex Zinenko         // (in particular, OpenMP operations using OpenMPIRBuilder) may have
265db884dafSAlex Zinenko         // split the blocks.
266db884dafSAlex Zinenko         llvm::Instruction *terminator =
2670881a4f1SAlex Zinenko             state.lookupBranch(pred->getTerminator());
268db884dafSAlex Zinenko         assert(terminator && "missing the mapping for a terminator");
2690881a4f1SAlex Zinenko         phiNode.addIncoming(
2700881a4f1SAlex Zinenko             state.lookupValue(getPHISourceValue(bb, pred, numArguments, index)),
271db884dafSAlex Zinenko             terminator->getParent());
272d9067dcaSKiran Chandramohan       }
273d9067dcaSKiran Chandramohan     }
274d9067dcaSKiran Chandramohan   }
275d9067dcaSKiran Chandramohan }
276d9067dcaSKiran Chandramohan 
277d9067dcaSKiran Chandramohan /// Sort function blocks topologically.
27866900b3eSAlex Zinenko llvm::SetVector<Block *>
27966900b3eSAlex Zinenko mlir::LLVM::detail::getTopologicallySortedBlocks(Region &region) {
280d4568ed7SGeorge Mitenkov   // For each block that has not been visited yet (i.e. that has no
281d4568ed7SGeorge Mitenkov   // predecessors), add it to the list as well as its successors.
282d9067dcaSKiran Chandramohan   llvm::SetVector<Block *> blocks;
28366900b3eSAlex Zinenko   for (Block &b : region) {
284d4568ed7SGeorge Mitenkov     if (blocks.count(&b) == 0) {
285d4568ed7SGeorge Mitenkov       llvm::ReversePostOrderTraversal<Block *> traversal(&b);
286d4568ed7SGeorge Mitenkov       blocks.insert(traversal.begin(), traversal.end());
287d4568ed7SGeorge Mitenkov     }
288d9067dcaSKiran Chandramohan   }
28966900b3eSAlex Zinenko   assert(blocks.size() == region.getBlocks().size() &&
29066900b3eSAlex Zinenko          "some blocks are not sorted");
291d9067dcaSKiran Chandramohan 
292d9067dcaSKiran Chandramohan   return blocks;
293d9067dcaSKiran Chandramohan }
294d9067dcaSKiran Chandramohan 
295176379e0SAlex Zinenko llvm::Value *mlir::LLVM::detail::createIntrinsicCall(
296176379e0SAlex Zinenko     llvm::IRBuilderBase &builder, llvm::Intrinsic::ID intrinsic,
297176379e0SAlex Zinenko     ArrayRef<llvm::Value *> args, ArrayRef<llvm::Type *> tys) {
298176379e0SAlex Zinenko   llvm::Module *module = builder.GetInsertBlock()->getModule();
299176379e0SAlex Zinenko   llvm::Function *fn = llvm::Intrinsic::getDeclaration(module, intrinsic, tys);
300176379e0SAlex Zinenko   return builder.CreateCall(fn, args);
301176379e0SAlex Zinenko }
302176379e0SAlex Zinenko 
3032666b973SRiver Riddle /// Given a single MLIR operation, create the corresponding LLVM IR operation
304176379e0SAlex Zinenko /// using the `builder`.
305ce8f10d6SAlex Zinenko LogicalResult
306ce8f10d6SAlex Zinenko ModuleTranslation::convertOperation(Operation &opInst,
307ce8f10d6SAlex Zinenko                                     llvm::IRBuilderBase &builder) {
308176379e0SAlex Zinenko   if (failed(iface.convertOperation(&opInst, builder, *this)))
309baa1ec22SAlex Zinenko     return opInst.emitError("unsupported or non-LLVM operation: ")
310baa1ec22SAlex Zinenko            << opInst.getName();
311176379e0SAlex Zinenko 
312176379e0SAlex Zinenko   return convertDialectAttributes(&opInst);
3135d7231d8SStephan Herhut }
3145d7231d8SStephan Herhut 
3152666b973SRiver Riddle /// Convert block to LLVM IR.  Unless `ignoreArguments` is set, emit PHI nodes
3162666b973SRiver Riddle /// to define values corresponding to the MLIR block arguments.  These nodes
31710164a2eSAlex Zinenko /// are not connected to the source basic blocks, which may not exist yet.  Uses
31810164a2eSAlex Zinenko /// `builder` to construct the LLVM IR. Expects the LLVM IR basic block to have
31910164a2eSAlex Zinenko /// been created for `bb` and included in the block mapping.  Inserts new
32010164a2eSAlex Zinenko /// instructions at the end of the block and leaves `builder` in a state
32110164a2eSAlex Zinenko /// suitable for further insertion into the end of the block.
32210164a2eSAlex Zinenko LogicalResult ModuleTranslation::convertBlock(Block &bb, bool ignoreArguments,
323ce8f10d6SAlex Zinenko                                               llvm::IRBuilderBase &builder) {
3240881a4f1SAlex Zinenko   builder.SetInsertPoint(lookupBlock(&bb));
325c33d6970SRiver Riddle   auto *subprogram = builder.GetInsertBlock()->getParent()->getSubprogram();
3265d7231d8SStephan Herhut 
3275d7231d8SStephan Herhut   // Before traversing operations, make block arguments available through
3285d7231d8SStephan Herhut   // value remapping and PHI nodes, but do not add incoming edges for the PHI
3295d7231d8SStephan Herhut   // nodes just yet: those values may be defined by this or following blocks.
3305d7231d8SStephan Herhut   // This step is omitted if "ignoreArguments" is set.  The arguments of the
3315d7231d8SStephan Herhut   // first block have been already made available through the remapping of
3325d7231d8SStephan Herhut   // LLVM function arguments.
3335d7231d8SStephan Herhut   if (!ignoreArguments) {
3345d7231d8SStephan Herhut     auto predecessors = bb.getPredecessors();
3355d7231d8SStephan Herhut     unsigned numPredecessors =
3365d7231d8SStephan Herhut         std::distance(predecessors.begin(), predecessors.end());
33735807bc4SRiver Riddle     for (auto arg : bb.getArguments()) {
338c69c9e0fSAlex Zinenko       auto wrappedType = arg.getType();
339c69c9e0fSAlex Zinenko       if (!isCompatibleType(wrappedType))
340baa1ec22SAlex Zinenko         return emitError(bb.front().getLoc(),
341a4c3a645SRiver Riddle                          "block argument does not have an LLVM type");
342aec38c61SAlex Zinenko       llvm::Type *type = convertType(wrappedType);
3435d7231d8SStephan Herhut       llvm::PHINode *phi = builder.CreatePHI(type, numPredecessors);
3440881a4f1SAlex Zinenko       mapValue(arg, phi);
3455d7231d8SStephan Herhut     }
3465d7231d8SStephan Herhut   }
3475d7231d8SStephan Herhut 
3485d7231d8SStephan Herhut   // Traverse operations.
3495d7231d8SStephan Herhut   for (auto &op : bb) {
350c33d6970SRiver Riddle     // Set the current debug location within the builder.
351c33d6970SRiver Riddle     builder.SetCurrentDebugLocation(
352c33d6970SRiver Riddle         debugTranslation->translateLoc(op.getLoc(), subprogram));
353c33d6970SRiver Riddle 
354baa1ec22SAlex Zinenko     if (failed(convertOperation(op, builder)))
355baa1ec22SAlex Zinenko       return failure();
3565d7231d8SStephan Herhut   }
3575d7231d8SStephan Herhut 
358baa1ec22SAlex Zinenko   return success();
3595d7231d8SStephan Herhut }
3605d7231d8SStephan Herhut 
361ce8f10d6SAlex Zinenko /// A helper method to get the single Block in an operation honoring LLVM's
362ce8f10d6SAlex Zinenko /// module requirements.
363ce8f10d6SAlex Zinenko static Block &getModuleBody(Operation *module) {
364ce8f10d6SAlex Zinenko   return module->getRegion(0).front();
365ce8f10d6SAlex Zinenko }
366ce8f10d6SAlex Zinenko 
367*ffa455d4SJean Perier /// A helper method to decide if a constant must not be set as a global variable
368*ffa455d4SJean Perier /// initializer.
369*ffa455d4SJean Perier static bool shouldDropGlobalInitializer(llvm::GlobalValue::LinkageTypes linkage,
370*ffa455d4SJean Perier                                         llvm::Constant *cst) {
371*ffa455d4SJean Perier   return (linkage == llvm::GlobalVariable::ExternalLinkage &&
372*ffa455d4SJean Perier           isa<llvm::UndefValue>(cst)) ||
373*ffa455d4SJean Perier          linkage == llvm::GlobalVariable::ExternalWeakLinkage;
374*ffa455d4SJean Perier }
375*ffa455d4SJean Perier 
3762666b973SRiver Riddle /// Create named global variables that correspond to llvm.mlir.global
3772666b973SRiver Riddle /// definitions.
378efa2d533SAlex Zinenko LogicalResult ModuleTranslation::convertGlobals() {
37944fc7d72STres Popp   for (auto op : getModuleBody(mlirModule).getOps<LLVM::GlobalOp>()) {
380aec38c61SAlex Zinenko     llvm::Type *type = convertType(op.getType());
381250a11aeSJames Molloy     llvm::Constant *cst = llvm::UndefValue::get(type);
382250a11aeSJames Molloy     if (op.getValueOrNull()) {
38368451df2SAlex Zinenko       // String attributes are treated separately because they cannot appear as
38468451df2SAlex Zinenko       // in-function constants and are thus not supported by getLLVMConstant.
38533a3a91bSChristian Sigg       if (auto strAttr = op.getValueOrNull().dyn_cast_or_null<StringAttr>()) {
3862dd38b09SAlex Zinenko         cst = llvm::ConstantDataArray::getString(
38768451df2SAlex Zinenko             llvmModule->getContext(), strAttr.getValue(), /*AddNull=*/false);
3882dd38b09SAlex Zinenko         type = cst->getType();
389176379e0SAlex Zinenko       } else if (!(cst = getLLVMConstant(type, op.getValueOrNull(), op.getLoc(),
390176379e0SAlex Zinenko                                          *this))) {
391efa2d533SAlex Zinenko         return failure();
39268451df2SAlex Zinenko       }
393*ffa455d4SJean Perier     }
394*ffa455d4SJean Perier 
395*ffa455d4SJean Perier     auto linkage = convertLinkageToLLVM(op.linkage());
396*ffa455d4SJean Perier     auto addrSpace = op.addr_space();
397*ffa455d4SJean Perier     auto *var = new llvm::GlobalVariable(
398*ffa455d4SJean Perier         *llvmModule, type, op.constant(), linkage,
399*ffa455d4SJean Perier         shouldDropGlobalInitializer(linkage, cst) ? nullptr : cst,
400*ffa455d4SJean Perier         op.sym_name(),
401*ffa455d4SJean Perier         /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal, addrSpace);
402*ffa455d4SJean Perier 
403*ffa455d4SJean Perier     globalsMapping.try_emplace(op, var);
404*ffa455d4SJean Perier   }
405*ffa455d4SJean Perier 
406*ffa455d4SJean Perier   // Convert global variable bodies. This is done after all global variables
407*ffa455d4SJean Perier   // have been created in LLVM IR because a global body may refer to another
408*ffa455d4SJean Perier   // global or itself. So all global variables need to be mapped first.
409*ffa455d4SJean Perier   for (auto op : getModuleBody(mlirModule).getOps<LLVM::GlobalOp>()) {
410*ffa455d4SJean Perier     if (Block *initializer = op.getInitializerBlock()) {
411250a11aeSJames Molloy       llvm::IRBuilder<> builder(llvmModule->getContext());
412250a11aeSJames Molloy       for (auto &op : initializer->without_terminator()) {
413250a11aeSJames Molloy         if (failed(convertOperation(op, builder)) ||
4140881a4f1SAlex Zinenko             !isa<llvm::Constant>(lookupValue(op.getResult(0))))
415efa2d533SAlex Zinenko           return emitError(op.getLoc(), "unemittable constant value");
416250a11aeSJames Molloy       }
417250a11aeSJames Molloy       ReturnOp ret = cast<ReturnOp>(initializer->getTerminator());
418*ffa455d4SJean Perier       llvm::Constant *cst =
419*ffa455d4SJean Perier           cast<llvm::Constant>(lookupValue(ret.getOperand(0)));
420*ffa455d4SJean Perier       auto *global = cast<llvm::GlobalVariable>(lookupGlobal(op));
421*ffa455d4SJean Perier       if (!shouldDropGlobalInitializer(global->getLinkage(), cst))
422*ffa455d4SJean Perier         global->setInitializer(cst);
423250a11aeSJames Molloy     }
424b9ff2dd8SAlex Zinenko   }
425efa2d533SAlex Zinenko 
426efa2d533SAlex Zinenko   return success();
427b9ff2dd8SAlex Zinenko }
428b9ff2dd8SAlex Zinenko 
4290a2131b7SAlex Zinenko /// Attempts to add an attribute identified by `key`, optionally with the given
4300a2131b7SAlex Zinenko /// `value` to LLVM function `llvmFunc`. Reports errors at `loc` if any. If the
4310a2131b7SAlex Zinenko /// attribute has a kind known to LLVM IR, create the attribute of this kind,
4320a2131b7SAlex Zinenko /// otherwise keep it as a string attribute. Performs additional checks for
4330a2131b7SAlex Zinenko /// attributes known to have or not have a value in order to avoid assertions
4340a2131b7SAlex Zinenko /// inside LLVM upon construction.
4350a2131b7SAlex Zinenko static LogicalResult checkedAddLLVMFnAttribute(Location loc,
4360a2131b7SAlex Zinenko                                                llvm::Function *llvmFunc,
4370a2131b7SAlex Zinenko                                                StringRef key,
4380a2131b7SAlex Zinenko                                                StringRef value = StringRef()) {
4390a2131b7SAlex Zinenko   auto kind = llvm::Attribute::getAttrKindFromName(key);
4400a2131b7SAlex Zinenko   if (kind == llvm::Attribute::None) {
4410a2131b7SAlex Zinenko     llvmFunc->addFnAttr(key, value);
4420a2131b7SAlex Zinenko     return success();
4430a2131b7SAlex Zinenko   }
4440a2131b7SAlex Zinenko 
4450a2131b7SAlex Zinenko   if (llvm::Attribute::doesAttrKindHaveArgument(kind)) {
4460a2131b7SAlex Zinenko     if (value.empty())
4470a2131b7SAlex Zinenko       return emitError(loc) << "LLVM attribute '" << key << "' expects a value";
4480a2131b7SAlex Zinenko 
4490a2131b7SAlex Zinenko     int result;
4500a2131b7SAlex Zinenko     if (!value.getAsInteger(/*Radix=*/0, result))
4510a2131b7SAlex Zinenko       llvmFunc->addFnAttr(
4520a2131b7SAlex Zinenko           llvm::Attribute::get(llvmFunc->getContext(), kind, result));
4530a2131b7SAlex Zinenko     else
4540a2131b7SAlex Zinenko       llvmFunc->addFnAttr(key, value);
4550a2131b7SAlex Zinenko     return success();
4560a2131b7SAlex Zinenko   }
4570a2131b7SAlex Zinenko 
4580a2131b7SAlex Zinenko   if (!value.empty())
4590a2131b7SAlex Zinenko     return emitError(loc) << "LLVM attribute '" << key
4600a2131b7SAlex Zinenko                           << "' does not expect a value, found '" << value
4610a2131b7SAlex Zinenko                           << "'";
4620a2131b7SAlex Zinenko 
4630a2131b7SAlex Zinenko   llvmFunc->addFnAttr(kind);
4640a2131b7SAlex Zinenko   return success();
4650a2131b7SAlex Zinenko }
4660a2131b7SAlex Zinenko 
4670a2131b7SAlex Zinenko /// Attaches the attributes listed in the given array attribute to `llvmFunc`.
4680a2131b7SAlex Zinenko /// Reports error to `loc` if any and returns immediately. Expects `attributes`
4690a2131b7SAlex Zinenko /// to be an array attribute containing either string attributes, treated as
4700a2131b7SAlex Zinenko /// value-less LLVM attributes, or array attributes containing two string
4710a2131b7SAlex Zinenko /// attributes, with the first string being the name of the corresponding LLVM
4720a2131b7SAlex Zinenko /// attribute and the second string beings its value. Note that even integer
4730a2131b7SAlex Zinenko /// attributes are expected to have their values expressed as strings.
4740a2131b7SAlex Zinenko static LogicalResult
4750a2131b7SAlex Zinenko forwardPassthroughAttributes(Location loc, Optional<ArrayAttr> attributes,
4760a2131b7SAlex Zinenko                              llvm::Function *llvmFunc) {
4770a2131b7SAlex Zinenko   if (!attributes)
4780a2131b7SAlex Zinenko     return success();
4790a2131b7SAlex Zinenko 
4800a2131b7SAlex Zinenko   for (Attribute attr : *attributes) {
4810a2131b7SAlex Zinenko     if (auto stringAttr = attr.dyn_cast<StringAttr>()) {
4820a2131b7SAlex Zinenko       if (failed(
4830a2131b7SAlex Zinenko               checkedAddLLVMFnAttribute(loc, llvmFunc, stringAttr.getValue())))
4840a2131b7SAlex Zinenko         return failure();
4850a2131b7SAlex Zinenko       continue;
4860a2131b7SAlex Zinenko     }
4870a2131b7SAlex Zinenko 
4880a2131b7SAlex Zinenko     auto arrayAttr = attr.dyn_cast<ArrayAttr>();
4890a2131b7SAlex Zinenko     if (!arrayAttr || arrayAttr.size() != 2)
4900a2131b7SAlex Zinenko       return emitError(loc)
4910a2131b7SAlex Zinenko              << "expected 'passthrough' to contain string or array attributes";
4920a2131b7SAlex Zinenko 
4930a2131b7SAlex Zinenko     auto keyAttr = arrayAttr[0].dyn_cast<StringAttr>();
4940a2131b7SAlex Zinenko     auto valueAttr = arrayAttr[1].dyn_cast<StringAttr>();
4950a2131b7SAlex Zinenko     if (!keyAttr || !valueAttr)
4960a2131b7SAlex Zinenko       return emitError(loc)
4970a2131b7SAlex Zinenko              << "expected arrays within 'passthrough' to contain two strings";
4980a2131b7SAlex Zinenko 
4990a2131b7SAlex Zinenko     if (failed(checkedAddLLVMFnAttribute(loc, llvmFunc, keyAttr.getValue(),
5000a2131b7SAlex Zinenko                                          valueAttr.getValue())))
5010a2131b7SAlex Zinenko       return failure();
5020a2131b7SAlex Zinenko   }
5030a2131b7SAlex Zinenko   return success();
5040a2131b7SAlex Zinenko }
5050a2131b7SAlex Zinenko 
5065e7959a3SAlex Zinenko LogicalResult ModuleTranslation::convertOneFunction(LLVMFuncOp func) {
507db884dafSAlex Zinenko   // Clear the block, branch value mappings, they are only relevant within one
5085d7231d8SStephan Herhut   // function.
5095d7231d8SStephan Herhut   blockMapping.clear();
5105d7231d8SStephan Herhut   valueMapping.clear();
511db884dafSAlex Zinenko   branchMapping.clear();
5120881a4f1SAlex Zinenko   llvm::Function *llvmFunc = lookupFunction(func.getName());
513c33d6970SRiver Riddle 
514c33d6970SRiver Riddle   // Translate the debug information for this function.
515c33d6970SRiver Riddle   debugTranslation->translate(func, *llvmFunc);
516c33d6970SRiver Riddle 
5175d7231d8SStephan Herhut   // Add function arguments to the value remapping table.
5185d7231d8SStephan Herhut   // If there was noalias info then we decorate each argument accordingly.
5195d7231d8SStephan Herhut   unsigned int argIdx = 0;
520eeef50b1SFangrui Song   for (auto kvp : llvm::zip(func.getArguments(), llvmFunc->args())) {
5215d7231d8SStephan Herhut     llvm::Argument &llvmArg = std::get<1>(kvp);
522e62a6956SRiver Riddle     BlockArgument mlirArg = std::get<0>(kvp);
5235d7231d8SStephan Herhut 
52467cc5cecSStephan Herhut     if (auto attr = func.getArgAttrOfType<BoolAttr>(
52567cc5cecSStephan Herhut             argIdx, LLVMDialect::getNoAliasAttrName())) {
5265d7231d8SStephan Herhut       // NB: Attribute already verified to be boolean, so check if we can indeed
5275d7231d8SStephan Herhut       // attach the attribute to this argument, based on its type.
528c69c9e0fSAlex Zinenko       auto argTy = mlirArg.getType();
5298de43b92SAlex Zinenko       if (!argTy.isa<LLVM::LLVMPointerType>())
530baa1ec22SAlex Zinenko         return func.emitError(
5315d7231d8SStephan Herhut             "llvm.noalias attribute attached to LLVM non-pointer argument");
5325d7231d8SStephan Herhut       if (attr.getValue())
5335d7231d8SStephan Herhut         llvmArg.addAttr(llvm::Attribute::AttrKind::NoAlias);
5345d7231d8SStephan Herhut     }
5352416e28cSStephan Herhut 
53667cc5cecSStephan Herhut     if (auto attr = func.getArgAttrOfType<IntegerAttr>(
53767cc5cecSStephan Herhut             argIdx, LLVMDialect::getAlignAttrName())) {
5382416e28cSStephan Herhut       // NB: Attribute already verified to be int, so check if we can indeed
5392416e28cSStephan Herhut       // attach the attribute to this argument, based on its type.
540c69c9e0fSAlex Zinenko       auto argTy = mlirArg.getType();
5418de43b92SAlex Zinenko       if (!argTy.isa<LLVM::LLVMPointerType>())
5422416e28cSStephan Herhut         return func.emitError(
5432416e28cSStephan Herhut             "llvm.align attribute attached to LLVM non-pointer argument");
5442416e28cSStephan Herhut       llvmArg.addAttrs(
5452416e28cSStephan Herhut           llvm::AttrBuilder().addAlignmentAttr(llvm::Align(attr.getInt())));
5462416e28cSStephan Herhut     }
5472416e28cSStephan Herhut 
54870b841acSEric Schweitz     if (auto attr = func.getArgAttrOfType<UnitAttr>(argIdx, "llvm.sret")) {
54970b841acSEric Schweitz       auto argTy = mlirArg.getType();
55070b841acSEric Schweitz       if (!argTy.isa<LLVM::LLVMPointerType>())
55170b841acSEric Schweitz         return func.emitError(
55270b841acSEric Schweitz             "llvm.sret attribute attached to LLVM non-pointer argument");
5531d6df1fcSEric Schweitz       llvmArg.addAttrs(llvm::AttrBuilder().addStructRetAttr(
5541d6df1fcSEric Schweitz           llvmArg.getType()->getPointerElementType()));
55570b841acSEric Schweitz     }
55670b841acSEric Schweitz 
55770b841acSEric Schweitz     if (auto attr = func.getArgAttrOfType<UnitAttr>(argIdx, "llvm.byval")) {
55870b841acSEric Schweitz       auto argTy = mlirArg.getType();
55970b841acSEric Schweitz       if (!argTy.isa<LLVM::LLVMPointerType>())
56070b841acSEric Schweitz         return func.emitError(
56170b841acSEric Schweitz             "llvm.byval attribute attached to LLVM non-pointer argument");
5621d6df1fcSEric Schweitz       llvmArg.addAttrs(llvm::AttrBuilder().addByValAttr(
5631d6df1fcSEric Schweitz           llvmArg.getType()->getPointerElementType()));
56470b841acSEric Schweitz     }
56570b841acSEric Schweitz 
5660881a4f1SAlex Zinenko     mapValue(mlirArg, &llvmArg);
5675d7231d8SStephan Herhut     argIdx++;
5685d7231d8SStephan Herhut   }
5695d7231d8SStephan Herhut 
570ff77397fSShraiysh Vaishay   // Check the personality and set it.
571ff77397fSShraiysh Vaishay   if (func.personality().hasValue()) {
572ff77397fSShraiysh Vaishay     llvm::Type *ty = llvm::Type::getInt8PtrTy(llvmFunc->getContext());
573ff77397fSShraiysh Vaishay     if (llvm::Constant *pfunc =
574176379e0SAlex Zinenko             getLLVMConstant(ty, func.personalityAttr(), func.getLoc(), *this))
575ff77397fSShraiysh Vaishay       llvmFunc->setPersonalityFn(pfunc);
576ff77397fSShraiysh Vaishay   }
577ff77397fSShraiysh Vaishay 
5785d7231d8SStephan Herhut   // First, create all blocks so we can jump to them.
5795d7231d8SStephan Herhut   llvm::LLVMContext &llvmContext = llvmFunc->getContext();
5805d7231d8SStephan Herhut   for (auto &bb : func) {
5815d7231d8SStephan Herhut     auto *llvmBB = llvm::BasicBlock::Create(llvmContext);
5825d7231d8SStephan Herhut     llvmBB->insertInto(llvmFunc);
5830881a4f1SAlex Zinenko     mapBlock(&bb, llvmBB);
5845d7231d8SStephan Herhut   }
5855d7231d8SStephan Herhut 
5865d7231d8SStephan Herhut   // Then, convert blocks one by one in topological order to ensure defs are
5875d7231d8SStephan Herhut   // converted before uses.
58866900b3eSAlex Zinenko   auto blocks = detail::getTopologicallySortedBlocks(func.getBody());
58910164a2eSAlex Zinenko   for (Block *bb : blocks) {
59010164a2eSAlex Zinenko     llvm::IRBuilder<> builder(llvmContext);
59110164a2eSAlex Zinenko     if (failed(convertBlock(*bb, bb->isEntryBlock(), builder)))
592baa1ec22SAlex Zinenko       return failure();
5935d7231d8SStephan Herhut   }
5945d7231d8SStephan Herhut 
595176379e0SAlex Zinenko   // After all blocks have been traversed and values mapped, connect the PHI
596176379e0SAlex Zinenko   // nodes to the results of preceding blocks.
59766900b3eSAlex Zinenko   detail::connectPHINodes(func.getBody(), *this);
598176379e0SAlex Zinenko 
599176379e0SAlex Zinenko   // Finally, convert dialect attributes attached to the function.
600176379e0SAlex Zinenko   return convertDialectAttributes(func);
601176379e0SAlex Zinenko }
602176379e0SAlex Zinenko 
603176379e0SAlex Zinenko LogicalResult ModuleTranslation::convertDialectAttributes(Operation *op) {
604176379e0SAlex Zinenko   for (NamedAttribute attribute : op->getDialectAttrs())
605176379e0SAlex Zinenko     if (failed(iface.amendOperation(op, attribute, *this)))
606176379e0SAlex Zinenko       return failure();
607baa1ec22SAlex Zinenko   return success();
6085d7231d8SStephan Herhut }
6095d7231d8SStephan Herhut 
610ce8f10d6SAlex Zinenko /// Check whether the module contains only supported ops directly in its body.
611ce8f10d6SAlex Zinenko static LogicalResult checkSupportedModuleOps(Operation *m) {
61244fc7d72STres Popp   for (Operation &o : getModuleBody(m).getOperations())
6134a2930f4SArpith C. Jacob     if (!isa<LLVM::LLVMFuncOp, LLVM::GlobalOp, LLVM::MetadataOp>(&o) &&
614fe7c0d90SRiver Riddle         !o.hasTrait<OpTrait::IsTerminator>())
6154dde19f0SAlex Zinenko       return o.emitOpError("unsupported module-level operation");
6164dde19f0SAlex Zinenko   return success();
6174dde19f0SAlex Zinenko }
6184dde19f0SAlex Zinenko 
619a084b94fSSean Silva LogicalResult ModuleTranslation::convertFunctionSignatures() {
6205d7231d8SStephan Herhut   // Declare all functions first because there may be function calls that form a
621a084b94fSSean Silva   // call graph with cycles, or global initializers that reference functions.
62244fc7d72STres Popp   for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) {
6235e7959a3SAlex Zinenko     llvm::FunctionCallee llvmFuncCst = llvmModule->getOrInsertFunction(
6245e7959a3SAlex Zinenko         function.getName(),
625aec38c61SAlex Zinenko         cast<llvm::FunctionType>(convertType(function.getType())));
6260a2131b7SAlex Zinenko     llvm::Function *llvmFunc = cast<llvm::Function>(llvmFuncCst.getCallee());
627ebbdecddSAlex Zinenko     llvmFunc->setLinkage(convertLinkageToLLVM(function.linkage()));
6280881a4f1SAlex Zinenko     mapFunction(function.getName(), llvmFunc);
6290a2131b7SAlex Zinenko 
6300a2131b7SAlex Zinenko     // Forward the pass-through attributes to LLVM.
6310a2131b7SAlex Zinenko     if (failed(forwardPassthroughAttributes(function.getLoc(),
6320a2131b7SAlex Zinenko                                             function.passthrough(), llvmFunc)))
6330a2131b7SAlex Zinenko       return failure();
6345d7231d8SStephan Herhut   }
6355d7231d8SStephan Herhut 
636a084b94fSSean Silva   return success();
637a084b94fSSean Silva }
638a084b94fSSean Silva 
639a084b94fSSean Silva LogicalResult ModuleTranslation::convertFunctions() {
6405d7231d8SStephan Herhut   // Convert functions.
64144fc7d72STres Popp   for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) {
6425d7231d8SStephan Herhut     // Ignore external functions.
6435d7231d8SStephan Herhut     if (function.isExternal())
6445d7231d8SStephan Herhut       continue;
6455d7231d8SStephan Herhut 
646baa1ec22SAlex Zinenko     if (failed(convertOneFunction(function)))
647baa1ec22SAlex Zinenko       return failure();
6485d7231d8SStephan Herhut   }
6495d7231d8SStephan Herhut 
650baa1ec22SAlex Zinenko   return success();
6515d7231d8SStephan Herhut }
6525d7231d8SStephan Herhut 
6534a2930f4SArpith C. Jacob llvm::MDNode *
6544a2930f4SArpith C. Jacob ModuleTranslation::getAccessGroup(Operation &opInst,
6554a2930f4SArpith C. Jacob                                   SymbolRefAttr accessGroupRef) const {
6564a2930f4SArpith C. Jacob   auto metadataName = accessGroupRef.getRootReference();
6574a2930f4SArpith C. Jacob   auto accessGroupName = accessGroupRef.getLeafReference();
6584a2930f4SArpith C. Jacob   auto metadataOp = SymbolTable::lookupNearestSymbolFrom<LLVM::MetadataOp>(
6594a2930f4SArpith C. Jacob       opInst.getParentOp(), metadataName);
6604a2930f4SArpith C. Jacob   auto *accessGroupOp =
6614a2930f4SArpith C. Jacob       SymbolTable::lookupNearestSymbolFrom(metadataOp, accessGroupName);
6624a2930f4SArpith C. Jacob   return accessGroupMetadataMapping.lookup(accessGroupOp);
6634a2930f4SArpith C. Jacob }
6644a2930f4SArpith C. Jacob 
6654a2930f4SArpith C. Jacob LogicalResult ModuleTranslation::createAccessGroupMetadata() {
6664a2930f4SArpith C. Jacob   mlirModule->walk([&](LLVM::MetadataOp metadatas) {
6674a2930f4SArpith C. Jacob     metadatas.walk([&](LLVM::AccessGroupMetadataOp op) {
6684a2930f4SArpith C. Jacob       llvm::LLVMContext &ctx = llvmModule->getContext();
6694a2930f4SArpith C. Jacob       llvm::MDNode *accessGroup = llvm::MDNode::getDistinct(ctx, {});
6704a2930f4SArpith C. Jacob       accessGroupMetadataMapping.insert({op, accessGroup});
6714a2930f4SArpith C. Jacob     });
6724a2930f4SArpith C. Jacob   });
6734a2930f4SArpith C. Jacob   return success();
6744a2930f4SArpith C. Jacob }
6754a2930f4SArpith C. Jacob 
6764e393350SArpith C. Jacob void ModuleTranslation::setAccessGroupsMetadata(Operation *op,
6774e393350SArpith C. Jacob                                                 llvm::Instruction *inst) {
6784e393350SArpith C. Jacob   auto accessGroups =
6794e393350SArpith C. Jacob       op->getAttrOfType<ArrayAttr>(LLVMDialect::getAccessGroupsAttrName());
6804e393350SArpith C. Jacob   if (accessGroups && !accessGroups.empty()) {
6814e393350SArpith C. Jacob     llvm::Module *module = inst->getModule();
6824e393350SArpith C. Jacob     SmallVector<llvm::Metadata *> metadatas;
6834e393350SArpith C. Jacob     for (SymbolRefAttr accessGroupRef :
6844e393350SArpith C. Jacob          accessGroups.getAsRange<SymbolRefAttr>())
6854e393350SArpith C. Jacob       metadatas.push_back(getAccessGroup(*op, accessGroupRef));
6864e393350SArpith C. Jacob 
6874e393350SArpith C. Jacob     llvm::MDNode *unionMD = nullptr;
6884e393350SArpith C. Jacob     if (metadatas.size() == 1)
6894e393350SArpith C. Jacob       unionMD = llvm::cast<llvm::MDNode>(metadatas.front());
6904e393350SArpith C. Jacob     else if (metadatas.size() >= 2)
6914e393350SArpith C. Jacob       unionMD = llvm::MDNode::get(module->getContext(), metadatas);
6924e393350SArpith C. Jacob 
6934e393350SArpith C. Jacob     inst->setMetadata(module->getMDKindID("llvm.access.group"), unionMD);
6944e393350SArpith C. Jacob   }
6954e393350SArpith C. Jacob }
6964e393350SArpith C. Jacob 
697c69c9e0fSAlex Zinenko llvm::Type *ModuleTranslation::convertType(Type type) {
698b2ab375dSAlex Zinenko   return typeTranslator.translateType(type);
699aec38c61SAlex Zinenko }
700aec38c61SAlex Zinenko 
701efadb6b8SAlex Zinenko /// A helper to look up remapped operands in the value remapping table.`
702efadb6b8SAlex Zinenko SmallVector<llvm::Value *, 8>
703efadb6b8SAlex Zinenko ModuleTranslation::lookupValues(ValueRange values) {
704efadb6b8SAlex Zinenko   SmallVector<llvm::Value *, 8> remapped;
705efadb6b8SAlex Zinenko   remapped.reserve(values.size());
7060881a4f1SAlex Zinenko   for (Value v : values)
7070881a4f1SAlex Zinenko     remapped.push_back(lookupValue(v));
708efadb6b8SAlex Zinenko   return remapped;
709efadb6b8SAlex Zinenko }
710efadb6b8SAlex Zinenko 
71166900b3eSAlex Zinenko const llvm::DILocation *
71266900b3eSAlex Zinenko ModuleTranslation::translateLoc(Location loc, llvm::DILocalScope *scope) {
71366900b3eSAlex Zinenko   return debugTranslation->translateLoc(loc, scope);
71466900b3eSAlex Zinenko }
71566900b3eSAlex Zinenko 
716176379e0SAlex Zinenko llvm::NamedMDNode *
717176379e0SAlex Zinenko ModuleTranslation::getOrInsertNamedModuleMetadata(StringRef name) {
718176379e0SAlex Zinenko   return llvmModule->getOrInsertNamedMetadata(name);
719176379e0SAlex Zinenko }
720176379e0SAlex Zinenko 
721ce8f10d6SAlex Zinenko static std::unique_ptr<llvm::Module>
722ce8f10d6SAlex Zinenko prepareLLVMModule(Operation *m, llvm::LLVMContext &llvmContext,
723ce8f10d6SAlex Zinenko                   StringRef name) {
724f9dc2b70SMehdi Amini   m->getContext()->getOrLoadDialect<LLVM::LLVMDialect>();
725db1c197bSAlex Zinenko   auto llvmModule = std::make_unique<llvm::Module>(name, llvmContext);
726168213f9SAlex Zinenko   if (auto dataLayoutAttr =
727168213f9SAlex Zinenko           m->getAttr(LLVM::LLVMDialect::getDataLayoutAttrName()))
728168213f9SAlex Zinenko     llvmModule->setDataLayout(dataLayoutAttr.cast<StringAttr>().getValue());
7295dd5a083SNicolas Vasilache   if (auto targetTripleAttr =
7305dd5a083SNicolas Vasilache           m->getAttr(LLVM::LLVMDialect::getTargetTripleAttrName()))
7315dd5a083SNicolas Vasilache     llvmModule->setTargetTriple(targetTripleAttr.cast<StringAttr>().getValue());
7325d7231d8SStephan Herhut 
7335d7231d8SStephan Herhut   // Inject declarations for `malloc` and `free` functions that can be used in
7345d7231d8SStephan Herhut   // memref allocation/deallocation coming from standard ops lowering.
735db1c197bSAlex Zinenko   llvm::IRBuilder<> builder(llvmContext);
7365d7231d8SStephan Herhut   llvmModule->getOrInsertFunction("malloc", builder.getInt8PtrTy(),
7375d7231d8SStephan Herhut                                   builder.getInt64Ty());
7385d7231d8SStephan Herhut   llvmModule->getOrInsertFunction("free", builder.getVoidTy(),
7395d7231d8SStephan Herhut                                   builder.getInt8PtrTy());
7405d7231d8SStephan Herhut 
7415d7231d8SStephan Herhut   return llvmModule;
7425d7231d8SStephan Herhut }
743ce8f10d6SAlex Zinenko 
744ce8f10d6SAlex Zinenko std::unique_ptr<llvm::Module>
745ce8f10d6SAlex Zinenko mlir::translateModuleToLLVMIR(Operation *module, llvm::LLVMContext &llvmContext,
746ce8f10d6SAlex Zinenko                               StringRef name) {
747ce8f10d6SAlex Zinenko   if (!satisfiesLLVMModule(module))
748ce8f10d6SAlex Zinenko     return nullptr;
749ce8f10d6SAlex Zinenko   if (failed(checkSupportedModuleOps(module)))
750ce8f10d6SAlex Zinenko     return nullptr;
751ce8f10d6SAlex Zinenko   std::unique_ptr<llvm::Module> llvmModule =
752ce8f10d6SAlex Zinenko       prepareLLVMModule(module, llvmContext, name);
753ce8f10d6SAlex Zinenko 
754ce8f10d6SAlex Zinenko   LLVM::ensureDistinctSuccessors(module);
755ce8f10d6SAlex Zinenko 
756ce8f10d6SAlex Zinenko   ModuleTranslation translator(module, std::move(llvmModule));
757ce8f10d6SAlex Zinenko   if (failed(translator.convertFunctionSignatures()))
758ce8f10d6SAlex Zinenko     return nullptr;
759ce8f10d6SAlex Zinenko   if (failed(translator.convertGlobals()))
760ce8f10d6SAlex Zinenko     return nullptr;
7614a2930f4SArpith C. Jacob   if (failed(translator.createAccessGroupMetadata()))
7624a2930f4SArpith C. Jacob     return nullptr;
763ce8f10d6SAlex Zinenko   if (failed(translator.convertFunctions()))
764ce8f10d6SAlex Zinenko     return nullptr;
765ce8f10d6SAlex Zinenko   if (llvm::verifyModule(*translator.llvmModule, &llvm::errs()))
766ce8f10d6SAlex Zinenko     return nullptr;
767ce8f10d6SAlex Zinenko 
768ce8f10d6SAlex Zinenko   return std::move(translator.llvmModule);
769ce8f10d6SAlex Zinenko }
770