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" 1892a295ebSKiran Chandramohan #include "mlir/Dialect/OpenMP/OpenMPDialect.h" 195d7231d8SStephan Herhut #include "mlir/IR/Attributes.h" 205d7231d8SStephan Herhut #include "mlir/IR/Module.h" 21a4a42160SAlex Zinenko #include "mlir/IR/StandardTypes.h" 225d7231d8SStephan Herhut #include "mlir/Support/LLVM.h" 23ebf190fcSRiver Riddle #include "llvm/ADT/TypeSwitch.h" 245d7231d8SStephan Herhut 255d7231d8SStephan Herhut #include "llvm/ADT/SetVector.h" 2692a295ebSKiran Chandramohan #include "llvm/Frontend/OpenMP/OMPIRBuilder.h" 275d7231d8SStephan Herhut #include "llvm/IR/BasicBlock.h" 285d7231d8SStephan Herhut #include "llvm/IR/Constants.h" 295d7231d8SStephan Herhut #include "llvm/IR/DerivedTypes.h" 305d7231d8SStephan Herhut #include "llvm/IR/IRBuilder.h" 315d7231d8SStephan Herhut #include "llvm/IR/LLVMContext.h" 325d7231d8SStephan Herhut #include "llvm/IR/Module.h" 335d7231d8SStephan Herhut #include "llvm/Transforms/Utils/Cloning.h" 345d7231d8SStephan Herhut 352666b973SRiver Riddle using namespace mlir; 362666b973SRiver Riddle using namespace mlir::LLVM; 37c33d6970SRiver Riddle using namespace mlir::LLVM::detail; 385d7231d8SStephan Herhut 39eb67bd78SAlex Zinenko #include "mlir/Dialect/LLVMIR/LLVMConversionEnumsToLLVM.inc" 40eb67bd78SAlex Zinenko 41a922e231SAlex Zinenko /// Builds a constant of a sequential LLVM type `type`, potentially containing 42a922e231SAlex Zinenko /// other sequential types recursively, from the individual constant values 43a922e231SAlex Zinenko /// provided in `constants`. `shape` contains the number of elements in nested 44a922e231SAlex Zinenko /// sequential types. Reports errors at `loc` and returns nullptr on error. 45a4a42160SAlex Zinenko static llvm::Constant * 46a4a42160SAlex Zinenko buildSequentialConstant(ArrayRef<llvm::Constant *> &constants, 47a4a42160SAlex Zinenko ArrayRef<int64_t> shape, llvm::Type *type, 48a4a42160SAlex Zinenko Location loc) { 49a4a42160SAlex Zinenko if (shape.empty()) { 50a4a42160SAlex Zinenko llvm::Constant *result = constants.front(); 51a4a42160SAlex Zinenko constants = constants.drop_front(); 52a4a42160SAlex Zinenko return result; 53a4a42160SAlex Zinenko } 54a4a42160SAlex Zinenko 5568b03aeeSEli Friedman llvm::Type *elementType; 5668b03aeeSEli Friedman if (auto *arrayTy = dyn_cast<llvm::ArrayType>(type)) { 5768b03aeeSEli Friedman elementType = arrayTy->getElementType(); 5868b03aeeSEli Friedman } else if (auto *vectorTy = dyn_cast<llvm::VectorType>(type)) { 5968b03aeeSEli Friedman elementType = vectorTy->getElementType(); 6068b03aeeSEli Friedman } else { 61a4a42160SAlex Zinenko emitError(loc) << "expected sequential LLVM types wrapping a scalar"; 62a4a42160SAlex Zinenko return nullptr; 63a4a42160SAlex Zinenko } 64a4a42160SAlex Zinenko 65a4a42160SAlex Zinenko SmallVector<llvm::Constant *, 8> nested; 66a4a42160SAlex Zinenko nested.reserve(shape.front()); 67a4a42160SAlex Zinenko for (int64_t i = 0; i < shape.front(); ++i) { 68a4a42160SAlex Zinenko nested.push_back(buildSequentialConstant(constants, shape.drop_front(), 69a4a42160SAlex Zinenko elementType, loc)); 70a4a42160SAlex Zinenko if (!nested.back()) 71a4a42160SAlex Zinenko return nullptr; 72a4a42160SAlex Zinenko } 73a4a42160SAlex Zinenko 74a4a42160SAlex Zinenko if (shape.size() == 1 && type->isVectorTy()) 75a4a42160SAlex Zinenko return llvm::ConstantVector::get(nested); 76a4a42160SAlex Zinenko return llvm::ConstantArray::get( 77a4a42160SAlex Zinenko llvm::ArrayType::get(elementType, shape.front()), nested); 78a4a42160SAlex Zinenko } 79a4a42160SAlex Zinenko 80fc817b09SKazuaki Ishizaki /// Returns the first non-sequential type nested in sequential types. 81a4a42160SAlex Zinenko static llvm::Type *getInnermostElementType(llvm::Type *type) { 8268b03aeeSEli Friedman do { 8368b03aeeSEli Friedman if (auto *arrayTy = dyn_cast<llvm::ArrayType>(type)) { 8468b03aeeSEli Friedman type = arrayTy->getElementType(); 8568b03aeeSEli Friedman } else if (auto *vectorTy = dyn_cast<llvm::VectorType>(type)) { 8668b03aeeSEli Friedman type = vectorTy->getElementType(); 8768b03aeeSEli Friedman } else { 88a4a42160SAlex Zinenko return type; 89a4a42160SAlex Zinenko } 9068b03aeeSEli Friedman } while (1); 9168b03aeeSEli Friedman } 92a4a42160SAlex Zinenko 932666b973SRiver Riddle /// Create an LLVM IR constant of `llvmType` from the MLIR attribute `attr`. 942666b973SRiver Riddle /// This currently supports integer, floating point, splat and dense element 952666b973SRiver Riddle /// attributes and combinations thereof. In case of error, report it to `loc` 962666b973SRiver Riddle /// and return nullptr. 975d7231d8SStephan Herhut llvm::Constant *ModuleTranslation::getLLVMConstant(llvm::Type *llvmType, 985d7231d8SStephan Herhut Attribute attr, 995d7231d8SStephan Herhut Location loc) { 10033a3a91bSChristian Sigg if (!attr) 10133a3a91bSChristian Sigg return llvm::UndefValue::get(llvmType); 102a4a42160SAlex Zinenko if (llvmType->isStructTy()) { 103a4a42160SAlex Zinenko emitError(loc, "struct types are not supported in constants"); 104a4a42160SAlex Zinenko return nullptr; 105a4a42160SAlex Zinenko } 106ac9d742bSStephan Herhut // For integer types, we allow a mismatch in sizes as the index type in 107ac9d742bSStephan Herhut // MLIR might have a different size than the index type in the LLVM module. 1085d7231d8SStephan Herhut if (auto intAttr = attr.dyn_cast<IntegerAttr>()) 109ac9d742bSStephan Herhut return llvm::ConstantInt::get( 110ac9d742bSStephan Herhut llvmType, 111ac9d742bSStephan Herhut intAttr.getValue().sextOrTrunc(llvmType->getIntegerBitWidth())); 11218fc42faSAhmed Taei if (auto boolAttr = attr.dyn_cast<BoolAttr>()) 11318fc42faSAhmed Taei return llvm::ConstantInt::get(llvmType, boolAttr.getValue()); 1145d7231d8SStephan Herhut if (auto floatAttr = attr.dyn_cast<FloatAttr>()) 1155d7231d8SStephan Herhut return llvm::ConstantFP::get(llvmType, floatAttr.getValue()); 1169b9c647cSRiver Riddle if (auto funcAttr = attr.dyn_cast<FlatSymbolRefAttr>()) 117ff77397fSShraiysh Vaishay return llvm::ConstantExpr::getBitCast( 118ff77397fSShraiysh Vaishay functionMapping.lookup(funcAttr.getValue()), llvmType); 1195d7231d8SStephan Herhut if (auto splatAttr = attr.dyn_cast<SplatElementsAttr>()) { 12068b03aeeSEli Friedman llvm::Type *elementType; 12168b03aeeSEli Friedman uint64_t numElements; 12268b03aeeSEli Friedman if (auto *arrayTy = dyn_cast<llvm::ArrayType>(llvmType)) { 12368b03aeeSEli Friedman elementType = arrayTy->getElementType(); 12468b03aeeSEli Friedman numElements = arrayTy->getNumElements(); 12568b03aeeSEli Friedman } else { 12668b03aeeSEli Friedman auto *vectorTy = cast<llvm::VectorType>(llvmType); 12768b03aeeSEli Friedman elementType = vectorTy->getElementType(); 12868b03aeeSEli Friedman numElements = vectorTy->getNumElements(); 12968b03aeeSEli Friedman } 130d6ea8ff0SAlex Zinenko // Splat value is a scalar. Extract it only if the element type is not 131d6ea8ff0SAlex Zinenko // another sequence type. The recursion terminates because each step removes 132d6ea8ff0SAlex Zinenko // one outer sequential type. 13368b03aeeSEli Friedman bool elementTypeSequential = 13468b03aeeSEli Friedman isa<llvm::ArrayType>(elementType) || isa<llvm::VectorType>(elementType); 135d6ea8ff0SAlex Zinenko llvm::Constant *child = getLLVMConstant( 136d6ea8ff0SAlex Zinenko elementType, 13768b03aeeSEli Friedman elementTypeSequential ? splatAttr : splatAttr.getSplatValue(), loc); 138a4a42160SAlex Zinenko if (!child) 139a4a42160SAlex Zinenko return nullptr; 1402f13df13SMLIR Team if (llvmType->isVectorTy()) 141396a42d9SRiver Riddle return llvm::ConstantVector::getSplat( 142396a42d9SRiver Riddle llvm::ElementCount(numElements, /*Scalable=*/false), child); 1432f13df13SMLIR Team if (llvmType->isArrayTy()) { 144ac9d742bSStephan Herhut auto *arrayType = llvm::ArrayType::get(elementType, numElements); 1452f13df13SMLIR Team SmallVector<llvm::Constant *, 8> constants(numElements, child); 1462f13df13SMLIR Team return llvm::ConstantArray::get(arrayType, constants); 1472f13df13SMLIR Team } 1485d7231d8SStephan Herhut } 149a4a42160SAlex Zinenko 150d906f84bSRiver Riddle if (auto elementsAttr = attr.dyn_cast<ElementsAttr>()) { 151a4a42160SAlex Zinenko assert(elementsAttr.getType().hasStaticShape()); 152a4a42160SAlex Zinenko assert(elementsAttr.getNumElements() != 0 && 153a4a42160SAlex Zinenko "unexpected empty elements attribute"); 154a4a42160SAlex Zinenko assert(!elementsAttr.getType().getShape().empty() && 155a4a42160SAlex Zinenko "unexpected empty elements attribute shape"); 156a4a42160SAlex Zinenko 1575d7231d8SStephan Herhut SmallVector<llvm::Constant *, 8> constants; 158a4a42160SAlex Zinenko constants.reserve(elementsAttr.getNumElements()); 159a4a42160SAlex Zinenko llvm::Type *innermostType = getInnermostElementType(llvmType); 160d906f84bSRiver Riddle for (auto n : elementsAttr.getValues<Attribute>()) { 161a4a42160SAlex Zinenko constants.push_back(getLLVMConstant(innermostType, n, loc)); 1625d7231d8SStephan Herhut if (!constants.back()) 1635d7231d8SStephan Herhut return nullptr; 1645d7231d8SStephan Herhut } 165a4a42160SAlex Zinenko ArrayRef<llvm::Constant *> constantsRef = constants; 166a4a42160SAlex Zinenko llvm::Constant *result = buildSequentialConstant( 167a4a42160SAlex Zinenko constantsRef, elementsAttr.getType().getShape(), llvmType, loc); 168a4a42160SAlex Zinenko assert(constantsRef.empty() && "did not consume all elemental constants"); 169a4a42160SAlex Zinenko return result; 1702f13df13SMLIR Team } 171a4a42160SAlex Zinenko 172cb348dffSStephan Herhut if (auto stringAttr = attr.dyn_cast<StringAttr>()) { 173cb348dffSStephan Herhut return llvm::ConstantDataArray::get( 174cb348dffSStephan Herhut llvmModule->getContext(), ArrayRef<char>{stringAttr.getValue().data(), 175cb348dffSStephan Herhut stringAttr.getValue().size()}); 176cb348dffSStephan Herhut } 177a4c3a645SRiver Riddle emitError(loc, "unsupported constant value"); 1785d7231d8SStephan Herhut return nullptr; 1795d7231d8SStephan Herhut } 1805d7231d8SStephan Herhut 1812666b973SRiver Riddle /// Convert MLIR integer comparison predicate to LLVM IR comparison predicate. 182ec82e1c9SAlex Zinenko static llvm::CmpInst::Predicate getLLVMCmpPredicate(ICmpPredicate p) { 1835d7231d8SStephan Herhut switch (p) { 184ec82e1c9SAlex Zinenko case LLVM::ICmpPredicate::eq: 1855d7231d8SStephan Herhut return llvm::CmpInst::Predicate::ICMP_EQ; 186ec82e1c9SAlex Zinenko case LLVM::ICmpPredicate::ne: 1875d7231d8SStephan Herhut return llvm::CmpInst::Predicate::ICMP_NE; 188ec82e1c9SAlex Zinenko case LLVM::ICmpPredicate::slt: 1895d7231d8SStephan Herhut return llvm::CmpInst::Predicate::ICMP_SLT; 190ec82e1c9SAlex Zinenko case LLVM::ICmpPredicate::sle: 1915d7231d8SStephan Herhut return llvm::CmpInst::Predicate::ICMP_SLE; 192ec82e1c9SAlex Zinenko case LLVM::ICmpPredicate::sgt: 1935d7231d8SStephan Herhut return llvm::CmpInst::Predicate::ICMP_SGT; 194ec82e1c9SAlex Zinenko case LLVM::ICmpPredicate::sge: 1955d7231d8SStephan Herhut return llvm::CmpInst::Predicate::ICMP_SGE; 196ec82e1c9SAlex Zinenko case LLVM::ICmpPredicate::ult: 1975d7231d8SStephan Herhut return llvm::CmpInst::Predicate::ICMP_ULT; 198ec82e1c9SAlex Zinenko case LLVM::ICmpPredicate::ule: 1995d7231d8SStephan Herhut return llvm::CmpInst::Predicate::ICMP_ULE; 200ec82e1c9SAlex Zinenko case LLVM::ICmpPredicate::ugt: 2015d7231d8SStephan Herhut return llvm::CmpInst::Predicate::ICMP_UGT; 202ec82e1c9SAlex Zinenko case LLVM::ICmpPredicate::uge: 2035d7231d8SStephan Herhut return llvm::CmpInst::Predicate::ICMP_UGE; 2045d7231d8SStephan Herhut } 205e6365f3dSJacques Pienaar llvm_unreachable("incorrect comparison predicate"); 2065d7231d8SStephan Herhut } 2075d7231d8SStephan Herhut 20848fdc8d7SNagy Mostafa static llvm::CmpInst::Predicate getLLVMCmpPredicate(FCmpPredicate p) { 20948fdc8d7SNagy Mostafa switch (p) { 21048fdc8d7SNagy Mostafa case LLVM::FCmpPredicate::_false: 21148fdc8d7SNagy Mostafa return llvm::CmpInst::Predicate::FCMP_FALSE; 21248fdc8d7SNagy Mostafa case LLVM::FCmpPredicate::oeq: 21348fdc8d7SNagy Mostafa return llvm::CmpInst::Predicate::FCMP_OEQ; 21448fdc8d7SNagy Mostafa case LLVM::FCmpPredicate::ogt: 21548fdc8d7SNagy Mostafa return llvm::CmpInst::Predicate::FCMP_OGT; 21648fdc8d7SNagy Mostafa case LLVM::FCmpPredicate::oge: 21748fdc8d7SNagy Mostafa return llvm::CmpInst::Predicate::FCMP_OGE; 21848fdc8d7SNagy Mostafa case LLVM::FCmpPredicate::olt: 21948fdc8d7SNagy Mostafa return llvm::CmpInst::Predicate::FCMP_OLT; 22048fdc8d7SNagy Mostafa case LLVM::FCmpPredicate::ole: 22148fdc8d7SNagy Mostafa return llvm::CmpInst::Predicate::FCMP_OLE; 22248fdc8d7SNagy Mostafa case LLVM::FCmpPredicate::one: 22348fdc8d7SNagy Mostafa return llvm::CmpInst::Predicate::FCMP_ONE; 22448fdc8d7SNagy Mostafa case LLVM::FCmpPredicate::ord: 22548fdc8d7SNagy Mostafa return llvm::CmpInst::Predicate::FCMP_ORD; 22648fdc8d7SNagy Mostafa case LLVM::FCmpPredicate::ueq: 22748fdc8d7SNagy Mostafa return llvm::CmpInst::Predicate::FCMP_UEQ; 22848fdc8d7SNagy Mostafa case LLVM::FCmpPredicate::ugt: 22948fdc8d7SNagy Mostafa return llvm::CmpInst::Predicate::FCMP_UGT; 23048fdc8d7SNagy Mostafa case LLVM::FCmpPredicate::uge: 23148fdc8d7SNagy Mostafa return llvm::CmpInst::Predicate::FCMP_UGE; 23248fdc8d7SNagy Mostafa case LLVM::FCmpPredicate::ult: 23348fdc8d7SNagy Mostafa return llvm::CmpInst::Predicate::FCMP_ULT; 23448fdc8d7SNagy Mostafa case LLVM::FCmpPredicate::ule: 23548fdc8d7SNagy Mostafa return llvm::CmpInst::Predicate::FCMP_ULE; 23648fdc8d7SNagy Mostafa case LLVM::FCmpPredicate::une: 23748fdc8d7SNagy Mostafa return llvm::CmpInst::Predicate::FCMP_UNE; 23848fdc8d7SNagy Mostafa case LLVM::FCmpPredicate::uno: 23948fdc8d7SNagy Mostafa return llvm::CmpInst::Predicate::FCMP_UNO; 24048fdc8d7SNagy Mostafa case LLVM::FCmpPredicate::_true: 24148fdc8d7SNagy Mostafa return llvm::CmpInst::Predicate::FCMP_TRUE; 24248fdc8d7SNagy Mostafa } 243e6365f3dSJacques Pienaar llvm_unreachable("incorrect comparison predicate"); 24448fdc8d7SNagy Mostafa } 24548fdc8d7SNagy Mostafa 24660a0c612SFrank Laub static llvm::AtomicRMWInst::BinOp getLLVMAtomicBinOp(AtomicBinOp op) { 24760a0c612SFrank Laub switch (op) { 24860a0c612SFrank Laub case LLVM::AtomicBinOp::xchg: 24960a0c612SFrank Laub return llvm::AtomicRMWInst::BinOp::Xchg; 25060a0c612SFrank Laub case LLVM::AtomicBinOp::add: 25160a0c612SFrank Laub return llvm::AtomicRMWInst::BinOp::Add; 25260a0c612SFrank Laub case LLVM::AtomicBinOp::sub: 25360a0c612SFrank Laub return llvm::AtomicRMWInst::BinOp::Sub; 25460a0c612SFrank Laub case LLVM::AtomicBinOp::_and: 25560a0c612SFrank Laub return llvm::AtomicRMWInst::BinOp::And; 25660a0c612SFrank Laub case LLVM::AtomicBinOp::nand: 25760a0c612SFrank Laub return llvm::AtomicRMWInst::BinOp::Nand; 25860a0c612SFrank Laub case LLVM::AtomicBinOp::_or: 25960a0c612SFrank Laub return llvm::AtomicRMWInst::BinOp::Or; 26060a0c612SFrank Laub case LLVM::AtomicBinOp::_xor: 26160a0c612SFrank Laub return llvm::AtomicRMWInst::BinOp::Xor; 26260a0c612SFrank Laub case LLVM::AtomicBinOp::max: 26360a0c612SFrank Laub return llvm::AtomicRMWInst::BinOp::Max; 26460a0c612SFrank Laub case LLVM::AtomicBinOp::min: 26560a0c612SFrank Laub return llvm::AtomicRMWInst::BinOp::Min; 26660a0c612SFrank Laub case LLVM::AtomicBinOp::umax: 26760a0c612SFrank Laub return llvm::AtomicRMWInst::BinOp::UMax; 26860a0c612SFrank Laub case LLVM::AtomicBinOp::umin: 26960a0c612SFrank Laub return llvm::AtomicRMWInst::BinOp::UMin; 27060a0c612SFrank Laub case LLVM::AtomicBinOp::fadd: 27160a0c612SFrank Laub return llvm::AtomicRMWInst::BinOp::FAdd; 27260a0c612SFrank Laub case LLVM::AtomicBinOp::fsub: 27360a0c612SFrank Laub return llvm::AtomicRMWInst::BinOp::FSub; 27460a0c612SFrank Laub } 27560a0c612SFrank Laub llvm_unreachable("incorrect atomic binary operator"); 27660a0c612SFrank Laub } 27760a0c612SFrank Laub 27860a0c612SFrank Laub static llvm::AtomicOrdering getLLVMAtomicOrdering(AtomicOrdering ordering) { 27960a0c612SFrank Laub switch (ordering) { 28060a0c612SFrank Laub case LLVM::AtomicOrdering::not_atomic: 28160a0c612SFrank Laub return llvm::AtomicOrdering::NotAtomic; 28260a0c612SFrank Laub case LLVM::AtomicOrdering::unordered: 28360a0c612SFrank Laub return llvm::AtomicOrdering::Unordered; 28460a0c612SFrank Laub case LLVM::AtomicOrdering::monotonic: 28560a0c612SFrank Laub return llvm::AtomicOrdering::Monotonic; 28660a0c612SFrank Laub case LLVM::AtomicOrdering::acquire: 28760a0c612SFrank Laub return llvm::AtomicOrdering::Acquire; 28860a0c612SFrank Laub case LLVM::AtomicOrdering::release: 28960a0c612SFrank Laub return llvm::AtomicOrdering::Release; 29060a0c612SFrank Laub case LLVM::AtomicOrdering::acq_rel: 29160a0c612SFrank Laub return llvm::AtomicOrdering::AcquireRelease; 29260a0c612SFrank Laub case LLVM::AtomicOrdering::seq_cst: 29360a0c612SFrank Laub return llvm::AtomicOrdering::SequentiallyConsistent; 29460a0c612SFrank Laub } 29560a0c612SFrank Laub llvm_unreachable("incorrect atomic ordering"); 29660a0c612SFrank Laub } 29760a0c612SFrank Laub 298c33d6970SRiver Riddle ModuleTranslation::ModuleTranslation(Operation *module, 299c33d6970SRiver Riddle std::unique_ptr<llvm::Module> llvmModule) 300c33d6970SRiver Riddle : mlirModule(module), llvmModule(std::move(llvmModule)), 301c33d6970SRiver Riddle debugTranslation( 30292a295ebSKiran Chandramohan std::make_unique<DebugTranslation>(module, *this->llvmModule)), 30392a295ebSKiran Chandramohan ompDialect( 30469040d5bSStephan Herhut module->getContext()->getRegisteredDialect<omp::OpenMPDialect>()), 30569040d5bSStephan Herhut llvmDialect(module->getContext()->getRegisteredDialect<LLVMDialect>()) { 306c33d6970SRiver Riddle assert(satisfiesLLVMModule(mlirModule) && 307c33d6970SRiver Riddle "mlirModule should honor LLVM's module semantics."); 308c33d6970SRiver Riddle } 309c33d6970SRiver Riddle ModuleTranslation::~ModuleTranslation() {} 310c33d6970SRiver Riddle 3117ecee63eSKiran Kumar T P /// Given an OpenMP MLIR operation, create the corresponding LLVM IR 3127ecee63eSKiran Kumar T P /// (including OpenMP runtime calls). 3137ecee63eSKiran Kumar T P LogicalResult 3147ecee63eSKiran Kumar T P ModuleTranslation::convertOmpOperation(Operation &opInst, 3157ecee63eSKiran Kumar T P llvm::IRBuilder<> &builder) { 3167ecee63eSKiran Kumar T P if (!ompBuilder) { 3177ecee63eSKiran Kumar T P ompBuilder = std::make_unique<llvm::OpenMPIRBuilder>(*llvmModule); 3187ecee63eSKiran Kumar T P ompBuilder->initialize(); 3197ecee63eSKiran Kumar T P } 320ebf190fcSRiver Riddle return llvm::TypeSwitch<Operation *, LogicalResult>(&opInst) 3217ecee63eSKiran Kumar T P .Case([&](omp::BarrierOp) { 3227ecee63eSKiran Kumar T P ompBuilder->CreateBarrier(builder.saveIP(), llvm::omp::OMPD_barrier); 3237ecee63eSKiran Kumar T P return success(); 3247ecee63eSKiran Kumar T P }) 3257ecee63eSKiran Kumar T P .Case([&](omp::TaskwaitOp) { 3267ecee63eSKiran Kumar T P ompBuilder->CreateTaskwait(builder.saveIP()); 3277ecee63eSKiran Kumar T P return success(); 3287ecee63eSKiran Kumar T P }) 3297ecee63eSKiran Kumar T P .Case([&](omp::TaskyieldOp) { 3307ecee63eSKiran Kumar T P ompBuilder->CreateTaskyield(builder.saveIP()); 3317ecee63eSKiran Kumar T P return success(); 3327ecee63eSKiran Kumar T P }) 333*fa8fc9ffSKiran Kumar T P .Case([&](omp::FlushOp) { 334*fa8fc9ffSKiran Kumar T P // No support in Openmp runtime funciton (__kmpc_flush) to accept 335*fa8fc9ffSKiran Kumar T P // the argument list. 336*fa8fc9ffSKiran Kumar T P // OpenMP standard states the following: 337*fa8fc9ffSKiran Kumar T P // "An implementation may implement a flush with a list by ignoring 338*fa8fc9ffSKiran Kumar T P // the list, and treating it the same as a flush without a list." 339*fa8fc9ffSKiran Kumar T P // 340*fa8fc9ffSKiran Kumar T P // The argument list is discarded so that, flush with a list is treated 341*fa8fc9ffSKiran Kumar T P // same as a flush without a list. 342*fa8fc9ffSKiran Kumar T P ompBuilder->CreateFlush(builder.saveIP()); 343*fa8fc9ffSKiran Kumar T P return success(); 344*fa8fc9ffSKiran Kumar T P }) 3457ecee63eSKiran Kumar T P .Default([&](Operation *inst) { 3467ecee63eSKiran Kumar T P return inst->emitError("unsupported OpenMP operation: ") 3477ecee63eSKiran Kumar T P << inst->getName(); 3487ecee63eSKiran Kumar T P }); 3497ecee63eSKiran Kumar T P } 3507ecee63eSKiran Kumar T P 3512666b973SRiver Riddle /// Given a single MLIR operation, create the corresponding LLVM IR operation 3522666b973SRiver Riddle /// using the `builder`. LLVM IR Builder does not have a generic interface so 3532666b973SRiver Riddle /// this has to be a long chain of `if`s calling different functions with a 3542666b973SRiver Riddle /// different number of arguments. 355baa1ec22SAlex Zinenko LogicalResult ModuleTranslation::convertOperation(Operation &opInst, 3565d7231d8SStephan Herhut llvm::IRBuilder<> &builder) { 3575d7231d8SStephan Herhut auto extractPosition = [](ArrayAttr attr) { 3585d7231d8SStephan Herhut SmallVector<unsigned, 4> position; 3595d7231d8SStephan Herhut position.reserve(attr.size()); 3605d7231d8SStephan Herhut for (Attribute v : attr) 3615d7231d8SStephan Herhut position.push_back(v.cast<IntegerAttr>().getValue().getZExtValue()); 3625d7231d8SStephan Herhut return position; 3635d7231d8SStephan Herhut }; 3645d7231d8SStephan Herhut 365ba0fa925SRiver Riddle #include "mlir/Dialect/LLVMIR/LLVMConversions.inc" 3665d7231d8SStephan Herhut 3675d7231d8SStephan Herhut // Emit function calls. If the "callee" attribute is present, this is a 3685d7231d8SStephan Herhut // direct function call and we also need to look up the remapped function 3695d7231d8SStephan Herhut // itself. Otherwise, this is an indirect call and the callee is the first 3705d7231d8SStephan Herhut // operand, look it up as a normal value. Return the llvm::Value representing 3715d7231d8SStephan Herhut // the function result, which may be of llvm::VoidTy type. 3725d7231d8SStephan Herhut auto convertCall = [this, &builder](Operation &op) -> llvm::Value * { 3735d7231d8SStephan Herhut auto operands = lookupValues(op.getOperands()); 3745d7231d8SStephan Herhut ArrayRef<llvm::Value *> operandsRef(operands); 3759b9c647cSRiver Riddle if (auto attr = op.getAttrOfType<FlatSymbolRefAttr>("callee")) { 3765d7231d8SStephan Herhut return builder.CreateCall(functionMapping.lookup(attr.getValue()), 3775d7231d8SStephan Herhut operandsRef); 3785d7231d8SStephan Herhut } else { 379133049d0SEli Friedman auto *calleePtrType = 380133049d0SEli Friedman cast<llvm::PointerType>(operandsRef.front()->getType()); 381133049d0SEli Friedman auto *calleeType = 382133049d0SEli Friedman cast<llvm::FunctionType>(calleePtrType->getElementType()); 383133049d0SEli Friedman return builder.CreateCall(calleeType, operandsRef.front(), 384133049d0SEli Friedman operandsRef.drop_front()); 3855d7231d8SStephan Herhut } 3865d7231d8SStephan Herhut }; 3875d7231d8SStephan Herhut 3885d7231d8SStephan Herhut // Emit calls. If the called function has a result, remap the corresponding 3895d7231d8SStephan Herhut // value. Note that LLVM IR dialect CallOp has either 0 or 1 result. 390d5b60ee8SRiver Riddle if (isa<LLVM::CallOp>(opInst)) { 3915d7231d8SStephan Herhut llvm::Value *result = convertCall(opInst); 3925d7231d8SStephan Herhut if (opInst.getNumResults() != 0) { 3935d7231d8SStephan Herhut valueMapping[opInst.getResult(0)] = result; 394baa1ec22SAlex Zinenko return success(); 3955d7231d8SStephan Herhut } 3965d7231d8SStephan Herhut // Check that LLVM call returns void for 0-result functions. 397baa1ec22SAlex Zinenko return success(result->getType()->isVoidTy()); 3985d7231d8SStephan Herhut } 3995d7231d8SStephan Herhut 400d242aa24SShraiysh Vaishay if (auto invOp = dyn_cast<LLVM::InvokeOp>(opInst)) { 401d242aa24SShraiysh Vaishay auto operands = lookupValues(opInst.getOperands()); 402d242aa24SShraiysh Vaishay ArrayRef<llvm::Value *> operandsRef(operands); 403133049d0SEli Friedman if (auto attr = opInst.getAttrOfType<FlatSymbolRefAttr>("callee")) { 404d242aa24SShraiysh Vaishay builder.CreateInvoke(functionMapping.lookup(attr.getValue()), 405d242aa24SShraiysh Vaishay blockMapping[invOp.getSuccessor(0)], 406d242aa24SShraiysh Vaishay blockMapping[invOp.getSuccessor(1)], operandsRef); 407133049d0SEli Friedman } else { 408133049d0SEli Friedman auto *calleePtrType = 409133049d0SEli Friedman cast<llvm::PointerType>(operandsRef.front()->getType()); 410133049d0SEli Friedman auto *calleeType = 411133049d0SEli Friedman cast<llvm::FunctionType>(calleePtrType->getElementType()); 412d242aa24SShraiysh Vaishay builder.CreateInvoke( 413133049d0SEli Friedman calleeType, operandsRef.front(), blockMapping[invOp.getSuccessor(0)], 414d242aa24SShraiysh Vaishay blockMapping[invOp.getSuccessor(1)], operandsRef.drop_front()); 415133049d0SEli Friedman } 416d242aa24SShraiysh Vaishay return success(); 417d242aa24SShraiysh Vaishay } 418d242aa24SShraiysh Vaishay 419d242aa24SShraiysh Vaishay if (auto lpOp = dyn_cast<LLVM::LandingpadOp>(opInst)) { 420d242aa24SShraiysh Vaishay llvm::Type *ty = lpOp.getType().dyn_cast<LLVMType>().getUnderlyingType(); 421d242aa24SShraiysh Vaishay llvm::LandingPadInst *lpi = 422d242aa24SShraiysh Vaishay builder.CreateLandingPad(ty, lpOp.getNumOperands()); 423d242aa24SShraiysh Vaishay 424d242aa24SShraiysh Vaishay // Add clauses 425d242aa24SShraiysh Vaishay for (auto operand : lookupValues(lpOp.getOperands())) { 426d242aa24SShraiysh Vaishay // All operands should be constant - checked by verifier 427d242aa24SShraiysh Vaishay if (auto constOperand = dyn_cast<llvm::Constant>(operand)) 428d242aa24SShraiysh Vaishay lpi->addClause(constOperand); 429d242aa24SShraiysh Vaishay } 430ff77397fSShraiysh Vaishay valueMapping[lpOp.getResult()] = lpi; 431d242aa24SShraiysh Vaishay return success(); 432d242aa24SShraiysh Vaishay } 433d242aa24SShraiysh Vaishay 4345d7231d8SStephan Herhut // Emit branches. We need to look up the remapped blocks and ignore the block 4355d7231d8SStephan Herhut // arguments that were transformed into PHI nodes. 436c5ecf991SRiver Riddle if (auto brOp = dyn_cast<LLVM::BrOp>(opInst)) { 437c0fd5e65SRiver Riddle builder.CreateBr(blockMapping[brOp.getSuccessor()]); 438baa1ec22SAlex Zinenko return success(); 4395d7231d8SStephan Herhut } 440c5ecf991SRiver Riddle if (auto condbrOp = dyn_cast<LLVM::CondBrOp>(opInst)) { 4415d7231d8SStephan Herhut builder.CreateCondBr(valueMapping.lookup(condbrOp.getOperand(0)), 4425d7231d8SStephan Herhut blockMapping[condbrOp.getSuccessor(0)], 4435d7231d8SStephan Herhut blockMapping[condbrOp.getSuccessor(1)]); 444baa1ec22SAlex Zinenko return success(); 4455d7231d8SStephan Herhut } 4465d7231d8SStephan Herhut 4472dd38b09SAlex Zinenko // Emit addressof. We need to look up the global value referenced by the 4482dd38b09SAlex Zinenko // operation and store it in the MLIR-to-LLVM value mapping. This does not 4492dd38b09SAlex Zinenko // emit any LLVM instruction. 4502dd38b09SAlex Zinenko if (auto addressOfOp = dyn_cast<LLVM::AddressOfOp>(opInst)) { 4512dd38b09SAlex Zinenko LLVM::GlobalOp global = addressOfOp.getGlobal(); 4522dd38b09SAlex Zinenko // The verifier should not have allowed this. 4532dd38b09SAlex Zinenko assert(global && "referencing an undefined global"); 4542dd38b09SAlex Zinenko 4552dd38b09SAlex Zinenko valueMapping[addressOfOp.getResult()] = globalsMapping.lookup(global); 4562dd38b09SAlex Zinenko return success(); 4572dd38b09SAlex Zinenko } 4582dd38b09SAlex Zinenko 45992a295ebSKiran Chandramohan if (opInst.getDialect() == ompDialect) { 4607ecee63eSKiran Kumar T P return convertOmpOperation(opInst, builder); 46192a295ebSKiran Chandramohan } 46292a295ebSKiran Chandramohan 463baa1ec22SAlex Zinenko return opInst.emitError("unsupported or non-LLVM operation: ") 464baa1ec22SAlex Zinenko << opInst.getName(); 4655d7231d8SStephan Herhut } 4665d7231d8SStephan Herhut 4672666b973SRiver Riddle /// Convert block to LLVM IR. Unless `ignoreArguments` is set, emit PHI nodes 4682666b973SRiver Riddle /// to define values corresponding to the MLIR block arguments. These nodes 4692666b973SRiver Riddle /// are not connected to the source basic blocks, which may not exist yet. 470baa1ec22SAlex Zinenko LogicalResult ModuleTranslation::convertBlock(Block &bb, bool ignoreArguments) { 4715d7231d8SStephan Herhut llvm::IRBuilder<> builder(blockMapping[&bb]); 472c33d6970SRiver Riddle auto *subprogram = builder.GetInsertBlock()->getParent()->getSubprogram(); 4735d7231d8SStephan Herhut 4745d7231d8SStephan Herhut // Before traversing operations, make block arguments available through 4755d7231d8SStephan Herhut // value remapping and PHI nodes, but do not add incoming edges for the PHI 4765d7231d8SStephan Herhut // nodes just yet: those values may be defined by this or following blocks. 4775d7231d8SStephan Herhut // This step is omitted if "ignoreArguments" is set. The arguments of the 4785d7231d8SStephan Herhut // first block have been already made available through the remapping of 4795d7231d8SStephan Herhut // LLVM function arguments. 4805d7231d8SStephan Herhut if (!ignoreArguments) { 4815d7231d8SStephan Herhut auto predecessors = bb.getPredecessors(); 4825d7231d8SStephan Herhut unsigned numPredecessors = 4835d7231d8SStephan Herhut std::distance(predecessors.begin(), predecessors.end()); 48435807bc4SRiver Riddle for (auto arg : bb.getArguments()) { 4852bdf33ccSRiver Riddle auto wrappedType = arg.getType().dyn_cast<LLVM::LLVMType>(); 486baa1ec22SAlex Zinenko if (!wrappedType) 487baa1ec22SAlex Zinenko return emitError(bb.front().getLoc(), 488a4c3a645SRiver Riddle "block argument does not have an LLVM type"); 4895d7231d8SStephan Herhut llvm::Type *type = wrappedType.getUnderlyingType(); 4905d7231d8SStephan Herhut llvm::PHINode *phi = builder.CreatePHI(type, numPredecessors); 4915d7231d8SStephan Herhut valueMapping[arg] = phi; 4925d7231d8SStephan Herhut } 4935d7231d8SStephan Herhut } 4945d7231d8SStephan Herhut 4955d7231d8SStephan Herhut // Traverse operations. 4965d7231d8SStephan Herhut for (auto &op : bb) { 497c33d6970SRiver Riddle // Set the current debug location within the builder. 498c33d6970SRiver Riddle builder.SetCurrentDebugLocation( 499c33d6970SRiver Riddle debugTranslation->translateLoc(op.getLoc(), subprogram)); 500c33d6970SRiver Riddle 501baa1ec22SAlex Zinenko if (failed(convertOperation(op, builder))) 502baa1ec22SAlex Zinenko return failure(); 5035d7231d8SStephan Herhut } 5045d7231d8SStephan Herhut 505baa1ec22SAlex Zinenko return success(); 5065d7231d8SStephan Herhut } 5075d7231d8SStephan Herhut 5082666b973SRiver Riddle /// Create named global variables that correspond to llvm.mlir.global 5092666b973SRiver Riddle /// definitions. 510efa2d533SAlex Zinenko LogicalResult ModuleTranslation::convertGlobals() { 51169040d5bSStephan Herhut // Lock access to the llvm context. 51269040d5bSStephan Herhut llvm::sys::SmartScopedLock<true> scopedLock( 51369040d5bSStephan Herhut llvmDialect->getLLVMContextMutex()); 51444fc7d72STres Popp for (auto op : getModuleBody(mlirModule).getOps<LLVM::GlobalOp>()) { 515250a11aeSJames Molloy llvm::Type *type = op.getType().getUnderlyingType(); 516250a11aeSJames Molloy llvm::Constant *cst = llvm::UndefValue::get(type); 517250a11aeSJames Molloy if (op.getValueOrNull()) { 51868451df2SAlex Zinenko // String attributes are treated separately because they cannot appear as 51968451df2SAlex Zinenko // in-function constants and are thus not supported by getLLVMConstant. 52033a3a91bSChristian Sigg if (auto strAttr = op.getValueOrNull().dyn_cast_or_null<StringAttr>()) { 5212dd38b09SAlex Zinenko cst = llvm::ConstantDataArray::getString( 52268451df2SAlex Zinenko llvmModule->getContext(), strAttr.getValue(), /*AddNull=*/false); 5232dd38b09SAlex Zinenko type = cst->getType(); 524efa2d533SAlex Zinenko } else if (!(cst = getLLVMConstant(type, op.getValueOrNull(), 525efa2d533SAlex Zinenko op.getLoc()))) { 526efa2d533SAlex Zinenko return failure(); 52768451df2SAlex Zinenko } 528250a11aeSJames Molloy } else if (Block *initializer = op.getInitializerBlock()) { 529250a11aeSJames Molloy llvm::IRBuilder<> builder(llvmModule->getContext()); 530250a11aeSJames Molloy for (auto &op : initializer->without_terminator()) { 531250a11aeSJames Molloy if (failed(convertOperation(op, builder)) || 532efa2d533SAlex Zinenko !isa<llvm::Constant>(valueMapping.lookup(op.getResult(0)))) 533efa2d533SAlex Zinenko return emitError(op.getLoc(), "unemittable constant value"); 534250a11aeSJames Molloy } 535250a11aeSJames Molloy ReturnOp ret = cast<ReturnOp>(initializer->getTerminator()); 536250a11aeSJames Molloy cst = cast<llvm::Constant>(valueMapping.lookup(ret.getOperand(0))); 537250a11aeSJames Molloy } 53868451df2SAlex Zinenko 539eb67bd78SAlex Zinenko auto linkage = convertLinkageToLLVM(op.linkage()); 540d5e627f8SAlex Zinenko bool anyExternalLinkage = 5417b5d4669SEric Schweitz ((linkage == llvm::GlobalVariable::ExternalLinkage && 5427b5d4669SEric Schweitz isa<llvm::UndefValue>(cst)) || 543d5e627f8SAlex Zinenko linkage == llvm::GlobalVariable::ExternalWeakLinkage); 544e79bfefbSMLIR Team auto addrSpace = op.addr_space().getLimitedValue(); 545e79bfefbSMLIR Team auto *var = new llvm::GlobalVariable( 546d5e627f8SAlex Zinenko *llvmModule, type, op.constant(), linkage, 547d5e627f8SAlex Zinenko anyExternalLinkage ? nullptr : cst, op.sym_name(), 548d5e627f8SAlex Zinenko /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal, addrSpace); 549e79bfefbSMLIR Team 5502dd38b09SAlex Zinenko globalsMapping.try_emplace(op, var); 551b9ff2dd8SAlex Zinenko } 552efa2d533SAlex Zinenko 553efa2d533SAlex Zinenko return success(); 554b9ff2dd8SAlex Zinenko } 555b9ff2dd8SAlex Zinenko 5562666b973SRiver Riddle /// Get the SSA value passed to the current block from the terminator operation 5572666b973SRiver Riddle /// of its predecessor. 558e62a6956SRiver Riddle static Value getPHISourceValue(Block *current, Block *pred, 5595d7231d8SStephan Herhut unsigned numArguments, unsigned index) { 5605d7231d8SStephan Herhut auto &terminator = *pred->getTerminator(); 561d5b60ee8SRiver Riddle if (isa<LLVM::BrOp>(terminator)) { 5625d7231d8SStephan Herhut return terminator.getOperand(index); 5635d7231d8SStephan Herhut } 5645d7231d8SStephan Herhut 5655d7231d8SStephan Herhut // For conditional branches, we need to check if the current block is reached 5665d7231d8SStephan Herhut // through the "true" or the "false" branch and take the relevant operands. 567c5ecf991SRiver Riddle auto condBranchOp = dyn_cast<LLVM::CondBrOp>(terminator); 5685d7231d8SStephan Herhut assert(condBranchOp && 5695d7231d8SStephan Herhut "only branch operations can be terminators of a block that " 5705d7231d8SStephan Herhut "has successors"); 5715d7231d8SStephan Herhut assert((condBranchOp.getSuccessor(0) != condBranchOp.getSuccessor(1)) && 5725d7231d8SStephan Herhut "successors with arguments in LLVM conditional branches must be " 5735d7231d8SStephan Herhut "different blocks"); 5745d7231d8SStephan Herhut 5755d7231d8SStephan Herhut return condBranchOp.getSuccessor(0) == current 576988249a5SRiver Riddle ? condBranchOp.trueDestOperands()[index] 577988249a5SRiver Riddle : condBranchOp.falseDestOperands()[index]; 5785d7231d8SStephan Herhut } 5795d7231d8SStephan Herhut 5805e7959a3SAlex Zinenko void ModuleTranslation::connectPHINodes(LLVMFuncOp func) { 5815d7231d8SStephan Herhut // Skip the first block, it cannot be branched to and its arguments correspond 5825d7231d8SStephan Herhut // to the arguments of the LLVM function. 5835d7231d8SStephan Herhut for (auto it = std::next(func.begin()), eit = func.end(); it != eit; ++it) { 5845d7231d8SStephan Herhut Block *bb = &*it; 5855d7231d8SStephan Herhut llvm::BasicBlock *llvmBB = blockMapping.lookup(bb); 5865d7231d8SStephan Herhut auto phis = llvmBB->phis(); 5875d7231d8SStephan Herhut auto numArguments = bb->getNumArguments(); 5885d7231d8SStephan Herhut assert(numArguments == std::distance(phis.begin(), phis.end())); 5895d7231d8SStephan Herhut for (auto &numberedPhiNode : llvm::enumerate(phis)) { 5905d7231d8SStephan Herhut auto &phiNode = numberedPhiNode.value(); 5915d7231d8SStephan Herhut unsigned index = numberedPhiNode.index(); 5925d7231d8SStephan Herhut for (auto *pred : bb->getPredecessors()) { 5935d7231d8SStephan Herhut phiNode.addIncoming(valueMapping.lookup(getPHISourceValue( 5945d7231d8SStephan Herhut bb, pred, numArguments, index)), 5955d7231d8SStephan Herhut blockMapping.lookup(pred)); 5965d7231d8SStephan Herhut } 5975d7231d8SStephan Herhut } 5985d7231d8SStephan Herhut } 5995d7231d8SStephan Herhut } 6005d7231d8SStephan Herhut 6015d7231d8SStephan Herhut // TODO(mlir-team): implement an iterative version 6025d7231d8SStephan Herhut static void topologicalSortImpl(llvm::SetVector<Block *> &blocks, Block *b) { 6035d7231d8SStephan Herhut blocks.insert(b); 6045d7231d8SStephan Herhut for (Block *bb : b->getSuccessors()) { 6055d7231d8SStephan Herhut if (blocks.count(bb) == 0) 6065d7231d8SStephan Herhut topologicalSortImpl(blocks, bb); 6075d7231d8SStephan Herhut } 6085d7231d8SStephan Herhut } 6095d7231d8SStephan Herhut 6102666b973SRiver Riddle /// Sort function blocks topologically. 6115e7959a3SAlex Zinenko static llvm::SetVector<Block *> topologicalSort(LLVMFuncOp f) { 6125d7231d8SStephan Herhut // For each blocks that has not been visited yet (i.e. that has no 6135d7231d8SStephan Herhut // predecessors), add it to the list and traverse its successors in DFS 6145d7231d8SStephan Herhut // preorder. 6155d7231d8SStephan Herhut llvm::SetVector<Block *> blocks; 6165d7231d8SStephan Herhut for (Block &b : f.getBlocks()) { 6175d7231d8SStephan Herhut if (blocks.count(&b) == 0) 6185d7231d8SStephan Herhut topologicalSortImpl(blocks, &b); 6195d7231d8SStephan Herhut } 6205d7231d8SStephan Herhut assert(blocks.size() == f.getBlocks().size() && "some blocks are not sorted"); 6215d7231d8SStephan Herhut 6225d7231d8SStephan Herhut return blocks; 6235d7231d8SStephan Herhut } 6245d7231d8SStephan Herhut 6250a2131b7SAlex Zinenko /// Attempts to add an attribute identified by `key`, optionally with the given 6260a2131b7SAlex Zinenko /// `value` to LLVM function `llvmFunc`. Reports errors at `loc` if any. If the 6270a2131b7SAlex Zinenko /// attribute has a kind known to LLVM IR, create the attribute of this kind, 6280a2131b7SAlex Zinenko /// otherwise keep it as a string attribute. Performs additional checks for 6290a2131b7SAlex Zinenko /// attributes known to have or not have a value in order to avoid assertions 6300a2131b7SAlex Zinenko /// inside LLVM upon construction. 6310a2131b7SAlex Zinenko static LogicalResult checkedAddLLVMFnAttribute(Location loc, 6320a2131b7SAlex Zinenko llvm::Function *llvmFunc, 6330a2131b7SAlex Zinenko StringRef key, 6340a2131b7SAlex Zinenko StringRef value = StringRef()) { 6350a2131b7SAlex Zinenko auto kind = llvm::Attribute::getAttrKindFromName(key); 6360a2131b7SAlex Zinenko if (kind == llvm::Attribute::None) { 6370a2131b7SAlex Zinenko llvmFunc->addFnAttr(key, value); 6380a2131b7SAlex Zinenko return success(); 6390a2131b7SAlex Zinenko } 6400a2131b7SAlex Zinenko 6410a2131b7SAlex Zinenko if (llvm::Attribute::doesAttrKindHaveArgument(kind)) { 6420a2131b7SAlex Zinenko if (value.empty()) 6430a2131b7SAlex Zinenko return emitError(loc) << "LLVM attribute '" << key << "' expects a value"; 6440a2131b7SAlex Zinenko 6450a2131b7SAlex Zinenko int result; 6460a2131b7SAlex Zinenko if (!value.getAsInteger(/*Radix=*/0, result)) 6470a2131b7SAlex Zinenko llvmFunc->addFnAttr( 6480a2131b7SAlex Zinenko llvm::Attribute::get(llvmFunc->getContext(), kind, result)); 6490a2131b7SAlex Zinenko else 6500a2131b7SAlex Zinenko llvmFunc->addFnAttr(key, value); 6510a2131b7SAlex Zinenko return success(); 6520a2131b7SAlex Zinenko } 6530a2131b7SAlex Zinenko 6540a2131b7SAlex Zinenko if (!value.empty()) 6550a2131b7SAlex Zinenko return emitError(loc) << "LLVM attribute '" << key 6560a2131b7SAlex Zinenko << "' does not expect a value, found '" << value 6570a2131b7SAlex Zinenko << "'"; 6580a2131b7SAlex Zinenko 6590a2131b7SAlex Zinenko llvmFunc->addFnAttr(kind); 6600a2131b7SAlex Zinenko return success(); 6610a2131b7SAlex Zinenko } 6620a2131b7SAlex Zinenko 6630a2131b7SAlex Zinenko /// Attaches the attributes listed in the given array attribute to `llvmFunc`. 6640a2131b7SAlex Zinenko /// Reports error to `loc` if any and returns immediately. Expects `attributes` 6650a2131b7SAlex Zinenko /// to be an array attribute containing either string attributes, treated as 6660a2131b7SAlex Zinenko /// value-less LLVM attributes, or array attributes containing two string 6670a2131b7SAlex Zinenko /// attributes, with the first string being the name of the corresponding LLVM 6680a2131b7SAlex Zinenko /// attribute and the second string beings its value. Note that even integer 6690a2131b7SAlex Zinenko /// attributes are expected to have their values expressed as strings. 6700a2131b7SAlex Zinenko static LogicalResult 6710a2131b7SAlex Zinenko forwardPassthroughAttributes(Location loc, Optional<ArrayAttr> attributes, 6720a2131b7SAlex Zinenko llvm::Function *llvmFunc) { 6730a2131b7SAlex Zinenko if (!attributes) 6740a2131b7SAlex Zinenko return success(); 6750a2131b7SAlex Zinenko 6760a2131b7SAlex Zinenko for (Attribute attr : *attributes) { 6770a2131b7SAlex Zinenko if (auto stringAttr = attr.dyn_cast<StringAttr>()) { 6780a2131b7SAlex Zinenko if (failed( 6790a2131b7SAlex Zinenko checkedAddLLVMFnAttribute(loc, llvmFunc, stringAttr.getValue()))) 6800a2131b7SAlex Zinenko return failure(); 6810a2131b7SAlex Zinenko continue; 6820a2131b7SAlex Zinenko } 6830a2131b7SAlex Zinenko 6840a2131b7SAlex Zinenko auto arrayAttr = attr.dyn_cast<ArrayAttr>(); 6850a2131b7SAlex Zinenko if (!arrayAttr || arrayAttr.size() != 2) 6860a2131b7SAlex Zinenko return emitError(loc) 6870a2131b7SAlex Zinenko << "expected 'passthrough' to contain string or array attributes"; 6880a2131b7SAlex Zinenko 6890a2131b7SAlex Zinenko auto keyAttr = arrayAttr[0].dyn_cast<StringAttr>(); 6900a2131b7SAlex Zinenko auto valueAttr = arrayAttr[1].dyn_cast<StringAttr>(); 6910a2131b7SAlex Zinenko if (!keyAttr || !valueAttr) 6920a2131b7SAlex Zinenko return emitError(loc) 6930a2131b7SAlex Zinenko << "expected arrays within 'passthrough' to contain two strings"; 6940a2131b7SAlex Zinenko 6950a2131b7SAlex Zinenko if (failed(checkedAddLLVMFnAttribute(loc, llvmFunc, keyAttr.getValue(), 6960a2131b7SAlex Zinenko valueAttr.getValue()))) 6970a2131b7SAlex Zinenko return failure(); 6980a2131b7SAlex Zinenko } 6990a2131b7SAlex Zinenko return success(); 7000a2131b7SAlex Zinenko } 7010a2131b7SAlex Zinenko 7025e7959a3SAlex Zinenko LogicalResult ModuleTranslation::convertOneFunction(LLVMFuncOp func) { 7035d7231d8SStephan Herhut // Clear the block and value mappings, they are only relevant within one 7045d7231d8SStephan Herhut // function. 7055d7231d8SStephan Herhut blockMapping.clear(); 7065d7231d8SStephan Herhut valueMapping.clear(); 707c33862b0SRiver Riddle llvm::Function *llvmFunc = functionMapping.lookup(func.getName()); 708c33d6970SRiver Riddle 709c33d6970SRiver Riddle // Translate the debug information for this function. 710c33d6970SRiver Riddle debugTranslation->translate(func, *llvmFunc); 711c33d6970SRiver Riddle 7125d7231d8SStephan Herhut // Add function arguments to the value remapping table. 7135d7231d8SStephan Herhut // If there was noalias info then we decorate each argument accordingly. 7145d7231d8SStephan Herhut unsigned int argIdx = 0; 715eeef50b1SFangrui Song for (auto kvp : llvm::zip(func.getArguments(), llvmFunc->args())) { 7165d7231d8SStephan Herhut llvm::Argument &llvmArg = std::get<1>(kvp); 717e62a6956SRiver Riddle BlockArgument mlirArg = std::get<0>(kvp); 7185d7231d8SStephan Herhut 7195d7231d8SStephan Herhut if (auto attr = func.getArgAttrOfType<BoolAttr>(argIdx, "llvm.noalias")) { 7205d7231d8SStephan Herhut // NB: Attribute already verified to be boolean, so check if we can indeed 7215d7231d8SStephan Herhut // attach the attribute to this argument, based on its type. 7222bdf33ccSRiver Riddle auto argTy = mlirArg.getType().dyn_cast<LLVM::LLVMType>(); 723baa1ec22SAlex Zinenko if (!argTy.getUnderlyingType()->isPointerTy()) 724baa1ec22SAlex Zinenko return func.emitError( 7255d7231d8SStephan Herhut "llvm.noalias attribute attached to LLVM non-pointer argument"); 7265d7231d8SStephan Herhut if (attr.getValue()) 7275d7231d8SStephan Herhut llvmArg.addAttr(llvm::Attribute::AttrKind::NoAlias); 7285d7231d8SStephan Herhut } 7295d7231d8SStephan Herhut valueMapping[mlirArg] = &llvmArg; 7305d7231d8SStephan Herhut argIdx++; 7315d7231d8SStephan Herhut } 7325d7231d8SStephan Herhut 733ff77397fSShraiysh Vaishay // Check the personality and set it. 734ff77397fSShraiysh Vaishay if (func.personality().hasValue()) { 735ff77397fSShraiysh Vaishay llvm::Type *ty = llvm::Type::getInt8PtrTy(llvmFunc->getContext()); 736ff77397fSShraiysh Vaishay if (llvm::Constant *pfunc = 737ff77397fSShraiysh Vaishay getLLVMConstant(ty, func.personalityAttr(), func.getLoc())) 738ff77397fSShraiysh Vaishay llvmFunc->setPersonalityFn(pfunc); 739ff77397fSShraiysh Vaishay } 740ff77397fSShraiysh Vaishay 7415d7231d8SStephan Herhut // First, create all blocks so we can jump to them. 7425d7231d8SStephan Herhut llvm::LLVMContext &llvmContext = llvmFunc->getContext(); 7435d7231d8SStephan Herhut for (auto &bb : func) { 7445d7231d8SStephan Herhut auto *llvmBB = llvm::BasicBlock::Create(llvmContext); 7455d7231d8SStephan Herhut llvmBB->insertInto(llvmFunc); 7465d7231d8SStephan Herhut blockMapping[&bb] = llvmBB; 7475d7231d8SStephan Herhut } 7485d7231d8SStephan Herhut 7495d7231d8SStephan Herhut // Then, convert blocks one by one in topological order to ensure defs are 7505d7231d8SStephan Herhut // converted before uses. 7515d7231d8SStephan Herhut auto blocks = topologicalSort(func); 7525d7231d8SStephan Herhut for (auto indexedBB : llvm::enumerate(blocks)) { 7535d7231d8SStephan Herhut auto *bb = indexedBB.value(); 754baa1ec22SAlex Zinenko if (failed(convertBlock(*bb, /*ignoreArguments=*/indexedBB.index() == 0))) 755baa1ec22SAlex Zinenko return failure(); 7565d7231d8SStephan Herhut } 7575d7231d8SStephan Herhut 7585d7231d8SStephan Herhut // Finally, after all blocks have been traversed and values mapped, connect 7595d7231d8SStephan Herhut // the PHI nodes to the results of preceding blocks. 7605d7231d8SStephan Herhut connectPHINodes(func); 761baa1ec22SAlex Zinenko return success(); 7625d7231d8SStephan Herhut } 7635d7231d8SStephan Herhut 76444fc7d72STres Popp LogicalResult ModuleTranslation::checkSupportedModuleOps(Operation *m) { 76544fc7d72STres Popp for (Operation &o : getModuleBody(m).getOperations()) 7664dde19f0SAlex Zinenko if (!isa<LLVM::LLVMFuncOp>(&o) && !isa<LLVM::GlobalOp>(&o) && 76744fc7d72STres Popp !o.isKnownTerminator()) 7684dde19f0SAlex Zinenko return o.emitOpError("unsupported module-level operation"); 7694dde19f0SAlex Zinenko return success(); 7704dde19f0SAlex Zinenko } 7714dde19f0SAlex Zinenko 772baa1ec22SAlex Zinenko LogicalResult ModuleTranslation::convertFunctions() { 77369040d5bSStephan Herhut // Lock access to the llvm context. 77469040d5bSStephan Herhut llvm::sys::SmartScopedLock<true> scopedLock( 77569040d5bSStephan Herhut llvmDialect->getLLVMContextMutex()); 7765d7231d8SStephan Herhut // Declare all functions first because there may be function calls that form a 7775d7231d8SStephan Herhut // call graph with cycles. 77844fc7d72STres Popp for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) { 7795e7959a3SAlex Zinenko llvm::FunctionCallee llvmFuncCst = llvmModule->getOrInsertFunction( 7805e7959a3SAlex Zinenko function.getName(), 7814562e389SRiver Riddle cast<llvm::FunctionType>(function.getType().getUnderlyingType())); 7820a2131b7SAlex Zinenko llvm::Function *llvmFunc = cast<llvm::Function>(llvmFuncCst.getCallee()); 7830a2131b7SAlex Zinenko functionMapping[function.getName()] = llvmFunc; 7840a2131b7SAlex Zinenko 7850a2131b7SAlex Zinenko // Forward the pass-through attributes to LLVM. 7860a2131b7SAlex Zinenko if (failed(forwardPassthroughAttributes(function.getLoc(), 7870a2131b7SAlex Zinenko function.passthrough(), llvmFunc))) 7880a2131b7SAlex Zinenko return failure(); 7895d7231d8SStephan Herhut } 7905d7231d8SStephan Herhut 7915d7231d8SStephan Herhut // Convert functions. 79244fc7d72STres Popp for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) { 7935d7231d8SStephan Herhut // Ignore external functions. 7945d7231d8SStephan Herhut if (function.isExternal()) 7955d7231d8SStephan Herhut continue; 7965d7231d8SStephan Herhut 797baa1ec22SAlex Zinenko if (failed(convertOneFunction(function))) 798baa1ec22SAlex Zinenko return failure(); 7995d7231d8SStephan Herhut } 8005d7231d8SStephan Herhut 801baa1ec22SAlex Zinenko return success(); 8025d7231d8SStephan Herhut } 8035d7231d8SStephan Herhut 804efadb6b8SAlex Zinenko /// A helper to look up remapped operands in the value remapping table.` 805efadb6b8SAlex Zinenko SmallVector<llvm::Value *, 8> 806efadb6b8SAlex Zinenko ModuleTranslation::lookupValues(ValueRange values) { 807efadb6b8SAlex Zinenko SmallVector<llvm::Value *, 8> remapped; 808efadb6b8SAlex Zinenko remapped.reserve(values.size()); 809ff77397fSShraiysh Vaishay for (Value v : values) { 810ff77397fSShraiysh Vaishay assert(valueMapping.count(v) && "referencing undefined value"); 811efadb6b8SAlex Zinenko remapped.push_back(valueMapping.lookup(v)); 812ff77397fSShraiysh Vaishay } 813efadb6b8SAlex Zinenko return remapped; 814efadb6b8SAlex Zinenko } 815efadb6b8SAlex Zinenko 81644fc7d72STres Popp std::unique_ptr<llvm::Module> 81744fc7d72STres Popp ModuleTranslation::prepareLLVMModule(Operation *m) { 81844fc7d72STres Popp auto *dialect = m->getContext()->getRegisteredDialect<LLVM::LLVMDialect>(); 8195d7231d8SStephan Herhut assert(dialect && "LLVM dialect must be registered"); 82069040d5bSStephan Herhut // Lock the LLVM context as we might create new types here. 82169040d5bSStephan Herhut llvm::sys::SmartScopedLock<true> scopedLock(dialect->getLLVMContextMutex()); 8225d7231d8SStephan Herhut 823bc5c7378SRiver Riddle auto llvmModule = llvm::CloneModule(dialect->getLLVMModule()); 8245d7231d8SStephan Herhut if (!llvmModule) 8255d7231d8SStephan Herhut return nullptr; 8265d7231d8SStephan Herhut 8275d7231d8SStephan Herhut llvm::LLVMContext &llvmContext = llvmModule->getContext(); 8285d7231d8SStephan Herhut llvm::IRBuilder<> builder(llvmContext); 8295d7231d8SStephan Herhut 8305d7231d8SStephan Herhut // Inject declarations for `malloc` and `free` functions that can be used in 8315d7231d8SStephan Herhut // memref allocation/deallocation coming from standard ops lowering. 8325d7231d8SStephan Herhut llvmModule->getOrInsertFunction("malloc", builder.getInt8PtrTy(), 8335d7231d8SStephan Herhut builder.getInt64Ty()); 8345d7231d8SStephan Herhut llvmModule->getOrInsertFunction("free", builder.getVoidTy(), 8355d7231d8SStephan Herhut builder.getInt8PtrTy()); 8365d7231d8SStephan Herhut 8375d7231d8SStephan Herhut return llvmModule; 8385d7231d8SStephan Herhut } 839