clang  8.0.0svn
HIP.cpp
Go to the documentation of this file.
1 //===--- HIP.cpp - HIP Tool and ToolChain Implementations -------*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "HIP.h"
11 #include "CommonArgs.h"
12 #include "InputInfo.h"
13 #include "clang/Basic/Cuda.h"
15 #include "clang/Driver/Driver.h"
17 #include "clang/Driver/Options.h"
18 #include "llvm/Support/FileSystem.h"
19 #include "llvm/Support/Path.h"
20 
21 using namespace clang::driver;
22 using namespace clang::driver::toolchains;
23 using namespace clang::driver::tools;
24 using namespace clang;
25 using namespace llvm::opt;
26 
27 namespace {
28 
29 static void addBCLib(Compilation &C, const ArgList &Args,
30  ArgStringList &CmdArgs, ArgStringList LibraryPaths,
31  StringRef BCName) {
32  StringRef FullName;
33  for (std::string LibraryPath : LibraryPaths) {
34  SmallString<128> Path(LibraryPath);
35  llvm::sys::path::append(Path, BCName);
36  FullName = Path;
37  if (llvm::sys::fs::exists(FullName)) {
38  CmdArgs.push_back(Args.MakeArgString(FullName));
39  return;
40  }
41  }
42  C.getDriver().Diag(diag::err_drv_no_such_file) << BCName;
43 }
44 
45 } // namespace
46 
47 const char *AMDGCN::Linker::constructLLVMLinkCommand(
48  Compilation &C, const JobAction &JA, const InputInfoList &Inputs,
49  const ArgList &Args, StringRef SubArchName,
50  StringRef OutputFilePrefix) const {
51  ArgStringList CmdArgs;
52  // Add the input bc's created by compile step.
53  for (const auto &II : Inputs)
54  CmdArgs.push_back(II.getFilename());
55 
56  ArgStringList LibraryPaths;
57 
58  // Find in --hip-device-lib-path and HIP_LIBRARY_PATH.
59  for (auto Path : Args.getAllArgValues(options::OPT_hip_device_lib_path_EQ))
60  LibraryPaths.push_back(Args.MakeArgString(Path));
61 
62  addDirectoryList(Args, LibraryPaths, "-L", "HIP_DEVICE_LIB_PATH");
63 
65 
66  // Add bitcode library in --hip-device-lib.
67  for (auto Lib : Args.getAllArgValues(options::OPT_hip_device_lib_EQ)) {
68  BCLibs.push_back(Args.MakeArgString(Lib));
69  }
70 
71  // If --hip-device-lib is not set, add the default bitcode libraries.
72  if (BCLibs.empty()) {
73  // Get the bc lib file name for ISA version. For example,
74  // gfx803 => oclc_isa_version_803.amdgcn.bc.
75  std::string ISAVerBC =
76  "oclc_isa_version_" + SubArchName.drop_front(3).str() + ".amdgcn.bc";
77 
78  llvm::StringRef FlushDenormalControlBC;
79  if (Args.hasArg(options::OPT_fcuda_flush_denormals_to_zero))
80  FlushDenormalControlBC = "oclc_daz_opt_on.amdgcn.bc";
81  else
82  FlushDenormalControlBC = "oclc_daz_opt_off.amdgcn.bc";
83 
84  BCLibs.append({"hip.amdgcn.bc", "opencl.amdgcn.bc",
85  "ocml.amdgcn.bc", "ockl.amdgcn.bc",
86  "oclc_finite_only_off.amdgcn.bc",
87  FlushDenormalControlBC,
88  "oclc_correctly_rounded_sqrt_on.amdgcn.bc",
89  "oclc_unsafe_math_off.amdgcn.bc", ISAVerBC});
90  }
91  for (auto Lib : BCLibs)
92  addBCLib(C, Args, CmdArgs, LibraryPaths, Lib);
93 
94  // Add an intermediate output file.
95  CmdArgs.push_back("-o");
96  std::string TmpName =
97  C.getDriver().GetTemporaryPath(OutputFilePrefix.str() + "-linked", "bc");
98  const char *OutputFileName =
99  C.addTempFile(C.getArgs().MakeArgString(TmpName));
100  CmdArgs.push_back(OutputFileName);
101  SmallString<128> ExecPath(C.getDriver().Dir);
102  llvm::sys::path::append(ExecPath, "llvm-link");
103  const char *Exec = Args.MakeArgString(ExecPath);
104  C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
105  return OutputFileName;
106 }
107 
108 const char *AMDGCN::Linker::constructOptCommand(
109  Compilation &C, const JobAction &JA, const InputInfoList &Inputs,
110  const llvm::opt::ArgList &Args, llvm::StringRef SubArchName,
111  llvm::StringRef OutputFilePrefix, const char *InputFileName) const {
112  // Construct opt command.
113  ArgStringList OptArgs;
114  // The input to opt is the output from llvm-link.
115  OptArgs.push_back(InputFileName);
116  // Pass optimization arg to opt.
117  if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
118  StringRef OOpt = "3";
119  if (A->getOption().matches(options::OPT_O4) ||
120  A->getOption().matches(options::OPT_Ofast))
121  OOpt = "3";
122  else if (A->getOption().matches(options::OPT_O0))
123  OOpt = "0";
124  else if (A->getOption().matches(options::OPT_O)) {
125  // -Os, -Oz, and -O(anything else) map to -O2
126  OOpt = llvm::StringSwitch<const char *>(A->getValue())
127  .Case("1", "1")
128  .Case("2", "2")
129  .Case("3", "3")
130  .Case("s", "2")
131  .Case("z", "2")
132  .Default("2");
133  }
134  OptArgs.push_back(Args.MakeArgString("-O" + OOpt));
135  }
136  OptArgs.push_back("-mtriple=amdgcn-amd-amdhsa");
137  OptArgs.push_back(Args.MakeArgString("-mcpu=" + SubArchName));
138  OptArgs.push_back("-o");
139  std::string TmpFileName = C.getDriver().GetTemporaryPath(
140  OutputFilePrefix.str() + "-optimized", "bc");
141  const char *OutputFileName =
142  C.addTempFile(C.getArgs().MakeArgString(TmpFileName));
143  OptArgs.push_back(OutputFileName);
144  SmallString<128> OptPath(C.getDriver().Dir);
145  llvm::sys::path::append(OptPath, "opt");
146  const char *OptExec = Args.MakeArgString(OptPath);
147  C.addCommand(llvm::make_unique<Command>(JA, *this, OptExec, OptArgs, Inputs));
148  return OutputFileName;
149 }
150 
151 const char *AMDGCN::Linker::constructLlcCommand(
152  Compilation &C, const JobAction &JA, const InputInfoList &Inputs,
153  const llvm::opt::ArgList &Args, llvm::StringRef SubArchName,
154  llvm::StringRef OutputFilePrefix, const char *InputFileName) const {
155  // Construct llc command.
156  ArgStringList LlcArgs{InputFileName, "-mtriple=amdgcn-amd-amdhsa",
157  "-filetype=obj", "-mattr=-code-object-v3",
158  Args.MakeArgString("-mcpu=" + SubArchName), "-o"};
159  std::string LlcOutputFileName =
160  C.getDriver().GetTemporaryPath(OutputFilePrefix, "o");
161  const char *LlcOutputFile =
162  C.addTempFile(C.getArgs().MakeArgString(LlcOutputFileName));
163  LlcArgs.push_back(LlcOutputFile);
164  SmallString<128> LlcPath(C.getDriver().Dir);
165  llvm::sys::path::append(LlcPath, "llc");
166  const char *Llc = Args.MakeArgString(LlcPath);
167  C.addCommand(llvm::make_unique<Command>(JA, *this, Llc, LlcArgs, Inputs));
168  return LlcOutputFile;
169 }
170 
171 void AMDGCN::Linker::constructLldCommand(Compilation &C, const JobAction &JA,
172  const InputInfoList &Inputs,
173  const InputInfo &Output,
174  const llvm::opt::ArgList &Args,
175  const char *InputFileName) const {
176  // Construct lld command.
177  // The output from ld.lld is an HSA code object file.
178  ArgStringList LldArgs{"-flavor", "gnu", "--no-undefined",
179  "-shared", "-o", Output.getFilename(),
180  InputFileName};
181  SmallString<128> LldPath(C.getDriver().Dir);
182  llvm::sys::path::append(LldPath, "lld");
183  const char *Lld = Args.MakeArgString(LldPath);
184  C.addCommand(llvm::make_unique<Command>(JA, *this, Lld, LldArgs, Inputs));
185 }
186 
187 // Construct a clang-offload-bundler command to bundle code objects for
188 // different GPU's into a HIP fat binary.
190  StringRef OutputFileName, const InputInfoList &Inputs,
191  const llvm::opt::ArgList &Args, const Tool& T) {
192  // Construct clang-offload-bundler command to bundle object files for
193  // for different GPU archs.
194  ArgStringList BundlerArgs;
195  BundlerArgs.push_back(Args.MakeArgString("-type=o"));
196 
197  // ToDo: Remove the dummy host binary entry which is required by
198  // clang-offload-bundler.
199  std::string BundlerTargetArg = "-targets=host-x86_64-unknown-linux";
200  std::string BundlerInputArg = "-inputs=/dev/null";
201 
202  for (const auto &II : Inputs) {
203  const auto* A = II.getAction();
204  BundlerTargetArg = BundlerTargetArg + ",hip-amdgcn-amd-amdhsa-" +
205  StringRef(A->getOffloadingArch()).str();
206  BundlerInputArg = BundlerInputArg + "," + II.getFilename();
207  }
208  BundlerArgs.push_back(Args.MakeArgString(BundlerTargetArg));
209  BundlerArgs.push_back(Args.MakeArgString(BundlerInputArg));
210 
211  auto BundlerOutputArg =
212  Args.MakeArgString(std::string("-outputs=").append(OutputFileName));
213  BundlerArgs.push_back(BundlerOutputArg);
214 
215  SmallString<128> BundlerPath(C.getDriver().Dir);
216  llvm::sys::path::append(BundlerPath, "clang-offload-bundler");
217  const char *Bundler = Args.MakeArgString(BundlerPath);
218  C.addCommand(llvm::make_unique<Command>(JA, T, Bundler, BundlerArgs, Inputs));
219 }
220 
221 // For amdgcn the inputs of the linker job are device bitcode and output is
222 // object file. It calls llvm-link, opt, llc, then lld steps.
223 void AMDGCN::Linker::ConstructJob(Compilation &C, const JobAction &JA,
224  const InputInfo &Output,
225  const InputInfoList &Inputs,
226  const ArgList &Args,
227  const char *LinkingOutput) const {
228 
229  if (JA.getType() == types::TY_HIP_FATBIN)
230  return constructHIPFatbinCommand(C, JA, Output.getFilename(), Inputs, Args, *this);
231 
232  assert(getToolChain().getTriple().getArch() == llvm::Triple::amdgcn &&
233  "Unsupported target");
234 
235  std::string SubArchName = JA.getOffloadingArch();
236  assert(StringRef(SubArchName).startswith("gfx") && "Unsupported sub arch");
237 
238  // Prefix for temporary file name.
239  std::string Prefix =
240  llvm::sys::path::stem(Inputs[0].getFilename()).str() + "-" + SubArchName;
241 
242  // Each command outputs different files.
243  const char *LLVMLinkCommand =
244  constructLLVMLinkCommand(C, JA, Inputs, Args, SubArchName, Prefix);
245  const char *OptCommand = constructOptCommand(C, JA, Inputs, Args, SubArchName,
246  Prefix, LLVMLinkCommand);
247  const char *LlcCommand =
248  constructLlcCommand(C, JA, Inputs, Args, SubArchName, Prefix, OptCommand);
249  constructLldCommand(C, JA, Inputs, Output, Args, LlcCommand);
250 }
251 
252 HIPToolChain::HIPToolChain(const Driver &D, const llvm::Triple &Triple,
253  const ToolChain &HostTC, const ArgList &Args)
254  : ToolChain(D, Triple, Args), HostTC(HostTC) {
255  // Lookup binaries into the driver directory, this is used to
256  // discover the clang-offload-bundler executable.
257  getProgramPaths().push_back(getDriver().Dir);
258 }
259 
261  const llvm::opt::ArgList &DriverArgs,
262  llvm::opt::ArgStringList &CC1Args,
263  Action::OffloadKind DeviceOffloadingKind) const {
264  HostTC.addClangTargetOptions(DriverArgs, CC1Args, DeviceOffloadingKind);
265 
266  StringRef GpuArch = DriverArgs.getLastArgValue(options::OPT_march_EQ);
267  assert(!GpuArch.empty() && "Must have an explicit GPU arch.");
268  (void) GpuArch;
269  assert(DeviceOffloadingKind == Action::OFK_HIP &&
270  "Only HIP offloading kinds are supported for GPUs.");
271 
272  CC1Args.push_back("-target-cpu");
273  CC1Args.push_back(DriverArgs.MakeArgStringRef(GpuArch));
274  CC1Args.push_back("-fcuda-is-device");
275 
276  if (DriverArgs.hasFlag(options::OPT_fcuda_flush_denormals_to_zero,
277  options::OPT_fno_cuda_flush_denormals_to_zero, false))
278  CC1Args.push_back("-fcuda-flush-denormals-to-zero");
279 
280  if (DriverArgs.hasFlag(options::OPT_fcuda_approx_transcendentals,
281  options::OPT_fno_cuda_approx_transcendentals, false))
282  CC1Args.push_back("-fcuda-approx-transcendentals");
283 
284  if (DriverArgs.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc,
285  false))
286  CC1Args.push_back("-fgpu-rdc");
287 
288  // Default to "hidden" visibility, as object level linking will not be
289  // supported for the foreseeable future.
290  if (!DriverArgs.hasArg(options::OPT_fvisibility_EQ,
291  options::OPT_fvisibility_ms_compat))
292  CC1Args.append({"-fvisibility", "hidden"});
293 }
294 
295 llvm::opt::DerivedArgList *
296 HIPToolChain::TranslateArgs(const llvm::opt::DerivedArgList &Args,
297  StringRef BoundArch,
298  Action::OffloadKind DeviceOffloadKind) const {
299  DerivedArgList *DAL =
300  HostTC.TranslateArgs(Args, BoundArch, DeviceOffloadKind);
301  if (!DAL)
302  DAL = new DerivedArgList(Args.getBaseArgs());
303 
304  const OptTable &Opts = getDriver().getOpts();
305 
306  for (Arg *A : Args) {
307  if (A->getOption().matches(options::OPT_Xarch__)) {
308  // Skip this argument unless the architecture matches BoundArch.
309  if (BoundArch.empty() || A->getValue(0) != BoundArch)
310  continue;
311 
312  unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
313  unsigned Prev = Index;
314  std::unique_ptr<Arg> XarchArg(Opts.ParseOneArg(Args, Index));
315 
316  // If the argument parsing failed or more than one argument was
317  // consumed, the -Xarch_ argument's parameter tried to consume
318  // extra arguments. Emit an error and ignore.
319  //
320  // We also want to disallow any options which would alter the
321  // driver behavior; that isn't going to work in our model. We
322  // use isDriverOption() as an approximation, although things
323  // like -O4 are going to slip through.
324  if (!XarchArg || Index > Prev + 1) {
325  getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args)
326  << A->getAsString(Args);
327  continue;
328  } else if (XarchArg->getOption().hasFlag(options::DriverOption)) {
329  getDriver().Diag(diag::err_drv_invalid_Xarch_argument_isdriver)
330  << A->getAsString(Args);
331  continue;
332  }
333  XarchArg->setBaseArg(A);
334  A = XarchArg.release();
335  DAL->AddSynthesizedArg(A);
336  }
337  DAL->append(A);
338  }
339 
340  if (!BoundArch.empty()) {
341  DAL->eraseArg(options::OPT_march_EQ);
342  DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_march_EQ), BoundArch);
343  }
344 
345  return DAL;
346 }
347 
349  assert(getTriple().getArch() == llvm::Triple::amdgcn);
350  return new tools::AMDGCN::Linker(*this);
351 }
352 
353 void HIPToolChain::addClangWarningOptions(ArgStringList &CC1Args) const {
355 }
356 
358 HIPToolChain::GetCXXStdlibType(const ArgList &Args) const {
359  return HostTC.GetCXXStdlibType(Args);
360 }
361 
362 void HIPToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
363  ArgStringList &CC1Args) const {
364  HostTC.AddClangSystemIncludeArgs(DriverArgs, CC1Args);
365 }
366 
368  ArgStringList &CC1Args) const {
369  HostTC.AddClangCXXStdlibIncludeArgs(Args, CC1Args);
370 }
371 
372 void HIPToolChain::AddIAMCUIncludeArgs(const ArgList &Args,
373  ArgStringList &CC1Args) const {
374  HostTC.AddIAMCUIncludeArgs(Args, CC1Args);
375 }
376 
378  // The HIPToolChain only supports sanitizers in the sense that it allows
379  // sanitizer arguments on the command line if they are supported by the host
380  // toolchain. The HIPToolChain will actually ignore any command line
381  // arguments for any of these "supported" sanitizers. That means that no
382  // sanitization of device code is actually supported at this time.
383  //
384  // This behavior is necessary because the host and device toolchains
385  // invocations often share the command line, so the device toolchain must
386  // tolerate flags meant only for the host toolchain.
388 }
389 
391  const ArgList &Args) const {
392  return HostTC.computeMSVCVersion(D, Args);
393 }
virtual void addClangWarningOptions(llvm::opt::ArgStringList &CC1Args) const
Add warning options that need to be passed to cc1 for this target.
Definition: ToolChain.cpp:651
std::string GetTemporaryPath(StringRef Prefix, StringRef Suffix) const
GetTemporaryPath - Return the pathname of a temporary file to use as part of compilation; the file wi...
Definition: Driver.cpp:4448
void AddClangSystemIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const override
Add the clang cc1 arguments for system include paths.
Definition: HIP.cpp:362
virtual void AddClangCXXStdlibIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
AddClangCXXStdlibIncludeArgs - Add the clang -cc1 level arguments to set the include paths to use for...
Definition: ToolChain.cpp:737
DiagnosticBuilder Diag(unsigned DiagID) const
Definition: Driver.h:109
const char * getFilename() const
Definition: InputInfo.h:84
path_list & getProgramPaths()
Definition: ToolChain.h:226
virtual void AddClangSystemIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
Add the clang cc1 arguments for system include paths.
Definition: ToolChain.cpp:642
std::string Dir
The path the driver executable was in, as invoked from the command line.
Definition: Driver.h:120
SanitizerMask getSupportedSanitizers() const override
Return sanitizers which are available in this toolchain.
Definition: HIP.cpp:377
InputInfo - Wrapper for information about an input source.
Definition: InputInfo.h:23
types::ID getType() const
Definition: Action.h:141
void AddIAMCUIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const override
Add arguments to use MCU GCC toolchain includes.
Definition: HIP.cpp:372
Driver - Encapsulate logic for constructing compilation processes from a set of gcc-driver-like comma...
Definition: Driver.h:58
void addDirectoryList(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, const char *ArgName, const char *EnvVar)
return Out str()
void constructHIPFatbinCommand(Compilation &C, const JobAction &JA, StringRef OutputFileName, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const Tool &T)
Definition: HIP.cpp:189
void AddClangCXXStdlibIncludeArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CC1Args) const override
AddClangCXXStdlibIncludeArgs - Add the clang -cc1 level arguments to set the include paths to use for...
Definition: HIP.cpp:367
void addClangWarningOptions(llvm::opt::ArgStringList &CC1Args) const override
Add warning options that need to be passed to cc1 for this target.
Definition: HIP.cpp:353
void addClangTargetOptions(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, Action::OffloadKind DeviceOffloadKind) const override
Add options that need to be passed to cc1 for this target.
Definition: HIP.cpp:260
virtual VersionTuple computeMSVCVersion(const Driver *D, const llvm::opt::ArgList &Args) const
On Windows, returns the MSVC compatibility version.
Definition: ToolChain.cpp:856
void addCommand(std::unique_ptr< Command > C)
Definition: Compilation.h:206
HIPToolChain(const Driver &D, const llvm::Triple &Triple, const ToolChain &HostTC, const llvm::opt::ArgList &Args)
Definition: HIP.cpp:252
llvm::Triple::ArchType getArch() const
Definition: ToolChain.h:201
const llvm::opt::DerivedArgList & getArgs() const
Definition: Compilation.h:187
llvm::opt::DerivedArgList * TranslateArgs(const llvm::opt::DerivedArgList &Args, StringRef BoundArch, Action::OffloadKind DeviceOffloadKind) const override
TranslateArgs - Create a new derived argument list for any argument translations this ToolChain may w...
Definition: HIP.cpp:296
const Driver & getDriver() const
Definition: ToolChain.h:185
CXXStdlibType GetCXXStdlibType(const llvm::opt::ArgList &Args) const override
Definition: HIP.cpp:358
Dataflow Directional Tag Classes.
Tool - Information on a specific compilation tool.
Definition: Tool.h:34
uint64_t SanitizerMask
Definition: Sanitizers.h:26
Compilation - A set of tasks to perform for a single driver invocation.
Definition: Compilation.h:46
const Driver & getDriver() const
Definition: Compilation.h:134
const llvm::Triple & getTriple() const
Definition: ToolChain.h:187
virtual SanitizerMask getSupportedSanitizers() const
Return sanitizers which are available in this toolchain.
Definition: ToolChain.cpp:814
VersionTuple computeMSVCVersion(const Driver *D, const llvm::opt::ArgList &Args) const override
On Windows, returns the MSVC compatibility version.
Definition: HIP.cpp:390
virtual llvm::opt::DerivedArgList * TranslateArgs(const llvm::opt::DerivedArgList &Args, StringRef BoundArch, Action::OffloadKind DeviceOffloadKind) const
TranslateArgs - Create a new derived argument list for any argument translations this ToolChain may w...
Definition: ToolChain.h:270
const llvm::opt::OptTable & getOpts() const
Definition: Driver.h:296
virtual CXXStdlibType GetCXXStdlibType(const llvm::opt::ArgList &Args) const
Definition: ToolChain.cpp:679
Tool * buildLinker() const override
Definition: HIP.cpp:348
const char * addTempFile(const char *Name)
addTempFile - Add a file to remove on exit, and returns its argument.
Definition: Compilation.h:233
virtual void AddIAMCUIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
Add arguments to use MCU GCC toolchain includes.
Definition: ToolChain.cpp:839
virtual void addClangTargetOptions(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, Action::OffloadKind DeviceOffloadKind) const
Add options that need to be passed to cc1 for this target.
Definition: ToolChain.cpp:647
const char * getOffloadingArch() const
Definition: Action.h:198
ToolChain - Access to tools for a single platform.
Definition: ToolChain.h:88