1 //===- ModuleTranslation.cpp - MLIR to LLVM conversion --------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the translation between an MLIR LLVM dialect module and 10 // the corresponding LLVMIR module. It only handles core LLVM IR operations. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "mlir/Target/LLVMIR/ModuleTranslation.h" 15 16 #include "DebugTranslation.h" 17 #include "mlir/Dialect/LLVMIR/LLVMDialect.h" 18 #include "mlir/Dialect/LLVMIR/Transforms/LegalizeForExport.h" 19 #include "mlir/Dialect/OpenMP/OpenMPDialect.h" 20 #include "mlir/IR/Attributes.h" 21 #include "mlir/IR/BuiltinOps.h" 22 #include "mlir/IR/BuiltinTypes.h" 23 #include "mlir/IR/RegionGraphTraits.h" 24 #include "mlir/Support/LLVM.h" 25 #include "mlir/Target/LLVMIR/LLVMTranslationInterface.h" 26 #include "mlir/Target/LLVMIR/TypeTranslation.h" 27 #include "llvm/ADT/TypeSwitch.h" 28 29 #include "llvm/ADT/PostOrderIterator.h" 30 #include "llvm/ADT/SetVector.h" 31 #include "llvm/Frontend/OpenMP/OMPIRBuilder.h" 32 #include "llvm/IR/BasicBlock.h" 33 #include "llvm/IR/CFG.h" 34 #include "llvm/IR/Constants.h" 35 #include "llvm/IR/DerivedTypes.h" 36 #include "llvm/IR/IRBuilder.h" 37 #include "llvm/IR/InlineAsm.h" 38 #include "llvm/IR/LLVMContext.h" 39 #include "llvm/IR/MDBuilder.h" 40 #include "llvm/IR/Module.h" 41 #include "llvm/IR/Verifier.h" 42 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 43 #include "llvm/Transforms/Utils/Cloning.h" 44 45 using namespace mlir; 46 using namespace mlir::LLVM; 47 using namespace mlir::LLVM::detail; 48 49 #include "mlir/Dialect/LLVMIR/LLVMConversionEnumsToLLVM.inc" 50 51 /// Builds a constant of a sequential LLVM type `type`, potentially containing 52 /// other sequential types recursively, from the individual constant values 53 /// provided in `constants`. `shape` contains the number of elements in nested 54 /// sequential types. Reports errors at `loc` and returns nullptr on error. 55 static llvm::Constant * 56 buildSequentialConstant(ArrayRef<llvm::Constant *> &constants, 57 ArrayRef<int64_t> shape, llvm::Type *type, 58 Location loc) { 59 if (shape.empty()) { 60 llvm::Constant *result = constants.front(); 61 constants = constants.drop_front(); 62 return result; 63 } 64 65 llvm::Type *elementType; 66 if (auto *arrayTy = dyn_cast<llvm::ArrayType>(type)) { 67 elementType = arrayTy->getElementType(); 68 } else if (auto *vectorTy = dyn_cast<llvm::VectorType>(type)) { 69 elementType = vectorTy->getElementType(); 70 } else { 71 emitError(loc) << "expected sequential LLVM types wrapping a scalar"; 72 return nullptr; 73 } 74 75 SmallVector<llvm::Constant *, 8> nested; 76 nested.reserve(shape.front()); 77 for (int64_t i = 0; i < shape.front(); ++i) { 78 nested.push_back(buildSequentialConstant(constants, shape.drop_front(), 79 elementType, loc)); 80 if (!nested.back()) 81 return nullptr; 82 } 83 84 if (shape.size() == 1 && type->isVectorTy()) 85 return llvm::ConstantVector::get(nested); 86 return llvm::ConstantArray::get( 87 llvm::ArrayType::get(elementType, shape.front()), nested); 88 } 89 90 /// Returns the first non-sequential type nested in sequential types. 91 static llvm::Type *getInnermostElementType(llvm::Type *type) { 92 do { 93 if (auto *arrayTy = dyn_cast<llvm::ArrayType>(type)) { 94 type = arrayTy->getElementType(); 95 } else if (auto *vectorTy = dyn_cast<llvm::VectorType>(type)) { 96 type = vectorTy->getElementType(); 97 } else { 98 return type; 99 } 100 } while (true); 101 } 102 103 /// Create an LLVM IR constant of `llvmType` from the MLIR attribute `attr`. 104 /// This currently supports integer, floating point, splat and dense element 105 /// attributes and combinations thereof. In case of error, report it to `loc` 106 /// and return nullptr. 107 llvm::Constant *mlir::LLVM::detail::getLLVMConstant( 108 llvm::Type *llvmType, Attribute attr, Location loc, 109 const ModuleTranslation &moduleTranslation) { 110 if (!attr) 111 return llvm::UndefValue::get(llvmType); 112 if (llvmType->isStructTy()) { 113 emitError(loc, "struct types are not supported in constants"); 114 return nullptr; 115 } 116 // For integer types, we allow a mismatch in sizes as the index type in 117 // MLIR might have a different size than the index type in the LLVM module. 118 if (auto intAttr = attr.dyn_cast<IntegerAttr>()) 119 return llvm::ConstantInt::get( 120 llvmType, 121 intAttr.getValue().sextOrTrunc(llvmType->getIntegerBitWidth())); 122 if (auto floatAttr = attr.dyn_cast<FloatAttr>()) 123 return llvm::ConstantFP::get(llvmType, floatAttr.getValue()); 124 if (auto funcAttr = attr.dyn_cast<FlatSymbolRefAttr>()) 125 return llvm::ConstantExpr::getBitCast( 126 moduleTranslation.lookupFunction(funcAttr.getValue()), llvmType); 127 if (auto splatAttr = attr.dyn_cast<SplatElementsAttr>()) { 128 llvm::Type *elementType; 129 uint64_t numElements; 130 if (auto *arrayTy = dyn_cast<llvm::ArrayType>(llvmType)) { 131 elementType = arrayTy->getElementType(); 132 numElements = arrayTy->getNumElements(); 133 } else { 134 auto *vectorTy = cast<llvm::FixedVectorType>(llvmType); 135 elementType = vectorTy->getElementType(); 136 numElements = vectorTy->getNumElements(); 137 } 138 // Splat value is a scalar. Extract it only if the element type is not 139 // another sequence type. The recursion terminates because each step removes 140 // one outer sequential type. 141 bool elementTypeSequential = 142 isa<llvm::ArrayType, llvm::VectorType>(elementType); 143 llvm::Constant *child = getLLVMConstant( 144 elementType, 145 elementTypeSequential ? splatAttr : splatAttr.getSplatValue(), loc, 146 moduleTranslation); 147 if (!child) 148 return nullptr; 149 if (llvmType->isVectorTy()) 150 return llvm::ConstantVector::getSplat( 151 llvm::ElementCount::get(numElements, /*Scalable=*/false), child); 152 if (llvmType->isArrayTy()) { 153 auto *arrayType = llvm::ArrayType::get(elementType, numElements); 154 SmallVector<llvm::Constant *, 8> constants(numElements, child); 155 return llvm::ConstantArray::get(arrayType, constants); 156 } 157 } 158 159 if (auto elementsAttr = attr.dyn_cast<ElementsAttr>()) { 160 assert(elementsAttr.getType().hasStaticShape()); 161 assert(elementsAttr.getNumElements() != 0 && 162 "unexpected empty elements attribute"); 163 assert(!elementsAttr.getType().getShape().empty() && 164 "unexpected empty elements attribute shape"); 165 166 SmallVector<llvm::Constant *, 8> constants; 167 constants.reserve(elementsAttr.getNumElements()); 168 llvm::Type *innermostType = getInnermostElementType(llvmType); 169 for (auto n : elementsAttr.getValues<Attribute>()) { 170 constants.push_back( 171 getLLVMConstant(innermostType, n, loc, moduleTranslation)); 172 if (!constants.back()) 173 return nullptr; 174 } 175 ArrayRef<llvm::Constant *> constantsRef = constants; 176 llvm::Constant *result = buildSequentialConstant( 177 constantsRef, elementsAttr.getType().getShape(), llvmType, loc); 178 assert(constantsRef.empty() && "did not consume all elemental constants"); 179 return result; 180 } 181 182 if (auto stringAttr = attr.dyn_cast<StringAttr>()) { 183 return llvm::ConstantDataArray::get( 184 moduleTranslation.getLLVMContext(), 185 ArrayRef<char>{stringAttr.getValue().data(), 186 stringAttr.getValue().size()}); 187 } 188 emitError(loc, "unsupported constant value"); 189 return nullptr; 190 } 191 192 ModuleTranslation::ModuleTranslation(Operation *module, 193 std::unique_ptr<llvm::Module> llvmModule) 194 : mlirModule(module), llvmModule(std::move(llvmModule)), 195 debugTranslation( 196 std::make_unique<DebugTranslation>(module, *this->llvmModule)), 197 typeTranslator(this->llvmModule->getContext()), 198 iface(module->getContext()) { 199 assert(satisfiesLLVMModule(mlirModule) && 200 "mlirModule should honor LLVM's module semantics."); 201 } 202 ModuleTranslation::~ModuleTranslation() { 203 if (ompBuilder) 204 ompBuilder->finalize(); 205 } 206 207 /// Get the SSA value passed to the current block from the terminator operation 208 /// of its predecessor. 209 static Value getPHISourceValue(Block *current, Block *pred, 210 unsigned numArguments, unsigned index) { 211 Operation &terminator = *pred->getTerminator(); 212 if (isa<LLVM::BrOp>(terminator)) 213 return terminator.getOperand(index); 214 215 SuccessorRange successors = terminator.getSuccessors(); 216 assert(std::adjacent_find(successors.begin(), successors.end()) == 217 successors.end() && 218 "successors with arguments in LLVM branches must be different blocks"); 219 (void)successors; 220 221 // For instructions that branch based on a condition value, we need to take 222 // the operands for the branch that was taken. 223 if (auto condBranchOp = dyn_cast<LLVM::CondBrOp>(terminator)) { 224 // For conditional branches, we take the operands from either the "true" or 225 // the "false" branch. 226 return condBranchOp.getSuccessor(0) == current 227 ? condBranchOp.trueDestOperands()[index] 228 : condBranchOp.falseDestOperands()[index]; 229 } 230 231 if (auto switchOp = dyn_cast<LLVM::SwitchOp>(terminator)) { 232 // For switches, we take the operands from either the default case, or from 233 // the case branch that was taken. 234 if (switchOp.defaultDestination() == current) 235 return switchOp.defaultOperands()[index]; 236 for (auto i : llvm::enumerate(switchOp.caseDestinations())) 237 if (i.value() == current) 238 return switchOp.getCaseOperands(i.index())[index]; 239 } 240 241 llvm_unreachable("only branch or switch operations can be terminators of a " 242 "block that has successors"); 243 } 244 245 /// Connect the PHI nodes to the results of preceding blocks. 246 void mlir::LLVM::detail::connectPHINodes(Region ®ion, 247 const ModuleTranslation &state) { 248 // Skip the first block, it cannot be branched to and its arguments correspond 249 // to the arguments of the LLVM function. 250 for (auto it = std::next(region.begin()), eit = region.end(); it != eit; 251 ++it) { 252 Block *bb = &*it; 253 llvm::BasicBlock *llvmBB = state.lookupBlock(bb); 254 auto phis = llvmBB->phis(); 255 auto numArguments = bb->getNumArguments(); 256 assert(numArguments == std::distance(phis.begin(), phis.end())); 257 for (auto &numberedPhiNode : llvm::enumerate(phis)) { 258 auto &phiNode = numberedPhiNode.value(); 259 unsigned index = numberedPhiNode.index(); 260 for (auto *pred : bb->getPredecessors()) { 261 // Find the LLVM IR block that contains the converted terminator 262 // instruction and use it in the PHI node. Note that this block is not 263 // necessarily the same as state.lookupBlock(pred), some operations 264 // (in particular, OpenMP operations using OpenMPIRBuilder) may have 265 // split the blocks. 266 llvm::Instruction *terminator = 267 state.lookupBranch(pred->getTerminator()); 268 assert(terminator && "missing the mapping for a terminator"); 269 phiNode.addIncoming( 270 state.lookupValue(getPHISourceValue(bb, pred, numArguments, index)), 271 terminator->getParent()); 272 } 273 } 274 } 275 } 276 277 /// Sort function blocks topologically. 278 llvm::SetVector<Block *> 279 mlir::LLVM::detail::getTopologicallySortedBlocks(Region ®ion) { 280 // For each block that has not been visited yet (i.e. that has no 281 // predecessors), add it to the list as well as its successors. 282 llvm::SetVector<Block *> blocks; 283 for (Block &b : region) { 284 if (blocks.count(&b) == 0) { 285 llvm::ReversePostOrderTraversal<Block *> traversal(&b); 286 blocks.insert(traversal.begin(), traversal.end()); 287 } 288 } 289 assert(blocks.size() == region.getBlocks().size() && 290 "some blocks are not sorted"); 291 292 return blocks; 293 } 294 295 llvm::Value *mlir::LLVM::detail::createIntrinsicCall( 296 llvm::IRBuilderBase &builder, llvm::Intrinsic::ID intrinsic, 297 ArrayRef<llvm::Value *> args, ArrayRef<llvm::Type *> tys) { 298 llvm::Module *module = builder.GetInsertBlock()->getModule(); 299 llvm::Function *fn = llvm::Intrinsic::getDeclaration(module, intrinsic, tys); 300 return builder.CreateCall(fn, args); 301 } 302 303 /// Given a single MLIR operation, create the corresponding LLVM IR operation 304 /// using the `builder`. 305 LogicalResult 306 ModuleTranslation::convertOperation(Operation &opInst, 307 llvm::IRBuilderBase &builder) { 308 if (failed(iface.convertOperation(&opInst, builder, *this))) 309 return opInst.emitError("unsupported or non-LLVM operation: ") 310 << opInst.getName(); 311 312 return convertDialectAttributes(&opInst); 313 } 314 315 /// Convert block to LLVM IR. Unless `ignoreArguments` is set, emit PHI nodes 316 /// to define values corresponding to the MLIR block arguments. These nodes 317 /// are not connected to the source basic blocks, which may not exist yet. Uses 318 /// `builder` to construct the LLVM IR. Expects the LLVM IR basic block to have 319 /// been created for `bb` and included in the block mapping. Inserts new 320 /// instructions at the end of the block and leaves `builder` in a state 321 /// suitable for further insertion into the end of the block. 322 LogicalResult ModuleTranslation::convertBlock(Block &bb, bool ignoreArguments, 323 llvm::IRBuilderBase &builder) { 324 builder.SetInsertPoint(lookupBlock(&bb)); 325 auto *subprogram = builder.GetInsertBlock()->getParent()->getSubprogram(); 326 327 // Before traversing operations, make block arguments available through 328 // value remapping and PHI nodes, but do not add incoming edges for the PHI 329 // nodes just yet: those values may be defined by this or following blocks. 330 // This step is omitted if "ignoreArguments" is set. The arguments of the 331 // first block have been already made available through the remapping of 332 // LLVM function arguments. 333 if (!ignoreArguments) { 334 auto predecessors = bb.getPredecessors(); 335 unsigned numPredecessors = 336 std::distance(predecessors.begin(), predecessors.end()); 337 for (auto arg : bb.getArguments()) { 338 auto wrappedType = arg.getType(); 339 if (!isCompatibleType(wrappedType)) 340 return emitError(bb.front().getLoc(), 341 "block argument does not have an LLVM type"); 342 llvm::Type *type = convertType(wrappedType); 343 llvm::PHINode *phi = builder.CreatePHI(type, numPredecessors); 344 mapValue(arg, phi); 345 } 346 } 347 348 // Traverse operations. 349 for (auto &op : bb) { 350 // Set the current debug location within the builder. 351 builder.SetCurrentDebugLocation( 352 debugTranslation->translateLoc(op.getLoc(), subprogram)); 353 354 if (failed(convertOperation(op, builder))) 355 return failure(); 356 } 357 358 return success(); 359 } 360 361 /// A helper method to get the single Block in an operation honoring LLVM's 362 /// module requirements. 363 static Block &getModuleBody(Operation *module) { 364 return module->getRegion(0).front(); 365 } 366 367 /// Create named global variables that correspond to llvm.mlir.global 368 /// definitions. 369 LogicalResult ModuleTranslation::convertGlobals() { 370 for (auto op : getModuleBody(mlirModule).getOps<LLVM::GlobalOp>()) { 371 llvm::Type *type = convertType(op.getType()); 372 llvm::Constant *cst = llvm::UndefValue::get(type); 373 if (op.getValueOrNull()) { 374 // String attributes are treated separately because they cannot appear as 375 // in-function constants and are thus not supported by getLLVMConstant. 376 if (auto strAttr = op.getValueOrNull().dyn_cast_or_null<StringAttr>()) { 377 cst = llvm::ConstantDataArray::getString( 378 llvmModule->getContext(), strAttr.getValue(), /*AddNull=*/false); 379 type = cst->getType(); 380 } else if (!(cst = getLLVMConstant(type, op.getValueOrNull(), op.getLoc(), 381 *this))) { 382 return failure(); 383 } 384 } else if (Block *initializer = op.getInitializerBlock()) { 385 llvm::IRBuilder<> builder(llvmModule->getContext()); 386 for (auto &op : initializer->without_terminator()) { 387 if (failed(convertOperation(op, builder)) || 388 !isa<llvm::Constant>(lookupValue(op.getResult(0)))) 389 return emitError(op.getLoc(), "unemittable constant value"); 390 } 391 ReturnOp ret = cast<ReturnOp>(initializer->getTerminator()); 392 cst = cast<llvm::Constant>(lookupValue(ret.getOperand(0))); 393 } 394 395 auto linkage = convertLinkageToLLVM(op.linkage()); 396 bool anyExternalLinkage = 397 ((linkage == llvm::GlobalVariable::ExternalLinkage && 398 isa<llvm::UndefValue>(cst)) || 399 linkage == llvm::GlobalVariable::ExternalWeakLinkage); 400 auto addrSpace = op.addr_space(); 401 auto *var = new llvm::GlobalVariable( 402 *llvmModule, type, op.constant(), linkage, 403 anyExternalLinkage ? nullptr : cst, op.sym_name(), 404 /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal, addrSpace); 405 406 globalsMapping.try_emplace(op, var); 407 } 408 409 return success(); 410 } 411 412 /// Attempts to add an attribute identified by `key`, optionally with the given 413 /// `value` to LLVM function `llvmFunc`. Reports errors at `loc` if any. If the 414 /// attribute has a kind known to LLVM IR, create the attribute of this kind, 415 /// otherwise keep it as a string attribute. Performs additional checks for 416 /// attributes known to have or not have a value in order to avoid assertions 417 /// inside LLVM upon construction. 418 static LogicalResult checkedAddLLVMFnAttribute(Location loc, 419 llvm::Function *llvmFunc, 420 StringRef key, 421 StringRef value = StringRef()) { 422 auto kind = llvm::Attribute::getAttrKindFromName(key); 423 if (kind == llvm::Attribute::None) { 424 llvmFunc->addFnAttr(key, value); 425 return success(); 426 } 427 428 if (llvm::Attribute::doesAttrKindHaveArgument(kind)) { 429 if (value.empty()) 430 return emitError(loc) << "LLVM attribute '" << key << "' expects a value"; 431 432 int result; 433 if (!value.getAsInteger(/*Radix=*/0, result)) 434 llvmFunc->addFnAttr( 435 llvm::Attribute::get(llvmFunc->getContext(), kind, result)); 436 else 437 llvmFunc->addFnAttr(key, value); 438 return success(); 439 } 440 441 if (!value.empty()) 442 return emitError(loc) << "LLVM attribute '" << key 443 << "' does not expect a value, found '" << value 444 << "'"; 445 446 llvmFunc->addFnAttr(kind); 447 return success(); 448 } 449 450 /// Attaches the attributes listed in the given array attribute to `llvmFunc`. 451 /// Reports error to `loc` if any and returns immediately. Expects `attributes` 452 /// to be an array attribute containing either string attributes, treated as 453 /// value-less LLVM attributes, or array attributes containing two string 454 /// attributes, with the first string being the name of the corresponding LLVM 455 /// attribute and the second string beings its value. Note that even integer 456 /// attributes are expected to have their values expressed as strings. 457 static LogicalResult 458 forwardPassthroughAttributes(Location loc, Optional<ArrayAttr> attributes, 459 llvm::Function *llvmFunc) { 460 if (!attributes) 461 return success(); 462 463 for (Attribute attr : *attributes) { 464 if (auto stringAttr = attr.dyn_cast<StringAttr>()) { 465 if (failed( 466 checkedAddLLVMFnAttribute(loc, llvmFunc, stringAttr.getValue()))) 467 return failure(); 468 continue; 469 } 470 471 auto arrayAttr = attr.dyn_cast<ArrayAttr>(); 472 if (!arrayAttr || arrayAttr.size() != 2) 473 return emitError(loc) 474 << "expected 'passthrough' to contain string or array attributes"; 475 476 auto keyAttr = arrayAttr[0].dyn_cast<StringAttr>(); 477 auto valueAttr = arrayAttr[1].dyn_cast<StringAttr>(); 478 if (!keyAttr || !valueAttr) 479 return emitError(loc) 480 << "expected arrays within 'passthrough' to contain two strings"; 481 482 if (failed(checkedAddLLVMFnAttribute(loc, llvmFunc, keyAttr.getValue(), 483 valueAttr.getValue()))) 484 return failure(); 485 } 486 return success(); 487 } 488 489 LogicalResult ModuleTranslation::convertOneFunction(LLVMFuncOp func) { 490 // Clear the block, branch value mappings, they are only relevant within one 491 // function. 492 blockMapping.clear(); 493 valueMapping.clear(); 494 branchMapping.clear(); 495 llvm::Function *llvmFunc = lookupFunction(func.getName()); 496 497 // Translate the debug information for this function. 498 debugTranslation->translate(func, *llvmFunc); 499 500 // Add function arguments to the value remapping table. 501 // If there was noalias info then we decorate each argument accordingly. 502 unsigned int argIdx = 0; 503 for (auto kvp : llvm::zip(func.getArguments(), llvmFunc->args())) { 504 llvm::Argument &llvmArg = std::get<1>(kvp); 505 BlockArgument mlirArg = std::get<0>(kvp); 506 507 if (auto attr = func.getArgAttrOfType<BoolAttr>( 508 argIdx, LLVMDialect::getNoAliasAttrName())) { 509 // NB: Attribute already verified to be boolean, so check if we can indeed 510 // attach the attribute to this argument, based on its type. 511 auto argTy = mlirArg.getType(); 512 if (!argTy.isa<LLVM::LLVMPointerType>()) 513 return func.emitError( 514 "llvm.noalias attribute attached to LLVM non-pointer argument"); 515 if (attr.getValue()) 516 llvmArg.addAttr(llvm::Attribute::AttrKind::NoAlias); 517 } 518 519 if (auto attr = func.getArgAttrOfType<IntegerAttr>( 520 argIdx, LLVMDialect::getAlignAttrName())) { 521 // NB: Attribute already verified to be int, so check if we can indeed 522 // attach the attribute to this argument, based on its type. 523 auto argTy = mlirArg.getType(); 524 if (!argTy.isa<LLVM::LLVMPointerType>()) 525 return func.emitError( 526 "llvm.align attribute attached to LLVM non-pointer argument"); 527 llvmArg.addAttrs( 528 llvm::AttrBuilder().addAlignmentAttr(llvm::Align(attr.getInt()))); 529 } 530 531 if (auto attr = func.getArgAttrOfType<UnitAttr>(argIdx, "llvm.sret")) { 532 auto argTy = mlirArg.getType(); 533 if (!argTy.isa<LLVM::LLVMPointerType>()) 534 return func.emitError( 535 "llvm.sret attribute attached to LLVM non-pointer argument"); 536 llvmArg.addAttrs(llvm::AttrBuilder().addStructRetAttr( 537 llvmArg.getType()->getPointerElementType())); 538 } 539 540 if (auto attr = func.getArgAttrOfType<UnitAttr>(argIdx, "llvm.byval")) { 541 auto argTy = mlirArg.getType(); 542 if (!argTy.isa<LLVM::LLVMPointerType>()) 543 return func.emitError( 544 "llvm.byval attribute attached to LLVM non-pointer argument"); 545 llvmArg.addAttrs(llvm::AttrBuilder().addByValAttr( 546 llvmArg.getType()->getPointerElementType())); 547 } 548 549 mapValue(mlirArg, &llvmArg); 550 argIdx++; 551 } 552 553 // Check the personality and set it. 554 if (func.personality().hasValue()) { 555 llvm::Type *ty = llvm::Type::getInt8PtrTy(llvmFunc->getContext()); 556 if (llvm::Constant *pfunc = 557 getLLVMConstant(ty, func.personalityAttr(), func.getLoc(), *this)) 558 llvmFunc->setPersonalityFn(pfunc); 559 } 560 561 // First, create all blocks so we can jump to them. 562 llvm::LLVMContext &llvmContext = llvmFunc->getContext(); 563 for (auto &bb : func) { 564 auto *llvmBB = llvm::BasicBlock::Create(llvmContext); 565 llvmBB->insertInto(llvmFunc); 566 mapBlock(&bb, llvmBB); 567 } 568 569 // Then, convert blocks one by one in topological order to ensure defs are 570 // converted before uses. 571 auto blocks = detail::getTopologicallySortedBlocks(func.getBody()); 572 for (Block *bb : blocks) { 573 llvm::IRBuilder<> builder(llvmContext); 574 if (failed(convertBlock(*bb, bb->isEntryBlock(), builder))) 575 return failure(); 576 } 577 578 // After all blocks have been traversed and values mapped, connect the PHI 579 // nodes to the results of preceding blocks. 580 detail::connectPHINodes(func.getBody(), *this); 581 582 // Finally, convert dialect attributes attached to the function. 583 return convertDialectAttributes(func); 584 } 585 586 LogicalResult ModuleTranslation::convertDialectAttributes(Operation *op) { 587 for (NamedAttribute attribute : op->getDialectAttrs()) 588 if (failed(iface.amendOperation(op, attribute, *this))) 589 return failure(); 590 return success(); 591 } 592 593 /// Check whether the module contains only supported ops directly in its body. 594 static LogicalResult checkSupportedModuleOps(Operation *m) { 595 for (Operation &o : getModuleBody(m).getOperations()) 596 if (!isa<LLVM::LLVMFuncOp, LLVM::GlobalOp>(&o) && 597 !o.hasTrait<OpTrait::IsTerminator>()) 598 return o.emitOpError("unsupported module-level operation"); 599 return success(); 600 } 601 602 LogicalResult ModuleTranslation::convertFunctionSignatures() { 603 // Declare all functions first because there may be function calls that form a 604 // call graph with cycles, or global initializers that reference functions. 605 for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) { 606 llvm::FunctionCallee llvmFuncCst = llvmModule->getOrInsertFunction( 607 function.getName(), 608 cast<llvm::FunctionType>(convertType(function.getType()))); 609 llvm::Function *llvmFunc = cast<llvm::Function>(llvmFuncCst.getCallee()); 610 llvmFunc->setLinkage(convertLinkageToLLVM(function.linkage())); 611 mapFunction(function.getName(), llvmFunc); 612 613 // Forward the pass-through attributes to LLVM. 614 if (failed(forwardPassthroughAttributes(function.getLoc(), 615 function.passthrough(), llvmFunc))) 616 return failure(); 617 } 618 619 return success(); 620 } 621 622 LogicalResult ModuleTranslation::convertFunctions() { 623 // Convert functions. 624 for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) { 625 // Ignore external functions. 626 if (function.isExternal()) 627 continue; 628 629 if (failed(convertOneFunction(function))) 630 return failure(); 631 } 632 633 return success(); 634 } 635 636 llvm::Type *ModuleTranslation::convertType(Type type) { 637 return typeTranslator.translateType(type); 638 } 639 640 /// A helper to look up remapped operands in the value remapping table.` 641 SmallVector<llvm::Value *, 8> 642 ModuleTranslation::lookupValues(ValueRange values) { 643 SmallVector<llvm::Value *, 8> remapped; 644 remapped.reserve(values.size()); 645 for (Value v : values) 646 remapped.push_back(lookupValue(v)); 647 return remapped; 648 } 649 650 const llvm::DILocation * 651 ModuleTranslation::translateLoc(Location loc, llvm::DILocalScope *scope) { 652 return debugTranslation->translateLoc(loc, scope); 653 } 654 655 llvm::NamedMDNode * 656 ModuleTranslation::getOrInsertNamedModuleMetadata(StringRef name) { 657 return llvmModule->getOrInsertNamedMetadata(name); 658 } 659 660 static std::unique_ptr<llvm::Module> 661 prepareLLVMModule(Operation *m, llvm::LLVMContext &llvmContext, 662 StringRef name) { 663 m->getContext()->getOrLoadDialect<LLVM::LLVMDialect>(); 664 auto llvmModule = std::make_unique<llvm::Module>(name, llvmContext); 665 if (auto dataLayoutAttr = 666 m->getAttr(LLVM::LLVMDialect::getDataLayoutAttrName())) 667 llvmModule->setDataLayout(dataLayoutAttr.cast<StringAttr>().getValue()); 668 if (auto targetTripleAttr = 669 m->getAttr(LLVM::LLVMDialect::getTargetTripleAttrName())) 670 llvmModule->setTargetTriple(targetTripleAttr.cast<StringAttr>().getValue()); 671 672 // Inject declarations for `malloc` and `free` functions that can be used in 673 // memref allocation/deallocation coming from standard ops lowering. 674 llvm::IRBuilder<> builder(llvmContext); 675 llvmModule->getOrInsertFunction("malloc", builder.getInt8PtrTy(), 676 builder.getInt64Ty()); 677 llvmModule->getOrInsertFunction("free", builder.getVoidTy(), 678 builder.getInt8PtrTy()); 679 680 return llvmModule; 681 } 682 683 std::unique_ptr<llvm::Module> 684 mlir::translateModuleToLLVMIR(Operation *module, llvm::LLVMContext &llvmContext, 685 StringRef name) { 686 if (!satisfiesLLVMModule(module)) 687 return nullptr; 688 if (failed(checkSupportedModuleOps(module))) 689 return nullptr; 690 std::unique_ptr<llvm::Module> llvmModule = 691 prepareLLVMModule(module, llvmContext, name); 692 693 LLVM::ensureDistinctSuccessors(module); 694 695 ModuleTranslation translator(module, std::move(llvmModule)); 696 if (failed(translator.convertFunctionSignatures())) 697 return nullptr; 698 if (failed(translator.convertGlobals())) 699 return nullptr; 700 if (failed(translator.convertFunctions())) 701 return nullptr; 702 if (llvm::verifyModule(*translator.llvmModule, &llvm::errs())) 703 return nullptr; 704 705 return std::move(translator.llvmModule); 706 } 707