MLIR 22.0.0git
Target.cpp
Go to the documentation of this file.
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
15
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
47using namespace mlir;
48using namespace mlir::NVVM;
49
50#ifndef __DEFAULT_CUDATOOLKIT_PATH__
51#define __DEFAULT_CUDATOOLKIT_PATH__ ""
52#endif
53
54extern "C" const unsigned char _mlir_embedded_libdevice[];
55extern "C" const unsigned _mlir_embedded_libdevice_size;
56
57namespace {
58// Implementation of the `TargetAttrInterface` model.
59class NVVMTargetAttrImpl
60 : public gpu::TargetAttrInterface::FallbackModel<NVVMTargetAttrImpl> {
61public:
62 std::optional<SmallVector<char, 0>>
63 serializeToObject(Attribute attribute, Operation *module,
64 const gpu::TargetOptions &options) const;
65
66 Attribute createObject(Attribute attribute, Operation *module,
67 const SmallVector<char, 0> &object,
68 const gpu::TargetOptions &options) const;
69};
70} // namespace
71
72// Register the NVVM dialect, the NVVM translation & the target interface.
74 DialectRegistry &registry) {
75 registry.addExtension(+[](MLIRContext *ctx, NVVM::NVVMDialect *dialect) {
76 NVVMTargetAttr::attachInterface<NVVMTargetAttrImpl>(*ctx);
77 });
78}
79
86
87// Search for the CUDA toolkit path.
89 if (const char *var = std::getenv("CUDA_ROOT"))
90 return var;
91 if (const char *var = std::getenv("CUDA_HOME"))
92 return var;
93 if (const char *var = std::getenv("CUDA_PATH"))
94 return var;
96}
97
99 Operation &module, NVVMTargetAttr target,
100 const gpu::TargetOptions &targetOptions)
101 : ModuleToObject(module, target.getTriple(), target.getChip(),
102 target.getFeatures(), target.getO(),
103 targetOptions.getInitialLlvmIRCallback(),
104 targetOptions.getLinkedLlvmIRCallback(),
105 targetOptions.getOptimizedLlvmIRCallback(),
106 targetOptions.getISACallback()),
107 target(target), toolkitPath(targetOptions.getToolkitPath()),
108 librariesToLink(targetOptions.getLibrariesToLink()) {
109
110 // If `targetOptions` have an empty toolkitPath use `getCUDAToolkitPath`
111 if (toolkitPath.empty())
113
114 // Append the files in the target attribute.
115 if (target.getLink())
116 librariesToLink.append(target.getLink().begin(), target.getLink().end());
117
118 // Append libdevice to the files to be loaded.
119 (void)appendStandardLibs();
120}
121
123 static llvm::once_flag initializeBackendOnce;
124 llvm::call_once(initializeBackendOnce, []() {
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
135NVVMTargetAttr SerializeGPUModuleBase::getTarget() const { return target; }
136
138
142
143// Try to append `libdevice` from a CUDA toolkit installation.
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 =
151 IntegerType::get(ctx, 8));
152 auto resourceManager = DenseResourceElementsHandle::getManagerInterface(ctx);
153
154 // Lookup if we already loaded the resource, otherwise create it.
156 resourceManager.getBlobManager().lookup("_mlir_embedded_libdevice");
157 if (blob) {
158 librariesToLink.push_back(DenseResourceElementsAttr::get(
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.
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()) {
176 path.insert(path.begin(), pathRef.begin(), pathRef.end());
177 pathRef = StringRef(path.data(), path.size());
178 if (!llvm::sys::fs::is_directory(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, "nvvm", "libdevice", "libdevice.10.bc");
184 pathRef = StringRef(path.data(), path.size());
185 if (!llvm::sys::fs::is_regular_file(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(StringAttr::get(target.getContext(), pathRef));
191 }
192#endif
193 return success();
194}
195
196std::optional<SmallVector<std::unique_ptr<llvm::Module>>>
199 if (failed(loadBitcodeFilesFromList(module.getContext(), librariesToLink,
200 bcFiles, true)))
201 return std::nullopt;
202 return std::move(bcFiles);
203}
204
205namespace {
206class NVPTXSerializer : public SerializeGPUModuleBase {
207public:
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
235private:
236 using TmpFile = std::pair<llvm::SmallString<128>, llvm::FileRemover>;
237
238 /// Creates a temp file.
239 std::optional<TmpFile> createTemp(StringRef name, StringRef suffix);
240
241 /// Finds the `tool` path, where `tool` is the name of the binary to search,
242 /// i.e. `ptxas` or `fatbinary`. The search order is:
243 /// 1. The toolkit path in `targetOptions`.
244 /// 2. In the system PATH.
245 /// 3. The path from `getCUDAToolkitPath()`.
246 std::optional<std::string> findTool(StringRef tool);
247
248 /// Target options.
249 gpu::TargetOptions targetOptions;
250
251 /// LLVMIR->ISA perf result.
252 std::optional<int64_t> llvmToISATimeInMs;
253
254 /// ISA->Binary perf result.
255 std::optional<int64_t> isaToBinaryTimeInMs;
256};
257} // namespace
258
259NVPTXSerializer::NVPTXSerializer(Operation &module, NVVMTargetAttr target,
260 const gpu::TargetOptions &targetOptions)
261 : SerializeGPUModuleBase(module, target, targetOptions),
262 targetOptions(targetOptions), llvmToISATimeInMs(std::nullopt),
263 isaToBinaryTimeInMs(std::nullopt) {}
264
265std::optional<NVPTXSerializer::TmpFile>
266NVPTXSerializer::createTemp(StringRef name, StringRef suffix) {
267 llvm::SmallString<128> filename;
268 if (name.size() > 80)
269 name = name.substr(0, 80);
270 std::error_code ec =
271 llvm::sys::fs::createTemporaryFile(name, suffix, filename);
272 if (ec) {
273 getOperation().emitError() << "Couldn't create the temp file: `" << filename
274 << "`, error message: " << ec.message();
275 return std::nullopt;
276 }
277 return TmpFile(filename, llvm::FileRemover(filename.c_str()));
278}
279
280std::optional<int64_t> NVPTXSerializer::getLLVMIRToISATimeInMs() {
281 return llvmToISATimeInMs;
282}
283
284std::optional<int64_t> NVPTXSerializer::getISAToBinaryTimeInMs() {
285 return isaToBinaryTimeInMs;
286}
287
288gpu::GPUModuleOp NVPTXSerializer::getOperation() {
289 return dyn_cast<gpu::GPUModuleOp>(&SerializeGPUModuleBase::getOperation());
290}
291
292std::optional<std::string> NVPTXSerializer::findTool(StringRef tool) {
293 // Find the `tool` path.
294 // 1. Check the toolkit path given in the command line.
295 StringRef pathRef = targetOptions.getToolkitPath();
296 SmallVector<char, 256> path;
297 if (!pathRef.empty()) {
298 path.insert(path.begin(), pathRef.begin(), pathRef.end());
299 llvm::sys::path::append(path, "bin", tool);
300 if (llvm::sys::fs::can_execute(path))
301 return StringRef(path.data(), path.size()).str();
302 }
303
304 // 2. Check PATH.
305 if (std::optional<std::string> toolPath =
306 llvm::sys::Process::FindInEnvPath("PATH", tool))
307 return *toolPath;
308
309 // 3. Check `getCUDAToolkitPath()`.
310 pathRef = getCUDAToolkitPath();
311 path.clear();
312 if (!pathRef.empty()) {
313 path.insert(path.begin(), pathRef.begin(), pathRef.end());
314 llvm::sys::path::append(path, "bin", tool);
315 if (llvm::sys::fs::can_execute(path))
316 return StringRef(path.data(), path.size()).str();
317 }
318 getOperation().emitError()
319 << "Couldn't find the `" << tool
320 << "` binary. Please specify the toolkit "
321 "path, add the compiler to $PATH, or set one of the environment "
322 "variables in `NVVM::getCUDAToolkitPath()`.";
323 return std::nullopt;
324}
325
326/// Adds optional command-line arguments to existing arguments.
327template <typename T>
328static void setOptionalCommandlineArguments(NVVMTargetAttr target,
329 SmallVectorImpl<T> &ptxasArgs) {
330 if (!target.hasCmdOptions())
331 return;
332
333 std::optional<mlir::NamedAttribute> cmdOptions = target.getCmdOptions();
334 for (Attribute attr : cast<ArrayAttr>(cmdOptions->getValue())) {
335 if (auto strAttr = dyn_cast<StringAttr>(attr)) {
336 if constexpr (std::is_same_v<T, StringRef>) {
337 ptxasArgs.push_back(strAttr.getValue());
338 } else if constexpr (std::is_same_v<T, const char *>) {
339 ptxasArgs.push_back(strAttr.getValue().data());
340 }
341 }
342 }
343}
344
345// TODO: clean this method & have a generic tool driver or never emit binaries
346// with this mechanism and let another stage take care of it.
347FailureOr<SmallVector<char, 0>>
348NVPTXSerializer::compileToBinary(StringRef ptxCode) {
349 // Determine if the serializer should create a fatbinary with the PTX embeded
350 // or a simple CUBIN binary.
351 const bool createFatbin =
352 targetOptions.getCompilationTarget() == gpu::CompilationTarget::Fatbin;
353
354 // Find the `ptxas` & `fatbinary` tools.
355 std::optional<std::string> ptxasCompiler = findTool("ptxas");
356 if (!ptxasCompiler)
357 return failure();
358 std::optional<std::string> fatbinaryTool;
359 if (createFatbin) {
360 fatbinaryTool = findTool("fatbinary");
361 if (!fatbinaryTool)
362 return failure();
363 }
364 Location loc = getOperation().getLoc();
365
366 // Base name for all temp files: mlir-<module name>-<target triple>-<chip>.
367 std::string basename =
368 llvm::formatv("mlir-{0}-{1}-{2}", getOperation().getNameAttr().getValue(),
369 getTarget().getTriple(), getTarget().getChip());
370
371 // Create temp files:
372 std::optional<TmpFile> ptxFile = createTemp(basename, "ptx");
373 if (!ptxFile)
374 return failure();
375 std::optional<TmpFile> logFile = createTemp(basename, "log");
376 if (!logFile)
377 return failure();
378 std::optional<TmpFile> binaryFile = createTemp(basename, "bin");
379 if (!binaryFile)
380 return failure();
381 TmpFile cubinFile;
382 if (createFatbin) {
383 std::string cubinFilename = (ptxFile->first + ".cubin").str();
384 cubinFile = TmpFile(cubinFilename, llvm::FileRemover(cubinFilename));
385 } else {
386 cubinFile.first = binaryFile->first;
387 }
388
389 std::error_code ec;
390 // Dump the PTX to a temp file.
391 {
392 llvm::raw_fd_ostream ptxStream(ptxFile->first, ec);
393 if (ec)
394 return emitError(loc) << "Couldn't open the file: `" << ptxFile->first
395 << "`, error message: " << ec.message();
396
397 ptxStream << ptxCode;
398 if (ptxStream.has_error())
399 return emitError(loc) << "An error occurred while writing the PTX to: `"
400 << ptxFile->first << "`.";
401
402 ptxStream.flush();
403 }
404
405 // Command redirects.
406 std::optional<StringRef> redirects[] = {
407 std::nullopt,
408 logFile->first,
409 logFile->first,
410 };
411
412 // Get any extra args passed in `targetOptions`.
413 std::pair<llvm::BumpPtrAllocator, SmallVector<const char *>> cmdOpts =
414 targetOptions.tokenizeCmdOptions();
415
416 // Create ptxas args.
417 std::string optLevel = std::to_string(this->optLevel);
418 SmallVector<StringRef, 12> ptxasArgs(
419 {StringRef("ptxas"), StringRef("-arch"), getTarget().getChip(),
420 StringRef(ptxFile->first), StringRef("-o"), StringRef(cubinFile.first),
421 "--opt-level", optLevel});
422
423 bool useFatbin32 = false;
424 for (const auto *cArg : cmdOpts.second) {
425 // All `cmdOpts` are for `ptxas` except `-32` which passes `-32` to
426 // `fatbinary`, indicating a 32-bit target. By default a 64-bit target is
427 // assumed.
428 if (StringRef arg(cArg); arg != "-32")
429 ptxasArgs.push_back(arg);
430 else
431 useFatbin32 = true;
432 }
433
434 // Set optional command line arguments
435 setOptionalCommandlineArguments(getTarget(), ptxasArgs);
436
437 // Create the `fatbinary` args.
438 StringRef chip = getTarget().getChip();
439 // Remove the arch prefix to obtain the compute capability.
440 chip.consume_front("sm_"), chip.consume_front("compute_");
441 // Embed the cubin object.
442 std::string cubinArg =
443 llvm::formatv("--image3=kind=elf,sm={0},file={1}", chip, cubinFile.first)
444 .str();
445 // Embed the PTX file so the driver can JIT if needed.
446 std::string ptxArg =
447 llvm::formatv("--image3=kind=ptx,sm={0},file={1}", chip, ptxFile->first)
448 .str();
449 SmallVector<StringRef, 6> fatbinArgs({StringRef("fatbinary"),
450 useFatbin32 ? "-32" : "-64", cubinArg,
451 ptxArg, "--create", binaryFile->first});
452
453 // Dump tool invocation commands.
454#define DEBUG_TYPE "serialize-to-binary"
455 LDBG() << "Tool invocation for module: " << getOperation().getNameAttr()
456 << "\nptxas executable:" << ptxasCompiler.value()
457 << "\nptxas args: " << llvm::interleaved(ptxasArgs, " ");
458 if (createFatbin)
459 LDBG() << "fatbin args: " << llvm::interleaved(fatbinArgs, " ");
460#undef DEBUG_TYPE
461
462 // Helper function for printing tool error logs.
463 std::string message;
464 auto emitLogError =
465 [&](StringRef toolName) -> FailureOr<SmallVector<char, 0>> {
466 if (message.empty()) {
467 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> toolStderr =
468 llvm::MemoryBuffer::getFile(logFile->first);
469 if (toolStderr)
470 return emitError(loc) << toolName << " invocation failed. Log:\n"
471 << toolStderr->get()->getBuffer();
472 else
473 return emitError(loc) << toolName << " invocation failed.";
474 }
475 return emitError(loc) << toolName
476 << " invocation failed, error message: " << message;
477 };
478
479 // Invoke PTXAS.
480 if (llvm::sys::ExecuteAndWait(ptxasCompiler.value(), ptxasArgs,
481 /*Env=*/std::nullopt,
482 /*Redirects=*/redirects,
483 /*SecondsToWait=*/0,
484 /*MemoryLimit=*/0,
485 /*ErrMsg=*/&message))
486 return emitLogError("`ptxas`");
487#define DEBUG_TYPE "dump-sass"
488 LLVM_DEBUG({
489 std::optional<std::string> nvdisasm = findTool("nvdisasm");
490 SmallVector<StringRef> nvdisasmArgs(
491 {StringRef("nvdisasm"), StringRef(cubinFile.first)});
492 if (llvm::sys::ExecuteAndWait(nvdisasm.value(), nvdisasmArgs,
493 /*Env=*/std::nullopt,
494 /*Redirects=*/redirects,
495 /*SecondsToWait=*/0,
496 /*MemoryLimit=*/0,
497 /*ErrMsg=*/&message))
498 return emitLogError("`nvdisasm`");
499 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> logBuffer =
500 llvm::MemoryBuffer::getFile(logFile->first);
501 if (logBuffer && !(*logBuffer)->getBuffer().empty()) {
502 LDBG() << "Output:\n" << (*logBuffer)->getBuffer();
503 llvm::dbgs().flush();
504 }
505 });
506#undef DEBUG_TYPE
507
508 // Invoke `fatbin`.
509 message.clear();
510 if (createFatbin && llvm::sys::ExecuteAndWait(*fatbinaryTool, fatbinArgs,
511 /*Env=*/std::nullopt,
512 /*Redirects=*/redirects,
513 /*SecondsToWait=*/0,
514 /*MemoryLimit=*/0,
515 /*ErrMsg=*/&message))
516 return emitLogError("`fatbinary`");
517
518// Dump the output of the tools, helpful if the verbose flag was passed.
519#define DEBUG_TYPE "serialize-to-binary"
520 LLVM_DEBUG({
521 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> logBuffer =
522 llvm::MemoryBuffer::getFile(logFile->first);
523 if (logBuffer && !(*logBuffer)->getBuffer().empty()) {
524 LDBG() << "Output:\n" << (*logBuffer)->getBuffer();
525 llvm::dbgs().flush();
526 }
527 });
528#undef DEBUG_TYPE
529
530 // Read the fatbin.
531 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> binaryBuffer =
532 llvm::MemoryBuffer::getFile(binaryFile->first);
533 if (!binaryBuffer)
534 return emitError(loc) << "Couldn't open the file: `" << binaryFile->first
535 << "`, error message: "
536 << binaryBuffer.getError().message();
537
538 StringRef fatbin = (*binaryBuffer)->getBuffer();
539 return SmallVector<char, 0>(fatbin.begin(), fatbin.end());
540}
541
542#if MLIR_ENABLE_NVPTXCOMPILER
543#include "nvPTXCompiler.h"
544
545#define RETURN_ON_NVPTXCOMPILER_ERROR(expr) \
546 do { \
547 if (auto status = (expr)) { \
548 emitError(loc) << llvm::Twine(#expr).concat(" failed with error code ") \
549 << status; \
550 return std::nullopt; \
551 } \
552 } while (false)
553
554#include "nvFatbin.h"
555
556#define RETURN_ON_NVFATBIN_ERROR(expr) \
557 do { \
558 auto result = (expr); \
559 if (result != nvFatbinResult::NVFATBIN_SUCCESS) { \
560 emitError(loc) << llvm::Twine(#expr).concat(" failed with error: ") \
561 << nvFatbinGetErrorString(result); \
562 return std::nullopt; \
563 } \
564 } while (false)
565
566FailureOr<SmallVector<char, 0>>
567NVPTXSerializer::compileToBinaryNVPTX(StringRef ptxCode) {
568 Location loc = getOperation().getLoc();
569 nvPTXCompilerHandle compiler = nullptr;
570 nvPTXCompileResult status;
571 size_t logSize;
572
573 // Create the options.
574 std::string optLevel = std::to_string(this->optLevel);
575 std::pair<llvm::BumpPtrAllocator, SmallVector<const char *>> cmdOpts =
576 targetOptions.tokenizeCmdOptions();
577 cmdOpts.second.append(
578 {"-arch", getTarget().getChip().data(), "--opt-level", optLevel.c_str()});
579
580 // Set optional command line arguments
581 setOptionalCommandlineArguments(getTarget(), cmdOpts.second);
582 // Create the compiler handle.
583 RETURN_ON_NVPTXCOMPILER_ERROR(
584 nvPTXCompilerCreate(&compiler, ptxCode.size(), ptxCode.c_str()));
585
586 // Try to compile the binary.
587 status = nvPTXCompilerCompile(compiler, cmdOpts.second.size(),
588 cmdOpts.second.data());
589
590 // Check if compilation failed.
591 if (status != NVPTXCOMPILE_SUCCESS) {
592 RETURN_ON_NVPTXCOMPILER_ERROR(
593 nvPTXCompilerGetErrorLogSize(compiler, &logSize));
594 if (logSize != 0) {
595 SmallVector<char> log(logSize + 1, 0);
596 RETURN_ON_NVPTXCOMPILER_ERROR(
597 nvPTXCompilerGetErrorLog(compiler, log.data()));
598 return emitError(loc)
599 << "NVPTX compiler invocation failed, error log: " << log.data();
600 } else {
601 return emitError(loc)
602 << "NVPTX compiler invocation failed with error code: " << status;
603 }
604 }
605
606 // Retrieve the binary.
607 size_t elfSize;
608 RETURN_ON_NVPTXCOMPILER_ERROR(
609 nvPTXCompilerGetCompiledProgramSize(compiler, &elfSize));
610 SmallVector<char, 0> binary(elfSize, 0);
611 RETURN_ON_NVPTXCOMPILER_ERROR(
612 nvPTXCompilerGetCompiledProgram(compiler, (void *)binary.data()));
613
614// Dump the log of the compiler, helpful if the verbose flag was passed.
615#define DEBUG_TYPE "serialize-to-binary"
616 LLVM_DEBUG({
617 RETURN_ON_NVPTXCOMPILER_ERROR(
618 nvPTXCompilerGetInfoLogSize(compiler, &logSize));
619 if (logSize != 0) {
620 SmallVector<char> log(logSize + 1, 0);
621 RETURN_ON_NVPTXCOMPILER_ERROR(
622 nvPTXCompilerGetInfoLog(compiler, log.data()));
623 LDBG() << "NVPTX compiler invocation for module: "
624 << getOperation().getNameAttr()
625 << "\nArguments: " << llvm::interleaved(cmdOpts.second, " ")
626 << "\nOutput\n"
627 << log.data();
628 }
629 });
630#undef DEBUG_TYPE
631 RETURN_ON_NVPTXCOMPILER_ERROR(nvPTXCompilerDestroy(&compiler));
632
633 if (targetOptions.getCompilationTarget() == gpu::CompilationTarget::Fatbin) {
634 bool useFatbin32 = llvm::any_of(cmdOpts.second, [](const char *option) {
635 return llvm::StringRef(option) == "-32";
636 });
637
638 const char *cubinOpts[1] = {useFatbin32 ? "-32" : "-64"};
639 nvFatbinHandle handle;
640
641 auto chip = getTarget().getChip();
642 chip.consume_front("sm_");
643
644 RETURN_ON_NVFATBIN_ERROR(nvFatbinCreate(&handle, cubinOpts, 1));
645 RETURN_ON_NVFATBIN_ERROR(nvFatbinAddCubin(
646 handle, binary.data(), binary.size(), chip.data(), nullptr));
647 RETURN_ON_NVFATBIN_ERROR(nvFatbinAddPTX(
648 handle, ptxCode.data(), ptxCode.size(), chip.data(), nullptr, nullptr));
649
650 size_t fatbinSize;
651 RETURN_ON_NVFATBIN_ERROR(nvFatbinSize(handle, &fatbinSize));
652 SmallVector<char, 0> fatbin(fatbinSize, 0);
653 RETURN_ON_NVFATBIN_ERROR(nvFatbinGet(handle, (void *)fatbin.data()));
654 RETURN_ON_NVFATBIN_ERROR(nvFatbinDestroy(&handle));
655 return fatbin;
656 }
657
658 return binary;
659}
660#endif // MLIR_ENABLE_NVPTXCOMPILER
661
662FailureOr<SmallVector<char, 0>>
663NVPTXSerializer::moduleToObject(llvm::Module &llvmModule) {
664 llvm::Timer moduleToObjectTimer(
665 "moduleToObjectTimer",
666 "Timer for perf llvm-ir -> isa and isa -> binary.");
667 auto clear = llvm::make_scope_exit([&]() { moduleToObjectTimer.clear(); });
668 // Return LLVM IR if the compilation target is `offload`.
669#define DEBUG_TYPE "serialize-to-llvm"
670 LLVM_DEBUG({
671 LDBG() << "LLVM IR for module: " << getOperation().getNameAttr();
672 LDBG() << llvmModule;
673 });
674#undef DEBUG_TYPE
675 if (targetOptions.getCompilationTarget() == gpu::CompilationTarget::Offload)
677
678#if !LLVM_HAS_NVPTX_TARGET
679 return getOperation()->emitError(
680 "The `NVPTX` target was not built. Please enable it when building LLVM.");
681#endif // LLVM_HAS_NVPTX_TARGET
682
683 // Emit PTX code.
684 FailureOr<llvm::TargetMachine *> targetMachine = getOrCreateTargetMachine();
685 if (failed(targetMachine))
686 return getOperation().emitError()
687 << "Target Machine unavailable for triple " << triple
688 << ", can't optimize with LLVM\n";
689
690 moduleToObjectTimer.startTimer();
691 FailureOr<SmallString<0>> serializedISA =
692 translateModuleToISA(llvmModule, **targetMachine,
693 [&]() { return getOperation().emitError(); });
694 moduleToObjectTimer.stopTimer();
695 llvmToISATimeInMs = moduleToObjectTimer.getTotalTime().getWallTime() * 1000;
696 moduleToObjectTimer.clear();
697 if (failed(serializedISA))
698 return getOperation().emitError()
699 << "Failed translating the module to ISA.";
700
701 if (isaCallback)
702 isaCallback(*serializedISA);
703
704#define DEBUG_TYPE "serialize-to-isa"
705 LDBG() << "PTX for module: " << getOperation().getNameAttr() << "\n"
706 << *serializedISA;
707#undef DEBUG_TYPE
708
709 // Return PTX if the compilation target is `assembly`.
710 if (targetOptions.getCompilationTarget() == gpu::CompilationTarget::Assembly)
711 return SmallVector<char, 0>(serializedISA->begin(), serializedISA->end());
712
713 FailureOr<SmallVector<char, 0>> result;
714 moduleToObjectTimer.startTimer();
715 // Compile to binary.
716#if MLIR_ENABLE_NVPTXCOMPILER
717 result = compileToBinaryNVPTX(*serializedISA);
718#else
719 result = compileToBinary(*serializedISA);
720#endif // MLIR_ENABLE_NVPTXCOMPILER
721
722 moduleToObjectTimer.stopTimer();
723 isaToBinaryTimeInMs = moduleToObjectTimer.getTotalTime().getWallTime() * 1000;
724 moduleToObjectTimer.clear();
725 return result;
726}
727
728std::optional<SmallVector<char, 0>>
729NVVMTargetAttrImpl::serializeToObject(Attribute attribute, Operation *module,
730 const gpu::TargetOptions &options) const {
731 Builder builder(attribute.getContext());
732 assert(module && "The module must be non null.");
733 if (!module)
734 return std::nullopt;
735 if (!mlir::isa<gpu::GPUModuleOp>(module)) {
736 module->emitError("Module must be a GPU module.");
737 return std::nullopt;
738 }
739 NVPTXSerializer serializer(*module, cast<NVVMTargetAttr>(attribute), options);
740 serializer.init();
741 std::optional<SmallVector<char, 0>> result = serializer.run();
742 auto llvmToISATimeInMs = serializer.getLLVMIRToISATimeInMs();
743 if (llvmToISATimeInMs.has_value())
744 module->setAttr("LLVMIRToISATimeInMs",
745 builder.getI64IntegerAttr(*llvmToISATimeInMs));
746 auto isaToBinaryTimeInMs = serializer.getISAToBinaryTimeInMs();
747 if (isaToBinaryTimeInMs.has_value())
748 module->setAttr("ISAToBinaryTimeInMs",
749 builder.getI64IntegerAttr(*isaToBinaryTimeInMs));
750 return result;
751}
752
753Attribute
754NVVMTargetAttrImpl::createObject(Attribute attribute, Operation *module,
755 const SmallVector<char, 0> &object,
756 const gpu::TargetOptions &options) const {
757 auto target = cast<NVVMTargetAttr>(attribute);
758 gpu::CompilationTarget format = options.getCompilationTarget();
759 DictionaryAttr objectProps;
760 Builder builder(attribute.getContext());
761 SmallVector<NamedAttribute, 4> properties;
762 if (format == gpu::CompilationTarget::Assembly)
763 properties.push_back(
764 builder.getNamedAttr("O", builder.getI32IntegerAttr(target.getO())));
765
766 if (StringRef section = options.getELFSection(); !section.empty())
767 properties.push_back(builder.getNamedAttr(gpu::elfSectionName,
768 builder.getStringAttr(section)));
769
770 for (const auto *perfName : {"LLVMIRToISATimeInMs", "ISAToBinaryTimeInMs"}) {
771 if (module->hasAttr(perfName)) {
772 IntegerAttr attr = llvm::dyn_cast<IntegerAttr>(module->getAttr(perfName));
773 properties.push_back(builder.getNamedAttr(
774 perfName, builder.getI64IntegerAttr(attr.getInt())));
775 }
776 }
777
778 if (!properties.empty())
779 objectProps = builder.getDictionaryAttr(properties);
780
781 return builder.getAttr<gpu::ObjectAttr>(
782 attribute, format,
783 builder.getStringAttr(StringRef(object.data(), object.size())),
784 objectProps, /*kernels=*/nullptr);
785}
return success()
static void setOptionalCommandlineArguments(NVVMTargetAttr target, SmallVectorImpl< T > &ptxasArgs)
Adds optional command-line arguments to existing arguments.
Definition Target.cpp:328
const unsigned _mlir_embedded_libdevice_size
Definition Target.cpp:55
#define __DEFAULT_CUDATOOLKIT_PATH__
Definition Target.cpp:51
const unsigned char _mlir_embedded_libdevice[]
Definition Target.cpp:54
values clear()
static llvm::ManagedStatic< PassManagerOptions > options
Attributes are known-constant values of operations.
Definition Attributes.h:25
MLIRContext * getContext() const
Return the context this attribute belongs to.
The DialectRegistry maps a dialect namespace to a constructor for the matching dialect.
bool addExtension(TypeID extensionID, std::unique_ptr< DialectExtensionBase > extension)
Add the given extension to the registry.
The class represents an individual entry of a blob.
LogicalResult loadBitcodeFilesFromList(llvm::LLVMContext &context, ArrayRef< Attribute > librariesToLink, SmallVector< std::unique_ptr< llvm::Module > > &llvmModules, bool failureOnError=true)
Loads multiple bitcode files.
virtual FailureOr< SmallVector< char, 0 > > moduleToObject(llvm::Module &llvmModule)
Serializes the LLVM IR bitcode to an object file, by default it serializes to LLVM bitcode.
Operation & getOperation()
Returns the operation being serialized.
ModuleToObject(Operation &module, StringRef triple, StringRef chip, StringRef features={}, int optLevel=3, function_ref< void(llvm::Module &)> initialLlvmIRCallback={}, function_ref< void(llvm::Module &)> linkedLlvmIRCallback={}, function_ref< void(llvm::Module &)> optimizedLlvmIRCallback={}, function_ref< void(StringRef)> isaCallback={})
Operation & module
Module to transform to a binary object.
MLIRContext is the top-level object for a collection of MLIR operations.
Definition MLIRContext.h:63
void appendDialectRegistry(const DialectRegistry &registry)
Append the contents of the given dialect registry to the registry associated with this context.
Dialect * getLoadedDialect(StringRef name)
Get a registered IR dialect with the given namespace.
Base class for all NVVM serializations from GPU modules into binary strings.
Definition Utils.h:32
ArrayRef< Attribute > getLibrariesToLink() const
Returns the bitcode libraries to be linked into the gpu module after translation to LLVM IR.
Definition Target.cpp:139
SerializeGPUModuleBase(Operation &module, NVVMTargetAttr target, const gpu::TargetOptions &targetOptions={})
Initializes the toolkitPath with the path in targetOptions or if empty with the path in getCUDAToolki...
Definition Target.cpp:98
NVVMTargetAttr target
NVVM target attribute.
Definition Utils.h:63
std::string toolkitPath
CUDA toolkit path.
Definition Utils.h:66
SmallVector< Attribute > librariesToLink
List of LLVM bitcode to link into after translation to LLVM IR.
Definition Utils.h:71
std::optional< SmallVector< std::unique_ptr< llvm::Module > > > loadBitcodeFiles(llvm::Module &module) override
Loads the bitcode files in librariesToLink.
Definition Target.cpp:197
LogicalResult appendStandardLibs()
Appends nvvm/libdevice.bc into librariesToLink.
Definition Target.cpp:144
static void init()
Initializes the LLVM NVPTX target by safely calling LLVMInitializeNVPTX* methods if available.
Definition Target.cpp:122
StringRef getToolkitPath() const
Returns the CUDA toolkit path.
Definition Target.cpp:137
NVVMTargetAttr getTarget() const
Returns the target attribute.
Definition Target.cpp:135
Operation is the basic unit of execution within MLIR.
Definition Operation.h:88
Attribute getAttr(StringAttr name)
Return the specified attribute if present, null otherwise.
Definition Operation.h:534
bool hasAttr(StringAttr name)
Return true if the operation has an attribute with the provided name, false otherwise.
Definition Operation.h:560
InFlightDiagnostic emitError(const Twine &message={})
Emit an error about fatal conditions with this operation, reporting up to any diagnostic handlers tha...
static AsmResourceBlob allocateInferAlign(ArrayRef< T > data, AsmResourceBlob::DeleterFn deleter={}, bool dataIsMutable=false)
Definition AsmState.h:235
This class serves as an opaque interface for passing options to the TargetAttrInterface methods.
void registerNVVMTargetInterfaceExternalModels(DialectRegistry &registry)
Registers the TargetAttrInterface for the #nvvm.target attribute in the given registry.
Definition Target.cpp:73
StringRef getCUDAToolkitPath()
Searches & returns the path CUDA toolkit path, the search order is:
Definition Target.cpp:88
constexpr StringLiteral elfSectionName
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:573
Include the generated interface declarations.
DialectResourceBlobHandle< BuiltinDialect > DenseResourceElementsHandle
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
static ManagerInterface & getManagerInterface(MLIRContext *ctx)