Clang.cpp revision 344779
1//===--- LLVM.cpp - Clang+LLVM ToolChain Implementations --------*- C++ -*-===// 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.h" 11#include "Arch/AArch64.h" 12#include "Arch/ARM.h" 13#include "Arch/Mips.h" 14#include "Arch/PPC.h" 15#include "Arch/RISCV.h" 16#include "Arch/Sparc.h" 17#include "Arch/SystemZ.h" 18#include "Arch/X86.h" 19#include "AMDGPU.h" 20#include "CommonArgs.h" 21#include "Hexagon.h" 22#include "MSP430.h" 23#include "InputInfo.h" 24#include "PS4CPU.h" 25#include "clang/Basic/CharInfo.h" 26#include "clang/Basic/LangOptions.h" 27#include "clang/Basic/ObjCRuntime.h" 28#include "clang/Basic/Version.h" 29#include "clang/Driver/Distro.h" 30#include "clang/Driver/DriverDiagnostic.h" 31#include "clang/Driver/Options.h" 32#include "clang/Driver/SanitizerArgs.h" 33#include "clang/Driver/XRayArgs.h" 34#include "llvm/ADT/StringExtras.h" 35#include "llvm/Config/llvm-config.h" 36#include "llvm/Option/ArgList.h" 37#include "llvm/Support/CodeGen.h" 38#include "llvm/Support/Compression.h" 39#include "llvm/Support/FileSystem.h" 40#include "llvm/Support/Path.h" 41#include "llvm/Support/Process.h" 42#include "llvm/Support/TargetParser.h" 43#include "llvm/Support/YAMLParser.h" 44 45#ifdef LLVM_ON_UNIX 46#include <unistd.h> // For getuid(). 47#endif 48 49using namespace clang::driver; 50using namespace clang::driver::tools; 51using namespace clang; 52using namespace llvm::opt; 53 54static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) { 55 if (Arg *A = 56 Args.getLastArg(clang::driver::options::OPT_C, options::OPT_CC)) { 57 if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_P) && 58 !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) { 59 D.Diag(clang::diag::err_drv_argument_only_allowed_with) 60 << A->getBaseArg().getAsString(Args) 61 << (D.IsCLMode() ? "/E, /P or /EP" : "-E"); 62 } 63 } 64} 65 66static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) { 67 // In gcc, only ARM checks this, but it seems reasonable to check universally. 68 if (Args.hasArg(options::OPT_static)) 69 if (const Arg *A = 70 Args.getLastArg(options::OPT_dynamic, options::OPT_mdynamic_no_pic)) 71 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args) 72 << "-static"; 73} 74 75// Add backslashes to escape spaces and other backslashes. 76// This is used for the space-separated argument list specified with 77// the -dwarf-debug-flags option. 78static void EscapeSpacesAndBackslashes(const char *Arg, 79 SmallVectorImpl<char> &Res) { 80 for (; *Arg; ++Arg) { 81 switch (*Arg) { 82 default: 83 break; 84 case ' ': 85 case '\\': 86 Res.push_back('\\'); 87 break; 88 } 89 Res.push_back(*Arg); 90 } 91} 92 93// Quote target names for inclusion in GNU Make dependency files. 94// Only the characters '$', '#', ' ', '\t' are quoted. 95static void QuoteTarget(StringRef Target, SmallVectorImpl<char> &Res) { 96 for (unsigned i = 0, e = Target.size(); i != e; ++i) { 97 switch (Target[i]) { 98 case ' ': 99 case '\t': 100 // Escape the preceding backslashes 101 for (int j = i - 1; j >= 0 && Target[j] == '\\'; --j) 102 Res.push_back('\\'); 103 104 // Escape the space/tab 105 Res.push_back('\\'); 106 break; 107 case '$': 108 Res.push_back('$'); 109 break; 110 case '#': 111 Res.push_back('\\'); 112 break; 113 default: 114 break; 115 } 116 117 Res.push_back(Target[i]); 118 } 119} 120 121/// Apply \a Work on the current tool chain \a RegularToolChain and any other 122/// offloading tool chain that is associated with the current action \a JA. 123static void 124forAllAssociatedToolChains(Compilation &C, const JobAction &JA, 125 const ToolChain &RegularToolChain, 126 llvm::function_ref<void(const ToolChain &)> Work) { 127 // Apply Work on the current/regular tool chain. 128 Work(RegularToolChain); 129 130 // Apply Work on all the offloading tool chains associated with the current 131 // action. 132 if (JA.isHostOffloading(Action::OFK_Cuda)) 133 Work(*C.getSingleOffloadToolChain<Action::OFK_Cuda>()); 134 else if (JA.isDeviceOffloading(Action::OFK_Cuda)) 135 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>()); 136 else if (JA.isHostOffloading(Action::OFK_HIP)) 137 Work(*C.getSingleOffloadToolChain<Action::OFK_HIP>()); 138 else if (JA.isDeviceOffloading(Action::OFK_HIP)) 139 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>()); 140 141 if (JA.isHostOffloading(Action::OFK_OpenMP)) { 142 auto TCs = C.getOffloadToolChains<Action::OFK_OpenMP>(); 143 for (auto II = TCs.first, IE = TCs.second; II != IE; ++II) 144 Work(*II->second); 145 } else if (JA.isDeviceOffloading(Action::OFK_OpenMP)) 146 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>()); 147 148 // 149 // TODO: Add support for other offloading programming models here. 150 // 151} 152 153/// This is a helper function for validating the optional refinement step 154/// parameter in reciprocal argument strings. Return false if there is an error 155/// parsing the refinement step. Otherwise, return true and set the Position 156/// of the refinement step in the input string. 157static bool getRefinementStep(StringRef In, const Driver &D, 158 const Arg &A, size_t &Position) { 159 const char RefinementStepToken = ':'; 160 Position = In.find(RefinementStepToken); 161 if (Position != StringRef::npos) { 162 StringRef Option = A.getOption().getName(); 163 StringRef RefStep = In.substr(Position + 1); 164 // Allow exactly one numeric character for the additional refinement 165 // step parameter. This is reasonable for all currently-supported 166 // operations and architectures because we would expect that a larger value 167 // of refinement steps would cause the estimate "optimization" to 168 // under-perform the native operation. Also, if the estimate does not 169 // converge quickly, it probably will not ever converge, so further 170 // refinement steps will not produce a better answer. 171 if (RefStep.size() != 1) { 172 D.Diag(diag::err_drv_invalid_value) << Option << RefStep; 173 return false; 174 } 175 char RefStepChar = RefStep[0]; 176 if (RefStepChar < '0' || RefStepChar > '9') { 177 D.Diag(diag::err_drv_invalid_value) << Option << RefStep; 178 return false; 179 } 180 } 181 return true; 182} 183 184/// The -mrecip flag requires processing of many optional parameters. 185static void ParseMRecip(const Driver &D, const ArgList &Args, 186 ArgStringList &OutStrings) { 187 StringRef DisabledPrefixIn = "!"; 188 StringRef DisabledPrefixOut = "!"; 189 StringRef EnabledPrefixOut = ""; 190 StringRef Out = "-mrecip="; 191 192 Arg *A = Args.getLastArg(options::OPT_mrecip, options::OPT_mrecip_EQ); 193 if (!A) 194 return; 195 196 unsigned NumOptions = A->getNumValues(); 197 if (NumOptions == 0) { 198 // No option is the same as "all". 199 OutStrings.push_back(Args.MakeArgString(Out + "all")); 200 return; 201 } 202 203 // Pass through "all", "none", or "default" with an optional refinement step. 204 if (NumOptions == 1) { 205 StringRef Val = A->getValue(0); 206 size_t RefStepLoc; 207 if (!getRefinementStep(Val, D, *A, RefStepLoc)) 208 return; 209 StringRef ValBase = Val.slice(0, RefStepLoc); 210 if (ValBase == "all" || ValBase == "none" || ValBase == "default") { 211 OutStrings.push_back(Args.MakeArgString(Out + Val)); 212 return; 213 } 214 } 215 216 // Each reciprocal type may be enabled or disabled individually. 217 // Check each input value for validity, concatenate them all back together, 218 // and pass through. 219 220 llvm::StringMap<bool> OptionStrings; 221 OptionStrings.insert(std::make_pair("divd", false)); 222 OptionStrings.insert(std::make_pair("divf", false)); 223 OptionStrings.insert(std::make_pair("vec-divd", false)); 224 OptionStrings.insert(std::make_pair("vec-divf", false)); 225 OptionStrings.insert(std::make_pair("sqrtd", false)); 226 OptionStrings.insert(std::make_pair("sqrtf", false)); 227 OptionStrings.insert(std::make_pair("vec-sqrtd", false)); 228 OptionStrings.insert(std::make_pair("vec-sqrtf", false)); 229 230 for (unsigned i = 0; i != NumOptions; ++i) { 231 StringRef Val = A->getValue(i); 232 233 bool IsDisabled = Val.startswith(DisabledPrefixIn); 234 // Ignore the disablement token for string matching. 235 if (IsDisabled) 236 Val = Val.substr(1); 237 238 size_t RefStep; 239 if (!getRefinementStep(Val, D, *A, RefStep)) 240 return; 241 242 StringRef ValBase = Val.slice(0, RefStep); 243 llvm::StringMap<bool>::iterator OptionIter = OptionStrings.find(ValBase); 244 if (OptionIter == OptionStrings.end()) { 245 // Try again specifying float suffix. 246 OptionIter = OptionStrings.find(ValBase.str() + 'f'); 247 if (OptionIter == OptionStrings.end()) { 248 // The input name did not match any known option string. 249 D.Diag(diag::err_drv_unknown_argument) << Val; 250 return; 251 } 252 // The option was specified without a float or double suffix. 253 // Make sure that the double entry was not already specified. 254 // The float entry will be checked below. 255 if (OptionStrings[ValBase.str() + 'd']) { 256 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val; 257 return; 258 } 259 } 260 261 if (OptionIter->second == true) { 262 // Duplicate option specified. 263 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val; 264 return; 265 } 266 267 // Mark the matched option as found. Do not allow duplicate specifiers. 268 OptionIter->second = true; 269 270 // If the precision was not specified, also mark the double entry as found. 271 if (ValBase.back() != 'f' && ValBase.back() != 'd') 272 OptionStrings[ValBase.str() + 'd'] = true; 273 274 // Build the output string. 275 StringRef Prefix = IsDisabled ? DisabledPrefixOut : EnabledPrefixOut; 276 Out = Args.MakeArgString(Out + Prefix + Val); 277 if (i != NumOptions - 1) 278 Out = Args.MakeArgString(Out + ","); 279 } 280 281 OutStrings.push_back(Args.MakeArgString(Out)); 282} 283 284/// The -mprefer-vector-width option accepts either a positive integer 285/// or the string "none". 286static void ParseMPreferVectorWidth(const Driver &D, const ArgList &Args, 287 ArgStringList &CmdArgs) { 288 Arg *A = Args.getLastArg(options::OPT_mprefer_vector_width_EQ); 289 if (!A) 290 return; 291 292 StringRef Value = A->getValue(); 293 if (Value == "none") { 294 CmdArgs.push_back("-mprefer-vector-width=none"); 295 } else { 296 unsigned Width; 297 if (Value.getAsInteger(10, Width)) { 298 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value; 299 return; 300 } 301 CmdArgs.push_back(Args.MakeArgString("-mprefer-vector-width=" + Value)); 302 } 303} 304 305static void getWebAssemblyTargetFeatures(const ArgList &Args, 306 std::vector<StringRef> &Features) { 307 handleTargetFeaturesGroup(Args, Features, options::OPT_m_wasm_Features_Group); 308} 309 310static void getTargetFeatures(const ToolChain &TC, const llvm::Triple &Triple, 311 const ArgList &Args, ArgStringList &CmdArgs, 312 bool ForAS) { 313 const Driver &D = TC.getDriver(); 314 std::vector<StringRef> Features; 315 switch (Triple.getArch()) { 316 default: 317 break; 318 case llvm::Triple::mips: 319 case llvm::Triple::mipsel: 320 case llvm::Triple::mips64: 321 case llvm::Triple::mips64el: 322 mips::getMIPSTargetFeatures(D, Triple, Args, Features); 323 break; 324 325 case llvm::Triple::arm: 326 case llvm::Triple::armeb: 327 case llvm::Triple::thumb: 328 case llvm::Triple::thumbeb: 329 arm::getARMTargetFeatures(TC, Triple, Args, CmdArgs, Features, ForAS); 330 break; 331 332 case llvm::Triple::ppc: 333 case llvm::Triple::ppc64: 334 case llvm::Triple::ppc64le: 335 ppc::getPPCTargetFeatures(D, Triple, Args, Features); 336 break; 337 case llvm::Triple::riscv32: 338 case llvm::Triple::riscv64: 339 riscv::getRISCVTargetFeatures(D, Args, Features); 340 break; 341 case llvm::Triple::systemz: 342 systemz::getSystemZTargetFeatures(Args, Features); 343 break; 344 case llvm::Triple::aarch64: 345 case llvm::Triple::aarch64_be: 346 aarch64::getAArch64TargetFeatures(D, Triple, Args, Features); 347 break; 348 case llvm::Triple::x86: 349 case llvm::Triple::x86_64: 350 x86::getX86TargetFeatures(D, Triple, Args, Features); 351 break; 352 case llvm::Triple::hexagon: 353 hexagon::getHexagonTargetFeatures(D, Args, Features); 354 break; 355 case llvm::Triple::wasm32: 356 case llvm::Triple::wasm64: 357 getWebAssemblyTargetFeatures(Args, Features); 358 break; 359 case llvm::Triple::sparc: 360 case llvm::Triple::sparcel: 361 case llvm::Triple::sparcv9: 362 sparc::getSparcTargetFeatures(D, Args, Features); 363 break; 364 case llvm::Triple::r600: 365 case llvm::Triple::amdgcn: 366 amdgpu::getAMDGPUTargetFeatures(D, Args, Features); 367 break; 368 case llvm::Triple::msp430: 369 msp430::getMSP430TargetFeatures(D, Args, Features); 370 } 371 372 // Find the last of each feature. 373 llvm::StringMap<unsigned> LastOpt; 374 for (unsigned I = 0, N = Features.size(); I < N; ++I) { 375 StringRef Name = Features[I]; 376 assert(Name[0] == '-' || Name[0] == '+'); 377 LastOpt[Name.drop_front(1)] = I; 378 } 379 380 for (unsigned I = 0, N = Features.size(); I < N; ++I) { 381 // If this feature was overridden, ignore it. 382 StringRef Name = Features[I]; 383 llvm::StringMap<unsigned>::iterator LastI = LastOpt.find(Name.drop_front(1)); 384 assert(LastI != LastOpt.end()); 385 unsigned Last = LastI->second; 386 if (Last != I) 387 continue; 388 389 CmdArgs.push_back("-target-feature"); 390 CmdArgs.push_back(Name.data()); 391 } 392} 393 394static bool 395shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime, 396 const llvm::Triple &Triple) { 397 // We use the zero-cost exception tables for Objective-C if the non-fragile 398 // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and 399 // later. 400 if (runtime.isNonFragile()) 401 return true; 402 403 if (!Triple.isMacOSX()) 404 return false; 405 406 return (!Triple.isMacOSXVersionLT(10, 5) && 407 (Triple.getArch() == llvm::Triple::x86_64 || 408 Triple.getArch() == llvm::Triple::arm)); 409} 410 411/// Adds exception related arguments to the driver command arguments. There's a 412/// master flag, -fexceptions and also language specific flags to enable/disable 413/// C++ and Objective-C exceptions. This makes it possible to for example 414/// disable C++ exceptions but enable Objective-C exceptions. 415static void addExceptionArgs(const ArgList &Args, types::ID InputType, 416 const ToolChain &TC, bool KernelOrKext, 417 const ObjCRuntime &objcRuntime, 418 ArgStringList &CmdArgs) { 419 const llvm::Triple &Triple = TC.getTriple(); 420 421 if (KernelOrKext) { 422 // -mkernel and -fapple-kext imply no exceptions, so claim exception related 423 // arguments now to avoid warnings about unused arguments. 424 Args.ClaimAllArgs(options::OPT_fexceptions); 425 Args.ClaimAllArgs(options::OPT_fno_exceptions); 426 Args.ClaimAllArgs(options::OPT_fobjc_exceptions); 427 Args.ClaimAllArgs(options::OPT_fno_objc_exceptions); 428 Args.ClaimAllArgs(options::OPT_fcxx_exceptions); 429 Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions); 430 return; 431 } 432 433 // See if the user explicitly enabled exceptions. 434 bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions, 435 false); 436 437 // Obj-C exceptions are enabled by default, regardless of -fexceptions. This 438 // is not necessarily sensible, but follows GCC. 439 if (types::isObjC(InputType) && 440 Args.hasFlag(options::OPT_fobjc_exceptions, 441 options::OPT_fno_objc_exceptions, true)) { 442 CmdArgs.push_back("-fobjc-exceptions"); 443 444 EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple); 445 } 446 447 if (types::isCXX(InputType)) { 448 // Disable C++ EH by default on XCore and PS4. 449 bool CXXExceptionsEnabled = 450 Triple.getArch() != llvm::Triple::xcore && !Triple.isPS4CPU(); 451 Arg *ExceptionArg = Args.getLastArg( 452 options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions, 453 options::OPT_fexceptions, options::OPT_fno_exceptions); 454 if (ExceptionArg) 455 CXXExceptionsEnabled = 456 ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) || 457 ExceptionArg->getOption().matches(options::OPT_fexceptions); 458 459 if (CXXExceptionsEnabled) { 460 CmdArgs.push_back("-fcxx-exceptions"); 461 462 EH = true; 463 } 464 } 465 466 if (EH) 467 CmdArgs.push_back("-fexceptions"); 468} 469 470static bool ShouldDisableAutolink(const ArgList &Args, const ToolChain &TC) { 471 bool Default = true; 472 if (TC.getTriple().isOSDarwin()) { 473 // The native darwin assembler doesn't support the linker_option directives, 474 // so we disable them if we think the .s file will be passed to it. 475 Default = TC.useIntegratedAs(); 476 } 477 return !Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink, 478 Default); 479} 480 481static bool ShouldDisableDwarfDirectory(const ArgList &Args, 482 const ToolChain &TC) { 483 bool UseDwarfDirectory = 484 Args.hasFlag(options::OPT_fdwarf_directory_asm, 485 options::OPT_fno_dwarf_directory_asm, TC.useIntegratedAs()); 486 return !UseDwarfDirectory; 487} 488 489// Convert an arg of the form "-gN" or "-ggdbN" or one of their aliases 490// to the corresponding DebugInfoKind. 491static codegenoptions::DebugInfoKind DebugLevelToInfoKind(const Arg &A) { 492 assert(A.getOption().matches(options::OPT_gN_Group) && 493 "Not a -g option that specifies a debug-info level"); 494 if (A.getOption().matches(options::OPT_g0) || 495 A.getOption().matches(options::OPT_ggdb0)) 496 return codegenoptions::NoDebugInfo; 497 if (A.getOption().matches(options::OPT_gline_tables_only) || 498 A.getOption().matches(options::OPT_ggdb1)) 499 return codegenoptions::DebugLineTablesOnly; 500 if (A.getOption().matches(options::OPT_gline_directives_only)) 501 return codegenoptions::DebugDirectivesOnly; 502 return codegenoptions::LimitedDebugInfo; 503} 504 505static bool mustUseNonLeafFramePointerForTarget(const llvm::Triple &Triple) { 506 switch (Triple.getArch()){ 507 default: 508 return false; 509 case llvm::Triple::arm: 510 case llvm::Triple::thumb: 511 // ARM Darwin targets require a frame pointer to be always present to aid 512 // offline debugging via backtraces. 513 return Triple.isOSDarwin(); 514 } 515} 516 517static bool useFramePointerForTargetByDefault(const ArgList &Args, 518 const llvm::Triple &Triple) { 519 switch (Triple.getArch()) { 520 case llvm::Triple::xcore: 521 case llvm::Triple::wasm32: 522 case llvm::Triple::wasm64: 523 // XCore never wants frame pointers, regardless of OS. 524 // WebAssembly never wants frame pointers. 525 return false; 526 case llvm::Triple::riscv32: 527 case llvm::Triple::riscv64: 528 return !areOptimizationsEnabled(Args); 529 default: 530 break; 531 } 532 533 if (Triple.isOSNetBSD()) { 534 return !areOptimizationsEnabled(Args); 535 } 536 537 if (Triple.isOSLinux() || Triple.getOS() == llvm::Triple::CloudABI || 538 Triple.isOSHurd()) { 539 switch (Triple.getArch()) { 540 // Don't use a frame pointer on linux if optimizing for certain targets. 541 case llvm::Triple::mips64: 542 case llvm::Triple::mips64el: 543 case llvm::Triple::mips: 544 case llvm::Triple::mipsel: 545 case llvm::Triple::ppc: 546 case llvm::Triple::ppc64: 547 case llvm::Triple::ppc64le: 548 case llvm::Triple::systemz: 549 case llvm::Triple::x86: 550 case llvm::Triple::x86_64: 551 return !areOptimizationsEnabled(Args); 552 default: 553 return true; 554 } 555 } 556 557 if (Triple.isOSWindows()) { 558 switch (Triple.getArch()) { 559 case llvm::Triple::x86: 560 return !areOptimizationsEnabled(Args); 561 case llvm::Triple::x86_64: 562 return Triple.isOSBinFormatMachO(); 563 case llvm::Triple::arm: 564 case llvm::Triple::thumb: 565 // Windows on ARM builds with FPO disabled to aid fast stack walking 566 return true; 567 default: 568 // All other supported Windows ISAs use xdata unwind information, so frame 569 // pointers are not generally useful. 570 return false; 571 } 572 } 573 574 return true; 575} 576 577static bool shouldUseFramePointer(const ArgList &Args, 578 const llvm::Triple &Triple) { 579 if (Arg *A = Args.getLastArg(options::OPT_fno_omit_frame_pointer, 580 options::OPT_fomit_frame_pointer)) 581 return A->getOption().matches(options::OPT_fno_omit_frame_pointer) || 582 mustUseNonLeafFramePointerForTarget(Triple); 583 584 if (Args.hasArg(options::OPT_pg)) 585 return true; 586 587 return useFramePointerForTargetByDefault(Args, Triple); 588} 589 590static bool shouldUseLeafFramePointer(const ArgList &Args, 591 const llvm::Triple &Triple) { 592 if (Arg *A = Args.getLastArg(options::OPT_mno_omit_leaf_frame_pointer, 593 options::OPT_momit_leaf_frame_pointer)) 594 return A->getOption().matches(options::OPT_mno_omit_leaf_frame_pointer); 595 596 if (Args.hasArg(options::OPT_pg)) 597 return true; 598 599 if (Triple.isPS4CPU()) 600 return false; 601 602 return useFramePointerForTargetByDefault(Args, Triple); 603} 604 605/// Add a CC1 option to specify the debug compilation directory. 606static void addDebugCompDirArg(const ArgList &Args, ArgStringList &CmdArgs) { 607 SmallString<128> cwd; 608 if (!llvm::sys::fs::current_path(cwd)) { 609 CmdArgs.push_back("-fdebug-compilation-dir"); 610 CmdArgs.push_back(Args.MakeArgString(cwd)); 611 } 612} 613 614/// Add a CC1 and CC1AS option to specify the debug file path prefix map. 615static void addDebugPrefixMapArg(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs) { 616 for (const Arg *A : Args.filtered(options::OPT_fdebug_prefix_map_EQ)) { 617 StringRef Map = A->getValue(); 618 if (Map.find('=') == StringRef::npos) 619 D.Diag(diag::err_drv_invalid_argument_to_fdebug_prefix_map) << Map; 620 else 621 CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map)); 622 A->claim(); 623 } 624} 625 626/// Vectorize at all optimization levels greater than 1 except for -Oz. 627/// For -Oz the loop vectorizer is disable, while the slp vectorizer is enabled. 628static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) { 629 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) { 630 if (A->getOption().matches(options::OPT_O4) || 631 A->getOption().matches(options::OPT_Ofast)) 632 return true; 633 634 if (A->getOption().matches(options::OPT_O0)) 635 return false; 636 637 assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag"); 638 639 // Vectorize -Os. 640 StringRef S(A->getValue()); 641 if (S == "s") 642 return true; 643 644 // Don't vectorize -Oz, unless it's the slp vectorizer. 645 if (S == "z") 646 return isSlpVec; 647 648 unsigned OptLevel = 0; 649 if (S.getAsInteger(10, OptLevel)) 650 return false; 651 652 return OptLevel > 1; 653 } 654 655 return false; 656} 657 658/// Add -x lang to \p CmdArgs for \p Input. 659static void addDashXForInput(const ArgList &Args, const InputInfo &Input, 660 ArgStringList &CmdArgs) { 661 // When using -verify-pch, we don't want to provide the type 662 // 'precompiled-header' if it was inferred from the file extension 663 if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH) 664 return; 665 666 CmdArgs.push_back("-x"); 667 if (Args.hasArg(options::OPT_rewrite_objc)) 668 CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX)); 669 else { 670 // Map the driver type to the frontend type. This is mostly an identity 671 // mapping, except that the distinction between module interface units 672 // and other source files does not exist at the frontend layer. 673 const char *ClangType; 674 switch (Input.getType()) { 675 case types::TY_CXXModule: 676 ClangType = "c++"; 677 break; 678 case types::TY_PP_CXXModule: 679 ClangType = "c++-cpp-output"; 680 break; 681 default: 682 ClangType = types::getTypeName(Input.getType()); 683 break; 684 } 685 CmdArgs.push_back(ClangType); 686 } 687} 688 689static void appendUserToPath(SmallVectorImpl<char> &Result) { 690#ifdef LLVM_ON_UNIX 691 const char *Username = getenv("LOGNAME"); 692#else 693 const char *Username = getenv("USERNAME"); 694#endif 695 if (Username) { 696 // Validate that LoginName can be used in a path, and get its length. 697 size_t Len = 0; 698 for (const char *P = Username; *P; ++P, ++Len) { 699 if (!clang::isAlphanumeric(*P) && *P != '_') { 700 Username = nullptr; 701 break; 702 } 703 } 704 705 if (Username && Len > 0) { 706 Result.append(Username, Username + Len); 707 return; 708 } 709 } 710 711// Fallback to user id. 712#ifdef LLVM_ON_UNIX 713 std::string UID = llvm::utostr(getuid()); 714#else 715 // FIXME: Windows seems to have an 'SID' that might work. 716 std::string UID = "9999"; 717#endif 718 Result.append(UID.begin(), UID.end()); 719} 720 721static void addPGOAndCoverageFlags(Compilation &C, const Driver &D, 722 const InputInfo &Output, const ArgList &Args, 723 ArgStringList &CmdArgs) { 724 725 auto *PGOGenerateArg = Args.getLastArg(options::OPT_fprofile_generate, 726 options::OPT_fprofile_generate_EQ, 727 options::OPT_fno_profile_generate); 728 if (PGOGenerateArg && 729 PGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate)) 730 PGOGenerateArg = nullptr; 731 732 auto *ProfileGenerateArg = Args.getLastArg( 733 options::OPT_fprofile_instr_generate, 734 options::OPT_fprofile_instr_generate_EQ, 735 options::OPT_fno_profile_instr_generate); 736 if (ProfileGenerateArg && 737 ProfileGenerateArg->getOption().matches( 738 options::OPT_fno_profile_instr_generate)) 739 ProfileGenerateArg = nullptr; 740 741 if (PGOGenerateArg && ProfileGenerateArg) 742 D.Diag(diag::err_drv_argument_not_allowed_with) 743 << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling(); 744 745 auto *ProfileUseArg = getLastProfileUseArg(Args); 746 747 if (PGOGenerateArg && ProfileUseArg) 748 D.Diag(diag::err_drv_argument_not_allowed_with) 749 << ProfileUseArg->getSpelling() << PGOGenerateArg->getSpelling(); 750 751 if (ProfileGenerateArg && ProfileUseArg) 752 D.Diag(diag::err_drv_argument_not_allowed_with) 753 << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling(); 754 755 if (ProfileGenerateArg) { 756 if (ProfileGenerateArg->getOption().matches( 757 options::OPT_fprofile_instr_generate_EQ)) 758 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-instrument-path=") + 759 ProfileGenerateArg->getValue())); 760 // The default is to use Clang Instrumentation. 761 CmdArgs.push_back("-fprofile-instrument=clang"); 762 } 763 764 if (PGOGenerateArg) { 765 CmdArgs.push_back("-fprofile-instrument=llvm"); 766 if (PGOGenerateArg->getOption().matches( 767 options::OPT_fprofile_generate_EQ)) { 768 SmallString<128> Path(PGOGenerateArg->getValue()); 769 llvm::sys::path::append(Path, "default_%m.profraw"); 770 CmdArgs.push_back( 771 Args.MakeArgString(Twine("-fprofile-instrument-path=") + Path)); 772 } 773 } 774 775 if (ProfileUseArg) { 776 if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ)) 777 CmdArgs.push_back(Args.MakeArgString( 778 Twine("-fprofile-instrument-use-path=") + ProfileUseArg->getValue())); 779 else if ((ProfileUseArg->getOption().matches( 780 options::OPT_fprofile_use_EQ) || 781 ProfileUseArg->getOption().matches( 782 options::OPT_fprofile_instr_use))) { 783 SmallString<128> Path( 784 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue()); 785 if (Path.empty() || llvm::sys::fs::is_directory(Path)) 786 llvm::sys::path::append(Path, "default.profdata"); 787 CmdArgs.push_back( 788 Args.MakeArgString(Twine("-fprofile-instrument-use-path=") + Path)); 789 } 790 } 791 792 if (Args.hasArg(options::OPT_ftest_coverage) || 793 Args.hasArg(options::OPT_coverage)) 794 CmdArgs.push_back("-femit-coverage-notes"); 795 if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs, 796 false) || 797 Args.hasArg(options::OPT_coverage)) 798 CmdArgs.push_back("-femit-coverage-data"); 799 800 if (Args.hasFlag(options::OPT_fcoverage_mapping, 801 options::OPT_fno_coverage_mapping, false)) { 802 if (!ProfileGenerateArg) 803 D.Diag(clang::diag::err_drv_argument_only_allowed_with) 804 << "-fcoverage-mapping" 805 << "-fprofile-instr-generate"; 806 807 CmdArgs.push_back("-fcoverage-mapping"); 808 } 809 810 if (Args.hasArg(options::OPT_fprofile_exclude_files_EQ)) { 811 auto *Arg = Args.getLastArg(options::OPT_fprofile_exclude_files_EQ); 812 if (!Args.hasArg(options::OPT_coverage)) 813 D.Diag(clang::diag::err_drv_argument_only_allowed_with) 814 << "-fprofile-exclude-files=" 815 << "--coverage"; 816 817 StringRef v = Arg->getValue(); 818 CmdArgs.push_back( 819 Args.MakeArgString(Twine("-fprofile-exclude-files=" + v))); 820 } 821 822 if (Args.hasArg(options::OPT_fprofile_filter_files_EQ)) { 823 auto *Arg = Args.getLastArg(options::OPT_fprofile_filter_files_EQ); 824 if (!Args.hasArg(options::OPT_coverage)) 825 D.Diag(clang::diag::err_drv_argument_only_allowed_with) 826 << "-fprofile-filter-files=" 827 << "--coverage"; 828 829 StringRef v = Arg->getValue(); 830 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-filter-files=" + v))); 831 } 832 833 if (C.getArgs().hasArg(options::OPT_c) || 834 C.getArgs().hasArg(options::OPT_S)) { 835 if (Output.isFilename()) { 836 CmdArgs.push_back("-coverage-notes-file"); 837 SmallString<128> OutputFilename; 838 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) 839 OutputFilename = FinalOutput->getValue(); 840 else 841 OutputFilename = llvm::sys::path::filename(Output.getBaseInput()); 842 SmallString<128> CoverageFilename = OutputFilename; 843 if (llvm::sys::path::is_relative(CoverageFilename)) { 844 SmallString<128> Pwd; 845 if (!llvm::sys::fs::current_path(Pwd)) { 846 llvm::sys::path::append(Pwd, CoverageFilename); 847 CoverageFilename.swap(Pwd); 848 } 849 } 850 llvm::sys::path::replace_extension(CoverageFilename, "gcno"); 851 CmdArgs.push_back(Args.MakeArgString(CoverageFilename)); 852 853 // Leave -fprofile-dir= an unused argument unless .gcda emission is 854 // enabled. To be polite, with '-fprofile-arcs -fno-profile-arcs' consider 855 // the flag used. There is no -fno-profile-dir, so the user has no 856 // targeted way to suppress the warning. 857 if (Args.hasArg(options::OPT_fprofile_arcs) || 858 Args.hasArg(options::OPT_coverage)) { 859 CmdArgs.push_back("-coverage-data-file"); 860 if (Arg *FProfileDir = Args.getLastArg(options::OPT_fprofile_dir)) { 861 CoverageFilename = FProfileDir->getValue(); 862 llvm::sys::path::append(CoverageFilename, OutputFilename); 863 } 864 llvm::sys::path::replace_extension(CoverageFilename, "gcda"); 865 CmdArgs.push_back(Args.MakeArgString(CoverageFilename)); 866 } 867 } 868 } 869} 870 871/// Check whether the given input tree contains any compilation actions. 872static bool ContainsCompileAction(const Action *A) { 873 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A)) 874 return true; 875 876 for (const auto &AI : A->inputs()) 877 if (ContainsCompileAction(AI)) 878 return true; 879 880 return false; 881} 882 883/// Check if -relax-all should be passed to the internal assembler. 884/// This is done by default when compiling non-assembler source with -O0. 885static bool UseRelaxAll(Compilation &C, const ArgList &Args) { 886 bool RelaxDefault = true; 887 888 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) 889 RelaxDefault = A->getOption().matches(options::OPT_O0); 890 891 if (RelaxDefault) { 892 RelaxDefault = false; 893 for (const auto &Act : C.getActions()) { 894 if (ContainsCompileAction(Act)) { 895 RelaxDefault = true; 896 break; 897 } 898 } 899 } 900 901 return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all, 902 RelaxDefault); 903} 904 905// Extract the integer N from a string spelled "-dwarf-N", returning 0 906// on mismatch. The StringRef input (rather than an Arg) allows 907// for use by the "-Xassembler" option parser. 908static unsigned DwarfVersionNum(StringRef ArgValue) { 909 return llvm::StringSwitch<unsigned>(ArgValue) 910 .Case("-gdwarf-2", 2) 911 .Case("-gdwarf-3", 3) 912 .Case("-gdwarf-4", 4) 913 .Case("-gdwarf-5", 5) 914 .Default(0); 915} 916 917static void RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs, 918 codegenoptions::DebugInfoKind DebugInfoKind, 919 unsigned DwarfVersion, 920 llvm::DebuggerKind DebuggerTuning) { 921 switch (DebugInfoKind) { 922 case codegenoptions::DebugDirectivesOnly: 923 CmdArgs.push_back("-debug-info-kind=line-directives-only"); 924 break; 925 case codegenoptions::DebugLineTablesOnly: 926 CmdArgs.push_back("-debug-info-kind=line-tables-only"); 927 break; 928 case codegenoptions::LimitedDebugInfo: 929 CmdArgs.push_back("-debug-info-kind=limited"); 930 break; 931 case codegenoptions::FullDebugInfo: 932 CmdArgs.push_back("-debug-info-kind=standalone"); 933 break; 934 default: 935 break; 936 } 937 if (DwarfVersion > 0) 938 CmdArgs.push_back( 939 Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion))); 940 switch (DebuggerTuning) { 941 case llvm::DebuggerKind::GDB: 942 CmdArgs.push_back("-debugger-tuning=gdb"); 943 break; 944 case llvm::DebuggerKind::LLDB: 945 CmdArgs.push_back("-debugger-tuning=lldb"); 946 break; 947 case llvm::DebuggerKind::SCE: 948 CmdArgs.push_back("-debugger-tuning=sce"); 949 break; 950 default: 951 break; 952 } 953} 954 955static bool checkDebugInfoOption(const Arg *A, const ArgList &Args, 956 const Driver &D, const ToolChain &TC) { 957 assert(A && "Expected non-nullptr argument."); 958 if (TC.supportsDebugInfoOption(A)) 959 return true; 960 D.Diag(diag::warn_drv_unsupported_debug_info_opt_for_target) 961 << A->getAsString(Args) << TC.getTripleString(); 962 return false; 963} 964 965static void RenderDebugInfoCompressionArgs(const ArgList &Args, 966 ArgStringList &CmdArgs, 967 const Driver &D, 968 const ToolChain &TC) { 969 const Arg *A = Args.getLastArg(options::OPT_gz, options::OPT_gz_EQ); 970 if (!A) 971 return; 972 if (checkDebugInfoOption(A, Args, D, TC)) { 973 if (A->getOption().getID() == options::OPT_gz) { 974 if (llvm::zlib::isAvailable()) 975 CmdArgs.push_back("-compress-debug-sections"); 976 else 977 D.Diag(diag::warn_debug_compression_unavailable); 978 return; 979 } 980 981 StringRef Value = A->getValue(); 982 if (Value == "none") { 983 CmdArgs.push_back("-compress-debug-sections=none"); 984 } else if (Value == "zlib" || Value == "zlib-gnu") { 985 if (llvm::zlib::isAvailable()) { 986 CmdArgs.push_back( 987 Args.MakeArgString("-compress-debug-sections=" + Twine(Value))); 988 } else { 989 D.Diag(diag::warn_debug_compression_unavailable); 990 } 991 } else { 992 D.Diag(diag::err_drv_unsupported_option_argument) 993 << A->getOption().getName() << Value; 994 } 995 } 996} 997 998static const char *RelocationModelName(llvm::Reloc::Model Model) { 999 switch (Model) { 1000 case llvm::Reloc::Static: 1001 return "static"; 1002 case llvm::Reloc::PIC_: 1003 return "pic"; 1004 case llvm::Reloc::DynamicNoPIC: 1005 return "dynamic-no-pic"; 1006 case llvm::Reloc::ROPI: 1007 return "ropi"; 1008 case llvm::Reloc::RWPI: 1009 return "rwpi"; 1010 case llvm::Reloc::ROPI_RWPI: 1011 return "ropi-rwpi"; 1012 } 1013 llvm_unreachable("Unknown Reloc::Model kind"); 1014} 1015 1016void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA, 1017 const Driver &D, const ArgList &Args, 1018 ArgStringList &CmdArgs, 1019 const InputInfo &Output, 1020 const InputInfoList &Inputs) const { 1021 Arg *A; 1022 const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU(); 1023 1024 CheckPreprocessingOptions(D, Args); 1025 1026 Args.AddLastArg(CmdArgs, options::OPT_C); 1027 Args.AddLastArg(CmdArgs, options::OPT_CC); 1028 1029 // Handle dependency file generation. 1030 if ((A = Args.getLastArg(options::OPT_M, options::OPT_MM)) || 1031 (A = Args.getLastArg(options::OPT_MD)) || 1032 (A = Args.getLastArg(options::OPT_MMD))) { 1033 // Determine the output location. 1034 const char *DepFile; 1035 if (Arg *MF = Args.getLastArg(options::OPT_MF)) { 1036 DepFile = MF->getValue(); 1037 C.addFailureResultFile(DepFile, &JA); 1038 } else if (Output.getType() == types::TY_Dependencies) { 1039 DepFile = Output.getFilename(); 1040 } else if (A->getOption().matches(options::OPT_M) || 1041 A->getOption().matches(options::OPT_MM)) { 1042 DepFile = "-"; 1043 } else { 1044 DepFile = getDependencyFileName(Args, Inputs); 1045 C.addFailureResultFile(DepFile, &JA); 1046 } 1047 CmdArgs.push_back("-dependency-file"); 1048 CmdArgs.push_back(DepFile); 1049 1050 // Add a default target if one wasn't specified. 1051 if (!Args.hasArg(options::OPT_MT) && !Args.hasArg(options::OPT_MQ)) { 1052 const char *DepTarget; 1053 1054 // If user provided -o, that is the dependency target, except 1055 // when we are only generating a dependency file. 1056 Arg *OutputOpt = Args.getLastArg(options::OPT_o); 1057 if (OutputOpt && Output.getType() != types::TY_Dependencies) { 1058 DepTarget = OutputOpt->getValue(); 1059 } else { 1060 // Otherwise derive from the base input. 1061 // 1062 // FIXME: This should use the computed output file location. 1063 SmallString<128> P(Inputs[0].getBaseInput()); 1064 llvm::sys::path::replace_extension(P, "o"); 1065 DepTarget = Args.MakeArgString(llvm::sys::path::filename(P)); 1066 } 1067 1068 if (!A->getOption().matches(options::OPT_MD) && !A->getOption().matches(options::OPT_MMD)) { 1069 CmdArgs.push_back("-w"); 1070 } 1071 CmdArgs.push_back("-MT"); 1072 SmallString<128> Quoted; 1073 QuoteTarget(DepTarget, Quoted); 1074 CmdArgs.push_back(Args.MakeArgString(Quoted)); 1075 } 1076 1077 if (A->getOption().matches(options::OPT_M) || 1078 A->getOption().matches(options::OPT_MD)) 1079 CmdArgs.push_back("-sys-header-deps"); 1080 if ((isa<PrecompileJobAction>(JA) && 1081 !Args.hasArg(options::OPT_fno_module_file_deps)) || 1082 Args.hasArg(options::OPT_fmodule_file_deps)) 1083 CmdArgs.push_back("-module-file-deps"); 1084 } 1085 1086 if (Args.hasArg(options::OPT_MG)) { 1087 if (!A || A->getOption().matches(options::OPT_MD) || 1088 A->getOption().matches(options::OPT_MMD)) 1089 D.Diag(diag::err_drv_mg_requires_m_or_mm); 1090 CmdArgs.push_back("-MG"); 1091 } 1092 1093 Args.AddLastArg(CmdArgs, options::OPT_MP); 1094 Args.AddLastArg(CmdArgs, options::OPT_MV); 1095 1096 // Convert all -MQ <target> args to -MT <quoted target> 1097 for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) { 1098 A->claim(); 1099 1100 if (A->getOption().matches(options::OPT_MQ)) { 1101 CmdArgs.push_back("-MT"); 1102 SmallString<128> Quoted; 1103 QuoteTarget(A->getValue(), Quoted); 1104 CmdArgs.push_back(Args.MakeArgString(Quoted)); 1105 1106 // -MT flag - no change 1107 } else { 1108 A->render(Args, CmdArgs); 1109 } 1110 } 1111 1112 // Add offload include arguments specific for CUDA. This must happen before 1113 // we -I or -include anything else, because we must pick up the CUDA headers 1114 // from the particular CUDA installation, rather than from e.g. 1115 // /usr/local/include. 1116 if (JA.isOffloading(Action::OFK_Cuda)) 1117 getToolChain().AddCudaIncludeArgs(Args, CmdArgs); 1118 1119 // Add -i* options, and automatically translate to 1120 // -include-pch/-include-pth for transparent PCH support. It's 1121 // wonky, but we include looking for .gch so we can support seamless 1122 // replacement into a build system already set up to be generating 1123 // .gch files. 1124 1125 if (getToolChain().getDriver().IsCLMode()) { 1126 const Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc); 1127 const Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu); 1128 if (YcArg && JA.getKind() >= Action::PrecompileJobClass && 1129 JA.getKind() <= Action::AssembleJobClass) { 1130 CmdArgs.push_back(Args.MakeArgString("-building-pch-with-obj")); 1131 } 1132 if (YcArg || YuArg) { 1133 StringRef ThroughHeader = YcArg ? YcArg->getValue() : YuArg->getValue(); 1134 if (!isa<PrecompileJobAction>(JA)) { 1135 CmdArgs.push_back("-include-pch"); 1136 CmdArgs.push_back(Args.MakeArgString(D.GetClPchPath( 1137 C, !ThroughHeader.empty() 1138 ? ThroughHeader 1139 : llvm::sys::path::filename(Inputs[0].getBaseInput())))); 1140 } 1141 1142 if (ThroughHeader.empty()) { 1143 CmdArgs.push_back(Args.MakeArgString( 1144 Twine("-pch-through-hdrstop-") + (YcArg ? "create" : "use"))); 1145 } else { 1146 CmdArgs.push_back( 1147 Args.MakeArgString(Twine("-pch-through-header=") + ThroughHeader)); 1148 } 1149 } 1150 } 1151 1152 bool RenderedImplicitInclude = false; 1153 for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) { 1154 if (A->getOption().matches(options::OPT_include)) { 1155 // Handling of gcc-style gch precompiled headers. 1156 bool IsFirstImplicitInclude = !RenderedImplicitInclude; 1157 RenderedImplicitInclude = true; 1158 1159 bool FoundPCH = false; 1160 SmallString<128> P(A->getValue()); 1161 // We want the files to have a name like foo.h.pch. Add a dummy extension 1162 // so that replace_extension does the right thing. 1163 P += ".dummy"; 1164 llvm::sys::path::replace_extension(P, "pch"); 1165 if (llvm::sys::fs::exists(P)) 1166 FoundPCH = true; 1167 1168 if (!FoundPCH) { 1169 llvm::sys::path::replace_extension(P, "gch"); 1170 if (llvm::sys::fs::exists(P)) { 1171 FoundPCH = true; 1172 } 1173 } 1174 1175 if (FoundPCH) { 1176 if (IsFirstImplicitInclude) { 1177 A->claim(); 1178 CmdArgs.push_back("-include-pch"); 1179 CmdArgs.push_back(Args.MakeArgString(P)); 1180 continue; 1181 } else { 1182 // Ignore the PCH if not first on command line and emit warning. 1183 D.Diag(diag::warn_drv_pch_not_first_include) << P 1184 << A->getAsString(Args); 1185 } 1186 } 1187 } else if (A->getOption().matches(options::OPT_isystem_after)) { 1188 // Handling of paths which must come late. These entries are handled by 1189 // the toolchain itself after the resource dir is inserted in the right 1190 // search order. 1191 // Do not claim the argument so that the use of the argument does not 1192 // silently go unnoticed on toolchains which do not honour the option. 1193 continue; 1194 } 1195 1196 // Not translated, render as usual. 1197 A->claim(); 1198 A->render(Args, CmdArgs); 1199 } 1200 1201 Args.AddAllArgs(CmdArgs, 1202 {options::OPT_D, options::OPT_U, options::OPT_I_Group, 1203 options::OPT_F, options::OPT_index_header_map}); 1204 1205 // Add -Wp, and -Xpreprocessor if using the preprocessor. 1206 1207 // FIXME: There is a very unfortunate problem here, some troubled 1208 // souls abuse -Wp, to pass preprocessor options in gcc syntax. To 1209 // really support that we would have to parse and then translate 1210 // those options. :( 1211 Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA, 1212 options::OPT_Xpreprocessor); 1213 1214 // -I- is a deprecated GCC feature, reject it. 1215 if (Arg *A = Args.getLastArg(options::OPT_I_)) 1216 D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args); 1217 1218 // If we have a --sysroot, and don't have an explicit -isysroot flag, add an 1219 // -isysroot to the CC1 invocation. 1220 StringRef sysroot = C.getSysRoot(); 1221 if (sysroot != "") { 1222 if (!Args.hasArg(options::OPT_isysroot)) { 1223 CmdArgs.push_back("-isysroot"); 1224 CmdArgs.push_back(C.getArgs().MakeArgString(sysroot)); 1225 } 1226 } 1227 1228 // Parse additional include paths from environment variables. 1229 // FIXME: We should probably sink the logic for handling these from the 1230 // frontend into the driver. It will allow deleting 4 otherwise unused flags. 1231 // CPATH - included following the user specified includes (but prior to 1232 // builtin and standard includes). 1233 addDirectoryList(Args, CmdArgs, "-I", "CPATH"); 1234 // C_INCLUDE_PATH - system includes enabled when compiling C. 1235 addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH"); 1236 // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++. 1237 addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH"); 1238 // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC. 1239 addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH"); 1240 // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++. 1241 addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH"); 1242 1243 // While adding the include arguments, we also attempt to retrieve the 1244 // arguments of related offloading toolchains or arguments that are specific 1245 // of an offloading programming model. 1246 1247 // Add C++ include arguments, if needed. 1248 if (types::isCXX(Inputs[0].getType())) 1249 forAllAssociatedToolChains(C, JA, getToolChain(), 1250 [&Args, &CmdArgs](const ToolChain &TC) { 1251 TC.AddClangCXXStdlibIncludeArgs(Args, CmdArgs); 1252 }); 1253 1254 // Add system include arguments for all targets but IAMCU. 1255 if (!IsIAMCU) 1256 forAllAssociatedToolChains(C, JA, getToolChain(), 1257 [&Args, &CmdArgs](const ToolChain &TC) { 1258 TC.AddClangSystemIncludeArgs(Args, CmdArgs); 1259 }); 1260 else { 1261 // For IAMCU add special include arguments. 1262 getToolChain().AddIAMCUIncludeArgs(Args, CmdArgs); 1263 } 1264} 1265 1266// FIXME: Move to target hook. 1267static bool isSignedCharDefault(const llvm::Triple &Triple) { 1268 switch (Triple.getArch()) { 1269 default: 1270 return true; 1271 1272 case llvm::Triple::aarch64: 1273 case llvm::Triple::aarch64_be: 1274 case llvm::Triple::arm: 1275 case llvm::Triple::armeb: 1276 case llvm::Triple::thumb: 1277 case llvm::Triple::thumbeb: 1278 if (Triple.isOSDarwin() || Triple.isOSWindows()) 1279 return true; 1280 return false; 1281 1282 case llvm::Triple::ppc: 1283 case llvm::Triple::ppc64: 1284 if (Triple.isOSDarwin()) 1285 return true; 1286 return false; 1287 1288 case llvm::Triple::hexagon: 1289 case llvm::Triple::ppc64le: 1290 case llvm::Triple::riscv32: 1291 case llvm::Triple::riscv64: 1292 case llvm::Triple::systemz: 1293 case llvm::Triple::xcore: 1294 return false; 1295 } 1296} 1297 1298static bool isNoCommonDefault(const llvm::Triple &Triple) { 1299 switch (Triple.getArch()) { 1300 default: 1301 if (Triple.isOSFuchsia()) 1302 return true; 1303 return false; 1304 1305 case llvm::Triple::xcore: 1306 case llvm::Triple::wasm32: 1307 case llvm::Triple::wasm64: 1308 return true; 1309 } 1310} 1311 1312namespace { 1313void RenderARMABI(const llvm::Triple &Triple, const ArgList &Args, 1314 ArgStringList &CmdArgs) { 1315 // Select the ABI to use. 1316 // FIXME: Support -meabi. 1317 // FIXME: Parts of this are duplicated in the backend, unify this somehow. 1318 const char *ABIName = nullptr; 1319 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) { 1320 ABIName = A->getValue(); 1321 } else { 1322 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false); 1323 ABIName = llvm::ARM::computeDefaultTargetABI(Triple, CPU).data(); 1324 } 1325 1326 CmdArgs.push_back("-target-abi"); 1327 CmdArgs.push_back(ABIName); 1328} 1329} 1330 1331void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args, 1332 ArgStringList &CmdArgs, bool KernelOrKext) const { 1333 RenderARMABI(Triple, Args, CmdArgs); 1334 1335 // Determine floating point ABI from the options & target defaults. 1336 arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args); 1337 if (ABI == arm::FloatABI::Soft) { 1338 // Floating point operations and argument passing are soft. 1339 // FIXME: This changes CPP defines, we need -target-soft-float. 1340 CmdArgs.push_back("-msoft-float"); 1341 CmdArgs.push_back("-mfloat-abi"); 1342 CmdArgs.push_back("soft"); 1343 } else if (ABI == arm::FloatABI::SoftFP) { 1344 // Floating point operations are hard, but argument passing is soft. 1345 CmdArgs.push_back("-mfloat-abi"); 1346 CmdArgs.push_back("soft"); 1347 } else { 1348 // Floating point operations and argument passing are hard. 1349 assert(ABI == arm::FloatABI::Hard && "Invalid float abi!"); 1350 CmdArgs.push_back("-mfloat-abi"); 1351 CmdArgs.push_back("hard"); 1352 } 1353 1354 // Forward the -mglobal-merge option for explicit control over the pass. 1355 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge, 1356 options::OPT_mno_global_merge)) { 1357 CmdArgs.push_back("-mllvm"); 1358 if (A->getOption().matches(options::OPT_mno_global_merge)) 1359 CmdArgs.push_back("-arm-global-merge=false"); 1360 else 1361 CmdArgs.push_back("-arm-global-merge=true"); 1362 } 1363 1364 if (!Args.hasFlag(options::OPT_mimplicit_float, 1365 options::OPT_mno_implicit_float, true)) 1366 CmdArgs.push_back("-no-implicit-float"); 1367} 1368 1369void Clang::RenderTargetOptions(const llvm::Triple &EffectiveTriple, 1370 const ArgList &Args, bool KernelOrKext, 1371 ArgStringList &CmdArgs) const { 1372 const ToolChain &TC = getToolChain(); 1373 1374 // Add the target features 1375 getTargetFeatures(TC, EffectiveTriple, Args, CmdArgs, false); 1376 1377 // Add target specific flags. 1378 switch (TC.getArch()) { 1379 default: 1380 break; 1381 1382 case llvm::Triple::arm: 1383 case llvm::Triple::armeb: 1384 case llvm::Triple::thumb: 1385 case llvm::Triple::thumbeb: 1386 // Use the effective triple, which takes into account the deployment target. 1387 AddARMTargetArgs(EffectiveTriple, Args, CmdArgs, KernelOrKext); 1388 CmdArgs.push_back("-fallow-half-arguments-and-returns"); 1389 break; 1390 1391 case llvm::Triple::aarch64: 1392 case llvm::Triple::aarch64_be: 1393 AddAArch64TargetArgs(Args, CmdArgs); 1394 CmdArgs.push_back("-fallow-half-arguments-and-returns"); 1395 break; 1396 1397 case llvm::Triple::mips: 1398 case llvm::Triple::mipsel: 1399 case llvm::Triple::mips64: 1400 case llvm::Triple::mips64el: 1401 AddMIPSTargetArgs(Args, CmdArgs); 1402 break; 1403 1404 case llvm::Triple::ppc: 1405 case llvm::Triple::ppc64: 1406 case llvm::Triple::ppc64le: 1407 AddPPCTargetArgs(Args, CmdArgs); 1408 break; 1409 1410 case llvm::Triple::riscv32: 1411 case llvm::Triple::riscv64: 1412 AddRISCVTargetArgs(Args, CmdArgs); 1413 break; 1414 1415 case llvm::Triple::sparc: 1416 case llvm::Triple::sparcel: 1417 case llvm::Triple::sparcv9: 1418 AddSparcTargetArgs(Args, CmdArgs); 1419 break; 1420 1421 case llvm::Triple::systemz: 1422 AddSystemZTargetArgs(Args, CmdArgs); 1423 break; 1424 1425 case llvm::Triple::x86: 1426 case llvm::Triple::x86_64: 1427 AddX86TargetArgs(Args, CmdArgs); 1428 break; 1429 1430 case llvm::Triple::lanai: 1431 AddLanaiTargetArgs(Args, CmdArgs); 1432 break; 1433 1434 case llvm::Triple::hexagon: 1435 AddHexagonTargetArgs(Args, CmdArgs); 1436 break; 1437 1438 case llvm::Triple::wasm32: 1439 case llvm::Triple::wasm64: 1440 AddWebAssemblyTargetArgs(Args, CmdArgs); 1441 break; 1442 } 1443} 1444 1445// Parse -mbranch-protection=<protection>[+<protection>]* where 1446// <protection> ::= standard | none | [bti,pac-ret[+b-key,+leaf]*] 1447// Returns a triple of (return address signing Scope, signing key, require 1448// landing pads) 1449static std::tuple<StringRef, StringRef, bool> 1450ParseAArch64BranchProtection(const Driver &D, const ArgList &Args, 1451 const Arg *A) { 1452 StringRef Scope = "none"; 1453 StringRef Key = "a_key"; 1454 bool IndirectBranches = false; 1455 1456 StringRef Value = A->getValue(); 1457 // This maps onto -mbranch-protection=<scope>+<key> 1458 1459 if (Value.equals("standard")) { 1460 Scope = "non-leaf"; 1461 Key = "a_key"; 1462 IndirectBranches = true; 1463 1464 } else if (!Value.equals("none")) { 1465 SmallVector<StringRef, 4> BranchProtection; 1466 StringRef(A->getValue()).split(BranchProtection, '+'); 1467 1468 auto Protection = BranchProtection.begin(); 1469 while (Protection != BranchProtection.end()) { 1470 if (Protection->equals("bti")) 1471 IndirectBranches = true; 1472 else if (Protection->equals("pac-ret")) { 1473 Scope = "non-leaf"; 1474 while (++Protection != BranchProtection.end()) { 1475 // Inner loop as "leaf" and "b-key" options must only appear attached 1476 // to pac-ret. 1477 if (Protection->equals("leaf")) 1478 Scope = "all"; 1479 else if (Protection->equals("b-key")) 1480 Key = "b_key"; 1481 else 1482 break; 1483 } 1484 Protection--; 1485 } else 1486 D.Diag(diag::err_invalid_branch_protection) 1487 << *Protection << A->getAsString(Args); 1488 Protection++; 1489 } 1490 } 1491 1492 return std::make_tuple(Scope, Key, IndirectBranches); 1493} 1494 1495namespace { 1496void RenderAArch64ABI(const llvm::Triple &Triple, const ArgList &Args, 1497 ArgStringList &CmdArgs) { 1498 const char *ABIName = nullptr; 1499 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) 1500 ABIName = A->getValue(); 1501 else if (Triple.isOSDarwin()) 1502 ABIName = "darwinpcs"; 1503 else 1504 ABIName = "aapcs"; 1505 1506 CmdArgs.push_back("-target-abi"); 1507 CmdArgs.push_back(ABIName); 1508} 1509} 1510 1511void Clang::AddAArch64TargetArgs(const ArgList &Args, 1512 ArgStringList &CmdArgs) const { 1513 const llvm::Triple &Triple = getToolChain().getEffectiveTriple(); 1514 1515 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) || 1516 Args.hasArg(options::OPT_mkernel) || 1517 Args.hasArg(options::OPT_fapple_kext)) 1518 CmdArgs.push_back("-disable-red-zone"); 1519 1520 if (!Args.hasFlag(options::OPT_mimplicit_float, 1521 options::OPT_mno_implicit_float, true)) 1522 CmdArgs.push_back("-no-implicit-float"); 1523 1524 RenderAArch64ABI(Triple, Args, CmdArgs); 1525 1526 if (Arg *A = Args.getLastArg(options::OPT_mfix_cortex_a53_835769, 1527 options::OPT_mno_fix_cortex_a53_835769)) { 1528 CmdArgs.push_back("-mllvm"); 1529 if (A->getOption().matches(options::OPT_mfix_cortex_a53_835769)) 1530 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1"); 1531 else 1532 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=0"); 1533 } else if (Triple.isAndroid()) { 1534 // Enabled A53 errata (835769) workaround by default on android 1535 CmdArgs.push_back("-mllvm"); 1536 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1"); 1537 } 1538 1539 // Forward the -mglobal-merge option for explicit control over the pass. 1540 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge, 1541 options::OPT_mno_global_merge)) { 1542 CmdArgs.push_back("-mllvm"); 1543 if (A->getOption().matches(options::OPT_mno_global_merge)) 1544 CmdArgs.push_back("-aarch64-enable-global-merge=false"); 1545 else 1546 CmdArgs.push_back("-aarch64-enable-global-merge=true"); 1547 } 1548 1549 // Enable/disable return address signing and indirect branch targets. 1550 if (Arg *A = Args.getLastArg(options::OPT_msign_return_address_EQ, 1551 options::OPT_mbranch_protection_EQ)) { 1552 1553 const Driver &D = getToolChain().getDriver(); 1554 1555 StringRef Scope, Key; 1556 bool IndirectBranches; 1557 1558 if (A->getOption().matches(options::OPT_msign_return_address_EQ)) { 1559 Scope = A->getValue(); 1560 if (!Scope.equals("none") && !Scope.equals("non-leaf") && 1561 !Scope.equals("all")) 1562 D.Diag(diag::err_invalid_branch_protection) 1563 << Scope << A->getAsString(Args); 1564 Key = "a_key"; 1565 IndirectBranches = false; 1566 } else 1567 std::tie(Scope, Key, IndirectBranches) = 1568 ParseAArch64BranchProtection(D, Args, A); 1569 1570 CmdArgs.push_back( 1571 Args.MakeArgString(Twine("-msign-return-address=") + Scope)); 1572 CmdArgs.push_back( 1573 Args.MakeArgString(Twine("-msign-return-address-key=") + Key)); 1574 if (IndirectBranches) 1575 CmdArgs.push_back("-mbranch-target-enforce"); 1576 } 1577} 1578 1579void Clang::AddMIPSTargetArgs(const ArgList &Args, 1580 ArgStringList &CmdArgs) const { 1581 const Driver &D = getToolChain().getDriver(); 1582 StringRef CPUName; 1583 StringRef ABIName; 1584 const llvm::Triple &Triple = getToolChain().getTriple(); 1585 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName); 1586 1587 CmdArgs.push_back("-target-abi"); 1588 CmdArgs.push_back(ABIName.data()); 1589 1590 mips::FloatABI ABI = mips::getMipsFloatABI(D, Args); 1591 if (ABI == mips::FloatABI::Soft) { 1592 // Floating point operations and argument passing are soft. 1593 CmdArgs.push_back("-msoft-float"); 1594 CmdArgs.push_back("-mfloat-abi"); 1595 CmdArgs.push_back("soft"); 1596 } else { 1597 // Floating point operations and argument passing are hard. 1598 assert(ABI == mips::FloatABI::Hard && "Invalid float abi!"); 1599 CmdArgs.push_back("-mfloat-abi"); 1600 CmdArgs.push_back("hard"); 1601 } 1602 1603 if (Arg *A = Args.getLastArg(options::OPT_mxgot, options::OPT_mno_xgot)) { 1604 if (A->getOption().matches(options::OPT_mxgot)) { 1605 CmdArgs.push_back("-mllvm"); 1606 CmdArgs.push_back("-mxgot"); 1607 } 1608 } 1609 1610 if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1, 1611 options::OPT_mno_ldc1_sdc1)) { 1612 if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) { 1613 CmdArgs.push_back("-mllvm"); 1614 CmdArgs.push_back("-mno-ldc1-sdc1"); 1615 } 1616 } 1617 1618 if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division, 1619 options::OPT_mno_check_zero_division)) { 1620 if (A->getOption().matches(options::OPT_mno_check_zero_division)) { 1621 CmdArgs.push_back("-mllvm"); 1622 CmdArgs.push_back("-mno-check-zero-division"); 1623 } 1624 } 1625 1626 if (Arg *A = Args.getLastArg(options::OPT_G)) { 1627 StringRef v = A->getValue(); 1628 CmdArgs.push_back("-mllvm"); 1629 CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v)); 1630 A->claim(); 1631 } 1632 1633 Arg *GPOpt = Args.getLastArg(options::OPT_mgpopt, options::OPT_mno_gpopt); 1634 Arg *ABICalls = 1635 Args.getLastArg(options::OPT_mabicalls, options::OPT_mno_abicalls); 1636 1637 // -mabicalls is the default for many MIPS environments, even with -fno-pic. 1638 // -mgpopt is the default for static, -fno-pic environments but these two 1639 // options conflict. We want to be certain that -mno-abicalls -mgpopt is 1640 // the only case where -mllvm -mgpopt is passed. 1641 // NOTE: We need a warning here or in the backend to warn when -mgpopt is 1642 // passed explicitly when compiling something with -mabicalls 1643 // (implictly) in affect. Currently the warning is in the backend. 1644 // 1645 // When the ABI in use is N64, we also need to determine the PIC mode that 1646 // is in use, as -fno-pic for N64 implies -mno-abicalls. 1647 bool NoABICalls = 1648 ABICalls && ABICalls->getOption().matches(options::OPT_mno_abicalls); 1649 1650 llvm::Reloc::Model RelocationModel; 1651 unsigned PICLevel; 1652 bool IsPIE; 1653 std::tie(RelocationModel, PICLevel, IsPIE) = 1654 ParsePICArgs(getToolChain(), Args); 1655 1656 NoABICalls = NoABICalls || 1657 (RelocationModel == llvm::Reloc::Static && ABIName == "n64"); 1658 1659 bool WantGPOpt = GPOpt && GPOpt->getOption().matches(options::OPT_mgpopt); 1660 // We quietly ignore -mno-gpopt as the backend defaults to -mno-gpopt. 1661 if (NoABICalls && (!GPOpt || WantGPOpt)) { 1662 CmdArgs.push_back("-mllvm"); 1663 CmdArgs.push_back("-mgpopt"); 1664 1665 Arg *LocalSData = Args.getLastArg(options::OPT_mlocal_sdata, 1666 options::OPT_mno_local_sdata); 1667 Arg *ExternSData = Args.getLastArg(options::OPT_mextern_sdata, 1668 options::OPT_mno_extern_sdata); 1669 Arg *EmbeddedData = Args.getLastArg(options::OPT_membedded_data, 1670 options::OPT_mno_embedded_data); 1671 if (LocalSData) { 1672 CmdArgs.push_back("-mllvm"); 1673 if (LocalSData->getOption().matches(options::OPT_mlocal_sdata)) { 1674 CmdArgs.push_back("-mlocal-sdata=1"); 1675 } else { 1676 CmdArgs.push_back("-mlocal-sdata=0"); 1677 } 1678 LocalSData->claim(); 1679 } 1680 1681 if (ExternSData) { 1682 CmdArgs.push_back("-mllvm"); 1683 if (ExternSData->getOption().matches(options::OPT_mextern_sdata)) { 1684 CmdArgs.push_back("-mextern-sdata=1"); 1685 } else { 1686 CmdArgs.push_back("-mextern-sdata=0"); 1687 } 1688 ExternSData->claim(); 1689 } 1690 1691 if (EmbeddedData) { 1692 CmdArgs.push_back("-mllvm"); 1693 if (EmbeddedData->getOption().matches(options::OPT_membedded_data)) { 1694 CmdArgs.push_back("-membedded-data=1"); 1695 } else { 1696 CmdArgs.push_back("-membedded-data=0"); 1697 } 1698 EmbeddedData->claim(); 1699 } 1700 1701 } else if ((!ABICalls || (!NoABICalls && ABICalls)) && WantGPOpt) 1702 D.Diag(diag::warn_drv_unsupported_gpopt) << (ABICalls ? 0 : 1); 1703 1704 if (GPOpt) 1705 GPOpt->claim(); 1706 1707 if (Arg *A = Args.getLastArg(options::OPT_mcompact_branches_EQ)) { 1708 StringRef Val = StringRef(A->getValue()); 1709 if (mips::hasCompactBranches(CPUName)) { 1710 if (Val == "never" || Val == "always" || Val == "optimal") { 1711 CmdArgs.push_back("-mllvm"); 1712 CmdArgs.push_back(Args.MakeArgString("-mips-compact-branches=" + Val)); 1713 } else 1714 D.Diag(diag::err_drv_unsupported_option_argument) 1715 << A->getOption().getName() << Val; 1716 } else 1717 D.Diag(diag::warn_target_unsupported_compact_branches) << CPUName; 1718 } 1719 1720 if (Arg *A = Args.getLastArg(options::OPT_mrelax_pic_calls, 1721 options::OPT_mno_relax_pic_calls)) { 1722 if (A->getOption().matches(options::OPT_mno_relax_pic_calls)) { 1723 CmdArgs.push_back("-mllvm"); 1724 CmdArgs.push_back("-mips-jalr-reloc=0"); 1725 } 1726 } 1727} 1728 1729void Clang::AddPPCTargetArgs(const ArgList &Args, 1730 ArgStringList &CmdArgs) const { 1731 // Select the ABI to use. 1732 const char *ABIName = nullptr; 1733 if (getToolChain().getTriple().isOSLinux()) 1734 switch (getToolChain().getArch()) { 1735 case llvm::Triple::ppc64: { 1736 // When targeting a processor that supports QPX, or if QPX is 1737 // specifically enabled, default to using the ABI that supports QPX (so 1738 // long as it is not specifically disabled). 1739 bool HasQPX = false; 1740 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) 1741 HasQPX = A->getValue() == StringRef("a2q"); 1742 HasQPX = Args.hasFlag(options::OPT_mqpx, options::OPT_mno_qpx, HasQPX); 1743 if (HasQPX) { 1744 ABIName = "elfv1-qpx"; 1745 break; 1746 } 1747 1748 ABIName = "elfv1"; 1749 break; 1750 } 1751 case llvm::Triple::ppc64le: 1752 ABIName = "elfv2"; 1753 break; 1754 default: 1755 break; 1756 } 1757 1758 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) 1759 // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore 1760 // the option if given as we don't have backend support for any targets 1761 // that don't use the altivec abi. 1762 if (StringRef(A->getValue()) != "altivec") 1763 ABIName = A->getValue(); 1764 1765 ppc::FloatABI FloatABI = 1766 ppc::getPPCFloatABI(getToolChain().getDriver(), Args); 1767 1768 if (FloatABI == ppc::FloatABI::Soft) { 1769 // Floating point operations and argument passing are soft. 1770 CmdArgs.push_back("-msoft-float"); 1771 CmdArgs.push_back("-mfloat-abi"); 1772 CmdArgs.push_back("soft"); 1773 } else { 1774 // Floating point operations and argument passing are hard. 1775 assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!"); 1776 CmdArgs.push_back("-mfloat-abi"); 1777 CmdArgs.push_back("hard"); 1778 } 1779 1780 if (ABIName) { 1781 CmdArgs.push_back("-target-abi"); 1782 CmdArgs.push_back(ABIName); 1783 } 1784} 1785 1786void Clang::AddRISCVTargetArgs(const ArgList &Args, 1787 ArgStringList &CmdArgs) const { 1788 // FIXME: currently defaults to the soft-float ABIs. Will need to be 1789 // expanded to select ilp32f, ilp32d, lp64f, lp64d when appropriate. 1790 const char *ABIName = nullptr; 1791 const llvm::Triple &Triple = getToolChain().getTriple(); 1792 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) 1793 ABIName = A->getValue(); 1794 else if (Triple.getArch() == llvm::Triple::riscv32) 1795 ABIName = "ilp32"; 1796 else if (Triple.getArch() == llvm::Triple::riscv64) 1797 ABIName = "lp64"; 1798 else 1799 llvm_unreachable("Unexpected triple!"); 1800 1801 CmdArgs.push_back("-target-abi"); 1802 CmdArgs.push_back(ABIName); 1803} 1804 1805void Clang::AddSparcTargetArgs(const ArgList &Args, 1806 ArgStringList &CmdArgs) const { 1807 sparc::FloatABI FloatABI = 1808 sparc::getSparcFloatABI(getToolChain().getDriver(), Args); 1809 1810 if (FloatABI == sparc::FloatABI::Soft) { 1811 // Floating point operations and argument passing are soft. 1812 CmdArgs.push_back("-msoft-float"); 1813 CmdArgs.push_back("-mfloat-abi"); 1814 CmdArgs.push_back("soft"); 1815 } else { 1816 // Floating point operations and argument passing are hard. 1817 assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!"); 1818 CmdArgs.push_back("-mfloat-abi"); 1819 CmdArgs.push_back("hard"); 1820 } 1821} 1822 1823void Clang::AddSystemZTargetArgs(const ArgList &Args, 1824 ArgStringList &CmdArgs) const { 1825 if (Args.hasFlag(options::OPT_mbackchain, options::OPT_mno_backchain, false)) 1826 CmdArgs.push_back("-mbackchain"); 1827} 1828 1829void Clang::AddX86TargetArgs(const ArgList &Args, 1830 ArgStringList &CmdArgs) const { 1831 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) || 1832 Args.hasArg(options::OPT_mkernel) || 1833 Args.hasArg(options::OPT_fapple_kext)) 1834 CmdArgs.push_back("-disable-red-zone"); 1835 1836 if (!Args.hasFlag(options::OPT_mtls_direct_seg_refs, 1837 options::OPT_mno_tls_direct_seg_refs, true)) 1838 CmdArgs.push_back("-mno-tls-direct-seg-refs"); 1839 1840 // Default to avoid implicit floating-point for kernel/kext code, but allow 1841 // that to be overridden with -mno-soft-float. 1842 bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) || 1843 Args.hasArg(options::OPT_fapple_kext)); 1844 if (Arg *A = Args.getLastArg( 1845 options::OPT_msoft_float, options::OPT_mno_soft_float, 1846 options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) { 1847 const Option &O = A->getOption(); 1848 NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) || 1849 O.matches(options::OPT_msoft_float)); 1850 } 1851 if (NoImplicitFloat) 1852 CmdArgs.push_back("-no-implicit-float"); 1853 1854 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) { 1855 StringRef Value = A->getValue(); 1856 if (Value == "intel" || Value == "att") { 1857 CmdArgs.push_back("-mllvm"); 1858 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value)); 1859 } else { 1860 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument) 1861 << A->getOption().getName() << Value; 1862 } 1863 } else if (getToolChain().getDriver().IsCLMode()) { 1864 CmdArgs.push_back("-mllvm"); 1865 CmdArgs.push_back("-x86-asm-syntax=intel"); 1866 } 1867 1868 // Set flags to support MCU ABI. 1869 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) { 1870 CmdArgs.push_back("-mfloat-abi"); 1871 CmdArgs.push_back("soft"); 1872 CmdArgs.push_back("-mstack-alignment=4"); 1873 } 1874} 1875 1876void Clang::AddHexagonTargetArgs(const ArgList &Args, 1877 ArgStringList &CmdArgs) const { 1878 CmdArgs.push_back("-mqdsp6-compat"); 1879 CmdArgs.push_back("-Wreturn-type"); 1880 1881 if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) { 1882 CmdArgs.push_back("-mllvm"); 1883 CmdArgs.push_back(Args.MakeArgString("-hexagon-small-data-threshold=" + 1884 Twine(G.getValue()))); 1885 } 1886 1887 if (!Args.hasArg(options::OPT_fno_short_enums)) 1888 CmdArgs.push_back("-fshort-enums"); 1889 if (Args.getLastArg(options::OPT_mieee_rnd_near)) { 1890 CmdArgs.push_back("-mllvm"); 1891 CmdArgs.push_back("-enable-hexagon-ieee-rnd-near"); 1892 } 1893 CmdArgs.push_back("-mllvm"); 1894 CmdArgs.push_back("-machine-sink-split=0"); 1895} 1896 1897void Clang::AddLanaiTargetArgs(const ArgList &Args, 1898 ArgStringList &CmdArgs) const { 1899 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) { 1900 StringRef CPUName = A->getValue(); 1901 1902 CmdArgs.push_back("-target-cpu"); 1903 CmdArgs.push_back(Args.MakeArgString(CPUName)); 1904 } 1905 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) { 1906 StringRef Value = A->getValue(); 1907 // Only support mregparm=4 to support old usage. Report error for all other 1908 // cases. 1909 int Mregparm; 1910 if (Value.getAsInteger(10, Mregparm)) { 1911 if (Mregparm != 4) { 1912 getToolChain().getDriver().Diag( 1913 diag::err_drv_unsupported_option_argument) 1914 << A->getOption().getName() << Value; 1915 } 1916 } 1917 } 1918} 1919 1920void Clang::AddWebAssemblyTargetArgs(const ArgList &Args, 1921 ArgStringList &CmdArgs) const { 1922 // Default to "hidden" visibility. 1923 if (!Args.hasArg(options::OPT_fvisibility_EQ, 1924 options::OPT_fvisibility_ms_compat)) { 1925 CmdArgs.push_back("-fvisibility"); 1926 CmdArgs.push_back("hidden"); 1927 } 1928} 1929 1930void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename, 1931 StringRef Target, const InputInfo &Output, 1932 const InputInfo &Input, const ArgList &Args) const { 1933 // If this is a dry run, do not create the compilation database file. 1934 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) 1935 return; 1936 1937 using llvm::yaml::escape; 1938 const Driver &D = getToolChain().getDriver(); 1939 1940 if (!CompilationDatabase) { 1941 std::error_code EC; 1942 auto File = llvm::make_unique<llvm::raw_fd_ostream>(Filename, EC, llvm::sys::fs::F_Text); 1943 if (EC) { 1944 D.Diag(clang::diag::err_drv_compilationdatabase) << Filename 1945 << EC.message(); 1946 return; 1947 } 1948 CompilationDatabase = std::move(File); 1949 } 1950 auto &CDB = *CompilationDatabase; 1951 SmallString<128> Buf; 1952 if (llvm::sys::fs::current_path(Buf)) 1953 Buf = "."; 1954 CDB << "{ \"directory\": \"" << escape(Buf) << "\""; 1955 CDB << ", \"file\": \"" << escape(Input.getFilename()) << "\""; 1956 CDB << ", \"output\": \"" << escape(Output.getFilename()) << "\""; 1957 CDB << ", \"arguments\": [\"" << escape(D.ClangExecutable) << "\""; 1958 Buf = "-x"; 1959 Buf += types::getTypeName(Input.getType()); 1960 CDB << ", \"" << escape(Buf) << "\""; 1961 if (!D.SysRoot.empty() && !Args.hasArg(options::OPT__sysroot_EQ)) { 1962 Buf = "--sysroot="; 1963 Buf += D.SysRoot; 1964 CDB << ", \"" << escape(Buf) << "\""; 1965 } 1966 CDB << ", \"" << escape(Input.getFilename()) << "\""; 1967 for (auto &A: Args) { 1968 auto &O = A->getOption(); 1969 // Skip language selection, which is positional. 1970 if (O.getID() == options::OPT_x) 1971 continue; 1972 // Skip writing dependency output and the compilation database itself. 1973 if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group) 1974 continue; 1975 // Skip inputs. 1976 if (O.getKind() == Option::InputClass) 1977 continue; 1978 // All other arguments are quoted and appended. 1979 ArgStringList ASL; 1980 A->render(Args, ASL); 1981 for (auto &it: ASL) 1982 CDB << ", \"" << escape(it) << "\""; 1983 } 1984 Buf = "--target="; 1985 Buf += Target; 1986 CDB << ", \"" << escape(Buf) << "\"]},\n"; 1987} 1988 1989static void CollectArgsForIntegratedAssembler(Compilation &C, 1990 const ArgList &Args, 1991 ArgStringList &CmdArgs, 1992 const Driver &D) { 1993 if (UseRelaxAll(C, Args)) 1994 CmdArgs.push_back("-mrelax-all"); 1995 1996 // Only default to -mincremental-linker-compatible if we think we are 1997 // targeting the MSVC linker. 1998 bool DefaultIncrementalLinkerCompatible = 1999 C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment(); 2000 if (Args.hasFlag(options::OPT_mincremental_linker_compatible, 2001 options::OPT_mno_incremental_linker_compatible, 2002 DefaultIncrementalLinkerCompatible)) 2003 CmdArgs.push_back("-mincremental-linker-compatible"); 2004 2005 switch (C.getDefaultToolChain().getArch()) { 2006 case llvm::Triple::arm: 2007 case llvm::Triple::armeb: 2008 case llvm::Triple::thumb: 2009 case llvm::Triple::thumbeb: 2010 if (Arg *A = Args.getLastArg(options::OPT_mimplicit_it_EQ)) { 2011 StringRef Value = A->getValue(); 2012 if (Value == "always" || Value == "never" || Value == "arm" || 2013 Value == "thumb") { 2014 CmdArgs.push_back("-mllvm"); 2015 CmdArgs.push_back(Args.MakeArgString("-arm-implicit-it=" + Value)); 2016 } else { 2017 D.Diag(diag::err_drv_unsupported_option_argument) 2018 << A->getOption().getName() << Value; 2019 } 2020 } 2021 break; 2022 default: 2023 break; 2024 } 2025 2026 // When passing -I arguments to the assembler we sometimes need to 2027 // unconditionally take the next argument. For example, when parsing 2028 // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the 2029 // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo' 2030 // arg after parsing the '-I' arg. 2031 bool TakeNextArg = false; 2032 2033 bool UseRelaxRelocations = C.getDefaultToolChain().useRelaxRelocations(); 2034 const char *MipsTargetFeature = nullptr; 2035 for (const Arg *A : 2036 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) { 2037 A->claim(); 2038 2039 for (StringRef Value : A->getValues()) { 2040 if (TakeNextArg) { 2041 CmdArgs.push_back(Value.data()); 2042 TakeNextArg = false; 2043 continue; 2044 } 2045 2046 if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() && 2047 Value == "-mbig-obj") 2048 continue; // LLVM handles bigobj automatically 2049 2050 switch (C.getDefaultToolChain().getArch()) { 2051 default: 2052 break; 2053 case llvm::Triple::thumb: 2054 case llvm::Triple::thumbeb: 2055 case llvm::Triple::arm: 2056 case llvm::Triple::armeb: 2057 if (Value == "-mthumb") 2058 // -mthumb has already been processed in ComputeLLVMTriple() 2059 // recognize but skip over here. 2060 continue; 2061 break; 2062 case llvm::Triple::mips: 2063 case llvm::Triple::mipsel: 2064 case llvm::Triple::mips64: 2065 case llvm::Triple::mips64el: 2066 if (Value == "--trap") { 2067 CmdArgs.push_back("-target-feature"); 2068 CmdArgs.push_back("+use-tcc-in-div"); 2069 continue; 2070 } 2071 if (Value == "--break") { 2072 CmdArgs.push_back("-target-feature"); 2073 CmdArgs.push_back("-use-tcc-in-div"); 2074 continue; 2075 } 2076 if (Value.startswith("-msoft-float")) { 2077 CmdArgs.push_back("-target-feature"); 2078 CmdArgs.push_back("+soft-float"); 2079 continue; 2080 } 2081 if (Value.startswith("-mhard-float")) { 2082 CmdArgs.push_back("-target-feature"); 2083 CmdArgs.push_back("-soft-float"); 2084 continue; 2085 } 2086 2087 MipsTargetFeature = llvm::StringSwitch<const char *>(Value) 2088 .Case("-mips1", "+mips1") 2089 .Case("-mips2", "+mips2") 2090 .Case("-mips3", "+mips3") 2091 .Case("-mips4", "+mips4") 2092 .Case("-mips5", "+mips5") 2093 .Case("-mips32", "+mips32") 2094 .Case("-mips32r2", "+mips32r2") 2095 .Case("-mips32r3", "+mips32r3") 2096 .Case("-mips32r5", "+mips32r5") 2097 .Case("-mips32r6", "+mips32r6") 2098 .Case("-mips64", "+mips64") 2099 .Case("-mips64r2", "+mips64r2") 2100 .Case("-mips64r3", "+mips64r3") 2101 .Case("-mips64r5", "+mips64r5") 2102 .Case("-mips64r6", "+mips64r6") 2103 .Default(nullptr); 2104 if (MipsTargetFeature) 2105 continue; 2106 } 2107 2108 if (Value == "-force_cpusubtype_ALL") { 2109 // Do nothing, this is the default and we don't support anything else. 2110 } else if (Value == "-L") { 2111 CmdArgs.push_back("-msave-temp-labels"); 2112 } else if (Value == "--fatal-warnings") { 2113 CmdArgs.push_back("-massembler-fatal-warnings"); 2114 } else if (Value == "--noexecstack") { 2115 CmdArgs.push_back("-mnoexecstack"); 2116 } else if (Value.startswith("-compress-debug-sections") || 2117 Value.startswith("--compress-debug-sections") || 2118 Value == "-nocompress-debug-sections" || 2119 Value == "--nocompress-debug-sections") { 2120 CmdArgs.push_back(Value.data()); 2121 } else if (Value == "-mrelax-relocations=yes" || 2122 Value == "--mrelax-relocations=yes") { 2123 UseRelaxRelocations = true; 2124 } else if (Value == "-mrelax-relocations=no" || 2125 Value == "--mrelax-relocations=no") { 2126 UseRelaxRelocations = false; 2127 } else if (Value.startswith("-I")) { 2128 CmdArgs.push_back(Value.data()); 2129 // We need to consume the next argument if the current arg is a plain 2130 // -I. The next arg will be the include directory. 2131 if (Value == "-I") 2132 TakeNextArg = true; 2133 } else if (Value.startswith("-gdwarf-")) { 2134 // "-gdwarf-N" options are not cc1as options. 2135 unsigned DwarfVersion = DwarfVersionNum(Value); 2136 if (DwarfVersion == 0) { // Send it onward, and let cc1as complain. 2137 CmdArgs.push_back(Value.data()); 2138 } else { 2139 RenderDebugEnablingArgs(Args, CmdArgs, 2140 codegenoptions::LimitedDebugInfo, 2141 DwarfVersion, llvm::DebuggerKind::Default); 2142 } 2143 } else if (Value.startswith("-mcpu") || Value.startswith("-mfpu") || 2144 Value.startswith("-mhwdiv") || Value.startswith("-march")) { 2145 // Do nothing, we'll validate it later. 2146 } else if (Value == "-defsym") { 2147 if (A->getNumValues() != 2) { 2148 D.Diag(diag::err_drv_defsym_invalid_format) << Value; 2149 break; 2150 } 2151 const char *S = A->getValue(1); 2152 auto Pair = StringRef(S).split('='); 2153 auto Sym = Pair.first; 2154 auto SVal = Pair.second; 2155 2156 if (Sym.empty() || SVal.empty()) { 2157 D.Diag(diag::err_drv_defsym_invalid_format) << S; 2158 break; 2159 } 2160 int64_t IVal; 2161 if (SVal.getAsInteger(0, IVal)) { 2162 D.Diag(diag::err_drv_defsym_invalid_symval) << SVal; 2163 break; 2164 } 2165 CmdArgs.push_back(Value.data()); 2166 TakeNextArg = true; 2167 } else if (Value == "-fdebug-compilation-dir") { 2168 CmdArgs.push_back("-fdebug-compilation-dir"); 2169 TakeNextArg = true; 2170 } else { 2171 D.Diag(diag::err_drv_unsupported_option_argument) 2172 << A->getOption().getName() << Value; 2173 } 2174 } 2175 } 2176 if (UseRelaxRelocations) 2177 CmdArgs.push_back("--mrelax-relocations"); 2178 if (MipsTargetFeature != nullptr) { 2179 CmdArgs.push_back("-target-feature"); 2180 CmdArgs.push_back(MipsTargetFeature); 2181 } 2182 2183 // forward -fembed-bitcode to assmebler 2184 if (C.getDriver().embedBitcodeEnabled() || 2185 C.getDriver().embedBitcodeMarkerOnly()) 2186 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ); 2187} 2188 2189static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D, 2190 bool OFastEnabled, const ArgList &Args, 2191 ArgStringList &CmdArgs) { 2192 // Handle various floating point optimization flags, mapping them to the 2193 // appropriate LLVM code generation flags. This is complicated by several 2194 // "umbrella" flags, so we do this by stepping through the flags incrementally 2195 // adjusting what we think is enabled/disabled, then at the end setting the 2196 // LLVM flags based on the final state. 2197 bool HonorINFs = true; 2198 bool HonorNaNs = true; 2199 // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes. 2200 bool MathErrno = TC.IsMathErrnoDefault(); 2201 bool AssociativeMath = false; 2202 bool ReciprocalMath = false; 2203 bool SignedZeros = true; 2204 bool TrappingMath = true; 2205 StringRef DenormalFPMath = ""; 2206 StringRef FPContract = ""; 2207 2208 if (const Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) { 2209 CmdArgs.push_back("-mlimit-float-precision"); 2210 CmdArgs.push_back(A->getValue()); 2211 } 2212 2213 for (const Arg *A : Args) { 2214 switch (A->getOption().getID()) { 2215 // If this isn't an FP option skip the claim below 2216 default: continue; 2217 2218 // Options controlling individual features 2219 case options::OPT_fhonor_infinities: HonorINFs = true; break; 2220 case options::OPT_fno_honor_infinities: HonorINFs = false; break; 2221 case options::OPT_fhonor_nans: HonorNaNs = true; break; 2222 case options::OPT_fno_honor_nans: HonorNaNs = false; break; 2223 case options::OPT_fmath_errno: MathErrno = true; break; 2224 case options::OPT_fno_math_errno: MathErrno = false; break; 2225 case options::OPT_fassociative_math: AssociativeMath = true; break; 2226 case options::OPT_fno_associative_math: AssociativeMath = false; break; 2227 case options::OPT_freciprocal_math: ReciprocalMath = true; break; 2228 case options::OPT_fno_reciprocal_math: ReciprocalMath = false; break; 2229 case options::OPT_fsigned_zeros: SignedZeros = true; break; 2230 case options::OPT_fno_signed_zeros: SignedZeros = false; break; 2231 case options::OPT_ftrapping_math: TrappingMath = true; break; 2232 case options::OPT_fno_trapping_math: TrappingMath = false; break; 2233 2234 case options::OPT_fdenormal_fp_math_EQ: 2235 DenormalFPMath = A->getValue(); 2236 break; 2237 2238 // Validate and pass through -fp-contract option. 2239 case options::OPT_ffp_contract: { 2240 StringRef Val = A->getValue(); 2241 if (Val == "fast" || Val == "on" || Val == "off") 2242 FPContract = Val; 2243 else 2244 D.Diag(diag::err_drv_unsupported_option_argument) 2245 << A->getOption().getName() << Val; 2246 break; 2247 } 2248 2249 case options::OPT_ffinite_math_only: 2250 HonorINFs = false; 2251 HonorNaNs = false; 2252 break; 2253 case options::OPT_fno_finite_math_only: 2254 HonorINFs = true; 2255 HonorNaNs = true; 2256 break; 2257 2258 case options::OPT_funsafe_math_optimizations: 2259 AssociativeMath = true; 2260 ReciprocalMath = true; 2261 SignedZeros = false; 2262 TrappingMath = false; 2263 break; 2264 case options::OPT_fno_unsafe_math_optimizations: 2265 AssociativeMath = false; 2266 ReciprocalMath = false; 2267 SignedZeros = true; 2268 TrappingMath = true; 2269 // -fno_unsafe_math_optimizations restores default denormal handling 2270 DenormalFPMath = ""; 2271 break; 2272 2273 case options::OPT_Ofast: 2274 // If -Ofast is the optimization level, then -ffast-math should be enabled 2275 if (!OFastEnabled) 2276 continue; 2277 LLVM_FALLTHROUGH; 2278 case options::OPT_ffast_math: 2279 HonorINFs = false; 2280 HonorNaNs = false; 2281 MathErrno = false; 2282 AssociativeMath = true; 2283 ReciprocalMath = true; 2284 SignedZeros = false; 2285 TrappingMath = false; 2286 // If fast-math is set then set the fp-contract mode to fast. 2287 FPContract = "fast"; 2288 break; 2289 case options::OPT_fno_fast_math: 2290 HonorINFs = true; 2291 HonorNaNs = true; 2292 // Turning on -ffast-math (with either flag) removes the need for 2293 // MathErrno. However, turning *off* -ffast-math merely restores the 2294 // toolchain default (which may be false). 2295 MathErrno = TC.IsMathErrnoDefault(); 2296 AssociativeMath = false; 2297 ReciprocalMath = false; 2298 SignedZeros = true; 2299 TrappingMath = true; 2300 // -fno_fast_math restores default denormal and fpcontract handling 2301 DenormalFPMath = ""; 2302 FPContract = ""; 2303 break; 2304 } 2305 2306 // If we handled this option claim it 2307 A->claim(); 2308 } 2309 2310 if (!HonorINFs) 2311 CmdArgs.push_back("-menable-no-infs"); 2312 2313 if (!HonorNaNs) 2314 CmdArgs.push_back("-menable-no-nans"); 2315 2316 if (MathErrno) 2317 CmdArgs.push_back("-fmath-errno"); 2318 2319 if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros && 2320 !TrappingMath) 2321 CmdArgs.push_back("-menable-unsafe-fp-math"); 2322 2323 if (!SignedZeros) 2324 CmdArgs.push_back("-fno-signed-zeros"); 2325 2326 if (AssociativeMath && !SignedZeros && !TrappingMath) 2327 CmdArgs.push_back("-mreassociate"); 2328 2329 if (ReciprocalMath) 2330 CmdArgs.push_back("-freciprocal-math"); 2331 2332 if (!TrappingMath) 2333 CmdArgs.push_back("-fno-trapping-math"); 2334 2335 if (!DenormalFPMath.empty()) 2336 CmdArgs.push_back( 2337 Args.MakeArgString("-fdenormal-fp-math=" + DenormalFPMath)); 2338 2339 if (!FPContract.empty()) 2340 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + FPContract)); 2341 2342 ParseMRecip(D, Args, CmdArgs); 2343 2344 // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the 2345 // individual features enabled by -ffast-math instead of the option itself as 2346 // that's consistent with gcc's behaviour. 2347 if (!HonorINFs && !HonorNaNs && !MathErrno && AssociativeMath && 2348 ReciprocalMath && !SignedZeros && !TrappingMath) 2349 CmdArgs.push_back("-ffast-math"); 2350 2351 // Handle __FINITE_MATH_ONLY__ similarly. 2352 if (!HonorINFs && !HonorNaNs) 2353 CmdArgs.push_back("-ffinite-math-only"); 2354 2355 if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) { 2356 CmdArgs.push_back("-mfpmath"); 2357 CmdArgs.push_back(A->getValue()); 2358 } 2359 2360 // Disable a codegen optimization for floating-point casts. 2361 if (Args.hasFlag(options::OPT_fno_strict_float_cast_overflow, 2362 options::OPT_fstrict_float_cast_overflow, false)) 2363 CmdArgs.push_back("-fno-strict-float-cast-overflow"); 2364} 2365 2366static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs, 2367 const llvm::Triple &Triple, 2368 const InputInfo &Input) { 2369 // Enable region store model by default. 2370 CmdArgs.push_back("-analyzer-store=region"); 2371 2372 // Treat blocks as analysis entry points. 2373 CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks"); 2374 2375 // Add default argument set. 2376 if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) { 2377 CmdArgs.push_back("-analyzer-checker=core"); 2378 CmdArgs.push_back("-analyzer-checker=apiModeling"); 2379 2380 if (!Triple.isWindowsMSVCEnvironment()) { 2381 CmdArgs.push_back("-analyzer-checker=unix"); 2382 } else { 2383 // Enable "unix" checkers that also work on Windows. 2384 CmdArgs.push_back("-analyzer-checker=unix.API"); 2385 CmdArgs.push_back("-analyzer-checker=unix.Malloc"); 2386 CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof"); 2387 CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator"); 2388 CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg"); 2389 CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg"); 2390 } 2391 2392 // Disable some unix checkers for PS4. 2393 if (Triple.isPS4CPU()) { 2394 CmdArgs.push_back("-analyzer-disable-checker=unix.API"); 2395 CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork"); 2396 } 2397 2398 if (Triple.isOSDarwin()) 2399 CmdArgs.push_back("-analyzer-checker=osx"); 2400 2401 CmdArgs.push_back("-analyzer-checker=deadcode"); 2402 2403 if (types::isCXX(Input.getType())) 2404 CmdArgs.push_back("-analyzer-checker=cplusplus"); 2405 2406 if (!Triple.isPS4CPU()) { 2407 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.UncheckedReturn"); 2408 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw"); 2409 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets"); 2410 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp"); 2411 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp"); 2412 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork"); 2413 } 2414 2415 // Default nullability checks. 2416 CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull"); 2417 CmdArgs.push_back("-analyzer-checker=nullability.NullReturnedFromNonnull"); 2418 } 2419 2420 // Set the output format. The default is plist, for (lame) historical reasons. 2421 CmdArgs.push_back("-analyzer-output"); 2422 if (Arg *A = Args.getLastArg(options::OPT__analyzer_output)) 2423 CmdArgs.push_back(A->getValue()); 2424 else 2425 CmdArgs.push_back("plist"); 2426 2427 // Disable the presentation of standard compiler warnings when using 2428 // --analyze. We only want to show static analyzer diagnostics or frontend 2429 // errors. 2430 CmdArgs.push_back("-w"); 2431 2432 // Add -Xanalyzer arguments when running as analyzer. 2433 Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer); 2434} 2435 2436static void RenderSSPOptions(const ToolChain &TC, const ArgList &Args, 2437 ArgStringList &CmdArgs, bool KernelOrKext) { 2438 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple(); 2439 2440 // NVPTX doesn't support stack protectors; from the compiler's perspective, it 2441 // doesn't even have a stack! 2442 if (EffectiveTriple.isNVPTX()) 2443 return; 2444 2445 // -stack-protector=0 is default. 2446 unsigned StackProtectorLevel = 0; 2447 unsigned DefaultStackProtectorLevel = 2448 TC.GetDefaultStackProtectorLevel(KernelOrKext); 2449 2450 if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector, 2451 options::OPT_fstack_protector_all, 2452 options::OPT_fstack_protector_strong, 2453 options::OPT_fstack_protector)) { 2454 if (A->getOption().matches(options::OPT_fstack_protector)) 2455 StackProtectorLevel = 2456 std::max<unsigned>(LangOptions::SSPOn, DefaultStackProtectorLevel); 2457 else if (A->getOption().matches(options::OPT_fstack_protector_strong)) 2458 StackProtectorLevel = LangOptions::SSPStrong; 2459 else if (A->getOption().matches(options::OPT_fstack_protector_all)) 2460 StackProtectorLevel = LangOptions::SSPReq; 2461 } else { 2462 StackProtectorLevel = DefaultStackProtectorLevel; 2463 } 2464 2465 if (StackProtectorLevel) { 2466 CmdArgs.push_back("-stack-protector"); 2467 CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel))); 2468 } 2469 2470 // --param ssp-buffer-size= 2471 for (const Arg *A : Args.filtered(options::OPT__param)) { 2472 StringRef Str(A->getValue()); 2473 if (Str.startswith("ssp-buffer-size=")) { 2474 if (StackProtectorLevel) { 2475 CmdArgs.push_back("-stack-protector-buffer-size"); 2476 // FIXME: Verify the argument is a valid integer. 2477 CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16))); 2478 } 2479 A->claim(); 2480 } 2481 } 2482} 2483 2484static void RenderTrivialAutoVarInitOptions(const Driver &D, 2485 const ToolChain &TC, 2486 const ArgList &Args, 2487 ArgStringList &CmdArgs) { 2488 auto DefaultTrivialAutoVarInit = TC.GetDefaultTrivialAutoVarInit(); 2489 StringRef TrivialAutoVarInit = ""; 2490 2491 for (const Arg *A : Args) { 2492 switch (A->getOption().getID()) { 2493 default: 2494 continue; 2495 case options::OPT_ftrivial_auto_var_init: { 2496 A->claim(); 2497 StringRef Val = A->getValue(); 2498 if (Val == "uninitialized" || Val == "zero" || Val == "pattern") 2499 TrivialAutoVarInit = Val; 2500 else 2501 D.Diag(diag::err_drv_unsupported_option_argument) 2502 << A->getOption().getName() << Val; 2503 break; 2504 } 2505 } 2506 } 2507 2508 if (TrivialAutoVarInit.empty()) 2509 switch (DefaultTrivialAutoVarInit) { 2510 case LangOptions::TrivialAutoVarInitKind::Uninitialized: 2511 break; 2512 case LangOptions::TrivialAutoVarInitKind::Pattern: 2513 TrivialAutoVarInit = "pattern"; 2514 break; 2515 case LangOptions::TrivialAutoVarInitKind::Zero: 2516 TrivialAutoVarInit = "zero"; 2517 break; 2518 } 2519 2520 if (!TrivialAutoVarInit.empty()) { 2521 if (TrivialAutoVarInit == "zero" && !Args.hasArg(options::OPT_enable_trivial_var_init_zero)) 2522 D.Diag(diag::err_drv_trivial_auto_var_init_zero_disabled); 2523 CmdArgs.push_back( 2524 Args.MakeArgString("-ftrivial-auto-var-init=" + TrivialAutoVarInit)); 2525 } 2526} 2527 2528static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs) { 2529 const unsigned ForwardedArguments[] = { 2530 options::OPT_cl_opt_disable, 2531 options::OPT_cl_strict_aliasing, 2532 options::OPT_cl_single_precision_constant, 2533 options::OPT_cl_finite_math_only, 2534 options::OPT_cl_kernel_arg_info, 2535 options::OPT_cl_unsafe_math_optimizations, 2536 options::OPT_cl_fast_relaxed_math, 2537 options::OPT_cl_mad_enable, 2538 options::OPT_cl_no_signed_zeros, 2539 options::OPT_cl_denorms_are_zero, 2540 options::OPT_cl_fp32_correctly_rounded_divide_sqrt, 2541 options::OPT_cl_uniform_work_group_size 2542 }; 2543 2544 if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) { 2545 std::string CLStdStr = std::string("-cl-std=") + A->getValue(); 2546 CmdArgs.push_back(Args.MakeArgString(CLStdStr)); 2547 } 2548 2549 for (const auto &Arg : ForwardedArguments) 2550 if (const auto *A = Args.getLastArg(Arg)) 2551 CmdArgs.push_back(Args.MakeArgString(A->getOption().getPrefixedName())); 2552} 2553 2554static void RenderARCMigrateToolOptions(const Driver &D, const ArgList &Args, 2555 ArgStringList &CmdArgs) { 2556 bool ARCMTEnabled = false; 2557 if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) { 2558 if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check, 2559 options::OPT_ccc_arcmt_modify, 2560 options::OPT_ccc_arcmt_migrate)) { 2561 ARCMTEnabled = true; 2562 switch (A->getOption().getID()) { 2563 default: llvm_unreachable("missed a case"); 2564 case options::OPT_ccc_arcmt_check: 2565 CmdArgs.push_back("-arcmt-check"); 2566 break; 2567 case options::OPT_ccc_arcmt_modify: 2568 CmdArgs.push_back("-arcmt-modify"); 2569 break; 2570 case options::OPT_ccc_arcmt_migrate: 2571 CmdArgs.push_back("-arcmt-migrate"); 2572 CmdArgs.push_back("-mt-migrate-directory"); 2573 CmdArgs.push_back(A->getValue()); 2574 2575 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output); 2576 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors); 2577 break; 2578 } 2579 } 2580 } else { 2581 Args.ClaimAllArgs(options::OPT_ccc_arcmt_check); 2582 Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify); 2583 Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate); 2584 } 2585 2586 if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) { 2587 if (ARCMTEnabled) 2588 D.Diag(diag::err_drv_argument_not_allowed_with) 2589 << A->getAsString(Args) << "-ccc-arcmt-migrate"; 2590 2591 CmdArgs.push_back("-mt-migrate-directory"); 2592 CmdArgs.push_back(A->getValue()); 2593 2594 if (!Args.hasArg(options::OPT_objcmt_migrate_literals, 2595 options::OPT_objcmt_migrate_subscripting, 2596 options::OPT_objcmt_migrate_property)) { 2597 // None specified, means enable them all. 2598 CmdArgs.push_back("-objcmt-migrate-literals"); 2599 CmdArgs.push_back("-objcmt-migrate-subscripting"); 2600 CmdArgs.push_back("-objcmt-migrate-property"); 2601 } else { 2602 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals); 2603 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting); 2604 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property); 2605 } 2606 } else { 2607 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals); 2608 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting); 2609 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property); 2610 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all); 2611 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property); 2612 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property); 2613 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax); 2614 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation); 2615 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype); 2616 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros); 2617 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance); 2618 Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property); 2619 Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property); 2620 Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly); 2621 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init); 2622 Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path); 2623 } 2624} 2625 2626static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T, 2627 const ArgList &Args, ArgStringList &CmdArgs) { 2628 // -fbuiltin is default unless -mkernel is used. 2629 bool UseBuiltins = 2630 Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin, 2631 !Args.hasArg(options::OPT_mkernel)); 2632 if (!UseBuiltins) 2633 CmdArgs.push_back("-fno-builtin"); 2634 2635 // -ffreestanding implies -fno-builtin. 2636 if (Args.hasArg(options::OPT_ffreestanding)) 2637 UseBuiltins = false; 2638 2639 // Process the -fno-builtin-* options. 2640 for (const auto &Arg : Args) { 2641 const Option &O = Arg->getOption(); 2642 if (!O.matches(options::OPT_fno_builtin_)) 2643 continue; 2644 2645 Arg->claim(); 2646 2647 // If -fno-builtin is specified, then there's no need to pass the option to 2648 // the frontend. 2649 if (!UseBuiltins) 2650 continue; 2651 2652 StringRef FuncName = Arg->getValue(); 2653 CmdArgs.push_back(Args.MakeArgString("-fno-builtin-" + FuncName)); 2654 } 2655 2656 // le32-specific flags: 2657 // -fno-math-builtin: clang should not convert math builtins to intrinsics 2658 // by default. 2659 if (TC.getArch() == llvm::Triple::le32) 2660 CmdArgs.push_back("-fno-math-builtin"); 2661} 2662 2663void Driver::getDefaultModuleCachePath(SmallVectorImpl<char> &Result) { 2664 llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false, Result); 2665 llvm::sys::path::append(Result, "org.llvm.clang."); 2666 appendUserToPath(Result); 2667 llvm::sys::path::append(Result, "ModuleCache"); 2668} 2669 2670static void RenderModulesOptions(Compilation &C, const Driver &D, 2671 const ArgList &Args, const InputInfo &Input, 2672 const InputInfo &Output, 2673 ArgStringList &CmdArgs, bool &HaveModules) { 2674 // -fmodules enables the use of precompiled modules (off by default). 2675 // Users can pass -fno-cxx-modules to turn off modules support for 2676 // C++/Objective-C++ programs. 2677 bool HaveClangModules = false; 2678 if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) { 2679 bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules, 2680 options::OPT_fno_cxx_modules, true); 2681 if (AllowedInCXX || !types::isCXX(Input.getType())) { 2682 CmdArgs.push_back("-fmodules"); 2683 HaveClangModules = true; 2684 } 2685 } 2686 2687 HaveModules = HaveClangModules; 2688 if (Args.hasArg(options::OPT_fmodules_ts)) { 2689 CmdArgs.push_back("-fmodules-ts"); 2690 HaveModules = true; 2691 } 2692 2693 // -fmodule-maps enables implicit reading of module map files. By default, 2694 // this is enabled if we are using Clang's flavor of precompiled modules. 2695 if (Args.hasFlag(options::OPT_fimplicit_module_maps, 2696 options::OPT_fno_implicit_module_maps, HaveClangModules)) 2697 CmdArgs.push_back("-fimplicit-module-maps"); 2698 2699 // -fmodules-decluse checks that modules used are declared so (off by default) 2700 if (Args.hasFlag(options::OPT_fmodules_decluse, 2701 options::OPT_fno_modules_decluse, false)) 2702 CmdArgs.push_back("-fmodules-decluse"); 2703 2704 // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that 2705 // all #included headers are part of modules. 2706 if (Args.hasFlag(options::OPT_fmodules_strict_decluse, 2707 options::OPT_fno_modules_strict_decluse, false)) 2708 CmdArgs.push_back("-fmodules-strict-decluse"); 2709 2710 // -fno-implicit-modules turns off implicitly compiling modules on demand. 2711 bool ImplicitModules = false; 2712 if (!Args.hasFlag(options::OPT_fimplicit_modules, 2713 options::OPT_fno_implicit_modules, HaveClangModules)) { 2714 if (HaveModules) 2715 CmdArgs.push_back("-fno-implicit-modules"); 2716 } else if (HaveModules) { 2717 ImplicitModules = true; 2718 // -fmodule-cache-path specifies where our implicitly-built module files 2719 // should be written. 2720 SmallString<128> Path; 2721 if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path)) 2722 Path = A->getValue(); 2723 2724 if (C.isForDiagnostics()) { 2725 // When generating crash reports, we want to emit the modules along with 2726 // the reproduction sources, so we ignore any provided module path. 2727 Path = Output.getFilename(); 2728 llvm::sys::path::replace_extension(Path, ".cache"); 2729 llvm::sys::path::append(Path, "modules"); 2730 } else if (Path.empty()) { 2731 // No module path was provided: use the default. 2732 Driver::getDefaultModuleCachePath(Path); 2733 } 2734 2735 const char Arg[] = "-fmodules-cache-path="; 2736 Path.insert(Path.begin(), Arg, Arg + strlen(Arg)); 2737 CmdArgs.push_back(Args.MakeArgString(Path)); 2738 } 2739 2740 if (HaveModules) { 2741 // -fprebuilt-module-path specifies where to load the prebuilt module files. 2742 for (const Arg *A : Args.filtered(options::OPT_fprebuilt_module_path)) { 2743 CmdArgs.push_back(Args.MakeArgString( 2744 std::string("-fprebuilt-module-path=") + A->getValue())); 2745 A->claim(); 2746 } 2747 } 2748 2749 // -fmodule-name specifies the module that is currently being built (or 2750 // used for header checking by -fmodule-maps). 2751 Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ); 2752 2753 // -fmodule-map-file can be used to specify files containing module 2754 // definitions. 2755 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file); 2756 2757 // -fbuiltin-module-map can be used to load the clang 2758 // builtin headers modulemap file. 2759 if (Args.hasArg(options::OPT_fbuiltin_module_map)) { 2760 SmallString<128> BuiltinModuleMap(D.ResourceDir); 2761 llvm::sys::path::append(BuiltinModuleMap, "include"); 2762 llvm::sys::path::append(BuiltinModuleMap, "module.modulemap"); 2763 if (llvm::sys::fs::exists(BuiltinModuleMap)) 2764 CmdArgs.push_back( 2765 Args.MakeArgString("-fmodule-map-file=" + BuiltinModuleMap)); 2766 } 2767 2768 // The -fmodule-file=<name>=<file> form specifies the mapping of module 2769 // names to precompiled module files (the module is loaded only if used). 2770 // The -fmodule-file=<file> form can be used to unconditionally load 2771 // precompiled module files (whether used or not). 2772 if (HaveModules) 2773 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file); 2774 else 2775 Args.ClaimAllArgs(options::OPT_fmodule_file); 2776 2777 // When building modules and generating crashdumps, we need to dump a module 2778 // dependency VFS alongside the output. 2779 if (HaveClangModules && C.isForDiagnostics()) { 2780 SmallString<128> VFSDir(Output.getFilename()); 2781 llvm::sys::path::replace_extension(VFSDir, ".cache"); 2782 // Add the cache directory as a temp so the crash diagnostics pick it up. 2783 C.addTempFile(Args.MakeArgString(VFSDir)); 2784 2785 llvm::sys::path::append(VFSDir, "vfs"); 2786 CmdArgs.push_back("-module-dependency-dir"); 2787 CmdArgs.push_back(Args.MakeArgString(VFSDir)); 2788 } 2789 2790 if (HaveClangModules) 2791 Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path); 2792 2793 // Pass through all -fmodules-ignore-macro arguments. 2794 Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro); 2795 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval); 2796 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after); 2797 2798 Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp); 2799 2800 if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) { 2801 if (Args.hasArg(options::OPT_fbuild_session_timestamp)) 2802 D.Diag(diag::err_drv_argument_not_allowed_with) 2803 << A->getAsString(Args) << "-fbuild-session-timestamp"; 2804 2805 llvm::sys::fs::file_status Status; 2806 if (llvm::sys::fs::status(A->getValue(), Status)) 2807 D.Diag(diag::err_drv_no_such_file) << A->getValue(); 2808 CmdArgs.push_back( 2809 Args.MakeArgString("-fbuild-session-timestamp=" + 2810 Twine((uint64_t)Status.getLastModificationTime() 2811 .time_since_epoch() 2812 .count()))); 2813 } 2814 2815 if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) { 2816 if (!Args.getLastArg(options::OPT_fbuild_session_timestamp, 2817 options::OPT_fbuild_session_file)) 2818 D.Diag(diag::err_drv_modules_validate_once_requires_timestamp); 2819 2820 Args.AddLastArg(CmdArgs, 2821 options::OPT_fmodules_validate_once_per_build_session); 2822 } 2823 2824 if (Args.hasFlag(options::OPT_fmodules_validate_system_headers, 2825 options::OPT_fno_modules_validate_system_headers, 2826 ImplicitModules)) 2827 CmdArgs.push_back("-fmodules-validate-system-headers"); 2828 2829 Args.AddLastArg(CmdArgs, options::OPT_fmodules_disable_diagnostic_validation); 2830} 2831 2832static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T, 2833 ArgStringList &CmdArgs) { 2834 // -fsigned-char is default. 2835 if (const Arg *A = Args.getLastArg(options::OPT_fsigned_char, 2836 options::OPT_fno_signed_char, 2837 options::OPT_funsigned_char, 2838 options::OPT_fno_unsigned_char)) { 2839 if (A->getOption().matches(options::OPT_funsigned_char) || 2840 A->getOption().matches(options::OPT_fno_signed_char)) { 2841 CmdArgs.push_back("-fno-signed-char"); 2842 } 2843 } else if (!isSignedCharDefault(T)) { 2844 CmdArgs.push_back("-fno-signed-char"); 2845 } 2846 2847 // The default depends on the language standard. 2848 if (const Arg *A = 2849 Args.getLastArg(options::OPT_fchar8__t, options::OPT_fno_char8__t)) 2850 A->render(Args, CmdArgs); 2851 2852 if (const Arg *A = Args.getLastArg(options::OPT_fshort_wchar, 2853 options::OPT_fno_short_wchar)) { 2854 if (A->getOption().matches(options::OPT_fshort_wchar)) { 2855 CmdArgs.push_back("-fwchar-type=short"); 2856 CmdArgs.push_back("-fno-signed-wchar"); 2857 } else { 2858 bool IsARM = T.isARM() || T.isThumb() || T.isAArch64(); 2859 CmdArgs.push_back("-fwchar-type=int"); 2860 if (IsARM && !(T.isOSWindows() || T.isOSNetBSD() || 2861 T.isOSOpenBSD())) 2862 CmdArgs.push_back("-fno-signed-wchar"); 2863 else 2864 CmdArgs.push_back("-fsigned-wchar"); 2865 } 2866 } 2867} 2868 2869static void RenderObjCOptions(const ToolChain &TC, const Driver &D, 2870 const llvm::Triple &T, const ArgList &Args, 2871 ObjCRuntime &Runtime, bool InferCovariantReturns, 2872 const InputInfo &Input, ArgStringList &CmdArgs) { 2873 const llvm::Triple::ArchType Arch = TC.getArch(); 2874 2875 // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and legacy 2876 // is the default. Except for deployment target of 10.5, next runtime is 2877 // always legacy dispatch and -fno-objc-legacy-dispatch gets ignored silently. 2878 if (Runtime.isNonFragile()) { 2879 if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch, 2880 options::OPT_fno_objc_legacy_dispatch, 2881 Runtime.isLegacyDispatchDefaultForArch(Arch))) { 2882 if (TC.UseObjCMixedDispatch()) 2883 CmdArgs.push_back("-fobjc-dispatch-method=mixed"); 2884 else 2885 CmdArgs.push_back("-fobjc-dispatch-method=non-legacy"); 2886 } 2887 } 2888 2889 // When ObjectiveC legacy runtime is in effect on MacOSX, turn on the option 2890 // to do Array/Dictionary subscripting by default. 2891 if (Arch == llvm::Triple::x86 && T.isMacOSX() && 2892 Runtime.getKind() == ObjCRuntime::FragileMacOSX && Runtime.isNeXTFamily()) 2893 CmdArgs.push_back("-fobjc-subscripting-legacy-runtime"); 2894 2895 // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc. 2896 // NOTE: This logic is duplicated in ToolChains.cpp. 2897 if (isObjCAutoRefCount(Args)) { 2898 TC.CheckObjCARC(); 2899 2900 CmdArgs.push_back("-fobjc-arc"); 2901 2902 // FIXME: It seems like this entire block, and several around it should be 2903 // wrapped in isObjC, but for now we just use it here as this is where it 2904 // was being used previously. 2905 if (types::isCXX(Input.getType()) && types::isObjC(Input.getType())) { 2906 if (TC.GetCXXStdlibType(Args) == ToolChain::CST_Libcxx) 2907 CmdArgs.push_back("-fobjc-arc-cxxlib=libc++"); 2908 else 2909 CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++"); 2910 } 2911 2912 // Allow the user to enable full exceptions code emission. 2913 // We default off for Objective-C, on for Objective-C++. 2914 if (Args.hasFlag(options::OPT_fobjc_arc_exceptions, 2915 options::OPT_fno_objc_arc_exceptions, 2916 /*default=*/types::isCXX(Input.getType()))) 2917 CmdArgs.push_back("-fobjc-arc-exceptions"); 2918 } 2919 2920 // Silence warning for full exception code emission options when explicitly 2921 // set to use no ARC. 2922 if (Args.hasArg(options::OPT_fno_objc_arc)) { 2923 Args.ClaimAllArgs(options::OPT_fobjc_arc_exceptions); 2924 Args.ClaimAllArgs(options::OPT_fno_objc_arc_exceptions); 2925 } 2926 2927 // Allow the user to control whether messages can be converted to runtime 2928 // functions. 2929 if (types::isObjC(Input.getType())) { 2930 auto *Arg = Args.getLastArg( 2931 options::OPT_fobjc_convert_messages_to_runtime_calls, 2932 options::OPT_fno_objc_convert_messages_to_runtime_calls); 2933 if (Arg && 2934 Arg->getOption().matches( 2935 options::OPT_fno_objc_convert_messages_to_runtime_calls)) 2936 CmdArgs.push_back("-fno-objc-convert-messages-to-runtime-calls"); 2937 } 2938 2939 // -fobjc-infer-related-result-type is the default, except in the Objective-C 2940 // rewriter. 2941 if (InferCovariantReturns) 2942 CmdArgs.push_back("-fno-objc-infer-related-result-type"); 2943 2944 // Pass down -fobjc-weak or -fno-objc-weak if present. 2945 if (types::isObjC(Input.getType())) { 2946 auto WeakArg = 2947 Args.getLastArg(options::OPT_fobjc_weak, options::OPT_fno_objc_weak); 2948 if (!WeakArg) { 2949 // nothing to do 2950 } else if (!Runtime.allowsWeak()) { 2951 if (WeakArg->getOption().matches(options::OPT_fobjc_weak)) 2952 D.Diag(diag::err_objc_weak_unsupported); 2953 } else { 2954 WeakArg->render(Args, CmdArgs); 2955 } 2956 } 2957} 2958 2959static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args, 2960 ArgStringList &CmdArgs) { 2961 bool CaretDefault = true; 2962 bool ColumnDefault = true; 2963 2964 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_diagnostics_classic, 2965 options::OPT__SLASH_diagnostics_column, 2966 options::OPT__SLASH_diagnostics_caret)) { 2967 switch (A->getOption().getID()) { 2968 case options::OPT__SLASH_diagnostics_caret: 2969 CaretDefault = true; 2970 ColumnDefault = true; 2971 break; 2972 case options::OPT__SLASH_diagnostics_column: 2973 CaretDefault = false; 2974 ColumnDefault = true; 2975 break; 2976 case options::OPT__SLASH_diagnostics_classic: 2977 CaretDefault = false; 2978 ColumnDefault = false; 2979 break; 2980 } 2981 } 2982 2983 // -fcaret-diagnostics is default. 2984 if (!Args.hasFlag(options::OPT_fcaret_diagnostics, 2985 options::OPT_fno_caret_diagnostics, CaretDefault)) 2986 CmdArgs.push_back("-fno-caret-diagnostics"); 2987 2988 // -fdiagnostics-fixit-info is default, only pass non-default. 2989 if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info, 2990 options::OPT_fno_diagnostics_fixit_info)) 2991 CmdArgs.push_back("-fno-diagnostics-fixit-info"); 2992 2993 // Enable -fdiagnostics-show-option by default. 2994 if (Args.hasFlag(options::OPT_fdiagnostics_show_option, 2995 options::OPT_fno_diagnostics_show_option)) 2996 CmdArgs.push_back("-fdiagnostics-show-option"); 2997 2998 if (const Arg *A = 2999 Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) { 3000 CmdArgs.push_back("-fdiagnostics-show-category"); 3001 CmdArgs.push_back(A->getValue()); 3002 } 3003 3004 if (Args.hasFlag(options::OPT_fdiagnostics_show_hotness, 3005 options::OPT_fno_diagnostics_show_hotness, false)) 3006 CmdArgs.push_back("-fdiagnostics-show-hotness"); 3007 3008 if (const Arg *A = 3009 Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) { 3010 std::string Opt = 3011 std::string("-fdiagnostics-hotness-threshold=") + A->getValue(); 3012 CmdArgs.push_back(Args.MakeArgString(Opt)); 3013 } 3014 3015 if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) { 3016 CmdArgs.push_back("-fdiagnostics-format"); 3017 CmdArgs.push_back(A->getValue()); 3018 } 3019 3020 if (const Arg *A = Args.getLastArg( 3021 options::OPT_fdiagnostics_show_note_include_stack, 3022 options::OPT_fno_diagnostics_show_note_include_stack)) { 3023 const Option &O = A->getOption(); 3024 if (O.matches(options::OPT_fdiagnostics_show_note_include_stack)) 3025 CmdArgs.push_back("-fdiagnostics-show-note-include-stack"); 3026 else 3027 CmdArgs.push_back("-fno-diagnostics-show-note-include-stack"); 3028 } 3029 3030 // Color diagnostics are parsed by the driver directly from argv and later 3031 // re-parsed to construct this job; claim any possible color diagnostic here 3032 // to avoid warn_drv_unused_argument and diagnose bad 3033 // OPT_fdiagnostics_color_EQ values. 3034 for (const Arg *A : Args) { 3035 const Option &O = A->getOption(); 3036 if (!O.matches(options::OPT_fcolor_diagnostics) && 3037 !O.matches(options::OPT_fdiagnostics_color) && 3038 !O.matches(options::OPT_fno_color_diagnostics) && 3039 !O.matches(options::OPT_fno_diagnostics_color) && 3040 !O.matches(options::OPT_fdiagnostics_color_EQ)) 3041 continue; 3042 3043 if (O.matches(options::OPT_fdiagnostics_color_EQ)) { 3044 StringRef Value(A->getValue()); 3045 if (Value != "always" && Value != "never" && Value != "auto") 3046 D.Diag(diag::err_drv_clang_unsupported) 3047 << ("-fdiagnostics-color=" + Value).str(); 3048 } 3049 A->claim(); 3050 } 3051 3052 if (D.getDiags().getDiagnosticOptions().ShowColors) 3053 CmdArgs.push_back("-fcolor-diagnostics"); 3054 3055 if (Args.hasArg(options::OPT_fansi_escape_codes)) 3056 CmdArgs.push_back("-fansi-escape-codes"); 3057 3058 if (!Args.hasFlag(options::OPT_fshow_source_location, 3059 options::OPT_fno_show_source_location)) 3060 CmdArgs.push_back("-fno-show-source-location"); 3061 3062 if (Args.hasArg(options::OPT_fdiagnostics_absolute_paths)) 3063 CmdArgs.push_back("-fdiagnostics-absolute-paths"); 3064 3065 if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column, 3066 ColumnDefault)) 3067 CmdArgs.push_back("-fno-show-column"); 3068 3069 if (!Args.hasFlag(options::OPT_fspell_checking, 3070 options::OPT_fno_spell_checking)) 3071 CmdArgs.push_back("-fno-spell-checking"); 3072} 3073 3074enum class DwarfFissionKind { None, Split, Single }; 3075 3076static DwarfFissionKind getDebugFissionKind(const Driver &D, 3077 const ArgList &Args, Arg *&Arg) { 3078 Arg = 3079 Args.getLastArg(options::OPT_gsplit_dwarf, options::OPT_gsplit_dwarf_EQ); 3080 if (!Arg) 3081 return DwarfFissionKind::None; 3082 3083 if (Arg->getOption().matches(options::OPT_gsplit_dwarf)) 3084 return DwarfFissionKind::Split; 3085 3086 StringRef Value = Arg->getValue(); 3087 if (Value == "split") 3088 return DwarfFissionKind::Split; 3089 if (Value == "single") 3090 return DwarfFissionKind::Single; 3091 3092 D.Diag(diag::err_drv_unsupported_option_argument) 3093 << Arg->getOption().getName() << Arg->getValue(); 3094 return DwarfFissionKind::None; 3095} 3096 3097static void RenderDebugOptions(const ToolChain &TC, const Driver &D, 3098 const llvm::Triple &T, const ArgList &Args, 3099 bool EmitCodeView, bool IsWindowsMSVC, 3100 ArgStringList &CmdArgs, 3101 codegenoptions::DebugInfoKind &DebugInfoKind, 3102 DwarfFissionKind &DwarfFission) { 3103 if (Args.hasFlag(options::OPT_fdebug_info_for_profiling, 3104 options::OPT_fno_debug_info_for_profiling, false) && 3105 checkDebugInfoOption( 3106 Args.getLastArg(options::OPT_fdebug_info_for_profiling), Args, D, TC)) 3107 CmdArgs.push_back("-fdebug-info-for-profiling"); 3108 3109 // The 'g' groups options involve a somewhat intricate sequence of decisions 3110 // about what to pass from the driver to the frontend, but by the time they 3111 // reach cc1 they've been factored into three well-defined orthogonal choices: 3112 // * what level of debug info to generate 3113 // * what dwarf version to write 3114 // * what debugger tuning to use 3115 // This avoids having to monkey around further in cc1 other than to disable 3116 // codeview if not running in a Windows environment. Perhaps even that 3117 // decision should be made in the driver as well though. 3118 unsigned DWARFVersion = 0; 3119 llvm::DebuggerKind DebuggerTuning = TC.getDefaultDebuggerTuning(); 3120 3121 bool SplitDWARFInlining = 3122 Args.hasFlag(options::OPT_fsplit_dwarf_inlining, 3123 options::OPT_fno_split_dwarf_inlining, true); 3124 3125 Args.ClaimAllArgs(options::OPT_g_Group); 3126 3127 Arg* SplitDWARFArg; 3128 DwarfFission = getDebugFissionKind(D, Args, SplitDWARFArg); 3129 3130 if (DwarfFission != DwarfFissionKind::None && 3131 !checkDebugInfoOption(SplitDWARFArg, Args, D, TC)) { 3132 DwarfFission = DwarfFissionKind::None; 3133 SplitDWARFInlining = false; 3134 } 3135 3136 if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) { 3137 if (checkDebugInfoOption(A, Args, D, TC)) { 3138 // If the last option explicitly specified a debug-info level, use it. 3139 if (A->getOption().matches(options::OPT_gN_Group)) { 3140 DebugInfoKind = DebugLevelToInfoKind(*A); 3141 // If you say "-gsplit-dwarf -gline-tables-only", -gsplit-dwarf loses. 3142 // But -gsplit-dwarf is not a g_group option, hence we have to check the 3143 // order explicitly. If -gsplit-dwarf wins, we fix DebugInfoKind later. 3144 // This gets a bit more complicated if you've disabled inline info in 3145 // the skeleton CUs (SplitDWARFInlining) - then there's value in 3146 // composing split-dwarf and line-tables-only, so let those compose 3147 // naturally in that case. And if you just turned off debug info, 3148 // (-gsplit-dwarf -g0) - do that. 3149 if (DwarfFission != DwarfFissionKind::None) { 3150 if (A->getIndex() > SplitDWARFArg->getIndex()) { 3151 if (DebugInfoKind == codegenoptions::NoDebugInfo || 3152 DebugInfoKind == codegenoptions::DebugDirectivesOnly || 3153 (DebugInfoKind == codegenoptions::DebugLineTablesOnly && 3154 SplitDWARFInlining)) 3155 DwarfFission = DwarfFissionKind::None; 3156 } else if (SplitDWARFInlining) 3157 DebugInfoKind = codegenoptions::NoDebugInfo; 3158 } 3159 } else { 3160 // For any other 'g' option, use Limited. 3161 DebugInfoKind = codegenoptions::LimitedDebugInfo; 3162 } 3163 } else { 3164 DebugInfoKind = codegenoptions::LimitedDebugInfo; 3165 } 3166 } 3167 3168 // If a debugger tuning argument appeared, remember it. 3169 if (const Arg *A = 3170 Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) { 3171 if (checkDebugInfoOption(A, Args, D, TC)) { 3172 if (A->getOption().matches(options::OPT_glldb)) 3173 DebuggerTuning = llvm::DebuggerKind::LLDB; 3174 else if (A->getOption().matches(options::OPT_gsce)) 3175 DebuggerTuning = llvm::DebuggerKind::SCE; 3176 else 3177 DebuggerTuning = llvm::DebuggerKind::GDB; 3178 } 3179 } 3180 3181 // If a -gdwarf argument appeared, remember it. 3182 if (const Arg *A = 3183 Args.getLastArg(options::OPT_gdwarf_2, options::OPT_gdwarf_3, 3184 options::OPT_gdwarf_4, options::OPT_gdwarf_5)) 3185 if (checkDebugInfoOption(A, Args, D, TC)) 3186 DWARFVersion = DwarfVersionNum(A->getSpelling()); 3187 3188 if (const Arg *A = Args.getLastArg(options::OPT_gcodeview)) { 3189 if (checkDebugInfoOption(A, Args, D, TC)) 3190 EmitCodeView = true; 3191 } 3192 3193 // If the user asked for debug info but did not explicitly specify -gcodeview 3194 // or -gdwarf, ask the toolchain for the default format. 3195 if (!EmitCodeView && DWARFVersion == 0 && 3196 DebugInfoKind != codegenoptions::NoDebugInfo) { 3197 switch (TC.getDefaultDebugFormat()) { 3198 case codegenoptions::DIF_CodeView: 3199 EmitCodeView = true; 3200 break; 3201 case codegenoptions::DIF_DWARF: 3202 DWARFVersion = TC.GetDefaultDwarfVersion(); 3203 break; 3204 } 3205 } 3206 3207 // -gline-directives-only supported only for the DWARF debug info. 3208 if (DWARFVersion == 0 && DebugInfoKind == codegenoptions::DebugDirectivesOnly) 3209 DebugInfoKind = codegenoptions::NoDebugInfo; 3210 3211 // We ignore flag -gstrict-dwarf for now. 3212 // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags. 3213 Args.ClaimAllArgs(options::OPT_g_flags_Group); 3214 3215 // Column info is included by default for everything except SCE and 3216 // CodeView. Clang doesn't track end columns, just starting columns, which, 3217 // in theory, is fine for CodeView (and PDB). In practice, however, the 3218 // Microsoft debuggers don't handle missing end columns well, so it's better 3219 // not to include any column info. 3220 if (const Arg *A = Args.getLastArg(options::OPT_gcolumn_info)) 3221 (void)checkDebugInfoOption(A, Args, D, TC); 3222 if (Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info, 3223 /*Default=*/!EmitCodeView && 3224 DebuggerTuning != llvm::DebuggerKind::SCE)) 3225 CmdArgs.push_back("-dwarf-column-info"); 3226 3227 // FIXME: Move backend command line options to the module. 3228 // If -gline-tables-only or -gline-directives-only is the last option it wins. 3229 if (const Arg *A = Args.getLastArg(options::OPT_gmodules)) 3230 if (checkDebugInfoOption(A, Args, D, TC)) { 3231 if (DebugInfoKind != codegenoptions::DebugLineTablesOnly && 3232 DebugInfoKind != codegenoptions::DebugDirectivesOnly) { 3233 DebugInfoKind = codegenoptions::LimitedDebugInfo; 3234 CmdArgs.push_back("-dwarf-ext-refs"); 3235 CmdArgs.push_back("-fmodule-format=obj"); 3236 } 3237 } 3238 3239 // -gsplit-dwarf should turn on -g and enable the backend dwarf 3240 // splitting and extraction. 3241 // FIXME: Currently only works on Linux and Fuchsia. 3242 if (T.isOSLinux() || T.isOSFuchsia()) { 3243 if (!SplitDWARFInlining) 3244 CmdArgs.push_back("-fno-split-dwarf-inlining"); 3245 3246 if (DwarfFission != DwarfFissionKind::None) { 3247 if (DebugInfoKind == codegenoptions::NoDebugInfo) 3248 DebugInfoKind = codegenoptions::LimitedDebugInfo; 3249 3250 if (DwarfFission == DwarfFissionKind::Single) 3251 CmdArgs.push_back("-enable-split-dwarf=single"); 3252 else 3253 CmdArgs.push_back("-enable-split-dwarf"); 3254 } 3255 } 3256 3257 // After we've dealt with all combinations of things that could 3258 // make DebugInfoKind be other than None or DebugLineTablesOnly, 3259 // figure out if we need to "upgrade" it to standalone debug info. 3260 // We parse these two '-f' options whether or not they will be used, 3261 // to claim them even if you wrote "-fstandalone-debug -gline-tables-only" 3262 bool NeedFullDebug = Args.hasFlag(options::OPT_fstandalone_debug, 3263 options::OPT_fno_standalone_debug, 3264 TC.GetDefaultStandaloneDebug()); 3265 if (const Arg *A = Args.getLastArg(options::OPT_fstandalone_debug)) 3266 (void)checkDebugInfoOption(A, Args, D, TC); 3267 if (DebugInfoKind == codegenoptions::LimitedDebugInfo && NeedFullDebug) 3268 DebugInfoKind = codegenoptions::FullDebugInfo; 3269 3270 if (Args.hasFlag(options::OPT_gembed_source, options::OPT_gno_embed_source, 3271 false)) { 3272 // Source embedding is a vendor extension to DWARF v5. By now we have 3273 // checked if a DWARF version was stated explicitly, and have otherwise 3274 // fallen back to the target default, so if this is still not at least 5 3275 // we emit an error. 3276 const Arg *A = Args.getLastArg(options::OPT_gembed_source); 3277 if (DWARFVersion < 5) 3278 D.Diag(diag::err_drv_argument_only_allowed_with) 3279 << A->getAsString(Args) << "-gdwarf-5"; 3280 else if (checkDebugInfoOption(A, Args, D, TC)) 3281 CmdArgs.push_back("-gembed-source"); 3282 } 3283 3284 if (EmitCodeView) { 3285 CmdArgs.push_back("-gcodeview"); 3286 3287 // Emit codeview type hashes if requested. 3288 if (Args.hasFlag(options::OPT_gcodeview_ghash, 3289 options::OPT_gno_codeview_ghash, false)) { 3290 CmdArgs.push_back("-gcodeview-ghash"); 3291 } 3292 } 3293 3294 // Adjust the debug info kind for the given toolchain. 3295 TC.adjustDebugInfoKind(DebugInfoKind, Args); 3296 3297 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DWARFVersion, 3298 DebuggerTuning); 3299 3300 // -fdebug-macro turns on macro debug info generation. 3301 if (Args.hasFlag(options::OPT_fdebug_macro, options::OPT_fno_debug_macro, 3302 false)) 3303 if (checkDebugInfoOption(Args.getLastArg(options::OPT_fdebug_macro), Args, 3304 D, TC)) 3305 CmdArgs.push_back("-debug-info-macro"); 3306 3307 // -ggnu-pubnames turns on gnu style pubnames in the backend. 3308 const auto *PubnamesArg = 3309 Args.getLastArg(options::OPT_ggnu_pubnames, options::OPT_gno_gnu_pubnames, 3310 options::OPT_gpubnames, options::OPT_gno_pubnames); 3311 if (DwarfFission != DwarfFissionKind::None || 3312 DebuggerTuning == llvm::DebuggerKind::LLDB || 3313 (PubnamesArg && checkDebugInfoOption(PubnamesArg, Args, D, TC))) 3314 if (!PubnamesArg || 3315 (!PubnamesArg->getOption().matches(options::OPT_gno_gnu_pubnames) && 3316 !PubnamesArg->getOption().matches(options::OPT_gno_pubnames))) 3317 CmdArgs.push_back(PubnamesArg && PubnamesArg->getOption().matches( 3318 options::OPT_gpubnames) 3319 ? "-gpubnames" 3320 : "-ggnu-pubnames"); 3321 3322 if (Args.hasFlag(options::OPT_fdebug_ranges_base_address, 3323 options::OPT_fno_debug_ranges_base_address, false)) { 3324 CmdArgs.push_back("-fdebug-ranges-base-address"); 3325 } 3326 3327 // -gdwarf-aranges turns on the emission of the aranges section in the 3328 // backend. 3329 // Always enabled for SCE tuning. 3330 bool NeedAranges = DebuggerTuning == llvm::DebuggerKind::SCE; 3331 if (const Arg *A = Args.getLastArg(options::OPT_gdwarf_aranges)) 3332 NeedAranges = checkDebugInfoOption(A, Args, D, TC) || NeedAranges; 3333 if (NeedAranges) { 3334 CmdArgs.push_back("-mllvm"); 3335 CmdArgs.push_back("-generate-arange-section"); 3336 } 3337 3338 if (Args.hasFlag(options::OPT_fdebug_types_section, 3339 options::OPT_fno_debug_types_section, false)) { 3340 if (!T.isOSBinFormatELF()) { 3341 D.Diag(diag::err_drv_unsupported_opt_for_target) 3342 << Args.getLastArg(options::OPT_fdebug_types_section) 3343 ->getAsString(Args) 3344 << T.getTriple(); 3345 } else if (checkDebugInfoOption( 3346 Args.getLastArg(options::OPT_fdebug_types_section), Args, D, 3347 TC)) { 3348 CmdArgs.push_back("-mllvm"); 3349 CmdArgs.push_back("-generate-type-units"); 3350 } 3351 } 3352 3353 // Decide how to render forward declarations of template instantiations. 3354 // SCE wants full descriptions, others just get them in the name. 3355 if (DebuggerTuning == llvm::DebuggerKind::SCE) 3356 CmdArgs.push_back("-debug-forward-template-params"); 3357 3358 // Do we need to explicitly import anonymous namespaces into the parent 3359 // scope? 3360 if (DebuggerTuning == llvm::DebuggerKind::SCE) 3361 CmdArgs.push_back("-dwarf-explicit-import"); 3362 3363 RenderDebugInfoCompressionArgs(Args, CmdArgs, D, TC); 3364} 3365 3366void Clang::ConstructJob(Compilation &C, const JobAction &JA, 3367 const InputInfo &Output, const InputInfoList &Inputs, 3368 const ArgList &Args, const char *LinkingOutput) const { 3369 const auto &TC = getToolChain(); 3370 const llvm::Triple &RawTriple = TC.getTriple(); 3371 const llvm::Triple &Triple = TC.getEffectiveTriple(); 3372 const std::string &TripleStr = Triple.getTriple(); 3373 3374 bool KernelOrKext = 3375 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext); 3376 const Driver &D = TC.getDriver(); 3377 ArgStringList CmdArgs; 3378 3379 // Check number of inputs for sanity. We need at least one input. 3380 assert(Inputs.size() >= 1 && "Must have at least one input."); 3381 // CUDA/HIP compilation may have multiple inputs (source file + results of 3382 // device-side compilations). OpenMP device jobs also take the host IR as a 3383 // second input. Module precompilation accepts a list of header files to 3384 // include as part of the module. All other jobs are expected to have exactly 3385 // one input. 3386 bool IsCuda = JA.isOffloading(Action::OFK_Cuda); 3387 bool IsHIP = JA.isOffloading(Action::OFK_HIP); 3388 bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP); 3389 bool IsHeaderModulePrecompile = isa<HeaderModulePrecompileJobAction>(JA); 3390 3391 // A header module compilation doesn't have a main input file, so invent a 3392 // fake one as a placeholder. 3393 const char *ModuleName = [&]{ 3394 auto *ModuleNameArg = Args.getLastArg(options::OPT_fmodule_name_EQ); 3395 return ModuleNameArg ? ModuleNameArg->getValue() : ""; 3396 }(); 3397 InputInfo HeaderModuleInput(Inputs[0].getType(), ModuleName, ModuleName); 3398 3399 const InputInfo &Input = 3400 IsHeaderModulePrecompile ? HeaderModuleInput : Inputs[0]; 3401 3402 InputInfoList ModuleHeaderInputs; 3403 const InputInfo *CudaDeviceInput = nullptr; 3404 const InputInfo *OpenMPDeviceInput = nullptr; 3405 for (const InputInfo &I : Inputs) { 3406 if (&I == &Input) { 3407 // This is the primary input. 3408 } else if (IsHeaderModulePrecompile && 3409 types::getPrecompiledType(I.getType()) == types::TY_PCH) { 3410 types::ID Expected = HeaderModuleInput.getType(); 3411 if (I.getType() != Expected) { 3412 D.Diag(diag::err_drv_module_header_wrong_kind) 3413 << I.getFilename() << types::getTypeName(I.getType()) 3414 << types::getTypeName(Expected); 3415 } 3416 ModuleHeaderInputs.push_back(I); 3417 } else if ((IsCuda || IsHIP) && !CudaDeviceInput) { 3418 CudaDeviceInput = &I; 3419 } else if (IsOpenMPDevice && !OpenMPDeviceInput) { 3420 OpenMPDeviceInput = &I; 3421 } else { 3422 llvm_unreachable("unexpectedly given multiple inputs"); 3423 } 3424 } 3425 3426 const llvm::Triple *AuxTriple = IsCuda ? TC.getAuxTriple() : nullptr; 3427 bool IsWindowsGNU = RawTriple.isWindowsGNUEnvironment(); 3428 bool IsWindowsCygnus = RawTriple.isWindowsCygwinEnvironment(); 3429 bool IsWindowsMSVC = RawTriple.isWindowsMSVCEnvironment(); 3430 bool IsIAMCU = RawTriple.isOSIAMCU(); 3431 3432 // Adjust IsWindowsXYZ for CUDA/HIP compilations. Even when compiling in 3433 // device mode (i.e., getToolchain().getTriple() is NVPTX/AMDGCN, not 3434 // Windows), we need to pass Windows-specific flags to cc1. 3435 if (IsCuda || IsHIP) { 3436 IsWindowsMSVC |= AuxTriple && AuxTriple->isWindowsMSVCEnvironment(); 3437 IsWindowsGNU |= AuxTriple && AuxTriple->isWindowsGNUEnvironment(); 3438 IsWindowsCygnus |= AuxTriple && AuxTriple->isWindowsCygwinEnvironment(); 3439 } 3440 3441 // C++ is not supported for IAMCU. 3442 if (IsIAMCU && types::isCXX(Input.getType())) 3443 D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU"; 3444 3445 // Invoke ourselves in -cc1 mode. 3446 // 3447 // FIXME: Implement custom jobs for internal actions. 3448 CmdArgs.push_back("-cc1"); 3449 3450 // Add the "effective" target triple. 3451 CmdArgs.push_back("-triple"); 3452 CmdArgs.push_back(Args.MakeArgString(TripleStr)); 3453 3454 if (const Arg *MJ = Args.getLastArg(options::OPT_MJ)) { 3455 DumpCompilationDatabase(C, MJ->getValue(), TripleStr, Output, Input, Args); 3456 Args.ClaimAllArgs(options::OPT_MJ); 3457 } 3458 3459 if (IsCuda || IsHIP) { 3460 // We have to pass the triple of the host if compiling for a CUDA/HIP device 3461 // and vice-versa. 3462 std::string NormalizedTriple; 3463 if (JA.isDeviceOffloading(Action::OFK_Cuda) || 3464 JA.isDeviceOffloading(Action::OFK_HIP)) 3465 NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Host>() 3466 ->getTriple() 3467 .normalize(); 3468 else 3469 NormalizedTriple = 3470 (IsCuda ? C.getSingleOffloadToolChain<Action::OFK_Cuda>() 3471 : C.getSingleOffloadToolChain<Action::OFK_HIP>()) 3472 ->getTriple() 3473 .normalize(); 3474 3475 CmdArgs.push_back("-aux-triple"); 3476 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple)); 3477 } 3478 3479 if (IsOpenMPDevice) { 3480 // We have to pass the triple of the host if compiling for an OpenMP device. 3481 std::string NormalizedTriple = 3482 C.getSingleOffloadToolChain<Action::OFK_Host>() 3483 ->getTriple() 3484 .normalize(); 3485 CmdArgs.push_back("-aux-triple"); 3486 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple)); 3487 } 3488 3489 if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm || 3490 Triple.getArch() == llvm::Triple::thumb)) { 3491 unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6; 3492 unsigned Version; 3493 Triple.getArchName().substr(Offset).getAsInteger(10, Version); 3494 if (Version < 7) 3495 D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName() 3496 << TripleStr; 3497 } 3498 3499 // Push all default warning arguments that are specific to 3500 // the given target. These come before user provided warning options 3501 // are provided. 3502 TC.addClangWarningOptions(CmdArgs); 3503 3504 // Select the appropriate action. 3505 RewriteKind rewriteKind = RK_None; 3506 3507 if (isa<AnalyzeJobAction>(JA)) { 3508 assert(JA.getType() == types::TY_Plist && "Invalid output type."); 3509 CmdArgs.push_back("-analyze"); 3510 } else if (isa<MigrateJobAction>(JA)) { 3511 CmdArgs.push_back("-migrate"); 3512 } else if (isa<PreprocessJobAction>(JA)) { 3513 if (Output.getType() == types::TY_Dependencies) 3514 CmdArgs.push_back("-Eonly"); 3515 else { 3516 CmdArgs.push_back("-E"); 3517 if (Args.hasArg(options::OPT_rewrite_objc) && 3518 !Args.hasArg(options::OPT_g_Group)) 3519 CmdArgs.push_back("-P"); 3520 } 3521 } else if (isa<AssembleJobAction>(JA)) { 3522 CmdArgs.push_back("-emit-obj"); 3523 3524 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D); 3525 3526 // Also ignore explicit -force_cpusubtype_ALL option. 3527 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL); 3528 } else if (isa<PrecompileJobAction>(JA)) { 3529 if (JA.getType() == types::TY_Nothing) 3530 CmdArgs.push_back("-fsyntax-only"); 3531 else if (JA.getType() == types::TY_ModuleFile) 3532 CmdArgs.push_back(IsHeaderModulePrecompile 3533 ? "-emit-header-module" 3534 : "-emit-module-interface"); 3535 else 3536 CmdArgs.push_back("-emit-pch"); 3537 } else if (isa<VerifyPCHJobAction>(JA)) { 3538 CmdArgs.push_back("-verify-pch"); 3539 } else { 3540 assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) && 3541 "Invalid action for clang tool."); 3542 if (JA.getType() == types::TY_Nothing) { 3543 CmdArgs.push_back("-fsyntax-only"); 3544 } else if (JA.getType() == types::TY_LLVM_IR || 3545 JA.getType() == types::TY_LTO_IR) { 3546 CmdArgs.push_back("-emit-llvm"); 3547 } else if (JA.getType() == types::TY_LLVM_BC || 3548 JA.getType() == types::TY_LTO_BC) { 3549 CmdArgs.push_back("-emit-llvm-bc"); 3550 } else if (JA.getType() == types::TY_PP_Asm) { 3551 CmdArgs.push_back("-S"); 3552 } else if (JA.getType() == types::TY_AST) { 3553 CmdArgs.push_back("-emit-pch"); 3554 } else if (JA.getType() == types::TY_ModuleFile) { 3555 CmdArgs.push_back("-module-file-info"); 3556 } else if (JA.getType() == types::TY_RewrittenObjC) { 3557 CmdArgs.push_back("-rewrite-objc"); 3558 rewriteKind = RK_NonFragile; 3559 } else if (JA.getType() == types::TY_RewrittenLegacyObjC) { 3560 CmdArgs.push_back("-rewrite-objc"); 3561 rewriteKind = RK_Fragile; 3562 } else { 3563 assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!"); 3564 } 3565 3566 // Preserve use-list order by default when emitting bitcode, so that 3567 // loading the bitcode up in 'opt' or 'llc' and running passes gives the 3568 // same result as running passes here. For LTO, we don't need to preserve 3569 // the use-list order, since serialization to bitcode is part of the flow. 3570 if (JA.getType() == types::TY_LLVM_BC) 3571 CmdArgs.push_back("-emit-llvm-uselists"); 3572 3573 // Device-side jobs do not support LTO. 3574 bool isDeviceOffloadAction = !(JA.isDeviceOffloading(Action::OFK_None) || 3575 JA.isDeviceOffloading(Action::OFK_Host)); 3576 3577 if (D.isUsingLTO() && !isDeviceOffloadAction) { 3578 Args.AddLastArg(CmdArgs, options::OPT_flto, options::OPT_flto_EQ); 3579 3580 // The Darwin and PS4 linkers currently use the legacy LTO API, which 3581 // does not support LTO unit features (CFI, whole program vtable opt) 3582 // under ThinLTO. 3583 if (!(RawTriple.isOSDarwin() || RawTriple.isPS4()) || 3584 D.getLTOMode() == LTOK_Full) 3585 CmdArgs.push_back("-flto-unit"); 3586 } 3587 } 3588 3589 if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) { 3590 if (!types::isLLVMIR(Input.getType())) 3591 D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args) 3592 << "-x ir"; 3593 Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ); 3594 } 3595 3596 if (Args.getLastArg(options::OPT_save_temps_EQ)) 3597 Args.AddLastArg(CmdArgs, options::OPT_save_temps_EQ); 3598 3599 // Embed-bitcode option. 3600 // Only white-listed flags below are allowed to be embedded. 3601 if (C.getDriver().embedBitcodeInObject() && !C.getDriver().isUsingLTO() && 3602 (isa<BackendJobAction>(JA) || isa<AssembleJobAction>(JA))) { 3603 // Add flags implied by -fembed-bitcode. 3604 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ); 3605 // Disable all llvm IR level optimizations. 3606 CmdArgs.push_back("-disable-llvm-passes"); 3607 3608 // reject options that shouldn't be supported in bitcode 3609 // also reject kernel/kext 3610 static const constexpr unsigned kBitcodeOptionBlacklist[] = { 3611 options::OPT_mkernel, 3612 options::OPT_fapple_kext, 3613 options::OPT_ffunction_sections, 3614 options::OPT_fno_function_sections, 3615 options::OPT_fdata_sections, 3616 options::OPT_fno_data_sections, 3617 options::OPT_funique_section_names, 3618 options::OPT_fno_unique_section_names, 3619 options::OPT_mrestrict_it, 3620 options::OPT_mno_restrict_it, 3621 options::OPT_mstackrealign, 3622 options::OPT_mno_stackrealign, 3623 options::OPT_mstack_alignment, 3624 options::OPT_mcmodel_EQ, 3625 options::OPT_mlong_calls, 3626 options::OPT_mno_long_calls, 3627 options::OPT_ggnu_pubnames, 3628 options::OPT_gdwarf_aranges, 3629 options::OPT_fdebug_types_section, 3630 options::OPT_fno_debug_types_section, 3631 options::OPT_fdwarf_directory_asm, 3632 options::OPT_fno_dwarf_directory_asm, 3633 options::OPT_mrelax_all, 3634 options::OPT_mno_relax_all, 3635 options::OPT_ftrap_function_EQ, 3636 options::OPT_ffixed_r9, 3637 options::OPT_mfix_cortex_a53_835769, 3638 options::OPT_mno_fix_cortex_a53_835769, 3639 options::OPT_ffixed_x18, 3640 options::OPT_mglobal_merge, 3641 options::OPT_mno_global_merge, 3642 options::OPT_mred_zone, 3643 options::OPT_mno_red_zone, 3644 options::OPT_Wa_COMMA, 3645 options::OPT_Xassembler, 3646 options::OPT_mllvm, 3647 }; 3648 for (const auto &A : Args) 3649 if (std::find(std::begin(kBitcodeOptionBlacklist), 3650 std::end(kBitcodeOptionBlacklist), 3651 A->getOption().getID()) != 3652 std::end(kBitcodeOptionBlacklist)) 3653 D.Diag(diag::err_drv_unsupported_embed_bitcode) << A->getSpelling(); 3654 3655 // Render the CodeGen options that need to be passed. 3656 if (!Args.hasFlag(options::OPT_foptimize_sibling_calls, 3657 options::OPT_fno_optimize_sibling_calls)) 3658 CmdArgs.push_back("-mdisable-tail-calls"); 3659 3660 RenderFloatingPointOptions(TC, D, isOptimizationLevelFast(Args), Args, 3661 CmdArgs); 3662 3663 // Render ABI arguments 3664 switch (TC.getArch()) { 3665 default: break; 3666 case llvm::Triple::arm: 3667 case llvm::Triple::armeb: 3668 case llvm::Triple::thumbeb: 3669 RenderARMABI(Triple, Args, CmdArgs); 3670 break; 3671 case llvm::Triple::aarch64: 3672 case llvm::Triple::aarch64_be: 3673 RenderAArch64ABI(Triple, Args, CmdArgs); 3674 break; 3675 } 3676 3677 // Optimization level for CodeGen. 3678 if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) { 3679 if (A->getOption().matches(options::OPT_O4)) { 3680 CmdArgs.push_back("-O3"); 3681 D.Diag(diag::warn_O4_is_O3); 3682 } else { 3683 A->render(Args, CmdArgs); 3684 } 3685 } 3686 3687 // Input/Output file. 3688 if (Output.getType() == types::TY_Dependencies) { 3689 // Handled with other dependency code. 3690 } else if (Output.isFilename()) { 3691 CmdArgs.push_back("-o"); 3692 CmdArgs.push_back(Output.getFilename()); 3693 } else { 3694 assert(Output.isNothing() && "Input output."); 3695 } 3696 3697 for (const auto &II : Inputs) { 3698 addDashXForInput(Args, II, CmdArgs); 3699 if (II.isFilename()) 3700 CmdArgs.push_back(II.getFilename()); 3701 else 3702 II.getInputArg().renderAsInput(Args, CmdArgs); 3703 } 3704 3705 C.addCommand(llvm::make_unique<Command>(JA, *this, D.getClangProgramPath(), 3706 CmdArgs, Inputs)); 3707 return; 3708 } 3709 3710 if (C.getDriver().embedBitcodeMarkerOnly() && !C.getDriver().isUsingLTO()) 3711 CmdArgs.push_back("-fembed-bitcode=marker"); 3712 3713 // We normally speed up the clang process a bit by skipping destructors at 3714 // exit, but when we're generating diagnostics we can rely on some of the 3715 // cleanup. 3716 if (!C.isForDiagnostics()) 3717 CmdArgs.push_back("-disable-free"); 3718 3719#ifdef NDEBUG 3720 const bool IsAssertBuild = false; 3721#else 3722 const bool IsAssertBuild = true; 3723#endif 3724 3725 // Disable the verification pass in -asserts builds. 3726 if (!IsAssertBuild) 3727 CmdArgs.push_back("-disable-llvm-verifier"); 3728 3729 // Discard value names in assert builds unless otherwise specified. 3730 if (Args.hasFlag(options::OPT_fdiscard_value_names, 3731 options::OPT_fno_discard_value_names, !IsAssertBuild)) 3732 CmdArgs.push_back("-discard-value-names"); 3733 3734 // Set the main file name, so that debug info works even with 3735 // -save-temps. 3736 CmdArgs.push_back("-main-file-name"); 3737 CmdArgs.push_back(getBaseInputName(Args, Input)); 3738 3739 // Some flags which affect the language (via preprocessor 3740 // defines). 3741 if (Args.hasArg(options::OPT_static)) 3742 CmdArgs.push_back("-static-define"); 3743 3744 if (Args.hasArg(options::OPT_municode)) 3745 CmdArgs.push_back("-DUNICODE"); 3746 3747 if (isa<AnalyzeJobAction>(JA)) 3748 RenderAnalyzerOptions(Args, CmdArgs, Triple, Input); 3749 3750 // Enable compatilibily mode to avoid analyzer-config related errors. 3751 // Since we can't access frontend flags through hasArg, let's manually iterate 3752 // through them. 3753 bool FoundAnalyzerConfig = false; 3754 for (auto Arg : Args.filtered(options::OPT_Xclang)) 3755 if (StringRef(Arg->getValue()) == "-analyzer-config") { 3756 FoundAnalyzerConfig = true; 3757 break; 3758 } 3759 if (!FoundAnalyzerConfig) 3760 for (auto Arg : Args.filtered(options::OPT_Xanalyzer)) 3761 if (StringRef(Arg->getValue()) == "-analyzer-config") { 3762 FoundAnalyzerConfig = true; 3763 break; 3764 } 3765 if (FoundAnalyzerConfig) 3766 CmdArgs.push_back("-analyzer-config-compatibility-mode=true"); 3767 3768 CheckCodeGenerationOptions(D, Args); 3769 3770 unsigned FunctionAlignment = ParseFunctionAlignment(TC, Args); 3771 assert(FunctionAlignment <= 31 && "function alignment will be truncated!"); 3772 if (FunctionAlignment) { 3773 CmdArgs.push_back("-function-alignment"); 3774 CmdArgs.push_back(Args.MakeArgString(std::to_string(FunctionAlignment))); 3775 } 3776 3777 llvm::Reloc::Model RelocationModel; 3778 unsigned PICLevel; 3779 bool IsPIE; 3780 std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(TC, Args); 3781 3782 const char *RMName = RelocationModelName(RelocationModel); 3783 3784 if ((RelocationModel == llvm::Reloc::ROPI || 3785 RelocationModel == llvm::Reloc::ROPI_RWPI) && 3786 types::isCXX(Input.getType()) && 3787 !Args.hasArg(options::OPT_fallow_unsupported)) 3788 D.Diag(diag::err_drv_ropi_incompatible_with_cxx); 3789 3790 if (RMName) { 3791 CmdArgs.push_back("-mrelocation-model"); 3792 CmdArgs.push_back(RMName); 3793 } 3794 if (PICLevel > 0) { 3795 CmdArgs.push_back("-pic-level"); 3796 CmdArgs.push_back(PICLevel == 1 ? "1" : "2"); 3797 if (IsPIE) 3798 CmdArgs.push_back("-pic-is-pie"); 3799 } 3800 3801 if (Arg *A = Args.getLastArg(options::OPT_meabi)) { 3802 CmdArgs.push_back("-meabi"); 3803 CmdArgs.push_back(A->getValue()); 3804 } 3805 3806 CmdArgs.push_back("-mthread-model"); 3807 if (Arg *A = Args.getLastArg(options::OPT_mthread_model)) { 3808 if (!TC.isThreadModelSupported(A->getValue())) 3809 D.Diag(diag::err_drv_invalid_thread_model_for_target) 3810 << A->getValue() << A->getAsString(Args); 3811 CmdArgs.push_back(A->getValue()); 3812 } 3813 else 3814 CmdArgs.push_back(Args.MakeArgString(TC.getThreadModel())); 3815 3816 Args.AddLastArg(CmdArgs, options::OPT_fveclib); 3817 3818 if (Args.hasFlag(options::OPT_fmerge_all_constants, 3819 options::OPT_fno_merge_all_constants, false)) 3820 CmdArgs.push_back("-fmerge-all-constants"); 3821 3822 if (Args.hasFlag(options::OPT_fno_delete_null_pointer_checks, 3823 options::OPT_fdelete_null_pointer_checks, false)) 3824 CmdArgs.push_back("-fno-delete-null-pointer-checks"); 3825 3826 // LLVM Code Generator Options. 3827 3828 if (Args.hasArg(options::OPT_frewrite_map_file) || 3829 Args.hasArg(options::OPT_frewrite_map_file_EQ)) { 3830 for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file, 3831 options::OPT_frewrite_map_file_EQ)) { 3832 StringRef Map = A->getValue(); 3833 if (!llvm::sys::fs::exists(Map)) { 3834 D.Diag(diag::err_drv_no_such_file) << Map; 3835 } else { 3836 CmdArgs.push_back("-frewrite-map-file"); 3837 CmdArgs.push_back(A->getValue()); 3838 A->claim(); 3839 } 3840 } 3841 } 3842 3843 if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) { 3844 StringRef v = A->getValue(); 3845 CmdArgs.push_back("-mllvm"); 3846 CmdArgs.push_back(Args.MakeArgString("-warn-stack-size=" + v)); 3847 A->claim(); 3848 } 3849 3850 if (!Args.hasFlag(options::OPT_fjump_tables, options::OPT_fno_jump_tables, 3851 true)) 3852 CmdArgs.push_back("-fno-jump-tables"); 3853 3854 if (Args.hasFlag(options::OPT_fprofile_sample_accurate, 3855 options::OPT_fno_profile_sample_accurate, false)) 3856 CmdArgs.push_back("-fprofile-sample-accurate"); 3857 3858 if (!Args.hasFlag(options::OPT_fpreserve_as_comments, 3859 options::OPT_fno_preserve_as_comments, true)) 3860 CmdArgs.push_back("-fno-preserve-as-comments"); 3861 3862 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) { 3863 CmdArgs.push_back("-mregparm"); 3864 CmdArgs.push_back(A->getValue()); 3865 } 3866 3867 if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return, 3868 options::OPT_freg_struct_return)) { 3869 if (TC.getArch() != llvm::Triple::x86) { 3870 D.Diag(diag::err_drv_unsupported_opt_for_target) 3871 << A->getSpelling() << RawTriple.str(); 3872 } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) { 3873 CmdArgs.push_back("-fpcc-struct-return"); 3874 } else { 3875 assert(A->getOption().matches(options::OPT_freg_struct_return)); 3876 CmdArgs.push_back("-freg-struct-return"); 3877 } 3878 } 3879 3880 if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false)) 3881 CmdArgs.push_back("-fdefault-calling-conv=stdcall"); 3882 3883 if (shouldUseFramePointer(Args, RawTriple)) 3884 CmdArgs.push_back("-mdisable-fp-elim"); 3885 if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss, 3886 options::OPT_fno_zero_initialized_in_bss)) 3887 CmdArgs.push_back("-mno-zero-initialized-in-bss"); 3888 3889 bool OFastEnabled = isOptimizationLevelFast(Args); 3890 // If -Ofast is the optimization level, then -fstrict-aliasing should be 3891 // enabled. This alias option is being used to simplify the hasFlag logic. 3892 OptSpecifier StrictAliasingAliasOption = 3893 OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing; 3894 // We turn strict aliasing off by default if we're in CL mode, since MSVC 3895 // doesn't do any TBAA. 3896 bool TBAAOnByDefault = !D.IsCLMode(); 3897 if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption, 3898 options::OPT_fno_strict_aliasing, TBAAOnByDefault)) 3899 CmdArgs.push_back("-relaxed-aliasing"); 3900 if (!Args.hasFlag(options::OPT_fstruct_path_tbaa, 3901 options::OPT_fno_struct_path_tbaa)) 3902 CmdArgs.push_back("-no-struct-path-tbaa"); 3903 if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums, 3904 false)) 3905 CmdArgs.push_back("-fstrict-enums"); 3906 if (!Args.hasFlag(options::OPT_fstrict_return, options::OPT_fno_strict_return, 3907 true)) 3908 CmdArgs.push_back("-fno-strict-return"); 3909 if (Args.hasFlag(options::OPT_fallow_editor_placeholders, 3910 options::OPT_fno_allow_editor_placeholders, false)) 3911 CmdArgs.push_back("-fallow-editor-placeholders"); 3912 if (Args.hasFlag(options::OPT_fstrict_vtable_pointers, 3913 options::OPT_fno_strict_vtable_pointers, 3914 false)) 3915 CmdArgs.push_back("-fstrict-vtable-pointers"); 3916 if (Args.hasFlag(options::OPT_fforce_emit_vtables, 3917 options::OPT_fno_force_emit_vtables, 3918 false)) 3919 CmdArgs.push_back("-fforce-emit-vtables"); 3920 if (!Args.hasFlag(options::OPT_foptimize_sibling_calls, 3921 options::OPT_fno_optimize_sibling_calls)) 3922 CmdArgs.push_back("-mdisable-tail-calls"); 3923 if (Args.hasFlag(options::OPT_fno_escaping_block_tail_calls, 3924 options::OPT_fescaping_block_tail_calls, false)) 3925 CmdArgs.push_back("-fno-escaping-block-tail-calls"); 3926 3927 Args.AddLastArg(CmdArgs, options::OPT_ffine_grained_bitfield_accesses, 3928 options::OPT_fno_fine_grained_bitfield_accesses); 3929 3930 // Handle segmented stacks. 3931 if (Args.hasArg(options::OPT_fsplit_stack)) 3932 CmdArgs.push_back("-split-stacks"); 3933 3934 RenderFloatingPointOptions(TC, D, OFastEnabled, Args, CmdArgs); 3935 3936 // Decide whether to use verbose asm. Verbose assembly is the default on 3937 // toolchains which have the integrated assembler on by default. 3938 bool IsIntegratedAssemblerDefault = TC.IsIntegratedAssemblerDefault(); 3939 if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm, 3940 IsIntegratedAssemblerDefault) || 3941 Args.hasArg(options::OPT_dA)) 3942 CmdArgs.push_back("-masm-verbose"); 3943 3944 if (!TC.useIntegratedAs()) 3945 CmdArgs.push_back("-no-integrated-as"); 3946 3947 if (Args.hasArg(options::OPT_fdebug_pass_structure)) { 3948 CmdArgs.push_back("-mdebug-pass"); 3949 CmdArgs.push_back("Structure"); 3950 } 3951 if (Args.hasArg(options::OPT_fdebug_pass_arguments)) { 3952 CmdArgs.push_back("-mdebug-pass"); 3953 CmdArgs.push_back("Arguments"); 3954 } 3955 3956 // Enable -mconstructor-aliases except on darwin, where we have to work around 3957 // a linker bug (see <rdar://problem/7651567>), and CUDA device code, where 3958 // aliases aren't supported. 3959 if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX()) 3960 CmdArgs.push_back("-mconstructor-aliases"); 3961 3962 // Darwin's kernel doesn't support guard variables; just die if we 3963 // try to use them. 3964 if (KernelOrKext && RawTriple.isOSDarwin()) 3965 CmdArgs.push_back("-fforbid-guard-variables"); 3966 3967 if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields, 3968 false)) { 3969 CmdArgs.push_back("-mms-bitfields"); 3970 } 3971 3972 if (Args.hasFlag(options::OPT_mpie_copy_relocations, 3973 options::OPT_mno_pie_copy_relocations, 3974 false)) { 3975 CmdArgs.push_back("-mpie-copy-relocations"); 3976 } 3977 3978 if (Args.hasFlag(options::OPT_fno_plt, options::OPT_fplt, false)) { 3979 CmdArgs.push_back("-fno-plt"); 3980 } 3981 3982 // -fhosted is default. 3983 // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to 3984 // use Freestanding. 3985 bool Freestanding = 3986 Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) || 3987 KernelOrKext; 3988 if (Freestanding) 3989 CmdArgs.push_back("-ffreestanding"); 3990 3991 // This is a coarse approximation of what llvm-gcc actually does, both 3992 // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more 3993 // complicated ways. 3994 bool AsynchronousUnwindTables = 3995 Args.hasFlag(options::OPT_fasynchronous_unwind_tables, 3996 options::OPT_fno_asynchronous_unwind_tables, 3997 (TC.IsUnwindTablesDefault(Args) || 3998 TC.getSanitizerArgs().needsUnwindTables()) && 3999 !Freestanding); 4000 if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables, 4001 AsynchronousUnwindTables)) 4002 CmdArgs.push_back("-munwind-tables"); 4003 4004 TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind()); 4005 4006 // FIXME: Handle -mtune=. 4007 (void)Args.hasArg(options::OPT_mtune_EQ); 4008 4009 if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) { 4010 CmdArgs.push_back("-mcode-model"); 4011 CmdArgs.push_back(A->getValue()); 4012 } 4013 4014 // Add the target cpu 4015 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false); 4016 if (!CPU.empty()) { 4017 CmdArgs.push_back("-target-cpu"); 4018 CmdArgs.push_back(Args.MakeArgString(CPU)); 4019 } 4020 4021 RenderTargetOptions(Triple, Args, KernelOrKext, CmdArgs); 4022 4023 // These two are potentially updated by AddClangCLArgs. 4024 codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo; 4025 bool EmitCodeView = false; 4026 4027 // Add clang-cl arguments. 4028 types::ID InputType = Input.getType(); 4029 if (D.IsCLMode()) 4030 AddClangCLArgs(Args, InputType, CmdArgs, &DebugInfoKind, &EmitCodeView); 4031 4032 DwarfFissionKind DwarfFission; 4033 RenderDebugOptions(TC, D, RawTriple, Args, EmitCodeView, IsWindowsMSVC, 4034 CmdArgs, DebugInfoKind, DwarfFission); 4035 4036 // Add the split debug info name to the command lines here so we 4037 // can propagate it to the backend. 4038 bool SplitDWARF = (DwarfFission != DwarfFissionKind::None) && 4039 (RawTriple.isOSLinux() || RawTriple.isOSFuchsia()) && 4040 (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) || 4041 isa<BackendJobAction>(JA)); 4042 const char *SplitDWARFOut; 4043 if (SplitDWARF) { 4044 CmdArgs.push_back("-split-dwarf-file"); 4045 SplitDWARFOut = SplitDebugName(Args, Output); 4046 CmdArgs.push_back(SplitDWARFOut); 4047 } 4048 4049 // Pass the linker version in use. 4050 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) { 4051 CmdArgs.push_back("-target-linker-version"); 4052 CmdArgs.push_back(A->getValue()); 4053 } 4054 4055 if (!shouldUseLeafFramePointer(Args, RawTriple)) 4056 CmdArgs.push_back("-momit-leaf-frame-pointer"); 4057 4058 // Explicitly error on some things we know we don't support and can't just 4059 // ignore. 4060 if (!Args.hasArg(options::OPT_fallow_unsupported)) { 4061 Arg *Unsupported; 4062 if (types::isCXX(InputType) && RawTriple.isOSDarwin() && 4063 TC.getArch() == llvm::Triple::x86) { 4064 if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) || 4065 (Unsupported = Args.getLastArg(options::OPT_mkernel))) 4066 D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386) 4067 << Unsupported->getOption().getName(); 4068 } 4069 // The faltivec option has been superseded by the maltivec option. 4070 if ((Unsupported = Args.getLastArg(options::OPT_faltivec))) 4071 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec) 4072 << Unsupported->getOption().getName() 4073 << "please use -maltivec and include altivec.h explicitly"; 4074 if ((Unsupported = Args.getLastArg(options::OPT_fno_altivec))) 4075 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec) 4076 << Unsupported->getOption().getName() << "please use -mno-altivec"; 4077 } 4078 4079 Args.AddAllArgs(CmdArgs, options::OPT_v); 4080 Args.AddLastArg(CmdArgs, options::OPT_H); 4081 if (D.CCPrintHeaders && !D.CCGenDiagnostics) { 4082 CmdArgs.push_back("-header-include-file"); 4083 CmdArgs.push_back(D.CCPrintHeadersFilename ? D.CCPrintHeadersFilename 4084 : "-"); 4085 } 4086 Args.AddLastArg(CmdArgs, options::OPT_P); 4087 Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout); 4088 4089 if (D.CCLogDiagnostics && !D.CCGenDiagnostics) { 4090 CmdArgs.push_back("-diagnostic-log-file"); 4091 CmdArgs.push_back(D.CCLogDiagnosticsFilename ? D.CCLogDiagnosticsFilename 4092 : "-"); 4093 } 4094 4095 bool UseSeparateSections = isUseSeparateSections(Triple); 4096 4097 if (Args.hasFlag(options::OPT_ffunction_sections, 4098 options::OPT_fno_function_sections, UseSeparateSections)) { 4099 CmdArgs.push_back("-ffunction-sections"); 4100 } 4101 4102 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections, 4103 UseSeparateSections)) { 4104 CmdArgs.push_back("-fdata-sections"); 4105 } 4106 4107 if (!Args.hasFlag(options::OPT_funique_section_names, 4108 options::OPT_fno_unique_section_names, true)) 4109 CmdArgs.push_back("-fno-unique-section-names"); 4110 4111 if (auto *A = Args.getLastArg( 4112 options::OPT_finstrument_functions, 4113 options::OPT_finstrument_functions_after_inlining, 4114 options::OPT_finstrument_function_entry_bare)) 4115 A->render(Args, CmdArgs); 4116 4117 // NVPTX doesn't support PGO or coverage. There's no runtime support for 4118 // sampling, overhead of call arc collection is way too high and there's no 4119 // way to collect the output. 4120 if (!Triple.isNVPTX()) 4121 addPGOAndCoverageFlags(C, D, Output, Args, CmdArgs); 4122 4123 if (auto *ABICompatArg = Args.getLastArg(options::OPT_fclang_abi_compat_EQ)) 4124 ABICompatArg->render(Args, CmdArgs); 4125 4126 // Add runtime flag for PS4 when PGO, coverage, or sanitizers are enabled. 4127 if (RawTriple.isPS4CPU() && 4128 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) { 4129 PS4cpu::addProfileRTArgs(TC, Args, CmdArgs); 4130 PS4cpu::addSanitizerArgs(TC, CmdArgs); 4131 } 4132 4133 // Pass options for controlling the default header search paths. 4134 if (Args.hasArg(options::OPT_nostdinc)) { 4135 CmdArgs.push_back("-nostdsysteminc"); 4136 CmdArgs.push_back("-nobuiltininc"); 4137 } else { 4138 if (Args.hasArg(options::OPT_nostdlibinc)) 4139 CmdArgs.push_back("-nostdsysteminc"); 4140 Args.AddLastArg(CmdArgs, options::OPT_nostdincxx); 4141 Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc); 4142 } 4143 4144 // Pass the path to compiler resource files. 4145 CmdArgs.push_back("-resource-dir"); 4146 CmdArgs.push_back(D.ResourceDir.c_str()); 4147 4148 Args.AddLastArg(CmdArgs, options::OPT_working_directory); 4149 4150 RenderARCMigrateToolOptions(D, Args, CmdArgs); 4151 4152 // Add preprocessing options like -I, -D, etc. if we are using the 4153 // preprocessor. 4154 // 4155 // FIXME: Support -fpreprocessed 4156 if (types::getPreprocessedType(InputType) != types::TY_INVALID) 4157 AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs); 4158 4159 // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes 4160 // that "The compiler can only warn and ignore the option if not recognized". 4161 // When building with ccache, it will pass -D options to clang even on 4162 // preprocessed inputs and configure concludes that -fPIC is not supported. 4163 Args.ClaimAllArgs(options::OPT_D); 4164 4165 // Manually translate -O4 to -O3; let clang reject others. 4166 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) { 4167 if (A->getOption().matches(options::OPT_O4)) { 4168 CmdArgs.push_back("-O3"); 4169 D.Diag(diag::warn_O4_is_O3); 4170 } else { 4171 A->render(Args, CmdArgs); 4172 } 4173 } 4174 4175 // Warn about ignored options to clang. 4176 for (const Arg *A : 4177 Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) { 4178 D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args); 4179 A->claim(); 4180 } 4181 4182 for (const Arg *A : 4183 Args.filtered(options::OPT_clang_ignored_legacy_options_Group)) { 4184 D.Diag(diag::warn_ignored_clang_option) << A->getAsString(Args); 4185 A->claim(); 4186 } 4187 4188 claimNoWarnArgs(Args); 4189 4190 Args.AddAllArgs(CmdArgs, options::OPT_R_Group); 4191 4192 Args.AddAllArgs(CmdArgs, options::OPT_W_Group); 4193 if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false)) 4194 CmdArgs.push_back("-pedantic"); 4195 Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors); 4196 Args.AddLastArg(CmdArgs, options::OPT_w); 4197 4198 // Fixed point flags 4199 if (Args.hasFlag(options::OPT_ffixed_point, options::OPT_fno_fixed_point, 4200 /*Default=*/false)) 4201 Args.AddLastArg(CmdArgs, options::OPT_ffixed_point); 4202 4203 // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi} 4204 // (-ansi is equivalent to -std=c89 or -std=c++98). 4205 // 4206 // If a std is supplied, only add -trigraphs if it follows the 4207 // option. 4208 bool ImplyVCPPCXXVer = false; 4209 if (Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) { 4210 if (Std->getOption().matches(options::OPT_ansi)) 4211 if (types::isCXX(InputType)) 4212 CmdArgs.push_back("-std=c++98"); 4213 else 4214 CmdArgs.push_back("-std=c89"); 4215 else 4216 Std->render(Args, CmdArgs); 4217 4218 // If -f(no-)trigraphs appears after the language standard flag, honor it. 4219 if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi, 4220 options::OPT_ftrigraphs, 4221 options::OPT_fno_trigraphs)) 4222 if (A != Std) 4223 A->render(Args, CmdArgs); 4224 } else { 4225 // Honor -std-default. 4226 // 4227 // FIXME: Clang doesn't correctly handle -std= when the input language 4228 // doesn't match. For the time being just ignore this for C++ inputs; 4229 // eventually we want to do all the standard defaulting here instead of 4230 // splitting it between the driver and clang -cc1. 4231 if (!types::isCXX(InputType)) 4232 Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=", 4233 /*Joined=*/true); 4234 else if (IsWindowsMSVC) 4235 ImplyVCPPCXXVer = true; 4236 4237 Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs, 4238 options::OPT_fno_trigraphs); 4239 } 4240 4241 // GCC's behavior for -Wwrite-strings is a bit strange: 4242 // * In C, this "warning flag" changes the types of string literals from 4243 // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning 4244 // for the discarded qualifier. 4245 // * In C++, this is just a normal warning flag. 4246 // 4247 // Implementing this warning correctly in C is hard, so we follow GCC's 4248 // behavior for now. FIXME: Directly diagnose uses of a string literal as 4249 // a non-const char* in C, rather than using this crude hack. 4250 if (!types::isCXX(InputType)) { 4251 // FIXME: This should behave just like a warning flag, and thus should also 4252 // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on. 4253 Arg *WriteStrings = 4254 Args.getLastArg(options::OPT_Wwrite_strings, 4255 options::OPT_Wno_write_strings, options::OPT_w); 4256 if (WriteStrings && 4257 WriteStrings->getOption().matches(options::OPT_Wwrite_strings)) 4258 CmdArgs.push_back("-fconst-strings"); 4259 } 4260 4261 // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active 4262 // during C++ compilation, which it is by default. GCC keeps this define even 4263 // in the presence of '-w', match this behavior bug-for-bug. 4264 if (types::isCXX(InputType) && 4265 Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated, 4266 true)) { 4267 CmdArgs.push_back("-fdeprecated-macro"); 4268 } 4269 4270 // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'. 4271 if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) { 4272 if (Asm->getOption().matches(options::OPT_fasm)) 4273 CmdArgs.push_back("-fgnu-keywords"); 4274 else 4275 CmdArgs.push_back("-fno-gnu-keywords"); 4276 } 4277 4278 if (ShouldDisableDwarfDirectory(Args, TC)) 4279 CmdArgs.push_back("-fno-dwarf-directory-asm"); 4280 4281 if (ShouldDisableAutolink(Args, TC)) 4282 CmdArgs.push_back("-fno-autolink"); 4283 4284 // Add in -fdebug-compilation-dir if necessary. 4285 addDebugCompDirArg(Args, CmdArgs); 4286 4287 addDebugPrefixMapArg(D, Args, CmdArgs); 4288 4289 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_, 4290 options::OPT_ftemplate_depth_EQ)) { 4291 CmdArgs.push_back("-ftemplate-depth"); 4292 CmdArgs.push_back(A->getValue()); 4293 } 4294 4295 if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) { 4296 CmdArgs.push_back("-foperator-arrow-depth"); 4297 CmdArgs.push_back(A->getValue()); 4298 } 4299 4300 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) { 4301 CmdArgs.push_back("-fconstexpr-depth"); 4302 CmdArgs.push_back(A->getValue()); 4303 } 4304 4305 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) { 4306 CmdArgs.push_back("-fconstexpr-steps"); 4307 CmdArgs.push_back(A->getValue()); 4308 } 4309 4310 if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) { 4311 CmdArgs.push_back("-fbracket-depth"); 4312 CmdArgs.push_back(A->getValue()); 4313 } 4314 4315 if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ, 4316 options::OPT_Wlarge_by_value_copy_def)) { 4317 if (A->getNumValues()) { 4318 StringRef bytes = A->getValue(); 4319 CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes)); 4320 } else 4321 CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value 4322 } 4323 4324 if (Args.hasArg(options::OPT_relocatable_pch)) 4325 CmdArgs.push_back("-relocatable-pch"); 4326 4327 if (const Arg *A = Args.getLastArg(options::OPT_fcf_runtime_abi_EQ)) { 4328 static const char *kCFABIs[] = { 4329 "standalone", "objc", "swift", "swift-5.0", "swift-4.2", "swift-4.1", 4330 }; 4331 4332 if (find(kCFABIs, StringRef(A->getValue())) == std::end(kCFABIs)) 4333 D.Diag(diag::err_drv_invalid_cf_runtime_abi) << A->getValue(); 4334 else 4335 A->render(Args, CmdArgs); 4336 } 4337 4338 if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) { 4339 CmdArgs.push_back("-fconstant-string-class"); 4340 CmdArgs.push_back(A->getValue()); 4341 } 4342 4343 if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) { 4344 CmdArgs.push_back("-ftabstop"); 4345 CmdArgs.push_back(A->getValue()); 4346 } 4347 4348 if (Args.hasFlag(options::OPT_fstack_size_section, 4349 options::OPT_fno_stack_size_section, RawTriple.isPS4())) 4350 CmdArgs.push_back("-fstack-size-section"); 4351 4352 CmdArgs.push_back("-ferror-limit"); 4353 if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ)) 4354 CmdArgs.push_back(A->getValue()); 4355 else 4356 CmdArgs.push_back("19"); 4357 4358 if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) { 4359 CmdArgs.push_back("-fmacro-backtrace-limit"); 4360 CmdArgs.push_back(A->getValue()); 4361 } 4362 4363 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) { 4364 CmdArgs.push_back("-ftemplate-backtrace-limit"); 4365 CmdArgs.push_back(A->getValue()); 4366 } 4367 4368 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) { 4369 CmdArgs.push_back("-fconstexpr-backtrace-limit"); 4370 CmdArgs.push_back(A->getValue()); 4371 } 4372 4373 if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) { 4374 CmdArgs.push_back("-fspell-checking-limit"); 4375 CmdArgs.push_back(A->getValue()); 4376 } 4377 4378 // Pass -fmessage-length=. 4379 CmdArgs.push_back("-fmessage-length"); 4380 if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) { 4381 CmdArgs.push_back(A->getValue()); 4382 } else { 4383 // If -fmessage-length=N was not specified, determine whether this is a 4384 // terminal and, if so, implicitly define -fmessage-length appropriately. 4385 unsigned N = llvm::sys::Process::StandardErrColumns(); 4386 CmdArgs.push_back(Args.MakeArgString(Twine(N))); 4387 } 4388 4389 // -fvisibility= and -fvisibility-ms-compat are of a piece. 4390 if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ, 4391 options::OPT_fvisibility_ms_compat)) { 4392 if (A->getOption().matches(options::OPT_fvisibility_EQ)) { 4393 CmdArgs.push_back("-fvisibility"); 4394 CmdArgs.push_back(A->getValue()); 4395 } else { 4396 assert(A->getOption().matches(options::OPT_fvisibility_ms_compat)); 4397 CmdArgs.push_back("-fvisibility"); 4398 CmdArgs.push_back("hidden"); 4399 CmdArgs.push_back("-ftype-visibility"); 4400 CmdArgs.push_back("default"); 4401 } 4402 } 4403 4404 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden); 4405 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_global_new_delete_hidden); 4406 4407 Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ); 4408 4409 // Forward -f (flag) options which we can pass directly. 4410 Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls); 4411 Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions); 4412 Args.AddLastArg(CmdArgs, options::OPT_fdigraphs, options::OPT_fno_digraphs); 4413 Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names); 4414 Args.AddLastArg(CmdArgs, options::OPT_femulated_tls, 4415 options::OPT_fno_emulated_tls); 4416 Args.AddLastArg(CmdArgs, options::OPT_fkeep_static_consts); 4417 4418 // AltiVec-like language extensions aren't relevant for assembling. 4419 if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm) 4420 Args.AddLastArg(CmdArgs, options::OPT_fzvector); 4421 4422 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree); 4423 Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type); 4424 4425 // Forward flags for OpenMP. We don't do this if the current action is an 4426 // device offloading action other than OpenMP. 4427 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ, 4428 options::OPT_fno_openmp, false) && 4429 (JA.isDeviceOffloading(Action::OFK_None) || 4430 JA.isDeviceOffloading(Action::OFK_OpenMP))) { 4431 switch (D.getOpenMPRuntime(Args)) { 4432 case Driver::OMPRT_OMP: 4433 case Driver::OMPRT_IOMP5: 4434 // Clang can generate useful OpenMP code for these two runtime libraries. 4435 CmdArgs.push_back("-fopenmp"); 4436 4437 // If no option regarding the use of TLS in OpenMP codegeneration is 4438 // given, decide a default based on the target. Otherwise rely on the 4439 // options and pass the right information to the frontend. 4440 if (!Args.hasFlag(options::OPT_fopenmp_use_tls, 4441 options::OPT_fnoopenmp_use_tls, /*Default=*/true)) 4442 CmdArgs.push_back("-fnoopenmp-use-tls"); 4443 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd, 4444 options::OPT_fno_openmp_simd); 4445 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ); 4446 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_number_of_sm_EQ); 4447 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_blocks_per_sm_EQ); 4448 if (Args.hasFlag(options::OPT_fopenmp_optimistic_collapse, 4449 options::OPT_fno_openmp_optimistic_collapse, 4450 /*Default=*/false)) 4451 CmdArgs.push_back("-fopenmp-optimistic-collapse"); 4452 4453 // When in OpenMP offloading mode with NVPTX target, forward 4454 // cuda-mode flag 4455 if (Args.hasFlag(options::OPT_fopenmp_cuda_mode, 4456 options::OPT_fno_openmp_cuda_mode, /*Default=*/false)) 4457 CmdArgs.push_back("-fopenmp-cuda-mode"); 4458 4459 // When in OpenMP offloading mode with NVPTX target, check if full runtime 4460 // is required. 4461 if (Args.hasFlag(options::OPT_fopenmp_cuda_force_full_runtime, 4462 options::OPT_fno_openmp_cuda_force_full_runtime, 4463 /*Default=*/false)) 4464 CmdArgs.push_back("-fopenmp-cuda-force-full-runtime"); 4465 break; 4466 default: 4467 // By default, if Clang doesn't know how to generate useful OpenMP code 4468 // for a specific runtime library, we just don't pass the '-fopenmp' flag 4469 // down to the actual compilation. 4470 // FIXME: It would be better to have a mode which *only* omits IR 4471 // generation based on the OpenMP support so that we get consistent 4472 // semantic analysis, etc. 4473 break; 4474 } 4475 } else { 4476 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd, 4477 options::OPT_fno_openmp_simd); 4478 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ); 4479 } 4480 4481 const SanitizerArgs &Sanitize = TC.getSanitizerArgs(); 4482 Sanitize.addArgs(TC, Args, CmdArgs, InputType); 4483 4484 const XRayArgs &XRay = TC.getXRayArgs(); 4485 XRay.addArgs(TC, Args, CmdArgs, InputType); 4486 4487 if (TC.SupportsProfiling()) 4488 Args.AddLastArg(CmdArgs, options::OPT_pg); 4489 4490 if (TC.SupportsProfiling()) 4491 Args.AddLastArg(CmdArgs, options::OPT_mfentry); 4492 4493 // -flax-vector-conversions is default. 4494 if (!Args.hasFlag(options::OPT_flax_vector_conversions, 4495 options::OPT_fno_lax_vector_conversions)) 4496 CmdArgs.push_back("-fno-lax-vector-conversions"); 4497 4498 if (Args.getLastArg(options::OPT_fapple_kext) || 4499 (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType))) 4500 CmdArgs.push_back("-fapple-kext"); 4501 4502 Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch); 4503 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info); 4504 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits); 4505 Args.AddLastArg(CmdArgs, options::OPT_ftime_report); 4506 Args.AddLastArg(CmdArgs, options::OPT_ftrapv); 4507 4508 if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) { 4509 CmdArgs.push_back("-ftrapv-handler"); 4510 CmdArgs.push_back(A->getValue()); 4511 } 4512 4513 Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ); 4514 4515 // -fno-strict-overflow implies -fwrapv if it isn't disabled, but 4516 // -fstrict-overflow won't turn off an explicitly enabled -fwrapv. 4517 if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) { 4518 if (A->getOption().matches(options::OPT_fwrapv)) 4519 CmdArgs.push_back("-fwrapv"); 4520 } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow, 4521 options::OPT_fno_strict_overflow)) { 4522 if (A->getOption().matches(options::OPT_fno_strict_overflow)) 4523 CmdArgs.push_back("-fwrapv"); 4524 } 4525 4526 if (Arg *A = Args.getLastArg(options::OPT_freroll_loops, 4527 options::OPT_fno_reroll_loops)) 4528 if (A->getOption().matches(options::OPT_freroll_loops)) 4529 CmdArgs.push_back("-freroll-loops"); 4530 4531 Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings); 4532 Args.AddLastArg(CmdArgs, options::OPT_funroll_loops, 4533 options::OPT_fno_unroll_loops); 4534 4535 Args.AddLastArg(CmdArgs, options::OPT_pthread); 4536 4537 if (Args.hasFlag(options::OPT_mspeculative_load_hardening, options::OPT_mno_speculative_load_hardening, 4538 false)) 4539 CmdArgs.push_back(Args.MakeArgString("-mspeculative-load-hardening")); 4540 4541 RenderSSPOptions(TC, Args, CmdArgs, KernelOrKext); 4542 RenderTrivialAutoVarInitOptions(D, TC, Args, CmdArgs); 4543 4544 // Translate -mstackrealign 4545 if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign, 4546 false)) 4547 CmdArgs.push_back(Args.MakeArgString("-mstackrealign")); 4548 4549 if (Args.hasArg(options::OPT_mstack_alignment)) { 4550 StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment); 4551 CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment)); 4552 } 4553 4554 if (Args.hasArg(options::OPT_mstack_probe_size)) { 4555 StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size); 4556 4557 if (!Size.empty()) 4558 CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size)); 4559 else 4560 CmdArgs.push_back("-mstack-probe-size=0"); 4561 } 4562 4563 if (!Args.hasFlag(options::OPT_mstack_arg_probe, 4564 options::OPT_mno_stack_arg_probe, true)) 4565 CmdArgs.push_back(Args.MakeArgString("-mno-stack-arg-probe")); 4566 4567 if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it, 4568 options::OPT_mno_restrict_it)) { 4569 if (A->getOption().matches(options::OPT_mrestrict_it)) { 4570 CmdArgs.push_back("-mllvm"); 4571 CmdArgs.push_back("-arm-restrict-it"); 4572 } else { 4573 CmdArgs.push_back("-mllvm"); 4574 CmdArgs.push_back("-arm-no-restrict-it"); 4575 } 4576 } else if (Triple.isOSWindows() && 4577 (Triple.getArch() == llvm::Triple::arm || 4578 Triple.getArch() == llvm::Triple::thumb)) { 4579 // Windows on ARM expects restricted IT blocks 4580 CmdArgs.push_back("-mllvm"); 4581 CmdArgs.push_back("-arm-restrict-it"); 4582 } 4583 4584 // Forward -cl options to -cc1 4585 RenderOpenCLOptions(Args, CmdArgs); 4586 4587 if (Arg *A = Args.getLastArg(options::OPT_fcf_protection_EQ)) { 4588 CmdArgs.push_back( 4589 Args.MakeArgString(Twine("-fcf-protection=") + A->getValue())); 4590 } 4591 4592 // Forward -f options with positive and negative forms; we translate 4593 // these by hand. 4594 if (Arg *A = getLastProfileSampleUseArg(Args)) { 4595 StringRef fname = A->getValue(); 4596 if (!llvm::sys::fs::exists(fname)) 4597 D.Diag(diag::err_drv_no_such_file) << fname; 4598 else 4599 A->render(Args, CmdArgs); 4600 } 4601 Args.AddLastArg(CmdArgs, options::OPT_fprofile_remapping_file_EQ); 4602 4603 RenderBuiltinOptions(TC, RawTriple, Args, CmdArgs); 4604 4605 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new, 4606 options::OPT_fno_assume_sane_operator_new)) 4607 CmdArgs.push_back("-fno-assume-sane-operator-new"); 4608 4609 // -fblocks=0 is default. 4610 if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks, 4611 TC.IsBlocksDefault()) || 4612 (Args.hasArg(options::OPT_fgnu_runtime) && 4613 Args.hasArg(options::OPT_fobjc_nonfragile_abi) && 4614 !Args.hasArg(options::OPT_fno_blocks))) { 4615 CmdArgs.push_back("-fblocks"); 4616 4617 if (!Args.hasArg(options::OPT_fgnu_runtime) && !TC.hasBlocksRuntime()) 4618 CmdArgs.push_back("-fblocks-runtime-optional"); 4619 } 4620 4621 // -fencode-extended-block-signature=1 is default. 4622 if (TC.IsEncodeExtendedBlockSignatureDefault()) 4623 CmdArgs.push_back("-fencode-extended-block-signature"); 4624 4625 if (Args.hasFlag(options::OPT_fcoroutines_ts, options::OPT_fno_coroutines_ts, 4626 false) && 4627 types::isCXX(InputType)) { 4628 CmdArgs.push_back("-fcoroutines-ts"); 4629 } 4630 4631 Args.AddLastArg(CmdArgs, options::OPT_fdouble_square_bracket_attributes, 4632 options::OPT_fno_double_square_bracket_attributes); 4633 4634 bool HaveModules = false; 4635 RenderModulesOptions(C, D, Args, Input, Output, CmdArgs, HaveModules); 4636 4637 // -faccess-control is default. 4638 if (Args.hasFlag(options::OPT_fno_access_control, 4639 options::OPT_faccess_control, false)) 4640 CmdArgs.push_back("-fno-access-control"); 4641 4642 // -felide-constructors is the default. 4643 if (Args.hasFlag(options::OPT_fno_elide_constructors, 4644 options::OPT_felide_constructors, false)) 4645 CmdArgs.push_back("-fno-elide-constructors"); 4646 4647 ToolChain::RTTIMode RTTIMode = TC.getRTTIMode(); 4648 4649 if (KernelOrKext || (types::isCXX(InputType) && 4650 (RTTIMode == ToolChain::RM_Disabled))) 4651 CmdArgs.push_back("-fno-rtti"); 4652 4653 // -fshort-enums=0 is default for all architectures except Hexagon. 4654 if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums, 4655 TC.getArch() == llvm::Triple::hexagon)) 4656 CmdArgs.push_back("-fshort-enums"); 4657 4658 RenderCharacterOptions(Args, AuxTriple ? *AuxTriple : RawTriple, CmdArgs); 4659 4660 // -fuse-cxa-atexit is default. 4661 if (!Args.hasFlag( 4662 options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit, 4663 !RawTriple.isOSWindows() && 4664 RawTriple.getOS() != llvm::Triple::Solaris && 4665 TC.getArch() != llvm::Triple::xcore && 4666 ((RawTriple.getVendor() != llvm::Triple::MipsTechnologies) || 4667 RawTriple.hasEnvironment())) || 4668 KernelOrKext) 4669 CmdArgs.push_back("-fno-use-cxa-atexit"); 4670 4671 if (Args.hasFlag(options::OPT_fregister_global_dtors_with_atexit, 4672 options::OPT_fno_register_global_dtors_with_atexit, 4673 RawTriple.isOSDarwin() && !KernelOrKext)) 4674 CmdArgs.push_back("-fregister-global-dtors-with-atexit"); 4675 4676 // -fms-extensions=0 is default. 4677 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions, 4678 IsWindowsMSVC)) 4679 CmdArgs.push_back("-fms-extensions"); 4680 4681 // -fno-use-line-directives is default. 4682 if (Args.hasFlag(options::OPT_fuse_line_directives, 4683 options::OPT_fno_use_line_directives, false)) 4684 CmdArgs.push_back("-fuse-line-directives"); 4685 4686 // -fms-compatibility=0 is default. 4687 if (Args.hasFlag(options::OPT_fms_compatibility, 4688 options::OPT_fno_ms_compatibility, 4689 (IsWindowsMSVC && 4690 Args.hasFlag(options::OPT_fms_extensions, 4691 options::OPT_fno_ms_extensions, true)))) 4692 CmdArgs.push_back("-fms-compatibility"); 4693 4694 VersionTuple MSVT = TC.computeMSVCVersion(&D, Args); 4695 if (!MSVT.empty()) 4696 CmdArgs.push_back( 4697 Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString())); 4698 4699 bool IsMSVC2015Compatible = MSVT.getMajor() >= 19; 4700 if (ImplyVCPPCXXVer) { 4701 StringRef LanguageStandard; 4702 if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) { 4703 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue()) 4704 .Case("c++14", "-std=c++14") 4705 .Case("c++17", "-std=c++17") 4706 .Case("c++latest", "-std=c++2a") 4707 .Default(""); 4708 if (LanguageStandard.empty()) 4709 D.Diag(clang::diag::warn_drv_unused_argument) 4710 << StdArg->getAsString(Args); 4711 } 4712 4713 if (LanguageStandard.empty()) { 4714 if (IsMSVC2015Compatible) 4715 LanguageStandard = "-std=c++14"; 4716 else 4717 LanguageStandard = "-std=c++11"; 4718 } 4719 4720 CmdArgs.push_back(LanguageStandard.data()); 4721 } 4722 4723 // -fno-borland-extensions is default. 4724 if (Args.hasFlag(options::OPT_fborland_extensions, 4725 options::OPT_fno_borland_extensions, false)) 4726 CmdArgs.push_back("-fborland-extensions"); 4727 4728 // -fno-declspec is default, except for PS4. 4729 if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec, 4730 RawTriple.isPS4())) 4731 CmdArgs.push_back("-fdeclspec"); 4732 else if (Args.hasArg(options::OPT_fno_declspec)) 4733 CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec. 4734 4735 // -fthreadsafe-static is default, except for MSVC compatibility versions less 4736 // than 19. 4737 if (!Args.hasFlag(options::OPT_fthreadsafe_statics, 4738 options::OPT_fno_threadsafe_statics, 4739 !IsWindowsMSVC || IsMSVC2015Compatible)) 4740 CmdArgs.push_back("-fno-threadsafe-statics"); 4741 4742 // -fno-delayed-template-parsing is default, except when targeting MSVC. 4743 // Many old Windows SDK versions require this to parse. 4744 // FIXME: MSVC introduced /Zc:twoPhase- to disable this behavior in their 4745 // compiler. We should be able to disable this by default at some point. 4746 if (Args.hasFlag(options::OPT_fdelayed_template_parsing, 4747 options::OPT_fno_delayed_template_parsing, IsWindowsMSVC)) 4748 CmdArgs.push_back("-fdelayed-template-parsing"); 4749 4750 // -fgnu-keywords default varies depending on language; only pass if 4751 // specified. 4752 if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords, 4753 options::OPT_fno_gnu_keywords)) 4754 A->render(Args, CmdArgs); 4755 4756 if (Args.hasFlag(options::OPT_fgnu89_inline, options::OPT_fno_gnu89_inline, 4757 false)) 4758 CmdArgs.push_back("-fgnu89-inline"); 4759 4760 if (Args.hasArg(options::OPT_fno_inline)) 4761 CmdArgs.push_back("-fno-inline"); 4762 4763 if (Arg* InlineArg = Args.getLastArg(options::OPT_finline_functions, 4764 options::OPT_finline_hint_functions, 4765 options::OPT_fno_inline_functions)) 4766 InlineArg->render(Args, CmdArgs); 4767 4768 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_new_pass_manager, 4769 options::OPT_fno_experimental_new_pass_manager); 4770 4771 ObjCRuntime Runtime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind); 4772 RenderObjCOptions(TC, D, RawTriple, Args, Runtime, rewriteKind != RK_None, 4773 Input, CmdArgs); 4774 4775 if (Args.hasFlag(options::OPT_fapplication_extension, 4776 options::OPT_fno_application_extension, false)) 4777 CmdArgs.push_back("-fapplication-extension"); 4778 4779 // Handle GCC-style exception args. 4780 if (!C.getDriver().IsCLMode()) 4781 addExceptionArgs(Args, InputType, TC, KernelOrKext, Runtime, CmdArgs); 4782 4783 // Handle exception personalities 4784 Arg *A = Args.getLastArg(options::OPT_fsjlj_exceptions, 4785 options::OPT_fseh_exceptions, 4786 options::OPT_fdwarf_exceptions); 4787 if (A) { 4788 const Option &Opt = A->getOption(); 4789 if (Opt.matches(options::OPT_fsjlj_exceptions)) 4790 CmdArgs.push_back("-fsjlj-exceptions"); 4791 if (Opt.matches(options::OPT_fseh_exceptions)) 4792 CmdArgs.push_back("-fseh-exceptions"); 4793 if (Opt.matches(options::OPT_fdwarf_exceptions)) 4794 CmdArgs.push_back("-fdwarf-exceptions"); 4795 } else { 4796 switch (TC.GetExceptionModel(Args)) { 4797 default: 4798 break; 4799 case llvm::ExceptionHandling::DwarfCFI: 4800 CmdArgs.push_back("-fdwarf-exceptions"); 4801 break; 4802 case llvm::ExceptionHandling::SjLj: 4803 CmdArgs.push_back("-fsjlj-exceptions"); 4804 break; 4805 case llvm::ExceptionHandling::WinEH: 4806 CmdArgs.push_back("-fseh-exceptions"); 4807 break; 4808 } 4809 } 4810 4811 // C++ "sane" operator new. 4812 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new, 4813 options::OPT_fno_assume_sane_operator_new)) 4814 CmdArgs.push_back("-fno-assume-sane-operator-new"); 4815 4816 // -frelaxed-template-template-args is off by default, as it is a severe 4817 // breaking change until a corresponding change to template partial ordering 4818 // is provided. 4819 if (Args.hasFlag(options::OPT_frelaxed_template_template_args, 4820 options::OPT_fno_relaxed_template_template_args, false)) 4821 CmdArgs.push_back("-frelaxed-template-template-args"); 4822 4823 // -fsized-deallocation is off by default, as it is an ABI-breaking change for 4824 // most platforms. 4825 if (Args.hasFlag(options::OPT_fsized_deallocation, 4826 options::OPT_fno_sized_deallocation, false)) 4827 CmdArgs.push_back("-fsized-deallocation"); 4828 4829 // -faligned-allocation is on by default in C++17 onwards and otherwise off 4830 // by default. 4831 if (Arg *A = Args.getLastArg(options::OPT_faligned_allocation, 4832 options::OPT_fno_aligned_allocation, 4833 options::OPT_faligned_new_EQ)) { 4834 if (A->getOption().matches(options::OPT_fno_aligned_allocation)) 4835 CmdArgs.push_back("-fno-aligned-allocation"); 4836 else 4837 CmdArgs.push_back("-faligned-allocation"); 4838 } 4839 4840 // The default new alignment can be specified using a dedicated option or via 4841 // a GCC-compatible option that also turns on aligned allocation. 4842 if (Arg *A = Args.getLastArg(options::OPT_fnew_alignment_EQ, 4843 options::OPT_faligned_new_EQ)) 4844 CmdArgs.push_back( 4845 Args.MakeArgString(Twine("-fnew-alignment=") + A->getValue())); 4846 4847 // -fconstant-cfstrings is default, and may be subject to argument translation 4848 // on Darwin. 4849 if (!Args.hasFlag(options::OPT_fconstant_cfstrings, 4850 options::OPT_fno_constant_cfstrings) || 4851 !Args.hasFlag(options::OPT_mconstant_cfstrings, 4852 options::OPT_mno_constant_cfstrings)) 4853 CmdArgs.push_back("-fno-constant-cfstrings"); 4854 4855 // -fno-pascal-strings is default, only pass non-default. 4856 if (Args.hasFlag(options::OPT_fpascal_strings, 4857 options::OPT_fno_pascal_strings, false)) 4858 CmdArgs.push_back("-fpascal-strings"); 4859 4860 // Honor -fpack-struct= and -fpack-struct, if given. Note that 4861 // -fno-pack-struct doesn't apply to -fpack-struct=. 4862 if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) { 4863 std::string PackStructStr = "-fpack-struct="; 4864 PackStructStr += A->getValue(); 4865 CmdArgs.push_back(Args.MakeArgString(PackStructStr)); 4866 } else if (Args.hasFlag(options::OPT_fpack_struct, 4867 options::OPT_fno_pack_struct, false)) { 4868 CmdArgs.push_back("-fpack-struct=1"); 4869 } 4870 4871 // Handle -fmax-type-align=N and -fno-type-align 4872 bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align); 4873 if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) { 4874 if (!SkipMaxTypeAlign) { 4875 std::string MaxTypeAlignStr = "-fmax-type-align="; 4876 MaxTypeAlignStr += A->getValue(); 4877 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr)); 4878 } 4879 } else if (RawTriple.isOSDarwin()) { 4880 if (!SkipMaxTypeAlign) { 4881 std::string MaxTypeAlignStr = "-fmax-type-align=16"; 4882 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr)); 4883 } 4884 } 4885 4886 if (!Args.hasFlag(options::OPT_Qy, options::OPT_Qn, true)) 4887 CmdArgs.push_back("-Qn"); 4888 4889 // -fcommon is the default unless compiling kernel code or the target says so 4890 bool NoCommonDefault = KernelOrKext || isNoCommonDefault(RawTriple); 4891 if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common, 4892 !NoCommonDefault)) 4893 CmdArgs.push_back("-fno-common"); 4894 4895 // -fsigned-bitfields is default, and clang doesn't yet support 4896 // -funsigned-bitfields. 4897 if (!Args.hasFlag(options::OPT_fsigned_bitfields, 4898 options::OPT_funsigned_bitfields)) 4899 D.Diag(diag::warn_drv_clang_unsupported) 4900 << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args); 4901 4902 // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope. 4903 if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope)) 4904 D.Diag(diag::err_drv_clang_unsupported) 4905 << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args); 4906 4907 // -finput_charset=UTF-8 is default. Reject others 4908 if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) { 4909 StringRef value = inputCharset->getValue(); 4910 if (!value.equals_lower("utf-8")) 4911 D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args) 4912 << value; 4913 } 4914 4915 // -fexec_charset=UTF-8 is default. Reject others 4916 if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) { 4917 StringRef value = execCharset->getValue(); 4918 if (!value.equals_lower("utf-8")) 4919 D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args) 4920 << value; 4921 } 4922 4923 RenderDiagnosticsOptions(D, Args, CmdArgs); 4924 4925 // -fno-asm-blocks is default. 4926 if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks, 4927 false)) 4928 CmdArgs.push_back("-fasm-blocks"); 4929 4930 // -fgnu-inline-asm is default. 4931 if (!Args.hasFlag(options::OPT_fgnu_inline_asm, 4932 options::OPT_fno_gnu_inline_asm, true)) 4933 CmdArgs.push_back("-fno-gnu-inline-asm"); 4934 4935 // Enable vectorization per default according to the optimization level 4936 // selected. For optimization levels that want vectorization we use the alias 4937 // option to simplify the hasFlag logic. 4938 bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false); 4939 OptSpecifier VectorizeAliasOption = 4940 EnableVec ? options::OPT_O_Group : options::OPT_fvectorize; 4941 if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption, 4942 options::OPT_fno_vectorize, EnableVec)) 4943 CmdArgs.push_back("-vectorize-loops"); 4944 4945 // -fslp-vectorize is enabled based on the optimization level selected. 4946 bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true); 4947 OptSpecifier SLPVectAliasOption = 4948 EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize; 4949 if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption, 4950 options::OPT_fno_slp_vectorize, EnableSLPVec)) 4951 CmdArgs.push_back("-vectorize-slp"); 4952 4953 ParseMPreferVectorWidth(D, Args, CmdArgs); 4954 4955 if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ)) 4956 A->render(Args, CmdArgs); 4957 4958 if (Arg *A = Args.getLastArg( 4959 options::OPT_fsanitize_undefined_strip_path_components_EQ)) 4960 A->render(Args, CmdArgs); 4961 4962 // -fdollars-in-identifiers default varies depending on platform and 4963 // language; only pass if specified. 4964 if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers, 4965 options::OPT_fno_dollars_in_identifiers)) { 4966 if (A->getOption().matches(options::OPT_fdollars_in_identifiers)) 4967 CmdArgs.push_back("-fdollars-in-identifiers"); 4968 else 4969 CmdArgs.push_back("-fno-dollars-in-identifiers"); 4970 } 4971 4972 // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for 4973 // practical purposes. 4974 if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time, 4975 options::OPT_fno_unit_at_a_time)) { 4976 if (A->getOption().matches(options::OPT_fno_unit_at_a_time)) 4977 D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args); 4978 } 4979 4980 if (Args.hasFlag(options::OPT_fapple_pragma_pack, 4981 options::OPT_fno_apple_pragma_pack, false)) 4982 CmdArgs.push_back("-fapple-pragma-pack"); 4983 4984 if (Args.hasFlag(options::OPT_fsave_optimization_record, 4985 options::OPT_foptimization_record_file_EQ, 4986 options::OPT_fno_save_optimization_record, false)) { 4987 CmdArgs.push_back("-opt-record-file"); 4988 4989 const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ); 4990 if (A) { 4991 CmdArgs.push_back(A->getValue()); 4992 } else { 4993 SmallString<128> F; 4994 4995 if (Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) { 4996 if (Arg *FinalOutput = Args.getLastArg(options::OPT_o)) 4997 F = FinalOutput->getValue(); 4998 } 4999 5000 if (F.empty()) { 5001 // Use the input filename. 5002 F = llvm::sys::path::stem(Input.getBaseInput()); 5003 5004 // If we're compiling for an offload architecture (i.e. a CUDA device), 5005 // we need to make the file name for the device compilation different 5006 // from the host compilation. 5007 if (!JA.isDeviceOffloading(Action::OFK_None) && 5008 !JA.isDeviceOffloading(Action::OFK_Host)) { 5009 llvm::sys::path::replace_extension(F, ""); 5010 F += Action::GetOffloadingFileNamePrefix(JA.getOffloadingDeviceKind(), 5011 Triple.normalize()); 5012 F += "-"; 5013 F += JA.getOffloadingArch(); 5014 } 5015 } 5016 5017 llvm::sys::path::replace_extension(F, "opt.yaml"); 5018 CmdArgs.push_back(Args.MakeArgString(F)); 5019 } 5020 } 5021 5022 bool RewriteImports = Args.hasFlag(options::OPT_frewrite_imports, 5023 options::OPT_fno_rewrite_imports, false); 5024 if (RewriteImports) 5025 CmdArgs.push_back("-frewrite-imports"); 5026 5027 // Enable rewrite includes if the user's asked for it or if we're generating 5028 // diagnostics. 5029 // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be 5030 // nice to enable this when doing a crashdump for modules as well. 5031 if (Args.hasFlag(options::OPT_frewrite_includes, 5032 options::OPT_fno_rewrite_includes, false) || 5033 (C.isForDiagnostics() && !HaveModules)) 5034 CmdArgs.push_back("-frewrite-includes"); 5035 5036 // Only allow -traditional or -traditional-cpp outside in preprocessing modes. 5037 if (Arg *A = Args.getLastArg(options::OPT_traditional, 5038 options::OPT_traditional_cpp)) { 5039 if (isa<PreprocessJobAction>(JA)) 5040 CmdArgs.push_back("-traditional-cpp"); 5041 else 5042 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args); 5043 } 5044 5045 Args.AddLastArg(CmdArgs, options::OPT_dM); 5046 Args.AddLastArg(CmdArgs, options::OPT_dD); 5047 5048 // Handle serialized diagnostics. 5049 if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) { 5050 CmdArgs.push_back("-serialize-diagnostic-file"); 5051 CmdArgs.push_back(Args.MakeArgString(A->getValue())); 5052 } 5053 5054 if (Args.hasArg(options::OPT_fretain_comments_from_system_headers)) 5055 CmdArgs.push_back("-fretain-comments-from-system-headers"); 5056 5057 // Forward -fcomment-block-commands to -cc1. 5058 Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands); 5059 // Forward -fparse-all-comments to -cc1. 5060 Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments); 5061 5062 // Turn -fplugin=name.so into -load name.so 5063 for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) { 5064 CmdArgs.push_back("-load"); 5065 CmdArgs.push_back(A->getValue()); 5066 A->claim(); 5067 } 5068 5069 // Setup statistics file output. 5070 SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D); 5071 if (!StatsFile.empty()) 5072 CmdArgs.push_back(Args.MakeArgString(Twine("-stats-file=") + StatsFile)); 5073 5074 // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option 5075 // parser. 5076 // -finclude-default-header flag is for preprocessor, 5077 // do not pass it to other cc1 commands when save-temps is enabled 5078 if (C.getDriver().isSaveTempsEnabled() && 5079 !isa<PreprocessJobAction>(JA)) { 5080 for (auto Arg : Args.filtered(options::OPT_Xclang)) { 5081 Arg->claim(); 5082 if (StringRef(Arg->getValue()) != "-finclude-default-header") 5083 CmdArgs.push_back(Arg->getValue()); 5084 } 5085 } 5086 else { 5087 Args.AddAllArgValues(CmdArgs, options::OPT_Xclang); 5088 } 5089 for (const Arg *A : Args.filtered(options::OPT_mllvm)) { 5090 A->claim(); 5091 5092 // We translate this by hand to the -cc1 argument, since nightly test uses 5093 // it and developers have been trained to spell it with -mllvm. Both 5094 // spellings are now deprecated and should be removed. 5095 if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") { 5096 CmdArgs.push_back("-disable-llvm-optzns"); 5097 } else { 5098 A->render(Args, CmdArgs); 5099 } 5100 } 5101 5102 // With -save-temps, we want to save the unoptimized bitcode output from the 5103 // CompileJobAction, use -disable-llvm-passes to get pristine IR generated 5104 // by the frontend. 5105 // When -fembed-bitcode is enabled, optimized bitcode is emitted because it 5106 // has slightly different breakdown between stages. 5107 // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of 5108 // pristine IR generated by the frontend. Ideally, a new compile action should 5109 // be added so both IR can be captured. 5110 if (C.getDriver().isSaveTempsEnabled() && 5111 !(C.getDriver().embedBitcodeInObject() && !C.getDriver().isUsingLTO()) && 5112 isa<CompileJobAction>(JA)) 5113 CmdArgs.push_back("-disable-llvm-passes"); 5114 5115 if (Output.getType() == types::TY_Dependencies) { 5116 // Handled with other dependency code. 5117 } else if (Output.isFilename()) { 5118 CmdArgs.push_back("-o"); 5119 CmdArgs.push_back(Output.getFilename()); 5120 } else { 5121 assert(Output.isNothing() && "Invalid output."); 5122 } 5123 5124 addDashXForInput(Args, Input, CmdArgs); 5125 5126 ArrayRef<InputInfo> FrontendInputs = Input; 5127 if (IsHeaderModulePrecompile) 5128 FrontendInputs = ModuleHeaderInputs; 5129 else if (Input.isNothing()) 5130 FrontendInputs = {}; 5131 5132 for (const InputInfo &Input : FrontendInputs) { 5133 if (Input.isFilename()) 5134 CmdArgs.push_back(Input.getFilename()); 5135 else 5136 Input.getInputArg().renderAsInput(Args, CmdArgs); 5137 } 5138 5139 Args.AddAllArgs(CmdArgs, options::OPT_undef); 5140 5141 const char *Exec = D.getClangProgramPath(); 5142 5143 // Optionally embed the -cc1 level arguments into the debug info or a 5144 // section, for build analysis. 5145 // Also record command line arguments into the debug info if 5146 // -grecord-gcc-switches options is set on. 5147 // By default, -gno-record-gcc-switches is set on and no recording. 5148 auto GRecordSwitches = 5149 Args.hasFlag(options::OPT_grecord_command_line, 5150 options::OPT_gno_record_command_line, false); 5151 auto FRecordSwitches = 5152 Args.hasFlag(options::OPT_frecord_command_line, 5153 options::OPT_fno_record_command_line, false); 5154 if (FRecordSwitches && !Triple.isOSBinFormatELF()) 5155 D.Diag(diag::err_drv_unsupported_opt_for_target) 5156 << Args.getLastArg(options::OPT_frecord_command_line)->getAsString(Args) 5157 << TripleStr; 5158 if (TC.UseDwarfDebugFlags() || GRecordSwitches || FRecordSwitches) { 5159 ArgStringList OriginalArgs; 5160 for (const auto &Arg : Args) 5161 Arg->render(Args, OriginalArgs); 5162 5163 SmallString<256> Flags; 5164 Flags += Exec; 5165 for (const char *OriginalArg : OriginalArgs) { 5166 SmallString<128> EscapedArg; 5167 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg); 5168 Flags += " "; 5169 Flags += EscapedArg; 5170 } 5171 auto FlagsArgString = Args.MakeArgString(Flags); 5172 if (TC.UseDwarfDebugFlags() || GRecordSwitches) { 5173 CmdArgs.push_back("-dwarf-debug-flags"); 5174 CmdArgs.push_back(FlagsArgString); 5175 } 5176 if (FRecordSwitches) { 5177 CmdArgs.push_back("-record-command-line"); 5178 CmdArgs.push_back(FlagsArgString); 5179 } 5180 } 5181 5182 // Host-side cuda compilation receives all device-side outputs in a single 5183 // fatbin as Inputs[1]. Include the binary with -fcuda-include-gpubinary. 5184 if ((IsCuda || IsHIP) && CudaDeviceInput) { 5185 CmdArgs.push_back("-fcuda-include-gpubinary"); 5186 CmdArgs.push_back(CudaDeviceInput->getFilename()); 5187 if (Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false)) 5188 CmdArgs.push_back("-fgpu-rdc"); 5189 } 5190 5191 if (IsCuda) { 5192 if (Args.hasFlag(options::OPT_fcuda_short_ptr, 5193 options::OPT_fno_cuda_short_ptr, false)) 5194 CmdArgs.push_back("-fcuda-short-ptr"); 5195 } 5196 5197 // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path 5198 // to specify the result of the compile phase on the host, so the meaningful 5199 // device declarations can be identified. Also, -fopenmp-is-device is passed 5200 // along to tell the frontend that it is generating code for a device, so that 5201 // only the relevant declarations are emitted. 5202 if (IsOpenMPDevice) { 5203 CmdArgs.push_back("-fopenmp-is-device"); 5204 if (OpenMPDeviceInput) { 5205 CmdArgs.push_back("-fopenmp-host-ir-file-path"); 5206 CmdArgs.push_back(Args.MakeArgString(OpenMPDeviceInput->getFilename())); 5207 } 5208 } 5209 5210 // For all the host OpenMP offloading compile jobs we need to pass the targets 5211 // information using -fopenmp-targets= option. 5212 if (JA.isHostOffloading(Action::OFK_OpenMP)) { 5213 SmallString<128> TargetInfo("-fopenmp-targets="); 5214 5215 Arg *Tgts = Args.getLastArg(options::OPT_fopenmp_targets_EQ); 5216 assert(Tgts && Tgts->getNumValues() && 5217 "OpenMP offloading has to have targets specified."); 5218 for (unsigned i = 0; i < Tgts->getNumValues(); ++i) { 5219 if (i) 5220 TargetInfo += ','; 5221 // We need to get the string from the triple because it may be not exactly 5222 // the same as the one we get directly from the arguments. 5223 llvm::Triple T(Tgts->getValue(i)); 5224 TargetInfo += T.getTriple(); 5225 } 5226 CmdArgs.push_back(Args.MakeArgString(TargetInfo.str())); 5227 } 5228 5229 bool WholeProgramVTables = 5230 Args.hasFlag(options::OPT_fwhole_program_vtables, 5231 options::OPT_fno_whole_program_vtables, false); 5232 if (WholeProgramVTables) { 5233 if (!D.isUsingLTO()) 5234 D.Diag(diag::err_drv_argument_only_allowed_with) 5235 << "-fwhole-program-vtables" 5236 << "-flto"; 5237 CmdArgs.push_back("-fwhole-program-vtables"); 5238 } 5239 5240 bool RequiresSplitLTOUnit = WholeProgramVTables || Sanitize.needsLTO(); 5241 bool SplitLTOUnit = 5242 Args.hasFlag(options::OPT_fsplit_lto_unit, 5243 options::OPT_fno_split_lto_unit, RequiresSplitLTOUnit); 5244 if (RequiresSplitLTOUnit && !SplitLTOUnit) 5245 D.Diag(diag::err_drv_argument_not_allowed_with) 5246 << "-fno-split-lto-unit" 5247 << (WholeProgramVTables ? "-fwhole-program-vtables" : "-fsanitize=cfi"); 5248 if (SplitLTOUnit) 5249 CmdArgs.push_back("-fsplit-lto-unit"); 5250 5251 if (Arg *A = Args.getLastArg(options::OPT_fexperimental_isel, 5252 options::OPT_fno_experimental_isel)) { 5253 CmdArgs.push_back("-mllvm"); 5254 if (A->getOption().matches(options::OPT_fexperimental_isel)) { 5255 CmdArgs.push_back("-global-isel=1"); 5256 5257 // GISel is on by default on AArch64 -O0, so don't bother adding 5258 // the fallback remarks for it. Other combinations will add a warning of 5259 // some kind. 5260 bool IsArchSupported = Triple.getArch() == llvm::Triple::aarch64; 5261 bool IsOptLevelSupported = false; 5262 5263 Arg *A = Args.getLastArg(options::OPT_O_Group); 5264 if (Triple.getArch() == llvm::Triple::aarch64) { 5265 if (!A || A->getOption().matches(options::OPT_O0)) 5266 IsOptLevelSupported = true; 5267 } 5268 if (!IsArchSupported || !IsOptLevelSupported) { 5269 CmdArgs.push_back("-mllvm"); 5270 CmdArgs.push_back("-global-isel-abort=2"); 5271 5272 if (!IsArchSupported) 5273 D.Diag(diag::warn_drv_experimental_isel_incomplete) << Triple.getArchName(); 5274 else 5275 D.Diag(diag::warn_drv_experimental_isel_incomplete_opt); 5276 } 5277 } else { 5278 CmdArgs.push_back("-global-isel=0"); 5279 } 5280 } 5281 5282 if (Arg *A = Args.getLastArg(options::OPT_fforce_enable_int128, 5283 options::OPT_fno_force_enable_int128)) { 5284 if (A->getOption().matches(options::OPT_fforce_enable_int128)) 5285 CmdArgs.push_back("-fforce-enable-int128"); 5286 } 5287 5288 if (Args.hasFlag(options::OPT_fcomplete_member_pointers, 5289 options::OPT_fno_complete_member_pointers, false)) 5290 CmdArgs.push_back("-fcomplete-member-pointers"); 5291 5292 if (!Args.hasFlag(options::OPT_fcxx_static_destructors, 5293 options::OPT_fno_cxx_static_destructors, true)) 5294 CmdArgs.push_back("-fno-c++-static-destructors"); 5295 5296 if (Arg *A = Args.getLastArg(options::OPT_moutline, 5297 options::OPT_mno_outline)) { 5298 if (A->getOption().matches(options::OPT_moutline)) { 5299 // We only support -moutline in AArch64 right now. If we're not compiling 5300 // for AArch64, emit a warning and ignore the flag. Otherwise, add the 5301 // proper mllvm flags. 5302 if (Triple.getArch() != llvm::Triple::aarch64) { 5303 D.Diag(diag::warn_drv_moutline_unsupported_opt) << Triple.getArchName(); 5304 } else { 5305 CmdArgs.push_back("-mllvm"); 5306 CmdArgs.push_back("-enable-machine-outliner"); 5307 } 5308 } else { 5309 // Disable all outlining behaviour. 5310 CmdArgs.push_back("-mllvm"); 5311 CmdArgs.push_back("-enable-machine-outliner=never"); 5312 } 5313 } 5314 5315 if (Args.hasFlag(options::OPT_faddrsig, options::OPT_fno_addrsig, 5316 (TC.getTriple().isOSBinFormatELF() || 5317 TC.getTriple().isOSBinFormatCOFF()) && 5318 !TC.getTriple().isPS4() && 5319 !TC.getTriple().isOSNetBSD() && 5320 !Distro(D.getVFS()).IsGentoo() && 5321 !TC.getTriple().isAndroid() && 5322 TC.useIntegratedAs())) 5323 CmdArgs.push_back("-faddrsig"); 5324 5325 // Finally add the compile command to the compilation. 5326 if (Args.hasArg(options::OPT__SLASH_fallback) && 5327 Output.getType() == types::TY_Object && 5328 (InputType == types::TY_C || InputType == types::TY_CXX)) { 5329 auto CLCommand = 5330 getCLFallback()->GetCommand(C, JA, Output, Inputs, Args, LinkingOutput); 5331 C.addCommand(llvm::make_unique<FallbackCommand>( 5332 JA, *this, Exec, CmdArgs, Inputs, std::move(CLCommand))); 5333 } else if (Args.hasArg(options::OPT__SLASH_fallback) && 5334 isa<PrecompileJobAction>(JA)) { 5335 // In /fallback builds, run the main compilation even if the pch generation 5336 // fails, so that the main compilation's fallback to cl.exe runs. 5337 C.addCommand(llvm::make_unique<ForceSuccessCommand>(JA, *this, Exec, 5338 CmdArgs, Inputs)); 5339 } else { 5340 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs)); 5341 } 5342 5343 // Make the compile command echo its inputs for /showFilenames. 5344 if (Output.getType() == types::TY_Object && 5345 Args.hasFlag(options::OPT__SLASH_showFilenames, 5346 options::OPT__SLASH_showFilenames_, false)) { 5347 C.getJobs().getJobs().back()->setPrintInputFilenames(true); 5348 } 5349 5350 if (Arg *A = Args.getLastArg(options::OPT_pg)) 5351 if (!shouldUseFramePointer(Args, Triple)) 5352 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer" 5353 << A->getAsString(Args); 5354 5355 // Claim some arguments which clang supports automatically. 5356 5357 // -fpch-preprocess is used with gcc to add a special marker in the output to 5358 // include the PCH file. 5359 Args.ClaimAllArgs(options::OPT_fpch_preprocess); 5360 5361 // Claim some arguments which clang doesn't support, but we don't 5362 // care to warn the user about. 5363 Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group); 5364 Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group); 5365 5366 // Disable warnings for clang -E -emit-llvm foo.c 5367 Args.ClaimAllArgs(options::OPT_emit_llvm); 5368} 5369 5370Clang::Clang(const ToolChain &TC) 5371 // CAUTION! The first constructor argument ("clang") is not arbitrary, 5372 // as it is for other tools. Some operations on a Tool actually test 5373 // whether that tool is Clang based on the Tool's Name as a string. 5374 : Tool("clang", "clang frontend", TC, RF_Full) {} 5375 5376Clang::~Clang() {} 5377 5378/// Add options related to the Objective-C runtime/ABI. 5379/// 5380/// Returns true if the runtime is non-fragile. 5381ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args, 5382 ArgStringList &cmdArgs, 5383 RewriteKind rewriteKind) const { 5384 // Look for the controlling runtime option. 5385 Arg *runtimeArg = 5386 args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime, 5387 options::OPT_fobjc_runtime_EQ); 5388 5389 // Just forward -fobjc-runtime= to the frontend. This supercedes 5390 // options about fragility. 5391 if (runtimeArg && 5392 runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) { 5393 ObjCRuntime runtime; 5394 StringRef value = runtimeArg->getValue(); 5395 if (runtime.tryParse(value)) { 5396 getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime) 5397 << value; 5398 } 5399 if ((runtime.getKind() == ObjCRuntime::GNUstep) && 5400 (runtime.getVersion() >= VersionTuple(2, 0))) 5401 if (!getToolChain().getTriple().isOSBinFormatELF() && 5402 !getToolChain().getTriple().isOSBinFormatCOFF()) { 5403 getToolChain().getDriver().Diag( 5404 diag::err_drv_gnustep_objc_runtime_incompatible_binary) 5405 << runtime.getVersion().getMajor(); 5406 } 5407 5408 runtimeArg->render(args, cmdArgs); 5409 return runtime; 5410 } 5411 5412 // Otherwise, we'll need the ABI "version". Version numbers are 5413 // slightly confusing for historical reasons: 5414 // 1 - Traditional "fragile" ABI 5415 // 2 - Non-fragile ABI, version 1 5416 // 3 - Non-fragile ABI, version 2 5417 unsigned objcABIVersion = 1; 5418 // If -fobjc-abi-version= is present, use that to set the version. 5419 if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) { 5420 StringRef value = abiArg->getValue(); 5421 if (value == "1") 5422 objcABIVersion = 1; 5423 else if (value == "2") 5424 objcABIVersion = 2; 5425 else if (value == "3") 5426 objcABIVersion = 3; 5427 else 5428 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value; 5429 } else { 5430 // Otherwise, determine if we are using the non-fragile ABI. 5431 bool nonFragileABIIsDefault = 5432 (rewriteKind == RK_NonFragile || 5433 (rewriteKind == RK_None && 5434 getToolChain().IsObjCNonFragileABIDefault())); 5435 if (args.hasFlag(options::OPT_fobjc_nonfragile_abi, 5436 options::OPT_fno_objc_nonfragile_abi, 5437 nonFragileABIIsDefault)) { 5438// Determine the non-fragile ABI version to use. 5439#ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO 5440 unsigned nonFragileABIVersion = 1; 5441#else 5442 unsigned nonFragileABIVersion = 2; 5443#endif 5444 5445 if (Arg *abiArg = 5446 args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) { 5447 StringRef value = abiArg->getValue(); 5448 if (value == "1") 5449 nonFragileABIVersion = 1; 5450 else if (value == "2") 5451 nonFragileABIVersion = 2; 5452 else 5453 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) 5454 << value; 5455 } 5456 5457 objcABIVersion = 1 + nonFragileABIVersion; 5458 } else { 5459 objcABIVersion = 1; 5460 } 5461 } 5462 5463 // We don't actually care about the ABI version other than whether 5464 // it's non-fragile. 5465 bool isNonFragile = objcABIVersion != 1; 5466 5467 // If we have no runtime argument, ask the toolchain for its default runtime. 5468 // However, the rewriter only really supports the Mac runtime, so assume that. 5469 ObjCRuntime runtime; 5470 if (!runtimeArg) { 5471 switch (rewriteKind) { 5472 case RK_None: 5473 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile); 5474 break; 5475 case RK_Fragile: 5476 runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple()); 5477 break; 5478 case RK_NonFragile: 5479 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple()); 5480 break; 5481 } 5482 5483 // -fnext-runtime 5484 } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) { 5485 // On Darwin, make this use the default behavior for the toolchain. 5486 if (getToolChain().getTriple().isOSDarwin()) { 5487 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile); 5488 5489 // Otherwise, build for a generic macosx port. 5490 } else { 5491 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple()); 5492 } 5493 5494 // -fgnu-runtime 5495 } else { 5496 assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime)); 5497 // Legacy behaviour is to target the gnustep runtime if we are in 5498 // non-fragile mode or the GCC runtime in fragile mode. 5499 if (isNonFragile) 5500 runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(2, 0)); 5501 else 5502 runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple()); 5503 } 5504 5505 cmdArgs.push_back( 5506 args.MakeArgString("-fobjc-runtime=" + runtime.getAsString())); 5507 return runtime; 5508} 5509 5510static bool maybeConsumeDash(const std::string &EH, size_t &I) { 5511 bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-'); 5512 I += HaveDash; 5513 return !HaveDash; 5514} 5515 5516namespace { 5517struct EHFlags { 5518 bool Synch = false; 5519 bool Asynch = false; 5520 bool NoUnwindC = false; 5521}; 5522} // end anonymous namespace 5523 5524/// /EH controls whether to run destructor cleanups when exceptions are 5525/// thrown. There are three modifiers: 5526/// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions. 5527/// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions. 5528/// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR. 5529/// - c: Assume that extern "C" functions are implicitly nounwind. 5530/// The default is /EHs-c-, meaning cleanups are disabled. 5531static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) { 5532 EHFlags EH; 5533 5534 std::vector<std::string> EHArgs = 5535 Args.getAllArgValues(options::OPT__SLASH_EH); 5536 for (auto EHVal : EHArgs) { 5537 for (size_t I = 0, E = EHVal.size(); I != E; ++I) { 5538 switch (EHVal[I]) { 5539 case 'a': 5540 EH.Asynch = maybeConsumeDash(EHVal, I); 5541 if (EH.Asynch) 5542 EH.Synch = false; 5543 continue; 5544 case 'c': 5545 EH.NoUnwindC = maybeConsumeDash(EHVal, I); 5546 continue; 5547 case 's': 5548 EH.Synch = maybeConsumeDash(EHVal, I); 5549 if (EH.Synch) 5550 EH.Asynch = false; 5551 continue; 5552 default: 5553 break; 5554 } 5555 D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal; 5556 break; 5557 } 5558 } 5559 // The /GX, /GX- flags are only processed if there are not /EH flags. 5560 // The default is that /GX is not specified. 5561 if (EHArgs.empty() && 5562 Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_, 5563 /*default=*/false)) { 5564 EH.Synch = true; 5565 EH.NoUnwindC = true; 5566 } 5567 5568 return EH; 5569} 5570 5571void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType, 5572 ArgStringList &CmdArgs, 5573 codegenoptions::DebugInfoKind *DebugInfoKind, 5574 bool *EmitCodeView) const { 5575 unsigned RTOptionID = options::OPT__SLASH_MT; 5576 5577 if (Args.hasArg(options::OPT__SLASH_LDd)) 5578 // The /LDd option implies /MTd. The dependent lib part can be overridden, 5579 // but defining _DEBUG is sticky. 5580 RTOptionID = options::OPT__SLASH_MTd; 5581 5582 if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group)) 5583 RTOptionID = A->getOption().getID(); 5584 5585 StringRef FlagForCRT; 5586 switch (RTOptionID) { 5587 case options::OPT__SLASH_MD: 5588 if (Args.hasArg(options::OPT__SLASH_LDd)) 5589 CmdArgs.push_back("-D_DEBUG"); 5590 CmdArgs.push_back("-D_MT"); 5591 CmdArgs.push_back("-D_DLL"); 5592 FlagForCRT = "--dependent-lib=msvcrt"; 5593 break; 5594 case options::OPT__SLASH_MDd: 5595 CmdArgs.push_back("-D_DEBUG"); 5596 CmdArgs.push_back("-D_MT"); 5597 CmdArgs.push_back("-D_DLL"); 5598 FlagForCRT = "--dependent-lib=msvcrtd"; 5599 break; 5600 case options::OPT__SLASH_MT: 5601 if (Args.hasArg(options::OPT__SLASH_LDd)) 5602 CmdArgs.push_back("-D_DEBUG"); 5603 CmdArgs.push_back("-D_MT"); 5604 CmdArgs.push_back("-flto-visibility-public-std"); 5605 FlagForCRT = "--dependent-lib=libcmt"; 5606 break; 5607 case options::OPT__SLASH_MTd: 5608 CmdArgs.push_back("-D_DEBUG"); 5609 CmdArgs.push_back("-D_MT"); 5610 CmdArgs.push_back("-flto-visibility-public-std"); 5611 FlagForCRT = "--dependent-lib=libcmtd"; 5612 break; 5613 default: 5614 llvm_unreachable("Unexpected option ID."); 5615 } 5616 5617 if (Args.hasArg(options::OPT__SLASH_Zl)) { 5618 CmdArgs.push_back("-D_VC_NODEFAULTLIB"); 5619 } else { 5620 CmdArgs.push_back(FlagForCRT.data()); 5621 5622 // This provides POSIX compatibility (maps 'open' to '_open'), which most 5623 // users want. The /Za flag to cl.exe turns this off, but it's not 5624 // implemented in clang. 5625 CmdArgs.push_back("--dependent-lib=oldnames"); 5626 } 5627 5628 if (Arg *A = Args.getLastArg(options::OPT_show_includes)) 5629 A->render(Args, CmdArgs); 5630 5631 // This controls whether or not we emit RTTI data for polymorphic types. 5632 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR, 5633 /*default=*/false)) 5634 CmdArgs.push_back("-fno-rtti-data"); 5635 5636 // This controls whether or not we emit stack-protector instrumentation. 5637 // In MSVC, Buffer Security Check (/GS) is on by default. 5638 if (Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_, 5639 /*default=*/true)) { 5640 CmdArgs.push_back("-stack-protector"); 5641 CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong))); 5642 } 5643 5644 // Emit CodeView if -Z7, -Zd, or -gline-tables-only are present. 5645 if (Arg *DebugInfoArg = 5646 Args.getLastArg(options::OPT__SLASH_Z7, options::OPT__SLASH_Zd, 5647 options::OPT_gline_tables_only)) { 5648 *EmitCodeView = true; 5649 if (DebugInfoArg->getOption().matches(options::OPT__SLASH_Z7)) 5650 *DebugInfoKind = codegenoptions::LimitedDebugInfo; 5651 else 5652 *DebugInfoKind = codegenoptions::DebugLineTablesOnly; 5653 } else { 5654 *EmitCodeView = false; 5655 } 5656 5657 const Driver &D = getToolChain().getDriver(); 5658 EHFlags EH = parseClangCLEHFlags(D, Args); 5659 if (EH.Synch || EH.Asynch) { 5660 if (types::isCXX(InputType)) 5661 CmdArgs.push_back("-fcxx-exceptions"); 5662 CmdArgs.push_back("-fexceptions"); 5663 } 5664 if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC) 5665 CmdArgs.push_back("-fexternc-nounwind"); 5666 5667 // /EP should expand to -E -P. 5668 if (Args.hasArg(options::OPT__SLASH_EP)) { 5669 CmdArgs.push_back("-E"); 5670 CmdArgs.push_back("-P"); 5671 } 5672 5673 unsigned VolatileOptionID; 5674 if (getToolChain().getArch() == llvm::Triple::x86_64 || 5675 getToolChain().getArch() == llvm::Triple::x86) 5676 VolatileOptionID = options::OPT__SLASH_volatile_ms; 5677 else 5678 VolatileOptionID = options::OPT__SLASH_volatile_iso; 5679 5680 if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group)) 5681 VolatileOptionID = A->getOption().getID(); 5682 5683 if (VolatileOptionID == options::OPT__SLASH_volatile_ms) 5684 CmdArgs.push_back("-fms-volatile"); 5685 5686 if (Args.hasFlag(options::OPT__SLASH_Zc_dllexportInlines_, 5687 options::OPT__SLASH_Zc_dllexportInlines, 5688 false)) { 5689 if (Args.hasArg(options::OPT__SLASH_fallback)) { 5690 D.Diag(clang::diag::err_drv_dllexport_inlines_and_fallback); 5691 } else { 5692 CmdArgs.push_back("-fno-dllexport-inlines"); 5693 } 5694 } 5695 5696 Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg); 5697 Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb); 5698 if (MostGeneralArg && BestCaseArg) 5699 D.Diag(clang::diag::err_drv_argument_not_allowed_with) 5700 << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args); 5701 5702 if (MostGeneralArg) { 5703 Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms); 5704 Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm); 5705 Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv); 5706 5707 Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg; 5708 Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg; 5709 if (FirstConflict && SecondConflict && FirstConflict != SecondConflict) 5710 D.Diag(clang::diag::err_drv_argument_not_allowed_with) 5711 << FirstConflict->getAsString(Args) 5712 << SecondConflict->getAsString(Args); 5713 5714 if (SingleArg) 5715 CmdArgs.push_back("-fms-memptr-rep=single"); 5716 else if (MultipleArg) 5717 CmdArgs.push_back("-fms-memptr-rep=multiple"); 5718 else 5719 CmdArgs.push_back("-fms-memptr-rep=virtual"); 5720 } 5721 5722 // Parse the default calling convention options. 5723 if (Arg *CCArg = 5724 Args.getLastArg(options::OPT__SLASH_Gd, options::OPT__SLASH_Gr, 5725 options::OPT__SLASH_Gz, options::OPT__SLASH_Gv, 5726 options::OPT__SLASH_Gregcall)) { 5727 unsigned DCCOptId = CCArg->getOption().getID(); 5728 const char *DCCFlag = nullptr; 5729 bool ArchSupported = true; 5730 llvm::Triple::ArchType Arch = getToolChain().getArch(); 5731 switch (DCCOptId) { 5732 case options::OPT__SLASH_Gd: 5733 DCCFlag = "-fdefault-calling-conv=cdecl"; 5734 break; 5735 case options::OPT__SLASH_Gr: 5736 ArchSupported = Arch == llvm::Triple::x86; 5737 DCCFlag = "-fdefault-calling-conv=fastcall"; 5738 break; 5739 case options::OPT__SLASH_Gz: 5740 ArchSupported = Arch == llvm::Triple::x86; 5741 DCCFlag = "-fdefault-calling-conv=stdcall"; 5742 break; 5743 case options::OPT__SLASH_Gv: 5744 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64; 5745 DCCFlag = "-fdefault-calling-conv=vectorcall"; 5746 break; 5747 case options::OPT__SLASH_Gregcall: 5748 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64; 5749 DCCFlag = "-fdefault-calling-conv=regcall"; 5750 break; 5751 } 5752 5753 // MSVC doesn't warn if /Gr or /Gz is used on x64, so we don't either. 5754 if (ArchSupported && DCCFlag) 5755 CmdArgs.push_back(DCCFlag); 5756 } 5757 5758 if (Arg *A = Args.getLastArg(options::OPT_vtordisp_mode_EQ)) 5759 A->render(Args, CmdArgs); 5760 5761 if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) { 5762 CmdArgs.push_back("-fdiagnostics-format"); 5763 if (Args.hasArg(options::OPT__SLASH_fallback)) 5764 CmdArgs.push_back("msvc-fallback"); 5765 else 5766 CmdArgs.push_back("msvc"); 5767 } 5768 5769 if (Arg *A = Args.getLastArg(options::OPT__SLASH_guard)) { 5770 SmallVector<StringRef, 1> SplitArgs; 5771 StringRef(A->getValue()).split(SplitArgs, ","); 5772 bool Instrument = false; 5773 bool NoChecks = false; 5774 for (StringRef Arg : SplitArgs) { 5775 if (Arg.equals_lower("cf")) 5776 Instrument = true; 5777 else if (Arg.equals_lower("cf-")) 5778 Instrument = false; 5779 else if (Arg.equals_lower("nochecks")) 5780 NoChecks = true; 5781 else if (Arg.equals_lower("nochecks-")) 5782 NoChecks = false; 5783 else 5784 D.Diag(diag::err_drv_invalid_value) << A->getSpelling() << Arg; 5785 } 5786 // Currently there's no support emitting CFG instrumentation; the flag only 5787 // emits the table of address-taken functions. 5788 if (Instrument || NoChecks) 5789 CmdArgs.push_back("-cfguard"); 5790 } 5791} 5792 5793visualstudio::Compiler *Clang::getCLFallback() const { 5794 if (!CLFallback) 5795 CLFallback.reset(new visualstudio::Compiler(getToolChain())); 5796 return CLFallback.get(); 5797} 5798 5799 5800const char *Clang::getBaseInputName(const ArgList &Args, 5801 const InputInfo &Input) { 5802 return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput())); 5803} 5804 5805const char *Clang::getBaseInputStem(const ArgList &Args, 5806 const InputInfoList &Inputs) { 5807 const char *Str = getBaseInputName(Args, Inputs[0]); 5808 5809 if (const char *End = strrchr(Str, '.')) 5810 return Args.MakeArgString(std::string(Str, End)); 5811 5812 return Str; 5813} 5814 5815const char *Clang::getDependencyFileName(const ArgList &Args, 5816 const InputInfoList &Inputs) { 5817 // FIXME: Think about this more. 5818 std::string Res; 5819 5820 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) { 5821 std::string Str(OutputOpt->getValue()); 5822 Res = Str.substr(0, Str.rfind('.')); 5823 } else { 5824 Res = getBaseInputStem(Args, Inputs); 5825 } 5826 return Args.MakeArgString(Res + ".d"); 5827} 5828 5829// Begin ClangAs 5830 5831void ClangAs::AddMIPSTargetArgs(const ArgList &Args, 5832 ArgStringList &CmdArgs) const { 5833 StringRef CPUName; 5834 StringRef ABIName; 5835 const llvm::Triple &Triple = getToolChain().getTriple(); 5836 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName); 5837 5838 CmdArgs.push_back("-target-abi"); 5839 CmdArgs.push_back(ABIName.data()); 5840} 5841 5842void ClangAs::AddX86TargetArgs(const ArgList &Args, 5843 ArgStringList &CmdArgs) const { 5844 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) { 5845 StringRef Value = A->getValue(); 5846 if (Value == "intel" || Value == "att") { 5847 CmdArgs.push_back("-mllvm"); 5848 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value)); 5849 } else { 5850 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument) 5851 << A->getOption().getName() << Value; 5852 } 5853 } 5854} 5855 5856void ClangAs::ConstructJob(Compilation &C, const JobAction &JA, 5857 const InputInfo &Output, const InputInfoList &Inputs, 5858 const ArgList &Args, 5859 const char *LinkingOutput) const { 5860 ArgStringList CmdArgs; 5861 5862 assert(Inputs.size() == 1 && "Unexpected number of inputs."); 5863 const InputInfo &Input = Inputs[0]; 5864 5865 const llvm::Triple &Triple = getToolChain().getEffectiveTriple(); 5866 const std::string &TripleStr = Triple.getTriple(); 5867 const auto &D = getToolChain().getDriver(); 5868 5869 // Don't warn about "clang -w -c foo.s" 5870 Args.ClaimAllArgs(options::OPT_w); 5871 // and "clang -emit-llvm -c foo.s" 5872 Args.ClaimAllArgs(options::OPT_emit_llvm); 5873 5874 claimNoWarnArgs(Args); 5875 5876 // Invoke ourselves in -cc1as mode. 5877 // 5878 // FIXME: Implement custom jobs for internal actions. 5879 CmdArgs.push_back("-cc1as"); 5880 5881 // Add the "effective" target triple. 5882 CmdArgs.push_back("-triple"); 5883 CmdArgs.push_back(Args.MakeArgString(TripleStr)); 5884 5885 // Set the output mode, we currently only expect to be used as a real 5886 // assembler. 5887 CmdArgs.push_back("-filetype"); 5888 CmdArgs.push_back("obj"); 5889 5890 // Set the main file name, so that debug info works even with 5891 // -save-temps or preprocessed assembly. 5892 CmdArgs.push_back("-main-file-name"); 5893 CmdArgs.push_back(Clang::getBaseInputName(Args, Input)); 5894 5895 // Add the target cpu 5896 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ true); 5897 if (!CPU.empty()) { 5898 CmdArgs.push_back("-target-cpu"); 5899 CmdArgs.push_back(Args.MakeArgString(CPU)); 5900 } 5901 5902 // Add the target features 5903 getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, true); 5904 5905 // Ignore explicit -force_cpusubtype_ALL option. 5906 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL); 5907 5908 // Pass along any -I options so we get proper .include search paths. 5909 Args.AddAllArgs(CmdArgs, options::OPT_I_Group); 5910 5911 // Determine the original source input. 5912 const Action *SourceAction = &JA; 5913 while (SourceAction->getKind() != Action::InputClass) { 5914 assert(!SourceAction->getInputs().empty() && "unexpected root action!"); 5915 SourceAction = SourceAction->getInputs()[0]; 5916 } 5917 5918 // Forward -g and handle debug info related flags, assuming we are dealing 5919 // with an actual assembly file. 5920 bool WantDebug = false; 5921 unsigned DwarfVersion = 0; 5922 Args.ClaimAllArgs(options::OPT_g_Group); 5923 if (Arg *A = Args.getLastArg(options::OPT_g_Group)) { 5924 WantDebug = !A->getOption().matches(options::OPT_g0) && 5925 !A->getOption().matches(options::OPT_ggdb0); 5926 if (WantDebug) 5927 DwarfVersion = DwarfVersionNum(A->getSpelling()); 5928 } 5929 if (DwarfVersion == 0) 5930 DwarfVersion = getToolChain().GetDefaultDwarfVersion(); 5931 5932 codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo; 5933 5934 if (SourceAction->getType() == types::TY_Asm || 5935 SourceAction->getType() == types::TY_PP_Asm) { 5936 // You might think that it would be ok to set DebugInfoKind outside of 5937 // the guard for source type, however there is a test which asserts 5938 // that some assembler invocation receives no -debug-info-kind, 5939 // and it's not clear whether that test is just overly restrictive. 5940 DebugInfoKind = (WantDebug ? codegenoptions::LimitedDebugInfo 5941 : codegenoptions::NoDebugInfo); 5942 // Add the -fdebug-compilation-dir flag if needed. 5943 addDebugCompDirArg(Args, CmdArgs); 5944 5945 addDebugPrefixMapArg(getToolChain().getDriver(), Args, CmdArgs); 5946 5947 // Set the AT_producer to the clang version when using the integrated 5948 // assembler on assembly source files. 5949 CmdArgs.push_back("-dwarf-debug-producer"); 5950 CmdArgs.push_back(Args.MakeArgString(getClangFullVersion())); 5951 5952 // And pass along -I options 5953 Args.AddAllArgs(CmdArgs, options::OPT_I); 5954 } 5955 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion, 5956 llvm::DebuggerKind::Default); 5957 RenderDebugInfoCompressionArgs(Args, CmdArgs, D, getToolChain()); 5958 5959 5960 // Handle -fPIC et al -- the relocation-model affects the assembler 5961 // for some targets. 5962 llvm::Reloc::Model RelocationModel; 5963 unsigned PICLevel; 5964 bool IsPIE; 5965 std::tie(RelocationModel, PICLevel, IsPIE) = 5966 ParsePICArgs(getToolChain(), Args); 5967 5968 const char *RMName = RelocationModelName(RelocationModel); 5969 if (RMName) { 5970 CmdArgs.push_back("-mrelocation-model"); 5971 CmdArgs.push_back(RMName); 5972 } 5973 5974 // Optionally embed the -cc1as level arguments into the debug info, for build 5975 // analysis. 5976 if (getToolChain().UseDwarfDebugFlags()) { 5977 ArgStringList OriginalArgs; 5978 for (const auto &Arg : Args) 5979 Arg->render(Args, OriginalArgs); 5980 5981 SmallString<256> Flags; 5982 const char *Exec = getToolChain().getDriver().getClangProgramPath(); 5983 Flags += Exec; 5984 for (const char *OriginalArg : OriginalArgs) { 5985 SmallString<128> EscapedArg; 5986 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg); 5987 Flags += " "; 5988 Flags += EscapedArg; 5989 } 5990 CmdArgs.push_back("-dwarf-debug-flags"); 5991 CmdArgs.push_back(Args.MakeArgString(Flags)); 5992 } 5993 5994 // FIXME: Add -static support, once we have it. 5995 5996 // Add target specific flags. 5997 switch (getToolChain().getArch()) { 5998 default: 5999 break; 6000 6001 case llvm::Triple::mips: 6002 case llvm::Triple::mipsel: 6003 case llvm::Triple::mips64: 6004 case llvm::Triple::mips64el: 6005 AddMIPSTargetArgs(Args, CmdArgs); 6006 break; 6007 6008 case llvm::Triple::x86: 6009 case llvm::Triple::x86_64: 6010 AddX86TargetArgs(Args, CmdArgs); 6011 break; 6012 6013 case llvm::Triple::arm: 6014 case llvm::Triple::armeb: 6015 case llvm::Triple::thumb: 6016 case llvm::Triple::thumbeb: 6017 // This isn't in AddARMTargetArgs because we want to do this for assembly 6018 // only, not C/C++. 6019 if (Args.hasFlag(options::OPT_mdefault_build_attributes, 6020 options::OPT_mno_default_build_attributes, true)) { 6021 CmdArgs.push_back("-mllvm"); 6022 CmdArgs.push_back("-arm-add-build-attributes"); 6023 } 6024 break; 6025 } 6026 6027 // Consume all the warning flags. Usually this would be handled more 6028 // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as 6029 // doesn't handle that so rather than warning about unused flags that are 6030 // actually used, we'll lie by omission instead. 6031 // FIXME: Stop lying and consume only the appropriate driver flags 6032 Args.ClaimAllArgs(options::OPT_W_Group); 6033 6034 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, 6035 getToolChain().getDriver()); 6036 6037 Args.AddAllArgs(CmdArgs, options::OPT_mllvm); 6038 6039 assert(Output.isFilename() && "Unexpected lipo output."); 6040 CmdArgs.push_back("-o"); 6041 CmdArgs.push_back(Output.getFilename()); 6042 6043 const llvm::Triple &T = getToolChain().getTriple(); 6044 Arg *A; 6045 if ((getDebugFissionKind(D, Args, A) == DwarfFissionKind::Split) && 6046 (T.isOSLinux() || T.isOSFuchsia())) { 6047 CmdArgs.push_back("-split-dwarf-file"); 6048 CmdArgs.push_back(SplitDebugName(Args, Output)); 6049 } 6050 6051 assert(Input.isFilename() && "Invalid input."); 6052 CmdArgs.push_back(Input.getFilename()); 6053 6054 const char *Exec = getToolChain().getDriver().getClangProgramPath(); 6055 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs)); 6056} 6057 6058// Begin OffloadBundler 6059 6060void OffloadBundler::ConstructJob(Compilation &C, const JobAction &JA, 6061 const InputInfo &Output, 6062 const InputInfoList &Inputs, 6063 const llvm::opt::ArgList &TCArgs, 6064 const char *LinkingOutput) const { 6065 // The version with only one output is expected to refer to a bundling job. 6066 assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!"); 6067 6068 // The bundling command looks like this: 6069 // clang-offload-bundler -type=bc 6070 // -targets=host-triple,openmp-triple1,openmp-triple2 6071 // -outputs=input_file 6072 // -inputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2" 6073 6074 ArgStringList CmdArgs; 6075 6076 // Get the type. 6077 CmdArgs.push_back(TCArgs.MakeArgString( 6078 Twine("-type=") + types::getTypeTempSuffix(Output.getType()))); 6079 6080 assert(JA.getInputs().size() == Inputs.size() && 6081 "Not have inputs for all dependence actions??"); 6082 6083 // Get the targets. 6084 SmallString<128> Triples; 6085 Triples += "-targets="; 6086 for (unsigned I = 0; I < Inputs.size(); ++I) { 6087 if (I) 6088 Triples += ','; 6089 6090 // Find ToolChain for this input. 6091 Action::OffloadKind CurKind = Action::OFK_Host; 6092 const ToolChain *CurTC = &getToolChain(); 6093 const Action *CurDep = JA.getInputs()[I]; 6094 6095 if (const auto *OA = dyn_cast<OffloadAction>(CurDep)) { 6096 CurTC = nullptr; 6097 OA->doOnEachDependence([&](Action *A, const ToolChain *TC, const char *) { 6098 assert(CurTC == nullptr && "Expected one dependence!"); 6099 CurKind = A->getOffloadingDeviceKind(); 6100 CurTC = TC; 6101 }); 6102 } 6103 Triples += Action::GetOffloadKindName(CurKind); 6104 Triples += '-'; 6105 Triples += CurTC->getTriple().normalize(); 6106 if (CurKind == Action::OFK_HIP && CurDep->getOffloadingArch()) { 6107 Triples += '-'; 6108 Triples += CurDep->getOffloadingArch(); 6109 } 6110 } 6111 CmdArgs.push_back(TCArgs.MakeArgString(Triples)); 6112 6113 // Get bundled file command. 6114 CmdArgs.push_back( 6115 TCArgs.MakeArgString(Twine("-outputs=") + Output.getFilename())); 6116 6117 // Get unbundled files command. 6118 SmallString<128> UB; 6119 UB += "-inputs="; 6120 for (unsigned I = 0; I < Inputs.size(); ++I) { 6121 if (I) 6122 UB += ','; 6123 6124 // Find ToolChain for this input. 6125 const ToolChain *CurTC = &getToolChain(); 6126 if (const auto *OA = dyn_cast<OffloadAction>(JA.getInputs()[I])) { 6127 CurTC = nullptr; 6128 OA->doOnEachDependence([&](Action *, const ToolChain *TC, const char *) { 6129 assert(CurTC == nullptr && "Expected one dependence!"); 6130 CurTC = TC; 6131 }); 6132 } 6133 UB += CurTC->getInputFilename(Inputs[I]); 6134 } 6135 CmdArgs.push_back(TCArgs.MakeArgString(UB)); 6136 6137 // All the inputs are encoded as commands. 6138 C.addCommand(llvm::make_unique<Command>( 6139 JA, *this, 6140 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())), 6141 CmdArgs, None)); 6142} 6143 6144void OffloadBundler::ConstructJobMultipleOutputs( 6145 Compilation &C, const JobAction &JA, const InputInfoList &Outputs, 6146 const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, 6147 const char *LinkingOutput) const { 6148 // The version with multiple outputs is expected to refer to a unbundling job. 6149 auto &UA = cast<OffloadUnbundlingJobAction>(JA); 6150 6151 // The unbundling command looks like this: 6152 // clang-offload-bundler -type=bc 6153 // -targets=host-triple,openmp-triple1,openmp-triple2 6154 // -inputs=input_file 6155 // -outputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2" 6156 // -unbundle 6157 6158 ArgStringList CmdArgs; 6159 6160 assert(Inputs.size() == 1 && "Expecting to unbundle a single file!"); 6161 InputInfo Input = Inputs.front(); 6162 6163 // Get the type. 6164 CmdArgs.push_back(TCArgs.MakeArgString( 6165 Twine("-type=") + types::getTypeTempSuffix(Input.getType()))); 6166 6167 // Get the targets. 6168 SmallString<128> Triples; 6169 Triples += "-targets="; 6170 auto DepInfo = UA.getDependentActionsInfo(); 6171 for (unsigned I = 0; I < DepInfo.size(); ++I) { 6172 if (I) 6173 Triples += ','; 6174 6175 auto &Dep = DepInfo[I]; 6176 Triples += Action::GetOffloadKindName(Dep.DependentOffloadKind); 6177 Triples += '-'; 6178 Triples += Dep.DependentToolChain->getTriple().normalize(); 6179 if (Dep.DependentOffloadKind == Action::OFK_HIP && 6180 !Dep.DependentBoundArch.empty()) { 6181 Triples += '-'; 6182 Triples += Dep.DependentBoundArch; 6183 } 6184 } 6185 6186 CmdArgs.push_back(TCArgs.MakeArgString(Triples)); 6187 6188 // Get bundled file command. 6189 CmdArgs.push_back( 6190 TCArgs.MakeArgString(Twine("-inputs=") + Input.getFilename())); 6191 6192 // Get unbundled files command. 6193 SmallString<128> UB; 6194 UB += "-outputs="; 6195 for (unsigned I = 0; I < Outputs.size(); ++I) { 6196 if (I) 6197 UB += ','; 6198 UB += DepInfo[I].DependentToolChain->getInputFilename(Outputs[I]); 6199 } 6200 CmdArgs.push_back(TCArgs.MakeArgString(UB)); 6201 CmdArgs.push_back("-unbundle"); 6202 6203 // All the inputs are encoded as commands. 6204 C.addCommand(llvm::make_unique<Command>( 6205 JA, *this, 6206 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())), 6207 CmdArgs, None)); 6208} 6209