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