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 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 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 &op, 307 llvm::IRBuilderBase &builder) { 308 const LLVMTranslationDialectInterface *opIface = iface.getInterfaceFor(&op); 309 if (!opIface) 310 return op.emitError("cannot be converted to LLVM IR: missing " 311 "`LLVMTranslationDialectInterface` registration for " 312 "dialect for op: ") 313 << op.getName(); 314 315 if (failed(opIface->convertOperation(&op, builder, *this))) 316 return op.emitError("LLVM Translation failed for operation: ") 317 << op.getName(); 318 319 return convertDialectAttributes(&op); 320 } 321 322 /// Convert block to LLVM IR. Unless `ignoreArguments` is set, emit PHI nodes 323 /// to define values corresponding to the MLIR block arguments. These nodes 324 /// are not connected to the source basic blocks, which may not exist yet. Uses 325 /// `builder` to construct the LLVM IR. Expects the LLVM IR basic block to have 326 /// been created for `bb` and included in the block mapping. Inserts new 327 /// instructions at the end of the block and leaves `builder` in a state 328 /// suitable for further insertion into the end of the block. 329 LogicalResult ModuleTranslation::convertBlock(Block &bb, bool ignoreArguments, 330 llvm::IRBuilderBase &builder) { 331 builder.SetInsertPoint(lookupBlock(&bb)); 332 auto *subprogram = builder.GetInsertBlock()->getParent()->getSubprogram(); 333 334 // Before traversing operations, make block arguments available through 335 // value remapping and PHI nodes, but do not add incoming edges for the PHI 336 // nodes just yet: those values may be defined by this or following blocks. 337 // This step is omitted if "ignoreArguments" is set. The arguments of the 338 // first block have been already made available through the remapping of 339 // LLVM function arguments. 340 if (!ignoreArguments) { 341 auto predecessors = bb.getPredecessors(); 342 unsigned numPredecessors = 343 std::distance(predecessors.begin(), predecessors.end()); 344 for (auto arg : bb.getArguments()) { 345 auto wrappedType = arg.getType(); 346 if (!isCompatibleType(wrappedType)) 347 return emitError(bb.front().getLoc(), 348 "block argument does not have an LLVM type"); 349 llvm::Type *type = convertType(wrappedType); 350 llvm::PHINode *phi = builder.CreatePHI(type, numPredecessors); 351 mapValue(arg, phi); 352 } 353 } 354 355 // Traverse operations. 356 for (auto &op : bb) { 357 // Set the current debug location within the builder. 358 builder.SetCurrentDebugLocation( 359 debugTranslation->translateLoc(op.getLoc(), subprogram)); 360 361 if (failed(convertOperation(op, builder))) 362 return failure(); 363 } 364 365 return success(); 366 } 367 368 /// A helper method to get the single Block in an operation honoring LLVM's 369 /// module requirements. 370 static Block &getModuleBody(Operation *module) { 371 return module->getRegion(0).front(); 372 } 373 374 /// A helper method to decide if a constant must not be set as a global variable 375 /// initializer. 376 static bool shouldDropGlobalInitializer(llvm::GlobalValue::LinkageTypes linkage, 377 llvm::Constant *cst) { 378 return (linkage == llvm::GlobalVariable::ExternalLinkage && 379 isa<llvm::UndefValue>(cst)) || 380 linkage == llvm::GlobalVariable::ExternalWeakLinkage; 381 } 382 383 /// Create named global variables that correspond to llvm.mlir.global 384 /// definitions. 385 LogicalResult ModuleTranslation::convertGlobals() { 386 for (auto op : getModuleBody(mlirModule).getOps<LLVM::GlobalOp>()) { 387 llvm::Type *type = convertType(op.getType()); 388 llvm::Constant *cst = llvm::UndefValue::get(type); 389 if (op.getValueOrNull()) { 390 // String attributes are treated separately because they cannot appear as 391 // in-function constants and are thus not supported by getLLVMConstant. 392 if (auto strAttr = op.getValueOrNull().dyn_cast_or_null<StringAttr>()) { 393 cst = llvm::ConstantDataArray::getString( 394 llvmModule->getContext(), strAttr.getValue(), /*AddNull=*/false); 395 type = cst->getType(); 396 } else if (!(cst = getLLVMConstant(type, op.getValueOrNull(), op.getLoc(), 397 *this))) { 398 return failure(); 399 } 400 } 401 402 auto linkage = convertLinkageToLLVM(op.linkage()); 403 auto addrSpace = op.addr_space(); 404 auto *var = new llvm::GlobalVariable( 405 *llvmModule, type, op.constant(), linkage, 406 shouldDropGlobalInitializer(linkage, cst) ? nullptr : cst, 407 op.sym_name(), 408 /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal, addrSpace); 409 410 if (op.unnamed_addr().hasValue()) 411 var->setUnnamedAddr(convertUnnamedAddrToLLVM(*op.unnamed_addr())); 412 413 globalsMapping.try_emplace(op, var); 414 } 415 416 // Convert global variable bodies. This is done after all global variables 417 // have been created in LLVM IR because a global body may refer to another 418 // global or itself. So all global variables need to be mapped first. 419 for (auto op : getModuleBody(mlirModule).getOps<LLVM::GlobalOp>()) { 420 if (Block *initializer = op.getInitializerBlock()) { 421 llvm::IRBuilder<> builder(llvmModule->getContext()); 422 for (auto &op : initializer->without_terminator()) { 423 if (failed(convertOperation(op, builder)) || 424 !isa<llvm::Constant>(lookupValue(op.getResult(0)))) 425 return emitError(op.getLoc(), "unemittable constant value"); 426 } 427 ReturnOp ret = cast<ReturnOp>(initializer->getTerminator()); 428 llvm::Constant *cst = 429 cast<llvm::Constant>(lookupValue(ret.getOperand(0))); 430 auto *global = cast<llvm::GlobalVariable>(lookupGlobal(op)); 431 if (!shouldDropGlobalInitializer(global->getLinkage(), cst)) 432 global->setInitializer(cst); 433 } 434 } 435 436 return success(); 437 } 438 439 /// Attempts to add an attribute identified by `key`, optionally with the given 440 /// `value` to LLVM function `llvmFunc`. Reports errors at `loc` if any. If the 441 /// attribute has a kind known to LLVM IR, create the attribute of this kind, 442 /// otherwise keep it as a string attribute. Performs additional checks for 443 /// attributes known to have or not have a value in order to avoid assertions 444 /// inside LLVM upon construction. 445 static LogicalResult checkedAddLLVMFnAttribute(Location loc, 446 llvm::Function *llvmFunc, 447 StringRef key, 448 StringRef value = StringRef()) { 449 auto kind = llvm::Attribute::getAttrKindFromName(key); 450 if (kind == llvm::Attribute::None) { 451 llvmFunc->addFnAttr(key, value); 452 return success(); 453 } 454 455 if (llvm::Attribute::doesAttrKindHaveArgument(kind)) { 456 if (value.empty()) 457 return emitError(loc) << "LLVM attribute '" << key << "' expects a value"; 458 459 int result; 460 if (!value.getAsInteger(/*Radix=*/0, result)) 461 llvmFunc->addFnAttr( 462 llvm::Attribute::get(llvmFunc->getContext(), kind, result)); 463 else 464 llvmFunc->addFnAttr(key, value); 465 return success(); 466 } 467 468 if (!value.empty()) 469 return emitError(loc) << "LLVM attribute '" << key 470 << "' does not expect a value, found '" << value 471 << "'"; 472 473 llvmFunc->addFnAttr(kind); 474 return success(); 475 } 476 477 /// Attaches the attributes listed in the given array attribute to `llvmFunc`. 478 /// Reports error to `loc` if any and returns immediately. Expects `attributes` 479 /// to be an array attribute containing either string attributes, treated as 480 /// value-less LLVM attributes, or array attributes containing two string 481 /// attributes, with the first string being the name of the corresponding LLVM 482 /// attribute and the second string beings its value. Note that even integer 483 /// attributes are expected to have their values expressed as strings. 484 static LogicalResult 485 forwardPassthroughAttributes(Location loc, Optional<ArrayAttr> attributes, 486 llvm::Function *llvmFunc) { 487 if (!attributes) 488 return success(); 489 490 for (Attribute attr : *attributes) { 491 if (auto stringAttr = attr.dyn_cast<StringAttr>()) { 492 if (failed( 493 checkedAddLLVMFnAttribute(loc, llvmFunc, stringAttr.getValue()))) 494 return failure(); 495 continue; 496 } 497 498 auto arrayAttr = attr.dyn_cast<ArrayAttr>(); 499 if (!arrayAttr || arrayAttr.size() != 2) 500 return emitError(loc) 501 << "expected 'passthrough' to contain string or array attributes"; 502 503 auto keyAttr = arrayAttr[0].dyn_cast<StringAttr>(); 504 auto valueAttr = arrayAttr[1].dyn_cast<StringAttr>(); 505 if (!keyAttr || !valueAttr) 506 return emitError(loc) 507 << "expected arrays within 'passthrough' to contain two strings"; 508 509 if (failed(checkedAddLLVMFnAttribute(loc, llvmFunc, keyAttr.getValue(), 510 valueAttr.getValue()))) 511 return failure(); 512 } 513 return success(); 514 } 515 516 LogicalResult ModuleTranslation::convertOneFunction(LLVMFuncOp func) { 517 // Clear the block, branch value mappings, they are only relevant within one 518 // function. 519 blockMapping.clear(); 520 valueMapping.clear(); 521 branchMapping.clear(); 522 llvm::Function *llvmFunc = lookupFunction(func.getName()); 523 524 // Translate the debug information for this function. 525 debugTranslation->translate(func, *llvmFunc); 526 527 // Add function arguments to the value remapping table. 528 // If there was noalias info then we decorate each argument accordingly. 529 unsigned int argIdx = 0; 530 for (auto kvp : llvm::zip(func.getArguments(), llvmFunc->args())) { 531 llvm::Argument &llvmArg = std::get<1>(kvp); 532 BlockArgument mlirArg = std::get<0>(kvp); 533 534 if (auto attr = func.getArgAttrOfType<BoolAttr>( 535 argIdx, LLVMDialect::getNoAliasAttrName())) { 536 // NB: Attribute already verified to be boolean, so check if we can indeed 537 // attach the attribute to this argument, based on its type. 538 auto argTy = mlirArg.getType(); 539 if (!argTy.isa<LLVM::LLVMPointerType>()) 540 return func.emitError( 541 "llvm.noalias attribute attached to LLVM non-pointer argument"); 542 if (attr.getValue()) 543 llvmArg.addAttr(llvm::Attribute::AttrKind::NoAlias); 544 } 545 546 if (auto attr = func.getArgAttrOfType<IntegerAttr>( 547 argIdx, LLVMDialect::getAlignAttrName())) { 548 // NB: Attribute already verified to be int, so check if we can indeed 549 // attach the attribute to this argument, based on its type. 550 auto argTy = mlirArg.getType(); 551 if (!argTy.isa<LLVM::LLVMPointerType>()) 552 return func.emitError( 553 "llvm.align attribute attached to LLVM non-pointer argument"); 554 llvmArg.addAttrs( 555 llvm::AttrBuilder().addAlignmentAttr(llvm::Align(attr.getInt()))); 556 } 557 558 if (auto attr = func.getArgAttrOfType<UnitAttr>(argIdx, "llvm.sret")) { 559 auto argTy = mlirArg.getType(); 560 if (!argTy.isa<LLVM::LLVMPointerType>()) 561 return func.emitError( 562 "llvm.sret attribute attached to LLVM non-pointer argument"); 563 llvmArg.addAttrs(llvm::AttrBuilder().addStructRetAttr( 564 llvmArg.getType()->getPointerElementType())); 565 } 566 567 if (auto attr = func.getArgAttrOfType<UnitAttr>(argIdx, "llvm.byval")) { 568 auto argTy = mlirArg.getType(); 569 if (!argTy.isa<LLVM::LLVMPointerType>()) 570 return func.emitError( 571 "llvm.byval attribute attached to LLVM non-pointer argument"); 572 llvmArg.addAttrs(llvm::AttrBuilder().addByValAttr( 573 llvmArg.getType()->getPointerElementType())); 574 } 575 576 mapValue(mlirArg, &llvmArg); 577 argIdx++; 578 } 579 580 // Check the personality and set it. 581 if (func.personality().hasValue()) { 582 llvm::Type *ty = llvm::Type::getInt8PtrTy(llvmFunc->getContext()); 583 if (llvm::Constant *pfunc = 584 getLLVMConstant(ty, func.personalityAttr(), func.getLoc(), *this)) 585 llvmFunc->setPersonalityFn(pfunc); 586 } 587 588 // First, create all blocks so we can jump to them. 589 llvm::LLVMContext &llvmContext = llvmFunc->getContext(); 590 for (auto &bb : func) { 591 auto *llvmBB = llvm::BasicBlock::Create(llvmContext); 592 llvmBB->insertInto(llvmFunc); 593 mapBlock(&bb, llvmBB); 594 } 595 596 // Then, convert blocks one by one in topological order to ensure defs are 597 // converted before uses. 598 auto blocks = detail::getTopologicallySortedBlocks(func.getBody()); 599 for (Block *bb : blocks) { 600 llvm::IRBuilder<> builder(llvmContext); 601 if (failed(convertBlock(*bb, bb->isEntryBlock(), builder))) 602 return failure(); 603 } 604 605 // After all blocks have been traversed and values mapped, connect the PHI 606 // nodes to the results of preceding blocks. 607 detail::connectPHINodes(func.getBody(), *this); 608 609 // Finally, convert dialect attributes attached to the function. 610 return convertDialectAttributes(func); 611 } 612 613 LogicalResult ModuleTranslation::convertDialectAttributes(Operation *op) { 614 for (NamedAttribute attribute : op->getDialectAttrs()) 615 if (failed(iface.amendOperation(op, attribute, *this))) 616 return failure(); 617 return success(); 618 } 619 620 /// Check whether the module contains only supported ops directly in its body. 621 static LogicalResult checkSupportedModuleOps(Operation *m) { 622 for (Operation &o : getModuleBody(m).getOperations()) 623 if (!isa<LLVM::LLVMFuncOp, LLVM::GlobalOp, LLVM::MetadataOp>(&o) && 624 !o.hasTrait<OpTrait::IsTerminator>()) 625 return o.emitOpError("unsupported module-level operation"); 626 return success(); 627 } 628 629 LogicalResult ModuleTranslation::convertFunctionSignatures() { 630 // Declare all functions first because there may be function calls that form a 631 // call graph with cycles, or global initializers that reference functions. 632 for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) { 633 llvm::FunctionCallee llvmFuncCst = llvmModule->getOrInsertFunction( 634 function.getName(), 635 cast<llvm::FunctionType>(convertType(function.getType()))); 636 llvm::Function *llvmFunc = cast<llvm::Function>(llvmFuncCst.getCallee()); 637 llvmFunc->setLinkage(convertLinkageToLLVM(function.linkage())); 638 mapFunction(function.getName(), llvmFunc); 639 640 // Forward the pass-through attributes to LLVM. 641 if (failed(forwardPassthroughAttributes(function.getLoc(), 642 function.passthrough(), llvmFunc))) 643 return failure(); 644 } 645 646 return success(); 647 } 648 649 LogicalResult ModuleTranslation::convertFunctions() { 650 // Convert functions. 651 for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) { 652 // Ignore external functions. 653 if (function.isExternal()) 654 continue; 655 656 if (failed(convertOneFunction(function))) 657 return failure(); 658 } 659 660 return success(); 661 } 662 663 llvm::MDNode * 664 ModuleTranslation::getAccessGroup(Operation &opInst, 665 SymbolRefAttr accessGroupRef) const { 666 auto metadataName = accessGroupRef.getRootReference(); 667 auto accessGroupName = accessGroupRef.getLeafReference(); 668 auto metadataOp = SymbolTable::lookupNearestSymbolFrom<LLVM::MetadataOp>( 669 opInst.getParentOp(), metadataName); 670 auto *accessGroupOp = 671 SymbolTable::lookupNearestSymbolFrom(metadataOp, accessGroupName); 672 return accessGroupMetadataMapping.lookup(accessGroupOp); 673 } 674 675 LogicalResult ModuleTranslation::createAccessGroupMetadata() { 676 mlirModule->walk([&](LLVM::MetadataOp metadatas) { 677 metadatas.walk([&](LLVM::AccessGroupMetadataOp op) { 678 llvm::LLVMContext &ctx = llvmModule->getContext(); 679 llvm::MDNode *accessGroup = llvm::MDNode::getDistinct(ctx, {}); 680 accessGroupMetadataMapping.insert({op, accessGroup}); 681 }); 682 }); 683 return success(); 684 } 685 686 void ModuleTranslation::setAccessGroupsMetadata(Operation *op, 687 llvm::Instruction *inst) { 688 auto accessGroups = 689 op->getAttrOfType<ArrayAttr>(LLVMDialect::getAccessGroupsAttrName()); 690 if (accessGroups && !accessGroups.empty()) { 691 llvm::Module *module = inst->getModule(); 692 SmallVector<llvm::Metadata *> metadatas; 693 for (SymbolRefAttr accessGroupRef : 694 accessGroups.getAsRange<SymbolRefAttr>()) 695 metadatas.push_back(getAccessGroup(*op, accessGroupRef)); 696 697 llvm::MDNode *unionMD = nullptr; 698 if (metadatas.size() == 1) 699 unionMD = llvm::cast<llvm::MDNode>(metadatas.front()); 700 else if (metadatas.size() >= 2) 701 unionMD = llvm::MDNode::get(module->getContext(), metadatas); 702 703 inst->setMetadata(module->getMDKindID("llvm.access.group"), unionMD); 704 } 705 } 706 707 llvm::Type *ModuleTranslation::convertType(Type type) { 708 return typeTranslator.translateType(type); 709 } 710 711 /// A helper to look up remapped operands in the value remapping table.` 712 SmallVector<llvm::Value *, 8> 713 ModuleTranslation::lookupValues(ValueRange values) { 714 SmallVector<llvm::Value *, 8> remapped; 715 remapped.reserve(values.size()); 716 for (Value v : values) 717 remapped.push_back(lookupValue(v)); 718 return remapped; 719 } 720 721 const llvm::DILocation * 722 ModuleTranslation::translateLoc(Location loc, llvm::DILocalScope *scope) { 723 return debugTranslation->translateLoc(loc, scope); 724 } 725 726 llvm::NamedMDNode * 727 ModuleTranslation::getOrInsertNamedModuleMetadata(StringRef name) { 728 return llvmModule->getOrInsertNamedMetadata(name); 729 } 730 731 static std::unique_ptr<llvm::Module> 732 prepareLLVMModule(Operation *m, llvm::LLVMContext &llvmContext, 733 StringRef name) { 734 m->getContext()->getOrLoadDialect<LLVM::LLVMDialect>(); 735 auto llvmModule = std::make_unique<llvm::Module>(name, llvmContext); 736 if (auto dataLayoutAttr = 737 m->getAttr(LLVM::LLVMDialect::getDataLayoutAttrName())) 738 llvmModule->setDataLayout(dataLayoutAttr.cast<StringAttr>().getValue()); 739 if (auto targetTripleAttr = 740 m->getAttr(LLVM::LLVMDialect::getTargetTripleAttrName())) 741 llvmModule->setTargetTriple(targetTripleAttr.cast<StringAttr>().getValue()); 742 743 // Inject declarations for `malloc` and `free` functions that can be used in 744 // memref allocation/deallocation coming from standard ops lowering. 745 llvm::IRBuilder<> builder(llvmContext); 746 llvmModule->getOrInsertFunction("malloc", builder.getInt8PtrTy(), 747 builder.getInt64Ty()); 748 llvmModule->getOrInsertFunction("free", builder.getVoidTy(), 749 builder.getInt8PtrTy()); 750 751 return llvmModule; 752 } 753 754 std::unique_ptr<llvm::Module> 755 mlir::translateModuleToLLVMIR(Operation *module, llvm::LLVMContext &llvmContext, 756 StringRef name) { 757 if (!satisfiesLLVMModule(module)) 758 return nullptr; 759 if (failed(checkSupportedModuleOps(module))) 760 return nullptr; 761 std::unique_ptr<llvm::Module> llvmModule = 762 prepareLLVMModule(module, llvmContext, name); 763 764 LLVM::ensureDistinctSuccessors(module); 765 766 ModuleTranslation translator(module, std::move(llvmModule)); 767 if (failed(translator.convertFunctionSignatures())) 768 return nullptr; 769 if (failed(translator.convertGlobals())) 770 return nullptr; 771 if (failed(translator.createAccessGroupMetadata())) 772 return nullptr; 773 if (failed(translator.convertFunctions())) 774 return nullptr; 775 if (llvm::verifyModule(*translator.llvmModule, &llvm::errs())) 776 return nullptr; 777 778 return std::move(translator.llvmModule); 779 } 780