AMDGPUOpenMP.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. //===- AMDGPUOpenMP.cpp - AMDGPUOpenMP ToolChain Implementation -*- 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 "AMDGPUOpenMP.h"
  9. #include "AMDGPU.h"
  10. #include "CommonArgs.h"
  11. #include "ToolChains/ROCm.h"
  12. #include "clang/Basic/DiagnosticDriver.h"
  13. #include "clang/Driver/Compilation.h"
  14. #include "clang/Driver/Driver.h"
  15. #include "clang/Driver/DriverDiagnostic.h"
  16. #include "clang/Driver/InputInfo.h"
  17. #include "clang/Driver/Options.h"
  18. #include "clang/Driver/Tool.h"
  19. #include "llvm/ADT/STLExtras.h"
  20. #include "llvm/Support/FileSystem.h"
  21. #include "llvm/Support/FormatAdapters.h"
  22. #include "llvm/Support/FormatVariadic.h"
  23. #include "llvm/Support/Path.h"
  24. using namespace clang::driver;
  25. using namespace clang::driver::toolchains;
  26. using namespace clang::driver::tools;
  27. using namespace clang;
  28. using namespace llvm::opt;
  29. namespace {
  30. static const char *getOutputFileName(Compilation &C, StringRef Base,
  31. const char *Postfix,
  32. const char *Extension) {
  33. const char *OutputFileName;
  34. if (C.getDriver().isSaveTempsEnabled()) {
  35. OutputFileName =
  36. C.getArgs().MakeArgString(Base.str() + Postfix + "." + Extension);
  37. } else {
  38. std::string TmpName =
  39. C.getDriver().GetTemporaryPath(Base.str() + Postfix, Extension);
  40. OutputFileName = C.addTempFile(C.getArgs().MakeArgString(TmpName));
  41. }
  42. return OutputFileName;
  43. }
  44. static void addLLCOptArg(const llvm::opt::ArgList &Args,
  45. llvm::opt::ArgStringList &CmdArgs) {
  46. if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
  47. StringRef OOpt = "0";
  48. if (A->getOption().matches(options::OPT_O4) ||
  49. A->getOption().matches(options::OPT_Ofast))
  50. OOpt = "3";
  51. else if (A->getOption().matches(options::OPT_O0))
  52. OOpt = "0";
  53. else if (A->getOption().matches(options::OPT_O)) {
  54. // Clang and opt support -Os/-Oz; llc only supports -O0, -O1, -O2 and -O3
  55. // so we map -Os/-Oz to -O2.
  56. // Only clang supports -Og, and maps it to -O1.
  57. // We map anything else to -O2.
  58. OOpt = llvm::StringSwitch<const char *>(A->getValue())
  59. .Case("1", "1")
  60. .Case("2", "2")
  61. .Case("3", "3")
  62. .Case("s", "2")
  63. .Case("z", "2")
  64. .Case("g", "1")
  65. .Default("0");
  66. }
  67. CmdArgs.push_back(Args.MakeArgString("-O" + OOpt));
  68. }
  69. }
  70. static bool checkSystemForAMDGPU(const ArgList &Args, const AMDGPUToolChain &TC,
  71. std::string &GPUArch) {
  72. if (auto Err = TC.getSystemGPUArch(Args, GPUArch)) {
  73. std::string ErrMsg =
  74. llvm::formatv("{0}", llvm::fmt_consume(std::move(Err)));
  75. TC.getDriver().Diag(diag::err_drv_undetermined_amdgpu_arch) << ErrMsg;
  76. return false;
  77. }
  78. return true;
  79. }
  80. } // namespace
  81. const char *AMDGCN::OpenMPLinker::constructLLVMLinkCommand(
  82. const toolchains::AMDGPUOpenMPToolChain &AMDGPUOpenMPTC, Compilation &C,
  83. const JobAction &JA, const InputInfoList &Inputs, const ArgList &Args,
  84. StringRef SubArchName, StringRef OutputFilePrefix) const {
  85. ArgStringList CmdArgs;
  86. for (const auto &II : Inputs)
  87. if (II.isFilename())
  88. CmdArgs.push_back(II.getFilename());
  89. bool HasLibm = false;
  90. if (Args.hasArg(options::OPT_l)) {
  91. auto Lm = Args.getAllArgValues(options::OPT_l);
  92. for (auto &Lib : Lm) {
  93. if (Lib == "m") {
  94. HasLibm = true;
  95. break;
  96. }
  97. }
  98. if (HasLibm) {
  99. // This is not certain to work. The device libs added here, and passed to
  100. // llvm-link, are missing attributes that they expect to be inserted when
  101. // passed to mlink-builtin-bitcode. The amdgpu backend does not generate
  102. // conservatively correct code when attributes are missing, so this may
  103. // be the root cause of miscompilations. Passing via mlink-builtin-bitcode
  104. // ultimately hits CodeGenModule::addDefaultFunctionDefinitionAttributes
  105. // on each function, see D28538 for context.
  106. // Potential workarounds:
  107. // - unconditionally link all of the device libs to every translation
  108. // unit in clang via mlink-builtin-bitcode
  109. // - build a libm bitcode file as part of the DeviceRTL and explictly
  110. // mlink-builtin-bitcode the rocm device libs components at build time
  111. // - drop this llvm-link fork in favour or some calls into LLVM, chosen
  112. // to do basically the same work as llvm-link but with that call first
  113. // - write an opt pass that sets that on every function it sees and pipe
  114. // the device-libs bitcode through that on the way to this llvm-link
  115. SmallVector<std::string, 12> BCLibs =
  116. AMDGPUOpenMPTC.getCommonDeviceLibNames(Args, SubArchName.str());
  117. llvm::for_each(BCLibs, [&](StringRef BCFile) {
  118. CmdArgs.push_back(Args.MakeArgString(BCFile));
  119. });
  120. }
  121. }
  122. AddStaticDeviceLibsLinking(C, *this, JA, Inputs, Args, CmdArgs, "amdgcn",
  123. SubArchName, /*isBitCodeSDL=*/true,
  124. /*postClangLink=*/false);
  125. // Add an intermediate output file.
  126. CmdArgs.push_back("-o");
  127. const char *OutputFileName =
  128. getOutputFileName(C, OutputFilePrefix, "-linked", "bc");
  129. CmdArgs.push_back(OutputFileName);
  130. const char *Exec =
  131. Args.MakeArgString(getToolChain().GetProgramPath("llvm-link"));
  132. C.addCommand(std::make_unique<Command>(
  133. JA, *this, ResponseFileSupport::AtFileCurCP(), Exec, CmdArgs, Inputs,
  134. InputInfo(&JA, Args.MakeArgString(OutputFileName))));
  135. // If we linked in libm definitions late we run another round of optimizations
  136. // to inline the definitions and fold what is foldable.
  137. if (HasLibm) {
  138. ArgStringList OptCmdArgs;
  139. const char *OptOutputFileName =
  140. getOutputFileName(C, OutputFilePrefix, "-linked-opt", "bc");
  141. addLLCOptArg(Args, OptCmdArgs);
  142. OptCmdArgs.push_back(OutputFileName);
  143. OptCmdArgs.push_back("-o");
  144. OptCmdArgs.push_back(OptOutputFileName);
  145. const char *OptExec =
  146. Args.MakeArgString(getToolChain().GetProgramPath("opt"));
  147. C.addCommand(std::make_unique<Command>(
  148. JA, *this, ResponseFileSupport::AtFileCurCP(), OptExec, OptCmdArgs,
  149. InputInfo(&JA, Args.MakeArgString(OutputFileName)),
  150. InputInfo(&JA, Args.MakeArgString(OptOutputFileName))));
  151. OutputFileName = OptOutputFileName;
  152. }
  153. return OutputFileName;
  154. }
  155. const char *AMDGCN::OpenMPLinker::constructLlcCommand(
  156. Compilation &C, const JobAction &JA, const InputInfoList &Inputs,
  157. const llvm::opt::ArgList &Args, llvm::StringRef SubArchName,
  158. llvm::StringRef OutputFilePrefix, const char *InputFileName,
  159. bool OutputIsAsm) const {
  160. // Construct llc command.
  161. ArgStringList LlcArgs;
  162. // The input to llc is the output from opt.
  163. LlcArgs.push_back(InputFileName);
  164. // Pass optimization arg to llc.
  165. addLLCOptArg(Args, LlcArgs);
  166. LlcArgs.push_back("-mtriple=amdgcn-amd-amdhsa");
  167. LlcArgs.push_back(Args.MakeArgString("-mcpu=" + SubArchName));
  168. LlcArgs.push_back(
  169. Args.MakeArgString(Twine("-filetype=") + (OutputIsAsm ? "asm" : "obj")));
  170. for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
  171. LlcArgs.push_back(A->getValue(0));
  172. }
  173. // Add output filename
  174. LlcArgs.push_back("-o");
  175. const char *LlcOutputFile =
  176. getOutputFileName(C, OutputFilePrefix, "", OutputIsAsm ? "s" : "o");
  177. LlcArgs.push_back(LlcOutputFile);
  178. const char *Llc = Args.MakeArgString(getToolChain().GetProgramPath("llc"));
  179. C.addCommand(std::make_unique<Command>(
  180. JA, *this, ResponseFileSupport::AtFileCurCP(), Llc, LlcArgs, Inputs,
  181. InputInfo(&JA, Args.MakeArgString(LlcOutputFile))));
  182. return LlcOutputFile;
  183. }
  184. void AMDGCN::OpenMPLinker::constructLldCommand(
  185. Compilation &C, const JobAction &JA, const InputInfoList &Inputs,
  186. const InputInfo &Output, const llvm::opt::ArgList &Args,
  187. const char *InputFileName) const {
  188. // Construct lld command.
  189. // The output from ld.lld is an HSA code object file.
  190. ArgStringList LldArgs{"-flavor", "gnu", "--no-undefined",
  191. "-shared", "-o", Output.getFilename(),
  192. InputFileName};
  193. const char *Lld = Args.MakeArgString(getToolChain().GetProgramPath("lld"));
  194. C.addCommand(std::make_unique<Command>(
  195. JA, *this, ResponseFileSupport::AtFileCurCP(), Lld, LldArgs, Inputs,
  196. InputInfo(&JA, Args.MakeArgString(Output.getFilename()))));
  197. }
  198. // For amdgcn the inputs of the linker job are device bitcode and output is
  199. // object file. It calls llvm-link, opt, llc, then lld steps.
  200. void AMDGCN::OpenMPLinker::ConstructJob(Compilation &C, const JobAction &JA,
  201. const InputInfo &Output,
  202. const InputInfoList &Inputs,
  203. const ArgList &Args,
  204. const char *LinkingOutput) const {
  205. const ToolChain &TC = getToolChain();
  206. assert(getToolChain().getTriple().isAMDGCN() && "Unsupported target");
  207. const toolchains::AMDGPUOpenMPToolChain &AMDGPUOpenMPTC =
  208. static_cast<const toolchains::AMDGPUOpenMPToolChain &>(TC);
  209. std::string GPUArch = Args.getLastArgValue(options::OPT_march_EQ).str();
  210. if (GPUArch.empty()) {
  211. if (!checkSystemForAMDGPU(Args, AMDGPUOpenMPTC, GPUArch))
  212. return;
  213. }
  214. // Prefix for temporary file name.
  215. std::string Prefix;
  216. for (const auto &II : Inputs)
  217. if (II.isFilename())
  218. Prefix = llvm::sys::path::stem(II.getFilename()).str() + "-" + GPUArch;
  219. assert(Prefix.length() && "no linker inputs are files ");
  220. // Each command outputs different files.
  221. const char *LLVMLinkCommand = constructLLVMLinkCommand(
  222. AMDGPUOpenMPTC, C, JA, Inputs, Args, GPUArch, Prefix);
  223. // Produce readable assembly if save-temps is enabled.
  224. if (C.getDriver().isSaveTempsEnabled())
  225. constructLlcCommand(C, JA, Inputs, Args, GPUArch, Prefix, LLVMLinkCommand,
  226. /*OutputIsAsm=*/true);
  227. const char *LlcCommand = constructLlcCommand(C, JA, Inputs, Args, GPUArch,
  228. Prefix, LLVMLinkCommand);
  229. constructLldCommand(C, JA, Inputs, Output, Args, LlcCommand);
  230. }
  231. AMDGPUOpenMPToolChain::AMDGPUOpenMPToolChain(const Driver &D,
  232. const llvm::Triple &Triple,
  233. const ToolChain &HostTC,
  234. const ArgList &Args)
  235. : ROCMToolChain(D, Triple, Args), HostTC(HostTC) {
  236. // Lookup binaries into the driver directory, this is used to
  237. // discover the clang-offload-bundler executable.
  238. getProgramPaths().push_back(getDriver().Dir);
  239. }
  240. void AMDGPUOpenMPToolChain::addClangTargetOptions(
  241. const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args,
  242. Action::OffloadKind DeviceOffloadingKind) const {
  243. HostTC.addClangTargetOptions(DriverArgs, CC1Args, DeviceOffloadingKind);
  244. std::string GPUArch = DriverArgs.getLastArgValue(options::OPT_march_EQ).str();
  245. if (GPUArch.empty()) {
  246. if (!checkSystemForAMDGPU(DriverArgs, *this, GPUArch))
  247. return;
  248. }
  249. assert(DeviceOffloadingKind == Action::OFK_OpenMP &&
  250. "Only OpenMP offloading kinds are supported.");
  251. CC1Args.push_back("-target-cpu");
  252. CC1Args.push_back(DriverArgs.MakeArgStringRef(GPUArch));
  253. CC1Args.push_back("-fcuda-is-device");
  254. if (DriverArgs.hasArg(options::OPT_nogpulib))
  255. return;
  256. // Link the bitcode library late if we're using device LTO.
  257. if (getDriver().isUsingLTO(/* IsOffload */ true))
  258. return;
  259. std::string BitcodeSuffix;
  260. if (DriverArgs.hasFlag(options::OPT_fopenmp_target_new_runtime,
  261. options::OPT_fno_openmp_target_new_runtime, true))
  262. BitcodeSuffix = "new-amdgpu-" + GPUArch;
  263. else
  264. BitcodeSuffix = "amdgcn-" + GPUArch;
  265. addOpenMPDeviceRTL(getDriver(), DriverArgs, CC1Args, BitcodeSuffix,
  266. getTriple());
  267. }
  268. llvm::opt::DerivedArgList *AMDGPUOpenMPToolChain::TranslateArgs(
  269. const llvm::opt::DerivedArgList &Args, StringRef BoundArch,
  270. Action::OffloadKind DeviceOffloadKind) const {
  271. DerivedArgList *DAL =
  272. HostTC.TranslateArgs(Args, BoundArch, DeviceOffloadKind);
  273. if (!DAL)
  274. DAL = new DerivedArgList(Args.getBaseArgs());
  275. const OptTable &Opts = getDriver().getOpts();
  276. if (DeviceOffloadKind == Action::OFK_OpenMP) {
  277. for (Arg *A : Args)
  278. if (!llvm::is_contained(*DAL, A))
  279. DAL->append(A);
  280. std::string Arch = DAL->getLastArgValue(options::OPT_march_EQ).str();
  281. if (Arch.empty()) {
  282. checkSystemForAMDGPU(Args, *this, Arch);
  283. DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_march_EQ), Arch);
  284. }
  285. return DAL;
  286. }
  287. for (Arg *A : Args) {
  288. DAL->append(A);
  289. }
  290. if (!BoundArch.empty()) {
  291. DAL->eraseArg(options::OPT_march_EQ);
  292. DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_march_EQ),
  293. BoundArch);
  294. }
  295. return DAL;
  296. }
  297. Tool *AMDGPUOpenMPToolChain::buildLinker() const {
  298. assert(getTriple().isAMDGCN());
  299. return new tools::AMDGCN::OpenMPLinker(*this);
  300. }
  301. void AMDGPUOpenMPToolChain::addClangWarningOptions(
  302. ArgStringList &CC1Args) const {
  303. HostTC.addClangWarningOptions(CC1Args);
  304. }
  305. ToolChain::CXXStdlibType
  306. AMDGPUOpenMPToolChain::GetCXXStdlibType(const ArgList &Args) const {
  307. return HostTC.GetCXXStdlibType(Args);
  308. }
  309. void AMDGPUOpenMPToolChain::AddClangSystemIncludeArgs(
  310. const ArgList &DriverArgs, ArgStringList &CC1Args) const {
  311. HostTC.AddClangSystemIncludeArgs(DriverArgs, CC1Args);
  312. }
  313. void AMDGPUOpenMPToolChain::AddIAMCUIncludeArgs(const ArgList &Args,
  314. ArgStringList &CC1Args) const {
  315. HostTC.AddIAMCUIncludeArgs(Args, CC1Args);
  316. }
  317. SanitizerMask AMDGPUOpenMPToolChain::getSupportedSanitizers() const {
  318. // The AMDGPUOpenMPToolChain only supports sanitizers in the sense that it
  319. // allows sanitizer arguments on the command line if they are supported by the
  320. // host toolchain. The AMDGPUOpenMPToolChain will actually ignore any command
  321. // line arguments for any of these "supported" sanitizers. That means that no
  322. // sanitization of device code is actually supported at this time.
  323. //
  324. // This behavior is necessary because the host and device toolchains
  325. // invocations often share the command line, so the device toolchain must
  326. // tolerate flags meant only for the host toolchain.
  327. return HostTC.getSupportedSanitizers();
  328. }
  329. VersionTuple
  330. AMDGPUOpenMPToolChain::computeMSVCVersion(const Driver *D,
  331. const ArgList &Args) const {
  332. return HostTC.computeMSVCVersion(D, Args);
  333. }