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/DLTI/DLTI.h" 18 #include "mlir/Dialect/LLVMIR/LLVMDialect.h" 19 #include "mlir/Dialect/LLVMIR/Transforms/LegalizeForExport.h" 20 #include "mlir/Dialect/OpenMP/OpenMPDialect.h" 21 #include "mlir/IR/Attributes.h" 22 #include "mlir/IR/BuiltinOps.h" 23 #include "mlir/IR/BuiltinTypes.h" 24 #include "mlir/IR/RegionGraphTraits.h" 25 #include "mlir/Support/LLVM.h" 26 #include "mlir/Target/LLVMIR/LLVMTranslationInterface.h" 27 #include "mlir/Target/LLVMIR/TypeToLLVM.h" 28 #include "llvm/ADT/TypeSwitch.h" 29 30 #include "llvm/ADT/PostOrderIterator.h" 31 #include "llvm/ADT/SetVector.h" 32 #include "llvm/Frontend/OpenMP/OMPIRBuilder.h" 33 #include "llvm/IR/BasicBlock.h" 34 #include "llvm/IR/CFG.h" 35 #include "llvm/IR/Constants.h" 36 #include "llvm/IR/DerivedTypes.h" 37 #include "llvm/IR/IRBuilder.h" 38 #include "llvm/IR/InlineAsm.h" 39 #include "llvm/IR/IntrinsicsNVPTX.h" 40 #include "llvm/IR/LLVMContext.h" 41 #include "llvm/IR/MDBuilder.h" 42 #include "llvm/IR/Module.h" 43 #include "llvm/IR/Verifier.h" 44 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 45 #include "llvm/Transforms/Utils/Cloning.h" 46 #include "llvm/Transforms/Utils/ModuleUtils.h" 47 48 using namespace mlir; 49 using namespace mlir::LLVM; 50 using namespace mlir::LLVM::detail; 51 52 #include "mlir/Dialect/LLVMIR/LLVMConversionEnumsToLLVM.inc" 53 54 /// Translates the given data layout spec attribute to the LLVM IR data layout. 55 /// Only integer, float and endianness entries are currently supported. 56 FailureOr<llvm::DataLayout> 57 translateDataLayout(DataLayoutSpecInterface attribute, 58 const DataLayout &dataLayout, 59 Optional<Location> loc = llvm::None) { 60 if (!loc) 61 loc = UnknownLoc::get(attribute.getContext()); 62 63 // Translate the endianness attribute. 64 std::string llvmDataLayout; 65 llvm::raw_string_ostream layoutStream(llvmDataLayout); 66 for (DataLayoutEntryInterface entry : attribute.getEntries()) { 67 auto key = entry.getKey().dyn_cast<StringAttr>(); 68 if (!key) 69 continue; 70 if (key.getValue() == DLTIDialect::kDataLayoutEndiannessKey) { 71 auto value = entry.getValue().cast<StringAttr>(); 72 bool isLittleEndian = 73 value.getValue() == DLTIDialect::kDataLayoutEndiannessLittle; 74 layoutStream << (isLittleEndian ? "e" : "E"); 75 layoutStream.flush(); 76 continue; 77 } 78 emitError(*loc) << "unsupported data layout key " << key; 79 return failure(); 80 } 81 82 // Go through the list of entries to check which types are explicitly 83 // specified in entries. Don't use the entries directly though but query the 84 // data from the layout. 85 for (DataLayoutEntryInterface entry : attribute.getEntries()) { 86 auto type = entry.getKey().dyn_cast<Type>(); 87 if (!type) 88 continue; 89 // Data layout for the index type is irrelevant at this point. 90 if (type.isa<IndexType>()) 91 continue; 92 FailureOr<std::string> prefix = 93 llvm::TypeSwitch<Type, FailureOr<std::string>>(type) 94 .Case<IntegerType>( 95 [loc](IntegerType integerType) -> FailureOr<std::string> { 96 if (integerType.getSignedness() == IntegerType::Signless) 97 return std::string("i"); 98 emitError(*loc) 99 << "unsupported data layout for non-signless integer " 100 << integerType; 101 return failure(); 102 }) 103 .Case<Float16Type, Float32Type, Float64Type, Float80Type, 104 Float128Type>([](Type) { return std::string("f"); }) 105 .Default([loc](Type type) -> FailureOr<std::string> { 106 emitError(*loc) << "unsupported type in data layout: " << type; 107 return failure(); 108 }); 109 if (failed(prefix)) 110 return failure(); 111 112 unsigned size = dataLayout.getTypeSizeInBits(type); 113 unsigned abi = dataLayout.getTypeABIAlignment(type) * 8u; 114 unsigned preferred = dataLayout.getTypePreferredAlignment(type) * 8u; 115 layoutStream << "-" << *prefix << size << ":" << abi; 116 if (abi != preferred) 117 layoutStream << ":" << preferred; 118 } 119 layoutStream.flush(); 120 StringRef layoutSpec(llvmDataLayout); 121 if (layoutSpec.startswith("-")) 122 layoutSpec = layoutSpec.drop_front(); 123 124 return llvm::DataLayout(layoutSpec); 125 } 126 127 /// Builds a constant of a sequential LLVM type `type`, potentially containing 128 /// other sequential types recursively, from the individual constant values 129 /// provided in `constants`. `shape` contains the number of elements in nested 130 /// sequential types. Reports errors at `loc` and returns nullptr on error. 131 static llvm::Constant * 132 buildSequentialConstant(ArrayRef<llvm::Constant *> &constants, 133 ArrayRef<int64_t> shape, llvm::Type *type, 134 Location loc) { 135 if (shape.empty()) { 136 llvm::Constant *result = constants.front(); 137 constants = constants.drop_front(); 138 return result; 139 } 140 141 llvm::Type *elementType; 142 if (auto *arrayTy = dyn_cast<llvm::ArrayType>(type)) { 143 elementType = arrayTy->getElementType(); 144 } else if (auto *vectorTy = dyn_cast<llvm::VectorType>(type)) { 145 elementType = vectorTy->getElementType(); 146 } else { 147 emitError(loc) << "expected sequential LLVM types wrapping a scalar"; 148 return nullptr; 149 } 150 151 SmallVector<llvm::Constant *, 8> nested; 152 nested.reserve(shape.front()); 153 for (int64_t i = 0; i < shape.front(); ++i) { 154 nested.push_back(buildSequentialConstant(constants, shape.drop_front(), 155 elementType, loc)); 156 if (!nested.back()) 157 return nullptr; 158 } 159 160 if (shape.size() == 1 && type->isVectorTy()) 161 return llvm::ConstantVector::get(nested); 162 return llvm::ConstantArray::get( 163 llvm::ArrayType::get(elementType, shape.front()), nested); 164 } 165 166 /// Returns the first non-sequential type nested in sequential types. 167 static llvm::Type *getInnermostElementType(llvm::Type *type) { 168 do { 169 if (auto *arrayTy = dyn_cast<llvm::ArrayType>(type)) { 170 type = arrayTy->getElementType(); 171 } else if (auto *vectorTy = dyn_cast<llvm::VectorType>(type)) { 172 type = vectorTy->getElementType(); 173 } else { 174 return type; 175 } 176 } while (true); 177 } 178 179 /// Convert a dense elements attribute to an LLVM IR constant using its raw data 180 /// storage if possible. This supports elements attributes of tensor or vector 181 /// type and avoids constructing separate objects for individual values of the 182 /// innermost dimension. Constants for other dimensions are still constructed 183 /// recursively. Returns null if constructing from raw data is not supported for 184 /// this type, e.g., element type is not a power-of-two-sized primitive. Reports 185 /// other errors at `loc`. 186 static llvm::Constant * 187 convertDenseElementsAttr(Location loc, DenseElementsAttr denseElementsAttr, 188 llvm::Type *llvmType, 189 const ModuleTranslation &moduleTranslation) { 190 if (!denseElementsAttr) 191 return nullptr; 192 193 llvm::Type *innermostLLVMType = getInnermostElementType(llvmType); 194 if (!llvm::ConstantDataSequential::isElementTypeCompatible(innermostLLVMType)) 195 return nullptr; 196 197 ShapedType type = denseElementsAttr.getType(); 198 if (type.getNumElements() == 0) 199 return nullptr; 200 201 // Compute the shape of all dimensions but the innermost. Note that the 202 // innermost dimension may be that of the vector element type. 203 bool hasVectorElementType = type.getElementType().isa<VectorType>(); 204 unsigned numAggregates = 205 denseElementsAttr.getNumElements() / 206 (hasVectorElementType ? 1 207 : denseElementsAttr.getType().getShape().back()); 208 ArrayRef<int64_t> outerShape = type.getShape(); 209 if (!hasVectorElementType) 210 outerShape = outerShape.drop_back(); 211 212 // Handle the case of vector splat, LLVM has special support for it. 213 if (denseElementsAttr.isSplat() && 214 (type.isa<VectorType>() || hasVectorElementType)) { 215 llvm::Constant *splatValue = LLVM::detail::getLLVMConstant( 216 innermostLLVMType, denseElementsAttr.getSplatValue<Attribute>(), loc, 217 moduleTranslation, /*isTopLevel=*/false); 218 llvm::Constant *splatVector = 219 llvm::ConstantDataVector::getSplat(0, splatValue); 220 SmallVector<llvm::Constant *> constants(numAggregates, splatVector); 221 ArrayRef<llvm::Constant *> constantsRef = constants; 222 return buildSequentialConstant(constantsRef, outerShape, llvmType, loc); 223 } 224 if (denseElementsAttr.isSplat()) 225 return nullptr; 226 227 // In case of non-splat, create a constructor for the innermost constant from 228 // a piece of raw data. 229 std::function<llvm::Constant *(StringRef)> buildCstData; 230 if (type.isa<TensorType>()) { 231 auto vectorElementType = type.getElementType().dyn_cast<VectorType>(); 232 if (vectorElementType && vectorElementType.getRank() == 1) { 233 buildCstData = [&](StringRef data) { 234 return llvm::ConstantDataVector::getRaw( 235 data, vectorElementType.getShape().back(), innermostLLVMType); 236 }; 237 } else if (!vectorElementType) { 238 buildCstData = [&](StringRef data) { 239 return llvm::ConstantDataArray::getRaw(data, type.getShape().back(), 240 innermostLLVMType); 241 }; 242 } 243 } else if (type.isa<VectorType>()) { 244 buildCstData = [&](StringRef data) { 245 return llvm::ConstantDataVector::getRaw(data, type.getShape().back(), 246 innermostLLVMType); 247 }; 248 } 249 if (!buildCstData) 250 return nullptr; 251 252 // Create innermost constants and defer to the default constant creation 253 // mechanism for other dimensions. 254 SmallVector<llvm::Constant *> constants; 255 unsigned aggregateSize = denseElementsAttr.getType().getShape().back() * 256 (innermostLLVMType->getScalarSizeInBits() / 8); 257 constants.reserve(numAggregates); 258 for (unsigned i = 0; i < numAggregates; ++i) { 259 StringRef data(denseElementsAttr.getRawData().data() + i * aggregateSize, 260 aggregateSize); 261 constants.push_back(buildCstData(data)); 262 } 263 264 ArrayRef<llvm::Constant *> constantsRef = constants; 265 return buildSequentialConstant(constantsRef, outerShape, llvmType, loc); 266 } 267 268 /// Create an LLVM IR constant of `llvmType` from the MLIR attribute `attr`. 269 /// This currently supports integer, floating point, splat and dense element 270 /// attributes and combinations thereof. Also, an array attribute with two 271 /// elements is supported to represent a complex constant. In case of error, 272 /// report it to `loc` and return nullptr. 273 llvm::Constant *mlir::LLVM::detail::getLLVMConstant( 274 llvm::Type *llvmType, Attribute attr, Location loc, 275 const ModuleTranslation &moduleTranslation, bool isTopLevel) { 276 if (!attr) 277 return llvm::UndefValue::get(llvmType); 278 if (auto *structType = dyn_cast<::llvm::StructType>(llvmType)) { 279 if (!isTopLevel) { 280 emitError(loc, "nested struct types are not supported in constants"); 281 return nullptr; 282 } 283 auto arrayAttr = attr.cast<ArrayAttr>(); 284 llvm::Type *elementType = structType->getElementType(0); 285 llvm::Constant *real = getLLVMConstant(elementType, arrayAttr[0], loc, 286 moduleTranslation, false); 287 if (!real) 288 return nullptr; 289 llvm::Constant *imag = getLLVMConstant(elementType, arrayAttr[1], loc, 290 moduleTranslation, false); 291 if (!imag) 292 return nullptr; 293 return llvm::ConstantStruct::get(structType, {real, imag}); 294 } 295 // For integer types, we allow a mismatch in sizes as the index type in 296 // MLIR might have a different size than the index type in the LLVM module. 297 if (auto intAttr = attr.dyn_cast<IntegerAttr>()) 298 return llvm::ConstantInt::get( 299 llvmType, 300 intAttr.getValue().sextOrTrunc(llvmType->getIntegerBitWidth())); 301 if (auto floatAttr = attr.dyn_cast<FloatAttr>()) { 302 if (llvmType != 303 llvm::Type::getFloatingPointTy(llvmType->getContext(), 304 floatAttr.getValue().getSemantics())) { 305 emitError(loc, "FloatAttr does not match expected type of the constant"); 306 return nullptr; 307 } 308 return llvm::ConstantFP::get(llvmType, floatAttr.getValue()); 309 } 310 if (auto funcAttr = attr.dyn_cast<FlatSymbolRefAttr>()) 311 return llvm::ConstantExpr::getBitCast( 312 moduleTranslation.lookupFunction(funcAttr.getValue()), llvmType); 313 if (auto splatAttr = attr.dyn_cast<SplatElementsAttr>()) { 314 llvm::Type *elementType; 315 uint64_t numElements; 316 bool isScalable = false; 317 if (auto *arrayTy = dyn_cast<llvm::ArrayType>(llvmType)) { 318 elementType = arrayTy->getElementType(); 319 numElements = arrayTy->getNumElements(); 320 } else if (auto *fVectorTy = dyn_cast<llvm::FixedVectorType>(llvmType)) { 321 elementType = fVectorTy->getElementType(); 322 numElements = fVectorTy->getNumElements(); 323 } else if (auto *sVectorTy = dyn_cast<llvm::ScalableVectorType>(llvmType)) { 324 elementType = sVectorTy->getElementType(); 325 numElements = sVectorTy->getMinNumElements(); 326 isScalable = true; 327 } else { 328 llvm_unreachable("unrecognized constant vector type"); 329 } 330 // Splat value is a scalar. Extract it only if the element type is not 331 // another sequence type. The recursion terminates because each step removes 332 // one outer sequential type. 333 bool elementTypeSequential = 334 isa<llvm::ArrayType, llvm::VectorType>(elementType); 335 llvm::Constant *child = getLLVMConstant( 336 elementType, 337 elementTypeSequential ? splatAttr 338 : splatAttr.getSplatValue<Attribute>(), 339 loc, moduleTranslation, false); 340 if (!child) 341 return nullptr; 342 if (llvmType->isVectorTy()) 343 return llvm::ConstantVector::getSplat( 344 llvm::ElementCount::get(numElements, /*Scalable=*/isScalable), child); 345 if (llvmType->isArrayTy()) { 346 auto *arrayType = llvm::ArrayType::get(elementType, numElements); 347 SmallVector<llvm::Constant *, 8> constants(numElements, child); 348 return llvm::ConstantArray::get(arrayType, constants); 349 } 350 } 351 352 // Try using raw elements data if possible. 353 if (llvm::Constant *result = 354 convertDenseElementsAttr(loc, attr.dyn_cast<DenseElementsAttr>(), 355 llvmType, moduleTranslation)) { 356 return result; 357 } 358 359 // Fall back to element-by-element construction otherwise. 360 if (auto elementsAttr = attr.dyn_cast<ElementsAttr>()) { 361 assert(elementsAttr.getType().hasStaticShape()); 362 assert(!elementsAttr.getType().getShape().empty() && 363 "unexpected empty elements attribute shape"); 364 365 SmallVector<llvm::Constant *, 8> constants; 366 constants.reserve(elementsAttr.getNumElements()); 367 llvm::Type *innermostType = getInnermostElementType(llvmType); 368 for (auto n : elementsAttr.getValues<Attribute>()) { 369 constants.push_back( 370 getLLVMConstant(innermostType, n, loc, moduleTranslation, false)); 371 if (!constants.back()) 372 return nullptr; 373 } 374 ArrayRef<llvm::Constant *> constantsRef = constants; 375 llvm::Constant *result = buildSequentialConstant( 376 constantsRef, elementsAttr.getType().getShape(), llvmType, loc); 377 assert(constantsRef.empty() && "did not consume all elemental constants"); 378 return result; 379 } 380 381 if (auto stringAttr = attr.dyn_cast<StringAttr>()) { 382 return llvm::ConstantDataArray::get( 383 moduleTranslation.getLLVMContext(), 384 ArrayRef<char>{stringAttr.getValue().data(), 385 stringAttr.getValue().size()}); 386 } 387 emitError(loc, "unsupported constant value"); 388 return nullptr; 389 } 390 391 ModuleTranslation::ModuleTranslation(Operation *module, 392 std::unique_ptr<llvm::Module> llvmModule) 393 : mlirModule(module), llvmModule(std::move(llvmModule)), 394 debugTranslation( 395 std::make_unique<DebugTranslation>(module, *this->llvmModule)), 396 typeTranslator(this->llvmModule->getContext()), 397 iface(module->getContext()) { 398 assert(satisfiesLLVMModule(mlirModule) && 399 "mlirModule should honor LLVM's module semantics."); 400 } 401 ModuleTranslation::~ModuleTranslation() { 402 if (ompBuilder) 403 ompBuilder->finalize(); 404 } 405 406 void ModuleTranslation::forgetMapping(Region ®ion) { 407 SmallVector<Region *> toProcess; 408 toProcess.push_back(®ion); 409 while (!toProcess.empty()) { 410 Region *current = toProcess.pop_back_val(); 411 for (Block &block : *current) { 412 blockMapping.erase(&block); 413 for (Value arg : block.getArguments()) 414 valueMapping.erase(arg); 415 for (Operation &op : block) { 416 for (Value value : op.getResults()) 417 valueMapping.erase(value); 418 if (op.hasSuccessors()) 419 branchMapping.erase(&op); 420 if (isa<LLVM::GlobalOp>(op)) 421 globalsMapping.erase(&op); 422 accessGroupMetadataMapping.erase(&op); 423 llvm::append_range( 424 toProcess, 425 llvm::map_range(op.getRegions(), [](Region &r) { return &r; })); 426 } 427 } 428 } 429 } 430 431 /// Get the SSA value passed to the current block from the terminator operation 432 /// of its predecessor. 433 static Value getPHISourceValue(Block *current, Block *pred, 434 unsigned numArguments, unsigned index) { 435 Operation &terminator = *pred->getTerminator(); 436 if (isa<LLVM::BrOp>(terminator)) 437 return terminator.getOperand(index); 438 439 #ifndef NDEBUG 440 llvm::SmallPtrSet<Block *, 4> seenSuccessors; 441 for (unsigned i = 0, e = terminator.getNumSuccessors(); i < e; ++i) { 442 Block *successor = terminator.getSuccessor(i); 443 auto branch = cast<BranchOpInterface>(terminator); 444 SuccessorOperands successorOperands = branch.getSuccessorOperands(i); 445 assert( 446 (!seenSuccessors.contains(successor) || successorOperands.empty()) && 447 "successors with arguments in LLVM branches must be different blocks"); 448 seenSuccessors.insert(successor); 449 } 450 #endif 451 452 // For instructions that branch based on a condition value, we need to take 453 // the operands for the branch that was taken. 454 if (auto condBranchOp = dyn_cast<LLVM::CondBrOp>(terminator)) { 455 // For conditional branches, we take the operands from either the "true" or 456 // the "false" branch. 457 return condBranchOp.getSuccessor(0) == current 458 ? condBranchOp.getTrueDestOperands()[index] 459 : condBranchOp.getFalseDestOperands()[index]; 460 } 461 462 if (auto switchOp = dyn_cast<LLVM::SwitchOp>(terminator)) { 463 // For switches, we take the operands from either the default case, or from 464 // the case branch that was taken. 465 if (switchOp.getDefaultDestination() == current) 466 return switchOp.getDefaultOperands()[index]; 467 for (const auto &i : llvm::enumerate(switchOp.getCaseDestinations())) 468 if (i.value() == current) 469 return switchOp.getCaseOperands(i.index())[index]; 470 } 471 472 if (auto invokeOp = dyn_cast<LLVM::InvokeOp>(terminator)) { 473 return invokeOp.getNormalDest() == current 474 ? invokeOp.getNormalDestOperands()[index] 475 : invokeOp.getUnwindDestOperands()[index]; 476 } 477 478 llvm_unreachable( 479 "only branch, switch or invoke operations can be terminators " 480 "of a block that has successors"); 481 } 482 483 /// Connect the PHI nodes to the results of preceding blocks. 484 void mlir::LLVM::detail::connectPHINodes(Region ®ion, 485 const ModuleTranslation &state) { 486 // Skip the first block, it cannot be branched to and its arguments correspond 487 // to the arguments of the LLVM function. 488 for (auto it = std::next(region.begin()), eit = region.end(); it != eit; 489 ++it) { 490 Block *bb = &*it; 491 llvm::BasicBlock *llvmBB = state.lookupBlock(bb); 492 auto phis = llvmBB->phis(); 493 auto numArguments = bb->getNumArguments(); 494 assert(numArguments == std::distance(phis.begin(), phis.end())); 495 for (auto &numberedPhiNode : llvm::enumerate(phis)) { 496 auto &phiNode = numberedPhiNode.value(); 497 unsigned index = numberedPhiNode.index(); 498 for (auto *pred : bb->getPredecessors()) { 499 // Find the LLVM IR block that contains the converted terminator 500 // instruction and use it in the PHI node. Note that this block is not 501 // necessarily the same as state.lookupBlock(pred), some operations 502 // (in particular, OpenMP operations using OpenMPIRBuilder) may have 503 // split the blocks. 504 llvm::Instruction *terminator = 505 state.lookupBranch(pred->getTerminator()); 506 assert(terminator && "missing the mapping for a terminator"); 507 phiNode.addIncoming( 508 state.lookupValue(getPHISourceValue(bb, pred, numArguments, index)), 509 terminator->getParent()); 510 } 511 } 512 } 513 } 514 515 /// Sort function blocks topologically. 516 SetVector<Block *> 517 mlir::LLVM::detail::getTopologicallySortedBlocks(Region ®ion) { 518 // For each block that has not been visited yet (i.e. that has no 519 // predecessors), add it to the list as well as its successors. 520 SetVector<Block *> blocks; 521 for (Block &b : region) { 522 if (blocks.count(&b) == 0) { 523 llvm::ReversePostOrderTraversal<Block *> traversal(&b); 524 blocks.insert(traversal.begin(), traversal.end()); 525 } 526 } 527 assert(blocks.size() == region.getBlocks().size() && 528 "some blocks are not sorted"); 529 530 return blocks; 531 } 532 533 llvm::Value *mlir::LLVM::detail::createIntrinsicCall( 534 llvm::IRBuilderBase &builder, llvm::Intrinsic::ID intrinsic, 535 ArrayRef<llvm::Value *> args, ArrayRef<llvm::Type *> tys) { 536 llvm::Module *module = builder.GetInsertBlock()->getModule(); 537 llvm::Function *fn = llvm::Intrinsic::getDeclaration(module, intrinsic, tys); 538 return builder.CreateCall(fn, args); 539 } 540 541 /// Given a single MLIR operation, create the corresponding LLVM IR operation 542 /// using the `builder`. 543 LogicalResult 544 ModuleTranslation::convertOperation(Operation &op, 545 llvm::IRBuilderBase &builder) { 546 const LLVMTranslationDialectInterface *opIface = iface.getInterfaceFor(&op); 547 if (!opIface) 548 return op.emitError("cannot be converted to LLVM IR: missing " 549 "`LLVMTranslationDialectInterface` registration for " 550 "dialect for op: ") 551 << op.getName(); 552 553 if (failed(opIface->convertOperation(&op, builder, *this))) 554 return op.emitError("LLVM Translation failed for operation: ") 555 << op.getName(); 556 557 return convertDialectAttributes(&op); 558 } 559 560 /// Convert block to LLVM IR. Unless `ignoreArguments` is set, emit PHI nodes 561 /// to define values corresponding to the MLIR block arguments. These nodes 562 /// are not connected to the source basic blocks, which may not exist yet. Uses 563 /// `builder` to construct the LLVM IR. Expects the LLVM IR basic block to have 564 /// been created for `bb` and included in the block mapping. Inserts new 565 /// instructions at the end of the block and leaves `builder` in a state 566 /// suitable for further insertion into the end of the block. 567 LogicalResult ModuleTranslation::convertBlock(Block &bb, bool ignoreArguments, 568 llvm::IRBuilderBase &builder) { 569 builder.SetInsertPoint(lookupBlock(&bb)); 570 auto *subprogram = builder.GetInsertBlock()->getParent()->getSubprogram(); 571 572 // Before traversing operations, make block arguments available through 573 // value remapping and PHI nodes, but do not add incoming edges for the PHI 574 // nodes just yet: those values may be defined by this or following blocks. 575 // This step is omitted if "ignoreArguments" is set. The arguments of the 576 // first block have been already made available through the remapping of 577 // LLVM function arguments. 578 if (!ignoreArguments) { 579 auto predecessors = bb.getPredecessors(); 580 unsigned numPredecessors = 581 std::distance(predecessors.begin(), predecessors.end()); 582 for (auto arg : bb.getArguments()) { 583 auto wrappedType = arg.getType(); 584 if (!isCompatibleType(wrappedType)) 585 return emitError(bb.front().getLoc(), 586 "block argument does not have an LLVM type"); 587 llvm::Type *type = convertType(wrappedType); 588 llvm::PHINode *phi = builder.CreatePHI(type, numPredecessors); 589 mapValue(arg, phi); 590 } 591 } 592 593 // Traverse operations. 594 for (auto &op : bb) { 595 // Set the current debug location within the builder. 596 builder.SetCurrentDebugLocation( 597 debugTranslation->translateLoc(op.getLoc(), subprogram)); 598 599 if (failed(convertOperation(op, builder))) 600 return failure(); 601 } 602 603 return success(); 604 } 605 606 /// A helper method to get the single Block in an operation honoring LLVM's 607 /// module requirements. 608 static Block &getModuleBody(Operation *module) { 609 return module->getRegion(0).front(); 610 } 611 612 /// A helper method to decide if a constant must not be set as a global variable 613 /// initializer. For an external linkage variable, the variable with an 614 /// initializer is considered externally visible and defined in this module, the 615 /// variable without an initializer is externally available and is defined 616 /// elsewhere. 617 static bool shouldDropGlobalInitializer(llvm::GlobalValue::LinkageTypes linkage, 618 llvm::Constant *cst) { 619 return (linkage == llvm::GlobalVariable::ExternalLinkage && !cst) || 620 linkage == llvm::GlobalVariable::ExternalWeakLinkage; 621 } 622 623 /// Sets the runtime preemption specifier of `gv` to dso_local if 624 /// `dsoLocalRequested` is true, otherwise it is left unchanged. 625 static void addRuntimePreemptionSpecifier(bool dsoLocalRequested, 626 llvm::GlobalValue *gv) { 627 if (dsoLocalRequested) 628 gv->setDSOLocal(true); 629 } 630 631 /// Create named global variables that correspond to llvm.mlir.global 632 /// definitions. Convert llvm.global_ctors and global_dtors ops. 633 LogicalResult ModuleTranslation::convertGlobals() { 634 for (auto op : getModuleBody(mlirModule).getOps<LLVM::GlobalOp>()) { 635 llvm::Type *type = convertType(op.getType()); 636 llvm::Constant *cst = nullptr; 637 if (op.getValueOrNull()) { 638 // String attributes are treated separately because they cannot appear as 639 // in-function constants and are thus not supported by getLLVMConstant. 640 if (auto strAttr = op.getValueOrNull().dyn_cast_or_null<StringAttr>()) { 641 cst = llvm::ConstantDataArray::getString( 642 llvmModule->getContext(), strAttr.getValue(), /*AddNull=*/false); 643 type = cst->getType(); 644 } else if (!(cst = getLLVMConstant(type, op.getValueOrNull(), op.getLoc(), 645 *this))) { 646 return failure(); 647 } 648 } 649 650 auto linkage = convertLinkageToLLVM(op.getLinkage()); 651 auto addrSpace = op.getAddrSpace(); 652 653 // LLVM IR requires constant with linkage other than external or weak 654 // external to have initializers. If MLIR does not provide an initializer, 655 // default to undef. 656 bool dropInitializer = shouldDropGlobalInitializer(linkage, cst); 657 if (!dropInitializer && !cst) 658 cst = llvm::UndefValue::get(type); 659 else if (dropInitializer && cst) 660 cst = nullptr; 661 662 auto *var = new llvm::GlobalVariable( 663 *llvmModule, type, op.getConstant(), linkage, cst, op.getSymName(), 664 /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal, addrSpace); 665 666 if (op.getUnnamedAddr().hasValue()) 667 var->setUnnamedAddr(convertUnnamedAddrToLLVM(*op.getUnnamedAddr())); 668 669 if (op.getSection().hasValue()) 670 var->setSection(*op.getSection()); 671 672 addRuntimePreemptionSpecifier(op.getDsoLocal(), var); 673 674 Optional<uint64_t> alignment = op.getAlignment(); 675 if (alignment.hasValue()) 676 var->setAlignment(llvm::MaybeAlign(alignment.getValue())); 677 678 globalsMapping.try_emplace(op, var); 679 } 680 681 // Convert global variable bodies. This is done after all global variables 682 // have been created in LLVM IR because a global body may refer to another 683 // global or itself. So all global variables need to be mapped first. 684 for (auto op : getModuleBody(mlirModule).getOps<LLVM::GlobalOp>()) { 685 if (Block *initializer = op.getInitializerBlock()) { 686 llvm::IRBuilder<> builder(llvmModule->getContext()); 687 for (auto &op : initializer->without_terminator()) { 688 if (failed(convertOperation(op, builder)) || 689 !isa<llvm::Constant>(lookupValue(op.getResult(0)))) 690 return emitError(op.getLoc(), "unemittable constant value"); 691 } 692 ReturnOp ret = cast<ReturnOp>(initializer->getTerminator()); 693 llvm::Constant *cst = 694 cast<llvm::Constant>(lookupValue(ret.getOperand(0))); 695 auto *global = cast<llvm::GlobalVariable>(lookupGlobal(op)); 696 if (!shouldDropGlobalInitializer(global->getLinkage(), cst)) 697 global->setInitializer(cst); 698 } 699 } 700 701 // Convert llvm.mlir.global_ctors and dtors. 702 for (Operation &op : getModuleBody(mlirModule)) { 703 auto ctorOp = dyn_cast<GlobalCtorsOp>(op); 704 auto dtorOp = dyn_cast<GlobalDtorsOp>(op); 705 if (!ctorOp && !dtorOp) 706 continue; 707 auto range = ctorOp ? llvm::zip(ctorOp.getCtors(), ctorOp.getPriorities()) 708 : llvm::zip(dtorOp.getDtors(), dtorOp.getPriorities()); 709 auto appendGlobalFn = 710 ctorOp ? llvm::appendToGlobalCtors : llvm::appendToGlobalDtors; 711 for (auto symbolAndPriority : range) { 712 llvm::Function *f = lookupFunction( 713 std::get<0>(symbolAndPriority).cast<FlatSymbolRefAttr>().getValue()); 714 appendGlobalFn( 715 *llvmModule, f, 716 std::get<1>(symbolAndPriority).cast<IntegerAttr>().getInt(), 717 /*Data=*/nullptr); 718 } 719 } 720 721 return success(); 722 } 723 724 /// Attempts to add an attribute identified by `key`, optionally with the given 725 /// `value` to LLVM function `llvmFunc`. Reports errors at `loc` if any. If the 726 /// attribute has a kind known to LLVM IR, create the attribute of this kind, 727 /// otherwise keep it as a string attribute. Performs additional checks for 728 /// attributes known to have or not have a value in order to avoid assertions 729 /// inside LLVM upon construction. 730 static LogicalResult checkedAddLLVMFnAttribute(Location loc, 731 llvm::Function *llvmFunc, 732 StringRef key, 733 StringRef value = StringRef()) { 734 auto kind = llvm::Attribute::getAttrKindFromName(key); 735 if (kind == llvm::Attribute::None) { 736 llvmFunc->addFnAttr(key, value); 737 return success(); 738 } 739 740 if (llvm::Attribute::isIntAttrKind(kind)) { 741 if (value.empty()) 742 return emitError(loc) << "LLVM attribute '" << key << "' expects a value"; 743 744 int result; 745 if (!value.getAsInteger(/*Radix=*/0, result)) 746 llvmFunc->addFnAttr( 747 llvm::Attribute::get(llvmFunc->getContext(), kind, result)); 748 else 749 llvmFunc->addFnAttr(key, value); 750 return success(); 751 } 752 753 if (!value.empty()) 754 return emitError(loc) << "LLVM attribute '" << key 755 << "' does not expect a value, found '" << value 756 << "'"; 757 758 llvmFunc->addFnAttr(kind); 759 return success(); 760 } 761 762 /// Attaches the attributes listed in the given array attribute to `llvmFunc`. 763 /// Reports error to `loc` if any and returns immediately. Expects `attributes` 764 /// to be an array attribute containing either string attributes, treated as 765 /// value-less LLVM attributes, or array attributes containing two string 766 /// attributes, with the first string being the name of the corresponding LLVM 767 /// attribute and the second string beings its value. Note that even integer 768 /// attributes are expected to have their values expressed as strings. 769 static LogicalResult 770 forwardPassthroughAttributes(Location loc, Optional<ArrayAttr> attributes, 771 llvm::Function *llvmFunc) { 772 if (!attributes) 773 return success(); 774 775 for (Attribute attr : *attributes) { 776 if (auto stringAttr = attr.dyn_cast<StringAttr>()) { 777 if (failed( 778 checkedAddLLVMFnAttribute(loc, llvmFunc, stringAttr.getValue()))) 779 return failure(); 780 continue; 781 } 782 783 auto arrayAttr = attr.dyn_cast<ArrayAttr>(); 784 if (!arrayAttr || arrayAttr.size() != 2) 785 return emitError(loc) 786 << "expected 'passthrough' to contain string or array attributes"; 787 788 auto keyAttr = arrayAttr[0].dyn_cast<StringAttr>(); 789 auto valueAttr = arrayAttr[1].dyn_cast<StringAttr>(); 790 if (!keyAttr || !valueAttr) 791 return emitError(loc) 792 << "expected arrays within 'passthrough' to contain two strings"; 793 794 if (failed(checkedAddLLVMFnAttribute(loc, llvmFunc, keyAttr.getValue(), 795 valueAttr.getValue()))) 796 return failure(); 797 } 798 return success(); 799 } 800 801 LogicalResult ModuleTranslation::convertOneFunction(LLVMFuncOp func) { 802 // Clear the block, branch value mappings, they are only relevant within one 803 // function. 804 blockMapping.clear(); 805 valueMapping.clear(); 806 branchMapping.clear(); 807 llvm::Function *llvmFunc = lookupFunction(func.getName()); 808 809 // Translate the debug information for this function. 810 debugTranslation->translate(func, *llvmFunc); 811 812 // Add function arguments to the value remapping table. 813 // If there was noalias info then we decorate each argument accordingly. 814 unsigned int argIdx = 0; 815 for (auto kvp : llvm::zip(func.getArguments(), llvmFunc->args())) { 816 llvm::Argument &llvmArg = std::get<1>(kvp); 817 BlockArgument mlirArg = std::get<0>(kvp); 818 819 if (auto attr = func.getArgAttrOfType<UnitAttr>( 820 argIdx, LLVMDialect::getNoAliasAttrName())) { 821 // NB: Attribute already verified to be boolean, so check if we can indeed 822 // attach the attribute to this argument, based on its type. 823 auto argTy = mlirArg.getType(); 824 if (!argTy.isa<LLVM::LLVMPointerType>()) 825 return func.emitError( 826 "llvm.noalias attribute attached to LLVM non-pointer argument"); 827 llvmArg.addAttr(llvm::Attribute::AttrKind::NoAlias); 828 } 829 830 if (auto attr = func.getArgAttrOfType<IntegerAttr>( 831 argIdx, LLVMDialect::getAlignAttrName())) { 832 // NB: Attribute already verified to be int, so check if we can indeed 833 // attach the attribute to this argument, based on its type. 834 auto argTy = mlirArg.getType(); 835 if (!argTy.isa<LLVM::LLVMPointerType>()) 836 return func.emitError( 837 "llvm.align attribute attached to LLVM non-pointer argument"); 838 llvmArg.addAttrs(llvm::AttrBuilder(llvmArg.getContext()) 839 .addAlignmentAttr(llvm::Align(attr.getInt()))); 840 } 841 842 if (auto attr = func.getArgAttrOfType<UnitAttr>(argIdx, "llvm.sret")) { 843 auto argTy = mlirArg.getType().dyn_cast<LLVM::LLVMPointerType>(); 844 if (!argTy) 845 return func.emitError( 846 "llvm.sret attribute attached to LLVM non-pointer argument"); 847 llvmArg.addAttrs( 848 llvm::AttrBuilder(llvmArg.getContext()) 849 .addStructRetAttr(convertType(argTy.getElementType()))); 850 } 851 852 if (auto attr = func.getArgAttrOfType<UnitAttr>(argIdx, "llvm.byval")) { 853 auto argTy = mlirArg.getType().dyn_cast<LLVM::LLVMPointerType>(); 854 if (!argTy) 855 return func.emitError( 856 "llvm.byval attribute attached to LLVM non-pointer argument"); 857 llvmArg.addAttrs(llvm::AttrBuilder(llvmArg.getContext()) 858 .addByValAttr(convertType(argTy.getElementType()))); 859 } 860 861 if (auto attr = func.getArgAttrOfType<UnitAttr>(argIdx, "llvm.nest")) { 862 auto argTy = mlirArg.getType(); 863 if (!argTy.isa<LLVM::LLVMPointerType>()) 864 return func.emitError( 865 "llvm.nest attribute attached to LLVM non-pointer argument"); 866 llvmArg.addAttrs(llvm::AttrBuilder(llvmArg.getContext()) 867 .addAttribute(llvm::Attribute::Nest)); 868 } 869 870 mapValue(mlirArg, &llvmArg); 871 argIdx++; 872 } 873 874 // Check the personality and set it. 875 if (func.getPersonality().hasValue()) { 876 llvm::Type *ty = llvm::Type::getInt8PtrTy(llvmFunc->getContext()); 877 if (llvm::Constant *pfunc = getLLVMConstant(ty, func.getPersonalityAttr(), 878 func.getLoc(), *this)) 879 llvmFunc->setPersonalityFn(pfunc); 880 } 881 882 if (auto gc = func.getGarbageCollector()) 883 llvmFunc->setGC(gc->str()); 884 885 // First, create all blocks so we can jump to them. 886 llvm::LLVMContext &llvmContext = llvmFunc->getContext(); 887 for (auto &bb : func) { 888 auto *llvmBB = llvm::BasicBlock::Create(llvmContext); 889 llvmBB->insertInto(llvmFunc); 890 mapBlock(&bb, llvmBB); 891 } 892 893 // Then, convert blocks one by one in topological order to ensure defs are 894 // converted before uses. 895 auto blocks = detail::getTopologicallySortedBlocks(func.getBody()); 896 for (Block *bb : blocks) { 897 llvm::IRBuilder<> builder(llvmContext); 898 if (failed(convertBlock(*bb, bb->isEntryBlock(), builder))) 899 return failure(); 900 } 901 902 // After all blocks have been traversed and values mapped, connect the PHI 903 // nodes to the results of preceding blocks. 904 detail::connectPHINodes(func.getBody(), *this); 905 906 // Finally, convert dialect attributes attached to the function. 907 return convertDialectAttributes(func); 908 } 909 910 LogicalResult ModuleTranslation::convertDialectAttributes(Operation *op) { 911 for (NamedAttribute attribute : op->getDialectAttrs()) 912 if (failed(iface.amendOperation(op, attribute, *this))) 913 return failure(); 914 return success(); 915 } 916 917 LogicalResult ModuleTranslation::convertFunctionSignatures() { 918 // Declare all functions first because there may be function calls that form a 919 // call graph with cycles, or global initializers that reference functions. 920 for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) { 921 llvm::FunctionCallee llvmFuncCst = llvmModule->getOrInsertFunction( 922 function.getName(), 923 cast<llvm::FunctionType>(convertType(function.getFunctionType()))); 924 llvm::Function *llvmFunc = cast<llvm::Function>(llvmFuncCst.getCallee()); 925 llvmFunc->setLinkage(convertLinkageToLLVM(function.getLinkage())); 926 mapFunction(function.getName(), llvmFunc); 927 addRuntimePreemptionSpecifier(function.getDsoLocal(), llvmFunc); 928 929 // Forward the pass-through attributes to LLVM. 930 if (failed(forwardPassthroughAttributes( 931 function.getLoc(), function.getPassthrough(), llvmFunc))) 932 return failure(); 933 } 934 935 return success(); 936 } 937 938 LogicalResult ModuleTranslation::convertFunctions() { 939 // Convert functions. 940 for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) { 941 // Ignore external functions. 942 if (function.isExternal()) 943 continue; 944 945 if (failed(convertOneFunction(function))) 946 return failure(); 947 } 948 949 return success(); 950 } 951 952 llvm::MDNode * 953 ModuleTranslation::getAccessGroup(Operation &opInst, 954 SymbolRefAttr accessGroupRef) const { 955 auto metadataName = accessGroupRef.getRootReference(); 956 auto accessGroupName = accessGroupRef.getLeafReference(); 957 auto metadataOp = SymbolTable::lookupNearestSymbolFrom<LLVM::MetadataOp>( 958 opInst.getParentOp(), metadataName); 959 auto *accessGroupOp = 960 SymbolTable::lookupNearestSymbolFrom(metadataOp, accessGroupName); 961 return accessGroupMetadataMapping.lookup(accessGroupOp); 962 } 963 964 LogicalResult ModuleTranslation::createAccessGroupMetadata() { 965 mlirModule->walk([&](LLVM::MetadataOp metadatas) { 966 metadatas.walk([&](LLVM::AccessGroupMetadataOp op) { 967 llvm::LLVMContext &ctx = llvmModule->getContext(); 968 llvm::MDNode *accessGroup = llvm::MDNode::getDistinct(ctx, {}); 969 accessGroupMetadataMapping.insert({op, accessGroup}); 970 }); 971 }); 972 return success(); 973 } 974 975 void ModuleTranslation::setAccessGroupsMetadata(Operation *op, 976 llvm::Instruction *inst) { 977 auto accessGroups = 978 op->getAttrOfType<ArrayAttr>(LLVMDialect::getAccessGroupsAttrName()); 979 if (accessGroups && !accessGroups.empty()) { 980 llvm::Module *module = inst->getModule(); 981 SmallVector<llvm::Metadata *> metadatas; 982 for (SymbolRefAttr accessGroupRef : 983 accessGroups.getAsRange<SymbolRefAttr>()) 984 metadatas.push_back(getAccessGroup(*op, accessGroupRef)); 985 986 llvm::MDNode *unionMD = nullptr; 987 if (metadatas.size() == 1) 988 unionMD = llvm::cast<llvm::MDNode>(metadatas.front()); 989 else if (metadatas.size() >= 2) 990 unionMD = llvm::MDNode::get(module->getContext(), metadatas); 991 992 inst->setMetadata(module->getMDKindID("llvm.access.group"), unionMD); 993 } 994 } 995 996 LogicalResult ModuleTranslation::createAliasScopeMetadata() { 997 mlirModule->walk([&](LLVM::MetadataOp metadatas) { 998 // Create the domains first, so they can be reference below in the scopes. 999 DenseMap<Operation *, llvm::MDNode *> aliasScopeDomainMetadataMapping; 1000 metadatas.walk([&](LLVM::AliasScopeDomainMetadataOp op) { 1001 llvm::LLVMContext &ctx = llvmModule->getContext(); 1002 llvm::SmallVector<llvm::Metadata *, 2> operands; 1003 operands.push_back({}); // Placeholder for self-reference 1004 if (Optional<StringRef> description = op.getDescription()) 1005 operands.push_back(llvm::MDString::get(ctx, description.getValue())); 1006 llvm::MDNode *domain = llvm::MDNode::get(ctx, operands); 1007 domain->replaceOperandWith(0, domain); // Self-reference for uniqueness 1008 aliasScopeDomainMetadataMapping.insert({op, domain}); 1009 }); 1010 1011 // Now create the scopes, referencing the domains created above. 1012 metadatas.walk([&](LLVM::AliasScopeMetadataOp op) { 1013 llvm::LLVMContext &ctx = llvmModule->getContext(); 1014 assert(isa<LLVM::MetadataOp>(op->getParentOp())); 1015 auto metadataOp = dyn_cast<LLVM::MetadataOp>(op->getParentOp()); 1016 Operation *domainOp = 1017 SymbolTable::lookupNearestSymbolFrom(metadataOp, op.getDomainAttr()); 1018 llvm::MDNode *domain = aliasScopeDomainMetadataMapping.lookup(domainOp); 1019 assert(domain && "Scope's domain should already be valid"); 1020 llvm::SmallVector<llvm::Metadata *, 3> operands; 1021 operands.push_back({}); // Placeholder for self-reference 1022 operands.push_back(domain); 1023 if (Optional<StringRef> description = op.getDescription()) 1024 operands.push_back(llvm::MDString::get(ctx, description.getValue())); 1025 llvm::MDNode *scope = llvm::MDNode::get(ctx, operands); 1026 scope->replaceOperandWith(0, scope); // Self-reference for uniqueness 1027 aliasScopeMetadataMapping.insert({op, scope}); 1028 }); 1029 }); 1030 return success(); 1031 } 1032 1033 llvm::MDNode * 1034 ModuleTranslation::getAliasScope(Operation &opInst, 1035 SymbolRefAttr aliasScopeRef) const { 1036 StringAttr metadataName = aliasScopeRef.getRootReference(); 1037 StringAttr scopeName = aliasScopeRef.getLeafReference(); 1038 auto metadataOp = SymbolTable::lookupNearestSymbolFrom<LLVM::MetadataOp>( 1039 opInst.getParentOp(), metadataName); 1040 Operation *aliasScopeOp = 1041 SymbolTable::lookupNearestSymbolFrom(metadataOp, scopeName); 1042 return aliasScopeMetadataMapping.lookup(aliasScopeOp); 1043 } 1044 1045 void ModuleTranslation::setAliasScopeMetadata(Operation *op, 1046 llvm::Instruction *inst) { 1047 auto populateScopeMetadata = [this, op, inst](StringRef attrName, 1048 StringRef llvmMetadataName) { 1049 auto scopes = op->getAttrOfType<ArrayAttr>(attrName); 1050 if (!scopes || scopes.empty()) 1051 return; 1052 llvm::Module *module = inst->getModule(); 1053 SmallVector<llvm::Metadata *> scopeMDs; 1054 for (SymbolRefAttr scopeRef : scopes.getAsRange<SymbolRefAttr>()) 1055 scopeMDs.push_back(getAliasScope(*op, scopeRef)); 1056 llvm::MDNode *unionMD = llvm::MDNode::get(module->getContext(), scopeMDs); 1057 inst->setMetadata(module->getMDKindID(llvmMetadataName), unionMD); 1058 }; 1059 1060 populateScopeMetadata(LLVMDialect::getAliasScopesAttrName(), "alias.scope"); 1061 populateScopeMetadata(LLVMDialect::getNoAliasScopesAttrName(), "noalias"); 1062 } 1063 1064 llvm::Type *ModuleTranslation::convertType(Type type) { 1065 return typeTranslator.translateType(type); 1066 } 1067 1068 /// A helper to look up remapped operands in the value remapping table. 1069 SmallVector<llvm::Value *> ModuleTranslation::lookupValues(ValueRange values) { 1070 SmallVector<llvm::Value *> remapped; 1071 remapped.reserve(values.size()); 1072 for (Value v : values) 1073 remapped.push_back(lookupValue(v)); 1074 return remapped; 1075 } 1076 1077 const llvm::DILocation * 1078 ModuleTranslation::translateLoc(Location loc, llvm::DILocalScope *scope) { 1079 return debugTranslation->translateLoc(loc, scope); 1080 } 1081 1082 llvm::NamedMDNode * 1083 ModuleTranslation::getOrInsertNamedModuleMetadata(StringRef name) { 1084 return llvmModule->getOrInsertNamedMetadata(name); 1085 } 1086 1087 void ModuleTranslation::StackFrame::anchor() {} 1088 1089 static std::unique_ptr<llvm::Module> 1090 prepareLLVMModule(Operation *m, llvm::LLVMContext &llvmContext, 1091 StringRef name) { 1092 m->getContext()->getOrLoadDialect<LLVM::LLVMDialect>(); 1093 auto llvmModule = std::make_unique<llvm::Module>(name, llvmContext); 1094 if (auto dataLayoutAttr = 1095 m->getAttr(LLVM::LLVMDialect::getDataLayoutAttrName())) { 1096 llvmModule->setDataLayout(dataLayoutAttr.cast<StringAttr>().getValue()); 1097 } else { 1098 FailureOr<llvm::DataLayout> llvmDataLayout(llvm::DataLayout("")); 1099 if (auto iface = dyn_cast<DataLayoutOpInterface>(m)) { 1100 if (DataLayoutSpecInterface spec = iface.getDataLayoutSpec()) { 1101 llvmDataLayout = 1102 translateDataLayout(spec, DataLayout(iface), m->getLoc()); 1103 } 1104 } else if (auto mod = dyn_cast<ModuleOp>(m)) { 1105 if (DataLayoutSpecInterface spec = mod.getDataLayoutSpec()) { 1106 llvmDataLayout = 1107 translateDataLayout(spec, DataLayout(mod), m->getLoc()); 1108 } 1109 } 1110 if (failed(llvmDataLayout)) 1111 return nullptr; 1112 llvmModule->setDataLayout(*llvmDataLayout); 1113 } 1114 if (auto targetTripleAttr = 1115 m->getAttr(LLVM::LLVMDialect::getTargetTripleAttrName())) 1116 llvmModule->setTargetTriple(targetTripleAttr.cast<StringAttr>().getValue()); 1117 1118 // Inject declarations for `malloc` and `free` functions that can be used in 1119 // memref allocation/deallocation coming from standard ops lowering. 1120 llvm::IRBuilder<> builder(llvmContext); 1121 llvmModule->getOrInsertFunction("malloc", builder.getInt8PtrTy(), 1122 builder.getInt64Ty()); 1123 llvmModule->getOrInsertFunction("free", builder.getVoidTy(), 1124 builder.getInt8PtrTy()); 1125 1126 return llvmModule; 1127 } 1128 1129 std::unique_ptr<llvm::Module> 1130 mlir::translateModuleToLLVMIR(Operation *module, llvm::LLVMContext &llvmContext, 1131 StringRef name) { 1132 if (!satisfiesLLVMModule(module)) 1133 return nullptr; 1134 1135 std::unique_ptr<llvm::Module> llvmModule = 1136 prepareLLVMModule(module, llvmContext, name); 1137 if (!llvmModule) 1138 return nullptr; 1139 1140 LLVM::ensureDistinctSuccessors(module); 1141 1142 ModuleTranslation translator(module, std::move(llvmModule)); 1143 if (failed(translator.convertFunctionSignatures())) 1144 return nullptr; 1145 if (failed(translator.convertGlobals())) 1146 return nullptr; 1147 if (failed(translator.createAccessGroupMetadata())) 1148 return nullptr; 1149 if (failed(translator.createAliasScopeMetadata())) 1150 return nullptr; 1151 if (failed(translator.convertFunctions())) 1152 return nullptr; 1153 1154 // Convert other top-level operations if possible. 1155 llvm::IRBuilder<> llvmBuilder(llvmContext); 1156 for (Operation &o : getModuleBody(module).getOperations()) { 1157 if (!isa<LLVM::LLVMFuncOp, LLVM::GlobalOp, LLVM::GlobalCtorsOp, 1158 LLVM::GlobalDtorsOp, LLVM::MetadataOp>(&o) && 1159 !o.hasTrait<OpTrait::IsTerminator>() && 1160 failed(translator.convertOperation(o, llvmBuilder))) { 1161 return nullptr; 1162 } 1163 } 1164 1165 if (llvm::verifyModule(*translator.llvmModule, &llvm::errs())) 1166 return nullptr; 1167 1168 return std::move(translator.llvmModule); 1169 } 1170