1 //===--- Driver.cpp - Clang GCC Compatible Driver -------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 #include "clang/Driver/Driver.h" 11 #include "InputInfo.h" 12 #include "ToolChains.h" 13 #include "clang/Basic/Version.h" 14 #include "clang/Basic/VirtualFileSystem.h" 15 #include "clang/Config/config.h" 16 #include "clang/Driver/Action.h" 17 #include "clang/Driver/Compilation.h" 18 #include "clang/Driver/DriverDiagnostic.h" 19 #include "clang/Driver/Job.h" 20 #include "clang/Driver/Options.h" 21 #include "clang/Driver/SanitizerArgs.h" 22 #include "clang/Driver/Tool.h" 23 #include "clang/Driver/ToolChain.h" 24 #include "llvm/ADT/ArrayRef.h" 25 #include "llvm/ADT/STLExtras.h" 26 #include "llvm/ADT/StringExtras.h" 27 #include "llvm/ADT/StringSet.h" 28 #include "llvm/ADT/StringSwitch.h" 29 #include "llvm/Option/Arg.h" 30 #include "llvm/Option/ArgList.h" 31 #include "llvm/Option/OptSpecifier.h" 32 #include "llvm/Option/OptTable.h" 33 #include "llvm/Option/Option.h" 34 #include "llvm/Support/Debug.h" 35 #include "llvm/Support/ErrorHandling.h" 36 #include "llvm/Support/FileSystem.h" 37 #include "llvm/Support/Path.h" 38 #include "llvm/Support/PrettyStackTrace.h" 39 #include "llvm/Support/Process.h" 40 #include "llvm/Support/Program.h" 41 #include "llvm/Support/raw_ostream.h" 42 #include <map> 43 #include <memory> 44 #include <utility> 45 46 using namespace clang::driver; 47 using namespace clang; 48 using namespace llvm::opt; 49 50 Driver::Driver(StringRef ClangExecutable, StringRef DefaultTargetTriple, 51 DiagnosticsEngine &Diags, 52 IntrusiveRefCntPtr<vfs::FileSystem> VFS) 53 : Opts(createDriverOptTable()), Diags(Diags), VFS(std::move(VFS)), 54 Mode(GCCMode), SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone), 55 LTOMode(LTOK_None), ClangExecutable(ClangExecutable), 56 SysRoot(DEFAULT_SYSROOT), UseStdLib(true), 57 DefaultTargetTriple(DefaultTargetTriple), 58 DriverTitle("clang LLVM compiler"), CCPrintOptionsFilename(nullptr), 59 CCPrintHeadersFilename(nullptr), CCLogDiagnosticsFilename(nullptr), 60 CCCPrintBindings(false), CCPrintHeaders(false), CCLogDiagnostics(false), 61 CCGenDiagnostics(false), CCCGenericGCCName(""), CheckInputsExist(true), 62 CCCUsePCH(true), SuppressMissingInputWarning(false) { 63 64 // Provide a sane fallback if no VFS is specified. 65 if (!this->VFS) 66 this->VFS = vfs::getRealFileSystem(); 67 68 Name = llvm::sys::path::filename(ClangExecutable); 69 Dir = llvm::sys::path::parent_path(ClangExecutable); 70 InstalledDir = Dir; // Provide a sensible default installed dir. 71 72 // Compute the path to the resource directory. 73 StringRef ClangResourceDir(CLANG_RESOURCE_DIR); 74 SmallString<128> P(Dir); 75 if (ClangResourceDir != "") { 76 llvm::sys::path::append(P, ClangResourceDir); 77 } else { 78 StringRef ClangLibdirSuffix(CLANG_LIBDIR_SUFFIX); 79 llvm::sys::path::append(P, "..", Twine("lib") + ClangLibdirSuffix, "clang", 80 CLANG_VERSION_STRING); 81 } 82 ResourceDir = P.str(); 83 } 84 85 Driver::~Driver() { 86 delete Opts; 87 88 llvm::DeleteContainerSeconds(ToolChains); 89 } 90 91 void Driver::ParseDriverMode(ArrayRef<const char *> Args) { 92 const std::string OptName = 93 getOpts().getOption(options::OPT_driver_mode).getPrefixedName(); 94 95 for (const char *ArgPtr : Args) { 96 // Ingore nullptrs, they are response file's EOL markers 97 if (ArgPtr == nullptr) 98 continue; 99 const StringRef Arg = ArgPtr; 100 if (!Arg.startswith(OptName)) 101 continue; 102 103 const StringRef Value = Arg.drop_front(OptName.size()); 104 const unsigned M = llvm::StringSwitch<unsigned>(Value) 105 .Case("gcc", GCCMode) 106 .Case("g++", GXXMode) 107 .Case("cpp", CPPMode) 108 .Case("cl", CLMode) 109 .Default(~0U); 110 111 if (M != ~0U) 112 Mode = static_cast<DriverMode>(M); 113 else 114 Diag(diag::err_drv_unsupported_option_argument) << OptName << Value; 115 } 116 } 117 118 InputArgList Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings) { 119 llvm::PrettyStackTraceString CrashInfo("Command line argument parsing"); 120 121 unsigned IncludedFlagsBitmask; 122 unsigned ExcludedFlagsBitmask; 123 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) = 124 getIncludeExcludeOptionFlagMasks(); 125 126 unsigned MissingArgIndex, MissingArgCount; 127 InputArgList Args = 128 getOpts().ParseArgs(ArgStrings, MissingArgIndex, MissingArgCount, 129 IncludedFlagsBitmask, ExcludedFlagsBitmask); 130 131 // Check for missing argument error. 132 if (MissingArgCount) 133 Diag(clang::diag::err_drv_missing_argument) 134 << Args.getArgString(MissingArgIndex) << MissingArgCount; 135 136 // Check for unsupported options. 137 for (const Arg *A : Args) { 138 if (A->getOption().hasFlag(options::Unsupported)) { 139 Diag(clang::diag::err_drv_unsupported_opt) << A->getAsString(Args); 140 continue; 141 } 142 143 // Warn about -mcpu= without an argument. 144 if (A->getOption().matches(options::OPT_mcpu_EQ) && A->containsValue("")) { 145 Diag(clang::diag::warn_drv_empty_joined_argument) << A->getAsString(Args); 146 } 147 } 148 149 for (const Arg *A : Args.filtered(options::OPT_UNKNOWN)) 150 Diags.Report(IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl : 151 diag::err_drv_unknown_argument) 152 << A->getAsString(Args); 153 154 return Args; 155 } 156 157 // Determine which compilation mode we are in. We look for options which 158 // affect the phase, starting with the earliest phases, and record which 159 // option we used to determine the final phase. 160 phases::ID Driver::getFinalPhase(const DerivedArgList &DAL, 161 Arg **FinalPhaseArg) const { 162 Arg *PhaseArg = nullptr; 163 phases::ID FinalPhase; 164 165 // -{E,EP,P,M,MM} only run the preprocessor. 166 if (CCCIsCPP() || (PhaseArg = DAL.getLastArg(options::OPT_E)) || 167 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_EP)) || 168 (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM)) || 169 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_P))) { 170 FinalPhase = phases::Preprocess; 171 172 // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler. 173 } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) || 174 (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) || 175 (PhaseArg = DAL.getLastArg(options::OPT_verify_pch)) || 176 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) || 177 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) || 178 (PhaseArg = DAL.getLastArg(options::OPT__migrate)) || 179 (PhaseArg = DAL.getLastArg(options::OPT__analyze, 180 options::OPT__analyze_auto)) || 181 (PhaseArg = DAL.getLastArg(options::OPT_emit_ast))) { 182 FinalPhase = phases::Compile; 183 184 // -S only runs up to the backend. 185 } else if ((PhaseArg = DAL.getLastArg(options::OPT_S))) { 186 FinalPhase = phases::Backend; 187 188 // -c compilation only runs up to the assembler. 189 } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) { 190 FinalPhase = phases::Assemble; 191 192 // Otherwise do everything. 193 } else 194 FinalPhase = phases::Link; 195 196 if (FinalPhaseArg) 197 *FinalPhaseArg = PhaseArg; 198 199 return FinalPhase; 200 } 201 202 static Arg *MakeInputArg(DerivedArgList &Args, OptTable *Opts, 203 StringRef Value) { 204 Arg *A = new Arg(Opts->getOption(options::OPT_INPUT), Value, 205 Args.getBaseArgs().MakeIndex(Value), Value.data()); 206 Args.AddSynthesizedArg(A); 207 A->claim(); 208 return A; 209 } 210 211 DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const { 212 DerivedArgList *DAL = new DerivedArgList(Args); 213 214 bool HasNostdlib = Args.hasArg(options::OPT_nostdlib); 215 bool HasNodefaultlib = Args.hasArg(options::OPT_nodefaultlibs); 216 for (Arg *A : Args) { 217 // Unfortunately, we have to parse some forwarding options (-Xassembler, 218 // -Xlinker, -Xpreprocessor) because we either integrate their functionality 219 // (assembler and preprocessor), or bypass a previous driver ('collect2'). 220 221 // Rewrite linker options, to replace --no-demangle with a custom internal 222 // option. 223 if ((A->getOption().matches(options::OPT_Wl_COMMA) || 224 A->getOption().matches(options::OPT_Xlinker)) && 225 A->containsValue("--no-demangle")) { 226 // Add the rewritten no-demangle argument. 227 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_Xlinker__no_demangle)); 228 229 // Add the remaining values as Xlinker arguments. 230 for (StringRef Val : A->getValues()) 231 if (Val != "--no-demangle") 232 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_Xlinker), Val); 233 234 continue; 235 } 236 237 // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by 238 // some build systems. We don't try to be complete here because we don't 239 // care to encourage this usage model. 240 if (A->getOption().matches(options::OPT_Wp_COMMA) && 241 (A->getValue(0) == StringRef("-MD") || 242 A->getValue(0) == StringRef("-MMD"))) { 243 // Rewrite to -MD/-MMD along with -MF. 244 if (A->getValue(0) == StringRef("-MD")) 245 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MD)); 246 else 247 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD)); 248 if (A->getNumValues() == 2) 249 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF), 250 A->getValue(1)); 251 continue; 252 } 253 254 // Rewrite reserved library names. 255 if (A->getOption().matches(options::OPT_l)) { 256 StringRef Value = A->getValue(); 257 258 // Rewrite unless -nostdlib is present. 259 if (!HasNostdlib && !HasNodefaultlib && Value == "stdc++") { 260 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_stdcxx)); 261 continue; 262 } 263 264 // Rewrite unconditionally. 265 if (Value == "cc_kext") { 266 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_cckext)); 267 continue; 268 } 269 } 270 271 // Pick up inputs via the -- option. 272 if (A->getOption().matches(options::OPT__DASH_DASH)) { 273 A->claim(); 274 for (StringRef Val : A->getValues()) 275 DAL->append(MakeInputArg(*DAL, Opts, Val)); 276 continue; 277 } 278 279 DAL->append(A); 280 } 281 282 // Enforce -static if -miamcu is present. 283 if (Args.hasArg(options::OPT_miamcu)) 284 DAL->AddFlagArg(0, Opts->getOption(options::OPT_static)); 285 286 // Add a default value of -mlinker-version=, if one was given and the user 287 // didn't specify one. 288 #if defined(HOST_LINK_VERSION) 289 if (!Args.hasArg(options::OPT_mlinker_version_EQ) && 290 strlen(HOST_LINK_VERSION) > 0) { 291 DAL->AddJoinedArg(0, Opts->getOption(options::OPT_mlinker_version_EQ), 292 HOST_LINK_VERSION); 293 DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim(); 294 } 295 #endif 296 297 return DAL; 298 } 299 300 /// \brief Compute target triple from args. 301 /// 302 /// This routine provides the logic to compute a target triple from various 303 /// args passed to the driver and the default triple string. 304 static llvm::Triple computeTargetTriple(const Driver &D, 305 StringRef DefaultTargetTriple, 306 const ArgList &Args, 307 StringRef DarwinArchName = "") { 308 // FIXME: Already done in Compilation *Driver::BuildCompilation 309 if (const Arg *A = Args.getLastArg(options::OPT_target)) 310 DefaultTargetTriple = A->getValue(); 311 312 llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple)); 313 314 // Handle Apple-specific options available here. 315 if (Target.isOSBinFormatMachO()) { 316 // If an explict Darwin arch name is given, that trumps all. 317 if (!DarwinArchName.empty()) { 318 tools::darwin::setTripleTypeForMachOArchName(Target, DarwinArchName); 319 return Target; 320 } 321 322 // Handle the Darwin '-arch' flag. 323 if (Arg *A = Args.getLastArg(options::OPT_arch)) { 324 StringRef ArchName = A->getValue(); 325 tools::darwin::setTripleTypeForMachOArchName(Target, ArchName); 326 } 327 } 328 329 // Handle pseudo-target flags '-mlittle-endian'/'-EL' and 330 // '-mbig-endian'/'-EB'. 331 if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian, 332 options::OPT_mbig_endian)) { 333 if (A->getOption().matches(options::OPT_mlittle_endian)) { 334 llvm::Triple LE = Target.getLittleEndianArchVariant(); 335 if (LE.getArch() != llvm::Triple::UnknownArch) 336 Target = std::move(LE); 337 } else { 338 llvm::Triple BE = Target.getBigEndianArchVariant(); 339 if (BE.getArch() != llvm::Triple::UnknownArch) 340 Target = std::move(BE); 341 } 342 } 343 344 // Skip further flag support on OSes which don't support '-m32' or '-m64'. 345 if (Target.getArch() == llvm::Triple::tce || 346 Target.getOS() == llvm::Triple::Minix) 347 return Target; 348 349 // Handle pseudo-target flags '-m64', '-mx32', '-m32' and '-m16'. 350 Arg *A = Args.getLastArg(options::OPT_m64, options::OPT_mx32, 351 options::OPT_m32, options::OPT_m16); 352 if (A) { 353 llvm::Triple::ArchType AT = llvm::Triple::UnknownArch; 354 355 if (A->getOption().matches(options::OPT_m64)) { 356 AT = Target.get64BitArchVariant().getArch(); 357 if (Target.getEnvironment() == llvm::Triple::GNUX32) 358 Target.setEnvironment(llvm::Triple::GNU); 359 } else if (A->getOption().matches(options::OPT_mx32) && 360 Target.get64BitArchVariant().getArch() == llvm::Triple::x86_64) { 361 AT = llvm::Triple::x86_64; 362 Target.setEnvironment(llvm::Triple::GNUX32); 363 } else if (A->getOption().matches(options::OPT_m32)) { 364 AT = Target.get32BitArchVariant().getArch(); 365 if (Target.getEnvironment() == llvm::Triple::GNUX32) 366 Target.setEnvironment(llvm::Triple::GNU); 367 } else if (A->getOption().matches(options::OPT_m16) && 368 Target.get32BitArchVariant().getArch() == llvm::Triple::x86) { 369 AT = llvm::Triple::x86; 370 Target.setEnvironment(llvm::Triple::CODE16); 371 } 372 373 if (AT != llvm::Triple::UnknownArch && AT != Target.getArch()) 374 Target.setArch(AT); 375 } 376 377 // Handle -miamcu flag. 378 if (Args.hasArg(options::OPT_miamcu)) { 379 if (Target.get32BitArchVariant().getArch() != llvm::Triple::x86) 380 D.Diag(diag::err_drv_unsupported_opt_for_target) << "-miamcu" 381 << Target.str(); 382 383 if (A && !A->getOption().matches(options::OPT_m32)) 384 D.Diag(diag::err_drv_argument_not_allowed_with) 385 << "-miamcu" << A->getBaseArg().getAsString(Args); 386 387 Target.setArch(llvm::Triple::x86); 388 Target.setArchName("i586"); 389 Target.setEnvironment(llvm::Triple::UnknownEnvironment); 390 Target.setEnvironmentName(""); 391 Target.setOS(llvm::Triple::ELFIAMCU); 392 Target.setVendor(llvm::Triple::UnknownVendor); 393 Target.setVendorName("intel"); 394 } 395 396 return Target; 397 } 398 399 // \brief Parse the LTO options and record the type of LTO compilation 400 // based on which -f(no-)?lto(=.*)? option occurs last. 401 void Driver::setLTOMode(const llvm::opt::ArgList &Args) { 402 LTOMode = LTOK_None; 403 if (!Args.hasFlag(options::OPT_flto, options::OPT_flto_EQ, 404 options::OPT_fno_lto, false)) 405 return; 406 407 StringRef LTOName("full"); 408 409 const Arg *A = Args.getLastArg(options::OPT_flto_EQ); 410 if (A) 411 LTOName = A->getValue(); 412 413 LTOMode = llvm::StringSwitch<LTOKind>(LTOName) 414 .Case("full", LTOK_Full) 415 .Case("thin", LTOK_Thin) 416 .Default(LTOK_Unknown); 417 418 if (LTOMode == LTOK_Unknown) { 419 assert(A); 420 Diag(diag::err_drv_unsupported_option_argument) << A->getOption().getName() 421 << A->getValue(); 422 } 423 } 424 425 Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) { 426 llvm::PrettyStackTraceString CrashInfo("Compilation construction"); 427 428 // FIXME: Handle environment options which affect driver behavior, somewhere 429 // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS. 430 431 if (char *env = ::getenv("COMPILER_PATH")) { 432 StringRef CompilerPath = env; 433 while (!CompilerPath.empty()) { 434 std::pair<StringRef, StringRef> Split = 435 CompilerPath.split(llvm::sys::EnvPathSeparator); 436 PrefixDirs.push_back(Split.first); 437 CompilerPath = Split.second; 438 } 439 } 440 441 // We look for the driver mode option early, because the mode can affect 442 // how other options are parsed. 443 ParseDriverMode(ArgList.slice(1)); 444 445 // FIXME: What are we going to do with -V and -b? 446 447 // FIXME: This stuff needs to go into the Compilation, not the driver. 448 bool CCCPrintPhases; 449 450 InputArgList Args = ParseArgStrings(ArgList.slice(1)); 451 452 // Silence driver warnings if requested 453 Diags.setIgnoreAllWarnings(Args.hasArg(options::OPT_w)); 454 455 // -no-canonical-prefixes is used very early in main. 456 Args.ClaimAllArgs(options::OPT_no_canonical_prefixes); 457 458 // Ignore -pipe. 459 Args.ClaimAllArgs(options::OPT_pipe); 460 461 // Extract -ccc args. 462 // 463 // FIXME: We need to figure out where this behavior should live. Most of it 464 // should be outside in the client; the parts that aren't should have proper 465 // options, either by introducing new ones or by overloading gcc ones like -V 466 // or -b. 467 CCCPrintPhases = Args.hasArg(options::OPT_ccc_print_phases); 468 CCCPrintBindings = Args.hasArg(options::OPT_ccc_print_bindings); 469 if (const Arg *A = Args.getLastArg(options::OPT_ccc_gcc_name)) 470 CCCGenericGCCName = A->getValue(); 471 CCCUsePCH = 472 Args.hasFlag(options::OPT_ccc_pch_is_pch, options::OPT_ccc_pch_is_pth); 473 // FIXME: DefaultTargetTriple is used by the target-prefixed calls to as/ld 474 // and getToolChain is const. 475 if (IsCLMode()) { 476 // clang-cl targets MSVC-style Win32. 477 llvm::Triple T(DefaultTargetTriple); 478 T.setOS(llvm::Triple::Win32); 479 T.setVendor(llvm::Triple::PC); 480 T.setEnvironment(llvm::Triple::MSVC); 481 DefaultTargetTriple = T.str(); 482 } 483 if (const Arg *A = Args.getLastArg(options::OPT_target)) 484 DefaultTargetTriple = A->getValue(); 485 if (const Arg *A = Args.getLastArg(options::OPT_ccc_install_dir)) 486 Dir = InstalledDir = A->getValue(); 487 for (const Arg *A : Args.filtered(options::OPT_B)) { 488 A->claim(); 489 PrefixDirs.push_back(A->getValue(0)); 490 } 491 if (const Arg *A = Args.getLastArg(options::OPT__sysroot_EQ)) 492 SysRoot = A->getValue(); 493 if (const Arg *A = Args.getLastArg(options::OPT__dyld_prefix_EQ)) 494 DyldPrefix = A->getValue(); 495 if (Args.hasArg(options::OPT_nostdlib)) 496 UseStdLib = false; 497 498 if (const Arg *A = Args.getLastArg(options::OPT_resource_dir)) 499 ResourceDir = A->getValue(); 500 501 if (const Arg *A = Args.getLastArg(options::OPT_save_temps_EQ)) { 502 SaveTemps = llvm::StringSwitch<SaveTempsMode>(A->getValue()) 503 .Case("cwd", SaveTempsCwd) 504 .Case("obj", SaveTempsObj) 505 .Default(SaveTempsCwd); 506 } 507 508 setLTOMode(Args); 509 510 // Ignore -fembed-bitcode options with LTO 511 // since the output will be bitcode anyway. 512 if (getLTOMode() == LTOK_None) { 513 if (Arg *A = Args.getLastArg(options::OPT_fembed_bitcode_EQ)) { 514 StringRef Name = A->getValue(); 515 unsigned Model = llvm::StringSwitch<unsigned>(Name) 516 .Case("off", EmbedNone) 517 .Case("all", EmbedBitcode) 518 .Case("bitcode", EmbedBitcode) 519 .Case("marker", EmbedMarker) 520 .Default(~0U); 521 if (Model == ~0U) { 522 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) 523 << Name; 524 } else 525 BitcodeEmbed = static_cast<BitcodeEmbedMode>(Model); 526 } 527 } else { 528 // claim the bitcode option under LTO so no warning is issued. 529 Args.ClaimAllArgs(options::OPT_fembed_bitcode_EQ); 530 } 531 532 std::unique_ptr<llvm::opt::InputArgList> UArgs = 533 llvm::make_unique<InputArgList>(std::move(Args)); 534 535 // Perform the default argument translations. 536 DerivedArgList *TranslatedArgs = TranslateInputArgs(*UArgs); 537 538 // Owned by the host. 539 const ToolChain &TC = getToolChain( 540 *UArgs, computeTargetTriple(*this, DefaultTargetTriple, *UArgs)); 541 542 // The compilation takes ownership of Args. 543 Compilation *C = new Compilation(*this, TC, UArgs.release(), TranslatedArgs); 544 545 if (!HandleImmediateArgs(*C)) 546 return C; 547 548 // Construct the list of inputs. 549 InputList Inputs; 550 BuildInputs(C->getDefaultToolChain(), *TranslatedArgs, Inputs); 551 552 // Initialize the CUDA device TC only if we have any CUDA Inputs. This is 553 // necessary so that we don't break compilations that pass flags that are 554 // incompatible with the NVPTX TC (e.g. -mthread-model single). 555 if (llvm::any_of(Inputs, [](const std::pair<types::ID, const Arg *> &I) { 556 return I.first == types::TY_CUDA || I.first == types::TY_PP_CUDA || 557 I.first == types::TY_CUDA_DEVICE; 558 })) { 559 C->setCudaDeviceToolChain( 560 &getToolChain(C->getArgs(), llvm::Triple(TC.getTriple().isArch64Bit() 561 ? "nvptx64-nvidia-cuda" 562 : "nvptx-nvidia-cuda"))); 563 } 564 565 // Construct the list of abstract actions to perform for this compilation. On 566 // MachO targets this uses the driver-driver and universal actions. 567 if (TC.getTriple().isOSBinFormatMachO()) 568 BuildUniversalActions(*C, C->getDefaultToolChain(), Inputs); 569 else 570 BuildActions(*C, C->getArgs(), Inputs, C->getActions()); 571 572 if (CCCPrintPhases) { 573 PrintActions(*C); 574 return C; 575 } 576 577 BuildJobs(*C); 578 579 return C; 580 } 581 582 static void printArgList(raw_ostream &OS, const llvm::opt::ArgList &Args) { 583 llvm::opt::ArgStringList ASL; 584 for (const auto *A : Args) 585 A->render(Args, ASL); 586 587 for (auto I = ASL.begin(), E = ASL.end(); I != E; ++I) { 588 if (I != ASL.begin()) 589 OS << ' '; 590 Command::printArg(OS, *I, true); 591 } 592 OS << '\n'; 593 } 594 595 // When clang crashes, produce diagnostic information including the fully 596 // preprocessed source file(s). Request that the developer attach the 597 // diagnostic information to a bug report. 598 void Driver::generateCompilationDiagnostics(Compilation &C, 599 const Command &FailingCommand) { 600 if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics)) 601 return; 602 603 // Don't try to generate diagnostics for link or dsymutil jobs. 604 if (FailingCommand.getCreator().isLinkJob() || 605 FailingCommand.getCreator().isDsymutilJob()) 606 return; 607 608 // Print the version of the compiler. 609 PrintVersion(C, llvm::errs()); 610 611 Diag(clang::diag::note_drv_command_failed_diag_msg) 612 << "PLEASE submit a bug report to " BUG_REPORT_URL " and include the " 613 "crash backtrace, preprocessed source, and associated run script."; 614 615 // Suppress driver output and emit preprocessor output to temp file. 616 Mode = CPPMode; 617 CCGenDiagnostics = true; 618 619 // Save the original job command(s). 620 Command Cmd = FailingCommand; 621 622 // Keep track of whether we produce any errors while trying to produce 623 // preprocessed sources. 624 DiagnosticErrorTrap Trap(Diags); 625 626 // Suppress tool output. 627 C.initCompilationForDiagnostics(); 628 629 // Construct the list of inputs. 630 InputList Inputs; 631 BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs); 632 633 for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) { 634 bool IgnoreInput = false; 635 636 // Ignore input from stdin or any inputs that cannot be preprocessed. 637 // Check type first as not all linker inputs have a value. 638 if (types::getPreprocessedType(it->first) == types::TY_INVALID) { 639 IgnoreInput = true; 640 } else if (!strcmp(it->second->getValue(), "-")) { 641 Diag(clang::diag::note_drv_command_failed_diag_msg) 642 << "Error generating preprocessed source(s) - " 643 "ignoring input from stdin."; 644 IgnoreInput = true; 645 } 646 647 if (IgnoreInput) { 648 it = Inputs.erase(it); 649 ie = Inputs.end(); 650 } else { 651 ++it; 652 } 653 } 654 655 if (Inputs.empty()) { 656 Diag(clang::diag::note_drv_command_failed_diag_msg) 657 << "Error generating preprocessed source(s) - " 658 "no preprocessable inputs."; 659 return; 660 } 661 662 // Don't attempt to generate preprocessed files if multiple -arch options are 663 // used, unless they're all duplicates. 664 llvm::StringSet<> ArchNames; 665 for (const Arg *A : C.getArgs()) { 666 if (A->getOption().matches(options::OPT_arch)) { 667 StringRef ArchName = A->getValue(); 668 ArchNames.insert(ArchName); 669 } 670 } 671 if (ArchNames.size() > 1) { 672 Diag(clang::diag::note_drv_command_failed_diag_msg) 673 << "Error generating preprocessed source(s) - cannot generate " 674 "preprocessed source with multiple -arch options."; 675 return; 676 } 677 678 // Construct the list of abstract actions to perform for this compilation. On 679 // Darwin OSes this uses the driver-driver and builds universal actions. 680 const ToolChain &TC = C.getDefaultToolChain(); 681 if (TC.getTriple().isOSBinFormatMachO()) 682 BuildUniversalActions(C, TC, Inputs); 683 else 684 BuildActions(C, C.getArgs(), Inputs, C.getActions()); 685 686 BuildJobs(C); 687 688 // If there were errors building the compilation, quit now. 689 if (Trap.hasErrorOccurred()) { 690 Diag(clang::diag::note_drv_command_failed_diag_msg) 691 << "Error generating preprocessed source(s)."; 692 return; 693 } 694 695 // Generate preprocessed output. 696 SmallVector<std::pair<int, const Command *>, 4> FailingCommands; 697 C.ExecuteJobs(C.getJobs(), FailingCommands); 698 699 // If any of the preprocessing commands failed, clean up and exit. 700 if (!FailingCommands.empty()) { 701 if (!isSaveTempsEnabled()) 702 C.CleanupFileList(C.getTempFiles(), true); 703 704 Diag(clang::diag::note_drv_command_failed_diag_msg) 705 << "Error generating preprocessed source(s)."; 706 return; 707 } 708 709 const ArgStringList &TempFiles = C.getTempFiles(); 710 if (TempFiles.empty()) { 711 Diag(clang::diag::note_drv_command_failed_diag_msg) 712 << "Error generating preprocessed source(s)."; 713 return; 714 } 715 716 Diag(clang::diag::note_drv_command_failed_diag_msg) 717 << "\n********************\n\n" 718 "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n" 719 "Preprocessed source(s) and associated run script(s) are located at:"; 720 721 SmallString<128> VFS; 722 for (const char *TempFile : TempFiles) { 723 Diag(clang::diag::note_drv_command_failed_diag_msg) << TempFile; 724 if (StringRef(TempFile).endswith(".cache")) { 725 // In some cases (modules) we'll dump extra data to help with reproducing 726 // the crash into a directory next to the output. 727 VFS = llvm::sys::path::filename(TempFile); 728 llvm::sys::path::append(VFS, "vfs", "vfs.yaml"); 729 } 730 } 731 732 // Assume associated files are based off of the first temporary file. 733 CrashReportInfo CrashInfo(TempFiles[0], VFS); 734 735 std::string Script = CrashInfo.Filename.rsplit('.').first.str() + ".sh"; 736 std::error_code EC; 737 llvm::raw_fd_ostream ScriptOS(Script, EC, llvm::sys::fs::F_Excl); 738 if (EC) { 739 Diag(clang::diag::note_drv_command_failed_diag_msg) 740 << "Error generating run script: " + Script + " " + EC.message(); 741 } else { 742 ScriptOS << "# Crash reproducer for " << getClangFullVersion() << "\n" 743 << "# Driver args: "; 744 printArgList(ScriptOS, C.getInputArgs()); 745 ScriptOS << "# Original command: "; 746 Cmd.Print(ScriptOS, "\n", /*Quote=*/true); 747 Cmd.Print(ScriptOS, "\n", /*Quote=*/true, &CrashInfo); 748 Diag(clang::diag::note_drv_command_failed_diag_msg) << Script; 749 } 750 751 for (const auto &A : C.getArgs().filtered(options::OPT_frewrite_map_file, 752 options::OPT_frewrite_map_file_EQ)) 753 Diag(clang::diag::note_drv_command_failed_diag_msg) << A->getValue(); 754 755 Diag(clang::diag::note_drv_command_failed_diag_msg) 756 << "\n\n********************"; 757 } 758 759 void Driver::setUpResponseFiles(Compilation &C, Command &Cmd) { 760 // Since commandLineFitsWithinSystemLimits() may underestimate system's capacity 761 // if the tool does not support response files, there is a chance/ that things 762 // will just work without a response file, so we silently just skip it. 763 if (Cmd.getCreator().getResponseFilesSupport() == Tool::RF_None || 764 llvm::sys::commandLineFitsWithinSystemLimits(Cmd.getExecutable(), Cmd.getArguments())) 765 return; 766 767 std::string TmpName = GetTemporaryPath("response", "txt"); 768 Cmd.setResponseFile( 769 C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str()))); 770 } 771 772 int Driver::ExecuteCompilation( 773 Compilation &C, 774 SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) { 775 // Just print if -### was present. 776 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) { 777 C.getJobs().Print(llvm::errs(), "\n", true); 778 return 0; 779 } 780 781 // If there were errors building the compilation, quit now. 782 if (Diags.hasErrorOccurred()) 783 return 1; 784 785 // Set up response file names for each command, if necessary 786 for (auto &Job : C.getJobs()) 787 setUpResponseFiles(C, Job); 788 789 C.ExecuteJobs(C.getJobs(), FailingCommands); 790 791 // Remove temp files. 792 C.CleanupFileList(C.getTempFiles()); 793 794 // If the command succeeded, we are done. 795 if (FailingCommands.empty()) 796 return 0; 797 798 // Otherwise, remove result files and print extra information about abnormal 799 // failures. 800 for (const auto &CmdPair : FailingCommands) { 801 int Res = CmdPair.first; 802 const Command *FailingCommand = CmdPair.second; 803 804 // Remove result files if we're not saving temps. 805 if (!isSaveTempsEnabled()) { 806 const JobAction *JA = cast<JobAction>(&FailingCommand->getSource()); 807 C.CleanupFileMap(C.getResultFiles(), JA, true); 808 809 // Failure result files are valid unless we crashed. 810 if (Res < 0) 811 C.CleanupFileMap(C.getFailureResultFiles(), JA, true); 812 } 813 814 // Print extra information about abnormal failures, if possible. 815 // 816 // This is ad-hoc, but we don't want to be excessively noisy. If the result 817 // status was 1, assume the command failed normally. In particular, if it 818 // was the compiler then assume it gave a reasonable error code. Failures 819 // in other tools are less common, and they generally have worse 820 // diagnostics, so always print the diagnostic there. 821 const Tool &FailingTool = FailingCommand->getCreator(); 822 823 if (!FailingCommand->getCreator().hasGoodDiagnostics() || Res != 1) { 824 // FIXME: See FIXME above regarding result code interpretation. 825 if (Res < 0) 826 Diag(clang::diag::err_drv_command_signalled) 827 << FailingTool.getShortName(); 828 else 829 Diag(clang::diag::err_drv_command_failed) << FailingTool.getShortName() 830 << Res; 831 } 832 } 833 return 0; 834 } 835 836 void Driver::PrintHelp(bool ShowHidden) const { 837 unsigned IncludedFlagsBitmask; 838 unsigned ExcludedFlagsBitmask; 839 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) = 840 getIncludeExcludeOptionFlagMasks(); 841 842 ExcludedFlagsBitmask |= options::NoDriverOption; 843 if (!ShowHidden) 844 ExcludedFlagsBitmask |= HelpHidden; 845 846 getOpts().PrintHelp(llvm::outs(), Name.c_str(), DriverTitle.c_str(), 847 IncludedFlagsBitmask, ExcludedFlagsBitmask); 848 } 849 850 void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const { 851 // FIXME: The following handlers should use a callback mechanism, we don't 852 // know what the client would like to do. 853 OS << getClangFullVersion() << '\n'; 854 const ToolChain &TC = C.getDefaultToolChain(); 855 OS << "Target: " << TC.getTripleString() << '\n'; 856 857 // Print the threading model. 858 if (Arg *A = C.getArgs().getLastArg(options::OPT_mthread_model)) { 859 // Don't print if the ToolChain would have barfed on it already 860 if (TC.isThreadModelSupported(A->getValue())) 861 OS << "Thread model: " << A->getValue(); 862 } else 863 OS << "Thread model: " << TC.getThreadModel(); 864 OS << '\n'; 865 866 // Print out the install directory. 867 OS << "InstalledDir: " << InstalledDir << '\n'; 868 } 869 870 /// PrintDiagnosticCategories - Implement the --print-diagnostic-categories 871 /// option. 872 static void PrintDiagnosticCategories(raw_ostream &OS) { 873 // Skip the empty category. 874 for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); i != max; 875 ++i) 876 OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n'; 877 } 878 879 bool Driver::HandleImmediateArgs(const Compilation &C) { 880 // The order these options are handled in gcc is all over the place, but we 881 // don't expect inconsistencies w.r.t. that to matter in practice. 882 883 if (C.getArgs().hasArg(options::OPT_dumpmachine)) { 884 llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n'; 885 return false; 886 } 887 888 if (C.getArgs().hasArg(options::OPT_dumpversion)) { 889 // Since -dumpversion is only implemented for pedantic GCC compatibility, we 890 // return an answer which matches our definition of __VERSION__. 891 // 892 // If we want to return a more correct answer some day, then we should 893 // introduce a non-pedantically GCC compatible mode to Clang in which we 894 // provide sensible definitions for -dumpversion, __VERSION__, etc. 895 llvm::outs() << "4.2.1\n"; 896 return false; 897 } 898 899 if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) { 900 PrintDiagnosticCategories(llvm::outs()); 901 return false; 902 } 903 904 if (C.getArgs().hasArg(options::OPT_help) || 905 C.getArgs().hasArg(options::OPT__help_hidden)) { 906 PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden)); 907 return false; 908 } 909 910 if (C.getArgs().hasArg(options::OPT__version)) { 911 // Follow gcc behavior and use stdout for --version and stderr for -v. 912 PrintVersion(C, llvm::outs()); 913 return false; 914 } 915 916 if (C.getArgs().hasArg(options::OPT_v) || 917 C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) { 918 PrintVersion(C, llvm::errs()); 919 SuppressMissingInputWarning = true; 920 } 921 922 const ToolChain &TC = C.getDefaultToolChain(); 923 924 if (C.getArgs().hasArg(options::OPT_v)) 925 TC.printVerboseInfo(llvm::errs()); 926 927 if (C.getArgs().hasArg(options::OPT_print_search_dirs)) { 928 llvm::outs() << "programs: ="; 929 bool separator = false; 930 for (const std::string &Path : TC.getProgramPaths()) { 931 if (separator) 932 llvm::outs() << ':'; 933 llvm::outs() << Path; 934 separator = true; 935 } 936 llvm::outs() << "\n"; 937 llvm::outs() << "libraries: =" << ResourceDir; 938 939 StringRef sysroot = C.getSysRoot(); 940 941 for (const std::string &Path : TC.getFilePaths()) { 942 // Always print a separator. ResourceDir was the first item shown. 943 llvm::outs() << ':'; 944 // Interpretation of leading '=' is needed only for NetBSD. 945 if (Path[0] == '=') 946 llvm::outs() << sysroot << Path.substr(1); 947 else 948 llvm::outs() << Path; 949 } 950 llvm::outs() << "\n"; 951 return false; 952 } 953 954 // FIXME: The following handlers should use a callback mechanism, we don't 955 // know what the client would like to do. 956 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) { 957 llvm::outs() << GetFilePath(A->getValue(), TC) << "\n"; 958 return false; 959 } 960 961 if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) { 962 llvm::outs() << GetProgramPath(A->getValue(), TC) << "\n"; 963 return false; 964 } 965 966 if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) { 967 llvm::outs() << GetFilePath("libgcc.a", TC) << "\n"; 968 return false; 969 } 970 971 if (C.getArgs().hasArg(options::OPT_print_multi_lib)) { 972 for (const Multilib &Multilib : TC.getMultilibs()) 973 llvm::outs() << Multilib << "\n"; 974 return false; 975 } 976 977 if (C.getArgs().hasArg(options::OPT_print_multi_directory)) { 978 for (const Multilib &Multilib : TC.getMultilibs()) { 979 if (Multilib.gccSuffix().empty()) 980 llvm::outs() << ".\n"; 981 else { 982 StringRef Suffix(Multilib.gccSuffix()); 983 assert(Suffix.front() == '/'); 984 llvm::outs() << Suffix.substr(1) << "\n"; 985 } 986 } 987 return false; 988 } 989 return true; 990 } 991 992 // Display an action graph human-readably. Action A is the "sink" node 993 // and latest-occuring action. Traversal is in pre-order, visiting the 994 // inputs to each action before printing the action itself. 995 static unsigned PrintActions1(const Compilation &C, Action *A, 996 std::map<Action *, unsigned> &Ids) { 997 if (Ids.count(A)) // A was already visited. 998 return Ids[A]; 999 1000 std::string str; 1001 llvm::raw_string_ostream os(str); 1002 1003 os << Action::getClassName(A->getKind()) << ", "; 1004 if (InputAction *IA = dyn_cast<InputAction>(A)) { 1005 os << "\"" << IA->getInputArg().getValue() << "\""; 1006 } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) { 1007 os << '"' << BIA->getArchName() << '"' << ", {" 1008 << PrintActions1(C, *BIA->input_begin(), Ids) << "}"; 1009 } else if (CudaDeviceAction *CDA = dyn_cast<CudaDeviceAction>(A)) { 1010 os << '"' 1011 << (CDA->getGpuArchName() ? CDA->getGpuArchName() : "(multiple archs)") 1012 << '"' << ", {" << PrintActions1(C, *CDA->input_begin(), Ids) << "}"; 1013 } else { 1014 const ActionList *AL; 1015 if (CudaHostAction *CHA = dyn_cast<CudaHostAction>(A)) { 1016 os << "{" << PrintActions1(C, *CHA->input_begin(), Ids) << "}" 1017 << ", gpu binaries "; 1018 AL = &CHA->getDeviceActions(); 1019 } else 1020 AL = &A->getInputs(); 1021 1022 if (AL->size()) { 1023 const char *Prefix = "{"; 1024 for (Action *PreRequisite : *AL) { 1025 os << Prefix << PrintActions1(C, PreRequisite, Ids); 1026 Prefix = ", "; 1027 } 1028 os << "}"; 1029 } else 1030 os << "{}"; 1031 } 1032 1033 unsigned Id = Ids.size(); 1034 Ids[A] = Id; 1035 llvm::errs() << Id << ": " << os.str() << ", " 1036 << types::getTypeName(A->getType()) << "\n"; 1037 1038 return Id; 1039 } 1040 1041 // Print the action graphs in a compilation C. 1042 // For example "clang -c file1.c file2.c" is composed of two subgraphs. 1043 void Driver::PrintActions(const Compilation &C) const { 1044 std::map<Action *, unsigned> Ids; 1045 for (Action *A : C.getActions()) 1046 PrintActions1(C, A, Ids); 1047 } 1048 1049 /// \brief Check whether the given input tree contains any compilation or 1050 /// assembly actions. 1051 static bool ContainsCompileOrAssembleAction(const Action *A) { 1052 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A) || 1053 isa<AssembleJobAction>(A)) 1054 return true; 1055 1056 for (const Action *Input : A->inputs()) 1057 if (ContainsCompileOrAssembleAction(Input)) 1058 return true; 1059 1060 return false; 1061 } 1062 1063 void Driver::BuildUniversalActions(Compilation &C, const ToolChain &TC, 1064 const InputList &BAInputs) const { 1065 DerivedArgList &Args = C.getArgs(); 1066 ActionList &Actions = C.getActions(); 1067 llvm::PrettyStackTraceString CrashInfo("Building universal build actions"); 1068 // Collect the list of architectures. Duplicates are allowed, but should only 1069 // be handled once (in the order seen). 1070 llvm::StringSet<> ArchNames; 1071 SmallVector<const char *, 4> Archs; 1072 for (Arg *A : Args) { 1073 if (A->getOption().matches(options::OPT_arch)) { 1074 // Validate the option here; we don't save the type here because its 1075 // particular spelling may participate in other driver choices. 1076 llvm::Triple::ArchType Arch = 1077 tools::darwin::getArchTypeForMachOArchName(A->getValue()); 1078 if (Arch == llvm::Triple::UnknownArch) { 1079 Diag(clang::diag::err_drv_invalid_arch_name) << A->getAsString(Args); 1080 continue; 1081 } 1082 1083 A->claim(); 1084 if (ArchNames.insert(A->getValue()).second) 1085 Archs.push_back(A->getValue()); 1086 } 1087 } 1088 1089 // When there is no explicit arch for this platform, make sure we still bind 1090 // the architecture (to the default) so that -Xarch_ is handled correctly. 1091 if (!Archs.size()) 1092 Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName())); 1093 1094 ActionList SingleActions; 1095 BuildActions(C, Args, BAInputs, SingleActions); 1096 1097 // Add in arch bindings for every top level action, as well as lipo and 1098 // dsymutil steps if needed. 1099 for (Action* Act : SingleActions) { 1100 // Make sure we can lipo this kind of output. If not (and it is an actual 1101 // output) then we disallow, since we can't create an output file with the 1102 // right name without overwriting it. We could remove this oddity by just 1103 // changing the output names to include the arch, which would also fix 1104 // -save-temps. Compatibility wins for now. 1105 1106 if (Archs.size() > 1 && !types::canLipoType(Act->getType())) 1107 Diag(clang::diag::err_drv_invalid_output_with_multiple_archs) 1108 << types::getTypeName(Act->getType()); 1109 1110 ActionList Inputs; 1111 for (unsigned i = 0, e = Archs.size(); i != e; ++i) 1112 Inputs.push_back(C.MakeAction<BindArchAction>(Act, Archs[i])); 1113 1114 // Lipo if necessary, we do it this way because we need to set the arch flag 1115 // so that -Xarch_ gets overwritten. 1116 if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing) 1117 Actions.append(Inputs.begin(), Inputs.end()); 1118 else 1119 Actions.push_back(C.MakeAction<LipoJobAction>(Inputs, Act->getType())); 1120 1121 // Handle debug info queries. 1122 Arg *A = Args.getLastArg(options::OPT_g_Group); 1123 if (A && !A->getOption().matches(options::OPT_g0) && 1124 !A->getOption().matches(options::OPT_gstabs) && 1125 ContainsCompileOrAssembleAction(Actions.back())) { 1126 1127 // Add a 'dsymutil' step if necessary, when debug info is enabled and we 1128 // have a compile input. We need to run 'dsymutil' ourselves in such cases 1129 // because the debug info will refer to a temporary object file which 1130 // will be removed at the end of the compilation process. 1131 if (Act->getType() == types::TY_Image) { 1132 ActionList Inputs; 1133 Inputs.push_back(Actions.back()); 1134 Actions.pop_back(); 1135 Actions.push_back( 1136 C.MakeAction<DsymutilJobAction>(Inputs, types::TY_dSYM)); 1137 } 1138 1139 // Verify the debug info output. 1140 if (Args.hasArg(options::OPT_verify_debug_info)) { 1141 Action* LastAction = Actions.back(); 1142 Actions.pop_back(); 1143 Actions.push_back(C.MakeAction<VerifyDebugInfoJobAction>( 1144 LastAction, types::TY_Nothing)); 1145 } 1146 } 1147 } 1148 } 1149 1150 /// \brief Check that the file referenced by Value exists. If it doesn't, 1151 /// issue a diagnostic and return false. 1152 static bool DiagnoseInputExistence(const Driver &D, const DerivedArgList &Args, 1153 StringRef Value, types::ID Ty) { 1154 if (!D.getCheckInputsExist()) 1155 return true; 1156 1157 // stdin always exists. 1158 if (Value == "-") 1159 return true; 1160 1161 SmallString<64> Path(Value); 1162 if (Arg *WorkDir = Args.getLastArg(options::OPT_working_directory)) { 1163 if (!llvm::sys::path::is_absolute(Path)) { 1164 SmallString<64> Directory(WorkDir->getValue()); 1165 llvm::sys::path::append(Directory, Value); 1166 Path.assign(Directory); 1167 } 1168 } 1169 1170 if (llvm::sys::fs::exists(Twine(Path))) 1171 return true; 1172 1173 if (D.IsCLMode()) { 1174 if (!llvm::sys::path::is_absolute(Twine(Path)) && 1175 llvm::sys::Process::FindInEnvPath("LIB", Value)) 1176 return true; 1177 1178 if (Args.hasArg(options::OPT__SLASH_link) && Ty == types::TY_Object) { 1179 // Arguments to the /link flag might cause the linker to search for object 1180 // and library files in paths we don't know about. Don't error in such 1181 // cases. 1182 return true; 1183 } 1184 } 1185 1186 D.Diag(clang::diag::err_drv_no_such_file) << Path; 1187 return false; 1188 } 1189 1190 // Construct a the list of inputs and their types. 1191 void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args, 1192 InputList &Inputs) const { 1193 // Track the current user specified (-x) input. We also explicitly track the 1194 // argument used to set the type; we only want to claim the type when we 1195 // actually use it, so we warn about unused -x arguments. 1196 types::ID InputType = types::TY_Nothing; 1197 Arg *InputTypeArg = nullptr; 1198 1199 // The last /TC or /TP option sets the input type to C or C++ globally. 1200 if (Arg *TCTP = Args.getLastArgNoClaim(options::OPT__SLASH_TC, 1201 options::OPT__SLASH_TP)) { 1202 InputTypeArg = TCTP; 1203 InputType = TCTP->getOption().matches(options::OPT__SLASH_TC) 1204 ? types::TY_C 1205 : types::TY_CXX; 1206 1207 arg_iterator it = 1208 Args.filtered_begin(options::OPT__SLASH_TC, options::OPT__SLASH_TP); 1209 const arg_iterator ie = Args.filtered_end(); 1210 Arg *Previous = *it++; 1211 bool ShowNote = false; 1212 while (it != ie) { 1213 Diag(clang::diag::warn_drv_overriding_flag_option) 1214 << Previous->getSpelling() << (*it)->getSpelling(); 1215 Previous = *it++; 1216 ShowNote = true; 1217 } 1218 if (ShowNote) 1219 Diag(clang::diag::note_drv_t_option_is_global); 1220 1221 // No driver mode exposes -x and /TC or /TP; we don't support mixing them. 1222 assert(!Args.hasArg(options::OPT_x) && "-x and /TC or /TP is not allowed"); 1223 } 1224 1225 for (Arg *A : Args) { 1226 if (A->getOption().getKind() == Option::InputClass) { 1227 const char *Value = A->getValue(); 1228 types::ID Ty = types::TY_INVALID; 1229 1230 // Infer the input type if necessary. 1231 if (InputType == types::TY_Nothing) { 1232 // If there was an explicit arg for this, claim it. 1233 if (InputTypeArg) 1234 InputTypeArg->claim(); 1235 1236 // stdin must be handled specially. 1237 if (memcmp(Value, "-", 2) == 0) { 1238 // If running with -E, treat as a C input (this changes the builtin 1239 // macros, for example). This may be overridden by -ObjC below. 1240 // 1241 // Otherwise emit an error but still use a valid type to avoid 1242 // spurious errors (e.g., no inputs). 1243 if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP()) 1244 Diag(IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl 1245 : clang::diag::err_drv_unknown_stdin_type); 1246 Ty = types::TY_C; 1247 } else { 1248 // Otherwise lookup by extension. 1249 // Fallback is C if invoked as C preprocessor or Object otherwise. 1250 // We use a host hook here because Darwin at least has its own 1251 // idea of what .s is. 1252 if (const char *Ext = strrchr(Value, '.')) 1253 Ty = TC.LookupTypeForExtension(Ext + 1); 1254 1255 if (Ty == types::TY_INVALID) { 1256 if (CCCIsCPP()) 1257 Ty = types::TY_C; 1258 else 1259 Ty = types::TY_Object; 1260 } 1261 1262 // If the driver is invoked as C++ compiler (like clang++ or c++) it 1263 // should autodetect some input files as C++ for g++ compatibility. 1264 if (CCCIsCXX()) { 1265 types::ID OldTy = Ty; 1266 Ty = types::lookupCXXTypeForCType(Ty); 1267 1268 if (Ty != OldTy) 1269 Diag(clang::diag::warn_drv_treating_input_as_cxx) 1270 << getTypeName(OldTy) << getTypeName(Ty); 1271 } 1272 } 1273 1274 // -ObjC and -ObjC++ override the default language, but only for "source 1275 // files". We just treat everything that isn't a linker input as a 1276 // source file. 1277 // 1278 // FIXME: Clean this up if we move the phase sequence into the type. 1279 if (Ty != types::TY_Object) { 1280 if (Args.hasArg(options::OPT_ObjC)) 1281 Ty = types::TY_ObjC; 1282 else if (Args.hasArg(options::OPT_ObjCXX)) 1283 Ty = types::TY_ObjCXX; 1284 } 1285 } else { 1286 assert(InputTypeArg && "InputType set w/o InputTypeArg"); 1287 if (!InputTypeArg->getOption().matches(options::OPT_x)) { 1288 // If emulating cl.exe, make sure that /TC and /TP don't affect input 1289 // object files. 1290 const char *Ext = strrchr(Value, '.'); 1291 if (Ext && TC.LookupTypeForExtension(Ext + 1) == types::TY_Object) 1292 Ty = types::TY_Object; 1293 } 1294 if (Ty == types::TY_INVALID) { 1295 Ty = InputType; 1296 InputTypeArg->claim(); 1297 } 1298 } 1299 1300 if (DiagnoseInputExistence(*this, Args, Value, Ty)) 1301 Inputs.push_back(std::make_pair(Ty, A)); 1302 1303 } else if (A->getOption().matches(options::OPT__SLASH_Tc)) { 1304 StringRef Value = A->getValue(); 1305 if (DiagnoseInputExistence(*this, Args, Value, types::TY_C)) { 1306 Arg *InputArg = MakeInputArg(Args, Opts, A->getValue()); 1307 Inputs.push_back(std::make_pair(types::TY_C, InputArg)); 1308 } 1309 A->claim(); 1310 } else if (A->getOption().matches(options::OPT__SLASH_Tp)) { 1311 StringRef Value = A->getValue(); 1312 if (DiagnoseInputExistence(*this, Args, Value, types::TY_CXX)) { 1313 Arg *InputArg = MakeInputArg(Args, Opts, A->getValue()); 1314 Inputs.push_back(std::make_pair(types::TY_CXX, InputArg)); 1315 } 1316 A->claim(); 1317 } else if (A->getOption().hasFlag(options::LinkerInput)) { 1318 // Just treat as object type, we could make a special type for this if 1319 // necessary. 1320 Inputs.push_back(std::make_pair(types::TY_Object, A)); 1321 1322 } else if (A->getOption().matches(options::OPT_x)) { 1323 InputTypeArg = A; 1324 InputType = types::lookupTypeForTypeSpecifier(A->getValue()); 1325 A->claim(); 1326 1327 // Follow gcc behavior and treat as linker input for invalid -x 1328 // options. Its not clear why we shouldn't just revert to unknown; but 1329 // this isn't very important, we might as well be bug compatible. 1330 if (!InputType) { 1331 Diag(clang::diag::err_drv_unknown_language) << A->getValue(); 1332 InputType = types::TY_Object; 1333 } 1334 } 1335 } 1336 if (CCCIsCPP() && Inputs.empty()) { 1337 // If called as standalone preprocessor, stdin is processed 1338 // if no other input is present. 1339 Arg *A = MakeInputArg(Args, Opts, "-"); 1340 Inputs.push_back(std::make_pair(types::TY_C, A)); 1341 } 1342 } 1343 1344 // For each unique --cuda-gpu-arch= argument creates a TY_CUDA_DEVICE 1345 // input action and then wraps each in CudaDeviceAction paired with 1346 // appropriate GPU arch name. In case of partial (i.e preprocessing 1347 // only) or device-only compilation, each device action is added to /p 1348 // Actions and /p Current is released. Otherwise the function creates 1349 // and returns a new CudaHostAction which wraps /p Current and device 1350 // side actions. 1351 static Action *buildCudaActions(Compilation &C, DerivedArgList &Args, 1352 const Arg *InputArg, Action *HostAction, 1353 ActionList &Actions) { 1354 Arg *PartialCompilationArg = Args.getLastArg( 1355 options::OPT_cuda_host_only, options::OPT_cuda_device_only, 1356 options::OPT_cuda_compile_host_device); 1357 bool CompileHostOnly = 1358 PartialCompilationArg && 1359 PartialCompilationArg->getOption().matches(options::OPT_cuda_host_only); 1360 bool CompileDeviceOnly = 1361 PartialCompilationArg && 1362 PartialCompilationArg->getOption().matches(options::OPT_cuda_device_only); 1363 1364 if (CompileHostOnly) 1365 return C.MakeAction<CudaHostAction>(HostAction, ActionList()); 1366 1367 // Collect all cuda_gpu_arch parameters, removing duplicates. 1368 SmallVector<const char *, 4> GpuArchList; 1369 llvm::StringSet<> GpuArchNames; 1370 for (Arg *A : Args) { 1371 if (!A->getOption().matches(options::OPT_cuda_gpu_arch_EQ)) 1372 continue; 1373 A->claim(); 1374 1375 const auto& Arch = A->getValue(); 1376 if (!CudaDeviceAction::IsValidGpuArchName(Arch)) 1377 C.getDriver().Diag(clang::diag::err_drv_cuda_bad_gpu_arch) << Arch; 1378 else if (GpuArchNames.insert(Arch).second) 1379 GpuArchList.push_back(Arch); 1380 } 1381 1382 // Default to sm_20 which is the lowest common denominator for supported GPUs. 1383 // sm_20 code should work correctly, if suboptimally, on all newer GPUs. 1384 if (GpuArchList.empty()) 1385 GpuArchList.push_back("sm_20"); 1386 1387 // Replicate inputs for each GPU architecture. 1388 Driver::InputList CudaDeviceInputs; 1389 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) 1390 CudaDeviceInputs.push_back(std::make_pair(types::TY_CUDA_DEVICE, InputArg)); 1391 1392 // Build actions for all device inputs. 1393 assert(C.getCudaDeviceToolChain() && 1394 "Missing toolchain for device-side compilation."); 1395 ActionList CudaDeviceActions; 1396 C.getDriver().BuildActions(C, Args, CudaDeviceInputs, CudaDeviceActions); 1397 assert(GpuArchList.size() == CudaDeviceActions.size() && 1398 "Failed to create actions for all devices"); 1399 1400 // Check whether any of device actions stopped before they could generate PTX. 1401 bool PartialCompilation = 1402 llvm::any_of(CudaDeviceActions, [](const Action *a) { 1403 return a->getKind() != Action::AssembleJobClass; 1404 }); 1405 1406 // Figure out what to do with device actions -- pass them as inputs to the 1407 // host action or run each of them independently. 1408 if (PartialCompilation || CompileDeviceOnly) { 1409 // In case of partial or device-only compilation results of device actions 1410 // are not consumed by the host action device actions have to be added to 1411 // top-level actions list with AtTopLevel=true and run independently. 1412 1413 // -o is ambiguous if we have more than one top-level action. 1414 if (Args.hasArg(options::OPT_o) && 1415 (!CompileDeviceOnly || GpuArchList.size() > 1)) { 1416 C.getDriver().Diag( 1417 clang::diag::err_drv_output_argument_with_multiple_files); 1418 return nullptr; 1419 } 1420 1421 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) 1422 Actions.push_back(C.MakeAction<CudaDeviceAction>(CudaDeviceActions[I], 1423 GpuArchList[I], 1424 /* AtTopLevel */ true)); 1425 // Kill host action in case of device-only compilation. 1426 if (CompileDeviceOnly) 1427 return nullptr; 1428 return HostAction; 1429 } 1430 1431 // If we're not a partial or device-only compilation, we compile each arch to 1432 // ptx and assemble to cubin, then feed the cubin *and* the ptx into a device 1433 // "link" action, which uses fatbinary to combine these cubins into one 1434 // fatbin. The fatbin is then an input to the host compilation. 1435 ActionList DeviceActions; 1436 for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) { 1437 Action* AssembleAction = CudaDeviceActions[I]; 1438 assert(AssembleAction->getType() == types::TY_Object); 1439 assert(AssembleAction->getInputs().size() == 1); 1440 1441 Action* BackendAction = AssembleAction->getInputs()[0]; 1442 assert(BackendAction->getType() == types::TY_PP_Asm); 1443 1444 for (const auto& A : {AssembleAction, BackendAction}) { 1445 DeviceActions.push_back(C.MakeAction<CudaDeviceAction>( 1446 A, GpuArchList[I], /* AtTopLevel */ false)); 1447 } 1448 } 1449 auto FatbinAction = C.MakeAction<CudaDeviceAction>( 1450 C.MakeAction<LinkJobAction>(DeviceActions, types::TY_CUDA_FATBIN), 1451 /* GpuArchName = */ nullptr, 1452 /* AtTopLevel = */ false); 1453 // Return a new host action that incorporates original host action and all 1454 // device actions. 1455 return C.MakeAction<CudaHostAction>(std::move(HostAction), 1456 ActionList({FatbinAction})); 1457 } 1458 1459 void Driver::BuildActions(Compilation &C, DerivedArgList &Args, 1460 const InputList &Inputs, ActionList &Actions) const { 1461 llvm::PrettyStackTraceString CrashInfo("Building compilation actions"); 1462 1463 if (!SuppressMissingInputWarning && Inputs.empty()) { 1464 Diag(clang::diag::err_drv_no_input_files); 1465 return; 1466 } 1467 1468 Arg *FinalPhaseArg; 1469 phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg); 1470 1471 if (FinalPhase == phases::Link && Args.hasArg(options::OPT_emit_llvm)) { 1472 Diag(clang::diag::err_drv_emit_llvm_link); 1473 } 1474 1475 // Reject -Z* at the top level, these options should never have been exposed 1476 // by gcc. 1477 if (Arg *A = Args.getLastArg(options::OPT_Z_Joined)) 1478 Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args); 1479 1480 // Diagnose misuse of /Fo. 1481 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) { 1482 StringRef V = A->getValue(); 1483 if (Inputs.size() > 1 && !V.empty() && 1484 !llvm::sys::path::is_separator(V.back())) { 1485 // Check whether /Fo tries to name an output file for multiple inputs. 1486 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources) 1487 << A->getSpelling() << V; 1488 Args.eraseArg(options::OPT__SLASH_Fo); 1489 } 1490 } 1491 1492 // Diagnose misuse of /Fa. 1493 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fa)) { 1494 StringRef V = A->getValue(); 1495 if (Inputs.size() > 1 && !V.empty() && 1496 !llvm::sys::path::is_separator(V.back())) { 1497 // Check whether /Fa tries to name an asm file for multiple inputs. 1498 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources) 1499 << A->getSpelling() << V; 1500 Args.eraseArg(options::OPT__SLASH_Fa); 1501 } 1502 } 1503 1504 // Diagnose misuse of /o. 1505 if (Arg *A = Args.getLastArg(options::OPT__SLASH_o)) { 1506 if (A->getValue()[0] == '\0') { 1507 // It has to have a value. 1508 Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1; 1509 Args.eraseArg(options::OPT__SLASH_o); 1510 } 1511 } 1512 1513 // Diagnose unsupported forms of /Yc /Yu. Ignore /Yc/Yu for now if: 1514 // * no filename after it 1515 // * both /Yc and /Yu passed but with different filenames 1516 // * corresponding file not also passed as /FI 1517 Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc); 1518 Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu); 1519 if (YcArg && YcArg->getValue()[0] == '\0') { 1520 Diag(clang::diag::warn_drv_ycyu_no_arg_clang_cl) << YcArg->getSpelling(); 1521 Args.eraseArg(options::OPT__SLASH_Yc); 1522 YcArg = nullptr; 1523 } 1524 if (YuArg && YuArg->getValue()[0] == '\0') { 1525 Diag(clang::diag::warn_drv_ycyu_no_arg_clang_cl) << YuArg->getSpelling(); 1526 Args.eraseArg(options::OPT__SLASH_Yu); 1527 YuArg = nullptr; 1528 } 1529 if (YcArg && YuArg && strcmp(YcArg->getValue(), YuArg->getValue()) != 0) { 1530 Diag(clang::diag::warn_drv_ycyu_different_arg_clang_cl); 1531 Args.eraseArg(options::OPT__SLASH_Yc); 1532 Args.eraseArg(options::OPT__SLASH_Yu); 1533 YcArg = YuArg = nullptr; 1534 } 1535 if (YcArg || YuArg) { 1536 StringRef Val = YcArg ? YcArg->getValue() : YuArg->getValue(); 1537 bool FoundMatchingInclude = false; 1538 for (const Arg *Inc : Args.filtered(options::OPT_include)) { 1539 // FIXME: Do case-insensitive matching and consider / and \ as equal. 1540 if (Inc->getValue() == Val) 1541 FoundMatchingInclude = true; 1542 } 1543 if (!FoundMatchingInclude) { 1544 Diag(clang::diag::warn_drv_ycyu_no_fi_arg_clang_cl) 1545 << (YcArg ? YcArg : YuArg)->getSpelling(); 1546 Args.eraseArg(options::OPT__SLASH_Yc); 1547 Args.eraseArg(options::OPT__SLASH_Yu); 1548 YcArg = YuArg = nullptr; 1549 } 1550 } 1551 if (YcArg && Inputs.size() > 1) { 1552 Diag(clang::diag::warn_drv_yc_multiple_inputs_clang_cl); 1553 Args.eraseArg(options::OPT__SLASH_Yc); 1554 YcArg = nullptr; 1555 } 1556 if (Args.hasArg(options::OPT__SLASH_Y_)) { 1557 // /Y- disables all pch handling. Rather than check for it everywhere, 1558 // just remove clang-cl pch-related flags here. 1559 Args.eraseArg(options::OPT__SLASH_Fp); 1560 Args.eraseArg(options::OPT__SLASH_Yc); 1561 Args.eraseArg(options::OPT__SLASH_Yu); 1562 YcArg = YuArg = nullptr; 1563 } 1564 1565 // Construct the actions to perform. 1566 ActionList LinkerInputs; 1567 1568 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PL; 1569 for (auto &I : Inputs) { 1570 types::ID InputType = I.first; 1571 const Arg *InputArg = I.second; 1572 1573 PL.clear(); 1574 types::getCompilationPhases(InputType, PL); 1575 1576 // If the first step comes after the final phase we are doing as part of 1577 // this compilation, warn the user about it. 1578 phases::ID InitialPhase = PL[0]; 1579 if (InitialPhase > FinalPhase) { 1580 // Claim here to avoid the more general unused warning. 1581 InputArg->claim(); 1582 1583 // Suppress all unused style warnings with -Qunused-arguments 1584 if (Args.hasArg(options::OPT_Qunused_arguments)) 1585 continue; 1586 1587 // Special case when final phase determined by binary name, rather than 1588 // by a command-line argument with a corresponding Arg. 1589 if (CCCIsCPP()) 1590 Diag(clang::diag::warn_drv_input_file_unused_by_cpp) 1591 << InputArg->getAsString(Args) << getPhaseName(InitialPhase); 1592 // Special case '-E' warning on a previously preprocessed file to make 1593 // more sense. 1594 else if (InitialPhase == phases::Compile && 1595 FinalPhase == phases::Preprocess && 1596 getPreprocessedType(InputType) == types::TY_INVALID) 1597 Diag(clang::diag::warn_drv_preprocessed_input_file_unused) 1598 << InputArg->getAsString(Args) << !!FinalPhaseArg 1599 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : ""); 1600 else 1601 Diag(clang::diag::warn_drv_input_file_unused) 1602 << InputArg->getAsString(Args) << getPhaseName(InitialPhase) 1603 << !!FinalPhaseArg 1604 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : ""); 1605 continue; 1606 } 1607 1608 if (YcArg) { 1609 // Add a separate precompile phase for the compile phase. 1610 if (FinalPhase >= phases::Compile) { 1611 llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PCHPL; 1612 types::getCompilationPhases(types::TY_CXXHeader, PCHPL); 1613 Arg *PchInputArg = MakeInputArg(Args, Opts, YcArg->getValue()); 1614 1615 // Build the pipeline for the pch file. 1616 Action *ClangClPch = C.MakeAction<InputAction>(*PchInputArg, InputType); 1617 for (phases::ID Phase : PCHPL) 1618 ClangClPch = ConstructPhaseAction(C, Args, Phase, ClangClPch); 1619 assert(ClangClPch); 1620 Actions.push_back(ClangClPch); 1621 // The driver currently exits after the first failed command. This 1622 // relies on that behavior, to make sure if the pch generation fails, 1623 // the main compilation won't run. 1624 } 1625 } 1626 1627 phases::ID CudaInjectionPhase = 1628 (phases::Compile < FinalPhase && 1629 llvm::find(PL, phases::Compile) != PL.end()) 1630 ? phases::Compile 1631 : FinalPhase; 1632 1633 // Build the pipeline for this file. 1634 Action *Current = C.MakeAction<InputAction>(*InputArg, InputType); 1635 for (SmallVectorImpl<phases::ID>::iterator i = PL.begin(), e = PL.end(); 1636 i != e; ++i) { 1637 phases::ID Phase = *i; 1638 1639 // We are done if this step is past what the user requested. 1640 if (Phase > FinalPhase) 1641 break; 1642 1643 // Queue linker inputs. 1644 if (Phase == phases::Link) { 1645 assert((i + 1) == e && "linking must be final compilation step."); 1646 LinkerInputs.push_back(Current); 1647 Current = nullptr; 1648 break; 1649 } 1650 1651 // Some types skip the assembler phase (e.g., llvm-bc), but we can't 1652 // encode this in the steps because the intermediate type depends on 1653 // arguments. Just special case here. 1654 if (Phase == phases::Assemble && Current->getType() != types::TY_PP_Asm) 1655 continue; 1656 1657 // Otherwise construct the appropriate action. 1658 Current = ConstructPhaseAction(C, Args, Phase, Current); 1659 1660 if (InputType == types::TY_CUDA && Phase == CudaInjectionPhase) { 1661 Current = buildCudaActions(C, Args, InputArg, Current, Actions); 1662 if (!Current) 1663 break; 1664 } 1665 1666 if (Current->getType() == types::TY_Nothing) 1667 break; 1668 } 1669 1670 // If we ended with something, add to the output list. 1671 if (Current) 1672 Actions.push_back(Current); 1673 } 1674 1675 // Add a link action if necessary. 1676 if (!LinkerInputs.empty()) 1677 Actions.push_back( 1678 C.MakeAction<LinkJobAction>(LinkerInputs, types::TY_Image)); 1679 1680 // If we are linking, claim any options which are obviously only used for 1681 // compilation. 1682 if (FinalPhase == phases::Link && PL.size() == 1) { 1683 Args.ClaimAllArgs(options::OPT_CompileOnly_Group); 1684 Args.ClaimAllArgs(options::OPT_cl_compile_Group); 1685 } 1686 1687 // Claim ignored clang-cl options. 1688 Args.ClaimAllArgs(options::OPT_cl_ignored_Group); 1689 1690 // Claim --cuda-host-only and --cuda-compile-host-device, which may be passed 1691 // to non-CUDA compilations and should not trigger warnings there. 1692 Args.ClaimAllArgs(options::OPT_cuda_host_only); 1693 Args.ClaimAllArgs(options::OPT_cuda_compile_host_device); 1694 } 1695 1696 Action *Driver::ConstructPhaseAction(Compilation &C, const ArgList &Args, 1697 phases::ID Phase, Action *Input) const { 1698 llvm::PrettyStackTraceString CrashInfo("Constructing phase actions"); 1699 // Build the appropriate action. 1700 switch (Phase) { 1701 case phases::Link: 1702 llvm_unreachable("link action invalid here."); 1703 case phases::Preprocess: { 1704 types::ID OutputTy; 1705 // -{M, MM} alter the output type. 1706 if (Args.hasArg(options::OPT_M, options::OPT_MM)) { 1707 OutputTy = types::TY_Dependencies; 1708 } else { 1709 OutputTy = Input->getType(); 1710 if (!Args.hasFlag(options::OPT_frewrite_includes, 1711 options::OPT_fno_rewrite_includes, false) && 1712 !CCGenDiagnostics) 1713 OutputTy = types::getPreprocessedType(OutputTy); 1714 assert(OutputTy != types::TY_INVALID && 1715 "Cannot preprocess this input type!"); 1716 } 1717 return C.MakeAction<PreprocessJobAction>(Input, OutputTy); 1718 } 1719 case phases::Precompile: { 1720 types::ID OutputTy = types::TY_PCH; 1721 if (Args.hasArg(options::OPT_fsyntax_only)) { 1722 // Syntax checks should not emit a PCH file 1723 OutputTy = types::TY_Nothing; 1724 } 1725 return C.MakeAction<PrecompileJobAction>(Input, OutputTy); 1726 } 1727 case phases::Compile: { 1728 if (Args.hasArg(options::OPT_fsyntax_only)) 1729 return C.MakeAction<CompileJobAction>(Input, types::TY_Nothing); 1730 if (Args.hasArg(options::OPT_rewrite_objc)) 1731 return C.MakeAction<CompileJobAction>(Input, types::TY_RewrittenObjC); 1732 if (Args.hasArg(options::OPT_rewrite_legacy_objc)) 1733 return C.MakeAction<CompileJobAction>(Input, 1734 types::TY_RewrittenLegacyObjC); 1735 if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto)) 1736 return C.MakeAction<AnalyzeJobAction>(Input, types::TY_Plist); 1737 if (Args.hasArg(options::OPT__migrate)) 1738 return C.MakeAction<MigrateJobAction>(Input, types::TY_Remap); 1739 if (Args.hasArg(options::OPT_emit_ast)) 1740 return C.MakeAction<CompileJobAction>(Input, types::TY_AST); 1741 if (Args.hasArg(options::OPT_module_file_info)) 1742 return C.MakeAction<CompileJobAction>(Input, types::TY_ModuleFile); 1743 if (Args.hasArg(options::OPT_verify_pch)) 1744 return C.MakeAction<VerifyPCHJobAction>(Input, types::TY_Nothing); 1745 return C.MakeAction<CompileJobAction>(Input, types::TY_LLVM_BC); 1746 } 1747 case phases::Backend: { 1748 if (isUsingLTO()) { 1749 types::ID Output = 1750 Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC; 1751 return C.MakeAction<BackendJobAction>(Input, Output); 1752 } 1753 if (Args.hasArg(options::OPT_emit_llvm)) { 1754 types::ID Output = 1755 Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC; 1756 return C.MakeAction<BackendJobAction>(Input, Output); 1757 } 1758 return C.MakeAction<BackendJobAction>(Input, types::TY_PP_Asm); 1759 } 1760 case phases::Assemble: 1761 return C.MakeAction<AssembleJobAction>(std::move(Input), types::TY_Object); 1762 } 1763 1764 llvm_unreachable("invalid phase in ConstructPhaseAction"); 1765 } 1766 1767 void Driver::BuildJobs(Compilation &C) const { 1768 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs"); 1769 1770 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o); 1771 1772 // It is an error to provide a -o option if we are making multiple output 1773 // files. 1774 if (FinalOutput) { 1775 unsigned NumOutputs = 0; 1776 for (const Action *A : C.getActions()) 1777 if (A->getType() != types::TY_Nothing) 1778 ++NumOutputs; 1779 1780 if (NumOutputs > 1) { 1781 Diag(clang::diag::err_drv_output_argument_with_multiple_files); 1782 FinalOutput = nullptr; 1783 } 1784 } 1785 1786 // Collect the list of architectures. 1787 llvm::StringSet<> ArchNames; 1788 if (C.getDefaultToolChain().getTriple().isOSBinFormatMachO()) 1789 for (const Arg *A : C.getArgs()) 1790 if (A->getOption().matches(options::OPT_arch)) 1791 ArchNames.insert(A->getValue()); 1792 1793 // Set of (Action, canonical ToolChain triple) pairs we've built jobs for. 1794 std::map<std::pair<const Action *, std::string>, InputInfo> CachedResults; 1795 for (Action *A : C.getActions()) { 1796 // If we are linking an image for multiple archs then the linker wants 1797 // -arch_multiple and -final_output <final image name>. Unfortunately, this 1798 // doesn't fit in cleanly because we have to pass this information down. 1799 // 1800 // FIXME: This is a hack; find a cleaner way to integrate this into the 1801 // process. 1802 const char *LinkingOutput = nullptr; 1803 if (isa<LipoJobAction>(A)) { 1804 if (FinalOutput) 1805 LinkingOutput = FinalOutput->getValue(); 1806 else 1807 LinkingOutput = getDefaultImageName(); 1808 } 1809 1810 BuildJobsForAction(C, A, &C.getDefaultToolChain(), 1811 /*BoundArch*/ nullptr, 1812 /*AtTopLevel*/ true, 1813 /*MultipleArchs*/ ArchNames.size() > 1, 1814 /*LinkingOutput*/ LinkingOutput, CachedResults); 1815 } 1816 1817 // If the user passed -Qunused-arguments or there were errors, don't warn 1818 // about any unused arguments. 1819 if (Diags.hasErrorOccurred() || 1820 C.getArgs().hasArg(options::OPT_Qunused_arguments)) 1821 return; 1822 1823 // Claim -### here. 1824 (void)C.getArgs().hasArg(options::OPT__HASH_HASH_HASH); 1825 1826 // Claim --driver-mode, --rsp-quoting, it was handled earlier. 1827 (void)C.getArgs().hasArg(options::OPT_driver_mode); 1828 (void)C.getArgs().hasArg(options::OPT_rsp_quoting); 1829 1830 for (Arg *A : C.getArgs()) { 1831 // FIXME: It would be nice to be able to send the argument to the 1832 // DiagnosticsEngine, so that extra values, position, and so on could be 1833 // printed. 1834 if (!A->isClaimed()) { 1835 if (A->getOption().hasFlag(options::NoArgumentUnused)) 1836 continue; 1837 1838 // Suppress the warning automatically if this is just a flag, and it is an 1839 // instance of an argument we already claimed. 1840 const Option &Opt = A->getOption(); 1841 if (Opt.getKind() == Option::FlagClass) { 1842 bool DuplicateClaimed = false; 1843 1844 for (const Arg *AA : C.getArgs().filtered(&Opt)) { 1845 if (AA->isClaimed()) { 1846 DuplicateClaimed = true; 1847 break; 1848 } 1849 } 1850 1851 if (DuplicateClaimed) 1852 continue; 1853 } 1854 1855 // In clang-cl, don't mention unknown arguments here since they have 1856 // already been warned about. 1857 if (!IsCLMode() || !A->getOption().matches(options::OPT_UNKNOWN)) 1858 Diag(clang::diag::warn_drv_unused_argument) 1859 << A->getAsString(C.getArgs()); 1860 } 1861 } 1862 } 1863 1864 // Returns a Tool for a given JobAction. In case the action and its 1865 // predecessors can be combined, updates Inputs with the inputs of the 1866 // first combined action. If one of the collapsed actions is a 1867 // CudaHostAction, updates CollapsedCHA with the pointer to it so the 1868 // caller can deal with extra handling such action requires. 1869 static const Tool *selectToolForJob(Compilation &C, bool SaveTemps, 1870 bool EmbedBitcode, const ToolChain *TC, 1871 const JobAction *JA, 1872 const ActionList *&Inputs, 1873 const CudaHostAction *&CollapsedCHA) { 1874 const Tool *ToolForJob = nullptr; 1875 CollapsedCHA = nullptr; 1876 1877 // See if we should look for a compiler with an integrated assembler. We match 1878 // bottom up, so what we are actually looking for is an assembler job with a 1879 // compiler input. 1880 1881 if (TC->useIntegratedAs() && !SaveTemps && 1882 !C.getArgs().hasArg(options::OPT_via_file_asm) && 1883 !C.getArgs().hasArg(options::OPT__SLASH_FA) && 1884 !C.getArgs().hasArg(options::OPT__SLASH_Fa) && 1885 isa<AssembleJobAction>(JA) && Inputs->size() == 1 && 1886 isa<BackendJobAction>(*Inputs->begin())) { 1887 // A BackendJob is always preceded by a CompileJob, and without -save-temps 1888 // or -fembed-bitcode, they will always get combined together, so instead of 1889 // checking the backend tool, check if the tool for the CompileJob has an 1890 // integrated assembler. For -fembed-bitcode, CompileJob is still used to 1891 // look up tools for BackendJob, but they need to match before we can split 1892 // them. 1893 const ActionList *BackendInputs = &(*Inputs)[0]->getInputs(); 1894 // Compile job may be wrapped in CudaHostAction, extract it if 1895 // that's the case and update CollapsedCHA if we combine phases. 1896 CudaHostAction *CHA = dyn_cast<CudaHostAction>(*BackendInputs->begin()); 1897 JobAction *CompileJA = cast<CompileJobAction>( 1898 CHA ? *CHA->input_begin() : *BackendInputs->begin()); 1899 assert(CompileJA && "Backend job is not preceeded by compile job."); 1900 const Tool *Compiler = TC->SelectTool(*CompileJA); 1901 if (!Compiler) 1902 return nullptr; 1903 // When using -fembed-bitcode, it is required to have the same tool (clang) 1904 // for both CompilerJA and BackendJA. Otherwise, combine two stages. 1905 if (EmbedBitcode) { 1906 JobAction *InputJA = cast<JobAction>(*Inputs->begin()); 1907 const Tool *BackendTool = TC->SelectTool(*InputJA); 1908 if (BackendTool == Compiler) 1909 CompileJA = InputJA; 1910 } 1911 if (Compiler->hasIntegratedAssembler()) { 1912 Inputs = &CompileJA->getInputs(); 1913 ToolForJob = Compiler; 1914 CollapsedCHA = CHA; 1915 } 1916 } 1917 1918 // A backend job should always be combined with the preceding compile job 1919 // unless OPT_save_temps or OPT_fembed_bitcode is enabled and the compiler is 1920 // capable of emitting LLVM IR as an intermediate output. 1921 if (isa<BackendJobAction>(JA)) { 1922 // Check if the compiler supports emitting LLVM IR. 1923 assert(Inputs->size() == 1); 1924 // Compile job may be wrapped in CudaHostAction, extract it if 1925 // that's the case and update CollapsedCHA if we combine phases. 1926 CudaHostAction *CHA = dyn_cast<CudaHostAction>(*Inputs->begin()); 1927 JobAction *CompileJA = 1928 cast<CompileJobAction>(CHA ? *CHA->input_begin() : *Inputs->begin()); 1929 assert(CompileJA && "Backend job is not preceeded by compile job."); 1930 const Tool *Compiler = TC->SelectTool(*CompileJA); 1931 if (!Compiler) 1932 return nullptr; 1933 if (!Compiler->canEmitIR() || 1934 (!SaveTemps && !EmbedBitcode)) { 1935 Inputs = &CompileJA->getInputs(); 1936 ToolForJob = Compiler; 1937 CollapsedCHA = CHA; 1938 } 1939 } 1940 1941 // Otherwise use the tool for the current job. 1942 if (!ToolForJob) 1943 ToolForJob = TC->SelectTool(*JA); 1944 1945 // See if we should use an integrated preprocessor. We do so when we have 1946 // exactly one input, since this is the only use case we care about 1947 // (irrelevant since we don't support combine yet). 1948 if (Inputs->size() == 1 && isa<PreprocessJobAction>(*Inputs->begin()) && 1949 !C.getArgs().hasArg(options::OPT_no_integrated_cpp) && 1950 !C.getArgs().hasArg(options::OPT_traditional_cpp) && !SaveTemps && 1951 !C.getArgs().hasArg(options::OPT_rewrite_objc) && 1952 ToolForJob->hasIntegratedCPP()) 1953 Inputs = &(*Inputs)[0]->getInputs(); 1954 1955 return ToolForJob; 1956 } 1957 1958 InputInfo Driver::BuildJobsForAction( 1959 Compilation &C, const Action *A, const ToolChain *TC, const char *BoundArch, 1960 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput, 1961 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults) 1962 const { 1963 // The bound arch is not necessarily represented in the toolchain's triple -- 1964 // for example, armv7 and armv7s both map to the same triple -- so we need 1965 // both in our map. 1966 std::string TriplePlusArch = TC->getTriple().normalize(); 1967 if (BoundArch) { 1968 TriplePlusArch += "-"; 1969 TriplePlusArch += BoundArch; 1970 } 1971 std::pair<const Action *, std::string> ActionTC = {A, TriplePlusArch}; 1972 auto CachedResult = CachedResults.find(ActionTC); 1973 if (CachedResult != CachedResults.end()) { 1974 return CachedResult->second; 1975 } 1976 InputInfo Result = 1977 BuildJobsForActionNoCache(C, A, TC, BoundArch, AtTopLevel, MultipleArchs, 1978 LinkingOutput, CachedResults); 1979 CachedResults[ActionTC] = Result; 1980 return Result; 1981 } 1982 1983 InputInfo Driver::BuildJobsForActionNoCache( 1984 Compilation &C, const Action *A, const ToolChain *TC, const char *BoundArch, 1985 bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput, 1986 std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults) 1987 const { 1988 llvm::PrettyStackTraceString CrashInfo("Building compilation jobs"); 1989 1990 InputInfoList CudaDeviceInputInfos; 1991 if (const CudaHostAction *CHA = dyn_cast<CudaHostAction>(A)) { 1992 // Append outputs of device jobs to the input list. 1993 for (const Action *DA : CHA->getDeviceActions()) { 1994 CudaDeviceInputInfos.push_back(BuildJobsForAction( 1995 C, DA, TC, nullptr, AtTopLevel, 1996 /*MultipleArchs*/ false, LinkingOutput, CachedResults)); 1997 } 1998 // Override current action with a real host compile action and continue 1999 // processing it. 2000 A = *CHA->input_begin(); 2001 } 2002 2003 if (const InputAction *IA = dyn_cast<InputAction>(A)) { 2004 // FIXME: It would be nice to not claim this here; maybe the old scheme of 2005 // just using Args was better? 2006 const Arg &Input = IA->getInputArg(); 2007 Input.claim(); 2008 if (Input.getOption().matches(options::OPT_INPUT)) { 2009 const char *Name = Input.getValue(); 2010 return InputInfo(A, Name, /* BaseInput = */ Name); 2011 } 2012 return InputInfo(A, &Input, /* BaseInput = */ ""); 2013 } 2014 2015 if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) { 2016 const ToolChain *TC; 2017 const char *ArchName = BAA->getArchName(); 2018 2019 if (ArchName) 2020 TC = &getToolChain(C.getArgs(), 2021 computeTargetTriple(*this, DefaultTargetTriple, 2022 C.getArgs(), ArchName)); 2023 else 2024 TC = &C.getDefaultToolChain(); 2025 2026 return BuildJobsForAction(C, *BAA->input_begin(), TC, ArchName, AtTopLevel, 2027 MultipleArchs, LinkingOutput, CachedResults); 2028 } 2029 2030 if (const CudaDeviceAction *CDA = dyn_cast<CudaDeviceAction>(A)) { 2031 // Initial processing of CudaDeviceAction carries host params. 2032 // Call BuildJobsForAction() again, now with correct device parameters. 2033 InputInfo II = BuildJobsForAction( 2034 C, *CDA->input_begin(), C.getCudaDeviceToolChain(), 2035 CDA->getGpuArchName(), CDA->isAtTopLevel(), /*MultipleArchs=*/true, 2036 LinkingOutput, CachedResults); 2037 // Currently II's Action is *CDA->input_begin(). Set it to CDA instead, so 2038 // that one can retrieve II's GPU arch. 2039 II.setAction(A); 2040 return II; 2041 } 2042 2043 const ActionList *Inputs = &A->getInputs(); 2044 2045 const JobAction *JA = cast<JobAction>(A); 2046 const CudaHostAction *CollapsedCHA = nullptr; 2047 const Tool *T = 2048 selectToolForJob(C, isSaveTempsEnabled(), embedBitcodeEnabled(), TC, JA, 2049 Inputs, CollapsedCHA); 2050 if (!T) 2051 return InputInfo(); 2052 2053 // If we've collapsed action list that contained CudaHostAction we 2054 // need to build jobs for device-side inputs it may have held. 2055 if (CollapsedCHA) { 2056 for (const Action *DA : CollapsedCHA->getDeviceActions()) { 2057 CudaDeviceInputInfos.push_back(BuildJobsForAction( 2058 C, DA, TC, "", AtTopLevel, 2059 /*MultipleArchs*/ false, LinkingOutput, CachedResults)); 2060 } 2061 } 2062 2063 // Only use pipes when there is exactly one input. 2064 InputInfoList InputInfos; 2065 for (const Action *Input : *Inputs) { 2066 // Treat dsymutil and verify sub-jobs as being at the top-level too, they 2067 // shouldn't get temporary output names. 2068 // FIXME: Clean this up. 2069 bool SubJobAtTopLevel = 2070 AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A)); 2071 InputInfos.push_back(BuildJobsForAction(C, Input, TC, BoundArch, 2072 SubJobAtTopLevel, MultipleArchs, 2073 LinkingOutput, CachedResults)); 2074 } 2075 2076 // Always use the first input as the base input. 2077 const char *BaseInput = InputInfos[0].getBaseInput(); 2078 2079 // ... except dsymutil actions, which use their actual input as the base 2080 // input. 2081 if (JA->getType() == types::TY_dSYM) 2082 BaseInput = InputInfos[0].getFilename(); 2083 2084 // Append outputs of cuda device jobs to the input list 2085 if (CudaDeviceInputInfos.size()) 2086 InputInfos.append(CudaDeviceInputInfos.begin(), CudaDeviceInputInfos.end()); 2087 2088 // Determine the place to write output to, if any. 2089 InputInfo Result; 2090 if (JA->getType() == types::TY_Nothing) 2091 Result = InputInfo(A, BaseInput); 2092 else 2093 Result = InputInfo(A, GetNamedOutputPath(C, *JA, BaseInput, BoundArch, 2094 AtTopLevel, MultipleArchs), 2095 BaseInput); 2096 2097 if (CCCPrintBindings && !CCGenDiagnostics) { 2098 llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"' 2099 << " - \"" << T->getName() << "\", inputs: ["; 2100 for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) { 2101 llvm::errs() << InputInfos[i].getAsString(); 2102 if (i + 1 != e) 2103 llvm::errs() << ", "; 2104 } 2105 llvm::errs() << "], output: " << Result.getAsString() << "\n"; 2106 } else { 2107 T->ConstructJob(C, *JA, Result, InputInfos, 2108 C.getArgsForToolChain(TC, BoundArch), LinkingOutput); 2109 } 2110 return Result; 2111 } 2112 2113 const char *Driver::getDefaultImageName() const { 2114 llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple)); 2115 return Target.isOSWindows() ? "a.exe" : "a.out"; 2116 } 2117 2118 /// \brief Create output filename based on ArgValue, which could either be a 2119 /// full filename, filename without extension, or a directory. If ArgValue 2120 /// does not provide a filename, then use BaseName, and use the extension 2121 /// suitable for FileType. 2122 static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue, 2123 StringRef BaseName, 2124 types::ID FileType) { 2125 SmallString<128> Filename = ArgValue; 2126 2127 if (ArgValue.empty()) { 2128 // If the argument is empty, output to BaseName in the current dir. 2129 Filename = BaseName; 2130 } else if (llvm::sys::path::is_separator(Filename.back())) { 2131 // If the argument is a directory, output to BaseName in that dir. 2132 llvm::sys::path::append(Filename, BaseName); 2133 } 2134 2135 if (!llvm::sys::path::has_extension(ArgValue)) { 2136 // If the argument didn't provide an extension, then set it. 2137 const char *Extension = types::getTypeTempSuffix(FileType, true); 2138 2139 if (FileType == types::TY_Image && 2140 Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) { 2141 // The output file is a dll. 2142 Extension = "dll"; 2143 } 2144 2145 llvm::sys::path::replace_extension(Filename, Extension); 2146 } 2147 2148 return Args.MakeArgString(Filename.c_str()); 2149 } 2150 2151 const char *Driver::GetNamedOutputPath(Compilation &C, const JobAction &JA, 2152 const char *BaseInput, 2153 const char *BoundArch, bool AtTopLevel, 2154 bool MultipleArchs) const { 2155 llvm::PrettyStackTraceString CrashInfo("Computing output path"); 2156 // Output to a user requested destination? 2157 if (AtTopLevel && !isa<DsymutilJobAction>(JA) && !isa<VerifyJobAction>(JA)) { 2158 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) 2159 return C.addResultFile(FinalOutput->getValue(), &JA); 2160 } 2161 2162 // For /P, preprocess to file named after BaseInput. 2163 if (C.getArgs().hasArg(options::OPT__SLASH_P)) { 2164 assert(AtTopLevel && isa<PreprocessJobAction>(JA)); 2165 StringRef BaseName = llvm::sys::path::filename(BaseInput); 2166 StringRef NameArg; 2167 if (Arg *A = C.getArgs().getLastArg(options::OPT__SLASH_Fi)) 2168 NameArg = A->getValue(); 2169 return C.addResultFile( 2170 MakeCLOutputFilename(C.getArgs(), NameArg, BaseName, types::TY_PP_C), 2171 &JA); 2172 } 2173 2174 // Default to writing to stdout? 2175 if (AtTopLevel && !CCGenDiagnostics && 2176 (isa<PreprocessJobAction>(JA) || JA.getType() == types::TY_ModuleFile)) 2177 return "-"; 2178 2179 // Is this the assembly listing for /FA? 2180 if (JA.getType() == types::TY_PP_Asm && 2181 (C.getArgs().hasArg(options::OPT__SLASH_FA) || 2182 C.getArgs().hasArg(options::OPT__SLASH_Fa))) { 2183 // Use /Fa and the input filename to determine the asm file name. 2184 StringRef BaseName = llvm::sys::path::filename(BaseInput); 2185 StringRef FaValue = C.getArgs().getLastArgValue(options::OPT__SLASH_Fa); 2186 return C.addResultFile( 2187 MakeCLOutputFilename(C.getArgs(), FaValue, BaseName, JA.getType()), 2188 &JA); 2189 } 2190 2191 // Output to a temporary file? 2192 if ((!AtTopLevel && !isSaveTempsEnabled() && 2193 !C.getArgs().hasArg(options::OPT__SLASH_Fo)) || 2194 CCGenDiagnostics) { 2195 StringRef Name = llvm::sys::path::filename(BaseInput); 2196 std::pair<StringRef, StringRef> Split = Name.split('.'); 2197 std::string TmpName = GetTemporaryPath( 2198 Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode())); 2199 return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str())); 2200 } 2201 2202 SmallString<128> BasePath(BaseInput); 2203 StringRef BaseName; 2204 2205 // Dsymutil actions should use the full path. 2206 if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA)) 2207 BaseName = BasePath; 2208 else 2209 BaseName = llvm::sys::path::filename(BasePath); 2210 2211 // Determine what the derived output name should be. 2212 const char *NamedOutput; 2213 2214 if (JA.getType() == types::TY_Object && 2215 C.getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) { 2216 // The /Fo or /o flag decides the object filename. 2217 StringRef Val = 2218 C.getArgs() 2219 .getLastArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o) 2220 ->getValue(); 2221 NamedOutput = 2222 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object); 2223 } else if (JA.getType() == types::TY_Image && 2224 C.getArgs().hasArg(options::OPT__SLASH_Fe, 2225 options::OPT__SLASH_o)) { 2226 // The /Fe or /o flag names the linked file. 2227 StringRef Val = 2228 C.getArgs() 2229 .getLastArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o) 2230 ->getValue(); 2231 NamedOutput = 2232 MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Image); 2233 } else if (JA.getType() == types::TY_Image) { 2234 if (IsCLMode()) { 2235 // clang-cl uses BaseName for the executable name. 2236 NamedOutput = 2237 MakeCLOutputFilename(C.getArgs(), "", BaseName, types::TY_Image); 2238 } else if (MultipleArchs && BoundArch) { 2239 SmallString<128> Output(getDefaultImageName()); 2240 Output += "-"; 2241 Output.append(BoundArch); 2242 NamedOutput = C.getArgs().MakeArgString(Output.c_str()); 2243 } else { 2244 NamedOutput = getDefaultImageName(); 2245 } 2246 } else if (JA.getType() == types::TY_PCH && IsCLMode()) { 2247 NamedOutput = C.getArgs().MakeArgString(GetClPchPath(C, BaseName).c_str()); 2248 } else { 2249 const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode()); 2250 assert(Suffix && "All types used for output should have a suffix."); 2251 2252 std::string::size_type End = std::string::npos; 2253 if (!types::appendSuffixForType(JA.getType())) 2254 End = BaseName.rfind('.'); 2255 SmallString<128> Suffixed(BaseName.substr(0, End)); 2256 if (MultipleArchs && BoundArch) { 2257 Suffixed += "-"; 2258 Suffixed.append(BoundArch); 2259 } 2260 // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for 2261 // the unoptimized bitcode so that it does not get overwritten by the ".bc" 2262 // optimized bitcode output. 2263 if (!AtTopLevel && C.getArgs().hasArg(options::OPT_emit_llvm) && 2264 JA.getType() == types::TY_LLVM_BC) 2265 Suffixed += ".tmp"; 2266 Suffixed += '.'; 2267 Suffixed += Suffix; 2268 NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str()); 2269 } 2270 2271 // Prepend object file path if -save-temps=obj 2272 if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(options::OPT_o) && 2273 JA.getType() != types::TY_PCH) { 2274 Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o); 2275 SmallString<128> TempPath(FinalOutput->getValue()); 2276 llvm::sys::path::remove_filename(TempPath); 2277 StringRef OutputFileName = llvm::sys::path::filename(NamedOutput); 2278 llvm::sys::path::append(TempPath, OutputFileName); 2279 NamedOutput = C.getArgs().MakeArgString(TempPath.c_str()); 2280 } 2281 2282 // If we're saving temps and the temp file conflicts with the input file, 2283 // then avoid overwriting input file. 2284 if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) { 2285 bool SameFile = false; 2286 SmallString<256> Result; 2287 llvm::sys::fs::current_path(Result); 2288 llvm::sys::path::append(Result, BaseName); 2289 llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile); 2290 // Must share the same path to conflict. 2291 if (SameFile) { 2292 StringRef Name = llvm::sys::path::filename(BaseInput); 2293 std::pair<StringRef, StringRef> Split = Name.split('.'); 2294 std::string TmpName = GetTemporaryPath( 2295 Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode())); 2296 return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str())); 2297 } 2298 } 2299 2300 // As an annoying special case, PCH generation doesn't strip the pathname. 2301 if (JA.getType() == types::TY_PCH && !IsCLMode()) { 2302 llvm::sys::path::remove_filename(BasePath); 2303 if (BasePath.empty()) 2304 BasePath = NamedOutput; 2305 else 2306 llvm::sys::path::append(BasePath, NamedOutput); 2307 return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA); 2308 } else { 2309 return C.addResultFile(NamedOutput, &JA); 2310 } 2311 } 2312 2313 std::string Driver::GetFilePath(const char *Name, const ToolChain &TC) const { 2314 // Respect a limited subset of the '-Bprefix' functionality in GCC by 2315 // attempting to use this prefix when looking for file paths. 2316 for (const std::string &Dir : PrefixDirs) { 2317 if (Dir.empty()) 2318 continue; 2319 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir); 2320 llvm::sys::path::append(P, Name); 2321 if (llvm::sys::fs::exists(Twine(P))) 2322 return P.str(); 2323 } 2324 2325 SmallString<128> P(ResourceDir); 2326 llvm::sys::path::append(P, Name); 2327 if (llvm::sys::fs::exists(Twine(P))) 2328 return P.str(); 2329 2330 for (const std::string &Dir : TC.getFilePaths()) { 2331 if (Dir.empty()) 2332 continue; 2333 SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir); 2334 llvm::sys::path::append(P, Name); 2335 if (llvm::sys::fs::exists(Twine(P))) 2336 return P.str(); 2337 } 2338 2339 return Name; 2340 } 2341 2342 void Driver::generatePrefixedToolNames( 2343 const char *Tool, const ToolChain &TC, 2344 SmallVectorImpl<std::string> &Names) const { 2345 // FIXME: Needs a better variable than DefaultTargetTriple 2346 Names.emplace_back(DefaultTargetTriple + "-" + Tool); 2347 Names.emplace_back(Tool); 2348 2349 // Allow the discovery of tools prefixed with LLVM's default target triple. 2350 std::string LLVMDefaultTargetTriple = llvm::sys::getDefaultTargetTriple(); 2351 if (LLVMDefaultTargetTriple != DefaultTargetTriple) 2352 Names.emplace_back(LLVMDefaultTargetTriple + "-" + Tool); 2353 } 2354 2355 static bool ScanDirForExecutable(SmallString<128> &Dir, 2356 ArrayRef<std::string> Names) { 2357 for (const auto &Name : Names) { 2358 llvm::sys::path::append(Dir, Name); 2359 if (llvm::sys::fs::can_execute(Twine(Dir))) 2360 return true; 2361 llvm::sys::path::remove_filename(Dir); 2362 } 2363 return false; 2364 } 2365 2366 std::string Driver::GetProgramPath(const char *Name, 2367 const ToolChain &TC) const { 2368 SmallVector<std::string, 2> TargetSpecificExecutables; 2369 generatePrefixedToolNames(Name, TC, TargetSpecificExecutables); 2370 2371 // Respect a limited subset of the '-Bprefix' functionality in GCC by 2372 // attempting to use this prefix when looking for program paths. 2373 for (const auto &PrefixDir : PrefixDirs) { 2374 if (llvm::sys::fs::is_directory(PrefixDir)) { 2375 SmallString<128> P(PrefixDir); 2376 if (ScanDirForExecutable(P, TargetSpecificExecutables)) 2377 return P.str(); 2378 } else { 2379 SmallString<128> P(PrefixDir + Name); 2380 if (llvm::sys::fs::can_execute(Twine(P))) 2381 return P.str(); 2382 } 2383 } 2384 2385 const ToolChain::path_list &List = TC.getProgramPaths(); 2386 for (const auto &Path : List) { 2387 SmallString<128> P(Path); 2388 if (ScanDirForExecutable(P, TargetSpecificExecutables)) 2389 return P.str(); 2390 } 2391 2392 // If all else failed, search the path. 2393 for (const auto &TargetSpecificExecutable : TargetSpecificExecutables) 2394 if (llvm::ErrorOr<std::string> P = 2395 llvm::sys::findProgramByName(TargetSpecificExecutable)) 2396 return *P; 2397 2398 return Name; 2399 } 2400 2401 std::string Driver::GetTemporaryPath(StringRef Prefix, 2402 const char *Suffix) const { 2403 SmallString<128> Path; 2404 std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path); 2405 if (EC) { 2406 Diag(clang::diag::err_unable_to_make_temp) << EC.message(); 2407 return ""; 2408 } 2409 2410 return Path.str(); 2411 } 2412 2413 std::string Driver::GetClPchPath(Compilation &C, StringRef BaseName) const { 2414 SmallString<128> Output; 2415 if (Arg *FpArg = C.getArgs().getLastArg(options::OPT__SLASH_Fp)) { 2416 // FIXME: If anybody needs it, implement this obscure rule: 2417 // "If you specify a directory without a file name, the default file name 2418 // is VCx0.pch., where x is the major version of Visual C++ in use." 2419 Output = FpArg->getValue(); 2420 2421 // "If you do not specify an extension as part of the path name, an 2422 // extension of .pch is assumed. " 2423 if (!llvm::sys::path::has_extension(Output)) 2424 Output += ".pch"; 2425 } else { 2426 Output = BaseName; 2427 llvm::sys::path::replace_extension(Output, ".pch"); 2428 } 2429 return Output.str(); 2430 } 2431 2432 const ToolChain &Driver::getToolChain(const ArgList &Args, 2433 const llvm::Triple &Target) const { 2434 2435 ToolChain *&TC = ToolChains[Target.str()]; 2436 if (!TC) { 2437 switch (Target.getOS()) { 2438 case llvm::Triple::Haiku: 2439 TC = new toolchains::Haiku(*this, Target, Args); 2440 break; 2441 case llvm::Triple::CloudABI: 2442 TC = new toolchains::CloudABI(*this, Target, Args); 2443 break; 2444 case llvm::Triple::Darwin: 2445 case llvm::Triple::MacOSX: 2446 case llvm::Triple::IOS: 2447 case llvm::Triple::TvOS: 2448 case llvm::Triple::WatchOS: 2449 TC = new toolchains::DarwinClang(*this, Target, Args); 2450 break; 2451 case llvm::Triple::DragonFly: 2452 TC = new toolchains::DragonFly(*this, Target, Args); 2453 break; 2454 case llvm::Triple::OpenBSD: 2455 TC = new toolchains::OpenBSD(*this, Target, Args); 2456 break; 2457 case llvm::Triple::Bitrig: 2458 TC = new toolchains::Bitrig(*this, Target, Args); 2459 break; 2460 case llvm::Triple::NetBSD: 2461 TC = new toolchains::NetBSD(*this, Target, Args); 2462 break; 2463 case llvm::Triple::FreeBSD: 2464 TC = new toolchains::FreeBSD(*this, Target, Args); 2465 break; 2466 case llvm::Triple::Minix: 2467 TC = new toolchains::Minix(*this, Target, Args); 2468 break; 2469 case llvm::Triple::Linux: 2470 if (Target.getArch() == llvm::Triple::hexagon) 2471 TC = new toolchains::HexagonToolChain(*this, Target, Args); 2472 else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) && 2473 !Target.hasEnvironment()) 2474 TC = new toolchains::MipsLLVMToolChain(*this, Target, Args); 2475 else 2476 TC = new toolchains::Linux(*this, Target, Args); 2477 break; 2478 case llvm::Triple::NaCl: 2479 TC = new toolchains::NaClToolChain(*this, Target, Args); 2480 break; 2481 case llvm::Triple::Solaris: 2482 TC = new toolchains::Solaris(*this, Target, Args); 2483 break; 2484 case llvm::Triple::AMDHSA: 2485 TC = new toolchains::AMDGPUToolChain(*this, Target, Args); 2486 break; 2487 case llvm::Triple::Win32: 2488 switch (Target.getEnvironment()) { 2489 default: 2490 if (Target.isOSBinFormatELF()) 2491 TC = new toolchains::Generic_ELF(*this, Target, Args); 2492 else if (Target.isOSBinFormatMachO()) 2493 TC = new toolchains::MachO(*this, Target, Args); 2494 else 2495 TC = new toolchains::Generic_GCC(*this, Target, Args); 2496 break; 2497 case llvm::Triple::GNU: 2498 TC = new toolchains::MinGW(*this, Target, Args); 2499 break; 2500 case llvm::Triple::Itanium: 2501 TC = new toolchains::CrossWindowsToolChain(*this, Target, Args); 2502 break; 2503 case llvm::Triple::MSVC: 2504 case llvm::Triple::UnknownEnvironment: 2505 TC = new toolchains::MSVCToolChain(*this, Target, Args); 2506 break; 2507 } 2508 break; 2509 case llvm::Triple::CUDA: 2510 TC = new toolchains::CudaToolChain(*this, Target, Args); 2511 break; 2512 case llvm::Triple::PS4: 2513 TC = new toolchains::PS4CPU(*this, Target, Args); 2514 break; 2515 default: 2516 // Of these targets, Hexagon is the only one that might have 2517 // an OS of Linux, in which case it got handled above already. 2518 switch (Target.getArch()) { 2519 case llvm::Triple::tce: 2520 TC = new toolchains::TCEToolChain(*this, Target, Args); 2521 break; 2522 case llvm::Triple::hexagon: 2523 TC = new toolchains::HexagonToolChain(*this, Target, Args); 2524 break; 2525 case llvm::Triple::lanai: 2526 TC = new toolchains::LanaiToolChain(*this, Target, Args); 2527 break; 2528 case llvm::Triple::xcore: 2529 TC = new toolchains::XCoreToolChain(*this, Target, Args); 2530 break; 2531 case llvm::Triple::wasm32: 2532 case llvm::Triple::wasm64: 2533 TC = new toolchains::WebAssembly(*this, Target, Args); 2534 break; 2535 default: 2536 if (Target.getVendor() == llvm::Triple::Myriad) 2537 TC = new toolchains::MyriadToolChain(*this, Target, Args); 2538 else if (Target.isOSBinFormatELF()) 2539 TC = new toolchains::Generic_ELF(*this, Target, Args); 2540 else if (Target.isOSBinFormatMachO()) 2541 TC = new toolchains::MachO(*this, Target, Args); 2542 else 2543 TC = new toolchains::Generic_GCC(*this, Target, Args); 2544 } 2545 } 2546 } 2547 return *TC; 2548 } 2549 2550 bool Driver::ShouldUseClangCompiler(const JobAction &JA) const { 2551 // Say "no" if there is not exactly one input of a type clang understands. 2552 if (JA.size() != 1 || 2553 !types::isAcceptedByClang((*JA.input_begin())->getType())) 2554 return false; 2555 2556 // And say "no" if this is not a kind of action clang understands. 2557 if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) && 2558 !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA)) 2559 return false; 2560 2561 return true; 2562 } 2563 2564 /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the 2565 /// grouped values as integers. Numbers which are not provided are set to 0. 2566 /// 2567 /// \return True if the entire string was parsed (9.2), or all groups were 2568 /// parsed (10.3.5extrastuff). 2569 bool Driver::GetReleaseVersion(const char *Str, unsigned &Major, 2570 unsigned &Minor, unsigned &Micro, 2571 bool &HadExtra) { 2572 HadExtra = false; 2573 2574 Major = Minor = Micro = 0; 2575 if (*Str == '\0') 2576 return false; 2577 2578 char *End; 2579 Major = (unsigned)strtol(Str, &End, 10); 2580 if (*Str != '\0' && *End == '\0') 2581 return true; 2582 if (*End != '.') 2583 return false; 2584 2585 Str = End + 1; 2586 Minor = (unsigned)strtol(Str, &End, 10); 2587 if (*Str != '\0' && *End == '\0') 2588 return true; 2589 if (*End != '.') 2590 return false; 2591 2592 Str = End + 1; 2593 Micro = (unsigned)strtol(Str, &End, 10); 2594 if (*Str != '\0' && *End == '\0') 2595 return true; 2596 if (Str == End) 2597 return false; 2598 HadExtra = true; 2599 return true; 2600 } 2601 2602 /// Parse digits from a string \p Str and fulfill \p Digits with 2603 /// the parsed numbers. This method assumes that the max number of 2604 /// digits to look for is equal to Digits.size(). 2605 /// 2606 /// \return True if the entire string was parsed and there are 2607 /// no extra characters remaining at the end. 2608 bool Driver::GetReleaseVersion(const char *Str, 2609 MutableArrayRef<unsigned> Digits) { 2610 if (*Str == '\0') 2611 return false; 2612 2613 char *End; 2614 unsigned CurDigit = 0; 2615 while (CurDigit < Digits.size()) { 2616 unsigned Digit = (unsigned)strtol(Str, &End, 10); 2617 Digits[CurDigit] = Digit; 2618 if (*Str != '\0' && *End == '\0') 2619 return true; 2620 if (*End != '.' || Str == End) 2621 return false; 2622 Str = End + 1; 2623 CurDigit++; 2624 } 2625 2626 // More digits than requested, bail out... 2627 return false; 2628 } 2629 2630 std::pair<unsigned, unsigned> Driver::getIncludeExcludeOptionFlagMasks() const { 2631 unsigned IncludedFlagsBitmask = 0; 2632 unsigned ExcludedFlagsBitmask = options::NoDriverOption; 2633 2634 if (Mode == CLMode) { 2635 // Include CL and Core options. 2636 IncludedFlagsBitmask |= options::CLOption; 2637 IncludedFlagsBitmask |= options::CoreOption; 2638 } else { 2639 ExcludedFlagsBitmask |= options::CLOption; 2640 } 2641 2642 return std::make_pair(IncludedFlagsBitmask, ExcludedFlagsBitmask); 2643 } 2644 2645 bool clang::driver::isOptimizationLevelFast(const ArgList &Args) { 2646 return Args.hasFlag(options::OPT_Ofast, options::OPT_O_Group, false); 2647 } 2648