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 Optional<OperandRange> successorOperands = branch.getSuccessorOperands(i); 445 assert( 446 (!seenSuccessors.contains(successor) || 447 (successorOperands && successorOperands->empty())) && 448 "successors with arguments in LLVM branches must be different blocks"); 449 seenSuccessors.insert(successor); 450 } 451 #endif 452 453 // For instructions that branch based on a condition value, we need to take 454 // the operands for the branch that was taken. 455 if (auto condBranchOp = dyn_cast<LLVM::CondBrOp>(terminator)) { 456 // For conditional branches, we take the operands from either the "true" or 457 // the "false" branch. 458 return condBranchOp.getSuccessor(0) == current 459 ? condBranchOp.getTrueDestOperands()[index] 460 : condBranchOp.getFalseDestOperands()[index]; 461 } 462 463 if (auto switchOp = dyn_cast<LLVM::SwitchOp>(terminator)) { 464 // For switches, we take the operands from either the default case, or from 465 // the case branch that was taken. 466 if (switchOp.getDefaultDestination() == current) 467 return switchOp.getDefaultOperands()[index]; 468 for (const auto &i : llvm::enumerate(switchOp.getCaseDestinations())) 469 if (i.value() == current) 470 return switchOp.getCaseOperands(i.index())[index]; 471 } 472 473 if (auto invokeOp = dyn_cast<LLVM::InvokeOp>(terminator)) { 474 return invokeOp.getNormalDest() == current 475 ? invokeOp.getNormalDestOperands()[index] 476 : invokeOp.getUnwindDestOperands()[index]; 477 } 478 479 llvm_unreachable( 480 "only branch, switch or invoke operations can be terminators " 481 "of a block that has successors"); 482 } 483 484 /// Connect the PHI nodes to the results of preceding blocks. 485 void mlir::LLVM::detail::connectPHINodes(Region ®ion, 486 const ModuleTranslation &state) { 487 // Skip the first block, it cannot be branched to and its arguments correspond 488 // to the arguments of the LLVM function. 489 for (auto it = std::next(region.begin()), eit = region.end(); it != eit; 490 ++it) { 491 Block *bb = &*it; 492 llvm::BasicBlock *llvmBB = state.lookupBlock(bb); 493 auto phis = llvmBB->phis(); 494 auto numArguments = bb->getNumArguments(); 495 assert(numArguments == std::distance(phis.begin(), phis.end())); 496 for (auto &numberedPhiNode : llvm::enumerate(phis)) { 497 auto &phiNode = numberedPhiNode.value(); 498 unsigned index = numberedPhiNode.index(); 499 for (auto *pred : bb->getPredecessors()) { 500 // Find the LLVM IR block that contains the converted terminator 501 // instruction and use it in the PHI node. Note that this block is not 502 // necessarily the same as state.lookupBlock(pred), some operations 503 // (in particular, OpenMP operations using OpenMPIRBuilder) may have 504 // split the blocks. 505 llvm::Instruction *terminator = 506 state.lookupBranch(pred->getTerminator()); 507 assert(terminator && "missing the mapping for a terminator"); 508 phiNode.addIncoming( 509 state.lookupValue(getPHISourceValue(bb, pred, numArguments, index)), 510 terminator->getParent()); 511 } 512 } 513 } 514 } 515 516 /// Sort function blocks topologically. 517 SetVector<Block *> 518 mlir::LLVM::detail::getTopologicallySortedBlocks(Region ®ion) { 519 // For each block that has not been visited yet (i.e. that has no 520 // predecessors), add it to the list as well as its successors. 521 SetVector<Block *> blocks; 522 for (Block &b : region) { 523 if (blocks.count(&b) == 0) { 524 llvm::ReversePostOrderTraversal<Block *> traversal(&b); 525 blocks.insert(traversal.begin(), traversal.end()); 526 } 527 } 528 assert(blocks.size() == region.getBlocks().size() && 529 "some blocks are not sorted"); 530 531 return blocks; 532 } 533 534 llvm::Value *mlir::LLVM::detail::createIntrinsicCall( 535 llvm::IRBuilderBase &builder, llvm::Intrinsic::ID intrinsic, 536 ArrayRef<llvm::Value *> args, ArrayRef<llvm::Type *> tys) { 537 llvm::Module *module = builder.GetInsertBlock()->getModule(); 538 llvm::Function *fn = llvm::Intrinsic::getDeclaration(module, intrinsic, tys); 539 return builder.CreateCall(fn, args); 540 } 541 542 /// Given a single MLIR operation, create the corresponding LLVM IR operation 543 /// using the `builder`. 544 LogicalResult 545 ModuleTranslation::convertOperation(Operation &op, 546 llvm::IRBuilderBase &builder) { 547 const LLVMTranslationDialectInterface *opIface = iface.getInterfaceFor(&op); 548 if (!opIface) 549 return op.emitError("cannot be converted to LLVM IR: missing " 550 "`LLVMTranslationDialectInterface` registration for " 551 "dialect for op: ") 552 << op.getName(); 553 554 if (failed(opIface->convertOperation(&op, builder, *this))) 555 return op.emitError("LLVM Translation failed for operation: ") 556 << op.getName(); 557 558 return convertDialectAttributes(&op); 559 } 560 561 /// Convert block to LLVM IR. Unless `ignoreArguments` is set, emit PHI nodes 562 /// to define values corresponding to the MLIR block arguments. These nodes 563 /// are not connected to the source basic blocks, which may not exist yet. Uses 564 /// `builder` to construct the LLVM IR. Expects the LLVM IR basic block to have 565 /// been created for `bb` and included in the block mapping. Inserts new 566 /// instructions at the end of the block and leaves `builder` in a state 567 /// suitable for further insertion into the end of the block. 568 LogicalResult ModuleTranslation::convertBlock(Block &bb, bool ignoreArguments, 569 llvm::IRBuilderBase &builder) { 570 builder.SetInsertPoint(lookupBlock(&bb)); 571 auto *subprogram = builder.GetInsertBlock()->getParent()->getSubprogram(); 572 573 // Before traversing operations, make block arguments available through 574 // value remapping and PHI nodes, but do not add incoming edges for the PHI 575 // nodes just yet: those values may be defined by this or following blocks. 576 // This step is omitted if "ignoreArguments" is set. The arguments of the 577 // first block have been already made available through the remapping of 578 // LLVM function arguments. 579 if (!ignoreArguments) { 580 auto predecessors = bb.getPredecessors(); 581 unsigned numPredecessors = 582 std::distance(predecessors.begin(), predecessors.end()); 583 for (auto arg : bb.getArguments()) { 584 auto wrappedType = arg.getType(); 585 if (!isCompatibleType(wrappedType)) 586 return emitError(bb.front().getLoc(), 587 "block argument does not have an LLVM type"); 588 llvm::Type *type = convertType(wrappedType); 589 llvm::PHINode *phi = builder.CreatePHI(type, numPredecessors); 590 mapValue(arg, phi); 591 } 592 } 593 594 // Traverse operations. 595 for (auto &op : bb) { 596 // Set the current debug location within the builder. 597 builder.SetCurrentDebugLocation( 598 debugTranslation->translateLoc(op.getLoc(), subprogram)); 599 600 if (failed(convertOperation(op, builder))) 601 return failure(); 602 } 603 604 return success(); 605 } 606 607 /// A helper method to get the single Block in an operation honoring LLVM's 608 /// module requirements. 609 static Block &getModuleBody(Operation *module) { 610 return module->getRegion(0).front(); 611 } 612 613 /// A helper method to decide if a constant must not be set as a global variable 614 /// initializer. For an external linkage variable, the variable with an 615 /// initializer is considered externally visible and defined in this module, the 616 /// variable without an initializer is externally available and is defined 617 /// elsewhere. 618 static bool shouldDropGlobalInitializer(llvm::GlobalValue::LinkageTypes linkage, 619 llvm::Constant *cst) { 620 return (linkage == llvm::GlobalVariable::ExternalLinkage && !cst) || 621 linkage == llvm::GlobalVariable::ExternalWeakLinkage; 622 } 623 624 /// Sets the runtime preemption specifier of `gv` to dso_local if 625 /// `dsoLocalRequested` is true, otherwise it is left unchanged. 626 static void addRuntimePreemptionSpecifier(bool dsoLocalRequested, 627 llvm::GlobalValue *gv) { 628 if (dsoLocalRequested) 629 gv->setDSOLocal(true); 630 } 631 632 /// Create named global variables that correspond to llvm.mlir.global 633 /// definitions. Convert llvm.global_ctors and global_dtors ops. 634 LogicalResult ModuleTranslation::convertGlobals() { 635 for (auto op : getModuleBody(mlirModule).getOps<LLVM::GlobalOp>()) { 636 llvm::Type *type = convertType(op.getType()); 637 llvm::Constant *cst = nullptr; 638 if (op.getValueOrNull()) { 639 // String attributes are treated separately because they cannot appear as 640 // in-function constants and are thus not supported by getLLVMConstant. 641 if (auto strAttr = op.getValueOrNull().dyn_cast_or_null<StringAttr>()) { 642 cst = llvm::ConstantDataArray::getString( 643 llvmModule->getContext(), strAttr.getValue(), /*AddNull=*/false); 644 type = cst->getType(); 645 } else if (!(cst = getLLVMConstant(type, op.getValueOrNull(), op.getLoc(), 646 *this))) { 647 return failure(); 648 } 649 } 650 651 auto linkage = convertLinkageToLLVM(op.getLinkage()); 652 auto addrSpace = op.getAddrSpace(); 653 654 // LLVM IR requires constant with linkage other than external or weak 655 // external to have initializers. If MLIR does not provide an initializer, 656 // default to undef. 657 bool dropInitializer = shouldDropGlobalInitializer(linkage, cst); 658 if (!dropInitializer && !cst) 659 cst = llvm::UndefValue::get(type); 660 else if (dropInitializer && cst) 661 cst = nullptr; 662 663 auto *var = new llvm::GlobalVariable( 664 *llvmModule, type, op.getConstant(), linkage, cst, op.getSymName(), 665 /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal, addrSpace); 666 667 if (op.getUnnamedAddr().hasValue()) 668 var->setUnnamedAddr(convertUnnamedAddrToLLVM(*op.getUnnamedAddr())); 669 670 if (op.getSection().hasValue()) 671 var->setSection(*op.getSection()); 672 673 addRuntimePreemptionSpecifier(op.getDsoLocal(), var); 674 675 Optional<uint64_t> alignment = op.getAlignment(); 676 if (alignment.hasValue()) 677 var->setAlignment(llvm::MaybeAlign(alignment.getValue())); 678 679 globalsMapping.try_emplace(op, var); 680 } 681 682 // Convert global variable bodies. This is done after all global variables 683 // have been created in LLVM IR because a global body may refer to another 684 // global or itself. So all global variables need to be mapped first. 685 for (auto op : getModuleBody(mlirModule).getOps<LLVM::GlobalOp>()) { 686 if (Block *initializer = op.getInitializerBlock()) { 687 llvm::IRBuilder<> builder(llvmModule->getContext()); 688 for (auto &op : initializer->without_terminator()) { 689 if (failed(convertOperation(op, builder)) || 690 !isa<llvm::Constant>(lookupValue(op.getResult(0)))) 691 return emitError(op.getLoc(), "unemittable constant value"); 692 } 693 ReturnOp ret = cast<ReturnOp>(initializer->getTerminator()); 694 llvm::Constant *cst = 695 cast<llvm::Constant>(lookupValue(ret.getOperand(0))); 696 auto *global = cast<llvm::GlobalVariable>(lookupGlobal(op)); 697 if (!shouldDropGlobalInitializer(global->getLinkage(), cst)) 698 global->setInitializer(cst); 699 } 700 } 701 702 // Convert llvm.mlir.global_ctors and dtors. 703 for (Operation &op : getModuleBody(mlirModule)) { 704 auto ctorOp = dyn_cast<GlobalCtorsOp>(op); 705 auto dtorOp = dyn_cast<GlobalDtorsOp>(op); 706 if (!ctorOp && !dtorOp) 707 continue; 708 auto range = ctorOp ? llvm::zip(ctorOp.getCtors(), ctorOp.getPriorities()) 709 : llvm::zip(dtorOp.getDtors(), dtorOp.getPriorities()); 710 auto appendGlobalFn = 711 ctorOp ? llvm::appendToGlobalCtors : llvm::appendToGlobalDtors; 712 for (auto symbolAndPriority : range) { 713 llvm::Function *f = lookupFunction( 714 std::get<0>(symbolAndPriority).cast<FlatSymbolRefAttr>().getValue()); 715 appendGlobalFn( 716 *llvmModule, f, 717 std::get<1>(symbolAndPriority).cast<IntegerAttr>().getInt(), 718 /*Data=*/nullptr); 719 } 720 } 721 722 return success(); 723 } 724 725 /// Attempts to add an attribute identified by `key`, optionally with the given 726 /// `value` to LLVM function `llvmFunc`. Reports errors at `loc` if any. If the 727 /// attribute has a kind known to LLVM IR, create the attribute of this kind, 728 /// otherwise keep it as a string attribute. Performs additional checks for 729 /// attributes known to have or not have a value in order to avoid assertions 730 /// inside LLVM upon construction. 731 static LogicalResult checkedAddLLVMFnAttribute(Location loc, 732 llvm::Function *llvmFunc, 733 StringRef key, 734 StringRef value = StringRef()) { 735 auto kind = llvm::Attribute::getAttrKindFromName(key); 736 if (kind == llvm::Attribute::None) { 737 llvmFunc->addFnAttr(key, value); 738 return success(); 739 } 740 741 if (llvm::Attribute::isIntAttrKind(kind)) { 742 if (value.empty()) 743 return emitError(loc) << "LLVM attribute '" << key << "' expects a value"; 744 745 int result; 746 if (!value.getAsInteger(/*Radix=*/0, result)) 747 llvmFunc->addFnAttr( 748 llvm::Attribute::get(llvmFunc->getContext(), kind, result)); 749 else 750 llvmFunc->addFnAttr(key, value); 751 return success(); 752 } 753 754 if (!value.empty()) 755 return emitError(loc) << "LLVM attribute '" << key 756 << "' does not expect a value, found '" << value 757 << "'"; 758 759 llvmFunc->addFnAttr(kind); 760 return success(); 761 } 762 763 /// Attaches the attributes listed in the given array attribute to `llvmFunc`. 764 /// Reports error to `loc` if any and returns immediately. Expects `attributes` 765 /// to be an array attribute containing either string attributes, treated as 766 /// value-less LLVM attributes, or array attributes containing two string 767 /// attributes, with the first string being the name of the corresponding LLVM 768 /// attribute and the second string beings its value. Note that even integer 769 /// attributes are expected to have their values expressed as strings. 770 static LogicalResult 771 forwardPassthroughAttributes(Location loc, Optional<ArrayAttr> attributes, 772 llvm::Function *llvmFunc) { 773 if (!attributes) 774 return success(); 775 776 for (Attribute attr : *attributes) { 777 if (auto stringAttr = attr.dyn_cast<StringAttr>()) { 778 if (failed( 779 checkedAddLLVMFnAttribute(loc, llvmFunc, stringAttr.getValue()))) 780 return failure(); 781 continue; 782 } 783 784 auto arrayAttr = attr.dyn_cast<ArrayAttr>(); 785 if (!arrayAttr || arrayAttr.size() != 2) 786 return emitError(loc) 787 << "expected 'passthrough' to contain string or array attributes"; 788 789 auto keyAttr = arrayAttr[0].dyn_cast<StringAttr>(); 790 auto valueAttr = arrayAttr[1].dyn_cast<StringAttr>(); 791 if (!keyAttr || !valueAttr) 792 return emitError(loc) 793 << "expected arrays within 'passthrough' to contain two strings"; 794 795 if (failed(checkedAddLLVMFnAttribute(loc, llvmFunc, keyAttr.getValue(), 796 valueAttr.getValue()))) 797 return failure(); 798 } 799 return success(); 800 } 801 802 LogicalResult ModuleTranslation::convertOneFunction(LLVMFuncOp func) { 803 // Clear the block, branch value mappings, they are only relevant within one 804 // function. 805 blockMapping.clear(); 806 valueMapping.clear(); 807 branchMapping.clear(); 808 llvm::Function *llvmFunc = lookupFunction(func.getName()); 809 810 // Translate the debug information for this function. 811 debugTranslation->translate(func, *llvmFunc); 812 813 // Add function arguments to the value remapping table. 814 // If there was noalias info then we decorate each argument accordingly. 815 unsigned int argIdx = 0; 816 for (auto kvp : llvm::zip(func.getArguments(), llvmFunc->args())) { 817 llvm::Argument &llvmArg = std::get<1>(kvp); 818 BlockArgument mlirArg = std::get<0>(kvp); 819 820 if (auto attr = func.getArgAttrOfType<UnitAttr>( 821 argIdx, LLVMDialect::getNoAliasAttrName())) { 822 // NB: Attribute already verified to be boolean, so check if we can indeed 823 // attach the attribute to this argument, based on its type. 824 auto argTy = mlirArg.getType(); 825 if (!argTy.isa<LLVM::LLVMPointerType>()) 826 return func.emitError( 827 "llvm.noalias attribute attached to LLVM non-pointer argument"); 828 llvmArg.addAttr(llvm::Attribute::AttrKind::NoAlias); 829 } 830 831 if (auto attr = func.getArgAttrOfType<IntegerAttr>( 832 argIdx, LLVMDialect::getAlignAttrName())) { 833 // NB: Attribute already verified to be int, so check if we can indeed 834 // attach the attribute to this argument, based on its type. 835 auto argTy = mlirArg.getType(); 836 if (!argTy.isa<LLVM::LLVMPointerType>()) 837 return func.emitError( 838 "llvm.align attribute attached to LLVM non-pointer argument"); 839 llvmArg.addAttrs( 840 llvm::AttrBuilder(llvmArg.getContext()).addAlignmentAttr(llvm::Align(attr.getInt()))); 841 } 842 843 if (auto attr = func.getArgAttrOfType<UnitAttr>(argIdx, "llvm.sret")) { 844 auto argTy = mlirArg.getType().dyn_cast<LLVM::LLVMPointerType>(); 845 if (!argTy) 846 return func.emitError( 847 "llvm.sret attribute attached to LLVM non-pointer argument"); 848 llvmArg.addAttrs( 849 llvm::AttrBuilder(llvmArg.getContext()) 850 .addStructRetAttr(convertType(argTy.getElementType()))); 851 } 852 853 if (auto attr = func.getArgAttrOfType<UnitAttr>(argIdx, "llvm.byval")) { 854 auto argTy = mlirArg.getType().dyn_cast<LLVM::LLVMPointerType>(); 855 if (!argTy) 856 return func.emitError( 857 "llvm.byval attribute attached to LLVM non-pointer argument"); 858 llvmArg.addAttrs(llvm::AttrBuilder(llvmArg.getContext()) 859 .addByValAttr(convertType(argTy.getElementType()))); 860 } 861 862 mapValue(mlirArg, &llvmArg); 863 argIdx++; 864 } 865 866 // Check the personality and set it. 867 if (func.getPersonality().hasValue()) { 868 llvm::Type *ty = llvm::Type::getInt8PtrTy(llvmFunc->getContext()); 869 if (llvm::Constant *pfunc = getLLVMConstant(ty, func.getPersonalityAttr(), 870 func.getLoc(), *this)) 871 llvmFunc->setPersonalityFn(pfunc); 872 } 873 874 if (auto gc = func.getGarbageCollector()) 875 llvmFunc->setGC(gc->str()); 876 877 // First, create all blocks so we can jump to them. 878 llvm::LLVMContext &llvmContext = llvmFunc->getContext(); 879 for (auto &bb : func) { 880 auto *llvmBB = llvm::BasicBlock::Create(llvmContext); 881 llvmBB->insertInto(llvmFunc); 882 mapBlock(&bb, llvmBB); 883 } 884 885 // Then, convert blocks one by one in topological order to ensure defs are 886 // converted before uses. 887 auto blocks = detail::getTopologicallySortedBlocks(func.getBody()); 888 for (Block *bb : blocks) { 889 llvm::IRBuilder<> builder(llvmContext); 890 if (failed(convertBlock(*bb, bb->isEntryBlock(), builder))) 891 return failure(); 892 } 893 894 // After all blocks have been traversed and values mapped, connect the PHI 895 // nodes to the results of preceding blocks. 896 detail::connectPHINodes(func.getBody(), *this); 897 898 // Finally, convert dialect attributes attached to the function. 899 return convertDialectAttributes(func); 900 } 901 902 LogicalResult ModuleTranslation::convertDialectAttributes(Operation *op) { 903 for (NamedAttribute attribute : op->getDialectAttrs()) 904 if (failed(iface.amendOperation(op, attribute, *this))) 905 return failure(); 906 return success(); 907 } 908 909 LogicalResult ModuleTranslation::convertFunctionSignatures() { 910 // Declare all functions first because there may be function calls that form a 911 // call graph with cycles, or global initializers that reference functions. 912 for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) { 913 llvm::FunctionCallee llvmFuncCst = llvmModule->getOrInsertFunction( 914 function.getName(), 915 cast<llvm::FunctionType>(convertType(function.getType()))); 916 llvm::Function *llvmFunc = cast<llvm::Function>(llvmFuncCst.getCallee()); 917 llvmFunc->setLinkage(convertLinkageToLLVM(function.getLinkage())); 918 mapFunction(function.getName(), llvmFunc); 919 addRuntimePreemptionSpecifier(function.getDsoLocal(), llvmFunc); 920 921 // Forward the pass-through attributes to LLVM. 922 if (failed(forwardPassthroughAttributes( 923 function.getLoc(), function.getPassthrough(), llvmFunc))) 924 return failure(); 925 } 926 927 return success(); 928 } 929 930 LogicalResult ModuleTranslation::convertFunctions() { 931 // Convert functions. 932 for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) { 933 // Ignore external functions. 934 if (function.isExternal()) 935 continue; 936 937 if (failed(convertOneFunction(function))) 938 return failure(); 939 } 940 941 return success(); 942 } 943 944 llvm::MDNode * 945 ModuleTranslation::getAccessGroup(Operation &opInst, 946 SymbolRefAttr accessGroupRef) const { 947 auto metadataName = accessGroupRef.getRootReference(); 948 auto accessGroupName = accessGroupRef.getLeafReference(); 949 auto metadataOp = SymbolTable::lookupNearestSymbolFrom<LLVM::MetadataOp>( 950 opInst.getParentOp(), metadataName); 951 auto *accessGroupOp = 952 SymbolTable::lookupNearestSymbolFrom(metadataOp, accessGroupName); 953 return accessGroupMetadataMapping.lookup(accessGroupOp); 954 } 955 956 LogicalResult ModuleTranslation::createAccessGroupMetadata() { 957 mlirModule->walk([&](LLVM::MetadataOp metadatas) { 958 metadatas.walk([&](LLVM::AccessGroupMetadataOp op) { 959 llvm::LLVMContext &ctx = llvmModule->getContext(); 960 llvm::MDNode *accessGroup = llvm::MDNode::getDistinct(ctx, {}); 961 accessGroupMetadataMapping.insert({op, accessGroup}); 962 }); 963 }); 964 return success(); 965 } 966 967 void ModuleTranslation::setAccessGroupsMetadata(Operation *op, 968 llvm::Instruction *inst) { 969 auto accessGroups = 970 op->getAttrOfType<ArrayAttr>(LLVMDialect::getAccessGroupsAttrName()); 971 if (accessGroups && !accessGroups.empty()) { 972 llvm::Module *module = inst->getModule(); 973 SmallVector<llvm::Metadata *> metadatas; 974 for (SymbolRefAttr accessGroupRef : 975 accessGroups.getAsRange<SymbolRefAttr>()) 976 metadatas.push_back(getAccessGroup(*op, accessGroupRef)); 977 978 llvm::MDNode *unionMD = nullptr; 979 if (metadatas.size() == 1) 980 unionMD = llvm::cast<llvm::MDNode>(metadatas.front()); 981 else if (metadatas.size() >= 2) 982 unionMD = llvm::MDNode::get(module->getContext(), metadatas); 983 984 inst->setMetadata(module->getMDKindID("llvm.access.group"), unionMD); 985 } 986 } 987 988 LogicalResult ModuleTranslation::createAliasScopeMetadata() { 989 mlirModule->walk([&](LLVM::MetadataOp metadatas) { 990 // Create the domains first, so they can be reference below in the scopes. 991 DenseMap<Operation *, llvm::MDNode *> aliasScopeDomainMetadataMapping; 992 metadatas.walk([&](LLVM::AliasScopeDomainMetadataOp op) { 993 llvm::LLVMContext &ctx = llvmModule->getContext(); 994 llvm::SmallVector<llvm::Metadata *, 2> operands; 995 operands.push_back({}); // Placeholder for self-reference 996 if (Optional<StringRef> description = op.getDescription()) 997 operands.push_back(llvm::MDString::get(ctx, description.getValue())); 998 llvm::MDNode *domain = llvm::MDNode::get(ctx, operands); 999 domain->replaceOperandWith(0, domain); // Self-reference for uniqueness 1000 aliasScopeDomainMetadataMapping.insert({op, domain}); 1001 }); 1002 1003 // Now create the scopes, referencing the domains created above. 1004 metadatas.walk([&](LLVM::AliasScopeMetadataOp op) { 1005 llvm::LLVMContext &ctx = llvmModule->getContext(); 1006 assert(isa<LLVM::MetadataOp>(op->getParentOp())); 1007 auto metadataOp = dyn_cast<LLVM::MetadataOp>(op->getParentOp()); 1008 Operation *domainOp = 1009 SymbolTable::lookupNearestSymbolFrom(metadataOp, op.getDomainAttr()); 1010 llvm::MDNode *domain = aliasScopeDomainMetadataMapping.lookup(domainOp); 1011 assert(domain && "Scope's domain should already be valid"); 1012 llvm::SmallVector<llvm::Metadata *, 3> operands; 1013 operands.push_back({}); // Placeholder for self-reference 1014 operands.push_back(domain); 1015 if (Optional<StringRef> description = op.getDescription()) 1016 operands.push_back(llvm::MDString::get(ctx, description.getValue())); 1017 llvm::MDNode *scope = llvm::MDNode::get(ctx, operands); 1018 scope->replaceOperandWith(0, scope); // Self-reference for uniqueness 1019 aliasScopeMetadataMapping.insert({op, scope}); 1020 }); 1021 }); 1022 return success(); 1023 } 1024 1025 llvm::MDNode * 1026 ModuleTranslation::getAliasScope(Operation &opInst, 1027 SymbolRefAttr aliasScopeRef) const { 1028 StringAttr metadataName = aliasScopeRef.getRootReference(); 1029 StringAttr scopeName = aliasScopeRef.getLeafReference(); 1030 auto metadataOp = SymbolTable::lookupNearestSymbolFrom<LLVM::MetadataOp>( 1031 opInst.getParentOp(), metadataName); 1032 Operation *aliasScopeOp = 1033 SymbolTable::lookupNearestSymbolFrom(metadataOp, scopeName); 1034 return aliasScopeMetadataMapping.lookup(aliasScopeOp); 1035 } 1036 1037 void ModuleTranslation::setAliasScopeMetadata(Operation *op, 1038 llvm::Instruction *inst) { 1039 auto populateScopeMetadata = [this, op, inst](StringRef attrName, 1040 StringRef llvmMetadataName) { 1041 auto scopes = op->getAttrOfType<ArrayAttr>(attrName); 1042 if (!scopes || scopes.empty()) 1043 return; 1044 llvm::Module *module = inst->getModule(); 1045 SmallVector<llvm::Metadata *> scopeMDs; 1046 for (SymbolRefAttr scopeRef : scopes.getAsRange<SymbolRefAttr>()) 1047 scopeMDs.push_back(getAliasScope(*op, scopeRef)); 1048 llvm::MDNode *unionMD = llvm::MDNode::get(module->getContext(), scopeMDs); 1049 inst->setMetadata(module->getMDKindID(llvmMetadataName), unionMD); 1050 }; 1051 1052 populateScopeMetadata(LLVMDialect::getAliasScopesAttrName(), "alias.scope"); 1053 populateScopeMetadata(LLVMDialect::getNoAliasScopesAttrName(), "noalias"); 1054 } 1055 1056 llvm::Type *ModuleTranslation::convertType(Type type) { 1057 return typeTranslator.translateType(type); 1058 } 1059 1060 /// A helper to look up remapped operands in the value remapping table. 1061 SmallVector<llvm::Value *> ModuleTranslation::lookupValues(ValueRange values) { 1062 SmallVector<llvm::Value *> remapped; 1063 remapped.reserve(values.size()); 1064 for (Value v : values) 1065 remapped.push_back(lookupValue(v)); 1066 return remapped; 1067 } 1068 1069 const llvm::DILocation * 1070 ModuleTranslation::translateLoc(Location loc, llvm::DILocalScope *scope) { 1071 return debugTranslation->translateLoc(loc, scope); 1072 } 1073 1074 llvm::NamedMDNode * 1075 ModuleTranslation::getOrInsertNamedModuleMetadata(StringRef name) { 1076 return llvmModule->getOrInsertNamedMetadata(name); 1077 } 1078 1079 void ModuleTranslation::StackFrame::anchor() {} 1080 1081 static std::unique_ptr<llvm::Module> 1082 prepareLLVMModule(Operation *m, llvm::LLVMContext &llvmContext, 1083 StringRef name) { 1084 m->getContext()->getOrLoadDialect<LLVM::LLVMDialect>(); 1085 auto llvmModule = std::make_unique<llvm::Module>(name, llvmContext); 1086 if (auto dataLayoutAttr = 1087 m->getAttr(LLVM::LLVMDialect::getDataLayoutAttrName())) { 1088 llvmModule->setDataLayout(dataLayoutAttr.cast<StringAttr>().getValue()); 1089 } else { 1090 FailureOr<llvm::DataLayout> llvmDataLayout(llvm::DataLayout("")); 1091 if (auto iface = dyn_cast<DataLayoutOpInterface>(m)) { 1092 if (DataLayoutSpecInterface spec = iface.getDataLayoutSpec()) { 1093 llvmDataLayout = 1094 translateDataLayout(spec, DataLayout(iface), m->getLoc()); 1095 } 1096 } else if (auto mod = dyn_cast<ModuleOp>(m)) { 1097 if (DataLayoutSpecInterface spec = mod.getDataLayoutSpec()) { 1098 llvmDataLayout = 1099 translateDataLayout(spec, DataLayout(mod), m->getLoc()); 1100 } 1101 } 1102 if (failed(llvmDataLayout)) 1103 return nullptr; 1104 llvmModule->setDataLayout(*llvmDataLayout); 1105 } 1106 if (auto targetTripleAttr = 1107 m->getAttr(LLVM::LLVMDialect::getTargetTripleAttrName())) 1108 llvmModule->setTargetTriple(targetTripleAttr.cast<StringAttr>().getValue()); 1109 1110 // Inject declarations for `malloc` and `free` functions that can be used in 1111 // memref allocation/deallocation coming from standard ops lowering. 1112 llvm::IRBuilder<> builder(llvmContext); 1113 llvmModule->getOrInsertFunction("malloc", builder.getInt8PtrTy(), 1114 builder.getInt64Ty()); 1115 llvmModule->getOrInsertFunction("free", builder.getVoidTy(), 1116 builder.getInt8PtrTy()); 1117 1118 return llvmModule; 1119 } 1120 1121 std::unique_ptr<llvm::Module> 1122 mlir::translateModuleToLLVMIR(Operation *module, llvm::LLVMContext &llvmContext, 1123 StringRef name) { 1124 if (!satisfiesLLVMModule(module)) 1125 return nullptr; 1126 1127 std::unique_ptr<llvm::Module> llvmModule = 1128 prepareLLVMModule(module, llvmContext, name); 1129 if (!llvmModule) 1130 return nullptr; 1131 1132 LLVM::ensureDistinctSuccessors(module); 1133 1134 ModuleTranslation translator(module, std::move(llvmModule)); 1135 if (failed(translator.convertFunctionSignatures())) 1136 return nullptr; 1137 if (failed(translator.convertGlobals())) 1138 return nullptr; 1139 if (failed(translator.createAccessGroupMetadata())) 1140 return nullptr; 1141 if (failed(translator.createAliasScopeMetadata())) 1142 return nullptr; 1143 if (failed(translator.convertFunctions())) 1144 return nullptr; 1145 1146 // Convert other top-level operations if possible. 1147 llvm::IRBuilder<> llvmBuilder(llvmContext); 1148 for (Operation &o : getModuleBody(module).getOperations()) { 1149 if (!isa<LLVM::LLVMFuncOp, LLVM::GlobalOp, LLVM::GlobalCtorsOp, 1150 LLVM::GlobalDtorsOp, LLVM::MetadataOp>(&o) && 1151 !o.hasTrait<OpTrait::IsTerminator>() && 1152 failed(translator.convertOperation(o, llvmBuilder))) { 1153 return nullptr; 1154 } 1155 } 1156 1157 if (llvm::verifyModule(*translator.llvmModule, &llvm::errs())) 1158 return nullptr; 1159 1160 return std::move(translator.llvmModule); 1161 } 1162