Bug Summary

File:tools/clang/lib/Driver/Driver.cpp
Warning:line 1808, column 17
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

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