1 //===--- Driver.cpp - Clang GCC Compatible Driver -------------------------===//
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/Driver.h"
10 #include "InputInfo.h"
11 #include "ToolChains/AIX.h"
12 #include "ToolChains/AMDGPU.h"
13 #include "ToolChains/AVR.h"
14 #include "ToolChains/Ananas.h"
15 #include "ToolChains/BareMetal.h"
16 #include "ToolChains/Clang.h"
17 #include "ToolChains/CloudABI.h"
18 #include "ToolChains/Contiki.h"
19 #include "ToolChains/CrossWindows.h"
20 #include "ToolChains/Cuda.h"
21 #include "ToolChains/Darwin.h"
22 #include "ToolChains/DragonFly.h"
23 #include "ToolChains/FreeBSD.h"
24 #include "ToolChains/Fuchsia.h"
25 #include "ToolChains/Gnu.h"
26 #include "ToolChains/HIP.h"
27 #include "ToolChains/Haiku.h"
28 #include "ToolChains/Hexagon.h"
29 #include "ToolChains/Hurd.h"
30 #include "ToolChains/Lanai.h"
31 #include "ToolChains/Linux.h"
32 #include "ToolChains/MSP430.h"
33 #include "ToolChains/MSVC.h"
34 #include "ToolChains/MinGW.h"
35 #include "ToolChains/Minix.h"
36 #include "ToolChains/MipsLinux.h"
37 #include "ToolChains/Myriad.h"
38 #include "ToolChains/NaCl.h"
39 #include "ToolChains/NetBSD.h"
40 #include "ToolChains/OpenBSD.h"
41 #include "ToolChains/PPCLinux.h"
42 #include "ToolChains/PS4CPU.h"
43 #include "ToolChains/RISCVToolchain.h"
44 #include "ToolChains/Solaris.h"
45 #include "ToolChains/TCE.h"
46 #include "ToolChains/VEToolchain.h"
47 #include "ToolChains/WebAssembly.h"
48 #include "ToolChains/XCore.h"
49 #include "ToolChains/ZOS.h"
50 #include "clang/Basic/TargetID.h"
51 #include "clang/Basic/Version.h"
52 #include "clang/Config/config.h"
53 #include "clang/Driver/Action.h"
54 #include "clang/Driver/Compilation.h"
55 #include "clang/Driver/DriverDiagnostic.h"
56 #include "clang/Driver/Job.h"
57 #include "clang/Driver/Options.h"
58 #include "clang/Driver/SanitizerArgs.h"
59 #include "clang/Driver/Tool.h"
60 #include "clang/Driver/ToolChain.h"
61 #include "llvm/ADT/ArrayRef.h"
62 #include "llvm/ADT/STLExtras.h"
63 #include "llvm/ADT/SmallSet.h"
64 #include "llvm/ADT/StringExtras.h"
65 #include "llvm/ADT/StringSet.h"
66 #include "llvm/ADT/StringSwitch.h"
67 #include "llvm/Config/llvm-config.h"
68 #include "llvm/Option/Arg.h"
69 #include "llvm/Option/ArgList.h"
70 #include "llvm/Option/OptSpecifier.h"
71 #include "llvm/Option/OptTable.h"
72 #include "llvm/Option/Option.h"
73 #include "llvm/Support/CommandLine.h"
74 #include "llvm/Support/ErrorHandling.h"
75 #include "llvm/Support/ExitCodes.h"
76 #include "llvm/Support/FileSystem.h"
77 #include "llvm/Support/FormatVariadic.h"
78 #include "llvm/Support/Host.h"
79 #include "llvm/Support/Path.h"
80 #include "llvm/Support/PrettyStackTrace.h"
81 #include "llvm/Support/Process.h"
82 #include "llvm/Support/Program.h"
83 #include "llvm/Support/StringSaver.h"
84 #include "llvm/Support/TargetRegistry.h"
85 #include "llvm/Support/VirtualFileSystem.h"
86 #include "llvm/Support/raw_ostream.h"
87 #include <map>
88 #include <memory>
89 #include <utility>
90 #if LLVM_ON_UNIX
91 #include <unistd.h> // getpid
92 #endif
93
94 using namespace clang::driver;
95 using namespace clang;
96 using namespace llvm::opt;
97
getHIPOffloadTargetTriple()98 static llvm::Triple getHIPOffloadTargetTriple() {
99 static const llvm::Triple T("amdgcn-amd-amdhsa");
100 return T;
101 }
102
103 // static
GetResourcesPath(StringRef BinaryPath,StringRef CustomResourceDir)104 std::string Driver::GetResourcesPath(StringRef BinaryPath,
105 StringRef CustomResourceDir) {
106 // Since the resource directory is embedded in the module hash, it's important
107 // that all places that need it call this function, so that they get the
108 // exact same string ("a/../b/" and "b/" get different hashes, for example).
109
110 // Dir is bin/ or lib/, depending on where BinaryPath is.
111 std::string Dir = std::string(llvm::sys::path::parent_path(BinaryPath));
112
113 SmallString<128> P(Dir);
114 if (CustomResourceDir != "") {
115 llvm::sys::path::append(P, CustomResourceDir);
116 } else {
117 // On Windows, libclang.dll is in bin/.
118 // On non-Windows, libclang.so/.dylib is in lib/.
119 // With a static-library build of libclang, LibClangPath will contain the
120 // path of the embedding binary, which for LLVM binaries will be in bin/.
121 // ../lib gets us to lib/ in both cases.
122 P = llvm::sys::path::parent_path(Dir);
123 llvm::sys::path::append(P, Twine("lib") + CLANG_LIBDIR_SUFFIX, "clang",
124 CLANG_VERSION_STRING);
125 }
126
127 return std::string(P.str());
128 }
129
Driver(StringRef ClangExecutable,StringRef TargetTriple,DiagnosticsEngine & Diags,std::string Title,IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS)130 Driver::Driver(StringRef ClangExecutable, StringRef TargetTriple,
131 DiagnosticsEngine &Diags, std::string Title,
132 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS)
133 : Diags(Diags), VFS(std::move(VFS)), Mode(GCCMode),
134 SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone), LTOMode(LTOK_None),
135 ClangExecutable(ClangExecutable), SysRoot(DEFAULT_SYSROOT),
136 DriverTitle(Title), CCPrintOptionsFilename(nullptr),
137 CCPrintHeadersFilename(nullptr), CCLogDiagnosticsFilename(nullptr),
138 CCCPrintBindings(false), CCPrintOptions(false), CCPrintHeaders(false),
139 CCLogDiagnostics(false), CCGenDiagnostics(false),
140 TargetTriple(TargetTriple), CCCGenericGCCName(""), Saver(Alloc),
141 CheckInputsExist(true), GenReproducer(false),
142 SuppressMissingInputWarning(false) {
143 // Provide a sane fallback if no VFS is specified.
144 if (!this->VFS)
145 this->VFS = llvm::vfs::getRealFileSystem();
146
147 Name = std::string(llvm::sys::path::filename(ClangExecutable));
148 Dir = std::string(llvm::sys::path::parent_path(ClangExecutable));
149 InstalledDir = Dir; // Provide a sensible default installed dir.
150
151 if ((!SysRoot.empty()) && llvm::sys::path::is_relative(SysRoot)) {
152 // Prepend InstalledDir if SysRoot is relative
153 SmallString<128> P(InstalledDir);
154 llvm::sys::path::append(P, SysRoot);
155 SysRoot = std::string(P);
156 }
157
158 #if defined(CLANG_CONFIG_FILE_SYSTEM_DIR)
159 SystemConfigDir = CLANG_CONFIG_FILE_SYSTEM_DIR;
160 #endif
161 #if defined(CLANG_CONFIG_FILE_USER_DIR)
162 UserConfigDir = CLANG_CONFIG_FILE_USER_DIR;
163 #endif
164
165 // Compute the path to the resource directory.
166 ResourceDir = GetResourcesPath(ClangExecutable, CLANG_RESOURCE_DIR);
167 }
168
ParseDriverMode(StringRef ProgramName,ArrayRef<const char * > Args)169 void Driver::ParseDriverMode(StringRef ProgramName,
170 ArrayRef<const char *> Args) {
171 if (ClangNameParts.isEmpty())
172 ClangNameParts = ToolChain::getTargetAndModeFromProgramName(ProgramName);
173 setDriverModeFromOption(ClangNameParts.DriverMode);
174
175 for (const char *ArgPtr : Args) {
176 // Ignore nullptrs, they are the response file's EOL markers.
177 if (ArgPtr == nullptr)
178 continue;
179 const StringRef Arg = ArgPtr;
180 setDriverModeFromOption(Arg);
181 }
182 }
183
setDriverModeFromOption(StringRef Opt)184 void Driver::setDriverModeFromOption(StringRef Opt) {
185 const std::string OptName =
186 getOpts().getOption(options::OPT_driver_mode).getPrefixedName();
187 if (!Opt.startswith(OptName))
188 return;
189 StringRef Value = Opt.drop_front(OptName.size());
190
191 if (auto M = llvm::StringSwitch<llvm::Optional<DriverMode>>(Value)
192 .Case("gcc", GCCMode)
193 .Case("g++", GXXMode)
194 .Case("cpp", CPPMode)
195 .Case("cl", CLMode)
196 .Case("flang", FlangMode)
197 .Default(None))
198 Mode = *M;
199 else
200 Diag(diag::err_drv_unsupported_option_argument) << OptName << Value;
201 }
202
ParseArgStrings(ArrayRef<const char * > ArgStrings,bool IsClCompatMode,bool & ContainsError)203 InputArgList Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings,
204 bool IsClCompatMode,
205 bool &ContainsError) {
206 llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
207 ContainsError = false;
208
209 unsigned IncludedFlagsBitmask;
210 unsigned ExcludedFlagsBitmask;
211 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
212 getIncludeExcludeOptionFlagMasks(IsClCompatMode);
213
214 // Make sure that Flang-only options don't pollute the Clang output
215 // TODO: Make sure that Clang-only options don't pollute Flang output
216 if (!IsFlangMode())
217 ExcludedFlagsBitmask |= options::FlangOnlyOption;
218
219 unsigned MissingArgIndex, MissingArgCount;
220 InputArgList Args =
221 getOpts().ParseArgs(ArgStrings, MissingArgIndex, MissingArgCount,
222 IncludedFlagsBitmask, ExcludedFlagsBitmask);
223
224 // Check for missing argument error.
225 if (MissingArgCount) {
226 Diag(diag::err_drv_missing_argument)
227 << Args.getArgString(MissingArgIndex) << MissingArgCount;
228 ContainsError |=
229 Diags.getDiagnosticLevel(diag::err_drv_missing_argument,
230 SourceLocation()) > DiagnosticsEngine::Warning;
231 }
232
233 // Check for unsupported options.
234 for (const Arg *A : Args) {
235 if (A->getOption().hasFlag(options::Unsupported)) {
236 unsigned DiagID;
237 auto ArgString = A->getAsString(Args);
238 std::string Nearest;
239 if (getOpts().findNearest(
240 ArgString, Nearest, IncludedFlagsBitmask,
241 ExcludedFlagsBitmask | options::Unsupported) > 1) {
242 DiagID = diag::err_drv_unsupported_opt;
243 Diag(DiagID) << ArgString;
244 } else {
245 DiagID = diag::err_drv_unsupported_opt_with_suggestion;
246 Diag(DiagID) << ArgString << Nearest;
247 }
248 ContainsError |= Diags.getDiagnosticLevel(DiagID, SourceLocation()) >
249 DiagnosticsEngine::Warning;
250 continue;
251 }
252
253 // Warn about -mcpu= without an argument.
254 if (A->getOption().matches(options::OPT_mcpu_EQ) && A->containsValue("")) {
255 Diag(diag::warn_drv_empty_joined_argument) << A->getAsString(Args);
256 ContainsError |= Diags.getDiagnosticLevel(
257 diag::warn_drv_empty_joined_argument,
258 SourceLocation()) > DiagnosticsEngine::Warning;
259 }
260 }
261
262 for (const Arg *A : Args.filtered(options::OPT_UNKNOWN)) {
263 unsigned DiagID;
264 auto ArgString = A->getAsString(Args);
265 std::string Nearest;
266 if (getOpts().findNearest(
267 ArgString, Nearest, IncludedFlagsBitmask, ExcludedFlagsBitmask) > 1) {
268 DiagID = IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl
269 : diag::err_drv_unknown_argument;
270 Diags.Report(DiagID) << ArgString;
271 } else {
272 DiagID = IsCLMode()
273 ? diag::warn_drv_unknown_argument_clang_cl_with_suggestion
274 : diag::err_drv_unknown_argument_with_suggestion;
275 Diags.Report(DiagID) << ArgString << Nearest;
276 }
277 ContainsError |= Diags.getDiagnosticLevel(DiagID, SourceLocation()) >
278 DiagnosticsEngine::Warning;
279 }
280
281 return Args;
282 }
283
284 // Determine which compilation mode we are in. We look for options which
285 // affect the phase, starting with the earliest phases, and record which
286 // option we used to determine the final phase.
getFinalPhase(const DerivedArgList & DAL,Arg ** FinalPhaseArg) const287 phases::ID Driver::getFinalPhase(const DerivedArgList &DAL,
288 Arg **FinalPhaseArg) const {
289 Arg *PhaseArg = nullptr;
290 phases::ID FinalPhase;
291
292 // -{E,EP,P,M,MM} only run the preprocessor.
293 if (CCCIsCPP() || (PhaseArg = DAL.getLastArg(options::OPT_E)) ||
294 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_EP)) ||
295 (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM)) ||
296 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_P))) {
297 FinalPhase = phases::Preprocess;
298
299 // --precompile only runs up to precompilation.
300 } else if ((PhaseArg = DAL.getLastArg(options::OPT__precompile))) {
301 FinalPhase = phases::Precompile;
302
303 // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
304 } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
305 (PhaseArg = DAL.getLastArg(options::OPT_print_supported_cpus)) ||
306 (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) ||
307 (PhaseArg = DAL.getLastArg(options::OPT_verify_pch)) ||
308 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) ||
309 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) ||
310 (PhaseArg = DAL.getLastArg(options::OPT__migrate)) ||
311 (PhaseArg = DAL.getLastArg(options::OPT__analyze)) ||
312 (PhaseArg = DAL.getLastArg(options::OPT_emit_ast))) {
313 FinalPhase = phases::Compile;
314
315 // -S only runs up to the backend.
316 } else if ((PhaseArg = DAL.getLastArg(options::OPT_S))) {
317 FinalPhase = phases::Backend;
318
319 // -c compilation only runs up to the assembler.
320 } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) {
321 FinalPhase = phases::Assemble;
322
323 // Otherwise do everything.
324 } else
325 FinalPhase = phases::Link;
326
327 if (FinalPhaseArg)
328 *FinalPhaseArg = PhaseArg;
329
330 return FinalPhase;
331 }
332
MakeInputArg(DerivedArgList & Args,const OptTable & Opts,StringRef Value,bool Claim=true)333 static Arg *MakeInputArg(DerivedArgList &Args, const OptTable &Opts,
334 StringRef Value, bool Claim = true) {
335 Arg *A = new Arg(Opts.getOption(options::OPT_INPUT), Value,
336 Args.getBaseArgs().MakeIndex(Value), Value.data());
337 Args.AddSynthesizedArg(A);
338 if (Claim)
339 A->claim();
340 return A;
341 }
342
TranslateInputArgs(const InputArgList & Args) const343 DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
344 const llvm::opt::OptTable &Opts = getOpts();
345 DerivedArgList *DAL = new DerivedArgList(Args);
346
347 bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
348 bool HasNostdlibxx = Args.hasArg(options::OPT_nostdlibxx);
349 bool HasNodefaultlib = Args.hasArg(options::OPT_nodefaultlibs);
350 for (Arg *A : Args) {
351 // Unfortunately, we have to parse some forwarding options (-Xassembler,
352 // -Xlinker, -Xpreprocessor) because we either integrate their functionality
353 // (assembler and preprocessor), or bypass a previous driver ('collect2').
354
355 // Rewrite linker options, to replace --no-demangle with a custom internal
356 // option.
357 if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
358 A->getOption().matches(options::OPT_Xlinker)) &&
359 A->containsValue("--no-demangle")) {
360 // Add the rewritten no-demangle argument.
361 DAL->AddFlagArg(A, Opts.getOption(options::OPT_Z_Xlinker__no_demangle));
362
363 // Add the remaining values as Xlinker arguments.
364 for (StringRef Val : A->getValues())
365 if (Val != "--no-demangle")
366 DAL->AddSeparateArg(A, Opts.getOption(options::OPT_Xlinker), Val);
367
368 continue;
369 }
370
371 // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
372 // some build systems. We don't try to be complete here because we don't
373 // care to encourage this usage model.
374 if (A->getOption().matches(options::OPT_Wp_COMMA) &&
375 (A->getValue(0) == StringRef("-MD") ||
376 A->getValue(0) == StringRef("-MMD"))) {
377 // Rewrite to -MD/-MMD along with -MF.
378 if (A->getValue(0) == StringRef("-MD"))
379 DAL->AddFlagArg(A, Opts.getOption(options::OPT_MD));
380 else
381 DAL->AddFlagArg(A, Opts.getOption(options::OPT_MMD));
382 if (A->getNumValues() == 2)
383 DAL->AddSeparateArg(A, Opts.getOption(options::OPT_MF), A->getValue(1));
384 continue;
385 }
386
387 // Rewrite reserved library names.
388 if (A->getOption().matches(options::OPT_l)) {
389 StringRef Value = A->getValue();
390
391 // Rewrite unless -nostdlib is present.
392 if (!HasNostdlib && !HasNodefaultlib && !HasNostdlibxx &&
393 Value == "stdc++") {
394 DAL->AddFlagArg(A, Opts.getOption(options::OPT_Z_reserved_lib_stdcxx));
395 continue;
396 }
397
398 // Rewrite unconditionally.
399 if (Value == "cc_kext") {
400 DAL->AddFlagArg(A, Opts.getOption(options::OPT_Z_reserved_lib_cckext));
401 continue;
402 }
403 }
404
405 // Pick up inputs via the -- option.
406 if (A->getOption().matches(options::OPT__DASH_DASH)) {
407 A->claim();
408 for (StringRef Val : A->getValues())
409 DAL->append(MakeInputArg(*DAL, Opts, Val, false));
410 continue;
411 }
412
413 DAL->append(A);
414 }
415
416 // Enforce -static if -miamcu is present.
417 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false))
418 DAL->AddFlagArg(0, Opts.getOption(options::OPT_static));
419
420 // Add a default value of -mlinker-version=, if one was given and the user
421 // didn't specify one.
422 #if defined(HOST_LINK_VERSION)
423 if (!Args.hasArg(options::OPT_mlinker_version_EQ) &&
424 strlen(HOST_LINK_VERSION) > 0) {
425 DAL->AddJoinedArg(0, Opts.getOption(options::OPT_mlinker_version_EQ),
426 HOST_LINK_VERSION);
427 DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
428 }
429 #endif
430
431 return DAL;
432 }
433
434 /// Compute target triple from args.
435 ///
436 /// This routine provides the logic to compute a target triple from various
437 /// args passed to the driver and the default triple string.
computeTargetTriple(const Driver & D,StringRef TargetTriple,const ArgList & Args,StringRef DarwinArchName="")438 static llvm::Triple computeTargetTriple(const Driver &D,
439 StringRef TargetTriple,
440 const ArgList &Args,
441 StringRef DarwinArchName = "") {
442 // FIXME: Already done in Compilation *Driver::BuildCompilation
443 if (const Arg *A = Args.getLastArg(options::OPT_target))
444 TargetTriple = A->getValue();
445
446 llvm::Triple Target(llvm::Triple::normalize(TargetTriple));
447
448 // GNU/Hurd's triples should have been -hurd-gnu*, but were historically made
449 // -gnu* only, and we can not change this, so we have to detect that case as
450 // being the Hurd OS.
451 if (TargetTriple.find("-unknown-gnu") != StringRef::npos ||
452 TargetTriple.find("-pc-gnu") != StringRef::npos)
453 Target.setOSName("hurd");
454
455 // Handle Apple-specific options available here.
456 if (Target.isOSBinFormatMachO()) {
457 // If an explicit Darwin arch name is given, that trumps all.
458 if (!DarwinArchName.empty()) {
459 tools::darwin::setTripleTypeForMachOArchName(Target, DarwinArchName);
460 return Target;
461 }
462
463 // Handle the Darwin '-arch' flag.
464 if (Arg *A = Args.getLastArg(options::OPT_arch)) {
465 StringRef ArchName = A->getValue();
466 tools::darwin::setTripleTypeForMachOArchName(Target, ArchName);
467 }
468 }
469
470 // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
471 // '-mbig-endian'/'-EB'.
472 if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
473 options::OPT_mbig_endian)) {
474 if (A->getOption().matches(options::OPT_mlittle_endian)) {
475 llvm::Triple LE = Target.getLittleEndianArchVariant();
476 if (LE.getArch() != llvm::Triple::UnknownArch)
477 Target = std::move(LE);
478 } else {
479 llvm::Triple BE = Target.getBigEndianArchVariant();
480 if (BE.getArch() != llvm::Triple::UnknownArch)
481 Target = std::move(BE);
482 }
483 }
484
485 // Skip further flag support on OSes which don't support '-m32' or '-m64'.
486 if (Target.getArch() == llvm::Triple::tce ||
487 Target.getOS() == llvm::Triple::Minix)
488 return Target;
489
490 // On AIX, the env OBJECT_MODE may affect the resulting arch variant.
491 if (Target.isOSAIX()) {
492 if (Optional<std::string> ObjectModeValue =
493 llvm::sys::Process::GetEnv("OBJECT_MODE")) {
494 StringRef ObjectMode = *ObjectModeValue;
495 llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
496
497 if (ObjectMode.equals("64")) {
498 AT = Target.get64BitArchVariant().getArch();
499 } else if (ObjectMode.equals("32")) {
500 AT = Target.get32BitArchVariant().getArch();
501 } else {
502 D.Diag(diag::err_drv_invalid_object_mode) << ObjectMode;
503 }
504
505 if (AT != llvm::Triple::UnknownArch && AT != Target.getArch())
506 Target.setArch(AT);
507 }
508 }
509
510 // Handle pseudo-target flags '-m64', '-mx32', '-m32' and '-m16'.
511 Arg *A = Args.getLastArg(options::OPT_m64, options::OPT_mx32,
512 options::OPT_m32, options::OPT_m16);
513 if (A) {
514 llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
515
516 if (A->getOption().matches(options::OPT_m64)) {
517 AT = Target.get64BitArchVariant().getArch();
518 if (Target.getEnvironment() == llvm::Triple::GNUX32)
519 Target.setEnvironment(llvm::Triple::GNU);
520 } else if (A->getOption().matches(options::OPT_mx32) &&
521 Target.get64BitArchVariant().getArch() == llvm::Triple::x86_64) {
522 AT = llvm::Triple::x86_64;
523 Target.setEnvironment(llvm::Triple::GNUX32);
524 } else if (A->getOption().matches(options::OPT_m32)) {
525 AT = Target.get32BitArchVariant().getArch();
526 if (Target.getEnvironment() == llvm::Triple::GNUX32)
527 Target.setEnvironment(llvm::Triple::GNU);
528 } else if (A->getOption().matches(options::OPT_m16) &&
529 Target.get32BitArchVariant().getArch() == llvm::Triple::x86) {
530 AT = llvm::Triple::x86;
531 Target.setEnvironment(llvm::Triple::CODE16);
532 }
533
534 if (AT != llvm::Triple::UnknownArch && AT != Target.getArch())
535 Target.setArch(AT);
536 }
537
538 // Handle -miamcu flag.
539 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
540 if (Target.get32BitArchVariant().getArch() != llvm::Triple::x86)
541 D.Diag(diag::err_drv_unsupported_opt_for_target) << "-miamcu"
542 << Target.str();
543
544 if (A && !A->getOption().matches(options::OPT_m32))
545 D.Diag(diag::err_drv_argument_not_allowed_with)
546 << "-miamcu" << A->getBaseArg().getAsString(Args);
547
548 Target.setArch(llvm::Triple::x86);
549 Target.setArchName("i586");
550 Target.setEnvironment(llvm::Triple::UnknownEnvironment);
551 Target.setEnvironmentName("");
552 Target.setOS(llvm::Triple::ELFIAMCU);
553 Target.setVendor(llvm::Triple::UnknownVendor);
554 Target.setVendorName("intel");
555 }
556
557 // If target is MIPS adjust the target triple
558 // accordingly to provided ABI name.
559 A = Args.getLastArg(options::OPT_mabi_EQ);
560 if (A && Target.isMIPS()) {
561 StringRef ABIName = A->getValue();
562 if (ABIName == "32") {
563 Target = Target.get32BitArchVariant();
564 if (Target.getEnvironment() == llvm::Triple::GNUABI64 ||
565 Target.getEnvironment() == llvm::Triple::GNUABIN32)
566 Target.setEnvironment(llvm::Triple::GNU);
567 } else if (ABIName == "n32") {
568 Target = Target.get64BitArchVariant();
569 if (Target.getEnvironment() == llvm::Triple::GNU ||
570 Target.getEnvironment() == llvm::Triple::GNUABI64)
571 Target.setEnvironment(llvm::Triple::GNUABIN32);
572 } else if (ABIName == "64") {
573 Target = Target.get64BitArchVariant();
574 if (Target.getEnvironment() == llvm::Triple::GNU ||
575 Target.getEnvironment() == llvm::Triple::GNUABIN32)
576 Target.setEnvironment(llvm::Triple::GNUABI64);
577 }
578 }
579
580 // If target is RISC-V adjust the target triple according to
581 // provided architecture name
582 A = Args.getLastArg(options::OPT_march_EQ);
583 if (A && Target.isRISCV()) {
584 StringRef ArchName = A->getValue();
585 if (ArchName.startswith_lower("rv32"))
586 Target.setArch(llvm::Triple::riscv32);
587 else if (ArchName.startswith_lower("rv64"))
588 Target.setArch(llvm::Triple::riscv64);
589 }
590
591 return Target;
592 }
593
594 // Parse the LTO options and record the type of LTO compilation
595 // based on which -f(no-)?lto(=.*)? option occurs last.
setLTOMode(const llvm::opt::ArgList & Args)596 void Driver::setLTOMode(const llvm::opt::ArgList &Args) {
597 LTOMode = LTOK_None;
598 if (!Args.hasFlag(options::OPT_flto, options::OPT_flto_EQ,
599 options::OPT_fno_lto, false))
600 return;
601
602 StringRef LTOName("full");
603
604 const Arg *A = Args.getLastArg(options::OPT_flto_EQ);
605 if (A)
606 LTOName = A->getValue();
607
608 LTOMode = llvm::StringSwitch<LTOKind>(LTOName)
609 .Case("full", LTOK_Full)
610 .Case("thin", LTOK_Thin)
611 .Default(LTOK_Unknown);
612
613 if (LTOMode == LTOK_Unknown) {
614 assert(A);
615 Diag(diag::err_drv_unsupported_option_argument) << A->getOption().getName()
616 << A->getValue();
617 }
618 }
619
620 /// Compute the desired OpenMP runtime from the flags provided.
getOpenMPRuntime(const ArgList & Args) const621 Driver::OpenMPRuntimeKind Driver::getOpenMPRuntime(const ArgList &Args) const {
622 StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
623
624 const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
625 if (A)
626 RuntimeName = A->getValue();
627
628 auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
629 .Case("libomp", OMPRT_OMP)
630 .Case("libgomp", OMPRT_GOMP)
631 .Case("libiomp5", OMPRT_IOMP5)
632 .Default(OMPRT_Unknown);
633
634 if (RT == OMPRT_Unknown) {
635 if (A)
636 Diag(diag::err_drv_unsupported_option_argument)
637 << A->getOption().getName() << A->getValue();
638 else
639 // FIXME: We could use a nicer diagnostic here.
640 Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
641 }
642
643 return RT;
644 }
645
CreateOffloadingDeviceToolChains(Compilation & C,InputList & Inputs)646 void Driver::CreateOffloadingDeviceToolChains(Compilation &C,
647 InputList &Inputs) {
648
649 //
650 // CUDA/HIP
651 //
652 // We need to generate a CUDA/HIP toolchain if any of the inputs has a CUDA
653 // or HIP type. However, mixed CUDA/HIP compilation is not supported.
654 bool IsCuda =
655 llvm::any_of(Inputs, [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
656 return types::isCuda(I.first);
657 });
658 bool IsHIP =
659 llvm::any_of(Inputs,
660 [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
661 return types::isHIP(I.first);
662 }) ||
663 C.getInputArgs().hasArg(options::OPT_hip_link);
664 if (IsCuda && IsHIP) {
665 Diag(clang::diag::err_drv_mix_cuda_hip);
666 return;
667 }
668 if (IsCuda) {
669 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
670 const llvm::Triple &HostTriple = HostTC->getTriple();
671 StringRef DeviceTripleStr;
672 auto OFK = Action::OFK_Cuda;
673 DeviceTripleStr =
674 HostTriple.isArch64Bit() ? "nvptx64-nvidia-cuda" : "nvptx-nvidia-cuda";
675 llvm::Triple CudaTriple(DeviceTripleStr);
676 // Use the CUDA and host triples as the key into the ToolChains map,
677 // because the device toolchain we create depends on both.
678 auto &CudaTC = ToolChains[CudaTriple.str() + "/" + HostTriple.str()];
679 if (!CudaTC) {
680 CudaTC = std::make_unique<toolchains::CudaToolChain>(
681 *this, CudaTriple, *HostTC, C.getInputArgs(), OFK);
682 }
683 C.addOffloadDeviceToolChain(CudaTC.get(), OFK);
684 } else if (IsHIP) {
685 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
686 const llvm::Triple &HostTriple = HostTC->getTriple();
687 auto OFK = Action::OFK_HIP;
688 llvm::Triple HIPTriple = getHIPOffloadTargetTriple();
689 // Use the HIP and host triples as the key into the ToolChains map,
690 // because the device toolchain we create depends on both.
691 auto &HIPTC = ToolChains[HIPTriple.str() + "/" + HostTriple.str()];
692 if (!HIPTC) {
693 HIPTC = std::make_unique<toolchains::HIPToolChain>(
694 *this, HIPTriple, *HostTC, C.getInputArgs());
695 }
696 C.addOffloadDeviceToolChain(HIPTC.get(), OFK);
697 }
698
699 //
700 // OpenMP
701 //
702 // We need to generate an OpenMP toolchain if the user specified targets with
703 // the -fopenmp-targets option.
704 if (Arg *OpenMPTargets =
705 C.getInputArgs().getLastArg(options::OPT_fopenmp_targets_EQ)) {
706 if (OpenMPTargets->getNumValues()) {
707 // We expect that -fopenmp-targets is always used in conjunction with the
708 // option -fopenmp specifying a valid runtime with offloading support,
709 // i.e. libomp or libiomp.
710 bool HasValidOpenMPRuntime = C.getInputArgs().hasFlag(
711 options::OPT_fopenmp, options::OPT_fopenmp_EQ,
712 options::OPT_fno_openmp, false);
713 if (HasValidOpenMPRuntime) {
714 OpenMPRuntimeKind OpenMPKind = getOpenMPRuntime(C.getInputArgs());
715 HasValidOpenMPRuntime =
716 OpenMPKind == OMPRT_OMP || OpenMPKind == OMPRT_IOMP5;
717 }
718
719 if (HasValidOpenMPRuntime) {
720 llvm::StringMap<const char *> FoundNormalizedTriples;
721 for (const char *Val : OpenMPTargets->getValues()) {
722 llvm::Triple TT(Val);
723 std::string NormalizedName = TT.normalize();
724
725 // Make sure we don't have a duplicate triple.
726 auto Duplicate = FoundNormalizedTriples.find(NormalizedName);
727 if (Duplicate != FoundNormalizedTriples.end()) {
728 Diag(clang::diag::warn_drv_omp_offload_target_duplicate)
729 << Val << Duplicate->second;
730 continue;
731 }
732
733 // Store the current triple so that we can check for duplicates in the
734 // following iterations.
735 FoundNormalizedTriples[NormalizedName] = Val;
736
737 // If the specified target is invalid, emit a diagnostic.
738 if (TT.getArch() == llvm::Triple::UnknownArch)
739 Diag(clang::diag::err_drv_invalid_omp_target) << Val;
740 else {
741 const ToolChain *TC;
742 // CUDA toolchains have to be selected differently. They pair host
743 // and device in their implementation.
744 if (TT.isNVPTX()) {
745 const ToolChain *HostTC =
746 C.getSingleOffloadToolChain<Action::OFK_Host>();
747 assert(HostTC && "Host toolchain should be always defined.");
748 auto &CudaTC =
749 ToolChains[TT.str() + "/" + HostTC->getTriple().normalize()];
750 if (!CudaTC)
751 CudaTC = std::make_unique<toolchains::CudaToolChain>(
752 *this, TT, *HostTC, C.getInputArgs(), Action::OFK_OpenMP);
753 TC = CudaTC.get();
754 } else
755 TC = &getToolChain(C.getInputArgs(), TT);
756 C.addOffloadDeviceToolChain(TC, Action::OFK_OpenMP);
757 }
758 }
759 } else
760 Diag(clang::diag::err_drv_expecting_fopenmp_with_fopenmp_targets);
761 } else
762 Diag(clang::diag::warn_drv_empty_joined_argument)
763 << OpenMPTargets->getAsString(C.getInputArgs());
764 }
765
766 //
767 // TODO: Add support for other offloading programming models here.
768 //
769 }
770
771 /// Looks the given directories for the specified file.
772 ///
773 /// \param[out] FilePath File path, if the file was found.
774 /// \param[in] Dirs Directories used for the search.
775 /// \param[in] FileName Name of the file to search for.
776 /// \return True if file was found.
777 ///
778 /// Looks for file specified by FileName sequentially in directories specified
779 /// by Dirs.
780 ///
searchForFile(SmallVectorImpl<char> & FilePath,ArrayRef<std::string> Dirs,StringRef FileName)781 static bool searchForFile(SmallVectorImpl<char> &FilePath,
782 ArrayRef<std::string> Dirs,
783 StringRef FileName) {
784 SmallString<128> WPath;
785 for (const std::string &Dir : Dirs) {
786 if (Dir.empty())
787 continue;
788 WPath.clear();
789 llvm::sys::path::append(WPath, Dir, FileName);
790 llvm::sys::path::native(WPath);
791 if (llvm::sys::fs::is_regular_file(WPath)) {
792 FilePath = std::move(WPath);
793 return true;
794 }
795 }
796 return false;
797 }
798
readConfigFile(StringRef FileName)799 bool Driver::readConfigFile(StringRef FileName) {
800 // Try reading the given file.
801 SmallVector<const char *, 32> NewCfgArgs;
802 if (!llvm::cl::readConfigFile(FileName, Saver, NewCfgArgs)) {
803 Diag(diag::err_drv_cannot_read_config_file) << FileName;
804 return true;
805 }
806
807 // Read options from config file.
808 llvm::SmallString<128> CfgFileName(FileName);
809 llvm::sys::path::native(CfgFileName);
810 ConfigFile = std::string(CfgFileName.str());
811 bool ContainErrors;
812 CfgOptions = std::make_unique<InputArgList>(
813 ParseArgStrings(NewCfgArgs, IsCLMode(), ContainErrors));
814 if (ContainErrors) {
815 CfgOptions.reset();
816 return true;
817 }
818
819 if (CfgOptions->hasArg(options::OPT_config)) {
820 CfgOptions.reset();
821 Diag(diag::err_drv_nested_config_file);
822 return true;
823 }
824
825 // Claim all arguments that come from a configuration file so that the driver
826 // does not warn on any that is unused.
827 for (Arg *A : *CfgOptions)
828 A->claim();
829 return false;
830 }
831
loadConfigFile()832 bool Driver::loadConfigFile() {
833 std::string CfgFileName;
834 bool FileSpecifiedExplicitly = false;
835
836 // Process options that change search path for config files.
837 if (CLOptions) {
838 if (CLOptions->hasArg(options::OPT_config_system_dir_EQ)) {
839 SmallString<128> CfgDir;
840 CfgDir.append(
841 CLOptions->getLastArgValue(options::OPT_config_system_dir_EQ));
842 if (!CfgDir.empty()) {
843 if (llvm::sys::fs::make_absolute(CfgDir).value() != 0)
844 SystemConfigDir.clear();
845 else
846 SystemConfigDir = std::string(CfgDir.begin(), CfgDir.end());
847 }
848 }
849 if (CLOptions->hasArg(options::OPT_config_user_dir_EQ)) {
850 SmallString<128> CfgDir;
851 CfgDir.append(
852 CLOptions->getLastArgValue(options::OPT_config_user_dir_EQ));
853 if (!CfgDir.empty()) {
854 if (llvm::sys::fs::make_absolute(CfgDir).value() != 0)
855 UserConfigDir.clear();
856 else
857 UserConfigDir = std::string(CfgDir.begin(), CfgDir.end());
858 }
859 }
860 }
861
862 // First try to find config file specified in command line.
863 if (CLOptions) {
864 std::vector<std::string> ConfigFiles =
865 CLOptions->getAllArgValues(options::OPT_config);
866 if (ConfigFiles.size() > 1) {
867 if (!std::all_of(
868 ConfigFiles.begin(), ConfigFiles.end(),
869 [ConfigFiles](std::string s) { return s == ConfigFiles[0]; })) {
870 Diag(diag::err_drv_duplicate_config);
871 return true;
872 }
873 }
874
875 if (!ConfigFiles.empty()) {
876 CfgFileName = ConfigFiles.front();
877 assert(!CfgFileName.empty());
878
879 // If argument contains directory separator, treat it as a path to
880 // configuration file.
881 if (llvm::sys::path::has_parent_path(CfgFileName)) {
882 SmallString<128> CfgFilePath;
883 if (llvm::sys::path::is_relative(CfgFileName))
884 llvm::sys::fs::current_path(CfgFilePath);
885 llvm::sys::path::append(CfgFilePath, CfgFileName);
886 if (!llvm::sys::fs::is_regular_file(CfgFilePath)) {
887 Diag(diag::err_drv_config_file_not_exist) << CfgFilePath;
888 return true;
889 }
890 return readConfigFile(CfgFilePath);
891 }
892
893 FileSpecifiedExplicitly = true;
894 }
895 }
896
897 // If config file is not specified explicitly, try to deduce configuration
898 // from executable name. For instance, an executable 'armv7l-clang' will
899 // search for config file 'armv7l-clang.cfg'.
900 if (CfgFileName.empty() && !ClangNameParts.TargetPrefix.empty())
901 CfgFileName = ClangNameParts.TargetPrefix + '-' + ClangNameParts.ModeSuffix;
902
903 if (CfgFileName.empty())
904 return false;
905
906 // Determine architecture part of the file name, if it is present.
907 StringRef CfgFileArch = CfgFileName;
908 size_t ArchPrefixLen = CfgFileArch.find('-');
909 if (ArchPrefixLen == StringRef::npos)
910 ArchPrefixLen = CfgFileArch.size();
911 llvm::Triple CfgTriple;
912 CfgFileArch = CfgFileArch.take_front(ArchPrefixLen);
913 CfgTriple = llvm::Triple(llvm::Triple::normalize(CfgFileArch));
914 if (CfgTriple.getArch() == llvm::Triple::ArchType::UnknownArch)
915 ArchPrefixLen = 0;
916
917 if (!StringRef(CfgFileName).endswith(".cfg"))
918 CfgFileName += ".cfg";
919
920 // If config file starts with architecture name and command line options
921 // redefine architecture (with options like -m32 -LE etc), try finding new
922 // config file with that architecture.
923 SmallString<128> FixedConfigFile;
924 size_t FixedArchPrefixLen = 0;
925 if (ArchPrefixLen) {
926 // Get architecture name from config file name like 'i386.cfg' or
927 // 'armv7l-clang.cfg'.
928 // Check if command line options changes effective triple.
929 llvm::Triple EffectiveTriple = computeTargetTriple(*this,
930 CfgTriple.getTriple(), *CLOptions);
931 if (CfgTriple.getArch() != EffectiveTriple.getArch()) {
932 FixedConfigFile = EffectiveTriple.getArchName();
933 FixedArchPrefixLen = FixedConfigFile.size();
934 // Append the rest of original file name so that file name transforms
935 // like: i386-clang.cfg -> x86_64-clang.cfg.
936 if (ArchPrefixLen < CfgFileName.size())
937 FixedConfigFile += CfgFileName.substr(ArchPrefixLen);
938 }
939 }
940
941 // Prepare list of directories where config file is searched for.
942 SmallVector<std::string, 3> CfgFileSearchDirs;
943 CfgFileSearchDirs.push_back(UserConfigDir);
944 CfgFileSearchDirs.push_back(SystemConfigDir);
945 CfgFileSearchDirs.push_back(Dir);
946
947 // Try to find config file. First try file with corrected architecture.
948 llvm::SmallString<128> CfgFilePath;
949 if (!FixedConfigFile.empty()) {
950 if (searchForFile(CfgFilePath, CfgFileSearchDirs, FixedConfigFile))
951 return readConfigFile(CfgFilePath);
952 // If 'x86_64-clang.cfg' was not found, try 'x86_64.cfg'.
953 FixedConfigFile.resize(FixedArchPrefixLen);
954 FixedConfigFile.append(".cfg");
955 if (searchForFile(CfgFilePath, CfgFileSearchDirs, FixedConfigFile))
956 return readConfigFile(CfgFilePath);
957 }
958
959 // Then try original file name.
960 if (searchForFile(CfgFilePath, CfgFileSearchDirs, CfgFileName))
961 return readConfigFile(CfgFilePath);
962
963 // Finally try removing driver mode part: 'x86_64-clang.cfg' -> 'x86_64.cfg'.
964 if (!ClangNameParts.ModeSuffix.empty() &&
965 !ClangNameParts.TargetPrefix.empty()) {
966 CfgFileName.assign(ClangNameParts.TargetPrefix);
967 CfgFileName.append(".cfg");
968 if (searchForFile(CfgFilePath, CfgFileSearchDirs, CfgFileName))
969 return readConfigFile(CfgFilePath);
970 }
971
972 // Report error but only if config file was specified explicitly, by option
973 // --config. If it was deduced from executable name, it is not an error.
974 if (FileSpecifiedExplicitly) {
975 Diag(diag::err_drv_config_file_not_found) << CfgFileName;
976 for (const std::string &SearchDir : CfgFileSearchDirs)
977 if (!SearchDir.empty())
978 Diag(diag::note_drv_config_file_searched_in) << SearchDir;
979 return true;
980 }
981
982 return false;
983 }
984
BuildCompilation(ArrayRef<const char * > ArgList)985 Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
986 llvm::PrettyStackTraceString CrashInfo("Compilation construction");
987
988 // FIXME: Handle environment options which affect driver behavior, somewhere
989 // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
990
991 // We look for the driver mode option early, because the mode can affect
992 // how other options are parsed.
993 ParseDriverMode(ClangExecutable, ArgList.slice(1));
994
995 // FIXME: What are we going to do with -V and -b?
996
997 // Arguments specified in command line.
998 bool ContainsError;
999 CLOptions = std::make_unique<InputArgList>(
1000 ParseArgStrings(ArgList.slice(1), IsCLMode(), ContainsError));
1001
1002 // Try parsing configuration file.
1003 if (!ContainsError)
1004 ContainsError = loadConfigFile();
1005 bool HasConfigFile = !ContainsError && (CfgOptions.get() != nullptr);
1006
1007 // All arguments, from both config file and command line.
1008 InputArgList Args = std::move(HasConfigFile ? std::move(*CfgOptions)
1009 : std::move(*CLOptions));
1010
1011 // The args for config files or /clang: flags belong to different InputArgList
1012 // objects than Args. This copies an Arg from one of those other InputArgLists
1013 // to the ownership of Args.
1014 auto appendOneArg = [&Args](const Arg *Opt, const Arg *BaseArg) {
1015 unsigned Index = Args.MakeIndex(Opt->getSpelling());
1016 Arg *Copy = new llvm::opt::Arg(Opt->getOption(), Opt->getSpelling(),
1017 Index, BaseArg);
1018 Copy->getValues() = Opt->getValues();
1019 if (Opt->isClaimed())
1020 Copy->claim();
1021 Args.append(Copy);
1022 };
1023
1024 if (HasConfigFile)
1025 for (auto *Opt : *CLOptions) {
1026 if (Opt->getOption().matches(options::OPT_config))
1027 continue;
1028 const Arg *BaseArg = &Opt->getBaseArg();
1029 if (BaseArg == Opt)
1030 BaseArg = nullptr;
1031 appendOneArg(Opt, BaseArg);
1032 }
1033
1034 // In CL mode, look for any pass-through arguments
1035 if (IsCLMode() && !ContainsError) {
1036 SmallVector<const char *, 16> CLModePassThroughArgList;
1037 for (const auto *A : Args.filtered(options::OPT__SLASH_clang)) {
1038 A->claim();
1039 CLModePassThroughArgList.push_back(A->getValue());
1040 }
1041
1042 if (!CLModePassThroughArgList.empty()) {
1043 // Parse any pass through args using default clang processing rather
1044 // than clang-cl processing.
1045 auto CLModePassThroughOptions = std::make_unique<InputArgList>(
1046 ParseArgStrings(CLModePassThroughArgList, false, ContainsError));
1047
1048 if (!ContainsError)
1049 for (auto *Opt : *CLModePassThroughOptions) {
1050 appendOneArg(Opt, nullptr);
1051 }
1052 }
1053 }
1054
1055 // Check for working directory option before accessing any files
1056 if (Arg *WD = Args.getLastArg(options::OPT_working_directory))
1057 if (VFS->setCurrentWorkingDirectory(WD->getValue()))
1058 Diag(diag::err_drv_unable_to_set_working_directory) << WD->getValue();
1059
1060 // FIXME: This stuff needs to go into the Compilation, not the driver.
1061 bool CCCPrintPhases;
1062
1063 // Silence driver warnings if requested
1064 Diags.setIgnoreAllWarnings(Args.hasArg(options::OPT_w));
1065
1066 // -no-canonical-prefixes is used very early in main.
1067 Args.ClaimAllArgs(options::OPT_no_canonical_prefixes);
1068
1069 // f(no-)integated-cc1 is also used very early in main.
1070 Args.ClaimAllArgs(options::OPT_fintegrated_cc1);
1071 Args.ClaimAllArgs(options::OPT_fno_integrated_cc1);
1072
1073 // Ignore -pipe.
1074 Args.ClaimAllArgs(options::OPT_pipe);
1075
1076 // Extract -ccc args.
1077 //
1078 // FIXME: We need to figure out where this behavior should live. Most of it
1079 // should be outside in the client; the parts that aren't should have proper
1080 // options, either by introducing new ones or by overloading gcc ones like -V
1081 // or -b.
1082 CCCPrintPhases = Args.hasArg(options::OPT_ccc_print_phases);
1083 CCCPrintBindings = Args.hasArg(options::OPT_ccc_print_bindings);
1084 if (const Arg *A = Args.getLastArg(options::OPT_ccc_gcc_name))
1085 CCCGenericGCCName = A->getValue();
1086 GenReproducer = Args.hasFlag(options::OPT_gen_reproducer,
1087 options::OPT_fno_crash_diagnostics,
1088 !!::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH"));
1089 // FIXME: TargetTriple is used by the target-prefixed calls to as/ld
1090 // and getToolChain is const.
1091 if (IsCLMode()) {
1092 // clang-cl targets MSVC-style Win32.
1093 llvm::Triple T(TargetTriple);
1094 T.setOS(llvm::Triple::Win32);
1095 T.setVendor(llvm::Triple::PC);
1096 T.setEnvironment(llvm::Triple::MSVC);
1097 T.setObjectFormat(llvm::Triple::COFF);
1098 TargetTriple = T.str();
1099 }
1100 if (const Arg *A = Args.getLastArg(options::OPT_target))
1101 TargetTriple = A->getValue();
1102 if (const Arg *A = Args.getLastArg(options::OPT_ccc_install_dir))
1103 Dir = InstalledDir = A->getValue();
1104 for (const Arg *A : Args.filtered(options::OPT_B)) {
1105 A->claim();
1106 PrefixDirs.push_back(A->getValue(0));
1107 }
1108 if (Optional<std::string> CompilerPathValue =
1109 llvm::sys::Process::GetEnv("COMPILER_PATH")) {
1110 StringRef CompilerPath = *CompilerPathValue;
1111 while (!CompilerPath.empty()) {
1112 std::pair<StringRef, StringRef> Split =
1113 CompilerPath.split(llvm::sys::EnvPathSeparator);
1114 PrefixDirs.push_back(std::string(Split.first));
1115 CompilerPath = Split.second;
1116 }
1117 }
1118 if (const Arg *A = Args.getLastArg(options::OPT__sysroot_EQ))
1119 SysRoot = A->getValue();
1120 if (const Arg *A = Args.getLastArg(options::OPT__dyld_prefix_EQ))
1121 DyldPrefix = A->getValue();
1122
1123 if (const Arg *A = Args.getLastArg(options::OPT_resource_dir))
1124 ResourceDir = A->getValue();
1125
1126 if (const Arg *A = Args.getLastArg(options::OPT_save_temps_EQ)) {
1127 SaveTemps = llvm::StringSwitch<SaveTempsMode>(A->getValue())
1128 .Case("cwd", SaveTempsCwd)
1129 .Case("obj", SaveTempsObj)
1130 .Default(SaveTempsCwd);
1131 }
1132
1133 setLTOMode(Args);
1134
1135 // Process -fembed-bitcode= flags.
1136 if (Arg *A = Args.getLastArg(options::OPT_fembed_bitcode_EQ)) {
1137 StringRef Name = A->getValue();
1138 unsigned Model = llvm::StringSwitch<unsigned>(Name)
1139 .Case("off", EmbedNone)
1140 .Case("all", EmbedBitcode)
1141 .Case("bitcode", EmbedBitcode)
1142 .Case("marker", EmbedMarker)
1143 .Default(~0U);
1144 if (Model == ~0U) {
1145 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
1146 << Name;
1147 } else
1148 BitcodeEmbed = static_cast<BitcodeEmbedMode>(Model);
1149 }
1150
1151 std::unique_ptr<llvm::opt::InputArgList> UArgs =
1152 std::make_unique<InputArgList>(std::move(Args));
1153
1154 // Perform the default argument translations.
1155 DerivedArgList *TranslatedArgs = TranslateInputArgs(*UArgs);
1156
1157 // Owned by the host.
1158 const ToolChain &TC = getToolChain(
1159 *UArgs, computeTargetTriple(*this, TargetTriple, *UArgs));
1160
1161 // The compilation takes ownership of Args.
1162 Compilation *C = new Compilation(*this, TC, UArgs.release(), TranslatedArgs,
1163 ContainsError);
1164
1165 if (!HandleImmediateArgs(*C))
1166 return C;
1167
1168 // Construct the list of inputs.
1169 InputList Inputs;
1170 BuildInputs(C->getDefaultToolChain(), *TranslatedArgs, Inputs);
1171
1172 // Populate the tool chains for the offloading devices, if any.
1173 CreateOffloadingDeviceToolChains(*C, Inputs);
1174
1175 // Construct the list of abstract actions to perform for this compilation. On
1176 // MachO targets this uses the driver-driver and universal actions.
1177 if (TC.getTriple().isOSBinFormatMachO())
1178 BuildUniversalActions(*C, C->getDefaultToolChain(), Inputs);
1179 else
1180 BuildActions(*C, C->getArgs(), Inputs, C->getActions());
1181
1182 if (CCCPrintPhases) {
1183 PrintActions(*C);
1184 return C;
1185 }
1186
1187 BuildJobs(*C);
1188
1189 return C;
1190 }
1191
printArgList(raw_ostream & OS,const llvm::opt::ArgList & Args)1192 static void printArgList(raw_ostream &OS, const llvm::opt::ArgList &Args) {
1193 llvm::opt::ArgStringList ASL;
1194 for (const auto *A : Args)
1195 A->render(Args, ASL);
1196
1197 for (auto I = ASL.begin(), E = ASL.end(); I != E; ++I) {
1198 if (I != ASL.begin())
1199 OS << ' ';
1200 llvm::sys::printArg(OS, *I, true);
1201 }
1202 OS << '\n';
1203 }
1204
getCrashDiagnosticFile(StringRef ReproCrashFilename,SmallString<128> & CrashDiagDir)1205 bool Driver::getCrashDiagnosticFile(StringRef ReproCrashFilename,
1206 SmallString<128> &CrashDiagDir) {
1207 using namespace llvm::sys;
1208 assert(llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin() &&
1209 "Only knows about .crash files on Darwin");
1210
1211 // The .crash file can be found on at ~/Library/Logs/DiagnosticReports/
1212 // (or /Library/Logs/DiagnosticReports for root) and has the filename pattern
1213 // clang-<VERSION>_<YYYY-MM-DD-HHMMSS>_<hostname>.crash.
1214 path::home_directory(CrashDiagDir);
1215 if (CrashDiagDir.startswith("/var/root"))
1216 CrashDiagDir = "/";
1217 path::append(CrashDiagDir, "Library/Logs/DiagnosticReports");
1218 int PID =
1219 #if LLVM_ON_UNIX
1220 getpid();
1221 #else
1222 0;
1223 #endif
1224 std::error_code EC;
1225 fs::file_status FileStatus;
1226 TimePoint<> LastAccessTime;
1227 SmallString<128> CrashFilePath;
1228 // Lookup the .crash files and get the one generated by a subprocess spawned
1229 // by this driver invocation.
1230 for (fs::directory_iterator File(CrashDiagDir, EC), FileEnd;
1231 File != FileEnd && !EC; File.increment(EC)) {
1232 StringRef FileName = path::filename(File->path());
1233 if (!FileName.startswith(Name))
1234 continue;
1235 if (fs::status(File->path(), FileStatus))
1236 continue;
1237 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> CrashFile =
1238 llvm::MemoryBuffer::getFile(File->path());
1239 if (!CrashFile)
1240 continue;
1241 // The first line should start with "Process:", otherwise this isn't a real
1242 // .crash file.
1243 StringRef Data = CrashFile.get()->getBuffer();
1244 if (!Data.startswith("Process:"))
1245 continue;
1246 // Parse parent process pid line, e.g: "Parent Process: clang-4.0 [79141]"
1247 size_t ParentProcPos = Data.find("Parent Process:");
1248 if (ParentProcPos == StringRef::npos)
1249 continue;
1250 size_t LineEnd = Data.find_first_of("\n", ParentProcPos);
1251 if (LineEnd == StringRef::npos)
1252 continue;
1253 StringRef ParentProcess = Data.slice(ParentProcPos+15, LineEnd).trim();
1254 int OpenBracket = -1, CloseBracket = -1;
1255 for (size_t i = 0, e = ParentProcess.size(); i < e; ++i) {
1256 if (ParentProcess[i] == '[')
1257 OpenBracket = i;
1258 if (ParentProcess[i] == ']')
1259 CloseBracket = i;
1260 }
1261 // Extract the parent process PID from the .crash file and check whether
1262 // it matches this driver invocation pid.
1263 int CrashPID;
1264 if (OpenBracket < 0 || CloseBracket < 0 ||
1265 ParentProcess.slice(OpenBracket + 1, CloseBracket)
1266 .getAsInteger(10, CrashPID) || CrashPID != PID) {
1267 continue;
1268 }
1269
1270 // Found a .crash file matching the driver pid. To avoid getting an older
1271 // and misleading crash file, continue looking for the most recent.
1272 // FIXME: the driver can dispatch multiple cc1 invocations, leading to
1273 // multiple crashes poiting to the same parent process. Since the driver
1274 // does not collect pid information for the dispatched invocation there's
1275 // currently no way to distinguish among them.
1276 const auto FileAccessTime = FileStatus.getLastModificationTime();
1277 if (FileAccessTime > LastAccessTime) {
1278 CrashFilePath.assign(File->path());
1279 LastAccessTime = FileAccessTime;
1280 }
1281 }
1282
1283 // If found, copy it over to the location of other reproducer files.
1284 if (!CrashFilePath.empty()) {
1285 EC = fs::copy_file(CrashFilePath, ReproCrashFilename);
1286 if (EC)
1287 return false;
1288 return true;
1289 }
1290
1291 return false;
1292 }
1293
1294 // When clang crashes, produce diagnostic information including the fully
1295 // preprocessed source file(s). Request that the developer attach the
1296 // diagnostic information to a bug report.
generateCompilationDiagnostics(Compilation & C,const Command & FailingCommand,StringRef AdditionalInformation,CompilationDiagnosticReport * Report)1297 void Driver::generateCompilationDiagnostics(
1298 Compilation &C, const Command &FailingCommand,
1299 StringRef AdditionalInformation, CompilationDiagnosticReport *Report) {
1300 if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics))
1301 return;
1302
1303 // Don't try to generate diagnostics for link or dsymutil jobs.
1304 if (FailingCommand.getCreator().isLinkJob() ||
1305 FailingCommand.getCreator().isDsymutilJob())
1306 return;
1307
1308 // Print the version of the compiler.
1309 PrintVersion(C, llvm::errs());
1310
1311 // Suppress driver output and emit preprocessor output to temp file.
1312 Mode = CPPMode;
1313 CCGenDiagnostics = true;
1314
1315 // Save the original job command(s).
1316 Command Cmd = FailingCommand;
1317
1318 // Keep track of whether we produce any errors while trying to produce
1319 // preprocessed sources.
1320 DiagnosticErrorTrap Trap(Diags);
1321
1322 // Suppress tool output.
1323 C.initCompilationForDiagnostics();
1324
1325 // Construct the list of inputs.
1326 InputList Inputs;
1327 BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs);
1328
1329 for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) {
1330 bool IgnoreInput = false;
1331
1332 // Ignore input from stdin or any inputs that cannot be preprocessed.
1333 // Check type first as not all linker inputs have a value.
1334 if (types::getPreprocessedType(it->first) == types::TY_INVALID) {
1335 IgnoreInput = true;
1336 } else if (!strcmp(it->second->getValue(), "-")) {
1337 Diag(clang::diag::note_drv_command_failed_diag_msg)
1338 << "Error generating preprocessed source(s) - "
1339 "ignoring input from stdin.";
1340 IgnoreInput = true;
1341 }
1342
1343 if (IgnoreInput) {
1344 it = Inputs.erase(it);
1345 ie = Inputs.end();
1346 } else {
1347 ++it;
1348 }
1349 }
1350
1351 if (Inputs.empty()) {
1352 Diag(clang::diag::note_drv_command_failed_diag_msg)
1353 << "Error generating preprocessed source(s) - "
1354 "no preprocessable inputs.";
1355 return;
1356 }
1357
1358 // Don't attempt to generate preprocessed files if multiple -arch options are
1359 // used, unless they're all duplicates.
1360 llvm::StringSet<> ArchNames;
1361 for (const Arg *A : C.getArgs()) {
1362 if (A->getOption().matches(options::OPT_arch)) {
1363 StringRef ArchName = A->getValue();
1364 ArchNames.insert(ArchName);
1365 }
1366 }
1367 if (ArchNames.size() > 1) {
1368 Diag(clang::diag::note_drv_command_failed_diag_msg)
1369 << "Error generating preprocessed source(s) - cannot generate "
1370 "preprocessed source with multiple -arch options.";
1371 return;
1372 }
1373
1374 // Construct the list of abstract actions to perform for this compilation. On
1375 // Darwin OSes this uses the driver-driver and builds universal actions.
1376 const ToolChain &TC = C.getDefaultToolChain();
1377 if (TC.getTriple().isOSBinFormatMachO())
1378 BuildUniversalActions(C, TC, Inputs);
1379 else
1380 BuildActions(C, C.getArgs(), Inputs, C.getActions());
1381
1382 BuildJobs(C);
1383
1384 // If there were errors building the compilation, quit now.
1385 if (Trap.hasErrorOccurred()) {
1386 Diag(clang::diag::note_drv_command_failed_diag_msg)
1387 << "Error generating preprocessed source(s).";
1388 return;
1389 }
1390
1391 // Generate preprocessed output.
1392 SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
1393 C.ExecuteJobs(C.getJobs(), FailingCommands);
1394
1395 // If any of the preprocessing commands failed, clean up and exit.
1396 if (!FailingCommands.empty()) {
1397 Diag(clang::diag::note_drv_command_failed_diag_msg)
1398 << "Error generating preprocessed source(s).";
1399 return;
1400 }
1401
1402 const ArgStringList &TempFiles = C.getTempFiles();
1403 if (TempFiles.empty()) {
1404 Diag(clang::diag::note_drv_command_failed_diag_msg)
1405 << "Error generating preprocessed source(s).";
1406 return;
1407 }
1408
1409 Diag(clang::diag::note_drv_command_failed_diag_msg)
1410 << "\n********************\n\n"
1411 "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n"
1412 "Preprocessed source(s) and associated run script(s) are located at:";
1413
1414 SmallString<128> VFS;
1415 SmallString<128> ReproCrashFilename;
1416 for (const char *TempFile : TempFiles) {
1417 Diag(clang::diag::note_drv_command_failed_diag_msg) << TempFile;
1418 if (Report)
1419 Report->TemporaryFiles.push_back(TempFile);
1420 if (ReproCrashFilename.empty()) {
1421 ReproCrashFilename = TempFile;
1422 llvm::sys::path::replace_extension(ReproCrashFilename, ".crash");
1423 }
1424 if (StringRef(TempFile).endswith(".cache")) {
1425 // In some cases (modules) we'll dump extra data to help with reproducing
1426 // the crash into a directory next to the output.
1427 VFS = llvm::sys::path::filename(TempFile);
1428 llvm::sys::path::append(VFS, "vfs", "vfs.yaml");
1429 }
1430 }
1431
1432 // Assume associated files are based off of the first temporary file.
1433 CrashReportInfo CrashInfo(TempFiles[0], VFS);
1434
1435 llvm::SmallString<128> Script(CrashInfo.Filename);
1436 llvm::sys::path::replace_extension(Script, "sh");
1437 std::error_code EC;
1438 llvm::raw_fd_ostream ScriptOS(Script, EC, llvm::sys::fs::CD_CreateNew);
1439 if (EC) {
1440 Diag(clang::diag::note_drv_command_failed_diag_msg)
1441 << "Error generating run script: " << Script << " " << EC.message();
1442 } else {
1443 ScriptOS << "# Crash reproducer for " << getClangFullVersion() << "\n"
1444 << "# Driver args: ";
1445 printArgList(ScriptOS, C.getInputArgs());
1446 ScriptOS << "# Original command: ";
1447 Cmd.Print(ScriptOS, "\n", /*Quote=*/true);
1448 Cmd.Print(ScriptOS, "\n", /*Quote=*/true, &CrashInfo);
1449 if (!AdditionalInformation.empty())
1450 ScriptOS << "\n# Additional information: " << AdditionalInformation
1451 << "\n";
1452 if (Report)
1453 Report->TemporaryFiles.push_back(std::string(Script.str()));
1454 Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
1455 }
1456
1457 // On darwin, provide information about the .crash diagnostic report.
1458 if (llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin()) {
1459 SmallString<128> CrashDiagDir;
1460 if (getCrashDiagnosticFile(ReproCrashFilename, CrashDiagDir)) {
1461 Diag(clang::diag::note_drv_command_failed_diag_msg)
1462 << ReproCrashFilename.str();
1463 } else { // Suggest a directory for the user to look for .crash files.
1464 llvm::sys::path::append(CrashDiagDir, Name);
1465 CrashDiagDir += "_<YYYY-MM-DD-HHMMSS>_<hostname>.crash";
1466 Diag(clang::diag::note_drv_command_failed_diag_msg)
1467 << "Crash backtrace is located in";
1468 Diag(clang::diag::note_drv_command_failed_diag_msg)
1469 << CrashDiagDir.str();
1470 Diag(clang::diag::note_drv_command_failed_diag_msg)
1471 << "(choose the .crash file that corresponds to your crash)";
1472 }
1473 }
1474
1475 for (const auto &A : C.getArgs().filtered(options::OPT_frewrite_map_file,
1476 options::OPT_frewrite_map_file_EQ))
1477 Diag(clang::diag::note_drv_command_failed_diag_msg) << A->getValue();
1478
1479 Diag(clang::diag::note_drv_command_failed_diag_msg)
1480 << "\n\n********************";
1481 }
1482
setUpResponseFiles(Compilation & C,Command & Cmd)1483 void Driver::setUpResponseFiles(Compilation &C, Command &Cmd) {
1484 // Since commandLineFitsWithinSystemLimits() may underestimate system's
1485 // capacity if the tool does not support response files, there is a chance/
1486 // that things will just work without a response file, so we silently just
1487 // skip it.
1488 if (Cmd.getResponseFileSupport().ResponseKind ==
1489 ResponseFileSupport::RF_None ||
1490 llvm::sys::commandLineFitsWithinSystemLimits(Cmd.getExecutable(),
1491 Cmd.getArguments()))
1492 return;
1493
1494 std::string TmpName = GetTemporaryPath("response", "txt");
1495 Cmd.setResponseFile(C.addTempFile(C.getArgs().MakeArgString(TmpName)));
1496 }
1497
ExecuteCompilation(Compilation & C,SmallVectorImpl<std::pair<int,const Command * >> & FailingCommands)1498 int Driver::ExecuteCompilation(
1499 Compilation &C,
1500 SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) {
1501 // Just print if -### was present.
1502 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
1503 C.getJobs().Print(llvm::errs(), "\n", true);
1504 return 0;
1505 }
1506
1507 // If there were errors building the compilation, quit now.
1508 if (Diags.hasErrorOccurred())
1509 return 1;
1510
1511 // Set up response file names for each command, if necessary
1512 for (auto &Job : C.getJobs())
1513 setUpResponseFiles(C, Job);
1514
1515 C.ExecuteJobs(C.getJobs(), FailingCommands);
1516
1517 // If the command succeeded, we are done.
1518 if (FailingCommands.empty())
1519 return 0;
1520
1521 // Otherwise, remove result files and print extra information about abnormal
1522 // failures.
1523 int Res = 0;
1524 for (const auto &CmdPair : FailingCommands) {
1525 int CommandRes = CmdPair.first;
1526 const Command *FailingCommand = CmdPair.second;
1527
1528 // Remove result files if we're not saving temps.
1529 if (!isSaveTempsEnabled()) {
1530 const JobAction *JA = cast<JobAction>(&FailingCommand->getSource());
1531 C.CleanupFileMap(C.getResultFiles(), JA, true);
1532
1533 // Failure result files are valid unless we crashed.
1534 if (CommandRes < 0)
1535 C.CleanupFileMap(C.getFailureResultFiles(), JA, true);
1536 }
1537
1538 #if LLVM_ON_UNIX
1539 // llvm/lib/Support/Unix/Signals.inc will exit with a special return code
1540 // for SIGPIPE. Do not print diagnostics for this case.
1541 if (CommandRes == EX_IOERR) {
1542 Res = CommandRes;
1543 continue;
1544 }
1545 #endif
1546
1547 // Print extra information about abnormal failures, if possible.
1548 //
1549 // This is ad-hoc, but we don't want to be excessively noisy. If the result
1550 // status was 1, assume the command failed normally. In particular, if it
1551 // was the compiler then assume it gave a reasonable error code. Failures
1552 // in other tools are less common, and they generally have worse
1553 // diagnostics, so always print the diagnostic there.
1554 const Tool &FailingTool = FailingCommand->getCreator();
1555
1556 if (!FailingCommand->getCreator().hasGoodDiagnostics() || CommandRes != 1) {
1557 // FIXME: See FIXME above regarding result code interpretation.
1558 if (CommandRes < 0)
1559 Diag(clang::diag::err_drv_command_signalled)
1560 << FailingTool.getShortName();
1561 else
1562 Diag(clang::diag::err_drv_command_failed)
1563 << FailingTool.getShortName() << CommandRes;
1564 }
1565 }
1566 return Res;
1567 }
1568
PrintHelp(bool ShowHidden) const1569 void Driver::PrintHelp(bool ShowHidden) const {
1570 unsigned IncludedFlagsBitmask;
1571 unsigned ExcludedFlagsBitmask;
1572 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
1573 getIncludeExcludeOptionFlagMasks(IsCLMode());
1574
1575 ExcludedFlagsBitmask |= options::NoDriverOption;
1576 if (!ShowHidden)
1577 ExcludedFlagsBitmask |= HelpHidden;
1578
1579 if (IsFlangMode())
1580 IncludedFlagsBitmask |= options::FlangOption;
1581 else
1582 ExcludedFlagsBitmask |= options::FlangOnlyOption;
1583
1584 std::string Usage = llvm::formatv("{0} [options] file...", Name).str();
1585 getOpts().PrintHelp(llvm::outs(), Usage.c_str(), DriverTitle.c_str(),
1586 IncludedFlagsBitmask, ExcludedFlagsBitmask,
1587 /*ShowAllAliases=*/false);
1588 }
1589
PrintVersion(const Compilation & C,raw_ostream & OS) const1590 void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const {
1591 if (IsFlangMode()) {
1592 OS << getClangToolFullVersion("flang-new") << '\n';
1593 } else {
1594 // FIXME: The following handlers should use a callback mechanism, we don't
1595 // know what the client would like to do.
1596 OS << getClangFullVersion() << '\n';
1597 }
1598 const ToolChain &TC = C.getDefaultToolChain();
1599 OS << "Target: " << TC.getTripleString() << '\n';
1600
1601 // Print the threading model.
1602 if (Arg *A = C.getArgs().getLastArg(options::OPT_mthread_model)) {
1603 // Don't print if the ToolChain would have barfed on it already
1604 if (TC.isThreadModelSupported(A->getValue()))
1605 OS << "Thread model: " << A->getValue();
1606 } else
1607 OS << "Thread model: " << TC.getThreadModel();
1608 OS << '\n';
1609
1610 // Print out the install directory.
1611 OS << "InstalledDir: " << InstalledDir << '\n';
1612
1613 // If configuration file was used, print its path.
1614 if (!ConfigFile.empty())
1615 OS << "Configuration file: " << ConfigFile << '\n';
1616 }
1617
1618 /// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
1619 /// option.
PrintDiagnosticCategories(raw_ostream & OS)1620 static void PrintDiagnosticCategories(raw_ostream &OS) {
1621 // Skip the empty category.
1622 for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); i != max;
1623 ++i)
1624 OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
1625 }
1626
HandleAutocompletions(StringRef PassedFlags) const1627 void Driver::HandleAutocompletions(StringRef PassedFlags) const {
1628 if (PassedFlags == "")
1629 return;
1630 // Print out all options that start with a given argument. This is used for
1631 // shell autocompletion.
1632 std::vector<std::string> SuggestedCompletions;
1633 std::vector<std::string> Flags;
1634
1635 unsigned int DisableFlags =
1636 options::NoDriverOption | options::Unsupported | options::Ignored;
1637
1638 // Make sure that Flang-only options don't pollute the Clang output
1639 // TODO: Make sure that Clang-only options don't pollute Flang output
1640 if (!IsFlangMode())
1641 DisableFlags |= options::FlangOnlyOption;
1642
1643 // Distinguish "--autocomplete=-someflag" and "--autocomplete=-someflag,"
1644 // because the latter indicates that the user put space before pushing tab
1645 // which should end up in a file completion.
1646 const bool HasSpace = PassedFlags.endswith(",");
1647
1648 // Parse PassedFlags by "," as all the command-line flags are passed to this
1649 // function separated by ","
1650 StringRef TargetFlags = PassedFlags;
1651 while (TargetFlags != "") {
1652 StringRef CurFlag;
1653 std::tie(CurFlag, TargetFlags) = TargetFlags.split(",");
1654 Flags.push_back(std::string(CurFlag));
1655 }
1656
1657 // We want to show cc1-only options only when clang is invoked with -cc1 or
1658 // -Xclang.
1659 if (llvm::is_contained(Flags, "-Xclang") || llvm::is_contained(Flags, "-cc1"))
1660 DisableFlags &= ~options::NoDriverOption;
1661
1662 const llvm::opt::OptTable &Opts = getOpts();
1663 StringRef Cur;
1664 Cur = Flags.at(Flags.size() - 1);
1665 StringRef Prev;
1666 if (Flags.size() >= 2) {
1667 Prev = Flags.at(Flags.size() - 2);
1668 SuggestedCompletions = Opts.suggestValueCompletions(Prev, Cur);
1669 }
1670
1671 if (SuggestedCompletions.empty())
1672 SuggestedCompletions = Opts.suggestValueCompletions(Cur, "");
1673
1674 // If Flags were empty, it means the user typed `clang [tab]` where we should
1675 // list all possible flags. If there was no value completion and the user
1676 // pressed tab after a space, we should fall back to a file completion.
1677 // We're printing a newline to be consistent with what we print at the end of
1678 // this function.
1679 if (SuggestedCompletions.empty() && HasSpace && !Flags.empty()) {
1680 llvm::outs() << '\n';
1681 return;
1682 }
1683
1684 // When flag ends with '=' and there was no value completion, return empty
1685 // string and fall back to the file autocompletion.
1686 if (SuggestedCompletions.empty() && !Cur.endswith("=")) {
1687 // If the flag is in the form of "--autocomplete=-foo",
1688 // we were requested to print out all option names that start with "-foo".
1689 // For example, "--autocomplete=-fsyn" is expanded to "-fsyntax-only".
1690 SuggestedCompletions = Opts.findByPrefix(Cur, DisableFlags);
1691
1692 // We have to query the -W flags manually as they're not in the OptTable.
1693 // TODO: Find a good way to add them to OptTable instead and them remove
1694 // this code.
1695 for (StringRef S : DiagnosticIDs::getDiagnosticFlags())
1696 if (S.startswith(Cur))
1697 SuggestedCompletions.push_back(std::string(S));
1698 }
1699
1700 // Sort the autocomplete candidates so that shells print them out in a
1701 // deterministic order. We could sort in any way, but we chose
1702 // case-insensitive sorting for consistency with the -help option
1703 // which prints out options in the case-insensitive alphabetical order.
1704 llvm::sort(SuggestedCompletions, [](StringRef A, StringRef B) {
1705 if (int X = A.compare_lower(B))
1706 return X < 0;
1707 return A.compare(B) > 0;
1708 });
1709
1710 llvm::outs() << llvm::join(SuggestedCompletions, "\n") << '\n';
1711 }
1712
HandleImmediateArgs(const Compilation & C)1713 bool Driver::HandleImmediateArgs(const Compilation &C) {
1714 // The order these options are handled in gcc is all over the place, but we
1715 // don't expect inconsistencies w.r.t. that to matter in practice.
1716
1717 if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
1718 llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
1719 return false;
1720 }
1721
1722 if (C.getArgs().hasArg(options::OPT_dumpversion)) {
1723 // Since -dumpversion is only implemented for pedantic GCC compatibility, we
1724 // return an answer which matches our definition of __VERSION__.
1725 llvm::outs() << CLANG_VERSION_STRING << "\n";
1726 return false;
1727 }
1728
1729 if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
1730 PrintDiagnosticCategories(llvm::outs());
1731 return false;
1732 }
1733
1734 if (C.getArgs().hasArg(options::OPT_help) ||
1735 C.getArgs().hasArg(options::OPT__help_hidden)) {
1736 PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
1737 return false;
1738 }
1739
1740 if (C.getArgs().hasArg(options::OPT__version)) {
1741 // Follow gcc behavior and use stdout for --version and stderr for -v.
1742 PrintVersion(C, llvm::outs());
1743 return false;
1744 }
1745
1746 if (C.getArgs().hasArg(options::OPT_v) ||
1747 C.getArgs().hasArg(options::OPT__HASH_HASH_HASH) ||
1748 C.getArgs().hasArg(options::OPT_print_supported_cpus)) {
1749 PrintVersion(C, llvm::errs());
1750 SuppressMissingInputWarning = true;
1751 }
1752
1753 if (C.getArgs().hasArg(options::OPT_v)) {
1754 if (!SystemConfigDir.empty())
1755 llvm::errs() << "System configuration file directory: "
1756 << SystemConfigDir << "\n";
1757 if (!UserConfigDir.empty())
1758 llvm::errs() << "User configuration file directory: "
1759 << UserConfigDir << "\n";
1760 }
1761
1762 const ToolChain &TC = C.getDefaultToolChain();
1763
1764 if (C.getArgs().hasArg(options::OPT_v))
1765 TC.printVerboseInfo(llvm::errs());
1766
1767 if (C.getArgs().hasArg(options::OPT_print_resource_dir)) {
1768 llvm::outs() << ResourceDir << '\n';
1769 return false;
1770 }
1771
1772 if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
1773 llvm::outs() << "programs: =";
1774 bool separator = false;
1775 // Print -B and COMPILER_PATH.
1776 for (const std::string &Path : PrefixDirs) {
1777 if (separator)
1778 llvm::outs() << llvm::sys::EnvPathSeparator;
1779 llvm::outs() << Path;
1780 separator = true;
1781 }
1782 for (const std::string &Path : TC.getProgramPaths()) {
1783 if (separator)
1784 llvm::outs() << llvm::sys::EnvPathSeparator;
1785 llvm::outs() << Path;
1786 separator = true;
1787 }
1788 llvm::outs() << "\n";
1789 llvm::outs() << "libraries: =" << ResourceDir;
1790
1791 StringRef sysroot = C.getSysRoot();
1792
1793 for (const std::string &Path : TC.getFilePaths()) {
1794 // Always print a separator. ResourceDir was the first item shown.
1795 llvm::outs() << llvm::sys::EnvPathSeparator;
1796 // Interpretation of leading '=' is needed only for NetBSD.
1797 if (Path[0] == '=')
1798 llvm::outs() << sysroot << Path.substr(1);
1799 else
1800 llvm::outs() << Path;
1801 }
1802 llvm::outs() << "\n";
1803 return false;
1804 }
1805
1806 // FIXME: The following handlers should use a callback mechanism, we don't
1807 // know what the client would like to do.
1808 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
1809 llvm::outs() << GetFilePath(A->getValue(), TC) << "\n";
1810 return false;
1811 }
1812
1813 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
1814 StringRef ProgName = A->getValue();
1815
1816 // Null program name cannot have a path.
1817 if (! ProgName.empty())
1818 llvm::outs() << GetProgramPath(ProgName, TC);
1819
1820 llvm::outs() << "\n";
1821 return false;
1822 }
1823
1824 if (Arg *A = C.getArgs().getLastArg(options::OPT_autocomplete)) {
1825 StringRef PassedFlags = A->getValue();
1826 HandleAutocompletions(PassedFlags);
1827 return false;
1828 }
1829
1830 if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
1831 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(C.getArgs());
1832 const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(C.getArgs()));
1833 RegisterEffectiveTriple TripleRAII(TC, Triple);
1834 switch (RLT) {
1835 case ToolChain::RLT_CompilerRT:
1836 llvm::outs() << TC.getCompilerRT(C.getArgs(), "builtins") << "\n";
1837 break;
1838 case ToolChain::RLT_Libgcc:
1839 llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
1840 break;
1841 }
1842 return false;
1843 }
1844
1845 if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
1846 for (const Multilib &Multilib : TC.getMultilibs())
1847 llvm::outs() << Multilib << "\n";
1848 return false;
1849 }
1850
1851 if (C.getArgs().hasArg(options::OPT_print_multi_directory)) {
1852 const Multilib &Multilib = TC.getMultilib();
1853 if (Multilib.gccSuffix().empty())
1854 llvm::outs() << ".\n";
1855 else {
1856 StringRef Suffix(Multilib.gccSuffix());
1857 assert(Suffix.front() == '/');
1858 llvm::outs() << Suffix.substr(1) << "\n";
1859 }
1860 return false;
1861 }
1862
1863 if (C.getArgs().hasArg(options::OPT_print_target_triple)) {
1864 llvm::outs() << TC.getTripleString() << "\n";
1865 return false;
1866 }
1867
1868 if (C.getArgs().hasArg(options::OPT_print_effective_triple)) {
1869 const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(C.getArgs()));
1870 llvm::outs() << Triple.getTriple() << "\n";
1871 return false;
1872 }
1873
1874 if (C.getArgs().hasArg(options::OPT_print_targets)) {
1875 llvm::TargetRegistry::printRegisteredTargetsForVersion(llvm::outs());
1876 return false;
1877 }
1878
1879 return true;
1880 }
1881
1882 enum {
1883 TopLevelAction = 0,
1884 HeadSibAction = 1,
1885 OtherSibAction = 2,
1886 };
1887
1888 // Display an action graph human-readably. Action A is the "sink" node
1889 // and latest-occuring action. Traversal is in pre-order, visiting the
1890 // inputs to each action before printing the action itself.
PrintActions1(const Compilation & C,Action * A,std::map<Action *,unsigned> & Ids,Twine Indent={},int Kind=TopLevelAction)1891 static unsigned PrintActions1(const Compilation &C, Action *A,
1892 std::map<Action *, unsigned> &Ids,
1893 Twine Indent = {}, int Kind = TopLevelAction) {
1894 if (Ids.count(A)) // A was already visited.
1895 return Ids[A];
1896
1897 std::string str;
1898 llvm::raw_string_ostream os(str);
1899
__anon1c4ff0b80702(int K) 1900 auto getSibIndent = [](int K) -> Twine {
1901 return (K == HeadSibAction) ? " " : (K == OtherSibAction) ? "| " : "";
1902 };
1903
1904 Twine SibIndent = Indent + getSibIndent(Kind);
1905 int SibKind = HeadSibAction;
1906 os << Action::getClassName(A->getKind()) << ", ";
1907 if (InputAction *IA = dyn_cast<InputAction>(A)) {
1908 os << "\"" << IA->getInputArg().getValue() << "\"";
1909 } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
1910 os << '"' << BIA->getArchName() << '"' << ", {"
1911 << PrintActions1(C, *BIA->input_begin(), Ids, SibIndent, SibKind) << "}";
1912 } else if (OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
1913 bool IsFirst = true;
1914 OA->doOnEachDependence(
__anon1c4ff0b80802(Action *A, const ToolChain *TC, const char *BoundArch) 1915 [&](Action *A, const ToolChain *TC, const char *BoundArch) {
1916 assert(TC && "Unknown host toolchain");
1917 // E.g. for two CUDA device dependences whose bound arch is sm_20 and
1918 // sm_35 this will generate:
1919 // "cuda-device" (nvptx64-nvidia-cuda:sm_20) {#ID}, "cuda-device"
1920 // (nvptx64-nvidia-cuda:sm_35) {#ID}
1921 if (!IsFirst)
1922 os << ", ";
1923 os << '"';
1924 os << A->getOffloadingKindPrefix();
1925 os << " (";
1926 os << TC->getTriple().normalize();
1927 if (BoundArch)
1928 os << ":" << BoundArch;
1929 os << ")";
1930 os << '"';
1931 os << " {" << PrintActions1(C, A, Ids, SibIndent, SibKind) << "}";
1932 IsFirst = false;
1933 SibKind = OtherSibAction;
1934 });
1935 } else {
1936 const ActionList *AL = &A->getInputs();
1937
1938 if (AL->size()) {
1939 const char *Prefix = "{";
1940 for (Action *PreRequisite : *AL) {
1941 os << Prefix << PrintActions1(C, PreRequisite, Ids, SibIndent, SibKind);
1942 Prefix = ", ";
1943 SibKind = OtherSibAction;
1944 }
1945 os << "}";
1946 } else
1947 os << "{}";
1948 }
1949
1950 // Append offload info for all options other than the offloading action
1951 // itself (e.g. (cuda-device, sm_20) or (cuda-host)).
1952 std::string offload_str;
1953 llvm::raw_string_ostream offload_os(offload_str);
1954 if (!isa<OffloadAction>(A)) {
1955 auto S = A->getOffloadingKindPrefix();
1956 if (!S.empty()) {
1957 offload_os << ", (" << S;
1958 if (A->getOffloadingArch())
1959 offload_os << ", " << A->getOffloadingArch();
1960 offload_os << ")";
1961 }
1962 }
1963
__anon1c4ff0b80902(int K) 1964 auto getSelfIndent = [](int K) -> Twine {
1965 return (K == HeadSibAction) ? "+- " : (K == OtherSibAction) ? "|- " : "";
1966 };
1967
1968 unsigned Id = Ids.size();
1969 Ids[A] = Id;
1970 llvm::errs() << Indent + getSelfIndent(Kind) << Id << ": " << os.str() << ", "
1971 << types::getTypeName(A->getType()) << offload_os.str() << "\n";
1972
1973 return Id;
1974 }
1975
1976 // Print the action graphs in a compilation C.
1977 // For example "clang -c file1.c file2.c" is composed of two subgraphs.
PrintActions(const Compilation & C) const1978 void Driver::PrintActions(const Compilation &C) const {
1979 std::map<Action *, unsigned> Ids;
1980 for (Action *A : C.getActions())
1981 PrintActions1(C, A, Ids);
1982 }
1983
1984 /// Check whether the given input tree contains any compilation or
1985 /// assembly actions.
ContainsCompileOrAssembleAction(const Action * A)1986 static bool ContainsCompileOrAssembleAction(const Action *A) {
1987 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A) ||
1988 isa<AssembleJobAction>(A))
1989 return true;
1990
1991 for (const Action *Input : A->inputs())
1992 if (ContainsCompileOrAssembleAction(Input))
1993 return true;
1994
1995 return false;
1996 }
1997
BuildUniversalActions(Compilation & C,const ToolChain & TC,const InputList & BAInputs) const1998 void Driver::BuildUniversalActions(Compilation &C, const ToolChain &TC,
1999 const InputList &BAInputs) const {
2000 DerivedArgList &Args = C.getArgs();
2001 ActionList &Actions = C.getActions();
2002 llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
2003 // Collect the list of architectures. Duplicates are allowed, but should only
2004 // be handled once (in the order seen).
2005 llvm::StringSet<> ArchNames;
2006 SmallVector<const char *, 4> Archs;
2007 for (Arg *A : Args) {
2008 if (A->getOption().matches(options::OPT_arch)) {
2009 // Validate the option here; we don't save the type here because its
2010 // particular spelling may participate in other driver choices.
2011 llvm::Triple::ArchType Arch =
2012 tools::darwin::getArchTypeForMachOArchName(A->getValue());
2013 if (Arch == llvm::Triple::UnknownArch) {
2014 Diag(clang::diag::err_drv_invalid_arch_name) << A->getAsString(Args);
2015 continue;
2016 }
2017
2018 A->claim();
2019 if (ArchNames.insert(A->getValue()).second)
2020 Archs.push_back(A->getValue());
2021 }
2022 }
2023
2024 // When there is no explicit arch for this platform, make sure we still bind
2025 // the architecture (to the default) so that -Xarch_ is handled correctly.
2026 if (!Archs.size())
2027 Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName()));
2028
2029 ActionList SingleActions;
2030 BuildActions(C, Args, BAInputs, SingleActions);
2031
2032 // Add in arch bindings for every top level action, as well as lipo and
2033 // dsymutil steps if needed.
2034 for (Action* Act : SingleActions) {
2035 // Make sure we can lipo this kind of output. If not (and it is an actual
2036 // output) then we disallow, since we can't create an output file with the
2037 // right name without overwriting it. We could remove this oddity by just
2038 // changing the output names to include the arch, which would also fix
2039 // -save-temps. Compatibility wins for now.
2040
2041 if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
2042 Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
2043 << types::getTypeName(Act->getType());
2044
2045 ActionList Inputs;
2046 for (unsigned i = 0, e = Archs.size(); i != e; ++i)
2047 Inputs.push_back(C.MakeAction<BindArchAction>(Act, Archs[i]));
2048
2049 // Lipo if necessary, we do it this way because we need to set the arch flag
2050 // so that -Xarch_ gets overwritten.
2051 if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
2052 Actions.append(Inputs.begin(), Inputs.end());
2053 else
2054 Actions.push_back(C.MakeAction<LipoJobAction>(Inputs, Act->getType()));
2055
2056 // Handle debug info queries.
2057 Arg *A = Args.getLastArg(options::OPT_g_Group);
2058 bool enablesDebugInfo = A && !A->getOption().matches(options::OPT_g0) &&
2059 !A->getOption().matches(options::OPT_gstabs);
2060 if ((enablesDebugInfo || willEmitRemarks(Args)) &&
2061 ContainsCompileOrAssembleAction(Actions.back())) {
2062
2063 // Add a 'dsymutil' step if necessary, when debug info is enabled and we
2064 // have a compile input. We need to run 'dsymutil' ourselves in such cases
2065 // because the debug info will refer to a temporary object file which
2066 // will be removed at the end of the compilation process.
2067 if (Act->getType() == types::TY_Image) {
2068 ActionList Inputs;
2069 Inputs.push_back(Actions.back());
2070 Actions.pop_back();
2071 Actions.push_back(
2072 C.MakeAction<DsymutilJobAction>(Inputs, types::TY_dSYM));
2073 }
2074
2075 // Verify the debug info output.
2076 if (Args.hasArg(options::OPT_verify_debug_info)) {
2077 Action* LastAction = Actions.back();
2078 Actions.pop_back();
2079 Actions.push_back(C.MakeAction<VerifyDebugInfoJobAction>(
2080 LastAction, types::TY_Nothing));
2081 }
2082 }
2083 }
2084 }
2085
DiagnoseInputExistence(const DerivedArgList & Args,StringRef Value,types::ID Ty,bool TypoCorrect) const2086 bool Driver::DiagnoseInputExistence(const DerivedArgList &Args, StringRef Value,
2087 types::ID Ty, bool TypoCorrect) const {
2088 if (!getCheckInputsExist())
2089 return true;
2090
2091 // stdin always exists.
2092 if (Value == "-")
2093 return true;
2094
2095 if (getVFS().exists(Value))
2096 return true;
2097
2098 if (IsCLMode()) {
2099 if (!llvm::sys::path::is_absolute(Twine(Value)) &&
2100 llvm::sys::Process::FindInEnvPath("LIB", Value, ';'))
2101 return true;
2102
2103 if (Args.hasArg(options::OPT__SLASH_link) && Ty == types::TY_Object) {
2104 // Arguments to the /link flag might cause the linker to search for object
2105 // and library files in paths we don't know about. Don't error in such
2106 // cases.
2107 return true;
2108 }
2109 }
2110
2111 if (TypoCorrect) {
2112 // Check if the filename is a typo for an option flag. OptTable thinks
2113 // that all args that are not known options and that start with / are
2114 // filenames, but e.g. `/diagnostic:caret` is more likely a typo for
2115 // the option `/diagnostics:caret` than a reference to a file in the root
2116 // directory.
2117 unsigned IncludedFlagsBitmask;
2118 unsigned ExcludedFlagsBitmask;
2119 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
2120 getIncludeExcludeOptionFlagMasks(IsCLMode());
2121 std::string Nearest;
2122 if (getOpts().findNearest(Value, Nearest, IncludedFlagsBitmask,
2123 ExcludedFlagsBitmask) <= 1) {
2124 Diag(clang::diag::err_drv_no_such_file_with_suggestion)
2125 << Value << Nearest;
2126 return false;
2127 }
2128 }
2129
2130 Diag(clang::diag::err_drv_no_such_file) << Value;
2131 return false;
2132 }
2133
2134 // Construct a the list of inputs and their types.
BuildInputs(const ToolChain & TC,DerivedArgList & Args,InputList & Inputs) const2135 void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args,
2136 InputList &Inputs) const {
2137 const llvm::opt::OptTable &Opts = getOpts();
2138 // Track the current user specified (-x) input. We also explicitly track the
2139 // argument used to set the type; we only want to claim the type when we
2140 // actually use it, so we warn about unused -x arguments.
2141 types::ID InputType = types::TY_Nothing;
2142 Arg *InputTypeArg = nullptr;
2143
2144 // The last /TC or /TP option sets the input type to C or C++ globally.
2145 if (Arg *TCTP = Args.getLastArgNoClaim(options::OPT__SLASH_TC,
2146 options::OPT__SLASH_TP)) {
2147 InputTypeArg = TCTP;
2148 InputType = TCTP->getOption().matches(options::OPT__SLASH_TC)
2149 ? types::TY_C
2150 : types::TY_CXX;
2151
2152 Arg *Previous = nullptr;
2153 bool ShowNote = false;
2154 for (Arg *A :
2155 Args.filtered(options::OPT__SLASH_TC, options::OPT__SLASH_TP)) {
2156 if (Previous) {
2157 Diag(clang::diag::warn_drv_overriding_flag_option)
2158 << Previous->getSpelling() << A->getSpelling();
2159 ShowNote = true;
2160 }
2161 Previous = A;
2162 }
2163 if (ShowNote)
2164 Diag(clang::diag::note_drv_t_option_is_global);
2165
2166 // No driver mode exposes -x and /TC or /TP; we don't support mixing them.
2167 assert(!Args.hasArg(options::OPT_x) && "-x and /TC or /TP is not allowed");
2168 }
2169
2170 for (Arg *A : Args) {
2171 if (A->getOption().getKind() == Option::InputClass) {
2172 const char *Value = A->getValue();
2173 types::ID Ty = types::TY_INVALID;
2174
2175 // Infer the input type if necessary.
2176 if (InputType == types::TY_Nothing) {
2177 // If there was an explicit arg for this, claim it.
2178 if (InputTypeArg)
2179 InputTypeArg->claim();
2180
2181 // stdin must be handled specially.
2182 if (memcmp(Value, "-", 2) == 0) {
2183 // If running with -E, treat as a C input (this changes the builtin
2184 // macros, for example). This may be overridden by -ObjC below.
2185 //
2186 // Otherwise emit an error but still use a valid type to avoid
2187 // spurious errors (e.g., no inputs).
2188 if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP())
2189 Diag(IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl
2190 : clang::diag::err_drv_unknown_stdin_type);
2191 Ty = types::TY_C;
2192 } else {
2193 // Otherwise lookup by extension.
2194 // Fallback is C if invoked as C preprocessor, C++ if invoked with
2195 // clang-cl /E, or Object otherwise.
2196 // We use a host hook here because Darwin at least has its own
2197 // idea of what .s is.
2198 if (const char *Ext = strrchr(Value, '.'))
2199 Ty = TC.LookupTypeForExtension(Ext + 1);
2200
2201 if (Ty == types::TY_INVALID) {
2202 if (CCCIsCPP())
2203 Ty = types::TY_C;
2204 else if (IsCLMode() && Args.hasArgNoClaim(options::OPT_E))
2205 Ty = types::TY_CXX;
2206 else
2207 Ty = types::TY_Object;
2208 }
2209
2210 // If the driver is invoked as C++ compiler (like clang++ or c++) it
2211 // should autodetect some input files as C++ for g++ compatibility.
2212 if (CCCIsCXX()) {
2213 types::ID OldTy = Ty;
2214 Ty = types::lookupCXXTypeForCType(Ty);
2215
2216 if (Ty != OldTy)
2217 Diag(clang::diag::warn_drv_treating_input_as_cxx)
2218 << getTypeName(OldTy) << getTypeName(Ty);
2219 }
2220
2221 // If running with -fthinlto-index=, extensions that normally identify
2222 // native object files actually identify LLVM bitcode files.
2223 if (Args.hasArgNoClaim(options::OPT_fthinlto_index_EQ) &&
2224 Ty == types::TY_Object)
2225 Ty = types::TY_LLVM_BC;
2226 }
2227
2228 // -ObjC and -ObjC++ override the default language, but only for "source
2229 // files". We just treat everything that isn't a linker input as a
2230 // source file.
2231 //
2232 // FIXME: Clean this up if we move the phase sequence into the type.
2233 if (Ty != types::TY_Object) {
2234 if (Args.hasArg(options::OPT_ObjC))
2235 Ty = types::TY_ObjC;
2236 else if (Args.hasArg(options::OPT_ObjCXX))
2237 Ty = types::TY_ObjCXX;
2238 }
2239 } else {
2240 assert(InputTypeArg && "InputType set w/o InputTypeArg");
2241 if (!InputTypeArg->getOption().matches(options::OPT_x)) {
2242 // If emulating cl.exe, make sure that /TC and /TP don't affect input
2243 // object files.
2244 const char *Ext = strrchr(Value, '.');
2245 if (Ext && TC.LookupTypeForExtension(Ext + 1) == types::TY_Object)
2246 Ty = types::TY_Object;
2247 }
2248 if (Ty == types::TY_INVALID) {
2249 Ty = InputType;
2250 InputTypeArg->claim();
2251 }
2252 }
2253
2254 if (DiagnoseInputExistence(Args, Value, Ty, /*TypoCorrect=*/true))
2255 Inputs.push_back(std::make_pair(Ty, A));
2256
2257 } else if (A->getOption().matches(options::OPT__SLASH_Tc)) {
2258 StringRef Value = A->getValue();
2259 if (DiagnoseInputExistence(Args, Value, types::TY_C,
2260 /*TypoCorrect=*/false)) {
2261 Arg *InputArg = MakeInputArg(Args, Opts, A->getValue());
2262 Inputs.push_back(std::make_pair(types::TY_C, InputArg));
2263 }
2264 A->claim();
2265 } else if (A->getOption().matches(options::OPT__SLASH_Tp)) {
2266 StringRef Value = A->getValue();
2267 if (DiagnoseInputExistence(Args, Value, types::TY_CXX,
2268 /*TypoCorrect=*/false)) {
2269 Arg *InputArg = MakeInputArg(Args, Opts, A->getValue());
2270 Inputs.push_back(std::make_pair(types::TY_CXX, InputArg));
2271 }
2272 A->claim();
2273 } else if (A->getOption().hasFlag(options::LinkerInput)) {
2274 // Just treat as object type, we could make a special type for this if
2275 // necessary.
2276 Inputs.push_back(std::make_pair(types::TY_Object, A));
2277
2278 } else if (A->getOption().matches(options::OPT_x)) {
2279 InputTypeArg = A;
2280 InputType = types::lookupTypeForTypeSpecifier(A->getValue());
2281 A->claim();
2282
2283 // Follow gcc behavior and treat as linker input for invalid -x
2284 // options. Its not clear why we shouldn't just revert to unknown; but
2285 // this isn't very important, we might as well be bug compatible.
2286 if (!InputType) {
2287 Diag(clang::diag::err_drv_unknown_language) << A->getValue();
2288 InputType = types::TY_Object;
2289 }
2290 } else if (A->getOption().getID() == options::OPT_U) {
2291 assert(A->getNumValues() == 1 && "The /U option has one value.");
2292 StringRef Val = A->getValue(0);
2293 if (Val.find_first_of("/\\") != StringRef::npos) {
2294 // Warn about e.g. "/Users/me/myfile.c".
2295 Diag(diag::warn_slash_u_filename) << Val;
2296 Diag(diag::note_use_dashdash);
2297 }
2298 }
2299 }
2300 if (CCCIsCPP() && Inputs.empty()) {
2301 // If called as standalone preprocessor, stdin is processed
2302 // if no other input is present.
2303 Arg *A = MakeInputArg(Args, Opts, "-");
2304 Inputs.push_back(std::make_pair(types::TY_C, A));
2305 }
2306 }
2307
2308 namespace {
2309 /// Provides a convenient interface for different programming models to generate
2310 /// the required device actions.
2311 class OffloadingActionBuilder final {
2312 /// Flag used to trace errors in the builder.
2313 bool IsValid = false;
2314
2315 /// The compilation that is using this builder.
2316 Compilation &C;
2317
2318 /// Map between an input argument and the offload kinds used to process it.
2319 std::map<const Arg *, unsigned> InputArgToOffloadKindMap;
2320
2321 /// Builder interface. It doesn't build anything or keep any state.
2322 class DeviceActionBuilder {
2323 public:
2324 typedef const llvm::SmallVectorImpl<phases::ID> PhasesTy;
2325
2326 enum ActionBuilderReturnCode {
2327 // The builder acted successfully on the current action.
2328 ABRT_Success,
2329 // The builder didn't have to act on the current action.
2330 ABRT_Inactive,
2331 // The builder was successful and requested the host action to not be
2332 // generated.
2333 ABRT_Ignore_Host,
2334 };
2335
2336 protected:
2337 /// Compilation associated with this builder.
2338 Compilation &C;
2339
2340 /// Tool chains associated with this builder. The same programming
2341 /// model may have associated one or more tool chains.
2342 SmallVector<const ToolChain *, 2> ToolChains;
2343
2344 /// The derived arguments associated with this builder.
2345 DerivedArgList &Args;
2346
2347 /// The inputs associated with this builder.
2348 const Driver::InputList &Inputs;
2349
2350 /// The associated offload kind.
2351 Action::OffloadKind AssociatedOffloadKind = Action::OFK_None;
2352
2353 public:
DeviceActionBuilder(Compilation & C,DerivedArgList & Args,const Driver::InputList & Inputs,Action::OffloadKind AssociatedOffloadKind)2354 DeviceActionBuilder(Compilation &C, DerivedArgList &Args,
2355 const Driver::InputList &Inputs,
2356 Action::OffloadKind AssociatedOffloadKind)
2357 : C(C), Args(Args), Inputs(Inputs),
2358 AssociatedOffloadKind(AssociatedOffloadKind) {}
~DeviceActionBuilder()2359 virtual ~DeviceActionBuilder() {}
2360
2361 /// Fill up the array \a DA with all the device dependences that should be
2362 /// added to the provided host action \a HostAction. By default it is
2363 /// inactive.
2364 virtual ActionBuilderReturnCode
getDeviceDependences(OffloadAction::DeviceDependences & DA,phases::ID CurPhase,phases::ID FinalPhase,PhasesTy & Phases)2365 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2366 phases::ID CurPhase, phases::ID FinalPhase,
2367 PhasesTy &Phases) {
2368 return ABRT_Inactive;
2369 }
2370
2371 /// Update the state to include the provided host action \a HostAction as a
2372 /// dependency of the current device action. By default it is inactive.
addDeviceDepences(Action * HostAction)2373 virtual ActionBuilderReturnCode addDeviceDepences(Action *HostAction) {
2374 return ABRT_Inactive;
2375 }
2376
2377 /// Append top level actions generated by the builder.
appendTopLevelActions(ActionList & AL)2378 virtual void appendTopLevelActions(ActionList &AL) {}
2379
2380 /// Append linker device actions generated by the builder.
appendLinkDeviceActions(ActionList & AL)2381 virtual void appendLinkDeviceActions(ActionList &AL) {}
2382
2383 /// Append linker host action generated by the builder.
appendLinkHostActions(ActionList & AL)2384 virtual Action* appendLinkHostActions(ActionList &AL) { return nullptr; }
2385
2386 /// Append linker actions generated by the builder.
appendLinkDependences(OffloadAction::DeviceDependences & DA)2387 virtual void appendLinkDependences(OffloadAction::DeviceDependences &DA) {}
2388
2389 /// Initialize the builder. Return true if any initialization errors are
2390 /// found.
initialize()2391 virtual bool initialize() { return false; }
2392
2393 /// Return true if the builder can use bundling/unbundling.
canUseBundlerUnbundler() const2394 virtual bool canUseBundlerUnbundler() const { return false; }
2395
2396 /// Return true if this builder is valid. We have a valid builder if we have
2397 /// associated device tool chains.
isValid()2398 bool isValid() { return !ToolChains.empty(); }
2399
2400 /// Return the associated offload kind.
getAssociatedOffloadKind()2401 Action::OffloadKind getAssociatedOffloadKind() {
2402 return AssociatedOffloadKind;
2403 }
2404 };
2405
2406 /// Base class for CUDA/HIP action builder. It injects device code in
2407 /// the host backend action.
2408 class CudaActionBuilderBase : public DeviceActionBuilder {
2409 protected:
2410 /// Flags to signal if the user requested host-only or device-only
2411 /// compilation.
2412 bool CompileHostOnly = false;
2413 bool CompileDeviceOnly = false;
2414 bool EmitLLVM = false;
2415 bool EmitAsm = false;
2416
2417 /// ID to identify each device compilation. For CUDA it is simply the
2418 /// GPU arch string. For HIP it is either the GPU arch string or GPU
2419 /// arch string plus feature strings delimited by a plus sign, e.g.
2420 /// gfx906+xnack.
2421 struct TargetID {
2422 /// Target ID string which is persistent throughout the compilation.
2423 const char *ID;
TargetID__anon1c4ff0b80a11::OffloadingActionBuilder::CudaActionBuilderBase::TargetID2424 TargetID(CudaArch Arch) { ID = CudaArchToString(Arch); }
TargetID__anon1c4ff0b80a11::OffloadingActionBuilder::CudaActionBuilderBase::TargetID2425 TargetID(const char *ID) : ID(ID) {}
operator const char*__anon1c4ff0b80a11::OffloadingActionBuilder::CudaActionBuilderBase::TargetID2426 operator const char *() { return ID; }
operator StringRef__anon1c4ff0b80a11::OffloadingActionBuilder::CudaActionBuilderBase::TargetID2427 operator StringRef() { return StringRef(ID); }
2428 };
2429 /// List of GPU architectures to use in this compilation.
2430 SmallVector<TargetID, 4> GpuArchList;
2431
2432 /// The CUDA actions for the current input.
2433 ActionList CudaDeviceActions;
2434
2435 /// The CUDA fat binary if it was generated for the current input.
2436 Action *CudaFatBinary = nullptr;
2437
2438 /// Flag that is set to true if this builder acted on the current input.
2439 bool IsActive = false;
2440
2441 /// Flag for -fgpu-rdc.
2442 bool Relocatable = false;
2443
2444 /// Default GPU architecture if there's no one specified.
2445 CudaArch DefaultCudaArch = CudaArch::UNKNOWN;
2446
2447 public:
CudaActionBuilderBase(Compilation & C,DerivedArgList & Args,const Driver::InputList & Inputs,Action::OffloadKind OFKind)2448 CudaActionBuilderBase(Compilation &C, DerivedArgList &Args,
2449 const Driver::InputList &Inputs,
2450 Action::OffloadKind OFKind)
2451 : DeviceActionBuilder(C, Args, Inputs, OFKind) {}
2452
addDeviceDepences(Action * HostAction)2453 ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
2454 // While generating code for CUDA, we only depend on the host input action
2455 // to trigger the creation of all the CUDA device actions.
2456
2457 // If we are dealing with an input action, replicate it for each GPU
2458 // architecture. If we are in host-only mode we return 'success' so that
2459 // the host uses the CUDA offload kind.
2460 if (auto *IA = dyn_cast<InputAction>(HostAction)) {
2461 assert(!GpuArchList.empty() &&
2462 "We should have at least one GPU architecture.");
2463
2464 // If the host input is not CUDA or HIP, we don't need to bother about
2465 // this input.
2466 if (IA->getType() != types::TY_CUDA &&
2467 IA->getType() != types::TY_HIP) {
2468 // The builder will ignore this input.
2469 IsActive = false;
2470 return ABRT_Inactive;
2471 }
2472
2473 // Set the flag to true, so that the builder acts on the current input.
2474 IsActive = true;
2475
2476 if (CompileHostOnly)
2477 return ABRT_Success;
2478
2479 // Replicate inputs for each GPU architecture.
2480 auto Ty = IA->getType() == types::TY_HIP ? types::TY_HIP_DEVICE
2481 : types::TY_CUDA_DEVICE;
2482 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
2483 CudaDeviceActions.push_back(
2484 C.MakeAction<InputAction>(IA->getInputArg(), Ty));
2485 }
2486
2487 return ABRT_Success;
2488 }
2489
2490 // If this is an unbundling action use it as is for each CUDA toolchain.
2491 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) {
2492
2493 // If -fgpu-rdc is disabled, should not unbundle since there is no
2494 // device code to link.
2495 if (!Relocatable)
2496 return ABRT_Inactive;
2497
2498 CudaDeviceActions.clear();
2499 auto *IA = cast<InputAction>(UA->getInputs().back());
2500 std::string FileName = IA->getInputArg().getAsString(Args);
2501 // Check if the type of the file is the same as the action. Do not
2502 // unbundle it if it is not. Do not unbundle .so files, for example,
2503 // which are not object files.
2504 if (IA->getType() == types::TY_Object &&
2505 (!llvm::sys::path::has_extension(FileName) ||
2506 types::lookupTypeForExtension(
2507 llvm::sys::path::extension(FileName).drop_front()) !=
2508 types::TY_Object))
2509 return ABRT_Inactive;
2510
2511 for (auto Arch : GpuArchList) {
2512 CudaDeviceActions.push_back(UA);
2513 UA->registerDependentActionInfo(ToolChains[0], Arch,
2514 AssociatedOffloadKind);
2515 }
2516 return ABRT_Success;
2517 }
2518
2519 return IsActive ? ABRT_Success : ABRT_Inactive;
2520 }
2521
appendTopLevelActions(ActionList & AL)2522 void appendTopLevelActions(ActionList &AL) override {
2523 // Utility to append actions to the top level list.
2524 auto AddTopLevel = [&](Action *A, TargetID TargetID) {
2525 OffloadAction::DeviceDependences Dep;
2526 Dep.add(*A, *ToolChains.front(), TargetID, AssociatedOffloadKind);
2527 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
2528 };
2529
2530 // If we have a fat binary, add it to the list.
2531 if (CudaFatBinary) {
2532 AddTopLevel(CudaFatBinary, CudaArch::UNUSED);
2533 CudaDeviceActions.clear();
2534 CudaFatBinary = nullptr;
2535 return;
2536 }
2537
2538 if (CudaDeviceActions.empty())
2539 return;
2540
2541 // If we have CUDA actions at this point, that's because we have a have
2542 // partial compilation, so we should have an action for each GPU
2543 // architecture.
2544 assert(CudaDeviceActions.size() == GpuArchList.size() &&
2545 "Expecting one action per GPU architecture.");
2546 assert(ToolChains.size() == 1 &&
2547 "Expecting to have a sing CUDA toolchain.");
2548 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
2549 AddTopLevel(CudaDeviceActions[I], GpuArchList[I]);
2550
2551 CudaDeviceActions.clear();
2552 }
2553
2554 /// Get canonicalized offload arch option. \returns empty StringRef if the
2555 /// option is invalid.
2556 virtual StringRef getCanonicalOffloadArch(StringRef Arch) = 0;
2557
2558 virtual llvm::Optional<std::pair<llvm::StringRef, llvm::StringRef>>
2559 getConflictOffloadArchCombination(const std::set<StringRef> &GpuArchs) = 0;
2560
initialize()2561 bool initialize() override {
2562 assert(AssociatedOffloadKind == Action::OFK_Cuda ||
2563 AssociatedOffloadKind == Action::OFK_HIP);
2564
2565 // We don't need to support CUDA.
2566 if (AssociatedOffloadKind == Action::OFK_Cuda &&
2567 !C.hasOffloadToolChain<Action::OFK_Cuda>())
2568 return false;
2569
2570 // We don't need to support HIP.
2571 if (AssociatedOffloadKind == Action::OFK_HIP &&
2572 !C.hasOffloadToolChain<Action::OFK_HIP>())
2573 return false;
2574
2575 Relocatable = Args.hasFlag(options::OPT_fgpu_rdc,
2576 options::OPT_fno_gpu_rdc, /*Default=*/false);
2577
2578 const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
2579 assert(HostTC && "No toolchain for host compilation.");
2580 if (HostTC->getTriple().isNVPTX() ||
2581 HostTC->getTriple().getArch() == llvm::Triple::amdgcn) {
2582 // We do not support targeting NVPTX/AMDGCN for host compilation. Throw
2583 // an error and abort pipeline construction early so we don't trip
2584 // asserts that assume device-side compilation.
2585 C.getDriver().Diag(diag::err_drv_cuda_host_arch)
2586 << HostTC->getTriple().getArchName();
2587 return true;
2588 }
2589
2590 ToolChains.push_back(
2591 AssociatedOffloadKind == Action::OFK_Cuda
2592 ? C.getSingleOffloadToolChain<Action::OFK_Cuda>()
2593 : C.getSingleOffloadToolChain<Action::OFK_HIP>());
2594
2595 Arg *PartialCompilationArg = Args.getLastArg(
2596 options::OPT_cuda_host_only, options::OPT_cuda_device_only,
2597 options::OPT_cuda_compile_host_device);
2598 CompileHostOnly = PartialCompilationArg &&
2599 PartialCompilationArg->getOption().matches(
2600 options::OPT_cuda_host_only);
2601 CompileDeviceOnly = PartialCompilationArg &&
2602 PartialCompilationArg->getOption().matches(
2603 options::OPT_cuda_device_only);
2604 EmitLLVM = Args.getLastArg(options::OPT_emit_llvm);
2605 EmitAsm = Args.getLastArg(options::OPT_S);
2606
2607 // Collect all cuda_gpu_arch parameters, removing duplicates.
2608 std::set<StringRef> GpuArchs;
2609 bool Error = false;
2610 for (Arg *A : Args) {
2611 if (!(A->getOption().matches(options::OPT_offload_arch_EQ) ||
2612 A->getOption().matches(options::OPT_no_offload_arch_EQ)))
2613 continue;
2614 A->claim();
2615
2616 StringRef ArchStr = A->getValue();
2617 if (A->getOption().matches(options::OPT_no_offload_arch_EQ) &&
2618 ArchStr == "all") {
2619 GpuArchs.clear();
2620 continue;
2621 }
2622 ArchStr = getCanonicalOffloadArch(ArchStr);
2623 if (ArchStr.empty()) {
2624 Error = true;
2625 } else if (A->getOption().matches(options::OPT_offload_arch_EQ))
2626 GpuArchs.insert(ArchStr);
2627 else if (A->getOption().matches(options::OPT_no_offload_arch_EQ))
2628 GpuArchs.erase(ArchStr);
2629 else
2630 llvm_unreachable("Unexpected option.");
2631 }
2632
2633 auto &&ConflictingArchs = getConflictOffloadArchCombination(GpuArchs);
2634 if (ConflictingArchs) {
2635 C.getDriver().Diag(clang::diag::err_drv_bad_offload_arch_combo)
2636 << ConflictingArchs.getValue().first
2637 << ConflictingArchs.getValue().second;
2638 C.setContainsError();
2639 return true;
2640 }
2641
2642 // Collect list of GPUs remaining in the set.
2643 for (auto Arch : GpuArchs)
2644 GpuArchList.push_back(Arch.data());
2645
2646 // Default to sm_20 which is the lowest common denominator for
2647 // supported GPUs. sm_20 code should work correctly, if
2648 // suboptimally, on all newer GPUs.
2649 if (GpuArchList.empty())
2650 GpuArchList.push_back(DefaultCudaArch);
2651
2652 return Error;
2653 }
2654 };
2655
2656 /// \brief CUDA action builder. It injects device code in the host backend
2657 /// action.
2658 class CudaActionBuilder final : public CudaActionBuilderBase {
2659 public:
CudaActionBuilder(Compilation & C,DerivedArgList & Args,const Driver::InputList & Inputs)2660 CudaActionBuilder(Compilation &C, DerivedArgList &Args,
2661 const Driver::InputList &Inputs)
2662 : CudaActionBuilderBase(C, Args, Inputs, Action::OFK_Cuda) {
2663 DefaultCudaArch = CudaArch::SM_20;
2664 }
2665
getCanonicalOffloadArch(StringRef ArchStr)2666 StringRef getCanonicalOffloadArch(StringRef ArchStr) override {
2667 CudaArch Arch = StringToCudaArch(ArchStr);
2668 if (Arch == CudaArch::UNKNOWN) {
2669 C.getDriver().Diag(clang::diag::err_drv_cuda_bad_gpu_arch) << ArchStr;
2670 return StringRef();
2671 }
2672 return CudaArchToString(Arch);
2673 }
2674
2675 llvm::Optional<std::pair<llvm::StringRef, llvm::StringRef>>
getConflictOffloadArchCombination(const std::set<StringRef> & GpuArchs)2676 getConflictOffloadArchCombination(
2677 const std::set<StringRef> &GpuArchs) override {
2678 return llvm::None;
2679 }
2680
2681 ActionBuilderReturnCode
getDeviceDependences(OffloadAction::DeviceDependences & DA,phases::ID CurPhase,phases::ID FinalPhase,PhasesTy & Phases)2682 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2683 phases::ID CurPhase, phases::ID FinalPhase,
2684 PhasesTy &Phases) override {
2685 if (!IsActive)
2686 return ABRT_Inactive;
2687
2688 // If we don't have more CUDA actions, we don't have any dependences to
2689 // create for the host.
2690 if (CudaDeviceActions.empty())
2691 return ABRT_Success;
2692
2693 assert(CudaDeviceActions.size() == GpuArchList.size() &&
2694 "Expecting one action per GPU architecture.");
2695 assert(!CompileHostOnly &&
2696 "Not expecting CUDA actions in host-only compilation.");
2697
2698 // If we are generating code for the device or we are in a backend phase,
2699 // we attempt to generate the fat binary. We compile each arch to ptx and
2700 // assemble to cubin, then feed the cubin *and* the ptx into a device
2701 // "link" action, which uses fatbinary to combine these cubins into one
2702 // fatbin. The fatbin is then an input to the host action if not in
2703 // device-only mode.
2704 if (CompileDeviceOnly || CurPhase == phases::Backend) {
2705 ActionList DeviceActions;
2706 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
2707 // Produce the device action from the current phase up to the assemble
2708 // phase.
2709 for (auto Ph : Phases) {
2710 // Skip the phases that were already dealt with.
2711 if (Ph < CurPhase)
2712 continue;
2713 // We have to be consistent with the host final phase.
2714 if (Ph > FinalPhase)
2715 break;
2716
2717 CudaDeviceActions[I] = C.getDriver().ConstructPhaseAction(
2718 C, Args, Ph, CudaDeviceActions[I], Action::OFK_Cuda);
2719
2720 if (Ph == phases::Assemble)
2721 break;
2722 }
2723
2724 // If we didn't reach the assemble phase, we can't generate the fat
2725 // binary. We don't need to generate the fat binary if we are not in
2726 // device-only mode.
2727 if (!isa<AssembleJobAction>(CudaDeviceActions[I]) ||
2728 CompileDeviceOnly)
2729 continue;
2730
2731 Action *AssembleAction = CudaDeviceActions[I];
2732 assert(AssembleAction->getType() == types::TY_Object);
2733 assert(AssembleAction->getInputs().size() == 1);
2734
2735 Action *BackendAction = AssembleAction->getInputs()[0];
2736 assert(BackendAction->getType() == types::TY_PP_Asm);
2737
2738 for (auto &A : {AssembleAction, BackendAction}) {
2739 OffloadAction::DeviceDependences DDep;
2740 DDep.add(*A, *ToolChains.front(), GpuArchList[I], Action::OFK_Cuda);
2741 DeviceActions.push_back(
2742 C.MakeAction<OffloadAction>(DDep, A->getType()));
2743 }
2744 }
2745
2746 // We generate the fat binary if we have device input actions.
2747 if (!DeviceActions.empty()) {
2748 CudaFatBinary =
2749 C.MakeAction<LinkJobAction>(DeviceActions, types::TY_CUDA_FATBIN);
2750
2751 if (!CompileDeviceOnly) {
2752 DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
2753 Action::OFK_Cuda);
2754 // Clear the fat binary, it is already a dependence to an host
2755 // action.
2756 CudaFatBinary = nullptr;
2757 }
2758
2759 // Remove the CUDA actions as they are already connected to an host
2760 // action or fat binary.
2761 CudaDeviceActions.clear();
2762 }
2763
2764 // We avoid creating host action in device-only mode.
2765 return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
2766 } else if (CurPhase > phases::Backend) {
2767 // If we are past the backend phase and still have a device action, we
2768 // don't have to do anything as this action is already a device
2769 // top-level action.
2770 return ABRT_Success;
2771 }
2772
2773 assert(CurPhase < phases::Backend && "Generating single CUDA "
2774 "instructions should only occur "
2775 "before the backend phase!");
2776
2777 // By default, we produce an action for each device arch.
2778 for (Action *&A : CudaDeviceActions)
2779 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
2780
2781 return ABRT_Success;
2782 }
2783 };
2784 /// \brief HIP action builder. It injects device code in the host backend
2785 /// action.
2786 class HIPActionBuilder final : public CudaActionBuilderBase {
2787 /// The linker inputs obtained for each device arch.
2788 SmallVector<ActionList, 8> DeviceLinkerInputs;
2789
2790 public:
HIPActionBuilder(Compilation & C,DerivedArgList & Args,const Driver::InputList & Inputs)2791 HIPActionBuilder(Compilation &C, DerivedArgList &Args,
2792 const Driver::InputList &Inputs)
2793 : CudaActionBuilderBase(C, Args, Inputs, Action::OFK_HIP) {
2794 DefaultCudaArch = CudaArch::GFX803;
2795 }
2796
canUseBundlerUnbundler() const2797 bool canUseBundlerUnbundler() const override { return true; }
2798
getCanonicalOffloadArch(StringRef IdStr)2799 StringRef getCanonicalOffloadArch(StringRef IdStr) override {
2800 llvm::StringMap<bool> Features;
2801 auto ArchStr =
2802 parseTargetID(getHIPOffloadTargetTriple(), IdStr, &Features);
2803 if (!ArchStr) {
2804 C.getDriver().Diag(clang::diag::err_drv_bad_target_id) << IdStr;
2805 C.setContainsError();
2806 return StringRef();
2807 }
2808 auto CanId = getCanonicalTargetID(ArchStr.getValue(), Features);
2809 return Args.MakeArgStringRef(CanId);
2810 };
2811
2812 llvm::Optional<std::pair<llvm::StringRef, llvm::StringRef>>
getConflictOffloadArchCombination(const std::set<StringRef> & GpuArchs)2813 getConflictOffloadArchCombination(
2814 const std::set<StringRef> &GpuArchs) override {
2815 return getConflictTargetIDCombination(GpuArchs);
2816 }
2817
2818 ActionBuilderReturnCode
getDeviceDependences(OffloadAction::DeviceDependences & DA,phases::ID CurPhase,phases::ID FinalPhase,PhasesTy & Phases)2819 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2820 phases::ID CurPhase, phases::ID FinalPhase,
2821 PhasesTy &Phases) override {
2822 // amdgcn does not support linking of object files, therefore we skip
2823 // backend and assemble phases to output LLVM IR. Except for generating
2824 // non-relocatable device coee, where we generate fat binary for device
2825 // code and pass to host in Backend phase.
2826 if (CudaDeviceActions.empty())
2827 return ABRT_Success;
2828
2829 assert(((CurPhase == phases::Link && Relocatable) ||
2830 CudaDeviceActions.size() == GpuArchList.size()) &&
2831 "Expecting one action per GPU architecture.");
2832 assert(!CompileHostOnly &&
2833 "Not expecting CUDA actions in host-only compilation.");
2834
2835 if (!Relocatable && CurPhase == phases::Backend && !EmitLLVM &&
2836 !EmitAsm) {
2837 // If we are in backend phase, we attempt to generate the fat binary.
2838 // We compile each arch to IR and use a link action to generate code
2839 // object containing ISA. Then we use a special "link" action to create
2840 // a fat binary containing all the code objects for different GPU's.
2841 // The fat binary is then an input to the host action.
2842 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
2843 auto BackendAction = C.getDriver().ConstructPhaseAction(
2844 C, Args, phases::Backend, CudaDeviceActions[I],
2845 AssociatedOffloadKind);
2846 auto AssembleAction = C.getDriver().ConstructPhaseAction(
2847 C, Args, phases::Assemble, BackendAction, AssociatedOffloadKind);
2848 // Create a link action to link device IR with device library
2849 // and generate ISA.
2850 ActionList AL;
2851 AL.push_back(AssembleAction);
2852 CudaDeviceActions[I] =
2853 C.MakeAction<LinkJobAction>(AL, types::TY_Image);
2854
2855 // OffloadingActionBuilder propagates device arch until an offload
2856 // action. Since the next action for creating fatbin does
2857 // not have device arch, whereas the above link action and its input
2858 // have device arch, an offload action is needed to stop the null
2859 // device arch of the next action being propagated to the above link
2860 // action.
2861 OffloadAction::DeviceDependences DDep;
2862 DDep.add(*CudaDeviceActions[I], *ToolChains.front(), GpuArchList[I],
2863 AssociatedOffloadKind);
2864 CudaDeviceActions[I] = C.MakeAction<OffloadAction>(
2865 DDep, CudaDeviceActions[I]->getType());
2866 }
2867 // Create HIP fat binary with a special "link" action.
2868 CudaFatBinary =
2869 C.MakeAction<LinkJobAction>(CudaDeviceActions,
2870 types::TY_HIP_FATBIN);
2871
2872 if (!CompileDeviceOnly) {
2873 DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
2874 AssociatedOffloadKind);
2875 // Clear the fat binary, it is already a dependence to an host
2876 // action.
2877 CudaFatBinary = nullptr;
2878 }
2879
2880 // Remove the CUDA actions as they are already connected to an host
2881 // action or fat binary.
2882 CudaDeviceActions.clear();
2883
2884 return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
2885 } else if (CurPhase == phases::Link) {
2886 // Save CudaDeviceActions to DeviceLinkerInputs for each GPU subarch.
2887 // This happens to each device action originated from each input file.
2888 // Later on, device actions in DeviceLinkerInputs are used to create
2889 // device link actions in appendLinkDependences and the created device
2890 // link actions are passed to the offload action as device dependence.
2891 DeviceLinkerInputs.resize(CudaDeviceActions.size());
2892 auto LI = DeviceLinkerInputs.begin();
2893 for (auto *A : CudaDeviceActions) {
2894 LI->push_back(A);
2895 ++LI;
2896 }
2897
2898 // We will pass the device action as a host dependence, so we don't
2899 // need to do anything else with them.
2900 CudaDeviceActions.clear();
2901 return ABRT_Success;
2902 }
2903
2904 // By default, we produce an action for each device arch.
2905 for (Action *&A : CudaDeviceActions)
2906 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A,
2907 AssociatedOffloadKind);
2908
2909 return (CompileDeviceOnly && CurPhase == FinalPhase) ? ABRT_Ignore_Host
2910 : ABRT_Success;
2911 }
2912
appendLinkDeviceActions(ActionList & AL)2913 void appendLinkDeviceActions(ActionList &AL) override {
2914 if (DeviceLinkerInputs.size() == 0)
2915 return;
2916
2917 assert(DeviceLinkerInputs.size() == GpuArchList.size() &&
2918 "Linker inputs and GPU arch list sizes do not match.");
2919
2920 // Append a new link action for each device.
2921 unsigned I = 0;
2922 for (auto &LI : DeviceLinkerInputs) {
2923 // Each entry in DeviceLinkerInputs corresponds to a GPU arch.
2924 auto *DeviceLinkAction =
2925 C.MakeAction<LinkJobAction>(LI, types::TY_Image);
2926 // Linking all inputs for the current GPU arch.
2927 // LI contains all the inputs for the linker.
2928 OffloadAction::DeviceDependences DeviceLinkDeps;
2929 DeviceLinkDeps.add(*DeviceLinkAction, *ToolChains[0],
2930 GpuArchList[I], AssociatedOffloadKind);
2931 AL.push_back(C.MakeAction<OffloadAction>(DeviceLinkDeps,
2932 DeviceLinkAction->getType()));
2933 ++I;
2934 }
2935 DeviceLinkerInputs.clear();
2936
2937 // Create a host object from all the device images by embedding them
2938 // in a fat binary.
2939 OffloadAction::DeviceDependences DDeps;
2940 auto *TopDeviceLinkAction =
2941 C.MakeAction<LinkJobAction>(AL, types::TY_Object);
2942 DDeps.add(*TopDeviceLinkAction, *ToolChains[0],
2943 nullptr, AssociatedOffloadKind);
2944
2945 // Offload the host object to the host linker.
2946 AL.push_back(C.MakeAction<OffloadAction>(DDeps, TopDeviceLinkAction->getType()));
2947 }
2948
appendLinkHostActions(ActionList & AL)2949 Action* appendLinkHostActions(ActionList &AL) override { return AL.back(); }
2950
appendLinkDependences(OffloadAction::DeviceDependences & DA)2951 void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {}
2952 };
2953
2954 /// OpenMP action builder. The host bitcode is passed to the device frontend
2955 /// and all the device linked images are passed to the host link phase.
2956 class OpenMPActionBuilder final : public DeviceActionBuilder {
2957 /// The OpenMP actions for the current input.
2958 ActionList OpenMPDeviceActions;
2959
2960 /// The linker inputs obtained for each toolchain.
2961 SmallVector<ActionList, 8> DeviceLinkerInputs;
2962
2963 public:
OpenMPActionBuilder(Compilation & C,DerivedArgList & Args,const Driver::InputList & Inputs)2964 OpenMPActionBuilder(Compilation &C, DerivedArgList &Args,
2965 const Driver::InputList &Inputs)
2966 : DeviceActionBuilder(C, Args, Inputs, Action::OFK_OpenMP) {}
2967
2968 ActionBuilderReturnCode
getDeviceDependences(OffloadAction::DeviceDependences & DA,phases::ID CurPhase,phases::ID FinalPhase,PhasesTy & Phases)2969 getDeviceDependences(OffloadAction::DeviceDependences &DA,
2970 phases::ID CurPhase, phases::ID FinalPhase,
2971 PhasesTy &Phases) override {
2972 if (OpenMPDeviceActions.empty())
2973 return ABRT_Inactive;
2974
2975 // We should always have an action for each input.
2976 assert(OpenMPDeviceActions.size() == ToolChains.size() &&
2977 "Number of OpenMP actions and toolchains do not match.");
2978
2979 // The host only depends on device action in the linking phase, when all
2980 // the device images have to be embedded in the host image.
2981 if (CurPhase == phases::Link) {
2982 assert(ToolChains.size() == DeviceLinkerInputs.size() &&
2983 "Toolchains and linker inputs sizes do not match.");
2984 auto LI = DeviceLinkerInputs.begin();
2985 for (auto *A : OpenMPDeviceActions) {
2986 LI->push_back(A);
2987 ++LI;
2988 }
2989
2990 // We passed the device action as a host dependence, so we don't need to
2991 // do anything else with them.
2992 OpenMPDeviceActions.clear();
2993 return ABRT_Success;
2994 }
2995
2996 // By default, we produce an action for each device arch.
2997 for (Action *&A : OpenMPDeviceActions)
2998 A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
2999
3000 return ABRT_Success;
3001 }
3002
addDeviceDepences(Action * HostAction)3003 ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
3004
3005 // If this is an input action replicate it for each OpenMP toolchain.
3006 if (auto *IA = dyn_cast<InputAction>(HostAction)) {
3007 OpenMPDeviceActions.clear();
3008 for (unsigned I = 0; I < ToolChains.size(); ++I)
3009 OpenMPDeviceActions.push_back(
3010 C.MakeAction<InputAction>(IA->getInputArg(), IA->getType()));
3011 return ABRT_Success;
3012 }
3013
3014 // If this is an unbundling action use it as is for each OpenMP toolchain.
3015 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) {
3016 OpenMPDeviceActions.clear();
3017 auto *IA = cast<InputAction>(UA->getInputs().back());
3018 std::string FileName = IA->getInputArg().getAsString(Args);
3019 // Check if the type of the file is the same as the action. Do not
3020 // unbundle it if it is not. Do not unbundle .so files, for example,
3021 // which are not object files.
3022 if (IA->getType() == types::TY_Object &&
3023 (!llvm::sys::path::has_extension(FileName) ||
3024 types::lookupTypeForExtension(
3025 llvm::sys::path::extension(FileName).drop_front()) !=
3026 types::TY_Object))
3027 return ABRT_Inactive;
3028 for (unsigned I = 0; I < ToolChains.size(); ++I) {
3029 OpenMPDeviceActions.push_back(UA);
3030 UA->registerDependentActionInfo(
3031 ToolChains[I], /*BoundArch=*/StringRef(), Action::OFK_OpenMP);
3032 }
3033 return ABRT_Success;
3034 }
3035
3036 // When generating code for OpenMP we use the host compile phase result as
3037 // a dependence to the device compile phase so that it can learn what
3038 // declarations should be emitted. However, this is not the only use for
3039 // the host action, so we prevent it from being collapsed.
3040 if (isa<CompileJobAction>(HostAction)) {
3041 HostAction->setCannotBeCollapsedWithNextDependentAction();
3042 assert(ToolChains.size() == OpenMPDeviceActions.size() &&
3043 "Toolchains and device action sizes do not match.");
3044 OffloadAction::HostDependence HDep(
3045 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
3046 /*BoundArch=*/nullptr, Action::OFK_OpenMP);
3047 auto TC = ToolChains.begin();
3048 for (Action *&A : OpenMPDeviceActions) {
3049 assert(isa<CompileJobAction>(A));
3050 OffloadAction::DeviceDependences DDep;
3051 DDep.add(*A, **TC, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
3052 A = C.MakeAction<OffloadAction>(HDep, DDep);
3053 ++TC;
3054 }
3055 }
3056 return ABRT_Success;
3057 }
3058
appendTopLevelActions(ActionList & AL)3059 void appendTopLevelActions(ActionList &AL) override {
3060 if (OpenMPDeviceActions.empty())
3061 return;
3062
3063 // We should always have an action for each input.
3064 assert(OpenMPDeviceActions.size() == ToolChains.size() &&
3065 "Number of OpenMP actions and toolchains do not match.");
3066
3067 // Append all device actions followed by the proper offload action.
3068 auto TI = ToolChains.begin();
3069 for (auto *A : OpenMPDeviceActions) {
3070 OffloadAction::DeviceDependences Dep;
3071 Dep.add(*A, **TI, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
3072 AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
3073 ++TI;
3074 }
3075 // We no longer need the action stored in this builder.
3076 OpenMPDeviceActions.clear();
3077 }
3078
appendLinkDeviceActions(ActionList & AL)3079 void appendLinkDeviceActions(ActionList &AL) override {
3080 assert(ToolChains.size() == DeviceLinkerInputs.size() &&
3081 "Toolchains and linker inputs sizes do not match.");
3082
3083 // Append a new link action for each device.
3084 auto TC = ToolChains.begin();
3085 for (auto &LI : DeviceLinkerInputs) {
3086 auto *DeviceLinkAction =
3087 C.MakeAction<LinkJobAction>(LI, types::TY_Image);
3088 OffloadAction::DeviceDependences DeviceLinkDeps;
3089 DeviceLinkDeps.add(*DeviceLinkAction, **TC, /*BoundArch=*/nullptr,
3090 Action::OFK_OpenMP);
3091 AL.push_back(C.MakeAction<OffloadAction>(DeviceLinkDeps,
3092 DeviceLinkAction->getType()));
3093 ++TC;
3094 }
3095 DeviceLinkerInputs.clear();
3096 }
3097
appendLinkHostActions(ActionList & AL)3098 Action* appendLinkHostActions(ActionList &AL) override {
3099 // Create wrapper bitcode from the result of device link actions and compile
3100 // it to an object which will be added to the host link command.
3101 auto *BC = C.MakeAction<OffloadWrapperJobAction>(AL, types::TY_LLVM_BC);
3102 auto *ASM = C.MakeAction<BackendJobAction>(BC, types::TY_PP_Asm);
3103 return C.MakeAction<AssembleJobAction>(ASM, types::TY_Object);
3104 }
3105
appendLinkDependences(OffloadAction::DeviceDependences & DA)3106 void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {}
3107
initialize()3108 bool initialize() override {
3109 // Get the OpenMP toolchains. If we don't get any, the action builder will
3110 // know there is nothing to do related to OpenMP offloading.
3111 auto OpenMPTCRange = C.getOffloadToolChains<Action::OFK_OpenMP>();
3112 for (auto TI = OpenMPTCRange.first, TE = OpenMPTCRange.second; TI != TE;
3113 ++TI)
3114 ToolChains.push_back(TI->second);
3115
3116 DeviceLinkerInputs.resize(ToolChains.size());
3117 return false;
3118 }
3119
canUseBundlerUnbundler() const3120 bool canUseBundlerUnbundler() const override {
3121 // OpenMP should use bundled files whenever possible.
3122 return true;
3123 }
3124 };
3125
3126 ///
3127 /// TODO: Add the implementation for other specialized builders here.
3128 ///
3129
3130 /// Specialized builders being used by this offloading action builder.
3131 SmallVector<DeviceActionBuilder *, 4> SpecializedBuilders;
3132
3133 /// Flag set to true if all valid builders allow file bundling/unbundling.
3134 bool CanUseBundler;
3135
3136 public:
OffloadingActionBuilder(Compilation & C,DerivedArgList & Args,const Driver::InputList & Inputs)3137 OffloadingActionBuilder(Compilation &C, DerivedArgList &Args,
3138 const Driver::InputList &Inputs)
3139 : C(C) {
3140 // Create a specialized builder for each device toolchain.
3141
3142 IsValid = true;
3143
3144 // Create a specialized builder for CUDA.
3145 SpecializedBuilders.push_back(new CudaActionBuilder(C, Args, Inputs));
3146
3147 // Create a specialized builder for HIP.
3148 SpecializedBuilders.push_back(new HIPActionBuilder(C, Args, Inputs));
3149
3150 // Create a specialized builder for OpenMP.
3151 SpecializedBuilders.push_back(new OpenMPActionBuilder(C, Args, Inputs));
3152
3153 //
3154 // TODO: Build other specialized builders here.
3155 //
3156
3157 // Initialize all the builders, keeping track of errors. If all valid
3158 // builders agree that we can use bundling, set the flag to true.
3159 unsigned ValidBuilders = 0u;
3160 unsigned ValidBuildersSupportingBundling = 0u;
3161 for (auto *SB : SpecializedBuilders) {
3162 IsValid = IsValid && !SB->initialize();
3163
3164 // Update the counters if the builder is valid.
3165 if (SB->isValid()) {
3166 ++ValidBuilders;
3167 if (SB->canUseBundlerUnbundler())
3168 ++ValidBuildersSupportingBundling;
3169 }
3170 }
3171 CanUseBundler =
3172 ValidBuilders && ValidBuilders == ValidBuildersSupportingBundling;
3173 }
3174
~OffloadingActionBuilder()3175 ~OffloadingActionBuilder() {
3176 for (auto *SB : SpecializedBuilders)
3177 delete SB;
3178 }
3179
3180 /// Generate an action that adds device dependences (if any) to a host action.
3181 /// If no device dependence actions exist, just return the host action \a
3182 /// HostAction. If an error is found or if no builder requires the host action
3183 /// to be generated, return nullptr.
3184 Action *
addDeviceDependencesToHostAction(Action * HostAction,const Arg * InputArg,phases::ID CurPhase,phases::ID FinalPhase,DeviceActionBuilder::PhasesTy & Phases)3185 addDeviceDependencesToHostAction(Action *HostAction, const Arg *InputArg,
3186 phases::ID CurPhase, phases::ID FinalPhase,
3187 DeviceActionBuilder::PhasesTy &Phases) {
3188 if (!IsValid)
3189 return nullptr;
3190
3191 if (SpecializedBuilders.empty())
3192 return HostAction;
3193
3194 assert(HostAction && "Invalid host action!");
3195
3196 OffloadAction::DeviceDependences DDeps;
3197 // Check if all the programming models agree we should not emit the host
3198 // action. Also, keep track of the offloading kinds employed.
3199 auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
3200 unsigned InactiveBuilders = 0u;
3201 unsigned IgnoringBuilders = 0u;
3202 for (auto *SB : SpecializedBuilders) {
3203 if (!SB->isValid()) {
3204 ++InactiveBuilders;
3205 continue;
3206 }
3207
3208 auto RetCode =
3209 SB->getDeviceDependences(DDeps, CurPhase, FinalPhase, Phases);
3210
3211 // If the builder explicitly says the host action should be ignored,
3212 // we need to increment the variable that tracks the builders that request
3213 // the host object to be ignored.
3214 if (RetCode == DeviceActionBuilder::ABRT_Ignore_Host)
3215 ++IgnoringBuilders;
3216
3217 // Unless the builder was inactive for this action, we have to record the
3218 // offload kind because the host will have to use it.
3219 if (RetCode != DeviceActionBuilder::ABRT_Inactive)
3220 OffloadKind |= SB->getAssociatedOffloadKind();
3221 }
3222
3223 // If all builders agree that the host object should be ignored, just return
3224 // nullptr.
3225 if (IgnoringBuilders &&
3226 SpecializedBuilders.size() == (InactiveBuilders + IgnoringBuilders))
3227 return nullptr;
3228
3229 if (DDeps.getActions().empty())
3230 return HostAction;
3231
3232 // We have dependences we need to bundle together. We use an offload action
3233 // for that.
3234 OffloadAction::HostDependence HDep(
3235 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
3236 /*BoundArch=*/nullptr, DDeps);
3237 return C.MakeAction<OffloadAction>(HDep, DDeps);
3238 }
3239
3240 /// Generate an action that adds a host dependence to a device action. The
3241 /// results will be kept in this action builder. Return true if an error was
3242 /// found.
addHostDependenceToDeviceActions(Action * & HostAction,const Arg * InputArg)3243 bool addHostDependenceToDeviceActions(Action *&HostAction,
3244 const Arg *InputArg) {
3245 if (!IsValid)
3246 return true;
3247
3248 // If we are supporting bundling/unbundling and the current action is an
3249 // input action of non-source file, we replace the host action by the
3250 // unbundling action. The bundler tool has the logic to detect if an input
3251 // is a bundle or not and if the input is not a bundle it assumes it is a
3252 // host file. Therefore it is safe to create an unbundling action even if
3253 // the input is not a bundle.
3254 if (CanUseBundler && isa<InputAction>(HostAction) &&
3255 InputArg->getOption().getKind() == llvm::opt::Option::InputClass &&
3256 !types::isSrcFile(HostAction->getType())) {
3257 auto UnbundlingHostAction =
3258 C.MakeAction<OffloadUnbundlingJobAction>(HostAction);
3259 UnbundlingHostAction->registerDependentActionInfo(
3260 C.getSingleOffloadToolChain<Action::OFK_Host>(),
3261 /*BoundArch=*/StringRef(), Action::OFK_Host);
3262 HostAction = UnbundlingHostAction;
3263 }
3264
3265 assert(HostAction && "Invalid host action!");
3266
3267 // Register the offload kinds that are used.
3268 auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
3269 for (auto *SB : SpecializedBuilders) {
3270 if (!SB->isValid())
3271 continue;
3272
3273 auto RetCode = SB->addDeviceDepences(HostAction);
3274
3275 // Host dependences for device actions are not compatible with that same
3276 // action being ignored.
3277 assert(RetCode != DeviceActionBuilder::ABRT_Ignore_Host &&
3278 "Host dependence not expected to be ignored.!");
3279
3280 // Unless the builder was inactive for this action, we have to record the
3281 // offload kind because the host will have to use it.
3282 if (RetCode != DeviceActionBuilder::ABRT_Inactive)
3283 OffloadKind |= SB->getAssociatedOffloadKind();
3284 }
3285
3286 // Do not use unbundler if the Host does not depend on device action.
3287 if (OffloadKind == Action::OFK_None && CanUseBundler)
3288 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction))
3289 HostAction = UA->getInputs().back();
3290
3291 return false;
3292 }
3293
3294 /// Add the offloading top level actions to the provided action list. This
3295 /// function can replace the host action by a bundling action if the
3296 /// programming models allow it.
appendTopLevelActions(ActionList & AL,Action * HostAction,const Arg * InputArg)3297 bool appendTopLevelActions(ActionList &AL, Action *HostAction,
3298 const Arg *InputArg) {
3299 // Get the device actions to be appended.
3300 ActionList OffloadAL;
3301 for (auto *SB : SpecializedBuilders) {
3302 if (!SB->isValid())
3303 continue;
3304 SB->appendTopLevelActions(OffloadAL);
3305 }
3306
3307 // If we can use the bundler, replace the host action by the bundling one in
3308 // the resulting list. Otherwise, just append the device actions. For
3309 // device only compilation, HostAction is a null pointer, therefore only do
3310 // this when HostAction is not a null pointer.
3311 if (CanUseBundler && HostAction &&
3312 HostAction->getType() != types::TY_Nothing && !OffloadAL.empty()) {
3313 // Add the host action to the list in order to create the bundling action.
3314 OffloadAL.push_back(HostAction);
3315
3316 // We expect that the host action was just appended to the action list
3317 // before this method was called.
3318 assert(HostAction == AL.back() && "Host action not in the list??");
3319 HostAction = C.MakeAction<OffloadBundlingJobAction>(OffloadAL);
3320 AL.back() = HostAction;
3321 } else
3322 AL.append(OffloadAL.begin(), OffloadAL.end());
3323
3324 // Propagate to the current host action (if any) the offload information
3325 // associated with the current input.
3326 if (HostAction)
3327 HostAction->propagateHostOffloadInfo(InputArgToOffloadKindMap[InputArg],
3328 /*BoundArch=*/nullptr);
3329 return false;
3330 }
3331
makeHostLinkAction()3332 Action* makeHostLinkAction() {
3333 // Build a list of device linking actions.
3334 ActionList DeviceAL;
3335 for (DeviceActionBuilder *SB : SpecializedBuilders) {
3336 if (!SB->isValid())
3337 continue;
3338 SB->appendLinkDeviceActions(DeviceAL);
3339 }
3340
3341 if (DeviceAL.empty())
3342 return nullptr;
3343
3344 // Let builders add host linking actions.
3345 Action* HA;
3346 for (DeviceActionBuilder *SB : SpecializedBuilders) {
3347 if (!SB->isValid())
3348 continue;
3349 HA = SB->appendLinkHostActions(DeviceAL);
3350 }
3351 return HA;
3352 }
3353
3354 /// Processes the host linker action. This currently consists of replacing it
3355 /// with an offload action if there are device link objects and propagate to
3356 /// the host action all the offload kinds used in the current compilation. The
3357 /// resulting action is returned.
processHostLinkAction(Action * HostAction)3358 Action *processHostLinkAction(Action *HostAction) {
3359 // Add all the dependences from the device linking actions.
3360 OffloadAction::DeviceDependences DDeps;
3361 for (auto *SB : SpecializedBuilders) {
3362 if (!SB->isValid())
3363 continue;
3364
3365 SB->appendLinkDependences(DDeps);
3366 }
3367
3368 // Calculate all the offload kinds used in the current compilation.
3369 unsigned ActiveOffloadKinds = 0u;
3370 for (auto &I : InputArgToOffloadKindMap)
3371 ActiveOffloadKinds |= I.second;
3372
3373 // If we don't have device dependencies, we don't have to create an offload
3374 // action.
3375 if (DDeps.getActions().empty()) {
3376 // Propagate all the active kinds to host action. Given that it is a link
3377 // action it is assumed to depend on all actions generated so far.
3378 HostAction->propagateHostOffloadInfo(ActiveOffloadKinds,
3379 /*BoundArch=*/nullptr);
3380 return HostAction;
3381 }
3382
3383 // Create the offload action with all dependences. When an offload action
3384 // is created the kinds are propagated to the host action, so we don't have
3385 // to do that explicitly here.
3386 OffloadAction::HostDependence HDep(
3387 *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
3388 /*BoundArch*/ nullptr, ActiveOffloadKinds);
3389 return C.MakeAction<OffloadAction>(HDep, DDeps);
3390 }
3391 };
3392 } // anonymous namespace.
3393
handleArguments(Compilation & C,DerivedArgList & Args,const InputList & Inputs,ActionList & Actions) const3394 void Driver::handleArguments(Compilation &C, DerivedArgList &Args,
3395 const InputList &Inputs,
3396 ActionList &Actions) const {
3397
3398 // Ignore /Yc/Yu if both /Yc and /Yu passed but with different filenames.
3399 Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
3400 Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
3401 if (YcArg && YuArg && strcmp(YcArg->getValue(), YuArg->getValue()) != 0) {
3402 Diag(clang::diag::warn_drv_ycyu_different_arg_clang_cl);
3403 Args.eraseArg(options::OPT__SLASH_Yc);
3404 Args.eraseArg(options::OPT__SLASH_Yu);
3405 YcArg = YuArg = nullptr;
3406 }
3407 if (YcArg && Inputs.size() > 1) {
3408 Diag(clang::diag::warn_drv_yc_multiple_inputs_clang_cl);
3409 Args.eraseArg(options::OPT__SLASH_Yc);
3410 YcArg = nullptr;
3411 }
3412
3413 Arg *FinalPhaseArg;
3414 phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
3415
3416 if (FinalPhase == phases::Link) {
3417 if (Args.hasArg(options::OPT_emit_llvm))
3418 Diag(clang::diag::err_drv_emit_llvm_link);
3419 if (IsCLMode() && LTOMode != LTOK_None &&
3420 !Args.getLastArgValue(options::OPT_fuse_ld_EQ).equals_lower("lld"))
3421 Diag(clang::diag::err_drv_lto_without_lld);
3422 }
3423
3424 if (FinalPhase == phases::Preprocess || Args.hasArg(options::OPT__SLASH_Y_)) {
3425 // If only preprocessing or /Y- is used, all pch handling is disabled.
3426 // Rather than check for it everywhere, just remove clang-cl pch-related
3427 // flags here.
3428 Args.eraseArg(options::OPT__SLASH_Fp);
3429 Args.eraseArg(options::OPT__SLASH_Yc);
3430 Args.eraseArg(options::OPT__SLASH_Yu);
3431 YcArg = YuArg = nullptr;
3432 }
3433
3434 unsigned LastPLSize = 0;
3435 for (auto &I : Inputs) {
3436 types::ID InputType = I.first;
3437 const Arg *InputArg = I.second;
3438
3439 auto PL = types::getCompilationPhases(InputType);
3440 LastPLSize = PL.size();
3441
3442 // If the first step comes after the final phase we are doing as part of
3443 // this compilation, warn the user about it.
3444 phases::ID InitialPhase = PL[0];
3445 if (InitialPhase > FinalPhase) {
3446 if (InputArg->isClaimed())
3447 continue;
3448
3449 // Claim here to avoid the more general unused warning.
3450 InputArg->claim();
3451
3452 // Suppress all unused style warnings with -Qunused-arguments
3453 if (Args.hasArg(options::OPT_Qunused_arguments))
3454 continue;
3455
3456 // Special case when final phase determined by binary name, rather than
3457 // by a command-line argument with a corresponding Arg.
3458 if (CCCIsCPP())
3459 Diag(clang::diag::warn_drv_input_file_unused_by_cpp)
3460 << InputArg->getAsString(Args) << getPhaseName(InitialPhase);
3461 // Special case '-E' warning on a previously preprocessed file to make
3462 // more sense.
3463 else if (InitialPhase == phases::Compile &&
3464 (Args.getLastArg(options::OPT__SLASH_EP,
3465 options::OPT__SLASH_P) ||
3466 Args.getLastArg(options::OPT_E) ||
3467 Args.getLastArg(options::OPT_M, options::OPT_MM)) &&
3468 getPreprocessedType(InputType) == types::TY_INVALID)
3469 Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
3470 << InputArg->getAsString(Args) << !!FinalPhaseArg
3471 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
3472 else
3473 Diag(clang::diag::warn_drv_input_file_unused)
3474 << InputArg->getAsString(Args) << getPhaseName(InitialPhase)
3475 << !!FinalPhaseArg
3476 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
3477 continue;
3478 }
3479
3480 if (YcArg) {
3481 // Add a separate precompile phase for the compile phase.
3482 if (FinalPhase >= phases::Compile) {
3483 const types::ID HeaderType = lookupHeaderTypeForSourceType(InputType);
3484 // Build the pipeline for the pch file.
3485 Action *ClangClPch = C.MakeAction<InputAction>(*InputArg, HeaderType);
3486 for (phases::ID Phase : types::getCompilationPhases(HeaderType))
3487 ClangClPch = ConstructPhaseAction(C, Args, Phase, ClangClPch);
3488 assert(ClangClPch);
3489 Actions.push_back(ClangClPch);
3490 // The driver currently exits after the first failed command. This
3491 // relies on that behavior, to make sure if the pch generation fails,
3492 // the main compilation won't run.
3493 // FIXME: If the main compilation fails, the PCH generation should
3494 // probably not be considered successful either.
3495 }
3496 }
3497 }
3498
3499 // If we are linking, claim any options which are obviously only used for
3500 // compilation.
3501 // FIXME: Understand why the last Phase List length is used here.
3502 if (FinalPhase == phases::Link && LastPLSize == 1) {
3503 Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
3504 Args.ClaimAllArgs(options::OPT_cl_compile_Group);
3505 }
3506 }
3507
BuildActions(Compilation & C,DerivedArgList & Args,const InputList & Inputs,ActionList & Actions) const3508 void Driver::BuildActions(Compilation &C, DerivedArgList &Args,
3509 const InputList &Inputs, ActionList &Actions) const {
3510 llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
3511
3512 if (!SuppressMissingInputWarning && Inputs.empty()) {
3513 Diag(clang::diag::err_drv_no_input_files);
3514 return;
3515 }
3516
3517 // Reject -Z* at the top level, these options should never have been exposed
3518 // by gcc.
3519 if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
3520 Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
3521
3522 // Diagnose misuse of /Fo.
3523 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) {
3524 StringRef V = A->getValue();
3525 if (Inputs.size() > 1 && !V.empty() &&
3526 !llvm::sys::path::is_separator(V.back())) {
3527 // Check whether /Fo tries to name an output file for multiple inputs.
3528 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
3529 << A->getSpelling() << V;
3530 Args.eraseArg(options::OPT__SLASH_Fo);
3531 }
3532 }
3533
3534 // Diagnose misuse of /Fa.
3535 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fa)) {
3536 StringRef V = A->getValue();
3537 if (Inputs.size() > 1 && !V.empty() &&
3538 !llvm::sys::path::is_separator(V.back())) {
3539 // Check whether /Fa tries to name an asm file for multiple inputs.
3540 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
3541 << A->getSpelling() << V;
3542 Args.eraseArg(options::OPT__SLASH_Fa);
3543 }
3544 }
3545
3546 // Diagnose misuse of /o.
3547 if (Arg *A = Args.getLastArg(options::OPT__SLASH_o)) {
3548 if (A->getValue()[0] == '\0') {
3549 // It has to have a value.
3550 Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1;
3551 Args.eraseArg(options::OPT__SLASH_o);
3552 }
3553 }
3554
3555 handleArguments(C, Args, Inputs, Actions);
3556
3557 // Builder to be used to build offloading actions.
3558 OffloadingActionBuilder OffloadBuilder(C, Args, Inputs);
3559
3560 // Construct the actions to perform.
3561 HeaderModulePrecompileJobAction *HeaderModuleAction = nullptr;
3562 ActionList LinkerInputs;
3563 ActionList MergerInputs;
3564
3565 for (auto &I : Inputs) {
3566 types::ID InputType = I.first;
3567 const Arg *InputArg = I.second;
3568
3569 auto PL = types::getCompilationPhases(*this, Args, InputType);
3570 if (PL.empty())
3571 continue;
3572
3573 auto FullPL = types::getCompilationPhases(InputType);
3574
3575 // Build the pipeline for this file.
3576 Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
3577
3578 // Use the current host action in any of the offloading actions, if
3579 // required.
3580 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
3581 break;
3582
3583 for (phases::ID Phase : PL) {
3584
3585 // Add any offload action the host action depends on.
3586 Current = OffloadBuilder.addDeviceDependencesToHostAction(
3587 Current, InputArg, Phase, PL.back(), FullPL);
3588 if (!Current)
3589 break;
3590
3591 // Queue linker inputs.
3592 if (Phase == phases::Link) {
3593 assert(Phase == PL.back() && "linking must be final compilation step.");
3594 LinkerInputs.push_back(Current);
3595 Current = nullptr;
3596 break;
3597 }
3598
3599 // TODO: Consider removing this because the merged may not end up being
3600 // the final Phase in the pipeline. Perhaps the merged could just merge
3601 // and then pass an artifact of some sort to the Link Phase.
3602 // Queue merger inputs.
3603 if (Phase == phases::IfsMerge) {
3604 assert(Phase == PL.back() && "merging must be final compilation step.");
3605 MergerInputs.push_back(Current);
3606 Current = nullptr;
3607 break;
3608 }
3609
3610 // Each precompiled header file after a module file action is a module
3611 // header of that same module file, rather than being compiled to a
3612 // separate PCH.
3613 if (Phase == phases::Precompile && HeaderModuleAction &&
3614 getPrecompiledType(InputType) == types::TY_PCH) {
3615 HeaderModuleAction->addModuleHeaderInput(Current);
3616 Current = nullptr;
3617 break;
3618 }
3619
3620 // FIXME: Should we include any prior module file outputs as inputs of
3621 // later actions in the same command line?
3622
3623 // Otherwise construct the appropriate action.
3624 Action *NewCurrent = ConstructPhaseAction(C, Args, Phase, Current);
3625
3626 // We didn't create a new action, so we will just move to the next phase.
3627 if (NewCurrent == Current)
3628 continue;
3629
3630 if (auto *HMA = dyn_cast<HeaderModulePrecompileJobAction>(NewCurrent))
3631 HeaderModuleAction = HMA;
3632
3633 Current = NewCurrent;
3634
3635 // Use the current host action in any of the offloading actions, if
3636 // required.
3637 if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
3638 break;
3639
3640 if (Current->getType() == types::TY_Nothing)
3641 break;
3642 }
3643
3644 // If we ended with something, add to the output list.
3645 if (Current)
3646 Actions.push_back(Current);
3647
3648 // Add any top level actions generated for offloading.
3649 OffloadBuilder.appendTopLevelActions(Actions, Current, InputArg);
3650 }
3651
3652 // Add a link action if necessary.
3653 if (!LinkerInputs.empty()) {
3654 if (Action *Wrapper = OffloadBuilder.makeHostLinkAction())
3655 LinkerInputs.push_back(Wrapper);
3656 Action *LA;
3657 // Check if this Linker Job should emit a static library.
3658 if (ShouldEmitStaticLibrary(Args)) {
3659 LA = C.MakeAction<StaticLibJobAction>(LinkerInputs, types::TY_Image);
3660 } else {
3661 LA = C.MakeAction<LinkJobAction>(LinkerInputs, types::TY_Image);
3662 }
3663 LA = OffloadBuilder.processHostLinkAction(LA);
3664 Actions.push_back(LA);
3665 }
3666
3667 // Add an interface stubs merge action if necessary.
3668 if (!MergerInputs.empty())
3669 Actions.push_back(
3670 C.MakeAction<IfsMergeJobAction>(MergerInputs, types::TY_Image));
3671
3672 if (Args.hasArg(options::OPT_emit_interface_stubs)) {
3673 auto PhaseList = types::getCompilationPhases(
3674 types::TY_IFS_CPP,
3675 Args.hasArg(options::OPT_c) ? phases::Compile : phases::LastPhase);
3676
3677 ActionList MergerInputs;
3678
3679 for (auto &I : Inputs) {
3680 types::ID InputType = I.first;
3681 const Arg *InputArg = I.second;
3682
3683 // Currently clang and the llvm assembler do not support generating symbol
3684 // stubs from assembly, so we skip the input on asm files. For ifs files
3685 // we rely on the normal pipeline setup in the pipeline setup code above.
3686 if (InputType == types::TY_IFS || InputType == types::TY_PP_Asm ||
3687 InputType == types::TY_Asm)
3688 continue;
3689
3690 Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
3691
3692 for (auto Phase : PhaseList) {
3693 switch (Phase) {
3694 default:
3695 llvm_unreachable(
3696 "IFS Pipeline can only consist of Compile followed by IfsMerge.");
3697 case phases::Compile: {
3698 // Only IfsMerge (llvm-ifs) can handle .o files by looking for ifs
3699 // files where the .o file is located. The compile action can not
3700 // handle this.
3701 if (InputType == types::TY_Object)
3702 break;
3703
3704 Current = C.MakeAction<CompileJobAction>(Current, types::TY_IFS_CPP);
3705 break;
3706 }
3707 case phases::IfsMerge: {
3708 assert(Phase == PhaseList.back() &&
3709 "merging must be final compilation step.");
3710 MergerInputs.push_back(Current);
3711 Current = nullptr;
3712 break;
3713 }
3714 }
3715 }
3716
3717 // If we ended with something, add to the output list.
3718 if (Current)
3719 Actions.push_back(Current);
3720 }
3721
3722 // Add an interface stubs merge action if necessary.
3723 if (!MergerInputs.empty())
3724 Actions.push_back(
3725 C.MakeAction<IfsMergeJobAction>(MergerInputs, types::TY_Image));
3726 }
3727
3728 // If --print-supported-cpus, -mcpu=? or -mtune=? is specified, build a custom
3729 // Compile phase that prints out supported cpu models and quits.
3730 if (Arg *A = Args.getLastArg(options::OPT_print_supported_cpus)) {
3731 // Use the -mcpu=? flag as the dummy input to cc1.
3732 Actions.clear();
3733 Action *InputAc = C.MakeAction<InputAction>(*A, types::TY_C);
3734 Actions.push_back(
3735 C.MakeAction<PrecompileJobAction>(InputAc, types::TY_Nothing));
3736 for (auto &I : Inputs)
3737 I.second->claim();
3738 }
3739
3740 // Claim ignored clang-cl options.
3741 Args.ClaimAllArgs(options::OPT_cl_ignored_Group);
3742
3743 // Claim --cuda-host-only and --cuda-compile-host-device, which may be passed
3744 // to non-CUDA compilations and should not trigger warnings there.
3745 Args.ClaimAllArgs(options::OPT_cuda_host_only);
3746 Args.ClaimAllArgs(options::OPT_cuda_compile_host_device);
3747 }
3748
ConstructPhaseAction(Compilation & C,const ArgList & Args,phases::ID Phase,Action * Input,Action::OffloadKind TargetDeviceOffloadKind) const3749 Action *Driver::ConstructPhaseAction(
3750 Compilation &C, const ArgList &Args, phases::ID Phase, Action *Input,
3751 Action::OffloadKind TargetDeviceOffloadKind) const {
3752 llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
3753
3754 // Some types skip the assembler phase (e.g., llvm-bc), but we can't
3755 // encode this in the steps because the intermediate type depends on
3756 // arguments. Just special case here.
3757 if (Phase == phases::Assemble && Input->getType() != types::TY_PP_Asm)
3758 return Input;
3759
3760 // Build the appropriate action.
3761 switch (Phase) {
3762 case phases::Link:
3763 llvm_unreachable("link action invalid here.");
3764 case phases::IfsMerge:
3765 llvm_unreachable("ifsmerge action invalid here.");
3766 case phases::Preprocess: {
3767 types::ID OutputTy;
3768 // -M and -MM specify the dependency file name by altering the output type,
3769 // -if -MD and -MMD are not specified.
3770 if (Args.hasArg(options::OPT_M, options::OPT_MM) &&
3771 !Args.hasArg(options::OPT_MD, options::OPT_MMD)) {
3772 OutputTy = types::TY_Dependencies;
3773 } else {
3774 OutputTy = Input->getType();
3775 if (!Args.hasFlag(options::OPT_frewrite_includes,
3776 options::OPT_fno_rewrite_includes, false) &&
3777 !Args.hasFlag(options::OPT_frewrite_imports,
3778 options::OPT_fno_rewrite_imports, false) &&
3779 !CCGenDiagnostics)
3780 OutputTy = types::getPreprocessedType(OutputTy);
3781 assert(OutputTy != types::TY_INVALID &&
3782 "Cannot preprocess this input type!");
3783 }
3784 return C.MakeAction<PreprocessJobAction>(Input, OutputTy);
3785 }
3786 case phases::Precompile: {
3787 types::ID OutputTy = getPrecompiledType(Input->getType());
3788 assert(OutputTy != types::TY_INVALID &&
3789 "Cannot precompile this input type!");
3790
3791 // If we're given a module name, precompile header file inputs as a
3792 // module, not as a precompiled header.
3793 const char *ModName = nullptr;
3794 if (OutputTy == types::TY_PCH) {
3795 if (Arg *A = Args.getLastArg(options::OPT_fmodule_name_EQ))
3796 ModName = A->getValue();
3797 if (ModName)
3798 OutputTy = types::TY_ModuleFile;
3799 }
3800
3801 if (Args.hasArg(options::OPT_fsyntax_only)) {
3802 // Syntax checks should not emit a PCH file
3803 OutputTy = types::TY_Nothing;
3804 }
3805
3806 if (ModName)
3807 return C.MakeAction<HeaderModulePrecompileJobAction>(Input, OutputTy,
3808 ModName);
3809 return C.MakeAction<PrecompileJobAction>(Input, OutputTy);
3810 }
3811 case phases::Compile: {
3812 if (Args.hasArg(options::OPT_fsyntax_only))
3813 return C.MakeAction<CompileJobAction>(Input, types::TY_Nothing);
3814 if (Args.hasArg(options::OPT_rewrite_objc))
3815 return C.MakeAction<CompileJobAction>(Input, types::TY_RewrittenObjC);
3816 if (Args.hasArg(options::OPT_rewrite_legacy_objc))
3817 return C.MakeAction<CompileJobAction>(Input,
3818 types::TY_RewrittenLegacyObjC);
3819 if (Args.hasArg(options::OPT__analyze))
3820 return C.MakeAction<AnalyzeJobAction>(Input, types::TY_Plist);
3821 if (Args.hasArg(options::OPT__migrate))
3822 return C.MakeAction<MigrateJobAction>(Input, types::TY_Remap);
3823 if (Args.hasArg(options::OPT_emit_ast))
3824 return C.MakeAction<CompileJobAction>(Input, types::TY_AST);
3825 if (Args.hasArg(options::OPT_module_file_info))
3826 return C.MakeAction<CompileJobAction>(Input, types::TY_ModuleFile);
3827 if (Args.hasArg(options::OPT_verify_pch))
3828 return C.MakeAction<VerifyPCHJobAction>(Input, types::TY_Nothing);
3829 return C.MakeAction<CompileJobAction>(Input, types::TY_LLVM_BC);
3830 }
3831 case phases::Backend: {
3832 if (isUsingLTO() && TargetDeviceOffloadKind == Action::OFK_None) {
3833 types::ID Output =
3834 Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
3835 return C.MakeAction<BackendJobAction>(Input, Output);
3836 }
3837 if (Args.hasArg(options::OPT_emit_llvm) ||
3838 (TargetDeviceOffloadKind == Action::OFK_HIP &&
3839 Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc,
3840 false))) {
3841 types::ID Output =
3842 Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC;
3843 return C.MakeAction<BackendJobAction>(Input, Output);
3844 }
3845 return C.MakeAction<BackendJobAction>(Input, types::TY_PP_Asm);
3846 }
3847 case phases::Assemble:
3848 return C.MakeAction<AssembleJobAction>(std::move(Input), types::TY_Object);
3849 }
3850
3851 llvm_unreachable("invalid phase in ConstructPhaseAction");
3852 }
3853
BuildJobs(Compilation & C) const3854 void Driver::BuildJobs(Compilation &C) const {
3855 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
3856
3857 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
3858
3859 // It is an error to provide a -o option if we are making multiple output
3860 // files. There are exceptions:
3861 //
3862 // IfsMergeJob: when generating interface stubs enabled we want to be able to
3863 // generate the stub file at the same time that we generate the real
3864 // library/a.out. So when a .o, .so, etc are the output, with clang interface
3865 // stubs there will also be a .ifs and .ifso at the same location.
3866 //
3867 // CompileJob of type TY_IFS_CPP: when generating interface stubs is enabled
3868 // and -c is passed, we still want to be able to generate a .ifs file while
3869 // we are also generating .o files. So we allow more than one output file in
3870 // this case as well.
3871 //
3872 if (FinalOutput) {
3873 unsigned NumOutputs = 0;
3874 unsigned NumIfsOutputs = 0;
3875 for (const Action *A : C.getActions())
3876 if (A->getType() != types::TY_Nothing &&
3877 !(A->getKind() == Action::IfsMergeJobClass ||
3878 (A->getType() == clang::driver::types::TY_IFS_CPP &&
3879 A->getKind() == clang::driver::Action::CompileJobClass &&
3880 0 == NumIfsOutputs++) ||
3881 (A->getKind() == Action::BindArchClass && A->getInputs().size() &&
3882 A->getInputs().front()->getKind() == Action::IfsMergeJobClass)))
3883 ++NumOutputs;
3884
3885 if (NumOutputs > 1) {
3886 Diag(clang::diag::err_drv_output_argument_with_multiple_files);
3887 FinalOutput = nullptr;
3888 }
3889 }
3890
3891 const llvm::Triple &RawTriple = C.getDefaultToolChain().getTriple();
3892 if (RawTriple.isOSAIX())
3893 if (Arg *A = C.getArgs().getLastArg(options::OPT_G))
3894 Diag(diag::err_drv_unsupported_opt_for_target)
3895 << A->getSpelling() << RawTriple.str();
3896
3897 // Collect the list of architectures.
3898 llvm::StringSet<> ArchNames;
3899 if (RawTriple.isOSBinFormatMachO())
3900 for (const Arg *A : C.getArgs())
3901 if (A->getOption().matches(options::OPT_arch))
3902 ArchNames.insert(A->getValue());
3903
3904 // Set of (Action, canonical ToolChain triple) pairs we've built jobs for.
3905 std::map<std::pair<const Action *, std::string>, InputInfo> CachedResults;
3906 for (Action *A : C.getActions()) {
3907 // If we are linking an image for multiple archs then the linker wants
3908 // -arch_multiple and -final_output <final image name>. Unfortunately, this
3909 // doesn't fit in cleanly because we have to pass this information down.
3910 //
3911 // FIXME: This is a hack; find a cleaner way to integrate this into the
3912 // process.
3913 const char *LinkingOutput = nullptr;
3914 if (isa<LipoJobAction>(A)) {
3915 if (FinalOutput)
3916 LinkingOutput = FinalOutput->getValue();
3917 else
3918 LinkingOutput = getDefaultImageName();
3919 }
3920
3921 BuildJobsForAction(C, A, &C.getDefaultToolChain(),
3922 /*BoundArch*/ StringRef(),
3923 /*AtTopLevel*/ true,
3924 /*MultipleArchs*/ ArchNames.size() > 1,
3925 /*LinkingOutput*/ LinkingOutput, CachedResults,
3926 /*TargetDeviceOffloadKind*/ Action::OFK_None);
3927 }
3928
3929 StringRef StatReportFile;
3930 bool PrintProcessStat = false;
3931 if (const Arg *A = C.getArgs().getLastArg(options::OPT_fproc_stat_report_EQ))
3932 StatReportFile = A->getValue();
3933 if (C.getArgs().hasArg(options::OPT_fproc_stat_report))
3934 PrintProcessStat = true;
3935
3936 // If we have more than one job, then disable integrated-cc1 for now. Do this
3937 // also when we need to report process execution statistics.
3938 if (C.getJobs().size() > 1 || !StatReportFile.empty() || PrintProcessStat)
3939 for (auto &J : C.getJobs())
3940 J.InProcess = false;
3941
3942 if (!StatReportFile.empty() || PrintProcessStat) {
3943 C.setPostCallback([=](const Command &Cmd, int Res) {
3944 Optional<llvm::sys::ProcessStatistics> ProcStat =
3945 Cmd.getProcessStatistics();
3946 if (!ProcStat)
3947 return;
3948 if (PrintProcessStat) {
3949 using namespace llvm;
3950 // Human readable output.
3951 outs() << sys::path::filename(Cmd.getExecutable()) << ": "
3952 << "output=";
3953 if (Cmd.getOutputFilenames().empty())
3954 outs() << "\"\"";
3955 else
3956 outs() << Cmd.getOutputFilenames().front();
3957 outs() << ", total="
3958 << format("%.3f", ProcStat->TotalTime.count() / 1000.) << " ms"
3959 << ", user="
3960 << format("%.3f", ProcStat->UserTime.count() / 1000.) << " ms"
3961 << ", mem=" << ProcStat->PeakMemory << " Kb\n";
3962 }
3963 if (!StatReportFile.empty()) {
3964 // CSV format.
3965 std::string Buffer;
3966 llvm::raw_string_ostream Out(Buffer);
3967 llvm::sys::printArg(Out, llvm::sys::path::filename(Cmd.getExecutable()),
3968 /*Quote*/ true);
3969 Out << ',';
3970 if (Cmd.getOutputFilenames().empty())
3971 Out << "\"\"";
3972 else
3973 llvm::sys::printArg(Out, Cmd.getOutputFilenames().front(), true);
3974 Out << ',' << ProcStat->TotalTime.count() << ','
3975 << ProcStat->UserTime.count() << ',' << ProcStat->PeakMemory
3976 << '\n';
3977 Out.flush();
3978 std::error_code EC;
3979 llvm::raw_fd_ostream OS(StatReportFile, EC, llvm::sys::fs::OF_Append);
3980 if (EC)
3981 return;
3982 auto L = OS.lock();
3983 if (!L) {
3984 llvm::errs() << "ERROR: Cannot lock file " << StatReportFile << ": "
3985 << toString(L.takeError()) << "\n";
3986 return;
3987 }
3988 OS << Buffer;
3989 }
3990 });
3991 }
3992
3993 // If the user passed -Qunused-arguments or there were errors, don't warn
3994 // about any unused arguments.
3995 if (Diags.hasErrorOccurred() ||
3996 C.getArgs().hasArg(options::OPT_Qunused_arguments))
3997 return;
3998
3999 // Claim -### here.
4000 (void)C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
4001
4002 // Claim --driver-mode, --rsp-quoting, it was handled earlier.
4003 (void)C.getArgs().hasArg(options::OPT_driver_mode);
4004 (void)C.getArgs().hasArg(options::OPT_rsp_quoting);
4005
4006 for (Arg *A : C.getArgs()) {
4007 // FIXME: It would be nice to be able to send the argument to the
4008 // DiagnosticsEngine, so that extra values, position, and so on could be
4009 // printed.
4010 if (!A->isClaimed()) {
4011 if (A->getOption().hasFlag(options::NoArgumentUnused))
4012 continue;
4013
4014 // Suppress the warning automatically if this is just a flag, and it is an
4015 // instance of an argument we already claimed.
4016 const Option &Opt = A->getOption();
4017 if (Opt.getKind() == Option::FlagClass) {
4018 bool DuplicateClaimed = false;
4019
4020 for (const Arg *AA : C.getArgs().filtered(&Opt)) {
4021 if (AA->isClaimed()) {
4022 DuplicateClaimed = true;
4023 break;
4024 }
4025 }
4026
4027 if (DuplicateClaimed)
4028 continue;
4029 }
4030
4031 // In clang-cl, don't mention unknown arguments here since they have
4032 // already been warned about.
4033 if (!IsCLMode() || !A->getOption().matches(options::OPT_UNKNOWN))
4034 Diag(clang::diag::warn_drv_unused_argument)
4035 << A->getAsString(C.getArgs());
4036 }
4037 }
4038 }
4039
4040 namespace {
4041 /// Utility class to control the collapse of dependent actions and select the
4042 /// tools accordingly.
4043 class ToolSelector final {
4044 /// The tool chain this selector refers to.
4045 const ToolChain &TC;
4046
4047 /// The compilation this selector refers to.
4048 const Compilation &C;
4049
4050 /// The base action this selector refers to.
4051 const JobAction *BaseAction;
4052
4053 /// Set to true if the current toolchain refers to host actions.
4054 bool IsHostSelector;
4055
4056 /// Set to true if save-temps and embed-bitcode functionalities are active.
4057 bool SaveTemps;
4058 bool EmbedBitcode;
4059
4060 /// Get previous dependent action or null if that does not exist. If
4061 /// \a CanBeCollapsed is false, that action must be legal to collapse or
4062 /// null will be returned.
getPrevDependentAction(const ActionList & Inputs,ActionList & SavedOffloadAction,bool CanBeCollapsed=true)4063 const JobAction *getPrevDependentAction(const ActionList &Inputs,
4064 ActionList &SavedOffloadAction,
4065 bool CanBeCollapsed = true) {
4066 // An option can be collapsed only if it has a single input.
4067 if (Inputs.size() != 1)
4068 return nullptr;
4069
4070 Action *CurAction = *Inputs.begin();
4071 if (CanBeCollapsed &&
4072 !CurAction->isCollapsingWithNextDependentActionLegal())
4073 return nullptr;
4074
4075 // If the input action is an offload action. Look through it and save any
4076 // offload action that can be dropped in the event of a collapse.
4077 if (auto *OA = dyn_cast<OffloadAction>(CurAction)) {
4078 // If the dependent action is a device action, we will attempt to collapse
4079 // only with other device actions. Otherwise, we would do the same but
4080 // with host actions only.
4081 if (!IsHostSelector) {
4082 if (OA->hasSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)) {
4083 CurAction =
4084 OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true);
4085 if (CanBeCollapsed &&
4086 !CurAction->isCollapsingWithNextDependentActionLegal())
4087 return nullptr;
4088 SavedOffloadAction.push_back(OA);
4089 return dyn_cast<JobAction>(CurAction);
4090 }
4091 } else if (OA->hasHostDependence()) {
4092 CurAction = OA->getHostDependence();
4093 if (CanBeCollapsed &&
4094 !CurAction->isCollapsingWithNextDependentActionLegal())
4095 return nullptr;
4096 SavedOffloadAction.push_back(OA);
4097 return dyn_cast<JobAction>(CurAction);
4098 }
4099 return nullptr;
4100 }
4101
4102 return dyn_cast<JobAction>(CurAction);
4103 }
4104
4105 /// Return true if an assemble action can be collapsed.
canCollapseAssembleAction() const4106 bool canCollapseAssembleAction() const {
4107 return TC.useIntegratedAs() && !SaveTemps &&
4108 !C.getArgs().hasArg(options::OPT_via_file_asm) &&
4109 !C.getArgs().hasArg(options::OPT__SLASH_FA) &&
4110 !C.getArgs().hasArg(options::OPT__SLASH_Fa);
4111 }
4112
4113 /// Return true if a preprocessor action can be collapsed.
canCollapsePreprocessorAction() const4114 bool canCollapsePreprocessorAction() const {
4115 return !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
4116 !C.getArgs().hasArg(options::OPT_traditional_cpp) && !SaveTemps &&
4117 !C.getArgs().hasArg(options::OPT_rewrite_objc);
4118 }
4119
4120 /// Struct that relates an action with the offload actions that would be
4121 /// collapsed with it.
4122 struct JobActionInfo final {
4123 /// The action this info refers to.
4124 const JobAction *JA = nullptr;
4125 /// The offload actions we need to take care off if this action is
4126 /// collapsed.
4127 ActionList SavedOffloadAction;
4128 };
4129
4130 /// Append collapsed offload actions from the give nnumber of elements in the
4131 /// action info array.
AppendCollapsedOffloadAction(ActionList & CollapsedOffloadAction,ArrayRef<JobActionInfo> & ActionInfo,unsigned ElementNum)4132 static void AppendCollapsedOffloadAction(ActionList &CollapsedOffloadAction,
4133 ArrayRef<JobActionInfo> &ActionInfo,
4134 unsigned ElementNum) {
4135 assert(ElementNum <= ActionInfo.size() && "Invalid number of elements.");
4136 for (unsigned I = 0; I < ElementNum; ++I)
4137 CollapsedOffloadAction.append(ActionInfo[I].SavedOffloadAction.begin(),
4138 ActionInfo[I].SavedOffloadAction.end());
4139 }
4140
4141 /// Functions that attempt to perform the combining. They detect if that is
4142 /// legal, and if so they update the inputs \a Inputs and the offload action
4143 /// that were collapsed in \a CollapsedOffloadAction. A tool that deals with
4144 /// the combined action is returned. If the combining is not legal or if the
4145 /// tool does not exist, null is returned.
4146 /// Currently three kinds of collapsing are supported:
4147 /// - Assemble + Backend + Compile;
4148 /// - Assemble + Backend ;
4149 /// - Backend + Compile.
4150 const Tool *
combineAssembleBackendCompile(ArrayRef<JobActionInfo> ActionInfo,ActionList & Inputs,ActionList & CollapsedOffloadAction)4151 combineAssembleBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
4152 ActionList &Inputs,
4153 ActionList &CollapsedOffloadAction) {
4154 if (ActionInfo.size() < 3 || !canCollapseAssembleAction())
4155 return nullptr;
4156 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
4157 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
4158 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[2].JA);
4159 if (!AJ || !BJ || !CJ)
4160 return nullptr;
4161
4162 // Get compiler tool.
4163 const Tool *T = TC.SelectTool(*CJ);
4164 if (!T)
4165 return nullptr;
4166
4167 // When using -fembed-bitcode, it is required to have the same tool (clang)
4168 // for both CompilerJA and BackendJA. Otherwise, combine two stages.
4169 if (EmbedBitcode) {
4170 const Tool *BT = TC.SelectTool(*BJ);
4171 if (BT == T)
4172 return nullptr;
4173 }
4174
4175 if (!T->hasIntegratedAssembler())
4176 return nullptr;
4177
4178 Inputs = CJ->getInputs();
4179 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
4180 /*NumElements=*/3);
4181 return T;
4182 }
combineAssembleBackend(ArrayRef<JobActionInfo> ActionInfo,ActionList & Inputs,ActionList & CollapsedOffloadAction)4183 const Tool *combineAssembleBackend(ArrayRef<JobActionInfo> ActionInfo,
4184 ActionList &Inputs,
4185 ActionList &CollapsedOffloadAction) {
4186 if (ActionInfo.size() < 2 || !canCollapseAssembleAction())
4187 return nullptr;
4188 auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
4189 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
4190 if (!AJ || !BJ)
4191 return nullptr;
4192
4193 // Get backend tool.
4194 const Tool *T = TC.SelectTool(*BJ);
4195 if (!T)
4196 return nullptr;
4197
4198 if (!T->hasIntegratedAssembler())
4199 return nullptr;
4200
4201 Inputs = BJ->getInputs();
4202 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
4203 /*NumElements=*/2);
4204 return T;
4205 }
combineBackendCompile(ArrayRef<JobActionInfo> ActionInfo,ActionList & Inputs,ActionList & CollapsedOffloadAction)4206 const Tool *combineBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
4207 ActionList &Inputs,
4208 ActionList &CollapsedOffloadAction) {
4209 if (ActionInfo.size() < 2)
4210 return nullptr;
4211 auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[0].JA);
4212 auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[1].JA);
4213 if (!BJ || !CJ)
4214 return nullptr;
4215
4216 // Check if the initial input (to the compile job or its predessor if one
4217 // exists) is LLVM bitcode. In that case, no preprocessor step is required
4218 // and we can still collapse the compile and backend jobs when we have
4219 // -save-temps. I.e. there is no need for a separate compile job just to
4220 // emit unoptimized bitcode.
4221 bool InputIsBitcode = true;
4222 for (size_t i = 1; i < ActionInfo.size(); i++)
4223 if (ActionInfo[i].JA->getType() != types::TY_LLVM_BC &&
4224 ActionInfo[i].JA->getType() != types::TY_LTO_BC) {
4225 InputIsBitcode = false;
4226 break;
4227 }
4228 if (!InputIsBitcode && !canCollapsePreprocessorAction())
4229 return nullptr;
4230
4231 // Get compiler tool.
4232 const Tool *T = TC.SelectTool(*CJ);
4233 if (!T)
4234 return nullptr;
4235
4236 if (T->canEmitIR() && ((SaveTemps && !InputIsBitcode) || EmbedBitcode))
4237 return nullptr;
4238
4239 Inputs = CJ->getInputs();
4240 AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
4241 /*NumElements=*/2);
4242 return T;
4243 }
4244
4245 /// Updates the inputs if the obtained tool supports combining with
4246 /// preprocessor action, and the current input is indeed a preprocessor
4247 /// action. If combining results in the collapse of offloading actions, those
4248 /// are appended to \a CollapsedOffloadAction.
combineWithPreprocessor(const Tool * T,ActionList & Inputs,ActionList & CollapsedOffloadAction)4249 void combineWithPreprocessor(const Tool *T, ActionList &Inputs,
4250 ActionList &CollapsedOffloadAction) {
4251 if (!T || !canCollapsePreprocessorAction() || !T->hasIntegratedCPP())
4252 return;
4253
4254 // Attempt to get a preprocessor action dependence.
4255 ActionList PreprocessJobOffloadActions;
4256 ActionList NewInputs;
4257 for (Action *A : Inputs) {
4258 auto *PJ = getPrevDependentAction({A}, PreprocessJobOffloadActions);
4259 if (!PJ || !isa<PreprocessJobAction>(PJ)) {
4260 NewInputs.push_back(A);
4261 continue;
4262 }
4263
4264 // This is legal to combine. Append any offload action we found and add the
4265 // current input to preprocessor inputs.
4266 CollapsedOffloadAction.append(PreprocessJobOffloadActions.begin(),
4267 PreprocessJobOffloadActions.end());
4268 NewInputs.append(PJ->input_begin(), PJ->input_end());
4269 }
4270 Inputs = NewInputs;
4271 }
4272
4273 public:
ToolSelector(const JobAction * BaseAction,const ToolChain & TC,const Compilation & C,bool SaveTemps,bool EmbedBitcode)4274 ToolSelector(const JobAction *BaseAction, const ToolChain &TC,
4275 const Compilation &C, bool SaveTemps, bool EmbedBitcode)
4276 : TC(TC), C(C), BaseAction(BaseAction), SaveTemps(SaveTemps),
4277 EmbedBitcode(EmbedBitcode) {
4278 assert(BaseAction && "Invalid base action.");
4279 IsHostSelector = BaseAction->getOffloadingDeviceKind() == Action::OFK_None;
4280 }
4281
4282 /// Check if a chain of actions can be combined and return the tool that can
4283 /// handle the combination of actions. The pointer to the current inputs \a
4284 /// Inputs and the list of offload actions \a CollapsedOffloadActions
4285 /// connected to collapsed actions are updated accordingly. The latter enables
4286 /// the caller of the selector to process them afterwards instead of just
4287 /// dropping them. If no suitable tool is found, null will be returned.
getTool(ActionList & Inputs,ActionList & CollapsedOffloadAction)4288 const Tool *getTool(ActionList &Inputs,
4289 ActionList &CollapsedOffloadAction) {
4290 //
4291 // Get the largest chain of actions that we could combine.
4292 //
4293
4294 SmallVector<JobActionInfo, 5> ActionChain(1);
4295 ActionChain.back().JA = BaseAction;
4296 while (ActionChain.back().JA) {
4297 const Action *CurAction = ActionChain.back().JA;
4298
4299 // Grow the chain by one element.
4300 ActionChain.resize(ActionChain.size() + 1);
4301 JobActionInfo &AI = ActionChain.back();
4302
4303 // Attempt to fill it with the
4304 AI.JA =
4305 getPrevDependentAction(CurAction->getInputs(), AI.SavedOffloadAction);
4306 }
4307
4308 // Pop the last action info as it could not be filled.
4309 ActionChain.pop_back();
4310
4311 //
4312 // Attempt to combine actions. If all combining attempts failed, just return
4313 // the tool of the provided action. At the end we attempt to combine the
4314 // action with any preprocessor action it may depend on.
4315 //
4316
4317 const Tool *T = combineAssembleBackendCompile(ActionChain, Inputs,
4318 CollapsedOffloadAction);
4319 if (!T)
4320 T = combineAssembleBackend(ActionChain, Inputs, CollapsedOffloadAction);
4321 if (!T)
4322 T = combineBackendCompile(ActionChain, Inputs, CollapsedOffloadAction);
4323 if (!T) {
4324 Inputs = BaseAction->getInputs();
4325 T = TC.SelectTool(*BaseAction);
4326 }
4327
4328 combineWithPreprocessor(T, Inputs, CollapsedOffloadAction);
4329 return T;
4330 }
4331 };
4332 }
4333
4334 /// Return a string that uniquely identifies the result of a job. The bound arch
4335 /// is not necessarily represented in the toolchain's triple -- for example,
4336 /// armv7 and armv7s both map to the same triple -- so we need both in our map.
4337 /// Also, we need to add the offloading device kind, as the same tool chain can
4338 /// be used for host and device for some programming models, e.g. OpenMP.
GetTriplePlusArchString(const ToolChain * TC,StringRef BoundArch,Action::OffloadKind OffloadKind)4339 static std::string GetTriplePlusArchString(const ToolChain *TC,
4340 StringRef BoundArch,
4341 Action::OffloadKind OffloadKind) {
4342 std::string TriplePlusArch = TC->getTriple().normalize();
4343 if (!BoundArch.empty()) {
4344 TriplePlusArch += "-";
4345 TriplePlusArch += BoundArch;
4346 }
4347 TriplePlusArch += "-";
4348 TriplePlusArch += Action::GetOffloadKindName(OffloadKind);
4349 return TriplePlusArch;
4350 }
4351
BuildJobsForAction(Compilation & C,const Action * A,const ToolChain * TC,StringRef BoundArch,bool AtTopLevel,bool MultipleArchs,const char * LinkingOutput,std::map<std::pair<const Action *,std::string>,InputInfo> & CachedResults,Action::OffloadKind TargetDeviceOffloadKind) const4352 InputInfo Driver::BuildJobsForAction(
4353 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
4354 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
4355 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
4356 Action::OffloadKind TargetDeviceOffloadKind) const {
4357 std::pair<const Action *, std::string> ActionTC = {
4358 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
4359 auto CachedResult = CachedResults.find(ActionTC);
4360 if (CachedResult != CachedResults.end()) {
4361 return CachedResult->second;
4362 }
4363 InputInfo Result = BuildJobsForActionNoCache(
4364 C, A, TC, BoundArch, AtTopLevel, MultipleArchs, LinkingOutput,
4365 CachedResults, TargetDeviceOffloadKind);
4366 CachedResults[ActionTC] = Result;
4367 return Result;
4368 }
4369
BuildJobsForActionNoCache(Compilation & C,const Action * A,const ToolChain * TC,StringRef BoundArch,bool AtTopLevel,bool MultipleArchs,const char * LinkingOutput,std::map<std::pair<const Action *,std::string>,InputInfo> & CachedResults,Action::OffloadKind TargetDeviceOffloadKind) const4370 InputInfo Driver::BuildJobsForActionNoCache(
4371 Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
4372 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
4373 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
4374 Action::OffloadKind TargetDeviceOffloadKind) const {
4375 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
4376
4377 InputInfoList OffloadDependencesInputInfo;
4378 bool BuildingForOffloadDevice = TargetDeviceOffloadKind != Action::OFK_None;
4379 if (const OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
4380 // The 'Darwin' toolchain is initialized only when its arguments are
4381 // computed. Get the default arguments for OFK_None to ensure that
4382 // initialization is performed before processing the offload action.
4383 // FIXME: Remove when darwin's toolchain is initialized during construction.
4384 C.getArgsForToolChain(TC, BoundArch, Action::OFK_None);
4385
4386 // The offload action is expected to be used in four different situations.
4387 //
4388 // a) Set a toolchain/architecture/kind for a host action:
4389 // Host Action 1 -> OffloadAction -> Host Action 2
4390 //
4391 // b) Set a toolchain/architecture/kind for a device action;
4392 // Device Action 1 -> OffloadAction -> Device Action 2
4393 //
4394 // c) Specify a device dependence to a host action;
4395 // Device Action 1 _
4396 // \
4397 // Host Action 1 ---> OffloadAction -> Host Action 2
4398 //
4399 // d) Specify a host dependence to a device action.
4400 // Host Action 1 _
4401 // \
4402 // Device Action 1 ---> OffloadAction -> Device Action 2
4403 //
4404 // For a) and b), we just return the job generated for the dependence. For
4405 // c) and d) we override the current action with the host/device dependence
4406 // if the current toolchain is host/device and set the offload dependences
4407 // info with the jobs obtained from the device/host dependence(s).
4408
4409 // If there is a single device option, just generate the job for it.
4410 if (OA->hasSingleDeviceDependence()) {
4411 InputInfo DevA;
4412 OA->doOnEachDeviceDependence([&](Action *DepA, const ToolChain *DepTC,
4413 const char *DepBoundArch) {
4414 DevA =
4415 BuildJobsForAction(C, DepA, DepTC, DepBoundArch, AtTopLevel,
4416 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput,
4417 CachedResults, DepA->getOffloadingDeviceKind());
4418 });
4419 return DevA;
4420 }
4421
4422 // If 'Action 2' is host, we generate jobs for the device dependences and
4423 // override the current action with the host dependence. Otherwise, we
4424 // generate the host dependences and override the action with the device
4425 // dependence. The dependences can't therefore be a top-level action.
4426 OA->doOnEachDependence(
4427 /*IsHostDependence=*/BuildingForOffloadDevice,
4428 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
4429 OffloadDependencesInputInfo.push_back(BuildJobsForAction(
4430 C, DepA, DepTC, DepBoundArch, /*AtTopLevel=*/false,
4431 /*MultipleArchs*/ !!DepBoundArch, LinkingOutput, CachedResults,
4432 DepA->getOffloadingDeviceKind()));
4433 });
4434
4435 A = BuildingForOffloadDevice
4436 ? OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)
4437 : OA->getHostDependence();
4438 }
4439
4440 if (const InputAction *IA = dyn_cast<InputAction>(A)) {
4441 // FIXME: It would be nice to not claim this here; maybe the old scheme of
4442 // just using Args was better?
4443 const Arg &Input = IA->getInputArg();
4444 Input.claim();
4445 if (Input.getOption().matches(options::OPT_INPUT)) {
4446 const char *Name = Input.getValue();
4447 return InputInfo(A, Name, /* _BaseInput = */ Name);
4448 }
4449 return InputInfo(A, &Input, /* _BaseInput = */ "");
4450 }
4451
4452 if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
4453 const ToolChain *TC;
4454 StringRef ArchName = BAA->getArchName();
4455
4456 if (!ArchName.empty())
4457 TC = &getToolChain(C.getArgs(),
4458 computeTargetTriple(*this, TargetTriple,
4459 C.getArgs(), ArchName));
4460 else
4461 TC = &C.getDefaultToolChain();
4462
4463 return BuildJobsForAction(C, *BAA->input_begin(), TC, ArchName, AtTopLevel,
4464 MultipleArchs, LinkingOutput, CachedResults,
4465 TargetDeviceOffloadKind);
4466 }
4467
4468
4469 ActionList Inputs = A->getInputs();
4470
4471 const JobAction *JA = cast<JobAction>(A);
4472 ActionList CollapsedOffloadActions;
4473
4474 ToolSelector TS(JA, *TC, C, isSaveTempsEnabled(),
4475 embedBitcodeInObject() && !isUsingLTO());
4476 const Tool *T = TS.getTool(Inputs, CollapsedOffloadActions);
4477
4478 if (!T)
4479 return InputInfo();
4480
4481 // If we've collapsed action list that contained OffloadAction we
4482 // need to build jobs for host/device-side inputs it may have held.
4483 for (const auto *OA : CollapsedOffloadActions)
4484 cast<OffloadAction>(OA)->doOnEachDependence(
4485 /*IsHostDependence=*/BuildingForOffloadDevice,
4486 [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
4487 OffloadDependencesInputInfo.push_back(BuildJobsForAction(
4488 C, DepA, DepTC, DepBoundArch, /* AtTopLevel */ false,
4489 /*MultipleArchs=*/!!DepBoundArch, LinkingOutput, CachedResults,
4490 DepA->getOffloadingDeviceKind()));
4491 });
4492
4493 // Only use pipes when there is exactly one input.
4494 InputInfoList InputInfos;
4495 for (const Action *Input : Inputs) {
4496 // Treat dsymutil and verify sub-jobs as being at the top-level too, they
4497 // shouldn't get temporary output names.
4498 // FIXME: Clean this up.
4499 bool SubJobAtTopLevel =
4500 AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A));
4501 InputInfos.push_back(BuildJobsForAction(
4502 C, Input, TC, BoundArch, SubJobAtTopLevel, MultipleArchs, LinkingOutput,
4503 CachedResults, A->getOffloadingDeviceKind()));
4504 }
4505
4506 // Always use the first input as the base input.
4507 const char *BaseInput = InputInfos[0].getBaseInput();
4508
4509 // ... except dsymutil actions, which use their actual input as the base
4510 // input.
4511 if (JA->getType() == types::TY_dSYM)
4512 BaseInput = InputInfos[0].getFilename();
4513
4514 // ... and in header module compilations, which use the module name.
4515 if (auto *ModuleJA = dyn_cast<HeaderModulePrecompileJobAction>(JA))
4516 BaseInput = ModuleJA->getModuleName();
4517
4518 // Append outputs of offload device jobs to the input list
4519 if (!OffloadDependencesInputInfo.empty())
4520 InputInfos.append(OffloadDependencesInputInfo.begin(),
4521 OffloadDependencesInputInfo.end());
4522
4523 // Set the effective triple of the toolchain for the duration of this job.
4524 llvm::Triple EffectiveTriple;
4525 const ToolChain &ToolTC = T->getToolChain();
4526 const ArgList &Args =
4527 C.getArgsForToolChain(TC, BoundArch, A->getOffloadingDeviceKind());
4528 if (InputInfos.size() != 1) {
4529 EffectiveTriple = llvm::Triple(ToolTC.ComputeEffectiveClangTriple(Args));
4530 } else {
4531 // Pass along the input type if it can be unambiguously determined.
4532 EffectiveTriple = llvm::Triple(
4533 ToolTC.ComputeEffectiveClangTriple(Args, InputInfos[0].getType()));
4534 }
4535 RegisterEffectiveTriple TripleRAII(ToolTC, EffectiveTriple);
4536
4537 // Determine the place to write output to, if any.
4538 InputInfo Result;
4539 InputInfoList UnbundlingResults;
4540 if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(JA)) {
4541 // If we have an unbundling job, we need to create results for all the
4542 // outputs. We also update the results cache so that other actions using
4543 // this unbundling action can get the right results.
4544 for (auto &UI : UA->getDependentActionsInfo()) {
4545 assert(UI.DependentOffloadKind != Action::OFK_None &&
4546 "Unbundling with no offloading??");
4547
4548 // Unbundling actions are never at the top level. When we generate the
4549 // offloading prefix, we also do that for the host file because the
4550 // unbundling action does not change the type of the output which can
4551 // cause a overwrite.
4552 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
4553 UI.DependentOffloadKind,
4554 UI.DependentToolChain->getTriple().normalize(),
4555 /*CreatePrefixForHost=*/true);
4556 auto CurI = InputInfo(
4557 UA,
4558 GetNamedOutputPath(C, *UA, BaseInput, UI.DependentBoundArch,
4559 /*AtTopLevel=*/false,
4560 MultipleArchs ||
4561 UI.DependentOffloadKind == Action::OFK_HIP,
4562 OffloadingPrefix),
4563 BaseInput);
4564 // Save the unbundling result.
4565 UnbundlingResults.push_back(CurI);
4566
4567 // Get the unique string identifier for this dependence and cache the
4568 // result.
4569 StringRef Arch;
4570 if (TargetDeviceOffloadKind == Action::OFK_HIP) {
4571 if (UI.DependentOffloadKind == Action::OFK_Host)
4572 Arch = StringRef();
4573 else
4574 Arch = UI.DependentBoundArch;
4575 } else
4576 Arch = BoundArch;
4577
4578 CachedResults[{A, GetTriplePlusArchString(UI.DependentToolChain, Arch,
4579 UI.DependentOffloadKind)}] =
4580 CurI;
4581 }
4582
4583 // Now that we have all the results generated, select the one that should be
4584 // returned for the current depending action.
4585 std::pair<const Action *, std::string> ActionTC = {
4586 A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
4587 assert(CachedResults.find(ActionTC) != CachedResults.end() &&
4588 "Result does not exist??");
4589 Result = CachedResults[ActionTC];
4590 } else if (JA->getType() == types::TY_Nothing)
4591 Result = InputInfo(A, BaseInput);
4592 else {
4593 // We only have to generate a prefix for the host if this is not a top-level
4594 // action.
4595 std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
4596 A->getOffloadingDeviceKind(), TC->getTriple().normalize(),
4597 /*CreatePrefixForHost=*/!!A->getOffloadingHostActiveKinds() &&
4598 !AtTopLevel);
4599 if (isa<OffloadWrapperJobAction>(JA)) {
4600 OffloadingPrefix += "-wrapper";
4601 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
4602 BaseInput = FinalOutput->getValue();
4603 else
4604 BaseInput = getDefaultImageName();
4605 }
4606 Result = InputInfo(A, GetNamedOutputPath(C, *JA, BaseInput, BoundArch,
4607 AtTopLevel, MultipleArchs,
4608 OffloadingPrefix),
4609 BaseInput);
4610 }
4611
4612 if (CCCPrintBindings && !CCGenDiagnostics) {
4613 llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"'
4614 << " - \"" << T->getName() << "\", inputs: [";
4615 for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
4616 llvm::errs() << InputInfos[i].getAsString();
4617 if (i + 1 != e)
4618 llvm::errs() << ", ";
4619 }
4620 if (UnbundlingResults.empty())
4621 llvm::errs() << "], output: " << Result.getAsString() << "\n";
4622 else {
4623 llvm::errs() << "], outputs: [";
4624 for (unsigned i = 0, e = UnbundlingResults.size(); i != e; ++i) {
4625 llvm::errs() << UnbundlingResults[i].getAsString();
4626 if (i + 1 != e)
4627 llvm::errs() << ", ";
4628 }
4629 llvm::errs() << "] \n";
4630 }
4631 } else {
4632 if (UnbundlingResults.empty())
4633 T->ConstructJob(
4634 C, *JA, Result, InputInfos,
4635 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
4636 LinkingOutput);
4637 else
4638 T->ConstructJobMultipleOutputs(
4639 C, *JA, UnbundlingResults, InputInfos,
4640 C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
4641 LinkingOutput);
4642 }
4643 return Result;
4644 }
4645
getDefaultImageName() const4646 const char *Driver::getDefaultImageName() const {
4647 llvm::Triple Target(llvm::Triple::normalize(TargetTriple));
4648 return Target.isOSWindows() ? "a.exe" : "a.out";
4649 }
4650
4651 /// Create output filename based on ArgValue, which could either be a
4652 /// full filename, filename without extension, or a directory. If ArgValue
4653 /// does not provide a filename, then use BaseName, and use the extension
4654 /// suitable for FileType.
MakeCLOutputFilename(const ArgList & Args,StringRef ArgValue,StringRef BaseName,types::ID FileType)4655 static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue,
4656 StringRef BaseName,
4657 types::ID FileType) {
4658 SmallString<128> Filename = ArgValue;
4659
4660 if (ArgValue.empty()) {
4661 // If the argument is empty, output to BaseName in the current dir.
4662 Filename = BaseName;
4663 } else if (llvm::sys::path::is_separator(Filename.back())) {
4664 // If the argument is a directory, output to BaseName in that dir.
4665 llvm::sys::path::append(Filename, BaseName);
4666 }
4667
4668 if (!llvm::sys::path::has_extension(ArgValue)) {
4669 // If the argument didn't provide an extension, then set it.
4670 const char *Extension = types::getTypeTempSuffix(FileType, true);
4671
4672 if (FileType == types::TY_Image &&
4673 Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) {
4674 // The output file is a dll.
4675 Extension = "dll";
4676 }
4677
4678 llvm::sys::path::replace_extension(Filename, Extension);
4679 }
4680
4681 return Args.MakeArgString(Filename.c_str());
4682 }
4683
HasPreprocessOutput(const Action & JA)4684 static bool HasPreprocessOutput(const Action &JA) {
4685 if (isa<PreprocessJobAction>(JA))
4686 return true;
4687 if (isa<OffloadAction>(JA) && isa<PreprocessJobAction>(JA.getInputs()[0]))
4688 return true;
4689 if (isa<OffloadBundlingJobAction>(JA) &&
4690 HasPreprocessOutput(*(JA.getInputs()[0])))
4691 return true;
4692 return false;
4693 }
4694
GetNamedOutputPath(Compilation & C,const JobAction & JA,const char * BaseInput,StringRef OrigBoundArch,bool AtTopLevel,bool MultipleArchs,StringRef OffloadingPrefix) const4695 const char *Driver::GetNamedOutputPath(Compilation &C, const JobAction &JA,
4696 const char *BaseInput,
4697 StringRef OrigBoundArch, bool AtTopLevel,
4698 bool MultipleArchs,
4699 StringRef OffloadingPrefix) const {
4700 std::string BoundArch = OrigBoundArch.str();
4701 #if defined(_WIN32)
4702 // BoundArch may contains ':', which is invalid in file names on Windows,
4703 // therefore replace it with '%'.
4704 std::replace(BoundArch.begin(), BoundArch.end(), ':', '@');
4705 #endif
4706
4707 llvm::PrettyStackTraceString CrashInfo("Computing output path");
4708 // Output to a user requested destination?
4709 if (AtTopLevel && !isa<DsymutilJobAction>(JA) && !isa<VerifyJobAction>(JA)) {
4710 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
4711 return C.addResultFile(FinalOutput->getValue(), &JA);
4712 }
4713
4714 // For /P, preprocess to file named after BaseInput.
4715 if (C.getArgs().hasArg(options::OPT__SLASH_P)) {
4716 assert(AtTopLevel && isa<PreprocessJobAction>(JA));
4717 StringRef BaseName = llvm::sys::path::filename(BaseInput);
4718 StringRef NameArg;
4719 if (Arg *A = C.getArgs().getLastArg(options::OPT__SLASH_Fi))
4720 NameArg = A->getValue();
4721 return C.addResultFile(
4722 MakeCLOutputFilename(C.getArgs(), NameArg, BaseName, types::TY_PP_C),
4723 &JA);
4724 }
4725
4726 // Default to writing to stdout?
4727 if (AtTopLevel && !CCGenDiagnostics && HasPreprocessOutput(JA)) {
4728 return "-";
4729 }
4730
4731 // Is this the assembly listing for /FA?
4732 if (JA.getType() == types::TY_PP_Asm &&
4733 (C.getArgs().hasArg(options::OPT__SLASH_FA) ||
4734 C.getArgs().hasArg(options::OPT__SLASH_Fa))) {
4735 // Use /Fa and the input filename to determine the asm file name.
4736 StringRef BaseName = llvm::sys::path::filename(BaseInput);
4737 StringRef FaValue = C.getArgs().getLastArgValue(options::OPT__SLASH_Fa);
4738 return C.addResultFile(
4739 MakeCLOutputFilename(C.getArgs(), FaValue, BaseName, JA.getType()),
4740 &JA);
4741 }
4742
4743 // Output to a temporary file?
4744 if ((!AtTopLevel && !isSaveTempsEnabled() &&
4745 !C.getArgs().hasArg(options::OPT__SLASH_Fo)) ||
4746 CCGenDiagnostics) {
4747 StringRef Name = llvm::sys::path::filename(BaseInput);
4748 std::pair<StringRef, StringRef> Split = Name.split('.');
4749 SmallString<128> TmpName;
4750 const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
4751 Arg *A = C.getArgs().getLastArg(options::OPT_fcrash_diagnostics_dir);
4752 if (CCGenDiagnostics && A) {
4753 SmallString<128> CrashDirectory(A->getValue());
4754 if (!getVFS().exists(CrashDirectory))
4755 llvm::sys::fs::create_directories(CrashDirectory);
4756 llvm::sys::path::append(CrashDirectory, Split.first);
4757 const char *Middle = Suffix ? "-%%%%%%." : "-%%%%%%";
4758 std::error_code EC = llvm::sys::fs::createUniqueFile(
4759 CrashDirectory + Middle + Suffix, TmpName);
4760 if (EC) {
4761 Diag(clang::diag::err_unable_to_make_temp) << EC.message();
4762 return "";
4763 }
4764 } else {
4765 TmpName = GetTemporaryPath(Split.first, Suffix);
4766 }
4767 return C.addTempFile(C.getArgs().MakeArgString(TmpName));
4768 }
4769
4770 SmallString<128> BasePath(BaseInput);
4771 SmallString<128> ExternalPath("");
4772 StringRef BaseName;
4773
4774 // Dsymutil actions should use the full path.
4775 if (isa<DsymutilJobAction>(JA) && C.getArgs().hasArg(options::OPT_dsym_dir)) {
4776 ExternalPath += C.getArgs().getLastArg(options::OPT_dsym_dir)->getValue();
4777 // We use posix style here because the tests (specifically
4778 // darwin-dsymutil.c) demonstrate that posix style paths are acceptable
4779 // even on Windows and if we don't then the similar test covering this
4780 // fails.
4781 llvm::sys::path::append(ExternalPath, llvm::sys::path::Style::posix,
4782 llvm::sys::path::filename(BasePath));
4783 BaseName = ExternalPath;
4784 } else if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA))
4785 BaseName = BasePath;
4786 else
4787 BaseName = llvm::sys::path::filename(BasePath);
4788
4789 // Determine what the derived output name should be.
4790 const char *NamedOutput;
4791
4792 if ((JA.getType() == types::TY_Object || JA.getType() == types::TY_LTO_BC) &&
4793 C.getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) {
4794 // The /Fo or /o flag decides the object filename.
4795 StringRef Val =
4796 C.getArgs()
4797 .getLastArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)
4798 ->getValue();
4799 NamedOutput =
4800 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object);
4801 } else if (JA.getType() == types::TY_Image &&
4802 C.getArgs().hasArg(options::OPT__SLASH_Fe,
4803 options::OPT__SLASH_o)) {
4804 // The /Fe or /o flag names the linked file.
4805 StringRef Val =
4806 C.getArgs()
4807 .getLastArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o)
4808 ->getValue();
4809 NamedOutput =
4810 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Image);
4811 } else if (JA.getType() == types::TY_Image) {
4812 if (IsCLMode()) {
4813 // clang-cl uses BaseName for the executable name.
4814 NamedOutput =
4815 MakeCLOutputFilename(C.getArgs(), "", BaseName, types::TY_Image);
4816 } else {
4817 SmallString<128> Output(getDefaultImageName());
4818 // HIP image for device compilation with -fno-gpu-rdc is per compilation
4819 // unit.
4820 bool IsHIPNoRDC = JA.getOffloadingDeviceKind() == Action::OFK_HIP &&
4821 !C.getArgs().hasFlag(options::OPT_fgpu_rdc,
4822 options::OPT_fno_gpu_rdc, false);
4823 if (IsHIPNoRDC) {
4824 Output = BaseName;
4825 llvm::sys::path::replace_extension(Output, "");
4826 }
4827 Output += OffloadingPrefix;
4828 if (MultipleArchs && !BoundArch.empty()) {
4829 Output += "-";
4830 Output.append(BoundArch);
4831 }
4832 if (IsHIPNoRDC)
4833 Output += ".out";
4834 NamedOutput = C.getArgs().MakeArgString(Output.c_str());
4835 }
4836 } else if (JA.getType() == types::TY_PCH && IsCLMode()) {
4837 NamedOutput = C.getArgs().MakeArgString(GetClPchPath(C, BaseName));
4838 } else {
4839 const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
4840 assert(Suffix && "All types used for output should have a suffix.");
4841
4842 std::string::size_type End = std::string::npos;
4843 if (!types::appendSuffixForType(JA.getType()))
4844 End = BaseName.rfind('.');
4845 SmallString<128> Suffixed(BaseName.substr(0, End));
4846 Suffixed += OffloadingPrefix;
4847 if (MultipleArchs && !BoundArch.empty()) {
4848 Suffixed += "-";
4849 Suffixed.append(BoundArch);
4850 }
4851 // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for
4852 // the unoptimized bitcode so that it does not get overwritten by the ".bc"
4853 // optimized bitcode output.
4854 auto IsHIPRDCInCompilePhase = [](const JobAction &JA,
4855 const llvm::opt::DerivedArgList &Args) {
4856 // The relocatable compilation in HIP implies -emit-llvm. Similarly, use a
4857 // ".tmp.bc" suffix for the unoptimized bitcode (generated in the compile
4858 // phase.)
4859 return isa<CompileJobAction>(JA) &&
4860 JA.getOffloadingDeviceKind() == Action::OFK_HIP &&
4861 Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc,
4862 false);
4863 };
4864 if (!AtTopLevel && JA.getType() == types::TY_LLVM_BC &&
4865 (C.getArgs().hasArg(options::OPT_emit_llvm) ||
4866 IsHIPRDCInCompilePhase(JA, C.getArgs())))
4867 Suffixed += ".tmp";
4868 Suffixed += '.';
4869 Suffixed += Suffix;
4870 NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
4871 }
4872
4873 // Prepend object file path if -save-temps=obj
4874 if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(options::OPT_o) &&
4875 JA.getType() != types::TY_PCH) {
4876 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
4877 SmallString<128> TempPath(FinalOutput->getValue());
4878 llvm::sys::path::remove_filename(TempPath);
4879 StringRef OutputFileName = llvm::sys::path::filename(NamedOutput);
4880 llvm::sys::path::append(TempPath, OutputFileName);
4881 NamedOutput = C.getArgs().MakeArgString(TempPath.c_str());
4882 }
4883
4884 // If we're saving temps and the temp file conflicts with the input file,
4885 // then avoid overwriting input file.
4886 if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) {
4887 bool SameFile = false;
4888 SmallString<256> Result;
4889 llvm::sys::fs::current_path(Result);
4890 llvm::sys::path::append(Result, BaseName);
4891 llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile);
4892 // Must share the same path to conflict.
4893 if (SameFile) {
4894 StringRef Name = llvm::sys::path::filename(BaseInput);
4895 std::pair<StringRef, StringRef> Split = Name.split('.');
4896 std::string TmpName = GetTemporaryPath(
4897 Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
4898 return C.addTempFile(C.getArgs().MakeArgString(TmpName));
4899 }
4900 }
4901
4902 // As an annoying special case, PCH generation doesn't strip the pathname.
4903 if (JA.getType() == types::TY_PCH && !IsCLMode()) {
4904 llvm::sys::path::remove_filename(BasePath);
4905 if (BasePath.empty())
4906 BasePath = NamedOutput;
4907 else
4908 llvm::sys::path::append(BasePath, NamedOutput);
4909 return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA);
4910 } else {
4911 return C.addResultFile(NamedOutput, &JA);
4912 }
4913 }
4914
GetFilePath(StringRef Name,const ToolChain & TC) const4915 std::string Driver::GetFilePath(StringRef Name, const ToolChain &TC) const {
4916 // Search for Name in a list of paths.
4917 auto SearchPaths = [&](const llvm::SmallVectorImpl<std::string> &P)
4918 -> llvm::Optional<std::string> {
4919 // Respect a limited subset of the '-Bprefix' functionality in GCC by
4920 // attempting to use this prefix when looking for file paths.
4921 for (const auto &Dir : P) {
4922 if (Dir.empty())
4923 continue;
4924 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
4925 llvm::sys::path::append(P, Name);
4926 if (llvm::sys::fs::exists(Twine(P)))
4927 return std::string(P);
4928 }
4929 return None;
4930 };
4931
4932 if (auto P = SearchPaths(PrefixDirs))
4933 return *P;
4934
4935 SmallString<128> R(ResourceDir);
4936 llvm::sys::path::append(R, Name);
4937 if (llvm::sys::fs::exists(Twine(R)))
4938 return std::string(R.str());
4939
4940 SmallString<128> P(TC.getCompilerRTPath());
4941 llvm::sys::path::append(P, Name);
4942 if (llvm::sys::fs::exists(Twine(P)))
4943 return std::string(P.str());
4944
4945 SmallString<128> D(Dir);
4946 llvm::sys::path::append(D, "..", Name);
4947 if (llvm::sys::fs::exists(Twine(D)))
4948 return std::string(D.str());
4949
4950 if (auto P = SearchPaths(TC.getLibraryPaths()))
4951 return *P;
4952
4953 if (auto P = SearchPaths(TC.getFilePaths()))
4954 return *P;
4955
4956 return std::string(Name);
4957 }
4958
generatePrefixedToolNames(StringRef Tool,const ToolChain & TC,SmallVectorImpl<std::string> & Names) const4959 void Driver::generatePrefixedToolNames(
4960 StringRef Tool, const ToolChain &TC,
4961 SmallVectorImpl<std::string> &Names) const {
4962 // FIXME: Needs a better variable than TargetTriple
4963 Names.emplace_back((TargetTriple + "-" + Tool).str());
4964 Names.emplace_back(Tool);
4965
4966 // Allow the discovery of tools prefixed with LLVM's default target triple.
4967 std::string DefaultTargetTriple = llvm::sys::getDefaultTargetTriple();
4968 if (DefaultTargetTriple != TargetTriple)
4969 Names.emplace_back((DefaultTargetTriple + "-" + Tool).str());
4970 }
4971
ScanDirForExecutable(SmallString<128> & Dir,StringRef Name)4972 static bool ScanDirForExecutable(SmallString<128> &Dir, StringRef Name) {
4973 llvm::sys::path::append(Dir, Name);
4974 if (llvm::sys::fs::can_execute(Twine(Dir)))
4975 return true;
4976 llvm::sys::path::remove_filename(Dir);
4977 return false;
4978 }
4979
GetProgramPath(StringRef Name,const ToolChain & TC) const4980 std::string Driver::GetProgramPath(StringRef Name, const ToolChain &TC) const {
4981 SmallVector<std::string, 2> TargetSpecificExecutables;
4982 generatePrefixedToolNames(Name, TC, TargetSpecificExecutables);
4983
4984 // Respect a limited subset of the '-Bprefix' functionality in GCC by
4985 // attempting to use this prefix when looking for program paths.
4986 for (const auto &PrefixDir : PrefixDirs) {
4987 if (llvm::sys::fs::is_directory(PrefixDir)) {
4988 SmallString<128> P(PrefixDir);
4989 if (ScanDirForExecutable(P, Name))
4990 return std::string(P.str());
4991 } else {
4992 SmallString<128> P((PrefixDir + Name).str());
4993 if (llvm::sys::fs::can_execute(Twine(P)))
4994 return std::string(P.str());
4995 }
4996 }
4997
4998 const ToolChain::path_list &List = TC.getProgramPaths();
4999 for (const auto &TargetSpecificExecutable : TargetSpecificExecutables) {
5000 // For each possible name of the tool look for it in
5001 // program paths first, then the path.
5002 // Higher priority names will be first, meaning that
5003 // a higher priority name in the path will be found
5004 // instead of a lower priority name in the program path.
5005 // E.g. <triple>-gcc on the path will be found instead
5006 // of gcc in the program path
5007 for (const auto &Path : List) {
5008 SmallString<128> P(Path);
5009 if (ScanDirForExecutable(P, TargetSpecificExecutable))
5010 return std::string(P.str());
5011 }
5012
5013 // Fall back to the path
5014 if (llvm::ErrorOr<std::string> P =
5015 llvm::sys::findProgramByName(TargetSpecificExecutable))
5016 return *P;
5017 }
5018
5019 return std::string(Name);
5020 }
5021
GetTemporaryPath(StringRef Prefix,StringRef Suffix) const5022 std::string Driver::GetTemporaryPath(StringRef Prefix, StringRef Suffix) const {
5023 SmallString<128> Path;
5024 std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path);
5025 if (EC) {
5026 Diag(clang::diag::err_unable_to_make_temp) << EC.message();
5027 return "";
5028 }
5029
5030 return std::string(Path.str());
5031 }
5032
GetTemporaryDirectory(StringRef Prefix) const5033 std::string Driver::GetTemporaryDirectory(StringRef Prefix) const {
5034 SmallString<128> Path;
5035 std::error_code EC = llvm::sys::fs::createUniqueDirectory(Prefix, Path);
5036 if (EC) {
5037 Diag(clang::diag::err_unable_to_make_temp) << EC.message();
5038 return "";
5039 }
5040
5041 return std::string(Path.str());
5042 }
5043
GetClPchPath(Compilation & C,StringRef BaseName) const5044 std::string Driver::GetClPchPath(Compilation &C, StringRef BaseName) const {
5045 SmallString<128> Output;
5046 if (Arg *FpArg = C.getArgs().getLastArg(options::OPT__SLASH_Fp)) {
5047 // FIXME: If anybody needs it, implement this obscure rule:
5048 // "If you specify a directory without a file name, the default file name
5049 // is VCx0.pch., where x is the major version of Visual C++ in use."
5050 Output = FpArg->getValue();
5051
5052 // "If you do not specify an extension as part of the path name, an
5053 // extension of .pch is assumed. "
5054 if (!llvm::sys::path::has_extension(Output))
5055 Output += ".pch";
5056 } else {
5057 if (Arg *YcArg = C.getArgs().getLastArg(options::OPT__SLASH_Yc))
5058 Output = YcArg->getValue();
5059 if (Output.empty())
5060 Output = BaseName;
5061 llvm::sys::path::replace_extension(Output, ".pch");
5062 }
5063 return std::string(Output.str());
5064 }
5065
getToolChain(const ArgList & Args,const llvm::Triple & Target) const5066 const ToolChain &Driver::getToolChain(const ArgList &Args,
5067 const llvm::Triple &Target) const {
5068
5069 auto &TC = ToolChains[Target.str()];
5070 if (!TC) {
5071 switch (Target.getOS()) {
5072 case llvm::Triple::AIX:
5073 TC = std::make_unique<toolchains::AIX>(*this, Target, Args);
5074 break;
5075 case llvm::Triple::Haiku:
5076 TC = std::make_unique<toolchains::Haiku>(*this, Target, Args);
5077 break;
5078 case llvm::Triple::Ananas:
5079 TC = std::make_unique<toolchains::Ananas>(*this, Target, Args);
5080 break;
5081 case llvm::Triple::CloudABI:
5082 TC = std::make_unique<toolchains::CloudABI>(*this, Target, Args);
5083 break;
5084 case llvm::Triple::Darwin:
5085 case llvm::Triple::MacOSX:
5086 case llvm::Triple::IOS:
5087 case llvm::Triple::TvOS:
5088 case llvm::Triple::WatchOS:
5089 TC = std::make_unique<toolchains::DarwinClang>(*this, Target, Args);
5090 break;
5091 case llvm::Triple::DragonFly:
5092 TC = std::make_unique<toolchains::DragonFly>(*this, Target, Args);
5093 break;
5094 case llvm::Triple::OpenBSD:
5095 TC = std::make_unique<toolchains::OpenBSD>(*this, Target, Args);
5096 break;
5097 case llvm::Triple::NetBSD:
5098 TC = std::make_unique<toolchains::NetBSD>(*this, Target, Args);
5099 break;
5100 case llvm::Triple::FreeBSD:
5101 TC = std::make_unique<toolchains::FreeBSD>(*this, Target, Args);
5102 break;
5103 case llvm::Triple::Minix:
5104 TC = std::make_unique<toolchains::Minix>(*this, Target, Args);
5105 break;
5106 case llvm::Triple::Linux:
5107 case llvm::Triple::ELFIAMCU:
5108 if (Target.getArch() == llvm::Triple::hexagon)
5109 TC = std::make_unique<toolchains::HexagonToolChain>(*this, Target,
5110 Args);
5111 else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) &&
5112 !Target.hasEnvironment())
5113 TC = std::make_unique<toolchains::MipsLLVMToolChain>(*this, Target,
5114 Args);
5115 else if (Target.getArch() == llvm::Triple::ppc ||
5116 Target.getArch() == llvm::Triple::ppc64 ||
5117 Target.getArch() == llvm::Triple::ppc64le)
5118 TC = std::make_unique<toolchains::PPCLinuxToolChain>(*this, Target,
5119 Args);
5120 else if (Target.getArch() == llvm::Triple::ve)
5121 TC = std::make_unique<toolchains::VEToolChain>(*this, Target, Args);
5122
5123 else
5124 TC = std::make_unique<toolchains::Linux>(*this, Target, Args);
5125 break;
5126 case llvm::Triple::NaCl:
5127 TC = std::make_unique<toolchains::NaClToolChain>(*this, Target, Args);
5128 break;
5129 case llvm::Triple::Fuchsia:
5130 TC = std::make_unique<toolchains::Fuchsia>(*this, Target, Args);
5131 break;
5132 case llvm::Triple::Solaris:
5133 TC = std::make_unique<toolchains::Solaris>(*this, Target, Args);
5134 break;
5135 case llvm::Triple::AMDHSA:
5136 TC = std::make_unique<toolchains::ROCMToolChain>(*this, Target, Args);
5137 break;
5138 case llvm::Triple::AMDPAL:
5139 case llvm::Triple::Mesa3D:
5140 TC = std::make_unique<toolchains::AMDGPUToolChain>(*this, Target, Args);
5141 break;
5142 case llvm::Triple::Win32:
5143 switch (Target.getEnvironment()) {
5144 default:
5145 if (Target.isOSBinFormatELF())
5146 TC = std::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
5147 else if (Target.isOSBinFormatMachO())
5148 TC = std::make_unique<toolchains::MachO>(*this, Target, Args);
5149 else
5150 TC = std::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
5151 break;
5152 case llvm::Triple::GNU:
5153 TC = std::make_unique<toolchains::MinGW>(*this, Target, Args);
5154 break;
5155 case llvm::Triple::Itanium:
5156 TC = std::make_unique<toolchains::CrossWindowsToolChain>(*this, Target,
5157 Args);
5158 break;
5159 case llvm::Triple::MSVC:
5160 case llvm::Triple::UnknownEnvironment:
5161 if (Args.getLastArgValue(options::OPT_fuse_ld_EQ)
5162 .startswith_lower("bfd"))
5163 TC = std::make_unique<toolchains::CrossWindowsToolChain>(
5164 *this, Target, Args);
5165 else
5166 TC =
5167 std::make_unique<toolchains::MSVCToolChain>(*this, Target, Args);
5168 break;
5169 }
5170 break;
5171 case llvm::Triple::PS4:
5172 TC = std::make_unique<toolchains::PS4CPU>(*this, Target, Args);
5173 break;
5174 case llvm::Triple::Contiki:
5175 TC = std::make_unique<toolchains::Contiki>(*this, Target, Args);
5176 break;
5177 case llvm::Triple::Hurd:
5178 TC = std::make_unique<toolchains::Hurd>(*this, Target, Args);
5179 break;
5180 case llvm::Triple::ZOS:
5181 TC = std::make_unique<toolchains::ZOS>(*this, Target, Args);
5182 break;
5183 default:
5184 // Of these targets, Hexagon is the only one that might have
5185 // an OS of Linux, in which case it got handled above already.
5186 switch (Target.getArch()) {
5187 case llvm::Triple::tce:
5188 TC = std::make_unique<toolchains::TCEToolChain>(*this, Target, Args);
5189 break;
5190 case llvm::Triple::tcele:
5191 TC = std::make_unique<toolchains::TCELEToolChain>(*this, Target, Args);
5192 break;
5193 case llvm::Triple::hexagon:
5194 TC = std::make_unique<toolchains::HexagonToolChain>(*this, Target,
5195 Args);
5196 break;
5197 case llvm::Triple::lanai:
5198 TC = std::make_unique<toolchains::LanaiToolChain>(*this, Target, Args);
5199 break;
5200 case llvm::Triple::xcore:
5201 TC = std::make_unique<toolchains::XCoreToolChain>(*this, Target, Args);
5202 break;
5203 case llvm::Triple::wasm32:
5204 case llvm::Triple::wasm64:
5205 TC = std::make_unique<toolchains::WebAssembly>(*this, Target, Args);
5206 break;
5207 case llvm::Triple::avr:
5208 TC = std::make_unique<toolchains::AVRToolChain>(*this, Target, Args);
5209 break;
5210 case llvm::Triple::msp430:
5211 TC =
5212 std::make_unique<toolchains::MSP430ToolChain>(*this, Target, Args);
5213 break;
5214 case llvm::Triple::riscv32:
5215 case llvm::Triple::riscv64:
5216 if (toolchains::RISCVToolChain::hasGCCToolchain(*this, Args))
5217 TC =
5218 std::make_unique<toolchains::RISCVToolChain>(*this, Target, Args);
5219 else
5220 TC = std::make_unique<toolchains::BareMetal>(*this, Target, Args);
5221 break;
5222 case llvm::Triple::ve:
5223 TC = std::make_unique<toolchains::VEToolChain>(*this, Target, Args);
5224 break;
5225 default:
5226 if (Target.getVendor() == llvm::Triple::Myriad)
5227 TC = std::make_unique<toolchains::MyriadToolChain>(*this, Target,
5228 Args);
5229 else if (toolchains::BareMetal::handlesTarget(Target))
5230 TC = std::make_unique<toolchains::BareMetal>(*this, Target, Args);
5231 else if (Target.isOSBinFormatELF())
5232 TC = std::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
5233 else if (Target.isOSBinFormatMachO())
5234 TC = std::make_unique<toolchains::MachO>(*this, Target, Args);
5235 else
5236 TC = std::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
5237 }
5238 }
5239 }
5240
5241 // Intentionally omitted from the switch above: llvm::Triple::CUDA. CUDA
5242 // compiles always need two toolchains, the CUDA toolchain and the host
5243 // toolchain. So the only valid way to create a CUDA toolchain is via
5244 // CreateOffloadingDeviceToolChains.
5245
5246 return *TC;
5247 }
5248
ShouldUseClangCompiler(const JobAction & JA) const5249 bool Driver::ShouldUseClangCompiler(const JobAction &JA) const {
5250 // Say "no" if there is not exactly one input of a type clang understands.
5251 if (JA.size() != 1 ||
5252 !types::isAcceptedByClang((*JA.input_begin())->getType()))
5253 return false;
5254
5255 // And say "no" if this is not a kind of action clang understands.
5256 if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) &&
5257 !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
5258 return false;
5259
5260 return true;
5261 }
5262
ShouldUseFlangCompiler(const JobAction & JA) const5263 bool Driver::ShouldUseFlangCompiler(const JobAction &JA) const {
5264 // Say "no" if there is not exactly one input of a type flang understands.
5265 if (JA.size() != 1 ||
5266 !types::isFortran((*JA.input_begin())->getType()))
5267 return false;
5268
5269 // And say "no" if this is not a kind of action flang understands.
5270 if (!isa<PreprocessJobAction>(JA) && !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
5271 return false;
5272
5273 return true;
5274 }
5275
ShouldEmitStaticLibrary(const ArgList & Args) const5276 bool Driver::ShouldEmitStaticLibrary(const ArgList &Args) const {
5277 // Only emit static library if the flag is set explicitly.
5278 if (Args.hasArg(options::OPT_emit_static_lib))
5279 return true;
5280 return false;
5281 }
5282
5283 /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
5284 /// grouped values as integers. Numbers which are not provided are set to 0.
5285 ///
5286 /// \return True if the entire string was parsed (9.2), or all groups were
5287 /// parsed (10.3.5extrastuff).
GetReleaseVersion(StringRef Str,unsigned & Major,unsigned & Minor,unsigned & Micro,bool & HadExtra)5288 bool Driver::GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor,
5289 unsigned &Micro, bool &HadExtra) {
5290 HadExtra = false;
5291
5292 Major = Minor = Micro = 0;
5293 if (Str.empty())
5294 return false;
5295
5296 if (Str.consumeInteger(10, Major))
5297 return false;
5298 if (Str.empty())
5299 return true;
5300 if (Str[0] != '.')
5301 return false;
5302
5303 Str = Str.drop_front(1);
5304
5305 if (Str.consumeInteger(10, Minor))
5306 return false;
5307 if (Str.empty())
5308 return true;
5309 if (Str[0] != '.')
5310 return false;
5311 Str = Str.drop_front(1);
5312
5313 if (Str.consumeInteger(10, Micro))
5314 return false;
5315 if (!Str.empty())
5316 HadExtra = true;
5317 return true;
5318 }
5319
5320 /// Parse digits from a string \p Str and fulfill \p Digits with
5321 /// the parsed numbers. This method assumes that the max number of
5322 /// digits to look for is equal to Digits.size().
5323 ///
5324 /// \return True if the entire string was parsed and there are
5325 /// no extra characters remaining at the end.
GetReleaseVersion(StringRef Str,MutableArrayRef<unsigned> Digits)5326 bool Driver::GetReleaseVersion(StringRef Str,
5327 MutableArrayRef<unsigned> Digits) {
5328 if (Str.empty())
5329 return false;
5330
5331 unsigned CurDigit = 0;
5332 while (CurDigit < Digits.size()) {
5333 unsigned Digit;
5334 if (Str.consumeInteger(10, Digit))
5335 return false;
5336 Digits[CurDigit] = Digit;
5337 if (Str.empty())
5338 return true;
5339 if (Str[0] != '.')
5340 return false;
5341 Str = Str.drop_front(1);
5342 CurDigit++;
5343 }
5344
5345 // More digits than requested, bail out...
5346 return false;
5347 }
5348
5349 std::pair<unsigned, unsigned>
getIncludeExcludeOptionFlagMasks(bool IsClCompatMode) const5350 Driver::getIncludeExcludeOptionFlagMasks(bool IsClCompatMode) const {
5351 unsigned IncludedFlagsBitmask = 0;
5352 unsigned ExcludedFlagsBitmask = options::NoDriverOption;
5353
5354 if (IsClCompatMode) {
5355 // Include CL and Core options.
5356 IncludedFlagsBitmask |= options::CLOption;
5357 IncludedFlagsBitmask |= options::CoreOption;
5358 } else {
5359 ExcludedFlagsBitmask |= options::CLOption;
5360 }
5361
5362 return std::make_pair(IncludedFlagsBitmask, ExcludedFlagsBitmask);
5363 }
5364
isOptimizationLevelFast(const ArgList & Args)5365 bool clang::driver::isOptimizationLevelFast(const ArgList &Args) {
5366 return Args.hasFlag(options::OPT_Ofast, options::OPT_O_Group, false);
5367 }
5368
willEmitRemarks(const ArgList & Args)5369 bool clang::driver::willEmitRemarks(const ArgList &Args) {
5370 // -fsave-optimization-record enables it.
5371 if (Args.hasFlag(options::OPT_fsave_optimization_record,
5372 options::OPT_fno_save_optimization_record, false))
5373 return true;
5374
5375 // -fsave-optimization-record=<format> enables it as well.
5376 if (Args.hasFlag(options::OPT_fsave_optimization_record_EQ,
5377 options::OPT_fno_save_optimization_record, false))
5378 return true;
5379
5380 // -foptimization-record-file alone enables it too.
5381 if (Args.hasFlag(options::OPT_foptimization_record_file_EQ,
5382 options::OPT_fno_save_optimization_record, false))
5383 return true;
5384
5385 // -foptimization-record-passes alone enables it too.
5386 if (Args.hasFlag(options::OPT_foptimization_record_passes_EQ,
5387 options::OPT_fno_save_optimization_record, false))
5388 return true;
5389 return false;
5390 }
5391