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