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