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" 26929189a4SWilliam S. Moses #include "mlir/Target/LLVMIR/TypeToLLVM.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 1065ef21506SAdrian Kuegel /// attributes and combinations thereof. Also, an array attribute with two 1075ef21506SAdrian Kuegel /// elements is supported to represent a complex constant. In case of error, 1085ef21506SAdrian Kuegel /// report it to `loc` and return nullptr. 109176379e0SAlex Zinenko llvm::Constant *mlir::LLVM::detail::getLLVMConstant( 110176379e0SAlex Zinenko llvm::Type *llvmType, Attribute attr, Location loc, 1115ef21506SAdrian Kuegel const ModuleTranslation &moduleTranslation, bool isTopLevel) { 11233a3a91bSChristian Sigg if (!attr) 11333a3a91bSChristian Sigg return llvm::UndefValue::get(llvmType); 1145ef21506SAdrian Kuegel if (auto *structType = dyn_cast<::llvm::StructType>(llvmType)) { 1155ef21506SAdrian Kuegel if (!isTopLevel) { 1165ef21506SAdrian Kuegel emitError(loc, "nested struct types are not supported in constants"); 117a4a42160SAlex Zinenko return nullptr; 118a4a42160SAlex Zinenko } 1195ef21506SAdrian Kuegel auto arrayAttr = attr.cast<ArrayAttr>(); 1205ef21506SAdrian Kuegel llvm::Type *elementType = structType->getElementType(0); 1215ef21506SAdrian Kuegel llvm::Constant *real = getLLVMConstant(elementType, arrayAttr[0], loc, 1225ef21506SAdrian Kuegel moduleTranslation, false); 1235ef21506SAdrian Kuegel if (!real) 1245ef21506SAdrian Kuegel return nullptr; 1255ef21506SAdrian Kuegel llvm::Constant *imag = getLLVMConstant(elementType, arrayAttr[1], loc, 1265ef21506SAdrian Kuegel moduleTranslation, false); 1275ef21506SAdrian Kuegel if (!imag) 1285ef21506SAdrian Kuegel return nullptr; 1295ef21506SAdrian Kuegel return llvm::ConstantStruct::get(structType, {real, imag}); 1305ef21506SAdrian Kuegel } 131ac9d742bSStephan Herhut // For integer types, we allow a mismatch in sizes as the index type in 132ac9d742bSStephan Herhut // MLIR might have a different size than the index type in the LLVM module. 1335d7231d8SStephan Herhut if (auto intAttr = attr.dyn_cast<IntegerAttr>()) 134ac9d742bSStephan Herhut return llvm::ConstantInt::get( 135ac9d742bSStephan Herhut llvmType, 136ac9d742bSStephan Herhut intAttr.getValue().sextOrTrunc(llvmType->getIntegerBitWidth())); 1375ef21506SAdrian Kuegel if (auto floatAttr = attr.dyn_cast<FloatAttr>()) { 1385ef21506SAdrian Kuegel if (llvmType != 1395ef21506SAdrian Kuegel llvm::Type::getFloatingPointTy(llvmType->getContext(), 1405ef21506SAdrian Kuegel floatAttr.getValue().getSemantics())) { 1415ef21506SAdrian Kuegel emitError(loc, "FloatAttr does not match expected type of the constant"); 1425ef21506SAdrian Kuegel return nullptr; 1435ef21506SAdrian Kuegel } 1445d7231d8SStephan Herhut return llvm::ConstantFP::get(llvmType, floatAttr.getValue()); 1455ef21506SAdrian Kuegel } 1469b9c647cSRiver Riddle if (auto funcAttr = attr.dyn_cast<FlatSymbolRefAttr>()) 147176379e0SAlex Zinenko return llvm::ConstantExpr::getBitCast( 148176379e0SAlex Zinenko moduleTranslation.lookupFunction(funcAttr.getValue()), llvmType); 1495d7231d8SStephan Herhut if (auto splatAttr = attr.dyn_cast<SplatElementsAttr>()) { 15068b03aeeSEli Friedman llvm::Type *elementType; 15168b03aeeSEli Friedman uint64_t numElements; 15268b03aeeSEli Friedman if (auto *arrayTy = dyn_cast<llvm::ArrayType>(llvmType)) { 15368b03aeeSEli Friedman elementType = arrayTy->getElementType(); 15468b03aeeSEli Friedman numElements = arrayTy->getNumElements(); 15568b03aeeSEli Friedman } else { 1565cba1c63SChristopher Tetreault auto *vectorTy = cast<llvm::FixedVectorType>(llvmType); 15768b03aeeSEli Friedman elementType = vectorTy->getElementType(); 15868b03aeeSEli Friedman numElements = vectorTy->getNumElements(); 15968b03aeeSEli Friedman } 160d6ea8ff0SAlex Zinenko // Splat value is a scalar. Extract it only if the element type is not 161d6ea8ff0SAlex Zinenko // another sequence type. The recursion terminates because each step removes 162d6ea8ff0SAlex Zinenko // one outer sequential type. 16368b03aeeSEli Friedman bool elementTypeSequential = 164d891d738SRahul Joshi isa<llvm::ArrayType, llvm::VectorType>(elementType); 165d6ea8ff0SAlex Zinenko llvm::Constant *child = getLLVMConstant( 166d6ea8ff0SAlex Zinenko elementType, 167176379e0SAlex Zinenko elementTypeSequential ? splatAttr : splatAttr.getSplatValue(), loc, 1685ef21506SAdrian Kuegel moduleTranslation, false); 169a4a42160SAlex Zinenko if (!child) 170a4a42160SAlex Zinenko return nullptr; 1712f13df13SMLIR Team if (llvmType->isVectorTy()) 172396a42d9SRiver Riddle return llvm::ConstantVector::getSplat( 1730f95e731SAlex Zinenko llvm::ElementCount::get(numElements, /*Scalable=*/false), child); 1742f13df13SMLIR Team if (llvmType->isArrayTy()) { 175ac9d742bSStephan Herhut auto *arrayType = llvm::ArrayType::get(elementType, numElements); 1762f13df13SMLIR Team SmallVector<llvm::Constant *, 8> constants(numElements, child); 1772f13df13SMLIR Team return llvm::ConstantArray::get(arrayType, constants); 1782f13df13SMLIR Team } 1795d7231d8SStephan Herhut } 180a4a42160SAlex Zinenko 181d906f84bSRiver Riddle if (auto elementsAttr = attr.dyn_cast<ElementsAttr>()) { 182a4a42160SAlex Zinenko assert(elementsAttr.getType().hasStaticShape()); 183a4a42160SAlex Zinenko assert(!elementsAttr.getType().getShape().empty() && 184a4a42160SAlex Zinenko "unexpected empty elements attribute shape"); 185a4a42160SAlex Zinenko 1865d7231d8SStephan Herhut SmallVector<llvm::Constant *, 8> constants; 187a4a42160SAlex Zinenko constants.reserve(elementsAttr.getNumElements()); 188a4a42160SAlex Zinenko llvm::Type *innermostType = getInnermostElementType(llvmType); 189d906f84bSRiver Riddle for (auto n : elementsAttr.getValues<Attribute>()) { 190176379e0SAlex Zinenko constants.push_back( 1915ef21506SAdrian Kuegel getLLVMConstant(innermostType, n, loc, moduleTranslation, false)); 1925d7231d8SStephan Herhut if (!constants.back()) 1935d7231d8SStephan Herhut return nullptr; 1945d7231d8SStephan Herhut } 195a4a42160SAlex Zinenko ArrayRef<llvm::Constant *> constantsRef = constants; 196a4a42160SAlex Zinenko llvm::Constant *result = buildSequentialConstant( 197a4a42160SAlex Zinenko constantsRef, elementsAttr.getType().getShape(), llvmType, loc); 198a4a42160SAlex Zinenko assert(constantsRef.empty() && "did not consume all elemental constants"); 199a4a42160SAlex Zinenko return result; 2002f13df13SMLIR Team } 201a4a42160SAlex Zinenko 202cb348dffSStephan Herhut if (auto stringAttr = attr.dyn_cast<StringAttr>()) { 203cb348dffSStephan Herhut return llvm::ConstantDataArray::get( 204176379e0SAlex Zinenko moduleTranslation.getLLVMContext(), 205176379e0SAlex Zinenko ArrayRef<char>{stringAttr.getValue().data(), 206cb348dffSStephan Herhut stringAttr.getValue().size()}); 207cb348dffSStephan Herhut } 208a4c3a645SRiver Riddle emitError(loc, "unsupported constant value"); 2095d7231d8SStephan Herhut return nullptr; 2105d7231d8SStephan Herhut } 2115d7231d8SStephan Herhut 212c33d6970SRiver Riddle ModuleTranslation::ModuleTranslation(Operation *module, 213c33d6970SRiver Riddle std::unique_ptr<llvm::Module> llvmModule) 214c33d6970SRiver Riddle : mlirModule(module), llvmModule(std::move(llvmModule)), 215c33d6970SRiver Riddle debugTranslation( 21692a295ebSKiran Chandramohan std::make_unique<DebugTranslation>(module, *this->llvmModule)), 217b77bac05SAlex Zinenko typeTranslator(this->llvmModule->getContext()), 218b77bac05SAlex Zinenko iface(module->getContext()) { 219c33d6970SRiver Riddle assert(satisfiesLLVMModule(mlirModule) && 220c33d6970SRiver Riddle "mlirModule should honor LLVM's module semantics."); 221c33d6970SRiver Riddle } 222d9067dcaSKiran Chandramohan ModuleTranslation::~ModuleTranslation() { 223d9067dcaSKiran Chandramohan if (ompBuilder) 224d9067dcaSKiran Chandramohan ompBuilder->finalize(); 225d9067dcaSKiran Chandramohan } 226d9067dcaSKiran Chandramohan 227d9067dcaSKiran Chandramohan /// Get the SSA value passed to the current block from the terminator operation 228d9067dcaSKiran Chandramohan /// of its predecessor. 229d9067dcaSKiran Chandramohan static Value getPHISourceValue(Block *current, Block *pred, 230d9067dcaSKiran Chandramohan unsigned numArguments, unsigned index) { 231d9067dcaSKiran Chandramohan Operation &terminator = *pred->getTerminator(); 232d9067dcaSKiran Chandramohan if (isa<LLVM::BrOp>(terminator)) 233d9067dcaSKiran Chandramohan return terminator.getOperand(index); 234d9067dcaSKiran Chandramohan 23514f24155SBrian Gesiak SuccessorRange successors = terminator.getSuccessors(); 23614f24155SBrian Gesiak assert(std::adjacent_find(successors.begin(), successors.end()) == 23714f24155SBrian Gesiak successors.end() && 23814f24155SBrian Gesiak "successors with arguments in LLVM branches must be different blocks"); 23958f2b765SChristian Sigg (void)successors; 240d9067dcaSKiran Chandramohan 24114f24155SBrian Gesiak // For instructions that branch based on a condition value, we need to take 24214f24155SBrian Gesiak // the operands for the branch that was taken. 24314f24155SBrian Gesiak if (auto condBranchOp = dyn_cast<LLVM::CondBrOp>(terminator)) { 24414f24155SBrian Gesiak // For conditional branches, we take the operands from either the "true" or 24514f24155SBrian Gesiak // the "false" branch. 246d9067dcaSKiran Chandramohan return condBranchOp.getSuccessor(0) == current 247d9067dcaSKiran Chandramohan ? condBranchOp.trueDestOperands()[index] 248d9067dcaSKiran Chandramohan : condBranchOp.falseDestOperands()[index]; 2490881a4f1SAlex Zinenko } 2500881a4f1SAlex Zinenko 2510881a4f1SAlex Zinenko if (auto switchOp = dyn_cast<LLVM::SwitchOp>(terminator)) { 25214f24155SBrian Gesiak // For switches, we take the operands from either the default case, or from 25314f24155SBrian Gesiak // the case branch that was taken. 25414f24155SBrian Gesiak if (switchOp.defaultDestination() == current) 25514f24155SBrian Gesiak return switchOp.defaultOperands()[index]; 25614f24155SBrian Gesiak for (auto i : llvm::enumerate(switchOp.caseDestinations())) 25714f24155SBrian Gesiak if (i.value() == current) 25814f24155SBrian Gesiak return switchOp.getCaseOperands(i.index())[index]; 25914f24155SBrian Gesiak } 26014f24155SBrian Gesiak 26114f24155SBrian Gesiak llvm_unreachable("only branch or switch operations can be terminators of a " 26214f24155SBrian Gesiak "block that has successors"); 263d9067dcaSKiran Chandramohan } 264d9067dcaSKiran Chandramohan 265d9067dcaSKiran Chandramohan /// Connect the PHI nodes to the results of preceding blocks. 26666900b3eSAlex Zinenko void mlir::LLVM::detail::connectPHINodes(Region ®ion, 26766900b3eSAlex Zinenko const ModuleTranslation &state) { 268d9067dcaSKiran Chandramohan // Skip the first block, it cannot be branched to and its arguments correspond 269d9067dcaSKiran Chandramohan // to the arguments of the LLVM function. 27066900b3eSAlex Zinenko for (auto it = std::next(region.begin()), eit = region.end(); it != eit; 27166900b3eSAlex Zinenko ++it) { 272d9067dcaSKiran Chandramohan Block *bb = &*it; 2730881a4f1SAlex Zinenko llvm::BasicBlock *llvmBB = state.lookupBlock(bb); 274d9067dcaSKiran Chandramohan auto phis = llvmBB->phis(); 275d9067dcaSKiran Chandramohan auto numArguments = bb->getNumArguments(); 276d9067dcaSKiran Chandramohan assert(numArguments == std::distance(phis.begin(), phis.end())); 277d9067dcaSKiran Chandramohan for (auto &numberedPhiNode : llvm::enumerate(phis)) { 278d9067dcaSKiran Chandramohan auto &phiNode = numberedPhiNode.value(); 279d9067dcaSKiran Chandramohan unsigned index = numberedPhiNode.index(); 280d9067dcaSKiran Chandramohan for (auto *pred : bb->getPredecessors()) { 281db884dafSAlex Zinenko // Find the LLVM IR block that contains the converted terminator 282db884dafSAlex Zinenko // instruction and use it in the PHI node. Note that this block is not 2830881a4f1SAlex Zinenko // necessarily the same as state.lookupBlock(pred), some operations 284db884dafSAlex Zinenko // (in particular, OpenMP operations using OpenMPIRBuilder) may have 285db884dafSAlex Zinenko // split the blocks. 286db884dafSAlex Zinenko llvm::Instruction *terminator = 2870881a4f1SAlex Zinenko state.lookupBranch(pred->getTerminator()); 288db884dafSAlex Zinenko assert(terminator && "missing the mapping for a terminator"); 2890881a4f1SAlex Zinenko phiNode.addIncoming( 2900881a4f1SAlex Zinenko state.lookupValue(getPHISourceValue(bb, pred, numArguments, index)), 291db884dafSAlex Zinenko terminator->getParent()); 292d9067dcaSKiran Chandramohan } 293d9067dcaSKiran Chandramohan } 294d9067dcaSKiran Chandramohan } 295d9067dcaSKiran Chandramohan } 296d9067dcaSKiran Chandramohan 297d9067dcaSKiran Chandramohan /// Sort function blocks topologically. 2984efb7754SRiver Riddle SetVector<Block *> 29966900b3eSAlex Zinenko mlir::LLVM::detail::getTopologicallySortedBlocks(Region ®ion) { 300d4568ed7SGeorge Mitenkov // For each block that has not been visited yet (i.e. that has no 301d4568ed7SGeorge Mitenkov // predecessors), add it to the list as well as its successors. 3024efb7754SRiver Riddle SetVector<Block *> blocks; 30366900b3eSAlex Zinenko for (Block &b : region) { 304d4568ed7SGeorge Mitenkov if (blocks.count(&b) == 0) { 305d4568ed7SGeorge Mitenkov llvm::ReversePostOrderTraversal<Block *> traversal(&b); 306d4568ed7SGeorge Mitenkov blocks.insert(traversal.begin(), traversal.end()); 307d4568ed7SGeorge Mitenkov } 308d9067dcaSKiran Chandramohan } 30966900b3eSAlex Zinenko assert(blocks.size() == region.getBlocks().size() && 31066900b3eSAlex Zinenko "some blocks are not sorted"); 311d9067dcaSKiran Chandramohan 312d9067dcaSKiran Chandramohan return blocks; 313d9067dcaSKiran Chandramohan } 314d9067dcaSKiran Chandramohan 315176379e0SAlex Zinenko llvm::Value *mlir::LLVM::detail::createIntrinsicCall( 316176379e0SAlex Zinenko llvm::IRBuilderBase &builder, llvm::Intrinsic::ID intrinsic, 317176379e0SAlex Zinenko ArrayRef<llvm::Value *> args, ArrayRef<llvm::Type *> tys) { 318176379e0SAlex Zinenko llvm::Module *module = builder.GetInsertBlock()->getModule(); 319176379e0SAlex Zinenko llvm::Function *fn = llvm::Intrinsic::getDeclaration(module, intrinsic, tys); 320176379e0SAlex Zinenko return builder.CreateCall(fn, args); 321176379e0SAlex Zinenko } 322176379e0SAlex Zinenko 323875eb523SNavdeep Kumar llvm::Value * 324875eb523SNavdeep Kumar mlir::LLVM::detail::createNvvmIntrinsicCall(llvm::IRBuilderBase &builder, 325875eb523SNavdeep Kumar llvm::Intrinsic::ID intrinsic, 326875eb523SNavdeep Kumar ArrayRef<llvm::Value *> args) { 327875eb523SNavdeep Kumar llvm::Module *module = builder.GetInsertBlock()->getModule(); 328875eb523SNavdeep Kumar llvm::Function *fn; 329875eb523SNavdeep Kumar if (llvm::Intrinsic::isOverloaded(intrinsic)) { 330875eb523SNavdeep Kumar if (intrinsic != llvm::Intrinsic::nvvm_wmma_m16n16k16_mma_row_row_f16_f16 && 331875eb523SNavdeep Kumar intrinsic != llvm::Intrinsic::nvvm_wmma_m16n16k16_mma_row_row_f32_f32) { 332875eb523SNavdeep Kumar // NVVM load and store instrinsic names are overloaded on the 333875eb523SNavdeep Kumar // source/destination pointer type. Pointer is the first argument in the 334875eb523SNavdeep Kumar // corresponding NVVM Op. 335875eb523SNavdeep Kumar fn = llvm::Intrinsic::getDeclaration(module, intrinsic, 336875eb523SNavdeep Kumar {args[0]->getType()}); 337875eb523SNavdeep Kumar } else { 338875eb523SNavdeep Kumar fn = llvm::Intrinsic::getDeclaration(module, intrinsic, {}); 339875eb523SNavdeep Kumar } 340875eb523SNavdeep Kumar } else { 341875eb523SNavdeep Kumar fn = llvm::Intrinsic::getDeclaration(module, intrinsic); 342875eb523SNavdeep Kumar } 343875eb523SNavdeep Kumar return builder.CreateCall(fn, args); 344875eb523SNavdeep Kumar } 345875eb523SNavdeep Kumar 3462666b973SRiver Riddle /// Given a single MLIR operation, create the corresponding LLVM IR operation 347176379e0SAlex Zinenko /// using the `builder`. 348ce8f10d6SAlex Zinenko LogicalResult 34938b106f6SMehdi Amini ModuleTranslation::convertOperation(Operation &op, 350ce8f10d6SAlex Zinenko llvm::IRBuilderBase &builder) { 35138b106f6SMehdi Amini const LLVMTranslationDialectInterface *opIface = iface.getInterfaceFor(&op); 35238b106f6SMehdi Amini if (!opIface) 35338b106f6SMehdi Amini return op.emitError("cannot be converted to LLVM IR: missing " 35438b106f6SMehdi Amini "`LLVMTranslationDialectInterface` registration for " 35538b106f6SMehdi Amini "dialect for op: ") 35638b106f6SMehdi Amini << op.getName(); 357176379e0SAlex Zinenko 35838b106f6SMehdi Amini if (failed(opIface->convertOperation(&op, builder, *this))) 35938b106f6SMehdi Amini return op.emitError("LLVM Translation failed for operation: ") 36038b106f6SMehdi Amini << op.getName(); 36138b106f6SMehdi Amini 36238b106f6SMehdi Amini return convertDialectAttributes(&op); 3635d7231d8SStephan Herhut } 3645d7231d8SStephan Herhut 3652666b973SRiver Riddle /// Convert block to LLVM IR. Unless `ignoreArguments` is set, emit PHI nodes 3662666b973SRiver Riddle /// to define values corresponding to the MLIR block arguments. These nodes 36710164a2eSAlex Zinenko /// are not connected to the source basic blocks, which may not exist yet. Uses 36810164a2eSAlex Zinenko /// `builder` to construct the LLVM IR. Expects the LLVM IR basic block to have 36910164a2eSAlex Zinenko /// been created for `bb` and included in the block mapping. Inserts new 37010164a2eSAlex Zinenko /// instructions at the end of the block and leaves `builder` in a state 37110164a2eSAlex Zinenko /// suitable for further insertion into the end of the block. 37210164a2eSAlex Zinenko LogicalResult ModuleTranslation::convertBlock(Block &bb, bool ignoreArguments, 373ce8f10d6SAlex Zinenko llvm::IRBuilderBase &builder) { 3740881a4f1SAlex Zinenko builder.SetInsertPoint(lookupBlock(&bb)); 375c33d6970SRiver Riddle auto *subprogram = builder.GetInsertBlock()->getParent()->getSubprogram(); 3765d7231d8SStephan Herhut 3775d7231d8SStephan Herhut // Before traversing operations, make block arguments available through 3785d7231d8SStephan Herhut // value remapping and PHI nodes, but do not add incoming edges for the PHI 3795d7231d8SStephan Herhut // nodes just yet: those values may be defined by this or following blocks. 3805d7231d8SStephan Herhut // This step is omitted if "ignoreArguments" is set. The arguments of the 3815d7231d8SStephan Herhut // first block have been already made available through the remapping of 3825d7231d8SStephan Herhut // LLVM function arguments. 3835d7231d8SStephan Herhut if (!ignoreArguments) { 3845d7231d8SStephan Herhut auto predecessors = bb.getPredecessors(); 3855d7231d8SStephan Herhut unsigned numPredecessors = 3865d7231d8SStephan Herhut std::distance(predecessors.begin(), predecessors.end()); 38735807bc4SRiver Riddle for (auto arg : bb.getArguments()) { 388c69c9e0fSAlex Zinenko auto wrappedType = arg.getType(); 389c69c9e0fSAlex Zinenko if (!isCompatibleType(wrappedType)) 390baa1ec22SAlex Zinenko return emitError(bb.front().getLoc(), 391a4c3a645SRiver Riddle "block argument does not have an LLVM type"); 392aec38c61SAlex Zinenko llvm::Type *type = convertType(wrappedType); 3935d7231d8SStephan Herhut llvm::PHINode *phi = builder.CreatePHI(type, numPredecessors); 3940881a4f1SAlex Zinenko mapValue(arg, phi); 3955d7231d8SStephan Herhut } 3965d7231d8SStephan Herhut } 3975d7231d8SStephan Herhut 3985d7231d8SStephan Herhut // Traverse operations. 3995d7231d8SStephan Herhut for (auto &op : bb) { 400c33d6970SRiver Riddle // Set the current debug location within the builder. 401c33d6970SRiver Riddle builder.SetCurrentDebugLocation( 402c33d6970SRiver Riddle debugTranslation->translateLoc(op.getLoc(), subprogram)); 403c33d6970SRiver Riddle 404baa1ec22SAlex Zinenko if (failed(convertOperation(op, builder))) 405baa1ec22SAlex Zinenko return failure(); 4065d7231d8SStephan Herhut } 4075d7231d8SStephan Herhut 408baa1ec22SAlex Zinenko return success(); 4095d7231d8SStephan Herhut } 4105d7231d8SStephan Herhut 411ce8f10d6SAlex Zinenko /// A helper method to get the single Block in an operation honoring LLVM's 412ce8f10d6SAlex Zinenko /// module requirements. 413ce8f10d6SAlex Zinenko static Block &getModuleBody(Operation *module) { 414ce8f10d6SAlex Zinenko return module->getRegion(0).front(); 415ce8f10d6SAlex Zinenko } 416ce8f10d6SAlex Zinenko 417ffa455d4SJean Perier /// A helper method to decide if a constant must not be set as a global variable 418d4df3825SAlex Zinenko /// initializer. For an external linkage variable, the variable with an 419d4df3825SAlex Zinenko /// initializer is considered externally visible and defined in this module, the 420d4df3825SAlex Zinenko /// variable without an initializer is externally available and is defined 421d4df3825SAlex Zinenko /// elsewhere. 422ffa455d4SJean Perier static bool shouldDropGlobalInitializer(llvm::GlobalValue::LinkageTypes linkage, 423ffa455d4SJean Perier llvm::Constant *cst) { 424d4df3825SAlex Zinenko return (linkage == llvm::GlobalVariable::ExternalLinkage && !cst) || 425ffa455d4SJean Perier linkage == llvm::GlobalVariable::ExternalWeakLinkage; 426ffa455d4SJean Perier } 427ffa455d4SJean Perier 4288ca04b05SFelipe de Azevedo Piovezan /// Sets the runtime preemption specifier of `gv` to dso_local if 4298ca04b05SFelipe de Azevedo Piovezan /// `dsoLocalRequested` is true, otherwise it is left unchanged. 4308ca04b05SFelipe de Azevedo Piovezan static void addRuntimePreemptionSpecifier(bool dsoLocalRequested, 4318ca04b05SFelipe de Azevedo Piovezan llvm::GlobalValue *gv) { 4328ca04b05SFelipe de Azevedo Piovezan if (dsoLocalRequested) 4338ca04b05SFelipe de Azevedo Piovezan gv->setDSOLocal(true); 4348ca04b05SFelipe de Azevedo Piovezan } 4358ca04b05SFelipe de Azevedo Piovezan 4362666b973SRiver Riddle /// Create named global variables that correspond to llvm.mlir.global 4372666b973SRiver Riddle /// definitions. 438efa2d533SAlex Zinenko LogicalResult ModuleTranslation::convertGlobals() { 43944fc7d72STres Popp for (auto op : getModuleBody(mlirModule).getOps<LLVM::GlobalOp>()) { 440aec38c61SAlex Zinenko llvm::Type *type = convertType(op.getType()); 441d4df3825SAlex Zinenko llvm::Constant *cst = nullptr; 442250a11aeSJames Molloy if (op.getValueOrNull()) { 44368451df2SAlex Zinenko // String attributes are treated separately because they cannot appear as 44468451df2SAlex Zinenko // in-function constants and are thus not supported by getLLVMConstant. 44533a3a91bSChristian Sigg if (auto strAttr = op.getValueOrNull().dyn_cast_or_null<StringAttr>()) { 4462dd38b09SAlex Zinenko cst = llvm::ConstantDataArray::getString( 44768451df2SAlex Zinenko llvmModule->getContext(), strAttr.getValue(), /*AddNull=*/false); 4482dd38b09SAlex Zinenko type = cst->getType(); 449176379e0SAlex Zinenko } else if (!(cst = getLLVMConstant(type, op.getValueOrNull(), op.getLoc(), 450176379e0SAlex Zinenko *this))) { 451efa2d533SAlex Zinenko return failure(); 45268451df2SAlex Zinenko } 453ffa455d4SJean Perier } 454ffa455d4SJean Perier 455ffa455d4SJean Perier auto linkage = convertLinkageToLLVM(op.linkage()); 456ffa455d4SJean Perier auto addrSpace = op.addr_space(); 457d4df3825SAlex Zinenko 458d4df3825SAlex Zinenko // LLVM IR requires constant with linkage other than external or weak 459d4df3825SAlex Zinenko // external to have initializers. If MLIR does not provide an initializer, 460d4df3825SAlex Zinenko // default to undef. 461d4df3825SAlex Zinenko bool dropInitializer = shouldDropGlobalInitializer(linkage, cst); 462d4df3825SAlex Zinenko if (!dropInitializer && !cst) 463d4df3825SAlex Zinenko cst = llvm::UndefValue::get(type); 464d4df3825SAlex Zinenko else if (dropInitializer && cst) 465d4df3825SAlex Zinenko cst = nullptr; 466d4df3825SAlex Zinenko 467ffa455d4SJean Perier auto *var = new llvm::GlobalVariable( 468d4df3825SAlex Zinenko *llvmModule, type, op.constant(), linkage, cst, op.sym_name(), 469ffa455d4SJean Perier /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal, addrSpace); 470ffa455d4SJean Perier 471c46a8862Sclementval if (op.unnamed_addr().hasValue()) 472c46a8862Sclementval var->setUnnamedAddr(convertUnnamedAddrToLLVM(*op.unnamed_addr())); 473c46a8862Sclementval 474b65472d6SRanjith Kumar H if (op.section().hasValue()) 475b65472d6SRanjith Kumar H var->setSection(*op.section()); 476b65472d6SRanjith Kumar H 4778ca04b05SFelipe de Azevedo Piovezan addRuntimePreemptionSpecifier(op.dso_local(), var); 4788ca04b05SFelipe de Azevedo Piovezan 4799a0ea599SDumitru Potop Optional<uint64_t> alignment = op.alignment(); 4809a0ea599SDumitru Potop if (alignment.hasValue()) 4819a0ea599SDumitru Potop var->setAlignment(llvm::MaybeAlign(alignment.getValue())); 4829a0ea599SDumitru Potop 483ffa455d4SJean Perier globalsMapping.try_emplace(op, var); 484ffa455d4SJean Perier } 485ffa455d4SJean Perier 486ffa455d4SJean Perier // Convert global variable bodies. This is done after all global variables 487ffa455d4SJean Perier // have been created in LLVM IR because a global body may refer to another 488ffa455d4SJean Perier // global or itself. So all global variables need to be mapped first. 489ffa455d4SJean Perier for (auto op : getModuleBody(mlirModule).getOps<LLVM::GlobalOp>()) { 490ffa455d4SJean Perier if (Block *initializer = op.getInitializerBlock()) { 491250a11aeSJames Molloy llvm::IRBuilder<> builder(llvmModule->getContext()); 492250a11aeSJames Molloy for (auto &op : initializer->without_terminator()) { 493250a11aeSJames Molloy if (failed(convertOperation(op, builder)) || 4940881a4f1SAlex Zinenko !isa<llvm::Constant>(lookupValue(op.getResult(0)))) 495efa2d533SAlex Zinenko return emitError(op.getLoc(), "unemittable constant value"); 496250a11aeSJames Molloy } 497250a11aeSJames Molloy ReturnOp ret = cast<ReturnOp>(initializer->getTerminator()); 498ffa455d4SJean Perier llvm::Constant *cst = 499ffa455d4SJean Perier cast<llvm::Constant>(lookupValue(ret.getOperand(0))); 500ffa455d4SJean Perier auto *global = cast<llvm::GlobalVariable>(lookupGlobal(op)); 501ffa455d4SJean Perier if (!shouldDropGlobalInitializer(global->getLinkage(), cst)) 502ffa455d4SJean Perier global->setInitializer(cst); 503250a11aeSJames Molloy } 504b9ff2dd8SAlex Zinenko } 505efa2d533SAlex Zinenko 506efa2d533SAlex Zinenko return success(); 507b9ff2dd8SAlex Zinenko } 508b9ff2dd8SAlex Zinenko 5090a2131b7SAlex Zinenko /// Attempts to add an attribute identified by `key`, optionally with the given 5100a2131b7SAlex Zinenko /// `value` to LLVM function `llvmFunc`. Reports errors at `loc` if any. If the 5110a2131b7SAlex Zinenko /// attribute has a kind known to LLVM IR, create the attribute of this kind, 5120a2131b7SAlex Zinenko /// otherwise keep it as a string attribute. Performs additional checks for 5130a2131b7SAlex Zinenko /// attributes known to have or not have a value in order to avoid assertions 5140a2131b7SAlex Zinenko /// inside LLVM upon construction. 5150a2131b7SAlex Zinenko static LogicalResult checkedAddLLVMFnAttribute(Location loc, 5160a2131b7SAlex Zinenko llvm::Function *llvmFunc, 5170a2131b7SAlex Zinenko StringRef key, 5180a2131b7SAlex Zinenko StringRef value = StringRef()) { 5190a2131b7SAlex Zinenko auto kind = llvm::Attribute::getAttrKindFromName(key); 5200a2131b7SAlex Zinenko if (kind == llvm::Attribute::None) { 5210a2131b7SAlex Zinenko llvmFunc->addFnAttr(key, value); 5220a2131b7SAlex Zinenko return success(); 5230a2131b7SAlex Zinenko } 5240a2131b7SAlex Zinenko 5256ac32872SNikita Popov if (llvm::Attribute::isIntAttrKind(kind)) { 5260a2131b7SAlex Zinenko if (value.empty()) 5270a2131b7SAlex Zinenko return emitError(loc) << "LLVM attribute '" << key << "' expects a value"; 5280a2131b7SAlex Zinenko 5290a2131b7SAlex Zinenko int result; 5300a2131b7SAlex Zinenko if (!value.getAsInteger(/*Radix=*/0, result)) 5310a2131b7SAlex Zinenko llvmFunc->addFnAttr( 5320a2131b7SAlex Zinenko llvm::Attribute::get(llvmFunc->getContext(), kind, result)); 5330a2131b7SAlex Zinenko else 5340a2131b7SAlex Zinenko llvmFunc->addFnAttr(key, value); 5350a2131b7SAlex Zinenko return success(); 5360a2131b7SAlex Zinenko } 5370a2131b7SAlex Zinenko 5380a2131b7SAlex Zinenko if (!value.empty()) 5390a2131b7SAlex Zinenko return emitError(loc) << "LLVM attribute '" << key 5400a2131b7SAlex Zinenko << "' does not expect a value, found '" << value 5410a2131b7SAlex Zinenko << "'"; 5420a2131b7SAlex Zinenko 5430a2131b7SAlex Zinenko llvmFunc->addFnAttr(kind); 5440a2131b7SAlex Zinenko return success(); 5450a2131b7SAlex Zinenko } 5460a2131b7SAlex Zinenko 5470a2131b7SAlex Zinenko /// Attaches the attributes listed in the given array attribute to `llvmFunc`. 5480a2131b7SAlex Zinenko /// Reports error to `loc` if any and returns immediately. Expects `attributes` 5490a2131b7SAlex Zinenko /// to be an array attribute containing either string attributes, treated as 5500a2131b7SAlex Zinenko /// value-less LLVM attributes, or array attributes containing two string 5510a2131b7SAlex Zinenko /// attributes, with the first string being the name of the corresponding LLVM 5520a2131b7SAlex Zinenko /// attribute and the second string beings its value. Note that even integer 5530a2131b7SAlex Zinenko /// attributes are expected to have their values expressed as strings. 5540a2131b7SAlex Zinenko static LogicalResult 5550a2131b7SAlex Zinenko forwardPassthroughAttributes(Location loc, Optional<ArrayAttr> attributes, 5560a2131b7SAlex Zinenko llvm::Function *llvmFunc) { 5570a2131b7SAlex Zinenko if (!attributes) 5580a2131b7SAlex Zinenko return success(); 5590a2131b7SAlex Zinenko 5600a2131b7SAlex Zinenko for (Attribute attr : *attributes) { 5610a2131b7SAlex Zinenko if (auto stringAttr = attr.dyn_cast<StringAttr>()) { 5620a2131b7SAlex Zinenko if (failed( 5630a2131b7SAlex Zinenko checkedAddLLVMFnAttribute(loc, llvmFunc, stringAttr.getValue()))) 5640a2131b7SAlex Zinenko return failure(); 5650a2131b7SAlex Zinenko continue; 5660a2131b7SAlex Zinenko } 5670a2131b7SAlex Zinenko 5680a2131b7SAlex Zinenko auto arrayAttr = attr.dyn_cast<ArrayAttr>(); 5690a2131b7SAlex Zinenko if (!arrayAttr || arrayAttr.size() != 2) 5700a2131b7SAlex Zinenko return emitError(loc) 5710a2131b7SAlex Zinenko << "expected 'passthrough' to contain string or array attributes"; 5720a2131b7SAlex Zinenko 5730a2131b7SAlex Zinenko auto keyAttr = arrayAttr[0].dyn_cast<StringAttr>(); 5740a2131b7SAlex Zinenko auto valueAttr = arrayAttr[1].dyn_cast<StringAttr>(); 5750a2131b7SAlex Zinenko if (!keyAttr || !valueAttr) 5760a2131b7SAlex Zinenko return emitError(loc) 5770a2131b7SAlex Zinenko << "expected arrays within 'passthrough' to contain two strings"; 5780a2131b7SAlex Zinenko 5790a2131b7SAlex Zinenko if (failed(checkedAddLLVMFnAttribute(loc, llvmFunc, keyAttr.getValue(), 5800a2131b7SAlex Zinenko valueAttr.getValue()))) 5810a2131b7SAlex Zinenko return failure(); 5820a2131b7SAlex Zinenko } 5830a2131b7SAlex Zinenko return success(); 5840a2131b7SAlex Zinenko } 5850a2131b7SAlex Zinenko 5865e7959a3SAlex Zinenko LogicalResult ModuleTranslation::convertOneFunction(LLVMFuncOp func) { 587db884dafSAlex Zinenko // Clear the block, branch value mappings, they are only relevant within one 5885d7231d8SStephan Herhut // function. 5895d7231d8SStephan Herhut blockMapping.clear(); 5905d7231d8SStephan Herhut valueMapping.clear(); 591db884dafSAlex Zinenko branchMapping.clear(); 5920881a4f1SAlex Zinenko llvm::Function *llvmFunc = lookupFunction(func.getName()); 593c33d6970SRiver Riddle 594c33d6970SRiver Riddle // Translate the debug information for this function. 595c33d6970SRiver Riddle debugTranslation->translate(func, *llvmFunc); 596c33d6970SRiver Riddle 5975d7231d8SStephan Herhut // Add function arguments to the value remapping table. 5985d7231d8SStephan Herhut // If there was noalias info then we decorate each argument accordingly. 5995d7231d8SStephan Herhut unsigned int argIdx = 0; 600eeef50b1SFangrui Song for (auto kvp : llvm::zip(func.getArguments(), llvmFunc->args())) { 6015d7231d8SStephan Herhut llvm::Argument &llvmArg = std::get<1>(kvp); 602e62a6956SRiver Riddle BlockArgument mlirArg = std::get<0>(kvp); 6035d7231d8SStephan Herhut 6041c777ab4SUday Bondhugula if (auto attr = func.getArgAttrOfType<UnitAttr>( 60567cc5cecSStephan Herhut argIdx, LLVMDialect::getNoAliasAttrName())) { 6065d7231d8SStephan Herhut // NB: Attribute already verified to be boolean, so check if we can indeed 6075d7231d8SStephan Herhut // attach the attribute to this argument, based on its type. 608c69c9e0fSAlex Zinenko auto argTy = mlirArg.getType(); 6098de43b92SAlex Zinenko if (!argTy.isa<LLVM::LLVMPointerType>()) 610baa1ec22SAlex Zinenko return func.emitError( 6115d7231d8SStephan Herhut "llvm.noalias attribute attached to LLVM non-pointer argument"); 6125d7231d8SStephan Herhut llvmArg.addAttr(llvm::Attribute::AttrKind::NoAlias); 6135d7231d8SStephan Herhut } 6142416e28cSStephan Herhut 61567cc5cecSStephan Herhut if (auto attr = func.getArgAttrOfType<IntegerAttr>( 61667cc5cecSStephan Herhut argIdx, LLVMDialect::getAlignAttrName())) { 6172416e28cSStephan Herhut // NB: Attribute already verified to be int, so check if we can indeed 6182416e28cSStephan Herhut // attach the attribute to this argument, based on its type. 619c69c9e0fSAlex Zinenko auto argTy = mlirArg.getType(); 6208de43b92SAlex Zinenko if (!argTy.isa<LLVM::LLVMPointerType>()) 6212416e28cSStephan Herhut return func.emitError( 6222416e28cSStephan Herhut "llvm.align attribute attached to LLVM non-pointer argument"); 6232416e28cSStephan Herhut llvmArg.addAttrs( 6242416e28cSStephan Herhut llvm::AttrBuilder().addAlignmentAttr(llvm::Align(attr.getInt()))); 6252416e28cSStephan Herhut } 6262416e28cSStephan Herhut 62770b841acSEric Schweitz if (auto attr = func.getArgAttrOfType<UnitAttr>(argIdx, "llvm.sret")) { 62870b841acSEric Schweitz auto argTy = mlirArg.getType(); 62970b841acSEric Schweitz if (!argTy.isa<LLVM::LLVMPointerType>()) 63070b841acSEric Schweitz return func.emitError( 63170b841acSEric Schweitz "llvm.sret attribute attached to LLVM non-pointer argument"); 6321d6df1fcSEric Schweitz llvmArg.addAttrs(llvm::AttrBuilder().addStructRetAttr( 6331d6df1fcSEric Schweitz llvmArg.getType()->getPointerElementType())); 63470b841acSEric Schweitz } 63570b841acSEric Schweitz 63670b841acSEric Schweitz if (auto attr = func.getArgAttrOfType<UnitAttr>(argIdx, "llvm.byval")) { 63770b841acSEric Schweitz auto argTy = mlirArg.getType(); 63870b841acSEric Schweitz if (!argTy.isa<LLVM::LLVMPointerType>()) 63970b841acSEric Schweitz return func.emitError( 64070b841acSEric Schweitz "llvm.byval attribute attached to LLVM non-pointer argument"); 6411d6df1fcSEric Schweitz llvmArg.addAttrs(llvm::AttrBuilder().addByValAttr( 6421d6df1fcSEric Schweitz llvmArg.getType()->getPointerElementType())); 64370b841acSEric Schweitz } 64470b841acSEric Schweitz 6450881a4f1SAlex Zinenko mapValue(mlirArg, &llvmArg); 6465d7231d8SStephan Herhut argIdx++; 6475d7231d8SStephan Herhut } 6485d7231d8SStephan Herhut 649ff77397fSShraiysh Vaishay // Check the personality and set it. 650ff77397fSShraiysh Vaishay if (func.personality().hasValue()) { 651ff77397fSShraiysh Vaishay llvm::Type *ty = llvm::Type::getInt8PtrTy(llvmFunc->getContext()); 652ff77397fSShraiysh Vaishay if (llvm::Constant *pfunc = 653176379e0SAlex Zinenko getLLVMConstant(ty, func.personalityAttr(), func.getLoc(), *this)) 654ff77397fSShraiysh Vaishay llvmFunc->setPersonalityFn(pfunc); 655ff77397fSShraiysh Vaishay } 656ff77397fSShraiysh Vaishay 6575d7231d8SStephan Herhut // First, create all blocks so we can jump to them. 6585d7231d8SStephan Herhut llvm::LLVMContext &llvmContext = llvmFunc->getContext(); 6595d7231d8SStephan Herhut for (auto &bb : func) { 6605d7231d8SStephan Herhut auto *llvmBB = llvm::BasicBlock::Create(llvmContext); 6615d7231d8SStephan Herhut llvmBB->insertInto(llvmFunc); 6620881a4f1SAlex Zinenko mapBlock(&bb, llvmBB); 6635d7231d8SStephan Herhut } 6645d7231d8SStephan Herhut 6655d7231d8SStephan Herhut // Then, convert blocks one by one in topological order to ensure defs are 6665d7231d8SStephan Herhut // converted before uses. 66766900b3eSAlex Zinenko auto blocks = detail::getTopologicallySortedBlocks(func.getBody()); 66810164a2eSAlex Zinenko for (Block *bb : blocks) { 66910164a2eSAlex Zinenko llvm::IRBuilder<> builder(llvmContext); 67010164a2eSAlex Zinenko if (failed(convertBlock(*bb, bb->isEntryBlock(), builder))) 671baa1ec22SAlex Zinenko return failure(); 6725d7231d8SStephan Herhut } 6735d7231d8SStephan Herhut 674176379e0SAlex Zinenko // After all blocks have been traversed and values mapped, connect the PHI 675176379e0SAlex Zinenko // nodes to the results of preceding blocks. 67666900b3eSAlex Zinenko detail::connectPHINodes(func.getBody(), *this); 677176379e0SAlex Zinenko 678176379e0SAlex Zinenko // Finally, convert dialect attributes attached to the function. 679176379e0SAlex Zinenko return convertDialectAttributes(func); 680176379e0SAlex Zinenko } 681176379e0SAlex Zinenko 682176379e0SAlex Zinenko LogicalResult ModuleTranslation::convertDialectAttributes(Operation *op) { 683176379e0SAlex Zinenko for (NamedAttribute attribute : op->getDialectAttrs()) 684176379e0SAlex Zinenko if (failed(iface.amendOperation(op, attribute, *this))) 685176379e0SAlex Zinenko return failure(); 686baa1ec22SAlex Zinenko return success(); 6875d7231d8SStephan Herhut } 6885d7231d8SStephan Herhut 689ce8f10d6SAlex Zinenko /// Check whether the module contains only supported ops directly in its body. 690ce8f10d6SAlex Zinenko static LogicalResult checkSupportedModuleOps(Operation *m) { 69144fc7d72STres Popp for (Operation &o : getModuleBody(m).getOperations()) 6924a2930f4SArpith C. Jacob if (!isa<LLVM::LLVMFuncOp, LLVM::GlobalOp, LLVM::MetadataOp>(&o) && 693fe7c0d90SRiver Riddle !o.hasTrait<OpTrait::IsTerminator>()) 6944dde19f0SAlex Zinenko return o.emitOpError("unsupported module-level operation"); 6954dde19f0SAlex Zinenko return success(); 6964dde19f0SAlex Zinenko } 6974dde19f0SAlex Zinenko 698a084b94fSSean Silva LogicalResult ModuleTranslation::convertFunctionSignatures() { 6995d7231d8SStephan Herhut // Declare all functions first because there may be function calls that form a 700a084b94fSSean Silva // call graph with cycles, or global initializers that reference functions. 70144fc7d72STres Popp for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) { 7025e7959a3SAlex Zinenko llvm::FunctionCallee llvmFuncCst = llvmModule->getOrInsertFunction( 7035e7959a3SAlex Zinenko function.getName(), 704aec38c61SAlex Zinenko cast<llvm::FunctionType>(convertType(function.getType()))); 7050a2131b7SAlex Zinenko llvm::Function *llvmFunc = cast<llvm::Function>(llvmFuncCst.getCallee()); 706ebbdecddSAlex Zinenko llvmFunc->setLinkage(convertLinkageToLLVM(function.linkage())); 7070881a4f1SAlex Zinenko mapFunction(function.getName(), llvmFunc); 7088ca04b05SFelipe de Azevedo Piovezan addRuntimePreemptionSpecifier(function.dso_local(), llvmFunc); 7090a2131b7SAlex Zinenko 7100a2131b7SAlex Zinenko // Forward the pass-through attributes to LLVM. 7110a2131b7SAlex Zinenko if (failed(forwardPassthroughAttributes(function.getLoc(), 7120a2131b7SAlex Zinenko function.passthrough(), llvmFunc))) 7130a2131b7SAlex Zinenko return failure(); 7145d7231d8SStephan Herhut } 7155d7231d8SStephan Herhut 716a084b94fSSean Silva return success(); 717a084b94fSSean Silva } 718a084b94fSSean Silva 719a084b94fSSean Silva LogicalResult ModuleTranslation::convertFunctions() { 7205d7231d8SStephan Herhut // Convert functions. 72144fc7d72STres Popp for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) { 7225d7231d8SStephan Herhut // Ignore external functions. 7235d7231d8SStephan Herhut if (function.isExternal()) 7245d7231d8SStephan Herhut continue; 7255d7231d8SStephan Herhut 726baa1ec22SAlex Zinenko if (failed(convertOneFunction(function))) 727baa1ec22SAlex Zinenko return failure(); 7285d7231d8SStephan Herhut } 7295d7231d8SStephan Herhut 730baa1ec22SAlex Zinenko return success(); 7315d7231d8SStephan Herhut } 7325d7231d8SStephan Herhut 7334a2930f4SArpith C. Jacob llvm::MDNode * 7344a2930f4SArpith C. Jacob ModuleTranslation::getAccessGroup(Operation &opInst, 7354a2930f4SArpith C. Jacob SymbolRefAttr accessGroupRef) const { 7364a2930f4SArpith C. Jacob auto metadataName = accessGroupRef.getRootReference(); 7374a2930f4SArpith C. Jacob auto accessGroupName = accessGroupRef.getLeafReference(); 7384a2930f4SArpith C. Jacob auto metadataOp = SymbolTable::lookupNearestSymbolFrom<LLVM::MetadataOp>( 7394a2930f4SArpith C. Jacob opInst.getParentOp(), metadataName); 7404a2930f4SArpith C. Jacob auto *accessGroupOp = 7414a2930f4SArpith C. Jacob SymbolTable::lookupNearestSymbolFrom(metadataOp, accessGroupName); 7424a2930f4SArpith C. Jacob return accessGroupMetadataMapping.lookup(accessGroupOp); 7434a2930f4SArpith C. Jacob } 7444a2930f4SArpith C. Jacob 7454a2930f4SArpith C. Jacob LogicalResult ModuleTranslation::createAccessGroupMetadata() { 7464a2930f4SArpith C. Jacob mlirModule->walk([&](LLVM::MetadataOp metadatas) { 7474a2930f4SArpith C. Jacob metadatas.walk([&](LLVM::AccessGroupMetadataOp op) { 7484a2930f4SArpith C. Jacob llvm::LLVMContext &ctx = llvmModule->getContext(); 7494a2930f4SArpith C. Jacob llvm::MDNode *accessGroup = llvm::MDNode::getDistinct(ctx, {}); 7504a2930f4SArpith C. Jacob accessGroupMetadataMapping.insert({op, accessGroup}); 7514a2930f4SArpith C. Jacob }); 7524a2930f4SArpith C. Jacob }); 7534a2930f4SArpith C. Jacob return success(); 7544a2930f4SArpith C. Jacob } 7554a2930f4SArpith C. Jacob 7564e393350SArpith C. Jacob void ModuleTranslation::setAccessGroupsMetadata(Operation *op, 7574e393350SArpith C. Jacob llvm::Instruction *inst) { 7584e393350SArpith C. Jacob auto accessGroups = 7594e393350SArpith C. Jacob op->getAttrOfType<ArrayAttr>(LLVMDialect::getAccessGroupsAttrName()); 7604e393350SArpith C. Jacob if (accessGroups && !accessGroups.empty()) { 7614e393350SArpith C. Jacob llvm::Module *module = inst->getModule(); 7624e393350SArpith C. Jacob SmallVector<llvm::Metadata *> metadatas; 7634e393350SArpith C. Jacob for (SymbolRefAttr accessGroupRef : 7644e393350SArpith C. Jacob accessGroups.getAsRange<SymbolRefAttr>()) 7654e393350SArpith C. Jacob metadatas.push_back(getAccessGroup(*op, accessGroupRef)); 7664e393350SArpith C. Jacob 7674e393350SArpith C. Jacob llvm::MDNode *unionMD = nullptr; 7684e393350SArpith C. Jacob if (metadatas.size() == 1) 7694e393350SArpith C. Jacob unionMD = llvm::cast<llvm::MDNode>(metadatas.front()); 7704e393350SArpith C. Jacob else if (metadatas.size() >= 2) 7714e393350SArpith C. Jacob unionMD = llvm::MDNode::get(module->getContext(), metadatas); 7724e393350SArpith C. Jacob 7734e393350SArpith C. Jacob inst->setMetadata(module->getMDKindID("llvm.access.group"), unionMD); 7744e393350SArpith C. Jacob } 7754e393350SArpith C. Jacob } 7764e393350SArpith C. Jacob 777d25e91d7STyler Augustine LogicalResult ModuleTranslation::createAliasScopeMetadata() { 778d25e91d7STyler Augustine mlirModule->walk([&](LLVM::MetadataOp metadatas) { 779d25e91d7STyler Augustine // Create the domains first, so they can be reference below in the scopes. 780d25e91d7STyler Augustine DenseMap<Operation *, llvm::MDNode *> aliasScopeDomainMetadataMapping; 781d25e91d7STyler Augustine metadatas.walk([&](LLVM::AliasScopeDomainMetadataOp op) { 782d25e91d7STyler Augustine llvm::LLVMContext &ctx = llvmModule->getContext(); 783d25e91d7STyler Augustine llvm::SmallVector<llvm::Metadata *, 2> operands; 784d25e91d7STyler Augustine operands.push_back({}); // Placeholder for self-reference 785d25e91d7STyler Augustine if (Optional<StringRef> description = op.description()) 786d25e91d7STyler Augustine operands.push_back(llvm::MDString::get(ctx, description.getValue())); 787d25e91d7STyler Augustine llvm::MDNode *domain = llvm::MDNode::get(ctx, operands); 788d25e91d7STyler Augustine domain->replaceOperandWith(0, domain); // Self-reference for uniqueness 789d25e91d7STyler Augustine aliasScopeDomainMetadataMapping.insert({op, domain}); 790d25e91d7STyler Augustine }); 791d25e91d7STyler Augustine 792d25e91d7STyler Augustine // Now create the scopes, referencing the domains created above. 793d25e91d7STyler Augustine metadatas.walk([&](LLVM::AliasScopeMetadataOp op) { 794d25e91d7STyler Augustine llvm::LLVMContext &ctx = llvmModule->getContext(); 795d25e91d7STyler Augustine assert(isa<LLVM::MetadataOp>(op->getParentOp())); 796d25e91d7STyler Augustine auto metadataOp = dyn_cast<LLVM::MetadataOp>(op->getParentOp()); 797d25e91d7STyler Augustine Operation *domainOp = 798d25e91d7STyler Augustine SymbolTable::lookupNearestSymbolFrom(metadataOp, op.domainAttr()); 799d25e91d7STyler Augustine llvm::MDNode *domain = aliasScopeDomainMetadataMapping.lookup(domainOp); 800d25e91d7STyler Augustine assert(domain && "Scope's domain should already be valid"); 801d25e91d7STyler Augustine llvm::SmallVector<llvm::Metadata *, 3> operands; 802d25e91d7STyler Augustine operands.push_back({}); // Placeholder for self-reference 803d25e91d7STyler Augustine operands.push_back(domain); 804d25e91d7STyler Augustine if (Optional<StringRef> description = op.description()) 805d25e91d7STyler Augustine operands.push_back(llvm::MDString::get(ctx, description.getValue())); 806d25e91d7STyler Augustine llvm::MDNode *scope = llvm::MDNode::get(ctx, operands); 807d25e91d7STyler Augustine scope->replaceOperandWith(0, scope); // Self-reference for uniqueness 808d25e91d7STyler Augustine aliasScopeMetadataMapping.insert({op, scope}); 809d25e91d7STyler Augustine }); 810d25e91d7STyler Augustine }); 811d25e91d7STyler Augustine return success(); 812d25e91d7STyler Augustine } 813d25e91d7STyler Augustine 814d25e91d7STyler Augustine llvm::MDNode * 815d25e91d7STyler Augustine ModuleTranslation::getAliasScope(Operation &opInst, 816d25e91d7STyler Augustine SymbolRefAttr aliasScopeRef) const { 817*41d4aa7dSChris Lattner StringAttr metadataName = aliasScopeRef.getRootReference(); 818*41d4aa7dSChris Lattner StringAttr scopeName = aliasScopeRef.getLeafReference(); 819d25e91d7STyler Augustine auto metadataOp = SymbolTable::lookupNearestSymbolFrom<LLVM::MetadataOp>( 820d25e91d7STyler Augustine opInst.getParentOp(), metadataName); 821d25e91d7STyler Augustine Operation *aliasScopeOp = 822d25e91d7STyler Augustine SymbolTable::lookupNearestSymbolFrom(metadataOp, scopeName); 823d25e91d7STyler Augustine return aliasScopeMetadataMapping.lookup(aliasScopeOp); 824d25e91d7STyler Augustine } 825d25e91d7STyler Augustine 826d25e91d7STyler Augustine void ModuleTranslation::setAliasScopeMetadata(Operation *op, 827d25e91d7STyler Augustine llvm::Instruction *inst) { 828d25e91d7STyler Augustine auto populateScopeMetadata = [this, op, inst](StringRef attrName, 829d25e91d7STyler Augustine StringRef llvmMetadataName) { 830d25e91d7STyler Augustine auto scopes = op->getAttrOfType<ArrayAttr>(attrName); 831d25e91d7STyler Augustine if (!scopes || scopes.empty()) 832d25e91d7STyler Augustine return; 833d25e91d7STyler Augustine llvm::Module *module = inst->getModule(); 834d25e91d7STyler Augustine SmallVector<llvm::Metadata *> scopeMDs; 835d25e91d7STyler Augustine for (SymbolRefAttr scopeRef : scopes.getAsRange<SymbolRefAttr>()) 836d25e91d7STyler Augustine scopeMDs.push_back(getAliasScope(*op, scopeRef)); 837d25e91d7STyler Augustine llvm::MDNode *unionMD = nullptr; 838d25e91d7STyler Augustine if (scopeMDs.size() == 1) 839d25e91d7STyler Augustine unionMD = llvm::cast<llvm::MDNode>(scopeMDs.front()); 840d25e91d7STyler Augustine else if (scopeMDs.size() >= 2) 841d25e91d7STyler Augustine unionMD = llvm::MDNode::get(module->getContext(), scopeMDs); 842d25e91d7STyler Augustine inst->setMetadata(module->getMDKindID(llvmMetadataName), unionMD); 843d25e91d7STyler Augustine }; 844d25e91d7STyler Augustine 845d25e91d7STyler Augustine populateScopeMetadata(LLVMDialect::getAliasScopesAttrName(), "alias.scope"); 846d25e91d7STyler Augustine populateScopeMetadata(LLVMDialect::getNoAliasScopesAttrName(), "noalias"); 847d25e91d7STyler Augustine } 848d25e91d7STyler Augustine 849c69c9e0fSAlex Zinenko llvm::Type *ModuleTranslation::convertType(Type type) { 850b2ab375dSAlex Zinenko return typeTranslator.translateType(type); 851aec38c61SAlex Zinenko } 852aec38c61SAlex Zinenko 853efadb6b8SAlex Zinenko /// A helper to look up remapped operands in the value remapping table.` 854efadb6b8SAlex Zinenko SmallVector<llvm::Value *, 8> 855efadb6b8SAlex Zinenko ModuleTranslation::lookupValues(ValueRange values) { 856efadb6b8SAlex Zinenko SmallVector<llvm::Value *, 8> remapped; 857efadb6b8SAlex Zinenko remapped.reserve(values.size()); 8580881a4f1SAlex Zinenko for (Value v : values) 8590881a4f1SAlex Zinenko remapped.push_back(lookupValue(v)); 860efadb6b8SAlex Zinenko return remapped; 861efadb6b8SAlex Zinenko } 862efadb6b8SAlex Zinenko 86366900b3eSAlex Zinenko const llvm::DILocation * 86466900b3eSAlex Zinenko ModuleTranslation::translateLoc(Location loc, llvm::DILocalScope *scope) { 86566900b3eSAlex Zinenko return debugTranslation->translateLoc(loc, scope); 86666900b3eSAlex Zinenko } 86766900b3eSAlex Zinenko 868176379e0SAlex Zinenko llvm::NamedMDNode * 869176379e0SAlex Zinenko ModuleTranslation::getOrInsertNamedModuleMetadata(StringRef name) { 870176379e0SAlex Zinenko return llvmModule->getOrInsertNamedMetadata(name); 871176379e0SAlex Zinenko } 872176379e0SAlex Zinenko 87372d013ddSAlex Zinenko void ModuleTranslation::StackFrame::anchor() {} 87472d013ddSAlex Zinenko 875ce8f10d6SAlex Zinenko static std::unique_ptr<llvm::Module> 876ce8f10d6SAlex Zinenko prepareLLVMModule(Operation *m, llvm::LLVMContext &llvmContext, 877ce8f10d6SAlex Zinenko StringRef name) { 878f9dc2b70SMehdi Amini m->getContext()->getOrLoadDialect<LLVM::LLVMDialect>(); 879db1c197bSAlex Zinenko auto llvmModule = std::make_unique<llvm::Module>(name, llvmContext); 880168213f9SAlex Zinenko if (auto dataLayoutAttr = 881168213f9SAlex Zinenko m->getAttr(LLVM::LLVMDialect::getDataLayoutAttrName())) 882168213f9SAlex Zinenko llvmModule->setDataLayout(dataLayoutAttr.cast<StringAttr>().getValue()); 8835dd5a083SNicolas Vasilache if (auto targetTripleAttr = 8845dd5a083SNicolas Vasilache m->getAttr(LLVM::LLVMDialect::getTargetTripleAttrName())) 8855dd5a083SNicolas Vasilache llvmModule->setTargetTriple(targetTripleAttr.cast<StringAttr>().getValue()); 8865d7231d8SStephan Herhut 8875d7231d8SStephan Herhut // Inject declarations for `malloc` and `free` functions that can be used in 8885d7231d8SStephan Herhut // memref allocation/deallocation coming from standard ops lowering. 889db1c197bSAlex Zinenko llvm::IRBuilder<> builder(llvmContext); 8905d7231d8SStephan Herhut llvmModule->getOrInsertFunction("malloc", builder.getInt8PtrTy(), 8915d7231d8SStephan Herhut builder.getInt64Ty()); 8925d7231d8SStephan Herhut llvmModule->getOrInsertFunction("free", builder.getVoidTy(), 8935d7231d8SStephan Herhut builder.getInt8PtrTy()); 8945d7231d8SStephan Herhut 8955d7231d8SStephan Herhut return llvmModule; 8965d7231d8SStephan Herhut } 897ce8f10d6SAlex Zinenko 898ce8f10d6SAlex Zinenko std::unique_ptr<llvm::Module> 899ce8f10d6SAlex Zinenko mlir::translateModuleToLLVMIR(Operation *module, llvm::LLVMContext &llvmContext, 900ce8f10d6SAlex Zinenko StringRef name) { 901ce8f10d6SAlex Zinenko if (!satisfiesLLVMModule(module)) 902ce8f10d6SAlex Zinenko return nullptr; 903ce8f10d6SAlex Zinenko if (failed(checkSupportedModuleOps(module))) 904ce8f10d6SAlex Zinenko return nullptr; 905ce8f10d6SAlex Zinenko std::unique_ptr<llvm::Module> llvmModule = 906ce8f10d6SAlex Zinenko prepareLLVMModule(module, llvmContext, name); 907ce8f10d6SAlex Zinenko 908ce8f10d6SAlex Zinenko LLVM::ensureDistinctSuccessors(module); 909ce8f10d6SAlex Zinenko 910ce8f10d6SAlex Zinenko ModuleTranslation translator(module, std::move(llvmModule)); 911ce8f10d6SAlex Zinenko if (failed(translator.convertFunctionSignatures())) 912ce8f10d6SAlex Zinenko return nullptr; 913ce8f10d6SAlex Zinenko if (failed(translator.convertGlobals())) 914ce8f10d6SAlex Zinenko return nullptr; 9154a2930f4SArpith C. Jacob if (failed(translator.createAccessGroupMetadata())) 9164a2930f4SArpith C. Jacob return nullptr; 917d25e91d7STyler Augustine if (failed(translator.createAliasScopeMetadata())) 918d25e91d7STyler Augustine return nullptr; 919ce8f10d6SAlex Zinenko if (failed(translator.convertFunctions())) 920ce8f10d6SAlex Zinenko return nullptr; 921ce8f10d6SAlex Zinenko if (llvm::verifyModule(*translator.llvmModule, &llvm::errs())) 922ce8f10d6SAlex Zinenko return nullptr; 923ce8f10d6SAlex Zinenko 924ce8f10d6SAlex Zinenko return std::move(translator.llvmModule); 925ce8f10d6SAlex Zinenko } 926