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