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