blob: f55dd2fc04f026df0fc461468515bb2af45fc52a [file] [log] [blame]
Yaxun Liuf6144222018-05-30 00:53:50 +00001//===--- HIP.cpp - HIP Tool and ToolChain Implementations -------*- C++ -*-===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Yaxun Liuf6144222018-05-30 00:53:50 +00006//
7//===----------------------------------------------------------------------===//
8
9#include "HIP.h"
10#include "CommonArgs.h"
11#include "InputInfo.h"
12#include "clang/Basic/Cuda.h"
13#include "clang/Driver/Compilation.h"
14#include "clang/Driver/Driver.h"
15#include "clang/Driver/DriverDiagnostic.h"
16#include "clang/Driver/Options.h"
17#include "llvm/Support/FileSystem.h"
18#include "llvm/Support/Path.h"
19
20using namespace clang::driver;
21using namespace clang::driver::toolchains;
22using namespace clang::driver::tools;
23using namespace clang;
24using namespace llvm::opt;
25
Yaxun Liu4fa83fc2019-01-10 20:09:52 +000026#if _WIN32 || _WIN64
27#define NULL_FILE "nul"
28#else
29#define NULL_FILE "/dev/null"
30#endif
31
Yaxun Liuf6144222018-05-30 00:53:50 +000032namespace {
33
34static void addBCLib(Compilation &C, const ArgList &Args,
35 ArgStringList &CmdArgs, ArgStringList LibraryPaths,
36 StringRef BCName) {
37 StringRef FullName;
38 for (std::string LibraryPath : LibraryPaths) {
39 SmallString<128> Path(LibraryPath);
40 llvm::sys::path::append(Path, BCName);
41 FullName = Path;
42 if (llvm::sys::fs::exists(FullName)) {
43 CmdArgs.push_back(Args.MakeArgString(FullName));
44 return;
45 }
46 }
47 C.getDriver().Diag(diag::err_drv_no_such_file) << BCName;
48}
49
50} // namespace
51
52const char *AMDGCN::Linker::constructLLVMLinkCommand(
53 Compilation &C, const JobAction &JA, const InputInfoList &Inputs,
54 const ArgList &Args, StringRef SubArchName,
55 StringRef OutputFilePrefix) const {
56 ArgStringList CmdArgs;
57 // Add the input bc's created by compile step.
58 for (const auto &II : Inputs)
59 CmdArgs.push_back(II.getFilename());
60
61 ArgStringList LibraryPaths;
62
63 // Find in --hip-device-lib-path and HIP_LIBRARY_PATH.
64 for (auto Path : Args.getAllArgValues(options::OPT_hip_device_lib_path_EQ))
65 LibraryPaths.push_back(Args.MakeArgString(Path));
66
67 addDirectoryList(Args, LibraryPaths, "-L", "HIP_DEVICE_LIB_PATH");
68
69 llvm::SmallVector<std::string, 10> BCLibs;
70
71 // Add bitcode library in --hip-device-lib.
72 for (auto Lib : Args.getAllArgValues(options::OPT_hip_device_lib_EQ)) {
73 BCLibs.push_back(Args.MakeArgString(Lib));
74 }
75
76 // If --hip-device-lib is not set, add the default bitcode libraries.
77 if (BCLibs.empty()) {
78 // Get the bc lib file name for ISA version. For example,
79 // gfx803 => oclc_isa_version_803.amdgcn.bc.
80 std::string ISAVerBC =
81 "oclc_isa_version_" + SubArchName.drop_front(3).str() + ".amdgcn.bc";
82
Aaron Enye Shidfb1bf02018-06-27 18:58:55 +000083 llvm::StringRef FlushDenormalControlBC;
84 if (Args.hasArg(options::OPT_fcuda_flush_denormals_to_zero))
85 FlushDenormalControlBC = "oclc_daz_opt_on.amdgcn.bc";
86 else
87 FlushDenormalControlBC = "oclc_daz_opt_off.amdgcn.bc";
88
Aaron Enye Shie1a353a2018-10-11 19:41:54 +000089 BCLibs.append({"hip.amdgcn.bc", "opencl.amdgcn.bc",
90 "ocml.amdgcn.bc", "ockl.amdgcn.bc",
Yaxun Liuf6144222018-05-30 00:53:50 +000091 "oclc_finite_only_off.amdgcn.bc",
Aaron Enye Shidfb1bf02018-06-27 18:58:55 +000092 FlushDenormalControlBC,
Yaxun Liuf6144222018-05-30 00:53:50 +000093 "oclc_correctly_rounded_sqrt_on.amdgcn.bc",
Aaron Enye Shi5c200be2018-06-26 17:40:36 +000094 "oclc_unsafe_math_off.amdgcn.bc", ISAVerBC});
Yaxun Liuf6144222018-05-30 00:53:50 +000095 }
96 for (auto Lib : BCLibs)
97 addBCLib(C, Args, CmdArgs, LibraryPaths, Lib);
98
99 // Add an intermediate output file.
100 CmdArgs.push_back("-o");
101 std::string TmpName =
102 C.getDriver().GetTemporaryPath(OutputFilePrefix.str() + "-linked", "bc");
103 const char *OutputFileName =
104 C.addTempFile(C.getArgs().MakeArgString(TmpName));
105 CmdArgs.push_back(OutputFileName);
106 SmallString<128> ExecPath(C.getDriver().Dir);
107 llvm::sys::path::append(ExecPath, "llvm-link");
108 const char *Exec = Args.MakeArgString(ExecPath);
109 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
110 return OutputFileName;
111}
112
113const char *AMDGCN::Linker::constructOptCommand(
114 Compilation &C, const JobAction &JA, const InputInfoList &Inputs,
115 const llvm::opt::ArgList &Args, llvm::StringRef SubArchName,
116 llvm::StringRef OutputFilePrefix, const char *InputFileName) const {
117 // Construct opt command.
118 ArgStringList OptArgs;
119 // The input to opt is the output from llvm-link.
120 OptArgs.push_back(InputFileName);
121 // Pass optimization arg to opt.
122 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
123 StringRef OOpt = "3";
124 if (A->getOption().matches(options::OPT_O4) ||
125 A->getOption().matches(options::OPT_Ofast))
126 OOpt = "3";
127 else if (A->getOption().matches(options::OPT_O0))
128 OOpt = "0";
129 else if (A->getOption().matches(options::OPT_O)) {
130 // -Os, -Oz, and -O(anything else) map to -O2
131 OOpt = llvm::StringSwitch<const char *>(A->getValue())
132 .Case("1", "1")
133 .Case("2", "2")
134 .Case("3", "3")
135 .Case("s", "2")
136 .Case("z", "2")
137 .Default("2");
138 }
139 OptArgs.push_back(Args.MakeArgString("-O" + OOpt));
140 }
141 OptArgs.push_back("-mtriple=amdgcn-amd-amdhsa");
142 OptArgs.push_back(Args.MakeArgString("-mcpu=" + SubArchName));
143 OptArgs.push_back("-o");
144 std::string TmpFileName = C.getDriver().GetTemporaryPath(
145 OutputFilePrefix.str() + "-optimized", "bc");
146 const char *OutputFileName =
147 C.addTempFile(C.getArgs().MakeArgString(TmpFileName));
148 OptArgs.push_back(OutputFileName);
149 SmallString<128> OptPath(C.getDriver().Dir);
150 llvm::sys::path::append(OptPath, "opt");
151 const char *OptExec = Args.MakeArgString(OptPath);
152 C.addCommand(llvm::make_unique<Command>(JA, *this, OptExec, OptArgs, Inputs));
153 return OutputFileName;
154}
155
156const char *AMDGCN::Linker::constructLlcCommand(
157 Compilation &C, const JobAction &JA, const InputInfoList &Inputs,
158 const llvm::opt::ArgList &Args, llvm::StringRef SubArchName,
159 llvm::StringRef OutputFilePrefix, const char *InputFileName) const {
160 // Construct llc command.
161 ArgStringList LlcArgs{InputFileName, "-mtriple=amdgcn-amd-amdhsa",
Yaxun Liu9b6d9f22018-10-16 17:36:23 +0000162 "-filetype=obj", "-mattr=-code-object-v3",
Yaxun Liuf6144222018-05-30 00:53:50 +0000163 Args.MakeArgString("-mcpu=" + SubArchName), "-o"};
164 std::string LlcOutputFileName =
165 C.getDriver().GetTemporaryPath(OutputFilePrefix, "o");
166 const char *LlcOutputFile =
167 C.addTempFile(C.getArgs().MakeArgString(LlcOutputFileName));
168 LlcArgs.push_back(LlcOutputFile);
169 SmallString<128> LlcPath(C.getDriver().Dir);
170 llvm::sys::path::append(LlcPath, "llc");
171 const char *Llc = Args.MakeArgString(LlcPath);
172 C.addCommand(llvm::make_unique<Command>(JA, *this, Llc, LlcArgs, Inputs));
173 return LlcOutputFile;
174}
175
176void AMDGCN::Linker::constructLldCommand(Compilation &C, const JobAction &JA,
177 const InputInfoList &Inputs,
178 const InputInfo &Output,
179 const llvm::opt::ArgList &Args,
180 const char *InputFileName) const {
181 // Construct lld command.
182 // The output from ld.lld is an HSA code object file.
183 ArgStringList LldArgs{"-flavor", "gnu", "--no-undefined",
184 "-shared", "-o", Output.getFilename(),
185 InputFileName};
186 SmallString<128> LldPath(C.getDriver().Dir);
187 llvm::sys::path::append(LldPath, "lld");
188 const char *Lld = Args.MakeArgString(LldPath);
189 C.addCommand(llvm::make_unique<Command>(JA, *this, Lld, LldArgs, Inputs));
190}
191
Yaxun Liu97670892018-10-02 17:48:54 +0000192// Construct a clang-offload-bundler command to bundle code objects for
193// different GPU's into a HIP fat binary.
194void AMDGCN::constructHIPFatbinCommand(Compilation &C, const JobAction &JA,
195 StringRef OutputFileName, const InputInfoList &Inputs,
196 const llvm::opt::ArgList &Args, const Tool& T) {
197 // Construct clang-offload-bundler command to bundle object files for
198 // for different GPU archs.
199 ArgStringList BundlerArgs;
200 BundlerArgs.push_back(Args.MakeArgString("-type=o"));
201
202 // ToDo: Remove the dummy host binary entry which is required by
203 // clang-offload-bundler.
204 std::string BundlerTargetArg = "-targets=host-x86_64-unknown-linux";
Yaxun Liu4fa83fc2019-01-10 20:09:52 +0000205 std::string BundlerInputArg = "-inputs=" NULL_FILE;
Yaxun Liu97670892018-10-02 17:48:54 +0000206
207 for (const auto &II : Inputs) {
208 const auto* A = II.getAction();
209 BundlerTargetArg = BundlerTargetArg + ",hip-amdgcn-amd-amdhsa-" +
210 StringRef(A->getOffloadingArch()).str();
211 BundlerInputArg = BundlerInputArg + "," + II.getFilename();
212 }
213 BundlerArgs.push_back(Args.MakeArgString(BundlerTargetArg));
214 BundlerArgs.push_back(Args.MakeArgString(BundlerInputArg));
215
216 auto BundlerOutputArg =
217 Args.MakeArgString(std::string("-outputs=").append(OutputFileName));
218 BundlerArgs.push_back(BundlerOutputArg);
219
220 SmallString<128> BundlerPath(C.getDriver().Dir);
221 llvm::sys::path::append(BundlerPath, "clang-offload-bundler");
222 const char *Bundler = Args.MakeArgString(BundlerPath);
223 C.addCommand(llvm::make_unique<Command>(JA, T, Bundler, BundlerArgs, Inputs));
224}
225
Yaxun Liuf6144222018-05-30 00:53:50 +0000226// For amdgcn the inputs of the linker job are device bitcode and output is
227// object file. It calls llvm-link, opt, llc, then lld steps.
228void AMDGCN::Linker::ConstructJob(Compilation &C, const JobAction &JA,
229 const InputInfo &Output,
230 const InputInfoList &Inputs,
231 const ArgList &Args,
232 const char *LinkingOutput) const {
233
Yaxun Liu97670892018-10-02 17:48:54 +0000234 if (JA.getType() == types::TY_HIP_FATBIN)
235 return constructHIPFatbinCommand(C, JA, Output.getFilename(), Inputs, Args, *this);
236
Sam McCall43fdd222018-05-30 08:03:43 +0000237 assert(getToolChain().getTriple().getArch() == llvm::Triple::amdgcn &&
Yaxun Liuf6144222018-05-30 00:53:50 +0000238 "Unsupported target");
239
240 std::string SubArchName = JA.getOffloadingArch();
241 assert(StringRef(SubArchName).startswith("gfx") && "Unsupported sub arch");
242
243 // Prefix for temporary file name.
244 std::string Prefix =
245 llvm::sys::path::stem(Inputs[0].getFilename()).str() + "-" + SubArchName;
246
247 // Each command outputs different files.
248 const char *LLVMLinkCommand =
249 constructLLVMLinkCommand(C, JA, Inputs, Args, SubArchName, Prefix);
250 const char *OptCommand = constructOptCommand(C, JA, Inputs, Args, SubArchName,
251 Prefix, LLVMLinkCommand);
252 const char *LlcCommand =
253 constructLlcCommand(C, JA, Inputs, Args, SubArchName, Prefix, OptCommand);
254 constructLldCommand(C, JA, Inputs, Output, Args, LlcCommand);
255}
256
257HIPToolChain::HIPToolChain(const Driver &D, const llvm::Triple &Triple,
258 const ToolChain &HostTC, const ArgList &Args)
259 : ToolChain(D, Triple, Args), HostTC(HostTC) {
260 // Lookup binaries into the driver directory, this is used to
261 // discover the clang-offload-bundler executable.
262 getProgramPaths().push_back(getDriver().Dir);
263}
264
265void HIPToolChain::addClangTargetOptions(
266 const llvm::opt::ArgList &DriverArgs,
267 llvm::opt::ArgStringList &CC1Args,
268 Action::OffloadKind DeviceOffloadingKind) const {
269 HostTC.addClangTargetOptions(DriverArgs, CC1Args, DeviceOffloadingKind);
270
271 StringRef GpuArch = DriverArgs.getLastArgValue(options::OPT_march_EQ);
272 assert(!GpuArch.empty() && "Must have an explicit GPU arch.");
Sam McCall43fdd222018-05-30 08:03:43 +0000273 (void) GpuArch;
Yaxun Liuf6144222018-05-30 00:53:50 +0000274 assert(DeviceOffloadingKind == Action::OFK_HIP &&
275 "Only HIP offloading kinds are supported for GPUs.");
276
Yaxun Liu6c3a74e2018-07-24 01:40:44 +0000277 CC1Args.push_back("-target-cpu");
278 CC1Args.push_back(DriverArgs.MakeArgStringRef(GpuArch));
Yaxun Liuf6144222018-05-30 00:53:50 +0000279 CC1Args.push_back("-fcuda-is-device");
280
281 if (DriverArgs.hasFlag(options::OPT_fcuda_flush_denormals_to_zero,
282 options::OPT_fno_cuda_flush_denormals_to_zero, false))
283 CC1Args.push_back("-fcuda-flush-denormals-to-zero");
284
285 if (DriverArgs.hasFlag(options::OPT_fcuda_approx_transcendentals,
286 options::OPT_fno_cuda_approx_transcendentals, false))
287 CC1Args.push_back("-fcuda-approx-transcendentals");
288
Yaxun Liu97670892018-10-02 17:48:54 +0000289 if (DriverArgs.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc,
Yaxun Liuf6144222018-05-30 00:53:50 +0000290 false))
Yaxun Liu97670892018-10-02 17:48:54 +0000291 CC1Args.push_back("-fgpu-rdc");
Yaxun Liu5e98c2b2018-08-30 15:10:20 +0000292
293 // Default to "hidden" visibility, as object level linking will not be
294 // supported for the foreseeable future.
295 if (!DriverArgs.hasArg(options::OPT_fvisibility_EQ,
296 options::OPT_fvisibility_ms_compat))
297 CC1Args.append({"-fvisibility", "hidden"});
Yaxun Liuf6144222018-05-30 00:53:50 +0000298}
299
300llvm::opt::DerivedArgList *
301HIPToolChain::TranslateArgs(const llvm::opt::DerivedArgList &Args,
302 StringRef BoundArch,
303 Action::OffloadKind DeviceOffloadKind) const {
304 DerivedArgList *DAL =
305 HostTC.TranslateArgs(Args, BoundArch, DeviceOffloadKind);
306 if (!DAL)
307 DAL = new DerivedArgList(Args.getBaseArgs());
308
309 const OptTable &Opts = getDriver().getOpts();
310
311 for (Arg *A : Args) {
312 if (A->getOption().matches(options::OPT_Xarch__)) {
Aaron Enye Shi4928d512018-06-26 17:12:29 +0000313 // Skip this argument unless the architecture matches BoundArch.
Yaxun Liuf6144222018-05-30 00:53:50 +0000314 if (BoundArch.empty() || A->getValue(0) != BoundArch)
315 continue;
316
317 unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
318 unsigned Prev = Index;
319 std::unique_ptr<Arg> XarchArg(Opts.ParseOneArg(Args, Index));
320
321 // If the argument parsing failed or more than one argument was
322 // consumed, the -Xarch_ argument's parameter tried to consume
323 // extra arguments. Emit an error and ignore.
324 //
325 // We also want to disallow any options which would alter the
326 // driver behavior; that isn't going to work in our model. We
327 // use isDriverOption() as an approximation, although things
328 // like -O4 are going to slip through.
329 if (!XarchArg || Index > Prev + 1) {
330 getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args)
331 << A->getAsString(Args);
332 continue;
333 } else if (XarchArg->getOption().hasFlag(options::DriverOption)) {
334 getDriver().Diag(diag::err_drv_invalid_Xarch_argument_isdriver)
335 << A->getAsString(Args);
336 continue;
337 }
338 XarchArg->setBaseArg(A);
339 A = XarchArg.release();
340 DAL->AddSynthesizedArg(A);
341 }
342 DAL->append(A);
343 }
344
345 if (!BoundArch.empty()) {
346 DAL->eraseArg(options::OPT_march_EQ);
347 DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_march_EQ), BoundArch);
348 }
349
350 return DAL;
351}
352
353Tool *HIPToolChain::buildLinker() const {
354 assert(getTriple().getArch() == llvm::Triple::amdgcn);
355 return new tools::AMDGCN::Linker(*this);
356}
357
358void HIPToolChain::addClangWarningOptions(ArgStringList &CC1Args) const {
359 HostTC.addClangWarningOptions(CC1Args);
360}
361
362ToolChain::CXXStdlibType
363HIPToolChain::GetCXXStdlibType(const ArgList &Args) const {
364 return HostTC.GetCXXStdlibType(Args);
365}
366
367void HIPToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
368 ArgStringList &CC1Args) const {
369 HostTC.AddClangSystemIncludeArgs(DriverArgs, CC1Args);
370}
371
372void HIPToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &Args,
373 ArgStringList &CC1Args) const {
374 HostTC.AddClangCXXStdlibIncludeArgs(Args, CC1Args);
375}
376
377void HIPToolChain::AddIAMCUIncludeArgs(const ArgList &Args,
378 ArgStringList &CC1Args) const {
379 HostTC.AddIAMCUIncludeArgs(Args, CC1Args);
380}
381
382SanitizerMask HIPToolChain::getSupportedSanitizers() const {
383 // The HIPToolChain only supports sanitizers in the sense that it allows
384 // sanitizer arguments on the command line if they are supported by the host
385 // toolchain. The HIPToolChain will actually ignore any command line
386 // arguments for any of these "supported" sanitizers. That means that no
387 // sanitization of device code is actually supported at this time.
388 //
389 // This behavior is necessary because the host and device toolchains
390 // invocations often share the command line, so the device toolchain must
391 // tolerate flags meant only for the host toolchain.
392 return HostTC.getSupportedSanitizers();
393}
394
395VersionTuple HIPToolChain::computeMSVCVersion(const Driver *D,
396 const ArgList &Args) const {
397 return HostTC.computeMSVCVersion(D, Args);
398}