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