1 //===--- Darwin.cpp - Darwin Tool and ToolChain Implementations -*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
11 #include "CommonArgs.h"
12 #include "clang/Basic/AlignedAllocation.h"
13 #include "clang/Basic/ObjCRuntime.h"
14 #include "clang/Config/config.h"
15 #include "clang/Driver/Compilation.h"
16 #include "clang/Driver/Driver.h"
17 #include "clang/Driver/DriverDiagnostic.h"
18 #include "clang/Driver/Options.h"
19 #include "clang/Driver/SanitizerArgs.h"
20 #include "llvm/ADT/StringSwitch.h"
21 #include "llvm/Option/ArgList.h"
22 #include "llvm/ProfileData/InstrProf.h"
23 #include "llvm/Support/Path.h"
24 #include "llvm/Support/ScopedPrinter.h"
25 #include "llvm/Support/TargetParser.h"
26 #include "llvm/Support/VirtualFileSystem.h"
27 #include <cstdlib> // ::getenv
29 using namespace clang::driver;
30 using namespace clang::driver::tools;
31 using namespace clang::driver::toolchains;
32 using namespace clang;
33 using namespace llvm::opt;
35 llvm::Triple::ArchType darwin::getArchTypeForMachOArchName(StringRef Str) {
36 // See arch(3) and llvm-gcc's driver-driver.c. We don't implement support for
37 // archs which Darwin doesn't use.
39 // The matching this routine does is fairly pointless, since it is neither the
40 // complete architecture list, nor a reasonable subset. The problem is that
41 // historically the driver driver accepts this and also ties its -march=
42 // handling to the architecture name, so we need to be careful before removing
45 // This code must be kept in sync with Clang's Darwin specific argument
48 return llvm::StringSwitch<llvm::Triple::ArchType>(Str)
49 .Cases("ppc", "ppc601", "ppc603", "ppc604", "ppc604e", llvm::Triple::ppc)
50 .Cases("ppc750", "ppc7400", "ppc7450", "ppc970", llvm::Triple::ppc)
51 .Case("ppc64", llvm::Triple::ppc64)
52 .Cases("i386", "i486", "i486SX", "i586", "i686", llvm::Triple::x86)
53 .Cases("pentium", "pentpro", "pentIIm3", "pentIIm5", "pentium4",
55 .Cases("x86_64", "x86_64h", llvm::Triple::x86_64)
56 // This is derived from the driver driver.
57 .Cases("arm", "armv4t", "armv5", "armv6", "armv6m", llvm::Triple::arm)
58 .Cases("armv7", "armv7em", "armv7k", "armv7m", llvm::Triple::arm)
59 .Cases("armv7s", "xscale", llvm::Triple::arm)
60 .Case("arm64", llvm::Triple::aarch64)
61 .Case("arm64_32", llvm::Triple::aarch64_32)
62 .Case("r600", llvm::Triple::r600)
63 .Case("amdgcn", llvm::Triple::amdgcn)
64 .Case("nvptx", llvm::Triple::nvptx)
65 .Case("nvptx64", llvm::Triple::nvptx64)
66 .Case("amdil", llvm::Triple::amdil)
67 .Case("spir", llvm::Triple::spir)
68 .Default(llvm::Triple::UnknownArch);
71 void darwin::setTripleTypeForMachOArchName(llvm::Triple &T, StringRef Str) {
72 const llvm::Triple::ArchType Arch = getArchTypeForMachOArchName(Str);
73 llvm::ARM::ArchKind ArchKind = llvm::ARM::parseArch(Str);
78 else if (ArchKind == llvm::ARM::ArchKind::ARMV6M ||
79 ArchKind == llvm::ARM::ArchKind::ARMV7M ||
80 ArchKind == llvm::ARM::ArchKind::ARMV7EM) {
81 T.setOS(llvm::Triple::UnknownOS);
82 T.setObjectFormat(llvm::Triple::MachO);
86 void darwin::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
87 const InputInfo &Output,
88 const InputInfoList &Inputs,
90 const char *LinkingOutput) const {
91 ArgStringList CmdArgs;
93 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
94 const InputInfo &Input = Inputs[0];
96 // Determine the original source input.
97 const Action *SourceAction = &JA;
98 while (SourceAction->getKind() != Action::InputClass) {
99 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
100 SourceAction = SourceAction->getInputs()[0];
103 // If -fno-integrated-as is used add -Q to the darwin assembler driver to make
104 // sure it runs its system assembler not clang's integrated assembler.
105 // Applicable to darwin11+ and Xcode 4+. darwin<10 lacked integrated-as.
106 // FIXME: at run-time detect assembler capabilities or rely on version
107 // information forwarded by -target-assembler-version.
108 if (Args.hasArg(options::OPT_fno_integrated_as)) {
109 const llvm::Triple &T(getToolChain().getTriple());
110 if (!(T.isMacOSX() && T.isMacOSXVersionLT(10, 7)))
111 CmdArgs.push_back("-Q");
114 // Forward -g, assuming we are dealing with an actual assembly file.
115 if (SourceAction->getType() == types::TY_Asm ||
116 SourceAction->getType() == types::TY_PP_Asm) {
117 if (Args.hasArg(options::OPT_gstabs))
118 CmdArgs.push_back("--gstabs");
119 else if (Args.hasArg(options::OPT_g_Group))
120 CmdArgs.push_back("-g");
123 // Derived from asm spec.
124 AddMachOArch(Args, CmdArgs);
126 // Use -force_cpusubtype_ALL on x86 by default.
127 if (getToolChain().getTriple().isX86() ||
128 Args.hasArg(options::OPT_force__cpusubtype__ALL))
129 CmdArgs.push_back("-force_cpusubtype_ALL");
131 if (getToolChain().getArch() != llvm::Triple::x86_64 &&
132 (((Args.hasArg(options::OPT_mkernel) ||
133 Args.hasArg(options::OPT_fapple_kext)) &&
134 getMachOToolChain().isKernelStatic()) ||
135 Args.hasArg(options::OPT_static)))
136 CmdArgs.push_back("-static");
138 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
140 assert(Output.isFilename() && "Unexpected lipo output.");
141 CmdArgs.push_back("-o");
142 CmdArgs.push_back(Output.getFilename());
144 assert(Input.isFilename() && "Invalid input.");
145 CmdArgs.push_back(Input.getFilename());
147 // asm_final spec is empty.
149 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
150 C.addCommand(std::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
153 void darwin::MachOTool::anchor() {}
155 void darwin::MachOTool::AddMachOArch(const ArgList &Args,
156 ArgStringList &CmdArgs) const {
157 StringRef ArchName = getMachOToolChain().getMachOArchName(Args);
159 // Derived from darwin_arch spec.
160 CmdArgs.push_back("-arch");
161 CmdArgs.push_back(Args.MakeArgString(ArchName));
163 // FIXME: Is this needed anymore?
164 if (ArchName == "arm")
165 CmdArgs.push_back("-force_cpusubtype_ALL");
168 bool darwin::Linker::NeedsTempPath(const InputInfoList &Inputs) const {
169 // We only need to generate a temp path for LTO if we aren't compiling object
170 // files. When compiling source files, we run 'dsymutil' after linking. We
171 // don't run 'dsymutil' when compiling object files.
172 for (const auto &Input : Inputs)
173 if (Input.getType() != types::TY_Object)
179 /// Pass -no_deduplicate to ld64 under certain conditions:
181 /// - Either -O0 or -O1 is explicitly specified
182 /// - No -O option is specified *and* this is a compile+link (implicit -O0)
184 /// Also do *not* add -no_deduplicate when no -O option is specified and this
185 /// is just a link (we can't imply -O0)
186 static bool shouldLinkerNotDedup(bool IsLinkerOnlyAction, const ArgList &Args) {
187 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
188 if (A->getOption().matches(options::OPT_O0))
190 if (A->getOption().matches(options::OPT_O))
191 return llvm::StringSwitch<bool>(A->getValue())
194 return false; // OPT_Ofast & OPT_O4
197 if (!IsLinkerOnlyAction) // Implicit -O0 for compile+linker only.
202 void darwin::Linker::AddLinkArgs(Compilation &C, const ArgList &Args,
203 ArgStringList &CmdArgs,
204 const InputInfoList &Inputs) const {
205 const Driver &D = getToolChain().getDriver();
206 const toolchains::MachO &MachOTC = getMachOToolChain();
208 unsigned Version[5] = {0, 0, 0, 0, 0};
209 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
210 if (!Driver::GetReleaseVersion(A->getValue(), Version))
211 D.Diag(diag::err_drv_invalid_version_number) << A->getAsString(Args);
214 // Newer linkers support -demangle. Pass it if supported and not disabled by
216 if (Version[0] >= 100 && !Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
217 CmdArgs.push_back("-demangle");
219 if (Args.hasArg(options::OPT_rdynamic) && Version[0] >= 137)
220 CmdArgs.push_back("-export_dynamic");
222 // If we are using App Extension restrictions, pass a flag to the linker
223 // telling it that the compiled code has been audited.
224 if (Args.hasFlag(options::OPT_fapplication_extension,
225 options::OPT_fno_application_extension, false))
226 CmdArgs.push_back("-application_extension");
228 if (D.isUsingLTO() && Version[0] >= 116 && NeedsTempPath(Inputs)) {
229 std::string TmpPathName;
230 if (D.getLTOMode() == LTOK_Full) {
231 // If we are using full LTO, then automatically create a temporary file
232 // path for the linker to use, so that it's lifetime will extend past a
233 // possible dsymutil step.
235 D.GetTemporaryPath("cc", types::getTypeTempSuffix(types::TY_Object));
236 } else if (D.getLTOMode() == LTOK_Thin)
237 // If we are using thin LTO, then create a directory instead.
238 TmpPathName = D.GetTemporaryDirectory("thinlto");
240 if (!TmpPathName.empty()) {
241 auto *TmpPath = C.getArgs().MakeArgString(TmpPathName);
242 C.addTempFile(TmpPath);
243 CmdArgs.push_back("-object_path_lto");
244 CmdArgs.push_back(TmpPath);
248 // Use -lto_library option to specify the libLTO.dylib path. Try to find
249 // it in clang installed libraries. ld64 will only look at this argument
250 // when it actually uses LTO, so libLTO.dylib only needs to exist at link
251 // time if ld64 decides that it needs to use LTO.
252 // Since this is passed unconditionally, ld64 will never look for libLTO.dylib
253 // next to it. That's ok since ld64 using a libLTO.dylib not matching the
254 // clang version won't work anyways.
255 if (Version[0] >= 133) {
256 // Search for libLTO in <InstalledDir>/../lib/libLTO.dylib
257 StringRef P = llvm::sys::path::parent_path(D.Dir);
258 SmallString<128> LibLTOPath(P);
259 llvm::sys::path::append(LibLTOPath, "lib");
260 llvm::sys::path::append(LibLTOPath, "libLTO.dylib");
261 CmdArgs.push_back("-lto_library");
262 CmdArgs.push_back(C.getArgs().MakeArgString(LibLTOPath));
265 // ld64 version 262 and above run the deduplicate pass by default.
266 if (Version[0] >= 262 && shouldLinkerNotDedup(C.getJobs().empty(), Args))
267 CmdArgs.push_back("-no_deduplicate");
269 // Derived from the "link" spec.
270 Args.AddAllArgs(CmdArgs, options::OPT_static);
271 if (!Args.hasArg(options::OPT_static))
272 CmdArgs.push_back("-dynamic");
273 if (Args.hasArg(options::OPT_fgnu_runtime)) {
274 // FIXME: gcc replaces -lobjc in forward args with -lobjc-gnu
275 // here. How do we wish to handle such things?
278 if (!Args.hasArg(options::OPT_dynamiclib)) {
279 AddMachOArch(Args, CmdArgs);
280 // FIXME: Why do this only on this path?
281 Args.AddLastArg(CmdArgs, options::OPT_force__cpusubtype__ALL);
283 Args.AddLastArg(CmdArgs, options::OPT_bundle);
284 Args.AddAllArgs(CmdArgs, options::OPT_bundle__loader);
285 Args.AddAllArgs(CmdArgs, options::OPT_client__name);
288 if ((A = Args.getLastArg(options::OPT_compatibility__version)) ||
289 (A = Args.getLastArg(options::OPT_current__version)) ||
290 (A = Args.getLastArg(options::OPT_install__name)))
291 D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
294 Args.AddLastArg(CmdArgs, options::OPT_force__flat__namespace);
295 Args.AddLastArg(CmdArgs, options::OPT_keep__private__externs);
296 Args.AddLastArg(CmdArgs, options::OPT_private__bundle);
298 CmdArgs.push_back("-dylib");
301 if ((A = Args.getLastArg(options::OPT_bundle)) ||
302 (A = Args.getLastArg(options::OPT_bundle__loader)) ||
303 (A = Args.getLastArg(options::OPT_client__name)) ||
304 (A = Args.getLastArg(options::OPT_force__flat__namespace)) ||
305 (A = Args.getLastArg(options::OPT_keep__private__externs)) ||
306 (A = Args.getLastArg(options::OPT_private__bundle)))
307 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
310 Args.AddAllArgsTranslated(CmdArgs, options::OPT_compatibility__version,
311 "-dylib_compatibility_version");
312 Args.AddAllArgsTranslated(CmdArgs, options::OPT_current__version,
313 "-dylib_current_version");
315 AddMachOArch(Args, CmdArgs);
317 Args.AddAllArgsTranslated(CmdArgs, options::OPT_install__name,
318 "-dylib_install_name");
321 Args.AddLastArg(CmdArgs, options::OPT_all__load);
322 Args.AddAllArgs(CmdArgs, options::OPT_allowable__client);
323 Args.AddLastArg(CmdArgs, options::OPT_bind__at__load);
324 if (MachOTC.isTargetIOSBased())
325 Args.AddLastArg(CmdArgs, options::OPT_arch__errors__fatal);
326 Args.AddLastArg(CmdArgs, options::OPT_dead__strip);
327 Args.AddLastArg(CmdArgs, options::OPT_no__dead__strip__inits__and__terms);
328 Args.AddAllArgs(CmdArgs, options::OPT_dylib__file);
329 Args.AddLastArg(CmdArgs, options::OPT_dynamic);
330 Args.AddAllArgs(CmdArgs, options::OPT_exported__symbols__list);
331 Args.AddLastArg(CmdArgs, options::OPT_flat__namespace);
332 Args.AddAllArgs(CmdArgs, options::OPT_force__load);
333 Args.AddAllArgs(CmdArgs, options::OPT_headerpad__max__install__names);
334 Args.AddAllArgs(CmdArgs, options::OPT_image__base);
335 Args.AddAllArgs(CmdArgs, options::OPT_init);
337 // Add the deployment target.
338 if (!Version[0] || Version[0] >= 520)
339 MachOTC.addPlatformVersionArgs(Args, CmdArgs);
341 MachOTC.addMinVersionArgs(Args, CmdArgs);
343 Args.AddLastArg(CmdArgs, options::OPT_nomultidefs);
344 Args.AddLastArg(CmdArgs, options::OPT_multi__module);
345 Args.AddLastArg(CmdArgs, options::OPT_single__module);
346 Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined);
347 Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined__unused);
350 Args.getLastArg(options::OPT_fpie, options::OPT_fPIE,
351 options::OPT_fno_pie, options::OPT_fno_PIE)) {
352 if (A->getOption().matches(options::OPT_fpie) ||
353 A->getOption().matches(options::OPT_fPIE))
354 CmdArgs.push_back("-pie");
356 CmdArgs.push_back("-no_pie");
359 // for embed-bitcode, use -bitcode_bundle in linker command
360 if (C.getDriver().embedBitcodeEnabled()) {
361 // Check if the toolchain supports bitcode build flow.
362 if (MachOTC.SupportsEmbeddedBitcode()) {
363 CmdArgs.push_back("-bitcode_bundle");
364 if (C.getDriver().embedBitcodeMarkerOnly() && Version[0] >= 278) {
365 CmdArgs.push_back("-bitcode_process_mode");
366 CmdArgs.push_back("marker");
369 D.Diag(diag::err_drv_bitcode_unsupported_on_toolchain);
372 Args.AddLastArg(CmdArgs, options::OPT_prebind);
373 Args.AddLastArg(CmdArgs, options::OPT_noprebind);
374 Args.AddLastArg(CmdArgs, options::OPT_nofixprebinding);
375 Args.AddLastArg(CmdArgs, options::OPT_prebind__all__twolevel__modules);
376 Args.AddLastArg(CmdArgs, options::OPT_read__only__relocs);
377 Args.AddAllArgs(CmdArgs, options::OPT_sectcreate);
378 Args.AddAllArgs(CmdArgs, options::OPT_sectorder);
379 Args.AddAllArgs(CmdArgs, options::OPT_seg1addr);
380 Args.AddAllArgs(CmdArgs, options::OPT_segprot);
381 Args.AddAllArgs(CmdArgs, options::OPT_segaddr);
382 Args.AddAllArgs(CmdArgs, options::OPT_segs__read__only__addr);
383 Args.AddAllArgs(CmdArgs, options::OPT_segs__read__write__addr);
384 Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table);
385 Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table__filename);
386 Args.AddAllArgs(CmdArgs, options::OPT_sub__library);
387 Args.AddAllArgs(CmdArgs, options::OPT_sub__umbrella);
389 // Give --sysroot= preference, over the Apple specific behavior to also use
390 // --isysroot as the syslibroot.
391 StringRef sysroot = C.getSysRoot();
393 CmdArgs.push_back("-syslibroot");
394 CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
395 } else if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
396 CmdArgs.push_back("-syslibroot");
397 CmdArgs.push_back(A->getValue());
400 Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace);
401 Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace__hints);
402 Args.AddAllArgs(CmdArgs, options::OPT_umbrella);
403 Args.AddAllArgs(CmdArgs, options::OPT_undefined);
404 Args.AddAllArgs(CmdArgs, options::OPT_unexported__symbols__list);
405 Args.AddAllArgs(CmdArgs, options::OPT_weak__reference__mismatches);
406 Args.AddLastArg(CmdArgs, options::OPT_X_Flag);
407 Args.AddAllArgs(CmdArgs, options::OPT_y);
408 Args.AddLastArg(CmdArgs, options::OPT_w);
409 Args.AddAllArgs(CmdArgs, options::OPT_pagezero__size);
410 Args.AddAllArgs(CmdArgs, options::OPT_segs__read__);
411 Args.AddLastArg(CmdArgs, options::OPT_seglinkedit);
412 Args.AddLastArg(CmdArgs, options::OPT_noseglinkedit);
413 Args.AddAllArgs(CmdArgs, options::OPT_sectalign);
414 Args.AddAllArgs(CmdArgs, options::OPT_sectobjectsymbols);
415 Args.AddAllArgs(CmdArgs, options::OPT_segcreate);
416 Args.AddLastArg(CmdArgs, options::OPT_whyload);
417 Args.AddLastArg(CmdArgs, options::OPT_whatsloaded);
418 Args.AddAllArgs(CmdArgs, options::OPT_dylinker__install__name);
419 Args.AddLastArg(CmdArgs, options::OPT_dylinker);
420 Args.AddLastArg(CmdArgs, options::OPT_Mach);
423 /// Determine whether we are linking the ObjC runtime.
424 static bool isObjCRuntimeLinked(const ArgList &Args) {
425 if (isObjCAutoRefCount(Args)) {
426 Args.ClaimAllArgs(options::OPT_fobjc_link_runtime);
429 return Args.hasArg(options::OPT_fobjc_link_runtime);
432 void darwin::Linker::ConstructJob(Compilation &C, const JobAction &JA,
433 const InputInfo &Output,
434 const InputInfoList &Inputs,
436 const char *LinkingOutput) const {
437 assert(Output.getType() == types::TY_Image && "Invalid linker output type.");
439 // If the number of arguments surpasses the system limits, we will encode the
440 // input files in a separate file, shortening the command line. To this end,
441 // build a list of input file names that can be passed via a file with the
442 // -filelist linker option.
443 llvm::opt::ArgStringList InputFileList;
445 // The logic here is derived from gcc's behavior; most of which
446 // comes from specs (starting with link_command). Consult gcc for
448 ArgStringList CmdArgs;
450 /// Hack(tm) to ignore linking errors when we are doing ARC migration.
451 if (Args.hasArg(options::OPT_ccc_arcmt_check,
452 options::OPT_ccc_arcmt_migrate)) {
453 for (const auto &Arg : Args)
456 Args.MakeArgString(getToolChain().GetProgramPath("touch"));
457 CmdArgs.push_back(Output.getFilename());
458 C.addCommand(std::make_unique<Command>(JA, *this, Exec, CmdArgs, None));
462 // I'm not sure why this particular decomposition exists in gcc, but
463 // we follow suite for ease of comparison.
464 AddLinkArgs(C, Args, CmdArgs, Inputs);
466 // For LTO, pass the name of the optimization record file and other
467 // opt-remarks flags.
468 if (Args.hasFlag(options::OPT_fsave_optimization_record,
469 options::OPT_fsave_optimization_record_EQ,
470 options::OPT_fno_save_optimization_record, false)) {
471 CmdArgs.push_back("-mllvm");
472 CmdArgs.push_back("-lto-pass-remarks-output");
473 CmdArgs.push_back("-mllvm");
476 F = Output.getFilename();
479 Args.getLastArg(options::OPT_fsave_optimization_record_EQ))
484 CmdArgs.push_back(Args.MakeArgString(F));
486 if (getLastProfileUseArg(Args)) {
487 CmdArgs.push_back("-mllvm");
488 CmdArgs.push_back("-lto-pass-remarks-with-hotness");
491 Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
492 CmdArgs.push_back("-mllvm");
494 std::string("-lto-pass-remarks-hotness-threshold=") + A->getValue();
495 CmdArgs.push_back(Args.MakeArgString(Opt));
500 Args.getLastArg(options::OPT_foptimization_record_passes_EQ)) {
501 CmdArgs.push_back("-mllvm");
503 std::string("-lto-pass-remarks-filter=") + A->getValue();
504 CmdArgs.push_back(Args.MakeArgString(Passes));
508 Args.getLastArg(options::OPT_fsave_optimization_record_EQ)) {
509 CmdArgs.push_back("-mllvm");
511 std::string("-lto-pass-remarks-format=") + A->getValue();
512 CmdArgs.push_back(Args.MakeArgString(Format));
516 // Propagate the -moutline flag to the linker in LTO.
518 Args.getLastArg(options::OPT_moutline, options::OPT_mno_outline)) {
519 if (A->getOption().matches(options::OPT_moutline)) {
520 if (getMachOToolChain().getMachOArchName(Args) == "arm64") {
521 CmdArgs.push_back("-mllvm");
522 CmdArgs.push_back("-enable-machine-outliner");
524 // Outline from linkonceodr functions by default in LTO.
525 CmdArgs.push_back("-mllvm");
526 CmdArgs.push_back("-enable-linkonceodr-outlining");
529 // Disable all outlining behaviour if we have mno-outline. We need to do
530 // this explicitly, because targets which support default outlining will
531 // try to do work if we don't.
532 CmdArgs.push_back("-mllvm");
533 CmdArgs.push_back("-enable-machine-outliner=never");
537 // Setup statistics file output.
538 SmallString<128> StatsFile =
539 getStatsFileName(Args, Output, Inputs[0], getToolChain().getDriver());
540 if (!StatsFile.empty()) {
541 CmdArgs.push_back("-mllvm");
542 CmdArgs.push_back(Args.MakeArgString("-lto-stats-file=" + StatsFile.str()));
545 // It seems that the 'e' option is completely ignored for dynamic executables
546 // (the default), and with static executables, the last one wins, as expected.
547 Args.AddAllArgs(CmdArgs, {options::OPT_d_Flag, options::OPT_s, options::OPT_t,
548 options::OPT_Z_Flag, options::OPT_u_Group,
549 options::OPT_e, options::OPT_r});
551 // Forward -ObjC when either -ObjC or -ObjC++ is used, to force loading
552 // members of static archive libraries which implement Objective-C classes or
554 if (Args.hasArg(options::OPT_ObjC) || Args.hasArg(options::OPT_ObjCXX))
555 CmdArgs.push_back("-ObjC");
557 CmdArgs.push_back("-o");
558 CmdArgs.push_back(Output.getFilename());
560 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
561 getMachOToolChain().addStartObjectFileArgs(Args, CmdArgs);
563 Args.AddAllArgs(CmdArgs, options::OPT_L);
565 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs, JA);
566 // Build the input file for -filelist (list of linker input files) in case we
568 for (const auto &II : Inputs) {
569 if (!II.isFilename()) {
570 // This is a linker input argument.
571 // We cannot mix input arguments and file names in a -filelist input, thus
572 // we prematurely stop our list (remaining files shall be passed as
574 if (InputFileList.size() > 0)
580 InputFileList.push_back(II.getFilename());
583 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs))
584 addOpenMPRuntime(CmdArgs, getToolChain(), Args);
586 if (isObjCRuntimeLinked(Args) &&
587 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
588 // We use arclite library for both ARC and subscripting support.
589 getMachOToolChain().AddLinkARCArgs(Args, CmdArgs);
591 CmdArgs.push_back("-framework");
592 CmdArgs.push_back("Foundation");
594 CmdArgs.push_back("-lobjc");
598 CmdArgs.push_back("-arch_multiple");
599 CmdArgs.push_back("-final_output");
600 CmdArgs.push_back(LinkingOutput);
603 if (Args.hasArg(options::OPT_fnested_functions))
604 CmdArgs.push_back("-allow_stack_execute");
606 getMachOToolChain().addProfileRTLibs(Args, CmdArgs);
608 if (unsigned Parallelism =
609 getLTOParallelism(Args, getToolChain().getDriver())) {
610 CmdArgs.push_back("-mllvm");
611 CmdArgs.push_back(Args.MakeArgString("-threads=" + Twine(Parallelism)));
614 if (getToolChain().ShouldLinkCXXStdlib(Args))
615 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
617 bool NoStdOrDefaultLibs =
618 Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs);
619 bool ForceLinkBuiltins = Args.hasArg(options::OPT_fapple_link_rtlib);
620 if (!NoStdOrDefaultLibs || ForceLinkBuiltins) {
621 // link_ssp spec is empty.
623 // If we have both -nostdlib/nodefaultlibs and -fapple-link-rtlib then
624 // we just want to link the builtins, not the other libs like libSystem.
625 if (NoStdOrDefaultLibs && ForceLinkBuiltins) {
626 getMachOToolChain().AddLinkRuntimeLib(Args, CmdArgs, "builtins");
628 // Let the tool chain choose which runtime library to link.
629 getMachOToolChain().AddLinkRuntimeLibArgs(Args, CmdArgs,
632 // No need to do anything for pthreads. Claim argument to avoid warning.
633 Args.ClaimAllArgs(options::OPT_pthread);
634 Args.ClaimAllArgs(options::OPT_pthreads);
638 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
639 // endfile_spec is empty.
642 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
643 Args.AddAllArgs(CmdArgs, options::OPT_F);
645 // -iframework should be forwarded as -F.
646 for (const Arg *A : Args.filtered(options::OPT_iframework))
647 CmdArgs.push_back(Args.MakeArgString(std::string("-F") + A->getValue()));
649 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
650 if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
651 if (A->getValue() == StringRef("Accelerate")) {
652 CmdArgs.push_back("-framework");
653 CmdArgs.push_back("Accelerate");
658 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
659 std::unique_ptr<Command> Cmd =
660 std::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs);
661 Cmd->setInputFileList(std::move(InputFileList));
662 C.addCommand(std::move(Cmd));
665 void darwin::Lipo::ConstructJob(Compilation &C, const JobAction &JA,
666 const InputInfo &Output,
667 const InputInfoList &Inputs,
669 const char *LinkingOutput) const {
670 ArgStringList CmdArgs;
672 CmdArgs.push_back("-create");
673 assert(Output.isFilename() && "Unexpected lipo output.");
675 CmdArgs.push_back("-output");
676 CmdArgs.push_back(Output.getFilename());
678 for (const auto &II : Inputs) {
679 assert(II.isFilename() && "Unexpected lipo input.");
680 CmdArgs.push_back(II.getFilename());
683 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("lipo"));
684 C.addCommand(std::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
687 void darwin::Dsymutil::ConstructJob(Compilation &C, const JobAction &JA,
688 const InputInfo &Output,
689 const InputInfoList &Inputs,
691 const char *LinkingOutput) const {
692 ArgStringList CmdArgs;
694 CmdArgs.push_back("-o");
695 CmdArgs.push_back(Output.getFilename());
697 assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
698 const InputInfo &Input = Inputs[0];
699 assert(Input.isFilename() && "Unexpected dsymutil input.");
700 CmdArgs.push_back(Input.getFilename());
703 Args.MakeArgString(getToolChain().GetProgramPath("dsymutil"));
704 C.addCommand(std::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
707 void darwin::VerifyDebug::ConstructJob(Compilation &C, const JobAction &JA,
708 const InputInfo &Output,
709 const InputInfoList &Inputs,
711 const char *LinkingOutput) const {
712 ArgStringList CmdArgs;
713 CmdArgs.push_back("--verify");
714 CmdArgs.push_back("--debug-info");
715 CmdArgs.push_back("--eh-frame");
716 CmdArgs.push_back("--quiet");
718 assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
719 const InputInfo &Input = Inputs[0];
720 assert(Input.isFilename() && "Unexpected verify input");
722 // Grabbing the output of the earlier dsymutil run.
723 CmdArgs.push_back(Input.getFilename());
726 Args.MakeArgString(getToolChain().GetProgramPath("dwarfdump"));
727 C.addCommand(std::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
730 MachO::MachO(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
731 : ToolChain(D, Triple, Args) {
732 // We expect 'as', 'ld', etc. to be adjacent to our install dir.
733 getProgramPaths().push_back(getDriver().getInstalledDir());
734 if (getDriver().getInstalledDir() != getDriver().Dir)
735 getProgramPaths().push_back(getDriver().Dir);
738 /// Darwin - Darwin tool chain for i386 and x86_64.
739 Darwin::Darwin(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
740 : MachO(D, Triple, Args), TargetInitialized(false),
741 CudaInstallation(D, Triple, Args) {}
743 types::ID MachO::LookupTypeForExtension(StringRef Ext) const {
744 types::ID Ty = ToolChain::LookupTypeForExtension(Ext);
746 // Darwin always preprocesses assembly files (unless -x is used explicitly).
747 if (Ty == types::TY_PP_Asm)
748 return types::TY_Asm;
753 bool MachO::HasNativeLLVMSupport() const { return true; }
755 ToolChain::CXXStdlibType Darwin::GetDefaultCXXStdlibType() const {
756 // Default to use libc++ on OS X 10.9+ and iOS 7+.
757 if ((isTargetMacOS() && !isMacosxVersionLT(10, 9)) ||
758 (isTargetIOSBased() && !isIPhoneOSVersionLT(7, 0)) ||
759 isTargetWatchOSBased())
760 return ToolChain::CST_Libcxx;
762 return ToolChain::CST_Libstdcxx;
765 /// Darwin provides an ARC runtime starting in MacOS X 10.7 and iOS 5.0.
766 ObjCRuntime Darwin::getDefaultObjCRuntime(bool isNonFragile) const {
767 if (isTargetWatchOSBased())
768 return ObjCRuntime(ObjCRuntime::WatchOS, TargetVersion);
769 if (isTargetIOSBased())
770 return ObjCRuntime(ObjCRuntime::iOS, TargetVersion);
772 return ObjCRuntime(ObjCRuntime::MacOSX, TargetVersion);
773 return ObjCRuntime(ObjCRuntime::FragileMacOSX, TargetVersion);
776 /// Darwin provides a blocks runtime starting in MacOS X 10.6 and iOS 3.2.
777 bool Darwin::hasBlocksRuntime() const {
778 if (isTargetWatchOSBased())
780 else if (isTargetIOSBased())
781 return !isIPhoneOSVersionLT(3, 2);
783 assert(isTargetMacOS() && "unexpected darwin target");
784 return !isMacosxVersionLT(10, 6);
788 void Darwin::AddCudaIncludeArgs(const ArgList &DriverArgs,
789 ArgStringList &CC1Args) const {
790 CudaInstallation.AddCudaIncludeArgs(DriverArgs, CC1Args);
793 // This is just a MachO name translation routine and there's no
794 // way to join this into ARMTargetParser without breaking all
795 // other assumptions. Maybe MachO should consider standardising
796 // their nomenclature.
797 static const char *ArmMachOArchName(StringRef Arch) {
798 return llvm::StringSwitch<const char *>(Arch)
799 .Case("armv6k", "armv6")
800 .Case("armv6m", "armv6m")
801 .Case("armv5tej", "armv5")
802 .Case("xscale", "xscale")
803 .Case("armv4t", "armv4t")
804 .Case("armv7", "armv7")
805 .Cases("armv7a", "armv7-a", "armv7")
806 .Cases("armv7r", "armv7-r", "armv7")
807 .Cases("armv7em", "armv7e-m", "armv7em")
808 .Cases("armv7k", "armv7-k", "armv7k")
809 .Cases("armv7m", "armv7-m", "armv7m")
810 .Cases("armv7s", "armv7-s", "armv7s")
814 static const char *ArmMachOArchNameCPU(StringRef CPU) {
815 llvm::ARM::ArchKind ArchKind = llvm::ARM::parseCPUArch(CPU);
816 if (ArchKind == llvm::ARM::ArchKind::INVALID)
818 StringRef Arch = llvm::ARM::getArchName(ArchKind);
820 // FIXME: Make sure this MachO triple mangling is really necessary.
821 // ARMv5* normalises to ARMv5.
822 if (Arch.startswith("armv5"))
823 Arch = Arch.substr(0, 5);
824 // ARMv6*, except ARMv6M, normalises to ARMv6.
825 else if (Arch.startswith("armv6") && !Arch.endswith("6m"))
826 Arch = Arch.substr(0, 5);
827 // ARMv7A normalises to ARMv7.
828 else if (Arch.endswith("v7a"))
829 Arch = Arch.substr(0, 5);
833 StringRef MachO::getMachOArchName(const ArgList &Args) const {
834 switch (getTriple().getArch()) {
836 return getDefaultUniversalArchName();
838 case llvm::Triple::aarch64_32:
841 case llvm::Triple::aarch64:
844 case llvm::Triple::thumb:
845 case llvm::Triple::arm:
846 if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_march_EQ))
847 if (const char *Arch = ArmMachOArchName(A->getValue()))
850 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
851 if (const char *Arch = ArmMachOArchNameCPU(A->getValue()))
862 std::string Darwin::ComputeEffectiveClangTriple(const ArgList &Args,
863 types::ID InputType) const {
864 llvm::Triple Triple(ComputeLLVMTriple(Args, InputType));
866 // If the target isn't initialized (e.g., an unknown Darwin platform, return
867 // the default triple).
868 if (!isTargetInitialized())
869 return Triple.getTriple();
872 if (isTargetWatchOSBased())
874 else if (isTargetTvOSBased())
876 else if (isTargetIOSBased())
880 Str += getTargetVersion().getAsString();
881 Triple.setOSName(Str);
883 return Triple.getTriple();
886 Tool *MachO::getTool(Action::ActionClass AC) const {
888 case Action::LipoJobClass:
890 Lipo.reset(new tools::darwin::Lipo(*this));
892 case Action::DsymutilJobClass:
894 Dsymutil.reset(new tools::darwin::Dsymutil(*this));
895 return Dsymutil.get();
896 case Action::VerifyDebugInfoJobClass:
898 VerifyDebug.reset(new tools::darwin::VerifyDebug(*this));
899 return VerifyDebug.get();
901 return ToolChain::getTool(AC);
905 Tool *MachO::buildLinker() const { return new tools::darwin::Linker(*this); }
907 Tool *MachO::buildAssembler() const {
908 return new tools::darwin::Assembler(*this);
911 DarwinClang::DarwinClang(const Driver &D, const llvm::Triple &Triple,
913 : Darwin(D, Triple, Args) {}
915 void DarwinClang::addClangWarningOptions(ArgStringList &CC1Args) const {
916 // For modern targets, promote certain warnings to errors.
917 if (isTargetWatchOSBased() || getTriple().isArch64Bit()) {
918 // Always enable -Wdeprecated-objc-isa-usage and promote it
920 CC1Args.push_back("-Wdeprecated-objc-isa-usage");
921 CC1Args.push_back("-Werror=deprecated-objc-isa-usage");
923 // For iOS and watchOS, also error about implicit function declarations,
924 // as that can impact calling conventions.
925 if (!isTargetMacOS())
926 CC1Args.push_back("-Werror=implicit-function-declaration");
930 /// Take a path that speculatively points into Xcode and return the
931 /// `XCODE/Contents/Developer` path if it is an Xcode path, or an empty path
933 static StringRef getXcodeDeveloperPath(StringRef PathIntoXcode) {
934 static constexpr llvm::StringLiteral XcodeAppSuffix(
935 ".app/Contents/Developer");
936 size_t Index = PathIntoXcode.find(XcodeAppSuffix);
937 if (Index == StringRef::npos)
939 return PathIntoXcode.take_front(Index + XcodeAppSuffix.size());
942 void DarwinClang::AddLinkARCArgs(const ArgList &Args,
943 ArgStringList &CmdArgs) const {
944 // Avoid linking compatibility stubs on i386 mac.
945 if (isTargetMacOS() && getArch() == llvm::Triple::x86)
948 ObjCRuntime runtime = getDefaultObjCRuntime(/*nonfragile*/ true);
950 if ((runtime.hasNativeARC() || !isObjCAutoRefCount(Args)) &&
951 runtime.hasSubscripting())
954 SmallString<128> P(getDriver().ClangExecutable);
955 llvm::sys::path::remove_filename(P); // 'clang'
956 llvm::sys::path::remove_filename(P); // 'bin'
958 // 'libarclite' usually lives in the same toolchain as 'clang'. However, the
959 // Swift open source toolchains for macOS distribute Clang without libarclite.
960 // In that case, to allow the linker to find 'libarclite', we point to the
961 // 'libarclite' in the XcodeDefault toolchain instead.
962 if (getXcodeDeveloperPath(P).empty()) {
963 if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
964 // Try to infer the path to 'libarclite' in the toolchain from the
965 // specified SDK path.
966 StringRef XcodePathForSDK = getXcodeDeveloperPath(A->getValue());
967 if (!XcodePathForSDK.empty()) {
969 llvm::sys::path::append(P, "Toolchains/XcodeDefault.xctoolchain/usr");
974 CmdArgs.push_back("-force_load");
975 llvm::sys::path::append(P, "lib", "arc", "libarclite_");
976 // Mash in the platform.
977 if (isTargetWatchOSSimulator())
978 P += "watchsimulator";
979 else if (isTargetWatchOS())
981 else if (isTargetTvOSSimulator())
982 P += "appletvsimulator";
983 else if (isTargetTvOS())
985 else if (isTargetIOSSimulator())
986 P += "iphonesimulator";
987 else if (isTargetIPhoneOS())
993 CmdArgs.push_back(Args.MakeArgString(P));
996 unsigned DarwinClang::GetDefaultDwarfVersion() const {
997 // Default to use DWARF 2 on OS X 10.10 / iOS 8 and lower.
998 if ((isTargetMacOS() && isMacosxVersionLT(10, 11)) ||
999 (isTargetIOSBased() && isIPhoneOSVersionLT(9)))
1004 void MachO::AddLinkRuntimeLib(const ArgList &Args, ArgStringList &CmdArgs,
1005 StringRef Component, RuntimeLinkOptions Opts,
1006 bool IsShared) const {
1007 SmallString<64> DarwinLibName = StringRef("libclang_rt.");
1008 // an Darwin the builtins compomnent is not in the library name
1009 if (Component != "builtins") {
1010 DarwinLibName += Component;
1011 if (!(Opts & RLO_IsEmbedded))
1012 DarwinLibName += "_";
1013 DarwinLibName += getOSLibraryNameSuffix();
1015 DarwinLibName += getOSLibraryNameSuffix(true);
1017 DarwinLibName += IsShared ? "_dynamic.dylib" : ".a";
1018 SmallString<128> Dir(getDriver().ResourceDir);
1019 llvm::sys::path::append(
1020 Dir, "lib", (Opts & RLO_IsEmbedded) ? "macho_embedded" : "darwin");
1022 SmallString<128> P(Dir);
1023 llvm::sys::path::append(P, DarwinLibName);
1025 // For now, allow missing resource libraries to support developers who may
1026 // not have compiler-rt checked out or integrated into their build (unless
1027 // we explicitly force linking with this library).
1028 if ((Opts & RLO_AlwaysLink) || getVFS().exists(P)) {
1029 const char *LibArg = Args.MakeArgString(P);
1030 if (Opts & RLO_FirstLink)
1031 CmdArgs.insert(CmdArgs.begin(), LibArg);
1033 CmdArgs.push_back(LibArg);
1036 // Adding the rpaths might negatively interact when other rpaths are involved,
1037 // so we should make sure we add the rpaths last, after all user-specified
1038 // rpaths. This is currently true from this place, but we need to be
1039 // careful if this function is ever called before user's rpaths are emitted.
1040 if (Opts & RLO_AddRPath) {
1041 assert(DarwinLibName.endswith(".dylib") && "must be a dynamic library");
1043 // Add @executable_path to rpath to support having the dylib copied with
1045 CmdArgs.push_back("-rpath");
1046 CmdArgs.push_back("@executable_path");
1048 // Add the path to the resource dir to rpath to support using the dylib
1049 // from the default location without copying.
1050 CmdArgs.push_back("-rpath");
1051 CmdArgs.push_back(Args.MakeArgString(Dir));
1055 StringRef Darwin::getPlatformFamily() const {
1056 switch (TargetPlatform) {
1057 case DarwinPlatformKind::MacOS:
1059 case DarwinPlatformKind::IPhoneOS:
1061 case DarwinPlatformKind::TvOS:
1063 case DarwinPlatformKind::WatchOS:
1066 llvm_unreachable("Unsupported platform");
1069 StringRef Darwin::getSDKName(StringRef isysroot) {
1070 // Assume SDK has path: SOME_PATH/SDKs/PlatformXX.YY.sdk
1071 auto BeginSDK = llvm::sys::path::begin(isysroot);
1072 auto EndSDK = llvm::sys::path::end(isysroot);
1073 for (auto IT = BeginSDK; IT != EndSDK; ++IT) {
1074 StringRef SDK = *IT;
1075 if (SDK.endswith(".sdk"))
1076 return SDK.slice(0, SDK.size() - 4);
1081 StringRef Darwin::getOSLibraryNameSuffix(bool IgnoreSim) const {
1082 switch (TargetPlatform) {
1083 case DarwinPlatformKind::MacOS:
1085 case DarwinPlatformKind::IPhoneOS:
1086 return TargetEnvironment == NativeEnvironment || IgnoreSim ? "ios"
1088 case DarwinPlatformKind::TvOS:
1089 return TargetEnvironment == NativeEnvironment || IgnoreSim ? "tvos"
1091 case DarwinPlatformKind::WatchOS:
1092 return TargetEnvironment == NativeEnvironment || IgnoreSim ? "watchos"
1095 llvm_unreachable("Unsupported platform");
1098 /// Check if the link command contains a symbol export directive.
1099 static bool hasExportSymbolDirective(const ArgList &Args) {
1100 for (Arg *A : Args) {
1101 if (A->getOption().matches(options::OPT_exported__symbols__list))
1103 if (!A->getOption().matches(options::OPT_Wl_COMMA) &&
1104 !A->getOption().matches(options::OPT_Xlinker))
1106 if (A->containsValue("-exported_symbols_list") ||
1107 A->containsValue("-exported_symbol"))
1113 /// Add an export directive for \p Symbol to the link command.
1114 static void addExportedSymbol(ArgStringList &CmdArgs, const char *Symbol) {
1115 CmdArgs.push_back("-exported_symbol");
1116 CmdArgs.push_back(Symbol);
1119 /// Add a sectalign directive for \p Segment and \p Section to the maximum
1120 /// expected page size for Darwin.
1122 /// On iPhone 6+ the max supported page size is 16K. On macOS, the max is 4K.
1123 /// Use a common alignment constant (16K) for now, and reduce the alignment on
1124 /// macOS if it proves important.
1125 static void addSectalignToPage(const ArgList &Args, ArgStringList &CmdArgs,
1126 StringRef Segment, StringRef Section) {
1127 for (const char *A : {"-sectalign", Args.MakeArgString(Segment),
1128 Args.MakeArgString(Section), "0x4000"})
1129 CmdArgs.push_back(A);
1132 void Darwin::addProfileRTLibs(const ArgList &Args,
1133 ArgStringList &CmdArgs) const {
1134 if (!needsProfileRT(Args)) return;
1136 AddLinkRuntimeLib(Args, CmdArgs, "profile",
1137 RuntimeLinkOptions(RLO_AlwaysLink | RLO_FirstLink));
1139 bool ForGCOV = needsGCovInstrumentation(Args);
1141 // If we have a symbol export directive and we're linking in the profile
1142 // runtime, automatically export symbols necessary to implement some of the
1143 // runtime's functionality.
1144 if (hasExportSymbolDirective(Args)) {
1146 addExportedSymbol(CmdArgs, "___gcov_flush");
1147 addExportedSymbol(CmdArgs, "_flush_fn_list");
1148 addExportedSymbol(CmdArgs, "_writeout_fn_list");
1150 addExportedSymbol(CmdArgs, "___llvm_profile_filename");
1151 addExportedSymbol(CmdArgs, "___llvm_profile_raw_version");
1153 addExportedSymbol(CmdArgs, "_lprofDirMode");
1156 // Align __llvm_prf_{cnts,data} sections to the maximum expected page
1157 // alignment. This allows profile counters to be mmap()'d to disk. Note that
1158 // it's not enough to just page-align __llvm_prf_cnts: the following section
1159 // must also be page-aligned so that its data is not clobbered by mmap().
1161 // The section alignment is only needed when continuous profile sync is
1162 // enabled, but this is expected to be the default in Xcode. Specifying the
1163 // extra alignment also allows the same binary to be used with/without sync
1166 for (auto IPSK : {llvm::IPSK_cnts, llvm::IPSK_data}) {
1168 Args, CmdArgs, "__DATA",
1169 llvm::getInstrProfSectionName(IPSK, llvm::Triple::MachO,
1170 /*AddSegmentInfo=*/false));
1175 void DarwinClang::AddLinkSanitizerLibArgs(const ArgList &Args,
1176 ArgStringList &CmdArgs,
1177 StringRef Sanitizer,
1178 bool Shared) const {
1179 auto RLO = RuntimeLinkOptions(RLO_AlwaysLink | (Shared ? RLO_AddRPath : 0U));
1180 AddLinkRuntimeLib(Args, CmdArgs, Sanitizer, RLO, Shared);
1183 ToolChain::RuntimeLibType DarwinClang::GetRuntimeLibType(
1184 const ArgList &Args) const {
1185 if (Arg* A = Args.getLastArg(options::OPT_rtlib_EQ)) {
1186 StringRef Value = A->getValue();
1187 if (Value != "compiler-rt")
1188 getDriver().Diag(clang::diag::err_drv_unsupported_rtlib_for_platform)
1189 << Value << "darwin";
1192 return ToolChain::RLT_CompilerRT;
1195 void DarwinClang::AddLinkRuntimeLibArgs(const ArgList &Args,
1196 ArgStringList &CmdArgs,
1197 bool ForceLinkBuiltinRT) const {
1198 // Call once to ensure diagnostic is printed if wrong value was specified
1199 GetRuntimeLibType(Args);
1201 // Darwin doesn't support real static executables, don't link any runtime
1202 // libraries with -static.
1203 if (Args.hasArg(options::OPT_static) ||
1204 Args.hasArg(options::OPT_fapple_kext) ||
1205 Args.hasArg(options::OPT_mkernel)) {
1206 if (ForceLinkBuiltinRT)
1207 AddLinkRuntimeLib(Args, CmdArgs, "builtins");
1211 // Reject -static-libgcc for now, we can deal with this when and if someone
1212 // cares. This is useful in situations where someone wants to statically link
1213 // something like libstdc++, and needs its runtime support routines.
1214 if (const Arg *A = Args.getLastArg(options::OPT_static_libgcc)) {
1215 getDriver().Diag(diag::err_drv_unsupported_opt) << A->getAsString(Args);
1219 const SanitizerArgs &Sanitize = getSanitizerArgs();
1220 if (Sanitize.needsAsanRt())
1221 AddLinkSanitizerLibArgs(Args, CmdArgs, "asan");
1222 if (Sanitize.needsLsanRt())
1223 AddLinkSanitizerLibArgs(Args, CmdArgs, "lsan");
1224 if (Sanitize.needsUbsanRt())
1225 AddLinkSanitizerLibArgs(Args, CmdArgs,
1226 Sanitize.requiresMinimalRuntime() ? "ubsan_minimal"
1228 Sanitize.needsSharedRt());
1229 if (Sanitize.needsTsanRt())
1230 AddLinkSanitizerLibArgs(Args, CmdArgs, "tsan");
1231 if (Sanitize.needsFuzzer() && !Args.hasArg(options::OPT_dynamiclib)) {
1232 AddLinkSanitizerLibArgs(Args, CmdArgs, "fuzzer", /*shared=*/false);
1234 // Libfuzzer is written in C++ and requires libcxx.
1235 AddCXXStdlibLibArgs(Args, CmdArgs);
1237 if (Sanitize.needsStatsRt()) {
1238 AddLinkRuntimeLib(Args, CmdArgs, "stats_client", RLO_AlwaysLink);
1239 AddLinkSanitizerLibArgs(Args, CmdArgs, "stats");
1242 const XRayArgs &XRay = getXRayArgs();
1243 if (XRay.needsXRayRt()) {
1244 AddLinkRuntimeLib(Args, CmdArgs, "xray");
1245 AddLinkRuntimeLib(Args, CmdArgs, "xray-basic");
1246 AddLinkRuntimeLib(Args, CmdArgs, "xray-fdr");
1249 // Otherwise link libSystem, then the dynamic runtime library, and finally any
1250 // target specific static runtime library.
1251 CmdArgs.push_back("-lSystem");
1253 // Select the dynamic runtime library and the target specific static library.
1254 if (isTargetIOSBased()) {
1255 // If we are compiling as iOS / simulator, don't attempt to link libgcc_s.1,
1256 // it never went into the SDK.
1257 // Linking against libgcc_s.1 isn't needed for iOS 5.0+
1258 if (isIPhoneOSVersionLT(5, 0) && !isTargetIOSSimulator() &&
1259 getTriple().getArch() != llvm::Triple::aarch64)
1260 CmdArgs.push_back("-lgcc_s.1");
1262 AddLinkRuntimeLib(Args, CmdArgs, "builtins");
1265 /// Returns the most appropriate macOS target version for the current process.
1267 /// If the macOS SDK version is the same or earlier than the system version,
1268 /// then the SDK version is returned. Otherwise the system version is returned.
1269 static std::string getSystemOrSDKMacOSVersion(StringRef MacOSSDKVersion) {
1270 unsigned Major, Minor, Micro;
1271 llvm::Triple SystemTriple(llvm::sys::getProcessTriple());
1272 if (!SystemTriple.isMacOSX())
1273 return MacOSSDKVersion;
1274 SystemTriple.getMacOSXVersion(Major, Minor, Micro);
1275 VersionTuple SystemVersion(Major, Minor, Micro);
1277 if (!Driver::GetReleaseVersion(MacOSSDKVersion, Major, Minor, Micro,
1279 return MacOSSDKVersion;
1280 VersionTuple SDKVersion(Major, Minor, Micro);
1281 if (SDKVersion > SystemVersion)
1282 return SystemVersion.getAsString();
1283 return MacOSSDKVersion;
1288 /// The Darwin OS that was selected or inferred from arguments / environment.
1289 struct DarwinPlatform {
1291 /// The OS was specified using the -target argument.
1293 /// The OS was specified using the -m<os>-version-min argument.
1295 /// The OS was specified using the OS_DEPLOYMENT_TARGET environment.
1296 DeploymentTargetEnv,
1297 /// The OS was inferred from the SDK.
1299 /// The OS was inferred from the -arch.
1303 using DarwinPlatformKind = Darwin::DarwinPlatformKind;
1304 using DarwinEnvironmentKind = Darwin::DarwinEnvironmentKind;
1306 DarwinPlatformKind getPlatform() const { return Platform; }
1308 DarwinEnvironmentKind getEnvironment() const { return Environment; }
1310 void setEnvironment(DarwinEnvironmentKind Kind) {
1312 InferSimulatorFromArch = false;
1315 StringRef getOSVersion() const {
1316 if (Kind == OSVersionArg)
1317 return Argument->getValue();
1321 void setOSVersion(StringRef S) {
1322 assert(Kind == TargetArg && "Unexpected kind!");
1326 bool hasOSVersion() const { return HasOSVersion; }
1328 /// Returns true if the target OS was explicitly specified.
1329 bool isExplicitlySpecified() const { return Kind <= DeploymentTargetEnv; }
1331 /// Returns true if the simulator environment can be inferred from the arch.
1332 bool canInferSimulatorFromArch() const { return InferSimulatorFromArch; }
1334 /// Adds the -m<os>-version-min argument to the compiler invocation.
1335 void addOSVersionMinArgument(DerivedArgList &Args, const OptTable &Opts) {
1338 assert(Kind != TargetArg && Kind != OSVersionArg && "Invalid kind");
1341 case DarwinPlatformKind::MacOS:
1342 Opt = options::OPT_mmacosx_version_min_EQ;
1344 case DarwinPlatformKind::IPhoneOS:
1345 Opt = options::OPT_miphoneos_version_min_EQ;
1347 case DarwinPlatformKind::TvOS:
1348 Opt = options::OPT_mtvos_version_min_EQ;
1350 case DarwinPlatformKind::WatchOS:
1351 Opt = options::OPT_mwatchos_version_min_EQ;
1354 Argument = Args.MakeJoinedArg(nullptr, Opts.getOption(Opt), OSVersion);
1355 Args.append(Argument);
1358 /// Returns the OS version with the argument / environment variable that
1360 std::string getAsString(DerivedArgList &Args, const OptTable &Opts) {
1364 case InferredFromSDK:
1365 case InferredFromArch:
1366 assert(Argument && "OS version argument not yet inferred");
1367 return Argument->getAsString(Args);
1368 case DeploymentTargetEnv:
1369 return (llvm::Twine(EnvVarName) + "=" + OSVersion).str();
1371 llvm_unreachable("Unsupported Darwin Source Kind");
1374 static DarwinPlatform createFromTarget(const llvm::Triple &TT,
1375 StringRef OSVersion, Arg *A) {
1376 DarwinPlatform Result(TargetArg, getPlatformFromOS(TT.getOS()), OSVersion,
1378 switch (TT.getEnvironment()) {
1379 case llvm::Triple::Simulator:
1380 Result.Environment = DarwinEnvironmentKind::Simulator;
1385 unsigned Major, Minor, Micro;
1386 TT.getOSVersion(Major, Minor, Micro);
1388 Result.HasOSVersion = false;
1391 static DarwinPlatform createOSVersionArg(DarwinPlatformKind Platform,
1393 return DarwinPlatform(OSVersionArg, Platform, A);
1395 static DarwinPlatform createDeploymentTargetEnv(DarwinPlatformKind Platform,
1396 StringRef EnvVarName,
1398 DarwinPlatform Result(DeploymentTargetEnv, Platform, Value);
1399 Result.EnvVarName = EnvVarName;
1402 static DarwinPlatform createFromSDK(DarwinPlatformKind Platform,
1404 bool IsSimulator = false) {
1405 DarwinPlatform Result(InferredFromSDK, Platform, Value);
1407 Result.Environment = DarwinEnvironmentKind::Simulator;
1408 Result.InferSimulatorFromArch = false;
1411 static DarwinPlatform createFromArch(llvm::Triple::OSType OS,
1413 return DarwinPlatform(InferredFromArch, getPlatformFromOS(OS), Value);
1416 /// Constructs an inferred SDKInfo value based on the version inferred from
1417 /// the SDK path itself. Only works for values that were created by inferring
1418 /// the platform from the SDKPath.
1419 DarwinSDKInfo inferSDKInfo() {
1420 assert(Kind == InferredFromSDK && "can infer SDK info only");
1421 llvm::VersionTuple Version;
1422 bool IsValid = !Version.tryParse(OSVersion);
1424 assert(IsValid && "invalid SDK version");
1425 return DarwinSDKInfo(Version);
1429 DarwinPlatform(SourceKind Kind, DarwinPlatformKind Platform, Arg *Argument)
1430 : Kind(Kind), Platform(Platform), Argument(Argument) {}
1431 DarwinPlatform(SourceKind Kind, DarwinPlatformKind Platform, StringRef Value,
1432 Arg *Argument = nullptr)
1433 : Kind(Kind), Platform(Platform), OSVersion(Value), Argument(Argument) {}
1435 static DarwinPlatformKind getPlatformFromOS(llvm::Triple::OSType OS) {
1437 case llvm::Triple::Darwin:
1438 case llvm::Triple::MacOSX:
1439 return DarwinPlatformKind::MacOS;
1440 case llvm::Triple::IOS:
1441 return DarwinPlatformKind::IPhoneOS;
1442 case llvm::Triple::TvOS:
1443 return DarwinPlatformKind::TvOS;
1444 case llvm::Triple::WatchOS:
1445 return DarwinPlatformKind::WatchOS;
1447 llvm_unreachable("Unable to infer Darwin variant");
1452 DarwinPlatformKind Platform;
1453 DarwinEnvironmentKind Environment = DarwinEnvironmentKind::NativeEnvironment;
1454 std::string OSVersion;
1455 bool HasOSVersion = true, InferSimulatorFromArch = true;
1457 StringRef EnvVarName;
1460 /// Returns the deployment target that's specified using the -m<os>-version-min
1462 Optional<DarwinPlatform>
1463 getDeploymentTargetFromOSVersionArg(DerivedArgList &Args,
1464 const Driver &TheDriver) {
1465 Arg *OSXVersion = Args.getLastArg(options::OPT_mmacosx_version_min_EQ);
1466 Arg *iOSVersion = Args.getLastArg(options::OPT_miphoneos_version_min_EQ,
1467 options::OPT_mios_simulator_version_min_EQ);
1469 Args.getLastArg(options::OPT_mtvos_version_min_EQ,
1470 options::OPT_mtvos_simulator_version_min_EQ);
1471 Arg *WatchOSVersion =
1472 Args.getLastArg(options::OPT_mwatchos_version_min_EQ,
1473 options::OPT_mwatchos_simulator_version_min_EQ);
1475 if (iOSVersion || TvOSVersion || WatchOSVersion) {
1476 TheDriver.Diag(diag::err_drv_argument_not_allowed_with)
1477 << OSXVersion->getAsString(Args)
1478 << (iOSVersion ? iOSVersion
1479 : TvOSVersion ? TvOSVersion : WatchOSVersion)
1480 ->getAsString(Args);
1482 return DarwinPlatform::createOSVersionArg(Darwin::MacOS, OSXVersion);
1483 } else if (iOSVersion) {
1484 if (TvOSVersion || WatchOSVersion) {
1485 TheDriver.Diag(diag::err_drv_argument_not_allowed_with)
1486 << iOSVersion->getAsString(Args)
1487 << (TvOSVersion ? TvOSVersion : WatchOSVersion)->getAsString(Args);
1489 return DarwinPlatform::createOSVersionArg(Darwin::IPhoneOS, iOSVersion);
1490 } else if (TvOSVersion) {
1491 if (WatchOSVersion) {
1492 TheDriver.Diag(diag::err_drv_argument_not_allowed_with)
1493 << TvOSVersion->getAsString(Args)
1494 << WatchOSVersion->getAsString(Args);
1496 return DarwinPlatform::createOSVersionArg(Darwin::TvOS, TvOSVersion);
1497 } else if (WatchOSVersion)
1498 return DarwinPlatform::createOSVersionArg(Darwin::WatchOS, WatchOSVersion);
1502 /// Returns the deployment target that's specified using the
1503 /// OS_DEPLOYMENT_TARGET environment variable.
1504 Optional<DarwinPlatform>
1505 getDeploymentTargetFromEnvironmentVariables(const Driver &TheDriver,
1506 const llvm::Triple &Triple) {
1507 std::string Targets[Darwin::LastDarwinPlatform + 1];
1508 const char *EnvVars[] = {
1509 "MACOSX_DEPLOYMENT_TARGET",
1510 "IPHONEOS_DEPLOYMENT_TARGET",
1511 "TVOS_DEPLOYMENT_TARGET",
1512 "WATCHOS_DEPLOYMENT_TARGET",
1514 static_assert(llvm::array_lengthof(EnvVars) == Darwin::LastDarwinPlatform + 1,
1515 "Missing platform");
1516 for (const auto &I : llvm::enumerate(llvm::makeArrayRef(EnvVars))) {
1517 if (char *Env = ::getenv(I.value()))
1518 Targets[I.index()] = Env;
1521 // Allow conflicts among OSX and iOS for historical reasons, but choose the
1522 // default platform.
1523 if (!Targets[Darwin::MacOS].empty() &&
1524 (!Targets[Darwin::IPhoneOS].empty() ||
1525 !Targets[Darwin::WatchOS].empty() || !Targets[Darwin::TvOS].empty())) {
1526 if (Triple.getArch() == llvm::Triple::arm ||
1527 Triple.getArch() == llvm::Triple::aarch64 ||
1528 Triple.getArch() == llvm::Triple::thumb)
1529 Targets[Darwin::MacOS] = "";
1531 Targets[Darwin::IPhoneOS] = Targets[Darwin::WatchOS] =
1532 Targets[Darwin::TvOS] = "";
1534 // Don't allow conflicts in any other platform.
1535 unsigned FirstTarget = llvm::array_lengthof(Targets);
1536 for (unsigned I = 0; I != llvm::array_lengthof(Targets); ++I) {
1537 if (Targets[I].empty())
1539 if (FirstTarget == llvm::array_lengthof(Targets))
1542 TheDriver.Diag(diag::err_drv_conflicting_deployment_targets)
1543 << Targets[FirstTarget] << Targets[I];
1547 for (const auto &Target : llvm::enumerate(llvm::makeArrayRef(Targets))) {
1548 if (!Target.value().empty())
1549 return DarwinPlatform::createDeploymentTargetEnv(
1550 (Darwin::DarwinPlatformKind)Target.index(), EnvVars[Target.index()],
1556 /// Tries to infer the deployment target from the SDK specified by -isysroot
1557 /// (or SDKROOT). Uses the version specified in the SDKSettings.json file if
1559 Optional<DarwinPlatform>
1560 inferDeploymentTargetFromSDK(DerivedArgList &Args,
1561 const Optional<DarwinSDKInfo> &SDKInfo) {
1562 const Arg *A = Args.getLastArg(options::OPT_isysroot);
1565 StringRef isysroot = A->getValue();
1566 StringRef SDK = Darwin::getSDKName(isysroot);
1570 std::string Version;
1572 // Get the version from the SDKSettings.json if it's available.
1573 Version = SDKInfo->getVersion().getAsString();
1575 // Slice the version number out.
1576 // Version number is between the first and the last number.
1577 size_t StartVer = SDK.find_first_of("0123456789");
1578 size_t EndVer = SDK.find_last_of("0123456789");
1579 if (StartVer != StringRef::npos && EndVer > StartVer)
1580 Version = SDK.slice(StartVer, EndVer + 1);
1582 if (Version.empty())
1585 if (SDK.startswith("iPhoneOS") || SDK.startswith("iPhoneSimulator"))
1586 return DarwinPlatform::createFromSDK(
1587 Darwin::IPhoneOS, Version,
1588 /*IsSimulator=*/SDK.startswith("iPhoneSimulator"));
1589 else if (SDK.startswith("MacOSX"))
1590 return DarwinPlatform::createFromSDK(Darwin::MacOS,
1591 getSystemOrSDKMacOSVersion(Version));
1592 else if (SDK.startswith("WatchOS") || SDK.startswith("WatchSimulator"))
1593 return DarwinPlatform::createFromSDK(
1594 Darwin::WatchOS, Version,
1595 /*IsSimulator=*/SDK.startswith("WatchSimulator"));
1596 else if (SDK.startswith("AppleTVOS") || SDK.startswith("AppleTVSimulator"))
1597 return DarwinPlatform::createFromSDK(
1598 Darwin::TvOS, Version,
1599 /*IsSimulator=*/SDK.startswith("AppleTVSimulator"));
1603 std::string getOSVersion(llvm::Triple::OSType OS, const llvm::Triple &Triple,
1604 const Driver &TheDriver) {
1605 unsigned Major, Minor, Micro;
1606 llvm::Triple SystemTriple(llvm::sys::getProcessTriple());
1608 case llvm::Triple::Darwin:
1609 case llvm::Triple::MacOSX:
1610 // If there is no version specified on triple, and both host and target are
1611 // macos, use the host triple to infer OS version.
1612 if (Triple.isMacOSX() && SystemTriple.isMacOSX() &&
1613 !Triple.getOSMajorVersion())
1614 SystemTriple.getMacOSXVersion(Major, Minor, Micro);
1615 else if (!Triple.getMacOSXVersion(Major, Minor, Micro))
1616 TheDriver.Diag(diag::err_drv_invalid_darwin_version)
1617 << Triple.getOSName();
1619 case llvm::Triple::IOS:
1620 Triple.getiOSVersion(Major, Minor, Micro);
1622 case llvm::Triple::TvOS:
1623 Triple.getOSVersion(Major, Minor, Micro);
1625 case llvm::Triple::WatchOS:
1626 Triple.getWatchOSVersion(Major, Minor, Micro);
1629 llvm_unreachable("Unexpected OS type");
1633 std::string OSVersion;
1634 llvm::raw_string_ostream(OSVersion) << Major << '.' << Minor << '.' << Micro;
1638 /// Tries to infer the target OS from the -arch.
1639 Optional<DarwinPlatform>
1640 inferDeploymentTargetFromArch(DerivedArgList &Args, const Darwin &Toolchain,
1641 const llvm::Triple &Triple,
1642 const Driver &TheDriver) {
1643 llvm::Triple::OSType OSTy = llvm::Triple::UnknownOS;
1645 StringRef MachOArchName = Toolchain.getMachOArchName(Args);
1646 if (MachOArchName == "armv7" || MachOArchName == "armv7s" ||
1647 MachOArchName == "arm64")
1648 OSTy = llvm::Triple::IOS;
1649 else if (MachOArchName == "armv7k" || MachOArchName == "arm64_32")
1650 OSTy = llvm::Triple::WatchOS;
1651 else if (MachOArchName != "armv6m" && MachOArchName != "armv7m" &&
1652 MachOArchName != "armv7em")
1653 OSTy = llvm::Triple::MacOSX;
1655 if (OSTy == llvm::Triple::UnknownOS)
1657 return DarwinPlatform::createFromArch(OSTy,
1658 getOSVersion(OSTy, Triple, TheDriver));
1661 /// Returns the deployment target that's specified using the -target option.
1662 Optional<DarwinPlatform> getDeploymentTargetFromTargetArg(
1663 DerivedArgList &Args, const llvm::Triple &Triple, const Driver &TheDriver) {
1664 if (!Args.hasArg(options::OPT_target))
1666 if (Triple.getOS() == llvm::Triple::Darwin ||
1667 Triple.getOS() == llvm::Triple::UnknownOS)
1669 std::string OSVersion = getOSVersion(Triple.getOS(), Triple, TheDriver);
1670 return DarwinPlatform::createFromTarget(Triple, OSVersion,
1671 Args.getLastArg(options::OPT_target));
1674 Optional<DarwinSDKInfo> parseSDKSettings(llvm::vfs::FileSystem &VFS,
1675 const ArgList &Args,
1676 const Driver &TheDriver) {
1677 const Arg *A = Args.getLastArg(options::OPT_isysroot);
1680 StringRef isysroot = A->getValue();
1681 auto SDKInfoOrErr = driver::parseDarwinSDKInfo(VFS, isysroot);
1682 if (!SDKInfoOrErr) {
1683 llvm::consumeError(SDKInfoOrErr.takeError());
1684 TheDriver.Diag(diag::warn_drv_darwin_sdk_invalid_settings);
1687 return *SDKInfoOrErr;
1692 void Darwin::AddDeploymentTarget(DerivedArgList &Args) const {
1693 const OptTable &Opts = getDriver().getOpts();
1695 // Support allowing the SDKROOT environment variable used by xcrun and other
1696 // Xcode tools to define the default sysroot, by making it the default for
1698 if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
1699 // Warn if the path does not exist.
1700 if (!getVFS().exists(A->getValue()))
1701 getDriver().Diag(clang::diag::warn_missing_sysroot) << A->getValue();
1703 if (char *env = ::getenv("SDKROOT")) {
1704 // We only use this value as the default if it is an absolute path,
1705 // exists, and it is not the root path.
1706 if (llvm::sys::path::is_absolute(env) && getVFS().exists(env) &&
1707 StringRef(env) != "/") {
1708 Args.append(Args.MakeSeparateArg(
1709 nullptr, Opts.getOption(options::OPT_isysroot), env));
1714 // Read the SDKSettings.json file for more information, like the SDK version
1715 // that we can pass down to the compiler.
1716 SDKInfo = parseSDKSettings(getVFS(), Args, getDriver());
1718 // The OS and the version can be specified using the -target argument.
1719 Optional<DarwinPlatform> OSTarget =
1720 getDeploymentTargetFromTargetArg(Args, getTriple(), getDriver());
1722 Optional<DarwinPlatform> OSVersionArgTarget =
1723 getDeploymentTargetFromOSVersionArg(Args, getDriver());
1724 if (OSVersionArgTarget) {
1725 unsigned TargetMajor, TargetMinor, TargetMicro;
1727 unsigned ArgMajor, ArgMinor, ArgMicro;
1729 if (OSTarget->getPlatform() != OSVersionArgTarget->getPlatform() ||
1730 (Driver::GetReleaseVersion(OSTarget->getOSVersion(), TargetMajor,
1731 TargetMinor, TargetMicro, TargetExtra) &&
1732 Driver::GetReleaseVersion(OSVersionArgTarget->getOSVersion(),
1733 ArgMajor, ArgMinor, ArgMicro, ArgExtra) &&
1734 (VersionTuple(TargetMajor, TargetMinor, TargetMicro) !=
1735 VersionTuple(ArgMajor, ArgMinor, ArgMicro) ||
1736 TargetExtra != ArgExtra))) {
1737 // Select the OS version from the -m<os>-version-min argument when
1738 // the -target does not include an OS version.
1739 if (OSTarget->getPlatform() == OSVersionArgTarget->getPlatform() &&
1740 !OSTarget->hasOSVersion()) {
1741 OSTarget->setOSVersion(OSVersionArgTarget->getOSVersion());
1743 // Warn about -m<os>-version-min that doesn't match the OS version
1744 // that's specified in the target.
1745 std::string OSVersionArg =
1746 OSVersionArgTarget->getAsString(Args, Opts);
1747 std::string TargetArg = OSTarget->getAsString(Args, Opts);
1748 getDriver().Diag(clang::diag::warn_drv_overriding_flag_option)
1749 << OSVersionArg << TargetArg;
1754 // The OS target can be specified using the -m<os>version-min argument.
1755 OSTarget = getDeploymentTargetFromOSVersionArg(Args, getDriver());
1756 // If no deployment target was specified on the command line, check for
1757 // environment defines.
1760 getDeploymentTargetFromEnvironmentVariables(getDriver(), getTriple());
1762 // Don't infer simulator from the arch when the SDK is also specified.
1763 Optional<DarwinPlatform> SDKTarget =
1764 inferDeploymentTargetFromSDK(Args, SDKInfo);
1766 OSTarget->setEnvironment(SDKTarget->getEnvironment());
1769 // If there is no command-line argument to specify the Target version and
1770 // no environment variable defined, see if we can set the default based
1771 // on -isysroot using SDKSettings.json if it exists.
1773 OSTarget = inferDeploymentTargetFromSDK(Args, SDKInfo);
1774 /// If the target was successfully constructed from the SDK path, try to
1775 /// infer the SDK info if the SDK doesn't have it.
1776 if (OSTarget && !SDKInfo)
1777 SDKInfo = OSTarget->inferSDKInfo();
1779 // If no OS targets have been specified, try to guess platform from -target
1780 // or arch name and compute the version from the triple.
1783 inferDeploymentTargetFromArch(Args, *this, getTriple(), getDriver());
1786 assert(OSTarget && "Unable to infer Darwin variant");
1787 OSTarget->addOSVersionMinArgument(Args, Opts);
1788 DarwinPlatformKind Platform = OSTarget->getPlatform();
1790 unsigned Major, Minor, Micro;
1792 // Set the tool chain target information.
1793 if (Platform == MacOS) {
1794 if (!Driver::GetReleaseVersion(OSTarget->getOSVersion(), Major, Minor,
1796 HadExtra || Major != 10 || Minor >= 100 || Micro >= 100)
1797 getDriver().Diag(diag::err_drv_invalid_version_number)
1798 << OSTarget->getAsString(Args, Opts);
1799 } else if (Platform == IPhoneOS) {
1800 if (!Driver::GetReleaseVersion(OSTarget->getOSVersion(), Major, Minor,
1802 HadExtra || Major >= 100 || Minor >= 100 || Micro >= 100)
1803 getDriver().Diag(diag::err_drv_invalid_version_number)
1804 << OSTarget->getAsString(Args, Opts);
1806 // For 32-bit targets, the deployment target for iOS has to be earlier than
1808 if (getTriple().isArch32Bit() && Major >= 11) {
1809 // If the deployment target is explicitly specified, print a diagnostic.
1810 if (OSTarget->isExplicitlySpecified()) {
1811 getDriver().Diag(diag::warn_invalid_ios_deployment_target)
1812 << OSTarget->getAsString(Args, Opts);
1813 // Otherwise, set it to 10.99.99.
1820 } else if (Platform == TvOS) {
1821 if (!Driver::GetReleaseVersion(OSTarget->getOSVersion(), Major, Minor,
1823 HadExtra || Major >= 100 || Minor >= 100 || Micro >= 100)
1824 getDriver().Diag(diag::err_drv_invalid_version_number)
1825 << OSTarget->getAsString(Args, Opts);
1826 } else if (Platform == WatchOS) {
1827 if (!Driver::GetReleaseVersion(OSTarget->getOSVersion(), Major, Minor,
1829 HadExtra || Major >= 10 || Minor >= 100 || Micro >= 100)
1830 getDriver().Diag(diag::err_drv_invalid_version_number)
1831 << OSTarget->getAsString(Args, Opts);
1833 llvm_unreachable("unknown kind of Darwin platform");
1835 DarwinEnvironmentKind Environment = OSTarget->getEnvironment();
1836 // Recognize iOS targets with an x86 architecture as the iOS simulator.
1837 if (Environment == NativeEnvironment && Platform != MacOS &&
1838 OSTarget->canInferSimulatorFromArch() && getTriple().isX86())
1839 Environment = Simulator;
1841 setTarget(Platform, Environment, Major, Minor, Micro);
1843 if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
1844 StringRef SDK = getSDKName(A->getValue());
1845 if (SDK.size() > 0) {
1846 size_t StartVer = SDK.find_first_of("0123456789");
1847 StringRef SDKName = SDK.slice(0, StartVer);
1848 if (!SDKName.startswith(getPlatformFamily()))
1849 getDriver().Diag(diag::warn_incompatible_sysroot)
1850 << SDKName << getPlatformFamily();
1855 // Returns the effective header sysroot path to use. This comes either from
1856 // -isysroot or --sysroot.
1857 llvm::StringRef DarwinClang::GetHeaderSysroot(const llvm::opt::ArgList &DriverArgs) const {
1858 if(DriverArgs.hasArg(options::OPT_isysroot))
1859 return DriverArgs.getLastArgValue(options::OPT_isysroot);
1860 if (!getDriver().SysRoot.empty())
1861 return getDriver().SysRoot;
1865 void DarwinClang::AddClangSystemIncludeArgs(const llvm::opt::ArgList &DriverArgs,
1866 llvm::opt::ArgStringList &CC1Args) const {
1867 const Driver &D = getDriver();
1869 llvm::StringRef Sysroot = GetHeaderSysroot(DriverArgs);
1871 bool NoStdInc = DriverArgs.hasArg(options::OPT_nostdinc);
1872 bool NoStdlibInc = DriverArgs.hasArg(options::OPT_nostdlibinc);
1873 bool NoBuiltinInc = DriverArgs.hasArg(options::OPT_nobuiltininc);
1875 // Add <sysroot>/usr/local/include
1876 if (!NoStdInc && !NoStdlibInc) {
1877 SmallString<128> P(Sysroot);
1878 llvm::sys::path::append(P, "usr", "local", "include");
1879 addSystemInclude(DriverArgs, CC1Args, P);
1882 // Add the Clang builtin headers (<resource>/include)
1883 if (!NoStdInc && !NoBuiltinInc) {
1884 SmallString<128> P(D.ResourceDir);
1885 llvm::sys::path::append(P, "include");
1886 addSystemInclude(DriverArgs, CC1Args, P);
1889 if (NoStdInc || NoStdlibInc)
1892 // Check for configure-time C include directories.
1893 llvm::StringRef CIncludeDirs(C_INCLUDE_DIRS);
1894 if (!CIncludeDirs.empty()) {
1895 llvm::SmallVector<llvm::StringRef, 5> dirs;
1896 CIncludeDirs.split(dirs, ":");
1897 for (llvm::StringRef dir : dirs) {
1898 llvm::StringRef Prefix =
1899 llvm::sys::path::is_absolute(dir) ? llvm::StringRef(Sysroot) : "";
1900 addExternCSystemInclude(DriverArgs, CC1Args, Prefix + dir);
1903 // Otherwise, add <sysroot>/usr/include.
1904 SmallString<128> P(Sysroot);
1905 llvm::sys::path::append(P, "usr", "include");
1906 addExternCSystemInclude(DriverArgs, CC1Args, P.str());
1910 bool DarwinClang::AddGnuCPlusPlusIncludePaths(const llvm::opt::ArgList &DriverArgs,
1911 llvm::opt::ArgStringList &CC1Args,
1912 llvm::SmallString<128> Base,
1913 llvm::StringRef Version,
1914 llvm::StringRef ArchDir,
1915 llvm::StringRef BitDir) const {
1916 llvm::sys::path::append(Base, Version);
1919 addSystemInclude(DriverArgs, CC1Args, Base);
1921 // Add the multilib dirs
1923 llvm::SmallString<128> P = Base;
1924 if (!ArchDir.empty())
1925 llvm::sys::path::append(P, ArchDir);
1926 if (!BitDir.empty())
1927 llvm::sys::path::append(P, BitDir);
1928 addSystemInclude(DriverArgs, CC1Args, P);
1931 // Add the backward dir
1933 llvm::SmallString<128> P = Base;
1934 llvm::sys::path::append(P, "backward");
1935 addSystemInclude(DriverArgs, CC1Args, P);
1938 return getVFS().exists(Base);
1941 void DarwinClang::AddClangCXXStdlibIncludeArgs(
1942 const llvm::opt::ArgList &DriverArgs,
1943 llvm::opt::ArgStringList &CC1Args) const {
1944 // The implementation from a base class will pass through the -stdlib to
1946 // FIXME: this should not be necessary, remove usages in the frontend
1947 // (e.g. HeaderSearchOptions::UseLibcxx) and don't pipe -stdlib.
1948 // Also check whether this is used for setting library search paths.
1949 ToolChain::AddClangCXXStdlibIncludeArgs(DriverArgs, CC1Args);
1951 if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
1952 DriverArgs.hasArg(options::OPT_nostdincxx))
1955 llvm::StringRef Sysroot = GetHeaderSysroot(DriverArgs);
1957 switch (GetCXXStdlibType(DriverArgs)) {
1958 case ToolChain::CST_Libcxx: {
1959 // On Darwin, libc++ is installed alongside the compiler in
1960 // include/c++/v1, so get from '<install>/bin' to '<install>/include/c++/v1'.
1962 llvm::SmallString<128> P = llvm::StringRef(getDriver().getInstalledDir());
1963 // Note that P can be relative, so we have to '..' and not parent_path.
1964 llvm::sys::path::append(P, "..", "include", "c++", "v1");
1965 addSystemInclude(DriverArgs, CC1Args, P);
1967 // Also add <sysroot>/usr/include/c++/v1 unless -nostdinc is used,
1968 // to match the legacy behavior in CC1.
1969 if (!DriverArgs.hasArg(options::OPT_nostdinc)) {
1970 llvm::SmallString<128> P = Sysroot;
1971 llvm::sys::path::append(P, "usr", "include", "c++", "v1");
1972 addSystemInclude(DriverArgs, CC1Args, P);
1977 case ToolChain::CST_Libstdcxx:
1978 llvm::SmallString<128> UsrIncludeCxx = Sysroot;
1979 llvm::sys::path::append(UsrIncludeCxx, "usr", "include", "c++");
1981 llvm::Triple::ArchType arch = getTriple().getArch();
1982 bool IsBaseFound = true;
1986 case llvm::Triple::ppc:
1987 case llvm::Triple::ppc64:
1988 IsBaseFound = AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, UsrIncludeCxx,
1990 "powerpc-apple-darwin10",
1991 arch == llvm::Triple::ppc64 ? "ppc64" : "");
1992 IsBaseFound |= AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, UsrIncludeCxx,
1993 "4.0.0", "powerpc-apple-darwin10",
1994 arch == llvm::Triple::ppc64 ? "ppc64" : "");
1997 case llvm::Triple::x86:
1998 case llvm::Triple::x86_64:
1999 IsBaseFound = AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, UsrIncludeCxx,
2001 "i686-apple-darwin10",
2002 arch == llvm::Triple::x86_64 ? "x86_64" : "");
2003 IsBaseFound |= AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, UsrIncludeCxx,
2004 "4.0.0", "i686-apple-darwin8",
2008 case llvm::Triple::arm:
2009 case llvm::Triple::thumb:
2010 IsBaseFound = AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, UsrIncludeCxx,
2012 "arm-apple-darwin10",
2014 IsBaseFound |= AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, UsrIncludeCxx,
2016 "arm-apple-darwin10",
2020 case llvm::Triple::aarch64:
2021 IsBaseFound = AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, UsrIncludeCxx,
2023 "arm64-apple-darwin10",
2029 getDriver().Diag(diag::warn_drv_libstdcxx_not_found);
2035 void DarwinClang::AddCXXStdlibLibArgs(const ArgList &Args,
2036 ArgStringList &CmdArgs) const {
2037 CXXStdlibType Type = GetCXXStdlibType(Args);
2040 case ToolChain::CST_Libcxx:
2041 CmdArgs.push_back("-lc++");
2044 case ToolChain::CST_Libstdcxx:
2045 // Unfortunately, -lstdc++ doesn't always exist in the standard search path;
2046 // it was previously found in the gcc lib dir. However, for all the Darwin
2047 // platforms we care about it was -lstdc++.6, so we search for that
2048 // explicitly if we can't see an obvious -lstdc++ candidate.
2050 // Check in the sysroot first.
2051 if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
2052 SmallString<128> P(A->getValue());
2053 llvm::sys::path::append(P, "usr", "lib", "libstdc++.dylib");
2055 if (!getVFS().exists(P)) {
2056 llvm::sys::path::remove_filename(P);
2057 llvm::sys::path::append(P, "libstdc++.6.dylib");
2058 if (getVFS().exists(P)) {
2059 CmdArgs.push_back(Args.MakeArgString(P));
2065 // Otherwise, look in the root.
2066 // FIXME: This should be removed someday when we don't have to care about
2067 // 10.6 and earlier, where /usr/lib/libstdc++.dylib does not exist.
2068 if (!getVFS().exists("/usr/lib/libstdc++.dylib") &&
2069 getVFS().exists("/usr/lib/libstdc++.6.dylib")) {
2070 CmdArgs.push_back("/usr/lib/libstdc++.6.dylib");
2074 // Otherwise, let the linker search.
2075 CmdArgs.push_back("-lstdc++");
2080 void DarwinClang::AddCCKextLibArgs(const ArgList &Args,
2081 ArgStringList &CmdArgs) const {
2082 // For Darwin platforms, use the compiler-rt-based support library
2083 // instead of the gcc-provided one (which is also incidentally
2084 // only present in the gcc lib dir, which makes it hard to find).
2086 SmallString<128> P(getDriver().ResourceDir);
2087 llvm::sys::path::append(P, "lib", "darwin");
2089 // Use the newer cc_kext for iOS ARM after 6.0.
2090 if (isTargetWatchOS()) {
2091 llvm::sys::path::append(P, "libclang_rt.cc_kext_watchos.a");
2092 } else if (isTargetTvOS()) {
2093 llvm::sys::path::append(P, "libclang_rt.cc_kext_tvos.a");
2094 } else if (isTargetIPhoneOS()) {
2095 llvm::sys::path::append(P, "libclang_rt.cc_kext_ios.a");
2097 llvm::sys::path::append(P, "libclang_rt.cc_kext.a");
2100 // For now, allow missing resource libraries to support developers who may
2101 // not have compiler-rt checked out or integrated into their build.
2102 if (getVFS().exists(P))
2103 CmdArgs.push_back(Args.MakeArgString(P));
2106 DerivedArgList *MachO::TranslateArgs(const DerivedArgList &Args,
2107 StringRef BoundArch,
2108 Action::OffloadKind) const {
2109 DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
2110 const OptTable &Opts = getDriver().getOpts();
2112 // FIXME: We really want to get out of the tool chain level argument
2113 // translation business, as it makes the driver functionality much
2114 // more opaque. For now, we follow gcc closely solely for the
2115 // purpose of easily achieving feature parity & testability. Once we
2116 // have something that works, we should reevaluate each translation
2117 // and try to push it down into tool specific logic.
2119 for (Arg *A : Args) {
2120 if (A->getOption().matches(options::OPT_Xarch__)) {
2121 // Skip this argument unless the architecture matches either the toolchain
2122 // triple arch, or the arch being bound.
2123 llvm::Triple::ArchType XarchArch =
2124 tools::darwin::getArchTypeForMachOArchName(A->getValue(0));
2125 if (!(XarchArch == getArch() ||
2126 (!BoundArch.empty() &&
2128 tools::darwin::getArchTypeForMachOArchName(BoundArch))))
2131 Arg *OriginalArg = A;
2132 unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
2133 unsigned Prev = Index;
2134 std::unique_ptr<Arg> XarchArg(Opts.ParseOneArg(Args, Index));
2136 // If the argument parsing failed or more than one argument was
2137 // consumed, the -Xarch_ argument's parameter tried to consume
2138 // extra arguments. Emit an error and ignore.
2140 // We also want to disallow any options which would alter the
2141 // driver behavior; that isn't going to work in our model. We
2142 // use isDriverOption() as an approximation, although things
2143 // like -O4 are going to slip through.
2144 if (!XarchArg || Index > Prev + 1) {
2145 getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args)
2146 << A->getAsString(Args);
2148 } else if (XarchArg->getOption().hasFlag(options::DriverOption)) {
2149 getDriver().Diag(diag::err_drv_invalid_Xarch_argument_isdriver)
2150 << A->getAsString(Args);
2154 XarchArg->setBaseArg(A);
2156 A = XarchArg.release();
2157 DAL->AddSynthesizedArg(A);
2159 // Linker input arguments require custom handling. The problem is that we
2160 // have already constructed the phase actions, so we can not treat them as
2161 // "input arguments".
2162 if (A->getOption().hasFlag(options::LinkerInput)) {
2163 // Convert the argument into individual Zlinker_input_args.
2164 for (const char *Value : A->getValues()) {
2165 DAL->AddSeparateArg(
2166 OriginalArg, Opts.getOption(options::OPT_Zlinker_input), Value);
2172 // Sob. These is strictly gcc compatible for the time being. Apple
2173 // gcc translates options twice, which means that self-expanding
2174 // options add duplicates.
2175 switch ((options::ID)A->getOption().getID()) {
2180 case options::OPT_mkernel:
2181 case options::OPT_fapple_kext:
2183 DAL->AddFlagArg(A, Opts.getOption(options::OPT_static));
2186 case options::OPT_dependency_file:
2187 DAL->AddSeparateArg(A, Opts.getOption(options::OPT_MF), A->getValue());
2190 case options::OPT_gfull:
2191 DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
2193 A, Opts.getOption(options::OPT_fno_eliminate_unused_debug_symbols));
2196 case options::OPT_gused:
2197 DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
2199 A, Opts.getOption(options::OPT_feliminate_unused_debug_symbols));
2202 case options::OPT_shared:
2203 DAL->AddFlagArg(A, Opts.getOption(options::OPT_dynamiclib));
2206 case options::OPT_fconstant_cfstrings:
2207 DAL->AddFlagArg(A, Opts.getOption(options::OPT_mconstant_cfstrings));
2210 case options::OPT_fno_constant_cfstrings:
2211 DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_constant_cfstrings));
2214 case options::OPT_Wnonportable_cfstrings:
2216 Opts.getOption(options::OPT_mwarn_nonportable_cfstrings));
2219 case options::OPT_Wno_nonportable_cfstrings:
2221 A, Opts.getOption(options::OPT_mno_warn_nonportable_cfstrings));
2224 case options::OPT_fpascal_strings:
2225 DAL->AddFlagArg(A, Opts.getOption(options::OPT_mpascal_strings));
2228 case options::OPT_fno_pascal_strings:
2229 DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_pascal_strings));
2234 if (getTriple().isX86())
2235 if (!Args.hasArgNoClaim(options::OPT_mtune_EQ))
2236 DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_mtune_EQ),
2239 // Add the arch options based on the particular spelling of -arch, to match
2240 // how the driver driver works.
2241 if (!BoundArch.empty()) {
2242 StringRef Name = BoundArch;
2243 const Option MCpu = Opts.getOption(options::OPT_mcpu_EQ);
2244 const Option MArch = Opts.getOption(clang::driver::options::OPT_march_EQ);
2246 // This code must be kept in sync with LLVM's getArchTypeForDarwinArch,
2247 // which defines the list of which architectures we accept.
2250 else if (Name == "ppc601")
2251 DAL->AddJoinedArg(nullptr, MCpu, "601");
2252 else if (Name == "ppc603")
2253 DAL->AddJoinedArg(nullptr, MCpu, "603");
2254 else if (Name == "ppc604")
2255 DAL->AddJoinedArg(nullptr, MCpu, "604");
2256 else if (Name == "ppc604e")
2257 DAL->AddJoinedArg(nullptr, MCpu, "604e");
2258 else if (Name == "ppc750")
2259 DAL->AddJoinedArg(nullptr, MCpu, "750");
2260 else if (Name == "ppc7400")
2261 DAL->AddJoinedArg(nullptr, MCpu, "7400");
2262 else if (Name == "ppc7450")
2263 DAL->AddJoinedArg(nullptr, MCpu, "7450");
2264 else if (Name == "ppc970")
2265 DAL->AddJoinedArg(nullptr, MCpu, "970");
2267 else if (Name == "ppc64" || Name == "ppc64le")
2268 DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64));
2270 else if (Name == "i386")
2272 else if (Name == "i486")
2273 DAL->AddJoinedArg(nullptr, MArch, "i486");
2274 else if (Name == "i586")
2275 DAL->AddJoinedArg(nullptr, MArch, "i586");
2276 else if (Name == "i686")
2277 DAL->AddJoinedArg(nullptr, MArch, "i686");
2278 else if (Name == "pentium")
2279 DAL->AddJoinedArg(nullptr, MArch, "pentium");
2280 else if (Name == "pentium2")
2281 DAL->AddJoinedArg(nullptr, MArch, "pentium2");
2282 else if (Name == "pentpro")
2283 DAL->AddJoinedArg(nullptr, MArch, "pentiumpro");
2284 else if (Name == "pentIIm3")
2285 DAL->AddJoinedArg(nullptr, MArch, "pentium2");
2287 else if (Name == "x86_64" || Name == "x86_64h")
2288 DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64));
2290 else if (Name == "arm")
2291 DAL->AddJoinedArg(nullptr, MArch, "armv4t");
2292 else if (Name == "armv4t")
2293 DAL->AddJoinedArg(nullptr, MArch, "armv4t");
2294 else if (Name == "armv5")
2295 DAL->AddJoinedArg(nullptr, MArch, "armv5tej");
2296 else if (Name == "xscale")
2297 DAL->AddJoinedArg(nullptr, MArch, "xscale");
2298 else if (Name == "armv6")
2299 DAL->AddJoinedArg(nullptr, MArch, "armv6k");
2300 else if (Name == "armv6m")
2301 DAL->AddJoinedArg(nullptr, MArch, "armv6m");
2302 else if (Name == "armv7")
2303 DAL->AddJoinedArg(nullptr, MArch, "armv7a");
2304 else if (Name == "armv7em")
2305 DAL->AddJoinedArg(nullptr, MArch, "armv7em");
2306 else if (Name == "armv7k")
2307 DAL->AddJoinedArg(nullptr, MArch, "armv7k");
2308 else if (Name == "armv7m")
2309 DAL->AddJoinedArg(nullptr, MArch, "armv7m");
2310 else if (Name == "armv7s")
2311 DAL->AddJoinedArg(nullptr, MArch, "armv7s");
2317 void MachO::AddLinkRuntimeLibArgs(const ArgList &Args,
2318 ArgStringList &CmdArgs,
2319 bool ForceLinkBuiltinRT) const {
2320 // Embedded targets are simple at the moment, not supporting sanitizers and
2321 // with different libraries for each member of the product { static, PIC } x
2322 // { hard-float, soft-float }
2323 llvm::SmallString<32> CompilerRT = StringRef("");
2325 (tools::arm::getARMFloatABI(*this, Args) == tools::arm::FloatABI::Hard)
2328 CompilerRT += Args.hasArg(options::OPT_fPIC) ? "_pic" : "_static";
2330 AddLinkRuntimeLib(Args, CmdArgs, CompilerRT, RLO_IsEmbedded);
2333 bool Darwin::isAlignedAllocationUnavailable() const {
2334 llvm::Triple::OSType OS;
2336 switch (TargetPlatform) {
2337 case MacOS: // Earlier than 10.13.
2338 OS = llvm::Triple::MacOSX;
2341 OS = llvm::Triple::IOS;
2343 case TvOS: // Earlier than 11.0.
2344 OS = llvm::Triple::TvOS;
2346 case WatchOS: // Earlier than 4.0.
2347 OS = llvm::Triple::WatchOS;
2351 return TargetVersion < alignedAllocMinVersion(OS);
2354 void Darwin::addClangTargetOptions(const llvm::opt::ArgList &DriverArgs,
2355 llvm::opt::ArgStringList &CC1Args,
2356 Action::OffloadKind DeviceOffloadKind) const {
2357 // Pass "-faligned-alloc-unavailable" only when the user hasn't manually
2358 // enabled or disabled aligned allocations.
2359 if (!DriverArgs.hasArgNoClaim(options::OPT_faligned_allocation,
2360 options::OPT_fno_aligned_allocation) &&
2361 isAlignedAllocationUnavailable())
2362 CC1Args.push_back("-faligned-alloc-unavailable");
2365 /// Pass the SDK version to the compiler when the SDK information is
2368 llvm::raw_string_ostream OS(Arg);
2369 OS << "-target-sdk-version=" << SDKInfo->getVersion();
2370 CC1Args.push_back(DriverArgs.MakeArgString(OS.str()));
2375 Darwin::TranslateArgs(const DerivedArgList &Args, StringRef BoundArch,
2376 Action::OffloadKind DeviceOffloadKind) const {
2377 // First get the generic Apple args, before moving onto Darwin-specific ones.
2378 DerivedArgList *DAL =
2379 MachO::TranslateArgs(Args, BoundArch, DeviceOffloadKind);
2380 const OptTable &Opts = getDriver().getOpts();
2382 // If no architecture is bound, none of the translations here are relevant.
2383 if (BoundArch.empty())
2386 // Add an explicit version min argument for the deployment target. We do this
2387 // after argument translation because -Xarch_ arguments may add a version min
2389 AddDeploymentTarget(*DAL);
2391 // For iOS 6, undo the translation to add -static for -mkernel/-fapple-kext.
2392 // FIXME: It would be far better to avoid inserting those -static arguments,
2393 // but we can't check the deployment target in the translation code until
2395 if (isTargetWatchOSBased() ||
2396 (isTargetIOSBased() && !isIPhoneOSVersionLT(6, 0))) {
2397 for (ArgList::iterator it = DAL->begin(), ie = DAL->end(); it != ie; ) {
2400 if (A->getOption().getID() != options::OPT_mkernel &&
2401 A->getOption().getID() != options::OPT_fapple_kext)
2403 assert(it != ie && "unexpected argument translation");
2405 assert(A->getOption().getID() == options::OPT_static &&
2406 "missing expected -static argument");
2412 if (!Args.getLastArg(options::OPT_stdlib_EQ) &&
2413 GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
2414 DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_stdlib_EQ),
2417 // Validate the C++ standard library choice.
2418 CXXStdlibType Type = GetCXXStdlibType(*DAL);
2419 if (Type == ToolChain::CST_Libcxx) {
2420 // Check whether the target provides libc++.
2423 // Complain about targeting iOS < 5.0 in any way.
2424 if (isTargetIOSBased() && isIPhoneOSVersionLT(5, 0))
2427 if (where != StringRef()) {
2428 getDriver().Diag(clang::diag::err_drv_invalid_libcxx_deployment) << where;
2432 auto Arch = tools::darwin::getArchTypeForMachOArchName(BoundArch);
2433 if ((Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb)) {
2434 if (Args.hasFlag(options::OPT_fomit_frame_pointer,
2435 options::OPT_fno_omit_frame_pointer, false))
2436 getDriver().Diag(clang::diag::warn_drv_unsupported_opt_for_target)
2437 << "-fomit-frame-pointer" << BoundArch;
2443 bool MachO::IsUnwindTablesDefault(const ArgList &Args) const {
2444 // Unwind tables are not emitted if -fno-exceptions is supplied (except when
2445 // targeting x86_64).
2446 return getArch() == llvm::Triple::x86_64 ||
2447 (GetExceptionModel(Args) != llvm::ExceptionHandling::SjLj &&
2448 Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
2452 bool MachO::UseDwarfDebugFlags() const {
2453 if (const char *S = ::getenv("RC_DEBUG_OPTIONS"))
2454 return S[0] != '\0';
2458 llvm::ExceptionHandling Darwin::GetExceptionModel(const ArgList &Args) const {
2459 // Darwin uses SjLj exceptions on ARM.
2460 if (getTriple().getArch() != llvm::Triple::arm &&
2461 getTriple().getArch() != llvm::Triple::thumb)
2462 return llvm::ExceptionHandling::None;
2464 // Only watchOS uses the new DWARF/Compact unwinding method.
2465 llvm::Triple Triple(ComputeLLVMTriple(Args));
2466 if (Triple.isWatchABI())
2467 return llvm::ExceptionHandling::DwarfCFI;
2469 return llvm::ExceptionHandling::SjLj;
2472 bool Darwin::SupportsEmbeddedBitcode() const {
2473 assert(TargetInitialized && "Target not initialized!");
2474 if (isTargetIPhoneOS() && isIPhoneOSVersionLT(6, 0))
2479 bool MachO::isPICDefault() const { return true; }
2481 bool MachO::isPIEDefault() const { return false; }
2483 bool MachO::isPICDefaultForced() const {
2484 return (getArch() == llvm::Triple::x86_64 ||
2485 getArch() == llvm::Triple::aarch64);
2488 bool MachO::SupportsProfiling() const {
2489 // Profiling instrumentation is only supported on x86.
2490 return getTriple().isX86();
2493 void Darwin::addMinVersionArgs(const ArgList &Args,
2494 ArgStringList &CmdArgs) const {
2495 VersionTuple TargetVersion = getTargetVersion();
2497 if (isTargetWatchOS())
2498 CmdArgs.push_back("-watchos_version_min");
2499 else if (isTargetWatchOSSimulator())
2500 CmdArgs.push_back("-watchos_simulator_version_min");
2501 else if (isTargetTvOS())
2502 CmdArgs.push_back("-tvos_version_min");
2503 else if (isTargetTvOSSimulator())
2504 CmdArgs.push_back("-tvos_simulator_version_min");
2505 else if (isTargetIOSSimulator())
2506 CmdArgs.push_back("-ios_simulator_version_min");
2507 else if (isTargetIOSBased())
2508 CmdArgs.push_back("-iphoneos_version_min");
2510 assert(isTargetMacOS() && "unexpected target");
2511 CmdArgs.push_back("-macosx_version_min");
2514 CmdArgs.push_back(Args.MakeArgString(TargetVersion.getAsString()));
2517 static const char *getPlatformName(Darwin::DarwinPlatformKind Platform,
2518 Darwin::DarwinEnvironmentKind Environment) {
2522 case Darwin::IPhoneOS:
2523 if (Environment == Darwin::NativeEnvironment ||
2524 Environment == Darwin::Simulator)
2526 // FIXME: Add macCatalyst support here ("\"mac catalyst\"").
2527 llvm_unreachable("macCatalyst isn't yet supported");
2530 case Darwin::WatchOS:
2533 llvm_unreachable("invalid platform");
2536 void Darwin::addPlatformVersionArgs(const llvm::opt::ArgList &Args,
2537 llvm::opt::ArgStringList &CmdArgs) const {
2538 // -platform_version <platform> <target_version> <sdk_version>
2539 // Both the target and SDK version support only up to 3 components.
2540 CmdArgs.push_back("-platform_version");
2541 std::string PlatformName = getPlatformName(TargetPlatform, TargetEnvironment);
2542 if (TargetEnvironment == Darwin::Simulator)
2543 PlatformName += "-simulator";
2544 CmdArgs.push_back(Args.MakeArgString(PlatformName));
2545 VersionTuple TargetVersion = getTargetVersion().withoutBuild();
2546 CmdArgs.push_back(Args.MakeArgString(TargetVersion.getAsString()));
2548 VersionTuple SDKVersion = SDKInfo->getVersion().withoutBuild();
2549 CmdArgs.push_back(Args.MakeArgString(SDKVersion.getAsString()));
2551 // Use a blank SDK version if it's not present.
2552 CmdArgs.push_back("0.0.0");
2556 void Darwin::addStartObjectFileArgs(const ArgList &Args,
2557 ArgStringList &CmdArgs) const {
2558 // Derived from startfile spec.
2559 if (Args.hasArg(options::OPT_dynamiclib)) {
2560 // Derived from darwin_dylib1 spec.
2561 if (isTargetWatchOSBased()) {
2562 ; // watchOS does not need dylib1.o.
2563 } else if (isTargetIOSSimulator()) {
2564 ; // iOS simulator does not need dylib1.o.
2565 } else if (isTargetIPhoneOS()) {
2566 if (isIPhoneOSVersionLT(3, 1))
2567 CmdArgs.push_back("-ldylib1.o");
2569 if (isMacosxVersionLT(10, 5))
2570 CmdArgs.push_back("-ldylib1.o");
2571 else if (isMacosxVersionLT(10, 6))
2572 CmdArgs.push_back("-ldylib1.10.5.o");
2575 if (Args.hasArg(options::OPT_bundle)) {
2576 if (!Args.hasArg(options::OPT_static)) {
2577 // Derived from darwin_bundle1 spec.
2578 if (isTargetWatchOSBased()) {
2579 ; // watchOS does not need bundle1.o.
2580 } else if (isTargetIOSSimulator()) {
2581 ; // iOS simulator does not need bundle1.o.
2582 } else if (isTargetIPhoneOS()) {
2583 if (isIPhoneOSVersionLT(3, 1))
2584 CmdArgs.push_back("-lbundle1.o");
2586 if (isMacosxVersionLT(10, 6))
2587 CmdArgs.push_back("-lbundle1.o");
2591 if (Args.hasArg(options::OPT_pg) && SupportsProfiling()) {
2592 if (isTargetMacOS() && isMacosxVersionLT(10, 9)) {
2593 if (Args.hasArg(options::OPT_static) ||
2594 Args.hasArg(options::OPT_object) ||
2595 Args.hasArg(options::OPT_preload)) {
2596 CmdArgs.push_back("-lgcrt0.o");
2598 CmdArgs.push_back("-lgcrt1.o");
2600 // darwin_crt2 spec is empty.
2602 // By default on OS X 10.8 and later, we don't link with a crt1.o
2603 // file and the linker knows to use _main as the entry point. But,
2604 // when compiling with -pg, we need to link with the gcrt1.o file,
2605 // so pass the -no_new_main option to tell the linker to use the
2606 // "start" symbol as the entry point.
2607 if (isTargetMacOS() && !isMacosxVersionLT(10, 8))
2608 CmdArgs.push_back("-no_new_main");
2610 getDriver().Diag(diag::err_drv_clang_unsupported_opt_pg_darwin)
2614 if (Args.hasArg(options::OPT_static) ||
2615 Args.hasArg(options::OPT_object) ||
2616 Args.hasArg(options::OPT_preload)) {
2617 CmdArgs.push_back("-lcrt0.o");
2619 // Derived from darwin_crt1 spec.
2620 if (isTargetWatchOSBased()) {
2621 ; // watchOS does not need crt1.o.
2622 } else if (isTargetIOSSimulator()) {
2623 ; // iOS simulator does not need crt1.o.
2624 } else if (isTargetIPhoneOS()) {
2625 if (getArch() == llvm::Triple::aarch64)
2626 ; // iOS does not need any crt1 files for arm64
2627 else if (isIPhoneOSVersionLT(3, 1))
2628 CmdArgs.push_back("-lcrt1.o");
2629 else if (isIPhoneOSVersionLT(6, 0))
2630 CmdArgs.push_back("-lcrt1.3.1.o");
2632 if (isMacosxVersionLT(10, 5))
2633 CmdArgs.push_back("-lcrt1.o");
2634 else if (isMacosxVersionLT(10, 6))
2635 CmdArgs.push_back("-lcrt1.10.5.o");
2636 else if (isMacosxVersionLT(10, 8))
2637 CmdArgs.push_back("-lcrt1.10.6.o");
2639 // darwin_crt2 spec is empty.
2646 if (!isTargetIPhoneOS() && Args.hasArg(options::OPT_shared_libgcc) &&
2647 !isTargetWatchOS() && isMacosxVersionLT(10, 5)) {
2648 const char *Str = Args.MakeArgString(GetFilePath("crt3.o"));
2649 CmdArgs.push_back(Str);
2653 void Darwin::CheckObjCARC() const {
2654 if (isTargetIOSBased() || isTargetWatchOSBased() ||
2655 (isTargetMacOS() && !isMacosxVersionLT(10, 6)))
2657 getDriver().Diag(diag::err_arc_unsupported_on_toolchain);
2660 SanitizerMask Darwin::getSupportedSanitizers() const {
2661 const bool IsX86_64 = getTriple().getArch() == llvm::Triple::x86_64;
2662 SanitizerMask Res = ToolChain::getSupportedSanitizers();
2663 Res |= SanitizerKind::Address;
2664 Res |= SanitizerKind::PointerCompare;
2665 Res |= SanitizerKind::PointerSubtract;
2666 Res |= SanitizerKind::Leak;
2667 Res |= SanitizerKind::Fuzzer;
2668 Res |= SanitizerKind::FuzzerNoLink;
2669 Res |= SanitizerKind::Function;
2671 // Prior to 10.9, macOS shipped a version of the C++ standard library without
2672 // C++11 support. The same is true of iOS prior to version 5. These OS'es are
2673 // incompatible with -fsanitize=vptr.
2674 if (!(isTargetMacOS() && isMacosxVersionLT(10, 9))
2675 && !(isTargetIPhoneOS() && isIPhoneOSVersionLT(5, 0)))
2676 Res |= SanitizerKind::Vptr;
2678 if (isTargetMacOS()) {
2680 Res |= SanitizerKind::Thread;
2681 } else if (isTargetIOSSimulator() || isTargetTvOSSimulator()) {
2683 Res |= SanitizerKind::Thread;
2688 void Darwin::printVerboseInfo(raw_ostream &OS) const {
2689 CudaInstallation.print(OS);