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