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 if (op.section().hasValue()) 414 var->setSection(*op.section()); 415 416 globalsMapping.try_emplace(op, var); 417 } 418 419 // Convert global variable bodies. This is done after all global variables 420 // have been created in LLVM IR because a global body may refer to another 421 // global or itself. So all global variables need to be mapped first. 422 for (auto op : getModuleBody(mlirModule).getOps<LLVM::GlobalOp>()) { 423 if (Block *initializer = op.getInitializerBlock()) { 424 llvm::IRBuilder<> builder(llvmModule->getContext()); 425 for (auto &op : initializer->without_terminator()) { 426 if (failed(convertOperation(op, builder)) || 427 !isa<llvm::Constant>(lookupValue(op.getResult(0)))) 428 return emitError(op.getLoc(), "unemittable constant value"); 429 } 430 ReturnOp ret = cast<ReturnOp>(initializer->getTerminator()); 431 llvm::Constant *cst = 432 cast<llvm::Constant>(lookupValue(ret.getOperand(0))); 433 auto *global = cast<llvm::GlobalVariable>(lookupGlobal(op)); 434 if (!shouldDropGlobalInitializer(global->getLinkage(), cst)) 435 global->setInitializer(cst); 436 } 437 } 438 439 return success(); 440 } 441 442 /// Attempts to add an attribute identified by `key`, optionally with the given 443 /// `value` to LLVM function `llvmFunc`. Reports errors at `loc` if any. If the 444 /// attribute has a kind known to LLVM IR, create the attribute of this kind, 445 /// otherwise keep it as a string attribute. Performs additional checks for 446 /// attributes known to have or not have a value in order to avoid assertions 447 /// inside LLVM upon construction. 448 static LogicalResult checkedAddLLVMFnAttribute(Location loc, 449 llvm::Function *llvmFunc, 450 StringRef key, 451 StringRef value = StringRef()) { 452 auto kind = llvm::Attribute::getAttrKindFromName(key); 453 if (kind == llvm::Attribute::None) { 454 llvmFunc->addFnAttr(key, value); 455 return success(); 456 } 457 458 if (llvm::Attribute::doesAttrKindHaveArgument(kind)) { 459 if (value.empty()) 460 return emitError(loc) << "LLVM attribute '" << key << "' expects a value"; 461 462 int result; 463 if (!value.getAsInteger(/*Radix=*/0, result)) 464 llvmFunc->addFnAttr( 465 llvm::Attribute::get(llvmFunc->getContext(), kind, result)); 466 else 467 llvmFunc->addFnAttr(key, value); 468 return success(); 469 } 470 471 if (!value.empty()) 472 return emitError(loc) << "LLVM attribute '" << key 473 << "' does not expect a value, found '" << value 474 << "'"; 475 476 llvmFunc->addFnAttr(kind); 477 return success(); 478 } 479 480 /// Attaches the attributes listed in the given array attribute to `llvmFunc`. 481 /// Reports error to `loc` if any and returns immediately. Expects `attributes` 482 /// to be an array attribute containing either string attributes, treated as 483 /// value-less LLVM attributes, or array attributes containing two string 484 /// attributes, with the first string being the name of the corresponding LLVM 485 /// attribute and the second string beings its value. Note that even integer 486 /// attributes are expected to have their values expressed as strings. 487 static LogicalResult 488 forwardPassthroughAttributes(Location loc, Optional<ArrayAttr> attributes, 489 llvm::Function *llvmFunc) { 490 if (!attributes) 491 return success(); 492 493 for (Attribute attr : *attributes) { 494 if (auto stringAttr = attr.dyn_cast<StringAttr>()) { 495 if (failed( 496 checkedAddLLVMFnAttribute(loc, llvmFunc, stringAttr.getValue()))) 497 return failure(); 498 continue; 499 } 500 501 auto arrayAttr = attr.dyn_cast<ArrayAttr>(); 502 if (!arrayAttr || arrayAttr.size() != 2) 503 return emitError(loc) 504 << "expected 'passthrough' to contain string or array attributes"; 505 506 auto keyAttr = arrayAttr[0].dyn_cast<StringAttr>(); 507 auto valueAttr = arrayAttr[1].dyn_cast<StringAttr>(); 508 if (!keyAttr || !valueAttr) 509 return emitError(loc) 510 << "expected arrays within 'passthrough' to contain two strings"; 511 512 if (failed(checkedAddLLVMFnAttribute(loc, llvmFunc, keyAttr.getValue(), 513 valueAttr.getValue()))) 514 return failure(); 515 } 516 return success(); 517 } 518 519 LogicalResult ModuleTranslation::convertOneFunction(LLVMFuncOp func) { 520 // Clear the block, branch value mappings, they are only relevant within one 521 // function. 522 blockMapping.clear(); 523 valueMapping.clear(); 524 branchMapping.clear(); 525 llvm::Function *llvmFunc = lookupFunction(func.getName()); 526 527 // Translate the debug information for this function. 528 debugTranslation->translate(func, *llvmFunc); 529 530 // Add function arguments to the value remapping table. 531 // If there was noalias info then we decorate each argument accordingly. 532 unsigned int argIdx = 0; 533 for (auto kvp : llvm::zip(func.getArguments(), llvmFunc->args())) { 534 llvm::Argument &llvmArg = std::get<1>(kvp); 535 BlockArgument mlirArg = std::get<0>(kvp); 536 537 if (auto attr = func.getArgAttrOfType<BoolAttr>( 538 argIdx, LLVMDialect::getNoAliasAttrName())) { 539 // NB: Attribute already verified to be boolean, so check if we can indeed 540 // attach the attribute to this argument, based on its type. 541 auto argTy = mlirArg.getType(); 542 if (!argTy.isa<LLVM::LLVMPointerType>()) 543 return func.emitError( 544 "llvm.noalias attribute attached to LLVM non-pointer argument"); 545 if (attr.getValue()) 546 llvmArg.addAttr(llvm::Attribute::AttrKind::NoAlias); 547 } 548 549 if (auto attr = func.getArgAttrOfType<IntegerAttr>( 550 argIdx, LLVMDialect::getAlignAttrName())) { 551 // NB: Attribute already verified to be int, so check if we can indeed 552 // attach the attribute to this argument, based on its type. 553 auto argTy = mlirArg.getType(); 554 if (!argTy.isa<LLVM::LLVMPointerType>()) 555 return func.emitError( 556 "llvm.align attribute attached to LLVM non-pointer argument"); 557 llvmArg.addAttrs( 558 llvm::AttrBuilder().addAlignmentAttr(llvm::Align(attr.getInt()))); 559 } 560 561 if (auto attr = func.getArgAttrOfType<UnitAttr>(argIdx, "llvm.sret")) { 562 auto argTy = mlirArg.getType(); 563 if (!argTy.isa<LLVM::LLVMPointerType>()) 564 return func.emitError( 565 "llvm.sret attribute attached to LLVM non-pointer argument"); 566 llvmArg.addAttrs(llvm::AttrBuilder().addStructRetAttr( 567 llvmArg.getType()->getPointerElementType())); 568 } 569 570 if (auto attr = func.getArgAttrOfType<UnitAttr>(argIdx, "llvm.byval")) { 571 auto argTy = mlirArg.getType(); 572 if (!argTy.isa<LLVM::LLVMPointerType>()) 573 return func.emitError( 574 "llvm.byval attribute attached to LLVM non-pointer argument"); 575 llvmArg.addAttrs(llvm::AttrBuilder().addByValAttr( 576 llvmArg.getType()->getPointerElementType())); 577 } 578 579 mapValue(mlirArg, &llvmArg); 580 argIdx++; 581 } 582 583 // Check the personality and set it. 584 if (func.personality().hasValue()) { 585 llvm::Type *ty = llvm::Type::getInt8PtrTy(llvmFunc->getContext()); 586 if (llvm::Constant *pfunc = 587 getLLVMConstant(ty, func.personalityAttr(), func.getLoc(), *this)) 588 llvmFunc->setPersonalityFn(pfunc); 589 } 590 591 // First, create all blocks so we can jump to them. 592 llvm::LLVMContext &llvmContext = llvmFunc->getContext(); 593 for (auto &bb : func) { 594 auto *llvmBB = llvm::BasicBlock::Create(llvmContext); 595 llvmBB->insertInto(llvmFunc); 596 mapBlock(&bb, llvmBB); 597 } 598 599 // Then, convert blocks one by one in topological order to ensure defs are 600 // converted before uses. 601 auto blocks = detail::getTopologicallySortedBlocks(func.getBody()); 602 for (Block *bb : blocks) { 603 llvm::IRBuilder<> builder(llvmContext); 604 if (failed(convertBlock(*bb, bb->isEntryBlock(), builder))) 605 return failure(); 606 } 607 608 // After all blocks have been traversed and values mapped, connect the PHI 609 // nodes to the results of preceding blocks. 610 detail::connectPHINodes(func.getBody(), *this); 611 612 // Finally, convert dialect attributes attached to the function. 613 return convertDialectAttributes(func); 614 } 615 616 LogicalResult ModuleTranslation::convertDialectAttributes(Operation *op) { 617 for (NamedAttribute attribute : op->getDialectAttrs()) 618 if (failed(iface.amendOperation(op, attribute, *this))) 619 return failure(); 620 return success(); 621 } 622 623 /// Check whether the module contains only supported ops directly in its body. 624 static LogicalResult checkSupportedModuleOps(Operation *m) { 625 for (Operation &o : getModuleBody(m).getOperations()) 626 if (!isa<LLVM::LLVMFuncOp, LLVM::GlobalOp, LLVM::MetadataOp>(&o) && 627 !o.hasTrait<OpTrait::IsTerminator>()) 628 return o.emitOpError("unsupported module-level operation"); 629 return success(); 630 } 631 632 LogicalResult ModuleTranslation::convertFunctionSignatures() { 633 // Declare all functions first because there may be function calls that form a 634 // call graph with cycles, or global initializers that reference functions. 635 for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) { 636 llvm::FunctionCallee llvmFuncCst = llvmModule->getOrInsertFunction( 637 function.getName(), 638 cast<llvm::FunctionType>(convertType(function.getType()))); 639 llvm::Function *llvmFunc = cast<llvm::Function>(llvmFuncCst.getCallee()); 640 llvmFunc->setLinkage(convertLinkageToLLVM(function.linkage())); 641 mapFunction(function.getName(), llvmFunc); 642 643 // Forward the pass-through attributes to LLVM. 644 if (failed(forwardPassthroughAttributes(function.getLoc(), 645 function.passthrough(), llvmFunc))) 646 return failure(); 647 } 648 649 return success(); 650 } 651 652 LogicalResult ModuleTranslation::convertFunctions() { 653 // Convert functions. 654 for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) { 655 // Ignore external functions. 656 if (function.isExternal()) 657 continue; 658 659 if (failed(convertOneFunction(function))) 660 return failure(); 661 } 662 663 return success(); 664 } 665 666 llvm::MDNode * 667 ModuleTranslation::getAccessGroup(Operation &opInst, 668 SymbolRefAttr accessGroupRef) const { 669 auto metadataName = accessGroupRef.getRootReference(); 670 auto accessGroupName = accessGroupRef.getLeafReference(); 671 auto metadataOp = SymbolTable::lookupNearestSymbolFrom<LLVM::MetadataOp>( 672 opInst.getParentOp(), metadataName); 673 auto *accessGroupOp = 674 SymbolTable::lookupNearestSymbolFrom(metadataOp, accessGroupName); 675 return accessGroupMetadataMapping.lookup(accessGroupOp); 676 } 677 678 LogicalResult ModuleTranslation::createAccessGroupMetadata() { 679 mlirModule->walk([&](LLVM::MetadataOp metadatas) { 680 metadatas.walk([&](LLVM::AccessGroupMetadataOp op) { 681 llvm::LLVMContext &ctx = llvmModule->getContext(); 682 llvm::MDNode *accessGroup = llvm::MDNode::getDistinct(ctx, {}); 683 accessGroupMetadataMapping.insert({op, accessGroup}); 684 }); 685 }); 686 return success(); 687 } 688 689 void ModuleTranslation::setAccessGroupsMetadata(Operation *op, 690 llvm::Instruction *inst) { 691 auto accessGroups = 692 op->getAttrOfType<ArrayAttr>(LLVMDialect::getAccessGroupsAttrName()); 693 if (accessGroups && !accessGroups.empty()) { 694 llvm::Module *module = inst->getModule(); 695 SmallVector<llvm::Metadata *> metadatas; 696 for (SymbolRefAttr accessGroupRef : 697 accessGroups.getAsRange<SymbolRefAttr>()) 698 metadatas.push_back(getAccessGroup(*op, accessGroupRef)); 699 700 llvm::MDNode *unionMD = nullptr; 701 if (metadatas.size() == 1) 702 unionMD = llvm::cast<llvm::MDNode>(metadatas.front()); 703 else if (metadatas.size() >= 2) 704 unionMD = llvm::MDNode::get(module->getContext(), metadatas); 705 706 inst->setMetadata(module->getMDKindID("llvm.access.group"), unionMD); 707 } 708 } 709 710 llvm::Type *ModuleTranslation::convertType(Type type) { 711 return typeTranslator.translateType(type); 712 } 713 714 /// A helper to look up remapped operands in the value remapping table.` 715 SmallVector<llvm::Value *, 8> 716 ModuleTranslation::lookupValues(ValueRange values) { 717 SmallVector<llvm::Value *, 8> remapped; 718 remapped.reserve(values.size()); 719 for (Value v : values) 720 remapped.push_back(lookupValue(v)); 721 return remapped; 722 } 723 724 const llvm::DILocation * 725 ModuleTranslation::translateLoc(Location loc, llvm::DILocalScope *scope) { 726 return debugTranslation->translateLoc(loc, scope); 727 } 728 729 llvm::NamedMDNode * 730 ModuleTranslation::getOrInsertNamedModuleMetadata(StringRef name) { 731 return llvmModule->getOrInsertNamedMetadata(name); 732 } 733 734 static std::unique_ptr<llvm::Module> 735 prepareLLVMModule(Operation *m, llvm::LLVMContext &llvmContext, 736 StringRef name) { 737 m->getContext()->getOrLoadDialect<LLVM::LLVMDialect>(); 738 auto llvmModule = std::make_unique<llvm::Module>(name, llvmContext); 739 if (auto dataLayoutAttr = 740 m->getAttr(LLVM::LLVMDialect::getDataLayoutAttrName())) 741 llvmModule->setDataLayout(dataLayoutAttr.cast<StringAttr>().getValue()); 742 if (auto targetTripleAttr = 743 m->getAttr(LLVM::LLVMDialect::getTargetTripleAttrName())) 744 llvmModule->setTargetTriple(targetTripleAttr.cast<StringAttr>().getValue()); 745 746 // Inject declarations for `malloc` and `free` functions that can be used in 747 // memref allocation/deallocation coming from standard ops lowering. 748 llvm::IRBuilder<> builder(llvmContext); 749 llvmModule->getOrInsertFunction("malloc", builder.getInt8PtrTy(), 750 builder.getInt64Ty()); 751 llvmModule->getOrInsertFunction("free", builder.getVoidTy(), 752 builder.getInt8PtrTy()); 753 754 return llvmModule; 755 } 756 757 std::unique_ptr<llvm::Module> 758 mlir::translateModuleToLLVMIR(Operation *module, llvm::LLVMContext &llvmContext, 759 StringRef name) { 760 if (!satisfiesLLVMModule(module)) 761 return nullptr; 762 if (failed(checkSupportedModuleOps(module))) 763 return nullptr; 764 std::unique_ptr<llvm::Module> llvmModule = 765 prepareLLVMModule(module, llvmContext, name); 766 767 LLVM::ensureDistinctSuccessors(module); 768 769 ModuleTranslation translator(module, std::move(llvmModule)); 770 if (failed(translator.convertFunctionSignatures())) 771 return nullptr; 772 if (failed(translator.convertGlobals())) 773 return nullptr; 774 if (failed(translator.createAccessGroupMetadata())) 775 return nullptr; 776 if (failed(translator.convertFunctions())) 777 return nullptr; 778 if (llvm::verifyModule(*translator.llvmModule, &llvm::errs())) 779 return nullptr; 780 781 return std::move(translator.llvmModule); 782 } 783