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