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