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