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