1 //===- ToolChain.cpp - Collections of tools for one platform --------------===//
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 "clang/Driver/ToolChain.h"
10 #include "InputInfo.h"
11 #include "ToolChains/Arch/ARM.h"
12 #include "ToolChains/Clang.h"
13 #include "ToolChains/InterfaceStubs.h"
14 #include "ToolChains/Flang.h"
15 #include "clang/Basic/ObjCRuntime.h"
16 #include "clang/Basic/Sanitizers.h"
17 #include "clang/Config/config.h"
18 #include "clang/Driver/Action.h"
19 #include "clang/Driver/Driver.h"
20 #include "clang/Driver/DriverDiagnostic.h"
21 #include "clang/Driver/Job.h"
22 #include "clang/Driver/Options.h"
23 #include "clang/Driver/SanitizerArgs.h"
24 #include "clang/Driver/XRayArgs.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SmallString.h"
27 #include "llvm/ADT/StringRef.h"
28 #include "llvm/ADT/Triple.h"
29 #include "llvm/ADT/Twine.h"
30 #include "llvm/Config/llvm-config.h"
31 #include "llvm/MC/MCTargetOptions.h"
32 #include "llvm/Option/Arg.h"
33 #include "llvm/Option/ArgList.h"
34 #include "llvm/Option/OptTable.h"
35 #include "llvm/Option/Option.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/FileSystem.h"
38 #include "llvm/Support/Path.h"
39 #include "llvm/Support/TargetParser.h"
40 #include "llvm/Support/TargetRegistry.h"
41 #include "llvm/Support/VersionTuple.h"
42 #include "llvm/Support/VirtualFileSystem.h"
43 #include <cassert>
44 #include <cstddef>
45 #include <cstring>
46 #include <string>
47
48 using namespace clang;
49 using namespace driver;
50 using namespace tools;
51 using namespace llvm;
52 using namespace llvm::opt;
53
GetRTTIArgument(const ArgList & Args)54 static llvm::opt::Arg *GetRTTIArgument(const ArgList &Args) {
55 return Args.getLastArg(options::OPT_mkernel, options::OPT_fapple_kext,
56 options::OPT_fno_rtti, options::OPT_frtti);
57 }
58
CalculateRTTIMode(const ArgList & Args,const llvm::Triple & Triple,const Arg * CachedRTTIArg)59 static ToolChain::RTTIMode CalculateRTTIMode(const ArgList &Args,
60 const llvm::Triple &Triple,
61 const Arg *CachedRTTIArg) {
62 // Explicit rtti/no-rtti args
63 if (CachedRTTIArg) {
64 if (CachedRTTIArg->getOption().matches(options::OPT_frtti))
65 return ToolChain::RM_Enabled;
66 else
67 return ToolChain::RM_Disabled;
68 }
69
70 // -frtti is default, except for the PS4 CPU.
71 return (Triple.isPS4CPU()) ? ToolChain::RM_Disabled : ToolChain::RM_Enabled;
72 }
73
ToolChain(const Driver & D,const llvm::Triple & T,const ArgList & Args)74 ToolChain::ToolChain(const Driver &D, const llvm::Triple &T,
75 const ArgList &Args)
76 : D(D), Triple(T), Args(Args), CachedRTTIArg(GetRTTIArgument(Args)),
77 CachedRTTIMode(CalculateRTTIMode(Args, Triple, CachedRTTIArg)) {
78 if (D.CCCIsCXX()) {
79 if (auto CXXStdlibPath = getCXXStdlibPath())
80 getFilePaths().push_back(*CXXStdlibPath);
81 }
82
83 if (auto RuntimePath = getRuntimePath())
84 getLibraryPaths().push_back(*RuntimePath);
85
86 std::string CandidateLibPath = getArchSpecificLibPath();
87 if (getVFS().exists(CandidateLibPath))
88 getFilePaths().push_back(CandidateLibPath);
89 }
90
setTripleEnvironment(llvm::Triple::EnvironmentType Env)91 void ToolChain::setTripleEnvironment(llvm::Triple::EnvironmentType Env) {
92 Triple.setEnvironment(Env);
93 if (EffectiveTriple != llvm::Triple())
94 EffectiveTriple.setEnvironment(Env);
95 }
96
97 ToolChain::~ToolChain() = default;
98
getVFS() const99 llvm::vfs::FileSystem &ToolChain::getVFS() const {
100 return getDriver().getVFS();
101 }
102
useIntegratedAs() const103 bool ToolChain::useIntegratedAs() const {
104 return Args.hasFlag(options::OPT_fintegrated_as,
105 options::OPT_fno_integrated_as,
106 IsIntegratedAssemblerDefault());
107 }
108
useRelaxRelocations() const109 bool ToolChain::useRelaxRelocations() const {
110 return ENABLE_X86_RELAX_RELOCATIONS;
111 }
112
isNoExecStackDefault() const113 bool ToolChain::isNoExecStackDefault() const {
114 return false;
115 }
116
getSanitizerArgs() const117 const SanitizerArgs& ToolChain::getSanitizerArgs() const {
118 if (!SanitizerArguments.get())
119 SanitizerArguments.reset(new SanitizerArgs(*this, Args));
120 return *SanitizerArguments.get();
121 }
122
getXRayArgs() const123 const XRayArgs& ToolChain::getXRayArgs() const {
124 if (!XRayArguments.get())
125 XRayArguments.reset(new XRayArgs(*this, Args));
126 return *XRayArguments.get();
127 }
128
129 namespace {
130
131 struct DriverSuffix {
132 const char *Suffix;
133 const char *ModeFlag;
134 };
135
136 } // namespace
137
FindDriverSuffix(StringRef ProgName,size_t & Pos)138 static const DriverSuffix *FindDriverSuffix(StringRef ProgName, size_t &Pos) {
139 // A list of known driver suffixes. Suffixes are compared against the
140 // program name in order. If there is a match, the frontend type is updated as
141 // necessary by applying the ModeFlag.
142 static const DriverSuffix DriverSuffixes[] = {
143 {"clang", nullptr},
144 {"clang++", "--driver-mode=g++"},
145 {"clang-c++", "--driver-mode=g++"},
146 {"clang-cc", nullptr},
147 {"clang-cpp", "--driver-mode=cpp"},
148 {"clang-g++", "--driver-mode=g++"},
149 {"clang-gcc", nullptr},
150 {"clang-cl", "--driver-mode=cl"},
151 {"cc", nullptr},
152 {"cpp", "--driver-mode=cpp"},
153 {"cl", "--driver-mode=cl"},
154 {"++", "--driver-mode=g++"},
155 {"flang", "--driver-mode=flang"},
156 };
157
158 for (size_t i = 0; i < llvm::array_lengthof(DriverSuffixes); ++i) {
159 StringRef Suffix(DriverSuffixes[i].Suffix);
160 if (ProgName.endswith(Suffix)) {
161 Pos = ProgName.size() - Suffix.size();
162 return &DriverSuffixes[i];
163 }
164 }
165 return nullptr;
166 }
167
168 /// Normalize the program name from argv[0] by stripping the file extension if
169 /// present and lower-casing the string on Windows.
normalizeProgramName(llvm::StringRef Argv0)170 static std::string normalizeProgramName(llvm::StringRef Argv0) {
171 std::string ProgName = std::string(llvm::sys::path::stem(Argv0));
172 #ifdef _WIN32
173 // Transform to lowercase for case insensitive file systems.
174 std::transform(ProgName.begin(), ProgName.end(), ProgName.begin(), ::tolower);
175 #endif
176 return ProgName;
177 }
178
parseDriverSuffix(StringRef ProgName,size_t & Pos)179 static const DriverSuffix *parseDriverSuffix(StringRef ProgName, size_t &Pos) {
180 // Try to infer frontend type and default target from the program name by
181 // comparing it against DriverSuffixes in order.
182
183 // If there is a match, the function tries to identify a target as prefix.
184 // E.g. "x86_64-linux-clang" as interpreted as suffix "clang" with target
185 // prefix "x86_64-linux". If such a target prefix is found, it may be
186 // added via -target as implicit first argument.
187 const DriverSuffix *DS = FindDriverSuffix(ProgName, Pos);
188
189 if (!DS) {
190 // Try again after stripping any trailing version number:
191 // clang++3.5 -> clang++
192 ProgName = ProgName.rtrim("0123456789.");
193 DS = FindDriverSuffix(ProgName, Pos);
194 }
195
196 if (!DS) {
197 // Try again after stripping trailing -component.
198 // clang++-tot -> clang++
199 ProgName = ProgName.slice(0, ProgName.rfind('-'));
200 DS = FindDriverSuffix(ProgName, Pos);
201 }
202 return DS;
203 }
204
205 ParsedClangName
getTargetAndModeFromProgramName(StringRef PN)206 ToolChain::getTargetAndModeFromProgramName(StringRef PN) {
207 std::string ProgName = normalizeProgramName(PN);
208 size_t SuffixPos;
209 const DriverSuffix *DS = parseDriverSuffix(ProgName, SuffixPos);
210 if (!DS)
211 return {};
212 size_t SuffixEnd = SuffixPos + strlen(DS->Suffix);
213
214 size_t LastComponent = ProgName.rfind('-', SuffixPos);
215 if (LastComponent == std::string::npos)
216 return ParsedClangName(ProgName.substr(0, SuffixEnd), DS->ModeFlag);
217 std::string ModeSuffix = ProgName.substr(LastComponent + 1,
218 SuffixEnd - LastComponent - 1);
219
220 // Infer target from the prefix.
221 StringRef Prefix(ProgName);
222 Prefix = Prefix.slice(0, LastComponent);
223 std::string IgnoredError;
224 bool IsRegistered =
225 llvm::TargetRegistry::lookupTarget(std::string(Prefix), IgnoredError);
226 return ParsedClangName{std::string(Prefix), ModeSuffix, DS->ModeFlag,
227 IsRegistered};
228 }
229
getDefaultUniversalArchName() const230 StringRef ToolChain::getDefaultUniversalArchName() const {
231 // In universal driver terms, the arch name accepted by -arch isn't exactly
232 // the same as the ones that appear in the triple. Roughly speaking, this is
233 // an inverse of the darwin::getArchTypeForDarwinArchName() function.
234 switch (Triple.getArch()) {
235 case llvm::Triple::aarch64: {
236 if (getTriple().isArm64e())
237 return "arm64e";
238 return "arm64";
239 }
240 case llvm::Triple::aarch64_32:
241 return "arm64_32";
242 case llvm::Triple::ppc:
243 return "ppc";
244 case llvm::Triple::ppc64:
245 return "ppc64";
246 case llvm::Triple::ppc64le:
247 return "ppc64le";
248 default:
249 return Triple.getArchName();
250 }
251 }
252
getInputFilename(const InputInfo & Input) const253 std::string ToolChain::getInputFilename(const InputInfo &Input) const {
254 return Input.getFilename();
255 }
256
IsUnwindTablesDefault(const ArgList & Args) const257 bool ToolChain::IsUnwindTablesDefault(const ArgList &Args) const {
258 return false;
259 }
260
getClang() const261 Tool *ToolChain::getClang() const {
262 if (!Clang)
263 Clang.reset(new tools::Clang(*this));
264 return Clang.get();
265 }
266
getFlang() const267 Tool *ToolChain::getFlang() const {
268 if (!Flang)
269 Flang.reset(new tools::Flang(*this));
270 return Flang.get();
271 }
272
buildAssembler() const273 Tool *ToolChain::buildAssembler() const {
274 return new tools::ClangAs(*this);
275 }
276
buildLinker() const277 Tool *ToolChain::buildLinker() const {
278 llvm_unreachable("Linking is not supported by this toolchain");
279 }
280
buildStaticLibTool() const281 Tool *ToolChain::buildStaticLibTool() const {
282 llvm_unreachable("Creating static lib is not supported by this toolchain");
283 }
284
getAssemble() const285 Tool *ToolChain::getAssemble() const {
286 if (!Assemble)
287 Assemble.reset(buildAssembler());
288 return Assemble.get();
289 }
290
getClangAs() const291 Tool *ToolChain::getClangAs() const {
292 if (!Assemble)
293 Assemble.reset(new tools::ClangAs(*this));
294 return Assemble.get();
295 }
296
getLink() const297 Tool *ToolChain::getLink() const {
298 if (!Link)
299 Link.reset(buildLinker());
300 return Link.get();
301 }
302
getStaticLibTool() const303 Tool *ToolChain::getStaticLibTool() const {
304 if (!StaticLibTool)
305 StaticLibTool.reset(buildStaticLibTool());
306 return StaticLibTool.get();
307 }
308
getIfsMerge() const309 Tool *ToolChain::getIfsMerge() const {
310 if (!IfsMerge)
311 IfsMerge.reset(new tools::ifstool::Merger(*this));
312 return IfsMerge.get();
313 }
314
getOffloadBundler() const315 Tool *ToolChain::getOffloadBundler() const {
316 if (!OffloadBundler)
317 OffloadBundler.reset(new tools::OffloadBundler(*this));
318 return OffloadBundler.get();
319 }
320
getOffloadWrapper() const321 Tool *ToolChain::getOffloadWrapper() const {
322 if (!OffloadWrapper)
323 OffloadWrapper.reset(new tools::OffloadWrapper(*this));
324 return OffloadWrapper.get();
325 }
326
getTool(Action::ActionClass AC) const327 Tool *ToolChain::getTool(Action::ActionClass AC) const {
328 switch (AC) {
329 case Action::AssembleJobClass:
330 return getAssemble();
331
332 case Action::IfsMergeJobClass:
333 return getIfsMerge();
334
335 case Action::LinkJobClass:
336 return getLink();
337
338 case Action::StaticLibJobClass:
339 return getStaticLibTool();
340
341 case Action::InputClass:
342 case Action::BindArchClass:
343 case Action::OffloadClass:
344 case Action::LipoJobClass:
345 case Action::DsymutilJobClass:
346 case Action::VerifyDebugInfoJobClass:
347 llvm_unreachable("Invalid tool kind.");
348
349 case Action::CompileJobClass:
350 case Action::PrecompileJobClass:
351 case Action::HeaderModulePrecompileJobClass:
352 case Action::PreprocessJobClass:
353 case Action::AnalyzeJobClass:
354 case Action::MigrateJobClass:
355 case Action::VerifyPCHJobClass:
356 case Action::BackendJobClass:
357 return getClang();
358
359 case Action::OffloadBundlingJobClass:
360 case Action::OffloadUnbundlingJobClass:
361 return getOffloadBundler();
362
363 case Action::OffloadWrapperJobClass:
364 return getOffloadWrapper();
365 }
366
367 llvm_unreachable("Invalid tool kind.");
368 }
369
getArchNameForCompilerRTLib(const ToolChain & TC,const ArgList & Args)370 static StringRef getArchNameForCompilerRTLib(const ToolChain &TC,
371 const ArgList &Args) {
372 const llvm::Triple &Triple = TC.getTriple();
373 bool IsWindows = Triple.isOSWindows();
374
375 if (TC.getArch() == llvm::Triple::arm || TC.getArch() == llvm::Triple::armeb)
376 return (arm::getARMFloatABI(TC, Args) == arm::FloatABI::Hard && !IsWindows)
377 ? "armhf"
378 : "arm";
379
380 // For historic reasons, Android library is using i686 instead of i386.
381 if (TC.getArch() == llvm::Triple::x86 && Triple.isAndroid())
382 return "i686";
383
384 return llvm::Triple::getArchTypeName(TC.getArch());
385 }
386
getOSLibName() const387 StringRef ToolChain::getOSLibName() const {
388 switch (Triple.getOS()) {
389 case llvm::Triple::FreeBSD:
390 return "freebsd";
391 case llvm::Triple::NetBSD:
392 return "netbsd";
393 case llvm::Triple::OpenBSD:
394 return "openbsd";
395 case llvm::Triple::Solaris:
396 return "sunos";
397 case llvm::Triple::AIX:
398 return "aix";
399 default:
400 return getOS();
401 }
402 }
403
getCompilerRTPath() const404 std::string ToolChain::getCompilerRTPath() const {
405 SmallString<128> Path(getDriver().ResourceDir);
406 if (Triple.isOSUnknown()) {
407 llvm::sys::path::append(Path, "lib");
408 } else {
409 llvm::sys::path::append(Path, "lib", getOSLibName());
410 }
411 return std::string(Path.str());
412 }
413
getCompilerRTBasename(const ArgList & Args,StringRef Component,FileType Type,bool AddArch) const414 std::string ToolChain::getCompilerRTBasename(const ArgList &Args,
415 StringRef Component, FileType Type,
416 bool AddArch) const {
417 const llvm::Triple &TT = getTriple();
418 bool IsITANMSVCWindows =
419 TT.isWindowsMSVCEnvironment() || TT.isWindowsItaniumEnvironment();
420
421 const char *Prefix =
422 IsITANMSVCWindows || Type == ToolChain::FT_Object ? "" : "lib";
423 const char *Suffix;
424 switch (Type) {
425 case ToolChain::FT_Object:
426 Suffix = IsITANMSVCWindows ? ".obj" : ".o";
427 break;
428 case ToolChain::FT_Static:
429 Suffix = IsITANMSVCWindows ? ".lib" : ".a";
430 break;
431 case ToolChain::FT_Shared:
432 Suffix = Triple.isOSWindows()
433 ? (Triple.isWindowsGNUEnvironment() ? ".dll.a" : ".lib")
434 : ".so";
435 break;
436 }
437
438 std::string ArchAndEnv;
439 if (AddArch) {
440 StringRef Arch = getArchNameForCompilerRTLib(*this, Args);
441 const char *Env = TT.isAndroid() ? "-android" : "";
442 ArchAndEnv = ("-" + Arch + Env).str();
443 }
444 return (Prefix + Twine("clang_rt.") + Component + ArchAndEnv + Suffix).str();
445 }
446
getCompilerRT(const ArgList & Args,StringRef Component,FileType Type) const447 std::string ToolChain::getCompilerRT(const ArgList &Args, StringRef Component,
448 FileType Type) const {
449 // Check for runtime files in the new layout without the architecture first.
450 std::string CRTBasename =
451 getCompilerRTBasename(Args, Component, Type, /*AddArch=*/false);
452 for (const auto &LibPath : getLibraryPaths()) {
453 SmallString<128> P(LibPath);
454 llvm::sys::path::append(P, CRTBasename);
455 if (getVFS().exists(P))
456 return std::string(P.str());
457 }
458
459 // Fall back to the old expected compiler-rt name if the new one does not
460 // exist.
461 CRTBasename = getCompilerRTBasename(Args, Component, Type, /*AddArch=*/true);
462 SmallString<128> Path(getCompilerRTPath());
463 llvm::sys::path::append(Path, CRTBasename);
464 return std::string(Path.str());
465 }
466
getCompilerRTArgString(const llvm::opt::ArgList & Args,StringRef Component,FileType Type) const467 const char *ToolChain::getCompilerRTArgString(const llvm::opt::ArgList &Args,
468 StringRef Component,
469 FileType Type) const {
470 return Args.MakeArgString(getCompilerRT(Args, Component, Type));
471 }
472
473
getRuntimePath() const474 Optional<std::string> ToolChain::getRuntimePath() const {
475 SmallString<128> P;
476
477 // First try the triple passed to driver as --target=<triple>.
478 P.assign(D.ResourceDir);
479 llvm::sys::path::append(P, "lib", D.getTargetTriple());
480 if (getVFS().exists(P))
481 return llvm::Optional<std::string>(std::string(P.str()));
482
483 // Second try the normalized triple.
484 P.assign(D.ResourceDir);
485 llvm::sys::path::append(P, "lib", Triple.str());
486 if (getVFS().exists(P))
487 return llvm::Optional<std::string>(std::string(P.str()));
488
489 return None;
490 }
491
getCXXStdlibPath() const492 Optional<std::string> ToolChain::getCXXStdlibPath() const {
493 SmallString<128> P;
494
495 // First try the triple passed to driver as --target=<triple>.
496 P.assign(D.Dir);
497 llvm::sys::path::append(P, "..", "lib", D.getTargetTriple(), "c++");
498 if (getVFS().exists(P))
499 return llvm::Optional<std::string>(std::string(P.str()));
500
501 // Second try the normalized triple.
502 P.assign(D.Dir);
503 llvm::sys::path::append(P, "..", "lib", Triple.str(), "c++");
504 if (getVFS().exists(P))
505 return llvm::Optional<std::string>(std::string(P.str()));
506
507 return None;
508 }
509
getArchSpecificLibPath() const510 std::string ToolChain::getArchSpecificLibPath() const {
511 SmallString<128> Path(getDriver().ResourceDir);
512 llvm::sys::path::append(Path, "lib", getOSLibName(),
513 llvm::Triple::getArchTypeName(getArch()));
514 return std::string(Path.str());
515 }
516
needsProfileRT(const ArgList & Args)517 bool ToolChain::needsProfileRT(const ArgList &Args) {
518 if (Args.hasArg(options::OPT_noprofilelib))
519 return false;
520
521 return Args.hasArg(options::OPT_fprofile_generate) ||
522 Args.hasArg(options::OPT_fprofile_generate_EQ) ||
523 Args.hasArg(options::OPT_fcs_profile_generate) ||
524 Args.hasArg(options::OPT_fcs_profile_generate_EQ) ||
525 Args.hasArg(options::OPT_fprofile_instr_generate) ||
526 Args.hasArg(options::OPT_fprofile_instr_generate_EQ) ||
527 Args.hasArg(options::OPT_fcreate_profile) ||
528 Args.hasArg(options::OPT_forder_file_instrumentation);
529 }
530
needsGCovInstrumentation(const llvm::opt::ArgList & Args)531 bool ToolChain::needsGCovInstrumentation(const llvm::opt::ArgList &Args) {
532 return Args.hasArg(options::OPT_coverage) ||
533 Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
534 false);
535 }
536
SelectTool(const JobAction & JA) const537 Tool *ToolChain::SelectTool(const JobAction &JA) const {
538 if (D.IsFlangMode() && getDriver().ShouldUseFlangCompiler(JA)) return getFlang();
539 if (getDriver().ShouldUseClangCompiler(JA)) return getClang();
540 Action::ActionClass AC = JA.getKind();
541 if (AC == Action::AssembleJobClass && useIntegratedAs())
542 return getClangAs();
543 return getTool(AC);
544 }
545
GetFilePath(const char * Name) const546 std::string ToolChain::GetFilePath(const char *Name) const {
547 return D.GetFilePath(Name, *this);
548 }
549
GetProgramPath(const char * Name) const550 std::string ToolChain::GetProgramPath(const char *Name) const {
551 return D.GetProgramPath(Name, *this);
552 }
553
GetLinkerPath(bool * LinkerIsLLD,bool * LinkerIsLLDDarwinNew) const554 std::string ToolChain::GetLinkerPath(bool *LinkerIsLLD,
555 bool *LinkerIsLLDDarwinNew) const {
556 if (LinkerIsLLD)
557 *LinkerIsLLD = false;
558 if (LinkerIsLLDDarwinNew)
559 *LinkerIsLLDDarwinNew = false;
560
561 // Get -fuse-ld= first to prevent -Wunused-command-line-argument. -fuse-ld= is
562 // considered as the linker flavor, e.g. "bfd", "gold", or "lld".
563 const Arg* A = Args.getLastArg(options::OPT_fuse_ld_EQ);
564 StringRef UseLinker = A ? A->getValue() : CLANG_DEFAULT_LINKER;
565
566 // --ld-path= takes precedence over -fuse-ld= and specifies the executable
567 // name. -B, COMPILER_PATH and PATH and consulted if the value does not
568 // contain a path component separator.
569 if (const Arg *A = Args.getLastArg(options::OPT_ld_path_EQ)) {
570 std::string Path(A->getValue());
571 if (!Path.empty()) {
572 if (llvm::sys::path::parent_path(Path).empty())
573 Path = GetProgramPath(A->getValue());
574 if (llvm::sys::fs::can_execute(Path))
575 return std::string(Path);
576 }
577 getDriver().Diag(diag::err_drv_invalid_linker_name) << A->getAsString(Args);
578 return GetProgramPath(getDefaultLinker());
579 }
580 // If we're passed -fuse-ld= with no argument, or with the argument ld,
581 // then use whatever the default system linker is.
582 if (UseLinker.empty() || UseLinker == "ld") {
583 const char *DefaultLinker = getDefaultLinker();
584 if (llvm::sys::path::is_absolute(DefaultLinker))
585 return std::string(DefaultLinker);
586 else
587 return GetProgramPath(DefaultLinker);
588 }
589
590 // Extending -fuse-ld= to an absolute or relative path is unexpected. Checking
591 // for the linker flavor is brittle. In addition, prepending "ld." or "ld64."
592 // to a relative path is surprising. This is more complex due to priorities
593 // among -B, COMPILER_PATH and PATH. --ld-path= should be used instead.
594 if (UseLinker.find('/') != StringRef::npos)
595 getDriver().Diag(diag::warn_drv_fuse_ld_path);
596
597 if (llvm::sys::path::is_absolute(UseLinker)) {
598 // If we're passed what looks like an absolute path, don't attempt to
599 // second-guess that.
600 if (llvm::sys::fs::can_execute(UseLinker))
601 return std::string(UseLinker);
602 } else {
603 llvm::SmallString<8> LinkerName;
604 if (Triple.isOSDarwin())
605 LinkerName.append("ld64.");
606 else
607 LinkerName.append("ld.");
608 LinkerName.append(UseLinker);
609
610 std::string LinkerPath(GetProgramPath(LinkerName.c_str()));
611 if (llvm::sys::fs::can_execute(LinkerPath)) {
612 // FIXME: Remove lld.darwinnew here once it's the only MachO lld.
613 if (LinkerIsLLD)
614 *LinkerIsLLD = UseLinker == "lld" || UseLinker == "lld.darwinnew";
615 if (LinkerIsLLDDarwinNew)
616 *LinkerIsLLDDarwinNew = UseLinker == "lld.darwinnew";
617 return LinkerPath;
618 }
619 }
620
621 if (A)
622 getDriver().Diag(diag::err_drv_invalid_linker_name) << A->getAsString(Args);
623
624 return GetProgramPath(getDefaultLinker());
625 }
626
GetStaticLibToolPath() const627 std::string ToolChain::GetStaticLibToolPath() const {
628 // TODO: Add support for static lib archiving on Windows
629 return GetProgramPath("llvm-ar");
630 }
631
LookupTypeForExtension(StringRef Ext) const632 types::ID ToolChain::LookupTypeForExtension(StringRef Ext) const {
633 types::ID id = types::lookupTypeForExtension(Ext);
634
635 // Flang always runs the preprocessor and has no notion of "preprocessed
636 // fortran". Here, TY_PP_Fortran is coerced to TY_Fortran to avoid treating
637 // them differently.
638 if (D.IsFlangMode() && id == types::TY_PP_Fortran)
639 id = types::TY_Fortran;
640
641 return id;
642 }
643
HasNativeLLVMSupport() const644 bool ToolChain::HasNativeLLVMSupport() const {
645 return false;
646 }
647
isCrossCompiling() const648 bool ToolChain::isCrossCompiling() const {
649 llvm::Triple HostTriple(LLVM_HOST_TRIPLE);
650 switch (HostTriple.getArch()) {
651 // The A32/T32/T16 instruction sets are not separate architectures in this
652 // context.
653 case llvm::Triple::arm:
654 case llvm::Triple::armeb:
655 case llvm::Triple::thumb:
656 case llvm::Triple::thumbeb:
657 return getArch() != llvm::Triple::arm && getArch() != llvm::Triple::thumb &&
658 getArch() != llvm::Triple::armeb && getArch() != llvm::Triple::thumbeb;
659 default:
660 return HostTriple.getArch() != getArch();
661 }
662 }
663
getDefaultObjCRuntime(bool isNonFragile) const664 ObjCRuntime ToolChain::getDefaultObjCRuntime(bool isNonFragile) const {
665 return ObjCRuntime(isNonFragile ? ObjCRuntime::GNUstep : ObjCRuntime::GCC,
666 VersionTuple());
667 }
668
669 llvm::ExceptionHandling
GetExceptionModel(const llvm::opt::ArgList & Args) const670 ToolChain::GetExceptionModel(const llvm::opt::ArgList &Args) const {
671 return llvm::ExceptionHandling::None;
672 }
673
isThreadModelSupported(const StringRef Model) const674 bool ToolChain::isThreadModelSupported(const StringRef Model) const {
675 if (Model == "single") {
676 // FIXME: 'single' is only supported on ARM and WebAssembly so far.
677 return Triple.getArch() == llvm::Triple::arm ||
678 Triple.getArch() == llvm::Triple::armeb ||
679 Triple.getArch() == llvm::Triple::thumb ||
680 Triple.getArch() == llvm::Triple::thumbeb || Triple.isWasm();
681 } else if (Model == "posix")
682 return true;
683
684 return false;
685 }
686
ComputeLLVMTriple(const ArgList & Args,types::ID InputType) const687 std::string ToolChain::ComputeLLVMTriple(const ArgList &Args,
688 types::ID InputType) const {
689 switch (getTriple().getArch()) {
690 default:
691 return getTripleString();
692
693 case llvm::Triple::x86_64: {
694 llvm::Triple Triple = getTriple();
695 if (!Triple.isOSBinFormatMachO())
696 return getTripleString();
697
698 if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
699 // x86_64h goes in the triple. Other -march options just use the
700 // vanilla triple we already have.
701 StringRef MArch = A->getValue();
702 if (MArch == "x86_64h")
703 Triple.setArchName(MArch);
704 }
705 return Triple.getTriple();
706 }
707 case llvm::Triple::aarch64: {
708 llvm::Triple Triple = getTriple();
709 if (!Triple.isOSBinFormatMachO())
710 return getTripleString();
711
712 if (Triple.isArm64e())
713 return getTripleString();
714
715 // FIXME: older versions of ld64 expect the "arm64" component in the actual
716 // triple string and query it to determine whether an LTO file can be
717 // handled. Remove this when we don't care any more.
718 Triple.setArchName("arm64");
719 return Triple.getTriple();
720 }
721 case llvm::Triple::aarch64_32:
722 return getTripleString();
723 case llvm::Triple::arm:
724 case llvm::Triple::armeb:
725 case llvm::Triple::thumb:
726 case llvm::Triple::thumbeb: {
727 // FIXME: Factor into subclasses.
728 llvm::Triple Triple = getTriple();
729 bool IsBigEndian = getTriple().getArch() == llvm::Triple::armeb ||
730 getTriple().getArch() == llvm::Triple::thumbeb;
731
732 // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
733 // '-mbig-endian'/'-EB'.
734 if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
735 options::OPT_mbig_endian)) {
736 IsBigEndian = !A->getOption().matches(options::OPT_mlittle_endian);
737 }
738
739 // Thumb2 is the default for V7 on Darwin.
740 //
741 // FIXME: Thumb should just be another -target-feaure, not in the triple.
742 StringRef MCPU, MArch;
743 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
744 MCPU = A->getValue();
745 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
746 MArch = A->getValue();
747 std::string CPU =
748 Triple.isOSBinFormatMachO()
749 ? tools::arm::getARMCPUForMArch(MArch, Triple).str()
750 : tools::arm::getARMTargetCPU(MCPU, MArch, Triple);
751 StringRef Suffix =
752 tools::arm::getLLVMArchSuffixForARM(CPU, MArch, Triple);
753 bool IsMProfile = ARM::parseArchProfile(Suffix) == ARM::ProfileKind::M;
754 bool ThumbDefault = IsMProfile || (ARM::parseArchVersion(Suffix) == 7 &&
755 getTriple().isOSBinFormatMachO());
756 // FIXME: this is invalid for WindowsCE
757 if (getTriple().isOSWindows())
758 ThumbDefault = true;
759 std::string ArchName;
760 if (IsBigEndian)
761 ArchName = "armeb";
762 else
763 ArchName = "arm";
764
765 // Check if ARM ISA was explicitly selected (using -mno-thumb or -marm) for
766 // M-Class CPUs/architecture variants, which is not supported.
767 bool ARMModeRequested = !Args.hasFlag(options::OPT_mthumb,
768 options::OPT_mno_thumb, ThumbDefault);
769 if (IsMProfile && ARMModeRequested) {
770 if (!MCPU.empty())
771 getDriver().Diag(diag::err_cpu_unsupported_isa) << CPU << "ARM";
772 else
773 getDriver().Diag(diag::err_arch_unsupported_isa)
774 << tools::arm::getARMArch(MArch, getTriple()) << "ARM";
775 }
776
777 // Check to see if an explicit choice to use thumb has been made via
778 // -mthumb. For assembler files we must check for -mthumb in the options
779 // passed to the assembler via -Wa or -Xassembler.
780 bool IsThumb = false;
781 if (InputType != types::TY_PP_Asm)
782 IsThumb = Args.hasFlag(options::OPT_mthumb, options::OPT_mno_thumb,
783 ThumbDefault);
784 else {
785 // Ideally we would check for these flags in
786 // CollectArgsForIntegratedAssembler but we can't change the ArchName at
787 // that point. There is no assembler equivalent of -mno-thumb, -marm, or
788 // -mno-arm.
789 for (const auto *A :
790 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
791 for (StringRef Value : A->getValues()) {
792 if (Value == "-mthumb")
793 IsThumb = true;
794 }
795 }
796 }
797 // Assembly files should start in ARM mode, unless arch is M-profile, or
798 // -mthumb has been passed explicitly to the assembler. Windows is always
799 // thumb.
800 if (IsThumb || IsMProfile || getTriple().isOSWindows()) {
801 if (IsBigEndian)
802 ArchName = "thumbeb";
803 else
804 ArchName = "thumb";
805 }
806 Triple.setArchName(ArchName + Suffix.str());
807
808 bool isHardFloat =
809 (arm::getARMFloatABI(getDriver(), Triple, Args) == arm::FloatABI::Hard);
810 switch (Triple.getEnvironment()) {
811 case Triple::GNUEABI:
812 case Triple::GNUEABIHF:
813 Triple.setEnvironment(isHardFloat ? Triple::GNUEABIHF : Triple::GNUEABI);
814 break;
815 case Triple::EABI:
816 case Triple::EABIHF:
817 Triple.setEnvironment(isHardFloat ? Triple::EABIHF : Triple::EABI);
818 break;
819 case Triple::MuslEABI:
820 case Triple::MuslEABIHF:
821 Triple.setEnvironment(isHardFloat ? Triple::MuslEABIHF
822 : Triple::MuslEABI);
823 break;
824 default: {
825 arm::FloatABI DefaultABI = arm::getDefaultFloatABI(Triple);
826 if (DefaultABI != arm::FloatABI::Invalid &&
827 isHardFloat != (DefaultABI == arm::FloatABI::Hard)) {
828 Arg *ABIArg =
829 Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
830 options::OPT_mfloat_abi_EQ);
831 assert(ABIArg && "Non-default float abi expected to be from arg");
832 D.Diag(diag::err_drv_unsupported_opt_for_target)
833 << ABIArg->getAsString(Args) << Triple.getTriple();
834 }
835 break;
836 }
837 }
838
839 return Triple.getTriple();
840 }
841 }
842 }
843
ComputeEffectiveClangTriple(const ArgList & Args,types::ID InputType) const844 std::string ToolChain::ComputeEffectiveClangTriple(const ArgList &Args,
845 types::ID InputType) const {
846 return ComputeLLVMTriple(Args, InputType);
847 }
848
computeSysRoot() const849 std::string ToolChain::computeSysRoot() const {
850 return D.SysRoot;
851 }
852
AddClangSystemIncludeArgs(const ArgList & DriverArgs,ArgStringList & CC1Args) const853 void ToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
854 ArgStringList &CC1Args) const {
855 // Each toolchain should provide the appropriate include flags.
856 }
857
addClangTargetOptions(const ArgList & DriverArgs,ArgStringList & CC1Args,Action::OffloadKind DeviceOffloadKind) const858 void ToolChain::addClangTargetOptions(
859 const ArgList &DriverArgs, ArgStringList &CC1Args,
860 Action::OffloadKind DeviceOffloadKind) const {}
861
addClangWarningOptions(ArgStringList & CC1Args) const862 void ToolChain::addClangWarningOptions(ArgStringList &CC1Args) const {}
863
addProfileRTLibs(const llvm::opt::ArgList & Args,llvm::opt::ArgStringList & CmdArgs) const864 void ToolChain::addProfileRTLibs(const llvm::opt::ArgList &Args,
865 llvm::opt::ArgStringList &CmdArgs) const {
866 if (!needsProfileRT(Args) && !needsGCovInstrumentation(Args))
867 return;
868
869 CmdArgs.push_back(getCompilerRTArgString(Args, "profile"));
870 }
871
GetRuntimeLibType(const ArgList & Args) const872 ToolChain::RuntimeLibType ToolChain::GetRuntimeLibType(
873 const ArgList &Args) const {
874 const Arg* A = Args.getLastArg(options::OPT_rtlib_EQ);
875 StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_RTLIB;
876
877 // Only use "platform" in tests to override CLANG_DEFAULT_RTLIB!
878 if (LibName == "compiler-rt")
879 return ToolChain::RLT_CompilerRT;
880 else if (LibName == "libgcc")
881 return ToolChain::RLT_Libgcc;
882 else if (LibName == "platform")
883 return GetDefaultRuntimeLibType();
884
885 if (A)
886 getDriver().Diag(diag::err_drv_invalid_rtlib_name) << A->getAsString(Args);
887
888 return GetDefaultRuntimeLibType();
889 }
890
GetUnwindLibType(const ArgList & Args) const891 ToolChain::UnwindLibType ToolChain::GetUnwindLibType(
892 const ArgList &Args) const {
893 const Arg *A = Args.getLastArg(options::OPT_unwindlib_EQ);
894 StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_UNWINDLIB;
895
896 if (LibName == "none")
897 return ToolChain::UNW_None;
898 else if (LibName == "platform" || LibName == "") {
899 ToolChain::RuntimeLibType RtLibType = GetRuntimeLibType(Args);
900 if (RtLibType == ToolChain::RLT_CompilerRT)
901 return ToolChain::UNW_None;
902 else if (RtLibType == ToolChain::RLT_Libgcc)
903 return ToolChain::UNW_Libgcc;
904 } else if (LibName == "libunwind") {
905 if (GetRuntimeLibType(Args) == RLT_Libgcc)
906 getDriver().Diag(diag::err_drv_incompatible_unwindlib);
907 return ToolChain::UNW_CompilerRT;
908 } else if (LibName == "libgcc")
909 return ToolChain::UNW_Libgcc;
910
911 if (A)
912 getDriver().Diag(diag::err_drv_invalid_unwindlib_name)
913 << A->getAsString(Args);
914
915 return GetDefaultUnwindLibType();
916 }
917
GetCXXStdlibType(const ArgList & Args) const918 ToolChain::CXXStdlibType ToolChain::GetCXXStdlibType(const ArgList &Args) const{
919 const Arg *A = Args.getLastArg(options::OPT_stdlib_EQ);
920 StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_CXX_STDLIB;
921
922 // Only use "platform" in tests to override CLANG_DEFAULT_CXX_STDLIB!
923 if (LibName == "libc++")
924 return ToolChain::CST_Libcxx;
925 else if (LibName == "libstdc++")
926 return ToolChain::CST_Libstdcxx;
927 else if (LibName == "platform")
928 return GetDefaultCXXStdlibType();
929
930 if (A)
931 getDriver().Diag(diag::err_drv_invalid_stdlib_name) << A->getAsString(Args);
932
933 return GetDefaultCXXStdlibType();
934 }
935
936 /// Utility function to add a system include directory to CC1 arguments.
addSystemInclude(const ArgList & DriverArgs,ArgStringList & CC1Args,const Twine & Path)937 /*static*/ void ToolChain::addSystemInclude(const ArgList &DriverArgs,
938 ArgStringList &CC1Args,
939 const Twine &Path) {
940 CC1Args.push_back("-internal-isystem");
941 CC1Args.push_back(DriverArgs.MakeArgString(Path));
942 }
943
944 /// Utility function to add a system include directory with extern "C"
945 /// semantics to CC1 arguments.
946 ///
947 /// Note that this should be used rarely, and only for directories that
948 /// historically and for legacy reasons are treated as having implicit extern
949 /// "C" semantics. These semantics are *ignored* by and large today, but its
950 /// important to preserve the preprocessor changes resulting from the
951 /// classification.
addExternCSystemInclude(const ArgList & DriverArgs,ArgStringList & CC1Args,const Twine & Path)952 /*static*/ void ToolChain::addExternCSystemInclude(const ArgList &DriverArgs,
953 ArgStringList &CC1Args,
954 const Twine &Path) {
955 CC1Args.push_back("-internal-externc-isystem");
956 CC1Args.push_back(DriverArgs.MakeArgString(Path));
957 }
958
addExternCSystemIncludeIfExists(const ArgList & DriverArgs,ArgStringList & CC1Args,const Twine & Path)959 void ToolChain::addExternCSystemIncludeIfExists(const ArgList &DriverArgs,
960 ArgStringList &CC1Args,
961 const Twine &Path) {
962 if (llvm::sys::fs::exists(Path))
963 addExternCSystemInclude(DriverArgs, CC1Args, Path);
964 }
965
966 /// Utility function to add a list of system include directories to CC1.
addSystemIncludes(const ArgList & DriverArgs,ArgStringList & CC1Args,ArrayRef<StringRef> Paths)967 /*static*/ void ToolChain::addSystemIncludes(const ArgList &DriverArgs,
968 ArgStringList &CC1Args,
969 ArrayRef<StringRef> Paths) {
970 for (const auto &Path : Paths) {
971 CC1Args.push_back("-internal-isystem");
972 CC1Args.push_back(DriverArgs.MakeArgString(Path));
973 }
974 }
975
AddClangCXXStdlibIncludeArgs(const ArgList & DriverArgs,ArgStringList & CC1Args) const976 void ToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
977 ArgStringList &CC1Args) const {
978 // Header search paths should be handled by each of the subclasses.
979 // Historically, they have not been, and instead have been handled inside of
980 // the CC1-layer frontend. As the logic is hoisted out, this generic function
981 // will slowly stop being called.
982 //
983 // While it is being called, replicate a bit of a hack to propagate the
984 // '-stdlib=' flag down to CC1 so that it can in turn customize the C++
985 // header search paths with it. Once all systems are overriding this
986 // function, the CC1 flag and this line can be removed.
987 DriverArgs.AddAllArgs(CC1Args, options::OPT_stdlib_EQ);
988 }
989
AddClangCXXStdlibIsystemArgs(const llvm::opt::ArgList & DriverArgs,llvm::opt::ArgStringList & CC1Args) const990 void ToolChain::AddClangCXXStdlibIsystemArgs(
991 const llvm::opt::ArgList &DriverArgs,
992 llvm::opt::ArgStringList &CC1Args) const {
993 DriverArgs.ClaimAllArgs(options::OPT_stdlibxx_isystem);
994 if (!DriverArgs.hasArg(options::OPT_nostdincxx))
995 for (const auto &P :
996 DriverArgs.getAllArgValues(options::OPT_stdlibxx_isystem))
997 addSystemInclude(DriverArgs, CC1Args, P);
998 }
999
ShouldLinkCXXStdlib(const llvm::opt::ArgList & Args) const1000 bool ToolChain::ShouldLinkCXXStdlib(const llvm::opt::ArgList &Args) const {
1001 return getDriver().CCCIsCXX() &&
1002 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs,
1003 options::OPT_nostdlibxx);
1004 }
1005
AddCXXStdlibLibArgs(const ArgList & Args,ArgStringList & CmdArgs) const1006 void ToolChain::AddCXXStdlibLibArgs(const ArgList &Args,
1007 ArgStringList &CmdArgs) const {
1008 assert(!Args.hasArg(options::OPT_nostdlibxx) &&
1009 "should not have called this");
1010 CXXStdlibType Type = GetCXXStdlibType(Args);
1011
1012 switch (Type) {
1013 case ToolChain::CST_Libcxx:
1014 CmdArgs.push_back("-lc++");
1015 break;
1016
1017 case ToolChain::CST_Libstdcxx:
1018 CmdArgs.push_back("-lstdc++");
1019 break;
1020 }
1021 }
1022
AddFilePathLibArgs(const ArgList & Args,ArgStringList & CmdArgs) const1023 void ToolChain::AddFilePathLibArgs(const ArgList &Args,
1024 ArgStringList &CmdArgs) const {
1025 for (const auto &LibPath : getFilePaths())
1026 if(LibPath.length() > 0)
1027 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
1028 }
1029
AddCCKextLibArgs(const ArgList & Args,ArgStringList & CmdArgs) const1030 void ToolChain::AddCCKextLibArgs(const ArgList &Args,
1031 ArgStringList &CmdArgs) const {
1032 CmdArgs.push_back("-lcc_kext");
1033 }
1034
isFastMathRuntimeAvailable(const ArgList & Args,std::string & Path) const1035 bool ToolChain::isFastMathRuntimeAvailable(const ArgList &Args,
1036 std::string &Path) const {
1037 // Do not check for -fno-fast-math or -fno-unsafe-math when -Ofast passed
1038 // (to keep the linker options consistent with gcc and clang itself).
1039 if (!isOptimizationLevelFast(Args)) {
1040 // Check if -ffast-math or -funsafe-math.
1041 Arg *A =
1042 Args.getLastArg(options::OPT_ffast_math, options::OPT_fno_fast_math,
1043 options::OPT_funsafe_math_optimizations,
1044 options::OPT_fno_unsafe_math_optimizations);
1045
1046 if (!A || A->getOption().getID() == options::OPT_fno_fast_math ||
1047 A->getOption().getID() == options::OPT_fno_unsafe_math_optimizations)
1048 return false;
1049 }
1050 // If crtfastmath.o exists add it to the arguments.
1051 Path = GetFilePath("crtfastmath.o");
1052 return (Path != "crtfastmath.o"); // Not found.
1053 }
1054
addFastMathRuntimeIfAvailable(const ArgList & Args,ArgStringList & CmdArgs) const1055 bool ToolChain::addFastMathRuntimeIfAvailable(const ArgList &Args,
1056 ArgStringList &CmdArgs) const {
1057 std::string Path;
1058 if (isFastMathRuntimeAvailable(Args, Path)) {
1059 CmdArgs.push_back(Args.MakeArgString(Path));
1060 return true;
1061 }
1062
1063 return false;
1064 }
1065
getSupportedSanitizers() const1066 SanitizerMask ToolChain::getSupportedSanitizers() const {
1067 // Return sanitizers which don't require runtime support and are not
1068 // platform dependent.
1069
1070 SanitizerMask Res =
1071 (SanitizerKind::Undefined & ~SanitizerKind::Vptr &
1072 ~SanitizerKind::Function) |
1073 (SanitizerKind::CFI & ~SanitizerKind::CFIICall) |
1074 SanitizerKind::CFICastStrict | SanitizerKind::FloatDivideByZero |
1075 SanitizerKind::UnsignedIntegerOverflow |
1076 SanitizerKind::UnsignedShiftBase | SanitizerKind::ImplicitConversion |
1077 SanitizerKind::Nullability | SanitizerKind::LocalBounds;
1078 if (getTriple().getArch() == llvm::Triple::x86 ||
1079 getTriple().getArch() == llvm::Triple::x86_64 ||
1080 getTriple().getArch() == llvm::Triple::arm || getTriple().isWasm() ||
1081 getTriple().isAArch64())
1082 Res |= SanitizerKind::CFIICall;
1083 if (getTriple().getArch() == llvm::Triple::x86_64 ||
1084 getTriple().isAArch64(64) || getTriple().isRISCV())
1085 Res |= SanitizerKind::ShadowCallStack;
1086 if (getTriple().isAArch64(64))
1087 Res |= SanitizerKind::MemTag;
1088 return Res;
1089 }
1090
AddCudaIncludeArgs(const ArgList & DriverArgs,ArgStringList & CC1Args) const1091 void ToolChain::AddCudaIncludeArgs(const ArgList &DriverArgs,
1092 ArgStringList &CC1Args) const {}
1093
AddHIPIncludeArgs(const ArgList & DriverArgs,ArgStringList & CC1Args) const1094 void ToolChain::AddHIPIncludeArgs(const ArgList &DriverArgs,
1095 ArgStringList &CC1Args) const {}
1096
AddIAMCUIncludeArgs(const ArgList & DriverArgs,ArgStringList & CC1Args) const1097 void ToolChain::AddIAMCUIncludeArgs(const ArgList &DriverArgs,
1098 ArgStringList &CC1Args) const {}
1099
separateMSVCFullVersion(unsigned Version)1100 static VersionTuple separateMSVCFullVersion(unsigned Version) {
1101 if (Version < 100)
1102 return VersionTuple(Version);
1103
1104 if (Version < 10000)
1105 return VersionTuple(Version / 100, Version % 100);
1106
1107 unsigned Build = 0, Factor = 1;
1108 for (; Version > 10000; Version = Version / 10, Factor = Factor * 10)
1109 Build = Build + (Version % 10) * Factor;
1110 return VersionTuple(Version / 100, Version % 100, Build);
1111 }
1112
1113 VersionTuple
computeMSVCVersion(const Driver * D,const llvm::opt::ArgList & Args) const1114 ToolChain::computeMSVCVersion(const Driver *D,
1115 const llvm::opt::ArgList &Args) const {
1116 const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version);
1117 const Arg *MSCompatibilityVersion =
1118 Args.getLastArg(options::OPT_fms_compatibility_version);
1119
1120 if (MSCVersion && MSCompatibilityVersion) {
1121 if (D)
1122 D->Diag(diag::err_drv_argument_not_allowed_with)
1123 << MSCVersion->getAsString(Args)
1124 << MSCompatibilityVersion->getAsString(Args);
1125 return VersionTuple();
1126 }
1127
1128 if (MSCompatibilityVersion) {
1129 VersionTuple MSVT;
1130 if (MSVT.tryParse(MSCompatibilityVersion->getValue())) {
1131 if (D)
1132 D->Diag(diag::err_drv_invalid_value)
1133 << MSCompatibilityVersion->getAsString(Args)
1134 << MSCompatibilityVersion->getValue();
1135 } else {
1136 return MSVT;
1137 }
1138 }
1139
1140 if (MSCVersion) {
1141 unsigned Version = 0;
1142 if (StringRef(MSCVersion->getValue()).getAsInteger(10, Version)) {
1143 if (D)
1144 D->Diag(diag::err_drv_invalid_value)
1145 << MSCVersion->getAsString(Args) << MSCVersion->getValue();
1146 } else {
1147 return separateMSVCFullVersion(Version);
1148 }
1149 }
1150
1151 return VersionTuple();
1152 }
1153
TranslateOpenMPTargetArgs(const llvm::opt::DerivedArgList & Args,bool SameTripleAsHost,SmallVectorImpl<llvm::opt::Arg * > & AllocatedArgs) const1154 llvm::opt::DerivedArgList *ToolChain::TranslateOpenMPTargetArgs(
1155 const llvm::opt::DerivedArgList &Args, bool SameTripleAsHost,
1156 SmallVectorImpl<llvm::opt::Arg *> &AllocatedArgs) const {
1157 DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
1158 const OptTable &Opts = getDriver().getOpts();
1159 bool Modified = false;
1160
1161 // Handle -Xopenmp-target flags
1162 for (auto *A : Args) {
1163 // Exclude flags which may only apply to the host toolchain.
1164 // Do not exclude flags when the host triple (AuxTriple)
1165 // matches the current toolchain triple. If it is not present
1166 // at all, target and host share a toolchain.
1167 if (A->getOption().matches(options::OPT_m_Group)) {
1168 if (SameTripleAsHost)
1169 DAL->append(A);
1170 else
1171 Modified = true;
1172 continue;
1173 }
1174
1175 unsigned Index;
1176 unsigned Prev;
1177 bool XOpenMPTargetNoTriple =
1178 A->getOption().matches(options::OPT_Xopenmp_target);
1179
1180 if (A->getOption().matches(options::OPT_Xopenmp_target_EQ)) {
1181 // Passing device args: -Xopenmp-target=<triple> -opt=val.
1182 if (A->getValue(0) == getTripleString())
1183 Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
1184 else
1185 continue;
1186 } else if (XOpenMPTargetNoTriple) {
1187 // Passing device args: -Xopenmp-target -opt=val.
1188 Index = Args.getBaseArgs().MakeIndex(A->getValue(0));
1189 } else {
1190 DAL->append(A);
1191 continue;
1192 }
1193
1194 // Parse the argument to -Xopenmp-target.
1195 Prev = Index;
1196 std::unique_ptr<Arg> XOpenMPTargetArg(Opts.ParseOneArg(Args, Index));
1197 if (!XOpenMPTargetArg || Index > Prev + 1) {
1198 getDriver().Diag(diag::err_drv_invalid_Xopenmp_target_with_args)
1199 << A->getAsString(Args);
1200 continue;
1201 }
1202 if (XOpenMPTargetNoTriple && XOpenMPTargetArg &&
1203 Args.getAllArgValues(options::OPT_fopenmp_targets_EQ).size() != 1) {
1204 getDriver().Diag(diag::err_drv_Xopenmp_target_missing_triple);
1205 continue;
1206 }
1207 XOpenMPTargetArg->setBaseArg(A);
1208 A = XOpenMPTargetArg.release();
1209 AllocatedArgs.push_back(A);
1210 DAL->append(A);
1211 Modified = true;
1212 }
1213
1214 if (Modified)
1215 return DAL;
1216
1217 delete DAL;
1218 return nullptr;
1219 }
1220
1221 // TODO: Currently argument values separated by space e.g.
1222 // -Xclang -mframe-pointer=no cannot be passed by -Xarch_. This should be
1223 // fixed.
TranslateXarchArgs(const llvm::opt::DerivedArgList & Args,llvm::opt::Arg * & A,llvm::opt::DerivedArgList * DAL,SmallVectorImpl<llvm::opt::Arg * > * AllocatedArgs) const1224 void ToolChain::TranslateXarchArgs(
1225 const llvm::opt::DerivedArgList &Args, llvm::opt::Arg *&A,
1226 llvm::opt::DerivedArgList *DAL,
1227 SmallVectorImpl<llvm::opt::Arg *> *AllocatedArgs) const {
1228 const OptTable &Opts = getDriver().getOpts();
1229 unsigned ValuePos = 1;
1230 if (A->getOption().matches(options::OPT_Xarch_device) ||
1231 A->getOption().matches(options::OPT_Xarch_host))
1232 ValuePos = 0;
1233
1234 unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(ValuePos));
1235 unsigned Prev = Index;
1236 std::unique_ptr<llvm::opt::Arg> XarchArg(Opts.ParseOneArg(Args, Index));
1237
1238 // If the argument parsing failed or more than one argument was
1239 // consumed, the -Xarch_ argument's parameter tried to consume
1240 // extra arguments. Emit an error and ignore.
1241 //
1242 // We also want to disallow any options which would alter the
1243 // driver behavior; that isn't going to work in our model. We
1244 // use options::NoXarchOption to control this.
1245 if (!XarchArg || Index > Prev + 1) {
1246 getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args)
1247 << A->getAsString(Args);
1248 return;
1249 } else if (XarchArg->getOption().hasFlag(options::NoXarchOption)) {
1250 auto &Diags = getDriver().getDiags();
1251 unsigned DiagID =
1252 Diags.getCustomDiagID(DiagnosticsEngine::Error,
1253 "invalid Xarch argument: '%0', not all driver "
1254 "options can be forwared via Xarch argument");
1255 Diags.Report(DiagID) << A->getAsString(Args);
1256 return;
1257 }
1258 XarchArg->setBaseArg(A);
1259 A = XarchArg.release();
1260 if (!AllocatedArgs)
1261 DAL->AddSynthesizedArg(A);
1262 else
1263 AllocatedArgs->push_back(A);
1264 }
1265
TranslateXarchArgs(const llvm::opt::DerivedArgList & Args,StringRef BoundArch,Action::OffloadKind OFK,SmallVectorImpl<llvm::opt::Arg * > * AllocatedArgs) const1266 llvm::opt::DerivedArgList *ToolChain::TranslateXarchArgs(
1267 const llvm::opt::DerivedArgList &Args, StringRef BoundArch,
1268 Action::OffloadKind OFK,
1269 SmallVectorImpl<llvm::opt::Arg *> *AllocatedArgs) const {
1270 DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
1271 bool Modified = false;
1272
1273 bool IsGPU = OFK == Action::OFK_Cuda || OFK == Action::OFK_HIP;
1274 for (Arg *A : Args) {
1275 bool NeedTrans = false;
1276 bool Skip = false;
1277 if (A->getOption().matches(options::OPT_Xarch_device)) {
1278 NeedTrans = IsGPU;
1279 Skip = !IsGPU;
1280 } else if (A->getOption().matches(options::OPT_Xarch_host)) {
1281 NeedTrans = !IsGPU;
1282 Skip = IsGPU;
1283 } else if (A->getOption().matches(options::OPT_Xarch__) && IsGPU) {
1284 // Do not translate -Xarch_ options for non CUDA/HIP toolchain since
1285 // they may need special translation.
1286 // Skip this argument unless the architecture matches BoundArch
1287 if (BoundArch.empty() || A->getValue(0) != BoundArch)
1288 Skip = true;
1289 else
1290 NeedTrans = true;
1291 }
1292 if (NeedTrans || Skip)
1293 Modified = true;
1294 if (NeedTrans)
1295 TranslateXarchArgs(Args, A, DAL, AllocatedArgs);
1296 if (!Skip)
1297 DAL->append(A);
1298 }
1299
1300 if (Modified)
1301 return DAL;
1302
1303 delete DAL;
1304 return nullptr;
1305 }
1306