]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Driver/ToolChains/Darwin.cpp
Merge llvm, clang, lld and lldb trunk r300890, and update build glue.
[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/ObjCRuntime.h"
14 #include "clang/Basic/VirtualFileSystem.h"
15 #include "clang/Driver/Compilation.h"
16 #include "clang/Driver/Driver.h"
17 #include "clang/Driver/DriverDiagnostic.h"
18 #include "clang/Driver/Options.h"
19 #include "clang/Driver/SanitizerArgs.h"
20 #include "llvm/ADT/StringSwitch.h"
21 #include "llvm/Option/ArgList.h"
22 #include "llvm/Support/Path.h"
23 #include "llvm/Support/ScopedPrinter.h"
24 #include "llvm/Support/TargetParser.h"
25 #include <cstdlib> // ::getenv
26
27 using namespace clang::driver;
28 using namespace clang::driver::tools;
29 using namespace clang::driver::toolchains;
30 using namespace clang;
31 using namespace llvm::opt;
32
33 llvm::Triple::ArchType darwin::getArchTypeForMachOArchName(StringRef Str) {
34   // See arch(3) and llvm-gcc's driver-driver.c. We don't implement support for
35   // archs which Darwin doesn't use.
36
37   // The matching this routine does is fairly pointless, since it is neither the
38   // complete architecture list, nor a reasonable subset. The problem is that
39   // historically the driver driver accepts this and also ties its -march=
40   // handling to the architecture name, so we need to be careful before removing
41   // support for it.
42
43   // This code must be kept in sync with Clang's Darwin specific argument
44   // translation.
45
46   return llvm::StringSwitch<llvm::Triple::ArchType>(Str)
47       .Cases("ppc", "ppc601", "ppc603", "ppc604", "ppc604e", llvm::Triple::ppc)
48       .Cases("ppc750", "ppc7400", "ppc7450", "ppc970", llvm::Triple::ppc)
49       .Case("ppc64", llvm::Triple::ppc64)
50       .Cases("i386", "i486", "i486SX", "i586", "i686", llvm::Triple::x86)
51       .Cases("pentium", "pentpro", "pentIIm3", "pentIIm5", "pentium4",
52              llvm::Triple::x86)
53       .Cases("x86_64", "x86_64h", llvm::Triple::x86_64)
54       // This is derived from the driver driver.
55       .Cases("arm", "armv4t", "armv5", "armv6", "armv6m", llvm::Triple::arm)
56       .Cases("armv7", "armv7em", "armv7k", "armv7m", llvm::Triple::arm)
57       .Cases("armv7s", "xscale", llvm::Triple::arm)
58       .Case("arm64", llvm::Triple::aarch64)
59       .Case("r600", llvm::Triple::r600)
60       .Case("amdgcn", llvm::Triple::amdgcn)
61       .Case("nvptx", llvm::Triple::nvptx)
62       .Case("nvptx64", llvm::Triple::nvptx64)
63       .Case("amdil", llvm::Triple::amdil)
64       .Case("spir", llvm::Triple::spir)
65       .Default(llvm::Triple::UnknownArch);
66 }
67
68 void darwin::setTripleTypeForMachOArchName(llvm::Triple &T, StringRef Str) {
69   const llvm::Triple::ArchType Arch = getArchTypeForMachOArchName(Str);
70   unsigned ArchKind = llvm::ARM::parseArch(Str);
71   T.setArch(Arch);
72
73   if (Str == "x86_64h")
74     T.setArchName(Str);
75   else if (ArchKind == llvm::ARM::AK_ARMV6M ||
76            ArchKind == llvm::ARM::AK_ARMV7M ||
77            ArchKind == llvm::ARM::AK_ARMV7EM) {
78     T.setOS(llvm::Triple::UnknownOS);
79     T.setObjectFormat(llvm::Triple::MachO);
80   }
81 }
82
83 void darwin::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
84                                      const InputInfo &Output,
85                                      const InputInfoList &Inputs,
86                                      const ArgList &Args,
87                                      const char *LinkingOutput) const {
88   ArgStringList CmdArgs;
89
90   assert(Inputs.size() == 1 && "Unexpected number of inputs.");
91   const InputInfo &Input = Inputs[0];
92
93   // Determine the original source input.
94   const Action *SourceAction = &JA;
95   while (SourceAction->getKind() != Action::InputClass) {
96     assert(!SourceAction->getInputs().empty() && "unexpected root action!");
97     SourceAction = SourceAction->getInputs()[0];
98   }
99
100   // If -fno-integrated-as is used add -Q to the darwin assember driver to make
101   // sure it runs its system assembler not clang's integrated assembler.
102   // Applicable to darwin11+ and Xcode 4+.  darwin<10 lacked integrated-as.
103   // FIXME: at run-time detect assembler capabilities or rely on version
104   // information forwarded by -target-assembler-version.
105   if (Args.hasArg(options::OPT_fno_integrated_as)) {
106     const llvm::Triple &T(getToolChain().getTriple());
107     if (!(T.isMacOSX() && T.isMacOSXVersionLT(10, 7)))
108       CmdArgs.push_back("-Q");
109   }
110
111   // Forward -g, assuming we are dealing with an actual assembly file.
112   if (SourceAction->getType() == types::TY_Asm ||
113       SourceAction->getType() == types::TY_PP_Asm) {
114     if (Args.hasArg(options::OPT_gstabs))
115       CmdArgs.push_back("--gstabs");
116     else if (Args.hasArg(options::OPT_g_Group))
117       CmdArgs.push_back("-g");
118   }
119
120   // Derived from asm spec.
121   AddMachOArch(Args, CmdArgs);
122
123   // Use -force_cpusubtype_ALL on x86 by default.
124   if (getToolChain().getArch() == llvm::Triple::x86 ||
125       getToolChain().getArch() == llvm::Triple::x86_64 ||
126       Args.hasArg(options::OPT_force__cpusubtype__ALL))
127     CmdArgs.push_back("-force_cpusubtype_ALL");
128
129   if (getToolChain().getArch() != llvm::Triple::x86_64 &&
130       (((Args.hasArg(options::OPT_mkernel) ||
131          Args.hasArg(options::OPT_fapple_kext)) &&
132         getMachOToolChain().isKernelStatic()) ||
133        Args.hasArg(options::OPT_static)))
134     CmdArgs.push_back("-static");
135
136   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
137
138   assert(Output.isFilename() && "Unexpected lipo output.");
139   CmdArgs.push_back("-o");
140   CmdArgs.push_back(Output.getFilename());
141
142   assert(Input.isFilename() && "Invalid input.");
143   CmdArgs.push_back(Input.getFilename());
144
145   // asm_final spec is empty.
146
147   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
148   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
149 }
150
151 void darwin::MachOTool::anchor() {}
152
153 void darwin::MachOTool::AddMachOArch(const ArgList &Args,
154                                      ArgStringList &CmdArgs) const {
155   StringRef ArchName = getMachOToolChain().getMachOArchName(Args);
156
157   // Derived from darwin_arch spec.
158   CmdArgs.push_back("-arch");
159   CmdArgs.push_back(Args.MakeArgString(ArchName));
160
161   // FIXME: Is this needed anymore?
162   if (ArchName == "arm")
163     CmdArgs.push_back("-force_cpusubtype_ALL");
164 }
165
166 bool darwin::Linker::NeedsTempPath(const InputInfoList &Inputs) const {
167   // We only need to generate a temp path for LTO if we aren't compiling object
168   // files. When compiling source files, we run 'dsymutil' after linking. We
169   // don't run 'dsymutil' when compiling object files.
170   for (const auto &Input : Inputs)
171     if (Input.getType() != types::TY_Object)
172       return true;
173
174   return false;
175 }
176
177 /// \brief Pass -no_deduplicate to ld64 under certain conditions:
178 ///
179 /// - Either -O0 or -O1 is explicitly specified
180 /// - No -O option is specified *and* this is a compile+link (implicit -O0)
181 ///
182 /// Also do *not* add -no_deduplicate when no -O option is specified and this
183 /// is just a link (we can't imply -O0)
184 static bool shouldLinkerNotDedup(bool IsLinkerOnlyAction, const ArgList &Args) {
185   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
186     if (A->getOption().matches(options::OPT_O0))
187       return true;
188     if (A->getOption().matches(options::OPT_O))
189       return llvm::StringSwitch<bool>(A->getValue())
190                     .Case("1", true)
191                     .Default(false);
192     return false; // OPT_Ofast & OPT_O4
193   }
194
195   if (!IsLinkerOnlyAction) // Implicit -O0 for compile+linker only.
196     return true;
197   return false;
198 }
199
200 void darwin::Linker::AddLinkArgs(Compilation &C, const ArgList &Args,
201                                  ArgStringList &CmdArgs,
202                                  const InputInfoList &Inputs) const {
203   const Driver &D = getToolChain().getDriver();
204   const toolchains::MachO &MachOTC = getMachOToolChain();
205
206   unsigned Version[5] = {0, 0, 0, 0, 0};
207   if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
208     if (!Driver::GetReleaseVersion(A->getValue(), Version))
209       D.Diag(diag::err_drv_invalid_version_number) << A->getAsString(Args);
210   }
211
212   // Newer linkers support -demangle. Pass it if supported and not disabled by
213   // the user.
214   if (Version[0] >= 100 && !Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
215     CmdArgs.push_back("-demangle");
216
217   if (Args.hasArg(options::OPT_rdynamic) && Version[0] >= 137)
218     CmdArgs.push_back("-export_dynamic");
219
220   // If we are using App Extension restrictions, pass a flag to the linker
221   // telling it that the compiled code has been audited.
222   if (Args.hasFlag(options::OPT_fapplication_extension,
223                    options::OPT_fno_application_extension, false))
224     CmdArgs.push_back("-application_extension");
225
226   if (D.isUsingLTO()) {
227     // If we are using LTO, then automatically create a temporary file path for
228     // the linker to use, so that it's lifetime will extend past a possible
229     // dsymutil step.
230     if (Version[0] >= 116 && NeedsTempPath(Inputs)) {
231       const char *TmpPath = C.getArgs().MakeArgString(
232           D.GetTemporaryPath("cc", types::getTypeTempSuffix(types::TY_Object)));
233       C.addTempFile(TmpPath);
234       CmdArgs.push_back("-object_path_lto");
235       CmdArgs.push_back(TmpPath);
236     }
237   }
238
239   // Use -lto_library option to specify the libLTO.dylib path. Try to find
240   // it in clang installed libraries. ld64 will only look at this argument
241   // when it actually uses LTO, so libLTO.dylib only needs to exist at link
242   // time if ld64 decides that it needs to use LTO.
243   // Since this is passed unconditionally, ld64 will never look for libLTO.dylib
244   // next to it. That's ok since ld64 using a libLTO.dylib not matching the
245   // clang version won't work anyways.
246   if (Version[0] >= 133) {
247     // Search for libLTO in <InstalledDir>/../lib/libLTO.dylib
248     StringRef P = llvm::sys::path::parent_path(D.Dir);
249     SmallString<128> LibLTOPath(P);
250     llvm::sys::path::append(LibLTOPath, "lib");
251     llvm::sys::path::append(LibLTOPath, "libLTO.dylib");
252     CmdArgs.push_back("-lto_library");
253     CmdArgs.push_back(C.getArgs().MakeArgString(LibLTOPath));
254   }
255
256   // ld64 version 262 and above run the deduplicate pass by default.
257   if (Version[0] >= 262 && shouldLinkerNotDedup(C.getJobs().empty(), Args))
258     CmdArgs.push_back("-no_deduplicate");
259
260   // Derived from the "link" spec.
261   Args.AddAllArgs(CmdArgs, options::OPT_static);
262   if (!Args.hasArg(options::OPT_static))
263     CmdArgs.push_back("-dynamic");
264   if (Args.hasArg(options::OPT_fgnu_runtime)) {
265     // FIXME: gcc replaces -lobjc in forward args with -lobjc-gnu
266     // here. How do we wish to handle such things?
267   }
268
269   if (!Args.hasArg(options::OPT_dynamiclib)) {
270     AddMachOArch(Args, CmdArgs);
271     // FIXME: Why do this only on this path?
272     Args.AddLastArg(CmdArgs, options::OPT_force__cpusubtype__ALL);
273
274     Args.AddLastArg(CmdArgs, options::OPT_bundle);
275     Args.AddAllArgs(CmdArgs, options::OPT_bundle__loader);
276     Args.AddAllArgs(CmdArgs, options::OPT_client__name);
277
278     Arg *A;
279     if ((A = Args.getLastArg(options::OPT_compatibility__version)) ||
280         (A = Args.getLastArg(options::OPT_current__version)) ||
281         (A = Args.getLastArg(options::OPT_install__name)))
282       D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
283                                                        << "-dynamiclib";
284
285     Args.AddLastArg(CmdArgs, options::OPT_force__flat__namespace);
286     Args.AddLastArg(CmdArgs, options::OPT_keep__private__externs);
287     Args.AddLastArg(CmdArgs, options::OPT_private__bundle);
288   } else {
289     CmdArgs.push_back("-dylib");
290
291     Arg *A;
292     if ((A = Args.getLastArg(options::OPT_bundle)) ||
293         (A = Args.getLastArg(options::OPT_bundle__loader)) ||
294         (A = Args.getLastArg(options::OPT_client__name)) ||
295         (A = Args.getLastArg(options::OPT_force__flat__namespace)) ||
296         (A = Args.getLastArg(options::OPT_keep__private__externs)) ||
297         (A = Args.getLastArg(options::OPT_private__bundle)))
298       D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
299                                                       << "-dynamiclib";
300
301     Args.AddAllArgsTranslated(CmdArgs, options::OPT_compatibility__version,
302                               "-dylib_compatibility_version");
303     Args.AddAllArgsTranslated(CmdArgs, options::OPT_current__version,
304                               "-dylib_current_version");
305
306     AddMachOArch(Args, CmdArgs);
307
308     Args.AddAllArgsTranslated(CmdArgs, options::OPT_install__name,
309                               "-dylib_install_name");
310   }
311
312   Args.AddLastArg(CmdArgs, options::OPT_all__load);
313   Args.AddAllArgs(CmdArgs, options::OPT_allowable__client);
314   Args.AddLastArg(CmdArgs, options::OPT_bind__at__load);
315   if (MachOTC.isTargetIOSBased())
316     Args.AddLastArg(CmdArgs, options::OPT_arch__errors__fatal);
317   Args.AddLastArg(CmdArgs, options::OPT_dead__strip);
318   Args.AddLastArg(CmdArgs, options::OPT_no__dead__strip__inits__and__terms);
319   Args.AddAllArgs(CmdArgs, options::OPT_dylib__file);
320   Args.AddLastArg(CmdArgs, options::OPT_dynamic);
321   Args.AddAllArgs(CmdArgs, options::OPT_exported__symbols__list);
322   Args.AddLastArg(CmdArgs, options::OPT_flat__namespace);
323   Args.AddAllArgs(CmdArgs, options::OPT_force__load);
324   Args.AddAllArgs(CmdArgs, options::OPT_headerpad__max__install__names);
325   Args.AddAllArgs(CmdArgs, options::OPT_image__base);
326   Args.AddAllArgs(CmdArgs, options::OPT_init);
327
328   // Add the deployment target.
329   MachOTC.addMinVersionArgs(Args, CmdArgs);
330
331   Args.AddLastArg(CmdArgs, options::OPT_nomultidefs);
332   Args.AddLastArg(CmdArgs, options::OPT_multi__module);
333   Args.AddLastArg(CmdArgs, options::OPT_single__module);
334   Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined);
335   Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined__unused);
336
337   if (const Arg *A =
338           Args.getLastArg(options::OPT_fpie, options::OPT_fPIE,
339                           options::OPT_fno_pie, options::OPT_fno_PIE)) {
340     if (A->getOption().matches(options::OPT_fpie) ||
341         A->getOption().matches(options::OPT_fPIE))
342       CmdArgs.push_back("-pie");
343     else
344       CmdArgs.push_back("-no_pie");
345   }
346
347   // for embed-bitcode, use -bitcode_bundle in linker command
348   if (C.getDriver().embedBitcodeEnabled()) {
349     // Check if the toolchain supports bitcode build flow.
350     if (MachOTC.SupportsEmbeddedBitcode()) {
351       CmdArgs.push_back("-bitcode_bundle");
352       if (C.getDriver().embedBitcodeMarkerOnly() && Version[0] >= 278) {
353         CmdArgs.push_back("-bitcode_process_mode");
354         CmdArgs.push_back("marker");
355       }
356     } else
357       D.Diag(diag::err_drv_bitcode_unsupported_on_toolchain);
358   }
359
360   Args.AddLastArg(CmdArgs, options::OPT_prebind);
361   Args.AddLastArg(CmdArgs, options::OPT_noprebind);
362   Args.AddLastArg(CmdArgs, options::OPT_nofixprebinding);
363   Args.AddLastArg(CmdArgs, options::OPT_prebind__all__twolevel__modules);
364   Args.AddLastArg(CmdArgs, options::OPT_read__only__relocs);
365   Args.AddAllArgs(CmdArgs, options::OPT_sectcreate);
366   Args.AddAllArgs(CmdArgs, options::OPT_sectorder);
367   Args.AddAllArgs(CmdArgs, options::OPT_seg1addr);
368   Args.AddAllArgs(CmdArgs, options::OPT_segprot);
369   Args.AddAllArgs(CmdArgs, options::OPT_segaddr);
370   Args.AddAllArgs(CmdArgs, options::OPT_segs__read__only__addr);
371   Args.AddAllArgs(CmdArgs, options::OPT_segs__read__write__addr);
372   Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table);
373   Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table__filename);
374   Args.AddAllArgs(CmdArgs, options::OPT_sub__library);
375   Args.AddAllArgs(CmdArgs, options::OPT_sub__umbrella);
376
377   // Give --sysroot= preference, over the Apple specific behavior to also use
378   // --isysroot as the syslibroot.
379   StringRef sysroot = C.getSysRoot();
380   if (sysroot != "") {
381     CmdArgs.push_back("-syslibroot");
382     CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
383   } else if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
384     CmdArgs.push_back("-syslibroot");
385     CmdArgs.push_back(A->getValue());
386   }
387
388   Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace);
389   Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace__hints);
390   Args.AddAllArgs(CmdArgs, options::OPT_umbrella);
391   Args.AddAllArgs(CmdArgs, options::OPT_undefined);
392   Args.AddAllArgs(CmdArgs, options::OPT_unexported__symbols__list);
393   Args.AddAllArgs(CmdArgs, options::OPT_weak__reference__mismatches);
394   Args.AddLastArg(CmdArgs, options::OPT_X_Flag);
395   Args.AddAllArgs(CmdArgs, options::OPT_y);
396   Args.AddLastArg(CmdArgs, options::OPT_w);
397   Args.AddAllArgs(CmdArgs, options::OPT_pagezero__size);
398   Args.AddAllArgs(CmdArgs, options::OPT_segs__read__);
399   Args.AddLastArg(CmdArgs, options::OPT_seglinkedit);
400   Args.AddLastArg(CmdArgs, options::OPT_noseglinkedit);
401   Args.AddAllArgs(CmdArgs, options::OPT_sectalign);
402   Args.AddAllArgs(CmdArgs, options::OPT_sectobjectsymbols);
403   Args.AddAllArgs(CmdArgs, options::OPT_segcreate);
404   Args.AddLastArg(CmdArgs, options::OPT_whyload);
405   Args.AddLastArg(CmdArgs, options::OPT_whatsloaded);
406   Args.AddAllArgs(CmdArgs, options::OPT_dylinker__install__name);
407   Args.AddLastArg(CmdArgs, options::OPT_dylinker);
408   Args.AddLastArg(CmdArgs, options::OPT_Mach);
409 }
410
411 /// \brief Determine whether we are linking the ObjC runtime.
412 static bool isObjCRuntimeLinked(const ArgList &Args) {
413   if (isObjCAutoRefCount(Args)) {
414     Args.ClaimAllArgs(options::OPT_fobjc_link_runtime);
415     return true;
416   }
417   return Args.hasArg(options::OPT_fobjc_link_runtime);
418 }
419
420 void darwin::Linker::ConstructJob(Compilation &C, const JobAction &JA,
421                                   const InputInfo &Output,
422                                   const InputInfoList &Inputs,
423                                   const ArgList &Args,
424                                   const char *LinkingOutput) const {
425   assert(Output.getType() == types::TY_Image && "Invalid linker output type.");
426
427   // If the number of arguments surpasses the system limits, we will encode the
428   // input files in a separate file, shortening the command line. To this end,
429   // build a list of input file names that can be passed via a file with the
430   // -filelist linker option.
431   llvm::opt::ArgStringList InputFileList;
432
433   // The logic here is derived from gcc's behavior; most of which
434   // comes from specs (starting with link_command). Consult gcc for
435   // more information.
436   ArgStringList CmdArgs;
437
438   /// Hack(tm) to ignore linking errors when we are doing ARC migration.
439   if (Args.hasArg(options::OPT_ccc_arcmt_check,
440                   options::OPT_ccc_arcmt_migrate)) {
441     for (const auto &Arg : Args)
442       Arg->claim();
443     const char *Exec =
444         Args.MakeArgString(getToolChain().GetProgramPath("touch"));
445     CmdArgs.push_back(Output.getFilename());
446     C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, None));
447     return;
448   }
449
450   // I'm not sure why this particular decomposition exists in gcc, but
451   // we follow suite for ease of comparison.
452   AddLinkArgs(C, Args, CmdArgs, Inputs);
453
454   // For LTO, pass the name of the optimization record file.
455   if (Args.hasFlag(options::OPT_fsave_optimization_record,
456                    options::OPT_fno_save_optimization_record, false)) {
457     CmdArgs.push_back("-mllvm");
458     CmdArgs.push_back("-lto-pass-remarks-output");
459     CmdArgs.push_back("-mllvm");
460
461     SmallString<128> F;
462     F = Output.getFilename();
463     F += ".opt.yaml";
464     CmdArgs.push_back(Args.MakeArgString(F));
465
466     if (getLastProfileUseArg(Args)) {
467       CmdArgs.push_back("-mllvm");
468       CmdArgs.push_back("-lto-pass-remarks-with-hotness");
469     }
470   }
471
472   // It seems that the 'e' option is completely ignored for dynamic executables
473   // (the default), and with static executables, the last one wins, as expected.
474   Args.AddAllArgs(CmdArgs, {options::OPT_d_Flag, options::OPT_s, options::OPT_t,
475                             options::OPT_Z_Flag, options::OPT_u_Group,
476                             options::OPT_e, options::OPT_r});
477
478   // Forward -ObjC when either -ObjC or -ObjC++ is used, to force loading
479   // members of static archive libraries which implement Objective-C classes or
480   // categories.
481   if (Args.hasArg(options::OPT_ObjC) || Args.hasArg(options::OPT_ObjCXX))
482     CmdArgs.push_back("-ObjC");
483
484   CmdArgs.push_back("-o");
485   CmdArgs.push_back(Output.getFilename());
486
487   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
488     getMachOToolChain().addStartObjectFileArgs(Args, CmdArgs);
489
490   // SafeStack requires its own runtime libraries
491   // These libraries should be linked first, to make sure the
492   // __safestack_init constructor executes before everything else
493   if (getToolChain().getSanitizerArgs().needsSafeStackRt()) {
494     getMachOToolChain().AddLinkRuntimeLib(Args, CmdArgs,
495                                           "libclang_rt.safestack_osx.a",
496                                           /*AlwaysLink=*/true);
497   }
498
499   Args.AddAllArgs(CmdArgs, options::OPT_L);
500
501   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs, JA);
502   // Build the input file for -filelist (list of linker input files) in case we
503   // need it later
504   for (const auto &II : Inputs) {
505     if (!II.isFilename()) {
506       // This is a linker input argument.
507       // We cannot mix input arguments and file names in a -filelist input, thus
508       // we prematurely stop our list (remaining files shall be passed as
509       // arguments).
510       if (InputFileList.size() > 0)
511         break;
512
513       continue;
514     }
515
516     InputFileList.push_back(II.getFilename());
517   }
518
519   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs))
520     addOpenMPRuntime(CmdArgs, getToolChain(), Args);
521
522   if (isObjCRuntimeLinked(Args) &&
523       !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
524     // We use arclite library for both ARC and subscripting support.
525     getMachOToolChain().AddLinkARCArgs(Args, CmdArgs);
526
527     CmdArgs.push_back("-framework");
528     CmdArgs.push_back("Foundation");
529     // Link libobj.
530     CmdArgs.push_back("-lobjc");
531   }
532
533   if (LinkingOutput) {
534     CmdArgs.push_back("-arch_multiple");
535     CmdArgs.push_back("-final_output");
536     CmdArgs.push_back(LinkingOutput);
537   }
538
539   if (Args.hasArg(options::OPT_fnested_functions))
540     CmdArgs.push_back("-allow_stack_execute");
541
542   getMachOToolChain().addProfileRTLibs(Args, CmdArgs);
543
544   if (unsigned Parallelism =
545           getLTOParallelism(Args, getToolChain().getDriver())) {
546     CmdArgs.push_back("-mllvm");
547     CmdArgs.push_back(
548         Args.MakeArgString(Twine("-threads=") + llvm::to_string(Parallelism)));
549   }
550
551   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
552     if (getToolChain().getDriver().CCCIsCXX())
553       getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
554
555     // link_ssp spec is empty.
556
557     // Let the tool chain choose which runtime library to link.
558     getMachOToolChain().AddLinkRuntimeLibArgs(Args, CmdArgs);
559
560     // No need to do anything for pthreads. Claim argument to avoid warning.
561     Args.ClaimAllArgs(options::OPT_pthread);
562     Args.ClaimAllArgs(options::OPT_pthreads);
563   }
564
565   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
566     // endfile_spec is empty.
567   }
568
569   Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
570   Args.AddAllArgs(CmdArgs, options::OPT_F);
571
572   // -iframework should be forwarded as -F.
573   for (const Arg *A : Args.filtered(options::OPT_iframework))
574     CmdArgs.push_back(Args.MakeArgString(std::string("-F") + A->getValue()));
575
576   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
577     if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
578       if (A->getValue() == StringRef("Accelerate")) {
579         CmdArgs.push_back("-framework");
580         CmdArgs.push_back("Accelerate");
581       }
582     }
583   }
584
585   const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
586   std::unique_ptr<Command> Cmd =
587       llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs);
588   Cmd->setInputFileList(std::move(InputFileList));
589   C.addCommand(std::move(Cmd));
590 }
591
592 void darwin::Lipo::ConstructJob(Compilation &C, const JobAction &JA,
593                                 const InputInfo &Output,
594                                 const InputInfoList &Inputs,
595                                 const ArgList &Args,
596                                 const char *LinkingOutput) const {
597   ArgStringList CmdArgs;
598
599   CmdArgs.push_back("-create");
600   assert(Output.isFilename() && "Unexpected lipo output.");
601
602   CmdArgs.push_back("-output");
603   CmdArgs.push_back(Output.getFilename());
604
605   for (const auto &II : Inputs) {
606     assert(II.isFilename() && "Unexpected lipo input.");
607     CmdArgs.push_back(II.getFilename());
608   }
609
610   const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("lipo"));
611   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
612 }
613
614 void darwin::Dsymutil::ConstructJob(Compilation &C, const JobAction &JA,
615                                     const InputInfo &Output,
616                                     const InputInfoList &Inputs,
617                                     const ArgList &Args,
618                                     const char *LinkingOutput) const {
619   ArgStringList CmdArgs;
620
621   CmdArgs.push_back("-o");
622   CmdArgs.push_back(Output.getFilename());
623
624   assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
625   const InputInfo &Input = Inputs[0];
626   assert(Input.isFilename() && "Unexpected dsymutil input.");
627   CmdArgs.push_back(Input.getFilename());
628
629   const char *Exec =
630       Args.MakeArgString(getToolChain().GetProgramPath("dsymutil"));
631   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
632 }
633
634 void darwin::VerifyDebug::ConstructJob(Compilation &C, const JobAction &JA,
635                                        const InputInfo &Output,
636                                        const InputInfoList &Inputs,
637                                        const ArgList &Args,
638                                        const char *LinkingOutput) const {
639   ArgStringList CmdArgs;
640   CmdArgs.push_back("--verify");
641   CmdArgs.push_back("--debug-info");
642   CmdArgs.push_back("--eh-frame");
643   CmdArgs.push_back("--quiet");
644
645   assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
646   const InputInfo &Input = Inputs[0];
647   assert(Input.isFilename() && "Unexpected verify input");
648
649   // Grabbing the output of the earlier dsymutil run.
650   CmdArgs.push_back(Input.getFilename());
651
652   const char *Exec =
653       Args.MakeArgString(getToolChain().GetProgramPath("dwarfdump"));
654   C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
655 }
656
657 MachO::MachO(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
658     : ToolChain(D, Triple, Args) {
659   // We expect 'as', 'ld', etc. to be adjacent to our install dir.
660   getProgramPaths().push_back(getDriver().getInstalledDir());
661   if (getDriver().getInstalledDir() != getDriver().Dir)
662     getProgramPaths().push_back(getDriver().Dir);
663 }
664
665 /// Darwin - Darwin tool chain for i386 and x86_64.
666 Darwin::Darwin(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
667     : MachO(D, Triple, Args), TargetInitialized(false),
668       CudaInstallation(D, Triple, Args) {}
669
670 types::ID MachO::LookupTypeForExtension(StringRef Ext) const {
671   types::ID Ty = types::lookupTypeForExtension(Ext);
672
673   // Darwin always preprocesses assembly files (unless -x is used explicitly).
674   if (Ty == types::TY_PP_Asm)
675     return types::TY_Asm;
676
677   return Ty;
678 }
679
680 bool MachO::HasNativeLLVMSupport() const { return true; }
681
682 ToolChain::CXXStdlibType Darwin::GetDefaultCXXStdlibType() const {
683   // Default to use libc++ on OS X 10.9+ and iOS 7+.
684   if ((isTargetMacOS() && !isMacosxVersionLT(10, 9)) ||
685        (isTargetIOSBased() && !isIPhoneOSVersionLT(7, 0)) ||
686        isTargetWatchOSBased())
687     return ToolChain::CST_Libcxx;
688
689   return ToolChain::CST_Libstdcxx;
690 }
691
692 /// Darwin provides an ARC runtime starting in MacOS X 10.7 and iOS 5.0.
693 ObjCRuntime Darwin::getDefaultObjCRuntime(bool isNonFragile) const {
694   if (isTargetWatchOSBased())
695     return ObjCRuntime(ObjCRuntime::WatchOS, TargetVersion);
696   if (isTargetIOSBased())
697     return ObjCRuntime(ObjCRuntime::iOS, TargetVersion);
698   if (isNonFragile)
699     return ObjCRuntime(ObjCRuntime::MacOSX, TargetVersion);
700   return ObjCRuntime(ObjCRuntime::FragileMacOSX, TargetVersion);
701 }
702
703 /// Darwin provides a blocks runtime starting in MacOS X 10.6 and iOS 3.2.
704 bool Darwin::hasBlocksRuntime() const {
705   if (isTargetWatchOSBased())
706     return true;
707   else if (isTargetIOSBased())
708     return !isIPhoneOSVersionLT(3, 2);
709   else {
710     assert(isTargetMacOS() && "unexpected darwin target");
711     return !isMacosxVersionLT(10, 6);
712   }
713 }
714
715 void Darwin::AddCudaIncludeArgs(const ArgList &DriverArgs,
716                                 ArgStringList &CC1Args) const {
717   CudaInstallation.AddCudaIncludeArgs(DriverArgs, CC1Args);
718 }
719
720 // This is just a MachO name translation routine and there's no
721 // way to join this into ARMTargetParser without breaking all
722 // other assumptions. Maybe MachO should consider standardising
723 // their nomenclature.
724 static const char *ArmMachOArchName(StringRef Arch) {
725   return llvm::StringSwitch<const char *>(Arch)
726       .Case("armv6k", "armv6")
727       .Case("armv6m", "armv6m")
728       .Case("armv5tej", "armv5")
729       .Case("xscale", "xscale")
730       .Case("armv4t", "armv4t")
731       .Case("armv7", "armv7")
732       .Cases("armv7a", "armv7-a", "armv7")
733       .Cases("armv7r", "armv7-r", "armv7")
734       .Cases("armv7em", "armv7e-m", "armv7em")
735       .Cases("armv7k", "armv7-k", "armv7k")
736       .Cases("armv7m", "armv7-m", "armv7m")
737       .Cases("armv7s", "armv7-s", "armv7s")
738       .Default(nullptr);
739 }
740
741 static const char *ArmMachOArchNameCPU(StringRef CPU) {
742   unsigned ArchKind = llvm::ARM::parseCPUArch(CPU);
743   if (ArchKind == llvm::ARM::AK_INVALID)
744     return nullptr;
745   StringRef Arch = llvm::ARM::getArchName(ArchKind);
746
747   // FIXME: Make sure this MachO triple mangling is really necessary.
748   // ARMv5* normalises to ARMv5.
749   if (Arch.startswith("armv5"))
750     Arch = Arch.substr(0, 5);
751   // ARMv6*, except ARMv6M, normalises to ARMv6.
752   else if (Arch.startswith("armv6") && !Arch.endswith("6m"))
753     Arch = Arch.substr(0, 5);
754   // ARMv7A normalises to ARMv7.
755   else if (Arch.endswith("v7a"))
756     Arch = Arch.substr(0, 5);
757   return Arch.data();
758 }
759
760 StringRef MachO::getMachOArchName(const ArgList &Args) const {
761   switch (getTriple().getArch()) {
762   default:
763     return getDefaultUniversalArchName();
764
765   case llvm::Triple::aarch64:
766     return "arm64";
767
768   case llvm::Triple::thumb:
769   case llvm::Triple::arm:
770     if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_march_EQ))
771       if (const char *Arch = ArmMachOArchName(A->getValue()))
772         return Arch;
773
774     if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
775       if (const char *Arch = ArmMachOArchNameCPU(A->getValue()))
776         return Arch;
777
778     return "arm";
779   }
780 }
781
782 Darwin::~Darwin() {}
783
784 MachO::~MachO() {}
785
786 std::string Darwin::ComputeEffectiveClangTriple(const ArgList &Args,
787                                                 types::ID InputType) const {
788   llvm::Triple Triple(ComputeLLVMTriple(Args, InputType));
789
790   // If the target isn't initialized (e.g., an unknown Darwin platform, return
791   // the default triple).
792   if (!isTargetInitialized())
793     return Triple.getTriple();
794
795   SmallString<16> Str;
796   if (isTargetWatchOSBased())
797     Str += "watchos";
798   else if (isTargetTvOSBased())
799     Str += "tvos";
800   else if (isTargetIOSBased())
801     Str += "ios";
802   else
803     Str += "macosx";
804   Str += getTargetVersion().getAsString();
805   Triple.setOSName(Str);
806
807   return Triple.getTriple();
808 }
809
810 Tool *MachO::getTool(Action::ActionClass AC) const {
811   switch (AC) {
812   case Action::LipoJobClass:
813     if (!Lipo)
814       Lipo.reset(new tools::darwin::Lipo(*this));
815     return Lipo.get();
816   case Action::DsymutilJobClass:
817     if (!Dsymutil)
818       Dsymutil.reset(new tools::darwin::Dsymutil(*this));
819     return Dsymutil.get();
820   case Action::VerifyDebugInfoJobClass:
821     if (!VerifyDebug)
822       VerifyDebug.reset(new tools::darwin::VerifyDebug(*this));
823     return VerifyDebug.get();
824   default:
825     return ToolChain::getTool(AC);
826   }
827 }
828
829 Tool *MachO::buildLinker() const { return new tools::darwin::Linker(*this); }
830
831 Tool *MachO::buildAssembler() const {
832   return new tools::darwin::Assembler(*this);
833 }
834
835 DarwinClang::DarwinClang(const Driver &D, const llvm::Triple &Triple,
836                          const ArgList &Args)
837     : Darwin(D, Triple, Args) {}
838
839 void DarwinClang::addClangWarningOptions(ArgStringList &CC1Args) const {
840   // For modern targets, promote certain warnings to errors.
841   if (isTargetWatchOSBased() || getTriple().isArch64Bit()) {
842     // Always enable -Wdeprecated-objc-isa-usage and promote it
843     // to an error.
844     CC1Args.push_back("-Wdeprecated-objc-isa-usage");
845     CC1Args.push_back("-Werror=deprecated-objc-isa-usage");
846
847     // For iOS and watchOS, also error about implicit function declarations,
848     // as that can impact calling conventions.
849     if (!isTargetMacOS())
850       CC1Args.push_back("-Werror=implicit-function-declaration");
851   }
852 }
853
854 void DarwinClang::AddLinkARCArgs(const ArgList &Args,
855                                  ArgStringList &CmdArgs) const {
856   // Avoid linking compatibility stubs on i386 mac.
857   if (isTargetMacOS() && getArch() == llvm::Triple::x86)
858     return;
859
860   ObjCRuntime runtime = getDefaultObjCRuntime(/*nonfragile*/ true);
861
862   if ((runtime.hasNativeARC() || !isObjCAutoRefCount(Args)) &&
863       runtime.hasSubscripting())
864     return;
865
866   CmdArgs.push_back("-force_load");
867   SmallString<128> P(getDriver().ClangExecutable);
868   llvm::sys::path::remove_filename(P); // 'clang'
869   llvm::sys::path::remove_filename(P); // 'bin'
870   llvm::sys::path::append(P, "lib", "arc", "libarclite_");
871   // Mash in the platform.
872   if (isTargetWatchOSSimulator())
873     P += "watchsimulator";
874   else if (isTargetWatchOS())
875     P += "watchos";
876   else if (isTargetTvOSSimulator())
877     P += "appletvsimulator";
878   else if (isTargetTvOS())
879     P += "appletvos";
880   else if (isTargetIOSSimulator())
881     P += "iphonesimulator";
882   else if (isTargetIPhoneOS())
883     P += "iphoneos";
884   else
885     P += "macosx";
886   P += ".a";
887
888   CmdArgs.push_back(Args.MakeArgString(P));
889 }
890
891 unsigned DarwinClang::GetDefaultDwarfVersion() const {
892   // Default to use DWARF 2 on OS X 10.10 / iOS 8 and lower.
893   if ((isTargetMacOS() && isMacosxVersionLT(10, 11)) ||
894       (isTargetIOSBased() && isIPhoneOSVersionLT(9)))
895     return 2;
896   return 4;
897 }
898
899 void MachO::AddLinkRuntimeLib(const ArgList &Args, ArgStringList &CmdArgs,
900                               StringRef DarwinLibName, bool AlwaysLink,
901                               bool IsEmbedded, bool AddRPath) const {
902   SmallString<128> Dir(getDriver().ResourceDir);
903   llvm::sys::path::append(Dir, "lib", 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 (AlwaysLink || getVFS().exists(P))
912     CmdArgs.push_back(Args.MakeArgString(P));
913
914   // Adding the rpaths might negatively interact when other rpaths are involved,
915   // so we should make sure we add the rpaths last, after all user-specified
916   // rpaths. This is currently true from this place, but we need to be
917   // careful if this function is ever called before user's rpaths are emitted.
918   if (AddRPath) {
919     assert(DarwinLibName.endswith(".dylib") && "must be a dynamic library");
920
921     // Add @executable_path to rpath to support having the dylib copied with
922     // the executable.
923     CmdArgs.push_back("-rpath");
924     CmdArgs.push_back("@executable_path");
925
926     // Add the path to the resource dir to rpath to support using the dylib
927     // from the default location without copying.
928     CmdArgs.push_back("-rpath");
929     CmdArgs.push_back(Args.MakeArgString(Dir));
930   }
931 }
932
933 StringRef Darwin::getPlatformFamily() const {
934   switch (TargetPlatform) {
935     case DarwinPlatformKind::MacOS:
936       return "MacOSX";
937     case DarwinPlatformKind::IPhoneOS:
938     case DarwinPlatformKind::IPhoneOSSimulator:
939       return "iPhone";
940     case DarwinPlatformKind::TvOS:
941     case DarwinPlatformKind::TvOSSimulator:
942       return "AppleTV";
943     case DarwinPlatformKind::WatchOS:
944     case DarwinPlatformKind::WatchOSSimulator:
945       return "Watch";
946   }
947   llvm_unreachable("Unsupported platform");
948 }
949
950 StringRef Darwin::getSDKName(StringRef isysroot) {
951   // Assume SDK has path: SOME_PATH/SDKs/PlatformXX.YY.sdk
952   llvm::sys::path::const_iterator SDKDir;
953   auto BeginSDK = llvm::sys::path::begin(isysroot);
954   auto EndSDK = llvm::sys::path::end(isysroot);
955   for (auto IT = BeginSDK; IT != EndSDK; ++IT) {
956     StringRef SDK = *IT;
957     if (SDK.endswith(".sdk"))
958       return SDK.slice(0, SDK.size() - 4);
959   }
960   return "";
961 }
962
963 StringRef Darwin::getOSLibraryNameSuffix() const {
964   switch(TargetPlatform) {
965   case DarwinPlatformKind::MacOS:
966     return "osx";
967   case DarwinPlatformKind::IPhoneOS:
968     return "ios";
969   case DarwinPlatformKind::IPhoneOSSimulator:
970     return "iossim";
971   case DarwinPlatformKind::TvOS:
972     return "tvos";
973   case DarwinPlatformKind::TvOSSimulator:
974     return "tvossim";
975   case DarwinPlatformKind::WatchOS:
976     return "watchos";
977   case DarwinPlatformKind::WatchOSSimulator:
978     return "watchossim";
979   }
980   llvm_unreachable("Unsupported platform");
981 }
982
983 void Darwin::addProfileRTLibs(const ArgList &Args,
984                               ArgStringList &CmdArgs) const {
985   if (!needsProfileRT(Args)) return;
986
987   AddLinkRuntimeLib(Args, CmdArgs, (Twine("libclang_rt.profile_") +
988        getOSLibraryNameSuffix() + ".a").str(),
989                     /*AlwaysLink*/ true);
990 }
991
992 void DarwinClang::AddLinkSanitizerLibArgs(const ArgList &Args,
993                                           ArgStringList &CmdArgs,
994                                           StringRef Sanitizer) const {
995   AddLinkRuntimeLib(
996       Args, CmdArgs,
997       (Twine("libclang_rt.") + Sanitizer + "_" +
998        getOSLibraryNameSuffix() + "_dynamic.dylib").str(),
999       /*AlwaysLink*/ true, /*IsEmbedded*/ false,
1000       /*AddRPath*/ true);
1001 }
1002
1003 ToolChain::RuntimeLibType DarwinClang::GetRuntimeLibType(
1004     const ArgList &Args) const {
1005   if (Arg* A = Args.getLastArg(options::OPT_rtlib_EQ)) {
1006     StringRef Value = A->getValue();
1007     if (Value != "compiler-rt")
1008       getDriver().Diag(clang::diag::err_drv_unsupported_rtlib_for_platform)
1009           << Value << "darwin";
1010   }
1011
1012   return ToolChain::RLT_CompilerRT;
1013 }
1014
1015 void DarwinClang::AddLinkRuntimeLibArgs(const ArgList &Args,
1016                                         ArgStringList &CmdArgs) const {
1017   // Call once to ensure diagnostic is printed if wrong value was specified
1018   GetRuntimeLibType(Args);
1019
1020   // Darwin doesn't support real static executables, don't link any runtime
1021   // libraries with -static.
1022   if (Args.hasArg(options::OPT_static) ||
1023       Args.hasArg(options::OPT_fapple_kext) ||
1024       Args.hasArg(options::OPT_mkernel))
1025     return;
1026
1027   // Reject -static-libgcc for now, we can deal with this when and if someone
1028   // cares. This is useful in situations where someone wants to statically link
1029   // something like libstdc++, and needs its runtime support routines.
1030   if (const Arg *A = Args.getLastArg(options::OPT_static_libgcc)) {
1031     getDriver().Diag(diag::err_drv_unsupported_opt) << A->getAsString(Args);
1032     return;
1033   }
1034
1035   const SanitizerArgs &Sanitize = getSanitizerArgs();
1036   if (Sanitize.needsAsanRt())
1037     AddLinkSanitizerLibArgs(Args, CmdArgs, "asan");
1038   if (Sanitize.needsUbsanRt())
1039     AddLinkSanitizerLibArgs(Args, CmdArgs, "ubsan");
1040   if (Sanitize.needsTsanRt())
1041     AddLinkSanitizerLibArgs(Args, CmdArgs, "tsan");
1042   if (Sanitize.needsStatsRt()) {
1043     StringRef OS = isTargetMacOS() ? "osx" : "iossim";
1044     AddLinkRuntimeLib(Args, CmdArgs,
1045                       (Twine("libclang_rt.stats_client_") + OS + ".a").str(),
1046                       /*AlwaysLink=*/true);
1047     AddLinkSanitizerLibArgs(Args, CmdArgs, "stats");
1048   }
1049   if (Sanitize.needsEsanRt())
1050     AddLinkSanitizerLibArgs(Args, CmdArgs, "esan");
1051
1052   // Otherwise link libSystem, then the dynamic runtime library, and finally any
1053   // target specific static runtime library.
1054   CmdArgs.push_back("-lSystem");
1055
1056   // Select the dynamic runtime library and the target specific static library.
1057   if (isTargetWatchOSBased()) {
1058     // We currently always need a static runtime library for watchOS.
1059     AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.watchos.a");
1060   } else if (isTargetTvOSBased()) {
1061     // We currently always need a static runtime library for tvOS.
1062     AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.tvos.a");
1063   } else if (isTargetIOSBased()) {
1064     // If we are compiling as iOS / simulator, don't attempt to link libgcc_s.1,
1065     // it never went into the SDK.
1066     // Linking against libgcc_s.1 isn't needed for iOS 5.0+
1067     if (isIPhoneOSVersionLT(5, 0) && !isTargetIOSSimulator() &&
1068         getTriple().getArch() != llvm::Triple::aarch64)
1069       CmdArgs.push_back("-lgcc_s.1");
1070
1071     // We currently always need a static runtime library for iOS.
1072     AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.ios.a");
1073   } else {
1074     assert(isTargetMacOS() && "unexpected non MacOS platform");
1075     // The dynamic runtime library was merged with libSystem for 10.6 and
1076     // beyond; only 10.4 and 10.5 need an additional runtime library.
1077     if (isMacosxVersionLT(10, 5))
1078       CmdArgs.push_back("-lgcc_s.10.4");
1079     else if (isMacosxVersionLT(10, 6))
1080       CmdArgs.push_back("-lgcc_s.10.5");
1081
1082     // Originally for OS X, we thought we would only need a static runtime
1083     // library when targeting 10.4, to provide versions of the static functions
1084     // which were omitted from 10.4.dylib. This led to the creation of the 10.4
1085     // builtins library.
1086     //
1087     // Unfortunately, that turned out to not be true, because Darwin system
1088     // headers can still use eprintf on i386, and it is not exported from
1089     // libSystem. Therefore, we still must provide a runtime library just for
1090     // the tiny tiny handful of projects that *might* use that symbol.
1091     //
1092     // Then over time, we figured out it was useful to add more things to the
1093     // runtime so we created libclang_rt.osx.a to provide new functions when
1094     // deploying to old OS builds, and for a long time we had both eprintf and
1095     // osx builtin libraries. Which just seems excessive. So with PR 28855, we
1096     // are removing the eprintf library and expecting eprintf to be provided by
1097     // the OS X builtins library.
1098     if (isMacosxVersionLT(10, 5))
1099       AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.10.4.a");
1100     else
1101       AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.osx.a");
1102   }
1103 }
1104
1105 void Darwin::AddDeploymentTarget(DerivedArgList &Args) const {
1106   const OptTable &Opts = getDriver().getOpts();
1107
1108   // Support allowing the SDKROOT environment variable used by xcrun and other
1109   // Xcode tools to define the default sysroot, by making it the default for
1110   // isysroot.
1111   if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
1112     // Warn if the path does not exist.
1113     if (!getVFS().exists(A->getValue()))
1114       getDriver().Diag(clang::diag::warn_missing_sysroot) << A->getValue();
1115   } else {
1116     if (char *env = ::getenv("SDKROOT")) {
1117       // We only use this value as the default if it is an absolute path,
1118       // exists, and it is not the root path.
1119       if (llvm::sys::path::is_absolute(env) && getVFS().exists(env) &&
1120           StringRef(env) != "/") {
1121         Args.append(Args.MakeSeparateArg(
1122             nullptr, Opts.getOption(options::OPT_isysroot), env));
1123       }
1124     }
1125   }
1126
1127   Arg *OSXVersion = Args.getLastArg(options::OPT_mmacosx_version_min_EQ);
1128   Arg *iOSVersion = Args.getLastArg(options::OPT_miphoneos_version_min_EQ,
1129                                     options::OPT_mios_simulator_version_min_EQ);
1130   Arg *TvOSVersion =
1131       Args.getLastArg(options::OPT_mtvos_version_min_EQ,
1132                       options::OPT_mtvos_simulator_version_min_EQ);
1133   Arg *WatchOSVersion =
1134       Args.getLastArg(options::OPT_mwatchos_version_min_EQ,
1135                       options::OPT_mwatchos_simulator_version_min_EQ);
1136
1137   // Add a macro to differentiate between m(iphone|tv|watch)os-version-min=X.Y and
1138   // -m(iphone|tv|watch)simulator-version-min=X.Y.
1139   if (Args.hasArg(options::OPT_mios_simulator_version_min_EQ) ||
1140       Args.hasArg(options::OPT_mtvos_simulator_version_min_EQ) ||
1141       Args.hasArg(options::OPT_mwatchos_simulator_version_min_EQ))
1142     Args.append(Args.MakeSeparateArg(nullptr, Opts.getOption(options::OPT_D),
1143                                      " __APPLE_EMBEDDED_SIMULATOR__=1"));
1144
1145   if (OSXVersion && (iOSVersion || TvOSVersion || WatchOSVersion)) {
1146     getDriver().Diag(diag::err_drv_argument_not_allowed_with)
1147         << OSXVersion->getAsString(Args)
1148         << (iOSVersion ? iOSVersion :
1149             TvOSVersion ? TvOSVersion : WatchOSVersion)->getAsString(Args);
1150     iOSVersion = TvOSVersion = WatchOSVersion = nullptr;
1151   } else if (iOSVersion && (TvOSVersion || WatchOSVersion)) {
1152     getDriver().Diag(diag::err_drv_argument_not_allowed_with)
1153         << iOSVersion->getAsString(Args)
1154         << (TvOSVersion ? TvOSVersion : WatchOSVersion)->getAsString(Args);
1155     TvOSVersion = WatchOSVersion = nullptr;
1156   } else if (TvOSVersion && WatchOSVersion) {
1157      getDriver().Diag(diag::err_drv_argument_not_allowed_with)
1158         << TvOSVersion->getAsString(Args)
1159         << WatchOSVersion->getAsString(Args);
1160     WatchOSVersion = nullptr;
1161   } else if (!OSXVersion && !iOSVersion && !TvOSVersion && !WatchOSVersion) {
1162     // If no deployment target was specified on the command line, check for
1163     // environment defines.
1164     std::string OSXTarget;
1165     std::string iOSTarget;
1166     std::string TvOSTarget;
1167     std::string WatchOSTarget;
1168
1169     if (char *env = ::getenv("MACOSX_DEPLOYMENT_TARGET"))
1170       OSXTarget = env;
1171     if (char *env = ::getenv("IPHONEOS_DEPLOYMENT_TARGET"))
1172       iOSTarget = env;
1173     if (char *env = ::getenv("TVOS_DEPLOYMENT_TARGET"))
1174       TvOSTarget = env;
1175     if (char *env = ::getenv("WATCHOS_DEPLOYMENT_TARGET"))
1176       WatchOSTarget = env;
1177
1178     // If there is no command-line argument to specify the Target version and
1179     // no environment variable defined, see if we can set the default based
1180     // on -isysroot.
1181     if (OSXTarget.empty() && iOSTarget.empty() && WatchOSTarget.empty() &&
1182         TvOSTarget.empty() && Args.hasArg(options::OPT_isysroot)) {
1183       if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
1184         StringRef isysroot = A->getValue();
1185         StringRef SDK = getSDKName(isysroot);
1186         if (SDK.size() > 0) {
1187           // Slice the version number out.
1188           // Version number is between the first and the last number.
1189           size_t StartVer = SDK.find_first_of("0123456789");
1190           size_t EndVer = SDK.find_last_of("0123456789");
1191           if (StartVer != StringRef::npos && EndVer > StartVer) {
1192             StringRef Version = SDK.slice(StartVer, EndVer + 1);
1193             if (SDK.startswith("iPhoneOS") ||
1194                 SDK.startswith("iPhoneSimulator"))
1195               iOSTarget = Version;
1196             else if (SDK.startswith("MacOSX"))
1197               OSXTarget = Version;
1198             else if (SDK.startswith("WatchOS") ||
1199                      SDK.startswith("WatchSimulator"))
1200               WatchOSTarget = Version;
1201             else if (SDK.startswith("AppleTVOS") ||
1202                      SDK.startswith("AppleTVSimulator"))
1203               TvOSTarget = Version;
1204           }
1205         }
1206       }
1207     }
1208
1209     // If no OSX or iOS target has been specified, try to guess platform
1210     // from arch name and compute the version from the triple.
1211     if (OSXTarget.empty() && iOSTarget.empty() && TvOSTarget.empty() &&
1212         WatchOSTarget.empty()) {
1213       StringRef MachOArchName = getMachOArchName(Args);
1214       unsigned Major, Minor, Micro;
1215       if (MachOArchName == "armv7" || MachOArchName == "armv7s" ||
1216           MachOArchName == "arm64") {
1217         getTriple().getiOSVersion(Major, Minor, Micro);
1218         llvm::raw_string_ostream(iOSTarget) << Major << '.' << Minor << '.'
1219                                             << Micro;
1220       } else if (MachOArchName == "armv7k") {
1221         getTriple().getWatchOSVersion(Major, Minor, Micro);
1222         llvm::raw_string_ostream(WatchOSTarget) << Major << '.' << Minor << '.'
1223                                                 << Micro;
1224       } else if (MachOArchName != "armv6m" && MachOArchName != "armv7m" &&
1225                  MachOArchName != "armv7em") {
1226         if (!getTriple().getMacOSXVersion(Major, Minor, Micro)) {
1227           getDriver().Diag(diag::err_drv_invalid_darwin_version)
1228               << getTriple().getOSName();
1229         }
1230         llvm::raw_string_ostream(OSXTarget) << Major << '.' << Minor << '.'
1231                                             << Micro;
1232       }
1233     }
1234
1235     // Do not allow conflicts with the watchOS target.
1236     if (!WatchOSTarget.empty() && (!iOSTarget.empty() || !TvOSTarget.empty())) {
1237       getDriver().Diag(diag::err_drv_conflicting_deployment_targets)
1238         << "WATCHOS_DEPLOYMENT_TARGET"
1239         << (!iOSTarget.empty() ? "IPHONEOS_DEPLOYMENT_TARGET" :
1240             "TVOS_DEPLOYMENT_TARGET");
1241     }
1242
1243     // Do not allow conflicts with the tvOS target.
1244     if (!TvOSTarget.empty() && !iOSTarget.empty()) {
1245       getDriver().Diag(diag::err_drv_conflicting_deployment_targets)
1246         << "TVOS_DEPLOYMENT_TARGET"
1247         << "IPHONEOS_DEPLOYMENT_TARGET";
1248     }
1249
1250     // Allow conflicts among OSX and iOS for historical reasons, but choose the
1251     // default platform.
1252     if (!OSXTarget.empty() && (!iOSTarget.empty() ||
1253                                !WatchOSTarget.empty() ||
1254                                !TvOSTarget.empty())) {
1255       if (getTriple().getArch() == llvm::Triple::arm ||
1256           getTriple().getArch() == llvm::Triple::aarch64 ||
1257           getTriple().getArch() == llvm::Triple::thumb)
1258         OSXTarget = "";
1259       else
1260         iOSTarget = WatchOSTarget = TvOSTarget = "";
1261     }
1262
1263     if (!OSXTarget.empty()) {
1264       const Option O = Opts.getOption(options::OPT_mmacosx_version_min_EQ);
1265       OSXVersion = Args.MakeJoinedArg(nullptr, O, OSXTarget);
1266       Args.append(OSXVersion);
1267     } else if (!iOSTarget.empty()) {
1268       const Option O = Opts.getOption(options::OPT_miphoneos_version_min_EQ);
1269       iOSVersion = Args.MakeJoinedArg(nullptr, O, iOSTarget);
1270       Args.append(iOSVersion);
1271     } else if (!TvOSTarget.empty()) {
1272       const Option O = Opts.getOption(options::OPT_mtvos_version_min_EQ);
1273       TvOSVersion = Args.MakeJoinedArg(nullptr, O, TvOSTarget);
1274       Args.append(TvOSVersion);
1275     } else if (!WatchOSTarget.empty()) {
1276       const Option O = Opts.getOption(options::OPT_mwatchos_version_min_EQ);
1277       WatchOSVersion = Args.MakeJoinedArg(nullptr, O, WatchOSTarget);
1278       Args.append(WatchOSVersion);
1279     }
1280   }
1281
1282   DarwinPlatformKind Platform;
1283   if (OSXVersion)
1284     Platform = MacOS;
1285   else if (iOSVersion)
1286     Platform = IPhoneOS;
1287   else if (TvOSVersion)
1288     Platform = TvOS;
1289   else if (WatchOSVersion)
1290     Platform = WatchOS;
1291   else
1292     llvm_unreachable("Unable to infer Darwin variant");
1293
1294   // Set the tool chain target information.
1295   unsigned Major, Minor, Micro;
1296   bool HadExtra;
1297   if (Platform == MacOS) {
1298     assert((!iOSVersion && !TvOSVersion && !WatchOSVersion) &&
1299            "Unknown target platform!");
1300     if (!Driver::GetReleaseVersion(OSXVersion->getValue(), Major, Minor, Micro,
1301                                    HadExtra) ||
1302         HadExtra || Major != 10 || Minor >= 100 || Micro >= 100)
1303       getDriver().Diag(diag::err_drv_invalid_version_number)
1304           << OSXVersion->getAsString(Args);
1305   } else if (Platform == IPhoneOS) {
1306     assert(iOSVersion && "Unknown target platform!");
1307     if (!Driver::GetReleaseVersion(iOSVersion->getValue(), Major, Minor, Micro,
1308                                    HadExtra) ||
1309         HadExtra || Major >= 100 || Minor >= 100 || Micro >= 100)
1310       getDriver().Diag(diag::err_drv_invalid_version_number)
1311           << iOSVersion->getAsString(Args);
1312   } else if (Platform == TvOS) {
1313     if (!Driver::GetReleaseVersion(TvOSVersion->getValue(), Major, Minor,
1314                                    Micro, HadExtra) || HadExtra ||
1315         Major >= 100 || Minor >= 100 || Micro >= 100)
1316       getDriver().Diag(diag::err_drv_invalid_version_number)
1317           << TvOSVersion->getAsString(Args);
1318   } else if (Platform == WatchOS) {
1319     if (!Driver::GetReleaseVersion(WatchOSVersion->getValue(), Major, Minor,
1320                                    Micro, HadExtra) || HadExtra ||
1321         Major >= 10 || Minor >= 100 || Micro >= 100)
1322       getDriver().Diag(diag::err_drv_invalid_version_number)
1323           << WatchOSVersion->getAsString(Args);
1324   } else
1325     llvm_unreachable("unknown kind of Darwin platform");
1326
1327   // Recognize iOS targets with an x86 architecture as the iOS simulator.
1328   if (iOSVersion && (getTriple().getArch() == llvm::Triple::x86 ||
1329                      getTriple().getArch() == llvm::Triple::x86_64))
1330     Platform = IPhoneOSSimulator;
1331   if (TvOSVersion && (getTriple().getArch() == llvm::Triple::x86 ||
1332                       getTriple().getArch() == llvm::Triple::x86_64))
1333     Platform = TvOSSimulator;
1334   if (WatchOSVersion && (getTriple().getArch() == llvm::Triple::x86 ||
1335                          getTriple().getArch() == llvm::Triple::x86_64))
1336     Platform = WatchOSSimulator;
1337
1338   setTarget(Platform, Major, Minor, Micro);
1339
1340   if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
1341     StringRef SDK = getSDKName(A->getValue());
1342     if (SDK.size() > 0) {
1343       size_t StartVer = SDK.find_first_of("0123456789");
1344       StringRef SDKName = SDK.slice(0, StartVer);
1345       if (!SDKName.startswith(getPlatformFamily()))
1346         getDriver().Diag(diag::warn_incompatible_sysroot)
1347             << SDKName << getPlatformFamily();
1348     }
1349   }
1350 }
1351
1352 void DarwinClang::AddCXXStdlibLibArgs(const ArgList &Args,
1353                                       ArgStringList &CmdArgs) const {
1354   CXXStdlibType Type = GetCXXStdlibType(Args);
1355
1356   switch (Type) {
1357   case ToolChain::CST_Libcxx:
1358     CmdArgs.push_back("-lc++");
1359     break;
1360
1361   case ToolChain::CST_Libstdcxx:
1362     // Unfortunately, -lstdc++ doesn't always exist in the standard search path;
1363     // it was previously found in the gcc lib dir. However, for all the Darwin
1364     // platforms we care about it was -lstdc++.6, so we search for that
1365     // explicitly if we can't see an obvious -lstdc++ candidate.
1366
1367     // Check in the sysroot first.
1368     if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
1369       SmallString<128> P(A->getValue());
1370       llvm::sys::path::append(P, "usr", "lib", "libstdc++.dylib");
1371
1372       if (!getVFS().exists(P)) {
1373         llvm::sys::path::remove_filename(P);
1374         llvm::sys::path::append(P, "libstdc++.6.dylib");
1375         if (getVFS().exists(P)) {
1376           CmdArgs.push_back(Args.MakeArgString(P));
1377           return;
1378         }
1379       }
1380     }
1381
1382     // Otherwise, look in the root.
1383     // FIXME: This should be removed someday when we don't have to care about
1384     // 10.6 and earlier, where /usr/lib/libstdc++.dylib does not exist.
1385     if (!getVFS().exists("/usr/lib/libstdc++.dylib") &&
1386         getVFS().exists("/usr/lib/libstdc++.6.dylib")) {
1387       CmdArgs.push_back("/usr/lib/libstdc++.6.dylib");
1388       return;
1389     }
1390
1391     // Otherwise, let the linker search.
1392     CmdArgs.push_back("-lstdc++");
1393     break;
1394   }
1395 }
1396
1397 void DarwinClang::AddCCKextLibArgs(const ArgList &Args,
1398                                    ArgStringList &CmdArgs) const {
1399   // For Darwin platforms, use the compiler-rt-based support library
1400   // instead of the gcc-provided one (which is also incidentally
1401   // only present in the gcc lib dir, which makes it hard to find).
1402
1403   SmallString<128> P(getDriver().ResourceDir);
1404   llvm::sys::path::append(P, "lib", "darwin");
1405
1406   // Use the newer cc_kext for iOS ARM after 6.0.
1407   if (isTargetWatchOS()) {
1408     llvm::sys::path::append(P, "libclang_rt.cc_kext_watchos.a");
1409   } else if (isTargetTvOS()) {
1410     llvm::sys::path::append(P, "libclang_rt.cc_kext_tvos.a");
1411   } else if (isTargetIPhoneOS()) {
1412     llvm::sys::path::append(P, "libclang_rt.cc_kext_ios.a");
1413   } else {
1414     llvm::sys::path::append(P, "libclang_rt.cc_kext.a");
1415   }
1416
1417   // For now, allow missing resource libraries to support developers who may
1418   // not have compiler-rt checked out or integrated into their build.
1419   if (getVFS().exists(P))
1420     CmdArgs.push_back(Args.MakeArgString(P));
1421 }
1422
1423 DerivedArgList *MachO::TranslateArgs(const DerivedArgList &Args,
1424                                      StringRef BoundArch,
1425                                      Action::OffloadKind) const {
1426   DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
1427   const OptTable &Opts = getDriver().getOpts();
1428
1429   // FIXME: We really want to get out of the tool chain level argument
1430   // translation business, as it makes the driver functionality much
1431   // more opaque. For now, we follow gcc closely solely for the
1432   // purpose of easily achieving feature parity & testability. Once we
1433   // have something that works, we should reevaluate each translation
1434   // and try to push it down into tool specific logic.
1435
1436   for (Arg *A : Args) {
1437     if (A->getOption().matches(options::OPT_Xarch__)) {
1438       // Skip this argument unless the architecture matches either the toolchain
1439       // triple arch, or the arch being bound.
1440       llvm::Triple::ArchType XarchArch =
1441           tools::darwin::getArchTypeForMachOArchName(A->getValue(0));
1442       if (!(XarchArch == getArch() ||
1443             (!BoundArch.empty() &&
1444              XarchArch ==
1445                  tools::darwin::getArchTypeForMachOArchName(BoundArch))))
1446         continue;
1447
1448       Arg *OriginalArg = A;
1449       unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
1450       unsigned Prev = Index;
1451       std::unique_ptr<Arg> XarchArg(Opts.ParseOneArg(Args, Index));
1452
1453       // If the argument parsing failed or more than one argument was
1454       // consumed, the -Xarch_ argument's parameter tried to consume
1455       // extra arguments. Emit an error and ignore.
1456       //
1457       // We also want to disallow any options which would alter the
1458       // driver behavior; that isn't going to work in our model. We
1459       // use isDriverOption() as an approximation, although things
1460       // like -O4 are going to slip through.
1461       if (!XarchArg || Index > Prev + 1) {
1462         getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args)
1463             << A->getAsString(Args);
1464         continue;
1465       } else if (XarchArg->getOption().hasFlag(options::DriverOption)) {
1466         getDriver().Diag(diag::err_drv_invalid_Xarch_argument_isdriver)
1467             << A->getAsString(Args);
1468         continue;
1469       }
1470
1471       XarchArg->setBaseArg(A);
1472
1473       A = XarchArg.release();
1474       DAL->AddSynthesizedArg(A);
1475
1476       // Linker input arguments require custom handling. The problem is that we
1477       // have already constructed the phase actions, so we can not treat them as
1478       // "input arguments".
1479       if (A->getOption().hasFlag(options::LinkerInput)) {
1480         // Convert the argument into individual Zlinker_input_args.
1481         for (const char *Value : A->getValues()) {
1482           DAL->AddSeparateArg(
1483               OriginalArg, Opts.getOption(options::OPT_Zlinker_input), Value);
1484         }
1485         continue;
1486       }
1487     }
1488
1489     // Sob. These is strictly gcc compatible for the time being. Apple
1490     // gcc translates options twice, which means that self-expanding
1491     // options add duplicates.
1492     switch ((options::ID)A->getOption().getID()) {
1493     default:
1494       DAL->append(A);
1495       break;
1496
1497     case options::OPT_mkernel:
1498     case options::OPT_fapple_kext:
1499       DAL->append(A);
1500       DAL->AddFlagArg(A, Opts.getOption(options::OPT_static));
1501       break;
1502
1503     case options::OPT_dependency_file:
1504       DAL->AddSeparateArg(A, Opts.getOption(options::OPT_MF), A->getValue());
1505       break;
1506
1507     case options::OPT_gfull:
1508       DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
1509       DAL->AddFlagArg(
1510           A, Opts.getOption(options::OPT_fno_eliminate_unused_debug_symbols));
1511       break;
1512
1513     case options::OPT_gused:
1514       DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
1515       DAL->AddFlagArg(
1516           A, Opts.getOption(options::OPT_feliminate_unused_debug_symbols));
1517       break;
1518
1519     case options::OPT_shared:
1520       DAL->AddFlagArg(A, Opts.getOption(options::OPT_dynamiclib));
1521       break;
1522
1523     case options::OPT_fconstant_cfstrings:
1524       DAL->AddFlagArg(A, Opts.getOption(options::OPT_mconstant_cfstrings));
1525       break;
1526
1527     case options::OPT_fno_constant_cfstrings:
1528       DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_constant_cfstrings));
1529       break;
1530
1531     case options::OPT_Wnonportable_cfstrings:
1532       DAL->AddFlagArg(A,
1533                       Opts.getOption(options::OPT_mwarn_nonportable_cfstrings));
1534       break;
1535
1536     case options::OPT_Wno_nonportable_cfstrings:
1537       DAL->AddFlagArg(
1538           A, Opts.getOption(options::OPT_mno_warn_nonportable_cfstrings));
1539       break;
1540
1541     case options::OPT_fpascal_strings:
1542       DAL->AddFlagArg(A, Opts.getOption(options::OPT_mpascal_strings));
1543       break;
1544
1545     case options::OPT_fno_pascal_strings:
1546       DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_pascal_strings));
1547       break;
1548     }
1549   }
1550
1551   if (getTriple().getArch() == llvm::Triple::x86 ||
1552       getTriple().getArch() == llvm::Triple::x86_64)
1553     if (!Args.hasArgNoClaim(options::OPT_mtune_EQ))
1554       DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_mtune_EQ),
1555                         "core2");
1556
1557   // Add the arch options based on the particular spelling of -arch, to match
1558   // how the driver driver works.
1559   if (!BoundArch.empty()) {
1560     StringRef Name = BoundArch;
1561     const Option MCpu = Opts.getOption(options::OPT_mcpu_EQ);
1562     const Option MArch = Opts.getOption(clang::driver::options::OPT_march_EQ);
1563
1564     // This code must be kept in sync with LLVM's getArchTypeForDarwinArch,
1565     // which defines the list of which architectures we accept.
1566     if (Name == "ppc")
1567       ;
1568     else if (Name == "ppc601")
1569       DAL->AddJoinedArg(nullptr, MCpu, "601");
1570     else if (Name == "ppc603")
1571       DAL->AddJoinedArg(nullptr, MCpu, "603");
1572     else if (Name == "ppc604")
1573       DAL->AddJoinedArg(nullptr, MCpu, "604");
1574     else if (Name == "ppc604e")
1575       DAL->AddJoinedArg(nullptr, MCpu, "604e");
1576     else if (Name == "ppc750")
1577       DAL->AddJoinedArg(nullptr, MCpu, "750");
1578     else if (Name == "ppc7400")
1579       DAL->AddJoinedArg(nullptr, MCpu, "7400");
1580     else if (Name == "ppc7450")
1581       DAL->AddJoinedArg(nullptr, MCpu, "7450");
1582     else if (Name == "ppc970")
1583       DAL->AddJoinedArg(nullptr, MCpu, "970");
1584
1585     else if (Name == "ppc64" || Name == "ppc64le")
1586       DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64));
1587
1588     else if (Name == "i386")
1589       ;
1590     else if (Name == "i486")
1591       DAL->AddJoinedArg(nullptr, MArch, "i486");
1592     else if (Name == "i586")
1593       DAL->AddJoinedArg(nullptr, MArch, "i586");
1594     else if (Name == "i686")
1595       DAL->AddJoinedArg(nullptr, MArch, "i686");
1596     else if (Name == "pentium")
1597       DAL->AddJoinedArg(nullptr, MArch, "pentium");
1598     else if (Name == "pentium2")
1599       DAL->AddJoinedArg(nullptr, MArch, "pentium2");
1600     else if (Name == "pentpro")
1601       DAL->AddJoinedArg(nullptr, MArch, "pentiumpro");
1602     else if (Name == "pentIIm3")
1603       DAL->AddJoinedArg(nullptr, MArch, "pentium2");
1604
1605     else if (Name == "x86_64")
1606       DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64));
1607     else if (Name == "x86_64h") {
1608       DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64));
1609       DAL->AddJoinedArg(nullptr, MArch, "x86_64h");
1610     }
1611
1612     else if (Name == "arm")
1613       DAL->AddJoinedArg(nullptr, MArch, "armv4t");
1614     else if (Name == "armv4t")
1615       DAL->AddJoinedArg(nullptr, MArch, "armv4t");
1616     else if (Name == "armv5")
1617       DAL->AddJoinedArg(nullptr, MArch, "armv5tej");
1618     else if (Name == "xscale")
1619       DAL->AddJoinedArg(nullptr, MArch, "xscale");
1620     else if (Name == "armv6")
1621       DAL->AddJoinedArg(nullptr, MArch, "armv6k");
1622     else if (Name == "armv6m")
1623       DAL->AddJoinedArg(nullptr, MArch, "armv6m");
1624     else if (Name == "armv7")
1625       DAL->AddJoinedArg(nullptr, MArch, "armv7a");
1626     else if (Name == "armv7em")
1627       DAL->AddJoinedArg(nullptr, MArch, "armv7em");
1628     else if (Name == "armv7k")
1629       DAL->AddJoinedArg(nullptr, MArch, "armv7k");
1630     else if (Name == "armv7m")
1631       DAL->AddJoinedArg(nullptr, MArch, "armv7m");
1632     else if (Name == "armv7s")
1633       DAL->AddJoinedArg(nullptr, MArch, "armv7s");
1634   }
1635
1636   return DAL;
1637 }
1638
1639 void MachO::AddLinkRuntimeLibArgs(const ArgList &Args,
1640                                   ArgStringList &CmdArgs) const {
1641   // Embedded targets are simple at the moment, not supporting sanitizers and
1642   // with different libraries for each member of the product { static, PIC } x
1643   // { hard-float, soft-float }
1644   llvm::SmallString<32> CompilerRT = StringRef("libclang_rt.");
1645   CompilerRT +=
1646       (tools::arm::getARMFloatABI(*this, Args) == tools::arm::FloatABI::Hard)
1647           ? "hard"
1648           : "soft";
1649   CompilerRT += Args.hasArg(options::OPT_fPIC) ? "_pic.a" : "_static.a";
1650
1651   AddLinkRuntimeLib(Args, CmdArgs, CompilerRT, false, true);
1652 }
1653
1654 DerivedArgList *
1655 Darwin::TranslateArgs(const DerivedArgList &Args, StringRef BoundArch,
1656                       Action::OffloadKind DeviceOffloadKind) const {
1657   // First get the generic Apple args, before moving onto Darwin-specific ones.
1658   DerivedArgList *DAL =
1659       MachO::TranslateArgs(Args, BoundArch, DeviceOffloadKind);
1660   const OptTable &Opts = getDriver().getOpts();
1661
1662   // If no architecture is bound, none of the translations here are relevant.
1663   if (BoundArch.empty())
1664     return DAL;
1665
1666   // Add an explicit version min argument for the deployment target. We do this
1667   // after argument translation because -Xarch_ arguments may add a version min
1668   // argument.
1669   AddDeploymentTarget(*DAL);
1670
1671   // For iOS 6, undo the translation to add -static for -mkernel/-fapple-kext.
1672   // FIXME: It would be far better to avoid inserting those -static arguments,
1673   // but we can't check the deployment target in the translation code until
1674   // it is set here.
1675   if (isTargetWatchOSBased() ||
1676       (isTargetIOSBased() && !isIPhoneOSVersionLT(6, 0))) {
1677     for (ArgList::iterator it = DAL->begin(), ie = DAL->end(); it != ie; ) {
1678       Arg *A = *it;
1679       ++it;
1680       if (A->getOption().getID() != options::OPT_mkernel &&
1681           A->getOption().getID() != options::OPT_fapple_kext)
1682         continue;
1683       assert(it != ie && "unexpected argument translation");
1684       A = *it;
1685       assert(A->getOption().getID() == options::OPT_static &&
1686              "missing expected -static argument");
1687       *it = nullptr;
1688       ++it;
1689     }
1690   }
1691
1692   if (!Args.getLastArg(options::OPT_stdlib_EQ) &&
1693       GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
1694     DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_stdlib_EQ),
1695                       "libc++");
1696
1697   // Validate the C++ standard library choice.
1698   CXXStdlibType Type = GetCXXStdlibType(*DAL);
1699   if (Type == ToolChain::CST_Libcxx) {
1700     // Check whether the target provides libc++.
1701     StringRef where;
1702
1703     // Complain about targeting iOS < 5.0 in any way.
1704     if (isTargetIOSBased() && isIPhoneOSVersionLT(5, 0))
1705       where = "iOS 5.0";
1706
1707     if (where != StringRef()) {
1708       getDriver().Diag(clang::diag::err_drv_invalid_libcxx_deployment) << where;
1709     }
1710   }
1711
1712   auto Arch = tools::darwin::getArchTypeForMachOArchName(BoundArch);
1713   if ((Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb)) {
1714     if (Args.hasFlag(options::OPT_fomit_frame_pointer,
1715                      options::OPT_fno_omit_frame_pointer, false))
1716       getDriver().Diag(clang::diag::warn_drv_unsupported_opt_for_target)
1717           << "-fomit-frame-pointer" << BoundArch;
1718   }
1719
1720   return DAL;
1721 }
1722
1723 bool MachO::IsUnwindTablesDefault() const {
1724   return getArch() == llvm::Triple::x86_64;
1725 }
1726
1727 bool MachO::UseDwarfDebugFlags() const {
1728   if (const char *S = ::getenv("RC_DEBUG_OPTIONS"))
1729     return S[0] != '\0';
1730   return false;
1731 }
1732
1733 bool Darwin::UseSjLjExceptions(const ArgList &Args) const {
1734   // Darwin uses SjLj exceptions on ARM.
1735   if (getTriple().getArch() != llvm::Triple::arm &&
1736       getTriple().getArch() != llvm::Triple::thumb)
1737     return false;
1738
1739   // Only watchOS uses the new DWARF/Compact unwinding method.
1740   llvm::Triple Triple(ComputeLLVMTriple(Args));
1741   return !Triple.isWatchABI();
1742 }
1743
1744 bool Darwin::SupportsEmbeddedBitcode() const {
1745   assert(TargetInitialized && "Target not initialized!");
1746   if (isTargetIPhoneOS() && isIPhoneOSVersionLT(6, 0))
1747     return false;
1748   return true;
1749 }
1750
1751 bool MachO::isPICDefault() const { return true; }
1752
1753 bool MachO::isPIEDefault() const { return false; }
1754
1755 bool MachO::isPICDefaultForced() const {
1756   return (getArch() == llvm::Triple::x86_64 ||
1757           getArch() == llvm::Triple::aarch64);
1758 }
1759
1760 bool MachO::SupportsProfiling() const {
1761   // Profiling instrumentation is only supported on x86.
1762   return getArch() == llvm::Triple::x86 || getArch() == llvm::Triple::x86_64;
1763 }
1764
1765 void Darwin::addMinVersionArgs(const ArgList &Args,
1766                                ArgStringList &CmdArgs) const {
1767   VersionTuple TargetVersion = getTargetVersion();
1768
1769   if (isTargetWatchOS())
1770     CmdArgs.push_back("-watchos_version_min");
1771   else if (isTargetWatchOSSimulator())
1772     CmdArgs.push_back("-watchos_simulator_version_min");
1773   else if (isTargetTvOS())
1774     CmdArgs.push_back("-tvos_version_min");
1775   else if (isTargetTvOSSimulator())
1776     CmdArgs.push_back("-tvos_simulator_version_min");
1777   else if (isTargetIOSSimulator())
1778     CmdArgs.push_back("-ios_simulator_version_min");
1779   else if (isTargetIOSBased())
1780     CmdArgs.push_back("-iphoneos_version_min");
1781   else {
1782     assert(isTargetMacOS() && "unexpected target");
1783     CmdArgs.push_back("-macosx_version_min");
1784   }
1785
1786   CmdArgs.push_back(Args.MakeArgString(TargetVersion.getAsString()));
1787 }
1788
1789 void Darwin::addStartObjectFileArgs(const ArgList &Args,
1790                                     ArgStringList &CmdArgs) const {
1791   // Derived from startfile spec.
1792   if (Args.hasArg(options::OPT_dynamiclib)) {
1793     // Derived from darwin_dylib1 spec.
1794     if (isTargetWatchOSBased()) {
1795       ; // watchOS does not need dylib1.o.
1796     } else if (isTargetIOSSimulator()) {
1797       ; // iOS simulator does not need dylib1.o.
1798     } else if (isTargetIPhoneOS()) {
1799       if (isIPhoneOSVersionLT(3, 1))
1800         CmdArgs.push_back("-ldylib1.o");
1801     } else {
1802       if (isMacosxVersionLT(10, 5))
1803         CmdArgs.push_back("-ldylib1.o");
1804       else if (isMacosxVersionLT(10, 6))
1805         CmdArgs.push_back("-ldylib1.10.5.o");
1806     }
1807   } else {
1808     if (Args.hasArg(options::OPT_bundle)) {
1809       if (!Args.hasArg(options::OPT_static)) {
1810         // Derived from darwin_bundle1 spec.
1811         if (isTargetWatchOSBased()) {
1812           ; // watchOS does not need bundle1.o.
1813         } else if (isTargetIOSSimulator()) {
1814           ; // iOS simulator does not need bundle1.o.
1815         } else if (isTargetIPhoneOS()) {
1816           if (isIPhoneOSVersionLT(3, 1))
1817             CmdArgs.push_back("-lbundle1.o");
1818         } else {
1819           if (isMacosxVersionLT(10, 6))
1820             CmdArgs.push_back("-lbundle1.o");
1821         }
1822       }
1823     } else {
1824       if (Args.hasArg(options::OPT_pg) && SupportsProfiling()) {
1825         if (Args.hasArg(options::OPT_static) ||
1826             Args.hasArg(options::OPT_object) ||
1827             Args.hasArg(options::OPT_preload)) {
1828           CmdArgs.push_back("-lgcrt0.o");
1829         } else {
1830           CmdArgs.push_back("-lgcrt1.o");
1831
1832           // darwin_crt2 spec is empty.
1833         }
1834         // By default on OS X 10.8 and later, we don't link with a crt1.o
1835         // file and the linker knows to use _main as the entry point.  But,
1836         // when compiling with -pg, we need to link with the gcrt1.o file,
1837         // so pass the -no_new_main option to tell the linker to use the
1838         // "start" symbol as the entry point.
1839         if (isTargetMacOS() && !isMacosxVersionLT(10, 8))
1840           CmdArgs.push_back("-no_new_main");
1841       } else {
1842         if (Args.hasArg(options::OPT_static) ||
1843             Args.hasArg(options::OPT_object) ||
1844             Args.hasArg(options::OPT_preload)) {
1845           CmdArgs.push_back("-lcrt0.o");
1846         } else {
1847           // Derived from darwin_crt1 spec.
1848           if (isTargetWatchOSBased()) {
1849             ; // watchOS does not need crt1.o.
1850           } else if (isTargetIOSSimulator()) {
1851             ; // iOS simulator does not need crt1.o.
1852           } else if (isTargetIPhoneOS()) {
1853             if (getArch() == llvm::Triple::aarch64)
1854               ; // iOS does not need any crt1 files for arm64
1855             else if (isIPhoneOSVersionLT(3, 1))
1856               CmdArgs.push_back("-lcrt1.o");
1857             else if (isIPhoneOSVersionLT(6, 0))
1858               CmdArgs.push_back("-lcrt1.3.1.o");
1859           } else {
1860             if (isMacosxVersionLT(10, 5))
1861               CmdArgs.push_back("-lcrt1.o");
1862             else if (isMacosxVersionLT(10, 6))
1863               CmdArgs.push_back("-lcrt1.10.5.o");
1864             else if (isMacosxVersionLT(10, 8))
1865               CmdArgs.push_back("-lcrt1.10.6.o");
1866
1867             // darwin_crt2 spec is empty.
1868           }
1869         }
1870       }
1871     }
1872   }
1873
1874   if (!isTargetIPhoneOS() && Args.hasArg(options::OPT_shared_libgcc) &&
1875       !isTargetWatchOS() &&
1876       isMacosxVersionLT(10, 5)) {
1877     const char *Str = Args.MakeArgString(GetFilePath("crt3.o"));
1878     CmdArgs.push_back(Str);
1879   }
1880 }
1881
1882 bool Darwin::SupportsObjCGC() const { return isTargetMacOS(); }
1883
1884 void Darwin::CheckObjCARC() const {
1885   if (isTargetIOSBased() || isTargetWatchOSBased() ||
1886       (isTargetMacOS() && !isMacosxVersionLT(10, 6)))
1887     return;
1888   getDriver().Diag(diag::err_arc_unsupported_on_toolchain);
1889 }
1890
1891 SanitizerMask Darwin::getSupportedSanitizers() const {
1892   const bool IsX86_64 = getTriple().getArch() == llvm::Triple::x86_64;
1893   SanitizerMask Res = ToolChain::getSupportedSanitizers();
1894   Res |= SanitizerKind::Address;
1895   if (isTargetMacOS()) {
1896     if (!isMacosxVersionLT(10, 9))
1897       Res |= SanitizerKind::Vptr;
1898     Res |= SanitizerKind::SafeStack;
1899     if (IsX86_64)
1900       Res |= SanitizerKind::Thread;
1901   } else if (isTargetIOSSimulator() || isTargetTvOSSimulator()) {
1902     if (IsX86_64)
1903       Res |= SanitizerKind::Thread;
1904   }
1905   return Res;
1906 }
1907
1908 void Darwin::printVerboseInfo(raw_ostream &OS) const {
1909   CudaInstallation.print(OS);
1910 }