Bug Summary

File:clang/lib/Driver/Driver.cpp
Warning:line 3460, column 5
Undefined or garbage value returned to caller

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -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 -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -fhalf-no-semantic-interposition -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/build-llvm/tools/clang/lib/Driver -resource-dir /usr/lib/llvm-13/lib/clang/13.0.0 -D CLANG_ROUND_TRIP_CC1_ARGS=ON -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/build-llvm/tools/clang/lib/Driver -I /build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Driver -I /build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/include -I /build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/build-llvm/include -I /build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/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/c++/6.3.0/backward -internal-isystem /usr/lib/llvm-13/lib/clang/13.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../x86_64-linux-gnu/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++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/build-llvm/tools/clang/lib/Driver -fdebug-prefix-map=/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2021-04-14-063029-18377-1 -x c++ /build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Driver/Driver.cpp

/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Driver/Driver.cpp

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

/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/ADT/SmallVector.h

1//===- llvm/ADT/SmallVector.h - 'Normally small' vectors --------*- C++ -*-===//
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// This file defines the SmallVector class.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_ADT_SMALLVECTOR_H
14#define LLVM_ADT_SMALLVECTOR_H
15
16#include "llvm/ADT/iterator_range.h"
17#include "llvm/Support/Compiler.h"
18#include "llvm/Support/ErrorHandling.h"
19#include "llvm/Support/MathExtras.h"
20#include "llvm/Support/MemAlloc.h"
21#include "llvm/Support/type_traits.h"
22#include <algorithm>
23#include <cassert>
24#include <cstddef>
25#include <cstdlib>
26#include <cstring>
27#include <initializer_list>
28#include <iterator>
29#include <limits>
30#include <memory>
31#include <new>
32#include <type_traits>
33#include <utility>
34
35namespace llvm {
36
37/// This is all the stuff common to all SmallVectors.
38///
39/// The template parameter specifies the type which should be used to hold the
40/// Size and Capacity of the SmallVector, so it can be adjusted.
41/// Using 32 bit size is desirable to shrink the size of the SmallVector.
42/// Using 64 bit size is desirable for cases like SmallVector<char>, where a
43/// 32 bit size would limit the vector to ~4GB. SmallVectors are used for
44/// buffering bitcode output - which can exceed 4GB.
45template <class Size_T> class SmallVectorBase {
46protected:
47 void *BeginX;
48 Size_T Size = 0, Capacity;
49
50 /// The maximum value of the Size_T used.
51 static constexpr size_t SizeTypeMax() {
52 return std::numeric_limits<Size_T>::max();
53 }
54
55 SmallVectorBase() = delete;
56 SmallVectorBase(void *FirstEl, size_t TotalCapacity)
57 : BeginX(FirstEl), Capacity(TotalCapacity) {}
58
59 /// This is a helper for \a grow() that's out of line to reduce code
60 /// duplication. This function will report a fatal error if it can't grow at
61 /// least to \p MinSize.
62 void *mallocForGrow(size_t MinSize, size_t TSize, size_t &NewCapacity);
63
64 /// This is an implementation of the grow() method which only works
65 /// on POD-like data types and is out of line to reduce code duplication.
66 /// This function will report a fatal error if it cannot increase capacity.
67 void grow_pod(void *FirstEl, size_t MinSize, size_t TSize);
68
69public:
70 size_t size() const { return Size; }
71 size_t capacity() const { return Capacity; }
72
73 LLVM_NODISCARD[[clang::warn_unused_result]] bool empty() const { return !Size; }
15
Assuming field 'Size' is not equal to 0, which participates in a condition later
16
Returning zero, which participates in a condition later
74
75 /// Set the array size to \p N, which the current array must have enough
76 /// capacity for.
77 ///
78 /// This does not construct or destroy any elements in the vector.
79 ///
80 /// Clients can use this in conjunction with capacity() to write past the end
81 /// of the buffer when they know that more elements are available, and only
82 /// update the size later. This avoids the cost of value initializing elements
83 /// which will only be overwritten.
84 void set_size(size_t N) {
85 assert(N <= capacity())((N <= capacity()) ? static_cast<void> (0) : __assert_fail
("N <= capacity()", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/ADT/SmallVector.h"
, 85, __PRETTY_FUNCTION__))
;
86 Size = N;
87 }
88};
89
90template <class T>
91using SmallVectorSizeType =
92 typename std::conditional<sizeof(T) < 4 && sizeof(void *) >= 8, uint64_t,
93 uint32_t>::type;
94
95/// Figure out the offset of the first element.
96template <class T, typename = void> struct SmallVectorAlignmentAndSize {
97 alignas(SmallVectorBase<SmallVectorSizeType<T>>) char Base[sizeof(
98 SmallVectorBase<SmallVectorSizeType<T>>)];
99 alignas(T) char FirstEl[sizeof(T)];
100};
101
102/// This is the part of SmallVectorTemplateBase which does not depend on whether
103/// the type T is a POD. The extra dummy template argument is used by ArrayRef
104/// to avoid unnecessarily requiring T to be complete.
105template <typename T, typename = void>
106class SmallVectorTemplateCommon
107 : public SmallVectorBase<SmallVectorSizeType<T>> {
108 using Base = SmallVectorBase<SmallVectorSizeType<T>>;
109
110 /// Find the address of the first element. For this pointer math to be valid
111 /// with small-size of 0 for T with lots of alignment, it's important that
112 /// SmallVectorStorage is properly-aligned even for small-size of 0.
113 void *getFirstEl() const {
114 return const_cast<void *>(reinterpret_cast<const void *>(
115 reinterpret_cast<const char *>(this) +
116 offsetof(SmallVectorAlignmentAndSize<T>, FirstEl)__builtin_offsetof(SmallVectorAlignmentAndSize<T>, FirstEl
)
));
117 }
118 // Space after 'FirstEl' is clobbered, do not add any instance vars after it.
119
120protected:
121 SmallVectorTemplateCommon(size_t Size) : Base(getFirstEl(), Size) {}
122
123 void grow_pod(size_t MinSize, size_t TSize) {
124 Base::grow_pod(getFirstEl(), MinSize, TSize);
125 }
126
127 /// Return true if this is a smallvector which has not had dynamic
128 /// memory allocated for it.
129 bool isSmall() const { return this->BeginX == getFirstEl(); }
130
131 /// Put this vector in a state of being small.
132 void resetToSmall() {
133 this->BeginX = getFirstEl();
134 this->Size = this->Capacity = 0; // FIXME: Setting Capacity to 0 is suspect.
135 }
136
137 /// Return true if V is an internal reference to the given range.
138 bool isReferenceToRange(const void *V, const void *First, const void *Last) const {
139 // Use std::less to avoid UB.
140 std::less<> LessThan;
141 return !LessThan(V, First) && LessThan(V, Last);
142 }
143
144 /// Return true if V is an internal reference to this vector.
145 bool isReferenceToStorage(const void *V) const {
146 return isReferenceToRange(V, this->begin(), this->end());
147 }
148
149 /// Return true if First and Last form a valid (possibly empty) range in this
150 /// vector's storage.
151 bool isRangeInStorage(const void *First, const void *Last) const {
152 // Use std::less to avoid UB.
153 std::less<> LessThan;
154 return !LessThan(First, this->begin()) && !LessThan(Last, First) &&
155 !LessThan(this->end(), Last);
156 }
157
158 /// Return true unless Elt will be invalidated by resizing the vector to
159 /// NewSize.
160 bool isSafeToReferenceAfterResize(const void *Elt, size_t NewSize) {
161 // Past the end.
162 if (LLVM_LIKELY(!isReferenceToStorage(Elt))__builtin_expect((bool)(!isReferenceToStorage(Elt)), true))
163 return true;
164
165 // Return false if Elt will be destroyed by shrinking.
166 if (NewSize <= this->size())
167 return Elt < this->begin() + NewSize;
168
169 // Return false if we need to grow.
170 return NewSize <= this->capacity();
171 }
172
173 /// Check whether Elt will be invalidated by resizing the vector to NewSize.
174 void assertSafeToReferenceAfterResize(const void *Elt, size_t NewSize) {
175 assert(isSafeToReferenceAfterResize(Elt, NewSize) &&((isSafeToReferenceAfterResize(Elt, NewSize) && "Attempting to reference an element of the vector in an operation "
"that invalidates it") ? static_cast<void> (0) : __assert_fail
("isSafeToReferenceAfterResize(Elt, NewSize) && \"Attempting to reference an element of the vector in an operation \" \"that invalidates it\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/ADT/SmallVector.h"
, 177, __PRETTY_FUNCTION__))
176 "Attempting to reference an element of the vector in an operation "((isSafeToReferenceAfterResize(Elt, NewSize) && "Attempting to reference an element of the vector in an operation "
"that invalidates it") ? static_cast<void> (0) : __assert_fail
("isSafeToReferenceAfterResize(Elt, NewSize) && \"Attempting to reference an element of the vector in an operation \" \"that invalidates it\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/ADT/SmallVector.h"
, 177, __PRETTY_FUNCTION__))
177 "that invalidates it")((isSafeToReferenceAfterResize(Elt, NewSize) && "Attempting to reference an element of the vector in an operation "
"that invalidates it") ? static_cast<void> (0) : __assert_fail
("isSafeToReferenceAfterResize(Elt, NewSize) && \"Attempting to reference an element of the vector in an operation \" \"that invalidates it\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/ADT/SmallVector.h"
, 177, __PRETTY_FUNCTION__))
;
178 }
179
180 /// Check whether Elt will be invalidated by increasing the size of the
181 /// vector by N.
182 void assertSafeToAdd(const void *Elt, size_t N = 1) {
183 this->assertSafeToReferenceAfterResize(Elt, this->size() + N);
184 }
185
186 /// Check whether any part of the range will be invalidated by clearing.
187 void assertSafeToReferenceAfterClear(const T *From, const T *To) {
188 if (From == To)
189 return;
190 this->assertSafeToReferenceAfterResize(From, 0);
191 this->assertSafeToReferenceAfterResize(To - 1, 0);
192 }
193 template <
194 class ItTy,
195 std::enable_if_t<!std::is_same<std::remove_const_t<ItTy>, T *>::value,
196 bool> = false>
197 void assertSafeToReferenceAfterClear(ItTy, ItTy) {}
198
199 /// Check whether any part of the range will be invalidated by growing.
200 void assertSafeToAddRange(const T *From, const T *To) {
201 if (From == To)
202 return;
203 this->assertSafeToAdd(From, To - From);
204 this->assertSafeToAdd(To - 1, To - From);
205 }
206 template <
207 class ItTy,
208 std::enable_if_t<!std::is_same<std::remove_const_t<ItTy>, T *>::value,
209 bool> = false>
210 void assertSafeToAddRange(ItTy, ItTy) {}
211
212 /// Reserve enough space to add one element, and return the updated element
213 /// pointer in case it was a reference to the storage.
214 template <class U>
215 static const T *reserveForParamAndGetAddressImpl(U *This, const T &Elt,
216 size_t N) {
217 size_t NewSize = This->size() + N;
218 if (LLVM_LIKELY(NewSize <= This->capacity())__builtin_expect((bool)(NewSize <= This->capacity()), true
)
)
219 return &Elt;
220
221 bool ReferencesStorage = false;
222 int64_t Index = -1;
223 if (!U::TakesParamByValue) {
224 if (LLVM_UNLIKELY(This->isReferenceToStorage(&Elt))__builtin_expect((bool)(This->isReferenceToStorage(&Elt
)), false)
) {
225 ReferencesStorage = true;
226 Index = &Elt - This->begin();
227 }
228 }
229 This->grow(NewSize);
230 return ReferencesStorage ? This->begin() + Index : &Elt;
231 }
232
233public:
234 using size_type = size_t;
235 using difference_type = ptrdiff_t;
236 using value_type = T;
237 using iterator = T *;
238 using const_iterator = const T *;
239
240 using const_reverse_iterator = std::reverse_iterator<const_iterator>;
241 using reverse_iterator = std::reverse_iterator<iterator>;
242
243 using reference = T &;
244 using const_reference = const T &;
245 using pointer = T *;
246 using const_pointer = const T *;
247
248 using Base::capacity;
249 using Base::empty;
250 using Base::size;
251
252 // forward iterator creation methods.
253 iterator begin() { return (iterator)this->BeginX; }
254 const_iterator begin() const { return (const_iterator)this->BeginX; }
255 iterator end() { return begin() + size(); }
256 const_iterator end() const { return begin() + size(); }
257
258 // reverse iterator creation methods.
259 reverse_iterator rbegin() { return reverse_iterator(end()); }
260 const_reverse_iterator rbegin() const{ return const_reverse_iterator(end()); }
261 reverse_iterator rend() { return reverse_iterator(begin()); }
262 const_reverse_iterator rend() const { return const_reverse_iterator(begin());}
263
264 size_type size_in_bytes() const { return size() * sizeof(T); }
265 size_type max_size() const {
266 return std::min(this->SizeTypeMax(), size_type(-1) / sizeof(T));
267 }
268
269 size_t capacity_in_bytes() const { return capacity() * sizeof(T); }
270
271 /// Return a pointer to the vector's buffer, even if empty().
272 pointer data() { return pointer(begin()); }
273 /// Return a pointer to the vector's buffer, even if empty().
274 const_pointer data() const { return const_pointer(begin()); }
275
276 reference operator[](size_type idx) {
277 assert(idx < size())((idx < size()) ? static_cast<void> (0) : __assert_fail
("idx < size()", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/ADT/SmallVector.h"
, 277, __PRETTY_FUNCTION__))
;
278 return begin()[idx];
279 }
280 const_reference operator[](size_type idx) const {
281 assert(idx < size())((idx < size()) ? static_cast<void> (0) : __assert_fail
("idx < size()", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/ADT/SmallVector.h"
, 281, __PRETTY_FUNCTION__))
;
282 return begin()[idx];
283 }
284
285 reference front() {
286 assert(!empty())((!empty()) ? static_cast<void> (0) : __assert_fail ("!empty()"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/ADT/SmallVector.h"
, 286, __PRETTY_FUNCTION__))
;
287 return begin()[0];
288 }
289 const_reference front() const {
290 assert(!empty())((!empty()) ? static_cast<void> (0) : __assert_fail ("!empty()"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/ADT/SmallVector.h"
, 290, __PRETTY_FUNCTION__))
;
291 return begin()[0];
292 }
293
294 reference back() {
295 assert(!empty())((!empty()) ? static_cast<void> (0) : __assert_fail ("!empty()"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/ADT/SmallVector.h"
, 295, __PRETTY_FUNCTION__))
;
296 return end()[-1];
297 }
298 const_reference back() const {
299 assert(!empty())((!empty()) ? static_cast<void> (0) : __assert_fail ("!empty()"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/ADT/SmallVector.h"
, 299, __PRETTY_FUNCTION__))
;
300 return end()[-1];
301 }
302};
303
304/// SmallVectorTemplateBase<TriviallyCopyable = false> - This is where we put
305/// method implementations that are designed to work with non-trivial T's.
306///
307/// We approximate is_trivially_copyable with trivial move/copy construction and
308/// trivial destruction. While the standard doesn't specify that you're allowed
309/// copy these types with memcpy, there is no way for the type to observe this.
310/// This catches the important case of std::pair<POD, POD>, which is not
311/// trivially assignable.
312template <typename T, bool = (is_trivially_copy_constructible<T>::value) &&
313 (is_trivially_move_constructible<T>::value) &&
314 std::is_trivially_destructible<T>::value>
315class SmallVectorTemplateBase : public SmallVectorTemplateCommon<T> {
316 friend class SmallVectorTemplateCommon<T>;
317
318protected:
319 static constexpr bool TakesParamByValue = false;
320 using ValueParamT = const T &;
321
322 SmallVectorTemplateBase(size_t Size) : SmallVectorTemplateCommon<T>(Size) {}
323
324 static void destroy_range(T *S, T *E) {
325 while (S != E) {
326 --E;
327 E->~T();
328 }
329 }
330
331 /// Move the range [I, E) into the uninitialized memory starting with "Dest",
332 /// constructing elements as needed.
333 template<typename It1, typename It2>
334 static void uninitialized_move(It1 I, It1 E, It2 Dest) {
335 std::uninitialized_copy(std::make_move_iterator(I),
336 std::make_move_iterator(E), Dest);
337 }
338
339 /// Copy the range [I, E) onto the uninitialized memory starting with "Dest",
340 /// constructing elements as needed.
341 template<typename It1, typename It2>
342 static void uninitialized_copy(It1 I, It1 E, It2 Dest) {
343 std::uninitialized_copy(I, E, Dest);
344 }
345
346 /// Grow the allocated memory (without initializing new elements), doubling
347 /// the size of the allocated memory. Guarantees space for at least one more
348 /// element, or MinSize more elements if specified.
349 void grow(size_t MinSize = 0);
350
351 /// Create a new allocation big enough for \p MinSize and pass back its size
352 /// in \p NewCapacity. This is the first section of \a grow().
353 T *mallocForGrow(size_t MinSize, size_t &NewCapacity) {
354 return static_cast<T *>(
355 SmallVectorBase<SmallVectorSizeType<T>>::mallocForGrow(
356 MinSize, sizeof(T), NewCapacity));
357 }
358
359 /// Move existing elements over to the new allocation \p NewElts, the middle
360 /// section of \a grow().
361 void moveElementsForGrow(T *NewElts);
362
363 /// Transfer ownership of the allocation, finishing up \a grow().
364 void takeAllocationForGrow(T *NewElts, size_t NewCapacity);
365
366 /// Reserve enough space to add one element, and return the updated element
367 /// pointer in case it was a reference to the storage.
368 const T *reserveForParamAndGetAddress(const T &Elt, size_t N = 1) {
369 return this->reserveForParamAndGetAddressImpl(this, Elt, N);
370 }
371
372 /// Reserve enough space to add one element, and return the updated element
373 /// pointer in case it was a reference to the storage.
374 T *reserveForParamAndGetAddress(T &Elt, size_t N = 1) {
375 return const_cast<T *>(
376 this->reserveForParamAndGetAddressImpl(this, Elt, N));
377 }
378
379 static T &&forward_value_param(T &&V) { return std::move(V); }
380 static const T &forward_value_param(const T &V) { return V; }
381
382 void growAndAssign(size_t NumElts, const T &Elt) {
383 // Grow manually in case Elt is an internal reference.
384 size_t NewCapacity;
385 T *NewElts = mallocForGrow(NumElts, NewCapacity);
386 std::uninitialized_fill_n(NewElts, NumElts, Elt);
387 this->destroy_range(this->begin(), this->end());
388 takeAllocationForGrow(NewElts, NewCapacity);
389 this->set_size(NumElts);
390 }
391
392 template <typename... ArgTypes> T &growAndEmplaceBack(ArgTypes &&... Args) {
393 // Grow manually in case one of Args is an internal reference.
394 size_t NewCapacity;
395 T *NewElts = mallocForGrow(0, NewCapacity);
396 ::new ((void *)(NewElts + this->size())) T(std::forward<ArgTypes>(Args)...);
397 moveElementsForGrow(NewElts);
398 takeAllocationForGrow(NewElts, NewCapacity);
399 this->set_size(this->size() + 1);
400 return this->back();
401 }
402
403public:
404 void push_back(const T &Elt) {
405 const T *EltPtr = reserveForParamAndGetAddress(Elt);
406 ::new ((void *)this->end()) T(*EltPtr);
407 this->set_size(this->size() + 1);
408 }
409
410 void push_back(T &&Elt) {
411 T *EltPtr = reserveForParamAndGetAddress(Elt);
412 ::new ((void *)this->end()) T(::std::move(*EltPtr));
413 this->set_size(this->size() + 1);
414 }
415
416 void pop_back() {
417 this->set_size(this->size() - 1);
418 this->end()->~T();
419 }
420};
421
422// Define this out-of-line to dissuade the C++ compiler from inlining it.
423template <typename T, bool TriviallyCopyable>
424void SmallVectorTemplateBase<T, TriviallyCopyable>::grow(size_t MinSize) {
425 size_t NewCapacity;
426 T *NewElts = mallocForGrow(MinSize, NewCapacity);
427 moveElementsForGrow(NewElts);
428 takeAllocationForGrow(NewElts, NewCapacity);
429}
430
431// Define this out-of-line to dissuade the C++ compiler from inlining it.
432template <typename T, bool TriviallyCopyable>