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
2488 // Support allowing the SDKROOT environment variable used by xcrun and other
2489 // Xcode tools to define the default sysroot, by making it the default for
2490 // isysroot.
2491 if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
2492 // Warn if the path does not exist.
2493 if (!getVFS().exists(A->getValue()))
2494 getDriver().Diag(clang::diag::warn_missing_sysroot) << A->getValue();
2495 } else if (const char *env = ::getenv("SDKROOT")) {
2496 // We only use this value as the default if it is an absolute path,
2497 // exists, and it is not the root path.
2498 if (llvm::sys::path::is_absolute(env) && getVFS().exists(env) &&
2499 StringRef(env) != "/") {
2500 Args.append(Args.MakeSeparateArg(
2501 nullptr, Opts.getOption(options::OPT_isysroot), env));
2502 }
2503 }
2504#ifdef CLANG_USE_XCSELECT
2505 // FIXME: This should check for `getTriple().isMacOSX()`, but this breaks
2506 // many tests. See https://github.com/llvm/llvm-project/pull/119670.
2507 else if (getTriple().getOS() == llvm::Triple::MacOSX) {
2508 char *p;
2509 if (!::xcselect_host_sdk_path(CLANG_XCSELECT_HOST_SDK_POLICY, &p)) {
2510 Args.append(Args.MakeSeparateArg(
2511 nullptr, Opts.getOption(options::OPT_isysroot), p));
2512 ::free(p);
2513 }
2514 }
2515#endif
2516
2517 // Read the SDKSettings.json file for more information, like the SDK version
2518 // that we can pass down to the compiler.
2519 SDKInfo = parseSDKSettings(getVFS(), Args, getDriver());
2520 // FIXME: If SDKInfo is std::nullopt, diagnose a bad isysroot value (e.g.
2521 // doesn't end in .sdk).
2522
2523 // The OS and the version can be specified using the -target argument.
2524 std::optional<DarwinPlatform> PlatformAndVersion =
2525 getDeploymentTargetFromTargetArg(Args, getTriple(), getDriver(), SDKInfo);
2526 if (PlatformAndVersion) {
2527 // Disallow mixing -target and -mtargetos=.
2528 if (const auto *MTargetOSArg = Args.getLastArg(options::OPT_mtargetos_EQ)) {
2529 std::string TargetArgStr = PlatformAndVersion->getAsString(Args, Opts);
2530 std::string MTargetOSArgStr = MTargetOSArg->getAsString(Args);
2531 getDriver().Diag(diag::err_drv_cannot_mix_options)
2532 << TargetArgStr << MTargetOSArgStr;
2533 }
2534 // Implicitly allow resolving the OS version when it wasn't explicitly set.
2535 bool TripleProvidedOSVersion = PlatformAndVersion->hasOSVersion();
2536 if (!TripleProvidedOSVersion)
2537 PlatformAndVersion->setOSVersion(
2538 getInferredOSVersion(getTriple().getOS(), getTriple(), getDriver()));
2539
2540 std::optional<DarwinPlatform> PlatformAndVersionFromOSVersionArg =
2541 getDeploymentTargetFromOSVersionArg(Args, getDriver());
2542 if (PlatformAndVersionFromOSVersionArg) {
2543 unsigned TargetMajor, TargetMinor, TargetMicro;
2544 bool TargetExtra;
2545 unsigned ArgMajor, ArgMinor, ArgMicro;
2546 bool ArgExtra;
2547 if (PlatformAndVersion->getPlatform() !=
2548 PlatformAndVersionFromOSVersionArg->getPlatform() ||
2550 PlatformAndVersion->getOSVersion().getAsString(), TargetMajor,
2551 TargetMinor, TargetMicro, TargetExtra) &&
2553 PlatformAndVersionFromOSVersionArg->getOSVersion().getAsString(),
2554 ArgMajor, ArgMinor, ArgMicro, ArgExtra) &&
2555 (VersionTuple(TargetMajor, TargetMinor, TargetMicro) !=
2556 VersionTuple(ArgMajor, ArgMinor, ArgMicro) ||
2557 TargetExtra != ArgExtra))) {
2558 // Select the OS version from the -m<os>-version-min argument when
2559 // the -target does not include an OS version.
2560 if (PlatformAndVersion->getPlatform() ==
2561 PlatformAndVersionFromOSVersionArg->getPlatform() &&
2562 !TripleProvidedOSVersion) {
2563 PlatformAndVersion->setOSVersion(
2564 PlatformAndVersionFromOSVersionArg->getOSVersion());
2565 } else {
2566 // Warn about -m<os>-version-min that doesn't match the OS version
2567 // that's specified in the target.
2568 std::string OSVersionArg =
2569 PlatformAndVersionFromOSVersionArg->getAsString(Args, Opts);
2570 std::string TargetArg = PlatformAndVersion->getAsString(Args, Opts);
2571 getDriver().Diag(clang::diag::warn_drv_overriding_option)
2572 << OSVersionArg << TargetArg;
2573 }
2574 }
2575 }
2576 } else if ((PlatformAndVersion = getDeploymentTargetFromMTargetOSArg(
2577 Args, getDriver(), SDKInfo))) {
2578 // The OS target can be specified using the -mtargetos= argument.
2579 // Disallow mixing -mtargetos= and -m<os>version-min=.
2580 std::optional<DarwinPlatform> PlatformAndVersionFromOSVersionArg =
2581 getDeploymentTargetFromOSVersionArg(Args, getDriver());
2582 if (PlatformAndVersionFromOSVersionArg) {
2583 std::string MTargetOSArgStr = PlatformAndVersion->getAsString(Args, Opts);
2584 std::string OSVersionArgStr =
2585 PlatformAndVersionFromOSVersionArg->getAsString(Args, Opts);
2586 getDriver().Diag(diag::err_drv_cannot_mix_options)
2587 << MTargetOSArgStr << OSVersionArgStr;
2588 }
2589 } else {
2590 // The OS target can be specified using the -m<os>version-min argument.
2591 PlatformAndVersion = getDeploymentTargetFromOSVersionArg(Args, getDriver());
2592 // If no deployment target was specified on the command line, check for
2593 // environment defines.
2594 if (!PlatformAndVersion) {
2595 PlatformAndVersion =
2596 getDeploymentTargetFromEnvironmentVariables(getDriver(), getTriple());
2597 if (PlatformAndVersion) {
2598 // Don't infer simulator from the arch when the SDK is also specified.
2599 std::optional<DarwinPlatform> SDKTarget =
2600 inferDeploymentTargetFromSDK(Args, SDKInfo);
2601 if (SDKTarget)
2602 PlatformAndVersion->setEnvironment(SDKTarget->getEnvironment());
2603 }
2604 }
2605 // If there is no command-line argument to specify the Target version and
2606 // no environment variable defined, see if we can set the default based
2607 // on -isysroot using SDKSettings.json if it exists.
2608 if (!PlatformAndVersion) {
2609 PlatformAndVersion = inferDeploymentTargetFromSDK(Args, SDKInfo);
2610 /// If the target was successfully constructed from the SDK path, try to
2611 /// infer the SDK info if the SDK doesn't have it.
2612 if (PlatformAndVersion && !SDKInfo)
2613 SDKInfo = PlatformAndVersion->inferSDKInfo();
2614 }
2615 // If no OS targets have been specified, try to guess platform from -target
2616 // or arch name and compute the version from the triple.
2617 if (!PlatformAndVersion)
2618 PlatformAndVersion =
2619 inferDeploymentTargetFromArch(Args, *this, getTriple(), getDriver());
2620 }
2621
2622 assert(PlatformAndVersion && "Unable to infer Darwin variant");
2623 if (!PlatformAndVersion->isValidOSVersion()) {
2624 if (PlatformAndVersion->isExplicitlySpecified())
2625 getDriver().Diag(diag::err_drv_invalid_version_number)
2626 << PlatformAndVersion->getAsString(Args, Opts);
2627 else
2628 getDriver().Diag(diag::err_drv_invalid_version_number_inferred)
2629 << PlatformAndVersion->getOSVersion().getAsString()
2630 << PlatformAndVersion->getInferredSource();
2631 }
2632 // After the deployment OS version has been resolved, set it to the canonical
2633 // version before further error detection and converting to a proper target
2634 // triple.
2635 VersionTuple CanonicalVersion = PlatformAndVersion->getCanonicalOSVersion();
2636 if (CanonicalVersion != PlatformAndVersion->getOSVersion()) {
2637 getDriver().Diag(diag::warn_drv_overriding_deployment_version)
2638 << PlatformAndVersion->getOSVersion().getAsString()
2639 << CanonicalVersion.getAsString();
2640 PlatformAndVersion->setOSVersion(CanonicalVersion);
2641 }
2642
2643 PlatformAndVersion->addOSVersionMinArgument(Args, Opts);
2644 DarwinPlatformKind Platform = PlatformAndVersion->getPlatform();
2645
2646 unsigned Major, Minor, Micro;
2647 bool HadExtra;
2648 // The major version should not be over this number.
2649 const unsigned MajorVersionLimit = 1000;
2650 const VersionTuple OSVersion = PlatformAndVersion->takeOSVersion();
2651 const std::string OSVersionStr = OSVersion.getAsString();
2652 // Set the tool chain target information.
2653 if (Platform == MacOS) {
2654 if (!Driver::GetReleaseVersion(OSVersionStr, Major, Minor, Micro,
2655 HadExtra) ||
2656 HadExtra || Major < 10 || Major >= MajorVersionLimit || Minor >= 100 ||
2657 Micro >= 100)
2658 getDriver().Diag(diag::err_drv_invalid_version_number)
2659 << PlatformAndVersion->getAsString(Args, Opts);
2660 } else if (Platform == IPhoneOS) {
2661 if (!Driver::GetReleaseVersion(OSVersionStr, Major, Minor, Micro,
2662 HadExtra) ||
2663 HadExtra || Major >= MajorVersionLimit || Minor >= 100 || Micro >= 100)
2664 getDriver().Diag(diag::err_drv_invalid_version_number)
2665 << PlatformAndVersion->getAsString(Args, Opts);
2666 ;
2667 if (PlatformAndVersion->getEnvironment() == MacCatalyst &&
2668 (Major < 13 || (Major == 13 && Minor < 1))) {
2669 getDriver().Diag(diag::err_drv_invalid_version_number)
2670 << PlatformAndVersion->getAsString(Args, Opts);
2671 Major = 13;
2672 Minor = 1;
2673 Micro = 0;
2674 }
2675 // For 32-bit targets, the deployment target for iOS has to be earlier than
2676 // iOS 11.
2677 if (getTriple().isArch32Bit() && Major >= 11) {
2678 // If the deployment target is explicitly specified, print a diagnostic.
2679 if (PlatformAndVersion->isExplicitlySpecified()) {
2680 if (PlatformAndVersion->getEnvironment() == MacCatalyst)
2681 getDriver().Diag(diag::err_invalid_macos_32bit_deployment_target);
2682 else
2683 getDriver().Diag(diag::warn_invalid_ios_deployment_target)
2684 << PlatformAndVersion->getAsString(Args, Opts);
2685 // Otherwise, set it to 10.99.99.
2686 } else {
2687 Major = 10;
2688 Minor = 99;
2689 Micro = 99;
2690 }
2691 }
2692 } else if (Platform == TvOS) {
2693 if (!Driver::GetReleaseVersion(OSVersionStr, Major, Minor, Micro,
2694 HadExtra) ||
2695 HadExtra || Major >= MajorVersionLimit || Minor >= 100 || Micro >= 100)
2696 getDriver().Diag(diag::err_drv_invalid_version_number)
2697 << PlatformAndVersion->getAsString(Args, Opts);
2698 } else if (Platform == WatchOS) {
2699 if (!Driver::GetReleaseVersion(OSVersionStr, Major, Minor, Micro,
2700 HadExtra) ||
2701 HadExtra || Major >= MajorVersionLimit || Minor >= 100 || Micro >= 100)
2702 getDriver().Diag(diag::err_drv_invalid_version_number)
2703 << PlatformAndVersion->getAsString(Args, Opts);
2704 } else if (Platform == DriverKit) {
2705 if (!Driver::GetReleaseVersion(OSVersionStr, Major, Minor, Micro,
2706 HadExtra) ||
2707 HadExtra || Major < 19 || Major >= MajorVersionLimit || Minor >= 100 ||
2708 Micro >= 100)
2709 getDriver().Diag(diag::err_drv_invalid_version_number)
2710 << PlatformAndVersion->getAsString(Args, Opts);
2711 } else {
2712 if (!Driver::GetReleaseVersion(OSVersionStr, Major, Minor, Micro,
2713 HadExtra) ||
2714 HadExtra || Major < 1 || Major >= MajorVersionLimit || Minor >= 100 ||
2715 Micro >= 100)
2716 getDriver().Diag(diag::err_drv_invalid_version_number)
2717 << PlatformAndVersion->getAsString(Args, Opts);
2718 }
2719
2720 DarwinEnvironmentKind Environment = PlatformAndVersion->getEnvironment();
2721 // Recognize iOS targets with an x86 architecture as the iOS simulator.
2722 if (Environment == NativeEnvironment && Platform != MacOS &&
2723 Platform != DriverKit &&
2724 PlatformAndVersion->canInferSimulatorFromArch() && getTriple().isX86())
2725 Environment = Simulator;
2726
2727 VersionTuple ZipperedOSVersion;
2728 if (Environment == MacCatalyst)
2729 ZipperedOSVersion = PlatformAndVersion->getZipperedOSVersion();
2730 setTarget(Platform, Environment, Major, Minor, Micro, ZipperedOSVersion);
2731 TargetVariantTriple = PlatformAndVersion->getTargetVariantTriple();
2732 if (TargetVariantTriple &&
2733 !llvm::Triple::isValidVersionForOS(TargetVariantTriple->getOS(),
2734 TargetVariantTriple->getOSVersion())) {
2735 getDriver().Diag(diag::err_drv_invalid_version_number)
2736 << TargetVariantTriple->str();
2737 }
2738}
2739
2740bool DarwinClang::HasPlatformPrefix(const llvm::Triple &T) const {
2741 if (SDKInfo)
2742 return !SDKInfo->getPlatformPrefix(T).empty();
2743 else
2744 return Darwin::HasPlatformPrefix(T);
2745}
2746
2747// For certain platforms/environments almost all resources (e.g., headers) are
2748// located in sub-directories, e.g., for DriverKit they live in
2749// <SYSROOT>/System/DriverKit/usr/include (instead of <SYSROOT>/usr/include).
2751 const llvm::Triple &T) const {
2752 if (SDKInfo) {
2753 const StringRef PlatformPrefix = SDKInfo->getPlatformPrefix(T);
2754 if (!PlatformPrefix.empty())
2755 llvm::sys::path::append(Path, PlatformPrefix);
2756 } else if (T.isDriverKit()) {
2757 // The first version of DriverKit didn't have SDKSettings.json, manually add
2758 // its prefix.
2759 llvm::sys::path::append(Path, "System", "DriverKit");
2760 }
2761}
2762
2763// Returns the effective sysroot from either -isysroot or --sysroot, plus the
2764// platform prefix (if any).
2766AppleMachO::GetEffectiveSysroot(const llvm::opt::ArgList &DriverArgs) const {
2767 llvm::SmallString<128> Path("/");
2768 if (DriverArgs.hasArg(options::OPT_isysroot))
2769 Path = DriverArgs.getLastArgValue(options::OPT_isysroot);
2770 else if (!getDriver().SysRoot.empty())
2771 Path = getDriver().SysRoot;
2772
2773 if (hasEffectiveTriple()) {
2775 }
2776 return Path;
2777}
2778
2780 const llvm::opt::ArgList &DriverArgs,
2781 llvm::opt::ArgStringList &CC1Args) const {
2782 const Driver &D = getDriver();
2783
2784 llvm::SmallString<128> Sysroot = GetEffectiveSysroot(DriverArgs);
2785
2786 bool NoStdInc = DriverArgs.hasArg(options::OPT_nostdinc);
2787 bool NoStdlibInc = DriverArgs.hasArg(options::OPT_nostdlibinc);
2788 bool NoBuiltinInc = DriverArgs.hasFlag(
2789 options::OPT_nobuiltininc, options::OPT_ibuiltininc, /*Default=*/false);
2790 bool ForceBuiltinInc = DriverArgs.hasFlag(
2791 options::OPT_ibuiltininc, options::OPT_nobuiltininc, /*Default=*/false);
2792
2793 // Add <sysroot>/usr/local/include
2794 if (!NoStdInc && !NoStdlibInc) {
2795 SmallString<128> P(Sysroot);
2796 llvm::sys::path::append(P, "usr", "local", "include");
2797 addSystemInclude(DriverArgs, CC1Args, P);
2798 }
2799
2800 // Add the Clang builtin headers (<resource>/include)
2801 if (!(NoStdInc && !ForceBuiltinInc) && !NoBuiltinInc) {
2802 SmallString<128> P(D.ResourceDir);
2803 llvm::sys::path::append(P, "include");
2804 addSystemInclude(DriverArgs, CC1Args, P);
2805 }
2806
2807 if (NoStdInc || NoStdlibInc)
2808 return;
2809
2810 // Check for configure-time C include directories.
2811 llvm::StringRef CIncludeDirs(C_INCLUDE_DIRS);
2812 if (!CIncludeDirs.empty()) {
2814 CIncludeDirs.split(dirs, ":");
2815 for (llvm::StringRef dir : dirs) {
2816 llvm::StringRef Prefix =
2817 llvm::sys::path::is_absolute(dir) ? "" : llvm::StringRef(Sysroot);
2818 addExternCSystemInclude(DriverArgs, CC1Args, Prefix + dir);
2819 }
2820 } else {
2821 // Otherwise, add <sysroot>/usr/include.
2822 SmallString<128> P(Sysroot);
2823 llvm::sys::path::append(P, "usr", "include");
2824 addExternCSystemInclude(DriverArgs, CC1Args, P.str());
2825 }
2826}
2827
2829 const llvm::opt::ArgList &DriverArgs,
2830 llvm::opt::ArgStringList &CC1Args) const {
2831 AppleMachO::AddClangSystemIncludeArgs(DriverArgs, CC1Args);
2832
2833 if (DriverArgs.hasArg(options::OPT_nostdinc, options::OPT_nostdlibinc))
2834 return;
2835
2836 llvm::SmallString<128> Sysroot = GetEffectiveSysroot(DriverArgs);
2837
2838 // Add <sysroot>/System/Library/Frameworks
2839 // Add <sysroot>/System/Library/SubFrameworks
2840 // Add <sysroot>/Library/Frameworks
2841 SmallString<128> P1(Sysroot), P2(Sysroot), P3(Sysroot);
2842 llvm::sys::path::append(P1, "System", "Library", "Frameworks");
2843 llvm::sys::path::append(P2, "System", "Library", "SubFrameworks");
2844 llvm::sys::path::append(P3, "Library", "Frameworks");
2845 addSystemFrameworkIncludes(DriverArgs, CC1Args, {P1, P2, P3});
2846}
2847
2848bool DarwinClang::AddGnuCPlusPlusIncludePaths(const llvm::opt::ArgList &DriverArgs,
2849 llvm::opt::ArgStringList &CC1Args,
2851 llvm::StringRef Version,
2852 llvm::StringRef ArchDir,
2853 llvm::StringRef BitDir) const {
2854 llvm::sys::path::append(Base, Version);
2855
2856 // Add the base dir
2857 addSystemInclude(DriverArgs, CC1Args, Base);
2858
2859 // Add the multilib dirs
2860 {
2862 if (!ArchDir.empty())
2863 llvm::sys::path::append(P, ArchDir);
2864 if (!BitDir.empty())
2865 llvm::sys::path::append(P, BitDir);
2866 addSystemInclude(DriverArgs, CC1Args, P);
2867 }
2868
2869 // Add the backward dir
2870 {
2872 llvm::sys::path::append(P, "backward");
2873 addSystemInclude(DriverArgs, CC1Args, P);
2874 }
2875
2876 return getVFS().exists(Base);
2877}
2878
2880 const llvm::opt::ArgList &DriverArgs,
2881 llvm::opt::ArgStringList &CC1Args) const {
2882 // The implementation from a base class will pass through the -stdlib to
2883 // CC1Args.
2884 // FIXME: this should not be necessary, remove usages in the frontend
2885 // (e.g. HeaderSearchOptions::UseLibcxx) and don't pipe -stdlib.
2886 // Also check whether this is used for setting library search paths.
2887 ToolChain::AddClangCXXStdlibIncludeArgs(DriverArgs, CC1Args);
2888
2889 if (DriverArgs.hasArg(options::OPT_nostdinc, options::OPT_nostdlibinc,
2890 options::OPT_nostdincxx))
2891 return;
2892
2893 llvm::SmallString<128> Sysroot = GetEffectiveSysroot(DriverArgs);
2894
2895 switch (GetCXXStdlibType(DriverArgs)) {
2896 case ToolChain::CST_Libcxx: {
2897 // On Darwin, libc++ can be installed in one of the following places:
2898 // 1. Alongside the compiler in <clang-executable-folder>/../include/c++/v1
2899 // 2. In a SDK (or a custom sysroot) in <sysroot>/usr/include/c++/v1
2900 //
2901 // The precedence of paths is as listed above, i.e. we take the first path
2902 // that exists. Note that we never include libc++ twice -- we take the first
2903 // path that exists and don't send the other paths to CC1 (otherwise
2904 // include_next could break).
2905
2906 // Check for (1)
2907 // Get from '<install>/bin' to '<install>/include/c++/v1'.
2908 // Note that InstallBin can be relative, so we use '..' instead of
2909 // parent_path.
2910 llvm::SmallString<128> InstallBin(getDriver().Dir); // <install>/bin
2911 llvm::sys::path::append(InstallBin, "..", "include", "c++", "v1");
2912 if (getVFS().exists(InstallBin)) {
2913 addSystemInclude(DriverArgs, CC1Args, InstallBin);
2914 return;
2915 } else if (DriverArgs.hasArg(options::OPT_v)) {
2916 llvm::errs() << "ignoring nonexistent directory \"" << InstallBin
2917 << "\"\n";
2918 }
2919
2920 // Otherwise, check for (2)
2921 llvm::SmallString<128> SysrootUsr = Sysroot;
2922 llvm::sys::path::append(SysrootUsr, "usr", "include", "c++", "v1");
2923 if (getVFS().exists(SysrootUsr)) {
2924 addSystemInclude(DriverArgs, CC1Args, SysrootUsr);
2925 return;
2926 } else if (DriverArgs.hasArg(options::OPT_v)) {
2927 llvm::errs() << "ignoring nonexistent directory \"" << SysrootUsr
2928 << "\"\n";
2929 }
2930
2931 // Otherwise, don't add any path.
2932 break;
2933 }
2934
2936 AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args);
2937 break;
2938 }
2939}
2940
2941void AppleMachO::AddGnuCPlusPlusIncludePaths(
2942 const llvm::opt::ArgList &DriverArgs,
2943 llvm::opt::ArgStringList &CC1Args) const {}
2944
2945void DarwinClang::AddGnuCPlusPlusIncludePaths(
2946 const llvm::opt::ArgList &DriverArgs,
2947 llvm::opt::ArgStringList &CC1Args) const {
2948 llvm::SmallString<128> UsrIncludeCxx = GetEffectiveSysroot(DriverArgs);
2949 llvm::sys::path::append(UsrIncludeCxx, "usr", "include", "c++");
2950
2951 llvm::Triple::ArchType arch = getTriple().getArch();
2952 bool IsBaseFound = true;
2953 switch (arch) {
2954 default:
2955 break;
2956
2957 case llvm::Triple::x86:
2958 case llvm::Triple::x86_64:
2959 IsBaseFound = AddGnuCPlusPlusIncludePaths(
2960 DriverArgs, CC1Args, UsrIncludeCxx, "4.2.1", "i686-apple-darwin10",
2961 arch == llvm::Triple::x86_64 ? "x86_64" : "");
2962 IsBaseFound |= AddGnuCPlusPlusIncludePaths(
2963 DriverArgs, CC1Args, UsrIncludeCxx, "4.0.0", "i686-apple-darwin8", "");
2964 break;
2965
2966 case llvm::Triple::arm:
2967 case llvm::Triple::thumb:
2968 IsBaseFound =
2969 AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, UsrIncludeCxx, "4.2.1",
2970 "arm-apple-darwin10", "v7");
2971 IsBaseFound |=
2972 AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, UsrIncludeCxx, "4.2.1",
2973 "arm-apple-darwin10", "v6");
2974 break;
2975
2976 case llvm::Triple::aarch64:
2977 IsBaseFound =
2978 AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, UsrIncludeCxx, "4.2.1",
2979 "arm64-apple-darwin10", "");
2980 break;
2981 }
2982
2983 if (!IsBaseFound) {
2984 getDriver().Diag(diag::warn_drv_libstdcxx_not_found);
2985 }
2986}
2987
2988void AppleMachO::AddCXXStdlibLibArgs(const ArgList &Args,
2989 ArgStringList &CmdArgs) const {
2991
2992 switch (Type) {
2994 CmdArgs.push_back("-lc++");
2995 if (Args.hasArg(options::OPT_fexperimental_library))
2996 CmdArgs.push_back("-lc++experimental");
2997 break;
2998
3000 // Unfortunately, -lstdc++ doesn't always exist in the standard search path;
3001 // it was previously found in the gcc lib dir. However, for all the Darwin
3002 // platforms we care about it was -lstdc++.6, so we search for that
3003 // explicitly if we can't see an obvious -lstdc++ candidate.
3004
3005 // Check in the sysroot first.
3006 if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
3007 SmallString<128> P(A->getValue());
3008 llvm::sys::path::append(P, "usr", "lib", "libstdc++.dylib");
3009
3010 if (!getVFS().exists(P)) {
3011 llvm::sys::path::remove_filename(P);
3012 llvm::sys::path::append(P, "libstdc++.6.dylib");
3013 if (getVFS().exists(P)) {
3014 CmdArgs.push_back(Args.MakeArgString(P));
3015 return;
3016 }
3017 }
3018 }
3019
3020 // Otherwise, look in the root.
3021 // FIXME: This should be removed someday when we don't have to care about
3022 // 10.6 and earlier, where /usr/lib/libstdc++.dylib does not exist.
3023 if (!getVFS().exists("/usr/lib/libstdc++.dylib") &&
3024 getVFS().exists("/usr/lib/libstdc++.6.dylib")) {
3025 CmdArgs.push_back("/usr/lib/libstdc++.6.dylib");
3026 return;
3027 }
3028
3029 // Otherwise, let the linker search.
3030 CmdArgs.push_back("-lstdc++");
3031 break;
3032 }
3033}
3034
3035void DarwinClang::AddCCKextLibArgs(const ArgList &Args,
3036 ArgStringList &CmdArgs) const {
3037 // For Darwin platforms, use the compiler-rt-based support library
3038 // instead of the gcc-provided one (which is also incidentally
3039 // only present in the gcc lib dir, which makes it hard to find).
3040
3041 SmallString<128> P(getDriver().ResourceDir);
3042 llvm::sys::path::append(P, "lib", "darwin");
3043
3044 // Use the newer cc_kext for iOS ARM after 6.0.
3045 if (isTargetWatchOS()) {
3046 llvm::sys::path::append(P, "libclang_rt.cc_kext_watchos.a");
3047 } else if (isTargetTvOS()) {
3048 llvm::sys::path::append(P, "libclang_rt.cc_kext_tvos.a");
3049 } else if (isTargetIPhoneOS()) {
3050 llvm::sys::path::append(P, "libclang_rt.cc_kext_ios.a");
3051 } else if (isTargetDriverKit()) {
3052 // DriverKit doesn't want extra runtime support.
3053 } else if (isTargetXROSDevice()) {
3054 llvm::sys::path::append(
3055 P, llvm::Twine("libclang_rt.cc_kext_") +
3056 llvm::Triple::getOSTypeName(llvm::Triple::XROS) + ".a");
3057 } else {
3058 llvm::sys::path::append(P, "libclang_rt.cc_kext.a");
3059 }
3060
3061 // For now, allow missing resource libraries to support developers who may
3062 // not have compiler-rt checked out or integrated into their build.
3063 if (getVFS().exists(P))
3064 CmdArgs.push_back(Args.MakeArgString(P));
3065}
3066
3067DerivedArgList *MachO::TranslateArgs(const DerivedArgList &Args,
3068 StringRef BoundArch,
3069 Action::OffloadKind) const {
3070 DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
3071 const OptTable &Opts = getDriver().getOpts();
3072
3073 // FIXME: We really want to get out of the tool chain level argument
3074 // translation business, as it makes the driver functionality much
3075 // more opaque. For now, we follow gcc closely solely for the
3076 // purpose of easily achieving feature parity & testability. Once we
3077 // have something that works, we should reevaluate each translation
3078 // and try to push it down into tool specific logic.
3079
3080 for (Arg *A : Args) {
3081 // Sob. These is strictly gcc compatible for the time being. Apple
3082 // gcc translates options twice, which means that self-expanding
3083 // options add duplicates.
3084 switch ((options::ID)A->getOption().getID()) {
3085 default:
3086 DAL->append(A);
3087 break;
3088
3089 case options::OPT_mkernel:
3090 case options::OPT_fapple_kext:
3091 DAL->append(A);
3092 DAL->AddFlagArg(A, Opts.getOption(options::OPT_static));
3093 break;
3094
3095 case options::OPT_dependency_file:
3096 DAL->AddSeparateArg(A, Opts.getOption(options::OPT_MF), A->getValue());
3097 break;
3098
3099 case options::OPT_gfull:
3100 DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
3101 DAL->AddFlagArg(
3102 A, Opts.getOption(options::OPT_fno_eliminate_unused_debug_symbols));
3103 break;
3104
3105 case options::OPT_gused:
3106 DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
3107 DAL->AddFlagArg(
3108 A, Opts.getOption(options::OPT_feliminate_unused_debug_symbols));
3109 break;
3110
3111 case options::OPT_shared:
3112 DAL->AddFlagArg(A, Opts.getOption(options::OPT_dynamiclib));
3113 break;
3114
3115 case options::OPT_fconstant_cfstrings:
3116 DAL->AddFlagArg(A, Opts.getOption(options::OPT_mconstant_cfstrings));
3117 break;
3118
3119 case options::OPT_fno_constant_cfstrings:
3120 DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_constant_cfstrings));
3121 break;
3122
3123 case options::OPT_Wnonportable_cfstrings:
3124 DAL->AddFlagArg(A,
3125 Opts.getOption(options::OPT_mwarn_nonportable_cfstrings));
3126 break;
3127
3128 case options::OPT_Wno_nonportable_cfstrings:
3129 DAL->AddFlagArg(
3130 A, Opts.getOption(options::OPT_mno_warn_nonportable_cfstrings));
3131 break;
3132 }
3133 }
3134
3135 // Add the arch options based on the particular spelling of -arch, to match
3136 // how the driver works.
3137 if (!BoundArch.empty()) {
3138 StringRef Name = BoundArch;
3139 const Option MCpu = Opts.getOption(options::OPT_mcpu_EQ);
3140 const Option MArch = Opts.getOption(options::OPT_march_EQ);
3141
3142 // This code must be kept in sync with LLVM's getArchTypeForDarwinArch,
3143 // which defines the list of which architectures we accept.
3144 if (Name == "ppc")
3145 ;
3146 else if (Name == "ppc601")
3147 DAL->AddJoinedArg(nullptr, MCpu, "601");
3148 else if (Name == "ppc603")
3149 DAL->AddJoinedArg(nullptr, MCpu, "603");
3150 else if (Name == "ppc604")
3151 DAL->AddJoinedArg(nullptr, MCpu, "604");
3152 else if (Name == "ppc604e")
3153 DAL->AddJoinedArg(nullptr, MCpu, "604e");
3154 else if (Name == "ppc750")
3155 DAL->AddJoinedArg(nullptr, MCpu, "750");
3156 else if (Name == "ppc7400")
3157 DAL->AddJoinedArg(nullptr, MCpu, "7400");
3158 else if (Name == "ppc7450")
3159 DAL->AddJoinedArg(nullptr, MCpu, "7450");
3160 else if (Name == "ppc970")
3161 DAL->AddJoinedArg(nullptr, MCpu, "970");
3162
3163 else if (Name == "ppc64" || Name == "ppc64le")
3164 DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64));
3165
3166 else if (Name == "i386")
3167 ;
3168 else if (Name == "i486")
3169 DAL->AddJoinedArg(nullptr, MArch, "i486");
3170 else if (Name == "i586")
3171 DAL->AddJoinedArg(nullptr, MArch, "i586");
3172 else if (Name == "i686")
3173 DAL->AddJoinedArg(nullptr, MArch, "i686");
3174 else if (Name == "pentium")
3175 DAL->AddJoinedArg(nullptr, MArch, "pentium");
3176 else if (Name == "pentium2")
3177 DAL->AddJoinedArg(nullptr, MArch, "pentium2");
3178 else if (Name == "pentpro")
3179 DAL->AddJoinedArg(nullptr, MArch, "pentiumpro");
3180 else if (Name == "pentIIm3")
3181 DAL->AddJoinedArg(nullptr, MArch, "pentium2");
3182
3183 else if (Name == "x86_64" || Name == "x86_64h")
3184 DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64));
3185
3186 else if (Name == "arm")
3187 DAL->AddJoinedArg(nullptr, MArch, "armv4t");
3188 else if (Name == "armv4t")
3189 DAL->AddJoinedArg(nullptr, MArch, "armv4t");
3190 else if (Name == "armv5")
3191 DAL->AddJoinedArg(nullptr, MArch, "armv5tej");
3192 else if (Name == "xscale")
3193 DAL->AddJoinedArg(nullptr, MArch, "xscale");
3194 else if (Name == "armv6")
3195 DAL->AddJoinedArg(nullptr, MArch, "armv6k");
3196 else if (Name == "armv6m")
3197 DAL->AddJoinedArg(nullptr, MArch, "armv6m");
3198 else if (Name == "armv7")
3199 DAL->AddJoinedArg(nullptr, MArch, "armv7a");
3200 else if (Name == "armv7em")
3201 DAL->AddJoinedArg(nullptr, MArch, "armv7em");
3202 else if (Name == "armv7k")
3203 DAL->AddJoinedArg(nullptr, MArch, "armv7k");
3204 else if (Name == "armv7m")
3205 DAL->AddJoinedArg(nullptr, MArch, "armv7m");
3206 else if (Name == "armv7s")
3207 DAL->AddJoinedArg(nullptr, MArch, "armv7s");
3208 }
3209
3210 return DAL;
3211}
3212
3213void MachO::AddLinkRuntimeLibArgs(const ArgList &Args,
3214 ArgStringList &CmdArgs,
3215 bool ForceLinkBuiltinRT) const {
3216 // Embedded targets are simple at the moment, not supporting sanitizers and
3217 // with different libraries for each member of the product { static, PIC } x
3218 // { hard-float, soft-float }
3219 llvm::SmallString<32> CompilerRT = StringRef("");
3220 CompilerRT +=
3222 ? "hard"
3223 : "soft";
3224 CompilerRT += Args.hasArg(options::OPT_fPIC) ? "_pic" : "_static";
3225
3226 AddLinkRuntimeLib(Args, CmdArgs, CompilerRT, RLO_IsEmbedded);
3227}
3228
3230 llvm::Triple::OSType OS;
3231
3232 if (isTargetMacCatalyst())
3233 return TargetVersion < alignedAllocMinVersion(llvm::Triple::MacOSX);
3234 switch (TargetPlatform) {
3235 case MacOS: // Earlier than 10.13.
3236 OS = llvm::Triple::MacOSX;
3237 break;
3238 case IPhoneOS:
3239 OS = llvm::Triple::IOS;
3240 break;
3241 case TvOS: // Earlier than 11.0.
3242 OS = llvm::Triple::TvOS;
3243 break;
3244 case WatchOS: // Earlier than 4.0.
3245 OS = llvm::Triple::WatchOS;
3246 break;
3247 default: // Always available on newer platforms.
3248 return false;
3249 }
3250
3252}
3253
3254static bool
3255sdkSupportsBuiltinModules(const std::optional<DarwinSDKInfo> &SDKInfo) {
3256 if (!SDKInfo)
3257 // If there is no SDK info, assume this is building against an SDK that
3258 // predates SDKSettings.json. None of those support builtin modules.
3259 return false;
3260
3261 switch (SDKInfo->getEnvironment()) {
3262 case llvm::Triple::UnknownEnvironment:
3263 case llvm::Triple::Simulator:
3264 case llvm::Triple::MacABI:
3265 // Standard xnu/Mach/Darwin based environments depend on the SDK version.
3266 break;
3267
3268 default:
3269 // All other environments support builtin modules from the start.
3270 return true;
3271 }
3272
3273 VersionTuple SDKVersion = SDKInfo->getVersion();
3274 switch (SDKInfo->getOS()) {
3275 // Existing SDKs added support for builtin modules in the fall
3276 // 2024 major releases.
3277 case llvm::Triple::MacOSX:
3278 return SDKVersion >= VersionTuple(15U);
3279 case llvm::Triple::IOS:
3280 return SDKVersion >= VersionTuple(18U);
3281 case llvm::Triple::TvOS:
3282 return SDKVersion >= VersionTuple(18U);
3283 case llvm::Triple::WatchOS:
3284 return SDKVersion >= VersionTuple(11U);
3285 case llvm::Triple::XROS:
3286 return SDKVersion >= VersionTuple(2U);
3287
3288 // New SDKs support builtin modules from the start.
3289 default:
3290 return true;
3291 }
3292}
3293
3294static inline llvm::VersionTuple
3295sizedDeallocMinVersion(llvm::Triple::OSType OS) {
3296 switch (OS) {
3297 default:
3298 break;
3299 case llvm::Triple::Darwin:
3300 case llvm::Triple::MacOSX: // Earliest supporting version is 10.12.
3301 return llvm::VersionTuple(10U, 12U);
3302 case llvm::Triple::IOS:
3303 case llvm::Triple::TvOS: // Earliest supporting version is 10.0.0.
3304 return llvm::VersionTuple(10U);
3305 case llvm::Triple::WatchOS: // Earliest supporting version is 3.0.0.
3306 return llvm::VersionTuple(3U);
3307 }
3308
3309 llvm_unreachable("Unexpected OS");
3310}
3311
3313 llvm::Triple::OSType OS;
3314
3315 if (isTargetMacCatalyst())
3316 return TargetVersion < sizedDeallocMinVersion(llvm::Triple::MacOSX);
3317 switch (TargetPlatform) {
3318 case MacOS: // Earlier than 10.12.
3319 OS = llvm::Triple::MacOSX;
3320 break;
3321 case IPhoneOS:
3322 OS = llvm::Triple::IOS;
3323 break;
3324 case TvOS: // Earlier than 10.0.
3325 OS = llvm::Triple::TvOS;
3326 break;
3327 case WatchOS: // Earlier than 3.0.
3328 OS = llvm::Triple::WatchOS;
3329 break;
3330 default:
3331 // Always available on newer platforms.
3332 return false;
3333 }
3334
3336}
3337
3338void MachO::addClangTargetOptions(const llvm::opt::ArgList &DriverArgs,
3339 llvm::opt::ArgStringList &CC1Args,
3340 Action::OffloadKind DeviceOffloadKind) const {
3341
3342 ToolChain::addClangTargetOptions(DriverArgs, CC1Args, DeviceOffloadKind);
3343
3344 // On arm64e, we enable all the features required for the Darwin userspace
3345 // ABI
3346 if (getTriple().isArm64e()) {
3347 // Core platform ABI
3348 if (!DriverArgs.hasArg(options::OPT_fptrauth_calls,
3349 options::OPT_fno_ptrauth_calls))
3350 CC1Args.push_back("-fptrauth-calls");
3351 if (!DriverArgs.hasArg(options::OPT_fptrauth_returns,
3352 options::OPT_fno_ptrauth_returns))
3353 CC1Args.push_back("-fptrauth-returns");
3354 if (!DriverArgs.hasArg(options::OPT_fptrauth_intrinsics,
3355 options::OPT_fno_ptrauth_intrinsics))
3356 CC1Args.push_back("-fptrauth-intrinsics");
3357 if (!DriverArgs.hasArg(options::OPT_fptrauth_indirect_gotos,
3358 options::OPT_fno_ptrauth_indirect_gotos))
3359 CC1Args.push_back("-fptrauth-indirect-gotos");
3360 if (!DriverArgs.hasArg(options::OPT_fptrauth_auth_traps,
3361 options::OPT_fno_ptrauth_auth_traps))
3362 CC1Args.push_back("-fptrauth-auth-traps");
3363
3364 // C++ v-table ABI
3365 if (!DriverArgs.hasArg(
3366 options::OPT_fptrauth_vtable_pointer_address_discrimination,
3367 options::OPT_fno_ptrauth_vtable_pointer_address_discrimination))
3368 CC1Args.push_back("-fptrauth-vtable-pointer-address-discrimination");
3369 if (!DriverArgs.hasArg(
3370 options::OPT_fptrauth_vtable_pointer_type_discrimination,
3371 options::OPT_fno_ptrauth_vtable_pointer_type_discrimination))
3372 CC1Args.push_back("-fptrauth-vtable-pointer-type-discrimination");
3373
3374 // Objective-C ABI
3375 if (!DriverArgs.hasArg(options::OPT_fptrauth_objc_isa,
3376 options::OPT_fno_ptrauth_objc_isa))
3377 CC1Args.push_back("-fptrauth-objc-isa");
3378 if (!DriverArgs.hasArg(options::OPT_fptrauth_objc_class_ro,
3379 options::OPT_fno_ptrauth_objc_class_ro))
3380 CC1Args.push_back("-fptrauth-objc-class-ro");
3381 if (!DriverArgs.hasArg(options::OPT_fptrauth_objc_interface_sel,
3382 options::OPT_fno_ptrauth_objc_interface_sel))
3383 CC1Args.push_back("-fptrauth-objc-interface-sel");
3384 }
3385}
3386
3388 const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args,
3389 Action::OffloadKind DeviceOffloadKind) const {
3390
3391 MachO::addClangTargetOptions(DriverArgs, CC1Args, DeviceOffloadKind);
3392
3393 // Pass "-faligned-alloc-unavailable" only when the user hasn't manually
3394 // enabled or disabled aligned allocations.
3395 if (!DriverArgs.hasArgNoClaim(options::OPT_faligned_allocation,
3396 options::OPT_fno_aligned_allocation) &&
3398 CC1Args.push_back("-faligned-alloc-unavailable");
3399
3400 // Enable objc_msgSend selector stubs by default if the linker supports it.
3401 // ld64-811.2+ does, for arm64, arm64e, and arm64_32.
3402 if (!DriverArgs.hasArgNoClaim(options::OPT_fobjc_msgsend_selector_stubs,
3403 options::OPT_fno_objc_msgsend_selector_stubs) &&
3404 getTriple().isAArch64() &&
3405 (getLinkerVersion(DriverArgs) >= VersionTuple(811, 2)))
3406 CC1Args.push_back("-fobjc-msgsend-selector-stubs");
3407
3408 // Enable objc_msgSend class selector stubs by default if the linker supports
3409 // it. ld64-1250+ does, for arm64, arm64e, and arm64_32.
3410 if (!DriverArgs.hasArgNoClaim(
3411 options::OPT_fobjc_msgsend_class_selector_stubs,
3412 options::OPT_fno_objc_msgsend_class_selector_stubs) &&
3413 getTriple().isAArch64() &&
3414 (getLinkerVersion(DriverArgs) >= VersionTuple(1250, 0)))
3415 CC1Args.push_back("-fobjc-msgsend-class-selector-stubs");
3416
3417 // Pass "-fno-sized-deallocation" only when the user hasn't manually enabled
3418 // or disabled sized deallocations.
3419 if (!DriverArgs.hasArgNoClaim(options::OPT_fsized_deallocation,
3420 options::OPT_fno_sized_deallocation) &&
3422 CC1Args.push_back("-fno-sized-deallocation");
3423
3424 addClangCC1ASTargetOptions(DriverArgs, CC1Args);
3425
3426 if (SDKInfo) {
3427 // Make the SDKSettings.json an explicit dependency for the compiler
3428 // invocation, in case the compiler needs to read it to remap versions.
3429 if (!SDKInfo->getFilePath().empty()) {
3430 SmallString<64> ExtraDepOpt("-fdepfile-entry=");
3431 ExtraDepOpt += SDKInfo->getFilePath();
3432 CC1Args.push_back(DriverArgs.MakeArgString(ExtraDepOpt));
3433 }
3434 }
3435
3436 // Enable compatibility mode for NSItemProviderCompletionHandler in
3437 // Foundation/NSItemProvider.h.
3438 CC1Args.push_back("-fcompatibility-qualified-id-block-type-checking");
3439
3440 // Give static local variables in inline functions hidden visibility when
3441 // -fvisibility-inlines-hidden is enabled.
3442 if (!DriverArgs.getLastArgNoClaim(
3443 options::OPT_fvisibility_inlines_hidden_static_local_var,
3444 options::OPT_fno_visibility_inlines_hidden_static_local_var))
3445 CC1Args.push_back("-fvisibility-inlines-hidden-static-local-var");
3446
3447 // Earlier versions of the darwin SDK have the C standard library headers
3448 // all together in the Darwin module. That leads to module cycles with
3449 // the _Builtin_ modules. e.g. <inttypes.h> on darwin includes <stdint.h>.
3450 // The builtin <stdint.h> include-nexts <stdint.h>. When both of those
3451 // darwin headers are in the Darwin module, there's a module cycle Darwin ->
3452 // _Builtin_stdint -> Darwin (i.e. inttypes.h (darwin) -> stdint.h (builtin) ->
3453 // stdint.h (darwin)). This is fixed in later versions of the darwin SDK,
3454 // but until then, the builtin headers need to join the system modules.
3455 // i.e. when the builtin stdint.h is in the Darwin module too, the cycle
3456 // goes away. Note that -fbuiltin-headers-in-system-modules does nothing
3457 // to fix the same problem with C++ headers, and is generally fragile.
3459 CC1Args.push_back("-fbuiltin-headers-in-system-modules");
3460
3461 if (!DriverArgs.hasArgNoClaim(options::OPT_fdefine_target_os_macros,
3462 options::OPT_fno_define_target_os_macros))
3463 CC1Args.push_back("-fdefine-target-os-macros");
3464
3465 // Disable subdirectory modulemap search on sufficiently recent SDKs.
3466 if (SDKInfo &&
3467 !DriverArgs.hasFlag(options::OPT_fmodulemap_allow_subdirectory_search,
3468 options::OPT_fno_modulemap_allow_subdirectory_search,
3469 false)) {
3470 bool RequiresSubdirectorySearch;
3471 VersionTuple SDKVersion = SDKInfo->getVersion();
3472 switch (TargetPlatform) {
3473 default:
3474 RequiresSubdirectorySearch = true;
3475 break;
3476 case MacOS:
3477 RequiresSubdirectorySearch = SDKVersion < VersionTuple(15, 0);
3478 break;
3479 case IPhoneOS:
3480 case TvOS:
3481 RequiresSubdirectorySearch = SDKVersion < VersionTuple(18, 0);
3482 break;
3483 case WatchOS:
3484 RequiresSubdirectorySearch = SDKVersion < VersionTuple(11, 0);
3485 break;
3486 case XROS:
3487 RequiresSubdirectorySearch = SDKVersion < VersionTuple(2, 0);
3488 break;
3489 }
3490 if (!RequiresSubdirectorySearch)
3491 CC1Args.push_back("-fno-modulemap-allow-subdirectory-search");
3492 }
3493}
3494
3496 const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CC1ASArgs) const {
3497 if (TargetVariantTriple) {
3498 CC1ASArgs.push_back("-darwin-target-variant-triple");
3499 CC1ASArgs.push_back(Args.MakeArgString(TargetVariantTriple->getTriple()));
3500 }
3501
3502 if (SDKInfo) {
3503 /// Pass the SDK version to the compiler when the SDK information is
3504 /// available.
3505 auto EmitTargetSDKVersionArg = [&](const VersionTuple &V) {
3506 std::string Arg;
3507 llvm::raw_string_ostream OS(Arg);
3508 OS << "-target-sdk-version=" << V;
3509 CC1ASArgs.push_back(Args.MakeArgString(Arg));
3510 };
3511
3512 if (isTargetMacCatalyst()) {
3513 if (const auto *MacOStoMacCatalystMapping = SDKInfo->getVersionMapping(
3515 std::optional<VersionTuple> SDKVersion = MacOStoMacCatalystMapping->map(
3517 std::nullopt);
3518 EmitTargetSDKVersionArg(
3519 SDKVersion ? *SDKVersion : minimumMacCatalystDeploymentTarget());
3520 }
3521 } else {
3522 EmitTargetSDKVersionArg(SDKInfo->getVersion());
3523 }
3524
3525 /// Pass the target variant SDK version to the compiler when the SDK
3526 /// information is available and is required for target variant.
3527 if (TargetVariantTriple) {
3528 if (isTargetMacCatalyst()) {
3529 std::string Arg;
3530 llvm::raw_string_ostream OS(Arg);
3531 OS << "-darwin-target-variant-sdk-version=" << SDKInfo->getVersion();
3532 CC1ASArgs.push_back(Args.MakeArgString(Arg));
3533 } else if (const auto *MacOStoMacCatalystMapping =
3534 SDKInfo->getVersionMapping(
3536 if (std::optional<VersionTuple> SDKVersion =
3537 MacOStoMacCatalystMapping->map(
3539 std::nullopt)) {
3540 std::string Arg;
3541 llvm::raw_string_ostream OS(Arg);
3542 OS << "-darwin-target-variant-sdk-version=" << *SDKVersion;
3543 CC1ASArgs.push_back(Args.MakeArgString(Arg));
3544 }
3545 }
3546 }
3547 }
3548}
3549
3550DerivedArgList *
3551Darwin::TranslateArgs(const DerivedArgList &Args, StringRef BoundArch,
3552 Action::OffloadKind DeviceOffloadKind) const {
3553 // First get the generic Apple args, before moving onto Darwin-specific ones.
3554 DerivedArgList *DAL =
3555 MachO::TranslateArgs(Args, BoundArch, DeviceOffloadKind);
3556
3557 // If no architecture is bound, none of the translations here are relevant.
3558 if (BoundArch.empty())
3559 return DAL;
3560
3561 // Add an explicit version min argument for the deployment target. We do this
3562 // after argument translation because -Xarch_ arguments may add a version min
3563 // argument.
3564 AddDeploymentTarget(*DAL);
3565
3566 // For iOS 6, undo the translation to add -static for -mkernel/-fapple-kext.
3567 // FIXME: It would be far better to avoid inserting those -static arguments,
3568 // but we can't check the deployment target in the translation code until
3569 // it is set here.
3571 (isTargetIOSBased() && !isIPhoneOSVersionLT(6, 0))) {
3572 for (ArgList::iterator it = DAL->begin(), ie = DAL->end(); it != ie; ) {
3573 Arg *A = *it;
3574 ++it;
3575 if (A->getOption().getID() != options::OPT_mkernel &&
3576 A->getOption().getID() != options::OPT_fapple_kext)
3577 continue;
3578 assert(it != ie && "unexpected argument translation");
3579 A = *it;
3580 assert(A->getOption().getID() == options::OPT_static &&
3581 "missing expected -static argument");
3582 *it = nullptr;
3583 ++it;
3584 }
3585 }
3586
3588 if ((Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb)) {
3589 if (Args.hasFlag(options::OPT_fomit_frame_pointer,
3590 options::OPT_fno_omit_frame_pointer, false))
3591 getDriver().Diag(clang::diag::warn_drv_unsupported_opt_for_target)
3592 << "-fomit-frame-pointer" << BoundArch;
3593 }
3594
3595 return DAL;
3596}
3597
3599 // Unwind tables are not emitted if -fno-exceptions is supplied (except when
3600 // targeting x86_64).
3601 if (getArch() == llvm::Triple::x86_64 ||
3602 (GetExceptionModel(Args) != llvm::ExceptionHandling::SjLj &&
3603 Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
3604 true)))
3605 return (getArch() == llvm::Triple::aarch64 ||
3606 getArch() == llvm::Triple::aarch64_32)
3609
3611}
3612
3614 if (const char *S = ::getenv("RC_DEBUG_OPTIONS"))
3615 return S[0] != '\0';
3616 return false;
3617}
3618
3620 if (const char *S = ::getenv("RC_DEBUG_PREFIX_MAP"))
3621 return S;
3622 return {};
3623}
3624
3625llvm::ExceptionHandling Darwin::GetExceptionModel(const ArgList &Args) const {
3626 // Darwin uses SjLj exceptions on ARM.
3627 if (getTriple().getArch() != llvm::Triple::arm &&
3628 getTriple().getArch() != llvm::Triple::thumb)
3629 return llvm::ExceptionHandling::None;
3630
3631 // Only watchOS uses the new DWARF/Compact unwinding method.
3632 llvm::Triple Triple(ComputeLLVMTriple(Args));
3633 if (Triple.isWatchABI())
3634 return llvm::ExceptionHandling::DwarfCFI;
3635
3636 return llvm::ExceptionHandling::SjLj;
3637}
3638
3640 assert(TargetInitialized && "Target not initialized!");
3642 return false;
3643 return true;
3644}
3645
3646bool MachO::isPICDefault() const { return true; }
3647
3648bool MachO::isPIEDefault(const llvm::opt::ArgList &Args) const { return false; }
3649
3651 return (getArch() == llvm::Triple::x86_64 ||
3652 getArch() == llvm::Triple::aarch64);
3653}
3654
3656 // Profiling instrumentation is only supported on x86.
3657 return getTriple().isX86();
3658}
3659
3660void Darwin::addMinVersionArgs(const ArgList &Args,
3661 ArgStringList &CmdArgs) const {
3662 VersionTuple TargetVersion = getTripleTargetVersion();
3663
3664 assert(!isTargetXROS() && "xrOS always uses -platform-version");
3665
3666 if (isTargetWatchOS())
3667 CmdArgs.push_back("-watchos_version_min");
3668 else if (isTargetWatchOSSimulator())
3669 CmdArgs.push_back("-watchos_simulator_version_min");
3670 else if (isTargetTvOS())
3671 CmdArgs.push_back("-tvos_version_min");
3672 else if (isTargetTvOSSimulator())
3673 CmdArgs.push_back("-tvos_simulator_version_min");
3674 else if (isTargetDriverKit())
3675 CmdArgs.push_back("-driverkit_version_min");
3676 else if (isTargetIOSSimulator())
3677 CmdArgs.push_back("-ios_simulator_version_min");
3678 else if (isTargetIOSBased())
3679 CmdArgs.push_back("-iphoneos_version_min");
3680 else if (isTargetMacCatalyst())
3681 CmdArgs.push_back("-maccatalyst_version_min");
3682 else {
3683 assert(isTargetMacOS() && "unexpected target");
3684 CmdArgs.push_back("-macosx_version_min");
3685 }
3686
3687 VersionTuple MinTgtVers = getEffectiveTriple().getMinimumSupportedOSVersion();
3688 if (!MinTgtVers.empty() && MinTgtVers > TargetVersion)
3689 TargetVersion = MinTgtVers;
3690 CmdArgs.push_back(Args.MakeArgString(TargetVersion.getAsString()));
3691 if (TargetVariantTriple) {
3692 assert(isTargetMacOSBased() && "unexpected target");
3693 VersionTuple VariantTargetVersion;
3694 if (TargetVariantTriple->isMacOSX()) {
3695 CmdArgs.push_back("-macosx_version_min");
3696 TargetVariantTriple->getMacOSXVersion(VariantTargetVersion);
3697 } else {
3698 assert(TargetVariantTriple->isiOS() &&
3699 TargetVariantTriple->isMacCatalystEnvironment() &&
3700 "unexpected target variant triple");
3701 CmdArgs.push_back("-maccatalyst_version_min");
3702 VariantTargetVersion = TargetVariantTriple->getiOSVersion();
3703 }
3704 VersionTuple MinTgtVers =
3705 TargetVariantTriple->getMinimumSupportedOSVersion();
3706 if (MinTgtVers.getMajor() && MinTgtVers > VariantTargetVersion)
3707 VariantTargetVersion = MinTgtVers;
3708 CmdArgs.push_back(Args.MakeArgString(VariantTargetVersion.getAsString()));
3709 }
3710}
3711
3713 Darwin::DarwinEnvironmentKind Environment) {
3714 switch (Platform) {
3715 case Darwin::MacOS:
3716 return "macos";
3717 case Darwin::IPhoneOS:
3718 if (Environment == Darwin::MacCatalyst)
3719 return "mac catalyst";
3720 return "ios";
3721 case Darwin::TvOS:
3722 return "tvos";
3723 case Darwin::WatchOS:
3724 return "watchos";
3725 case Darwin::XROS:
3726 return "xros";
3727 case Darwin::DriverKit:
3728 return "driverkit";
3729 default:
3730 break;
3731 }
3732 llvm_unreachable("invalid platform");
3733}
3734
3735void Darwin::addPlatformVersionArgs(const llvm::opt::ArgList &Args,
3736 llvm::opt::ArgStringList &CmdArgs) const {
3737 // Firmware doesn't use -platform_version.
3739 return MachO::addPlatformVersionArgs(Args, CmdArgs);
3740
3741 auto EmitPlatformVersionArg =
3742 [&](const VersionTuple &TV, Darwin::DarwinPlatformKind TargetPlatform,
3744 const llvm::Triple &TT) {
3745 // -platform_version <platform> <target_version> <sdk_version>
3746 // Both the target and SDK version support only up to 3 components.
3747 CmdArgs.push_back("-platform_version");
3748 std::string PlatformName =
3751 PlatformName += "-simulator";
3752 CmdArgs.push_back(Args.MakeArgString(PlatformName));
3753 VersionTuple TargetVersion = TV.withoutBuild();
3756 getTriple().getArchName() == "arm64e" &&
3757 TargetVersion.getMajor() < 14) {
3758 // arm64e slice is supported on iOS/tvOS 14+ only.
3759 TargetVersion = VersionTuple(14, 0);
3760 }
3761 VersionTuple MinTgtVers = TT.getMinimumSupportedOSVersion();
3762 if (!MinTgtVers.empty() && MinTgtVers > TargetVersion)
3763 TargetVersion = MinTgtVers;
3764 CmdArgs.push_back(Args.MakeArgString(TargetVersion.getAsString()));
3765
3767 // Mac Catalyst programs must use the appropriate iOS SDK version
3768 // that corresponds to the macOS SDK version used for the compilation.
3769 std::optional<VersionTuple> iOSSDKVersion;
3770 if (SDKInfo) {
3771 if (const auto *MacOStoMacCatalystMapping =
3772 SDKInfo->getVersionMapping(
3774 iOSSDKVersion = MacOStoMacCatalystMapping->map(
3775 SDKInfo->getVersion().withoutBuild(),
3776 minimumMacCatalystDeploymentTarget(), std::nullopt);
3777 }
3778 }
3779 CmdArgs.push_back(Args.MakeArgString(
3780 (iOSSDKVersion ? *iOSSDKVersion
3782 .getAsString()));
3783 return;
3784 }
3785
3786 if (SDKInfo) {
3787 VersionTuple SDKVersion = SDKInfo->getVersion().withoutBuild();
3788 if (!SDKVersion.getMinor())
3789 SDKVersion = VersionTuple(SDKVersion.getMajor(), 0);
3790 CmdArgs.push_back(Args.MakeArgString(SDKVersion.getAsString()));
3791 } else {
3792 // Use an SDK version that's matching the deployment target if the SDK
3793 // version is missing. This is preferred over an empty SDK version
3794 // (0.0.0) as the system's runtime might expect the linked binary to
3795 // contain a valid SDK version in order for the binary to work
3796 // correctly. It's reasonable to use the deployment target version as
3797 // a proxy for the SDK version because older SDKs don't guarantee
3798 // support for deployment targets newer than the SDK versions, so that
3799 // rules out using some predetermined older SDK version, which leaves
3800 // the deployment target version as the only reasonable choice.
3801 CmdArgs.push_back(Args.MakeArgString(TargetVersion.getAsString()));
3802 }
3803 };
3804 EmitPlatformVersionArg(getTripleTargetVersion(), TargetPlatform,
3807 return;
3810 VersionTuple TargetVariantVersion;
3811 if (TargetVariantTriple->isMacOSX()) {
3812 TargetVariantTriple->getMacOSXVersion(TargetVariantVersion);
3813 Platform = Darwin::MacOS;
3814 Environment = Darwin::NativeEnvironment;
3815 } else {
3816 assert(TargetVariantTriple->isiOS() &&
3817 TargetVariantTriple->isMacCatalystEnvironment() &&
3818 "unexpected target variant triple");
3819 TargetVariantVersion = TargetVariantTriple->getiOSVersion();
3820 Platform = Darwin::IPhoneOS;
3821 Environment = Darwin::MacCatalyst;
3822 }
3823 EmitPlatformVersionArg(TargetVariantVersion, Platform, Environment,
3825}
3826
3827// Add additional link args for the -dynamiclib option.
3828static void addDynamicLibLinkArgs(const Darwin &D, const ArgList &Args,
3829 ArgStringList &CmdArgs) {
3830 // Derived from darwin_dylib1 spec.
3831 if (D.isTargetIPhoneOS()) {
3832 if (D.isIPhoneOSVersionLT(3, 1))
3833 CmdArgs.push_back("-ldylib1.o");
3834 return;
3835 }
3836
3837 if (!D.isTargetMacOS())
3838 return;
3839 if (D.isMacosxVersionLT(10, 5))
3840 CmdArgs.push_back("-ldylib1.o");
3841 else if (D.isMacosxVersionLT(10, 6))
3842 CmdArgs.push_back("-ldylib1.10.5.o");
3843}
3844
3845// Add additional link args for the -bundle option.
3846static void addBundleLinkArgs(const Darwin &D, const ArgList &Args,
3847 ArgStringList &CmdArgs) {
3848 if (Args.hasArg(options::OPT_static))
3849 return;
3850 // Derived from darwin_bundle1 spec.
3851 if ((D.isTargetIPhoneOS() && D.isIPhoneOSVersionLT(3, 1)) ||
3852 (D.isTargetMacOS() && D.isMacosxVersionLT(10, 6)))
3853 CmdArgs.push_back("-lbundle1.o");
3854}
3855
3856// Add additional link args for the -pg option.
3857static void addPgProfilingLinkArgs(const Darwin &D, const ArgList &Args,
3858 ArgStringList &CmdArgs) {
3859 if (D.isTargetMacOS() && D.isMacosxVersionLT(10, 9)) {
3860 if (Args.hasArg(options::OPT_static) || Args.hasArg(options::OPT_object) ||
3861 Args.hasArg(options::OPT_preload)) {
3862 CmdArgs.push_back("-lgcrt0.o");
3863 } else {
3864 CmdArgs.push_back("-lgcrt1.o");
3865
3866 // darwin_crt2 spec is empty.
3867 }
3868 // By default on OS X 10.8 and later, we don't link with a crt1.o
3869 // file and the linker knows to use _main as the entry point. But,
3870 // when compiling with -pg, we need to link with the gcrt1.o file,
3871 // so pass the -no_new_main option to tell the linker to use the
3872 // "start" symbol as the entry point.
3873 if (!D.isMacosxVersionLT(10, 8))
3874 CmdArgs.push_back("-no_new_main");
3875 } else {
3876 D.getDriver().Diag(diag::err_drv_clang_unsupported_opt_pg_darwin)
3877 << D.isTargetMacOSBased();
3878 }
3879}
3880
3881static void addDefaultCRTLinkArgs(const Darwin &D, const ArgList &Args,
3882 ArgStringList &CmdArgs) {
3883 // Derived from darwin_crt1 spec.
3884 if (D.isTargetIPhoneOS()) {
3885 if (D.getArch() == llvm::Triple::aarch64)
3886 ; // iOS does not need any crt1 files for arm64
3887 else if (D.isIPhoneOSVersionLT(3, 1))
3888 CmdArgs.push_back("-lcrt1.o");
3889 else if (D.isIPhoneOSVersionLT(6, 0))
3890 CmdArgs.push_back("-lcrt1.3.1.o");
3891 return;
3892 }
3893
3894 if (!D.isTargetMacOS())
3895 return;
3896 if (D.isMacosxVersionLT(10, 5))
3897 CmdArgs.push_back("-lcrt1.o");
3898 else if (D.isMacosxVersionLT(10, 6))
3899 CmdArgs.push_back("-lcrt1.10.5.o");
3900 else if (D.isMacosxVersionLT(10, 8))
3901 CmdArgs.push_back("-lcrt1.10.6.o");
3902 // darwin_crt2 spec is empty.
3903}
3904
3905void Darwin::addStartObjectFileArgs(const ArgList &Args,
3906 ArgStringList &CmdArgs) const {
3907 // Firmware uses the "bare metal" start object file args.
3908 if (isTargetFirmware())
3909 return MachO::addStartObjectFileArgs(Args, CmdArgs);
3910
3911 // Derived from startfile spec.
3912 if (Args.hasArg(options::OPT_dynamiclib))
3913 addDynamicLibLinkArgs(*this, Args, CmdArgs);
3914 else if (Args.hasArg(options::OPT_bundle))
3915 addBundleLinkArgs(*this, Args, CmdArgs);
3916 else if (Args.hasArg(options::OPT_pg) && SupportsProfiling())
3917 addPgProfilingLinkArgs(*this, Args, CmdArgs);
3918 else if (Args.hasArg(options::OPT_static) ||
3919 Args.hasArg(options::OPT_object) ||
3920 Args.hasArg(options::OPT_preload))
3921 CmdArgs.push_back("-lcrt0.o");
3922 else
3923 addDefaultCRTLinkArgs(*this, Args, CmdArgs);
3924
3925 if (isTargetMacOS() && Args.hasArg(options::OPT_shared_libgcc) &&
3926 isMacosxVersionLT(10, 5)) {
3927 const char *Str = Args.MakeArgString(GetFilePath("crt3.o"));
3928 CmdArgs.push_back(Str);
3929 }
3930}
3931
3935 return;
3936 getDriver().Diag(diag::err_arc_unsupported_on_toolchain);
3937}
3938
3940 const bool IsX86_64 = getTriple().getArch() == llvm::Triple::x86_64;
3941 const bool IsAArch64 = getTriple().getArch() == llvm::Triple::aarch64;
3943 Res |= SanitizerKind::Address;
3944 Res |= SanitizerKind::PointerCompare;
3945 Res |= SanitizerKind::PointerSubtract;
3946 Res |= SanitizerKind::Realtime;
3947 Res |= SanitizerKind::Leak;
3948 Res |= SanitizerKind::Fuzzer;
3949 Res |= SanitizerKind::FuzzerNoLink;
3950 Res |= SanitizerKind::ObjCCast;
3951
3952 // Prior to 10.9, macOS shipped a version of the C++ standard library without
3953 // C++11 support. The same is true of iOS prior to version 5. These OS'es are
3954 // incompatible with -fsanitize=vptr.
3955 if (!(isTargetMacOSBased() && isMacosxVersionLT(10, 9)) &&
3957 Res |= SanitizerKind::Vptr;
3958
3959 if ((IsX86_64 || IsAArch64) &&
3962 Res |= SanitizerKind::Thread;
3963 }
3964
3965 if ((IsX86_64 || IsAArch64) && isTargetMacOSBased()) {
3966 Res |= SanitizerKind::Type;
3967 }
3968
3969 if (IsX86_64)
3970 Res |= SanitizerKind::NumericalStability;
3971
3972 return Res;
3973}
3974
3975void AppleMachO::printVerboseInfo(raw_ostream &OS) const {
3976 CudaInstallation->print(OS);
3977 RocmInstallation->print(OS);
3978}
#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:3255
static void addPgProfilingLinkArgs(const Darwin &D, const ArgList &Args, ArgStringList &CmdArgs)
Definition Darwin.cpp:3857
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:3881
static void addBundleLinkArgs(const Darwin &D, const ArgList &Args, ArgStringList &CmdArgs)
Definition Darwin.cpp:3846
static llvm::VersionTuple sizedDeallocMinVersion(llvm::Triple::OSType OS)
Definition Darwin.cpp:3295
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:3828
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:3712
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:1839
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:6830
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:7184
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:6819
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:2988
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:3975
llvm::SmallString< 128 > GetEffectiveSysroot(const llvm::opt::ArgList &DriverArgs) const
Definition Darwin.cpp:2766
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:2779
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:2879
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:2750
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:2828
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:3035
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:2740
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:3735
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:3639
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:3939
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:3387
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:3932
llvm::ExceptionHandling GetExceptionModel(const llvm::opt::ArgList &Args) const override
GetExceptionModel - Return the tool chain exception model.
Definition Darwin.cpp:3625
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:3312
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:3551
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:3495
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:3660
void addStartObjectFileArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const override
Definition Darwin.cpp:3905
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:3229
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:3646
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:3650
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:3338
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:3598
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:3619
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:3655
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:3213
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:3648
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:3067
bool UseDwarfDebugFlags() const override
UseDwarfDebugFlags - Embed the compile options to clang into the Dwarf compile unit information.
Definition Darwin.cpp:3613
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