1//===--- Darwin.cpp - Darwin Tool and ToolChain Implementations -*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "Darwin.h"
10#include "Arch/ARM.h"
11#include "clang/Basic/AlignedAllocation.h"
12#include "clang/Basic/ObjCRuntime.h"
13#include "clang/Config/config.h"
14#include "clang/Driver/CommonArgs.h"
15#include "clang/Driver/Compilation.h"
16#include "clang/Driver/Driver.h"
17#include "clang/Driver/SanitizerArgs.h"
18#include "clang/Options/Options.h"
19#include "llvm/ADT/StringSwitch.h"
20#include "llvm/Option/ArgList.h"
21#include "llvm/ProfileData/InstrProf.h"
22#include "llvm/ProfileData/MemProf.h"
23#include "llvm/Support/Path.h"
24#include "llvm/Support/Threading.h"
25#include "llvm/Support/VirtualFileSystem.h"
26#include "llvm/TargetParser/TargetParser.h"
27#include "llvm/TargetParser/Triple.h"
28#include <cstdlib> // ::getenv
29
30#ifdef CLANG_USE_XCSELECT
31#include <xcselect.h> // ::xcselect_host_sdk_path
32#endif
33
34using namespace clang::driver;
35using namespace clang::driver::tools;
36using namespace clang::driver::toolchains;
37using namespace clang;
38using namespace llvm::opt;
39
40static VersionTuple minimumMacCatalystDeploymentTarget() {
41 return VersionTuple(13, 1);
42}
43
44llvm::Triple::ArchType darwin::getArchTypeForMachOArchName(StringRef Str) {
45 // See arch(3) and llvm-gcc's driver-driver.c. We don't implement support for
46 // archs which Darwin doesn't use.
47
48 // The matching this routine does is fairly pointless, since it is neither the
49 // complete architecture list, nor a reasonable subset. The problem is that
50 // historically the driver accepts this and also ties its -march=
51 // handling to the architecture name, so we need to be careful before removing
52 // support for it.
53
54 // This code must be kept in sync with Clang's Darwin specific argument
55 // translation.
56
57 return llvm::StringSwitch<llvm::Triple::ArchType>(Str)
58 .Cases(CaseStrings: {"i386", "i486", "i486SX", "i586", "i686"}, Value: llvm::Triple::x86)
59 .Cases(CaseStrings: {"pentium", "pentpro", "pentIIm3", "pentIIm5", "pentium4"},
60 Value: llvm::Triple::x86)
61 .Cases(CaseStrings: {"x86_64", "x86_64h"}, Value: llvm::Triple::x86_64)
62 // This is derived from the driver.
63 .Cases(CaseStrings: {"arm", "armv4t", "armv5", "armv6", "armv6m"}, Value: llvm::Triple::arm)
64 .Cases(CaseStrings: {"armv7", "armv7em", "armv7k", "armv7m"}, Value: llvm::Triple::arm)
65 .Cases(CaseStrings: {"armv7s", "xscale"}, Value: llvm::Triple::arm)
66 .Cases(CaseStrings: {"armv8m.base", "armv8m.main", "armv8.1m.main"}, Value: llvm::Triple::arm)
67 .Cases(CaseStrings: {"arm64", "arm64e"}, Value: llvm::Triple::aarch64)
68 .Case(S: "arm64_32", Value: llvm::Triple::aarch64_32)
69 .Cases(CaseStrings: {"amdgpu", "amdgcn"}, Value: llvm::Triple::amdgpu)
70 .Case(S: "r600", Value: llvm::Triple::r600)
71 .Case(S: "nvptx", Value: llvm::Triple::nvptx)
72 .Case(S: "nvptx64", Value: llvm::Triple::nvptx64)
73 .Case(S: "amdil", Value: llvm::Triple::amdil)
74 .Case(S: "spir", Value: llvm::Triple::spir)
75 .Default(Value: llvm::Triple::UnknownArch);
76}
77
78void darwin::setTripleTypeForMachOArchName(llvm::Triple &T, StringRef Str,
79 const ArgList &Args) {
80 const llvm::Triple::ArchType Arch = getArchTypeForMachOArchName(Str);
81 llvm::ARM::ArchKind ArchKind = llvm::ARM::parseArch(Arch: Str);
82 T.setArch(Kind: Arch);
83 if (Arch != llvm::Triple::UnknownArch)
84 T.setArchName(Str);
85
86 // Standalone/bare metal compiles often unintentionally come out as
87 // armv6m-apple-ios (-target not specified, or set from Xcode). Change these
88 // cases to armv6m-apple-unknown-macho to better reflect intent.
89 if ((T.getOS() != llvm::Triple::Firmware) &&
90 (ArchKind == llvm::ARM::ArchKind::ARMV6M ||
91 ArchKind == llvm::ARM::ArchKind::ARMV7M ||
92 ArchKind == llvm::ARM::ArchKind::ARMV7EM ||
93 ArchKind == llvm::ARM::ArchKind::ARMV8MBaseline ||
94 ArchKind == llvm::ARM::ArchKind::ARMV8MMainline ||
95 ArchKind == llvm::ARM::ArchKind::ARMV8_1MMainline)) {
96 // Don't reject these -version-min= if we have the appropriate triple.
97 if (T.getOS() == llvm::Triple::IOS)
98 for (Arg *A : Args.filtered(Ids: options::OPT_mios_version_min_EQ))
99 A->ignoreTargetSpecific();
100 if (T.getOS() == llvm::Triple::WatchOS)
101 for (Arg *A : Args.filtered(Ids: options::OPT_mwatchos_version_min_EQ))
102 A->ignoreTargetSpecific();
103 if (T.getOS() == llvm::Triple::TvOS)
104 for (Arg *A : Args.filtered(Ids: options::OPT_mtvos_version_min_EQ))
105 A->ignoreTargetSpecific();
106
107 T.setOS(llvm::Triple::UnknownOS);
108 T.setObjectFormat(llvm::Triple::MachO);
109 }
110}
111
112void darwin::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
113 const InputInfo &Output,
114 const InputInfoList &Inputs,
115 const ArgList &Args,
116 const char *LinkingOutput) const {
117 const llvm::Triple &T(getToolChain().getTriple());
118
119 ArgStringList CmdArgs;
120
121 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
122 const InputInfo &Input = Inputs[0];
123
124 // Determine the original source input.
125 const Action *SourceAction = &JA;
126 while (SourceAction->getKind() != Action::InputClass) {
127 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
128 SourceAction = SourceAction->getInputs()[0];
129 }
130
131 // If -fno-integrated-as is used add -Q to the darwin assembler driver to make
132 // sure it runs its system assembler not clang's integrated assembler.
133 // Applicable to darwin11+ and Xcode 4+. darwin<10 lacked integrated-as.
134 // FIXME: at run-time detect assembler capabilities or rely on version
135 // information forwarded by -target-assembler-version.
136 if (Args.hasArg(Ids: options::OPT_fno_integrated_as)) {
137 if (!(T.isMacOSX() && T.isMacOSXVersionLT(Major: 10, Minor: 7)))
138 CmdArgs.push_back(Elt: "-Q");
139 }
140
141 // Forward -g, assuming we are dealing with an actual assembly file.
142 if (SourceAction->getType() == types::TY_Asm ||
143 SourceAction->getType() == types::TY_PP_Asm) {
144 if (Args.hasArg(Ids: options::OPT_gstabs))
145 CmdArgs.push_back(Elt: "--gstabs");
146 else if (Args.hasArg(Ids: options::OPT_g_Group))
147 CmdArgs.push_back(Elt: "-g");
148 }
149
150 // Derived from asm spec.
151 AddMachOArch(Args, CmdArgs);
152
153 // Use -force_cpusubtype_ALL on x86 by default.
154 if (T.isX86() || Args.hasArg(Ids: options::OPT_force__cpusubtype__ALL))
155 CmdArgs.push_back(Elt: "-force_cpusubtype_ALL");
156
157 if (getToolChain().getArch() != llvm::Triple::x86_64 &&
158 (((Args.hasArg(Ids: options::OPT_mkernel) ||
159 Args.hasArg(Ids: options::OPT_fapple_kext)) &&
160 getMachOToolChain().isKernelStatic()) ||
161 Args.hasArg(Ids: options::OPT_static)))
162 CmdArgs.push_back(Elt: "-static");
163
164 Args.AddAllArgValues(Output&: CmdArgs, Id0: options::OPT_Wa_COMMA, Id1: options::OPT_Xassembler);
165
166 assert(Output.isFilename() && "Unexpected lipo output.");
167 CmdArgs.push_back(Elt: "-o");
168 CmdArgs.push_back(Elt: Output.getFilename());
169
170 assert(Input.isFilename() && "Invalid input.");
171 CmdArgs.push_back(Elt: Input.getFilename());
172
173 // asm_final spec is empty.
174
175 const char *Exec = Args.MakeArgString(Str: getToolChain().GetProgramPath(Name: "as"));
176 C.addCommand(Cmd: std::make_unique<Command>(args: JA, args: *this, args: ResponseFileSupport::None(),
177 args&: Exec, args&: CmdArgs, args: Inputs, args: Output));
178}
179
180void darwin::MachOTool::anchor() {}
181
182void darwin::MachOTool::AddMachOArch(const ArgList &Args,
183 ArgStringList &CmdArgs) const {
184 StringRef ArchName = getMachOToolChain().getMachOArchName(Args);
185
186 // Derived from darwin_arch spec.
187 CmdArgs.push_back(Elt: "-arch");
188 CmdArgs.push_back(Elt: Args.MakeArgString(Str: ArchName));
189
190 // FIXME: Is this needed anymore?
191 if (ArchName == "arm")
192 CmdArgs.push_back(Elt: "-force_cpusubtype_ALL");
193}
194
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;
1214 if (Platform == MacOS) {
1215 // Record the macOS product version (e.g. macosx15), not the Darwin kernel
1216 // version (e.g. darwin24.3): version checks against the lazily-recorded
1217 // target must behave as if AddDeploymentTarget() had computed it.
1218 if (!getTriple().getMacOSXVersion(Version&: OsVer))
1219 return;
1220 } else {
1221 OsVer = getTriple().getOSVersion();
1222 }
1223 setTarget(Platform, Environment, Major: OsVer.getMajor(),
1224 Minor: OsVer.getMinor().value_or(u: 0), Micro: OsVer.getSubminor().value_or(u: 0),
1225 NativeTargetVersion: VersionTuple());
1226 // The version above is a guess from the triple alone; AddDeploymentTarget()
1227 // may later derive a different deployment target from flags, environment
1228 // variables, or the SDK, and overwrite this initialization.
1229 TargetInitializedLazily = true;
1230}
1231
1232AppleMachO::~AppleMachO() {}
1233
1234MachO::~MachO() {}
1235
1236void Darwin::VerifyTripleForSDK(const llvm::opt::ArgList &Args,
1237 const llvm::Triple &Triple) const {
1238 if (SDKInfo) {
1239 if (!SDKInfo->supportsTriple(Triple))
1240 getDriver().Diag(DiagID: diag::warn_incompatible_sysroot)
1241 << SDKInfo->getDisplayName() << Triple.getTriple();
1242 } else if (const Arg *A = Args.getLastArg(Ids: options::OPT_isysroot)) {
1243 // If there is no SDK info, assume this is building against an SDK that
1244 // predates SDKSettings.json. Try to match the triple to the SDK path.
1245 const char *isysroot = A->getValue();
1246 StringRef SDKName = getSDKName(isysroot);
1247 if (!SDKName.empty()) {
1248 bool supported = true;
1249 if (Triple.isWatchOS())
1250 supported = SDKName.starts_with(Prefix: "Watch");
1251 else if (Triple.isTvOS())
1252 supported = SDKName.starts_with(Prefix: "AppleTV");
1253 else if (Triple.isDriverKit())
1254 supported = SDKName.starts_with(Prefix: "DriverKit");
1255 else if (Triple.isiOS())
1256 supported = SDKName.starts_with(Prefix: "iPhone");
1257 else if (Triple.isMacOSX())
1258 supported = SDKName.starts_with(Prefix: "MacOSX");
1259 // If it's not an older SDK, then it might be a damaged SDK or a
1260 // non-standard -isysroot path. Don't try to diagnose that here.
1261
1262 if (!supported)
1263 getDriver().Diag(DiagID: diag::warn_incompatible_sysroot)
1264 << SDKName << Triple.getTriple();
1265 }
1266 }
1267}
1268
1269std::string Darwin::ComputeEffectiveClangTriple(const ArgList &Args,
1270 BoundArch BA,
1271 types::ID InputType) const {
1272 llvm::Triple Triple(ComputeLLVMTriple(Args, BA, InputType));
1273
1274 // If the target isn't initialized (e.g., an unknown Darwin platform, return
1275 // the default triple). Note: we intentionally do NOT call
1276 // ensureTargetInitialized() here because this method is called before
1277 // AddDeploymentTarget() in some code paths (e.g. -print-libgcc-file-name),
1278 // and lazy init with version 0.0.0 would conflict with the real version
1279 // that AddDeploymentTarget() later sets via setTarget().
1280 if (!isTargetInitialized())
1281 return Triple.getTriple();
1282
1283 SmallString<16> Str;
1284 if (isTargetWatchOSBased())
1285 Str += "watchos";
1286 else if (isTargetTvOSBased())
1287 Str += "tvos";
1288 else if (isTargetDriverKit())
1289 Str += "driverkit";
1290 else if (isTargetIOSBased() || isTargetMacCatalyst())
1291 Str += "ios";
1292 else if (isTargetXROS())
1293 Str += llvm::Triple::getOSTypeName(Kind: llvm::Triple::XROS);
1294 else if (isTargetFirmware())
1295 Str += llvm::Triple::getOSTypeName(Kind: llvm::Triple::Firmware);
1296 else
1297 Str += "macosx";
1298 Str += getTripleTargetVersion().getAsString();
1299 Triple.setOSName(Str);
1300
1301 VerifyTripleForSDK(Args, Triple);
1302
1303 return Triple.getTriple();
1304}
1305
1306Tool *MachO::getTool(Action::ActionClass AC) const {
1307 switch (AC) {
1308 case Action::LipoJobClass:
1309 if (!Lipo)
1310 Lipo.reset(p: new tools::darwin::Lipo(*this));
1311 return Lipo.get();
1312 case Action::DsymutilJobClass:
1313 if (!Dsymutil)
1314 Dsymutil.reset(p: new tools::darwin::Dsymutil(*this));
1315 return Dsymutil.get();
1316 case Action::VerifyDebugInfoJobClass:
1317 if (!VerifyDebug)
1318 VerifyDebug.reset(p: new tools::darwin::VerifyDebug(*this));
1319 return VerifyDebug.get();
1320 default:
1321 return ToolChain::getTool(AC);
1322 }
1323}
1324
1325Tool *MachO::buildLinker() const { return new tools::darwin::Linker(*this); }
1326
1327Tool *MachO::buildStaticLibTool() const {
1328 return new tools::darwin::StaticLibTool(*this);
1329}
1330
1331Tool *MachO::buildAssembler() const {
1332 return new tools::darwin::Assembler(*this);
1333}
1334
1335DarwinClang::DarwinClang(const Driver &D, const llvm::Triple &Triple,
1336 const ArgList &Args)
1337 : Darwin(D, Triple, Args) {}
1338
1339void DarwinClang::addClangWarningOptions(ArgStringList &CC1Args) const {
1340 // Always error about undefined 'TARGET_OS_*' macros.
1341 CC1Args.push_back(Elt: "-Wundef-prefix=TARGET_OS_");
1342 CC1Args.push_back(Elt: "-Werror=undef-prefix");
1343
1344 // For modern targets, promote certain warnings to errors.
1345 // Lazily initialize the target if needed (e.g. when Darwin is used as
1346 // a host toolchain for device offloading).
1347 ensureTargetInitialized();
1348 if (!isTargetInitialized())
1349 return;
1350 if (isTargetWatchOSBased() || getTriple().isArch64Bit()) {
1351 // Always enable -Wdeprecated-objc-isa-usage and promote it
1352 // to an error.
1353 CC1Args.push_back(Elt: "-Wdeprecated-objc-isa-usage");
1354 CC1Args.push_back(Elt: "-Werror=deprecated-objc-isa-usage");
1355
1356 // For iOS and watchOS, also error about implicit function declarations,
1357 // as that can impact calling conventions.
1358 if (!isTargetMacOS())
1359 CC1Args.push_back(Elt: "-Werror=implicit-function-declaration");
1360 }
1361}
1362
1363void DarwinClang::addClangTargetOptions(
1364 const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args,
1365 BoundArch BA, Action::OffloadKind DeviceOffloadKind) const {
1366
1367 Darwin::addClangTargetOptions(DriverArgs, CC1Args, BA, DeviceOffloadKind);
1368}
1369
1370/// Take a path that speculatively points into Xcode and return the
1371/// `XCODE/Contents/Developer` path if it is an Xcode path, or an empty path
1372/// otherwise.
1373static StringRef getXcodeDeveloperPath(StringRef PathIntoXcode) {
1374 static constexpr llvm::StringLiteral XcodeAppSuffix(
1375 ".app/Contents/Developer");
1376 size_t Index = PathIntoXcode.find(Str: XcodeAppSuffix);
1377 if (Index == StringRef::npos)
1378 return "";
1379 return PathIntoXcode.take_front(N: Index + XcodeAppSuffix.size());
1380}
1381
1382void DarwinClang::AddLinkARCArgs(const ArgList &Args,
1383 ArgStringList &CmdArgs) const {
1384 // Avoid linking compatibility stubs on i386 mac.
1385 if (isTargetMacOSBased() && getArch() == llvm::Triple::x86)
1386 return;
1387 if (isTargetAppleSiliconMac())
1388 return;
1389 // ARC runtime is supported everywhere on arm64e.
1390 if (getTriple().isArm64e())
1391 return;
1392 if (isTargetXROS())
1393 return;
1394
1395 ObjCRuntime runtime = getDefaultObjCRuntime(/*nonfragile*/ isNonFragile: true);
1396
1397 if ((runtime.hasNativeARC() || !isObjCAutoRefCount(Args)) &&
1398 runtime.hasSubscripting())
1399 return;
1400
1401 SmallString<128> P(getDriver().DriverExecutable);
1402 llvm::sys::path::remove_filename(path&: P); // 'clang'
1403 llvm::sys::path::remove_filename(path&: P); // 'bin'
1404 llvm::sys::path::append(path&: P, a: "lib", b: "arc");
1405
1406 // 'libarclite' usually lives in the same toolchain as 'clang'. However, the
1407 // Swift open source toolchains for macOS distribute Clang without libarclite.
1408 // In that case, to allow the linker to find 'libarclite', we point to the
1409 // 'libarclite' in the XcodeDefault toolchain instead.
1410 if (!getVFS().exists(Path: P)) {
1411 auto updatePath = [&](const Arg *A) {
1412 // Try to infer the path to 'libarclite' in the toolchain from the
1413 // specified SDK path.
1414 StringRef XcodePathForSDK = getXcodeDeveloperPath(PathIntoXcode: A->getValue());
1415 if (XcodePathForSDK.empty())
1416 return false;
1417
1418 P = XcodePathForSDK;
1419 llvm::sys::path::append(path&: P, a: "Toolchains/XcodeDefault.xctoolchain/usr",
1420 b: "lib", c: "arc");
1421 return getVFS().exists(Path: P);
1422 };
1423
1424 bool updated = false;
1425 if (const Arg *A = Args.getLastArg(Ids: options::OPT_isysroot))
1426 updated = updatePath(A);
1427
1428 if (!updated) {
1429 if (const Arg *A = Args.getLastArg(Ids: options::OPT__sysroot_EQ))
1430 updatePath(A);
1431 }
1432 }
1433
1434 CmdArgs.push_back(Elt: "-force_load");
1435 llvm::sys::path::append(path&: P, a: "libarclite_");
1436 // Mash in the platform.
1437 if (isTargetWatchOSSimulator())
1438 P += "watchsimulator";
1439 else if (isTargetWatchOS())
1440 P += "watchos";
1441 else if (isTargetTvOSSimulator())
1442 P += "appletvsimulator";
1443 else if (isTargetTvOS())
1444 P += "appletvos";
1445 else if (isTargetIOSSimulator())
1446 P += "iphonesimulator";
1447 else if (isTargetIPhoneOS())
1448 P += "iphoneos";
1449 else
1450 P += "macosx";
1451 P += ".a";
1452
1453 if (!getVFS().exists(Path: P))
1454 getDriver().Diag(DiagID: clang::diag::err_drv_darwin_sdk_missing_arclite) << P;
1455
1456 CmdArgs.push_back(Elt: Args.MakeArgString(Str: P));
1457}
1458
1459unsigned DarwinClang::GetDefaultDwarfVersion() const {
1460 // Default to use DWARF 2 on OS X 10.10 / iOS 8 and lower.
1461 if ((isTargetMacOSBased() && isMacosxVersionLT(V0: 10, V1: 11)) ||
1462 (isTargetIOSBased() && isIPhoneOSVersionLT(V0: 9)))
1463 return 2;
1464 // Default to use DWARF 4 on OS X 10.11 - macOS 14 / iOS 9 - iOS 17.
1465 if ((isTargetMacOSBased() && isMacosxVersionLT(V0: 15)) ||
1466 (isTargetIOSBased() && isIPhoneOSVersionLT(V0: 18)) ||
1467 (isTargetWatchOSBased() && TargetVersion < llvm::VersionTuple(11)) ||
1468 (isTargetXROS() && TargetVersion < llvm::VersionTuple(2)) ||
1469 (isTargetDriverKit() && TargetVersion < llvm::VersionTuple(24)) ||
1470 (isTargetMacOSBased() &&
1471 TargetVersion.empty())) // apple-darwin, no version.
1472 return 4;
1473 return 5;
1474}
1475
1476bool DarwinClang::getDefaultDebugSimpleTemplateNames() const {
1477 // Default to an OS version on which LLDB supports debugging
1478 // -gsimple-template-names programs.
1479 if ((isTargetMacOSBased() && isMacosxVersionLT(V0: 26)) ||
1480 (isTargetIOSBased() && isIPhoneOSVersionLT(V0: 26)) ||
1481 (isTargetWatchOSBased() && TargetVersion < llvm::VersionTuple(26)) ||
1482 (isTargetXROS() && TargetVersion < llvm::VersionTuple(26)) ||
1483 (isTargetDriverKit() && TargetVersion < llvm::VersionTuple(25)) ||
1484 (isTargetMacOSBased() &&
1485 TargetVersion.empty())) // apple-darwin, no version.
1486 return false;
1487
1488 return true;
1489}
1490
1491void MachO::AddLinkRuntimeLib(const ArgList &Args, ArgStringList &CmdArgs,
1492 StringRef Component, RuntimeLinkOptions Opts,
1493 bool IsShared) const {
1494 std::string P = getCompilerRT(
1495 Args, Component, Type: IsShared ? ToolChain::FT_Shared : ToolChain::FT_Static);
1496
1497 // For now, allow missing resource libraries to support developers who may
1498 // not have compiler-rt checked out or integrated into their build (unless
1499 // we explicitly force linking with this library).
1500 if ((Opts & RLO_AlwaysLink) || getVFS().exists(Path: P)) {
1501 const char *LibArg = Args.MakeArgString(Str: P);
1502 CmdArgs.push_back(Elt: LibArg);
1503 }
1504
1505 // Adding the rpaths might negatively interact when other rpaths are involved,
1506 // so we should make sure we add the rpaths last, after all user-specified
1507 // rpaths. This is currently true from this place, but we need to be
1508 // careful if this function is ever called before user's rpaths are emitted.
1509 if (Opts & RLO_AddRPath) {
1510 assert(StringRef(P).ends_with(".dylib") && "must be a dynamic library");
1511
1512 // Add @executable_path to rpath to support having the dylib copied with
1513 // the executable.
1514 CmdArgs.push_back(Elt: "-rpath");
1515 CmdArgs.push_back(Elt: "@executable_path");
1516
1517 // Add the compiler-rt library's directory to rpath to support using the
1518 // dylib from the default location without copying.
1519 CmdArgs.push_back(Elt: "-rpath");
1520 CmdArgs.push_back(Elt: Args.MakeArgString(Str: llvm::sys::path::parent_path(path: P)));
1521 }
1522}
1523
1524std::string MachO::getCompilerRT(const ArgList &Args, StringRef Component,
1525 FileType Type, bool IsFortran) const {
1526 assert(Type != ToolChain::FT_Object &&
1527 "it doesn't make sense to ask for the compiler-rt library name as an "
1528 "object file");
1529 SmallString<64> MachOLibName = StringRef("libclang_rt");
1530 // On MachO, the builtins component is not in the library name
1531 if (Component != "builtins") {
1532 MachOLibName += '.';
1533 MachOLibName += Component;
1534 }
1535 MachOLibName += Type == ToolChain::FT_Shared ? "_dynamic.dylib" : ".a";
1536
1537 SmallString<128> FullPath(getDriver().ResourceDir);
1538 llvm::sys::path::append(path&: FullPath, a: "lib", b: "darwin", c: "macho_embedded",
1539 d: MachOLibName);
1540 return std::string(FullPath);
1541}
1542
1543std::string Darwin::getCompilerRT(const ArgList &Args, StringRef Component,
1544 FileType Type, bool IsFortran) const {
1545 // Firmware uses the "bare metal" RT.
1546 if (TargetPlatform == DarwinPlatformKind::Firmware)
1547 return MachO::getCompilerRT(Args, Component, Type, IsFortran);
1548
1549 assert(Type != ToolChain::FT_Object &&
1550 "it doesn't make sense to ask for the compiler-rt library name as an "
1551 "object file");
1552 SmallString<64> DarwinLibName = StringRef("libclang_rt.");
1553 // On Darwin, the builtins component is not in the library name
1554 if (Component != "builtins") {
1555 DarwinLibName += Component;
1556 DarwinLibName += '_';
1557 }
1558 DarwinLibName += getOSLibraryNameSuffix();
1559 DarwinLibName += Type == ToolChain::FT_Shared ? "_dynamic.dylib" : ".a";
1560
1561 SmallString<128> FullPath(getDriver().ResourceDir);
1562 llvm::sys::path::append(path&: FullPath, a: "lib", b: "darwin", c: DarwinLibName);
1563 return std::string(FullPath);
1564}
1565
1566StringRef Darwin::getSDKName(StringRef isysroot) {
1567 // Assume SDK has path: SOME_PATH/SDKs/PlatformXX.YY.sdk
1568 auto BeginSDK = llvm::sys::path::rbegin(path: isysroot);
1569 auto EndSDK = llvm::sys::path::rend(path: isysroot);
1570 for (auto IT = BeginSDK; IT != EndSDK; ++IT) {
1571 StringRef SDK = *IT;
1572 if (SDK.consume_back(Suffix: ".sdk"))
1573 return SDK;
1574 }
1575 return "";
1576}
1577
1578StringRef Darwin::getOSLibraryNameSuffix(bool IgnoreSim) const {
1579 switch (TargetPlatform) {
1580 case DarwinPlatformKind::MacOS:
1581 return "osx";
1582 case DarwinPlatformKind::IPhoneOS:
1583 if (TargetEnvironment == MacCatalyst)
1584 return "osx";
1585 return TargetEnvironment == NativeEnvironment || IgnoreSim ? "ios"
1586 : "iossim";
1587 case DarwinPlatformKind::TvOS:
1588 return TargetEnvironment == NativeEnvironment || IgnoreSim ? "tvos"
1589 : "tvossim";
1590 case DarwinPlatformKind::WatchOS:
1591 return TargetEnvironment == NativeEnvironment || IgnoreSim ? "watchos"
1592 : "watchossim";
1593 case DarwinPlatformKind::XROS:
1594 return TargetEnvironment == NativeEnvironment || IgnoreSim ? "xros"
1595 : "xrossim";
1596 case DarwinPlatformKind::DriverKit:
1597 return "driverkit";
1598
1599 case DarwinPlatformKind::Firmware:
1600 break;
1601 }
1602 llvm_unreachable("Unsupported platform");
1603}
1604
1605/// Check if the link command contains a symbol export directive.
1606static bool hasExportSymbolDirective(const ArgList &Args) {
1607 for (Arg *A : Args) {
1608 if (A->getOption().matches(ID: options::OPT_exported__symbols__list))
1609 return true;
1610 if (!A->getOption().matches(ID: options::OPT_Wl_COMMA) &&
1611 !A->getOption().matches(ID: options::OPT_Xlinker))
1612 continue;
1613 if (A->containsValue(Value: "-exported_symbols_list") ||
1614 A->containsValue(Value: "-exported_symbol"))
1615 return true;
1616 }
1617 return false;
1618}
1619
1620/// Add an export directive for \p Symbol to the link command.
1621static void addExportedSymbol(ArgStringList &CmdArgs, const char *Symbol) {
1622 CmdArgs.push_back(Elt: "-exported_symbol");
1623 CmdArgs.push_back(Elt: Symbol);
1624}
1625
1626/// Add a sectalign directive for \p Segment and \p Section to the maximum
1627/// expected page size for Darwin.
1628///
1629/// On iPhone 6+ the max supported page size is 16K. On macOS, the max is 4K.
1630/// Use a common alignment constant (16K) for now, and reduce the alignment on
1631/// macOS if it proves important.
1632static void addSectalignToPage(const ArgList &Args, ArgStringList &CmdArgs,
1633 StringRef Segment, StringRef Section) {
1634 for (const char *A : {"-sectalign", Args.MakeArgString(Str: Segment),
1635 Args.MakeArgString(Str: Section), "0x4000"})
1636 CmdArgs.push_back(Elt: A);
1637}
1638
1639void Darwin::addProfileRTLibs(const ArgList &Args,
1640 ArgStringList &CmdArgs) const {
1641 if (!needsProfileRT(Args) && !needsGCovInstrumentation(Args))
1642 return;
1643
1644 AddLinkRuntimeLib(Args, CmdArgs, Component: "profile",
1645 Opts: RuntimeLinkOptions(RLO_AlwaysLink));
1646
1647 bool ForGCOV = needsGCovInstrumentation(Args);
1648
1649 // If we have a symbol export directive and we're linking in the profile
1650 // runtime, automatically export symbols necessary to implement some of the
1651 // runtime's functionality.
1652 if (hasExportSymbolDirective(Args) && ForGCOV) {
1653 addExportedSymbol(CmdArgs, Symbol: "___gcov_dump");
1654 addExportedSymbol(CmdArgs, Symbol: "___gcov_reset");
1655 addExportedSymbol(CmdArgs, Symbol: "_writeout_fn_list");
1656 addExportedSymbol(CmdArgs, Symbol: "_reset_fn_list");
1657 }
1658
1659 // Align __llvm_prf_{cnts,bits,data} sections to the maximum expected page
1660 // alignment. This allows profile counters to be mmap()'d to disk. Note that
1661 // it's not enough to just page-align __llvm_prf_cnts: the following section
1662 // must also be page-aligned so that its data is not clobbered by mmap().
1663 //
1664 // The section alignment is only needed when continuous profile sync is
1665 // enabled, but this is expected to be the default in Xcode. Specifying the
1666 // extra alignment also allows the same binary to be used with/without sync
1667 // enabled.
1668 if (!ForGCOV) {
1669 for (auto IPSK : {llvm::IPSK_cnts, llvm::IPSK_bitmap, llvm::IPSK_data}) {
1670 addSectalignToPage(
1671 Args, CmdArgs, Segment: "__DATA",
1672 Section: llvm::getInstrProfSectionName(IPSK, OF: llvm::Triple::MachO,
1673 /*AddSegmentInfo=*/false));
1674 }
1675 }
1676}
1677
1678void DarwinClang::AddLinkSanitizerLibArgs(const ArgList &Args,
1679 ArgStringList &CmdArgs,
1680 StringRef Sanitizer,
1681 bool Shared) const {
1682 auto RLO = RuntimeLinkOptions(RLO_AlwaysLink | (Shared ? RLO_AddRPath : 0U));
1683 AddLinkRuntimeLib(Args, CmdArgs, Component: Sanitizer, Opts: RLO, IsShared: Shared);
1684}
1685
1686ToolChain::RuntimeLibType DarwinClang::GetRuntimeLibType(
1687 const ArgList &Args) const {
1688 if (Arg* A = Args.getLastArg(Ids: options::OPT_rtlib_EQ)) {
1689 StringRef Value = A->getValue();
1690 if (Value != "compiler-rt" && Value != "platform")
1691 getDriver().Diag(DiagID: clang::diag::err_drv_unsupported_rtlib_for_platform)
1692 << Value << "darwin";
1693 }
1694
1695 return ToolChain::GetRuntimeLibType(Args);
1696}
1697
1698void DarwinClang::AddLinkRuntimeLibArgs(const ArgList &Args,
1699 ArgStringList &CmdArgs,
1700 bool ForceLinkBuiltinRT) const {
1701 // Firmware uses the "bare metal" runtime lib.
1702 if (TargetPlatform == DarwinPlatformKind::Firmware)
1703 return MachO::AddLinkRuntimeLibArgs(Args, CmdArgs, ForceLinkBuiltinRT);
1704
1705 // Call once to ensure diagnostic is printed if wrong value was specified
1706 GetRuntimeLibType(Args);
1707
1708 // Darwin doesn't support real static executables, don't link any runtime
1709 // libraries with -static.
1710 if (Args.hasArg(Ids: options::OPT_static) ||
1711 Args.hasArg(Ids: options::OPT_fapple_kext) ||
1712 Args.hasArg(Ids: options::OPT_mkernel)) {
1713 if (ForceLinkBuiltinRT)
1714 AddLinkRuntimeLib(Args, CmdArgs, Component: "builtins");
1715 return;
1716 }
1717
1718 // Reject -static-libgcc for now, we can deal with this when and if someone
1719 // cares. This is useful in situations where someone wants to statically link
1720 // something like libstdc++, and needs its runtime support routines.
1721 if (const Arg *A = Args.getLastArg(Ids: options::OPT_static_libgcc)) {
1722 getDriver().Diag(DiagID: diag::err_drv_unsupported_opt) << A->getAsString(Args);
1723 return;
1724 }
1725
1726 const SanitizerArgs &Sanitize = getSanitizerArgs(JobArgs: Args);
1727
1728 if (!Sanitize.needsSharedRt()) {
1729 const char *sanitizer = nullptr;
1730 if (Sanitize.needsUbsanRt()) {
1731 sanitizer = "UndefinedBehaviorSanitizer";
1732 } else if (Sanitize.needsRtsanRt()) {
1733 sanitizer = "RealtimeSanitizer";
1734 } else if (Sanitize.needsAsanRt()) {
1735 sanitizer = "AddressSanitizer";
1736 } else if (Sanitize.needsTsanRt()) {
1737 sanitizer = "ThreadSanitizer";
1738 }
1739 if (sanitizer) {
1740 getDriver().Diag(DiagID: diag::err_drv_unsupported_static_sanitizer_darwin)
1741 << sanitizer;
1742 return;
1743 }
1744 }
1745
1746 if (Sanitize.linkRuntimes()) {
1747 if (Sanitize.needsAsanRt()) {
1748 if (Sanitize.needsStableAbi()) {
1749 AddLinkSanitizerLibArgs(Args, CmdArgs, Sanitizer: "asan_abi", /*shared=*/Shared: false);
1750 } else {
1751 assert(Sanitize.needsSharedRt() &&
1752 "Static sanitizer runtimes not supported");
1753 AddLinkSanitizerLibArgs(Args, CmdArgs, Sanitizer: "asan");
1754 }
1755 }
1756 if (Sanitize.needsRtsanRt()) {
1757 assert(Sanitize.needsSharedRt() &&
1758 "Static sanitizer runtimes not supported");
1759 AddLinkSanitizerLibArgs(Args, CmdArgs, Sanitizer: "rtsan");
1760 }
1761 if (Sanitize.needsLsanRt())
1762 AddLinkSanitizerLibArgs(Args, CmdArgs, Sanitizer: "lsan");
1763 if (Sanitize.needsUbsanRt()) {
1764 assert(Sanitize.needsSharedRt() &&
1765 "Static sanitizer runtimes not supported");
1766 AddLinkSanitizerLibArgs(
1767 Args, CmdArgs,
1768 Sanitizer: Sanitize.requiresMinimalRuntime() ? "ubsan_minimal" : "ubsan");
1769 }
1770 if (Sanitize.needsTsanRt()) {
1771 assert(Sanitize.needsSharedRt() &&
1772 "Static sanitizer runtimes not supported");
1773 AddLinkSanitizerLibArgs(Args, CmdArgs, Sanitizer: "tsan");
1774 }
1775 if (Sanitize.needsTysanRt())
1776 AddLinkSanitizerLibArgs(Args, CmdArgs, Sanitizer: "tysan");
1777 if (Sanitize.needsFuzzer() && !Args.hasArg(Ids: options::OPT_dynamiclib)) {
1778 AddLinkSanitizerLibArgs(Args, CmdArgs, Sanitizer: "fuzzer", /*shared=*/Shared: false);
1779
1780 // Libfuzzer is written in C++ and requires libcxx.
1781 // Since darwin::Linker::ConstructJob already adds -lc++ for clang++
1782 // by default if ShouldLinkCXXStdlib(Args), we only add the option if
1783 // !ShouldLinkCXXStdlib(Args). This avoids duplicate library errors
1784 // on Darwin.
1785 if (!ShouldLinkCXXStdlib(Args))
1786 AddCXXStdlibLibArgs(Args, CmdArgs);
1787 }
1788 if (Sanitize.needsStatsRt()) {
1789 AddLinkRuntimeLib(Args, CmdArgs, Component: "stats_client", Opts: RLO_AlwaysLink);
1790 AddLinkSanitizerLibArgs(Args, CmdArgs, Sanitizer: "stats");
1791 }
1792 }
1793
1794 if (Sanitize.needsMemProfRt())
1795 if (hasExportSymbolDirective(Args))
1796 addExportedSymbol(
1797 CmdArgs,
1798 Symbol: llvm::memprof::getMemprofOptionsSymbolDarwinLinkageName().data());
1799
1800 const XRayArgs &XRay = getXRayArgs(Args);
1801 if (XRay.needsXRayRt()) {
1802 AddLinkRuntimeLib(Args, CmdArgs, Component: "xray");
1803 AddLinkRuntimeLib(Args, CmdArgs, Component: "xray-basic");
1804 AddLinkRuntimeLib(Args, CmdArgs, Component: "xray-fdr");
1805 }
1806
1807 if (isTargetDriverKit() && !Args.hasArg(Ids: options::OPT_nodriverkitlib)) {
1808 CmdArgs.push_back(Elt: "-framework");
1809 CmdArgs.push_back(Elt: "DriverKit");
1810 }
1811
1812 // Otherwise link libSystem, then the dynamic runtime library, and finally any
1813 // target specific static runtime library.
1814 if (!isTargetDriverKit())
1815 CmdArgs.push_back(Elt: "-lSystem");
1816
1817 // Select the dynamic runtime library and the target specific static library.
1818 // Some old Darwin versions put builtins, libunwind, and some other stuff in
1819 // libgcc_s.1.dylib. MacOS X 10.6 and iOS 5 moved those functions to
1820 // libSystem, and made libgcc_s.1.dylib a stub. We never link libgcc_s when
1821 // building for aarch64 or iOS simulator, since libgcc_s was made obsolete
1822 // before either existed.
1823 if (getTriple().getArch() != llvm::Triple::aarch64 &&
1824 ((isTargetIOSBased() && isIPhoneOSVersionLT(V0: 5, V1: 0) &&
1825 !isTargetIOSSimulator()) ||
1826 (isTargetMacOSBased() && isMacosxVersionLT(V0: 10, V1: 6))))
1827 CmdArgs.push_back(Elt: "-lgcc_s.1");
1828 AddLinkRuntimeLib(Args, CmdArgs, Component: "builtins");
1829}
1830
1831/// Returns the most appropriate macOS target version for the current process.
1832///
1833/// If the macOS SDK version is the same or earlier than the system version,
1834/// then the SDK version is returned. Otherwise the system version is returned.
1835static std::string getSystemOrSDKMacOSVersion(StringRef MacOSSDKVersion) {
1836 llvm::Triple SystemTriple(llvm::sys::getProcessTriple());
1837 if (!SystemTriple.isMacOSX())
1838 return std::string(MacOSSDKVersion);
1839 VersionTuple SystemVersion;
1840 SystemTriple.getMacOSXVersion(Version&: SystemVersion);
1841
1842 unsigned Major, Minor, Micro;
1843 bool HadExtra;
1844 if (!Driver::GetReleaseVersion(Str: MacOSSDKVersion, Major, Minor, Micro,
1845 HadExtra))
1846 return std::string(MacOSSDKVersion);
1847 VersionTuple SDKVersion(Major, Minor, Micro);
1848
1849 if (SDKVersion > SystemVersion)
1850 return SystemVersion.getAsString();
1851 return std::string(MacOSSDKVersion);
1852}
1853
1854namespace {
1855
1856/// The Darwin OS and version that was selected or inferred from arguments or
1857/// environment.
1858struct DarwinPlatform {
1859 enum SourceKind {
1860 /// The OS was specified using the -target argument.
1861 TargetArg,
1862 /// The OS was specified using the -mtargetos= argument.
1863 MTargetOSArg,
1864 /// The OS was specified using the -m<os>-version-min argument.
1865 OSVersionArg,
1866 /// The OS was specified using the OS_DEPLOYMENT_TARGET environment.
1867 DeploymentTargetEnv,
1868 /// The OS was inferred from the SDK.
1869 InferredFromSDK,
1870 /// The OS was inferred from the -arch.
1871 InferredFromArch
1872 };
1873
1874 using DarwinPlatformKind = Darwin::DarwinPlatformKind;
1875 using DarwinEnvironmentKind = Darwin::DarwinEnvironmentKind;
1876
1877 DarwinPlatformKind getPlatform() const { return Platform; }
1878
1879 DarwinEnvironmentKind getEnvironment() const { return Environment; }
1880
1881 void setEnvironment(DarwinEnvironmentKind Kind) {
1882 Environment = Kind;
1883 InferSimulatorFromArch = false;
1884 }
1885
1886 const VersionTuple getOSVersion() const {
1887 return UnderlyingOSVersion.value_or(u: VersionTuple());
1888 }
1889
1890 VersionTuple takeOSVersion() {
1891 assert(UnderlyingOSVersion.has_value() &&
1892 "attempting to get an unset OS version");
1893 VersionTuple Result = *UnderlyingOSVersion;
1894 UnderlyingOSVersion.reset();
1895 return Result;
1896 }
1897 bool isValidOSVersion() const {
1898 return llvm::Triple::isValidVersionForOS(OSKind: getOSFromPlatform(Platform),
1899 Version: getOSVersion());
1900 }
1901
1902 VersionTuple getCanonicalOSVersion() const {
1903 return llvm::Triple::getCanonicalVersionForOS(
1904 OSKind: getOSFromPlatform(Platform), Version: getOSVersion(), /*IsInValidRange=*/true);
1905 }
1906
1907 void setOSVersion(const VersionTuple &Version) {
1908 UnderlyingOSVersion = Version;
1909 }
1910
1911 bool hasOSVersion() const { return UnderlyingOSVersion.has_value(); }
1912
1913 VersionTuple getZipperedOSVersion() const {
1914 assert(Environment == DarwinEnvironmentKind::MacCatalyst &&
1915 "zippered target version is specified only for Mac Catalyst");
1916 return ZipperedOSVersion;
1917 }
1918
1919 /// Returns true if the target OS was explicitly specified.
1920 bool isExplicitlySpecified() const { return Kind <= DeploymentTargetEnv; }
1921
1922 /// Returns true if the simulator environment can be inferred from the arch.
1923 bool canInferSimulatorFromArch() const { return InferSimulatorFromArch; }
1924
1925 const std::optional<llvm::Triple> &getTargetVariantTriple() const {
1926 return TargetVariantTriple;
1927 }
1928
1929 /// Adds the -m<os>-version-min argument to the compiler invocation.
1930 void addOSVersionMinArgument(DerivedArgList &Args, const OptTable &Opts) {
1931 auto &[Arg, OSVersionStr] = Arguments;
1932 if (Arg)
1933 return;
1934 assert(Kind != TargetArg && Kind != MTargetOSArg && Kind != OSVersionArg &&
1935 "Invalid kind");
1936 options::ID Opt;
1937 switch (Platform) {
1938 case DarwinPlatformKind::MacOS:
1939 Opt = options::OPT_mmacos_version_min_EQ;
1940 break;
1941 case DarwinPlatformKind::IPhoneOS:
1942 Opt = options::OPT_mios_version_min_EQ;
1943 break;
1944 case DarwinPlatformKind::TvOS:
1945 Opt = options::OPT_mtvos_version_min_EQ;
1946 break;
1947 case DarwinPlatformKind::WatchOS:
1948 Opt = options::OPT_mwatchos_version_min_EQ;
1949 break;
1950 default:
1951 // New platforms always explicitly provide a version in the triple.
1952 return;
1953 }
1954 Arg = Args.MakeJoinedArg(BaseArg: nullptr, Opt: Opts.getOption(Opt), Value: OSVersionStr);
1955 Args.append(A: Arg);
1956 }
1957
1958 /// Returns the OS version with the argument / environment variable that
1959 /// specified it.
1960 std::string getAsString(DerivedArgList &Args, const OptTable &Opts) {
1961 auto &[Arg, OSVersionStr] = Arguments;
1962 switch (Kind) {
1963 case TargetArg:
1964 case MTargetOSArg:
1965 case OSVersionArg:
1966 assert(Arg && "OS version argument not yet inferred");
1967 return Arg->getAsString(Args);
1968 case DeploymentTargetEnv:
1969 return (llvm::Twine(EnvVarName) + "=" + OSVersionStr).str();
1970 case InferredFromSDK:
1971 case InferredFromArch:
1972 llvm_unreachable("Cannot print arguments for inferred OS version");
1973 }
1974 llvm_unreachable("Unsupported Darwin Source Kind");
1975 }
1976
1977 // Returns the inferred source of how the OS version was resolved.
1978 std::string getInferredSource() {
1979 assert(!isExplicitlySpecified() && "OS version was not inferred");
1980 return InferredSource.str();
1981 }
1982
1983 void setEnvironment(llvm::Triple::EnvironmentType EnvType,
1984 const VersionTuple &OSVersion,
1985 const std::optional<DarwinSDKInfo> &SDKInfo) {
1986 switch (EnvType) {
1987 case llvm::Triple::Simulator:
1988 Environment = DarwinEnvironmentKind::Simulator;
1989 break;
1990 case llvm::Triple::MacABI: {
1991 Environment = DarwinEnvironmentKind::MacCatalyst;
1992 // The minimum native macOS target for MacCatalyst is macOS 10.15.
1993 ZipperedOSVersion = VersionTuple(10, 15);
1994 if (hasOSVersion() && SDKInfo) {
1995 if (const auto *MacCatalystToMacOSMapping = SDKInfo->getVersionMapping(
1996 Kind: DarwinSDKInfo::OSEnvPair::macCatalystToMacOSPair())) {
1997 if (auto MacOSVersion = MacCatalystToMacOSMapping->map(
1998 Key: OSVersion, MinimumValue: ZipperedOSVersion, MaximumValue: std::nullopt)) {
1999 ZipperedOSVersion = *MacOSVersion;
2000 }
2001 }
2002 }
2003 // In a zippered build, we could be building for a macOS target that's
2004 // lower than the version that's implied by the OS version. In that case
2005 // we need to use the minimum version as the native target version.
2006 if (TargetVariantTriple) {
2007 auto TargetVariantVersion = TargetVariantTriple->getOSVersion();
2008 if (TargetVariantVersion.getMajor()) {
2009 if (TargetVariantVersion < ZipperedOSVersion)
2010 ZipperedOSVersion = std::move(TargetVariantVersion);
2011 }
2012 }
2013 break;
2014 }
2015 default:
2016 break;
2017 }
2018 }
2019
2020 static DarwinPlatform
2021 createFromTarget(const llvm::Triple &TT, Arg *A,
2022 std::optional<llvm::Triple> TargetVariantTriple,
2023 const std::optional<DarwinSDKInfo> &SDKInfo) {
2024 DarwinPlatform Result(TargetArg, getPlatformFromOS(OS: TT.getOS()),
2025 TT.getOSVersion(), A);
2026 VersionTuple OsVersion = TT.getOSVersion();
2027 Result.TargetVariantTriple = std::move(TargetVariantTriple);
2028 Result.setEnvironment(EnvType: TT.getEnvironment(), OSVersion: OsVersion, SDKInfo);
2029 return Result;
2030 }
2031 static DarwinPlatform
2032 createFromMTargetOS(llvm::Triple::OSType OS, VersionTuple OSVersion,
2033 llvm::Triple::EnvironmentType Environment, Arg *A,
2034 const std::optional<DarwinSDKInfo> &SDKInfo) {
2035 DarwinPlatform Result(MTargetOSArg, getPlatformFromOS(OS), OSVersion, A);
2036 Result.InferSimulatorFromArch = false;
2037 Result.setEnvironment(EnvType: Environment, OSVersion, SDKInfo);
2038 return Result;
2039 }
2040 static DarwinPlatform createOSVersionArg(DarwinPlatformKind Platform, Arg *A,
2041 bool IsSimulator) {
2042 DarwinPlatform Result{OSVersionArg, Platform,
2043 getVersionFromString(Input: A->getValue()), A};
2044 if (IsSimulator)
2045 Result.Environment = DarwinEnvironmentKind::Simulator;
2046 return Result;
2047 }
2048 static DarwinPlatform createDeploymentTargetEnv(DarwinPlatformKind Platform,
2049 StringRef EnvVarName,
2050 StringRef OSVersion) {
2051 DarwinPlatform Result(DeploymentTargetEnv, Platform,
2052 getVersionFromString(Input: OSVersion));
2053 Result.EnvVarName = EnvVarName;
2054 return Result;
2055 }
2056 static DarwinPlatform createFromSDKInfo(StringRef SDKRoot,
2057 const DarwinSDKInfo &SDKInfo) {
2058 const llvm::Triple &PlatformTriple = SDKInfo.getCanonicalPlatformTriple();
2059 const llvm::Triple::OSType OS = PlatformTriple.getOS();
2060 VersionTuple Version = SDKInfo.getVersion();
2061 if (OS == llvm::Triple::MacOSX)
2062 Version = getVersionFromString(
2063 Input: getSystemOrSDKMacOSVersion(MacOSSDKVersion: Version.getAsString()));
2064 DarwinPlatform Result(InferredFromSDK, getPlatformFromOS(OS), Version);
2065 Result.Environment = getEnvKindFromEnvType(EnvironmentType: PlatformTriple.getEnvironment());
2066 Result.InferSimulatorFromArch = false;
2067 Result.InferredSource = SDKRoot;
2068 return Result;
2069 }
2070 static DarwinPlatform createFromSDK(StringRef SDKRoot,
2071 DarwinPlatformKind Platform,
2072 StringRef Value,
2073 bool IsSimulator = false) {
2074 DarwinPlatform Result(InferredFromSDK, Platform,
2075 getVersionFromString(Input: Value));
2076 if (IsSimulator)
2077 Result.Environment = DarwinEnvironmentKind::Simulator;
2078 Result.InferSimulatorFromArch = false;
2079 Result.InferredSource = SDKRoot;
2080 return Result;
2081 }
2082 static DarwinPlatform createFromArch(StringRef Arch, llvm::Triple::OSType OS,
2083 VersionTuple Version) {
2084 auto Result =
2085 DarwinPlatform(InferredFromArch, getPlatformFromOS(OS), Version);
2086 Result.InferredSource = Arch;
2087 return Result;
2088 }
2089
2090 /// Constructs an inferred SDKInfo value based on the version inferred from
2091 /// the SDK path itself. Only works for values that were created by inferring
2092 /// the platform from the SDKPath.
2093 DarwinSDKInfo inferSDKInfo() {
2094 assert(Kind == InferredFromSDK && "can infer SDK info only");
2095 llvm::Triple::OSType OS = getOSFromPlatform(Platform);
2096 llvm::Triple::EnvironmentType EnvironmentType =
2097 getEnvTypeFromEnvKind(EnvironmentKind: Environment);
2098 return DarwinSDKInfo(OS, EnvironmentType, getOSVersion(),
2099 getDisplayName(TargetPlatform: Platform, TargetEnvironment: Environment, Version: getOSVersion()),
2100 /*MaximumDeploymentTarget=*/
2101 VersionTuple(getOSVersion().getMajor(), 0, 99));
2102 }
2103
2104private:
2105 DarwinPlatform(SourceKind Kind, DarwinPlatformKind Platform, Arg *Argument)
2106 : Kind(Kind), Platform(Platform),
2107 Arguments({Argument, VersionTuple().getAsString()}) {}
2108 DarwinPlatform(SourceKind Kind, DarwinPlatformKind Platform,
2109 VersionTuple Value, Arg *Argument = nullptr)
2110 : Kind(Kind), Platform(Platform),
2111 Arguments({Argument, Value.getAsString()}) {
2112 if (!Value.empty())
2113 UnderlyingOSVersion = Value;
2114 }
2115
2116 static VersionTuple getVersionFromString(const StringRef Input) {
2117 llvm::VersionTuple Version;
2118 bool IsValid = !Version.tryParse(string: Input);
2119 assert(IsValid && "unable to convert input version to version tuple");
2120 (void)IsValid;
2121 return Version;
2122 }
2123
2124 static DarwinPlatformKind getPlatformFromOS(llvm::Triple::OSType OS) {
2125 switch (OS) {
2126 case llvm::Triple::Darwin:
2127 case llvm::Triple::MacOSX:
2128 return DarwinPlatformKind::MacOS;
2129 case llvm::Triple::IOS:
2130 return DarwinPlatformKind::IPhoneOS;
2131 case llvm::Triple::TvOS:
2132 return DarwinPlatformKind::TvOS;
2133 case llvm::Triple::WatchOS:
2134 return DarwinPlatformKind::WatchOS;
2135 case llvm::Triple::XROS:
2136 return DarwinPlatformKind::XROS;
2137 case llvm::Triple::DriverKit:
2138 return DarwinPlatformKind::DriverKit;
2139 case llvm::Triple::Firmware:
2140 return DarwinPlatformKind::Firmware;
2141 default:
2142 llvm_unreachable("Unable to infer Darwin variant");
2143 }
2144 }
2145
2146 static llvm::Triple::OSType getOSFromPlatform(DarwinPlatformKind Platform) {
2147 switch (Platform) {
2148 case DarwinPlatformKind::MacOS:
2149 return llvm::Triple::MacOSX;
2150 case DarwinPlatformKind::IPhoneOS:
2151 return llvm::Triple::IOS;
2152 case DarwinPlatformKind::TvOS:
2153 return llvm::Triple::TvOS;
2154 case DarwinPlatformKind::WatchOS:
2155 return llvm::Triple::WatchOS;
2156 case DarwinPlatformKind::DriverKit:
2157 return llvm::Triple::DriverKit;
2158 case DarwinPlatformKind::XROS:
2159 return llvm::Triple::XROS;
2160 case DarwinPlatformKind::Firmware:
2161 return llvm::Triple::Firmware;
2162 }
2163 llvm_unreachable("Unknown DarwinPlatformKind enum");
2164 }
2165
2166 static DarwinEnvironmentKind
2167 getEnvKindFromEnvType(llvm::Triple::EnvironmentType EnvironmentType) {
2168 switch (EnvironmentType) {
2169 case llvm::Triple::UnknownEnvironment:
2170 return DarwinEnvironmentKind::NativeEnvironment;
2171 case llvm::Triple::Simulator:
2172 return DarwinEnvironmentKind::Simulator;
2173 case llvm::Triple::MacABI:
2174 return DarwinEnvironmentKind::MacCatalyst;
2175 default:
2176 llvm_unreachable("Unable to infer Darwin environment");
2177 }
2178 }
2179
2180 static llvm::Triple::EnvironmentType
2181 getEnvTypeFromEnvKind(DarwinEnvironmentKind EnvironmentKind) {
2182 switch (EnvironmentKind) {
2183 case DarwinEnvironmentKind::NativeEnvironment:
2184 return llvm::Triple::UnknownEnvironment;
2185 case DarwinEnvironmentKind::Simulator:
2186 return llvm::Triple::Simulator;
2187 case DarwinEnvironmentKind::MacCatalyst:
2188 return llvm::Triple::MacABI;
2189 }
2190 llvm_unreachable("Unknown DarwinEnvironmentKind enum");
2191 }
2192
2193 static std::string getDisplayName(DarwinPlatformKind TargetPlatform,
2194 DarwinEnvironmentKind TargetEnvironment,
2195 VersionTuple Version) {
2196 SmallVector<std::string, 3> Components;
2197 switch (TargetPlatform) {
2198 case DarwinPlatformKind::MacOS:
2199 Components.push_back(Elt: "macOS");
2200 break;
2201 case DarwinPlatformKind::IPhoneOS:
2202 Components.push_back(Elt: "iOS");
2203 break;
2204 case DarwinPlatformKind::TvOS:
2205 Components.push_back(Elt: "tvOS");
2206 break;
2207 case DarwinPlatformKind::WatchOS:
2208 Components.push_back(Elt: "watchOS");
2209 break;
2210 case DarwinPlatformKind::DriverKit:
2211 Components.push_back(Elt: "DriverKit");
2212 break;
2213 default:
2214 llvm::reportFatalUsageError(reason: Twine("Platform: '") +
2215 std::to_string(val: TargetPlatform) +
2216 "' is unsupported when inferring SDK Info.");
2217 }
2218 switch (TargetEnvironment) {
2219 case DarwinEnvironmentKind::NativeEnvironment:
2220 break;
2221 case DarwinEnvironmentKind::Simulator:
2222 Components.push_back(Elt: "Simulator");
2223 break;
2224 default:
2225 llvm::reportFatalUsageError(reason: Twine("Environment: '") +
2226 std::to_string(val: TargetEnvironment) +
2227 "' is unsupported when inferring SDK Info.");
2228 }
2229 Components.push_back(Elt: Version.getAsString());
2230 return join(R&: Components, Separator: " ");
2231 }
2232
2233 SourceKind Kind;
2234 DarwinPlatformKind Platform;
2235 DarwinEnvironmentKind Environment = DarwinEnvironmentKind::NativeEnvironment;
2236 // When compiling for a zippered target, this means both target &
2237 // target variant is set on the command line, ZipperedOSVersion holds the
2238 // OSVersion tied to the main target value.
2239 VersionTuple ZipperedOSVersion;
2240 // We allow multiple ways to set or default the OS
2241 // version used for compilation. When set, UnderlyingOSVersion represents
2242 // the intended version to match the platform information computed from
2243 // arguments.
2244 std::optional<VersionTuple> UnderlyingOSVersion;
2245 bool InferSimulatorFromArch = true;
2246 std::pair<Arg *, std::string> Arguments;
2247 StringRef EnvVarName;
2248 // If the DarwinPlatform information is derived from an inferred source, this
2249 // captures what that source input was for error reporting.
2250 StringRef InferredSource;
2251 // When compiling for a zippered target, this value represents the target
2252 // triple encoded in the target variant.
2253 std::optional<llvm::Triple> TargetVariantTriple;
2254};
2255
2256/// Returns the deployment target that's specified using the -m<os>-version-min
2257/// argument.
2258std::optional<DarwinPlatform>
2259getDeploymentTargetFromOSVersionArg(DerivedArgList &Args,
2260 const Driver &TheDriver) {
2261 Arg *macOSVersion = Args.getLastArg(Ids: options::OPT_mmacos_version_min_EQ);
2262 Arg *iOSVersion = Args.getLastArg(Ids: options::OPT_mios_version_min_EQ,
2263 Ids: options::OPT_mios_simulator_version_min_EQ);
2264 Arg *TvOSVersion =
2265 Args.getLastArg(Ids: options::OPT_mtvos_version_min_EQ,
2266 Ids: options::OPT_mtvos_simulator_version_min_EQ);
2267 Arg *WatchOSVersion =
2268 Args.getLastArg(Ids: options::OPT_mwatchos_version_min_EQ,
2269 Ids: options::OPT_mwatchos_simulator_version_min_EQ);
2270
2271 auto GetDarwinPlatform =
2272 [&](DarwinPlatform::DarwinPlatformKind Platform, Arg *VersionArg,
2273 bool IsSimulator) -> std::optional<DarwinPlatform> {
2274 if (StringRef(VersionArg->getValue()).empty()) {
2275 TheDriver.Diag(DiagID: diag::err_drv_missing_version_number)
2276 << VersionArg->getAsString(Args);
2277 return std::nullopt;
2278 }
2279 return DarwinPlatform::createOSVersionArg(Platform, A: VersionArg,
2280 /*IsSimulator=*/IsSimulator);
2281 };
2282
2283 if (macOSVersion) {
2284 if (iOSVersion || TvOSVersion || WatchOSVersion) {
2285 TheDriver.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
2286 << macOSVersion->getAsString(Args)
2287 << (iOSVersion ? iOSVersion
2288 : TvOSVersion ? TvOSVersion : WatchOSVersion)
2289 ->getAsString(Args);
2290 }
2291 return GetDarwinPlatform(Darwin::MacOS, macOSVersion,
2292 /*IsSimulator=*/false);
2293
2294 } else if (iOSVersion) {
2295 if (TvOSVersion || WatchOSVersion) {
2296 TheDriver.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
2297 << iOSVersion->getAsString(Args)
2298 << (TvOSVersion ? TvOSVersion : WatchOSVersion)->getAsString(Args);
2299 }
2300 return GetDarwinPlatform(Darwin::IPhoneOS, iOSVersion,
2301 iOSVersion->getOption().getID() ==
2302 options::OPT_mios_simulator_version_min_EQ);
2303 } else if (TvOSVersion) {
2304 if (WatchOSVersion) {
2305 TheDriver.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
2306 << TvOSVersion->getAsString(Args)
2307 << WatchOSVersion->getAsString(Args);
2308 }
2309 return GetDarwinPlatform(Darwin::TvOS, TvOSVersion,
2310 TvOSVersion->getOption().getID() ==
2311 options::OPT_mtvos_simulator_version_min_EQ);
2312 } else if (WatchOSVersion)
2313 return GetDarwinPlatform(
2314 Darwin::WatchOS, WatchOSVersion,
2315 WatchOSVersion->getOption().getID() ==
2316 options::OPT_mwatchos_simulator_version_min_EQ);
2317 return std::nullopt;
2318}
2319
2320/// Returns the deployment target that's specified using the
2321/// OS_DEPLOYMENT_TARGET environment variable.
2322std::optional<DarwinPlatform>
2323getDeploymentTargetFromEnvironmentVariables(const Driver &TheDriver,
2324 const llvm::Triple &Triple) {
2325 const char *EnvVars[] = {
2326 "MACOSX_DEPLOYMENT_TARGET",
2327 "IPHONEOS_DEPLOYMENT_TARGET",
2328 "TVOS_DEPLOYMENT_TARGET",
2329 "WATCHOS_DEPLOYMENT_TARGET",
2330 "DRIVERKIT_DEPLOYMENT_TARGET",
2331 "XROS_DEPLOYMENT_TARGET"
2332 };
2333 std::string Targets[std::size(EnvVars)];
2334 for (const auto &I : llvm::enumerate(First: llvm::ArrayRef(EnvVars))) {
2335 if (char *Env = ::getenv(name: I.value()))
2336 Targets[I.index()] = Env;
2337 }
2338
2339 // Allow conflicts among OSX and iOS for historical reasons, but choose the
2340 // default platform.
2341 if (!Targets[Darwin::MacOS].empty() &&
2342 (!Targets[Darwin::IPhoneOS].empty() ||
2343 !Targets[Darwin::WatchOS].empty() || !Targets[Darwin::TvOS].empty() ||
2344 !Targets[Darwin::XROS].empty())) {
2345 if (Triple.getArch() == llvm::Triple::arm ||
2346 Triple.getArch() == llvm::Triple::aarch64 ||
2347 Triple.getArch() == llvm::Triple::thumb)
2348 Targets[Darwin::MacOS] = "";
2349 else
2350 Targets[Darwin::IPhoneOS] = Targets[Darwin::WatchOS] =
2351 Targets[Darwin::TvOS] = Targets[Darwin::XROS] = "";
2352 } else {
2353 // Don't allow conflicts in any other platform.
2354 unsigned FirstTarget = std::size(Targets);
2355 for (unsigned I = 0; I != std::size(Targets); ++I) {
2356 if (Targets[I].empty())
2357 continue;
2358 if (FirstTarget == std::size(Targets))
2359 FirstTarget = I;
2360 else
2361 TheDriver.Diag(DiagID: diag::err_drv_conflicting_deployment_targets)
2362 << Targets[FirstTarget] << Targets[I];
2363 }
2364 }
2365
2366 for (const auto &Target : llvm::enumerate(First: llvm::ArrayRef(Targets))) {
2367 if (!Target.value().empty())
2368 return DarwinPlatform::createDeploymentTargetEnv(
2369 Platform: (Darwin::DarwinPlatformKind)Target.index(), EnvVarName: EnvVars[Target.index()],
2370 OSVersion: Target.value());
2371 }
2372 return std::nullopt;
2373}
2374
2375/// Tries to infer the deployment target from the SDK specified by -isysroot
2376/// (or SDKROOT). Uses the version specified in the SDKSettings.json file if
2377/// it's available.
2378std::optional<DarwinPlatform>
2379inferDeploymentTargetFromSDK(DerivedArgList &Args,
2380 const std::optional<DarwinSDKInfo> &SDKInfo) {
2381 const Arg *A = Args.getLastArg(Ids: options::OPT_isysroot);
2382 if (!A)
2383 return std::nullopt;
2384 StringRef isysroot = A->getValue();
2385 if (SDKInfo)
2386 return DarwinPlatform::createFromSDKInfo(SDKRoot: isysroot, SDKInfo: *SDKInfo);
2387
2388 StringRef SDK = Darwin::getSDKName(isysroot);
2389 if (!SDK.size())
2390 return std::nullopt;
2391
2392 std::string Version;
2393 // Slice the version number out.
2394 // Version number is between the first and the last number.
2395 size_t StartVer = SDK.find_first_of(Chars: "0123456789");
2396 size_t EndVer = SDK.find_last_of(Chars: "0123456789");
2397 if (StartVer != StringRef::npos && EndVer > StartVer)
2398 Version = std::string(SDK.slice(Start: StartVer, End: EndVer + 1));
2399 if (Version.empty())
2400 return std::nullopt;
2401
2402 if (SDK.starts_with(Prefix: "iPhoneOS") || SDK.starts_with(Prefix: "iPhoneSimulator"))
2403 return DarwinPlatform::createFromSDK(
2404 SDKRoot: isysroot, Platform: Darwin::IPhoneOS, Value: Version,
2405 /*IsSimulator=*/SDK.starts_with(Prefix: "iPhoneSimulator"));
2406 else if (SDK.starts_with(Prefix: "MacOSX"))
2407 return DarwinPlatform::createFromSDK(SDKRoot: isysroot, Platform: Darwin::MacOS,
2408 Value: getSystemOrSDKMacOSVersion(MacOSSDKVersion: Version));
2409 else if (SDK.starts_with(Prefix: "WatchOS") || SDK.starts_with(Prefix: "WatchSimulator"))
2410 return DarwinPlatform::createFromSDK(
2411 SDKRoot: isysroot, Platform: Darwin::WatchOS, Value: Version,
2412 /*IsSimulator=*/SDK.starts_with(Prefix: "WatchSimulator"));
2413 else if (SDK.starts_with(Prefix: "AppleTVOS") || SDK.starts_with(Prefix: "AppleTVSimulator"))
2414 return DarwinPlatform::createFromSDK(
2415 SDKRoot: isysroot, Platform: Darwin::TvOS, Value: Version,
2416 /*IsSimulator=*/SDK.starts_with(Prefix: "AppleTVSimulator"));
2417 else if (SDK.starts_with(Prefix: "DriverKit"))
2418 return DarwinPlatform::createFromSDK(SDKRoot: isysroot, Platform: Darwin::DriverKit, Value: Version);
2419 return std::nullopt;
2420}
2421
2422// Compute & get the OS Version when the target triple omitted one.
2423VersionTuple getInferredOSVersion(llvm::Triple::OSType OS,
2424 const llvm::Triple &Triple,
2425 const Driver &TheDriver) {
2426 VersionTuple OsVersion;
2427 llvm::Triple SystemTriple(llvm::sys::getProcessTriple());
2428 switch (OS) {
2429 case llvm::Triple::Darwin:
2430 case llvm::Triple::MacOSX:
2431 // If there is no version specified on triple, and both host and target are
2432 // macos, use the host triple to infer OS version.
2433 if (Triple.isMacOSX() && SystemTriple.isMacOSX() &&
2434 !Triple.getOSMajorVersion())
2435 SystemTriple.getMacOSXVersion(Version&: OsVersion);
2436 else if (!Triple.getMacOSXVersion(Version&: OsVersion))
2437 TheDriver.Diag(DiagID: diag::err_drv_invalid_darwin_version)
2438 << Triple.getOSName();
2439 break;
2440 case llvm::Triple::IOS:
2441 if (Triple.isMacCatalystEnvironment() && !Triple.getOSMajorVersion()) {
2442 OsVersion = VersionTuple(13, 1);
2443 } else
2444 OsVersion = Triple.getiOSVersion();
2445 break;
2446 case llvm::Triple::TvOS:
2447 OsVersion = Triple.getOSVersion();
2448 break;
2449 case llvm::Triple::WatchOS:
2450 OsVersion = Triple.getWatchOSVersion();
2451 break;
2452 case llvm::Triple::DriverKit:
2453 OsVersion = Triple.getDriverKitVersion();
2454 break;
2455 default:
2456 OsVersion = Triple.getOSVersion();
2457 if (!OsVersion.getMajor())
2458 OsVersion = OsVersion.withMajorReplaced(NewMajor: 1);
2459 break;
2460 }
2461 return OsVersion;
2462}
2463
2464/// Tries to infer the target OS from the -arch.
2465std::optional<DarwinPlatform>
2466inferDeploymentTargetFromArch(DerivedArgList &Args, const Darwin &Toolchain,
2467 const llvm::Triple &Triple,
2468 const Driver &TheDriver) {
2469 llvm::Triple::OSType OSTy = llvm::Triple::UnknownOS;
2470
2471 StringRef MachOArchName = Toolchain.getMachOArchName(Args);
2472 if (MachOArchName == "arm64" || MachOArchName == "arm64e")
2473 OSTy = llvm::Triple::MacOSX;
2474 else if (MachOArchName == "armv7" || MachOArchName == "armv7s" ||
2475 MachOArchName == "armv6")
2476 OSTy = llvm::Triple::IOS;
2477 else if (MachOArchName == "armv7k" || MachOArchName == "arm64_32")
2478 OSTy = llvm::Triple::WatchOS;
2479 else if (MachOArchName != "armv6m" && MachOArchName != "armv7m" &&
2480 MachOArchName != "armv7em" && MachOArchName != "armv8m.base" &&
2481 MachOArchName != "armv8m.main" && MachOArchName != "armv8.1m.main")
2482 OSTy = llvm::Triple::MacOSX;
2483 if (OSTy == llvm::Triple::UnknownOS)
2484 return std::nullopt;
2485 return DarwinPlatform::createFromArch(
2486 Arch: MachOArchName, OS: OSTy, Version: getInferredOSVersion(OS: OSTy, Triple, TheDriver));
2487}
2488
2489/// Returns the deployment target that's specified using the -target option.
2490std::optional<DarwinPlatform> getDeploymentTargetFromTargetArg(
2491 DerivedArgList &Args, const llvm::Triple &Triple, const Driver &TheDriver,
2492 const std::optional<DarwinSDKInfo> &SDKInfo) {
2493 if (!Args.hasArg(Ids: options::OPT_target))
2494 return std::nullopt;
2495 if (Triple.getOS() == llvm::Triple::Darwin ||
2496 Triple.getOS() == llvm::Triple::UnknownOS)
2497 return std::nullopt;
2498 std::optional<llvm::Triple> TargetVariantTriple;
2499 for (const Arg *A : Args.filtered(Ids: options::OPT_darwin_target_variant)) {
2500 llvm::Triple TVT(A->getValue());
2501 // Find a matching <arch>-<vendor> target variant triple that can be used.
2502 if ((Triple.getArch() == llvm::Triple::aarch64 ||
2503 TVT.getArchName() == Triple.getArchName()) &&
2504 TVT.getArch() == Triple.getArch() &&
2505 TVT.getSubArch() == Triple.getSubArch() &&
2506 TVT.getVendor() == Triple.getVendor()) {
2507 if (TargetVariantTriple)
2508 continue;
2509 A->claim();
2510 // Accept a -target-variant triple when compiling code that may run on
2511 // macOS or Mac Catalyst.
2512 if ((Triple.isMacOSX() && TVT.getOS() == llvm::Triple::IOS &&
2513 TVT.isMacCatalystEnvironment()) ||
2514 (TVT.isMacOSX() && Triple.getOS() == llvm::Triple::IOS &&
2515 Triple.isMacCatalystEnvironment())) {
2516 TargetVariantTriple = TVT;
2517 continue;
2518 }
2519 TheDriver.Diag(DiagID: diag::err_drv_target_variant_invalid)
2520 << A->getSpelling() << A->getValue();
2521 }
2522 }
2523 DarwinPlatform PlatformAndVersion = DarwinPlatform::createFromTarget(
2524 TT: Triple, A: Args.getLastArg(Ids: options::OPT_target), TargetVariantTriple,
2525 SDKInfo);
2526
2527 return PlatformAndVersion;
2528}
2529
2530/// Returns the deployment target that's specified using the -mtargetos option.
2531std::optional<DarwinPlatform> getDeploymentTargetFromMTargetOSArg(
2532 DerivedArgList &Args, const Driver &TheDriver,
2533 const std::optional<DarwinSDKInfo> &SDKInfo) {
2534 auto *A = Args.getLastArg(Ids: options::OPT_mtargetos_EQ);
2535 if (!A)
2536 return std::nullopt;
2537 llvm::Triple TT(llvm::Twine("unknown-apple-") + A->getValue());
2538 switch (TT.getOS()) {
2539 case llvm::Triple::MacOSX:
2540 case llvm::Triple::IOS:
2541 case llvm::Triple::TvOS:
2542 case llvm::Triple::WatchOS:
2543 case llvm::Triple::XROS:
2544 break;
2545 default:
2546 TheDriver.Diag(DiagID: diag::err_drv_invalid_os_in_arg)
2547 << TT.getOSName() << A->getAsString(Args);
2548 return std::nullopt;
2549 }
2550
2551 VersionTuple Version = TT.getOSVersion();
2552 if (!Version.getMajor()) {
2553 TheDriver.Diag(DiagID: diag::err_drv_invalid_version_number)
2554 << A->getAsString(Args);
2555 return std::nullopt;
2556 }
2557 return DarwinPlatform::createFromMTargetOS(OS: TT.getOS(), OSVersion: Version,
2558 Environment: TT.getEnvironment(), A, SDKInfo);
2559}
2560
2561std::optional<DarwinSDKInfo> parseSDKSettings(llvm::vfs::FileSystem &VFS,
2562 const ArgList &Args,
2563 const Driver &TheDriver) {
2564 const Arg *A = Args.getLastArg(Ids: options::OPT_isysroot);
2565 if (!A)
2566 return std::nullopt;
2567 StringRef isysroot = A->getValue();
2568 auto SDKInfoOrErr = parseDarwinSDKInfo(VFS, SDKRootPath: isysroot);
2569 if (!SDKInfoOrErr) {
2570 llvm::consumeError(Err: SDKInfoOrErr.takeError());
2571 TheDriver.Diag(DiagID: diag::warn_drv_darwin_sdk_invalid_settings);
2572 return std::nullopt;
2573 }
2574 return *SDKInfoOrErr;
2575}
2576
2577} // namespace
2578
2579void Darwin::AddDeploymentTarget(DerivedArgList &Args) const {
2580 const OptTable &Opts = getDriver().getOpts();
2581 // TryXcselect keeps track of whether we use xcselect to find the SDK
2582 // when CLANG_USE_XCSELECT is enabled. Currently, we do this when we
2583 // do not have a sysroot from -isysroot, --sysroot, or SDKROOT, and
2584 // we do not have --no-xcselect.
2585 bool TryXcselect = false;
2586 (void)TryXcselect;
2587
2588 // Support allowing the SDKROOT environment variable used by xcrun and other
2589 // Xcode tools to define the default sysroot, by making it the default for
2590 // isysroot.
2591 if (const Arg *A = Args.getLastArg(Ids: options::OPT_isysroot)) {
2592 // Warn if the path does not exist.
2593 if (!getVFS().exists(Path: A->getValue()))
2594 getDriver().Diag(DiagID: clang::diag::warn_missing_sysroot) << A->getValue();
2595 } else if (const char *env = ::getenv(name: "SDKROOT")) {
2596 // We only use this value as the default if it is an absolute path,
2597 // exists, and it is not the root path.
2598 if (llvm::sys::path::is_absolute(path: env) && getVFS().exists(Path: env) &&
2599 StringRef(env) != "/") {
2600 Args.append(A: Args.MakeSeparateArg(
2601 BaseArg: nullptr, Opt: Opts.getOption(Opt: options::OPT_isysroot), Value: env));
2602 }
2603 } else {
2604 TryXcselect = !Args.hasArg(Ids: options::OPT__sysroot_EQ) &&
2605 !Args.hasArg(Ids: options::OPT_no_xcselect);
2606 }
2607
2608 // Read the SDKSettings.json file for more information, like the SDK version
2609 // that we can pass down to the compiler.
2610 SDKInfo = parseSDKSettings(VFS&: getVFS(), Args, TheDriver: getDriver());
2611 // FIXME: If SDKInfo is std::nullopt, diagnose a bad isysroot value (e.g.
2612 // doesn't end in .sdk).
2613
2614 // The OS and the version can be specified using the -target argument.
2615 std::optional<DarwinPlatform> PlatformAndVersion =
2616 getDeploymentTargetFromTargetArg(Args, Triple: getTriple(), TheDriver: getDriver(), SDKInfo);
2617 if (PlatformAndVersion) {
2618 // Disallow mixing -target and -mtargetos=.
2619 if (const auto *MTargetOSArg = Args.getLastArg(Ids: options::OPT_mtargetos_EQ)) {
2620 std::string TargetArgStr = PlatformAndVersion->getAsString(Args, Opts);
2621 std::string MTargetOSArgStr = MTargetOSArg->getAsString(Args);
2622 getDriver().Diag(DiagID: diag::err_drv_cannot_mix_options)
2623 << TargetArgStr << MTargetOSArgStr;
2624 }
2625 // Implicitly allow resolving the OS version when it wasn't explicitly set.
2626 bool TripleProvidedOSVersion = PlatformAndVersion->hasOSVersion();
2627 if (!TripleProvidedOSVersion)
2628 PlatformAndVersion->setOSVersion(
2629 getInferredOSVersion(OS: getTriple().getOS(), Triple: getTriple(), TheDriver: getDriver()));
2630
2631 std::optional<DarwinPlatform> PlatformAndVersionFromOSVersionArg =
2632 getDeploymentTargetFromOSVersionArg(Args, TheDriver: getDriver());
2633 if (PlatformAndVersionFromOSVersionArg) {
2634 unsigned TargetMajor, TargetMinor, TargetMicro;
2635 bool TargetExtra;
2636 unsigned ArgMajor, ArgMinor, ArgMicro;
2637 bool ArgExtra;
2638 if (PlatformAndVersion->getPlatform() !=
2639 PlatformAndVersionFromOSVersionArg->getPlatform() ||
2640 (Driver::GetReleaseVersion(
2641 Str: PlatformAndVersion->getOSVersion().getAsString(), Major&: TargetMajor,
2642 Minor&: TargetMinor, Micro&: TargetMicro, HadExtra&: TargetExtra) &&
2643 Driver::GetReleaseVersion(
2644 Str: PlatformAndVersionFromOSVersionArg->getOSVersion().getAsString(),
2645 Major&: ArgMajor, Minor&: ArgMinor, Micro&: ArgMicro, HadExtra&: ArgExtra) &&
2646 (VersionTuple(TargetMajor, TargetMinor, TargetMicro) !=
2647 VersionTuple(ArgMajor, ArgMinor, ArgMicro) ||
2648 TargetExtra != ArgExtra))) {
2649 // Select the OS version from the -m<os>-version-min argument when
2650 // the -target does not include an OS version.
2651 if (PlatformAndVersion->getPlatform() ==
2652 PlatformAndVersionFromOSVersionArg->getPlatform() &&
2653 !TripleProvidedOSVersion) {
2654 PlatformAndVersion->setOSVersion(
2655 PlatformAndVersionFromOSVersionArg->getOSVersion());
2656 } else {
2657 // Warn about -m<os>-version-min that doesn't match the OS version
2658 // that's specified in the target.
2659 std::string OSVersionArg =
2660 PlatformAndVersionFromOSVersionArg->getAsString(Args, Opts);
2661 std::string TargetArg = PlatformAndVersion->getAsString(Args, Opts);
2662 getDriver().Diag(DiagID: clang::diag::warn_drv_overriding_option)
2663 << OSVersionArg << TargetArg;
2664 }
2665 }
2666 }
2667 } else if ((PlatformAndVersion = getDeploymentTargetFromMTargetOSArg(
2668 Args, TheDriver: getDriver(), SDKInfo))) {
2669 // The OS target can be specified using the -mtargetos= argument.
2670 // Disallow mixing -mtargetos= and -m<os>version-min=.
2671 std::optional<DarwinPlatform> PlatformAndVersionFromOSVersionArg =
2672 getDeploymentTargetFromOSVersionArg(Args, TheDriver: getDriver());
2673 if (PlatformAndVersionFromOSVersionArg) {
2674 std::string MTargetOSArgStr = PlatformAndVersion->getAsString(Args, Opts);
2675 std::string OSVersionArgStr =
2676 PlatformAndVersionFromOSVersionArg->getAsString(Args, Opts);
2677 getDriver().Diag(DiagID: diag::err_drv_cannot_mix_options)
2678 << MTargetOSArgStr << OSVersionArgStr;
2679 }
2680 } else {
2681 // The OS target can be specified using the -m<os>version-min argument.
2682 PlatformAndVersion = getDeploymentTargetFromOSVersionArg(Args, TheDriver: getDriver());
2683 // If no deployment target was specified on the command line, check for
2684 // environment defines.
2685 if (!PlatformAndVersion) {
2686 PlatformAndVersion =
2687 getDeploymentTargetFromEnvironmentVariables(TheDriver: getDriver(), Triple: getTriple());
2688 if (PlatformAndVersion) {
2689 // Don't infer simulator from the arch when the SDK is also specified.
2690 std::optional<DarwinPlatform> SDKTarget =
2691 inferDeploymentTargetFromSDK(Args, SDKInfo);
2692 if (SDKTarget)
2693 PlatformAndVersion->setEnvironment(SDKTarget->getEnvironment());
2694 }
2695 }
2696 // If there is no command-line argument to specify the Target version and
2697 // no environment variable defined, see if we can set the default based
2698 // on -isysroot using SDKSettings.json if it exists.
2699 if (!PlatformAndVersion) {
2700 PlatformAndVersion = inferDeploymentTargetFromSDK(Args, SDKInfo);
2701 /// If the target was successfully constructed from the SDK path, try to
2702 /// infer the SDK info if the SDK doesn't have it.
2703 if (PlatformAndVersion && !SDKInfo)
2704 SDKInfo = PlatformAndVersion->inferSDKInfo();
2705 }
2706 // If no OS targets have been specified, try to guess platform from -target
2707 // or arch name and compute the version from the triple.
2708 if (!PlatformAndVersion)
2709 PlatformAndVersion =
2710 inferDeploymentTargetFromArch(Args, Toolchain: *this, Triple: getTriple(), TheDriver: getDriver());
2711 }
2712
2713 assert(PlatformAndVersion && "Unable to infer Darwin variant");
2714 if (!PlatformAndVersion->isValidOSVersion()) {
2715 if (PlatformAndVersion->isExplicitlySpecified())
2716 getDriver().Diag(DiagID: diag::err_drv_invalid_version_number)
2717 << PlatformAndVersion->getAsString(Args, Opts);
2718 else
2719 getDriver().Diag(DiagID: diag::err_drv_invalid_version_number_inferred)
2720 << PlatformAndVersion->getOSVersion().getAsString()
2721 << PlatformAndVersion->getInferredSource();
2722 }
2723 // After the deployment OS version has been resolved, set it to the canonical
2724 // version before further error detection and converting to a proper target
2725 // triple.
2726 VersionTuple CanonicalVersion = PlatformAndVersion->getCanonicalOSVersion();
2727 if (CanonicalVersion != PlatformAndVersion->getOSVersion()) {
2728 getDriver().Diag(DiagID: diag::warn_drv_overriding_deployment_version)
2729 << PlatformAndVersion->getOSVersion().getAsString()
2730 << CanonicalVersion.getAsString();
2731 PlatformAndVersion->setOSVersion(CanonicalVersion);
2732 }
2733
2734 PlatformAndVersion->addOSVersionMinArgument(Args, Opts);
2735 DarwinPlatformKind Platform = PlatformAndVersion->getPlatform();
2736
2737 unsigned Major, Minor, Micro;
2738 bool HadExtra;
2739 // The major version should not be over this number.
2740 const unsigned MajorVersionLimit = 1000;
2741 const VersionTuple OSVersion = PlatformAndVersion->takeOSVersion();
2742 const std::string OSVersionStr = OSVersion.getAsString();
2743 // Set the tool chain target information.
2744 if (Platform == MacOS) {
2745#ifdef CLANG_USE_XCSELECT
2746 if (TryXcselect) {
2747 char *p;
2748 if (!::xcselect_host_sdk_path(CLANG_XCSELECT_HOST_SDK_POLICY, &p)) {
2749 Args.append(Args.MakeSeparateArg(
2750 nullptr, Opts.getOption(options::OPT_isysroot), p));
2751 ::free(p);
2752 if (!SDKInfo)
2753 SDKInfo = parseSDKSettings(getVFS(), Args, getDriver());
2754 }
2755 }
2756#endif
2757 if (!Driver::GetReleaseVersion(Str: OSVersionStr, Major, Minor, Micro,
2758 HadExtra) ||
2759 HadExtra || Major < 10 || Major >= MajorVersionLimit || Minor >= 100 ||
2760 Micro >= 100)
2761 getDriver().Diag(DiagID: diag::err_drv_invalid_version_number)
2762 << PlatformAndVersion->getAsString(Args, Opts);
2763 } else if (Platform == IPhoneOS) {
2764 if (!Driver::GetReleaseVersion(Str: OSVersionStr, Major, Minor, Micro,
2765 HadExtra) ||
2766 HadExtra || Major >= MajorVersionLimit || Minor >= 100 || Micro >= 100)
2767 getDriver().Diag(DiagID: diag::err_drv_invalid_version_number)
2768 << PlatformAndVersion->getAsString(Args, Opts);
2769 ;
2770 if (PlatformAndVersion->getEnvironment() == MacCatalyst &&
2771 (Major < 13 || (Major == 13 && Minor < 1))) {
2772 getDriver().Diag(DiagID: diag::err_drv_invalid_version_number)
2773 << PlatformAndVersion->getAsString(Args, Opts);
2774 Major = 13;
2775 Minor = 1;
2776 Micro = 0;
2777 }
2778 // For 32-bit targets, the deployment target for iOS has to be earlier than
2779 // iOS 11.
2780 if (getTriple().isArch32Bit() && Major >= 11) {
2781 // If the deployment target is explicitly specified, print a diagnostic.
2782 if (PlatformAndVersion->isExplicitlySpecified()) {
2783 if (PlatformAndVersion->getEnvironment() == MacCatalyst)
2784 getDriver().Diag(DiagID: diag::err_invalid_macos_32bit_deployment_target);
2785 else
2786 getDriver().Diag(DiagID: diag::warn_invalid_ios_deployment_target)
2787 << PlatformAndVersion->getAsString(Args, Opts);
2788 // Otherwise, set it to 10.99.99.
2789 } else {
2790 Major = 10;
2791 Minor = 99;
2792 Micro = 99;
2793 }
2794 }
2795 } else if (Platform == TvOS) {
2796 if (!Driver::GetReleaseVersion(Str: OSVersionStr, Major, Minor, Micro,
2797 HadExtra) ||
2798 HadExtra || Major >= MajorVersionLimit || Minor >= 100 || Micro >= 100)
2799 getDriver().Diag(DiagID: diag::err_drv_invalid_version_number)
2800 << PlatformAndVersion->getAsString(Args, Opts);
2801 } else if (Platform == WatchOS) {
2802 if (!Driver::GetReleaseVersion(Str: OSVersionStr, Major, Minor, Micro,
2803 HadExtra) ||
2804 HadExtra || Major >= MajorVersionLimit || Minor >= 100 || Micro >= 100)
2805 getDriver().Diag(DiagID: diag::err_drv_invalid_version_number)
2806 << PlatformAndVersion->getAsString(Args, Opts);
2807 } else if (Platform == DriverKit) {
2808 if (!Driver::GetReleaseVersion(Str: OSVersionStr, Major, Minor, Micro,
2809 HadExtra) ||
2810 HadExtra || Major < 19 || Major >= MajorVersionLimit || Minor >= 100 ||
2811 Micro >= 100)
2812 getDriver().Diag(DiagID: diag::err_drv_invalid_version_number)
2813 << PlatformAndVersion->getAsString(Args, Opts);
2814 } else {
2815 if (!Driver::GetReleaseVersion(Str: OSVersionStr, Major, Minor, Micro,
2816 HadExtra) ||
2817 HadExtra || Major < 1 || Major >= MajorVersionLimit || Minor >= 100 ||
2818 Micro >= 100)
2819 getDriver().Diag(DiagID: diag::err_drv_invalid_version_number)
2820 << PlatformAndVersion->getAsString(Args, Opts);
2821 }
2822
2823 DarwinEnvironmentKind Environment = PlatformAndVersion->getEnvironment();
2824 // Recognize iOS targets with an x86 architecture as the iOS simulator.
2825 if (Environment == NativeEnvironment && Platform != MacOS &&
2826 Platform != DriverKit &&
2827 PlatformAndVersion->canInferSimulatorFromArch() && getTriple().isX86())
2828 Environment = Simulator;
2829
2830 VersionTuple ZipperedOSVersion;
2831 if (Environment == MacCatalyst)
2832 ZipperedOSVersion = PlatformAndVersion->getZipperedOSVersion();
2833 setTarget(Platform, Environment, Major, Minor, Micro, NativeTargetVersion: ZipperedOSVersion);
2834 TargetVariantTriple = PlatformAndVersion->getTargetVariantTriple();
2835 if (TargetVariantTriple &&
2836 !llvm::Triple::isValidVersionForOS(OSKind: TargetVariantTriple->getOS(),
2837 Version: TargetVariantTriple->getOSVersion())) {
2838 getDriver().Diag(DiagID: diag::err_drv_invalid_version_number)
2839 << TargetVariantTriple->str();
2840 }
2841}
2842
2843bool DarwinClang::HasPlatformPrefix(const llvm::Triple &T) const {
2844 if (SDKInfo)
2845 return !SDKInfo->getPlatformPrefix(Triple: T).empty();
2846 else
2847 return Darwin::HasPlatformPrefix(T);
2848}
2849
2850// For certain platforms/environments almost all resources (e.g., headers) are
2851// located in sub-directories, e.g., for DriverKit they live in
2852// <SYSROOT>/System/DriverKit/usr/include (instead of <SYSROOT>/usr/include).
2853void DarwinClang::AppendPlatformPrefix(SmallString<128> &Path,
2854 const llvm::Triple &T) const {
2855 if (SDKInfo) {
2856 const StringRef PlatformPrefix = SDKInfo->getPlatformPrefix(Triple: T);
2857 if (!PlatformPrefix.empty())
2858 llvm::sys::path::append(path&: Path, a: PlatformPrefix);
2859 } else if (T.isDriverKit()) {
2860 // The first version of DriverKit didn't have SDKSettings.json, manually add
2861 // its prefix.
2862 llvm::sys::path::append(path&: Path, a: "System", b: "DriverKit");
2863 }
2864}
2865
2866// Returns the effective sysroot from either -isysroot or --sysroot, plus the
2867// platform prefix (if any).
2868llvm::SmallString<128>
2869AppleMachO::GetEffectiveSysroot(const llvm::opt::ArgList &DriverArgs) const {
2870 llvm::SmallString<128> Path("/");
2871 if (DriverArgs.hasArg(Ids: options::OPT_isysroot))
2872 Path = DriverArgs.getLastArgValue(Id: options::OPT_isysroot);
2873 else if (!getDriver().SysRoot.empty())
2874 Path = getDriver().SysRoot;
2875
2876 if (hasEffectiveTriple()) {
2877 AppendPlatformPrefix(Path, T: getEffectiveTriple());
2878 }
2879 return Path;
2880}
2881
2882void AppleMachO::AddClangSystemIncludeArgs(
2883 const llvm::opt::ArgList &DriverArgs,
2884 llvm::opt::ArgStringList &CC1Args) const {
2885 const Driver &D = getDriver();
2886
2887 llvm::SmallString<128> Sysroot = GetEffectiveSysroot(DriverArgs);
2888
2889 bool NoStdInc = DriverArgs.hasArg(Ids: options::OPT_nostdinc);
2890 bool NoStdlibInc = DriverArgs.hasArg(Ids: options::OPT_nostdlibinc);
2891 bool NoBuiltinInc = DriverArgs.hasFlag(
2892 Pos: options::OPT_nobuiltininc, Neg: options::OPT_ibuiltininc, /*Default=*/false);
2893 bool ForceBuiltinInc = DriverArgs.hasFlag(
2894 Pos: options::OPT_ibuiltininc, Neg: options::OPT_nobuiltininc, /*Default=*/false);
2895
2896 // Add <sysroot>/usr/local/include
2897 if (!NoStdInc && !NoStdlibInc) {
2898 SmallString<128> P(Sysroot);
2899 llvm::sys::path::append(path&: P, a: "usr", b: "local", c: "include");
2900 addSystemInclude(DriverArgs, CC1Args, Path: P);
2901 }
2902
2903 // Add the Clang builtin headers (<resource>/include)
2904 if (!(NoStdInc && !ForceBuiltinInc) && !NoBuiltinInc) {
2905 SmallString<128> P(D.ResourceDir);
2906 llvm::sys::path::append(path&: P, a: "include");
2907 addSystemInclude(DriverArgs, CC1Args, Path: P);
2908 }
2909
2910 if (NoStdInc || NoStdlibInc)
2911 return;
2912
2913 // Check for configure-time C include directories.
2914 llvm::StringRef CIncludeDirs(C_INCLUDE_DIRS);
2915 if (!CIncludeDirs.empty()) {
2916 llvm::SmallVector<llvm::StringRef, 5> dirs;
2917 CIncludeDirs.split(A&: dirs, Separator: ":");
2918 for (llvm::StringRef dir : dirs) {
2919 llvm::StringRef Prefix =
2920 llvm::sys::path::is_absolute(path: dir) ? "" : llvm::StringRef(Sysroot);
2921 addExternCSystemInclude(DriverArgs, CC1Args, Path: Prefix + dir);
2922 }
2923 } else {
2924 // Otherwise, add <sysroot>/usr/include.
2925 SmallString<128> P(Sysroot);
2926 llvm::sys::path::append(path&: P, a: "usr", b: "include");
2927 addExternCSystemInclude(DriverArgs, CC1Args, Path: P.str());
2928 }
2929}
2930
2931void DarwinClang::AddClangSystemIncludeArgs(
2932 const llvm::opt::ArgList &DriverArgs,
2933 llvm::opt::ArgStringList &CC1Args) const {
2934 AppleMachO::AddClangSystemIncludeArgs(DriverArgs, CC1Args);
2935
2936 if (DriverArgs.hasArg(Ids: options::OPT_nostdinc, Ids: options::OPT_nostdlibinc))
2937 return;
2938
2939 llvm::SmallString<128> Sysroot = GetEffectiveSysroot(DriverArgs);
2940
2941 // Add <sysroot>/System/Library/Frameworks
2942 // Add <sysroot>/System/Library/SubFrameworks
2943 // Add <sysroot>/Library/Frameworks
2944 SmallString<128> P1(Sysroot), P2(Sysroot), P3(Sysroot);
2945 llvm::sys::path::append(path&: P1, a: "System", b: "Library", c: "Frameworks");
2946 llvm::sys::path::append(path&: P2, a: "System", b: "Library", c: "SubFrameworks");
2947 llvm::sys::path::append(path&: P3, a: "Library", b: "Frameworks");
2948 addSystemFrameworkIncludes(DriverArgs, CC1Args, Paths: {P1, P2, P3});
2949}
2950
2951bool DarwinClang::AddGnuCPlusPlusIncludePaths(const llvm::opt::ArgList &DriverArgs,
2952 llvm::opt::ArgStringList &CC1Args,
2953 llvm::SmallString<128> Base,
2954 llvm::StringRef Version,
2955 llvm::StringRef ArchDir,
2956 llvm::StringRef BitDir) const {
2957 llvm::sys::path::append(path&: Base, a: Version);
2958
2959 // Add the base dir
2960 addSystemInclude(DriverArgs, CC1Args, Path: Base);
2961
2962 // Add the multilib dirs
2963 {
2964 llvm::SmallString<128> P = Base;
2965 if (!ArchDir.empty())
2966 llvm::sys::path::append(path&: P, a: ArchDir);
2967 if (!BitDir.empty())
2968 llvm::sys::path::append(path&: P, a: BitDir);
2969 addSystemInclude(DriverArgs, CC1Args, Path: P);
2970 }
2971
2972 // Add the backward dir
2973 {
2974 llvm::SmallString<128> P = Base;
2975 llvm::sys::path::append(path&: P, a: "backward");
2976 addSystemInclude(DriverArgs, CC1Args, Path: P);
2977 }
2978
2979 return getVFS().exists(Path: Base);
2980}
2981
2982void AppleMachO::AddClangCXXStdlibIncludeArgs(
2983 const llvm::opt::ArgList &DriverArgs,
2984 llvm::opt::ArgStringList &CC1Args) const {
2985 // The implementation from a base class will pass through the -stdlib to
2986 // CC1Args.
2987 // FIXME: this should not be necessary, remove usages in the frontend
2988 // (e.g. HeaderSearchOptions::UseLibcxx) and don't pipe -stdlib.
2989 // Also check whether this is used for setting library search paths.
2990 ToolChain::AddClangCXXStdlibIncludeArgs(DriverArgs, CC1Args);
2991
2992 if (DriverArgs.hasArg(Ids: options::OPT_nostdinc, Ids: options::OPT_nostdlibinc,
2993 Ids: options::OPT_nostdincxx))
2994 return;
2995
2996 llvm::SmallString<128> Sysroot = GetEffectiveSysroot(DriverArgs);
2997
2998 switch (GetCXXStdlibType(Args: DriverArgs)) {
2999 case ToolChain::CST_Libcxx: {
3000 // On Darwin, libc++ can be installed in one of the following places:
3001 // 1. Alongside the compiler in <clang-executable-folder>/../include/c++/v1
3002 // 2. In a SDK (or a custom sysroot) in <sysroot>/usr/include/c++/v1
3003 //
3004 // The precedence of paths is as listed above, i.e. we take the first path
3005 // that exists. Note that we never include libc++ twice -- we take the first
3006 // path that exists and don't send the other paths to CC1 (otherwise
3007 // include_next could break).
3008
3009 // Check for (1)
3010 // Get from '<install>/bin' to '<install>/include/c++/v1'.
3011 // Note that InstallBin can be relative, so we use '..' instead of
3012 // parent_path.
3013 llvm::SmallString<128> InstallBin(getDriver().Dir); // <install>/bin
3014 llvm::sys::path::append(path&: InstallBin, a: "..", b: "include", c: "c++", d: "v1");
3015 if (getVFS().exists(Path: InstallBin)) {
3016 addSystemInclude(DriverArgs, CC1Args, Path: InstallBin);
3017 return;
3018 } else if (DriverArgs.hasArg(Ids: options::OPT_v)) {
3019 llvm::errs() << "ignoring nonexistent directory \"" << InstallBin
3020 << "\"\n";
3021 }
3022
3023 // Otherwise, check for (2)
3024 llvm::SmallString<128> SysrootUsr = Sysroot;
3025 llvm::sys::path::append(path&: SysrootUsr, a: "usr", b: "include", c: "c++", d: "v1");
3026 if (getVFS().exists(Path: SysrootUsr)) {
3027 addSystemInclude(DriverArgs, CC1Args, Path: SysrootUsr);
3028 return;
3029 } else if (DriverArgs.hasArg(Ids: options::OPT_v)) {
3030 llvm::errs() << "ignoring nonexistent directory \"" << SysrootUsr
3031 << "\"\n";
3032 }
3033
3034 // Otherwise, don't add any path.
3035 break;
3036 }
3037
3038 case ToolChain::CST_Libstdcxx:
3039 AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args);
3040 break;
3041 }
3042}
3043
3044void AppleMachO::AddGnuCPlusPlusIncludePaths(
3045 const llvm::opt::ArgList &DriverArgs,
3046 llvm::opt::ArgStringList &CC1Args) const {}
3047
3048void DarwinClang::AddGnuCPlusPlusIncludePaths(
3049 const llvm::opt::ArgList &DriverArgs,
3050 llvm::opt::ArgStringList &CC1Args) const {
3051 llvm::SmallString<128> UsrIncludeCxx = GetEffectiveSysroot(DriverArgs);
3052 llvm::sys::path::append(path&: UsrIncludeCxx, a: "usr", b: "include", c: "c++");
3053
3054 llvm::Triple::ArchType arch = getTriple().getArch();
3055 bool IsBaseFound = true;
3056 switch (arch) {
3057 default:
3058 break;
3059
3060 case llvm::Triple::x86:
3061 case llvm::Triple::x86_64:
3062 IsBaseFound = AddGnuCPlusPlusIncludePaths(
3063 DriverArgs, CC1Args, Base: UsrIncludeCxx, Version: "4.2.1", ArchDir: "i686-apple-darwin10",
3064 BitDir: arch == llvm::Triple::x86_64 ? "x86_64" : "");
3065 IsBaseFound |= AddGnuCPlusPlusIncludePaths(
3066 DriverArgs, CC1Args, Base: UsrIncludeCxx, Version: "4.0.0", ArchDir: "i686-apple-darwin8", BitDir: "");
3067 break;
3068
3069 case llvm::Triple::arm:
3070 case llvm::Triple::thumb:
3071 IsBaseFound =
3072 AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, Base: UsrIncludeCxx, Version: "4.2.1",
3073 ArchDir: "arm-apple-darwin10", BitDir: "v7");
3074 IsBaseFound |=
3075 AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, Base: UsrIncludeCxx, Version: "4.2.1",
3076 ArchDir: "arm-apple-darwin10", BitDir: "v6");
3077 break;
3078
3079 case llvm::Triple::aarch64:
3080 IsBaseFound =
3081 AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, Base: UsrIncludeCxx, Version: "4.2.1",
3082 ArchDir: "arm64-apple-darwin10", BitDir: "");
3083 break;
3084 }
3085
3086 if (!IsBaseFound) {
3087 getDriver().Diag(DiagID: diag::warn_drv_libstdcxx_not_found);
3088 }
3089}
3090
3091void AppleMachO::AddCXXStdlibLibArgs(const ArgList &Args,
3092 ArgStringList &CmdArgs) const {
3093 CXXStdlibType Type = GetCXXStdlibType(Args);
3094
3095 switch (Type) {
3096 case ToolChain::CST_Libcxx:
3097 CmdArgs.push_back(Elt: "-lc++");
3098 if (Args.hasArg(Ids: options::OPT_fexperimental_library))
3099 CmdArgs.push_back(Elt: "-lc++experimental");
3100 break;
3101
3102 case ToolChain::CST_Libstdcxx:
3103 // Unfortunately, -lstdc++ doesn't always exist in the standard search path;
3104 // it was previously found in the gcc lib dir. However, for all the Darwin
3105 // platforms we care about it was -lstdc++.6, so we search for that
3106 // explicitly if we can't see an obvious -lstdc++ candidate.
3107
3108 // Check in the sysroot first.
3109 if (const Arg *A = Args.getLastArg(Ids: options::OPT_isysroot)) {
3110 SmallString<128> P(A->getValue());
3111 llvm::sys::path::append(path&: P, a: "usr", b: "lib", c: "libstdc++.dylib");
3112
3113 if (!getVFS().exists(Path: P)) {
3114 llvm::sys::path::remove_filename(path&: P);
3115 llvm::sys::path::append(path&: P, a: "libstdc++.6.dylib");
3116 if (getVFS().exists(Path: P)) {
3117 CmdArgs.push_back(Elt: Args.MakeArgString(Str: P));
3118 return;
3119 }
3120 }
3121 }
3122
3123 // Otherwise, look in the root.
3124 // FIXME: This should be removed someday when we don't have to care about
3125 // 10.6 and earlier, where /usr/lib/libstdc++.dylib does not exist.
3126 if (!getVFS().exists(Path: "/usr/lib/libstdc++.dylib") &&
3127 getVFS().exists(Path: "/usr/lib/libstdc++.6.dylib")) {
3128 CmdArgs.push_back(Elt: "/usr/lib/libstdc++.6.dylib");
3129 return;
3130 }
3131
3132 // Otherwise, let the linker search.
3133 CmdArgs.push_back(Elt: "-lstdc++");
3134 break;
3135 }
3136}
3137
3138void DarwinClang::AddCCKextLibArgs(const ArgList &Args,
3139 ArgStringList &CmdArgs) const {
3140 // For Darwin platforms, use the compiler-rt-based support library
3141 // instead of the gcc-provided one (which is also incidentally
3142 // only present in the gcc lib dir, which makes it hard to find).
3143
3144 SmallString<128> P(getDriver().ResourceDir);
3145 llvm::sys::path::append(path&: P, a: "lib", b: "darwin");
3146
3147 // Use the newer cc_kext for iOS ARM after 6.0.
3148 if (isTargetWatchOS()) {
3149 llvm::sys::path::append(path&: P, a: "libclang_rt.cc_kext_watchos.a");
3150 } else if (isTargetTvOS()) {
3151 llvm::sys::path::append(path&: P, a: "libclang_rt.cc_kext_tvos.a");
3152 } else if (isTargetIPhoneOS()) {
3153 llvm::sys::path::append(path&: P, a: "libclang_rt.cc_kext_ios.a");
3154 } else if (isTargetDriverKit()) {
3155 // DriverKit doesn't want extra runtime support.
3156 } else if (isTargetXROSDevice()) {
3157 llvm::sys::path::append(
3158 path&: P, a: llvm::Twine("libclang_rt.cc_kext_") +
3159 llvm::Triple::getOSTypeName(Kind: llvm::Triple::XROS) + ".a");
3160 } else {
3161 llvm::sys::path::append(path&: P, a: "libclang_rt.cc_kext.a");
3162 }
3163
3164 // For now, allow missing resource libraries to support developers who may
3165 // not have compiler-rt checked out or integrated into their build.
3166 if (getVFS().exists(Path: P))
3167 CmdArgs.push_back(Elt: Args.MakeArgString(Str: P));
3168}
3169
3170DerivedArgList *MachO::TranslateArgs(const DerivedArgList &Args, BoundArch BA,
3171 Action::OffloadKind) const {
3172 DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
3173 const OptTable &Opts = getDriver().getOpts();
3174
3175 // FIXME: We really want to get out of the tool chain level argument
3176 // translation business, as it makes the driver functionality much
3177 // more opaque. For now, we follow gcc closely solely for the
3178 // purpose of easily achieving feature parity & testability. Once we
3179 // have something that works, we should reevaluate each translation
3180 // and try to push it down into tool specific logic.
3181
3182 for (Arg *A : Args) {
3183 // Sob. These is strictly gcc compatible for the time being. Apple
3184 // gcc translates options twice, which means that self-expanding
3185 // options add duplicates.
3186 switch ((options::ID)A->getOption().getID()) {
3187 default:
3188 DAL->append(A);
3189 break;
3190
3191 case options::OPT_mkernel:
3192 case options::OPT_fapple_kext:
3193 DAL->append(A);
3194 DAL->AddFlagArg(BaseArg: A, Opt: Opts.getOption(Opt: options::OPT_static));
3195 break;
3196
3197 case options::OPT_dependency_file:
3198 DAL->AddSeparateArg(BaseArg: A, Opt: Opts.getOption(Opt: options::OPT_MF), Value: A->getValue());
3199 break;
3200
3201 case options::OPT_gfull:
3202 DAL->AddFlagArg(BaseArg: A, Opt: Opts.getOption(Opt: options::OPT_g_Flag));
3203 DAL->AddFlagArg(
3204 BaseArg: A, Opt: Opts.getOption(Opt: options::OPT_fno_eliminate_unused_debug_symbols));
3205 break;
3206
3207 case options::OPT_gused:
3208 DAL->AddFlagArg(BaseArg: A, Opt: Opts.getOption(Opt: options::OPT_g_Flag));
3209 DAL->AddFlagArg(
3210 BaseArg: A, Opt: Opts.getOption(Opt: options::OPT_feliminate_unused_debug_symbols));
3211 break;
3212
3213 case options::OPT_shared:
3214 DAL->AddFlagArg(BaseArg: A, Opt: Opts.getOption(Opt: options::OPT_dynamiclib));
3215 break;
3216
3217 case options::OPT_fconstant_cfstrings:
3218 DAL->AddFlagArg(BaseArg: A, Opt: Opts.getOption(Opt: options::OPT_mconstant_cfstrings));
3219 break;
3220
3221 case options::OPT_fno_constant_cfstrings:
3222 DAL->AddFlagArg(BaseArg: A, Opt: Opts.getOption(Opt: options::OPT_mno_constant_cfstrings));
3223 break;
3224
3225 case options::OPT_Wnonportable_cfstrings:
3226 DAL->AddFlagArg(BaseArg: A,
3227 Opt: Opts.getOption(Opt: options::OPT_mwarn_nonportable_cfstrings));
3228 break;
3229
3230 case options::OPT_Wno_nonportable_cfstrings:
3231 DAL->AddFlagArg(
3232 BaseArg: A, Opt: Opts.getOption(Opt: options::OPT_mno_warn_nonportable_cfstrings));
3233 break;
3234 }
3235 }
3236
3237 // Add the arch options based on the particular spelling of -arch, to match
3238 // how the driver works.
3239 if (BA) {
3240 StringRef Name = BA.ArchName;
3241 const Option MCpu = Opts.getOption(Opt: options::OPT_mcpu_EQ);
3242 const Option MArch = Opts.getOption(Opt: options::OPT_march_EQ);
3243
3244 // This code must be kept in sync with LLVM's getArchTypeForDarwinArch,
3245 // which defines the list of which architectures we accept.
3246 if (Name == "ppc")
3247 ;
3248 else if (Name == "ppc601")
3249 DAL->AddJoinedArg(BaseArg: nullptr, Opt: MCpu, Value: "601");
3250 else if (Name == "ppc603")
3251 DAL->AddJoinedArg(BaseArg: nullptr, Opt: MCpu, Value: "603");
3252 else if (Name == "ppc604")
3253 DAL->AddJoinedArg(BaseArg: nullptr, Opt: MCpu, Value: "604");
3254 else if (Name == "ppc604e")
3255 DAL->AddJoinedArg(BaseArg: nullptr, Opt: MCpu, Value: "604e");
3256 else if (Name == "ppc750")
3257 DAL->AddJoinedArg(BaseArg: nullptr, Opt: MCpu, Value: "750");
3258 else if (Name == "ppc7400")
3259 DAL->AddJoinedArg(BaseArg: nullptr, Opt: MCpu, Value: "7400");
3260 else if (Name == "ppc7450")
3261 DAL->AddJoinedArg(BaseArg: nullptr, Opt: MCpu, Value: "7450");
3262 else if (Name == "ppc970")
3263 DAL->AddJoinedArg(BaseArg: nullptr, Opt: MCpu, Value: "970");
3264
3265 else if (Name == "ppc64" || Name == "ppc64le")
3266 DAL->AddFlagArg(BaseArg: nullptr, Opt: Opts.getOption(Opt: options::OPT_m64));
3267
3268 else if (Name == "i386")
3269 ;
3270 else if (Name == "i486")
3271 DAL->AddJoinedArg(BaseArg: nullptr, Opt: MArch, Value: "i486");
3272 else if (Name == "i586")
3273 DAL->AddJoinedArg(BaseArg: nullptr, Opt: MArch, Value: "i586");
3274 else if (Name == "i686")
3275 DAL->AddJoinedArg(BaseArg: nullptr, Opt: MArch, Value: "i686");
3276 else if (Name == "pentium")
3277 DAL->AddJoinedArg(BaseArg: nullptr, Opt: MArch, Value: "pentium");
3278 else if (Name == "pentium2")
3279 DAL->AddJoinedArg(BaseArg: nullptr, Opt: MArch, Value: "pentium2");
3280 else if (Name == "pentpro")
3281 DAL->AddJoinedArg(BaseArg: nullptr, Opt: MArch, Value: "pentiumpro");
3282 else if (Name == "pentIIm3")
3283 DAL->AddJoinedArg(BaseArg: nullptr, Opt: MArch, Value: "pentium2");
3284
3285 else if (Name == "x86_64" || Name == "x86_64h")
3286 DAL->AddFlagArg(BaseArg: nullptr, Opt: Opts.getOption(Opt: options::OPT_m64));
3287
3288 else if (Name == "arm")
3289 DAL->AddJoinedArg(BaseArg: nullptr, Opt: MArch, Value: "armv4t");
3290 else if (Name == "armv4t")
3291 DAL->AddJoinedArg(BaseArg: nullptr, Opt: MArch, Value: "armv4t");
3292 else if (Name == "armv5")
3293 DAL->AddJoinedArg(BaseArg: nullptr, Opt: MArch, Value: "armv5tej");
3294 else if (Name == "xscale")
3295 DAL->AddJoinedArg(BaseArg: nullptr, Opt: MArch, Value: "xscale");
3296 else if (Name == "armv6")
3297 DAL->AddJoinedArg(BaseArg: nullptr, Opt: MArch, Value: "armv6k");
3298 else if (Name == "armv6m")
3299 DAL->AddJoinedArg(BaseArg: nullptr, Opt: MArch, Value: "armv6m");
3300 else if (Name == "armv7")
3301 DAL->AddJoinedArg(BaseArg: nullptr, Opt: MArch, Value: "armv7a");
3302 else if (Name == "armv7em")
3303 DAL->AddJoinedArg(BaseArg: nullptr, Opt: MArch, Value: "armv7em");
3304 else if (Name == "armv7k")
3305 DAL->AddJoinedArg(BaseArg: nullptr, Opt: MArch, Value: "armv7k");
3306 else if (Name == "armv7m")
3307 DAL->AddJoinedArg(BaseArg: nullptr, Opt: MArch, Value: "armv7m");
3308 else if (Name == "armv7s")
3309 DAL->AddJoinedArg(BaseArg: nullptr, Opt: MArch, Value: "armv7s");
3310 else if (Name == "armv8-m.base" || Name == "armv8m.base")
3311 DAL->AddJoinedArg(BaseArg: nullptr, Opt: MArch, Value: "armv8m.base");
3312 else if (Name == "armv8-m.main" || Name == "armv8m.main")
3313 DAL->AddJoinedArg(BaseArg: nullptr, Opt: MArch, Value: "armv8m.main");
3314 else if (Name == "armv8.1-m.main" || Name == "armv8.1m.main")
3315 DAL->AddJoinedArg(BaseArg: nullptr, Opt: MArch, Value: "armv8.1m.main");
3316 }
3317
3318 return DAL;
3319}
3320
3321void MachO::AddLinkRuntimeLibArgs(const ArgList &Args,
3322 ArgStringList &CmdArgs,
3323 bool ForceLinkBuiltinRT) const {
3324 // Embedded targets are simple at the moment, not supporting sanitizers and
3325 // with different libraries for each member of the product { static, PIC } x
3326 // { hard-float, soft-float }
3327 llvm::SmallString<32> CompilerRT = StringRef("");
3328 CompilerRT +=
3329 (tools::arm::getARMFloatABI(TC: *this, Args) == tools::arm::FloatABI::Hard)
3330 ? "hard"
3331 : "soft";
3332 CompilerRT += Args.hasArg(Ids: options::OPT_fPIC) ? "_pic" : "_static";
3333
3334 AddLinkRuntimeLib(Args, CmdArgs, Component: CompilerRT, Opts: RLO_IsEmbedded);
3335}
3336
3337bool Darwin::isAlignedAllocationUnavailable() const {
3338 llvm::Triple::OSType OS;
3339
3340 if (isTargetMacCatalyst())
3341 return TargetVersion < alignedAllocMinVersion(OS: llvm::Triple::MacOSX);
3342 switch (TargetPlatform) {
3343 case MacOS: // Earlier than 10.13.
3344 OS = llvm::Triple::MacOSX;
3345 break;
3346 case IPhoneOS:
3347 OS = llvm::Triple::IOS;
3348 break;
3349 case TvOS: // Earlier than 11.0.
3350 OS = llvm::Triple::TvOS;
3351 break;
3352 case WatchOS: // Earlier than 4.0.
3353 OS = llvm::Triple::WatchOS;
3354 break;
3355 default: // Always available on newer platforms.
3356 return false;
3357 }
3358
3359 return TargetVersion < alignedAllocMinVersion(OS);
3360}
3361
3362static bool
3363sdkSupportsBuiltinModules(const std::optional<DarwinSDKInfo> &SDKInfo) {
3364 if (!SDKInfo)
3365 // If there is no SDK info, assume this is building against an SDK that
3366 // predates SDKSettings.json. None of those support builtin modules.
3367 return false;
3368
3369 switch (SDKInfo->getEnvironment()) {
3370 case llvm::Triple::UnknownEnvironment:
3371 case llvm::Triple::Simulator:
3372 case llvm::Triple::MacABI:
3373 // Standard xnu/Mach/Darwin based environments depend on the SDK version.
3374 break;
3375
3376 default:
3377 // All other environments support builtin modules from the start.
3378 return true;
3379 }
3380
3381 VersionTuple SDKVersion = SDKInfo->getVersion();
3382 switch (SDKInfo->getOS()) {
3383 // Existing SDKs added support for builtin modules in the fall
3384 // 2024 major releases.
3385 case llvm::Triple::MacOSX:
3386 return SDKVersion >= VersionTuple(15U);
3387 case llvm::Triple::IOS:
3388 return SDKVersion >= VersionTuple(18U);
3389 case llvm::Triple::TvOS:
3390 return SDKVersion >= VersionTuple(18U);
3391 case llvm::Triple::WatchOS:
3392 return SDKVersion >= VersionTuple(11U);
3393 case llvm::Triple::XROS:
3394 return SDKVersion >= VersionTuple(2U);
3395
3396 // New SDKs support builtin modules from the start.
3397 default:
3398 return true;
3399 }
3400}
3401
3402static inline llvm::VersionTuple
3403sizedDeallocMinVersion(llvm::Triple::OSType OS) {
3404 switch (OS) {
3405 default:
3406 break;
3407 case llvm::Triple::Darwin:
3408 case llvm::Triple::MacOSX: // Earliest supporting version is 10.12.
3409 return llvm::VersionTuple(10U, 12U);
3410 case llvm::Triple::IOS:
3411 case llvm::Triple::TvOS: // Earliest supporting version is 10.0.0.
3412 return llvm::VersionTuple(10U);
3413 case llvm::Triple::WatchOS: // Earliest supporting version is 3.0.0.
3414 return llvm::VersionTuple(3U);
3415 }
3416
3417 llvm_unreachable("Unexpected OS");
3418}
3419
3420bool Darwin::isSizedDeallocationUnavailable() const {
3421 llvm::Triple::OSType OS;
3422
3423 if (isTargetMacCatalyst())
3424 return TargetVersion < sizedDeallocMinVersion(OS: llvm::Triple::MacOSX);
3425 switch (TargetPlatform) {
3426 case MacOS: // Earlier than 10.12.
3427 OS = llvm::Triple::MacOSX;
3428 break;
3429 case IPhoneOS:
3430 OS = llvm::Triple::IOS;
3431 break;
3432 case TvOS: // Earlier than 10.0.
3433 OS = llvm::Triple::TvOS;
3434 break;
3435 case WatchOS: // Earlier than 3.0.
3436 OS = llvm::Triple::WatchOS;
3437 break;
3438 default:
3439 // Always available on newer platforms.
3440 return false;
3441 }
3442
3443 return TargetVersion < sizedDeallocMinVersion(OS);
3444}
3445
3446void MachO::addClangTargetOptions(const llvm::opt::ArgList &DriverArgs,
3447 llvm::opt::ArgStringList &CC1Args,
3448 BoundArch BA,
3449 Action::OffloadKind DeviceOffloadKind) const {
3450
3451 ToolChain::addClangTargetOptions(DriverArgs, CC1Args, BA, DeviceOffloadKind);
3452
3453 // On arm64e, we enable all the features required for the Darwin userspace
3454 // ABI
3455 if (getTriple().isArm64e()) {
3456 // Core platform ABI
3457 if (!DriverArgs.hasArg(Ids: options::OPT_fptrauth_calls,
3458 Ids: options::OPT_fno_ptrauth_calls))
3459 CC1Args.push_back(Elt: "-fptrauth-calls");
3460 if (!DriverArgs.hasArg(Ids: options::OPT_fptrauth_returns,
3461 Ids: options::OPT_fno_ptrauth_returns))
3462 CC1Args.push_back(Elt: "-fptrauth-returns");
3463 if (!DriverArgs.hasArg(Ids: options::OPT_fptrauth_intrinsics,
3464 Ids: options::OPT_fno_ptrauth_intrinsics))
3465 CC1Args.push_back(Elt: "-fptrauth-intrinsics");
3466 if (!DriverArgs.hasArg(Ids: options::OPT_fptrauth_indirect_gotos,
3467 Ids: options::OPT_fno_ptrauth_indirect_gotos))
3468 CC1Args.push_back(Elt: "-fptrauth-indirect-gotos");
3469 if (!DriverArgs.hasArg(Ids: options::OPT_fptrauth_auth_traps,
3470 Ids: options::OPT_fno_ptrauth_auth_traps))
3471 CC1Args.push_back(Elt: "-fptrauth-auth-traps");
3472
3473 // C++ v-table ABI
3474 if (!DriverArgs.hasArg(
3475 Ids: options::OPT_fptrauth_vtable_pointer_address_discrimination,
3476 Ids: options::OPT_fno_ptrauth_vtable_pointer_address_discrimination))
3477 CC1Args.push_back(Elt: "-fptrauth-vtable-pointer-address-discrimination");
3478 if (!DriverArgs.hasArg(
3479 Ids: options::OPT_fptrauth_vtable_pointer_type_discrimination,
3480 Ids: options::OPT_fno_ptrauth_vtable_pointer_type_discrimination))
3481 CC1Args.push_back(Elt: "-fptrauth-vtable-pointer-type-discrimination");
3482
3483 // Objective-C ABI
3484 if (!DriverArgs.hasArg(Ids: options::OPT_fptrauth_objc_isa,
3485 Ids: options::OPT_fno_ptrauth_objc_isa))
3486 CC1Args.push_back(Elt: "-fptrauth-objc-isa");
3487 if (!DriverArgs.hasArg(Ids: options::OPT_fptrauth_objc_class_ro,
3488 Ids: options::OPT_fno_ptrauth_objc_class_ro))
3489 CC1Args.push_back(Elt: "-fptrauth-objc-class-ro");
3490 if (!DriverArgs.hasArg(Ids: options::OPT_fptrauth_objc_interface_sel,
3491 Ids: options::OPT_fno_ptrauth_objc_interface_sel))
3492 CC1Args.push_back(Elt: "-fptrauth-objc-interface-sel");
3493 }
3494}
3495
3496void Darwin::addClangTargetOptions(
3497 const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args,
3498 BoundArch BA, Action::OffloadKind DeviceOffloadKind) const {
3499
3500 MachO::addClangTargetOptions(DriverArgs, CC1Args, BA, DeviceOffloadKind);
3501
3502 // When compiling device code (e.g. SPIR-V for HIP), skip host-specific
3503 // flags like -faligned-alloc-unavailable and -fno-sized-deallocation
3504 // that depend on the host OS version and are irrelevant to device code.
3505 if (DeviceOffloadKind != Action::OFK_None)
3506 return;
3507
3508 // Pass "-faligned-alloc-unavailable" only when the user hasn't manually
3509 // enabled or disabled aligned allocations.
3510 if (!DriverArgs.hasArgNoClaim(Ids: options::OPT_faligned_allocation,
3511 Ids: options::OPT_fno_aligned_allocation) &&
3512 isAlignedAllocationUnavailable())
3513 CC1Args.push_back(Elt: "-faligned-alloc-unavailable");
3514
3515 // Enable objc_msgSend selector stubs by default if the linker supports it.
3516 // ld64-811.2+ does, for arm64, arm64e, and arm64_32.
3517 if (!DriverArgs.hasArgNoClaim(Ids: options::OPT_fobjc_msgsend_selector_stubs,
3518 Ids: options::OPT_fno_objc_msgsend_selector_stubs) &&
3519 getTriple().isAArch64() &&
3520 (getLinkerVersion(Args: DriverArgs) >= VersionTuple(811, 2)))
3521 CC1Args.push_back(Elt: "-fobjc-msgsend-selector-stubs");
3522
3523 // Enable objc_msgSend class selector stubs by default if the linker supports
3524 // it. ld64-1250+ does, for arm64, arm64e, and arm64_32.
3525 if (!DriverArgs.hasArgNoClaim(
3526 Ids: options::OPT_fobjc_msgsend_class_selector_stubs,
3527 Ids: options::OPT_fno_objc_msgsend_class_selector_stubs) &&
3528 getTriple().isAArch64() &&
3529 (getLinkerVersion(Args: DriverArgs) >= VersionTuple(1250, 0)))
3530 CC1Args.push_back(Elt: "-fobjc-msgsend-class-selector-stubs");
3531
3532 // Pass "-fno-sized-deallocation" only when the user hasn't manually enabled
3533 // or disabled sized deallocations.
3534 if (!DriverArgs.hasArgNoClaim(Ids: options::OPT_fsized_deallocation,
3535 Ids: options::OPT_fno_sized_deallocation) &&
3536 isSizedDeallocationUnavailable())
3537 CC1Args.push_back(Elt: "-fno-sized-deallocation");
3538
3539 addClangCC1ASTargetOptions(Args: DriverArgs, CC1ASArgs&: CC1Args);
3540
3541 if (SDKInfo) {
3542 // Make the SDKSettings.json an explicit dependency for the compiler
3543 // invocation, in case the compiler needs to read it to remap versions.
3544 if (!SDKInfo->getFilePath().empty()) {
3545 SmallString<64> ExtraDepOpt("-fdepfile-entry=");
3546 ExtraDepOpt += SDKInfo->getFilePath();
3547 CC1Args.push_back(Elt: DriverArgs.MakeArgString(Str: ExtraDepOpt));
3548 }
3549 }
3550
3551 // Enable compatibility mode for NSItemProviderCompletionHandler in
3552 // Foundation/NSItemProvider.h.
3553 CC1Args.push_back(Elt: "-fcompatibility-qualified-id-block-type-checking");
3554
3555 // Give static local variables in inline functions hidden visibility when
3556 // -fvisibility-inlines-hidden is enabled.
3557 if (!DriverArgs.getLastArgNoClaim(
3558 Ids: options::OPT_fvisibility_inlines_hidden_static_local_var,
3559 Ids: options::OPT_fno_visibility_inlines_hidden_static_local_var))
3560 CC1Args.push_back(Elt: "-fvisibility-inlines-hidden-static-local-var");
3561
3562 // Earlier versions of the darwin SDK have the C standard library headers
3563 // all together in the Darwin module. That leads to module cycles with
3564 // the _Builtin_ modules. e.g. <inttypes.h> on darwin includes <stdint.h>.
3565 // The builtin <stdint.h> include-nexts <stdint.h>. When both of those
3566 // darwin headers are in the Darwin module, there's a module cycle Darwin ->
3567 // _Builtin_stdint -> Darwin (i.e. inttypes.h (darwin) -> stdint.h (builtin) ->
3568 // stdint.h (darwin)). This is fixed in later versions of the darwin SDK,
3569 // but until then, the builtin headers need to join the system modules.
3570 // i.e. when the builtin stdint.h is in the Darwin module too, the cycle
3571 // goes away. Note that -fbuiltin-headers-in-system-modules does nothing
3572 // to fix the same problem with C++ headers, and is generally fragile.
3573 if (!sdkSupportsBuiltinModules(SDKInfo))
3574 CC1Args.push_back(Elt: "-fbuiltin-headers-in-system-modules");
3575
3576 if (!DriverArgs.hasArgNoClaim(Ids: options::OPT_fdefine_target_os_macros,
3577 Ids: options::OPT_fno_define_target_os_macros))
3578 CC1Args.push_back(Elt: "-fdefine-target-os-macros");
3579
3580 // Disable subdirectory modulemap search on sufficiently recent SDKs.
3581 if (SDKInfo &&
3582 !DriverArgs.hasFlag(Pos: options::OPT_fmodulemap_allow_subdirectory_search,
3583 Neg: options::OPT_fno_modulemap_allow_subdirectory_search,
3584 Default: false)) {
3585 bool RequiresSubdirectorySearch;
3586 VersionTuple SDKVersion = SDKInfo->getVersion();
3587 switch (TargetPlatform) {
3588 default:
3589 RequiresSubdirectorySearch = true;
3590 break;
3591 case MacOS:
3592 RequiresSubdirectorySearch = SDKVersion < VersionTuple(15, 0);
3593 break;
3594 case IPhoneOS:
3595 case TvOS:
3596 RequiresSubdirectorySearch = SDKVersion < VersionTuple(18, 0);
3597 break;
3598 case WatchOS:
3599 RequiresSubdirectorySearch = SDKVersion < VersionTuple(11, 0);
3600 break;
3601 case XROS:
3602 RequiresSubdirectorySearch = SDKVersion < VersionTuple(2, 0);
3603 break;
3604 }
3605 if (!RequiresSubdirectorySearch)
3606 CC1Args.push_back(Elt: "-fno-modulemap-allow-subdirectory-search");
3607 }
3608}
3609
3610void Darwin::addClangCC1ASTargetOptions(
3611 const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CC1ASArgs) const {
3612 if (TargetVariantTriple) {
3613 CC1ASArgs.push_back(Elt: "-darwin-target-variant-triple");
3614 CC1ASArgs.push_back(Elt: Args.MakeArgString(Str: TargetVariantTriple->getTriple()));
3615 }
3616
3617 if (SDKInfo) {
3618 /// Pass the SDK version to the compiler when the SDK information is
3619 /// available.
3620 auto EmitTargetSDKVersionArg = [&](const VersionTuple &V) {
3621 std::string Arg;
3622 llvm::raw_string_ostream OS(Arg);
3623 OS << "-target-sdk-version=" << V;
3624 CC1ASArgs.push_back(Elt: Args.MakeArgString(Str: Arg));
3625 };
3626
3627 if (isTargetMacCatalyst()) {
3628 if (const auto *MacOStoMacCatalystMapping = SDKInfo->getVersionMapping(
3629 Kind: DarwinSDKInfo::OSEnvPair::macOStoMacCatalystPair())) {
3630 std::optional<VersionTuple> SDKVersion = MacOStoMacCatalystMapping->map(
3631 Key: SDKInfo->getVersion(), MinimumValue: minimumMacCatalystDeploymentTarget(),
3632 MaximumValue: std::nullopt);
3633 EmitTargetSDKVersionArg(
3634 SDKVersion ? *SDKVersion : minimumMacCatalystDeploymentTarget());
3635 }
3636 } else {
3637 EmitTargetSDKVersionArg(SDKInfo->getVersion());
3638 }
3639
3640 /// Pass the target variant SDK version to the compiler when the SDK
3641 /// information is available and is required for target variant.
3642 if (TargetVariantTriple) {
3643 if (isTargetMacCatalyst()) {
3644 std::string Arg;
3645 llvm::raw_string_ostream OS(Arg);
3646 OS << "-darwin-target-variant-sdk-version=" << SDKInfo->getVersion();
3647 CC1ASArgs.push_back(Elt: Args.MakeArgString(Str: Arg));
3648 } else if (const auto *MacOStoMacCatalystMapping =
3649 SDKInfo->getVersionMapping(
3650 Kind: DarwinSDKInfo::OSEnvPair::macOStoMacCatalystPair())) {
3651 if (std::optional<VersionTuple> SDKVersion =
3652 MacOStoMacCatalystMapping->map(
3653 Key: SDKInfo->getVersion(), MinimumValue: minimumMacCatalystDeploymentTarget(),
3654 MaximumValue: std::nullopt)) {
3655 std::string Arg;
3656 llvm::raw_string_ostream OS(Arg);
3657 OS << "-darwin-target-variant-sdk-version=" << *SDKVersion;
3658 CC1ASArgs.push_back(Elt: Args.MakeArgString(Str: Arg));
3659 }
3660 }
3661 }
3662 }
3663}
3664
3665DerivedArgList *
3666Darwin::TranslateArgs(const DerivedArgList &Args, BoundArch BA,
3667 Action::OffloadKind DeviceOffloadKind) const {
3668 // First get the generic Apple args, before moving onto Darwin-specific ones.
3669 DerivedArgList *DAL = MachO::TranslateArgs(Args, BA, DeviceOffloadKind);
3670
3671 // If no architecture is bound, none of the translations here are relevant.
3672 if (!BA)
3673 return DAL;
3674
3675 // Add an explicit version min argument for the deployment target. We do this
3676 // after argument translation because -Xarch_ arguments may add a version min
3677 // argument.
3678 AddDeploymentTarget(Args&: *DAL);
3679
3680 // For iOS 6, undo the translation to add -static for -mkernel/-fapple-kext.
3681 // FIXME: It would be far better to avoid inserting those -static arguments,
3682 // but we can't check the deployment target in the translation code until
3683 // it is set here.
3684 if (isTargetWatchOSBased() || isTargetDriverKit() || isTargetXROS() ||
3685 (isTargetIOSBased() && !isIPhoneOSVersionLT(V0: 6, V1: 0))) {
3686 for (ArgList::iterator it = DAL->begin(), ie = DAL->end(); it != ie; ) {
3687 Arg *A = *it;
3688 ++it;
3689 if (A->getOption().getID() != options::OPT_mkernel &&
3690 A->getOption().getID() != options::OPT_fapple_kext)
3691 continue;
3692 assert(it != ie && "unexpected argument translation");
3693 A = *it;
3694 assert(A->getOption().getID() == options::OPT_static &&
3695 "missing expected -static argument");
3696 *it = nullptr;
3697 ++it;
3698 }
3699 }
3700
3701 auto Arch = tools::darwin::getArchTypeForMachOArchName(Str: BA.ArchName);
3702 if ((Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb)) {
3703 if (Args.hasFlag(Pos: options::OPT_fomit_frame_pointer,
3704 Neg: options::OPT_fno_omit_frame_pointer, Default: false))
3705 getDriver().Diag(DiagID: clang::diag::warn_drv_unsupported_opt_for_target)
3706 << "-fomit-frame-pointer" << BA.ArchName;
3707 }
3708
3709 return DAL;
3710}
3711
3712ToolChain::UnwindTableLevel MachO::getDefaultUnwindTableLevel(const ArgList &Args) const {
3713 // Unwind tables are not emitted if -fno-exceptions is supplied (except when
3714 // targeting x86_64).
3715 if (getArch() == llvm::Triple::x86_64 ||
3716 (GetExceptionModel(Args) != llvm::ExceptionHandling::SjLj &&
3717 Args.hasFlag(Pos: options::OPT_fexceptions, Neg: options::OPT_fno_exceptions,
3718 Default: true)))
3719 return (getArch() == llvm::Triple::aarch64 ||
3720 getArch() == llvm::Triple::aarch64_32)
3721 ? UnwindTableLevel::Synchronous
3722 : UnwindTableLevel::Asynchronous;
3723
3724 return UnwindTableLevel::None;
3725}
3726
3727bool MachO::UseDwarfDebugFlags() const {
3728 if (const char *S = ::getenv(name: "RC_DEBUG_OPTIONS"))
3729 return S[0] != '\0';
3730 return false;
3731}
3732
3733std::string MachO::GetGlobalDebugPathRemapping() const {
3734 if (const char *S = ::getenv(name: "RC_DEBUG_PREFIX_MAP"))
3735 return S;
3736 return {};
3737}
3738
3739llvm::ExceptionHandling Darwin::GetExceptionModel(const ArgList &Args) const {
3740 // Darwin uses SjLj exceptions on ARM.
3741 if (getTriple().getArch() != llvm::Triple::arm &&
3742 getTriple().getArch() != llvm::Triple::thumb)
3743 return llvm::ExceptionHandling::None;
3744
3745 // Only watchOS uses the new DWARF/Compact unwinding method.
3746 llvm::Triple Triple(ComputeLLVMTriple(Args));
3747 if (Triple.isWatchABI())
3748 return llvm::ExceptionHandling::DwarfCFI;
3749
3750 return llvm::ExceptionHandling::SjLj;
3751}
3752
3753bool Darwin::SupportsEmbeddedBitcode() const {
3754 assert(TargetInitialized && "Target not initialized!");
3755 if (isTargetIPhoneOS() && isIPhoneOSVersionLT(V0: 6, V1: 0))
3756 return false;
3757 return true;
3758}
3759
3760bool MachO::isPICDefault() const { return true; }
3761
3762bool MachO::isPIEDefault(const llvm::opt::ArgList &Args) const { return false; }
3763
3764bool MachO::isPICDefaultForced() const {
3765 return (getArch() == llvm::Triple::x86_64 ||
3766 getArch() == llvm::Triple::aarch64);
3767}
3768
3769bool MachO::SupportsProfiling() const {
3770 // Profiling instrumentation is only supported on x86.
3771 return getTriple().isX86();
3772}
3773
3774void Darwin::addMinVersionArgs(const ArgList &Args,
3775 ArgStringList &CmdArgs) const {
3776 VersionTuple TargetVersion = getTripleTargetVersion();
3777
3778 assert(!isTargetXROS() && "xrOS always uses -platform-version");
3779
3780 if (isTargetWatchOS())
3781 CmdArgs.push_back(Elt: "-watchos_version_min");
3782 else if (isTargetWatchOSSimulator())
3783 CmdArgs.push_back(Elt: "-watchos_simulator_version_min");
3784 else if (isTargetTvOS())
3785 CmdArgs.push_back(Elt: "-tvos_version_min");
3786 else if (isTargetTvOSSimulator())
3787 CmdArgs.push_back(Elt: "-tvos_simulator_version_min");
3788 else if (isTargetDriverKit())
3789 CmdArgs.push_back(Elt: "-driverkit_version_min");
3790 else if (isTargetIOSSimulator())
3791 CmdArgs.push_back(Elt: "-ios_simulator_version_min");
3792 else if (isTargetIOSBased())
3793 CmdArgs.push_back(Elt: "-iphoneos_version_min");
3794 else if (isTargetMacCatalyst())
3795 CmdArgs.push_back(Elt: "-maccatalyst_version_min");
3796 else {
3797 assert(isTargetMacOS() && "unexpected target");
3798 CmdArgs.push_back(Elt: "-macosx_version_min");
3799 }
3800
3801 VersionTuple MinTgtVers = getEffectiveTriple().getMinimumSupportedOSVersion();
3802 if (!MinTgtVers.empty() && MinTgtVers > TargetVersion)
3803 TargetVersion = MinTgtVers;
3804 CmdArgs.push_back(Elt: Args.MakeArgString(Str: TargetVersion.getAsString()));
3805 if (TargetVariantTriple) {
3806 assert(isTargetMacOSBased() && "unexpected target");
3807 VersionTuple VariantTargetVersion;
3808 if (TargetVariantTriple->isMacOSX()) {
3809 CmdArgs.push_back(Elt: "-macosx_version_min");
3810 TargetVariantTriple->getMacOSXVersion(Version&: VariantTargetVersion);
3811 } else {
3812 assert(TargetVariantTriple->isiOS() &&
3813 TargetVariantTriple->isMacCatalystEnvironment() &&
3814 "unexpected target variant triple");
3815 CmdArgs.push_back(Elt: "-maccatalyst_version_min");
3816 VariantTargetVersion = TargetVariantTriple->getiOSVersion();
3817 }
3818 VersionTuple MinTgtVers =
3819 TargetVariantTriple->getMinimumSupportedOSVersion();
3820 if (MinTgtVers.getMajor() && MinTgtVers > VariantTargetVersion)
3821 VariantTargetVersion = MinTgtVers;
3822 CmdArgs.push_back(Elt: Args.MakeArgString(Str: VariantTargetVersion.getAsString()));
3823 }
3824}
3825
3826static const char *getPlatformName(Darwin::DarwinPlatformKind Platform,
3827 Darwin::DarwinEnvironmentKind Environment) {
3828 switch (Platform) {
3829 case Darwin::MacOS:
3830 return "macos";
3831 case Darwin::IPhoneOS:
3832 if (Environment == Darwin::MacCatalyst)
3833 return "mac catalyst";
3834 return "ios";
3835 case Darwin::TvOS:
3836 return "tvos";
3837 case Darwin::WatchOS:
3838 return "watchos";
3839 case Darwin::XROS:
3840 return "xros";
3841 case Darwin::DriverKit:
3842 return "driverkit";
3843 default:
3844 break;
3845 }
3846 llvm_unreachable("invalid platform");
3847}
3848
3849void Darwin::addPlatformVersionArgs(const llvm::opt::ArgList &Args,
3850 llvm::opt::ArgStringList &CmdArgs) const {
3851 // Firmware doesn't use -platform_version.
3852 if (TargetPlatform == DarwinPlatformKind::Firmware)
3853 return MachO::addPlatformVersionArgs(Args, CmdArgs);
3854
3855 auto EmitPlatformVersionArg =
3856 [&](const VersionTuple &TV, Darwin::DarwinPlatformKind TargetPlatform,
3857 Darwin::DarwinEnvironmentKind TargetEnvironment,
3858 const llvm::Triple &TT) {
3859 // -platform_version <platform> <target_version> <sdk_version>
3860 // Both the target and SDK version support only up to 3 components.
3861 CmdArgs.push_back(Elt: "-platform_version");
3862 std::string PlatformName =
3863 getPlatformName(Platform: TargetPlatform, Environment: TargetEnvironment);
3864 if (TargetEnvironment == Darwin::Simulator)
3865 PlatformName += "-simulator";
3866 CmdArgs.push_back(Elt: Args.MakeArgString(Str: PlatformName));
3867 VersionTuple TargetVersion = TV.withoutBuild();
3868 if ((TargetPlatform == Darwin::IPhoneOS ||
3869 TargetPlatform == Darwin::TvOS) &&
3870 getTriple().getArchName() == "arm64e" &&
3871 TargetVersion.getMajor() < 14) {
3872 // arm64e slice is supported on iOS/tvOS 14+ only.
3873 TargetVersion = VersionTuple(14, 0);
3874 }
3875 VersionTuple MinTgtVers = TT.getMinimumSupportedOSVersion();
3876 if (!MinTgtVers.empty() && MinTgtVers > TargetVersion)
3877 TargetVersion = MinTgtVers;
3878 CmdArgs.push_back(Elt: Args.MakeArgString(Str: TargetVersion.getAsString()));
3879
3880 if (TargetPlatform == IPhoneOS && TargetEnvironment == MacCatalyst) {
3881 // Mac Catalyst programs must use the appropriate iOS SDK version
3882 // that corresponds to the macOS SDK version used for the compilation.
3883 std::optional<VersionTuple> iOSSDKVersion;
3884 if (SDKInfo) {
3885 if (const auto *MacOStoMacCatalystMapping =
3886 SDKInfo->getVersionMapping(
3887 Kind: DarwinSDKInfo::OSEnvPair::macOStoMacCatalystPair())) {
3888 iOSSDKVersion = MacOStoMacCatalystMapping->map(
3889 Key: SDKInfo->getVersion().withoutBuild(),
3890 MinimumValue: minimumMacCatalystDeploymentTarget(), MaximumValue: std::nullopt);
3891 }
3892 }
3893 CmdArgs.push_back(Elt: Args.MakeArgString(
3894 Str: (iOSSDKVersion ? *iOSSDKVersion
3895 : minimumMacCatalystDeploymentTarget())
3896 .getAsString()));
3897 return;
3898 }
3899
3900 if (SDKInfo) {
3901 VersionTuple SDKVersion = SDKInfo->getVersion().withoutBuild();
3902 if (!SDKVersion.getMinor())
3903 SDKVersion = VersionTuple(SDKVersion.getMajor(), 0);
3904 CmdArgs.push_back(Elt: Args.MakeArgString(Str: SDKVersion.getAsString()));
3905 } else {
3906 // Use an SDK version that's matching the deployment target if the SDK
3907 // version is missing. This is preferred over an empty SDK version
3908 // (0.0.0) as the system's runtime might expect the linked binary to
3909 // contain a valid SDK version in order for the binary to work
3910 // correctly. It's reasonable to use the deployment target version as
3911 // a proxy for the SDK version because older SDKs don't guarantee
3912 // support for deployment targets newer than the SDK versions, so that
3913 // rules out using some predetermined older SDK version, which leaves
3914 // the deployment target version as the only reasonable choice.
3915 CmdArgs.push_back(Elt: Args.MakeArgString(Str: TargetVersion.getAsString()));
3916 }
3917 };
3918 EmitPlatformVersionArg(getTripleTargetVersion(), TargetPlatform,
3919 TargetEnvironment, getEffectiveTriple());
3920 if (!TargetVariantTriple)
3921 return;
3922 Darwin::DarwinPlatformKind Platform;
3923 Darwin::DarwinEnvironmentKind Environment;
3924 VersionTuple TargetVariantVersion;
3925 if (TargetVariantTriple->isMacOSX()) {
3926 TargetVariantTriple->getMacOSXVersion(Version&: TargetVariantVersion);
3927 Platform = Darwin::MacOS;
3928 Environment = Darwin::NativeEnvironment;
3929 } else {
3930 assert(TargetVariantTriple->isiOS() &&
3931 TargetVariantTriple->isMacCatalystEnvironment() &&
3932 "unexpected target variant triple");
3933 TargetVariantVersion = TargetVariantTriple->getiOSVersion();
3934 Platform = Darwin::IPhoneOS;
3935 Environment = Darwin::MacCatalyst;
3936 }
3937 EmitPlatformVersionArg(TargetVariantVersion, Platform, Environment,
3938 *TargetVariantTriple);
3939}
3940
3941// Add additional link args for the -dynamiclib option.
3942static void addDynamicLibLinkArgs(const Darwin &D, const ArgList &Args,
3943 ArgStringList &CmdArgs) {
3944 // Derived from darwin_dylib1 spec.
3945 if (D.isTargetIPhoneOS()) {
3946 if (D.isIPhoneOSVersionLT(V0: 3, V1: 1))
3947 CmdArgs.push_back(Elt: "-ldylib1.o");
3948 return;
3949 }
3950
3951 if (!D.isTargetMacOS())
3952 return;
3953 if (D.isMacosxVersionLT(V0: 10, V1: 5))
3954 CmdArgs.push_back(Elt: "-ldylib1.o");
3955 else if (D.isMacosxVersionLT(V0: 10, V1: 6))
3956 CmdArgs.push_back(Elt: "-ldylib1.10.5.o");
3957}
3958
3959// Add additional link args for the -bundle option.
3960static void addBundleLinkArgs(const Darwin &D, const ArgList &Args,
3961 ArgStringList &CmdArgs) {
3962 if (Args.hasArg(Ids: options::OPT_static))
3963 return;
3964 // Derived from darwin_bundle1 spec.
3965 if ((D.isTargetIPhoneOS() && D.isIPhoneOSVersionLT(V0: 3, V1: 1)) ||
3966 (D.isTargetMacOS() && D.isMacosxVersionLT(V0: 10, V1: 6)))
3967 CmdArgs.push_back(Elt: "-lbundle1.o");
3968}
3969
3970// Add additional link args for the -pg option.
3971static void addPgProfilingLinkArgs(const Darwin &D, const ArgList &Args,
3972 ArgStringList &CmdArgs) {
3973 if (D.isTargetMacOS() && D.isMacosxVersionLT(V0: 10, V1: 9)) {
3974 if (Args.hasArg(Ids: options::OPT_static) || Args.hasArg(Ids: options::OPT_object) ||
3975 Args.hasArg(Ids: options::OPT_preload)) {
3976 CmdArgs.push_back(Elt: "-lgcrt0.o");
3977 } else {
3978 CmdArgs.push_back(Elt: "-lgcrt1.o");
3979
3980 // darwin_crt2 spec is empty.
3981 }
3982 // By default on OS X 10.8 and later, we don't link with a crt1.o
3983 // file and the linker knows to use _main as the entry point. But,
3984 // when compiling with -pg, we need to link with the gcrt1.o file,
3985 // so pass the -no_new_main option to tell the linker to use the
3986 // "start" symbol as the entry point.
3987 if (!D.isMacosxVersionLT(V0: 10, V1: 8))
3988 CmdArgs.push_back(Elt: "-no_new_main");
3989 } else {
3990 D.getDriver().Diag(DiagID: diag::err_drv_clang_unsupported_opt_pg_darwin)
3991 << D.isTargetMacOSBased();
3992 }
3993}
3994
3995static void addDefaultCRTLinkArgs(const Darwin &D, const ArgList &Args,
3996 ArgStringList &CmdArgs) {
3997 // Derived from darwin_crt1 spec.
3998 if (D.isTargetIPhoneOS()) {
3999 if (D.getArch() == llvm::Triple::aarch64)
4000 ; // iOS does not need any crt1 files for arm64
4001 else if (D.isIPhoneOSVersionLT(V0: 3, V1: 1))
4002 CmdArgs.push_back(Elt: "-lcrt1.o");
4003 else if (D.isIPhoneOSVersionLT(V0: 6, V1: 0))
4004 CmdArgs.push_back(Elt: "-lcrt1.3.1.o");
4005 return;
4006 }
4007
4008 if (!D.isTargetMacOS())
4009 return;
4010 if (D.isMacosxVersionLT(V0: 10, V1: 5))
4011 CmdArgs.push_back(Elt: "-lcrt1.o");
4012 else if (D.isMacosxVersionLT(V0: 10, V1: 6))
4013 CmdArgs.push_back(Elt: "-lcrt1.10.5.o");
4014 else if (D.isMacosxVersionLT(V0: 10, V1: 8))
4015 CmdArgs.push_back(Elt: "-lcrt1.10.6.o");
4016 // darwin_crt2 spec is empty.
4017}
4018
4019void Darwin::addStartObjectFileArgs(const ArgList &Args,
4020 ArgStringList &CmdArgs) const {
4021 // Firmware uses the "bare metal" start object file args.
4022 if (isTargetFirmware())
4023 return MachO::addStartObjectFileArgs(Args, CmdArgs);
4024
4025 // Derived from startfile spec.
4026 if (Args.hasArg(Ids: options::OPT_dynamiclib))
4027 addDynamicLibLinkArgs(D: *this, Args, CmdArgs);
4028 else if (Args.hasArg(Ids: options::OPT_bundle))
4029 addBundleLinkArgs(D: *this, Args, CmdArgs);
4030 else if (Args.hasArg(Ids: options::OPT_pg) && SupportsProfiling())
4031 addPgProfilingLinkArgs(D: *this, Args, CmdArgs);
4032 else if (Args.hasArg(Ids: options::OPT_static) ||
4033 Args.hasArg(Ids: options::OPT_object) ||
4034 Args.hasArg(Ids: options::OPT_preload))
4035 CmdArgs.push_back(Elt: "-lcrt0.o");
4036 else
4037 addDefaultCRTLinkArgs(D: *this, Args, CmdArgs);
4038
4039 if (isTargetMacOS() && Args.hasArg(Ids: options::OPT_shared_libgcc) &&
4040 isMacosxVersionLT(V0: 10, V1: 5)) {
4041 const char *Str = Args.MakeArgString(Str: GetFilePath(Name: "crt3.o"));
4042 CmdArgs.push_back(Elt: Str);
4043 }
4044}
4045
4046void Darwin::CheckObjCARC() const {
4047 ensureTargetInitialized();
4048 if (!isTargetInitialized())
4049 return;
4050 if (isTargetIOSBased() || isTargetWatchOSBased() || isTargetXROS() ||
4051 (isTargetMacOSBased() && !isMacosxVersionLT(V0: 10, V1: 6)))
4052 return;
4053 getDriver().Diag(DiagID: diag::err_arc_unsupported_on_toolchain);
4054}
4055
4056SanitizerMask
4057Darwin::getSupportedSanitizers(BoundArch BA,
4058 Action::OffloadKind DeviceOffloadKind) const {
4059 const bool IsX86_64 = getTriple().getArch() == llvm::Triple::x86_64;
4060 const bool IsAArch64 = getTriple().getArch() == llvm::Triple::aarch64;
4061 SanitizerMask Res = ToolChain::getSupportedSanitizers(BA, DeviceOffloadKind);
4062 Res |= SanitizerKind::Address;
4063 Res |= SanitizerKind::PointerCompare;
4064 Res |= SanitizerKind::PointerSubtract;
4065 Res |= SanitizerKind::Realtime;
4066 Res |= SanitizerKind::Leak;
4067 Res |= SanitizerKind::Fuzzer;
4068 Res |= SanitizerKind::FuzzerNoLink;
4069 Res |= SanitizerKind::ObjCCast;
4070
4071 ensureTargetInitialized();
4072 if (!isTargetInitialized())
4073 return Res;
4074 // Prior to 10.9, macOS shipped a version of the C++ standard library without
4075 // C++11 support. The same is true of iOS prior to version 5. These OS'es are
4076 // incompatible with -fsanitize=vptr.
4077 if (!(isTargetMacOSBased() && isMacosxVersionLT(V0: 10, V1: 9)) &&
4078 !(isTargetIPhoneOS() && isIPhoneOSVersionLT(V0: 5, V1: 0)))
4079 Res |= SanitizerKind::Vptr;
4080
4081 if ((IsX86_64 || IsAArch64) &&
4082 (isTargetMacOSBased() || isTargetIOSSimulator() ||
4083 isTargetTvOSSimulator() || isTargetWatchOSSimulator())) {
4084 Res |= SanitizerKind::Thread;
4085 }
4086
4087 if ((IsX86_64 || IsAArch64) && isTargetMacOSBased()) {
4088 Res |= SanitizerKind::Type;
4089 }
4090
4091 if (IsX86_64)
4092 Res |= SanitizerKind::NumericalStability;
4093
4094 return Res;
4095}
4096
4097void AppleMachO::printVerboseInfo(raw_ostream &OS) const {
4098 CudaInstallation->print(OS);
4099 RocmInstallation->print(OS);
4100}
4101