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] >= 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");
1149 addExportedSymbol(CmdArgs, "_reset_fn_list");
1151 addExportedSymbol(CmdArgs, "___llvm_profile_filename");
1152 addExportedSymbol(CmdArgs, "___llvm_profile_raw_version");
1154 addExportedSymbol(CmdArgs, "_lprofDirMode");
1157 // Align __llvm_prf_{cnts,data} sections to the maximum expected page
1158 // alignment. This allows profile counters to be mmap()'d to disk. Note that
1159 // it's not enough to just page-align __llvm_prf_cnts: the following section
1160 // must also be page-aligned so that its data is not clobbered by mmap().
1162 // The section alignment is only needed when continuous profile sync is
1163 // enabled, but this is expected to be the default in Xcode. Specifying the
1164 // extra alignment also allows the same binary to be used with/without sync
1167 for (auto IPSK : {llvm::IPSK_cnts, llvm::IPSK_data}) {
1169 Args, CmdArgs, "__DATA",
1170 llvm::getInstrProfSectionName(IPSK, llvm::Triple::MachO,
1171 /*AddSegmentInfo=*/false));
1176 void DarwinClang::AddLinkSanitizerLibArgs(const ArgList &Args,
1177 ArgStringList &CmdArgs,
1178 StringRef Sanitizer,
1179 bool Shared) const {
1180 auto RLO = RuntimeLinkOptions(RLO_AlwaysLink | (Shared ? RLO_AddRPath : 0U));
1181 AddLinkRuntimeLib(Args, CmdArgs, Sanitizer, RLO, Shared);
1184 ToolChain::RuntimeLibType DarwinClang::GetRuntimeLibType(
1185 const ArgList &Args) const {
1186 if (Arg* A = Args.getLastArg(options::OPT_rtlib_EQ)) {
1187 StringRef Value = A->getValue();
1188 if (Value != "compiler-rt")
1189 getDriver().Diag(clang::diag::err_drv_unsupported_rtlib_for_platform)
1190 << Value << "darwin";
1193 return ToolChain::RLT_CompilerRT;
1196 void DarwinClang::AddLinkRuntimeLibArgs(const ArgList &Args,
1197 ArgStringList &CmdArgs,
1198 bool ForceLinkBuiltinRT) const {
1199 // Call once to ensure diagnostic is printed if wrong value was specified
1200 GetRuntimeLibType(Args);
1202 // Darwin doesn't support real static executables, don't link any runtime
1203 // libraries with -static.
1204 if (Args.hasArg(options::OPT_static) ||
1205 Args.hasArg(options::OPT_fapple_kext) ||
1206 Args.hasArg(options::OPT_mkernel)) {
1207 if (ForceLinkBuiltinRT)
1208 AddLinkRuntimeLib(Args, CmdArgs, "builtins");
1212 // Reject -static-libgcc for now, we can deal with this when and if someone
1213 // cares. This is useful in situations where someone wants to statically link
1214 // something like libstdc++, and needs its runtime support routines.
1215 if (const Arg *A = Args.getLastArg(options::OPT_static_libgcc)) {
1216 getDriver().Diag(diag::err_drv_unsupported_opt) << A->getAsString(Args);
1220 const SanitizerArgs &Sanitize = getSanitizerArgs();
1221 if (Sanitize.needsAsanRt())
1222 AddLinkSanitizerLibArgs(Args, CmdArgs, "asan");
1223 if (Sanitize.needsLsanRt())
1224 AddLinkSanitizerLibArgs(Args, CmdArgs, "lsan");
1225 if (Sanitize.needsUbsanRt())
1226 AddLinkSanitizerLibArgs(Args, CmdArgs,
1227 Sanitize.requiresMinimalRuntime() ? "ubsan_minimal"
1229 Sanitize.needsSharedRt());
1230 if (Sanitize.needsTsanRt())
1231 AddLinkSanitizerLibArgs(Args, CmdArgs, "tsan");
1232 if (Sanitize.needsFuzzer() && !Args.hasArg(options::OPT_dynamiclib)) {
1233 AddLinkSanitizerLibArgs(Args, CmdArgs, "fuzzer", /*shared=*/false);
1235 // Libfuzzer is written in C++ and requires libcxx.
1236 AddCXXStdlibLibArgs(Args, CmdArgs);
1238 if (Sanitize.needsStatsRt()) {
1239 AddLinkRuntimeLib(Args, CmdArgs, "stats_client", RLO_AlwaysLink);
1240 AddLinkSanitizerLibArgs(Args, CmdArgs, "stats");
1243 const XRayArgs &XRay = getXRayArgs();
1244 if (XRay.needsXRayRt()) {
1245 AddLinkRuntimeLib(Args, CmdArgs, "xray");
1246 AddLinkRuntimeLib(Args, CmdArgs, "xray-basic");
1247 AddLinkRuntimeLib(Args, CmdArgs, "xray-fdr");
1250 // Otherwise link libSystem, then the dynamic runtime library, and finally any
1251 // target specific static runtime library.
1252 CmdArgs.push_back("-lSystem");
1254 // Select the dynamic runtime library and the target specific static library.
1255 if (isTargetIOSBased()) {
1256 // If we are compiling as iOS / simulator, don't attempt to link libgcc_s.1,
1257 // it never went into the SDK.
1258 // Linking against libgcc_s.1 isn't needed for iOS 5.0+
1259 if (isIPhoneOSVersionLT(5, 0) && !isTargetIOSSimulator() &&
1260 getTriple().getArch() != llvm::Triple::aarch64)
1261 CmdArgs.push_back("-lgcc_s.1");
1263 AddLinkRuntimeLib(Args, CmdArgs, "builtins");
1266 /// Returns the most appropriate macOS target version for the current process.
1268 /// If the macOS SDK version is the same or earlier than the system version,
1269 /// then the SDK version is returned. Otherwise the system version is returned.
1270 static std::string getSystemOrSDKMacOSVersion(StringRef MacOSSDKVersion) {
1271 unsigned Major, Minor, Micro;
1272 llvm::Triple SystemTriple(llvm::sys::getProcessTriple());
1273 if (!SystemTriple.isMacOSX())
1274 return MacOSSDKVersion;
1275 SystemTriple.getMacOSXVersion(Major, Minor, Micro);
1276 VersionTuple SystemVersion(Major, Minor, Micro);
1278 if (!Driver::GetReleaseVersion(MacOSSDKVersion, Major, Minor, Micro,
1280 return MacOSSDKVersion;
1281 VersionTuple SDKVersion(Major, Minor, Micro);
1282 if (SDKVersion > SystemVersion)
1283 return SystemVersion.getAsString();
1284 return MacOSSDKVersion;
1289 /// The Darwin OS that was selected or inferred from arguments / environment.
1290 struct DarwinPlatform {
1292 /// The OS was specified using the -target argument.
1294 /// The OS was specified using the -m<os>-version-min argument.
1296 /// The OS was specified using the OS_DEPLOYMENT_TARGET environment.
1297 DeploymentTargetEnv,
1298 /// The OS was inferred from the SDK.
1300 /// The OS was inferred from the -arch.
1304 using DarwinPlatformKind = Darwin::DarwinPlatformKind;
1305 using DarwinEnvironmentKind = Darwin::DarwinEnvironmentKind;
1307 DarwinPlatformKind getPlatform() const { return Platform; }
1309 DarwinEnvironmentKind getEnvironment() const { return Environment; }
1311 void setEnvironment(DarwinEnvironmentKind Kind) {
1313 InferSimulatorFromArch = false;
1316 StringRef getOSVersion() const {
1317 if (Kind == OSVersionArg)
1318 return Argument->getValue();
1322 void setOSVersion(StringRef S) {
1323 assert(Kind == TargetArg && "Unexpected kind!");
1327 bool hasOSVersion() const { return HasOSVersion; }
1329 /// Returns true if the target OS was explicitly specified.
1330 bool isExplicitlySpecified() const { return Kind <= DeploymentTargetEnv; }
1332 /// Returns true if the simulator environment can be inferred from the arch.
1333 bool canInferSimulatorFromArch() const { return InferSimulatorFromArch; }
1335 /// Adds the -m<os>-version-min argument to the compiler invocation.
1336 void addOSVersionMinArgument(DerivedArgList &Args, const OptTable &Opts) {
1339 assert(Kind != TargetArg && Kind != OSVersionArg && "Invalid kind");
1342 case DarwinPlatformKind::MacOS:
1343 Opt = options::OPT_mmacosx_version_min_EQ;
1345 case DarwinPlatformKind::IPhoneOS:
1346 Opt = options::OPT_miphoneos_version_min_EQ;
1348 case DarwinPlatformKind::TvOS:
1349 Opt = options::OPT_mtvos_version_min_EQ;
1351 case DarwinPlatformKind::WatchOS:
1352 Opt = options::OPT_mwatchos_version_min_EQ;
1355 Argument = Args.MakeJoinedArg(nullptr, Opts.getOption(Opt), OSVersion);
1356 Args.append(Argument);
1359 /// Returns the OS version with the argument / environment variable that
1361 std::string getAsString(DerivedArgList &Args, const OptTable &Opts) {
1365 case InferredFromSDK:
1366 case InferredFromArch:
1367 assert(Argument && "OS version argument not yet inferred");
1368 return Argument->getAsString(Args);
1369 case DeploymentTargetEnv:
1370 return (llvm::Twine(EnvVarName) + "=" + OSVersion).str();
1372 llvm_unreachable("Unsupported Darwin Source Kind");
1375 static DarwinPlatform createFromTarget(const llvm::Triple &TT,
1376 StringRef OSVersion, Arg *A) {
1377 DarwinPlatform Result(TargetArg, getPlatformFromOS(TT.getOS()), OSVersion,
1379 switch (TT.getEnvironment()) {
1380 case llvm::Triple::Simulator:
1381 Result.Environment = DarwinEnvironmentKind::Simulator;
1386 unsigned Major, Minor, Micro;
1387 TT.getOSVersion(Major, Minor, Micro);
1389 Result.HasOSVersion = false;
1392 static DarwinPlatform createOSVersionArg(DarwinPlatformKind Platform,
1394 return DarwinPlatform(OSVersionArg, Platform, A);
1396 static DarwinPlatform createDeploymentTargetEnv(DarwinPlatformKind Platform,
1397 StringRef EnvVarName,
1399 DarwinPlatform Result(DeploymentTargetEnv, Platform, Value);
1400 Result.EnvVarName = EnvVarName;
1403 static DarwinPlatform createFromSDK(DarwinPlatformKind Platform,
1405 bool IsSimulator = false) {
1406 DarwinPlatform Result(InferredFromSDK, Platform, Value);
1408 Result.Environment = DarwinEnvironmentKind::Simulator;
1409 Result.InferSimulatorFromArch = false;
1412 static DarwinPlatform createFromArch(llvm::Triple::OSType OS,
1414 return DarwinPlatform(InferredFromArch, getPlatformFromOS(OS), Value);
1417 /// Constructs an inferred SDKInfo value based on the version inferred from
1418 /// the SDK path itself. Only works for values that were created by inferring
1419 /// the platform from the SDKPath.
1420 DarwinSDKInfo inferSDKInfo() {
1421 assert(Kind == InferredFromSDK && "can infer SDK info only");
1422 llvm::VersionTuple Version;
1423 bool IsValid = !Version.tryParse(OSVersion);
1425 assert(IsValid && "invalid SDK version");
1426 return DarwinSDKInfo(Version);
1430 DarwinPlatform(SourceKind Kind, DarwinPlatformKind Platform, Arg *Argument)
1431 : Kind(Kind), Platform(Platform), Argument(Argument) {}
1432 DarwinPlatform(SourceKind Kind, DarwinPlatformKind Platform, StringRef Value,
1433 Arg *Argument = nullptr)
1434 : Kind(Kind), Platform(Platform), OSVersion(Value), Argument(Argument) {}
1436 static DarwinPlatformKind getPlatformFromOS(llvm::Triple::OSType OS) {
1438 case llvm::Triple::Darwin:
1439 case llvm::Triple::MacOSX:
1440 return DarwinPlatformKind::MacOS;
1441 case llvm::Triple::IOS:
1442 return DarwinPlatformKind::IPhoneOS;
1443 case llvm::Triple::TvOS:
1444 return DarwinPlatformKind::TvOS;
1445 case llvm::Triple::WatchOS:
1446 return DarwinPlatformKind::WatchOS;
1448 llvm_unreachable("Unable to infer Darwin variant");
1453 DarwinPlatformKind Platform;
1454 DarwinEnvironmentKind Environment = DarwinEnvironmentKind::NativeEnvironment;
1455 std::string OSVersion;
1456 bool HasOSVersion = true, InferSimulatorFromArch = true;
1458 StringRef EnvVarName;
1461 /// Returns the deployment target that's specified using the -m<os>-version-min
1463 Optional<DarwinPlatform>
1464 getDeploymentTargetFromOSVersionArg(DerivedArgList &Args,
1465 const Driver &TheDriver) {
1466 Arg *OSXVersion = Args.getLastArg(options::OPT_mmacosx_version_min_EQ);
1467 Arg *iOSVersion = Args.getLastArg(options::OPT_miphoneos_version_min_EQ,
1468 options::OPT_mios_simulator_version_min_EQ);
1470 Args.getLastArg(options::OPT_mtvos_version_min_EQ,
1471 options::OPT_mtvos_simulator_version_min_EQ);
1472 Arg *WatchOSVersion =
1473 Args.getLastArg(options::OPT_mwatchos_version_min_EQ,
1474 options::OPT_mwatchos_simulator_version_min_EQ);
1476 if (iOSVersion || TvOSVersion || WatchOSVersion) {
1477 TheDriver.Diag(diag::err_drv_argument_not_allowed_with)
1478 << OSXVersion->getAsString(Args)
1479 << (iOSVersion ? iOSVersion
1480 : TvOSVersion ? TvOSVersion : WatchOSVersion)
1481 ->getAsString(Args);
1483 return DarwinPlatform::createOSVersionArg(Darwin::MacOS, OSXVersion);
1484 } else if (iOSVersion) {
1485 if (TvOSVersion || WatchOSVersion) {
1486 TheDriver.Diag(diag::err_drv_argument_not_allowed_with)
1487 << iOSVersion->getAsString(Args)
1488 << (TvOSVersion ? TvOSVersion : WatchOSVersion)->getAsString(Args);
1490 return DarwinPlatform::createOSVersionArg(Darwin::IPhoneOS, iOSVersion);
1491 } else if (TvOSVersion) {
1492 if (WatchOSVersion) {
1493 TheDriver.Diag(diag::err_drv_argument_not_allowed_with)
1494 << TvOSVersion->getAsString(Args)
1495 << WatchOSVersion->getAsString(Args);
1497 return DarwinPlatform::createOSVersionArg(Darwin::TvOS, TvOSVersion);
1498 } else if (WatchOSVersion)
1499 return DarwinPlatform::createOSVersionArg(Darwin::WatchOS, WatchOSVersion);
1503 /// Returns the deployment target that's specified using the
1504 /// OS_DEPLOYMENT_TARGET environment variable.
1505 Optional<DarwinPlatform>
1506 getDeploymentTargetFromEnvironmentVariables(const Driver &TheDriver,
1507 const llvm::Triple &Triple) {
1508 std::string Targets[Darwin::LastDarwinPlatform + 1];
1509 const char *EnvVars[] = {
1510 "MACOSX_DEPLOYMENT_TARGET",
1511 "IPHONEOS_DEPLOYMENT_TARGET",
1512 "TVOS_DEPLOYMENT_TARGET",
1513 "WATCHOS_DEPLOYMENT_TARGET",
1515 static_assert(llvm::array_lengthof(EnvVars) == Darwin::LastDarwinPlatform + 1,
1516 "Missing platform");
1517 for (const auto &I : llvm::enumerate(llvm::makeArrayRef(EnvVars))) {
1518 if (char *Env = ::getenv(I.value()))
1519 Targets[I.index()] = Env;
1522 // Allow conflicts among OSX and iOS for historical reasons, but choose the
1523 // default platform.
1524 if (!Targets[Darwin::MacOS].empty() &&
1525 (!Targets[Darwin::IPhoneOS].empty() ||
1526 !Targets[Darwin::WatchOS].empty() || !Targets[Darwin::TvOS].empty())) {
1527 if (Triple.getArch() == llvm::Triple::arm ||
1528 Triple.getArch() == llvm::Triple::aarch64 ||
1529 Triple.getArch() == llvm::Triple::thumb)
1530 Targets[Darwin::MacOS] = "";
1532 Targets[Darwin::IPhoneOS] = Targets[Darwin::WatchOS] =
1533 Targets[Darwin::TvOS] = "";
1535 // Don't allow conflicts in any other platform.
1536 unsigned FirstTarget = llvm::array_lengthof(Targets);
1537 for (unsigned I = 0; I != llvm::array_lengthof(Targets); ++I) {
1538 if (Targets[I].empty())
1540 if (FirstTarget == llvm::array_lengthof(Targets))
1543 TheDriver.Diag(diag::err_drv_conflicting_deployment_targets)
1544 << Targets[FirstTarget] << Targets[I];
1548 for (const auto &Target : llvm::enumerate(llvm::makeArrayRef(Targets))) {
1549 if (!Target.value().empty())
1550 return DarwinPlatform::createDeploymentTargetEnv(
1551 (Darwin::DarwinPlatformKind)Target.index(), EnvVars[Target.index()],
1557 /// Tries to infer the deployment target from the SDK specified by -isysroot
1558 /// (or SDKROOT). Uses the version specified in the SDKSettings.json file if
1560 Optional<DarwinPlatform>
1561 inferDeploymentTargetFromSDK(DerivedArgList &Args,
1562 const Optional<DarwinSDKInfo> &SDKInfo) {
1563 const Arg *A = Args.getLastArg(options::OPT_isysroot);
1566 StringRef isysroot = A->getValue();
1567 StringRef SDK = Darwin::getSDKName(isysroot);
1571 std::string Version;
1573 // Get the version from the SDKSettings.json if it's available.
1574 Version = SDKInfo->getVersion().getAsString();
1576 // Slice the version number out.
1577 // Version number is between the first and the last number.
1578 size_t StartVer = SDK.find_first_of("0123456789");
1579 size_t EndVer = SDK.find_last_of("0123456789");
1580 if (StartVer != StringRef::npos && EndVer > StartVer)
1581 Version = SDK.slice(StartVer, EndVer + 1);
1583 if (Version.empty())
1586 if (SDK.startswith("iPhoneOS") || SDK.startswith("iPhoneSimulator"))
1587 return DarwinPlatform::createFromSDK(
1588 Darwin::IPhoneOS, Version,
1589 /*IsSimulator=*/SDK.startswith("iPhoneSimulator"));
1590 else if (SDK.startswith("MacOSX"))
1591 return DarwinPlatform::createFromSDK(Darwin::MacOS,
1592 getSystemOrSDKMacOSVersion(Version));
1593 else if (SDK.startswith("WatchOS") || SDK.startswith("WatchSimulator"))
1594 return DarwinPlatform::createFromSDK(
1595 Darwin::WatchOS, Version,
1596 /*IsSimulator=*/SDK.startswith("WatchSimulator"));
1597 else if (SDK.startswith("AppleTVOS") || SDK.startswith("AppleTVSimulator"))
1598 return DarwinPlatform::createFromSDK(
1599 Darwin::TvOS, Version,
1600 /*IsSimulator=*/SDK.startswith("AppleTVSimulator"));
1604 std::string getOSVersion(llvm::Triple::OSType OS, const llvm::Triple &Triple,
1605 const Driver &TheDriver) {
1606 unsigned Major, Minor, Micro;
1607 llvm::Triple SystemTriple(llvm::sys::getProcessTriple());
1609 case llvm::Triple::Darwin:
1610 case llvm::Triple::MacOSX:
1611 // If there is no version specified on triple, and both host and target are
1612 // macos, use the host triple to infer OS version.
1613 if (Triple.isMacOSX() && SystemTriple.isMacOSX() &&
1614 !Triple.getOSMajorVersion())
1615 SystemTriple.getMacOSXVersion(Major, Minor, Micro);
1616 else if (!Triple.getMacOSXVersion(Major, Minor, Micro))
1617 TheDriver.Diag(diag::err_drv_invalid_darwin_version)
1618 << Triple.getOSName();
1620 case llvm::Triple::IOS:
1621 Triple.getiOSVersion(Major, Minor, Micro);
1623 case llvm::Triple::TvOS:
1624 Triple.getOSVersion(Major, Minor, Micro);
1626 case llvm::Triple::WatchOS:
1627 Triple.getWatchOSVersion(Major, Minor, Micro);
1630 llvm_unreachable("Unexpected OS type");
1634 std::string OSVersion;
1635 llvm::raw_string_ostream(OSVersion) << Major << '.' << Minor << '.' << Micro;
1639 /// Tries to infer the target OS from the -arch.
1640 Optional<DarwinPlatform>
1641 inferDeploymentTargetFromArch(DerivedArgList &Args, const Darwin &Toolchain,
1642 const llvm::Triple &Triple,
1643 const Driver &TheDriver) {
1644 llvm::Triple::OSType OSTy = llvm::Triple::UnknownOS;
1646 StringRef MachOArchName = Toolchain.getMachOArchName(Args);
1647 if (MachOArchName == "armv7" || MachOArchName == "armv7s" ||
1648 MachOArchName == "arm64")
1649 OSTy = llvm::Triple::IOS;
1650 else if (MachOArchName == "armv7k" || MachOArchName == "arm64_32")
1651 OSTy = llvm::Triple::WatchOS;
1652 else if (MachOArchName != "armv6m" && MachOArchName != "armv7m" &&
1653 MachOArchName != "armv7em")
1654 OSTy = llvm::Triple::MacOSX;
1656 if (OSTy == llvm::Triple::UnknownOS)
1658 return DarwinPlatform::createFromArch(OSTy,
1659 getOSVersion(OSTy, Triple, TheDriver));
1662 /// Returns the deployment target that's specified using the -target option.
1663 Optional<DarwinPlatform> getDeploymentTargetFromTargetArg(
1664 DerivedArgList &Args, const llvm::Triple &Triple, const Driver &TheDriver) {
1665 if (!Args.hasArg(options::OPT_target))
1667 if (Triple.getOS() == llvm::Triple::Darwin ||
1668 Triple.getOS() == llvm::Triple::UnknownOS)
1670 std::string OSVersion = getOSVersion(Triple.getOS(), Triple, TheDriver);
1671 return DarwinPlatform::createFromTarget(Triple, OSVersion,
1672 Args.getLastArg(options::OPT_target));
1675 Optional<DarwinSDKInfo> parseSDKSettings(llvm::vfs::FileSystem &VFS,
1676 const ArgList &Args,
1677 const Driver &TheDriver) {
1678 const Arg *A = Args.getLastArg(options::OPT_isysroot);
1681 StringRef isysroot = A->getValue();
1682 auto SDKInfoOrErr = driver::parseDarwinSDKInfo(VFS, isysroot);
1683 if (!SDKInfoOrErr) {
1684 llvm::consumeError(SDKInfoOrErr.takeError());
1685 TheDriver.Diag(diag::warn_drv_darwin_sdk_invalid_settings);
1688 return *SDKInfoOrErr;
1693 void Darwin::AddDeploymentTarget(DerivedArgList &Args) const {
1694 const OptTable &Opts = getDriver().getOpts();
1696 // Support allowing the SDKROOT environment variable used by xcrun and other
1697 // Xcode tools to define the default sysroot, by making it the default for
1699 if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
1700 // Warn if the path does not exist.
1701 if (!getVFS().exists(A->getValue()))
1702 getDriver().Diag(clang::diag::warn_missing_sysroot) << A->getValue();
1704 if (char *env = ::getenv("SDKROOT")) {
1705 // We only use this value as the default if it is an absolute path,
1706 // exists, and it is not the root path.
1707 if (llvm::sys::path::is_absolute(env) && getVFS().exists(env) &&
1708 StringRef(env) != "/") {
1709 Args.append(Args.MakeSeparateArg(
1710 nullptr, Opts.getOption(options::OPT_isysroot), env));
1715 // Read the SDKSettings.json file for more information, like the SDK version
1716 // that we can pass down to the compiler.
1717 SDKInfo = parseSDKSettings(getVFS(), Args, getDriver());
1719 // The OS and the version can be specified using the -target argument.
1720 Optional<DarwinPlatform> OSTarget =
1721 getDeploymentTargetFromTargetArg(Args, getTriple(), getDriver());
1723 Optional<DarwinPlatform> OSVersionArgTarget =
1724 getDeploymentTargetFromOSVersionArg(Args, getDriver());
1725 if (OSVersionArgTarget) {
1726 unsigned TargetMajor, TargetMinor, TargetMicro;
1728 unsigned ArgMajor, ArgMinor, ArgMicro;
1730 if (OSTarget->getPlatform() != OSVersionArgTarget->getPlatform() ||
1731 (Driver::GetReleaseVersion(OSTarget->getOSVersion(), TargetMajor,
1732 TargetMinor, TargetMicro, TargetExtra) &&
1733 Driver::GetReleaseVersion(OSVersionArgTarget->getOSVersion(),
1734 ArgMajor, ArgMinor, ArgMicro, ArgExtra) &&
1735 (VersionTuple(TargetMajor, TargetMinor, TargetMicro) !=
1736 VersionTuple(ArgMajor, ArgMinor, ArgMicro) ||
1737 TargetExtra != ArgExtra))) {
1738 // Select the OS version from the -m<os>-version-min argument when
1739 // the -target does not include an OS version.
1740 if (OSTarget->getPlatform() == OSVersionArgTarget->getPlatform() &&
1741 !OSTarget->hasOSVersion()) {
1742 OSTarget->setOSVersion(OSVersionArgTarget->getOSVersion());
1744 // Warn about -m<os>-version-min that doesn't match the OS version
1745 // that's specified in the target.
1746 std::string OSVersionArg =
1747 OSVersionArgTarget->getAsString(Args, Opts);
1748 std::string TargetArg = OSTarget->getAsString(Args, Opts);
1749 getDriver().Diag(clang::diag::warn_drv_overriding_flag_option)
1750 << OSVersionArg << TargetArg;
1755 // The OS target can be specified using the -m<os>version-min argument.
1756 OSTarget = getDeploymentTargetFromOSVersionArg(Args, getDriver());
1757 // If no deployment target was specified on the command line, check for
1758 // environment defines.
1761 getDeploymentTargetFromEnvironmentVariables(getDriver(), getTriple());
1763 // Don't infer simulator from the arch when the SDK is also specified.
1764 Optional<DarwinPlatform> SDKTarget =
1765 inferDeploymentTargetFromSDK(Args, SDKInfo);
1767 OSTarget->setEnvironment(SDKTarget->getEnvironment());
1770 // If there is no command-line argument to specify the Target version and
1771 // no environment variable defined, see if we can set the default based
1772 // on -isysroot using SDKSettings.json if it exists.
1774 OSTarget = inferDeploymentTargetFromSDK(Args, SDKInfo);
1775 /// If the target was successfully constructed from the SDK path, try to
1776 /// infer the SDK info if the SDK doesn't have it.
1777 if (OSTarget && !SDKInfo)
1778 SDKInfo = OSTarget->inferSDKInfo();
1780 // If no OS targets have been specified, try to guess platform from -target
1781 // or arch name and compute the version from the triple.
1784 inferDeploymentTargetFromArch(Args, *this, getTriple(), getDriver());
1787 assert(OSTarget && "Unable to infer Darwin variant");
1788 OSTarget->addOSVersionMinArgument(Args, Opts);
1789 DarwinPlatformKind Platform = OSTarget->getPlatform();
1791 unsigned Major, Minor, Micro;
1793 // Set the tool chain target information.
1794 if (Platform == MacOS) {
1795 if (!Driver::GetReleaseVersion(OSTarget->getOSVersion(), Major, Minor,
1797 HadExtra || Major != 10 || Minor >= 100 || Micro >= 100)
1798 getDriver().Diag(diag::err_drv_invalid_version_number)
1799 << OSTarget->getAsString(Args, Opts);
1800 } else if (Platform == IPhoneOS) {
1801 if (!Driver::GetReleaseVersion(OSTarget->getOSVersion(), Major, Minor,
1803 HadExtra || Major >= 100 || Minor >= 100 || Micro >= 100)
1804 getDriver().Diag(diag::err_drv_invalid_version_number)
1805 << OSTarget->getAsString(Args, Opts);
1807 // For 32-bit targets, the deployment target for iOS has to be earlier than
1809 if (getTriple().isArch32Bit() && Major >= 11) {
1810 // If the deployment target is explicitly specified, print a diagnostic.
1811 if (OSTarget->isExplicitlySpecified()) {
1812 getDriver().Diag(diag::warn_invalid_ios_deployment_target)
1813 << OSTarget->getAsString(Args, Opts);
1814 // Otherwise, set it to 10.99.99.
1821 } else if (Platform == TvOS) {
1822 if (!Driver::GetReleaseVersion(OSTarget->getOSVersion(), Major, Minor,
1824 HadExtra || Major >= 100 || Minor >= 100 || Micro >= 100)
1825 getDriver().Diag(diag::err_drv_invalid_version_number)
1826 << OSTarget->getAsString(Args, Opts);
1827 } else if (Platform == WatchOS) {
1828 if (!Driver::GetReleaseVersion(OSTarget->getOSVersion(), Major, Minor,
1830 HadExtra || Major >= 10 || Minor >= 100 || Micro >= 100)
1831 getDriver().Diag(diag::err_drv_invalid_version_number)
1832 << OSTarget->getAsString(Args, Opts);
1834 llvm_unreachable("unknown kind of Darwin platform");
1836 DarwinEnvironmentKind Environment = OSTarget->getEnvironment();
1837 // Recognize iOS targets with an x86 architecture as the iOS simulator.
1838 if (Environment == NativeEnvironment && Platform != MacOS &&
1839 OSTarget->canInferSimulatorFromArch() && getTriple().isX86())
1840 Environment = Simulator;
1842 setTarget(Platform, Environment, Major, Minor, Micro);
1844 if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
1845 StringRef SDK = getSDKName(A->getValue());
1846 if (SDK.size() > 0) {
1847 size_t StartVer = SDK.find_first_of("0123456789");
1848 StringRef SDKName = SDK.slice(0, StartVer);
1849 if (!SDKName.startswith(getPlatformFamily()))
1850 getDriver().Diag(diag::warn_incompatible_sysroot)
1851 << SDKName << getPlatformFamily();
1856 // Returns the effective header sysroot path to use. This comes either from
1857 // -isysroot or --sysroot.
1858 llvm::StringRef DarwinClang::GetHeaderSysroot(const llvm::opt::ArgList &DriverArgs) const {
1859 if(DriverArgs.hasArg(options::OPT_isysroot))
1860 return DriverArgs.getLastArgValue(options::OPT_isysroot);
1861 if (!getDriver().SysRoot.empty())
1862 return getDriver().SysRoot;
1866 void DarwinClang::AddClangSystemIncludeArgs(const llvm::opt::ArgList &DriverArgs,
1867 llvm::opt::ArgStringList &CC1Args) const {
1868 const Driver &D = getDriver();
1870 llvm::StringRef Sysroot = GetHeaderSysroot(DriverArgs);
1872 bool NoStdInc = DriverArgs.hasArg(options::OPT_nostdinc);
1873 bool NoStdlibInc = DriverArgs.hasArg(options::OPT_nostdlibinc);
1874 bool NoBuiltinInc = DriverArgs.hasArg(options::OPT_nobuiltininc);
1876 // Add <sysroot>/usr/local/include
1877 if (!NoStdInc && !NoStdlibInc) {
1878 SmallString<128> P(Sysroot);
1879 llvm::sys::path::append(P, "usr", "local", "include");
1880 addSystemInclude(DriverArgs, CC1Args, P);
1883 // Add the Clang builtin headers (<resource>/include)
1884 if (!NoStdInc && !NoBuiltinInc) {
1885 SmallString<128> P(D.ResourceDir);
1886 llvm::sys::path::append(P, "include");
1887 addSystemInclude(DriverArgs, CC1Args, P);
1890 if (NoStdInc || NoStdlibInc)
1893 // Check for configure-time C include directories.
1894 llvm::StringRef CIncludeDirs(C_INCLUDE_DIRS);
1895 if (!CIncludeDirs.empty()) {
1896 llvm::SmallVector<llvm::StringRef, 5> dirs;
1897 CIncludeDirs.split(dirs, ":");
1898 for (llvm::StringRef dir : dirs) {
1899 llvm::StringRef Prefix =
1900 llvm::sys::path::is_absolute(dir) ? llvm::StringRef(Sysroot) : "";
1901 addExternCSystemInclude(DriverArgs, CC1Args, Prefix + dir);
1904 // Otherwise, add <sysroot>/usr/include.
1905 SmallString<128> P(Sysroot);
1906 llvm::sys::path::append(P, "usr", "include");
1907 addExternCSystemInclude(DriverArgs, CC1Args, P.str());
1911 bool DarwinClang::AddGnuCPlusPlusIncludePaths(const llvm::opt::ArgList &DriverArgs,
1912 llvm::opt::ArgStringList &CC1Args,
1913 llvm::SmallString<128> Base,
1914 llvm::StringRef Version,
1915 llvm::StringRef ArchDir,
1916 llvm::StringRef BitDir) const {
1917 llvm::sys::path::append(Base, Version);
1920 addSystemInclude(DriverArgs, CC1Args, Base);
1922 // Add the multilib dirs
1924 llvm::SmallString<128> P = Base;
1925 if (!ArchDir.empty())
1926 llvm::sys::path::append(P, ArchDir);
1927 if (!BitDir.empty())
1928 llvm::sys::path::append(P, BitDir);
1929 addSystemInclude(DriverArgs, CC1Args, P);
1932 // Add the backward dir
1934 llvm::SmallString<128> P = Base;
1935 llvm::sys::path::append(P, "backward");
1936 addSystemInclude(DriverArgs, CC1Args, P);
1939 return getVFS().exists(Base);
1942 void DarwinClang::AddClangCXXStdlibIncludeArgs(
1943 const llvm::opt::ArgList &DriverArgs,
1944 llvm::opt::ArgStringList &CC1Args) const {
1945 // The implementation from a base class will pass through the -stdlib to
1947 // FIXME: this should not be necessary, remove usages in the frontend
1948 // (e.g. HeaderSearchOptions::UseLibcxx) and don't pipe -stdlib.
1949 // Also check whether this is used for setting library search paths.
1950 ToolChain::AddClangCXXStdlibIncludeArgs(DriverArgs, CC1Args);
1952 if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
1953 DriverArgs.hasArg(options::OPT_nostdincxx))
1956 llvm::StringRef Sysroot = GetHeaderSysroot(DriverArgs);
1958 switch (GetCXXStdlibType(DriverArgs)) {
1959 case ToolChain::CST_Libcxx: {
1960 // On Darwin, libc++ is installed alongside the compiler in
1961 // include/c++/v1, so get from '<install>/bin' to '<install>/include/c++/v1'.
1963 llvm::SmallString<128> P = llvm::StringRef(getDriver().getInstalledDir());
1964 // Note that P can be relative, so we have to '..' and not parent_path.
1965 llvm::sys::path::append(P, "..", "include", "c++", "v1");
1966 addSystemInclude(DriverArgs, CC1Args, P);
1968 // Also add <sysroot>/usr/include/c++/v1 unless -nostdinc is used,
1969 // to match the legacy behavior in CC1.
1970 if (!DriverArgs.hasArg(options::OPT_nostdinc)) {
1971 llvm::SmallString<128> P = Sysroot;
1972 llvm::sys::path::append(P, "usr", "include", "c++", "v1");
1973 addSystemInclude(DriverArgs, CC1Args, P);
1978 case ToolChain::CST_Libstdcxx:
1979 llvm::SmallString<128> UsrIncludeCxx = Sysroot;
1980 llvm::sys::path::append(UsrIncludeCxx, "usr", "include", "c++");
1982 llvm::Triple::ArchType arch = getTriple().getArch();
1983 bool IsBaseFound = true;
1987 case llvm::Triple::ppc:
1988 case llvm::Triple::ppc64:
1989 IsBaseFound = AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, UsrIncludeCxx,
1991 "powerpc-apple-darwin10",
1992 arch == llvm::Triple::ppc64 ? "ppc64" : "");
1993 IsBaseFound |= AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, UsrIncludeCxx,
1994 "4.0.0", "powerpc-apple-darwin10",
1995 arch == llvm::Triple::ppc64 ? "ppc64" : "");
1998 case llvm::Triple::x86:
1999 case llvm::Triple::x86_64:
2000 IsBaseFound = AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, UsrIncludeCxx,
2002 "i686-apple-darwin10",
2003 arch == llvm::Triple::x86_64 ? "x86_64" : "");
2004 IsBaseFound |= AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, UsrIncludeCxx,
2005 "4.0.0", "i686-apple-darwin8",
2009 case llvm::Triple::arm:
2010 case llvm::Triple::thumb:
2011 IsBaseFound = AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, UsrIncludeCxx,
2013 "arm-apple-darwin10",
2015 IsBaseFound |= AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, UsrIncludeCxx,
2017 "arm-apple-darwin10",
2021 case llvm::Triple::aarch64:
2022 IsBaseFound = AddGnuCPlusPlusIncludePaths(DriverArgs, CC1Args, UsrIncludeCxx,
2024 "arm64-apple-darwin10",
2030 getDriver().Diag(diag::warn_drv_libstdcxx_not_found);
2036 void DarwinClang::AddCXXStdlibLibArgs(const ArgList &Args,
2037 ArgStringList &CmdArgs) const {
2038 CXXStdlibType Type = GetCXXStdlibType(Args);
2041 case ToolChain::CST_Libcxx:
2042 CmdArgs.push_back("-lc++");
2045 case ToolChain::CST_Libstdcxx:
2046 // Unfortunately, -lstdc++ doesn't always exist in the standard search path;
2047 // it was previously found in the gcc lib dir. However, for all the Darwin
2048 // platforms we care about it was -lstdc++.6, so we search for that
2049 // explicitly if we can't see an obvious -lstdc++ candidate.
2051 // Check in the sysroot first.
2052 if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
2053 SmallString<128> P(A->getValue());
2054 llvm::sys::path::append(P, "usr", "lib", "libstdc++.dylib");
2056 if (!getVFS().exists(P)) {
2057 llvm::sys::path::remove_filename(P);
2058 llvm::sys::path::append(P, "libstdc++.6.dylib");
2059 if (getVFS().exists(P)) {
2060 CmdArgs.push_back(Args.MakeArgString(P));
2066 // Otherwise, look in the root.
2067 // FIXME: This should be removed someday when we don't have to care about
2068 // 10.6 and earlier, where /usr/lib/libstdc++.dylib does not exist.
2069 if (!getVFS().exists("/usr/lib/libstdc++.dylib") &&
2070 getVFS().exists("/usr/lib/libstdc++.6.dylib")) {
2071 CmdArgs.push_back("/usr/lib/libstdc++.6.dylib");
2075 // Otherwise, let the linker search.
2076 CmdArgs.push_back("-lstdc++");
2081 void DarwinClang::AddCCKextLibArgs(const ArgList &Args,
2082 ArgStringList &CmdArgs) const {
2083 // For Darwin platforms, use the compiler-rt-based support library
2084 // instead of the gcc-provided one (which is also incidentally
2085 // only present in the gcc lib dir, which makes it hard to find).
2087 SmallString<128> P(getDriver().ResourceDir);
2088 llvm::sys::path::append(P, "lib", "darwin");
2090 // Use the newer cc_kext for iOS ARM after 6.0.
2091 if (isTargetWatchOS()) {
2092 llvm::sys::path::append(P, "libclang_rt.cc_kext_watchos.a");
2093 } else if (isTargetTvOS()) {
2094 llvm::sys::path::append(P, "libclang_rt.cc_kext_tvos.a");
2095 } else if (isTargetIPhoneOS()) {
2096 llvm::sys::path::append(P, "libclang_rt.cc_kext_ios.a");
2098 llvm::sys::path::append(P, "libclang_rt.cc_kext.a");
2101 // For now, allow missing resource libraries to support developers who may
2102 // not have compiler-rt checked out or integrated into their build.
2103 if (getVFS().exists(P))
2104 CmdArgs.push_back(Args.MakeArgString(P));
2107 DerivedArgList *MachO::TranslateArgs(const DerivedArgList &Args,
2108 StringRef BoundArch,
2109 Action::OffloadKind) const {
2110 DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
2111 const OptTable &Opts = getDriver().getOpts();
2113 // FIXME: We really want to get out of the tool chain level argument
2114 // translation business, as it makes the driver functionality much
2115 // more opaque. For now, we follow gcc closely solely for the
2116 // purpose of easily achieving feature parity & testability. Once we
2117 // have something that works, we should reevaluate each translation
2118 // and try to push it down into tool specific logic.
2120 for (Arg *A : Args) {
2121 if (A->getOption().matches(options::OPT_Xarch__)) {
2122 // Skip this argument unless the architecture matches either the toolchain
2123 // triple arch, or the arch being bound.
2124 llvm::Triple::ArchType XarchArch =
2125 tools::darwin::getArchTypeForMachOArchName(A->getValue(0));
2126 if (!(XarchArch == getArch() ||
2127 (!BoundArch.empty() &&
2129 tools::darwin::getArchTypeForMachOArchName(BoundArch))))
2132 Arg *OriginalArg = A;
2133 unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
2134 unsigned Prev = Index;
2135 std::unique_ptr<Arg> XarchArg(Opts.ParseOneArg(Args, Index));
2137 // If the argument parsing failed or more than one argument was
2138 // consumed, the -Xarch_ argument's parameter tried to consume
2139 // extra arguments. Emit an error and ignore.
2141 // We also want to disallow any options which would alter the
2142 // driver behavior; that isn't going to work in our model. We
2143 // use isDriverOption() as an approximation, although things
2144 // like -O4 are going to slip through.
2145 if (!XarchArg || Index > Prev + 1) {
2146 getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args)
2147 << A->getAsString(Args);
2149 } else if (XarchArg->getOption().hasFlag(options::DriverOption)) {
2150 getDriver().Diag(diag::err_drv_invalid_Xarch_argument_isdriver)
2151 << A->getAsString(Args);
2155 XarchArg->setBaseArg(A);
2157 A = XarchArg.release();
2158 DAL->AddSynthesizedArg(A);
2160 // Linker input arguments require custom handling. The problem is that we
2161 // have already constructed the phase actions, so we can not treat them as
2162 // "input arguments".
2163 if (A->getOption().hasFlag(options::LinkerInput)) {
2164 // Convert the argument into individual Zlinker_input_args.
2165 for (const char *Value : A->getValues()) {
2166 DAL->AddSeparateArg(
2167 OriginalArg, Opts.getOption(options::OPT_Zlinker_input), Value);
2173 // Sob. These is strictly gcc compatible for the time being. Apple
2174 // gcc translates options twice, which means that self-expanding
2175 // options add duplicates.
2176 switch ((options::ID)A->getOption().getID()) {
2181 case options::OPT_mkernel:
2182 case options::OPT_fapple_kext:
2184 DAL->AddFlagArg(A, Opts.getOption(options::OPT_static));
2187 case options::OPT_dependency_file:
2188 DAL->AddSeparateArg(A, Opts.getOption(options::OPT_MF), A->getValue());
2191 case options::OPT_gfull:
2192 DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
2194 A, Opts.getOption(options::OPT_fno_eliminate_unused_debug_symbols));
2197 case options::OPT_gused:
2198 DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag));
2200 A, Opts.getOption(options::OPT_feliminate_unused_debug_symbols));
2203 case options::OPT_shared:
2204 DAL->AddFlagArg(A, Opts.getOption(options::OPT_dynamiclib));
2207 case options::OPT_fconstant_cfstrings:
2208 DAL->AddFlagArg(A, Opts.getOption(options::OPT_mconstant_cfstrings));
2211 case options::OPT_fno_constant_cfstrings:
2212 DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_constant_cfstrings));
2215 case options::OPT_Wnonportable_cfstrings:
2217 Opts.getOption(options::OPT_mwarn_nonportable_cfstrings));
2220 case options::OPT_Wno_nonportable_cfstrings:
2222 A, Opts.getOption(options::OPT_mno_warn_nonportable_cfstrings));
2225 case options::OPT_fpascal_strings:
2226 DAL->AddFlagArg(A, Opts.getOption(options::OPT_mpascal_strings));
2229 case options::OPT_fno_pascal_strings:
2230 DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_pascal_strings));
2235 if (getTriple().isX86())
2236 if (!Args.hasArgNoClaim(options::OPT_mtune_EQ))
2237 DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_mtune_EQ),
2240 // Add the arch options based on the particular spelling of -arch, to match
2241 // how the driver driver works.
2242 if (!BoundArch.empty()) {
2243 StringRef Name = BoundArch;
2244 const Option MCpu = Opts.getOption(options::OPT_mcpu_EQ);
2245 const Option MArch = Opts.getOption(clang::driver::options::OPT_march_EQ);
2247 // This code must be kept in sync with LLVM's getArchTypeForDarwinArch,
2248 // which defines the list of which architectures we accept.
2251 else if (Name == "ppc601")
2252 DAL->AddJoinedArg(nullptr, MCpu, "601");
2253 else if (Name == "ppc603")
2254 DAL->AddJoinedArg(nullptr, MCpu, "603");
2255 else if (Name == "ppc604")
2256 DAL->AddJoinedArg(nullptr, MCpu, "604");
2257 else if (Name == "ppc604e")
2258 DAL->AddJoinedArg(nullptr, MCpu, "604e");
2259 else if (Name == "ppc750")
2260 DAL->AddJoinedArg(nullptr, MCpu, "750");
2261 else if (Name == "ppc7400")
2262 DAL->AddJoinedArg(nullptr, MCpu, "7400");
2263 else if (Name == "ppc7450")
2264 DAL->AddJoinedArg(nullptr, MCpu, "7450");
2265 else if (Name == "ppc970")
2266 DAL->AddJoinedArg(nullptr, MCpu, "970");
2268 else if (Name == "ppc64" || Name == "ppc64le")
2269 DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64));
2271 else if (Name == "i386")
2273 else if (Name == "i486")
2274 DAL->AddJoinedArg(nullptr, MArch, "i486");
2275 else if (Name == "i586")
2276 DAL->AddJoinedArg(nullptr, MArch, "i586");
2277 else if (Name == "i686")
2278 DAL->AddJoinedArg(nullptr, MArch, "i686");
2279 else if (Name == "pentium")
2280 DAL->AddJoinedArg(nullptr, MArch, "pentium");
2281 else if (Name == "pentium2")
2282 DAL->AddJoinedArg(nullptr, MArch, "pentium2");
2283 else if (Name == "pentpro")
2284 DAL->AddJoinedArg(nullptr, MArch, "pentiumpro");
2285 else if (Name == "pentIIm3")
2286 DAL->AddJoinedArg(nullptr, MArch, "pentium2");
2288 else if (Name == "x86_64" || Name == "x86_64h")
2289 DAL->AddFlagArg(nullptr, Opts.getOption(options::OPT_m64));
2291 else if (Name == "arm")
2292 DAL->AddJoinedArg(nullptr, MArch, "armv4t");
2293 else if (Name == "armv4t")
2294 DAL->AddJoinedArg(nullptr, MArch, "armv4t");
2295 else if (Name == "armv5")
2296 DAL->AddJoinedArg(nullptr, MArch, "armv5tej");
2297 else if (Name == "xscale")
2298 DAL->AddJoinedArg(nullptr, MArch, "xscale");
2299 else if (Name == "armv6")
2300 DAL->AddJoinedArg(nullptr, MArch, "armv6k");
2301 else if (Name == "armv6m")
2302 DAL->AddJoinedArg(nullptr, MArch, "armv6m");
2303 else if (Name == "armv7")
2304 DAL->AddJoinedArg(nullptr, MArch, "armv7a");
2305 else if (Name == "armv7em")
2306 DAL->AddJoinedArg(nullptr, MArch, "armv7em");
2307 else if (Name == "armv7k")
2308 DAL->AddJoinedArg(nullptr, MArch, "armv7k");
2309 else if (Name == "armv7m")
2310 DAL->AddJoinedArg(nullptr, MArch, "armv7m");
2311 else if (Name == "armv7s")
2312 DAL->AddJoinedArg(nullptr, MArch, "armv7s");
2318 void MachO::AddLinkRuntimeLibArgs(const ArgList &Args,
2319 ArgStringList &CmdArgs,
2320 bool ForceLinkBuiltinRT) const {
2321 // Embedded targets are simple at the moment, not supporting sanitizers and
2322 // with different libraries for each member of the product { static, PIC } x
2323 // { hard-float, soft-float }
2324 llvm::SmallString<32> CompilerRT = StringRef("");
2326 (tools::arm::getARMFloatABI(*this, Args) == tools::arm::FloatABI::Hard)
2329 CompilerRT += Args.hasArg(options::OPT_fPIC) ? "_pic" : "_static";
2331 AddLinkRuntimeLib(Args, CmdArgs, CompilerRT, RLO_IsEmbedded);
2334 bool Darwin::isAlignedAllocationUnavailable() const {
2335 llvm::Triple::OSType OS;
2337 switch (TargetPlatform) {
2338 case MacOS: // Earlier than 10.13.
2339 OS = llvm::Triple::MacOSX;
2342 OS = llvm::Triple::IOS;
2344 case TvOS: // Earlier than 11.0.
2345 OS = llvm::Triple::TvOS;
2347 case WatchOS: // Earlier than 4.0.
2348 OS = llvm::Triple::WatchOS;
2352 return TargetVersion < alignedAllocMinVersion(OS);
2355 void Darwin::addClangTargetOptions(const llvm::opt::ArgList &DriverArgs,
2356 llvm::opt::ArgStringList &CC1Args,
2357 Action::OffloadKind DeviceOffloadKind) const {
2358 // Pass "-faligned-alloc-unavailable" only when the user hasn't manually
2359 // enabled or disabled aligned allocations.
2360 if (!DriverArgs.hasArgNoClaim(options::OPT_faligned_allocation,
2361 options::OPT_fno_aligned_allocation) &&
2362 isAlignedAllocationUnavailable())
2363 CC1Args.push_back("-faligned-alloc-unavailable");
2366 /// Pass the SDK version to the compiler when the SDK information is
2369 llvm::raw_string_ostream OS(Arg);
2370 OS << "-target-sdk-version=" << SDKInfo->getVersion();
2371 CC1Args.push_back(DriverArgs.MakeArgString(OS.str()));
2376 Darwin::TranslateArgs(const DerivedArgList &Args, StringRef BoundArch,
2377 Action::OffloadKind DeviceOffloadKind) const {
2378 // First get the generic Apple args, before moving onto Darwin-specific ones.
2379 DerivedArgList *DAL =
2380 MachO::TranslateArgs(Args, BoundArch, DeviceOffloadKind);
2381 const OptTable &Opts = getDriver().getOpts();
2383 // If no architecture is bound, none of the translations here are relevant.
2384 if (BoundArch.empty())
2387 // Add an explicit version min argument for the deployment target. We do this
2388 // after argument translation because -Xarch_ arguments may add a version min
2390 AddDeploymentTarget(*DAL);
2392 // For iOS 6, undo the translation to add -static for -mkernel/-fapple-kext.
2393 // FIXME: It would be far better to avoid inserting those -static arguments,
2394 // but we can't check the deployment target in the translation code until
2396 if (isTargetWatchOSBased() ||
2397 (isTargetIOSBased() && !isIPhoneOSVersionLT(6, 0))) {
2398 for (ArgList::iterator it = DAL->begin(), ie = DAL->end(); it != ie; ) {
2401 if (A->getOption().getID() != options::OPT_mkernel &&
2402 A->getOption().getID() != options::OPT_fapple_kext)
2404 assert(it != ie && "unexpected argument translation");
2406 assert(A->getOption().getID() == options::OPT_static &&
2407 "missing expected -static argument");
2413 if (!Args.getLastArg(options::OPT_stdlib_EQ) &&
2414 GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
2415 DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_stdlib_EQ),
2418 // Validate the C++ standard library choice.
2419 CXXStdlibType Type = GetCXXStdlibType(*DAL);
2420 if (Type == ToolChain::CST_Libcxx) {
2421 // Check whether the target provides libc++.
2424 // Complain about targeting iOS < 5.0 in any way.
2425 if (isTargetIOSBased() && isIPhoneOSVersionLT(5, 0))
2428 if (where != StringRef()) {
2429 getDriver().Diag(clang::diag::err_drv_invalid_libcxx_deployment) << where;
2433 auto Arch = tools::darwin::getArchTypeForMachOArchName(BoundArch);
2434 if ((Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb)) {
2435 if (Args.hasFlag(options::OPT_fomit_frame_pointer,
2436 options::OPT_fno_omit_frame_pointer, false))
2437 getDriver().Diag(clang::diag::warn_drv_unsupported_opt_for_target)
2438 << "-fomit-frame-pointer" << BoundArch;
2444 bool MachO::IsUnwindTablesDefault(const ArgList &Args) const {
2445 // Unwind tables are not emitted if -fno-exceptions is supplied (except when
2446 // targeting x86_64).
2447 return getArch() == llvm::Triple::x86_64 ||
2448 (GetExceptionModel(Args) != llvm::ExceptionHandling::SjLj &&
2449 Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
2453 bool MachO::UseDwarfDebugFlags() const {
2454 if (const char *S = ::getenv("RC_DEBUG_OPTIONS"))
2455 return S[0] != '\0';
2459 llvm::ExceptionHandling Darwin::GetExceptionModel(const ArgList &Args) const {
2460 // Darwin uses SjLj exceptions on ARM.
2461 if (getTriple().getArch() != llvm::Triple::arm &&
2462 getTriple().getArch() != llvm::Triple::thumb)
2463 return llvm::ExceptionHandling::None;
2465 // Only watchOS uses the new DWARF/Compact unwinding method.
2466 llvm::Triple Triple(ComputeLLVMTriple(Args));
2467 if (Triple.isWatchABI())
2468 return llvm::ExceptionHandling::DwarfCFI;
2470 return llvm::ExceptionHandling::SjLj;
2473 bool Darwin::SupportsEmbeddedBitcode() const {
2474 assert(TargetInitialized && "Target not initialized!");
2475 if (isTargetIPhoneOS() && isIPhoneOSVersionLT(6, 0))
2480 bool MachO::isPICDefault() const { return true; }
2482 bool MachO::isPIEDefault() const { return false; }
2484 bool MachO::isPICDefaultForced() const {
2485 return (getArch() == llvm::Triple::x86_64 ||
2486 getArch() == llvm::Triple::aarch64);
2489 bool MachO::SupportsProfiling() const {
2490 // Profiling instrumentation is only supported on x86.
2491 return getTriple().isX86();
2494 void Darwin::addMinVersionArgs(const ArgList &Args,
2495 ArgStringList &CmdArgs) const {
2496 VersionTuple TargetVersion = getTargetVersion();
2498 if (isTargetWatchOS())
2499 CmdArgs.push_back("-watchos_version_min");
2500 else if (isTargetWatchOSSimulator())
2501 CmdArgs.push_back("-watchos_simulator_version_min");
2502 else if (isTargetTvOS())
2503 CmdArgs.push_back("-tvos_version_min");
2504 else if (isTargetTvOSSimulator())
2505 CmdArgs.push_back("-tvos_simulator_version_min");
2506 else if (isTargetIOSSimulator())
2507 CmdArgs.push_back("-ios_simulator_version_min");
2508 else if (isTargetIOSBased())
2509 CmdArgs.push_back("-iphoneos_version_min");
2511 assert(isTargetMacOS() && "unexpected target");
2512 CmdArgs.push_back("-macosx_version_min");
2515 CmdArgs.push_back(Args.MakeArgString(TargetVersion.getAsString()));
2518 static const char *getPlatformName(Darwin::DarwinPlatformKind Platform,
2519 Darwin::DarwinEnvironmentKind Environment) {
2523 case Darwin::IPhoneOS:
2524 if (Environment == Darwin::NativeEnvironment ||
2525 Environment == Darwin::Simulator)
2527 // FIXME: Add macCatalyst support here ("\"mac catalyst\"").
2528 llvm_unreachable("macCatalyst isn't yet supported");
2531 case Darwin::WatchOS:
2534 llvm_unreachable("invalid platform");
2537 void Darwin::addPlatformVersionArgs(const llvm::opt::ArgList &Args,
2538 llvm::opt::ArgStringList &CmdArgs) const {
2539 // -platform_version <platform> <target_version> <sdk_version>
2540 // Both the target and SDK version support only up to 3 components.
2541 CmdArgs.push_back("-platform_version");
2542 std::string PlatformName = getPlatformName(TargetPlatform, TargetEnvironment);
2543 if (TargetEnvironment == Darwin::Simulator)
2544 PlatformName += "-simulator";
2545 CmdArgs.push_back(Args.MakeArgString(PlatformName));
2546 VersionTuple TargetVersion = getTargetVersion().withoutBuild();
2547 CmdArgs.push_back(Args.MakeArgString(TargetVersion.getAsString()));
2549 VersionTuple SDKVersion = SDKInfo->getVersion().withoutBuild();
2550 CmdArgs.push_back(Args.MakeArgString(SDKVersion.getAsString()));
2552 // Use a blank SDK version if it's not present.
2553 CmdArgs.push_back("0.0.0");
2557 void Darwin::addStartObjectFileArgs(const ArgList &Args,
2558 ArgStringList &CmdArgs) const {
2559 // Derived from startfile spec.
2560 if (Args.hasArg(options::OPT_dynamiclib)) {
2561 // Derived from darwin_dylib1 spec.
2562 if (isTargetWatchOSBased()) {
2563 ; // watchOS does not need dylib1.o.
2564 } else if (isTargetIOSSimulator()) {
2565 ; // iOS simulator does not need dylib1.o.
2566 } else if (isTargetIPhoneOS()) {
2567 if (isIPhoneOSVersionLT(3, 1))
2568 CmdArgs.push_back("-ldylib1.o");
2570 if (isMacosxVersionLT(10, 5))
2571 CmdArgs.push_back("-ldylib1.o");
2572 else if (isMacosxVersionLT(10, 6))
2573 CmdArgs.push_back("-ldylib1.10.5.o");
2576 if (Args.hasArg(options::OPT_bundle)) {
2577 if (!Args.hasArg(options::OPT_static)) {
2578 // Derived from darwin_bundle1 spec.
2579 if (isTargetWatchOSBased()) {
2580 ; // watchOS does not need bundle1.o.
2581 } else if (isTargetIOSSimulator()) {
2582 ; // iOS simulator does not need bundle1.o.
2583 } else if (isTargetIPhoneOS()) {
2584 if (isIPhoneOSVersionLT(3, 1))
2585 CmdArgs.push_back("-lbundle1.o");
2587 if (isMacosxVersionLT(10, 6))
2588 CmdArgs.push_back("-lbundle1.o");
2592 if (Args.hasArg(options::OPT_pg) && SupportsProfiling()) {
2593 if (isTargetMacOS() && isMacosxVersionLT(10, 9)) {
2594 if (Args.hasArg(options::OPT_static) ||
2595 Args.hasArg(options::OPT_object) ||
2596 Args.hasArg(options::OPT_preload)) {
2597 CmdArgs.push_back("-lgcrt0.o");
2599 CmdArgs.push_back("-lgcrt1.o");
2601 // darwin_crt2 spec is empty.
2603 // By default on OS X 10.8 and later, we don't link with a crt1.o
2604 // file and the linker knows to use _main as the entry point. But,
2605 // when compiling with -pg, we need to link with the gcrt1.o file,
2606 // so pass the -no_new_main option to tell the linker to use the
2607 // "start" symbol as the entry point.
2608 if (isTargetMacOS() && !isMacosxVersionLT(10, 8))
2609 CmdArgs.push_back("-no_new_main");
2611 getDriver().Diag(diag::err_drv_clang_unsupported_opt_pg_darwin)
2615 if (Args.hasArg(options::OPT_static) ||
2616 Args.hasArg(options::OPT_object) ||
2617 Args.hasArg(options::OPT_preload)) {
2618 CmdArgs.push_back("-lcrt0.o");
2620 // Derived from darwin_crt1 spec.
2621 if (isTargetWatchOSBased()) {
2622 ; // watchOS does not need crt1.o.
2623 } else if (isTargetIOSSimulator()) {
2624 ; // iOS simulator does not need crt1.o.
2625 } else if (isTargetIPhoneOS()) {
2626 if (getArch() == llvm::Triple::aarch64)
2627 ; // iOS does not need any crt1 files for arm64
2628 else if (isIPhoneOSVersionLT(3, 1))
2629 CmdArgs.push_back("-lcrt1.o");
2630 else if (isIPhoneOSVersionLT(6, 0))
2631 CmdArgs.push_back("-lcrt1.3.1.o");
2633 if (isMacosxVersionLT(10, 5))
2634 CmdArgs.push_back("-lcrt1.o");
2635 else if (isMacosxVersionLT(10, 6))
2636 CmdArgs.push_back("-lcrt1.10.5.o");
2637 else if (isMacosxVersionLT(10, 8))
2638 CmdArgs.push_back("-lcrt1.10.6.o");
2640 // darwin_crt2 spec is empty.
2647 if (!isTargetIPhoneOS() && Args.hasArg(options::OPT_shared_libgcc) &&
2648 !isTargetWatchOS() && isMacosxVersionLT(10, 5)) {
2649 const char *Str = Args.MakeArgString(GetFilePath("crt3.o"));
2650 CmdArgs.push_back(Str);
2654 void Darwin::CheckObjCARC() const {
2655 if (isTargetIOSBased() || isTargetWatchOSBased() ||
2656 (isTargetMacOS() && !isMacosxVersionLT(10, 6)))
2658 getDriver().Diag(diag::err_arc_unsupported_on_toolchain);
2661 SanitizerMask Darwin::getSupportedSanitizers() const {
2662 const bool IsX86_64 = getTriple().getArch() == llvm::Triple::x86_64;
2663 SanitizerMask Res = ToolChain::getSupportedSanitizers();
2664 Res |= SanitizerKind::Address;
2665 Res |= SanitizerKind::PointerCompare;
2666 Res |= SanitizerKind::PointerSubtract;
2667 Res |= SanitizerKind::Leak;
2668 Res |= SanitizerKind::Fuzzer;
2669 Res |= SanitizerKind::FuzzerNoLink;
2670 Res |= SanitizerKind::Function;
2672 // Prior to 10.9, macOS shipped a version of the C++ standard library without
2673 // C++11 support. The same is true of iOS prior to version 5. These OS'es are
2674 // incompatible with -fsanitize=vptr.
2675 if (!(isTargetMacOS() && isMacosxVersionLT(10, 9))
2676 && !(isTargetIPhoneOS() && isIPhoneOSVersionLT(5, 0)))
2677 Res |= SanitizerKind::Vptr;
2679 if (isTargetMacOS()) {
2681 Res |= SanitizerKind::Thread;
2682 } else if (isTargetIOSSimulator() || isTargetTvOSSimulator()) {
2684 Res |= SanitizerKind::Thread;
2689 void Darwin::printVerboseInfo(raw_ostream &OS) const {
2690 CudaInstallation.print(OS);