HIPUtility.cpp 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. //===--- HIPUtility.cpp - Common HIP Tool Chain Utilities -------*- 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. #include "HIPUtility.h"
  9. #include "CommonArgs.h"
  10. #include "clang/Driver/Compilation.h"
  11. #include "llvm/ADT/StringRef.h"
  12. #include "llvm/ADT/Triple.h"
  13. #include "llvm/Support/Path.h"
  14. using namespace clang::driver;
  15. using namespace clang::driver::tools;
  16. using namespace llvm::opt;
  17. #if defined(_WIN32) || defined(_WIN64)
  18. #define NULL_FILE "nul"
  19. #else
  20. #define NULL_FILE "/dev/null"
  21. #endif
  22. namespace {
  23. const unsigned HIPCodeObjectAlign = 4096;
  24. } // namespace
  25. // Constructs a triple string for clang offload bundler.
  26. static std::string normalizeForBundler(const llvm::Triple &T,
  27. bool HasTargetID) {
  28. return HasTargetID ? (T.getArchName() + "-" + T.getVendorName() + "-" +
  29. T.getOSName() + "-" + T.getEnvironmentName())
  30. .str()
  31. : T.normalize();
  32. }
  33. // Construct a clang-offload-bundler command to bundle code objects for
  34. // different devices into a HIP fat binary.
  35. void HIP::constructHIPFatbinCommand(Compilation &C, const JobAction &JA,
  36. llvm::StringRef OutputFileName,
  37. const InputInfoList &Inputs,
  38. const llvm::opt::ArgList &Args,
  39. const Tool &T) {
  40. // Construct clang-offload-bundler command to bundle object files for
  41. // for different GPU archs.
  42. ArgStringList BundlerArgs;
  43. BundlerArgs.push_back(Args.MakeArgString("-type=o"));
  44. BundlerArgs.push_back(
  45. Args.MakeArgString("-bundle-align=" + Twine(HIPCodeObjectAlign)));
  46. // ToDo: Remove the dummy host binary entry which is required by
  47. // clang-offload-bundler.
  48. std::string BundlerTargetArg = "-targets=host-x86_64-unknown-linux";
  49. std::string BundlerInputArg = "-inputs=" NULL_FILE;
  50. // AMDGCN:
  51. // For code object version 2 and 3, the offload kind in bundle ID is 'hip'
  52. // for backward compatibility. For code object version 4 and greater, the
  53. // offload kind in bundle ID is 'hipv4'.
  54. std::string OffloadKind = "hip";
  55. auto &TT = T.getToolChain().getTriple();
  56. if (TT.isAMDGCN() && getAMDGPUCodeObjectVersion(C.getDriver(), Args) >= 4)
  57. OffloadKind = OffloadKind + "v4";
  58. for (const auto &II : Inputs) {
  59. const auto *A = II.getAction();
  60. auto ArchStr = llvm::StringRef(A->getOffloadingArch());
  61. BundlerTargetArg +=
  62. "," + OffloadKind + "-" + normalizeForBundler(TT, !ArchStr.empty());
  63. if (!ArchStr.empty())
  64. BundlerTargetArg += "-" + ArchStr.str();
  65. BundlerInputArg = BundlerInputArg + "," + II.getFilename();
  66. }
  67. BundlerArgs.push_back(Args.MakeArgString(BundlerTargetArg));
  68. BundlerArgs.push_back(Args.MakeArgString(BundlerInputArg));
  69. std::string Output = std::string(OutputFileName);
  70. auto *BundlerOutputArg =
  71. Args.MakeArgString(std::string("-outputs=").append(Output));
  72. BundlerArgs.push_back(BundlerOutputArg);
  73. const char *Bundler = Args.MakeArgString(
  74. T.getToolChain().GetProgramPath("clang-offload-bundler"));
  75. C.addCommand(std::make_unique<Command>(
  76. JA, T, ResponseFileSupport::None(), Bundler, BundlerArgs, Inputs,
  77. InputInfo(&JA, Args.MakeArgString(Output))));
  78. }
  79. /// Add Generated HIP Object File which has device images embedded into the
  80. /// host to the argument list for linking. Using MC directives, embed the
  81. /// device code and also define symbols required by the code generation so that
  82. /// the image can be retrieved at runtime.
  83. void HIP::constructGenerateObjFileFromHIPFatBinary(
  84. Compilation &C, const InputInfo &Output, const InputInfoList &Inputs,
  85. const ArgList &Args, const JobAction &JA, const Tool &T) {
  86. const ToolChain &TC = T.getToolChain();
  87. std::string Name = std::string(llvm::sys::path::stem(Output.getFilename()));
  88. // Create Temp Object File Generator,
  89. // Offload Bundled file and Bundled Object file.
  90. // Keep them if save-temps is enabled.
  91. const char *McinFile;
  92. const char *BundleFile;
  93. if (C.getDriver().isSaveTempsEnabled()) {
  94. McinFile = C.getArgs().MakeArgString(Name + ".mcin");
  95. BundleFile = C.getArgs().MakeArgString(Name + ".hipfb");
  96. } else {
  97. auto TmpNameMcin = C.getDriver().GetTemporaryPath(Name, "mcin");
  98. McinFile = C.addTempFile(C.getArgs().MakeArgString(TmpNameMcin));
  99. auto TmpNameFb = C.getDriver().GetTemporaryPath(Name, "hipfb");
  100. BundleFile = C.addTempFile(C.getArgs().MakeArgString(TmpNameFb));
  101. }
  102. HIP::constructHIPFatbinCommand(C, JA, BundleFile, Inputs, Args, T);
  103. // Create a buffer to write the contents of the temp obj generator.
  104. std::string ObjBuffer;
  105. llvm::raw_string_ostream ObjStream(ObjBuffer);
  106. auto HostTriple =
  107. C.getSingleOffloadToolChain<Action::OFK_Host>()->getTriple();
  108. // Add MC directives to embed target binaries. We ensure that each
  109. // section and image is 16-byte aligned. This is not mandatory, but
  110. // increases the likelihood of data to be aligned with a cache block
  111. // in several main host machines.
  112. ObjStream << "# HIP Object Generator\n";
  113. ObjStream << "# *** Automatically generated by Clang ***\n";
  114. if (HostTriple.isWindowsMSVCEnvironment()) {
  115. ObjStream << " .section .hip_fatbin, \"dw\"\n";
  116. } else {
  117. ObjStream << " .protected __hip_fatbin\n";
  118. ObjStream << " .type __hip_fatbin,@object\n";
  119. ObjStream << " .section .hip_fatbin,\"a\",@progbits\n";
  120. }
  121. ObjStream << " .globl __hip_fatbin\n";
  122. ObjStream << " .p2align " << llvm::Log2(llvm::Align(HIPCodeObjectAlign))
  123. << "\n";
  124. ObjStream << "__hip_fatbin:\n";
  125. ObjStream << " .incbin ";
  126. llvm::sys::printArg(ObjStream, BundleFile, /*Quote=*/true);
  127. ObjStream << "\n";
  128. ObjStream.flush();
  129. // Dump the contents of the temp object file gen if the user requested that.
  130. // We support this option to enable testing of behavior with -###.
  131. if (C.getArgs().hasArg(options::OPT_fhip_dump_offload_linker_script))
  132. llvm::errs() << ObjBuffer;
  133. // Open script file and write the contents.
  134. std::error_code EC;
  135. llvm::raw_fd_ostream Objf(McinFile, EC, llvm::sys::fs::OF_None);
  136. if (EC) {
  137. C.getDriver().Diag(clang::diag::err_unable_to_make_temp) << EC.message();
  138. return;
  139. }
  140. Objf << ObjBuffer;
  141. ArgStringList McArgs{"-triple", Args.MakeArgString(HostTriple.normalize()),
  142. "-o", Output.getFilename(),
  143. McinFile, "--filetype=obj"};
  144. const char *Mc = Args.MakeArgString(TC.GetProgramPath("llvm-mc"));
  145. C.addCommand(std::make_unique<Command>(JA, T, ResponseFileSupport::None(), Mc,
  146. McArgs, Inputs, Output));
  147. }