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