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