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