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