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