Darwin.cpp revision 363496
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"
12#include "clang/Basic/AlignedAllocation.h"
13#include "clang/Basic/ObjCRuntime.h"
14#include "clang/Config/config.h"
15#include "clang/Driver/Compilation.h"
16#include "clang/Driver/Driver.h"
17#include "clang/Driver/DriverDiagnostic.h"
18#include "clang/Driver/Options.h"
19#include "clang/Driver/SanitizerArgs.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
29using namespace clang::driver;
30using namespace clang::driver::tools;
31using namespace clang::driver::toolchains;
32using namespace clang;
33using namespace llvm::opt;
34
35llvm::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
71void 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
86void darwin::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
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
153void darwin::MachOTool::anchor() {}
154
155void 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
168bool 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)
186static 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
202void 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] >= 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.
424static 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
432void darwin::Linker::ConstructJob(Compilation &C, const JobAction &JA,
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
475    SmallString<128> F;
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
665void darwin::Lipo::ConstructJob(Compilation &C, const JobAction &JA,
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
687void darwin::Dsymutil::ConstructJob(Compilation &C, const JobAction &JA,
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
707void darwin::VerifyDebug::ConstructJob(Compilation &C, const JobAction &JA,
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
730MachO::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.
739Darwin::Darwin(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
740    : MachO(D, Triple, Args), TargetInitialized(false),
741      CudaInstallation(D, Triple, Args) {}
742
743types::ID MachO::LookupTypeForExtension(StringRef Ext) const {
744  types::ID Ty = ToolChain::LookupTypeForExtension(Ext);
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
753bool MachO::HasNativeLLVMSupport() const { return true; }
754
755ToolChain::CXXStdlibType Darwin::GetDefaultCXXStdlibType() const {
756  // Default to use libc++ on OS X 10.9+ and iOS 7+.
757  if ((isTargetMacOS() && !isMacosxVersionLT(10, 9)) ||
758       (isTargetIOSBased() && !isIPhoneOSVersionLT(7, 0)) ||
759       isTargetWatchOSBased())
760    return ToolChain::CST_Libcxx;
761
762  return ToolChain::CST_Libstdcxx;
763}
764
765/// Darwin provides an ARC runtime starting in MacOS X 10.7 and iOS 5.0.
766ObjCRuntime Darwin::getDefaultObjCRuntime(bool isNonFragile) const {
767  if (isTargetWatchOSBased())
768    return ObjCRuntime(ObjCRuntime::WatchOS, TargetVersion);
769  if (isTargetIOSBased())
770    return ObjCRuntime(ObjCRuntime::iOS, TargetVersion);
771  if (isNonFragile)
772    return ObjCRuntime(ObjCRuntime::MacOSX, TargetVersion);
773  return ObjCRuntime(ObjCRuntime::FragileMacOSX, TargetVersion);
774}
775
776/// Darwin provides a blocks runtime starting in MacOS X 10.6 and iOS 3.2.
777bool Darwin::hasBlocksRuntime() const {
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
788void 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.
797static 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
814static 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
833StringRef MachO::getMachOArchName(const ArgList &Args) const {
834  switch (getTriple().getArch()) {
835  default:
836    return getDefaultUniversalArchName();
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
858Darwin::~Darwin() {}
859
860MachO::~MachO() {}
861
862std::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
886Tool *MachO::getTool(Action::ActionClass AC) const {
887  switch (AC) {
888  case Action::LipoJobClass:
889    if (!Lipo)
890      Lipo.reset(new tools::darwin::Lipo(*this));
891    return Lipo.get();
892  case Action::DsymutilJobClass:
893    if (!Dsymutil)
894      Dsymutil.reset(new tools::darwin::Dsymutil(*this));
895    return Dsymutil.get();
896  case Action::VerifyDebugInfoJobClass:
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
905Tool *MachO::buildLinker() const { return new tools::darwin::Linker(*this); }
906
907Tool *MachO::buildAssembler() const {
908  return new tools::darwin::Assembler(*this);
909}
910
911DarwinClang::DarwinClang(const Driver &D, const llvm::Triple &Triple,
912                         const ArgList &Args)
913    : Darwin(D, Triple, Args) {}
914
915void 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.
933static 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
942void 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.
977  if (isTargetWatchOSSimulator())
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
996unsigned DarwinClang::GetDefaultDwarfVersion() const {
997  // Default to use DWARF 2 on OS X 10.10 / iOS 8 and lower.
998  if ((isTargetMacOS() && isMacosxVersionLT(10, 11)) ||
999      (isTargetIOSBased() && isIPhoneOSVersionLT(9)))
1000    return 2;
1001  return 4;
1002}
1003
1004void 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
1055StringRef 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
1069StringRef 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
1081StringRef 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.
1099static 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.
1114static 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.
1125static 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
1132void Darwin::addProfileRTLibs(const ArgList &Args,
1133                              ArgStringList &CmdArgs) const {
1134  if (!needsProfileRT(Args)) return;
1135
1136  AddLinkRuntimeLib(Args, CmdArgs, "profile",
1137                    RuntimeLinkOptions(RLO_AlwaysLink | RLO_FirstLink));
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      addExportedSymbol(CmdArgs, "_reset_fn_list");
1150    } else {
1151      addExportedSymbol(CmdArgs, "___llvm_profile_filename");
1152      addExportedSymbol(CmdArgs, "___llvm_profile_raw_version");
1153    }
1154    addExportedSymbol(CmdArgs, "_lprofDirMode");
1155  }
1156
1157  // Align __llvm_prf_{cnts,data} sections to the maximum expected page
1158  // alignment. This allows profile counters to be mmap()'d to disk. Note that
1159  // it's not enough to just page-align __llvm_prf_cnts: the following section
1160  // must also be page-aligned so that its data is not clobbered by mmap().
1161  //
1162  // The section alignment is only needed when continuous profile sync is
1163  // enabled, but this is expected to be the default in Xcode. Specifying the
1164  // extra alignment also allows the same binary to be used with/without sync
1165  // enabled.
1166  if (!ForGCOV) {
1167    for (auto IPSK : {llvm::IPSK_cnts, llvm::IPSK_data}) {
1168      addSectalignToPage(
1169          Args, CmdArgs, "__DATA",
1170          llvm::getInstrProfSectionName(IPSK, llvm::Triple::MachO,
1171                                        /*AddSegmentInfo=*/false));
1172    }
1173  }
1174}
1175
1176void DarwinClang::AddLinkSanitizerLibArgs(const ArgList &Args,
1177                                          ArgStringList &CmdArgs,
1178                                          StringRef Sanitizer,
1179                                          bool Shared) const {
1180  auto RLO = RuntimeLinkOptions(RLO_AlwaysLink | (Shared ? RLO_AddRPath : 0U));
1181  AddLinkRuntimeLib(Args, CmdArgs, Sanitizer, RLO, Shared);
1182}
1183
1184ToolChain::RuntimeLibType DarwinClang::GetRuntimeLibType(
1185    const ArgList &Args) const {
1186  if (Arg* A = Args.getLastArg(options::OPT_rtlib_EQ)) {
1187    StringRef Value = A->getValue();
1188    if (Value != "compiler-rt")
1189      getDriver().Diag(clang::diag::err_drv_unsupported_rtlib_for_platform)
1190          << Value << "darwin";
1191  }
1192
1193  return ToolChain::RLT_CompilerRT;
1194}
1195
1196void DarwinClang::AddLinkRuntimeLibArgs(const ArgList &Args,
1197                                        ArgStringList &CmdArgs,
1198                                        bool ForceLinkBuiltinRT) const {
1199  // Call once to ensure diagnostic is printed if wrong value was specified
1200  GetRuntimeLibType(Args);
1201
1202  // Darwin doesn't support real static executables, don't link any runtime
1203  // libraries with -static.
1204  if (Args.hasArg(options::OPT_static) ||
1205      Args.hasArg(options::OPT_fapple_kext) ||
1206      Args.hasArg(options::OPT_mkernel)) {
1207    if (ForceLinkBuiltinRT)
1208      AddLinkRuntimeLib(Args, CmdArgs, "builtins");
1209    return;
1210  }
1211
1212  // Reject -static-libgcc for now, we can deal with this when and if someone
1213  // cares. This is useful in situations where someone wants to statically link
1214  // something like libstdc++, and needs its runtime support routines.
1215  if (const Arg *A = Args.getLastArg(options::OPT_static_libgcc)) {
1216    getDriver().Diag(diag::err_drv_unsupported_opt) << A->getAsString(Args);
1217    return;
1218  }
1219
1220  const SanitizerArgs &Sanitize = getSanitizerArgs();
1221  if (Sanitize.needsAsanRt())
1222    AddLinkSanitizerLibArgs(Args, CmdArgs, "asan");
1223  if (Sanitize.needsLsanRt())
1224    AddLinkSanitizerLibArgs(Args, CmdArgs, "lsan");
1225  if (Sanitize.needsUbsanRt())
1226    AddLinkSanitizerLibArgs(Args, CmdArgs,
1227                            Sanitize.requiresMinimalRuntime() ? "ubsan_minimal"
1228                                                              : "ubsan",
1229                            Sanitize.needsSharedRt());
1230  if (Sanitize.needsTsanRt())
1231    AddLinkSanitizerLibArgs(Args, CmdArgs, "tsan");
1232  if (Sanitize.needsFuzzer() && !Args.hasArg(options::OPT_dynamiclib)) {
1233    AddLinkSanitizerLibArgs(Args, CmdArgs, "fuzzer", /*shared=*/false);
1234
1235    // Libfuzzer is written in C++ and requires libcxx.
1236    AddCXXStdlibLibArgs(Args, CmdArgs);
1237  }
1238  if (Sanitize.needsStatsRt()) {
1239    AddLinkRuntimeLib(Args, CmdArgs, "stats_client", RLO_AlwaysLink);
1240    AddLinkSanitizerLibArgs(Args, CmdArgs, "stats");
1241  }
1242
1243  const XRayArgs &XRay = getXRayArgs();
1244  if (XRay.needsXRayRt()) {
1245    AddLinkRuntimeLib(Args, CmdArgs, "xray");
1246    AddLinkRuntimeLib(Args, CmdArgs, "xray-basic");
1247    AddLinkRuntimeLib(Args, CmdArgs, "xray-fdr");
1248  }
1249
1250  // Otherwise link libSystem, then the dynamic runtime library, and finally any
1251  // target specific static runtime library.
1252  CmdArgs.push_back("-lSystem");
1253
1254  // Select the dynamic runtime library and the target specific static library.
1255  if (isTargetIOSBased()) {
1256    // If we are compiling as iOS / simulator, don't attempt to link libgcc_s.1,
1257    // it never went into the SDK.
1258    // Linking against libgcc_s.1 isn't needed for iOS 5.0+
1259    if (isIPhoneOSVersionLT(5, 0) && !isTargetIOSSimulator() &&
1260        getTriple().getArch() != llvm::Triple::aarch64)
1261      CmdArgs.push_back("-lgcc_s.1");
1262  }
1263  AddLinkRuntimeLib(Args, CmdArgs, "builtins");
1264}
1265
1266/// Returns the most appropriate macOS target version for the current process.
1267///
1268/// If the macOS SDK version is the same or earlier than the system version,
1269/// then the SDK version is returned. Otherwise the system version is returned.
1270static std::string getSystemOrSDKMacOSVersion(StringRef MacOSSDKVersion) {
1271  unsigned Major, Minor, Micro;
1272  llvm::Triple SystemTriple(llvm::sys::getProcessTriple());
1273  if (!SystemTriple.isMacOSX())
1274    return MacOSSDKVersion;
1275  SystemTriple.getMacOSXVersion(Major, Minor, Micro);
1276  VersionTuple SystemVersion(Major, Minor, Micro);
1277  bool HadExtra;
1278  if (!Driver::GetReleaseVersion(MacOSSDKVersion, Major, Minor, Micro,
1279                                 HadExtra))
1280    return MacOSSDKVersion;
1281  VersionTuple SDKVersion(Major, Minor, Micro);
1282  if (SDKVersion > SystemVersion)
1283    return SystemVersion.getAsString();
1284  return MacOSSDKVersion;
1285}
1286
1287namespace {
1288
1289/// The Darwin OS that was selected or inferred from arguments / environment.
1290struct DarwinPlatform {
1291  enum SourceKind {
1292    /// The OS was specified using the -target argument.
1293    TargetArg,
1294    /// The OS was specified using the -m<os>-version-min argument.
1295    OSVersionArg,
1296    /// The OS was specified using the OS_DEPLOYMENT_TARGET environment.
1297    DeploymentTargetEnv,
1298    /// The OS was inferred from the SDK.
1299    InferredFromSDK,
1300    /// The OS was inferred from the -arch.
1301    InferredFromArch
1302  };
1303
1304  using DarwinPlatformKind = Darwin::DarwinPlatformKind;
1305  using DarwinEnvironmentKind = Darwin::DarwinEnvironmentKind;
1306
1307  DarwinPlatformKind getPlatform() const { return Platform; }
1308
1309  DarwinEnvironmentKind getEnvironment() const { return Environment; }
1310
1311  void setEnvironment(DarwinEnvironmentKind Kind) {
1312    Environment = Kind;
1313    InferSimulatorFromArch = false;
1314  }
1315
1316  StringRef getOSVersion() const {
1317    if (Kind == OSVersionArg)
1318      return Argument->getValue();
1319    return OSVersion;
1320  }
1321
1322  void setOSVersion(StringRef S) {
1323    assert(Kind == TargetArg && "Unexpected kind!");
1324    OSVersion = S;
1325  }
1326
1327  bool hasOSVersion() const { return HasOSVersion; }
1328
1329  /// Returns true if the target OS was explicitly specified.
1330  bool isExplicitlySpecified() const { return Kind <= DeploymentTargetEnv; }
1331
1332  /// Returns true if the simulator environment can be inferred from the arch.
1333  bool canInferSimulatorFromArch() const { return InferSimulatorFromArch; }
1334
1335  /// Adds the -m<os>-version-min argument to the compiler invocation.
1336  void addOSVersionMinArgument(DerivedArgList &Args, const OptTable &Opts) {
1337    if (Argument)
1338      return;
1339    assert(Kind != TargetArg && Kind != OSVersionArg && "Invalid kind");
1340    options::ID Opt;
1341    switch (Platform) {
1342    case DarwinPlatformKind::MacOS:
1343      Opt = options::OPT_mmacosx_version_min_EQ;
1344      break;
1345    case DarwinPlatformKind::IPhoneOS:
1346      Opt = options::OPT_miphoneos_version_min_EQ;
1347      break;
1348    case DarwinPlatformKind::TvOS:
1349      Opt = options::OPT_mtvos_version_min_EQ;
1350      break;
1351    case DarwinPlatformKind::WatchOS:
1352      Opt = options::OPT_mwatchos_version_min_EQ;
1353      break;
1354    }
1355    Argument = Args.MakeJoinedArg(nullptr, Opts.getOption(Opt), OSVersion);
1356    Args.append(Argument);
1357  }
1358
1359  /// Returns the OS version with the argument / environment variable that
1360  /// specified it.
1361  std::string getAsString(DerivedArgList &Args, const OptTable &Opts) {
1362    switch (Kind) {
1363    case TargetArg:
1364    case OSVersionArg:
1365    case InferredFromSDK:
1366    case InferredFromArch:
1367      assert(Argument && "OS version argument not yet inferred");
1368      return Argument->getAsString(Args);
1369    case DeploymentTargetEnv:
1370      return (llvm::Twine(EnvVarName) + "=" + OSVersion).str();
1371    }
1372    llvm_unreachable("Unsupported Darwin Source Kind");
1373  }
1374
1375  static DarwinPlatform createFromTarget(const llvm::Triple &TT,
1376                                         StringRef OSVersion, Arg *A) {
1377    DarwinPlatform Result(TargetArg, getPlatformFromOS(TT.getOS()), OSVersion,
1378                          A);
1379    switch (TT.getEnvironment()) {
1380    case llvm::Triple::Simulator:
1381      Result.Environment = DarwinEnvironmentKind::Simulator;
1382      break;
1383    default:
1384      break;
1385    }
1386    unsigned Major, Minor, Micro;
1387    TT.getOSVersion(Major, Minor, Micro);
1388    if (Major == 0)
1389      Result.HasOSVersion = false;
1390    return Result;
1391  }
1392  static DarwinPlatform createOSVersionArg(DarwinPlatformKind Platform,
1393                                           Arg *A) {
1394    return DarwinPlatform(OSVersionArg, Platform, A);
1395  }
1396  static DarwinPlatform createDeploymentTargetEnv(DarwinPlatformKind Platform,
1397                                                  StringRef EnvVarName,
1398                                                  StringRef Value) {
1399    DarwinPlatform Result(DeploymentTargetEnv, Platform, Value);
1400    Result.EnvVarName = EnvVarName;
1401    return Result;
1402  }
1403  static DarwinPlatform createFromSDK(DarwinPlatformKind Platform,
1404                                      StringRef Value,
1405                                      bool IsSimulator = false) {
1406    DarwinPlatform Result(InferredFromSDK, Platform, Value);
1407    if (IsSimulator)
1408      Result.Environment = DarwinEnvironmentKind::Simulator;
1409    Result.InferSimulatorFromArch = false;
1410    return Result;
1411  }
1412  static DarwinPlatform createFromArch(llvm::Triple::OSType OS,
1413                                       StringRef Value) {
1414    return DarwinPlatform(InferredFromArch, getPlatformFromOS(OS), Value);
1415  }
1416
1417  /// Constructs an inferred SDKInfo value based on the version inferred from
1418  /// the SDK path itself. Only works for values that were created by inferring
1419  /// the platform from the SDKPath.
1420  DarwinSDKInfo inferSDKInfo() {
1421    assert(Kind == InferredFromSDK && "can infer SDK info only");
1422    llvm::VersionTuple Version;
1423    bool IsValid = !Version.tryParse(OSVersion);
1424    (void)IsValid;
1425    assert(IsValid && "invalid SDK version");
1426    return DarwinSDKInfo(Version);
1427  }
1428
1429private:
1430  DarwinPlatform(SourceKind Kind, DarwinPlatformKind Platform, Arg *Argument)
1431      : Kind(Kind), Platform(Platform), Argument(Argument) {}
1432  DarwinPlatform(SourceKind Kind, DarwinPlatformKind Platform, StringRef Value,
1433                 Arg *Argument = nullptr)
1434      : Kind(Kind), Platform(Platform), OSVersion(Value), Argument(Argument) {}
1435
1436  static DarwinPlatformKind getPlatformFromOS(llvm::Triple::OSType OS) {
1437    switch (OS) {
1438    case llvm::Triple::Darwin:
1439    case llvm::Triple::MacOSX:
1440      return DarwinPlatformKind::MacOS;
1441    case llvm::Triple::IOS:
1442      return DarwinPlatformKind::IPhoneOS;
1443    case llvm::Triple::TvOS:
1444      return DarwinPlatformKind::TvOS;
1445    case llvm::Triple::WatchOS:
1446      return DarwinPlatformKind::WatchOS;
1447    default:
1448      llvm_unreachable("Unable to infer Darwin variant");
1449    }
1450  }
1451
1452  SourceKind Kind;
1453  DarwinPlatformKind Platform;
1454  DarwinEnvironmentKind Environment = DarwinEnvironmentKind::NativeEnvironment;
1455  std::string OSVersion;
1456  bool HasOSVersion = true, InferSimulatorFromArch = true;
1457  Arg *Argument;
1458  StringRef EnvVarName;
1459};
1460
1461/// Returns the deployment target that's specified using the -m<os>-version-min
1462/// argument.
1463Optional<DarwinPlatform>
1464getDeploymentTargetFromOSVersionArg(DerivedArgList &Args,
1465                                    const Driver &TheDriver) {
1466  Arg *OSXVersion = Args.getLastArg(options::OPT_mmacosx_version_min_EQ);
1467  Arg *iOSVersion = Args.getLastArg(options::OPT_miphoneos_version_min_EQ,
1468                                    options::OPT_mios_simulator_version_min_EQ);
1469  Arg *TvOSVersion =
1470      Args.getLastArg(options::OPT_mtvos_version_min_EQ,
1471                      options::OPT_mtvos_simulator_version_min_EQ);
1472  Arg *WatchOSVersion =
1473      Args.getLastArg(options::OPT_mwatchos_version_min_EQ,
1474                      options::OPT_mwatchos_simulator_version_min_EQ);
1475  if (OSXVersion) {
1476    if (iOSVersion || TvOSVersion || WatchOSVersion) {
1477      TheDriver.Diag(diag::err_drv_argument_not_allowed_with)
1478          << OSXVersion->getAsString(Args)
1479          << (iOSVersion ? iOSVersion
1480                         : TvOSVersion ? TvOSVersion : WatchOSVersion)
1481                 ->getAsString(Args);
1482    }
1483    return DarwinPlatform::createOSVersionArg(Darwin::MacOS, OSXVersion);
1484  } else if (iOSVersion) {
1485    if (TvOSVersion || WatchOSVersion) {
1486      TheDriver.Diag(diag::err_drv_argument_not_allowed_with)
1487          << iOSVersion->getAsString(Args)
1488          << (TvOSVersion ? TvOSVersion : WatchOSVersion)->getAsString(Args);
1489    }
1490    return DarwinPlatform::createOSVersionArg(Darwin::IPhoneOS, iOSVersion);
1491  } else if (TvOSVersion) {
1492    if (WatchOSVersion) {
1493      TheDriver.Diag(diag::err_drv_argument_not_allowed_with)
1494          << TvOSVersion->getAsString(Args)
1495          << WatchOSVersion->getAsString(Args);
1496    }
1497    return DarwinPlatform::createOSVersionArg(Darwin::TvOS, TvOSVersion);
1498  } else if (WatchOSVersion)
1499    return DarwinPlatform::createOSVersionArg(Darwin::WatchOS, WatchOSVersion);
1500  return None;
1501}
1502
1503/// Returns the deployment target that's specified using the
1504/// OS_DEPLOYMENT_TARGET environment variable.
1505Optional<DarwinPlatform>
1506getDeploymentTargetFromEnvironmentVariables(const Driver &TheDriver,
1507                                            const llvm::Triple &Triple) {
1508  std::string Targets[Darwin::LastDarwinPlatform + 1];
1509  const char *EnvVars[] = {
1510      "MACOSX_DEPLOYMENT_TARGET",
1511      "IPHONEOS_DEPLOYMENT_TARGET",
1512      "TVOS_DEPLOYMENT_TARGET",
1513      "WATCHOS_DEPLOYMENT_TARGET",
1514  };
1515  static_assert(llvm::array_lengthof(EnvVars) == Darwin::LastDarwinPlatform + 1,
1516                "Missing platform");
1517  for (const auto &I : llvm::enumerate(llvm::makeArrayRef(EnvVars))) {
1518    if (char *Env = ::getenv(I.value()))
1519      Targets[I.index()] = Env;
1520  }
1521
1522  // Allow conflicts among OSX and iOS for historical reasons, but choose the
1523  // default platform.
1524  if (!Targets[Darwin::MacOS].empty() &&
1525      (!Targets[Darwin::IPhoneOS].empty() ||
1526       !Targets[Darwin::WatchOS].empty() || !Targets[Darwin::TvOS].empty())) {
1527    if (Triple.getArch() == llvm::Triple::arm ||
1528        Triple.getArch() == llvm::Triple::aarch64 ||
1529        Triple.getArch() == llvm::Triple::thumb)
1530      Targets[Darwin::MacOS] = "";
1531    else
1532      Targets[Darwin::IPhoneOS] = Targets[Darwin::WatchOS] =
1533          Targets[Darwin::TvOS] = "";
1534  } else {
1535    // Don't allow conflicts in any other platform.
1536    unsigned FirstTarget = llvm::array_lengthof(Targets);
1537    for (unsigned I = 0; I != llvm::array_lengthof(Targets); ++I) {
1538      if (Targets[I].empty())
1539        continue;
1540      if (FirstTarget == llvm::array_lengthof(Targets))
1541        FirstTarget = I;
1542      else
1543        TheDriver.Diag(diag::err_drv_conflicting_deployment_targets)
1544            << Targets[FirstTarget] << Targets[I];
1545    }
1546  }
1547
1548  for (const auto &Target : llvm::enumerate(llvm::makeArrayRef(Targets))) {
1549    if (!Target.value().empty())
1550      return DarwinPlatform::createDeploymentTargetEnv(
1551          (Darwin::DarwinPlatformKind)Target.index(), EnvVars[Target.index()],
1552          Target.value());
1553  }
1554  return None;
1555}
1556
1557/// Tries to infer the deployment target from the SDK specified by -isysroot
1558/// (or SDKROOT). Uses the version specified in the SDKSettings.json file if
1559/// it's available.
1560Optional<DarwinPlatform>
1561inferDeploymentTargetFromSDK(DerivedArgList &Args,
1562                             const Optional<DarwinSDKInfo> &SDKInfo) {
1563  const Arg *A = Args.getLastArg(options::OPT_isysroot);
1564  if (!A)
1565    return None;
1566  StringRef isysroot = A->getValue();
1567  StringRef SDK = Darwin::getSDKName(isysroot);
1568  if (!SDK.size())
1569    return None;
1570
1571  std::string Version;
1572  if (SDKInfo) {
1573    // Get the version from the SDKSettings.json if it's available.
1574    Version = SDKInfo->getVersion().getAsString();
1575  } else {
1576    // Slice the version number out.
1577    // Version number is between the first and the last number.
1578    size_t StartVer = SDK.find_first_of("0123456789");
1579    size_t EndVer = SDK.find_last_of("0123456789");
1580    if (StartVer != StringRef::npos && EndVer > StartVer)
1581      Version = SDK.slice(StartVer, EndVer + 1);
1582  }
1583  if (Version.empty())
1584    return None;
1585
1586  if (SDK.startswith("iPhoneOS") || SDK.startswith("iPhoneSimulator"))
1587    return DarwinPlatform::createFromSDK(
1588        Darwin::IPhoneOS, Version,
1589        /*IsSimulator=*/SDK.startswith("iPhoneSimulator"));
1590  else if (SDK.startswith("MacOSX"))
1591    return DarwinPlatform::createFromSDK(Darwin::MacOS,
1592                                         getSystemOrSDKMacOSVersion(Version));
1593  else if (SDK.startswith("WatchOS") || SDK.startswith("WatchSimulator"))
1594    return DarwinPlatform::createFromSDK(
1595        Darwin::WatchOS, Version,
1596        /*IsSimulator=*/SDK.startswith("WatchSimulator"));
1597  else if (SDK.startswith("AppleTVOS") || SDK.startswith("AppleTVSimulator"))
1598    return DarwinPlatform::createFromSDK(
1599        Darwin::TvOS, Version,
1600        /*IsSimulator=*/SDK.startswith("AppleTVSimulator"));
1601  return None;
1602}
1603
1604std::string getOSVersion(llvm::Triple::OSType OS, const llvm::Triple &Triple,
1605                         const Driver &TheDriver) {
1606  unsigned Major, Minor, Micro;
1607  llvm::Triple SystemTriple(llvm::sys::getProcessTriple());
1608  switch (OS) {
1609  case llvm::Triple::Darwin:
1610  case llvm::Triple::MacOSX:
1611    // If there is no version specified on triple, and both host and target are
1612    // macos, use the host triple to infer OS version.
1613    if (Triple.isMacOSX() && SystemTriple.isMacOSX() &&
1614        !Triple.getOSMajorVersion())
1615      SystemTriple.getMacOSXVersion(Major, Minor, Micro);
1616    else if (!Triple.getMacOSXVersion(Major, Minor, Micro))
1617      TheDriver.Diag(diag::err_drv_invalid_darwin_version)
1618          << Triple.getOSName();
1619    break;
1620  case llvm::Triple::IOS:
1621    Triple.getiOSVersion(Major, Minor, Micro);
1622    break;
1623  case llvm::Triple::TvOS:
1624    Triple.getOSVersion(Major, Minor, Micro);
1625    break;
1626  case llvm::Triple::WatchOS:
1627    Triple.getWatchOSVersion(Major, Minor, Micro);
1628    break;
1629  default:
1630    llvm_unreachable("Unexpected OS type");
1631    break;
1632  }
1633
1634  std::string OSVersion;
1635  llvm::raw_string_ostream(OSVersion) << Major << '.' << Minor << '.' << Micro;
1636  return OSVersion;
1637}
1638
1639/// Tries to infer the target OS from the -arch.
1640Optional<DarwinPlatform>
1641inferDeploymentTargetFromArch(DerivedArgList &Args, const Darwin &Toolchain,
1642                              const llvm::Triple &Triple,
1643                              const Driver &TheDriver) {
1644  llvm::Triple::OSType OSTy = llvm::Triple::UnknownOS;
1645
1646  StringRef MachOArchName = Toolchain.getMachOArchName(Args);
1647  if (MachOArchName == "armv7" || MachOArchName == "armv7s" ||
1648      MachOArchName == "arm64")
1649    OSTy = llvm::Triple::IOS;
1650  else if (MachOArchName == "armv7k" || MachOArchName == "arm64_32")
1651    OSTy = llvm::Triple::WatchOS;
1652  else if (MachOArchName != "armv6m" && MachOArchName != "armv7m" &&
1653           MachOArchName != "armv7em")
1654    OSTy = llvm::Triple::MacOSX;
1655
1656  if (OSTy == llvm::Triple::UnknownOS)
1657    return None;
1658  return DarwinPlatform::createFromArch(OSTy,
1659                                        getOSVersion(OSTy, Triple, TheDriver));
1660}
1661
1662/// Returns the deployment target that's specified using the -target option.
1663Optional<DarwinPlatform> getDeploymentTargetFromTargetArg(
1664    DerivedArgList &Args, const llvm::Triple &Triple, const Driver &TheDriver) {
1665  if (!Args.hasArg(options::OPT_target))
1666    return None;
1667  if (Triple.getOS() == llvm::Triple::Darwin ||
1668      Triple.getOS() == llvm::Triple::UnknownOS)
1669    return None;
1670  std::string OSVersion = getOSVersion(Triple.getOS(), Triple, TheDriver);
1671  return DarwinPlatform::createFromTarget(Triple, OSVersion,
1672                                          Args.getLastArg(options::OPT_target));
1673}
1674
1675Optional<DarwinSDKInfo> parseSDKSettings(llvm::vfs::FileSystem &VFS,
1676                                         const ArgList &Args,
1677                                         const Driver &TheDriver) {
1678  const Arg *A = Args.getLastArg(options::OPT_isysroot);
1679  if (!A)
1680    return None;
1681  StringRef isysroot = A->getValue();
1682  auto SDKInfoOrErr = driver::parseDarwinSDKInfo(VFS, isysroot);
1683  if (!SDKInfoOrErr) {
1684    llvm::consumeError(SDKInfoOrErr.takeError());
1685    TheDriver.Diag(diag::warn_drv_darwin_sdk_invalid_settings);
1686    return None;
1687  }
1688  return *SDKInfoOrErr;
1689}
1690
1691} // namespace
1692
1693void Darwin::AddDeploymentTarget(DerivedArgList &Args) const {
1694  const OptTable &Opts = getDriver().getOpts();
1695
1696  // Support allowing the SDKROOT environment variable used by xcrun and other
1697  // Xcode tools to define the default sysroot, by making it the default for
1698  // isysroot.
1699  if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
1700    // Warn if the path does not exist.
1701    if (!getVFS().exists(A->getValue()))
1702      getDriver().Diag(clang::diag::warn_missing_sysroot) << A->getValue();
1703  } else {
1704    if (char *env = ::getenv("SDKROOT")) {
1705      // We only use this value as the default if it is an absolute path,
1706      // exists, and it is not the root path.
1707      if (llvm::sys::path::is_absolute(env) && getVFS().exists(env) &&
1708          StringRef(env) != "/") {
1709        Args.append(Args.MakeSeparateArg(
1710            nullptr, Opts.getOption(options::OPT_isysroot), env));
1711      }
1712    }
1713  }
1714
1715  // Read the SDKSettings.json file for more information, like the SDK version
1716  // that we can pass down to the compiler.
1717  SDKInfo = parseSDKSettings(getVFS(), Args, getDriver());
1718
1719  // The OS and the version can be specified using the -target argument.
1720  Optional<DarwinPlatform> OSTarget =
1721      getDeploymentTargetFromTargetArg(Args, getTriple(), getDriver());
1722  if (OSTarget) {
1723    Optional<DarwinPlatform> OSVersionArgTarget =
1724        getDeploymentTargetFromOSVersionArg(Args, getDriver());
1725    if (OSVersionArgTarget) {
1726      unsigned TargetMajor, TargetMinor, TargetMicro;
1727      bool TargetExtra;
1728      unsigned ArgMajor, ArgMinor, ArgMicro;
1729      bool ArgExtra;
1730      if (OSTarget->getPlatform() != OSVersionArgTarget->getPlatform() ||
1731          (Driver::GetReleaseVersion(OSTarget->getOSVersion(), TargetMajor,
1732                                     TargetMinor, TargetMicro, TargetExtra) &&
1733           Driver::GetReleaseVersion(OSVersionArgTarget->getOSVersion(),
1734                                     ArgMajor, ArgMinor, ArgMicro, ArgExtra) &&
1735           (VersionTuple(TargetMajor, TargetMinor, TargetMicro) !=
1736                VersionTuple(ArgMajor, ArgMinor, ArgMicro) ||
1737            TargetExtra != ArgExtra))) {
1738        // Select the OS version from the -m<os>-version-min argument when
1739        // the -target does not include an OS version.
1740        if (OSTarget->getPlatform() == OSVersionArgTarget->getPlatform() &&
1741            !OSTarget->hasOSVersion()) {
1742          OSTarget->setOSVersion(OSVersionArgTarget->getOSVersion());
1743        } else {
1744          // Warn about -m<os>-version-min that doesn't match the OS version
1745          // that's specified in the target.
1746          std::string OSVersionArg =
1747              OSVersionArgTarget->getAsString(Args, Opts);
1748          std::string TargetArg = OSTarget->getAsString(Args, Opts);
1749          getDriver().Diag(clang::diag::warn_drv_overriding_flag_option)
1750              << OSVersionArg << TargetArg;
1751        }
1752      }
1753    }
1754  } else {
1755    // The OS target can be specified using the -m<os>version-min argument.
1756    OSTarget = getDeploymentTargetFromOSVersionArg(Args, getDriver());
1757    // If no deployment target was specified on the command line, check for
1758    // environment defines.
1759    if (!OSTarget) {
1760      OSTarget =
1761          getDeploymentTargetFromEnvironmentVariables(getDriver(), getTriple());
1762      if (OSTarget) {
1763        // Don't infer simulator from the arch when the SDK is also specified.
1764        Optional<DarwinPlatform> SDKTarget =
1765            inferDeploymentTargetFromSDK(Args, SDKInfo);
1766        if (SDKTarget)
1767          OSTarget->setEnvironment(SDKTarget->getEnvironment());
1768      }
1769    }
1770    // If there is no command-line argument to specify the Target version and
1771    // no environment variable defined, see if we can set the default based
1772    // on -isysroot using SDKSettings.json if it exists.
1773    if (!OSTarget) {
1774      OSTarget = inferDeploymentTargetFromSDK(Args, SDKInfo);
1775      /// If the target was successfully constructed from the SDK path, try to
1776      /// infer the SDK info if the SDK doesn't have it.
1777      if (OSTarget && !SDKInfo)
1778        SDKInfo = OSTarget->inferSDKInfo();
1779    }
1780    // If no OS targets have been specified, try to guess platform from -target
1781    // or arch name and compute the version from the triple.
1782    if (!OSTarget)
1783      OSTarget =
1784          inferDeploymentTargetFromArch(Args, *this, getTriple(), getDriver());
1785  }
1786
1787  assert(OSTarget && "Unable to infer Darwin variant");
1788  OSTarget->addOSVersionMinArgument(Args, Opts);
1789  DarwinPlatformKind Platform = OSTarget->getPlatform();
1790
1791  unsigned Major, Minor, Micro;
1792  bool HadExtra;
1793  // Set the tool chain target information.
1794  if (Platform == MacOS) {
1795    if (!Driver::GetReleaseVersion(OSTarget->getOSVersion(), Major, Minor,
1796                                   Micro, HadExtra) ||
1797        HadExtra || Major != 10 || Minor >= 100 || Micro >= 100)
1798      getDriver().Diag(diag::err_drv_invalid_version_number)
1799          << OSTarget->getAsString(Args, Opts);
1800  } else if (Platform == IPhoneOS) {
1801    if (!Driver::GetReleaseVersion(OSTarget->getOSVersion(), Major, Minor,
1802                                   Micro, HadExtra) ||
1803        HadExtra || Major >= 100 || Minor >= 100 || Micro >= 100)
1804      getDriver().Diag(diag::err_drv_invalid_version_number)
1805          << OSTarget->getAsString(Args, Opts);
1806    ;
1807    // For 32-bit targets, the deployment target for iOS has to be earlier than
1808    // iOS 11.
1809    if (getTriple().isArch32Bit() && Major >= 11) {
1810      // If the deployment target is explicitly specified, print a diagnostic.
1811      if (OSTarget->isExplicitlySpecified()) {
1812        getDriver().Diag(diag::warn_invalid_ios_deployment_target)
1813            << OSTarget->getAsString(Args, Opts);
1814        // Otherwise, set it to 10.99.99.
1815      } else {
1816        Major = 10;
1817        Minor = 99;
1818        Micro = 99;
1819      }
1820    }
1821  } else if (Platform == TvOS) {
1822    if (!Driver::GetReleaseVersion(OSTarget->getOSVersion(), Major, Minor,
1823                                   Micro, HadExtra) ||
1824        HadExtra || Major >= 100 || Minor >= 100 || Micro >= 100)
1825      getDriver().Diag(diag::err_drv_invalid_version_number)
1826          << OSTarget->getAsString(Args, Opts);
1827  } else if (Platform == WatchOS) {
1828    if (!Driver::GetReleaseVersion(OSTarget->getOSVersion(), Major, Minor,
1829                                   Micro, HadExtra) ||
1830        HadExtra || Major >= 10 || Minor >= 100 || Micro >= 100)
1831      getDriver().Diag(diag::err_drv_invalid_version_number)
1832          << OSTarget->getAsString(Args, Opts);
1833  } else
1834    llvm_unreachable("unknown kind of Darwin platform");
1835
1836  DarwinEnvironmentKind Environment = OSTarget->getEnvironment();
1837  // Recognize iOS targets with an x86 architecture as the iOS simulator.
1838  if (Environment == NativeEnvironment && Platform != MacOS &&
1839      OSTarget->canInferSimulatorFromArch() && getTriple().isX86())
1840    Environment = Simulator;
1841
1842  setTarget(Platform, Environment, Major, Minor, Micro);
1843
1844  if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
1845    StringRef SDK = getSDKName(A->getValue());
1846    if (SDK.size() > 0) {
1847      size_t StartVer = SDK.find_first_of("0123456789");
1848      StringRef SDKName = SDK.slice(0, StartVer);
1849      if (!SDKName.startswith(getPlatformFamily()))
1850        getDriver().Diag(diag::warn_incompatible_sysroot)
1851            << SDKName << getPlatformFamily();
1852    }
1853  }
1854}
1855
1856// Returns the effective header sysroot path to use. This comes either from
1857// -isysroot or --sysroot.
1858llvm::StringRef DarwinClang::GetHeaderSysroot(const llvm::opt::ArgList &DriverArgs) const {
1859  if(DriverArgs.hasArg(options::OPT_isysroot))
1860    return DriverArgs.getLastArgValue(options::OPT_isysroot);
1861  if (!getDriver().SysRoot.empty())
1862    return getDriver().SysRoot;
1863  return "/";
1864}
1865
1866void DarwinClang::AddClangSystemIncludeArgs(const llvm::opt::ArgList &DriverArgs,
1867                                            llvm::opt::ArgStringList &CC1Args) const {
1868  const Driver &D = getDriver();
1869
1870  llvm::StringRef Sysroot = GetHeaderSysroot(DriverArgs);
1871
1872  bool NoStdInc = DriverArgs.hasArg(options::OPT_nostdinc);
1873  bool NoStdlibInc = DriverArgs.hasArg(options::OPT_nostdlibinc);
1874  bool NoBuiltinInc = DriverArgs.hasArg(options::OPT_nobuiltininc);
1875
1876  // Add <sysroot>/usr/local/include
1877  if (!NoStdInc && !NoStdlibInc) {
1878      SmallString<128> P(Sysroot);
1879      llvm::sys::path::append(P, "usr", "local", "include");
1880      addSystemInclude(DriverArgs, CC1Args, P);
1881  }
1882
1883  // Add the Clang builtin headers (<resource>/include)
1884  if (!NoStdInc && !NoBuiltinInc) {
1885    SmallString<128> P(D.ResourceDir);
1886    llvm::sys::path::append(P, "include");
1887    addSystemInclude(DriverArgs, CC1Args, P);
1888  }
1889
1890  if (NoStdInc || NoStdlibInc)
1891    return;
1892
1893  // Check for configure-time C include directories.
1894  llvm::StringRef CIncludeDirs(C_INCLUDE_DIRS);
1895  if (!CIncludeDirs.empty()) {
1896    llvm::SmallVector<llvm::StringRef, 5> dirs;
1897    CIncludeDirs.split(dirs, ":");
1898    for (llvm::StringRef dir : dirs) {
1899      llvm::StringRef Prefix =
1900          llvm::sys::path::is_absolute(dir) ? llvm::StringRef(Sysroot) : "";
1901      addExternCSystemInclude(DriverArgs, CC1Args, Prefix + dir);
1902    }
1903  } else {
1904    // Otherwise, add <sysroot>/usr/include.
1905    SmallString<128> P(Sysroot);
1906    llvm::sys::path::append(P, "usr", "include");
1907    addExternCSystemInclude(DriverArgs, CC1Args, P.str());
1908  }
1909}
1910
1911bool DarwinClang::AddGnuCPlusPlusIncludePaths(const llvm::opt::ArgList &DriverArgs,
1912                                              llvm::opt::ArgStringList &CC1Args,
1913                                              llvm::SmallString<128> Base,
1914                                              llvm::StringRef Version,
1915                                              llvm::StringRef ArchDir,
1916                                              llvm::StringRef BitDir) const {
1917  llvm::sys::path::append(Base, Version);
1918
1919  // Add the base dir
1920  addSystemInclude(DriverArgs, CC1Args, Base);
1921
1922  // Add the multilib dirs
1923  {
1924    llvm::SmallString<128> P = Base;
1925    if (!ArchDir.empty())
1926      llvm::sys::path::append(P, ArchDir);
1927    if (!BitDir.empty())
1928      llvm::sys::path::append(P, BitDir);
1929    addSystemInclude(DriverArgs, CC1Args, P);
1930  }
1931
1932  // Add the backward dir
1933  {
1934    llvm::SmallString<128> P = Base;
1935    llvm::sys::path::append(P, "backward");
1936    addSystemInclude(DriverArgs, CC1Args, P);
1937  }
1938
1939  return getVFS().exists(Base);
1940}
1941
1942void DarwinClang::AddClangCXXStdlibIncludeArgs(
1943    const llvm::opt::ArgList &DriverArgs,
1944    llvm::opt::ArgStringList &CC1Args) const {
1945  // The implementation from a base class will pass through the -stdlib to
1946  // CC1Args.
1947  // FIXME: this should not be necessary, remove usages in the frontend
1948  //        (e.g. HeaderSearchOptions::UseLibcxx) and don't pipe -stdlib.
1949  //        Also check whether this is used for setting library search paths.
1950  ToolChain::AddClangCXXStdlibIncludeArgs(DriverArgs, CC1Args);
1951
1952  if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
1953      DriverArgs.hasArg(options::OPT_nostdincxx))
1954    return;
1955
1956  llvm::StringRef Sysroot = GetHeaderSysroot(DriverArgs);
1957
1958  switch (GetCXXStdlibType(DriverArgs)) {
1959  case ToolChain::CST_Libcxx: {
1960    // On Darwin, libc++ is installed alongside the compiler in
1961    // include/c++/v1, so get from '<install>/bin' to '<install>/include/c++/v1'.
1962    {
1963      llvm::SmallString<128> P = llvm::StringRef(getDriver().getInstalledDir());
1964      // Note that P can be relative, so we have to '..' and not parent_path.
1965      llvm::sys::path::append(P, "..", "include", "c++", "v1");
1966      addSystemInclude(DriverArgs, CC1Args, P);
1967    }
1968    // Also add <sysroot>/usr/include/c++/v1 unless -nostdinc is used,
1969    // to match the legacy behavior in CC1.
1970    if (!DriverArgs.hasArg(options::OPT_nostdinc)) {
1971      llvm::SmallString<128> P = Sysroot;
1972      llvm::sys::path::append(P, "usr", "include", "c++", "v1");
1973      addSystemInclude(DriverArgs, CC1Args, P);
1974    }
1975    break;
1976  }
1977
1978  case ToolChain::CST_Libstdcxx:
1979    llvm::SmallString<128> UsrIncludeCxx = Sysroot;
1980    llvm::sys::path::append(UsrIncludeCxx, "usr", "include", "c++");
1981
1982    llvm::Triple::ArchType arch = getTriple().getArch();
1983    bool IsBaseFound = true;
1984    switch (arch) {
1985    default: break;
1986
1987    case llvm::Triple::ppc:
1988    case llvm::Triple::ppc64:
1989      IsBaseFound = AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, UsrIncludeCxx,
1990                                                "4.2.1",
1991                                                "powerpc-apple-darwin10",
1992                                                arch == llvm::Triple::ppc64 ? "ppc64" : "");
1993      IsBaseFound |= AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, UsrIncludeCxx,
1994                                                "4.0.0", "powerpc-apple-darwin10",
1995                                                 arch == llvm::Triple::ppc64 ? "ppc64" : "");
1996      break;
1997
1998    case llvm::Triple::x86:
1999    case llvm::Triple::x86_64:
2000      IsBaseFound = AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, UsrIncludeCxx,
2001                                                "4.2.1",
2002                                                "i686-apple-darwin10",
2003                                                arch == llvm::Triple::x86_64 ? "x86_64" : "");
2004      IsBaseFound |= AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, UsrIncludeCxx,
2005                                                "4.0.0", "i686-apple-darwin8",
2006                                                 "");
2007      break;
2008
2009    case llvm::Triple::arm:
2010    case llvm::Triple::thumb:
2011      IsBaseFound = AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, UsrIncludeCxx,
2012                                                "4.2.1",
2013                                                "arm-apple-darwin10",
2014                                                "v7");
2015      IsBaseFound |= AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, UsrIncludeCxx,
2016                                                "4.2.1",
2017                                                "arm-apple-darwin10",
2018                                                 "v6");
2019      break;
2020
2021    case llvm::Triple::aarch64:
2022      IsBaseFound = AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, UsrIncludeCxx,
2023                                                "4.2.1",
2024                                                "arm64-apple-darwin10",
2025                                                "");
2026      break;
2027    }
2028
2029    if (!IsBaseFound) {
2030      getDriver().Diag(diag::warn_drv_libstdcxx_not_found);
2031    }
2032
2033    break;
2034  }
2035}
2036void DarwinClang::AddCXXStdlibLibArgs(const ArgList &Args,
2037                                      ArgStringList &CmdArgs) const {
2038  CXXStdlibType Type = GetCXXStdlibType(Args);
2039
2040  switch (Type) {
2041  case ToolChain::CST_Libcxx:
2042    CmdArgs.push_back("-lc++");
2043    break;
2044
2045  case ToolChain::CST_Libstdcxx:
2046    // Unfortunately, -lstdc++ doesn't always exist in the standard search path;
2047    // it was previously found in the gcc lib dir. However, for all the Darwin
2048    // platforms we care about it was -lstdc++.6, so we search for that
2049    // explicitly if we can't see an obvious -lstdc++ candidate.
2050
2051    // Check in the sysroot first.
2052    if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
2053      SmallString<128> P(A->getValue());
2054      llvm::sys::path::append(P, "usr", "lib", "libstdc++.dylib");
2055
2056      if (!getVFS().exists(P)) {
2057        llvm::sys::path::remove_filename(P);
2058        llvm::sys::path::append(P, "libstdc++.6.dylib");
2059        if (getVFS().exists(P)) {
2060          CmdArgs.push_back(Args.MakeArgString(P));
2061          return;
2062        }
2063      }
2064    }
2065
2066    // Otherwise, look in the root.
2067    // FIXME: This should be removed someday when we don't have to care about
2068    // 10.6 and earlier, where /usr/lib/libstdc++.dylib does not exist.
2069    if (!getVFS().exists("/usr/lib/libstdc++.dylib") &&
2070        getVFS().exists("/usr/lib/libstdc++.6.dylib")) {
2071      CmdArgs.push_back("/usr/lib/libstdc++.6.dylib");
2072      return;
2073    }
2074
2075    // Otherwise, let the linker search.
2076    CmdArgs.push_back("-lstdc++");
2077    break;
2078  }
2079}
2080
2081void DarwinClang::AddCCKextLibArgs(const ArgList &Args,
2082                                   ArgStringList &CmdArgs) const {
2083  // For Darwin platforms, use the compiler-rt-based support library
2084  // instead of the gcc-provided one (which is also incidentally
2085  // only present in the gcc lib dir, which makes it hard to find).
2086
2087  SmallString<128> P(getDriver().ResourceDir);
2088  llvm::sys::path::append(P, "lib", "darwin");
2089
2090  // Use the newer cc_kext for iOS ARM after 6.0.
2091  if (isTargetWatchOS()) {
2092    llvm::sys::path::append(P, "libclang_rt.cc_kext_watchos.a");
2093  } else if (isTargetTvOS()) {
2094    llvm::sys::path::append(P, "libclang_rt.cc_kext_tvos.a");
2095  } else if (isTargetIPhoneOS()) {
2096    llvm::sys::path::append(P, "libclang_rt.cc_kext_ios.a");
2097  } else {
2098    llvm::sys::path::append(P, "libclang_rt.cc_kext.a");
2099  }
2100
2101  // For now, allow missing resource libraries to support developers who may
2102  // not have compiler-rt checked out or integrated into their build.
2103  if (getVFS().exists(P))
2104    CmdArgs.push_back(Args.MakeArgString(P));
2105}
2106
2107DerivedArgList *MachO::TranslateArgs(const DerivedArgList &Args,
2108                                     StringRef BoundArch,
2109                                     Action::OffloadKind) const {
2110  DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
2111  const OptTable &Opts = getDriver().getOpts();
2112
2113  // FIXME: We really want to get out of the tool chain level argument
2114  // translation business, as it makes the driver functionality much
2115  // more opaque. For now, we follow gcc closely solely for the
2116  // purpose of easily achieving feature parity & testability. Once we
2117  // have something that works, we should reevaluate each translation
2118  // and try to push it down into tool specific logic.
2119
2120  for (Arg *A : Args) {
2121    if (A->getOption().matches(options::OPT_Xarch__)) {
2122      // Skip this argument unless the architecture matches either the toolchain
2123      // triple arch, or the arch being bound.
2124      llvm::Triple::ArchType XarchArch =
2125          tools::darwin::getArchTypeForMachOArchName(A->getValue(0));
2126      if (!(XarchArch == getArch() ||
2127            (!BoundArch.empty() &&
2128             XarchArch ==
2129                 tools::darwin::getArchTypeForMachOArchName(BoundArch))))
2130        continue;
2131
2132      Arg *OriginalArg = A;
2133      unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
2134      unsigned Prev = Index;
2135      std::unique_ptr<Arg> XarchArg(Opts.ParseOneArg(Args, Index));
2136
2137      // If the argument parsing failed or more than one argument was
2138      // consumed, the -Xarch_ argument's parameter tried to consume
2139      // extra arguments. Emit an error and ignore.
2140      //
2141      // We also want to disallow any options which would alter the
2142      // driver behavior; that isn't going to work in our model. We
2143      // use isDriverOption() as an approximation, although things
2144      // like -O4 are going to slip through.
2145      if (!XarchArg || Index > Prev + 1) {
2146        getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args)
2147            << A->getAsString(Args);
2148        continue;
2149      } else if (XarchArg->getOption().hasFlag(options::DriverOption)) {
2150        getDriver().Diag(diag::err_drv_invalid_Xarch_argument_isdriver)
2151            << A->getAsString(Args);
2152        continue;
2153      }
2154
2155      XarchArg->setBaseArg(A);
2156
2157      A = XarchArg.release();
2158      DAL->AddSynthesizedArg(A);
2159
2160      // Linker input arguments require custom handling. The problem is that we
2161      // have already constructed the phase actions, so we can not treat them as
2162      // "input arguments".
2163      if (A->getOption().hasFlag(options::LinkerInput)) {
2164        // Convert the argument into individual Zlinker_input_args.
2165        for (const char *Value : A->getValues()) {
2166          DAL->AddSeparateArg(
2167              OriginalArg, Opts.getOption(options::OPT_Zlinker_input), Value);
2168        }
2169        continue;
2170      }
2171    }
2172
2173    // Sob. These is strictly gcc compatible for the time being. Apple
2174    // gcc translates options twice, which means that self-expanding
2175    // options add duplicates.
2176    switch ((options::ID)A->getOption().getID()) {
2177    default:
2178      DAL->append(A);
2179      break;
2180
2181    case options::OPT_mkernel:
2182    case options::OPT_fapple_kext:
2183      DAL->append(A);
2184      DAL->AddFlagArg(A, Opts.getOption(options::OPT_static));
2185      break;
2186
2187    case options::OPT_dependency_file:
2188      DAL->AddSeparateArg(A, Opts.getOption(options::OPT_MF), A->getValue());
2189      break;
2190
2191    case options::OPT_gfull:
2192      DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
2193      DAL->AddFlagArg(
2194          A, Opts.getOption(options::OPT_fno_eliminate_unused_debug_symbols));
2195      break;
2196
2197    case options::OPT_gused:
2198      DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
2199      DAL->AddFlagArg(
2200          A, Opts.getOption(options::OPT_feliminate_unused_debug_symbols));
2201      break;
2202
2203    case options::OPT_shared:
2204      DAL->AddFlagArg(A, Opts.getOption(options::OPT_dynamiclib));
2205      break;
2206
2207    case options::OPT_fconstant_cfstrings:
2208      DAL->AddFlagArg(A, Opts.getOption(options::OPT_mconstant_cfstrings));
2209      break;
2210
2211    case options::OPT_fno_constant_cfstrings:
2212      DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_constant_cfstrings));
2213      break;
2214
2215    case options::OPT_Wnonportable_cfstrings:
2216      DAL->AddFlagArg(A,
2217                      Opts.getOption(options::OPT_mwarn_nonportable_cfstrings));
2218      break;
2219
2220    case options::OPT_Wno_nonportable_cfstrings:
2221      DAL->AddFlagArg(
2222          A, Opts.getOption(options::OPT_mno_warn_nonportable_cfstrings));
2223      break;
2224
2225    case options::OPT_fpascal_strings:
2226      DAL->AddFlagArg(A, Opts.getOption(options::OPT_mpascal_strings));
2227      break;
2228
2229    case options::OPT_fno_pascal_strings:
2230      DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_pascal_strings));
2231      break;
2232    }
2233  }
2234
2235  if (getTriple().isX86())
2236    if (!Args.hasArgNoClaim(options::OPT_mtune_EQ))
2237      DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_mtune_EQ),
2238                        "core2");
2239
2240  // Add the arch options based on the particular spelling of -arch, to match
2241  // how the driver driver works.
2242  if (!BoundArch.empty()) {
2243    StringRef Name = BoundArch;
2244    const Option MCpu = Opts.getOption(options::OPT_mcpu_EQ);
2245    const Option MArch = Opts.getOption(clang::driver::options::OPT_march_EQ);
2246
2247    // This code must be kept in sync with LLVM's getArchTypeForDarwinArch,
2248    // which defines the list of which architectures we accept.
2249    if (Name == "ppc")
2250      ;
2251    else if (Name == "ppc601")
2252      DAL->AddJoinedArg(nullptr, MCpu, "601");
2253    else if (Name == "ppc603")
2254      DAL->AddJoinedArg(nullptr, MCpu, "603");
2255    else if (Name == "ppc604")
2256      DAL->AddJoinedArg(nullptr, MCpu, "604");
2257    else if (Name == "ppc604e")
2258      DAL->AddJoinedArg(nullptr, MCpu, "604e");
2259    else if (Name == "ppc750")
2260      DAL->AddJoinedArg(nullptr, MCpu, "750");
2261    else if (Name == "ppc7400")
2262      DAL->AddJoinedArg(nullptr, MCpu, "7400");
2263    else if (Name == "ppc7450")
2264      DAL->AddJoinedArg(nullptr, MCpu, "7450");
2265    else if (Name == "ppc970")
2266      DAL->AddJoinedArg(nullptr, MCpu, "970");
2267
2268    else if (Name == "ppc64" || Name == "ppc64le")
2269      DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64));
2270
2271    else if (Name == "i386")
2272      ;
2273    else if (Name == "i486")
2274      DAL->AddJoinedArg(nullptr, MArch, "i486");
2275    else if (Name == "i586")
2276      DAL->AddJoinedArg(nullptr, MArch, "i586");
2277    else if (Name == "i686")
2278      DAL->AddJoinedArg(nullptr, MArch, "i686");
2279    else if (Name == "pentium")
2280      DAL->AddJoinedArg(nullptr, MArch, "pentium");
2281    else if (Name == "pentium2")
2282      DAL->AddJoinedArg(nullptr, MArch, "pentium2");
2283    else if (Name == "pentpro")
2284      DAL->AddJoinedArg(nullptr, MArch, "pentiumpro");
2285    else if (Name == "pentIIm3")
2286      DAL->AddJoinedArg(nullptr, MArch, "pentium2");
2287
2288    else if (Name == "x86_64" || Name == "x86_64h")
2289      DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64));
2290
2291    else if (Name == "arm")
2292      DAL->AddJoinedArg(nullptr, MArch, "armv4t");
2293    else if (Name == "armv4t")
2294      DAL->AddJoinedArg(nullptr, MArch, "armv4t");
2295    else if (Name == "armv5")
2296      DAL->AddJoinedArg(nullptr, MArch, "armv5tej");
2297    else if (Name == "xscale")
2298      DAL->AddJoinedArg(nullptr, MArch, "xscale");
2299    else if (Name == "armv6")
2300      DAL->AddJoinedArg(nullptr, MArch, "armv6k");
2301    else if (Name == "armv6m")
2302      DAL->AddJoinedArg(nullptr, MArch, "armv6m");
2303    else if (Name == "armv7")
2304      DAL->AddJoinedArg(nullptr, MArch, "armv7a");
2305    else if (Name == "armv7em")
2306      DAL->AddJoinedArg(nullptr, MArch, "armv7em");
2307    else if (Name == "armv7k")
2308      DAL->AddJoinedArg(nullptr, MArch, "armv7k");
2309    else if (Name == "armv7m")
2310      DAL->AddJoinedArg(nullptr, MArch, "armv7m");
2311    else if (Name == "armv7s")
2312      DAL->AddJoinedArg(nullptr, MArch, "armv7s");
2313  }
2314
2315  return DAL;
2316}
2317
2318void MachO::AddLinkRuntimeLibArgs(const ArgList &Args,
2319                                  ArgStringList &CmdArgs,
2320                                  bool ForceLinkBuiltinRT) const {
2321  // Embedded targets are simple at the moment, not supporting sanitizers and
2322  // with different libraries for each member of the product { static, PIC } x
2323  // { hard-float, soft-float }
2324  llvm::SmallString<32> CompilerRT = StringRef("");
2325  CompilerRT +=
2326      (tools::arm::getARMFloatABI(*this, Args) == tools::arm::FloatABI::Hard)
2327          ? "hard"
2328          : "soft";
2329  CompilerRT += Args.hasArg(options::OPT_fPIC) ? "_pic" : "_static";
2330
2331  AddLinkRuntimeLib(Args, CmdArgs, CompilerRT, RLO_IsEmbedded);
2332}
2333
2334bool Darwin::isAlignedAllocationUnavailable() const {
2335  llvm::Triple::OSType OS;
2336
2337  switch (TargetPlatform) {
2338  case MacOS: // Earlier than 10.13.
2339    OS = llvm::Triple::MacOSX;
2340    break;
2341  case IPhoneOS:
2342    OS = llvm::Triple::IOS;
2343    break;
2344  case TvOS: // Earlier than 11.0.
2345    OS = llvm::Triple::TvOS;
2346    break;
2347  case WatchOS: // Earlier than 4.0.
2348    OS = llvm::Triple::WatchOS;
2349    break;
2350  }
2351
2352  return TargetVersion < alignedAllocMinVersion(OS);
2353}
2354
2355void Darwin::addClangTargetOptions(const llvm::opt::ArgList &DriverArgs,
2356                                   llvm::opt::ArgStringList &CC1Args,
2357                                   Action::OffloadKind DeviceOffloadKind) const {
2358  // Pass "-faligned-alloc-unavailable" only when the user hasn't manually
2359  // enabled or disabled aligned allocations.
2360  if (!DriverArgs.hasArgNoClaim(options::OPT_faligned_allocation,
2361                                options::OPT_fno_aligned_allocation) &&
2362      isAlignedAllocationUnavailable())
2363    CC1Args.push_back("-faligned-alloc-unavailable");
2364
2365  if (SDKInfo) {
2366    /// Pass the SDK version to the compiler when the SDK information is
2367    /// available.
2368    std::string Arg;
2369    llvm::raw_string_ostream OS(Arg);
2370    OS << "-target-sdk-version=" << SDKInfo->getVersion();
2371    CC1Args.push_back(DriverArgs.MakeArgString(OS.str()));
2372  }
2373}
2374
2375DerivedArgList *
2376Darwin::TranslateArgs(const DerivedArgList &Args, StringRef BoundArch,
2377                      Action::OffloadKind DeviceOffloadKind) const {
2378  // First get the generic Apple args, before moving onto Darwin-specific ones.
2379  DerivedArgList *DAL =
2380      MachO::TranslateArgs(Args, BoundArch, DeviceOffloadKind);
2381  const OptTable &Opts = getDriver().getOpts();
2382
2383  // If no architecture is bound, none of the translations here are relevant.
2384  if (BoundArch.empty())
2385    return DAL;
2386
2387  // Add an explicit version min argument for the deployment target. We do this
2388  // after argument translation because -Xarch_ arguments may add a version min
2389  // argument.
2390  AddDeploymentTarget(*DAL);
2391
2392  // For iOS 6, undo the translation to add -static for -mkernel/-fapple-kext.
2393  // FIXME: It would be far better to avoid inserting those -static arguments,
2394  // but we can't check the deployment target in the translation code until
2395  // it is set here.
2396  if (isTargetWatchOSBased() ||
2397      (isTargetIOSBased() && !isIPhoneOSVersionLT(6, 0))) {
2398    for (ArgList::iterator it = DAL->begin(), ie = DAL->end(); it != ie; ) {
2399      Arg *A = *it;
2400      ++it;
2401      if (A->getOption().getID() != options::OPT_mkernel &&
2402          A->getOption().getID() != options::OPT_fapple_kext)
2403        continue;
2404      assert(it != ie && "unexpected argument translation");
2405      A = *it;
2406      assert(A->getOption().getID() == options::OPT_static &&
2407             "missing expected -static argument");
2408      *it = nullptr;
2409      ++it;
2410    }
2411  }
2412
2413  if (!Args.getLastArg(options::OPT_stdlib_EQ) &&
2414      GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
2415    DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_stdlib_EQ),
2416                      "libc++");
2417
2418  // Validate the C++ standard library choice.
2419  CXXStdlibType Type = GetCXXStdlibType(*DAL);
2420  if (Type == ToolChain::CST_Libcxx) {
2421    // Check whether the target provides libc++.
2422    StringRef where;
2423
2424    // Complain about targeting iOS < 5.0 in any way.
2425    if (isTargetIOSBased() && isIPhoneOSVersionLT(5, 0))
2426      where = "iOS 5.0";
2427
2428    if (where != StringRef()) {
2429      getDriver().Diag(clang::diag::err_drv_invalid_libcxx_deployment) << where;
2430    }
2431  }
2432
2433  auto Arch = tools::darwin::getArchTypeForMachOArchName(BoundArch);
2434  if ((Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb)) {
2435    if (Args.hasFlag(options::OPT_fomit_frame_pointer,
2436                     options::OPT_fno_omit_frame_pointer, false))
2437      getDriver().Diag(clang::diag::warn_drv_unsupported_opt_for_target)
2438          << "-fomit-frame-pointer" << BoundArch;
2439  }
2440
2441  return DAL;
2442}
2443
2444bool MachO::IsUnwindTablesDefault(const ArgList &Args) const {
2445  // Unwind tables are not emitted if -fno-exceptions is supplied (except when
2446  // targeting x86_64).
2447  return getArch() == llvm::Triple::x86_64 ||
2448         (GetExceptionModel(Args) != llvm::ExceptionHandling::SjLj &&
2449          Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
2450                       true));
2451}
2452
2453bool MachO::UseDwarfDebugFlags() const {
2454  if (const char *S = ::getenv("RC_DEBUG_OPTIONS"))
2455    return S[0] != '\0';
2456  return false;
2457}
2458
2459llvm::ExceptionHandling Darwin::GetExceptionModel(const ArgList &Args) const {
2460  // Darwin uses SjLj exceptions on ARM.
2461  if (getTriple().getArch() != llvm::Triple::arm &&
2462      getTriple().getArch() != llvm::Triple::thumb)
2463    return llvm::ExceptionHandling::None;
2464
2465  // Only watchOS uses the new DWARF/Compact unwinding method.
2466  llvm::Triple Triple(ComputeLLVMTriple(Args));
2467  if (Triple.isWatchABI())
2468    return llvm::ExceptionHandling::DwarfCFI;
2469
2470  return llvm::ExceptionHandling::SjLj;
2471}
2472
2473bool Darwin::SupportsEmbeddedBitcode() const {
2474  assert(TargetInitialized && "Target not initialized!");
2475  if (isTargetIPhoneOS() && isIPhoneOSVersionLT(6, 0))
2476    return false;
2477  return true;
2478}
2479
2480bool MachO::isPICDefault() const { return true; }
2481
2482bool MachO::isPIEDefault() const { return false; }
2483
2484bool MachO::isPICDefaultForced() const {
2485  return (getArch() == llvm::Triple::x86_64 ||
2486          getArch() == llvm::Triple::aarch64);
2487}
2488
2489bool MachO::SupportsProfiling() const {
2490  // Profiling instrumentation is only supported on x86.
2491  return getTriple().isX86();
2492}
2493
2494void Darwin::addMinVersionArgs(const ArgList &Args,
2495                               ArgStringList &CmdArgs) const {
2496  VersionTuple TargetVersion = getTargetVersion();
2497
2498  if (isTargetWatchOS())
2499    CmdArgs.push_back("-watchos_version_min");
2500  else if (isTargetWatchOSSimulator())
2501    CmdArgs.push_back("-watchos_simulator_version_min");
2502  else if (isTargetTvOS())
2503    CmdArgs.push_back("-tvos_version_min");
2504  else if (isTargetTvOSSimulator())
2505    CmdArgs.push_back("-tvos_simulator_version_min");
2506  else if (isTargetIOSSimulator())
2507    CmdArgs.push_back("-ios_simulator_version_min");
2508  else if (isTargetIOSBased())
2509    CmdArgs.push_back("-iphoneos_version_min");
2510  else {
2511    assert(isTargetMacOS() && "unexpected target");
2512    CmdArgs.push_back("-macosx_version_min");
2513  }
2514
2515  CmdArgs.push_back(Args.MakeArgString(TargetVersion.getAsString()));
2516}
2517
2518static const char *getPlatformName(Darwin::DarwinPlatformKind Platform,
2519                                   Darwin::DarwinEnvironmentKind Environment) {
2520  switch (Platform) {
2521  case Darwin::MacOS:
2522    return "macos";
2523  case Darwin::IPhoneOS:
2524    if (Environment == Darwin::NativeEnvironment ||
2525        Environment == Darwin::Simulator)
2526      return "ios";
2527    // FIXME: Add macCatalyst support here ("\"mac catalyst\"").
2528    llvm_unreachable("macCatalyst isn't yet supported");
2529  case Darwin::TvOS:
2530    return "tvos";
2531  case Darwin::WatchOS:
2532    return "watchos";
2533  }
2534  llvm_unreachable("invalid platform");
2535}
2536
2537void Darwin::addPlatformVersionArgs(const llvm::opt::ArgList &Args,
2538                                    llvm::opt::ArgStringList &CmdArgs) const {
2539  // -platform_version <platform> <target_version> <sdk_version>
2540  // Both the target and SDK version support only up to 3 components.
2541  CmdArgs.push_back("-platform_version");
2542  std::string PlatformName = getPlatformName(TargetPlatform, TargetEnvironment);
2543  if (TargetEnvironment == Darwin::Simulator)
2544    PlatformName += "-simulator";
2545  CmdArgs.push_back(Args.MakeArgString(PlatformName));
2546  VersionTuple TargetVersion = getTargetVersion().withoutBuild();
2547  CmdArgs.push_back(Args.MakeArgString(TargetVersion.getAsString()));
2548  if (SDKInfo) {
2549    VersionTuple SDKVersion = SDKInfo->getVersion().withoutBuild();
2550    CmdArgs.push_back(Args.MakeArgString(SDKVersion.getAsString()));
2551  } else {
2552    // Use a blank SDK version if it's not present.
2553    CmdArgs.push_back("0.0.0");
2554  }
2555}
2556
2557void Darwin::addStartObjectFileArgs(const ArgList &Args,
2558                                    ArgStringList &CmdArgs) const {
2559  // Derived from startfile spec.
2560  if (Args.hasArg(options::OPT_dynamiclib)) {
2561    // Derived from darwin_dylib1 spec.
2562    if (isTargetWatchOSBased()) {
2563      ; // watchOS does not need dylib1.o.
2564    } else if (isTargetIOSSimulator()) {
2565      ; // iOS simulator does not need dylib1.o.
2566    } else if (isTargetIPhoneOS()) {
2567      if (isIPhoneOSVersionLT(3, 1))
2568        CmdArgs.push_back("-ldylib1.o");
2569    } else {
2570      if (isMacosxVersionLT(10, 5))
2571        CmdArgs.push_back("-ldylib1.o");
2572      else if (isMacosxVersionLT(10, 6))
2573        CmdArgs.push_back("-ldylib1.10.5.o");
2574    }
2575  } else {
2576    if (Args.hasArg(options::OPT_bundle)) {
2577      if (!Args.hasArg(options::OPT_static)) {
2578        // Derived from darwin_bundle1 spec.
2579        if (isTargetWatchOSBased()) {
2580          ; // watchOS does not need bundle1.o.
2581        } else if (isTargetIOSSimulator()) {
2582          ; // iOS simulator does not need bundle1.o.
2583        } else if (isTargetIPhoneOS()) {
2584          if (isIPhoneOSVersionLT(3, 1))
2585            CmdArgs.push_back("-lbundle1.o");
2586        } else {
2587          if (isMacosxVersionLT(10, 6))
2588            CmdArgs.push_back("-lbundle1.o");
2589        }
2590      }
2591    } else {
2592      if (Args.hasArg(options::OPT_pg) && SupportsProfiling()) {
2593        if (isTargetMacOS() && isMacosxVersionLT(10, 9)) {
2594          if (Args.hasArg(options::OPT_static) ||
2595              Args.hasArg(options::OPT_object) ||
2596              Args.hasArg(options::OPT_preload)) {
2597            CmdArgs.push_back("-lgcrt0.o");
2598          } else {
2599            CmdArgs.push_back("-lgcrt1.o");
2600
2601            // darwin_crt2 spec is empty.
2602          }
2603          // By default on OS X 10.8 and later, we don't link with a crt1.o
2604          // file and the linker knows to use _main as the entry point.  But,
2605          // when compiling with -pg, we need to link with the gcrt1.o file,
2606          // so pass the -no_new_main option to tell the linker to use the
2607          // "start" symbol as the entry point.
2608          if (isTargetMacOS() && !isMacosxVersionLT(10, 8))
2609            CmdArgs.push_back("-no_new_main");
2610        } else {
2611          getDriver().Diag(diag::err_drv_clang_unsupported_opt_pg_darwin)
2612              << isTargetMacOS();
2613        }
2614      } else {
2615        if (Args.hasArg(options::OPT_static) ||
2616            Args.hasArg(options::OPT_object) ||
2617            Args.hasArg(options::OPT_preload)) {
2618          CmdArgs.push_back("-lcrt0.o");
2619        } else {
2620          // Derived from darwin_crt1 spec.
2621          if (isTargetWatchOSBased()) {
2622            ; // watchOS does not need crt1.o.
2623          } else if (isTargetIOSSimulator()) {
2624            ; // iOS simulator does not need crt1.o.
2625          } else if (isTargetIPhoneOS()) {
2626            if (getArch() == llvm::Triple::aarch64)
2627              ; // iOS does not need any crt1 files for arm64
2628            else if (isIPhoneOSVersionLT(3, 1))
2629              CmdArgs.push_back("-lcrt1.o");
2630            else if (isIPhoneOSVersionLT(6, 0))
2631              CmdArgs.push_back("-lcrt1.3.1.o");
2632          } else {
2633            if (isMacosxVersionLT(10, 5))
2634              CmdArgs.push_back("-lcrt1.o");
2635            else if (isMacosxVersionLT(10, 6))
2636              CmdArgs.push_back("-lcrt1.10.5.o");
2637            else if (isMacosxVersionLT(10, 8))
2638              CmdArgs.push_back("-lcrt1.10.6.o");
2639
2640            // darwin_crt2 spec is empty.
2641          }
2642        }
2643      }
2644    }
2645  }
2646
2647  if (!isTargetIPhoneOS() && Args.hasArg(options::OPT_shared_libgcc) &&
2648      !isTargetWatchOS() && isMacosxVersionLT(10, 5)) {
2649    const char *Str = Args.MakeArgString(GetFilePath("crt3.o"));
2650    CmdArgs.push_back(Str);
2651  }
2652}
2653
2654void Darwin::CheckObjCARC() const {
2655  if (isTargetIOSBased() || isTargetWatchOSBased() ||
2656      (isTargetMacOS() && !isMacosxVersionLT(10, 6)))
2657    return;
2658  getDriver().Diag(diag::err_arc_unsupported_on_toolchain);
2659}
2660
2661SanitizerMask Darwin::getSupportedSanitizers() const {
2662  const bool IsX86_64 = getTriple().getArch() == llvm::Triple::x86_64;
2663  SanitizerMask Res = ToolChain::getSupportedSanitizers();
2664  Res |= SanitizerKind::Address;
2665  Res |= SanitizerKind::PointerCompare;
2666  Res |= SanitizerKind::PointerSubtract;
2667  Res |= SanitizerKind::Leak;
2668  Res |= SanitizerKind::Fuzzer;
2669  Res |= SanitizerKind::FuzzerNoLink;
2670  Res |= SanitizerKind::Function;
2671
2672  // Prior to 10.9, macOS shipped a version of the C++ standard library without
2673  // C++11 support. The same is true of iOS prior to version 5. These OS'es are
2674  // incompatible with -fsanitize=vptr.
2675  if (!(isTargetMacOS() && isMacosxVersionLT(10, 9))
2676      && !(isTargetIPhoneOS() && isIPhoneOSVersionLT(5, 0)))
2677    Res |= SanitizerKind::Vptr;
2678
2679  if (isTargetMacOS()) {
2680    if (IsX86_64)
2681      Res |= SanitizerKind::Thread;
2682  } else if (isTargetIOSSimulator() || isTargetTvOSSimulator()) {
2683    if (IsX86_64)
2684      Res |= SanitizerKind::Thread;
2685  }
2686  return Res;
2687}
2688
2689void Darwin::printVerboseInfo(raw_ostream &OS) const {
2690  CudaInstallation.print(OS);
2691}
2692