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.h"
13 #include "clang/Basic/Version.h"
14 #include "clang/Config/config.h"
15 #include "clang/Driver/Action.h"
16 #include "clang/Driver/Compilation.h"
17 #include "clang/Driver/DriverDiagnostic.h"
18 #include "clang/Driver/Job.h"
19 #include "clang/Driver/Options.h"
20 #include "clang/Driver/Tool.h"
21 #include "clang/Driver/ToolChain.h"
22 #include "llvm/ADT/ArrayRef.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/StringSet.h"
26 #include "llvm/ADT/StringSwitch.h"
27 #include "llvm/Option/Arg.h"
28 #include "llvm/Option/ArgList.h"
29 #include "llvm/Option/OptSpecifier.h"
30 #include "llvm/Option/OptTable.h"
31 #include "llvm/Option/Option.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/FileSystem.h"
35 #include "llvm/Support/Path.h"
36 #include "llvm/Support/PrettyStackTrace.h"
37 #include "llvm/Support/Process.h"
38 #include "llvm/Support/Program.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include <map>
41 #include <memory>
42
43 using namespace clang::driver;
44 using namespace clang;
45 using namespace llvm::opt;
46
Driver(StringRef ClangExecutable,StringRef DefaultTargetTriple,DiagnosticsEngine & Diags)47 Driver::Driver(StringRef ClangExecutable,
48 StringRef DefaultTargetTriple,
49 DiagnosticsEngine &Diags)
50 : Opts(createDriverOptTable()), Diags(Diags), Mode(GCCMode),
51 ClangExecutable(ClangExecutable), SysRoot(DEFAULT_SYSROOT),
52 UseStdLib(true), DefaultTargetTriple(DefaultTargetTriple),
53 DriverTitle("clang LLVM compiler"),
54 CCPrintOptionsFilename(nullptr), CCPrintHeadersFilename(nullptr),
55 CCLogDiagnosticsFilename(nullptr),
56 CCCPrintBindings(false),
57 CCPrintHeaders(false), CCLogDiagnostics(false),
58 CCGenDiagnostics(false), CCCGenericGCCName(""), CheckInputsExist(true),
59 CCCUsePCH(true), SuppressMissingInputWarning(false) {
60
61 Name = llvm::sys::path::stem(ClangExecutable);
62 Dir = llvm::sys::path::parent_path(ClangExecutable);
63
64 // Compute the path to the resource directory.
65 StringRef ClangResourceDir(CLANG_RESOURCE_DIR);
66 SmallString<128> P(Dir);
67 if (ClangResourceDir != "") {
68 llvm::sys::path::append(P, ClangResourceDir);
69 } else {
70 StringRef ClangLibdirSuffix(CLANG_LIBDIR_SUFFIX);
71 llvm::sys::path::append(P, "..", Twine("lib") + ClangLibdirSuffix, "clang",
72 CLANG_VERSION_STRING);
73 }
74 ResourceDir = P.str();
75 }
76
~Driver()77 Driver::~Driver() {
78 delete Opts;
79
80 llvm::DeleteContainerSeconds(ToolChains);
81 }
82
ParseDriverMode(ArrayRef<const char * > Args)83 void Driver::ParseDriverMode(ArrayRef<const char *> Args) {
84 const std::string OptName =
85 getOpts().getOption(options::OPT_driver_mode).getPrefixedName();
86
87 for (size_t I = 0, E = Args.size(); I != E; ++I) {
88 // Ingore nullptrs, they are response file's EOL markers
89 if (Args[I] == nullptr)
90 continue;
91 const StringRef Arg = Args[I];
92 if (!Arg.startswith(OptName))
93 continue;
94
95 const StringRef Value = Arg.drop_front(OptName.size());
96 const unsigned M = llvm::StringSwitch<unsigned>(Value)
97 .Case("gcc", GCCMode)
98 .Case("g++", GXXMode)
99 .Case("cpp", CPPMode)
100 .Case("cl", CLMode)
101 .Default(~0U);
102
103 if (M != ~0U)
104 Mode = static_cast<DriverMode>(M);
105 else
106 Diag(diag::err_drv_unsupported_option_argument) << OptName << Value;
107 }
108 }
109
ParseArgStrings(ArrayRef<const char * > ArgStrings)110 InputArgList *Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings) {
111 llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
112
113 unsigned IncludedFlagsBitmask;
114 unsigned ExcludedFlagsBitmask;
115 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
116 getIncludeExcludeOptionFlagMasks();
117
118 unsigned MissingArgIndex, MissingArgCount;
119 InputArgList *Args = getOpts().ParseArgs(ArgStrings.begin(), ArgStrings.end(),
120 MissingArgIndex, MissingArgCount,
121 IncludedFlagsBitmask,
122 ExcludedFlagsBitmask);
123
124 // Check for missing argument error.
125 if (MissingArgCount)
126 Diag(clang::diag::err_drv_missing_argument)
127 << Args->getArgString(MissingArgIndex) << MissingArgCount;
128
129 // Check for unsupported options.
130 for (const Arg *A : *Args) {
131 if (A->getOption().hasFlag(options::Unsupported)) {
132 Diag(clang::diag::err_drv_unsupported_opt) << A->getAsString(*Args);
133 continue;
134 }
135
136 // Warn about -mcpu= without an argument.
137 if (A->getOption().matches(options::OPT_mcpu_EQ) &&
138 A->containsValue("")) {
139 Diag(clang::diag::warn_drv_empty_joined_argument) <<
140 A->getAsString(*Args);
141 }
142 }
143
144 for (arg_iterator it = Args->filtered_begin(options::OPT_UNKNOWN),
145 ie = Args->filtered_end(); it != ie; ++it) {
146 Diags.Report(diag::err_drv_unknown_argument) << (*it) ->getAsString(*Args);
147 }
148
149 return Args;
150 }
151
152 // Determine which compilation mode we are in. We look for options which
153 // affect the phase, starting with the earliest phases, and record which
154 // option we used to determine the final phase.
getFinalPhase(const DerivedArgList & DAL,Arg ** FinalPhaseArg) const155 phases::ID Driver::getFinalPhase(const DerivedArgList &DAL, Arg **FinalPhaseArg)
156 const {
157 Arg *PhaseArg = nullptr;
158 phases::ID FinalPhase;
159
160 // -{E,EP,P,M,MM} only run the preprocessor.
161 if (CCCIsCPP() ||
162 (PhaseArg = DAL.getLastArg(options::OPT_E)) ||
163 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_EP)) ||
164 (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM)) ||
165 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_P))) {
166 FinalPhase = phases::Preprocess;
167
168 // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
169 } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
170 (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) ||
171 (PhaseArg = DAL.getLastArg(options::OPT_verify_pch)) ||
172 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) ||
173 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) ||
174 (PhaseArg = DAL.getLastArg(options::OPT__migrate)) ||
175 (PhaseArg = DAL.getLastArg(options::OPT__analyze,
176 options::OPT__analyze_auto)) ||
177 (PhaseArg = DAL.getLastArg(options::OPT_emit_ast))) {
178 FinalPhase = phases::Compile;
179
180 // -S only runs up to the backend.
181 } else if ((PhaseArg = DAL.getLastArg(options::OPT_S))) {
182 FinalPhase = phases::Backend;
183
184 // -c only runs up to the assembler.
185 } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) {
186 FinalPhase = phases::Assemble;
187
188 // Otherwise do everything.
189 } else
190 FinalPhase = phases::Link;
191
192 if (FinalPhaseArg)
193 *FinalPhaseArg = PhaseArg;
194
195 return FinalPhase;
196 }
197
MakeInputArg(DerivedArgList & Args,OptTable * Opts,StringRef Value)198 static Arg* MakeInputArg(DerivedArgList &Args, OptTable *Opts,
199 StringRef Value) {
200 Arg *A = new Arg(Opts->getOption(options::OPT_INPUT), Value,
201 Args.getBaseArgs().MakeIndex(Value), Value.data());
202 Args.AddSynthesizedArg(A);
203 A->claim();
204 return A;
205 }
206
TranslateInputArgs(const InputArgList & Args) const207 DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
208 DerivedArgList *DAL = new DerivedArgList(Args);
209
210 bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
211 for (Arg *A : Args) {
212 // Unfortunately, we have to parse some forwarding options (-Xassembler,
213 // -Xlinker, -Xpreprocessor) because we either integrate their functionality
214 // (assembler and preprocessor), or bypass a previous driver ('collect2').
215
216 // Rewrite linker options, to replace --no-demangle with a custom internal
217 // option.
218 if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
219 A->getOption().matches(options::OPT_Xlinker)) &&
220 A->containsValue("--no-demangle")) {
221 // Add the rewritten no-demangle argument.
222 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_Xlinker__no_demangle));
223
224 // Add the remaining values as Xlinker arguments.
225 for (unsigned i = 0, e = A->getNumValues(); i != e; ++i)
226 if (StringRef(A->getValue(i)) != "--no-demangle")
227 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_Xlinker),
228 A->getValue(i));
229
230 continue;
231 }
232
233 // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
234 // some build systems. We don't try to be complete here because we don't
235 // care to encourage this usage model.
236 if (A->getOption().matches(options::OPT_Wp_COMMA) &&
237 (A->getValue(0) == StringRef("-MD") ||
238 A->getValue(0) == StringRef("-MMD"))) {
239 // Rewrite to -MD/-MMD along with -MF.
240 if (A->getValue(0) == StringRef("-MD"))
241 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MD));
242 else
243 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD));
244 if (A->getNumValues() == 2)
245 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF),
246 A->getValue(1));
247 continue;
248 }
249
250 // Rewrite reserved library names.
251 if (A->getOption().matches(options::OPT_l)) {
252 StringRef Value = A->getValue();
253
254 // Rewrite unless -nostdlib is present.
255 if (!HasNostdlib && Value == "stdc++") {
256 DAL->AddFlagArg(A, Opts->getOption(
257 options::OPT_Z_reserved_lib_stdcxx));
258 continue;
259 }
260
261 // Rewrite unconditionally.
262 if (Value == "cc_kext") {
263 DAL->AddFlagArg(A, Opts->getOption(
264 options::OPT_Z_reserved_lib_cckext));
265 continue;
266 }
267 }
268
269 // Pick up inputs via the -- option.
270 if (A->getOption().matches(options::OPT__DASH_DASH)) {
271 A->claim();
272 for (unsigned i = 0, e = A->getNumValues(); i != e; ++i)
273 DAL->append(MakeInputArg(*DAL, Opts, A->getValue(i)));
274 continue;
275 }
276
277 DAL->append(A);
278 }
279
280 // Add a default value of -mlinker-version=, if one was given and the user
281 // didn't specify one.
282 #if defined(HOST_LINK_VERSION)
283 if (!Args.hasArg(options::OPT_mlinker_version_EQ)) {
284 DAL->AddJoinedArg(0, Opts->getOption(options::OPT_mlinker_version_EQ),
285 HOST_LINK_VERSION);
286 DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
287 }
288 #endif
289
290 return DAL;
291 }
292
BuildCompilation(ArrayRef<const char * > ArgList)293 Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
294 llvm::PrettyStackTraceString CrashInfo("Compilation construction");
295
296 // FIXME: Handle environment options which affect driver behavior, somewhere
297 // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
298
299 if (char *env = ::getenv("COMPILER_PATH")) {
300 StringRef CompilerPath = env;
301 while (!CompilerPath.empty()) {
302 std::pair<StringRef, StringRef> Split
303 = CompilerPath.split(llvm::sys::EnvPathSeparator);
304 PrefixDirs.push_back(Split.first);
305 CompilerPath = Split.second;
306 }
307 }
308
309 // We look for the driver mode option early, because the mode can affect
310 // how other options are parsed.
311 ParseDriverMode(ArgList.slice(1));
312
313 // FIXME: What are we going to do with -V and -b?
314
315 // FIXME: This stuff needs to go into the Compilation, not the driver.
316 bool CCCPrintActions;
317
318 InputArgList *Args = ParseArgStrings(ArgList.slice(1));
319
320 // -no-canonical-prefixes is used very early in main.
321 Args->ClaimAllArgs(options::OPT_no_canonical_prefixes);
322
323 // Ignore -pipe.
324 Args->ClaimAllArgs(options::OPT_pipe);
325
326 // Extract -ccc args.
327 //
328 // FIXME: We need to figure out where this behavior should live. Most of it
329 // should be outside in the client; the parts that aren't should have proper
330 // options, either by introducing new ones or by overloading gcc ones like -V
331 // or -b.
332 CCCPrintActions = Args->hasArg(options::OPT_ccc_print_phases);
333 CCCPrintBindings = Args->hasArg(options::OPT_ccc_print_bindings);
334 if (const Arg *A = Args->getLastArg(options::OPT_ccc_gcc_name))
335 CCCGenericGCCName = A->getValue();
336 CCCUsePCH = Args->hasFlag(options::OPT_ccc_pch_is_pch,
337 options::OPT_ccc_pch_is_pth);
338 // FIXME: DefaultTargetTriple is used by the target-prefixed calls to as/ld
339 // and getToolChain is const.
340 if (IsCLMode()) {
341 // clang-cl targets MSVC-style Win32.
342 llvm::Triple T(DefaultTargetTriple);
343 T.setOS(llvm::Triple::Win32);
344 T.setEnvironment(llvm::Triple::MSVC);
345 DefaultTargetTriple = T.str();
346 }
347 if (const Arg *A = Args->getLastArg(options::OPT_target))
348 DefaultTargetTriple = A->getValue();
349 if (const Arg *A = Args->getLastArg(options::OPT_ccc_install_dir))
350 Dir = InstalledDir = A->getValue();
351 for (arg_iterator it = Args->filtered_begin(options::OPT_B),
352 ie = Args->filtered_end(); it != ie; ++it) {
353 const Arg *A = *it;
354 A->claim();
355 PrefixDirs.push_back(A->getValue(0));
356 }
357 if (const Arg *A = Args->getLastArg(options::OPT__sysroot_EQ))
358 SysRoot = A->getValue();
359 if (const Arg *A = Args->getLastArg(options::OPT__dyld_prefix_EQ))
360 DyldPrefix = A->getValue();
361 if (Args->hasArg(options::OPT_nostdlib))
362 UseStdLib = false;
363
364 if (const Arg *A = Args->getLastArg(options::OPT_resource_dir))
365 ResourceDir = A->getValue();
366
367 // Perform the default argument translations.
368 DerivedArgList *TranslatedArgs = TranslateInputArgs(*Args);
369
370 // Owned by the host.
371 const ToolChain &TC = getToolChain(*Args);
372
373 // The compilation takes ownership of Args.
374 Compilation *C = new Compilation(*this, TC, Args, TranslatedArgs);
375
376 if (!HandleImmediateArgs(*C))
377 return C;
378
379 // Construct the list of inputs.
380 InputList Inputs;
381 BuildInputs(C->getDefaultToolChain(), *TranslatedArgs, Inputs);
382
383 // Construct the list of abstract actions to perform for this compilation. On
384 // MachO targets this uses the driver-driver and universal actions.
385 if (TC.getTriple().isOSBinFormatMachO())
386 BuildUniversalActions(C->getDefaultToolChain(), C->getArgs(),
387 Inputs, C->getActions());
388 else
389 BuildActions(C->getDefaultToolChain(), C->getArgs(), Inputs,
390 C->getActions());
391
392 if (CCCPrintActions) {
393 PrintActions(*C);
394 return C;
395 }
396
397 BuildJobs(*C);
398
399 return C;
400 }
401
402 // When clang crashes, produce diagnostic information including the fully
403 // preprocessed source file(s). Request that the developer attach the
404 // diagnostic information to a bug report.
generateCompilationDiagnostics(Compilation & C,const Command & FailingCommand)405 void Driver::generateCompilationDiagnostics(Compilation &C,
406 const Command &FailingCommand) {
407 if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics))
408 return;
409
410 // Don't try to generate diagnostics for link or dsymutil jobs.
411 if (FailingCommand.getCreator().isLinkJob() ||
412 FailingCommand.getCreator().isDsymutilJob())
413 return;
414
415 // Print the version of the compiler.
416 PrintVersion(C, llvm::errs());
417
418 Diag(clang::diag::note_drv_command_failed_diag_msg)
419 << "PLEASE submit a bug report to " BUG_REPORT_URL " and include the "
420 "crash backtrace, preprocessed source, and associated run script.";
421
422 // Suppress driver output and emit preprocessor output to temp file.
423 Mode = CPPMode;
424 CCGenDiagnostics = true;
425
426 // Save the original job command(s).
427 Command Cmd = FailingCommand;
428
429 // Keep track of whether we produce any errors while trying to produce
430 // preprocessed sources.
431 DiagnosticErrorTrap Trap(Diags);
432
433 // Suppress tool output.
434 C.initCompilationForDiagnostics();
435
436 // Construct the list of inputs.
437 InputList Inputs;
438 BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs);
439
440 for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) {
441 bool IgnoreInput = false;
442
443 // Ignore input from stdin or any inputs that cannot be preprocessed.
444 // Check type first as not all linker inputs have a value.
445 if (types::getPreprocessedType(it->first) == types::TY_INVALID) {
446 IgnoreInput = true;
447 } else if (!strcmp(it->second->getValue(), "-")) {
448 Diag(clang::diag::note_drv_command_failed_diag_msg)
449 << "Error generating preprocessed source(s) - ignoring input from stdin"
450 ".";
451 IgnoreInput = true;
452 }
453
454 if (IgnoreInput) {
455 it = Inputs.erase(it);
456 ie = Inputs.end();
457 } else {
458 ++it;
459 }
460 }
461
462 if (Inputs.empty()) {
463 Diag(clang::diag::note_drv_command_failed_diag_msg)
464 << "Error generating preprocessed source(s) - no preprocessable inputs.";
465 return;
466 }
467
468 // Don't attempt to generate preprocessed files if multiple -arch options are
469 // used, unless they're all duplicates.
470 llvm::StringSet<> ArchNames;
471 for (const Arg *A : C.getArgs()) {
472 if (A->getOption().matches(options::OPT_arch)) {
473 StringRef ArchName = A->getValue();
474 ArchNames.insert(ArchName);
475 }
476 }
477 if (ArchNames.size() > 1) {
478 Diag(clang::diag::note_drv_command_failed_diag_msg)
479 << "Error generating preprocessed source(s) - cannot generate "
480 "preprocessed source with multiple -arch options.";
481 return;
482 }
483
484 // Construct the list of abstract actions to perform for this compilation. On
485 // Darwin OSes this uses the driver-driver and builds universal actions.
486 const ToolChain &TC = C.getDefaultToolChain();
487 if (TC.getTriple().isOSBinFormatMachO())
488 BuildUniversalActions(TC, C.getArgs(), Inputs, C.getActions());
489 else
490 BuildActions(TC, C.getArgs(), Inputs, C.getActions());
491
492 BuildJobs(C);
493
494 // If there were errors building the compilation, quit now.
495 if (Trap.hasErrorOccurred()) {
496 Diag(clang::diag::note_drv_command_failed_diag_msg)
497 << "Error generating preprocessed source(s).";
498 return;
499 }
500
501 // Generate preprocessed output.
502 SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
503 C.ExecuteJob(C.getJobs(), FailingCommands);
504
505 // If any of the preprocessing commands failed, clean up and exit.
506 if (!FailingCommands.empty()) {
507 if (!C.getArgs().hasArg(options::OPT_save_temps))
508 C.CleanupFileList(C.getTempFiles(), true);
509
510 Diag(clang::diag::note_drv_command_failed_diag_msg)
511 << "Error generating preprocessed source(s).";
512 return;
513 }
514
515 const ArgStringList &TempFiles = C.getTempFiles();
516 if (TempFiles.empty()) {
517 Diag(clang::diag::note_drv_command_failed_diag_msg)
518 << "Error generating preprocessed source(s).";
519 return;
520 }
521
522 Diag(clang::diag::note_drv_command_failed_diag_msg)
523 << "\n********************\n\n"
524 "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n"
525 "Preprocessed source(s) and associated run script(s) are located at:";
526
527 SmallString<128> VFS;
528 for (const char *TempFile : TempFiles) {
529 Diag(clang::diag::note_drv_command_failed_diag_msg) << TempFile;
530 if (StringRef(TempFile).endswith(".cache")) {
531 // In some cases (modules) we'll dump extra data to help with reproducing
532 // the crash into a directory next to the output.
533 VFS = llvm::sys::path::filename(TempFile);
534 llvm::sys::path::append(VFS, "vfs", "vfs.yaml");
535 }
536 }
537
538 // Assume associated files are based off of the first temporary file.
539 CrashReportInfo CrashInfo(TempFiles[0], VFS);
540
541 std::string Script = CrashInfo.Filename.rsplit('.').first.str() + ".sh";
542 std::error_code EC;
543 llvm::raw_fd_ostream ScriptOS(Script, EC, llvm::sys::fs::F_Excl);
544 if (EC) {
545 Diag(clang::diag::note_drv_command_failed_diag_msg)
546 << "Error generating run script: " + Script + " " + EC.message();
547 } else {
548 Cmd.Print(ScriptOS, "\n", /*Quote=*/true, &CrashInfo);
549 Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
550 }
551
552 for (const auto &A : C.getArgs().filtered(options::OPT_frewrite_map_file,
553 options::OPT_frewrite_map_file_EQ))
554 Diag(clang::diag::note_drv_command_failed_diag_msg) << A->getValue();
555
556 Diag(clang::diag::note_drv_command_failed_diag_msg)
557 << "\n\n********************";
558 }
559
setUpResponseFiles(Compilation & C,Job & J)560 void Driver::setUpResponseFiles(Compilation &C, Job &J) {
561 if (JobList *Jobs = dyn_cast<JobList>(&J)) {
562 for (auto &Job : *Jobs)
563 setUpResponseFiles(C, Job);
564 return;
565 }
566
567 Command *CurCommand = dyn_cast<Command>(&J);
568 if (!CurCommand)
569 return;
570
571 // Since argumentsFitWithinSystemLimits() may underestimate system's capacity
572 // if the tool does not support response files, there is a chance/ that things
573 // will just work without a response file, so we silently just skip it.
574 if (CurCommand->getCreator().getResponseFilesSupport() == Tool::RF_None ||
575 llvm::sys::argumentsFitWithinSystemLimits(CurCommand->getArguments()))
576 return;
577
578 std::string TmpName = GetTemporaryPath("response", "txt");
579 CurCommand->setResponseFile(C.addTempFile(C.getArgs().MakeArgString(
580 TmpName.c_str())));
581 }
582
ExecuteCompilation(Compilation & C,SmallVectorImpl<std::pair<int,const Command * >> & FailingCommands)583 int Driver::ExecuteCompilation(Compilation &C,
584 SmallVectorImpl< std::pair<int, const Command *> > &FailingCommands) {
585 // Just print if -### was present.
586 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
587 C.getJobs().Print(llvm::errs(), "\n", true);
588 return 0;
589 }
590
591 // If there were errors building the compilation, quit now.
592 if (Diags.hasErrorOccurred())
593 return 1;
594
595 // Set up response file names for each command, if necessary
596 setUpResponseFiles(C, C.getJobs());
597
598 C.ExecuteJob(C.getJobs(), FailingCommands);
599
600 // Remove temp files.
601 C.CleanupFileList(C.getTempFiles());
602
603 // If the command succeeded, we are done.
604 if (FailingCommands.empty())
605 return 0;
606
607 // Otherwise, remove result files and print extra information about abnormal
608 // failures.
609 for (SmallVectorImpl< std::pair<int, const Command *> >::iterator it =
610 FailingCommands.begin(), ie = FailingCommands.end(); it != ie; ++it) {
611 int Res = it->first;
612 const Command *FailingCommand = it->second;
613
614 // Remove result files if we're not saving temps.
615 if (!C.getArgs().hasArg(options::OPT_save_temps)) {
616 const JobAction *JA = cast<JobAction>(&FailingCommand->getSource());
617 C.CleanupFileMap(C.getResultFiles(), JA, true);
618
619 // Failure result files are valid unless we crashed.
620 if (Res < 0)
621 C.CleanupFileMap(C.getFailureResultFiles(), JA, true);
622 }
623
624 // Print extra information about abnormal failures, if possible.
625 //
626 // This is ad-hoc, but we don't want to be excessively noisy. If the result
627 // status was 1, assume the command failed normally. In particular, if it
628 // was the compiler then assume it gave a reasonable error code. Failures
629 // in other tools are less common, and they generally have worse
630 // diagnostics, so always print the diagnostic there.
631 const Tool &FailingTool = FailingCommand->getCreator();
632
633 if (!FailingCommand->getCreator().hasGoodDiagnostics() || Res != 1) {
634 // FIXME: See FIXME above regarding result code interpretation.
635 if (Res < 0)
636 Diag(clang::diag::err_drv_command_signalled)
637 << FailingTool.getShortName();
638 else
639 Diag(clang::diag::err_drv_command_failed)
640 << FailingTool.getShortName() << Res;
641 }
642 }
643 return 0;
644 }
645
PrintHelp(bool ShowHidden) const646 void Driver::PrintHelp(bool ShowHidden) const {
647 unsigned IncludedFlagsBitmask;
648 unsigned ExcludedFlagsBitmask;
649 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
650 getIncludeExcludeOptionFlagMasks();
651
652 ExcludedFlagsBitmask |= options::NoDriverOption;
653 if (!ShowHidden)
654 ExcludedFlagsBitmask |= HelpHidden;
655
656 getOpts().PrintHelp(llvm::outs(), Name.c_str(), DriverTitle.c_str(),
657 IncludedFlagsBitmask, ExcludedFlagsBitmask);
658 }
659
PrintVersion(const Compilation & C,raw_ostream & OS) const660 void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const {
661 // FIXME: The following handlers should use a callback mechanism, we don't
662 // know what the client would like to do.
663 OS << getClangFullVersion() << '\n';
664 const ToolChain &TC = C.getDefaultToolChain();
665 OS << "Target: " << TC.getTripleString() << '\n';
666
667 // Print the threading model.
668 if (Arg *A = C.getArgs().getLastArg(options::OPT_mthread_model)) {
669 // Don't print if the ToolChain would have barfed on it already
670 if (TC.isThreadModelSupported(A->getValue()))
671 OS << "Thread model: " << A->getValue();
672 } else
673 OS << "Thread model: " << TC.getThreadModel();
674 OS << '\n';
675 }
676
677 /// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
678 /// option.
PrintDiagnosticCategories(raw_ostream & OS)679 static void PrintDiagnosticCategories(raw_ostream &OS) {
680 // Skip the empty category.
681 for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories();
682 i != max; ++i)
683 OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
684 }
685
HandleImmediateArgs(const Compilation & C)686 bool Driver::HandleImmediateArgs(const Compilation &C) {
687 // The order these options are handled in gcc is all over the place, but we
688 // don't expect inconsistencies w.r.t. that to matter in practice.
689
690 if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
691 llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
692 return false;
693 }
694
695 if (C.getArgs().hasArg(options::OPT_dumpversion)) {
696 // Since -dumpversion is only implemented for pedantic GCC compatibility, we
697 // return an answer which matches our definition of __VERSION__.
698 //
699 // If we want to return a more correct answer some day, then we should
700 // introduce a non-pedantically GCC compatible mode to Clang in which we
701 // provide sensible definitions for -dumpversion, __VERSION__, etc.
702 llvm::outs() << "4.2.1\n";
703 return false;
704 }
705
706 if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
707 PrintDiagnosticCategories(llvm::outs());
708 return false;
709 }
710
711 if (C.getArgs().hasArg(options::OPT_help) ||
712 C.getArgs().hasArg(options::OPT__help_hidden)) {
713 PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
714 return false;
715 }
716
717 if (C.getArgs().hasArg(options::OPT__version)) {
718 // Follow gcc behavior and use stdout for --version and stderr for -v.
719 PrintVersion(C, llvm::outs());
720 return false;
721 }
722
723 if (C.getArgs().hasArg(options::OPT_v) ||
724 C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
725 PrintVersion(C, llvm::errs());
726 SuppressMissingInputWarning = true;
727 }
728
729 const ToolChain &TC = C.getDefaultToolChain();
730
731 if (C.getArgs().hasArg(options::OPT_v))
732 TC.printVerboseInfo(llvm::errs());
733
734 if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
735 llvm::outs() << "programs: =";
736 for (ToolChain::path_list::const_iterator it = TC.getProgramPaths().begin(),
737 ie = TC.getProgramPaths().end(); it != ie; ++it) {
738 if (it != TC.getProgramPaths().begin())
739 llvm::outs() << ':';
740 llvm::outs() << *it;
741 }
742 llvm::outs() << "\n";
743 llvm::outs() << "libraries: =" << ResourceDir;
744
745 StringRef sysroot = C.getSysRoot();
746
747 for (ToolChain::path_list::const_iterator it = TC.getFilePaths().begin(),
748 ie = TC.getFilePaths().end(); it != ie; ++it) {
749 llvm::outs() << ':';
750 const char *path = it->c_str();
751 if (path[0] == '=')
752 llvm::outs() << sysroot << path + 1;
753 else
754 llvm::outs() << path;
755 }
756 llvm::outs() << "\n";
757 return false;
758 }
759
760 // FIXME: The following handlers should use a callback mechanism, we don't
761 // know what the client would like to do.
762 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
763 llvm::outs() << GetFilePath(A->getValue(), TC) << "\n";
764 return false;
765 }
766
767 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
768 llvm::outs() << GetProgramPath(A->getValue(), TC) << "\n";
769 return false;
770 }
771
772 if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
773 llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
774 return false;
775 }
776
777 if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
778 const MultilibSet &Multilibs = TC.getMultilibs();
779
780 for (MultilibSet::const_iterator I = Multilibs.begin(), E = Multilibs.end();
781 I != E; ++I) {
782 llvm::outs() << *I << "\n";
783 }
784 return false;
785 }
786
787 if (C.getArgs().hasArg(options::OPT_print_multi_directory)) {
788 const MultilibSet &Multilibs = TC.getMultilibs();
789 for (MultilibSet::const_iterator I = Multilibs.begin(), E = Multilibs.end();
790 I != E; ++I) {
791 if (I->gccSuffix().empty())
792 llvm::outs() << ".\n";
793 else {
794 StringRef Suffix(I->gccSuffix());
795 assert(Suffix.front() == '/');
796 llvm::outs() << Suffix.substr(1) << "\n";
797 }
798 }
799 return false;
800 }
801
802 if (C.getArgs().hasArg(options::OPT_print_multi_os_directory)) {
803 // FIXME: This should print out "lib/../lib", "lib/../lib64", or
804 // "lib/../lib32" as appropriate for the toolchain. For now, print
805 // nothing because it's not supported yet.
806 return false;
807 }
808
809 return true;
810 }
811
PrintActions1(const Compilation & C,Action * A,std::map<Action *,unsigned> & Ids)812 static unsigned PrintActions1(const Compilation &C, Action *A,
813 std::map<Action*, unsigned> &Ids) {
814 if (Ids.count(A))
815 return Ids[A];
816
817 std::string str;
818 llvm::raw_string_ostream os(str);
819
820 os << Action::getClassName(A->getKind()) << ", ";
821 if (InputAction *IA = dyn_cast<InputAction>(A)) {
822 os << "\"" << IA->getInputArg().getValue() << "\"";
823 } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
824 os << '"' << BIA->getArchName() << '"'
825 << ", {" << PrintActions1(C, *BIA->begin(), Ids) << "}";
826 } else {
827 os << "{";
828 for (Action::iterator it = A->begin(), ie = A->end(); it != ie;) {
829 os << PrintActions1(C, *it, Ids);
830 ++it;
831 if (it != ie)
832 os << ", ";
833 }
834 os << "}";
835 }
836
837 unsigned Id = Ids.size();
838 Ids[A] = Id;
839 llvm::errs() << Id << ": " << os.str() << ", "
840 << types::getTypeName(A->getType()) << "\n";
841
842 return Id;
843 }
844
PrintActions(const Compilation & C) const845 void Driver::PrintActions(const Compilation &C) const {
846 std::map<Action*, unsigned> Ids;
847 for (ActionList::const_iterator it = C.getActions().begin(),
848 ie = C.getActions().end(); it != ie; ++it)
849 PrintActions1(C, *it, Ids);
850 }
851
852 /// \brief Check whether the given input tree contains any compilation or
853 /// assembly actions.
ContainsCompileOrAssembleAction(const Action * A)854 static bool ContainsCompileOrAssembleAction(const Action *A) {
855 if (isa<CompileJobAction>(A) ||
856 isa<BackendJobAction>(A) ||
857 isa<AssembleJobAction>(A))
858 return true;
859
860 for (Action::const_iterator it = A->begin(), ie = A->end(); it != ie; ++it)
861 if (ContainsCompileOrAssembleAction(*it))
862 return true;
863
864 return false;
865 }
866
BuildUniversalActions(const ToolChain & TC,DerivedArgList & Args,const InputList & BAInputs,ActionList & Actions) const867 void Driver::BuildUniversalActions(const ToolChain &TC,
868 DerivedArgList &Args,
869 const InputList &BAInputs,
870 ActionList &Actions) const {
871 llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
872 // Collect the list of architectures. Duplicates are allowed, but should only
873 // be handled once (in the order seen).
874 llvm::StringSet<> ArchNames;
875 SmallVector<const char *, 4> Archs;
876 for (Arg *A : Args) {
877 if (A->getOption().matches(options::OPT_arch)) {
878 // Validate the option here; we don't save the type here because its
879 // particular spelling may participate in other driver choices.
880 llvm::Triple::ArchType Arch =
881 tools::darwin::getArchTypeForMachOArchName(A->getValue());
882 if (Arch == llvm::Triple::UnknownArch) {
883 Diag(clang::diag::err_drv_invalid_arch_name)
884 << A->getAsString(Args);
885 continue;
886 }
887
888 A->claim();
889 if (ArchNames.insert(A->getValue()).second)
890 Archs.push_back(A->getValue());
891 }
892 }
893
894 // When there is no explicit arch for this platform, make sure we still bind
895 // the architecture (to the default) so that -Xarch_ is handled correctly.
896 if (!Archs.size())
897 Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName()));
898
899 ActionList SingleActions;
900 BuildActions(TC, Args, BAInputs, SingleActions);
901
902 // Add in arch bindings for every top level action, as well as lipo and
903 // dsymutil steps if needed.
904 for (unsigned i = 0, e = SingleActions.size(); i != e; ++i) {
905 Action *Act = SingleActions[i];
906
907 // Make sure we can lipo this kind of output. If not (and it is an actual
908 // output) then we disallow, since we can't create an output file with the
909 // right name without overwriting it. We could remove this oddity by just
910 // changing the output names to include the arch, which would also fix
911 // -save-temps. Compatibility wins for now.
912
913 if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
914 Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
915 << types::getTypeName(Act->getType());
916
917 ActionList Inputs;
918 for (unsigned i = 0, e = Archs.size(); i != e; ++i) {
919 Inputs.push_back(
920 new BindArchAction(std::unique_ptr<Action>(Act), Archs[i]));
921 if (i != 0)
922 Inputs.back()->setOwnsInputs(false);
923 }
924
925 // Lipo if necessary, we do it this way because we need to set the arch flag
926 // so that -Xarch_ gets overwritten.
927 if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
928 Actions.append(Inputs.begin(), Inputs.end());
929 else
930 Actions.push_back(new LipoJobAction(Inputs, Act->getType()));
931
932 // Handle debug info queries.
933 Arg *A = Args.getLastArg(options::OPT_g_Group);
934 if (A && !A->getOption().matches(options::OPT_g0) &&
935 !A->getOption().matches(options::OPT_gstabs) &&
936 ContainsCompileOrAssembleAction(Actions.back())) {
937
938 // Add a 'dsymutil' step if necessary, when debug info is enabled and we
939 // have a compile input. We need to run 'dsymutil' ourselves in such cases
940 // because the debug info will refer to a temporary object file which
941 // will be removed at the end of the compilation process.
942 if (Act->getType() == types::TY_Image) {
943 ActionList Inputs;
944 Inputs.push_back(Actions.back());
945 Actions.pop_back();
946 Actions.push_back(new DsymutilJobAction(Inputs, types::TY_dSYM));
947 }
948
949 // Verify the debug info output.
950 if (Args.hasArg(options::OPT_verify_debug_info)) {
951 std::unique_ptr<Action> VerifyInput(Actions.back());
952 Actions.pop_back();
953 Actions.push_back(new VerifyDebugInfoJobAction(std::move(VerifyInput),
954 types::TY_Nothing));
955 }
956 }
957 }
958 }
959
960 /// \brief Check that the file referenced by Value exists. If it doesn't,
961 /// issue a diagnostic and return false.
DiagnoseInputExistence(const Driver & D,const DerivedArgList & Args,StringRef Value)962 static bool DiagnoseInputExistence(const Driver &D, const DerivedArgList &Args,
963 StringRef Value) {
964 if (!D.getCheckInputsExist())
965 return true;
966
967 // stdin always exists.
968 if (Value == "-")
969 return true;
970
971 SmallString<64> Path(Value);
972 if (Arg *WorkDir = Args.getLastArg(options::OPT_working_directory)) {
973 if (!llvm::sys::path::is_absolute(Path.str())) {
974 SmallString<64> Directory(WorkDir->getValue());
975 llvm::sys::path::append(Directory, Value);
976 Path.assign(Directory);
977 }
978 }
979
980 if (llvm::sys::fs::exists(Twine(Path)))
981 return true;
982
983 if (D.IsCLMode() && llvm::sys::Process::FindInEnvPath("LIB", Value))
984 return true;
985
986 D.Diag(clang::diag::err_drv_no_such_file) << Path.str();
987 return false;
988 }
989
990 // Construct a the list of inputs and their types.
BuildInputs(const ToolChain & TC,DerivedArgList & Args,InputList & Inputs) const991 void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args,
992 InputList &Inputs) const {
993 // Track the current user specified (-x) input. We also explicitly track the
994 // argument used to set the type; we only want to claim the type when we
995 // actually use it, so we warn about unused -x arguments.
996 types::ID InputType = types::TY_Nothing;
997 Arg *InputTypeArg = nullptr;
998
999 // The last /TC or /TP option sets the input type to C or C++ globally.
1000 if (Arg *TCTP = Args.getLastArgNoClaim(options::OPT__SLASH_TC,
1001 options::OPT__SLASH_TP)) {
1002 InputTypeArg = TCTP;
1003 InputType = TCTP->getOption().matches(options::OPT__SLASH_TC)
1004 ? types::TY_C : types::TY_CXX;
1005
1006 arg_iterator it = Args.filtered_begin(options::OPT__SLASH_TC,
1007 options::OPT__SLASH_TP);
1008 const arg_iterator ie = Args.filtered_end();
1009 Arg *Previous = *it++;
1010 bool ShowNote = false;
1011 while (it != ie) {
1012 Diag(clang::diag::warn_drv_overriding_flag_option)
1013 << Previous->getSpelling() << (*it)->getSpelling();
1014 Previous = *it++;
1015 ShowNote = true;
1016 }
1017 if (ShowNote)
1018 Diag(clang::diag::note_drv_t_option_is_global);
1019
1020 // No driver mode exposes -x and /TC or /TP; we don't support mixing them.
1021 assert(!Args.hasArg(options::OPT_x) && "-x and /TC or /TP is not allowed");
1022 }
1023
1024 for (Arg *A : Args) {
1025 if (A->getOption().getKind() == Option::InputClass) {
1026 const char *Value = A->getValue();
1027 types::ID Ty = types::TY_INVALID;
1028
1029 // Infer the input type if necessary.
1030 if (InputType == types::TY_Nothing) {
1031 // If there was an explicit arg for this, claim it.
1032 if (InputTypeArg)
1033 InputTypeArg->claim();
1034
1035 // stdin must be handled specially.
1036 if (memcmp(Value, "-", 2) == 0) {
1037 // If running with -E, treat as a C input (this changes the builtin
1038 // macros, for example). This may be overridden by -ObjC below.
1039 //
1040 // Otherwise emit an error but still use a valid type to avoid
1041 // spurious errors (e.g., no inputs).
1042 if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP())
1043 Diag(IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl
1044 : clang::diag::err_drv_unknown_stdin_type);
1045 Ty = types::TY_C;
1046 } else {
1047 // Otherwise lookup by extension.
1048 // Fallback is C if invoked as C preprocessor or Object otherwise.
1049 // We use a host hook here because Darwin at least has its own
1050 // idea of what .s is.
1051 if (const char *Ext = strrchr(Value, '.'))
1052 Ty = TC.LookupTypeForExtension(Ext + 1);
1053
1054 if (Ty == types::TY_INVALID) {
1055 if (CCCIsCPP())
1056 Ty = types::TY_C;
1057 else
1058 Ty = types::TY_Object;
1059 }
1060
1061 // If the driver is invoked as C++ compiler (like clang++ or c++) it
1062 // should autodetect some input files as C++ for g++ compatibility.
1063 if (CCCIsCXX()) {
1064 types::ID OldTy = Ty;
1065 Ty = types::lookupCXXTypeForCType(Ty);
1066
1067 if (Ty != OldTy)
1068 Diag(clang::diag::warn_drv_treating_input_as_cxx)
1069 << getTypeName(OldTy) << getTypeName(Ty);
1070 }
1071 }
1072
1073 // -ObjC and -ObjC++ override the default language, but only for "source
1074 // files". We just treat everything that isn't a linker input as a
1075 // source file.
1076 //
1077 // FIXME: Clean this up if we move the phase sequence into the type.
1078 if (Ty != types::TY_Object) {
1079 if (Args.hasArg(options::OPT_ObjC))
1080 Ty = types::TY_ObjC;
1081 else if (Args.hasArg(options::OPT_ObjCXX))
1082 Ty = types::TY_ObjCXX;
1083 }
1084 } else {
1085 assert(InputTypeArg && "InputType set w/o InputTypeArg");
1086 if (!InputTypeArg->getOption().matches(options::OPT_x)) {
1087 // If emulating cl.exe, make sure that /TC and /TP don't affect input
1088 // object files.
1089 const char *Ext = strrchr(Value, '.');
1090 if (Ext && TC.LookupTypeForExtension(Ext + 1) == types::TY_Object)
1091 Ty = types::TY_Object;
1092 }
1093 if (Ty == types::TY_INVALID) {
1094 Ty = InputType;
1095 InputTypeArg->claim();
1096 }
1097 }
1098
1099 if (DiagnoseInputExistence(*this, Args, Value))
1100 Inputs.push_back(std::make_pair(Ty, A));
1101
1102 } else if (A->getOption().matches(options::OPT__SLASH_Tc)) {
1103 StringRef Value = A->getValue();
1104 if (DiagnoseInputExistence(*this, Args, Value)) {
1105 Arg *InputArg = MakeInputArg(Args, Opts, A->getValue());
1106 Inputs.push_back(std::make_pair(types::TY_C, InputArg));
1107 }
1108 A->claim();
1109 } else if (A->getOption().matches(options::OPT__SLASH_Tp)) {
1110 StringRef Value = A->getValue();
1111 if (DiagnoseInputExistence(*this, Args, Value)) {
1112 Arg *InputArg = MakeInputArg(Args, Opts, A->getValue());
1113 Inputs.push_back(std::make_pair(types::TY_CXX, InputArg));
1114 }
1115 A->claim();
1116 } else if (A->getOption().hasFlag(options::LinkerInput)) {
1117 // Just treat as object type, we could make a special type for this if
1118 // necessary.
1119 Inputs.push_back(std::make_pair(types::TY_Object, A));
1120
1121 } else if (A->getOption().matches(options::OPT_x)) {
1122 InputTypeArg = A;
1123 InputType = types::lookupTypeForTypeSpecifier(A->getValue());
1124 A->claim();
1125
1126 // Follow gcc behavior and treat as linker input for invalid -x
1127 // options. Its not clear why we shouldn't just revert to unknown; but
1128 // this isn't very important, we might as well be bug compatible.
1129 if (!InputType) {
1130 Diag(clang::diag::err_drv_unknown_language) << A->getValue();
1131 InputType = types::TY_Object;
1132 }
1133 }
1134 }
1135 if (CCCIsCPP() && Inputs.empty()) {
1136 // If called as standalone preprocessor, stdin is processed
1137 // if no other input is present.
1138 Arg *A = MakeInputArg(Args, Opts, "-");
1139 Inputs.push_back(std::make_pair(types::TY_C, A));
1140 }
1141 }
1142
BuildActions(const ToolChain & TC,DerivedArgList & Args,const InputList & Inputs,ActionList & Actions) const1143 void Driver::BuildActions(const ToolChain &TC, DerivedArgList &Args,
1144 const InputList &Inputs, ActionList &Actions) const {
1145 llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
1146
1147 if (!SuppressMissingInputWarning && Inputs.empty()) {
1148 Diag(clang::diag::err_drv_no_input_files);
1149 return;
1150 }
1151
1152 Arg *FinalPhaseArg;
1153 phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
1154
1155 if (FinalPhase == phases::Link && Args.hasArg(options::OPT_emit_llvm)) {
1156 Diag(clang::diag::err_drv_emit_llvm_link);
1157 }
1158
1159 // Reject -Z* at the top level, these options should never have been exposed
1160 // by gcc.
1161 if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
1162 Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
1163
1164 // Diagnose misuse of /Fo.
1165 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) {
1166 StringRef V = A->getValue();
1167 if (Inputs.size() > 1 && !V.empty() &&
1168 !llvm::sys::path::is_separator(V.back())) {
1169 // Check whether /Fo tries to name an output file for multiple inputs.
1170 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
1171 << A->getSpelling() << V;
1172 Args.eraseArg(options::OPT__SLASH_Fo);
1173 }
1174 }
1175
1176 // Diagnose misuse of /Fa.
1177 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fa)) {
1178 StringRef V = A->getValue();
1179 if (Inputs.size() > 1 && !V.empty() &&
1180 !llvm::sys::path::is_separator(V.back())) {
1181 // Check whether /Fa tries to name an asm file for multiple inputs.
1182 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
1183 << A->getSpelling() << V;
1184 Args.eraseArg(options::OPT__SLASH_Fa);
1185 }
1186 }
1187
1188 // Diagnose misuse of /o.
1189 if (Arg *A = Args.getLastArg(options::OPT__SLASH_o)) {
1190 if (A->getValue()[0] == '\0') {
1191 // It has to have a value.
1192 Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1;
1193 Args.eraseArg(options::OPT__SLASH_o);
1194 }
1195 }
1196
1197 // Construct the actions to perform.
1198 ActionList LinkerInputs;
1199
1200 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PL;
1201 for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
1202 types::ID InputType = Inputs[i].first;
1203 const Arg *InputArg = Inputs[i].second;
1204
1205 PL.clear();
1206 types::getCompilationPhases(InputType, PL);
1207
1208 // If the first step comes after the final phase we are doing as part of
1209 // this compilation, warn the user about it.
1210 phases::ID InitialPhase = PL[0];
1211 if (InitialPhase > FinalPhase) {
1212 // Claim here to avoid the more general unused warning.
1213 InputArg->claim();
1214
1215 // Suppress all unused style warnings with -Qunused-arguments
1216 if (Args.hasArg(options::OPT_Qunused_arguments))
1217 continue;
1218
1219 // Special case when final phase determined by binary name, rather than
1220 // by a command-line argument with a corresponding Arg.
1221 if (CCCIsCPP())
1222 Diag(clang::diag::warn_drv_input_file_unused_by_cpp)
1223 << InputArg->getAsString(Args)
1224 << getPhaseName(InitialPhase);
1225 // Special case '-E' warning on a previously preprocessed file to make
1226 // more sense.
1227 else if (InitialPhase == phases::Compile &&
1228 FinalPhase == phases::Preprocess &&
1229 getPreprocessedType(InputType) == types::TY_INVALID)
1230 Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
1231 << InputArg->getAsString(Args)
1232 << !!FinalPhaseArg
1233 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
1234 else
1235 Diag(clang::diag::warn_drv_input_file_unused)
1236 << InputArg->getAsString(Args)
1237 << getPhaseName(InitialPhase)
1238 << !!FinalPhaseArg
1239 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
1240 continue;
1241 }
1242
1243 // Build the pipeline for this file.
1244 std::unique_ptr<Action> Current(new InputAction(*InputArg, InputType));
1245 for (SmallVectorImpl<phases::ID>::iterator
1246 i = PL.begin(), e = PL.end(); i != e; ++i) {
1247 phases::ID Phase = *i;
1248
1249 // We are done if this step is past what the user requested.
1250 if (Phase > FinalPhase)
1251 break;
1252
1253 // Queue linker inputs.
1254 if (Phase == phases::Link) {
1255 assert((i + 1) == e && "linking must be final compilation step.");
1256 LinkerInputs.push_back(Current.release());
1257 break;
1258 }
1259
1260 // Some types skip the assembler phase (e.g., llvm-bc), but we can't
1261 // encode this in the steps because the intermediate type depends on
1262 // arguments. Just special case here.
1263 if (Phase == phases::Assemble && Current->getType() != types::TY_PP_Asm)
1264 continue;
1265
1266 // Otherwise construct the appropriate action.
1267 Current = ConstructPhaseAction(Args, Phase, std::move(Current));
1268 if (Current->getType() == types::TY_Nothing)
1269 break;
1270 }
1271
1272 // If we ended with something, add to the output list.
1273 if (Current)
1274 Actions.push_back(Current.release());
1275 }
1276
1277 // Add a link action if necessary.
1278 if (!LinkerInputs.empty())
1279 Actions.push_back(new LinkJobAction(LinkerInputs, types::TY_Image));
1280
1281 // If we are linking, claim any options which are obviously only used for
1282 // compilation.
1283 if (FinalPhase == phases::Link && PL.size() == 1) {
1284 Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
1285 Args.ClaimAllArgs(options::OPT_cl_compile_Group);
1286 }
1287
1288 // Claim ignored clang-cl options.
1289 Args.ClaimAllArgs(options::OPT_cl_ignored_Group);
1290 }
1291
1292 std::unique_ptr<Action>
ConstructPhaseAction(const ArgList & Args,phases::ID Phase,std::unique_ptr<Action> Input) const1293 Driver::ConstructPhaseAction(const ArgList &Args, phases::ID Phase,
1294 std::unique_ptr<Action> Input) const {
1295 llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
1296 // Build the appropriate action.
1297 switch (Phase) {
1298 case phases::Link: llvm_unreachable("link action invalid here.");
1299 case phases::Preprocess: {
1300 types::ID OutputTy;
1301 // -{M, MM} alter the output type.
1302 if (Args.hasArg(options::OPT_M, options::OPT_MM)) {
1303 OutputTy = types::TY_Dependencies;
1304 } else {
1305 OutputTy = Input->getType();
1306 if (!Args.hasFlag(options::OPT_frewrite_includes,
1307 options::OPT_fno_rewrite_includes, false) &&
1308 !CCGenDiagnostics)
1309 OutputTy = types::getPreprocessedType(OutputTy);
1310 assert(OutputTy != types::TY_INVALID &&
1311 "Cannot preprocess this input type!");
1312 }
1313 return llvm::make_unique<PreprocessJobAction>(std::move(Input), OutputTy);
1314 }
1315 case phases::Precompile: {
1316 types::ID OutputTy = types::TY_PCH;
1317 if (Args.hasArg(options::OPT_fsyntax_only)) {
1318 // Syntax checks should not emit a PCH file
1319 OutputTy = types::TY_Nothing;
1320 }
1321 return llvm::make_unique<PrecompileJobAction>(std::move(Input), OutputTy);
1322 }
1323 case phases::Compile: {
1324 if (Args.hasArg(options::OPT_fsyntax_only))
1325 return llvm::make_unique<CompileJobAction>(std::move(Input),
1326 types::TY_Nothing);
1327 if (Args.hasArg(options::OPT_rewrite_objc))
1328 return llvm::make_unique<CompileJobAction>(std::move(Input),
1329 types::TY_RewrittenObjC);
1330 if (Args.hasArg(options::OPT_rewrite_legacy_objc))
1331 return llvm::make_unique<CompileJobAction>(std::move(Input),
1332 types::TY_RewrittenLegacyObjC);
1333 if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto))
1334 return llvm::make_unique<AnalyzeJobAction>(std::move(Input),
1335 types::TY_Plist);
1336 if (Args.hasArg(options::OPT__migrate))
1337 return llvm::make_unique<MigrateJobAction>(std::move(Input),
1338 types::TY_Remap);
1339 if (Args.hasArg(options::OPT_emit_ast))
1340 return llvm::make_unique<CompileJobAction>(std::move(Input),
1341 types::TY_AST);
1342 if (Args.hasArg(options::OPT_module_file_info))
1343 return llvm::make_unique<CompileJobAction>(std::move(Input),
1344 types::TY_ModuleFile);
1345 if (Args.hasArg(options::OPT_verify_pch))
1346 return llvm::make_unique<VerifyPCHJobAction>(std::move(Input),
1347 types::TY_Nothing);
1348 return llvm::make_unique<CompileJobAction>(std::move(Input),
1349 types::TY_LLVM_BC);
1350 }
1351 case phases::Backend: {
1352 if (IsUsingLTO(Args)) {
1353 types::ID Output =
1354 Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
1355 return llvm::make_unique<BackendJobAction>(std::move(Input), Output);
1356 }
1357 if (Args.hasArg(options::OPT_emit_llvm)) {
1358 types::ID Output =
1359 Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC;
1360 return llvm::make_unique<BackendJobAction>(std::move(Input), Output);
1361 }
1362 return llvm::make_unique<BackendJobAction>(std::move(Input),
1363 types::TY_PP_Asm);
1364 }
1365 case phases::Assemble:
1366 return llvm::make_unique<AssembleJobAction>(std::move(Input),
1367 types::TY_Object);
1368 }
1369
1370 llvm_unreachable("invalid phase in ConstructPhaseAction");
1371 }
1372
IsUsingLTO(const ArgList & Args) const1373 bool Driver::IsUsingLTO(const ArgList &Args) const {
1374 if (Args.hasFlag(options::OPT_flto, options::OPT_fno_lto, false))
1375 return true;
1376
1377 return false;
1378 }
1379
BuildJobs(Compilation & C) const1380 void Driver::BuildJobs(Compilation &C) const {
1381 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
1382
1383 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
1384
1385 // It is an error to provide a -o option if we are making multiple output
1386 // files.
1387 if (FinalOutput) {
1388 unsigned NumOutputs = 0;
1389 for (const Action *A : C.getActions())
1390 if (A->getType() != types::TY_Nothing)
1391 ++NumOutputs;
1392
1393 if (NumOutputs > 1) {
1394 Diag(clang::diag::err_drv_output_argument_with_multiple_files);
1395 FinalOutput = nullptr;
1396 }
1397 }
1398
1399 // Collect the list of architectures.
1400 llvm::StringSet<> ArchNames;
1401 if (C.getDefaultToolChain().getTriple().isOSBinFormatMachO())
1402 for (const Arg *A : C.getArgs())
1403 if (A->getOption().matches(options::OPT_arch))
1404 ArchNames.insert(A->getValue());
1405
1406 for (Action *A : C.getActions()) {
1407 // If we are linking an image for multiple archs then the linker wants
1408 // -arch_multiple and -final_output <final image name>. Unfortunately, this
1409 // doesn't fit in cleanly because we have to pass this information down.
1410 //
1411 // FIXME: This is a hack; find a cleaner way to integrate this into the
1412 // process.
1413 const char *LinkingOutput = nullptr;
1414 if (isa<LipoJobAction>(A)) {
1415 if (FinalOutput)
1416 LinkingOutput = FinalOutput->getValue();
1417 else
1418 LinkingOutput = getDefaultImageName();
1419 }
1420
1421 InputInfo II;
1422 BuildJobsForAction(C, A, &C.getDefaultToolChain(),
1423 /*BoundArch*/nullptr,
1424 /*AtTopLevel*/ true,
1425 /*MultipleArchs*/ ArchNames.size() > 1,
1426 /*LinkingOutput*/ LinkingOutput,
1427 II);
1428 }
1429
1430 // If the user passed -Qunused-arguments or there were errors, don't warn
1431 // about any unused arguments.
1432 if (Diags.hasErrorOccurred() ||
1433 C.getArgs().hasArg(options::OPT_Qunused_arguments))
1434 return;
1435
1436 // Claim -### here.
1437 (void) C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
1438
1439 // Claim --driver-mode, it was handled earlier.
1440 (void) C.getArgs().hasArg(options::OPT_driver_mode);
1441
1442 for (Arg *A : C.getArgs()) {
1443 // FIXME: It would be nice to be able to send the argument to the
1444 // DiagnosticsEngine, so that extra values, position, and so on could be
1445 // printed.
1446 if (!A->isClaimed()) {
1447 if (A->getOption().hasFlag(options::NoArgumentUnused))
1448 continue;
1449
1450 // Suppress the warning automatically if this is just a flag, and it is an
1451 // instance of an argument we already claimed.
1452 const Option &Opt = A->getOption();
1453 if (Opt.getKind() == Option::FlagClass) {
1454 bool DuplicateClaimed = false;
1455
1456 for (arg_iterator it = C.getArgs().filtered_begin(&Opt),
1457 ie = C.getArgs().filtered_end(); it != ie; ++it) {
1458 if ((*it)->isClaimed()) {
1459 DuplicateClaimed = true;
1460 break;
1461 }
1462 }
1463
1464 if (DuplicateClaimed)
1465 continue;
1466 }
1467
1468 Diag(clang::diag::warn_drv_unused_argument)
1469 << A->getAsString(C.getArgs());
1470 }
1471 }
1472 }
1473
SelectToolForJob(Compilation & C,const ToolChain * TC,const JobAction * JA,const ActionList * & Inputs)1474 static const Tool *SelectToolForJob(Compilation &C, const ToolChain *TC,
1475 const JobAction *JA,
1476 const ActionList *&Inputs) {
1477 const Tool *ToolForJob = nullptr;
1478
1479 // See if we should look for a compiler with an integrated assembler. We match
1480 // bottom up, so what we are actually looking for is an assembler job with a
1481 // compiler input.
1482
1483 if (TC->useIntegratedAs() &&
1484 !C.getArgs().hasArg(options::OPT_save_temps) &&
1485 !C.getArgs().hasArg(options::OPT_via_file_asm) &&
1486 !C.getArgs().hasArg(options::OPT__SLASH_FA) &&
1487 !C.getArgs().hasArg(options::OPT__SLASH_Fa) &&
1488 isa<AssembleJobAction>(JA) &&
1489 Inputs->size() == 1 && isa<BackendJobAction>(*Inputs->begin())) {
1490 // A BackendJob is always preceded by a CompileJob, and without
1491 // -save-temps they will always get combined together, so instead of
1492 // checking the backend tool, check if the tool for the CompileJob
1493 // has an integrated assembler.
1494 const ActionList *BackendInputs = &(*Inputs)[0]->getInputs();
1495 JobAction *CompileJA = cast<CompileJobAction>(*BackendInputs->begin());
1496 const Tool *Compiler = TC->SelectTool(*CompileJA);
1497 if (!Compiler)
1498 return nullptr;
1499 if (Compiler->hasIntegratedAssembler()) {
1500 Inputs = &(*BackendInputs)[0]->getInputs();
1501 ToolForJob = Compiler;
1502 }
1503 }
1504
1505 // A backend job should always be combined with the preceding compile job
1506 // unless OPT_save_temps is enabled and the compiler is capable of emitting
1507 // LLVM IR as an intermediate output.
1508 if (isa<BackendJobAction>(JA)) {
1509 // Check if the compiler supports emitting LLVM IR.
1510 assert(Inputs->size() == 1);
1511 JobAction *CompileJA = cast<CompileJobAction>(*Inputs->begin());
1512 const Tool *Compiler = TC->SelectTool(*CompileJA);
1513 if (!Compiler)
1514 return nullptr;
1515 if (!Compiler->canEmitIR() ||
1516 !C.getArgs().hasArg(options::OPT_save_temps)) {
1517 Inputs = &(*Inputs)[0]->getInputs();
1518 ToolForJob = Compiler;
1519 }
1520 }
1521
1522 // Otherwise use the tool for the current job.
1523 if (!ToolForJob)
1524 ToolForJob = TC->SelectTool(*JA);
1525
1526 // See if we should use an integrated preprocessor. We do so when we have
1527 // exactly one input, since this is the only use case we care about
1528 // (irrelevant since we don't support combine yet).
1529 if (Inputs->size() == 1 && isa<PreprocessJobAction>(*Inputs->begin()) &&
1530 !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
1531 !C.getArgs().hasArg(options::OPT_traditional_cpp) &&
1532 !C.getArgs().hasArg(options::OPT_save_temps) &&
1533 !C.getArgs().hasArg(options::OPT_rewrite_objc) &&
1534 ToolForJob->hasIntegratedCPP())
1535 Inputs = &(*Inputs)[0]->getInputs();
1536
1537 return ToolForJob;
1538 }
1539
BuildJobsForAction(Compilation & C,const Action * A,const ToolChain * TC,const char * BoundArch,bool AtTopLevel,bool MultipleArchs,const char * LinkingOutput,InputInfo & Result) const1540 void Driver::BuildJobsForAction(Compilation &C,
1541 const Action *A,
1542 const ToolChain *TC,
1543 const char *BoundArch,
1544 bool AtTopLevel,
1545 bool MultipleArchs,
1546 const char *LinkingOutput,
1547 InputInfo &Result) const {
1548 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
1549
1550 if (const InputAction *IA = dyn_cast<InputAction>(A)) {
1551 // FIXME: It would be nice to not claim this here; maybe the old scheme of
1552 // just using Args was better?
1553 const Arg &Input = IA->getInputArg();
1554 Input.claim();
1555 if (Input.getOption().matches(options::OPT_INPUT)) {
1556 const char *Name = Input.getValue();
1557 Result = InputInfo(Name, A->getType(), Name);
1558 } else
1559 Result = InputInfo(&Input, A->getType(), "");
1560 return;
1561 }
1562
1563 if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
1564 const ToolChain *TC;
1565 const char *ArchName = BAA->getArchName();
1566
1567 if (ArchName)
1568 TC = &getToolChain(C.getArgs(), ArchName);
1569 else
1570 TC = &C.getDefaultToolChain();
1571
1572 BuildJobsForAction(C, *BAA->begin(), TC, BAA->getArchName(),
1573 AtTopLevel, MultipleArchs, LinkingOutput, Result);
1574 return;
1575 }
1576
1577 const ActionList *Inputs = &A->getInputs();
1578
1579 const JobAction *JA = cast<JobAction>(A);
1580 const Tool *T = SelectToolForJob(C, TC, JA, Inputs);
1581 if (!T)
1582 return;
1583
1584 // Only use pipes when there is exactly one input.
1585 InputInfoList InputInfos;
1586 for (const Action *Input : *Inputs) {
1587 // Treat dsymutil and verify sub-jobs as being at the top-level too, they
1588 // shouldn't get temporary output names.
1589 // FIXME: Clean this up.
1590 bool SubJobAtTopLevel = false;
1591 if (AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A)))
1592 SubJobAtTopLevel = true;
1593
1594 InputInfo II;
1595 BuildJobsForAction(C, Input, TC, BoundArch, SubJobAtTopLevel, MultipleArchs,
1596 LinkingOutput, II);
1597 InputInfos.push_back(II);
1598 }
1599
1600 // Always use the first input as the base input.
1601 const char *BaseInput = InputInfos[0].getBaseInput();
1602
1603 // ... except dsymutil actions, which use their actual input as the base
1604 // input.
1605 if (JA->getType() == types::TY_dSYM)
1606 BaseInput = InputInfos[0].getFilename();
1607
1608 // Determine the place to write output to, if any.
1609 if (JA->getType() == types::TY_Nothing)
1610 Result = InputInfo(A->getType(), BaseInput);
1611 else
1612 Result = InputInfo(GetNamedOutputPath(C, *JA, BaseInput, BoundArch,
1613 AtTopLevel, MultipleArchs),
1614 A->getType(), BaseInput);
1615
1616 if (CCCPrintBindings && !CCGenDiagnostics) {
1617 llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"'
1618 << " - \"" << T->getName() << "\", inputs: [";
1619 for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
1620 llvm::errs() << InputInfos[i].getAsString();
1621 if (i + 1 != e)
1622 llvm::errs() << ", ";
1623 }
1624 llvm::errs() << "], output: " << Result.getAsString() << "\n";
1625 } else {
1626 T->ConstructJob(C, *JA, Result, InputInfos,
1627 C.getArgsForToolChain(TC, BoundArch), LinkingOutput);
1628 }
1629 }
1630
getDefaultImageName() const1631 const char *Driver::getDefaultImageName() const {
1632 llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
1633 return Target.isOSWindows() ? "a.exe" : "a.out";
1634 }
1635
1636 /// \brief Create output filename based on ArgValue, which could either be a
1637 /// full filename, filename without extension, or a directory. If ArgValue
1638 /// does not provide a filename, then use BaseName, and use the extension
1639 /// suitable for FileType.
MakeCLOutputFilename(const ArgList & Args,StringRef ArgValue,StringRef BaseName,types::ID FileType)1640 static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue,
1641 StringRef BaseName, types::ID FileType) {
1642 SmallString<128> Filename = ArgValue;
1643
1644 if (ArgValue.empty()) {
1645 // If the argument is empty, output to BaseName in the current dir.
1646 Filename = BaseName;
1647 } else if (llvm::sys::path::is_separator(Filename.back())) {
1648 // If the argument is a directory, output to BaseName in that dir.
1649 llvm::sys::path::append(Filename, BaseName);
1650 }
1651
1652 if (!llvm::sys::path::has_extension(ArgValue)) {
1653 // If the argument didn't provide an extension, then set it.
1654 const char *Extension = types::getTypeTempSuffix(FileType, true);
1655
1656 if (FileType == types::TY_Image &&
1657 Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) {
1658 // The output file is a dll.
1659 Extension = "dll";
1660 }
1661
1662 llvm::sys::path::replace_extension(Filename, Extension);
1663 }
1664
1665 return Args.MakeArgString(Filename.c_str());
1666 }
1667
GetNamedOutputPath(Compilation & C,const JobAction & JA,const char * BaseInput,const char * BoundArch,bool AtTopLevel,bool MultipleArchs) const1668 const char *Driver::GetNamedOutputPath(Compilation &C,
1669 const JobAction &JA,
1670 const char *BaseInput,
1671 const char *BoundArch,
1672 bool AtTopLevel,
1673 bool MultipleArchs) const {
1674 llvm::PrettyStackTraceString CrashInfo("Computing output path");
1675 // Output to a user requested destination?
1676 if (AtTopLevel && !isa<DsymutilJobAction>(JA) &&
1677 !isa<VerifyJobAction>(JA)) {
1678 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
1679 return C.addResultFile(FinalOutput->getValue(), &JA);
1680 }
1681
1682 // For /P, preprocess to file named after BaseInput.
1683 if (C.getArgs().hasArg(options::OPT__SLASH_P)) {
1684 assert(AtTopLevel && isa<PreprocessJobAction>(JA));
1685 StringRef BaseName = llvm::sys::path::filename(BaseInput);
1686 StringRef NameArg;
1687 if (Arg *A = C.getArgs().getLastArg(options::OPT__SLASH_Fi,
1688 options::OPT__SLASH_o))
1689 NameArg = A->getValue();
1690 return C.addResultFile(MakeCLOutputFilename(C.getArgs(), NameArg, BaseName,
1691 types::TY_PP_C), &JA);
1692 }
1693
1694 // Default to writing to stdout?
1695 if (AtTopLevel && !CCGenDiagnostics &&
1696 (isa<PreprocessJobAction>(JA) || JA.getType() == types::TY_ModuleFile))
1697 return "-";
1698
1699 // Is this the assembly listing for /FA?
1700 if (JA.getType() == types::TY_PP_Asm &&
1701 (C.getArgs().hasArg(options::OPT__SLASH_FA) ||
1702 C.getArgs().hasArg(options::OPT__SLASH_Fa))) {
1703 // Use /Fa and the input filename to determine the asm file name.
1704 StringRef BaseName = llvm::sys::path::filename(BaseInput);
1705 StringRef FaValue = C.getArgs().getLastArgValue(options::OPT__SLASH_Fa);
1706 return C.addResultFile(MakeCLOutputFilename(C.getArgs(), FaValue, BaseName,
1707 JA.getType()), &JA);
1708 }
1709
1710 // Output to a temporary file?
1711 if ((!AtTopLevel && !C.getArgs().hasArg(options::OPT_save_temps) &&
1712 !C.getArgs().hasArg(options::OPT__SLASH_Fo)) ||
1713 CCGenDiagnostics) {
1714 StringRef Name = llvm::sys::path::filename(BaseInput);
1715 std::pair<StringRef, StringRef> Split = Name.split('.');
1716 std::string TmpName =
1717 GetTemporaryPath(Split.first,
1718 types::getTypeTempSuffix(JA.getType(), IsCLMode()));
1719 return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str()));
1720 }
1721
1722 SmallString<128> BasePath(BaseInput);
1723 StringRef BaseName;
1724
1725 // Dsymutil actions should use the full path.
1726 if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA))
1727 BaseName = BasePath;
1728 else
1729 BaseName = llvm::sys::path::filename(BasePath);
1730
1731 // Determine what the derived output name should be.
1732 const char *NamedOutput;
1733
1734 if (JA.getType() == types::TY_Object &&
1735 C.getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) {
1736 // The /Fo or /o flag decides the object filename.
1737 StringRef Val = C.getArgs().getLastArg(options::OPT__SLASH_Fo,
1738 options::OPT__SLASH_o)->getValue();
1739 NamedOutput = MakeCLOutputFilename(C.getArgs(), Val, BaseName,
1740 types::TY_Object);
1741 } else if (JA.getType() == types::TY_Image &&
1742 C.getArgs().hasArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o)) {
1743 // The /Fe or /o flag names the linked file.
1744 StringRef Val = C.getArgs().getLastArg(options::OPT__SLASH_Fe,
1745 options::OPT__SLASH_o)->getValue();
1746 NamedOutput = MakeCLOutputFilename(C.getArgs(), Val, BaseName,
1747 types::TY_Image);
1748 } else if (JA.getType() == types::TY_Image) {
1749 if (IsCLMode()) {
1750 // clang-cl uses BaseName for the executable name.
1751 NamedOutput = MakeCLOutputFilename(C.getArgs(), "", BaseName,
1752 types::TY_Image);
1753 } else if (MultipleArchs && BoundArch) {
1754 SmallString<128> Output(getDefaultImageName());
1755 Output += "-";
1756 Output.append(BoundArch);
1757 NamedOutput = C.getArgs().MakeArgString(Output.c_str());
1758 } else
1759 NamedOutput = getDefaultImageName();
1760 } else {
1761 const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
1762 assert(Suffix && "All types used for output should have a suffix.");
1763
1764 std::string::size_type End = std::string::npos;
1765 if (!types::appendSuffixForType(JA.getType()))
1766 End = BaseName.rfind('.');
1767 SmallString<128> Suffixed(BaseName.substr(0, End));
1768 if (MultipleArchs && BoundArch) {
1769 Suffixed += "-";
1770 Suffixed.append(BoundArch);
1771 }
1772 // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for
1773 // the unoptimized bitcode so that it does not get overwritten by the ".bc"
1774 // optimized bitcode output.
1775 if (!AtTopLevel && C.getArgs().hasArg(options::OPT_emit_llvm) &&
1776 JA.getType() == types::TY_LLVM_BC)
1777 Suffixed += ".tmp";
1778 Suffixed += '.';
1779 Suffixed += Suffix;
1780 NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
1781 }
1782
1783 // If we're saving temps and the temp file conflicts with the input file,
1784 // then avoid overwriting input file.
1785 if (!AtTopLevel && C.getArgs().hasArg(options::OPT_save_temps) &&
1786 NamedOutput == BaseName) {
1787
1788 bool SameFile = false;
1789 SmallString<256> Result;
1790 llvm::sys::fs::current_path(Result);
1791 llvm::sys::path::append(Result, BaseName);
1792 llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile);
1793 // Must share the same path to conflict.
1794 if (SameFile) {
1795 StringRef Name = llvm::sys::path::filename(BaseInput);
1796 std::pair<StringRef, StringRef> Split = Name.split('.');
1797 std::string TmpName =
1798 GetTemporaryPath(Split.first,
1799 types::getTypeTempSuffix(JA.getType(), IsCLMode()));
1800 return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str()));
1801 }
1802 }
1803
1804 // As an annoying special case, PCH generation doesn't strip the pathname.
1805 if (JA.getType() == types::TY_PCH) {
1806 llvm::sys::path::remove_filename(BasePath);
1807 if (BasePath.empty())
1808 BasePath = NamedOutput;
1809 else
1810 llvm::sys::path::append(BasePath, NamedOutput);
1811 return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA);
1812 } else {
1813 return C.addResultFile(NamedOutput, &JA);
1814 }
1815 }
1816
GetFilePath(const char * Name,const ToolChain & TC) const1817 std::string Driver::GetFilePath(const char *Name, const ToolChain &TC) const {
1818 // Respect a limited subset of the '-Bprefix' functionality in GCC by
1819 // attempting to use this prefix when looking for file paths.
1820 for (Driver::prefix_list::const_iterator it = PrefixDirs.begin(),
1821 ie = PrefixDirs.end(); it != ie; ++it) {
1822 std::string Dir(*it);
1823 if (Dir.empty())
1824 continue;
1825 if (Dir[0] == '=')
1826 Dir = SysRoot + Dir.substr(1);
1827 SmallString<128> P(Dir);
1828 llvm::sys::path::append(P, Name);
1829 if (llvm::sys::fs::exists(Twine(P)))
1830 return P.str();
1831 }
1832
1833 SmallString<128> P(ResourceDir);
1834 llvm::sys::path::append(P, Name);
1835 if (llvm::sys::fs::exists(Twine(P)))
1836 return P.str();
1837
1838 const ToolChain::path_list &List = TC.getFilePaths();
1839 for (ToolChain::path_list::const_iterator
1840 it = List.begin(), ie = List.end(); it != ie; ++it) {
1841 std::string Dir(*it);
1842 if (Dir.empty())
1843 continue;
1844 if (Dir[0] == '=')
1845 Dir = SysRoot + Dir.substr(1);
1846 SmallString<128> P(Dir);
1847 llvm::sys::path::append(P, Name);
1848 if (llvm::sys::fs::exists(Twine(P)))
1849 return P.str();
1850 }
1851
1852 return Name;
1853 }
1854
1855 void
generatePrefixedToolNames(const char * Tool,const ToolChain & TC,SmallVectorImpl<std::string> & Names) const1856 Driver::generatePrefixedToolNames(const char *Tool, const ToolChain &TC,
1857 SmallVectorImpl<std::string> &Names) const {
1858 // FIXME: Needs a better variable than DefaultTargetTriple
1859 Names.push_back(DefaultTargetTriple + "-" + Tool);
1860 Names.push_back(Tool);
1861 }
1862
ScanDirForExecutable(SmallString<128> & Dir,ArrayRef<std::string> Names)1863 static bool ScanDirForExecutable(SmallString<128> &Dir,
1864 ArrayRef<std::string> Names) {
1865 for (const auto &Name : Names) {
1866 llvm::sys::path::append(Dir, Name);
1867 if (llvm::sys::fs::can_execute(Twine(Dir)))
1868 return true;
1869 llvm::sys::path::remove_filename(Dir);
1870 }
1871 return false;
1872 }
1873
GetProgramPath(const char * Name,const ToolChain & TC) const1874 std::string Driver::GetProgramPath(const char *Name,
1875 const ToolChain &TC) const {
1876 SmallVector<std::string, 2> TargetSpecificExecutables;
1877 generatePrefixedToolNames(Name, TC, TargetSpecificExecutables);
1878
1879 // Respect a limited subset of the '-Bprefix' functionality in GCC by
1880 // attempting to use this prefix when looking for program paths.
1881 for (const auto &PrefixDir : PrefixDirs) {
1882 if (llvm::sys::fs::is_directory(PrefixDir)) {
1883 SmallString<128> P(PrefixDir);
1884 if (ScanDirForExecutable(P, TargetSpecificExecutables))
1885 return P.str();
1886 } else {
1887 SmallString<128> P(PrefixDir + Name);
1888 if (llvm::sys::fs::can_execute(Twine(P)))
1889 return P.str();
1890 }
1891 }
1892
1893 const ToolChain::path_list &List = TC.getProgramPaths();
1894 for (const auto &Path : List) {
1895 SmallString<128> P(Path);
1896 if (ScanDirForExecutable(P, TargetSpecificExecutables))
1897 return P.str();
1898 }
1899
1900 // If all else failed, search the path.
1901 for (const auto &TargetSpecificExecutable : TargetSpecificExecutables)
1902 if (llvm::ErrorOr<std::string> P =
1903 llvm::sys::findProgramByName(TargetSpecificExecutable))
1904 return *P;
1905
1906 return Name;
1907 }
1908
GetTemporaryPath(StringRef Prefix,const char * Suffix) const1909 std::string Driver::GetTemporaryPath(StringRef Prefix, const char *Suffix)
1910 const {
1911 SmallString<128> Path;
1912 std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path);
1913 if (EC) {
1914 Diag(clang::diag::err_unable_to_make_temp) << EC.message();
1915 return "";
1916 }
1917
1918 return Path.str();
1919 }
1920
1921 /// \brief Compute target triple from args.
1922 ///
1923 /// This routine provides the logic to compute a target triple from various
1924 /// args passed to the driver and the default triple string.
computeTargetTriple(StringRef DefaultTargetTriple,const ArgList & Args,StringRef DarwinArchName)1925 static llvm::Triple computeTargetTriple(StringRef DefaultTargetTriple,
1926 const ArgList &Args,
1927 StringRef DarwinArchName) {
1928 // FIXME: Already done in Compilation *Driver::BuildCompilation
1929 if (const Arg *A = Args.getLastArg(options::OPT_target))
1930 DefaultTargetTriple = A->getValue();
1931
1932 llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
1933
1934 // Handle Apple-specific options available here.
1935 if (Target.isOSBinFormatMachO()) {
1936 // If an explict Darwin arch name is given, that trumps all.
1937 if (!DarwinArchName.empty()) {
1938 tools::darwin::setTripleTypeForMachOArchName(Target, DarwinArchName);
1939 return Target;
1940 }
1941
1942 // Handle the Darwin '-arch' flag.
1943 if (Arg *A = Args.getLastArg(options::OPT_arch)) {
1944 StringRef ArchName = A->getValue();
1945 tools::darwin::setTripleTypeForMachOArchName(Target, ArchName);
1946 }
1947 }
1948
1949 // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
1950 // '-mbig-endian'/'-EB'.
1951 if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
1952 options::OPT_mbig_endian)) {
1953 if (A->getOption().matches(options::OPT_mlittle_endian)) {
1954 if (Target.getArch() == llvm::Triple::mips)
1955 Target.setArch(llvm::Triple::mipsel);
1956 else if (Target.getArch() == llvm::Triple::mips64)
1957 Target.setArch(llvm::Triple::mips64el);
1958 else if (Target.getArch() == llvm::Triple::aarch64_be)
1959 Target.setArch(llvm::Triple::aarch64);
1960 } else {
1961 if (Target.getArch() == llvm::Triple::mipsel)
1962 Target.setArch(llvm::Triple::mips);
1963 else if (Target.getArch() == llvm::Triple::mips64el)
1964 Target.setArch(llvm::Triple::mips64);
1965 else if (Target.getArch() == llvm::Triple::aarch64)
1966 Target.setArch(llvm::Triple::aarch64_be);
1967 }
1968 }
1969
1970 // Skip further flag support on OSes which don't support '-m32' or '-m64'.
1971 if (Target.getArchName() == "tce" || Target.getOS() == llvm::Triple::Minix)
1972 return Target;
1973
1974 // Handle pseudo-target flags '-m64', '-mx32', '-m32' and '-m16'.
1975 if (Arg *A = Args.getLastArg(options::OPT_m64, options::OPT_mx32,
1976 options::OPT_m32, options::OPT_m16)) {
1977 llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
1978
1979 if (A->getOption().matches(options::OPT_m64)) {
1980 AT = Target.get64BitArchVariant().getArch();
1981 if (Target.getEnvironment() == llvm::Triple::GNUX32)
1982 Target.setEnvironment(llvm::Triple::GNU);
1983 } else if (A->getOption().matches(options::OPT_mx32) &&
1984 Target.get64BitArchVariant().getArch() == llvm::Triple::x86_64) {
1985 AT = llvm::Triple::x86_64;
1986 Target.setEnvironment(llvm::Triple::GNUX32);
1987 } else if (A->getOption().matches(options::OPT_m32)) {
1988 AT = Target.get32BitArchVariant().getArch();
1989 if (Target.getEnvironment() == llvm::Triple::GNUX32)
1990 Target.setEnvironment(llvm::Triple::GNU);
1991 } else if (A->getOption().matches(options::OPT_m16) &&
1992 Target.get32BitArchVariant().getArch() == llvm::Triple::x86) {
1993 AT = llvm::Triple::x86;
1994 Target.setEnvironment(llvm::Triple::CODE16);
1995 }
1996
1997 if (AT != llvm::Triple::UnknownArch && AT != Target.getArch())
1998 Target.setArch(AT);
1999 }
2000
2001 return Target;
2002 }
2003
getToolChain(const ArgList & Args,StringRef DarwinArchName) const2004 const ToolChain &Driver::getToolChain(const ArgList &Args,
2005 StringRef DarwinArchName) const {
2006 llvm::Triple Target = computeTargetTriple(DefaultTargetTriple, Args,
2007 DarwinArchName);
2008
2009 ToolChain *&TC = ToolChains[Target.str()];
2010 if (!TC) {
2011 switch (Target.getOS()) {
2012 case llvm::Triple::Darwin:
2013 case llvm::Triple::MacOSX:
2014 case llvm::Triple::IOS:
2015 TC = new toolchains::DarwinClang(*this, Target, Args);
2016 break;
2017 case llvm::Triple::DragonFly:
2018 TC = new toolchains::DragonFly(*this, Target, Args);
2019 break;
2020 case llvm::Triple::OpenBSD:
2021 TC = new toolchains::OpenBSD(*this, Target, Args);
2022 break;
2023 case llvm::Triple::Bitrig:
2024 TC = new toolchains::Bitrig(*this, Target, Args);
2025 break;
2026 case llvm::Triple::NetBSD:
2027 TC = new toolchains::NetBSD(*this, Target, Args);
2028 break;
2029 case llvm::Triple::FreeBSD:
2030 TC = new toolchains::FreeBSD(*this, Target, Args);
2031 break;
2032 case llvm::Triple::Minix:
2033 TC = new toolchains::Minix(*this, Target, Args);
2034 break;
2035 case llvm::Triple::Linux:
2036 if (Target.getArch() == llvm::Triple::hexagon)
2037 TC = new toolchains::Hexagon_TC(*this, Target, Args);
2038 else
2039 TC = new toolchains::Linux(*this, Target, Args);
2040 break;
2041 case llvm::Triple::Solaris:
2042 TC = new toolchains::Solaris(*this, Target, Args);
2043 break;
2044 case llvm::Triple::Win32:
2045 switch (Target.getEnvironment()) {
2046 default:
2047 if (Target.isOSBinFormatELF())
2048 TC = new toolchains::Generic_ELF(*this, Target, Args);
2049 else if (Target.isOSBinFormatMachO())
2050 TC = new toolchains::MachO(*this, Target, Args);
2051 else
2052 TC = new toolchains::Generic_GCC(*this, Target, Args);
2053 break;
2054 case llvm::Triple::GNU:
2055 // FIXME: We need a MinGW toolchain. Use the default Generic_GCC
2056 // toolchain for now as the default case would below otherwise.
2057 if (Target.isOSBinFormatELF())
2058 TC = new toolchains::Generic_ELF(*this, Target, Args);
2059 else
2060 TC = new toolchains::Generic_GCC(*this, Target, Args);
2061 break;
2062 case llvm::Triple::Itanium:
2063 TC = new toolchains::CrossWindowsToolChain(*this, Target, Args);
2064 break;
2065 case llvm::Triple::MSVC:
2066 case llvm::Triple::UnknownEnvironment:
2067 TC = new toolchains::MSVCToolChain(*this, Target, Args);
2068 break;
2069 }
2070 break;
2071 default:
2072 // TCE is an OSless target
2073 if (Target.getArchName() == "tce") {
2074 TC = new toolchains::TCEToolChain(*this, Target, Args);
2075 break;
2076 }
2077 // If Hexagon is configured as an OSless target
2078 if (Target.getArch() == llvm::Triple::hexagon) {
2079 TC = new toolchains::Hexagon_TC(*this, Target, Args);
2080 break;
2081 }
2082 if (Target.getArch() == llvm::Triple::xcore) {
2083 TC = new toolchains::XCore(*this, Target, Args);
2084 break;
2085 }
2086 if (Target.isOSBinFormatELF()) {
2087 TC = new toolchains::Generic_ELF(*this, Target, Args);
2088 break;
2089 }
2090 if (Target.isOSBinFormatMachO()) {
2091 TC = new toolchains::MachO(*this, Target, Args);
2092 break;
2093 }
2094 TC = new toolchains::Generic_GCC(*this, Target, Args);
2095 break;
2096 }
2097 }
2098 return *TC;
2099 }
2100
ShouldUseClangCompiler(const JobAction & JA) const2101 bool Driver::ShouldUseClangCompiler(const JobAction &JA) const {
2102 // Check if user requested no clang, or clang doesn't understand this type (we
2103 // only handle single inputs for now).
2104 if (JA.size() != 1 ||
2105 !types::isAcceptedByClang((*JA.begin())->getType()))
2106 return false;
2107
2108 // Otherwise make sure this is an action clang understands.
2109 if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) &&
2110 !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
2111 return false;
2112
2113 return true;
2114 }
2115
2116 /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
2117 /// grouped values as integers. Numbers which are not provided are set to 0.
2118 ///
2119 /// \return True if the entire string was parsed (9.2), or all groups were
2120 /// parsed (10.3.5extrastuff).
GetReleaseVersion(const char * Str,unsigned & Major,unsigned & Minor,unsigned & Micro,bool & HadExtra)2121 bool Driver::GetReleaseVersion(const char *Str, unsigned &Major,
2122 unsigned &Minor, unsigned &Micro,
2123 bool &HadExtra) {
2124 HadExtra = false;
2125
2126 Major = Minor = Micro = 0;
2127 if (*Str == '\0')
2128 return true;
2129
2130 char *End;
2131 Major = (unsigned) strtol(Str, &End, 10);
2132 if (*Str != '\0' && *End == '\0')
2133 return true;
2134 if (*End != '.')
2135 return false;
2136
2137 Str = End+1;
2138 Minor = (unsigned) strtol(Str, &End, 10);
2139 if (*Str != '\0' && *End == '\0')
2140 return true;
2141 if (*End != '.')
2142 return false;
2143
2144 Str = End+1;
2145 Micro = (unsigned) strtol(Str, &End, 10);
2146 if (*Str != '\0' && *End == '\0')
2147 return true;
2148 if (Str == End)
2149 return false;
2150 HadExtra = true;
2151 return true;
2152 }
2153
getIncludeExcludeOptionFlagMasks() const2154 std::pair<unsigned, unsigned> Driver::getIncludeExcludeOptionFlagMasks() const {
2155 unsigned IncludedFlagsBitmask = 0;
2156 unsigned ExcludedFlagsBitmask = options::NoDriverOption;
2157
2158 if (Mode == CLMode) {
2159 // Include CL and Core options.
2160 IncludedFlagsBitmask |= options::CLOption;
2161 IncludedFlagsBitmask |= options::CoreOption;
2162 } else {
2163 ExcludedFlagsBitmask |= options::CLOption;
2164 }
2165
2166 return std::make_pair(IncludedFlagsBitmask, ExcludedFlagsBitmask);
2167 }
2168
isOptimizationLevelFast(const llvm::opt::ArgList & Args)2169 bool clang::driver::isOptimizationLevelFast(const llvm::opt::ArgList &Args) {
2170 return Args.hasFlag(options::OPT_Ofast, options::OPT_O_Group, false);
2171 }
2172