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