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