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