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