Bug Summary

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