clang 23.0.0git
Darwin.cpp
Go to the documentation of this file.
1//===--- Darwin.cpp - Darwin Tool and ToolChain Implementations -*- 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#include "Darwin.h"
10#include "Arch/ARM.h"
13#include "clang/Config/config.h"
16#include "clang/Driver/Driver.h"
19#include "llvm/ADT/StringSwitch.h"
20#include "llvm/Option/ArgList.h"
21#include "llvm/ProfileData/InstrProf.h"
22#include "llvm/ProfileData/MemProf.h"
23#include "llvm/Support/Path.h"
24#include "llvm/Support/Threading.h"
25#include "llvm/Support/VirtualFileSystem.h"
26#include "llvm/TargetParser/TargetParser.h"
27#include "llvm/TargetParser/Triple.h"
28#include <cstdlib> // ::getenv
29
30#ifdef CLANG_USE_XCSELECT
31#include <xcselect.h> // ::xcselect_host_sdk_path
32#endif
33
34using namespace clang::driver;
35using namespace clang::driver::tools;
36using namespace clang::driver::toolchains;
37using namespace clang;
38using namespace llvm::opt;
39
41 return VersionTuple(13, 1);
42}
43
44llvm::Triple::ArchType darwin::getArchTypeForMachOArchName(StringRef Str) {
45 // See arch(3) and llvm-gcc's driver-driver.c. We don't implement support for
46 // archs which Darwin doesn't use.
47
48 // The matching this routine does is fairly pointless, since it is neither the
49 // complete architecture list, nor a reasonable subset. The problem is that
50 // historically the driver accepts this and also ties its -march=
51 // handling to the architecture name, so we need to be careful before removing
52 // support for it.
53
54 // This code must be kept in sync with Clang's Darwin specific argument
55 // translation.
56
57 return llvm::StringSwitch<llvm::Triple::ArchType>(Str)
58 .Cases({"i386", "i486", "i486SX", "i586", "i686"}, llvm::Triple::x86)
59 .Cases({"pentium", "pentpro", "pentIIm3", "pentIIm5", "pentium4"},
60 llvm::Triple::x86)
61 .Cases({"x86_64", "x86_64h"}, llvm::Triple::x86_64)
62 // This is derived from the driver.
63 .Cases({"arm", "armv4t", "armv5", "armv6", "armv6m"}, llvm::Triple::arm)
64 .Cases({"armv7", "armv7em", "armv7k", "armv7m"}, llvm::Triple::arm)
65 .Cases({"armv7s", "xscale"}, llvm::Triple::arm)
66 .Cases({"armv8m.base", "armv8m.main", "armv8.1m.main"}, llvm::Triple::arm)
67 .Cases({"arm64", "arm64e"}, llvm::Triple::aarch64)
68 .Case("arm64_32", llvm::Triple::aarch64_32)
69 .Case("r600", llvm::Triple::r600)
70 .Case("amdgcn", llvm::Triple::amdgcn)
71 .Case("nvptx", llvm::Triple::nvptx)
72 .Case("nvptx64", llvm::Triple::nvptx64)
73 .Case("amdil", llvm::Triple::amdil)
74 .Case("spir", llvm::Triple::spir)
75 .Default(llvm::Triple::UnknownArch);
76}
77
78void darwin::setTripleTypeForMachOArchName(llvm::Triple &T, StringRef Str,
79 const ArgList &Args) {
80 const llvm::Triple::ArchType Arch = getArchTypeForMachOArchName(Str);
81 llvm::ARM::ArchKind ArchKind = llvm::ARM::parseArch(Str);
82 T.setArch(Arch);
83 if (Arch != llvm::Triple::UnknownArch)
84 T.setArchName(Str);
85
86 // Standalone/bare metal compiles often unintentionally come out as
87 // armv6m-apple-ios (-target not specified, or set from Xcode). Change these
88 // cases to armv6m-apple-unknown-macho to better reflect intent.
89 if ((T.getOS() != llvm::Triple::Firmware) &&
90 (ArchKind == llvm::ARM::ArchKind::ARMV6M ||
91 ArchKind == llvm::ARM::ArchKind::ARMV7M ||
92 ArchKind == llvm::ARM::ArchKind::ARMV7EM ||
93 ArchKind == llvm::ARM::ArchKind::ARMV8MBaseline ||
94 ArchKind == llvm::ARM::ArchKind::ARMV8MMainline ||
95 ArchKind == llvm::ARM::ArchKind::ARMV8_1MMainline)) {
96 // Don't reject these -version-min= if we have the appropriate triple.
97 if (T.getOS() == llvm::Triple::IOS)
98 for (Arg *A : Args.filtered(options::OPT_mios_version_min_EQ))
99 A->ignoreTargetSpecific();
100 if (T.getOS() == llvm::Triple::WatchOS)
101 for (Arg *A : Args.filtered(options::OPT_mwatchos_version_min_EQ))
102 A->ignoreTargetSpecific();
103 if (T.getOS() == llvm::Triple::TvOS)
104 for (Arg *A : Args.filtered(options::OPT_mtvos_version_min_EQ))
105 A->ignoreTargetSpecific();
106
107 T.setOS(llvm::Triple::UnknownOS);
108 T.setObjectFormat(llvm::Triple::MachO);
109 }
110}
111
113 const InputInfo &Output,
114 const InputInfoList &Inputs,
115 const ArgList &Args,
116 const char *LinkingOutput) const {
117 const llvm::Triple &T(getToolChain().getTriple());
118
119 ArgStringList CmdArgs;
120
121 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
122 const InputInfo &Input = Inputs[0];
123
124 // Determine the original source input.
125 const Action *SourceAction = &JA;
126 while (SourceAction->getKind() != Action::InputClass) {
127 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
128 SourceAction = SourceAction->getInputs()[0];
129 }
130
131 // If -fno-integrated-as is used add -Q to the darwin assembler driver to make
132 // sure it runs its system assembler not clang's integrated assembler.
133 // Applicable to darwin11+ and Xcode 4+. darwin<10 lacked integrated-as.
134 // FIXME: at run-time detect assembler capabilities or rely on version
135 // information forwarded by -target-assembler-version.
136 if (Args.hasArg(options::OPT_fno_integrated_as)) {
137 if (!(T.isMacOSX() && T.isMacOSXVersionLT(10, 7)))
138 CmdArgs.push_back("-Q");
139 }
140
141 // Forward -g, assuming we are dealing with an actual assembly file.
142 if (SourceAction->getType() == types::TY_Asm ||
143 SourceAction->getType() == types::TY_PP_Asm) {
144 if (Args.hasArg(options::OPT_gstabs))
145 CmdArgs.push_back("--gstabs");
146 else if (Args.hasArg(options::OPT_g_Group))
147 CmdArgs.push_back("-g");
148 }
149
150 // Derived from asm spec.
151 AddMachOArch(Args, CmdArgs);
152
153 // Use -force_cpusubtype_ALL on x86 by default.
154 if (T.isX86() || Args.hasArg(options::OPT_force__cpusubtype__ALL))
155 CmdArgs.push_back("-force_cpusubtype_ALL");
156
157 if (getToolChain().getArch() != llvm::Triple::x86_64 &&
158 (((Args.hasArg(options::OPT_mkernel) ||
159 Args.hasArg(options::OPT_fapple_kext)) &&
160 getMachOToolChain().isKernelStatic()) ||
161 Args.hasArg(options::OPT_static)))
162 CmdArgs.push_back("-static");
163
164 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
165
166 assert(Output.isFilename() && "Unexpected lipo output.");
167 CmdArgs.push_back("-o");
168 CmdArgs.push_back(Output.getFilename());
169
170 assert(Input.isFilename() && "Invalid input.");
171 CmdArgs.push_back(Input.getFilename());
172
173 // asm_final spec is empty.
174
175 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
176 C.addCommand(std::make_unique<Command>(JA, *this, ResponseFileSupport::None(),
177 Exec, CmdArgs, Inputs, Output));
178}
179
180void darwin::MachOTool::anchor() {}
181
182void darwin::MachOTool::AddMachOArch(const ArgList &Args,
183 ArgStringList &CmdArgs) const {
184 StringRef ArchName = getMachOToolChain().getMachOArchName(Args);
185
186 // Derived from darwin_arch spec.
187 CmdArgs.push_back("-arch");
188 CmdArgs.push_back(Args.MakeArgString(ArchName));
189
190 // FIXME: Is this needed anymore?
191 if (ArchName == "arm")
192 CmdArgs.push_back("-force_cpusubtype_ALL");
193}
194
195bool darwin::Linker::NeedsTempPath(const InputInfoList &Inputs) const {
196 // We only need to generate a temp path for LTO if we aren't compiling object
197 // files. When compiling source files, we run 'dsymutil' after linking. We
198 // don't run 'dsymutil' when compiling object files.
199 for (const auto &Input : Inputs)
200 if (Input.getType() != types::TY_Object)
201 return true;
202
203 return false;
204}
205
206/// Pass -no_deduplicate to ld64 under certain conditions:
207///
208/// - Either -O0 or -O1 is explicitly specified
209/// - No -O option is specified *and* this is a compile+link (implicit -O0)
210///
211/// Also do *not* add -no_deduplicate when no -O option is specified and this
212/// is just a link (we can't imply -O0)
213static bool shouldLinkerNotDedup(bool IsLinkerOnlyAction, const ArgList &Args) {
214 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
215 if (A->getOption().matches(options::OPT_O0))
216 return true;
217 if (A->getOption().matches(options::OPT_O))
218 return llvm::StringSwitch<bool>(A->getValue())
219 .Case("1", true)
220 .Default(false);
221 return false; // OPT_Ofast & OPT_O4
222 }
223
224 if (!IsLinkerOnlyAction) // Implicit -O0 for compile+linker only.
225 return true;
226 return false;
227}
228
229void darwin::Linker::AddLinkArgs(Compilation &C, const ArgList &Args,
230 ArgStringList &CmdArgs,
231 const InputInfoList &Inputs,
232 VersionTuple Version, bool LinkerIsLLD,
233 bool UsePlatformVersion) const {
234 const Driver &D = getToolChain().getDriver();
235 const toolchains::MachO &MachOTC = getMachOToolChain();
236
237 // Newer linkers support -demangle. Pass it if supported and not disabled by
238 // the user.
239 if ((Version >= VersionTuple(100) || LinkerIsLLD) &&
240 !Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
241 CmdArgs.push_back("-demangle");
242
243 if (Args.hasArg(options::OPT_rdynamic) &&
244 (Version >= VersionTuple(137) || LinkerIsLLD))
245 CmdArgs.push_back("-export_dynamic");
246
247 // If we are using App Extension restrictions, pass a flag to the linker
248 // telling it that the compiled code has been audited.
249 if (Args.hasFlag(options::OPT_fapplication_extension,
250 options::OPT_fno_application_extension, false))
251 CmdArgs.push_back("-application_extension");
252
253 if (auto LTO = getToolChain().getLTOMode(Args);
254 LTO != LTOK_None && (Version >= VersionTuple(116) || LinkerIsLLD) &&
255 NeedsTempPath(Inputs)) {
256 std::string TmpPathName;
257 if (LTO == LTOK_Full) {
258 // If we are using full LTO, then automatically create a temporary file
259 // path for the linker to use, so that it's lifetime will extend past a
260 // possible dsymutil step.
261 TmpPathName =
262 D.GetTemporaryPath("cc", types::getTypeTempSuffix(types::TY_Object));
263 } else if (LTO == LTOK_Thin)
264 // If we are using thin LTO, then create a directory instead.
265 TmpPathName = D.GetTemporaryDirectory("thinlto");
266
267 if (!TmpPathName.empty()) {
268 auto *TmpPath = C.getArgs().MakeArgString(TmpPathName);
269 C.addTempFile(TmpPath);
270 CmdArgs.push_back("-object_path_lto");
271 CmdArgs.push_back(TmpPath);
272 }
273 }
274
275 // Use -lto_library option to specify the libLTO.dylib path. Try to find
276 // it in clang installed libraries. ld64 will only look at this argument
277 // when it actually uses LTO, so libLTO.dylib only needs to exist at link
278 // time if ld64 decides that it needs to use LTO.
279 // Since this is passed unconditionally, ld64 will never look for libLTO.dylib
280 // next to it. That's ok since ld64 using a libLTO.dylib not matching the
281 // clang version won't work anyways.
282 // lld is built at the same revision as clang and statically links in
283 // LLVM libraries, so it doesn't need libLTO.dylib.
284 if (Version >= VersionTuple(133) && !LinkerIsLLD) {
285 // Search for libLTO in <InstalledDir>/../lib/libLTO.dylib
286 StringRef P = llvm::sys::path::parent_path(D.Dir);
287 SmallString<128> LibLTOPath(P);
288 llvm::sys::path::append(LibLTOPath, "lib");
289 llvm::sys::path::append(LibLTOPath, "libLTO.dylib");
290 CmdArgs.push_back("-lto_library");
291 CmdArgs.push_back(C.getArgs().MakeArgString(LibLTOPath));
292 }
293
294 // ld64 version 262 and above runs the deduplicate pass by default.
295 // FIXME: lld doesn't dedup by default. Should we pass `--icf=safe`
296 // if `!shouldLinkerNotDedup()` if LinkerIsLLD here?
297 if (Version >= VersionTuple(262) &&
298 shouldLinkerNotDedup(C.getJobs().empty(), Args))
299 CmdArgs.push_back("-no_deduplicate");
300
301 // Derived from the "link" spec.
302 Args.AddAllArgs(CmdArgs, options::OPT_static);
303 if (!Args.hasArg(options::OPT_static))
304 CmdArgs.push_back("-dynamic");
305 if (Args.hasArg(options::OPT_fgnu_runtime)) {
306 // FIXME: gcc replaces -lobjc in forward args with -lobjc-gnu
307 // here. How do we wish to handle such things?
308 }
309
310 if (!Args.hasArg(options::OPT_dynamiclib)) {
311 AddMachOArch(Args, CmdArgs);
312 // FIXME: Why do this only on this path?
313 Args.AddLastArg(CmdArgs, options::OPT_force__cpusubtype__ALL);
314
315 Args.AddLastArg(CmdArgs, options::OPT_bundle);
316 Args.AddAllArgs(CmdArgs, options::OPT_bundle__loader);
317 Args.AddAllArgs(CmdArgs, options::OPT_client__name);
318
319 Arg *A;
320 if ((A = Args.getLastArg(options::OPT_compatibility__version)) ||
321 (A = Args.getLastArg(options::OPT_current__version)) ||
322 (A = Args.getLastArg(options::OPT_install__name)))
323 D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
324 << "-dynamiclib";
325
326 Args.AddLastArg(CmdArgs, options::OPT_force__flat__namespace);
327 Args.AddLastArg(CmdArgs, options::OPT_keep__private__externs);
328 Args.AddLastArg(CmdArgs, options::OPT_private__bundle);
329 } else {
330 CmdArgs.push_back("-dylib");
331
332 Arg *A;
333 if ((A = Args.getLastArg(options::OPT_bundle)) ||
334 (A = Args.getLastArg(options::OPT_bundle__loader)) ||
335 (A = Args.getLastArg(options::OPT_client__name)) ||
336 (A = Args.getLastArg(options::OPT_force__flat__namespace)) ||
337 (A = Args.getLastArg(options::OPT_keep__private__externs)) ||
338 (A = Args.getLastArg(options::OPT_private__bundle)))
339 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
340 << "-dynamiclib";
341
342 Args.AddAllArgsTranslated(CmdArgs, options::OPT_compatibility__version,
343 "-dylib_compatibility_version");
344 Args.AddAllArgsTranslated(CmdArgs, options::OPT_current__version,
345 "-dylib_current_version");
346
347 AddMachOArch(Args, CmdArgs);
348
349 Args.AddAllArgsTranslated(CmdArgs, options::OPT_install__name,
350 "-dylib_install_name");
351 }
352
353 Args.AddLastArg(CmdArgs, options::OPT_all__load);
354 Args.AddAllArgs(CmdArgs, options::OPT_allowable__client);
355 Args.AddLastArg(CmdArgs, options::OPT_bind__at__load);
356 if (MachOTC.isTargetIOSBased())
357 Args.AddLastArg(CmdArgs, options::OPT_arch__errors__fatal);
358 Args.AddLastArg(CmdArgs, options::OPT_dead__strip);
359 Args.AddLastArg(CmdArgs, options::OPT_no__dead__strip__inits__and__terms);
360 Args.AddAllArgs(CmdArgs, options::OPT_dylib__file);
361 Args.AddLastArg(CmdArgs, options::OPT_dynamic);
362 Args.AddAllArgs(CmdArgs, options::OPT_exported__symbols__list);
363 Args.AddLastArg(CmdArgs, options::OPT_flat__namespace);
364 Args.AddAllArgs(CmdArgs, options::OPT_force__load);
365 Args.AddAllArgs(CmdArgs, options::OPT_headerpad__max__install__names);
366 Args.AddAllArgs(CmdArgs, options::OPT_image__base);
367 Args.AddAllArgs(CmdArgs, options::OPT_init);
368
369 // Add the deployment target.
370 if (Version >= VersionTuple(520) || LinkerIsLLD || UsePlatformVersion)
371 MachOTC.addPlatformVersionArgs(Args, CmdArgs);
372 else
373 MachOTC.addMinVersionArgs(Args, CmdArgs);
374
375 Args.AddLastArg(CmdArgs, options::OPT_nomultidefs);
376 Args.AddLastArg(CmdArgs, options::OPT_multi__module);
377 Args.AddLastArg(CmdArgs, options::OPT_single__module);
378 Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined);
379 Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined__unused);
380
381 if (const Arg *A =
382 Args.getLastArg(options::OPT_fpie, options::OPT_fPIE,
383 options::OPT_fno_pie, options::OPT_fno_PIE)) {
384 if (A->getOption().matches(options::OPT_fpie) ||
385 A->getOption().matches(options::OPT_fPIE))
386 CmdArgs.push_back("-pie");
387 else
388 CmdArgs.push_back("-no_pie");
389 }
390
391 // for embed-bitcode, use -bitcode_bundle in linker command
392 if (C.getDriver().embedBitcodeEnabled()) {
393 // Check if the toolchain supports bitcode build flow.
394 if (MachOTC.SupportsEmbeddedBitcode()) {
395 CmdArgs.push_back("-bitcode_bundle");
396 // FIXME: Pass this if LinkerIsLLD too, once it implements this flag.
397 if (C.getDriver().embedBitcodeMarkerOnly() &&
398 Version >= VersionTuple(278)) {
399 CmdArgs.push_back("-bitcode_process_mode");
400 CmdArgs.push_back("marker");
401 }
402 } else
403 D.Diag(diag::err_drv_bitcode_unsupported_on_toolchain);
404 }
405
406 // If GlobalISel is enabled, pass it through to LLVM.
407 if (Arg *A = Args.getLastArg(options::OPT_fglobal_isel,
408 options::OPT_fno_global_isel)) {
409 if (A->getOption().matches(options::OPT_fglobal_isel)) {
410 CmdArgs.push_back("-mllvm");
411 CmdArgs.push_back("-global-isel");
412 // Disable abort and fall back to SDAG silently.
413 CmdArgs.push_back("-mllvm");
414 CmdArgs.push_back("-global-isel-abort=0");
415 }
416 }
417
418 if (Args.hasArg(options::OPT_mkernel) ||
419 Args.hasArg(options::OPT_fapple_kext) ||
420 Args.hasArg(options::OPT_ffreestanding)) {
421 CmdArgs.push_back("-mllvm");
422 CmdArgs.push_back("-disable-atexit-based-global-dtor-lowering");
423 }
424
425 Args.AddLastArg(CmdArgs, options::OPT_prebind);
426 Args.AddLastArg(CmdArgs, options::OPT_noprebind);
427 Args.AddLastArg(CmdArgs, options::OPT_nofixprebinding);
428 Args.AddLastArg(CmdArgs, options::OPT_prebind__all__twolevel__modules);
429 Args.AddLastArg(CmdArgs, options::OPT_read__only__relocs);
430 Args.AddAllArgs(CmdArgs, options::OPT_sectcreate);
431 Args.AddAllArgs(CmdArgs, options::OPT_sectorder);
432 Args.AddAllArgs(CmdArgs, options::OPT_seg1addr);
433 Args.AddAllArgs(CmdArgs, options::OPT_segprot);
434 Args.AddAllArgs(CmdArgs, options::OPT_segaddr);
435 Args.AddAllArgs(CmdArgs, options::OPT_segs__read__only__addr);
436 Args.AddAllArgs(CmdArgs, options::OPT_segs__read__write__addr);
437 Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table);
438 Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table__filename);
439 Args.AddAllArgs(CmdArgs, options::OPT_sub__library);
440 Args.AddAllArgs(CmdArgs, options::OPT_sub__umbrella);
441
442 // Give --sysroot= preference, over the Apple specific behavior to also use
443 // --isysroot as the syslibroot.
444 // We check `OPT__sysroot_EQ` directly instead of `getSysRoot` to make sure we
445 // prioritise command line arguments over configuration of `DEFAULT_SYSROOT`.
446 if (const Arg *A = Args.getLastArg(options::OPT__sysroot_EQ)) {
447 CmdArgs.push_back("-syslibroot");
448 CmdArgs.push_back(A->getValue());
449 } else if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
450 CmdArgs.push_back("-syslibroot");
451 CmdArgs.push_back(A->getValue());
452 } else if (StringRef sysroot = C.getSysRoot(); sysroot != "") {
453 CmdArgs.push_back("-syslibroot");
454 CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
455 }
456
457 Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace);
458 Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace__hints);
459 Args.AddAllArgs(CmdArgs, options::OPT_umbrella);
460 Args.AddAllArgs(CmdArgs, options::OPT_undefined);
461 Args.AddAllArgs(CmdArgs, options::OPT_unexported__symbols__list);
462 Args.AddAllArgs(CmdArgs, options::OPT_weak__reference__mismatches);
463 Args.AddLastArg(CmdArgs, options::OPT_X_Flag);
464 Args.AddAllArgs(CmdArgs, options::OPT_y);
465 Args.AddLastArg(CmdArgs, options::OPT_w);
466 Args.AddAllArgs(CmdArgs, options::OPT_pagezero__size);
467 Args.AddAllArgs(CmdArgs, options::OPT_segs__read__);
468 Args.AddLastArg(CmdArgs, options::OPT_seglinkedit);
469 Args.AddLastArg(CmdArgs, options::OPT_noseglinkedit);
470 Args.AddAllArgs(CmdArgs, options::OPT_sectalign);
471 Args.AddAllArgs(CmdArgs, options::OPT_sectobjectsymbols);
472 Args.AddAllArgs(CmdArgs, options::OPT_segcreate);
473 Args.AddLastArg(CmdArgs, options::OPT_why_load);
474 Args.AddLastArg(CmdArgs, options::OPT_whatsloaded);
475 Args.AddAllArgs(CmdArgs, options::OPT_dylinker__install__name);
476 Args.AddLastArg(CmdArgs, options::OPT_dylinker);
477 Args.AddLastArg(CmdArgs, options::OPT_Mach);
478
479 if (LinkerIsLLD) {
480 if (auto *CSPGOGenerateArg = getLastCSProfileGenerateArg(Args)) {
481 SmallString<128> Path(CSPGOGenerateArg->getNumValues() == 0
482 ? ""
483 : CSPGOGenerateArg->getValue());
484 llvm::sys::path::append(Path, "default_%m.profraw");
485 CmdArgs.push_back("--cs-profile-generate");
486 CmdArgs.push_back(Args.MakeArgString(Twine("--cs-profile-path=") + Path));
487 } else if (auto *ProfileUseArg = getLastProfileUseArg(Args)) {
488 SmallString<128> Path(
489 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
490 if (Path.empty() || llvm::sys::fs::is_directory(Path))
491 llvm::sys::path::append(Path, "default.profdata");
492 CmdArgs.push_back(Args.MakeArgString(Twine("--cs-profile-path=") + Path));
493 }
494
495 auto *CodeGenDataGenArg =
496 Args.getLastArg(options::OPT_fcodegen_data_generate_EQ);
497 if (CodeGenDataGenArg)
498 CmdArgs.push_back(
499 Args.MakeArgString(Twine("--codegen-data-generate-path=") +
500 CodeGenDataGenArg->getValue()));
501 } else {
502 if (auto *CSPGOGenerateArg = getLastCSProfileGenerateArg(Args)) {
503 SmallString<128> Path(CSPGOGenerateArg->getNumValues() == 0
504 ? ""
505 : CSPGOGenerateArg->getValue());
506 llvm::sys::path::append(Path, "default_%m.profraw");
507 CmdArgs.push_back("-mllvm");
508 CmdArgs.push_back("-cs-profile-generate");
509 CmdArgs.push_back("-mllvm");
510 CmdArgs.push_back(Args.MakeArgString(Twine("-cs-profile-path=") + Path));
511 } else if (auto *ProfileUseArg = getLastProfileUseArg(Args)) {
512 SmallString<128> Path(
513 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
514 if (Path.empty() || llvm::sys::fs::is_directory(Path))
515 llvm::sys::path::append(Path, "default.profdata");
516 CmdArgs.push_back("-mllvm");
517 CmdArgs.push_back(Args.MakeArgString(Twine("-cs-profile-path=") + Path));
518 }
519 }
520
521 if (Arg *A = getLastProfileSampleUseArg(Args)) {
522 CmdArgs.push_back("-mllvm");
523 CmdArgs.push_back(
524 Args.MakeArgString(Twine("-sample-profile-file=") + A->getValue()));
525 }
526}
527
528/// Determine whether we are linking the ObjC runtime.
529static bool isObjCRuntimeLinked(const ArgList &Args) {
530 if (isObjCAutoRefCount(Args)) {
531 Args.ClaimAllArgs(options::OPT_fobjc_link_runtime);
532 return true;
533 }
534 return Args.hasArg(options::OPT_fobjc_link_runtime);
535}
536
537static bool checkRemarksOptions(const Driver &D, const ArgList &Args,
538 const llvm::Triple &Triple) {
539 // When enabling remarks, we need to error if:
540 // * The remark file is specified but we're targeting multiple architectures,
541 // which means more than one remark file is being generated.
543 Args.getAllArgValues(options::OPT_arch).size() > 1;
544 bool hasExplicitOutputFile =
545 Args.getLastArg(options::OPT_foptimization_record_file_EQ);
546 if (hasMultipleInvocations && hasExplicitOutputFile) {
547 D.Diag(diag::err_drv_invalid_output_with_multiple_archs)
548 << "-foptimization-record-file";
549 return false;
550 }
551 return true;
552}
553
554static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs,
555 const llvm::Triple &Triple,
556 const InputInfo &Output, const JobAction &JA) {
557 StringRef Format = "yaml";
558 if (const Arg *A = Args.getLastArg(options::OPT_fsave_optimization_record_EQ))
559 Format = A->getValue();
560
561 CmdArgs.push_back("-mllvm");
562 CmdArgs.push_back("-lto-pass-remarks-output");
563 CmdArgs.push_back("-mllvm");
564
565 const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
566 if (A) {
567 CmdArgs.push_back(A->getValue());
568 } else {
569 assert(Output.isFilename() && "Unexpected ld output.");
571 F = Output.getFilename();
572 F += ".opt.";
573 F += Format;
574
575 CmdArgs.push_back(Args.MakeArgString(F));
576 }
577
578 if (const Arg *A =
579 Args.getLastArg(options::OPT_foptimization_record_passes_EQ)) {
580 CmdArgs.push_back("-mllvm");
581 std::string Passes =
582 std::string("-lto-pass-remarks-filter=") + A->getValue();
583 CmdArgs.push_back(Args.MakeArgString(Passes));
584 }
585
586 if (!Format.empty()) {
587 CmdArgs.push_back("-mllvm");
588 Twine FormatArg = Twine("-lto-pass-remarks-format=") + Format;
589 CmdArgs.push_back(Args.MakeArgString(FormatArg));
590 }
591
592 if (getLastProfileUseArg(Args)) {
593 CmdArgs.push_back("-mllvm");
594 CmdArgs.push_back("-lto-pass-remarks-with-hotness");
595
596 if (const Arg *A =
597 Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
598 CmdArgs.push_back("-mllvm");
599 std::string Opt =
600 std::string("-lto-pass-remarks-hotness-threshold=") + A->getValue();
601 CmdArgs.push_back(Args.MakeArgString(Opt));
602 }
603 }
604}
605
607 const InputInfo &Output,
608 const InputInfoList &Inputs,
609 const ArgList &Args,
610 const char *LinkingOutput) const {
611 assert((Output.getType() == types::TY_Image ||
612 Output.getType() == types::TY_Object) &&
613 "Invalid linker output type.");
614
615 // If the number of arguments surpasses the system limits, we will encode the
616 // input files in a separate file, shortening the command line. To this end,
617 // build a list of input file names that can be passed via a file with the
618 // -filelist linker option.
619 llvm::opt::ArgStringList InputFileList;
620
621 // The logic here is derived from gcc's behavior; most of which
622 // comes from specs (starting with link_command). Consult gcc for
623 // more information.
624 ArgStringList CmdArgs;
625
626 VersionTuple Version = getMachOToolChain().getLinkerVersion(Args);
627
628 bool LinkerIsLLD;
629 const char *Exec =
630 Args.MakeArgString(getToolChain().GetLinkerPath(&LinkerIsLLD));
631
632 // Newer triples always use -platform-version.
633 llvm::Triple Triple = getToolChain().getTriple();
634 bool UsePlatformVersion = Triple.isXROS() || Triple.isOSFirmware();
635
636 // I'm not sure why this particular decomposition exists in gcc, but
637 // we follow suite for ease of comparison.
638 AddLinkArgs(C, Args, CmdArgs, Inputs, Version, LinkerIsLLD,
639 UsePlatformVersion);
640
641 if (willEmitRemarks(Args) &&
642 checkRemarksOptions(getToolChain().getDriver(), Args,
644 renderRemarksOptions(Args, CmdArgs, getToolChain().getTriple(), Output, JA);
645
646 // Propagate the -moutline flag to the linker in LTO.
647 if (Arg *A =
648 Args.getLastArg(options::OPT_moutline, options::OPT_mno_outline)) {
649 if (A->getOption().matches(options::OPT_moutline)) {
650 if (getMachOToolChain().getMachOArchName(Args) == "arm64") {
651 CmdArgs.push_back("-mllvm");
652 CmdArgs.push_back("-enable-machine-outliner");
653 }
654 } else {
655 // Disable all outlining behaviour if we have mno-outline. We need to do
656 // this explicitly, because targets which support default outlining will
657 // try to do work if we don't.
658 CmdArgs.push_back("-mllvm");
659 CmdArgs.push_back("-enable-machine-outliner=never");
660 }
661 }
662
663 // Outline from linkonceodr functions by default in LTO, whenever the outliner
664 // is enabled. Note that the target may enable the machine outliner
665 // independently of -moutline.
666 CmdArgs.push_back("-mllvm");
667 CmdArgs.push_back("-enable-linkonceodr-outlining");
668
669 // Propagate codegen data flags to the linker for the LLVM backend.
670 auto *CodeGenDataGenArg =
671 Args.getLastArg(options::OPT_fcodegen_data_generate_EQ);
672 auto *CodeGenDataUseArg = Args.getLastArg(options::OPT_fcodegen_data_use_EQ);
673
674 // We only allow one of them to be specified.
675 const Driver &D = getToolChain().getDriver();
676 if (CodeGenDataGenArg && CodeGenDataUseArg)
677 D.Diag(diag::err_drv_argument_not_allowed_with)
678 << CodeGenDataGenArg->getAsString(Args)
679 << CodeGenDataUseArg->getAsString(Args);
680
681 // For codegen data gen, the output file is passed to the linker
682 // while a boolean flag is passed to the LLVM backend.
683 if (CodeGenDataGenArg) {
684 CmdArgs.push_back("-mllvm");
685 CmdArgs.push_back("-codegen-data-generate");
686 }
687
688 // For codegen data use, the input file is passed to the LLVM backend.
689 if (CodeGenDataUseArg) {
690 CmdArgs.push_back("-mllvm");
691 CmdArgs.push_back(Args.MakeArgString(Twine("-codegen-data-use-path=") +
692 CodeGenDataUseArg->getValue()));
693 }
694
695 // Setup statistics file output.
696 SmallString<128> StatsFile =
697 getStatsFileName(Args, Output, Inputs[0], getToolChain().getDriver());
698 if (!StatsFile.empty()) {
699 CmdArgs.push_back("-mllvm");
700 CmdArgs.push_back(Args.MakeArgString("-lto-stats-file=" + StatsFile.str()));
701 }
702
703 // Set up stack usage file path.
704 if (Args.hasArg(options::OPT_fstack_usage)) {
705 SmallString<128> StackUsageFile(Output.getFilename());
706 llvm::sys::path::replace_extension(StackUsageFile, "su");
707 CmdArgs.push_back("-mllvm");
708 CmdArgs.push_back(
709 Args.MakeArgString("-stack-usage-file=" + StackUsageFile));
710 }
711
712 // It seems that the 'e' option is completely ignored for dynamic executables
713 // (the default), and with static executables, the last one wins, as expected.
714 Args.addAllArgs(CmdArgs, {options::OPT_d_Flag, options::OPT_s, options::OPT_t,
715 options::OPT_Z_Flag, options::OPT_u_Group});
716
717 // Forward -ObjC when either -ObjC or -ObjC++ is used, to force loading
718 // members of static archive libraries which implement Objective-C classes or
719 // categories.
720 if (Args.hasArg(options::OPT_ObjC) || Args.hasArg(options::OPT_ObjCXX))
721 CmdArgs.push_back("-ObjC");
722
723 CmdArgs.push_back("-o");
724 CmdArgs.push_back(Output.getFilename());
725
726 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
727 getMachOToolChain().addStartObjectFileArgs(Args, CmdArgs);
728
729 Args.AddAllArgs(CmdArgs, options::OPT_L);
730
731 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs, JA);
732 // Build the input file for -filelist (list of linker input files) in case we
733 // need it later
734 for (const auto &II : Inputs) {
735 if (!II.isFilename()) {
736 // This is a linker input argument.
737 // We cannot mix input arguments and file names in a -filelist input, thus
738 // we prematurely stop our list (remaining files shall be passed as
739 // arguments).
740 if (InputFileList.size() > 0)
741 break;
742
743 continue;
744 }
745
746 InputFileList.push_back(II.getFilename());
747 }
748
749 // Additional linker set-up and flags for Fortran. This is required in order
750 // to generate executables.
751 if (getToolChain().getDriver().IsFlangMode() &&
752 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
753 getToolChain().addFortranRuntimeLibraryPath(Args, CmdArgs);
754 getToolChain().addFortranRuntimeLibs(Args, CmdArgs);
755 }
756
757 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs))
758 addOpenMPRuntime(C, CmdArgs, getToolChain(), Args);
759
760 if (isObjCRuntimeLinked(Args) &&
761 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
762 // We use arclite library for both ARC and subscripting support.
763 getMachOToolChain().AddLinkARCArgs(Args, CmdArgs);
764
765 CmdArgs.push_back("-framework");
766 CmdArgs.push_back("Foundation");
767 // Link libobj.
768 CmdArgs.push_back("-lobjc");
769 }
770
771 if (LinkingOutput) {
772 CmdArgs.push_back("-arch_multiple");
773 CmdArgs.push_back("-final_output");
774 CmdArgs.push_back(LinkingOutput);
775 }
776
777 if (Args.hasArg(options::OPT_fnested_functions))
778 CmdArgs.push_back("-allow_stack_execute");
779
780 getMachOToolChain().addProfileRTLibs(Args, CmdArgs);
781
782 StringRef Parallelism = getLTOParallelism(Args, getToolChain().getDriver());
783 if (!Parallelism.empty()) {
784 CmdArgs.push_back("-mllvm");
785 unsigned NumThreads =
786 llvm::get_threadpool_strategy(Parallelism)->compute_thread_count();
787 CmdArgs.push_back(Args.MakeArgString("-threads=" + Twine(NumThreads)));
788 }
789
790 if (getToolChain().ShouldLinkCXXStdlib(Args))
791 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
792
793 bool NoStdOrDefaultLibs =
794 Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs);
795 bool ForceLinkBuiltins = Args.hasArg(options::OPT_fapple_link_rtlib);
796 if (!NoStdOrDefaultLibs || ForceLinkBuiltins) {
797 // link_ssp spec is empty.
798
799 // If we have both -nostdlib/nodefaultlibs and -fapple-link-rtlib then
800 // we just want to link the builtins, not the other libs like libSystem.
801 if (NoStdOrDefaultLibs && ForceLinkBuiltins) {
802 getMachOToolChain().AddLinkRuntimeLib(Args, CmdArgs, "builtins");
803 } else {
804 // Let the tool chain choose which runtime library to link.
805 getMachOToolChain().AddLinkRuntimeLibArgs(Args, CmdArgs,
806 ForceLinkBuiltins);
807
808 // No need to do anything for pthreads. Claim argument to avoid warning.
809 Args.ClaimAllArgs(options::OPT_pthread);
810 Args.ClaimAllArgs(options::OPT_pthreads);
811 }
812 }
813
814 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
815 // endfile_spec is empty.
816 }
817
818 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
819 Args.AddAllArgs(CmdArgs, options::OPT_F);
820
821 // -iframework should be forwarded as -F.
822 for (const Arg *A : Args.filtered(options::OPT_iframework))
823 CmdArgs.push_back(Args.MakeArgString(std::string("-F") + A->getValue()));
824
825 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
826 if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
827 if (A->getValue() == StringRef("Accelerate")) {
828 CmdArgs.push_back("-framework");
829 CmdArgs.push_back("Accelerate");
830 }
831 }
832 }
833
834 // Add non-standard, platform-specific search paths, e.g., for DriverKit:
835 // -L<sysroot>/System/DriverKit/usr/lib
836 // -F<sysroot>/System/DriverKit/System/Library/Framework
837 {
838 bool NonStandardSearchPath = false;
839 const auto &Triple = getToolChain().getTriple();
840 if (Triple.isDriverKit()) {
841 // ld64 fixed the implicit -F and -L paths in ld64-605.1+.
842 NonStandardSearchPath =
843 Version.getMajor() < 605 ||
844 (Version.getMajor() == 605 && Version.getMinor().value_or(0) < 1);
845 } else {
846 NonStandardSearchPath = getMachOToolChain().HasPlatformPrefix(Triple);
847 }
848
849 if (NonStandardSearchPath) {
850 if (auto *Sysroot = Args.getLastArg(options::OPT_isysroot)) {
851 auto AddSearchPath = [&](StringRef Flag, StringRef SearchPath) {
852 SmallString<128> P(Sysroot->getValue());
853 getMachOToolChain().AppendPlatformPrefix(P, Triple);
854 llvm::sys::path::append(P, SearchPath);
855 if (getToolChain().getVFS().exists(P)) {
856 CmdArgs.push_back(Args.MakeArgString(Flag + P));
857 }
858 };
859 AddSearchPath("-L", "/usr/lib");
860 AddSearchPath("-F", "/System/Library/Frameworks");
861 }
862 }
863 }
864
865 ResponseFileSupport ResponseSupport;
866 if (Version >= VersionTuple(705) || LinkerIsLLD) {
867 ResponseSupport = ResponseFileSupport::AtFileUTF8();
868 } else {
869 // For older versions of the linker, use the legacy filelist method instead.
870 ResponseSupport = {ResponseFileSupport::RF_FileList, llvm::sys::WEM_UTF8,
871 "-filelist"};
872 }
873
874 std::unique_ptr<Command> Cmd = std::make_unique<Command>(
875 JA, *this, ResponseSupport, Exec, CmdArgs, Inputs, Output);
876 Cmd->setInputFileList(std::move(InputFileList));
877 C.addCommand(std::move(Cmd));
878}
879
881 const InputInfo &Output,
882 const InputInfoList &Inputs,
883 const ArgList &Args,
884 const char *LinkingOutput) const {
885 const Driver &D = getToolChain().getDriver();
886
887 // Silence warning for "clang -g foo.o -o foo"
888 Args.ClaimAllArgs(options::OPT_g_Group);
889 // and "clang -emit-llvm foo.o -o foo"
890 Args.ClaimAllArgs(options::OPT_emit_llvm);
891 // and for "clang -w foo.o -o foo". Other warning options are already
892 // handled somewhere else.
893 Args.ClaimAllArgs(options::OPT_w);
894 // Silence warnings when linking C code with a C++ '-stdlib' argument.
895 Args.ClaimAllArgs(options::OPT_stdlib_EQ);
896
897 // libtool <options> <output_file> <input_files>
898 ArgStringList CmdArgs;
899 // Create and insert file members with a deterministic index.
900 CmdArgs.push_back("-static");
901 CmdArgs.push_back("-D");
902 CmdArgs.push_back("-no_warning_for_no_symbols");
903 CmdArgs.push_back("-o");
904 CmdArgs.push_back(Output.getFilename());
905
906 for (const auto &II : Inputs) {
907 if (II.isFilename()) {
908 CmdArgs.push_back(II.getFilename());
909 }
910 }
911
912 // Delete old output archive file if it already exists before generating a new
913 // archive file.
914 const auto *OutputFileName = Output.getFilename();
915 if (Output.isFilename() && llvm::sys::fs::exists(OutputFileName)) {
916 if (std::error_code EC = llvm::sys::fs::remove(OutputFileName)) {
917 D.Diag(diag::err_drv_unable_to_remove_file) << EC.message();
918 return;
919 }
920 }
921
922 const char *Exec = Args.MakeArgString(getToolChain().GetStaticLibToolPath());
923 C.addCommand(std::make_unique<Command>(JA, *this,
925 Exec, CmdArgs, Inputs, Output));
926}
927
929 const InputInfo &Output,
930 const InputInfoList &Inputs,
931 const ArgList &Args,
932 const char *LinkingOutput) const {
933 ArgStringList CmdArgs;
934
935 CmdArgs.push_back("-create");
936 assert(Output.isFilename() && "Unexpected lipo output.");
937
938 CmdArgs.push_back("-output");
939 CmdArgs.push_back(Output.getFilename());
940
941 for (const auto &II : Inputs) {
942 assert(II.isFilename() && "Unexpected lipo input.");
943 CmdArgs.push_back(II.getFilename());
944 }
945
946 StringRef LipoName = Args.getLastArgValue(options::OPT_fuse_lipo_EQ, "lipo");
947 const char *Exec =
948 Args.MakeArgString(getToolChain().GetProgramPath(LipoName.data()));
949 C.addCommand(std::make_unique<Command>(JA, *this, ResponseFileSupport::None(),
950 Exec, CmdArgs, Inputs, Output));
951}
952
954 const InputInfo &Output,
955 const InputInfoList &Inputs,
956 const ArgList &Args,
957 const char *LinkingOutput) const {
958 ArgStringList CmdArgs;
959
960 CmdArgs.push_back("-o");
961 CmdArgs.push_back(Output.getFilename());
962
963 assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
964 const InputInfo &Input = Inputs[0];
965 assert(Input.isFilename() && "Unexpected dsymutil input.");
966 CmdArgs.push_back(Input.getFilename());
967
968 const char *Exec =
969 Args.MakeArgString(getToolChain().GetProgramPath("dsymutil"));
970 C.addCommand(std::make_unique<Command>(JA, *this, ResponseFileSupport::None(),
971 Exec, CmdArgs, Inputs, Output));
972}
973
975 const InputInfo &Output,
976 const InputInfoList &Inputs,
977 const ArgList &Args,
978 const char *LinkingOutput) const {
979 ArgStringList CmdArgs;
980 CmdArgs.push_back("--verify");
981 CmdArgs.push_back("--debug-info");
982 CmdArgs.push_back("--eh-frame");
983 CmdArgs.push_back("--quiet");
984
985 assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
986 const InputInfo &Input = Inputs[0];
987 assert(Input.isFilename() && "Unexpected verify input");
988
989 // Grabbing the output of the earlier dsymutil run.
990 CmdArgs.push_back(Input.getFilename());
991
992 const char *Exec =
993 Args.MakeArgString(getToolChain().GetProgramPath("dwarfdump"));
994 C.addCommand(std::make_unique<Command>(JA, *this, ResponseFileSupport::None(),
995 Exec, CmdArgs, Inputs, Output));
996}
997
998MachO::MachO(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
999 : ToolChain(D, Triple, Args) {
1000 // We expect 'as', 'ld', etc. to be adjacent to our install dir.
1001 getProgramPaths().push_back(getDriver().Dir);
1002}
1003
1004AppleMachO::AppleMachO(const Driver &D, const llvm::Triple &Triple,
1005 const ArgList &Args)
1006 : MachO(D, Triple, Args), CudaInstallation(D, Triple, Args),
1007 RocmInstallation(D, Triple, Args), SYCLInstallation(D, Triple, Args) {}
1008
1009/// Darwin - Darwin tool chain for i386 and x86_64.
1010Darwin::Darwin(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
1011 : AppleMachO(D, Triple, Args), TargetInitialized(false) {}
1012
1015
1016 // Darwin always preprocesses assembly files (unless -x is used explicitly).
1017 if (Ty == types::TY_PP_Asm)
1018 return types::TY_Asm;
1019
1020 return Ty;
1021}
1022
1023bool MachO::HasNativeLLVMSupport() const { return true; }
1024
1026 // Always use libc++ by default
1027 return ToolChain::CST_Libcxx;
1028}
1029
1030/// Darwin provides an ARC runtime starting in MacOS X 10.7 and iOS 5.0.
1034 if (isTargetIOSBased())
1036 if (isTargetXROS()) {
1037 // XROS uses the iOS runtime.
1038 auto T = llvm::Triple(Twine("arm64-apple-") +
1039 llvm::Triple::getOSTypeName(llvm::Triple::XROS) +
1040 TargetVersion.getAsString());
1041 return ObjCRuntime(ObjCRuntime::iOS, T.getiOSVersion());
1042 }
1043 if (isNonFragile)
1046}
1047
1048/// Darwin provides a blocks runtime starting in MacOS X 10.6 and iOS 3.2.
1051 return true;
1052 else if (isTargetFirmware())
1053 return false;
1054 else if (isTargetIOSBased())
1055 return !isIPhoneOSVersionLT(3, 2);
1056 else {
1057 assert(isTargetMacOSBased() && "unexpected darwin target");
1058 return !isMacosxVersionLT(10, 6);
1059 }
1060}
1061
1062void AppleMachO::AddCudaIncludeArgs(const ArgList &DriverArgs,
1063 ArgStringList &CC1Args) const {
1064 CudaInstallation->AddCudaIncludeArgs(DriverArgs, CC1Args);
1065}
1066
1067void AppleMachO::AddHIPIncludeArgs(const ArgList &DriverArgs,
1068 ArgStringList &CC1Args) const {
1069 RocmInstallation->AddHIPIncludeArgs(DriverArgs, CC1Args);
1070}
1071
1072void AppleMachO::addSYCLIncludeArgs(const ArgList &DriverArgs,
1073 ArgStringList &CC1Args) const {
1074 SYCLInstallation->addSYCLIncludeArgs(DriverArgs, CC1Args);
1075}
1076
1077// This is just a MachO name translation routine and there's no
1078// way to join this into ARMTargetParser without breaking all
1079// other assumptions. Maybe MachO should consider standardising
1080// their nomenclature.
1081static const char *ArmMachOArchName(StringRef Arch) {
1082 return llvm::StringSwitch<const char *>(Arch)
1083 .Case("armv6k", "armv6")
1084 .Case("armv6m", "armv6m")
1085 .Case("armv5tej", "armv5")
1086 .Case("xscale", "xscale")
1087 .Case("armv4t", "armv4t")
1088 .Case("armv7", "armv7")
1089 .Cases({"armv7a", "armv7-a"}, "armv7")
1090 .Cases({"armv7r", "armv7-r"}, "armv7")
1091 .Cases({"armv7em", "armv7e-m"}, "armv7em")
1092 .Cases({"armv7k", "armv7-k"}, "armv7k")
1093 .Cases({"armv7m", "armv7-m"}, "armv7m")
1094 .Cases({"armv7s", "armv7-s"}, "armv7s")
1095 .Cases({"armv8-m.base", "armv8m.base"}, "armv8m.base")
1096 .Cases({"armv8-m.main", "armv8m.main"}, "armv8m.main")
1097 .Cases({"armv8.1-m.main", "armv8m.main"}, "armv8.1m.main")
1098 .Default(nullptr);
1099}
1100
1101static const char *ArmMachOArchNameCPU(StringRef CPU) {
1102 llvm::ARM::ArchKind ArchKind = llvm::ARM::parseCPUArch(CPU);
1103 if (ArchKind == llvm::ARM::ArchKind::INVALID)
1104 return nullptr;
1105 StringRef Arch = llvm::ARM::getArchName(ArchKind);
1106
1107 // FIXME: Make sure this MachO triple mangling is really necessary.
1108 // ARMv5* normalises to ARMv5.
1109 if (Arch.starts_with("armv5"))
1110 Arch = Arch.substr(0, 5);
1111 // ARMv6*, except ARMv6M, normalises to ARMv6.
1112 else if (Arch.starts_with("armv6") && !Arch.ends_with("6m"))
1113 Arch = Arch.substr(0, 5);
1114 // ARMv7A normalises to ARMv7.
1115 else if (Arch.ends_with("v7a"))
1116 Arch = Arch.substr(0, 5);
1117 return Arch.data();
1118}
1119
1120StringRef MachO::getMachOArchName(const ArgList &Args) const {
1121 switch (getTriple().getArch()) {
1122 default:
1124
1125 case llvm::Triple::aarch64_32:
1126 return "arm64_32";
1127
1128 case llvm::Triple::aarch64: {
1129 if (getTriple().isArm64e())
1130 return "arm64e";
1131 return "arm64";
1132 }
1133
1134 case llvm::Triple::thumb:
1135 case llvm::Triple::arm:
1136 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
1137 if (const char *Arch = ArmMachOArchName(A->getValue()))
1138 return Arch;
1139
1140 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
1141 if (const char *Arch = ArmMachOArchNameCPU(A->getValue()))
1142 return Arch;
1143
1144 return "arm";
1145 }
1146}
1147
1148VersionTuple MachO::getLinkerVersion(const llvm::opt::ArgList &Args) const {
1149 if (LinkerVersion) {
1150#ifndef NDEBUG
1151 VersionTuple NewLinkerVersion;
1152 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ))
1153 (void)NewLinkerVersion.tryParse(A->getValue());
1154 assert(NewLinkerVersion == LinkerVersion);
1155#endif
1156 return *LinkerVersion;
1157 }
1158
1159 VersionTuple NewLinkerVersion;
1160 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
1161 // Rejecting subbuild version is probably not necessary, but some
1162 // existing tests depend on this.
1163 if (NewLinkerVersion.tryParse(A->getValue()) ||
1164 NewLinkerVersion.getSubbuild())
1165 getDriver().Diag(diag::err_drv_invalid_version_number)
1166 << A->getAsString(Args);
1167 }
1168
1169 LinkerVersion = NewLinkerVersion;
1170 return *LinkerVersion;
1171}
1172
1174
1177 return;
1178
1179 llvm::Triple::OSType OS = getTriple().getOS();
1180
1181 DarwinPlatformKind Platform;
1182 switch (OS) {
1183 case llvm::Triple::Darwin:
1184 case llvm::Triple::MacOSX:
1185 Platform = MacOS;
1186 break;
1187 case llvm::Triple::IOS:
1188 Platform = IPhoneOS;
1189 break;
1190 case llvm::Triple::TvOS:
1191 Platform = TvOS;
1192 break;
1193 case llvm::Triple::WatchOS:
1194 Platform = WatchOS;
1195 break;
1196 case llvm::Triple::XROS:
1197 Platform = XROS;
1198 break;
1199 case llvm::Triple::DriverKit:
1200 Platform = DriverKit;
1201 break;
1202 default:
1203 // Unknown platform; leave uninitialized.
1204 return;
1205 }
1206
1208 if (getTriple().isSimulatorEnvironment())
1209 Environment = Simulator;
1210 else if (getTriple().isMacCatalystEnvironment())
1211 Environment = MacCatalyst;
1212
1213 VersionTuple OsVer = getTriple().getOSVersion();
1214 setTarget(Platform, Environment, OsVer.getMajor(),
1215 OsVer.getMinor().value_or(0), OsVer.getSubminor().value_or(0),
1216 VersionTuple());
1217}
1218
1220
1222
1223void Darwin::VerifyTripleForSDK(const llvm::opt::ArgList &Args,
1224 const llvm::Triple Triple) const {
1225 if (SDKInfo) {
1226 if (!SDKInfo->supportsTriple(Triple))
1227 getDriver().Diag(diag::warn_incompatible_sysroot)
1228 << SDKInfo->getDisplayName() << Triple.getTriple();
1229 } else if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
1230 // If there is no SDK info, assume this is building against an SDK that
1231 // predates SDKSettings.json. Try to match the triple to the SDK path.
1232 const char *isysroot = A->getValue();
1233 StringRef SDKName = getSDKName(isysroot);
1234 if (!SDKName.empty()) {
1235 bool supported = true;
1236 if (Triple.isWatchOS())
1237 supported = SDKName.starts_with("Watch");
1238 else if (Triple.isTvOS())
1239 supported = SDKName.starts_with("AppleTV");
1240 else if (Triple.isDriverKit())
1241 supported = SDKName.starts_with("DriverKit");
1242 else if (Triple.isiOS())
1243 supported = SDKName.starts_with("iPhone");
1244 else if (Triple.isMacOSX())
1245 supported = SDKName.starts_with("MacOSX");
1246 // If it's not an older SDK, then it might be a damaged SDK or a
1247 // non-standard -isysroot path. Don't try to diagnose that here.
1248
1249 if (!supported)
1250 getDriver().Diag(diag::warn_incompatible_sysroot)
1251 << SDKName << Triple.getTriple();
1252 }
1253 }
1254}
1255
1256std::string Darwin::ComputeEffectiveClangTriple(const ArgList &Args,
1257 llvm::StringRef BoundArch,
1258 types::ID InputType) const {
1259 llvm::Triple Triple(ComputeLLVMTriple(Args, BoundArch, InputType));
1260
1261 // If the target isn't initialized (e.g., an unknown Darwin platform, return
1262 // the default triple). Note: we intentionally do NOT call
1263 // ensureTargetInitialized() here because this method is called before
1264 // AddDeploymentTarget() in some code paths (e.g. -print-libgcc-file-name),
1265 // and lazy init with version 0.0.0 would conflict with the real version
1266 // that AddDeploymentTarget() later sets via setTarget().
1267 if (!isTargetInitialized())
1268 return Triple.getTriple();
1269
1270 SmallString<16> Str;
1272 Str += "watchos";
1273 else if (isTargetTvOSBased())
1274 Str += "tvos";
1275 else if (isTargetDriverKit())
1276 Str += "driverkit";
1277 else if (isTargetIOSBased() || isTargetMacCatalyst())
1278 Str += "ios";
1279 else if (isTargetXROS())
1280 Str += llvm::Triple::getOSTypeName(llvm::Triple::XROS);
1281 else if (isTargetFirmware())
1282 Str += llvm::Triple::getOSTypeName(llvm::Triple::Firmware);
1283 else
1284 Str += "macosx";
1285 Str += getTripleTargetVersion().getAsString();
1286 Triple.setOSName(Str);
1287
1288 VerifyTripleForSDK(Args, Triple);
1289
1290 return Triple.getTriple();
1291}
1292
1294 switch (AC) {
1296 if (!Lipo)
1297 Lipo.reset(new tools::darwin::Lipo(*this));
1298 return Lipo.get();
1300 if (!Dsymutil)
1301 Dsymutil.reset(new tools::darwin::Dsymutil(*this));
1302 return Dsymutil.get();
1304 if (!VerifyDebug)
1305 VerifyDebug.reset(new tools::darwin::VerifyDebug(*this));
1306 return VerifyDebug.get();
1307 default:
1308 return ToolChain::getTool(AC);
1309 }
1310}
1311
1312Tool *MachO::buildLinker() const { return new tools::darwin::Linker(*this); }
1313
1315 return new tools::darwin::StaticLibTool(*this);
1316}
1317
1319 return new tools::darwin::Assembler(*this);
1320}
1321
1322DarwinClang::DarwinClang(const Driver &D, const llvm::Triple &Triple,
1323 const ArgList &Args)
1324 : Darwin(D, Triple, Args) {}
1325
1326void DarwinClang::addClangWarningOptions(ArgStringList &CC1Args) const {
1327 // Always error about undefined 'TARGET_OS_*' macros.
1328 CC1Args.push_back("-Wundef-prefix=TARGET_OS_");
1329 CC1Args.push_back("-Werror=undef-prefix");
1330
1331 // For modern targets, promote certain warnings to errors.
1332 // Lazily initialize the target if needed (e.g. when Darwin is used as
1333 // a host toolchain for device offloading).
1335 if (!isTargetInitialized())
1336 return;
1337 if (isTargetWatchOSBased() || getTriple().isArch64Bit()) {
1338 // Always enable -Wdeprecated-objc-isa-usage and promote it
1339 // to an error.
1340 CC1Args.push_back("-Wdeprecated-objc-isa-usage");
1341 CC1Args.push_back("-Werror=deprecated-objc-isa-usage");
1342
1343 // For iOS and watchOS, also error about implicit function declarations,
1344 // as that can impact calling conventions.
1345 if (!isTargetMacOS())
1346 CC1Args.push_back("-Werror=implicit-function-declaration");
1347 }
1348}
1349
1351 const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args,
1352 llvm::StringRef BoundArch, Action::OffloadKind DeviceOffloadKind) const {
1353
1354 Darwin::addClangTargetOptions(DriverArgs, CC1Args, BoundArch,
1355 DeviceOffloadKind);
1356}
1357
1358/// Take a path that speculatively points into Xcode and return the
1359/// `XCODE/Contents/Developer` path if it is an Xcode path, or an empty path
1360/// otherwise.
1361static StringRef getXcodeDeveloperPath(StringRef PathIntoXcode) {
1362 static constexpr llvm::StringLiteral XcodeAppSuffix(
1363 ".app/Contents/Developer");
1364 size_t Index = PathIntoXcode.find(XcodeAppSuffix);
1365 if (Index == StringRef::npos)
1366 return "";
1367 return PathIntoXcode.take_front(Index + XcodeAppSuffix.size());
1368}
1369
1370void DarwinClang::AddLinkARCArgs(const ArgList &Args,
1371 ArgStringList &CmdArgs) const {
1372 // Avoid linking compatibility stubs on i386 mac.
1373 if (isTargetMacOSBased() && getArch() == llvm::Triple::x86)
1374 return;
1376 return;
1377 // ARC runtime is supported everywhere on arm64e.
1378 if (getTriple().isArm64e())
1379 return;
1380 if (isTargetXROS())
1381 return;
1382
1383 ObjCRuntime runtime = getDefaultObjCRuntime(/*nonfragile*/ true);
1384
1385 if ((runtime.hasNativeARC() || !isObjCAutoRefCount(Args)) &&
1386 runtime.hasSubscripting())
1387 return;
1388
1389 SmallString<128> P(getDriver().DriverExecutable);
1390 llvm::sys::path::remove_filename(P); // 'clang'
1391 llvm::sys::path::remove_filename(P); // 'bin'
1392 llvm::sys::path::append(P, "lib", "arc");
1393
1394 // 'libarclite' usually lives in the same toolchain as 'clang'. However, the
1395 // Swift open source toolchains for macOS distribute Clang without libarclite.
1396 // In that case, to allow the linker to find 'libarclite', we point to the
1397 // 'libarclite' in the XcodeDefault toolchain instead.
1398 if (!getVFS().exists(P)) {
1399 auto updatePath = [&](const Arg *A) {
1400 // Try to infer the path to 'libarclite' in the toolchain from the
1401 // specified SDK path.
1402 StringRef XcodePathForSDK = getXcodeDeveloperPath(A->getValue());
1403 if (XcodePathForSDK.empty())
1404 return false;
1405
1406 P = XcodePathForSDK;
1407 llvm::sys::path::append(P, "Toolchains/XcodeDefault.xctoolchain/usr",
1408 "lib", "arc");
1409 return getVFS().exists(P);
1410 };
1411
1412 bool updated = false;
1413 if (const Arg *A = Args.getLastArg(options::OPT_isysroot))
1414 updated = updatePath(A);
1415
1416 if (!updated) {
1417 if (const Arg *A = Args.getLastArg(options::OPT__sysroot_EQ))
1418 updatePath(A);
1419 }
1420 }
1421
1422 CmdArgs.push_back("-force_load");
1423 llvm::sys::path::append(P, "libarclite_");
1424 // Mash in the platform.
1426 P += "watchsimulator";
1427 else if (isTargetWatchOS())
1428 P += "watchos";
1429 else if (isTargetTvOSSimulator())
1430 P += "appletvsimulator";
1431 else if (isTargetTvOS())
1432 P += "appletvos";
1433 else if (isTargetIOSSimulator())
1434 P += "iphonesimulator";
1435 else if (isTargetIPhoneOS())
1436 P += "iphoneos";
1437 else
1438 P += "macosx";
1439 P += ".a";
1440
1441 if (!getVFS().exists(P))
1442 getDriver().Diag(clang::diag::err_drv_darwin_sdk_missing_arclite) << P;
1443
1444 CmdArgs.push_back(Args.MakeArgString(P));
1445}
1446
1448 // Default to use DWARF 2 on OS X 10.10 / iOS 8 and lower.
1449 if ((isTargetMacOSBased() && isMacosxVersionLT(10, 11)) ||
1451 return 2;
1452 // Default to use DWARF 4 on OS X 10.11 - macOS 14 / iOS 9 - iOS 17.
1453 if ((isTargetMacOSBased() && isMacosxVersionLT(15)) ||
1455 (isTargetWatchOSBased() && TargetVersion < llvm::VersionTuple(11)) ||
1456 (isTargetXROS() && TargetVersion < llvm::VersionTuple(2)) ||
1457 (isTargetDriverKit() && TargetVersion < llvm::VersionTuple(24)) ||
1458 (isTargetMacOSBased() &&
1459 TargetVersion.empty())) // apple-darwin, no version.
1460 return 4;
1461 return 5;
1462}
1463
1465 // Default to an OS version on which LLDB supports debugging
1466 // -gsimple-template-names programs.
1467 if ((isTargetMacOSBased() && isMacosxVersionLT(26)) ||
1469 (isTargetWatchOSBased() && TargetVersion < llvm::VersionTuple(26)) ||
1470 (isTargetXROS() && TargetVersion < llvm::VersionTuple(26)) ||
1471 (isTargetDriverKit() && TargetVersion < llvm::VersionTuple(25)) ||
1472 (isTargetMacOSBased() &&
1473 TargetVersion.empty())) // apple-darwin, no version.
1474 return false;
1475
1476 return true;
1477}
1478
1479void MachO::AddLinkRuntimeLib(const ArgList &Args, ArgStringList &CmdArgs,
1480 StringRef Component, RuntimeLinkOptions Opts,
1481 bool IsShared) const {
1482 std::string P = getCompilerRT(
1483 Args, Component, IsShared ? ToolChain::FT_Shared : ToolChain::FT_Static);
1484
1485 // For now, allow missing resource libraries to support developers who may
1486 // not have compiler-rt checked out or integrated into their build (unless
1487 // we explicitly force linking with this library).
1488 if ((Opts & RLO_AlwaysLink) || getVFS().exists(P)) {
1489 const char *LibArg = Args.MakeArgString(P);
1490 CmdArgs.push_back(LibArg);
1491 }
1492
1493 // Adding the rpaths might negatively interact when other rpaths are involved,
1494 // so we should make sure we add the rpaths last, after all user-specified
1495 // rpaths. This is currently true from this place, but we need to be
1496 // careful if this function is ever called before user's rpaths are emitted.
1497 if (Opts & RLO_AddRPath) {
1498 assert(StringRef(P).ends_with(".dylib") && "must be a dynamic library");
1499
1500 // Add @executable_path to rpath to support having the dylib copied with
1501 // the executable.
1502 CmdArgs.push_back("-rpath");
1503 CmdArgs.push_back("@executable_path");
1504
1505 // Add the compiler-rt library's directory to rpath to support using the
1506 // dylib from the default location without copying.
1507 CmdArgs.push_back("-rpath");
1508 CmdArgs.push_back(Args.MakeArgString(llvm::sys::path::parent_path(P)));
1509 }
1510}
1511
1512std::string MachO::getCompilerRT(const ArgList &Args, StringRef Component,
1513 FileType Type, bool IsFortran) const {
1514 assert(Type != ToolChain::FT_Object &&
1515 "it doesn't make sense to ask for the compiler-rt library name as an "
1516 "object file");
1517 SmallString<64> MachOLibName = StringRef("libclang_rt");
1518 // On MachO, the builtins component is not in the library name
1519 if (Component != "builtins") {
1520 MachOLibName += '.';
1521 MachOLibName += Component;
1522 }
1523 MachOLibName += Type == ToolChain::FT_Shared ? "_dynamic.dylib" : ".a";
1524
1525 SmallString<128> FullPath(getDriver().ResourceDir);
1526 llvm::sys::path::append(FullPath, "lib", "darwin", "macho_embedded",
1527 MachOLibName);
1528 return std::string(FullPath);
1529}
1530
1531std::string Darwin::getCompilerRT(const ArgList &Args, StringRef Component,
1532 FileType Type, bool IsFortran) const {
1533 // Firmware uses the "bare metal" RT.
1535 return MachO::getCompilerRT(Args, Component, Type, IsFortran);
1536
1537 assert(Type != ToolChain::FT_Object &&
1538 "it doesn't make sense to ask for the compiler-rt library name as an "
1539 "object file");
1540 SmallString<64> DarwinLibName = StringRef("libclang_rt.");
1541 // On Darwin, the builtins component is not in the library name
1542 if (Component != "builtins") {
1543 DarwinLibName += Component;
1544 DarwinLibName += '_';
1545 }
1546 DarwinLibName += getOSLibraryNameSuffix();
1547 DarwinLibName += Type == ToolChain::FT_Shared ? "_dynamic.dylib" : ".a";
1548
1549 SmallString<128> FullPath(getDriver().ResourceDir);
1550 llvm::sys::path::append(FullPath, "lib", "darwin", DarwinLibName);
1551 return std::string(FullPath);
1552}
1553
1554StringRef Darwin::getSDKName(StringRef isysroot) {
1555 // Assume SDK has path: SOME_PATH/SDKs/PlatformXX.YY.sdk
1556 auto BeginSDK = llvm::sys::path::rbegin(isysroot);
1557 auto EndSDK = llvm::sys::path::rend(isysroot);
1558 for (auto IT = BeginSDK; IT != EndSDK; ++IT) {
1559 StringRef SDK = *IT;
1560 if (SDK.consume_back(".sdk"))
1561 return SDK;
1562 }
1563 return "";
1564}
1565
1566StringRef Darwin::getOSLibraryNameSuffix(bool IgnoreSim) const {
1567 switch (TargetPlatform) {
1569 return "osx";
1572 return "osx";
1573 return TargetEnvironment == NativeEnvironment || IgnoreSim ? "ios"
1574 : "iossim";
1576 return TargetEnvironment == NativeEnvironment || IgnoreSim ? "tvos"
1577 : "tvossim";
1579 return TargetEnvironment == NativeEnvironment || IgnoreSim ? "watchos"
1580 : "watchossim";
1582 return TargetEnvironment == NativeEnvironment || IgnoreSim ? "xros"
1583 : "xrossim";
1585 return "driverkit";
1586
1588 break;
1589 }
1590 llvm_unreachable("Unsupported platform");
1591}
1592
1593/// Check if the link command contains a symbol export directive.
1594static bool hasExportSymbolDirective(const ArgList &Args) {
1595 for (Arg *A : Args) {
1596 if (A->getOption().matches(options::OPT_exported__symbols__list))
1597 return true;
1598 if (!A->getOption().matches(options::OPT_Wl_COMMA) &&
1599 !A->getOption().matches(options::OPT_Xlinker))
1600 continue;
1601 if (A->containsValue("-exported_symbols_list") ||
1602 A->containsValue("-exported_symbol"))
1603 return true;
1604 }
1605 return false;
1606}
1607
1608/// Add an export directive for \p Symbol to the link command.
1609static void addExportedSymbol(ArgStringList &CmdArgs, const char *Symbol) {
1610 CmdArgs.push_back("-exported_symbol");
1611 CmdArgs.push_back(Symbol);
1612}
1613
1614/// Add a sectalign directive for \p Segment and \p Section to the maximum
1615/// expected page size for Darwin.
1616///
1617/// On iPhone 6+ the max supported page size is 16K. On macOS, the max is 4K.
1618/// Use a common alignment constant (16K) for now, and reduce the alignment on
1619/// macOS if it proves important.
1620static void addSectalignToPage(const ArgList &Args, ArgStringList &CmdArgs,
1621 StringRef Segment, StringRef Section) {
1622 for (const char *A : {"-sectalign", Args.MakeArgString(Segment),
1623 Args.MakeArgString(Section), "0x4000"})
1624 CmdArgs.push_back(A);
1625}
1626
1627void Darwin::addProfileRTLibs(const ArgList &Args,
1628 ArgStringList &CmdArgs) const {
1629 if (!needsProfileRT(Args) && !needsGCovInstrumentation(Args))
1630 return;
1631
1632 AddLinkRuntimeLib(Args, CmdArgs, "profile",
1634
1635 bool ForGCOV = needsGCovInstrumentation(Args);
1636
1637 // If we have a symbol export directive and we're linking in the profile
1638 // runtime, automatically export symbols necessary to implement some of the
1639 // runtime's functionality.
1640 if (hasExportSymbolDirective(Args) && ForGCOV) {
1641 addExportedSymbol(CmdArgs, "___gcov_dump");
1642 addExportedSymbol(CmdArgs, "___gcov_reset");
1643 addExportedSymbol(CmdArgs, "_writeout_fn_list");
1644 addExportedSymbol(CmdArgs, "_reset_fn_list");
1645 }
1646
1647 // Align __llvm_prf_{cnts,bits,data} sections to the maximum expected page
1648 // alignment. This allows profile counters to be mmap()'d to disk. Note that
1649 // it's not enough to just page-align __llvm_prf_cnts: the following section
1650 // must also be page-aligned so that its data is not clobbered by mmap().
1651 //
1652 // The section alignment is only needed when continuous profile sync is
1653 // enabled, but this is expected to be the default in Xcode. Specifying the
1654 // extra alignment also allows the same binary to be used with/without sync
1655 // enabled.
1656 if (!ForGCOV) {
1657 for (auto IPSK : {llvm::IPSK_cnts, llvm::IPSK_bitmap, llvm::IPSK_data}) {
1659 Args, CmdArgs, "__DATA",
1660 llvm::getInstrProfSectionName(IPSK, llvm::Triple::MachO,
1661 /*AddSegmentInfo=*/false));
1662 }
1663 }
1664}
1665
1666void DarwinClang::AddLinkSanitizerLibArgs(const ArgList &Args,
1667 ArgStringList &CmdArgs,
1668 StringRef Sanitizer,
1669 bool Shared) const {
1670 auto RLO = RuntimeLinkOptions(RLO_AlwaysLink | (Shared ? RLO_AddRPath : 0U));
1671 AddLinkRuntimeLib(Args, CmdArgs, Sanitizer, RLO, Shared);
1672}
1673
1675 const ArgList &Args) const {
1676 if (Arg* A = Args.getLastArg(options::OPT_rtlib_EQ)) {
1677 StringRef Value = A->getValue();
1678 if (Value != "compiler-rt" && Value != "platform")
1679 getDriver().Diag(clang::diag::err_drv_unsupported_rtlib_for_platform)
1680 << Value << "darwin";
1681 }
1682
1683 return ToolChain::GetRuntimeLibType(Args);
1684}
1685
1686void DarwinClang::AddLinkRuntimeLibArgs(const ArgList &Args,
1687 ArgStringList &CmdArgs,
1688 bool ForceLinkBuiltinRT) const {
1689 // Firmware uses the "bare metal" runtime lib.
1691 return MachO::AddLinkRuntimeLibArgs(Args, CmdArgs, ForceLinkBuiltinRT);
1692
1693 // Call once to ensure diagnostic is printed if wrong value was specified
1694 GetRuntimeLibType(Args);
1695
1696 // Darwin doesn't support real static executables, don't link any runtime
1697 // libraries with -static.
1698 if (Args.hasArg(options::OPT_static) ||
1699 Args.hasArg(options::OPT_fapple_kext) ||
1700 Args.hasArg(options::OPT_mkernel)) {
1701 if (ForceLinkBuiltinRT)
1702 AddLinkRuntimeLib(Args, CmdArgs, "builtins");
1703 return;
1704 }
1705
1706 // Reject -static-libgcc for now, we can deal with this when and if someone
1707 // cares. This is useful in situations where someone wants to statically link
1708 // something like libstdc++, and needs its runtime support routines.
1709 if (const Arg *A = Args.getLastArg(options::OPT_static_libgcc)) {
1710 getDriver().Diag(diag::err_drv_unsupported_opt) << A->getAsString(Args);
1711 return;
1712 }
1713
1714 const SanitizerArgs &Sanitize = getSanitizerArgs(Args);
1715
1716 if (!Sanitize.needsSharedRt()) {
1717 const char *sanitizer = nullptr;
1718 if (Sanitize.needsUbsanRt()) {
1719 sanitizer = "UndefinedBehaviorSanitizer";
1720 } else if (Sanitize.needsRtsanRt()) {
1721 sanitizer = "RealtimeSanitizer";
1722 } else if (Sanitize.needsAsanRt()) {
1723 sanitizer = "AddressSanitizer";
1724 } else if (Sanitize.needsTsanRt()) {
1725 sanitizer = "ThreadSanitizer";
1726 }
1727 if (sanitizer) {
1728 getDriver().Diag(diag::err_drv_unsupported_static_sanitizer_darwin)
1729 << sanitizer;
1730 return;
1731 }
1732 }
1733
1734 if (Sanitize.linkRuntimes()) {
1735 if (Sanitize.needsAsanRt()) {
1736 if (Sanitize.needsStableAbi()) {
1737 AddLinkSanitizerLibArgs(Args, CmdArgs, "asan_abi", /*shared=*/false);
1738 } else {
1739 assert(Sanitize.needsSharedRt() &&
1740 "Static sanitizer runtimes not supported");
1741 AddLinkSanitizerLibArgs(Args, CmdArgs, "asan");
1742 }
1743 }
1744 if (Sanitize.needsRtsanRt()) {
1745 assert(Sanitize.needsSharedRt() &&
1746 "Static sanitizer runtimes not supported");
1747 AddLinkSanitizerLibArgs(Args, CmdArgs, "rtsan");
1748 }
1749 if (Sanitize.needsLsanRt())
1750 AddLinkSanitizerLibArgs(Args, CmdArgs, "lsan");
1751 if (Sanitize.needsUbsanRt()) {
1752 assert(Sanitize.needsSharedRt() &&
1753 "Static sanitizer runtimes not supported");
1754 AddLinkSanitizerLibArgs(
1755 Args, CmdArgs,
1756 Sanitize.requiresMinimalRuntime() ? "ubsan_minimal" : "ubsan");
1757 }
1758 if (Sanitize.needsTsanRt()) {
1759 assert(Sanitize.needsSharedRt() &&
1760 "Static sanitizer runtimes not supported");
1761 AddLinkSanitizerLibArgs(Args, CmdArgs, "tsan");
1762 }
1763 if (Sanitize.needsTysanRt())
1764 AddLinkSanitizerLibArgs(Args, CmdArgs, "tysan");
1765 if (Sanitize.needsFuzzer() && !Args.hasArg(options::OPT_dynamiclib)) {
1766 AddLinkSanitizerLibArgs(Args, CmdArgs, "fuzzer", /*shared=*/false);
1767
1768 // Libfuzzer is written in C++ and requires libcxx.
1769 // Since darwin::Linker::ConstructJob already adds -lc++ for clang++
1770 // by default if ShouldLinkCXXStdlib(Args), we only add the option if
1771 // !ShouldLinkCXXStdlib(Args). This avoids duplicate library errors
1772 // on Darwin.
1773 if (!ShouldLinkCXXStdlib(Args))
1774 AddCXXStdlibLibArgs(Args, CmdArgs);
1775 }
1776 if (Sanitize.needsStatsRt()) {
1777 AddLinkRuntimeLib(Args, CmdArgs, "stats_client", RLO_AlwaysLink);
1778 AddLinkSanitizerLibArgs(Args, CmdArgs, "stats");
1779 }
1780 }
1781
1782 if (Sanitize.needsMemProfRt())
1783 if (hasExportSymbolDirective(Args))
1785 CmdArgs,
1786 llvm::memprof::getMemprofOptionsSymbolDarwinLinkageName().data());
1787
1788 const XRayArgs &XRay = getXRayArgs(Args);
1789 if (XRay.needsXRayRt()) {
1790 AddLinkRuntimeLib(Args, CmdArgs, "xray");
1791 AddLinkRuntimeLib(Args, CmdArgs, "xray-basic");
1792 AddLinkRuntimeLib(Args, CmdArgs, "xray-fdr");
1793 }
1794
1795 if (isTargetDriverKit() && !Args.hasArg(options::OPT_nodriverkitlib)) {
1796 CmdArgs.push_back("-framework");
1797 CmdArgs.push_back("DriverKit");
1798 }
1799
1800 // Otherwise link libSystem, then the dynamic runtime library, and finally any
1801 // target specific static runtime library.
1802 if (!isTargetDriverKit())
1803 CmdArgs.push_back("-lSystem");
1804
1805 // Select the dynamic runtime library and the target specific static library.
1806 // Some old Darwin versions put builtins, libunwind, and some other stuff in
1807 // libgcc_s.1.dylib. MacOS X 10.6 and iOS 5 moved those functions to
1808 // libSystem, and made libgcc_s.1.dylib a stub. We never link libgcc_s when
1809 // building for aarch64 or iOS simulator, since libgcc_s was made obsolete
1810 // before either existed.
1811 if (getTriple().getArch() != llvm::Triple::aarch64 &&
1815 CmdArgs.push_back("-lgcc_s.1");
1816 AddLinkRuntimeLib(Args, CmdArgs, "builtins");
1817}
1818
1819/// Returns the most appropriate macOS target version for the current process.
1820///
1821/// If the macOS SDK version is the same or earlier than the system version,
1822/// then the SDK version is returned. Otherwise the system version is returned.
1823static std::string getSystemOrSDKMacOSVersion(StringRef MacOSSDKVersion) {
1824 llvm::Triple SystemTriple(llvm::sys::getProcessTriple());
1825 if (!SystemTriple.isMacOSX())
1826 return std::string(MacOSSDKVersion);
1827 VersionTuple SystemVersion;
1828 SystemTriple.getMacOSXVersion(SystemVersion);
1829
1830 unsigned Major, Minor, Micro;
1831 bool HadExtra;
1832 if (!Driver::GetReleaseVersion(MacOSSDKVersion, Major, Minor, Micro,
1833 HadExtra))
1834 return std::string(MacOSSDKVersion);
1835 VersionTuple SDKVersion(Major, Minor, Micro);
1836
1837 if (SDKVersion > SystemVersion)
1838 return SystemVersion.getAsString();
1839 return std::string(MacOSSDKVersion);
1840}
1841
1842namespace {
1843
1844/// The Darwin OS and version that was selected or inferred from arguments or
1845/// environment.
1846struct DarwinPlatform {
1847 enum SourceKind {
1848 /// The OS was specified using the -target argument.
1849 TargetArg,
1850 /// The OS was specified using the -mtargetos= argument.
1851 MTargetOSArg,
1852 /// The OS was specified using the -m<os>-version-min argument.
1853 OSVersionArg,
1854 /// The OS was specified using the OS_DEPLOYMENT_TARGET environment.
1855 DeploymentTargetEnv,
1856 /// The OS was inferred from the SDK.
1857 InferredFromSDK,
1858 /// The OS was inferred from the -arch.
1859 InferredFromArch
1860 };
1861
1862 using DarwinPlatformKind = Darwin::DarwinPlatformKind;
1863 using DarwinEnvironmentKind = Darwin::DarwinEnvironmentKind;
1864
1865 DarwinPlatformKind getPlatform() const { return Platform; }
1866
1867 DarwinEnvironmentKind getEnvironment() const { return Environment; }
1868
1869 void setEnvironment(DarwinEnvironmentKind Kind) {
1870 Environment = Kind;
1871 InferSimulatorFromArch = false;
1872 }
1873
1874 const VersionTuple getOSVersion() const {
1875 return UnderlyingOSVersion.value_or(VersionTuple());
1876 }
1877
1878 VersionTuple takeOSVersion() {
1879 assert(UnderlyingOSVersion.has_value() &&
1880 "attempting to get an unset OS version");
1881 VersionTuple Result = *UnderlyingOSVersion;
1882 UnderlyingOSVersion.reset();
1883 return Result;
1884 }
1885 bool isValidOSVersion() const {
1886 return llvm::Triple::isValidVersionForOS(getOSFromPlatform(Platform),
1887 getOSVersion());
1888 }
1889
1890 VersionTuple getCanonicalOSVersion() const {
1891 return llvm::Triple::getCanonicalVersionForOS(
1892 getOSFromPlatform(Platform), getOSVersion(), /*IsInValidRange=*/true);
1893 }
1894
1895 void setOSVersion(const VersionTuple &Version) {
1896 UnderlyingOSVersion = Version;
1897 }
1898
1899 bool hasOSVersion() const { return UnderlyingOSVersion.has_value(); }
1900
1901 VersionTuple getZipperedOSVersion() const {
1902 assert(Environment == DarwinEnvironmentKind::MacCatalyst &&
1903 "zippered target version is specified only for Mac Catalyst");
1904 return ZipperedOSVersion;
1905 }
1906
1907 /// Returns true if the target OS was explicitly specified.
1908 bool isExplicitlySpecified() const { return Kind <= DeploymentTargetEnv; }
1909
1910 /// Returns true if the simulator environment can be inferred from the arch.
1911 bool canInferSimulatorFromArch() const { return InferSimulatorFromArch; }
1912
1913 const std::optional<llvm::Triple> &getTargetVariantTriple() const {
1914 return TargetVariantTriple;
1915 }
1916
1917 /// Adds the -m<os>-version-min argument to the compiler invocation.
1918 void addOSVersionMinArgument(DerivedArgList &Args, const OptTable &Opts) {
1919 auto &[Arg, OSVersionStr] = Arguments;
1920 if (Arg)
1921 return;
1922 assert(Kind != TargetArg && Kind != MTargetOSArg && Kind != OSVersionArg &&
1923 "Invalid kind");
1924 options::ID Opt;
1925 switch (Platform) {
1926 case DarwinPlatformKind::MacOS:
1927 Opt = options::OPT_mmacos_version_min_EQ;
1928 break;
1929 case DarwinPlatformKind::IPhoneOS:
1930 Opt = options::OPT_mios_version_min_EQ;
1931 break;
1932 case DarwinPlatformKind::TvOS:
1933 Opt = options::OPT_mtvos_version_min_EQ;
1934 break;
1935 case DarwinPlatformKind::WatchOS:
1936 Opt = options::OPT_mwatchos_version_min_EQ;
1937 break;
1938 default:
1939 // New platforms always explicitly provide a version in the triple.
1940 return;
1941 }
1942 Arg = Args.MakeJoinedArg(nullptr, Opts.getOption(Opt), OSVersionStr);
1943 Args.append(Arg);
1944 }
1945
1946 /// Returns the OS version with the argument / environment variable that
1947 /// specified it.
1948 std::string getAsString(DerivedArgList &Args, const OptTable &Opts) {
1949 auto &[Arg, OSVersionStr] = Arguments;
1950 switch (Kind) {
1951 case TargetArg:
1952 case MTargetOSArg:
1953 case OSVersionArg:
1954 assert(Arg && "OS version argument not yet inferred");
1955 return Arg->getAsString(Args);
1956 case DeploymentTargetEnv:
1957 return (llvm::Twine(EnvVarName) + "=" + OSVersionStr).str();
1958 case InferredFromSDK:
1959 case InferredFromArch:
1960 llvm_unreachable("Cannot print arguments for inferred OS version");
1961 }
1962 llvm_unreachable("Unsupported Darwin Source Kind");
1963 }
1964
1965 // Returns the inferred source of how the OS version was resolved.
1966 std::string getInferredSource() {
1967 assert(!isExplicitlySpecified() && "OS version was not inferred");
1968 return InferredSource.str();
1969 }
1970
1971 void setEnvironment(llvm::Triple::EnvironmentType EnvType,
1972 const VersionTuple &OSVersion,
1973 const std::optional<DarwinSDKInfo> &SDKInfo) {
1974 switch (EnvType) {
1975 case llvm::Triple::Simulator:
1976 Environment = DarwinEnvironmentKind::Simulator;
1977 break;
1978 case llvm::Triple::MacABI: {
1979 Environment = DarwinEnvironmentKind::MacCatalyst;
1980 // The minimum native macOS target for MacCatalyst is macOS 10.15.
1981 ZipperedOSVersion = VersionTuple(10, 15);
1982 if (hasOSVersion() && SDKInfo) {
1983 if (const auto *MacCatalystToMacOSMapping = SDKInfo->getVersionMapping(
1985 if (auto MacOSVersion = MacCatalystToMacOSMapping->map(
1986 OSVersion, ZipperedOSVersion, std::nullopt)) {
1987 ZipperedOSVersion = *MacOSVersion;
1988 }
1989 }
1990 }
1991 // In a zippered build, we could be building for a macOS target that's
1992 // lower than the version that's implied by the OS version. In that case
1993 // we need to use the minimum version as the native target version.
1994 if (TargetVariantTriple) {
1995 auto TargetVariantVersion = TargetVariantTriple->getOSVersion();
1996 if (TargetVariantVersion.getMajor()) {
1997 if (TargetVariantVersion < ZipperedOSVersion)
1998 ZipperedOSVersion = std::move(TargetVariantVersion);
1999 }
2000 }
2001 break;
2002 }
2003 default:
2004 break;
2005 }
2006 }
2007
2008 static DarwinPlatform
2009 createFromTarget(const llvm::Triple &TT, Arg *A,
2010 std::optional<llvm::Triple> TargetVariantTriple,
2011 const std::optional<DarwinSDKInfo> &SDKInfo) {
2012 DarwinPlatform Result(TargetArg, getPlatformFromOS(TT.getOS()),
2013 TT.getOSVersion(), A);
2014 VersionTuple OsVersion = TT.getOSVersion();
2015 Result.TargetVariantTriple = std::move(TargetVariantTriple);
2016 Result.setEnvironment(TT.getEnvironment(), OsVersion, SDKInfo);
2017 return Result;
2018 }
2019 static DarwinPlatform
2020 createFromMTargetOS(llvm::Triple::OSType OS, VersionTuple OSVersion,
2021 llvm::Triple::EnvironmentType Environment, Arg *A,
2022 const std::optional<DarwinSDKInfo> &SDKInfo) {
2023 DarwinPlatform Result(MTargetOSArg, getPlatformFromOS(OS), OSVersion, A);
2024 Result.InferSimulatorFromArch = false;
2025 Result.setEnvironment(Environment, OSVersion, SDKInfo);
2026 return Result;
2027 }
2028 static DarwinPlatform createOSVersionArg(DarwinPlatformKind Platform, Arg *A,
2029 bool IsSimulator) {
2030 DarwinPlatform Result{OSVersionArg, Platform,
2031 getVersionFromString(A->getValue()), A};
2032 if (IsSimulator)
2033 Result.Environment = DarwinEnvironmentKind::Simulator;
2034 return Result;
2035 }
2036 static DarwinPlatform createDeploymentTargetEnv(DarwinPlatformKind Platform,
2037 StringRef EnvVarName,
2038 StringRef OSVersion) {
2039 DarwinPlatform Result(DeploymentTargetEnv, Platform,
2040 getVersionFromString(OSVersion));
2041 Result.EnvVarName = EnvVarName;
2042 return Result;
2043 }
2044 static DarwinPlatform createFromSDKInfo(StringRef SDKRoot,
2045 const DarwinSDKInfo &SDKInfo) {
2046 const DarwinSDKInfo::SDKPlatformInfo PlatformInfo =
2047 SDKInfo.getCanonicalPlatformInfo();
2048 const llvm::Triple::OSType OS = PlatformInfo.getOS();
2049 VersionTuple Version = SDKInfo.getVersion();
2050 if (OS == llvm::Triple::MacOSX)
2051 Version = getVersionFromString(
2052 getSystemOrSDKMacOSVersion(Version.getAsString()));
2053 DarwinPlatform Result(InferredFromSDK, getPlatformFromOS(OS), Version);
2054 Result.Environment = getEnvKindFromEnvType(PlatformInfo.getEnvironment());
2055 Result.InferSimulatorFromArch = false;
2056 Result.InferredSource = SDKRoot;
2057 return Result;
2058 }
2059 static DarwinPlatform createFromSDK(StringRef SDKRoot,
2060 DarwinPlatformKind Platform,
2061 StringRef Value,
2062 bool IsSimulator = false) {
2063 DarwinPlatform Result(InferredFromSDK, Platform,
2064 getVersionFromString(Value));
2065 if (IsSimulator)
2066 Result.Environment = DarwinEnvironmentKind::Simulator;
2067 Result.InferSimulatorFromArch = false;
2068 Result.InferredSource = SDKRoot;
2069 return Result;
2070 }
2071 static DarwinPlatform createFromArch(StringRef Arch, llvm::Triple::OSType OS,
2072 VersionTuple Version) {
2073 auto Result =
2074 DarwinPlatform(InferredFromArch, getPlatformFromOS(OS), Version);
2075 Result.InferredSource = Arch;
2076 return Result;
2077 }
2078
2079 /// Constructs an inferred SDKInfo value based on the version inferred from
2080 /// the SDK path itself. Only works for values that were created by inferring
2081 /// the platform from the SDKPath.
2082 DarwinSDKInfo inferSDKInfo() {
2083 assert(Kind == InferredFromSDK && "can infer SDK info only");
2084 llvm::Triple::OSType OS = getOSFromPlatform(Platform);
2085 llvm::Triple::EnvironmentType EnvironmentType =
2086 getEnvTypeFromEnvKind(Environment);
2087 StringRef PlatformPrefix =
2088 (Platform == DarwinPlatformKind::DriverKit) ? "/System/DriverKit" : "";
2089 return DarwinSDKInfo("", OS, EnvironmentType, getOSVersion(),
2090 getDisplayName(Platform, Environment, getOSVersion()),
2091 /*MaximumDeploymentTarget=*/
2092 VersionTuple(getOSVersion().getMajor(), 0, 99),
2093 {DarwinSDKInfo::SDKPlatformInfo(
2094 llvm::Triple::Apple, OS, EnvironmentType,
2095 llvm::Triple::MachO, PlatformPrefix)});
2096 }
2097
2098private:
2099 DarwinPlatform(SourceKind Kind, DarwinPlatformKind Platform, Arg *Argument)
2100 : Kind(Kind), Platform(Platform),
2101 Arguments({Argument, VersionTuple().getAsString()}) {}
2102 DarwinPlatform(SourceKind Kind, DarwinPlatformKind Platform,
2103 VersionTuple Value, Arg *Argument = nullptr)
2104 : Kind(Kind), Platform(Platform),
2105 Arguments({Argument, Value.getAsString()}) {
2106 if (!Value.empty())
2107 UnderlyingOSVersion = Value;
2108 }
2109
2110 static VersionTuple getVersionFromString(const StringRef Input) {
2111 llvm::VersionTuple Version;
2112 bool IsValid = !Version.tryParse(Input);
2113 assert(IsValid && "unable to convert input version to version tuple");
2114 (void)IsValid;
2115 return Version;
2116 }
2117
2118 static DarwinPlatformKind getPlatformFromOS(llvm::Triple::OSType OS) {
2119 switch (OS) {
2120 case llvm::Triple::Darwin:
2121 case llvm::Triple::MacOSX:
2122 return DarwinPlatformKind::MacOS;
2123 case llvm::Triple::IOS:
2124 return DarwinPlatformKind::IPhoneOS;
2125 case llvm::Triple::TvOS:
2126 return DarwinPlatformKind::TvOS;
2127 case llvm::Triple::WatchOS:
2128 return DarwinPlatformKind::WatchOS;
2129 case llvm::Triple::XROS:
2130 return DarwinPlatformKind::XROS;
2131 case llvm::Triple::DriverKit:
2132 return DarwinPlatformKind::DriverKit;
2133 case llvm::Triple::Firmware:
2134 return DarwinPlatformKind::Firmware;
2135 default:
2136 llvm_unreachable("Unable to infer Darwin variant");
2137 }
2138 }
2139
2140 static llvm::Triple::OSType getOSFromPlatform(DarwinPlatformKind Platform) {
2141 switch (Platform) {
2142 case DarwinPlatformKind::MacOS:
2143 return llvm::Triple::MacOSX;
2144 case DarwinPlatformKind::IPhoneOS:
2145 return llvm::Triple::IOS;
2146 case DarwinPlatformKind::TvOS:
2147 return llvm::Triple::TvOS;
2148 case DarwinPlatformKind::WatchOS:
2149 return llvm::Triple::WatchOS;
2150 case DarwinPlatformKind::DriverKit:
2151 return llvm::Triple::DriverKit;
2152 case DarwinPlatformKind::XROS:
2153 return llvm::Triple::XROS;
2154 case DarwinPlatformKind::Firmware:
2155 return llvm::Triple::Firmware;
2156 }
2157 llvm_unreachable("Unknown DarwinPlatformKind enum");
2158 }
2159
2160 static DarwinEnvironmentKind
2161 getEnvKindFromEnvType(llvm::Triple::EnvironmentType EnvironmentType) {
2162 switch (EnvironmentType) {
2163 case llvm::Triple::UnknownEnvironment:
2164 return DarwinEnvironmentKind::NativeEnvironment;
2165 case llvm::Triple::Simulator:
2166 return DarwinEnvironmentKind::Simulator;
2167 case llvm::Triple::MacABI:
2168 return DarwinEnvironmentKind::MacCatalyst;
2169 default:
2170 llvm_unreachable("Unable to infer Darwin environment");
2171 }
2172 }
2173
2174 static llvm::Triple::EnvironmentType
2175 getEnvTypeFromEnvKind(DarwinEnvironmentKind EnvironmentKind) {
2176 switch (EnvironmentKind) {
2177 case DarwinEnvironmentKind::NativeEnvironment:
2178 return llvm::Triple::UnknownEnvironment;
2179 case DarwinEnvironmentKind::Simulator:
2180 return llvm::Triple::Simulator;
2181 case DarwinEnvironmentKind::MacCatalyst:
2182 return llvm::Triple::MacABI;
2183 }
2184 llvm_unreachable("Unknown DarwinEnvironmentKind enum");
2185 }
2186
2187 static std::string getDisplayName(DarwinPlatformKind TargetPlatform,
2188 DarwinEnvironmentKind TargetEnvironment,
2189 VersionTuple Version) {
2190 SmallVector<std::string, 3> Components;
2191 switch (TargetPlatform) {
2192 case DarwinPlatformKind::MacOS:
2193 Components.push_back("macOS");
2194 break;
2195 case DarwinPlatformKind::IPhoneOS:
2196 Components.push_back("iOS");
2197 break;
2198 case DarwinPlatformKind::TvOS:
2199 Components.push_back("tvOS");
2200 break;
2201 case DarwinPlatformKind::WatchOS:
2202 Components.push_back("watchOS");
2203 break;
2204 case DarwinPlatformKind::DriverKit:
2205 Components.push_back("DriverKit");
2206 break;
2207 default:
2208 llvm::reportFatalUsageError(Twine("Platform: '") +
2209 std::to_string(TargetPlatform) +
2210 "' is unsupported when inferring SDK Info.");
2211 }
2212 switch (TargetEnvironment) {
2213 case DarwinEnvironmentKind::NativeEnvironment:
2214 break;
2215 case DarwinEnvironmentKind::Simulator:
2216 Components.push_back("Simulator");
2217 break;
2218 default:
2219 llvm::reportFatalUsageError(Twine("Environment: '") +
2220 std::to_string(TargetEnvironment) +
2221 "' is unsupported when inferring SDK Info.");
2222 }
2223 Components.push_back(Version.getAsString());
2224 return join(Components, " ");
2225 }
2226
2227 SourceKind Kind;
2228 DarwinPlatformKind Platform;
2229 DarwinEnvironmentKind Environment = DarwinEnvironmentKind::NativeEnvironment;
2230 // When compiling for a zippered target, this means both target &
2231 // target variant is set on the command line, ZipperedOSVersion holds the
2232 // OSVersion tied to the main target value.
2233 VersionTuple ZipperedOSVersion;
2234 // We allow multiple ways to set or default the OS
2235 // version used for compilation. When set, UnderlyingOSVersion represents
2236 // the intended version to match the platform information computed from
2237 // arguments.
2238 std::optional<VersionTuple> UnderlyingOSVersion;
2239 bool InferSimulatorFromArch = true;
2240 std::pair<Arg *, std::string> Arguments;
2241 StringRef EnvVarName;
2242 // If the DarwinPlatform information is derived from an inferred source, this
2243 // captures what that source input was for error reporting.
2244 StringRef InferredSource;
2245 // When compiling for a zippered target, this value represents the target
2246 // triple encoded in the target variant.
2247 std::optional<llvm::Triple> TargetVariantTriple;
2248};
2249
2250/// Returns the deployment target that's specified using the -m<os>-version-min
2251/// argument.
2252std::optional<DarwinPlatform>
2253getDeploymentTargetFromOSVersionArg(DerivedArgList &Args,
2254 const Driver &TheDriver) {
2255 Arg *macOSVersion = Args.getLastArg(options::OPT_mmacos_version_min_EQ);
2256 Arg *iOSVersion = Args.getLastArg(options::OPT_mios_version_min_EQ,
2257 options::OPT_mios_simulator_version_min_EQ);
2258 Arg *TvOSVersion =
2259 Args.getLastArg(options::OPT_mtvos_version_min_EQ,
2260 options::OPT_mtvos_simulator_version_min_EQ);
2261 Arg *WatchOSVersion =
2262 Args.getLastArg(options::OPT_mwatchos_version_min_EQ,
2263 options::OPT_mwatchos_simulator_version_min_EQ);
2264
2265 auto GetDarwinPlatform =
2266 [&](DarwinPlatform::DarwinPlatformKind Platform, Arg *VersionArg,
2267 bool IsSimulator) -> std::optional<DarwinPlatform> {
2268 if (StringRef(VersionArg->getValue()).empty()) {
2269 TheDriver.Diag(diag::err_drv_missing_version_number)
2270 << VersionArg->getAsString(Args);
2271 return std::nullopt;
2272 }
2273 return DarwinPlatform::createOSVersionArg(Platform, VersionArg,
2274 /*IsSimulator=*/IsSimulator);
2275 };
2276
2277 if (macOSVersion) {
2278 if (iOSVersion || TvOSVersion || WatchOSVersion) {
2279 TheDriver.Diag(diag::err_drv_argument_not_allowed_with)
2280 << macOSVersion->getAsString(Args)
2281 << (iOSVersion ? iOSVersion
2282 : TvOSVersion ? TvOSVersion : WatchOSVersion)
2283 ->getAsString(Args);
2284 }
2285 return GetDarwinPlatform(Darwin::MacOS, macOSVersion,
2286 /*IsSimulator=*/false);
2287
2288 } else if (iOSVersion) {
2289 if (TvOSVersion || WatchOSVersion) {
2290 TheDriver.Diag(diag::err_drv_argument_not_allowed_with)
2291 << iOSVersion->getAsString(Args)
2292 << (TvOSVersion ? TvOSVersion : WatchOSVersion)->getAsString(Args);
2293 }
2294 return GetDarwinPlatform(Darwin::IPhoneOS, iOSVersion,
2295 iOSVersion->getOption().getID() ==
2296 options::OPT_mios_simulator_version_min_EQ);
2297 } else if (TvOSVersion) {
2298 if (WatchOSVersion) {
2299 TheDriver.Diag(diag::err_drv_argument_not_allowed_with)
2300 << TvOSVersion->getAsString(Args)
2301 << WatchOSVersion->getAsString(Args);
2302 }
2303 return GetDarwinPlatform(Darwin::TvOS, TvOSVersion,
2304 TvOSVersion->getOption().getID() ==
2305 options::OPT_mtvos_simulator_version_min_EQ);
2306 } else if (WatchOSVersion)
2307 return GetDarwinPlatform(
2308 Darwin::WatchOS, WatchOSVersion,
2309 WatchOSVersion->getOption().getID() ==
2310 options::OPT_mwatchos_simulator_version_min_EQ);
2311 return std::nullopt;
2312}
2313
2314/// Returns the deployment target that's specified using the
2315/// OS_DEPLOYMENT_TARGET environment variable.
2316std::optional<DarwinPlatform>
2317getDeploymentTargetFromEnvironmentVariables(const Driver &TheDriver,
2318 const llvm::Triple &Triple) {
2319 const char *EnvVars[] = {
2320 "MACOSX_DEPLOYMENT_TARGET",
2321 "IPHONEOS_DEPLOYMENT_TARGET",
2322 "TVOS_DEPLOYMENT_TARGET",
2323 "WATCHOS_DEPLOYMENT_TARGET",
2324 "DRIVERKIT_DEPLOYMENT_TARGET",
2325 "XROS_DEPLOYMENT_TARGET"
2326 };
2327 std::string Targets[std::size(EnvVars)];
2328 for (const auto &I : llvm::enumerate(llvm::ArrayRef(EnvVars))) {
2329 if (char *Env = ::getenv(I.value()))
2330 Targets[I.index()] = Env;
2331 }
2332
2333 // Allow conflicts among OSX and iOS for historical reasons, but choose the
2334 // default platform.
2335 if (!Targets[Darwin::MacOS].empty() &&
2336 (!Targets[Darwin::IPhoneOS].empty() ||
2337 !Targets[Darwin::WatchOS].empty() || !Targets[Darwin::TvOS].empty() ||
2338 !Targets[Darwin::XROS].empty())) {
2339 if (Triple.getArch() == llvm::Triple::arm ||
2340 Triple.getArch() == llvm::Triple::aarch64 ||
2341 Triple.getArch() == llvm::Triple::thumb)
2342 Targets[Darwin::MacOS] = "";
2343 else
2344 Targets[Darwin::IPhoneOS] = Targets[Darwin::WatchOS] =
2345 Targets[Darwin::TvOS] = Targets[Darwin::XROS] = "";
2346 } else {
2347 // Don't allow conflicts in any other platform.
2348 unsigned FirstTarget = std::size(Targets);
2349 for (unsigned I = 0; I != std::size(Targets); ++I) {
2350 if (Targets[I].empty())
2351 continue;
2352 if (FirstTarget == std::size(Targets))
2353 FirstTarget = I;
2354 else
2355 TheDriver.Diag(diag::err_drv_conflicting_deployment_targets)
2356 << Targets[FirstTarget] << Targets[I];
2357 }
2358 }
2359
2360 for (const auto &Target : llvm::enumerate(llvm::ArrayRef(Targets))) {
2361 if (!Target.value().empty())
2362 return DarwinPlatform::createDeploymentTargetEnv(
2363 (Darwin::DarwinPlatformKind)Target.index(), EnvVars[Target.index()],
2364 Target.value());
2365 }
2366 return std::nullopt;
2367}
2368
2369/// Tries to infer the deployment target from the SDK specified by -isysroot
2370/// (or SDKROOT). Uses the version specified in the SDKSettings.json file if
2371/// it's available.
2372std::optional<DarwinPlatform>
2373inferDeploymentTargetFromSDK(DerivedArgList &Args,
2374 const std::optional<DarwinSDKInfo> &SDKInfo) {
2375 const Arg *A = Args.getLastArg(options::OPT_isysroot);
2376 if (!A)
2377 return std::nullopt;
2378 StringRef isysroot = A->getValue();
2379 if (SDKInfo)
2380 return DarwinPlatform::createFromSDKInfo(isysroot, *SDKInfo);
2381
2382 StringRef SDK = Darwin::getSDKName(isysroot);
2383 if (!SDK.size())
2384 return std::nullopt;
2385
2386 std::string Version;
2387 // Slice the version number out.
2388 // Version number is between the first and the last number.
2389 size_t StartVer = SDK.find_first_of("0123456789");
2390 size_t EndVer = SDK.find_last_of("0123456789");
2391 if (StartVer != StringRef::npos && EndVer > StartVer)
2392 Version = std::string(SDK.slice(StartVer, EndVer + 1));
2393 if (Version.empty())
2394 return std::nullopt;
2395
2396 if (SDK.starts_with("iPhoneOS") || SDK.starts_with("iPhoneSimulator"))
2397 return DarwinPlatform::createFromSDK(
2398 isysroot, Darwin::IPhoneOS, Version,
2399 /*IsSimulator=*/SDK.starts_with("iPhoneSimulator"));
2400 else if (SDK.starts_with("MacOSX"))
2401 return DarwinPlatform::createFromSDK(isysroot, Darwin::MacOS,
2403 else if (SDK.starts_with("WatchOS") || SDK.starts_with("WatchSimulator"))
2404 return DarwinPlatform::createFromSDK(
2405 isysroot, Darwin::WatchOS, Version,
2406 /*IsSimulator=*/SDK.starts_with("WatchSimulator"));
2407 else if (SDK.starts_with("AppleTVOS") || SDK.starts_with("AppleTVSimulator"))
2408 return DarwinPlatform::createFromSDK(
2409 isysroot, Darwin::TvOS, Version,
2410 /*IsSimulator=*/SDK.starts_with("AppleTVSimulator"));
2411 else if (SDK.starts_with("DriverKit"))
2412 return DarwinPlatform::createFromSDK(isysroot, Darwin::DriverKit, Version);
2413 return std::nullopt;
2414}
2415
2416// Compute & get the OS Version when the target triple omitted one.
2417VersionTuple getInferredOSVersion(llvm::Triple::OSType OS,
2418 const llvm::Triple &Triple,
2419 const Driver &TheDriver) {
2420 VersionTuple OsVersion;
2421 llvm::Triple SystemTriple(llvm::sys::getProcessTriple());
2422 switch (OS) {
2423 case llvm::Triple::Darwin:
2424 case llvm::Triple::MacOSX:
2425 // If there is no version specified on triple, and both host and target are
2426 // macos, use the host triple to infer OS version.
2427 if (Triple.isMacOSX() && SystemTriple.isMacOSX() &&
2428 !Triple.getOSMajorVersion())
2429 SystemTriple.getMacOSXVersion(OsVersion);
2430 else if (!Triple.getMacOSXVersion(OsVersion))
2431 TheDriver.Diag(diag::err_drv_invalid_darwin_version)
2432 << Triple.getOSName();
2433 break;
2434 case llvm::Triple::IOS:
2435 if (Triple.isMacCatalystEnvironment() && !Triple.getOSMajorVersion()) {
2436 OsVersion = VersionTuple(13, 1);
2437 } else
2438 OsVersion = Triple.getiOSVersion();
2439 break;
2440 case llvm::Triple::TvOS:
2441 OsVersion = Triple.getOSVersion();
2442 break;
2443 case llvm::Triple::WatchOS:
2444 OsVersion = Triple.getWatchOSVersion();
2445 break;
2446 case llvm::Triple::DriverKit:
2447 OsVersion = Triple.getDriverKitVersion();
2448 break;
2449 default:
2450 OsVersion = Triple.getOSVersion();
2451 if (!OsVersion.getMajor())
2452 OsVersion = OsVersion.withMajorReplaced(1);
2453 break;
2454 }
2455 return OsVersion;
2456}
2457
2458/// Tries to infer the target OS from the -arch.
2459std::optional<DarwinPlatform>
2460inferDeploymentTargetFromArch(DerivedArgList &Args, const Darwin &Toolchain,
2461 const llvm::Triple &Triple,
2462 const Driver &TheDriver) {
2463 llvm::Triple::OSType OSTy = llvm::Triple::UnknownOS;
2464
2465 StringRef MachOArchName = Toolchain.getMachOArchName(Args);
2466 if (MachOArchName == "arm64" || MachOArchName == "arm64e")
2467 OSTy = llvm::Triple::MacOSX;
2468 else if (MachOArchName == "armv7" || MachOArchName == "armv7s" ||
2469 MachOArchName == "armv6")
2470 OSTy = llvm::Triple::IOS;
2471 else if (MachOArchName == "armv7k" || MachOArchName == "arm64_32")
2472 OSTy = llvm::Triple::WatchOS;
2473 else if (MachOArchName != "armv6m" && MachOArchName != "armv7m" &&
2474 MachOArchName != "armv7em" && MachOArchName != "armv8m.base" &&
2475 MachOArchName != "armv8m.main" && MachOArchName != "armv8.1m.main")
2476 OSTy = llvm::Triple::MacOSX;
2477 if (OSTy == llvm::Triple::UnknownOS)
2478 return std::nullopt;
2479 return DarwinPlatform::createFromArch(
2480 MachOArchName, OSTy, getInferredOSVersion(OSTy, Triple, TheDriver));
2481}
2482
2483/// Returns the deployment target that's specified using the -target option.
2484std::optional<DarwinPlatform> getDeploymentTargetFromTargetArg(
2485 DerivedArgList &Args, const llvm::Triple &Triple, const Driver &TheDriver,
2486 const std::optional<DarwinSDKInfo> &SDKInfo) {
2487 if (!Args.hasArg(options::OPT_target))
2488 return std::nullopt;
2489 if (Triple.getOS() == llvm::Triple::Darwin ||
2490 Triple.getOS() == llvm::Triple::UnknownOS)
2491 return std::nullopt;
2492 std::optional<llvm::Triple> TargetVariantTriple;
2493 for (const Arg *A : Args.filtered(options::OPT_darwin_target_variant)) {
2494 llvm::Triple TVT(A->getValue());
2495 // Find a matching <arch>-<vendor> target variant triple that can be used.
2496 if ((Triple.getArch() == llvm::Triple::aarch64 ||
2497 TVT.getArchName() == Triple.getArchName()) &&
2498 TVT.getArch() == Triple.getArch() &&
2499 TVT.getSubArch() == Triple.getSubArch() &&
2500 TVT.getVendor() == Triple.getVendor()) {
2501 if (TargetVariantTriple)
2502 continue;
2503 A->claim();
2504 // Accept a -target-variant triple when compiling code that may run on
2505 // macOS or Mac Catalyst.
2506 if ((Triple.isMacOSX() && TVT.getOS() == llvm::Triple::IOS &&
2507 TVT.isMacCatalystEnvironment()) ||
2508 (TVT.isMacOSX() && Triple.getOS() == llvm::Triple::IOS &&
2509 Triple.isMacCatalystEnvironment())) {
2510 TargetVariantTriple = TVT;
2511 continue;
2512 }
2513 TheDriver.Diag(diag::err_drv_target_variant_invalid)
2514 << A->getSpelling() << A->getValue();
2515 }
2516 }
2517 DarwinPlatform PlatformAndVersion = DarwinPlatform::createFromTarget(
2518 Triple, Args.getLastArg(options::OPT_target), TargetVariantTriple,
2519 SDKInfo);
2520
2521 return PlatformAndVersion;
2522}
2523
2524/// Returns the deployment target that's specified using the -mtargetos option.
2525std::optional<DarwinPlatform> getDeploymentTargetFromMTargetOSArg(
2526 DerivedArgList &Args, const Driver &TheDriver,
2527 const std::optional<DarwinSDKInfo> &SDKInfo) {
2528 auto *A = Args.getLastArg(options::OPT_mtargetos_EQ);
2529 if (!A)
2530 return std::nullopt;
2531 llvm::Triple TT(llvm::Twine("unknown-apple-") + A->getValue());
2532 switch (TT.getOS()) {
2533 case llvm::Triple::MacOSX:
2534 case llvm::Triple::IOS:
2535 case llvm::Triple::TvOS:
2536 case llvm::Triple::WatchOS:
2537 case llvm::Triple::XROS:
2538 break;
2539 default:
2540 TheDriver.Diag(diag::err_drv_invalid_os_in_arg)
2541 << TT.getOSName() << A->getAsString(Args);
2542 return std::nullopt;
2543 }
2544
2545 VersionTuple Version = TT.getOSVersion();
2546 if (!Version.getMajor()) {
2547 TheDriver.Diag(diag::err_drv_invalid_version_number)
2548 << A->getAsString(Args);
2549 return std::nullopt;
2550 }
2551 return DarwinPlatform::createFromMTargetOS(TT.getOS(), Version,
2552 TT.getEnvironment(), A, SDKInfo);
2553}
2554
2555std::optional<DarwinSDKInfo> parseSDKSettings(llvm::vfs::FileSystem &VFS,
2556 const ArgList &Args,
2557 const Driver &TheDriver) {
2558 const Arg *A = Args.getLastArg(options::OPT_isysroot);
2559 if (!A)
2560 return std::nullopt;
2561 StringRef isysroot = A->getValue();
2562 auto SDKInfoOrErr = parseDarwinSDKInfo(VFS, isysroot);
2563 if (!SDKInfoOrErr) {
2564 llvm::consumeError(SDKInfoOrErr.takeError());
2565 TheDriver.Diag(diag::warn_drv_darwin_sdk_invalid_settings);
2566 return std::nullopt;
2567 }
2568 return *SDKInfoOrErr;
2569}
2570
2571} // namespace
2572
2573void Darwin::AddDeploymentTarget(DerivedArgList &Args) const {
2574 const OptTable &Opts = getDriver().getOpts();
2575 // TryXcselect keeps track of whether we use xcselect to find the SDK
2576 // when CLANG_USE_XCSELECT is enabled. Currently, we do this when we
2577 // do not have a sysroot from -isysroot, --sysroot, or SDKROOT, and
2578 // we do not have --no-xcselect.
2579 bool TryXcselect = false;
2580 (void)TryXcselect;
2581
2582 // Support allowing the SDKROOT environment variable used by xcrun and other
2583 // Xcode tools to define the default sysroot, by making it the default for
2584 // isysroot.
2585 if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
2586 // Warn if the path does not exist.
2587 if (!getVFS().exists(A->getValue()))
2588 getDriver().Diag(clang::diag::warn_missing_sysroot) << A->getValue();
2589 } else if (const char *env = ::getenv("SDKROOT")) {
2590 // We only use this value as the default if it is an absolute path,
2591 // exists, and it is not the root path.
2592 if (llvm::sys::path::is_absolute(env) && getVFS().exists(env) &&
2593 StringRef(env) != "/") {
2594 Args.append(Args.MakeSeparateArg(
2595 nullptr, Opts.getOption(options::OPT_isysroot), env));
2596 }
2597 } else {
2598 TryXcselect = !Args.hasArg(options::OPT__sysroot_EQ) &&
2599 !Args.hasArg(options::OPT_no_xcselect);
2600 }
2601
2602 // Read the SDKSettings.json file for more information, like the SDK version
2603 // that we can pass down to the compiler.
2604 SDKInfo = parseSDKSettings(getVFS(), Args, getDriver());
2605 // FIXME: If SDKInfo is std::nullopt, diagnose a bad isysroot value (e.g.
2606 // doesn't end in .sdk).
2607
2608 // The OS and the version can be specified using the -target argument.
2609 std::optional<DarwinPlatform> PlatformAndVersion =
2610 getDeploymentTargetFromTargetArg(Args, getTriple(), getDriver(), SDKInfo);
2611 if (PlatformAndVersion) {
2612 // Disallow mixing -target and -mtargetos=.
2613 if (const auto *MTargetOSArg = Args.getLastArg(options::OPT_mtargetos_EQ)) {
2614 std::string TargetArgStr = PlatformAndVersion->getAsString(Args, Opts);
2615 std::string MTargetOSArgStr = MTargetOSArg->getAsString(Args);
2616 getDriver().Diag(diag::err_drv_cannot_mix_options)
2617 << TargetArgStr << MTargetOSArgStr;
2618 }
2619 // Implicitly allow resolving the OS version when it wasn't explicitly set.
2620 bool TripleProvidedOSVersion = PlatformAndVersion->hasOSVersion();
2621 if (!TripleProvidedOSVersion)
2622 PlatformAndVersion->setOSVersion(
2623 getInferredOSVersion(getTriple().getOS(), getTriple(), getDriver()));
2624
2625 std::optional<DarwinPlatform> PlatformAndVersionFromOSVersionArg =
2626 getDeploymentTargetFromOSVersionArg(Args, getDriver());
2627 if (PlatformAndVersionFromOSVersionArg) {
2628 unsigned TargetMajor, TargetMinor, TargetMicro;
2629 bool TargetExtra;
2630 unsigned ArgMajor, ArgMinor, ArgMicro;
2631 bool ArgExtra;
2632 if (PlatformAndVersion->getPlatform() !=
2633 PlatformAndVersionFromOSVersionArg->getPlatform() ||
2635 PlatformAndVersion->getOSVersion().getAsString(), TargetMajor,
2636 TargetMinor, TargetMicro, TargetExtra) &&
2638 PlatformAndVersionFromOSVersionArg->getOSVersion().getAsString(),
2639 ArgMajor, ArgMinor, ArgMicro, ArgExtra) &&
2640 (VersionTuple(TargetMajor, TargetMinor, TargetMicro) !=
2641 VersionTuple(ArgMajor, ArgMinor, ArgMicro) ||
2642 TargetExtra != ArgExtra))) {
2643 // Select the OS version from the -m<os>-version-min argument when
2644 // the -target does not include an OS version.
2645 if (PlatformAndVersion->getPlatform() ==
2646 PlatformAndVersionFromOSVersionArg->getPlatform() &&
2647 !TripleProvidedOSVersion) {
2648 PlatformAndVersion->setOSVersion(
2649 PlatformAndVersionFromOSVersionArg->getOSVersion());
2650 } else {
2651 // Warn about -m<os>-version-min that doesn't match the OS version
2652 // that's specified in the target.
2653 std::string OSVersionArg =
2654 PlatformAndVersionFromOSVersionArg->getAsString(Args, Opts);
2655 std::string TargetArg = PlatformAndVersion->getAsString(Args, Opts);
2656 getDriver().Diag(clang::diag::warn_drv_overriding_option)
2657 << OSVersionArg << TargetArg;
2658 }
2659 }
2660 }
2661 } else if ((PlatformAndVersion = getDeploymentTargetFromMTargetOSArg(
2662 Args, getDriver(), SDKInfo))) {
2663 // The OS target can be specified using the -mtargetos= argument.
2664 // Disallow mixing -mtargetos= and -m<os>version-min=.
2665 std::optional<DarwinPlatform> PlatformAndVersionFromOSVersionArg =
2666 getDeploymentTargetFromOSVersionArg(Args, getDriver());
2667 if (PlatformAndVersionFromOSVersionArg) {
2668 std::string MTargetOSArgStr = PlatformAndVersion->getAsString(Args, Opts);
2669 std::string OSVersionArgStr =
2670 PlatformAndVersionFromOSVersionArg->getAsString(Args, Opts);
2671 getDriver().Diag(diag::err_drv_cannot_mix_options)
2672 << MTargetOSArgStr << OSVersionArgStr;
2673 }
2674 } else {
2675 // The OS target can be specified using the -m<os>version-min argument.
2676 PlatformAndVersion = getDeploymentTargetFromOSVersionArg(Args, getDriver());
2677 // If no deployment target was specified on the command line, check for
2678 // environment defines.
2679 if (!PlatformAndVersion) {
2680 PlatformAndVersion =
2681 getDeploymentTargetFromEnvironmentVariables(getDriver(), getTriple());
2682 if (PlatformAndVersion) {
2683 // Don't infer simulator from the arch when the SDK is also specified.
2684 std::optional<DarwinPlatform> SDKTarget =
2685 inferDeploymentTargetFromSDK(Args, SDKInfo);
2686 if (SDKTarget)
2687 PlatformAndVersion->setEnvironment(SDKTarget->getEnvironment());
2688 }
2689 }
2690 // If there is no command-line argument to specify the Target version and
2691 // no environment variable defined, see if we can set the default based
2692 // on -isysroot using SDKSettings.json if it exists.
2693 if (!PlatformAndVersion) {
2694 PlatformAndVersion = inferDeploymentTargetFromSDK(Args, SDKInfo);
2695 /// If the target was successfully constructed from the SDK path, try to
2696 /// infer the SDK info if the SDK doesn't have it.
2697 if (PlatformAndVersion && !SDKInfo)
2698 SDKInfo = PlatformAndVersion->inferSDKInfo();
2699 }
2700 // If no OS targets have been specified, try to guess platform from -target
2701 // or arch name and compute the version from the triple.
2702 if (!PlatformAndVersion)
2703 PlatformAndVersion =
2704 inferDeploymentTargetFromArch(Args, *this, getTriple(), getDriver());
2705 }
2706
2707 assert(PlatformAndVersion && "Unable to infer Darwin variant");
2708 if (!PlatformAndVersion->isValidOSVersion()) {
2709 if (PlatformAndVersion->isExplicitlySpecified())
2710 getDriver().Diag(diag::err_drv_invalid_version_number)
2711 << PlatformAndVersion->getAsString(Args, Opts);
2712 else
2713 getDriver().Diag(diag::err_drv_invalid_version_number_inferred)
2714 << PlatformAndVersion->getOSVersion().getAsString()
2715 << PlatformAndVersion->getInferredSource();
2716 }
2717 // After the deployment OS version has been resolved, set it to the canonical
2718 // version before further error detection and converting to a proper target
2719 // triple.
2720 VersionTuple CanonicalVersion = PlatformAndVersion->getCanonicalOSVersion();
2721 if (CanonicalVersion != PlatformAndVersion->getOSVersion()) {
2722 getDriver().Diag(diag::warn_drv_overriding_deployment_version)
2723 << PlatformAndVersion->getOSVersion().getAsString()
2724 << CanonicalVersion.getAsString();
2725 PlatformAndVersion->setOSVersion(CanonicalVersion);
2726 }
2727
2728 PlatformAndVersion->addOSVersionMinArgument(Args, Opts);
2729 DarwinPlatformKind Platform = PlatformAndVersion->getPlatform();
2730
2731 unsigned Major, Minor, Micro;
2732 bool HadExtra;
2733 // The major version should not be over this number.
2734 const unsigned MajorVersionLimit = 1000;
2735 const VersionTuple OSVersion = PlatformAndVersion->takeOSVersion();
2736 const std::string OSVersionStr = OSVersion.getAsString();
2737 // Set the tool chain target information.
2738 if (Platform == MacOS) {
2739#ifdef CLANG_USE_XCSELECT
2740 if (TryXcselect) {
2741 char *p;
2742 if (!::xcselect_host_sdk_path(CLANG_XCSELECT_HOST_SDK_POLICY, &p)) {
2743 Args.append(Args.MakeSeparateArg(
2744 nullptr, Opts.getOption(options::OPT_isysroot), p));
2745 ::free(p);
2746 if (!SDKInfo)
2747 SDKInfo = parseSDKSettings(getVFS(), Args, getDriver());
2748 }
2749 }
2750#endif
2751 if (!Driver::GetReleaseVersion(OSVersionStr, Major, Minor, Micro,
2752 HadExtra) ||
2753 HadExtra || Major < 10 || Major >= MajorVersionLimit || Minor >= 100 ||
2754 Micro >= 100)
2755 getDriver().Diag(diag::err_drv_invalid_version_number)
2756 << PlatformAndVersion->getAsString(Args, Opts);
2757 } else if (Platform == IPhoneOS) {
2758 if (!Driver::GetReleaseVersion(OSVersionStr, Major, Minor, Micro,
2759 HadExtra) ||
2760 HadExtra || Major >= MajorVersionLimit || Minor >= 100 || Micro >= 100)
2761 getDriver().Diag(diag::err_drv_invalid_version_number)
2762 << PlatformAndVersion->getAsString(Args, Opts);
2763 ;
2764 if (PlatformAndVersion->getEnvironment() == MacCatalyst &&
2765 (Major < 13 || (Major == 13 && Minor < 1))) {
2766 getDriver().Diag(diag::err_drv_invalid_version_number)
2767 << PlatformAndVersion->getAsString(Args, Opts);
2768 Major = 13;
2769 Minor = 1;
2770 Micro = 0;
2771 }
2772 // For 32-bit targets, the deployment target for iOS has to be earlier than
2773 // iOS 11.
2774 if (getTriple().isArch32Bit() && Major >= 11) {
2775 // If the deployment target is explicitly specified, print a diagnostic.
2776 if (PlatformAndVersion->isExplicitlySpecified()) {
2777 if (PlatformAndVersion->getEnvironment() == MacCatalyst)
2778 getDriver().Diag(diag::err_invalid_macos_32bit_deployment_target);
2779 else
2780 getDriver().Diag(diag::warn_invalid_ios_deployment_target)
2781 << PlatformAndVersion->getAsString(Args, Opts);
2782 // Otherwise, set it to 10.99.99.
2783 } else {
2784 Major = 10;
2785 Minor = 99;
2786 Micro = 99;
2787 }
2788 }
2789 } else if (Platform == TvOS) {
2790 if (!Driver::GetReleaseVersion(OSVersionStr, Major, Minor, Micro,
2791 HadExtra) ||
2792 HadExtra || Major >= MajorVersionLimit || Minor >= 100 || Micro >= 100)
2793 getDriver().Diag(diag::err_drv_invalid_version_number)
2794 << PlatformAndVersion->getAsString(Args, Opts);
2795 } else if (Platform == WatchOS) {
2796 if (!Driver::GetReleaseVersion(OSVersionStr, Major, Minor, Micro,
2797 HadExtra) ||
2798 HadExtra || Major >= MajorVersionLimit || Minor >= 100 || Micro >= 100)
2799 getDriver().Diag(diag::err_drv_invalid_version_number)
2800 << PlatformAndVersion->getAsString(Args, Opts);
2801 } else if (Platform == DriverKit) {
2802 if (!Driver::GetReleaseVersion(OSVersionStr, Major, Minor, Micro,
2803 HadExtra) ||
2804 HadExtra || Major < 19 || Major >= MajorVersionLimit || Minor >= 100 ||
2805 Micro >= 100)
2806 getDriver().Diag(diag::err_drv_invalid_version_number)
2807 << PlatformAndVersion->getAsString(Args, Opts);
2808 } else {
2809 if (!Driver::GetReleaseVersion(OSVersionStr, Major, Minor, Micro,
2810 HadExtra) ||
2811 HadExtra || Major < 1 || Major >= MajorVersionLimit || Minor >= 100 ||
2812 Micro >= 100)
2813 getDriver().Diag(diag::err_drv_invalid_version_number)
2814 << PlatformAndVersion->getAsString(Args, Opts);
2815 }
2816
2817 DarwinEnvironmentKind Environment = PlatformAndVersion->getEnvironment();
2818 // Recognize iOS targets with an x86 architecture as the iOS simulator.
2819 if (Environment == NativeEnvironment && Platform != MacOS &&
2820 Platform != DriverKit &&
2821 PlatformAndVersion->canInferSimulatorFromArch() && getTriple().isX86())
2822 Environment = Simulator;
2823
2824 VersionTuple ZipperedOSVersion;
2825 if (Environment == MacCatalyst)
2826 ZipperedOSVersion = PlatformAndVersion->getZipperedOSVersion();
2827 setTarget(Platform, Environment, Major, Minor, Micro, ZipperedOSVersion);
2828 TargetVariantTriple = PlatformAndVersion->getTargetVariantTriple();
2829 if (TargetVariantTriple &&
2830 !llvm::Triple::isValidVersionForOS(TargetVariantTriple->getOS(),
2831 TargetVariantTriple->getOSVersion())) {
2832 getDriver().Diag(diag::err_drv_invalid_version_number)
2833 << TargetVariantTriple->str();
2834 }
2835}
2836
2837bool DarwinClang::HasPlatformPrefix(const llvm::Triple &T) const {
2838 if (SDKInfo)
2839 return !SDKInfo->getPlatformPrefix(T).empty();
2840 else
2841 return Darwin::HasPlatformPrefix(T);
2842}
2843
2844// For certain platforms/environments almost all resources (e.g., headers) are
2845// located in sub-directories, e.g., for DriverKit they live in
2846// <SYSROOT>/System/DriverKit/usr/include (instead of <SYSROOT>/usr/include).
2848 const llvm::Triple &T) const {
2849 if (SDKInfo) {
2850 const StringRef PlatformPrefix = SDKInfo->getPlatformPrefix(T);
2851 if (!PlatformPrefix.empty())
2852 llvm::sys::path::append(Path, PlatformPrefix);
2853 } else if (T.isDriverKit()) {
2854 // The first version of DriverKit didn't have SDKSettings.json, manually add
2855 // its prefix.
2856 llvm::sys::path::append(Path, "System", "DriverKit");
2857 }
2858}
2859
2860// Returns the effective sysroot from either -isysroot or --sysroot, plus the
2861// platform prefix (if any).
2863AppleMachO::GetEffectiveSysroot(const llvm::opt::ArgList &DriverArgs) const {
2864 llvm::SmallString<128> Path("/");
2865 if (DriverArgs.hasArg(options::OPT_isysroot))
2866 Path = DriverArgs.getLastArgValue(options::OPT_isysroot);
2867 else if (!getDriver().SysRoot.empty())
2868 Path = getDriver().SysRoot;
2869
2870 if (hasEffectiveTriple()) {
2872 }
2873 return Path;
2874}
2875
2877 const llvm::opt::ArgList &DriverArgs,
2878 llvm::opt::ArgStringList &CC1Args) const {
2879 const Driver &D = getDriver();
2880
2881 llvm::SmallString<128> Sysroot = GetEffectiveSysroot(DriverArgs);
2882
2883 bool NoStdInc = DriverArgs.hasArg(options::OPT_nostdinc);
2884 bool NoStdlibInc = DriverArgs.hasArg(options::OPT_nostdlibinc);
2885 bool NoBuiltinInc = DriverArgs.hasFlag(
2886 options::OPT_nobuiltininc, options::OPT_ibuiltininc, /*Default=*/false);
2887 bool ForceBuiltinInc = DriverArgs.hasFlag(
2888 options::OPT_ibuiltininc, options::OPT_nobuiltininc, /*Default=*/false);
2889
2890 // Add <sysroot>/usr/local/include
2891 if (!NoStdInc && !NoStdlibInc) {
2892 SmallString<128> P(Sysroot);
2893 llvm::sys::path::append(P, "usr", "local", "include");
2894 addSystemInclude(DriverArgs, CC1Args, P);
2895 }
2896
2897 // Add the Clang builtin headers (<resource>/include)
2898 if (!(NoStdInc && !ForceBuiltinInc) && !NoBuiltinInc) {
2899 SmallString<128> P(D.ResourceDir);
2900 llvm::sys::path::append(P, "include");
2901 addSystemInclude(DriverArgs, CC1Args, P);
2902 }
2903
2904 if (NoStdInc || NoStdlibInc)
2905 return;
2906
2907 // Check for configure-time C include directories.
2908 llvm::StringRef CIncludeDirs(C_INCLUDE_DIRS);
2909 if (!CIncludeDirs.empty()) {
2911 CIncludeDirs.split(dirs, ":");
2912 for (llvm::StringRef dir : dirs) {
2913 llvm::StringRef Prefix =
2914 llvm::sys::path::is_absolute(dir) ? "" : llvm::StringRef(Sysroot);
2915 addExternCSystemInclude(DriverArgs, CC1Args, Prefix + dir);
2916 }
2917 } else {
2918 // Otherwise, add <sysroot>/usr/include.
2919 SmallString<128> P(Sysroot);
2920 llvm::sys::path::append(P, "usr", "include");
2921 addExternCSystemInclude(DriverArgs, CC1Args, P.str());
2922 }
2923}
2924
2926 const llvm::opt::ArgList &DriverArgs,
2927 llvm::opt::ArgStringList &CC1Args) const {
2928 AppleMachO::AddClangSystemIncludeArgs(DriverArgs, CC1Args);
2929
2930 if (DriverArgs.hasArg(options::OPT_nostdinc, options::OPT_nostdlibinc))
2931 return;
2932
2933 llvm::SmallString<128> Sysroot = GetEffectiveSysroot(DriverArgs);
2934
2935 // Add <sysroot>/System/Library/Frameworks
2936 // Add <sysroot>/System/Library/SubFrameworks
2937 // Add <sysroot>/Library/Frameworks
2938 SmallString<128> P1(Sysroot), P2(Sysroot), P3(Sysroot);
2939 llvm::sys::path::append(P1, "System", "Library", "Frameworks");
2940 llvm::sys::path::append(P2, "System", "Library", "SubFrameworks");
2941 llvm::sys::path::append(P3, "Library", "Frameworks");
2942 addSystemFrameworkIncludes(DriverArgs, CC1Args, {P1, P2, P3});
2943}
2944
2945bool DarwinClang::AddGnuCPlusPlusIncludePaths(const llvm::opt::ArgList &DriverArgs,
2946 llvm::opt::ArgStringList &CC1Args,
2948 llvm::StringRef Version,
2949 llvm::StringRef ArchDir,
2950 llvm::StringRef BitDir) const {
2951 llvm::sys::path::append(Base, Version);
2952
2953 // Add the base dir
2954 addSystemInclude(DriverArgs, CC1Args, Base);
2955
2956 // Add the multilib dirs
2957 {
2959 if (!ArchDir.empty())
2960 llvm::sys::path::append(P, ArchDir);
2961 if (!BitDir.empty())
2962 llvm::sys::path::append(P, BitDir);
2963 addSystemInclude(DriverArgs, CC1Args, P);
2964 }
2965
2966 // Add the backward dir
2967 {
2969 llvm::sys::path::append(P, "backward");
2970 addSystemInclude(DriverArgs, CC1Args, P);
2971 }
2972
2973 return getVFS().exists(Base);
2974}
2975
2977 const llvm::opt::ArgList &DriverArgs,
2978 llvm::opt::ArgStringList &CC1Args) const {
2979 // The implementation from a base class will pass through the -stdlib to
2980 // CC1Args.
2981 // FIXME: this should not be necessary, remove usages in the frontend
2982 // (e.g. HeaderSearchOptions::UseLibcxx) and don't pipe -stdlib.
2983 // Also check whether this is used for setting library search paths.
2984 ToolChain::AddClangCXXStdlibIncludeArgs(DriverArgs, CC1Args);
2985
2986 if (DriverArgs.hasArg(options::OPT_nostdinc, options::OPT_nostdlibinc,
2987 options::OPT_nostdincxx))
2988 return;
2989
2990 llvm::SmallString<128> Sysroot = GetEffectiveSysroot(DriverArgs);
2991
2992 switch (GetCXXStdlibType(DriverArgs)) {
2993 case ToolChain::CST_Libcxx: {
2994 // On Darwin, libc++ can be installed in one of the following places:
2995 // 1. Alongside the compiler in <clang-executable-folder>/../include/c++/v1
2996 // 2. In a SDK (or a custom sysroot) in <sysroot>/usr/include/c++/v1
2997 //
2998 // The precedence of paths is as listed above, i.e. we take the first path
2999 // that exists. Note that we never include libc++ twice -- we take the first
3000 // path that exists and don't send the other paths to CC1 (otherwise
3001 // include_next could break).
3002
3003 // Check for (1)
3004 // Get from '<install>/bin' to '<install>/include/c++/v1'.
3005 // Note that InstallBin can be relative, so we use '..' instead of
3006 // parent_path.
3007 llvm::SmallString<128> InstallBin(getDriver().Dir); // <install>/bin
3008 llvm::sys::path::append(InstallBin, "..", "include", "c++", "v1");
3009 if (getVFS().exists(InstallBin)) {
3010 addSystemInclude(DriverArgs, CC1Args, InstallBin);
3011 return;
3012 } else if (DriverArgs.hasArg(options::OPT_v)) {
3013 llvm::errs() << "ignoring nonexistent directory \"" << InstallBin
3014 << "\"\n";
3015 }
3016
3017 // Otherwise, check for (2)
3018 llvm::SmallString<128> SysrootUsr = Sysroot;
3019 llvm::sys::path::append(SysrootUsr, "usr", "include", "c++", "v1");
3020 if (getVFS().exists(SysrootUsr)) {
3021 addSystemInclude(DriverArgs, CC1Args, SysrootUsr);
3022 return;
3023 } else if (DriverArgs.hasArg(options::OPT_v)) {
3024 llvm::errs() << "ignoring nonexistent directory \"" << SysrootUsr
3025 << "\"\n";
3026 }
3027
3028 // Otherwise, don't add any path.
3029 break;
3030 }
3031
3033 AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args);
3034 break;
3035 }
3036}
3037
3038void AppleMachO::AddGnuCPlusPlusIncludePaths(
3039 const llvm::opt::ArgList &DriverArgs,
3040 llvm::opt::ArgStringList &CC1Args) const {}
3041
3042void DarwinClang::AddGnuCPlusPlusIncludePaths(
3043 const llvm::opt::ArgList &DriverArgs,
3044 llvm::opt::ArgStringList &CC1Args) const {
3045 llvm::SmallString<128> UsrIncludeCxx = GetEffectiveSysroot(DriverArgs);
3046 llvm::sys::path::append(UsrIncludeCxx, "usr", "include", "c++");
3047
3048 llvm::Triple::ArchType arch = getTriple().getArch();
3049 bool IsBaseFound = true;
3050 switch (arch) {
3051 default:
3052 break;
3053
3054 case llvm::Triple::x86:
3055 case llvm::Triple::x86_64:
3056 IsBaseFound = AddGnuCPlusPlusIncludePaths(
3057 DriverArgs, CC1Args, UsrIncludeCxx, "4.2.1", "i686-apple-darwin10",
3058 arch == llvm::Triple::x86_64 ? "x86_64" : "");
3059 IsBaseFound |= AddGnuCPlusPlusIncludePaths(
3060 DriverArgs, CC1Args, UsrIncludeCxx, "4.0.0", "i686-apple-darwin8", "");
3061 break;
3062
3063 case llvm::Triple::arm:
3064 case llvm::Triple::thumb:
3065 IsBaseFound =
3066 AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, UsrIncludeCxx, "4.2.1",
3067 "arm-apple-darwin10", "v7");
3068 IsBaseFound |=
3069 AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, UsrIncludeCxx, "4.2.1",
3070 "arm-apple-darwin10", "v6");
3071 break;
3072
3073 case llvm::Triple::aarch64:
3074 IsBaseFound =
3075 AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, UsrIncludeCxx, "4.2.1",
3076 "arm64-apple-darwin10", "");
3077 break;
3078 }
3079
3080 if (!IsBaseFound) {
3081 getDriver().Diag(diag::warn_drv_libstdcxx_not_found);
3082 }
3083}
3084
3085void AppleMachO::AddCXXStdlibLibArgs(const ArgList &Args,
3086 ArgStringList &CmdArgs) const {
3088
3089 switch (Type) {
3091 CmdArgs.push_back("-lc++");
3092 if (Args.hasArg(options::OPT_fexperimental_library))
3093 CmdArgs.push_back("-lc++experimental");
3094 break;
3095
3097 // Unfortunately, -lstdc++ doesn't always exist in the standard search path;
3098 // it was previously found in the gcc lib dir. However, for all the Darwin
3099 // platforms we care about it was -lstdc++.6, so we search for that
3100 // explicitly if we can't see an obvious -lstdc++ candidate.
3101
3102 // Check in the sysroot first.
3103 if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
3104 SmallString<128> P(A->getValue());
3105 llvm::sys::path::append(P, "usr", "lib", "libstdc++.dylib");
3106
3107 if (!getVFS().exists(P)) {
3108 llvm::sys::path::remove_filename(P);
3109 llvm::sys::path::append(P, "libstdc++.6.dylib");
3110 if (getVFS().exists(P)) {
3111 CmdArgs.push_back(Args.MakeArgString(P));
3112 return;
3113 }
3114 }
3115 }
3116
3117 // Otherwise, look in the root.
3118 // FIXME: This should be removed someday when we don't have to care about
3119 // 10.6 and earlier, where /usr/lib/libstdc++.dylib does not exist.
3120 if (!getVFS().exists("/usr/lib/libstdc++.dylib") &&
3121 getVFS().exists("/usr/lib/libstdc++.6.dylib")) {
3122 CmdArgs.push_back("/usr/lib/libstdc++.6.dylib");
3123 return;
3124 }
3125
3126 // Otherwise, let the linker search.
3127 CmdArgs.push_back("-lstdc++");
3128 break;
3129 }
3130}
3131
3132void DarwinClang::AddCCKextLibArgs(const ArgList &Args,
3133 ArgStringList &CmdArgs) const {
3134 // For Darwin platforms, use the compiler-rt-based support library
3135 // instead of the gcc-provided one (which is also incidentally
3136 // only present in the gcc lib dir, which makes it hard to find).
3137
3138 SmallString<128> P(getDriver().ResourceDir);
3139 llvm::sys::path::append(P, "lib", "darwin");
3140
3141 // Use the newer cc_kext for iOS ARM after 6.0.
3142 if (isTargetWatchOS()) {
3143 llvm::sys::path::append(P, "libclang_rt.cc_kext_watchos.a");
3144 } else if (isTargetTvOS()) {
3145 llvm::sys::path::append(P, "libclang_rt.cc_kext_tvos.a");
3146 } else if (isTargetIPhoneOS()) {
3147 llvm::sys::path::append(P, "libclang_rt.cc_kext_ios.a");
3148 } else if (isTargetDriverKit()) {
3149 // DriverKit doesn't want extra runtime support.
3150 } else if (isTargetXROSDevice()) {
3151 llvm::sys::path::append(
3152 P, llvm::Twine("libclang_rt.cc_kext_") +
3153 llvm::Triple::getOSTypeName(llvm::Triple::XROS) + ".a");
3154 } else {
3155 llvm::sys::path::append(P, "libclang_rt.cc_kext.a");
3156 }
3157
3158 // For now, allow missing resource libraries to support developers who may
3159 // not have compiler-rt checked out or integrated into their build.
3160 if (getVFS().exists(P))
3161 CmdArgs.push_back(Args.MakeArgString(P));
3162}
3163
3164DerivedArgList *MachO::TranslateArgs(const DerivedArgList &Args,
3165 StringRef BoundArch,
3166 Action::OffloadKind) const {
3167 DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
3168 const OptTable &Opts = getDriver().getOpts();
3169
3170 // FIXME: We really want to get out of the tool chain level argument
3171 // translation business, as it makes the driver functionality much
3172 // more opaque. For now, we follow gcc closely solely for the
3173 // purpose of easily achieving feature parity & testability. Once we
3174 // have something that works, we should reevaluate each translation
3175 // and try to push it down into tool specific logic.
3176
3177 for (Arg *A : Args) {
3178 // Sob. These is strictly gcc compatible for the time being. Apple
3179 // gcc translates options twice, which means that self-expanding
3180 // options add duplicates.
3181 switch ((options::ID)A->getOption().getID()) {
3182 default:
3183 DAL->append(A);
3184 break;
3185
3186 case options::OPT_mkernel:
3187 case options::OPT_fapple_kext:
3188 DAL->append(A);
3189 DAL->AddFlagArg(A, Opts.getOption(options::OPT_static));
3190 break;
3191
3192 case options::OPT_dependency_file:
3193 DAL->AddSeparateArg(A, Opts.getOption(options::OPT_MF), A->getValue());
3194 break;
3195
3196 case options::OPT_gfull:
3197 DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
3198 DAL->AddFlagArg(
3199 A, Opts.getOption(options::OPT_fno_eliminate_unused_debug_symbols));
3200 break;
3201
3202 case options::OPT_gused:
3203 DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
3204 DAL->AddFlagArg(
3205 A, Opts.getOption(options::OPT_feliminate_unused_debug_symbols));
3206 break;
3207
3208 case options::OPT_shared:
3209 DAL->AddFlagArg(A, Opts.getOption(options::OPT_dynamiclib));
3210 break;
3211
3212 case options::OPT_fconstant_cfstrings:
3213 DAL->AddFlagArg(A, Opts.getOption(options::OPT_mconstant_cfstrings));
3214 break;
3215
3216 case options::OPT_fno_constant_cfstrings:
3217 DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_constant_cfstrings));
3218 break;
3219
3220 case options::OPT_Wnonportable_cfstrings:
3221 DAL->AddFlagArg(A,
3222 Opts.getOption(options::OPT_mwarn_nonportable_cfstrings));
3223 break;
3224
3225 case options::OPT_Wno_nonportable_cfstrings:
3226 DAL->AddFlagArg(
3227 A, Opts.getOption(options::OPT_mno_warn_nonportable_cfstrings));
3228 break;
3229 }
3230 }
3231
3232 // Add the arch options based on the particular spelling of -arch, to match
3233 // how the driver works.
3234 if (!BoundArch.empty()) {
3235 StringRef Name = BoundArch;
3236 const Option MCpu = Opts.getOption(options::OPT_mcpu_EQ);
3237 const Option MArch = Opts.getOption(options::OPT_march_EQ);
3238
3239 // This code must be kept in sync with LLVM's getArchTypeForDarwinArch,
3240 // which defines the list of which architectures we accept.
3241 if (Name == "ppc")
3242 ;
3243 else if (Name == "ppc601")
3244 DAL->AddJoinedArg(nullptr, MCpu, "601");
3245 else if (Name == "ppc603")
3246 DAL->AddJoinedArg(nullptr, MCpu, "603");
3247 else if (Name == "ppc604")
3248 DAL->AddJoinedArg(nullptr, MCpu, "604");
3249 else if (Name == "ppc604e")
3250 DAL->AddJoinedArg(nullptr, MCpu, "604e");
3251 else if (Name == "ppc750")
3252 DAL->AddJoinedArg(nullptr, MCpu, "750");
3253 else if (Name == "ppc7400")
3254 DAL->AddJoinedArg(nullptr, MCpu, "7400");
3255 else if (Name == "ppc7450")
3256 DAL->AddJoinedArg(nullptr, MCpu, "7450");
3257 else if (Name == "ppc970")
3258 DAL->AddJoinedArg(nullptr, MCpu, "970");
3259
3260 else if (Name == "ppc64" || Name == "ppc64le")
3261 DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64));
3262
3263 else if (Name == "i386")
3264 ;
3265 else if (Name == "i486")
3266 DAL->AddJoinedArg(nullptr, MArch, "i486");
3267 else if (Name == "i586")
3268 DAL->AddJoinedArg(nullptr, MArch, "i586");
3269 else if (Name == "i686")
3270 DAL->AddJoinedArg(nullptr, MArch, "i686");
3271 else if (Name == "pentium")
3272 DAL->AddJoinedArg(nullptr, MArch, "pentium");
3273 else if (Name == "pentium2")
3274 DAL->AddJoinedArg(nullptr, MArch, "pentium2");
3275 else if (Name == "pentpro")
3276 DAL->AddJoinedArg(nullptr, MArch, "pentiumpro");
3277 else if (Name == "pentIIm3")
3278 DAL->AddJoinedArg(nullptr, MArch, "pentium2");
3279
3280 else if (Name == "x86_64" || Name == "x86_64h")
3281 DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64));
3282
3283 else if (Name == "arm")
3284 DAL->AddJoinedArg(nullptr, MArch, "armv4t");
3285 else if (Name == "armv4t")
3286 DAL->AddJoinedArg(nullptr, MArch, "armv4t");
3287 else if (Name == "armv5")
3288 DAL->AddJoinedArg(nullptr, MArch, "armv5tej");
3289 else if (Name == "xscale")
3290 DAL->AddJoinedArg(nullptr, MArch, "xscale");
3291 else if (Name == "armv6")
3292 DAL->AddJoinedArg(nullptr, MArch, "armv6k");
3293 else if (Name == "armv6m")
3294 DAL->AddJoinedArg(nullptr, MArch, "armv6m");
3295 else if (Name == "armv7")
3296 DAL->AddJoinedArg(nullptr, MArch, "armv7a");
3297 else if (Name == "armv7em")
3298 DAL->AddJoinedArg(nullptr, MArch, "armv7em");
3299 else if (Name == "armv7k")
3300 DAL->AddJoinedArg(nullptr, MArch, "armv7k");
3301 else if (Name == "armv7m")
3302 DAL->AddJoinedArg(nullptr, MArch, "armv7m");
3303 else if (Name == "armv7s")
3304 DAL->AddJoinedArg(nullptr, MArch, "armv7s");
3305 else if (Name == "armv8-m.base" || Name == "armv8m.base")
3306 DAL->AddJoinedArg(nullptr, MArch, "armv8m.base");
3307 else if (Name == "armv8-m.main" || Name == "armv8m.main")
3308 DAL->AddJoinedArg(nullptr, MArch, "armv8m.main");
3309 else if (Name == "armv8.1-m.main" || Name == "armv8.1m.main")
3310 DAL->AddJoinedArg(nullptr, MArch, "armv8.1m.main");
3311 }
3312
3313 return DAL;
3314}
3315
3316void MachO::AddLinkRuntimeLibArgs(const ArgList &Args,
3317 ArgStringList &CmdArgs,
3318 bool ForceLinkBuiltinRT) const {
3319 // Embedded targets are simple at the moment, not supporting sanitizers and
3320 // with different libraries for each member of the product { static, PIC } x
3321 // { hard-float, soft-float }
3322 llvm::SmallString<32> CompilerRT = StringRef("");
3323 CompilerRT +=
3325 ? "hard"
3326 : "soft";
3327 CompilerRT += Args.hasArg(options::OPT_fPIC) ? "_pic" : "_static";
3328
3329 AddLinkRuntimeLib(Args, CmdArgs, CompilerRT, RLO_IsEmbedded);
3330}
3331
3333 llvm::Triple::OSType OS;
3334
3335 if (isTargetMacCatalyst())
3336 return TargetVersion < alignedAllocMinVersion(llvm::Triple::MacOSX);
3337 switch (TargetPlatform) {
3338 case MacOS: // Earlier than 10.13.
3339 OS = llvm::Triple::MacOSX;
3340 break;
3341 case IPhoneOS:
3342 OS = llvm::Triple::IOS;
3343 break;
3344 case TvOS: // Earlier than 11.0.
3345 OS = llvm::Triple::TvOS;
3346 break;
3347 case WatchOS: // Earlier than 4.0.
3348 OS = llvm::Triple::WatchOS;
3349 break;
3350 default: // Always available on newer platforms.
3351 return false;
3352 }
3353
3355}
3356
3357static bool
3358sdkSupportsBuiltinModules(const std::optional<DarwinSDKInfo> &SDKInfo) {
3359 if (!SDKInfo)
3360 // If there is no SDK info, assume this is building against an SDK that
3361 // predates SDKSettings.json. None of those support builtin modules.
3362 return false;
3363
3364 switch (SDKInfo->getEnvironment()) {
3365 case llvm::Triple::UnknownEnvironment:
3366 case llvm::Triple::Simulator:
3367 case llvm::Triple::MacABI:
3368 // Standard xnu/Mach/Darwin based environments depend on the SDK version.
3369 break;
3370
3371 default:
3372 // All other environments support builtin modules from the start.
3373 return true;
3374 }
3375
3376 VersionTuple SDKVersion = SDKInfo->getVersion();
3377 switch (SDKInfo->getOS()) {
3378 // Existing SDKs added support for builtin modules in the fall
3379 // 2024 major releases.
3380 case llvm::Triple::MacOSX:
3381 return SDKVersion >= VersionTuple(15U);
3382 case llvm::Triple::IOS:
3383 return SDKVersion >= VersionTuple(18U);
3384 case llvm::Triple::TvOS:
3385 return SDKVersion >= VersionTuple(18U);
3386 case llvm::Triple::WatchOS:
3387 return SDKVersion >= VersionTuple(11U);
3388 case llvm::Triple::XROS:
3389 return SDKVersion >= VersionTuple(2U);
3390
3391 // New SDKs support builtin modules from the start.
3392 default:
3393 return true;
3394 }
3395}
3396
3397static inline llvm::VersionTuple
3398sizedDeallocMinVersion(llvm::Triple::OSType OS) {
3399 switch (OS) {
3400 default:
3401 break;
3402 case llvm::Triple::Darwin:
3403 case llvm::Triple::MacOSX: // Earliest supporting version is 10.12.
3404 return llvm::VersionTuple(10U, 12U);
3405 case llvm::Triple::IOS:
3406 case llvm::Triple::TvOS: // Earliest supporting version is 10.0.0.
3407 return llvm::VersionTuple(10U);
3408 case llvm::Triple::WatchOS: // Earliest supporting version is 3.0.0.
3409 return llvm::VersionTuple(3U);
3410 }
3411
3412 llvm_unreachable("Unexpected OS");
3413}
3414
3416 llvm::Triple::OSType OS;
3417
3418 if (isTargetMacCatalyst())
3419 return TargetVersion < sizedDeallocMinVersion(llvm::Triple::MacOSX);
3420 switch (TargetPlatform) {
3421 case MacOS: // Earlier than 10.12.
3422 OS = llvm::Triple::MacOSX;
3423 break;
3424 case IPhoneOS:
3425 OS = llvm::Triple::IOS;
3426 break;
3427 case TvOS: // Earlier than 10.0.
3428 OS = llvm::Triple::TvOS;
3429 break;
3430 case WatchOS: // Earlier than 3.0.
3431 OS = llvm::Triple::WatchOS;
3432 break;
3433 default:
3434 // Always available on newer platforms.
3435 return false;
3436 }
3437
3439}
3440
3441void MachO::addClangTargetOptions(const llvm::opt::ArgList &DriverArgs,
3442 llvm::opt::ArgStringList &CC1Args,
3443 llvm::StringRef BoundArch,
3444 Action::OffloadKind DeviceOffloadKind) const {
3445
3446 ToolChain::addClangTargetOptions(DriverArgs, CC1Args, BoundArch,
3447 DeviceOffloadKind);
3448
3449 // On arm64e, we enable all the features required for the Darwin userspace
3450 // ABI
3451 if (getTriple().isArm64e()) {
3452 // Core platform ABI
3453 if (!DriverArgs.hasArg(options::OPT_fptrauth_calls,
3454 options::OPT_fno_ptrauth_calls))
3455 CC1Args.push_back("-fptrauth-calls");
3456 if (!DriverArgs.hasArg(options::OPT_fptrauth_returns,
3457 options::OPT_fno_ptrauth_returns))
3458 CC1Args.push_back("-fptrauth-returns");
3459 if (!DriverArgs.hasArg(options::OPT_fptrauth_intrinsics,
3460 options::OPT_fno_ptrauth_intrinsics))
3461 CC1Args.push_back("-fptrauth-intrinsics");
3462 if (!DriverArgs.hasArg(options::OPT_fptrauth_indirect_gotos,
3463 options::OPT_fno_ptrauth_indirect_gotos))
3464 CC1Args.push_back("-fptrauth-indirect-gotos");
3465 if (!DriverArgs.hasArg(options::OPT_fptrauth_auth_traps,
3466 options::OPT_fno_ptrauth_auth_traps))
3467 CC1Args.push_back("-fptrauth-auth-traps");
3468
3469 // C++ v-table ABI
3470 if (!DriverArgs.hasArg(
3471 options::OPT_fptrauth_vtable_pointer_address_discrimination,
3472 options::OPT_fno_ptrauth_vtable_pointer_address_discrimination))
3473 CC1Args.push_back("-fptrauth-vtable-pointer-address-discrimination");
3474 if (!DriverArgs.hasArg(
3475 options::OPT_fptrauth_vtable_pointer_type_discrimination,
3476 options::OPT_fno_ptrauth_vtable_pointer_type_discrimination))
3477 CC1Args.push_back("-fptrauth-vtable-pointer-type-discrimination");
3478
3479 // Objective-C ABI
3480 if (!DriverArgs.hasArg(options::OPT_fptrauth_objc_isa,
3481 options::OPT_fno_ptrauth_objc_isa))
3482 CC1Args.push_back("-fptrauth-objc-isa");
3483 if (!DriverArgs.hasArg(options::OPT_fptrauth_objc_class_ro,
3484 options::OPT_fno_ptrauth_objc_class_ro))
3485 CC1Args.push_back("-fptrauth-objc-class-ro");
3486 if (!DriverArgs.hasArg(options::OPT_fptrauth_objc_interface_sel,
3487 options::OPT_fno_ptrauth_objc_interface_sel))
3488 CC1Args.push_back("-fptrauth-objc-interface-sel");
3489 }
3490}
3491
3493 const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args,
3494 llvm::StringRef BoundArch, Action::OffloadKind DeviceOffloadKind) const {
3495
3496 MachO::addClangTargetOptions(DriverArgs, CC1Args, BoundArch,
3497 DeviceOffloadKind);
3498
3499 // When compiling device code (e.g. SPIR-V for HIP), skip host-specific
3500 // flags like -faligned-alloc-unavailable and -fno-sized-deallocation
3501 // that depend on the host OS version and are irrelevant to device code.
3502 if (DeviceOffloadKind != Action::OFK_None)
3503 return;
3504
3505 // Pass "-faligned-alloc-unavailable" only when the user hasn't manually
3506 // enabled or disabled aligned allocations.
3507 if (!DriverArgs.hasArgNoClaim(options::OPT_faligned_allocation,
3508 options::OPT_fno_aligned_allocation) &&
3510 CC1Args.push_back("-faligned-alloc-unavailable");
3511
3512 // Enable objc_msgSend selector stubs by default if the linker supports it.
3513 // ld64-811.2+ does, for arm64, arm64e, and arm64_32.
3514 if (!DriverArgs.hasArgNoClaim(options::OPT_fobjc_msgsend_selector_stubs,
3515 options::OPT_fno_objc_msgsend_selector_stubs) &&
3516 getTriple().isAArch64() &&
3517 (getLinkerVersion(DriverArgs) >= VersionTuple(811, 2)))
3518 CC1Args.push_back("-fobjc-msgsend-selector-stubs");
3519
3520 // Enable objc_msgSend class selector stubs by default if the linker supports
3521 // it. ld64-1250+ does, for arm64, arm64e, and arm64_32.
3522 if (!DriverArgs.hasArgNoClaim(
3523 options::OPT_fobjc_msgsend_class_selector_stubs,
3524 options::OPT_fno_objc_msgsend_class_selector_stubs) &&
3525 getTriple().isAArch64() &&
3526 (getLinkerVersion(DriverArgs) >= VersionTuple(1250, 0)))
3527 CC1Args.push_back("-fobjc-msgsend-class-selector-stubs");
3528
3529 // Pass "-fno-sized-deallocation" only when the user hasn't manually enabled
3530 // or disabled sized deallocations.
3531 if (!DriverArgs.hasArgNoClaim(options::OPT_fsized_deallocation,
3532 options::OPT_fno_sized_deallocation) &&
3534 CC1Args.push_back("-fno-sized-deallocation");
3535
3536 addClangCC1ASTargetOptions(DriverArgs, CC1Args);
3537
3538 if (SDKInfo) {
3539 // Make the SDKSettings.json an explicit dependency for the compiler
3540 // invocation, in case the compiler needs to read it to remap versions.
3541 if (!SDKInfo->getFilePath().empty()) {
3542 SmallString<64> ExtraDepOpt("-fdepfile-entry=");
3543 ExtraDepOpt += SDKInfo->getFilePath();
3544 CC1Args.push_back(DriverArgs.MakeArgString(ExtraDepOpt));
3545 }
3546 }
3547
3548 // Enable compatibility mode for NSItemProviderCompletionHandler in
3549 // Foundation/NSItemProvider.h.
3550 CC1Args.push_back("-fcompatibility-qualified-id-block-type-checking");
3551
3552 // Give static local variables in inline functions hidden visibility when
3553 // -fvisibility-inlines-hidden is enabled.
3554 if (!DriverArgs.getLastArgNoClaim(
3555 options::OPT_fvisibility_inlines_hidden_static_local_var,
3556 options::OPT_fno_visibility_inlines_hidden_static_local_var))
3557 CC1Args.push_back("-fvisibility-inlines-hidden-static-local-var");
3558
3559 // Earlier versions of the darwin SDK have the C standard library headers
3560 // all together in the Darwin module. That leads to module cycles with
3561 // the _Builtin_ modules. e.g. <inttypes.h> on darwin includes <stdint.h>.
3562 // The builtin <stdint.h> include-nexts <stdint.h>. When both of those
3563 // darwin headers are in the Darwin module, there's a module cycle Darwin ->
3564 // _Builtin_stdint -> Darwin (i.e. inttypes.h (darwin) -> stdint.h (builtin) ->
3565 // stdint.h (darwin)). This is fixed in later versions of the darwin SDK,
3566 // but until then, the builtin headers need to join the system modules.
3567 // i.e. when the builtin stdint.h is in the Darwin module too, the cycle
3568 // goes away. Note that -fbuiltin-headers-in-system-modules does nothing
3569 // to fix the same problem with C++ headers, and is generally fragile.
3571 CC1Args.push_back("-fbuiltin-headers-in-system-modules");
3572
3573 if (!DriverArgs.hasArgNoClaim(options::OPT_fdefine_target_os_macros,
3574 options::OPT_fno_define_target_os_macros))
3575 CC1Args.push_back("-fdefine-target-os-macros");
3576
3577 // Disable subdirectory modulemap search on sufficiently recent SDKs.
3578 if (SDKInfo &&
3579 !DriverArgs.hasFlag(options::OPT_fmodulemap_allow_subdirectory_search,
3580 options::OPT_fno_modulemap_allow_subdirectory_search,
3581 false)) {
3582 bool RequiresSubdirectorySearch;
3583 VersionTuple SDKVersion = SDKInfo->getVersion();
3584 switch (TargetPlatform) {
3585 default:
3586 RequiresSubdirectorySearch = true;
3587 break;
3588 case MacOS:
3589 RequiresSubdirectorySearch = SDKVersion < VersionTuple(15, 0);
3590 break;
3591 case IPhoneOS:
3592 case TvOS:
3593 RequiresSubdirectorySearch = SDKVersion < VersionTuple(18, 0);
3594 break;
3595 case WatchOS:
3596 RequiresSubdirectorySearch = SDKVersion < VersionTuple(11, 0);
3597 break;
3598 case XROS:
3599 RequiresSubdirectorySearch = SDKVersion < VersionTuple(2, 0);
3600 break;
3601 }
3602 if (!RequiresSubdirectorySearch)
3603 CC1Args.push_back("-fno-modulemap-allow-subdirectory-search");
3604 }
3605}
3606
3608 const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CC1ASArgs) const {
3609 if (TargetVariantTriple) {
3610 CC1ASArgs.push_back("-darwin-target-variant-triple");
3611 CC1ASArgs.push_back(Args.MakeArgString(TargetVariantTriple->getTriple()));
3612 }
3613
3614 if (SDKInfo) {
3615 /// Pass the SDK version to the compiler when the SDK information is
3616 /// available.
3617 auto EmitTargetSDKVersionArg = [&](const VersionTuple &V) {
3618 std::string Arg;
3619 llvm::raw_string_ostream OS(Arg);
3620 OS << "-target-sdk-version=" << V;
3621 CC1ASArgs.push_back(Args.MakeArgString(Arg));
3622 };
3623
3624 if (isTargetMacCatalyst()) {
3625 if (const auto *MacOStoMacCatalystMapping = SDKInfo->getVersionMapping(
3627 std::optional<VersionTuple> SDKVersion = MacOStoMacCatalystMapping->map(
3629 std::nullopt);
3630 EmitTargetSDKVersionArg(
3631 SDKVersion ? *SDKVersion : minimumMacCatalystDeploymentTarget());
3632 }
3633 } else {
3634 EmitTargetSDKVersionArg(SDKInfo->getVersion());
3635 }
3636
3637 /// Pass the target variant SDK version to the compiler when the SDK
3638 /// information is available and is required for target variant.
3639 if (TargetVariantTriple) {
3640 if (isTargetMacCatalyst()) {
3641 std::string Arg;
3642 llvm::raw_string_ostream OS(Arg);
3643 OS << "-darwin-target-variant-sdk-version=" << SDKInfo->getVersion();
3644 CC1ASArgs.push_back(Args.MakeArgString(Arg));
3645 } else if (const auto *MacOStoMacCatalystMapping =
3646 SDKInfo->getVersionMapping(
3648 if (std::optional<VersionTuple> SDKVersion =
3649 MacOStoMacCatalystMapping->map(
3651 std::nullopt)) {
3652 std::string Arg;
3653 llvm::raw_string_ostream OS(Arg);
3654 OS << "-darwin-target-variant-sdk-version=" << *SDKVersion;
3655 CC1ASArgs.push_back(Args.MakeArgString(Arg));
3656 }
3657 }
3658 }
3659 }
3660}
3661
3662DerivedArgList *
3663Darwin::TranslateArgs(const DerivedArgList &Args, StringRef BoundArch,
3664 Action::OffloadKind DeviceOffloadKind) const {
3665 // First get the generic Apple args, before moving onto Darwin-specific ones.
3666 DerivedArgList *DAL =
3667 MachO::TranslateArgs(Args, BoundArch, DeviceOffloadKind);
3668
3669 // If no architecture is bound, none of the translations here are relevant.
3670 if (BoundArch.empty())
3671 return DAL;
3672
3673 // Add an explicit version min argument for the deployment target. We do this
3674 // after argument translation because -Xarch_ arguments may add a version min
3675 // argument.
3676 AddDeploymentTarget(*DAL);
3677
3678 // For iOS 6, undo the translation to add -static for -mkernel/-fapple-kext.
3679 // FIXME: It would be far better to avoid inserting those -static arguments,
3680 // but we can't check the deployment target in the translation code until
3681 // it is set here.
3683 (isTargetIOSBased() && !isIPhoneOSVersionLT(6, 0))) {
3684 for (ArgList::iterator it = DAL->begin(), ie = DAL->end(); it != ie; ) {
3685 Arg *A = *it;
3686 ++it;
3687 if (A->getOption().getID() != options::OPT_mkernel &&
3688 A->getOption().getID() != options::OPT_fapple_kext)
3689 continue;
3690 assert(it != ie && "unexpected argument translation");
3691 A = *it;
3692 assert(A->getOption().getID() == options::OPT_static &&
3693 "missing expected -static argument");
3694 *it = nullptr;
3695 ++it;
3696 }
3697 }
3698
3700 if ((Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb)) {
3701 if (Args.hasFlag(options::OPT_fomit_frame_pointer,
3702 options::OPT_fno_omit_frame_pointer, false))
3703 getDriver().Diag(clang::diag::warn_drv_unsupported_opt_for_target)
3704 << "-fomit-frame-pointer" << BoundArch;
3705 }
3706
3707 return DAL;
3708}
3709
3711 // Unwind tables are not emitted if -fno-exceptions is supplied (except when
3712 // targeting x86_64).
3713 if (getArch() == llvm::Triple::x86_64 ||
3714 (GetExceptionModel(Args) != llvm::ExceptionHandling::SjLj &&
3715 Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
3716 true)))
3717 return (getArch() == llvm::Triple::aarch64 ||
3718 getArch() == llvm::Triple::aarch64_32)
3721
3723}
3724
3726 if (const char *S = ::getenv("RC_DEBUG_OPTIONS"))
3727 return S[0] != '\0';
3728 return false;
3729}
3730
3732 if (const char *S = ::getenv("RC_DEBUG_PREFIX_MAP"))
3733 return S;
3734 return {};
3735}
3736
3737llvm::ExceptionHandling Darwin::GetExceptionModel(const ArgList &Args) const {
3738 // Darwin uses SjLj exceptions on ARM.
3739 if (getTriple().getArch() != llvm::Triple::arm &&
3740 getTriple().getArch() != llvm::Triple::thumb)
3741 return llvm::ExceptionHandling::None;
3742
3743 // Only watchOS uses the new DWARF/Compact unwinding method.
3744 llvm::Triple Triple(ComputeLLVMTriple(Args));
3745 if (Triple.isWatchABI())
3746 return llvm::ExceptionHandling::DwarfCFI;
3747
3748 return llvm::ExceptionHandling::SjLj;
3749}
3750
3752 assert(TargetInitialized && "Target not initialized!");
3754 return false;
3755 return true;
3756}
3757
3758bool MachO::isPICDefault() const { return true; }
3759
3760bool MachO::isPIEDefault(const llvm::opt::ArgList &Args) const { return false; }
3761
3763 return (getArch() == llvm::Triple::x86_64 ||
3764 getArch() == llvm::Triple::aarch64);
3765}
3766
3768 // Profiling instrumentation is only supported on x86.
3769 return getTriple().isX86();
3770}
3771
3772void Darwin::addMinVersionArgs(const ArgList &Args,
3773 ArgStringList &CmdArgs) const {
3774 VersionTuple TargetVersion = getTripleTargetVersion();
3775
3776 assert(!isTargetXROS() && "xrOS always uses -platform-version");
3777
3778 if (isTargetWatchOS())
3779 CmdArgs.push_back("-watchos_version_min");
3780 else if (isTargetWatchOSSimulator())
3781 CmdArgs.push_back("-watchos_simulator_version_min");
3782 else if (isTargetTvOS())
3783 CmdArgs.push_back("-tvos_version_min");
3784 else if (isTargetTvOSSimulator())
3785 CmdArgs.push_back("-tvos_simulator_version_min");
3786 else if (isTargetDriverKit())
3787 CmdArgs.push_back("-driverkit_version_min");
3788 else if (isTargetIOSSimulator())
3789 CmdArgs.push_back("-ios_simulator_version_min");
3790 else if (isTargetIOSBased())
3791 CmdArgs.push_back("-iphoneos_version_min");
3792 else if (isTargetMacCatalyst())
3793 CmdArgs.push_back("-maccatalyst_version_min");
3794 else {
3795 assert(isTargetMacOS() && "unexpected target");
3796 CmdArgs.push_back("-macosx_version_min");
3797 }
3798
3799 VersionTuple MinTgtVers = getEffectiveTriple().getMinimumSupportedOSVersion();
3800 if (!MinTgtVers.empty() && MinTgtVers > TargetVersion)
3801 TargetVersion = MinTgtVers;
3802 CmdArgs.push_back(Args.MakeArgString(TargetVersion.getAsString()));
3803 if (TargetVariantTriple) {
3804 assert(isTargetMacOSBased() && "unexpected target");
3805 VersionTuple VariantTargetVersion;
3806 if (TargetVariantTriple->isMacOSX()) {
3807 CmdArgs.push_back("-macosx_version_min");
3808 TargetVariantTriple->getMacOSXVersion(VariantTargetVersion);
3809 } else {
3810 assert(TargetVariantTriple->isiOS() &&
3811 TargetVariantTriple->isMacCatalystEnvironment() &&
3812 "unexpected target variant triple");
3813 CmdArgs.push_back("-maccatalyst_version_min");
3814 VariantTargetVersion = TargetVariantTriple->getiOSVersion();
3815 }
3816 VersionTuple MinTgtVers =
3817 TargetVariantTriple->getMinimumSupportedOSVersion();
3818 if (MinTgtVers.getMajor() && MinTgtVers > VariantTargetVersion)
3819 VariantTargetVersion = MinTgtVers;
3820 CmdArgs.push_back(Args.MakeArgString(VariantTargetVersion.getAsString()));
3821 }
3822}
3823
3825 Darwin::DarwinEnvironmentKind Environment) {
3826 switch (Platform) {
3827 case Darwin::MacOS:
3828 return "macos";
3829 case Darwin::IPhoneOS:
3830 if (Environment == Darwin::MacCatalyst)
3831 return "mac catalyst";
3832 return "ios";
3833 case Darwin::TvOS:
3834 return "tvos";
3835 case Darwin::WatchOS:
3836 return "watchos";
3837 case Darwin::XROS:
3838 return "xros";
3839 case Darwin::DriverKit:
3840 return "driverkit";
3841 default:
3842 break;
3843 }
3844 llvm_unreachable("invalid platform");
3845}
3846
3847void Darwin::addPlatformVersionArgs(const llvm::opt::ArgList &Args,
3848 llvm::opt::ArgStringList &CmdArgs) const {
3849 // Firmware doesn't use -platform_version.
3851 return MachO::addPlatformVersionArgs(Args, CmdArgs);
3852
3853 auto EmitPlatformVersionArg =
3854 [&](const VersionTuple &TV, Darwin::DarwinPlatformKind TargetPlatform,
3856 const llvm::Triple &TT) {
3857 // -platform_version <platform> <target_version> <sdk_version>
3858 // Both the target and SDK version support only up to 3 components.
3859 CmdArgs.push_back("-platform_version");
3860 std::string PlatformName =
3863 PlatformName += "-simulator";
3864 CmdArgs.push_back(Args.MakeArgString(PlatformName));
3865 VersionTuple TargetVersion = TV.withoutBuild();
3868 getTriple().getArchName() == "arm64e" &&
3869 TargetVersion.getMajor() < 14) {
3870 // arm64e slice is supported on iOS/tvOS 14+ only.
3871 TargetVersion = VersionTuple(14, 0);
3872 }
3873 VersionTuple MinTgtVers = TT.getMinimumSupportedOSVersion();
3874 if (!MinTgtVers.empty() && MinTgtVers > TargetVersion)
3875 TargetVersion = MinTgtVers;
3876 CmdArgs.push_back(Args.MakeArgString(TargetVersion.getAsString()));
3877
3879 // Mac Catalyst programs must use the appropriate iOS SDK version
3880 // that corresponds to the macOS SDK version used for the compilation.
3881 std::optional<VersionTuple> iOSSDKVersion;
3882 if (SDKInfo) {
3883 if (const auto *MacOStoMacCatalystMapping =
3884 SDKInfo->getVersionMapping(
3886 iOSSDKVersion = MacOStoMacCatalystMapping->map(
3887 SDKInfo->getVersion().withoutBuild(),
3888 minimumMacCatalystDeploymentTarget(), std::nullopt);
3889 }
3890 }
3891 CmdArgs.push_back(Args.MakeArgString(
3892 (iOSSDKVersion ? *iOSSDKVersion
3894 .getAsString()));
3895 return;
3896 }
3897
3898 if (SDKInfo) {
3899 VersionTuple SDKVersion = SDKInfo->getVersion().withoutBuild();
3900 if (!SDKVersion.getMinor())
3901 SDKVersion = VersionTuple(SDKVersion.getMajor(), 0);
3902 CmdArgs.push_back(Args.MakeArgString(SDKVersion.getAsString()));
3903 } else {
3904 // Use an SDK version that's matching the deployment target if the SDK
3905 // version is missing. This is preferred over an empty SDK version
3906 // (0.0.0) as the system's runtime might expect the linked binary to
3907 // contain a valid SDK version in order for the binary to work
3908 // correctly. It's reasonable to use the deployment target version as
3909 // a proxy for the SDK version because older SDKs don't guarantee
3910 // support for deployment targets newer than the SDK versions, so that
3911 // rules out using some predetermined older SDK version, which leaves
3912 // the deployment target version as the only reasonable choice.
3913 CmdArgs.push_back(Args.MakeArgString(TargetVersion.getAsString()));
3914 }
3915 };
3916 EmitPlatformVersionArg(getTripleTargetVersion(), TargetPlatform,
3919 return;
3922 VersionTuple TargetVariantVersion;
3923 if (TargetVariantTriple->isMacOSX()) {
3924 TargetVariantTriple->getMacOSXVersion(TargetVariantVersion);
3925 Platform = Darwin::MacOS;
3926 Environment = Darwin::NativeEnvironment;
3927 } else {
3928 assert(TargetVariantTriple->isiOS() &&
3929 TargetVariantTriple->isMacCatalystEnvironment() &&
3930 "unexpected target variant triple");
3931 TargetVariantVersion = TargetVariantTriple->getiOSVersion();
3932 Platform = Darwin::IPhoneOS;
3933 Environment = Darwin::MacCatalyst;
3934 }
3935 EmitPlatformVersionArg(TargetVariantVersion, Platform, Environment,
3937}
3938
3939// Add additional link args for the -dynamiclib option.
3940static void addDynamicLibLinkArgs(const Darwin &D, const ArgList &Args,
3941 ArgStringList &CmdArgs) {
3942 // Derived from darwin_dylib1 spec.
3943 if (D.isTargetIPhoneOS()) {
3944 if (D.isIPhoneOSVersionLT(3, 1))
3945 CmdArgs.push_back("-ldylib1.o");
3946 return;
3947 }
3948
3949 if (!D.isTargetMacOS())
3950 return;
3951 if (D.isMacosxVersionLT(10, 5))
3952 CmdArgs.push_back("-ldylib1.o");
3953 else if (D.isMacosxVersionLT(10, 6))
3954 CmdArgs.push_back("-ldylib1.10.5.o");
3955}
3956
3957// Add additional link args for the -bundle option.
3958static void addBundleLinkArgs(const Darwin &D, const ArgList &Args,
3959 ArgStringList &CmdArgs) {
3960 if (Args.hasArg(options::OPT_static))
3961 return;
3962 // Derived from darwin_bundle1 spec.
3963 if ((D.isTargetIPhoneOS() && D.isIPhoneOSVersionLT(3, 1)) ||
3964 (D.isTargetMacOS() && D.isMacosxVersionLT(10, 6)))
3965 CmdArgs.push_back("-lbundle1.o");
3966}
3967
3968// Add additional link args for the -pg option.
3969static void addPgProfilingLinkArgs(const Darwin &D, const ArgList &Args,
3970 ArgStringList &CmdArgs) {
3971 if (D.isTargetMacOS() && D.isMacosxVersionLT(10, 9)) {
3972 if (Args.hasArg(options::OPT_static) || Args.hasArg(options::OPT_object) ||
3973 Args.hasArg(options::OPT_preload)) {
3974 CmdArgs.push_back("-lgcrt0.o");
3975 } else {
3976 CmdArgs.push_back("-lgcrt1.o");
3977
3978 // darwin_crt2 spec is empty.
3979 }
3980 // By default on OS X 10.8 and later, we don't link with a crt1.o
3981 // file and the linker knows to use _main as the entry point. But,
3982 // when compiling with -pg, we need to link with the gcrt1.o file,
3983 // so pass the -no_new_main option to tell the linker to use the
3984 // "start" symbol as the entry point.
3985 if (!D.isMacosxVersionLT(10, 8))
3986 CmdArgs.push_back("-no_new_main");
3987 } else {
3988 D.getDriver().Diag(diag::err_drv_clang_unsupported_opt_pg_darwin)
3989 << D.isTargetMacOSBased();
3990 }
3991}
3992
3993static void addDefaultCRTLinkArgs(const Darwin &D, const ArgList &Args,
3994 ArgStringList &CmdArgs) {
3995 // Derived from darwin_crt1 spec.
3996 if (D.isTargetIPhoneOS()) {
3997 if (D.getArch() == llvm::Triple::aarch64)
3998 ; // iOS does not need any crt1 files for arm64
3999 else if (D.isIPhoneOSVersionLT(3, 1))
4000 CmdArgs.push_back("-lcrt1.o");
4001 else if (D.isIPhoneOSVersionLT(6, 0))
4002 CmdArgs.push_back("-lcrt1.3.1.o");
4003 return;
4004 }
4005
4006 if (!D.isTargetMacOS())
4007 return;
4008 if (D.isMacosxVersionLT(10, 5))
4009 CmdArgs.push_back("-lcrt1.o");
4010 else if (D.isMacosxVersionLT(10, 6))
4011 CmdArgs.push_back("-lcrt1.10.5.o");
4012 else if (D.isMacosxVersionLT(10, 8))
4013 CmdArgs.push_back("-lcrt1.10.6.o");
4014 // darwin_crt2 spec is empty.
4015}
4016
4017void Darwin::addStartObjectFileArgs(const ArgList &Args,
4018 ArgStringList &CmdArgs) const {
4019 // Firmware uses the "bare metal" start object file args.
4020 if (isTargetFirmware())
4021 return MachO::addStartObjectFileArgs(Args, CmdArgs);
4022
4023 // Derived from startfile spec.
4024 if (Args.hasArg(options::OPT_dynamiclib))
4025 addDynamicLibLinkArgs(*this, Args, CmdArgs);
4026 else if (Args.hasArg(options::OPT_bundle))
4027 addBundleLinkArgs(*this, Args, CmdArgs);
4028 else if (Args.hasArg(options::OPT_pg) && SupportsProfiling())
4029 addPgProfilingLinkArgs(*this, Args, CmdArgs);
4030 else if (Args.hasArg(options::OPT_static) ||
4031 Args.hasArg(options::OPT_object) ||
4032 Args.hasArg(options::OPT_preload))
4033 CmdArgs.push_back("-lcrt0.o");
4034 else
4035 addDefaultCRTLinkArgs(*this, Args, CmdArgs);
4036
4037 if (isTargetMacOS() && Args.hasArg(options::OPT_shared_libgcc) &&
4038 isMacosxVersionLT(10, 5)) {
4039 const char *Str = Args.MakeArgString(GetFilePath("crt3.o"));
4040 CmdArgs.push_back(Str);
4041 }
4042}
4043
4046 if (!isTargetInitialized())
4047 return;
4050 return;
4051 getDriver().Diag(diag::err_arc_unsupported_on_toolchain);
4052}
4053
4056 Action::OffloadKind DeviceOffloadKind) const {
4057 const bool IsX86_64 = getTriple().getArch() == llvm::Triple::x86_64;
4058 const bool IsAArch64 = getTriple().getArch() == llvm::Triple::aarch64;
4059 SanitizerMask Res =
4060 ToolChain::getSupportedSanitizers(BoundArch, DeviceOffloadKind);
4061 Res |= SanitizerKind::Address;
4062 Res |= SanitizerKind::PointerCompare;
4063 Res |= SanitizerKind::PointerSubtract;
4064 Res |= SanitizerKind::Realtime;
4065 Res |= SanitizerKind::Leak;
4066 Res |= SanitizerKind::Fuzzer;
4067 Res |= SanitizerKind::FuzzerNoLink;
4068 Res |= SanitizerKind::ObjCCast;
4069
4071 if (!isTargetInitialized())
4072 return Res;
4073 // Prior to 10.9, macOS shipped a version of the C++ standard library without
4074 // C++11 support. The same is true of iOS prior to version 5. These OS'es are
4075 // incompatible with -fsanitize=vptr.
4076 if (!(isTargetMacOSBased() && isMacosxVersionLT(10, 9)) &&
4078 Res |= SanitizerKind::Vptr;
4079
4080 if ((IsX86_64 || IsAArch64) &&
4083 Res |= SanitizerKind::Thread;
4084 }
4085
4086 if ((IsX86_64 || IsAArch64) && isTargetMacOSBased()) {
4087 Res |= SanitizerKind::Type;
4088 }
4089
4090 if (IsX86_64)
4091 Res |= SanitizerKind::NumericalStability;
4092
4093 return Res;
4094}
4095
4096void AppleMachO::printVerboseInfo(raw_ostream &OS) const {
4097 CudaInstallation->print(OS);
4098 RocmInstallation->print(OS);
4099}
#define V(N, I)
Defines a function that returns the minimum OS versions supporting C++17's aligned allocation functio...
static bool hasMultipleInvocations(const llvm::Triple &Triple, const ArgList &Args)
Definition Clang.cpp:1247
static bool checkRemarksOptions(const Driver &D, const ArgList &Args, const llvm::Triple &Triple)
Definition Clang.cpp:1258
static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs, const llvm::Triple &Triple, const InputInfo &Input, const InputInfo &Output, const JobAction &JA)
Definition Clang.cpp:1274
static bool sdkSupportsBuiltinModules(const std::optional< DarwinSDKInfo > &SDKInfo)
Definition Darwin.cpp:3358
static void addPgProfilingLinkArgs(const Darwin &D, const ArgList &Args, ArgStringList &CmdArgs)
Definition Darwin.cpp:3969
static const char * ArmMachOArchName(StringRef Arch)
Definition Darwin.cpp:1081
static bool shouldLinkerNotDedup(bool IsLinkerOnlyAction, const ArgList &Args)
Pass -no_deduplicate to ld64 under certain conditions:
Definition Darwin.cpp:213
static bool hasExportSymbolDirective(const ArgList &Args)
Check if the link command contains a symbol export directive.
Definition Darwin.cpp:1594
static void addDefaultCRTLinkArgs(const Darwin &D, const ArgList &Args, ArgStringList &CmdArgs)
Definition Darwin.cpp:3993
static void addBundleLinkArgs(const Darwin &D, const ArgList &Args, ArgStringList &CmdArgs)
Definition Darwin.cpp:3958
static llvm::VersionTuple sizedDeallocMinVersion(llvm::Triple::OSType OS)
Definition Darwin.cpp:3398
static VersionTuple minimumMacCatalystDeploymentTarget()
Definition Darwin.cpp:40
static std::string getSystemOrSDKMacOSVersion(StringRef MacOSSDKVersion)
Returns the most appropriate macOS target version for the current process.
Definition Darwin.cpp:1823
static void addDynamicLibLinkArgs(const Darwin &D, const ArgList &Args, ArgStringList &CmdArgs)
Definition Darwin.cpp:3940
static bool isObjCRuntimeLinked(const ArgList &Args)
Determine whether we are linking the ObjC runtime.
Definition Darwin.cpp:529
static const char * getPlatformName(Darwin::DarwinPlatformKind Platform, Darwin::DarwinEnvironmentKind Environment)
Definition Darwin.cpp:3824
static const char * ArmMachOArchNameCPU(StringRef CPU)
Definition Darwin.cpp:1101
static void addExportedSymbol(ArgStringList &CmdArgs, const char *Symbol)
Add an export directive for Symbol to the link command.
Definition Darwin.cpp:1609
static StringRef getXcodeDeveloperPath(StringRef PathIntoXcode)
Take a path that speculatively points into Xcode and return the XCODE/Contents/Developer path if it i...
Definition Darwin.cpp:1361
static void addSectalignToPage(const ArgList &Args, ArgStringList &CmdArgs, StringRef Segment, StringRef Section)
Add a sectalign directive for Segment and Section to the maximum expected page size for Darwin.
Definition Darwin.cpp:1620
Result
Implement __builtin_bit_cast and related operations.
static StringRef getTriple(const Command &Job)
Defines types useful for describing an Objective-C runtime.
const SDKPlatformInfo & getCanonicalPlatformInfo() const
const llvm::VersionTuple & getVersion() const
The basic abstraction for the target Objective-C runtime.
Definition ObjCRuntime.h:28
bool hasNativeARC() const
Does this runtime natively provide the ARC entrypoints?
bool hasSubscripting() const
Does this runtime directly support the subscripting methods?
@ MacOSX
'macosx' is the Apple-provided NeXT-derived runtime on Mac OS X platforms that use the non-fragile AB...
Definition ObjCRuntime.h:35
@ FragileMacOSX
'macosx-fragile' is the Apple-provided NeXT-derived runtime on Mac OS X platforms that use the fragil...
Definition ObjCRuntime.h:40
@ iOS
'ios' is the Apple-provided NeXT-derived runtime on iOS or the iOS simulator; it is always non-fragil...
Definition ObjCRuntime.h:45
@ WatchOS
'watchos' is a variant of iOS for Apple's watchOS.
Definition ObjCRuntime.h:49
The base class of the type hierarchy.
Definition TypeBase.h:1875
Action - Represent an abstract compilation step to perform.
Definition Action.h:47
types::ID getType() const
Definition Action.h:153
ActionClass getKind() const
Definition Action.h:152
ActionList & getInputs()
Definition Action.h:155
Compilation - A set of tasks to perform for a single driver invocation.
Definition Compilation.h:45
Driver - Encapsulate logic for constructing compilation processes from a set of gcc-driver-like comma...
Definition Driver.h:94
std::string SysRoot
sysroot, if present
Definition Driver.h:194
std::string GetTemporaryDirectory(StringRef Prefix) const
GetTemporaryDirectory - Return the pathname of a temporary directory to use as part of compilation; t...
Definition Driver.cpp:6936
DiagnosticBuilder Diag(unsigned DiagID) const
Definition Driver.h:158
static bool GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor, unsigned &Micro, bool &HadExtra)
GetReleaseVersion - Parse (([0-9]+)(.
Definition Driver.cpp:7306
const llvm::opt::OptTable & getOpts() const
Definition Driver.h:406
std::string GetTemporaryPath(StringRef Prefix, StringRef Suffix) const
GetTemporaryPath - Return the pathname of a temporary file to use as part of compilation; the file wi...
Definition Driver.cpp:6925
std::string Dir
The path the driver executable was in, as invoked from the command line.
Definition Driver.h:169
InputInfo - Wrapper for information about an input source.
Definition InputInfo.h:22
const char * getFilename() const
Definition InputInfo.h:83
bool isFilename() const
Definition InputInfo.h:75
types::ID getType() const
Definition InputInfo.h:77
static void addSystemInclude(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, const Twine &Path)
Utility function to add a system include directory to CC1 arguments.
virtual RuntimeLibType GetRuntimeLibType(const llvm::opt::ArgList &Args) const
bool ShouldLinkCXXStdlib(const llvm::opt::ArgList &Args) const
Returns if the C++ standard library should be linked in.
static void addSystemFrameworkIncludes(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, ArrayRef< StringRef > Paths)
Utility function to add a list of system framework directories to CC1.
static void addExternCSystemInclude(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, const Twine &Path)
Utility function to add a system include directory with extern "C" semantics to CC1 arguments.
std::string GetFilePath(const char *Name) const
virtual void addClangTargetOptions(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, llvm::StringRef BoundArch, Action::OffloadKind DeviceOffloadKind) const
Add options that need to be passed to cc1 for this target.
static bool needsProfileRT(const llvm::opt::ArgList &Args)
needsProfileRT - returns true if instrumentation profile is on.
StringRef getOS() const
Definition ToolChain.h:304
llvm::Triple::ArchType getArch() const
Definition ToolChain.h:301
const Driver & getDriver() const
Definition ToolChain.h:285
llvm::vfs::FileSystem & getVFS() const
static bool needsGCovInstrumentation(const llvm::opt::ArgList &Args)
Returns true if gcov instrumentation (-fprofile-arcs or –coverage) is on.
ToolChain(const Driver &D, const llvm::Triple &T, const llvm::opt::ArgList &Args)
Definition ToolChain.cpp:91
virtual bool SupportsEmbeddedBitcode() const
SupportsEmbeddedBitcode - Does this tool chain support embedded bitcode.
Definition ToolChain.h:698
path_list & getProgramPaths()
Definition ToolChain.h:328
bool hasEffectiveTriple() const
Definition ToolChain.h:318
virtual SanitizerMask getSupportedSanitizers(StringRef BoundArch, Action::OffloadKind DeviceOffloadKind) const
Return sanitizers which are available in this toolchain.
const llvm::Triple & getEffectiveTriple() const
Get the toolchain's effective clang triple.
Definition ToolChain.h:313
const llvm::Triple & getTriple() const
Definition ToolChain.h:287
virtual types::ID LookupTypeForExtension(StringRef Ext) const
LookupTypeForExtension - Return the default language type to use for the given extension.
const XRayArgs getXRayArgs(const llvm::opt::ArgList &) const
virtual void AddClangCXXStdlibIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
AddClangCXXStdlibIncludeArgs - Add the clang -cc1 level arguments to set the include paths to use for...
StringRef getDefaultUniversalArchName() const
Provide the default architecture name (as expected by -arch) for this toolchain.
virtual CXXStdlibType GetCXXStdlibType(const llvm::opt::ArgList &Args) const
virtual Tool * getTool(Action::ActionClass AC) const
virtual std::string ComputeLLVMTriple(const llvm::opt::ArgList &Args, StringRef BoundArch={}, types::ID InputType=types::TY_INVALID) const
ComputeLLVMTriple - Return the LLVM target triple to use, after taking command line arguments into ac...
SanitizerArgs getSanitizerArgs(const llvm::opt::ArgList &JobArgs, StringRef BoundArch="", Action::OffloadKind DeviceOffloadKind=Action::OFK_None) const
StringRef getArchName() const
Definition ToolChain.h:302
Tool - Information on a specific compilation tool.
Definition Tool.h:32
const ToolChain & getToolChain() const
Definition Tool.h:52
bool needsXRayRt() const
Definition XRayArgs.h:38
void AddCXXStdlibLibArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const override
AddCXXStdlibLibArgs - Add the system specific linker arguments to use for the given C++ standard libr...
Definition Darwin.cpp:3085
void AddCudaIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const override
Add arguments to use system-specific CUDA includes.
Definition Darwin.cpp:1062
void AddHIPIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const override
Add arguments to use system-specific HIP includes.
Definition Darwin.cpp:1067
void printVerboseInfo(raw_ostream &OS) const override
Dispatch to the specific toolchain for verbose printing.
Definition Darwin.cpp:4096
llvm::SmallString< 128 > GetEffectiveSysroot(const llvm::opt::ArgList &DriverArgs) const
Definition Darwin.cpp:2863
void AddClangSystemIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const override
Add the clang cc1 arguments for system include paths.
Definition Darwin.cpp:2876
LazyDetector< RocmInstallationDetector > RocmInstallation
Definition Darwin.h:336
LazyDetector< SYCLInstallationDetector > SYCLInstallation
Definition Darwin.h:337
void AddClangCXXStdlibIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const override
AddClangCXXStdlibIncludeArgs - Add the clang -cc1 level arguments to set the include paths to use for...
Definition Darwin.cpp:2976
LazyDetector< CudaInstallationDetector > CudaInstallation
}
Definition Darwin.h:335
AppleMachO(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args)
Definition Darwin.cpp:1004
void addSYCLIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const override
Add arguments to use system-specific SYCL includes.
Definition Darwin.cpp:1072
void addClangWarningOptions(llvm::opt::ArgStringList &CC1Args) const override
Add warning options that need to be passed to cc1 for this target.
Definition Darwin.cpp:1326
void AppendPlatformPrefix(SmallString< 128 > &Path, const llvm::Triple &T) const override
Definition Darwin.cpp:2847
void AddClangSystemIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const override
Add the clang cc1 arguments for system include paths.
Definition Darwin.cpp:2925
void AddCCKextLibArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const override
AddCCKextLibArgs - Add the system specific linker arguments to use for kernel extensions (Darwin-spec...
Definition Darwin.cpp:3132
bool getDefaultDebugSimpleTemplateNames() const override
Returns true if this toolchain adds '-gsimple-template-names=simple' by default when generating debug...
Definition Darwin.cpp:1464
void AddLinkRuntimeLibArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, bool ForceLinkBuiltinRT=false) const override
Add the linker arguments to link the compiler runtime library.
Definition Darwin.cpp:1686
RuntimeLibType GetRuntimeLibType(const llvm::opt::ArgList &Args) const override
Definition Darwin.cpp:1674
DarwinClang(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args)
Definition Darwin.cpp:1322
void addClangTargetOptions(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, llvm::StringRef BoundArch, Action::OffloadKind DeviceOffloadKind) const override
Add options that need to be passed to cc1 for this target.
Definition Darwin.cpp:1350
void AddLinkARCArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const override
Add the linker arguments to link the ARC runtime library.
Definition Darwin.cpp:1370
bool HasPlatformPrefix(const llvm::Triple &T) const override
Definition Darwin.cpp:2837
unsigned GetDefaultDwarfVersion() const override
Definition Darwin.cpp:1447
Darwin - The base Darwin tool chain.
Definition Darwin.h:350
VersionTuple TargetVersion
The native OS version we are targeting.
Definition Darwin.h:379
void addPlatformVersionArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const override
Definition Darwin.cpp:3847
bool TargetInitialized
Whether the information on the target has been initialized.
Definition Darwin.h:357
bool isIPhoneOSVersionLT(unsigned V0, unsigned V1=0, unsigned V2=0) const
Definition Darwin.h:563
bool SupportsEmbeddedBitcode() const override
SupportsEmbeddedBitcode - Does this tool chain support embedded bitcode.
Definition Darwin.cpp:3751
void addProfileRTLibs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const override
addProfileRTLibs - When -fprofile-instr-profile is specified, try to pass a suitable profile runtime ...
Definition Darwin.cpp:1627
Darwin(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args)
Darwin - Darwin tool chain for i386 and x86_64.
Definition Darwin.cpp:1010
void CheckObjCARC() const override
Complain if this tool chain doesn't support Objective-C ARC.
Definition Darwin.cpp:4044
llvm::ExceptionHandling GetExceptionModel(const llvm::opt::ArgList &Args) const override
GetExceptionModel - Return the tool chain exception model.
Definition Darwin.cpp:3737
std::optional< DarwinSDKInfo > SDKInfo
The information about the darwin SDK that was used.
Definition Darwin.h:384
bool isSizedDeallocationUnavailable() const
Return true if c++14 sized deallocation functions are not implemented in the c++ standard library of ...
Definition Darwin.cpp:3415
std::string getCompilerRT(const llvm::opt::ArgList &Args, StringRef Component, FileType Type=ToolChain::FT_Static, bool IsFortran=false) const override
Definition Darwin.cpp:1531
void ensureTargetInitialized() const
Lazily initialize the target platform from the triple when AddDeploymentTarget has not run yet (e....
Definition Darwin.cpp:1175
ObjCRuntime getDefaultObjCRuntime(bool isNonFragile) const override
Darwin provides an ARC runtime starting in MacOS X 10.7 and iOS 5.0.
Definition Darwin.cpp:1031
bool hasBlocksRuntime() const override
Darwin provides a blocks runtime starting in MacOS X 10.6 and iOS 3.2.
Definition Darwin.cpp:1049
bool isMacosxVersionLT(unsigned V0, unsigned V1=0, unsigned V2=0) const
Returns true if the minimum supported macOS version for the slice that's being built is less than the...
Definition Darwin.h:573
bool isTargetAppleSiliconMac() const
Definition Darwin.h:547
static StringRef getSDKName(StringRef isysroot)
Definition Darwin.cpp:1554
llvm::opt::DerivedArgList * TranslateArgs(const llvm::opt::DerivedArgList &Args, StringRef BoundArch, Action::OffloadKind DeviceOffloadKind) const override
TranslateArgs - Create a new derived argument list for any argument translations this ToolChain may w...
Definition Darwin.cpp:3663
void addClangCC1ASTargetOptions(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CC1ASArgs) const override
Add options that need to be passed to cc1as for this target.
Definition Darwin.cpp:3607
void setTarget(DarwinPlatformKind Platform, DarwinEnvironmentKind Environment, unsigned Major, unsigned Minor, unsigned Micro, VersionTuple NativeTargetVersion) const
Definition Darwin.h:443
std::string ComputeEffectiveClangTriple(const llvm::opt::ArgList &Args, llvm::StringRef BoundArch, types::ID InputType) const override
Definition Darwin.cpp:1256
CXXStdlibType GetDefaultCXXStdlibType() const override
Definition Darwin.cpp:1025
bool isTargetWatchOSSimulator() const
Definition Darwin.h:516
DarwinPlatformKind TargetPlatform
Definition Darwin.h:375
StringRef getOSLibraryNameSuffix(bool IgnoreSim=false) const override
Definition Darwin.cpp:1566
void addClangTargetOptions(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, llvm::StringRef BoundArch, Action::OffloadKind DeviceOffloadKind) const override
Add options that need to be passed to cc1 for this target.
Definition Darwin.cpp:3492
void addMinVersionArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const override
Definition Darwin.cpp:3772
void addStartObjectFileArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const override
Definition Darwin.cpp:4017
std::optional< llvm::Triple > TargetVariantTriple
The target variant triple that was specified (if any).
Definition Darwin.h:387
VersionTuple getTripleTargetVersion() const
The version of the OS that's used by the OS specified in the target triple.
Definition Darwin.h:558
bool isAlignedAllocationUnavailable() const
Return true if c++17 aligned allocation/deallocation functions are not implemented in the c++ standar...
Definition Darwin.cpp:3332
SanitizerMask getSupportedSanitizers(StringRef BoundArch, Action::OffloadKind DeviceOffloadKind) const override
Return sanitizers which are available in this toolchain.
Definition Darwin.cpp:4055
DarwinEnvironmentKind TargetEnvironment
Definition Darwin.h:376
VersionTuple getLinkerVersion(const llvm::opt::ArgList &Args) const
Get the version of the linker known to be available for a particular compiler invocation (via the -ml...
Definition Darwin.cpp:1148
Tool * buildLinker() const override
Definition Darwin.cpp:1312
Tool * buildStaticLibTool() const override
Definition Darwin.cpp:1314
bool isTargetIOSBased() const
Is the target either iOS or an iOS simulator?
Definition Darwin.h:211
bool isPICDefault() const override
Test whether this toolchain defaults to PIC.
Definition Darwin.cpp:3758
virtual void AppendPlatformPrefix(SmallString< 128 > &Path, const llvm::Triple &T) const
Definition Darwin.h:203
bool isPICDefaultForced() const override
Tests whether this toolchain forces its default for PIC, PIE or non-PIC.
Definition Darwin.cpp:3762
llvm::ExceptionHandling GetExceptionModel(const llvm::opt::ArgList &Args) const override
GetExceptionModel - Return the tool chain exception model.
Definition Darwin.h:291
Tool * getTool(Action::ActionClass AC) const override
Definition Darwin.cpp:1293
types::ID LookupTypeForExtension(StringRef Ext) const override
LookupTypeForExtension - Return the default language type to use for the given extension.
Definition Darwin.cpp:1013
void AddLinkRuntimeLib(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, StringRef Component, RuntimeLinkOptions Opts=RuntimeLinkOptions(), bool IsShared=false) const
Add a runtime library to the list of items to link.
Definition Darwin.cpp:1479
virtual void addMinVersionArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
Definition Darwin.h:194
virtual void addPlatformVersionArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
Definition Darwin.h:197
UnwindTableLevel getDefaultUnwindTableLevel(const llvm::opt::ArgList &Args) const override
How detailed should the unwind tables be by default.
Definition Darwin.cpp:3710
bool HasNativeLLVMSupport() const override
HasNativeLTOLinker - Check whether the linker and related tools have native LLVM support.
Definition Darwin.cpp:1023
std::string GetGlobalDebugPathRemapping() const override
Add an additional -fdebug-prefix-map entry.
Definition Darwin.cpp:3731
virtual void addStartObjectFileArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
Definition Darwin.h:190
virtual bool HasPlatformPrefix(const llvm::Triple &T) const
Definition Darwin.h:201
void addClangTargetOptions(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, llvm::StringRef BoundArch, Action::OffloadKind DeviceOffloadKind) const override
Add options that need to be passed to cc1 for this target.
Definition Darwin.cpp:3441
bool SupportsProfiling() const override
SupportsProfiling - Does this tool chain support -pg.
Definition Darwin.cpp:3767
RuntimeLinkOptions
Options to control how a runtime library is linked.
Definition Darwin.h:214
@ RLO_IsEmbedded
Use the embedded runtime from the macho_embedded directory.
Definition Darwin.h:219
@ RLO_AddRPath
Emit rpaths for @executable_path as well as the resource directory.
Definition Darwin.h:222
@ RLO_AlwaysLink
Link the library in even if it can't be found in the VFS.
Definition Darwin.h:216
MachO(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args)
Definition Darwin.cpp:998
virtual void AddLinkRuntimeLibArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, bool ForceLinkBuiltinRT=false) const
Add the linker arguments to link the compiler runtime library.
Definition Darwin.cpp:3316
std::string getCompilerRT(const llvm::opt::ArgList &Args, StringRef Component, FileType Type=ToolChain::FT_Static, bool IsFortran=false) const override
Definition Darwin.cpp:1512
StringRef getMachOArchName(const llvm::opt::ArgList &Args) const
Get the "MachO" arch name for a particular compiler invocation.
Definition Darwin.cpp:1120
Tool * buildAssembler() const override
Definition Darwin.cpp:1318
bool isPIEDefault(const llvm::opt::ArgList &Args) const override
Test whether this toolchain defaults to PIE.
Definition Darwin.cpp:3760
llvm::opt::DerivedArgList * TranslateArgs(const llvm::opt::DerivedArgList &Args, StringRef BoundArch, Action::OffloadKind DeviceOffloadKind) const override
TranslateArgs - Create a new derived argument list for any argument translations this ToolChain may w...
Definition Darwin.cpp:3164
bool UseDwarfDebugFlags() const override
UseDwarfDebugFlags - Embed the compile options to clang into the Dwarf compile unit information.
Definition Darwin.cpp:3725
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs,...
Definition Darwin.cpp:112
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs,...
Definition Darwin.cpp:953
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs,...
Definition Darwin.cpp:606
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs,...
Definition Darwin.cpp:928
const toolchains::MachO & getMachOToolChain() const
Definition Darwin.h:43
void AddMachOArch(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
Definition Darwin.cpp:182
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs,...
Definition Darwin.cpp:880
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs,...
Definition Darwin.cpp:974
FloatABI getARMFloatABI(const ToolChain &TC, const llvm::opt::ArgList &Args)
llvm::Triple::ArchType getArchTypeForMachOArchName(StringRef Str)
Definition Darwin.cpp:44
void setTripleTypeForMachOArchName(llvm::Triple &T, StringRef Str, const llvm::opt::ArgList &Args)
llvm::opt::Arg * getLastProfileSampleUseArg(const llvm::opt::ArgList &Args)
llvm::opt::Arg * getLastCSProfileGenerateArg(const llvm::opt::ArgList &Args)
llvm::opt::Arg * getLastProfileUseArg(const llvm::opt::ArgList &Args)
llvm::StringRef getLTOParallelism(const llvm::opt::ArgList &Args, const Driver &D)
bool addOpenMPRuntime(const Compilation &C, llvm::opt::ArgStringList &CmdArgs, const ToolChain &TC, const llvm::opt::ArgList &Args, bool ForceStaticHostRuntime=false, bool IsOffloadingHost=false, bool GompNeedsRT=false)
Returns true, if an OpenMP runtime has been added.
void AddLinkerInputs(const ToolChain &TC, const InputInfoList &Inputs, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, const JobAction &JA)
SmallString< 128 > getStatsFileName(const llvm::opt::ArgList &Args, const InputInfo &Output, const InputInfo &Input, const Driver &D)
Handles the -save-stats option and returns the filename to save statistics to.
bool isObjCAutoRefCount(const llvm::opt::ArgList &Args)
const char * getTypeTempSuffix(ID Id, bool CLStyle=false)
getTypeTempSuffix - Return the suffix to use when creating a temp file of this type,...
Definition Types.cpp:81
SmallVector< InputInfo, 4 > InputInfoList
Definition Driver.h:50
bool willEmitRemarks(const llvm::opt::ArgList &Args)
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
llvm::ImmutableSet< T > join(llvm::ImmutableSet< T > A, llvm::ImmutableSet< T > B, typename llvm::ImmutableSet< T >::Factory &F)
Computes the union of two ImmutableSets.
Definition Utils.h:39
The JSON file list parser is used to communicate input to InstallAPI.
Expected< std::optional< DarwinSDKInfo > > parseDarwinSDKInfo(llvm::vfs::FileSystem &VFS, StringRef SDKRootPath)
Parse the SDK information from the SDKSettings.json file.
llvm::VersionTuple alignedAllocMinVersion(llvm::Triple::OSType OS)
llvm::StringRef getAsString(SyncScope S)
Definition SyncScope.h:62
bool(*)(llvm::ArrayRef< const char * >, llvm::raw_ostream &, llvm::raw_ostream &, bool, bool) Driver
Definition Wasm.cpp:36
#define false
Definition stdbool.h:26
static constexpr OSEnvPair macCatalystToMacOSPair()
Returns the os-environment mapping pair that's used to represent the Mac Catalyst -> macOS version ma...
static constexpr OSEnvPair macOStoMacCatalystPair()
Returns the os-environment mapping pair that's used to represent the macOS -> Mac Catalyst version ma...
llvm::Triple::OSType getOS() const
llvm::Triple::EnvironmentType getEnvironment() const
static constexpr ResponseFileSupport None()
Returns a ResponseFileSupport indicating that response files are not supported.
Definition Job.h:78
static constexpr ResponseFileSupport AtFileUTF8()
Definition Job.h:85