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