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