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