clang 22.0.0git
AMDGPU.cpp
Go to the documentation of this file.
1//===--- AMDGPU.cpp - AMDGPU ToolChain Implementations ----------*- 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#include "AMDGPU.h"
11#include "clang/Config/config.h"
17#include "llvm/ADT/StringExtras.h"
18#include "llvm/Option/ArgList.h"
19#include "llvm/Support/Error.h"
20#include "llvm/Support/LineIterator.h"
21#include "llvm/Support/Path.h"
22#include "llvm/Support/Process.h"
23#include "llvm/Support/VirtualFileSystem.h"
24#include "llvm/TargetParser/Host.h"
25#include <optional>
26#include <system_error>
27
28using namespace clang::driver;
29using namespace clang::driver::tools;
30using namespace clang::driver::toolchains;
31using namespace clang;
32using namespace llvm::opt;
33
34RocmInstallationDetector::CommonBitcodeLibsPreferences::
35 CommonBitcodeLibsPreferences(const Driver &D,
36 const llvm::opt::ArgList &DriverArgs,
37 StringRef GPUArch,
38 const Action::OffloadKind DeviceOffloadingKind,
39 const bool NeedsASanRT)
40 : ABIVer(DeviceLibABIVersion::fromCodeObjectVersion(
41 tools::getAMDGPUCodeObjectVersion(D, DriverArgs))) {
42 const auto Kind = llvm::AMDGPU::parseArchAMDGCN(GPUArch);
43 const unsigned ArchAttr = llvm::AMDGPU::getArchAttrAMDGCN(Kind);
44
45 IsOpenMP = DeviceOffloadingKind == Action::OFK_OpenMP;
46
47 const bool HasWave32 = (ArchAttr & llvm::AMDGPU::FEATURE_WAVE32);
48 Wave64 =
49 !HasWave32 || DriverArgs.hasFlag(options::OPT_mwavefrontsize64,
50 options::OPT_mno_wavefrontsize64, false);
51
52 const bool IsKnownOffloading = DeviceOffloadingKind == Action::OFK_OpenMP ||
53 DeviceOffloadingKind == Action::OFK_HIP;
54
55 // Default to enabling f32 denormals on subtargets where fma is fast with
56 // denormals
57 const bool DefaultDAZ =
58 (Kind == llvm::AMDGPU::GK_NONE)
59 ? false
60 : !((ArchAttr & llvm::AMDGPU::FEATURE_FAST_FMA_F32) &&
61 (ArchAttr & llvm::AMDGPU::FEATURE_FAST_DENORMAL_F32));
62 // TODO: There are way too many flags that change this. Do we need to
63 // check them all?
64 DAZ = IsKnownOffloading
65 ? DriverArgs.hasFlag(options::OPT_fgpu_flush_denormals_to_zero,
66 options::OPT_fno_gpu_flush_denormals_to_zero,
67 DefaultDAZ)
68 : DriverArgs.hasArg(options::OPT_cl_denorms_are_zero) || DefaultDAZ;
69
70 FiniteOnly = DriverArgs.hasArg(options::OPT_cl_finite_math_only) ||
71 DriverArgs.hasFlag(options::OPT_ffinite_math_only,
72 options::OPT_fno_finite_math_only, false);
73
74 UnsafeMathOpt =
75 DriverArgs.hasArg(options::OPT_cl_unsafe_math_optimizations) ||
76 DriverArgs.hasFlag(options::OPT_funsafe_math_optimizations,
77 options::OPT_fno_unsafe_math_optimizations, false);
78
79 FastRelaxedMath = DriverArgs.hasArg(options::OPT_cl_fast_relaxed_math) ||
80 DriverArgs.hasFlag(options::OPT_ffast_math,
81 options::OPT_fno_fast_math, false);
82
83 const bool DefaultSqrt = IsKnownOffloading ? true : false;
84 CorrectSqrt =
85 DriverArgs.hasArg(options::OPT_cl_fp32_correctly_rounded_divide_sqrt) ||
86 DriverArgs.hasFlag(
87 options::OPT_fhip_fp32_correctly_rounded_divide_sqrt,
88 options::OPT_fno_hip_fp32_correctly_rounded_divide_sqrt, DefaultSqrt);
89 // GPU Sanitizer currently only supports ASan and is enabled through host
90 // ASan.
91 GPUSan = (DriverArgs.hasFlag(options::OPT_fgpu_sanitize,
92 options::OPT_fno_gpu_sanitize, true) &&
93 NeedsASanRT);
94}
95
96void RocmInstallationDetector::scanLibDevicePath(llvm::StringRef Path) {
97 assert(!Path.empty());
98
99 const StringRef Suffix(".bc");
100 const StringRef Suffix2(".amdgcn.bc");
101
102 std::error_code EC;
103 for (llvm::vfs::directory_iterator LI = D.getVFS().dir_begin(Path, EC), LE;
104 !EC && LI != LE; LI = LI.increment(EC)) {
105 StringRef FilePath = LI->path();
106 StringRef FileName = llvm::sys::path::filename(FilePath);
107 if (!FileName.ends_with(Suffix))
108 continue;
109
110 StringRef BaseName;
111 if (FileName.ends_with(Suffix2))
112 BaseName = FileName.drop_back(Suffix2.size());
113 else if (FileName.ends_with(Suffix))
114 BaseName = FileName.drop_back(Suffix.size());
115
116 const StringRef ABIVersionPrefix = "oclc_abi_version_";
117 if (BaseName == "ocml") {
118 OCML = FilePath;
119 } else if (BaseName == "ockl") {
120 OCKL = FilePath;
121 } else if (BaseName == "opencl") {
122 OpenCL = FilePath;
123 } else if (BaseName == "asanrtl") {
124 AsanRTL = FilePath;
125 } else if (BaseName == "oclc_finite_only_off") {
126 FiniteOnly.Off = FilePath;
127 } else if (BaseName == "oclc_finite_only_on") {
128 FiniteOnly.On = FilePath;
129 } else if (BaseName == "oclc_daz_opt_on") {
130 DenormalsAreZero.On = FilePath;
131 } else if (BaseName == "oclc_daz_opt_off") {
132 DenormalsAreZero.Off = FilePath;
133 } else if (BaseName == "oclc_correctly_rounded_sqrt_on") {
134 CorrectlyRoundedSqrt.On = FilePath;
135 } else if (BaseName == "oclc_correctly_rounded_sqrt_off") {
136 CorrectlyRoundedSqrt.Off = FilePath;
137 } else if (BaseName == "oclc_unsafe_math_on") {
138 UnsafeMath.On = FilePath;
139 } else if (BaseName == "oclc_unsafe_math_off") {
140 UnsafeMath.Off = FilePath;
141 } else if (BaseName == "oclc_wavefrontsize64_on") {
142 WavefrontSize64.On = FilePath;
143 } else if (BaseName == "oclc_wavefrontsize64_off") {
144 WavefrontSize64.Off = FilePath;
145 } else if (BaseName.starts_with(ABIVersionPrefix)) {
146 unsigned ABIVersionNumber;
147 if (BaseName.drop_front(ABIVersionPrefix.size())
148 .getAsInteger(/*Redex=*/0, ABIVersionNumber))
149 continue;
150 ABIVersionMap[ABIVersionNumber] = FilePath.str();
151 } else {
152 // Process all bitcode filenames that look like
153 // ocl_isa_version_XXX.amdgcn.bc
154 const StringRef DeviceLibPrefix = "oclc_isa_version_";
155 if (!BaseName.starts_with(DeviceLibPrefix))
156 continue;
157
158 StringRef IsaVersionNumber =
159 BaseName.drop_front(DeviceLibPrefix.size());
160
161 llvm::Twine GfxName = Twine("gfx") + IsaVersionNumber;
162 SmallString<8> Tmp;
163 LibDeviceMap.insert(
164 std::make_pair(GfxName.toStringRef(Tmp), FilePath.str()));
165 }
166 }
167}
168
169// Parse and extract version numbers from `.hipVersion`. Return `true` if
170// the parsing fails.
171bool RocmInstallationDetector::parseHIPVersionFile(llvm::StringRef V) {
172 SmallVector<StringRef, 4> VersionParts;
173 V.split(VersionParts, '\n');
174 unsigned Major = ~0U;
175 unsigned Minor = ~0U;
176 for (auto Part : VersionParts) {
177 auto Splits = Part.rtrim().split('=');
178 if (Splits.first == "HIP_VERSION_MAJOR") {
179 if (Splits.second.getAsInteger(0, Major))
180 return true;
181 } else if (Splits.first == "HIP_VERSION_MINOR") {
182 if (Splits.second.getAsInteger(0, Minor))
183 return true;
184 } else if (Splits.first == "HIP_VERSION_PATCH")
185 VersionPatch = Splits.second.str();
186 }
187 if (Major == ~0U || Minor == ~0U)
188 return true;
189 VersionMajorMinor = llvm::VersionTuple(Major, Minor);
190 DetectedVersion =
191 (Twine(Major) + "." + Twine(Minor) + "." + VersionPatch).str();
192 return false;
193}
194
195/// \returns a list of candidate directories for ROCm installation, which is
196/// cached and populated only once.
198RocmInstallationDetector::getInstallationPathCandidates() {
199
200 // Return the cached candidate list if it has already been populated.
201 if (!ROCmSearchDirs.empty())
202 return ROCmSearchDirs;
203
204 auto DoPrintROCmSearchDirs = [&]() {
205 if (PrintROCmSearchDirs)
206 for (auto Cand : ROCmSearchDirs) {
207 llvm::errs() << "ROCm installation search path: " << Cand.Path << '\n';
208 }
209 };
210
211 // For candidate specified by --rocm-path we do not do strict check, i.e.,
212 // checking existence of HIP version file and device library files.
213 if (!RocmPathArg.empty()) {
214 ROCmSearchDirs.emplace_back(RocmPathArg.str());
215 DoPrintROCmSearchDirs();
216 return ROCmSearchDirs;
217 } else if (std::optional<std::string> RocmPathEnv =
218 llvm::sys::Process::GetEnv("ROCM_PATH")) {
219 if (!RocmPathEnv->empty()) {
220 ROCmSearchDirs.emplace_back(std::move(*RocmPathEnv));
221 DoPrintROCmSearchDirs();
222 return ROCmSearchDirs;
223 }
224 }
225
226 // Try to find relative to the compiler binary.
227 StringRef InstallDir = D.Dir;
228
229 // Check both a normal Unix prefix position of the clang binary, as well as
230 // the Windows-esque layout the ROCm packages use with the host architecture
231 // subdirectory of bin.
232 auto DeduceROCmPath = [](StringRef ClangPath) {
233 // Strip off directory (usually bin)
234 StringRef ParentDir = llvm::sys::path::parent_path(ClangPath);
235 StringRef ParentName = llvm::sys::path::filename(ParentDir);
236
237 // Some builds use bin/{host arch}, so go up again.
238 if (ParentName == "bin") {
239 ParentDir = llvm::sys::path::parent_path(ParentDir);
240 ParentName = llvm::sys::path::filename(ParentDir);
241 }
242
243 // Some versions of the rocm llvm package install to /opt/rocm/llvm/bin
244 // Some versions of the aomp package install to /opt/rocm/aomp/bin
245 if (ParentName == "llvm" || ParentName.starts_with("aomp"))
246 ParentDir = llvm::sys::path::parent_path(ParentDir);
247
248 return Candidate(ParentDir.str(), /*StrictChecking=*/true);
249 };
250
251 // Deduce ROCm path by the path used to invoke clang. Do not resolve symbolic
252 // link of clang itself.
253 ROCmSearchDirs.emplace_back(DeduceROCmPath(InstallDir));
254
255 // Deduce ROCm path by the real path of the invoked clang, resolving symbolic
256 // link of clang itself.
257 llvm::SmallString<256> RealClangPath;
258 llvm::sys::fs::real_path(D.getClangProgramPath(), RealClangPath);
259 auto ParentPath = llvm::sys::path::parent_path(RealClangPath);
260 if (ParentPath != InstallDir)
261 ROCmSearchDirs.emplace_back(DeduceROCmPath(ParentPath));
262
263 // Device library may be installed in clang or resource directory.
264 auto ClangRoot = llvm::sys::path::parent_path(InstallDir);
265 auto RealClangRoot = llvm::sys::path::parent_path(ParentPath);
266 ROCmSearchDirs.emplace_back(ClangRoot.str(), /*StrictChecking=*/true);
267 if (RealClangRoot != ClangRoot)
268 ROCmSearchDirs.emplace_back(RealClangRoot.str(), /*StrictChecking=*/true);
269 ROCmSearchDirs.emplace_back(D.ResourceDir,
270 /*StrictChecking=*/true);
271
272 ROCmSearchDirs.emplace_back(D.SysRoot + "/opt/rocm",
273 /*StrictChecking=*/true);
274
275 // Find the latest /opt/rocm-{release} directory.
276 std::error_code EC;
277 std::string LatestROCm;
278 llvm::VersionTuple LatestVer;
279 // Get ROCm version from ROCm directory name.
280 auto GetROCmVersion = [](StringRef DirName) {
281 llvm::VersionTuple V;
282 std::string VerStr = DirName.drop_front(strlen("rocm-")).str();
283 // The ROCm directory name follows the format of
284 // rocm-{major}.{minor}.{subMinor}[-{build}]
285 llvm::replace(VerStr, '-', '.');
286 V.tryParse(VerStr);
287 return V;
288 };
289 for (llvm::vfs::directory_iterator
290 File = D.getVFS().dir_begin(D.SysRoot + "/opt", EC),
291 FileEnd;
292 File != FileEnd && !EC; File.increment(EC)) {
293 llvm::StringRef FileName = llvm::sys::path::filename(File->path());
294 if (!FileName.starts_with("rocm-"))
295 continue;
296 if (LatestROCm.empty()) {
297 LatestROCm = FileName.str();
298 LatestVer = GetROCmVersion(LatestROCm);
299 continue;
300 }
301 auto Ver = GetROCmVersion(FileName);
302 if (LatestVer < Ver) {
303 LatestROCm = FileName.str();
304 LatestVer = Ver;
305 }
306 }
307 if (!LatestROCm.empty())
308 ROCmSearchDirs.emplace_back(D.SysRoot + "/opt/" + LatestROCm,
309 /*StrictChecking=*/true);
310
311 ROCmSearchDirs.emplace_back(D.SysRoot + "/usr/local",
312 /*StrictChecking=*/true);
313 ROCmSearchDirs.emplace_back(D.SysRoot + "/usr",
314 /*StrictChecking=*/true);
315
316 DoPrintROCmSearchDirs();
317 return ROCmSearchDirs;
318}
319
321 const Driver &D, const llvm::Triple &HostTriple,
322 const llvm::opt::ArgList &Args, bool DetectHIPRuntime, bool DetectDeviceLib)
323 : D(D) {
324 Verbose = Args.hasArg(options::OPT_v);
325 RocmPathArg = Args.getLastArgValue(clang::driver::options::OPT_rocm_path_EQ);
326 PrintROCmSearchDirs =
327 Args.hasArg(clang::driver::options::OPT_print_rocm_search_dirs);
328 RocmDeviceLibPathArg =
329 Args.getAllArgValues(clang::driver::options::OPT_rocm_device_lib_path_EQ);
330 HIPPathArg = Args.getLastArgValue(clang::driver::options::OPT_hip_path_EQ);
331 HIPStdParPathArg =
332 Args.getLastArgValue(clang::driver::options::OPT_hipstdpar_path_EQ);
333 HasHIPStdParLibrary =
334 !HIPStdParPathArg.empty() && D.getVFS().exists(HIPStdParPathArg +
335 "/hipstdpar_lib.hpp");
336 HIPRocThrustPathArg =
337 Args.getLastArgValue(clang::driver::options::OPT_hipstdpar_thrust_path_EQ);
338 HasRocThrustLibrary = !HIPRocThrustPathArg.empty() &&
339 D.getVFS().exists(HIPRocThrustPathArg + "/thrust");
340 HIPRocPrimPathArg =
341 Args.getLastArgValue(clang::driver::options::OPT_hipstdpar_prim_path_EQ);
342 HasRocPrimLibrary = !HIPRocPrimPathArg.empty() &&
343 D.getVFS().exists(HIPRocPrimPathArg + "/rocprim");
344
345 if (auto *A = Args.getLastArg(clang::driver::options::OPT_hip_version_EQ)) {
346 HIPVersionArg = A->getValue();
347 unsigned Major = ~0U;
348 unsigned Minor = ~0U;
350 HIPVersionArg.split(Parts, '.');
351 if (Parts.size())
352 Parts[0].getAsInteger(0, Major);
353 if (Parts.size() > 1)
354 Parts[1].getAsInteger(0, Minor);
355 if (Parts.size() > 2)
356 VersionPatch = Parts[2].str();
357 if (VersionPatch.empty())
358 VersionPatch = "0";
359 if (Major != ~0U && Minor == ~0U)
360 Minor = 0;
361 if (Major == ~0U || Minor == ~0U)
362 D.Diag(diag::err_drv_invalid_value)
363 << A->getAsString(Args) << HIPVersionArg;
364
365 VersionMajorMinor = llvm::VersionTuple(Major, Minor);
366 DetectedVersion =
367 (Twine(Major) + "." + Twine(Minor) + "." + VersionPatch).str();
368 } else {
369 VersionPatch = DefaultVersionPatch;
370 VersionMajorMinor =
371 llvm::VersionTuple(DefaultVersionMajor, DefaultVersionMinor);
372 DetectedVersion = (Twine(DefaultVersionMajor) + "." +
373 Twine(DefaultVersionMinor) + "." + VersionPatch)
374 .str();
375 }
376
377 if (DetectHIPRuntime)
379 if (DetectDeviceLib)
381}
382
384 assert(LibDevicePath.empty());
385
386 if (!RocmDeviceLibPathArg.empty())
387 LibDevicePath = RocmDeviceLibPathArg[RocmDeviceLibPathArg.size() - 1];
388 else if (std::optional<std::string> LibPathEnv =
389 llvm::sys::Process::GetEnv("HIP_DEVICE_LIB_PATH"))
390 LibDevicePath = std::move(*LibPathEnv);
391
392 auto &FS = D.getVFS();
393 if (!LibDevicePath.empty()) {
394 // Maintain compatability with HIP flag/envvar pointing directly at the
395 // bitcode library directory. This points directly at the library path instead
396 // of the rocm root installation.
397 if (!FS.exists(LibDevicePath))
398 return;
399
400 scanLibDevicePath(LibDevicePath);
401 HasDeviceLibrary = allGenericLibsValid() && !LibDeviceMap.empty();
402 return;
403 }
404
405 // Check device library exists at the given path.
406 auto CheckDeviceLib = [&](StringRef Path, bool StrictChecking) {
407 bool CheckLibDevice = (!NoBuiltinLibs || StrictChecking);
408 if (CheckLibDevice && !FS.exists(Path))
409 return false;
410
411 scanLibDevicePath(Path);
412
413 if (!NoBuiltinLibs) {
414 // Check that the required non-target libraries are all available.
415 if (!allGenericLibsValid())
416 return false;
417
418 // Check that we have found at least one libdevice that we can link in
419 // if -nobuiltinlib hasn't been specified.
420 if (LibDeviceMap.empty())
421 return false;
422 }
423 return true;
424 };
425
426 // Find device libraries in <LLVM_DIR>/lib/clang/<ver>/lib/amdgcn/bitcode
427 LibDevicePath = D.ResourceDir;
428 llvm::sys::path::append(LibDevicePath, CLANG_INSTALL_LIBDIR_BASENAME,
429 "amdgcn", "bitcode");
430 HasDeviceLibrary = CheckDeviceLib(LibDevicePath, true);
431 if (HasDeviceLibrary)
432 return;
433
434 // Find device libraries in a legacy ROCm directory structure
435 // ${ROCM_ROOT}/amdgcn/bitcode/*
436 auto &ROCmDirs = getInstallationPathCandidates();
437 for (const auto &Candidate : ROCmDirs) {
438 LibDevicePath = Candidate.Path;
439 llvm::sys::path::append(LibDevicePath, "amdgcn", "bitcode");
440 HasDeviceLibrary = CheckDeviceLib(LibDevicePath, Candidate.StrictChecking);
441 if (HasDeviceLibrary)
442 return;
443 }
444}
445
447 SmallVector<Candidate, 4> HIPSearchDirs;
448 if (!HIPPathArg.empty())
449 HIPSearchDirs.emplace_back(HIPPathArg.str());
450 else if (std::optional<std::string> HIPPathEnv =
451 llvm::sys::Process::GetEnv("HIP_PATH")) {
452 if (!HIPPathEnv->empty())
453 HIPSearchDirs.emplace_back(std::move(*HIPPathEnv));
454 }
455 if (HIPSearchDirs.empty())
456 HIPSearchDirs.append(getInstallationPathCandidates());
457 auto &FS = D.getVFS();
458
459 for (const auto &Candidate : HIPSearchDirs) {
460 InstallPath = Candidate.Path;
461 if (InstallPath.empty() || !FS.exists(InstallPath))
462 continue;
463
464 BinPath = InstallPath;
465 llvm::sys::path::append(BinPath, "bin");
466 IncludePath = InstallPath;
467 llvm::sys::path::append(IncludePath, "include");
468 LibPath = InstallPath;
469 llvm::sys::path::append(LibPath, "lib");
470 SharePath = InstallPath;
471 llvm::sys::path::append(SharePath, "share");
472
473 // Get parent of InstallPath and append "share"
474 SmallString<0> ParentSharePath = llvm::sys::path::parent_path(InstallPath);
475 llvm::sys::path::append(ParentSharePath, "share");
476
477 auto Append = [](SmallString<0> &path, const Twine &a, const Twine &b = "",
478 const Twine &c = "", const Twine &d = "") {
479 SmallString<0> newpath = path;
480 llvm::sys::path::append(newpath, a, b, c, d);
481 return newpath;
482 };
483 // If HIP version file can be found and parsed, use HIP version from there.
484 std::vector<SmallString<0>> VersionFilePaths = {
485 Append(SharePath, "hip", "version"),
486 InstallPath != D.SysRoot + "/usr/local"
487 ? Append(ParentSharePath, "hip", "version")
488 : SmallString<0>(),
489 Append(BinPath, ".hipVersion")};
490
491 for (const auto &VersionFilePath : VersionFilePaths) {
492 if (VersionFilePath.empty())
493 continue;
494 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> VersionFile =
495 FS.getBufferForFile(VersionFilePath);
496 if (!VersionFile)
497 continue;
498 if (HIPVersionArg.empty() && VersionFile)
499 if (parseHIPVersionFile((*VersionFile)->getBuffer()))
500 continue;
501
502 HasHIPRuntime = true;
503 return;
504 }
505 // Otherwise, if -rocm-path is specified (no strict checking), use the
506 // default HIP version or specified by --hip-version.
507 if (!Candidate.StrictChecking) {
508 HasHIPRuntime = true;
509 return;
510 }
511 }
512 HasHIPRuntime = false;
513}
514
515void RocmInstallationDetector::print(raw_ostream &OS) const {
516 if (hasHIPRuntime())
517 OS << "Found HIP installation: " << InstallPath << ", version "
518 << DetectedVersion << '\n';
519}
520
521void RocmInstallationDetector::AddHIPIncludeArgs(const ArgList &DriverArgs,
522 ArgStringList &CC1Args) const {
523 bool UsesRuntimeWrapper = VersionMajorMinor > llvm::VersionTuple(3, 5) &&
524 !DriverArgs.hasArg(options::OPT_nohipwrapperinc);
525 bool HasHipStdPar = DriverArgs.hasArg(options::OPT_hipstdpar);
526
527 if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
528 // HIP header includes standard library wrapper headers under clang
529 // cuda_wrappers directory. Since these wrapper headers include_next
530 // standard C++ headers, whereas libc++ headers include_next other clang
531 // headers. The include paths have to follow this order:
532 // - wrapper include path
533 // - standard C++ include path
534 // - other clang include path
535 // Since standard C++ and other clang include paths are added in other
536 // places after this function, here we only need to make sure wrapper
537 // include path is added.
538 //
539 // ROCm 3.5 does not fully support the wrapper headers. Therefore it needs
540 // a workaround.
541 SmallString<128> P(D.ResourceDir);
542 if (UsesRuntimeWrapper)
543 llvm::sys::path::append(P, "include", "cuda_wrappers");
544 CC1Args.push_back("-internal-isystem");
545 CC1Args.push_back(DriverArgs.MakeArgString(P));
546 }
547
548 const auto HandleHipStdPar = [=, &DriverArgs, &CC1Args]() {
549 StringRef Inc = getIncludePath();
550 auto &FS = D.getVFS();
551
552 if (!hasHIPStdParLibrary())
553 if (!HIPStdParPathArg.empty() ||
554 !FS.exists(Inc + "/thrust/system/hip/hipstdpar/hipstdpar_lib.hpp")) {
555 D.Diag(diag::err_drv_no_hipstdpar_lib);
556 return;
557 }
558 if (!HasRocThrustLibrary && !FS.exists(Inc + "/thrust")) {
559 D.Diag(diag::err_drv_no_hipstdpar_thrust_lib);
560 return;
561 }
562 if (!HasRocPrimLibrary && !FS.exists(Inc + "/rocprim")) {
563 D.Diag(diag::err_drv_no_hipstdpar_prim_lib);
564 return;
565 }
566 const char *ThrustPath;
567 if (HasRocThrustLibrary)
568 ThrustPath = DriverArgs.MakeArgString(HIPRocThrustPathArg);
569 else
570 ThrustPath = DriverArgs.MakeArgString(Inc + "/thrust");
571
572 const char *HIPStdParPath;
574 HIPStdParPath = DriverArgs.MakeArgString(HIPStdParPathArg);
575 else
576 HIPStdParPath = DriverArgs.MakeArgString(StringRef(ThrustPath) +
577 "/system/hip/hipstdpar");
578
579 const char *PrimPath;
580 if (HasRocPrimLibrary)
581 PrimPath = DriverArgs.MakeArgString(HIPRocPrimPathArg);
582 else
583 PrimPath = DriverArgs.MakeArgString(getIncludePath() + "/rocprim");
584
585 CC1Args.append({"-idirafter", ThrustPath, "-idirafter", PrimPath,
586 "-idirafter", HIPStdParPath, "-include",
587 "hipstdpar_lib.hpp"});
588 };
589
590 if (!DriverArgs.hasFlag(options::OPT_offload_inc, options::OPT_no_offload_inc,
591 true)) {
592 if (HasHipStdPar)
593 HandleHipStdPar();
594
595 return;
596 }
597
598 if (!hasHIPRuntime()) {
599 D.Diag(diag::err_drv_no_hip_runtime);
600 return;
601 }
602
603 CC1Args.push_back("-idirafter");
604 CC1Args.push_back(DriverArgs.MakeArgString(getIncludePath()));
605 if (UsesRuntimeWrapper)
606 CC1Args.append({"-include", "__clang_hip_runtime_wrapper.h"});
607 if (HasHipStdPar)
608 HandleHipStdPar();
609}
610
612 const InputInfo &Output,
613 const InputInfoList &Inputs,
614 const ArgList &Args,
615 const char *LinkingOutput) const {
616 std::string Linker = getToolChain().GetLinkerPath();
617 ArgStringList CmdArgs;
618 if (!Args.hasArg(options::OPT_r)) {
619 CmdArgs.push_back("--no-undefined");
620 CmdArgs.push_back("-shared");
621 }
622
623 if (C.getDriver().isUsingLTO()) {
624 const bool ThinLTO = (C.getDriver().getLTOMode() == LTOK_Thin);
625 addLTOOptions(getToolChain(), Args, CmdArgs, Output, Inputs, ThinLTO);
626 } else if (Args.hasArg(options::OPT_mcpu_EQ)) {
627 CmdArgs.push_back(Args.MakeArgString(
628 "-plugin-opt=mcpu=" +
629 getProcessorFromTargetID(getToolChain().getTriple(),
630 Args.getLastArgValue(options::OPT_mcpu_EQ))));
631 }
632 addLinkerCompressDebugSectionsOption(getToolChain(), Args, CmdArgs);
633 getToolChain().AddFilePathLibArgs(Args, CmdArgs);
634 Args.AddAllArgs(CmdArgs, options::OPT_L);
635 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs, JA);
636
637 // Always pass the target-id features to the LTO job.
638 std::vector<StringRef> Features;
639 getAMDGPUTargetFeatures(C.getDriver(), getToolChain().getTriple(), Args,
640 Features);
641 if (!Features.empty()) {
642 CmdArgs.push_back(
643 Args.MakeArgString("-plugin-opt=-mattr=" + llvm::join(Features, ",")));
644 }
645
646 if (Args.hasArg(options::OPT_stdlib))
647 CmdArgs.append({"-lc", "-lm"});
648 if (Args.hasArg(options::OPT_startfiles)) {
649 std::optional<std::string> IncludePath = getToolChain().getStdlibPath();
650 if (!IncludePath)
651 IncludePath = "/lib";
652 SmallString<128> P(*IncludePath);
653 llvm::sys::path::append(P, "crt1.o");
654 CmdArgs.push_back(Args.MakeArgString(P));
655 }
656
657 CmdArgs.push_back("-o");
658 CmdArgs.push_back(Output.getFilename());
659 C.addCommand(std::make_unique<Command>(
660 JA, *this, ResponseFileSupport::AtFileCurCP(), Args.MakeArgString(Linker),
661 CmdArgs, Inputs, Output));
662}
663
665 const llvm::Triple &Triple,
666 const llvm::opt::ArgList &Args,
667 std::vector<StringRef> &Features) {
668 // Add target ID features to -target-feature options. No diagnostics should
669 // be emitted here since invalid target ID is diagnosed at other places.
670 StringRef TargetID;
671 if (Args.hasArg(options::OPT_mcpu_EQ))
672 TargetID = Args.getLastArgValue(options::OPT_mcpu_EQ);
673 else if (Args.hasArg(options::OPT_march_EQ))
674 TargetID = Args.getLastArgValue(options::OPT_march_EQ);
675 if (!TargetID.empty()) {
676 llvm::StringMap<bool> FeatureMap;
677 auto OptionalGpuArch = parseTargetID(Triple, TargetID, &FeatureMap);
678 if (OptionalGpuArch) {
679 StringRef GpuArch = *OptionalGpuArch;
680 // Iterate through all possible target ID features for the given GPU.
681 // If it is mapped to true, add +feature.
682 // If it is mapped to false, add -feature.
683 // If it is not in the map (default), do not add it
684 for (auto &&Feature : getAllPossibleTargetIDFeatures(Triple, GpuArch)) {
685 auto Pos = FeatureMap.find(Feature);
686 if (Pos == FeatureMap.end())
687 continue;
688 Features.push_back(Args.MakeArgStringRef(
689 (Twine(Pos->second ? "+" : "-") + Feature).str()));
690 }
691 }
692 }
693
694 if (Args.hasFlag(options::OPT_mwavefrontsize64,
695 options::OPT_mno_wavefrontsize64, false))
696 Features.push_back("+wavefrontsize64");
697
698 if (Args.hasFlag(options::OPT_mamdgpu_precise_memory_op,
699 options::OPT_mno_amdgpu_precise_memory_op, false))
700 Features.push_back("+precise-memory");
701
702 handleTargetFeaturesGroup(D, Triple, Args, Features,
703 options::OPT_m_amdgpu_Features_Group);
704}
705
706/// AMDGPU Toolchain
707AMDGPUToolChain::AMDGPUToolChain(const Driver &D, const llvm::Triple &Triple,
708 const ArgList &Args)
709 : Generic_ELF(D, Triple, Args),
710 OptionsDefault(
711 {{options::OPT_O, "3"}, {options::OPT_cl_std_EQ, "CL1.2"}}) {
712 // Check code object version options. Emit warnings for legacy options
713 // and errors for the last invalid code object version options.
714 // It is done here to avoid repeated warning or error messages for
715 // each tool invocation.
717}
718
720 return new tools::amdgpu::Linker(*this);
721}
722
723DerivedArgList *
724AMDGPUToolChain::TranslateArgs(const DerivedArgList &Args, StringRef BoundArch,
725 Action::OffloadKind DeviceOffloadKind) const {
726
727 DerivedArgList *DAL =
728 Generic_ELF::TranslateArgs(Args, BoundArch, DeviceOffloadKind);
729
730 const OptTable &Opts = getDriver().getOpts();
731
732 if (!DAL)
733 DAL = new DerivedArgList(Args.getBaseArgs());
734
735 for (Arg *A : Args)
736 DAL->append(A);
737
738 // Replace -mcpu=native with detected GPU.
739 Arg *LastMCPUArg = DAL->getLastArg(options::OPT_mcpu_EQ);
740 if (LastMCPUArg && StringRef(LastMCPUArg->getValue()) == "native") {
741 DAL->eraseArg(options::OPT_mcpu_EQ);
742 auto GPUsOrErr = getSystemGPUArchs(Args);
743 if (!GPUsOrErr) {
744 getDriver().Diag(diag::err_drv_undetermined_gpu_arch)
745 << llvm::Triple::getArchTypeName(getArch())
746 << llvm::toString(GPUsOrErr.takeError()) << "-mcpu";
747 } else {
748 auto &GPUs = *GPUsOrErr;
749 if (GPUs.size() > 1) {
750 getDriver().Diag(diag::warn_drv_multi_gpu_arch)
751 << llvm::Triple::getArchTypeName(getArch())
752 << llvm::join(GPUs, ", ") << "-mcpu";
753 }
754 DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_mcpu_EQ),
755 Args.MakeArgString(GPUs.front()));
756 }
757 }
758
759 checkTargetID(*DAL);
760
761 if (Args.getLastArgValue(options::OPT_x) != "cl")
762 return DAL;
763
764 // Phase 1 (.cl -> .bc)
765 if (Args.hasArg(options::OPT_c) && Args.hasArg(options::OPT_emit_llvm)) {
766 DAL->AddFlagArg(nullptr, Opts.getOption(getTriple().isArch64Bit()
767 ? options::OPT_m64
768 : options::OPT_m32));
769
770 // Have to check OPT_O4, OPT_O0 & OPT_Ofast separately
771 // as they defined that way in Options.td
772 if (!Args.hasArg(options::OPT_O, options::OPT_O0, options::OPT_O4,
773 options::OPT_Ofast))
774 DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_O),
775 getOptionDefault(options::OPT_O));
776 }
777
778 return DAL;
779}
780
782 llvm::AMDGPU::GPUKind Kind) {
783
784 // Assume nothing without a specific target.
785 if (Kind == llvm::AMDGPU::GK_NONE)
786 return false;
787
788 const unsigned ArchAttr = llvm::AMDGPU::getArchAttrAMDGCN(Kind);
789
790 // Default to enabling f32 denormals by default on subtargets where fma is
791 // fast with denormals
792 const bool BothDenormAndFMAFast =
793 (ArchAttr & llvm::AMDGPU::FEATURE_FAST_FMA_F32) &&
794 (ArchAttr & llvm::AMDGPU::FEATURE_FAST_DENORMAL_F32);
795 return !BothDenormAndFMAFast;
796}
797
799 const llvm::opt::ArgList &DriverArgs, const JobAction &JA,
800 const llvm::fltSemantics *FPType) const {
801 // Denormals should always be enabled for f16 and f64.
802 if (!FPType || FPType != &llvm::APFloat::IEEEsingle())
803 return llvm::DenormalMode::getIEEE();
804
808 auto Kind = llvm::AMDGPU::parseArchAMDGCN(Arch);
809 if (FPType && FPType == &llvm::APFloat::IEEEsingle() &&
810 DriverArgs.hasFlag(options::OPT_fgpu_flush_denormals_to_zero,
811 options::OPT_fno_gpu_flush_denormals_to_zero,
813 return llvm::DenormalMode::getPreserveSign();
814
815 return llvm::DenormalMode::getIEEE();
816 }
817
818 const StringRef GpuArch = getGPUArch(DriverArgs);
819 auto Kind = llvm::AMDGPU::parseArchAMDGCN(GpuArch);
820
821 // TODO: There are way too many flags that change this. Do we need to check
822 // them all?
823 bool DAZ = DriverArgs.hasArg(options::OPT_cl_denorms_are_zero) ||
825
826 // Outputs are flushed to zero (FTZ), preserving sign. Denormal inputs are
827 // also implicit treated as zero (DAZ).
828 return DAZ ? llvm::DenormalMode::getPreserveSign() :
829 llvm::DenormalMode::getIEEE();
830}
831
832bool AMDGPUToolChain::isWave64(const llvm::opt::ArgList &DriverArgs,
833 llvm::AMDGPU::GPUKind Kind) {
834 const unsigned ArchAttr = llvm::AMDGPU::getArchAttrAMDGCN(Kind);
835 bool HasWave32 = (ArchAttr & llvm::AMDGPU::FEATURE_WAVE32);
836
837 return !HasWave32 || DriverArgs.hasFlag(
838 options::OPT_mwavefrontsize64, options::OPT_mno_wavefrontsize64, false);
839}
840
841
842/// ROCM Toolchain
843ROCMToolChain::ROCMToolChain(const Driver &D, const llvm::Triple &Triple,
844 const ArgList &Args)
845 : AMDGPUToolChain(D, Triple, Args) {
846 RocmInstallation->detectDeviceLibrary();
847}
848
850 const llvm::opt::ArgList &DriverArgs,
851 llvm::opt::ArgStringList &CC1Args,
852 Action::OffloadKind DeviceOffloadingKind) const {
853 // Default to "hidden" visibility, as object level linking will not be
854 // supported for the foreseeable future.
855 if (!DriverArgs.hasArg(options::OPT_fvisibility_EQ,
856 options::OPT_fvisibility_ms_compat)) {
857 CC1Args.push_back("-fvisibility=hidden");
858 CC1Args.push_back("-fapply-global-visibility-to-externs");
859 }
860
861 if (DeviceOffloadingKind == Action::OFK_None)
862 addOpenCLBuiltinsLib(getDriver(), DriverArgs, CC1Args);
863}
864
865void AMDGPUToolChain::addClangWarningOptions(ArgStringList &CC1Args) const {
866 // AMDGPU does not support atomic lib call. Treat atomic alignment
867 // warnings as errors.
868 CC1Args.push_back("-Werror=atomic-alignment");
869}
870
871StringRef
872AMDGPUToolChain::getGPUArch(const llvm::opt::ArgList &DriverArgs) const {
874 getTriple(), DriverArgs.getLastArgValue(options::OPT_mcpu_EQ));
875}
876
878AMDGPUToolChain::getParsedTargetID(const llvm::opt::ArgList &DriverArgs) const {
879 StringRef TargetID = DriverArgs.getLastArgValue(options::OPT_mcpu_EQ);
880 if (TargetID.empty())
881 return {std::nullopt, std::nullopt, std::nullopt};
882
883 llvm::StringMap<bool> FeatureMap;
884 auto OptionalGpuArch = parseTargetID(getTriple(), TargetID, &FeatureMap);
885 if (!OptionalGpuArch)
886 return {TargetID.str(), std::nullopt, std::nullopt};
887
888 return {TargetID.str(), OptionalGpuArch->str(), FeatureMap};
889}
890
892 const llvm::opt::ArgList &DriverArgs) const {
893 auto PTID = getParsedTargetID(DriverArgs);
894 if (PTID.OptionalTargetID && !PTID.OptionalGPUArch) {
895 getDriver().Diag(clang::diag::err_drv_bad_target_id)
896 << *PTID.OptionalTargetID;
897 }
898}
899
901AMDGPUToolChain::getSystemGPUArchs(const ArgList &Args) const {
902 // Detect AMD GPUs availible on the system.
903 std::string Program;
904 if (Arg *A = Args.getLastArg(options::OPT_offload_arch_tool_EQ))
905 Program = A->getValue();
906 else
907 Program = GetProgramPath("amdgpu-arch");
908
909 auto StdoutOrErr = getDriver().executeProgram({Program});
910 if (!StdoutOrErr)
911 return StdoutOrErr.takeError();
912
914 for (StringRef Arch : llvm::split((*StdoutOrErr)->getBuffer(), "\n"))
915 if (!Arch.empty())
916 GPUArchs.push_back(Arch.str());
917
918 if (GPUArchs.empty())
919 return llvm::createStringError(std::error_code(),
920 "No AMD GPU detected in the system");
921
922 return std::move(GPUArchs);
923}
924
926 const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args,
927 Action::OffloadKind DeviceOffloadingKind) const {
928 AMDGPUToolChain::addClangTargetOptions(DriverArgs, CC1Args,
929 DeviceOffloadingKind);
930
931 // For the OpenCL case where there is no offload target, accept -nostdlib to
932 // disable bitcode linking.
933 if (DeviceOffloadingKind == Action::OFK_None &&
934 DriverArgs.hasArg(options::OPT_nostdlib))
935 return;
936
937 if (!DriverArgs.hasFlag(options::OPT_offloadlib, options::OPT_no_offloadlib,
938 true))
939 return;
940
941 // Get the device name and canonicalize it
942 const StringRef GpuArch = getGPUArch(DriverArgs);
943 auto Kind = llvm::AMDGPU::parseArchAMDGCN(GpuArch);
944 const StringRef CanonArch = llvm::AMDGPU::getArchNameAMDGCN(Kind);
945 StringRef LibDeviceFile = RocmInstallation->getLibDeviceFile(CanonArch);
948 if (!RocmInstallation->checkCommonBitcodeLibs(CanonArch, LibDeviceFile,
949 ABIVer))
950 return;
951
952 // Add the OpenCL specific bitcode library.
954 BCLibs.emplace_back(RocmInstallation->getOpenCLPath().str());
955
956 // Add the generic set of libraries.
957 BCLibs.append(RocmInstallation->getCommonBitcodeLibs(
958 DriverArgs, LibDeviceFile, GpuArch, DeviceOffloadingKind,
959 getSanitizerArgs(DriverArgs).needsAsanRt()));
960
961 for (auto [BCFile, Internalize] : BCLibs) {
962 if (Internalize)
963 CC1Args.push_back("-mlink-builtin-bitcode");
964 else
965 CC1Args.push_back("-mlink-bitcode-file");
966 CC1Args.push_back(DriverArgs.MakeArgString(BCFile));
967 }
968}
969
971 StringRef GPUArch, StringRef LibDeviceFile,
972 DeviceLibABIVersion ABIVer) const {
973 if (!hasDeviceLibrary()) {
974 D.Diag(diag::err_drv_no_rocm_device_lib) << 0;
975 return false;
976 }
977 if (LibDeviceFile.empty()) {
978 D.Diag(diag::err_drv_no_rocm_device_lib) << 1 << GPUArch;
979 return false;
980 }
981 if (ABIVer.requiresLibrary() && getABIVersionPath(ABIVer).empty()) {
982 // Starting from COV6, we will report minimum ROCm version requirement in
983 // the error message.
984 if (ABIVer.getAsCodeObjectVersion() < 6)
985 D.Diag(diag::err_drv_no_rocm_device_lib) << 2 << ABIVer.toString() << 0;
986 else
987 D.Diag(diag::err_drv_no_rocm_device_lib)
988 << 2 << ABIVer.toString() << 1 << "6.3";
989 return false;
990 }
991 return true;
992}
993
996 const llvm::opt::ArgList &DriverArgs, StringRef LibDeviceFile,
997 StringRef GPUArch, const Action::OffloadKind DeviceOffloadingKind,
998 const bool NeedsASanRT) const {
1000
1001 CommonBitcodeLibsPreferences Pref{D, DriverArgs, GPUArch,
1002 DeviceOffloadingKind, NeedsASanRT};
1003
1004 auto AddBCLib = [&](ToolChain::BitCodeLibraryInfo BCLib,
1005 bool Internalize = true) {
1006 BCLib.ShouldInternalize = Internalize;
1007 BCLibs.emplace_back(BCLib);
1008 };
1009 auto AddSanBCLibs = [&]() {
1010 if (Pref.GPUSan)
1011 AddBCLib(getAsanRTLPath(), false);
1012 };
1013
1014 AddSanBCLibs();
1015 AddBCLib(getOCMLPath());
1016 if (!Pref.IsOpenMP)
1017 AddBCLib(getOCKLPath());
1018 else if (Pref.GPUSan && Pref.IsOpenMP)
1019 AddBCLib(getOCKLPath(), false);
1020 AddBCLib(getDenormalsAreZeroPath(Pref.DAZ));
1021 AddBCLib(getUnsafeMathPath(Pref.UnsafeMathOpt || Pref.FastRelaxedMath));
1022 AddBCLib(getFiniteOnlyPath(Pref.FiniteOnly || Pref.FastRelaxedMath));
1023 AddBCLib(getCorrectlyRoundedSqrtPath(Pref.CorrectSqrt));
1024 AddBCLib(getWavefrontSize64Path(Pref.Wave64));
1025 AddBCLib(LibDeviceFile);
1026 auto ABIVerPath = getABIVersionPath(Pref.ABIVer);
1027 if (!ABIVerPath.empty())
1028 AddBCLib(ABIVerPath);
1029
1030 return BCLibs;
1031}
1032
1035 const llvm::opt::ArgList &DriverArgs, const std::string &GPUArch,
1036 Action::OffloadKind DeviceOffloadingKind) const {
1037 auto Kind = llvm::AMDGPU::parseArchAMDGCN(GPUArch);
1038 const StringRef CanonArch = llvm::AMDGPU::getArchNameAMDGCN(Kind);
1039
1040 StringRef LibDeviceFile = RocmInstallation->getLibDeviceFile(CanonArch);
1042 getAMDGPUCodeObjectVersion(getDriver(), DriverArgs));
1043 if (!RocmInstallation->checkCommonBitcodeLibs(CanonArch, LibDeviceFile,
1044 ABIVer))
1045 return {};
1046
1047 return RocmInstallation->getCommonBitcodeLibs(
1048 DriverArgs, LibDeviceFile, GPUArch, DeviceOffloadingKind,
1049 getSanitizerArgs(DriverArgs).needsAsanRt());
1050}
1051
1053 const ToolChain &TC, const llvm::opt::ArgList &DriverArgs,
1054 StringRef TargetID, const llvm::opt::Arg *A) const {
1055 // For actions without targetID, do nothing.
1056 if (TargetID.empty())
1057 return false;
1058 Option O = A->getOption();
1059
1060 if (!O.matches(options::OPT_fsanitize_EQ))
1061 return false;
1062
1063 if (!DriverArgs.hasFlag(options::OPT_fgpu_sanitize,
1064 options::OPT_fno_gpu_sanitize, true))
1065 return true;
1066
1067 auto &Diags = TC.getDriver().getDiags();
1068
1069 // For simplicity, we only allow -fsanitize=address
1070 SanitizerMask K = parseSanitizerValue(A->getValue(), /*AllowGroups=*/false);
1071 if (K != SanitizerKind::Address)
1072 return true;
1073
1074 llvm::StringMap<bool> FeatureMap;
1075 auto OptionalGpuArch = parseTargetID(TC.getTriple(), TargetID, &FeatureMap);
1076
1077 assert(OptionalGpuArch && "Invalid Target ID");
1078 (void)OptionalGpuArch;
1079 auto Loc = FeatureMap.find("xnack");
1080 if (Loc == FeatureMap.end() || !Loc->second) {
1081 Diags.Report(
1082 clang::diag::warn_drv_unsupported_option_for_offload_arch_req_feature)
1083 << A->getAsString(DriverArgs) << TargetID << "xnack+";
1084 return true;
1085 }
1086 return false;
1087}
#define V(N, I)
Definition: ASTContext.h:3597
StringRef P
const Decl * D
IndirectLocalPath & Path
static void Append(char *Start, char *End, char *&Buffer, unsigned &BufferSize, unsigned &BufferCapacity)
OffloadArch Arch
Definition: OffloadArch.cpp:10
SourceLocation Loc
Definition: SemaObjC.cpp:754
__device__ __2f16 b
__device__ __2f16 float c
const char * getOffloadingArch() const
Definition: Action.h:213
OffloadKind getOffloadingDeviceKind() const
Definition: Action.h:212
Compilation - A set of tasks to perform for a single driver invocation.
Definition: Compilation.h:45
Driver - Encapsulate logic for constructing compilation processes from a set of gcc-driver-like comma...
Definition: Driver.h:99
DiagnosticsEngine & getDiags() const
Definition: Driver.h:430
llvm::Expected< std::unique_ptr< llvm::MemoryBuffer > > executeProgram(llvm::ArrayRef< llvm::StringRef > Args) const
Definition: Driver.cpp:406
DiagnosticBuilder Diag(unsigned DiagID) const
Definition: Driver.h:169
const llvm::opt::OptTable & getOpts() const
Definition: Driver.h:428
InputInfo - Wrapper for information about an input source.
Definition: InputInfo.h:22
const char * getFilename() const
Definition: InputInfo.h:83
StringRef getIncludePath() const
Get the detected path to Rocm's bin directory.
RocmInstallationDetector(const Driver &D, const llvm::Triple &HostTriple, const llvm::opt::ArgList &Args, bool DetectHIPRuntime=true, bool DetectDeviceLib=false)
Definition: AMDGPU.cpp:320
bool checkCommonBitcodeLibs(StringRef GPUArch, StringRef LibDeviceFile, DeviceLibABIVersion ABIVer) const
Check file paths of default bitcode libraries common to AMDGPU based toolchains.
Definition: AMDGPU.cpp:970
bool hasHIPStdParLibrary() const
Check whether we detected a valid HIP STDPAR Acceleration library.
llvm::SmallVector< ToolChain::BitCodeLibraryInfo, 12 > getCommonBitcodeLibs(const llvm::opt::ArgList &DriverArgs, StringRef LibDeviceFile, StringRef GPUArch, const Action::OffloadKind DeviceOffloadingKind, const bool NeedsASanRT) const
Get file paths of default bitcode libraries common to AMDGPU based toolchains.
Definition: AMDGPU.cpp:995
bool hasHIPRuntime() const
Check whether we detected a valid HIP runtime.
void AddHIPIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
Definition: AMDGPU.cpp:521
void print(raw_ostream &OS) const
Print information about the detected ROCm installation.
Definition: AMDGPU.cpp:515
ToolChain - Access to tools for a single platform.
Definition: ToolChain.h:92
llvm::Triple::ArchType getArch() const
Definition: ToolChain.h:269
const Driver & getDriver() const
Definition: ToolChain.h:253
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:359
const llvm::Triple & getTriple() const
Definition: ToolChain.h:255
std::string GetProgramPath(const char *Name) const
Definition: ToolChain.cpp:1094
SanitizerArgs getSanitizerArgs(const llvm::opt::ArgList &JobArgs) const
Definition: ToolChain.cpp:404
Tool - Information on a specific compilation tool.
Definition: Tool.h:32
llvm::DenormalMode getDefaultDenormalModeForType(const llvm::opt::ArgList &DriverArgs, const JobAction &JA, const llvm::fltSemantics *FPType=nullptr) const override
Returns the output denormal handling type in the default floating point environment for the given FPT...
Definition: AMDGPU.cpp:798
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: AMDGPU.cpp:724
static bool getDefaultDenormsAreZeroForTarget(llvm::AMDGPU::GPUKind GPUKind)
Return whether denormals should be flushed, and treated as 0 by default for the subtarget.
Definition: AMDGPU.cpp:781
StringRef getGPUArch(const llvm::opt::ArgList &DriverArgs) const
Get GPU arch from -mcpu without checking.
Definition: AMDGPU.cpp:872
bool shouldSkipSanitizeOption(const ToolChain &TC, const llvm::opt::ArgList &DriverArgs, StringRef TargetID, const llvm::opt::Arg *A) const
Should skip sanitize options.
Definition: AMDGPU.cpp:1052
virtual void checkTargetID(const llvm::opt::ArgList &DriverArgs) const
Check and diagnose invalid target ID specified by -mcpu.
Definition: AMDGPU.cpp:891
Tool * buildLinker() const override
Definition: AMDGPU.cpp:719
static bool isWave64(const llvm::opt::ArgList &DriverArgs, llvm::AMDGPU::GPUKind Kind)
Definition: AMDGPU.cpp:832
void addClangWarningOptions(llvm::opt::ArgStringList &CC1Args) const override
Common warning options shared by AMDGPU HIP, OpenCL and OpenMP toolchains.
Definition: AMDGPU.cpp:865
AMDGPUToolChain(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args)
AMDGPU Toolchain.
Definition: AMDGPU.cpp:707
ParsedTargetIDType getParsedTargetID(const llvm::opt::ArgList &DriverArgs) const
Get target ID, GPU arch, and target ID features if the target ID is specified and valid.
Definition: AMDGPU.cpp:878
StringRef getOptionDefault(options::ID OptID) const
Definition: AMDGPU.h:55
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: AMDGPU.cpp:849
virtual Expected< SmallVector< std::string > > getSystemGPUArchs(const llvm::opt::ArgList &Args) const override
Uses amdgpu-arch tool to get arch of the system GPU.
Definition: AMDGPU.cpp:901
LazyDetector< RocmInstallationDetector > RocmInstallation
Definition: Gnu.h:359
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: AMDGPU.cpp:925
llvm::SmallVector< BitCodeLibraryInfo, 12 > getCommonDeviceLibNames(const llvm::opt::ArgList &DriverArgs, const std::string &GPUArch, Action::OffloadKind DeviceOffloadingKind) const
Definition: AMDGPU.cpp:1034
ROCMToolChain(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args)
ROCM Toolchain.
Definition: AMDGPU.cpp:843
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs,...
Definition: AMDGPU.cpp:611
void getAMDGPUTargetFeatures(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args, std::vector< StringRef > &Features)
Definition: AMDGPU.cpp:664
void addOpenCLBuiltinsLib(const Driver &D, const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args)
void handleTargetFeaturesGroup(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args, std::vector< StringRef > &Features, llvm::opt::OptSpecifier Group)
Iterate Args and convert -mxxx to +xxx and -mno-xxx to -xxx and append it to Features.
void checkAMDGPUCodeObjectVersion(const Driver &D, const llvm::opt::ArgList &Args)
void addLTOOptions(const ToolChain &ToolChain, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, const InputInfo &Output, const InputInfoList &Inputs, bool IsThinLTO)
void addLinkerCompressDebugSectionsOption(const ToolChain &TC, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
Definition: CommonArgs.cpp:626
void AddLinkerInputs(const ToolChain &TC, const InputInfoList &Inputs, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, const JobAction &JA)
unsigned getAMDGPUCodeObjectVersion(const Driver &D, const llvm::opt::ArgList &Args)
The JSON file list parser is used to communicate input to InstallAPI.
std::optional< llvm::StringRef > parseTargetID(const llvm::Triple &T, llvm::StringRef OffloadArch, llvm::StringMap< bool > *FeatureMap)
Parse a target ID to get processor and feature map.
Definition: TargetID.cpp:103
llvm::StringRef getProcessorFromTargetID(const llvm::Triple &T, llvm::StringRef OffloadArch)
Get processor name from target ID.
Definition: TargetID.cpp:54
llvm::SmallVector< llvm::StringRef, 4 > getAllPossibleTargetIDFeatures(const llvm::Triple &T, llvm::StringRef Processor)
Get all feature strings that can be used in target ID for Processor.
Definition: TargetID.cpp:38
SanitizerMask parseSanitizerValue(StringRef Value, bool AllowGroups)
Parse a single value from a -fsanitize= or -fno-sanitize= value list.
Definition: Sanitizers.cpp:74
#define true
Definition: stdbool.h:25
ABI version of device library.
static DeviceLibABIVersion fromCodeObjectVersion(unsigned CodeObjectVersion)
bool requiresLibrary()
Whether ABI version bc file is requested.
static constexpr ResponseFileSupport AtFileCurCP()
Definition: Job.h:92
The struct type returned by getParsedTargetID.
Definition: AMDGPU.h:117