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