| 1 | //===- Target.cpp - MLIR LLVM NVVM target compilation -----------*- C++ -*-===// |
| 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 files defines NVVM target related functions including registration |
| 10 | // calls for the `#nvvm.target` compilation attribute. |
| 11 | // |
| 12 | //===----------------------------------------------------------------------===// |
| 13 | |
| 14 | #include "mlir/Target/LLVM/NVVM/Target.h" |
| 15 | |
| 16 | #include "mlir/Dialect/GPU/IR/CompilationInterfaces.h" |
| 17 | #include "mlir/Dialect/GPU/IR/GPUDialect.h" |
| 18 | #include "mlir/Dialect/LLVMIR/NVVMAttributes.h" |
| 19 | #include "mlir/IR/BuiltinDialect.h" |
| 20 | #include "mlir/IR/BuiltinTypes.h" |
| 21 | #include "mlir/IR/DialectResourceBlobManager.h" |
| 22 | #include "mlir/Target/LLVM/NVVM/Utils.h" |
| 23 | #include "mlir/Target/LLVMIR/Dialect/GPU/GPUToLLVMIRTranslation.h" |
| 24 | #include "mlir/Target/LLVMIR/Dialect/LLVMIR/LLVMToLLVMIRTranslation.h" |
| 25 | #include "mlir/Target/LLVMIR/Dialect/NVVM/NVVMToLLVMIRTranslation.h" |
| 26 | #include "mlir/Target/LLVMIR/Export.h" |
| 27 | #include "llvm/Support/InterleavedRange.h" |
| 28 | |
| 29 | #include "llvm/ADT/ScopeExit.h" |
| 30 | #include "llvm/Config/Targets.h" |
| 31 | #include "llvm/Support/DebugLog.h" |
| 32 | #include "llvm/Support/FileSystem.h" |
| 33 | #include "llvm/Support/FileUtilities.h" |
| 34 | #include "llvm/Support/FormatVariadic.h" |
| 35 | #include "llvm/Support/MemoryBuffer.h" |
| 36 | #include "llvm/Support/Path.h" |
| 37 | #include "llvm/Support/Process.h" |
| 38 | #include "llvm/Support/Program.h" |
| 39 | #include "llvm/Support/TargetSelect.h" |
| 40 | #include "llvm/Support/Timer.h" |
| 41 | #include "llvm/Support/raw_ostream.h" |
| 42 | |
| 43 | #include <cstdint> |
| 44 | #include <cstdlib> |
| 45 | #include <optional> |
| 46 | |
| 47 | using namespace mlir; |
| 48 | using namespace mlir::NVVM; |
| 49 | |
| 50 | #ifndef __DEFAULT_CUDATOOLKIT_PATH__ |
| 51 | #define __DEFAULT_CUDATOOLKIT_PATH__ "" |
| 52 | #endif |
| 53 | |
| 54 | extern "C" const unsigned char _mlir_embedded_libdevice[]; |
| 55 | extern "C" const unsigned _mlir_embedded_libdevice_size; |
| 56 | |
| 57 | namespace { |
| 58 | // Implementation of the `TargetAttrInterface` model. |
| 59 | class NVVMTargetAttrImpl |
| 60 | : public gpu::TargetAttrInterface::FallbackModel<NVVMTargetAttrImpl> { |
| 61 | public: |
| 62 | std::optional<mlir::gpu::SerializedObject> |
| 63 | serializeToObject(Attribute attribute, Operation *module, |
| 64 | const gpu::TargetOptions &options) const; |
| 65 | |
| 66 | Attribute createObject(Attribute attribute, Operation *module, |
| 67 | const mlir::gpu::SerializedObject &object, |
| 68 | const gpu::TargetOptions &options) const; |
| 69 | }; |
| 70 | } // namespace |
| 71 | |
| 72 | // Register the NVVM dialect, the NVVM translation & the target interface. |
| 73 | void mlir::NVVM::registerNVVMTargetInterfaceExternalModels( |
| 74 | DialectRegistry ®istry) { |
| 75 | registry.addExtension(extensionFn: +[](MLIRContext *ctx, NVVM::NVVMDialect *dialect) { |
| 76 | NVVMTargetAttr::attachInterface<NVVMTargetAttrImpl>(context&: *ctx); |
| 77 | }); |
| 78 | } |
| 79 | |
| 80 | void mlir::NVVM::registerNVVMTargetInterfaceExternalModels( |
| 81 | MLIRContext &context) { |
| 82 | DialectRegistry registry; |
| 83 | registerNVVMTargetInterfaceExternalModels(registry); |
| 84 | context.appendDialectRegistry(registry); |
| 85 | } |
| 86 | |
| 87 | // Search for the CUDA toolkit path. |
| 88 | StringRef mlir::NVVM::getCUDAToolkitPath() { |
| 89 | if (const char *var = std::getenv(name: "CUDA_ROOT" )) |
| 90 | return var; |
| 91 | if (const char *var = std::getenv(name: "CUDA_HOME" )) |
| 92 | return var; |
| 93 | if (const char *var = std::getenv(name: "CUDA_PATH" )) |
| 94 | return var; |
| 95 | return __DEFAULT_CUDATOOLKIT_PATH__; |
| 96 | } |
| 97 | |
| 98 | SerializeGPUModuleBase::SerializeGPUModuleBase( |
| 99 | Operation &module, NVVMTargetAttr target, |
| 100 | const gpu::TargetOptions &targetOptions) |
| 101 | : ModuleToObject( |
| 102 | module, target.getTriple(), target.getChip(), target.getFeatures(), |
| 103 | target.getO(), targetOptions.getInitialLlvmIRCallback(), |
| 104 | targetOptions.getLinkedLlvmIRCallback(), |
| 105 | targetOptions.getOptimizedLlvmIRCallback(), |
| 106 | targetOptions.getISACallback(), targetOptions.getLibraryOptions()), |
| 107 | target(target), toolkitPath(targetOptions.getToolkitPath()), |
| 108 | librariesToLink(targetOptions.getLibrariesToLink()) { |
| 109 | |
| 110 | // If `targetOptions` have an empty toolkitPath use `getCUDAToolkitPath` |
| 111 | if (toolkitPath.empty()) |
| 112 | toolkitPath = getCUDAToolkitPath(); |
| 113 | |
| 114 | // Append the files in the target attribute. |
| 115 | if (target.getLink()) |
| 116 | librariesToLink.append(in_start: target.getLink().begin(), in_end: target.getLink().end()); |
| 117 | |
| 118 | // Append libdevice to the files to be loaded. |
| 119 | (void)appendStandardLibs(); |
| 120 | } |
| 121 | |
| 122 | void SerializeGPUModuleBase::init() { |
| 123 | static llvm::once_flag initializeBackendOnce; |
| 124 | llvm::call_once(flag&: initializeBackendOnce, F: []() { |
| 125 | // If the `NVPTX` LLVM target was built, initialize it. |
| 126 | #if LLVM_HAS_NVPTX_TARGET |
| 127 | LLVMInitializeNVPTXTarget(); |
| 128 | LLVMInitializeNVPTXTargetInfo(); |
| 129 | LLVMInitializeNVPTXTargetMC(); |
| 130 | LLVMInitializeNVPTXAsmPrinter(); |
| 131 | #endif |
| 132 | }); |
| 133 | } |
| 134 | |
| 135 | NVVMTargetAttr SerializeGPUModuleBase::getTarget() const { return target; } |
| 136 | |
| 137 | StringRef SerializeGPUModuleBase::getToolkitPath() const { return toolkitPath; } |
| 138 | |
| 139 | ArrayRef<Attribute> SerializeGPUModuleBase::getLibrariesToLink() const { |
| 140 | return librariesToLink; |
| 141 | } |
| 142 | |
| 143 | // Try to append `libdevice` from a CUDA toolkit installation. |
| 144 | LogicalResult SerializeGPUModuleBase::appendStandardLibs() { |
| 145 | #if MLIR_NVVM_EMBED_LIBDEVICE |
| 146 | // If libdevice is embedded in the binary, we don't look it up on the |
| 147 | // filesystem. |
| 148 | MLIRContext *ctx = target.getContext(); |
| 149 | auto type = |
| 150 | RankedTensorType::get(ArrayRef<int64_t>{_mlir_embedded_libdevice_size}, |
| 151 | IntegerType::get(ctx, 8)); |
| 152 | auto resourceManager = DenseResourceElementsHandle::getManagerInterface(ctx); |
| 153 | |
| 154 | // Lookup if we already loaded the resource, otherwise create it. |
| 155 | DialectResourceBlobManager::BlobEntry *blob = |
| 156 | resourceManager.getBlobManager().lookup("_mlir_embedded_libdevice" ); |
| 157 | if (blob) { |
| 158 | librariesToLink.push_back(DenseResourceElementsAttr::get( |
| 159 | type, DenseResourceElementsHandle( |
| 160 | blob, ctx->getLoadedDialect<BuiltinDialect>()))); |
| 161 | return success(); |
| 162 | } |
| 163 | |
| 164 | // Allocate a resource using one of the UnManagedResourceBlob method to wrap |
| 165 | // the embedded data. |
| 166 | auto unmanagedBlob = UnmanagedAsmResourceBlob::allocateInferAlign( |
| 167 | ArrayRef<char>{(const char *)_mlir_embedded_libdevice, |
| 168 | _mlir_embedded_libdevice_size}); |
| 169 | librariesToLink.push_back(DenseResourceElementsAttr::get( |
| 170 | type, resourceManager.insert("_mlir_embedded_libdevice" , |
| 171 | std::move(unmanagedBlob)))); |
| 172 | #else |
| 173 | StringRef pathRef = getToolkitPath(); |
| 174 | if (!pathRef.empty()) { |
| 175 | SmallVector<char, 256> path; |
| 176 | path.insert(I: path.begin(), From: pathRef.begin(), To: pathRef.end()); |
| 177 | pathRef = StringRef(path.data(), path.size()); |
| 178 | if (!llvm::sys::fs::is_directory(Path: pathRef)) { |
| 179 | getOperation().emitError() << "CUDA path: " << pathRef |
| 180 | << " does not exist or is not a directory.\n" ; |
| 181 | return failure(); |
| 182 | } |
| 183 | llvm::sys::path::append(path, a: "nvvm" , b: "libdevice" , c: "libdevice.10.bc" ); |
| 184 | pathRef = StringRef(path.data(), path.size()); |
| 185 | if (!llvm::sys::fs::is_regular_file(Path: pathRef)) { |
| 186 | getOperation().emitError() << "LibDevice path: " << pathRef |
| 187 | << " does not exist or is not a file.\n" ; |
| 188 | return failure(); |
| 189 | } |
| 190 | librariesToLink.push_back(Elt: StringAttr::get(context: target.getContext(), bytes: pathRef)); |
| 191 | } |
| 192 | #endif |
| 193 | return success(); |
| 194 | } |
| 195 | |
| 196 | std::optional<SmallVector<std::unique_ptr<llvm::Module>>> |
| 197 | SerializeGPUModuleBase::loadBitcodeFiles(llvm::Module &module) { |
| 198 | SmallVector<std::unique_ptr<llvm::Module>> bcFiles; |
| 199 | if (failed(Result: loadBitcodeFilesFromList(context&: module.getContext(), librariesToLink, |
| 200 | llvmModules&: bcFiles, failureOnError: true))) |
| 201 | return std::nullopt; |
| 202 | return std::move(bcFiles); |
| 203 | } |
| 204 | |
| 205 | namespace { |
| 206 | class NVPTXSerializer : public SerializeGPUModuleBase { |
| 207 | public: |
| 208 | NVPTXSerializer(Operation &module, NVVMTargetAttr target, |
| 209 | const gpu::TargetOptions &targetOptions); |
| 210 | |
| 211 | /// Returns the GPU module op being serialized. |
| 212 | gpu::GPUModuleOp getOperation(); |
| 213 | |
| 214 | /// Compiles PTX to cubin using `ptxas`. |
| 215 | FailureOr<SmallVector<char, 0>> compileToBinary(StringRef ptxCode); |
| 216 | |
| 217 | /// Compiles PTX to cubin using the `nvptxcompiler` library. |
| 218 | FailureOr<SmallVector<char, 0>> compileToBinaryNVPTX(StringRef ptxCode); |
| 219 | |
| 220 | /// Serializes the LLVM module to an object format, depending on the |
| 221 | /// compilation target selected in target options. |
| 222 | FailureOr<SmallVector<char, 0>> |
| 223 | moduleToObject(llvm::Module &llvmModule) override; |
| 224 | |
| 225 | /// Get LLVMIR->ISA performance result. |
| 226 | /// Return nullopt if moduleToObject has not been called or the target format |
| 227 | /// is LLVMIR. |
| 228 | std::optional<int64_t> getLLVMIRToISATimeInMs(); |
| 229 | |
| 230 | /// Get ISA->Binary performance result. |
| 231 | /// Return nullopt if moduleToObject has not been called or the target format |
| 232 | /// is LLVMIR or ISA. |
| 233 | std::optional<int64_t> getISAToBinaryTimeInMs(); |
| 234 | |
| 235 | /// Get the compiler log from ISA compiler. |
| 236 | StringRef getISACompilerLog() const; |
| 237 | |
| 238 | private: |
| 239 | using TmpFile = std::pair<llvm::SmallString<128>, llvm::FileRemover>; |
| 240 | |
| 241 | /// Creates a temp file. |
| 242 | std::optional<TmpFile> createTemp(StringRef name, StringRef suffix); |
| 243 | |
| 244 | /// Finds the `tool` path, where `tool` is the name of the binary to search, |
| 245 | /// i.e. `ptxas` or `fatbinary`. The search order is: |
| 246 | /// 1. The toolkit path in `targetOptions`. |
| 247 | /// 2. In the system PATH. |
| 248 | /// 3. The path from `getCUDAToolkitPath()`. |
| 249 | std::optional<std::string> findTool(StringRef tool); |
| 250 | |
| 251 | /// Target options. |
| 252 | gpu::TargetOptions targetOptions; |
| 253 | |
| 254 | /// LLVMIR->ISA perf result. |
| 255 | std::optional<int64_t> llvmToISATimeInMs; |
| 256 | |
| 257 | /// ISA->Binary perf result. |
| 258 | std::optional<int64_t> isaToBinaryTimeInMs; |
| 259 | |
| 260 | /// Compiler log from ptxas or libnvptxcompiler. |
| 261 | std::string isaCompilerLog; |
| 262 | }; |
| 263 | } // namespace |
| 264 | |
| 265 | NVPTXSerializer::NVPTXSerializer(Operation &module, NVVMTargetAttr target, |
| 266 | const gpu::TargetOptions &targetOptions) |
| 267 | : SerializeGPUModuleBase(module, target, targetOptions), |
| 268 | targetOptions(targetOptions), llvmToISATimeInMs(std::nullopt), |
| 269 | isaToBinaryTimeInMs(std::nullopt) {} |
| 270 | |
| 271 | std::optional<NVPTXSerializer::TmpFile> |
| 272 | NVPTXSerializer::createTemp(StringRef name, StringRef suffix) { |
| 273 | llvm::SmallString<128> filename; |
| 274 | if (name.size() > 80) |
| 275 | name = name.substr(Start: 0, N: 80); |
| 276 | std::error_code ec = |
| 277 | llvm::sys::fs::createTemporaryFile(Prefix: name, Suffix: suffix, ResultPath&: filename); |
| 278 | if (ec) { |
| 279 | getOperation().emitError() << "Couldn't create the temp file: `" << filename |
| 280 | << "`, error message: " << ec.message(); |
| 281 | return std::nullopt; |
| 282 | } |
| 283 | return TmpFile(filename, llvm::FileRemover(filename.c_str())); |
| 284 | } |
| 285 | |
| 286 | std::optional<int64_t> NVPTXSerializer::getLLVMIRToISATimeInMs() { |
| 287 | return llvmToISATimeInMs; |
| 288 | } |
| 289 | |
| 290 | std::optional<int64_t> NVPTXSerializer::getISAToBinaryTimeInMs() { |
| 291 | return isaToBinaryTimeInMs; |
| 292 | } |
| 293 | |
| 294 | StringRef NVPTXSerializer::getISACompilerLog() const { return isaCompilerLog; } |
| 295 | |
| 296 | gpu::GPUModuleOp NVPTXSerializer::getOperation() { |
| 297 | return dyn_cast<gpu::GPUModuleOp>(Val: &SerializeGPUModuleBase::getOperation()); |
| 298 | } |
| 299 | |
| 300 | std::optional<std::string> NVPTXSerializer::findTool(StringRef tool) { |
| 301 | // Find the `tool` path. |
| 302 | // 1. Check the toolkit path given in the command line. |
| 303 | StringRef pathRef = targetOptions.getToolkitPath(); |
| 304 | SmallVector<char, 256> path; |
| 305 | if (!pathRef.empty()) { |
| 306 | path.insert(I: path.begin(), From: pathRef.begin(), To: pathRef.end()); |
| 307 | llvm::sys::path::append(path, a: "bin" , b: tool); |
| 308 | if (llvm::sys::fs::can_execute(Path: path)) |
| 309 | return StringRef(path.data(), path.size()).str(); |
| 310 | } |
| 311 | |
| 312 | // 2. Check PATH. |
| 313 | if (std::optional<std::string> toolPath = |
| 314 | llvm::sys::Process::FindInEnvPath(EnvName: "PATH" , FileName: tool)) |
| 315 | return *toolPath; |
| 316 | |
| 317 | // 3. Check `getCUDAToolkitPath()`. |
| 318 | pathRef = getCUDAToolkitPath(); |
| 319 | path.clear(); |
| 320 | if (!pathRef.empty()) { |
| 321 | path.insert(I: path.begin(), From: pathRef.begin(), To: pathRef.end()); |
| 322 | llvm::sys::path::append(path, a: "bin" , b: tool); |
| 323 | if (llvm::sys::fs::can_execute(Path: path)) |
| 324 | return StringRef(path.data(), path.size()).str(); |
| 325 | } |
| 326 | getOperation().emitError() |
| 327 | << "Couldn't find the `" << tool |
| 328 | << "` binary. Please specify the toolkit " |
| 329 | "path, add the compiler to $PATH, or set one of the environment " |
| 330 | "variables in `NVVM::getCUDAToolkitPath()`." ; |
| 331 | return std::nullopt; |
| 332 | } |
| 333 | |
| 334 | /// Adds optional command-line arguments to existing arguments. |
| 335 | template <typename T> |
| 336 | static void setOptionalCommandlineArguments(NVVMTargetAttr target, |
| 337 | SmallVectorImpl<T> &ptxasArgs) { |
| 338 | if (!target.hasCmdOptions()) |
| 339 | return; |
| 340 | |
| 341 | std::optional<mlir::NamedAttribute> cmdOptions = target.getCmdOptions(); |
| 342 | for (Attribute attr : cast<ArrayAttr>(Val: cmdOptions->getValue())) { |
| 343 | if (auto strAttr = dyn_cast<StringAttr>(Val&: attr)) { |
| 344 | if constexpr (std::is_same_v<T, StringRef>) { |
| 345 | ptxasArgs.push_back(strAttr.getValue()); |
| 346 | } else if constexpr (std::is_same_v<T, const char *>) { |
| 347 | ptxasArgs.push_back(strAttr.getValue().data()); |
| 348 | } |
| 349 | } |
| 350 | } |
| 351 | } |
| 352 | |
| 353 | // TODO: clean this method & have a generic tool driver or never emit binaries |
| 354 | // with this mechanism and let another stage take care of it. |
| 355 | FailureOr<SmallVector<char, 0>> |
| 356 | NVPTXSerializer::compileToBinary(StringRef ptxCode) { |
| 357 | // Determine if the serializer should create a fatbinary with the PTX embeded |
| 358 | // or a simple CUBIN binary. |
| 359 | const bool createFatbin = |
| 360 | targetOptions.getCompilationTarget() == gpu::CompilationTarget::Fatbin; |
| 361 | |
| 362 | // Find the `ptxas` & `fatbinary` tools. |
| 363 | std::optional<std::string> ptxasCompiler = findTool(tool: "ptxas" ); |
| 364 | if (!ptxasCompiler) |
| 365 | return failure(); |
| 366 | std::optional<std::string> fatbinaryTool; |
| 367 | if (createFatbin) { |
| 368 | fatbinaryTool = findTool(tool: "fatbinary" ); |
| 369 | if (!fatbinaryTool) |
| 370 | return failure(); |
| 371 | } |
| 372 | Location loc = getOperation().getLoc(); |
| 373 | |
| 374 | // Base name for all temp files: mlir-<module name>-<target triple>-<chip>. |
| 375 | std::string basename = |
| 376 | llvm::formatv(Fmt: "mlir-{0}-{1}-{2}" , Vals: getOperation().getNameAttr().getValue(), |
| 377 | Vals: getTarget().getTriple(), Vals: getTarget().getChip()); |
| 378 | |
| 379 | // Create temp files: |
| 380 | std::optional<TmpFile> ptxFile = createTemp(name: basename, suffix: "ptx" ); |
| 381 | if (!ptxFile) |
| 382 | return failure(); |
| 383 | std::optional<TmpFile> logFile = createTemp(name: basename, suffix: "log" ); |
| 384 | if (!logFile) |
| 385 | return failure(); |
| 386 | std::optional<TmpFile> binaryFile = createTemp(name: basename, suffix: "bin" ); |
| 387 | if (!binaryFile) |
| 388 | return failure(); |
| 389 | TmpFile cubinFile; |
| 390 | if (createFatbin) { |
| 391 | std::string cubinFilename = (ptxFile->first + ".cubin" ).str(); |
| 392 | cubinFile = TmpFile(cubinFilename, llvm::FileRemover(cubinFilename)); |
| 393 | } else { |
| 394 | cubinFile.first = binaryFile->first; |
| 395 | } |
| 396 | |
| 397 | std::error_code ec; |
| 398 | // Dump the PTX to a temp file. |
| 399 | { |
| 400 | llvm::raw_fd_ostream ptxStream(ptxFile->first, ec); |
| 401 | if (ec) |
| 402 | return emitError(loc) << "Couldn't open the file: `" << ptxFile->first |
| 403 | << "`, error message: " << ec.message(); |
| 404 | |
| 405 | ptxStream << ptxCode; |
| 406 | if (ptxStream.has_error()) |
| 407 | return emitError(loc) << "An error occurred while writing the PTX to: `" |
| 408 | << ptxFile->first << "`." ; |
| 409 | |
| 410 | ptxStream.flush(); |
| 411 | } |
| 412 | |
| 413 | // Command redirects. |
| 414 | std::optional<StringRef> redirects[] = { |
| 415 | std::nullopt, |
| 416 | logFile->first, |
| 417 | logFile->first, |
| 418 | }; |
| 419 | |
| 420 | // Get any extra args passed in `targetOptions`. |
| 421 | std::pair<llvm::BumpPtrAllocator, SmallVector<const char *>> cmdOpts = |
| 422 | targetOptions.tokenizeCmdOptions(); |
| 423 | |
| 424 | // Create ptxas args. |
| 425 | std::string optLevel = std::to_string(val: this->optLevel); |
| 426 | SmallVector<StringRef, 12> ptxasArgs( |
| 427 | {StringRef("ptxas" ), StringRef("-arch" ), getTarget().getChip(), |
| 428 | StringRef(ptxFile->first), StringRef("-o" ), StringRef(cubinFile.first), |
| 429 | "--opt-level" , optLevel}); |
| 430 | |
| 431 | bool useFatbin32 = false; |
| 432 | for (const auto *cArg : cmdOpts.second) { |
| 433 | // All `cmdOpts` are for `ptxas` except `-32` which passes `-32` to |
| 434 | // `fatbinary`, indicating a 32-bit target. By default a 64-bit target is |
| 435 | // assumed. |
| 436 | if (StringRef arg(cArg); arg != "-32" ) |
| 437 | ptxasArgs.push_back(Elt: arg); |
| 438 | else |
| 439 | useFatbin32 = true; |
| 440 | } |
| 441 | |
| 442 | // Set optional command line arguments |
| 443 | setOptionalCommandlineArguments(target: getTarget(), ptxasArgs); |
| 444 | |
| 445 | // Create the `fatbinary` args. |
| 446 | StringRef chip = getTarget().getChip(); |
| 447 | // Remove the arch prefix to obtain the compute capability. |
| 448 | chip.consume_front(Prefix: "sm_" ), chip.consume_front(Prefix: "compute_" ); |
| 449 | // Embed the cubin object. |
| 450 | std::string cubinArg = |
| 451 | llvm::formatv(Fmt: "--image3=kind=elf,sm={0},file={1}" , Vals&: chip, Vals&: cubinFile.first) |
| 452 | .str(); |
| 453 | // Embed the PTX file so the driver can JIT if needed. |
| 454 | std::string ptxArg = |
| 455 | llvm::formatv(Fmt: "--image3=kind=ptx,sm={0},file={1}" , Vals&: chip, Vals&: ptxFile->first) |
| 456 | .str(); |
| 457 | SmallVector<StringRef, 6> fatbinArgs({StringRef("fatbinary" ), |
| 458 | useFatbin32 ? "-32" : "-64" , cubinArg, |
| 459 | ptxArg, "--create" , binaryFile->first}); |
| 460 | |
| 461 | // Dump tool invocation commands. |
| 462 | #define DEBUG_TYPE "serialize-to-binary" |
| 463 | LDBG() << "Tool invocation for module: " << getOperation().getNameAttr() |
| 464 | << "\nptxas executable:" << ptxasCompiler.value() |
| 465 | << "\nptxas args: " << llvm::interleaved(R: ptxasArgs, Separator: " " ); |
| 466 | if (createFatbin) |
| 467 | LDBG() << "fatbin args: " << llvm::interleaved(R: fatbinArgs, Separator: " " ); |
| 468 | #undef DEBUG_TYPE |
| 469 | |
| 470 | // Helper function for printing tool error logs. |
| 471 | std::string message; |
| 472 | auto emitLogError = |
| 473 | [&](StringRef toolName) -> FailureOr<SmallVector<char, 0>> { |
| 474 | if (message.empty()) { |
| 475 | llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> toolStderr = |
| 476 | llvm::MemoryBuffer::getFile(Filename: logFile->first); |
| 477 | if (toolStderr) |
| 478 | return emitError(loc) << toolName << " invocation failed. Log:\n" |
| 479 | << toolStderr->get()->getBuffer(); |
| 480 | else |
| 481 | return emitError(loc) << toolName << " invocation failed." ; |
| 482 | } |
| 483 | return emitError(loc) << toolName |
| 484 | << " invocation failed, error message: " << message; |
| 485 | }; |
| 486 | |
| 487 | // Invoke PTXAS. |
| 488 | if (llvm::sys::ExecuteAndWait(Program: ptxasCompiler.value(), Args: ptxasArgs, |
| 489 | /*Env=*/std::nullopt, |
| 490 | /*Redirects=*/redirects, |
| 491 | /*SecondsToWait=*/0, |
| 492 | /*MemoryLimit=*/0, |
| 493 | /*ErrMsg=*/&message)) |
| 494 | return emitLogError("`ptxas`" ); |
| 495 | |
| 496 | if (target.hasFlag(flag: "collect-compiler-diagnostics" )) { |
| 497 | if (auto logBuffer = llvm::MemoryBuffer::getFile(Filename: logFile->first)) |
| 498 | isaCompilerLog = (*logBuffer)->getBuffer().str(); |
| 499 | } |
| 500 | #define DEBUG_TYPE "dump-sass" |
| 501 | LLVM_DEBUG({ |
| 502 | std::optional<std::string> nvdisasm = findTool("nvdisasm" ); |
| 503 | SmallVector<StringRef> nvdisasmArgs( |
| 504 | {StringRef("nvdisasm" ), StringRef(cubinFile.first)}); |
| 505 | if (llvm::sys::ExecuteAndWait(nvdisasm.value(), nvdisasmArgs, |
| 506 | /*Env=*/std::nullopt, |
| 507 | /*Redirects=*/redirects, |
| 508 | /*SecondsToWait=*/0, |
| 509 | /*MemoryLimit=*/0, |
| 510 | /*ErrMsg=*/&message)) |
| 511 | return emitLogError("`nvdisasm`" ); |
| 512 | llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> logBuffer = |
| 513 | llvm::MemoryBuffer::getFile(logFile->first); |
| 514 | if (logBuffer && !(*logBuffer)->getBuffer().empty()) { |
| 515 | LDBG() << "Output:\n" << (*logBuffer)->getBuffer(); |
| 516 | llvm::dbgs().flush(); |
| 517 | } |
| 518 | }); |
| 519 | #undef DEBUG_TYPE |
| 520 | |
| 521 | // Invoke `fatbin`. |
| 522 | message.clear(); |
| 523 | if (createFatbin && llvm::sys::ExecuteAndWait(Program: *fatbinaryTool, Args: fatbinArgs, |
| 524 | /*Env=*/std::nullopt, |
| 525 | /*Redirects=*/redirects, |
| 526 | /*SecondsToWait=*/0, |
| 527 | /*MemoryLimit=*/0, |
| 528 | /*ErrMsg=*/&message)) |
| 529 | return emitLogError("`fatbinary`" ); |
| 530 | |
| 531 | // Dump the output of the tools, helpful if the verbose flag was passed. |
| 532 | #define DEBUG_TYPE "serialize-to-binary" |
| 533 | LLVM_DEBUG({ |
| 534 | llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> logBuffer = |
| 535 | llvm::MemoryBuffer::getFile(logFile->first); |
| 536 | if (logBuffer && !(*logBuffer)->getBuffer().empty()) { |
| 537 | LDBG() << "Output:\n" << (*logBuffer)->getBuffer(); |
| 538 | llvm::dbgs().flush(); |
| 539 | } |
| 540 | }); |
| 541 | #undef DEBUG_TYPE |
| 542 | |
| 543 | // Read the fatbin. |
| 544 | llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> binaryBuffer = |
| 545 | llvm::MemoryBuffer::getFile(Filename: binaryFile->first); |
| 546 | if (!binaryBuffer) |
| 547 | return emitError(loc) << "Couldn't open the file: `" << binaryFile->first |
| 548 | << "`, error message: " |
| 549 | << binaryBuffer.getError().message(); |
| 550 | |
| 551 | StringRef fatbin = (*binaryBuffer)->getBuffer(); |
| 552 | return SmallVector<char, 0>(fatbin.begin(), fatbin.end()); |
| 553 | } |
| 554 | |
| 555 | #if MLIR_ENABLE_NVPTXCOMPILER |
| 556 | #include "nvPTXCompiler.h" |
| 557 | |
| 558 | #define RETURN_ON_NVPTXCOMPILER_ERROR(expr) \ |
| 559 | do { \ |
| 560 | if (auto status = (expr)) { \ |
| 561 | emitError(loc) << llvm::Twine(#expr).concat(" failed with error code ") \ |
| 562 | << status; \ |
| 563 | return failure(); \ |
| 564 | } \ |
| 565 | } while (false) |
| 566 | |
| 567 | #include "nvFatbin.h" |
| 568 | |
| 569 | #define RETURN_ON_NVFATBIN_ERROR(expr) \ |
| 570 | do { \ |
| 571 | auto result = (expr); \ |
| 572 | if (result != nvFatbinResult::NVFATBIN_SUCCESS) { \ |
| 573 | emitError(loc) << llvm::Twine(#expr).concat(" failed with error: ") \ |
| 574 | << nvFatbinGetErrorString(result); \ |
| 575 | return failure(); \ |
| 576 | } \ |
| 577 | } while (false) |
| 578 | |
| 579 | FailureOr<SmallVector<char, 0>> |
| 580 | NVPTXSerializer::compileToBinaryNVPTX(StringRef ptxCode) { |
| 581 | Location loc = getOperation().getLoc(); |
| 582 | nvPTXCompilerHandle compiler = nullptr; |
| 583 | nvPTXCompileResult status; |
| 584 | size_t logSize; |
| 585 | |
| 586 | // Create the options. |
| 587 | std::string optLevel = std::to_string(this->optLevel); |
| 588 | std::pair<llvm::BumpPtrAllocator, SmallVector<const char *>> cmdOpts = |
| 589 | targetOptions.tokenizeCmdOptions(); |
| 590 | cmdOpts.second.insert( |
| 591 | cmdOpts.second.begin(), |
| 592 | {"-arch" , getTarget().getChip().data(), "--opt-level" , optLevel.c_str()}); |
| 593 | |
| 594 | // Set optional command line arguments |
| 595 | setOptionalCommandlineArguments(getTarget(), cmdOpts.second); |
| 596 | // Create the compiler handle. |
| 597 | RETURN_ON_NVPTXCOMPILER_ERROR( |
| 598 | nvPTXCompilerCreate(&compiler, ptxCode.size(), ptxCode.str().c_str())); |
| 599 | |
| 600 | // Try to compile the binary. |
| 601 | status = nvPTXCompilerCompile(compiler, cmdOpts.second.size(), |
| 602 | cmdOpts.second.data()); |
| 603 | |
| 604 | // Check if compilation failed. |
| 605 | if (status != NVPTXCOMPILE_SUCCESS) { |
| 606 | RETURN_ON_NVPTXCOMPILER_ERROR( |
| 607 | nvPTXCompilerGetErrorLogSize(compiler, &logSize)); |
| 608 | if (logSize != 0) { |
| 609 | SmallVector<char> log(logSize + 1, 0); |
| 610 | RETURN_ON_NVPTXCOMPILER_ERROR( |
| 611 | nvPTXCompilerGetErrorLog(compiler, log.data())); |
| 612 | return emitError(loc) |
| 613 | << "NVPTX compiler invocation failed, error log: " << log.data(); |
| 614 | } else { |
| 615 | return emitError(loc) |
| 616 | << "NVPTX compiler invocation failed with error code: " << status; |
| 617 | } |
| 618 | } |
| 619 | |
| 620 | // Retrieve the binary. |
| 621 | size_t elfSize; |
| 622 | RETURN_ON_NVPTXCOMPILER_ERROR( |
| 623 | nvPTXCompilerGetCompiledProgramSize(compiler, &elfSize)); |
| 624 | SmallVector<char, 0> binary(elfSize, 0); |
| 625 | RETURN_ON_NVPTXCOMPILER_ERROR( |
| 626 | nvPTXCompilerGetCompiledProgram(compiler, (void *)binary.data())); |
| 627 | |
| 628 | // Lambda to fetch info log; returns empty vector on failure or no log. |
| 629 | auto fetchInfoLog = [&]() -> SmallVector<char> { |
| 630 | size_t size = 0; |
| 631 | if (nvPTXCompilerGetInfoLogSize(compiler, &size) != NVPTXCOMPILE_SUCCESS || |
| 632 | size == 0) |
| 633 | return {}; |
| 634 | SmallVector<char> log(size + 1, 0); |
| 635 | if (nvPTXCompilerGetInfoLog(compiler, log.data()) != NVPTXCOMPILE_SUCCESS) |
| 636 | return {}; |
| 637 | return log; |
| 638 | }; |
| 639 | |
| 640 | if (target.hasFlag("collect-compiler-diagnostics" )) { |
| 641 | if (auto log = fetchInfoLog(); !log.empty()) |
| 642 | isaCompilerLog = log.data(); |
| 643 | } |
| 644 | |
| 645 | // Dump the log of the compiler, helpful if the verbose flag was passed. |
| 646 | #define DEBUG_TYPE "serialize-to-binary" |
| 647 | LLVM_DEBUG({ |
| 648 | if (auto log = fetchInfoLog(); !log.empty()) |
| 649 | LDBG() << "NVPTX compiler invocation for module: " |
| 650 | << getOperation().getNameAttr() |
| 651 | << "\nArguments: " << llvm::interleaved(cmdOpts.second, " " ) |
| 652 | << "\nOutput\n" |
| 653 | << log.data(); |
| 654 | }); |
| 655 | #undef DEBUG_TYPE |
| 656 | RETURN_ON_NVPTXCOMPILER_ERROR(nvPTXCompilerDestroy(&compiler)); |
| 657 | |
| 658 | if (targetOptions.getCompilationTarget() == gpu::CompilationTarget::Fatbin) { |
| 659 | bool useFatbin32 = llvm::any_of(cmdOpts.second, [](const char *option) { |
| 660 | return llvm::StringRef(option) == "-32" ; |
| 661 | }); |
| 662 | |
| 663 | const char *cubinOpts[1] = {useFatbin32 ? "-32" : "-64" }; |
| 664 | nvFatbinHandle handle; |
| 665 | |
| 666 | auto chip = getTarget().getChip(); |
| 667 | chip.consume_front("sm_" ); |
| 668 | |
| 669 | RETURN_ON_NVFATBIN_ERROR(nvFatbinCreate(&handle, cubinOpts, 1)); |
| 670 | RETURN_ON_NVFATBIN_ERROR(nvFatbinAddCubin( |
| 671 | handle, binary.data(), binary.size(), chip.data(), nullptr)); |
| 672 | RETURN_ON_NVFATBIN_ERROR(nvFatbinAddPTX( |
| 673 | handle, ptxCode.data(), ptxCode.size(), chip.data(), nullptr, nullptr)); |
| 674 | |
| 675 | size_t fatbinSize; |
| 676 | RETURN_ON_NVFATBIN_ERROR(nvFatbinSize(handle, &fatbinSize)); |
| 677 | SmallVector<char, 0> fatbin(fatbinSize, 0); |
| 678 | RETURN_ON_NVFATBIN_ERROR(nvFatbinGet(handle, (void *)fatbin.data())); |
| 679 | RETURN_ON_NVFATBIN_ERROR(nvFatbinDestroy(&handle)); |
| 680 | return fatbin; |
| 681 | } |
| 682 | |
| 683 | return binary; |
| 684 | } |
| 685 | #endif // MLIR_ENABLE_NVPTXCOMPILER |
| 686 | |
| 687 | FailureOr<SmallVector<char, 0>> |
| 688 | NVPTXSerializer::moduleToObject(llvm::Module &llvmModule) { |
| 689 | llvm::Timer moduleToObjectTimer( |
| 690 | "moduleToObjectTimer" , |
| 691 | "Timer for perf llvm-ir -> isa and isa -> binary." ); |
| 692 | llvm::scope_exit clear([&]() { moduleToObjectTimer.clear(); }); |
| 693 | // Return LLVM IR if the compilation target is `offload`. |
| 694 | #define DEBUG_TYPE "serialize-to-llvm" |
| 695 | LLVM_DEBUG({ |
| 696 | LDBG() << "LLVM IR for module: " << getOperation().getNameAttr(); |
| 697 | LDBG() << llvmModule; |
| 698 | }); |
| 699 | #undef DEBUG_TYPE |
| 700 | if (targetOptions.getCompilationTarget() == gpu::CompilationTarget::Offload) |
| 701 | return SerializeGPUModuleBase::moduleToObject(llvmModule); |
| 702 | |
| 703 | #if !LLVM_HAS_NVPTX_TARGET |
| 704 | return getOperation()->emitError( |
| 705 | "The `NVPTX` target was not built. Please enable it when building LLVM." ); |
| 706 | #endif // LLVM_HAS_NVPTX_TARGET |
| 707 | |
| 708 | // Emit PTX code. |
| 709 | FailureOr<llvm::TargetMachine *> targetMachine = getOrCreateTargetMachine(); |
| 710 | if (failed(Result: targetMachine)) |
| 711 | return getOperation().emitError() |
| 712 | << "Target Machine unavailable for triple " << triple |
| 713 | << ", can't optimize with LLVM\n" ; |
| 714 | |
| 715 | moduleToObjectTimer.startTimer(); |
| 716 | FailureOr<SmallString<0>> serializedISA = |
| 717 | translateModuleToISA(llvmModule, targetMachine&: **targetMachine, |
| 718 | emitError: [&]() { return getOperation().emitError(); }); |
| 719 | moduleToObjectTimer.stopTimer(); |
| 720 | llvmToISATimeInMs = moduleToObjectTimer.getTotalTime().getWallTime() * 1000; |
| 721 | moduleToObjectTimer.clear(); |
| 722 | if (failed(Result: serializedISA)) |
| 723 | return getOperation().emitError() |
| 724 | << "Failed translating the module to ISA." ; |
| 725 | |
| 726 | if (isaCallback) |
| 727 | isaCallback(*serializedISA); |
| 728 | |
| 729 | #define DEBUG_TYPE "serialize-to-isa" |
| 730 | LDBG() << "PTX for module: " << getOperation().getNameAttr() << "\n" |
| 731 | << *serializedISA; |
| 732 | #undef DEBUG_TYPE |
| 733 | |
| 734 | // Return PTX if the compilation target is `assembly`. |
| 735 | if (targetOptions.getCompilationTarget() == gpu::CompilationTarget::Assembly) |
| 736 | return SmallVector<char, 0>(serializedISA->begin(), serializedISA->end()); |
| 737 | |
| 738 | FailureOr<SmallVector<char, 0>> result; |
| 739 | moduleToObjectTimer.startTimer(); |
| 740 | // Compile to binary. |
| 741 | #if MLIR_ENABLE_NVPTXCOMPILER |
| 742 | result = compileToBinaryNVPTX(*serializedISA); |
| 743 | #else |
| 744 | result = compileToBinary(ptxCode: *serializedISA); |
| 745 | #endif // MLIR_ENABLE_NVPTXCOMPILER |
| 746 | |
| 747 | moduleToObjectTimer.stopTimer(); |
| 748 | isaToBinaryTimeInMs = moduleToObjectTimer.getTotalTime().getWallTime() * 1000; |
| 749 | moduleToObjectTimer.clear(); |
| 750 | return result; |
| 751 | } |
| 752 | |
| 753 | std::optional<mlir::gpu::SerializedObject> |
| 754 | NVVMTargetAttrImpl::serializeToObject(Attribute attribute, Operation *module, |
| 755 | const gpu::TargetOptions &options) const { |
| 756 | Builder builder(attribute.getContext()); |
| 757 | assert(module && "The module must be non null." ); |
| 758 | if (!module) |
| 759 | return std::nullopt; |
| 760 | if (!mlir::isa<gpu::GPUModuleOp>(Val: module)) { |
| 761 | module->emitError(message: "Module must be a GPU module." ); |
| 762 | return std::nullopt; |
| 763 | } |
| 764 | NVPTXSerializer serializer(*module, cast<NVVMTargetAttr>(Val&: attribute), options); |
| 765 | serializer.init(); |
| 766 | std::optional<SmallVector<char, 0>> result = serializer.run(); |
| 767 | if (!result) |
| 768 | return std::nullopt; |
| 769 | |
| 770 | SmallVector<NamedAttribute, 4> properties; |
| 771 | auto llvmToISATimeInMs = serializer.getLLVMIRToISATimeInMs(); |
| 772 | if (llvmToISATimeInMs.has_value()) |
| 773 | properties.push_back(Elt: builder.getNamedAttr( |
| 774 | name: "LLVMIRToISATimeInMs" , val: builder.getI64IntegerAttr(value: *llvmToISATimeInMs))); |
| 775 | auto isaToBinaryTimeInMs = serializer.getISAToBinaryTimeInMs(); |
| 776 | if (isaToBinaryTimeInMs.has_value()) |
| 777 | properties.push_back( |
| 778 | Elt: builder.getNamedAttr(name: "ISAToBinaryTimeInMs" , |
| 779 | val: builder.getI64IntegerAttr(value: *isaToBinaryTimeInMs))); |
| 780 | StringRef isaCompilerLog = serializer.getISACompilerLog(); |
| 781 | if (!isaCompilerLog.empty()) |
| 782 | properties.push_back(Elt: builder.getNamedAttr( |
| 783 | name: "ISACompilerLog" , val: builder.getStringAttr(bytes: isaCompilerLog))); |
| 784 | |
| 785 | return gpu::SerializedObject{std::move(*result), |
| 786 | builder.getDictionaryAttr(value: properties)}; |
| 787 | } |
| 788 | |
| 789 | Attribute |
| 790 | NVVMTargetAttrImpl::createObject(Attribute attribute, Operation *module, |
| 791 | const mlir::gpu::SerializedObject &object, |
| 792 | const gpu::TargetOptions &options) const { |
| 793 | auto target = cast<NVVMTargetAttr>(Val&: attribute); |
| 794 | gpu::CompilationTarget format = options.getCompilationTarget(); |
| 795 | DictionaryAttr objectProps; |
| 796 | Builder builder(attribute.getContext()); |
| 797 | SmallVector<NamedAttribute> properties = |
| 798 | llvm::to_vector(Range: object.getMetadata().getValue()); |
| 799 | if (format == gpu::CompilationTarget::Assembly) |
| 800 | properties.push_back( |
| 801 | Elt: builder.getNamedAttr(name: "O" , val: builder.getI32IntegerAttr(value: target.getO()))); |
| 802 | |
| 803 | if (StringRef section = options.getELFSection(); !section.empty()) |
| 804 | properties.push_back(Elt: builder.getNamedAttr(name: gpu::elfSectionName, |
| 805 | val: builder.getStringAttr(bytes: section))); |
| 806 | |
| 807 | if (!properties.empty()) |
| 808 | objectProps = builder.getDictionaryAttr(value: properties); |
| 809 | |
| 810 | return builder.getAttr<gpu::ObjectAttr>( |
| 811 | args&: attribute, args&: format, |
| 812 | args: builder.getStringAttr( |
| 813 | bytes: StringRef(object.getObject().data(), object.getObject().size())), |
| 814 | args&: objectProps, /*kernels=*/args: nullptr); |
| 815 | } |
| 816 | |