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