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" 38875eb523SNavdeep Kumar #include "llvm/IR/IntrinsicsNVPTX.h" 395d7231d8SStephan Herhut #include "llvm/IR/LLVMContext.h" 4099d03f03SGeorge Mitenkov #include "llvm/IR/MDBuilder.h" 415d7231d8SStephan Herhut #include "llvm/IR/Module.h" 42ce8f10d6SAlex Zinenko #include "llvm/IR/Verifier.h" 43d9067dcaSKiran Chandramohan #include "llvm/Transforms/Utils/BasicBlockUtils.h" 445d7231d8SStephan Herhut #include "llvm/Transforms/Utils/Cloning.h" 455d7231d8SStephan Herhut 462666b973SRiver Riddle using namespace mlir; 472666b973SRiver Riddle using namespace mlir::LLVM; 48c33d6970SRiver Riddle using namespace mlir::LLVM::detail; 495d7231d8SStephan Herhut 50eb67bd78SAlex Zinenko #include "mlir/Dialect/LLVMIR/LLVMConversionEnumsToLLVM.inc" 51eb67bd78SAlex Zinenko 52a922e231SAlex Zinenko /// Builds a constant of a sequential LLVM type `type`, potentially containing 53a922e231SAlex Zinenko /// other sequential types recursively, from the individual constant values 54a922e231SAlex Zinenko /// provided in `constants`. `shape` contains the number of elements in nested 55a922e231SAlex Zinenko /// sequential types. Reports errors at `loc` and returns nullptr on error. 56a4a42160SAlex Zinenko static llvm::Constant * 57a4a42160SAlex Zinenko buildSequentialConstant(ArrayRef<llvm::Constant *> &constants, 58a4a42160SAlex Zinenko ArrayRef<int64_t> shape, llvm::Type *type, 59a4a42160SAlex Zinenko Location loc) { 60a4a42160SAlex Zinenko if (shape.empty()) { 61a4a42160SAlex Zinenko llvm::Constant *result = constants.front(); 62a4a42160SAlex Zinenko constants = constants.drop_front(); 63a4a42160SAlex Zinenko return result; 64a4a42160SAlex Zinenko } 65a4a42160SAlex Zinenko 6668b03aeeSEli Friedman llvm::Type *elementType; 6768b03aeeSEli Friedman if (auto *arrayTy = dyn_cast<llvm::ArrayType>(type)) { 6868b03aeeSEli Friedman elementType = arrayTy->getElementType(); 6968b03aeeSEli Friedman } else if (auto *vectorTy = dyn_cast<llvm::VectorType>(type)) { 7068b03aeeSEli Friedman elementType = vectorTy->getElementType(); 7168b03aeeSEli Friedman } else { 72a4a42160SAlex Zinenko emitError(loc) << "expected sequential LLVM types wrapping a scalar"; 73a4a42160SAlex Zinenko return nullptr; 74a4a42160SAlex Zinenko } 75a4a42160SAlex Zinenko 76a4a42160SAlex Zinenko SmallVector<llvm::Constant *, 8> nested; 77a4a42160SAlex Zinenko nested.reserve(shape.front()); 78a4a42160SAlex Zinenko for (int64_t i = 0; i < shape.front(); ++i) { 79a4a42160SAlex Zinenko nested.push_back(buildSequentialConstant(constants, shape.drop_front(), 80a4a42160SAlex Zinenko elementType, loc)); 81a4a42160SAlex Zinenko if (!nested.back()) 82a4a42160SAlex Zinenko return nullptr; 83a4a42160SAlex Zinenko } 84a4a42160SAlex Zinenko 85a4a42160SAlex Zinenko if (shape.size() == 1 && type->isVectorTy()) 86a4a42160SAlex Zinenko return llvm::ConstantVector::get(nested); 87a4a42160SAlex Zinenko return llvm::ConstantArray::get( 88a4a42160SAlex Zinenko llvm::ArrayType::get(elementType, shape.front()), nested); 89a4a42160SAlex Zinenko } 90a4a42160SAlex Zinenko 91fc817b09SKazuaki Ishizaki /// Returns the first non-sequential type nested in sequential types. 92a4a42160SAlex Zinenko static llvm::Type *getInnermostElementType(llvm::Type *type) { 9368b03aeeSEli Friedman do { 9468b03aeeSEli Friedman if (auto *arrayTy = dyn_cast<llvm::ArrayType>(type)) { 9568b03aeeSEli Friedman type = arrayTy->getElementType(); 9668b03aeeSEli Friedman } else if (auto *vectorTy = dyn_cast<llvm::VectorType>(type)) { 9768b03aeeSEli Friedman type = vectorTy->getElementType(); 9868b03aeeSEli Friedman } else { 99a4a42160SAlex Zinenko return type; 100a4a42160SAlex Zinenko } 1010881a4f1SAlex Zinenko } while (true); 10268b03aeeSEli Friedman } 103a4a42160SAlex Zinenko 1042666b973SRiver Riddle /// Create an LLVM IR constant of `llvmType` from the MLIR attribute `attr`. 1052666b973SRiver Riddle /// This currently supports integer, floating point, splat and dense element 1062666b973SRiver Riddle /// attributes and combinations thereof. In case of error, report it to `loc` 1072666b973SRiver Riddle /// and return nullptr. 108176379e0SAlex Zinenko llvm::Constant *mlir::LLVM::detail::getLLVMConstant( 109176379e0SAlex Zinenko llvm::Type *llvmType, Attribute attr, Location loc, 110176379e0SAlex Zinenko const ModuleTranslation &moduleTranslation) { 11133a3a91bSChristian Sigg if (!attr) 11233a3a91bSChristian Sigg return llvm::UndefValue::get(llvmType); 113a4a42160SAlex Zinenko if (llvmType->isStructTy()) { 114a4a42160SAlex Zinenko emitError(loc, "struct types are not supported in constants"); 115a4a42160SAlex Zinenko return nullptr; 116a4a42160SAlex Zinenko } 117ac9d742bSStephan Herhut // For integer types, we allow a mismatch in sizes as the index type in 118ac9d742bSStephan Herhut // MLIR might have a different size than the index type in the LLVM module. 1195d7231d8SStephan Herhut if (auto intAttr = attr.dyn_cast<IntegerAttr>()) 120ac9d742bSStephan Herhut return llvm::ConstantInt::get( 121ac9d742bSStephan Herhut llvmType, 122ac9d742bSStephan Herhut intAttr.getValue().sextOrTrunc(llvmType->getIntegerBitWidth())); 1235d7231d8SStephan Herhut if (auto floatAttr = attr.dyn_cast<FloatAttr>()) 1245d7231d8SStephan Herhut return llvm::ConstantFP::get(llvmType, floatAttr.getValue()); 1259b9c647cSRiver Riddle if (auto funcAttr = attr.dyn_cast<FlatSymbolRefAttr>()) 126176379e0SAlex Zinenko return llvm::ConstantExpr::getBitCast( 127176379e0SAlex Zinenko moduleTranslation.lookupFunction(funcAttr.getValue()), llvmType); 1285d7231d8SStephan Herhut if (auto splatAttr = attr.dyn_cast<SplatElementsAttr>()) { 12968b03aeeSEli Friedman llvm::Type *elementType; 13068b03aeeSEli Friedman uint64_t numElements; 13168b03aeeSEli Friedman if (auto *arrayTy = dyn_cast<llvm::ArrayType>(llvmType)) { 13268b03aeeSEli Friedman elementType = arrayTy->getElementType(); 13368b03aeeSEli Friedman numElements = arrayTy->getNumElements(); 13468b03aeeSEli Friedman } else { 1355cba1c63SChristopher Tetreault auto *vectorTy = cast<llvm::FixedVectorType>(llvmType); 13668b03aeeSEli Friedman elementType = vectorTy->getElementType(); 13768b03aeeSEli Friedman numElements = vectorTy->getNumElements(); 13868b03aeeSEli Friedman } 139d6ea8ff0SAlex Zinenko // Splat value is a scalar. Extract it only if the element type is not 140d6ea8ff0SAlex Zinenko // another sequence type. The recursion terminates because each step removes 141d6ea8ff0SAlex Zinenko // one outer sequential type. 14268b03aeeSEli Friedman bool elementTypeSequential = 143d891d738SRahul Joshi isa<llvm::ArrayType, llvm::VectorType>(elementType); 144d6ea8ff0SAlex Zinenko llvm::Constant *child = getLLVMConstant( 145d6ea8ff0SAlex Zinenko elementType, 146176379e0SAlex Zinenko elementTypeSequential ? splatAttr : splatAttr.getSplatValue(), loc, 147176379e0SAlex Zinenko moduleTranslation); 148a4a42160SAlex Zinenko if (!child) 149a4a42160SAlex Zinenko return nullptr; 1502f13df13SMLIR Team if (llvmType->isVectorTy()) 151396a42d9SRiver Riddle return llvm::ConstantVector::getSplat( 1520f95e731SAlex Zinenko llvm::ElementCount::get(numElements, /*Scalable=*/false), child); 1532f13df13SMLIR Team if (llvmType->isArrayTy()) { 154ac9d742bSStephan Herhut auto *arrayType = llvm::ArrayType::get(elementType, numElements); 1552f13df13SMLIR Team SmallVector<llvm::Constant *, 8> constants(numElements, child); 1562f13df13SMLIR Team return llvm::ConstantArray::get(arrayType, constants); 1572f13df13SMLIR Team } 1585d7231d8SStephan Herhut } 159a4a42160SAlex Zinenko 160d906f84bSRiver Riddle if (auto elementsAttr = attr.dyn_cast<ElementsAttr>()) { 161a4a42160SAlex Zinenko assert(elementsAttr.getType().hasStaticShape()); 162a4a42160SAlex Zinenko assert(elementsAttr.getNumElements() != 0 && 163a4a42160SAlex Zinenko "unexpected empty elements attribute"); 164a4a42160SAlex Zinenko assert(!elementsAttr.getType().getShape().empty() && 165a4a42160SAlex Zinenko "unexpected empty elements attribute shape"); 166a4a42160SAlex Zinenko 1675d7231d8SStephan Herhut SmallVector<llvm::Constant *, 8> constants; 168a4a42160SAlex Zinenko constants.reserve(elementsAttr.getNumElements()); 169a4a42160SAlex Zinenko llvm::Type *innermostType = getInnermostElementType(llvmType); 170d906f84bSRiver Riddle for (auto n : elementsAttr.getValues<Attribute>()) { 171176379e0SAlex Zinenko constants.push_back( 172176379e0SAlex Zinenko getLLVMConstant(innermostType, n, loc, moduleTranslation)); 1735d7231d8SStephan Herhut if (!constants.back()) 1745d7231d8SStephan Herhut return nullptr; 1755d7231d8SStephan Herhut } 176a4a42160SAlex Zinenko ArrayRef<llvm::Constant *> constantsRef = constants; 177a4a42160SAlex Zinenko llvm::Constant *result = buildSequentialConstant( 178a4a42160SAlex Zinenko constantsRef, elementsAttr.getType().getShape(), llvmType, loc); 179a4a42160SAlex Zinenko assert(constantsRef.empty() && "did not consume all elemental constants"); 180a4a42160SAlex Zinenko return result; 1812f13df13SMLIR Team } 182a4a42160SAlex Zinenko 183cb348dffSStephan Herhut if (auto stringAttr = attr.dyn_cast<StringAttr>()) { 184cb348dffSStephan Herhut return llvm::ConstantDataArray::get( 185176379e0SAlex Zinenko moduleTranslation.getLLVMContext(), 186176379e0SAlex Zinenko ArrayRef<char>{stringAttr.getValue().data(), 187cb348dffSStephan Herhut stringAttr.getValue().size()}); 188cb348dffSStephan Herhut } 189a4c3a645SRiver Riddle emitError(loc, "unsupported constant value"); 1905d7231d8SStephan Herhut return nullptr; 1915d7231d8SStephan Herhut } 1925d7231d8SStephan Herhut 193c33d6970SRiver Riddle ModuleTranslation::ModuleTranslation(Operation *module, 194c33d6970SRiver Riddle std::unique_ptr<llvm::Module> llvmModule) 195c33d6970SRiver Riddle : mlirModule(module), llvmModule(std::move(llvmModule)), 196c33d6970SRiver Riddle debugTranslation( 19792a295ebSKiran Chandramohan std::make_unique<DebugTranslation>(module, *this->llvmModule)), 198b77bac05SAlex Zinenko typeTranslator(this->llvmModule->getContext()), 199b77bac05SAlex Zinenko iface(module->getContext()) { 200c33d6970SRiver Riddle assert(satisfiesLLVMModule(mlirModule) && 201c33d6970SRiver Riddle "mlirModule should honor LLVM's module semantics."); 202c33d6970SRiver Riddle } 203d9067dcaSKiran Chandramohan ModuleTranslation::~ModuleTranslation() { 204d9067dcaSKiran Chandramohan if (ompBuilder) 205d9067dcaSKiran Chandramohan ompBuilder->finalize(); 206d9067dcaSKiran Chandramohan } 207d9067dcaSKiran Chandramohan 208d9067dcaSKiran Chandramohan /// Get the SSA value passed to the current block from the terminator operation 209d9067dcaSKiran Chandramohan /// of its predecessor. 210d9067dcaSKiran Chandramohan static Value getPHISourceValue(Block *current, Block *pred, 211d9067dcaSKiran Chandramohan unsigned numArguments, unsigned index) { 212d9067dcaSKiran Chandramohan Operation &terminator = *pred->getTerminator(); 213d9067dcaSKiran Chandramohan if (isa<LLVM::BrOp>(terminator)) 214d9067dcaSKiran Chandramohan return terminator.getOperand(index); 215d9067dcaSKiran Chandramohan 21614f24155SBrian Gesiak SuccessorRange successors = terminator.getSuccessors(); 21714f24155SBrian Gesiak assert(std::adjacent_find(successors.begin(), successors.end()) == 21814f24155SBrian Gesiak successors.end() && 21914f24155SBrian Gesiak "successors with arguments in LLVM branches must be different blocks"); 22058f2b765SChristian Sigg (void)successors; 221d9067dcaSKiran Chandramohan 22214f24155SBrian Gesiak // For instructions that branch based on a condition value, we need to take 22314f24155SBrian Gesiak // the operands for the branch that was taken. 22414f24155SBrian Gesiak if (auto condBranchOp = dyn_cast<LLVM::CondBrOp>(terminator)) { 22514f24155SBrian Gesiak // For conditional branches, we take the operands from either the "true" or 22614f24155SBrian Gesiak // the "false" branch. 227d9067dcaSKiran Chandramohan return condBranchOp.getSuccessor(0) == current 228d9067dcaSKiran Chandramohan ? condBranchOp.trueDestOperands()[index] 229d9067dcaSKiran Chandramohan : condBranchOp.falseDestOperands()[index]; 2300881a4f1SAlex Zinenko } 2310881a4f1SAlex Zinenko 2320881a4f1SAlex Zinenko if (auto switchOp = dyn_cast<LLVM::SwitchOp>(terminator)) { 23314f24155SBrian Gesiak // For switches, we take the operands from either the default case, or from 23414f24155SBrian Gesiak // the case branch that was taken. 23514f24155SBrian Gesiak if (switchOp.defaultDestination() == current) 23614f24155SBrian Gesiak return switchOp.defaultOperands()[index]; 23714f24155SBrian Gesiak for (auto i : llvm::enumerate(switchOp.caseDestinations())) 23814f24155SBrian Gesiak if (i.value() == current) 23914f24155SBrian Gesiak return switchOp.getCaseOperands(i.index())[index]; 24014f24155SBrian Gesiak } 24114f24155SBrian Gesiak 24214f24155SBrian Gesiak llvm_unreachable("only branch or switch operations can be terminators of a " 24314f24155SBrian Gesiak "block that has successors"); 244d9067dcaSKiran Chandramohan } 245d9067dcaSKiran Chandramohan 246d9067dcaSKiran Chandramohan /// Connect the PHI nodes to the results of preceding blocks. 24766900b3eSAlex Zinenko void mlir::LLVM::detail::connectPHINodes(Region ®ion, 24866900b3eSAlex Zinenko const ModuleTranslation &state) { 249d9067dcaSKiran Chandramohan // Skip the first block, it cannot be branched to and its arguments correspond 250d9067dcaSKiran Chandramohan // to the arguments of the LLVM function. 25166900b3eSAlex Zinenko for (auto it = std::next(region.begin()), eit = region.end(); it != eit; 25266900b3eSAlex Zinenko ++it) { 253d9067dcaSKiran Chandramohan Block *bb = &*it; 2540881a4f1SAlex Zinenko llvm::BasicBlock *llvmBB = state.lookupBlock(bb); 255d9067dcaSKiran Chandramohan auto phis = llvmBB->phis(); 256d9067dcaSKiran Chandramohan auto numArguments = bb->getNumArguments(); 257d9067dcaSKiran Chandramohan assert(numArguments == std::distance(phis.begin(), phis.end())); 258d9067dcaSKiran Chandramohan for (auto &numberedPhiNode : llvm::enumerate(phis)) { 259d9067dcaSKiran Chandramohan auto &phiNode = numberedPhiNode.value(); 260d9067dcaSKiran Chandramohan unsigned index = numberedPhiNode.index(); 261d9067dcaSKiran Chandramohan for (auto *pred : bb->getPredecessors()) { 262db884dafSAlex Zinenko // Find the LLVM IR block that contains the converted terminator 263db884dafSAlex Zinenko // instruction and use it in the PHI node. Note that this block is not 2640881a4f1SAlex Zinenko // necessarily the same as state.lookupBlock(pred), some operations 265db884dafSAlex Zinenko // (in particular, OpenMP operations using OpenMPIRBuilder) may have 266db884dafSAlex Zinenko // split the blocks. 267db884dafSAlex Zinenko llvm::Instruction *terminator = 2680881a4f1SAlex Zinenko state.lookupBranch(pred->getTerminator()); 269db884dafSAlex Zinenko assert(terminator && "missing the mapping for a terminator"); 2700881a4f1SAlex Zinenko phiNode.addIncoming( 2710881a4f1SAlex Zinenko state.lookupValue(getPHISourceValue(bb, pred, numArguments, index)), 272db884dafSAlex Zinenko terminator->getParent()); 273d9067dcaSKiran Chandramohan } 274d9067dcaSKiran Chandramohan } 275d9067dcaSKiran Chandramohan } 276d9067dcaSKiran Chandramohan } 277d9067dcaSKiran Chandramohan 278d9067dcaSKiran Chandramohan /// Sort function blocks topologically. 2794efb7754SRiver Riddle SetVector<Block *> 28066900b3eSAlex Zinenko mlir::LLVM::detail::getTopologicallySortedBlocks(Region ®ion) { 281d4568ed7SGeorge Mitenkov // For each block that has not been visited yet (i.e. that has no 282d4568ed7SGeorge Mitenkov // predecessors), add it to the list as well as its successors. 2834efb7754SRiver Riddle SetVector<Block *> blocks; 28466900b3eSAlex Zinenko for (Block &b : region) { 285d4568ed7SGeorge Mitenkov if (blocks.count(&b) == 0) { 286d4568ed7SGeorge Mitenkov llvm::ReversePostOrderTraversal<Block *> traversal(&b); 287d4568ed7SGeorge Mitenkov blocks.insert(traversal.begin(), traversal.end()); 288d4568ed7SGeorge Mitenkov } 289d9067dcaSKiran Chandramohan } 29066900b3eSAlex Zinenko assert(blocks.size() == region.getBlocks().size() && 29166900b3eSAlex Zinenko "some blocks are not sorted"); 292d9067dcaSKiran Chandramohan 293d9067dcaSKiran Chandramohan return blocks; 294d9067dcaSKiran Chandramohan } 295d9067dcaSKiran Chandramohan 296176379e0SAlex Zinenko llvm::Value *mlir::LLVM::detail::createIntrinsicCall( 297176379e0SAlex Zinenko llvm::IRBuilderBase &builder, llvm::Intrinsic::ID intrinsic, 298176379e0SAlex Zinenko ArrayRef<llvm::Value *> args, ArrayRef<llvm::Type *> tys) { 299176379e0SAlex Zinenko llvm::Module *module = builder.GetInsertBlock()->getModule(); 300176379e0SAlex Zinenko llvm::Function *fn = llvm::Intrinsic::getDeclaration(module, intrinsic, tys); 301176379e0SAlex Zinenko return builder.CreateCall(fn, args); 302176379e0SAlex Zinenko } 303176379e0SAlex Zinenko 304875eb523SNavdeep Kumar llvm::Value * 305875eb523SNavdeep Kumar mlir::LLVM::detail::createNvvmIntrinsicCall(llvm::IRBuilderBase &builder, 306875eb523SNavdeep Kumar llvm::Intrinsic::ID intrinsic, 307875eb523SNavdeep Kumar ArrayRef<llvm::Value *> args) { 308875eb523SNavdeep Kumar llvm::Module *module = builder.GetInsertBlock()->getModule(); 309875eb523SNavdeep Kumar llvm::Function *fn; 310875eb523SNavdeep Kumar if (llvm::Intrinsic::isOverloaded(intrinsic)) { 311875eb523SNavdeep Kumar if (intrinsic != llvm::Intrinsic::nvvm_wmma_m16n16k16_mma_row_row_f16_f16 && 312875eb523SNavdeep Kumar intrinsic != llvm::Intrinsic::nvvm_wmma_m16n16k16_mma_row_row_f32_f32) { 313875eb523SNavdeep Kumar // NVVM load and store instrinsic names are overloaded on the 314875eb523SNavdeep Kumar // source/destination pointer type. Pointer is the first argument in the 315875eb523SNavdeep Kumar // corresponding NVVM Op. 316875eb523SNavdeep Kumar fn = llvm::Intrinsic::getDeclaration(module, intrinsic, 317875eb523SNavdeep Kumar {args[0]->getType()}); 318875eb523SNavdeep Kumar } else { 319875eb523SNavdeep Kumar fn = llvm::Intrinsic::getDeclaration(module, intrinsic, {}); 320875eb523SNavdeep Kumar } 321875eb523SNavdeep Kumar } else { 322875eb523SNavdeep Kumar fn = llvm::Intrinsic::getDeclaration(module, intrinsic); 323875eb523SNavdeep Kumar } 324875eb523SNavdeep Kumar return builder.CreateCall(fn, args); 325875eb523SNavdeep Kumar } 326875eb523SNavdeep Kumar 3272666b973SRiver Riddle /// Given a single MLIR operation, create the corresponding LLVM IR operation 328176379e0SAlex Zinenko /// using the `builder`. 329ce8f10d6SAlex Zinenko LogicalResult 33038b106f6SMehdi Amini ModuleTranslation::convertOperation(Operation &op, 331ce8f10d6SAlex Zinenko llvm::IRBuilderBase &builder) { 33238b106f6SMehdi Amini const LLVMTranslationDialectInterface *opIface = iface.getInterfaceFor(&op); 33338b106f6SMehdi Amini if (!opIface) 33438b106f6SMehdi Amini return op.emitError("cannot be converted to LLVM IR: missing " 33538b106f6SMehdi Amini "`LLVMTranslationDialectInterface` registration for " 33638b106f6SMehdi Amini "dialect for op: ") 33738b106f6SMehdi Amini << op.getName(); 338176379e0SAlex Zinenko 33938b106f6SMehdi Amini if (failed(opIface->convertOperation(&op, builder, *this))) 34038b106f6SMehdi Amini return op.emitError("LLVM Translation failed for operation: ") 34138b106f6SMehdi Amini << op.getName(); 34238b106f6SMehdi Amini 34338b106f6SMehdi Amini return convertDialectAttributes(&op); 3445d7231d8SStephan Herhut } 3455d7231d8SStephan Herhut 3462666b973SRiver Riddle /// Convert block to LLVM IR. Unless `ignoreArguments` is set, emit PHI nodes 3472666b973SRiver Riddle /// to define values corresponding to the MLIR block arguments. These nodes 34810164a2eSAlex Zinenko /// are not connected to the source basic blocks, which may not exist yet. Uses 34910164a2eSAlex Zinenko /// `builder` to construct the LLVM IR. Expects the LLVM IR basic block to have 35010164a2eSAlex Zinenko /// been created for `bb` and included in the block mapping. Inserts new 35110164a2eSAlex Zinenko /// instructions at the end of the block and leaves `builder` in a state 35210164a2eSAlex Zinenko /// suitable for further insertion into the end of the block. 35310164a2eSAlex Zinenko LogicalResult ModuleTranslation::convertBlock(Block &bb, bool ignoreArguments, 354ce8f10d6SAlex Zinenko llvm::IRBuilderBase &builder) { 3550881a4f1SAlex Zinenko builder.SetInsertPoint(lookupBlock(&bb)); 356c33d6970SRiver Riddle auto *subprogram = builder.GetInsertBlock()->getParent()->getSubprogram(); 3575d7231d8SStephan Herhut 3585d7231d8SStephan Herhut // Before traversing operations, make block arguments available through 3595d7231d8SStephan Herhut // value remapping and PHI nodes, but do not add incoming edges for the PHI 3605d7231d8SStephan Herhut // nodes just yet: those values may be defined by this or following blocks. 3615d7231d8SStephan Herhut // This step is omitted if "ignoreArguments" is set. The arguments of the 3625d7231d8SStephan Herhut // first block have been already made available through the remapping of 3635d7231d8SStephan Herhut // LLVM function arguments. 3645d7231d8SStephan Herhut if (!ignoreArguments) { 3655d7231d8SStephan Herhut auto predecessors = bb.getPredecessors(); 3665d7231d8SStephan Herhut unsigned numPredecessors = 3675d7231d8SStephan Herhut std::distance(predecessors.begin(), predecessors.end()); 36835807bc4SRiver Riddle for (auto arg : bb.getArguments()) { 369c69c9e0fSAlex Zinenko auto wrappedType = arg.getType(); 370c69c9e0fSAlex Zinenko if (!isCompatibleType(wrappedType)) 371baa1ec22SAlex Zinenko return emitError(bb.front().getLoc(), 372a4c3a645SRiver Riddle "block argument does not have an LLVM type"); 373aec38c61SAlex Zinenko llvm::Type *type = convertType(wrappedType); 3745d7231d8SStephan Herhut llvm::PHINode *phi = builder.CreatePHI(type, numPredecessors); 3750881a4f1SAlex Zinenko mapValue(arg, phi); 3765d7231d8SStephan Herhut } 3775d7231d8SStephan Herhut } 3785d7231d8SStephan Herhut 3795d7231d8SStephan Herhut // Traverse operations. 3805d7231d8SStephan Herhut for (auto &op : bb) { 381c33d6970SRiver Riddle // Set the current debug location within the builder. 382c33d6970SRiver Riddle builder.SetCurrentDebugLocation( 383c33d6970SRiver Riddle debugTranslation->translateLoc(op.getLoc(), subprogram)); 384c33d6970SRiver Riddle 385baa1ec22SAlex Zinenko if (failed(convertOperation(op, builder))) 386baa1ec22SAlex Zinenko return failure(); 3875d7231d8SStephan Herhut } 3885d7231d8SStephan Herhut 389baa1ec22SAlex Zinenko return success(); 3905d7231d8SStephan Herhut } 3915d7231d8SStephan Herhut 392ce8f10d6SAlex Zinenko /// A helper method to get the single Block in an operation honoring LLVM's 393ce8f10d6SAlex Zinenko /// module requirements. 394ce8f10d6SAlex Zinenko static Block &getModuleBody(Operation *module) { 395ce8f10d6SAlex Zinenko return module->getRegion(0).front(); 396ce8f10d6SAlex Zinenko } 397ce8f10d6SAlex Zinenko 398ffa455d4SJean Perier /// A helper method to decide if a constant must not be set as a global variable 399ffa455d4SJean Perier /// initializer. 400ffa455d4SJean Perier static bool shouldDropGlobalInitializer(llvm::GlobalValue::LinkageTypes linkage, 401ffa455d4SJean Perier llvm::Constant *cst) { 402ffa455d4SJean Perier return (linkage == llvm::GlobalVariable::ExternalLinkage && 403ffa455d4SJean Perier isa<llvm::UndefValue>(cst)) || 404ffa455d4SJean Perier linkage == llvm::GlobalVariable::ExternalWeakLinkage; 405ffa455d4SJean Perier } 406ffa455d4SJean Perier 4072666b973SRiver Riddle /// Create named global variables that correspond to llvm.mlir.global 4082666b973SRiver Riddle /// definitions. 409efa2d533SAlex Zinenko LogicalResult ModuleTranslation::convertGlobals() { 41044fc7d72STres Popp for (auto op : getModuleBody(mlirModule).getOps<LLVM::GlobalOp>()) { 411aec38c61SAlex Zinenko llvm::Type *type = convertType(op.getType()); 412250a11aeSJames Molloy llvm::Constant *cst = llvm::UndefValue::get(type); 413250a11aeSJames Molloy if (op.getValueOrNull()) { 41468451df2SAlex Zinenko // String attributes are treated separately because they cannot appear as 41568451df2SAlex Zinenko // in-function constants and are thus not supported by getLLVMConstant. 41633a3a91bSChristian Sigg if (auto strAttr = op.getValueOrNull().dyn_cast_or_null<StringAttr>()) { 4172dd38b09SAlex Zinenko cst = llvm::ConstantDataArray::getString( 41868451df2SAlex Zinenko llvmModule->getContext(), strAttr.getValue(), /*AddNull=*/false); 4192dd38b09SAlex Zinenko type = cst->getType(); 420176379e0SAlex Zinenko } else if (!(cst = getLLVMConstant(type, op.getValueOrNull(), op.getLoc(), 421176379e0SAlex Zinenko *this))) { 422efa2d533SAlex Zinenko return failure(); 42368451df2SAlex Zinenko } 424ffa455d4SJean Perier } 425ffa455d4SJean Perier 426ffa455d4SJean Perier auto linkage = convertLinkageToLLVM(op.linkage()); 427ffa455d4SJean Perier auto addrSpace = op.addr_space(); 428ffa455d4SJean Perier auto *var = new llvm::GlobalVariable( 429ffa455d4SJean Perier *llvmModule, type, op.constant(), linkage, 430ffa455d4SJean Perier shouldDropGlobalInitializer(linkage, cst) ? nullptr : cst, 431ffa455d4SJean Perier op.sym_name(), 432ffa455d4SJean Perier /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal, addrSpace); 433ffa455d4SJean Perier 434c46a8862Sclementval if (op.unnamed_addr().hasValue()) 435c46a8862Sclementval var->setUnnamedAddr(convertUnnamedAddrToLLVM(*op.unnamed_addr())); 436c46a8862Sclementval 437b65472d6SRanjith Kumar H if (op.section().hasValue()) 438b65472d6SRanjith Kumar H var->setSection(*op.section()); 439b65472d6SRanjith Kumar H 440*9a0ea599SDumitru Potop Optional<uint64_t> alignment = op.alignment(); 441*9a0ea599SDumitru Potop if (alignment.hasValue()) 442*9a0ea599SDumitru Potop var->setAlignment(llvm::MaybeAlign(alignment.getValue())); 443*9a0ea599SDumitru Potop 444ffa455d4SJean Perier globalsMapping.try_emplace(op, var); 445ffa455d4SJean Perier } 446ffa455d4SJean Perier 447ffa455d4SJean Perier // Convert global variable bodies. This is done after all global variables 448ffa455d4SJean Perier // have been created in LLVM IR because a global body may refer to another 449ffa455d4SJean Perier // global or itself. So all global variables need to be mapped first. 450ffa455d4SJean Perier for (auto op : getModuleBody(mlirModule).getOps<LLVM::GlobalOp>()) { 451ffa455d4SJean Perier if (Block *initializer = op.getInitializerBlock()) { 452250a11aeSJames Molloy llvm::IRBuilder<> builder(llvmModule->getContext()); 453250a11aeSJames Molloy for (auto &op : initializer->without_terminator()) { 454250a11aeSJames Molloy if (failed(convertOperation(op, builder)) || 4550881a4f1SAlex Zinenko !isa<llvm::Constant>(lookupValue(op.getResult(0)))) 456efa2d533SAlex Zinenko return emitError(op.getLoc(), "unemittable constant value"); 457250a11aeSJames Molloy } 458250a11aeSJames Molloy ReturnOp ret = cast<ReturnOp>(initializer->getTerminator()); 459ffa455d4SJean Perier llvm::Constant *cst = 460ffa455d4SJean Perier cast<llvm::Constant>(lookupValue(ret.getOperand(0))); 461ffa455d4SJean Perier auto *global = cast<llvm::GlobalVariable>(lookupGlobal(op)); 462ffa455d4SJean Perier if (!shouldDropGlobalInitializer(global->getLinkage(), cst)) 463ffa455d4SJean Perier global->setInitializer(cst); 464250a11aeSJames Molloy } 465b9ff2dd8SAlex Zinenko } 466efa2d533SAlex Zinenko 467efa2d533SAlex Zinenko return success(); 468b9ff2dd8SAlex Zinenko } 469b9ff2dd8SAlex Zinenko 4700a2131b7SAlex Zinenko /// Attempts to add an attribute identified by `key`, optionally with the given 4710a2131b7SAlex Zinenko /// `value` to LLVM function `llvmFunc`. Reports errors at `loc` if any. If the 4720a2131b7SAlex Zinenko /// attribute has a kind known to LLVM IR, create the attribute of this kind, 4730a2131b7SAlex Zinenko /// otherwise keep it as a string attribute. Performs additional checks for 4740a2131b7SAlex Zinenko /// attributes known to have or not have a value in order to avoid assertions 4750a2131b7SAlex Zinenko /// inside LLVM upon construction. 4760a2131b7SAlex Zinenko static LogicalResult checkedAddLLVMFnAttribute(Location loc, 4770a2131b7SAlex Zinenko llvm::Function *llvmFunc, 4780a2131b7SAlex Zinenko StringRef key, 4790a2131b7SAlex Zinenko StringRef value = StringRef()) { 4800a2131b7SAlex Zinenko auto kind = llvm::Attribute::getAttrKindFromName(key); 4810a2131b7SAlex Zinenko if (kind == llvm::Attribute::None) { 4820a2131b7SAlex Zinenko llvmFunc->addFnAttr(key, value); 4830a2131b7SAlex Zinenko return success(); 4840a2131b7SAlex Zinenko } 4850a2131b7SAlex Zinenko 4860a2131b7SAlex Zinenko if (llvm::Attribute::doesAttrKindHaveArgument(kind)) { 4870a2131b7SAlex Zinenko if (value.empty()) 4880a2131b7SAlex Zinenko return emitError(loc) << "LLVM attribute '" << key << "' expects a value"; 4890a2131b7SAlex Zinenko 4900a2131b7SAlex Zinenko int result; 4910a2131b7SAlex Zinenko if (!value.getAsInteger(/*Radix=*/0, result)) 4920a2131b7SAlex Zinenko llvmFunc->addFnAttr( 4930a2131b7SAlex Zinenko llvm::Attribute::get(llvmFunc->getContext(), kind, result)); 4940a2131b7SAlex Zinenko else 4950a2131b7SAlex Zinenko llvmFunc->addFnAttr(key, value); 4960a2131b7SAlex Zinenko return success(); 4970a2131b7SAlex Zinenko } 4980a2131b7SAlex Zinenko 4990a2131b7SAlex Zinenko if (!value.empty()) 5000a2131b7SAlex Zinenko return emitError(loc) << "LLVM attribute '" << key 5010a2131b7SAlex Zinenko << "' does not expect a value, found '" << value 5020a2131b7SAlex Zinenko << "'"; 5030a2131b7SAlex Zinenko 5040a2131b7SAlex Zinenko llvmFunc->addFnAttr(kind); 5050a2131b7SAlex Zinenko return success(); 5060a2131b7SAlex Zinenko } 5070a2131b7SAlex Zinenko 5080a2131b7SAlex Zinenko /// Attaches the attributes listed in the given array attribute to `llvmFunc`. 5090a2131b7SAlex Zinenko /// Reports error to `loc` if any and returns immediately. Expects `attributes` 5100a2131b7SAlex Zinenko /// to be an array attribute containing either string attributes, treated as 5110a2131b7SAlex Zinenko /// value-less LLVM attributes, or array attributes containing two string 5120a2131b7SAlex Zinenko /// attributes, with the first string being the name of the corresponding LLVM 5130a2131b7SAlex Zinenko /// attribute and the second string beings its value. Note that even integer 5140a2131b7SAlex Zinenko /// attributes are expected to have their values expressed as strings. 5150a2131b7SAlex Zinenko static LogicalResult 5160a2131b7SAlex Zinenko forwardPassthroughAttributes(Location loc, Optional<ArrayAttr> attributes, 5170a2131b7SAlex Zinenko llvm::Function *llvmFunc) { 5180a2131b7SAlex Zinenko if (!attributes) 5190a2131b7SAlex Zinenko return success(); 5200a2131b7SAlex Zinenko 5210a2131b7SAlex Zinenko for (Attribute attr : *attributes) { 5220a2131b7SAlex Zinenko if (auto stringAttr = attr.dyn_cast<StringAttr>()) { 5230a2131b7SAlex Zinenko if (failed( 5240a2131b7SAlex Zinenko checkedAddLLVMFnAttribute(loc, llvmFunc, stringAttr.getValue()))) 5250a2131b7SAlex Zinenko return failure(); 5260a2131b7SAlex Zinenko continue; 5270a2131b7SAlex Zinenko } 5280a2131b7SAlex Zinenko 5290a2131b7SAlex Zinenko auto arrayAttr = attr.dyn_cast<ArrayAttr>(); 5300a2131b7SAlex Zinenko if (!arrayAttr || arrayAttr.size() != 2) 5310a2131b7SAlex Zinenko return emitError(loc) 5320a2131b7SAlex Zinenko << "expected 'passthrough' to contain string or array attributes"; 5330a2131b7SAlex Zinenko 5340a2131b7SAlex Zinenko auto keyAttr = arrayAttr[0].dyn_cast<StringAttr>(); 5350a2131b7SAlex Zinenko auto valueAttr = arrayAttr[1].dyn_cast<StringAttr>(); 5360a2131b7SAlex Zinenko if (!keyAttr || !valueAttr) 5370a2131b7SAlex Zinenko return emitError(loc) 5380a2131b7SAlex Zinenko << "expected arrays within 'passthrough' to contain two strings"; 5390a2131b7SAlex Zinenko 5400a2131b7SAlex Zinenko if (failed(checkedAddLLVMFnAttribute(loc, llvmFunc, keyAttr.getValue(), 5410a2131b7SAlex Zinenko valueAttr.getValue()))) 5420a2131b7SAlex Zinenko return failure(); 5430a2131b7SAlex Zinenko } 5440a2131b7SAlex Zinenko return success(); 5450a2131b7SAlex Zinenko } 5460a2131b7SAlex Zinenko 5475e7959a3SAlex Zinenko LogicalResult ModuleTranslation::convertOneFunction(LLVMFuncOp func) { 548db884dafSAlex Zinenko // Clear the block, branch value mappings, they are only relevant within one 5495d7231d8SStephan Herhut // function. 5505d7231d8SStephan Herhut blockMapping.clear(); 5515d7231d8SStephan Herhut valueMapping.clear(); 552db884dafSAlex Zinenko branchMapping.clear(); 5530881a4f1SAlex Zinenko llvm::Function *llvmFunc = lookupFunction(func.getName()); 554c33d6970SRiver Riddle 555c33d6970SRiver Riddle // Translate the debug information for this function. 556c33d6970SRiver Riddle debugTranslation->translate(func, *llvmFunc); 557c33d6970SRiver Riddle 5585d7231d8SStephan Herhut // Add function arguments to the value remapping table. 5595d7231d8SStephan Herhut // If there was noalias info then we decorate each argument accordingly. 5605d7231d8SStephan Herhut unsigned int argIdx = 0; 561eeef50b1SFangrui Song for (auto kvp : llvm::zip(func.getArguments(), llvmFunc->args())) { 5625d7231d8SStephan Herhut llvm::Argument &llvmArg = std::get<1>(kvp); 563e62a6956SRiver Riddle BlockArgument mlirArg = std::get<0>(kvp); 5645d7231d8SStephan Herhut 5651c777ab4SUday Bondhugula if (auto attr = func.getArgAttrOfType<UnitAttr>( 56667cc5cecSStephan Herhut argIdx, LLVMDialect::getNoAliasAttrName())) { 5675d7231d8SStephan Herhut // NB: Attribute already verified to be boolean, so check if we can indeed 5685d7231d8SStephan Herhut // attach the attribute to this argument, based on its type. 569c69c9e0fSAlex Zinenko auto argTy = mlirArg.getType(); 5708de43b92SAlex Zinenko if (!argTy.isa<LLVM::LLVMPointerType>()) 571baa1ec22SAlex Zinenko return func.emitError( 5725d7231d8SStephan Herhut "llvm.noalias attribute attached to LLVM non-pointer argument"); 5735d7231d8SStephan Herhut llvmArg.addAttr(llvm::Attribute::AttrKind::NoAlias); 5745d7231d8SStephan Herhut } 5752416e28cSStephan Herhut 57667cc5cecSStephan Herhut if (auto attr = func.getArgAttrOfType<IntegerAttr>( 57767cc5cecSStephan Herhut argIdx, LLVMDialect::getAlignAttrName())) { 5782416e28cSStephan Herhut // NB: Attribute already verified to be int, so check if we can indeed 5792416e28cSStephan Herhut // attach the attribute to this argument, based on its type. 580c69c9e0fSAlex Zinenko auto argTy = mlirArg.getType(); 5818de43b92SAlex Zinenko if (!argTy.isa<LLVM::LLVMPointerType>()) 5822416e28cSStephan Herhut return func.emitError( 5832416e28cSStephan Herhut "llvm.align attribute attached to LLVM non-pointer argument"); 5842416e28cSStephan Herhut llvmArg.addAttrs( 5852416e28cSStephan Herhut llvm::AttrBuilder().addAlignmentAttr(llvm::Align(attr.getInt()))); 5862416e28cSStephan Herhut } 5872416e28cSStephan Herhut 58870b841acSEric Schweitz if (auto attr = func.getArgAttrOfType<UnitAttr>(argIdx, "llvm.sret")) { 58970b841acSEric Schweitz auto argTy = mlirArg.getType(); 59070b841acSEric Schweitz if (!argTy.isa<LLVM::LLVMPointerType>()) 59170b841acSEric Schweitz return func.emitError( 59270b841acSEric Schweitz "llvm.sret attribute attached to LLVM non-pointer argument"); 5931d6df1fcSEric Schweitz llvmArg.addAttrs(llvm::AttrBuilder().addStructRetAttr( 5941d6df1fcSEric Schweitz llvmArg.getType()->getPointerElementType())); 59570b841acSEric Schweitz } 59670b841acSEric Schweitz 59770b841acSEric Schweitz if (auto attr = func.getArgAttrOfType<UnitAttr>(argIdx, "llvm.byval")) { 59870b841acSEric Schweitz auto argTy = mlirArg.getType(); 59970b841acSEric Schweitz if (!argTy.isa<LLVM::LLVMPointerType>()) 60070b841acSEric Schweitz return func.emitError( 60170b841acSEric Schweitz "llvm.byval attribute attached to LLVM non-pointer argument"); 6021d6df1fcSEric Schweitz llvmArg.addAttrs(llvm::AttrBuilder().addByValAttr( 6031d6df1fcSEric Schweitz llvmArg.getType()->getPointerElementType())); 60470b841acSEric Schweitz } 60570b841acSEric Schweitz 6060881a4f1SAlex Zinenko mapValue(mlirArg, &llvmArg); 6075d7231d8SStephan Herhut argIdx++; 6085d7231d8SStephan Herhut } 6095d7231d8SStephan Herhut 610ff77397fSShraiysh Vaishay // Check the personality and set it. 611ff77397fSShraiysh Vaishay if (func.personality().hasValue()) { 612ff77397fSShraiysh Vaishay llvm::Type *ty = llvm::Type::getInt8PtrTy(llvmFunc->getContext()); 613ff77397fSShraiysh Vaishay if (llvm::Constant *pfunc = 614176379e0SAlex Zinenko getLLVMConstant(ty, func.personalityAttr(), func.getLoc(), *this)) 615ff77397fSShraiysh Vaishay llvmFunc->setPersonalityFn(pfunc); 616ff77397fSShraiysh Vaishay } 617ff77397fSShraiysh Vaishay 6185d7231d8SStephan Herhut // First, create all blocks so we can jump to them. 6195d7231d8SStephan Herhut llvm::LLVMContext &llvmContext = llvmFunc->getContext(); 6205d7231d8SStephan Herhut for (auto &bb : func) { 6215d7231d8SStephan Herhut auto *llvmBB = llvm::BasicBlock::Create(llvmContext); 6225d7231d8SStephan Herhut llvmBB->insertInto(llvmFunc); 6230881a4f1SAlex Zinenko mapBlock(&bb, llvmBB); 6245d7231d8SStephan Herhut } 6255d7231d8SStephan Herhut 6265d7231d8SStephan Herhut // Then, convert blocks one by one in topological order to ensure defs are 6275d7231d8SStephan Herhut // converted before uses. 62866900b3eSAlex Zinenko auto blocks = detail::getTopologicallySortedBlocks(func.getBody()); 62910164a2eSAlex Zinenko for (Block *bb : blocks) { 63010164a2eSAlex Zinenko llvm::IRBuilder<> builder(llvmContext); 63110164a2eSAlex Zinenko if (failed(convertBlock(*bb, bb->isEntryBlock(), builder))) 632baa1ec22SAlex Zinenko return failure(); 6335d7231d8SStephan Herhut } 6345d7231d8SStephan Herhut 635176379e0SAlex Zinenko // After all blocks have been traversed and values mapped, connect the PHI 636176379e0SAlex Zinenko // nodes to the results of preceding blocks. 63766900b3eSAlex Zinenko detail::connectPHINodes(func.getBody(), *this); 638176379e0SAlex Zinenko 639176379e0SAlex Zinenko // Finally, convert dialect attributes attached to the function. 640176379e0SAlex Zinenko return convertDialectAttributes(func); 641176379e0SAlex Zinenko } 642176379e0SAlex Zinenko 643176379e0SAlex Zinenko LogicalResult ModuleTranslation::convertDialectAttributes(Operation *op) { 644176379e0SAlex Zinenko for (NamedAttribute attribute : op->getDialectAttrs()) 645176379e0SAlex Zinenko if (failed(iface.amendOperation(op, attribute, *this))) 646176379e0SAlex Zinenko return failure(); 647baa1ec22SAlex Zinenko return success(); 6485d7231d8SStephan Herhut } 6495d7231d8SStephan Herhut 650ce8f10d6SAlex Zinenko /// Check whether the module contains only supported ops directly in its body. 651ce8f10d6SAlex Zinenko static LogicalResult checkSupportedModuleOps(Operation *m) { 65244fc7d72STres Popp for (Operation &o : getModuleBody(m).getOperations()) 6534a2930f4SArpith C. Jacob if (!isa<LLVM::LLVMFuncOp, LLVM::GlobalOp, LLVM::MetadataOp>(&o) && 654fe7c0d90SRiver Riddle !o.hasTrait<OpTrait::IsTerminator>()) 6554dde19f0SAlex Zinenko return o.emitOpError("unsupported module-level operation"); 6564dde19f0SAlex Zinenko return success(); 6574dde19f0SAlex Zinenko } 6584dde19f0SAlex Zinenko 659a084b94fSSean Silva LogicalResult ModuleTranslation::convertFunctionSignatures() { 6605d7231d8SStephan Herhut // Declare all functions first because there may be function calls that form a 661a084b94fSSean Silva // call graph with cycles, or global initializers that reference functions. 66244fc7d72STres Popp for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) { 6635e7959a3SAlex Zinenko llvm::FunctionCallee llvmFuncCst = llvmModule->getOrInsertFunction( 6645e7959a3SAlex Zinenko function.getName(), 665aec38c61SAlex Zinenko cast<llvm::FunctionType>(convertType(function.getType()))); 6660a2131b7SAlex Zinenko llvm::Function *llvmFunc = cast<llvm::Function>(llvmFuncCst.getCallee()); 667ebbdecddSAlex Zinenko llvmFunc->setLinkage(convertLinkageToLLVM(function.linkage())); 6680881a4f1SAlex Zinenko mapFunction(function.getName(), llvmFunc); 6690a2131b7SAlex Zinenko 6700a2131b7SAlex Zinenko // Forward the pass-through attributes to LLVM. 6710a2131b7SAlex Zinenko if (failed(forwardPassthroughAttributes(function.getLoc(), 6720a2131b7SAlex Zinenko function.passthrough(), llvmFunc))) 6730a2131b7SAlex Zinenko return failure(); 6745d7231d8SStephan Herhut } 6755d7231d8SStephan Herhut 676a084b94fSSean Silva return success(); 677a084b94fSSean Silva } 678a084b94fSSean Silva 679a084b94fSSean Silva LogicalResult ModuleTranslation::convertFunctions() { 6805d7231d8SStephan Herhut // Convert functions. 68144fc7d72STres Popp for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) { 6825d7231d8SStephan Herhut // Ignore external functions. 6835d7231d8SStephan Herhut if (function.isExternal()) 6845d7231d8SStephan Herhut continue; 6855d7231d8SStephan Herhut 686baa1ec22SAlex Zinenko if (failed(convertOneFunction(function))) 687baa1ec22SAlex Zinenko return failure(); 6885d7231d8SStephan Herhut } 6895d7231d8SStephan Herhut 690baa1ec22SAlex Zinenko return success(); 6915d7231d8SStephan Herhut } 6925d7231d8SStephan Herhut 6934a2930f4SArpith C. Jacob llvm::MDNode * 6944a2930f4SArpith C. Jacob ModuleTranslation::getAccessGroup(Operation &opInst, 6954a2930f4SArpith C. Jacob SymbolRefAttr accessGroupRef) const { 6964a2930f4SArpith C. Jacob auto metadataName = accessGroupRef.getRootReference(); 6974a2930f4SArpith C. Jacob auto accessGroupName = accessGroupRef.getLeafReference(); 6984a2930f4SArpith C. Jacob auto metadataOp = SymbolTable::lookupNearestSymbolFrom<LLVM::MetadataOp>( 6994a2930f4SArpith C. Jacob opInst.getParentOp(), metadataName); 7004a2930f4SArpith C. Jacob auto *accessGroupOp = 7014a2930f4SArpith C. Jacob SymbolTable::lookupNearestSymbolFrom(metadataOp, accessGroupName); 7024a2930f4SArpith C. Jacob return accessGroupMetadataMapping.lookup(accessGroupOp); 7034a2930f4SArpith C. Jacob } 7044a2930f4SArpith C. Jacob 7054a2930f4SArpith C. Jacob LogicalResult ModuleTranslation::createAccessGroupMetadata() { 7064a2930f4SArpith C. Jacob mlirModule->walk([&](LLVM::MetadataOp metadatas) { 7074a2930f4SArpith C. Jacob metadatas.walk([&](LLVM::AccessGroupMetadataOp op) { 7084a2930f4SArpith C. Jacob llvm::LLVMContext &ctx = llvmModule->getContext(); 7094a2930f4SArpith C. Jacob llvm::MDNode *accessGroup = llvm::MDNode::getDistinct(ctx, {}); 7104a2930f4SArpith C. Jacob accessGroupMetadataMapping.insert({op, accessGroup}); 7114a2930f4SArpith C. Jacob }); 7124a2930f4SArpith C. Jacob }); 7134a2930f4SArpith C. Jacob return success(); 7144a2930f4SArpith C. Jacob } 7154a2930f4SArpith C. Jacob 7164e393350SArpith C. Jacob void ModuleTranslation::setAccessGroupsMetadata(Operation *op, 7174e393350SArpith C. Jacob llvm::Instruction *inst) { 7184e393350SArpith C. Jacob auto accessGroups = 7194e393350SArpith C. Jacob op->getAttrOfType<ArrayAttr>(LLVMDialect::getAccessGroupsAttrName()); 7204e393350SArpith C. Jacob if (accessGroups && !accessGroups.empty()) { 7214e393350SArpith C. Jacob llvm::Module *module = inst->getModule(); 7224e393350SArpith C. Jacob SmallVector<llvm::Metadata *> metadatas; 7234e393350SArpith C. Jacob for (SymbolRefAttr accessGroupRef : 7244e393350SArpith C. Jacob accessGroups.getAsRange<SymbolRefAttr>()) 7254e393350SArpith C. Jacob metadatas.push_back(getAccessGroup(*op, accessGroupRef)); 7264e393350SArpith C. Jacob 7274e393350SArpith C. Jacob llvm::MDNode *unionMD = nullptr; 7284e393350SArpith C. Jacob if (metadatas.size() == 1) 7294e393350SArpith C. Jacob unionMD = llvm::cast<llvm::MDNode>(metadatas.front()); 7304e393350SArpith C. Jacob else if (metadatas.size() >= 2) 7314e393350SArpith C. Jacob unionMD = llvm::MDNode::get(module->getContext(), metadatas); 7324e393350SArpith C. Jacob 7334e393350SArpith C. Jacob inst->setMetadata(module->getMDKindID("llvm.access.group"), unionMD); 7344e393350SArpith C. Jacob } 7354e393350SArpith C. Jacob } 7364e393350SArpith C. Jacob 737c69c9e0fSAlex Zinenko llvm::Type *ModuleTranslation::convertType(Type type) { 738b2ab375dSAlex Zinenko return typeTranslator.translateType(type); 739aec38c61SAlex Zinenko } 740aec38c61SAlex Zinenko 741efadb6b8SAlex Zinenko /// A helper to look up remapped operands in the value remapping table.` 742efadb6b8SAlex Zinenko SmallVector<llvm::Value *, 8> 743efadb6b8SAlex Zinenko ModuleTranslation::lookupValues(ValueRange values) { 744efadb6b8SAlex Zinenko SmallVector<llvm::Value *, 8> remapped; 745efadb6b8SAlex Zinenko remapped.reserve(values.size()); 7460881a4f1SAlex Zinenko for (Value v : values) 7470881a4f1SAlex Zinenko remapped.push_back(lookupValue(v)); 748efadb6b8SAlex Zinenko return remapped; 749efadb6b8SAlex Zinenko } 750efadb6b8SAlex Zinenko 75166900b3eSAlex Zinenko const llvm::DILocation * 75266900b3eSAlex Zinenko ModuleTranslation::translateLoc(Location loc, llvm::DILocalScope *scope) { 75366900b3eSAlex Zinenko return debugTranslation->translateLoc(loc, scope); 75466900b3eSAlex Zinenko } 75566900b3eSAlex Zinenko 756176379e0SAlex Zinenko llvm::NamedMDNode * 757176379e0SAlex Zinenko ModuleTranslation::getOrInsertNamedModuleMetadata(StringRef name) { 758176379e0SAlex Zinenko return llvmModule->getOrInsertNamedMetadata(name); 759176379e0SAlex Zinenko } 760176379e0SAlex Zinenko 76172d013ddSAlex Zinenko void ModuleTranslation::StackFrame::anchor() {} 76272d013ddSAlex Zinenko 763ce8f10d6SAlex Zinenko static std::unique_ptr<llvm::Module> 764ce8f10d6SAlex Zinenko prepareLLVMModule(Operation *m, llvm::LLVMContext &llvmContext, 765ce8f10d6SAlex Zinenko StringRef name) { 766f9dc2b70SMehdi Amini m->getContext()->getOrLoadDialect<LLVM::LLVMDialect>(); 767db1c197bSAlex Zinenko auto llvmModule = std::make_unique<llvm::Module>(name, llvmContext); 768168213f9SAlex Zinenko if (auto dataLayoutAttr = 769168213f9SAlex Zinenko m->getAttr(LLVM::LLVMDialect::getDataLayoutAttrName())) 770168213f9SAlex Zinenko llvmModule->setDataLayout(dataLayoutAttr.cast<StringAttr>().getValue()); 7715dd5a083SNicolas Vasilache if (auto targetTripleAttr = 7725dd5a083SNicolas Vasilache m->getAttr(LLVM::LLVMDialect::getTargetTripleAttrName())) 7735dd5a083SNicolas Vasilache llvmModule->setTargetTriple(targetTripleAttr.cast<StringAttr>().getValue()); 7745d7231d8SStephan Herhut 7755d7231d8SStephan Herhut // Inject declarations for `malloc` and `free` functions that can be used in 7765d7231d8SStephan Herhut // memref allocation/deallocation coming from standard ops lowering. 777db1c197bSAlex Zinenko llvm::IRBuilder<> builder(llvmContext); 7785d7231d8SStephan Herhut llvmModule->getOrInsertFunction("malloc", builder.getInt8PtrTy(), 7795d7231d8SStephan Herhut builder.getInt64Ty()); 7805d7231d8SStephan Herhut llvmModule->getOrInsertFunction("free", builder.getVoidTy(), 7815d7231d8SStephan Herhut builder.getInt8PtrTy()); 7825d7231d8SStephan Herhut 7835d7231d8SStephan Herhut return llvmModule; 7845d7231d8SStephan Herhut } 785ce8f10d6SAlex Zinenko 786ce8f10d6SAlex Zinenko std::unique_ptr<llvm::Module> 787ce8f10d6SAlex Zinenko mlir::translateModuleToLLVMIR(Operation *module, llvm::LLVMContext &llvmContext, 788ce8f10d6SAlex Zinenko StringRef name) { 789ce8f10d6SAlex Zinenko if (!satisfiesLLVMModule(module)) 790ce8f10d6SAlex Zinenko return nullptr; 791ce8f10d6SAlex Zinenko if (failed(checkSupportedModuleOps(module))) 792ce8f10d6SAlex Zinenko return nullptr; 793ce8f10d6SAlex Zinenko std::unique_ptr<llvm::Module> llvmModule = 794ce8f10d6SAlex Zinenko prepareLLVMModule(module, llvmContext, name); 795ce8f10d6SAlex Zinenko 796ce8f10d6SAlex Zinenko LLVM::ensureDistinctSuccessors(module); 797ce8f10d6SAlex Zinenko 798ce8f10d6SAlex Zinenko ModuleTranslation translator(module, std::move(llvmModule)); 799ce8f10d6SAlex Zinenko if (failed(translator.convertFunctionSignatures())) 800ce8f10d6SAlex Zinenko return nullptr; 801ce8f10d6SAlex Zinenko if (failed(translator.convertGlobals())) 802ce8f10d6SAlex Zinenko return nullptr; 8034a2930f4SArpith C. Jacob if (failed(translator.createAccessGroupMetadata())) 8044a2930f4SArpith C. Jacob return nullptr; 805ce8f10d6SAlex Zinenko if (failed(translator.convertFunctions())) 806ce8f10d6SAlex Zinenko return nullptr; 807ce8f10d6SAlex Zinenko if (llvm::verifyModule(*translator.llvmModule, &llvm::errs())) 808ce8f10d6SAlex Zinenko return nullptr; 809ce8f10d6SAlex Zinenko 810ce8f10d6SAlex Zinenko return std::move(translator.llvmModule); 811ce8f10d6SAlex Zinenko } 812