Bug Summary

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