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())); 1125d7231d8SStephan Herhut if (auto floatAttr = attr.dyn_cast<FloatAttr>()) 1135d7231d8SStephan Herhut return llvm::ConstantFP::get(llvmType, floatAttr.getValue()); 1149b9c647cSRiver Riddle if (auto funcAttr = attr.dyn_cast<FlatSymbolRefAttr>()) 115ff77397fSShraiysh Vaishay return llvm::ConstantExpr::getBitCast( 116ff77397fSShraiysh Vaishay functionMapping.lookup(funcAttr.getValue()), llvmType); 1175d7231d8SStephan Herhut if (auto splatAttr = attr.dyn_cast<SplatElementsAttr>()) { 11868b03aeeSEli Friedman llvm::Type *elementType; 11968b03aeeSEli Friedman uint64_t numElements; 12068b03aeeSEli Friedman if (auto *arrayTy = dyn_cast<llvm::ArrayType>(llvmType)) { 12168b03aeeSEli Friedman elementType = arrayTy->getElementType(); 12268b03aeeSEli Friedman numElements = arrayTy->getNumElements(); 12368b03aeeSEli Friedman } else { 1245cba1c63SChristopher Tetreault auto *vectorTy = cast<llvm::FixedVectorType>(llvmType); 12568b03aeeSEli Friedman elementType = vectorTy->getElementType(); 12668b03aeeSEli Friedman numElements = vectorTy->getNumElements(); 12768b03aeeSEli Friedman } 128d6ea8ff0SAlex Zinenko // Splat value is a scalar. Extract it only if the element type is not 129d6ea8ff0SAlex Zinenko // another sequence type. The recursion terminates because each step removes 130d6ea8ff0SAlex Zinenko // one outer sequential type. 13168b03aeeSEli Friedman bool elementTypeSequential = 132d891d738SRahul Joshi isa<llvm::ArrayType, llvm::VectorType>(elementType); 133d6ea8ff0SAlex Zinenko llvm::Constant *child = getLLVMConstant( 134d6ea8ff0SAlex Zinenko elementType, 13568b03aeeSEli Friedman elementTypeSequential ? splatAttr : splatAttr.getSplatValue(), loc); 136a4a42160SAlex Zinenko if (!child) 137a4a42160SAlex Zinenko return nullptr; 1382f13df13SMLIR Team if (llvmType->isVectorTy()) 139396a42d9SRiver Riddle return llvm::ConstantVector::getSplat( 140396a42d9SRiver Riddle llvm::ElementCount(numElements, /*Scalable=*/false), child); 1412f13df13SMLIR Team if (llvmType->isArrayTy()) { 142ac9d742bSStephan Herhut auto *arrayType = llvm::ArrayType::get(elementType, numElements); 1432f13df13SMLIR Team SmallVector<llvm::Constant *, 8> constants(numElements, child); 1442f13df13SMLIR Team return llvm::ConstantArray::get(arrayType, constants); 1452f13df13SMLIR Team } 1465d7231d8SStephan Herhut } 147a4a42160SAlex Zinenko 148d906f84bSRiver Riddle if (auto elementsAttr = attr.dyn_cast<ElementsAttr>()) { 149a4a42160SAlex Zinenko assert(elementsAttr.getType().hasStaticShape()); 150a4a42160SAlex Zinenko assert(elementsAttr.getNumElements() != 0 && 151a4a42160SAlex Zinenko "unexpected empty elements attribute"); 152a4a42160SAlex Zinenko assert(!elementsAttr.getType().getShape().empty() && 153a4a42160SAlex Zinenko "unexpected empty elements attribute shape"); 154a4a42160SAlex Zinenko 1555d7231d8SStephan Herhut SmallVector<llvm::Constant *, 8> constants; 156a4a42160SAlex Zinenko constants.reserve(elementsAttr.getNumElements()); 157a4a42160SAlex Zinenko llvm::Type *innermostType = getInnermostElementType(llvmType); 158d906f84bSRiver Riddle for (auto n : elementsAttr.getValues<Attribute>()) { 159a4a42160SAlex Zinenko constants.push_back(getLLVMConstant(innermostType, n, loc)); 1605d7231d8SStephan Herhut if (!constants.back()) 1615d7231d8SStephan Herhut return nullptr; 1625d7231d8SStephan Herhut } 163a4a42160SAlex Zinenko ArrayRef<llvm::Constant *> constantsRef = constants; 164a4a42160SAlex Zinenko llvm::Constant *result = buildSequentialConstant( 165a4a42160SAlex Zinenko constantsRef, elementsAttr.getType().getShape(), llvmType, loc); 166a4a42160SAlex Zinenko assert(constantsRef.empty() && "did not consume all elemental constants"); 167a4a42160SAlex Zinenko return result; 1682f13df13SMLIR Team } 169a4a42160SAlex Zinenko 170cb348dffSStephan Herhut if (auto stringAttr = attr.dyn_cast<StringAttr>()) { 171cb348dffSStephan Herhut return llvm::ConstantDataArray::get( 172cb348dffSStephan Herhut llvmModule->getContext(), ArrayRef<char>{stringAttr.getValue().data(), 173cb348dffSStephan Herhut stringAttr.getValue().size()}); 174cb348dffSStephan Herhut } 175a4c3a645SRiver Riddle emitError(loc, "unsupported constant value"); 1765d7231d8SStephan Herhut return nullptr; 1775d7231d8SStephan Herhut } 1785d7231d8SStephan Herhut 1792666b973SRiver Riddle /// Convert MLIR integer comparison predicate to LLVM IR comparison predicate. 180ec82e1c9SAlex Zinenko static llvm::CmpInst::Predicate getLLVMCmpPredicate(ICmpPredicate p) { 1815d7231d8SStephan Herhut switch (p) { 182ec82e1c9SAlex Zinenko case LLVM::ICmpPredicate::eq: 1835d7231d8SStephan Herhut return llvm::CmpInst::Predicate::ICMP_EQ; 184ec82e1c9SAlex Zinenko case LLVM::ICmpPredicate::ne: 1855d7231d8SStephan Herhut return llvm::CmpInst::Predicate::ICMP_NE; 186ec82e1c9SAlex Zinenko case LLVM::ICmpPredicate::slt: 1875d7231d8SStephan Herhut return llvm::CmpInst::Predicate::ICMP_SLT; 188ec82e1c9SAlex Zinenko case LLVM::ICmpPredicate::sle: 1895d7231d8SStephan Herhut return llvm::CmpInst::Predicate::ICMP_SLE; 190ec82e1c9SAlex Zinenko case LLVM::ICmpPredicate::sgt: 1915d7231d8SStephan Herhut return llvm::CmpInst::Predicate::ICMP_SGT; 192ec82e1c9SAlex Zinenko case LLVM::ICmpPredicate::sge: 1935d7231d8SStephan Herhut return llvm::CmpInst::Predicate::ICMP_SGE; 194ec82e1c9SAlex Zinenko case LLVM::ICmpPredicate::ult: 1955d7231d8SStephan Herhut return llvm::CmpInst::Predicate::ICMP_ULT; 196ec82e1c9SAlex Zinenko case LLVM::ICmpPredicate::ule: 1975d7231d8SStephan Herhut return llvm::CmpInst::Predicate::ICMP_ULE; 198ec82e1c9SAlex Zinenko case LLVM::ICmpPredicate::ugt: 1995d7231d8SStephan Herhut return llvm::CmpInst::Predicate::ICMP_UGT; 200ec82e1c9SAlex Zinenko case LLVM::ICmpPredicate::uge: 2015d7231d8SStephan Herhut return llvm::CmpInst::Predicate::ICMP_UGE; 2025d7231d8SStephan Herhut } 203e6365f3dSJacques Pienaar llvm_unreachable("incorrect comparison predicate"); 2045d7231d8SStephan Herhut } 2055d7231d8SStephan Herhut 20648fdc8d7SNagy Mostafa static llvm::CmpInst::Predicate getLLVMCmpPredicate(FCmpPredicate p) { 20748fdc8d7SNagy Mostafa switch (p) { 20848fdc8d7SNagy Mostafa case LLVM::FCmpPredicate::_false: 20948fdc8d7SNagy Mostafa return llvm::CmpInst::Predicate::FCMP_FALSE; 21048fdc8d7SNagy Mostafa case LLVM::FCmpPredicate::oeq: 21148fdc8d7SNagy Mostafa return llvm::CmpInst::Predicate::FCMP_OEQ; 21248fdc8d7SNagy Mostafa case LLVM::FCmpPredicate::ogt: 21348fdc8d7SNagy Mostafa return llvm::CmpInst::Predicate::FCMP_OGT; 21448fdc8d7SNagy Mostafa case LLVM::FCmpPredicate::oge: 21548fdc8d7SNagy Mostafa return llvm::CmpInst::Predicate::FCMP_OGE; 21648fdc8d7SNagy Mostafa case LLVM::FCmpPredicate::olt: 21748fdc8d7SNagy Mostafa return llvm::CmpInst::Predicate::FCMP_OLT; 21848fdc8d7SNagy Mostafa case LLVM::FCmpPredicate::ole: 21948fdc8d7SNagy Mostafa return llvm::CmpInst::Predicate::FCMP_OLE; 22048fdc8d7SNagy Mostafa case LLVM::FCmpPredicate::one: 22148fdc8d7SNagy Mostafa return llvm::CmpInst::Predicate::FCMP_ONE; 22248fdc8d7SNagy Mostafa case LLVM::FCmpPredicate::ord: 22348fdc8d7SNagy Mostafa return llvm::CmpInst::Predicate::FCMP_ORD; 22448fdc8d7SNagy Mostafa case LLVM::FCmpPredicate::ueq: 22548fdc8d7SNagy Mostafa return llvm::CmpInst::Predicate::FCMP_UEQ; 22648fdc8d7SNagy Mostafa case LLVM::FCmpPredicate::ugt: 22748fdc8d7SNagy Mostafa return llvm::CmpInst::Predicate::FCMP_UGT; 22848fdc8d7SNagy Mostafa case LLVM::FCmpPredicate::uge: 22948fdc8d7SNagy Mostafa return llvm::CmpInst::Predicate::FCMP_UGE; 23048fdc8d7SNagy Mostafa case LLVM::FCmpPredicate::ult: 23148fdc8d7SNagy Mostafa return llvm::CmpInst::Predicate::FCMP_ULT; 23248fdc8d7SNagy Mostafa case LLVM::FCmpPredicate::ule: 23348fdc8d7SNagy Mostafa return llvm::CmpInst::Predicate::FCMP_ULE; 23448fdc8d7SNagy Mostafa case LLVM::FCmpPredicate::une: 23548fdc8d7SNagy Mostafa return llvm::CmpInst::Predicate::FCMP_UNE; 23648fdc8d7SNagy Mostafa case LLVM::FCmpPredicate::uno: 23748fdc8d7SNagy Mostafa return llvm::CmpInst::Predicate::FCMP_UNO; 23848fdc8d7SNagy Mostafa case LLVM::FCmpPredicate::_true: 23948fdc8d7SNagy Mostafa return llvm::CmpInst::Predicate::FCMP_TRUE; 24048fdc8d7SNagy Mostafa } 241e6365f3dSJacques Pienaar llvm_unreachable("incorrect comparison predicate"); 24248fdc8d7SNagy Mostafa } 24348fdc8d7SNagy Mostafa 24460a0c612SFrank Laub static llvm::AtomicRMWInst::BinOp getLLVMAtomicBinOp(AtomicBinOp op) { 24560a0c612SFrank Laub switch (op) { 24660a0c612SFrank Laub case LLVM::AtomicBinOp::xchg: 24760a0c612SFrank Laub return llvm::AtomicRMWInst::BinOp::Xchg; 24860a0c612SFrank Laub case LLVM::AtomicBinOp::add: 24960a0c612SFrank Laub return llvm::AtomicRMWInst::BinOp::Add; 25060a0c612SFrank Laub case LLVM::AtomicBinOp::sub: 25160a0c612SFrank Laub return llvm::AtomicRMWInst::BinOp::Sub; 25260a0c612SFrank Laub case LLVM::AtomicBinOp::_and: 25360a0c612SFrank Laub return llvm::AtomicRMWInst::BinOp::And; 25460a0c612SFrank Laub case LLVM::AtomicBinOp::nand: 25560a0c612SFrank Laub return llvm::AtomicRMWInst::BinOp::Nand; 25660a0c612SFrank Laub case LLVM::AtomicBinOp::_or: 25760a0c612SFrank Laub return llvm::AtomicRMWInst::BinOp::Or; 25860a0c612SFrank Laub case LLVM::AtomicBinOp::_xor: 25960a0c612SFrank Laub return llvm::AtomicRMWInst::BinOp::Xor; 26060a0c612SFrank Laub case LLVM::AtomicBinOp::max: 26160a0c612SFrank Laub return llvm::AtomicRMWInst::BinOp::Max; 26260a0c612SFrank Laub case LLVM::AtomicBinOp::min: 26360a0c612SFrank Laub return llvm::AtomicRMWInst::BinOp::Min; 26460a0c612SFrank Laub case LLVM::AtomicBinOp::umax: 26560a0c612SFrank Laub return llvm::AtomicRMWInst::BinOp::UMax; 26660a0c612SFrank Laub case LLVM::AtomicBinOp::umin: 26760a0c612SFrank Laub return llvm::AtomicRMWInst::BinOp::UMin; 26860a0c612SFrank Laub case LLVM::AtomicBinOp::fadd: 26960a0c612SFrank Laub return llvm::AtomicRMWInst::BinOp::FAdd; 27060a0c612SFrank Laub case LLVM::AtomicBinOp::fsub: 27160a0c612SFrank Laub return llvm::AtomicRMWInst::BinOp::FSub; 27260a0c612SFrank Laub } 27360a0c612SFrank Laub llvm_unreachable("incorrect atomic binary operator"); 27460a0c612SFrank Laub } 27560a0c612SFrank Laub 27660a0c612SFrank Laub static llvm::AtomicOrdering getLLVMAtomicOrdering(AtomicOrdering ordering) { 27760a0c612SFrank Laub switch (ordering) { 27860a0c612SFrank Laub case LLVM::AtomicOrdering::not_atomic: 27960a0c612SFrank Laub return llvm::AtomicOrdering::NotAtomic; 28060a0c612SFrank Laub case LLVM::AtomicOrdering::unordered: 28160a0c612SFrank Laub return llvm::AtomicOrdering::Unordered; 28260a0c612SFrank Laub case LLVM::AtomicOrdering::monotonic: 28360a0c612SFrank Laub return llvm::AtomicOrdering::Monotonic; 28460a0c612SFrank Laub case LLVM::AtomicOrdering::acquire: 28560a0c612SFrank Laub return llvm::AtomicOrdering::Acquire; 28660a0c612SFrank Laub case LLVM::AtomicOrdering::release: 28760a0c612SFrank Laub return llvm::AtomicOrdering::Release; 28860a0c612SFrank Laub case LLVM::AtomicOrdering::acq_rel: 28960a0c612SFrank Laub return llvm::AtomicOrdering::AcquireRelease; 29060a0c612SFrank Laub case LLVM::AtomicOrdering::seq_cst: 29160a0c612SFrank Laub return llvm::AtomicOrdering::SequentiallyConsistent; 29260a0c612SFrank Laub } 29360a0c612SFrank Laub llvm_unreachable("incorrect atomic ordering"); 29460a0c612SFrank Laub } 29560a0c612SFrank Laub 296c33d6970SRiver Riddle ModuleTranslation::ModuleTranslation(Operation *module, 297c33d6970SRiver Riddle std::unique_ptr<llvm::Module> llvmModule) 298c33d6970SRiver Riddle : mlirModule(module), llvmModule(std::move(llvmModule)), 299c33d6970SRiver Riddle debugTranslation( 30092a295ebSKiran Chandramohan std::make_unique<DebugTranslation>(module, *this->llvmModule)), 30192a295ebSKiran Chandramohan ompDialect( 30269040d5bSStephan Herhut module->getContext()->getRegisteredDialect<omp::OpenMPDialect>()), 30369040d5bSStephan Herhut llvmDialect(module->getContext()->getRegisteredDialect<LLVMDialect>()) { 304c33d6970SRiver Riddle assert(satisfiesLLVMModule(mlirModule) && 305c33d6970SRiver Riddle "mlirModule should honor LLVM's module semantics."); 306c33d6970SRiver Riddle } 307c33d6970SRiver Riddle ModuleTranslation::~ModuleTranslation() {} 308c33d6970SRiver Riddle 3097ecee63eSKiran Kumar T P /// Given an OpenMP MLIR operation, create the corresponding LLVM IR 3107ecee63eSKiran Kumar T P /// (including OpenMP runtime calls). 3117ecee63eSKiran Kumar T P LogicalResult 3127ecee63eSKiran Kumar T P ModuleTranslation::convertOmpOperation(Operation &opInst, 3137ecee63eSKiran Kumar T P llvm::IRBuilder<> &builder) { 3147ecee63eSKiran Kumar T P if (!ompBuilder) { 3157ecee63eSKiran Kumar T P ompBuilder = std::make_unique<llvm::OpenMPIRBuilder>(*llvmModule); 3167ecee63eSKiran Kumar T P ompBuilder->initialize(); 3177ecee63eSKiran Kumar T P } 318ebf190fcSRiver Riddle return llvm::TypeSwitch<Operation *, LogicalResult>(&opInst) 3197ecee63eSKiran Kumar T P .Case([&](omp::BarrierOp) { 3207ecee63eSKiran Kumar T P ompBuilder->CreateBarrier(builder.saveIP(), llvm::omp::OMPD_barrier); 3217ecee63eSKiran Kumar T P return success(); 3227ecee63eSKiran Kumar T P }) 3237ecee63eSKiran Kumar T P .Case([&](omp::TaskwaitOp) { 3247ecee63eSKiran Kumar T P ompBuilder->CreateTaskwait(builder.saveIP()); 3257ecee63eSKiran Kumar T P return success(); 3267ecee63eSKiran Kumar T P }) 3277ecee63eSKiran Kumar T P .Case([&](omp::TaskyieldOp) { 3287ecee63eSKiran Kumar T P ompBuilder->CreateTaskyield(builder.saveIP()); 3297ecee63eSKiran Kumar T P return success(); 3307ecee63eSKiran Kumar T P }) 331fa8fc9ffSKiran Kumar T P .Case([&](omp::FlushOp) { 332fa8fc9ffSKiran Kumar T P // No support in Openmp runtime funciton (__kmpc_flush) to accept 333fa8fc9ffSKiran Kumar T P // the argument list. 334fa8fc9ffSKiran Kumar T P // OpenMP standard states the following: 335fa8fc9ffSKiran Kumar T P // "An implementation may implement a flush with a list by ignoring 336fa8fc9ffSKiran Kumar T P // the list, and treating it the same as a flush without a list." 337fa8fc9ffSKiran Kumar T P // 338fa8fc9ffSKiran Kumar T P // The argument list is discarded so that, flush with a list is treated 339fa8fc9ffSKiran Kumar T P // same as a flush without a list. 340fa8fc9ffSKiran Kumar T P ompBuilder->CreateFlush(builder.saveIP()); 341fa8fc9ffSKiran Kumar T P return success(); 342fa8fc9ffSKiran Kumar T P }) 3437ecee63eSKiran Kumar T P .Default([&](Operation *inst) { 3447ecee63eSKiran Kumar T P return inst->emitError("unsupported OpenMP operation: ") 3457ecee63eSKiran Kumar T P << inst->getName(); 3467ecee63eSKiran Kumar T P }); 3477ecee63eSKiran Kumar T P } 3487ecee63eSKiran Kumar T P 3492666b973SRiver Riddle /// Given a single MLIR operation, create the corresponding LLVM IR operation 3502666b973SRiver Riddle /// using the `builder`. LLVM IR Builder does not have a generic interface so 3512666b973SRiver Riddle /// this has to be a long chain of `if`s calling different functions with a 3522666b973SRiver Riddle /// different number of arguments. 353baa1ec22SAlex Zinenko LogicalResult ModuleTranslation::convertOperation(Operation &opInst, 3545d7231d8SStephan Herhut llvm::IRBuilder<> &builder) { 3555d7231d8SStephan Herhut auto extractPosition = [](ArrayAttr attr) { 3565d7231d8SStephan Herhut SmallVector<unsigned, 4> position; 3575d7231d8SStephan Herhut position.reserve(attr.size()); 3585d7231d8SStephan Herhut for (Attribute v : attr) 3595d7231d8SStephan Herhut position.push_back(v.cast<IntegerAttr>().getValue().getZExtValue()); 3605d7231d8SStephan Herhut return position; 3615d7231d8SStephan Herhut }; 3625d7231d8SStephan Herhut 363ba0fa925SRiver Riddle #include "mlir/Dialect/LLVMIR/LLVMConversions.inc" 3645d7231d8SStephan Herhut 3655d7231d8SStephan Herhut // Emit function calls. If the "callee" attribute is present, this is a 3665d7231d8SStephan Herhut // direct function call and we also need to look up the remapped function 3675d7231d8SStephan Herhut // itself. Otherwise, this is an indirect call and the callee is the first 3685d7231d8SStephan Herhut // operand, look it up as a normal value. Return the llvm::Value representing 3695d7231d8SStephan Herhut // the function result, which may be of llvm::VoidTy type. 3705d7231d8SStephan Herhut auto convertCall = [this, &builder](Operation &op) -> llvm::Value * { 3715d7231d8SStephan Herhut auto operands = lookupValues(op.getOperands()); 3725d7231d8SStephan Herhut ArrayRef<llvm::Value *> operandsRef(operands); 3739b9c647cSRiver Riddle if (auto attr = op.getAttrOfType<FlatSymbolRefAttr>("callee")) { 3745d7231d8SStephan Herhut return builder.CreateCall(functionMapping.lookup(attr.getValue()), 3755d7231d8SStephan Herhut operandsRef); 3765d7231d8SStephan Herhut } else { 377133049d0SEli Friedman auto *calleePtrType = 378133049d0SEli Friedman cast<llvm::PointerType>(operandsRef.front()->getType()); 379133049d0SEli Friedman auto *calleeType = 380133049d0SEli Friedman cast<llvm::FunctionType>(calleePtrType->getElementType()); 381133049d0SEli Friedman return builder.CreateCall(calleeType, operandsRef.front(), 382133049d0SEli Friedman operandsRef.drop_front()); 3835d7231d8SStephan Herhut } 3845d7231d8SStephan Herhut }; 3855d7231d8SStephan Herhut 3865d7231d8SStephan Herhut // Emit calls. If the called function has a result, remap the corresponding 3875d7231d8SStephan Herhut // value. Note that LLVM IR dialect CallOp has either 0 or 1 result. 388d5b60ee8SRiver Riddle if (isa<LLVM::CallOp>(opInst)) { 3895d7231d8SStephan Herhut llvm::Value *result = convertCall(opInst); 3905d7231d8SStephan Herhut if (opInst.getNumResults() != 0) { 3915d7231d8SStephan Herhut valueMapping[opInst.getResult(0)] = result; 392baa1ec22SAlex Zinenko return success(); 3935d7231d8SStephan Herhut } 3945d7231d8SStephan Herhut // Check that LLVM call returns void for 0-result functions. 395baa1ec22SAlex Zinenko return success(result->getType()->isVoidTy()); 3965d7231d8SStephan Herhut } 3975d7231d8SStephan Herhut 398d242aa24SShraiysh Vaishay if (auto invOp = dyn_cast<LLVM::InvokeOp>(opInst)) { 399d242aa24SShraiysh Vaishay auto operands = lookupValues(opInst.getOperands()); 400d242aa24SShraiysh Vaishay ArrayRef<llvm::Value *> operandsRef(operands); 401133049d0SEli Friedman if (auto attr = opInst.getAttrOfType<FlatSymbolRefAttr>("callee")) { 402d242aa24SShraiysh Vaishay builder.CreateInvoke(functionMapping.lookup(attr.getValue()), 403d242aa24SShraiysh Vaishay blockMapping[invOp.getSuccessor(0)], 404d242aa24SShraiysh Vaishay blockMapping[invOp.getSuccessor(1)], operandsRef); 405133049d0SEli Friedman } else { 406133049d0SEli Friedman auto *calleePtrType = 407133049d0SEli Friedman cast<llvm::PointerType>(operandsRef.front()->getType()); 408133049d0SEli Friedman auto *calleeType = 409133049d0SEli Friedman cast<llvm::FunctionType>(calleePtrType->getElementType()); 410d242aa24SShraiysh Vaishay builder.CreateInvoke( 411133049d0SEli Friedman calleeType, operandsRef.front(), blockMapping[invOp.getSuccessor(0)], 412d242aa24SShraiysh Vaishay blockMapping[invOp.getSuccessor(1)], operandsRef.drop_front()); 413133049d0SEli Friedman } 414d242aa24SShraiysh Vaishay return success(); 415d242aa24SShraiysh Vaishay } 416d242aa24SShraiysh Vaishay 417d242aa24SShraiysh Vaishay if (auto lpOp = dyn_cast<LLVM::LandingpadOp>(opInst)) { 418d242aa24SShraiysh Vaishay llvm::Type *ty = lpOp.getType().dyn_cast<LLVMType>().getUnderlyingType(); 419d242aa24SShraiysh Vaishay llvm::LandingPadInst *lpi = 420d242aa24SShraiysh Vaishay builder.CreateLandingPad(ty, lpOp.getNumOperands()); 421d242aa24SShraiysh Vaishay 422d242aa24SShraiysh Vaishay // Add clauses 423d242aa24SShraiysh Vaishay for (auto operand : lookupValues(lpOp.getOperands())) { 424d242aa24SShraiysh Vaishay // All operands should be constant - checked by verifier 425d242aa24SShraiysh Vaishay if (auto constOperand = dyn_cast<llvm::Constant>(operand)) 426d242aa24SShraiysh Vaishay lpi->addClause(constOperand); 427d242aa24SShraiysh Vaishay } 428ff77397fSShraiysh Vaishay valueMapping[lpOp.getResult()] = lpi; 429d242aa24SShraiysh Vaishay return success(); 430d242aa24SShraiysh Vaishay } 431d242aa24SShraiysh Vaishay 4325d7231d8SStephan Herhut // Emit branches. We need to look up the remapped blocks and ignore the block 4335d7231d8SStephan Herhut // arguments that were transformed into PHI nodes. 434c5ecf991SRiver Riddle if (auto brOp = dyn_cast<LLVM::BrOp>(opInst)) { 435c0fd5e65SRiver Riddle builder.CreateBr(blockMapping[brOp.getSuccessor()]); 436baa1ec22SAlex Zinenko return success(); 4375d7231d8SStephan Herhut } 438c5ecf991SRiver Riddle if (auto condbrOp = dyn_cast<LLVM::CondBrOp>(opInst)) { 4395d7231d8SStephan Herhut builder.CreateCondBr(valueMapping.lookup(condbrOp.getOperand(0)), 4405d7231d8SStephan Herhut blockMapping[condbrOp.getSuccessor(0)], 4415d7231d8SStephan Herhut blockMapping[condbrOp.getSuccessor(1)]); 442baa1ec22SAlex Zinenko return success(); 4435d7231d8SStephan Herhut } 4445d7231d8SStephan Herhut 4452dd38b09SAlex Zinenko // Emit addressof. We need to look up the global value referenced by the 4462dd38b09SAlex Zinenko // operation and store it in the MLIR-to-LLVM value mapping. This does not 4472dd38b09SAlex Zinenko // emit any LLVM instruction. 4482dd38b09SAlex Zinenko if (auto addressOfOp = dyn_cast<LLVM::AddressOfOp>(opInst)) { 4492dd38b09SAlex Zinenko LLVM::GlobalOp global = addressOfOp.getGlobal(); 450cba733edSAlex Zinenko LLVM::LLVMFuncOp function = addressOfOp.getFunction(); 4512dd38b09SAlex Zinenko 452cba733edSAlex Zinenko // The verifier should not have allowed this. 453cba733edSAlex Zinenko assert((global || function) && 454cba733edSAlex Zinenko "referencing an undefined global or function"); 455cba733edSAlex Zinenko 456cba733edSAlex Zinenko valueMapping[addressOfOp.getResult()] = 457cba733edSAlex Zinenko global ? globalsMapping.lookup(global) 458cba733edSAlex Zinenko : functionMapping.lookup(function.getName()); 4592dd38b09SAlex Zinenko return success(); 4602dd38b09SAlex Zinenko } 4612dd38b09SAlex Zinenko 46292a295ebSKiran Chandramohan if (opInst.getDialect() == ompDialect) { 4637ecee63eSKiran Kumar T P return convertOmpOperation(opInst, builder); 46492a295ebSKiran Chandramohan } 46592a295ebSKiran Chandramohan 466baa1ec22SAlex Zinenko return opInst.emitError("unsupported or non-LLVM operation: ") 467baa1ec22SAlex Zinenko << opInst.getName(); 4685d7231d8SStephan Herhut } 4695d7231d8SStephan Herhut 4702666b973SRiver Riddle /// Convert block to LLVM IR. Unless `ignoreArguments` is set, emit PHI nodes 4712666b973SRiver Riddle /// to define values corresponding to the MLIR block arguments. These nodes 4722666b973SRiver Riddle /// are not connected to the source basic blocks, which may not exist yet. 473baa1ec22SAlex Zinenko LogicalResult ModuleTranslation::convertBlock(Block &bb, bool ignoreArguments) { 4745d7231d8SStephan Herhut llvm::IRBuilder<> builder(blockMapping[&bb]); 475c33d6970SRiver Riddle auto *subprogram = builder.GetInsertBlock()->getParent()->getSubprogram(); 4765d7231d8SStephan Herhut 4775d7231d8SStephan Herhut // Before traversing operations, make block arguments available through 4785d7231d8SStephan Herhut // value remapping and PHI nodes, but do not add incoming edges for the PHI 4795d7231d8SStephan Herhut // nodes just yet: those values may be defined by this or following blocks. 4805d7231d8SStephan Herhut // This step is omitted if "ignoreArguments" is set. The arguments of the 4815d7231d8SStephan Herhut // first block have been already made available through the remapping of 4825d7231d8SStephan Herhut // LLVM function arguments. 4835d7231d8SStephan Herhut if (!ignoreArguments) { 4845d7231d8SStephan Herhut auto predecessors = bb.getPredecessors(); 4855d7231d8SStephan Herhut unsigned numPredecessors = 4865d7231d8SStephan Herhut std::distance(predecessors.begin(), predecessors.end()); 48735807bc4SRiver Riddle for (auto arg : bb.getArguments()) { 4882bdf33ccSRiver Riddle auto wrappedType = arg.getType().dyn_cast<LLVM::LLVMType>(); 489baa1ec22SAlex Zinenko if (!wrappedType) 490baa1ec22SAlex Zinenko return emitError(bb.front().getLoc(), 491a4c3a645SRiver Riddle "block argument does not have an LLVM type"); 4925d7231d8SStephan Herhut llvm::Type *type = wrappedType.getUnderlyingType(); 4935d7231d8SStephan Herhut llvm::PHINode *phi = builder.CreatePHI(type, numPredecessors); 4945d7231d8SStephan Herhut valueMapping[arg] = phi; 4955d7231d8SStephan Herhut } 4965d7231d8SStephan Herhut } 4975d7231d8SStephan Herhut 4985d7231d8SStephan Herhut // Traverse operations. 4995d7231d8SStephan Herhut for (auto &op : bb) { 500c33d6970SRiver Riddle // Set the current debug location within the builder. 501c33d6970SRiver Riddle builder.SetCurrentDebugLocation( 502c33d6970SRiver Riddle debugTranslation->translateLoc(op.getLoc(), subprogram)); 503c33d6970SRiver Riddle 504baa1ec22SAlex Zinenko if (failed(convertOperation(op, builder))) 505baa1ec22SAlex Zinenko return failure(); 5065d7231d8SStephan Herhut } 5075d7231d8SStephan Herhut 508baa1ec22SAlex Zinenko return success(); 5095d7231d8SStephan Herhut } 5105d7231d8SStephan Herhut 5112666b973SRiver Riddle /// Create named global variables that correspond to llvm.mlir.global 5122666b973SRiver Riddle /// definitions. 513efa2d533SAlex Zinenko LogicalResult ModuleTranslation::convertGlobals() { 51469040d5bSStephan Herhut // Lock access to the llvm context. 51569040d5bSStephan Herhut llvm::sys::SmartScopedLock<true> scopedLock( 51669040d5bSStephan Herhut llvmDialect->getLLVMContextMutex()); 51744fc7d72STres Popp for (auto op : getModuleBody(mlirModule).getOps<LLVM::GlobalOp>()) { 518250a11aeSJames Molloy llvm::Type *type = op.getType().getUnderlyingType(); 519250a11aeSJames Molloy llvm::Constant *cst = llvm::UndefValue::get(type); 520250a11aeSJames Molloy if (op.getValueOrNull()) { 52168451df2SAlex Zinenko // String attributes are treated separately because they cannot appear as 52268451df2SAlex Zinenko // in-function constants and are thus not supported by getLLVMConstant. 52333a3a91bSChristian Sigg if (auto strAttr = op.getValueOrNull().dyn_cast_or_null<StringAttr>()) { 5242dd38b09SAlex Zinenko cst = llvm::ConstantDataArray::getString( 52568451df2SAlex Zinenko llvmModule->getContext(), strAttr.getValue(), /*AddNull=*/false); 5262dd38b09SAlex Zinenko type = cst->getType(); 527efa2d533SAlex Zinenko } else if (!(cst = getLLVMConstant(type, op.getValueOrNull(), 528efa2d533SAlex Zinenko op.getLoc()))) { 529efa2d533SAlex Zinenko return failure(); 53068451df2SAlex Zinenko } 531250a11aeSJames Molloy } else if (Block *initializer = op.getInitializerBlock()) { 532250a11aeSJames Molloy llvm::IRBuilder<> builder(llvmModule->getContext()); 533250a11aeSJames Molloy for (auto &op : initializer->without_terminator()) { 534250a11aeSJames Molloy if (failed(convertOperation(op, builder)) || 535efa2d533SAlex Zinenko !isa<llvm::Constant>(valueMapping.lookup(op.getResult(0)))) 536efa2d533SAlex Zinenko return emitError(op.getLoc(), "unemittable constant value"); 537250a11aeSJames Molloy } 538250a11aeSJames Molloy ReturnOp ret = cast<ReturnOp>(initializer->getTerminator()); 539250a11aeSJames Molloy cst = cast<llvm::Constant>(valueMapping.lookup(ret.getOperand(0))); 540250a11aeSJames Molloy } 54168451df2SAlex Zinenko 542eb67bd78SAlex Zinenko auto linkage = convertLinkageToLLVM(op.linkage()); 543d5e627f8SAlex Zinenko bool anyExternalLinkage = 5447b5d4669SEric Schweitz ((linkage == llvm::GlobalVariable::ExternalLinkage && 5457b5d4669SEric Schweitz isa<llvm::UndefValue>(cst)) || 546d5e627f8SAlex Zinenko linkage == llvm::GlobalVariable::ExternalWeakLinkage); 547e79bfefbSMLIR Team auto addrSpace = op.addr_space().getLimitedValue(); 548e79bfefbSMLIR Team auto *var = new llvm::GlobalVariable( 549d5e627f8SAlex Zinenko *llvmModule, type, op.constant(), linkage, 550d5e627f8SAlex Zinenko anyExternalLinkage ? nullptr : cst, op.sym_name(), 551d5e627f8SAlex Zinenko /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal, addrSpace); 552e79bfefbSMLIR Team 5532dd38b09SAlex Zinenko globalsMapping.try_emplace(op, var); 554b9ff2dd8SAlex Zinenko } 555efa2d533SAlex Zinenko 556efa2d533SAlex Zinenko return success(); 557b9ff2dd8SAlex Zinenko } 558b9ff2dd8SAlex Zinenko 5592666b973SRiver Riddle /// Get the SSA value passed to the current block from the terminator operation 5602666b973SRiver Riddle /// of its predecessor. 561e62a6956SRiver Riddle static Value getPHISourceValue(Block *current, Block *pred, 5625d7231d8SStephan Herhut unsigned numArguments, unsigned index) { 5635d7231d8SStephan Herhut auto &terminator = *pred->getTerminator(); 564d5b60ee8SRiver Riddle if (isa<LLVM::BrOp>(terminator)) { 5655d7231d8SStephan Herhut return terminator.getOperand(index); 5665d7231d8SStephan Herhut } 5675d7231d8SStephan Herhut 5685d7231d8SStephan Herhut // For conditional branches, we need to check if the current block is reached 5695d7231d8SStephan Herhut // through the "true" or the "false" branch and take the relevant operands. 570c5ecf991SRiver Riddle auto condBranchOp = dyn_cast<LLVM::CondBrOp>(terminator); 5715d7231d8SStephan Herhut assert(condBranchOp && 5725d7231d8SStephan Herhut "only branch operations can be terminators of a block that " 5735d7231d8SStephan Herhut "has successors"); 5745d7231d8SStephan Herhut assert((condBranchOp.getSuccessor(0) != condBranchOp.getSuccessor(1)) && 5755d7231d8SStephan Herhut "successors with arguments in LLVM conditional branches must be " 5765d7231d8SStephan Herhut "different blocks"); 5775d7231d8SStephan Herhut 5785d7231d8SStephan Herhut return condBranchOp.getSuccessor(0) == current 579988249a5SRiver Riddle ? condBranchOp.trueDestOperands()[index] 580988249a5SRiver Riddle : condBranchOp.falseDestOperands()[index]; 5815d7231d8SStephan Herhut } 5825d7231d8SStephan Herhut 5835e7959a3SAlex Zinenko void ModuleTranslation::connectPHINodes(LLVMFuncOp func) { 5845d7231d8SStephan Herhut // Skip the first block, it cannot be branched to and its arguments correspond 5855d7231d8SStephan Herhut // to the arguments of the LLVM function. 5865d7231d8SStephan Herhut for (auto it = std::next(func.begin()), eit = func.end(); it != eit; ++it) { 5875d7231d8SStephan Herhut Block *bb = &*it; 5885d7231d8SStephan Herhut llvm::BasicBlock *llvmBB = blockMapping.lookup(bb); 5895d7231d8SStephan Herhut auto phis = llvmBB->phis(); 5905d7231d8SStephan Herhut auto numArguments = bb->getNumArguments(); 5915d7231d8SStephan Herhut assert(numArguments == std::distance(phis.begin(), phis.end())); 5925d7231d8SStephan Herhut for (auto &numberedPhiNode : llvm::enumerate(phis)) { 5935d7231d8SStephan Herhut auto &phiNode = numberedPhiNode.value(); 5945d7231d8SStephan Herhut unsigned index = numberedPhiNode.index(); 5955d7231d8SStephan Herhut for (auto *pred : bb->getPredecessors()) { 5965d7231d8SStephan Herhut phiNode.addIncoming(valueMapping.lookup(getPHISourceValue( 5975d7231d8SStephan Herhut bb, pred, numArguments, index)), 5985d7231d8SStephan Herhut blockMapping.lookup(pred)); 5995d7231d8SStephan Herhut } 6005d7231d8SStephan Herhut } 6015d7231d8SStephan Herhut } 6025d7231d8SStephan Herhut } 6035d7231d8SStephan Herhut 6045d7231d8SStephan Herhut // TODO(mlir-team): implement an iterative version 6055d7231d8SStephan Herhut static void topologicalSortImpl(llvm::SetVector<Block *> &blocks, Block *b) { 6065d7231d8SStephan Herhut blocks.insert(b); 6075d7231d8SStephan Herhut for (Block *bb : b->getSuccessors()) { 6085d7231d8SStephan Herhut if (blocks.count(bb) == 0) 6095d7231d8SStephan Herhut topologicalSortImpl(blocks, bb); 6105d7231d8SStephan Herhut } 6115d7231d8SStephan Herhut } 6125d7231d8SStephan Herhut 6132666b973SRiver Riddle /// Sort function blocks topologically. 6145e7959a3SAlex Zinenko static llvm::SetVector<Block *> topologicalSort(LLVMFuncOp f) { 6155d7231d8SStephan Herhut // For each blocks that has not been visited yet (i.e. that has no 6165d7231d8SStephan Herhut // predecessors), add it to the list and traverse its successors in DFS 6175d7231d8SStephan Herhut // preorder. 6185d7231d8SStephan Herhut llvm::SetVector<Block *> blocks; 619d1506620SRahul Joshi for (Block &b : f) { 6205d7231d8SStephan Herhut if (blocks.count(&b) == 0) 6215d7231d8SStephan Herhut topologicalSortImpl(blocks, &b); 6225d7231d8SStephan Herhut } 6235d7231d8SStephan Herhut assert(blocks.size() == f.getBlocks().size() && "some blocks are not sorted"); 6245d7231d8SStephan Herhut 6255d7231d8SStephan Herhut return blocks; 6265d7231d8SStephan Herhut } 6275d7231d8SStephan Herhut 6280a2131b7SAlex Zinenko /// Attempts to add an attribute identified by `key`, optionally with the given 6290a2131b7SAlex Zinenko /// `value` to LLVM function `llvmFunc`. Reports errors at `loc` if any. If the 6300a2131b7SAlex Zinenko /// attribute has a kind known to LLVM IR, create the attribute of this kind, 6310a2131b7SAlex Zinenko /// otherwise keep it as a string attribute. Performs additional checks for 6320a2131b7SAlex Zinenko /// attributes known to have or not have a value in order to avoid assertions 6330a2131b7SAlex Zinenko /// inside LLVM upon construction. 6340a2131b7SAlex Zinenko static LogicalResult checkedAddLLVMFnAttribute(Location loc, 6350a2131b7SAlex Zinenko llvm::Function *llvmFunc, 6360a2131b7SAlex Zinenko StringRef key, 6370a2131b7SAlex Zinenko StringRef value = StringRef()) { 6380a2131b7SAlex Zinenko auto kind = llvm::Attribute::getAttrKindFromName(key); 6390a2131b7SAlex Zinenko if (kind == llvm::Attribute::None) { 6400a2131b7SAlex Zinenko llvmFunc->addFnAttr(key, value); 6410a2131b7SAlex Zinenko return success(); 6420a2131b7SAlex Zinenko } 6430a2131b7SAlex Zinenko 6440a2131b7SAlex Zinenko if (llvm::Attribute::doesAttrKindHaveArgument(kind)) { 6450a2131b7SAlex Zinenko if (value.empty()) 6460a2131b7SAlex Zinenko return emitError(loc) << "LLVM attribute '" << key << "' expects a value"; 6470a2131b7SAlex Zinenko 6480a2131b7SAlex Zinenko int result; 6490a2131b7SAlex Zinenko if (!value.getAsInteger(/*Radix=*/0, result)) 6500a2131b7SAlex Zinenko llvmFunc->addFnAttr( 6510a2131b7SAlex Zinenko llvm::Attribute::get(llvmFunc->getContext(), kind, result)); 6520a2131b7SAlex Zinenko else 6530a2131b7SAlex Zinenko llvmFunc->addFnAttr(key, value); 6540a2131b7SAlex Zinenko return success(); 6550a2131b7SAlex Zinenko } 6560a2131b7SAlex Zinenko 6570a2131b7SAlex Zinenko if (!value.empty()) 6580a2131b7SAlex Zinenko return emitError(loc) << "LLVM attribute '" << key 6590a2131b7SAlex Zinenko << "' does not expect a value, found '" << value 6600a2131b7SAlex Zinenko << "'"; 6610a2131b7SAlex Zinenko 6620a2131b7SAlex Zinenko llvmFunc->addFnAttr(kind); 6630a2131b7SAlex Zinenko return success(); 6640a2131b7SAlex Zinenko } 6650a2131b7SAlex Zinenko 6660a2131b7SAlex Zinenko /// Attaches the attributes listed in the given array attribute to `llvmFunc`. 6670a2131b7SAlex Zinenko /// Reports error to `loc` if any and returns immediately. Expects `attributes` 6680a2131b7SAlex Zinenko /// to be an array attribute containing either string attributes, treated as 6690a2131b7SAlex Zinenko /// value-less LLVM attributes, or array attributes containing two string 6700a2131b7SAlex Zinenko /// attributes, with the first string being the name of the corresponding LLVM 6710a2131b7SAlex Zinenko /// attribute and the second string beings its value. Note that even integer 6720a2131b7SAlex Zinenko /// attributes are expected to have their values expressed as strings. 6730a2131b7SAlex Zinenko static LogicalResult 6740a2131b7SAlex Zinenko forwardPassthroughAttributes(Location loc, Optional<ArrayAttr> attributes, 6750a2131b7SAlex Zinenko llvm::Function *llvmFunc) { 6760a2131b7SAlex Zinenko if (!attributes) 6770a2131b7SAlex Zinenko return success(); 6780a2131b7SAlex Zinenko 6790a2131b7SAlex Zinenko for (Attribute attr : *attributes) { 6800a2131b7SAlex Zinenko if (auto stringAttr = attr.dyn_cast<StringAttr>()) { 6810a2131b7SAlex Zinenko if (failed( 6820a2131b7SAlex Zinenko checkedAddLLVMFnAttribute(loc, llvmFunc, stringAttr.getValue()))) 6830a2131b7SAlex Zinenko return failure(); 6840a2131b7SAlex Zinenko continue; 6850a2131b7SAlex Zinenko } 6860a2131b7SAlex Zinenko 6870a2131b7SAlex Zinenko auto arrayAttr = attr.dyn_cast<ArrayAttr>(); 6880a2131b7SAlex Zinenko if (!arrayAttr || arrayAttr.size() != 2) 6890a2131b7SAlex Zinenko return emitError(loc) 6900a2131b7SAlex Zinenko << "expected 'passthrough' to contain string or array attributes"; 6910a2131b7SAlex Zinenko 6920a2131b7SAlex Zinenko auto keyAttr = arrayAttr[0].dyn_cast<StringAttr>(); 6930a2131b7SAlex Zinenko auto valueAttr = arrayAttr[1].dyn_cast<StringAttr>(); 6940a2131b7SAlex Zinenko if (!keyAttr || !valueAttr) 6950a2131b7SAlex Zinenko return emitError(loc) 6960a2131b7SAlex Zinenko << "expected arrays within 'passthrough' to contain two strings"; 6970a2131b7SAlex Zinenko 6980a2131b7SAlex Zinenko if (failed(checkedAddLLVMFnAttribute(loc, llvmFunc, keyAttr.getValue(), 6990a2131b7SAlex Zinenko valueAttr.getValue()))) 7000a2131b7SAlex Zinenko return failure(); 7010a2131b7SAlex Zinenko } 7020a2131b7SAlex Zinenko return success(); 7030a2131b7SAlex Zinenko } 7040a2131b7SAlex Zinenko 7055e7959a3SAlex Zinenko LogicalResult ModuleTranslation::convertOneFunction(LLVMFuncOp func) { 7065d7231d8SStephan Herhut // Clear the block and value mappings, they are only relevant within one 7075d7231d8SStephan Herhut // function. 7085d7231d8SStephan Herhut blockMapping.clear(); 7095d7231d8SStephan Herhut valueMapping.clear(); 710c33862b0SRiver Riddle llvm::Function *llvmFunc = functionMapping.lookup(func.getName()); 711c33d6970SRiver Riddle 712c33d6970SRiver Riddle // Translate the debug information for this function. 713c33d6970SRiver Riddle debugTranslation->translate(func, *llvmFunc); 714c33d6970SRiver Riddle 7155d7231d8SStephan Herhut // Add function arguments to the value remapping table. 7165d7231d8SStephan Herhut // If there was noalias info then we decorate each argument accordingly. 7175d7231d8SStephan Herhut unsigned int argIdx = 0; 718eeef50b1SFangrui Song for (auto kvp : llvm::zip(func.getArguments(), llvmFunc->args())) { 7195d7231d8SStephan Herhut llvm::Argument &llvmArg = std::get<1>(kvp); 720e62a6956SRiver Riddle BlockArgument mlirArg = std::get<0>(kvp); 7215d7231d8SStephan Herhut 7225d7231d8SStephan Herhut if (auto attr = func.getArgAttrOfType<BoolAttr>(argIdx, "llvm.noalias")) { 7235d7231d8SStephan Herhut // NB: Attribute already verified to be boolean, so check if we can indeed 7245d7231d8SStephan Herhut // attach the attribute to this argument, based on its type. 7252bdf33ccSRiver Riddle auto argTy = mlirArg.getType().dyn_cast<LLVM::LLVMType>(); 726baa1ec22SAlex Zinenko if (!argTy.getUnderlyingType()->isPointerTy()) 727baa1ec22SAlex Zinenko return func.emitError( 7285d7231d8SStephan Herhut "llvm.noalias attribute attached to LLVM non-pointer argument"); 7295d7231d8SStephan Herhut if (attr.getValue()) 7305d7231d8SStephan Herhut llvmArg.addAttr(llvm::Attribute::AttrKind::NoAlias); 7315d7231d8SStephan Herhut } 7322416e28cSStephan Herhut 7332416e28cSStephan Herhut if (auto attr = func.getArgAttrOfType<IntegerAttr>(argIdx, "llvm.align")) { 7342416e28cSStephan Herhut // NB: Attribute already verified to be int, so check if we can indeed 7352416e28cSStephan Herhut // attach the attribute to this argument, based on its type. 7362416e28cSStephan Herhut auto argTy = mlirArg.getType().dyn_cast<LLVM::LLVMType>(); 7372416e28cSStephan Herhut if (!argTy.getUnderlyingType()->isPointerTy()) 7382416e28cSStephan Herhut return func.emitError( 7392416e28cSStephan Herhut "llvm.align attribute attached to LLVM non-pointer argument"); 7402416e28cSStephan Herhut llvmArg.addAttrs( 7412416e28cSStephan Herhut llvm::AttrBuilder().addAlignmentAttr(llvm::Align(attr.getInt()))); 7422416e28cSStephan Herhut } 7432416e28cSStephan Herhut 7445d7231d8SStephan Herhut valueMapping[mlirArg] = &llvmArg; 7455d7231d8SStephan Herhut argIdx++; 7465d7231d8SStephan Herhut } 7475d7231d8SStephan Herhut 748ff77397fSShraiysh Vaishay // Check the personality and set it. 749ff77397fSShraiysh Vaishay if (func.personality().hasValue()) { 750ff77397fSShraiysh Vaishay llvm::Type *ty = llvm::Type::getInt8PtrTy(llvmFunc->getContext()); 751ff77397fSShraiysh Vaishay if (llvm::Constant *pfunc = 752ff77397fSShraiysh Vaishay getLLVMConstant(ty, func.personalityAttr(), func.getLoc())) 753ff77397fSShraiysh Vaishay llvmFunc->setPersonalityFn(pfunc); 754ff77397fSShraiysh Vaishay } 755ff77397fSShraiysh Vaishay 7565d7231d8SStephan Herhut // First, create all blocks so we can jump to them. 7575d7231d8SStephan Herhut llvm::LLVMContext &llvmContext = llvmFunc->getContext(); 7585d7231d8SStephan Herhut for (auto &bb : func) { 7595d7231d8SStephan Herhut auto *llvmBB = llvm::BasicBlock::Create(llvmContext); 7605d7231d8SStephan Herhut llvmBB->insertInto(llvmFunc); 7615d7231d8SStephan Herhut blockMapping[&bb] = llvmBB; 7625d7231d8SStephan Herhut } 7635d7231d8SStephan Herhut 7645d7231d8SStephan Herhut // Then, convert blocks one by one in topological order to ensure defs are 7655d7231d8SStephan Herhut // converted before uses. 7665d7231d8SStephan Herhut auto blocks = topologicalSort(func); 7675d7231d8SStephan Herhut for (auto indexedBB : llvm::enumerate(blocks)) { 7685d7231d8SStephan Herhut auto *bb = indexedBB.value(); 769baa1ec22SAlex Zinenko if (failed(convertBlock(*bb, /*ignoreArguments=*/indexedBB.index() == 0))) 770baa1ec22SAlex Zinenko return failure(); 7715d7231d8SStephan Herhut } 7725d7231d8SStephan Herhut 7735d7231d8SStephan Herhut // Finally, after all blocks have been traversed and values mapped, connect 7745d7231d8SStephan Herhut // the PHI nodes to the results of preceding blocks. 7755d7231d8SStephan Herhut connectPHINodes(func); 776baa1ec22SAlex Zinenko return success(); 7775d7231d8SStephan Herhut } 7785d7231d8SStephan Herhut 77944fc7d72STres Popp LogicalResult ModuleTranslation::checkSupportedModuleOps(Operation *m) { 78044fc7d72STres Popp for (Operation &o : getModuleBody(m).getOperations()) 781*ee394e68SRahul Joshi if (!isa<LLVM::LLVMFuncOp, LLVM::GlobalOp>(&o) && !o.isKnownTerminator()) 7824dde19f0SAlex Zinenko return o.emitOpError("unsupported module-level operation"); 7834dde19f0SAlex Zinenko return success(); 7844dde19f0SAlex Zinenko } 7854dde19f0SAlex Zinenko 786baa1ec22SAlex Zinenko LogicalResult ModuleTranslation::convertFunctions() { 78769040d5bSStephan Herhut // Lock access to the llvm context. 78869040d5bSStephan Herhut llvm::sys::SmartScopedLock<true> scopedLock( 78969040d5bSStephan Herhut llvmDialect->getLLVMContextMutex()); 7905d7231d8SStephan Herhut // Declare all functions first because there may be function calls that form a 7915d7231d8SStephan Herhut // call graph with cycles. 79244fc7d72STres Popp for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) { 7935e7959a3SAlex Zinenko llvm::FunctionCallee llvmFuncCst = llvmModule->getOrInsertFunction( 7945e7959a3SAlex Zinenko function.getName(), 7954562e389SRiver Riddle cast<llvm::FunctionType>(function.getType().getUnderlyingType())); 7960a2131b7SAlex Zinenko llvm::Function *llvmFunc = cast<llvm::Function>(llvmFuncCst.getCallee()); 7970a2131b7SAlex Zinenko functionMapping[function.getName()] = llvmFunc; 7980a2131b7SAlex Zinenko 7990a2131b7SAlex Zinenko // Forward the pass-through attributes to LLVM. 8000a2131b7SAlex Zinenko if (failed(forwardPassthroughAttributes(function.getLoc(), 8010a2131b7SAlex Zinenko function.passthrough(), llvmFunc))) 8020a2131b7SAlex Zinenko return failure(); 8035d7231d8SStephan Herhut } 8045d7231d8SStephan Herhut 8055d7231d8SStephan Herhut // Convert functions. 80644fc7d72STres Popp for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) { 8075d7231d8SStephan Herhut // Ignore external functions. 8085d7231d8SStephan Herhut if (function.isExternal()) 8095d7231d8SStephan Herhut continue; 8105d7231d8SStephan Herhut 811baa1ec22SAlex Zinenko if (failed(convertOneFunction(function))) 812baa1ec22SAlex Zinenko return failure(); 8135d7231d8SStephan Herhut } 8145d7231d8SStephan Herhut 815baa1ec22SAlex Zinenko return success(); 8165d7231d8SStephan Herhut } 8175d7231d8SStephan Herhut 818efadb6b8SAlex Zinenko /// A helper to look up remapped operands in the value remapping table.` 819efadb6b8SAlex Zinenko SmallVector<llvm::Value *, 8> 820efadb6b8SAlex Zinenko ModuleTranslation::lookupValues(ValueRange values) { 821efadb6b8SAlex Zinenko SmallVector<llvm::Value *, 8> remapped; 822efadb6b8SAlex Zinenko remapped.reserve(values.size()); 823ff77397fSShraiysh Vaishay for (Value v : values) { 824ff77397fSShraiysh Vaishay assert(valueMapping.count(v) && "referencing undefined value"); 825efadb6b8SAlex Zinenko remapped.push_back(valueMapping.lookup(v)); 826ff77397fSShraiysh Vaishay } 827efadb6b8SAlex Zinenko return remapped; 828efadb6b8SAlex Zinenko } 829efadb6b8SAlex Zinenko 83044fc7d72STres Popp std::unique_ptr<llvm::Module> 83144fc7d72STres Popp ModuleTranslation::prepareLLVMModule(Operation *m) { 83244fc7d72STres Popp auto *dialect = m->getContext()->getRegisteredDialect<LLVM::LLVMDialect>(); 8335d7231d8SStephan Herhut assert(dialect && "LLVM dialect must be registered"); 83469040d5bSStephan Herhut // Lock the LLVM context as we might create new types here. 83569040d5bSStephan Herhut llvm::sys::SmartScopedLock<true> scopedLock(dialect->getLLVMContextMutex()); 8365d7231d8SStephan Herhut 837bc5c7378SRiver Riddle auto llvmModule = llvm::CloneModule(dialect->getLLVMModule()); 8385d7231d8SStephan Herhut if (!llvmModule) 8395d7231d8SStephan Herhut return nullptr; 8405d7231d8SStephan Herhut 8415d7231d8SStephan Herhut llvm::LLVMContext &llvmContext = llvmModule->getContext(); 8425d7231d8SStephan Herhut llvm::IRBuilder<> builder(llvmContext); 8435d7231d8SStephan Herhut 8445d7231d8SStephan Herhut // Inject declarations for `malloc` and `free` functions that can be used in 8455d7231d8SStephan Herhut // memref allocation/deallocation coming from standard ops lowering. 8465d7231d8SStephan Herhut llvmModule->getOrInsertFunction("malloc", builder.getInt8PtrTy(), 8475d7231d8SStephan Herhut builder.getInt64Ty()); 8485d7231d8SStephan Herhut llvmModule->getOrInsertFunction("free", builder.getVoidTy(), 8495d7231d8SStephan Herhut builder.getInt8PtrTy()); 8505d7231d8SStephan Herhut 8515d7231d8SStephan Herhut return llvmModule; 8525d7231d8SStephan Herhut } 853