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