1 //===--- Gnu.cpp - Gnu 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 "Gnu.h" 10 #include "Arch/ARM.h" 11 #include "Arch/CSKY.h" 12 #include "Arch/LoongArch.h" 13 #include "Arch/Mips.h" 14 #include "Arch/PPC.h" 15 #include "Arch/RISCV.h" 16 #include "Arch/Sparc.h" 17 #include "Arch/SystemZ.h" 18 #include "CommonArgs.h" 19 #include "Linux.h" 20 #include "clang/Config/config.h" // for GCC_INSTALL_PREFIX 21 #include "clang/Driver/Compilation.h" 22 #include "clang/Driver/Driver.h" 23 #include "clang/Driver/DriverDiagnostic.h" 24 #include "clang/Driver/MultilibBuilder.h" 25 #include "clang/Driver/Options.h" 26 #include "clang/Driver/Tool.h" 27 #include "clang/Driver/ToolChain.h" 28 #include "llvm/ADT/StringSet.h" 29 #include "llvm/ADT/Twine.h" 30 #include "llvm/Option/ArgList.h" 31 #include "llvm/Support/CodeGen.h" 32 #include "llvm/Support/Path.h" 33 #include "llvm/Support/VirtualFileSystem.h" 34 #include "llvm/TargetParser/RISCVISAInfo.h" 35 #include "llvm/TargetParser/TargetParser.h" 36 #include <system_error> 37 38 using namespace clang::driver; 39 using namespace clang::driver::toolchains; 40 using namespace clang; 41 using namespace llvm::opt; 42 43 using tools::addMultilibFlag; 44 using tools::addPathIfExists; 45 46 static bool forwardToGCC(const Option &O) { 47 // LinkerInput options have been forwarded. Don't duplicate. 48 if (O.hasFlag(options::LinkerInput)) 49 return false; 50 return O.matches(options::OPT_Link_Group) || O.hasFlag(options::LinkOption); 51 } 52 53 // Switch CPU names not recognized by GNU assembler to a close CPU that it does 54 // recognize, instead of a lower march from being picked in the absence of a cpu 55 // flag. 56 static void normalizeCPUNamesForAssembler(const ArgList &Args, 57 ArgStringList &CmdArgs) { 58 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) { 59 StringRef CPUArg(A->getValue()); 60 if (CPUArg.equals_insensitive("krait")) 61 CmdArgs.push_back("-mcpu=cortex-a15"); 62 else if (CPUArg.equals_insensitive("kryo")) 63 CmdArgs.push_back("-mcpu=cortex-a57"); 64 else 65 Args.AddLastArg(CmdArgs, options::OPT_mcpu_EQ); 66 } 67 } 68 69 void tools::gcc::Common::ConstructJob(Compilation &C, const JobAction &JA, 70 const InputInfo &Output, 71 const InputInfoList &Inputs, 72 const ArgList &Args, 73 const char *LinkingOutput) const { 74 const Driver &D = getToolChain().getDriver(); 75 ArgStringList CmdArgs; 76 77 for (const auto &A : Args) { 78 if (forwardToGCC(A->getOption())) { 79 // It is unfortunate that we have to claim here, as this means 80 // we will basically never report anything interesting for 81 // platforms using a generic gcc, even if we are just using gcc 82 // to get to the assembler. 83 A->claim(); 84 85 A->render(Args, CmdArgs); 86 } 87 } 88 89 RenderExtraToolArgs(JA, CmdArgs); 90 91 // If using a driver, force the arch. 92 if (getToolChain().getTriple().isOSDarwin()) { 93 CmdArgs.push_back("-arch"); 94 CmdArgs.push_back( 95 Args.MakeArgString(getToolChain().getDefaultUniversalArchName())); 96 } 97 98 // Try to force gcc to match the tool chain we want, if we recognize 99 // the arch. 100 // 101 // FIXME: The triple class should directly provide the information we want 102 // here. 103 switch (getToolChain().getArch()) { 104 default: 105 break; 106 case llvm::Triple::x86: 107 case llvm::Triple::ppc: 108 case llvm::Triple::ppcle: 109 CmdArgs.push_back("-m32"); 110 break; 111 case llvm::Triple::x86_64: 112 case llvm::Triple::ppc64: 113 case llvm::Triple::ppc64le: 114 CmdArgs.push_back("-m64"); 115 break; 116 case llvm::Triple::sparcel: 117 CmdArgs.push_back("-EL"); 118 break; 119 } 120 121 assert((Output.isFilename() || Output.isNothing()) && "Invalid output."); 122 if (Output.isFilename()) { 123 CmdArgs.push_back("-o"); 124 CmdArgs.push_back(Output.getFilename()); 125 } else { 126 CmdArgs.push_back("-fsyntax-only"); 127 } 128 129 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler); 130 131 // Only pass -x if gcc will understand it; otherwise hope gcc 132 // understands the suffix correctly. The main use case this would go 133 // wrong in is for linker inputs if they happened to have an odd 134 // suffix; really the only way to get this to happen is a command 135 // like '-x foobar a.c' which will treat a.c like a linker input. 136 // 137 // FIXME: For the linker case specifically, can we safely convert 138 // inputs into '-Wl,' options? 139 for (const auto &II : Inputs) { 140 // Don't try to pass LLVM or AST inputs to a generic gcc. 141 if (types::isLLVMIR(II.getType())) 142 D.Diag(clang::diag::err_drv_no_linker_llvm_support) 143 << getToolChain().getTripleString(); 144 else if (II.getType() == types::TY_AST) 145 D.Diag(diag::err_drv_no_ast_support) << getToolChain().getTripleString(); 146 else if (II.getType() == types::TY_ModuleFile) 147 D.Diag(diag::err_drv_no_module_support) 148 << getToolChain().getTripleString(); 149 150 if (types::canTypeBeUserSpecified(II.getType())) { 151 CmdArgs.push_back("-x"); 152 CmdArgs.push_back(types::getTypeName(II.getType())); 153 } 154 155 if (II.isFilename()) 156 CmdArgs.push_back(II.getFilename()); 157 else { 158 const Arg &A = II.getInputArg(); 159 160 // Reverse translate some rewritten options. 161 if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) { 162 CmdArgs.push_back("-lstdc++"); 163 continue; 164 } 165 166 // Don't render as input, we need gcc to do the translations. 167 A.render(Args, CmdArgs); 168 } 169 } 170 171 const std::string &customGCCName = D.getCCCGenericGCCName(); 172 const char *GCCName; 173 if (!customGCCName.empty()) 174 GCCName = customGCCName.c_str(); 175 else if (D.CCCIsCXX()) { 176 GCCName = "g++"; 177 } else 178 GCCName = "gcc"; 179 180 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath(GCCName)); 181 C.addCommand(std::make_unique<Command>(JA, *this, 182 ResponseFileSupport::AtFileCurCP(), 183 Exec, CmdArgs, Inputs, Output)); 184 } 185 186 void tools::gcc::Preprocessor::RenderExtraToolArgs( 187 const JobAction &JA, ArgStringList &CmdArgs) const { 188 CmdArgs.push_back("-E"); 189 } 190 191 void tools::gcc::Compiler::RenderExtraToolArgs(const JobAction &JA, 192 ArgStringList &CmdArgs) const { 193 const Driver &D = getToolChain().getDriver(); 194 195 switch (JA.getType()) { 196 // If -flto, etc. are present then make sure not to force assembly output. 197 case types::TY_LLVM_IR: 198 case types::TY_LTO_IR: 199 case types::TY_LLVM_BC: 200 case types::TY_LTO_BC: 201 CmdArgs.push_back("-c"); 202 break; 203 // We assume we've got an "integrated" assembler in that gcc will produce an 204 // object file itself. 205 case types::TY_Object: 206 CmdArgs.push_back("-c"); 207 break; 208 case types::TY_PP_Asm: 209 CmdArgs.push_back("-S"); 210 break; 211 case types::TY_Nothing: 212 CmdArgs.push_back("-fsyntax-only"); 213 break; 214 default: 215 D.Diag(diag::err_drv_invalid_gcc_output_type) << getTypeName(JA.getType()); 216 } 217 } 218 219 void tools::gcc::Linker::RenderExtraToolArgs(const JobAction &JA, 220 ArgStringList &CmdArgs) const { 221 // The types are (hopefully) good enough. 222 } 223 224 static const char *getLDMOption(const llvm::Triple &T, const ArgList &Args) { 225 switch (T.getArch()) { 226 case llvm::Triple::x86: 227 if (T.isOSIAMCU()) 228 return "elf_iamcu"; 229 return "elf_i386"; 230 case llvm::Triple::aarch64: 231 return "aarch64linux"; 232 case llvm::Triple::aarch64_be: 233 return "aarch64linuxb"; 234 case llvm::Triple::arm: 235 case llvm::Triple::thumb: 236 case llvm::Triple::armeb: 237 case llvm::Triple::thumbeb: 238 return tools::arm::isARMBigEndian(T, Args) ? "armelfb_linux_eabi" 239 : "armelf_linux_eabi"; 240 case llvm::Triple::m68k: 241 return "m68kelf"; 242 case llvm::Triple::ppc: 243 if (T.isOSLinux()) 244 return "elf32ppclinux"; 245 return "elf32ppc"; 246 case llvm::Triple::ppcle: 247 if (T.isOSLinux()) 248 return "elf32lppclinux"; 249 return "elf32lppc"; 250 case llvm::Triple::ppc64: 251 return "elf64ppc"; 252 case llvm::Triple::ppc64le: 253 return "elf64lppc"; 254 case llvm::Triple::riscv32: 255 return "elf32lriscv"; 256 case llvm::Triple::riscv64: 257 return "elf64lriscv"; 258 case llvm::Triple::sparc: 259 case llvm::Triple::sparcel: 260 return "elf32_sparc"; 261 case llvm::Triple::sparcv9: 262 return "elf64_sparc"; 263 case llvm::Triple::loongarch32: 264 return "elf32loongarch"; 265 case llvm::Triple::loongarch64: 266 return "elf64loongarch"; 267 case llvm::Triple::mips: 268 return "elf32btsmip"; 269 case llvm::Triple::mipsel: 270 return "elf32ltsmip"; 271 case llvm::Triple::mips64: 272 if (tools::mips::hasMipsAbiArg(Args, "n32") || 273 T.getEnvironment() == llvm::Triple::GNUABIN32) 274 return "elf32btsmipn32"; 275 return "elf64btsmip"; 276 case llvm::Triple::mips64el: 277 if (tools::mips::hasMipsAbiArg(Args, "n32") || 278 T.getEnvironment() == llvm::Triple::GNUABIN32) 279 return "elf32ltsmipn32"; 280 return "elf64ltsmip"; 281 case llvm::Triple::systemz: 282 return "elf64_s390"; 283 case llvm::Triple::x86_64: 284 if (T.isX32()) 285 return "elf32_x86_64"; 286 return "elf_x86_64"; 287 case llvm::Triple::ve: 288 return "elf64ve"; 289 case llvm::Triple::csky: 290 return "cskyelf_linux"; 291 default: 292 return nullptr; 293 } 294 } 295 296 static bool getStaticPIE(const ArgList &Args, const ToolChain &TC) { 297 bool HasStaticPIE = Args.hasArg(options::OPT_static_pie); 298 if (HasStaticPIE && Args.hasArg(options::OPT_no_pie)) { 299 const Driver &D = TC.getDriver(); 300 const llvm::opt::OptTable &Opts = D.getOpts(); 301 StringRef StaticPIEName = Opts.getOptionName(options::OPT_static_pie); 302 StringRef NoPIEName = Opts.getOptionName(options::OPT_nopie); 303 D.Diag(diag::err_drv_cannot_mix_options) << StaticPIEName << NoPIEName; 304 } 305 return HasStaticPIE; 306 } 307 308 static bool getStatic(const ArgList &Args) { 309 return Args.hasArg(options::OPT_static) && 310 !Args.hasArg(options::OPT_static_pie); 311 } 312 313 void tools::gnutools::StaticLibTool::ConstructJob( 314 Compilation &C, const JobAction &JA, const InputInfo &Output, 315 const InputInfoList &Inputs, const ArgList &Args, 316 const char *LinkingOutput) const { 317 const Driver &D = getToolChain().getDriver(); 318 319 // Silence warning for "clang -g foo.o -o foo" 320 Args.ClaimAllArgs(options::OPT_g_Group); 321 // and "clang -emit-llvm foo.o -o foo" 322 Args.ClaimAllArgs(options::OPT_emit_llvm); 323 // and for "clang -w foo.o -o foo". Other warning options are already 324 // handled somewhere else. 325 Args.ClaimAllArgs(options::OPT_w); 326 // Silence warnings when linking C code with a C++ '-stdlib' argument. 327 Args.ClaimAllArgs(options::OPT_stdlib_EQ); 328 329 // ar tool command "llvm-ar <options> <output_file> <input_files>". 330 ArgStringList CmdArgs; 331 // Create and insert file members with a deterministic index. 332 CmdArgs.push_back("rcsD"); 333 CmdArgs.push_back(Output.getFilename()); 334 335 for (const auto &II : Inputs) { 336 if (II.isFilename()) { 337 CmdArgs.push_back(II.getFilename()); 338 } 339 } 340 341 // Delete old output archive file if it already exists before generating a new 342 // archive file. 343 auto OutputFileName = Output.getFilename(); 344 if (Output.isFilename() && llvm::sys::fs::exists(OutputFileName)) { 345 if (std::error_code EC = llvm::sys::fs::remove(OutputFileName)) { 346 D.Diag(diag::err_drv_unable_to_remove_file) << EC.message(); 347 return; 348 } 349 } 350 351 const char *Exec = Args.MakeArgString(getToolChain().GetStaticLibToolPath()); 352 C.addCommand(std::make_unique<Command>(JA, *this, 353 ResponseFileSupport::AtFileCurCP(), 354 Exec, CmdArgs, Inputs, Output)); 355 } 356 357 void tools::gnutools::Linker::ConstructJob(Compilation &C, const JobAction &JA, 358 const InputInfo &Output, 359 const InputInfoList &Inputs, 360 const ArgList &Args, 361 const char *LinkingOutput) const { 362 // FIXME: The Linker class constructor takes a ToolChain and not a 363 // Generic_ELF, so the static_cast might return a reference to a invalid 364 // instance (see PR45061). Ideally, the Linker constructor needs to take a 365 // Generic_ELF instead. 366 const auto &ToolChain = static_cast<const Generic_ELF &>(getToolChain()); 367 const Driver &D = ToolChain.getDriver(); 368 369 const llvm::Triple &Triple = getToolChain().getEffectiveTriple(); 370 371 const llvm::Triple::ArchType Arch = ToolChain.getArch(); 372 const bool isOHOSFamily = ToolChain.getTriple().isOHOSFamily(); 373 const bool isAndroid = ToolChain.getTriple().isAndroid(); 374 const bool IsIAMCU = ToolChain.getTriple().isOSIAMCU(); 375 const bool IsVE = ToolChain.getTriple().isVE(); 376 const bool IsStaticPIE = getStaticPIE(Args, ToolChain); 377 const bool IsStatic = getStatic(Args); 378 const bool HasCRTBeginEndFiles = 379 ToolChain.getTriple().hasEnvironment() || 380 (ToolChain.getTriple().getVendor() != llvm::Triple::MipsTechnologies); 381 382 ArgStringList CmdArgs; 383 384 // Silence warning for "clang -g foo.o -o foo" 385 Args.ClaimAllArgs(options::OPT_g_Group); 386 // and "clang -emit-llvm foo.o -o foo" 387 Args.ClaimAllArgs(options::OPT_emit_llvm); 388 // and for "clang -w foo.o -o foo". Other warning options are already 389 // handled somewhere else. 390 Args.ClaimAllArgs(options::OPT_w); 391 392 if (!D.SysRoot.empty()) 393 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot)); 394 395 if (Args.hasArg(options::OPT_s)) 396 CmdArgs.push_back("-s"); 397 398 if (Triple.isARM() || Triple.isThumb()) { 399 bool IsBigEndian = arm::isARMBigEndian(Triple, Args); 400 if (IsBigEndian) 401 arm::appendBE8LinkFlag(Args, CmdArgs, Triple); 402 CmdArgs.push_back(IsBigEndian ? "-EB" : "-EL"); 403 } else if (Triple.isAArch64()) { 404 CmdArgs.push_back(Arch == llvm::Triple::aarch64_be ? "-EB" : "-EL"); 405 } 406 407 // Most Android ARM64 targets should enable the linker fix for erratum 408 // 843419. Only non-Cortex-A53 devices are allowed to skip this flag. 409 if (Arch == llvm::Triple::aarch64 && (isAndroid || isOHOSFamily)) { 410 std::string CPU = getCPUName(D, Args, Triple); 411 if (CPU.empty() || CPU == "generic" || CPU == "cortex-a53") 412 CmdArgs.push_back("--fix-cortex-a53-843419"); 413 } 414 415 ToolChain.addExtraOpts(CmdArgs); 416 417 CmdArgs.push_back("--eh-frame-hdr"); 418 419 if (const char *LDMOption = getLDMOption(ToolChain.getTriple(), Args)) { 420 CmdArgs.push_back("-m"); 421 CmdArgs.push_back(LDMOption); 422 } else { 423 D.Diag(diag::err_target_unknown_triple) << Triple.str(); 424 return; 425 } 426 427 if (Triple.isRISCV()) { 428 CmdArgs.push_back("-X"); 429 if (Args.hasArg(options::OPT_mno_relax)) 430 CmdArgs.push_back("--no-relax"); 431 } 432 433 const bool IsShared = Args.hasArg(options::OPT_shared); 434 if (IsShared) 435 CmdArgs.push_back("-shared"); 436 bool IsPIE = false; 437 if (IsStaticPIE) { 438 CmdArgs.push_back("-static"); 439 CmdArgs.push_back("-pie"); 440 CmdArgs.push_back("--no-dynamic-linker"); 441 CmdArgs.push_back("-z"); 442 CmdArgs.push_back("text"); 443 } else if (IsStatic) { 444 CmdArgs.push_back("-static"); 445 } else if (!Args.hasArg(options::OPT_r)) { 446 if (Args.hasArg(options::OPT_rdynamic)) 447 CmdArgs.push_back("-export-dynamic"); 448 if (!IsShared) { 449 IsPIE = Args.hasFlag(options::OPT_pie, options::OPT_no_pie, 450 ToolChain.isPIEDefault(Args)); 451 if (IsPIE) 452 CmdArgs.push_back("-pie"); 453 CmdArgs.push_back("-dynamic-linker"); 454 CmdArgs.push_back(Args.MakeArgString(Twine(D.DyldPrefix) + 455 ToolChain.getDynamicLinker(Args))); 456 } 457 } 458 459 CmdArgs.push_back("-o"); 460 CmdArgs.push_back(Output.getFilename()); 461 462 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles, 463 options::OPT_r)) { 464 if (!isAndroid && !IsIAMCU) { 465 const char *crt1 = nullptr; 466 if (!Args.hasArg(options::OPT_shared)) { 467 if (Args.hasArg(options::OPT_pg)) 468 crt1 = "gcrt1.o"; 469 else if (IsPIE) 470 crt1 = "Scrt1.o"; 471 else if (IsStaticPIE) 472 crt1 = "rcrt1.o"; 473 else 474 crt1 = "crt1.o"; 475 } 476 if (crt1) 477 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1))); 478 479 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o"))); 480 } 481 482 if (IsVE) { 483 CmdArgs.push_back("-z"); 484 CmdArgs.push_back("max-page-size=0x4000000"); 485 } 486 487 if (IsIAMCU) 488 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt0.o"))); 489 else if (HasCRTBeginEndFiles) { 490 std::string P; 491 if (ToolChain.GetRuntimeLibType(Args) == ToolChain::RLT_CompilerRT && 492 !isAndroid) { 493 std::string crtbegin = ToolChain.getCompilerRT(Args, "crtbegin", 494 ToolChain::FT_Object); 495 if (ToolChain.getVFS().exists(crtbegin)) 496 P = crtbegin; 497 } 498 if (P.empty()) { 499 const char *crtbegin; 500 if (Args.hasArg(options::OPT_shared)) 501 crtbegin = isAndroid ? "crtbegin_so.o" : "crtbeginS.o"; 502 else if (IsStatic) 503 crtbegin = isAndroid ? "crtbegin_static.o" : "crtbeginT.o"; 504 else if (IsPIE || IsStaticPIE) 505 crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbeginS.o"; 506 else 507 crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbegin.o"; 508 P = ToolChain.GetFilePath(crtbegin); 509 } 510 CmdArgs.push_back(Args.MakeArgString(P)); 511 } 512 513 // Add crtfastmath.o if available and fast math is enabled. 514 ToolChain.addFastMathRuntimeIfAvailable(Args, CmdArgs); 515 516 if (isAndroid && Args.hasFlag(options::OPT_fandroid_pad_segment, 517 options::OPT_fno_android_pad_segment, false)) 518 CmdArgs.push_back( 519 Args.MakeArgString(ToolChain.GetFilePath("crt_pad_segment.o"))); 520 } 521 522 Args.addAllArgs(CmdArgs, {options::OPT_L, options::OPT_u}); 523 524 ToolChain.AddFilePathLibArgs(Args, CmdArgs); 525 526 if (D.isUsingLTO()) { 527 assert(!Inputs.empty() && "Must have at least one input."); 528 // Find the first filename InputInfo object. 529 auto Input = llvm::find_if( 530 Inputs, [](const InputInfo &II) -> bool { return II.isFilename(); }); 531 if (Input == Inputs.end()) 532 // For a very rare case, all of the inputs to the linker are 533 // InputArg. If that happens, just use the first InputInfo. 534 Input = Inputs.begin(); 535 536 addLTOOptions(ToolChain, Args, CmdArgs, Output, *Input, 537 D.getLTOMode() == LTOK_Thin); 538 } 539 540 if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle)) 541 CmdArgs.push_back("--no-demangle"); 542 543 bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs); 544 bool NeedsXRayDeps = addXRayRuntime(ToolChain, Args, CmdArgs); 545 addLinkerCompressDebugSectionsOption(ToolChain, Args, CmdArgs); 546 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs, JA); 547 548 addHIPRuntimeLibArgs(ToolChain, C, Args, CmdArgs); 549 550 // The profile runtime also needs access to system libraries. 551 getToolChain().addProfileRTLibs(Args, CmdArgs); 552 553 if (D.CCCIsCXX() && 554 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs, 555 options::OPT_r)) { 556 if (ToolChain.ShouldLinkCXXStdlib(Args)) { 557 bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) && 558 !Args.hasArg(options::OPT_static); 559 if (OnlyLibstdcxxStatic) 560 CmdArgs.push_back("-Bstatic"); 561 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs); 562 if (OnlyLibstdcxxStatic) 563 CmdArgs.push_back("-Bdynamic"); 564 } 565 CmdArgs.push_back("-lm"); 566 } 567 568 // Silence warnings when linking C code with a C++ '-stdlib' argument. 569 Args.ClaimAllArgs(options::OPT_stdlib_EQ); 570 571 // Additional linker set-up and flags for Fortran. This is required in order 572 // to generate executables. As Fortran runtime depends on the C runtime, 573 // these dependencies need to be listed before the C runtime below (i.e. 574 // AddRunTimeLibs). 575 if (D.IsFlangMode()) { 576 addFortranRuntimeLibraryPath(ToolChain, Args, CmdArgs); 577 addFortranRuntimeLibs(ToolChain, Args, CmdArgs); 578 CmdArgs.push_back("-lm"); 579 } 580 581 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_r)) { 582 if (!Args.hasArg(options::OPT_nodefaultlibs)) { 583 if (IsStatic || IsStaticPIE) 584 CmdArgs.push_back("--start-group"); 585 586 if (NeedsSanitizerDeps) 587 linkSanitizerRuntimeDeps(ToolChain, Args, CmdArgs); 588 589 if (NeedsXRayDeps) 590 linkXRayRuntimeDeps(ToolChain, Args, CmdArgs); 591 592 bool WantPthread = Args.hasArg(options::OPT_pthread) || 593 Args.hasArg(options::OPT_pthreads); 594 595 // Use the static OpenMP runtime with -static-openmp 596 bool StaticOpenMP = Args.hasArg(options::OPT_static_openmp) && 597 !Args.hasArg(options::OPT_static); 598 599 // FIXME: Only pass GompNeedsRT = true for platforms with libgomp that 600 // require librt. Most modern Linux platforms do, but some may not. 601 if (addOpenMPRuntime(C, CmdArgs, ToolChain, Args, StaticOpenMP, 602 JA.isHostOffloading(Action::OFK_OpenMP), 603 /* GompNeedsRT= */ true)) 604 // OpenMP runtimes implies pthreads when using the GNU toolchain. 605 // FIXME: Does this really make sense for all GNU toolchains? 606 WantPthread = true; 607 608 AddRunTimeLibs(ToolChain, D, CmdArgs, Args); 609 610 // LLVM support for atomics on 32-bit SPARC V8+ is incomplete, so 611 // forcibly link with libatomic as a workaround. 612 // TODO: Issue #41880 and D118021. 613 if (getToolChain().getTriple().getArch() == llvm::Triple::sparc) { 614 CmdArgs.push_back("--push-state"); 615 CmdArgs.push_back("--as-needed"); 616 CmdArgs.push_back("-latomic"); 617 CmdArgs.push_back("--pop-state"); 618 } 619 620 // We don't need libpthread neither for bionic (Android) nor for musl, 621 // (used by OHOS as runtime library). 622 if (WantPthread && !isAndroid && !isOHOSFamily) 623 CmdArgs.push_back("-lpthread"); 624 625 if (Args.hasArg(options::OPT_fsplit_stack)) 626 CmdArgs.push_back("--wrap=pthread_create"); 627 628 if (!Args.hasArg(options::OPT_nolibc)) 629 CmdArgs.push_back("-lc"); 630 631 // Add IAMCU specific libs, if needed. 632 if (IsIAMCU) 633 CmdArgs.push_back("-lgloss"); 634 635 if (IsStatic || IsStaticPIE) 636 CmdArgs.push_back("--end-group"); 637 else 638 AddRunTimeLibs(ToolChain, D, CmdArgs, Args); 639 640 // Add IAMCU specific libs (outside the group), if needed. 641 if (IsIAMCU) { 642 CmdArgs.push_back("--as-needed"); 643 CmdArgs.push_back("-lsoftfp"); 644 CmdArgs.push_back("--no-as-needed"); 645 } 646 } 647 648 if (!Args.hasArg(options::OPT_nostartfiles) && !IsIAMCU) { 649 if (HasCRTBeginEndFiles) { 650 std::string P; 651 if (ToolChain.GetRuntimeLibType(Args) == ToolChain::RLT_CompilerRT && 652 !isAndroid) { 653 std::string crtend = ToolChain.getCompilerRT(Args, "crtend", 654 ToolChain::FT_Object); 655 if (ToolChain.getVFS().exists(crtend)) 656 P = crtend; 657 } 658 if (P.empty()) { 659 const char *crtend; 660 if (Args.hasArg(options::OPT_shared)) 661 crtend = isAndroid ? "crtend_so.o" : "crtendS.o"; 662 else if (IsPIE || IsStaticPIE) 663 crtend = isAndroid ? "crtend_android.o" : "crtendS.o"; 664 else 665 crtend = isAndroid ? "crtend_android.o" : "crtend.o"; 666 P = ToolChain.GetFilePath(crtend); 667 } 668 CmdArgs.push_back(Args.MakeArgString(P)); 669 } 670 if (!isAndroid) 671 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o"))); 672 } 673 } 674 675 Args.AddAllArgs(CmdArgs, options::OPT_T); 676 677 const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath()); 678 C.addCommand(std::make_unique<Command>(JA, *this, 679 ResponseFileSupport::AtFileCurCP(), 680 Exec, CmdArgs, Inputs, Output)); 681 } 682 683 void tools::gnutools::Assembler::ConstructJob(Compilation &C, 684 const JobAction &JA, 685 const InputInfo &Output, 686 const InputInfoList &Inputs, 687 const ArgList &Args, 688 const char *LinkingOutput) const { 689 const auto &D = getToolChain().getDriver(); 690 691 claimNoWarnArgs(Args); 692 693 ArgStringList CmdArgs; 694 695 llvm::Reloc::Model RelocationModel; 696 unsigned PICLevel; 697 bool IsPIE; 698 const char *DefaultAssembler = "as"; 699 // Enforce GNU as on Solaris; the native assembler's input syntax isn't fully 700 // compatible. 701 if (getToolChain().getTriple().isOSSolaris()) 702 DefaultAssembler = "gas"; 703 std::tie(RelocationModel, PICLevel, IsPIE) = 704 ParsePICArgs(getToolChain(), Args); 705 706 if (const Arg *A = Args.getLastArg(options::OPT_gz, options::OPT_gz_EQ)) { 707 if (A->getOption().getID() == options::OPT_gz) { 708 CmdArgs.push_back("--compress-debug-sections"); 709 } else { 710 StringRef Value = A->getValue(); 711 if (Value == "none" || Value == "zlib" || Value == "zstd") { 712 CmdArgs.push_back( 713 Args.MakeArgString("--compress-debug-sections=" + Twine(Value))); 714 } else { 715 D.Diag(diag::err_drv_unsupported_option_argument) 716 << A->getSpelling() << Value; 717 } 718 } 719 } 720 721 switch (getToolChain().getArch()) { 722 default: 723 break; 724 // Add --32/--64 to make sure we get the format we want. 725 // This is incomplete 726 case llvm::Triple::x86: 727 CmdArgs.push_back("--32"); 728 break; 729 case llvm::Triple::x86_64: 730 if (getToolChain().getTriple().isX32()) 731 CmdArgs.push_back("--x32"); 732 else 733 CmdArgs.push_back("--64"); 734 break; 735 case llvm::Triple::ppc: { 736 CmdArgs.push_back("-a32"); 737 CmdArgs.push_back("-mppc"); 738 CmdArgs.push_back("-mbig-endian"); 739 CmdArgs.push_back(ppc::getPPCAsmModeForCPU( 740 getCPUName(D, Args, getToolChain().getTriple()))); 741 break; 742 } 743 case llvm::Triple::ppcle: { 744 CmdArgs.push_back("-a32"); 745 CmdArgs.push_back("-mppc"); 746 CmdArgs.push_back("-mlittle-endian"); 747 CmdArgs.push_back(ppc::getPPCAsmModeForCPU( 748 getCPUName(D, Args, getToolChain().getTriple()))); 749 break; 750 } 751 case llvm::Triple::ppc64: { 752 CmdArgs.push_back("-a64"); 753 CmdArgs.push_back("-mppc64"); 754 CmdArgs.push_back("-mbig-endian"); 755 CmdArgs.push_back(ppc::getPPCAsmModeForCPU( 756 getCPUName(D, Args, getToolChain().getTriple()))); 757 break; 758 } 759 case llvm::Triple::ppc64le: { 760 CmdArgs.push_back("-a64"); 761 CmdArgs.push_back("-mppc64"); 762 CmdArgs.push_back("-mlittle-endian"); 763 CmdArgs.push_back(ppc::getPPCAsmModeForCPU( 764 getCPUName(D, Args, getToolChain().getTriple()))); 765 break; 766 } 767 case llvm::Triple::riscv32: 768 case llvm::Triple::riscv64: { 769 StringRef ABIName = riscv::getRISCVABI(Args, getToolChain().getTriple()); 770 CmdArgs.push_back("-mabi"); 771 CmdArgs.push_back(ABIName.data()); 772 std::string MArchName = 773 riscv::getRISCVArch(Args, getToolChain().getTriple()); 774 CmdArgs.push_back("-march"); 775 CmdArgs.push_back(Args.MakeArgString(MArchName)); 776 if (!Args.hasFlag(options::OPT_mrelax, options::OPT_mno_relax, true)) 777 Args.addOptOutFlag(CmdArgs, options::OPT_mrelax, options::OPT_mno_relax); 778 break; 779 } 780 case llvm::Triple::sparc: 781 case llvm::Triple::sparcel: { 782 CmdArgs.push_back("-32"); 783 std::string CPU = getCPUName(D, Args, getToolChain().getTriple()); 784 CmdArgs.push_back( 785 sparc::getSparcAsmModeForCPU(CPU, getToolChain().getTriple())); 786 AddAssemblerKPIC(getToolChain(), Args, CmdArgs); 787 break; 788 } 789 case llvm::Triple::sparcv9: { 790 CmdArgs.push_back("-64"); 791 std::string CPU = getCPUName(D, Args, getToolChain().getTriple()); 792 CmdArgs.push_back( 793 sparc::getSparcAsmModeForCPU(CPU, getToolChain().getTriple())); 794 AddAssemblerKPIC(getToolChain(), Args, CmdArgs); 795 break; 796 } 797 case llvm::Triple::arm: 798 case llvm::Triple::armeb: 799 case llvm::Triple::thumb: 800 case llvm::Triple::thumbeb: { 801 const llvm::Triple &Triple2 = getToolChain().getTriple(); 802 CmdArgs.push_back(arm::isARMBigEndian(Triple2, Args) ? "-EB" : "-EL"); 803 switch (Triple2.getSubArch()) { 804 case llvm::Triple::ARMSubArch_v7: 805 CmdArgs.push_back("-mfpu=neon"); 806 break; 807 case llvm::Triple::ARMSubArch_v8: 808 CmdArgs.push_back("-mfpu=crypto-neon-fp-armv8"); 809 break; 810 default: 811 break; 812 } 813 814 switch (arm::getARMFloatABI(getToolChain(), Args)) { 815 case arm::FloatABI::Invalid: llvm_unreachable("must have an ABI!"); 816 case arm::FloatABI::Soft: 817 CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=soft")); 818 break; 819 case arm::FloatABI::SoftFP: 820 CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=softfp")); 821 break; 822 case arm::FloatABI::Hard: 823 CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=hard")); 824 break; 825 } 826 827 Args.AddLastArg(CmdArgs, options::OPT_march_EQ); 828 normalizeCPUNamesForAssembler(Args, CmdArgs); 829 830 Args.AddLastArg(CmdArgs, options::OPT_mfpu_EQ); 831 // The integrated assembler doesn't implement e_flags setting behavior for 832 // -meabi=gnu (gcc -mabi={apcs-gnu,atpcs} passes -meabi=gnu to gas). For 833 // compatibility we accept but warn. 834 if (Arg *A = Args.getLastArgNoClaim(options::OPT_mabi_EQ)) 835 A->ignoreTargetSpecific(); 836 break; 837 } 838 case llvm::Triple::aarch64: 839 case llvm::Triple::aarch64_be: { 840 CmdArgs.push_back( 841 getToolChain().getArch() == llvm::Triple::aarch64_be ? "-EB" : "-EL"); 842 Args.AddLastArg(CmdArgs, options::OPT_march_EQ); 843 normalizeCPUNamesForAssembler(Args, CmdArgs); 844 845 break; 846 } 847 // TODO: handle loongarch32. 848 case llvm::Triple::loongarch64: { 849 StringRef ABIName = 850 loongarch::getLoongArchABI(D, Args, getToolChain().getTriple()); 851 CmdArgs.push_back(Args.MakeArgString("-mabi=" + ABIName)); 852 break; 853 } 854 case llvm::Triple::mips: 855 case llvm::Triple::mipsel: 856 case llvm::Triple::mips64: 857 case llvm::Triple::mips64el: { 858 StringRef CPUName; 859 StringRef ABIName; 860 mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName); 861 ABIName = mips::getGnuCompatibleMipsABIName(ABIName); 862 863 CmdArgs.push_back("-march"); 864 CmdArgs.push_back(CPUName.data()); 865 866 CmdArgs.push_back("-mabi"); 867 CmdArgs.push_back(ABIName.data()); 868 869 // -mno-shared should be emitted unless -fpic, -fpie, -fPIC, -fPIE, 870 // or -mshared (not implemented) is in effect. 871 if (RelocationModel == llvm::Reloc::Static) 872 CmdArgs.push_back("-mno-shared"); 873 874 // LLVM doesn't support -mplt yet and acts as if it is always given. 875 // However, -mplt has no effect with the N64 ABI. 876 if (ABIName != "64" && !Args.hasArg(options::OPT_mno_abicalls)) 877 CmdArgs.push_back("-call_nonpic"); 878 879 if (getToolChain().getTriple().isLittleEndian()) 880 CmdArgs.push_back("-EL"); 881 else 882 CmdArgs.push_back("-EB"); 883 884 if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) { 885 if (StringRef(A->getValue()) == "2008") 886 CmdArgs.push_back(Args.MakeArgString("-mnan=2008")); 887 } 888 889 // Add the last -mfp32/-mfpxx/-mfp64 or -mfpxx if it is enabled by default. 890 if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx, 891 options::OPT_mfp64)) { 892 A->claim(); 893 A->render(Args, CmdArgs); 894 } else if (mips::shouldUseFPXX( 895 Args, getToolChain().getTriple(), CPUName, ABIName, 896 mips::getMipsFloatABI(getToolChain().getDriver(), Args, 897 getToolChain().getTriple()))) 898 CmdArgs.push_back("-mfpxx"); 899 900 // Pass on -mmips16 or -mno-mips16. However, the assembler equivalent of 901 // -mno-mips16 is actually -no-mips16. 902 if (Arg *A = 903 Args.getLastArg(options::OPT_mips16, options::OPT_mno_mips16)) { 904 if (A->getOption().matches(options::OPT_mips16)) { 905 A->claim(); 906 A->render(Args, CmdArgs); 907 } else { 908 A->claim(); 909 CmdArgs.push_back("-no-mips16"); 910 } 911 } 912 913 Args.AddLastArg(CmdArgs, options::OPT_mmicromips, 914 options::OPT_mno_micromips); 915 Args.AddLastArg(CmdArgs, options::OPT_mdsp, options::OPT_mno_dsp); 916 Args.AddLastArg(CmdArgs, options::OPT_mdspr2, options::OPT_mno_dspr2); 917 918 if (Arg *A = Args.getLastArg(options::OPT_mmsa, options::OPT_mno_msa)) { 919 // Do not use AddLastArg because not all versions of MIPS assembler 920 // support -mmsa / -mno-msa options. 921 if (A->getOption().matches(options::OPT_mmsa)) 922 CmdArgs.push_back(Args.MakeArgString("-mmsa")); 923 } 924 925 Args.AddLastArg(CmdArgs, options::OPT_mhard_float, 926 options::OPT_msoft_float); 927 928 Args.AddLastArg(CmdArgs, options::OPT_mdouble_float, 929 options::OPT_msingle_float); 930 931 Args.AddLastArg(CmdArgs, options::OPT_modd_spreg, 932 options::OPT_mno_odd_spreg); 933 934 AddAssemblerKPIC(getToolChain(), Args, CmdArgs); 935 break; 936 } 937 case llvm::Triple::systemz: { 938 // Always pass an -march option, since our default of z10 is later 939 // than the GNU assembler's default. 940 std::string CPUName = systemz::getSystemZTargetCPU(Args); 941 CmdArgs.push_back(Args.MakeArgString("-march=" + CPUName)); 942 break; 943 } 944 case llvm::Triple::ve: 945 DefaultAssembler = "nas"; 946 } 947 948 for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ, 949 options::OPT_fdebug_prefix_map_EQ)) { 950 StringRef Map = A->getValue(); 951 if (!Map.contains('=')) 952 D.Diag(diag::err_drv_invalid_argument_to_option) 953 << Map << A->getOption().getName(); 954 else { 955 CmdArgs.push_back(Args.MakeArgString("--debug-prefix-map")); 956 CmdArgs.push_back(Args.MakeArgString(Map)); 957 } 958 A->claim(); 959 } 960 961 Args.AddAllArgs(CmdArgs, options::OPT_I); 962 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler); 963 964 CmdArgs.push_back("-o"); 965 CmdArgs.push_back(Output.getFilename()); 966 967 for (const auto &II : Inputs) 968 CmdArgs.push_back(II.getFilename()); 969 970 if (Arg *A = Args.getLastArg(options::OPT_g_Flag, options::OPT_gN_Group, 971 options::OPT_gdwarf_2, options::OPT_gdwarf_3, 972 options::OPT_gdwarf_4, options::OPT_gdwarf_5, 973 options::OPT_gdwarf)) 974 if (!A->getOption().matches(options::OPT_g0)) { 975 Args.AddLastArg(CmdArgs, options::OPT_g_Flag); 976 977 unsigned DwarfVersion = getDwarfVersion(getToolChain(), Args); 978 CmdArgs.push_back(Args.MakeArgString("-gdwarf-" + Twine(DwarfVersion))); 979 } 980 981 const char *Exec = 982 Args.MakeArgString(getToolChain().GetProgramPath(DefaultAssembler)); 983 C.addCommand(std::make_unique<Command>(JA, *this, 984 ResponseFileSupport::AtFileCurCP(), 985 Exec, CmdArgs, Inputs, Output)); 986 987 // Handle the debug info splitting at object creation time if we're 988 // creating an object. 989 // TODO: Currently only works on linux with newer objcopy. 990 if (Args.hasArg(options::OPT_gsplit_dwarf) && 991 getToolChain().getTriple().isOSLinux()) 992 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output, 993 SplitDebugName(JA, Args, Inputs[0], Output)); 994 } 995 996 namespace { 997 // Filter to remove Multilibs that don't exist as a suffix to Path 998 class FilterNonExistent { 999 StringRef Base, File; 1000 llvm::vfs::FileSystem &VFS; 1001 1002 public: 1003 FilterNonExistent(StringRef Base, StringRef File, llvm::vfs::FileSystem &VFS) 1004 : Base(Base), File(File), VFS(VFS) {} 1005 bool operator()(const Multilib &M) { 1006 return !VFS.exists(Base + M.gccSuffix() + File); 1007 } 1008 }; 1009 } // end anonymous namespace 1010 1011 static bool isSoftFloatABI(const ArgList &Args) { 1012 Arg *A = Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float, 1013 options::OPT_mfloat_abi_EQ); 1014 if (!A) 1015 return false; 1016 1017 return A->getOption().matches(options::OPT_msoft_float) || 1018 (A->getOption().matches(options::OPT_mfloat_abi_EQ) && 1019 A->getValue() == StringRef("soft")); 1020 } 1021 1022 static bool isArmOrThumbArch(llvm::Triple::ArchType Arch) { 1023 return Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb; 1024 } 1025 1026 static bool isMipsEL(llvm::Triple::ArchType Arch) { 1027 return Arch == llvm::Triple::mipsel || Arch == llvm::Triple::mips64el; 1028 } 1029 1030 static bool isMips16(const ArgList &Args) { 1031 Arg *A = Args.getLastArg(options::OPT_mips16, options::OPT_mno_mips16); 1032 return A && A->getOption().matches(options::OPT_mips16); 1033 } 1034 1035 static bool isMicroMips(const ArgList &Args) { 1036 Arg *A = Args.getLastArg(options::OPT_mmicromips, options::OPT_mno_micromips); 1037 return A && A->getOption().matches(options::OPT_mmicromips); 1038 } 1039 1040 static bool isMSP430(llvm::Triple::ArchType Arch) { 1041 return Arch == llvm::Triple::msp430; 1042 } 1043 1044 static bool findMipsCsMultilibs(const Multilib::flags_list &Flags, 1045 FilterNonExistent &NonExistent, 1046 DetectedMultilibs &Result) { 1047 // Check for Code Sourcery toolchain multilibs 1048 MultilibSet CSMipsMultilibs; 1049 { 1050 auto MArchMips16 = MultilibBuilder("/mips16").flag("-m32").flag("-mips16"); 1051 1052 auto MArchMicroMips = 1053 MultilibBuilder("/micromips").flag("-m32").flag("-mmicromips"); 1054 1055 auto MArchDefault = MultilibBuilder("") 1056 .flag("-mips16", /*Disallow=*/true) 1057 .flag("-mmicromips", /*Disallow=*/true); 1058 1059 auto UCLibc = MultilibBuilder("/uclibc").flag("-muclibc"); 1060 1061 auto SoftFloat = MultilibBuilder("/soft-float").flag("-msoft-float"); 1062 1063 auto Nan2008 = MultilibBuilder("/nan2008").flag("-mnan=2008"); 1064 1065 auto DefaultFloat = MultilibBuilder("") 1066 .flag("-msoft-float", /*Disallow=*/true) 1067 .flag("-mnan=2008", /*Disallow=*/true); 1068 1069 auto BigEndian = 1070 MultilibBuilder("").flag("-EB").flag("-EL", /*Disallow=*/true); 1071 1072 auto LittleEndian = 1073 MultilibBuilder("/el").flag("-EL").flag("-EB", /*Disallow=*/true); 1074 1075 // Note that this one's osSuffix is "" 1076 auto MAbi64 = MultilibBuilder("") 1077 .gccSuffix("/64") 1078 .includeSuffix("/64") 1079 .flag("-mabi=n64") 1080 .flag("-mabi=n32", /*Disallow=*/true) 1081 .flag("-m32", /*Disallow=*/true); 1082 1083 CSMipsMultilibs = 1084 MultilibSetBuilder() 1085 .Either(MArchMips16, MArchMicroMips, MArchDefault) 1086 .Maybe(UCLibc) 1087 .Either(SoftFloat, Nan2008, DefaultFloat) 1088 .FilterOut("/micromips/nan2008") 1089 .FilterOut("/mips16/nan2008") 1090 .Either(BigEndian, LittleEndian) 1091 .Maybe(MAbi64) 1092 .FilterOut("/mips16.*/64") 1093 .FilterOut("/micromips.*/64") 1094 .makeMultilibSet() 1095 .FilterOut(NonExistent) 1096 .setIncludeDirsCallback([](const Multilib &M) { 1097 std::vector<std::string> Dirs({"/include"}); 1098 if (StringRef(M.includeSuffix()).starts_with("/uclibc")) 1099 Dirs.push_back( 1100 "/../../../../mips-linux-gnu/libc/uclibc/usr/include"); 1101 else 1102 Dirs.push_back("/../../../../mips-linux-gnu/libc/usr/include"); 1103 return Dirs; 1104 }); 1105 } 1106 1107 MultilibSet DebianMipsMultilibs; 1108 { 1109 MultilibBuilder MAbiN32 = 1110 MultilibBuilder().gccSuffix("/n32").includeSuffix("/n32").flag( 1111 "-mabi=n32"); 1112 1113 MultilibBuilder M64 = MultilibBuilder() 1114 .gccSuffix("/64") 1115 .includeSuffix("/64") 1116 .flag("-m64") 1117 .flag("-m32", /*Disallow=*/true) 1118 .flag("-mabi=n32", /*Disallow=*/true); 1119 1120 MultilibBuilder M32 = MultilibBuilder() 1121 .gccSuffix("/32") 1122 .flag("-m64", /*Disallow=*/true) 1123 .flag("-m32") 1124 .flag("-mabi=n32", /*Disallow=*/true); 1125 1126 DebianMipsMultilibs = MultilibSetBuilder() 1127 .Either(M32, M64, MAbiN32) 1128 .makeMultilibSet() 1129 .FilterOut(NonExistent); 1130 } 1131 1132 // Sort candidates. Toolchain that best meets the directories tree goes first. 1133 // Then select the first toolchains matches command line flags. 1134 MultilibSet *Candidates[] = {&CSMipsMultilibs, &DebianMipsMultilibs}; 1135 if (CSMipsMultilibs.size() < DebianMipsMultilibs.size()) 1136 std::iter_swap(Candidates, Candidates + 1); 1137 for (const MultilibSet *Candidate : Candidates) { 1138 if (Candidate->select(Flags, Result.SelectedMultilibs)) { 1139 if (Candidate == &DebianMipsMultilibs) 1140 Result.BiarchSibling = Multilib(); 1141 Result.Multilibs = *Candidate; 1142 return true; 1143 } 1144 } 1145 return false; 1146 } 1147 1148 static bool findMipsAndroidMultilibs(llvm::vfs::FileSystem &VFS, StringRef Path, 1149 const Multilib::flags_list &Flags, 1150 FilterNonExistent &NonExistent, 1151 DetectedMultilibs &Result) { 1152 1153 MultilibSet AndroidMipsMultilibs = 1154 MultilibSetBuilder() 1155 .Maybe(MultilibBuilder("/mips-r2", {}, {}).flag("-march=mips32r2")) 1156 .Maybe(MultilibBuilder("/mips-r6", {}, {}).flag("-march=mips32r6")) 1157 .makeMultilibSet() 1158 .FilterOut(NonExistent); 1159 1160 MultilibSet AndroidMipselMultilibs = 1161 MultilibSetBuilder() 1162 .Either(MultilibBuilder().flag("-march=mips32"), 1163 MultilibBuilder("/mips-r2", "", "/mips-r2") 1164 .flag("-march=mips32r2"), 1165 MultilibBuilder("/mips-r6", "", "/mips-r6") 1166 .flag("-march=mips32r6")) 1167 .makeMultilibSet() 1168 .FilterOut(NonExistent); 1169 1170 MultilibSet AndroidMips64elMultilibs = 1171 MultilibSetBuilder() 1172 .Either(MultilibBuilder().flag("-march=mips64r6"), 1173 MultilibBuilder("/32/mips-r1", "", "/mips-r1") 1174 .flag("-march=mips32"), 1175 MultilibBuilder("/32/mips-r2", "", "/mips-r2") 1176 .flag("-march=mips32r2"), 1177 MultilibBuilder("/32/mips-r6", "", "/mips-r6") 1178 .flag("-march=mips32r6")) 1179 .makeMultilibSet() 1180 .FilterOut(NonExistent); 1181 1182 MultilibSet *MS = &AndroidMipsMultilibs; 1183 if (VFS.exists(Path + "/mips-r6")) 1184 MS = &AndroidMipselMultilibs; 1185 else if (VFS.exists(Path + "/32")) 1186 MS = &AndroidMips64elMultilibs; 1187 if (MS->select(Flags, Result.SelectedMultilibs)) { 1188 Result.Multilibs = *MS; 1189 return true; 1190 } 1191 return false; 1192 } 1193 1194 static bool findMipsMuslMultilibs(const Multilib::flags_list &Flags, 1195 FilterNonExistent &NonExistent, 1196 DetectedMultilibs &Result) { 1197 // Musl toolchain multilibs 1198 MultilibSet MuslMipsMultilibs; 1199 { 1200 auto MArchMipsR2 = MultilibBuilder("") 1201 .osSuffix("/mips-r2-hard-musl") 1202 .flag("-EB") 1203 .flag("-EL", /*Disallow=*/true) 1204 .flag("-march=mips32r2"); 1205 1206 auto MArchMipselR2 = MultilibBuilder("/mipsel-r2-hard-musl") 1207 .flag("-EB", /*Disallow=*/true) 1208 .flag("-EL") 1209 .flag("-march=mips32r2"); 1210 1211 MuslMipsMultilibs = MultilibSetBuilder() 1212 .Either(MArchMipsR2, MArchMipselR2) 1213 .makeMultilibSet(); 1214 1215 // Specify the callback that computes the include directories. 1216 MuslMipsMultilibs.setIncludeDirsCallback([](const Multilib &M) { 1217 return std::vector<std::string>( 1218 {"/../sysroot" + M.osSuffix() + "/usr/include"}); 1219 }); 1220 } 1221 if (MuslMipsMultilibs.select(Flags, Result.SelectedMultilibs)) { 1222 Result.Multilibs = MuslMipsMultilibs; 1223 return true; 1224 } 1225 return false; 1226 } 1227 1228 static bool findMipsMtiMultilibs(const Multilib::flags_list &Flags, 1229 FilterNonExistent &NonExistent, 1230 DetectedMultilibs &Result) { 1231 // CodeScape MTI toolchain v1.2 and early. 1232 MultilibSet MtiMipsMultilibsV1; 1233 { 1234 auto MArchMips32 = MultilibBuilder("/mips32") 1235 .flag("-m32") 1236 .flag("-m64", /*Disallow=*/true) 1237 .flag("-mmicromips", /*Disallow=*/true) 1238 .flag("-march=mips32"); 1239 1240 auto MArchMicroMips = MultilibBuilder("/micromips") 1241 .flag("-m32") 1242 .flag("-m64", /*Disallow=*/true) 1243 .flag("-mmicromips"); 1244 1245 auto MArchMips64r2 = MultilibBuilder("/mips64r2") 1246 .flag("-m32", /*Disallow=*/true) 1247 .flag("-m64") 1248 .flag("-march=mips64r2"); 1249 1250 auto MArchMips64 = MultilibBuilder("/mips64") 1251 .flag("-m32", /*Disallow=*/true) 1252 .flag("-m64") 1253 .flag("-march=mips64r2", /*Disallow=*/true); 1254 1255 auto MArchDefault = MultilibBuilder("") 1256 .flag("-m32") 1257 .flag("-m64", /*Disallow=*/true) 1258 .flag("-mmicromips", /*Disallow=*/true) 1259 .flag("-march=mips32r2"); 1260 1261 auto Mips16 = MultilibBuilder("/mips16").flag("-mips16"); 1262 1263 auto UCLibc = MultilibBuilder("/uclibc").flag("-muclibc"); 1264 1265 auto MAbi64 = MultilibBuilder("/64") 1266 .flag("-mabi=n64") 1267 .flag("-mabi=n32", /*Disallow=*/true) 1268 .flag("-m32", /*Disallow=*/true); 1269 1270 auto BigEndian = 1271 MultilibBuilder("").flag("-EB").flag("-EL", /*Disallow=*/true); 1272 1273 auto LittleEndian = 1274 MultilibBuilder("/el").flag("-EL").flag("-EB", /*Disallow=*/true); 1275 1276 auto SoftFloat = MultilibBuilder("/sof").flag("-msoft-float"); 1277 1278 auto Nan2008 = MultilibBuilder("/nan2008").flag("-mnan=2008"); 1279 1280 MtiMipsMultilibsV1 = 1281 MultilibSetBuilder() 1282 .Either(MArchMips32, MArchMicroMips, MArchMips64r2, MArchMips64, 1283 MArchDefault) 1284 .Maybe(UCLibc) 1285 .Maybe(Mips16) 1286 .FilterOut("/mips64/mips16") 1287 .FilterOut("/mips64r2/mips16") 1288 .FilterOut("/micromips/mips16") 1289 .Maybe(MAbi64) 1290 .FilterOut("/micromips/64") 1291 .FilterOut("/mips32/64") 1292 .FilterOut("^/64") 1293 .FilterOut("/mips16/64") 1294 .Either(BigEndian, LittleEndian) 1295 .Maybe(SoftFloat) 1296 .Maybe(Nan2008) 1297 .FilterOut(".*sof/nan2008") 1298 .makeMultilibSet() 1299 .FilterOut(NonExistent) 1300 .setIncludeDirsCallback([](const Multilib &M) { 1301 std::vector<std::string> Dirs({"/include"}); 1302 if (StringRef(M.includeSuffix()).starts_with("/uclibc")) 1303 Dirs.push_back("/../../../../sysroot/uclibc/usr/include"); 1304 else 1305 Dirs.push_back("/../../../../sysroot/usr/include"); 1306 return Dirs; 1307 }); 1308 } 1309 1310 // CodeScape IMG toolchain starting from v1.3. 1311 MultilibSet MtiMipsMultilibsV2; 1312 { 1313 auto BeHard = MultilibBuilder("/mips-r2-hard") 1314 .flag("-EB") 1315 .flag("-msoft-float", /*Disallow=*/true) 1316 .flag("-mnan=2008", /*Disallow=*/true) 1317 .flag("-muclibc", /*Disallow=*/true); 1318 auto BeSoft = MultilibBuilder("/mips-r2-soft") 1319 .flag("-EB") 1320 .flag("-msoft-float") 1321 .flag("-mnan=2008", /*Disallow=*/true); 1322 auto ElHard = MultilibBuilder("/mipsel-r2-hard") 1323 .flag("-EL") 1324 .flag("-msoft-float", /*Disallow=*/true) 1325 .flag("-mnan=2008", /*Disallow=*/true) 1326 .flag("-muclibc", /*Disallow=*/true); 1327 auto ElSoft = MultilibBuilder("/mipsel-r2-soft") 1328 .flag("-EL") 1329 .flag("-msoft-float") 1330 .flag("-mnan=2008", /*Disallow=*/true) 1331 .flag("-mmicromips", /*Disallow=*/true); 1332 auto BeHardNan = MultilibBuilder("/mips-r2-hard-nan2008") 1333 .flag("-EB") 1334 .flag("-msoft-float", /*Disallow=*/true) 1335 .flag("-mnan=2008") 1336 .flag("-muclibc", /*Disallow=*/true); 1337 auto ElHardNan = MultilibBuilder("/mipsel-r2-hard-nan2008") 1338 .flag("-EL") 1339 .flag("-msoft-float", /*Disallow=*/true) 1340 .flag("-mnan=2008") 1341 .flag("-muclibc", /*Disallow=*/true) 1342 .flag("-mmicromips", /*Disallow=*/true); 1343 auto BeHardNanUclibc = MultilibBuilder("/mips-r2-hard-nan2008-uclibc") 1344 .flag("-EB") 1345 .flag("-msoft-float", /*Disallow=*/true) 1346 .flag("-mnan=2008") 1347 .flag("-muclibc"); 1348 auto ElHardNanUclibc = MultilibBuilder("/mipsel-r2-hard-nan2008-uclibc") 1349 .flag("-EL") 1350 .flag("-msoft-float", /*Disallow=*/true) 1351 .flag("-mnan=2008") 1352 .flag("-muclibc"); 1353 auto BeHardUclibc = MultilibBuilder("/mips-r2-hard-uclibc") 1354 .flag("-EB") 1355 .flag("-msoft-float", /*Disallow=*/true) 1356 .flag("-mnan=2008", /*Disallow=*/true) 1357 .flag("-muclibc"); 1358 auto ElHardUclibc = MultilibBuilder("/mipsel-r2-hard-uclibc") 1359 .flag("-EL") 1360 .flag("-msoft-float", /*Disallow=*/true) 1361 .flag("-mnan=2008", /*Disallow=*/true) 1362 .flag("-muclibc"); 1363 auto ElMicroHardNan = MultilibBuilder("/micromipsel-r2-hard-nan2008") 1364 .flag("-EL") 1365 .flag("-msoft-float", /*Disallow=*/true) 1366 .flag("-mnan=2008") 1367 .flag("-mmicromips"); 1368 auto ElMicroSoft = MultilibBuilder("/micromipsel-r2-soft") 1369 .flag("-EL") 1370 .flag("-msoft-float") 1371 .flag("-mnan=2008", /*Disallow=*/true) 1372 .flag("-mmicromips"); 1373 1374 auto O32 = MultilibBuilder("/lib") 1375 .osSuffix("") 1376 .flag("-mabi=n32", /*Disallow=*/true) 1377 .flag("-mabi=n64", /*Disallow=*/true); 1378 auto N32 = MultilibBuilder("/lib32") 1379 .osSuffix("") 1380 .flag("-mabi=n32") 1381 .flag("-mabi=n64", /*Disallow=*/true); 1382 auto N64 = MultilibBuilder("/lib64") 1383 .osSuffix("") 1384 .flag("-mabi=n32", /*Disallow=*/true) 1385 .flag("-mabi=n64"); 1386 1387 MtiMipsMultilibsV2 = 1388 MultilibSetBuilder() 1389 .Either({BeHard, BeSoft, ElHard, ElSoft, BeHardNan, ElHardNan, 1390 BeHardNanUclibc, ElHardNanUclibc, BeHardUclibc, 1391 ElHardUclibc, ElMicroHardNan, ElMicroSoft}) 1392 .Either(O32, N32, N64) 1393 .makeMultilibSet() 1394 .FilterOut(NonExistent) 1395 .setIncludeDirsCallback([](const Multilib &M) { 1396 return std::vector<std::string>({"/../../../../sysroot" + 1397 M.includeSuffix() + 1398 "/../usr/include"}); 1399 }) 1400 .setFilePathsCallback([](const Multilib &M) { 1401 return std::vector<std::string>( 1402 {"/../../../../mips-mti-linux-gnu/lib" + M.gccSuffix()}); 1403 }); 1404 } 1405 for (auto *Candidate : {&MtiMipsMultilibsV1, &MtiMipsMultilibsV2}) { 1406 if (Candidate->select(Flags, Result.SelectedMultilibs)) { 1407 Result.Multilibs = *Candidate; 1408 return true; 1409 } 1410 } 1411 return false; 1412 } 1413 1414 static bool findMipsImgMultilibs(const Multilib::flags_list &Flags, 1415 FilterNonExistent &NonExistent, 1416 DetectedMultilibs &Result) { 1417 // CodeScape IMG toolchain v1.2 and early. 1418 MultilibSet ImgMultilibsV1; 1419 { 1420 auto Mips64r6 = MultilibBuilder("/mips64r6") 1421 .flag("-m64") 1422 .flag("-m32", /*Disallow=*/true); 1423 1424 auto LittleEndian = 1425 MultilibBuilder("/el").flag("-EL").flag("-EB", /*Disallow=*/true); 1426 1427 auto MAbi64 = MultilibBuilder("/64") 1428 .flag("-mabi=n64") 1429 .flag("-mabi=n32", /*Disallow=*/true) 1430 .flag("-m32", /*Disallow=*/true); 1431 1432 ImgMultilibsV1 = 1433 MultilibSetBuilder() 1434 .Maybe(Mips64r6) 1435 .Maybe(MAbi64) 1436 .Maybe(LittleEndian) 1437 .makeMultilibSet() 1438 .FilterOut(NonExistent) 1439 .setIncludeDirsCallback([](const Multilib &M) { 1440 return std::vector<std::string>( 1441 {"/include", "/../../../../sysroot/usr/include"}); 1442 }); 1443 } 1444 1445 // CodeScape IMG toolchain starting from v1.3. 1446 MultilibSet ImgMultilibsV2; 1447 { 1448 auto BeHard = MultilibBuilder("/mips-r6-hard") 1449 .flag("-EB") 1450 .flag("-msoft-float", /*Disallow=*/true) 1451 .flag("-mmicromips", /*Disallow=*/true); 1452 auto BeSoft = MultilibBuilder("/mips-r6-soft") 1453 .flag("-EB") 1454 .flag("-msoft-float") 1455 .flag("-mmicromips", /*Disallow=*/true); 1456 auto ElHard = MultilibBuilder("/mipsel-r6-hard") 1457 .flag("-EL") 1458 .flag("-msoft-float", /*Disallow=*/true) 1459 .flag("-mmicromips", /*Disallow=*/true); 1460 auto ElSoft = MultilibBuilder("/mipsel-r6-soft") 1461 .flag("-EL") 1462 .flag("-msoft-float") 1463 .flag("-mmicromips", /*Disallow=*/true); 1464 auto BeMicroHard = MultilibBuilder("/micromips-r6-hard") 1465 .flag("-EB") 1466 .flag("-msoft-float", /*Disallow=*/true) 1467 .flag("-mmicromips"); 1468 auto BeMicroSoft = MultilibBuilder("/micromips-r6-soft") 1469 .flag("-EB") 1470 .flag("-msoft-float") 1471 .flag("-mmicromips"); 1472 auto ElMicroHard = MultilibBuilder("/micromipsel-r6-hard") 1473 .flag("-EL") 1474 .flag("-msoft-float", /*Disallow=*/true) 1475 .flag("-mmicromips"); 1476 auto ElMicroSoft = MultilibBuilder("/micromipsel-r6-soft") 1477 .flag("-EL") 1478 .flag("-msoft-float") 1479 .flag("-mmicromips"); 1480 1481 auto O32 = MultilibBuilder("/lib") 1482 .osSuffix("") 1483 .flag("-mabi=n32", /*Disallow=*/true) 1484 .flag("-mabi=n64", /*Disallow=*/true); 1485 auto N32 = MultilibBuilder("/lib32") 1486 .osSuffix("") 1487 .flag("-mabi=n32") 1488 .flag("-mabi=n64", /*Disallow=*/true); 1489 auto N64 = MultilibBuilder("/lib64") 1490 .osSuffix("") 1491 .flag("-mabi=n32", /*Disallow=*/true) 1492 .flag("-mabi=n64"); 1493 1494 ImgMultilibsV2 = 1495 MultilibSetBuilder() 1496 .Either({BeHard, BeSoft, ElHard, ElSoft, BeMicroHard, BeMicroSoft, 1497 ElMicroHard, ElMicroSoft}) 1498 .Either(O32, N32, N64) 1499 .makeMultilibSet() 1500 .FilterOut(NonExistent) 1501 .setIncludeDirsCallback([](const Multilib &M) { 1502 return std::vector<std::string>({"/../../../../sysroot" + 1503 M.includeSuffix() + 1504 "/../usr/include"}); 1505 }) 1506 .setFilePathsCallback([](const Multilib &M) { 1507 return std::vector<std::string>( 1508 {"/../../../../mips-img-linux-gnu/lib" + M.gccSuffix()}); 1509 }); 1510 } 1511 for (auto *Candidate : {&ImgMultilibsV1, &ImgMultilibsV2}) { 1512 if (Candidate->select(Flags, Result.SelectedMultilibs)) { 1513 Result.Multilibs = *Candidate; 1514 return true; 1515 } 1516 } 1517 return false; 1518 } 1519 1520 bool clang::driver::findMIPSMultilibs(const Driver &D, 1521 const llvm::Triple &TargetTriple, 1522 StringRef Path, const ArgList &Args, 1523 DetectedMultilibs &Result) { 1524 FilterNonExistent NonExistent(Path, "/crtbegin.o", D.getVFS()); 1525 1526 StringRef CPUName; 1527 StringRef ABIName; 1528 tools::mips::getMipsCPUAndABI(Args, TargetTriple, CPUName, ABIName); 1529 1530 llvm::Triple::ArchType TargetArch = TargetTriple.getArch(); 1531 1532 Multilib::flags_list Flags; 1533 addMultilibFlag(TargetTriple.isMIPS32(), "-m32", Flags); 1534 addMultilibFlag(TargetTriple.isMIPS64(), "-m64", Flags); 1535 addMultilibFlag(isMips16(Args), "-mips16", Flags); 1536 addMultilibFlag(CPUName == "mips32", "-march=mips32", Flags); 1537 addMultilibFlag(CPUName == "mips32r2" || CPUName == "mips32r3" || 1538 CPUName == "mips32r5" || CPUName == "p5600", 1539 "-march=mips32r2", Flags); 1540 addMultilibFlag(CPUName == "mips32r6", "-march=mips32r6", Flags); 1541 addMultilibFlag(CPUName == "mips64", "-march=mips64", Flags); 1542 addMultilibFlag(CPUName == "mips64r2" || CPUName == "mips64r3" || 1543 CPUName == "mips64r5" || CPUName == "octeon" || 1544 CPUName == "octeon+", 1545 "-march=mips64r2", Flags); 1546 addMultilibFlag(CPUName == "mips64r6", "-march=mips64r6", Flags); 1547 addMultilibFlag(isMicroMips(Args), "-mmicromips", Flags); 1548 addMultilibFlag(tools::mips::isUCLibc(Args), "-muclibc", Flags); 1549 addMultilibFlag(tools::mips::isNaN2008(D, Args, TargetTriple), "-mnan=2008", 1550 Flags); 1551 addMultilibFlag(ABIName == "n32", "-mabi=n32", Flags); 1552 addMultilibFlag(ABIName == "n64", "-mabi=n64", Flags); 1553 addMultilibFlag(isSoftFloatABI(Args), "-msoft-float", Flags); 1554 addMultilibFlag(!isSoftFloatABI(Args), "-mhard-float", Flags); 1555 addMultilibFlag(isMipsEL(TargetArch), "-EL", Flags); 1556 addMultilibFlag(!isMipsEL(TargetArch), "-EB", Flags); 1557 1558 if (TargetTriple.isAndroid()) 1559 return findMipsAndroidMultilibs(D.getVFS(), Path, Flags, NonExistent, 1560 Result); 1561 1562 if (TargetTriple.getVendor() == llvm::Triple::MipsTechnologies && 1563 TargetTriple.getOS() == llvm::Triple::Linux && 1564 TargetTriple.getEnvironment() == llvm::Triple::UnknownEnvironment) 1565 return findMipsMuslMultilibs(Flags, NonExistent, Result); 1566 1567 if (TargetTriple.getVendor() == llvm::Triple::MipsTechnologies && 1568 TargetTriple.getOS() == llvm::Triple::Linux && 1569 TargetTriple.isGNUEnvironment()) 1570 return findMipsMtiMultilibs(Flags, NonExistent, Result); 1571 1572 if (TargetTriple.getVendor() == llvm::Triple::ImaginationTechnologies && 1573 TargetTriple.getOS() == llvm::Triple::Linux && 1574 TargetTriple.isGNUEnvironment()) 1575 return findMipsImgMultilibs(Flags, NonExistent, Result); 1576 1577 if (findMipsCsMultilibs(Flags, NonExistent, Result)) 1578 return true; 1579 1580 // Fallback to the regular toolchain-tree structure. 1581 Multilib Default; 1582 Result.Multilibs.push_back(Default); 1583 Result.Multilibs.FilterOut(NonExistent); 1584 1585 if (Result.Multilibs.select(Flags, Result.SelectedMultilibs)) { 1586 Result.BiarchSibling = Multilib(); 1587 return true; 1588 } 1589 1590 return false; 1591 } 1592 1593 static void findAndroidArmMultilibs(const Driver &D, 1594 const llvm::Triple &TargetTriple, 1595 StringRef Path, const ArgList &Args, 1596 DetectedMultilibs &Result) { 1597 // Find multilibs with subdirectories like armv7-a, thumb, armv7-a/thumb. 1598 FilterNonExistent NonExistent(Path, "/crtbegin.o", D.getVFS()); 1599 MultilibBuilder ArmV7Multilib = MultilibBuilder("/armv7-a") 1600 .flag("-march=armv7-a") 1601 .flag("-mthumb", /*Disallow=*/true); 1602 MultilibBuilder ThumbMultilib = MultilibBuilder("/thumb") 1603 .flag("-march=armv7-a", /*Disallow=*/true) 1604 .flag("-mthumb"); 1605 MultilibBuilder ArmV7ThumbMultilib = 1606 MultilibBuilder("/armv7-a/thumb").flag("-march=armv7-a").flag("-mthumb"); 1607 MultilibBuilder DefaultMultilib = 1608 MultilibBuilder("") 1609 .flag("-march=armv7-a", /*Disallow=*/true) 1610 .flag("-mthumb", /*Disallow=*/true); 1611 MultilibSet AndroidArmMultilibs = 1612 MultilibSetBuilder() 1613 .Either(ThumbMultilib, ArmV7Multilib, ArmV7ThumbMultilib, 1614 DefaultMultilib) 1615 .makeMultilibSet() 1616 .FilterOut(NonExistent); 1617 1618 Multilib::flags_list Flags; 1619 llvm::StringRef Arch = Args.getLastArgValue(options::OPT_march_EQ); 1620 bool IsArmArch = TargetTriple.getArch() == llvm::Triple::arm; 1621 bool IsThumbArch = TargetTriple.getArch() == llvm::Triple::thumb; 1622 bool IsV7SubArch = TargetTriple.getSubArch() == llvm::Triple::ARMSubArch_v7; 1623 bool IsThumbMode = IsThumbArch || 1624 Args.hasFlag(options::OPT_mthumb, options::OPT_mno_thumb, false) || 1625 (IsArmArch && llvm::ARM::parseArchISA(Arch) == llvm::ARM::ISAKind::THUMB); 1626 bool IsArmV7Mode = (IsArmArch || IsThumbArch) && 1627 (llvm::ARM::parseArchVersion(Arch) == 7 || 1628 (IsArmArch && Arch == "" && IsV7SubArch)); 1629 addMultilibFlag(IsArmV7Mode, "-march=armv7-a", Flags); 1630 addMultilibFlag(IsThumbMode, "-mthumb", Flags); 1631 1632 if (AndroidArmMultilibs.select(Flags, Result.SelectedMultilibs)) 1633 Result.Multilibs = AndroidArmMultilibs; 1634 } 1635 1636 static bool findMSP430Multilibs(const Driver &D, 1637 const llvm::Triple &TargetTriple, 1638 StringRef Path, const ArgList &Args, 1639 DetectedMultilibs &Result) { 1640 FilterNonExistent NonExistent(Path, "/crtbegin.o", D.getVFS()); 1641 MultilibBuilder WithoutExceptions = 1642 MultilibBuilder("/430").flag("-exceptions", /*Disallow=*/true); 1643 MultilibBuilder WithExceptions = 1644 MultilibBuilder("/430/exceptions").flag("-exceptions"); 1645 1646 // FIXME: when clang starts to support msp430x ISA additional logic 1647 // to select between multilib must be implemented 1648 // MultilibBuilder MSP430xMultilib = MultilibBuilder("/large"); 1649 1650 Result.Multilibs.push_back(WithoutExceptions.makeMultilib()); 1651 Result.Multilibs.push_back(WithExceptions.makeMultilib()); 1652 Result.Multilibs.FilterOut(NonExistent); 1653 1654 Multilib::flags_list Flags; 1655 addMultilibFlag(Args.hasFlag(options::OPT_fexceptions, 1656 options::OPT_fno_exceptions, false), 1657 "-exceptions", Flags); 1658 if (Result.Multilibs.select(Flags, Result.SelectedMultilibs)) 1659 return true; 1660 1661 return false; 1662 } 1663 1664 static void findCSKYMultilibs(const Driver &D, const llvm::Triple &TargetTriple, 1665 StringRef Path, const ArgList &Args, 1666 DetectedMultilibs &Result) { 1667 FilterNonExistent NonExistent(Path, "/crtbegin.o", D.getVFS()); 1668 1669 tools::csky::FloatABI TheFloatABI = tools::csky::getCSKYFloatABI(D, Args); 1670 std::optional<llvm::StringRef> Res = 1671 tools::csky::getCSKYArchName(D, Args, TargetTriple); 1672 1673 if (!Res) 1674 return; 1675 auto ARCHName = *Res; 1676 1677 Multilib::flags_list Flags; 1678 addMultilibFlag(TheFloatABI == tools::csky::FloatABI::Hard, "-hard-fp", 1679 Flags); 1680 addMultilibFlag(TheFloatABI == tools::csky::FloatABI::SoftFP, "-soft-fp", 1681 Flags); 1682 addMultilibFlag(TheFloatABI == tools::csky::FloatABI::Soft, "-soft", Flags); 1683 addMultilibFlag(ARCHName == "ck801", "-march=ck801", Flags); 1684 addMultilibFlag(ARCHName == "ck802", "-march=ck802", Flags); 1685 addMultilibFlag(ARCHName == "ck803", "-march=ck803", Flags); 1686 addMultilibFlag(ARCHName == "ck804", "-march=ck804", Flags); 1687 addMultilibFlag(ARCHName == "ck805", "-march=ck805", Flags); 1688 addMultilibFlag(ARCHName == "ck807", "-march=ck807", Flags); 1689 addMultilibFlag(ARCHName == "ck810", "-march=ck810", Flags); 1690 addMultilibFlag(ARCHName == "ck810v", "-march=ck810v", Flags); 1691 addMultilibFlag(ARCHName == "ck860", "-march=ck860", Flags); 1692 addMultilibFlag(ARCHName == "ck860v", "-march=ck860v", Flags); 1693 1694 bool isBigEndian = false; 1695 if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian, 1696 options::OPT_mbig_endian)) 1697 isBigEndian = !A->getOption().matches(options::OPT_mlittle_endian); 1698 addMultilibFlag(isBigEndian, "-EB", Flags); 1699 1700 auto HardFloat = MultilibBuilder("/hard-fp").flag("-hard-fp"); 1701 auto SoftFpFloat = MultilibBuilder("/soft-fp").flag("-soft-fp"); 1702 auto SoftFloat = MultilibBuilder("").flag("-soft"); 1703 auto Arch801 = MultilibBuilder("/ck801").flag("-march=ck801"); 1704 auto Arch802 = MultilibBuilder("/ck802").flag("-march=ck802"); 1705 auto Arch803 = MultilibBuilder("/ck803").flag("-march=ck803"); 1706 // CK804 use the same library as CK803 1707 auto Arch804 = MultilibBuilder("/ck803").flag("-march=ck804"); 1708 auto Arch805 = MultilibBuilder("/ck805").flag("-march=ck805"); 1709 auto Arch807 = MultilibBuilder("/ck807").flag("-march=ck807"); 1710 auto Arch810 = MultilibBuilder("").flag("-march=ck810"); 1711 auto Arch810v = MultilibBuilder("/ck810v").flag("-march=ck810v"); 1712 auto Arch860 = MultilibBuilder("/ck860").flag("-march=ck860"); 1713 auto Arch860v = MultilibBuilder("/ck860v").flag("-march=ck860v"); 1714 auto BigEndian = MultilibBuilder("/big").flag("-EB"); 1715 1716 MultilibSet CSKYMultilibs = 1717 MultilibSetBuilder() 1718 .Maybe(BigEndian) 1719 .Either({Arch801, Arch802, Arch803, Arch804, Arch805, Arch807, 1720 Arch810, Arch810v, Arch860, Arch860v}) 1721 .Either(HardFloat, SoftFpFloat, SoftFloat) 1722 .makeMultilibSet() 1723 .FilterOut(NonExistent); 1724 1725 if (CSKYMultilibs.select(Flags, Result.SelectedMultilibs)) 1726 Result.Multilibs = CSKYMultilibs; 1727 } 1728 1729 /// Extend the multi-lib re-use selection mechanism for RISC-V. 1730 /// This function will try to re-use multi-lib if they are compatible. 1731 /// Definition of compatible: 1732 /// - ABI must be the same. 1733 /// - multi-lib is a subset of current arch, e.g. multi-lib=march=rv32im 1734 /// is a subset of march=rv32imc. 1735 /// - march that contains atomic extension can't reuse multi-lib that 1736 /// doesn't have atomic, vice versa. e.g. multi-lib=march=rv32im and 1737 /// march=rv32ima are not compatible, because software and hardware 1738 /// atomic operation can't work together correctly. 1739 static bool 1740 selectRISCVMultilib(const MultilibSet &RISCVMultilibSet, StringRef Arch, 1741 const Multilib::flags_list &Flags, 1742 llvm::SmallVectorImpl<Multilib> &SelectedMultilibs) { 1743 // Try to find the perfect matching multi-lib first. 1744 if (RISCVMultilibSet.select(Flags, SelectedMultilibs)) 1745 return true; 1746 1747 Multilib::flags_list NewFlags; 1748 std::vector<MultilibBuilder> NewMultilibs; 1749 1750 llvm::Expected<std::unique_ptr<llvm::RISCVISAInfo>> ParseResult = 1751 llvm::RISCVISAInfo::parseArchString( 1752 Arch, /*EnableExperimentalExtension=*/true, 1753 /*ExperimentalExtensionVersionCheck=*/false); 1754 // Ignore any error here, we assume it will be handled in another place. 1755 if (llvm::errorToBool(ParseResult.takeError())) 1756 return false; 1757 1758 auto &ISAInfo = *ParseResult; 1759 1760 addMultilibFlag(ISAInfo->getXLen() == 32, "-m32", NewFlags); 1761 addMultilibFlag(ISAInfo->getXLen() == 64, "-m64", NewFlags); 1762 1763 // Collect all flags except march=* 1764 for (StringRef Flag : Flags) { 1765 if (Flag.starts_with("!march=") || Flag.starts_with("-march=")) 1766 continue; 1767 1768 NewFlags.push_back(Flag.str()); 1769 } 1770 1771 llvm::StringSet<> AllArchExts; 1772 // Reconstruct multi-lib list, and break march option into separated 1773 // extension. e.g. march=rv32im -> +i +m 1774 for (const auto &M : RISCVMultilibSet) { 1775 bool Skip = false; 1776 1777 MultilibBuilder NewMultilib = 1778 MultilibBuilder(M.gccSuffix(), M.osSuffix(), M.includeSuffix()); 1779 for (StringRef Flag : M.flags()) { 1780 // Add back all flags except -march. 1781 if (!Flag.consume_front("-march=")) { 1782 NewMultilib.flag(Flag); 1783 continue; 1784 } 1785 1786 // Break down -march into individual extension. 1787 llvm::Expected<std::unique_ptr<llvm::RISCVISAInfo>> MLConfigParseResult = 1788 llvm::RISCVISAInfo::parseArchString( 1789 Flag, /*EnableExperimentalExtension=*/true, 1790 /*ExperimentalExtensionVersionCheck=*/false); 1791 // Ignore any error here, we assume it will handled in another place. 1792 if (llvm::errorToBool(MLConfigParseResult.takeError())) { 1793 // We might get a parsing error if rv32e in the list, we could just skip 1794 // that and process the rest of multi-lib configs. 1795 Skip = true; 1796 continue; 1797 } 1798 auto &MLConfigISAInfo = *MLConfigParseResult; 1799 1800 for (auto &MLConfigArchExt : MLConfigISAInfo->getExtensions()) { 1801 auto ExtName = MLConfigArchExt.first; 1802 NewMultilib.flag(Twine("-", ExtName).str()); 1803 1804 if (AllArchExts.insert(ExtName).second) { 1805 addMultilibFlag(ISAInfo->hasExtension(ExtName), 1806 Twine("-", ExtName).str(), NewFlags); 1807 } 1808 } 1809 1810 // Check the XLEN explicitly. 1811 if (MLConfigISAInfo->getXLen() == 32) { 1812 NewMultilib.flag("-m32"); 1813 NewMultilib.flag("-m64", /*Disallow*/ true); 1814 } else { 1815 NewMultilib.flag("-m32", /*Disallow*/ true); 1816 NewMultilib.flag("-m64"); 1817 } 1818 1819 // Atomic extension must be explicitly checked, soft and hard atomic 1820 // operation never co-work correctly. 1821 if (!MLConfigISAInfo->hasExtension("a")) 1822 NewMultilib.flag("-a", /*Disallow*/ true); 1823 } 1824 1825 if (Skip) 1826 continue; 1827 1828 NewMultilibs.emplace_back(NewMultilib); 1829 } 1830 1831 // Build an internal used only multi-lib list, used for checking any 1832 // compatible multi-lib. 1833 MultilibSet NewRISCVMultilibs = 1834 MultilibSetBuilder().Either(NewMultilibs).makeMultilibSet(); 1835 1836 if (NewRISCVMultilibs.select(NewFlags, SelectedMultilibs)) 1837 for (const Multilib &NewSelectedM : SelectedMultilibs) 1838 for (const auto &M : RISCVMultilibSet) 1839 // Look up the corresponding multi-lib entry in original multi-lib set. 1840 if (M.gccSuffix() == NewSelectedM.gccSuffix()) 1841 return true; 1842 1843 return false; 1844 } 1845 1846 static void findRISCVBareMetalMultilibs(const Driver &D, 1847 const llvm::Triple &TargetTriple, 1848 StringRef Path, const ArgList &Args, 1849 DetectedMultilibs &Result) { 1850 FilterNonExistent NonExistent(Path, "/crtbegin.o", D.getVFS()); 1851 struct RiscvMultilib { 1852 StringRef march; 1853 StringRef mabi; 1854 }; 1855 // currently only support the set of multilibs like riscv-gnu-toolchain does. 1856 // TODO: support MULTILIB_REUSE 1857 constexpr RiscvMultilib RISCVMultilibSet[] = { 1858 {"rv32i", "ilp32"}, {"rv32im", "ilp32"}, {"rv32iac", "ilp32"}, 1859 {"rv32imac", "ilp32"}, {"rv32imafc", "ilp32f"}, {"rv64imac", "lp64"}, 1860 {"rv64imafdc", "lp64d"}}; 1861 1862 std::vector<MultilibBuilder> Ms; 1863 for (auto Element : RISCVMultilibSet) { 1864 // multilib path rule is ${march}/${mabi} 1865 Ms.emplace_back( 1866 MultilibBuilder( 1867 (Twine(Element.march) + "/" + Twine(Element.mabi)).str()) 1868 .flag(Twine("-march=", Element.march).str()) 1869 .flag(Twine("-mabi=", Element.mabi).str())); 1870 } 1871 MultilibSet RISCVMultilibs = 1872 MultilibSetBuilder() 1873 .Either(Ms) 1874 .makeMultilibSet() 1875 .FilterOut(NonExistent) 1876 .setFilePathsCallback([](const Multilib &M) { 1877 return std::vector<std::string>( 1878 {M.gccSuffix(), 1879 "/../../../../riscv64-unknown-elf/lib" + M.gccSuffix(), 1880 "/../../../../riscv32-unknown-elf/lib" + M.gccSuffix()}); 1881 }); 1882 1883 Multilib::flags_list Flags; 1884 llvm::StringSet<> Added_ABIs; 1885 StringRef ABIName = tools::riscv::getRISCVABI(Args, TargetTriple); 1886 std::string MArch = tools::riscv::getRISCVArch(Args, TargetTriple); 1887 for (auto Element : RISCVMultilibSet) { 1888 addMultilibFlag(MArch == Element.march, 1889 Twine("-march=", Element.march).str().c_str(), Flags); 1890 if (!Added_ABIs.count(Element.mabi)) { 1891 Added_ABIs.insert(Element.mabi); 1892 addMultilibFlag(ABIName == Element.mabi, 1893 Twine("-mabi=", Element.mabi).str().c_str(), Flags); 1894 } 1895 } 1896 1897 if (selectRISCVMultilib(RISCVMultilibs, MArch, Flags, 1898 Result.SelectedMultilibs)) 1899 Result.Multilibs = RISCVMultilibs; 1900 } 1901 1902 static void findRISCVMultilibs(const Driver &D, 1903 const llvm::Triple &TargetTriple, StringRef Path, 1904 const ArgList &Args, DetectedMultilibs &Result) { 1905 if (TargetTriple.getOS() == llvm::Triple::UnknownOS) 1906 return findRISCVBareMetalMultilibs(D, TargetTriple, Path, Args, Result); 1907 1908 FilterNonExistent NonExistent(Path, "/crtbegin.o", D.getVFS()); 1909 MultilibBuilder Ilp32 = 1910 MultilibBuilder("lib32/ilp32").flag("-m32").flag("-mabi=ilp32"); 1911 MultilibBuilder Ilp32f = 1912 MultilibBuilder("lib32/ilp32f").flag("-m32").flag("-mabi=ilp32f"); 1913 MultilibBuilder Ilp32d = 1914 MultilibBuilder("lib32/ilp32d").flag("-m32").flag("-mabi=ilp32d"); 1915 MultilibBuilder Lp64 = 1916 MultilibBuilder("lib64/lp64").flag("-m64").flag("-mabi=lp64"); 1917 MultilibBuilder Lp64f = 1918 MultilibBuilder("lib64/lp64f").flag("-m64").flag("-mabi=lp64f"); 1919 MultilibBuilder Lp64d = 1920 MultilibBuilder("lib64/lp64d").flag("-m64").flag("-mabi=lp64d"); 1921 MultilibSet RISCVMultilibs = 1922 MultilibSetBuilder() 1923 .Either({Ilp32, Ilp32f, Ilp32d, Lp64, Lp64f, Lp64d}) 1924 .makeMultilibSet() 1925 .FilterOut(NonExistent); 1926 1927 Multilib::flags_list Flags; 1928 bool IsRV64 = TargetTriple.getArch() == llvm::Triple::riscv64; 1929 StringRef ABIName = tools::riscv::getRISCVABI(Args, TargetTriple); 1930 1931 addMultilibFlag(!IsRV64, "-m32", Flags); 1932 addMultilibFlag(IsRV64, "-m64", Flags); 1933 addMultilibFlag(ABIName == "ilp32", "-mabi=ilp32", Flags); 1934 addMultilibFlag(ABIName == "ilp32f", "-mabi=ilp32f", Flags); 1935 addMultilibFlag(ABIName == "ilp32d", "-mabi=ilp32d", Flags); 1936 addMultilibFlag(ABIName == "lp64", "-mabi=lp64", Flags); 1937 addMultilibFlag(ABIName == "lp64f", "-mabi=lp64f", Flags); 1938 addMultilibFlag(ABIName == "lp64d", "-mabi=lp64d", Flags); 1939 1940 if (RISCVMultilibs.select(Flags, Result.SelectedMultilibs)) 1941 Result.Multilibs = RISCVMultilibs; 1942 } 1943 1944 static bool findBiarchMultilibs(const Driver &D, 1945 const llvm::Triple &TargetTriple, 1946 StringRef Path, const ArgList &Args, 1947 bool NeedsBiarchSuffix, 1948 DetectedMultilibs &Result) { 1949 MultilibBuilder DefaultBuilder; 1950 1951 // Some versions of SUSE and Fedora on ppc64 put 32-bit libs 1952 // in what would normally be GCCInstallPath and put the 64-bit 1953 // libs in a subdirectory named 64. The simple logic we follow is that 1954 // *if* there is a subdirectory of the right name with crtbegin.o in it, 1955 // we use that. If not, and if not a biarch triple alias, we look for 1956 // crtbegin.o without the subdirectory. 1957 1958 StringRef Suff64 = "/64"; 1959 // Solaris uses platform-specific suffixes instead of /64. 1960 if (TargetTriple.isOSSolaris()) { 1961 switch (TargetTriple.getArch()) { 1962 case llvm::Triple::x86: 1963 case llvm::Triple::x86_64: 1964 Suff64 = "/amd64"; 1965 break; 1966 case llvm::Triple::sparc: 1967 case llvm::Triple::sparcv9: 1968 Suff64 = "/sparcv9"; 1969 break; 1970 default: 1971 break; 1972 } 1973 } 1974 1975 Multilib Alt64 = MultilibBuilder() 1976 .gccSuffix(Suff64) 1977 .includeSuffix(Suff64) 1978 .flag("-m32", /*Disallow=*/true) 1979 .flag("-m64") 1980 .flag("-mx32", /*Disallow=*/true) 1981 .makeMultilib(); 1982 Multilib Alt32 = MultilibBuilder() 1983 .gccSuffix("/32") 1984 .includeSuffix("/32") 1985 .flag("-m32") 1986 .flag("-m64", /*Disallow=*/true) 1987 .flag("-mx32", /*Disallow=*/true) 1988 .makeMultilib(); 1989 Multilib Altx32 = MultilibBuilder() 1990 .gccSuffix("/x32") 1991 .includeSuffix("/x32") 1992 .flag("-m32", /*Disallow=*/true) 1993 .flag("-m64", /*Disallow=*/true) 1994 .flag("-mx32") 1995 .makeMultilib(); 1996 Multilib Alt32sparc = MultilibBuilder() 1997 .gccSuffix("/sparcv8plus") 1998 .includeSuffix("/sparcv8plus") 1999 .flag("-m32") 2000 .flag("-m64", /*Disallow=*/true) 2001 .makeMultilib(); 2002 2003 // GCC toolchain for IAMCU doesn't have crtbegin.o, so look for libgcc.a. 2004 FilterNonExistent NonExistent( 2005 Path, TargetTriple.isOSIAMCU() ? "/libgcc.a" : "/crtbegin.o", D.getVFS()); 2006 2007 // Determine default multilib from: 32, 64, x32 2008 // Also handle cases such as 64 on 32, 32 on 64, etc. 2009 enum { UNKNOWN, WANT32, WANT64, WANTX32 } Want = UNKNOWN; 2010 const bool IsX32 = TargetTriple.isX32(); 2011 if (TargetTriple.isArch32Bit() && !NonExistent(Alt32)) 2012 Want = WANT64; 2013 if (TargetTriple.isArch32Bit() && !NonExistent(Alt32sparc)) 2014 Want = WANT64; 2015 else if (TargetTriple.isArch64Bit() && IsX32 && !NonExistent(Altx32)) 2016 Want = WANT64; 2017 else if (TargetTriple.isArch64Bit() && !IsX32 && !NonExistent(Alt64)) 2018 Want = WANT32; 2019 else if (TargetTriple.isArch64Bit() && !NonExistent(Alt32sparc)) 2020 Want = WANT64; 2021 else { 2022 if (TargetTriple.isArch32Bit()) 2023 Want = NeedsBiarchSuffix ? WANT64 : WANT32; 2024 else if (IsX32) 2025 Want = NeedsBiarchSuffix ? WANT64 : WANTX32; 2026 else 2027 Want = NeedsBiarchSuffix ? WANT32 : WANT64; 2028 } 2029 2030 if (Want == WANT32) 2031 DefaultBuilder.flag("-m32") 2032 .flag("-m64", /*Disallow=*/true) 2033 .flag("-mx32", /*Disallow=*/true); 2034 else if (Want == WANT64) 2035 DefaultBuilder.flag("-m32", /*Disallow=*/true) 2036 .flag("-m64") 2037 .flag("-mx32", /*Disallow=*/true); 2038 else if (Want == WANTX32) 2039 DefaultBuilder.flag("-m32", /*Disallow=*/true) 2040 .flag("-m64", /*Disallow=*/true) 2041 .flag("-mx32"); 2042 else 2043 return false; 2044 2045 Multilib Default = DefaultBuilder.makeMultilib(); 2046 2047 Result.Multilibs.push_back(Default); 2048 Result.Multilibs.push_back(Alt64); 2049 Result.Multilibs.push_back(Alt32); 2050 Result.Multilibs.push_back(Altx32); 2051 Result.Multilibs.push_back(Alt32sparc); 2052 2053 Result.Multilibs.FilterOut(NonExistent); 2054 2055 Multilib::flags_list Flags; 2056 addMultilibFlag(TargetTriple.isArch64Bit() && !IsX32, "-m64", Flags); 2057 addMultilibFlag(TargetTriple.isArch32Bit(), "-m32", Flags); 2058 addMultilibFlag(TargetTriple.isArch64Bit() && IsX32, "-mx32", Flags); 2059 2060 if (!Result.Multilibs.select(Flags, Result.SelectedMultilibs)) 2061 return false; 2062 2063 if (Result.SelectedMultilibs.back() == Alt64 || 2064 Result.SelectedMultilibs.back() == Alt32 || 2065 Result.SelectedMultilibs.back() == Altx32 || 2066 Result.SelectedMultilibs.back() == Alt32sparc) 2067 Result.BiarchSibling = Default; 2068 2069 return true; 2070 } 2071 2072 /// Generic_GCC - A tool chain using the 'gcc' command to perform 2073 /// all subcommands; this relies on gcc translating the majority of 2074 /// command line options. 2075 2076 /// Less-than for GCCVersion, implementing a Strict Weak Ordering. 2077 bool Generic_GCC::GCCVersion::isOlderThan(int RHSMajor, int RHSMinor, 2078 int RHSPatch, 2079 StringRef RHSPatchSuffix) const { 2080 if (Major != RHSMajor) 2081 return Major < RHSMajor; 2082 if (Minor != RHSMinor) { 2083 // Note that versions without a specified minor sort higher than those with 2084 // a minor. 2085 if (RHSMinor == -1) 2086 return true; 2087 if (Minor == -1) 2088 return false; 2089 return Minor < RHSMinor; 2090 } 2091 if (Patch != RHSPatch) { 2092 // Note that versions without a specified patch sort higher than those with 2093 // a patch. 2094 if (RHSPatch == -1) 2095 return true; 2096 if (Patch == -1) 2097 return false; 2098 2099 // Otherwise just sort on the patch itself. 2100 return Patch < RHSPatch; 2101 } 2102 if (PatchSuffix != RHSPatchSuffix) { 2103 // Sort empty suffixes higher. 2104 if (RHSPatchSuffix.empty()) 2105 return true; 2106 if (PatchSuffix.empty()) 2107 return false; 2108 2109 // Provide a lexicographic sort to make this a total ordering. 2110 return PatchSuffix < RHSPatchSuffix; 2111 } 2112 2113 // The versions are equal. 2114 return false; 2115 } 2116 2117 /// Parse a GCCVersion object out of a string of text. 2118 /// 2119 /// This is the primary means of forming GCCVersion objects. 2120 /*static*/ 2121 Generic_GCC::GCCVersion Generic_GCC::GCCVersion::Parse(StringRef VersionText) { 2122 const GCCVersion BadVersion = {VersionText.str(), -1, -1, -1, "", "", ""}; 2123 std::pair<StringRef, StringRef> First = VersionText.split('.'); 2124 std::pair<StringRef, StringRef> Second = First.second.split('.'); 2125 2126 StringRef MajorStr = First.first; 2127 StringRef MinorStr = Second.first; 2128 StringRef PatchStr = Second.second; 2129 2130 GCCVersion GoodVersion = {VersionText.str(), -1, -1, -1, "", "", ""}; 2131 2132 // Parse version number strings such as: 2133 // 5 2134 // 4.4 2135 // 4.4-patched 2136 // 4.4.0 2137 // 4.4.x 2138 // 4.4.2-rc4 2139 // 4.4.x-patched 2140 // 10-win32 2141 // Split on '.', handle 1, 2 or 3 such segments. Each segment must contain 2142 // purely a number, except for the last one, where a non-number suffix 2143 // is stored in PatchSuffix. The third segment is allowed to not contain 2144 // a number at all. 2145 2146 auto TryParseLastNumber = [&](StringRef Segment, int &Number, 2147 std::string &OutStr) -> bool { 2148 // Look for a number prefix and parse that, and split out any trailing 2149 // string into GoodVersion.PatchSuffix. 2150 2151 if (size_t EndNumber = Segment.find_first_not_of("0123456789")) { 2152 StringRef NumberStr = Segment.slice(0, EndNumber); 2153 if (NumberStr.getAsInteger(10, Number) || Number < 0) 2154 return false; 2155 OutStr = NumberStr; 2156 GoodVersion.PatchSuffix = Segment.substr(EndNumber); 2157 return true; 2158 } 2159 return false; 2160 }; 2161 auto TryParseNumber = [](StringRef Segment, int &Number) -> bool { 2162 if (Segment.getAsInteger(10, Number) || Number < 0) 2163 return false; 2164 return true; 2165 }; 2166 2167 if (MinorStr.empty()) { 2168 // If no minor string, major is the last segment 2169 if (!TryParseLastNumber(MajorStr, GoodVersion.Major, GoodVersion.MajorStr)) 2170 return BadVersion; 2171 return GoodVersion; 2172 } 2173 2174 if (!TryParseNumber(MajorStr, GoodVersion.Major)) 2175 return BadVersion; 2176 GoodVersion.MajorStr = MajorStr; 2177 2178 if (PatchStr.empty()) { 2179 // If no patch string, minor is the last segment 2180 if (!TryParseLastNumber(MinorStr, GoodVersion.Minor, GoodVersion.MinorStr)) 2181 return BadVersion; 2182 return GoodVersion; 2183 } 2184 2185 if (!TryParseNumber(MinorStr, GoodVersion.Minor)) 2186 return BadVersion; 2187 GoodVersion.MinorStr = MinorStr; 2188 2189 // For the last segment, tolerate a missing number. 2190 std::string DummyStr; 2191 TryParseLastNumber(PatchStr, GoodVersion.Patch, DummyStr); 2192 return GoodVersion; 2193 } 2194 2195 static llvm::StringRef getGCCToolchainDir(const ArgList &Args, 2196 llvm::StringRef SysRoot) { 2197 const Arg *A = Args.getLastArg(clang::driver::options::OPT_gcc_toolchain); 2198 if (A) 2199 return A->getValue(); 2200 2201 // If we have a SysRoot, ignore GCC_INSTALL_PREFIX. 2202 // GCC_INSTALL_PREFIX specifies the gcc installation for the default 2203 // sysroot and is likely not valid with a different sysroot. 2204 if (!SysRoot.empty()) 2205 return ""; 2206 2207 return GCC_INSTALL_PREFIX; 2208 } 2209 2210 /// Initialize a GCCInstallationDetector from the driver. 2211 /// 2212 /// This performs all of the autodetection and sets up the various paths. 2213 /// Once constructed, a GCCInstallationDetector is essentially immutable. 2214 /// 2215 /// FIXME: We shouldn't need an explicit TargetTriple parameter here, and 2216 /// should instead pull the target out of the driver. This is currently 2217 /// necessary because the driver doesn't store the final version of the target 2218 /// triple. 2219 void Generic_GCC::GCCInstallationDetector::init( 2220 const llvm::Triple &TargetTriple, const ArgList &Args) { 2221 llvm::Triple BiarchVariantTriple = TargetTriple.isArch32Bit() 2222 ? TargetTriple.get64BitArchVariant() 2223 : TargetTriple.get32BitArchVariant(); 2224 // The library directories which may contain GCC installations. 2225 SmallVector<StringRef, 4> CandidateLibDirs, CandidateBiarchLibDirs; 2226 // The compatible GCC triples for this particular architecture. 2227 SmallVector<StringRef, 16> CandidateTripleAliases; 2228 SmallVector<StringRef, 16> CandidateBiarchTripleAliases; 2229 // Add some triples that we want to check first. 2230 CandidateTripleAliases.push_back(TargetTriple.str()); 2231 std::string TripleNoVendor, BiarchTripleNoVendor; 2232 if (TargetTriple.getVendor() == llvm::Triple::UnknownVendor) { 2233 StringRef OSEnv = TargetTriple.getOSAndEnvironmentName(); 2234 if (TargetTriple.getEnvironment() == llvm::Triple::GNUX32) 2235 OSEnv = "linux-gnu"; 2236 TripleNoVendor = (TargetTriple.getArchName().str() + '-' + OSEnv).str(); 2237 CandidateTripleAliases.push_back(TripleNoVendor); 2238 if (BiarchVariantTriple.getArch() != llvm::Triple::UnknownArch) { 2239 BiarchTripleNoVendor = 2240 (BiarchVariantTriple.getArchName().str() + '-' + OSEnv).str(); 2241 CandidateBiarchTripleAliases.push_back(BiarchTripleNoVendor); 2242 } 2243 } 2244 2245 CollectLibDirsAndTriples(TargetTriple, BiarchVariantTriple, CandidateLibDirs, 2246 CandidateTripleAliases, CandidateBiarchLibDirs, 2247 CandidateBiarchTripleAliases); 2248 2249 // If --gcc-install-dir= is specified, skip filesystem detection. 2250 if (const Arg *A = 2251 Args.getLastArg(clang::driver::options::OPT_gcc_install_dir_EQ); 2252 A && A->getValue()[0]) { 2253 StringRef InstallDir = A->getValue(); 2254 if (!ScanGCCForMultilibs(TargetTriple, Args, InstallDir, false)) { 2255 D.Diag(diag::err_drv_invalid_gcc_install_dir) << InstallDir; 2256 } else { 2257 (void)InstallDir.consume_back("/"); 2258 StringRef VersionText = llvm::sys::path::filename(InstallDir); 2259 StringRef TripleText = 2260 llvm::sys::path::filename(llvm::sys::path::parent_path(InstallDir)); 2261 2262 Version = GCCVersion::Parse(VersionText); 2263 GCCTriple.setTriple(TripleText); 2264 GCCInstallPath = std::string(InstallDir); 2265 GCCParentLibPath = GCCInstallPath + "/../../.."; 2266 IsValid = true; 2267 } 2268 return; 2269 } 2270 2271 // If --gcc-triple is specified use this instead of trying to 2272 // auto-detect a triple. 2273 if (const Arg *A = 2274 Args.getLastArg(clang::driver::options::OPT_gcc_triple_EQ)) { 2275 StringRef GCCTriple = A->getValue(); 2276 CandidateTripleAliases.clear(); 2277 CandidateTripleAliases.push_back(GCCTriple); 2278 } 2279 2280 // Compute the set of prefixes for our search. 2281 SmallVector<std::string, 8> Prefixes; 2282 StringRef GCCToolchainDir = getGCCToolchainDir(Args, D.SysRoot); 2283 if (GCCToolchainDir != "") { 2284 if (GCCToolchainDir.back() == '/') 2285 GCCToolchainDir = GCCToolchainDir.drop_back(); // remove the / 2286 2287 Prefixes.push_back(std::string(GCCToolchainDir)); 2288 } else { 2289 // If we have a SysRoot, try that first. 2290 if (!D.SysRoot.empty()) { 2291 Prefixes.push_back(D.SysRoot); 2292 AddDefaultGCCPrefixes(TargetTriple, Prefixes, D.SysRoot); 2293 } 2294 2295 // Then look for gcc installed alongside clang. 2296 Prefixes.push_back(D.Dir + "/.."); 2297 2298 // Next, look for prefix(es) that correspond to distribution-supplied gcc 2299 // installations. 2300 if (D.SysRoot.empty()) { 2301 // Typically /usr. 2302 AddDefaultGCCPrefixes(TargetTriple, Prefixes, D.SysRoot); 2303 } 2304 2305 // Try to respect gcc-config on Gentoo if --gcc-toolchain is not provided. 2306 // This avoids accidentally enforcing the system GCC version when using a 2307 // custom toolchain. 2308 SmallVector<StringRef, 16> GentooTestTriples; 2309 // Try to match an exact triple as target triple first. 2310 // e.g. crossdev -S x86_64-gentoo-linux-gnu will install gcc libs for 2311 // x86_64-gentoo-linux-gnu. But "clang -target x86_64-gentoo-linux-gnu" 2312 // may pick the libraries for x86_64-pc-linux-gnu even when exact matching 2313 // triple x86_64-gentoo-linux-gnu is present. 2314 GentooTestTriples.push_back(TargetTriple.str()); 2315 GentooTestTriples.append(CandidateTripleAliases.begin(), 2316 CandidateTripleAliases.end()); 2317 if (ScanGentooConfigs(TargetTriple, Args, GentooTestTriples, 2318 CandidateBiarchTripleAliases)) 2319 return; 2320 } 2321 2322 // Loop over the various components which exist and select the best GCC 2323 // installation available. GCC installs are ranked by version number. 2324 const GCCVersion VersionZero = GCCVersion::Parse("0.0.0"); 2325 Version = VersionZero; 2326 for (const std::string &Prefix : Prefixes) { 2327 auto &VFS = D.getVFS(); 2328 if (!VFS.exists(Prefix)) 2329 continue; 2330 for (StringRef Suffix : CandidateLibDirs) { 2331 const std::string LibDir = concat(Prefix, Suffix); 2332 if (!VFS.exists(LibDir)) 2333 continue; 2334 // Maybe filter out <libdir>/gcc and <libdir>/gcc-cross. 2335 bool GCCDirExists = VFS.exists(LibDir + "/gcc"); 2336 bool GCCCrossDirExists = VFS.exists(LibDir + "/gcc-cross"); 2337 for (StringRef Candidate : CandidateTripleAliases) 2338 ScanLibDirForGCCTriple(TargetTriple, Args, LibDir, Candidate, false, 2339 GCCDirExists, GCCCrossDirExists); 2340 } 2341 for (StringRef Suffix : CandidateBiarchLibDirs) { 2342 const std::string LibDir = Prefix + Suffix.str(); 2343 if (!VFS.exists(LibDir)) 2344 continue; 2345 bool GCCDirExists = VFS.exists(LibDir + "/gcc"); 2346 bool GCCCrossDirExists = VFS.exists(LibDir + "/gcc-cross"); 2347 for (StringRef Candidate : CandidateBiarchTripleAliases) 2348 ScanLibDirForGCCTriple(TargetTriple, Args, LibDir, Candidate, true, 2349 GCCDirExists, GCCCrossDirExists); 2350 } 2351 2352 // Skip other prefixes once a GCC installation is found. 2353 if (Version > VersionZero) 2354 break; 2355 } 2356 } 2357 2358 void Generic_GCC::GCCInstallationDetector::print(raw_ostream &OS) const { 2359 for (const auto &InstallPath : CandidateGCCInstallPaths) 2360 OS << "Found candidate GCC installation: " << InstallPath << "\n"; 2361 2362 if (!GCCInstallPath.empty()) 2363 OS << "Selected GCC installation: " << GCCInstallPath << "\n"; 2364 2365 for (const auto &Multilib : Multilibs) 2366 OS << "Candidate multilib: " << Multilib << "\n"; 2367 2368 if (Multilibs.size() != 0 || !SelectedMultilib.isDefault()) 2369 OS << "Selected multilib: " << SelectedMultilib << "\n"; 2370 } 2371 2372 bool Generic_GCC::GCCInstallationDetector::getBiarchSibling(Multilib &M) const { 2373 if (BiarchSibling) { 2374 M = *BiarchSibling; 2375 return true; 2376 } 2377 return false; 2378 } 2379 2380 void Generic_GCC::GCCInstallationDetector::AddDefaultGCCPrefixes( 2381 const llvm::Triple &TargetTriple, SmallVectorImpl<std::string> &Prefixes, 2382 StringRef SysRoot) { 2383 2384 if (TargetTriple.isOSHaiku()) { 2385 Prefixes.push_back(concat(SysRoot, "/boot/system/develop/tools")); 2386 return; 2387 } 2388 2389 if (TargetTriple.isOSSolaris()) { 2390 // Solaris is a special case. 2391 // The GCC installation is under 2392 // /usr/gcc/<major>.<minor>/lib/gcc/<triple>/<major>.<minor>.<patch>/ 2393 // so we need to find those /usr/gcc/*/lib/gcc libdirs and go with 2394 // /usr/gcc/<version> as a prefix. 2395 2396 SmallVector<std::pair<GCCVersion, std::string>, 8> SolarisPrefixes; 2397 std::string PrefixDir = concat(SysRoot, "/usr/gcc"); 2398 std::error_code EC; 2399 for (llvm::vfs::directory_iterator LI = D.getVFS().dir_begin(PrefixDir, EC), 2400 LE; 2401 !EC && LI != LE; LI = LI.increment(EC)) { 2402 StringRef VersionText = llvm::sys::path::filename(LI->path()); 2403 GCCVersion CandidateVersion = GCCVersion::Parse(VersionText); 2404 2405 // Filter out obviously bad entries. 2406 if (CandidateVersion.Major == -1 || CandidateVersion.isOlderThan(4, 1, 1)) 2407 continue; 2408 2409 std::string CandidatePrefix = PrefixDir + "/" + VersionText.str(); 2410 std::string CandidateLibPath = CandidatePrefix + "/lib/gcc"; 2411 if (!D.getVFS().exists(CandidateLibPath)) 2412 continue; 2413 2414 SolarisPrefixes.emplace_back( 2415 std::make_pair(CandidateVersion, CandidatePrefix)); 2416 } 2417 // Sort in reverse order so GCCInstallationDetector::init picks the latest. 2418 std::sort(SolarisPrefixes.rbegin(), SolarisPrefixes.rend()); 2419 for (auto p : SolarisPrefixes) 2420 Prefixes.emplace_back(p.second); 2421 return; 2422 } 2423 2424 // For Linux, if --sysroot is not specified, look for RHEL/CentOS devtoolsets 2425 // and gcc-toolsets. 2426 if (SysRoot.empty() && TargetTriple.getOS() == llvm::Triple::Linux && 2427 D.getVFS().exists("/opt/rh")) { 2428 // TODO: We may want to remove this, since the functionality 2429 // can be achieved using config files. 2430 Prefixes.push_back("/opt/rh/gcc-toolset-12/root/usr"); 2431 Prefixes.push_back("/opt/rh/gcc-toolset-11/root/usr"); 2432 Prefixes.push_back("/opt/rh/gcc-toolset-10/root/usr"); 2433 Prefixes.push_back("/opt/rh/devtoolset-12/root/usr"); 2434 Prefixes.push_back("/opt/rh/devtoolset-11/root/usr"); 2435 Prefixes.push_back("/opt/rh/devtoolset-10/root/usr"); 2436 Prefixes.push_back("/opt/rh/devtoolset-9/root/usr"); 2437 Prefixes.push_back("/opt/rh/devtoolset-8/root/usr"); 2438 Prefixes.push_back("/opt/rh/devtoolset-7/root/usr"); 2439 Prefixes.push_back("/opt/rh/devtoolset-6/root/usr"); 2440 Prefixes.push_back("/opt/rh/devtoolset-4/root/usr"); 2441 Prefixes.push_back("/opt/rh/devtoolset-3/root/usr"); 2442 Prefixes.push_back("/opt/rh/devtoolset-2/root/usr"); 2443 } 2444 2445 // Fall back to /usr which is used by most non-Solaris systems. 2446 Prefixes.push_back(concat(SysRoot, "/usr")); 2447 } 2448 2449 /*static*/ void Generic_GCC::GCCInstallationDetector::CollectLibDirsAndTriples( 2450 const llvm::Triple &TargetTriple, const llvm::Triple &BiarchTriple, 2451 SmallVectorImpl<StringRef> &LibDirs, 2452 SmallVectorImpl<StringRef> &TripleAliases, 2453 SmallVectorImpl<StringRef> &BiarchLibDirs, 2454 SmallVectorImpl<StringRef> &BiarchTripleAliases) { 2455 // Declare a bunch of static data sets that we'll select between below. These 2456 // are specifically designed to always refer to string literals to avoid any 2457 // lifetime or initialization issues. 2458 // 2459 // The *Triples variables hard code some triples so that, for example, 2460 // --target=aarch64 (incomplete triple) can detect lib/aarch64-linux-gnu. 2461 // They are not needed when the user has correct LLVM_DEFAULT_TARGET_TRIPLE 2462 // and always uses the full --target (e.g. --target=aarch64-linux-gnu). The 2463 // lists should shrink over time. Please don't add more elements to *Triples. 2464 static const char *const AArch64LibDirs[] = {"/lib64", "/lib"}; 2465 static const char *const AArch64Triples[] = { 2466 "aarch64-none-linux-gnu", "aarch64-linux-gnu", "aarch64-redhat-linux", 2467 "aarch64-suse-linux"}; 2468 static const char *const AArch64beLibDirs[] = {"/lib"}; 2469 static const char *const AArch64beTriples[] = {"aarch64_be-none-linux-gnu"}; 2470 2471 static const char *const ARMLibDirs[] = {"/lib"}; 2472 static const char *const ARMTriples[] = {"arm-linux-gnueabi"}; 2473 static const char *const ARMHFTriples[] = {"arm-linux-gnueabihf", 2474 "armv7hl-redhat-linux-gnueabi", 2475 "armv6hl-suse-linux-gnueabi", 2476 "armv7hl-suse-linux-gnueabi"}; 2477 static const char *const ARMebLibDirs[] = {"/lib"}; 2478 static const char *const ARMebTriples[] = {"armeb-linux-gnueabi"}; 2479 static const char *const ARMebHFTriples[] = { 2480 "armeb-linux-gnueabihf", "armebv7hl-redhat-linux-gnueabi"}; 2481 2482 static const char *const AVRLibDirs[] = {"/lib"}; 2483 static const char *const AVRTriples[] = {"avr"}; 2484 2485 static const char *const CSKYLibDirs[] = {"/lib"}; 2486 static const char *const CSKYTriples[] = { 2487 "csky-linux-gnuabiv2", "csky-linux-uclibcabiv2", "csky-elf-noneabiv2"}; 2488 2489 static const char *const X86_64LibDirs[] = {"/lib64", "/lib"}; 2490 static const char *const X86_64Triples[] = { 2491 "x86_64-linux-gnu", "x86_64-unknown-linux-gnu", 2492 "x86_64-pc-linux-gnu", "x86_64-redhat-linux6E", 2493 "x86_64-redhat-linux", "x86_64-suse-linux", 2494 "x86_64-manbo-linux-gnu", "x86_64-slackware-linux", 2495 "x86_64-unknown-linux", "x86_64-amazon-linux"}; 2496 static const char *const X32Triples[] = {"x86_64-linux-gnux32", 2497 "x86_64-pc-linux-gnux32"}; 2498 static const char *const X32LibDirs[] = {"/libx32", "/lib"}; 2499 static const char *const X86LibDirs[] = {"/lib32", "/lib"}; 2500 static const char *const X86Triples[] = { 2501 "i586-linux-gnu", "i686-linux-gnu", "i686-pc-linux-gnu", 2502 "i386-redhat-linux6E", "i686-redhat-linux", "i386-redhat-linux", 2503 "i586-suse-linux", "i686-montavista-linux", 2504 }; 2505 2506 static const char *const LoongArch64LibDirs[] = {"/lib64", "/lib"}; 2507 static const char *const LoongArch64Triples[] = { 2508 "loongarch64-linux-gnu", "loongarch64-unknown-linux-gnu"}; 2509 2510 static const char *const M68kLibDirs[] = {"/lib"}; 2511 static const char *const M68kTriples[] = {"m68k-unknown-linux-gnu", 2512 "m68k-suse-linux"}; 2513 2514 static const char *const MIPSLibDirs[] = {"/libo32", "/lib"}; 2515 static const char *const MIPSTriples[] = { 2516 "mips-linux-gnu", "mips-mti-linux", "mips-mti-linux-gnu", 2517 "mips-img-linux-gnu", "mipsisa32r6-linux-gnu"}; 2518 static const char *const MIPSELLibDirs[] = {"/libo32", "/lib"}; 2519 static const char *const MIPSELTriples[] = {"mipsel-linux-gnu", 2520 "mips-img-linux-gnu"}; 2521 2522 static const char *const MIPS64LibDirs[] = {"/lib64", "/lib"}; 2523 static const char *const MIPS64Triples[] = { 2524 "mips-mti-linux-gnu", "mips-img-linux-gnu", "mips64-linux-gnuabi64", 2525 "mipsisa64r6-linux-gnu", "mipsisa64r6-linux-gnuabi64"}; 2526 static const char *const MIPS64ELLibDirs[] = {"/lib64", "/lib"}; 2527 static const char *const MIPS64ELTriples[] = { 2528 "mips-mti-linux-gnu", "mips-img-linux-gnu", "mips64el-linux-gnuabi64", 2529 "mipsisa64r6el-linux-gnu", "mipsisa64r6el-linux-gnuabi64"}; 2530 2531 static const char *const MIPSN32LibDirs[] = {"/lib32"}; 2532 static const char *const MIPSN32Triples[] = {"mips64-linux-gnuabin32", 2533 "mipsisa64r6-linux-gnuabin32"}; 2534 static const char *const MIPSN32ELLibDirs[] = {"/lib32"}; 2535 static const char *const MIPSN32ELTriples[] = { 2536 "mips64el-linux-gnuabin32", "mipsisa64r6el-linux-gnuabin32"}; 2537 2538 static const char *const MSP430LibDirs[] = {"/lib"}; 2539 static const char *const MSP430Triples[] = {"msp430-elf"}; 2540 2541 static const char *const PPCLibDirs[] = {"/lib32", "/lib"}; 2542 static const char *const PPCTriples[] = { 2543 "powerpc-unknown-linux-gnu", 2544 // On 32-bit PowerPC systems running SUSE Linux, gcc is configured as a 2545 // 64-bit compiler which defaults to "-m32", hence "powerpc64-suse-linux". 2546 "powerpc64-suse-linux", "powerpc-montavista-linuxspe"}; 2547 static const char *const PPCLELibDirs[] = {"/lib32", "/lib"}; 2548 static const char *const PPCLETriples[] = {"powerpcle-unknown-linux-gnu", 2549 "powerpcle-linux-musl"}; 2550 2551 static const char *const PPC64LibDirs[] = {"/lib64", "/lib"}; 2552 static const char *const PPC64Triples[] = {"powerpc64-unknown-linux-gnu", 2553 "powerpc64-suse-linux", 2554 "ppc64-redhat-linux"}; 2555 static const char *const PPC64LELibDirs[] = {"/lib64", "/lib"}; 2556 static const char *const PPC64LETriples[] = { 2557 "powerpc64le-unknown-linux-gnu", "powerpc64le-none-linux-gnu", 2558 "powerpc64le-suse-linux", "ppc64le-redhat-linux"}; 2559 2560 static const char *const RISCV32LibDirs[] = {"/lib32", "/lib"}; 2561 static const char *const RISCV32Triples[] = {"riscv32-unknown-linux-gnu", 2562 "riscv32-unknown-elf"}; 2563 static const char *const RISCV64LibDirs[] = {"/lib64", "/lib"}; 2564 static const char *const RISCV64Triples[] = {"riscv64-unknown-linux-gnu", 2565 "riscv64-unknown-elf"}; 2566 2567 static const char *const SPARCv8LibDirs[] = {"/lib32", "/lib"}; 2568 static const char *const SPARCv8Triples[] = {"sparc-linux-gnu", 2569 "sparcv8-linux-gnu"}; 2570 static const char *const SPARCv9LibDirs[] = {"/lib64", "/lib"}; 2571 static const char *const SPARCv9Triples[] = {"sparc64-linux-gnu", 2572 "sparcv9-linux-gnu"}; 2573 2574 static const char *const SystemZLibDirs[] = {"/lib64", "/lib"}; 2575 static const char *const SystemZTriples[] = { 2576 "s390x-unknown-linux-gnu", "s390x-ibm-linux-gnu", "s390x-suse-linux", 2577 "s390x-redhat-linux"}; 2578 2579 using std::begin; 2580 using std::end; 2581 2582 if (TargetTriple.isOSSolaris()) { 2583 static const char *const SolarisLibDirs[] = {"/lib"}; 2584 static const char *const SolarisSparcV8Triples[] = { 2585 "sparc-sun-solaris2.11"}; 2586 static const char *const SolarisSparcV9Triples[] = { 2587 "sparcv9-sun-solaris2.11"}; 2588 static const char *const SolarisX86Triples[] = {"i386-pc-solaris2.11"}; 2589 static const char *const SolarisX86_64Triples[] = {"x86_64-pc-solaris2.11"}; 2590 LibDirs.append(begin(SolarisLibDirs), end(SolarisLibDirs)); 2591 BiarchLibDirs.append(begin(SolarisLibDirs), end(SolarisLibDirs)); 2592 switch (TargetTriple.getArch()) { 2593 case llvm::Triple::x86: 2594 TripleAliases.append(begin(SolarisX86Triples), end(SolarisX86Triples)); 2595 BiarchTripleAliases.append(begin(SolarisX86_64Triples), 2596 end(SolarisX86_64Triples)); 2597 break; 2598 case llvm::Triple::x86_64: 2599 TripleAliases.append(begin(SolarisX86_64Triples), 2600 end(SolarisX86_64Triples)); 2601 BiarchTripleAliases.append(begin(SolarisX86Triples), 2602 end(SolarisX86Triples)); 2603 break; 2604 case llvm::Triple::sparc: 2605 TripleAliases.append(begin(SolarisSparcV8Triples), 2606 end(SolarisSparcV8Triples)); 2607 BiarchTripleAliases.append(begin(SolarisSparcV9Triples), 2608 end(SolarisSparcV9Triples)); 2609 break; 2610 case llvm::Triple::sparcv9: 2611 TripleAliases.append(begin(SolarisSparcV9Triples), 2612 end(SolarisSparcV9Triples)); 2613 BiarchTripleAliases.append(begin(SolarisSparcV8Triples), 2614 end(SolarisSparcV8Triples)); 2615 break; 2616 default: 2617 break; 2618 } 2619 return; 2620 } 2621 2622 // Android targets should not use GNU/Linux tools or libraries. 2623 if (TargetTriple.isAndroid()) { 2624 static const char *const AArch64AndroidTriples[] = { 2625 "aarch64-linux-android"}; 2626 static const char *const ARMAndroidTriples[] = {"arm-linux-androideabi"}; 2627 static const char *const X86AndroidTriples[] = {"i686-linux-android"}; 2628 static const char *const X86_64AndroidTriples[] = {"x86_64-linux-android"}; 2629 2630 switch (TargetTriple.getArch()) { 2631 case llvm::Triple::aarch64: 2632 LibDirs.append(begin(AArch64LibDirs), end(AArch64LibDirs)); 2633 TripleAliases.append(begin(AArch64AndroidTriples), 2634 end(AArch64AndroidTriples)); 2635 break; 2636 case llvm::Triple::arm: 2637 case llvm::Triple::thumb: 2638 LibDirs.append(begin(ARMLibDirs), end(ARMLibDirs)); 2639 TripleAliases.append(begin(ARMAndroidTriples), end(ARMAndroidTriples)); 2640 break; 2641 case llvm::Triple::x86_64: 2642 LibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs)); 2643 TripleAliases.append(begin(X86_64AndroidTriples), 2644 end(X86_64AndroidTriples)); 2645 BiarchLibDirs.append(begin(X86LibDirs), end(X86LibDirs)); 2646 BiarchTripleAliases.append(begin(X86AndroidTriples), 2647 end(X86AndroidTriples)); 2648 break; 2649 case llvm::Triple::x86: 2650 LibDirs.append(begin(X86LibDirs), end(X86LibDirs)); 2651 TripleAliases.append(begin(X86AndroidTriples), end(X86AndroidTriples)); 2652 BiarchLibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs)); 2653 BiarchTripleAliases.append(begin(X86_64AndroidTriples), 2654 end(X86_64AndroidTriples)); 2655 break; 2656 default: 2657 break; 2658 } 2659 2660 return; 2661 } 2662 2663 if (TargetTriple.isOSHurd()) { 2664 switch (TargetTriple.getArch()) { 2665 case llvm::Triple::x86_64: 2666 LibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs)); 2667 TripleAliases.push_back("x86_64-gnu"); 2668 break; 2669 case llvm::Triple::x86: 2670 LibDirs.append(begin(X86LibDirs), end(X86LibDirs)); 2671 TripleAliases.push_back("i686-gnu"); 2672 break; 2673 default: 2674 break; 2675 } 2676 2677 return; 2678 } 2679 2680 switch (TargetTriple.getArch()) { 2681 case llvm::Triple::aarch64: 2682 LibDirs.append(begin(AArch64LibDirs), end(AArch64LibDirs)); 2683 TripleAliases.append(begin(AArch64Triples), end(AArch64Triples)); 2684 BiarchLibDirs.append(begin(AArch64LibDirs), end(AArch64LibDirs)); 2685 BiarchTripleAliases.append(begin(AArch64Triples), end(AArch64Triples)); 2686 break; 2687 case llvm::Triple::aarch64_be: 2688 LibDirs.append(begin(AArch64beLibDirs), end(AArch64beLibDirs)); 2689 TripleAliases.append(begin(AArch64beTriples), end(AArch64beTriples)); 2690 BiarchLibDirs.append(begin(AArch64beLibDirs), end(AArch64beLibDirs)); 2691 BiarchTripleAliases.append(begin(AArch64beTriples), end(AArch64beTriples)); 2692 break; 2693 case llvm::Triple::arm: 2694 case llvm::Triple::thumb: 2695 LibDirs.append(begin(ARMLibDirs), end(ARMLibDirs)); 2696 if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF || 2697 TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHFT64 || 2698 TargetTriple.getEnvironment() == llvm::Triple::MuslEABIHF || 2699 TargetTriple.getEnvironment() == llvm::Triple::EABIHF) { 2700 TripleAliases.append(begin(ARMHFTriples), end(ARMHFTriples)); 2701 } else { 2702 TripleAliases.append(begin(ARMTriples), end(ARMTriples)); 2703 } 2704 break; 2705 case llvm::Triple::armeb: 2706 case llvm::Triple::thumbeb: 2707 LibDirs.append(begin(ARMebLibDirs), end(ARMebLibDirs)); 2708 if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF || 2709 TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHFT64 || 2710 TargetTriple.getEnvironment() == llvm::Triple::MuslEABIHF || 2711 TargetTriple.getEnvironment() == llvm::Triple::EABIHF) { 2712 TripleAliases.append(begin(ARMebHFTriples), end(ARMebHFTriples)); 2713 } else { 2714 TripleAliases.append(begin(ARMebTriples), end(ARMebTriples)); 2715 } 2716 break; 2717 case llvm::Triple::avr: 2718 LibDirs.append(begin(AVRLibDirs), end(AVRLibDirs)); 2719 TripleAliases.append(begin(AVRTriples), end(AVRTriples)); 2720 break; 2721 case llvm::Triple::csky: 2722 LibDirs.append(begin(CSKYLibDirs), end(CSKYLibDirs)); 2723 TripleAliases.append(begin(CSKYTriples), end(CSKYTriples)); 2724 break; 2725 case llvm::Triple::x86_64: 2726 if (TargetTriple.isX32()) { 2727 LibDirs.append(begin(X32LibDirs), end(X32LibDirs)); 2728 TripleAliases.append(begin(X32Triples), end(X32Triples)); 2729 BiarchLibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs)); 2730 BiarchTripleAliases.append(begin(X86_64Triples), end(X86_64Triples)); 2731 } else { 2732 LibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs)); 2733 TripleAliases.append(begin(X86_64Triples), end(X86_64Triples)); 2734 BiarchLibDirs.append(begin(X32LibDirs), end(X32LibDirs)); 2735 BiarchTripleAliases.append(begin(X32Triples), end(X32Triples)); 2736 } 2737 BiarchLibDirs.append(begin(X86LibDirs), end(X86LibDirs)); 2738 BiarchTripleAliases.append(begin(X86Triples), end(X86Triples)); 2739 break; 2740 case llvm::Triple::x86: 2741 LibDirs.append(begin(X86LibDirs), end(X86LibDirs)); 2742 // MCU toolchain is 32 bit only and its triple alias is TargetTriple 2743 // itself, which will be appended below. 2744 if (!TargetTriple.isOSIAMCU()) { 2745 TripleAliases.append(begin(X86Triples), end(X86Triples)); 2746 BiarchLibDirs.append(begin(X86_64LibDirs), end(X86_64LibDirs)); 2747 BiarchTripleAliases.append(begin(X86_64Triples), end(X86_64Triples)); 2748 BiarchLibDirs.append(begin(X32LibDirs), end(X32LibDirs)); 2749 BiarchTripleAliases.append(begin(X32Triples), end(X32Triples)); 2750 } 2751 break; 2752 // TODO: Handle loongarch32. 2753 case llvm::Triple::loongarch64: 2754 LibDirs.append(begin(LoongArch64LibDirs), end(LoongArch64LibDirs)); 2755 TripleAliases.append(begin(LoongArch64Triples), end(LoongArch64Triples)); 2756 break; 2757 case llvm::Triple::m68k: 2758 LibDirs.append(begin(M68kLibDirs), end(M68kLibDirs)); 2759 TripleAliases.append(begin(M68kTriples), end(M68kTriples)); 2760 break; 2761 case llvm::Triple::mips: 2762 LibDirs.append(begin(MIPSLibDirs), end(MIPSLibDirs)); 2763 TripleAliases.append(begin(MIPSTriples), end(MIPSTriples)); 2764 BiarchLibDirs.append(begin(MIPS64LibDirs), end(MIPS64LibDirs)); 2765 BiarchTripleAliases.append(begin(MIPS64Triples), end(MIPS64Triples)); 2766 BiarchLibDirs.append(begin(MIPSN32LibDirs), end(MIPSN32LibDirs)); 2767 BiarchTripleAliases.append(begin(MIPSN32Triples), end(MIPSN32Triples)); 2768 break; 2769 case llvm::Triple::mipsel: 2770 LibDirs.append(begin(MIPSELLibDirs), end(MIPSELLibDirs)); 2771 TripleAliases.append(begin(MIPSELTriples), end(MIPSELTriples)); 2772 TripleAliases.append(begin(MIPSTriples), end(MIPSTriples)); 2773 BiarchLibDirs.append(begin(MIPS64ELLibDirs), end(MIPS64ELLibDirs)); 2774 BiarchTripleAliases.append(begin(MIPS64ELTriples), end(MIPS64ELTriples)); 2775 BiarchLibDirs.append(begin(MIPSN32ELLibDirs), end(MIPSN32ELLibDirs)); 2776 BiarchTripleAliases.append(begin(MIPSN32ELTriples), end(MIPSN32ELTriples)); 2777 break; 2778 case llvm::Triple::mips64: 2779 LibDirs.append(begin(MIPS64LibDirs), end(MIPS64LibDirs)); 2780 TripleAliases.append(begin(MIPS64Triples), end(MIPS64Triples)); 2781 BiarchLibDirs.append(begin(MIPSLibDirs), end(MIPSLibDirs)); 2782 BiarchTripleAliases.append(begin(MIPSTriples), end(MIPSTriples)); 2783 BiarchLibDirs.append(begin(MIPSN32LibDirs), end(MIPSN32LibDirs)); 2784 BiarchTripleAliases.append(begin(MIPSN32Triples), end(MIPSN32Triples)); 2785 break; 2786 case llvm::Triple::mips64el: 2787 LibDirs.append(begin(MIPS64ELLibDirs), end(MIPS64ELLibDirs)); 2788 TripleAliases.append(begin(MIPS64ELTriples), end(MIPS64ELTriples)); 2789 BiarchLibDirs.append(begin(MIPSELLibDirs), end(MIPSELLibDirs)); 2790 BiarchTripleAliases.append(begin(MIPSELTriples), end(MIPSELTriples)); 2791 BiarchLibDirs.append(begin(MIPSN32ELLibDirs), end(MIPSN32ELLibDirs)); 2792 BiarchTripleAliases.append(begin(MIPSN32ELTriples), end(MIPSN32ELTriples)); 2793 BiarchTripleAliases.append(begin(MIPSTriples), end(MIPSTriples)); 2794 break; 2795 case llvm::Triple::msp430: 2796 LibDirs.append(begin(MSP430LibDirs), end(MSP430LibDirs)); 2797 TripleAliases.append(begin(MSP430Triples), end(MSP430Triples)); 2798 break; 2799 case llvm::Triple::ppc: 2800 LibDirs.append(begin(PPCLibDirs), end(PPCLibDirs)); 2801 TripleAliases.append(begin(PPCTriples), end(PPCTriples)); 2802 BiarchLibDirs.append(begin(PPC64LibDirs), end(PPC64LibDirs)); 2803 BiarchTripleAliases.append(begin(PPC64Triples), end(PPC64Triples)); 2804 break; 2805 case llvm::Triple::ppcle: 2806 LibDirs.append(begin(PPCLELibDirs), end(PPCLELibDirs)); 2807 TripleAliases.append(begin(PPCLETriples), end(PPCLETriples)); 2808 BiarchLibDirs.append(begin(PPC64LELibDirs), end(PPC64LELibDirs)); 2809 BiarchTripleAliases.append(begin(PPC64LETriples), end(PPC64LETriples)); 2810 break; 2811 case llvm::Triple::ppc64: 2812 LibDirs.append(begin(PPC64LibDirs), end(PPC64LibDirs)); 2813 TripleAliases.append(begin(PPC64Triples), end(PPC64Triples)); 2814 BiarchLibDirs.append(begin(PPCLibDirs), end(PPCLibDirs)); 2815 BiarchTripleAliases.append(begin(PPCTriples), end(PPCTriples)); 2816 break; 2817 case llvm::Triple::ppc64le: 2818 LibDirs.append(begin(PPC64LELibDirs), end(PPC64LELibDirs)); 2819 TripleAliases.append(begin(PPC64LETriples), end(PPC64LETriples)); 2820 BiarchLibDirs.append(begin(PPCLELibDirs), end(PPCLELibDirs)); 2821 BiarchTripleAliases.append(begin(PPCLETriples), end(PPCLETriples)); 2822 break; 2823 case llvm::Triple::riscv32: 2824 LibDirs.append(begin(RISCV32LibDirs), end(RISCV32LibDirs)); 2825 TripleAliases.append(begin(RISCV32Triples), end(RISCV32Triples)); 2826 BiarchLibDirs.append(begin(RISCV64LibDirs), end(RISCV64LibDirs)); 2827 BiarchTripleAliases.append(begin(RISCV64Triples), end(RISCV64Triples)); 2828 break; 2829 case llvm::Triple::riscv64: 2830 LibDirs.append(begin(RISCV64LibDirs), end(RISCV64LibDirs)); 2831 TripleAliases.append(begin(RISCV64Triples), end(RISCV64Triples)); 2832 BiarchLibDirs.append(begin(RISCV32LibDirs), end(RISCV32LibDirs)); 2833 BiarchTripleAliases.append(begin(RISCV32Triples), end(RISCV32Triples)); 2834 break; 2835 case llvm::Triple::sparc: 2836 case llvm::Triple::sparcel: 2837 LibDirs.append(begin(SPARCv8LibDirs), end(SPARCv8LibDirs)); 2838 TripleAliases.append(begin(SPARCv8Triples), end(SPARCv8Triples)); 2839 BiarchLibDirs.append(begin(SPARCv9LibDirs), end(SPARCv9LibDirs)); 2840 BiarchTripleAliases.append(begin(SPARCv9Triples), end(SPARCv9Triples)); 2841 break; 2842 case llvm::Triple::sparcv9: 2843 LibDirs.append(begin(SPARCv9LibDirs), end(SPARCv9LibDirs)); 2844 TripleAliases.append(begin(SPARCv9Triples), end(SPARCv9Triples)); 2845 BiarchLibDirs.append(begin(SPARCv8LibDirs), end(SPARCv8LibDirs)); 2846 BiarchTripleAliases.append(begin(SPARCv8Triples), end(SPARCv8Triples)); 2847 break; 2848 case llvm::Triple::systemz: 2849 LibDirs.append(begin(SystemZLibDirs), end(SystemZLibDirs)); 2850 TripleAliases.append(begin(SystemZTriples), end(SystemZTriples)); 2851 break; 2852 default: 2853 // By default, just rely on the standard lib directories and the original 2854 // triple. 2855 break; 2856 } 2857 2858 // Also include the multiarch variant if it's different. 2859 if (TargetTriple.str() != BiarchTriple.str()) 2860 BiarchTripleAliases.push_back(BiarchTriple.str()); 2861 } 2862 2863 bool Generic_GCC::GCCInstallationDetector::ScanGCCForMultilibs( 2864 const llvm::Triple &TargetTriple, const ArgList &Args, 2865 StringRef Path, bool NeedsBiarchSuffix) { 2866 llvm::Triple::ArchType TargetArch = TargetTriple.getArch(); 2867 DetectedMultilibs Detected; 2868 2869 // Android standalone toolchain could have multilibs for ARM and Thumb. 2870 // Debian mips multilibs behave more like the rest of the biarch ones, 2871 // so handle them there 2872 if (isArmOrThumbArch(TargetArch) && TargetTriple.isAndroid()) { 2873 // It should also work without multilibs in a simplified toolchain. 2874 findAndroidArmMultilibs(D, TargetTriple, Path, Args, Detected); 2875 } else if (TargetTriple.isCSKY()) { 2876 findCSKYMultilibs(D, TargetTriple, Path, Args, Detected); 2877 } else if (TargetTriple.isMIPS()) { 2878 if (!findMIPSMultilibs(D, TargetTriple, Path, Args, Detected)) 2879 return false; 2880 } else if (TargetTriple.isRISCV()) { 2881 findRISCVMultilibs(D, TargetTriple, Path, Args, Detected); 2882 } else if (isMSP430(TargetArch)) { 2883 findMSP430Multilibs(D, TargetTriple, Path, Args, Detected); 2884 } else if (TargetArch == llvm::Triple::avr) { 2885 // AVR has no multilibs. 2886 } else if (!findBiarchMultilibs(D, TargetTriple, Path, Args, 2887 NeedsBiarchSuffix, Detected)) { 2888 return false; 2889 } 2890 2891 Multilibs = Detected.Multilibs; 2892 SelectedMultilib = Detected.SelectedMultilibs.empty() 2893 ? Multilib() 2894 : Detected.SelectedMultilibs.back(); 2895 BiarchSibling = Detected.BiarchSibling; 2896 2897 return true; 2898 } 2899 2900 void Generic_GCC::GCCInstallationDetector::ScanLibDirForGCCTriple( 2901 const llvm::Triple &TargetTriple, const ArgList &Args, 2902 const std::string &LibDir, StringRef CandidateTriple, 2903 bool NeedsBiarchSuffix, bool GCCDirExists, bool GCCCrossDirExists) { 2904 // Locations relative to the system lib directory where GCC's triple-specific 2905 // directories might reside. 2906 struct GCCLibSuffix { 2907 // Path from system lib directory to GCC triple-specific directory. 2908 std::string LibSuffix; 2909 // Path from GCC triple-specific directory back to system lib directory. 2910 // This is one '..' component per component in LibSuffix. 2911 StringRef ReversePath; 2912 // Whether this library suffix is relevant for the triple. 2913 bool Active; 2914 } Suffixes[] = { 2915 // This is the normal place. 2916 {"gcc/" + CandidateTriple.str(), "../..", GCCDirExists}, 2917 2918 // Debian puts cross-compilers in gcc-cross. 2919 {"gcc-cross/" + CandidateTriple.str(), "../..", GCCCrossDirExists}, 2920 2921 // The Freescale PPC SDK has the gcc libraries in 2922 // <sysroot>/usr/lib/<triple>/x.y.z so have a look there as well. Only do 2923 // this on Freescale triples, though, since some systems put a *lot* of 2924 // files in that location, not just GCC installation data. 2925 {CandidateTriple.str(), "..", 2926 TargetTriple.getVendor() == llvm::Triple::Freescale || 2927 TargetTriple.getVendor() == llvm::Triple::OpenEmbedded}}; 2928 2929 for (auto &Suffix : Suffixes) { 2930 if (!Suffix.Active) 2931 continue; 2932 2933 StringRef LibSuffix = Suffix.LibSuffix; 2934 std::error_code EC; 2935 for (llvm::vfs::directory_iterator 2936 LI = D.getVFS().dir_begin(LibDir + "/" + LibSuffix, EC), 2937 LE; 2938 !EC && LI != LE; LI = LI.increment(EC)) { 2939 StringRef VersionText = llvm::sys::path::filename(LI->path()); 2940 GCCVersion CandidateVersion = GCCVersion::Parse(VersionText); 2941 if (CandidateVersion.Major != -1) // Filter obviously bad entries. 2942 if (!CandidateGCCInstallPaths.insert(std::string(LI->path())).second) 2943 continue; // Saw this path before; no need to look at it again. 2944 if (CandidateVersion.isOlderThan(4, 1, 1)) 2945 continue; 2946 if (CandidateVersion <= Version) 2947 continue; 2948 2949 if (!ScanGCCForMultilibs(TargetTriple, Args, LI->path(), 2950 NeedsBiarchSuffix)) 2951 continue; 2952 2953 Version = CandidateVersion; 2954 GCCTriple.setTriple(CandidateTriple); 2955 // FIXME: We hack together the directory name here instead of 2956 // using LI to ensure stable path separators across Windows and 2957 // Linux. 2958 GCCInstallPath = (LibDir + "/" + LibSuffix + "/" + VersionText).str(); 2959 GCCParentLibPath = (GCCInstallPath + "/../" + Suffix.ReversePath).str(); 2960 IsValid = true; 2961 } 2962 } 2963 } 2964 2965 bool Generic_GCC::GCCInstallationDetector::ScanGentooConfigs( 2966 const llvm::Triple &TargetTriple, const ArgList &Args, 2967 const SmallVectorImpl<StringRef> &CandidateTriples, 2968 const SmallVectorImpl<StringRef> &CandidateBiarchTriples) { 2969 if (!D.getVFS().exists(concat(D.SysRoot, GentooConfigDir))) 2970 return false; 2971 2972 for (StringRef CandidateTriple : CandidateTriples) { 2973 if (ScanGentooGccConfig(TargetTriple, Args, CandidateTriple)) 2974 return true; 2975 } 2976 2977 for (StringRef CandidateTriple : CandidateBiarchTriples) { 2978 if (ScanGentooGccConfig(TargetTriple, Args, CandidateTriple, true)) 2979 return true; 2980 } 2981 return false; 2982 } 2983 2984 bool Generic_GCC::GCCInstallationDetector::ScanGentooGccConfig( 2985 const llvm::Triple &TargetTriple, const ArgList &Args, 2986 StringRef CandidateTriple, bool NeedsBiarchSuffix) { 2987 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> File = 2988 D.getVFS().getBufferForFile(concat(D.SysRoot, GentooConfigDir, 2989 "/config-" + CandidateTriple.str())); 2990 if (File) { 2991 SmallVector<StringRef, 2> Lines; 2992 File.get()->getBuffer().split(Lines, "\n"); 2993 for (StringRef Line : Lines) { 2994 Line = Line.trim(); 2995 // CURRENT=triple-version 2996 if (!Line.consume_front("CURRENT=")) 2997 continue; 2998 // Process the config file pointed to by CURRENT. 2999 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> ConfigFile = 3000 D.getVFS().getBufferForFile( 3001 concat(D.SysRoot, GentooConfigDir, "/" + Line)); 3002 std::pair<StringRef, StringRef> ActiveVersion = Line.rsplit('-'); 3003 // List of paths to scan for libraries. 3004 SmallVector<StringRef, 4> GentooScanPaths; 3005 // Scan the Config file to find installed GCC libraries path. 3006 // Typical content of the GCC config file: 3007 // LDPATH="/usr/lib/gcc/x86_64-pc-linux-gnu/4.9.x:/usr/lib/gcc/ 3008 // (continued from previous line) x86_64-pc-linux-gnu/4.9.x/32" 3009 // MANPATH="/usr/share/gcc-data/x86_64-pc-linux-gnu/4.9.x/man" 3010 // INFOPATH="/usr/share/gcc-data/x86_64-pc-linux-gnu/4.9.x/info" 3011 // STDCXX_INCDIR="/usr/lib/gcc/x86_64-pc-linux-gnu/4.9.x/include/g++-v4" 3012 // We are looking for the paths listed in LDPATH=... . 3013 if (ConfigFile) { 3014 SmallVector<StringRef, 2> ConfigLines; 3015 ConfigFile.get()->getBuffer().split(ConfigLines, "\n"); 3016 for (StringRef ConfLine : ConfigLines) { 3017 ConfLine = ConfLine.trim(); 3018 if (ConfLine.consume_front("LDPATH=")) { 3019 // Drop '"' from front and back if present. 3020 ConfLine.consume_back("\""); 3021 ConfLine.consume_front("\""); 3022 // Get all paths sperated by ':' 3023 ConfLine.split(GentooScanPaths, ':', -1, /*AllowEmpty*/ false); 3024 } 3025 } 3026 } 3027 // Test the path based on the version in /etc/env.d/gcc/config-{tuple}. 3028 std::string basePath = "/usr/lib/gcc/" + ActiveVersion.first.str() + "/" 3029 + ActiveVersion.second.str(); 3030 GentooScanPaths.push_back(StringRef(basePath)); 3031 3032 // Scan all paths for GCC libraries. 3033 for (const auto &GentooScanPath : GentooScanPaths) { 3034 std::string GentooPath = concat(D.SysRoot, GentooScanPath); 3035 if (D.getVFS().exists(GentooPath + "/crtbegin.o")) { 3036 if (!ScanGCCForMultilibs(TargetTriple, Args, GentooPath, 3037 NeedsBiarchSuffix)) 3038 continue; 3039 3040 Version = GCCVersion::Parse(ActiveVersion.second); 3041 GCCInstallPath = GentooPath; 3042 GCCParentLibPath = GentooPath + std::string("/../../.."); 3043 GCCTriple.setTriple(ActiveVersion.first); 3044 IsValid = true; 3045 return true; 3046 } 3047 } 3048 } 3049 } 3050 3051 return false; 3052 } 3053 3054 Generic_GCC::Generic_GCC(const Driver &D, const llvm::Triple &Triple, 3055 const ArgList &Args) 3056 : ToolChain(D, Triple, Args), GCCInstallation(D), 3057 CudaInstallation(D, Triple, Args), RocmInstallation(D, Triple, Args) { 3058 getProgramPaths().push_back(getDriver().Dir); 3059 } 3060 3061 Generic_GCC::~Generic_GCC() {} 3062 3063 Tool *Generic_GCC::getTool(Action::ActionClass AC) const { 3064 switch (AC) { 3065 case Action::PreprocessJobClass: 3066 if (!Preprocess) 3067 Preprocess.reset(new clang::driver::tools::gcc::Preprocessor(*this)); 3068 return Preprocess.get(); 3069 case Action::CompileJobClass: 3070 if (!Compile) 3071 Compile.reset(new tools::gcc::Compiler(*this)); 3072 return Compile.get(); 3073 default: 3074 return ToolChain::getTool(AC); 3075 } 3076 } 3077 3078 Tool *Generic_GCC::buildAssembler() const { 3079 return new tools::gnutools::Assembler(*this); 3080 } 3081 3082 Tool *Generic_GCC::buildLinker() const { return new tools::gcc::Linker(*this); } 3083 3084 void Generic_GCC::printVerboseInfo(raw_ostream &OS) const { 3085 // Print the information about how we detected the GCC installation. 3086 GCCInstallation.print(OS); 3087 CudaInstallation->print(OS); 3088 RocmInstallation->print(OS); 3089 } 3090 3091 ToolChain::UnwindTableLevel 3092 Generic_GCC::getDefaultUnwindTableLevel(const ArgList &Args) const { 3093 switch (getArch()) { 3094 case llvm::Triple::aarch64: 3095 case llvm::Triple::aarch64_be: 3096 case llvm::Triple::ppc: 3097 case llvm::Triple::ppcle: 3098 case llvm::Triple::ppc64: 3099 case llvm::Triple::ppc64le: 3100 case llvm::Triple::riscv32: 3101 case llvm::Triple::riscv64: 3102 case llvm::Triple::x86: 3103 case llvm::Triple::x86_64: 3104 return UnwindTableLevel::Asynchronous; 3105 default: 3106 return UnwindTableLevel::None; 3107 } 3108 } 3109 3110 bool Generic_GCC::isPICDefault() const { 3111 switch (getArch()) { 3112 case llvm::Triple::x86_64: 3113 return getTriple().isOSWindows(); 3114 case llvm::Triple::mips64: 3115 case llvm::Triple::mips64el: 3116 return true; 3117 default: 3118 return false; 3119 } 3120 } 3121 3122 bool Generic_GCC::isPIEDefault(const llvm::opt::ArgList &Args) const { 3123 return false; 3124 } 3125 3126 bool Generic_GCC::isPICDefaultForced() const { 3127 return getArch() == llvm::Triple::x86_64 && getTriple().isOSWindows(); 3128 } 3129 3130 bool Generic_GCC::IsIntegratedAssemblerDefault() const { 3131 switch (getTriple().getArch()) { 3132 case llvm::Triple::nvptx: 3133 case llvm::Triple::nvptx64: 3134 case llvm::Triple::xcore: 3135 return false; 3136 default: 3137 return true; 3138 } 3139 } 3140 3141 void Generic_GCC::PushPPaths(ToolChain::path_list &PPaths) { 3142 // Cross-compiling binutils and GCC installations (vanilla and openSUSE at 3143 // least) put various tools in a triple-prefixed directory off of the parent 3144 // of the GCC installation. We use the GCC triple here to ensure that we end 3145 // up with tools that support the same amount of cross compiling as the 3146 // detected GCC installation. For example, if we find a GCC installation 3147 // targeting x86_64, but it is a bi-arch GCC installation, it can also be 3148 // used to target i386. 3149 if (GCCInstallation.isValid()) { 3150 PPaths.push_back(Twine(GCCInstallation.getParentLibPath() + "/../" + 3151 GCCInstallation.getTriple().str() + "/bin") 3152 .str()); 3153 } 3154 } 3155 3156 void Generic_GCC::AddMultilibPaths(const Driver &D, 3157 const std::string &SysRoot, 3158 const std::string &OSLibDir, 3159 const std::string &MultiarchTriple, 3160 path_list &Paths) { 3161 // Add the multilib suffixed paths where they are available. 3162 if (GCCInstallation.isValid()) { 3163 assert(!SelectedMultilibs.empty()); 3164 const llvm::Triple &GCCTriple = GCCInstallation.getTriple(); 3165 const std::string &LibPath = 3166 std::string(GCCInstallation.getParentLibPath()); 3167 3168 // Sourcery CodeBench MIPS toolchain holds some libraries under 3169 // a biarch-like suffix of the GCC installation. 3170 if (const auto &PathsCallback = Multilibs.filePathsCallback()) 3171 for (const auto &Path : PathsCallback(SelectedMultilibs.back())) 3172 addPathIfExists(D, GCCInstallation.getInstallPath() + Path, Paths); 3173 3174 // Add lib/gcc/$triple/$version, with an optional /multilib suffix. 3175 addPathIfExists(D, 3176 GCCInstallation.getInstallPath() + 3177 SelectedMultilibs.back().gccSuffix(), 3178 Paths); 3179 3180 // Add lib/gcc/$triple/$libdir 3181 // For GCC built with --enable-version-specific-runtime-libs. 3182 addPathIfExists(D, GCCInstallation.getInstallPath() + "/../" + OSLibDir, 3183 Paths); 3184 3185 // GCC cross compiling toolchains will install target libraries which ship 3186 // as part of the toolchain under <prefix>/<triple>/<libdir> rather than as 3187 // any part of the GCC installation in 3188 // <prefix>/<libdir>/gcc/<triple>/<version>. This decision is somewhat 3189 // debatable, but is the reality today. We need to search this tree even 3190 // when we have a sysroot somewhere else. It is the responsibility of 3191 // whomever is doing the cross build targeting a sysroot using a GCC 3192 // installation that is *not* within the system root to ensure two things: 3193 // 3194 // 1) Any DSOs that are linked in from this tree or from the install path 3195 // above must be present on the system root and found via an 3196 // appropriate rpath. 3197 // 2) There must not be libraries installed into 3198 // <prefix>/<triple>/<libdir> unless they should be preferred over 3199 // those within the system root. 3200 // 3201 // Note that this matches the GCC behavior. See the below comment for where 3202 // Clang diverges from GCC's behavior. 3203 addPathIfExists(D, 3204 LibPath + "/../" + GCCTriple.str() + "/lib/../" + OSLibDir + 3205 SelectedMultilibs.back().osSuffix(), 3206 Paths); 3207 3208 // If the GCC installation we found is inside of the sysroot, we want to 3209 // prefer libraries installed in the parent prefix of the GCC installation. 3210 // It is important to *not* use these paths when the GCC installation is 3211 // outside of the system root as that can pick up unintended libraries. 3212 // This usually happens when there is an external cross compiler on the 3213 // host system, and a more minimal sysroot available that is the target of 3214 // the cross. Note that GCC does include some of these directories in some 3215 // configurations but this seems somewhere between questionable and simply 3216 // a bug. 3217 if (StringRef(LibPath).starts_with(SysRoot)) 3218 addPathIfExists(D, LibPath + "/../" + OSLibDir, Paths); 3219 } 3220 } 3221 3222 void Generic_GCC::AddMultiarchPaths(const Driver &D, 3223 const std::string &SysRoot, 3224 const std::string &OSLibDir, 3225 path_list &Paths) { 3226 if (GCCInstallation.isValid()) { 3227 const std::string &LibPath = 3228 std::string(GCCInstallation.getParentLibPath()); 3229 const llvm::Triple &GCCTriple = GCCInstallation.getTriple(); 3230 const Multilib &Multilib = GCCInstallation.getMultilib(); 3231 addPathIfExists( 3232 D, LibPath + "/../" + GCCTriple.str() + "/lib" + Multilib.osSuffix(), 3233 Paths); 3234 } 3235 } 3236 3237 void Generic_GCC::AddMultilibIncludeArgs(const ArgList &DriverArgs, 3238 ArgStringList &CC1Args) const { 3239 // Add include directories specific to the selected multilib set and multilib. 3240 if (!GCCInstallation.isValid()) 3241 return; 3242 // gcc TOOL_INCLUDE_DIR. 3243 const llvm::Triple &GCCTriple = GCCInstallation.getTriple(); 3244 std::string LibPath(GCCInstallation.getParentLibPath()); 3245 addSystemInclude(DriverArgs, CC1Args, 3246 Twine(LibPath) + "/../" + GCCTriple.str() + "/include"); 3247 3248 const auto &Callback = Multilibs.includeDirsCallback(); 3249 if (Callback) { 3250 for (const auto &Path : Callback(GCCInstallation.getMultilib())) 3251 addExternCSystemIncludeIfExists(DriverArgs, CC1Args, 3252 GCCInstallation.getInstallPath() + Path); 3253 } 3254 } 3255 3256 void Generic_GCC::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs, 3257 ArgStringList &CC1Args) const { 3258 if (DriverArgs.hasArg(options::OPT_nostdinc, options::OPT_nostdincxx, 3259 options::OPT_nostdlibinc)) 3260 return; 3261 3262 switch (GetCXXStdlibType(DriverArgs)) { 3263 case ToolChain::CST_Libcxx: 3264 addLibCxxIncludePaths(DriverArgs, CC1Args); 3265 break; 3266 3267 case ToolChain::CST_Libstdcxx: 3268 addLibStdCxxIncludePaths(DriverArgs, CC1Args); 3269 break; 3270 } 3271 } 3272 3273 void 3274 Generic_GCC::addLibCxxIncludePaths(const llvm::opt::ArgList &DriverArgs, 3275 llvm::opt::ArgStringList &CC1Args) const { 3276 const Driver &D = getDriver(); 3277 std::string SysRoot = computeSysRoot(); 3278 if (SysRoot.empty()) 3279 SysRoot = llvm::sys::path::get_separator(); 3280 3281 auto AddIncludePath = [&](StringRef Path, bool TargetDirRequired = false) { 3282 std::string Version = detectLibcxxVersion(Path); 3283 if (Version.empty()) 3284 return false; 3285 3286 // First add the per-target include path if it exists. 3287 bool TargetDirExists = false; 3288 std::optional<std::string> TargetIncludeDir = getTargetSubDirPath(Path); 3289 if (TargetIncludeDir) { 3290 SmallString<128> TargetDir(*TargetIncludeDir); 3291 llvm::sys::path::append(TargetDir, "c++", Version); 3292 if (D.getVFS().exists(TargetDir)) { 3293 addSystemInclude(DriverArgs, CC1Args, TargetDir); 3294 TargetDirExists = true; 3295 } 3296 } 3297 if (TargetDirRequired && !TargetDirExists) 3298 return false; 3299 3300 // Second add the generic one. 3301 SmallString<128> GenericDir(Path); 3302 llvm::sys::path::append(GenericDir, "c++", Version); 3303 addSystemInclude(DriverArgs, CC1Args, GenericDir); 3304 return true; 3305 }; 3306 3307 // Android only uses the libc++ headers installed alongside the toolchain if 3308 // they contain an Android-specific target include path, otherwise they're 3309 // incompatible with the NDK libraries. 3310 SmallString<128> DriverIncludeDir(getDriver().Dir); 3311 llvm::sys::path::append(DriverIncludeDir, "..", "include"); 3312 if (AddIncludePath(DriverIncludeDir, 3313 /*TargetDirRequired=*/getTriple().isAndroid())) 3314 return; 3315 // If this is a development, non-installed, clang, libcxx will 3316 // not be found at ../include/c++ but it likely to be found at 3317 // one of the following two locations: 3318 SmallString<128> UsrLocalIncludeDir(SysRoot); 3319 llvm::sys::path::append(UsrLocalIncludeDir, "usr", "local", "include"); 3320 if (AddIncludePath(UsrLocalIncludeDir)) 3321 return; 3322 SmallString<128> UsrIncludeDir(SysRoot); 3323 llvm::sys::path::append(UsrIncludeDir, "usr", "include"); 3324 if (AddIncludePath(UsrIncludeDir)) 3325 return; 3326 } 3327 3328 bool Generic_GCC::addLibStdCXXIncludePaths(Twine IncludeDir, StringRef Triple, 3329 Twine IncludeSuffix, 3330 const llvm::opt::ArgList &DriverArgs, 3331 llvm::opt::ArgStringList &CC1Args, 3332 bool DetectDebian) const { 3333 if (!getVFS().exists(IncludeDir)) 3334 return false; 3335 3336 // Debian native gcc uses g++-multiarch-incdir.diff which uses 3337 // include/x86_64-linux-gnu/c++/10$IncludeSuffix instead of 3338 // include/c++/10/x86_64-linux-gnu$IncludeSuffix. 3339 std::string Dir = IncludeDir.str(); 3340 StringRef Include = 3341 llvm::sys::path::parent_path(llvm::sys::path::parent_path(Dir)); 3342 std::string Path = 3343 (Include + "/" + Triple + Dir.substr(Include.size()) + IncludeSuffix) 3344 .str(); 3345 if (DetectDebian && !getVFS().exists(Path)) 3346 return false; 3347 3348 // GPLUSPLUS_INCLUDE_DIR 3349 addSystemInclude(DriverArgs, CC1Args, IncludeDir); 3350 // GPLUSPLUS_TOOL_INCLUDE_DIR. If Triple is not empty, add a target-dependent 3351 // include directory. 3352 if (DetectDebian) 3353 addSystemInclude(DriverArgs, CC1Args, Path); 3354 else if (!Triple.empty()) 3355 addSystemInclude(DriverArgs, CC1Args, 3356 IncludeDir + "/" + Triple + IncludeSuffix); 3357 // GPLUSPLUS_BACKWARD_INCLUDE_DIR 3358 addSystemInclude(DriverArgs, CC1Args, IncludeDir + "/backward"); 3359 return true; 3360 } 3361 3362 bool Generic_GCC::addGCCLibStdCxxIncludePaths( 3363 const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, 3364 StringRef DebianMultiarch) const { 3365 assert(GCCInstallation.isValid()); 3366 3367 // By default, look for the C++ headers in an include directory adjacent to 3368 // the lib directory of the GCC installation. Note that this is expect to be 3369 // equivalent to '/usr/include/c++/X.Y' in almost all cases. 3370 StringRef LibDir = GCCInstallation.getParentLibPath(); 3371 StringRef InstallDir = GCCInstallation.getInstallPath(); 3372 StringRef TripleStr = GCCInstallation.getTriple().str(); 3373 const Multilib &Multilib = GCCInstallation.getMultilib(); 3374 const GCCVersion &Version = GCCInstallation.getVersion(); 3375 3376 // Try /../$triple/include/c++/$version (gcc --print-multiarch is not empty). 3377 if (addLibStdCXXIncludePaths( 3378 LibDir.str() + "/../" + TripleStr + "/include/c++/" + Version.Text, 3379 TripleStr, Multilib.includeSuffix(), DriverArgs, CC1Args)) 3380 return true; 3381 3382 // Try /gcc/$triple/$version/include/c++/ (gcc --print-multiarch is not 3383 // empty). Like above but for GCC built with 3384 // --enable-version-specific-runtime-libs. 3385 if (addLibStdCXXIncludePaths(LibDir.str() + "/gcc/" + TripleStr + "/" + 3386 Version.Text + "/include/c++/", 3387 TripleStr, Multilib.includeSuffix(), DriverArgs, 3388 CC1Args)) 3389 return true; 3390 3391 // Detect Debian g++-multiarch-incdir.diff. 3392 if (addLibStdCXXIncludePaths(LibDir.str() + "/../include/c++/" + Version.Text, 3393 DebianMultiarch, Multilib.includeSuffix(), 3394 DriverArgs, CC1Args, /*Debian=*/true)) 3395 return true; 3396 3397 // Try /../include/c++/$version (gcc --print-multiarch is empty). 3398 if (addLibStdCXXIncludePaths(LibDir.str() + "/../include/c++/" + Version.Text, 3399 TripleStr, Multilib.includeSuffix(), DriverArgs, 3400 CC1Args)) 3401 return true; 3402 3403 // Otherwise, fall back on a bunch of options which don't use multiarch 3404 // layouts for simplicity. 3405 const std::string LibStdCXXIncludePathCandidates[] = { 3406 // Gentoo is weird and places its headers inside the GCC install, 3407 // so if the first attempt to find the headers fails, try these patterns. 3408 InstallDir.str() + "/include/g++-v" + Version.Text, 3409 InstallDir.str() + "/include/g++-v" + Version.MajorStr + "." + 3410 Version.MinorStr, 3411 InstallDir.str() + "/include/g++-v" + Version.MajorStr, 3412 }; 3413 3414 for (const auto &IncludePath : LibStdCXXIncludePathCandidates) { 3415 if (addLibStdCXXIncludePaths(IncludePath, TripleStr, 3416 Multilib.includeSuffix(), DriverArgs, CC1Args)) 3417 return true; 3418 } 3419 return false; 3420 } 3421 3422 void 3423 Generic_GCC::addLibStdCxxIncludePaths(const llvm::opt::ArgList &DriverArgs, 3424 llvm::opt::ArgStringList &CC1Args) const { 3425 if (GCCInstallation.isValid()) { 3426 addGCCLibStdCxxIncludePaths(DriverArgs, CC1Args, 3427 GCCInstallation.getTriple().str()); 3428 } 3429 } 3430 3431 llvm::opt::DerivedArgList * 3432 Generic_GCC::TranslateArgs(const llvm::opt::DerivedArgList &Args, StringRef, 3433 Action::OffloadKind DeviceOffloadKind) const { 3434 3435 // If this tool chain is used for an OpenMP offloading device we have to make 3436 // sure we always generate a shared library regardless of the commands the 3437 // user passed to the host. This is required because the runtime library 3438 // is required to load the device image dynamically at run time. 3439 if (DeviceOffloadKind == Action::OFK_OpenMP) { 3440 DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs()); 3441 const OptTable &Opts = getDriver().getOpts(); 3442 3443 // Request the shared library. Given that these options are decided 3444 // implicitly, they do not refer to any base argument. 3445 DAL->AddFlagArg(/*BaseArg=*/nullptr, Opts.getOption(options::OPT_shared)); 3446 DAL->AddFlagArg(/*BaseArg=*/nullptr, Opts.getOption(options::OPT_fPIC)); 3447 3448 // Filter all the arguments we don't care passing to the offloading 3449 // toolchain as they can mess up with the creation of a shared library. 3450 for (auto *A : Args) { 3451 switch ((options::ID)A->getOption().getID()) { 3452 default: 3453 DAL->append(A); 3454 break; 3455 case options::OPT_shared: 3456 case options::OPT_dynamic: 3457 case options::OPT_static: 3458 case options::OPT_fPIC: 3459 case options::OPT_fno_PIC: 3460 case options::OPT_fpic: 3461 case options::OPT_fno_pic: 3462 case options::OPT_fPIE: 3463 case options::OPT_fno_PIE: 3464 case options::OPT_fpie: 3465 case options::OPT_fno_pie: 3466 break; 3467 } 3468 } 3469 return DAL; 3470 } 3471 return nullptr; 3472 } 3473 3474 void Generic_ELF::anchor() {} 3475 3476 void Generic_ELF::addClangTargetOptions(const ArgList &DriverArgs, 3477 ArgStringList &CC1Args, 3478 Action::OffloadKind) const { 3479 if (!DriverArgs.hasFlag(options::OPT_fuse_init_array, 3480 options::OPT_fno_use_init_array, true)) 3481 CC1Args.push_back("-fno-use-init-array"); 3482 } 3483