1cde4d5a6SJacques Pienaar //===- ModuleTranslation.cpp - MLIR to LLVM conversion --------------------===// 25d7231d8SStephan Herhut // 35d7231d8SStephan Herhut // Copyright 2019 The MLIR Authors. 45d7231d8SStephan Herhut // 55d7231d8SStephan Herhut // Licensed under the Apache License, Version 2.0 (the "License"); 65d7231d8SStephan Herhut // you may not use this file except in compliance with the License. 75d7231d8SStephan Herhut // You may obtain a copy of the License at 85d7231d8SStephan Herhut // 95d7231d8SStephan Herhut // http://www.apache.org/licenses/LICENSE-2.0 105d7231d8SStephan Herhut // 115d7231d8SStephan Herhut // Unless required by applicable law or agreed to in writing, software 125d7231d8SStephan Herhut // distributed under the License is distributed on an "AS IS" BASIS, 135d7231d8SStephan Herhut // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 145d7231d8SStephan Herhut // See the License for the specific language governing permissions and 155d7231d8SStephan Herhut // limitations under the License. 165d7231d8SStephan Herhut // ============================================================================= 175d7231d8SStephan Herhut // 185d7231d8SStephan Herhut // This file implements the translation between an MLIR LLVM dialect module and 195d7231d8SStephan Herhut // the corresponding LLVMIR module. It only handles core LLVM IR operations. 205d7231d8SStephan Herhut // 215d7231d8SStephan Herhut //===----------------------------------------------------------------------===// 225d7231d8SStephan Herhut 235d7231d8SStephan Herhut #include "mlir/Target/LLVMIR/ModuleTranslation.h" 245d7231d8SStephan Herhut 255d7231d8SStephan Herhut #include "mlir/IR/Attributes.h" 265d7231d8SStephan Herhut #include "mlir/IR/Module.h" 275d7231d8SStephan Herhut #include "mlir/LLVMIR/LLVMDialect.h" 285d7231d8SStephan Herhut #include "mlir/StandardOps/Ops.h" 295d7231d8SStephan Herhut #include "mlir/Support/LLVM.h" 305d7231d8SStephan Herhut 315d7231d8SStephan Herhut #include "llvm/ADT/SetVector.h" 325d7231d8SStephan Herhut #include "llvm/IR/BasicBlock.h" 335d7231d8SStephan Herhut #include "llvm/IR/Constants.h" 345d7231d8SStephan Herhut #include "llvm/IR/DerivedTypes.h" 355d7231d8SStephan Herhut #include "llvm/IR/IRBuilder.h" 365d7231d8SStephan Herhut #include "llvm/IR/LLVMContext.h" 375d7231d8SStephan Herhut #include "llvm/IR/Module.h" 385d7231d8SStephan Herhut #include "llvm/Transforms/Utils/Cloning.h" 395d7231d8SStephan Herhut 405d7231d8SStephan Herhut namespace mlir { 415d7231d8SStephan Herhut namespace LLVM { 425d7231d8SStephan Herhut 435d7231d8SStephan Herhut // Convert an MLIR function type to LLVM IR. Arguments of the function must of 445d7231d8SStephan Herhut // MLIR LLVM IR dialect types. Use `loc` as a location when reporting errors. 455d7231d8SStephan Herhut // Return nullptr on errors. 465d7231d8SStephan Herhut static llvm::FunctionType *convertFunctionType(llvm::LLVMContext &llvmContext, 475d7231d8SStephan Herhut FunctionType type, Location loc, 485d7231d8SStephan Herhut bool isVarArgs) { 495d7231d8SStephan Herhut assert(type && "expected non-null type"); 505d7231d8SStephan Herhut 515d7231d8SStephan Herhut auto context = type.getContext(); 525d7231d8SStephan Herhut if (type.getNumResults() > 1) 535d7231d8SStephan Herhut return context->emitError(loc, 545d7231d8SStephan Herhut "LLVM functions can only have 0 or 1 result"), 555d7231d8SStephan Herhut nullptr; 565d7231d8SStephan Herhut 575d7231d8SStephan Herhut SmallVector<llvm::Type *, 8> argTypes; 585d7231d8SStephan Herhut argTypes.reserve(type.getNumInputs()); 595d7231d8SStephan Herhut for (auto t : type.getInputs()) { 605d7231d8SStephan Herhut auto wrappedLLVMType = t.dyn_cast<LLVM::LLVMType>(); 615d7231d8SStephan Herhut if (!wrappedLLVMType) 625d7231d8SStephan Herhut return context->emitError(loc, "non-LLVM function argument type"), 635d7231d8SStephan Herhut nullptr; 645d7231d8SStephan Herhut argTypes.push_back(wrappedLLVMType.getUnderlyingType()); 655d7231d8SStephan Herhut } 665d7231d8SStephan Herhut 675d7231d8SStephan Herhut if (type.getNumResults() == 0) 685d7231d8SStephan Herhut return llvm::FunctionType::get(llvm::Type::getVoidTy(llvmContext), argTypes, 695d7231d8SStephan Herhut isVarArgs); 705d7231d8SStephan Herhut 715d7231d8SStephan Herhut auto wrappedResultType = type.getResult(0).dyn_cast<LLVM::LLVMType>(); 725d7231d8SStephan Herhut if (!wrappedResultType) 735d7231d8SStephan Herhut return context->emitError(loc, "non-LLVM function result"), nullptr; 745d7231d8SStephan Herhut 755d7231d8SStephan Herhut return llvm::FunctionType::get(wrappedResultType.getUnderlyingType(), 765d7231d8SStephan Herhut argTypes, isVarArgs); 775d7231d8SStephan Herhut } 785d7231d8SStephan Herhut 795d7231d8SStephan Herhut // Create an LLVM IR constant of `llvmType` from the MLIR attribute `attr`. 805d7231d8SStephan Herhut // This currently supports integer, floating point, splat and dense element 815d7231d8SStephan Herhut // attributes and combinations thereof. In case of error, report it to `loc` 825d7231d8SStephan Herhut // and return nullptr. 835d7231d8SStephan Herhut llvm::Constant *ModuleTranslation::getLLVMConstant(llvm::Type *llvmType, 845d7231d8SStephan Herhut Attribute attr, 855d7231d8SStephan Herhut Location loc) { 865d7231d8SStephan Herhut if (auto intAttr = attr.dyn_cast<IntegerAttr>()) 875d7231d8SStephan Herhut return llvm::ConstantInt::get(llvmType, intAttr.getValue()); 885d7231d8SStephan Herhut if (auto floatAttr = attr.dyn_cast<FloatAttr>()) 895d7231d8SStephan Herhut return llvm::ConstantFP::get(llvmType, floatAttr.getValue()); 905d7231d8SStephan Herhut if (auto funcAttr = attr.dyn_cast<FunctionAttr>()) 915d7231d8SStephan Herhut return functionMapping.lookup(funcAttr.getValue()); 925d7231d8SStephan Herhut if (auto splatAttr = attr.dyn_cast<SplatElementsAttr>()) { 935d7231d8SStephan Herhut auto *vectorType = cast<llvm::VectorType>(llvmType); 945d7231d8SStephan Herhut auto *child = getLLVMConstant(vectorType->getElementType(), 95*30bbd910SRiver Riddle splatAttr.getSplatValue(), loc); 965d7231d8SStephan Herhut return llvm::ConstantVector::getSplat(vectorType->getNumElements(), child); 975d7231d8SStephan Herhut } 985d7231d8SStephan Herhut if (auto denseAttr = attr.dyn_cast<DenseElementsAttr>()) { 995d7231d8SStephan Herhut auto *vectorType = cast<llvm::VectorType>(llvmType); 1005d7231d8SStephan Herhut SmallVector<llvm::Constant *, 8> constants; 1015d7231d8SStephan Herhut uint64_t numElements = vectorType->getNumElements(); 1025d7231d8SStephan Herhut constants.reserve(numElements); 1035d7231d8SStephan Herhut SmallVector<Attribute, 8> nested; 1045d7231d8SStephan Herhut denseAttr.getValues(nested); 1055d7231d8SStephan Herhut for (auto n : nested) { 1065d7231d8SStephan Herhut constants.push_back( 1075d7231d8SStephan Herhut getLLVMConstant(vectorType->getElementType(), n, loc)); 1085d7231d8SStephan Herhut if (!constants.back()) 1095d7231d8SStephan Herhut return nullptr; 1105d7231d8SStephan Herhut } 1115d7231d8SStephan Herhut return llvm::ConstantVector::get(constants); 1125d7231d8SStephan Herhut } 113cb348dffSStephan Herhut if (auto stringAttr = attr.dyn_cast<StringAttr>()) { 114cb348dffSStephan Herhut return llvm::ConstantDataArray::get( 115cb348dffSStephan Herhut llvmModule->getContext(), ArrayRef<char>{stringAttr.getValue().data(), 116cb348dffSStephan Herhut stringAttr.getValue().size()}); 117cb348dffSStephan Herhut } 1185d7231d8SStephan Herhut mlirModule.getContext()->emitError(loc, "unsupported constant value"); 1195d7231d8SStephan Herhut return nullptr; 1205d7231d8SStephan Herhut } 1215d7231d8SStephan Herhut 1225d7231d8SStephan Herhut // Convert MLIR integer comparison predicate to LLVM IR comparison predicate. 1235d7231d8SStephan Herhut static llvm::CmpInst::Predicate getLLVMCmpPredicate(CmpIPredicate p) { 1245d7231d8SStephan Herhut switch (p) { 1255d7231d8SStephan Herhut case CmpIPredicate::EQ: 1265d7231d8SStephan Herhut return llvm::CmpInst::Predicate::ICMP_EQ; 1275d7231d8SStephan Herhut case CmpIPredicate::NE: 1285d7231d8SStephan Herhut return llvm::CmpInst::Predicate::ICMP_NE; 1295d7231d8SStephan Herhut case CmpIPredicate::SLT: 1305d7231d8SStephan Herhut return llvm::CmpInst::Predicate::ICMP_SLT; 1315d7231d8SStephan Herhut case CmpIPredicate::SLE: 1325d7231d8SStephan Herhut return llvm::CmpInst::Predicate::ICMP_SLE; 1335d7231d8SStephan Herhut case CmpIPredicate::SGT: 1345d7231d8SStephan Herhut return llvm::CmpInst::Predicate::ICMP_SGT; 1355d7231d8SStephan Herhut case CmpIPredicate::SGE: 1365d7231d8SStephan Herhut return llvm::CmpInst::Predicate::ICMP_SGE; 1375d7231d8SStephan Herhut case CmpIPredicate::ULT: 1385d7231d8SStephan Herhut return llvm::CmpInst::Predicate::ICMP_ULT; 1395d7231d8SStephan Herhut case CmpIPredicate::ULE: 1405d7231d8SStephan Herhut return llvm::CmpInst::Predicate::ICMP_ULE; 1415d7231d8SStephan Herhut case CmpIPredicate::UGT: 1425d7231d8SStephan Herhut return llvm::CmpInst::Predicate::ICMP_UGT; 1435d7231d8SStephan Herhut case CmpIPredicate::UGE: 1445d7231d8SStephan Herhut return llvm::CmpInst::Predicate::ICMP_UGE; 1455d7231d8SStephan Herhut default: 1465d7231d8SStephan Herhut llvm_unreachable("incorrect comparison predicate"); 1475d7231d8SStephan Herhut } 1485d7231d8SStephan Herhut } 1495d7231d8SStephan Herhut 1505d7231d8SStephan Herhut // A helper to look up remapped operands in the value remapping table. 1515d7231d8SStephan Herhut template <typename Range> 1525d7231d8SStephan Herhut SmallVector<llvm::Value *, 8> ModuleTranslation::lookupValues(Range &&values) { 1535d7231d8SStephan Herhut SmallVector<llvm::Value *, 8> remapped; 1545d7231d8SStephan Herhut remapped.reserve(llvm::size(values)); 1555d7231d8SStephan Herhut for (Value *v : values) { 1565d7231d8SStephan Herhut remapped.push_back(valueMapping.lookup(v)); 1575d7231d8SStephan Herhut } 1585d7231d8SStephan Herhut return remapped; 1595d7231d8SStephan Herhut } 1605d7231d8SStephan Herhut 1615d7231d8SStephan Herhut // Given a single MLIR operation, create the corresponding LLVM IR operation 1625d7231d8SStephan Herhut // using the `builder`. LLVM IR Builder does not have a generic interface so 1635d7231d8SStephan Herhut // this has to be a long chain of `if`s calling different functions with a 1645d7231d8SStephan Herhut // different number of arguments. 1655d7231d8SStephan Herhut bool ModuleTranslation::convertOperation(Operation &opInst, 1665d7231d8SStephan Herhut llvm::IRBuilder<> &builder) { 1675d7231d8SStephan Herhut auto extractPosition = [](ArrayAttr attr) { 1685d7231d8SStephan Herhut SmallVector<unsigned, 4> position; 1695d7231d8SStephan Herhut position.reserve(attr.size()); 1705d7231d8SStephan Herhut for (Attribute v : attr) 1715d7231d8SStephan Herhut position.push_back(v.cast<IntegerAttr>().getValue().getZExtValue()); 1725d7231d8SStephan Herhut return position; 1735d7231d8SStephan Herhut }; 1745d7231d8SStephan Herhut 1755d7231d8SStephan Herhut #include "mlir/LLVMIR/LLVMConversions.inc" 1765d7231d8SStephan Herhut 1775d7231d8SStephan Herhut // Emit function calls. If the "callee" attribute is present, this is a 1785d7231d8SStephan Herhut // direct function call and we also need to look up the remapped function 1795d7231d8SStephan Herhut // itself. Otherwise, this is an indirect call and the callee is the first 1805d7231d8SStephan Herhut // operand, look it up as a normal value. Return the llvm::Value representing 1815d7231d8SStephan Herhut // the function result, which may be of llvm::VoidTy type. 1825d7231d8SStephan Herhut auto convertCall = [this, &builder](Operation &op) -> llvm::Value * { 1835d7231d8SStephan Herhut auto operands = lookupValues(op.getOperands()); 1845d7231d8SStephan Herhut ArrayRef<llvm::Value *> operandsRef(operands); 1855d7231d8SStephan Herhut if (auto attr = op.getAttrOfType<FunctionAttr>("callee")) { 1865d7231d8SStephan Herhut return builder.CreateCall(functionMapping.lookup(attr.getValue()), 1875d7231d8SStephan Herhut operandsRef); 1885d7231d8SStephan Herhut } else { 1895d7231d8SStephan Herhut return builder.CreateCall(operandsRef.front(), operandsRef.drop_front()); 1905d7231d8SStephan Herhut } 1915d7231d8SStephan Herhut }; 1925d7231d8SStephan Herhut 1935d7231d8SStephan Herhut // Emit calls. If the called function has a result, remap the corresponding 1945d7231d8SStephan Herhut // value. Note that LLVM IR dialect CallOp has either 0 or 1 result. 195d5b60ee8SRiver Riddle if (isa<LLVM::CallOp>(opInst)) { 1965d7231d8SStephan Herhut llvm::Value *result = convertCall(opInst); 1975d7231d8SStephan Herhut if (opInst.getNumResults() != 0) { 1985d7231d8SStephan Herhut valueMapping[opInst.getResult(0)] = result; 1995d7231d8SStephan Herhut return false; 2005d7231d8SStephan Herhut } 2015d7231d8SStephan Herhut // Check that LLVM call returns void for 0-result functions. 2025d7231d8SStephan Herhut return !result->getType()->isVoidTy(); 2035d7231d8SStephan Herhut } 2045d7231d8SStephan Herhut 2055d7231d8SStephan Herhut // Emit branches. We need to look up the remapped blocks and ignore the block 2065d7231d8SStephan Herhut // arguments that were transformed into PHI nodes. 207c5ecf991SRiver Riddle if (auto brOp = dyn_cast<LLVM::BrOp>(opInst)) { 2085d7231d8SStephan Herhut builder.CreateBr(blockMapping[brOp.getSuccessor(0)]); 2095d7231d8SStephan Herhut return false; 2105d7231d8SStephan Herhut } 211c5ecf991SRiver Riddle if (auto condbrOp = dyn_cast<LLVM::CondBrOp>(opInst)) { 2125d7231d8SStephan Herhut builder.CreateCondBr(valueMapping.lookup(condbrOp.getOperand(0)), 2135d7231d8SStephan Herhut blockMapping[condbrOp.getSuccessor(0)], 2145d7231d8SStephan Herhut blockMapping[condbrOp.getSuccessor(1)]); 2155d7231d8SStephan Herhut return false; 2165d7231d8SStephan Herhut } 2175d7231d8SStephan Herhut 218039800bfSRiver Riddle opInst.emitError("unsupported or non-LLVM operation: ") << opInst.getName(); 2195d7231d8SStephan Herhut return true; 2205d7231d8SStephan Herhut } 2215d7231d8SStephan Herhut 2225d7231d8SStephan Herhut // Convert block to LLVM IR. Unless `ignoreArguments` is set, emit PHI nodes 2235d7231d8SStephan Herhut // to define values corresponding to the MLIR block arguments. These nodes 2245d7231d8SStephan Herhut // are not connected to the source basic blocks, which may not exist yet. 2255d7231d8SStephan Herhut bool ModuleTranslation::convertBlock(Block &bb, bool ignoreArguments) { 2265d7231d8SStephan Herhut llvm::IRBuilder<> builder(blockMapping[&bb]); 2275d7231d8SStephan Herhut 2285d7231d8SStephan Herhut // Before traversing operations, make block arguments available through 2295d7231d8SStephan Herhut // value remapping and PHI nodes, but do not add incoming edges for the PHI 2305d7231d8SStephan Herhut // nodes just yet: those values may be defined by this or following blocks. 2315d7231d8SStephan Herhut // This step is omitted if "ignoreArguments" is set. The arguments of the 2325d7231d8SStephan Herhut // first block have been already made available through the remapping of 2335d7231d8SStephan Herhut // LLVM function arguments. 2345d7231d8SStephan Herhut if (!ignoreArguments) { 2355d7231d8SStephan Herhut auto predecessors = bb.getPredecessors(); 2365d7231d8SStephan Herhut unsigned numPredecessors = 2375d7231d8SStephan Herhut std::distance(predecessors.begin(), predecessors.end()); 2385d7231d8SStephan Herhut for (auto *arg : bb.getArguments()) { 2395d7231d8SStephan Herhut auto wrappedType = arg->getType().dyn_cast<LLVM::LLVMType>(); 2405d7231d8SStephan Herhut if (!wrappedType) { 2415d7231d8SStephan Herhut arg->getType().getContext()->emitError( 2425d7231d8SStephan Herhut bb.front().getLoc(), "block argument does not have an LLVM type"); 2435d7231d8SStephan Herhut return true; 2445d7231d8SStephan Herhut } 2455d7231d8SStephan Herhut llvm::Type *type = wrappedType.getUnderlyingType(); 2465d7231d8SStephan Herhut llvm::PHINode *phi = builder.CreatePHI(type, numPredecessors); 2475d7231d8SStephan Herhut valueMapping[arg] = phi; 2485d7231d8SStephan Herhut } 2495d7231d8SStephan Herhut } 2505d7231d8SStephan Herhut 2515d7231d8SStephan Herhut // Traverse operations. 2525d7231d8SStephan Herhut for (auto &op : bb) { 2535d7231d8SStephan Herhut if (convertOperation(op, builder)) 2545d7231d8SStephan Herhut return true; 2555d7231d8SStephan Herhut } 2565d7231d8SStephan Herhut 2575d7231d8SStephan Herhut return false; 2585d7231d8SStephan Herhut } 2595d7231d8SStephan Herhut 2605d7231d8SStephan Herhut // Get the SSA value passed to the current block from the terminator operation 2615d7231d8SStephan Herhut // of its predecessor. 2625d7231d8SStephan Herhut static Value *getPHISourceValue(Block *current, Block *pred, 2635d7231d8SStephan Herhut unsigned numArguments, unsigned index) { 2645d7231d8SStephan Herhut auto &terminator = *pred->getTerminator(); 265d5b60ee8SRiver Riddle if (isa<LLVM::BrOp>(terminator)) { 2665d7231d8SStephan Herhut return terminator.getOperand(index); 2675d7231d8SStephan Herhut } 2685d7231d8SStephan Herhut 2695d7231d8SStephan Herhut // For conditional branches, we need to check if the current block is reached 2705d7231d8SStephan Herhut // through the "true" or the "false" branch and take the relevant operands. 271c5ecf991SRiver Riddle auto condBranchOp = dyn_cast<LLVM::CondBrOp>(terminator); 2725d7231d8SStephan Herhut assert(condBranchOp && 2735d7231d8SStephan Herhut "only branch operations can be terminators of a block that " 2745d7231d8SStephan Herhut "has successors"); 2755d7231d8SStephan Herhut assert((condBranchOp.getSuccessor(0) != condBranchOp.getSuccessor(1)) && 2765d7231d8SStephan Herhut "successors with arguments in LLVM conditional branches must be " 2775d7231d8SStephan Herhut "different blocks"); 2785d7231d8SStephan Herhut 2795d7231d8SStephan Herhut return condBranchOp.getSuccessor(0) == current 2805d7231d8SStephan Herhut ? terminator.getSuccessorOperand(0, index) 2815d7231d8SStephan Herhut : terminator.getSuccessorOperand(1, index); 2825d7231d8SStephan Herhut } 2835d7231d8SStephan Herhut 2845d7231d8SStephan Herhut void ModuleTranslation::connectPHINodes(Function &func) { 2855d7231d8SStephan Herhut // Skip the first block, it cannot be branched to and its arguments correspond 2865d7231d8SStephan Herhut // to the arguments of the LLVM function. 2875d7231d8SStephan Herhut for (auto it = std::next(func.begin()), eit = func.end(); it != eit; ++it) { 2885d7231d8SStephan Herhut Block *bb = &*it; 2895d7231d8SStephan Herhut llvm::BasicBlock *llvmBB = blockMapping.lookup(bb); 2905d7231d8SStephan Herhut auto phis = llvmBB->phis(); 2915d7231d8SStephan Herhut auto numArguments = bb->getNumArguments(); 2925d7231d8SStephan Herhut assert(numArguments == std::distance(phis.begin(), phis.end())); 2935d7231d8SStephan Herhut for (auto &numberedPhiNode : llvm::enumerate(phis)) { 2945d7231d8SStephan Herhut auto &phiNode = numberedPhiNode.value(); 2955d7231d8SStephan Herhut unsigned index = numberedPhiNode.index(); 2965d7231d8SStephan Herhut for (auto *pred : bb->getPredecessors()) { 2975d7231d8SStephan Herhut phiNode.addIncoming(valueMapping.lookup(getPHISourceValue( 2985d7231d8SStephan Herhut bb, pred, numArguments, index)), 2995d7231d8SStephan Herhut blockMapping.lookup(pred)); 3005d7231d8SStephan Herhut } 3015d7231d8SStephan Herhut } 3025d7231d8SStephan Herhut } 3035d7231d8SStephan Herhut } 3045d7231d8SStephan Herhut 3055d7231d8SStephan Herhut // TODO(mlir-team): implement an iterative version 3065d7231d8SStephan Herhut static void topologicalSortImpl(llvm::SetVector<Block *> &blocks, Block *b) { 3075d7231d8SStephan Herhut blocks.insert(b); 3085d7231d8SStephan Herhut for (Block *bb : b->getSuccessors()) { 3095d7231d8SStephan Herhut if (blocks.count(bb) == 0) 3105d7231d8SStephan Herhut topologicalSortImpl(blocks, bb); 3115d7231d8SStephan Herhut } 3125d7231d8SStephan Herhut } 3135d7231d8SStephan Herhut 3145d7231d8SStephan Herhut // Sort function blocks topologically. 3155d7231d8SStephan Herhut static llvm::SetVector<Block *> topologicalSort(Function &f) { 3165d7231d8SStephan Herhut // For each blocks that has not been visited yet (i.e. that has no 3175d7231d8SStephan Herhut // predecessors), add it to the list and traverse its successors in DFS 3185d7231d8SStephan Herhut // preorder. 3195d7231d8SStephan Herhut llvm::SetVector<Block *> blocks; 3205d7231d8SStephan Herhut for (Block &b : f.getBlocks()) { 3215d7231d8SStephan Herhut if (blocks.count(&b) == 0) 3225d7231d8SStephan Herhut topologicalSortImpl(blocks, &b); 3235d7231d8SStephan Herhut } 3245d7231d8SStephan Herhut assert(blocks.size() == f.getBlocks().size() && "some blocks are not sorted"); 3255d7231d8SStephan Herhut 3265d7231d8SStephan Herhut return blocks; 3275d7231d8SStephan Herhut } 3285d7231d8SStephan Herhut 3295d7231d8SStephan Herhut bool ModuleTranslation::convertOneFunction(Function &func) { 3305d7231d8SStephan Herhut // Clear the block and value mappings, they are only relevant within one 3315d7231d8SStephan Herhut // function. 3325d7231d8SStephan Herhut blockMapping.clear(); 3335d7231d8SStephan Herhut valueMapping.clear(); 334c33862b0SRiver Riddle llvm::Function *llvmFunc = functionMapping.lookup(func.getName()); 3355d7231d8SStephan Herhut // Add function arguments to the value remapping table. 3365d7231d8SStephan Herhut // If there was noalias info then we decorate each argument accordingly. 3375d7231d8SStephan Herhut unsigned int argIdx = 0; 3385d7231d8SStephan Herhut for (const auto &kvp : llvm::zip(func.getArguments(), llvmFunc->args())) { 3395d7231d8SStephan Herhut llvm::Argument &llvmArg = std::get<1>(kvp); 3405d7231d8SStephan Herhut BlockArgument *mlirArg = std::get<0>(kvp); 3415d7231d8SStephan Herhut 3425d7231d8SStephan Herhut if (auto attr = func.getArgAttrOfType<BoolAttr>(argIdx, "llvm.noalias")) { 3435d7231d8SStephan Herhut // NB: Attribute already verified to be boolean, so check if we can indeed 3445d7231d8SStephan Herhut // attach the attribute to this argument, based on its type. 3455d7231d8SStephan Herhut auto argTy = mlirArg->getType().dyn_cast<LLVM::LLVMType>(); 346ff6e7cf5SRiver Riddle if (!argTy.getUnderlyingType()->isPointerTy()) { 347ff6e7cf5SRiver Riddle argTy.getContext()->emitError( 3485d7231d8SStephan Herhut func.getLoc(), 3495d7231d8SStephan Herhut "llvm.noalias attribute attached to LLVM non-pointer argument"); 350ff6e7cf5SRiver Riddle return true; 351ff6e7cf5SRiver Riddle } 3525d7231d8SStephan Herhut if (attr.getValue()) 3535d7231d8SStephan Herhut llvmArg.addAttr(llvm::Attribute::AttrKind::NoAlias); 3545d7231d8SStephan Herhut } 3555d7231d8SStephan Herhut valueMapping[mlirArg] = &llvmArg; 3565d7231d8SStephan Herhut argIdx++; 3575d7231d8SStephan Herhut } 3585d7231d8SStephan Herhut 3595d7231d8SStephan Herhut // First, create all blocks so we can jump to them. 3605d7231d8SStephan Herhut llvm::LLVMContext &llvmContext = llvmFunc->getContext(); 3615d7231d8SStephan Herhut for (auto &bb : func) { 3625d7231d8SStephan Herhut auto *llvmBB = llvm::BasicBlock::Create(llvmContext); 3635d7231d8SStephan Herhut llvmBB->insertInto(llvmFunc); 3645d7231d8SStephan Herhut blockMapping[&bb] = llvmBB; 3655d7231d8SStephan Herhut } 3665d7231d8SStephan Herhut 3675d7231d8SStephan Herhut // Then, convert blocks one by one in topological order to ensure defs are 3685d7231d8SStephan Herhut // converted before uses. 3695d7231d8SStephan Herhut auto blocks = topologicalSort(func); 3705d7231d8SStephan Herhut for (auto indexedBB : llvm::enumerate(blocks)) { 3715d7231d8SStephan Herhut auto *bb = indexedBB.value(); 3725d7231d8SStephan Herhut if (convertBlock(*bb, /*ignoreArguments=*/indexedBB.index() == 0)) 3735d7231d8SStephan Herhut return true; 3745d7231d8SStephan Herhut } 3755d7231d8SStephan Herhut 3765d7231d8SStephan Herhut // Finally, after all blocks have been traversed and values mapped, connect 3775d7231d8SStephan Herhut // the PHI nodes to the results of preceding blocks. 3785d7231d8SStephan Herhut connectPHINodes(func); 3795d7231d8SStephan Herhut return false; 3805d7231d8SStephan Herhut } 3815d7231d8SStephan Herhut 3825d7231d8SStephan Herhut bool ModuleTranslation::convertFunctions() { 3835d7231d8SStephan Herhut // Declare all functions first because there may be function calls that form a 3845d7231d8SStephan Herhut // call graph with cycles. 3855d7231d8SStephan Herhut for (Function &function : mlirModule) { 3865d7231d8SStephan Herhut mlir::BoolAttr isVarArgsAttr = 3875d7231d8SStephan Herhut function.getAttrOfType<BoolAttr>("std.varargs"); 3885d7231d8SStephan Herhut bool isVarArgs = isVarArgsAttr && isVarArgsAttr.getValue(); 3895d7231d8SStephan Herhut llvm::FunctionType *functionType = 3905d7231d8SStephan Herhut convertFunctionType(llvmModule->getContext(), function.getType(), 3915d7231d8SStephan Herhut function.getLoc(), isVarArgs); 3925d7231d8SStephan Herhut if (!functionType) 3935d7231d8SStephan Herhut return true; 3945d7231d8SStephan Herhut llvm::FunctionCallee llvmFuncCst = 3955d7231d8SStephan Herhut llvmModule->getOrInsertFunction(function.getName(), functionType); 3965d7231d8SStephan Herhut assert(isa<llvm::Function>(llvmFuncCst.getCallee())); 397c33862b0SRiver Riddle functionMapping[function.getName()] = 3985d7231d8SStephan Herhut cast<llvm::Function>(llvmFuncCst.getCallee()); 3995d7231d8SStephan Herhut } 4005d7231d8SStephan Herhut 4015d7231d8SStephan Herhut // Convert functions. 4025d7231d8SStephan Herhut for (Function &function : mlirModule) { 4035d7231d8SStephan Herhut // Ignore external functions. 4045d7231d8SStephan Herhut if (function.isExternal()) 4055d7231d8SStephan Herhut continue; 4065d7231d8SStephan Herhut 4075d7231d8SStephan Herhut if (convertOneFunction(function)) 4085d7231d8SStephan Herhut return true; 4095d7231d8SStephan Herhut } 4105d7231d8SStephan Herhut 4115d7231d8SStephan Herhut return false; 4125d7231d8SStephan Herhut } 4135d7231d8SStephan Herhut 4145d7231d8SStephan Herhut std::unique_ptr<llvm::Module> ModuleTranslation::prepareLLVMModule(Module &m) { 415bc5c7378SRiver Riddle auto *dialect = m.getContext()->getRegisteredDialect<LLVM::LLVMDialect>(); 4165d7231d8SStephan Herhut assert(dialect && "LLVM dialect must be registered"); 4175d7231d8SStephan Herhut 418bc5c7378SRiver Riddle auto llvmModule = llvm::CloneModule(dialect->getLLVMModule()); 4195d7231d8SStephan Herhut if (!llvmModule) 4205d7231d8SStephan Herhut return nullptr; 4215d7231d8SStephan Herhut 4225d7231d8SStephan Herhut llvm::LLVMContext &llvmContext = llvmModule->getContext(); 4235d7231d8SStephan Herhut llvm::IRBuilder<> builder(llvmContext); 4245d7231d8SStephan Herhut 4255d7231d8SStephan Herhut // Inject declarations for `malloc` and `free` functions that can be used in 4265d7231d8SStephan Herhut // memref allocation/deallocation coming from standard ops lowering. 4275d7231d8SStephan Herhut llvmModule->getOrInsertFunction("malloc", builder.getInt8PtrTy(), 4285d7231d8SStephan Herhut builder.getInt64Ty()); 4295d7231d8SStephan Herhut llvmModule->getOrInsertFunction("free", builder.getVoidTy(), 4305d7231d8SStephan Herhut builder.getInt8PtrTy()); 4315d7231d8SStephan Herhut 4325d7231d8SStephan Herhut return llvmModule; 4335d7231d8SStephan Herhut } 4345d7231d8SStephan Herhut 4355d7231d8SStephan Herhut } // namespace LLVM 4365d7231d8SStephan Herhut } // namespace mlir 437