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